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 Main where
import qualified Sonos.Main as M
main :: IO ()
main = M.main
| merc1031/haskell-sonos-http-api | app/Main.hs | Haskell | bsd-3-clause | 81 |
module ErrorMessagesSpec where
import TestImport
import Data.List
import qualified Data.Map as M
import qualified Parser
import Codegen
import Err
import Text.RawString.QQ (r)
spec :: Spec
spec = describe "generateDedan" $ context "should show context in errors" $ do
it "in servers" $ do
testErrorMessageContains [r|
server buf {
var count : 1..N;
}
|] ["server buf", "var count", "N"]
testErrorMessageContains [r|
server buf {
var count : (0..1)[:banana];
}
|] ["server buf", "var count", "banana not in type Int"]
testErrorMessageContains [r|
server sem {
{ v | value = :up } -> { ok }
}
|] ["server sem", "action v", "predicate", "value"]
testErrorMessageContains [r|
server sem {
var value : {up, down};
{ v | value = foo } -> { ok }
}
|] ["server sem", "action v", "predicate", "state { value = :up }", "foo"]
testErrorMessageContains [r|
server sem {
var value : {up, down};
{ v } -> { value = 7 }
}
|] ["server sem", "action v",
"updates",
"state { value = :up }",
"assignment of variable \"value\"",
"value 7 not in type {up, down}"]
testErrorMessageContains [r|
server sem {
var value : {up, down};
{ v } -> { bleh = 7 }
}
|] ["server sem",
"action v",
"updates",
"state { value = :up }",
"Undefined symbol \"bleh\""]
it "in initializers" $ do
testErrorMessageContains [r|
server sem { var state : {up, down} }
var mutex = sem() { state = bleh };
|] ["initializer of server instance \"mutex\"",
"Undefined symbol \"bleh\""]
it "in processes" $ do
testErrorMessageContains [r|
process foo() { loop skip; }
|] ["process \"foo\"",
"Cycle detected in CFG"]
testErrorMessageContains :: String -> [String] -> Assertion
testErrorMessageContains source chunks =
let model = unsafeParse Parser.model source
in case generateDedan model of
Right _ -> error $ "Expected error message with " ++ show chunks ++ ", got success!"
Left err ->
let msg = ppError err
in forM_ chunks $ \chunk ->
unless (chunk `isInfixOf` msg) $
error $ "Error message:\n" ++ msg ++ "\ndoes not contain " ++ show chunk
| zyla/rybu | test/ErrorMessagesSpec.hs | Haskell | bsd-3-clause | 2,683 |
module Even where
{-@ type Even = {v:Int | v mod 2 = 0} @-}
{-@ notEven :: Int -> Even @-}
notEven :: Int -> Int
notEven x = x * 2
| ssaavedra/liquidhaskell | tests/pos/Even.hs | Haskell | bsd-3-clause | 134 |
--
-- Copyright (C) 2012 Parallel Scientific. All rights reserved.
--
-- See the accompanying LICENSE file for license information.
--
import Control.Exception ( finally )
import Control.Monad ( forever, void )
import qualified Data.ByteString.Char8 as B ( putStrLn, pack )
import Network.CCI ( withCCI, withPollingEndpoint, getEndpt_URI, accept
, pollWithEventData, EventData(..), disconnect, send
, unsafePackEventBytes
)
main :: IO ()
main =
withCCI$
withPollingEndpoint Nothing$ \ep -> do
getEndpt_URI ep >>= putStrLn
_ <- forever$ pollWithEventData ep$ \evd ->
case evd of
EvConnectRequest ev _bs _cattr -> void$ accept ev 0
EvRecv ebs conn -> flip finally (disconnect conn)$
do unsafePackEventBytes ebs >>= B.putStrLn
send conn (B.pack "pong!") 1
_ -> print evd
return ()
| tkonolige/haskell-cci | examples/Server.hs | Haskell | bsd-3-clause | 976 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeApplications #-}
module Main where
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import Data.Proxy (Proxy(Proxy))
import Data.Ratio ((%), numerator, denominator)
import qualified Data.Serialize as Cereal
import Data.Word (Word8)
import GHC.Exts (fromList)
import GHC.TypeLits (Nat, Symbol, KnownSymbol, symbolVal)
import qualified Money
import qualified Test.Tasty as Tasty
import Test.Tasty.HUnit ((@?=), (@=?))
import qualified Test.Tasty.HUnit as HU
import qualified Test.Tasty.Runners as Tasty
import Test.Tasty.QuickCheck ((===), (==>), (.&&.))
import qualified Test.Tasty.QuickCheck as QC
import Money.Cereal ()
--------------------------------------------------------------------------------
main :: IO ()
main = Tasty.defaultMainWithIngredients
[ Tasty.consoleTestReporter
, Tasty.listingTests
] (Tasty.localOption (QC.QuickCheckTests 100) tests)
tests :: Tasty.TestTree
tests =
Tasty.testGroup "root"
[ testCurrencies
, testCurrencyUnits
, testExchange
, testRawSerializations
]
testCurrencies :: Tasty.TestTree
testCurrencies =
Tasty.testGroup "Currency"
[ testDense (Proxy :: Proxy "BTC") -- A cryptocurrency.
, testDense (Proxy :: Proxy "USD") -- A fiat currency with decimal fractions.
, testDense (Proxy :: Proxy "VUV") -- A fiat currency with non-decimal fractions.
, testDense (Proxy :: Proxy "XAU") -- A precious metal.
]
testCurrencyUnits :: Tasty.TestTree
testCurrencyUnits =
Tasty.testGroup "Currency units"
[ testDiscrete (Proxy :: Proxy "BTC") (Proxy :: Proxy "satoshi")
, testDiscrete (Proxy :: Proxy "BTC") (Proxy :: Proxy "bitcoin")
, testDiscrete (Proxy :: Proxy "USD") (Proxy :: Proxy "cent")
, testDiscrete (Proxy :: Proxy "USD") (Proxy :: Proxy "dollar")
, testDiscrete (Proxy :: Proxy "VUV") (Proxy :: Proxy "vatu")
, testDiscrete (Proxy :: Proxy "XAU") (Proxy :: Proxy "gram")
, testDiscrete (Proxy :: Proxy "XAU") (Proxy :: Proxy "grain")
]
testDense
:: forall currency
. KnownSymbol currency
=> Proxy currency
-> Tasty.TestTree
testDense pc =
Tasty.testGroup ("Dense " ++ show (symbolVal pc))
[ QC.testProperty "Cereal encoding roundtrip" $
QC.forAll QC.arbitrary $ \(x :: Money.Dense currency) ->
Right x === Cereal.decode (Cereal.encode x)
, QC.testProperty "Cereal encoding roundtrip (SomeDense)" $
QC.forAll QC.arbitrary $ \(x :: Money.Dense currency) ->
let x' = Money.toSomeDense x
in Right x' === Cereal.decode (Cereal.encode x')
, QC.testProperty "Cereal encoding roundtrip (Dense through SomeDense)" $
QC.forAll QC.arbitrary $ \(x :: Money.Dense currency) ->
Right x === Cereal.decode (Cereal.encode (Money.toSomeDense x))
, QC.testProperty "Cereal encoding roundtrip (SomeDense through Dense)" $
QC.forAll QC.arbitrary $ \(x :: Money.Dense currency) ->
Right (Money.toSomeDense x) === Cereal.decode (Cereal.encode x)
]
testExchange :: Tasty.TestTree
testExchange =
Tasty.testGroup "Exchange"
[ testExchangeRate (Proxy :: Proxy "BTC") (Proxy :: Proxy "BTC")
, testExchangeRate (Proxy :: Proxy "BTC") (Proxy :: Proxy "USD")
, testExchangeRate (Proxy :: Proxy "BTC") (Proxy :: Proxy "VUV")
, testExchangeRate (Proxy :: Proxy "BTC") (Proxy :: Proxy "XAU")
, testExchangeRate (Proxy :: Proxy "USD") (Proxy :: Proxy "BTC")
, testExchangeRate (Proxy :: Proxy "USD") (Proxy :: Proxy "USD")
, testExchangeRate (Proxy :: Proxy "USD") (Proxy :: Proxy "VUV")
, testExchangeRate (Proxy :: Proxy "USD") (Proxy :: Proxy "XAU")
, testExchangeRate (Proxy :: Proxy "VUV") (Proxy :: Proxy "BTC")
, testExchangeRate (Proxy :: Proxy "VUV") (Proxy :: Proxy "USD")
, testExchangeRate (Proxy :: Proxy "VUV") (Proxy :: Proxy "VUV")
, testExchangeRate (Proxy :: Proxy "VUV") (Proxy :: Proxy "XAU")
, testExchangeRate (Proxy :: Proxy "XAU") (Proxy :: Proxy "BTC")
, testExchangeRate (Proxy :: Proxy "XAU") (Proxy :: Proxy "USD")
, testExchangeRate (Proxy :: Proxy "XAU") (Proxy :: Proxy "VUV")
, testExchangeRate (Proxy :: Proxy "XAU") (Proxy :: Proxy "XAU")
]
testDiscrete
:: forall (currency :: Symbol) (unit :: Symbol)
. ( Money.GoodScale (Money.UnitScale currency unit)
, KnownSymbol currency
, KnownSymbol unit )
=> Proxy currency
-> Proxy unit
-> Tasty.TestTree
testDiscrete pc pu =
Tasty.testGroup ("Discrete " ++ show (symbolVal pc) ++ " "
++ show (symbolVal pu))
[ QC.testProperty "Cereal encoding roundtrip" $
QC.forAll QC.arbitrary $ \(x :: Money.Discrete currency unit) ->
Right x === Cereal.decode (Cereal.encode x)
, QC.testProperty "Cereal encoding roundtrip (SomeDiscrete)" $
QC.forAll QC.arbitrary $ \(x :: Money.Discrete currency unit) ->
let x' = Money.toSomeDiscrete x
in Right x' === Cereal.decode (Cereal.encode x')
, QC.testProperty "Cereal encoding roundtrip (Discrete through SomeDiscrete)" $
QC.forAll QC.arbitrary $ \(x :: Money.Discrete currency unit) ->
Right x === Cereal.decode (Cereal.encode (Money.toSomeDiscrete x))
, QC.testProperty "Cereal encoding roundtrip (SomeDiscrete through Discrete)" $
QC.forAll QC.arbitrary $ \(x :: Money.Discrete currency unit) ->
Right (Money.toSomeDiscrete x) === Cereal.decode (Cereal.encode x)
]
testExchangeRate
:: forall (src :: Symbol) (dst :: Symbol)
. (KnownSymbol src, KnownSymbol dst)
=> Proxy src
-> Proxy dst
-> Tasty.TestTree
testExchangeRate ps pd =
Tasty.testGroup ("ExchangeRate " ++ show (symbolVal ps) ++ " "
++ show (symbolVal pd))
[ QC.testProperty "Cereal encoding roundtrip" $
QC.forAll QC.arbitrary $ \(x :: Money.ExchangeRate src dst) ->
Right x === Cereal.decode (Cereal.encode x)
, QC.testProperty "Cereal encoding roundtrip (SomeExchangeRate)" $
QC.forAll QC.arbitrary $ \(x :: Money.ExchangeRate src dst) ->
let x' = Money.toSomeExchangeRate x
in Right x' === Cereal.decode (Cereal.encode x')
, QC.testProperty "Cereal encoding roundtrip (ExchangeRate through SomeExchangeRate)" $
QC.forAll QC.arbitrary $ \(x :: Money.ExchangeRate src dst) ->
Right x === Cereal.decode (Cereal.encode (Money.toSomeExchangeRate x))
, QC.testProperty "Cereal encoding roundtrip (SomeExchangeRate through ExchangeRate)" $
QC.forAll QC.arbitrary $ \(x :: Money.ExchangeRate src dst) ->
Right (Money.toSomeExchangeRate x) === Cereal.decode (Cereal.encode x)
]
--------------------------------------------------------------------------------
-- Raw parsing "golden tests"
testRawSerializations :: Tasty.TestTree
testRawSerializations =
Tasty.testGroup "Raw serializations"
[ Tasty.testGroup "cereal"
[ Tasty.testGroup "decode"
[ HU.testCase "Dense" $ do
Right rawDns0 @=? Cereal.decode rawDns0_cereal
, HU.testCase "Discrete" $ do
Right rawDis0 @=? Cereal.decode rawDis0_cereal
, HU.testCase "ExchangeRate" $ do
Right rawXr0 @=? Cereal.decode rawXr0_cereal
]
, Tasty.testGroup "encode"
[ HU.testCase "Dense" $ rawDns0_cereal @=? Cereal.encode rawDns0
, HU.testCase "Discrete" $ rawDis0_cereal @=? Cereal.encode rawDis0
, HU.testCase "ExchangeRate" $ rawXr0_cereal @=? Cereal.encode rawXr0
]
]
]
rawDns0 :: Money.Dense "USD"
rawDns0 = Money.dense' (26%1)
rawDis0 :: Money.Discrete "USD" "cent"
rawDis0 = Money.discrete 4
rawXr0 :: Money.ExchangeRate "USD" "BTC"
Just rawXr0 = Money.exchangeRate (3%2)
-- Such a waste of space these many bytes! Can we shrink this and maintain
-- backwards compatibility?
rawDns0_cereal :: B.ByteString
rawDns0_cereal = "\NUL\NUL\NUL\NUL\NUL\NUL\NUL\ETXUSD\NUL\NUL\NUL\NUL\SUB\NUL\NUL\NUL\NUL\SOH"
rawDis0_cereal :: B.ByteString
rawDis0_cereal = "\NUL\NUL\NUL\NUL\NUL\NUL\NUL\ETXUSD\NUL\NUL\NUL\NULd\NUL\NUL\NUL\NUL\SOH\NUL\NUL\NUL\NUL\EOT"
rawXr0_cereal :: B.ByteString
rawXr0_cereal = "\NUL\NUL\NUL\NUL\NUL\NUL\NUL\ETXUSD\NUL\NUL\NUL\NUL\NUL\NUL\NUL\ETXBTC\NUL\NUL\NUL\NUL\ETX\NUL\NUL\NUL\NUL\STX"
| k0001/haskell-money | safe-money-cereal/test/Main.hs | Haskell | bsd-3-clause | 8,375 |
-- | This module provides support for parsing values from ByteString
-- 'InputStream's using @attoparsec@. /Since: 1.4.0.0./
module System.IO.Streams.Attoparsec.ByteString
( -- * Parsing
parseFromStream
, parserToInputStream
, ParseException(..)
) where
------------------------------------------------------------------------------
import Data.Attoparsec.ByteString.Char8 (Parser)
import Data.ByteString (ByteString)
------------------------------------------------------------------------------
import System.IO.Streams.Internal (InputStream)
import qualified System.IO.Streams.Internal as Streams
import System.IO.Streams.Internal.Attoparsec (ParseData (..), ParseException (..), parseFromStreamInternal)
------------------------------------------------------------------------------
-- | Supplies an @attoparsec@ 'Parser' with an 'InputStream', returning the
-- final parsed value or throwing a 'ParseException' if parsing fails.
--
-- 'parseFromStream' consumes only as much input as necessary to satisfy the
-- 'Parser': any unconsumed input is pushed back onto the 'InputStream'.
--
-- If the 'Parser' exhausts the 'InputStream', the end-of-stream signal is sent
-- to attoparsec.
--
-- Example:
--
-- @
-- ghci> import "Data.Attoparsec.ByteString.Char8"
-- ghci> is <- 'System.IO.Streams.fromList' [\"12345xxx\" :: 'ByteString']
-- ghci> 'parseFromStream' ('Data.Attoparsec.ByteString.Char8.takeWhile' 'Data.Attoparsec.ByteString.Char8.isDigit') is
-- \"12345\"
-- ghci> 'System.IO.Streams.read' is
-- Just \"xxx\"
-- @
parseFromStream :: Parser r
-> InputStream ByteString
-> IO r
parseFromStream = parseFromStreamInternal parse feed
------------------------------------------------------------------------------
-- | Given a 'Parser' yielding values of type @'Maybe' r@, transforms an
-- 'InputStream' over byte strings to an 'InputStream' yielding values of type
-- @r@.
--
-- If the parser yields @Just x@, then @x@ will be passed along downstream, and
-- if the parser yields @Nothing@, that will be interpreted as end-of-stream.
--
-- Upon a parse error, 'parserToInputStream' will throw a 'ParseException'.
--
-- Example:
--
-- @
-- ghci> import "Control.Applicative"
-- ghci> import "Data.Attoparsec.ByteString.Char8"
-- ghci> is <- 'System.IO.Streams.fromList' [\"1 2 3 4 5\" :: 'ByteString']
-- ghci> let parser = ('Data.Attoparsec.ByteString.Char8.endOfInput' >> 'Control.Applicative.pure' 'Nothing') \<|\> (Just \<$\> ('Data.Attoparsec.ByteString.Char8.skipWhile' 'Data.Attoparsec.ByteString.Char8.isSpace' *> 'Data.Attoparsec.ByteString.Char8.decimal'))
-- ghci> 'parserToInputStream' parser is >>= 'System.IO.Streams.toList'
-- [1,2,3,4,5]
-- ghci> is' \<- 'System.IO.Streams.fromList' [\"1 2xx3 4 5\" :: 'ByteString'] >>= 'parserToInputStream' parser
-- ghci> 'read' is'
-- Just 1
-- ghci> 'read' is'
-- Just 2
-- ghci> 'read' is'
-- *** Exception: Parse exception: Failed reading: takeWhile1
-- @
parserToInputStream :: Parser (Maybe r)
-> InputStream ByteString
-> IO (InputStream r)
parserToInputStream = (Streams.makeInputStream .) . parseFromStream
{-# INLINE parserToInputStream #-}
| LukeHoersten/io-streams | src/System/IO/Streams/Attoparsec/ByteString.hs | Haskell | bsd-3-clause | 3,289 |
-- Utility for sending a command to xmonad and have
-- it immediately executed even when xmonad isn't built
-- with -threaded.
module Main () where
import Control.Concurrent
import Control.Monad
import Data.List
import Data.Monoid
import Data.Word
import Graphics.X11.Xlib
import Graphics.X11.Xlib.Event
import Graphics.X11.Xlib.Extras
import Network
import System.Console.GetOpt
import System.Environment
import System.IO
data Options = Options { optPort :: PortID
, optHost :: HostName
, optWait :: Bool
, optHelp :: Bool
}
defaultOptions :: Options
defaultOptions = Options { optPort = PortNumber 4242
, optHost = "localhost"
, optWait = False
, optHelp = False
}
readPort :: String -> Options -> Options
readPort str opts = opts { optPort = portNum }
where portNum = PortNumber . fromIntegral $ (read str :: Word16)
options :: [OptDescr (Endo Options)]
options = [ Option ['p'] ["port"]
(ReqArg (Endo . readPort) "<port>")
("Port on which to connect. <port> is expected to be an integer"
++ " between 0 and 65535. (Defaults to 4242)")
, Option ['h'] ["host"]
(ReqArg (\s -> Endo $ \opts -> opts { optHost = s }) "<hostname>")
"Which host to connect to. (Defaults to \"localhost\")"
, Option ['w'] ["wait"]
(NoArg . Endo $ \opts -> opts { optWait = True })
"Wait until the command is executed and print the result. (Default: False)"
, Option [] ["help"]
(NoArg . Endo $ \opts -> opts { optHelp = True })
"Show usage information."
]
getOptions :: [String] -> IO (Options,String)
getOptions args =
case getOpt Permute options args of
(o,rest,[]) -> return (mconcat o `appEndo` defaultOptions, intercalate " " rest)
(_,_,errs) -> ioError . userError $ concat errs ++ usageInfo header options
header :: String
header = "USAGE: xmonadcmd [OPTIONS] <string to send>"
sendCommand :: Options -> String -> IO ()
sendCommand opts cmd = openDisplay "" >>= \dpy -> do
putStrLn cmd
h <- connectTo (optHost opts) (optPort opts)
hSetBuffering h LineBuffering
hPutStrLn h cmd
rootw <- rootWindow dpy $ defaultScreen dpy
atom <- internAtom dpy "TEST" True
forkIO $ allocaXEvent $ \e -> do
setEventType e clientMessage
setClientMessageEvent e rootw atom 32 0 currentTime
sendEvent dpy rootw False structureNotifyMask e
sync dpy False
when (optWait opts) $ putStrLn =<< hGetLine h
hClose h
main :: IO ()
main = do
(opts,cmd) <- getOptions =<< getArgs
if optHelp opts
then putStrLn $ usageInfo header options
else sendCommand opts cmd | LeifW/xmonad-extras | XMonadCmd.hs | Haskell | bsd-3-clause | 2,902 |
{-# LANGUAGE NoImplicitPrelude, CPP #-}
{-| Export Prelude as in base 4.8.0
-}
{-
Copyright (C) 2015 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.Prelude (
-- * Standard types, classes and related functions
-- ** Basic data types
Bool(False, True),
(&&), (||), not, otherwise,
Maybe(Nothing, Just),
maybe,
Either(Left, Right),
either,
Ordering(LT, EQ, GT),
Char, String,
-- *** Tuples
fst, snd, curry, uncurry,
-- ** Basic type classes
Eq((==), (/=)),
Ord(compare, (<), (<=), (>=), (>), max, min),
Enum(succ, pred, toEnum, fromEnum, enumFrom, enumFromThen,
enumFromTo, enumFromThenTo),
Bounded(minBound, maxBound),
-- ** Numbers
-- *** Numeric types
Int, Integer, Float, Double,
Rational, Word,
-- *** Numeric type classes
Num((+), (-), (*), negate, abs, signum, fromInteger),
Real(toRational),
Integral(quot, rem, div, mod, quotRem, divMod, toInteger),
Fractional((/), recip, fromRational),
Floating(pi, exp, log, sqrt, (**), logBase, sin, cos, tan,
asin, acos, atan, sinh, cosh, tanh, asinh, acosh, atanh),
RealFrac(properFraction, truncate, round, ceiling, floor),
RealFloat(floatRadix, floatDigits, floatRange, decodeFloat,
encodeFloat, exponent, significand, scaleFloat, isNaN,
isInfinite, isDenormalized, isIEEE, isNegativeZero, atan2),
-- *** Numeric functions
subtract, even, odd, gcd, lcm, (^), (^^),
fromIntegral, realToFrac,
-- ** Monoids
Monoid(mempty, mappend, mconcat),
-- ** Monads and functors
Functor(fmap, (<$)), (<$>),
Applicative(pure, (<*>), (*>), (<*)),
Monad((>>=), (>>), return, fail),
mapM_, sequence_, (=<<),
#if MIN_VERSION_base(4,8,0)
-- ** Folds and traversals
Foldable(elem, -- :: (Foldable t, Eq a) => a -> t a -> Bool
-- fold, -- :: Monoid m => t m -> m
foldMap, -- :: Monoid m => (a -> m) -> t a -> m
foldr, -- :: (a -> b -> b) -> b -> t a -> b
-- foldr', -- :: (a -> b -> b) -> b -> t a -> b
foldl, -- :: (b -> a -> b) -> b -> t a -> b
-- foldl', -- :: (b -> a -> b) -> b -> t a -> b
foldr1, -- :: (a -> a -> a) -> t a -> a
foldl1, -- :: (a -> a -> a) -> t a -> a
maximum, -- :: (Foldable t, Ord a) => t a -> a
minimum, -- :: (Foldable t, Ord a) => t a -> a
product, -- :: (Foldable t, Num a) => t a -> a
sum), -- :: Num a => t a -> a
-- toList) -- :: Foldable t => t a -> [a]
#else
Foldable(foldMap,
foldr,
foldl,
foldr1,
foldl1),
elem,
maximum,
minimum,
product,
sum,
#endif
Traversable(traverse, sequenceA, mapM, sequence),
-- ** Miscellaneous functions
id, const, (.), flip, ($), until,
asTypeOf, error, undefined,
seq, ($!),
-- * List operations
map, (++), filter,
head, last, tail, init, null, length, (!!),
reverse,
-- *** Special folds
and, or, any, all,
concat, concatMap,
-- ** Building lists
-- *** Scans
scanl, scanl1, scanr, scanr1,
-- *** Infinite lists
iterate, repeat, replicate, cycle,
-- ** Sublists
take, drop, splitAt, takeWhile, dropWhile, span, break,
-- ** Searching lists
notElem, lookup,
-- ** Zipping and unzipping lists
zip, zip3, zipWith, zipWith3, unzip, unzip3,
-- ** Functions on strings
lines, words, unlines, unwords,
-- * Converting to and from @String@
-- ** Converting to @String@
ShowS,
Show(showsPrec, showList, show),
shows,
showChar, showString, showParen,
-- ** Converting from @String@
ReadS,
Read(readsPrec, readList),
reads, readParen, read, lex,
-- * Basic Input and output
IO,
-- ** Simple I\/O operations
-- All I/O functions defined here are character oriented. The
-- treatment of the newline character will vary on different systems.
-- For example, two characters of input, return and linefeed, may
-- read as a single newline character. These functions cannot be
-- used portably for binary I/O.
-- *** Output functions
putChar,
putStr, putStrLn, print,
-- *** Input functions
getChar,
getLine, getContents, interact,
-- *** Files
FilePath,
readFile, writeFile, appendFile, readIO, readLn,
-- ** Exception handling in the I\/O monad
IOError, ioError, userError,
) where
#if MIN_VERSION_base(4,8,0)
import Prelude
#else
import Prelude hiding ( elem, maximum, minimum, product, sum )
import Data.Foldable ( Foldable(..), elem, maximum, minimum, product, sum )
import Data.Traversable ( Traversable(..) )
import Control.Applicative
import Data.Monoid
import Data.Word
#endif
| leshchevds/ganeti | src/Ganeti/Prelude.hs | Haskell | bsd-2-clause | 6,145 |
module Github.Teams (
teamInfoFor
,teamInfoFor'
,teamsInfo'
,createTeamFor'
,editTeam'
,deleteTeam'
,listTeamsCurrent'
,module Github.Data
) where
import Github.Data
import Github.Private
-- | The information for a single team, by team id.
-- | With authentication
--
-- > teamInfoFor' (Just $ GithubOAuth "token") 1010101
teamInfoFor' :: Maybe GithubAuth -> Int -> IO (Either Error DetailedTeam)
teamInfoFor' auth team_id = githubGet' auth ["teams", show team_id]
-- | The information for a single team, by team id.
--
-- > teamInfoFor' (Just $ GithubOAuth "token") 1010101
teamInfoFor :: Int -> IO (Either Error DetailedTeam)
teamInfoFor = teamInfoFor' Nothing
-- | Lists all teams, across all organizations, that the current user belongs to.
--
-- > teamsInfo' (Just $ GithubOAuth "token")
teamsInfo' :: Maybe GithubAuth -> IO (Either Error [DetailedTeam])
teamsInfo' auth = githubGet' auth ["user", "teams"]
-- | Create a team under an organization
--
-- > createTeamFor' (GithubOAuth "token") "organization" (CreateTeam "newteamname" "some description" [] PermssionPull)
createTeamFor' :: GithubAuth
-> String
-> CreateTeam
-> IO (Either Error DetailedTeam)
createTeamFor' auth organization create_team =
githubPost auth ["orgs", organization, "teams"] create_team
-- | Edit a team, by id.
--
-- > editTeamFor'
editTeam' :: GithubAuth
-> Int
-> EditTeam
-> IO (Either Error DetailedTeam)
editTeam' auth team_id edit_team =
githubPatch auth ["teams", show team_id] edit_team
-- | Delete a team, by id.
--
-- > deleteTeam' (GithubOAuth "token") 1010101
deleteTeam' :: GithubAuth -> Int -> IO (Either Error ())
deleteTeam' auth team_id = githubDelete auth ["teams", show team_id]
-- | List teams for current authenticated user
--
-- > listTeamsCurrent' (GithubOAuth "token")
listTeamsCurrent' :: GithubAuth -> IO (Either Error [DetailedTeam])
listTeamsCurrent' auth = githubGet' (Just auth) ["user", "teams"]
| beni55/github | Github/Teams.hs | Haskell | bsd-3-clause | 1,999 |
{-# LANGUAGE FlexibleInstances #-}
module MockedProcess where
import MockedEnv
import Control.Monad.IO.Class
import Control.Monad.Trans.Reader
import Tinc.Process
type ReadProcess = FilePath -> [String] -> String -> IO String
type CallProcess = FilePath -> [String] -> IO ()
data Env = Env {
envReadProcess :: ReadProcess
, envCallProcess :: CallProcess
}
env :: Env
env = Env readProcessM callProcessM
instance MonadProcess (WithEnv Env) where
readProcessM command args input = WithEnv $ asks envReadProcess >>= liftIO . ($ input) . ($ args) . ($ command)
callProcessM command args = WithEnv $ asks envCallProcess >>= liftIO . ($ args) . ($ command)
| sol/tinc | test/MockedProcess.hs | Haskell | mit | 664 |
module Util.DocLike(module Util.DocLike, module Data.Monoid) where
-- simplified from Doc.DocLike
import Control.Applicative
import Data.Monoid(Monoid(..),(<>))
import Data.Traversable as T
import qualified Text.PrettyPrint.HughesPJ as P
import qualified Text.PrettyPrint.Leijen as L
--infixr 5 <$> -- ,<//>,<$>,<$$>
infixr 6 <+>, <->
infixl 5 $$, $+$
-- we expect a monoid instance with <>
class DocLike a where
emptyDoc :: a
text :: String -> a
oobText :: String -> a
char :: Char -> a
char x = text [x]
(<+>) :: a -> a -> a
(<->) :: a -> a -> a
($$) :: a -> a -> a
($+$) :: a -> a -> a
hsep :: [a] -> a
hcat :: [a] -> a
vcat :: [a] -> a
tupled :: [a] -> a
list :: [a] -> a
fsep :: [a] -> a
fcat :: [a] -> a
sep :: [a] -> a
cat :: [a] -> a
semiBraces :: [a] -> a
enclose :: a -> a -> a -> a
encloseSep :: a -> a -> a -> [a] -> a
oobText _ = emptyDoc
emptyDoc = text []
hcat [] = emptyDoc
hcat xs = foldr1 (<->) xs
hsep [] = emptyDoc
hsep xs = foldr1 (<+>) xs
vcat [] = emptyDoc
vcat xs = foldr1 (\x y -> x <-> char '\n' <-> y) xs
fsep = hsep
fcat = hcat
sep = hsep
cat = hcat
x <+> y = x <-> char ' ' <-> y
x $$ y = x <-> char '\n' <-> y
x $+$ y = x $$ y
encloseSep l r s ds = enclose l r (hcat $ punctuate s ds)
enclose l r x = l <-> x <-> r
list = encloseSep lbracket rbracket comma
tupled = encloseSep lparen rparen comma
semiBraces = encloseSep lbrace rbrace semi
------------------------
-- Basic building blocks
------------------------
tshow :: (Show a,DocLike b) => a -> b
tshow x = text (show x)
lparen,rparen,langle,rangle,
lbrace,rbrace,lbracket,rbracket,squote,
dquote,semi,colon,comma,space,dot,backslash,equals
:: DocLike a => a
lparen = char '('
rparen = char ')'
langle = char '<'
rangle = char '>'
lbrace = char '{'
rbrace = char '}'
lbracket = char '['
rbracket = char ']'
squote = char '\''
dquote = char '"'
semi = char ';'
colon = char ':'
comma = char ','
space = char ' '
dot = char '.'
backslash = char '\\'
equals = char '='
squotes x = enclose squote squote x
dquotes x = enclose dquote dquote x
parens x = enclose lparen rparen x
braces x = enclose lbrace rbrace x
brackets x = enclose lbracket rbracket x
angles x = enclose langle rangle x
-----------------------------------------------------------
-- punctuate p [d1,d2,...,dn] => [d1 <> p,d2 <> p, ... ,dn]
-----------------------------------------------------------
punctuate _ [] = []
punctuate _ [d] = [d]
punctuate p (d:ds) = (d <-> p) : punctuate p ds
newtype ShowSDoc = SD { unSD :: String -> String }
showSD (SD s) = s ""
instance Monoid ShowSDoc where
mempty = SD id
mappend (SD a) (SD b) = SD $ a . b
instance (DocLike ShowSDoc) where
char c = SD (c:)
text s = SD (s ++)
SD x <+> SD y = SD $ x . (' ':) . y
x <-> y = mappend x y
emptyDoc = mempty
instance (DocLike [Char]) where
char c = [c]
text s = s
x <+> y = x ++ " " ++ y
x <-> y = mappend x y
emptyDoc = mempty
instance (DocLike a, Applicative m) => DocLike (m a) where
emptyDoc = pure emptyDoc
char x = pure (char x)
text x = pure (text x)
($$) = liftA2 ($$)
($+$) = liftA2 ($+$)
(<+>) = liftA2 (<+>)
(<->) = liftA2 (<->)
vcat xs = vcat <$> traverse id xs
hsep xs = hsep <$> traverse id xs
---------------------
-- HughesPJ instances
---------------------
-- instance Monoid P.Doc where
-- mappend = (P.<>)
-- mempty = P.empty
-- mconcat = P.hcat
instance DocLike P.Doc where
emptyDoc = mempty
text = P.text
char = P.char
(<->) = (P.<>)
(<+>) = (P.<+>)
($$) = (P.$$)
($+$) = (P.$+$)
hsep = P.hsep
vcat = P.vcat
oobText = P.zeroWidthText
fcat = P.fcat
fsep = P.fsep
cat = P.cat
sep = P.sep
instance DocLike L.Doc where
emptyDoc = mempty
text = L.text
char = L.char
(<->) = (L.<>)
(<+>) = (L.<+>)
($$) = (L.</>)
($+$) = (L.<$>)
hsep = L.hsep
vcat = L.vcat
fcat = L.fillCat
fsep = L.fillSep
cat = L.cat
sep = L.sep
instance Monoid L.Doc where
mempty = L.empty
mappend = (L.<>)
mconcat = L.hcat
| hvr/jhc | src/Util/DocLike.hs | Haskell | mit | 4,453 |
{-# LANGUAGE BangPatterns, CPP, OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
module Aeson
(
aeson
, value'
) where
import Data.ByteString.Builder
(Builder, byteString, toLazyByteString, charUtf8, word8)
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative ((*>), (<$>), (<*), pure)
import Data.Monoid (mappend, mempty)
#endif
import Common (pathTo)
import Control.Applicative (liftA2)
import Control.DeepSeq (NFData(..))
import Control.Monad (forM)
import Data.Attoparsec.ByteString.Char8 (Parser, char, endOfInput, scientific,
skipSpace, string)
import Data.Bits ((.|.), shiftL)
import Data.ByteString (ByteString)
import Data.Char (chr)
import Data.List (sort)
import Data.Scientific (Scientific)
import Data.Text (Text)
import Data.Text.Encoding (decodeUtf8')
import Data.Vector as Vector (Vector, foldl', fromList)
import Data.Word (Word8)
import System.Directory (getDirectoryContents)
import System.FilePath ((</>), dropExtension)
import qualified Data.Attoparsec.ByteString as A
import qualified Data.Attoparsec.Lazy as L
import qualified Data.Attoparsec.Zepto as Z
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Unsafe as B
import qualified Data.HashMap.Strict as H
import Criterion.Main
#define BACKSLASH 92
#define CLOSE_CURLY 125
#define CLOSE_SQUARE 93
#define COMMA 44
#define DOUBLE_QUOTE 34
#define OPEN_CURLY 123
#define OPEN_SQUARE 91
#define C_0 48
#define C_9 57
#define C_A 65
#define C_F 70
#define C_a 97
#define C_f 102
#define C_n 110
#define C_t 116
data Result a = Error String
| Success a
deriving (Eq, Show)
-- | A JSON \"object\" (key\/value map).
type Object = H.HashMap Text Value
-- | A JSON \"array\" (sequence).
type Array = Vector Value
-- | A JSON value represented as a Haskell value.
data Value = Object !Object
| Array !Array
| String !Text
| Number !Scientific
| Bool !Bool
| Null
deriving (Eq, Show)
instance NFData Value where
rnf (Object o) = rnf o
rnf (Array a) = Vector.foldl' (\x y -> rnf y `seq` x) () a
rnf (String s) = rnf s
rnf (Number n) = rnf n
rnf (Bool b) = rnf b
rnf Null = ()
-- | Parse a top-level JSON value. This must be either an object or
-- an array, per RFC 4627.
--
-- The conversion of a parsed value to a Haskell value is deferred
-- until the Haskell value is needed. This may improve performance if
-- only a subset of the results of conversions are needed, but at a
-- cost in thunk allocation.
json :: Parser Value
json = json_ object_ array_
-- | Parse a top-level JSON value. This must be either an object or
-- an array, per RFC 4627.
--
-- This is a strict version of 'json' which avoids building up thunks
-- during parsing; it performs all conversions immediately. Prefer
-- this version if most of the JSON data needs to be accessed.
json' :: Parser Value
json' = json_ object_' array_'
json_ :: Parser Value -> Parser Value -> Parser Value
json_ obj ary = do
w <- skipSpace *> A.satisfy (\w -> w == OPEN_CURLY || w == OPEN_SQUARE)
if w == OPEN_CURLY
then obj
else ary
{-# INLINE json_ #-}
object_ :: Parser Value
object_ = {-# SCC "object_" #-} Object <$> objectValues jstring value
object_' :: Parser Value
object_' = {-# SCC "object_'" #-} do
!vals <- objectValues jstring' value'
return (Object vals)
where
jstring' = do
!s <- jstring
return s
objectValues :: Parser Text -> Parser Value -> Parser (H.HashMap Text Value)
objectValues str val = do
skipSpace
let pair = liftA2 (,) (str <* skipSpace) (char ':' *> skipSpace *> val)
H.fromList <$> commaSeparated pair CLOSE_CURLY
{-# INLINE objectValues #-}
array_ :: Parser Value
array_ = {-# SCC "array_" #-} Array <$> arrayValues value
array_' :: Parser Value
array_' = {-# SCC "array_'" #-} do
!vals <- arrayValues value'
return (Array vals)
commaSeparated :: Parser a -> Word8 -> Parser [a]
commaSeparated item endByte = do
w <- A.peekWord8'
if w == endByte
then A.anyWord8 >> return []
else loop
where
loop = do
v <- item <* skipSpace
ch <- A.satisfy $ \w -> w == COMMA || w == endByte
if ch == COMMA
then skipSpace >> (v:) <$> loop
else return [v]
{-# INLINE commaSeparated #-}
arrayValues :: Parser Value -> Parser (Vector Value)
arrayValues val = do
skipSpace
Vector.fromList <$> commaSeparated val CLOSE_SQUARE
{-# INLINE arrayValues #-}
-- | Parse any JSON value. You should usually 'json' in preference to
-- this function, as this function relaxes the object-or-array
-- requirement of RFC 4627.
--
-- In particular, be careful in using this function if you think your
-- code might interoperate with Javascript. A naïve Javascript
-- library that parses JSON data using @eval@ is vulnerable to attack
-- unless the encoded data represents an object or an array. JSON
-- implementations in other languages conform to that same restriction
-- to preserve interoperability and security.
value :: Parser Value
value = do
w <- A.peekWord8'
case w of
DOUBLE_QUOTE -> A.anyWord8 *> (String <$> jstring_)
OPEN_CURLY -> A.anyWord8 *> object_
OPEN_SQUARE -> A.anyWord8 *> array_
C_f -> string "false" *> pure (Bool False)
C_t -> string "true" *> pure (Bool True)
C_n -> string "null" *> pure Null
_ | w >= 48 && w <= 57 || w == 45
-> Number <$> scientific
| otherwise -> fail "not a valid json value"
-- | Strict version of 'value'. See also 'json''.
value' :: Parser Value
value' = do
w <- A.peekWord8'
case w of
DOUBLE_QUOTE -> do
!s <- A.anyWord8 *> jstring_
return (String s)
OPEN_CURLY -> A.anyWord8 *> object_'
OPEN_SQUARE -> A.anyWord8 *> array_'
C_f -> string "false" *> pure (Bool False)
C_t -> string "true" *> pure (Bool True)
C_n -> string "null" *> pure Null
_ | w >= 48 && w <= 57 || w == 45
-> do
!n <- scientific
return (Number n)
| otherwise -> fail "not a valid json value"
-- | Parse a quoted JSON string.
jstring :: Parser Text
jstring = A.word8 DOUBLE_QUOTE *> jstring_
-- | Parse a string without a leading quote.
jstring_ :: Parser Text
jstring_ = {-# SCC "jstring_" #-} do
s <- A.scan False $ \s c -> if s then Just False
else if c == DOUBLE_QUOTE
then Nothing
else Just (c == BACKSLASH)
_ <- A.word8 DOUBLE_QUOTE
s1 <- if BACKSLASH `B.elem` s
then case Z.parse unescape s of
Right r -> return r
Left err -> fail err
else return s
case decodeUtf8' s1 of
Right r -> return r
Left err -> fail $ show err
{-# INLINE jstring_ #-}
unescape :: Z.Parser ByteString
unescape = toByteString <$> go mempty where
go acc = do
h <- Z.takeWhile (/=BACKSLASH)
let rest = do
start <- Z.take 2
let !slash = B.unsafeHead start
!t = B.unsafeIndex start 1
escape = case B.findIndex (==t) "\"\\/ntbrfu" of
Just i -> i
_ -> 255
if slash /= BACKSLASH || escape == 255
then fail "invalid JSON escape sequence"
else do
let cont m = go (acc `mappend` byteString h `mappend` m)
{-# INLINE cont #-}
if t /= 117 -- 'u'
then cont (word8 (B.unsafeIndex mapping escape))
else do
a <- hexQuad
if a < 0xd800 || a > 0xdfff
then cont (charUtf8 (chr a))
else do
b <- Z.string "\\u" *> hexQuad
if a <= 0xdbff && b >= 0xdc00 && b <= 0xdfff
then let !c = ((a - 0xd800) `shiftL` 10) +
(b - 0xdc00) + 0x10000
in cont (charUtf8 (chr c))
else fail "invalid UTF-16 surrogates"
done <- Z.atEnd
if done
then return (acc `mappend` byteString h)
else rest
mapping = "\"\\/\n\t\b\r\f"
hexQuad :: Z.Parser Int
hexQuad = do
s <- Z.take 4
let hex n | w >= C_0 && w <= C_9 = w - C_0
| w >= C_a && w <= C_f = w - 87
| w >= C_A && w <= C_F = w - 55
| otherwise = 255
where w = fromIntegral $ B.unsafeIndex s n
a = hex 0; b = hex 1; c = hex 2; d = hex 3
if (a .|. b .|. c .|. d) /= 255
then return $! d .|. (c `shiftL` 4) .|. (b `shiftL` 8) .|. (a `shiftL` 12)
else fail "invalid hex escape"
decodeWith :: Parser Value -> (Value -> Result a) -> L.ByteString -> Maybe a
decodeWith p to s =
case L.parse p s of
L.Done _ v -> case to v of
Success a -> Just a
_ -> Nothing
_ -> Nothing
{-# INLINE decodeWith #-}
decodeStrictWith :: Parser Value -> (Value -> Result a) -> B.ByteString
-> Maybe a
decodeStrictWith p to s =
case either Error to (A.parseOnly p s) of
Success a -> Just a
Error _ -> Nothing
{-# INLINE decodeStrictWith #-}
eitherDecodeWith :: Parser Value -> (Value -> Result a) -> L.ByteString
-> Either String a
eitherDecodeWith p to s =
case L.parse p s of
L.Done _ v -> case to v of
Success a -> Right a
Error msg -> Left msg
L.Fail _ _ msg -> Left msg
{-# INLINE eitherDecodeWith #-}
eitherDecodeStrictWith :: Parser Value -> (Value -> Result a) -> B.ByteString
-> Either String a
eitherDecodeStrictWith p to s =
case either Error to (A.parseOnly p s) of
Success a -> Right a
Error msg -> Left msg
{-# INLINE eitherDecodeStrictWith #-}
-- $lazy
--
-- The 'json' and 'value' parsers decouple identification from
-- conversion. Identification occurs immediately (so that an invalid
-- JSON document can be rejected as early as possible), but conversion
-- to a Haskell value is deferred until that value is needed.
--
-- This decoupling can be time-efficient if only a smallish subset of
-- elements in a JSON value need to be inspected, since the cost of
-- conversion is zero for uninspected elements. The trade off is an
-- increase in memory usage, due to allocation of thunks for values
-- that have not yet been converted.
-- $strict
--
-- The 'json'' and 'value'' parsers combine identification with
-- conversion. They consume more CPU cycles up front, but have a
-- smaller memory footprint.
-- | Parse a top-level JSON value followed by optional whitespace and
-- end-of-input. See also: 'json'.
jsonEOF :: Parser Value
jsonEOF = json <* skipSpace <* endOfInput
-- | Parse a top-level JSON value followed by optional whitespace and
-- end-of-input. See also: 'json''.
jsonEOF' :: Parser Value
jsonEOF' = json' <* skipSpace <* endOfInput
toByteString :: Builder -> ByteString
toByteString = L.toStrict . toLazyByteString
{-# INLINE toByteString #-}
aeson :: IO Benchmark
aeson = do
path <- pathTo "json-data"
names <- sort . filter (`notElem` [".", ".."]) <$> getDirectoryContents path
benches <- forM names $ \name -> do
bs <- B.readFile (path </> name)
return . bench (dropExtension name) $ nf (A.parseOnly jsonEOF') bs
return $ bgroup "aeson" benches
| beni55/attoparsec | benchmarks/Aeson.hs | Haskell | bsd-3-clause | 11,671 |
<?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="sq-AL">
<title>Code Dx | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | thc202/zap-extensions | addOns/codedx/src/main/javahelp/org/zaproxy/zap/extension/codedx/resources/help_sq_AL/helpset_sq_AL.hs | Haskell | apache-2.0 | 968 |
-- | UTF-8 encode a text
--
-- Tested in this benchmark:
--
-- * Replicating a string a number of times
--
-- * UTF-8 encoding it
--
module Benchmarks.EncodeUtf8
( benchmark
) where
import Criterion (Benchmark, bgroup, bench, whnf)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TL
benchmark :: String -> IO Benchmark
benchmark string = do
return $ bgroup "EncodeUtf8"
[ bench "Text" $ whnf (B.length . T.encodeUtf8) text
, bench "LazyText" $ whnf (BL.length . TL.encodeUtf8) lazyText
]
where
-- The string in different formats
text = T.replicate k $ T.pack string
lazyText = TL.replicate (fromIntegral k) $ TL.pack string
-- Amount
k = 100000
| beni55/text | benchmarks/haskell/Benchmarks/EncodeUtf8.hs | Haskell | bsd-2-clause | 901 |
{-# LANGUAGE DeriveDataTypeable, TypeFamilies, TemplateHaskell,
RankNTypes, NamedFieldPuns, RecordWildCards,
RecursiveDo, BangPatterns, CPP #-}
module Distribution.Server.Features.HoogleData (
initHoogleDataFeature,
HoogleDataFeature(..),
) where
import Distribution.Server.Framework hiding (path)
import Distribution.Server.Framework.BlobStorage (BlobId)
import qualified Distribution.Server.Framework.BlobStorage as BlobStorage
import Distribution.Server.Features.Core
import Distribution.Server.Features.Documentation
import Distribution.Server.Features.TarIndexCache
import qualified Distribution.Server.Packages.PackageIndex as PackageIndex
import Data.TarIndex as TarIndex
import Distribution.Package
import Distribution.Text
import qualified Codec.Archive.Tar as Tar
import qualified Codec.Archive.Tar.Entry as Tar
import qualified Codec.Compression.GZip as GZip
import qualified Codec.Compression.Zlib.Internal as Zlib
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (Map)
import qualified Data.Map as Map
import qualified Data.ByteString.Lazy as BS
import Data.Serialize (runGetLazy, runPutLazy)
import Data.SafeCopy (SafeCopy, safeGet, safePut)
import Data.Maybe
import Control.Monad.State
import System.IO
import System.IO.Unsafe (unsafeInterleaveIO)
import System.Directory
import System.FilePath
import Control.Concurrent.MVar
import Control.Concurrent.Async
import Control.Exception
import qualified System.IO.Error as IOError
-- | A feature to serve up a tarball of hoogle files, for the hoogle client.
--
data HoogleDataFeature = HoogleDataFeature {
hoogleDataFeatureInterface :: HackageFeature
}
instance IsHackageFeature HoogleDataFeature where
getFeatureInterface = hoogleDataFeatureInterface
----------------------------------------
-- Feature definition & initialisation
--
initHoogleDataFeature :: ServerEnv
-> IO (CoreFeature
-> DocumentationFeature
-> TarIndexCacheFeature
-> IO HoogleDataFeature)
initHoogleDataFeature env@ServerEnv{ serverCacheDelay,
serverVerbosity = verbosity } = do
-- Ephemeral state
docsUpdatedState <- newMemStateWHNF Set.empty
hoogleBundleUpdateJob <- newAsyncUpdate serverCacheDelay verbosity
"hoogle.tar.gz"
return $ \core docs tarIndexCache -> do
let feature = hoogleDataFeature docsUpdatedState
hoogleBundleUpdateJob
env core docs tarIndexCache
return feature
hoogleDataFeature :: MemState (Set PackageId)
-> AsyncUpdate
-> ServerEnv
-> CoreFeature
-> DocumentationFeature
-> TarIndexCacheFeature
-> HoogleDataFeature
hoogleDataFeature docsUpdatedState hoogleBundleUpdateJob
ServerEnv{serverBlobStore = store, serverStateDir}
CoreFeature{..} DocumentationFeature{..}
TarIndexCacheFeature{..}
= HoogleDataFeature {..}
where
hoogleDataFeatureInterface = (emptyHackageFeature "hoogle-data") {
featureDesc = "Provide a tarball of all package's hoogle files"
, featureResources = [hoogleBundleResource]
, featureState = []
, featureCaches = []
, featurePostInit = postInit
}
-- Resources
--
hoogleBundleResource =
(resourceAt "/packages/hoogle.tar.gz") {
resourceDesc = [ (GET, "get the tarball of hoogle files for all packages")
]
, resourceGet = [ ("tarball", serveHoogleData) ]
}
-- Request handlers
--
featureStateDir = serverStateDir </> "db" </> "HoogleData"
bundleTarGzFile = featureStateDir </> "hoogle.tar.gz"
bundleCacheFile = featureStateDir </> "cache"
serveHoogleData :: DynamicPath -> ServerPartE Response
serveHoogleData _ =
-- serve the cached hoogle.tar.gz file
serveFile (asContentType "application/x-gzip") bundleTarGzFile
postInit :: IO ()
postInit = do
createDirectoryIfMissing False featureStateDir
prodFileCacheUpdate
registerHook documentationChangeHook $ \pkgid -> do
modifyMemState docsUpdatedState (Set.insert pkgid)
prodFileCacheUpdate
prodFileCacheUpdate :: IO ()
prodFileCacheUpdate =
asyncUpdate hoogleBundleUpdateJob updateHoogleBundle
-- Actually do the update. Here we are guaranteed that we're only doing
-- one update at once, no concurrent updates.
updateHoogleBundle :: IO ()
updateHoogleBundle = do
docsUpdated <- readMemState docsUpdatedState
writeMemState docsUpdatedState Set.empty
updated <- maybeWithFile bundleTarGzFile $ \mhOldTar -> do
mcache <- readCacheFile bundleCacheFile
let docEntryCache = maybe Map.empty fst mcache
oldTarPkgids = maybe Set.empty snd mcache
tmpdir = featureStateDir
updateTarBundle mhOldTar tmpdir
docEntryCache oldTarPkgids
docsUpdated
case updated of
Nothing -> return ()
Just (docEntryCache', newTarPkgids, newTarFile) -> do
renameFile newTarFile bundleTarGzFile
writeCacheFile bundleCacheFile (docEntryCache', newTarPkgids)
updateTarBundle :: Maybe Handle -> FilePath
-> Map PackageId (Maybe (BlobId, TarEntryOffset))
-> Set PackageId
-> Set PackageId
-> IO (Maybe (Map PackageId (Maybe (BlobId, TarEntryOffset))
,Set PackageId, FilePath))
updateTarBundle mhOldTar tmpdir docEntryCache oldTarPkgids docsUpdated = do
-- Invalidate cached info about any package docs that have been updated
let docEntryCache' = docEntryCache `Map.difference` fromSet docsUpdated
cachedPkgids = fromSet (oldTarPkgids `Set.difference` docsUpdated)
-- get the package & docs index
pkgindex <- queryGetPackageIndex
docindex <- queryDocumentationIndex
-- Select the package ids that have corresponding docs that contain a
-- hoogle .txt file.
-- We prefer later package versions, but if a later one is missing the
-- hoogle .txt file then we fall back to older ones.
--
-- For the package ids we pick we keep the associated doc tarball blobid
-- and the offset of the hoogle .txt file within that tarball.
--
-- Looking up if a package's docs contains the hoogle .txt file is
-- expensive (have to read the doc tarball's index) so we maintain a
-- cache of that information.
(selectedPkgids, docEntryCache'') <-
-- use a state monad for access to and updating the cache
flip runStateT docEntryCache' $
fmap (Map.fromList . catMaybes) $
sequence
[ findFirstCached (lookupHoogleEntry docindex)
(reverse (map packageId pkgs))
| pkgs <- PackageIndex.allPackagesByName pkgindex ]
-- the set of pkgids to try to reuse from the existing tar file
let reusePkgs :: Map PackageId ()
reusePkgs = cachedPkgids `Map.intersection` selectedPkgids
-- the packages where we need to read it fresh
readFreshPkgs :: Map PackageId (BlobId, TarEntryOffset)
readFreshPkgs = selectedPkgids `Map.difference` reusePkgs
if Map.null readFreshPkgs && Map.keysSet reusePkgs == oldTarPkgids
then return Nothing
else liftM Just $
withTempFile tmpdir "newtar" $ \hNewTar newTarFile ->
withWriter (tarWriter hNewTar) $ \putEntry -> do
-- We truncate on tar format errors. This works for the empty case
-- and should be self-correcting for real errors. It just means we
-- miss a few entries from the tarball 'til next time its updated.
oldEntries <- case mhOldTar of
Nothing -> return []
Just hOldTar ->
return . Tar.foldEntries (:) [] (const [])
. Tar.read
. BS.fromChunks
. Zlib.foldDecompressStream (:) [] (\_ _ -> [])
. Zlib.decompressWithErrors
Zlib.gzipFormat
Zlib.defaultDecompressParams
=<< BS.hGetContents hOldTar
-- Write out the cached ones
sequence_
[ putEntry entry
| entry <- oldEntries
, pkgid <- maybeToList (entryPkgId entry)
, pkgid `Map.member` reusePkgs ]
-- Write out the new/changed ones
sequence_
[ withFile doctarfile ReadMode $ \hDocTar -> do
mentry <- newCacheTarEntry pkgid hDocTar taroffset
maybe (return ()) putEntry mentry
| (pkgid, (doctarblobid, taroffset)) <- Map.toList readFreshPkgs
, let doctarfile = BlobStorage.filepath store doctarblobid ]
return (docEntryCache'', Map.keysSet selectedPkgids, newTarFile)
lookupHoogleEntry :: Map PackageId BlobId -> PackageId -> IO (Maybe (BlobId, TarEntryOffset))
lookupHoogleEntry docindex pkgid
| Just doctarblobid <- Map.lookup pkgid docindex
= do doctarindex <- cachedTarIndex doctarblobid
case lookupPkgDocHoogleFile pkgid doctarindex of
Nothing -> return Nothing
Just offset -> return (Just (doctarblobid, offset))
| otherwise = return Nothing
fromSet :: Ord a => Set a -> Map a ()
fromSet = Map.fromAscList . map (\x -> (x, ())) . Set.toAscList
-- | Like list 'find' but with a monadic lookup function and we cache the
-- results of that lookup function.
--
findFirstCached :: (Ord a, Monad m)
=> (a -> m (Maybe b))
-> [a] -> StateT (Map a (Maybe b)) m (Maybe (a, b))
findFirstCached _ [] = return Nothing
findFirstCached f (x:xs) = do
cache <- get
case Map.lookup x cache of
Just m_y -> checkY m_y
Nothing -> do
m_y <- lift (f x)
put (Map.insert x m_y cache)
checkY m_y
where
checkY Nothing = findFirstCached f xs
checkY (Just y) = return (Just (x, y))
withTempFile :: FilePath -> String -> (Handle -> FilePath -> IO a) -> IO a
withTempFile tmpdir template action =
mask $ \restore -> do
(fname, hnd) <- openTempFile tmpdir template
x <- restore (action hnd fname)
`onException` (hClose hnd >> removeFile fname)
hClose hnd
return x
maybeWithFile :: FilePath -> (Maybe Handle -> IO a) -> IO a
maybeWithFile file action =
mask $ \unmask -> do
mhnd <- try $ openFile file ReadMode
case mhnd of
Right hnd -> unmask (action (Just hnd)) `finally` hClose hnd
Left e | IOError.isDoesNotExistError e
, Just file == IOError.ioeGetFileName e
-> unmask (action Nothing)
Left e -> throw e
readCacheFile :: SafeCopy a => FilePath -> IO (Maybe a)
readCacheFile file =
maybeWithFile file $ \mhnd ->
case mhnd of
Nothing -> return Nothing
Just hnd -> do
content <- BS.hGetContents hnd
case runGetLazy safeGet content of
Left _ -> return Nothing
Right x -> return (Just x)
writeCacheFile :: SafeCopy a => FilePath -> a -> IO ()
writeCacheFile file x =
BS.writeFile file (runPutLazy (safePut x))
lookupPkgDocHoogleFile :: PackageId -> TarIndex -> Maybe TarEntryOffset
lookupPkgDocHoogleFile pkgid index = do
TarFileEntry offset <- TarIndex.lookup index path
return offset
where
path = (display pkgid ++ "-docs") </> display (packageName pkgid) <.> "txt"
newCacheTarEntry :: PackageId -> Handle -> TarEntryOffset -> IO (Maybe Tar.Entry)
newCacheTarEntry pkgid htar offset
| Just entrypath <- hoogleDataTarPath pkgid = do
morigEntry <- readTarEntryAt htar offset
case morigEntry of
Nothing -> return Nothing
Just origEntry ->
return $ Just
(Tar.simpleEntry entrypath (Tar.entryContent origEntry)) {
Tar.entryTime = Tar.entryTime origEntry
}
| otherwise = return Nothing
hoogleDataTarPath :: PackageId -> Maybe Tar.TarPath
hoogleDataTarPath pkgid =
either (const Nothing) Just (Tar.toTarPath False filepath)
where
-- like zlib/0.5.4.1/doc/html/zlib.txt
filepath = joinPath [ display (packageName pkgid)
, display (packageVersion pkgid)
, "doc", "html"
, display (packageName pkgid) <.> "txt" ]
entryPkgId :: Tar.Entry -> Maybe PackageId
entryPkgId = parseEntryPath . Tar.entryPath
parseEntryPath :: FilePath -> Maybe PackageId
parseEntryPath filename
| [namestr, verstr,
"doc", "html",
filestr] <- splitDirectories filename
, Just pkgname <- simpleParse namestr
, Just pkgver <- simpleParse verstr
, (namestr', ".txt") <- splitExtension filestr
, Just pkgname' <- simpleParse namestr'
, pkgname == pkgname'
= Just (PackageIdentifier pkgname pkgver)
| otherwise
= Nothing
readTarEntryAt :: Handle -> TarEntryOffset -> IO (Maybe Tar.Entry)
readTarEntryAt htar off = do
hSeek htar AbsoluteSeek (fromIntegral (off * 512))
header <- BS.hGet htar 512
case Tar.read header of
(Tar.Next [email protected]{Tar.entryContent = Tar.NormalFile _ size} _) -> do
content <- BS.hGet htar (fromIntegral size)
return $ Just entry { Tar.entryContent = Tar.NormalFile content size }
_ -> return Nothing
data Writer a = Writer { wWrite :: a -> IO (), wClose :: IO () }
withWriter :: IO (Writer b) -> ((b -> IO ()) -> IO a) -> IO a
withWriter mkwriter action = bracket mkwriter wClose (action . wWrite)
tarWriter :: Handle -> IO (Writer Tar.Entry)
tarWriter hnd = do
chan <- newBChan
awriter <- async $ do
entries <- getBChanContents chan
BS.hPut hnd ((GZip.compress . Tar.write) entries)
return Writer {
wWrite = writeBChan chan,
wClose = do closeBChan chan
wait awriter
}
newtype BChan a = BChan (MVar (Maybe a))
newBChan :: IO (BChan a)
newBChan = liftM BChan newEmptyMVar
writeBChan :: BChan a -> a -> IO ()
writeBChan (BChan c) = putMVar c . Just
closeBChan :: BChan a -> IO ()
closeBChan (BChan c) = putMVar c Nothing
getBChanContents :: BChan a -> IO [a]
getBChanContents (BChan c) = do
res <- takeMVar c
case res of
Nothing -> return []
Just x -> do xs <- unsafeInterleaveIO (getBChanContents (BChan c))
return (x : xs)
| ocharles/hackage-server | Distribution/Server/Features/HoogleData.hs | Haskell | bsd-3-clause | 14,928 |
-- Trac #958
module ShoulFail where
data Succ a = S a -- NB: deriving Show omitted
data Seq a = Cons a (Seq (Succ a)) | Nil deriving Show
| ezyang/ghc | testsuite/tests/typecheck/should_fail/tcfail169.hs | Haskell | bsd-3-clause | 148 |
{-# LANGUAGE Arrows #-}
module Main(main) where
import Control.Arrow
import Control.Category
import Prelude hiding (id, (.))
class ArrowLoop a => ArrowCircuit a where
delay :: b -> a b b
-- stream map instance
data Stream a = Cons a (Stream a)
instance Functor Stream where
fmap f ~(Cons a as) = Cons (f a) (fmap f as)
zipStream :: Stream a -> Stream b -> Stream (a,b)
zipStream ~(Cons a as) ~(Cons b bs) = Cons (a,b) (zipStream as bs)
unzipStream :: Stream (a,b) -> (Stream a, Stream b)
unzipStream abs = (fmap fst abs, fmap snd abs)
newtype StreamMap a b = StreamMap (Stream a -> Stream b)
unStreamMap (StreamMap f) = f
instance Category StreamMap where
id = StreamMap id
StreamMap f . StreamMap g = StreamMap (f . g)
instance Arrow StreamMap where
arr f = StreamMap (fmap f)
first (StreamMap f) =
StreamMap (uncurry zipStream . first f . unzipStream)
instance ArrowLoop StreamMap where
loop (StreamMap f) =
StreamMap (loop (unzipStream . f . uncurry zipStream))
instance ArrowCircuit StreamMap where
delay a = StreamMap (Cons a)
listToStream :: [a] -> Stream a
listToStream = foldr Cons undefined
streamToList :: Stream a -> [a]
streamToList (Cons a as) = a:streamToList as
runStreamMap :: StreamMap a b -> [a] -> [b]
runStreamMap (StreamMap f) as =
take (length as) (streamToList (f (listToStream as)))
-- simple automaton instance
data Auto a b = Auto (a -> (b, Auto a b))
instance Category Auto where
id = Auto $ \a -> (a, id)
Auto f . Auto g = Auto $ \b ->
let (c, g') = g b
(d, f') = f c
in (d, f' . g')
instance Arrow Auto where
arr f = Auto $ \a -> (f a, arr f)
first (Auto f) = Auto $ \(b,d) -> let (c,f') = f b in ((c,d), first f')
instance ArrowLoop Auto where
loop (Auto f) = Auto $ \b ->
let (~(c,d), f') = f (b,d)
in (c, loop f')
instance ArrowCircuit Auto where
delay a = Auto $ \a' -> (a, delay a')
runAuto :: Auto a b -> [a] -> [b]
runAuto (Auto f) [] = []
runAuto (Auto f) (a:as) = let (b, f') = f a in b:runAuto f' as
-- Some simple example circuits
-- A resettable counter (first example in several Hawk papers):
counter :: ArrowCircuit a => a Bool Int
counter = proc reset -> do
rec output <- returnA -< if reset then 0 else next
next <- delay 0 -< output+1
returnA -< output
-- Some other basic circuits from the Hawk library.
-- flush: when reset is True, return d for n ticks, otherwise copy value.
-- (a variation on the resettable counter)
flush :: ArrowCircuit a => Int -> b -> a (b, Bool) b
flush n d = proc (value, reset) -> do
rec count <- returnA -< if reset then n else max (next-1) 0
next <- delay 0 -< count
returnA -< if count > 0 then d else value
-- latch: on each tick, return the last value for which reset was True,
-- or init if there was none.
--
latch :: ArrowCircuit a => b -> a (b, Bool) b
latch init = proc (value, reset) -> do
rec out <- returnA -< if reset then value else last
last <- delay init -< out
returnA -< out
-- Some tests using the counter
test_input = [True, False, True, False, False, True, False, True]
test_input2 = zip [1..] test_input
-- A test of the resettable counter.
main = do
print (runStreamMap counter test_input)
print (runAuto counter test_input)
print (runStreamMap (flush 2 0) test_input2)
print (runAuto (flush 2 0) test_input2)
print (runStreamMap (latch 0) test_input2)
print (runAuto (latch 0) test_input2)
-- A step function (cf current in Lustre)
step :: ArrowCircuit a => b -> a (Either b c) b
step b = proc x -> do
rec last_b <- delay b -< getLeft last_b x
returnA -< last_b
where getLeft _ (Left b) = b
getLeft b (Right _) = b
| wxwxwwxxx/ghc | testsuite/tests/arrows/should_run/arrowrun003.hs | Haskell | bsd-3-clause | 3,614 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
module JPSubreddits.Types where
import Control.Applicative
import Control.Monad
import Control.Monad.IO.Class (MonadIO)
import Data.Aeson (FromJSON (..), ToJSON (..), object, (.:), (.=))
import Data.Text (Text)
import Data.Time (ZonedTime)
class DataSource a where
getListFromDataSource :: (Functor m, MonadIO m) => a -> m [(CategoryName, [(Title, Url)])]
newtype Url = Url { unUrl :: Text }
deriving (Show, Read, ToJSON, FromJSON)
newtype Title = Title { unTitle :: Text }
deriving (Show, Read, ToJSON, FromJSON)
newtype CategoryName = CategoryName { unCategoryName :: Text }
deriving (Show, Read, ToJSON, FromJSON)
data Subreddit = Subreddit
{ url :: Url
, title :: Title
}
deriving (Show, Read)
data Category = Category
{ name :: CategoryName
, subreddits :: [Subreddit]
}
deriving (Show, Read)
data JPSubreddits = JPSubreddits
{ generatedAt :: ZonedTime
, categories :: [Category]
}
deriving (Show, Read)
---------------------------------------------
-- Instancies
---------------------------------------------
instance FromJSON Subreddit where
parseJSON = parseJSON >=> go
where
go o = Subreddit
<$> o .: "url"
<*> o .: "title"
instance ToJSON Subreddit where
toJSON s = object
[ "url" .= url s
, "title" .= title s
]
instance FromJSON Category where
parseJSON = parseJSON >=> go
where
go o = Category
<$> o .: "category"
<*> o .: "list"
instance ToJSON Category where
toJSON s = object
[ "category" .= name s
, "list" .= subreddits s
]
instance FromJSON JPSubreddits where
parseJSON = parseJSON >=> go
where
go o = JPSubreddits
<$> o .: "generated_at"
<*> o .: "jpsubreddits"
instance ToJSON JPSubreddits where
toJSON s = object
[ "generated_at" .= show (generatedAt s)
, "jpsubreddits" .= categories s
]
| sifisifi/jpsubreddits | src/JPSubreddits/Types.hs | Haskell | mit | 2,136 |
-- prolog engine v1
-- TODO lists and strings
import Prelude hiding (pred)
import Test.Hspec
import Text.ParserCombinators.Parsec
import Text.Parsec.Error
import Control.Applicative hiding ((<|>), many)
import Control.Monad
import System.IO
import Data.List
import Data.Maybe
import qualified Data.Map as Map
--import Debug.Trace (trace)
type VarName = String
data Term = Atom String | Var VarName | Func String [Term] | Int Integer
deriving (Show, Eq)
data Pred = Pred String [Term] | NegPred String [Term]
deriving (Show, Eq)
data Rule = Rule Pred [Pred]
deriving (Show, Eq)
-- do we need a completely separate representation of logical formulas?
type Clause = [Pred]
-- substitution Var -> Term
type Sub = Map.Map VarName Term
-- ====== --
-- Parser --
-- ====== --
lowerWordP :: Parser String
lowerWordP = (:) <$> lower <*> many alphaNum
atomP :: Parser Term
atomP = Atom <$> lowerWordP
varP :: Parser Term
varP = liftM Var $ (:) <$> upper <*> many alphaNum
intP :: Parser Term
intP = Int . read <$> many1 digit
funcP :: Parser Term
funcP = Func <$>
((lowerWordP <|> string ".") <* char '(') <*>
(termListP <* char ')')
termP :: Parser Term
termP = try funcP <|> intP <|> varP <|> atomP
-- interesting approach for just a list of terms, "return" here acts
-- as the list constructor
-- termListP = return <$> termP
termListP :: Parser [Term]
-- left-recursive version doesn't work
-- termListP = ((++) <$> termListP <* char ',' <*> (return <$> termP)) <|>
-- return <$> termP
termListP = sepBy termP (char ',' <* spaces)
predP :: Parser Pred
predP = Pred <$> lowerWordP <* char '(' <*> termListP <* char ')'
predListP :: Parser [Pred]
predListP = sepBy predP (char ',' <* spaces)
queryP :: Parser [Pred]
queryP = predListP <* char '.'
ruleP :: Parser Rule
ruleP = Rule <$> predP <* spaces <* string ":-" <* spaces <*> predListP <* char '.'
-- =========== --
-- Unification --
-- =========== --
-- handbook of tableau methods (pg 160)
-- purposely don't handle term lists of different lengths. will throw an exception at runtime
-- should probably handle functors with different arity here as they will never unify anyways
disagreement :: [Term] -> [Term] -> Maybe (Term, Term)
disagreement [] [] = Nothing
disagreement (x:xs) (y:ys)
| x == y = disagreement xs ys
disagreement (Func f1 args1 : _) (Func f2 args2 : _)
-- decomposition of functors, agreeing functors handled above
| f1 == f2 = disagreement args1 args2
-- make sure the variable comes first if there is one
-- disagreement (x:_) (y:_) = Just $ case x of Var _ -> (x, y)
-- _ -> (y, x)
-- clearer than preceding?
disagreement (x@(Var _):_) (y:_) = Just (x, y)
disagreement (x:_) (y:_) = Just (y, x)
applySub :: [Term] -> Sub -> [Term]
applySub [] _ = []
applySub (t@(Var v):ts) sub = newT : applySub ts sub
where newT = case Map.lookup v sub of
Just x -> x
_ -> t
applySub (Func f args : ts) sub = Func f (applySub args sub) : applySub ts sub
applySub (t:ts) sub = t : applySub ts sub
applySubPred :: Pred -> Sub -> Pred
applySubPred (Pred name args) s = Pred name (applySub args s)
applySubPred (NegPred name args) s = NegPred name (applySub args s)
occursCheck :: Term -> String -> Bool
occursCheck (Atom _) _ = False
occursCheck (Func _ args) vname = Var vname `elem` args
occursCheck _ _ = False
unify :: [Term] -> [Term] -> Maybe Sub
unify = let applyAndContinue s t1 t2 = unifyInternal s t1' t2'
where t1' = applySub t1 s
t2' = applySub t2 s
unifyInternal s t1 t2 = case disagreement t1 t2 of
Nothing -> Just s
Just (Var vname, t)
| not $ occursCheck t vname ->
applyAndContinue (Map.insert vname t s) t1 t2
_ -> Nothing
in unifyInternal Map.empty
-- unify [Func "vertical" [Func "line" [Func "point" [Var "X", Var "Y"], Func "point" [Var "X", Var "Z"]]]] [Func "vertical" [Func "line" [Func "point" [Var "X", Var "Y"], Func "point" [Var "X", Var "Z"]]]]
-- TODO add these to tests:
{--
*Main> unify [Func "vertical" [Func "line" [Func "point" [Var "X", Var "Y"], Func "point" [Var "X", Var "Z"]]]] [Func "vertical" [Func "line" [Func "point" [Int 1, Int 1], Func "point" [Int 1, Int 3]]]]
Just (fromList [("X",Int 1),("Y",Int 1),("Z",Int 3)])
*Main> unify [Func "vertical" [Func "line" [Func "point" [Var "X", Var "Y"], Func "point" [Var "X", Var "Z"]]]] [Func "vertical" [Func "line" [Func "point" [Int 1, Int 1], Func "point" [Int 3, Int 2]]]]
Nothing
--}
-- ========== --
-- Resolution --
-- ========== --
-- KB is (ultimately) a conjunction of clauses
testKb1 :: [Clause]
testKb1 = [[Pred "rdf:type" [Atom "bsbase:ABriefHistoryOfEverything",
Atom "bibo:Book"]],
[Pred "bsbase:subject" [Atom "bsbase:ABriefHistoryOfEverything",
Atom "bsbase:IntegralTheory"]],
-- thinksItsCool(X, Y) :- thinksItsCool(jess, Y).
-- If Jess thinks it's cool, everyone thinks it's cool.
[Pred "thinksItsCool" [Var "X", Var "Y"],
NegPred "thinksItsCool" [Atom "jess", Var "Y"]],
[Pred "thinksItsCool" [Atom "jess", Atom "PhilCollins"]],
[Pred "f" [Atom "a"]], [Pred "f" [Atom "b"]],
[Pred "g" [Atom "a"]], [Pred "g" [Atom "b"]],
[Pred "h" [Atom "b"]],
[Pred "k" [Var "X"], NegPred "f" [Var "X"], NegPred "g" [Var "X"], NegPred "h" [Var "X"]]]
predArgs :: Pred -> [Term]
predArgs (Pred _ a) = a
predArgs (NegPred _ a) = a
predVarNames :: Pred -> [VarName]
predVarNames =
let foldIt names term = case term of (Var name) -> name:names; _ -> names
in nub . foldl foldIt [] . predArgs
-- find a way to rewrite this?
findClashingPred :: Clause -> Pred -> Maybe (Pred, Clause)
findClashingPred c (Pred predName _) = case partition (\x -> case x of NegPred predName' _ | predName' == predName -> True
_ -> False) c
of ([p], rest) -> Just (p, rest)
_ -> Nothing
findClashingPred c (NegPred predName _) = case partition (\x -> case x of Pred predName' _ | predName' == predName -> True
_ -> False) c
of ([p], rest) -> Just (p, rest)
_ -> Nothing
findClashingClauses :: [Clause] -> Pred -> [(Sub, Clause)]
findClashingClauses clauses pred =
let clausesMatchingPred :: [(Pred, Clause)]
clausesMatchingPred = mapMaybe (`findClashingPred` pred) clauses
args :: [Term]
args = predArgs pred
maybeUnifyAndReturnBoth :: (Pred, Clause) -> Maybe (Sub, Clause)
--maybeUnifyAndReturnBoth (p, c) = (unify args $ predArgs p) >>= (\sub -> return (p, map (`applySubPred` sub) c))
maybeUnifyAndReturnBoth (p, c) = do
sub <- unify args $ predArgs p
return (sub, map (`applySubPred` sub) c)
-- clausesUnifying :: [Sub]
-- clausesUnifying = mapMaybe ((unify args) . (predArgs . fst)) clausesMatchingPred
-- c0 = head clausesMatchingPred
-- c0args = (predArgs . fst) c0
-- c0sub = fromJust $ unify args c0args
-- c0resolvents = map (`applySubPred` c0sub) $ snd c0
--dealWithPred possibleClash =
in --[c0resolvents]
mapMaybe maybeUnifyAndReturnBoth clausesMatchingPred
-- TODO allow multiple clauses instead of a single predicate
solve1 :: Pred -> [Clause] -> [Sub]
solve1 pred kb =
let clashes0 :: (Sub, Clause)
clashes0 = head $ findClashingClauses kb pred
--vars = predVars pred
in []
solve01 :: [Clause] -> [Term] -> Sub -> Maybe Sub
-- nothing left to resolve, return sub
solve01 [] _ s = Just s
solve01 clauses vars s =
let kb :: [Clause]
kb = testKb1
sub :: Sub
sub = fst . head $ findClashingClauses kb $ (head . head) clauses
in Nothing
-- resolve :: Pred -> Disj -> Disj
-- resolve _ [] = []
-- resolve goal ps = -- @(Pred pname args) ps =
-- -- let x a b = (a, b)
-- -- in snd $ mapAccumL x "" []
-- let (negGoal, gname, gargs) = case goal of
-- NegPred gname gargs -> (Pred gname gargs, gname, gargs)
-- Pred gname gargs -> (NegPred gname gargs, gname, gargs)
-- xXX (sub, newList) (Pred pname args:ps)
-- | pname == gname and s@(unify args gargs) = (s
-- foldl xXX (Map.empty, []) ps
-- ========================== --
-- repl stuff copied from:
-- ========================== --
-- http://en.wikibooks.org/wiki/Write_Yourself_a_Scheme_in_48_Hours/Building_a_REPL
flushStr :: String -> IO ()
flushStr str = putStr str >> hFlush stdout
readPrompt :: String -> IO String
readPrompt prompt = flushStr prompt >> getLine
evalString :: String -> IO String
evalString expr = --return $ extractValue $ trapError (liftM show $ readExpr expr >>= eval)
return $ case parse (queryP <* eof) "" expr
of Right x -> show x
-- TODO this error message isn't useful
Left err -> intercalate "\n" (map messageString $ errorMessages err)
--Left err -> foldl (\x y -> messageString x ++ y (Message "") $ errorMessages err
evalAndPrint :: String -> IO ()
evalAndPrint expr = evalString expr >>= putStrLn
until_ :: Monad m => (a -> Bool) -> m a -> (a -> m ()) -> m ()
until_ pred prompt action = do
result <- prompt
unless (pred result) $ action result >> until_ pred prompt action
runRepl :: IO ()
runRepl = until_ (== "quit") (readPrompt "?- ") evalAndPrint
-- ===============================
main :: IO ()
main = do
putStrLn "================="
putStrLn " Prolog Engine 1"
putStrLn "================="
hspec . describe ">>> Parser tests" $ do
it "should parse basic predicates" $
case parse (predP <* eof) "" "pred(a, B)"
of Right x -> x `shouldBe`
Pred "pred" [Atom "a", Var "B"]
it "should parse functors" $
case parse (predP <* eof) "" "pred(sentence(nphrase(john),vbphrase(verb(likes),nphrase(mary))), B)"
of Right x -> x `shouldBe`
Pred "pred"
[Func "sentence"
[Func "nphrase"
[Atom "john"],
Func "vbphrase"
[Func "verb"
[Atom "likes"],
Func "nphrase"
[Atom "mary"]]],
Var "B"]
it "should parse rules" $
case parse (ruleP <* eof) "" "jealous(X, Y) :- loves(X, Z), loves(Y, Z)."
of Right x -> x `shouldBe`
Rule (Pred "jealous" [Var "X",Var "Y"])
[Pred "loves" [Var "X",Var "Z"],
Pred "loves" [Var "Y",Var "Z"]]
it "should parse unsugared lists" $
-- TODO last param should be the empty list
case parse (termP <* eof) "" ".(1, .(2, .(3, .())))"
of Right x -> x `shouldBe`
Func "." [Int 1,Func "." [Int 2,Func "." [Int 3,Func "." []]]]
hspec . describe ">>> Unification tests" $ do
it "should calculate disagreement sets properly" $
let dset = disagreement
[Func "g" [Atom "x"], Atom "y"]
[Func "g" [Atom "a", Atom "y", Atom "u"]] in
dset `shouldBe` Just (Atom "a",Atom "x")
it "should calculate disagreement sets with functors properly" $
let dset = disagreement
[Func "g" [Atom "x"], Atom "y"]
[Func "g" [Atom "x"], Atom "n", Atom "u"] in
dset `shouldBe` Just (Atom "n",Atom "y")
it "should apply a substitution" $
let sub = Map.fromList [("X",Atom "a")]
expr1 = Func "f" [Atom "b", Var "X"]
expr2 = Func "f" [Func "g" [Atom "a"]]
expr1' = applySub [expr1] sub
expr2' = applySub [expr2] sub
in (expr1', expr2') `shouldBe`
([Func "f" [Atom "b",Atom "a"]], [Func "f" [Func "g" [Atom "a"]]])
it "should perform a trivial unification" $
unify [Var "X"] [Atom "a"] `shouldBe` Just (Map.fromList [("X",Atom "a")])
it "should reject an invalid unification" $
unify [Atom "b"] [Func "f" [Var "X"]] `shouldBe` Nothing
it "should unify within functors" $
unify
[Atom "a", Func "f" [Atom "a", Var "X"]]
[Atom "a", Func "f" [Atom "a", Var "Y"]]
`shouldBe`
Just (Map.fromList [("X",Var "Y")])
it "should perform correctly on `complex terms' example" $
-- from Learn Prolog Now
unify
-- k(s(g), Y) = k(X, t(k))
[Func "k" [Func "s" [Atom "g"], Var "Y"]]
[Func "k" [Var "X", Func "t" [Atom "k"]]]
`shouldBe`
-- X = s(g), Y = t(k)
Just (Map.fromList [("X",Func "s" [Atom "g"]),("Y",Func "t" [Atom "k"])])
it "should reject impossible variable instantiations" $
unify
[Func "loves" [Var "X", Var "X"]]
[Func "loves" [Atom "marcellus", Atom "mia"]]
`shouldBe` Nothing
-- hspec . describe ">>> Resolution tests" $ do
-- it "should find clashing predicates in clauses" $
-- findClashingClauses testKb1 (NegPred "rdf:type" [])
-- `shouldBe`
-- [(Pred "rdf:type" [Atom "bsbase:ABriefHistoryOfEverything",Atom "bibo:Book"],[])]
-- it "should not find clashing predicates sometimes" $
-- findClashingClauses testKb1 (Pred "rdf:type" [])
-- `shouldBe` []
putStrLn "Welcome to Prolog Engine 1"
--runRepl
return ()
| jbalint/banshee-sympatico | meera/prolog_engine1.hs | Haskell | mit | 13,740 |
module Operation
( Operation(..)
, operate
, undo
) where
import Data.Ix
data Operation = SwapIndices Int Int
| SwapLetters Char Char
| RotateLeft Int
| RotateRight Int
| RotateAroundLetter Char
| Reverse Int Int
| Move Int Int
deriving (Show)
operate :: String -> Operation -> String
operate str (SwapIndices x y) = map (\(c', c) -> if c == x then y' else if c == y then x' else c') (zip str [0..])
where (x', y') = (str !! x, str !! y)
operate str (SwapLetters x y) = map (\c -> if c == x then y else if c == y then x else c) str
operate str (RotateLeft steps)
| steps == 0 = str
| otherwise = operate str' (RotateLeft (steps - 1))
where str' = (tail str) ++ [head str]
operate str (RotateRight steps)
| steps == 0 = str
| otherwise = operate str' (RotateRight (steps - 1))
where str' = (last str) : (take (n - 1) str)
n = length str
operate str (RotateAroundLetter x) = operate str rotator
where xIndex = (snd . head) (filter (\(c, i) -> c == x) (zip str [0..]))
rotator = RotateRight (1 + xIndex + maybeExtra)
maybeExtra = if xIndex >= 4 then 1 else 0
operate str (Reverse x y) = front ++ (reverse middle) ++ back
where front = ((map fst) . (filter (\(a, b) -> b < x))) (zip str [0..])
middle = ((map fst) . (filter (\(a, b) -> inRange (x, y) b))) (zip str [0..])
back = ((map fst) . (filter (\(a, b) -> b > y))) (zip str [0..])
operate str (Move x y) = str''
where chr = str !! x
str' = (take x str) ++ (drop (x + 1) str)
str'' = (take y str') ++ [chr] ++ (drop y str')
undo :: String -> Operation -> String
undo str (RotateLeft steps) = operate str (RotateRight steps)
undo str (RotateRight steps) = operate str (RotateLeft steps)
undo str (RotateAroundLetter x) = until done (\str' -> operate str' (RotateLeft 1)) str
where done str' = str == (operate str' (RotateAroundLetter x))
undo str (Move x y) = operate str (Move y x)
undo str op = operate str op -- covers SwapIndices, SwapLetters, Reverse
instance Read Operation where
readsPrec _ ('s':'w':'a':'p':rs)
| r1 == "position" = [(SwapIndices ((read p1) :: Int) ((read p2) :: Int), "")]
| otherwise = [(SwapLetters (head p1) (head p2), "")]
where (r1:p1:_:_:p2:_) = words rs
readsPrec _ ('r':'o':'t':'a':'t':'e':rs)
| dir == "left" = [(RotateLeft n, "")]
| dir == "right" = [(RotateRight n, "")]
| otherwise = [(RotateAroundLetter ((head . last) rs'), "")]
where rs'@(dir:_) = words rs
n = read (rs' !! 1) :: Int
c = (head . last) rs'
readsPrec _ ('r':'e':'v':'e':'r':'s':'e':rs) = [(Reverse ((read p1) :: Int) ((read p2) :: Int), "")]
where (_:p1:_:p2:_) = words rs
readsPrec _ ('m':'o':'v':'e':rs) = [(Move ((read p1) :: Int) ((read p2) :: Int), "")]
where (_:p1:_:_:p2:_) = words rs
| ajm188/advent_of_code | 2016/21/Operation.hs | Haskell | mit | 2,988 |
module Test where
import Nat
import System.Random (newStdGen, randomRs)
import Tree (FoldTree (..), Tree (..))
tOrder = (5,2,10)
tBits = [15..17]
tFirstNat = fromInteger (5) :: Nat
tSecondNat = fromInteger (7) :: Nat
tContains = [[1..5], [2,0], [3,4]]
tList3 = [1..3] :: [Int]
tTree = Node 3 (Node 1 Leaf Leaf) $ Node 66 (Node 4 Leaf Leaf) Leaf
tFold = Tree 3 (Tree 1 Empty Empty) $ Tree 66 (Tree 4 Empty Empty) Empty
tList5 = [1..5]
tStr = "abc"
tCollect = [1..8]
passTests = [ "1", "1 2 3", " 1", "1 ", "\t1\t", "\t12345\t", "010 020 030"
, " 123 456 789 ", "-1", "-1 -2 -3", "\t-12345\t", " -123 -456 -789 "
, "\n1\t\n3 555 -1\n\n\n-5", "123\t\n\t\n\t\n321 -4 -40"
]
mustFail = ["asd", "1-1", "1.2", "--2", "+1", "1+"]
advancedTests = [ "+1", "1 +1", "-1 +1", "+1 -1"]
advancedMustFail = ["1+1", "++1", "-+1", "+-1", "1 + 1"]
tMerge = [2,1,0,3,10,5]
randomIntList :: Int -> Int -> Int -> IO [Int]
randomIntList n from to = take n . randomRs (from, to) <$> newStdGen
| mortum5/programming | haskell/ITMO-Course/hw1/src/Test.hs | Haskell | mit | 1,068 |
{-# LANGUAGE OverloadedStrings #-}
module Text.Blaze.Bootstrap where
import qualified Text.Blaze.Html5 as BH
import qualified Text.Blaze.Internal as TBI
nav :: BH.Html -- ^ Inner HTML.
-> BH.Html -- ^ Resulting HTML.
nav = TBI.Parent "nav" "<nav" "</nav>"
-- Bootstrap attributes
dataToggle :: BH.AttributeValue -- ^ Attribute value.
-> BH.Attribute -- ^ Resulting attribute.
dataToggle = TBI.customAttribute "data-toggle"
dataTarget :: BH.AttributeValue -- ^ Attribute value.
-> BH.Attribute -- ^ Resulting attribute.
dataTarget = TBI.customAttribute "data-target"
ariaExpanded :: BH.AttributeValue -- ^ Attribute value.
-> BH.Attribute -- ^ Resulting attribute.
ariaExpanded = TBI.customAttribute "aria-expanded"
ariaControls :: BH.AttributeValue -- ^ Attribute value.
-> BH.Attribute -- ^ Resulting attribute.
ariaControls = TBI.customAttribute "aria-controls"
ariaHaspopup :: BH.AttributeValue -- ^ Attribute value.
-> BH.Attribute -- ^ Resulting attribute.
ariaHaspopup = TBI.customAttribute "aria-haspopup"
ariaLabelledby :: BH.AttributeValue -- ^ Attribute value.
-> BH.Attribute -- ^ Resulting attribute.
ariaLabelledby = TBI.customAttribute "aria-labelledby"
role :: BH.AttributeValue -- ^ Attribute value.
-> BH.Attribute -- ^ Resulting attribute.
role = TBI.customAttribute "role"
| lhoghu/happstack | src/Text/Blaze/Bootstrap.hs | Haskell | mit | 1,444 |
module TestHelpers where
import qualified Data.Aeson as AE
import qualified Data.Aeson.Encode.Pretty as AE
import qualified Data.ByteString.Lazy.Char8 as BS
import Data.Maybe (fromJust)
import Data.Text (Text, pack)
import GHC.Generics (Generic)
import Network.JSONApi
import Network.URL (URL, importURL)
prettyEncode :: AE.ToJSON a => a -> BS.ByteString
prettyEncode = AE.encodePretty' prettyConfig
prettyConfig :: AE.Config
prettyConfig = AE.defConfig
{ AE.confIndent = AE.Spaces 2
, AE.confCompare = mempty
}
class HasIdentifiers a where
uniqueId :: a -> Int
typeDescriptor :: a -> Text
data TestResource = TestResource
{ myId :: Int
, myName :: Text
, myAge :: Int
, myFavoriteFood :: Text
} deriving (Show, Generic)
instance AE.ToJSON TestResource
instance AE.FromJSON TestResource
instance ResourcefulEntity TestResource where
resourceIdentifier = pack . show . myId
resourceType _ = "testResource"
resourceLinks _ = Nothing
resourceMetaData _ = Nothing
resourceRelationships _ = Nothing
instance HasIdentifiers TestResource where
uniqueId = myId
typeDescriptor _ = "TestResource"
data OtherTestResource = OtherTestResource
{ myFavoriteNumber :: Int
, myJob :: Text
, myPay :: Int
, myEmployer :: Text
} deriving (Show, Generic)
instance AE.ToJSON OtherTestResource
instance AE.FromJSON OtherTestResource
instance ResourcefulEntity OtherTestResource where
resourceIdentifier = pack . show . myFavoriteNumber
resourceType _ = "otherTestResource"
resourceLinks _ = Nothing
resourceMetaData _ = Nothing
resourceRelationships _ = Nothing
instance HasIdentifiers OtherTestResource where
uniqueId = myFavoriteNumber
typeDescriptor _ = "OtherTestResource"
data TestMetaObject = TestMetaObject
{ totalPages :: Int
, isSuperFun :: Bool
} deriving (Show, Generic)
instance AE.ToJSON TestMetaObject
instance AE.FromJSON TestMetaObject
instance MetaObject TestMetaObject where
typeName _ = "importantData"
toResource' :: (HasIdentifiers a) => a
-> Maybe Links
-> Maybe Meta
-> Resource a
toResource' obj links meta =
Resource
(Identifier (pack . show . uniqueId $ obj) (typeDescriptor obj) meta)
obj
links
Nothing
linksObj :: Links
linksObj = mkLinks [ ("self", toURL "/things/1")
, ("related", toURL "http://some.domain.com/other/things/1")
]
testObject :: TestResource
testObject = TestResource 1 "Fred Armisen" 51 "Pizza"
testObject2 :: TestResource
testObject2 = TestResource 2 "Carrie Brownstein" 35 "Lunch"
otherTestObject :: OtherTestResource
otherTestObject = OtherTestResource 999 "Atom Smasher" 100 "Atom Smashers, Inc"
testMetaObj :: Meta
testMetaObj = mkMeta (TestMetaObject 3 True)
emptyMeta :: Maybe Meta
emptyMeta = Nothing
toURL :: String -> URL
toURL = fromJust . importURL
emptyLinks :: Maybe Links
emptyLinks = Nothing
| toddmohney/json-api | test/TestHelpers.hs | Haskell | mit | 2,915 |
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE RecordWildCards #-}
------------------------------------------------------------------------------
-- |
-- Module : Forecast
-- Copyright : (C) 2014 Samuli Thomasson
-- License : MIT (see the file LICENSE)
-- Maintainer : Samuli Thomasson <[email protected]>
-- Stability : experimental
-- Portability : non-portable
--
-- Regression utilities.
------------------------------------------------------------------------------
module Forecast where
import ZabbixDB (Epoch)
import Control.Applicative
import Control.Arrow
import Control.Monad.State.Strict
import Data.Char (toLower)
import Data.Function
import Data.Aeson.TH
import Data.Vector.Storable (Vector)
import qualified Data.Vector.Storable as V
import qualified Data.Vector as DV
import Data.Text (pack, unpack)
import Database.Persist.Quasi (PersistSettings(psToDBName), lowerCaseSettings)
-- | A simple stateful abstraction
type Predict = StateT (V.Vector Epoch, V.Vector Double) IO
-- | `simpleLinearRegression xs ys` gives (a, b, r2) for the line
-- y = a * x + b.
simpleLinearRegression :: (Eq n, Fractional n, V.Storable n) => Vector n -> Vector n
-> Maybe (n, n, n)
simpleLinearRegression xs ys
| num_x == 0 || num_y == 0 = Nothing
| otherwise = Just (a, b, r2)
where
a = cov_xy / var_x
b = mean_y - a * mean_x
cov_xy = (V.sum (V.zipWith (*) xs ys) / num_x) - mean_x * mean_y
var_x = V.sum (V.map (\x -> (x - mean_x) ^ (2 :: Int)) xs) / num_x
mean_x = V.sum xs / num_x
mean_y = V.sum ys / num_y
num_x = fromIntegral (V.length xs)
num_y = fromIntegral (V.length ys)
r2 = 1 - ss_res / ss_tot
ss_tot = V.sum $ V.map (\y -> (y - mean_y) ^ (2 :: Int)) ys
ss_res = V.sum $ V.zipWith (\x y -> (y - f x) ^ (2 :: Int)) xs ys
f x = a * x + b
-- |
--
-- @
-- y - y0 = a * (x - x0)
-- ==> y = a * x + (y0 - a * x0) = a * x + b'
-- @
drawFuture :: Double -- ^ a
-> Double -- ^ b
-> Maybe (Epoch, Double) -- ^ draw starting at (time, value)
-> V.Vector Epoch -- ^ clocks
-> V.Vector Double
drawFuture a b mlast = V.map (\x -> a * fromIntegral x + b')
where b' = case mlast of
Just (x0, y0) -> y0 - a * fromIntegral x0
Nothing -> b
-- * Filters
data Filter = Filter
{ aggregate :: FilterAggregate
, interval :: Epoch -- ^ seconds; a day an hour...
, intervalStarts :: Epoch }
data FilterAggregate = Max | Min | Avg
applyFilter :: Filter -> Predict ()
applyFilter Filter{..} = do
(clocks, values) <- get
let ixs = DV.map fst $ splittedAt (intervalStarts `rem` interval) interval (V.convert clocks)
slices vs = DV.zipWith (\i j -> DV.slice i (j - i) vs) ixs (DV.tail ixs)
put . (V.convert *** V.convert)
. DV.unzip . DV.map (apply aggregate) . slices
$ DV.zip (V.convert clocks) (V.convert values)
apply aggregate = case aggregate of
Max -> DV.maximumBy (compare `on` snd)
Min -> DV.minimumBy (compare `on` snd)
Avg -> (vectorMedian *** vectorAvg) . DV.unzip
-- | Fold left; accumulate the current index (and timestamp) when day changes.
splittedAt :: Epoch -> Epoch -> DV.Vector Epoch -> DV.Vector (Int, Epoch)
splittedAt start interval =
DV.ifoldl' go <$> DV.singleton . ((0,) . toInterval) . DV.head <*> DV.init
where
go v m c | (_, t) <- DV.last v, t == toInterval c = v
| otherwise = v `DV.snoc` (m, toInterval c)
toInterval = floor . (/ fromIntegral interval) . fromIntegral . (+ start)
maybeDrop vs =
let l = DV.length vs - 1 in
(if snd (vs DV.! 0) + (interval `div` 2) > snd (vs DV.! 1) then DV.tail else id)
. (if snd (vs DV.! (l - 1)) + (interval `div` 2) > snd (vs DV.! l) then DV.init else id)
$ vs
-- * Utility
vectorAvg :: (Real a, Fractional a) => DV.Vector a -> a
vectorAvg v = fromRational $ toRational (DV.sum v) / toRational (DV.length v)
vectorMedian :: DV.Vector a -> a
vectorMedian v = v DV.! floor (fromIntegral (DV.length v) / 2 :: Double)
aesonOptions = defaultOptions
{ fieldLabelModifier = unpack . psToDBName lowerCaseSettings . pack
, constructorTagModifier = map toLower }
| Multi-Axis/habbix | src/Forecast.hs | Haskell | mit | 4,506 |
module Main where
factorial :: Integer -> Integer
factorial x
| x > 1 = x * factorial(x -1)
| otherwise = 1
| mtraina/seven-languages-seven-weeks | week-7-haskell/day1/factorial_with_guards.hs | Haskell | mit | 124 |
import System.IO
import System.Environment
import Paths_hackertyper
main = do
args <- getArgs
let n = if null args then 3 else read (args !! 0) :: Int
hSetBuffering stdout NoBuffering
hSetBuffering stdin NoBuffering
hSetEcho stdin False
kernelPath <- getDataFileName "kernel.txt"
kernel <- readFile kernelPath
putStr "\ESC[2J" --clear the screen
typer n $ concat $ repeat kernel
typer n str = do
getChar
putStr $ take n str
typer n $ drop n str | fgaz/hackertyper | hackertyper.hs | Haskell | mit | 493 |
module Numbering where
import URM
piF m n = 2^m*(2*n+1)-1
xiF m n q = piF (piF (m-1) (n-1)) (q-1)
tauF as = (sum $ map (2^) as)-1
tauF' x = f (x+1) 0 where
f 0 _ = []
f b k | m==0 = r
| m==1 = k:r
where
r = f d (k+1)
(d,m) = b `divMod` 2
betaF (Z n) = 4*(n-1)
betaF (S n) = 4*(n-1)+1
betaF (T m n) = 4*(piF (m-1) (n-1))+2
betaF (J m n q) = 4*(xiF m n q)+3
betaF' x = s r where
s 0 = Z (u+1)
s 1 = S (u+1)
--s 2 = T (pi1F u+1) (pi2F i+1)
--s 3 = J m n q where (m,n,q) = xiF' u
(u,r) = x `divMod` 4
gammaF p = tauF $ map betaF p
| ducis/URMsim | Numbering.hs | Haskell | mit | 567 |
module Ylang.Lexer where
import Text.Parsec.String (Parser)
import Text.Parsec.Language (emptyDef)
import qualified Text.Parsec.Token as Token
lexer :: Token.TokenParser ()
lexer = Token.makeTokenParser style
where
style = emptyDef {
Token.commentLine = commentLine
, Token.reservedOpNames = operators
, Token.reservedNames = keywords
}
commentLine = ";"
operators = ["+", "-", "*", "/", "=", "\\", "->", ",", ".", ":"]
keywords = ["dec", "def", "let", "var"]
integer :: Parser Integer
integer = Token.integer lexer
floating :: Parser Double
floating = Token.float lexer
strings :: Parser String
strings = Token.stringLiteral lexer
charLit :: Parser Char
charLit = Token.charLiteral lexer
parens :: Parser a -> Parser a
parens = Token.parens lexer
brackets :: Parser a -> Parser a
brackets = Token.brackets lexer
reserved :: String -> Parser ()
reserved = Token.reserved lexer
reservedOp :: String -> Parser ()
reservedOp = Token.reservedOp lexer
| VoQn/ylang | Ylang/Lexer.hs | Haskell | apache-2.0 | 1,011 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QGraphicsItem.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:25
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QGraphicsItem (
QqGraphicsItem(..)
,QqGraphicsItem_nf(..)
,children
,qGraphicsItem_delete, qGraphicsItem_delete1
)
where
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Core.Qt
import Qtc.Enums.Gui.QGraphicsItem
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 (QGraphicsItem ()) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsItem_userMethod cobj_qobj (toCInt evid)
foreign import ccall "qtc_QGraphicsItem_userMethod" qtc_QGraphicsItem_userMethod :: Ptr (TQGraphicsItem a) -> CInt -> IO ()
instance QuserMethod (QGraphicsItemSc a) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsItem_userMethod cobj_qobj (toCInt evid)
instance QuserMethod (QGraphicsItem ()) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QGraphicsItem_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
foreign import ccall "qtc_QGraphicsItem_userMethodVariant" qtc_QGraphicsItem_userMethodVariant :: Ptr (TQGraphicsItem a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
instance QuserMethod (QGraphicsItemSc a) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QGraphicsItem_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
class QqGraphicsItem x1 where
qGraphicsItem :: x1 -> IO (QGraphicsItem ())
instance QqGraphicsItem (()) where
qGraphicsItem ()
= withQGraphicsItemResult $
qtc_QGraphicsItem
foreign import ccall "qtc_QGraphicsItem" qtc_QGraphicsItem :: IO (Ptr (TQGraphicsItem ()))
instance QqGraphicsItem ((QGraphicsItem t1)) where
qGraphicsItem (x1)
= withQGraphicsItemResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem1 cobj_x1
foreign import ccall "qtc_QGraphicsItem1" qtc_QGraphicsItem1 :: Ptr (TQGraphicsItem t1) -> IO (Ptr (TQGraphicsItem ()))
instance QqGraphicsItem ((QGraphicsTextItem t1)) where
qGraphicsItem (x1)
= withQGraphicsItemResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem1_graphicstextitem cobj_x1
foreign import ccall "qtc_QGraphicsItem1_graphicstextitem" qtc_QGraphicsItem1_graphicstextitem :: Ptr (TQGraphicsTextItem t1) -> IO (Ptr (TQGraphicsItem ()))
instance QqGraphicsItem ((QGraphicsItem t1, QGraphicsScene t2)) where
qGraphicsItem (x1, x2)
= withQGraphicsItemResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem2 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem2" qtc_QGraphicsItem2 :: Ptr (TQGraphicsItem t1) -> Ptr (TQGraphicsScene t2) -> IO (Ptr (TQGraphicsItem ()))
instance QqGraphicsItem ((QGraphicsTextItem t1, QGraphicsScene t2)) where
qGraphicsItem (x1, x2)
= withQGraphicsItemResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem2_graphicstextitem cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem2_graphicstextitem" qtc_QGraphicsItem2_graphicstextitem :: Ptr (TQGraphicsTextItem t1) -> Ptr (TQGraphicsScene t2) -> IO (Ptr (TQGraphicsItem ()))
class QqGraphicsItem_nf x1 where
qGraphicsItem_nf :: x1 -> IO (QGraphicsItem ())
instance QqGraphicsItem_nf (()) where
qGraphicsItem_nf ()
= withObjectRefResult $
qtc_QGraphicsItem
instance QqGraphicsItem_nf ((QGraphicsItem t1)) where
qGraphicsItem_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem1 cobj_x1
instance QqGraphicsItem_nf ((QGraphicsTextItem t1)) where
qGraphicsItem_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem1_graphicstextitem cobj_x1
instance QqGraphicsItem_nf ((QGraphicsItem t1, QGraphicsScene t2)) where
qGraphicsItem_nf (x1, x2)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem2 cobj_x1 cobj_x2
instance QqGraphicsItem_nf ((QGraphicsTextItem t1, QGraphicsScene t2)) where
qGraphicsItem_nf (x1, x2)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem2_graphicstextitem cobj_x1 cobj_x2
instance QacceptDrops (QGraphicsItem a) (()) where
acceptDrops x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_acceptDrops cobj_x0
foreign import ccall "qtc_QGraphicsItem_acceptDrops" qtc_QGraphicsItem_acceptDrops :: Ptr (TQGraphicsItem a) -> IO CBool
instance QacceptedMouseButtons (QGraphicsItem a) (()) where
acceptedMouseButtons x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_acceptedMouseButtons cobj_x0
foreign import ccall "qtc_QGraphicsItem_acceptedMouseButtons" qtc_QGraphicsItem_acceptedMouseButtons :: Ptr (TQGraphicsItem a) -> IO CLong
instance QacceptsHoverEvents (QGraphicsItem a) (()) where
acceptsHoverEvents x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_acceptsHoverEvents cobj_x0
foreign import ccall "qtc_QGraphicsItem_acceptsHoverEvents" qtc_QGraphicsItem_acceptsHoverEvents :: Ptr (TQGraphicsItem a) -> IO CBool
instance QaddToIndex (QGraphicsItem ()) (()) where
addToIndex x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_addToIndex cobj_x0
foreign import ccall "qtc_QGraphicsItem_addToIndex" qtc_QGraphicsItem_addToIndex :: Ptr (TQGraphicsItem a) -> IO ()
instance QaddToIndex (QGraphicsItemSc a) (()) where
addToIndex x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_addToIndex cobj_x0
instance Qadvance (QGraphicsItem ()) ((Int)) where
advance x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_advance_h cobj_x0 (toCInt x1)
foreign import ccall "qtc_QGraphicsItem_advance_h" qtc_QGraphicsItem_advance_h :: Ptr (TQGraphicsItem a) -> CInt -> IO ()
instance Qadvance (QGraphicsItemSc a) ((Int)) where
advance x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_advance_h cobj_x0 (toCInt x1)
instance QqqboundingRect (QGraphicsItem ()) (()) (IO (QRectF ())) where
qqboundingRect x0 ()
= withQRectFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_boundingRect_h cobj_x0
foreign import ccall "qtc_QGraphicsItem_boundingRect_h" qtc_QGraphicsItem_boundingRect_h :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQRectF ()))
instance QqqboundingRect (QGraphicsItemSc a) (()) (IO (QRectF ())) where
qqboundingRect x0 ()
= withQRectFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_boundingRect_h cobj_x0
instance QqboundingRect (QGraphicsItem ()) (()) (IO (RectF)) where
qboundingRect x0 ()
= withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_boundingRect_qth_h cobj_x0 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h
foreign import ccall "qtc_QGraphicsItem_boundingRect_qth_h" qtc_QGraphicsItem_boundingRect_qth_h :: Ptr (TQGraphicsItem a) -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QqboundingRect (QGraphicsItemSc a) (()) (IO (RectF)) where
qboundingRect x0 ()
= withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_boundingRect_qth_h cobj_x0 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h
children :: QGraphicsItem a -> (()) -> IO ([QGraphicsItem ()])
children x0 ()
= withQListObjectRefResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_children cobj_x0 arr
foreign import ccall "qtc_QGraphicsItem_children" qtc_QGraphicsItem_children :: Ptr (TQGraphicsItem a) -> Ptr (Ptr (TQGraphicsItem ())) -> IO CInt
instance QqchildrenBoundingRect (QGraphicsItem a) (()) where
qchildrenBoundingRect x0 ()
= withQRectFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_childrenBoundingRect cobj_x0
foreign import ccall "qtc_QGraphicsItem_childrenBoundingRect" qtc_QGraphicsItem_childrenBoundingRect :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQRectF ()))
instance QchildrenBoundingRect (QGraphicsItem a) (()) where
childrenBoundingRect x0 ()
= withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_childrenBoundingRect_qth cobj_x0 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h
foreign import ccall "qtc_QGraphicsItem_childrenBoundingRect_qth" qtc_QGraphicsItem_childrenBoundingRect_qth :: Ptr (TQGraphicsItem a) -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QclearFocus (QGraphicsItem a) (()) where
clearFocus x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_clearFocus cobj_x0
foreign import ccall "qtc_QGraphicsItem_clearFocus" qtc_QGraphicsItem_clearFocus :: Ptr (TQGraphicsItem a) -> IO ()
instance QcollidesWithItem (QGraphicsItem ()) ((QGraphicsItem t1)) where
collidesWithItem x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_collidesWithItem_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_collidesWithItem_h" qtc_QGraphicsItem_collidesWithItem_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> IO CBool
instance QcollidesWithItem (QGraphicsItemSc a) ((QGraphicsItem t1)) where
collidesWithItem x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_collidesWithItem_h cobj_x0 cobj_x1
instance QcollidesWithItem (QGraphicsItem ()) ((QGraphicsItem t1, ItemSelectionMode)) where
collidesWithItem x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_collidesWithItem1_h cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QGraphicsItem_collidesWithItem1_h" qtc_QGraphicsItem_collidesWithItem1_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> CLong -> IO CBool
instance QcollidesWithItem (QGraphicsItemSc a) ((QGraphicsItem t1, ItemSelectionMode)) where
collidesWithItem x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_collidesWithItem1_h cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QcollidesWithItem (QGraphicsItem ()) ((QGraphicsTextItem t1)) where
collidesWithItem x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_collidesWithItem_graphicstextitem_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_collidesWithItem_graphicstextitem_h" qtc_QGraphicsItem_collidesWithItem_graphicstextitem_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> IO CBool
instance QcollidesWithItem (QGraphicsItemSc a) ((QGraphicsTextItem t1)) where
collidesWithItem x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_collidesWithItem_graphicstextitem_h cobj_x0 cobj_x1
instance QcollidesWithItem (QGraphicsItem ()) ((QGraphicsTextItem t1, ItemSelectionMode)) where
collidesWithItem x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_collidesWithItem1_graphicstextitem_h cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QGraphicsItem_collidesWithItem1_graphicstextitem_h" qtc_QGraphicsItem_collidesWithItem1_graphicstextitem_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> CLong -> IO CBool
instance QcollidesWithItem (QGraphicsItemSc a) ((QGraphicsTextItem t1, ItemSelectionMode)) where
collidesWithItem x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_collidesWithItem1_graphicstextitem_h cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QcollidesWithPath (QGraphicsItem ()) ((QPainterPath t1)) where
collidesWithPath x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_collidesWithPath_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_collidesWithPath_h" qtc_QGraphicsItem_collidesWithPath_h :: Ptr (TQGraphicsItem a) -> Ptr (TQPainterPath t1) -> IO CBool
instance QcollidesWithPath (QGraphicsItemSc a) ((QPainterPath t1)) where
collidesWithPath x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_collidesWithPath_h cobj_x0 cobj_x1
instance QcollidesWithPath (QGraphicsItem ()) ((QPainterPath t1, ItemSelectionMode)) where
collidesWithPath x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_collidesWithPath1_h cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QGraphicsItem_collidesWithPath1_h" qtc_QGraphicsItem_collidesWithPath1_h :: Ptr (TQGraphicsItem a) -> Ptr (TQPainterPath t1) -> CLong -> IO CBool
instance QcollidesWithPath (QGraphicsItemSc a) ((QPainterPath t1, ItemSelectionMode)) where
collidesWithPath x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_collidesWithPath1_h cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QcollidingItems (QGraphicsItem a) (()) where
collidingItems x0 ()
= withQListObjectRefResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_collidingItems cobj_x0 arr
foreign import ccall "qtc_QGraphicsItem_collidingItems" qtc_QGraphicsItem_collidingItems :: Ptr (TQGraphicsItem a) -> Ptr (Ptr (TQGraphicsItem ())) -> IO CInt
instance QcollidingItems (QGraphicsItem a) ((ItemSelectionMode)) where
collidingItems x0 (x1)
= withQListObjectRefResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_collidingItems1 cobj_x0 (toCLong $ qEnum_toInt x1) arr
foreign import ccall "qtc_QGraphicsItem_collidingItems1" qtc_QGraphicsItem_collidingItems1 :: Ptr (TQGraphicsItem a) -> CLong -> Ptr (Ptr (TQGraphicsItem ())) -> IO CInt
instance Qqcontains (QGraphicsItem ()) ((PointF)) where
qcontains x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QGraphicsItem_contains_qth_h cobj_x0 cpointf_x1_x cpointf_x1_y
foreign import ccall "qtc_QGraphicsItem_contains_qth_h" qtc_QGraphicsItem_contains_qth_h :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> IO CBool
instance Qqcontains (QGraphicsItemSc a) ((PointF)) where
qcontains x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QGraphicsItem_contains_qth_h cobj_x0 cpointf_x1_x cpointf_x1_y
instance Qqqcontains (QGraphicsItem ()) ((QPointF t1)) where
qqcontains x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_contains_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_contains_h" qtc_QGraphicsItem_contains_h :: Ptr (TQGraphicsItem a) -> Ptr (TQPointF t1) -> IO CBool
instance Qqqcontains (QGraphicsItemSc a) ((QPointF t1)) where
qqcontains x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_contains_h cobj_x0 cobj_x1
instance QcontextMenuEvent (QGraphicsItem ()) ((QGraphicsSceneContextMenuEvent t1)) where
contextMenuEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_contextMenuEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_contextMenuEvent_h" qtc_QGraphicsItem_contextMenuEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsSceneContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent (QGraphicsItemSc a) ((QGraphicsSceneContextMenuEvent t1)) where
contextMenuEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_contextMenuEvent_h cobj_x0 cobj_x1
instance Qcursor (QGraphicsItem a) (()) where
cursor x0 ()
= withQCursorResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_cursor cobj_x0
foreign import ccall "qtc_QGraphicsItem_cursor" qtc_QGraphicsItem_cursor :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQCursor ()))
instance Qqdata (QGraphicsItem ()) ((Int)) (IO (QVariant ())) where
qdata x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_data cobj_x0 (toCInt x1)
foreign import ccall "qtc_QGraphicsItem_data" qtc_QGraphicsItem_data :: Ptr (TQGraphicsItem a) -> CInt -> IO (Ptr (TQVariant ()))
instance Qqdata (QGraphicsItemSc a) ((Int)) (IO (QVariant ())) where
qdata x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_data cobj_x0 (toCInt x1)
instance Qqdata_nf (QGraphicsItem ()) ((Int)) (IO (QVariant ())) where
qdata_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_data cobj_x0 (toCInt x1)
instance Qqdata_nf (QGraphicsItemSc a) ((Int)) (IO (QVariant ())) where
qdata_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_data cobj_x0 (toCInt x1)
instance QdeviceTransform (QGraphicsItem a) ((QTransform t1)) where
deviceTransform x0 (x1)
= withQTransformResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_deviceTransform cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_deviceTransform" qtc_QGraphicsItem_deviceTransform :: Ptr (TQGraphicsItem a) -> Ptr (TQTransform t1) -> IO (Ptr (TQTransform ()))
instance QdragEnterEvent (QGraphicsItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dragEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_dragEnterEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_dragEnterEvent_h" qtc_QGraphicsItem_dragEnterEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdragEnterEvent (QGraphicsItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dragEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_dragEnterEvent_h cobj_x0 cobj_x1
instance QdragLeaveEvent (QGraphicsItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dragLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_dragLeaveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_dragLeaveEvent_h" qtc_QGraphicsItem_dragLeaveEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdragLeaveEvent (QGraphicsItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dragLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_dragLeaveEvent_h cobj_x0 cobj_x1
instance QdragMoveEvent (QGraphicsItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dragMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_dragMoveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_dragMoveEvent_h" qtc_QGraphicsItem_dragMoveEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdragMoveEvent (QGraphicsItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dragMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_dragMoveEvent_h cobj_x0 cobj_x1
instance QdropEvent (QGraphicsItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dropEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_dropEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_dropEvent_h" qtc_QGraphicsItem_dropEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdropEvent (QGraphicsItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dropEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_dropEvent_h cobj_x0 cobj_x1
instance QensureVisible (QGraphicsItem a) (()) where
ensureVisible x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_ensureVisible cobj_x0
foreign import ccall "qtc_QGraphicsItem_ensureVisible" qtc_QGraphicsItem_ensureVisible :: Ptr (TQGraphicsItem a) -> IO ()
instance QensureVisible (QGraphicsItem a) ((Double, Double, Double, Double)) where
ensureVisible x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_ensureVisible4 cobj_x0 (toCDouble x1) (toCDouble x2) (toCDouble x3) (toCDouble x4)
foreign import ccall "qtc_QGraphicsItem_ensureVisible4" qtc_QGraphicsItem_ensureVisible4 :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> IO ()
instance QensureVisible (QGraphicsItem a) ((Double, Double, Double, Double, Int)) where
ensureVisible x0 (x1, x2, x3, x4, x5)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_ensureVisible5 cobj_x0 (toCDouble x1) (toCDouble x2) (toCDouble x3) (toCDouble x4) (toCInt x5)
foreign import ccall "qtc_QGraphicsItem_ensureVisible5" qtc_QGraphicsItem_ensureVisible5 :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> CInt -> IO ()
instance QensureVisible (QGraphicsItem a) ((Double, Double, Double, Double, Int, Int)) where
ensureVisible x0 (x1, x2, x3, x4, x5, x6)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_ensureVisible6 cobj_x0 (toCDouble x1) (toCDouble x2) (toCDouble x3) (toCDouble x4) (toCInt x5) (toCInt x6)
foreign import ccall "qtc_QGraphicsItem_ensureVisible6" qtc_QGraphicsItem_ensureVisible6 :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> CInt -> CInt -> IO ()
instance QqensureVisible (QGraphicsItem a) ((QRectF t1)) where
qensureVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_ensureVisible1 cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_ensureVisible1" qtc_QGraphicsItem_ensureVisible1 :: Ptr (TQGraphicsItem a) -> Ptr (TQRectF t1) -> IO ()
instance QqensureVisible (QGraphicsItem a) ((QRectF t1, Int)) where
qensureVisible x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_ensureVisible2 cobj_x0 cobj_x1 (toCInt x2)
foreign import ccall "qtc_QGraphicsItem_ensureVisible2" qtc_QGraphicsItem_ensureVisible2 :: Ptr (TQGraphicsItem a) -> Ptr (TQRectF t1) -> CInt -> IO ()
instance QqensureVisible (QGraphicsItem a) ((QRectF t1, Int, Int)) where
qensureVisible x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_ensureVisible3 cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QGraphicsItem_ensureVisible3" qtc_QGraphicsItem_ensureVisible3 :: Ptr (TQGraphicsItem a) -> Ptr (TQRectF t1) -> CInt -> CInt -> IO ()
instance QensureVisible (QGraphicsItem a) ((RectF)) where
ensureVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRectF x1 $ \crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h ->
qtc_QGraphicsItem_ensureVisible1_qth cobj_x0 crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h
foreign import ccall "qtc_QGraphicsItem_ensureVisible1_qth" qtc_QGraphicsItem_ensureVisible1_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> IO ()
instance QensureVisible (QGraphicsItem a) ((RectF, Int)) where
ensureVisible x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withCRectF x1 $ \crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h ->
qtc_QGraphicsItem_ensureVisible2_qth cobj_x0 crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h (toCInt x2)
foreign import ccall "qtc_QGraphicsItem_ensureVisible2_qth" qtc_QGraphicsItem_ensureVisible2_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> CInt -> IO ()
instance QensureVisible (QGraphicsItem a) ((RectF, Int, Int)) where
ensureVisible x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withCRectF x1 $ \crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h ->
qtc_QGraphicsItem_ensureVisible3_qth cobj_x0 crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QGraphicsItem_ensureVisible3_qth" qtc_QGraphicsItem_ensureVisible3_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> CInt -> CInt -> IO ()
instance Qextension (QGraphicsItem ()) ((QVariant t1)) (IO (QVariant ())) where
extension x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_extension cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_extension" qtc_QGraphicsItem_extension :: Ptr (TQGraphicsItem a) -> Ptr (TQVariant t1) -> IO (Ptr (TQVariant ()))
instance Qextension (QGraphicsItemSc a) ((QVariant t1)) (IO (QVariant ())) where
extension x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_extension cobj_x0 cobj_x1
instance Qflags (QGraphicsItem a) (()) (IO (GraphicsItemFlags)) where
flags x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_flags cobj_x0
foreign import ccall "qtc_QGraphicsItem_flags" qtc_QGraphicsItem_flags :: Ptr (TQGraphicsItem a) -> IO CLong
instance QfocusInEvent (QGraphicsItem ()) ((QFocusEvent t1)) where
focusInEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_focusInEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_focusInEvent_h" qtc_QGraphicsItem_focusInEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent (QGraphicsItemSc a) ((QFocusEvent t1)) where
focusInEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_focusInEvent_h cobj_x0 cobj_x1
instance QfocusOutEvent (QGraphicsItem ()) ((QFocusEvent t1)) where
focusOutEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_focusOutEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_focusOutEvent_h" qtc_QGraphicsItem_focusOutEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent (QGraphicsItemSc a) ((QFocusEvent t1)) where
focusOutEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_focusOutEvent_h cobj_x0 cobj_x1
instance Qgroup (QGraphicsItem a) (()) (IO (QGraphicsItemGroup ())) where
group x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_group cobj_x0
foreign import ccall "qtc_QGraphicsItem_group" qtc_QGraphicsItem_group :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQGraphicsItemGroup ()))
instance QhandlesChildEvents (QGraphicsItem a) (()) where
handlesChildEvents x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_handlesChildEvents cobj_x0
foreign import ccall "qtc_QGraphicsItem_handlesChildEvents" qtc_QGraphicsItem_handlesChildEvents :: Ptr (TQGraphicsItem a) -> IO CBool
instance QhasCursor (QGraphicsItem a) (()) where
hasCursor x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_hasCursor cobj_x0
foreign import ccall "qtc_QGraphicsItem_hasCursor" qtc_QGraphicsItem_hasCursor :: Ptr (TQGraphicsItem a) -> IO CBool
instance QhasFocus (QGraphicsItem a) (()) where
hasFocus x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_hasFocus cobj_x0
foreign import ccall "qtc_QGraphicsItem_hasFocus" qtc_QGraphicsItem_hasFocus :: Ptr (TQGraphicsItem a) -> IO CBool
instance Qhide (QGraphicsItem a) (()) where
hide x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_hide cobj_x0
foreign import ccall "qtc_QGraphicsItem_hide" qtc_QGraphicsItem_hide :: Ptr (TQGraphicsItem a) -> IO ()
instance QhoverEnterEvent (QGraphicsItem ()) ((QGraphicsSceneHoverEvent t1)) where
hoverEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_hoverEnterEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_hoverEnterEvent_h" qtc_QGraphicsItem_hoverEnterEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO ()
instance QhoverEnterEvent (QGraphicsItemSc a) ((QGraphicsSceneHoverEvent t1)) where
hoverEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_hoverEnterEvent_h cobj_x0 cobj_x1
instance QhoverLeaveEvent (QGraphicsItem ()) ((QGraphicsSceneHoverEvent t1)) where
hoverLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_hoverLeaveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_hoverLeaveEvent_h" qtc_QGraphicsItem_hoverLeaveEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO ()
instance QhoverLeaveEvent (QGraphicsItemSc a) ((QGraphicsSceneHoverEvent t1)) where
hoverLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_hoverLeaveEvent_h cobj_x0 cobj_x1
instance QhoverMoveEvent (QGraphicsItem ()) ((QGraphicsSceneHoverEvent t1)) where
hoverMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_hoverMoveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_hoverMoveEvent_h" qtc_QGraphicsItem_hoverMoveEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO ()
instance QhoverMoveEvent (QGraphicsItemSc a) ((QGraphicsSceneHoverEvent t1)) where
hoverMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_hoverMoveEvent_h cobj_x0 cobj_x1
instance QinputMethodEvent (QGraphicsItem ()) ((QInputMethodEvent t1)) where
inputMethodEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_inputMethodEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_inputMethodEvent_h" qtc_QGraphicsItem_inputMethodEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQInputMethodEvent t1) -> IO ()
instance QinputMethodEvent (QGraphicsItemSc a) ((QInputMethodEvent t1)) where
inputMethodEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_inputMethodEvent_h cobj_x0 cobj_x1
instance QinputMethodQuery (QGraphicsItem ()) ((InputMethodQuery)) where
inputMethodQuery x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QGraphicsItem_inputMethodQuery_h" qtc_QGraphicsItem_inputMethodQuery_h :: Ptr (TQGraphicsItem a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery (QGraphicsItemSc a) ((InputMethodQuery)) where
inputMethodQuery x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1)
instance QinstallSceneEventFilter (QGraphicsItem a) ((QGraphicsItem t1)) where
installSceneEventFilter x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_installSceneEventFilter cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_installSceneEventFilter" qtc_QGraphicsItem_installSceneEventFilter :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> IO ()
instance QinstallSceneEventFilter (QGraphicsItem a) ((QGraphicsTextItem t1)) where
installSceneEventFilter x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_installSceneEventFilter_graphicstextitem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_installSceneEventFilter_graphicstextitem" qtc_QGraphicsItem_installSceneEventFilter_graphicstextitem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> IO ()
instance QisAncestorOf (QGraphicsItem a) ((QGraphicsItem t1)) where
isAncestorOf x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_isAncestorOf cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_isAncestorOf" qtc_QGraphicsItem_isAncestorOf :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> IO CBool
instance QisAncestorOf (QGraphicsItem a) ((QGraphicsTextItem t1)) where
isAncestorOf x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_isAncestorOf_graphicstextitem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_isAncestorOf_graphicstextitem" qtc_QGraphicsItem_isAncestorOf_graphicstextitem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> IO CBool
instance QisEnabled (QGraphicsItem a) (()) where
isEnabled x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_isEnabled cobj_x0
foreign import ccall "qtc_QGraphicsItem_isEnabled" qtc_QGraphicsItem_isEnabled :: Ptr (TQGraphicsItem a) -> IO CBool
instance QisObscured (QGraphicsItem a) (()) where
isObscured x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_isObscured cobj_x0
foreign import ccall "qtc_QGraphicsItem_isObscured" qtc_QGraphicsItem_isObscured :: Ptr (TQGraphicsItem a) -> IO CBool
instance QisObscured (QGraphicsItem a) ((Double, Double, Double, Double)) where
isObscured x0 (x1, x2, x3, x4)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_isObscured2 cobj_x0 (toCDouble x1) (toCDouble x2) (toCDouble x3) (toCDouble x4)
foreign import ccall "qtc_QGraphicsItem_isObscured2" qtc_QGraphicsItem_isObscured2 :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> IO CBool
instance QqisObscured (QGraphicsItem a) ((QRectF t1)) where
qisObscured x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_isObscured1 cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_isObscured1" qtc_QGraphicsItem_isObscured1 :: Ptr (TQGraphicsItem a) -> Ptr (TQRectF t1) -> IO CBool
instance QisObscured (QGraphicsItem a) ((RectF)) where
isObscured x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCRectF x1 $ \crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h ->
qtc_QGraphicsItem_isObscured1_qth cobj_x0 crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h
foreign import ccall "qtc_QGraphicsItem_isObscured1_qth" qtc_QGraphicsItem_isObscured1_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> IO CBool
instance QisObscuredBy (QGraphicsItem ()) ((QGraphicsItem t1)) where
isObscuredBy x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_isObscuredBy_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_isObscuredBy_h" qtc_QGraphicsItem_isObscuredBy_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> IO CBool
instance QisObscuredBy (QGraphicsItemSc a) ((QGraphicsItem t1)) where
isObscuredBy x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_isObscuredBy_h cobj_x0 cobj_x1
instance QisObscuredBy (QGraphicsItem ()) ((QGraphicsTextItem t1)) where
isObscuredBy x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_isObscuredBy_graphicstextitem_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_isObscuredBy_graphicstextitem_h" qtc_QGraphicsItem_isObscuredBy_graphicstextitem_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> IO CBool
instance QisObscuredBy (QGraphicsItemSc a) ((QGraphicsTextItem t1)) where
isObscuredBy x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_isObscuredBy_graphicstextitem_h cobj_x0 cobj_x1
instance QisSelected (QGraphicsItem a) (()) where
isSelected x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_isSelected cobj_x0
foreign import ccall "qtc_QGraphicsItem_isSelected" qtc_QGraphicsItem_isSelected :: Ptr (TQGraphicsItem a) -> IO CBool
instance QisVisible (QGraphicsItem a) (()) where
isVisible x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_isVisible cobj_x0
foreign import ccall "qtc_QGraphicsItem_isVisible" qtc_QGraphicsItem_isVisible :: Ptr (TQGraphicsItem a) -> IO CBool
instance QitemChange (QGraphicsItem ()) ((GraphicsItemChange, QVariant t2)) where
itemChange x0 (x1, x2)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_itemChange_h cobj_x0 (toCLong $ qEnum_toInt x1) cobj_x2
foreign import ccall "qtc_QGraphicsItem_itemChange_h" qtc_QGraphicsItem_itemChange_h :: Ptr (TQGraphicsItem a) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant ()))
instance QitemChange (QGraphicsItemSc a) ((GraphicsItemChange, QVariant t2)) where
itemChange x0 (x1, x2)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_itemChange_h cobj_x0 (toCLong $ qEnum_toInt x1) cobj_x2
instance QkeyPressEvent (QGraphicsItem ()) ((QKeyEvent t1)) where
keyPressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_keyPressEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_keyPressEvent_h" qtc_QGraphicsItem_keyPressEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent (QGraphicsItemSc a) ((QKeyEvent t1)) where
keyPressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_keyPressEvent_h cobj_x0 cobj_x1
instance QkeyReleaseEvent (QGraphicsItem ()) ((QKeyEvent t1)) where
keyReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_keyReleaseEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_keyReleaseEvent_h" qtc_QGraphicsItem_keyReleaseEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent (QGraphicsItemSc a) ((QKeyEvent t1)) where
keyReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_keyReleaseEvent_h cobj_x0 cobj_x1
instance QmapFromItem (QGraphicsItem a) ((QGraphicsItem t1, Double, Double)) (IO (PointF)) where
mapFromItem x0 (x1, x2, x3)
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapFromItem4_qth cobj_x0 cobj_x1 (toCDouble x2) (toCDouble x3) cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_mapFromItem4_qth" qtc_QGraphicsItem_mapFromItem4_qth :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> CDouble -> CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QmapFromItem (QGraphicsItem a) ((QGraphicsItem t1, PointF)) (IO (PointF)) where
mapFromItem x0 (x1, x2)
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCPointF x2 $ \cpointf_x2_x cpointf_x2_y ->
qtc_QGraphicsItem_mapFromItem2_qth cobj_x0 cobj_x1 cpointf_x2_x cpointf_x2_y cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_mapFromItem2_qth" qtc_QGraphicsItem_mapFromItem2_qth :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> CDouble -> CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QmapFromItem (QGraphicsItem a) ((QGraphicsTextItem t1, Double, Double)) (IO (PointF)) where
mapFromItem x0 (x1, x2, x3)
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapFromItem4_graphicstextitem_qth cobj_x0 cobj_x1 (toCDouble x2) (toCDouble x3) cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_mapFromItem4_graphicstextitem_qth" qtc_QGraphicsItem_mapFromItem4_graphicstextitem_qth :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> CDouble -> CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QmapFromItem (QGraphicsItem a) ((QGraphicsTextItem t1, PointF)) (IO (PointF)) where
mapFromItem x0 (x1, x2)
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCPointF x2 $ \cpointf_x2_x cpointf_x2_y ->
qtc_QGraphicsItem_mapFromItem2_graphicstextitem_qth cobj_x0 cobj_x1 cpointf_x2_x cpointf_x2_y cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_mapFromItem2_graphicstextitem_qth" qtc_QGraphicsItem_mapFromItem2_graphicstextitem_qth :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> CDouble -> CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QmapFromItem (QGraphicsItem a) ((QGraphicsItem t1, QPainterPath t2)) (IO (QPainterPath ())) where
mapFromItem x0 (x1, x2)
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_mapFromItem3 cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_mapFromItem3" qtc_QGraphicsItem_mapFromItem3 :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> Ptr (TQPainterPath t2) -> IO (Ptr (TQPainterPath ()))
instance QmapFromItem (QGraphicsItem a) ((QGraphicsTextItem t1, QPainterPath t2)) (IO (QPainterPath ())) where
mapFromItem x0 (x1, x2)
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_mapFromItem3_graphicstextitem cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_mapFromItem3_graphicstextitem" qtc_QGraphicsItem_mapFromItem3_graphicstextitem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> Ptr (TQPainterPath t2) -> IO (Ptr (TQPainterPath ()))
instance QqmapFromItem (QGraphicsItem a) ((QGraphicsItem t1, Double, Double)) (IO (QPointF ())) where
qmapFromItem x0 (x1, x2, x3)
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapFromItem4 cobj_x0 cobj_x1 (toCDouble x2) (toCDouble x3)
foreign import ccall "qtc_QGraphicsItem_mapFromItem4" qtc_QGraphicsItem_mapFromItem4 :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> CDouble -> CDouble -> IO (Ptr (TQPointF ()))
instance QqmapFromItem (QGraphicsItem a) ((QGraphicsItem t1, QPointF t2)) (IO (QPointF ())) where
qmapFromItem x0 (x1, x2)
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_mapFromItem2 cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_mapFromItem2" qtc_QGraphicsItem_mapFromItem2 :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> Ptr (TQPointF t2) -> IO (Ptr (TQPointF ()))
instance QqmapFromItem (QGraphicsItem a) ((QGraphicsTextItem t1, Double, Double)) (IO (QPointF ())) where
qmapFromItem x0 (x1, x2, x3)
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapFromItem4_graphicstextitem cobj_x0 cobj_x1 (toCDouble x2) (toCDouble x3)
foreign import ccall "qtc_QGraphicsItem_mapFromItem4_graphicstextitem" qtc_QGraphicsItem_mapFromItem4_graphicstextitem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> CDouble -> CDouble -> IO (Ptr (TQPointF ()))
instance QqmapFromItem (QGraphicsItem a) ((QGraphicsTextItem t1, QPointF t2)) (IO (QPointF ())) where
qmapFromItem x0 (x1, x2)
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_mapFromItem2_graphicstextitem cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_mapFromItem2_graphicstextitem" qtc_QGraphicsItem_mapFromItem2_graphicstextitem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> Ptr (TQPointF t2) -> IO (Ptr (TQPointF ()))
instance QmapFromItem (QGraphicsItem a) ((QGraphicsItem t1, Double, Double, Double, Double)) (IO (QPolygonF ())) where
mapFromItem x0 (x1, x2, x3, x4, x5)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapFromItem5 cobj_x0 cobj_x1 (toCDouble x2) (toCDouble x3) (toCDouble x4) (toCDouble x5)
foreign import ccall "qtc_QGraphicsItem_mapFromItem5" qtc_QGraphicsItem_mapFromItem5 :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQPolygonF ()))
instance QmapFromItem (QGraphicsItem a) ((QGraphicsItem t1, QPolygonF t2)) (IO (QPolygonF ())) where
mapFromItem x0 (x1, x2)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_mapFromItem1 cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_mapFromItem1" qtc_QGraphicsItem_mapFromItem1 :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> Ptr (TQPolygonF t2) -> IO (Ptr (TQPolygonF ()))
instance QqmapFromItem (QGraphicsItem a) ((QGraphicsItem t1, QRectF t2)) (IO (QPolygonF ())) where
qmapFromItem x0 (x1, x2)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_mapFromItem cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_mapFromItem" qtc_QGraphicsItem_mapFromItem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> Ptr (TQRectF t2) -> IO (Ptr (TQPolygonF ()))
instance QmapFromItem (QGraphicsItem a) ((QGraphicsItem t1, RectF)) (IO (QPolygonF ())) where
mapFromItem x0 (x1, x2)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCRectF x2 $ \crectf_x2_x crectf_x2_y crectf_x2_w crectf_x2_h ->
qtc_QGraphicsItem_mapFromItem_qth cobj_x0 cobj_x1 crectf_x2_x crectf_x2_y crectf_x2_w crectf_x2_h
foreign import ccall "qtc_QGraphicsItem_mapFromItem_qth" qtc_QGraphicsItem_mapFromItem_qth :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQPolygonF ()))
instance QmapFromItem (QGraphicsItem a) ((QGraphicsTextItem t1, Double, Double, Double, Double)) (IO (QPolygonF ())) where
mapFromItem x0 (x1, x2, x3, x4, x5)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapFromItem5_graphicstextitem cobj_x0 cobj_x1 (toCDouble x2) (toCDouble x3) (toCDouble x4) (toCDouble x5)
foreign import ccall "qtc_QGraphicsItem_mapFromItem5_graphicstextitem" qtc_QGraphicsItem_mapFromItem5_graphicstextitem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQPolygonF ()))
instance QmapFromItem (QGraphicsItem a) ((QGraphicsTextItem t1, QPolygonF t2)) (IO (QPolygonF ())) where
mapFromItem x0 (x1, x2)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_mapFromItem1_graphicstextitem cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_mapFromItem1_graphicstextitem" qtc_QGraphicsItem_mapFromItem1_graphicstextitem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> Ptr (TQPolygonF t2) -> IO (Ptr (TQPolygonF ()))
instance QqmapFromItem (QGraphicsItem a) ((QGraphicsTextItem t1, QRectF t2)) (IO (QPolygonF ())) where
qmapFromItem x0 (x1, x2)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_mapFromItem_graphicstextitem cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_mapFromItem_graphicstextitem" qtc_QGraphicsItem_mapFromItem_graphicstextitem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> Ptr (TQRectF t2) -> IO (Ptr (TQPolygonF ()))
instance QmapFromItem (QGraphicsItem a) ((QGraphicsTextItem t1, RectF)) (IO (QPolygonF ())) where
mapFromItem x0 (x1, x2)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCRectF x2 $ \crectf_x2_x crectf_x2_y crectf_x2_w crectf_x2_h ->
qtc_QGraphicsItem_mapFromItem_graphicstextitem_qth cobj_x0 cobj_x1 crectf_x2_x crectf_x2_y crectf_x2_w crectf_x2_h
foreign import ccall "qtc_QGraphicsItem_mapFromItem_graphicstextitem_qth" qtc_QGraphicsItem_mapFromItem_graphicstextitem_qth :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQPolygonF ()))
instance QmapFromParent (QGraphicsItem a) ((Double, Double)) (IO (PointF)) where
mapFromParent x0 (x1, x2)
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_mapFromParent4_qth cobj_x0 (toCDouble x1) (toCDouble x2) cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_mapFromParent4_qth" qtc_QGraphicsItem_mapFromParent4_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QmapFromParent (QGraphicsItem a) ((PointF)) (IO (PointF)) where
mapFromParent x0 (x1)
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QGraphicsItem_mapFromParent1_qth cobj_x0 cpointf_x1_x cpointf_x1_y cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_mapFromParent1_qth" qtc_QGraphicsItem_mapFromParent1_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QmapFromParent (QGraphicsItem a) ((QPainterPath t1)) (IO (QPainterPath ())) where
mapFromParent x0 (x1)
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapFromParent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mapFromParent" qtc_QGraphicsItem_mapFromParent :: Ptr (TQGraphicsItem a) -> Ptr (TQPainterPath t1) -> IO (Ptr (TQPainterPath ()))
instance QqmapFromParent (QGraphicsItem a) ((Double, Double)) (IO (QPointF ())) where
qmapFromParent x0 (x1, x2)
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_mapFromParent4 cobj_x0 (toCDouble x1) (toCDouble x2)
foreign import ccall "qtc_QGraphicsItem_mapFromParent4" qtc_QGraphicsItem_mapFromParent4 :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> IO (Ptr (TQPointF ()))
instance QqmapFromParent (QGraphicsItem a) ((QPointF t1)) (IO (QPointF ())) where
qmapFromParent x0 (x1)
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapFromParent1 cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mapFromParent1" qtc_QGraphicsItem_mapFromParent1 :: Ptr (TQGraphicsItem a) -> Ptr (TQPointF t1) -> IO (Ptr (TQPointF ()))
instance QmapFromParent (QGraphicsItem a) ((Double, Double, Double, Double)) (IO (QPolygonF ())) where
mapFromParent x0 (x1, x2, x3, x4)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_mapFromParent5 cobj_x0 (toCDouble x1) (toCDouble x2) (toCDouble x3) (toCDouble x4)
foreign import ccall "qtc_QGraphicsItem_mapFromParent5" qtc_QGraphicsItem_mapFromParent5 :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQPolygonF ()))
instance QmapFromParent (QGraphicsItem a) ((QPolygonF t1)) (IO (QPolygonF ())) where
mapFromParent x0 (x1)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapFromParent2 cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mapFromParent2" qtc_QGraphicsItem_mapFromParent2 :: Ptr (TQGraphicsItem a) -> Ptr (TQPolygonF t1) -> IO (Ptr (TQPolygonF ()))
instance QqmapFromParent (QGraphicsItem a) ((QRectF t1)) (IO (QPolygonF ())) where
qmapFromParent x0 (x1)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapFromParent3 cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mapFromParent3" qtc_QGraphicsItem_mapFromParent3 :: Ptr (TQGraphicsItem a) -> Ptr (TQRectF t1) -> IO (Ptr (TQPolygonF ()))
instance QmapFromParent (QGraphicsItem a) ((RectF)) (IO (QPolygonF ())) where
mapFromParent x0 (x1)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withCRectF x1 $ \crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h ->
qtc_QGraphicsItem_mapFromParent3_qth cobj_x0 crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h
foreign import ccall "qtc_QGraphicsItem_mapFromParent3_qth" qtc_QGraphicsItem_mapFromParent3_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQPolygonF ()))
instance QmapFromScene (QGraphicsItem a) ((Double, Double)) (IO (PointF)) where
mapFromScene x0 (x1, x2)
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_mapFromScene4_qth cobj_x0 (toCDouble x1) (toCDouble x2) cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_mapFromScene4_qth" qtc_QGraphicsItem_mapFromScene4_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QmapFromScene (QGraphicsItem a) ((PointF)) (IO (PointF)) where
mapFromScene x0 (x1)
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QGraphicsItem_mapFromScene1_qth cobj_x0 cpointf_x1_x cpointf_x1_y cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_mapFromScene1_qth" qtc_QGraphicsItem_mapFromScene1_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QmapFromScene (QGraphicsItem a) ((QPainterPath t1)) (IO (QPainterPath ())) where
mapFromScene x0 (x1)
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapFromScene cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mapFromScene" qtc_QGraphicsItem_mapFromScene :: Ptr (TQGraphicsItem a) -> Ptr (TQPainterPath t1) -> IO (Ptr (TQPainterPath ()))
instance QqmapFromScene (QGraphicsItem a) ((Double, Double)) (IO (QPointF ())) where
qmapFromScene x0 (x1, x2)
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_mapFromScene4 cobj_x0 (toCDouble x1) (toCDouble x2)
foreign import ccall "qtc_QGraphicsItem_mapFromScene4" qtc_QGraphicsItem_mapFromScene4 :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> IO (Ptr (TQPointF ()))
instance QqmapFromScene (QGraphicsItem a) ((QPointF t1)) (IO (QPointF ())) where
qmapFromScene x0 (x1)
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapFromScene1 cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mapFromScene1" qtc_QGraphicsItem_mapFromScene1 :: Ptr (TQGraphicsItem a) -> Ptr (TQPointF t1) -> IO (Ptr (TQPointF ()))
instance QmapFromScene (QGraphicsItem a) ((Double, Double, Double, Double)) (IO (QPolygonF ())) where
mapFromScene x0 (x1, x2, x3, x4)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_mapFromScene5 cobj_x0 (toCDouble x1) (toCDouble x2) (toCDouble x3) (toCDouble x4)
foreign import ccall "qtc_QGraphicsItem_mapFromScene5" qtc_QGraphicsItem_mapFromScene5 :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQPolygonF ()))
instance QmapFromScene (QGraphicsItem a) ((QPolygonF t1)) (IO (QPolygonF ())) where
mapFromScene x0 (x1)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapFromScene2 cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mapFromScene2" qtc_QGraphicsItem_mapFromScene2 :: Ptr (TQGraphicsItem a) -> Ptr (TQPolygonF t1) -> IO (Ptr (TQPolygonF ()))
instance QqmapFromScene (QGraphicsItem a) ((QRectF t1)) (IO (QPolygonF ())) where
qmapFromScene x0 (x1)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapFromScene3 cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mapFromScene3" qtc_QGraphicsItem_mapFromScene3 :: Ptr (TQGraphicsItem a) -> Ptr (TQRectF t1) -> IO (Ptr (TQPolygonF ()))
instance QmapFromScene (QGraphicsItem a) ((RectF)) (IO (QPolygonF ())) where
mapFromScene x0 (x1)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withCRectF x1 $ \crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h ->
qtc_QGraphicsItem_mapFromScene3_qth cobj_x0 crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h
foreign import ccall "qtc_QGraphicsItem_mapFromScene3_qth" qtc_QGraphicsItem_mapFromScene3_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQPolygonF ()))
instance QmapToItem (QGraphicsItem a) ((QGraphicsItem t1, Double, Double)) (IO (PointF)) where
mapToItem x0 (x1, x2, x3)
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapToItem4_qth cobj_x0 cobj_x1 (toCDouble x2) (toCDouble x3) cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_mapToItem4_qth" qtc_QGraphicsItem_mapToItem4_qth :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> CDouble -> CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QmapToItem (QGraphicsItem a) ((QGraphicsItem t1, PointF)) (IO (PointF)) where
mapToItem x0 (x1, x2)
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCPointF x2 $ \cpointf_x2_x cpointf_x2_y ->
qtc_QGraphicsItem_mapToItem1_qth cobj_x0 cobj_x1 cpointf_x2_x cpointf_x2_y cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_mapToItem1_qth" qtc_QGraphicsItem_mapToItem1_qth :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> CDouble -> CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QmapToItem (QGraphicsItem a) ((QGraphicsTextItem t1, Double, Double)) (IO (PointF)) where
mapToItem x0 (x1, x2, x3)
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapToItem4_graphicstextitem_qth cobj_x0 cobj_x1 (toCDouble x2) (toCDouble x3) cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_mapToItem4_graphicstextitem_qth" qtc_QGraphicsItem_mapToItem4_graphicstextitem_qth :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> CDouble -> CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QmapToItem (QGraphicsItem a) ((QGraphicsTextItem t1, PointF)) (IO (PointF)) where
mapToItem x0 (x1, x2)
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCPointF x2 $ \cpointf_x2_x cpointf_x2_y ->
qtc_QGraphicsItem_mapToItem1_graphicstextitem_qth cobj_x0 cobj_x1 cpointf_x2_x cpointf_x2_y cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_mapToItem1_graphicstextitem_qth" qtc_QGraphicsItem_mapToItem1_graphicstextitem_qth :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> CDouble -> CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QmapToItem (QGraphicsItem a) ((QGraphicsItem t1, QPainterPath t2)) (IO (QPainterPath ())) where
mapToItem x0 (x1, x2)
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_mapToItem cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_mapToItem" qtc_QGraphicsItem_mapToItem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> Ptr (TQPainterPath t2) -> IO (Ptr (TQPainterPath ()))
instance QmapToItem (QGraphicsItem a) ((QGraphicsTextItem t1, QPainterPath t2)) (IO (QPainterPath ())) where
mapToItem x0 (x1, x2)
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_mapToItem_graphicstextitem cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_mapToItem_graphicstextitem" qtc_QGraphicsItem_mapToItem_graphicstextitem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> Ptr (TQPainterPath t2) -> IO (Ptr (TQPainterPath ()))
instance QqmapToItem (QGraphicsItem a) ((QGraphicsItem t1, Double, Double)) (IO (QPointF ())) where
qmapToItem x0 (x1, x2, x3)
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapToItem4 cobj_x0 cobj_x1 (toCDouble x2) (toCDouble x3)
foreign import ccall "qtc_QGraphicsItem_mapToItem4" qtc_QGraphicsItem_mapToItem4 :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> CDouble -> CDouble -> IO (Ptr (TQPointF ()))
instance QqmapToItem (QGraphicsItem a) ((QGraphicsItem t1, QPointF t2)) (IO (QPointF ())) where
qmapToItem x0 (x1, x2)
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_mapToItem1 cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_mapToItem1" qtc_QGraphicsItem_mapToItem1 :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> Ptr (TQPointF t2) -> IO (Ptr (TQPointF ()))
instance QqmapToItem (QGraphicsItem a) ((QGraphicsTextItem t1, Double, Double)) (IO (QPointF ())) where
qmapToItem x0 (x1, x2, x3)
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapToItem4_graphicstextitem cobj_x0 cobj_x1 (toCDouble x2) (toCDouble x3)
foreign import ccall "qtc_QGraphicsItem_mapToItem4_graphicstextitem" qtc_QGraphicsItem_mapToItem4_graphicstextitem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> CDouble -> CDouble -> IO (Ptr (TQPointF ()))
instance QqmapToItem (QGraphicsItem a) ((QGraphicsTextItem t1, QPointF t2)) (IO (QPointF ())) where
qmapToItem x0 (x1, x2)
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_mapToItem1_graphicstextitem cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_mapToItem1_graphicstextitem" qtc_QGraphicsItem_mapToItem1_graphicstextitem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> Ptr (TQPointF t2) -> IO (Ptr (TQPointF ()))
instance QmapToItem (QGraphicsItem a) ((QGraphicsItem t1, Double, Double, Double, Double)) (IO (QPolygonF ())) where
mapToItem x0 (x1, x2, x3, x4, x5)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapToItem5 cobj_x0 cobj_x1 (toCDouble x2) (toCDouble x3) (toCDouble x4) (toCDouble x5)
foreign import ccall "qtc_QGraphicsItem_mapToItem5" qtc_QGraphicsItem_mapToItem5 :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQPolygonF ()))
instance QmapToItem (QGraphicsItem a) ((QGraphicsItem t1, QPolygonF t2)) (IO (QPolygonF ())) where
mapToItem x0 (x1, x2)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_mapToItem2 cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_mapToItem2" qtc_QGraphicsItem_mapToItem2 :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> Ptr (TQPolygonF t2) -> IO (Ptr (TQPolygonF ()))
instance QqmapToItem (QGraphicsItem a) ((QGraphicsItem t1, QRectF t2)) (IO (QPolygonF ())) where
qmapToItem x0 (x1, x2)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_mapToItem3 cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_mapToItem3" qtc_QGraphicsItem_mapToItem3 :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> Ptr (TQRectF t2) -> IO (Ptr (TQPolygonF ()))
instance QmapToItem (QGraphicsItem a) ((QGraphicsItem t1, RectF)) (IO (QPolygonF ())) where
mapToItem x0 (x1, x2)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCRectF x2 $ \crectf_x2_x crectf_x2_y crectf_x2_w crectf_x2_h ->
qtc_QGraphicsItem_mapToItem3_qth cobj_x0 cobj_x1 crectf_x2_x crectf_x2_y crectf_x2_w crectf_x2_h
foreign import ccall "qtc_QGraphicsItem_mapToItem3_qth" qtc_QGraphicsItem_mapToItem3_qth :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQPolygonF ()))
instance QmapToItem (QGraphicsItem a) ((QGraphicsTextItem t1, Double, Double, Double, Double)) (IO (QPolygonF ())) where
mapToItem x0 (x1, x2, x3, x4, x5)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapToItem5_graphicstextitem cobj_x0 cobj_x1 (toCDouble x2) (toCDouble x3) (toCDouble x4) (toCDouble x5)
foreign import ccall "qtc_QGraphicsItem_mapToItem5_graphicstextitem" qtc_QGraphicsItem_mapToItem5_graphicstextitem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQPolygonF ()))
instance QmapToItem (QGraphicsItem a) ((QGraphicsTextItem t1, QPolygonF t2)) (IO (QPolygonF ())) where
mapToItem x0 (x1, x2)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_mapToItem2_graphicstextitem cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_mapToItem2_graphicstextitem" qtc_QGraphicsItem_mapToItem2_graphicstextitem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> Ptr (TQPolygonF t2) -> IO (Ptr (TQPolygonF ()))
instance QqmapToItem (QGraphicsItem a) ((QGraphicsTextItem t1, QRectF t2)) (IO (QPolygonF ())) where
qmapToItem x0 (x1, x2)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_mapToItem3_graphicstextitem cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_mapToItem3_graphicstextitem" qtc_QGraphicsItem_mapToItem3_graphicstextitem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> Ptr (TQRectF t2) -> IO (Ptr (TQPolygonF ()))
instance QmapToItem (QGraphicsItem a) ((QGraphicsTextItem t1, RectF)) (IO (QPolygonF ())) where
mapToItem x0 (x1, x2)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCRectF x2 $ \crectf_x2_x crectf_x2_y crectf_x2_w crectf_x2_h ->
qtc_QGraphicsItem_mapToItem3_graphicstextitem_qth cobj_x0 cobj_x1 crectf_x2_x crectf_x2_y crectf_x2_w crectf_x2_h
foreign import ccall "qtc_QGraphicsItem_mapToItem3_graphicstextitem_qth" qtc_QGraphicsItem_mapToItem3_graphicstextitem_qth :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQPolygonF ()))
instance QmapToParent (QGraphicsItem a) ((Double, Double)) (IO (PointF)) where
mapToParent x0 (x1, x2)
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_mapToParent4_qth cobj_x0 (toCDouble x1) (toCDouble x2) cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_mapToParent4_qth" qtc_QGraphicsItem_mapToParent4_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QmapToParent (QGraphicsItem a) ((PointF)) (IO (PointF)) where
mapToParent x0 (x1)
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QGraphicsItem_mapToParent1_qth cobj_x0 cpointf_x1_x cpointf_x1_y cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_mapToParent1_qth" qtc_QGraphicsItem_mapToParent1_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QmapToParent (QGraphicsItem a) ((QPainterPath t1)) (IO (QPainterPath ())) where
mapToParent x0 (x1)
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapToParent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mapToParent" qtc_QGraphicsItem_mapToParent :: Ptr (TQGraphicsItem a) -> Ptr (TQPainterPath t1) -> IO (Ptr (TQPainterPath ()))
instance QqmapToParent (QGraphicsItem a) ((Double, Double)) (IO (QPointF ())) where
qmapToParent x0 (x1, x2)
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_mapToParent4 cobj_x0 (toCDouble x1) (toCDouble x2)
foreign import ccall "qtc_QGraphicsItem_mapToParent4" qtc_QGraphicsItem_mapToParent4 :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> IO (Ptr (TQPointF ()))
instance QqmapToParent (QGraphicsItem a) ((QPointF t1)) (IO (QPointF ())) where
qmapToParent x0 (x1)
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapToParent1 cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mapToParent1" qtc_QGraphicsItem_mapToParent1 :: Ptr (TQGraphicsItem a) -> Ptr (TQPointF t1) -> IO (Ptr (TQPointF ()))
instance QmapToParent (QGraphicsItem a) ((Double, Double, Double, Double)) (IO (QPolygonF ())) where
mapToParent x0 (x1, x2, x3, x4)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_mapToParent5 cobj_x0 (toCDouble x1) (toCDouble x2) (toCDouble x3) (toCDouble x4)
foreign import ccall "qtc_QGraphicsItem_mapToParent5" qtc_QGraphicsItem_mapToParent5 :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQPolygonF ()))
instance QmapToParent (QGraphicsItem a) ((QPolygonF t1)) (IO (QPolygonF ())) where
mapToParent x0 (x1)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapToParent2 cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mapToParent2" qtc_QGraphicsItem_mapToParent2 :: Ptr (TQGraphicsItem a) -> Ptr (TQPolygonF t1) -> IO (Ptr (TQPolygonF ()))
instance QqmapToParent (QGraphicsItem a) ((QRectF t1)) (IO (QPolygonF ())) where
qmapToParent x0 (x1)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapToParent3 cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mapToParent3" qtc_QGraphicsItem_mapToParent3 :: Ptr (TQGraphicsItem a) -> Ptr (TQRectF t1) -> IO (Ptr (TQPolygonF ()))
instance QmapToParent (QGraphicsItem a) ((RectF)) (IO (QPolygonF ())) where
mapToParent x0 (x1)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withCRectF x1 $ \crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h ->
qtc_QGraphicsItem_mapToParent3_qth cobj_x0 crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h
foreign import ccall "qtc_QGraphicsItem_mapToParent3_qth" qtc_QGraphicsItem_mapToParent3_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQPolygonF ()))
instance QmapToScene (QGraphicsItem a) ((Double, Double)) (IO (PointF)) where
mapToScene x0 (x1, x2)
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_mapToScene4_qth cobj_x0 (toCDouble x1) (toCDouble x2) cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_mapToScene4_qth" qtc_QGraphicsItem_mapToScene4_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QmapToScene (QGraphicsItem a) ((PointF)) (IO (PointF)) where
mapToScene x0 (x1)
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QGraphicsItem_mapToScene1_qth cobj_x0 cpointf_x1_x cpointf_x1_y cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_mapToScene1_qth" qtc_QGraphicsItem_mapToScene1_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QmapToScene (QGraphicsItem a) ((QPainterPath t1)) (IO (QPainterPath ())) where
mapToScene x0 (x1)
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapToScene cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mapToScene" qtc_QGraphicsItem_mapToScene :: Ptr (TQGraphicsItem a) -> Ptr (TQPainterPath t1) -> IO (Ptr (TQPainterPath ()))
instance QqmapToScene (QGraphicsItem a) ((Double, Double)) (IO (QPointF ())) where
qmapToScene x0 (x1, x2)
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_mapToScene4 cobj_x0 (toCDouble x1) (toCDouble x2)
foreign import ccall "qtc_QGraphicsItem_mapToScene4" qtc_QGraphicsItem_mapToScene4 :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> IO (Ptr (TQPointF ()))
instance QqmapToScene (QGraphicsItem a) ((QPointF t1)) (IO (QPointF ())) where
qmapToScene x0 (x1)
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapToScene1 cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mapToScene1" qtc_QGraphicsItem_mapToScene1 :: Ptr (TQGraphicsItem a) -> Ptr (TQPointF t1) -> IO (Ptr (TQPointF ()))
instance QmapToScene (QGraphicsItem a) ((Double, Double, Double, Double)) (IO (QPolygonF ())) where
mapToScene x0 (x1, x2, x3, x4)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_mapToScene5 cobj_x0 (toCDouble x1) (toCDouble x2) (toCDouble x3) (toCDouble x4)
foreign import ccall "qtc_QGraphicsItem_mapToScene5" qtc_QGraphicsItem_mapToScene5 :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQPolygonF ()))
instance QmapToScene (QGraphicsItem a) ((QPolygonF t1)) (IO (QPolygonF ())) where
mapToScene x0 (x1)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapToScene2 cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mapToScene2" qtc_QGraphicsItem_mapToScene2 :: Ptr (TQGraphicsItem a) -> Ptr (TQPolygonF t1) -> IO (Ptr (TQPolygonF ()))
instance QqmapToScene (QGraphicsItem a) ((QRectF t1)) (IO (QPolygonF ())) where
qmapToScene x0 (x1)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapToScene3 cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mapToScene3" qtc_QGraphicsItem_mapToScene3 :: Ptr (TQGraphicsItem a) -> Ptr (TQRectF t1) -> IO (Ptr (TQPolygonF ()))
instance QmapToScene (QGraphicsItem a) ((RectF)) (IO (QPolygonF ())) where
mapToScene x0 (x1)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withCRectF x1 $ \crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h ->
qtc_QGraphicsItem_mapToScene3_qth cobj_x0 crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h
foreign import ccall "qtc_QGraphicsItem_mapToScene3_qth" qtc_QGraphicsItem_mapToScene3_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQPolygonF ()))
instance Qmatrix (QGraphicsItem a) (()) where
matrix x0 ()
= withQMatrixResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_matrix cobj_x0
foreign import ccall "qtc_QGraphicsItem_matrix" qtc_QGraphicsItem_matrix :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQMatrix ()))
instance QmouseDoubleClickEvent (QGraphicsItem ()) ((QGraphicsSceneMouseEvent t1)) where
mouseDoubleClickEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mouseDoubleClickEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mouseDoubleClickEvent_h" qtc_QGraphicsItem_mouseDoubleClickEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent (QGraphicsItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mouseDoubleClickEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mouseDoubleClickEvent_h cobj_x0 cobj_x1
instance QmouseMoveEvent (QGraphicsItem ()) ((QGraphicsSceneMouseEvent t1)) where
mouseMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mouseMoveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mouseMoveEvent_h" qtc_QGraphicsItem_mouseMoveEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmouseMoveEvent (QGraphicsItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mouseMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mouseMoveEvent_h cobj_x0 cobj_x1
instance QmousePressEvent (QGraphicsItem ()) ((QGraphicsSceneMouseEvent t1)) where
mousePressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mousePressEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mousePressEvent_h" qtc_QGraphicsItem_mousePressEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmousePressEvent (QGraphicsItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mousePressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mousePressEvent_h cobj_x0 cobj_x1
instance QmouseReleaseEvent (QGraphicsItem ()) ((QGraphicsSceneMouseEvent t1)) where
mouseReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mouseReleaseEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mouseReleaseEvent_h" qtc_QGraphicsItem_mouseReleaseEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmouseReleaseEvent (QGraphicsItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mouseReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mouseReleaseEvent_h cobj_x0 cobj_x1
instance QmoveBy (QGraphicsItem a) ((Double, Double)) where
moveBy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_moveBy cobj_x0 (toCDouble x1) (toCDouble x2)
foreign import ccall "qtc_QGraphicsItem_moveBy" qtc_QGraphicsItem_moveBy :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> IO ()
instance QopaqueArea (QGraphicsItem ()) (()) where
opaqueArea x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_opaqueArea_h cobj_x0
foreign import ccall "qtc_QGraphicsItem_opaqueArea_h" qtc_QGraphicsItem_opaqueArea_h :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQPainterPath ()))
instance QopaqueArea (QGraphicsItemSc a) (()) where
opaqueArea x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_opaqueArea_h cobj_x0
instance Qpaint (QGraphicsItem ()) ((QPainter t1, QStyleOptionGraphicsItem t2)) where
paint x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_paint_h cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_paint_h" qtc_QGraphicsItem_paint_h :: Ptr (TQGraphicsItem a) -> Ptr (TQPainter t1) -> Ptr (TQStyleOptionGraphicsItem t2) -> IO ()
instance Qpaint (QGraphicsItemSc a) ((QPainter t1, QStyleOptionGraphicsItem t2)) where
paint x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_paint_h cobj_x0 cobj_x1 cobj_x2
instance Qpaint (QGraphicsItem ()) ((QPainter t1, QStyleOptionGraphicsItem t2, QWidget t3)) where
paint x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QGraphicsItem_paint1_h cobj_x0 cobj_x1 cobj_x2 cobj_x3
foreign import ccall "qtc_QGraphicsItem_paint1_h" qtc_QGraphicsItem_paint1_h :: Ptr (TQGraphicsItem a) -> Ptr (TQPainter t1) -> Ptr (TQStyleOptionGraphicsItem t2) -> Ptr (TQWidget t3) -> IO ()
instance Qpaint (QGraphicsItemSc a) ((QPainter t1, QStyleOptionGraphicsItem t2, QWidget t3)) where
paint x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QGraphicsItem_paint1_h cobj_x0 cobj_x1 cobj_x2 cobj_x3
instance QparentItem (QGraphicsItem a) (()) where
parentItem x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_parentItem cobj_x0
foreign import ccall "qtc_QGraphicsItem_parentItem" qtc_QGraphicsItem_parentItem :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQGraphicsItem ()))
instance Qpos (QGraphicsItem a) (()) (IO (PointF)) where
pos x0 ()
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_pos_qth cobj_x0 cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_pos_qth" qtc_QGraphicsItem_pos_qth :: Ptr (TQGraphicsItem a) -> Ptr CDouble -> Ptr CDouble -> IO ()
instance Qqpos (QGraphicsItem a) (()) (IO (QPointF ())) where
qpos x0 ()
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_pos cobj_x0
foreign import ccall "qtc_QGraphicsItem_pos" qtc_QGraphicsItem_pos :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQPointF ()))
instance QprepareGeometryChange (QGraphicsItem ()) (()) where
prepareGeometryChange x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_prepareGeometryChange cobj_x0
foreign import ccall "qtc_QGraphicsItem_prepareGeometryChange" qtc_QGraphicsItem_prepareGeometryChange :: Ptr (TQGraphicsItem a) -> IO ()
instance QprepareGeometryChange (QGraphicsItemSc a) (()) where
prepareGeometryChange x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_prepareGeometryChange cobj_x0
instance QremoveFromIndex (QGraphicsItem ()) (()) where
removeFromIndex x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_removeFromIndex cobj_x0
foreign import ccall "qtc_QGraphicsItem_removeFromIndex" qtc_QGraphicsItem_removeFromIndex :: Ptr (TQGraphicsItem a) -> IO ()
instance QremoveFromIndex (QGraphicsItemSc a) (()) where
removeFromIndex x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_removeFromIndex cobj_x0
instance QremoveSceneEventFilter (QGraphicsItem a) ((QGraphicsItem t1)) where
removeSceneEventFilter x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_removeSceneEventFilter cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_removeSceneEventFilter" qtc_QGraphicsItem_removeSceneEventFilter :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> IO ()
instance QremoveSceneEventFilter (QGraphicsItem a) ((QGraphicsTextItem t1)) where
removeSceneEventFilter x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_removeSceneEventFilter_graphicstextitem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_removeSceneEventFilter_graphicstextitem" qtc_QGraphicsItem_removeSceneEventFilter_graphicstextitem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> IO ()
instance QresetMatrix (QGraphicsItem a) (()) where
resetMatrix x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_resetMatrix cobj_x0
foreign import ccall "qtc_QGraphicsItem_resetMatrix" qtc_QGraphicsItem_resetMatrix :: Ptr (TQGraphicsItem a) -> IO ()
instance QresetTransform (QGraphicsItem a) (()) where
resetTransform x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_resetTransform cobj_x0
foreign import ccall "qtc_QGraphicsItem_resetTransform" qtc_QGraphicsItem_resetTransform :: Ptr (TQGraphicsItem a) -> IO ()
instance Qrotate (QGraphicsItem a) ((Double)) where
rotate x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_rotate cobj_x0 (toCDouble x1)
foreign import ccall "qtc_QGraphicsItem_rotate" qtc_QGraphicsItem_rotate :: Ptr (TQGraphicsItem a) -> CDouble -> IO ()
instance Qqscale (QGraphicsItem a) ((Double, Double)) where
qscale x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_scale cobj_x0 (toCDouble x1) (toCDouble x2)
foreign import ccall "qtc_QGraphicsItem_scale" qtc_QGraphicsItem_scale :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> IO ()
instance Qscene (QGraphicsItem a) (()) where
scene x0 ()
= withQGraphicsSceneResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_scene cobj_x0
foreign import ccall "qtc_QGraphicsItem_scene" qtc_QGraphicsItem_scene :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQGraphicsScene ()))
instance QqsceneBoundingRect (QGraphicsItem a) (()) where
qsceneBoundingRect x0 ()
= withQRectFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_sceneBoundingRect cobj_x0
foreign import ccall "qtc_QGraphicsItem_sceneBoundingRect" qtc_QGraphicsItem_sceneBoundingRect :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQRectF ()))
instance QsceneBoundingRect (QGraphicsItem a) (()) where
sceneBoundingRect x0 ()
= withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_sceneBoundingRect_qth cobj_x0 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h
foreign import ccall "qtc_QGraphicsItem_sceneBoundingRect_qth" qtc_QGraphicsItem_sceneBoundingRect_qth :: Ptr (TQGraphicsItem a) -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QsceneEvent (QGraphicsItem ()) ((QEvent t1)) where
sceneEvent x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_sceneEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_sceneEvent_h" qtc_QGraphicsItem_sceneEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQEvent t1) -> IO CBool
instance QsceneEvent (QGraphicsItemSc a) ((QEvent t1)) where
sceneEvent x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_sceneEvent_h cobj_x0 cobj_x1
instance QsceneEventFilter (QGraphicsItem ()) ((QGraphicsItem t1, QEvent t2)) where
sceneEventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_sceneEventFilter_h cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_sceneEventFilter_h" qtc_QGraphicsItem_sceneEventFilter_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO CBool
instance QsceneEventFilter (QGraphicsItemSc a) ((QGraphicsItem t1, QEvent t2)) where
sceneEventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_sceneEventFilter_h cobj_x0 cobj_x1 cobj_x2
instance QsceneEventFilter (QGraphicsItem ()) ((QGraphicsTextItem t1, QEvent t2)) where
sceneEventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_sceneEventFilter_graphicstextitem_h cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_sceneEventFilter_graphicstextitem_h" qtc_QGraphicsItem_sceneEventFilter_graphicstextitem_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> Ptr (TQEvent t2) -> IO CBool
instance QsceneEventFilter (QGraphicsItemSc a) ((QGraphicsTextItem t1, QEvent t2)) where
sceneEventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_sceneEventFilter_graphicstextitem_h cobj_x0 cobj_x1 cobj_x2
instance QsceneMatrix (QGraphicsItem a) (()) where
sceneMatrix x0 ()
= withQMatrixResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_sceneMatrix cobj_x0
foreign import ccall "qtc_QGraphicsItem_sceneMatrix" qtc_QGraphicsItem_sceneMatrix :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQMatrix ()))
instance QscenePos (QGraphicsItem a) (()) where
scenePos x0 ()
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_scenePos_qth cobj_x0 cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_scenePos_qth" qtc_QGraphicsItem_scenePos_qth :: Ptr (TQGraphicsItem a) -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QqscenePos (QGraphicsItem a) (()) where
qscenePos x0 ()
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_scenePos cobj_x0
foreign import ccall "qtc_QGraphicsItem_scenePos" qtc_QGraphicsItem_scenePos :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQPointF ()))
instance QsceneTransform (QGraphicsItem a) (()) where
sceneTransform x0 ()
= withQTransformResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_sceneTransform cobj_x0
foreign import ccall "qtc_QGraphicsItem_sceneTransform" qtc_QGraphicsItem_sceneTransform :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQTransform ()))
instance QsetAcceptDrops (QGraphicsItem a) ((Bool)) where
setAcceptDrops x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_setAcceptDrops cobj_x0 (toCBool x1)
foreign import ccall "qtc_QGraphicsItem_setAcceptDrops" qtc_QGraphicsItem_setAcceptDrops :: Ptr (TQGraphicsItem a) -> CBool -> IO ()
instance QsetAcceptedMouseButtons (QGraphicsItem a) ((MouseButtons)) where
setAcceptedMouseButtons x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_setAcceptedMouseButtons cobj_x0 (toCLong $ qFlags_toInt x1)
foreign import ccall "qtc_QGraphicsItem_setAcceptedMouseButtons" qtc_QGraphicsItem_setAcceptedMouseButtons :: Ptr (TQGraphicsItem a) -> CLong -> IO ()
instance QsetAcceptsHoverEvents (QGraphicsItem a) ((Bool)) where
setAcceptsHoverEvents x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_setAcceptsHoverEvents cobj_x0 (toCBool x1)
foreign import ccall "qtc_QGraphicsItem_setAcceptsHoverEvents" qtc_QGraphicsItem_setAcceptsHoverEvents :: Ptr (TQGraphicsItem a) -> CBool -> IO ()
instance QsetCursor (QGraphicsItem a) ((QCursor t1)) where
setCursor x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_setCursor cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_setCursor" qtc_QGraphicsItem_setCursor :: Ptr (TQGraphicsItem a) -> Ptr (TQCursor t1) -> IO ()
instance QsetData (QGraphicsItem a) ((Int, QVariant t2)) (IO ()) where
setData x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_setData cobj_x0 (toCInt x1) cobj_x2
foreign import ccall "qtc_QGraphicsItem_setData" qtc_QGraphicsItem_setData :: Ptr (TQGraphicsItem a) -> CInt -> Ptr (TQVariant t2) -> IO ()
instance QsetEnabled (QGraphicsItem a) ((Bool)) where
setEnabled x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_setEnabled cobj_x0 (toCBool x1)
foreign import ccall "qtc_QGraphicsItem_setEnabled" qtc_QGraphicsItem_setEnabled :: Ptr (TQGraphicsItem a) -> CBool -> IO ()
instance QsetExtension (QGraphicsItem ()) ((QGraphicsItemExtension, QVariant t2)) where
setExtension x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_setExtension cobj_x0 (toCLong $ qEnum_toInt x1) cobj_x2
foreign import ccall "qtc_QGraphicsItem_setExtension" qtc_QGraphicsItem_setExtension :: Ptr (TQGraphicsItem a) -> CLong -> Ptr (TQVariant t2) -> IO ()
instance QsetExtension (QGraphicsItemSc a) ((QGraphicsItemExtension, QVariant t2)) where
setExtension x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_setExtension cobj_x0 (toCLong $ qEnum_toInt x1) cobj_x2
instance QsetFlag (QGraphicsItem a) ((GraphicsItemFlag)) where
setFlag x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_setFlag cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QGraphicsItem_setFlag" qtc_QGraphicsItem_setFlag :: Ptr (TQGraphicsItem a) -> CLong -> IO ()
instance QsetFlag (QGraphicsItem a) ((GraphicsItemFlag, Bool)) where
setFlag x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_setFlag1 cobj_x0 (toCLong $ qEnum_toInt x1) (toCBool x2)
foreign import ccall "qtc_QGraphicsItem_setFlag1" qtc_QGraphicsItem_setFlag1 :: Ptr (TQGraphicsItem a) -> CLong -> CBool -> IO ()
instance QsetFlags (QGraphicsItem a) ((GraphicsItemFlags)) where
setFlags x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_setFlags cobj_x0 (toCLong $ qFlags_toInt x1)
foreign import ccall "qtc_QGraphicsItem_setFlags" qtc_QGraphicsItem_setFlags :: Ptr (TQGraphicsItem a) -> CLong -> IO ()
instance QsetFocus (QGraphicsItem a) (()) where
setFocus x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_setFocus cobj_x0
foreign import ccall "qtc_QGraphicsItem_setFocus" qtc_QGraphicsItem_setFocus :: Ptr (TQGraphicsItem a) -> IO ()
instance QsetFocus (QGraphicsItem a) ((FocusReason)) where
setFocus x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_setFocus1 cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QGraphicsItem_setFocus1" qtc_QGraphicsItem_setFocus1 :: Ptr (TQGraphicsItem a) -> CLong -> IO ()
instance QsetGroup (QGraphicsItem a) ((QGraphicsItemGroup t1)) where
setGroup x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_setGroup cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_setGroup" qtc_QGraphicsItem_setGroup :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItemGroup t1) -> IO ()
instance QsetHandlesChildEvents (QGraphicsItem a) ((Bool)) where
setHandlesChildEvents x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_setHandlesChildEvents cobj_x0 (toCBool x1)
foreign import ccall "qtc_QGraphicsItem_setHandlesChildEvents" qtc_QGraphicsItem_setHandlesChildEvents :: Ptr (TQGraphicsItem a) -> CBool -> IO ()
instance QsetMatrix (QGraphicsItem a) ((QMatrix t1)) where
setMatrix x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_setMatrix cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_setMatrix" qtc_QGraphicsItem_setMatrix :: Ptr (TQGraphicsItem a) -> Ptr (TQMatrix t1) -> IO ()
instance QsetMatrix (QGraphicsItem a) ((QMatrix t1, Bool)) where
setMatrix x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_setMatrix1 cobj_x0 cobj_x1 (toCBool x2)
foreign import ccall "qtc_QGraphicsItem_setMatrix1" qtc_QGraphicsItem_setMatrix1 :: Ptr (TQGraphicsItem a) -> Ptr (TQMatrix t1) -> CBool -> IO ()
instance QsetParentItem (QGraphicsItem a) ((QGraphicsItem t1)) where
setParentItem x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_setParentItem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_setParentItem" qtc_QGraphicsItem_setParentItem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> IO ()
instance QsetParentItem (QGraphicsItem a) ((QGraphicsTextItem t1)) where
setParentItem x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_setParentItem_graphicstextitem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_setParentItem_graphicstextitem" qtc_QGraphicsItem_setParentItem_graphicstextitem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> IO ()
instance QsetPos (QGraphicsItem a) ((Double, Double)) where
setPos x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_setPos1 cobj_x0 (toCDouble x1) (toCDouble x2)
foreign import ccall "qtc_QGraphicsItem_setPos1" qtc_QGraphicsItem_setPos1 :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> IO ()
instance QsetPos (QGraphicsItem a) ((PointF)) where
setPos x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QGraphicsItem_setPos_qth cobj_x0 cpointf_x1_x cpointf_x1_y
foreign import ccall "qtc_QGraphicsItem_setPos_qth" qtc_QGraphicsItem_setPos_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> IO ()
instance QqsetPos (QGraphicsItem a) ((QPointF t1)) where
qsetPos x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_setPos cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_setPos" qtc_QGraphicsItem_setPos :: Ptr (TQGraphicsItem a) -> Ptr (TQPointF t1) -> IO ()
instance QsetSelected (QGraphicsItem a) ((Bool)) where
setSelected x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_setSelected cobj_x0 (toCBool x1)
foreign import ccall "qtc_QGraphicsItem_setSelected" qtc_QGraphicsItem_setSelected :: Ptr (TQGraphicsItem a) -> CBool -> IO ()
instance QsetToolTip (QGraphicsItem a) ((String)) where
setToolTip x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QGraphicsItem_setToolTip cobj_x0 cstr_x1
foreign import ccall "qtc_QGraphicsItem_setToolTip" qtc_QGraphicsItem_setToolTip :: Ptr (TQGraphicsItem a) -> CWString -> IO ()
instance QsetTransform (QGraphicsItem a) ((QTransform t1)) where
setTransform x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_setTransform cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_setTransform" qtc_QGraphicsItem_setTransform :: Ptr (TQGraphicsItem a) -> Ptr (TQTransform t1) -> IO ()
instance QsetTransform (QGraphicsItem a) ((QTransform t1, Bool)) where
setTransform x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_setTransform1 cobj_x0 cobj_x1 (toCBool x2)
foreign import ccall "qtc_QGraphicsItem_setTransform1" qtc_QGraphicsItem_setTransform1 :: Ptr (TQGraphicsItem a) -> Ptr (TQTransform t1) -> CBool -> IO ()
instance QsetVisible (QGraphicsItem a) ((Bool)) where
setVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_setVisible cobj_x0 (toCBool x1)
foreign import ccall "qtc_QGraphicsItem_setVisible" qtc_QGraphicsItem_setVisible :: Ptr (TQGraphicsItem a) -> CBool -> IO ()
instance QsetZValue (QGraphicsItem a) ((Double)) where
setZValue x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_setZValue cobj_x0 (toCDouble x1)
foreign import ccall "qtc_QGraphicsItem_setZValue" qtc_QGraphicsItem_setZValue :: Ptr (TQGraphicsItem a) -> CDouble -> IO ()
instance Qshape (QGraphicsItem ()) (()) (IO (QPainterPath ())) where
shape x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_shape_h cobj_x0
foreign import ccall "qtc_QGraphicsItem_shape_h" qtc_QGraphicsItem_shape_h :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQPainterPath ()))
instance Qshape (QGraphicsItemSc a) (()) (IO (QPainterPath ())) where
shape x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_shape_h cobj_x0
instance Qshear (QGraphicsItem a) ((Double, Double)) where
shear x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_shear cobj_x0 (toCDouble x1) (toCDouble x2)
foreign import ccall "qtc_QGraphicsItem_shear" qtc_QGraphicsItem_shear :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> IO ()
instance Qqshow (QGraphicsItem a) (()) where
qshow x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_show cobj_x0
foreign import ccall "qtc_QGraphicsItem_show" qtc_QGraphicsItem_show :: Ptr (TQGraphicsItem a) -> IO ()
instance QsupportsExtension (QGraphicsItem ()) ((QGraphicsItemExtension)) where
supportsExtension x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_supportsExtension cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QGraphicsItem_supportsExtension" qtc_QGraphicsItem_supportsExtension :: Ptr (TQGraphicsItem a) -> CLong -> IO CBool
instance QsupportsExtension (QGraphicsItemSc a) ((QGraphicsItemExtension)) where
supportsExtension x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_supportsExtension cobj_x0 (toCLong $ qEnum_toInt x1)
instance QtoolTip (QGraphicsItem a) (()) where
toolTip x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_toolTip cobj_x0
foreign import ccall "qtc_QGraphicsItem_toolTip" qtc_QGraphicsItem_toolTip :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQString ()))
instance QtopLevelItem (QGraphicsItem a) (()) (IO (QGraphicsItem ())) where
topLevelItem x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_topLevelItem cobj_x0
foreign import ccall "qtc_QGraphicsItem_topLevelItem" qtc_QGraphicsItem_topLevelItem :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQGraphicsItem ()))
instance Qtransform (QGraphicsItem a) (()) where
transform x0 ()
= withQTransformResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_transform cobj_x0
foreign import ccall "qtc_QGraphicsItem_transform" qtc_QGraphicsItem_transform :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQTransform ()))
instance Qqtranslate (QGraphicsItem a) ((Double, Double)) (IO ()) where
qtranslate x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_translate cobj_x0 (toCDouble x1) (toCDouble x2)
foreign import ccall "qtc_QGraphicsItem_translate" qtc_QGraphicsItem_translate :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> IO ()
instance Qqtype (QGraphicsItem ()) (()) (IO (Int)) where
qtype x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_type_h cobj_x0
foreign import ccall "qtc_QGraphicsItem_type_h" qtc_QGraphicsItem_type_h :: Ptr (TQGraphicsItem a) -> IO CInt
instance Qqtype (QGraphicsItemSc a) (()) (IO (Int)) where
qtype x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_type_h cobj_x0
instance QunsetCursor (QGraphicsItem a) (()) where
unsetCursor x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_unsetCursor cobj_x0
foreign import ccall "qtc_QGraphicsItem_unsetCursor" qtc_QGraphicsItem_unsetCursor :: Ptr (TQGraphicsItem a) -> IO ()
instance Qupdate (QGraphicsItem a) (()) where
update x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_update cobj_x0
foreign import ccall "qtc_QGraphicsItem_update" qtc_QGraphicsItem_update :: Ptr (TQGraphicsItem a) -> IO ()
instance Qupdate (QGraphicsItem a) ((Double, Double, Double, Double)) where
update x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_update2 cobj_x0 (toCDouble x1) (toCDouble x2) (toCDouble x3) (toCDouble x4)
foreign import ccall "qtc_QGraphicsItem_update2" qtc_QGraphicsItem_update2 :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> IO ()
instance Qqupdate (QGraphicsItem a) ((QRectF t1)) where
qupdate x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_update1 cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_update1" qtc_QGraphicsItem_update1 :: Ptr (TQGraphicsItem a) -> Ptr (TQRectF t1) -> IO ()
instance Qupdate (QGraphicsItem a) ((RectF)) where
update x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRectF x1 $ \crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h ->
qtc_QGraphicsItem_update1_qth cobj_x0 crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h
foreign import ccall "qtc_QGraphicsItem_update1_qth" qtc_QGraphicsItem_update1_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> IO ()
instance QwheelEvent (QGraphicsItem ()) ((QGraphicsSceneWheelEvent t1)) where
wheelEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_wheelEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_wheelEvent_h" qtc_QGraphicsItem_wheelEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsSceneWheelEvent t1) -> IO ()
instance QwheelEvent (QGraphicsItemSc a) ((QGraphicsSceneWheelEvent t1)) where
wheelEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_wheelEvent_h cobj_x0 cobj_x1
instance Qqx (QGraphicsItem a) (()) (IO (Double)) where
qx x0 ()
= withDoubleResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_x cobj_x0
foreign import ccall "qtc_QGraphicsItem_x" qtc_QGraphicsItem_x :: Ptr (TQGraphicsItem a) -> IO CDouble
instance Qqy (QGraphicsItem a) (()) (IO (Double)) where
qy x0 ()
= withDoubleResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_y cobj_x0
foreign import ccall "qtc_QGraphicsItem_y" qtc_QGraphicsItem_y :: Ptr (TQGraphicsItem a) -> IO CDouble
instance QzValue (QGraphicsItem a) (()) where
zValue x0 ()
= withDoubleResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_zValue cobj_x0
foreign import ccall "qtc_QGraphicsItem_zValue" qtc_QGraphicsItem_zValue :: Ptr (TQGraphicsItem a) -> IO CDouble
qGraphicsItem_delete :: QGraphicsItem a -> IO ()
qGraphicsItem_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_delete cobj_x0
foreign import ccall "qtc_QGraphicsItem_delete" qtc_QGraphicsItem_delete :: Ptr (TQGraphicsItem a) -> IO ()
qGraphicsItem_delete1 :: QGraphicsItem a -> IO ()
qGraphicsItem_delete1 x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_delete1 cobj_x0
foreign import ccall "qtc_QGraphicsItem_delete1" qtc_QGraphicsItem_delete1 :: Ptr (TQGraphicsItem a) -> IO ()
| uduki/hsQt | Qtc/Gui/QGraphicsItem.hs | Haskell | bsd-2-clause | 106,074 |
module Main where
import Crypto.Classes
import Crypto.Hash.Ed2k
import Crypto.Types (BitLength)
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as L
import Data.Int (Int64)
import Data.Tagged
import Test.Framework (defaultMain, testGroup, Test)
import Test.Framework.Providers.HUnit
import Test.HUnit hiding (Test)
import Text.Printf (printf)
ed2kBlockLength :: Int64
ed2kBlockLength = let bits = untag (blockLength :: Tagged Ed2k BitLength) in fromIntegral $ bits `div` 8
toHex :: Ed2k -> String
toHex d = concatMap (printf "%02x") (B.unpack $ encode $ d)
main :: IO ()
main = defaultMain tests
tests :: [Test]
tests = [testGroup "Hashing tests" [
testCase "Block length" $
9728000 @=? ed2kBlockLength,
testCase "No data (lazy)" $
"31d6cfe0d16ae931b73c59d7e0c089c0" @=? (toHex $ hash L.empty),
testCase "No data (strict)" $
"31d6cfe0d16ae931b73c59d7e0c089c0" @=? (toHex $ hash' B.empty),
testCase "Short text (lazy)" $
"1bee69a46ba811185c194762abaeae90" @=? (toHex $ hash (L.pack "The quick brown fox jumps over the lazy dog")),
testCase "Short text (strict)" $
"1bee69a46ba811185c194762abaeae90" @=? (toHex $ hash' (B.pack "The quick brown fox jumps over the lazy dog")),
testCase "Single block, zeroes (lazy)" $
"d7def262a127cd79096a108e7a9fc138" @=? (toHex $ hash (L.replicate ed2kBlockLength '\0')),
testCase "Single block, zeroes (strict)" $
"d7def262a127cd79096a108e7a9fc138" @=? (toHex $ hash' (B.replicate (fromIntegral ed2kBlockLength) '\0')),
testCase "Two blocks, zeroes (lazy)" $
"194ee9e4fa79b2ee9f8829284c466051" @=? (toHex $ hash (L.replicate (2 * ed2kBlockLength) '\0')),
testCase "Two blocks, zeroes (strict)" $
"194ee9e4fa79b2ee9f8829284c466051" @=? (toHex $ hash' (B.replicate (2 * (fromIntegral ed2kBlockLength)) '\0'))]]
| nullref/haskell-hash-ed2k | Test/Ed2k.hs | Haskell | bsd-2-clause | 1,991 |
{-# LANGUAGE OverloadedStrings #-}
module Game.GameChase where
import Control.Lens (use, (^.), (.=), zoom, ix, preuse, (%=), (&), (+~), (%~))
import Control.Monad (unless, liftM)
import Data.Bits ((.&.), complement)
import Linear (_x, _z, normalize)
import {-# SOURCE #-} Game.GameImportT
import Game.CVarT
import Game.GameLocalsT
import Game.PMoveT
import Game.EntityStateT
import Game.EdictT
import Game.PlayerStateT
import Game.GClientT
import Game.ClientRespawnT
import Types
import Game.PMoveStateT
import QuakeState
import QuakeRef
import CVarVariables
import qualified Util.Math3D as Math3D
getChaseTarget :: Ref EdictT -> Quake ()
getChaseTarget edictRef = do
maxClientsValue <- liftM (^.cvValue) maxClientsCVar
done <- findChaseTarget 1 (truncate maxClientsValue)
unless done $ do
centerPrintf <- use $ gameBaseGlobals.gbGameImport.giCenterPrintf
centerPrintf edictRef "No other players to chase."
where findChaseTarget :: Int -> Int -> Quake Bool
findChaseTarget idx maxIdx
| idx > maxIdx = return False
| otherwise = do
let otherRef = Ref idx
other <- readRef otherRef
let Just (Ref gClientIdx) = other^.eClient
Just gClient <- preuse $ gameBaseGlobals.gbGame.glClients.ix gClientIdx
if (other^.eInUse) && not (gClient^.gcResp.crSpectator)
then do
zoom (gameBaseGlobals.gbGame.glClients.ix gClientIdx) $ do
gcChaseTarget .= Just otherRef
gcUpdateChase .= True
updateChaseCam edictRef
return True
else
findChaseTarget (idx + 1) maxIdx
updateChaseCam :: Ref EdictT -> Quake ()
updateChaseCam edictRef = do
edict <- readRef edictRef
let Just gClientRef@(Ref gClientIdx) = edict^.eClient
-- is our chase target gone?
gone <- isChaseTargetGone gClientRef
unless gone $ do
Just gClient <- preuse $ gameBaseGlobals.gbGame.glClients.ix gClientIdx
let Just targRef = gClient^.gcChaseTarget
targ <- readRef targRef
let Just (Ref targClientIdx) = targ^.eClient
Just targClient <- preuse $ gameBaseGlobals.gbGame.glClients.ix targClientIdx
let ownerV = (targ^.eEntityState.esOrigin) & _z +~ fromIntegral (targ^.eViewHeight)
oldGoal = edict^.eEntityState.esOrigin
angles = (targClient^.gcVAngle) & _x %~ (\v -> if v > 56 then 56 else v) -- IMPROVE: use Constants.pitch instead of _x directly
(Just fwrd, Just right, _) = Math3D.angleVectors angles True True False
forward = normalize fwrd
o = ownerV + fmap (* (-30)) forward
io (putStrLn "GameChase.updateChaseCam") >> undefined -- TODO
where isChaseTargetGone :: Ref GClientT -> Quake Bool
isChaseTargetGone (Ref gClientIdx) = do
Just gClient <- preuse $ gameBaseGlobals.gbGame.glClients.ix gClientIdx
let Just chaseTargetRef = gClient^.gcChaseTarget
chaseTarget <- readRef chaseTargetRef
let Just (Ref chaseTargetClientIdx) = chaseTarget^.eClient
Just chaseTargetClient <- preuse $ gameBaseGlobals.gbGame.glClients.ix gClientIdx
if not (chaseTarget^.eInUse) || (chaseTargetClient^.gcResp.crSpectator)
then do
let oldRef = chaseTargetRef
chaseNext edictRef
Just gClient' <- preuse $ gameBaseGlobals.gbGame.glClients.ix gClientIdx
if (gClient'^.gcChaseTarget) == Just oldRef
then do
zoom (gameBaseGlobals.gbGame.glClients.ix gClientIdx) $ do
gcChaseTarget .= Nothing
gcPlayerState.psPMoveState.pmsPMFlags %= (.&. (complement pmfNoPrediction))
return True
else
return False
else
return False
chaseNext :: Ref EdictT -> Quake ()
chaseNext _ = do
io (putStrLn "GameChase.chaseNext") >> undefined -- TODO
| ksaveljev/hake-2 | src/Game/GameChase.hs | Haskell | bsd-3-clause | 4,042 |
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Actions.DynamicWorkspaces
-- Copyright : (c) David Roundy <[email protected]>
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : none
-- Stability : unstable
-- Portability : unportable
--
-- Provides bindings to add and delete workspaces.
--
-----------------------------------------------------------------------------
module XMonad.Actions.DynamicWorkspaces (
-- * Usage
-- $usage
addWorkspace, addWorkspacePrompt,
removeWorkspace,
removeEmptyWorkspace,
removeEmptyWorkspaceAfter,
removeEmptyWorkspaceAfterExcept,
addHiddenWorkspace,
withWorkspace,
selectWorkspace, renameWorkspace,
renameWorkspaceByName,
toNthWorkspace, withNthWorkspace
) where
import XMonad hiding (workspaces)
import XMonad.StackSet hiding (filter, modify, delete)
import XMonad.Prompt.Workspace ( Wor(Wor), workspacePrompt )
import XMonad.Prompt ( XPConfig, mkXPrompt )
import XMonad.Util.WorkspaceCompare ( getSortByIndex )
import Data.List (find)
import Data.Maybe (isNothing)
import Control.Monad (when)
-- $usage
-- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@ file:
--
-- > import XMonad.Actions.DynamicWorkspaces
-- > import XMonad.Actions.CopyWindow(copy)
--
-- Then add keybindings like the following:
--
-- > , ((modm .|. shiftMask, xK_BackSpace), removeWorkspace)
-- > , ((modm .|. shiftMask, xK_v ), selectWorkspace defaultXPConfig)
-- > , ((modm, xK_m ), withWorkspace defaultXPConfig (windows . W.shift))
-- > , ((modm .|. shiftMask, xK_m ), withWorkspace defaultXPConfig (windows . copy))
-- > , ((modm .|. shiftMask, xK_r ), renameWorkspace defaultXPConfig)
--
-- > -- mod-[1..9] %! Switch to workspace N
-- > -- mod-shift-[1..9] %! Move client to workspace N
-- > ++
-- > zip (zip (repeat (modm)) [xK_1..xK_9]) (map (withNthWorkspace W.greedyView) [0..])
-- > ++
-- > zip (zip (repeat (modm .|. shiftMask)) [xK_1..xK_9]) (map (withNthWorkspace W.shift) [0..])
--
-- For detailed instructions on editing your key bindings, see
-- "XMonad.Doc.Extending#Editing_key_bindings". See also the documentation for
-- "XMonad.Actions.CopyWindow", 'windows', 'shift', and 'defaultXPConfig'.
mkCompl :: [String] -> String -> IO [String]
mkCompl l s = return $ filter (\x -> take (length s) x == s) l
withWorkspace :: XPConfig -> (String -> X ()) -> X ()
withWorkspace c job = do ws <- gets (workspaces . windowset)
sort <- getSortByIndex
let ts = map tag $ sort ws
job' t | t `elem` ts = job t
| otherwise = addHiddenWorkspace t >> job t
mkXPrompt (Wor "") c (mkCompl ts) job'
renameWorkspace :: XPConfig -> X ()
renameWorkspace conf = workspacePrompt conf renameWorkspaceByName
renameWorkspaceByName :: String -> X ()
renameWorkspaceByName w = windows $ \s -> let sett wk = wk { tag = w }
setscr scr = scr { workspace = sett $ workspace scr }
sets q = q { current = setscr $ current q }
in sets $ removeWorkspace' w s
toNthWorkspace :: (String -> X ()) -> Int -> X ()
toNthWorkspace job wnum = do sort <- getSortByIndex
ws <- gets (map tag . sort . workspaces . windowset)
case drop wnum ws of
(w:_) -> job w
[] -> return ()
withNthWorkspace :: (String -> WindowSet -> WindowSet) -> Int -> X ()
withNthWorkspace job wnum = do sort <- getSortByIndex
ws <- gets (map tag . sort . workspaces . windowset)
case drop wnum ws of
(w:_) -> windows $ job w
[] -> return ()
selectWorkspace :: XPConfig -> X ()
selectWorkspace conf = workspacePrompt conf $ \w ->
do s <- gets windowset
if tagMember w s
then windows $ greedyView w
else addWorkspace w
-- | Add a new workspace with the given name, or do nothing if a
-- workspace with the given name already exists; then switch to the
-- newly created workspace.
addWorkspace :: String -> X ()
addWorkspace newtag = addHiddenWorkspace newtag >> windows (greedyView newtag)
-- | Prompt for the name of a new workspace, add it if it does not
-- already exist, and switch to it.
addWorkspacePrompt :: XPConfig -> X ()
addWorkspacePrompt conf = mkXPrompt (Wor "New workspace name: ") conf (const (return [])) addWorkspace
-- | Add a new hidden workspace with the given name, or do nothing if
-- a workspace with the given name already exists.
addHiddenWorkspace :: String -> X ()
addHiddenWorkspace newtag =
whenX (gets (not . tagMember newtag . windowset)) $ do
l <- asks (layoutHook . config)
windows (addHiddenWorkspace' newtag l)
-- | Remove the current workspace if it contains no windows.
removeEmptyWorkspace :: X ()
removeEmptyWorkspace = gets (currentTag . windowset) >>= removeEmptyWorkspaceByTag
-- | Remove the current workspace.
removeWorkspace :: X ()
removeWorkspace = gets (currentTag . windowset) >>= removeWorkspaceByTag
-- | Remove workspace with specific tag if it contains no windows. Only works
-- on the current or the last workspace.
removeEmptyWorkspaceByTag :: String -> X ()
removeEmptyWorkspaceByTag t = whenX (isEmpty t) $ removeWorkspaceByTag t
-- | Remove workspace with specific tag. Only works on the current or the last workspace.
removeWorkspaceByTag :: String -> X ()
removeWorkspaceByTag torem = do
s <- gets windowset
case s of
StackSet { current = Screen { workspace = cur }, hidden = (w:_) } -> do
when (torem==tag cur) $ windows $ view $ tag w
windows $ removeWorkspace' torem
_ -> return ()
-- | Remove the current workspace after an operation if it is empty and hidden.
-- Can be used to remove a workspace if it is empty when leaving it. The
-- operation may only change workspace once, otherwise the workspace will not
-- be removed.
removeEmptyWorkspaceAfter :: X () -> X ()
removeEmptyWorkspaceAfter = removeEmptyWorkspaceAfterExcept []
-- | Like 'removeEmptyWorkspaceAfter' but use a list of sticky workspaces,
-- whose entries will never be removed.
removeEmptyWorkspaceAfterExcept :: [String] -> X () -> X ()
removeEmptyWorkspaceAfterExcept sticky f = do
before <- gets (currentTag . windowset)
f
after <- gets (currentTag . windowset)
when (before/=after && before `notElem` sticky) $ removeEmptyWorkspaceByTag before
isEmpty :: String -> X Bool
isEmpty t = do wsl <- gets $ workspaces . windowset
let mws = find (\ws -> tag ws == t) wsl
return $ maybe True (isNothing . stack) mws
addHiddenWorkspace' :: i -> l -> StackSet i l a sid sd -> StackSet i l a sid sd
addHiddenWorkspace' newtag l s@(StackSet { hidden = ws }) = s { hidden = Workspace newtag l Nothing:ws }
removeWorkspace' :: (Eq i) => i -> StackSet i l a sid sd -> StackSet i l a sid sd
removeWorkspace' torem s@(StackSet { current = scr@(Screen { workspace = wc })
, hidden = (w:ws) })
| tag w == torem = s { current = scr { workspace = wc { stack = meld (stack w) (stack wc) } }
, hidden = ws }
where meld Nothing Nothing = Nothing
meld x Nothing = x
meld Nothing x = x
meld (Just x) (Just y) = differentiate (integrate x ++ integrate y)
removeWorkspace' _ s = s
| markus1189/xmonad-contrib-710 | XMonad/Actions/DynamicWorkspaces.hs | Haskell | bsd-3-clause | 8,317 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedStrings #-}
#if __GLASGOW_HASKELL__ >= 800
{-# OPTIONS_GHC -Wno-redundant-constraints #-}
#endif
-- | Execute commands within the properly configured Stack
-- environment.
module Stack.Exec where
import Control.Monad.IO.Unlift
import Control.Monad.Logger
import Stack.Types.Config
import System.Process.Log
import Data.Streaming.Process (ProcessExitedUnsuccessfully(..))
import System.Exit
import System.Process.Run (callProcess, callProcessObserveStdout, Cmd(..))
#ifdef WINDOWS
import System.Process.Read (EnvOverride)
#else
import qualified System.Process.PID1 as PID1
import System.Process.Read (EnvOverride, envHelper, preProcess)
#endif
-- | Default @EnvSettings@ which includes locals and GHC_PACKAGE_PATH
defaultEnvSettings :: EnvSettings
defaultEnvSettings = EnvSettings
{ esIncludeLocals = True
, esIncludeGhcPackagePath = True
, esStackExe = True
, esLocaleUtf8 = False
}
-- | Environment settings which do not embellish the environment
plainEnvSettings :: EnvSettings
plainEnvSettings = EnvSettings
{ esIncludeLocals = False
, esIncludeGhcPackagePath = False
, esStackExe = False
, esLocaleUtf8 = False
}
-- | Execute a process within the Stack configured environment.
--
-- Execution will not return, because either:
--
-- 1) On non-windows, execution is taken over by execv of the
-- sub-process. This allows signals to be propagated (#527)
--
-- 2) On windows, an 'ExitCode' exception will be thrown.
exec :: (MonadUnliftIO m, MonadLogger m)
=> EnvOverride -> String -> [String] -> m b
#ifdef WINDOWS
exec = execSpawn
#else
exec menv cmd0 args = do
cmd <- preProcess Nothing menv cmd0
$withProcessTimeLog cmd args $
liftIO $ PID1.run cmd args (envHelper menv)
#endif
-- | Like 'exec', but does not use 'execv' on non-windows. This way, there
-- is a sub-process, which is helpful in some cases (#1306)
--
-- This function only exits by throwing 'ExitCode'.
execSpawn :: (MonadUnliftIO m, MonadLogger m)
=> EnvOverride -> String -> [String] -> m b
execSpawn menv cmd0 args = do
e <- $withProcessTimeLog cmd0 args $
try (callProcess (Cmd Nothing cmd0 menv args))
liftIO $ case e of
Left (ProcessExitedUnsuccessfully _ ec) -> exitWith ec
Right () -> exitSuccess
execObserve :: (MonadUnliftIO m, MonadLogger m)
=> EnvOverride -> String -> [String] -> m String
execObserve menv cmd0 args = do
e <- $withProcessTimeLog cmd0 args $
try (callProcessObserveStdout (Cmd Nothing cmd0 menv args))
case e of
Left (ProcessExitedUnsuccessfully _ ec) -> liftIO $ exitWith ec
Right s -> return s
| martin-kolinek/stack | src/Stack/Exec.hs | Haskell | bsd-3-clause | 2,839 |
{-# language CPP #-}
-- | = Name
--
-- VK_EXT_global_priority - device extension
--
-- == VK_EXT_global_priority
--
-- [__Name String__]
-- @VK_EXT_global_priority@
--
-- [__Extension Type__]
-- Device extension
--
-- [__Registered Extension Number__]
-- 175
--
-- [__Revision__]
-- 2
--
-- [__Extension and Version Dependencies__]
--
-- - Requires Vulkan 1.0
--
-- [__Deprecation state__]
--
-- - /Promoted/ to @VK_KHR_global_priority@ extension
--
-- [__Contact__]
--
-- - Andres Rodriguez
-- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_EXT_global_priority] @lostgoat%0A<<Here describe the issue or question you have about the VK_EXT_global_priority extension>> >
--
-- == Other Extension Metadata
--
-- [__Last Modified Date__]
-- 2017-10-06
--
-- [__IP Status__]
-- No known IP claims.
--
-- [__Contributors__]
--
-- - Andres Rodriguez, Valve
--
-- - Pierre-Loup Griffais, Valve
--
-- - Dan Ginsburg, Valve
--
-- - Mitch Singer, AMD
--
-- == Description
--
-- In Vulkan, users can specify device-scope queue priorities. In some
-- cases it may be useful to extend this concept to a system-wide scope.
-- This extension provides a mechanism for callers to set their system-wide
-- priority. The default queue priority is
-- 'Vulkan.Extensions.VK_KHR_global_priority.QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT'.
--
-- The driver implementation will attempt to skew hardware resource
-- allocation in favour of the higher-priority task. Therefore,
-- higher-priority work may retain similar latency and throughput
-- characteristics even if the system is congested with lower priority
-- work.
--
-- The global priority level of a queue shall take precedence over the
-- per-process queue priority
-- ('Vulkan.Core10.Device.DeviceQueueCreateInfo'::@pQueuePriorities@).
--
-- Abuse of this feature may result in starving the rest of the system from
-- hardware resources. Therefore, the driver implementation may deny
-- requests to acquire a priority above the default priority
-- ('Vulkan.Extensions.VK_KHR_global_priority.QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT')
-- if the caller does not have sufficient privileges. In this scenario
-- 'ERROR_NOT_PERMITTED_EXT' is returned.
--
-- The driver implementation may fail the queue allocation request if
-- resources required to complete the operation have been exhausted (either
-- by the same process or a different process). In this scenario
-- 'Vulkan.Core10.Enums.Result.ERROR_INITIALIZATION_FAILED' is returned.
--
-- == New Structures
--
-- - Extending 'Vulkan.Core10.Device.DeviceQueueCreateInfo':
--
-- - 'DeviceQueueGlobalPriorityCreateInfoEXT'
--
-- == New Enums
--
-- - 'QueueGlobalPriorityEXT'
--
-- == New Enum Constants
--
-- - 'EXT_GLOBAL_PRIORITY_EXTENSION_NAME'
--
-- - 'EXT_GLOBAL_PRIORITY_SPEC_VERSION'
--
-- - Extending 'Vulkan.Core10.Enums.Result.Result':
--
-- - 'ERROR_NOT_PERMITTED_EXT'
--
-- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType':
--
-- - 'STRUCTURE_TYPE_DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_EXT'
--
-- == Version History
--
-- - Revision 2, 2017-11-03 (Andres Rodriguez)
--
-- - Fixed VkQueueGlobalPriorityEXT missing _EXT suffix
--
-- - Revision 1, 2017-10-06 (Andres Rodriguez)
--
-- - First version.
--
-- == See Also
--
-- 'DeviceQueueGlobalPriorityCreateInfoEXT', 'QueueGlobalPriorityEXT'
--
-- == Document Notes
--
-- For more information, see the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_EXT_global_priority Vulkan Specification>
--
-- This page is a generated document. Fixes and changes should be made to
-- the generator scripts, not directly.
module Vulkan.Extensions.VK_EXT_global_priority ( pattern STRUCTURE_TYPE_DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_EXT
, pattern ERROR_NOT_PERMITTED_EXT
, QueueGlobalPriorityEXT
, DeviceQueueGlobalPriorityCreateInfoEXT
, EXT_GLOBAL_PRIORITY_SPEC_VERSION
, pattern EXT_GLOBAL_PRIORITY_SPEC_VERSION
, EXT_GLOBAL_PRIORITY_EXTENSION_NAME
, pattern EXT_GLOBAL_PRIORITY_EXTENSION_NAME
, DeviceQueueGlobalPriorityCreateInfoKHR(..)
, QueueGlobalPriorityKHR(..)
) where
import Data.String (IsString)
import Vulkan.Extensions.VK_KHR_global_priority (DeviceQueueGlobalPriorityCreateInfoKHR)
import Vulkan.Extensions.VK_KHR_global_priority (QueueGlobalPriorityKHR)
import Vulkan.Core10.Enums.Result (Result(ERROR_NOT_PERMITTED_KHR))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_KHR))
import Vulkan.Extensions.VK_KHR_global_priority (DeviceQueueGlobalPriorityCreateInfoKHR(..))
import Vulkan.Extensions.VK_KHR_global_priority (QueueGlobalPriorityKHR(..))
-- No documentation found for TopLevel "VK_STRUCTURE_TYPE_DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_EXT"
pattern STRUCTURE_TYPE_DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_EXT = STRUCTURE_TYPE_DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_KHR
-- No documentation found for TopLevel "VK_ERROR_NOT_PERMITTED_EXT"
pattern ERROR_NOT_PERMITTED_EXT = ERROR_NOT_PERMITTED_KHR
-- No documentation found for TopLevel "VkQueueGlobalPriorityEXT"
type QueueGlobalPriorityEXT = QueueGlobalPriorityKHR
-- No documentation found for TopLevel "VkDeviceQueueGlobalPriorityCreateInfoEXT"
type DeviceQueueGlobalPriorityCreateInfoEXT = DeviceQueueGlobalPriorityCreateInfoKHR
type EXT_GLOBAL_PRIORITY_SPEC_VERSION = 2
-- No documentation found for TopLevel "VK_EXT_GLOBAL_PRIORITY_SPEC_VERSION"
pattern EXT_GLOBAL_PRIORITY_SPEC_VERSION :: forall a . Integral a => a
pattern EXT_GLOBAL_PRIORITY_SPEC_VERSION = 2
type EXT_GLOBAL_PRIORITY_EXTENSION_NAME = "VK_EXT_global_priority"
-- No documentation found for TopLevel "VK_EXT_GLOBAL_PRIORITY_EXTENSION_NAME"
pattern EXT_GLOBAL_PRIORITY_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern EXT_GLOBAL_PRIORITY_EXTENSION_NAME = "VK_EXT_global_priority"
| expipiplus1/vulkan | src/Vulkan/Extensions/VK_EXT_global_priority.hs | Haskell | bsd-3-clause | 6,417 |
{-# LANGUAGE DeriveGeneric #-}
module Crawl.Stats.Shield where
import qualified Data.Csv as CSV
import GHC.Generics (Generic)
import qualified Data.Default as Default
import qualified Crawl.Stats.Named as Named
data Shield = Shield {
name :: String,
block :: Integer,
evPenalty :: Integer,
dexContrib :: Integer,
strContrib :: Integer
} deriving (Generic, Eq)
instance CSV.FromNamedRecord Shield
instance Named.Named Shield where
name = name
instance Default.Default Shield where
def = Shield "none" 0 0 0 0
| jfrikker/crawlstats | src/Crawl/Stats/Shield.hs | Haskell | bsd-3-clause | 529 |
-- Config.hs
{-# OPTIONS_GHC -Wall #-}
module Lab2.Config( cL
, cN
, hilbertDim
, imageSize
) where
hilbertDim :: Int
hilbertDim = 16 -- for max value of 65535
cL, cN :: Int
cL = 3
cN = 4
imageSize :: Num a => a
imageSize = 500
| ghorn/cs240h-class | Lab2/Config.hs | Haskell | bsd-3-clause | 305 |
module Data.Wavelets.ReconstructionSpec (main, spec) where
import Test.Hspec
import Data.Wavelets.Reconstruction
import Data.Wavelets
import System.IO
import qualified Data.Vector.Storable as V
{-| The test waveletData below was transformed into several of the result dataFiles |-}
-- 3 sinusoids added together to make an interesting data set that is easy to understand
testWaveletData :: [Double]
testWaveletData = [ ((sin (pi*t*2))+ (sin (pi * t * 2.1) + (sin (pi * t * 2.002))))* 12 | t <- [1 .. 1000] ]
impulse = replicate 499 1
++ replicate 1 100
++ replicate 500 1
impulseAvg = (1.3956047904191924)
waveletHaar_packer_separate_testStub :: IO [[Double]]
waveletHaar_packer_separate_testStub = do
(read `fmap` readFile "./test/Data/haar_separate.tst" )
testWaveletHaar_PackerSeparate = dwt 12 haar wp_separate impulse
compareWaveletHaarResults = do
let rslt = testWaveletHaar_PackerSeparate
ctrl <- waveletHaar_packer_separate_testStub
return $ (length rslt ) == (length ctrl)
testReconstructTimeSeries = reconstructTimeSeries (12-n) haar wp_separate $ drop n testWaveletHaar_PackerSeparate
where n = 3
main :: IO ()
main = do
haar_separate_test_data <- waveletHaar_packer_separate_testStub
hspec $ spec
-- | Have to bring in test data from a file to test this
spec :: Spec
spec = do
describe "reconstructTimeSeries" $ do
it "shouldReturn a scaled wavelet" $ do
let tstData = testWaveletData
tst <- compareWaveletHaarResults
tst `shouldBe` True
| smurphy8/wavelets | test/Data/Wavelets/ReconstructionSpec.hs | Haskell | bsd-3-clause | 1,533 |
{-# LANGUAGE RankNTypes #-}
module Parser (parseTerm) where
import Syntax
import Text.Parsec hiding(State)
import Text.Parsec.String
import qualified Text.Parsec.Token as P
import Text.Parsec.Language
import Data.Char
import Control.Monad
import Control.Applicative((<*))
{- --------------------------------------------------------
インデックスを付けるための機構
-------------------------------------------------------- -}
data Context = Ctx {
depth :: Int,
binding :: [(Char, Int)],
tyDepth :: Int,
tyBinding :: [(Char, Int)]
}
updateCtx :: Context -> Char -> Context
updateCtx (Ctx d b tyD tyB) c = (Ctx (d+1) ((c, d):b) tyD tyB)
updateTyCtx :: Context -> Char -> Context
updateTyCtx (Ctx d b tyD tyB) c = (Ctx d b (tyD+1) ((c, tyD):tyB))
freeVar :: Char -> Int
freeVar c = (ord c) - (ord 'a')
freshTyVar :: Char -> Int
freshTyVar c = (ord c) - (ord 'A')
{- 外側から小さい値を使う de Bruijin レベルを使う.
束縛変数ならばそのまま値を返してよく,
自由変数ならば深さの分だけシフトしてインデックスとする.-}
index :: Context -> Char -> Int
index (Ctx depth bind _ _) v =
case lookup v bind of
Just d -> d
Nothing -> depth + freeVar v
tyIndex :: Context -> Char -> Int
tyIndex (Ctx _ _ depth bind) v =
case lookup v bind of
Just d -> d
Nothing -> depth + freshTyVar v
{- --------------------------------------------------------
パーサー
-------------------------------------------------------- -}
parseTerm :: String -> Check Term
parseTerm input =
case parse (term $ Ctx 0 [] 0 []) "" input of
Left er -> Left $ show er
Right r -> Right r
def :: LanguageDef st
def = emptyDef {
P.opLetter = oneOf "\\:->",
P.reservedOpNames = ["\\", ":", "->"],
P.reservedNames = ["if", "then", "else", "true", "false", "Bool"]
}
lexer :: P.TokenParser st
lexer = P.makeTokenParser def
operator :: Parser String
operator = P.operator lexer
identifier :: Parser String
identifier = P.identifier lexer
var :: Parser Char
var = do
i <- identifier
if length i == 1 && head i `elem` ['a'..'z']
then return $ head i
else fail "variable must be one lower character"
tyVar :: Parser Char
tyVar = do
i <- identifier
if length i == 1 && head i `elem` ['A'..'Z']
then return $ head i
else fail "variable must be one upper character"
reservedOp :: String -> Parser ()
reservedOp = P.reservedOp lexer
parens :: forall a. Parser a -> Parser a
parens = P.parens lexer
brackets :: forall a. Parser a -> Parser a
brackets = P.brackets lexer
braces :: forall a. Parser a -> Parser a
braces = P.braces lexer
whiteSpace :: Parser ()
whiteSpace = P.whiteSpace lexer
symbol :: String -> Parser String
symbol = P.symbol lexer
term :: Context -> Parser Term
term c = do
whiteSpace
t <- termBody c
eof >> (return t)
termBody :: Context -> Parser Term
termBody c = try (abst c)
<|> try (tyAbst c)
<|> try (generalApp c)
<|> termif c
generalApp :: Context -> Parser Term
generalApp c = unit c >>= appChain c
appChain :: Context -> Term -> Parser Term
appChain c t = try (do t' <- unit c
appChain c (TmApp t t'))
<|> try (do t' <- brackets (tyAnnot c)
appChain c (TmTyApp t t'))
<|> return t
abst :: Context -> Parser Term
abst c = do
a <- (reservedOp "\\") >> var
ty <- optionMaybe (reservedOp ":" >> tyAnnot c)
t <- termBody (updateCtx c a)
case ty of Just ty' -> return $ TmAbs a ty' t
Nothing -> fail "annotate type"
unit :: Context -> Parser Term
unit c = try (liftM2 (foldl TmProj) (unit_rec c) (many $ symbol "." >> identifier))
<|> unit_rec c
unit_rec :: Context -> Parser Term
unit_rec c = parens (termBody c)
<|> try (liftM TmRcd (braces $ record c `sepBy1` symbol ","))
<|> try (symbol "true" >> return TmTrue)
<|> try (symbol "false" >> return TmFalse)
<|> do a <- var
return $ TmVar (index c a) a
record :: Context -> Parser (String, Term)
record c = liftM2 (,) (identifier <* symbol "=") (termBody c)
termif :: Context -> Parser Term
termif c = do
p <- try (symbol "if") >> termBody c
t <- try (symbol "then") >> termBody c
f <- try (symbol "else") >> termBody c
return $ TmIf p t f
tyAnnot :: Context -> Parser TyTerm
tyAnnot c = tyunit c `chainl1` (reservedOp "->" >> return TyArr)
tyunit :: Context -> Parser TyTerm
tyunit c = try (symbol "Bool" >> return TyBool)
<|> try (symbol "Top" >> return TyTop)
<|> try (parens $ tyAnnot c)
<|> try (liftM TyRcd (braces $ tyRecord c `sepBy1` symbol ","))
<|> do v <- tyVar
return $ TyVar v (tyIndex c v)
tyRecord :: Context -> Parser (String, TyTerm)
tyRecord c = liftM2 (,) (identifier <* symbol ":") (tyAnnot c)
tyAbst :: Context -> Parser Term
tyAbst c = do
v <- (reservedOp "\\") >> tyVar
t <- termBody (updateTyCtx c v)
return $ TmTyAbs v t
| yu-i9/SystemF | parser/Parser.hs | Haskell | bsd-3-clause | 5,199 |
module Tests.Regress
( testTree -- :: TestTree
) where
import Test.Tasty
import qualified Tests.Regress.Issue13 as Issue13
import qualified Tests.Regress.FlatTerm as FlatTerm
--------------------------------------------------------------------------------
-- Tests and properties
testTree :: TestTree
testTree = testGroup "Regression tests"
[ FlatTerm.testTree
, Issue13.testTree
]
| arianvp/binary-serialise-cbor | tests/Tests/Regress.hs | Haskell | bsd-3-clause | 407 |
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TemplateHaskell #-}
module Web.Zwaluw (
-- * Types
Router, (:-)(..), (<>), (.~)
-- * Running routers
, parse, unparse
, parse1, unparse1
-- * Router combinators
, pure, xmap, xmaph
, val, readshow, lit, push
, opt, duck, satisfy, rFilter, printAs
, manyr, somer, chainr, chainr1
, manyl, somel, chainl, chainl1
-- * Built-in routers
, int, integer, string, char, digit, hexDigit
, (/), part
, rNil, rCons, rList, rListSep
, rPair
, rLeft, rRight, rEither
, rNothing, rJust, rMaybe
, rTrue, rFalse
) where
import Prelude hiding ((.), id, (/))
import Control.Monad (guard)
import Control.Category
import Data.Monoid
import Data.Char (isDigit, isHexDigit, intToDigit, digitToInt)
import Web.Zwaluw.Core
import Web.Zwaluw.TH
infixr 8 <>
-- | Infix operator for 'mappend'.
(<>) :: Monoid m => m -> m -> m
(<>) = mappend
-- | Make a router optional.
opt :: Router r r -> Router r r
opt = (id <>)
-- | Repeat a router zero or more times, combining the results from left to right.
manyr :: Router r r -> Router r r
manyr = opt . somer
-- | Repeat a router one or more times, combining the results from left to right.
somer :: Router r r -> Router r r
somer p = p . manyr p
-- | @chainr p op@ repeats @p@ zero or more times, separated by @op@.
-- The result is a right associative fold of the results of @p@ with the results of @op@.
chainr :: Router r r -> Router r r -> Router r r
chainr p op = opt (manyr (p .~ op) . p)
-- | @chainr1 p op@ repeats @p@ one or more times, separated by @op@.
-- The result is a right associative fold of the results of @p@ with the results of @op@.
chainr1 :: Router r (a :- r) -> Router (a :- a :- r) (a :- r) -> Router r (a :- r)
chainr1 p op = manyr (duck1 p .~ op) . p
-- | Repeat a router zero or more times, combining the results from right to left.
manyl :: Router r r -> Router r r
manyl = opt . somel
-- | Repeat a router one or more times, combining the results from right to left.
somel :: Router r r -> Router r r
somel p = p .~ manyl p
-- | @chainl1 p op@ repeats @p@ zero or more times, separated by @op@.
-- The result is a left associative fold of the results of @p@ with the results of @op@.
chainl :: Router r r -> Router r r -> Router r r
chainl p op = opt (p .~ manyl (op . p))
-- | @chainl1 p op@ repeats @p@ one or more times, separated by @op@.
-- The result is a left associative fold of the results of @p@ with the results of @op@.
chainl1 :: Router r (a :- r) -> Router (a :- a :- r) (a :- r) -> Router r (a :- r)
chainl1 p op = p .~ manyl (op . duck p)
-- | Filtering on routers.
rFilter :: (a -> Bool) -> Router () (a :- ()) -> Router r (a :- r)
rFilter p r = val
(\s -> [ (a, s') | (f, s') <- prs r s, let a = hhead (f ()), p a ])
(\a -> [ f | p a, (f, _) <- ser r (a :- ()) ])
-- | Push a value on the stack (during parsing, pop it from the stack when serializing).
push :: Eq a => a -> Router r (a :- r)
push a = pure (a :-) (\(a' :- t) -> guard (a' == a) >> Just t)
-- | Routes any value that has a Show and Read instance.
readshow :: (Show a, Read a) => Router r (a :- r)
readshow = val reads (return . shows)
-- | Routes any @Int@.
int :: Router r (Int :- r)
int = readshow
-- | Routes any @Integer@.
integer :: Router r (Integer :- r)
integer = readshow
-- | Routes any string.
string :: Router r (String :- r)
string = val (\s -> [(s, "")]) (return . (++))
-- | Routes one character satisfying the given predicate.
satisfy :: (Char -> Bool) -> Router r (Char :- r)
satisfy p = val
(\s -> [ (c, cs) | c:cs <- [s], p c ])
(\c -> [ (c :) | p c ])
-- | Routes one character.
char :: Router r (Char :- r)
char = satisfy (const True)
-- | Routes one decimal digit.
digit :: Router r (Int :- r)
digit = xmaph digitToInt (\i -> guard (i >= 0 && i < 10) >> Just (intToDigit i)) (satisfy isDigit)
-- | Routes one hexadecimal digit.
hexDigit :: Router r (Int :- r)
hexDigit = xmaph digitToInt (\i -> guard (i >= 0 && i < 16) >> Just (intToDigit i)) (satisfy isHexDigit)
infixr 9 /
-- | @p \/ q@ is equivalent to @p . \"\/\" . q@.
(/) :: Router b c -> Router a b -> Router a c
(/) f g = f . lit "/" . g
-- | Routes part of a URL, i.e. a String not containing @\'\/\'@ or @\'\?\'@.
part :: Router r (String :- r)
part = rList (satisfy (\c -> c /= '/' && c /= '?'))
rNil :: Router r ([a] :- r)
rNil = pure ([] :-) $ \(xs :- t) -> do [] <- Just xs; Just t
rCons :: Router (a :- [a] :- r) ([a] :- r)
rCons = pure (arg (arg (:-)) (:)) $ \(xs :- t) -> do a:as <- Just xs; Just (a :- as :- t)
-- | Converts a router for a value @a@ to a router for a list of @a@.
rList :: Router r (a :- r) -> Router r ([a] :- r)
rList r = manyr (rCons . duck1 r) . rNil
-- | Converts a router for a value @a@ to a router for a list of @a@, with a separator.
rListSep :: Router r (a :- r) -> Router ([a] :- r) ([a] :- r) -> Router r ([a] :- r)
rListSep r sep = chainr (rCons . duck1 r) sep . rNil
rPair :: Router (f :- s :- r) ((f, s) :- r)
rPair = pure (arg (arg (:-)) (,)) $ \(ab :- t) -> do (a,b) <- Just ab; Just (a :- b :- t)
$(deriveRouters ''Either)
rLeft :: Router (a :- r) (Either a b :- r)
rRight :: Router (b :- r) (Either a b :- r)
-- | Combines a router for a value @a@ and a router for a value @b@ into a router for @Either a b@.
rEither :: Router r (a :- r) -> Router r (b :- r) -> Router r (Either a b :- r)
rEither l r = rLeft . l <> rRight . r
$(deriveRouters ''Maybe)
rNothing :: Router r (Maybe a :- r)
rJust :: Router (a :- r) (Maybe a :- r)
-- | Converts a router for a value @a@ to a router for a @Maybe a@.
rMaybe :: Router r (a :- r) -> Router r (Maybe a :- r)
rMaybe r = rJust . r <> rNothing
$(deriveRouters ''Bool)
rTrue :: Router r (Bool :- r)
rFalse :: Router r (Bool :- r) | MedeaMelana/Zwaluw | Web/Zwaluw.hs | Haskell | bsd-3-clause | 5,875 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1998
\section[DataCon]{@DataCon@: Data Constructors}
-}
{-# LANGUAGE CPP, DeriveDataTypeable #-}
module DataCon (
-- * Main data types
DataCon, DataConRep(..),
SrcStrictness(..), SrcUnpackedness(..),
HsSrcBang(..), HsImplBang(..),
StrictnessMark(..),
ConTag,
-- ** Equality specs
EqSpec, mkEqSpec, eqSpecTyVar, eqSpecType,
eqSpecPair, eqSpecPreds,
substEqSpec, filterEqSpec,
-- ** Field labels
FieldLbl(..), FieldLabel, FieldLabelString,
-- ** Type construction
mkDataCon, buildAlgTyCon, fIRST_TAG,
-- ** Type deconstruction
dataConRepType, dataConSig, dataConInstSig, dataConFullSig,
dataConName, dataConIdentity, dataConTag, dataConTyCon,
dataConOrigTyCon, dataConUserType,
dataConUnivTyVars, dataConUnivTyBinders,
dataConExTyVars, dataConExTyBinders,
dataConAllTyVars,
dataConEqSpec, dataConTheta,
dataConStupidTheta,
dataConInstArgTys, dataConOrigArgTys, dataConOrigResTy,
dataConInstOrigArgTys, dataConRepArgTys,
dataConFieldLabels, dataConFieldType,
dataConSrcBangs,
dataConSourceArity, dataConRepArity, dataConRepRepArity,
dataConIsInfix,
dataConWorkId, dataConWrapId, dataConWrapId_maybe,
dataConImplicitTyThings,
dataConRepStrictness, dataConImplBangs, dataConBoxer,
splitDataProductType_maybe,
-- ** Predicates on DataCons
isNullarySrcDataCon, isNullaryRepDataCon, isTupleDataCon, isUnboxedTupleCon,
isVanillaDataCon, classDataCon, dataConCannotMatch,
isBanged, isMarkedStrict, eqHsBang, isSrcStrict, isSrcUnpacked,
specialPromotedDc, isLegacyPromotableDataCon, isLegacyPromotableTyCon,
-- ** Promotion related functions
promoteDataCon
) where
#include "HsVersions.h"
import {-# SOURCE #-} MkId( DataConBoxer )
import Type
import ForeignCall ( CType )
import Coercion
import Unify
import TyCon
import FieldLabel
import Class
import Name
import PrelNames
import Var
import Outputable
import ListSetOps
import Util
import BasicTypes
import FastString
import Module
import Binary
import UniqFM
import qualified Data.Data as Data
import Data.Char
import Data.Word
import Data.List( mapAccumL, find )
{-
Data constructor representation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider the following Haskell data type declaration
data T = T !Int ![Int]
Using the strictness annotations, GHC will represent this as
data T = T Int# [Int]
That is, the Int has been unboxed. Furthermore, the Haskell source construction
T e1 e2
is translated to
case e1 of { I# x ->
case e2 of { r ->
T x r }}
That is, the first argument is unboxed, and the second is evaluated. Finally,
pattern matching is translated too:
case e of { T a b -> ... }
becomes
case e of { T a' b -> let a = I# a' in ... }
To keep ourselves sane, we name the different versions of the data constructor
differently, as follows.
Note [Data Constructor Naming]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Each data constructor C has two, and possibly up to four, Names associated with it:
OccName Name space Name of Notes
---------------------------------------------------------------------------
The "data con itself" C DataName DataCon In dom( GlobalRdrEnv )
The "worker data con" C VarName Id The worker
The "wrapper data con" $WC VarName Id The wrapper
The "newtype coercion" :CoT TcClsName TyCon
EVERY data constructor (incl for newtypes) has the former two (the
data con itself, and its worker. But only some data constructors have a
wrapper (see Note [The need for a wrapper]).
Each of these three has a distinct Unique. The "data con itself" name
appears in the output of the renamer, and names the Haskell-source
data constructor. The type checker translates it into either the wrapper Id
(if it exists) or worker Id (otherwise).
The data con has one or two Ids associated with it:
The "worker Id", is the actual data constructor.
* Every data constructor (newtype or data type) has a worker
* The worker is very like a primop, in that it has no binding.
* For a *data* type, the worker *is* the data constructor;
it has no unfolding
* For a *newtype*, the worker has a compulsory unfolding which
does a cast, e.g.
newtype T = MkT Int
The worker for MkT has unfolding
\\(x:Int). x `cast` sym CoT
Here CoT is the type constructor, witnessing the FC axiom
axiom CoT : T = Int
The "wrapper Id", \$WC, goes as follows
* Its type is exactly what it looks like in the source program.
* It is an ordinary function, and it gets a top-level binding
like any other function.
* The wrapper Id isn't generated for a data type if there is
nothing for the wrapper to do. That is, if its defn would be
\$wC = C
Note [The need for a wrapper]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Why might the wrapper have anything to do? Two reasons:
* Unboxing strict fields (with -funbox-strict-fields)
data T = MkT !(Int,Int)
\$wMkT :: (Int,Int) -> T
\$wMkT (x,y) = MkT x y
Notice that the worker has two fields where the wapper has
just one. That is, the worker has type
MkT :: Int -> Int -> T
* Equality constraints for GADTs
data T a where { MkT :: a -> T [a] }
The worker gets a type with explicit equality
constraints, thus:
MkT :: forall a b. (a=[b]) => b -> T a
The wrapper has the programmer-specified type:
\$wMkT :: a -> T [a]
\$wMkT a x = MkT [a] a [a] x
The third argument is a coercion
[a] :: [a]~[a]
INVARIANT: the dictionary constructor for a class
never has a wrapper.
A note about the stupid context
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Data types can have a context:
data (Eq a, Ord b) => T a b = T1 a b | T2 a
and that makes the constructors have a context too
(notice that T2's context is "thinned"):
T1 :: (Eq a, Ord b) => a -> b -> T a b
T2 :: (Eq a) => a -> T a b
Furthermore, this context pops up when pattern matching
(though GHC hasn't implemented this, but it is in H98, and
I've fixed GHC so that it now does):
f (T2 x) = x
gets inferred type
f :: Eq a => T a b -> a
I say the context is "stupid" because the dictionaries passed
are immediately discarded -- they do nothing and have no benefit.
It's a flaw in the language.
Up to now [March 2002] I have put this stupid context into the
type of the "wrapper" constructors functions, T1 and T2, but
that turned out to be jolly inconvenient for generics, and
record update, and other functions that build values of type T
(because they don't have suitable dictionaries available).
So now I've taken the stupid context out. I simply deal with
it separately in the type checker on occurrences of a
constructor, either in an expression or in a pattern.
[May 2003: actually I think this decision could evasily be
reversed now, and probably should be. Generics could be
disabled for types with a stupid context; record updates now
(H98) needs the context too; etc. It's an unforced change, so
I'm leaving it for now --- but it does seem odd that the
wrapper doesn't include the stupid context.]
[July 04] With the advent of generalised data types, it's less obvious
what the "stupid context" is. Consider
C :: forall a. Ord a => a -> a -> T (Foo a)
Does the C constructor in Core contain the Ord dictionary? Yes, it must:
f :: T b -> Ordering
f = /\b. \x:T b.
case x of
C a (d:Ord a) (p:a) (q:a) -> compare d p q
Note that (Foo a) might not be an instance of Ord.
************************************************************************
* *
\subsection{Data constructors}
* *
************************************************************************
-}
-- | A data constructor
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnClose','ApiAnnotation.AnnComma'
-- For details on above see note [Api annotations] in ApiAnnotation
data DataCon
= MkData {
dcName :: Name, -- This is the name of the *source data con*
-- (see "Note [Data Constructor Naming]" above)
dcUnique :: Unique, -- Cached from Name
dcTag :: ConTag, -- ^ Tag, used for ordering 'DataCon's
-- Running example:
--
-- *** As declared by the user
-- data T a where
-- MkT :: forall x y. (x~y,Ord x) => x -> y -> T (x,y)
-- *** As represented internally
-- data T a where
-- MkT :: forall a. forall x y. (a~(x,y),x~y,Ord x) => x -> y -> T a
--
-- The next six fields express the type of the constructor, in pieces
-- e.g.
--
-- dcUnivTyVars = [a]
-- dcExTyVars = [x,y]
-- dcEqSpec = [a~(x,y)]
-- dcOtherTheta = [x~y, Ord x]
-- dcOrigArgTys = [x,y]
-- dcRepTyCon = T
-- In general, the dcUnivTyVars are NOT NECESSARILY THE SAME AS THE TYVARS
-- FOR THE PARENT TyCon. (This is a change (Oct05): previously, vanilla
-- datacons guaranteed to have the same type variables as their parent TyCon,
-- but that seems ugly.)
dcVanilla :: Bool, -- True <=> This is a vanilla Haskell 98 data constructor
-- Its type is of form
-- forall a1..an . t1 -> ... tm -> T a1..an
-- No existentials, no coercions, nothing.
-- That is: dcExTyVars = dcEqSpec = dcOtherTheta = []
-- NB 1: newtypes always have a vanilla data con
-- NB 2: a vanilla constructor can still be declared in GADT-style
-- syntax, provided its type looks like the above.
-- The declaration format is held in the TyCon (algTcGadtSyntax)
-- Universally-quantified type vars [a,b,c]
-- INVARIANT: length matches arity of the dcRepTyCon
-- INVARIANT: result type of data con worker is exactly (T a b c)
dcUnivTyVars :: [TyVar], -- Two linked fields
dcUnivTyBinders :: [TyBinder], -- see Note [TyBinders in DataCons]
-- Existentially-quantified type vars [x,y]
dcExTyVars :: [TyVar], -- Two linked fields
dcExTyBinders :: [TyBinder], -- see Note [TyBinders in DataCons]
-- INVARIANT: the UnivTyVars and ExTyVars all have distinct OccNames
-- Reason: less confusing, and easier to generate IfaceSyn
dcEqSpec :: [EqSpec], -- Equalities derived from the result type,
-- _as written by the programmer_
-- This field allows us to move conveniently between the two ways
-- of representing a GADT constructor's type:
-- MkT :: forall a b. (a ~ [b]) => b -> T a
-- MkT :: forall b. b -> T [b]
-- Each equality is of the form (a ~ ty), where 'a' is one of
-- the universally quantified type variables
-- The next two fields give the type context of the data constructor
-- (aside from the GADT constraints,
-- which are given by the dcExpSpec)
-- In GADT form, this is *exactly* what the programmer writes, even if
-- the context constrains only universally quantified variables
-- MkT :: forall a b. (a ~ b, Ord b) => a -> T a b
dcOtherTheta :: ThetaType, -- The other constraints in the data con's type
-- other than those in the dcEqSpec
dcStupidTheta :: ThetaType, -- The context of the data type declaration
-- data Eq a => T a = ...
-- or, rather, a "thinned" version thereof
-- "Thinned", because the Report says
-- to eliminate any constraints that don't mention
-- tyvars free in the arg types for this constructor
--
-- INVARIANT: the free tyvars of dcStupidTheta are a subset of dcUnivTyVars
-- Reason: dcStupidTeta is gotten by thinning the stupid theta from the tycon
--
-- "Stupid", because the dictionaries aren't used for anything.
-- Indeed, [as of March 02] they are no longer in the type of
-- the wrapper Id, because that makes it harder to use the wrap-id
-- to rebuild values after record selection or in generics.
dcOrigArgTys :: [Type], -- Original argument types
-- (before unboxing and flattening of strict fields)
dcOrigResTy :: Type, -- Original result type, as seen by the user
-- NB: for a data instance, the original user result type may
-- differ from the DataCon's representation TyCon. Example
-- data instance T [a] where MkT :: a -> T [a]
-- The OrigResTy is T [a], but the dcRepTyCon might be :T123
-- Now the strictness annotations and field labels of the constructor
dcSrcBangs :: [HsSrcBang],
-- See Note [Bangs on data constructor arguments]
--
-- The [HsSrcBang] as written by the programmer.
--
-- Matches 1-1 with dcOrigArgTys
-- Hence length = dataConSourceArity dataCon
dcFields :: [FieldLabel],
-- Field labels for this constructor, in the
-- same order as the dcOrigArgTys;
-- length = 0 (if not a record) or dataConSourceArity.
-- The curried worker function that corresponds to the constructor:
-- It doesn't have an unfolding; the code generator saturates these Ids
-- and allocates a real constructor when it finds one.
dcWorkId :: Id,
-- Constructor representation
dcRep :: DataConRep,
-- Cached
-- dcRepArity == length dataConRepArgTys
dcRepArity :: Arity,
-- dcSourceArity == length dcOrigArgTys
dcSourceArity :: Arity,
-- Result type of constructor is T t1..tn
dcRepTyCon :: TyCon, -- Result tycon, T
dcRepType :: Type, -- Type of the constructor
-- forall a x y. (a~(x,y), x~y, Ord x) =>
-- x -> y -> T a
-- (this is *not* of the constructor wrapper Id:
-- see Note [Data con representation] below)
-- Notice that the existential type parameters come *second*.
-- Reason: in a case expression we may find:
-- case (e :: T t) of
-- MkT x y co1 co2 (d:Ord x) (v:r) (w:F s) -> ...
-- It's convenient to apply the rep-type of MkT to 't', to get
-- forall x y. (t~(x,y), x~y, Ord x) => x -> y -> T t
-- and use that to check the pattern. Mind you, this is really only
-- used in CoreLint.
dcInfix :: Bool, -- True <=> declared infix
-- Used for Template Haskell and 'deriving' only
-- The actual fixity is stored elsewhere
dcPromoted :: TyCon -- The promoted TyCon
-- See Note [Promoted data constructors] in TyCon
}
{- Note [TyBinders in DataCons]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
DataCons and PatSyns store their universal and existential type
variables in a pair of fields, e.g.
dcUnivTyVars :: [TyVar],
dcUnivTyBinders :: [TyBinder],
and similarly dcExTyVars/dcExTyVarBinders
Of these, the former is always redundant:
dcUnivTyVars = [ tv | Named tv _ <- dcUnivTyBinders ]
Specifically:
* The two fields correspond 1-1
* Each TyBinder a Named (no Anons)
* The TyVar in each TyBinder is the same as the TyVar in
the corresponding tyvar in the TyVars list.
* Each Visibilty flag (va, vb, etc) is Invisible or Specified.
None are Visible. (A DataCon is a term-level function; see
Note [No Visible TyBinder in terms] in TyCoRep.)
Why store these fields redundantly? Purely convenience. In most
places in GHC, it's just the TyVars that are needed, so that's what's
returned from, say, dataConFullSig.
Why do we need the TyBinders? So that we can construct the right
type for the DataCon with its foralls attributed the correce visiblity.
That in turn governs whether you can use visible type application
at a call of the data constructor.
-}
data DataConRep
= NoDataConRep -- No wrapper
| DCR { dcr_wrap_id :: Id -- Takes src args, unboxes/flattens,
-- and constructs the representation
, dcr_boxer :: DataConBoxer
, dcr_arg_tys :: [Type] -- Final, representation argument types,
-- after unboxing and flattening,
-- and *including* all evidence args
, dcr_stricts :: [StrictnessMark] -- 1-1 with dcr_arg_tys
-- See also Note [Data-con worker strictness] in MkId.hs
, dcr_bangs :: [HsImplBang] -- The actual decisions made (including failures)
-- about the original arguments; 1-1 with orig_arg_tys
-- See Note [Bangs on data constructor arguments]
}
-- Algebraic data types always have a worker, and
-- may or may not have a wrapper, depending on whether
-- the wrapper does anything.
--
-- Data types have a worker with no unfolding
-- Newtypes just have a worker, which has a compulsory unfolding (just a cast)
-- _Neither_ the worker _nor_ the wrapper take the dcStupidTheta dicts as arguments
-- The wrapper (if it exists) takes dcOrigArgTys as its arguments
-- The worker takes dataConRepArgTys as its arguments
-- If the worker is absent, dataConRepArgTys is the same as dcOrigArgTys
-- The 'NoDataConRep' case is important
-- Not only is this efficient,
-- but it also ensures that the wrapper is replaced
-- by the worker (because it *is* the worker)
-- even when there are no args. E.g. in
-- f (:) x
-- the (:) *is* the worker.
-- This is really important in rule matching,
-- (We could match on the wrappers,
-- but that makes it less likely that rules will match
-- when we bring bits of unfoldings together.)
-------------------------
-- | Bangs on data constructor arguments as the user wrote them in the
-- source code.
--
-- (HsSrcBang _ SrcUnpack SrcLazy) and
-- (HsSrcBang _ SrcUnpack NoSrcStrict) (without StrictData) makes no sense, we
-- emit a warning (in checkValidDataCon) and treat it like
-- (HsSrcBang _ NoSrcUnpack SrcLazy)
data HsSrcBang =
HsSrcBang (Maybe SourceText) -- Note [Pragma source text] in BasicTypes
SrcUnpackedness
SrcStrictness
deriving Data.Data
-- | Bangs of data constructor arguments as generated by the compiler
-- after consulting HsSrcBang, flags, etc.
data HsImplBang
= HsLazy -- ^ Lazy field
| HsStrict -- ^ Strict but not unpacked field
| HsUnpack (Maybe Coercion)
-- ^ Strict and unpacked field
-- co :: arg-ty ~ product-ty HsBang
deriving Data.Data
-- | What strictness annotation the user wrote
data SrcStrictness = SrcLazy -- ^ Lazy, ie '~'
| SrcStrict -- ^ Strict, ie '!'
| NoSrcStrict -- ^ no strictness annotation
deriving (Eq, Data.Data)
-- | What unpackedness the user requested
data SrcUnpackedness = SrcUnpack -- ^ {-# UNPACK #-} specified
| SrcNoUnpack -- ^ {-# NOUNPACK #-} specified
| NoSrcUnpack -- ^ no unpack pragma
deriving (Eq, Data.Data)
-------------------------
-- StrictnessMark is internal only, used to indicate strictness
-- of the DataCon *worker* fields
data StrictnessMark = MarkedStrict | NotMarkedStrict
-- | An 'EqSpec' is a tyvar/type pair representing an equality made in
-- rejigging a GADT constructor
data EqSpec = EqSpec TyVar
Type
-- | Make an 'EqSpec'
mkEqSpec :: TyVar -> Type -> EqSpec
mkEqSpec tv ty = EqSpec tv ty
eqSpecTyVar :: EqSpec -> TyVar
eqSpecTyVar (EqSpec tv _) = tv
eqSpecType :: EqSpec -> Type
eqSpecType (EqSpec _ ty) = ty
eqSpecPair :: EqSpec -> (TyVar, Type)
eqSpecPair (EqSpec tv ty) = (tv, ty)
eqSpecPreds :: [EqSpec] -> ThetaType
eqSpecPreds spec = [ mkPrimEqPred (mkTyVarTy tv) ty
| EqSpec tv ty <- spec ]
-- | Substitute in an 'EqSpec'. Precondition: if the LHS of the EqSpec
-- is mapped in the substitution, it is mapped to a type variable, not
-- a full type.
substEqSpec :: TCvSubst -> EqSpec -> EqSpec
substEqSpec subst (EqSpec tv ty)
= EqSpec tv' (substTy subst ty)
where
tv' = getTyVar "substEqSpec" (substTyVar subst tv)
-- | Filter out any TyBinders mentioned in an EqSpec
filterEqSpec :: [EqSpec] -> [TyBinder] -> [TyBinder]
filterEqSpec eq_spec
= filter not_in_eq_spec
where
not_in_eq_spec bndr = let var = binderVar "filterEqSpec" bndr in
all (not . (== var) . eqSpecTyVar) eq_spec
instance Outputable EqSpec where
ppr (EqSpec tv ty) = ppr (tv, ty)
{- Note [Bangs on data constructor arguments]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
data T = MkT !Int {-# UNPACK #-} !Int Bool
When compiling the module, GHC will decide how to represent
MkT, depending on the optimisation level, and settings of
flags like -funbox-small-strict-fields.
Terminology:
* HsSrcBang: What the user wrote
Constructors: HsSrcBang
* HsImplBang: What GHC decided
Constructors: HsLazy, HsStrict, HsUnpack
* If T was defined in this module, MkT's dcSrcBangs field
records the [HsSrcBang] of what the user wrote; in the example
[ HsSrcBang _ NoSrcUnpack SrcStrict
, HsSrcBang _ SrcUnpack SrcStrict
, HsSrcBang _ NoSrcUnpack NoSrcStrictness]
* However, if T was defined in an imported module, the importing module
must follow the decisions made in the original module, regardless of
the flag settings in the importing module.
Also see Note [Bangs on imported data constructors] in MkId
* The dcr_bangs field of the dcRep field records the [HsImplBang]
If T was defined in this module, Without -O the dcr_bangs might be
[HsStrict, HsStrict, HsLazy]
With -O it might be
[HsStrict, HsUnpack _, HsLazy]
With -funbox-small-strict-fields it might be
[HsUnpack, HsUnpack _, HsLazy]
With -XStrictData it might be
[HsStrict, HsUnpack _, HsStrict]
Note [Data con representation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The dcRepType field contains the type of the representation of a contructor
This may differ from the type of the constructor *Id* (built
by MkId.mkDataConId) for two reasons:
a) the constructor Id may be overloaded, but the dictionary isn't stored
e.g. data Eq a => T a = MkT a a
b) the constructor may store an unboxed version of a strict field.
Here's an example illustrating both:
data Ord a => T a = MkT Int! a
Here
T :: Ord a => Int -> a -> T a
but the rep type is
Trep :: Int# -> a -> T a
Actually, the unboxed part isn't implemented yet!
************************************************************************
* *
\subsection{Instances}
* *
************************************************************************
-}
instance Eq DataCon where
a == b = getUnique a == getUnique b
a /= b = getUnique a /= getUnique b
instance Ord DataCon where
a <= b = getUnique a <= getUnique b
a < b = getUnique a < getUnique b
a >= b = getUnique a >= getUnique b
a > b = getUnique a > getUnique b
compare a b = getUnique a `compare` getUnique b
instance Uniquable DataCon where
getUnique = dcUnique
instance NamedThing DataCon where
getName = dcName
instance Outputable DataCon where
ppr con = ppr (dataConName con)
instance OutputableBndr DataCon where
pprInfixOcc con = pprInfixName (dataConName con)
pprPrefixOcc con = pprPrefixName (dataConName con)
instance Data.Data DataCon where
-- don't traverse?
toConstr _ = abstractConstr "DataCon"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "DataCon"
instance Outputable HsSrcBang where
ppr (HsSrcBang _ prag mark) = ppr prag <+> ppr mark
instance Outputable HsImplBang where
ppr HsLazy = text "Lazy"
ppr (HsUnpack Nothing) = text "Unpacked"
ppr (HsUnpack (Just co)) = text "Unpacked" <> parens (ppr co)
ppr HsStrict = text "StrictNotUnpacked"
instance Outputable SrcStrictness where
ppr SrcLazy = char '~'
ppr SrcStrict = char '!'
ppr NoSrcStrict = empty
instance Outputable SrcUnpackedness where
ppr SrcUnpack = text "{-# UNPACK #-}"
ppr SrcNoUnpack = text "{-# NOUNPACK #-}"
ppr NoSrcUnpack = empty
instance Outputable StrictnessMark where
ppr MarkedStrict = text "!"
ppr NotMarkedStrict = empty
instance Binary SrcStrictness where
put_ bh SrcLazy = putByte bh 0
put_ bh SrcStrict = putByte bh 1
put_ bh NoSrcStrict = putByte bh 2
get bh =
do h <- getByte bh
case h of
0 -> return SrcLazy
1 -> return SrcLazy
_ -> return NoSrcStrict
instance Binary SrcUnpackedness where
put_ bh SrcNoUnpack = putByte bh 0
put_ bh SrcUnpack = putByte bh 1
put_ bh NoSrcUnpack = putByte bh 2
get bh =
do h <- getByte bh
case h of
0 -> return SrcNoUnpack
1 -> return SrcUnpack
_ -> return NoSrcUnpack
-- | Compare strictness annotations
eqHsBang :: HsImplBang -> HsImplBang -> Bool
eqHsBang HsLazy HsLazy = True
eqHsBang HsStrict HsStrict = True
eqHsBang (HsUnpack Nothing) (HsUnpack Nothing) = True
eqHsBang (HsUnpack (Just c1)) (HsUnpack (Just c2))
= eqType (coercionType c1) (coercionType c2)
eqHsBang _ _ = False
isBanged :: HsImplBang -> Bool
isBanged (HsUnpack {}) = True
isBanged (HsStrict {}) = True
isBanged HsLazy = False
isSrcStrict :: SrcStrictness -> Bool
isSrcStrict SrcStrict = True
isSrcStrict _ = False
isSrcUnpacked :: SrcUnpackedness -> Bool
isSrcUnpacked SrcUnpack = True
isSrcUnpacked _ = False
isMarkedStrict :: StrictnessMark -> Bool
isMarkedStrict NotMarkedStrict = False
isMarkedStrict _ = True -- All others are strict
{- *********************************************************************
* *
\subsection{Construction}
* *
********************************************************************* -}
-- | Build a new data constructor
mkDataCon :: Name
-> Bool -- ^ Is the constructor declared infix?
-> TyConRepName -- ^ TyConRepName for the promoted TyCon
-> [HsSrcBang] -- ^ Strictness/unpack annotations, from user
-> [FieldLabel] -- ^ Field labels for the constructor,
-- if it is a record, otherwise empty
-> [TyVar] -> [TyBinder] -- ^ Universals. See Note [TyBinders in DataCons]
-> [TyVar] -> [TyBinder] -- ^ Existentials.
-- (These last two must be Named and Invisible/Specified)
-> [EqSpec] -- ^ GADT equalities
-> ThetaType -- ^ Theta-type occuring before the arguments proper
-> [Type] -- ^ Original argument types
-> Type -- ^ Original result type
-> RuntimeRepInfo -- ^ See comments on 'TyCon.RuntimeRepInfo'
-> TyCon -- ^ Representation type constructor
-> ThetaType -- ^ The "stupid theta", context of the data
-- declaration e.g. @data Eq a => T a ...@
-> Id -- ^ Worker Id
-> DataConRep -- ^ Representation
-> DataCon
-- Can get the tag from the TyCon
mkDataCon name declared_infix prom_info
arg_stricts -- Must match orig_arg_tys 1-1
fields
univ_tvs univ_bndrs ex_tvs ex_bndrs
eq_spec theta
orig_arg_tys orig_res_ty rep_info rep_tycon
stupid_theta work_id rep
-- Warning: mkDataCon is not a good place to check invariants.
-- If the programmer writes the wrong result type in the decl, thus:
-- data T a where { MkT :: S }
-- then it's possible that the univ_tvs may hit an assertion failure
-- if you pull on univ_tvs. This case is checked by checkValidDataCon,
-- so the error is detected properly... it's just that asaertions here
-- are a little dodgy.
= con
where
is_vanilla = null ex_tvs && null eq_spec && null theta
con = MkData {dcName = name, dcUnique = nameUnique name,
dcVanilla = is_vanilla, dcInfix = declared_infix,
dcUnivTyVars = univ_tvs, dcUnivTyBinders = univ_bndrs,
dcExTyVars = ex_tvs, dcExTyBinders = ex_bndrs,
dcEqSpec = eq_spec,
dcOtherTheta = theta,
dcStupidTheta = stupid_theta,
dcOrigArgTys = orig_arg_tys, dcOrigResTy = orig_res_ty,
dcRepTyCon = rep_tycon,
dcSrcBangs = arg_stricts,
dcFields = fields, dcTag = tag, dcRepType = rep_ty,
dcWorkId = work_id,
dcRep = rep,
dcSourceArity = length orig_arg_tys,
dcRepArity = length rep_arg_tys,
dcPromoted = promoted }
-- The 'arg_stricts' passed to mkDataCon are simply those for the
-- source-language arguments. We add extra ones for the
-- dictionary arguments right here.
tag = assoc "mkDataCon" (tyConDataCons rep_tycon `zip` [fIRST_TAG..]) con
rep_arg_tys = dataConRepArgTys con
rep_ty = mkForAllTys univ_bndrs $ mkForAllTys ex_bndrs $
mkFunTys rep_arg_tys $
mkTyConApp rep_tycon (mkTyVarTys univ_tvs)
-- See Note [Promoted data constructors] in TyCon
prom_binders = filterEqSpec eq_spec univ_bndrs ++
ex_bndrs ++
map mkAnonBinder theta ++
map mkAnonBinder orig_arg_tys
prom_res_kind = orig_res_ty
promoted
= mkPromotedDataCon con name prom_info prom_binders prom_res_kind roles rep_info
roles = map (const Nominal) (univ_tvs ++ ex_tvs) ++
map (const Representational) orig_arg_tys
-- | The 'Name' of the 'DataCon', giving it a unique, rooted identification
dataConName :: DataCon -> Name
dataConName = dcName
-- | The tag used for ordering 'DataCon's
dataConTag :: DataCon -> ConTag
dataConTag = dcTag
-- | The type constructor that we are building via this data constructor
dataConTyCon :: DataCon -> TyCon
dataConTyCon = dcRepTyCon
-- | The original type constructor used in the definition of this data
-- constructor. In case of a data family instance, that will be the family
-- type constructor.
dataConOrigTyCon :: DataCon -> TyCon
dataConOrigTyCon dc
| Just (tc, _) <- tyConFamInst_maybe (dcRepTyCon dc) = tc
| otherwise = dcRepTyCon dc
-- | The representation type of the data constructor, i.e. the sort
-- type that will represent values of this type at runtime
dataConRepType :: DataCon -> Type
dataConRepType = dcRepType
-- | Should the 'DataCon' be presented infix?
dataConIsInfix :: DataCon -> Bool
dataConIsInfix = dcInfix
-- | The universally-quantified type variables of the constructor
dataConUnivTyVars :: DataCon -> [TyVar]
dataConUnivTyVars = dcUnivTyVars
-- | 'TyBinder's for the universally-quantified type variables
dataConUnivTyBinders :: DataCon -> [TyBinder]
dataConUnivTyBinders = dcUnivTyBinders
-- | The existentially-quantified type variables of the constructor
dataConExTyVars :: DataCon -> [TyVar]
dataConExTyVars = dcExTyVars
-- | 'TyBinder's for the existentially-quantified type variables
dataConExTyBinders :: DataCon -> [TyBinder]
dataConExTyBinders = dcExTyBinders
-- | Both the universal and existentiatial type variables of the constructor
dataConAllTyVars :: DataCon -> [TyVar]
dataConAllTyVars (MkData { dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs })
= univ_tvs ++ ex_tvs
-- | Equalities derived from the result type of the data constructor, as written
-- by the programmer in any GADT declaration. This includes *all* GADT-like
-- equalities, including those written in by hand by the programmer.
dataConEqSpec :: DataCon -> [EqSpec]
dataConEqSpec (MkData { dcEqSpec = eq_spec, dcOtherTheta = theta })
= eq_spec ++
[ spec -- heterogeneous equality
| Just (tc, [_k1, _k2, ty1, ty2]) <- map splitTyConApp_maybe theta
, tc `hasKey` heqTyConKey
, spec <- case (getTyVar_maybe ty1, getTyVar_maybe ty2) of
(Just tv1, _) -> [mkEqSpec tv1 ty2]
(_, Just tv2) -> [mkEqSpec tv2 ty1]
_ -> []
] ++
[ spec -- homogeneous equality
| Just (tc, [_k, ty1, ty2]) <- map splitTyConApp_maybe theta
, tc `hasKey` eqTyConKey
, spec <- case (getTyVar_maybe ty1, getTyVar_maybe ty2) of
(Just tv1, _) -> [mkEqSpec tv1 ty2]
(_, Just tv2) -> [mkEqSpec tv2 ty1]
_ -> []
]
-- | The *full* constraints on the constructor type.
dataConTheta :: DataCon -> ThetaType
dataConTheta (MkData { dcEqSpec = eq_spec, dcOtherTheta = theta })
= eqSpecPreds eq_spec ++ theta
-- | Get the Id of the 'DataCon' worker: a function that is the "actual"
-- constructor and has no top level binding in the program. The type may
-- be different from the obvious one written in the source program. Panics
-- if there is no such 'Id' for this 'DataCon'
dataConWorkId :: DataCon -> Id
dataConWorkId dc = dcWorkId dc
-- | Get the Id of the 'DataCon' wrapper: a function that wraps the "actual"
-- constructor so it has the type visible in the source program: c.f. 'dataConWorkId'.
-- Returns Nothing if there is no wrapper, which occurs for an algebraic data constructor
-- and also for a newtype (whose constructor is inlined compulsorily)
dataConWrapId_maybe :: DataCon -> Maybe Id
dataConWrapId_maybe dc = case dcRep dc of
NoDataConRep -> Nothing
DCR { dcr_wrap_id = wrap_id } -> Just wrap_id
-- | Returns an Id which looks like the Haskell-source constructor by using
-- the wrapper if it exists (see 'dataConWrapId_maybe') and failing over to
-- the worker (see 'dataConWorkId')
dataConWrapId :: DataCon -> Id
dataConWrapId dc = case dcRep dc of
NoDataConRep-> dcWorkId dc -- worker=wrapper
DCR { dcr_wrap_id = wrap_id } -> wrap_id
-- | Find all the 'Id's implicitly brought into scope by the data constructor. Currently,
-- the union of the 'dataConWorkId' and the 'dataConWrapId'
dataConImplicitTyThings :: DataCon -> [TyThing]
dataConImplicitTyThings (MkData { dcWorkId = work, dcRep = rep })
= [AnId work] ++ wrap_ids
where
wrap_ids = case rep of
NoDataConRep -> []
DCR { dcr_wrap_id = wrap } -> [AnId wrap]
-- | The labels for the fields of this particular 'DataCon'
dataConFieldLabels :: DataCon -> [FieldLabel]
dataConFieldLabels = dcFields
-- | Extract the type for any given labelled field of the 'DataCon'
dataConFieldType :: DataCon -> FieldLabelString -> Type
dataConFieldType con label
= case find ((== label) . flLabel . fst) (dcFields con `zip` dcOrigArgTys con) of
Just (_, ty) -> ty
Nothing -> pprPanic "dataConFieldType" (ppr con <+> ppr label)
-- | Strictness/unpack annotations, from user; or, for imported
-- DataCons, from the interface file
-- The list is in one-to-one correspondence with the arity of the 'DataCon'
dataConSrcBangs :: DataCon -> [HsSrcBang]
dataConSrcBangs = dcSrcBangs
-- | Source-level arity of the data constructor
dataConSourceArity :: DataCon -> Arity
dataConSourceArity (MkData { dcSourceArity = arity }) = arity
-- | Gives the number of actual fields in the /representation/ of the
-- data constructor. This may be more than appear in the source code;
-- the extra ones are the existentially quantified dictionaries
dataConRepArity :: DataCon -> Arity
dataConRepArity (MkData { dcRepArity = arity }) = arity
-- | The number of fields in the /representation/ of the constructor
-- AFTER taking into account the unpacking of any unboxed tuple fields
dataConRepRepArity :: DataCon -> RepArity
dataConRepRepArity dc = typeRepArity (dataConRepArity dc) (dataConRepType dc)
-- | Return whether there are any argument types for this 'DataCon's original source type
isNullarySrcDataCon :: DataCon -> Bool
isNullarySrcDataCon dc = null (dcOrigArgTys dc)
-- | Return whether there are any argument types for this 'DataCon's runtime representation type
isNullaryRepDataCon :: DataCon -> Bool
isNullaryRepDataCon dc = dataConRepArity dc == 0
dataConRepStrictness :: DataCon -> [StrictnessMark]
-- ^ Give the demands on the arguments of a
-- Core constructor application (Con dc args)
dataConRepStrictness dc = case dcRep dc of
NoDataConRep -> [NotMarkedStrict | _ <- dataConRepArgTys dc]
DCR { dcr_stricts = strs } -> strs
dataConImplBangs :: DataCon -> [HsImplBang]
-- The implementation decisions about the strictness/unpack of each
-- source program argument to the data constructor
dataConImplBangs dc
= case dcRep dc of
NoDataConRep -> replicate (dcSourceArity dc) HsLazy
DCR { dcr_bangs = bangs } -> bangs
dataConBoxer :: DataCon -> Maybe DataConBoxer
dataConBoxer (MkData { dcRep = DCR { dcr_boxer = boxer } }) = Just boxer
dataConBoxer _ = Nothing
-- | The \"signature\" of the 'DataCon' returns, in order:
--
-- 1) The result of 'dataConAllTyVars',
--
-- 2) All the 'ThetaType's relating to the 'DataCon' (coercion, dictionary, implicit
-- parameter - whatever)
--
-- 3) The type arguments to the constructor
--
-- 4) The /original/ result type of the 'DataCon'
dataConSig :: DataCon -> ([TyVar], ThetaType, [Type], Type)
dataConSig con@(MkData {dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs,
dcOrigArgTys = arg_tys, dcOrigResTy = res_ty})
= (univ_tvs ++ ex_tvs, dataConTheta con, arg_tys, res_ty)
dataConInstSig
:: DataCon
-> [Type] -- Instantiate the *universal* tyvars with these types
-> ([TyVar], ThetaType, [Type]) -- Return instantiated existentials
-- theta and arg tys
-- ^ Instantantiate the universal tyvars of a data con,
-- returning the instantiated existentials, constraints, and args
dataConInstSig (MkData { dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs
, dcEqSpec = eq_spec, dcOtherTheta = theta
, dcOrigArgTys = arg_tys })
univ_tys
= (ex_tvs'
, substTheta subst (eqSpecPreds eq_spec ++ theta)
, substTys subst arg_tys)
where
univ_subst = zipTvSubst univ_tvs univ_tys
(subst, ex_tvs') = mapAccumL Type.substTyVarBndr univ_subst ex_tvs
-- | The \"full signature\" of the 'DataCon' returns, in order:
--
-- 1) The result of 'dataConUnivTyVars'
--
-- 2) The result of 'dataConExTyVars'
--
-- 3) The GADT equalities
--
-- 4) The result of 'dataConDictTheta'
--
-- 5) The original argument types to the 'DataCon' (i.e. before
-- any change of the representation of the type)
--
-- 6) The original result type of the 'DataCon'
dataConFullSig :: DataCon
-> ([TyVar], [TyVar], [EqSpec], ThetaType, [Type], Type)
dataConFullSig (MkData {dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs,
dcEqSpec = eq_spec, dcOtherTheta = theta,
dcOrigArgTys = arg_tys, dcOrigResTy = res_ty})
= (univ_tvs, ex_tvs, eq_spec, theta, arg_tys, res_ty)
dataConOrigResTy :: DataCon -> Type
dataConOrigResTy dc = dcOrigResTy dc
-- | The \"stupid theta\" of the 'DataCon', such as @data Eq a@ in:
--
-- > data Eq a => T a = ...
dataConStupidTheta :: DataCon -> ThetaType
dataConStupidTheta dc = dcStupidTheta dc
dataConUserType :: DataCon -> Type
-- ^ The user-declared type of the data constructor
-- in the nice-to-read form:
--
-- > T :: forall a b. a -> b -> T [a]
--
-- rather than:
--
-- > T :: forall a c. forall b. (c~[a]) => a -> b -> T c
--
-- NB: If the constructor is part of a data instance, the result type
-- mentions the family tycon, not the internal one.
dataConUserType (MkData { dcUnivTyBinders = univ_bndrs,
dcExTyBinders = ex_bndrs, dcEqSpec = eq_spec,
dcOtherTheta = theta, dcOrigArgTys = arg_tys,
dcOrigResTy = res_ty })
= mkForAllTys (filterEqSpec eq_spec univ_bndrs) $
mkForAllTys ex_bndrs $
mkFunTys theta $
mkFunTys arg_tys $
res_ty
where
-- | Finds the instantiated types of the arguments required to construct a 'DataCon' representation
-- NB: these INCLUDE any dictionary args
-- but EXCLUDE the data-declaration context, which is discarded
-- It's all post-flattening etc; this is a representation type
dataConInstArgTys :: DataCon -- ^ A datacon with no existentials or equality constraints
-- However, it can have a dcTheta (notably it can be a
-- class dictionary, with superclasses)
-> [Type] -- ^ Instantiated at these types
-> [Type]
dataConInstArgTys dc@(MkData {dcUnivTyVars = univ_tvs,
dcExTyVars = ex_tvs}) inst_tys
= ASSERT2( length univ_tvs == length inst_tys
, text "dataConInstArgTys" <+> ppr dc $$ ppr univ_tvs $$ ppr inst_tys)
ASSERT2( null ex_tvs, ppr dc )
map (substTyWith univ_tvs inst_tys) (dataConRepArgTys dc)
-- | Returns just the instantiated /value/ argument types of a 'DataCon',
-- (excluding dictionary args)
dataConInstOrigArgTys
:: DataCon -- Works for any DataCon
-> [Type] -- Includes existential tyvar args, but NOT
-- equality constraints or dicts
-> [Type]
-- For vanilla datacons, it's all quite straightforward
-- But for the call in MatchCon, we really do want just the value args
dataConInstOrigArgTys dc@(MkData {dcOrigArgTys = arg_tys,
dcUnivTyVars = univ_tvs,
dcExTyVars = ex_tvs}) inst_tys
= ASSERT2( length tyvars == length inst_tys
, text "dataConInstOrigArgTys" <+> ppr dc $$ ppr tyvars $$ ppr inst_tys )
map (substTyWith tyvars inst_tys) arg_tys
where
tyvars = univ_tvs ++ ex_tvs
-- | Returns the argument types of the wrapper, excluding all dictionary arguments
-- and without substituting for any type variables
dataConOrigArgTys :: DataCon -> [Type]
dataConOrigArgTys dc = dcOrigArgTys dc
-- | Returns the arg types of the worker, including *all*
-- evidence, after any flattening has been done and without substituting for
-- any type variables
dataConRepArgTys :: DataCon -> [Type]
dataConRepArgTys (MkData { dcRep = rep
, dcEqSpec = eq_spec
, dcOtherTheta = theta
, dcOrigArgTys = orig_arg_tys })
= case rep of
NoDataConRep -> ASSERT( null eq_spec ) theta ++ orig_arg_tys
DCR { dcr_arg_tys = arg_tys } -> arg_tys
-- | The string @package:module.name@ identifying a constructor, which is attached
-- to its info table and used by the GHCi debugger and the heap profiler
dataConIdentity :: DataCon -> [Word8]
-- We want this string to be UTF-8, so we get the bytes directly from the FastStrings.
dataConIdentity dc = bytesFS (unitIdFS (moduleUnitId mod)) ++
fromIntegral (ord ':') : bytesFS (moduleNameFS (moduleName mod)) ++
fromIntegral (ord '.') : bytesFS (occNameFS (nameOccName name))
where name = dataConName dc
mod = ASSERT( isExternalName name ) nameModule name
isTupleDataCon :: DataCon -> Bool
isTupleDataCon (MkData {dcRepTyCon = tc}) = isTupleTyCon tc
isUnboxedTupleCon :: DataCon -> Bool
isUnboxedTupleCon (MkData {dcRepTyCon = tc}) = isUnboxedTupleTyCon tc
-- | Vanilla 'DataCon's are those that are nice boring Haskell 98 constructors
isVanillaDataCon :: DataCon -> Bool
isVanillaDataCon dc = dcVanilla dc
-- | Should this DataCon be allowed in a type even without -XDataKinds?
-- Currently, only Lifted & Unlifted
specialPromotedDc :: DataCon -> Bool
specialPromotedDc = isKindTyCon . dataConTyCon
-- | Was this datacon promotable before GHC 8.0? That is, is it promotable
-- without -XTypeInType
isLegacyPromotableDataCon :: DataCon -> Bool
isLegacyPromotableDataCon dc
= null (dataConEqSpec dc) -- no GADTs
&& null (dataConTheta dc) -- no context
&& not (isFamInstTyCon (dataConTyCon dc)) -- no data instance constructors
&& allUFM isLegacyPromotableTyCon (tyConsOfType (dataConUserType dc))
-- | Was this tycon promotable before GHC 8.0? That is, is it promotable
-- without -XTypeInType
isLegacyPromotableTyCon :: TyCon -> Bool
isLegacyPromotableTyCon tc
= isVanillaAlgTyCon tc ||
-- This returns True more often than it should, but it's quite painful
-- to make this fully accurate. And no harm is caused; we just don't
-- require -XTypeInType every time we need to. (We'll always require
-- -XDataKinds, though, so there's no standards-compliance issue.)
isFunTyCon tc || isKindTyCon tc
classDataCon :: Class -> DataCon
classDataCon clas = case tyConDataCons (classTyCon clas) of
(dict_constr:no_more) -> ASSERT( null no_more ) dict_constr
[] -> panic "classDataCon"
dataConCannotMatch :: [Type] -> DataCon -> Bool
-- Returns True iff the data con *definitely cannot* match a
-- scrutinee of type (T tys)
-- where T is the dcRepTyCon for the data con
dataConCannotMatch tys con
| null inst_theta = False -- Common
| all isTyVarTy tys = False -- Also common
| otherwise = typesCantMatch (concatMap predEqs inst_theta)
where
(_, inst_theta, _) = dataConInstSig con tys
-- TODO: could gather equalities from superclasses too
predEqs pred = case classifyPredType pred of
EqPred NomEq ty1 ty2 -> [(ty1, ty2)]
ClassPred eq [_, ty1, ty2]
| eq `hasKey` eqTyConKey -> [(ty1, ty2)]
_ -> []
{-
%************************************************************************
%* *
Promoting of data types to the kind level
* *
************************************************************************
-}
promoteDataCon :: DataCon -> TyCon
promoteDataCon (MkData { dcPromoted = tc }) = tc
{-
************************************************************************
* *
\subsection{Splitting products}
* *
************************************************************************
-}
-- | Extract the type constructor, type argument, data constructor and it's
-- /representation/ argument types from a type if it is a product type.
--
-- Precisely, we return @Just@ for any type that is all of:
--
-- * Concrete (i.e. constructors visible)
--
-- * Single-constructor
--
-- * Not existentially quantified
--
-- Whether the type is a @data@ type or a @newtype@
splitDataProductType_maybe
:: Type -- ^ A product type, perhaps
-> Maybe (TyCon, -- The type constructor
[Type], -- Type args of the tycon
DataCon, -- The data constructor
[Type]) -- Its /representation/ arg types
-- Rejecting existentials is conservative. Maybe some things
-- could be made to work with them, but I'm not going to sweat
-- it through till someone finds it's important.
splitDataProductType_maybe ty
| Just (tycon, ty_args) <- splitTyConApp_maybe ty
, Just con <- isDataProductTyCon_maybe tycon
= Just (tycon, ty_args, con, dataConInstArgTys con ty_args)
| otherwise
= Nothing
{-
************************************************************************
* *
Building an algebraic data type
* *
************************************************************************
buildAlgTyCon is here because it is called from TysWiredIn, which can
depend on this module, but not on BuildTyCl.
-}
buildAlgTyCon :: Name
-> [TyVar] -- ^ Kind variables and type variables
-> [Role]
-> Maybe CType
-> ThetaType -- ^ Stupid theta
-> AlgTyConRhs
-> RecFlag
-> Bool -- ^ True <=> was declared in GADT syntax
-> AlgTyConFlav
-> TyCon
buildAlgTyCon tc_name ktvs roles cType stupid_theta rhs
is_rec gadt_syn parent
= mkAlgTyCon tc_name binders liftedTypeKind ktvs roles cType stupid_theta
rhs parent is_rec gadt_syn
where
binders = mkTyBindersPreferAnon ktvs liftedTypeKind
| vikraman/ghc | compiler/basicTypes/DataCon.hs | Haskell | bsd-3-clause | 50,860 |
{-
(c) The University of Glasgow 2006
(c) The AQUA Project, Glasgow University, 1994-1998
Desugaring foreign calls
-}
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}
module DsCCall
( dsCCall
, mkFCall
, unboxArg
, boxResult
, resultWrapper
) where
#include "HsVersions.h"
import GhcPrelude
import CoreSyn
import DsMonad
import CoreUtils
import MkCore
import MkId
import ForeignCall
import DataCon
import DsUtils
import TcType
import Type
import Id ( Id )
import Coercion
import PrimOp
import TysPrim
import TyCon
import TysWiredIn
import BasicTypes
import Literal
import PrelNames
import DynFlags
import Outputable
import Util
import Data.Maybe
{-
Desugaring of @ccall@s consists of adding some state manipulation,
unboxing any boxed primitive arguments and boxing the result if
desired.
The state stuff just consists of adding in
@PrimIO (\ s -> case s of { S# s# -> ... })@ in an appropriate place.
The unboxing is straightforward, as all information needed to unbox is
available from the type. For each boxed-primitive argument, we
transform:
\begin{verbatim}
_ccall_ foo [ r, t1, ... tm ] e1 ... em
|
|
V
case e1 of { T1# x1# ->
...
case em of { Tm# xm# -> xm#
ccall# foo [ r, t1#, ... tm# ] x1# ... xm#
} ... }
\end{verbatim}
The reboxing of a @_ccall_@ result is a bit tricker: the types don't
contain information about the state-pairing functions so we have to
keep a list of \tr{(type, s-p-function)} pairs. We transform as
follows:
\begin{verbatim}
ccall# foo [ r, t1#, ... tm# ] e1# ... em#
|
|
V
\ s# -> case (ccall# foo [ r, t1#, ... tm# ] s# e1# ... em#) of
(StateAnd<r># result# state#) -> (R# result#, realWorld#)
\end{verbatim}
-}
dsCCall :: CLabelString -- C routine to invoke
-> [CoreExpr] -- Arguments (desugared)
-- Precondition: none have levity-polymorphic types
-> Safety -- Safety of the call
-> Type -- Type of the result: IO t
-> DsM CoreExpr -- Result, of type ???
dsCCall lbl args may_gc result_ty
= do (unboxed_args, arg_wrappers) <- mapAndUnzipM unboxArg args
(ccall_result_ty, res_wrapper) <- boxResult result_ty
uniq <- newUnique
dflags <- getDynFlags
let
target = StaticTarget NoSourceText lbl Nothing True
the_fcall = CCall (CCallSpec target CCallConv may_gc)
the_prim_app = mkFCall dflags uniq the_fcall unboxed_args ccall_result_ty
return (foldr ($) (res_wrapper the_prim_app) arg_wrappers)
mkFCall :: DynFlags -> Unique -> ForeignCall
-> [CoreExpr] -- Args
-> Type -- Result type
-> CoreExpr
-- Construct the ccall. The only tricky bit is that the ccall Id should have
-- no free vars, so if any of the arg tys do we must give it a polymorphic type.
-- [I forget *why* it should have no free vars!]
-- For example:
-- mkCCall ... [s::StablePtr (a->b), x::Addr, c::Char]
--
-- Here we build a ccall thus
-- (ccallid::(forall a b. StablePtr (a -> b) -> Addr -> Char -> IO Addr))
-- a b s x c
mkFCall dflags uniq the_fcall val_args res_ty
= ASSERT( all isTyVar tyvars ) -- this must be true because the type is top-level
mkApps (mkVarApps (Var the_fcall_id) tyvars) val_args
where
arg_tys = map exprType val_args
body_ty = (mkVisFunTys arg_tys res_ty)
tyvars = tyCoVarsOfTypeWellScoped body_ty
ty = mkInvForAllTys tyvars body_ty
the_fcall_id = mkFCallId dflags uniq the_fcall ty
unboxArg :: CoreExpr -- The supplied argument, not levity-polymorphic
-> DsM (CoreExpr, -- To pass as the actual argument
CoreExpr -> CoreExpr -- Wrapper to unbox the arg
)
-- Example: if the arg is e::Int, unboxArg will return
-- (x#::Int#, \W. case x of I# x# -> W)
-- where W is a CoreExpr that probably mentions x#
-- always returns a non-levity-polymorphic expression
unboxArg arg
-- Primitive types: nothing to unbox
| isPrimitiveType arg_ty
= return (arg, \body -> body)
-- Recursive newtypes
| Just(co, _rep_ty) <- topNormaliseNewType_maybe arg_ty
= unboxArg (mkCastDs arg co)
-- Booleans
| Just tc <- tyConAppTyCon_maybe arg_ty,
tc `hasKey` boolTyConKey
= do dflags <- getDynFlags
prim_arg <- newSysLocalDs intPrimTy
return (Var prim_arg,
\ body -> Case (mkWildCase arg arg_ty intPrimTy
[(DataAlt falseDataCon,[],mkIntLit dflags 0),
(DataAlt trueDataCon, [],mkIntLit dflags 1)])
-- In increasing tag order!
prim_arg
(exprType body)
[(DEFAULT,[],body)])
-- Data types with a single constructor, which has a single, primitive-typed arg
-- This deals with Int, Float etc; also Ptr, ForeignPtr
| is_product_type && data_con_arity == 1
= ASSERT2(isUnliftedType data_con_arg_ty1, pprType arg_ty)
-- Typechecker ensures this
do case_bndr <- newSysLocalDs arg_ty
prim_arg <- newSysLocalDs data_con_arg_ty1
return (Var prim_arg,
\ body -> Case arg case_bndr (exprType body) [(DataAlt data_con,[prim_arg],body)]
)
-- Byte-arrays, both mutable and otherwise; hack warning
-- We're looking for values of type ByteArray, MutableByteArray
-- data ByteArray ix = ByteArray ix ix ByteArray#
-- data MutableByteArray s ix = MutableByteArray ix ix (MutableByteArray# s)
| is_product_type &&
data_con_arity == 3 &&
isJust maybe_arg3_tycon &&
(arg3_tycon == byteArrayPrimTyCon ||
arg3_tycon == mutableByteArrayPrimTyCon)
= do case_bndr <- newSysLocalDs arg_ty
vars@[_l_var, _r_var, arr_cts_var] <- newSysLocalsDs data_con_arg_tys
return (Var arr_cts_var,
\ body -> Case arg case_bndr (exprType body) [(DataAlt data_con,vars,body)]
)
| otherwise
= do l <- getSrcSpanDs
pprPanic "unboxArg: " (ppr l <+> ppr arg_ty)
where
arg_ty = exprType arg
maybe_product_type = splitDataProductType_maybe arg_ty
is_product_type = isJust maybe_product_type
Just (_, _, data_con, data_con_arg_tys) = maybe_product_type
data_con_arity = dataConSourceArity data_con
(data_con_arg_ty1 : _) = data_con_arg_tys
(_ : _ : data_con_arg_ty3 : _) = data_con_arg_tys
maybe_arg3_tycon = tyConAppTyCon_maybe data_con_arg_ty3
Just arg3_tycon = maybe_arg3_tycon
boxResult :: Type
-> DsM (Type, CoreExpr -> CoreExpr)
-- Takes the result of the user-level ccall:
-- either (IO t),
-- or maybe just t for a side-effect-free call
-- Returns a wrapper for the primitive ccall itself, along with the
-- type of the result of the primitive ccall. This result type
-- will be of the form
-- State# RealWorld -> (# State# RealWorld, t' #)
-- where t' is the unwrapped form of t. If t is simply (), then
-- the result type will be
-- State# RealWorld -> (# State# RealWorld #)
boxResult result_ty
| Just (io_tycon, io_res_ty) <- tcSplitIOType_maybe result_ty
-- isIOType_maybe handles the case where the type is a
-- simple wrapping of IO. E.g.
-- newtype Wrap a = W (IO a)
-- No coercion necessary because its a non-recursive newtype
-- (If we wanted to handle a *recursive* newtype too, we'd need
-- another case, and a coercion.)
-- The result is IO t, so wrap the result in an IO constructor
= do { res <- resultWrapper io_res_ty
; let extra_result_tys
= case res of
(Just ty,_)
| isUnboxedTupleType ty
-> let Just ls = tyConAppArgs_maybe ty in tail ls
_ -> []
return_result state anss
= mkCoreUbxTup
(realWorldStatePrimTy : io_res_ty : extra_result_tys)
(state : anss)
; (ccall_res_ty, the_alt) <- mk_alt return_result res
; state_id <- newSysLocalDs realWorldStatePrimTy
; let io_data_con = head (tyConDataCons io_tycon)
toIOCon = dataConWrapId io_data_con
wrap the_call =
mkApps (Var toIOCon)
[ Type io_res_ty,
Lam state_id $
mkWildCase (App the_call (Var state_id))
ccall_res_ty
(coreAltType the_alt)
[the_alt]
]
; return (realWorldStatePrimTy `mkVisFunTy` ccall_res_ty, wrap) }
boxResult result_ty
= do -- It isn't IO, so do unsafePerformIO
-- It's not conveniently available, so we inline it
res <- resultWrapper result_ty
(ccall_res_ty, the_alt) <- mk_alt return_result res
let
wrap = \ the_call -> mkWildCase (App the_call (Var realWorldPrimId))
ccall_res_ty
(coreAltType the_alt)
[the_alt]
return (realWorldStatePrimTy `mkVisFunTy` ccall_res_ty, wrap)
where
return_result _ [ans] = ans
return_result _ _ = panic "return_result: expected single result"
mk_alt :: (Expr Var -> [Expr Var] -> Expr Var)
-> (Maybe Type, Expr Var -> Expr Var)
-> DsM (Type, (AltCon, [Id], Expr Var))
mk_alt return_result (Nothing, wrap_result)
= do -- The ccall returns ()
state_id <- newSysLocalDs realWorldStatePrimTy
let
the_rhs = return_result (Var state_id)
[wrap_result (panic "boxResult")]
ccall_res_ty = mkTupleTy Unboxed [realWorldStatePrimTy]
the_alt = (DataAlt (tupleDataCon Unboxed 1), [state_id], the_rhs)
return (ccall_res_ty, the_alt)
mk_alt return_result (Just prim_res_ty, wrap_result)
= -- The ccall returns a non-() value
ASSERT2( isPrimitiveType prim_res_ty, ppr prim_res_ty )
-- True because resultWrapper ensures it is so
do { result_id <- newSysLocalDs prim_res_ty
; state_id <- newSysLocalDs realWorldStatePrimTy
; let the_rhs = return_result (Var state_id)
[wrap_result (Var result_id)]
ccall_res_ty = mkTupleTy Unboxed [realWorldStatePrimTy, prim_res_ty]
the_alt = (DataAlt (tupleDataCon Unboxed 2), [state_id, result_id], the_rhs)
; return (ccall_res_ty, the_alt) }
resultWrapper :: Type
-> DsM (Maybe Type, -- Type of the expected result, if any
CoreExpr -> CoreExpr) -- Wrapper for the result
-- resultWrapper deals with the result *value*
-- E.g. foreign import foo :: Int -> IO T
-- Then resultWrapper deals with marshalling the 'T' part
-- So if resultWrapper ty = (Just ty_rep, marshal)
-- then marshal (e :: ty_rep) :: ty
-- That is, 'marshal' wrape the result returned by the foreign call,
-- of type ty_rep, into the value Haskell expected, of type 'ty'
--
-- Invariant: ty_rep is always a primitive type
-- i.e. (isPrimitiveType ty_rep) is True
resultWrapper result_ty
-- Base case 1: primitive types
| isPrimitiveType result_ty
= return (Just result_ty, \e -> e)
-- Base case 2: the unit type ()
| Just (tc,_) <- maybe_tc_app
, tc `hasKey` unitTyConKey
= return (Nothing, \_ -> Var unitDataConId)
-- Base case 3: the boolean type
| Just (tc,_) <- maybe_tc_app
, tc `hasKey` boolTyConKey
= do { dflags <- getDynFlags
; let marshal_bool e
= mkWildCase e intPrimTy boolTy
[ (DEFAULT ,[],Var trueDataConId )
, (LitAlt (mkLitInt dflags 0),[],Var falseDataConId)]
; return (Just intPrimTy, marshal_bool) }
-- Newtypes
| Just (co, rep_ty) <- topNormaliseNewType_maybe result_ty
= do { (maybe_ty, wrapper) <- resultWrapper rep_ty
; return (maybe_ty, \e -> mkCastDs (wrapper e) (mkSymCo co)) }
-- The type might contain foralls (eg. for dummy type arguments,
-- referring to 'Ptr a' is legal).
| Just (tyvar, rest) <- splitForAllTy_maybe result_ty
= do { (maybe_ty, wrapper) <- resultWrapper rest
; return (maybe_ty, \e -> Lam tyvar (wrapper e)) }
-- Data types with a single constructor, which has a single arg
-- This includes types like Ptr and ForeignPtr
| Just (tycon, tycon_arg_tys) <- maybe_tc_app
, Just data_con <- isDataProductTyCon_maybe tycon -- One constructor, no existentials
, [unwrapped_res_ty] <- dataConInstOrigArgTys data_con tycon_arg_tys -- One argument
= do { dflags <- getDynFlags
; (maybe_ty, wrapper) <- resultWrapper unwrapped_res_ty
; let narrow_wrapper = maybeNarrow dflags tycon
marshal_con e = Var (dataConWrapId data_con)
`mkTyApps` tycon_arg_tys
`App` wrapper (narrow_wrapper e)
; return (maybe_ty, marshal_con) }
| otherwise
= pprPanic "resultWrapper" (ppr result_ty)
where
maybe_tc_app = splitTyConApp_maybe result_ty
-- When the result of a foreign call is smaller than the word size, we
-- need to sign- or zero-extend the result up to the word size. The C
-- standard appears to say that this is the responsibility of the
-- caller, not the callee.
maybeNarrow :: DynFlags -> TyCon -> (CoreExpr -> CoreExpr)
maybeNarrow dflags tycon
| tycon `hasKey` int8TyConKey = \e -> App (Var (mkPrimOpId Narrow8IntOp)) e
| tycon `hasKey` int16TyConKey = \e -> App (Var (mkPrimOpId Narrow16IntOp)) e
| tycon `hasKey` int32TyConKey
&& wORD_SIZE dflags > 4 = \e -> App (Var (mkPrimOpId Narrow32IntOp)) e
| tycon `hasKey` word8TyConKey = \e -> App (Var (mkPrimOpId Narrow8WordOp)) e
| tycon `hasKey` word16TyConKey = \e -> App (Var (mkPrimOpId Narrow16WordOp)) e
| tycon `hasKey` word32TyConKey
&& wORD_SIZE dflags > 4 = \e -> App (Var (mkPrimOpId Narrow32WordOp)) e
| otherwise = id
| sdiehl/ghc | compiler/deSugar/DsCCall.hs | Haskell | bsd-3-clause | 14,632 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
#if __GLASGOW_HASKELL__ >= 707
{-# LANGUAGE RoleAnnotations #-}
#endif
-----------------------------------------------------------------------------
-- |
-- Module : Control.Lens.Internal.Context
-- Copyright : (C) 2012-2016 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : experimental
-- Portability : non-portable
--
----------------------------------------------------------------------------
module Control.Lens.Internal.Context
( IndexedFunctor(..)
, IndexedComonad(..)
, IndexedComonadStore(..)
, Sellable(..)
, Context(..), Context'
, Pretext(..), Pretext'
, PretextT(..), PretextT'
) where
import Prelude ()
import Control.Arrow
import qualified Control.Category as C
import Control.Comonad
import Control.Comonad.Store.Class
import Control.Lens.Internal.Indexed
import Control.Lens.Internal.Prelude
import Data.Profunctor.Rep
import Prelude hiding ((.),id)
------------------------------------------------------------------------------
-- IndexedFunctor
------------------------------------------------------------------------------
-- | This is a Bob Atkey -style 2-argument indexed functor.
--
-- It exists as a superclass for 'IndexedComonad' and expresses the functoriality
-- of an 'IndexedComonad' in its third argument.
class IndexedFunctor w where
ifmap :: (s -> t) -> w a b s -> w a b t
------------------------------------------------------------------------------
-- IndexedComonad
------------------------------------------------------------------------------
-- | This is a Bob Atkey -style 2-argument indexed comonad.
--
-- It exists as a superclass for 'IndexedComonad' and expresses the functoriality
-- of an 'IndexedComonad' in its third argument.
--
-- The notion of indexed monads is covered in more depth in Bob Atkey's
-- "Parameterized Notions of Computation" <http://bentnib.org/paramnotions-jfp.pdf>
-- and that construction is dualized here.
class IndexedFunctor w => IndexedComonad w where
#if __GLASGOW_HASKELL__ >= 708
{-# MINIMAL iextract, (iduplicate | iextend) #-}
#endif
-- | extract from an indexed comonadic value when the indices match.
iextract :: w a a t -> t
-- | duplicate an indexed comonadic value splitting the index.
iduplicate :: w a c t -> w a b (w b c t)
iduplicate = iextend id
{-# INLINE iduplicate #-}
-- | extend a indexed comonadic computation splitting the index.
iextend :: (w b c t -> r) -> w a c t -> w a b r
iextend f = ifmap f . iduplicate
{-# INLINE iextend #-}
------------------------------------------------------------------------------
-- IndexedComonadStore
------------------------------------------------------------------------------
-- | This is an indexed analogue to 'ComonadStore' for when you are working with an
-- 'IndexedComonad'.
class IndexedComonad w => IndexedComonadStore w where
-- | This is the generalization of 'pos' to an indexed comonad store.
ipos :: w a c t -> a
-- | This is the generalization of 'peek' to an indexed comonad store.
ipeek :: c -> w a c t -> t
ipeek c = iextract . iseek c
{-# INLINE ipeek #-}
-- | This is the generalization of 'peeks' to an indexed comonad store.
ipeeks :: (a -> c) -> w a c t -> t
ipeeks f = iextract . iseeks f
{-# INLINE ipeeks #-}
-- | This is the generalization of 'seek' to an indexed comonad store.
iseek :: b -> w a c t -> w b c t
-- | This is the generalization of 'seeks' to an indexed comonad store.
iseeks :: (a -> b) -> w a c t -> w b c t
-- | This is the generalization of 'experiment' to an indexed comonad store.
iexperiment :: Functor f => (b -> f c) -> w b c t -> f t
iexperiment bfc wbct = (`ipeek` wbct) <$> bfc (ipos wbct)
{-# INLINE iexperiment #-}
-- | We can always forget the rest of the structure of 'w' and obtain a simpler
-- indexed comonad store model called 'Context'.
context :: w a b t -> Context a b t
context wabt = Context (`ipeek` wabt) (ipos wabt)
{-# INLINE context #-}
------------------------------------------------------------------------------
-- Sellable
------------------------------------------------------------------------------
-- | This is used internally to construct a 'Control.Lens.Internal.Bazaar.Bazaar', 'Context' or 'Pretext'
-- from a singleton value.
class Corepresentable p => Sellable p w | w -> p where
sell :: p a (w a b b)
------------------------------------------------------------------------------
-- Context
------------------------------------------------------------------------------
-- | The indexed store can be used to characterize a 'Control.Lens.Lens.Lens'
-- and is used by 'Control.Lens.Lens.cloneLens'.
--
-- @'Context' a b t@ is isomorphic to
-- @newtype 'Context' a b t = 'Context' { runContext :: forall f. 'Functor' f => (a -> f b) -> f t }@,
-- and to @exists s. (s, 'Control.Lens.Lens.Lens' s t a b)@.
--
-- A 'Context' is like a 'Control.Lens.Lens.Lens' that has already been applied to a some structure.
data Context a b t = Context (b -> t) a
-- type role Context representational representational representational
instance IndexedFunctor Context where
ifmap f (Context g t) = Context (f . g) t
{-# INLINE ifmap #-}
instance IndexedComonad Context where
iextract (Context f a) = f a
{-# INLINE iextract #-}
iduplicate (Context f a) = Context (Context f) a
{-# INLINE iduplicate #-}
iextend g (Context f a) = Context (g . Context f) a
{-# INLINE iextend #-}
instance IndexedComonadStore Context where
ipos (Context _ a) = a
{-# INLINE ipos #-}
ipeek b (Context g _) = g b
{-# INLINE ipeek #-}
ipeeks f (Context g a) = g (f a)
{-# INLINE ipeeks #-}
iseek a (Context g _) = Context g a
{-# INLINE iseek #-}
iseeks f (Context g a) = Context g (f a)
{-# INLINE iseeks #-}
iexperiment f (Context g a) = g <$> f a
{-# INLINE iexperiment #-}
context = id
{-# INLINE context #-}
instance Functor (Context a b) where
fmap f (Context g t) = Context (f . g) t
{-# INLINE fmap #-}
instance a ~ b => Comonad (Context a b) where
extract (Context f a) = f a
{-# INLINE extract #-}
duplicate (Context f a) = Context (Context f) a
{-# INLINE duplicate #-}
extend g (Context f a) = Context (g . Context f) a
{-# INLINE extend #-}
instance a ~ b => ComonadStore a (Context a b) where
pos = ipos
{-# INLINE pos #-}
peek = ipeek
{-# INLINE peek #-}
peeks = ipeeks
{-# INLINE peeks #-}
seek = iseek
{-# INLINE seek #-}
seeks = iseeks
{-# INLINE seeks #-}
experiment = iexperiment
{-# INLINE experiment #-}
instance Sellable (->) Context where
sell = Context id
{-# INLINE sell #-}
-- | @type 'Context'' a s = 'Context' a a s@
type Context' a = Context a a
------------------------------------------------------------------------------
-- Pretext
------------------------------------------------------------------------------
-- | This is a generalized form of 'Context' that can be repeatedly cloned with less
-- impact on its performance, and which permits the use of an arbitrary 'Conjoined'
-- 'Profunctor'
newtype Pretext p a b t = Pretext { runPretext :: forall f. Functor f => p a (f b) -> f t }
-- type role Pretext representational nominal nominal nominal
-- | @type 'Pretext'' p a s = 'Pretext' p a a s@
type Pretext' p a = Pretext p a a
instance IndexedFunctor (Pretext p) where
ifmap f (Pretext k) = Pretext (fmap f . k)
{-# INLINE ifmap #-}
instance Functor (Pretext p a b) where
fmap = ifmap
{-# INLINE fmap #-}
instance Conjoined p => IndexedComonad (Pretext p) where
iextract (Pretext m) = runIdentity $ m (arr Identity)
{-# INLINE iextract #-}
iduplicate (Pretext m) = getCompose $ m (Compose #. distrib sell C.. sell)
{-# INLINE iduplicate #-}
instance (a ~ b, Conjoined p) => Comonad (Pretext p a b) where
extract = iextract
{-# INLINE extract #-}
duplicate = iduplicate
{-# INLINE duplicate #-}
instance Conjoined p => IndexedComonadStore (Pretext p) where
ipos (Pretext m) = getConst $ coarr m $ arr Const
{-# INLINE ipos #-}
ipeek a (Pretext m) = runIdentity $ coarr m $ arr (\_ -> Identity a)
{-# INLINE ipeek #-}
ipeeks f (Pretext m) = runIdentity $ coarr m $ arr (Identity . f)
{-# INLINE ipeeks #-}
iseek a (Pretext m) = Pretext (lmap (lmap (const a)) m)
{-# INLINE iseek #-}
iseeks f (Pretext m) = Pretext (lmap (lmap f) m)
{-# INLINE iseeks #-}
iexperiment f (Pretext m) = coarr m (arr f)
{-# INLINE iexperiment #-}
context (Pretext m) = coarr m (arr sell)
{-# INLINE context #-}
instance (a ~ b, Conjoined p) => ComonadStore a (Pretext p a b) where
pos = ipos
{-# INLINE pos #-}
peek = ipeek
{-# INLINE peek #-}
peeks = ipeeks
{-# INLINE peeks #-}
seek = iseek
{-# INLINE seek #-}
seeks = iseeks
{-# INLINE seeks #-}
experiment = iexperiment
{-# INLINE experiment #-}
instance Corepresentable p => Sellable p (Pretext p) where
sell = cotabulate $ \ w -> Pretext (`cosieve` w)
{-# INLINE sell #-}
------------------------------------------------------------------------------
-- PretextT
------------------------------------------------------------------------------
-- | This is a generalized form of 'Context' that can be repeatedly cloned with less
-- impact on its performance, and which permits the use of an arbitrary 'Conjoined'
-- 'Profunctor'.
--
-- The extra phantom 'Functor' is used to let us lie and claim
-- 'Control.Lens.Getter.Getter'-compatibility under limited circumstances.
-- This is used internally to permit a number of combinators to gracefully
-- degrade when applied to a 'Control.Lens.Fold.Fold' or
-- 'Control.Lens.Getter.Getter'.
newtype PretextT p (g :: * -> *) a b t = PretextT { runPretextT :: forall f. Functor f => p a (f b) -> f t }
#if __GLASGOW_HASKELL__ >= 707
-- really we want PretextT p g a b t to permit the last 3 arguments to be representational iff p and f accept representational arguments
-- but that isn't currently an option in GHC
type role PretextT representational nominal nominal nominal nominal
#endif
-- | @type 'PretextT'' p g a s = 'PretextT' p g a a s@
type PretextT' p g a = PretextT p g a a
instance IndexedFunctor (PretextT p g) where
ifmap f (PretextT k) = PretextT (fmap f . k)
{-# INLINE ifmap #-}
instance Functor (PretextT p g a b) where
fmap = ifmap
{-# INLINE fmap #-}
instance Conjoined p => IndexedComonad (PretextT p g) where
iextract (PretextT m) = runIdentity $ m (arr Identity)
{-# INLINE iextract #-}
iduplicate (PretextT m) = getCompose $ m (Compose #. distrib sell C.. sell)
{-# INLINE iduplicate #-}
instance (a ~ b, Conjoined p) => Comonad (PretextT p g a b) where
extract = iextract
{-# INLINE extract #-}
duplicate = iduplicate
{-# INLINE duplicate #-}
instance Conjoined p => IndexedComonadStore (PretextT p g) where
ipos (PretextT m) = getConst $ coarr m $ arr Const
{-# INLINE ipos #-}
ipeek a (PretextT m) = runIdentity $ coarr m $ arr (\_ -> Identity a)
{-# INLINE ipeek #-}
ipeeks f (PretextT m) = runIdentity $ coarr m $ arr (Identity . f)
{-# INLINE ipeeks #-}
iseek a (PretextT m) = PretextT (lmap (lmap (const a)) m)
{-# INLINE iseek #-}
iseeks f (PretextT m) = PretextT (lmap (lmap f) m)
{-# INLINE iseeks #-}
iexperiment f (PretextT m) = coarr m (arr f)
{-# INLINE iexperiment #-}
context (PretextT m) = coarr m (arr sell)
{-# INLINE context #-}
instance (a ~ b, Conjoined p) => ComonadStore a (PretextT p g a b) where
pos = ipos
{-# INLINE pos #-}
peek = ipeek
{-# INLINE peek #-}
peeks = ipeeks
{-# INLINE peeks #-}
seek = iseek
{-# INLINE seek #-}
seeks = iseeks
{-# INLINE seeks #-}
experiment = iexperiment
{-# INLINE experiment #-}
instance Corepresentable p => Sellable p (PretextT p g) where
sell = cotabulate $ \ w -> PretextT (`cosieve` w)
{-# INLINE sell #-}
instance (Profunctor p, Contravariant g) => Contravariant (PretextT p g a b) where
contramap _ = (<$) (error "contramap: PretextT")
{-# INLINE contramap #-}
------------------------------------------------------------------------------
-- Utilities
------------------------------------------------------------------------------
-- | We can convert any 'Conjoined' 'Profunctor' to a function,
-- possibly losing information about an index in the process.
coarr :: (Representable q, Comonad (Rep q)) => q a b -> a -> b
coarr qab = extract . sieve qab
{-# INLINE coarr #-}
| ddssff/lens | src/Control/Lens/Internal/Context.hs | Haskell | bsd-3-clause | 12,647 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE FlexibleContexts #-}
module Analytics
( runAnalytics
, analyzeBoard
) where
import Data.Aeson (eitherDecode, FromJSON)
import Data.Either (rights, lefts)
import Data.Typeable
import Data.List
import Data.Maybe
import Text.Format
import Control.Monad.IO.Class (liftIO, MonadIO)
import Control.Monad.Catch
import Control.Monad.Logger
import Control.Monad.Reader
import Control.Applicative
import Control.Concurrent.ParallelIO
import Control.Concurrent (threadDelay)
import qualified Data.Text as T
import qualified Data.Text.Lazy as L
import qualified Data.ByteString.Lazy.Char8 as C (pack)
import GHC.Generics
import Debug.Trace
import Network.HTTP (simpleHTTP, getRequest, getResponseBody)
import Hakyll.Web.Html (stripTags)
import qualified Post as P
import qualified Logging as Log
import Types
newtype Analytics a = Analytics { unAnalytics :: ReaderT Log.Config (LoggingT IO) a }
deriving (Functor, Applicative, Monad, MonadIO, MonadLogger, MonadReader Log.Config)
runAnalytics :: Analytics a -> IO a
runAnalytics a = runStdoutLoggingT $ runReaderT (unAnalytics a) (Log.mkConfig "Analytics")
bmemeCount :: Meme -> Board -> Int
bmemeCount meme board = sum $ map (memeCount meme) board
postCount :: Thread -> Int
postCount x = length $ posts x
memeCount :: Meme -> Thread -> Int
memeCount meme thread = sum $ (map wordCount (alias meme)) <*> (posts thread)
where wordCount meme post = T.count (T.toLower meme) (T.toLower (fromMaybe "" (P.com post)))
catToThreadNo :: Catalog -> [ThreadID]
catToThreadNo cat = map no (concatMap threads cat)
dubs :: Board -> [Int]
dubs b = filter isDubs $ map P.no (concatMap posts b)
where
isDubs :: Int -> Bool
isDubs x = case digs x of
x:y:xs -> x == y
x -> error $ "Chan.dubs malformed post number" ++ (show x )
-- convert number to list of digits
digs :: Integral x => x -> [x]
digs 0 = []
digs x = x `mod` 10 : digs (x `div` 10)
containsMeme :: T.Text -> P.Post -> Bool
containsMeme meme post
= case (P.com post) of
Nothing -> False
Just com -> T.isInfixOf (T.toLower meme) (T.toLower com)
isAnon :: P.Post -> Bool
isAnon p
= case (P.name p) of
Nothing -> False
Just n -> n == "Anonymous"
isTripcode :: P.Post -> Bool
isTripcode p
= case (P.name p) of
Nothing -> False
Just n -> T.isInfixOf " !!" n
displayPost :: P.Post -> (ThreadID, String)
displayPost post = (P.no post, stripTags $ T.unpack (fromMaybe "" (P.com post)))
analyzeBoard :: (MonadReader Log.Config m, MonadLogger m) => Board -> m ()
analyzeBoard board = do
recordMemes board
recordCount board
recordPosts board
recordDubs board
recordTripcodes board
recordMemes :: (MonadReader Log.Config m, MonadLogger m) => Board -> m ()
recordMemes board = do
Log.info "Top Memes:"
Log.info . show $ map (\x -> (x, bmemeCount x board)) memes
recordCount :: (MonadReader Log.Config m, MonadLogger m) => Board -> m ()
recordCount board = do
Log.info "Post Counts"
let pcs = map postCount board
Log.info $ show pcs
Log.info $ format "Average post count: {0}." [show (realToFrac (sum pcs) / (genericLength pcs))]
recordPosts :: (MonadReader Log.Config m, MonadLogger m) => Board -> m ()
recordPosts board = do
let haskellPosts = filter (containsMeme "haskell") (concatMap posts board)
Log.info $ format "Found {0} haskell posts:\n{1} " [show (length haskellPosts), concatMap (show . displayPost) haskellPosts]
recordDubs :: (MonadReader Log.Config m, MonadLogger m) => Board -> m ()
recordDubs board = do
let ds = map show (dubs board)
Log.info $ format "Found {0} dubs in {1} posts: " [(show (length ds)), show $ length (concatMap posts board)]
Log.info $ unwords ds
recordTripcodes :: (MonadReader Log.Config m, MonadLogger m) => Board -> m ()
recordTripcodes b = do
let ps = concatMap posts b
let anons = filter isAnon ps
let tripcodes = filter isTripcode ps
let tripcodePercent = ((fromIntegral $ length tripcodes) / (fromIntegral $length ps))
Log.info $ format "Found {0} Anonymous posts and {1} tripcode posts out of {2} total posts." [show $ length anons, show $ length tripcodes, show $ length ps]
Log.info $ format "That's {0}" [status tripcodePercent]
where
status :: (Real a, Fractional a)=> a -> String
status tripcodePercent
| tripcodePercent == 0 = "The Best Day Ever!"
| tripcodePercent > 0.1 = "Terrible."
| otherwise = "Same old, same old.."
showT :: Show a => a -> T.Text
showT = T.pack . show
| k4smiley/Chan | src/Analytics.hs | Haskell | bsd-3-clause | 4,721 |
import Control.Monad (unless)
import qualified Data.ByteString as BS
import qualified Data.HashMap.Strict as HM
import qualified Data.Vector as V
import Data.Yaml
import System.Environment (getArgs)
import System.IO (stdout)
main :: IO ()
main = do
vs <- getArgs >>= decodeFiles
unless (null vs) $ do
let bs = encode $ foldr1 mergeObjects vs
BS.hPut stdout bs
decodeFiles :: [String] -> IO [Value]
decodeFiles = mapM $ \f -> do
e <- decodeFileEither f
case e of
Left ex -> error $ showParseException ex
Right v -> return v
mergeObjects :: Value -> Value -> Value
mergeObjects (Object o1) (Object o2) = Object $ HM.unionWith mergeObjects o1 o2
mergeObjects (Array a1) (Array a2) = Array $ (V.++) a1 a2
mergeObjects v1 v2 = error $ "Cannot merge " ++ show v1 ++ " with " ++ show v2
showParseException :: ParseException -> String
showParseException (InvalidYaml (Just ex)) = showYamlException ex
showParseException (AesonException s) = s
showParseException ex = show ex
showYamlException :: YamlException -> String
showYamlException (YamlException s) = show s
showYamlException (YamlParseException p c m) = p ++ " " ++ c ++ " at " ++ show m
| djoyner/yamlmerge | Main.hs | Haskell | bsd-3-clause | 1,224 |
{- |
Copyright : Galois, Inc. 2012-2014
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : non-portable (language extensions)
-}
module Main where
import System.Environment (getArgs)
import Verifier.SAW
processFile :: FilePath -> IO ()
processFile file = do
sc <- mkSharedContext preludeModule
tm <- scReadExternal sc =<< readFile file
putStrLn $ "Shared size: " ++ show (scSharedSize tm)
putStrLn $ "Tree size: " ++ show (scTreeSize tm)
main :: IO ()
main = mapM_ processFile =<< getArgs
| iblumenfeld/saw-core | tools/extcore-info.hs | Haskell | bsd-3-clause | 547 |
import Data.Pipe
import GHC.Event
| YoshikuniJujo/xmpipe | test/testMergeChan.hs | Haskell | bsd-3-clause | 36 |
import Disorder.Core.Main
import qualified Test.Zodiac.HttpClient.Request
import qualified Test.Zodiac.HttpClient.TSRP
main :: IO ()
main =
disorderMain [
Test.Zodiac.HttpClient.Request.tests
, Test.Zodiac.HttpClient.TSRP.tests
]
| ambiata/zodiac | zodiac-http-client/test/test.hs | Haskell | bsd-3-clause | 252 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
-- |
-- Module: $HEADER$
-- Description: TODO
-- Copyright: (c) 2016 Peter Trško
-- License: BSD3
--
-- Stability: experimental
-- Portability: GHC specific language extensions.
--
-- TODO
module Data.DHT.DKS.Type.Message.JoinDone
( JoinDone(..)
)
where
import Data.Eq (Eq)
import Data.Typeable (Typeable)
import GHC.Generics (Generic)
import Text.Show (Show)
import Data.Default.Class (Default(def))
import Data.OverloadedRecords.TH (overloadedRecord)
import Data.DHT.DKS.Type.Hash (DksHash)
data JoinDone = JoinDone
{ _requester :: !DksHash
, _successor :: !DksHash
, _predecessor :: !DksHash
}
deriving (Eq, Generic, Show, Typeable)
overloadedRecord def ''JoinDone
| FPBrno/dht-dks | src/Data/DHT/DKS/Type/Message/JoinDone.hs | Haskell | bsd-3-clause | 988 |
{-# LANGUAGE CPP #-}
module TcInteract (
solveSimpleGivens, -- Solves [EvVar],GivenLoc
solveSimpleWanteds -- Solves Cts
) where
#include "HsVersions.h"
import BasicTypes ()
import TcCanonical
import TcFlatten
import VarSet
import Type
import Unify
import InstEnv( DFunInstType, lookupInstEnv, instanceDFunId )
import CoAxiom(sfInteractTop, sfInteractInert)
import Var
import TcType
import PrelNames (knownNatClassName, knownSymbolClassName, ipClassNameKey )
import Id( idType )
import Class
import TyCon
import FunDeps
import FamInst
import Inst( tyVarsOfCt )
import TcEvidence
import Outputable
import TcRnTypes
import TcErrors
import TcSMonad
import Bag
import Data.List( partition, foldl', deleteFirstsBy )
import VarEnv
import Control.Monad
import Maybes( isJust )
import Pair (Pair(..))
import Unique( hasKey )
import FastString ( sLit )
import DynFlags
import Util
{-
**********************************************************************
* *
* Main Interaction Solver *
* *
**********************************************************************
Note [Basic Simplifier Plan]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1. Pick an element from the WorkList if there exists one with depth
less than our context-stack depth.
2. Run it down the 'stage' pipeline. Stages are:
- canonicalization
- inert reactions
- spontaneous reactions
- top-level intreactions
Each stage returns a StopOrContinue and may have sideffected
the inerts or worklist.
The threading of the stages is as follows:
- If (Stop) is returned by a stage then we start again from Step 1.
- If (ContinueWith ct) is returned by a stage, we feed 'ct' on to
the next stage in the pipeline.
4. If the element has survived (i.e. ContinueWith x) the last stage
then we add him in the inerts and jump back to Step 1.
If in Step 1 no such element exists, we have exceeded our context-stack
depth and will simply fail.
Note [Unflatten after solving the simple wanteds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We unflatten after solving the wc_simples of an implication, and before attempting
to float. This means that
* The fsk/fmv flatten-skolems only survive during solveSimples. We don't
need to worry about then across successive passes over the constraint tree.
(E.g. we don't need the old ic_fsk field of an implication.
* When floating an equality outwards, we don't need to worry about floating its
associated flattening constraints.
* Another tricky case becomes easy: Trac #4935
type instance F True a b = a
type instance F False a b = b
[w] F c a b ~ gamma
(c ~ True) => a ~ gamma
(c ~ False) => b ~ gamma
Obviously this is soluble with gamma := F c a b, and unflattening
will do exactly that after solving the simple constraints and before
attempting the implications. Before, when we were not unflattening,
we had to push Wanted funeqs in as new givens. Yuk!
Another example that becomes easy: indexed_types/should_fail/T7786
[W] BuriedUnder sub k Empty ~ fsk
[W] Intersect fsk inv ~ s
[w] xxx[1] ~ s
[W] forall[2] . (xxx[1] ~ Empty)
=> Intersect (BuriedUnder sub k Empty) inv ~ Empty
Note [Running plugins on unflattened wanteds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There is an annoying mismatch between solveSimpleGivens and
solveSimpleWanteds, because the latter needs to fiddle with the inert
set, unflatten and and zonk the wanteds. It passes the zonked wanteds
to runTcPluginsWanteds, which produces a replacement set of wanteds,
some additional insolubles and a flag indicating whether to go round
the loop again. If so, prepareInertsForImplications is used to remove
the previous wanteds (which will still be in the inert set). Note
that prepareInertsForImplications will discard the insolubles, so we
must keep track of them separately.
-}
solveSimpleGivens :: CtLoc -> [EvVar] -> TcS ()
solveSimpleGivens loc givens
| null givens -- Shortcut for common case
= return ()
| otherwise
= go (map mk_given_ct givens)
where
mk_given_ct ev_id = mkNonCanonical (CtGiven { ctev_evtm = EvId ev_id
, ctev_pred = evVarPred ev_id
, ctev_loc = loc })
go givens = do { solveSimples (listToBag givens)
; new_givens <- runTcPluginsGiven
; when (notNull new_givens) (go new_givens)
}
solveSimpleWanteds :: Cts -> TcS WantedConstraints
solveSimpleWanteds = go emptyBag
where
go insols0 wanteds
= do { solveSimples wanteds
; (implics, tv_eqs, fun_eqs, insols, others) <- getUnsolvedInerts
; unflattened_eqs <- unflatten tv_eqs fun_eqs
-- See Note [Unflatten after solving the simple wanteds]
; zonked <- zonkSimples (others `andCts` unflattened_eqs)
-- Postcondition is that the wl_simples are zonked
; (wanteds', insols', rerun) <- runTcPluginsWanted zonked
-- See Note [Running plugins on unflattened wanteds]
; let all_insols = insols0 `unionBags` insols `unionBags` insols'
; if rerun then do { updInertTcS prepareInertsForImplications
; go all_insols wanteds' }
else return (WC { wc_simple = wanteds'
, wc_insol = all_insols
, wc_impl = implics }) }
-- The main solver loop implements Note [Basic Simplifier Plan]
---------------------------------------------------------------
solveSimples :: Cts -> TcS ()
-- Returns the final InertSet in TcS
-- Has no effect on work-list or residual-iplications
-- The constraints are initially examined in left-to-right order
solveSimples cts
= {-# SCC "solveSimples" #-}
do { dyn_flags <- getDynFlags
; updWorkListTcS (\wl -> foldrBag extendWorkListCt wl cts)
; solve_loop (maxSubGoalDepth dyn_flags) }
where
solve_loop max_depth
= {-# SCC "solve_loop" #-}
do { sel <- selectNextWorkItem max_depth
; case sel of
NoWorkRemaining -- Done, successfuly (modulo frozen)
-> return ()
MaxDepthExceeded cnt ct -- Failure, depth exceeded
-> wrapErrTcS $ solverDepthErrorTcS cnt (ctEvidence ct)
NextWorkItem ct -- More work, loop around!
-> do { runSolverPipeline thePipeline ct; solve_loop max_depth } }
-- | Extract the (inert) givens and invoke the plugins on them.
-- Remove solved givens from the inert set and emit insolubles, but
-- return new work produced so that 'solveSimpleGivens' can feed it back
-- into the main solver.
runTcPluginsGiven :: TcS [Ct]
runTcPluginsGiven = do
(givens,_,_) <- fmap splitInertCans getInertCans
if null givens
then return []
else do
p <- runTcPlugins (givens,[],[])
let (solved_givens, _, _) = pluginSolvedCts p
updInertCans (removeInertCts solved_givens)
mapM_ emitInsoluble (pluginBadCts p)
return (pluginNewCts p)
-- | Given a bag of (flattened, zonked) wanteds, invoke the plugins on
-- them and produce an updated bag of wanteds (possibly with some new
-- work) and a bag of insolubles. The boolean indicates whether
-- 'solveSimpleWanteds' should feed the updated wanteds back into the
-- main solver.
runTcPluginsWanted :: Cts -> TcS (Cts, Cts, Bool)
runTcPluginsWanted zonked_wanteds
| isEmptyBag zonked_wanteds = return (zonked_wanteds, emptyBag, False)
| otherwise = do
(given,derived,_) <- fmap splitInertCans getInertCans
p <- runTcPlugins (given, derived, bagToList zonked_wanteds)
let (solved_givens, solved_deriveds, solved_wanteds) = pluginSolvedCts p
(_, _, wanteds) = pluginInputCts p
updInertCans (removeInertCts $ solved_givens ++ solved_deriveds)
mapM_ setEv solved_wanteds
return ( listToBag $ pluginNewCts p ++ wanteds
, listToBag $ pluginBadCts p
, notNull (pluginNewCts p) )
where
setEv :: (EvTerm,Ct) -> TcS ()
setEv (ev,ct) = case ctEvidence ct of
CtWanted {ctev_evar = evar} -> setWantedEvBind evar ev
_ -> panic "runTcPluginsWanted.setEv: attempt to solve non-wanted!"
-- | A triple of (given, derived, wanted) constraints to pass to plugins
type SplitCts = ([Ct], [Ct], [Ct])
-- | A solved triple of constraints, with evidence for wanteds
type SolvedCts = ([Ct], [Ct], [(EvTerm,Ct)])
-- | Represents collections of constraints generated by typechecker
-- plugins
data TcPluginProgress = TcPluginProgress
{ pluginInputCts :: SplitCts
-- ^ Original inputs to the plugins with solved/bad constraints
-- removed, but otherwise unmodified
, pluginSolvedCts :: SolvedCts
-- ^ Constraints solved by plugins
, pluginBadCts :: [Ct]
-- ^ Constraints reported as insoluble by plugins
, pluginNewCts :: [Ct]
-- ^ New constraints emitted by plugins
}
-- | Starting from a triple of (given, derived, wanted) constraints,
-- invoke each of the typechecker plugins in turn and return
--
-- * the remaining unmodified constraints,
-- * constraints that have been solved,
-- * constraints that are insoluble, and
-- * new work.
--
-- Note that new work generated by one plugin will not be seen by
-- other plugins on this pass (but the main constraint solver will be
-- re-invoked and they will see it later). There is no check that new
-- work differs from the original constraints supplied to the plugin:
-- the plugin itself should perform this check if necessary.
runTcPlugins :: SplitCts -> TcS TcPluginProgress
runTcPlugins all_cts = do
gblEnv <- getGblEnv
foldM do_plugin initialProgress (tcg_tc_plugins gblEnv)
where
do_plugin :: TcPluginProgress -> TcPluginSolver -> TcS TcPluginProgress
do_plugin p solver = do
result <- runTcPluginTcS (uncurry3 solver (pluginInputCts p))
return $ progress p result
progress :: TcPluginProgress -> TcPluginResult -> TcPluginProgress
progress p (TcPluginContradiction bad_cts) =
p { pluginInputCts = discard bad_cts (pluginInputCts p)
, pluginBadCts = bad_cts ++ pluginBadCts p
}
progress p (TcPluginOk solved_cts new_cts) =
p { pluginInputCts = discard (map snd solved_cts) (pluginInputCts p)
, pluginSolvedCts = add solved_cts (pluginSolvedCts p)
, pluginNewCts = new_cts ++ pluginNewCts p
}
initialProgress = TcPluginProgress all_cts ([], [], []) [] []
discard :: [Ct] -> SplitCts -> SplitCts
discard cts (xs, ys, zs) =
(xs `without` cts, ys `without` cts, zs `without` cts)
without :: [Ct] -> [Ct] -> [Ct]
without = deleteFirstsBy eqCt
eqCt :: Ct -> Ct -> Bool
eqCt c c' = case (ctEvidence c, ctEvidence c') of
(CtGiven pred _ _, CtGiven pred' _ _) -> pred `eqType` pred'
(CtWanted pred _ _, CtWanted pred' _ _) -> pred `eqType` pred'
(CtDerived pred _ , CtDerived pred' _ ) -> pred `eqType` pred'
(_ , _ ) -> False
add :: [(EvTerm,Ct)] -> SolvedCts -> SolvedCts
add xs scs = foldl' addOne scs xs
addOne :: SolvedCts -> (EvTerm,Ct) -> SolvedCts
addOne (givens, deriveds, wanteds) (ev,ct) = case ctEvidence ct of
CtGiven {} -> (ct:givens, deriveds, wanteds)
CtDerived{} -> (givens, ct:deriveds, wanteds)
CtWanted {} -> (givens, deriveds, (ev,ct):wanteds)
type WorkItem = Ct
type SimplifierStage = WorkItem -> TcS (StopOrContinue Ct)
data SelectWorkItem
= NoWorkRemaining -- No more work left (effectively we're done!)
| MaxDepthExceeded SubGoalCounter Ct
-- More work left to do but this constraint has exceeded
-- the maximum depth for one of the subgoal counters and we
-- must stop
| NextWorkItem Ct -- More work left, here's the next item to look at
selectNextWorkItem :: SubGoalDepth -- Max depth allowed
-> TcS SelectWorkItem
selectNextWorkItem max_depth
= updWorkListTcS_return pick_next
where
pick_next :: WorkList -> (SelectWorkItem, WorkList)
pick_next wl
= case selectWorkItem wl of
(Nothing,_)
-> (NoWorkRemaining,wl) -- No more work
(Just ct, new_wl)
| Just cnt <- subGoalDepthExceeded max_depth (ctLocDepth (ctLoc ct)) -- Depth exceeded
-> (MaxDepthExceeded cnt ct,new_wl)
(Just ct, new_wl)
-> (NextWorkItem ct, new_wl) -- New workitem and worklist
runSolverPipeline :: [(String,SimplifierStage)] -- The pipeline
-> WorkItem -- The work item
-> TcS ()
-- Run this item down the pipeline, leaving behind new work and inerts
runSolverPipeline pipeline workItem
= do { initial_is <- getTcSInerts
; traceTcS "Start solver pipeline {" $
vcat [ ptext (sLit "work item = ") <+> ppr workItem
, ptext (sLit "inerts = ") <+> ppr initial_is]
; bumpStepCountTcS -- One step for each constraint processed
; final_res <- run_pipeline pipeline (ContinueWith workItem)
; final_is <- getTcSInerts
; case final_res of
Stop ev s -> do { traceFireTcS ev s
; traceTcS "End solver pipeline (discharged) }"
(ptext (sLit "inerts =") <+> ppr final_is)
; return () }
ContinueWith ct -> do { traceFireTcS (ctEvidence ct) (ptext (sLit "Kept as inert"))
; traceTcS "End solver pipeline (not discharged) }" $
vcat [ ptext (sLit "final_item =") <+> ppr ct
, pprTvBndrs (varSetElems $ tyVarsOfCt ct)
, ptext (sLit "inerts =") <+> ppr final_is]
; insertInertItemTcS ct }
}
where run_pipeline :: [(String,SimplifierStage)] -> StopOrContinue Ct
-> TcS (StopOrContinue Ct)
run_pipeline [] res = return res
run_pipeline _ (Stop ev s) = return (Stop ev s)
run_pipeline ((stg_name,stg):stgs) (ContinueWith ct)
= do { traceTcS ("runStage " ++ stg_name ++ " {")
(text "workitem = " <+> ppr ct)
; res <- stg ct
; traceTcS ("end stage " ++ stg_name ++ " }") empty
; run_pipeline stgs res }
{-
Example 1:
Inert: {c ~ d, F a ~ t, b ~ Int, a ~ ty} (all given)
Reagent: a ~ [b] (given)
React with (c~d) ==> IR (ContinueWith (a~[b])) True []
React with (F a ~ t) ==> IR (ContinueWith (a~[b])) False [F [b] ~ t]
React with (b ~ Int) ==> IR (ContinueWith (a~[Int]) True []
Example 2:
Inert: {c ~w d, F a ~g t, b ~w Int, a ~w ty}
Reagent: a ~w [b]
React with (c ~w d) ==> IR (ContinueWith (a~[b])) True []
React with (F a ~g t) ==> IR (ContinueWith (a~[b])) True [] (can't rewrite given with wanted!)
etc.
Example 3:
Inert: {a ~ Int, F Int ~ b} (given)
Reagent: F a ~ b (wanted)
React with (a ~ Int) ==> IR (ContinueWith (F Int ~ b)) True []
React with (F Int ~ b) ==> IR Stop True [] -- after substituting we re-canonicalize and get nothing
-}
thePipeline :: [(String,SimplifierStage)]
thePipeline = [ ("canonicalization", TcCanonical.canonicalize)
, ("interact with inerts", interactWithInertsStage)
, ("top-level reactions", topReactionsStage) ]
{-
*********************************************************************************
* *
The interact-with-inert Stage
* *
*********************************************************************************
Note [The Solver Invariant]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
We always add Givens first. So you might think that the solver has
the invariant
If the work-item is Given,
then the inert item must Given
But this isn't quite true. Suppose we have,
c1: [W] beta ~ [alpha], c2 : [W] blah, c3 :[W] alpha ~ Int
After processing the first two, we get
c1: [G] beta ~ [alpha], c2 : [W] blah
Now, c3 does not interact with the the given c1, so when we spontaneously
solve c3, we must re-react it with the inert set. So we can attempt a
reaction between inert c2 [W] and work-item c3 [G].
It *is* true that [Solver Invariant]
If the work-item is Given,
AND there is a reaction
then the inert item must Given
or, equivalently,
If the work-item is Given,
and the inert item is Wanted/Derived
then there is no reaction
-}
-- Interaction result of WorkItem <~> Ct
type StopNowFlag = Bool -- True <=> stop after this interaction
interactWithInertsStage :: WorkItem -> TcS (StopOrContinue Ct)
-- Precondition: if the workitem is a CTyEqCan then it will not be able to
-- react with anything at this stage.
interactWithInertsStage wi
= do { inerts <- getTcSInerts
; let ics = inert_cans inerts
; case wi of
CTyEqCan {} -> interactTyVarEq ics wi
CFunEqCan {} -> interactFunEq ics wi
CIrredEvCan {} -> interactIrred ics wi
CDictCan {} -> interactDict ics wi
_ -> pprPanic "interactWithInerts" (ppr wi) }
-- CHoleCan are put straight into inert_frozen, so never get here
-- CNonCanonical have been canonicalised
data InteractResult
= IRKeep -- Keep the existing inert constraint in the inert set
| IRReplace -- Replace the existing inert constraint with the work item
| IRDelete -- Delete the existing inert constraint from the inert set
instance Outputable InteractResult where
ppr IRKeep = ptext (sLit "keep")
ppr IRReplace = ptext (sLit "replace")
ppr IRDelete = ptext (sLit "delete")
solveOneFromTheOther :: CtEvidence -- Inert
-> CtEvidence -- WorkItem
-> TcS (InteractResult, StopNowFlag)
-- Preconditions:
-- 1) inert and work item represent evidence for the /same/ predicate
-- 2) ip/class/irred evidence (no coercions) only
solveOneFromTheOther ev_i ev_w
| isDerived ev_w
= return (IRKeep, True)
| isDerived ev_i -- The inert item is Derived, we can just throw it away,
-- The ev_w is inert wrt earlier inert-set items,
-- so it's safe to continue on from this point
= return (IRDelete, False)
| CtWanted { ctev_evar = ev_id } <- ev_w
= do { setWantedEvBind ev_id (ctEvTerm ev_i)
; return (IRKeep, True) }
| CtWanted { ctev_evar = ev_id } <- ev_i
= do { setWantedEvBind ev_id (ctEvTerm ev_w)
; return (IRReplace, True) }
-- So they are both Given
-- See Note [Replacement vs keeping]
| lvl_i == lvl_w
= do { binds <- getTcEvBindsMap
; if has_binding binds ev_w && not (has_binding binds ev_i)
then return (IRReplace, True)
else return (IRKeep, True) }
| otherwise -- Both are Given
= return (if use_replacement then IRReplace else IRKeep, True)
where
pred = ctEvPred ev_i
loc_i = ctEvLoc ev_i
loc_w = ctEvLoc ev_w
lvl_i = ctLocLevel loc_i
lvl_w = ctLocLevel loc_w
has_binding binds ev
| EvId v <- ctEvTerm ev = isJust (lookupEvBind binds v)
| otherwise = True
use_replacement
| isIPPred pred = lvl_w > lvl_i
| otherwise = lvl_w < lvl_i
{-
Note [Replacement vs keeping]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we have two Given constraints both of type (C tys), say, which should
we keep?
* For implicit parameters we want to keep the innermost (deepest)
one, so that it overrides the outer one.
See Note [Shadowing of Implicit Parameters]
* For everything else, we want to keep the outermost one. Reason: that
makes it more likely that the inner one will turn out to be unused,
and can be reported as redundant. See Note [Tracking redundant constraints]
in TcSimplify.
It transpires that using the outermost one is reponsible for an
8% performance improvement in nofib cryptarithm2, compared to
just rolling the dice. I didn't investigate why.
* If there is no "outermost" one, we keep the one that has a non-trivial
evidence binding. Note [Tracking redundant constraints] again.
Example: f :: (Eq a, Ord a) => blah
then we may find [G] sc_sel (d1::Ord a) :: Eq a
[G] d2 :: Eq a
We want to discard d2 in favour of the superclass selection from
the Ord dictionary.
* Finally, when there is still a choice, use IRKeep rather than
IRReplace, to avoid unnecesary munging of the inert set.
Doing the depth-check for implicit parameters, rather than making the work item
always overrride, is important. Consider
data T a where { T1 :: (?x::Int) => T Int; T2 :: T a }
f :: (?x::a) => T a -> Int
f T1 = ?x
f T2 = 3
We have a [G] (?x::a) in the inert set, and at the pattern match on T1 we add
two new givens in the work-list: [G] (?x::Int)
[G] (a ~ Int)
Now consider these steps
- process a~Int, kicking out (?x::a)
- process (?x::Int), the inner given, adding to inert set
- process (?x::a), the outer given, overriding the inner given
Wrong! The depth-check ensures that the inner implicit parameter wins.
(Actually I think that the order in which the work-list is processed means
that this chain of events won't happen, but that's very fragile.)
*********************************************************************************
* *
interactIrred
* *
*********************************************************************************
-}
-- Two pieces of irreducible evidence: if their types are *exactly identical*
-- we can rewrite them. We can never improve using this:
-- if we want ty1 :: Constraint and have ty2 :: Constraint it clearly does not
-- mean that (ty1 ~ ty2)
interactIrred :: InertCans -> Ct -> TcS (StopOrContinue Ct)
interactIrred inerts workItem@(CIrredEvCan { cc_ev = ev_w })
| let pred = ctEvPred ev_w
(matching_irreds, others) = partitionBag (\ct -> ctPred ct `tcEqType` pred)
(inert_irreds inerts)
, (ct_i : rest) <- bagToList matching_irreds
, let ctev_i = ctEvidence ct_i
= ASSERT( null rest )
do { (inert_effect, stop_now) <- solveOneFromTheOther ctev_i ev_w
; case inert_effect of
IRKeep -> return ()
IRDelete -> updInertIrreds (\_ -> others)
IRReplace -> updInertIrreds (\_ -> others `snocCts` workItem)
-- These const upd's assume that solveOneFromTheOther
-- has no side effects on InertCans
; if stop_now then
return (Stop ev_w (ptext (sLit "Irred equal") <+> parens (ppr inert_effect)))
; else
continueWith workItem }
| otherwise
= continueWith workItem
interactIrred _ wi = pprPanic "interactIrred" (ppr wi)
{-
*********************************************************************************
* *
interactDict
* *
*********************************************************************************
-}
interactDict :: InertCans -> Ct -> TcS (StopOrContinue Ct)
interactDict inerts workItem@(CDictCan { cc_ev = ev_w, cc_class = cls, cc_tyargs = tys })
| Just ctev_i <- lookupInertDict inerts (ctEvLoc ev_w) cls tys
= do { (inert_effect, stop_now) <- solveOneFromTheOther ctev_i ev_w
; case inert_effect of
IRKeep -> return ()
IRDelete -> updInertDicts $ \ ds -> delDict ds cls tys
IRReplace -> updInertDicts $ \ ds -> addDict ds cls tys workItem
; if stop_now then
return (Stop ev_w (ptext (sLit "Dict equal") <+> parens (ppr inert_effect)))
else
continueWith workItem }
| cls `hasKey` ipClassNameKey
, isGiven ev_w
= interactGivenIP inerts workItem
| otherwise
= do { mapBagM_ (addFunDepWork workItem) (findDictsByClass (inert_dicts inerts) cls)
-- Standard thing: create derived fds and keep on going. Importantly we don't
-- throw workitem back in the worklist because this can cause loops (see #5236)
; continueWith workItem }
interactDict _ wi = pprPanic "interactDict" (ppr wi)
interactGivenIP :: InertCans -> Ct -> TcS (StopOrContinue Ct)
-- Work item is Given (?x:ty)
-- See Note [Shadowing of Implicit Parameters]
interactGivenIP inerts workItem@(CDictCan { cc_ev = ev, cc_class = cls
, cc_tyargs = tys@(ip_str:_) })
= do { updInertCans $ \cans -> cans { inert_dicts = addDict filtered_dicts cls tys workItem }
; stopWith ev "Given IP" }
where
dicts = inert_dicts inerts
ip_dicts = findDictsByClass dicts cls
other_ip_dicts = filterBag (not . is_this_ip) ip_dicts
filtered_dicts = addDictsByClass dicts cls other_ip_dicts
-- Pick out any Given constraints for the same implicit parameter
is_this_ip (CDictCan { cc_ev = ev, cc_tyargs = ip_str':_ })
= isGiven ev && ip_str `tcEqType` ip_str'
is_this_ip _ = False
interactGivenIP _ wi = pprPanic "interactGivenIP" (ppr wi)
addFunDepWork :: Ct -> Ct -> TcS ()
addFunDepWork work_ct inert_ct
= do { let fd_eqns :: [Equation CtLoc]
fd_eqns = [ eqn { fd_loc = derived_loc }
| eqn <- improveFromAnother inert_pred work_pred ]
; rewriteWithFunDeps fd_eqns
-- We don't really rewrite tys2, see below _rewritten_tys2, so that's ok
-- NB: We do create FDs for given to report insoluble equations that arise
-- from pairs of Givens, and also because of floating when we approximate
-- implications. The relevant test is: typecheck/should_fail/FDsFromGivens.hs
-- Also see Note [When improvement happens]
}
where
work_pred = ctPred work_ct
inert_pred = ctPred inert_ct
work_loc = ctLoc work_ct
inert_loc = ctLoc inert_ct
derived_loc = work_loc { ctl_origin = FunDepOrigin1 work_pred work_loc
inert_pred inert_loc }
{-
Note [Shadowing of Implicit Parameters]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider the following example:
f :: (?x :: Char) => Char
f = let ?x = 'a' in ?x
The "let ?x = ..." generates an implication constraint of the form:
?x :: Char => ?x :: Char
Furthermore, the signature for `f` also generates an implication
constraint, so we end up with the following nested implication:
?x :: Char => (?x :: Char => ?x :: Char)
Note that the wanted (?x :: Char) constraint may be solved in
two incompatible ways: either by using the parameter from the
signature, or by using the local definition. Our intention is
that the local definition should "shadow" the parameter of the
signature, and we implement this as follows: when we add a new
*given* implicit parameter to the inert set, it replaces any existing
givens for the same implicit parameter.
This works for the normal cases but it has an odd side effect
in some pathological programs like this:
-- This is accepted, the second parameter shadows
f1 :: (?x :: Int, ?x :: Char) => Char
f1 = ?x
-- This is rejected, the second parameter shadows
f2 :: (?x :: Int, ?x :: Char) => Int
f2 = ?x
Both of these are actually wrong: when we try to use either one,
we'll get two incompatible wnated constraints (?x :: Int, ?x :: Char),
which would lead to an error.
I can think of two ways to fix this:
1. Simply disallow multiple constratits for the same implicit
parameter---this is never useful, and it can be detected completely
syntactically.
2. Move the shadowing machinery to the location where we nest
implications, and add some code here that will produce an
error if we get multiple givens for the same implicit parameter.
*********************************************************************************
* *
interactFunEq
* *
*********************************************************************************
-}
interactFunEq :: InertCans -> Ct -> TcS (StopOrContinue Ct)
-- Try interacting the work item with the inert set
interactFunEq inerts workItem@(CFunEqCan { cc_ev = ev, cc_fun = tc
, cc_tyargs = args, cc_fsk = fsk })
| Just (CFunEqCan { cc_ev = ev_i, cc_fsk = fsk_i }) <- matching_inerts
= if ev_i `canRewriteOrSame` ev
then -- Rewrite work-item using inert
do { traceTcS "reactFunEq (discharge work item):" $
vcat [ text "workItem =" <+> ppr workItem
, text "inertItem=" <+> ppr ev_i ]
; reactFunEq ev_i fsk_i ev fsk
; stopWith ev "Inert rewrites work item" }
else -- Rewrite intert using work-item
do { traceTcS "reactFunEq (rewrite inert item):" $
vcat [ text "workItem =" <+> ppr workItem
, text "inertItem=" <+> ppr ev_i ]
; updInertFunEqs $ \ feqs -> insertFunEq feqs tc args workItem
-- Do the updInertFunEqs before the reactFunEq, so that
-- we don't kick out the inertItem as well as consuming it!
; reactFunEq ev fsk ev_i fsk_i
; stopWith ev "Work item rewrites inert" }
| Just ops <- isBuiltInSynFamTyCon_maybe tc
= do { let matching_funeqs = findFunEqsByTyCon funeqs tc
; let interact = sfInteractInert ops args (lookupFlattenTyVar eqs fsk)
do_one (CFunEqCan { cc_tyargs = iargs, cc_fsk = ifsk, cc_ev = iev })
= mapM_ (unifyDerived (ctEvLoc iev) Nominal)
(interact iargs (lookupFlattenTyVar eqs ifsk))
do_one ct = pprPanic "interactFunEq" (ppr ct)
; mapM_ do_one matching_funeqs
; traceTcS "builtInCandidates 1: " $ vcat [ ptext (sLit "Candidates:") <+> ppr matching_funeqs
, ptext (sLit "TvEqs:") <+> ppr eqs ]
; return (ContinueWith workItem) }
| otherwise
= return (ContinueWith workItem)
where
eqs = inert_eqs inerts
funeqs = inert_funeqs inerts
matching_inerts = findFunEqs funeqs tc args
interactFunEq _ wi = pprPanic "interactFunEq" (ppr wi)
lookupFlattenTyVar :: TyVarEnv EqualCtList -> TcTyVar -> TcType
-- ^ Look up a flatten-tyvar in the inert nominal TyVarEqs;
-- this is used only when dealing with a CFunEqCan
lookupFlattenTyVar inert_eqs ftv
= case lookupVarEnv inert_eqs ftv of
Just (CTyEqCan { cc_rhs = rhs, cc_eq_rel = NomEq } : _) -> rhs
_ -> mkTyVarTy ftv
reactFunEq :: CtEvidence -> TcTyVar -- From this :: F tys ~ fsk1
-> CtEvidence -> TcTyVar -- Solve this :: F tys ~ fsk2
-> TcS ()
reactFunEq from_this fsk1 (CtGiven { ctev_evtm = tm, ctev_loc = loc }) fsk2
= do { let fsk_eq_co = mkTcSymCo (evTermCoercion tm)
`mkTcTransCo` ctEvCoercion from_this
-- :: fsk2 ~ fsk1
fsk_eq_pred = mkTcEqPred (mkTyVarTy fsk2) (mkTyVarTy fsk1)
; new_ev <- newGivenEvVar loc (fsk_eq_pred, EvCoercion fsk_eq_co)
; emitWorkNC [new_ev] }
reactFunEq from_this fuv1 (CtWanted { ctev_evar = evar }) fuv2
= dischargeFmv evar fuv2 (ctEvCoercion from_this) (mkTyVarTy fuv1)
reactFunEq _ _ solve_this@(CtDerived {}) _
= pprPanic "reactFunEq" (ppr solve_this)
{-
Note [Cache-caused loops]
~~~~~~~~~~~~~~~~~~~~~~~~~
It is very dangerous to cache a rewritten wanted family equation as 'solved' in our
solved cache (which is the default behaviour or xCtEvidence), because the interaction
may not be contributing towards a solution. Here is an example:
Initial inert set:
[W] g1 : F a ~ beta1
Work item:
[W] g2 : F a ~ beta2
The work item will react with the inert yielding the _same_ inert set plus:
i) Will set g2 := g1 `cast` g3
ii) Will add to our solved cache that [S] g2 : F a ~ beta2
iii) Will emit [W] g3 : beta1 ~ beta2
Now, the g3 work item will be spontaneously solved to [G] g3 : beta1 ~ beta2
and then it will react the item in the inert ([W] g1 : F a ~ beta1). So it
will set
g1 := g ; sym g3
and what is g? Well it would ideally be a new goal of type (F a ~ beta2) but
remember that we have this in our solved cache, and it is ... g2! In short we
created the evidence loop:
g2 := g1 ; g3
g3 := refl
g1 := g2 ; sym g3
To avoid this situation we do not cache as solved any workitems (or inert)
which did not really made a 'step' towards proving some goal. Solved's are
just an optimization so we don't lose anything in terms of completeness of
solving.
Note [Efficient Orientation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we are interacting two FunEqCans with the same LHS:
(inert) ci :: (F ty ~ xi_i)
(work) cw :: (F ty ~ xi_w)
We prefer to keep the inert (else we pass the work item on down
the pipeline, which is a bit silly). If we keep the inert, we
will (a) discharge 'cw'
(b) produce a new equality work-item (xi_w ~ xi_i)
Notice the orientation (xi_w ~ xi_i) NOT (xi_i ~ xi_w):
new_work :: xi_w ~ xi_i
cw := ci ; sym new_work
Why? Consider the simplest case when xi1 is a type variable. If
we generate xi1~xi2, porcessing that constraint will kick out 'ci'.
If we generate xi2~xi1, there is less chance of that happening.
Of course it can and should still happen if xi1=a, xi1=Int, say.
But we want to avoid it happening needlessly.
Similarly, if we *can't* keep the inert item (because inert is Wanted,
and work is Given, say), we prefer to orient the new equality (xi_i ~
xi_w).
Note [Carefully solve the right CFunEqCan]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
---- OLD COMMENT, NOW NOT NEEDED
---- because we now allow multiple
---- wanted FunEqs with the same head
Consider the constraints
c1 :: F Int ~ a -- Arising from an application line 5
c2 :: F Int ~ Bool -- Arising from an application line 10
Suppose that 'a' is a unification variable, arising only from
flattening. So there is no error on line 5; it's just a flattening
variable. But there is (or might be) an error on line 10.
Two ways to combine them, leaving either (Plan A)
c1 :: F Int ~ a -- Arising from an application line 5
c3 :: a ~ Bool -- Arising from an application line 10
or (Plan B)
c2 :: F Int ~ Bool -- Arising from an application line 10
c4 :: a ~ Bool -- Arising from an application line 5
Plan A will unify c3, leaving c1 :: F Int ~ Bool as an error
on the *totally innocent* line 5. An example is test SimpleFail16
where the expected/actual message comes out backwards if we use
the wrong plan.
The second is the right thing to do. Hence the isMetaTyVarTy
test when solving pairwise CFunEqCan.
*********************************************************************************
* *
interactTyVarEq
* *
*********************************************************************************
-}
interactTyVarEq :: InertCans -> Ct -> TcS (StopOrContinue Ct)
-- CTyEqCans are always consumed, so always returns Stop
interactTyVarEq inerts workItem@(CTyEqCan { cc_tyvar = tv
, cc_rhs = rhs
, cc_ev = ev
, cc_eq_rel = eq_rel })
| (ev_i : _) <- [ ev_i | CTyEqCan { cc_ev = ev_i, cc_rhs = rhs_i }
<- findTyEqs inerts tv
, ev_i `canRewriteOrSame` ev
, rhs_i `tcEqType` rhs ]
= -- Inert: a ~ b
-- Work item: a ~ b
do { setEvBindIfWanted ev (ctEvTerm ev_i)
; stopWith ev "Solved from inert" }
| Just tv_rhs <- getTyVar_maybe rhs
, (ev_i : _) <- [ ev_i | CTyEqCan { cc_ev = ev_i, cc_rhs = rhs_i }
<- findTyEqs inerts tv_rhs
, ev_i `canRewriteOrSame` ev
, rhs_i `tcEqType` mkTyVarTy tv ]
= -- Inert: a ~ b
-- Work item: b ~ a
do { setEvBindIfWanted ev
(EvCoercion (mkTcSymCo (ctEvCoercion ev_i)))
; stopWith ev "Solved from inert (r)" }
| otherwise
= do { tclvl <- getTcLevel
; if canSolveByUnification tclvl ev eq_rel tv rhs
then do { solveByUnification ev tv rhs
; n_kicked <- kickOutRewritable Given NomEq tv
-- Given because the tv := xi is given
-- NomEq because only nom. equalities are solved
-- by unification
; return (Stop ev (ptext (sLit "Spontaneously solved") <+> ppr_kicked n_kicked)) }
else do { traceTcS "Can't solve tyvar equality"
(vcat [ text "LHS:" <+> ppr tv <+> dcolon <+> ppr (tyVarKind tv)
, ppWhen (isMetaTyVar tv) $
nest 4 (text "TcLevel of" <+> ppr tv
<+> text "is" <+> ppr (metaTyVarTcLevel tv))
, text "RHS:" <+> ppr rhs <+> dcolon <+> ppr (typeKind rhs)
, text "TcLevel =" <+> ppr tclvl ])
; n_kicked <- kickOutRewritable (ctEvFlavour ev)
(ctEvEqRel ev)
tv
; updInertCans (\ ics -> addInertCan ics workItem)
; return (Stop ev (ptext (sLit "Kept as inert") <+> ppr_kicked n_kicked)) } }
interactTyVarEq _ wi = pprPanic "interactTyVarEq" (ppr wi)
-- @trySpontaneousSolve wi@ solves equalities where one side is a
-- touchable unification variable.
-- Returns True <=> spontaneous solve happened
canSolveByUnification :: TcLevel -> CtEvidence -> EqRel
-> TcTyVar -> Xi -> Bool
canSolveByUnification tclvl gw eq_rel tv xi
| ReprEq <- eq_rel -- we never solve representational equalities this way.
= False
| isGiven gw -- See Note [Touchables and givens]
= False
| isTouchableMetaTyVar tclvl tv
= case metaTyVarInfo tv of
SigTv -> is_tyvar xi
_ -> True
| otherwise -- Untouchable
= False
where
is_tyvar xi
= case tcGetTyVar_maybe xi of
Nothing -> False
Just tv -> case tcTyVarDetails tv of
MetaTv { mtv_info = info }
-> case info of
SigTv -> True
_ -> False
SkolemTv {} -> True
FlatSkol {} -> False
RuntimeUnk -> True
solveByUnification :: CtEvidence -> TcTyVar -> Xi -> TcS ()
-- Solve with the identity coercion
-- Precondition: kind(xi) is a sub-kind of kind(tv)
-- Precondition: CtEvidence is Wanted or Derived
-- Precondition: CtEvidence is nominal
-- Returns: workItem where
-- workItem = the new Given constraint
--
-- NB: No need for an occurs check here, because solveByUnification always
-- arises from a CTyEqCan, a *canonical* constraint. Its invariants
-- say that in (a ~ xi), the type variable a does not appear in xi.
-- See TcRnTypes.Ct invariants.
--
-- Post: tv is unified (by side effect) with xi;
-- we often write tv := xi
solveByUnification wd tv xi
= do { let tv_ty = mkTyVarTy tv
; traceTcS "Sneaky unification:" $
vcat [text "Unifies:" <+> ppr tv <+> ptext (sLit ":=") <+> ppr xi,
text "Coercion:" <+> pprEq tv_ty xi,
text "Left Kind is:" <+> ppr (typeKind tv_ty),
text "Right Kind is:" <+> ppr (typeKind xi) ]
; let xi' = defaultKind xi
-- We only instantiate kind unification variables
-- with simple kinds like *, not OpenKind or ArgKind
-- cf TcUnify.uUnboundKVar
; setWantedTyBind tv xi'
; setEvBindIfWanted wd (EvCoercion (mkTcNomReflCo xi')) }
ppr_kicked :: Int -> SDoc
ppr_kicked 0 = empty
ppr_kicked n = parens (int n <+> ptext (sLit "kicked out"))
kickOutRewritable :: CtFlavour -- Flavour of the equality that is
-- being added to the inert set
-> EqRel -- of the new equality
-> TcTyVar -- The new equality is tv ~ ty
-> TcS Int
kickOutRewritable new_flavour new_eq_rel new_tv
| not ((new_flavour, new_eq_rel) `eqCanRewriteFR` (new_flavour, new_eq_rel))
= return 0 -- If new_flavour can't rewrite itself, it can't rewrite
-- anything else, so no need to kick out anything
-- This is a common case: wanteds can't rewrite wanteds
| otherwise
= do { ics <- getInertCans
; let (kicked_out, ics') = kick_out new_flavour new_eq_rel new_tv ics
; setInertCans ics'
; updWorkListTcS (appendWorkList kicked_out)
; unless (isEmptyWorkList kicked_out) $
csTraceTcS $
hang (ptext (sLit "Kick out, tv =") <+> ppr new_tv)
2 (vcat [ text "n-kicked =" <+> int (workListSize kicked_out)
, text "n-kept fun-eqs =" <+> int (sizeFunEqMap (inert_funeqs ics'))
, ppr kicked_out ])
; return (workListSize kicked_out) }
kick_out :: CtFlavour -> EqRel -> TcTyVar -> InertCans -> (WorkList, InertCans)
kick_out new_flavour new_eq_rel new_tv (IC { inert_eqs = tv_eqs
, inert_dicts = dictmap
, inert_funeqs = funeqmap
, inert_irreds = irreds
, inert_insols = insols })
= (kicked_out, inert_cans_in)
where
-- NB: Notice that don't rewrite
-- inert_solved_dicts, and inert_solved_funeqs
-- optimistically. But when we lookup we have to
-- take the substitution into account
inert_cans_in = IC { inert_eqs = tv_eqs_in
, inert_dicts = dicts_in
, inert_funeqs = feqs_in
, inert_irreds = irs_in
, inert_insols = insols_in }
kicked_out = WL { wl_eqs = tv_eqs_out
, wl_funeqs = feqs_out
, wl_rest = bagToList (dicts_out `andCts` irs_out
`andCts` insols_out)
, wl_implics = emptyBag }
(tv_eqs_out, tv_eqs_in) = foldVarEnv kick_out_eqs ([], emptyVarEnv) tv_eqs
(feqs_out, feqs_in) = partitionFunEqs kick_out_ct funeqmap
(dicts_out, dicts_in) = partitionDicts kick_out_ct dictmap
(irs_out, irs_in) = partitionBag kick_out_irred irreds
(insols_out, insols_in) = partitionBag kick_out_ct insols
-- Kick out even insolubles; see Note [Kick out insolubles]
can_rewrite :: CtEvidence -> Bool
can_rewrite = ((new_flavour, new_eq_rel) `eqCanRewriteFR`) . ctEvFlavourRole
kick_out_ct :: Ct -> Bool
kick_out_ct ct = kick_out_ctev (ctEvidence ct)
kick_out_ctev :: CtEvidence -> Bool
kick_out_ctev ev = can_rewrite ev
&& new_tv `elemVarSet` tyVarsOfType (ctEvPred ev)
-- See Note [Kicking out inert constraints]
kick_out_irred :: Ct -> Bool
kick_out_irred ct = can_rewrite (cc_ev ct)
&& new_tv `elemVarSet` closeOverKinds (tyVarsOfCt ct)
-- See Note [Kicking out Irreds]
kick_out_eqs :: EqualCtList -> ([Ct], TyVarEnv EqualCtList)
-> ([Ct], TyVarEnv EqualCtList)
kick_out_eqs eqs (acc_out, acc_in)
= (eqs_out ++ acc_out, case eqs_in of
[] -> acc_in
(eq1:_) -> extendVarEnv acc_in (cc_tyvar eq1) eqs_in)
where
(eqs_in, eqs_out) = partition keep_eq eqs
-- implements criteria K1-K3 in Note [The inert equalities] in TcFlatten
keep_eq (CTyEqCan { cc_tyvar = tv, cc_rhs = rhs_ty, cc_ev = ev
, cc_eq_rel = eq_rel })
| tv == new_tv
= not (can_rewrite ev) -- (K1)
| otherwise
= check_k2 && check_k3
where
check_k2 = not (ev `eqCanRewrite` ev)
|| not (can_rewrite ev)
|| not (new_tv `elemVarSet` tyVarsOfType rhs_ty)
check_k3
| can_rewrite ev
= case eq_rel of
NomEq -> not (rhs_ty `eqType` mkTyVarTy new_tv)
ReprEq -> isTyVarExposed new_tv rhs_ty
| otherwise
= True
keep_eq ct = pprPanic "keep_eq" (ppr ct)
{-
Note [Kicking out inert constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Given a new (a -> ty) inert, we want to kick out an existing inert
constraint if
a) the new constraint can rewrite the inert one
b) 'a' is free in the inert constraint (so that it *will*)
rewrite it if we kick it out.
For (b) we use tyVarsOfCt, which returns the type variables /and
the kind variables/ that are directly visible in the type. Hence we
will have exposed all the rewriting we care about to make the most
precise kinds visible for matching classes etc. No need to kick out
constraints that mention type variables whose kinds contain this
variable! (Except see Note [Kicking out Irreds].)
Note [Kicking out Irreds]
~~~~~~~~~~~~~~~~~~~~~~~~~
There is an awkward special case for Irreds. When we have a
kind-mis-matched equality constraint (a:k1) ~ (ty:k2), we turn it into
an Irred (see Note [Equalities with incompatible kinds] in
TcCanonical). So in this case the free kind variables of k1 and k2
are not visible. More precisely, the type looks like
(~) k1 (a:k1) (ty:k2)
because (~) has kind forall k. k -> k -> Constraint. So the constraint
itself is ill-kinded. We can "see" k1 but not k2. That's why we use
closeOverKinds to make sure we see k2.
This is not pretty. Maybe (~) should have kind
(~) :: forall k1 k1. k1 -> k2 -> Constraint
Note [Kick out insolubles]
~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have an insoluble alpha ~ [alpha], which is insoluble
because an occurs check. And then we unify alpha := [Int].
Then we really want to rewrite the insouluble to [Int] ~ [[Int]].
Now it can be decomposed. Otherwise we end up with a "Can't match
[Int] ~ [[Int]]" which is true, but a bit confusing because the
outer type constructors match.
Note [Avoid double unifications]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The spontaneous solver has to return a given which mentions the unified unification
variable *on the left* of the equality. Here is what happens if not:
Original wanted: (a ~ alpha), (alpha ~ Int)
We spontaneously solve the first wanted, without changing the order!
given : a ~ alpha [having unified alpha := a]
Now the second wanted comes along, but he cannot rewrite the given, so we simply continue.
At the end we spontaneously solve that guy, *reunifying* [alpha := Int]
We avoid this problem by orienting the resulting given so that the unification
variable is on the left. [Note that alternatively we could attempt to
enforce this at canonicalization]
See also Note [No touchables as FunEq RHS] in TcSMonad; avoiding
double unifications is the main reason we disallow touchable
unification variables as RHS of type family equations: F xis ~ alpha.
************************************************************************
* *
* Functional dependencies, instantiation of equations
* *
************************************************************************
When we spot an equality arising from a functional dependency,
we now use that equality (a "wanted") to rewrite the work-item
constraint right away. This avoids two dangers
Danger 1: If we send the original constraint on down the pipeline
it may react with an instance declaration, and in delicate
situations (when a Given overlaps with an instance) that
may produce new insoluble goals: see Trac #4952
Danger 2: If we don't rewrite the constraint, it may re-react
with the same thing later, and produce the same equality
again --> termination worries.
To achieve this required some refactoring of FunDeps.lhs (nicer
now!).
-}
rewriteWithFunDeps :: [Equation CtLoc] -> TcS ()
-- NB: The returned constraints are all Derived
-- Post: returns no trivial equalities (identities) and all EvVars returned are fresh
rewriteWithFunDeps eqn_pred_locs
= mapM_ instFunDepEqn eqn_pred_locs
instFunDepEqn :: Equation CtLoc -> TcS ()
-- Post: Returns the position index as well as the corresponding FunDep equality
instFunDepEqn (FDEqn { fd_qtvs = tvs, fd_eqs = eqs, fd_loc = loc })
= do { (subst, _) <- instFlexiTcS tvs -- Takes account of kind substitution
; mapM_ (do_one subst) eqs }
where
do_one subst (FDEq { fd_ty_left = ty1, fd_ty_right = ty2 })
= unifyDerived loc Nominal $
Pair (Type.substTy subst ty1) (Type.substTy subst ty2)
{-
*********************************************************************************
* *
The top-reaction Stage
* *
*********************************************************************************
-}
topReactionsStage :: WorkItem -> TcS (StopOrContinue Ct)
topReactionsStage wi
= do { inerts <- getTcSInerts
; tir <- doTopReact inerts wi
; case tir of
ContinueWith wi -> return (ContinueWith wi)
Stop ev s -> return (Stop ev (ptext (sLit "Top react:") <+> s)) }
doTopReact :: InertSet -> WorkItem -> TcS (StopOrContinue Ct)
-- The work item does not react with the inert set, so try interaction with top-level
-- instances. Note:
--
-- (a) The place to add superclasses in not here in doTopReact stage.
-- Instead superclasses are added in the worklist as part of the
-- canonicalization process. See Note [Adding superclasses].
doTopReact inerts work_item
= do { traceTcS "doTopReact" (ppr work_item)
; case work_item of
CDictCan {} -> doTopReactDict inerts work_item
CFunEqCan {} -> doTopReactFunEq work_item
_ -> -- Any other work item does not react with any top-level equations
return (ContinueWith work_item) }
--------------------
doTopReactDict :: InertSet -> Ct -> TcS (StopOrContinue Ct)
-- Try to use type-class instance declarations to simplify the constraint
doTopReactDict inerts work_item@(CDictCan { cc_ev = fl, cc_class = cls
, cc_tyargs = xis })
| not (isWanted fl) -- Never use instances for Given or Derived constraints
= try_fundeps_and_return
| Just ev <- lookupSolvedDict inerts loc cls xis -- Cached
= do { setWantedEvBind dict_id (ctEvTerm ev);
; stopWith fl "Dict/Top (cached)" }
| otherwise -- Not cached
= do { lkup_inst_res <- matchClassInst inerts cls xis loc
; case lkup_inst_res of
GenInst wtvs ev_term -> do { addSolvedDict fl cls xis
; solve_from_instance wtvs ev_term }
NoInstance -> try_fundeps_and_return }
where
dict_id = ASSERT( isWanted fl ) ctEvId fl
pred = mkClassPred cls xis
loc = ctEvLoc fl
solve_from_instance :: [CtEvidence] -> EvTerm -> TcS (StopOrContinue Ct)
-- Precondition: evidence term matches the predicate workItem
solve_from_instance evs ev_term
| null evs
= do { traceTcS "doTopReact/found nullary instance for" $
ppr dict_id
; setWantedEvBind dict_id ev_term
; stopWith fl "Dict/Top (solved, no new work)" }
| otherwise
= do { traceTcS "doTopReact/found non-nullary instance for" $
ppr dict_id
; setWantedEvBind dict_id ev_term
; let mk_new_wanted ev
= mkNonCanonical (ev {ctev_loc = bumpCtLocDepth CountConstraints loc })
; updWorkListTcS (extendWorkListCts (map mk_new_wanted evs))
; stopWith fl "Dict/Top (solved, more work)" }
-- We didn't solve it; so try functional dependencies with
-- the instance environment, and return
-- NB: even if there *are* some functional dependencies against the
-- instance environment, there might be a unique match, and if
-- so we make sure we get on and solve it first. See Note [Weird fundeps]
try_fundeps_and_return
= do { instEnvs <- getInstEnvs
; let fd_eqns :: [Equation CtLoc]
fd_eqns = [ fd { fd_loc = loc { ctl_origin = FunDepOrigin2 pred (ctl_origin loc)
inst_pred inst_loc } }
| fd@(FDEqn { fd_loc = inst_loc, fd_pred1 = inst_pred })
<- improveFromInstEnv instEnvs pred ]
; rewriteWithFunDeps fd_eqns
; continueWith work_item }
doTopReactDict _ w = pprPanic "doTopReactDict" (ppr w)
--------------------
doTopReactFunEq :: Ct -> TcS (StopOrContinue Ct)
doTopReactFunEq work_item@(CFunEqCan { cc_ev = old_ev, cc_fun = fam_tc
, cc_tyargs = args , cc_fsk = fsk })
= ASSERT(isTypeFamilyTyCon fam_tc) -- No associated data families
-- have reached this far
ASSERT( not (isDerived old_ev) ) -- CFunEqCan is never Derived
-- Look up in top-level instances, or built-in axiom
do { match_res <- matchFam fam_tc args -- See Note [MATCHING-SYNONYMS]
; case match_res of {
Nothing -> do { try_improvement; continueWith work_item } ;
Just (ax_co, rhs_ty)
-- Found a top-level instance
| Just (tc, tc_args) <- tcSplitTyConApp_maybe rhs_ty
, isTypeFamilyTyCon tc
, tc_args `lengthIs` tyConArity tc -- Short-cut
-> shortCutReduction old_ev fsk ax_co tc tc_args
-- Try shortcut; see Note [Short cut for top-level reaction]
| isGiven old_ev -- Not shortcut
-> do { let final_co = mkTcSymCo (ctEvCoercion old_ev) `mkTcTransCo` ax_co
-- final_co :: fsk ~ rhs_ty
; new_ev <- newGivenEvVar deeper_loc (mkTcEqPred (mkTyVarTy fsk) rhs_ty,
EvCoercion final_co)
; emitWorkNC [new_ev] -- Non-cannonical; that will mean we flatten rhs_ty
; stopWith old_ev "Fun/Top (given)" }
| not (fsk `elemVarSet` tyVarsOfType rhs_ty)
-> do { dischargeFmv (ctEvId old_ev) fsk ax_co rhs_ty
; traceTcS "doTopReactFunEq" $
vcat [ text "old_ev:" <+> ppr old_ev
, nest 2 (text ":=") <+> ppr ax_co ]
; stopWith old_ev "Fun/Top (wanted)" }
| otherwise -- We must not assign ufsk := ...ufsk...!
-> do { alpha_ty <- newFlexiTcSTy (tyVarKind fsk)
; new_ev <- newWantedEvVarNC loc (mkTcEqPred alpha_ty rhs_ty)
; emitWorkNC [new_ev]
-- By emitting this as non-canonical, we deal with all
-- flattening, occurs-check, and ufsk := ufsk issues
; let final_co = ax_co `mkTcTransCo` mkTcSymCo (ctEvCoercion new_ev)
-- ax_co :: fam_tc args ~ rhs_ty
-- new_ev :: alpha ~ rhs_ty
-- ufsk := alpha
-- final_co :: fam_tc args ~ alpha
; dischargeFmv (ctEvId old_ev) fsk final_co alpha_ty
; traceTcS "doTopReactFunEq (occurs)" $
vcat [ text "old_ev:" <+> ppr old_ev
, nest 2 (text ":=") <+> ppr final_co
, text "new_ev:" <+> ppr new_ev ]
; stopWith old_ev "Fun/Top (wanted)" } } }
where
loc = ctEvLoc old_ev
deeper_loc = bumpCtLocDepth CountTyFunApps loc
try_improvement
| Just ops <- isBuiltInSynFamTyCon_maybe fam_tc
= do { inert_eqs <- getInertEqs
; let eqns = sfInteractTop ops args (lookupFlattenTyVar inert_eqs fsk)
; mapM_ (unifyDerived loc Nominal) eqns }
| otherwise
= return ()
doTopReactFunEq w = pprPanic "doTopReactFunEq" (ppr w)
shortCutReduction :: CtEvidence -> TcTyVar -> TcCoercion
-> TyCon -> [TcType] -> TcS (StopOrContinue Ct)
shortCutReduction old_ev fsk ax_co fam_tc tc_args
| isGiven old_ev
= ASSERT( ctEvEqRel old_ev == NomEq )
runFlatten $
do { (xis, cos) <- flattenManyNom old_ev tc_args
-- ax_co :: F args ~ G tc_args
-- cos :: xis ~ tc_args
-- old_ev :: F args ~ fsk
-- G cos ; sym ax_co ; old_ev :: G xis ~ fsk
; new_ev <- newGivenEvVar deeper_loc
( mkTcEqPred (mkTyConApp fam_tc xis) (mkTyVarTy fsk)
, EvCoercion (mkTcTyConAppCo Nominal fam_tc cos
`mkTcTransCo` mkTcSymCo ax_co
`mkTcTransCo` ctEvCoercion old_ev) )
; let new_ct = CFunEqCan { cc_ev = new_ev, cc_fun = fam_tc, cc_tyargs = xis, cc_fsk = fsk }
; emitFlatWork new_ct
; stopWith old_ev "Fun/Top (given, shortcut)" }
| otherwise
= ASSERT( not (isDerived old_ev) ) -- Caller ensures this
ASSERT( ctEvEqRel old_ev == NomEq )
do { (xis, cos) <- flattenManyNom old_ev tc_args
-- ax_co :: F args ~ G tc_args
-- cos :: xis ~ tc_args
-- G cos ; sym ax_co ; old_ev :: G xis ~ fsk
-- new_ev :: G xis ~ fsk
-- old_ev :: F args ~ fsk := ax_co ; sym (G cos) ; new_ev
; new_ev <- newWantedEvVarNC deeper_loc
(mkTcEqPred (mkTyConApp fam_tc xis) (mkTyVarTy fsk))
; setWantedEvBind (ctEvId old_ev)
(EvCoercion (ax_co `mkTcTransCo` mkTcSymCo (mkTcTyConAppCo Nominal fam_tc cos)
`mkTcTransCo` ctEvCoercion new_ev))
; let new_ct = CFunEqCan { cc_ev = new_ev, cc_fun = fam_tc, cc_tyargs = xis, cc_fsk = fsk }
; emitFlatWork new_ct
; stopWith old_ev "Fun/Top (wanted, shortcut)" }
where
loc = ctEvLoc old_ev
deeper_loc = bumpCtLocDepth CountTyFunApps loc
dischargeFmv :: EvVar -> TcTyVar -> TcCoercion -> TcType -> TcS ()
-- (dischargeFmv x fmv co ty)
-- [W] x :: F tys ~ fuv
-- co :: F tys ~ ty
-- Precondition: fuv is not filled, and fuv `notElem` ty
--
-- Then set fuv := ty,
-- set x := co
-- kick out any inert things that are now rewritable
dischargeFmv evar fmv co xi
= ASSERT2( not (fmv `elemVarSet` tyVarsOfType xi), ppr evar $$ ppr fmv $$ ppr xi )
do { setWantedTyBind fmv xi
; setWantedEvBind evar (EvCoercion co)
; n_kicked <- kickOutRewritable Given NomEq fmv
; traceTcS "dischargeFuv" (ppr fmv <+> equals <+> ppr xi $$ ppr_kicked n_kicked) }
{-
Note [Cached solved FunEqs]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
When trying to solve, say (FunExpensive big-type ~ ty), it's important
to see if we have reduced (FunExpensive big-type) before, lest we
simply repeat it. Hence the lookup in inert_solved_funeqs. Moreover
we must use `canRewriteOrSame` because both uses might (say) be Wanteds,
and we *still* want to save the re-computation.
Note [MATCHING-SYNONYMS]
~~~~~~~~~~~~~~~~~~~~~~~~
When trying to match a dictionary (D tau) to a top-level instance, or a
type family equation (F taus_1 ~ tau_2) to a top-level family instance,
we do *not* need to expand type synonyms because the matcher will do that for us.
Note [RHS-FAMILY-SYNONYMS]
~~~~~~~~~~~~~~~~~~~~~~~~~~
The RHS of a family instance is represented as yet another constructor which is
like a type synonym for the real RHS the programmer declared. Eg:
type instance F (a,a) = [a]
Becomes:
:R32 a = [a] -- internal type synonym introduced
F (a,a) ~ :R32 a -- instance
When we react a family instance with a type family equation in the work list
we keep the synonym-using RHS without expansion.
Note [FunDep and implicit parameter reactions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Currently, our story of interacting two dictionaries (or a dictionary
and top-level instances) for functional dependencies, and implicit
paramters, is that we simply produce new Derived equalities. So for example
class D a b | a -> b where ...
Inert:
d1 :g D Int Bool
WorkItem:
d2 :w D Int alpha
We generate the extra work item
cv :d alpha ~ Bool
where 'cv' is currently unused. However, this new item can perhaps be
spontaneously solved to become given and react with d2,
discharging it in favour of a new constraint d2' thus:
d2' :w D Int Bool
d2 := d2' |> D Int cv
Now d2' can be discharged from d1
We could be more aggressive and try to *immediately* solve the dictionary
using those extra equalities, but that requires those equalities to carry
evidence and derived do not carry evidence.
If that were the case with the same inert set and work item we might dischard
d2 directly:
cv :w alpha ~ Bool
d2 := d1 |> D Int cv
But in general it's a bit painful to figure out the necessary coercion,
so we just take the first approach. Here is a better example. Consider:
class C a b c | a -> b
And:
[Given] d1 : C T Int Char
[Wanted] d2 : C T beta Int
In this case, it's *not even possible* to solve the wanted immediately.
So we should simply output the functional dependency and add this guy
[but NOT its superclasses] back in the worklist. Even worse:
[Given] d1 : C T Int beta
[Wanted] d2: C T beta Int
Then it is solvable, but its very hard to detect this on the spot.
It's exactly the same with implicit parameters, except that the
"aggressive" approach would be much easier to implement.
Note [When improvement happens]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We fire an improvement rule when
* Two constraints match (modulo the fundep)
e.g. C t1 t2, C t1 t3 where C a b | a->b
The two match because the first arg is identical
Note that we *do* fire the improvement if one is Given and one is Derived (e.g. a
superclass of a Wanted goal) or if both are Given.
Example (tcfail138)
class L a b | a -> b
class (G a, L a b) => C a b
instance C a b' => G (Maybe a)
instance C a b => C (Maybe a) a
instance L (Maybe a) a
When solving the superclasses of the (C (Maybe a) a) instance, we get
Given: C a b ... and hance by superclasses, (G a, L a b)
Wanted: G (Maybe a)
Use the instance decl to get
Wanted: C a b'
The (C a b') is inert, so we generate its Derived superclasses (L a b'),
and now we need improvement between that derived superclass an the Given (L a b)
Test typecheck/should_fail/FDsFromGivens also shows why it's a good idea to
emit Derived FDs for givens as well.
Note [Weird fundeps]
~~~~~~~~~~~~~~~~~~~~
Consider class Het a b | a -> b where
het :: m (f c) -> a -> m b
class GHet (a :: * -> *) (b :: * -> *) | a -> b
instance GHet (K a) (K [a])
instance Het a b => GHet (K a) (K b)
The two instances don't actually conflict on their fundeps,
although it's pretty strange. So they are both accepted. Now
try [W] GHet (K Int) (K Bool)
This triggers fudeps from both instance decls; but it also
matches a *unique* instance decl, and we should go ahead and
pick that one right now. Otherwise, if we don't, it ends up
unsolved in the inert set and is reported as an error.
Trac #7875 is a case in point.
Note [Overriding implicit parameters]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
f :: (?x::a) -> Bool -> a
g v = let ?x::Int = 3
in (f v, let ?x::Bool = True in f v)
This should probably be well typed, with
g :: Bool -> (Int, Bool)
So the inner binding for ?x::Bool *overrides* the outer one.
Hence a work-item Given overrides an inert-item Given.
-}
data LookupInstResult
= NoInstance
| GenInst [CtEvidence] EvTerm
instance Outputable LookupInstResult where
ppr NoInstance = text "NoInstance"
ppr (GenInst ev t) = text "GenInst" <+> ppr ev <+> ppr t
matchClassInst :: InertSet -> Class -> [Type] -> CtLoc -> TcS LookupInstResult
matchClassInst _ clas [ ty ] _
| className clas == knownNatClassName
, Just n <- isNumLitTy ty = makeDict (EvNum n)
| className clas == knownSymbolClassName
, Just s <- isStrLitTy ty = makeDict (EvStr s)
where
{- This adds a coercion that will convert the literal into a dictionary
of the appropriate type. See Note [KnownNat & KnownSymbol and EvLit]
in TcEvidence. The coercion happens in 2 steps:
Integer -> SNat n -- representation of literal to singleton
SNat n -> KnownNat n -- singleton to dictionary
The process is mirrored for Symbols:
String -> SSymbol n
SSymbol n -> KnownSymbol n
-}
makeDict evLit
| Just (_, co_dict) <- tcInstNewTyCon_maybe (classTyCon clas) [ty]
-- co_dict :: KnownNat n ~ SNat n
, [ meth ] <- classMethods clas
, Just tcRep <- tyConAppTyCon_maybe -- SNat
$ funResultTy -- SNat n
$ dropForAlls -- KnownNat n => SNat n
$ idType meth -- forall n. KnownNat n => SNat n
, Just (_, co_rep) <- tcInstNewTyCon_maybe tcRep [ty]
-- SNat n ~ Integer
= return (GenInst [] $ mkEvCast (EvLit evLit) (mkTcSymCo (mkTcTransCo co_dict co_rep)))
| otherwise
= panicTcS (text "Unexpected evidence for" <+> ppr (className clas)
$$ vcat (map (ppr . idType) (classMethods clas)))
matchClassInst inerts clas tys loc
= do { dflags <- getDynFlags
; tclvl <- getTcLevel
; traceTcS "matchClassInst" $ vcat [ text "pred =" <+> ppr pred
, text "inerts=" <+> ppr inerts
, text "untouchables=" <+> ppr tclvl ]
; instEnvs <- getInstEnvs
; case lookupInstEnv instEnvs clas tys of
([], _, _) -- Nothing matches
-> do { traceTcS "matchClass not matching" $
vcat [ text "dict" <+> ppr pred ]
; return NoInstance }
([(ispec, inst_tys)], [], _) -- A single match
| not (xopt Opt_IncoherentInstances dflags)
, given_overlap tclvl
-> -- See Note [Instance and Given overlap]
do { traceTcS "Delaying instance application" $
vcat [ text "Workitem=" <+> pprType (mkClassPred clas tys)
, text "Relevant given dictionaries=" <+> ppr givens_for_this_clas ]
; return NoInstance }
| otherwise
-> do { let dfun_id = instanceDFunId ispec
; traceTcS "matchClass success" $
vcat [text "dict" <+> ppr pred,
text "witness" <+> ppr dfun_id
<+> ppr (idType dfun_id) ]
-- Record that this dfun is needed
; match_one dfun_id inst_tys }
(matches, _, _) -- More than one matches
-- Defer any reactions of a multitude
-- until we learn more about the reagent
-> do { traceTcS "matchClass multiple matches, deferring choice" $
vcat [text "dict" <+> ppr pred,
text "matches" <+> ppr matches]
; return NoInstance } }
where
pred = mkClassPred clas tys
match_one :: DFunId -> [DFunInstType] -> TcS LookupInstResult
-- See Note [DFunInstType: instantiating types] in InstEnv
match_one dfun_id mb_inst_tys
= do { checkWellStagedDFun pred dfun_id loc
; (tys, theta) <- instDFunType dfun_id mb_inst_tys
; evc_vars <- mapM (newWantedEvVar loc) theta
; let new_ev_vars = freshGoals evc_vars
-- new_ev_vars are only the real new variables that can be emitted
dfun_app = EvDFunApp dfun_id tys (map (ctEvTerm . fst) evc_vars)
; return $ GenInst new_ev_vars dfun_app }
givens_for_this_clas :: Cts
givens_for_this_clas
= filterBag isGivenCt (findDictsByClass (inert_dicts $ inert_cans inerts) clas)
given_overlap :: TcLevel -> Bool
given_overlap tclvl = anyBag (matchable tclvl) givens_for_this_clas
matchable tclvl (CDictCan { cc_class = clas_g, cc_tyargs = sys
, cc_ev = fl })
| isGiven fl
= ASSERT( clas_g == clas )
case tcUnifyTys (\tv -> if isTouchableMetaTyVar tclvl tv &&
tv `elemVarSet` tyVarsOfTypes tys
then BindMe else Skolem) tys sys of
-- We can't learn anything more about any variable at this point, so the only
-- cause of overlap can be by an instantiation of a touchable unification
-- variable. Hence we only bind touchable unification variables. In addition,
-- we use tcUnifyTys instead of tcMatchTys to rule out cyclic substitutions.
Nothing -> False
Just _ -> True
| otherwise = False -- No overlap with a solved, already been taken care of
-- by the overlap check with the instance environment.
matchable _tys ct = pprPanic "Expecting dictionary!" (ppr ct)
{-
Note [Instance and Given overlap]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Example, from the OutsideIn(X) paper:
instance P x => Q [x]
instance (x ~ y) => R y [x]
wob :: forall a b. (Q [b], R b a) => a -> Int
g :: forall a. Q [a] => [a] -> Int
g x = wob x
This will generate the impliation constraint:
Q [a] => (Q [beta], R beta [a])
If we react (Q [beta]) with its top-level axiom, we end up with a
(P beta), which we have no way of discharging. On the other hand,
if we react R beta [a] with the top-level we get (beta ~ a), which
is solvable and can help us rewrite (Q [beta]) to (Q [a]) which is
now solvable by the given Q [a].
The solution is that:
In matchClassInst (and thus in topReact), we return a matching
instance only when there is no Given in the inerts which is
unifiable to this particular dictionary.
The end effect is that, much as we do for overlapping instances, we delay choosing a
class instance if there is a possibility of another instance OR a given to match our
constraint later on. This fixes bugs #4981 and #5002.
This is arguably not easy to appear in practice due to our aggressive prioritization
of equality solving over other constraints, but it is possible. I've added a test case
in typecheck/should-compile/GivenOverlapping.hs
We ignore the overlap problem if -XIncoherentInstances is in force: see
Trac #6002 for a worked-out example where this makes a difference.
Moreover notice that our goals here are different than the goals of the top-level
overlapping checks. There we are interested in validating the following principle:
If we inline a function f at a site where the same global instance environment
is available as the instance environment at the definition site of f then we
should get the same behaviour.
But for the Given Overlap check our goal is just related to completeness of
constraint solving.
-}
| green-haskell/ghc | compiler/typecheck/TcInteract.hs | Haskell | bsd-3-clause | 73,245 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.GL.PixelRectangles.Rasterization
-- Copyright : (c) Sven Panne 2002-2005
-- License : BSD-style (see the file libraries/OpenGL/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- This module corresponds to a part of section 3.6.4 (Rasterization of Pixel
-- Rectangles) of the OpenGL 1.5 specs.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.GL.PixelRectangles.Rasterization (
PixelData(..), PixelFormat(..), drawPixels, pixelZoom
) where
import Control.Monad ( liftM2 )
import Foreign.Ptr ( Ptr )
import Graphics.Rendering.OpenGL.GL.BasicTypes ( GLenum, GLsizei, GLfloat )
import Graphics.Rendering.OpenGL.GL.CoordTrans ( Size(..) )
import Graphics.Rendering.OpenGL.GL.PixelData ( PixelData(..), withPixelData )
import Graphics.Rendering.OpenGL.GL.PixelFormat ( PixelFormat(..) )
import Graphics.Rendering.OpenGL.GL.QueryUtils (
GetPName(GetZoomX,GetZoomY), getFloat1 )
import Graphics.Rendering.OpenGL.GL.StateVar ( StateVar, makeStateVar )
--------------------------------------------------------------------------------
drawPixels :: Size -> PixelData a -> IO ()
drawPixels (Size w h) pd = withPixelData pd $ glDrawPixels w h
foreign import CALLCONV unsafe "glDrawPixels" glDrawPixels ::
GLsizei -> GLsizei -> GLenum -> GLenum -> Ptr a -> IO ()
--------------------------------------------------------------------------------
pixelZoom :: StateVar (GLfloat, GLfloat)
pixelZoom =
makeStateVar
(liftM2 (,) (getFloat1 id GetZoomX) (getFloat1 id GetZoomY))
(uncurry glPixelZoom)
foreign import CALLCONV unsafe "glPixelZoom" glPixelZoom ::
GLfloat -> GLfloat -> IO ()
| FranklinChen/hugs98-plus-Sep2006 | packages/OpenGL/Graphics/Rendering/OpenGL/GL/PixelRectangles/Rasterization.hs | Haskell | bsd-3-clause | 1,872 |
----------------------------------------------------------------
-- Модуль приложения
-- Скрипты графического интерфейса (HScript)
-- Язык JavaScript
----------------------------------------------------------------
module WebUI.Scripts.JavaScript.HJavaScript
( module HJavaScriptBuilder
, module HJavaScriptTypes
, module HJavaScriptVars
, module HJavaScriptExps
, module HJavaScriptMath
, module HJavaScriptFunction
, module HJavaScriptElementDOM
, hjs
, ujs
, upjs
, hjsBR
, jsFinish
) where
-- Импорт модулей
import Prelude as PRL
import Data.Char (toLower)
import Data.String.Utils (strip)
import qualified Data.Text.Lazy as DTL
import Data.Int
import Control.Monad.RWS as ConMonRWS
import System.IO.Unsafe (unsafePerformIO)
import Text.Blaze.Html5
import Text.Hamlet
import Text.Lucius
import Text.Cassius
import Text.Julius
import WebUI.Scripts.HScript
import WebUI.Scripts.JavaScript.HJSUtils (smartTrim, ujs, upjs)
import WebUI.Scripts.JavaScript.HJSBuilder as HJavaScriptBuilder
import WebUI.Scripts.JavaScript.HJSTypes as HJavaScriptTypes
import WebUI.Scripts.JavaScript.HJSVars as HJavaScriptVars
import WebUI.Scripts.JavaScript.HJSExps as HJavaScriptExps
import WebUI.Scripts.JavaScript.HJSMath as HJavaScriptMath
import WebUI.Scripts.JavaScript.HJSFunction as HJavaScriptFunction
import WebUI.Scripts.JavaScript.HJSElementDOM as HJavaScriptElementDOM
-- | Подготовка JavaScript
prepareJS b = renderJavascriptUrl undefined b
-- | Виджет скрипта JS
hjs :: JavascriptUrl b
-> HSL HLangJS HLangJS
hjs js = do
hl <- return $ HL $ smartTrim $ do prepareJS js
modify (:> hl)
return hl
-- | Детектор WebGL
hjsBR :: HSL HLangJS HLangJS
hjsBR = do
c <- ask
hl <- return $ HL $ " " ++ (hbc_entryLine c)
modify (:> hl)
return hl
jsFinish :: HSL HLangJS HLFinish
jsFinish = do
return HLFinish
| iqsf/HFitUI | src/WebUI/Scripts/JavaScript/HJavaScript.hs | Haskell | bsd-3-clause | 2,483 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="pt-BR">
<title>Eventos Enviados pelo Servidor | Exstensão do ZAP</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Conteúdo</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Índice</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Busca</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favoritos</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | veggiespam/zap-extensions | addOns/sse/src/main/javahelp/org/zaproxy/zap/extension/sse/resources/help_pt_BR/helpset_pt_BR.hs | Haskell | apache-2.0 | 998 |
{-# LANGUAGE BangPatterns, DeriveDataTypeable #-}
module Eta.Profiling.CostCentre (
CostCentre(..), CcName, IsCafCC(..),
-- All abstract except to friend: ParseIface.y
CostCentreStack,
CollectedCCs,
noCCS, currentCCS, dontCareCCS,
noCCSAttached, isCurrentCCS,
maybeSingletonCCS,
mkUserCC, mkAutoCC, mkAllCafsCC,
mkSingletonCCS,
isCafCCS, isCafCC, isSccCountCC, sccAbleCC, ccFromThisModule,
pprCostCentreCore,
costCentreUserName, costCentreUserNameFS,
costCentreSrcSpan,
cmpCostCentre -- used for removing dups in a list
) where
import Eta.Utils.Binary
import Eta.BasicTypes.Var
import Eta.BasicTypes.Name
import Eta.BasicTypes.Module
import Eta.BasicTypes.Unique
import Eta.Utils.Outputable
import Eta.Utils.FastTypes
import Eta.BasicTypes.SrcLoc
import Eta.Utils.FastString
import Eta.Utils.Util
import Data.Data
-----------------------------------------------------------------------------
-- Cost Centres
-- | A Cost Centre is a single @{-# SCC #-}@ annotation.
data CostCentre
= NormalCC {
cc_key :: {-# UNPACK #-} !Int,
-- ^ Two cost centres may have the same name and
-- module but different SrcSpans, so we need a way to
-- distinguish them easily and give them different
-- object-code labels. So every CostCentre has a
-- Unique that is distinct from every other
-- CostCentre in the same module.
--
-- XXX: should really be using Unique here, but we
-- need to derive Data below and there's no Data
-- instance for Unique.
cc_name :: CcName, -- ^ Name of the cost centre itself
cc_mod :: Module, -- ^ Name of module defining this CC.
cc_loc :: SrcSpan,
cc_is_caf :: IsCafCC -- see below
}
| AllCafsCC {
cc_mod :: Module, -- Name of module defining this CC.
cc_loc :: SrcSpan
}
deriving (Data, Typeable)
type CcName = FastString
data IsCafCC = NotCafCC | CafCC
deriving (Eq, Ord, Data, Typeable)
instance Eq CostCentre where
c1 == c2 = case c1 `cmpCostCentre` c2 of { EQ -> True; _ -> False }
instance Ord CostCentre where
compare = cmpCostCentre
cmpCostCentre :: CostCentre -> CostCentre -> Ordering
cmpCostCentre (AllCafsCC {cc_mod = m1}) (AllCafsCC {cc_mod = m2})
= m1 `compare` m2
cmpCostCentre NormalCC {cc_key = n1, cc_mod = m1}
NormalCC {cc_key = n2, cc_mod = m2}
-- first key is module name, then the integer key
= (m1 `compare` m2) `thenCmp` (n1 `compare` n2)
cmpCostCentre other_1 other_2
= let
!tag1 = tag_CC other_1
!tag2 = tag_CC other_2
in
if tag1 <# tag2 then LT else GT
where
tag_CC (NormalCC {}) = _ILIT(0)
tag_CC (AllCafsCC {}) = _ILIT(1)
-----------------------------------------------------------------------------
-- Predicates on CostCentre
isCafCC :: CostCentre -> Bool
isCafCC (AllCafsCC {}) = True
isCafCC (NormalCC {cc_is_caf = CafCC}) = True
isCafCC _ = False
-- | Is this a cost-centre which records scc counts
isSccCountCC :: CostCentre -> Bool
isSccCountCC cc | isCafCC cc = False
| otherwise = True
-- | Is this a cost-centre which can be sccd ?
sccAbleCC :: CostCentre -> Bool
sccAbleCC cc | isCafCC cc = False
| otherwise = True
ccFromThisModule :: CostCentre -> Module -> Bool
ccFromThisModule cc m = cc_mod cc == m
-----------------------------------------------------------------------------
-- Building cost centres
mkUserCC :: FastString -> Module -> SrcSpan -> Unique -> CostCentre
mkUserCC cc_name mod loc key
= NormalCC { cc_key = getKey key, cc_name = cc_name, cc_mod = mod, cc_loc = loc,
cc_is_caf = NotCafCC {-might be changed-}
}
mkAutoCC :: Id -> Module -> IsCafCC -> CostCentre
mkAutoCC id mod is_caf
= NormalCC { cc_key = getKey (getUnique id),
cc_name = str, cc_mod = mod,
cc_loc = nameSrcSpan (getName id),
cc_is_caf = is_caf
}
where
name = getName id
-- beware: only external names are guaranteed to have unique
-- Occnames. If the name is not external, we must append its
-- Unique.
-- See bug #249, tests prof001, prof002, also #2411
str | isExternalName name = occNameFS (getOccName id)
| otherwise = occNameFS (getOccName id)
`appendFS`
mkFastString ('_' : show (getUnique name))
mkAllCafsCC :: Module -> SrcSpan -> CostCentre
mkAllCafsCC m loc = AllCafsCC { cc_mod = m, cc_loc = loc }
-----------------------------------------------------------------------------
-- Cost Centre Stacks
-- | A Cost Centre Stack is something that can be attached to a closure.
-- This is either:
--
-- * the current cost centre stack (CCCS)
-- * a pre-defined cost centre stack (there are several
-- pre-defined CCSs, see below).
data CostCentreStack
= NoCCS
| CurrentCCS -- Pinned on a let(rec)-bound
-- thunk/function/constructor, this says that the
-- cost centre to be attached to the object, when it
-- is allocated, is whatever is in the
-- current-cost-centre-stack register.
| DontCareCCS -- We need a CCS to stick in static closures
-- (for data), but we *don't* expect them to
-- accumulate any costs. But we still need
-- the placeholder. This CCS is it.
| SingletonCCS CostCentre
deriving (Eq, Ord) -- needed for Ord on CLabel
-- synonym for triple which describes the cost centre info in the generated
-- code for a module.
type CollectedCCs
= ( [CostCentre] -- local cost-centres that need to be decl'd
, [CostCentre] -- "extern" cost-centres
, [CostCentreStack] -- pre-defined "singleton" cost centre stacks
)
noCCS, currentCCS, dontCareCCS :: CostCentreStack
noCCS = NoCCS
currentCCS = CurrentCCS
dontCareCCS = DontCareCCS
-----------------------------------------------------------------------------
-- Predicates on Cost-Centre Stacks
noCCSAttached :: CostCentreStack -> Bool
noCCSAttached NoCCS = True
noCCSAttached _ = False
isCurrentCCS :: CostCentreStack -> Bool
isCurrentCCS CurrentCCS = True
isCurrentCCS _ = False
isCafCCS :: CostCentreStack -> Bool
isCafCCS (SingletonCCS cc) = isCafCC cc
isCafCCS _ = False
maybeSingletonCCS :: CostCentreStack -> Maybe CostCentre
maybeSingletonCCS (SingletonCCS cc) = Just cc
maybeSingletonCCS _ = Nothing
mkSingletonCCS :: CostCentre -> CostCentreStack
mkSingletonCCS cc = SingletonCCS cc
-----------------------------------------------------------------------------
-- Printing Cost Centre Stacks.
-- The outputable instance for CostCentreStack prints the CCS as a C
-- expression.
instance Outputable CostCentreStack where
ppr NoCCS = ptext (sLit "NO_CCS")
ppr CurrentCCS = ptext (sLit "CCCS")
ppr DontCareCCS = ptext (sLit "CCS_DONT_CARE")
ppr (SingletonCCS cc) = ppr cc <> ptext (sLit "_ccs")
-----------------------------------------------------------------------------
-- Printing Cost Centres
--
-- There are several different ways in which we might want to print a
-- cost centre:
--
-- - the name of the cost centre, for profiling output (a C string)
-- - the label, i.e. C label for cost centre in .hc file.
-- - the debugging name, for output in -ddump things
-- - the interface name, for printing in _scc_ exprs in iface files.
--
-- The last 3 are derived from costCentreStr below. The first is given
-- by costCentreName.
instance Outputable CostCentre where
ppr cc = getPprStyle $ \ sty ->
if codeStyle sty
then ppCostCentreLbl cc
else text (costCentreUserName cc)
-- Printing in Core
pprCostCentreCore :: CostCentre -> SDoc
pprCostCentreCore (AllCafsCC {cc_mod = m})
= text "__sccC" <+> braces (ppr m)
pprCostCentreCore (NormalCC {cc_key = key, cc_name = n, cc_mod = m, cc_loc = loc,
cc_is_caf = caf})
= text "__scc" <+> braces (hsep [
ppr m <> char '.' <> ftext n,
ifPprDebug (ppr key),
pp_caf caf,
ifPprDebug (ppr loc)
])
pp_caf :: IsCafCC -> SDoc
pp_caf CafCC = text "__C"
pp_caf _ = empty
-- Printing as a C label
ppCostCentreLbl :: CostCentre -> SDoc
ppCostCentreLbl (AllCafsCC {cc_mod = m}) = ppr m <> text "_CAFs_cc"
ppCostCentreLbl (NormalCC {cc_key = k, cc_name = n, cc_mod = m,
cc_is_caf = is_caf})
= ppr m <> char '_' <> ztext (zEncodeFS n) <> char '_' <>
case is_caf of { CafCC -> ptext (sLit "CAF"); _ -> ppr (mkUniqueGrimily k)} <> text "_cc"
-- This is the name to go in the user-displayed string,
-- recorded in the cost centre declaration
costCentreUserName :: CostCentre -> String
costCentreUserName = unpackFS . costCentreUserNameFS
costCentreUserNameFS :: CostCentre -> FastString
costCentreUserNameFS (AllCafsCC {}) = mkFastString "CAF"
costCentreUserNameFS (NormalCC {cc_name = name, cc_is_caf = is_caf})
= case is_caf of
CafCC -> mkFastString "CAF:" `appendFS` name
_ -> name
costCentreSrcSpan :: CostCentre -> SrcSpan
costCentreSrcSpan = cc_loc
instance Binary IsCafCC where
put_ bh CafCC = do
putByte bh 0
put_ bh NotCafCC = do
putByte bh 1
get bh = do
h <- getByte bh
case h of
0 -> do return CafCC
_ -> do return NotCafCC
instance Binary CostCentre where
put_ bh (NormalCC aa ab ac _ad ae) = do
putByte bh 0
put_ bh aa
put_ bh ab
put_ bh ac
put_ bh ae
put_ bh (AllCafsCC ae _af) = do
putByte bh 1
put_ bh ae
get bh = do
h <- getByte bh
case h of
0 -> do aa <- get bh
ab <- get bh
ac <- get bh
ae <- get bh
return (NormalCC aa ab ac noSrcSpan ae)
_ -> do ae <- get bh
return (AllCafsCC ae noSrcSpan)
-- We ignore the SrcSpans in CostCentres when we serialise them,
-- and set the SrcSpans to noSrcSpan when deserialising. This is
-- ok, because we only need the SrcSpan when declaring the
-- CostCentre in the original module, it is not used by importing
-- modules.
| rahulmutt/ghcvm | compiler/Eta/Profiling/CostCentre.hs | Haskell | bsd-3-clause | 11,032 |
{-# LANGUAGE OverloadedStrings #-}
module System.Mesos.Raw.FrameworkInfo where
import System.Mesos.Internal
import System.Mesos.Raw.FrameworkId
type FrameworkInfoPtr = Ptr FrameworkInfo
foreign import ccall "ext/types.h toFrameworkInfo" c_toFrameworkInfo
:: Ptr CChar
-> CInt
-> Ptr CChar
-> CInt
-> Ptr FrameworkIDPtr
-> Ptr CDouble
-> Ptr CBool
-> Ptr CChar
-> CInt
-> Ptr CChar
-> CInt
-> Ptr CChar
-> CInt
-> IO FrameworkInfoPtr
foreign import ccall "ext/types.h fromFrameworkInfo" c_fromFrameworkInfo
:: FrameworkInfoPtr
-> Ptr (Ptr CChar)
-> Ptr CInt
-> Ptr (Ptr CChar)
-> Ptr CInt
-> Ptr FrameworkIDPtr
-> Ptr CBool
-> Ptr CDouble
-> Ptr CBool
-> Ptr CBool
-> Ptr (Ptr CChar)
-> Ptr CInt
-> Ptr (Ptr CChar)
-> Ptr CInt
-> Ptr (Ptr CChar)
-> Ptr CInt
-> IO ()
foreign import ccall "ext/types.h destroyFrameworkInfo" c_destroyFrameworkInfo
:: FrameworkInfoPtr
-> IO ()
instance CPPValue FrameworkInfo where
marshal fi = do
(up, ul) <- cstring $ frameworkInfoUser fi
(np, nl) <- cstring $ frameworkInfoName fi
(rp, rl) <- maybeCString $ frameworkInfoRole fi
(hp, hl) <- maybeCString $ frameworkInfoHostname fi
(pp, pl) <- maybeCString $ frameworkInfoPrincipal fi
fp' <- allocMaybe $ fmap CDouble $ frameworkInfoFailoverTimeout fi
cp' <- allocMaybe $ fmap toCBool $ frameworkInfoCheckpoint fi
let fidFun f = case frameworkInfoId' fi of
Nothing -> f nullPtr
Just r -> do
p <- alloc
fidp <- cppValue r
poke p fidp
f p
fidFun $ \fidp -> liftIO $ c_toFrameworkInfo up
(fromIntegral ul)
np
(fromIntegral nl)
fidp
fp'
cp'
rp
(fromIntegral rl)
hp
(fromIntegral hl)
pp
(fromIntegral pl)
unmarshal fp = do
(up, ul) <- arrayPair
(np, nl) <- arrayPair
idp <- alloc
tps <- alloc
tp <- alloc
cps <- alloc
cp <- alloc
(rp, rl) <- arrayPair
(hp, hl) <- arrayPair
(pp, pl) <- arrayPair
poke up nullPtr
poke ul 0
poke np nullPtr
poke nl 0
poke idp nullPtr
poke rp nullPtr
poke rl 0
poke hp nullPtr
poke hl 0
poke pp nullPtr
poke pl 0
liftIO $ c_fromFrameworkInfo fp up ul np nl idp tps tp cps cp rp rl hp hl pp pl
ubs <- peekCString (up, ul)
nbs <- peekCString (np, nl)
mid <- do
midp <- peek idp
if midp == nullPtr
then return Nothing
else fmap Just $ unmarshal midp
mt <- fmap (fmap (\(CDouble d) -> d)) $ peekMaybePrim tp tps
mc <- fmap (fmap (== 1)) $ peekMaybePrim cp cps
mr <- peekMaybeBS rp rl
mh <- peekMaybeBS hp hl
mp <- peekMaybeBS pp pl
return $ FrameworkInfo ubs nbs mid mt mc mr mh mp
destroy = c_destroyFrameworkInfo
equalExceptDefaults (FrameworkInfo u n i ft cp r hn p) (FrameworkInfo u' n' i' ft' cp' r' hn' p') =
u == u' && n == n' && i == i' && defEq 0 ft ft' && defEq False cp cp' && defEq "*" r r' && hn == hn' && p == p'
| Atidot/hs-mesos | src/System/Mesos/Raw/FrameworkInfo.hs | Haskell | mit | 3,065 |
-- Copyright (c) Microsoft. All rights reserved.
-- Licensed under the MIT license. See LICENSE file in the project root for full license information.
{-# LANGUAGE OverloadedStrings, RecordWildCards #-}
{-|
Copyright : (c) Microsoft
License : MIT
Maintainer : [email protected]
Stability : provisional
Portability : portable
This module defines abstractions for mapping from the Bond type system into the
type system of a target programming language.
-}
module Language.Bond.Codegen.TypeMapping
( -- * Mapping context
MappingContext(..)
, TypeMapping(..)
, TypeNameBuilder
-- * Type mappings
, idlTypeMapping
, cppTypeMapping
, cppCustomAllocTypeMapping
, cppExpandAliasesTypeMapping
, csTypeMapping
, csCollectionInterfacesTypeMapping
, javaTypeMapping
, javaBoxedTypeMapping
-- * Alias mapping
--
-- | <https://microsoft.github.io/bond/manual/compiler.html#type-aliases Type aliases>
-- defined in a schema can optionally be mapped to user specified types.
, AliasMapping(..)
, Fragment(..)
, parseAliasMapping
-- #namespace-mapping#
-- * Namespace mapping
--
-- | Schema namespaces can be mapped into languange-specific namespaces in the
-- generated code.
, NamespaceMapping(..)
, parseNamespaceMapping
-- * Name builders
, getTypeName
, getInstanceTypeName
, getElementTypeName
, getAnnotatedTypeName
, getDeclTypeName
, getQualifiedName
-- * Helper functions
, getNamespace
, getDeclNamespace
, customAliasMapping
-- * TypeMapping helper functions
, elementTypeName
, aliasTypeName
, getAliasDeclTypeName
, declTypeName
, declQualifiedTypeName
) where
import Data.List
import Data.Monoid
import Data.Maybe
import Control.Applicative
import Control.Monad.Reader
import Prelude
import qualified Data.Text.Lazy as L
import Data.Text.Lazy.Builder
import Text.Shakespeare.Text
import Language.Bond.Syntax.Types
import Language.Bond.Syntax.Util
import Language.Bond.Util
import Language.Bond.Codegen.CustomMapping
-- | The 'MappingContext' encapsulates information about mapping Bond types
-- into types in the target language. A context instance is passed to code
-- generation templates.
data MappingContext = MappingContext
{ typeMapping :: TypeMapping
, aliasMapping :: [AliasMapping]
, namespaceMapping :: [NamespaceMapping]
, namespaces :: [Namespace]
}
-- | A type representing a type mapping.
data TypeMapping = TypeMapping
{ language :: Maybe Language
, global :: Builder
, separator :: Builder
, mapType :: Type -> TypeNameBuilder
, fixSyntax :: Builder -> Builder
, instanceMapping :: TypeMapping
, elementMapping :: TypeMapping
, annotatedMapping :: TypeMapping
}
type TypeNameBuilder = Reader MappingContext Builder
-- | Returns the namespace for the 'MappingContext'. The namespace may be
-- different than specified in the schema definition file due to
-- <#namespace-mapping namespace mapping>.
getNamespace :: MappingContext -> QualifiedName
getNamespace c@MappingContext {..} = resolveNamespace c namespaces
-- | Returns the namespace for a 'Declaration' in the specified 'MappingContext'.
getDeclNamespace :: MappingContext -> Declaration -> QualifiedName
getDeclNamespace c = resolveNamespace c . declNamespaces
-- | Builds a qualified name in the specified 'MappingContext'.
getQualifiedName :: MappingContext -> QualifiedName -> Builder
getQualifiedName MappingContext { typeMapping = m } = (global m <>) . sepBy (separator m) toText
-- | Builds the qualified name for a 'Declaration' in the specified
-- 'MappingContext'.
getDeclTypeName :: MappingContext -> Declaration -> Builder
getDeclTypeName c = getQualifiedName c . declQualifiedName c
-- | Builds the name of a 'Type' in the specified 'MappingContext'.
getTypeName :: MappingContext -> Type -> Builder
getTypeName c t = fix' $ runReader (typeName t) c
where
fix' = fixSyntax $ typeMapping c
getAliasDeclTypeName :: MappingContext -> Declaration -> Builder
getAliasDeclTypeName c d = fix' $ runReader (aliasDeclTypeName d) c
where
fix' = fixSyntax $ typeMapping c
-- | Builds the name to be used when instantiating a 'Type'. The instance type
-- name may be different than the type name returned by 'getTypeName' when the
-- latter is an interface.
getInstanceTypeName :: MappingContext -> Type -> Builder
getInstanceTypeName c t = runReader (instanceTypeName t) c
-- | Builds the name to be used when instantiating an element 'Type'.
getElementTypeName :: MappingContext -> Type -> Builder
getElementTypeName c t = runReader (elementTypeName t) c
-- | Builds the annotated name of a 'Type'. The type annotations are used to
-- express type information about a Bond type that doesn't directly map to
-- the target language type system (e.g. distinction between a nullable and
-- non-nullable string in C# type system).
getAnnotatedTypeName :: MappingContext -> Type -> Builder
getAnnotatedTypeName c t = runReader (annotatedTypeName t) c
-- | Returns 'True' if the alias has a custom mapping in the given
-- 'MappingContext'.
customAliasMapping :: MappingContext -> Declaration -> Bool
customAliasMapping = (maybe False (const True) .) . findAliasMapping
-- | The Bond IDL type name mapping.
idlTypeMapping :: TypeMapping
idlTypeMapping = TypeMapping
Nothing
""
"."
idlType
id
idlTypeMapping
idlTypeMapping
idlTypeMapping
-- | The default C++ type name mapping.
cppTypeMapping :: TypeMapping
cppTypeMapping = TypeMapping
(Just Cpp)
"::"
"::"
cppType
cppSyntaxFix
cppTypeMapping
cppTypeMapping
cppTypeMapping
-- | C++ type name mapping using a custom allocator.
cppCustomAllocTypeMapping :: ToText a => Bool -> a -> TypeMapping
cppCustomAllocTypeMapping scoped alloc = TypeMapping
(Just Cpp)
"::"
"::"
(cppTypeCustomAlloc scoped $ toText alloc)
cppSyntaxFix
(cppCustomAllocTypeMapping scoped alloc)
(cppCustomAllocTypeMapping scoped alloc)
(cppCustomAllocTypeMapping scoped alloc)
cppExpandAliasesTypeMapping :: TypeMapping -> TypeMapping
cppExpandAliasesTypeMapping m = m
{ mapType = cppTypeExpandAliases $ mapType m
, instanceMapping = cppExpandAliasesTypeMapping $ instanceMapping m
, elementMapping = cppExpandAliasesTypeMapping $ elementMapping m
, annotatedMapping = cppExpandAliasesTypeMapping $ annotatedMapping m
}
-- | The default C# type name mapping.
csTypeMapping :: TypeMapping
csTypeMapping = TypeMapping
(Just Cs)
"global::"
"."
csType
id
csTypeMapping
csTypeMapping
csAnnotatedTypeMapping
-- | C# type name mapping using interfaces rather than concrete types to
-- represent collections.
csCollectionInterfacesTypeMapping :: TypeMapping
csCollectionInterfacesTypeMapping = TypeMapping
(Just Cs)
"global::"
"."
csInterfaceType
id
csCollectionInstancesTypeMapping
csCollectionInterfacesTypeMapping
csAnnotatedTypeMapping
csCollectionInstancesTypeMapping :: TypeMapping
csCollectionInstancesTypeMapping = csCollectionInterfacesTypeMapping {mapType = csType}
csAnnotatedTypeMapping :: TypeMapping
csAnnotatedTypeMapping = TypeMapping
(Just Cs)
"global::"
"."
(csTypeAnnotation csType)
id
csAnnotatedTypeMapping
csAnnotatedTypeMapping
csAnnotatedTypeMapping
-- | The default Java type name mapping.
javaTypeMapping :: TypeMapping
javaTypeMapping = TypeMapping
(Just Java)
""
"."
javaType
id
javaTypeMapping
javaBoxedTypeMapping
javaTypeMapping
-- | Java type mapping that boxes all primitives.
javaBoxedTypeMapping :: TypeMapping
javaBoxedTypeMapping = TypeMapping
(Just Java)
""
"."
javaBoxedType
id
javaTypeMapping
javaBoxedTypeMapping
javaTypeMapping
infixr 6 <<>>
(<<>>) :: (Monoid r, Monad m) => m r -> m r -> m r
(<<>>) = liftM2 (<>)
infixr 6 <>>
(<>>) :: (Monoid r, Monad m) => r -> m r -> m r
(<>>) x = liftM (x <>)
infixr 6 <<>
(<<>) :: (Monoid r, Monad m) => m r -> r -> m r
(<<>) x y = liftM (<> y) x
pureText :: ToText a => a -> TypeNameBuilder
pureText = pure . toText
commaSepTypeNames :: [Type] -> TypeNameBuilder
commaSepTypeNames [] = return mempty
commaSepTypeNames [x] = typeName x
commaSepTypeNames (x:xs) = typeName x <<>> ", " <>> commaSepTypeNames xs
typeName :: Type -> TypeNameBuilder
typeName t = do
m <- asks $ mapType . typeMapping
m t
localWith :: (TypeMapping -> TypeMapping) -> TypeNameBuilder -> TypeNameBuilder
localWith f = local $ \c -> c { typeMapping = f $ typeMapping c }
-- | Builder for nested element types (e.g. list elements) in context of 'TypeNameBuilder' monad.
-- Used to implement 'mapType' function of 'TypeMapping'.
elementTypeName :: Type -> TypeNameBuilder
elementTypeName = localWith elementMapping . typeName
instanceTypeName :: Type -> TypeNameBuilder
instanceTypeName = localWith instanceMapping . typeName
annotatedTypeName :: Type -> TypeNameBuilder
annotatedTypeName = localWith annotatedMapping . typeName
resolveNamespace :: MappingContext -> [Namespace] -> QualifiedName
resolveNamespace MappingContext {..} ns =
maybe namespaceName toNamespace $ find ((namespaceName ==) . fromNamespace) namespaceMapping
where
namespaceName = nsName . fromJust $ mappingNamespace <|> neutralNamespace <|> fallbackNamespace
mappingNamespace = find ((language typeMapping ==) . nsLanguage) ns
neutralNamespace = find (isNothing . nsLanguage) ns
fallbackNamespace = case (language typeMapping) of
Nothing -> Just $ last ns
Just l -> error $ "No namespace declared for " ++ show l
declQualifiedName :: MappingContext -> Declaration -> QualifiedName
declQualifiedName c decl = getDeclNamespace c decl ++ [declName decl]
-- | Builder for the qualified name for a 'Declaration' in context of 'TypeNameBuilder' monad.
-- Used to implement 'mapType' function of 'TypeMapping'.
declQualifiedTypeName :: Declaration -> TypeNameBuilder
declQualifiedTypeName decl = do
ctx <- ask
return $ getDeclTypeName ctx decl
-- | Builder for the name for a 'Declaration' in context of 'TypeNameBuilder' monad.
-- Used to implement 'mapType' function of 'TypeMapping'.
declTypeName :: Declaration -> TypeNameBuilder
declTypeName decl = do
ctx <- ask
if namespaces ctx == declNamespaces decl
then pureText $ declName decl
else declQualifiedTypeName decl
findAliasMapping :: MappingContext -> Declaration -> Maybe AliasMapping
findAliasMapping ctx a = find isSameAlias $ aliasMapping ctx
where
aliasDeclName = declQualifiedName ctx a
isSameNs = namespaces ctx == declNamespaces a
isSameAlias m = aliasDeclName == aliasName m || isSameNs && [declName a] == aliasName m
-- | Builder for the type alias name in context of 'TypeNameBuilder' monad.
-- Used to implement 'mapType' function of 'TypeMapping'.
aliasTypeName :: Declaration -> [Type] -> TypeNameBuilder
aliasTypeName a args = do
ctx <- ask
case findAliasMapping ctx a of
Just AliasMapping {..} -> foldr ((<<>>) . fragment) (pure mempty) aliasTemplate
Nothing -> typeName $ resolveAlias a args
where
fragment (Fragment s) = pureText s
fragment (Placeholder i) = typeName $ args !! i
aliasDeclTypeName :: Declaration -> TypeNameBuilder
aliasDeclTypeName a@Alias {..} = do
ctx <- ask
case findAliasMapping ctx a of
Just AliasMapping {..} -> foldr ((<<>>) . fragment) (pure mempty) aliasTemplate
Nothing -> typeName aliasType
where
fragment (Fragment s) = pureText s
fragment (Placeholder i) = pureText $ paramName $ declParams !! i
aliasDeclTypeName _ = error "aliasDeclTypeName: impossible happened."
-- | Builder for the type alias element name in context of 'TypeNameBuilder' monad.
aliasElementTypeName :: Declaration -> [Type] -> TypeNameBuilder
aliasElementTypeName a args = do
ctx <- ask
case findAliasMapping ctx a of
Just AliasMapping {..} -> foldr ((<<>>) . fragment) (pure mempty) aliasTemplate
Nothing -> elementTypeName $ resolveAlias a args
where
fragment (Fragment s) = pureText s
fragment (Placeholder i) = elementTypeName $ args !! i
-- IDL type mapping
idlType :: Type -> TypeNameBuilder
idlType BT_Int8 = pure "int8"
idlType BT_Int16 = pure "int16"
idlType BT_Int32 = pure "int32"
idlType BT_Int64 = pure "int64"
idlType BT_UInt8 = pure "uint8"
idlType BT_UInt16 = pure "uint16"
idlType BT_UInt32 = pure "uint32"
idlType BT_UInt64 = pure "uint64"
idlType BT_Float = pure "float"
idlType BT_Double = pure "double"
idlType BT_Bool = pure "bool"
idlType BT_String = pure "string"
idlType BT_WString = pure "wstring"
idlType BT_MetaName = pure "bond_meta::name"
idlType BT_MetaFullName = pure "bond_meta::full_name"
idlType BT_Blob = pure "blob"
idlType (BT_IntTypeArg x) = pureText x
idlType (BT_Maybe type_) = elementTypeName type_
idlType (BT_List element) = "list<" <>> elementTypeName element <<> ">"
idlType (BT_Nullable element) = "nullable<" <>> elementTypeName element <<> ">"
idlType (BT_Vector element) = "vector<" <>> elementTypeName element <<> ">"
idlType (BT_Set element) = "set<" <>> elementTypeName element <<> ">"
idlType (BT_Map key value) = "map<" <>> elementTypeName key <<>> ", " <>> elementTypeName value <<> ">"
idlType (BT_Bonded type_) = "bonded<" <>> elementTypeName type_ <<> ">"
idlType (BT_TypeParam param) = pureText $ paramName param
idlType (BT_UserDefined a@Alias {..} args) = aliasTypeName a args
idlType (BT_UserDefined decl args) = declQualifiedTypeName decl <<>> (angles <$> commaSepTypeNames args)
-- C++ type mapping
cppType :: Type -> TypeNameBuilder
cppType BT_Int8 = pure "int8_t"
cppType BT_Int16 = pure "int16_t"
cppType BT_Int32 = pure "int32_t"
cppType BT_Int64 = pure "int64_t"
cppType BT_UInt8 = pure "uint8_t"
cppType BT_UInt16 = pure "uint16_t"
cppType BT_UInt32 = pure "uint32_t"
cppType BT_UInt64 = pure "uint64_t"
cppType BT_Float = pure "float"
cppType BT_Double = pure "double"
cppType BT_Bool = pure "bool"
cppType BT_String = pure "std::string"
cppType BT_WString = pure "std::wstring"
cppType BT_MetaName = pure "std::string"
cppType BT_MetaFullName = pure "std::string"
cppType BT_Blob = pure "::bond::blob"
cppType (BT_IntTypeArg x) = pureText x
cppType (BT_Maybe type_) = "::bond::maybe<" <>> elementTypeName type_ <<> ">"
cppType (BT_List element) = "std::list<" <>> elementTypeName element <<> ">"
cppType (BT_Nullable element) = "::bond::nullable<" <>> elementTypeName element <<> ">"
cppType (BT_Vector element) = "std::vector<" <>> elementTypeName element <<> ">"
cppType (BT_Set element) = "std::set<" <>> elementTypeName element <<> ">"
cppType (BT_Map key value) = "std::map<" <>> elementTypeName key <<>> ", " <>> elementTypeName value <<> ">"
cppType (BT_Bonded type_) = "::bond::bonded<" <>> elementTypeName type_ <<> ">"
cppType (BT_TypeParam param) = pureText $ paramName param
cppType (BT_UserDefined decl args) = declQualifiedTypeName decl <<>> (angles <$> commaSepTypeNames args)
-- C++ type mapping with custom allocator
cppTypeCustomAlloc :: Bool -> Builder -> Type -> TypeNameBuilder
cppTypeCustomAlloc scoped alloc BT_String = "std::basic_string<char, std::char_traits<char>, " <>> rebindAllocator scoped alloc (pure "char") <<> " >"
cppTypeCustomAlloc scoped alloc BT_WString = "std::basic_string<wchar_t, std::char_traits<wchar_t>, " <>> rebindAllocator scoped alloc (pure "wchar_t") <<> " >"
cppTypeCustomAlloc scoped alloc BT_MetaName = cppTypeCustomAlloc scoped alloc BT_String
cppTypeCustomAlloc scoped alloc BT_MetaFullName = cppTypeCustomAlloc scoped alloc BT_String
cppTypeCustomAlloc scoped alloc (BT_List element) = "std::list<" <>> elementTypeName element <<>> ", " <>> allocator scoped alloc element <<> ">"
cppTypeCustomAlloc scoped alloc (BT_Vector element) = "std::vector<" <>> elementTypeName element <<>> ", " <>> allocator scoped alloc element <<> ">"
cppTypeCustomAlloc scoped alloc (BT_Set element) = "std::set<" <>> elementTypeName element <<>> comparer element <<>> allocator scoped alloc element <<> ">"
cppTypeCustomAlloc scoped alloc (BT_Map key value) = "std::map<" <>> elementTypeName key <<>> ", " <>> elementTypeName value <<>> comparer key <<>> pairAllocator scoped alloc key value <<> ">"
cppTypeCustomAlloc _ _ t = cppType t
cppTypeExpandAliases :: (Type -> TypeNameBuilder) -> Type -> TypeNameBuilder
cppTypeExpandAliases _ (BT_UserDefined a@Alias {..} args) = aliasTypeName a args
cppTypeExpandAliases m t = m t
comparer :: Type -> TypeNameBuilder
comparer t = ", std::less<" <>> elementTypeName t <<> ">, "
rebindAllocator :: Bool -> Builder -> TypeNameBuilder -> TypeNameBuilder
rebindAllocator False alloc element = "typename std::allocator_traits<" <>> alloc <>> ">::template rebind_alloc<" <>> element <<> ">"
rebindAllocator True alloc element = "std::scoped_allocator_adaptor<" <>> rebindAllocator False alloc element <<> " >"
allocator :: Bool -> Builder -> Type -> TypeNameBuilder
allocator scoped alloc element = rebindAllocator scoped alloc $ elementTypeName element
pairAllocator :: Bool -> Builder -> Type -> Type -> TypeNameBuilder
pairAllocator scoped alloc key value = rebindAllocator scoped alloc $ "std::pair<const " <>> elementTypeName key <<>> ", " <>> elementTypeName value <<> "> "
cppSyntaxFix :: Builder -> Builder
cppSyntaxFix = fromLazyText . snd . L.foldr fixInvalid (' ', mempty) . toLazyText
where
fixInvalid c r
-- C++98 requires space between consecutive angle brackets
| c == '>' && fst r == '>' = (c, L.cons c (L.cons ' ' $ snd r))
-- <: is digraph for [
| c == '<' && fst r == ':' = (c, L.cons c (L.cons ' ' $ snd r))
| otherwise = (c, L.cons c (snd r))
-- C# type mapping
csType :: Type -> TypeNameBuilder
csType BT_Int8 = pure "sbyte"
csType BT_Int16 = pure "short"
csType BT_Int32 = pure "int"
csType BT_Int64 = pure "long"
csType BT_UInt8 = pure "byte"
csType BT_UInt16 = pure "ushort"
csType BT_UInt32 = pure "uint"
csType BT_UInt64 = pure "ulong"
csType BT_Float = pure "float"
csType BT_Double = pure "double"
csType BT_Bool = pure "bool"
csType BT_String = pure "string"
csType BT_WString = pure "string"
csType BT_MetaName = pure "string"
csType BT_MetaFullName = pure "string"
csType BT_Blob = pure "System.ArraySegment<byte>"
csType (BT_IntTypeArg x) = pureText x
csType (BT_Maybe type_) = csType (BT_Nullable type_)
csType (BT_Nullable element) = typeName element <<> if isScalar element then "?" else mempty
csType (BT_List element) = "LinkedList<" <>> elementTypeName element <<> ">"
csType (BT_Vector element) = "List<" <>> elementTypeName element <<> ">"
csType (BT_Set element) = "HashSet<" <>> elementTypeName element <<> ">"
csType (BT_Map key value) = "Dictionary<" <>> elementTypeName key <<>> ", " <>> elementTypeName value <<> ">"
csType (BT_Bonded type_) = "global::Bond.IBonded<" <>> typeName type_ <<> ">"
csType (BT_TypeParam param) = pureText $ paramName param
csType (BT_UserDefined a@Alias {} args) = aliasTypeName a args
csType (BT_UserDefined decl args) = declTypeName decl <<>> (angles <$> localWith (const csTypeMapping) (commaSepTypeNames args))
-- C# type mapping with collection interfaces
csInterfaceType :: Type -> TypeNameBuilder
csInterfaceType (BT_List element) = "ICollection<" <>> elementTypeName element <<> ">"
csInterfaceType (BT_Vector element) = "IList<" <>> elementTypeName element <<> ">"
csInterfaceType (BT_Set element) = "ISet<" <>> elementTypeName element <<> ">"
csInterfaceType (BT_Map key value) = "IDictionary<" <>> elementTypeName key <<>> ", " <>> elementTypeName value <<> ">"
csInterfaceType t = csType t
-- C# type annotation mapping
csTypeAnnotation :: (Type -> TypeNameBuilder) -> Type -> TypeNameBuilder
csTypeAnnotation _ BT_WString = pure "global::Bond.Tag.wstring"
csTypeAnnotation _ (BT_Nullable element) = "global::Bond.Tag.nullable<" <>> typeName element <<> ">"
csTypeAnnotation _ (BT_Maybe a@(BT_UserDefined Alias{} _)) = typeName a
csTypeAnnotation _ (BT_TypeParam (TypeParam _ Nothing)) = pure "global::Bond.Tag.classT"
csTypeAnnotation _ (BT_TypeParam (TypeParam _ (Just Value))) = pure "global::Bond.Tag.structT"
csTypeAnnotation _ (BT_UserDefined Alias {aliasType = BT_Blob} _) = pure "global::Bond.Tag.blob"
csTypeAnnotation m t@(BT_UserDefined a@Alias {..} args)
| isContainer t = m t
| otherwise = typeName $ resolveAlias a args
csTypeAnnotation _ (BT_UserDefined decl args) = declTypeName decl <<>> (angles <$> commaSepTypeNames args)
csTypeAnnotation m t = m t
-- Java type mapping
javaType :: Type -> TypeNameBuilder
javaType BT_Int8 = pure "byte"
javaType BT_Int16 = pure "short"
javaType BT_Int32 = pure "int"
javaType BT_Int64 = pure "long"
javaType BT_UInt8 = pure "byte"
javaType BT_UInt16 = pure "short"
javaType BT_UInt32 = pure "int"
javaType BT_UInt64 = pure "long"
javaType BT_Float = pure "float"
javaType BT_Double = pure "double"
javaType BT_Bool = pure "boolean"
javaType BT_String = pure "java.lang.String"
javaType BT_WString = pure "java.lang.String"
javaType BT_MetaName = pure "java.lang.String"
javaType BT_MetaFullName = pure "java.lang.String"
javaType BT_Blob = pure "org.bondlib.Blob"
javaType (BT_IntTypeArg x) = pureText x
javaType (BT_Maybe BT_Int8) = pure "org.bondlib.SomethingByte"
javaType (BT_Maybe BT_Int16) = pure "org.bondlib.SomethingShort"
javaType (BT_Maybe BT_Int32) = pure "org.bondlib.SomethingInteger"
javaType (BT_Maybe BT_Int64) = pure "org.bondlib.SomethingLong"
javaType (BT_Maybe BT_UInt8) = pure "org.bondlib.SomethingByte"
javaType (BT_Maybe BT_UInt16) = pure "org.bondlib.SomethingShort"
javaType (BT_Maybe BT_UInt32) = pure "org.bondlib.SomethingInteger"
javaType (BT_Maybe BT_UInt64) = pure "org.bondlib.SomethingLong"
javaType (BT_Maybe BT_Float) = pure "org.bondlib.SomethingFloat"
javaType (BT_Maybe BT_Double) = pure "org.bondlib.SomethingDouble"
javaType (BT_Maybe BT_Bool) = pure "org.bondlib.SomethingBoolean"
javaType (BT_UserDefined a@Alias {} args) = javaType (resolveAlias a args)
javaType (BT_Maybe (BT_UserDefined a@Alias {} args)) = javaType (BT_Maybe (resolveAlias a args))
javaType (BT_Maybe fieldType) = "org.bondlib.SomethingObject<" <>> javaBoxedType fieldType <<> ">"
javaType (BT_Nullable elementType) = javaBoxedType elementType
javaType (BT_List elementType) = "java.util.List<" <>> elementTypeName elementType <<> ">"
javaType (BT_Vector elementType) = "java.util.List<" <>> elementTypeName elementType <<> ">"
javaType (BT_Set elementType) = "java.util.Set<" <>> elementTypeName elementType <<> ">"
javaType (BT_Map keyType valueType) = "java.util.Map<" <>> elementTypeName keyType <<>> ", " <>> elementTypeName valueType <<> ">"
javaType (BT_TypeParam param) = pureText $ paramName param
javaType (BT_Bonded structType) = "org.bondlib.Bonded<" <>> javaBoxedType structType <<> ">"
javaType (BT_UserDefined decl args) =
declQualifiedTypeName decl <<>> (angles <$> localWith (const javaBoxedTypeMapping) (commaSepTypeNames args))
-- Java type mapping to a reference type with primitive types boxed
javaBoxedType :: Type -> TypeNameBuilder
javaBoxedType BT_Int8 = pure "java.lang.Byte"
javaBoxedType BT_Int16 = pure "java.lang.Short"
javaBoxedType BT_Int32 = pure "java.lang.Integer"
javaBoxedType BT_Int64 = pure "java.lang.Long"
javaBoxedType BT_UInt8 = pure "java.lang.Byte"
javaBoxedType BT_UInt16 = pure "java.lang.Short"
javaBoxedType BT_UInt32 = pure "java.lang.Integer"
javaBoxedType BT_UInt64 = pure "java.lang.Long"
javaBoxedType BT_Float = pure "java.lang.Float"
javaBoxedType BT_Double = pure "java.lang.Double"
javaBoxedType BT_Bool = pure "java.lang.Boolean"
javaBoxedType (BT_UserDefined a@Alias {} args) = aliasElementTypeName a args
javaBoxedType t = javaType t
| jdubrule/bond | compiler/src/Language/Bond/Codegen/TypeMapping.hs | Haskell | mit | 23,861 |
{-# LANGUAGE TypeFamilies #-}
module Data.Mutable.Deque
( Deque
, UDeque
, asUDeque
, SDeque
, asSDeque
, BDeque
, asBDeque
, module Data.Mutable.Class
) where
import Control.Exception (assert)
import Control.Monad (liftM)
import Data.Mutable.Class
import qualified Data.Vector.Generic.Mutable as V
import qualified Data.Vector.Mutable as B
import qualified Data.Vector.Storable.Mutable as S
import qualified Data.Vector.Unboxed.Mutable as U
data DequeState v s a = DequeState
(v s a)
{-# UNPACK #-} !Int -- start
{-# UNPACK #-} !Int -- size
-- | A double-ended queue supporting any underlying vector type and any monad.
--
-- This implements a circular double-ended queue with exponential growth.
--
-- Since 0.2.0
newtype Deque v s a = Deque (MutVar s (DequeState v s a))
-- | A 'Deque' specialized to unboxed vectors.
--
-- Since 0.2.0
type UDeque = Deque U.MVector
-- | A 'Deque' specialized to storable vectors.
--
-- Since 0.2.0
type SDeque = Deque S.MVector
-- | A 'Deque' specialized to boxed vectors.
--
-- Since 0.2.0
type BDeque = Deque B.MVector
-- |
-- Since 0.2.0
asUDeque :: UDeque s a -> UDeque s a
asUDeque = id
-- |
-- Since 0.2.0
asSDeque :: SDeque s a -> SDeque s a
asSDeque = id
-- |
-- Since 0.2.0
asBDeque :: BDeque s a -> BDeque s a
asBDeque = id
instance MutableContainer (Deque v s a) where
type MCState (Deque v s a) = s
instance V.MVector v a => MutableCollection (Deque v s a) where
type CollElement (Deque v s a) = a
newColl = do
v <- V.new baseSize
liftM Deque $ newRef (DequeState v 0 0)
where
baseSize = 32
{-# INLINE newColl #-}
instance V.MVector v a => MutablePopFront (Deque v s a) where
popFront (Deque var) = do
DequeState v start size <- readRef var
if size == 0
then return Nothing
else do
x <- V.unsafeRead v start
let start' = start + 1
start''
| start' >= V.length v = 0
| otherwise = start'
writeRef var $! DequeState v start'' (size - 1)
return $! Just x
{-# INLINE popFront #-}
instance V.MVector v a => MutablePopBack (Deque v s a) where
popBack (Deque var) = do
DequeState v start size <- readRef var
if size == 0
then return Nothing
else do
let size' = size - 1
end = start + size'
end'
| end >= V.length v = end - V.length v
| otherwise = end
x <- V.unsafeRead v end'
writeRef var $! DequeState v start size'
return $! Just x
{-# INLINE popBack #-}
instance V.MVector v a => MutablePushFront (Deque v s a) where
pushFront (Deque var) x = do
DequeState v start size <- readRef var
inner v start size
where
inner v start size = do
if size >= V.length v
then newVector v start size inner
else do
let size' = size + 1
start' = (start - 1) `rem` V.length v
start''
| start' < 0 = V.length v + start'
| otherwise = start'
V.unsafeWrite v start'' x
writeRef var $! DequeState v start'' size'
{-# INLINE pushFront #-}
instance V.MVector v a => MutablePushBack (Deque v s a) where
pushBack (Deque var) x = do
DequeState v start size <- readRef var
inner v start size
where
inner v start size = do
if size >= V.length v
then newVector v start size inner
else do
let end = start + size
end'
| end >= V.length v = end - V.length v
| otherwise = end
V.unsafeWrite v end' x
writeRef var $! DequeState v start (size + 1)
{-# INLINE pushBack #-}
newVector :: (PrimMonad m, V.MVector v a)
=> v (PrimState m) a
-> Int
-> Int
-> (v (PrimState m) a -> Int -> Int -> m b)
-> m b
newVector v size2 sizeOrig f = assert (sizeOrig == V.length v) $ do
v' <- V.unsafeNew (V.length v * 2)
let size1 = V.length v - size2
V.unsafeCopy
(V.unsafeTake size1 v')
(V.unsafeSlice size2 size1 v)
V.unsafeCopy
(V.unsafeSlice size1 size2 v')
(V.unsafeTake size2 v)
f v' 0 sizeOrig
{-# INLINE newVector #-}
| bitemyapp/mutable-containers | Data/Mutable/Deque.hs | Haskell | mit | 4,740 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ru-RU">
<title>Revisit | 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> | 0xkasun/security-tools | src/org/zaproxy/zap/extension/revisit/resources/help_ru_RU/helpset_ru_RU.hs | Haskell | apache-2.0 | 969 |
{-# LANGUAGE ViewPatterns #-}
module PrettyPrint (showExpr) where
import Data.List (intersperse)
import qualified Language.Java.Pretty (prettyPrint)
import Text.PrettyPrint.ANSI.Leijen (Doc, (<+>), (<>), text, dot, colon)
import qualified Text.PrettyPrint.ANSI.Leijen as PP
import Unbound.Generics.LocallyNameless
import qualified Src as S
import Syntax
class Pretty p where
ppr :: (Applicative m, LFresh m) => p -> m Doc
instance Pretty Expr where
ppr (Var x) = return . text . show $ x
ppr (App e es) = PP.parens <$> ((<+>) <$> ppr e <*> (ppr es))
ppr (Lam bnd) = lunbind bnd $ \(delta, b) -> do
delta' <- ppr delta
b' <- ppr b
return (PP.parens $ text "λ" <> delta' <+> dot <+> b')
ppr (Star) = return $ PP.char '★'
ppr (Pi bnd) = lunbind bnd $ \(delta, b) -> do
let Cons bb = delta
let ((x, Embed t), bb') = unrebind bb
b' <- ppr b
if (head (show x) == '_' && isEmpty bb')
then do
t' <- ppr t
return (PP.parens $ t' <+> text "→" <+> b')
else do
delta' <- ppr delta
return (PP.parens $ text "Π" <> delta' <+> dot <+> b')
ppr (Mu b) = lunbind b $ \((x, Embed t), e) -> do
t' <- ppr t
e' <- ppr e
return (PP.parens $ text "μ" <+> (text . show $ x) <+> colon <+> t' <+> dot <+> e')
ppr (F t e) = do
e' <- ppr e
t' <- ppr t
return (text "cast↑" <> PP.brackets t' <+> e')
ppr (U e) = (text "cast↓" <+>) <$> ppr e
ppr (Let bnd) = lunbind bnd $ \((x, Embed e1), e2) -> do
e1' <- ppr e1
e2' <- ppr e2
return (text "let" <+> (text . show $ x) <+> PP.equals <+> e1' PP.<$> text "in" PP.<$> e2')
ppr (LetRec bnd) = lunbind bnd $ \((unrec -> binds, body)) -> do
binds' <- mapM
(\(n, Embed t, Embed e) -> do
e' <- ppr e
t' <- ppr t
return (text (show n) <+> PP.colon <+> t' PP.<$> (PP.indent 2 (PP.equals <+> e'))))
binds
body' <- ppr body
return $ text "let" <+> text "rec" PP.<$>
PP.vcat (intersperse (text "and") (map (PP.indent 2) binds')) PP.<$>
text "in" PP.<$>
body'
ppr (If g e1 e2) = do
g' <- ppr g
e1' <- ppr e1
e2' <- ppr e2
return (text "if" <+> g' <+> text "then" <+> e1' <+> text "else" <+> e2')
ppr (Lit (S.Int n)) = return $ PP.integer n
ppr (Lit (S.String s)) = return $ PP.dquotes (PP.string s)
ppr (Lit (S.Bool b)) = return $ PP.bool b
ppr (Lit (S.Char c)) = return $ PP.char c
ppr (Lit (S.UnitLit)) = return $ text "()"
ppr (PrimOp op e1 e2) = do
e1' <- ppr e1
e2' <- ppr e2
return $ PP.parens (e1' <+> op' <+> e2')
where
op' = text (Language.Java.Pretty.prettyPrint java_op)
java_op =
case op of
S.Arith op' -> op'
S.Compare op' -> op'
S.Logic op' -> op'
ppr Unit = return $ text "Unit"
ppr (JClass "java.lang.Integer") = return $ text "Int"
ppr (JClass "java.lang.String") = return $ text "String"
ppr (JClass "java.lang.Boolean") = return $ text "Bool"
ppr (JClass "java.lang.Character") = return $ text "Char"
ppr (JClass c) = return $ text c
ppr (JNew c args) = do
args' <- mapM ppr args
return (text "new" <+> text c <> PP.parens (PP.cat $ PP.punctuate PP.comma args'))
ppr (JMethod rcv mname args _) = do
args' <- mapM ppr args
c <- case rcv of Left cn -> return $ text cn
Right e -> ppr e
return (c <> dot <> text mname <> PP.parens (PP.cat $ PP.punctuate PP.comma args'))
ppr (JField rcv fname _) = do
c <- case rcv of Left cn -> return $ text cn
Right e -> ppr e
return (c <> dot <> text fname)
ppr (Tuple t) = do
t' <- mapM ppr t
return $ PP.parens $ PP.cat $ PP.punctuate PP.comma t'
ppr (Proj i t) = do
t' <- ppr t
return $ t' <> dot <> text (show i)
ppr (Seq es) = do
es' <- mapM ppr es
return $ PP.vcat es'
ppr (Product ts) = do
ts' <- mapM ppr ts
return $ PP.parens $ PP.cat $ PP.punctuate PP.comma ts'
ppr (Sum bnd) = lunbind bnd $ \((x, Embed t), e) -> do
t' <- ppr t
e' <- ppr e
return (PP.parens $ text "Σ" <+> (text . show $ x) <+> colon <+> t' <+> dot <+> e')
ppr (Pack (e1, e2) t) = do
e1' <- ppr e1
e2' <- ppr e2
t' <- ppr t
return $ text "pack" <+> (PP.parens $ e1' <+> PP.comma <+> e2') <+> text "as" <+> t'
ppr (UnPack (e1, e2) e3 e4) = do
e1' <- ppr e1
e2' <- ppr e2
e3' <- ppr e3
e4' <- ppr e4
return $ text "unpack" <+>
(PP.parens e1' <+> PP.comma <+> e2') <+>
PP.equals <+>
e3' <+>
text "in" <+>
e4'
instance Pretty Tele where
ppr Empty = return PP.empty
ppr (Cons bnd) = do
t' <- ppr t
bnd' <- ppr b'
return ((PP.parens $ (text . show $ x) <+> colon <+> t') <> bnd')
where
((x, Embed t), b') = unrebind bnd
showExpr :: Expr -> String
showExpr = show . runLFreshM . ppr
isEmpty :: Tele -> Bool
isEmpty Empty = True
isEmpty _ = False
| bixuanzju/fcore | lib/newlib/PrettyPrint.hs | Haskell | bsd-2-clause | 5,268 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import Prelude.Compat
import Control.DeepSeq
import Control.Exception
import Control.Monad
import Data.Aeson
import Data.Aeson.Parser
import Data.Attoparsec
import Data.Time.Clock
import System.Environment (getArgs)
import System.IO
import qualified Data.ByteString as B
main = do
(cnt:args) <- getArgs
let count = read cnt :: Int
forM_ args $ \arg -> withFile arg ReadMode $ \h -> do
putStrLn $ arg ++ ":"
start <- getCurrentTime
let loop !n
| n >= count = return ()
| otherwise = do
let go = do
s <- B.hGet h 16384
if B.null s
then loop (n+1)
else go
go
loop 0
end <- getCurrentTime
putStrLn $ " " ++ show (diffUTCTime end start)
| dmjio/aeson | benchmarks/bench/ReadFile.hs | Haskell | bsd-3-clause | 904 |
{-# LANGUAGE LambdaCase, RankNTypes, BangPatterns #-}
module Stream.Combinators where
import Stream.Types
import Control.Applicative
import Control.Monad hiding (foldM)
import Control.Monad.Trans
import Control.Monad.Morph
import Data.Functor.Identity
import qualified Control.Monad.Trans.Free as Free
import Control.Monad.Trans.Free ( FreeT(..), FreeF(Free) )
import qualified Control.Foldl as L
jfold op seed out = \(Folding phi) ->
do x <- phi (\(a :> mx) -> mx >>= \x -> return (op x a))
join
(\_ -> return seed)
return (out x)
jfoldM op seed out = \(Folding phi) ->
do x <- phi (\(a :> mx) -> mx >>= \x -> op x a)
join
(const seed)
out x
-- purely fold ((,) <$> L.product <*> L.sum )
fold op seed out ls = liftM out (loop seed ls) where
loop !x = \case Step (a :> as) -> loop (op x a) as
Delay mas -> mas >>= \as -> loop x as
Return r -> return x
{-# INLINE[0] fold #-}
-- impurely foldM (generalize $ (,) <$> L.product <*> L.sum )
foldM op seed out ls = seed >>= \y -> loop y ls >>= out where
loop !x = \case Step (a :> as) -> op x a >>= \y -> loop y as
Delay mas -> mas >>= \as -> loop x as
Return r -> return x
{-# INLINE[0] foldM #-}
{-# RULES
"fold/buildStream"
forall op seed out phi.
fold op seed out (buildStream phi) = jfold op seed out phi
#-}
{-# RULES
"foldLM/buildStream"
forall op seed out phi.
foldM op seed out (buildStream phi) = jfoldM op seed out phi
#-}
iterFolding_ :: (Monad m) => Folding_ f m a -> (f (m a) -> m a) -> m a
iterFolding_ phi alg = phi alg join return
iterFolding :: (Monad m) => Folding f m a -> (f (m a) -> m a) -> m a
iterFolding phi alg = getFolding phi alg join return
-- -------
-- unfolds
-- -------
unfold :: (Functor f)
=> (a -> Either r (f a)) -> a -> Stream f m r
unfold f = let go = either Return (Step . fmap go) . f in go
unfold_ :: (Functor f)
=> (a -> Either r (f a)) -> a -> Folding_ f m r
unfold_ f a = \construct wrap done ->
let loop = either done (construct . fmap loop) . f in loop a
unfoldM :: (Functor f, Monad m)
=> (a -> m (Either r (f a))) -> a -> Stream f m r
unfoldM f = let loop = Delay . liftM (either Return (Step . fmap loop)) . f
in loop
unfoldM_ :: (Functor f, Monad m)
=> (a -> m (Either r (f a))) -> a -> Folding_ f m r
unfoldM_ f a construct wrap done = loop a where
loop = wrap . liftM (either done (construct . fmap loop)) . f
-- -------------------
-- unfoldM uncons = id
-- -------------------
uncons :: (Monad m, Functor f)
=> Stream f m r -> m (Either r (f (Stream f m r)))
uncons = \case Delay m -> m >>= uncons
Step ff -> return (Right ff)
Return r -> return (Left r)
next :: (Monad m)
=> Stream (Of a) m r -> m (Either r (a, Stream (Of a) m r))
next = liftM (fmap (\(a:>b) -> (a,b))). uncons
-- --------------------
-- diverse combinators
-- --------------------
-- cp Atkey & co
effectfulFolding :: (Functor f, Monad m) =>
(m a -> a)
-> (r -> a)
-> (f a -> a)
-> Stream f m r
-> a
effectfulFolding malg nil falg = loop where
loop = \case Delay m -> malg (liftM loop m)
Step f -> falg (fmap loop f)
Return r -> nil r
efold :: (Functor f, Monad m)
=> (m b -> b) -> (Either a (f b) -> b) -> Stream f m a -> b
efold malg ealg = loop where
loop = \case Delay m -> malg (liftM loop m)
Step f -> ealg (Right (fmap loop f))
Return r -> ealg (Left r)
crush :: (Monad m, Functor f) => Stream f m r -> m (Stream f m r)
crush = \case Delay m -> m; a -> return a
pr :: Functor f => f r -> Folding_ f m r
pr fr = \construct wrap done -> construct (fmap done fr)
sing :: a -> Folding_ (Of a) m () --yield
sing a = \construct wrap done -> construct (a :> done ())
ret :: r -> Folding_ f m r
ret r = \construct wrap done -> done r
consFolding_ :: a -> Folding_ (Of a) m r -> Folding_ (Of a) m r
consFolding_ a phi construct = phi (construct . (a :>) . construct)
consFolding :: a -> Folding (Of a) m r -> Folding (Of a) m r
consFolding a = \(Folding phi) -> Folding (consFolding_ a phi)
consFB :: (Functor f) => f x -> Folding_ f m x -> Folding_ f m x
consFB fx phi construct wrap done = construct (fmap done fx)
consFB_ :: a -> Folding_ (Of a) m x -> Folding_ (Of a) m x
consFB_ a phi construct wrap done =
phi (\_Ofar -> construct (a :> construct _Ofar))
wrap
done
-- ---------
augmentFolding :: Folding (Of a) m () -> Folding (Of a) m r -> Folding (Of a) m r
augmentFolding phi psi = Folding (augmentFolding_ (getFolding phi) (getFolding psi))
augmentsFolding :: Folding f m r -> Folding f m s -> Folding f m (r,s)
augmentsFolding phi psi = Folding (augmentsFolding_ (getFolding phi) (getFolding psi))
augmentFolding_ ::
(forall r'. (f r' -> r') -> (m r' -> r') -> (() -> r') -> r')
-> (forall r'. (f r' -> r') -> (m r' -> r') -> (s -> r') -> r')
-> (forall r'. (f r' -> r') -> (m r' -> r') -> (s -> r') -> r')
augmentFolding_ = \phi psi construct wrap done ->
phi construct
wrap
(\() -> psi construct
wrap
done)
augmentsFolding_ ::
(forall r'. (f r' -> r') -> (m r' -> r') -> (r -> r') -> r')
-> (forall r'. (f r' -> r') -> (m r' -> r') -> (s -> r') -> r')
-> (forall r'. (f r' -> r') -> (m r' -> r') -> ((r,s) -> r') -> r')
augmentsFolding_ = \phi psi construct wrap done ->
phi construct
wrap
(\r -> psi construct
wrap
(\s -> done (r,s)))
-- ---------
maps :: (forall x . f x -> g x) -> Folding f m a -> Folding g m a
maps morph fold = Folding (maps_ morph (getFolding fold))
maps_ :: (forall x . f x -> g x) -> Folding_ f m a -> Folding_ g m a
maps_ morph phi = \construct wrap done ->
phi (construct . morph)
wrap
done
iterT2 :: (Monad m) => (f (m a) -> m a) -> Folding_ f m a -> m a
iterT2 phi fold = fold phi join return
--
-- folded'' :: (Functor f, Monad m) => (f (m a) -> m a) -> Stream f m a -> m a
-- folded'' phi ls = iterT2 phi (foldStreamx ls)
-- ---------------
-- ----------------------------------
-- ill-fated 'distribution' principles
-- ----------------------------------
-- | Distribute 'Proxy' over a monad transformer
-- distribute
-- :: ( Monad m , MonadTrans t , MFunctor t
-- , Monad (t m) , Monad (t (Proxy a' a b' b m)) )
-- => Proxy a' a b' b (t m) r
-- -> t (Proxy a' a b' b m) r
freeFoldingDist2
:: (MFunctor t, MonadTrans t, Functor f, Monad (t (FreeT f m)),
Monad (t m), Monad m) =>
FreeT f (t m) a -> t (FreeT f m) a
freeFoldingDist2 = freeFolding (join . lift . FreeT. return . Free . fmap return)
(join . hoist lift) return
where
freeFolding construct wrap done =
wrap
. liftM (\case Free.Pure r -> done r
Free free_ -> construct (fmap (freeFolding construct wrap done) free_))
. runFreeT
newtype D m f = D {unD :: m (f (D m f))}
dist22
:: (MFunctor t, Monad (t (Folding f m)), Monad m)
=> Folding f (t m) a
-> (f (t (Folding f m) a) -> t (Folding f m) a)
-> t (Folding f m) a
dist22 (Folding phi) construct = phi construct
(join . hoist lift)
return
dd (Folding phi) = phi join join (lift . return)
d3 (Folding phi) y x = phi y (join . hoist lift) x -- (lift . return)
| haskell-streaming/streaming | benchmarks/old/Stream/Combinators.hs | Haskell | bsd-3-clause | 7,792 |
-----------------------------------------------------------------------------
-- |
-- Module : RefacFunDef
-- Copyright : (c) Christopher Brown 2005
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- This module contains a transformation for HaRe.
-- Function Definition folding.
-- Looks for duplicate code and replaces it with a call to the function.
-- e.g.
--
-- @ square x = x * x @
--
-- @ g x y = x * x + y * y @
--
-- will be refactored to:
--
-- @ square x = x * x @
--
-- @ g x y = square x + square y @
--
-----------------------------------------------------------------------------
module RefacFunDef (
-- ** Data types
Binding, Environment, NonSetEnv,
FunctionPats, WhereDecls,
-- * Function types
subFunctionDef, checkInWhere, checkInPat,
createFunc, createFunc', getEnvironment,
canAddBind, checkVal, rewritePatsInEnv,
doZip, zipHighlightedMatch, callZipHighlightedMatch,
zipHighlightedField, zipHighlightedStmt,
-- * Type signatures with argument docs
findDefNameAndExp
) where
import PrettyPrint
import PrettyPrint
import PosSyntax
import AbstractIO
import Data.Maybe
import TypedIds
import UniqueNames hiding (srcLoc)
import PNT
import TiPNT
import Data.List
import RefacUtils
import PFE0 (findFile)
import MUtils (( # ))
import RefacLocUtils
import RefacGenFold hiding (FunctionPats, WhereDecls, Er, Patt, Mat, findDefNameAndExp, PatFun)
-- | Binds an exp to another e.g. (HsID x, HsLit 5) says x is bound to 5.
-- and it continues until the next non-comment line
type Binding = (HsExpP, HsExpP)
-- | An environment is a *set* of bindings.
type Environment = [Binding]
{- | An environment that is not yet a set - should be processed into an
'Environment'. -}
type NonSetEnv = [Maybe Binding]
-- | An argument list for a function which of course is a list of paterns.
type FunctionPats = [HsPatP]
-- | A list of declarations used to represent a where or let clause.
type WhereDecls = [HsDeclP]
data PatFun = Mat | Patt | Er deriving (Eq, Show)
{- | Function Definition folding.
This folding takes a function definition, looks for duplicate code and
replaces it with a call to the function.
e.g.
@
square x = x * x
g x y = x * x + y * y
@
will be refactored to:
@
square x = x * x
g x y = square x + square y
@
-}
subFunctionDef args
= do let fileName = args!!0
beginRow = read (args!!1)::Int
beginCol = read (args!!2)::Int
endRow = read (args!!3)::Int
endCol = read (args!!4)::Int
AbstractIO.putStrLn "subFunctionDef"
(inscps, exps, mod, tokList) <- parseSourceFile fileName
-- Parse the input file.
-- (inscps, exps, mod, tokList) <- parseSourceFile fileName
-- Find the function that's been highlighted as the refactree
let (ty, pnt, pats, subExp, wh)
= findDefNameAndExp tokList
(beginRow, beginCol)
(endRow, endCol)
mod
let exp = locToExp (beginRow, beginCol)
(endRow, endCol)
tokList
mod
{-
- Do the refactoring! Returns modifications as below:
- mod' - the modified Abstract Syntax Tree
- tokList' - the modified Token Stream
- m - ???
-}
if ty == Mat
then do
(mod', ((tokList', m), _)) <- runStateT (doZip pnt wh pats subExp mod)
((tokList, False), (0,0))
-- Write out the refactoring
writeRefactoredFiles False [((fileName, m), (tokList', mod'))]
AbstractIO.putStrLn "Completed.\n"
else do
(mod', ((tokList', m) , _)) <- runStateT (doSubstitution pnt subExp mod) ((tokList,False),( 0, 0))
writeRefactoredFiles False [((fileName, m), (tokList', mod'))]
AbstractIO.putStrLn "Completed.\n"
doSubstitution p e
= applyTP (full_tdTP (idTP `adhocTP` inMod
`adhocTP` inMatch
`adhocTP` inPat ))
where
inMod (mod@(HsModule loc name exps imps ds):: HsModuleP)
| p `elem` (map declToPNT ds)
= do
ds' <- doZipModule ds
return (HsModule loc name exps imps ds')
where
doZipModule t
= applyTP (full_tdTP (idTP `adhocTP` inMatch2
`adhocTP` inPat2)) t
where
inMatch2 (match@(HsMatch loc name pats rhs ds)::HsMatchP)
= do
(_, declared) <- hsFreeAndDeclaredNames pats
(_, declared') <- hsFreeAndDeclaredNames match
(_, declared'') <- hsFreeAndDeclaredNames ds
if (pNTtoName p) `elem` (declared++(declared'++declared''))
then return match
else do e' <- doSubstitution' p e declared rhs
return (HsMatch loc name pats e' ds)
inPat2 (pat@(Dec (HsPatBind loc pa rhs ds))::HsDeclP)
= do
(_, declared) <- hsFreeAndDeclaredNames pat
(_, declared') <- hsFreeAndDeclaredNames ds
if (pNTtoName p) `elem` (declared++declared')
then return pat
else do e' <- doSubstitution' p e declared rhs
return (Dec (HsPatBind loc pa e' ds))
inPat2 x = return x
inMod x = return x
inMatch (match@(HsMatch loc name pats rhs ds)::HsMatchP)
| p `elem` (map declToPNT ds)
= do
(_, declared) <- hsFreeAndDeclaredNames pats
(_, declared') <- hsFreeAndDeclaredNames match
if (pNTtoName p) `elem` (declared++declared')
then return match
else do
e' <- doSubstitution' p e declared rhs
return (HsMatch loc name pats e' ds)
inMatch x = return x
inPat (pat@(Dec (HsPatBind loc pa rhs ds))::HsDeclP)
| p `elem` (map declToPNT ds)
= do
(_, declared) <- hsFreeAndDeclaredNames pat
if (pNTtoName p) `elem` declared
then return pat
else do e' <- doSubstitution' p e declared rhs
return (Dec (HsPatBind loc pa e' ds))
inPat x = return x
doSubstitution' p e declared t
= applyTP (stop_tdTP (failTP `adhocTP` subExp)) t
where
subExp exp@((Exp _)::HsExpP)
| sameOccurrence exp e == False
= if toRelativeLocs e == toRelativeLocs exp then update exp (createFunc p) exp
else mzero
| otherwise
= mzero
createFunc pat = (Exp (HsId (HsVar pat)))
{-|
Takes the position of the highlighted code and returns
the function name, the list of arguments, the expression that has been
highlighted by the user, and any where\/let clauses associated with the
function.
-}
findDefNameAndExp :: Term t => [PosToken] -- ^ The token stream for the
-- file to be
-- refactored.
-> (Int, Int) -- ^ The beginning position of the highlighting.
-> (Int, Int) -- ^ The end position of the highlighting.
-> t -- ^ The abstract syntax tree.
-> (PatFun, PNT, FunctionPats, HsExpP, WhereDecls) -- ^ A tuple of,
-- (the function name, the list of arguments,
-- the expression highlighted, any where\/let clauses
-- associated with the function).
findDefNameAndExp toks beginPos endPos t
= fromMaybe (Er, defaultPNT, [], defaultExp, [])
(applyTU (once_tdTU (failTU `adhocTU` inMatch `adhocTU` inPat)) t)
where
--The selected sub-expression is in the rhs of a match
inMatch (match@(HsMatch loc1 pnt pats rhs@(HsBody e) ds)::HsMatchP)
| locToExp beginPos endPos toks rhs /= defaultExp
= Just (Mat, pnt, pats, locToExp beginPos endPos toks rhs, ds)
inMatch (match@(HsMatch loc1 pnt pats rhs@(HsGuard e) ds)::HsMatchP)
| locToExp beginPos endPos toks rhs /= defaultExp
= Just (Mat, pnt, pats, rmGuard rhs, ds)
inMatch _ = Nothing
--The selected sub-expression is in the rhs of a pattern-binding
inPat (pat@(Dec (HsPatBind loc1 ps rhs@(HsBody e) ds))::HsDeclP)
| locToExp beginPos endPos toks rhs /= defaultExp
= Just (Patt, patToPNT ps, [], locToExp beginPos endPos toks rhs, ds)
--The selected sub-expression is in the rhs of a pattern-binding
inPat (pat@(Dec (HsPatBind loc1 ps rhs@(HsGuard es) ds))::HsDeclP)
| locToExp beginPos endPos toks rhs /= defaultExp
= Just (Patt, patToPNT ps, [], rmGuard rhs, ds)
inPat _ = Nothing
rmGuard ((HsGuard gs)::RhsP)
= let (_,e1,e2)=glast "guardToIfThenElse" gs
in if ((pNtoName.expToPN) e1)=="otherwise"
then (foldl mkIfThenElse e2 (tail(reverse gs)))
else (foldl mkIfThenElse defaultElse (reverse gs))
mkIfThenElse e (_,e1, e2)=(Exp (HsIf e1 e2 e))
defaultElse=(Exp (HsApp (Exp (HsId (HsVar (PNT (PN (UnQual "error") (G (PlainModule "Prelude") "error"
(N (Just loc0)))) Value (N (Just loc0)))))) (Exp (HsLit loc0 (HsString "UnMatched Pattern")))))
doZip :: (MonadPlus m, Term t, MonadState (([PosToken],Bool),(Int, Int)) m) =>
PNT -> WhereDecls -> FunctionPats -> HsExpP -> t
-> m t
doZip p w patsGlob e t
= applyTP (full_tdTP (idTP `adhocTP` inMod
`adhocTP` inMatch
`adhocTP` inPat )) t
where
inMod (mod@(HsModule loc name exps imps ds):: HsModuleP)
| p `elem` (map declToPNT ds)
= do
ds' <- doZipModule ds
return (HsModule loc name exps imps ds')
where
doZipModule t
= applyTP (full_tdTP (idTP `adhocTP` inMatch2
`adhocTP` inPat2)) t
where
inMatch2 (match@(HsMatch loc name pats rhs ds)::HsMatchP)
= do
(_, declared) <- hsFreeAndDeclaredNames pats
(_, declared') <- hsFreeAndDeclaredNames match
(_, declared'') <- hsFreeAndDeclaredNames ds
if (pNTtoName p) `elem` (declared++(declared'++declared''))
then return match
else do e' <- doZip' p w patsGlob e rhs
return (HsMatch loc name pats e' ds)
inPat2 (pat@(Dec (HsPatBind loc pa rhs ds))::HsDeclP)
= do
(_, declared) <- hsFreeAndDeclaredNames pat
(_, declared') <- hsFreeAndDeclaredNames ds
if (pNTtoName p) `elem` (declared++declared')
then return pat
else do e' <- doZip' p w patsGlob e rhs
return (Dec (HsPatBind loc pa e' ds))
inPat2 x = return x
inMod x = return x
inMatch (match@(HsMatch loc name pats rhs ds)::HsMatchP)
| p `elem` (map declToPNT ds)
= do
(_, declared) <- hsFreeAndDeclaredNames pats
(_, declared') <- hsFreeAndDeclaredNames match
if (pNTtoName p) `elem` (declared++declared')
then return match
else do e' <- doZip' p w patsGlob e rhs
return (HsMatch loc name pats e' ds)
inMatch x = return x
inPat (pat@(Dec (HsPatBind loc pa rhs ds))::HsDeclP)
| p `elem` (map declToPNT ds)
= do
(_, declared) <- hsFreeAndDeclaredNames pat
if (pNTtoName p) `elem` declared
then return pat
else do e' <- doZip' p w patsGlob e rhs
return (Dec (HsPatBind loc pa e' ds))
inPat x = return x
{-|
doZip uses Strafunski to traverse each node of the AST and
then performs the folding on each node.
-}
doZip' :: (MonadPlus m, Term t, MonadState (([PosToken],Bool),(Int, Int)) m) =>
PNT -> WhereDecls -> FunctionPats -> HsExpP -> t
-> m t
doZip' p w pats e t
= applyTP (stop_tdTP (failTP `adhocTP` (zipExpCheck p w pats e))) t
where
zipExpCheck p w pats (exp1::HsExpP) (exp2::HsExpP)
| sameOccurrence exp1 exp2 == False
= do
result <- (callZipHighlightedMatch pats w exp1 exp2)
let environment = getEnvironment result
if result == [Nothing] || environment == Nothing
then do fail ""
else do let Just env = environment
let result' = map (rewritePatsInEnv env) pats
update exp2 (createFunc p result') exp2
| otherwise
= return exp1
{-|
checkVal calls checkAddBind in succession to check that all the bindings
can be added to the environment or not.
-}
checkVal :: NonSetEnv -> Bool
checkVal xs
= checkValAux xs []
where
checkValAux :: NonSetEnv -> Environment -> Bool
checkValAux [] _ = True
checkValAux ((Just (x,y)) : xs) env
= canAddBind (x,y) env &&
checkValAux xs ((x,y):env)
checkValAux (Nothing:xs) env = checkValAux xs env
{-|
canAddBind takes a binding and some environments, and checks to see
whether the binding can be added to the environment or not.
The binding will not be added to the environment if that binding
already exists within the environment. canAddBind returns True
if the binding can be added, and False if it cannot.
-}
canAddBind :: Binding -> Environment -> Bool
canAddBind _ [] = True
canAddBind (x,y) ((x',y'):xs)
= (x1 == x1' && y1 == y1') ||
(x1 /= x1' && canAddBind (x,y) xs)
where
[x1,x1',y1,y1'] = map toRelativeLocs [x,x',y,y']
{-|
getEnvironment takes a list of bindings and removes
the duplicates within the bindings
-}
getEnvironment :: NonSetEnv -> Maybe Environment
getEnvironment [] = Just []
getEnvironment (Nothing: xs) = getEnvironment xs
getEnvironment (Just (x,y):xs)
= case subEnv of
Nothing -> Nothing
Just env -> if canAddBind (x,y) env
then Just ((x,y):env)
else Nothing
where
subEnv = getEnvironment xs
{-|
rewritePatsInEnv takes the Environment and a pattern belonging to the
argument list of the function the user is folding against.
rewritePatsInEnv then forms an expression based on this pattern
taking into consideration the environment. This is used when forming
the function call
e.g.
@
Environment = [("x", [1,2,3]), ("y", 1)]
pat = (x,y)
@
would return...
@
HsTuple ([1,2,3], 1)
@
-}
rewritePatsInEnv :: Environment -> HsPatP -> HsExpP
rewritePatsInEnv [] p = error "Empty Environment!"
rewritePatsInEnv env (pat1@(Pat (HsPRec x y)))
= Exp (HsRecConstr loc0 x (map (sortField env) y))
where
sortField :: Environment -> HsFieldI a HsPatP -> HsFieldI a HsExpP
sortField env (HsField i e) = (HsField i (rewritePatsInEnv env e))
rewritePatsInEnv env (pat1@(Pat (HsPLit x y)))
= Exp (HsLit x y)
rewritePatsInEnv env (pat1@(Pat (HsPAsPat i p1)))
= Exp (HsAsPat i (rewritePatsInEnv env p1))
rewritePatsInEnv env (pat1@(Pat (HsPIrrPat p1)))
= Exp (HsIrrPat (rewritePatsInEnv env p1))
rewritePatsInEnv env (pat1@(Pat (HsPWildCard)))
= nameToExp "undefined"
rewritePatsInEnv env (pat1@(Pat (HsPApp i p1)))
= createFunc i (map (rewritePatsInEnv env) p1)
rewritePatsInEnv env (pat1@(Pat (HsPList _ p1)))
= Exp (HsList (map (rewritePatsInEnv env) p1))
rewritePatsInEnv env (pat1@(Pat (HsPTuple _ p1)))
= Exp (HsTuple (map (rewritePatsInEnv env) p1))
rewritePatsInEnv env (pat1@(Pat (HsPInfixApp p1 x p2)))
= Exp (HsInfixApp (rewritePatsInEnv env p1)
(HsCon x)
(rewritePatsInEnv env p2))
rewritePatsInEnv env (pat@(Pat (HsPParen p1)))
= Exp (HsParen (rewritePatsInEnv env p1))
rewritePatsInEnv env (pat1@(Pat (HsPId (HsVar (PNT (PN (UnQual i) _) _ _)))))
= if findRewrites i == []
then nameToExp "undefined"
else snd (head (findRewrites i))
where
findRewrites i = filter (checkPat i) env
checkPat i (Exp (HsId (HsVar (PNT (PN (UnQual i2) _) _ _))), (Exp z))
= i == i2
checkPat i _ = False
{-|
callZipHighlightedMatch simply calls the function zipHighlightedMatch
and then returns the value wrapped in a monad
-}
callZipHighlightedMatch :: Monad m => FunctionPats -> WhereDecls
-> HsExpP -> HsExpP -> m NonSetEnv
callZipHighlightedMatch pats w (exp1::HsExpP) (exp2::HsExpP)
= do zippedE1 <- zipHighlightedMatch False pats w exp1 exp2
return zippedE1
{- |
zipHighlightedMatch takes a list of patterns (the list of arguments for the
function highlighted, the where clause associated with the function,
the expression that has been highlighted and the expression that we are trying
to fold against.
zipHighlightedMatch then checks to see if the the expressions can be paired.
The expressions will only be paired if:
both expressions have the ssame type
e.g.
refactoron -> [1,2,3,4]
refactorod -> [1,2,3,4] becomes ([1,2,3,4], [1,2,3,4])
or, the highlighted expression is an idenitfier, in which case a pair is
always created, unless the idenitifier does not appear in the argument list
(pats)
-}
zipHighlightedMatch :: Monad m => Bool -> FunctionPats -> WhereDecls
-> HsExpP -> HsExpP -> m NonSetEnv
zipHighlightedMatch b pats w (exp1@(Exp (HsId (HsCon i1)))::HsExpP)
(exp2@(Exp (HsId (HsCon i2)))::HsExpP)
| i1 == i2 = return [ Just (exp1, exp2) ]
| otherwise = return [ Nothing ]
zipHighlightedMatch b pats w (exp1@(Exp (HsId (HsCon i1)))::HsExpP)
(exp2::HsExpP)
= return [ Nothing ]
zipHighlightedMatch True pats w (exp1@(Exp (HsId i1))::HsExpP)
(exp2@(Exp (HsId i2))::HsExpP)
| not (checkDefs i1 i2) = fail "untouched"
| checkInPat pats exp2 = return [ Just (exp1, exp2) ]
-- | checkInPat pats exp1 = return [ Just (exp1, exp2) ]
| checkGlobal i1 i2 = return [ Just (exp1, exp2) ]
| not (checkInWhere w exp1) = return [Nothing]
| otherwise = fail "untouched"
where
checkGlobal (HsVar i1) (HsVar i2) = (pNTtoPN i1) == (pNTtoPN i2)
checkGlobal _ _ = False
zipHighlightedMatch False pats w (exp1@(Exp (HsId i1))::HsExpP)
(exp2@(Exp (HsId i2))::HsExpP)
| checkInPat pats exp1 = return [ Just (exp1, exp2) ]
| checkGlobal i1 i2 = return [ Just (exp1, exp2) ]
| not (checkInWhere w exp1) = return [Nothing]
| otherwise = fail "untouched"
where
checkGlobal (HsVar i1) (HsVar i2) = (pNTtoPN i1) == (pNTtoPN i2)
checkGlobal _ _ = False
zipHighlightedMatch b pats w (exp1@(Exp (HsId i))::HsExpP) (exp2::HsExpP)
| checkInPat pats exp1 == True &&
checkInWhere w exp1 /= True
= return [ Just (exp1, exp2) ]
| otherwise
= fail "untouched"
zipHighlightedMatch b pats w (exp1@(Exp (HsLit _ i1))::HsExpP)
(exp2@(Exp (HsLit _ i2))::HsExpP)
| i1 == i2 = return [ Just (exp1, exp2) ]
| otherwise = return [ Nothing ]
zipHighlightedMatch b pats w (exp1@(Exp (HsLit _ _))::HsExpP) (exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsInfixApp e1 i e2))::HsExpP)
(exp2@(Exp (HsInfixApp e11 i2 e22))::HsExpP)
| i == i2 = do zippedE1 <- zipHighlightedMatch b pats w e1 e11
zippedE2 <- zipHighlightedMatch b pats w e2 e22
if zippedE1 == [ Nothing ] || zippedE2 == [ Nothing ]
then return [ Nothing ]
else return (zippedE1 ++ zippedE2)
| otherwise = return [ Nothing ]
zipHighlightedMatch b pats w (exp1@(Exp (HsInfixApp e1 i e2))::HsExpP)
(exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsApp e1 e2))::HsExpP)
(exp2@(Exp (HsApp e11 e22))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e11
zippedE2 <- zipHighlightedMatch b pats w e2 e22
if zippedE1 == [Nothing] || zippedE2 == [ Nothing ]
then return [Nothing]
else return (zippedE1 ++ zippedE2)
zipHighlightedMatch b pats w (exp1@(Exp (HsApp e1 e2))::HsExpP) (exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsNegApp _ e1))::HsExpP)
(exp2@(Exp (HsNegApp _ e2))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e2
return zippedE1
zipHighlightedMatch b pats w (exp1@(Exp (HsNegApp _ e1))::HsExpP) (exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsLambda ps e1))::HsExpP)
(exp2@(Exp (HsLambda ps2 e11))::HsExpP)
| wildCardAllPNs ps == wildCardAllPNs ps2
= do zippedE1 <- zipHighlightedMatch b pats w e1 (localRewriteExp e11 (localRewritePats ps ps2))
return zippedE1
where
localRewritePats [] ps = []
localRewritePats ps [] = []
localRewritePats (p1:p1s) (p2:p2s)
= (rewritePat p2 p1) : (localRewritePats p1s p2s)
localRewriteExp e [] = e
localRewriteExp e (p1:p1s)
= let e1' = rewritePatsInExp p1 e in localRewriteExp e1' p1s
zipHighlightedMatch b pats w (exp1@(Exp (HsLet _ e1))::HsExpP)
(exp2@(Exp (HsLet _ e11))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e11
return zippedE1
zipHighlightedMatch b pats w (exp@(Exp (HsLet _ e1))::HsExpP) (exp2::HsExpP)
= fail ""
zipHighlightedMatch b pats w (exp1@(Exp (HsLambda _ e1))::HsExpP) (exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsIf e1 e2 e3))::HsExpP)
(exp2@(Exp (HsIf e11 e22 e33))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e11
zippedE2 <- zipHighlightedMatch b pats w e2 e22
zippedE3 <- zipHighlightedMatch b pats w e3 e33
return (zippedE1 ++ zippedE2 ++ zippedE3)
zipHighlightedMatch b pats w (exp1@(Exp (HsIf e1 e2 e3))::HsExpP) (exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats
w
(exp1@(Exp (HsCase e1 (alt@(HsAlt _ p1 e2 ds1):alts1)))::HsExpP)
(exp2@(Exp
(HsCase e11
(alt2@(HsAlt _ p11 e22 ds11):alts2)
))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e11
res <- zippedAlts (alt:alts1) (alt2:alts2)
if res == [Nothing]
then return [Nothing]
else return (zippedE1 ++ res)
where
zippedAlts [] alts = return []
zippedAlts alts [] = return []
zippedAlts ((HsAlt _ p1 (HsBody exp1) ds1):alts1) ((HsAlt _ p11 (HsBody exp2) ds11):alts2)
| wildCardAllPNs p1 == wildCardAllPNs p11
= do
zippedE1 <- zipHighlightedMatch b pats w exp1 (rewritePatsInExp (rewritePat p11 p1) exp2)
if zippedE1 == [Nothing]
then return [Nothing]
else do res <- zippedAlts alts1 alts2
if res == [Nothing] then return [Nothing]
else return (zippedE1 ++ res)
| otherwise = return [Nothing]
zippedAlts ((HsAlt _ p1 (HsGuard g1) ds1):alts1) ((HsAlt _ p22 (HsGuard g2) ds11):alts2)
| wildCardAllPNs p1 == wildCardAllPNs p22
= do
zippedE1 <- zippedGuards g1 (rewritePatsInGuard (rewritePat p22 p1) g2)
-- error $ show zippedE1
if zippedE1 == [Nothing]
then return [Nothing]
else do
res <- zippedAlts alts1 alts2
if res == [Nothing] then return [Nothing]
else return (zippedE1 ++ res)
where
zippedGuards _ [] = return []
zippedGuards [] _ = return []
zippedGuards ((_, e1, e2):gs1) ((_, e3, e4):gs2)
= do
e1' <- zipHighlightedMatch True pats w e1 e3
e2' <- zipHighlightedMatch True pats w e2 e4
res <- zippedGuards gs1 gs2
return ((e1' ++ e2') ++ res)
zippedAlts _ _ = return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp
(HsCase e1
((HsAlt _ e2 p1 ds1):alts1)
))::HsExpP)
(exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsDo (stat1)))::HsExpP)
(exp2@(Exp (HsDo (stat2)))::HsExpP)
= do zippedE1 <- zipHighlightedStmt pats w stat1 stat2
return zippedE1
zipHighlightedMatch b pats w (exp1@(Exp (HsDo (stat1)))::HsExpP) (exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsTuple ([e1])))::HsExpP)
(exp2@(Exp (HsTuple ([e11])))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e11
return zippedE1
zipHighlightedMatch b pats w (exp1@(Exp (HsTuple (e1:e1s)))::HsExpP)
(exp2@(Exp (HsTuple (e11:e11s)))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e11
result <- zippedE2 e1s e11s
if result == [Nothing] || zippedE1 == [Nothing]
then return [Nothing]
else return (zippedE1 ++ result)
where
zippedE2 [] [] = return []
zippedE2 _ [] = return [Nothing]
zippedE2 [] _ = return [Nothing]
zippedE2 (x:xs) (y:ys)
= do result1 <- zipHighlightedMatch b pats w x y
result2 <- zippedE2 xs ys
if result1 == [Nothing] || result2 == [Nothing]
then return [Nothing]
else return (result1 ++ result2)
zipHighlightedMatch b pats w (exp1@(Exp (HsTuple (e1:e1s)))::HsExpP)
(exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsList ([e1])))::HsExpP)
(exp2@(Exp (HsList ([e11])))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e11
return zippedE1
zipHighlightedMatch b pats w (exp1@(Exp (HsList (e1:e1s)))::HsExpP)
(exp2@(Exp (HsList (e11:e11s)))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e11
result <- zippedE2 e1s e11s
-- error (show zippedE1 ++ " " ++ show result)
if result == [Nothing] || zippedE1 == [Nothing]
then return [Nothing]
else return (zippedE1 ++ result)
where
zippedE2 [] [] = return []
zippedE2 _ [] = return [Nothing]
zippedE2 [] _ = return [Nothing]
zippedE2 (x:xs) (y:ys) = do
result1 <- zipHighlightedMatch b pats w x y
result2 <- zippedE2 xs ys
if result1 == [Nothing] || result2 == [Nothing]
then return [Nothing]
else return (result1 ++ result2)
zipHighlightedMatch b pats w (exp1@(Exp (HsList (e1:e1s)))::HsExpP) (exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsParen e1))::HsExpP)
(exp2@(Exp (HsParen e11))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e11
return zippedE1
zipHighlightedMatch b pats w (exp1@(Exp (HsParen e1))::HsExpP) (exp2::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 exp2
return zippedE1
zipHighlightedMatch b pats w (exp1::HsExpP) (exp2@(Exp (HsParen e2))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w exp1 e2
return zippedE1
zipHighlightedMatch b pats w (exp1@(Exp (HsLeftSection e1 i1))::HsExpP)
(exp2@(Exp (HsLeftSection e11 i2))::HsExpP)
| i1 == i2 = do zippedE1 <- zipHighlightedMatch b pats w e1 e11
return zippedE1
| otherwise = return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsLeftSection e1 i1))::HsExpP)
(exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsRightSection i1 e1))::HsExpP)
(exp2@(Exp (HsRightSection i2 e11))::HsExpP)
| i1 == i2 = do zippedE1 <- zipHighlightedMatch b pats w e1 e11
return zippedE1
| otherwise = return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsRightSection i1 e1))::HsExpP)
(exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsRecConstr _ i1 i2 ))::HsExpP)
(exp2@(Exp (HsRecConstr _ i11 i22 ))::HsExpP)
| i1 == i11 = do zippedE1 <- zipHighlightedField pats w i2 i22
return zippedE1
| otherwise = do return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsRecConstr _ i1 i2))::HsExpP)
(exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsRecUpdate _ e1 i1))::HsExpP)
(exp2@(Exp (HsRecUpdate _ e11 i11))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e11
zippedE2 <- zipHighlightedField pats w i1 i11
return (zippedE1 ++ zippedE2)
zipHighlightedMatch b pats w (exp1@(Exp (HsRecUpdate _ e1 i1))::HsExpP)
(exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsEnumFrom e1))::HsExpP)
(exp2@(Exp (HsEnumFrom e11))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e11
return zippedE1
zipHighlightedMatch b pats w (exp1@(Exp (HsEnumFrom e1))::HsExpP) (exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsEnumFromTo e1 e2))::HsExpP)
(exp2@(Exp (HsEnumFromTo e11 e22))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e11
zippedE2 <- zipHighlightedMatch b pats w e2 e22
return (zippedE1 ++ zippedE2)
zipHighlightedMatch b pats w (exp1@(Exp (HsEnumFromTo e1 e2))::HsExpP)
(exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsEnumFromThen e1 e2))::HsExpP)
(exp2@(Exp (HsEnumFromThen e11 e22))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e11
zippedE2 <- zipHighlightedMatch b pats w e2 e22
return (zippedE1 ++ zippedE2)
zipHighlightedMatch b pats w (exp1@(Exp (HsEnumFromThen e1 e2))::HsExpP)
(exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsEnumFromThenTo e1 e2 e3))::HsExpP)
(exp2@(Exp (HsEnumFromThenTo e11 e22 e33))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e11
zippedE2 <- zipHighlightedMatch b pats w e2 e22
zippedE3 <- zipHighlightedMatch b pats w e3 e33
return (zippedE1 ++ zippedE2 ++ zippedE3)
zipHighlightedMatch b pats w (exp1@(Exp (HsEnumFromThenTo e1 e2 e3))::HsExpP)
(exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsListComp (stat1)))::HsExpP)
(exp2@(Exp (HsListComp (stat2)))::HsExpP)
= do zippedE1 <- zipHighlightedStmt pats w stat1 stat2
return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsListComp (stat1)))::HsExpP)
(exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsExpTypeSig _ e1 c1 t1))::HsExpP)
(exp2@(Exp (HsExpTypeSig _ e2 c2 t2))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e2
return zippedE1
zipHighlightedMatch b pats w (exp1@(Exp (HsExpTypeSig _ e1 c1 t1))::HsExpP)
(exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsAsPat i1 e1))::HsExpP)
(exp2@(Exp (HsAsPat i11 e11))::HsExpP)
| i1 == i11 = do zippedE1 <- zipHighlightedMatch b pats w e1 e11
return zippedE1
| otherwise = return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsAsPat i1 e1))::HsExpP) (exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsIrrPat e1))::HsExpP)
(exp2@(Exp (HsIrrPat e11))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e11
return zippedE1
zipHighlightedMatch b pats w (exp1@(Exp (HsIrrPat e1))::HsExpP) (exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1::HsExpP) (exp2::HsExpP)
= return [Nothing]
{-|
zipHighlightedField takes the highlighted expression
, and takes the expression that we are folding against.
If they are both fields, it then calls zipHiglightedMatch to
pair up the expressions within the fields.
-}
zipHighlightedField :: Monad m => FunctionPats -> WhereDecls
-> HsFieldsI PNT (HsExpI PNT) -> HsFieldsI PNT (HsExpI PNT)
-> m NonSetEnv
zipHighlightedField pats w [] _
= return [Nothing]
zipHighlightedField pats w _ []
= return [Nothing]
zipHighlightedField pats w ((fiel1@(HsField i1 e1)):xs)
((fiel2@(HsField i11 e11)):ys)
= if i1 == i11
then do zippedE1 <- zipHighlightedMatch False pats w e1 e11
return zippedE1
else do
return [Nothing]
checkDefs (HsVar p1@(PNT (PN (UnQual i) (_) ) _ _ )) (HsVar p2@(PNT (PN (UnQual i2) (_) ) _ _ ))
= i == i2
checkDefs _ _ = False
{-|
checkInPat checks that the Expression (supplied as 2nd argument)
occurs within the Function Arugment List.
checkInPat needs to check for every case that expression could be
e.g. literals, lists, tuples and records.
if the expression occurs then the function returns True
otherwise returns False.
-}
checkInPat :: FunctionPats -> HsExpP -> Bool
checkInPat (pat1@(Pat (HsPRec x y)):pats) exp
| (checkField y) == False = (checkInPat pats exp)
| otherwise = True
where
checkField ((HsField i e):xs)
| (checkInPat [e] exp) == False = (checkField xs)
| otherwise = True
checkInPat (pat1@(Pat (HsPIrrPat p)):pats) exp
| (checkInPat [p] exp) == False = checkInPat pats exp
| otherwise = True
checkInPat (pat1@(Pat (HsPAsPat i p)):pats) exp
| (checkInPat [p] exp) == False = checkInPat pats exp
| otherwise = True
checkInPat (pat1@(Pat (HsPWildCard)):pats) exp
= checkInPat pats exp
checkInPat (pat1@(Pat (HsPId (HsVar (PNT p@(PN (UnQual i) (_) ) _ _ )))):pats)
(exp1@(Exp (HsId (HsVar (PNT p2@(PN (UnQual i2) (_) ) _ _ ))))::HsExpP)
= if p == p2 then True else checkInPat pats exp1
{- = if i == i2
then True
else checkInPat pats exp1 -}
checkInPat (pat1@(Pat (HsPParen pat)):pats) exp
| (checkInPat [pat] exp) == False = checkInPat pats exp
| otherwise = True
checkInPat (pat@(Pat (HsPInfixApp pat1 x pat2)):pats) exp
| (checkInPat [pat1] exp) == False &&
(checkInPat [pat2] exp) == False
= checkInPat pats exp
| otherwise = True
checkInPat (pat@(Pat (HsPTuple _ pat1)):pats) exp
| (checkInPat pat1 exp) == False = checkInPat pats exp
| otherwise = True
checkInPat (pat@(Pat (HsPList _ pat1)):pats) exp
| (checkInPat pat1 exp) == False = checkInPat pats exp
| otherwise = True
checkInPat (pat@(Pat (HsPApp i pat1)):pats) exp
| (checkInPat pat1 exp) == False = checkInPat pats exp
| otherwise = True
checkInPat ((Pat (HsPLit _ (HsInt x))):pats) exp1
= checkInPat pats exp1
checkInPat _ _ = False
{-|
checkInWhere checks that where clause of the function does not contain
the expressions (as second argument). If it does the function returns
True, otherwise returns False.
-}
checkInWhere :: [HsDeclP] -> HsExpP -> Bool
checkInWhere [] _ = False
checkInWhere (wh@(Dec
(HsPatBind _
(Pat
(HsPId
(HsVar
(PNT
(PN
(UnQual i)
_
)
_
_
)
)
)
)
_
rest)):ws)
(exp1@(Exp (HsId (HsVar (PNT (PN (UnQual i2) _ ) _ _ ))))::HsExpP)
= i == i2
-- extractHsBody simply extracts the expression within an HsBody
-- and returns that Expression.
extractHsBody (HsBody exp) = return exp
extractHsBody _ = error "Case must contain HsBody"
{-|
zipHighLightedStmt checks that two statements are identical,
if they are, zipHighLightedStmt returns the two statements paired together
-}
zipHighlightedStmt :: Monad m => FunctionPats -> WhereDecls
-> HsStmtP -> HsStmtP -> m NonSetEnv
zipHighlightedStmt pats w (exp1@(HsGenerator _ p1 e1 e1')::HsStmtP)
(exp2@(HsGenerator _ p2 e2 e2')::HsStmtP)
| wildCardAllPNs p1 == wildCardAllPNs p2
= do zippedE1 <- zipHighlightedMatch False pats w e1 e2
zippedE2 <- zipHighlightedStmt pats w e1' e2'
return (zippedE1 ++ zippedE2)
zipHighlightedStmt pats w (exp1@(HsQualifier e1 e1')::HsStmtP)
(exp2@(HsQualifier e2 e2')::HsStmtP)
= do zippedE1 <- zipHighlightedMatch False pats w e1 e2
zippedE2 <- zipHighlightedStmt pats w e1' e2'
return [Nothing]
zipHighlightedStmt pats w (exp1@(HsLetStmt ds1 e1)::HsStmtP)
(exp2@(HsLetStmt ds2 e2)::HsStmtP)
= do zippedE1 <- zipHighlightedStmt pats w e1 e2
return zippedE1
zipHighlightedStmt pats w (exp1@(HsLast e1)::HsStmtP)
(exp2@(HsLast e2)::HsStmtP)
= do zippedE1 <- zipHighlightedMatch False pats w e1 e2
return zippedE1
zipHighlightedStmt pats w (exp1::HsStmtP) (exp2::HsStmtP)
= return [Nothing]
| kmate/HaRe | old/refactorer/RefacFunDef.hs | Haskell | bsd-3-clause | 39,473 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP, NoImplicitPrelude, MagicHash, UnboxedTuples, AutoDeriveTypeable #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
{-# OPTIONS_HADDOCK not-home #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Conc.Windows
-- Copyright : (c) The University of Glasgow, 1994-2002
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable (GHC extensions)
--
-- Windows I/O manager
--
-----------------------------------------------------------------------------
-- #not-home
module GHC.Conc.Windows
( ensureIOManagerIsRunning
-- * Waiting
, threadDelay
, registerDelay
-- * Miscellaneous
, asyncRead
, asyncWrite
, asyncDoProc
, asyncReadBA
, asyncWriteBA
, ConsoleEvent(..)
, win32ConsoleHandler
, toWin32ConsoleEvent
) where
import Control.Monad
import Data.Bits (shiftR)
import Data.Maybe (Maybe(..))
import Data.Typeable
import GHC.Base
import GHC.Conc.Sync
import GHC.Enum (Enum)
import GHC.IO (unsafePerformIO)
import GHC.IORef
import GHC.MVar
import GHC.Num (Num(..))
import GHC.Ptr
import GHC.Read (Read)
import GHC.Real (div, fromIntegral)
import GHC.Show (Show)
import GHC.Word (Word32, Word64)
import GHC.Windows
#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
-- ----------------------------------------------------------------------------
-- Thread waiting
-- Note: threadWaitRead and threadWaitWrite aren't really functional
-- on Win32, but left in there because lib code (still) uses them (the manner
-- in which they're used doesn't cause problems on a Win32 platform though.)
asyncRead :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
asyncRead (I# fd) (I# isSock) (I# len) (Ptr buf) =
IO $ \s -> case asyncRead# fd isSock len buf s of
(# s', len#, err# #) -> (# s', (I# len#, I# err#) #)
asyncWrite :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
asyncWrite (I# fd) (I# isSock) (I# len) (Ptr buf) =
IO $ \s -> case asyncWrite# fd isSock len buf s of
(# s', len#, err# #) -> (# s', (I# len#, I# err#) #)
asyncDoProc :: FunPtr (Ptr a -> IO Int) -> Ptr a -> IO Int
asyncDoProc (FunPtr proc) (Ptr param) =
-- the 'length' value is ignored; simplifies implementation of
-- the async*# primops to have them all return the same result.
IO $ \s -> case asyncDoProc# proc param s of
(# s', _len#, err# #) -> (# s', I# err# #)
-- to aid the use of these primops by the IO Handle implementation,
-- provide the following convenience funs:
-- this better be a pinned byte array!
asyncReadBA :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int,Int)
asyncReadBA fd isSock len off bufB =
asyncRead fd isSock len ((Ptr (byteArrayContents# (unsafeCoerce# bufB))) `plusPtr` off)
asyncWriteBA :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int,Int)
asyncWriteBA fd isSock len off bufB =
asyncWrite fd isSock len ((Ptr (byteArrayContents# (unsafeCoerce# bufB))) `plusPtr` off)
-- ----------------------------------------------------------------------------
-- Threaded RTS implementation of threadDelay
-- | Suspends the current thread for a given number of microseconds
-- (GHC only).
--
-- There is no guarantee that the thread will be rescheduled promptly
-- when the delay has expired, but the thread will never continue to
-- run /earlier/ than specified.
--
threadDelay :: Int -> IO ()
threadDelay time
| threaded = waitForDelayEvent time
| otherwise = IO $ \s ->
case time of { I# time# ->
case delay# time# s of { s' -> (# s', () #)
}}
-- | Set the value of returned TVar to True after a given number of
-- microseconds. The caveats associated with threadDelay also apply.
--
registerDelay :: Int -> IO (TVar Bool)
registerDelay usecs
| threaded = waitForDelayEventSTM usecs
| otherwise = error "registerDelay: requires -threaded"
foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool
waitForDelayEvent :: Int -> IO ()
waitForDelayEvent usecs = do
m <- newEmptyMVar
target <- calculateTarget usecs
atomicModifyIORef pendingDelays (\xs -> (Delay target m : xs, ()))
prodServiceThread
takeMVar m
-- Delays for use in STM
waitForDelayEventSTM :: Int -> IO (TVar Bool)
waitForDelayEventSTM usecs = do
t <- atomically $ newTVar False
target <- calculateTarget usecs
atomicModifyIORef pendingDelays (\xs -> (DelaySTM target t : xs, ()))
prodServiceThread
return t
calculateTarget :: Int -> IO USecs
calculateTarget usecs = do
now <- getMonotonicUSec
return $ now + (fromIntegral usecs)
data DelayReq
= Delay {-# UNPACK #-} !USecs {-# UNPACK #-} !(MVar ())
| DelaySTM {-# UNPACK #-} !USecs {-# UNPACK #-} !(TVar Bool)
{-# NOINLINE pendingDelays #-}
pendingDelays :: IORef [DelayReq]
pendingDelays = unsafePerformIO $ do
m <- newIORef []
sharedCAF m getOrSetGHCConcWindowsPendingDelaysStore
foreign import ccall unsafe "getOrSetGHCConcWindowsPendingDelaysStore"
getOrSetGHCConcWindowsPendingDelaysStore :: Ptr a -> IO (Ptr a)
{-# NOINLINE ioManagerThread #-}
ioManagerThread :: MVar (Maybe ThreadId)
ioManagerThread = unsafePerformIO $ do
m <- newMVar Nothing
sharedCAF m getOrSetGHCConcWindowsIOManagerThreadStore
foreign import ccall unsafe "getOrSetGHCConcWindowsIOManagerThreadStore"
getOrSetGHCConcWindowsIOManagerThreadStore :: Ptr a -> IO (Ptr a)
ensureIOManagerIsRunning :: IO ()
ensureIOManagerIsRunning
| threaded = startIOManagerThread
| otherwise = return ()
startIOManagerThread :: IO ()
startIOManagerThread = do
modifyMVar_ ioManagerThread $ \old -> do
let create = do t <- forkIO ioManager; return (Just t)
case old of
Nothing -> create
Just t -> do
s <- threadStatus t
case s of
ThreadFinished -> create
ThreadDied -> create
_other -> return (Just t)
insertDelay :: DelayReq -> [DelayReq] -> [DelayReq]
insertDelay d [] = [d]
insertDelay d1 ds@(d2 : rest)
| delayTime d1 <= delayTime d2 = d1 : ds
| otherwise = d2 : insertDelay d1 rest
delayTime :: DelayReq -> USecs
delayTime (Delay t _) = t
delayTime (DelaySTM t _) = t
type USecs = Word64
type NSecs = Word64
foreign import ccall unsafe "getMonotonicNSec"
getMonotonicNSec :: IO NSecs
getMonotonicUSec :: IO USecs
getMonotonicUSec = fmap (`div` 1000) getMonotonicNSec
{-# NOINLINE prodding #-}
prodding :: IORef Bool
prodding = unsafePerformIO $ do
r <- newIORef False
sharedCAF r getOrSetGHCConcWindowsProddingStore
foreign import ccall unsafe "getOrSetGHCConcWindowsProddingStore"
getOrSetGHCConcWindowsProddingStore :: Ptr a -> IO (Ptr a)
prodServiceThread :: IO ()
prodServiceThread = do
-- NB. use atomicModifyIORef here, otherwise there are race
-- conditions in which prodding is left at True but the server is
-- blocked in select().
was_set <- atomicModifyIORef prodding $ \b -> (True,b)
unless was_set wakeupIOManager
-- ----------------------------------------------------------------------------
-- Windows IO manager thread
ioManager :: IO ()
ioManager = do
wakeup <- c_getIOManagerEvent
service_loop wakeup []
service_loop :: HANDLE -- read end of pipe
-> [DelayReq] -- current delay requests
-> IO ()
service_loop wakeup old_delays = do
-- pick up new delay requests
new_delays <- atomicModifyIORef pendingDelays (\a -> ([],a))
let delays = foldr insertDelay old_delays new_delays
now <- getMonotonicUSec
(delays', timeout) <- getDelay now delays
r <- c_WaitForSingleObject wakeup timeout
case r of
0xffffffff -> do throwGetLastError "service_loop"
0 -> do
r2 <- c_readIOManagerEvent
exit <-
case r2 of
_ | r2 == io_MANAGER_WAKEUP -> return False
_ | r2 == io_MANAGER_DIE -> return True
0 -> return False -- spurious wakeup
_ -> do start_console_handler (r2 `shiftR` 1); return False
unless exit $ service_cont wakeup delays'
_other -> service_cont wakeup delays' -- probably timeout
service_cont :: HANDLE -> [DelayReq] -> IO ()
service_cont wakeup delays = do
r <- atomicModifyIORef prodding (\_ -> (False,False))
r `seq` return () -- avoid space leak
service_loop wakeup delays
-- must agree with rts/win32/ThrIOManager.c
io_MANAGER_WAKEUP, io_MANAGER_DIE :: Word32
io_MANAGER_WAKEUP = 0xffffffff
io_MANAGER_DIE = 0xfffffffe
data ConsoleEvent
= ControlC
| Break
| Close
-- these are sent to Services only.
| Logoff
| Shutdown
deriving (Eq, Ord, Enum, Show, Read, Typeable)
start_console_handler :: Word32 -> IO ()
start_console_handler r =
case toWin32ConsoleEvent r of
Just x -> withMVar win32ConsoleHandler $ \handler -> do
_ <- forkIO (handler x)
return ()
Nothing -> return ()
toWin32ConsoleEvent :: (Eq a, Num a) => a -> Maybe ConsoleEvent
toWin32ConsoleEvent ev =
case ev of
0 {- CTRL_C_EVENT-} -> Just ControlC
1 {- CTRL_BREAK_EVENT-} -> Just Break
2 {- CTRL_CLOSE_EVENT-} -> Just Close
5 {- CTRL_LOGOFF_EVENT-} -> Just Logoff
6 {- CTRL_SHUTDOWN_EVENT-} -> Just Shutdown
_ -> Nothing
win32ConsoleHandler :: MVar (ConsoleEvent -> IO ())
win32ConsoleHandler = unsafePerformIO (newMVar (error "win32ConsoleHandler"))
wakeupIOManager :: IO ()
wakeupIOManager = c_sendIOManagerEvent io_MANAGER_WAKEUP
-- Walk the queue of pending delays, waking up any that have passed
-- and return the smallest delay to wait for. The queue of pending
-- delays is kept ordered.
getDelay :: USecs -> [DelayReq] -> IO ([DelayReq], DWORD)
getDelay _ [] = return ([], iNFINITE)
getDelay now all@(d : rest)
= case d of
Delay time m | now >= time -> do
putMVar m ()
getDelay now rest
DelaySTM time t | now >= time -> do
atomically $ writeTVar t True
getDelay now rest
_otherwise ->
-- delay is in millisecs for WaitForSingleObject
let micro_seconds = delayTime d - now
milli_seconds = (micro_seconds + 999) `div` 1000
in return (all, fromIntegral milli_seconds)
foreign import ccall unsafe "getIOManagerEvent" -- in the RTS (ThrIOManager.c)
c_getIOManagerEvent :: IO HANDLE
foreign import ccall unsafe "readIOManagerEvent" -- in the RTS (ThrIOManager.c)
c_readIOManagerEvent :: IO Word32
foreign import ccall unsafe "sendIOManagerEvent" -- in the RTS (ThrIOManager.c)
c_sendIOManagerEvent :: Word32 -> IO ()
foreign import WINDOWS_CCONV "WaitForSingleObject"
c_WaitForSingleObject :: HANDLE -> DWORD -> IO DWORD
| frantisekfarka/ghc-dsi | libraries/base/GHC/Conc/Windows.hs | Haskell | bsd-3-clause | 11,013 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE UnboxedTuples #-}
{-# LANGUAGE ExistentialQuantification #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.StaticPtr
-- Copyright : (C) 2014 I/O Tweag
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- Symbolic references to values.
--
-- References to values are usually implemented with memory addresses, and this
-- is practical when communicating values between the different pieces of a
-- single process.
--
-- When values are communicated across different processes running in possibly
-- different machines, though, addresses are no longer useful since each
-- process may use different addresses to store a given value.
--
-- To solve such concern, the references provided by this module offer a key
-- that can be used to locate the values on each process. Each process maintains
-- a global table of references which can be looked up with a given key. This
-- table is known as the Static Pointer Table. The reference can then be
-- dereferenced to obtain the value.
--
-----------------------------------------------------------------------------
module GHC.StaticPtr
( StaticPtr
, deRefStaticPtr
, StaticKey
, staticKey
, unsafeLookupStaticPtr
, StaticPtrInfo(..)
, staticPtrInfo
, staticPtrKeys
) where
import Data.Typeable (Typeable)
import Foreign.C.Types (CInt(..))
import Foreign.Marshal (allocaArray, peekArray, withArray)
import Foreign.Ptr (castPtr)
import GHC.Exts (addrToAny#)
import GHC.Ptr (Ptr(..), nullPtr)
import GHC.Fingerprint (Fingerprint(..))
-- | A reference to a value of type 'a'.
data StaticPtr a = StaticPtr StaticKey StaticPtrInfo a
deriving Typeable
-- | Dereferences a static pointer.
deRefStaticPtr :: StaticPtr a -> a
deRefStaticPtr (StaticPtr _ _ v) = v
-- | A key for `StaticPtrs` that can be serialized and used with
-- 'unsafeLookupStaticPtr'.
type StaticKey = Fingerprint
-- | The 'StaticKey' that can be used to look up the given 'StaticPtr'.
staticKey :: StaticPtr a -> StaticKey
staticKey (StaticPtr k _ _) = k
-- | Looks up a 'StaticPtr' by its 'StaticKey'.
--
-- If the 'StaticPtr' is not found returns @Nothing@.
--
-- This function is unsafe because the program behavior is undefined if the type
-- of the returned 'StaticPtr' does not match the expected one.
--
unsafeLookupStaticPtr :: StaticKey -> IO (Maybe (StaticPtr a))
unsafeLookupStaticPtr (Fingerprint w1 w2) = do
ptr@(Ptr addr) <- withArray [w1,w2] (hs_spt_lookup . castPtr)
if (ptr == nullPtr)
then return Nothing
else case addrToAny# addr of
(# spe #) -> return (Just spe)
foreign import ccall unsafe hs_spt_lookup :: Ptr () -> IO (Ptr a)
-- | Miscelaneous information available for debugging purposes.
data StaticPtrInfo = StaticPtrInfo
{ -- | Package key of the package where the static pointer is defined
spInfoPackageKey :: String
-- | Name of the module where the static pointer is defined
, spInfoModuleName :: String
-- | An internal name that is distinct for every static pointer defined in
-- a given module.
, spInfoName :: String
-- | Source location of the definition of the static pointer as a
-- @(Line, Column)@ pair.
, spInfoSrcLoc :: (Int, Int)
}
deriving (Show, Typeable)
-- | 'StaticPtrInfo' of the given 'StaticPtr'.
staticPtrInfo :: StaticPtr a -> StaticPtrInfo
staticPtrInfo (StaticPtr _ n _) = n
-- | A list of all known keys.
staticPtrKeys :: IO [StaticKey]
staticPtrKeys = do
keyCount <- hs_spt_key_count
allocaArray (fromIntegral keyCount) $ \p -> do
count <- hs_spt_keys p keyCount
peekArray (fromIntegral count) p >>=
mapM (\pa -> peekArray 2 pa >>= \[w1, w2] -> return $ Fingerprint w1 w2)
{-# NOINLINE staticPtrKeys #-}
foreign import ccall unsafe hs_spt_key_count :: IO CInt
foreign import ccall unsafe hs_spt_keys :: Ptr a -> CInt -> IO CInt
| beni55/haste-compiler | libraries/ghc-7.10/base/GHC/StaticPtr.hs | Haskell | bsd-3-clause | 4,186 |
module Where4 where
-- source functions
f1 :: [a] -> [a]
f1 l = ls
where
ls = take (rs - 1) l
rs = length l
f2 :: [a] -> Int
f2 l = rs - 1
where
rs = length l | mpickering/HaRe | old/testing/merging/Where4_TokOut.hs | Haskell | bsd-3-clause | 210 |
import Distribution.Simple
import Ros.Internal.SetupUtil
main = defaultMainWithHooks $
simpleUserHooks { confHook = rosConf }
| bitemyapp/roshask | Examples/Turtle/Setup.hs | Haskell | bsd-3-clause | 134 |
-- | A collection of commonly-used combinators to build up larger
-- codecs.
module Data.Wheat.Combinators where
import Control.Applicative ((<$>))
import Control.Monad ((>=>))
import Data.Foldable (foldMap)
import Data.Functor.Contravariant.Divisible (divide)
import Data.Monoid (Monoid, (<>))
-- Local imports
import Data.Wheat.Types
-- | Sequential composition of codecs.
--
-- When encoding, the input value is encoded with both codecs and the
-- results are concatenated. When decoding, the remaining bytestring
-- from the first codec is used as input to the second.
(<:>) :: Monoid b => GCodec i b e d1 -> GCodec i b e d2 -> GCodec i b e (d1, d2)
c1 <:> c2 = Codec (encoderOf c1 <> encoderOf c2) decoder where
decoder = do
x <- decoderOf c1
y <- decoderOf c2
return (x, y)
-- | Sequential composition of codecs, combining the results of
-- decoding monoidally.
(<<:>>) :: (Monoid b, Monoid d) => GCodec i b e d -> GCodec i b e d -> GCodec i b e d
c1 <<:>> c2 = Codec (encoderOf cx) (uncurry (<>) <$> decoderOf cx) where
cx = c1 <:> c2
-- | Right-biased sequential composition of codecs.
--
-- Encoding behaviour is the same as '<:>', decoding throws away the
-- result of the first codec.
(<:>>) :: Monoid b => GCodec i b e d1 -> GCodec i b e d2 -> GCodec i b e d2
c1 <:>> c2 = Codec (encoderOf cx) (snd <$> decoderOf cx) where
cx = c1 <:> c2
-- | Left-biased sequential composition of codecs.
--
-- Encoding behaviour is the same as '<:>', decoding throws away the
-- result of the second codec.
(<<:>) :: Monoid b => GCodec i b e d1 -> GCodec i b e d2 -> GCodec i b e d1
c1 <<:> c2 = Codec (encoderOf cx) (fst <$> decoderOf cx) where
cx = c1 <:> c2
-- | Combine two codecs into a codec for tuples of those types, where
-- the encoded forms of each element are concatenated.
(<++>) :: Monoid b => GCodec i b e1 d1 -> GCodec i b e2 d2 -> GCodec i b (e1, e2) (d1, d2)
(<++>) = separate id id
-- | Lift a codec over a type to over a list of that type.
--
-- Encoded elements are concatenated. Decoding never fails, as an
-- empty list is acceptable.
elementwise :: Monoid b => GCodec i b e d -> GCodec i b [e] [d]
elementwise c = Codec encoder decoder where
encoder = toEncoder' go where
go = foldMap (runEncoder' $ encoderOf c)
decoder = toDecoder $ go [] where
go ds b = case runDecoder (decoderOf c) b of
Just (d, b') -> go (d:ds) b'
Nothing -> Just (reverse ds, b)
-- | Encode a value as a combination of header and encoded value. The
-- codec used for encoding/decoding the value itself receives the
-- (encoded/decoded) header as a parameter.
header :: Monoid b => (e -> h) -> GCodec i b h h -> (h -> GCodec i b e d) -> GCodec i b e d
header hf hc cf = Codec encoder decoder where
encoder = toEncoder' $ \e ->
let h = hf e
in runEncoder' (encoderOf hc) h <> runEncoder' (encoderOf $ cf h) e
decoder = decoderOf hc >>= decoderOf . cf
-- | Apply a divide-and-conquer approach: given a function to split up
-- the encoding into two smaller components, and a function to combine
-- the smaller components after decoding, construct a codec for the
-- more complex type.
separate :: Monoid b => (e -> (e1, e2)) -> ((d1, d2) -> d) -> GCodec i b e1 d1 -> GCodec i b e2 d2 -> GCodec i b e d
separate split merge c1 c2 = Codec encoder decoder where
encoder = divide split (encoderOf c1) (encoderOf c2)
decoder = do
x <- decoderOf c1
y <- decoderOf c2
return $ merge (x, y)
-- | Given functions to convert the types, wrap one codec inside another.
--
-- Encoding and decoding will fail if the function does, even if the
-- inner codec succeeds.
wrap :: (d' -> Maybe d) -> (e -> Maybe e') -> GCodec i b e' d' -> GCodec i b e d
wrap df ef c = Codec encoder decoder where
encoder = toEncoder $ ef >=> runEncoder (encoderOf c)
decoder = toDecoder $ \b -> case runDecoder (decoderOf c) b of
Just (d, b') -> (\d' -> (d',b')) <$> df d
Nothing -> Nothing
| barrucadu/wheat | Data/Wheat/Combinators.hs | Haskell | mit | 3,946 |
{-# LANGUAGE OverloadedStrings #-}
module Haskbot.Internal.Request
( Params
, jsonContentType
, textContentType
, getPostParams
, headOnly
, getParamsMap
, optParam
, reqParam
) where
import Control.Monad.Error (liftIO, throwError)
import Data.ByteString.Lazy (fromStrict)
import Data.Text (Text)
import Data.Text.Encoding (decodeUtf8)
import Haskbot.Internal.Environment (HaskbotM)
import qualified Data.Map as M
import qualified Network.HTTP.Types as N
import qualified Network.Wai as W
type Params = M.Map Text Text
-- constants
jsonContentType :: N.Header
jsonContentType = (N.hContentType, "application/json")
textContentType :: N.Header
textContentType = (N.hContentType, "text/plain")
-- internal functions
headOnly :: N.Status -> W.Response
headOnly status = W.responseLBS status [] . fromStrict $ N.statusMessage status
getParamsMap :: W.Request -> IO Params
getParamsMap req = do
body <- W.requestBody req
return . M.fromList . map decode $ N.parseSimpleQuery body
where
decode (k,v) = (decodeUtf8 k, decodeUtf8 v)
getPostParams :: W.Request -> HaskbotM Params
getPostParams req
| isPost = liftIO $ getParamsMap req
| otherwise = throwError N.status403
where
isPost = W.requestMethod req == N.methodPost
optParam :: Params -> Text -> HaskbotM (Maybe Text)
optParam pMap key = return $ M.lookup key pMap
reqParam :: Params -> Text -> HaskbotM Text
reqParam pMap key =
case M.lookup key pMap of
Just p -> return p
_ -> throwError N.badRequest400
| Jonplussed/haskbot-core | src/Haskbot/Internal/Request.hs | Haskell | mit | 1,512 |
{-# LANGUAGE ScopedTypeVariables
, ExistentialQuantification
, LambdaCase
, KindSignatures
#-}
module Document.VarScope where
-- Modules
import Document.Phase.Types
import Document.Scope
import Latex.Parser (uncurry3)
import Logic.Expr
import UnitB.Syntax
-- Libraries
import qualified Control.Invariant as I
import Control.Lens
import Control.Precondition
import Data.Existential
import Data.Hashable
import qualified Data.List.NonEmpty as NE
import Data.Map as M
import Data.Typeable
import GHC.Generics.Instances
import Test.QuickCheck
import Test.QuickCheck.Regression
import Test.QuickCheck.Report
import Test.QuickCheck.ZoomEq
import Text.Printf.TH
import Utilities.Syntactic
class (Typeable a,Scope a,PrettyPrintable a) => IsVarScope a where
toOldEventDecl :: Name -> a -> [Either Error (EventId,[EventP2Field])]
toNewEventDecl :: Name -> a -> [Either Error (EventId,[EventP2Field])]
toThyDecl :: Name -> a -> [Either Error TheoryP2Field]
toMchDecl :: Name -> a -> [Either Error (MachineP2'Field ae ce t)]
newtype VarScope = VarScope { _varScopeCell :: Cell IsVarScope }
deriving (Typeable,Generic)
makeFields ''VarScope
instance Show VarScope where
show = readCell' show
instance ZoomEq VarScope where
x .== y = read2CellsWith' (.==) (x I.=== y) x y
instance Scope VarScope where
keep_from s = traverseCell' (keep_from s)
make_inherited = traverseCell' make_inherited
merge_scopes' = -- fmap (runIdentity . fromJust) .
apply2Cells' merge_scopes' Nothing
error_item = readCell' error_item
rename_events' m = traverseCell' (rename_events' m)
kind = readCell' kind
instance IsVarScope VarScope where
toOldEventDecl s = readCell' $ toOldEventDecl s
toNewEventDecl s = readCell' $ toNewEventDecl s
toThyDecl s = readCell' $ toThyDecl s
toMchDecl s = readCell' $ toMchDecl s
instance PrettyPrintable VarScope where
pretty = readCell' pretty
data TheoryConst = TheoryConst
{ thCons :: Var
, _theoryConstDeclSource :: DeclSource
, _theoryConstLineInfo :: LineInfo }
deriving (Eq,Ord,Show,Typeable,Generic)
data TheoryDef = TheoryDef
{ thDef :: Def
, _theoryDefDeclSource :: DeclSource
, _theoryDefLineInfo :: LineInfo }
deriving (Eq,Ord,Show,Typeable,Generic)
data MachineVar =
MchVar
{ var :: Var
, _machineVarDeclSource :: DeclSource
, _machineVarLineInfo :: LineInfo }
| DelMchVar
{ mvar :: Maybe Var
, _machineVarDeclSource :: DeclSource
, _machineVarLineInfo :: LineInfo }
deriving (Eq,Ord,Show,Typeable,Generic)
data MachineDef = MchDef
{ _machineDefName :: Name
, _term :: StringLi
, _machineDefDeclSource :: DeclSource
, _machineDefLineInfo :: LineInfo }
deriving (Eq,Ord,Show,Typeable,Generic)
data EvtDecls = Evt (Map EventOrDummy EventDecl)
deriving (Eq,Ord,Show,Typeable,Generic)
-- -- in Evt, 'Nothing' stands for a dummy
data DummyDecl = DummyDecl
deriving (Eq,Ord,Show,Generic)
type EventOrDummy = Either DummyDecl EventId
data EventDecl = EventDecl
{ _scope :: EvtScope Var
, _source :: NonEmpty EventOrDummy
, _eventDeclDeclSource :: DeclSource
, _eventDeclLineInfo :: LineInfo
} deriving (Show,Eq,Ord,Generic)
data EvtScope a = Param a | Index (InhStatus a) | Promoted (Maybe a)
deriving (Eq,Ord,Generic,Functor,Show)
instance Eq VarScope where
(==) = cellEqual' (==)
instance Ord VarScope where
compare = cellCompare' compare
makeLenses ''EventDecl
makeFields ''EventDecl
makePrisms ''EvtScope
makeFields ''TheoryConst
makeFields ''TheoryDef
makeFields ''MachineVar
makeFields ''MachineDef
makeFields ''EvtDecls
varDecl :: Getter EventDecl (Maybe Var)
varDecl = scope.to declOf
declOf :: EvtScope var -> Maybe var
declOf (Index (InhAdd v)) = Just v
declOf (Index (InhDelete v)) = v
declOf (Param v) = Just v
declOf (Promoted v) = v
instance PrettyRecord TheoryConst where
instance PrettyPrintable TheoryConst where
pretty = prettyRecord
instance ZoomEq TheoryConst where
instance Scope TheoryConst where
kind _ = "constant"
rename_events' _ e = [e]
instance PrettyRecord TheoryDef where
instance PrettyPrintable TheoryDef where
pretty = prettyRecord
instance ZoomEq TheoryDef where
instance Scope TheoryDef where
kind _ = "constant"
rename_events' _ e = [e]
instance PrettyRecord MachineDef where
instance PrettyPrintable MachineDef where
pretty = prettyRecord
instance ZoomEq MachineDef where
instance Scope MachineDef where
kind _ = "definition"
rename_events' _ e = [e]
instance PrettyRecord MachineVar where
instance PrettyPrintable MachineVar where
pretty = prettyRecord
instance ZoomEq MachineVar where
instance Scope MachineVar where
merge_scopes' (DelMchVar Nothing s _) (MchVar v Inherited li) = Just $ DelMchVar (Just v) s li
merge_scopes' (MchVar v Inherited li) (DelMchVar Nothing s _) = Just $ DelMchVar (Just v) s li
merge_scopes' _ _ = Nothing
kind (DelMchVar _ _ _) = "deleted variable"
kind (MchVar _ _ _) = "state variable"
rename_events' _ e = [e]
instance PrettyRecord EventDecl where
instance PrettyPrintable EventDecl where
pretty = prettyRecord
instance ZoomEq DummyDecl where
(.==) = (I.===)
instance ZoomEq EventDecl where
instance Scope EventDecl where
kind x = case x^.scope of
Index _ -> "index"
Param _ -> "parameter"
Promoted _ -> "promoted parameter"
keep_from s x | s == (x^.declSource) = Just x
| otherwise = Nothing
make_inherited = Just . (declSource .~ Inherited)
merge_scopes' s0 s1 = case (s0^.scope,s1^.scope) of
(Index (InhAdd v),Index (InhDelete Nothing)) ->
Just $ s1
& scope .~ Index (InhDelete (Just v))
& source .~ s0^.source
-- & declSource %~ declUnion (s0^.declSource)
(Index (InhDelete Nothing),Index (InhAdd v)) ->
Just $ s0
& scope .~ Index (InhDelete (Just v))
& source .~ s1^.source
-- & declSource %~ declUnion (s1^.declSource)
(Param v,Promoted Nothing) -> Just $ s1
& scope .~ Promoted (Just v)
& source .~ s0^.source
(Promoted Nothing,Param v) -> Just $ s0
& scope .~ Promoted (Just v)
& source .~ s1^.source
_ -> Nothing
rename_events' _ e = [e]
instance PrettyPrintable a => PrettyPrintable (EvtScope a) where
pretty = show . fmap Pretty
instance PrettyPrintable DummyDecl where
pretty DummyDecl = "dummy declaration"
instance Hashable DummyDecl where
instance PrettyPrintable EvtDecls where
pretty (Evt e) = "Evt " ++ pretty e
instance ZoomEq EvtDecls where
instance Scope EvtDecls where
kind (Evt m) = show $ M.map (view scope) m
keep_from s (Evt m)
| M.null r = Nothing
| otherwise = Just $ Evt r
where
r = M.mapMaybe (keep_from s) m
-- f x
-- | s == (x^.declSource) = Just x
-- | otherwise = Nothing
make_inherited (Evt m) = fmap Evt $ f $ M.mapMaybe make_inherited m
where
f m | M.null m = Nothing
| otherwise = Just m
error_item (Evt m) = fromJust' $ NE.nonEmpty $ elems $ mapWithKey msg m
where
msg (Right k) x = ([s|%s (event '%s')|] (kind x) (pretty k), x^.lineInfo)
msg (Left DummyDecl) x = ("dummy", x^.lineInfo)
merge_scopes' (Evt m0) (Evt m1) = Evt <$> scopeUnion merge_scopes' m0 m1
rename_events' lookup (Evt vs) = Evt <$> concatMap f (toList vs)
where
f (Right eid,x) = [ singleton (Right e) $ setSource (Right eid) x | e <- lookup eid ]
f (Left DummyDecl,x) = [ singleton (Left DummyDecl) x ]
setSource eid = source .~ eid :| []
instance Arbitrary TheoryDef where
arbitrary = genericArbitrary
shrink = genericShrink
instance Arbitrary TheoryConst where
arbitrary = genericArbitrary
shrink = genericShrink
instance Arbitrary MachineVar where
arbitrary = genericArbitrary
shrink = genericShrink
instance Arbitrary MachineDef where
arbitrary = genericArbitrary
shrink = genericShrink
instance Arbitrary EventDecl where
arbitrary = genericArbitrary
shrink = genericShrink
instance Arbitrary DummyDecl where
arbitrary = return DummyDecl
instance Arbitrary EvtDecls where
arbitrary = Evt . fromList <$> arbitrary
shrink = genericShrink
instance ZoomEq a => ZoomEq (EvtScope a) where
instance Arbitrary a => Arbitrary (EvtScope a) where
arbitrary = genericArbitrary
shrink = genericShrink
prop_axiom_Scope_clashesOverMerge :: Property
prop_axiom_Scope_clashesOverMerge = regression (uncurry3 axiom_Scope_clashesOverMerge)
[ (x,y,z) ]
where
x = Evt (fromList [(Left DummyDecl,EventDecl {_scope = Param (Var (Name {_backslash = False, _base = 'a' :| "", _primes = 0, _suffix = ""}) (Gen (DefSort (Name {_backslash = False, _base = 'a' :| "", _primes = 0, _suffix = ""}) (InternalName "" (Name {_backslash = False, _base = 'a' :| "", _primes = 0, _suffix = ""}) "") [] (Gen (Sort (Name {_backslash = False, _base = 'a' :| "", _primes = 0, _suffix = ""}) (InternalName "" (Name {_backslash = False, _base = 'a' :| "", _primes = 0, _suffix = ""}) "") 0) [])) [])), _source = Right (EventId (Lbl "m")) :| [], _eventDeclDeclSource = Local, _eventDeclLineInfo = (LI "file" 0 0)})])
y = Evt (fromList [(Left DummyDecl,EventDecl {_scope = Promoted Nothing, _source = Right (EventId (Lbl "c")) :| [], _eventDeclDeclSource = Inherited, _eventDeclLineInfo = (LI "file" 0 0)})])
z = Evt (fromList [(Left DummyDecl,EventDecl {_scope = Index (InhDelete Nothing), _source = Right (EventId (Lbl "c")) :| [], _eventDeclDeclSource = Local, _eventDeclLineInfo = (LI "file" 0 10)})])
return []
run_tests :: (PropName -> Property -> IO (a, Result))
-> IO ([a], Bool)
run_tests = $forAllProperties'
| literate-unitb/literate-unitb | src/Document/VarScope.hs | Haskell | mit | 10,411 |
module Main where
import Engine
import GLUI
import SimpleBots
main :: IO ()
main = runBattle openGLUI [
("bot1", runInCircle),
("bot2", fireBot)
]
| andreyLevushkin/LambdaWars | src/Main.hs | Haskell | mit | 173 |
module Handler.CustomError where
import Assets (getAllExams)
import Import
import Widgets (titleWidget, iconWidget, publicExamWidget, privateExamWidget)
-- | Custom 404 page
getCustomErrorR :: Handler Html
getCustomErrorR = do
setUltDestCurrent
memail <- lookupSession "_ID"
(publicExams, privateExams) <- runDB $ getAllExams memail
let middleWidget = [whamlet| <p class=boldWhite>_{MsgGet404} |]
defaultLayout $(widgetFile "error") | cirquit/quizlearner | quizlearner/Handler/CustomError.hs | Haskell | mit | 454 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module Models where
import Control.Monad.Logger (runStderrLoggingT)
import Control.Monad.Reader
import Control.Monad.Trans.Control
import Data.Aeson
import Data.Aeson.TH
import Data.Char (toLower)
import Data.Text (Text ())
import Data.Time
import Database.Persist.Postgresql
import Database.Persist.TH
import GHC.Generics
import Web.Users.Persistent
import Web.Users.Types
import Config
share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
Liftsession json
text Text
date UTCTime
user LoginId
deriving Show
Profile json
user LoginId
deriving Show
|]
data Registration
= Registration
{ regName :: Text
, regEmail :: Text
, regPassword :: Text
, regConfirmation :: Text
} deriving (Eq, Show)
deriveJSON defaultOptions { fieldLabelModifier = map toLower . Prelude.drop 3, constructorTagModifier = map toLower } ''Registration
data Auth
= Auth
{ authEmail :: Text
, authPassword :: Text
} deriving (Eq, Show)
deriveJSON defaultOptions { fieldLabelModifier = map toLower . Prelude.drop 4, constructorTagModifier = map toLower } ''Auth
doMigrations :: ReaderT SqlBackend IO ()
doMigrations = runMigration migrateAll
runDb :: (MonadIO m, MonadReader Config m) => SqlPersistT IO b -> m b
runDb query = asks getPool >>= liftIO . runSqlPool query
db :: (MonadIO m, MonadBaseControl IO m) => SqlPersistM a -> m a
db query =
runStderrLoggingT .
withPostgresqlPool (connStr Development) 1 $
liftIO . runSqlPersistMPool query
data Person = Person
{ name :: Text
, email :: Text
, personId :: LoginId
} deriving (Eq, Show, Generic)
instance ToJSON Person
instance FromJSON Person
type QLUser = User UserDetails
type UserDetails = ()
userToPerson :: LoginId -> QLUser -> Person
userToPerson lid User {..} =
Person { name = u_name
, email = u_email
, personId = lid
}
convertRegistration :: Registration -> QLUser
convertRegistration Registration{..} =
User { u_name = regName
, u_email = regEmail
, u_password = makePassword . PasswordPlain $ regPassword
, u_more = ()
, u_active = True
}
data AuthResponse
= AuthResponse
{ sessionId :: SessionId
, person :: Person
} deriving (Eq, Show, Generic)
instance ToJSON AuthResponse
| parsonsmatt/QuickLift | src/Models.hs | Haskell | mit | 3,145 |
-- Tiny lambda-Micro-Haskell program TPJ 2015
z = 10 ;
neg b = if b then False else True ;
mnsdbl m n = m - n - n ;
once f x = f x ;
twice f x = f (f x) ;
| jaanos/TPJ-2015-16 | lmh/tiny_lmh.hs | Haskell | mit | 157 |
import qualified Codec.Archive.Tar as Tar
import qualified Codec.Compression.GZip as GZ
import Control.Monad (forM_, when)
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as BL
import Data.Char (toLower)
import qualified Data.Text.Lazy.IO as TL
import Distribution.Compiler (CompilerId(..), CompilerFlavor(..))
import Distribution.Homebrew
import qualified Distribution.PackageDescription as PD
import Distribution.PackageDescription.Configuration (finalizePackageDescription)
import Distribution.PackageDescription.Parse (readPackageDescription)
import Distribution.System (Platform(..), Arch(..), OS(..))
import Distribution.Verbosity (silent)
import Distribution.Version (Version(..))
import Network.HTTP (simpleHTTP, defaultGETRequest_, getResponseBody)
import Network.URI (URI(..), parseURI)
import Prelude hiding (or)
import System.Directory
import System.FilePath ((</>),(<.>))
import Text.Printf (printf)
-- * Configuration
instantiatePackageDescription :: PD.GenericPackageDescription -> Maybe PD.PackageDescription
instantiatePackageDescription gpd = case finalize gpd of
Left _ -> Nothing
Right (pd, _) -> Just pd
where
flags = []
isokay = const True
platform = Platform I386 OSX
compiler = CompilerId GHC (Version [7,6,3] [])
miscDeps = []
finalize = finalizePackageDescription flags isokay platform compiler miscDeps
remoteIndex :: String
remoteIndex = "http://hackage.haskell.org/packages/index.tar.gz"
localIndex :: FilePath
localIndex = "index"
-- * Main script
main :: IO ()
main = do
--home <- getHomeDirectory
--let cache =
-- home </> "Library" </> "Haskell" </> "repo-cache" </> "hackage.haskell.org"
putStrLn "Downloading the latest package list from hackage.haskell.org"
case parseURI remoteIndex of
Nothing -> error $ "Invalid URI: " ++ remoteIndex
Just uri -> do
indexTarGz <- getRequest uri
let indexTar = GZ.decompress (BL.fromChunks ((:[]) indexTarGz))
BL.writeFile "index.tar" indexTar
createDirectoryIfMissing False localIndex
Tar.extract localIndex "index.tar"
removeFile "index.tar"
putStrLn "Analysing package list"
packages <- getDirectoryContents localIndex
forM_ packages $ \package -> do
let packagePath = localIndex </> package
packagePathExists <- doesDirectoryExist packagePath
when (packagePathExists && package `notElem` [".",".."]) $ do
versions <- getDirectoryContents packagePath
let latestVersion = maximum versions
let latestPath = packagePath </> latestVersion
let cabalFile = latestPath </> package <.> "cabal"
cabalFileExists <- doesFileExist cabalFile
when cabalFileExists $ do
gpd <- readPackageDescription silent cabalFile
case instantiatePackageDescription gpd of
Nothing -> return ()
Just pd -> do
maybeFormula <- fromPackageDescription pd
case maybeFormula of
Nothing -> return ()
Just formDesc -> do
formCode <- renderFormula formDesc
let formPath = map toLower package <.> "rb"
putStrLn (printf "Writing formula for %s-%s" package latestVersion)
TL.writeFile formPath formCode
removeDirectoryRecursive localIndex
putStrLn "Done"
getRequest :: URI -> IO ByteString
getRequest url = simpleHTTP (defaultGETRequest_ url) >>= getResponseBody
| pepijnkokke/homebrew-hackage | Main.hs | Haskell | mit | 3,728 |
module Main where
import Popeye.CLI
main :: IO ()
main = run
| codeclimate/popeye | app/Main.hs | Haskell | mit | 63 |
#!/usr/bin/env stack
-- stack --install-ghc runghc --package turtle
-- #!/bin/bash
{-# LANGUAGE OverloadedStrings #-} --
--
import Turtle
say = echo
main = say "Hello, world!"
| capitanbatata/functional-systems-in-haskell | fsh-exercises/scripts/example1.hs | Haskell | mit | 260 |
-- The number, 197, is called a circular prime because
-- all rotations of the digits: 197, 971, and 719, are themselves prime.
-- There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
-- How many circular primes are there below one million?
module Euler35 where
import Data.Numbers.Primes
import Data.List
-- TODO copy paste from Euler 34 - refactor
digits :: Integer -> [Integer]
digits a = reverse (digitsInternal a)
digitsInternal a
| a < 10 = [a]
| otherwise = q : digitsInternal r
where (r, q) = quotRem a 10
combine :: [Integer] -> Integer
combine list = foldl (\a b -> a * 10 + b) 0 list
-- https://stackoverflow.com/questions/7631664/how-to-define-a-rotates-function
listRotations :: [a] -> [[a]]
listRotations l = init (zipWith (++) (tails l) (inits l))
-- TODO read about ad hoc polimorphism
rotations :: Integer -> [Integer]
rotations a = nub (map combine (listRotations (digits a)))
allAre :: (Integer -> Bool) -> [Integer] -> Bool
allAre func [] = True -- not logical?
allAre func (x:xs)
| func(x) == False = False
| otherwise = allAre func xs
circularPrime :: Integer -> Bool
circularPrime 1 = False
circularPrime a
| not (isPrime a) = False
| otherwise = allAre isPrime (rotations a)
result = length(filter circularPrime (takeWhile (<1000000) [1..])) | kirhgoff/haskell-sandbox | euler35/euler35.hs | Haskell | mit | 1,333 |
main :: IO ()
main = putStrLn $ show $ solve
solve :: Int
solve = sum [sumMultiplesToN 3 1000, sumMultiplesToN 5 1000, -sumMultiplesToN 15 1000]
sumMultiplesToN :: (Integral a) => a -> a -> a
sumMultiplesToN m n = m * (sumToN $ (n-1) `div` m)
sumToN :: (Integral a) => a -> a
sumToN n = n * (n+1) `div` 2
| pshendry/project-euler-solutions | 0001/solution.hs | Haskell | mit | 308 |
{-# Language InstanceSigs, DoAndIfThenElse #-}
module Observables where
import Prelude hiding (map, takeWhile)
import System.IO
import Data.Char
import System.Console.ANSI
import Control.Monad
import Control.Monad.Trans
import qualified Data.List
import Data.IORef
import Coroutine
(|>) :: a -> (a -> b) -> b
x |> f = f x
isLeft :: Either a b -> Bool
isLeft (Left _) = True
isLeft _ = False
isRight :: Either a b -> Bool
isRight (Right _) = True
isRight _ = False
data Observer a = Observer (a -> Trampoline IO ())
data Observable a = Observable (Observer a -> Trampoline IO ())
onNext :: a -> Observer a -> Trampoline IO ()
onNext x (Observer f) = f x
unit :: a -> Observable a
unit x = Observable (\o -> o |> onNext x)
subscribe :: Observer a -> Observable a -> Trampoline IO ()
subscribe f (Observable m) = m f
merge :: Observable (Observable a) -> Observable a
merge xss = Observable (\o -> xss |> subscribe (Observer (\xs -> xs |> subscribe o)))
instance Functor Observable where
fmap :: (a -> b) -> Observable a -> Observable b
fmap f m = Observable (\o -> m |> subscribe(Observer(\x -> o |> onNext (f x))))
instance Monad Observable where
(>>=) :: Observable a -> (a -> Observable b) -> Observable b
m >>= f = merge (fmap f m)
return :: a -> Observable a
return = unit
instance MonadPlus Observable where
mzero :: Observable a
mzero = Observable (\o -> return ())
mplus :: Observable a -> Observable a -> Observable a
mplus xs ys = Observable (\o -> sequence_ [xs |> subscribe (Observer (\x -> o |> onNext x)),
ys |> subscribe (Observer (\x -> o |> onNext x))])
filter :: (a -> Bool) -> Observable a -> Observable a
filter p xs = Observable (\o -> xs |> subscribe (Observer (\x -> if (p x) then
(o |> onNext x)
else pause)))
takeWhile :: (a -> Bool) -> Observable a -> Observable a
takeWhile p xs = do x <- xs;
guard (p x);
return x
skipWhile :: (a -> Bool) -> Observable a -> Observable a
skipWhile p xs = takeWhile (not . p) xs
combine :: Observable a -> Observable b -> Observable (Either a b)
combine xs ys = Observable (\o -> do interleave [xs |> subscribe(Observer (\x -> do o |> onNext (Left x)
pause)),
ys |> subscribe(Observer (\x -> do o |> onNext (Right x)
pause))]
return ())
takeUntil :: Observable b -> Observable a -> Observable a
takeUntil sig xs = Observable (\o -> do ref <- liftIO $ newIORef False
(combine sig xs) |> subscribe (obs ref o))
where obs ref o = Observer (\x -> do b <- liftIO $ readIORef ref
if (b) then return ()
else if (isLeft x) then liftIO $ writeIORef ref True
else let (Right v) = x in o|> onNext v)
skipUntil :: Observable b -> Observable a -> Observable a
skipUntil sig xs = Observable (\o -> do ref <- liftIO $ newIORef False
(combine sig xs) |> subscribe (obs ref o))
where obs ref o = Observer (\x -> do b <- liftIO $ readIORef ref
if (b) then let (Right v) = x in o|> onNext v
else if (isLeft x) then liftIO $ writeIORef ref True
else return())
-- Work in progress,,
window :: Observable a -> Observable b -> Observable (Observable b)
window cl xs = Observable (\o -> do o |> onNext (xs |> takeUntil cl)
o |> onNext (xs |> skipUntil cl))
toObservable :: [a] -> Observable a
toObservable xs = Observable (\o -> (mapM_ (\ x -> o |> onNext x) xs))
keys :: Observable Char
keys = Observable loop
where loop o = do x <- liftIO $ getChar;
o |> onNext x;
loop o
| holoed/Rx.hs | Observables.hs | Haskell | apache-2.0 | 4,421 |
module Inference
(
inferRules
) where
import Types
infer :: Relation -> Expr -> [Relation]
infer (premices `Imply` (lhs `And` rhs)) goal =
infer (premices `Imply` rhs) goal ++
infer (premices `Imply` lhs) goal
infer (premices `Imply` (lhs `Or` rhs)) goal =
infer ((premices `And` Not lhs) `Imply` rhs) goal ++
infer ((premices `And` Not rhs) `Imply` lhs) goal
infer (premices `Imply` (lhs `Xor` rhs)) goal =
infer (premices `Imply` ((lhs `Or` rhs) `And` Not (lhs `And` rhs))) goal
-- inference of not rules
infer (rhs `Imply` Not (Not lhs)) goal =
infer (rhs `Imply` lhs) goal
infer (premices `Imply` Not (lhs `And` rhs)) goal =
infer (premices `Imply` (Not lhs `Or` Not rhs)) goal
infer (premices `Imply` Not (lhs `Or` rhs)) goal =
infer (premices `Imply` (Not lhs `And` Not rhs)) goal
infer (premices `Imply` Not (lhs `Xor` rhs)) goal =
infer (premices `Imply` (Not (lhs `Or` rhs) `Or` (lhs `And` rhs))) goal
-- return the rule sent if the rhs is the fact we are looking for
infer r@(_ `Imply` fact) goal
| goal == fact = [r]
-- | Not goal == fact = [r]
| otherwise = []
--modus tollens or transposition
launchInferences ( lhs `Imply` rhs) goal =
infer ( lhs `Imply` rhs) goal ++ infer ( Not rhs `Imply` Not lhs) goal
-- distribution of Equivalence in implications
launchInferences (rhs `Eq` lhs) goal =
launchInferences (rhs `Imply` lhs) goal ++ launchInferences (lhs `Imply` rhs) goal
-- inferRules :: [Relation] -> Expr -> [Relation]
inferRules rules goal = foldr (\r -> (++) (launchInferences r goal)) [] rules
| tmielcza/demiurge | src/Inference.hs | Haskell | apache-2.0 | 1,568 |
-----------------------------------------------------------------------------
--
-- Module : Marshaller
-- Description :
-- Copyright : (c) Tobias Reinhardt, 2015 <[email protected]
-- License : Apache License, Version 2.0
--
-- Maintainer : Tobias Reinhardt <[email protected]>
-- Portability : tested only on linux
-- |
--
-----------------------------------------------------------------------------
module Marshaller (
Option (Short, Long, Both),
NeedForArgument (Optional, Compulsory, None),
MarshalledEntity (NonOptionArgument, OptionWithArgument, OnlyOption),
marshal,
marshalArguments
) where
import Data.List.Split (splitOn)
import System.Environment
data NeedForArgument = Optional String | Compulsory | None
deriving(Show)
data Option = Short Char |
Long String |
Both Char String
deriving(Show)
instance Eq Option where
Short c1 == Short c2 = c1 == c2
Long s1 == Long s2 = s1 == s2
Short c1 == Both c2 _ = c1 == c2
Long s1 == Both _ s2 = s1 == s2
Both c1 _ == Short c2 = c1 == c2
Both _ s1 == Long s2 = s1 == s2
_ == _ = False
data MarshalledEntity = NonOptionArgument String |
OptionWithArgument Option String |
OnlyOption Option
deriving(Show)
type CommandLineArgument = String
type OptionDefinition = (Option, NeedForArgument)
marshalArguments :: [OptionDefinition] -> IO [MarshalledEntity]
marshalArguments x = do args <- getArgs
return (marshal args x)
marshal :: [CommandLineArgument] -> [OptionDefinition] -> [MarshalledEntity]
marshal [] _ = []
marshal (('-':'-':x):xs) ys = parseLong x xs ys
marshal (('-':x:[]):xs) ys = parseShort x xs ys
marshal (('-':x):xs) ys = parseCluster x xs ys
marshal (x:xs) ys = NonOptionArgument x : marshal xs ys
parseShort :: Char -> [CommandLineArgument] -> [OptionDefinition] -> [MarshalledEntity]
parseShort z [] ys = qualifyArgumentForOption (Short z) [] ys : []
parseShort z xxs@(('-':_):_) ys = qualifyArgumentForOption (Short z) [] ys : marshal xxs ys
parseShort z xxs@(x:xs) ys = case (getNeedForArgument (Short z) ys) of
None -> OnlyOption (Short z) : marshal xxs ys
_ -> OptionWithArgument (Short z) x : marshal xs ys
parseLong :: String -> [CommandLineArgument] -> [OptionDefinition] -> [MarshalledEntity]
parseLong z xs ys = case splitOn "=" z of
(u:[]) -> qualifyArgumentForOption (Long u) [] ys : marshal xs ys
(u:(v:[])) -> qualifyArgumentForOption (Long u) v ys : marshal xs ys
(_) -> error "Too many arguments"
parseCluster :: String -> [CommandLineArgument] -> [OptionDefinition] -> [MarshalledEntity]
parseCluster [] xs ys = marshal xs ys
parseCluster (z:zs) xs ys = qualifyArgumentForOption (Short z) [] ys : parseCluster zs xs ys
getNeedForArgument :: Option -> [OptionDefinition] -> NeedForArgument
getNeedForArgument x xs = case lookup x xs of
Nothing -> error "Option not defined"
Just u -> u
qualifyArgumentForOption :: Option -> String -> [OptionDefinition] -> MarshalledEntity
qualifyArgumentForOption x y xs = case (getNeedForArgument x xs, y) of
(Compulsory, []) -> error "option needs an argument"
(None, _:_) -> error "option can't have an argument"
(Optional u, []) -> OptionWithArgument x u
(_, []) -> OnlyOption x
(_, _) -> OptionWithArgument x y
| tobiasreinhardt/show | CLIArguments/src/Marshaller.hs | Haskell | apache-2.0 | 3,915 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Seraph.Model
( Directive(..)
, Event(..)
, OracleM
, oracle
, oracleModel
, oracleDebug
) where
-------------------------------------------------------------------------------
import Control.Lens
import Control.Monad.State.Strict
import Control.Monad.Writer.Strict
import qualified Data.Map as M
import Data.Maybe (isJust, mapMaybe)
import Data.Set (Set, (\\))
import qualified Data.Set as S
import Debug.Trace
import MVC
-------------------------------------------------------------------------------
import Seraph.Types
-------------------------------------------------------------------------------
oracleModel :: Model Config Event (Directives, [String])
oracleModel = asPipe $ loop model
where
model = unwrapModel oracle
-- model = unwrapModel oracleDebug
-------------------------------------------------------------------------------
type OracleM a = WriterT [String] (State Config) a
-------------------------------------------------------------------------------
unwrapModel :: (Event -> OracleM a)
-> Event
-> ListT (State Config) (a, [String])
unwrapModel f e = lift $ runWriterT (f e)
-------------------------------------------------------------------------------
oracleDebug :: Event -> OracleM Directives
oracleDebug e = do
s <- get
res <- traceShow s $ oracle e
-- s' <- get
-- traceShow ("EVT", e, "BEFORE", s, "AFTER", s') $ return res
traceShow ("EVT", e, "RES", res) $ return res
-------------------------------------------------------------------------------
oracle :: Event -> OracleM Directives
oracle (ProcessDeath prid) = do
progLogger "Process died"
existing <- gets $ view $ running . at prid . to isJust
mainLogger $ if existing
then "Spawning " ++ prid ^. pidStr
else "Process " ++ prid ^. pidStr ++ " not configured for restart"
modify $ set (running . at prid) Nothing
progs <- gets $ toListOf $ configured . ix prid
return $ Directives $ if null progs
then []
else map SpawnProg progs
where
progLogger = ctxLogger (prid ^. pidStr)
oracle (ProgRunning prid) = do
modify $ \c -> c & running <>~ S.singleton prid
progLogger "Marked as running"
return $ Directives []
where
progLogger = ctxLogger (prid ^. pidStr)
oracle (NewConfig cfg) = do
mainLogger "New config"
oldCfg <- get
put cfg
let oldPids = configPids oldCfg
let newPids = configPids cfg
let currentlyRunning = oldCfg ^. running
let spawnPids = newPids \\ oldPids
let killPids = currentlyRunning \\ newPids
spawnProgs <- getProgs $ spawnPids ^. to S.toList
let spawns = map SpawnProg spawnProgs
let kills = map KillProg $ killPids ^. to S.toList
mainLogger $ "Spawning " ++ slen spawns ++ " programs and killing " ++ slen kills
return . Directives $ spawns ++ kills
oracle ShutdownRequested = do
mainLogger "Shutdown requested."
modify $ set configured mempty
killPids <- gets $ view (running . to S.toList)
return . FinalDirectives . map KillProg $ killPids
oracle (ProgNotStarted prid e) = do
spawnProgs <- getProgs [prid]
progLogger $ "Failed to start: " ++ show e ++ ", retrying."
return $ Directives $ map SpawnProg spawnProgs
where
progLogger = ctxLogger (prid ^. pidStr)
-------------------------------------------------------------------------------
getProgs :: [ProgramId] -> OracleM [Program]
getProgs spawnPids = do
cfg <- get
return $ mapMaybe (progForPid cfg) spawnPids
where
progForPid cfg prid = cfg ^. configured . at prid
-------------------------------------------------------------------------------
configPids :: Config -> Set ProgramId
configPids cfg = cfg ^. configured . to M.keys . to S.fromList
-------------------------------------------------------------------------------
mainLogger :: MonadWriter [String] m => String -> m ()
mainLogger = ctxLogger "seraph"
-------------------------------------------------------------------------------
ctxLogger :: MonadWriter [String] m => String -> String -> m ()
ctxLogger label s = tell [unwords [label, "-", s]]
-------------------------------------------------------------------------------
slen :: Show a => [a] -> String
slen = show . length
| MichaelXavier/Seraph | src/Seraph/Model.hs | Haskell | bsd-2-clause | 4,483 |
-- 709
import Data.Function(on)
import Data.List(sortBy)
import Euler(splitOn)
parseBaseExp ws = [(a,b,n+1) | n <- [0..length ws-1],
let [a,b] = parseOne $ ws !! n]
where parseOne w = map read $ splitOn ',' w
findLargest ws = snd $ last $ sortBy (compare `on` fst) $
map logBaseExp $ parseBaseExp ws
where logBaseExp (a,b,n) = (b * log a, n)
main = do
ns <- readFile "../files/p099_base_exp.txt"
putStrLn $ show $ findLargest $ lines ns
| higgsd/euler | hs/99.hs | Haskell | bsd-2-clause | 505 |
{-# LANGUAGE RankNTypes #-}
module Insomnia.Interp.PMonad (ProbabilityMonad(..)
, SupportMonad(..)
, ExpMonad(..)
, SamplingMonad(..)
, ContinuousProbabilityMonad(..)
, samples
, ConditioningMonad(..)
, Exp
, Support
, Sample
, probability
, certainty
, impossibility
, logOdds)
where
import Control.Applicative
import Control.Monad (liftM)
import System.Random (RandomGen(split), random, newStdGen)
import Data.Number.Erf (invnormcdf)
type Probability = Double -- number from 0 to 1
certainty, impossibility :: Probability
certainty = 1.0
impossibility = 0.0
probability :: ExpMonad m => (a -> Bool) -> m a -> Double
probability p = expectation (numOfBool . p)
where numOfBool True = certainty
numOfBool False = impossibility
logOdds :: ExpMonad m => (a -> Bool) -> m a -> Double
logOdds p dist =
10 * (logBase 10 (probability p dist) - logBase 10 (probability (not . p) dist))
class Monad m => ProbabilityMonad m where
choose :: Probability -> m a -> m a -> m a
class ProbabilityMonad m => SupportMonad m where
support :: m a -> [a]
-- support (return x) = [x]
-- support (d >>= k) =
-- concat [support (k x) | x <- support d]
-- support (choose p d d') =
-- support d ++ support d'
class ProbabilityMonad m => ExpMonad m where
expectation :: (a -> Double) -> m a -> Double
-- expectation h (return x) = h x
-- expectation h (d >>= k) = expectation g d
-- where g x = expectation h (k x)
-- expectation h (choose p d d') =
-- p * expectation h d +
-- (1-p) * expectation h d'
-- sample (return x) r = (x, r)
-- sample (d >>= k) r =
-- let (x, r') = sample d r in sample (k x) r'
-- sample (choose p d d') r =
-- if r < p then sample d (r/p)
-- else sample d' ((1-r)/(1-p))
class ProbabilityMonad m => SamplingMonad m where
sample :: RandomGen g => m a -> g -> (a, g)
-- sample (return x) g = (x, g)
-- sample (d >>= k) g =
-- let (x, g') = sample d g in sample (k x) g'
-- sample (choose p d d') g =
-- let (x, g') = random g in
-- sample (if x < p then d else d') g'
newtype Support a = Support [a]
instance Functor Support where
fmap f (Support l) = Support (fmap f l)
instance Applicative Support where
pure = return
(Support lf) <*> (Support lx) =
Support [f x | f <- lf , x <- lx]
instance Monad Support where
return x = Support [x]
(Support l) >>= k =
Support (concat [s | x <- l, let Support s = k x])
instance ProbabilityMonad Support where
choose _ (Support l) (Support l') = Support (l ++ l')
instance SupportMonad Support where
support (Support l) = l
newtype Exp a = Exp ((a -> Double) -> Double)
instance Functor Exp where
fmap f (Exp d) = Exp (\h -> d (h . f))
instance Applicative Exp where
pure = return
(Exp df) <*> (Exp dx) = Exp (\h -> df (\f -> dx (\x -> h (f x))))
instance Monad Exp where
return x = Exp (\h -> h x)
(Exp d) >>= k =
Exp (\h -> let apply (Exp f) arg = f arg
g x = apply (k x) h
in d g)
instance ProbabilityMonad Exp where
choose p (Exp d1) (Exp d2) =
Exp (\h -> p * d1 h + (1-p) * d2 h)
instance ExpMonad Exp where
expectation h (Exp d) = d h
newtype Sample a = Sample (forall g . RandomGen g => g -> (a, g))
instance Functor Sample where
fmap f (Sample s) = Sample (\g -> let (x, g') = s g
in (f x, g'))
instance Applicative Sample where
pure = return
(Sample sf) <*> (Sample sx) =
Sample (\g -> let
(g1, g2) = split g
(f, _) = sf g1
(x, g'') = sx g2
in (f x, g''))
instance Monad Sample where
return x = Sample (\ g -> (x, g))
(Sample s) >>= k =
Sample (\ g -> let (a, g') = s g
Sample s' = k a
in s' g')
instance ProbabilityMonad Sample where
choose p (Sample s1) (Sample s2) =
Sample (\g -> let (x, g') = random g
in (if x < p then s1 else s2) g')
instance SamplingMonad Sample where
sample (Sample s) g = s g
class ProbabilityMonad m => ContinuousProbabilityMonad m where
u :: m Probability -- uniform over the unit interval
gauss :: m Double
gauss = liftM invnormcdf u
{-# MINIMAL u #-}
instance ContinuousProbabilityMonad Sample where
u = Sample random
samples :: SamplingMonad m => m a -> IO [a]
samples m =
do gen <- newStdGen
return $ run gen
where run g = let (a, g') = sample m g in a : run g'
class ProbabilityMonad m => ConditioningMonad m where
pfilter :: (a -> Bool) -> m a -> m a
instance ConditioningMonad Sample where
-- conditioning implemented by rejection sampling
pfilter p (Sample s) = Sample s'
where s' g = let (a, g') = s g
in if p a then (a, g')
else s' g'
instance ConditioningMonad Exp where
pfilter p (Exp integrate) = Exp integrate'
where integrate' f = integrate (\a -> if p a then f a else 0) /
integrate (\a -> if p a then 1 else 0)
instance ConditioningMonad Support where
pfilter p (Support as) = Support (filter p as)
| lambdageek/insomnia | src/Insomnia/Interp/PMonad.hs | Haskell | bsd-3-clause | 5,536 |
module Settings.Flavours.Quickest (quickestFlavour) where
import Expression
import Flavour
import {-# SOURCE #-} Settings.Default
-- Please update doc/flavours.md when changing this file.
quickestFlavour :: Flavour
quickestFlavour = defaultFlavour
{ name = "quickest"
, args = defaultBuilderArgs <> quickestArgs <> defaultPackageArgs
, libraryWays = pure [vanilla]
, rtsWays = quickestRtsWays }
quickestArgs :: Args
quickestArgs = sourceArgs SourceArgs
{ hsDefault = pure ["-O0", "-H64m"]
, hsLibrary = mempty
, hsCompiler = stage0 ? arg "-O"
, hsGhc = stage0 ? arg "-O" }
quickestRtsWays :: Ways
quickestRtsWays = pure [vanilla, threaded]
| ezyang/ghc | hadrian/src/Settings/Flavours/Quickest.hs | Haskell | bsd-3-clause | 701 |
{-# LANGUAGE ScopedTypeVariables #-}
module Utils where
import Kerchief.Prelude
import Prelude hiding (foldl, getLine, putStr, putStrLn)
import Control.Exception (SomeException, catch)
import Control.Monad.Trans (MonadIO)
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.Foldable (Foldable, foldl)
import System.Directory (getDirectoryContents)
askYesNo :: MonadIO m => String -> m a -> m a -> m a
askYesNo s yes no = io (prompt s) >>= \s -> case s of
"y" -> yes
"Y" -> yes
"yes" -> yes
"n" -> no
"N" -> no
"no" -> no
_ -> putStrLn "Please input \"y\" or \"n\"." >> askYesNo s yes no
catchNothing :: IO (Maybe a) -> IO (Maybe a)
catchNothing = (`catch` (\(_ :: SomeException) -> return Nothing))
catchVoid :: IO () -> IO ()
catchVoid = (`catch` (\(_ :: SomeException) -> return ()))
eitherToMaybe :: Either a b -> Maybe b
eitherToMaybe = either (const Nothing) Just
getDirectoryContents' :: FilePath -> IO [FilePath]
getDirectoryContents' = fmap (filter (\a -> a /= "." && a/= "..")) . getDirectoryContents
ifM :: Monad m => m Bool -> m a -> m a -> m a
ifM mb t f = mb >>= \b -> if b then t else f
-- | maybeThen a f m performs action |a| unconditionally, possibly preceded by
-- action |f b| if |m| is Just b.
maybeThen :: Monad m => m a -> (b -> m c) -> Maybe b -> m a
maybeThen thn _ Nothing = thn
maybeThen thn f (Just b) = f b >> thn
partitionM :: Monad m => (a -> m Bool) -> [a] -> m ([a], [a])
partitionM p = foldM (select p) ([],[])
where
select :: Monad m => (a -> m Bool) -> ([a],[a]) -> a -> m ([a],[a])
select q (ts,fs) x =
ifM (q x)
(return (x:ts,fs))
(return (ts,x:fs))
-- | Print each element of a Foldable, prepended by a number (starting at 1).
printNumbered :: (Show a, Foldable t) => t a -> IO ()
printNumbered = printNumberedWith show
printNumberedWith :: (MonadIO m, Foldable t) => (a -> String) -> t a -> m ()
printNumberedWith f = mapM_ putStrLn . showNumberedWith f
prompt :: MonadIO m => String -> m String
prompt s = putStr s >> getLine
showNumbered :: (Show a, Foldable t) => t a -> [String]
showNumbered = showNumberedWith show
showNumberedWith :: forall a t. Foldable t => (a -> String) -> t a -> [String]
showNumberedWith f = snd . foldl g (1,[])
where
g :: (Int,[String]) -> a -> (Int,[String])
g (n,ss) a = (n+1, ss ++ [show n ++ ". " ++ f a])
reads' :: Read a => String -> Maybe a
reads' s = case reads s of
[(a,"")] -> Just a
_ -> Nothing
unless' :: Monad m => m () -> Bool -> m ()
unless' = flip unless
whenJust :: (Functor m, Monad m) => (a -> m b) -> Maybe a -> m ()
whenJust _ Nothing = return ()
whenJust f (Just a) = void (f a)
safeReadFile :: FilePath -> IO (Maybe ByteString)
safeReadFile path = catchNothing (Just <$> BS.readFile path)
| mitchellwrosen/kerchief | src/Utils.hs | Haskell | bsd-3-clause | 2,909 |
module HQuestions where
import Control.Arrow ((&&&))
import System.Random
import Data.List
import Data.Maybe
import Data.Function (on)
import Control.Monad (replicateM)
h1 :: [a] -> a
h1 = last
h2 :: [a] -> a
h2 = last . init
h3 :: [a] -> Int -> a
h3 xs n = xs !! (n-1)
h4 :: [a] -> Int
h4 = foldr (const (+1)) 0
h5 :: [a] -> [a]
h5 = foldl (\acc x -> x : acc) []
h6 :: Eq a => [a] -> Bool
h6 xs = xs == h5 xs
data NestedList a = Elem a | List [NestedList a]
h7 :: NestedList a -> [a]
h7 (Elem a) = [a]
h7 (List as) = concatMap h7 $ as
h8 :: Eq a => [a] -> [a]
h8 = fmap head . h9
h9 :: Eq a => [a] -> [[a]]
h9 = foldr f []
where f x [] = [[x]]
f x ((a:ac):acc) = if a == x then (x:a:ac):acc
else [x]:(a:ac):acc
h10 :: Eq a => [a] -> [(Int, a)]
h10 = fmap (length &&& head) . h9
data SingleOrMultiple a = Single a | Multiple Int a deriving (Show)
h11 :: Eq a => [a] -> [SingleOrMultiple a]
h11 = fmap check . h9
where check [x] = Single x
check xs@(x:_) = Multiple (length xs) x
h12 :: [SingleOrMultiple a] -> [a]
h12 = concatMap change
where change (Single x) = [x]
change (Multiple n x) = replicate n x
h13 :: Eq a => [a] -> [SingleOrMultiple a]
h13 = foldr change []
where change x [] = [Single x]
change x acc@((Single y):ac) = if x == y
then (Multiple 2 x):ac
else (Single x):acc
change x acc@((Multiple n y):ac) = if x == y
then (Multiple (n+1) y):ac
else (Single x):acc
h14 :: [a] -> [a]
h14 = concatMap (replicate 2)
h15 :: [a] -> Int -> [a]
h15 xs n = xs >>= replicate n
h16 :: [a] -> Int -> [a]
-- h16 xs n = fmap snd . filter ((/=0) . flip mod n . fst) . zip [1..] $ xs
h16 xs n = [c | (i, c) <- zip [1..] xs, mod i n /= 0]
h17 :: [a] -> Int -> ([a], [a])
-- h17 = flip splitAt
h17 [] _ = ([], [])
h17 li@(x:xs) n | n <= 0 = ([], li)
| otherwise = let (a, ac) = h17 xs (n-1)
in (x:a, ac)
h18 :: [a] -> Int -> Int -> [a]
h18 xs start stop = [xs !! (i-1) | i <- [start .. stop]]
h19 :: [a] -> Int -> [a]
h19 xs n = b ++ a
where (a, b) = h17 xs (if n > 0 then n else length xs + n)
h20 :: Int -> [a] -> (a, [a])
h20 n xs = (last a, init a ++ b)
where (a, b) = h17 xs (if n > 0 then n else length xs + n)
h21 :: a -> [a] -> Int -> [a]
h21 x xs n = r ++ (x:l)
where (r, l) = h17 xs (if n > 0 then n-1 else length xs + n - 1)
h22 :: Int -> Int -> [Int]
h22 start stop = [start .. stop]
h23 :: [a] -> Int -> IO [a]
h23 xs n = do
g <- getStdGen
let index = take n $ randomRs (0, length xs - 1) g
return [xs !! i | i <- index]
h24 :: Int -> Int -> IO [Int]
h24 num stop = do
g <- getStdGen
return . take num $ randomRs (1, stop) g
h25 :: Eq a => [a] -> IO [a]
-- h25 xs = do
-- g <- getStdGen
-- return . take (length xs) . nub $ [xs !! i | i <- randomRs (0, length xs - 1) g]
--too stupid
h25 [] = return []
h25 xs = do
ind <- randomRIO (0, length xs-1)
let (as, b:bs) = h17 xs ind
rest <- h25 (as++bs)
return (b : rest)
h26 :: Int -> [a] -> [[a]]
h26 0 _ = [[]]
h26 _ [] = [] -- very very important here
h26 n (x:xs) = ((x:) <$> h26 (n-1) xs) ++ (h26 n xs)
h27 :: [Int] -> [a] -> [[[a]]]
h27 [] _ = [[]]
h27 _ [] = []
h27 nl@(n:ns) xs =
[ (li:gs) | (li, ri) <- change n xs, gs <- h27 ns ri ]
where change :: Int -> [a] -> [([a], [a])]
change 0 xs = [([], xs)]
change _ [] = []
change m (y:ys) = ((\(z, zs) -> (y:z, zs)) <$> change (m-1) ys) ++
((\(z, zs) -> (z, y:zs)) <$> change m ys)
h28 :: [[a]] -> [[a]]
h28 = sortBy (compare `on` length)
h28' :: [[a]] -> [[a]]
h28' xs =
let table = map (head &&& length) . group . sort . map length $ xs
getFre x = case lookup (length x) table of
Just fre -> fre
Nothing -> error "This should not happen"
in sortBy (compare `on` getFre) xs
h31 :: Integer -> Bool
h31 n = n `elem` (takeWhile (<=n) primes)
where primes = 2 : 3 : 5 : (filter check [7,9..])
check m = all ((/=0) . mod m) (takeWhile (<= (round . sqrt . fromIntegral $ m)) primes)
h32 :: Integer -> Integer -> Integer
h32 a b = if b == 0
then abs a
else h32 b (mod a b)
h33 :: Integer -> Integer -> Bool
h33 a b = (gcd a b) == 1
h34 :: Integer -> Int
h34 n = length . filter (h33 n) $ [1..n-1]
h35 :: Integer -> [Integer]
h35 = helper
where primes = 2 : 3 : 5 : (filter check [7,9..])
check m = all ((/=0) . mod m) (takeWhile (<= (round . sqrt . fromIntegral $ m)) primes)
helper 1 = []
helper m =
let n':_ = dropWhile ((/=0) . mod m) primes
in n':(h35 (div m n'))
h36 :: Integer -> [(Integer, Int)]
h36 = map (head &&& length) . group . h35
h37 :: Integer -> Integer
h37 n = product [(p-1) * p^(m-1) | (p, m) <- (h36 n)] -- more effect
h39 :: Integer -> Integer -> [Integer]
h39 start stop = takeWhile (<= stop) (dropWhile (< start) primes)
where primes = 2 : 3 : 5 : (filter check [7,9..])
check m = all ((/=0) . mod m) (takeWhile (<= (round . sqrt . fromIntegral $ m)) primes)
h40 :: Integer -> (Integer, Integer)
h40 n = head [(m, k) | m <- thisprimes, let k = n - m, k `elem` thisprimes]
where primes = 2 : 3 : 5 : (filter check [7,9..])
check m = all ((/=0) . mod m) (takeWhile (<= (round . sqrt . fromIntegral $ m)) primes)
thisprimes = takeWhile (<=n) primes
h41 :: Integer -> Integer -> [(Integer, Integer)]
h41 start stop = [h40 k | k <- [start .. stop], even k]
h41' :: Integer -> Integer -> Integer -> [(Integer, Integer)]
h41' start stop limit = filter ((> limit) . fst) . map h40 . filter even $ [start .. stop]
not' :: Bool -> Bool
not' True = False
not' _ = True
and', or', nand',nor',equ',xor',impl' :: Bool -> Bool -> Bool
and' True True = True
and' _ _ = False
or' False False = False
or' _ _ = True
nand' a b = not' (and' a b)
nor' a b = not' (or' a b)
equ' True True = True
equ' False False = True
equ' _ _ = False
xor' a b = not' (equ' a b)
impl' a b = or' b (not' a)
h47 :: (Bool -> Bool -> Bool) -> IO ()
h47 f = mapM_ putStrLn $ [show a ++ " " ++ show b ++ " " ++ show (f a b) |
a <- [True, False],
b <- [True, False]]
infixl 4 `or'`
infixl 6 `and'`
infixl 3 `equ'`
h48 :: Int -> ([Bool] -> Bool) -> IO ()
h48 n f = mapM_ putStrLn [toStr args ++ " => " ++ show (f args)| args <- replicateM n [True, False]]
where toStr = unwords . map space
space True = "True "
space False = "False"
h49 :: Int -> [String]
h49 n = replicateM n "01" -- maybe wrong, if the order matters
h50 = undefined
-- prepare data constructure for tree
-- this shouldn't be visit outside this
data Tree a = Empty | Branch a (Tree a) (Tree a) deriving (Show, Eq)
tree1 = Branch 'a' (Branch 'b' (leaf 'd')
(leaf 'e'))
(Branch 'c' Empty
(Branch 'f' (leaf 'g')
Empty))
-- A binary tree consisting of a root node only
tree2 = Branch 'a' Empty Empty
-- An empty binary tree
tree3 = Empty
-- A tree of integers
tree4 = Branch 1 (Branch 2 Empty (Branch 4 Empty Empty))
(Branch 2 Empty Empty)
leaf :: a -> Tree a
leaf x = Branch x Empty Empty
height :: Tree a -> Int
height Empty = 0
height (Branch _ li ri) = 1 + max (height li) (height ri)
add :: a -> Tree a -> [Tree a]
add x Empty = [leaf x]
add x (Branch y li ri) =
if height li - height ri == 0
then map (\li' -> Branch y li' ri) (add x li) ++
map (Branch y li) (add x ri)
else if height li > height ri
then map (Branch y li) (add x ri)
else map (\li' -> Branch y li' ri) (add x li)
h55 :: Int -> [Tree Char]
h55 0 = [Empty]
h55 n = nub $ concatMap (add 'x') (h55 (n-1))
-- Too slow
h55' :: Int -> [Tree Char]
h55' 0 = [Empty]
h55' n =
let (q, r) = (n-1) `quotRem` 2
in [Branch 'x' left right | i <- [q .. q+r],
left <- h55' i,
right <- h55' (n-1-i)]
image :: Tree a -> Tree a
image Empty = Empty
image (Branch x li ri) = Branch x (image ri) (image li)
h56 :: Eq a => Tree a -> Bool
h56 Empty = True
h56 (Branch _ li ri) =
mirror li ri
where mirror Empty Empty = True
mirror (Branch _ l1 r1) (Branch _ l2 r2) = mirror l1 r2 && mirror l2 r1
mirror _ _ = False
insertTree :: Ord a => a -> Tree a -> Tree a
insertTree x Empty = leaf x
insertTree x al@(Branch y li ri) =
if x == y
then al
else if x > y
then Branch y li (insertTree x ri)
else Branch y (insertTree x li) ri
h57 :: Ord a => [a] -> Tree a
h57 = foldl (flip insertTree) Empty
h58 :: Int -> [Tree Char]
h58 n =
let (q, r) = n `quotRem` 2
in if r == 0
then [Branch 'x' li (image li) | li <- h58 q]
else []
h59 :: Int -> a -> [Tree a]
h59 0 _ = [Empty]
h59 1 x = [Branch x Empty Empty]
h59 n x =
[Branch x li ri | (ln, rn) <- [(n-1, n-2), (n-1, n-1), (n-2, n-1)],
li <- h59 ln x,
ri <- h59 rn x]
h90 :: [[Int]]
h90 = filter isAlone (permutations [1..8])
where isAlone li = and [ not (or (zipWith elem li diag)) |
ind <- [1..8],
let ded = fmap (+ (-ind)) [1..8],
let pos = li !! (ind - 1),
let diag = fmap (\b -> if b == 0 then [] else [pos+b, pos-b]) ded]
type KnightPath = [(Int, Int)]
h91 :: Int -> (Int, Int) -> [KnightPath]
h91 size (x, y) =
let from :: (Int, Int) -> KnightPath -> [(Int, Int)]
from (a, b) old = filter (`notElem` old) (jump (a, b))
next :: KnightPath -> (Int, Int) -> [KnightPath]
next old now = if length old == size^2 - 1
then (now : old):[]
else concatMap (next (now:old)) (from now old)
jump :: (Int, Int) -> [(Int, Int)]
jump (a, b) = [(col, row) | i <- [-2, -1, 1, 2],
j <- if abs i == 2 then [-1, 1] else [-2, 2],
let col = a + i,
let row = b + j,
col >= 1 && col <= size && row >= 1 && row <= size]
in next [] (x, y) -- too slow
-- just copy from the answers ORZ
h93 :: [Integer] -> IO ()
h93 = mapM_ putStrLn . puzzle
data Expr = Const Integer |
Binary Op Expr Expr deriving (Eq, Show)
data Op = Plus | Minus | Times | Divide deriving (Show, Enum, Eq, Bounded)
type Equation = (Expr, Expr)
type Value = Rational
puzzle :: [Integer] -> [String]
puzzle = map (flip showEquation "") . equations
equations :: [Integer] -> [Equation]
equations [] = error "no equations for empty list"
equations [_] = error "no equations for one element list"
equations xs = [ (e1, e2) |
(ns1, ns2) <- splits xs,
(e1, v1) <- exprs ns1,
(e2, v2) <- exprs ns2,
v1 == v2]
exprs :: [Integer] -> [(Expr, Value)]
exprs [n] = [(Const n, fromIntegral n)]
exprs xs = [ (Binary op e1 e2, v) |
(ns1, ns2) <- splits xs,
(e1, v1) <- exprs ns1,
(e2, v2) <- exprs ns2,
op <- [minBound .. maxBound],
v <- maybeToList (apply op v1 v2),
not (rightAssiable op e2)]
splits :: [a] -> [([a], [a])] -- split list into two non-empty list
splits xs = tail . init $ (zip (inits xs) (tails xs)) -- xs at least two element
apply :: Op -> Value -> Value -> Maybe Value
apply Plus v1 v2 = Just (v1 + v2)
apply Minus v1 v2 = Just (v1 - v2)
apply Times v1 v2 = Just (v1 * v2)
apply Divide _ 0 = Nothing
apply Divide v1 v2 = Just (v1 / v2)
rightAssiable :: Op -> Expr -> Bool
rightAssiable Plus (Binary Plus _ _) = True
rightAssiable Plus (Binary Minus _ _) = True
rightAssiable Times (Binary Times _ _) = True
rightAssiable Times (Binary Divide _ _) = True
rightAssiable _ _ = False
showEquation :: Equation -> ShowS
showEquation (l, r) = showEquPrec 0 l . showString "=" . showEquPrec 0 r
showEquPrec :: Int -> Expr -> ShowS
showEquPrec _ (Const n) = shows n
showEquPrec p (Binary op e1 e2) = showParen (p > op_pre) $
showEquPrec op_pre e1 . showString (name op) . showEquPrec (op_pre + 1) e2
where op_pre = precendence op
name :: Op -> String
name Plus = "+"
name Minus = "-"
name Times = "*"
name Divide = "/"
precendence :: Op -> Int
precendence Plus = 6
precendence Minus = 6
precendence Times = 7
precendence Divide = 7
| niexshao/Exercises | src/HQuestions.hs | Haskell | bsd-3-clause | 12,574 |
module Example.Lens () where
| smurphy8/refactor-patternmatch-with-lens | src/Example/Lens.hs | Haskell | bsd-3-clause | 30 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE PostfixOperators #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE PolyKinds #-}
module Ion.Private.Types where
import Data.Char
import Data.List
import Data.Complex
import Data.Boolean
import Control.Monad.State
import Control.Monad.Free
{- Synonyms ---------------------------------------------------}
type Name = String
type ReturnType = String
type Stmt = Free Statement
type Ion = StateT Int Stmt
type LibName = String
{- Data Types -------------------------------------------------}
data Expr a where
-- Supported primitive types
B :: Bool -> Expr Bool
F :: Float -> Expr Float
C :: Char -> Expr Char
D :: Double -> Expr Double
I :: Int -> Expr Int
Cx :: Complex Float -> Expr (Complex Float)
-- Supported operations
And :: Expr a -> Expr a -> Expr a
Or :: Expr a -> Expr a -> Expr a
Not :: Expr a -> Expr a
Add :: Expr a -> Expr a -> Expr a
Mult :: Expr a -> Expr a -> Expr a
Sub :: Expr a -> Expr a -> Expr a
Var :: String -> Expr a
-- Conditional Logic
While :: Expr Bool -> Expr a -> Expr a
If :: Expr Bool -> Expr a -> Expr a -> Expr a
Set :: Expr a -> Expr a -> Expr a
data CFunc a = CFunc { name :: Name
, body :: Expr a
, loc :: LocationDecl
, inherit :: InheritDecl
, funcType :: FuncType
, numArgs :: Int
}
{-- Vector definitions ---------------------------------}
-- Phantoms
data Location = Host | Device
-- Inner type, not to be exposed
data Vector (l::Location) a = Vector { label :: String
, size :: Int
, elems :: [(Int, Expr a)]
}
deriving Show
data Iterator a = CountingIterator { ilabel :: String
, initval :: Expr a
}
data Random a = Random { rLabels :: [String]
, bounds :: (Int, Int)
}
data Statement next where
Decl :: Vector Host a -> next -> Statement next
DeclEmpty :: Vector Host a -> next -> Statement next
Trans :: CFunc a -> Vector Device a -> next -> Statement next
Cout :: Vector Host a -> next -> Statement next
Fold :: (Show a) => Name -> CFunc a -> Vector Device a -> Expr a -> next -> Statement next
Load :: Vector Device a -> next -> Statement next
Unload:: Vector Host a -> next -> Statement next
FoldD :: (Show a) => Name -> CFunc a -> CFunc a -> Vector Device a -> next -> Statement next
Sort :: Vector Device a -> next -> Statement next
AdjDiff :: Vector Device a -> next -> Statement next
IDecl :: Iterator a -> next -> Statement next
UpperBound :: Vector Device a -> Vector Device a -> Iterator a -> next -> Statement next
RandomGen :: Vector Host a -> Random a -> next -> Statement next
-- Declares whether a functor
-- is to be executed on the GPU or CPU
data LocationDecl = HostDecl | DeviceDecl | Both | Neither
data InheritDecl = None | BinaryFunc
data FuncType = Regular | StructBased
data ImportDecl = Stdlib | Thrust | Cuda | Iterator
{- Conversion Instances ------------------------------------------}
class ToExpr a where
toExpr :: a -> Expr a
class InitExpr a where
init :: Expr a
instance InitExpr Int where
init = I 0
instance InitExpr Bool where
init = B False
instance InitExpr Float where
init = F 0.0
instance InitExpr Double where
init = D 0.0
instance ToExpr Bool where
toExpr = B
instance ToExpr Int where
toExpr = I
instance ToExpr Float where
toExpr = F
instance ToExpr Double where
toExpr = D
instance ToExpr (Complex Float) where
toExpr = Cx
{- Show Instances -------------------------------------------------}
{- Used for emitting C++ code. Could perhaps be parameterized in
the future to output code in other languages such as Rust -}
instance Show (Expr a) where
show (Add e1 e2) = "(" ++ show e1 ++ " + " ++ show e2 ++ ")"
show (Sub e1 e2) = "(" ++ show e1 ++ " - " ++ show e2 ++ ")"
show (Mult e1 e2) = "(" ++ show e1 ++ " * " ++ show e2 ++ ")"
show (Or e1 e2) = "(" ++ show e1 ++ " || " ++ show e2 ++ ")"
show (And e1 e2) = "(" ++ show e1 ++ " && " ++ show e2 ++ ")"
show (Not e1) = "(!" ++ show e1 ++ ")"
show (Var s) = s
show (I n) = show n
show (B b) = map toLower $ show b
show (C c) = show c
show (F f) = show f
show (D d) = show d
show (Cx c) = "Complex("
++ (show $ realPart c) ++ ","
++ (show $ imagPart c) ++ ")"
show (If c a b) = "if(" ++ (show c) ++ "){\n"
++ show a ++ "}\n"
++ "else {\n"
++ show b ++ "}\n"
show (While c a) = "while(" ++ show c ++ "){\n"
++ show a ++ "}\n"
instance Show ImportDecl where
show Thrust = "thrust/"
show Stdlib = ""
show Cuda = ""
show Iterator = "iterator/"
-- TODO lookup thrust decl types
instance Show InheritDecl where
show l = case l of
BinaryFunc -> " : public thrust::binary_function"
None -> ""
instance Show LocationDecl where
show l = case l of
HostDecl -> "__host__ "
DeviceDecl -> "__device__ "
Both -> "__host__ __device__ \n"
Neither -> ""
instance Show (CFunc a) where
show func = preamble
++ "return " ++ (show $ body func) ++ ";"
++ closing
where preamble = case funcType func of
StructBased -> "struct "
++ (name func)
++ (case inherit func of
BinaryFunc -> show (inherit func) ++ "<const " ++ (retType $ body func) ++ "&"
++ ", const " ++ (retType $ body func) ++ "&"
++ ", " ++ (retType $ body func) ++ ">\n"
None -> "")
++ " {\n\t"
++ (show $ loc func)
++ (retType $ body func) ++ " operator()("
++ (case numArgs func of
1 -> args func
2 -> args2 func
3 -> args3 func)
++ ") const{\n\t\t"
Regular -> (retType $ body func)
++ "("
++ (case numArgs func of
1 -> args func
2 -> args2 func
3 -> args3 func)
++ ")"
++ " " ++ (name func) ++ "{\n\t"
closing = case funcType func of
StructBased -> "\n\t}\n};\n"
Regular -> "\n}\n"
iters :: String -> (String,String)
iters ident = (ident ++ ".begin()", ident ++ ".end()")
instance Show (Statement next) where
show (Decl (Vector ident sz elems) next) = "\tthrust::host_vector<"
++ (retType $ snd $ head elems)
++ "> "
++ ident
++ "(" ++ show sz ++ ")"
++ ";\n\t"
++ concatMap (\(ind, val) -> ident
++ "["
++ (show ind)
++ "] = "
++ (show val)
++ ";\n\t") elems
show (DeclEmpty (Vector ident sz elems) next) = "\tthrust::host_vector<"
++ (retType $ snd $ head elems)
++ "> "
++ ident
++ "(" ++ show sz ++ ")"
++ ";\n\t"
show (Load (Vector ident sz elems) next) = "\tthrust::device_vector<"
++ (retType $ snd $ head elems)
++ "> "
++ ident
++ " = v"
++ drop 1 ident
++ ";\n"
show (Unload (Vector ident sz elems) next) = "\tthrust::host_vector<"
++ (retType $ snd $ head elems)
++ "> "
++ ident
++ " = d"
++ drop 1 ident
++ ";\n"
show (Sort (Vector ident sz elems) next) = "\tthrust::sort("
++ (concat $ intersperse "," $
[ (fst $ iters ident),
(snd $ iters ident)])
++ ");"
show (AdjDiff (Vector ident sz elems) next) = "\tthrust::adjacent_difference("
++ (concat $ intersperse "," $
[ (fst $ iters ident),
(snd $ iters ident),
(fst $ iters ident)])
++ ");"
show (UpperBound (Vector ident1 sz1 elems1)
(Vector ident2 sz2 elems2)
(CountingIterator ident expr) next) = "\tthrust::upper_bound("
++ (concat $ intersperse "," $
[(fst $ iters ident1),
(snd $ iters ident1),
ident,
ident ++ " + " ++ show sz2,
(fst $ iters ident2)])
++ ");"
show (Trans fun (Vector ident _ _) next) = "\tthrust::transform("
++ (concat $ intersperse "," $
[ (fst $ iters ident),
(snd $ iters ident),
(fst $ iters ident)])
++ "," ++ (name fun)
++ "());"
show (Cout (Vector ident sz elems) next) = "\n\tfor (int i = 0; i < "
++ show sz
++ "; ++i){std::cout << "
++ ident
++ "[i] << \" \";}\n"
++ "\tstd::cout << std::endl;"
show (Fold to fun (Vector ident _ elems) init _) = "\t" ++ (retType init)
++ " "
++ to
++ " = "
++ "thrust::reduce("
++ (fst $ iters ident) ++ ", "
++ (snd $ iters ident) ++ ", "
++ (show init) ++ ", "
++ (name fun) ++ "());"
show (IDecl (CountingIterator ident expr) next) = "\tthrust::counting_iterator<"
++ retType expr
++ "> "
++ ident
++ "("
++ show expr
++ ");"
show (RandomGen (Vector id _ elems) (Random ident (a,b)) next) = "\tstatic thrust::default_random_engine "
++ ident !! 0
++ ";\n"
++ "\tstatic thrust::uniform_int_distribution<"
++ (retType $ snd $ head elems)
++ "> "
++ ident !! 1
++ "("
++ show a
++ ","
++ show b
++ ");\n"
++ "\tthrust::generate("
++ (fst $ iters id) ++ ", "
++ (snd $ iters id) ++ ", "
++ (ident !! 1) ++ "(" ++ ident !! 0 ++ "));\n"
{- Num, Ord, Frac Instances -------------------------------------}
{- This allows the Expr types to utilize regular arithmetic and
boolean operators for a more natural syntax -}
instance Num (Expr Int) where
fromInteger = I . fromIntegral
lhs + rhs = Add lhs rhs
lhs * rhs = Mult lhs rhs
lhs - rhs = Sub lhs rhs
signum (I v) = (I . signum) v
abs (I v) = (I . abs) v
instance Num (Expr Double) where
fromInteger = D . fromInteger
lhs + rhs = Add lhs rhs
lhs * rhs = Mult lhs rhs
lhs - rhs = Sub lhs rhs
signum (D v) = (D . signum) v
abs (D v) = (D . abs) v
instance Num (Expr Float) where
fromInteger = F . fromInteger
lhs + rhs = Add lhs rhs
lhs * rhs = Mult lhs rhs
lhs - rhs = Sub lhs rhs
signum (F v) = (F . signum) v
abs (F v) = (F . abs) v
instance Eq (Expr a) where
(Add a1 b1) == (Add a2 b2) = a1 == a2 && b1 == b2
(Sub a1 b1) == (Sub a2 b2) = a1 == a2 && b1 == b2
(I i1) == (I i2) = i1 == i2
(B b1) == (B b2) = b1 == b2
_ == _ = False
instance Ord (Expr Bool) where
(B b1) `compare` (B b2) = b1 `compare` b2
instance Ord (Expr Int) where
(I i1) `compare` (I i2) = i1 `compare` i2
instance Fractional (Expr Double) where
fromRational = D . realToFrac
recip = error "Undefined operation"
(/) = error "Undefined operation"
instance Fractional (Expr Float) where
fromRational = F . realToFrac
recip = error "Undefined operation"
(/) = error "Undefined operation"
instance Functor Statement where
fmap f (Decl vec next) = Decl vec (f next)
fmap f (DeclEmpty vec next) = DeclEmpty vec (f next)
fmap f (Load vec next) = Load vec (f next)
fmap f (Unload vec next) = Unload vec (f next)
fmap f (Trans cfunc vec next) = Trans cfunc vec (f next)
fmap f (Cout v next) = Cout v (f next)
fmap f (Fold to cfunc vec val next) = Fold to cfunc vec val (f next)
fmap f (Sort v next) = Sort v (f next)
fmap f (AdjDiff v next) = AdjDiff v (f next)
fmap f (IDecl iter next) = IDecl iter (f next)
fmap f (UpperBound v1 v2 i next) = UpperBound v1 v2 i (f next)
fmap f (RandomGen v rand next) = RandomGen v rand (f next)
{- Convenience operators for (Expr) bool's -}
instance Boolean (Expr Bool) where
b1 &&* b2 = And b1 b2
b1 ||* b2 = Or b1 b2
notB b1 = Not b1
true = B True
false = B False
{- Helper functions ---------------------------------------------}
{- Only for use in show instance, not to be exported It may be
better to work these into the type more naturally later on -}
retType :: (Expr a) -> String
retType (I _) = "int"
retType (F _) = "float"
retType (D _) = "double"
retType (C _) = "char"
retType (B _) = "bool"
retType (Cx _) = "complex<float> " -- Add space for C++98 compilers
retType (Add a b) = concat $ nub $ [retType a] ++ [retType b]
retType (Mult a b) = concat $ nub $ [retType a] ++ [retType b]
retType (Sub a b) = concat $ nub $ [retType a] ++ [retType b]
retType (And a b) = concat $ nub $ [retType a] ++ [retType b]
retType (Or a b) = concat $ nub $ [retType a] ++ [retType b]
retType (Not a) = concat $ nub $ [retType a]
retType (Var a) = ""
idents :: (Expr a) -> [String]
idents body = case body of
(Var a) -> [a]
(Add a b) -> idents a ++ idents b
(Or a b) -> idents a ++ idents b
(And a b) -> idents a ++ idents b
(Not a ) -> idents a
(Mult a b) -> idents a ++ idents b
(Sub a b) -> idents a ++ idents b
_ -> []
args :: (CFunc a) -> String
args fn = "const " ++ retType b ++ " " ++ (idents b !! 0)
where b = body fn
args2 :: (CFunc a) -> String
args2 fn = "const " ++ retType b ++ " " ++ (idents b !! 0) ++ ", "
++ "const " ++ retType b ++ " " ++ (idents b !! 1)
where b = body fn
args3 :: (CFunc a) -> String
args3 fn = "const " ++ retType b ++ " " ++ (idents b !! 0) ++ ", "
++ "const " ++ retType b ++ " " ++ (idents b !! 1) ++ ", "
++ "const " ++ retType b ++ " " ++ (idents b !! 2)
where b = body fn
| ku-fpg/thrust-gen | src/Ion/Private/Types.hs | Haskell | bsd-3-clause | 18,582 |
{-# LANGUAGE FlexibleContexts #-}
{-|
Module : $Header$
CopyRight : (c) 8c6794b6, 2011-2013
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : portable
Synthesis methods
-}
module Spectrofy.Synth
( sinsyn
, fftsyn
) where
import Data.Complex (Complex(..), realPart)
import Data.Word (Word8)
import Data.List (foldl1')
import Data.Array.Repa
((:.)(..), Array, All(..), D, DIM2, DIM3, Source, U, Z(..))
import qualified Data.Array.Repa as R
import qualified Data.Array.Repa.FFTW as R
-- --------------------------------------------------------------------------
--
-- Manual sinusoids
--
-- | Sums up sinusoids manually.
--
-- Frequency is taken from y axis, time from x axis.
-- Amplitude for each frequency is result of luminated value in each pixel.
--
sinsyn ::
Source s (Word8, Word8, Word8)
=> Int -> Int -> Array s DIM2 (Word8, Word8, Word8) -> Array D DIM2 Double
sinsyn rate delta = squash . sumSins . toSins rate . to3D delta . rgbamp
{-# INLINE sinsyn #-}
rgbamp ::
Source s (Word8, Word8, Word8)
=> Array s DIM2 (Word8, Word8, Word8) -> Array D DIM2 Double
rgbamp arr = {-# SCC "rgbamp" #-} R.traverse arr f g where
f = id
g h ix = 10 ** ((red*0.21 + green*0.71 + blue*0.07) / (255*3)) - 1 where
(red', green', blue') = h ix
red = fromIntegral red'
green = fromIntegral green'
blue = fromIntegral blue'
{-# INLINE rgbamp #-}
to3D :: Source s Double => Int -> Array s DIM2 Double -> Array D DIM3 Double
to3D n = R.extend (Z:.All:.All:.n)
{-# INLINE to3D #-}
toSins :: Source s Double => Int -> Array s DIM3 Double -> Array D DIM3 Double
toSins rate arr = {-# SCC "toSins" #-} R.traverse arr id f where
_:.y:._:._ = R.extent arr
f g ix@(_:.i:._:.k)
| amp <= 0 = 0
| otherwise = amp * sin (frq * k' * 2 * pi / rate') / y'
where
amp = g ix
frq = (rate'/2) - (((y'-i'+1)/y') * (rate'/2))
rate' = fromIntegral rate
i' = fromIntegral i
y' = fromIntegral y
k' = fromIntegral k
{-# INLINE toSins #-}
sumSins :: (Source s Double) => Array s DIM3 Double -> Array U DIM2 Double
sumSins arr = {-# SCC "sumSins" #-} R.sumS (R.backpermute sh' f arr) where
f (_:.i:.j:.k) = Z:.k:.j:.i
sh' = Z:.z:.y:.x
(_:.x:.y:.z) = R.extent arr
{-# INLINE sumSins #-}
squash :: Source s Double => Array s DIM2 Double -> Array D DIM2 Double
squash arr = {-# SCC squash #-} R.backpermute sh' f arr where
f (_:._:.j) = Z:.j `mod` x:.j `div` x
(_:.x:.y) = R.extent arr
sh' = Z:.1:.(x*y)
{-# INLINE squash #-}
-- --------------------------------------------------------------------------
--
-- Inversed FFT
--
-- | Performs 1-dimensional inverse fft on each column, then concatenate results.
--
-- RGB values are used for initial phases and magnitude.
--
fftsyn :: Int -> Array D DIM2 (Word8, Word8, Word8) -> Array D DIM2 Double
fftsyn fsz img =
{-# SCC "fftsyn" #-}
foldl1' R.append $ map (fftslice fsz img') [0..n-1] where
img' = rgbamp img
_:._:.n = R.extent img
{-# INLINE fftsyn #-}
fftslice :: Int -> Array D DIM2 Double -> Int -> Array D DIM2 Double
fftslice wsize arr n =
{-# SCC "fs_reshape" #-}
R.reshape (Z :. 1 :. wsize :: DIM2) $
{-# SCC "fs_map" #-}
R.map realPart $
{-# SCC "fs_ifft" #-}
R.ifft $
{-# SCC "fs_computeS" #-}
R.computeS $
{-# SCC "fs_slice" #-}
R.slice (R.map (\x -> x :+ x) $ grow2d wsize (zpad arr)) (Z:.All:.n)
{-# INLINE fftslice #-}
grow2d :: Int -> Array D DIM2 Double -> Array D DIM2 Double
grow2d n arr = {-# SCC "grow2d" #-} R.traverse arr f g where
f _ = Z :. n :. y
_:.x:.y = R.extent arr
g h (_:.i:.j)
| i' >= 4 = k/4
| otherwise = h (Z:.i':.j)
where
k = h (Z:.i'-3:.j) + h (Z:.i'-2:.j) + h (Z:.i'-1:.j) + h (Z:.i':.j)
i' = fst $ properFraction $ (x' * fromIntegral i / n')
n' = fromIntegral n :: Double
x' = fromIntegral x
{-# INLINE grow2d #-}
zpad :: Array D DIM2 Double -> Array D DIM2 Double
zpad arr = {-# SCC "zpad" #-} R.reshape sh' arr' where
_:.x:.y = R.extent arr
len = x * y
zeros = R.fromFunction zsh (const 0)
zsh = Z :. len
sh' = Z :. (2*x) :. y
arr' = R.append (R.reshape zsh arr) zeros
{-# INLINE zpad #-}
| 8c6794b6/spectrofy | Spectrofy/Synth.hs | Haskell | bsd-3-clause | 4,204 |
module Paths_Demotivation (
version,
getBinDir, getLibDir, getDataDir, getLibexecDir,
getDataFileName, getSysconfDir
) where
import qualified Control.Exception as Exception
import Data.Version (Version(..))
import System.Environment (getEnv)
import Prelude
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
catchIO = Exception.catch
version :: Version
version = Version [0,1,0,0] []
bindir, libdir, datadir, libexecdir, sysconfdir :: FilePath
bindir = "/home/michael/CodeRepository/Demotivation/.stack-work/install/x86_64-linux/lts-3.13/7.10.2/bin"
libdir = "/home/michael/CodeRepository/Demotivation/.stack-work/install/x86_64-linux/lts-3.13/7.10.2/lib/x86_64-linux-ghc-7.10.2/Demotivation-0.1.0.0-LXV8E2iIDbJ2sYgWYZwx7a"
datadir = "/home/michael/CodeRepository/Demotivation/.stack-work/install/x86_64-linux/lts-3.13/7.10.2/share/x86_64-linux-ghc-7.10.2/Demotivation-0.1.0.0"
libexecdir = "/home/michael/CodeRepository/Demotivation/.stack-work/install/x86_64-linux/lts-3.13/7.10.2/libexec"
sysconfdir = "/home/michael/CodeRepository/Demotivation/.stack-work/install/x86_64-linux/lts-3.13/7.10.2/etc"
getBinDir, getLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath
getBinDir = catchIO (getEnv "Demotivation_bindir") (\_ -> return bindir)
getLibDir = catchIO (getEnv "Demotivation_libdir") (\_ -> return libdir)
getDataDir = catchIO (getEnv "Demotivation_datadir") (\_ -> return datadir)
getLibexecDir = catchIO (getEnv "Demotivation_libexecdir") (\_ -> return libexecdir)
getSysconfDir = catchIO (getEnv "Demotivation_sysconfdir") (\_ -> return sysconfdir)
getDataFileName :: FilePath -> IO FilePath
getDataFileName name = do
dir <- getDataDir
return (dir ++ "/" ++ name)
| Michaelt293/Demotivation | .stack-work/dist/x86_64-linux/Cabal-1.22.4.0/build/autogen/Paths_Demotivation.hs | Haskell | bsd-3-clause | 1,730 |
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE LambdaCase #-}
module Main where
import Hans
import Hans.Device
import Hans.IP4.Dhcp.Client (DhcpLease(..),defaultDhcpConfig,dhcpClient)
import Hans.IP4.Packet (pattern WildcardIP4)
import Hans.Socket
import System.IO
import Control.Concurrent (forkIO,threadDelay)
import Control.Exception
import Control.Monad (forever,void)
import qualified Data.ByteString.Char8 as S8
import qualified Data.ByteString.Lazy.Char8 as L8
import System.Environment (getArgs)
import System.Exit (exitFailure)
main :: IO ()
main =
getArgs >>= \case
[name] -> run (S8.pack name)
_ -> fail "Expected a device name (i.e. en0)"
run :: S8.ByteString -> IO ()
run name = do
ns <- newNetworkStack defaultConfig
dev <- addDevice ns name defaultDeviceConfig
_ <- forkIO (showExceptions "processPackets" (processPackets ns))
startDevice dev
mbLease <- dhcpClient ns defaultDhcpConfig dev
case mbLease of
Just lease ->
putStrLn ("Assigned IP: " ++ show (unpackIP4 (dhcpAddr lease)))
Nothing -> do
putStrLn "Dhcp failed"
exitFailure
sock <- sListen ns defaultSocketConfig WildcardIP4 8080 10
void . forkIO . forever $ do
putStrLn "Waiting for a client"
client <- sAccept (sock :: TcpListenSocket IP4)
putStrLn "Got a client"
void $ forkIO (handleClient client)
forever $ do
threadDelay (secs 10)
dumpStats (devStats dev)
secs :: Int -> Int
secs = (*1000000)
showExceptions :: String -> IO a -> IO a
showExceptions l m = m `catch` \ e ->
do print (l, e :: SomeException)
throwIO e
handleClient :: TcpSocket IP4 -> IO ()
handleClient sock = loop `finally` sClose sock
where
loop =
do str <- sRead sock 1024
if L8.null str
then hPutStrLn stderr "Closing client"
else do
_ <- sWrite sock str
loop
| GaloisInc/HaNS | examples/echo-server/Main.hs | Haskell | bsd-3-clause | 2,193 |
module Sound.Player.Widgets (
songWidget,
playbackProgressBar
) where
import Brick.Types (Widget)
import Brick.Widgets.Core ((<+>), str, fill, vLimit, vBox)
import qualified Brick.Widgets.List as L
import qualified Brick.Widgets.ProgressBar as P
import qualified Data.Vector as Vec
import GHC.Float (double2Float)
import Lens.Micro ((^.))
import Sound.Player.Types (Song(Song), Status(Play, Pause), Playback(Playback))
-- | A song 'Widget', one of the items in the songs list.
songWidget :: Song -> Widget
songWidget (Song _ path status) =
vLimit 1 $ str (statusSymbol status) <+> str " " <+> str path <+> fill ' '
where
statusSymbol Play = "♫"
statusSymbol Pause = "•"
statusSymbol _ = " "
-- | A 'Widget' that shows two progress bars, the top bar shows the path of
-- the playing song, the bottom bar shows the playhead position, song duration
-- and playback percentage.
playbackProgressBar :: Maybe Playback -> L.List Song -> Widget
playbackProgressBar mPlayback l =
vBox [ titlePlaybackProgressBar mPlayback l
, infoPlaybackProgressBar mPlayback
]
-- | A 'Widget' that shows a progress bar with the path of the song.
titlePlaybackProgressBar :: Maybe Playback -> L.List Song -> Widget
titlePlaybackProgressBar Nothing _ = str " "
titlePlaybackProgressBar (Just pb@(Playback playPos _ _ _ _)) l =
P.progressBar (Just path) (playbackProgress pb)
where
songs = l ^. L.listElementsL
(Song _ path _) = songs Vec.! playPos
-- | A 'Widget' that shows a progress bar with the playhead position, song
-- duration and playback percentage.
infoPlaybackProgressBar :: Maybe Playback -> Widget
infoPlaybackProgressBar Nothing = str " "
infoPlaybackProgressBar (Just pb@(Playback _ _ ph d _)) =
P.progressBar (Just title) progress
where
progress = playbackProgress pb
percentage :: Integer
percentage = round (progress * 100)
title =
formatSeconds (d - ph) ++ " / " ++
formatSeconds d ++ " ~ " ++
show percentage ++ "%"
-- | A 'Float' number between 0 and 1 that is playing song's progress.
playbackProgress :: Playback -> Float
playbackProgress (Playback _ _ ph d _) = 1 - (double2Float ph / double2Float d)
-- | Returns a string that is a time formatted as /mm:ss/
formatSeconds :: Double -> String
formatSeconds s = pad (minutes s) ++ ":" ++ pad (seconds s)
where
seconds :: Double -> Int
seconds n = round n `mod` 60
minutes :: Double -> Int
minutes n = round n `div` 60
pad :: Int -> String
pad n
| length ns < 2 = "0" ++ ns
| otherwise = ns
where
ns = show n
| potomak/haskell-player | src/Sound/Player/Widgets.hs | Haskell | bsd-3-clause | 2,622 |
{-# LANGUAGE NoImplicitPrelude #-}
module Stack.Options.ScriptParser where
import Options.Applicative
import Options.Applicative.Builder.Extra
import Stack.Options.Completion
import Stack.Prelude
data ScriptOpts = ScriptOpts
{ soPackages :: ![String]
, soFile :: !FilePath
, soArgs :: ![String]
, soCompile :: !ScriptExecute
, soGhcOptions :: ![String]
, soScriptExtraDeps :: ![PackageIdentifierRevision]
}
deriving Show
data ScriptExecute
= SEInterpret
| SECompile
| SEOptimize
deriving Show
scriptOptsParser :: Parser ScriptOpts
scriptOptsParser = ScriptOpts
<$> many (strOption
(long "package" <>
metavar "PACKAGE(S)" <>
help "Additional package(s) that must be installed"))
<*> strArgument (metavar "FILE" <> completer (fileExtCompleter [".hs", ".lhs"]))
<*> many (strArgument (metavar "-- ARGUMENT(S) (e.g. stack script X.hs -- argument(s) to program)"))
<*> (flag' SECompile
( long "compile"
<> help "Compile the script without optimization and run the executable"
) <|>
flag' SEOptimize
( long "optimize"
<> help "Compile the script with optimization and run the executable"
) <|>
pure SEInterpret)
<*> many (strOption
(long "ghc-options" <>
metavar "OPTIONS" <>
completer ghcOptsCompleter <>
help "Additional options passed to GHC"))
<*> many (option extraDepRead
(long "extra-dep" <>
metavar "PACKAGE-VERSION" <>
help "Extra dependencies to be added to the snapshot"))
where
extraDepRead = eitherReader $ mapLeft show . parsePackageIdentifierRevision . fromString
| juhp/stack | src/Stack/Options/ScriptParser.hs | Haskell | bsd-3-clause | 1,773 |
module Statistics.Quantile.Bench.Accuracy where
import qualified Data.Vector as V
import Statistics.Quantile.Types
import Statistics.Quantile.Util
import Statistics.Sample
import System.IO
err :: Double
-> Double
-> Double
err true estimate =
let e = abs (true - estimate)
in e * e
selectorAccuracy :: Stream IO
-> Quantile
-> Double
-> Selector IO
-> IO Double
selectorAccuracy src q true (Selector select) =
err true <$> select q src
benchAccuracy :: Int
-> FilePath
-> Quantile
-> Double
-> Selector IO
-> IO Deviation
benchAccuracy n fp q true s = do
as <- V.replicateM n accuracy
pure $ Deviation (mean as) (stdDev as)
where accuracy = do
h <- openFile fp ReadMode
r <- selectorAccuracy (streamHandle h) q true s
hClose h
pure r
| olorin/slides | 2015-08-26-fp-syd-approx-quantiles/approx-quantile/src/Statistics/Quantile/Bench/Accuracy.hs | Haskell | mit | 940 |
module Main where
import Test.Tasty
-- import Test.Tasty.QuickCheck as QC
-- import Test.Tasty.HUnit as HU
-- import Test.Tasty.Golden as TG
import Test.Tasty.Hspec
specs :: Spec
specs = undefined
tests :: TestTree
tests = testGroup "main"
[ testCase "something" specs
]
main = defaultMain tests
| erochest/life-cast | specs/Specs.hs | Haskell | apache-2.0 | 313 |
{-# LANGUAGE CPP, DeriveDataTypeable, TupleSections #-}
{-# OPTIONS -Wall #-}
module Language.Paraiso.Optimization.DeadCodeElimination (
deadCodeElimination
) where
import Control.Applicative
import qualified Data.Graph.Inductive as FGL
import Data.Maybe
import qualified Data.Vector as V
import qualified Language.Paraiso.Annotation as Anot
import qualified Language.Paraiso.Annotation.Execution as Anot
import Language.Paraiso.Prelude
import Language.Paraiso.OM.Graph
import Language.Paraiso.Optimization.Graph
import Prelude hiding ((++))
-- | an optimization that changes nothing.
deadCodeElimination :: Optimization
deadCodeElimination = removeDead . markDead
markDead :: Optimization
markDead graph = imap update graph
where
update :: FGL.Node -> Anot.Annotation -> Anot.Annotation
update i a = Anot.set (Anot.Alive $ memoAlive V.! i) a
memoAlive :: V.Vector Bool
memoAlive = V.generate (FGL.noNodes graph) alive
alive i = case FGL.lab graph i of
Nothing -> error $ "node [" ++ show i ++ "] disappeared"
Just x -> case x of
NInst (Store _)_ -> True
NInst (Load _)_ -> True
_ -> or $ map (memoAlive V.!) $ FGL.suc graph i
removeDead :: Optimization
removeDead graph = graph2
where
graph2 = FGL.mkGraph newNodes newEdges
newNodes =
catMaybes $
fmap (\(idx, lab) -> (,lab) <$> renumber idx) $
FGL.labNodes graph
newEdges =
catMaybes $
fmap (\(iFrom, iTo, lab) -> (,,lab) <$> renumber iFrom <*> renumber iTo) $
FGL.labEdges graph
renumber :: Int -> Maybe Int
renumber = (oldToNew V.!)
oldToNew :: V.Vector (Maybe FGL.Node)
oldToNew =
V.update (V.replicate (FGL.noNodes graph) (Nothing)) $
V.imap (\newIdx oldIdx -> (oldIdx, Just newIdx)) $
newToOld
newToOld :: V.Vector FGL.Node
newToOld =
V.filter alive $ -- filter only alive nodes of
V.generate (FGL.noNodes graph) id -- all the node indices
alive :: FGL.Node -> Bool
alive i = case Anot.toMaybe $ getA $ fromJust $ FGL.lab graph i of
Just (Anot.Alive x) -> x
Nothing -> error $ "please markDead before removeDead" | nushio3/Paraiso | Language/Paraiso/Optimization/DeadCodeElimination.hs | Haskell | bsd-3-clause | 2,354 |
{-
(c) The University of Glasgow 2006
(c) The AQUA Project, Glasgow University, 1998
\section[TcForeign]{Typechecking \tr{foreign} declarations}
A foreign declaration is used to either give an externally
implemented function a Haskell type (and calling interface) or
give a Haskell function an external calling interface. Either way,
the range of argument and result types these functions can accommodate
is restricted to what the outside world understands (read C), and this
module checks to see if a foreign declaration has got a legal type.
-}
{-# LANGUAGE CPP #-}
module TcForeign
( tcForeignImports
, tcForeignExports
-- Low-level exports for hooks
, isForeignImport, isForeignExport
, tcFImport, tcFExport
, tcForeignImports'
, tcCheckFIType, checkCTarget, checkForeignArgs, checkForeignRes
, normaliseFfiType
, nonIOok, mustBeIO
, checkSafe, noCheckSafe
, tcForeignExports'
, tcCheckFEType
) where
#include "HsVersions.h"
import HsSyn
import TcRnMonad
import TcHsType
import TcExpr
import TcEnv
import FamInst
import FamInstEnv
import Coercion
import Type
import ForeignCall
import ErrUtils
import Id
import Name
import RdrName
import DataCon
import TyCon
import TcType
import PrelNames
import DynFlags
import Outputable
import Platform
import SrcLoc
import Bag
import Hooks
import qualified GHC.LanguageExtensions as LangExt
import Control.Monad
import Data.Maybe
-- Defines a binding
isForeignImport :: LForeignDecl name -> Bool
isForeignImport (L _ (ForeignImport {})) = True
isForeignImport _ = False
-- Exports a binding
isForeignExport :: LForeignDecl name -> Bool
isForeignExport (L _ (ForeignExport {})) = True
isForeignExport _ = False
{-
Note [Don't recur in normaliseFfiType']
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
normaliseFfiType' is the workhorse for normalising a type used in a foreign
declaration. If we have
newtype Age = MkAge Int
we want to see that Age -> IO () is the same as Int -> IO (). But, we don't
need to recur on any type parameters, because no paramaterized types (with
interesting parameters) are marshalable! The full list of marshalable types
is in the body of boxedMarshalableTyCon in TcType. The only members of that
list not at kind * are Ptr, FunPtr, and StablePtr, all of which get marshaled
the same way regardless of type parameter. So, no need to recur into
parameters.
Similarly, we don't need to look in AppTy's, because nothing headed by
an AppTy will be marshalable.
Note [FFI type roles]
~~~~~~~~~~~~~~~~~~~~~
The 'go' helper function within normaliseFfiType' always produces
representational coercions. But, in the "children_only" case, we need to
use these coercions in a TyConAppCo. Accordingly, the roles on the coercions
must be twiddled to match the expectation of the enclosing TyCon. However,
we cannot easily go from an R coercion to an N one, so we forbid N roles
on FFI type constructors. Currently, only two such type constructors exist:
IO and FunPtr. Thus, this is not an onerous burden.
If we ever want to lift this restriction, we would need to make 'go' take
the target role as a parameter. This wouldn't be hard, but it's a complication
not yet necessary and so is not yet implemented.
-}
-- normaliseFfiType takes the type from an FFI declaration, and
-- evaluates any type synonyms, type functions, and newtypes. However,
-- we are only allowed to look through newtypes if the constructor is
-- in scope. We return a bag of all the newtype constructors thus found.
-- Always returns a Representational coercion
normaliseFfiType :: Type -> TcM (Coercion, Type, Bag GlobalRdrElt)
normaliseFfiType ty
= do fam_envs <- tcGetFamInstEnvs
normaliseFfiType' fam_envs ty
normaliseFfiType' :: FamInstEnvs -> Type -> TcM (Coercion, Type, Bag GlobalRdrElt)
normaliseFfiType' env ty0 = go initRecTc ty0
where
go :: RecTcChecker -> Type -> TcM (Coercion, Type, Bag GlobalRdrElt)
go rec_nts ty
| Just ty' <- coreView ty -- Expand synonyms
= go rec_nts ty'
| Just (tc, tys) <- splitTyConApp_maybe ty
= go_tc_app rec_nts tc tys
| Just (bndr, inner_ty) <- splitPiTy_maybe ty
, Just tyvar <- binderVar_maybe bndr
= do (coi, nty1, gres1) <- go rec_nts inner_ty
return ( mkHomoForAllCos [tyvar] coi
, mkForAllTy bndr nty1, gres1 )
| otherwise -- see Note [Don't recur in normaliseFfiType']
= return (mkRepReflCo ty, ty, emptyBag)
go_tc_app :: RecTcChecker -> TyCon -> [Type]
-> TcM (Coercion, Type, Bag GlobalRdrElt)
go_tc_app rec_nts tc tys
-- We don't want to look through the IO newtype, even if it is
-- in scope, so we have a special case for it:
| tc_key `elem` [ioTyConKey, funPtrTyConKey, funTyConKey]
-- These *must not* have nominal roles on their parameters!
-- See Note [FFI type roles]
= children_only
| isNewTyCon tc -- Expand newtypes
, Just rec_nts' <- checkRecTc rec_nts tc
-- See Note [Expanding newtypes] in TyCon.hs
-- We can't just use isRecursiveTyCon; sometimes recursion is ok:
-- newtype T = T (Ptr T)
-- Here, we don't reject the type for being recursive.
-- If this is a recursive newtype then it will normally
-- be rejected later as not being a valid FFI type.
= do { rdr_env <- getGlobalRdrEnv
; case checkNewtypeFFI rdr_env tc of
Nothing -> nothing
Just gre -> do { (co', ty', gres) <- go rec_nts' nt_rhs
; return (mkTransCo nt_co co', ty', gre `consBag` gres) } }
| isFamilyTyCon tc -- Expand open tycons
, (co, ty) <- normaliseTcApp env Representational tc tys
, not (isReflexiveCo co)
= do (co', ty', gres) <- go rec_nts ty
return (mkTransCo co co', ty', gres)
| otherwise
= nothing -- see Note [Don't recur in normaliseFfiType']
where
tc_key = getUnique tc
children_only
= do xs <- mapM (go rec_nts) tys
let (cos, tys', gres) = unzip3 xs
-- the (repeat Representational) is because 'go' always
-- returns R coercions
cos' = zipWith3 downgradeRole (tyConRoles tc)
(repeat Representational) cos
return ( mkTyConAppCo Representational tc cos'
, mkTyConApp tc tys', unionManyBags gres)
nt_co = mkUnbranchedAxInstCo Representational (newTyConCo tc) tys []
nt_rhs = newTyConInstRhs tc tys
ty = mkTyConApp tc tys
nothing = return (mkRepReflCo ty, ty, emptyBag)
checkNewtypeFFI :: GlobalRdrEnv -> TyCon -> Maybe GlobalRdrElt
checkNewtypeFFI rdr_env tc
| Just con <- tyConSingleDataCon_maybe tc
, [gre] <- lookupGRE_Name rdr_env (dataConName con)
= Just gre -- See Note [Newtype constructor usage in foreign declarations]
| otherwise
= Nothing
{-
Note [Newtype constructor usage in foreign declarations]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GHC automatically "unwraps" newtype constructors in foreign import/export
declarations. In effect that means that a newtype data constructor is
used even though it is not mentioned expclitly in the source, so we don't
want to report it as "defined but not used" or "imported but not used".
eg newtype D = MkD Int
foreign import foo :: D -> IO ()
Here 'MkD' us used. See Trac #7408.
GHC also expands type functions during this process, so it's not enough
just to look at the free variables of the declaration.
eg type instance F Bool = D
foreign import bar :: F Bool -> IO ()
Here again 'MkD' is used.
So we really have wait until the type checker to decide what is used.
That's why tcForeignImports and tecForeignExports return a (Bag GRE)
for the newtype constructors they see. Then TcRnDriver can add them
to the module's usages.
************************************************************************
* *
\subsection{Imports}
* *
************************************************************************
-}
tcForeignImports :: [LForeignDecl Name] -> TcM ([Id], [LForeignDecl Id], Bag GlobalRdrElt)
tcForeignImports decls
= getHooked tcForeignImportsHook tcForeignImports' >>= ($ decls)
tcForeignImports' :: [LForeignDecl Name] -> TcM ([Id], [LForeignDecl Id], Bag GlobalRdrElt)
-- For the (Bag GlobalRdrElt) result,
-- see Note [Newtype constructor usage in foreign declarations]
tcForeignImports' decls
= do { (ids, decls, gres) <- mapAndUnzip3M tcFImport $
filter isForeignImport decls
; return (ids, decls, unionManyBags gres) }
tcFImport :: LForeignDecl Name -> TcM (Id, LForeignDecl Id, Bag GlobalRdrElt)
tcFImport (L dloc fo@(ForeignImport { fd_name = L nloc nm, fd_sig_ty = hs_ty
, fd_fi = imp_decl }))
= setSrcSpan dloc $ addErrCtxt (foreignDeclCtxt fo) $
do { sig_ty <- solveEqualities $ tcHsSigType (ForSigCtxt nm) hs_ty
; (norm_co, norm_sig_ty, gres) <- normaliseFfiType sig_ty
; let
-- Drop the foralls before inspecting the
-- structure of the foreign type.
(bndrs, res_ty) = tcSplitPiTys norm_sig_ty
arg_tys = mapMaybe binderRelevantType_maybe bndrs
id = mkLocalId nm sig_ty
-- Use a LocalId to obey the invariant that locally-defined
-- things are LocalIds. However, it does not need zonking,
-- (so TcHsSyn.zonkForeignExports ignores it).
; imp_decl' <- tcCheckFIType arg_tys res_ty imp_decl
-- Can't use sig_ty here because sig_ty :: Type and
-- we need HsType Id hence the undefined
; let fi_decl = ForeignImport { fd_name = L nloc id
, fd_sig_ty = undefined
, fd_co = mkSymCo norm_co
, fd_fi = imp_decl' }
; return (id, L dloc fi_decl, gres) }
tcFImport d = pprPanic "tcFImport" (ppr d)
-- ------------ Checking types for foreign import ----------------------
tcCheckFIType :: [Type] -> Type -> ForeignImport -> TcM ForeignImport
tcCheckFIType arg_tys res_ty (CImport (L lc cconv) safety mh l@(CLabel _) src)
-- Foreign import label
= do checkCg checkCOrAsmOrLlvmOrInterp
-- NB check res_ty not sig_ty!
-- In case sig_ty is (forall a. ForeignPtr a)
check (isFFILabelTy (mkFunTys arg_tys res_ty)) (illegalForeignTyErr Outputable.empty)
cconv' <- checkCConv cconv
return (CImport (L lc cconv') safety mh l src)
tcCheckFIType arg_tys res_ty (CImport (L lc cconv) safety mh CWrapper src) = do
-- Foreign wrapper (former f.e.d.)
-- The type must be of the form ft -> IO (FunPtr ft), where ft is a valid
-- foreign type. For legacy reasons ft -> IO (Ptr ft) is accepted, too.
-- The use of the latter form is DEPRECATED, though.
checkCg checkCOrAsmOrLlvmOrInterp
cconv' <- checkCConv cconv
case arg_tys of
[arg1_ty] -> do checkForeignArgs isFFIExternalTy arg1_tys
checkForeignRes nonIOok checkSafe isFFIExportResultTy res1_ty
checkForeignRes mustBeIO checkSafe (isFFIDynTy arg1_ty) res_ty
where
(arg1_tys, res1_ty) = tcSplitFunTys arg1_ty
_ -> addErrTc (illegalForeignTyErr Outputable.empty (text "One argument expected"))
return (CImport (L lc cconv') safety mh CWrapper src)
tcCheckFIType arg_tys res_ty idecl@(CImport (L lc cconv) (L ls safety) mh
(CFunction target) src)
| isDynamicTarget target = do -- Foreign import dynamic
checkCg checkCOrAsmOrLlvmOrInterp
cconv' <- checkCConv cconv
case arg_tys of -- The first arg must be Ptr or FunPtr
[] ->
addErrTc (illegalForeignTyErr Outputable.empty (text "At least one argument expected"))
(arg1_ty:arg_tys) -> do
dflags <- getDynFlags
let curried_res_ty = mkFunTys arg_tys res_ty
check (isFFIDynTy curried_res_ty arg1_ty)
(illegalForeignTyErr argument)
checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys
checkForeignRes nonIOok checkSafe (isFFIImportResultTy dflags) res_ty
return $ CImport (L lc cconv') (L ls safety) mh (CFunction target) src
| cconv == PrimCallConv = do
dflags <- getDynFlags
checkTc (xopt LangExt.GHCForeignImportPrim dflags)
(text "Use GHCForeignImportPrim to allow `foreign import prim'.")
checkCg checkCOrAsmOrLlvmOrInterp
checkCTarget target
checkTc (playSafe safety)
(text "The safe/unsafe annotation should not be used with `foreign import prim'.")
checkForeignArgs (isFFIPrimArgumentTy dflags) arg_tys
-- prim import result is more liberal, allows (#,,#)
checkForeignRes nonIOok checkSafe (isFFIPrimResultTy dflags) res_ty
return idecl
| otherwise = do -- Normal foreign import
checkCg checkCOrAsmOrLlvmOrInterp
cconv' <- checkCConv cconv
checkCTarget target
dflags <- getDynFlags
checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys
checkForeignRes nonIOok checkSafe (isFFIImportResultTy dflags) res_ty
checkMissingAmpersand dflags arg_tys res_ty
case target of
StaticTarget _ _ _ False
| not (null arg_tys) ->
addErrTc (text "`value' imports cannot have function types")
_ -> return ()
return $ CImport (L lc cconv') (L ls safety) mh (CFunction target) src
-- This makes a convenient place to check
-- that the C identifier is valid for C
checkCTarget :: CCallTarget -> TcM ()
checkCTarget (StaticTarget _ str _ _) = do
checkCg checkCOrAsmOrLlvmOrInterp
checkTc (isCLabelString str) (badCName str)
checkCTarget DynamicTarget = panic "checkCTarget DynamicTarget"
checkMissingAmpersand :: DynFlags -> [Type] -> Type -> TcM ()
checkMissingAmpersand dflags arg_tys res_ty
| null arg_tys && isFunPtrTy res_ty &&
wopt Opt_WarnDodgyForeignImports dflags
= addWarn (text "possible missing & in foreign import of FunPtr")
| otherwise
= return ()
{-
************************************************************************
* *
\subsection{Exports}
* *
************************************************************************
-}
tcForeignExports :: [LForeignDecl Name]
-> TcM (LHsBinds TcId, [LForeignDecl TcId], Bag GlobalRdrElt)
tcForeignExports decls =
getHooked tcForeignExportsHook tcForeignExports' >>= ($ decls)
tcForeignExports' :: [LForeignDecl Name]
-> TcM (LHsBinds TcId, [LForeignDecl TcId], Bag GlobalRdrElt)
-- For the (Bag GlobalRdrElt) result,
-- see Note [Newtype constructor usage in foreign declarations]
tcForeignExports' decls
= foldlM combine (emptyLHsBinds, [], emptyBag) (filter isForeignExport decls)
where
combine (binds, fs, gres1) (L loc fe) = do
(b, f, gres2) <- setSrcSpan loc (tcFExport fe)
return (b `consBag` binds, L loc f : fs, gres1 `unionBags` gres2)
tcFExport :: ForeignDecl Name -> TcM (LHsBind Id, ForeignDecl Id, Bag GlobalRdrElt)
tcFExport fo@(ForeignExport { fd_name = L loc nm, fd_sig_ty = hs_ty, fd_fe = spec })
= addErrCtxt (foreignDeclCtxt fo) $ do
sig_ty <- tcHsSigType (ForSigCtxt nm) hs_ty
rhs <- tcPolyExpr (nlHsVar nm) sig_ty
(norm_co, norm_sig_ty, gres) <- normaliseFfiType sig_ty
spec' <- tcCheckFEType norm_sig_ty spec
-- we're exporting a function, but at a type possibly more
-- constrained than its declared/inferred type. Hence the need
-- to create a local binding which will call the exported function
-- at a particular type (and, maybe, overloading).
-- We need to give a name to the new top-level binding that
-- is *stable* (i.e. the compiler won't change it later),
-- because this name will be referred to by the C code stub.
id <- mkStableIdFromName nm sig_ty loc mkForeignExportOcc
return ( mkVarBind id rhs
, ForeignExport { fd_name = L loc id
, fd_sig_ty = undefined
, fd_co = norm_co, fd_fe = spec' }
, gres)
tcFExport d = pprPanic "tcFExport" (ppr d)
-- ------------ Checking argument types for foreign export ----------------------
tcCheckFEType :: Type -> ForeignExport -> TcM ForeignExport
tcCheckFEType sig_ty (CExport (L l (CExportStatic esrc str cconv)) src) = do
checkCg checkCOrAsmOrLlvm
checkTc (isCLabelString str) (badCName str)
cconv' <- checkCConv cconv
checkForeignArgs isFFIExternalTy arg_tys
checkForeignRes nonIOok noCheckSafe isFFIExportResultTy res_ty
return (CExport (L l (CExportStatic esrc str cconv')) src)
where
-- Drop the foralls before inspecting n
-- the structure of the foreign type.
(bndrs, res_ty) = tcSplitPiTys sig_ty
arg_tys = mapMaybe binderRelevantType_maybe bndrs
{-
************************************************************************
* *
\subsection{Miscellaneous}
* *
************************************************************************
-}
------------ Checking argument types for foreign import ----------------------
checkForeignArgs :: (Type -> Validity) -> [Type] -> TcM ()
checkForeignArgs pred tys = mapM_ go tys
where
go ty = check (pred ty) (illegalForeignTyErr argument)
------------ Checking result types for foreign calls ----------------------
-- | Check that the type has the form
-- (IO t) or (t) , and that t satisfies the given predicate.
-- When calling this function, any newtype wrappers (should) have been
-- already dealt with by normaliseFfiType.
--
-- We also check that the Safe Haskell condition of FFI imports having
-- results in the IO monad holds.
--
checkForeignRes :: Bool -> Bool -> (Type -> Validity) -> Type -> TcM ()
checkForeignRes non_io_result_ok check_safe pred_res_ty ty
| Just (_, res_ty) <- tcSplitIOType_maybe ty
= -- Got an IO result type, that's always fine!
check (pred_res_ty res_ty) (illegalForeignTyErr result)
-- Case for non-IO result type with FFI Import
| not non_io_result_ok
= addErrTc $ illegalForeignTyErr result (text "IO result type expected")
| otherwise
= do { dflags <- getDynFlags
; case pred_res_ty ty of
-- Handle normal typecheck fail, we want to handle this first and
-- only report safe haskell errors if the normal type check is OK.
NotValid msg -> addErrTc $ illegalForeignTyErr result msg
-- handle safe infer fail
_ | check_safe && safeInferOn dflags
-> recordUnsafeInfer emptyBag
-- handle safe language typecheck fail
_ | check_safe && safeLanguageOn dflags
-> addErrTc (illegalForeignTyErr result safeHsErr)
-- success! non-IO return is fine
_ -> return () }
where
safeHsErr =
text "Safe Haskell is on, all FFI imports must be in the IO monad"
nonIOok, mustBeIO :: Bool
nonIOok = True
mustBeIO = False
checkSafe, noCheckSafe :: Bool
checkSafe = True
noCheckSafe = False
-- Checking a supported backend is in use
checkCOrAsmOrLlvm :: HscTarget -> Validity
checkCOrAsmOrLlvm HscC = IsValid
checkCOrAsmOrLlvm HscAsm = IsValid
checkCOrAsmOrLlvm HscLlvm = IsValid
checkCOrAsmOrLlvm _
= NotValid (text "requires unregisterised, llvm (-fllvm) or native code generation (-fasm)")
checkCOrAsmOrLlvmOrInterp :: HscTarget -> Validity
checkCOrAsmOrLlvmOrInterp HscC = IsValid
checkCOrAsmOrLlvmOrInterp HscAsm = IsValid
checkCOrAsmOrLlvmOrInterp HscLlvm = IsValid
checkCOrAsmOrLlvmOrInterp HscInterpreted = IsValid
checkCOrAsmOrLlvmOrInterp _
= NotValid (text "requires interpreted, unregisterised, llvm or native code generation")
checkCg :: (HscTarget -> Validity) -> TcM ()
checkCg check = do
dflags <- getDynFlags
let target = hscTarget dflags
case target of
HscNothing -> return ()
_ ->
case check target of
IsValid -> return ()
NotValid err -> addErrTc (text "Illegal foreign declaration:" <+> err)
-- Calling conventions
checkCConv :: CCallConv -> TcM CCallConv
checkCConv CCallConv = return CCallConv
checkCConv CApiConv = return CApiConv
checkCConv StdCallConv = do dflags <- getDynFlags
let platform = targetPlatform dflags
if platformArch platform == ArchX86
then return StdCallConv
else do -- This is a warning, not an error. see #3336
when (wopt Opt_WarnUnsupportedCallingConventions dflags) $
addWarnTc (text "the 'stdcall' calling convention is unsupported on this platform," $$ text "treating as ccall")
return CCallConv
checkCConv PrimCallConv = do addErrTc (text "The `prim' calling convention can only be used with `foreign import'")
return PrimCallConv
checkCConv JavaScriptCallConv = do dflags <- getDynFlags
if platformArch (targetPlatform dflags) == ArchJavaScript
then return JavaScriptCallConv
else do addErrTc (text "The `javascript' calling convention is unsupported on this platform")
return JavaScriptCallConv
-- Warnings
check :: Validity -> (MsgDoc -> MsgDoc) -> TcM ()
check IsValid _ = return ()
check (NotValid doc) err_fn = addErrTc (err_fn doc)
illegalForeignTyErr :: SDoc -> SDoc -> SDoc
illegalForeignTyErr arg_or_res extra
= hang msg 2 extra
where
msg = hsep [ text "Unacceptable", arg_or_res
, text "type in foreign declaration:"]
-- Used for 'arg_or_res' argument to illegalForeignTyErr
argument, result :: SDoc
argument = text "argument"
result = text "result"
badCName :: CLabelString -> MsgDoc
badCName target
= sep [quotes (ppr target) <+> text "is not a valid C identifier"]
foreignDeclCtxt :: ForeignDecl Name -> SDoc
foreignDeclCtxt fo
= hang (text "When checking declaration:")
2 (ppr fo)
| nushio3/ghc | compiler/typecheck/TcForeign.hs | Haskell | bsd-3-clause | 23,241 |
{-# OPTIONS_GHC -Wall #-}
module Reporting.Error.Type where
import qualified Data.Map as Map
import qualified Data.Maybe as Maybe
import Text.PrettyPrint.ANSI.Leijen
( Doc, (<>), (<+>), colon, dullyellow
, fillSep, hang, indent, text, underline, vcat
)
import qualified AST.Type as Type
import qualified AST.Variable as Var
import qualified Reporting.Error.Helpers as Help
import qualified Reporting.Region as Region
import qualified Reporting.Render.Type as RenderType
import qualified Reporting.Report as Report
-- ERRORS
data Error
= Mismatch Mismatch
| BadMain Type.Canonical
| InfiniteType String Type.Canonical
data Mismatch = MismatchInfo
{ _hint :: Hint
, _leftType :: Type.Canonical
, _rightType :: Type.Canonical
, _reason :: Maybe Reason
}
data Reason
= MessyFields [String] [String]
| IntFloat
| TooLongComparableTuple Int
| BadVar (Maybe VarType) (Maybe VarType)
data VarType
= Number
| Comparable
| Appendable
| CompAppend
| Rigid (Maybe String)
data Hint
= CaseBranch Int Region.Region
| Case
| IfCondition
| IfBranches
| MultiIfBranch Int Region.Region
| If
| List
| ListElement Int Region.Region
| BinopLeft Var.Canonical Region.Region
| BinopRight Var.Canonical Region.Region
| Binop Var.Canonical
| Function (Maybe Var.Canonical)
| UnexpectedArg (Maybe Var.Canonical) Int Int Region.Region
| FunctionArity (Maybe Var.Canonical) Int Int Region.Region
| BadTypeAnnotation String
| Instance String
| Literal String
| Pattern Pattern
| Shader
| Range
| Lambda
| Record
data Pattern
= PVar String
| PAlias String
| PData String
| PRecord
-- TO REPORT
toReport :: RenderType.Localizer -> Error -> Report.Report
toReport localizer err =
case err of
Mismatch info ->
mismatchToReport localizer info
InfiniteType name overallType ->
infiniteTypeToReport localizer name overallType
BadMain tipe ->
Report.report
"BAD MAIN TYPE"
Nothing
"The 'main' value has an unsupported type."
( Help.stack
[ Help.reflowParagraph $
"I need an Element, Html, (Signal Element), or (Signal Html) so I can render it\
\ on screen, but you gave me:"
, indent 4 (RenderType.toDoc localizer tipe)
]
)
-- TYPE MISMATCHES
mismatchToReport :: RenderType.Localizer -> Mismatch -> Report.Report
mismatchToReport localizer (MismatchInfo hint leftType rightType maybeReason) =
let
report =
Report.report "TYPE MISMATCH"
cmpHint leftWords rightWords extraHints =
comparisonHint localizer leftType rightType leftWords rightWords
( Maybe.maybeToList (reasonToString =<< maybeReason)
++ map toHint extraHints
)
in
case hint of
CaseBranch branchNumber region ->
report
(Just region)
( "The " ++ ordinalPair branchNumber
++ " branches of this `case` produce different types of values."
)
( cmpHint
("The " ++ Help.ordinalize (branchNumber -1) ++ " branch has this type:")
("But the " ++ Help.ordinalize branchNumber ++ " is:")
[ "All branches in a `case` must have the same type. So no matter\
\ which one we take, we always get back the same type of value."
]
)
Case ->
report
Nothing
( "All the branches of this case-expression are consistent, but the overall\n"
++ "type does not match how it is used elsewhere."
)
( cmpHint
"The `case` evaluates to something of type:"
"Which is fine, but the surrounding context wants it to be:"
[]
)
IfCondition ->
report
Nothing
"This condition does not evaluate to a boolean value, True or False."
( cmpHint
"You have given me a condition with this type:"
"But I need it to be:"
[ "Elm does not have \"truthiness\" such that ints and strings and lists\
\ are automatically converted to booleans. Do that conversion explicitly."
]
)
IfBranches ->
report
Nothing
"The branches of this `if` produce different types of values."
( cmpHint
"The `then` branch has type:"
"But the `else` branch is:"
[ "These need to match so that no matter which branch we take, we\
\ always get back the same type of value."
]
)
MultiIfBranch branchNumber region ->
report
(Just region)
( "The " ++ ordinalPair branchNumber
++ " branches of this `if` produce different types of values."
)
( cmpHint
("The " ++ Help.ordinalize (branchNumber - 1) ++ " branch has this type:")
("But the "++ Help.ordinalize branchNumber ++ " is:")
[ "All the branches of an `if` need to match so that no matter which\
\ one we take, we get back the same type of value overall."
]
)
If ->
report
Nothing
"All the branches of this `if` are consistent, but the overall\
\ type does not match how it is used elsewhere."
( cmpHint
"The `if` evaluates to something of type:"
"Which is fine, but the surrounding context wants it to be:"
[]
)
ListElement elementNumber region ->
report
(Just region)
("The " ++ ordinalPair elementNumber ++ " elements are different types of values.")
( cmpHint
("The " ++ Help.ordinalize (elementNumber - 1) ++ " element has this type:")
("But the "++ Help.ordinalize elementNumber ++ " is:")
[ "All elements should be the same type of value so that we can\
\ iterate through the list without running into unexpected values."
]
)
List ->
report
Nothing
( "All the elements in this list are the same type, but the overall\n"
++ "type does not match how it is used elsewhere."
)
( cmpHint
"The list has type:"
"Which is fine, but the surrounding context wants it to be:"
[]
)
BinopLeft op region ->
report
(Just region)
("The left argument of " ++ prettyName op ++ " is causing a type mismatch.")
( cmpHint
(prettyName op ++ " is expecting the left argument to be a:")
"But the left argument is:"
(binopHint op leftType rightType)
)
BinopRight op region ->
report
(Just region)
("The right argument of " ++ prettyName op ++ " is causing a type mismatch.")
( cmpHint
(prettyName op ++ " is expecting the right argument to be a:")
"But the right argument is:"
( binopHint op leftType rightType
++
[ "I always figure out the type of the left argument first and if it is\
\ acceptable on its own, I assume it is \"correct\" in subsequent checks.\
\ So the problem may actually be in how the left and right arguments interact."
]
)
)
Binop op ->
report
Nothing
( "The two arguments to " ++ prettyName op ++
" are fine, but the overall type of this expression\
\ does not match how it is used elsewhere."
)
( cmpHint
"The result of this binary operation is:"
"Which is fine, but the surrounding context wants it to be:"
[]
)
Function maybeName ->
report
Nothing
( "The return type of " ++ funcName maybeName ++ " is being used in unexpected ways."
)
( cmpHint
"The function results in this type of value:"
"Which is fine, but the surrounding context wants it to be:"
[]
)
UnexpectedArg maybeName 1 1 region ->
report
(Just region)
("The argument to " ++ funcName maybeName ++ " is causing a mismatch.")
( cmpHint
(Help.capitalize (funcName maybeName) ++ " is expecting the argument to be:")
"But it is:"
[]
)
UnexpectedArg maybeName index _totalArgs region ->
report
(Just region)
( "The " ++ Help.ordinalize index ++ " argument to " ++ funcName maybeName
++ " is causing a mismatch."
)
( cmpHint
( Help.capitalize (funcName maybeName) ++ " is expecting the "
++ Help.ordinalize index ++ " argument to be:"
)
"But it is:"
( if index == 1 then
[]
else
[ "I always figure out the type of arguments from left to right. If an argument\
\ is acceptable when I check it, I assume it is \"correct\" in subsequent checks.\
\ So the problem may actually be in how previous arguments interact with the "
++ Help.ordinalize index ++ "."
]
)
)
FunctionArity maybeName 0 actual region ->
let
arg =
if actual == 1 then "an argument" else show actual ++ " arguments"
preHint =
case maybeName of
Nothing ->
"You are giving " ++ arg ++ " to something that is not a function!"
Just name ->
prettyName name ++ " is not a function, but you are giving it " ++ arg ++ "!"
in
report
(Just region)
preHint
(text "Maybe you forgot some parentheses? Or a comma?")
FunctionArity maybeName expected actual region ->
let
s = if expected == 1 then "" else "s"
in
report
(Just region)
( Help.capitalize (funcName maybeName) ++ " is expecting " ++ show expected
++ " argument" ++ s ++ ", but was given " ++ show actual ++ "."
)
(text "Maybe you forgot some parentheses? Or a comma?")
BadTypeAnnotation name ->
report
Nothing
("The type annotation for " ++ Help.functionName name ++ " does not match its definition.")
( cmpHint
"The type annotation is saying:"
"But I am inferring that the definition has this type:"
[]
)
Instance name ->
report
Nothing
(Help.functionName name ++ " is being used in an unexpected way.")
( cmpHint
("Based on its definition, " ++ Help.functionName name ++ " has this type:")
"But you are trying to use it as:"
[]
)
Literal name ->
report
Nothing
( "This " ++ name ++ " value is being used as if it is some other type of value."
)
( cmpHint
("The " ++ name ++ " definitely has this type:")
("But it is being used as:")
[]
)
Pattern patErr ->
let
thing =
case patErr of
PVar name -> "variable `" ++ name ++ "`"
PAlias name -> "alias `" ++ name ++ "`"
PData name -> "tag `" ++ name ++ "`"
PRecord -> "a record"
in
report
Nothing
( Help.capitalize thing ++ " is causing problems in this pattern match."
)
( cmpHint
"This pattern matches things of type:"
"But the values it will actually be trying to match are:"
[]
)
Shader ->
report
Nothing
"There is some problem with this GLSL shader."
( cmpHint
"The shader block has this type:"
"Which is fine, but the surrounding context wants it to be:"
[]
)
Range ->
report
Nothing
"The low and high members of this list range are not the same type of value."
( cmpHint
"The low end of the range has type:"
"But the high end is:"
[]
)
Lambda ->
report
Nothing
"This anonymous function is being used in an unexpected way."
( cmpHint
"The anonymous function has type:"
"But you are trying to use it as:"
[]
)
Record ->
report
Nothing
"This record is being used in an unexpected way."
( cmpHint
"The record has type:"
"But you are trying to use it as:"
[]
)
comparisonHint
:: RenderType.Localizer
-> Type.Canonical
-> Type.Canonical
-> String
-> String
-> [Doc]
-> Doc
comparisonHint localizer leftType rightType leftWords rightWords finalHints =
let
(leftDoc, rightDoc) =
RenderType.diffToDocs localizer leftType rightType
in
Help.stack $
[ Help.reflowParagraph leftWords
, indent 4 leftDoc
, Help.reflowParagraph rightWords
, indent 4 rightDoc
]
++
finalHints
-- BINOP HINTS
binopHint :: Var.Canonical -> Type.Canonical -> Type.Canonical -> [String]
binopHint op leftType rightType =
let
leftString =
show (RenderType.toDoc Map.empty leftType)
rightString =
show (RenderType.toDoc Map.empty rightType)
in
if Var.is ["Basics"] "+" op && elem "String" [leftString, rightString] then
[ "To append strings in Elm, you need to use the (++) operator, not (+). "
++ "<http://package.elm-lang.org/packages/elm-lang/core/latest/Basics#++>"
]
else if Var.is ["Basics"] "/" op && elem "Int" [leftString, rightString] then
[ "The (/) operator is specifically for floating point division, and (//) is\
\ for integer division. You may need to do some conversions between ints and\
\ floats to get both arguments matching the division operator you want."
]
else
[]
-- MISMATCH HELPERS
ordinalPair :: Int -> String
ordinalPair number =
Help.ordinalize (number -1 ) ++ " and " ++ Help.ordinalize number
prettyName :: Var.Canonical -> String
prettyName (Var.Canonical _ opName) =
Help.functionName opName
funcName :: Maybe Var.Canonical -> String
funcName maybeVar =
case maybeVar of
Nothing ->
"this function"
Just var ->
"function " ++ prettyName var
-- MISMTACH REASONS
flipReason :: Reason -> Reason
flipReason reason =
case reason of
MessyFields leftOnly rightOnly ->
MessyFields rightOnly leftOnly
IntFloat ->
IntFloat
TooLongComparableTuple len ->
TooLongComparableTuple len
BadVar left right ->
BadVar right left
reasonToString :: Reason -> Maybe Doc
reasonToString reason =
let
go msg =
Just (toHint msg)
in
case reason of
MessyFields leftOnly rightOnly ->
do let typos = Help.findPotentialTypos leftOnly rightOnly
_ <- Help.vetTypos typos
misspellingMessage typos
IntFloat ->
go
"Elm does not automatically convert between Ints and Floats. Use\
\ `toFloat` and `round` to do specific conversions.\
\ <http://package.elm-lang.org/packages/elm-lang/core/latest/Basics#toFloat>"
TooLongComparableTuple len ->
go $
"Although tuples are comparable, this is currently only supported\
\ for tuples with 6 or fewer entries, not " ++ show len ++ "."
BadVar (Just Comparable) _ ->
go "Only ints, floats, chars, strings, lists, and tuples are comparable."
BadVar (Just Appendable) _ ->
go "Only strings, text, and lists are appendable."
BadVar (Just CompAppend) _ ->
go "Only strings and lists are both comparable and appendable."
BadVar (Just (Rigid _)) (Just (Rigid _)) ->
go doubleRigidError
BadVar (Just (Rigid _)) _ ->
go singleRigidError
BadVar _ (Just (Rigid _)) ->
go singleRigidError
BadVar _ _ ->
Nothing
singleRigidError :: String
singleRigidError =
"A type annotation is too generic. You can probably just switch to the\
\ type I inferred. These issues can be subtle though, so read more about it. "
++ Help.hintLink "type-annotations"
doubleRigidError :: String
doubleRigidError =
"A type annotation is clashing with itself or with a sub-annotation.\
\ This can be particularly tricky, so read more about it. "
++ Help.hintLink "type-annotations"
hintDoc :: Doc
hintDoc =
underline (text "Hint") <> colon
toHint :: String -> Doc
toHint str =
fillSep (hintDoc : map text (words str))
misspellingMessage :: [(String,String)] -> Maybe Doc
misspellingMessage typos =
if null typos then
Nothing
else
let
maxLen =
maximum (map (length . fst) typos)
in
Just $ hang 4 $ vcat $
toHint "I compared the record fields and found some potential typos."
: text ""
: map (pad maxLen) typos
pad :: Int -> (String, String) -> Doc
pad maxLen (leftField, rightField) =
text (replicate (maxLen - length leftField) ' ')
<> dullyellow (text leftField)
<+> text "<->"
<+> dullyellow (text rightField)
-- INFINITE TYPES
infiniteTypeToReport
:: RenderType.Localizer
-> String
-> Type.Canonical
-> Report.Report
infiniteTypeToReport localizer name overallType =
Report.report
"INFINITE TYPE"
Nothing
( "I am inferring a weird self-referential type for " ++ Help.functionName name
)
( Help.stack
[ Help.reflowParagraph $
"Here is my best effort at writing down the type. You will see ? and ∞ for\
\ parts of the type that repeat something already printed out infinitely."
, indent 4 (RenderType.toDoc localizer overallType)
, Help.reflowParagraph $
"Usually staring at the type is not so helpful in these cases, so definitely\
\ read the debugging hints for ideas on how to figure this out: "
++ Help.hintLink "infinite-type"
]
)
| laszlopandy/elm-compiler | src/Reporting/Error/Type.hs | Haskell | bsd-3-clause | 18,809 |
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- | Filter operators for JSON values added to PostgreSQL 9.4
module Database.Persist.Postgresql.JSON
( (@>.)
, (<@.)
, (?.)
, (?|.)
, (?&.)
, Value()
) where
import Data.Aeson (FromJSON, ToJSON, Value, encode, eitherDecodeStrict)
import qualified Data.ByteString.Lazy as BSL
import Data.Proxy (Proxy)
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding as TE (encodeUtf8)
import Database.Persist (EntityField, Filter(..), PersistValue(..), PersistField(..), PersistFilter(..))
import Database.Persist.Sql (PersistFieldSql(..), SqlType(..))
import Database.Persist.Types (FilterValue(..))
infix 4 @>., <@., ?., ?|., ?&.
-- | This operator checks inclusion of the JSON value
-- on the right hand side in the JSON value on the left
-- hand side.
--
-- === __Objects__
--
-- An empty Object matches any object
--
-- @
-- {} \@> {} == True
-- {"a":1,"b":false} \@> {} == True
-- @
--
-- Any key-value will be matched top-level
--
-- @
-- {"a":1,"b":{"c":true"}} \@> {"a":1} == True
-- {"a":1,"b":{"c":true"}} \@> {"b":1} == False
-- {"a":1,"b":{"c":true"}} \@> {"b":{}} == True
-- {"a":1,"b":{"c":true"}} \@> {"c":true} == False
-- {"a":1,"b":{"c":true"}} \@> {"b":{c":true}} == True
-- @
--
-- === __Arrays__
--
-- An empty Array matches any array
--
-- @
-- [] \@> [] == True
-- [1,2,"hi",false,null] \@> [] == True
-- @
--
-- Any array has to be a sub-set.
-- Any object or array will also be compared as being a subset of.
--
-- @
-- [1,2,"hi",false,null] \@> [1] == True
-- [1,2,"hi",false,null] \@> [null,"hi"] == True
-- [1,2,"hi",false,null] \@> ["hi",true] == False
-- [1,2,"hi",false,null] \@> ["hi",2,null,false,1] == True
-- [1,2,"hi",false,null] \@> [1,2,"hi",false,null,{}] == False
-- @
--
-- Arrays and objects inside arrays match the same way they'd
-- be matched as being on their own.
--
-- @
-- [1,"hi",[false,3],{"a":[null]}] \@> [{}] == True
-- [1,"hi",[false,3],{"a":[null]}] \@> [{"a":[]}] == True
-- [1,"hi",[false,3],{"a":[null]}] \@> [{"b":[null]}] == False
-- [1,"hi",[false,3],{"a":[null]}] \@> [[]] == True
-- [1,"hi",[false,3],{"a":[null]}] \@> [[3]] == True
-- [1,"hi",[false,3],{"a":[null]}] \@> [[true,3]] == False
-- @
--
-- A regular value has to be a member
--
-- @
-- [1,2,"hi",false,null] \@> 1 == True
-- [1,2,"hi",false,null] \@> 5 == False
-- [1,2,"hi",false,null] \@> "hi" == True
-- [1,2,"hi",false,null] \@> false == True
-- [1,2,"hi",false,null] \@> "2" == False
-- @
--
-- An object will never match with an array
--
-- @
-- [1,2,"hi",[false,3],{"a":null}] \@> {} == False
-- [1,2,"hi",[false,3],{"a":null}] \@> {"a":null} == False
-- @
--
-- === __Other values__
--
-- For any other JSON values the `(\@>.)` operator
-- functions like an equivalence operator.
--
-- @
-- "hello" \@> "hello" == True
-- "hello" \@> \"Hello" == False
-- "hello" \@> "h" == False
-- "hello" \@> {"hello":1} == False
-- "hello" \@> ["hello"] == False
--
-- 5 \@> 5 == True
-- 5 \@> 5.00 == True
-- 5 \@> 1 == False
-- 5 \@> 7 == False
-- 12345 \@> 1234 == False
-- 12345 \@> 2345 == False
-- 12345 \@> "12345" == False
-- 12345 \@> [1,2,3,4,5] == False
--
-- true \@> true == True
-- true \@> false == False
-- false \@> true == False
-- true \@> "true" == False
--
-- null \@> null == True
-- null \@> 23 == False
-- null \@> "null" == False
-- null \@> {} == False
-- @
--
-- @since 2.8.2
(@>.) :: EntityField record Value -> Value -> Filter record
(@>.) field val = Filter field (FilterValue val) $ BackendSpecificFilter " @> "
-- | Same as '@>.' except the inclusion check is reversed.
-- i.e. is the JSON value on the left hand side included
-- in the JSON value of the right hand side.
--
-- @since 2.8.2
(<@.) :: EntityField record Value -> Value -> Filter record
(<@.) field val = Filter field (FilterValue val) $ BackendSpecificFilter " <@ "
-- | This operator takes a column and a string to find a
-- top-level key/field in an object.
--
-- @column ?. string@
--
-- N.B. This operator might have some unexpected interactions
-- with non-object values. Please reference the examples.
--
-- === __Objects__
--
-- @
-- {"a":null} ? "a" == True
-- {"test":false,"a":500} ? "a" == True
-- {"b":{"a":[]}} ? "a" == False
-- {} ? "a" == False
-- {} ? "{}" == False
-- {} ? "" == False
-- {"":9001} ? "" == True
-- @
--
-- === __Arrays__
--
-- This operator will match an array if the string to be matched
-- is an element of that array, but nothing else.
--
-- @
-- ["a"] ? "a" == True
-- [["a"]] ? "a" == False
-- [9,false,"1",null] ? "1" == True
-- [] ? "[]" == False
-- [{"a":true}] ? "a" == False
-- @
--
-- === __Other values__
--
-- This operator functions like an equivalence operator on strings only.
-- Any other value does not match.
--
-- @
-- "a" ? "a" == True
-- "1" ? "1" == True
-- "ab" ? "a" == False
-- 1 ? "1" == False
-- null ? "null" == False
-- true ? "true" == False
-- 1.5 ? "1.5" == False
-- @
--
-- @since 2.10.0
(?.) :: EntityField record Value -> Text -> Filter record
(?.) = jsonFilter " ?? "
-- | This operator takes a column and a list of strings to
-- test whether ANY of the elements of the list are top
-- level fields in an object.
--
-- @column ?|. list@
--
-- /N.B. An empty list __will never match anything__. Also, this/
-- /operator might have some unexpected interactions with/
-- /non-object values. Please reference the examples./
--
-- === __Objects__
--
-- @
-- {"a":null} ?| ["a","b","c"] == True
-- {"test":false,"a":500} ?| ["a","b","c"] == True
-- {} ?| ["a","{}"] == False
-- {"b":{"a":[]}} ?| ["a","c"] == False
-- {"b":{"a":[]},"test":null} ?| [] == False
-- @
--
-- === __Arrays__
--
-- This operator will match an array if __any__ of the elements
-- of the list are matching string elements of the array.
--
-- @
-- ["a"] ?| ["a","b","c"] == True
-- [["a"]] ?| ["a","b","c"] == False
-- [9,false,"1",null] ?| ["a","false"] == False
-- [] ?| ["a","b","c"] == False
-- [] ?| [] == False
-- [{"a":true}] ?| ["a","b","c"] == False
-- [null,4,"b",[]] ?| ["a","b","c"] == True
-- @
--
-- === __Other values__
--
-- This operator functions much like an equivalence operator
-- on strings only. If a string matches with __any__ element of
-- the given list, the comparison matches. No other values match.
--
-- @
-- "a" ?| ["a","b","c"] == True
-- "1" ?| ["a","b","1"] == True
-- "ab" ?| ["a","b","c"] == False
-- 1 ?| ["a","1"] == False
-- null ?| ["a","null"] == False
-- true ?| ["a","true"] == False
-- "a" ?| [] == False
-- @
--
-- @since 2.10.0
(?|.) :: EntityField record Value -> [Text] -> Filter record
(?|.) field = jsonFilter " ??| " field . PostgresArray
-- | This operator takes a column and a list of strings to
-- test whether ALL of the elements of the list are top
-- level fields in an object.
--
-- @column ?&. list@
--
-- /N.B. An empty list __will match anything__. Also, this/
-- /operator might have some unexpected interactions with/
-- /non-object values. Please reference the examples./
--
-- === __Objects__
--
-- @
-- {"a":null} ?& ["a"] == True
-- {"a":null} ?& ["a","a"] == True
-- {"test":false,"a":500} ?& ["a"] == True
-- {"test":false,"a":500} ?& ["a","b"] == False
-- {} ?& ["{}"] == False
-- {"b":{"a":[]}} ?& ["a"] == False
-- {"b":{"a":[]},"c":false} ?& ["a","c"] == False
-- {"a":1,"b":2,"c":3,"d":4} ?& ["b","d"] == True
-- {} ?& [] == True
-- {"b":{"a":[]},"test":null} ?& [] == True
-- @
--
-- === __Arrays__
--
-- This operator will match an array if __all__ of the elements
-- of the list are matching string elements of the array.
--
-- @
-- ["a"] ?& ["a"] == True
-- ["a"] ?& ["a","a"] == True
-- [["a"]] ?& ["a"] == False
-- ["a","b","c"] ?& ["a","b","d"] == False
-- [9,"false","1",null] ?& ["1","false"] == True
-- [] ?& ["a","b"] == False
-- [{"a":true}] ?& ["a"] == False
-- ["a","b","c","d"] ?& ["b","c","d"] == True
-- [null,4,{"test":false}] ?& [] == True
-- [] ?& [] == True
-- @
--
-- === __Other values__
--
-- This operator functions much like an equivalence operator
-- on strings only. If a string matches with all elements of
-- the given list, the comparison matches.
--
-- @
-- "a" ?& ["a"] == True
-- "1" ?& ["a","1"] == False
-- "b" ?& ["b","b"] == True
-- "ab" ?& ["a","b"] == False
-- 1 ?& ["1"] == False
-- null ?& ["null"] == False
-- true ?& ["true"] == False
-- 31337 ?& [] == True
-- true ?& [] == True
-- null ?& [] == True
-- @
--
-- @since 2.10.0
(?&.) :: EntityField record Value -> [Text] -> Filter record
(?&.) field = jsonFilter " ??& " field . PostgresArray
jsonFilter :: PersistField a => Text -> EntityField record Value -> a -> Filter record
jsonFilter op field a = Filter field (UnsafeValue a) $ BackendSpecificFilter op
-----------------
-- AESON VALUE --
-----------------
instance PersistField Value where
toPersistValue = toPersistValueJsonB
fromPersistValue = fromPersistValueJsonB
instance PersistFieldSql Value where
sqlType = sqlTypeJsonB
-- FIXME: PersistText might be a bit more efficient,
-- but needs testing/profiling before changing it.
-- (When entering into the DB the type isn't as important as fromPersistValue)
toPersistValueJsonB :: ToJSON a => a -> PersistValue
toPersistValueJsonB = PersistDbSpecific . BSL.toStrict . encode
fromPersistValueJsonB :: FromJSON a => PersistValue -> Either Text a
fromPersistValueJsonB (PersistText t) =
case eitherDecodeStrict $ TE.encodeUtf8 t of
Left str -> Left $ fromPersistValueParseError "FromJSON" t $ T.pack str
Right v -> Right v
fromPersistValueJsonB (PersistByteString bs) =
case eitherDecodeStrict bs of
Left str -> Left $ fromPersistValueParseError "FromJSON" bs $ T.pack str
Right v -> Right v
fromPersistValueJsonB x = Left $ fromPersistValueError "FromJSON" "string or bytea" x
-- Constraints on the type might not be necessary,
-- but better to leave them in.
sqlTypeJsonB :: (ToJSON a, FromJSON a) => Proxy a -> SqlType
sqlTypeJsonB _ = SqlOther "JSONB"
fromPersistValueError :: Text -- ^ Haskell type, should match Haskell name exactly, e.g. "Int64"
-> Text -- ^ Database type(s), should appear different from Haskell name, e.g. "integer" or "INT", not "Int".
-> PersistValue -- ^ Incorrect value
-> Text -- ^ Error message
fromPersistValueError haskellType databaseType received = T.concat
[ "Failed to parse Haskell type `"
, haskellType
, "`; expected "
, databaseType
, " from database, but received: "
, T.pack (show received)
, ". Potential solution: Check that your database schema matches your Persistent model definitions."
]
fromPersistValueParseError :: (Show a)
=> Text -- ^ Haskell type, should match Haskell name exactly, e.g. "Int64"
-> a -- ^ Received value
-> Text -- ^ Additional error
-> Text -- ^ Error message
fromPersistValueParseError haskellType received err = T.concat
[ "Failed to parse Haskell type `"
, haskellType
, "`, but received "
, T.pack (show received)
, " | with error: "
, err
]
newtype PostgresArray a = PostgresArray [a]
instance PersistField a => PersistField (PostgresArray a) where
toPersistValue (PostgresArray ts) = PersistArray $ toPersistValue <$> ts
fromPersistValue (PersistArray as) = PostgresArray <$> traverse fromPersistValue as
fromPersistValue wat = Left $ fromPersistValueError "PostgresArray" "array" wat
| naushadh/persistent | persistent-postgresql/Database/Persist/Postgresql/JSON.hs | Haskell | mit | 12,559 |