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
|
|---|---|---|---|---|---|
--The following iterative sequence is defined for the set of positive integers:
--n → n/2 (n is even)
--n → 3n + 1 (n is odd)
--Using the rule above and starting with 13, we generate the following sequence:
--13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
--It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
--Which starting number, under one million, produces the longest chain?
--NOTE: Once the chain starts the terms are allowed to go above one million.
-- Generate a list of Collatz sequences with arguments 1 to 1000000.
listOfSequences = map collatzSequence [1..1000000]
-- Generate a list of lengths of Collatz sequences
listOfSubsetLengths = map length listOfSequences
-- Zip indices starting from 1 to the list of the lengths of Collatz sequences
-- Select the largest value pair and print the second value from the pair.
main = print $ snd . maximum $ zip listOfSubsetLengths [1..]
-- The Collatz function to generate the next term.
collatz :: Integer -> Integer
collatz 1 = 1
collatz n = if (odd n)
then (3 * n + 1)
else n `div` 2
-- Generate the entire Collatz sequence
collatzSequence :: Integer -> [Integer]
collatzSequence = terminate . iterate collatz
where
terminate (1:_) = [1]
terminate (x:xs) = x:terminate xs
|
jongensvantechniek/Project-Euler
|
problem014-haskell/problem14.hs
|
Haskell
|
mit
| 1,427
|
module Main where
import Render.Setup
import Graphics.UI.GLUT
import Data.Time
main :: IO ()
main = do
(progName, _args) <- getArgsAndInitialize
start <- getCurrentTime
initialDisplayMode $= [ SingleBuffered, RGBMode ]
initialWindowSize $= Size 512 512
initialWindowPosition $= Position 100 100
_ <- createWindow progName
state <- makeState
sceneImage <- createShadedImage
displayCallback $= display sceneImage
reshapeCallback $= Just reshape
stop <- getCurrentTime
putStr "Rendered in: "
print $ (diffUTCTime stop start)
mainLoop
|
dongy7/raytracer
|
src/Main.hs
|
Haskell
|
mit
| 576
|
module Twilio.IVRSpec where
import Test.Hspec
import Twilio.IVR
import Control.Lens
import Control.Lens.Setter
import Control.Monad.Coroutine
import Control.Monad.Coroutine.SuspensionFunctors
import Text.XML.Light
-- never use for production purposes, NOT TRUE XML EQUIVALENCE
instance Eq Content where
x == y = (showContent x) == (showContent y)
spec :: Spec
spec = do
describe "say" $ do
it "generates data structure" $ do
Left (Request res _) <- resume (say "Test Message")
res `shouldBe` (Right (Say "Test Message"))
it "generates XML" $ do
Left (Request res _) <- resume (say "Test Message")
renderTwiML res `shouldBe` (Elem $ unode "Say" "Test Message")
describe "hangup" $ do
it "generates data structure" $ do
Left (Request res _) <- resume hangup
res `shouldBe` (Right Hangup)
it "generates XML" $ do
Left (Request res _) <- resume hangup
renderTwiML res `shouldBe` (Elem $ unode "Hangup" ())
describe "gather" $ do
it "generates XML" $ do
Left (Request res _) <- resume (gather "Test Message" (numDigits .~ 10))
renderTwiML res `shouldBe` (Elem $ unode "Gather" (Elem $ unode "Say" "Test Message") &
add_attrs [
Attr (unqual "timeout") "5",
Attr (unqual "finishOnKey") "#",
Attr (unqual "numDigits") "10",
Attr (unqual "method") "POST",
Attr (unqual "action") "" ])
Left (Request res2 _) <- resume (gather "Test Message" (
(numDigits .~ 5) .
(timeout .~ 10) .
(finishOnKey .~ Nothing)
))
renderTwiML res2 `shouldBe` (Elem $ unode "Gather" (Elem $ unode "Say" "Test Message") &
add_attrs [
Attr (unqual "timeout") "10",
Attr (unqual "finishOnKey") "",
Attr (unqual "numDigits") "5",
Attr (unqual "method") "POST",
Attr (unqual "action") "" ])
|
steven777400/TwilioIVR
|
test/Twilio/IVRSpec.hs
|
Haskell
|
mit
| 2,244
|
module Neural_Net where
import System.Random
import qualified System.Posix.Types as P
import qualified GHC.IO.Handle.Types as T
import Data.Dynamic
import qualified Data.Array.Repa as R
import qualified Data.Array.Repa.Eval as R
import qualified Data.Array.Repa.Unsafe as R
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as VUN
--import qualified ConvolveCPU as CV
--import qualified ConvolveGPU as CV
import qualified ConvolvePY as CV
import qualified Data.Array.Repa.Repr.Unboxed as RU
import qualified Data.Array.Repa.Algorithms.Matrix as RM
import qualified Data.Array.Repa.Algorithms.Randomish as RR
import qualified Configure as CF
import qualified Utils as U
-- Define the parameters for the two convulational layers
cnvLyr1Config = ([4, 84, 84], 16, [4, 8, 8], 4, U.sol [20, 20, 16, 1])
cnvLyr2Config = ([16, 20, 20], 32, [16, 4, 4], 2, U.sol [2592, 1])
type NNEnv = ((RU.Array RU.U R.DIM4 Float,
RU.Array RU.U R.DIM4 Float,
RU.Array RU.U R.DIM2 Float,
RU.Array RU.U R.DIM2 Float),
(RU.Array RU.U R.DIM4 Float,
RU.Array RU.U R.DIM4 Float,
RU.Array RU.U R.DIM2 Float,
RU.Array RU.U R.DIM2 Float))
initilaizeEnv :: NNEnv
initilaizeEnv =
-- Setup the weight and bias vector for layer 1
let (w1,b1) = let (inpImgDim, numFltrs, fltrDim, strd, _) = cnvLyr1Config
-- Feature map dimensions
ftrMpSd = (1 + quot (inpImgDim !! 1 - fltrDim !! 1) strd)
-- number of input and output connections per neuron
numInpPer = (fltrDim !! 0 * fltrDim !! 1 * fltrDim !! 2)
numOutPer = (numFltrs * ftrMpSd * ftrMpSd)
wBnd = sqrt (6.0 / (fromIntegral (numInpPer + numOutPer)))
dummyWieghtTest = R.fromListUnboxed
(U.sol $ reverse (numFltrs : fltrDim))
[0.037 |
_ <- [1..numFltrs * product fltrDim]]
w = dummyWieghtTest
-- XXX reactivate this
--w = RR.randomishDoubleArray
-- (U.sol $ reverse (numFltrs : fltrDim))
-- (-wBnd)
-- wBnd
-- 1
b = R.fromUnboxed ((U.sol [ftrMpSd, ftrMpSd, numFltrs, 1]))
(VUN.replicate (numFltrs * ftrMpSd * ftrMpSd)
(0 :: Float))
in (w, b)
-- Setup the weight and bias vector for layer 2
(w2,b2) = let (inpImgDim, numFltrs, fltrDim, strd, _) = cnvLyr2Config
-- Feature map dimensions
ftrMpSd = (1 + quot (inpImgDim !! 1 - fltrDim !! 1) strd)
-- number of input and output connections per neuron
numInpPer = (fltrDim !! 0 * fltrDim !! 1 * fltrDim !! 2)
numOutPer = (numFltrs * ftrMpSd * ftrMpSd)
wBnd = sqrt (6.0 / (fromIntegral (numInpPer + numOutPer)))
dummyWieghtTest = R.fromListUnboxed
(U.sol $ reverse (numFltrs : fltrDim))
[0.037 |
_ <- [1..numFltrs * product fltrDim]]
w = dummyWieghtTest
-- XXX reactivate this
--w = RR.randomishDoubleArray
-- (U.sol $ reverse (numFltrs : fltrDim))
-- (-wBnd)
-- wBnd
-- 1
b = R.fromUnboxed ((U.sol [ftrMpSd, ftrMpSd, numFltrs, 1]))
(VUN.replicate (numFltrs * ftrMpSd * ftrMpSd)
(0 :: Float))
in (w, b)
-- Setup the weight and bias vector for layer 3
(w3,b3) = let nIn = 32 * 9 * 9 -- Number of inputs
nOut = 256 -- Number of neurons
wBnd = sqrt (6.0 / (fromIntegral (nIn + nOut)))
dummyWieghtTest = R.fromListUnboxed
(U.sol [nOut, nIn])
[0.037 | _ <- [1..nOut * nIn]]
w = dummyWieghtTest
--w = RR.randomishDoubleArray ((U.sol [nOut, nIn])) (-wBnd)
-- wBnd 1
b = R.fromUnboxed ((U.sol [nOut, 1]))
(VUN.replicate nOut (0 :: Float))
in (w, b)
-- Setup the weight and bias vector for layer 4
(w4,b4) = let nIn = 256 -- Number of inputs
nOut = length CF.availActns -- Number of neurons
wBnd = sqrt (6.0 / (fromIntegral (nIn + nOut)))
dummyWieghtTest = R.fromListUnboxed
(U.sol [nOut, nIn])
[0.037 | _ <- [1..nOut * nIn]]
w = dummyWieghtTest
--w = RR.randomishDoubleArray ((U.sol [nOut, nIn])) (-wBnd)
-- wBnd 1
b = R.fromUnboxed ((U.sol [nOut, 1]))
(VUN.replicate nOut (0 :: Float))
in (w, b)
in ((w1, w2, w3, w4), (b1, b2, b3, b4))
nnBestAction
:: T.Handle
-> T.Handle
-> V.Vector (VUN.Vector Float)
-> NNEnv
-> IO (Char)
nnBestAction toC fromC screens nnEnv = do
-- Link the layers and give output
let ((w1, w2, w3, w4), (b1, b2, b3, b4)) = nnEnv
if V.length screens < 4 then
return '0'
else do
actnProb <- evalActnProb toC fromC nnEnv (getLastState screens)
-- Get the most probable action
return (CF.availActns !! (VUN.maxIndex actnProb))
--evalActnProb
-- :: (Monad m)
-- => NNEnv
-- -> RU.Array R.D R.DIM4 Float
-- -> m(VUN.Vector Float)
evalActnProb toC fromC nnEnv input = do
-- Link the layers and give output
let ((w1, w2, w3, w4), (b1, b2, b3, b4)) = nnEnv
out1 <- cnvLyr toC fromC cnvLyr1Config input w1 b1
out2 <- cnvLyr toC fromC cnvLyr2Config out1 w2 b2
out3 <- cnctdLyr3 out2 w3 b3
actnProb <- outptLyr4 out3 w4 b4
return actnProb
trainHelper
:: T.Handle
-> T.Handle
-> IO (NNEnv)
-> (RU.Array R.D R.DIM4 Float, Char, Integer, RU.Array R.D R.DIM4 Float)
-> IO (NNEnv)
trainHelper toC fromC nnEnv transition = do
let (pre, act, reward, post) = transition
nnEnvUnwraped <- nnEnv
-- Train the nn on transition here
preProb <- evalActnProb toC fromC nnEnvUnwraped pre
postProb <- evalActnProb toC fromC nnEnvUnwraped post
return nnEnvUnwraped
nnTrain
:: T.Handle
-> T.Handle
-> V.Vector (VUN.Vector Float)
-> V.Vector Char
-> V.Vector Integer
-> NNEnv
-> IO NNEnv
nnTrain toC fromC screens actions rewards nnEnv = do
let ((w1, w2, w3, w4), (b1, b2, b3, b4)) = nnEnv
lMem = V.length screens
g <- newStdGen
if V.length screens < 4 then do
return nnEnv
else do
-- Pick n random states from memory and train on them
let numMiniBatches = 32
indices = take numMiniBatches (randomRs (0, lMem - 2) g :: [Int])
getTransition i = ((getState screens i), actions V.! i, rewards V.! i, (getState screens (i + 1)))
transitions = map getTransition indices
putStrLn ("Training on state indices: " ++ show indices)
-- Our fold helper that accumulates on nnEnv
nnNew <- (foldl (trainHelper toC fromC) (return nnEnv) transitions)
return nnNew
getState screens n =
-- Consturct the indices of the 4 frames and extract them from mem
let indices = map (max 0) [n - 3..n]
screenState = map (screens V.!) indices
as1DVector = foldl (VUN.++) (head screenState) (tail screenState)
asTensor = R.delay (R.fromUnboxed ((U.sol [84, 84, 4, 1]) :: R.DIM4)
as1DVector)
in asTensor
getLastState screens =
let last4 = V.take 4 screens
as1DVector = V.foldl (VUN.++) (V.head last4) (V.tail last4)
asTensor = R.delay (R.fromUnboxed (U.sol [84, 84, 4, 1]) as1DVector)
in asTensor
--cnvLyr
-- :: (Monad m, R.Shape sh1, R.Shape sh2)
-- => ([Int], Int, [Int], Int, sh1)
-- -> RU.Array R.D R.DIM4 Float
-- -> RU.Array R.U R.DIM4 Float
-- -> RU.Array R.U R.DIM4 Float
-- -> m(sh2)
cnvLyr toC fromC lyrConfig input w b = do
let (_, _, _, strd, outPShape) = lyrConfig
convOutpt <- (CV.conv4D toC fromC input (R.delay w) strd)
let thresh = (0.0 :: Float)
actvtn = (R.+^) convOutpt b
abvThresh = R.map (\e -> if e > thresh then (e - thresh) else 0) actvtn
outP = R.reshape outPShape abvThresh
return outP
--cnctdLyr3
-- :: (Monad m)
-- => RU.Array R.D R.DIM2 Float
-- -> RU.Array R.U R.DIM2 Float
-- -> RU.Array R.U R.DIM2 Float
-- -> m(RU.Array R.D R.DIM2 Float)
cnctdLyr3 input w b = do
-- input has extent 1, 32 * 9 * 9
inputC <- R.computeUnboxedP input
prodIW <- mmultP inputC w
let actvtn = (R.+^) prodIW b
abvThresh = R.map (\e -> if e > 0.0 then (e - 0.0) else 0) actvtn
outP = abvThresh
-- outP has extent 256
return outP
--outptLyr4
-- :: (Monad m)
-- => RU.Array R.D R.DIM2 Float
-- -> RU.Array R.U R.DIM2 Float
-- -> RU.Array R.U R.DIM2 Float
-- -> m(VUN.Vector Float)
outptLyr4 input w b = do
-- input has extent 256
inputC <- R.computeUnboxedP input
prodIW <- mmultP inputC w
let actvtn = (R.+^) prodIW b
outP = VUN.fromList (R.toList actvtn)
-- outP has extent (length availActns)
return outP
mmultP :: Monad m
=> R.Array RU.U R.DIM2 Float
-> R.Array RU.U R.DIM2 Float
-> m (R.Array RU.U R.DIM2 Float)
mmultP arr brr
= [arr, brr] `R.deepSeqArrays`
do trr <- transpose2P brr
let (R.Z R.:. h1 R.:. _) = R.extent arr
let (R.Z R.:. _ R.:. w2) = R.extent brr
R.computeP
$ R.fromFunction (R.Z R.:. h1 R.:. w2)
$ \ix -> R.sumAllS
$ R.zipWith (*)
(R.unsafeSlice arr (R.Any R.:. (RM.row ix) R.:. R.All))
(R.unsafeSlice trr (R.Any R.:. (RM.col ix) R.:. R.All))
transpose2P
:: Monad m
=> R.Array RU.U R.DIM2 Float
-> m (R.Array RU.U R.DIM2 Float)
transpose2P arr
= arr `R.deepSeqArray`
do R.computeUnboxedP
$ R.unsafeBackpermute new_extent swap arr
where swap (R.Z R.:. i R.:. j) = R.Z R.:. j R.:. i
new_extent = swap (R.extent arr)
|
hamsal/DM-AtariAI
|
src/Neural_Net.hs
|
Haskell
|
mit
| 11,066
|
{-
Reasonably fast enumerations for combinations, `recombinations', and
permutations.
2009 Nathan Blythe, Dr. Oscar Boykin (see LICENSE for details)
A combination is a length m subset of {0 .. n - 1}.
A `recombination' is a length m submultiset of {0 .. n - 1}.
A permutation is a length m ordered subset of {0 .. n - 1}.
General notes:
- The num* functions determine how many of that particular object can be
constructed.
- The nat2* functions construct the unique * corresponding to the natural
number provided.
- The *2nat functions construct the unique natural number corresponding to
the * provided.
- select constructs a sublist of a provided list using indices from another
provided list.
- nat2* is slow, but next* is fast. make* uses nat2* and next* to
construct sequences of *s.
- Unfortunately there is no nextPerm or makePerm (yet!). For the time
being, use Perms.hs when a large series of permutations is needed.
-}
module Combinadics (numCombs, comb2nat, nat2comb, nextComb, makeCombs,
numRecombs, recomb2nat, nat2recomb, nextRecomb, makeRecombs,
numPerms, perm2nat, nat2perm,
select) where
import Data.List
import Data.Maybe
{-
A handy factorial function (memoized).
-}
facs :: [Integer]
facs = scanl (*) 1 [1..]
fac :: Integer -> Integer
fac n = genericIndex facs n
{-
A handy n-choose-k function.
-}
nchoosek :: Integer -> Integer -> Integer
nchoosek n k | k > n = 0
| k == n = 1
| otherwise = div (fac n) ((fac (n - k)) * (fac k))
{-
Infix notation for n-choose-k.
-}
(#) :: Integer -> Integer -> Integer
(#) n k = nchoosek n k
{-
Infix notation for n-choose-k (with repetition/replacement).
-}
(&) :: Integer -> Integer -> Integer
(&) n k = nchoosek (n + k - 1) k
{-
Number of length m combinations in n variables.
-}
numCombs :: Integer -> Integer -> Integer
numCombs n m = n # m
{-
Natural number corresponding to a combination r in n variables.
-}
comb2nat :: Integer -> [Integer] -> Integer
comb2nat n r = f (m - 1) r
where m = toInteger $ length r
f 0 _ = (n # m)
- ((n - (head r)) # m)
f j (h1 : h2 : t) = ((n - h1 - 1) # j)
- ((n - h2) # j)
+ f (j - 1) (h2 : t)
{-
Length m combination in n variables corresponding to a natural number x.
-}
nat2comb :: Integer -> Integer -> Integer -> [Integer]
nat2comb n m x = f (-1) m x
where f _ 1 i = [i]
f p d i = j : f j (d - 1) (i' j)
where i' v = i
- (n # d)
+ ((n - v) # d)
+ (n # (d - 1))
- ((n - v - 1) # (d - 1))
g v = ((i' v) >= 0)
&& ((i' v) < (n#(d-1)))
&& (v > p)
j = head $ filter g [0 .. n - 1]
{-
Next combination in n variables.
-}
nextComb :: Integer -> [Integer] -> [Integer]
nextComb n x = snd $ f n x
where f k (h : []) = (h == k - 1, (h + 1)
: [] )
f k (h : t) = (h' == k - (toInteger $ length t), h'
: g h' r)
where h' = if c
then h + 1
else h
(c, r) = f k t
g v [] = []
g v (lH : lT) = if lH == k - (toInteger $ length lT)
then (v + 1) : (g (v + 1) lT)
else lH : lT
{-
Length m combinations x through x + c - 1 (c combinations starting with x)
in n variables.
-}
makeCombs :: Integer -> Integer -> Integer -> Integer -> [[Integer]]
makeCombs n m x c = genericTake c $ iterate (nextComb n) f
where f = nat2comb n m x
{-
Number of length m recombinations in n variables.
-}
numRecombs :: Integer -> Integer -> Integer
numRecombs n m = n & m
{-
Natural number corresponding to a recombination r in n variables.
-}
recomb2nat :: Integer -> [Integer] -> Integer
recomb2nat n r = f (m - 1) r
where m = toInteger $ length r
f 0 _ = (n & m)
- ((n - (head r)) & m)
f j (h1 : h2 : t) = ((n - h1) & j)
- ((n - h2) & j)
+ f (j - 1) (h2 : t)
{-
Length m recombination in n variables corresponding to a natural number x.
-}
nat2recomb :: Integer -> Integer -> Integer -> [Integer]
nat2recomb n m x = f 0 m x
where f _ 1 i = [i]
f p d i = j : f j (d - 1) (i' j)
where i' v = i
- (n & d)
+ ((n - v) & d)
+ (n & (d - 1))
- ((n - v) & (d - 1))
g v = ((i' v) >= 0)
&& ((i' v) < (n&(d-1)))
&& (v >= p)
j = head $ filter g [0 .. n - 1]
{-
Next recombination in n variables.
-}
nextRecomb :: Integer -> [Integer] -> [Integer]
nextRecomb n x = snd $ f n x
where f k (h : []) = (h == k - 1, (h + 1) : [])
f k (h : t) = (h' == k, h' : g h' r)
where h' = if c
then h + 1
else h
(c, r) = f k t
g v [] = []
g v (lH : lT) = if lH == k
then v : (g v lT)
else lH : lT
{-
Length m recombinations x through x + c - 1 (c recombinations starting with x)
in n variables.
-}
makeRecombs :: Integer -> Integer -> Integer -> Integer -> [[Integer]]
makeRecombs n m x c = genericTake c $ iterate (nextRecomb n) f
where f = nat2recomb n m x
{-
Number of length m permutations.
-}
numPerms :: Integer -> Integer
numPerms m = fac m
{-
Natural number corresponding to a factoradic f.
-}
fact2nat :: [Integer] -> Integer
fact2nat [] = 0
fact2nat (h : t) = h * (fac . toInteger $ length t) + (fact2nat t)
{-
Length m factoradic corresponding to a natural number x.
-}
nat2fact :: Integer -> Integer -> [Integer]
nat2fact 0 _ = []
nat2fact m x = (div x (fac (m - 1))) : nat2fact (m - 1) (mod x (fac (m - 1)))
{-
Natural number corresponding to a permutation p.
-}
perm2nat :: [Integer] -> Integer
perm2nat [] = 0
perm2nat p = fact2nat $ f' [0 .. (toInteger $ length p) - 1] p
where f' _ [] = []
f' l (h : t) = h' : f' l' t
where h' = (toInteger . fromJust) (findIndex (== h) l)
l' = delete h l
{-
Length m permutation corresponding to a natural number x.
-}
nat2perm :: Integer -> Integer -> [Integer]
nat2perm m x = f' [0 .. m - 1] (nat2fact m x)
where f' _ [] = []
f' l (h : t) = h' : f' l' t
where h' = genericIndex l h
l' = delete h' l
{-
Select elements from a list x based on indices in s.
-}
select :: [a] -> [Integer] -> [a]
select x s = map (genericIndex x) s
{-
Test functions for combinations, recombinations, and permutations.. Should
return a list of `True's. Use `and' to test for failure.
Note: these functions are not a good test of the speed of generation and
do not test next*.
-}
testCombs :: Integer -> Integer -> [Bool]
testCombs n m = map (\ (a, b) -> a == b) $ zip xs x's
where xs = [0 .. (numCombs n m) - 1]
cs = map (nat2comb n m) xs
x's = map (comb2nat n) cs
testRecombs :: Integer -> Integer -> [Bool]
testRecombs n m = map (\ (a, b) -> a == b) $ zip xs x's
where xs = [0 .. (numRecombs n m) - 1]
rs = map (nat2recomb n m) xs
x's = map (recomb2nat n) rs
testPerms :: Integer -> [Bool]
testPerms m = map (\ (a, b) -> a == b) $ zip xs x's
where xs = [0 .. (numPerms m) - 1]
ps = map (nat2perm m) xs
x's = map (perm2nat) ps
|
nblythe/MUB-Search
|
Combinadics.hs
|
Haskell
|
mit
| 9,472
|
module Akarui.FOL.PrettyPrint
( PrettyPrint(..)
) where
import qualified Data.Text as T
import Akarui.FOL.Symbols
class PrettyPrint t where
prettyPrint :: Symbols -> t -> T.Text
|
PhDP/Manticore
|
Akarui/FOL/PrettyPrint.hs
|
Haskell
|
apache-2.0
| 182
|
module Lambda.Deconstruct
(
-- * Convenient polymorphic deconstruction
app
, lam
, var
-- * Combinator
, (|>)
, (<!>)
-- ** From "Control.Applicative"
, Alternative
, (<|>)
)
where
import Control.Applicative
(
Alternative
, empty
, (<|>)
)
import Data.Maybe
(
fromMaybe
)
import Lambda.Term
-- | Deconstruct a lambda application.
app :: (Alternative m, Term t) => (t -> m a) -> (t -> m b) -> (t -> m (a, b))
app f g = unApp (\ x y -> (,) <$> f x <*> g y) (const empty)
-- | Deconstruct a lambda abstraction.
lam :: (Alternative m, Term t) => (String -> m a) -> (t -> m b) -> (t -> m (a, b))
lam f g = unLam (\ x y -> (,) <$> f x <*> g y) (const empty)
-- | Deconstruct a variable.
var :: (Alternative m, Term t) => t -> m String
var = unVar pure (const empty)
-- | Flipped '<$>' with the same precedence level but flipped fixity.
(|>) :: (Functor f) => f a -> (a -> b) -> f b
(|>) = flip (<$>)
infixr 4 |>
-- | Flipped 'fromMaybe' that has the same fixity as that of '<|>'.
(<!>) :: Maybe a -> a -> a
(<!>) = flip fromMaybe
infixl 3 <!>
|
edom/ptt
|
src/Lambda/Deconstruct.hs
|
Haskell
|
apache-2.0
| 1,138
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Openshift.V1.Handler where
import GHC.Generics
import Openshift.V1.ExecAction
import Openshift.V1.HTTPGetAction
import Openshift.V1.TCPSocketAction
import qualified Data.Aeson
-- | Handler defines a specific action that should be taken
data Handler = Handler
{ exec :: Maybe ExecAction -- ^ One and only one of the following should be specified. Exec specifies the action to take.
, httpGet :: Maybe HTTPGetAction -- ^ HTTPGet specifies the http request to perform.
, tcpSocket :: Maybe TCPSocketAction -- ^ TCPSocket specifies an action involving a TCP port. TCP hooks not yet supported
} deriving (Show, Eq, Generic)
instance Data.Aeson.FromJSON Handler
instance Data.Aeson.ToJSON Handler
|
minhdoboi/deprecated-openshift-haskell-api
|
openshift/lib/Openshift/V1/Handler.hs
|
Haskell
|
apache-2.0
| 889
|
module Helpers.Binary (lastBits, bitsList, splitBits) where
-- Number of partitions of the binary expansion of n into consecutive blocks with no leading zeroes.
-- 23 = 0b11011 -> [0, 0b1, 0b11, 0b011, 0b1011] = [0,1,3,3,11]
lastBits :: Int -> [Int]
lastBits n = recurse 0 n where
recurse _ 0 = []
recurse k n' = (n `mod` 2^k) : recurse (k + 1) (div n' 2)
bitsList :: Integer -> [Bool]
bitsList 0 = [False]
bitsList n = recurse n [] where
recurse n' b
| n' == 0 = b
| even n' = recurse (n' `div` 2) (False : b)
| odd n' = recurse (n' `div` 2) (True : b)
splitBits :: Int -> [(Int, Int)]
splitBits n = recurse 0 n where
recurse _ 0 = []
recurse k n' = (n `div` 2^k, n `mod` 2^k) : recurse (k + 1) (div n' 2)
|
peterokagey/haskellOEIS
|
src/Helpers/Binary.hs
|
Haskell
|
apache-2.0
| 733
|
-- |
-- Module : Text.Megaparsec.ByteString
-- Copyright : © 2015 Megaparsec contributors
-- © 2007 Paolo Martini
-- License : BSD3
--
-- Maintainer : Mark Karpov <markkarpov@opmbx.org>
-- Stability : experimental
-- Portability : portable
--
-- Convenience definitions for working with 'C.ByteString'.
module Text.Megaparsec.ByteString
( Parser
, parseFromFile )
where
import Text.Megaparsec.Error
import Text.Megaparsec.Prim
import qualified Data.ByteString.Char8 as C
-- | Different modules corresponding to various types of streams (@String@,
-- @Text@, @ByteString@) define it differently, so user can use “abstract”
-- @Parser@ type and easily change it by importing different “type
-- modules”. This one is for strict bytestrings.
type Parser = Parsec C.ByteString
-- | @parseFromFile p filePath@ runs a strict bytestring parser @p@ on the
-- input read from @filePath@ using 'ByteString.Char8.readFile'. Returns
-- either a 'ParseError' ('Left') or a value of type @a@ ('Right').
--
-- > main = do
-- > result <- parseFromFile numbers "digits.txt"
-- > case result of
-- > Left err -> print err
-- > Right xs -> print (sum xs)
parseFromFile :: Parser a -> String -> IO (Either ParseError a)
parseFromFile p fname = runParser p fname <$> C.readFile fname
|
neongreen/megaparsec
|
Text/Megaparsec/ByteString.hs
|
Haskell
|
bsd-2-clause
| 1,330
|
{-# LANGUAGE TypeFamilies, FlexibleInstances, FlexibleContexts,
DeriveDataTypeable, TypeSynonymInstances #-}
module HEP.ModelScan.MSSMScan.Model.MSUGRA where
import HEP.ModelScan.MSSMScan.Model
import qualified Data.ByteString.Lazy.Char8 as B
import Data.ByteString.Lex.Lazy.Double
instance Model MSUGRA where
data ModelInput MSUGRA = IMSUGRA (Double,Double,Double,Double)
parseInput oneline = let chunks = B.split ' ' oneline
a1:a2:a3:a4:[] = take 6 $ filter (not. B.null) chunks
m0 = maybe 0 fst $ readDouble a1
m12 = maybe 0 fst $ readDouble a2
a0 = maybe 0 fst $ readDouble a3
tanb = maybe 0 fst $ readDouble a4
in IMSUGRA (m0,m12,a0,tanb)
tanbeta (IMSUGRA (_,_,_,tanb)) = tanb
type InputMSUGRA = ModelInput MSUGRA
instance Show InputMSUGRA where
show (IMSUGRA (m0,m12,a0,tanb)) = "m0=" ++ show m0 ++ ", "
++ "m12=" ++ show m12 ++ ", "
++ "a0=" ++ show a0 ++ ", "
++ "tanb=" ++ show tanb
|
wavewave/MSSMScan
|
src/HEP/ModelScan/MSSMScan/Model/MSUGRA.hs
|
Haskell
|
bsd-2-clause
| 1,236
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ExtendedDefaultRules #-}
module Control.Monad.Shmonad.ExpressionSpec (main, spec, VStr(..), VInt(..)) where
import Test.Hspec
import Test.QuickCheck
import Control.Monad
import Control.Monad.Shmonad.Expression
import Control.Applicative ((<$>), (<*>))
import Data.Char (isDigit, chr)
import Data.Monoid ((<>))
import Data.Number.Nat
import qualified Data.Text.Lazy as L
default (L.Text)
randText :: Gen L.Text
randText = sized $ \n ->
do k <- choose (0, n)
L.pack <$> vectorOf k validChars
where validChars = chr <$> choose (32, 126)
instance Arbitrary L.Text where
arbitrary = randText
instance Arbitrary Name where
arbitrary = toName <$> randText `suchThat` isValidName
instance Arbitrary Nat where
arbitrary = do
NonNegative x <- arbitrary :: Gen (NonNegative Integer)
return $ toNat x
instance Variable a => Arbitrary (VarID a) where
arbitrary = VarID <$> arbitrary <*> arbitrary
newtype VStr = VStr (Expr Str)
instance Arbitrary VStr where
arbitrary = VStr <$> Var <$> arbitrary
newtype VInt = VInt (Expr Integer)
instance Arbitrary VInt where
arbitrary = VInt <$> Var <$> arbitrary
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
variableSpec
expressionSpec
redirectSpec
variableSpec :: Spec
variableSpec = do
describe "A Name" $ do
it "must be non-empty" $
"" `shouldSatisfy` not . isValidName
it "must be non-empty (QC)" $ property $
\(Blind x) -> not . L.null $ fromName x
it "must not start with a digit" $ property $
\str -> not (L.null str) && isDigit (L.head str) ==>
not (isValidName str)
it "can only contain letters, digits and underscores" $ property $
\(Blind x) -> isValidName $ fromName x
let var :: (VarID Integer)
var = VarID (Just 0) "hello"
describe "A VarID" $ do
it "has a unique numerical ID and a name" $ do
varID var `shouldBe` Just 0
let n = toName "hello"
varName var `shouldBe` n
it "has an associated type" $ do
let var2 :: (VarID Str)
var2 = VarID (Just 1) "world"
varID var2 `shouldBe` Just 1
-- because of phantom type var, impossible to write:
-- var2 `shouldSatisfy` (/=) var
describe "The Variable typeclass" $ do
it "should turn a VarID into a unique name" $ do
let n = toName "hello0"
uniqueName var `shouldBe` n
it "should produce a unique name that is a valid shell name" $ property $
\(Blind (VStr (Var x))) -> isValidName . fromName $ uniqueName x
expressionSpec :: Spec
expressionSpec =
describe "An Expr" $ do
describe "Lit a" $
it "should have a single value" $ do
let l :: Expr Integer
l = Lit 1
shExpr l `shouldBe` "1"
describe "Var a" $
it "turns a VarID into an expression" $ do
let var :: Expr Str
var = Var (VarID (Just 2) "foo")
shExpr var `shouldBe` "${foo2}"
describe "Plus" $
it "adds two Expr Integers" $ do
let int1 = Lit 1
let int2 = Lit 2
let sumInts = Plus int1 int2
shExpr sumInts `shouldBe` "$((1+2))"
describe "Concat" $
it "concatenates two Expr Strs" $ do
let str1 = quote "Hello, "
let str2 = quote "world!"
let str = str1 <> str2
shExpr str `shouldBe` "\"Hello, \"\"world!\""
describe "Shown" $
it "turns an Expr a with Show a into Expr Str" $ do
let l :: Expr Integer
l = Lit 1
let s = Shown l
shExpr s `shouldBe` "1"
describe "StrEquals" $ do
it "checks whether two strings are equal" $ do
let l1 = quote ""
let l2 = quote "hi"
let eqs = l1 .==. l2
shExpr eqs `shouldBe` "[ \"\" = \"hi\" ]"
it "checks whether two strings are not equal" $ do
let l1 = quote ""
let l2 = quote "hi"
let ne = l1 ./=. l2
shExpr ne `shouldBe` "! [ \"\" = \"hi\" ]"
describe "NumCompare" $ do
let n1 = Lit (0 :: Integer)
let n2 = Lit 1
it "checks whether two numbers are equal" $ do
let eq = n1 .==. n2
shExpr eq `shouldBe` "[ 0 -eq 1 ]"
it "checks whether two numbers are not equal" $ do
let eq = n1 ./=. n2
shExpr eq `shouldBe` "! [ 0 -eq 1 ]"
it "checks whether one numbers is less than another" $ do
let lt = n1 .<. n2
shExpr lt `shouldBe` "[ 0 -lt 1 ]"
it "checks whether one number is less than or equal to another" $ do
let le = n1 .<=. n2
shExpr le `shouldBe` "[ 0 -le 1 ]"
it "checks whether one number is greater than another" $ do
let gt = n1 .>. n2
shExpr gt `shouldBe` "[ 0 -gt 1 ]"
it "checks whether one number is greater than or equal to another" $ do
let ge = n1 .>=. n2
shExpr ge `shouldBe` "[ 0 -ge 1 ]"
redirectSpec :: Spec
redirectSpec =
describe "A Redirect" $ do
it "can map a file descriptor to a file" $ do
let r = redirToStr (toFile (path "/tmp/blah"))
shExpr r `shouldBe` "> \"/tmp/blah\""
it "can map a file descriptor to a file for append" $ do
let r = redirToStr (appendToFile (path "/tmp/blah"))
shExpr r `shouldBe` ">> \"/tmp/blah\""
it "can map a file descriptor to a different file descriptor" $ do
let r = redirToStr stderrToStdout
shExpr r `shouldBe` "2>&1"
it "can send a file to stdin" $ do
let inputFile = fromFile (path "/test")
let r = redirToStr inputFile
shExpr r `shouldBe` "< \"/test\""
|
corajr/shmonad
|
test/Control/Monad/Shmonad/ExpressionSpec.hs
|
Haskell
|
bsd-2-clause
| 5,547
|
module AERN2.PPoly.Eval where
import MixedTypesNumPrelude
import qualified AERN2.Poly.Cheb as Cheb hiding (evalDf)
import AERN2.Poly.Cheb (ChPoly)
import qualified AERN2.Poly.Cheb.Eval as ChE (evalDirect, evalDf, evalLDf)
import AERN2.PPoly.Type
import AERN2.MP.Ball
import AERN2.Poly.Ball
import AERN2.Interval
import Data.List
import AERN2.RealFun.Operations
import Debug.Trace
evalDirect :: PPoly -> MPBall -> MPBall
evalDirect (PPoly ps dom) x =
foldl1' hullMPBall $
map (\(_,f) -> ChE.evalDirect f xI) intersectingPieces
where
xI = (Cheb.fromDomToUnitInterval dom x)
xAsInterval = dyadicInterval xI
intersectingPieces =
filter (\p -> (fst p) `intersects` xAsInterval) ps
evalDirectWithAccuracy :: Accuracy -> PPoly -> MPBall -> MPBall
evalDirectWithAccuracy bts (PPoly ps dom) x =
foldl1' hullMPBall $
map (\(_,f) -> Cheb.evalDirectWithAccuracy bts f xI) intersectingPieces
where
xI = (Cheb.fromDomToUnitInterval dom x)
xAsInterval = dyadicInterval xI
intersectingPieces =
filter (\p -> (fst p) `intersects` xAsInterval) ps
evalDf :: PPoly -> [ChPoly MPBall] -> MPBall -> MPBall
evalDf (PPoly ps dom) fs' x =
foldl1' hullMPBall $
map (\((_, f), f') -> (ChE.evalDf f f' xI)) intersectingPieces
where
xI = (Cheb.fromDomToUnitInterval dom x)
xAsInterval = dyadicInterval xI
intersectingPieces =
filter (\p -> fst (fst p) `intersects` xAsInterval) $ zip ps fs'
evalLDf :: PPoly -> [ChPoly MPBall] -> MPBall -> MPBall
evalLDf (PPoly ps dom) fs' x =
foldl1' hullMPBall $
map (\((_, f), f') -> (ChE.evalLDf f f' xI)) intersectingPieces
where
xI = (Cheb.fromDomToUnitInterval dom x)
xAsInterval = dyadicInterval (Cheb.fromDomToUnitInterval dom xI)
intersectingPieces =
filter (\p -> fst (fst p) `intersects` xAsInterval) $ zip ps fs'
evalDI :: PPoly -> MPBall -> MPBall
evalDI f@(PPoly ps dom) x =
evalDf f dfs x
where
(Interval l r) = dom
c = 1/!(0.5*(r - l))
dfs = map ((c *) . Cheb.derivative . snd) ps
instance
CanApply PPoly MPBall where
type ApplyType PPoly MPBall = MPBall
apply p x =
case getAccuracy x of
Exact -> evalDirect p x
_ -> evalDI p x
instance
CanApply PPoly (CN MPBall) where
type ApplyType PPoly (CN MPBall) = CN MPBall
apply p x =
-- TODO: check x is in the domain
apply p <$> x
instance CanApplyApprox PPoly DyadicInterval where
type ApplyApproxType PPoly DyadicInterval = DyadicInterval
applyApprox p di =
dyadicInterval (fromEndpointsAsIntervals lB uB)
where
(Interval lB uB) = sampledRange di 5 p :: Interval MPBall MPBall
|
michalkonecny/aern2
|
aern2-fun-univariate/src/AERN2/PPoly/Eval.hs
|
Haskell
|
bsd-3-clause
| 2,584
|
{-# LANGUAGE
DeriveDataTypeable
, DeriveFunctor
, DeriveFoldable
, DeriveTraversable
#-}
module Language.TNT.Location
( Point (..)
, Location (..)
, Located (..)
) where
import Control.Comonad
import Data.Data
import Data.Foldable
import Data.Functor.Apply
import Data.Semigroup
import Data.Traversable
data Point = Point Int Int deriving (Show, Eq, Ord, Data, Typeable)
data Location = Location Point Point deriving (Show, Data, Typeable)
data Located a = Locate Location a deriving ( Show
, Functor
, Foldable
, Traversable
, Data
, Typeable
)
instance Semigroup Location where
Location a b <> Location c d = Location (min a c) (max b d)
instance Extend Located where
duplicate w@(Locate x _) = Locate x w
extend f w@(Locate x _) = Locate x (f w)
instance Comonad Located where
extract (Locate _ a) = a
instance Apply Located where
Locate x f <.> Locate y a = Locate (x <> y) (f a)
|
sonyandy/tnt
|
Language/TNT/Location.hs
|
Haskell
|
bsd-3-clause
| 1,206
|
-----------------------------------------------------------------------------
-- |
-- Module : Data.Group.Combinators
-- Copyright : (c) Edward Kmett 2009
-- License : BSD-style
-- Maintainer : ekmett@gmail.com
-- Stability : experimental
-- Portability : portable
--
-- Utilities for working with Groups that conflict with names from the "Prelude".
--
-- Intended to be imported qualified.
--
-- > import Data.Group.Combinators as Group (replicate)
--
-----------------------------------------------------------------------------
module Data.Group.Combinators
( replicate
) where
import Prelude hiding (replicate)
import Data.Monoid (mappend, mempty)
import Data.Group
-- shamelessly stolen from Lennart Augustsson's post:
-- http://augustss.blogspot.com/2008/07/lost-and-found-if-i-write-108-in.html
-- adapted to groups, which can permit negative exponents
replicate :: (Group m, Integral n) => m -> n -> m
replicate x0 y0
| y0 < 0 = f (gnegate x0) (negate y0)
| y0 == 0 = mempty
| otherwise = f x0 y0
where
f x y
| even y = f (x `mappend` x) (y `quot` 2)
| y == 1 = x
| otherwise = g (x `mappend` x) ((y - 1) `quot` 2) x
g x y z
| even y = g (x `mappend` x) (y `quot` 2) z
| y == 1 = x `mappend` z
| otherwise = g (x `mappend` x) ((y - 1) `quot` 2) (x `mappend` z)
|
ekmett/monoids
|
Data/Group/Combinators.hs
|
Haskell
|
bsd-3-clause
| 1,410
|
{-# LANGUAGE GADTs #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Language.SynArrow where
import Prelude hiding ((.),id,init)
import Control.Category
import Control.Arrow hiding (second)
-- | The AST of arrow syntax
data SynArrow i a b c where
Arr :: a b c -> SynArrow i a b c
First :: SynArrow i a b c -> SynArrow i a (b,d) (c,d)
Compose :: SynArrow i a b c -> SynArrow i a c d -> SynArrow i a b d
Init :: i b -> SynArrow i a b b
Loop :: SynArrow i a (b,d) (c,d) -> SynArrow i a b c
LoopD :: i d -> a (b,d) (c,d) -> SynArrow i a b c
--second :: Optimizable a => SynArrow i a b c -> SynArrow i a (d,b) (d,c)
--second f = Arr swap >>> First f >>> Arr swap
instance Show (SynArrow i a b c) where
showsPrec d e = case e of
(Arr _) -> showParen (d > app_prec)
$ showString "arr _"
(First f) -> showParen (d > app_prec)
$ showString "first "
. showsPrec (app_prec+1) f
(Compose f g) -> showParen (d > compose_prec)
$ showsPrec (compose_prec+1) f
. showString " >>> "
. showsPrec (d+1) g
(Init _) -> showParen (d > app_prec)
$ showString "init _"
(LoopD _ _) -> showParen (d > app_prec)
$ showString "loopD _ _"
(Loop f) -> showParen (d > app_prec)
$ showString "loop "
. showsPrec (app_prec+1) f
where app_prec = 10
compose_prec = 1
instance Category a => Category (SynArrow i a) where
id = Arr id
f . g = Compose g f
instance Arrow a => Arrow (SynArrow i a) where
arr = Arr . arr
first = First
class Category a => SemiArrow a where
swap :: a (b,c) (c,b)
assoc1 :: a ((x,y),z) (x,(y,z))
assoc2 :: a (x,(y,z)) ((x,y),z)
(><) :: a b c -> a b' c' -> a (b,b') (c,c')
dup :: a b (b,b)
instance SemiArrow (->) where
swap (x,y) = (y,x)
assoc1 ((x,y),z) = (x,(y,z))
assoc2 (x,(y,z)) = ((x,y),z)
(><) = (***)
dup a = (a,a)
class Product m where
unit :: m ()
inj :: m a -> m b -> m (a,b)
fix :: m a
optimize :: (SemiArrow a, Product i) => SynArrow i a b c -> SynArrow i a b c
optimize a0 =
case a0 of
normal@(Arr _) -> normal
normal@(LoopD _ _) -> normal
(Init i) -> LoopD i swap
(First f) -> single (First (optimize f))
(Compose f g) -> single (Compose (optimize f) (optimize g))
(Loop f) -> single (Loop (optimize f))
where
single :: (SemiArrow a, Product i) => SynArrow i a b c -> SynArrow i a b c
single b0 =
case b0 of
-- composition
Compose (Arr f) (Arr g) -> Arr (f >>> g)
-- left tightening
Compose (Arr f) (LoopD i g) -> LoopD i ((f >< id) >>> g)
-- right tightening
Compose (LoopD i f) (Arr g) -> LoopD i (f >>> (g >< id))
-- sequencing
Compose (LoopD i f) (LoopD j g) ->
LoopD (inj i j) $ assoc' (juggle' (g >< id) . (f >< id))
-- extension
First (Arr f) -> Arr (f >< id)
-- superposing
First (LoopD i f) -> LoopD i (juggle' (f >< id))
-- loop-extension
Loop (Arr f) -> LoopD fix f
-- vanishing
Loop (LoopD i f) -> LoopD (inj fix i) (assoc' f)
a -> a
assoc' f = assoc2 >>> f >>> assoc1
juggle' f = juggle >>> f >>> juggle
juggle :: SemiArrow a => a ((b,c),d) ((b,d),c)
juggle = assoc2 <<< (id >< swap) <<< assoc1
|
svenkeidel/hsynth
|
src/Language/SynArrow.hs
|
Haskell
|
bsd-3-clause
| 3,579
|
{-|
Copyright : (c) Dave Laing, 2017
License : BSD3
Maintainer : dave.laing.80@gmail.com
Stability : experimental
Portability : non-portable
-}
{-# LANGUAGE ConstraintKinds #-}
module Fragment.Tuple.Rules.Type (
TupleNormalizeConstraint
, tupleNormalizeRules
) where
import Control.Lens (review, preview)
import Rules.Type
import Ast.Type
import Fragment.Tuple.Ast.Type
type TupleNormalizeConstraint ki ty a = AsTyTuple ki ty
normalizeTuple :: TupleNormalizeConstraint ki ty a
=> (Type ki ty a -> Type ki ty a)
-> Type ki ty a
-> Maybe (Type ki ty a)
normalizeTuple normalizeFn ty = do
tys <- preview _TyTuple ty
return $ review _TyTuple (fmap normalizeFn tys)
tupleNormalizeRules :: TupleNormalizeConstraint ki ty a
=> NormalizeInput ki ty a
tupleNormalizeRules =
NormalizeInput [ NormalizeTypeRecurse normalizeTuple ]
|
dalaing/type-systems
|
src/Fragment/Tuple/Rules/Type.hs
|
Haskell
|
bsd-3-clause
| 914
|
-----------------------------------------------------------------------------
-- |
-- Module : Data.SBV.Examples.Uninterpreted.Function
-- Copyright : (c) Levent Erkok
-- License : BSD3
-- Maintainer : erkokl@gmail.com
-- Stability : experimental
--
-- Demonstrates function counter-examples
-----------------------------------------------------------------------------
module Data.SBV.Examples.Uninterpreted.Function where
import Data.SBV
-- | An uninterpreted function
f :: SWord8 -> SWord8 -> SWord16
f = uninterpret "f"
-- | Asserts that @f x z == f (y+2) z@ whenever @x == y+2@. Naturally correct:
--
-- >>> prove thmGood
-- Q.E.D.
thmGood :: SWord8 -> SWord8 -> SWord8 -> SBool
thmGood x y z = x .== y+2 ==> f x z .== f (y + 2) z
|
josefs/sbv
|
Data/SBV/Examples/Uninterpreted/Function.hs
|
Haskell
|
bsd-3-clause
| 759
|
{-# LANGUAGE OverloadedStrings #-}
module Main where
import CMark (Node(..))
import Data.Maybe (fromMaybe)
import Data.Monoid ((<>))
import Data.Morgue.Agenda
import Data.Morgue.Agenda.Types
import Data.Text (Text, pack, stripSuffix)
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import System.Environment (getArgs)
-- | generate indent
indent :: Int -> Text
indent k = T.replicate k " "
-- | dump a markdown AST
dump :: Int -> Node -> Text
dump k (Node _ nType ns) =
indent k <> pack (show nType) <> "\n" <> mconcat (map (dump (k + 1)) ns)
-- | dump our own, agenda specific AST
dumpOwn :: Int -> AgendaTree -> Text
dumpOwn k (AgendaTree t []) = indent k <> "elem: " <> repr t <> "\n"
dumpOwn k (AgendaTree t ns) =
indent k <> "elem: " <> repr t <> "\n" <> mconcat (map (dumpOwn (k + 1)) ns)
-- | render an `AgendaElement`
repr :: AgendaElement -> Text
repr (Elem d (Just todo) _ _)
| todo = "[ ] " <> (stripNewline . T.unlines) d
| otherwise = "[x] " <> (stripNewline . T.unlines) d
repr (Elem d Nothing _ _) = (stripNewline . T.unlines) d
-- | strip the trailing newline from a `Text`, if there is any
stripNewline :: Text -> Text
stripNewline = fromMaybe <$> id <*> stripSuffix "\n"
-- | get a file name from the command line
getFileName :: IO FilePath
getFileName = do
args <- getArgs
case args of
f : _ -> return f
_ -> error "no file specified"
-- | glue everything together (we use the guarantee that our tree dump ends with a newline)
main :: IO ()
main = getFileName >>= TIO.readFile >>=
mapM_ (TIO.putStr . dumpOwn 0) . getAgendaTree
|
ibabushkin/morgue
|
app/Dump.hs
|
Haskell
|
bsd-3-clause
| 1,619
|
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.IBM.VertexArrayLists
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/IBM/vertex_array_lists.txt IBM_vertex_array_lists> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.IBM.VertexArrayLists (
-- * Enums
gl_COLOR_ARRAY_LIST_IBM,
gl_COLOR_ARRAY_LIST_STRIDE_IBM,
gl_EDGE_FLAG_ARRAY_LIST_IBM,
gl_EDGE_FLAG_ARRAY_LIST_STRIDE_IBM,
gl_FOG_COORDINATE_ARRAY_LIST_IBM,
gl_FOG_COORDINATE_ARRAY_LIST_STRIDE_IBM,
gl_INDEX_ARRAY_LIST_IBM,
gl_INDEX_ARRAY_LIST_STRIDE_IBM,
gl_NORMAL_ARRAY_LIST_IBM,
gl_NORMAL_ARRAY_LIST_STRIDE_IBM,
gl_SECONDARY_COLOR_ARRAY_LIST_IBM,
gl_SECONDARY_COLOR_ARRAY_LIST_STRIDE_IBM,
gl_TEXTURE_COORD_ARRAY_LIST_IBM,
gl_TEXTURE_COORD_ARRAY_LIST_STRIDE_IBM,
gl_VERTEX_ARRAY_LIST_IBM,
gl_VERTEX_ARRAY_LIST_STRIDE_IBM,
-- * Functions
glColorPointerListIBM,
glEdgeFlagPointerListIBM,
glFogCoordPointerListIBM,
glIndexPointerListIBM,
glNormalPointerListIBM,
glSecondaryColorPointerListIBM,
glTexCoordPointerListIBM,
glVertexPointerListIBM
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
import Graphics.Rendering.OpenGL.Raw.Functions
|
phaazon/OpenGLRaw
|
src/Graphics/Rendering/OpenGL/Raw/IBM/VertexArrayLists.hs
|
Haskell
|
bsd-3-clause
| 1,481
|
{-# LANGUAGE TypeFamilies #-}
module LOGL.Internal.Shader
(
)
where
import Graphics.GLUtil
import LOGL.Internal.Resource
instance Resource ShaderProgram where
type LoadParam ShaderProgram = (String, FilePath, FilePath)
load (name, vfile, ffile) = do
shader <- simpleShaderProgram vfile ffile
return (name, shader)
delete prg = return ()
|
atwupack/LearnOpenGL
|
src/LOGL/Internal/Shader.hs
|
Haskell
|
bsd-3-clause
| 368
|
-------------------------------------------------------------------------------
---- |
---- Module : Parser
---- Copyright : (c) Syoyo Fujita
---- License : BSD-style
----
---- Maintainer : syoyo@lighttransport.com
---- Stability : experimental
---- Portability : GHC 6.10
----
---- Parser : A parser for LLL.
----
-------------------------------------------------------------------------------
{-# LANGUAGE DeriveDataTypeable #-}
module LLL.Parser where
import Text.ParserCombinators.Parsec
import qualified Text.ParserCombinators.Parsec.Token as P
import Text.ParserCombinators.Parsec.Expr
import Text.ParserCombinators.Parsec.Language
import Text.ParserCombinators.Parsec.Error
import Control.Monad.State
import Debug.Trace
import LLL.AST
-- | LLL parser state
data LLLState = LLLState { symbolTable :: SymbolTable
, n :: Int
}
-- | LLL parser having LLL parser state
type LLLParser a = GenParser Char LLLState a
-- | Initial state of shader env.
-- Builtin variables are added in global scope.
initLLLState :: LLLState
initLLLState = LLLState {
symbolTable = [("global", [])]
, n = 0
}
-- | Push scope into the symbol table
pushScope :: String -> [Symbol] -> LLLState -> LLLState
pushScope scope xs st =
st { symbolTable = newTable }
where
-- Add new scope to the first elem of the list.
newTable = [(scope, xs)] ++ (symbolTable st)
-- | Pop scope from the symbol table
popScope :: LLLState -> LLLState
popScope st =
st { symbolTable = newTable }
where
-- Pop first scope from the scope chain
newTable = tail (symbolTable st)
-- | Add the symbol to the first scope in the symbol list.
-- TODO: Check duplication of the symbol.
addSymbol :: Symbol -> LLLState -> LLLState
addSymbol sym st = trace ("// Add " ++ (show sym)) $
st { symbolTable = newTable }
where
newTable = case (symbolTable st) of
[(scope, xs)] -> [(scope, [sym] ++ xs)]
((scope, xs):xxs) -> [(scope, [sym] ++ xs)] ++ xxs
--
-- Topmost parsing rule
--
program :: LLLParser LLLUnit
program = do { ast <- many (spaces >> global)
; return ast
}
<?> "shader program"
global :: LLLParser Func
global = functionDefinition
<?> "top level definition"
functionDefinition ::LLLParser Func
functionDefinition = do { ty <- option (TyVoid) funType
; name <- identifier
; symbol "("
; symbol ")"
-- push scope
; updateState (pushScope name [])
; symbol "{"
; symbol "}"
-- pop scope
; updateState (popScope)
-- Add user function to global scope.
; -- updateState (addSymbol $ mkFunSym name ty (extractTysFromDecls decls))
; return (ShaderFunc ty name)
}
<?> "function definition"
funType = (reserved "void" >> return TyVoid)
--
-- Parse error reporting routines
--
offt :: Int -> String
offt n = replicate n ' '
showLine :: SourceName -> Int -> Int -> IO ()
showLine name n m =
do input <- readFile name
if (length (lines input)) < n
then
if length (lines input) == 0
then putStrLn ""
else
do { putStrLn $ (lines input) !! ((length (lines input)) - 1)
; putStrLn ""
; putStrLn $ ((offt (m-1)) ++ "^")
}
else
do { let l = (lines input) !! (n-1)
; putStrLn l
; putStrLn $ ((offt (m-1)) ++ "^")
}
--
-- Parser interface
--
parseLLLFromFile :: LLLParser a -> SourceName -> IO (Either ParseError a)
parseLLLFromFile p fname =
do { input <- readFile fname
; return (runParser p initLLLState fname input)
}
--
-- Same as in Error.hs of Parsec, just replaced to show error line.
--
showErrorMsg :: ParseError -> FilePath -> String
showErrorMsg err fname =
show (setSourceName (errorPos err) fname) ++ ":" ++
showErrorMessages "or" "unknown parse error"
"expecting" "unexpected" "end of input"
(errorMessages err)
mkMyError :: ParseError -> FilePath -> ParseError
mkMyError err fname = setErrorPos (setSourceName (errorPos err) fname) err
run :: LLLParser LLLUnit -> FilePath -> FilePath -> (LLLUnit -> IO ()) -> IO ()
run p prepname name proc =
do { result <- parseLLLFromFile p prepname
; case (result) of
Left err -> do { -- Parse preprocessed file, but print original file
-- when reporting error.
putStrLn "Parse err:"
; showLine name (sourceLine (errorPos err)) (sourceColumn (errorPos err))
; print (mkMyError err name)
}
Right x -> do { proc x
}
}
runLex :: LLLParser LLLUnit -> FilePath -> FilePath -> (LLLUnit -> IO ()) -> IO ()
runLex p prepname name proc =
run (do { whiteSpace
; x <- p
; eof
; return x
}
) prepname name proc
--
-- Useful parsing tools
--
lexer = P.makeTokenParser rslStyle
whiteSpace = P.whiteSpace lexer
lexeme = P.lexeme lexer
symbol = P.symbol lexer
natural = P.natural lexer
naturalOrFloat = P.naturalOrFloat lexer
stringLiteral = P.stringLiteral lexer
float = P.float lexer
parens = P.parens lexer
braces = P.braces lexer
semi = P.semi lexer
commaSep = P.commaSep lexer
identifier = P.identifier lexer
reserved = P.reserved lexer
reservedOp = P.reservedOp lexer
{-
expr :: LLLParser Expr
expr = buildExpressionParser table primary
<?> "expression"
primary = try (parens expr)
<|> triple
<|> try varRef
<|> procedureCall -- Do I really need "try"?
-- <|> procedureCall -- Do I really need "try"?
<|> number
<|> constString
<?> "primary"
table = [
-- typecast
[typecast]
-- unary
, [prefix "-" OpSub, prefix "!" OpNeg]
-- binop
, [binOp "." OpDot AssocLeft]
, [binOp "*" OpMul AssocLeft, binOp "/" OpDiv AssocLeft]
, [binOp "+" OpAdd AssocLeft, binOp "-" OpSub AssocLeft]
-- relop
, [binOp ">" OpGt AssocLeft, binOp ">=" OpGe AssocLeft]
, [binOp "<" OpLt AssocLeft, binOp "<=" OpLe AssocLeft]
, [binOp "==" OpEq AssocLeft, binOp "!=" OpNeq AssocLeft]
-- logop
, [binOp "&&" OpAnd AssocLeft, binOp "||" OpOr AssocLeft]
-- a ? b : c
, [conditional]
-- assign
, [ assignOp "=" OpAssign AssocRight
, assignOp "+=" OpAddAssign AssocRight
, assignOp "-=" OpSubAssign AssocRight
, assignOp "*=" OpMulAssign AssocRight
, assignOp "/=" OpDivAssign AssocRight
]
]
where
typecast
= Prefix ( do { ty <- rslType
; spacety <- option "" stringLiteral
; return (\e -> TypeCast Nothing ty spacety e)
} <?> "typecast" )
prefix name f
= Prefix ( do { reservedOp name
; return (\x -> UnaryOp Nothing f x)
} )
binOp name f assoc
= Infix ( do { reservedOp name
; return (\x y -> BinOp Nothing f x y)
} ) assoc
conditional
= Infix ( do { reservedOp "?"
; thenExpr <- expr
; reservedOp ":"
; return (\condExpr elseExpr -> Conditional Nothing condExpr thenExpr elseExpr)
} <?> "conditional" ) AssocRight
assignOp name f assoc
= Infix ( do { state <- getState
; reservedOp name
; return (\x y -> mkAssign f x y)
} <?> "assign" ) assoc
-- Make Assign node with flattening expression.
mkAssign :: Op -> Expr -> Expr -> Expr
mkAssign op x y = case op of
OpAssign -> Assign Nothing OpAssign x y
OpAddAssign -> Assign Nothing OpAssign x (BinOp Nothing OpAdd x y)
OpSubAssign -> Assign Nothing OpAssign x (BinOp Nothing OpSub x y)
OpMulAssign -> Assign Nothing OpAssign x (BinOp Nothing OpMul x y)
OpDivAssign -> Assign Nothing OpAssign x (BinOp Nothing OpDiv x y)
-}
rslStyle = javaStyle
{ reservedNames = [ "const"
, "break", "continue"
, "while", "if", "for", "solar", "illuminate", "illuminance"
, "surface", "volume", "displacement", "imager"
, "varying", "uniform", "facevarygin", "facevertex"
, "output"
, "extern"
, "return"
, "color", "vector", "normal", "matrix", "point", "void"
-- LLL 2.0
, "public", "class", "struct"
-- More is TODO
]
, reservedOpNames = ["+", "-", "*", "/"] -- More is TODO
, caseSensitive = True
, commentStart = "/*"
, commentEnd = "*/"
, commentLine = "//"
, nestedComments = True
}
|
syoyo/LLL
|
LLL/Parser.hs
|
Haskell
|
bsd-3-clause
| 10,335
|
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE OverlappingInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE DeriveGeneric #-}
module Forml.Types.Namespace where
import Language.Javascript.JMacro
import Control.Applicative
import Text.Parsec hiding ((<|>), State, many, spaces, parse, label)
import Data.Monoid
import qualified Data.List as L
import Data.Serialize
import GHC.Generics
import Forml.Parser.Utils
import Forml.Javascript.Utils
import Prelude hiding (curry, (++))
newtype Namespace = Namespace [String] deriving (Eq, Ord, Generic)
instance Serialize Namespace
instance Monoid Namespace where
mempty = Namespace []
mappend (Namespace x) (Namespace y) = Namespace (x ++ y)
instance Show Namespace where
show (Namespace []) = "global"
show (Namespace x) = concat $ L.intersperse "." x
instance Syntax Namespace where
syntax = Namespace <$> (many1 (lower <|> char '_') `sepBy1` char '.')
instance ToJExpr Namespace where
toJExpr (Namespace []) = [jmacroE| (typeof global == "undefined" ? window : global) |]
toJExpr (Namespace (end -> x : xs)) = [jmacroE| `(Namespace xs)`["$" ++ `(x)`] |]
data Module = Module Namespace [Module]
| Var String
instance Show Module where
show (Module (Namespace (reverse -> (x:_))) _) = x
show (Var s) = s
|
texodus/forml
|
src/hs/lib/Forml/Types/Namespace.hs
|
Haskell
|
bsd-3-clause
| 1,574
|
-- (c) 1999-2005 by Martin Erwig [see file COPYRIGHT]
-- | Static and Dynamic Inductive Graphs
module Data.Graph.Inductive.Graph (
-- * General Type Defintions
-- ** Node and Edge Types
Node,LNode,UNode,
Edge,LEdge,UEdge,
-- ** Types Supporting Inductive Graph View
Adj,Context,MContext,Decomp,GDecomp,UDecomp,
Path,LPath(..),UPath,
-- * Graph Type Classes
-- | We define two graph classes:
--
-- Graph: static, decomposable graphs.
-- Static means that a graph itself cannot be changed
--
-- DynGraph: dynamic, extensible graphs.
-- Dynamic graphs inherit all operations from static graphs
-- but also offer operations to extend and change graphs.
--
-- Each class contains in addition to its essential operations those
-- derived operations that might be overwritten by a more efficient
-- implementation in an instance definition.
--
-- Note that labNodes is essentially needed because the default definition
-- for matchAny is based on it: we need some node from the graph to define
-- matchAny in terms of match. Alternatively, we could have made matchAny
-- essential and have labNodes defined in terms of ufold and matchAny.
-- However, in general, labNodes seems to be (at least) as easy to define
-- as matchAny. We have chosen labNodes instead of the function nodes since
-- nodes can be easily derived from labNodes, but not vice versa.
Graph(..),
DynGraph(..),
-- * Operations
-- ** Graph Folds and Maps
ufold,gmap,nmap,emap,
-- ** Graph Projection
nodes,edges,newNodes,gelem,
-- ** Graph Construction and Destruction
insNode,insEdge,delNode,delEdge,delLEdge,
insNodes,insEdges,delNodes,delEdges,
buildGr,mkUGraph,
-- ** Graph Inspection
context,lab,neighbors,
suc,pre,lsuc,lpre,
out,inn,outdeg,indeg,deg,
equal,
-- ** Context Inspection
node',lab',labNode',neighbors',
suc',pre',lpre',lsuc',
out',inn',outdeg',indeg',deg',
) where
import Data.List (sortBy)
{- Signatures:
-- basic operations
empty :: Graph gr => gr a b
isEmpty :: Graph gr => gr a b -> Bool
match :: Graph gr => Node -> gr a b -> Decomp gr a b
mkGraph :: Graph gr => [LNode a] -> [LEdge b] -> gr a b
(&) :: DynGraph gr => Context a b -> gr a b -> gr a b
-- graph folds and maps
ufold :: Graph gr => ((Context a b) -> c -> c) -> c -> gr a b -> c
gmap :: Graph gr => (Context a b -> Context c d) -> gr a b -> gr c d
nmap :: Graph gr => (a -> c) -> gr a b -> gr c b
emap :: Graph gr => (b -> c) -> gr a b -> gr a c
-- graph projection
matchAny :: Graph gr => gr a b -> GDecomp g a b
nodes :: Graph gr => gr a b -> [Node]
edges :: Graph gr => gr a b -> [Edge]
labNodes :: Graph gr => gr a b -> [LNode a]
labEdges :: Graph gr => gr a b -> [LEdge b]
newNodes :: Graph gr => Int -> gr a b -> [Node]
noNodes :: Graph gr => gr a b -> Int
nodeRange :: Graph gr => gr a b -> (Node,Node)
gelem :: Graph gr => Node -> gr a b -> Bool
-- graph construction & destruction
insNode :: DynGraph gr => LNode a -> gr a b -> gr a b
insEdge :: DynGraph gr => LEdge b -> gr a b -> gr a b
delNode :: Graph gr => Node -> gr a b -> gr a b
delEdge :: DynGraph gr => Edge -> gr a b -> gr a b
delLEdge :: (DynGraph gr, Eq b) =>
LEdge b -> gr a b -> gr a b
insNodes :: DynGraph gr => [LNode a] -> gr a b -> gr a b
insEdges :: DynGraph gr => [LEdge b] -> gr a b -> gr a b
delNodes :: Graph gr => [Node] -> gr a b -> gr a b
delEdges :: DynGraph gr => [Edge] -> gr a b -> gr a b
buildGr :: DynGraph gr => [Context a b] -> gr a b
mkUGraph :: DynGraph gr => [Node] -> [Edge] -> gr () ()
-- graph inspection
context :: Graph gr => gr a b -> Node -> Context a b
lab :: Graph gr => gr a b -> Node -> Maybe a
neighbors :: Graph gr => gr a b -> Node -> [Node]
suc :: Graph gr => gr a b -> Node -> [Node]
pre :: Graph gr => gr a b -> Node -> [Node]
lsuc :: Graph gr => gr a b -> Node -> [(Node,b)]
lpre :: Graph gr => gr a b -> Node -> [(Node,b)]
out :: Graph gr => gr a b -> Node -> [LEdge b]
inn :: Graph gr => gr a b -> Node -> [LEdge b]
outdeg :: Graph gr => gr a b -> Node -> Int
indeg :: Graph gr => gr a b -> Node -> Int
deg :: Graph gr => gr a b -> Node -> Int
-- context inspection
node' :: Context a b -> Node
lab' :: Context a b -> a
labNode' :: Context a b -> LNode a
neighbors' :: Context a b -> [Node]
suc' :: Context a b -> [Node]
pre' :: Context a b -> [Node]
lpre' :: Context a b -> [(Node,b)]
lsuc' :: Context a b -> [(Node,b)]
out' :: Context a b -> [LEdge b]
inn' :: Context a b -> [LEdge b]
outdeg' :: Context a b -> Int
indeg' :: Context a b -> Int
deg' :: Context a b -> Int
-}
-- | Unlabeled node
type Node = Int
-- | Labeled node
type LNode a = (Node,a)
-- | Quasi-unlabeled node
type UNode = LNode ()
-- | Unlabeled edge
type Edge = (Node,Node)
-- | Labeled edge
type LEdge b = (Node,Node,b)
-- | Quasi-unlabeled edge
type UEdge = LEdge ()
-- | Unlabeled path
type Path = [Node]
-- | Labeled path
newtype LPath a = LP [LNode a]
instance Show a => Show (LPath a) where
show (LP xs) = show xs
-- | Quasi-unlabeled path
type UPath = [UNode]
-- | Labeled links to or from a 'Node'.
type Adj b = [(b,Node)]
-- | Links to the 'Node', the 'Node' itself, a label, links from the 'Node'.
type Context a b = (Adj b,Node,a,Adj b) -- Context a b "=" Context' a b "+" Node
type MContext a b = Maybe (Context a b)
-- | 'Graph' decomposition - the context removed from a 'Graph', and the rest
-- of the 'Graph'.
type Decomp g a b = (MContext a b,g a b)
-- | The same as 'Decomp', only more sure of itself.
type GDecomp g a b = (Context a b,g a b)
-- | Unlabeled context.
type UContext = ([Node],Node,[Node])
-- | Unlabeled decomposition.
type UDecomp g = (Maybe UContext,g)
-- | Minimum implementation: 'empty', 'isEmpty', 'match', 'mkGraph', 'labNodes'
class Graph gr where
-- essential operations
-- | An empty 'Graph'.
empty :: gr a b
-- | True if the given 'Graph' is empty.
isEmpty :: gr a b -> Bool
-- | Decompose a 'Graph' into the 'MContext' found for the given node and the
-- remaining 'Graph'.
match :: Node -> gr a b -> Decomp gr a b
-- | Create a 'Graph' from the list of 'LNode's and 'LEdge's.
mkGraph :: [LNode a] -> [LEdge b] -> gr a b
-- | A list of all 'LNode's in the 'Graph'.
labNodes :: gr a b -> [LNode a]
-- derived operations
-- | Decompose a graph into the 'Context' for an arbitrarily-chosen 'Node'
-- and the remaining 'Graph'.
matchAny :: gr a b -> GDecomp gr a b
-- | The number of 'Node's in a 'Graph'.
noNodes :: gr a b -> Int
-- | The minimum and maximum 'Node' in a 'Graph'.
nodeRange :: gr a b -> (Node,Node)
-- | A list of all 'LEdge's in the 'Graph'.
labEdges :: gr a b -> [LEdge b]
-- default implementation of derived operations
matchAny g = case labNodes g of
[] -> error "Match Exception, Empty Graph"
(v,_):_ -> (c,g') where (Just c,g') = match v g
noNodes = length . labNodes
nodeRange g = (minimum vs,maximum vs) where vs = map fst (labNodes g)
labEdges = ufold (\(_,v,_,s)->((map (\(l,w)->(v,w,l)) s)++)) []
class Graph gr => DynGraph gr where
-- | Merge the 'Context' into the 'DynGraph'.
(&) :: Context a b -> gr a b -> gr a b
-- | Fold a function over the graph.
ufold :: Graph gr => ((Context a b) -> c -> c) -> c -> gr a b -> c
ufold f u g | isEmpty g = u
| otherwise = f c (ufold f u g')
where (c,g') = matchAny g
-- | Map a function over the graph.
gmap :: DynGraph gr => (Context a b -> Context c d) -> gr a b -> gr c d
gmap f = ufold (\c->(f c&)) empty
-- | Map a function over the 'Node' labels in a graph.
nmap :: DynGraph gr => (a -> c) -> gr a b -> gr c b
nmap f = gmap (\(p,v,l,s)->(p,v,f l,s))
-- | Map a function over the 'Edge' labels in a graph.
emap :: DynGraph gr => (b -> c) -> gr a b -> gr a c
emap f = gmap (\(p,v,l,s)->(map1 f p,v,l,map1 f s))
where map1 g = map (\(l,v)->(g l,v))
-- | List all 'Node's in the 'Graph'.
nodes :: Graph gr => gr a b -> [Node]
nodes = map fst . labNodes
-- | List all 'Edge's in the 'Graph'.
edges :: Graph gr => gr a b -> [Edge]
edges = map (\(v,w,_)->(v,w)) . labEdges
-- | List N available 'Node's, i.e. 'Node's that are not used in the 'Graph'.
newNodes :: Graph gr => Int -> gr a b -> [Node]
newNodes i g = [n+1..n+i] where (_,n) = nodeRange g
-- | 'True' if the 'Node' is present in the 'Graph'.
gelem :: Graph gr => Node -> gr a b -> Bool
gelem v g = case match v g of {(Just _,_) -> True; _ -> False}
-- | Insert a 'LNode' into the 'Graph'.
insNode :: DynGraph gr => LNode a -> gr a b -> gr a b
insNode (v,l) = (([],v,l,[])&)
-- | Insert a 'LEdge' into the 'Graph'.
insEdge :: DynGraph gr => LEdge b -> gr a b -> gr a b
insEdge (v,w,l) g = (pr,v,la,(l,w):su) & g'
where (Just (pr,_,la,su),g') = match v g
-- | Remove a 'Node' from the 'Graph'.
delNode :: Graph gr => Node -> gr a b -> gr a b
delNode v = delNodes [v]
-- | Remove an 'Edge' from the 'Graph'.
delEdge :: DynGraph gr => Edge -> gr a b -> gr a b
delEdge (v,w) g = case match v g of
(Nothing,_) -> g
(Just (p,v',l,s),g') -> (p,v',l,filter ((/=w).snd) s) & g'
-- | Remove an 'LEdge' from the 'Graph'.
delLEdge :: (DynGraph gr, Eq b) => LEdge b -> gr a b -> gr a b
delLEdge (v,w,b) g = case match v g of
(Nothing,_) -> g
(Just (p,v',l,s),g') -> (p,v',l,filter (\(x,n) -> x /= b || n /= w) s) & g'
-- | Insert multiple 'LNode's into the 'Graph'.
insNodes :: DynGraph gr => [LNode a] -> gr a b -> gr a b
insNodes vs g = foldr insNode g vs
-- | Insert multiple 'LEdge's into the 'Graph'.
insEdges :: DynGraph gr => [LEdge b] -> gr a b -> gr a b
insEdges es g = foldr insEdge g es
-- | Remove multiple 'Node's from the 'Graph'.
delNodes :: Graph gr => [Node] -> gr a b -> gr a b
delNodes [] g = g
delNodes (v:vs) g = delNodes vs (snd (match v g))
-- | Remove multiple 'Edge's from the 'Graph'.
delEdges :: DynGraph gr => [Edge] -> gr a b -> gr a b
delEdges es g = foldr delEdge g es
-- | Build a 'Graph' from a list of 'Context's.
buildGr :: DynGraph gr => [Context a b] -> gr a b
buildGr = foldr (&) empty
-- mkGraph :: DynGraph gr => [LNode a] -> [LEdge b] -> gr a b
-- mkGraph vs es = (insEdges es . insNodes vs) empty
-- | Build a quasi-unlabeled 'Graph'.
mkUGraph :: Graph gr => [Node] -> [Edge] -> gr () ()
mkUGraph vs es = mkGraph (labUNodes vs) (labUEdges es)
labUEdges = map (\(v,w)->(v,w,()))
labUNodes = map (\v->(v,()))
-- | Find the context for the given 'Node'. Causes an error if the 'Node' is
-- not present in the 'Graph'.
context :: Graph gr => gr a b -> Node -> Context a b
context g v = case match v g of
(Nothing,_) -> error ("Match Exception, Node: "++show v)
(Just c,_) -> c
-- | Find the label for a 'Node'.
lab :: Graph gr => gr a b -> Node -> Maybe a
lab g v = fst (match v g) >>= return.lab'
-- | Find the neighbors for a 'Node'.
neighbors :: Graph gr => gr a b -> Node -> [Node]
neighbors = (\(p,_,_,s) -> map snd (p++s)) .: context
-- | Find all 'Node's that have a link from the given 'Node'.
suc :: Graph gr => gr a b -> Node -> [Node]
suc = map snd .: context4
-- | Find all 'Node's that link to to the given 'Node'.
pre :: Graph gr => gr a b -> Node -> [Node]
pre = map snd .: context1
-- | Find all 'Node's that are linked from the given 'Node' and the label of
-- each link.
lsuc :: Graph gr => gr a b -> Node -> [(Node,b)]
lsuc = map flip2 .: context4
-- | Find all 'Node's that link to the given 'Node' and the label of each link.
lpre :: Graph gr => gr a b -> Node -> [(Node,b)]
lpre = map flip2 .: context1
-- | Find all outward-bound 'LEdge's for the given 'Node'.
out :: Graph gr => gr a b -> Node -> [LEdge b]
out g v = map (\(l,w)->(v,w,l)) (context4 g v)
-- | Find all inward-bound 'LEdge's for the given 'Node'.
inn :: Graph gr => gr a b -> Node -> [LEdge b]
inn g v = map (\(l,w)->(w,v,l)) (context1 g v)
-- | The outward-bound degree of the 'Node'.
outdeg :: Graph gr => gr a b -> Node -> Int
outdeg = length .: context4
-- | The inward-bound degree of the 'Node'.
indeg :: Graph gr => gr a b -> Node -> Int
indeg = length .: context1
-- | The degree of the 'Node'.
deg :: Graph gr => gr a b -> Node -> Int
deg = (\(p,_,_,s) -> length p+length s) .: context
-- | The 'Node' in a 'Context'.
node' :: Context a b -> Node
node' (_,v,_,_) = v
-- | The label in a 'Context'.
lab' :: Context a b -> a
lab' (_,_,l,_) = l
-- | The 'LNode' from a 'Context'.
labNode' :: Context a b -> LNode a
labNode' (_,v,l,_) = (v,l)
-- | All 'Node's linked to or from in a 'Context'.
neighbors' :: Context a b -> [Node]
neighbors' (p,_,_,s) = map snd p++map snd s
-- | All 'Node's linked to in a 'Context'.
suc' :: Context a b -> [Node]
suc' (_,_,_,s) = map snd s
-- | All 'Node's linked from in a 'Context'.
pre' :: Context a b -> [Node]
pre' (p,_,_,_) = map snd p
-- | All 'Node's linked from in a 'Context', and the label of the links.
lpre' :: Context a b -> [(Node,b)]
lpre' (p,_,_,_) = map flip2 p
-- | All 'Node's linked from in a 'Context', and the label of the links.
lsuc' :: Context a b -> [(Node,b)]
lsuc' (_,_,_,s) = map flip2 s
-- | All outward-directed 'LEdge's in a 'Context'.
out' :: Context a b -> [LEdge b]
out' (_,v,_,s) = map (\(l,w)->(v,w,l)) s
-- | All inward-directed 'LEdge's in a 'Context'.
inn' :: Context a b -> [LEdge b]
inn' (p,v,_,_) = map (\(l,w)->(w,v,l)) p
-- | The outward degree of a 'Context'.
outdeg' :: Context a b -> Int
outdeg' (_,_,_,s) = length s
-- | The inward degree of a 'Context'.
indeg' :: Context a b -> Int
indeg' (p,_,_,_) = length p
-- | The degree of a 'Context'.
deg' :: Context a b -> Int
deg' (p,_,_,s) = length p+length s
-- graph equality
--
nodeComp :: Eq b => LNode b -> LNode b -> Ordering
nodeComp n@(v,_) n'@(w,_) | n == n' = EQ
| v<w = LT
| otherwise = GT
slabNodes :: (Eq a,Graph gr) => gr a b -> [LNode a]
slabNodes = sortBy nodeComp . labNodes
edgeComp :: Eq b => LEdge b -> LEdge b -> Ordering
edgeComp e@(v,w,_) e'@(x,y,_) | e == e' = EQ
| v<x || (v==x && w<y) = LT
| otherwise = GT
slabEdges :: (Eq b,Graph gr) => gr a b -> [LEdge b]
slabEdges = sortBy edgeComp . labEdges
-- instance (Eq a,Eq b,Graph gr) => Eq (gr a b) where
-- g == g' = slabNodes g == slabNodes g' && slabEdges g == slabEdges g'
equal :: (Eq a,Eq b,Graph gr) => gr a b -> gr a b -> Bool
equal g g' = slabNodes g == slabNodes g' && slabEdges g == slabEdges g'
----------------------------------------------------------------------
-- UTILITIES
----------------------------------------------------------------------
-- auxiliary functions used in the implementation of the
-- derived class members
--
(.:) :: (c -> d) -> (a -> b -> c) -> (a -> b -> d)
-- f .: g = \x y->f (g x y)
-- f .: g = (f .) . g
-- (.:) f = ((f .) .)
-- (.:) = (.) (.) (.)
(.:) = (.) . (.)
fst4 (x,_,_,_) = x
{- not used
snd4 (_,x,_,_) = x
thd4 (_,_,x,_) = x
-}
fth4 (_,_,_,x) = x
{- not used
fst3 (x,_,_) = x
snd3 (_,x,_) = x
thd3 (_,_,x) = x
-}
flip2 (x,y) = (y,x)
-- projecting on context elements
--
-- context1 g v = fst4 (contextP g v)
context1 :: Graph gr => gr a b -> Node -> Adj b
{- not used
context2 :: Graph gr => gr a b -> Node -> Node
context3 :: Graph gr => gr a b -> Node -> a
-}
context4 :: Graph gr => gr a b -> Node -> Adj b
context1 = fst4 .: context
{- not used
context2 = snd4 .: context
context3 = thd4 .: context
-}
context4 = fth4 .: context
|
FranklinChen/hugs98-plus-Sep2006
|
packages/fgl/Data/Graph/Inductive/Graph.hs
|
Haskell
|
bsd-3-clause
| 16,059
|
{-# LANGUAGE TupleSections, GADTs, StandaloneDeriving, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts #-}
module IndexedState
where
newtype IStateT m i o a = IStateT { runIState :: i -> m (o, a) }
class IMonad m where
ireturn :: a -> m i i a
(>>>=) :: m i j a -> (a -> m j k b) -> m i k b
(>>>) :: IMonad m => m i j a -> m j k b -> m i k b
mx >>> my = mx >>>= const my
class IMonadTrans t where
ilift :: Monad m => m a -> t m i i a
iget :: Monad m => IStateT m s s s
iget = IStateT $ \s -> return (s, s)
iput :: Monad m => o -> IStateT m i o ()
iput x = IStateT $ \_ -> return (x, ())
imodify :: Monad m => (i -> o) -> IStateT m i o ()
imodify f = IStateT $ \s -> return (f s, ())
instance Monad m => IMonad (IStateT m) where
ireturn x = IStateT (\s -> return (s, x))
IStateT f >>>= g = IStateT $ \s -> do
(s', x) <- f s
let IStateT h = g x
h s'
instance IMonadTrans IStateT where
ilift m = IStateT $ \s -> m >>= \x -> return (s, x)
type StateMachine = IStateT IO
newtype Size = Size Int deriving (Read, Show)
newtype Height = Height Int deriving (Read, Show)
newtype Weight = Weight Int deriving (Read, Show)
newtype Colour = Colour String deriving (Read, Show)
askKnownSize :: StateMachine as (Bool, as) Bool
askKnownSize = askYN' "Do you know your size?"
-- askSize takes an environment of type as and adds a Size element
askSize :: StateMachine as (Size, as) ()
askSize = askNumber "What is your size?" Size
receiveSize :: String -> StateMachine as (Size, as) ()
receiveSize = receiveNumber Size
-- askHeight takes an environment of type as and adds a Height element
askHeight :: StateMachine as (Height, as) ()
askHeight = askNumber "What is your height?" Height
-- etc
askWeight :: StateMachine as (Weight, as) ()
askWeight = askNumber "What is your weight?" Weight
askColour :: StateMachine as (Colour, as) ()
askColour =
ilift (putStrLn "What is your favourite colour?") >>>
ilift readLn >>>= \answer ->
imodify (Colour answer,)
calculateSize :: Height -> Weight -> Size
calculateSize (Height h) (Weight w) = Size (h - w) -- or whatever the calculation is
askNumber :: String -> (Int -> a) -> StateMachine as (a, as) ()
askNumber question mk =
ilift (putStrLn question) >>>
ilift readLn >>>= \answer ->
case reads answer of
[(x, _)] -> imodify (mk x,)
_ -> ilift (putStrLn "Please type a number") >>> askNumber question mk
justAskColour :: StateMachine as (Maybe Colour, as) ()
justAskColour =
ilift (putStrLn "What is your favourite colour?") >>>
imodify (Nothing, )
justAnswer :: String -> Suspended -> StateMachine as (Maybe Colour, (Size, (Bool, ()))) ()
justAnswer answer (Suspended AskSize e) =
iput e >>>
receiveSize answer >>>
iget >>>= \ s -> undefined -- resume' AskColour (Just s) --TODO: rewrite types of resume' and resume
receiveNumber :: (Int -> a) -> String -> StateMachine as (a, as) ()
receiveNumber mk answer =
case reads answer of
[(x, _)] -> imodify (mk x,)
_ -> error "invalid number"
askYN :: String -> StateMachine as as Bool
askYN question =
ilift (putStrLn question) >>>
ilift readLn >>>= \answer ->
case answer of
"y" -> ireturn True
"n" -> ireturn False
_ -> ilift (putStrLn "Please type y or n") >>> askYN question
askYN' :: String -> StateMachine as (Bool, as) Bool
askYN' question =
ilift (putStrLn question) >>>
ilift readLn >>>= \answer ->
case answer of
"y" -> imodify (True,) >>> ireturn True
"n" -> imodify (False,) >>> ireturn False
_ -> ilift (putStrLn "Please type y or n") >>> askYN' question
answerYN question answer =
case answer of
"y" -> imodify (True,) >>> ireturn True
"n" -> imodify (False,) >>> ireturn False
_ -> ilift (putStrLn "Please type y or n") >>> askYN' question
-- interaction :: StateMachine xs (Colour, (Size, xs)) ()
-- interaction :: interaction :: StateMachine () (Colour, (Size, ())) ()
interaction =
(suspend AskKnownSize >>> askKnownSize) >>>= \ answer ->
askOrCalculateSize answer >>>
askColour
where
askOrCalculateSize True = suspend AskSize >>> askSize
askOrCalculateSize False =
(suspend AskWeight >>> askWeight) >>>
(suspend AskHeight >>> askHeight) >>>
imodify (\ (h, (w, xs)) -> (calculateSize h w, xs)) >>> suspend AskColour
-- interaction' :: (Functor m, Show as) => i -> IStateT m i as t -> Stage as -> m Suspended
-- interaction' as machine stage = (\(r, _) -> Suspended stage r) <$> runIState machine as
--
-- interaction'' =
-- askYN "Do you know your size?" >>>= \ ans -> suspend AskWeight
-- interaction' () askWeight AskHeight
-- interaction' () askWeight AskHeight
data Stage as where
AskKnownSize :: Stage ()
AskSize :: Stage (Bool, ())
AskWeight :: Stage (Bool, ())
AskHeight :: Stage (Weight, (Bool, ()))
AskColour :: Stage (Size, (Bool, ()))
deriving instance Show (Stage as)
data Suspended where
Suspended :: (Show as) => Stage as -> as -> Suspended
instance Show Suspended where
show (Suspended stage as) = show stage ++ ", " ++ show as
instance Read Suspended where
readsPrec = const $ uncurry ($) . mapFst parse . fmap (drop 2) . break (==',')
where
parse :: String -> String -> [(Suspended, String)]
parse stage = case stage of
"AskKnownSize" -> parse' AskKnownSize
"AskSize" -> parse' AskSize
"AskWeight" -> parse' AskWeight
"AskHeight" -> parse' AskHeight
"AskColour" -> parse' AskColour
_ -> const []
parse' :: (Show as, Read as) => Stage as -> String -> [(Suspended, String)]
parse' stg st = [(Suspended stg (read st), mempty)]
mapFst :: (a -> c) -> (a, b) -> (c, b)
mapFst f ~(a, b) = (f a, b)
-- WORKS: runIState (resume (read "AskColour, (Size 33, (True, ()))" )) ()
-- WORKS: runIState (resume (read "AskKnownSize, ()" )) ()
-- runIState (resume (Suspended AskWeight (False, ()) )) ()
-- runIState (resume (Suspended AskHeight (Weight 40, ()))) ()
resume :: Suspended -> StateMachine as (Colour, (Size, (Bool, ()))) ()
resume (Suspended AskKnownSize e) =
iput e >>>
askKnownSize >>>= \ b ->
resume' (if b then AskSize else AskWeight) (b, e)
resume (Suspended AskSize e) =
iput e >>>
askSize >>>
iget >>>= resume' AskColour
resume (Suspended AskWeight e) =
iput e >>>
askWeight >>>
iget >>>= resume' AskHeight
resume (Suspended AskHeight e) =
iput e >>>
askHeight >>>
imodify (\(h, (w, xs)) -> (calculateSize h w, xs)) >>>
iget >>>= resume' AskColour
resume (Suspended AskColour e) =
iput e >>>
askColour
resume' :: Show as => Stage as -> as -> StateMachine as (Colour, (Size, (Bool, ()))) ()
resume' stage as = suspend stage >>> resume (Suspended stage as)
-- given persist :: Suspended -> IO ()
suspend :: (Show as) => Stage as -> StateMachine as as ()
suspend stage =
iget >>>= \env ->
ilift (persist (Suspended stage env))
persist :: Suspended -> IO ()
persist = print
-- main = runIState interaction () >>= print
-- main = runIState (resume (read "AskKnownSize, ()" )) () >>= print
main = resume'' "AskKnownSize, ()" sizeFlow ()
-- runIState (suspend AskHeight ) (Weight 4, ())
-- runIState (suspend AskWeight) ()
newtype Flow sp as o a = Flow { unFlow :: sp -> StateMachine as o a }
sizeFlow :: Flow Suspended as (Colour, (Size, (Bool, ()))) ()
sizeFlow = Flow resume
resume'' :: (Read sp, Show o, Show a) => String -> Flow sp i o a -> i -> IO ()
resume'' st flow i = runIState (unFlow flow (read st)) i >>= print
--- ----
data Flows sp as o a where
SizeFlow :: Flow Suspended as (Colour, (Size, (Bool, ()))) () -> Flows sp as o a
TryAtHomeFlow :: Flow Suspended as (Colour, (Size, (Int, ()))) () -> Flows sp as o a
getFlow "SizeFlow" = SizeFlow sizeFlow
getFlow "TryAtHomeFlow" = TryAtHomeFlow undefined
---
ask :: Suspended -> StateMachine as (Colour, (Size, (Bool, ()))) ()
ask (Suspended AskKnownSize e) =
iput e >>>
suspend AskKnownSize >>>
askKnownSize >>>= \ b ->
resume' (if b then AskSize else AskWeight) (b, e)
-- runIState (answer "5" (Suspended AskSize (True, ()))) () AskColour, (Size 5,(True,()))
answer :: String -> Suspended -> StateMachine as (Colour, (Size, (Bool, ()))) ()
answer answer (Suspended AskSize e) =
iput e >>>
receiveSize answer >>>
iget >>>= \ s -> resume' AskColour s
|
homam/fsm-conversational-ui
|
src/IndexedState.hs
|
Haskell
|
bsd-3-clause
| 8,330
|
-- Copyright (c) 2017 Eric McCorkle. 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.
-- 3. Neither the name of the author nor the names of any contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE AUTHORS 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 AUTHORS
-- 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.
{-# OPTIONS_GHC -Wall -Werror #-}
{-# LANGUAGE DataKinds, TypeFamilies #-}
module RISCV.ISA.Registers.Regular(
Reg(..)
) where
import Prelude
import CLaSH.Class.BitPack
-- | Regular RISC-V registers (ie. those provided by the I-instruction set)
data Reg =
ZERO
| RA
| SP
| GP
| TP
| T0
| T1
| T2
| FP
| S1
| A0
| A1
| A2
| A3
| A4
| A5
| A6
| A7
| S2
| S3
| S4
| S5
| S6
| S7
| S8
| S9
| S10
| S11
| T3
| T4
| T5
| T6
deriving (Eq, Ord, Show)
instance Enum Reg where
fromEnum ZERO = 0x00
fromEnum RA = 0x01
fromEnum SP = 0x02
fromEnum GP = 0x03
fromEnum TP = 0x04
fromEnum T0 = 0x05
fromEnum T1 = 0x06
fromEnum T2 = 0x07
fromEnum FP = 0x08
fromEnum S1 = 0x09
fromEnum A0 = 0x0a
fromEnum A1 = 0x0b
fromEnum A2 = 0x0c
fromEnum A3 = 0x0d
fromEnum A4 = 0x0e
fromEnum A5 = 0x0f
fromEnum A6 = 0x10
fromEnum A7 = 0x11
fromEnum S2 = 0x12
fromEnum S3 = 0x13
fromEnum S4 = 0x14
fromEnum S5 = 0x15
fromEnum S6 = 0x16
fromEnum S7 = 0x17
fromEnum S8 = 0x18
fromEnum S9 = 0x19
fromEnum S10 = 0x1a
fromEnum S11 = 0x1b
fromEnum T3 = 0x1c
fromEnum T4 = 0x1d
fromEnum T5 = 0x1e
fromEnum T6 = 0x1f
toEnum 0x00 = ZERO
toEnum 0x01 = RA
toEnum 0x02 = SP
toEnum 0x03 = GP
toEnum 0x04 = TP
toEnum 0x05 = T0
toEnum 0x06 = T1
toEnum 0x07 = T2
toEnum 0x08 = FP
toEnum 0x09 = S1
toEnum 0x0a = A0
toEnum 0x0b = A1
toEnum 0x0c = A2
toEnum 0x0d = A3
toEnum 0x0e = A4
toEnum 0x0f = A5
toEnum 0x10 = A6
toEnum 0x11 = A7
toEnum 0x12 = S2
toEnum 0x13 = S3
toEnum 0x14 = S4
toEnum 0x15 = S5
toEnum 0x16 = S6
toEnum 0x17 = S7
toEnum 0x18 = S8
toEnum 0x19 = S9
toEnum 0x1a = S10
toEnum 0x1b = S11
toEnum 0x1c = T3
toEnum 0x1d = T4
toEnum 0x1e = T5
toEnum 0x1f = T6
toEnum _ = error "Invalid register ID"
instance BitPack Reg where
type BitSize Reg = 5
pack = toEnum . fromEnum
unpack = toEnum . fromEnum
|
emc2/clash-riscv
|
src/RISCV/ISA/Registers/Regular.hs
|
Haskell
|
bsd-3-clause
| 3,540
|
{-# LANGUAGE FlexibleContexts, ConstraintKinds #-}
-----------------------------------------------------------------------------
-- |
-- Module : Call.Util.Deck
-- Copyright : (c) Fumiaki Kinoshita 2014
-- License : BSD3
--
-- Maintainer : Fumiaki Kinoshita <fumiexcel@gmail.com>
-- Stability : experimental
-- Portability : non-portable
--
-- Polyphonic sampler
--
-----------------------------------------------------------------------------
module Audiovisual.Sampler where
import qualified Data.Vector.Storable as V
import qualified Data.Vector.Storable.Mutable as MV
import Control.Monad.ST
import Control.Monad.State.Strict
import Data.Audio
import Foreign.Storable
data Sampler a = Sampler [(Sample a, Time)]
empty :: Sampler a
empty = Sampler []
playback :: (Num a, Storable a, MonadState (Sampler a) m) => Time -> Int -> m (V.Vector a)
playback dt n = do
Sampler vs <- get
let (vs'', r) = runST $ do
v <- MV.new n
vs' <- forM vs $ \(s0@(Sample d (Source s)), t0) -> do
if d > t0 then return []
else do
forM_ [0..n-1] $ \i -> do
z <- MV.unsafeRead v i
MV.unsafeWrite v i $ z + s (t0 + f * fromIntegral i)
return [(s0, t0 + dt)]
v' <- V.unsafeFreeze v
return (vs', v')
put $ Sampler $ concat vs''
return r
where
f = dt / fromIntegral n
play :: MonadState (Sampler a) m => Sample a -> m ()
play s = modify $ \(Sampler xs) -> Sampler $ (s, 0) : xs
|
fumieval/audiovisual
|
src/Audiovisual/Sampler.hs
|
Haskell
|
bsd-3-clause
| 1,505
|
{-# LANGUAGE CPP, OverloadedStrings #-}
-- | DNS Resolver and generic (lower-level) lookup functions.
module Network.DNS.Resolver (
-- * Documentation
-- ** Configuration for resolver
FileOrNumericHost(..), ResolvConf(..), defaultResolvConf
-- ** Intermediate data type for resolver
, ResolvSeed, makeResolvSeed
-- ** Type and function for resolver
, Resolver(..), withResolver, withResolvers
-- ** Looking up functions
, lookup
, lookupAuth
-- ** Raw looking up function
, lookupRaw
, lookupRawAD
, fromDNSMessage
, fromDNSFormat
) where
import Control.Exception (bracket)
import Data.Char (isSpace)
import Data.List (isPrefixOf)
import Data.Maybe (fromMaybe)
import Network.BSD (getProtocolNumber)
import Network.DNS.Decode
import Network.DNS.Encode
import Network.DNS.Internal
import qualified Data.ByteString.Char8 as BS
import Network.Socket (HostName, Socket, SocketType(Stream, Datagram))
import Network.Socket (AddrInfoFlag(..), AddrInfo(..), SockAddr(..))
import Network.Socket (Family(AF_INET, AF_INET6), PortNumber(..))
import Network.Socket (close, socket, connect, getPeerName, getAddrInfo)
import Network.Socket (defaultHints, defaultProtocol)
import Prelude hiding (lookup)
import System.Random (getStdRandom, random)
import System.Timeout (timeout)
import Data.Word (Word16)
#if __GLASGOW_HASKELL__ < 709
import Control.Applicative ((<$>), (<*>), pure)
#endif
#if mingw32_HOST_OS == 1
import Network.Socket (send)
import qualified Data.ByteString.Char8 as BS
import Control.Monad (when)
#else
import Network.Socket.ByteString (sendAll)
#endif
----------------------------------------------------------------
-- | Union type for 'FilePath' and 'HostName'. Specify 'FilePath' to
-- \"resolv.conf\" or numeric IP address in 'String' form.
--
-- /Warning/: Only numeric IP addresses are valid @RCHostName@s.
--
-- Example (using Google's public DNS cache):
--
-- >>> let cache = RCHostName "8.8.8.8"
--
data FileOrNumericHost = RCFilePath FilePath -- ^ A path for \"resolv.conf\"
| RCHostName HostName -- ^ A numeric IP address
| RCHostPort HostName PortNumber -- ^ A numeric IP address and port number
-- | Type for resolver configuration. The easiest way to construct a
-- @ResolvConf@ object is to modify the 'defaultResolvConf'.
data ResolvConf = ResolvConf {
resolvInfo :: FileOrNumericHost
-- | Timeout in micro seconds.
, resolvTimeout :: Int
-- | The number of retries including the first try.
, resolvRetry :: Int
-- | This field was obsoleted.
, resolvBufsize :: Integer
}
-- | Return a default 'ResolvConf':
--
-- * 'resolvInfo' is 'RCFilePath' \"\/etc\/resolv.conf\".
--
-- * 'resolvTimeout' is 3,000,000 micro seconds.
--
-- * 'resolvRetry' is 3.
--
-- * 'resolvBufsize' is 512. (obsoleted)
--
-- Example (use Google's public DNS cache instead of resolv.conf):
--
-- >>> let cache = RCHostName "8.8.8.8"
-- >>> let rc = defaultResolvConf { resolvInfo = cache }
--
defaultResolvConf :: ResolvConf
defaultResolvConf = ResolvConf {
resolvInfo = RCFilePath "/etc/resolv.conf"
, resolvTimeout = 3 * 1000 * 1000
, resolvRetry = 3
, resolvBufsize = 512
}
----------------------------------------------------------------
-- | Abstract data type of DNS Resolver seed.
-- When implementing a DNS cache, this should be re-used.
data ResolvSeed = ResolvSeed {
addrInfo :: AddrInfo
, rsTimeout :: Int
, rsRetry :: Int
, rsBufsize :: Integer
}
-- | Abstract data type of DNS Resolver
-- When implementing a DNS cache, this MUST NOT be re-used.
data Resolver = Resolver {
genId :: IO Word16
, dnsSock :: Socket
, dnsTimeout :: Int
, dnsRetry :: Int
, dnsBufsize :: Integer
}
----------------------------------------------------------------
-- | Make a 'ResolvSeed' from a 'ResolvConf'.
--
-- Examples:
--
-- >>> rs <- makeResolvSeed defaultResolvConf
--
makeResolvSeed :: ResolvConf -> IO ResolvSeed
makeResolvSeed conf = ResolvSeed <$> addr
<*> pure (resolvTimeout conf)
<*> pure (resolvRetry conf)
<*> pure (resolvBufsize conf)
where
addr = case resolvInfo conf of
RCHostName numhost -> makeAddrInfo numhost Nothing
RCHostPort numhost mport -> makeAddrInfo numhost $ Just mport
RCFilePath file -> toAddr <$> readFile file >>= \i -> makeAddrInfo i Nothing
toAddr cs = let l:_ = filter ("nameserver" `isPrefixOf`) $ lines cs
in extract l
extract = reverse . dropWhile isSpace . reverse . dropWhile isSpace . drop 11
makeAddrInfo :: HostName -> Maybe PortNumber -> IO AddrInfo
makeAddrInfo addr mport = do
proto <- getProtocolNumber "udp"
let hints = defaultHints {
addrFlags = [AI_ADDRCONFIG, AI_NUMERICHOST, AI_PASSIVE]
, addrSocketType = Datagram
, addrProtocol = proto
}
a:_ <- getAddrInfo (Just hints) (Just addr) (Just "domain")
let connectPort = case addrAddress a of
SockAddrInet pn ha -> SockAddrInet (fromMaybe pn mport) ha
SockAddrInet6 pn fi ha sid -> SockAddrInet6 (fromMaybe pn mport) fi ha sid
unixAddr -> unixAddr
return $ a { addrAddress = connectPort }
----------------------------------------------------------------
-- | Giving a thread-safe 'Resolver' to the function of the second
-- argument. A socket for UDP is opened inside and is surely closed.
-- Multiple 'withResolver's can be used concurrently.
-- Multiple lookups must be done sequentially with a given
-- 'Resolver'. If multiple 'Resolver's are necessary for
-- concurrent purpose, use 'withResolvers'.
withResolver :: ResolvSeed -> (Resolver -> IO a) -> IO a
withResolver seed func = bracket (openSocket seed) close $ \sock -> do
connectSocket sock seed
func $ makeResolver seed sock
-- | Giving thread-safe 'Resolver's to the function of the second
-- argument. Sockets for UDP are opened inside and are surely closed.
-- For each 'Resolver', multiple lookups must be done sequentially.
-- 'Resolver's can be used concurrently.
withResolvers :: [ResolvSeed] -> ([Resolver] -> IO a) -> IO a
withResolvers seeds func = bracket openSockets closeSockets $ \socks -> do
mapM_ (uncurry connectSocket) $ zip socks seeds
let resolvs = zipWith makeResolver seeds socks
func resolvs
where
openSockets = mapM openSocket seeds
closeSockets = mapM close
openSocket :: ResolvSeed -> IO Socket
openSocket seed = socket (addrFamily ai) (addrSocketType ai) (addrProtocol ai)
where
ai = addrInfo seed
connectSocket :: Socket -> ResolvSeed -> IO ()
connectSocket sock seed = connect sock (addrAddress ai)
where
ai = addrInfo seed
makeResolver :: ResolvSeed -> Socket -> Resolver
makeResolver seed sock = Resolver {
genId = getRandom
, dnsSock = sock
, dnsTimeout = rsTimeout seed
, dnsRetry = rsRetry seed
, dnsBufsize = rsBufsize seed
}
getRandom :: IO Word16
getRandom = getStdRandom random
----------------------------------------------------------------
-- | Looking up resource records of a domain. The first parameter is one of
-- the field accessors of the 'DNSMessage' type -- this allows you to
-- choose which section (answer, authority, or additional) you would like
-- to inspect for the result.
lookupSection :: (DNSMessage -> [ResourceRecord])
-> Resolver
-> Domain
-> TYPE
-> IO (Either DNSError [RData])
lookupSection section rlv dom typ = do
eans <- lookupRaw rlv dom typ
case eans of
Left err -> return $ Left err
Right ans -> return $ fromDNSMessage ans toRData
where
{- CNAME hack
dom' = if "." `isSuffixOf` dom then dom else dom ++ "."
correct r = rrname r == dom' && rrtype r == typ
-}
correct (ResourceRecord _ rrtype _ _) = rrtype == typ
correct (OptRecord _ _ _ _) = False
toRData x = map getRdata . filter correct $ section x
-- | Extract necessary information from 'DNSMessage'
fromDNSMessage :: DNSMessage -> (DNSMessage -> a) -> Either DNSError a
fromDNSMessage ans conv = case errcode ans of
NoErr -> Right $ conv ans
FormatErr -> Left FormatError
ServFail -> Left ServerFailure
NameErr -> Left NameError
NotImpl -> Left NotImplemented
Refused -> Left OperationRefused
BadOpt -> Left BadOptRecord
where
errcode = rcode . flags . header
-- | For backward compatibility.
fromDNSFormat :: DNSMessage -> (DNSMessage -> a) -> Either DNSError a
fromDNSFormat = fromDNSMessage
-- | Look up resource records for a domain, collecting the results
-- from the ANSWER section of the response.
--
-- We repeat an example from "Network.DNS.Lookup":
--
-- >>> let hostname = Data.ByteString.Char8.pack "www.example.com"
-- >>> rs <- makeResolvSeed defaultResolvConf
-- >>> withResolver rs $ \resolver -> lookup resolver hostname A
-- Right [RD_A 93.184.216.34]
--
lookup :: Resolver -> Domain -> TYPE -> IO (Either DNSError [RData])
lookup = lookupSection answer
-- | Look up resource records for a domain, collecting the results
-- from the AUTHORITY section of the response.
lookupAuth :: Resolver -> Domain -> TYPE -> IO (Either DNSError [RData])
lookupAuth = lookupSection authority
-- | Look up a name and return the entire DNS Response. If the
-- initial UDP query elicits a truncated answer, the query is
-- retried over TCP. The TCP retry may extend the total time
-- taken by one more timeout beyond timeout * tries.
--
-- Sample output is included below, however it is /not/ tested
-- the sequence number is unpredictable (it has to be!).
--
-- The example code:
--
-- @
-- let hostname = Data.ByteString.Char8.pack \"www.example.com\"
-- rs <- makeResolvSeed defaultResolvConf
-- withResolver rs $ \resolver -> lookupRaw resolver hostname A
-- @
--
-- And the (formatted) expected output:
--
-- @
-- Right (DNSMessage
-- { header = DNSHeader
-- { identifier = 1,
-- flags = DNSFlags
-- { qOrR = QR_Response,
-- opcode = OP_STD,
-- authAnswer = False,
-- trunCation = False,
-- recDesired = True,
-- recAvailable = True,
-- rcode = NoErr,
-- authenData = False
-- },
-- },
-- question = [Question { qname = \"www.example.com.\",
-- qtype = A}],
-- answer = [ResourceRecord {rrname = \"www.example.com.\",
-- rrtype = A,
-- rrttl = 800,
-- rdlen = 4,
-- rdata = 93.184.216.119}],
-- authority = [],
-- additional = []})
-- @
--
lookupRaw :: Resolver -> Domain -> TYPE -> IO (Either DNSError DNSMessage)
lookupRaw = lookupRawInternal receive False
-- | Same as lookupRaw, but the query sets the AD bit, which solicits the
-- the authentication status in the server reply. In most applications
-- (other than diagnostic tools) that want authenticated data It is
-- unwise to trust the AD bit in the responses of non-local servers, this
-- interface should in most cases only be used with a loopback resolver.
--
lookupRawAD :: Resolver -> Domain -> TYPE -> IO (Either DNSError DNSMessage)
lookupRawAD = lookupRawInternal receive True
-- Lookup loop, we try UDP until we get a response. If the response
-- is truncated, we try TCP once, with no further UDP retries.
-- EDNS0 support would significantly reduce the need for TCP retries.
--
-- For now, we optimize for low latency high-availability caches
-- (e.g. running on a loopback interface), where TCP is cheap
-- enough. We could attempt to complete the TCP lookup within the
-- original time budget of the truncated UDP query, by wrapping both
-- within a a single 'timeout' thereby staying within the original
-- time budget, but it seems saner to give TCP a full opportunity to
-- return results. TCP latency after a truncated UDP reply will be
-- atypical.
--
-- Future improvements might also include support for TCP on the
-- initial query, and of course support for multiple nameservers.
lookupRawInternal ::
(Socket -> IO DNSMessage)
-> Bool
-> Resolver
-> Domain
-> TYPE
-> IO (Either DNSError DNSMessage)
lookupRawInternal _ _ _ dom _
| isIllegal dom = return $ Left IllegalDomain
lookupRawInternal rcv ad rlv dom typ = do
seqno <- genId rlv
let query = (if ad then composeQueryAD else composeQuery) seqno [q]
checkSeqno = check seqno
loop query checkSeqno 0 False
where
loop query checkSeqno cnt mismatch
| cnt == retry = do
let ret | mismatch = SequenceNumberMismatch
| otherwise = TimeoutExpired
return $ Left ret
| otherwise = do
sendAll sock query
response <- timeout tm (rcv sock)
case response of
Nothing -> loop query checkSeqno (cnt + 1) False
Just res -> do
let valid = checkSeqno res
case valid of
False -> loop query checkSeqno (cnt + 1) False
True | not $ trunCation $ flags $ header res
-> return $ Right res
_ -> tcpRetry query sock tm
sock = dnsSock rlv
tm = dnsTimeout rlv
retry = dnsRetry rlv
q = makeQuestion dom typ
check seqno res = identifier (header res) == seqno
-- Create a TCP socket `just like` our UDP socket and retry the same
-- query over TCP. Since TCP is a reliable transport, and we just
-- got a (truncated) reply from the server over UDP (so it has the
-- answer, but it is just too large for UDP), we expect to succeed
-- quickly on the first try. There will be no further retries.
tcpRetry ::
Query
-> Socket
-> Int
-> IO (Either DNSError DNSMessage)
tcpRetry query sock tm = do
peer <- getPeerName sock
bracket (tcpOpen peer)
(maybe (return ()) close)
(tcpLookup query peer tm)
-- Create a TCP socket with the given socket address (taken from a
-- corresponding UDP socket). This might throw an I/O Exception
-- if we run out of file descriptors. Should this use tryIOError,
-- and return "Nothing" also in that case? If so, perhaps similar
-- code is needed in openSocket, but that has to wait until we
-- refactor `withResolver` to not do "early" socket allocation, and
-- instead allocate a fresh UDP socket for each `lookupRawInternal`
-- invocation. It would be bad to fail an entire `withResolver`
-- action, if the socket shortage is transient, and the user intends
-- to make many DNS queries with the same resolver handle.
tcpOpen :: SockAddr -> IO (Maybe Socket)
tcpOpen peer = do
case (peer) of
SockAddrInet _ _ ->
socket AF_INET Stream defaultProtocol >>= return . Just
SockAddrInet6 _ _ _ _ ->
socket AF_INET6 Stream defaultProtocol >>= return . Just
_ -> return Nothing -- Only IPv4 and IPv6 are possible
-- Perform a DNS query over TCP, if we were successful in creating
-- the TCP socket. The socket creation can only fail if we run out
-- of file descriptors, we're not making connections here. Failure
-- is reported as "server" failure, though it is really our stub
-- resolver that's failing. This is likely good enough.
tcpLookup ::
Query
-> SockAddr
-> Int
-> Maybe Socket
-> IO (Either DNSError DNSMessage)
tcpLookup _ _ _ Nothing = return $ Left ServerFailure
tcpLookup query peer tm (Just vc) = do
response <- timeout tm $ do
connect vc $ peer
sendAll vc $ encodeVC query
receiveVC vc
case response of
Nothing -> return $ Left TimeoutExpired
Just res -> return $ Right res
#if mingw32_HOST_OS == 1
-- Windows does not support sendAll in Network.ByteString.
-- This implements sendAll with Haskell Strings.
sendAll :: Socket -> BS.ByteString -> IO ()
sendAll sock bs = do
sent <- send sock (BS.unpack bs)
when (sent < fromIntegral (BS.length bs)) $ sendAll sock (BS.drop (fromIntegral sent) bs)
#endif
isIllegal :: Domain -> Bool
isIllegal "" = True
isIllegal dom
| '.' `BS.notElem` dom = True
| ':' `BS.elem` dom = True
| '/' `BS.elem` dom = True
| BS.length dom > 253 = True
| any (\x -> BS.length x > 63)
(BS.split '.' dom) = True
isIllegal _ = False
|
greydot/dns
|
Network/DNS/Resolver.hs
|
Haskell
|
bsd-3-clause
| 17,032
|
{-# LANGUAGE PatternSynonyms #-}
module System.Win32.SystemServices.Services
( HandlerFunction
, ServiceMainFunction
, SCM_ACCESS_RIGHTS (..)
, SVC_ACCESS_RIGHTS (..)
, SERVICE_ACCEPT (..)
, SERVICE_CONTROL (..)
, SERVICE_ERROR (..)
, SERVICE_STATE (..)
, pattern SERVICE_CONTINUE_PENDING
, pattern SERVICE_PAUSE_PENDING
, pattern SERVICE_PAUSED
, pattern SERVICE_RUNNING
, pattern SERVICE_START_PENDING
, pattern SERVICE_STOP_PENDING
, pattern SERVICE_STOPPED
, SERVICE_STATUS (..)
, SERVICE_TYPE (..)
, SERVICE_START_TYPE(..)
, pattern SERVICE_FILE_SYSTEM_DRIVER
, pattern SERVICE_KERNEL_DRIVER
, pattern SERVICE_WIN32_OWN_PROCESS
, pattern SERVICE_WIN32_SHARE_PROCESS
, pattern SERVICE_INTERACTIVE_PROCESS
, pattern SERVICE_AUTO_START
, pattern SERVICE_BOOT_START
, pattern SERVICE_DEMAND_START
, pattern SERVICE_DISABLED
, pattern SERVICE_SYSTEM_START
, FromDWORD (..)
, EnumServiceState (..)
, EnumServiceStatus (..)
, SERVICE_CONFIG (..)
, nO_ERROR
, eRROR_SERVICE_SPECIFIC_ERROR
, changeServiceConfig
, changeServiceConfigDependencies
, changeServiceConfigStartType
, queryServiceConfig
, closeServiceHandle
, controlService
, openSCManagerDef
, openService
, openService'
, queryServiceStatus
, setServiceStatus
, startServiceWithoutArgs
, startServiceCtrlDispatcher
, withHandle
, enumDependentServices
) where
import Control.Exception
import Control.Monad (unless, forM_)
import Control.Monad.Fix
import Data.IORef
import Foreign.C.Types (CWchar)
import Foreign.C.String (CWString, peekCWString, withCWString, withCWStringLen)
import Import
import System.Win32.SystemServices.Services.Raw
import System.Win32.SystemServices.Services.SCM_ACCESS_RIGHTS as AR
import System.Win32.SystemServices.Services.SVC_ACCESS_RIGHTS as SV
import System.Win32.SystemServices.Services.SERVICE_ACCEPT
import System.Win32.SystemServices.Services.SERVICE_CONTROL
import System.Win32.SystemServices.Services.SERVICE_ERROR
import qualified System.Win32.SystemServices.Services.SERVICE_CONTROL as SC
import System.Win32.SystemServices.Services.SERVICE_STATE
import System.Win32.SystemServices.Services.SERVICE_STATUS
import System.Win32.SystemServices.Services.SERVICE_TABLE_ENTRY
import System.Win32.SystemServices.Services.SERVICE_TYPE
import qualified System.Win32.SystemServices.Services.SERVICE_OPTIONAL as SO
import System.Win32.SystemServices.Services.QUERY_SERVICE_CONFIG
import System.Win32.SystemServices.Services.SERVICE_START_TYPE
import System.Win32.SystemServices.Services.Types
-- | A handler function is registered with the service dispatcher thread
-- from a 'ServiceMainFunction'. The first argument is a 'HANDLE' returned
-- from calling 'registerServiceCtrlHandler'. The second argument represents
-- the command this service has been directed to perform.
type HandlerFunction = HANDLE -> SERVICE_CONTROL -> IO Bool
-- | The service dispatcher thread will call each function of this type that
-- you provide. The first argument will be the name of the service. Any
-- additional command-line parameters will appear in the second argument.
--
-- Each of these functions should call 'registerServiceCtrlHandler' to
-- register a function to handle incoming commands. It should then set
-- the service's status to 'START_PENDING', and specify that no controls
-- will be accepted. At this point the function may perform any other
-- initialization steps before setting the service's status to
-- 'RUNNING'. All of this should take no more than 100ms.
type ServiceMainFunction = String -> [String] -> HANDLE -> IO ()
withCWString' :: Maybe String -> (CWString -> IO a) -> IO a
withCWString' (Just s) f = withCWString s f
withCWString' Nothing f = f nullPtr
withCWStringList' :: Maybe [String] -> (CWString -> IO a) -> IO a
withCWStringList' (Just ss) f = withCWStringList ss f
withCWStringList' Nothing f = f nullPtr
wNUL :: CWchar
wNUL = 0
withCWStringList :: [String] -> (CWString -> IO a) -> IO a
withCWStringList ss fun =
let
wsize = sizeOf (undefined :: CWchar)
size' = if (length ss) == 0
then 0
else foldl (+) 0 $ map (\s -> length s + 1) ss
size = (size' + 1) * wsize
in
allocaBytes size $ \ptr ->
do
pRef <- newIORef ptr
forM_ ss $ \s ->
withCWStringLen s $ \(p', l') -> do
let l = l' * wsize
p <- readIORef pRef
copyBytes p p' l
let nulPos = p `plusPtr` l
poke nulPos wNUL
writeIORef pRef $ nulPos `plusPtr` wsize
p <- readIORef pRef
poke p wNUL
fun ptr
peekCWStringList :: LPCWSTR -> IO [String]
peekCWStringList pStr = do
str <- peekCWString pStr
let
wsize = sizeOf (undefined :: CWchar)
len = length str * wsize
if len == 0
then return []
else do
strs <- peekCWStringList $ pStr `plusPtr` (len + wsize)
return $ str:strs
changeServiceConfig :: HANDLE -> DWORD -> DWORD -> DWORD -> Maybe String -> Maybe String -> LPDWORD -> Maybe [String] -> Maybe String -> Maybe String -> Maybe String -> IO ()
changeServiceConfig h svcType startType errCtl path' loadOrderGrp' tag srvDeps' startName' pass' displayname' =
withCWString' path' $ \path ->
withCWString' loadOrderGrp' $ \loadOrderGrp ->
withCWStringList' srvDeps' $ \srvDeps ->
withCWString' startName' $ \startName ->
withCWString' pass' $ \pass ->
withCWString' displayname' $ \displayname ->
failIfFalse_ (unwords ["changeServiceConfig"]) $
c_ChangeServiceConfig h svcType startType errCtl path loadOrderGrp tag srvDeps startName pass displayname
changeServiceConfigDependencies :: HANDLE -> [String] -> IO ()
changeServiceConfigDependencies h dependsOnSvcs =
let snc = SO.toDWORD SO.SERVICE_NO_CHANGE
in changeServiceConfig h snc snc snc Nothing Nothing nullPtr (Just dependsOnSvcs) Nothing Nothing Nothing
changeServiceConfigStartType :: HANDLE -> DWORD -> IO ()
changeServiceConfigStartType h startType =
let snc = SO.toDWORD SO.SERVICE_NO_CHANGE in
changeServiceConfig h snc startType snc Nothing Nothing nullPtr Nothing Nothing Nothing Nothing
data SERVICE_CONFIG = SERVICE_CONFIG
{ scServiceType :: Int
, scStartType :: Int
, scErrorControl :: Int
, scBinaryPathName :: String
, scLoadOrderGroup :: String
, scTagId :: Int
, scDependencies :: [String]
, scServiceStartName :: String
, scDisplayName :: String
} deriving (Show)
fromRawServiceConfig :: QUERY_SERVICE_CONFIG -> IO SERVICE_CONFIG
fromRawServiceConfig config = do
bpn <- peekCWString $ rawBinaryPathName config
ogr <- peekCWString $ rawLoadOrderGroup config
dep <- peekCWStringList $ rawDependencies config
ssn <- peekCWString $ rawServiceStartName config
sdn <- peekCWString $ rawDisplayName config
return SERVICE_CONFIG
{ scServiceType = fromIntegral $ rawServiceType config
, scStartType = fromIntegral $ rawStartType config
, scErrorControl = fromIntegral $ rawErrorControl config
, scBinaryPathName = bpn
, scLoadOrderGroup = ogr
, scTagId = fromIntegral $ rawTagId config
, scDependencies = dep
, scServiceStartName = ssn
, scDisplayName = sdn
}
failIfTrue_ :: String -> IO Bool -> IO ()
failIfTrue_ s b = do
b' <- b
failIfFalse_ s $ return $ not b'
queryServiceConfig :: HANDLE -> IO SERVICE_CONFIG
queryServiceConfig h =
alloca $ \pBufSize -> do
failIfTrue_ (unwords ["queryServiceConfig", "get buffer size"]) $
c_QueryServiceConfig h nullPtr 0 pBufSize
bufSize <- peek pBufSize
allocaBytes (fromIntegral bufSize) $ \pConfig -> do
failIfFalse_ (unwords ["queryServiceConfig", "get actual config", "buf size is", show bufSize]) $
c_QueryServiceConfig h pConfig bufSize pBufSize
config <- peek pConfig
fromRawServiceConfig config
closeServiceHandle :: HANDLE -> IO ()
closeServiceHandle =
failIfFalse_ (unwords ["CloseServiceHandle"]) . c_CloseServiceHandle
controlService :: HANDLE -> SERVICE_CONTROL -> IO SERVICE_STATUS
controlService h c = alloca $ \pStatus -> do
failIfFalse_ (unwords ["ControlService"])
$ c_ControlService h (SC.toDWORD c) pStatus
peek pStatus
openSCManagerDef :: SCM_ACCESS_RIGHTS -> IO HANDLE
openSCManagerDef ar =
failIfNull (unwords ["OpenSCManager"])
$ c_OpenSCManager nullPtr nullPtr (AR.toDWORD ar)
_openService :: HANDLE -> String -> DWORD -> IO HANDLE
_openService h n ar =
withTString n $ \lpcwstr -> failIfNull (unwords ["OpenService", n])
$ c_OpenService h lpcwstr ar
-- |Opens an existing service.
openService :: HANDLE
-- ^ MSDN documentation: A handle to the service control manager
-- database. The OpenSCManager function returns this handle.
-> String
-- ^ MSDN documentation: The name of the service to be opened. This is
-- the name specified by the lpServiceName parameter of the CreateService
-- function when the service object was created, not the service display
-- name that is shown by user interface applications to identify the service.
-> SVC_ACCESS_RIGHTS
-- ^ The list of access rights for a service.
-> IO HANDLE
-- ^ This function will raise an exception if the Win32 call returned an
-- error condition.openService h n ar =
openService h n ar = _openService h n (SV.toDWORD ar)
-- |Opens an existing service with list of access rights.
openService' :: HANDLE
-- ^ MSDN documentation: A handle to the service control manager
-- database. The OpenSCManager function returns this handle.
-> String
-- ^ MSDN documentation: The name of the service to be opened. This is
-- the name specified by the lpServiceName parameter of the CreateService
-- function when the service object was created, not the service display
-- name that is shown by user interface applications to identify the service.
-> [SVC_ACCESS_RIGHTS]
-- ^ The list of access rights for a service.
-> IO HANDLE
-- ^ This function will raise an exception if the Win32 call returned an
-- error condition.
openService' h n ars =
_openService h n (SV.flag ars)
-- |Retrieves the current status of the specified service.
queryServiceStatus :: HANDLE
-- ^ MSDN documentation: A handle to the service. This handle is returned
-- by the OpenService or the CreateService function, and it must have the
-- SERVICE_QUERY_STATUS access right. For more information, see Service
-- Security and Access Rights.
-> IO SERVICE_STATUS
-- ^ This function will raise an exception if the Win32 call returned an
-- error condition.
queryServiceStatus h = alloca $ \pStatus -> do
failIfFalse_ (unwords ["QueryServiceStatus"])
$ c_QueryServiceStatus h pStatus
peek pStatus
-- | Register an handler function to be called whenever the operating system
-- receives service control messages.
registerServiceCtrlHandlerEx :: String
-- ^ The name of the service. According to MSDN documentation this
-- argument is unused in WIN32_OWN_PROCESS type services, which is the
-- only type supported by this binding. Even so, it is recommended
-- that the name of the service be used.
--
-- MSDN description: The name of the service run by the calling thread.
-- This is the service name that the service control program specified in
-- the CreateService function when creating the service.
-> HandlerFunction
-- ^ A Handler function to be called in response to service control
-- messages. Behind the scenes this is translated into a "HandlerEx" type
-- handler.
-> IO (HANDLE, LPHANDLER_FUNCTION_EX)
-- ^ The returned handle may be used in calls to SetServiceStatus. For
-- convenience Handler functions also receive a handle for the service.
registerServiceCtrlHandlerEx str handler =
withTString str $ \lptstr ->
-- use 'ret' instead of (h', _) to avoid divergence.
mfix $ \ret -> do
fpHandler <- handlerToFunPtr $ toHandlerEx (fst ret) handler
h <- failIfNull (unwords ["RegisterServiceCtrlHandlerEx", str])
$ c_RegisterServiceCtrlHandlerEx lptstr fpHandler nullPtr
return (h, fpHandler)
-- |Updates the service control manager's status information for the calling
-- service.
setServiceStatus :: HANDLE
-- ^ MSDN documentation: A handle to the status information structure for
-- the current service. This handle is returned by the
-- RegisterServiceCtrlHandlerEx function.
-> SERVICE_STATUS
-- ^ MSDN documentation: A pointer to the SERVICE_STATUS structure the
-- contains the latest status information for the calling service.
-> IO ()
-- ^ This function will raise an exception if the Win32 call returned an
-- error condition.
setServiceStatus h status =
with status $ \pStatus -> do
failIfFalse_ (unwords ["SetServiceStatus", show h, show status])
$ c_SetServiceStatus h pStatus
-- |Starts a service.
startServiceWithoutArgs :: HANDLE -> IO ()
-- ^ MSDN documentation: A handle to the service. This handle is returned
-- by the OpenService or CreateService function, and it must have the
-- SERVICE_START access right.
startServiceWithoutArgs h =
failIfFalse_ (unwords ["StartService"])
$ c_StartService h 0 nullPtr
-- |Register a callback function to initialize the service, which will be
-- called by the operating system immediately. startServiceCtrlDispatcher
-- will block until the provided callback function returns.
--
-- MSDN documentation: Connects the main thread of a service process to the
-- service control manager, which causes the thread to be the service control
-- dispatcher thread for the calling process.
startServiceCtrlDispatcher :: String
-- ^ The name of the service. According to MSDN documentation this
-- argument is unused in WIN32_OWN_PROCESS type services, which is the
-- only type supported by this binding. Even so, it is recommended
-- that the name of the service be used.
--
-- MSDN description: The name of the service run by the calling thread.
-- This is the service name that the service control program specified in
-- the CreateService function when creating the service.
-> DWORD
-- ^
-- [@waitHint@] The estimated time required for a pending start, stop,
-- pause, or continue operation, in milliseconds.
-> HandlerFunction
-> ServiceMainFunction
-- ^ This is a callback function that will be called by the operating
-- system whenever the service is started. It should perform service
-- initialization including the registration of a handler function.
-- MSDN documentation gives conflicting advice as to whether this function
-- should return before the service has entered the stopped state.
-- In the official example the service main function blocks until the
-- service is ready to stop.
-> IO ()
-- ^ An exception will be raised if the underlying Win32 call returns an
-- error condition.
startServiceCtrlDispatcher name wh handler main =
withTString name $ \lptstr ->
bracket (toSMF main handler wh >>= smfToFunPtr) freeHaskellFunPtr $ \fpMain ->
withArray [SERVICE_TABLE_ENTRY lptstr fpMain, nullSTE] $ \pSTE ->
failIfFalse_ (unwords ["StartServiceCtrlDispatcher", name]) $ do
c_StartServiceCtrlDispatcher pSTE
toSMF :: ServiceMainFunction -> HandlerFunction -> DWORD -> IO SERVICE_MAIN_FUNCTION
toSMF f handler wh = return $ \len pLPTSTR -> do
lptstrx <- peekArray (fromIntegral len) pLPTSTR
args <- mapM peekTString lptstrx
-- MSDN guarantees args will have at least 1 member.
let name = head args
(h, fpHandler) <- registerServiceCtrlHandlerEx name handler
setServiceStatus h $ SERVICE_STATUS SERVICE_WIN32_OWN_PROCESS SERVICE_START_PENDING [] nO_ERROR 0 0 wh
f name (tail args) h
freeHaskellFunPtr fpHandler
-- This was originally written with older style handle functions in mind.
-- I'm now using HandlerEx style functions, and need to add support for
-- the extra parameters here.
toHandlerEx :: HANDLE -> HandlerFunction -> HANDLER_FUNCTION_EX
toHandlerEx h f = \dwControl _ _ _ ->
case SC.fromDWORD dwControl of
Right control -> do
handled <- f h control
case control of
INTERROGATE -> return nO_ERROR
-- If we ever support extended control codes this will have to
-- change. see "Dev Center - Desktop > Docs > Desktop app
-- development documentation > System Services > Services >
-- Service Reference > Service Functions > HandlerEx".
_ -> return $ if handled then nO_ERROR
else eRROR_CALL_NOT_IMPLEMENTED
Left _ -> return eRROR_CALL_NOT_IMPLEMENTED
withHandle :: IO HANDLE -> (HANDLE -> IO a) -> IO a
withHandle before = bracket before closeServiceHandle
data EnumServiceStatus = EnumServiceStatus
{ enumServiceName :: String
, enumDisplayName :: String
, enumServiceStatus :: SERVICE_STATUS
}
enumDependentServices :: HANDLE -> EnumServiceState -> IO [EnumServiceStatus]
enumDependentServices hService ess =
alloca $ \pcbBytesNeeded ->
alloca $ \lpServicesReturned -> do
res <- c_EnumDependentServices hService (enumServiceStateToDWORD ess)
nullPtr 0 pcbBytesNeeded lpServicesReturned
if res
then return [] -- The only case when call without a buffer succeeds is when no buffer is needed.
else do
lastErr <- getLastError
unless (lastErr == eRROR_MORE_DATA) $
failWith "EnumDependentServices" lastErr
bytesNeeded <- peek pcbBytesNeeded
allocaBytes (fromIntegral bytesNeeded) $ \lpServices -> do
failIfFalse_ "EnumDependentServices" $ c_EnumDependentServices hService (enumServiceStateToDWORD ess)
lpServices bytesNeeded pcbBytesNeeded lpServicesReturned
actualServices <- peek lpServicesReturned
rawStatuses <- peekArray (fromIntegral actualServices) lpServices
mapM rawEssToEss rawStatuses
where
rawEssToEss rawEss = do
svcName <- peekCWString $ rawESSServiceName rawEss
dispName <- peekCWString $ rawESSDisplayName rawEss
return EnumServiceStatus
{ enumServiceName = svcName
, enumDisplayName = dispName
, enumServiceStatus = rawESSServiceStatus rawEss
}
|
nick0x01/Win32-services
|
src/System/Win32/SystemServices/Services.hs
|
Haskell
|
bsd-3-clause
| 18,709
|
import Criterion.Main
import IOCP.Windows
main = defaultMain [bench "getLastError" getLastError]
|
joeyadams/hs-windows-iocp
|
lab/bench-getLastError.hs
|
Haskell
|
bsd-3-clause
| 98
|
{-# LANGUAGE OverloadedStrings #-}
module ReadXLSX.AllSheetsToJSON
where
import Codec.Xlsx
import Data.Aeson (encode, Value)
import Data.ByteString.Lazy (ByteString)
import qualified Data.Map as DM
import Data.Text (Text)
import ReadXLSX.SheetToDataframe
allSheetsToDataframe :: Xlsx -> (Cell -> Value) -> Bool -> ByteString
allSheetsToDataframe xlsx cellToValue header = encode $
DM.map (\sheet -> sheetToMapList sheet cellToValue header)
nonEmptySheets
where nonEmptySheets = DM.filter isNotEmpty (DM.map _wsCells $ DM.fromList (_xlSheets xlsx))
isNotEmpty cellmap = DM.keys cellmap /= []
allSheetsToTwoDataframes :: Xlsx -> Text -> (Cell -> Value) -> Text -> (Cell -> Value) -> Bool -> Bool -> ByteString
allSheetsToTwoDataframes xlsx key1 cellToValue1 key2 cellToValue2 header toNull =
encode $
DM.map (\sheet -> sheetToTwoMapLists sheet key1 cellToValue1 key2 cellToValue2 header toNull)
nonEmptySheets
where nonEmptySheets = DM.filter isNotEmpty (DM.map _wsCells $ DM.fromList (_xlSheets xlsx))
isNotEmpty cellmap = DM.keys cellmap /= []
-- encode $ if toNull then out else twoDataframes
-- where twoDataframes = sheetToTwoMapLists cells key1 cellToValue1 key2 cellToValue2 header
-- out = if isNullDataframe df2 then DM.fromList [(key1, df1), (key2, [DHSI.empty])] else twoDataframes
-- df1 = twoDataframes DM.! key1
-- df2 = twoDataframes DM.! key2
|
stla/jsonxlsx
|
src/ReadXLSX/AllSheetsToJSON.hs
|
Haskell
|
bsd-3-clause
| 1,648
|
module Termination.Generaliser where
import Core.Renaming (Out)
import Core.Syntax (Var)
import Evaluator.Syntax
import Utilities (FinMap, FinSet, Tag, Tagged, injectTag, tag, tagInt)
import qualified Data.IntMap as IM
import qualified Data.IntSet as IS
data Generaliser = Generaliser
{ generaliseStackFrame :: Tagged StackFrame -> Bool
, generaliseHeapBinding :: Out Var -> HeapBinding -> Bool
}
generaliseNothing :: Generaliser
generaliseNothing = Generaliser (\_ -> False) (\_ _ -> False)
generaliserFromGrowing :: FinMap Bool -> Generaliser
generaliserFromGrowing = generaliserFromFinSet . IM.keysSet . IM.filter id
generaliserFromFinSet :: FinSet -> Generaliser
generaliserFromFinSet generalise_what = Generaliser
{ generaliseStackFrame =
\kf -> should_generalise (stackFrameTag' kf)
, generaliseHeapBinding =
\_ hb -> maybe False (should_generalise . pureHeapBindingTag') $ heapBindingTag hb
}
where
should_generalise tg = IS.member (tagInt tg) generalise_what
pureHeapBindingTag' :: Tag -> Tag
pureHeapBindingTag' = injectTag 5
stackFrameTag' :: Tagged StackFrame -> Tag
stackFrameTag' = injectTag 3 . tag
qaTag' :: Anned QA -> Tag
qaTag' = injectTag 2 . annedTag
|
osa1/chsc
|
Termination/Generaliser.hs
|
Haskell
|
bsd-3-clause
| 1,227
|
{-# LANGUAGE RecordWildCards #-}
module Target
( targetRules
)
where
import Control.Applicative ((<$>))
import Control.Monad (forM_, when)
import Development.Shake
import Development.Shake.FilePath
import Config
import Dirs
import LocalCommand
import HaddockMaster
import OS
import Paths
import PlatformDB
import Types
import Utils
targetRules :: BuildConfig -> Rules ()
targetRules bc = do
buildRules
installRules bc
targetDir ~> do
hpRel <- askHpRelease
bc' <- askBuildConfig
let OS{..} = osFromConfig bc'
let packages = platformPackages hpRel
need $ vdir ghcVirtualTarget
: dir (haddockDocDir bc')
: map (dir . (targetDir </+>) . osPackageTargetDir) packages
osTargetAction
buildRules :: Rules ()
buildRules = do
packageBuildDir PackageWildCard %/> \buildDir -> do
hpRel <- askHpRelease
bc <- askBuildConfig
buildAction buildDir hpRel bc
buildAction :: FilePath -> Release -> BuildConfig -> Action ()
buildAction buildDir hpRel bc = do
need [ dir sourceDir, vdir ghcVirtualTarget ]
needsAlex <- usesTool ["//*.x", "//*.lx"]
needsHappy <- usesTool ["//*.y", "//*.ly"]
-- These are not *all* the dependencies; just those of the HP
-- packages, not those from GHC. depsLibs is just the libraries,
-- while deps adds any HP packages which provide needed tools.
depsLibs <- map read <$> readFileLines (packageDepsFile pkg)
deps <-
return $ depsLibs ++ needsAlex ?: [alexVer]
++ needsHappy ?: [happyVer]
putNormal $ show pkg ++ " needs " ++ unwords (map show deps)
need $ map (dir . packageBuildDir) deps
putNormal $ ">>> Building " ++ show pkg
command_ [] "cp" ["-pR", sourceDir, buildDir]
ghcPkgVerbosity <- shakeToGhcPkgVerbosity
removeDirectoryRecursive depsDB
localCommand' [] "ghc-pkg" ["init", depsDB]
forM_ deps $ \d -> do
let inplace = packageInplaceConf d
hasInplace <- doesFileExist inplace
when hasInplace $
localCommand' [] "ghc-pkg"
[ "register"
, "--package-db=" ++ depsDB
, "--verbose=" ++ show ghcPkgVerbosity
, inplace
]
cabalVerbosity <- show . fromEnum <$> shakeToCabalVerbosity
let cabal c as = localCommand' [Cwd buildDir] "cabal" $
c : ("--verbose=" ++ cabalVerbosity) : as
when (not isAlexOrHappy) $
cabal "clean" [] -- This is a hack to handle when packages, other
-- than alex or happy themselves, have outdated
-- bootstrap files in their sdist tarballs.
cabal "configure" $ confOpts needsAlex needsHappy
cabal "build" []
cabal "register"
["--gen-pkg-config=" ++ packageTargetConf pkg ® buildDir]
osPackagePostRegister pkg
cabal "register"
["--inplace"
, "--gen-pkg-config=" ++ packageInplaceConf pkg ® buildDir]
cReadArgs <- map (haddockReadArg . osGhcPkgPathMunge pkgHtmlDir)
<$> haddockAllCorePkgLocs hpRel bc
pReadArgs <- map (haddockReadArg . osPlatformPkgPathMunge pkgHtmlDir)
<$> haddockPlatformPkgLocs depsLibs
cabal "haddock" $
[ "--hyperlink-source" -- TODO(mzero): make optional
, "--with-haddock=" ++ haddockExe ® buildDir
]
++ map (\s -> "--haddock-option=" ++ s) (cReadArgs ++ pReadArgs)
where
OS{..} = osFromConfig bc
pkg = extractPackage buildDir
sourceDir = packageSourceDir pkg
depsDB = packageDepsDB pkg
isAlexOrHappy = pkgName pkg `elem` ["alex", "happy"]
usesTool pats =
if not isAlexOrHappy
then (not . null) <$> getDirectoryFiles sourceDir pats
else return False -- don't depend on yourself!
happyExe = packageBuildDir happyVer </> "dist/build/happy/happy"
happyTemplateDir = packageBuildDir happyVer
alexExe = packageBuildDir alexVer </> "dist/build/alex/alex"
haddockExe = ghcLocalDir </> "bin/haddock"
haveCabalInstall = False
cabalInstallDir = undefined
doProfiling = True
doShared = osDoShared
confOpts needsAlex needsHappy =
osPackageConfigureExtraArgs pkg
++ map ("--package-db="++) [ "clear", "global", "../package.conf.d" ]
++ needsAlex ?: [ "--with-alex=" ++ alexExe ® buildDir ]
++ needsHappy ?: [ "--with-happy=" ++ happyExe ® buildDir
, "--happy-options=--template=" ++ happyTemplateDir ® buildDir
]
++ haveCabalInstall ?: [ "--with-cabal-install=" ++ cabalInstallDir ]
++ doProfiling ?: [ "--enable-library-profiling" ]
++ doShared ?: [ "--enable-shared" ]
b ?: l = if b then l else []
alexVer = findPackage "alex"
happyVer = findPackage "happy"
findPackage s = case filter ((==s) . pkgName) . allPackages $ hpRel of
(p:_) -> p
[] -> error $ "Can't find needed package " ++ s ++ " in HP."
pkgHtmlDir = osPkgHtmlDir pkg
installRules :: BuildConfig -> Rules ()
installRules bc = do
targetDir </+> osPackageTargetDir PackageWildCard %/> \targetPkgDir -> do
let pkg = read $ takeFileName targetPkgDir :: Package
let buildDir = packageBuildDir pkg
need [ dir buildDir ]
-- The reason to "copy" rather than "install" is to avoid actually
-- executing anything from within the targetDir, thus keeping it
-- pristine, just as it will be for the actual end-user when first
-- installed.
localCommand' [Cwd buildDir]
"cabal" ["copy", "--destdir=" ++ targetDir ® buildDir]
osPackageInstallAction pkg
where
OS{..} = osFromConfig bc
|
bgamari/haskell-platform
|
hptool/src/Target.hs
|
Haskell
|
bsd-3-clause
| 6,025
|
-----------------------------------------------------------------------------
-- |
-- Module : Language.Pylon.Util.Generics
-- Copyright : Lukas Heidemann 2014
-- License : BSD
--
-- Maintainer : lukasheidemann@gmail.com
-- Stability : experimental
-- Portability : semi-portable
--------------------------------------------------------------------------------
module Language.Pylon.Util.Generics where
--------------------------------------------------------------------------------
import Data.Data
import Data.Typeable
import Data.Generics.Uniplate.Data
import Data.Generics.Str
--------------------------------------------------------------------------------
-- Traversals
--------------------------------------------------------------------------------
transformCtx :: (Monad m, Data on) => (on -> [m on -> m on]) -> (on -> m on) -> on -> m on
transformCtx gs f x = cur' >>= f . gen . strUn where
(cur, gen) = uniplate x
(strL, strUn) = strStructure cur
gs' = gs x ++ repeat id
cur' = sequence -- sequence and convert back to str
$ zipWith ($) gs' -- apply contexts
$ fmap (transformCtx gs f) -- transform children
$ strL -- str to list
|
zrho/pylon
|
src/Language/Pylon/Util/Generics.hs
|
Haskell
|
bsd-3-clause
| 1,242
|
{-# LANGUAGE PartialTypeSignatures #-}
{-# OPTIONS_GHC -fno-warn-partial-type-signatures #-}
module MultiClockFifo where
import CLaSH.Prelude
import CLaSH.Prelude.Explicit
import Data.Maybe (isJust)
fifoMem wclk rclk addrSize wfull raddr wdataM =
asyncRam' wclk rclk
(pow2SNat addrSize)
raddr
(mux (not <$> wfull)
wdataM
(pure Nothing))
ptrCompareT addrSize flagGen (bin,ptr,flag) (s_ptr,inc) =
((bin',ptr',flag')
,(flag,addr,ptr))
where
-- GRAYSTYLE2 pointer
bin' = bin + boolToBV (inc && not flag)
ptr' = (bin' `shiftR` 1) `xor` bin'
addr = slice (addrSize `subSNat` d1) d0 bin
flag' = flagGen ptr' s_ptr
-- FIFO empty: when next pntr == synchronized wptr or on reset
isEmpty = (==)
rptrEmptyInit = (0,0,True)
-- FIFO full: when next pntr == synchonized {~wptr[addrSize:addrSize-1],wptr[addrSize-1:0]}
isFull addrSize ptr s_ptr =
ptr == complement (slice addrSize (addrSize `subSNat` d1) s_ptr) ++#
slice (addrSize `subSNat` d2) d0 s_ptr
wptrFullInit = (0,0,False)
-- Dual flip-flip synchroniser
ptrSync clk1 clk2 = register' clk2 0
. register' clk2 0
. unsafeSynchronizer clk1 clk2
-- Async FIFO synchroniser
fifo
:: _
=> SNat (addrSize + 2)
-> SClock wclk
-> SClock rclk
-> Signal' rclk Bool
-> Signal' wclk (Maybe a)
-> (Signal' rclk a, Signal' rclk Bool, Signal' wclk Bool)
fifo addrSize wclk rclk rinc wdataM = (rdata,rempty,wfull)
where
s_rptr = ptrSync rclk wclk rptr
s_wptr = ptrSync wclk rclk wptr
rdata = fifoMem wclk rclk addrSize wfull raddr
(liftA2 (,) <$> (Just <$> waddr) <*> wdataM)
(rempty,raddr,rptr) = mealyB' rclk (ptrCompareT addrSize isEmpty) rptrEmptyInit
(s_wptr,rinc)
(wfull,waddr,wptr) = mealyB' wclk (ptrCompareT addrSize (isFull addrSize))
wptrFullInit (s_rptr,isJust <$> wdataM)
|
trxeste/wrk
|
haskell/cl3sh/MultiClockFifo.hs
|
Haskell
|
bsd-3-clause
| 2,032
|
--------------------------------------------------------------------------
-- |
-- Module : Language.Assembly.X86
-- Copyright : (c) Martin Grabmueller and Dirk Kleeblatt
-- License : BSD3
--
-- Maintainer : martin@grabmueller.de,klee@cs.tu-berlin.de
-- Stability : provisional
-- Portability : portable
--
-- Disassembler for x86 machine code.
--
-- This is a disassembler for object code for the x86 architecture.
-- It provides functions for disassembling byte arrays, byte lists and
-- memory blocks containing raw binary code.
--
-- Features:
--
-- - Disassembles memory blocks, lists or arrays of bytes into lists of
-- instructions.
--
-- - Abstract instructions provide as much information as possible about
-- opcodes, addressing modes or operand sizes, allowing for detailed
-- output.
--
-- - Provides functions for displaying instructions in Intel or AT&T
-- style (like the GNU tools)
--
-- Differences to GNU tools, like gdb or objdump:
--
-- - Displacements are shown in decimal, with sign if negative.
--
-- Missing:
--
-- - LOCK and repeat prefixes are recognized, but not contained in the
-- opcodes of instructions.
--
-- - Support for 16-bit addressing modes. Could be added when needed.
--
-- - Complete disassembly of all 64-bit instructions. I have tried to
-- disassemble them properly but have been limited to the information
-- in the docs, because I have no 64-bit machine to test on. This will
-- probably change when I get GNU as to produce 64-bit object files.
--
-- - Not all MMX and SSE/SSE2/SSE3 instructions are decoded yet. This is
-- just a matter of missing time.
--
-- - segment override prefixes are decoded, but not appended to memory
-- references
--
-- On the implementation:
--
-- This disassembler uses the Parsec parser combinators, working on byte
-- lists. This proved to be very convenient, as the combinators keep
-- track of the current position, etc.
--------------------------------------------------------------------------
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE FlexibleContexts #-}
module Language.Assembly.X86 (
-- * Types
Opcode,
Operand(..),
InstrOperandSize(..),
Instruction(..),
ShowStyle(..),
Config(..),
-- * Functions
disassembleBlock,
disassembleList,
disassembleArray,
disassembleFile,
disassembleBlockWithConfig,
disassembleListWithConfig,
disassembleArrayWithConfig,
disassembleFileWithConfig,
showIntel,
showAtt,
defaultConfig
) where
import Data.Array.IArray
import Data.Char
import Foreign
import Language.Assembly.X86.Instruction
import Language.Assembly.X86.Parse
import Language.Assembly.X86.Print
import Text.Parsec hiding (many, (<|>))
-- | Disassemble a block of memory. Starting at the location
-- pointed to by the given pointer, the given number of bytes are
-- disassembled.
disassembleBlock :: Ptr Word8 -> Int -> IO (Either ParseError [Instruction])
disassembleBlock ptr len =
disassembleBlockWithConfig defaultConfig{confStartAddr = fromIntegral (minusPtr ptr nullPtr)}
ptr len
disassembleBlockWithConfig :: Config -> Ptr Word8 -> Int -> IO (Either ParseError [Instruction])
disassembleBlockWithConfig config ptr len =
do l <- toList ptr len 0 []
parseInstructions (configToState config) (reverse l)
where toList :: (Ptr Word8) -> Int -> Int -> [Word8] -> IO [Word8]
toList ptr len idx acc
| idx < len = do p <- peekByteOff ptr idx
toList ptr len (idx + 1) (p : acc)
--return (p : r)
| idx >= len = return acc
-- | Disassemble the contents of the given array.
disassembleArray :: (Monad m, IArray a Word8, Ix i) =>
a i Word8 -> m (Either ParseError [Instruction])
disassembleArray arr = disassembleArrayWithConfig defaultConfig arr
disassembleArrayWithConfig :: (Monad m, IArray a Word8, Ix i) => Config ->
a i Word8 -> m (Either ParseError [Instruction])
disassembleArrayWithConfig config arr = parseInstructions (configToState config) l
where l = elems arr
-- | Disassemble the contents of the given list.
disassembleList :: (Monad m) =>
[Word8] -> m (Either ParseError [Instruction])
disassembleList ls = disassembleListWithConfig defaultConfig ls
disassembleListWithConfig :: (Monad m) => Config ->
[Word8] -> m (Either ParseError [Instruction])
disassembleListWithConfig config ls =
parseInstructions (configToState config) ls
disassembleFile :: FilePath -> IO (Either ParseError [Instruction])
disassembleFile filename = disassembleFileWithConfig defaultConfig filename
disassembleFileWithConfig
:: Config -> FilePath -> IO (Either ParseError [Instruction])
disassembleFileWithConfig config filename = do
l <- readFile filename
parseInstructions (configToState config) (map (fromIntegral . ord) l)
instrToString :: [Instruction] -> ShowStyle -> [[Char]]
instrToString insts style =
map showInstr insts
where
showInstr = case style of
IntelStyle -> showIntel
AttStyle -> showAtt
-- | Test function for disassembling the contents of a binary file and
-- displaying it in the provided style ("IntelStyle" or "AttStyle").
testFile :: FilePath -> ShowStyle -> IO ()
testFile fname style = do
l <- readFile fname
i <- parseInstructions defaultState (map (fromIntegral . ord) l)
case i of
Left err -> putStrLn (show err)
Right i' -> mapM_ (putStrLn . showInstr) i'
where
showInstr = case style of
IntelStyle -> showIntel
AttStyle -> showAtt
|
cnc-patch/disass
|
src/Language/Assembly/X86.hs
|
Haskell
|
bsd-3-clause
| 5,729
|
module Control.ComonadTrans where
import Prelude()
import Control.Comonad
class ComonadTrans f where
lower ::
Comonad g =>
f g a
-> g a
|
tonymorris/lens-proposal
|
src/Control/ComonadTrans.hs
|
Haskell
|
bsd-3-clause
| 152
|
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.PackageDescription.Check
-- Copyright : Lennart Kolmodin 2008
-- License : BSD3
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- This has code for checking for various problems in packages. There is one
-- set of checks that just looks at a 'PackageDescription' in isolation and
-- another set of checks that also looks at files in the package. Some of the
-- checks are basic sanity checks, others are portability standards that we'd
-- like to encourage. There is a 'PackageCheck' type that distinguishes the
-- different kinds of check so we can see which ones are appropriate to report
-- in different situations. This code gets uses when configuring a package when
-- we consider only basic problems. The higher standard is uses when when
-- preparing a source tarball and by Hackage when uploading new packages. The
-- reason for this is that we want to hold packages that are expected to be
-- distributed to a higher standard than packages that are only ever expected
-- to be used on the author's own environment.
module Distribution.PackageDescription.Check (
-- * Package Checking
PackageCheck(..),
checkPackage,
checkConfiguredPackage,
-- ** Checking package contents
checkPackageFiles,
checkPackageContent,
CheckPackageContentOps(..),
checkPackageFileNames,
) where
import Distribution.PackageDescription
import Distribution.PackageDescription.Configuration
import Distribution.Compiler
import Distribution.System
import Distribution.License
import Distribution.Simple.CCompiler
import Distribution.Simple.Utils hiding (findPackageDesc, notice)
import Distribution.Version
import Distribution.Package
import Distribution.Text
import Language.Haskell.Extension
import Data.Maybe
( isNothing, isJust, catMaybes, mapMaybe, maybeToList, fromMaybe )
import Data.List (sort, group, isPrefixOf, nub, find)
import Control.Monad
( filterM, liftM )
import qualified System.Directory as System
( doesFileExist, doesDirectoryExist )
import qualified Data.Map as Map
import qualified Text.PrettyPrint as Disp
import Text.PrettyPrint ((<>), (<+>))
import qualified System.Directory (getDirectoryContents)
import System.IO (openBinaryFile, IOMode(ReadMode), hGetContents)
import System.FilePath
( (</>), takeExtension, isRelative, isAbsolute
, splitDirectories, splitPath, splitExtension )
import System.FilePath.Windows as FilePath.Windows
( isValid )
-- | Results of some kind of failed package check.
--
-- There are a range of severities, from merely dubious to totally insane.
-- All of them come with a human readable explanation. In future we may augment
-- them with more machine readable explanations, for example to help an IDE
-- suggest automatic corrections.
--
data PackageCheck =
-- | This package description is no good. There's no way it's going to
-- build sensibly. This should give an error at configure time.
PackageBuildImpossible { explanation :: String }
-- | A problem that is likely to affect building the package, or an
-- issue that we'd like every package author to be aware of, even if
-- the package is never distributed.
| PackageBuildWarning { explanation :: String }
-- | An issue that might not be a problem for the package author but
-- might be annoying or detrimental when the package is distributed to
-- users. We should encourage distributed packages to be free from these
-- issues, but occasionally there are justifiable reasons so we cannot
-- ban them entirely.
| PackageDistSuspicious { explanation :: String }
-- | Like PackageDistSuspicious but will only display warnings
-- rather than causing abnormal exit when you run 'cabal check'.
| PackageDistSuspiciousWarn { explanation :: String }
-- | An issue that is OK in the author's environment but is almost
-- certain to be a portability problem for other environments. We can
-- quite legitimately refuse to publicly distribute packages with these
-- problems.
| PackageDistInexcusable { explanation :: String }
deriving (Eq)
instance Show PackageCheck where
show notice = explanation notice
check :: Bool -> PackageCheck -> Maybe PackageCheck
check False _ = Nothing
check True pc = Just pc
checkSpecVersion :: PackageDescription -> [Int] -> Bool -> PackageCheck
-> Maybe PackageCheck
checkSpecVersion pkg specver cond pc
| specVersion pkg >= Version specver [] = Nothing
| otherwise = check cond pc
-- ------------------------------------------------------------
-- * Standard checks
-- ------------------------------------------------------------
-- | Check for common mistakes and problems in package descriptions.
--
-- This is the standard collection of checks covering all aspects except
-- for checks that require looking at files within the package. For those
-- see 'checkPackageFiles'.
--
-- It requires the 'GenericPackageDescription' and optionally a particular
-- configuration of that package. If you pass 'Nothing' then we just check
-- a version of the generic description using 'flattenPackageDescription'.
--
checkPackage :: GenericPackageDescription
-> Maybe PackageDescription
-> [PackageCheck]
checkPackage gpkg mpkg =
checkConfiguredPackage pkg
++ checkConditionals gpkg
++ checkPackageVersions gpkg
++ checkDevelopmentOnlyFlags gpkg
where
pkg = fromMaybe (flattenPackageDescription gpkg) mpkg
--TODO: make this variant go away
-- we should always know the GenericPackageDescription
checkConfiguredPackage :: PackageDescription -> [PackageCheck]
checkConfiguredPackage pkg =
checkSanity pkg
++ checkFields pkg
++ checkLicense pkg
++ checkSourceRepos pkg
++ checkGhcOptions pkg
++ checkCCOptions pkg
++ checkCPPOptions pkg
++ checkPaths pkg
++ checkCabalVersion pkg
-- ------------------------------------------------------------
-- * Basic sanity checks
-- ------------------------------------------------------------
-- | Check that this package description is sane.
--
checkSanity :: PackageDescription -> [PackageCheck]
checkSanity pkg =
catMaybes [
check (null . (\(PackageName n) -> n) . packageName $ pkg) $
PackageBuildImpossible "No 'name' field."
, check (null . versionBranch . packageVersion $ pkg) $
PackageBuildImpossible "No 'version' field."
, check (all ($ pkg) [ null . executables
, null . testSuites
, null . benchmarks
, isNothing . library ]) $
PackageBuildImpossible
"No executables, libraries, tests, or benchmarks found. Nothing to do."
, check (not (null duplicateNames)) $
PackageBuildImpossible $ "Duplicate sections: " ++ commaSep duplicateNames
++ ". The name of every executable, test suite, and benchmark section in"
++ " the package must be unique."
]
--TODO: check for name clashes case insensitively: windows file systems cannot
--cope.
++ maybe [] (checkLibrary pkg) (library pkg)
++ concatMap (checkExecutable pkg) (executables pkg)
++ concatMap (checkTestSuite pkg) (testSuites pkg)
++ concatMap (checkBenchmark pkg) (benchmarks pkg)
++ catMaybes [
check (specVersion pkg > cabalVersion) $
PackageBuildImpossible $
"This package description follows version "
++ display (specVersion pkg) ++ " of the Cabal specification. This "
++ "tool only supports up to version " ++ display cabalVersion ++ "."
]
where
exeNames = map exeName $ executables pkg
testNames = map testName $ testSuites pkg
bmNames = map benchmarkName $ benchmarks pkg
duplicateNames = dups $ exeNames ++ testNames ++ bmNames
checkLibrary :: PackageDescription -> Library -> [PackageCheck]
checkLibrary pkg lib =
catMaybes [
check (not (null moduleDuplicates)) $
PackageBuildImpossible $
"Duplicate modules in library: "
++ commaSep (map display moduleDuplicates)
-- check use of required-signatures/exposed-signatures sections
, checkVersion [1,21] (not (null (requiredSignatures lib))) $
PackageDistInexcusable $
"To use the 'required-signatures' field the package needs to specify "
++ "at least 'cabal-version: >= 1.21'."
, checkVersion [1,21] (not (null (exposedSignatures lib))) $
PackageDistInexcusable $
"To use the 'exposed-signatures' field the package needs to specify "
++ "at least 'cabal-version: >= 1.21'."
]
where
checkVersion :: [Int] -> Bool -> PackageCheck -> Maybe PackageCheck
checkVersion ver cond pc
| specVersion pkg >= Version ver [] = Nothing
| otherwise = check cond pc
moduleDuplicates = dups (libModules lib ++
map moduleReexportName (reexportedModules lib))
checkExecutable :: PackageDescription -> Executable -> [PackageCheck]
checkExecutable pkg exe =
catMaybes [
check (null (modulePath exe)) $
PackageBuildImpossible $
"No 'main-is' field found for executable " ++ exeName exe
, check (not (null (modulePath exe))
&& (not $ fileExtensionSupportedLanguage $ modulePath exe)) $
PackageBuildImpossible $
"The 'main-is' field must specify a '.hs' or '.lhs' file "
++ "(even if it is generated by a preprocessor), "
++ "or it may specify a C/C++/obj-C source file."
, checkSpecVersion pkg [1,17]
(fileExtensionSupportedLanguage (modulePath exe)
&& takeExtension (modulePath exe) `notElem` [".hs", ".lhs"]) $
PackageDistInexcusable $
"The package uses a C/C++/obj-C source file for the 'main-is' field. "
++ "To use this feature you must specify 'cabal-version: >= 1.18'."
, check (not (null moduleDuplicates)) $
PackageBuildImpossible $
"Duplicate modules in executable '" ++ exeName exe ++ "': "
++ commaSep (map display moduleDuplicates)
]
where
moduleDuplicates = dups (exeModules exe)
checkTestSuite :: PackageDescription -> TestSuite -> [PackageCheck]
checkTestSuite pkg test =
catMaybes [
case testInterface test of
TestSuiteUnsupported tt@(TestTypeUnknown _ _) -> Just $
PackageBuildWarning $
quote (display tt) ++ " is not a known type of test suite. "
++ "The known test suite types are: "
++ commaSep (map display knownTestTypes)
TestSuiteUnsupported tt -> Just $
PackageBuildWarning $
quote (display tt) ++ " is not a supported test suite version. "
++ "The known test suite types are: "
++ commaSep (map display knownTestTypes)
_ -> Nothing
, check (not $ null moduleDuplicates) $
PackageBuildImpossible $
"Duplicate modules in test suite '" ++ testName test ++ "': "
++ commaSep (map display moduleDuplicates)
, check mainIsWrongExt $
PackageBuildImpossible $
"The 'main-is' field must specify a '.hs' or '.lhs' file "
++ "(even if it is generated by a preprocessor), "
++ "or it may specify a C/C++/obj-C source file."
, checkSpecVersion pkg [1,17] (mainIsNotHsExt && not mainIsWrongExt) $
PackageDistInexcusable $
"The package uses a C/C++/obj-C source file for the 'main-is' field. "
++ "To use this feature you must specify 'cabal-version: >= 1.18'."
]
where
moduleDuplicates = dups $ testModules test
mainIsWrongExt = case testInterface test of
TestSuiteExeV10 _ f -> not $ fileExtensionSupportedLanguage f
_ -> False
mainIsNotHsExt = case testInterface test of
TestSuiteExeV10 _ f -> takeExtension f `notElem` [".hs", ".lhs"]
_ -> False
checkBenchmark :: PackageDescription -> Benchmark -> [PackageCheck]
checkBenchmark _pkg bm =
catMaybes [
case benchmarkInterface bm of
BenchmarkUnsupported tt@(BenchmarkTypeUnknown _ _) -> Just $
PackageBuildWarning $
quote (display tt) ++ " is not a known type of benchmark. "
++ "The known benchmark types are: "
++ commaSep (map display knownBenchmarkTypes)
BenchmarkUnsupported tt -> Just $
PackageBuildWarning $
quote (display tt) ++ " is not a supported benchmark version. "
++ "The known benchmark types are: "
++ commaSep (map display knownBenchmarkTypes)
_ -> Nothing
, check (not $ null moduleDuplicates) $
PackageBuildImpossible $
"Duplicate modules in benchmark '" ++ benchmarkName bm ++ "': "
++ commaSep (map display moduleDuplicates)
, check mainIsWrongExt $
PackageBuildImpossible $
"The 'main-is' field must specify a '.hs' or '.lhs' file "
++ "(even if it is generated by a preprocessor)."
]
where
moduleDuplicates = dups $ benchmarkModules bm
mainIsWrongExt = case benchmarkInterface bm of
BenchmarkExeV10 _ f -> takeExtension f `notElem` [".hs", ".lhs"]
_ -> False
-- ------------------------------------------------------------
-- * Additional pure checks
-- ------------------------------------------------------------
checkFields :: PackageDescription -> [PackageCheck]
checkFields pkg =
catMaybes [
check (not . FilePath.Windows.isValid . display . packageName $ pkg) $
PackageDistInexcusable $
"Unfortunately, the package name '" ++ display (packageName pkg)
++ "' is one of the reserved system file names on Windows. Many tools "
++ "need to convert package names to file names so using this name "
++ "would cause problems."
, check (isNothing (buildType pkg)) $
PackageBuildWarning $
"No 'build-type' specified. If you do not need a custom Setup.hs or "
++ "./configure script then use 'build-type: Simple'."
, case buildType pkg of
Just (UnknownBuildType unknown) -> Just $
PackageBuildWarning $
quote unknown ++ " is not a known 'build-type'. "
++ "The known build types are: "
++ commaSep (map display knownBuildTypes)
_ -> Nothing
, check (isJust (setupBuildInfo pkg) && buildType pkg /= Just Custom) $
PackageBuildWarning $
"Ignoring the 'custom-setup' section because the 'build-type' is "
++ "not 'Custom'. Use 'build-type: Custom' if you need to use a "
++ "custom Setup.hs script."
, check (not (null unknownCompilers)) $
PackageBuildWarning $
"Unknown compiler " ++ commaSep (map quote unknownCompilers)
++ " in 'tested-with' field."
, check (not (null unknownLanguages)) $
PackageBuildWarning $
"Unknown languages: " ++ commaSep unknownLanguages
, check (not (null unknownExtensions)) $
PackageBuildWarning $
"Unknown extensions: " ++ commaSep unknownExtensions
, check (not (null languagesUsedAsExtensions)) $
PackageBuildWarning $
"Languages listed as extensions: "
++ commaSep languagesUsedAsExtensions
++ ". Languages must be specified in either the 'default-language' "
++ " or the 'other-languages' field."
, check (not (null ourDeprecatedExtensions)) $
PackageDistSuspicious $
"Deprecated extensions: "
++ commaSep (map (quote . display . fst) ourDeprecatedExtensions)
++ ". " ++ unwords
[ "Instead of '" ++ display ext
++ "' use '" ++ display replacement ++ "'."
| (ext, Just replacement) <- ourDeprecatedExtensions ]
, check (null (category pkg)) $
PackageDistSuspicious "No 'category' field."
, check (null (maintainer pkg)) $
PackageDistSuspicious "No 'maintainer' field."
, check (null (synopsis pkg) && null (description pkg)) $
PackageDistInexcusable "No 'synopsis' or 'description' field."
, check (null (description pkg) && not (null (synopsis pkg))) $
PackageDistSuspicious "No 'description' field."
, check (null (synopsis pkg) && not (null (description pkg))) $
PackageDistSuspicious "No 'synopsis' field."
--TODO: recommend the bug reports URL, author and homepage fields
--TODO: recommend not using the stability field
--TODO: recommend specifying a source repo
, check (length (synopsis pkg) >= 80) $
PackageDistSuspicious
"The 'synopsis' field is rather long (max 80 chars is recommended)."
-- check use of impossible constraints "tested-with: GHC== 6.10 && ==6.12"
, check (not (null testedWithImpossibleRanges)) $
PackageDistInexcusable $
"Invalid 'tested-with' version range: "
++ commaSep (map display testedWithImpossibleRanges)
++ ". To indicate that you have tested a package with multiple "
++ "different versions of the same compiler use multiple entries, "
++ "for example 'tested-with: GHC==6.10.4, GHC==6.12.3' and not "
++ "'tested-with: GHC==6.10.4 && ==6.12.3'."
]
where
unknownCompilers = [ name | (OtherCompiler name, _) <- testedWith pkg ]
unknownLanguages = [ name | bi <- allBuildInfo pkg
, UnknownLanguage name <- allLanguages bi ]
unknownExtensions = [ name | bi <- allBuildInfo pkg
, UnknownExtension name <- allExtensions bi
, name `notElem` map display knownLanguages ]
ourDeprecatedExtensions = nub $ catMaybes
[ find ((==ext) . fst) deprecatedExtensions
| bi <- allBuildInfo pkg
, ext <- allExtensions bi ]
languagesUsedAsExtensions =
[ name | bi <- allBuildInfo pkg
, UnknownExtension name <- allExtensions bi
, name `elem` map display knownLanguages ]
testedWithImpossibleRanges =
[ Dependency (PackageName (display compiler)) vr
| (compiler, vr) <- testedWith pkg
, isNoVersion vr ]
checkLicense :: PackageDescription -> [PackageCheck]
checkLicense pkg =
catMaybes [
check (license pkg == UnspecifiedLicense) $
PackageDistInexcusable
"The 'license' field is missing."
, check (license pkg == AllRightsReserved) $
PackageDistSuspicious
"The 'license' is AllRightsReserved. Is that really what you want?"
, case license pkg of
UnknownLicense l -> Just $
PackageBuildWarning $
quote ("license: " ++ l) ++ " is not a recognised license. The "
++ "known licenses are: "
++ commaSep (map display knownLicenses)
_ -> Nothing
, check (license pkg == BSD4) $
PackageDistSuspicious $
"Using 'license: BSD4' is almost always a misunderstanding. 'BSD4' "
++ "refers to the old 4-clause BSD license with the advertising "
++ "clause. 'BSD3' refers the new 3-clause BSD license."
, case unknownLicenseVersion (license pkg) of
Just knownVersions -> Just $
PackageDistSuspicious $
"'license: " ++ display (license pkg) ++ "' is not a known "
++ "version of that license. The known versions are "
++ commaSep (map display knownVersions)
++ ". If this is not a mistake and you think it should be a known "
++ "version then please file a ticket."
_ -> Nothing
, check (license pkg `notElem` [ AllRightsReserved
, UnspecifiedLicense, PublicDomain]
-- AllRightsReserved and PublicDomain are not strictly
-- licenses so don't need license files.
&& null (licenseFiles pkg)) $
PackageDistSuspicious "A 'license-file' is not specified."
]
where
unknownLicenseVersion (GPL (Just v))
| v `notElem` knownVersions = Just knownVersions
where knownVersions = [ v' | GPL (Just v') <- knownLicenses ]
unknownLicenseVersion (LGPL (Just v))
| v `notElem` knownVersions = Just knownVersions
where knownVersions = [ v' | LGPL (Just v') <- knownLicenses ]
unknownLicenseVersion (AGPL (Just v))
| v `notElem` knownVersions = Just knownVersions
where knownVersions = [ v' | AGPL (Just v') <- knownLicenses ]
unknownLicenseVersion (Apache (Just v))
| v `notElem` knownVersions = Just knownVersions
where knownVersions = [ v' | Apache (Just v') <- knownLicenses ]
unknownLicenseVersion _ = Nothing
checkSourceRepos :: PackageDescription -> [PackageCheck]
checkSourceRepos pkg =
catMaybes $ concat [[
case repoKind repo of
RepoKindUnknown kind -> Just $ PackageDistInexcusable $
quote kind ++ " is not a recognised kind of source-repository. "
++ "The repo kind is usually 'head' or 'this'"
_ -> Nothing
, check (isNothing (repoType repo)) $
PackageDistInexcusable
"The source-repository 'type' is a required field."
, check (isNothing (repoLocation repo)) $
PackageDistInexcusable
"The source-repository 'location' is a required field."
, check (repoType repo == Just CVS && isNothing (repoModule repo)) $
PackageDistInexcusable
"For a CVS source-repository, the 'module' is a required field."
, check (repoKind repo == RepoThis && isNothing (repoTag repo)) $
PackageDistInexcusable $
"For the 'this' kind of source-repository, the 'tag' is a required "
++ "field. It should specify the tag corresponding to this version "
++ "or release of the package."
, check (maybe False System.FilePath.isAbsolute (repoSubdir repo)) $
PackageDistInexcusable
"The 'subdir' field of a source-repository must be a relative path."
]
| repo <- sourceRepos pkg ]
--TODO: check location looks like a URL for some repo types.
checkGhcOptions :: PackageDescription -> [PackageCheck]
checkGhcOptions pkg =
catMaybes [
checkFlags ["-fasm"] $
PackageDistInexcusable $
"'ghc-options: -fasm' is unnecessary and will not work on CPU "
++ "architectures other than x86, x86-64, ppc or sparc."
, checkFlags ["-fvia-C"] $
PackageDistSuspicious $
"'ghc-options: -fvia-C' is usually unnecessary. If your package "
++ "needs -via-C for correctness rather than performance then it "
++ "is using the FFI incorrectly and will probably not work with GHC "
++ "6.10 or later."
, checkFlags ["-fhpc"] $
PackageDistInexcusable $
"'ghc-options: -fhpc' is not not necessary. Use the configure flag "
++ " --enable-coverage instead."
, checkFlags ["-prof"] $
PackageBuildWarning $
"'ghc-options: -prof' is not necessary and will lead to problems "
++ "when used on a library. Use the configure flag "
++ "--enable-library-profiling and/or --enable-executable-profiling."
, checkFlags ["-o"] $
PackageBuildWarning $
"'ghc-options: -o' is not needed. "
++ "The output files are named automatically."
, checkFlags ["-hide-package"] $
PackageBuildWarning $
"'ghc-options: -hide-package' is never needed. "
++ "Cabal hides all packages."
, checkFlags ["--make"] $
PackageBuildWarning $
"'ghc-options: --make' is never needed. Cabal uses this automatically."
, checkFlags ["-main-is"] $
PackageDistSuspicious $
"'ghc-options: -main-is' is not portable."
, checkFlags ["-O0", "-Onot"] $
PackageDistSuspicious $
"'ghc-options: -O0' is not needed. "
++ "Use the --disable-optimization configure flag."
, checkFlags [ "-O", "-O1"] $
PackageDistInexcusable $
"'ghc-options: -O' is not needed. "
++ "Cabal automatically adds the '-O' flag. "
++ "Setting it yourself interferes with the --disable-optimization flag."
, checkFlags ["-O2"] $
PackageDistSuspiciousWarn $
"'ghc-options: -O2' is rarely needed. "
++ "Check that it is giving a real benefit "
++ "and not just imposing longer compile times on your users."
, checkFlags ["-split-objs"] $
PackageBuildWarning $
"'ghc-options: -split-objs' is not needed. "
++ "Use the --enable-split-objs configure flag."
, checkFlags ["-optl-Wl,-s", "-optl-s"] $
PackageDistInexcusable $
"'ghc-options: -optl-Wl,-s' is not needed and is not portable to all"
++ " operating systems. Cabal 1.4 and later automatically strip"
++ " executables. Cabal also has a flag --disable-executable-stripping"
++ " which is necessary when building packages for some Linux"
++ " distributions and using '-optl-Wl,-s' prevents that from working."
, checkFlags ["-fglasgow-exts"] $
PackageDistSuspicious $
"Instead of 'ghc-options: -fglasgow-exts' it is preferable to use "
++ "the 'extensions' field."
, check ("-threaded" `elem` lib_ghc_options) $
PackageBuildWarning $
"'ghc-options: -threaded' has no effect for libraries. It should "
++ "only be used for executables."
, check ("-rtsopts" `elem` lib_ghc_options) $
PackageBuildWarning $
"'ghc-options: -rtsopts' has no effect for libraries. It should "
++ "only be used for executables."
, check (any (\opt -> "-with-rtsopts" `isPrefixOf` opt) lib_ghc_options) $
PackageBuildWarning $
"'ghc-options: -with-rtsopts' has no effect for libraries. It "
++ "should only be used for executables."
, checkAlternatives "ghc-options" "extensions"
[ (flag, display extension) | flag <- all_ghc_options
, Just extension <- [ghcExtension flag] ]
, checkAlternatives "ghc-options" "extensions"
[ (flag, extension) | flag@('-':'X':extension) <- all_ghc_options ]
, checkAlternatives "ghc-options" "cpp-options" $
[ (flag, flag) | flag@('-':'D':_) <- all_ghc_options ]
++ [ (flag, flag) | flag@('-':'U':_) <- all_ghc_options ]
, checkAlternatives "ghc-options" "include-dirs"
[ (flag, dir) | flag@('-':'I':dir) <- all_ghc_options ]
, checkAlternatives "ghc-options" "extra-libraries"
[ (flag, lib) | flag@('-':'l':lib) <- all_ghc_options ]
, checkAlternatives "ghc-options" "extra-lib-dirs"
[ (flag, dir) | flag@('-':'L':dir) <- all_ghc_options ]
, checkAlternatives "ghc-options" "frameworks"
[ (flag, fmwk) | (flag@"-framework", fmwk) <-
zip all_ghc_options (safeTail all_ghc_options) ]
, checkAlternatives "ghc-options" "extra-framework-dirs"
[ (flag, dir) | (flag@"-framework-path", dir) <-
zip all_ghc_options (safeTail all_ghc_options) ]
]
where
all_ghc_options = concatMap get_ghc_options (allBuildInfo pkg)
lib_ghc_options = maybe [] (get_ghc_options . libBuildInfo) (library pkg)
get_ghc_options bi = hcOptions GHC bi ++ hcProfOptions GHC bi
++ hcSharedOptions GHC bi
checkFlags :: [String] -> PackageCheck -> Maybe PackageCheck
checkFlags flags = check (any (`elem` flags) all_ghc_options)
ghcExtension ('-':'f':name) = case name of
"allow-overlapping-instances" -> enable OverlappingInstances
"no-allow-overlapping-instances" -> disable OverlappingInstances
"th" -> enable TemplateHaskell
"no-th" -> disable TemplateHaskell
"ffi" -> enable ForeignFunctionInterface
"no-ffi" -> disable ForeignFunctionInterface
"fi" -> enable ForeignFunctionInterface
"no-fi" -> disable ForeignFunctionInterface
"monomorphism-restriction" -> enable MonomorphismRestriction
"no-monomorphism-restriction" -> disable MonomorphismRestriction
"mono-pat-binds" -> enable MonoPatBinds
"no-mono-pat-binds" -> disable MonoPatBinds
"allow-undecidable-instances" -> enable UndecidableInstances
"no-allow-undecidable-instances" -> disable UndecidableInstances
"allow-incoherent-instances" -> enable IncoherentInstances
"no-allow-incoherent-instances" -> disable IncoherentInstances
"arrows" -> enable Arrows
"no-arrows" -> disable Arrows
"generics" -> enable Generics
"no-generics" -> disable Generics
"implicit-prelude" -> enable ImplicitPrelude
"no-implicit-prelude" -> disable ImplicitPrelude
"implicit-params" -> enable ImplicitParams
"no-implicit-params" -> disable ImplicitParams
"bang-patterns" -> enable BangPatterns
"no-bang-patterns" -> disable BangPatterns
"scoped-type-variables" -> enable ScopedTypeVariables
"no-scoped-type-variables" -> disable ScopedTypeVariables
"extended-default-rules" -> enable ExtendedDefaultRules
"no-extended-default-rules" -> disable ExtendedDefaultRules
_ -> Nothing
ghcExtension "-cpp" = enable CPP
ghcExtension _ = Nothing
enable e = Just (EnableExtension e)
disable e = Just (DisableExtension e)
checkCCOptions :: PackageDescription -> [PackageCheck]
checkCCOptions pkg =
catMaybes [
checkAlternatives "cc-options" "include-dirs"
[ (flag, dir) | flag@('-':'I':dir) <- all_ccOptions ]
, checkAlternatives "cc-options" "extra-libraries"
[ (flag, lib) | flag@('-':'l':lib) <- all_ccOptions ]
, checkAlternatives "cc-options" "extra-lib-dirs"
[ (flag, dir) | flag@('-':'L':dir) <- all_ccOptions ]
, checkAlternatives "ld-options" "extra-libraries"
[ (flag, lib) | flag@('-':'l':lib) <- all_ldOptions ]
, checkAlternatives "ld-options" "extra-lib-dirs"
[ (flag, dir) | flag@('-':'L':dir) <- all_ldOptions ]
, checkCCFlags [ "-O", "-Os", "-O0", "-O1", "-O2", "-O3" ] $
PackageDistSuspicious $
"'cc-options: -O[n]' is generally not needed. When building with "
++ " optimisations Cabal automatically adds '-O2' for C code. "
++ "Setting it yourself interferes with the --disable-optimization "
++ "flag."
]
where all_ccOptions = [ opts | bi <- allBuildInfo pkg
, opts <- ccOptions bi ]
all_ldOptions = [ opts | bi <- allBuildInfo pkg
, opts <- ldOptions bi ]
checkCCFlags :: [String] -> PackageCheck -> Maybe PackageCheck
checkCCFlags flags = check (any (`elem` flags) all_ccOptions)
checkCPPOptions :: PackageDescription -> [PackageCheck]
checkCPPOptions pkg =
catMaybes [
checkAlternatives "cpp-options" "include-dirs"
[ (flag, dir) | flag@('-':'I':dir) <- all_cppOptions]
]
where all_cppOptions = [ opts | bi <- allBuildInfo pkg
, opts <- cppOptions bi ]
checkAlternatives :: String -> String -> [(String, String)] -> Maybe PackageCheck
checkAlternatives badField goodField flags =
check (not (null badFlags)) $
PackageBuildWarning $
"Instead of " ++ quote (badField ++ ": " ++ unwords badFlags)
++ " use " ++ quote (goodField ++ ": " ++ unwords goodFlags)
where (badFlags, goodFlags) = unzip flags
checkPaths :: PackageDescription -> [PackageCheck]
checkPaths pkg =
[ PackageBuildWarning $
quote (kind ++ ": " ++ path)
++ " is a relative path outside of the source tree. "
++ "This will not work when generating a tarball with 'sdist'."
| (path, kind) <- relPaths ++ absPaths
, isOutsideTree path ]
++
[ PackageDistInexcusable $
quote (kind ++ ": " ++ path) ++ " is an absolute path."
| (path, kind) <- relPaths
, isAbsolute path ]
++
[ PackageDistInexcusable $
quote (kind ++ ": " ++ path) ++ " points inside the 'dist' "
++ "directory. This is not reliable because the location of this "
++ "directory is configurable by the user (or package manager). In "
++ "addition the layout of the 'dist' directory is subject to change "
++ "in future versions of Cabal."
| (path, kind) <- relPaths ++ absPaths
, isInsideDist path ]
++
[ PackageDistInexcusable $
"The 'ghc-options' contains the path '" ++ path ++ "' which points "
++ "inside the 'dist' directory. This is not reliable because the "
++ "location of this directory is configurable by the user (or package "
++ "manager). In addition the layout of the 'dist' directory is subject "
++ "to change in future versions of Cabal."
| bi <- allBuildInfo pkg
, (GHC, flags) <- options bi
, path <- flags
, isInsideDist path ]
where
isOutsideTree path = case splitDirectories path of
"..":_ -> True
".":"..":_ -> True
_ -> False
isInsideDist path = case map lowercase (splitDirectories path) of
"dist" :_ -> True
".":"dist":_ -> True
_ -> False
-- paths that must be relative
relPaths =
[ (path, "extra-src-files") | path <- extraSrcFiles pkg ]
++ [ (path, "extra-tmp-files") | path <- extraTmpFiles pkg ]
++ [ (path, "extra-doc-files") | path <- extraDocFiles pkg ]
++ [ (path, "data-files") | path <- dataFiles pkg ]
++ [ (path, "data-dir") | path <- [dataDir pkg]]
++ [ (path, "license-file") | path <- licenseFiles pkg ]
++ concat
[ [ (path, "c-sources") | path <- cSources bi ]
++ [ (path, "js-sources") | path <- jsSources bi ]
++ [ (path, "install-includes") | path <- installIncludes bi ]
++ [ (path, "hs-source-dirs") | path <- hsSourceDirs bi ]
| bi <- allBuildInfo pkg ]
-- paths that are allowed to be absolute
absPaths = concat
[ [ (path, "includes") | path <- includes bi ]
++ [ (path, "include-dirs") | path <- includeDirs bi ]
++ [ (path, "extra-lib-dirs") | path <- extraLibDirs bi ]
| bi <- allBuildInfo pkg ]
--TODO: check sets of paths that would be interpreted differently between Unix
-- and windows, ie case-sensitive or insensitive. Things that might clash, or
-- conversely be distinguished.
--TODO: use the tar path checks on all the above paths
-- | Check that the package declares the version in the @\"cabal-version\"@
-- field correctly.
--
checkCabalVersion :: PackageDescription -> [PackageCheck]
checkCabalVersion pkg =
catMaybes [
-- check syntax of cabal-version field
check (specVersion pkg >= Version [1,10] []
&& not simpleSpecVersionRangeSyntax) $
PackageBuildWarning $
"Packages relying on Cabal 1.10 or later must only specify a "
++ "version range of the form 'cabal-version: >= x.y'. Use "
++ "'cabal-version: >= " ++ display (specVersion pkg) ++ "'."
-- check syntax of cabal-version field
, check (specVersion pkg < Version [1,9] []
&& not simpleSpecVersionRangeSyntax) $
PackageDistSuspicious $
"It is recommended that the 'cabal-version' field only specify a "
++ "version range of the form '>= x.y'. Use "
++ "'cabal-version: >= " ++ display (specVersion pkg) ++ "'. "
++ "Tools based on Cabal 1.10 and later will ignore upper bounds."
-- check syntax of cabal-version field
, checkVersion [1,12] simpleSpecVersionSyntax $
PackageBuildWarning $
"With Cabal 1.10 or earlier, the 'cabal-version' field must use "
++ "range syntax rather than a simple version number. Use "
++ "'cabal-version: >= " ++ display (specVersion pkg) ++ "'."
-- check use of test suite sections
, checkVersion [1,8] (not (null $ testSuites pkg)) $
PackageDistInexcusable $
"The 'test-suite' section is new in Cabal 1.10. "
++ "Unfortunately it messes up the parser in older Cabal versions "
++ "so you must specify at least 'cabal-version: >= 1.8', but note "
++ "that only Cabal 1.10 and later can actually run such test suites."
-- check use of default-language field
-- note that we do not need to do an equivalent check for the
-- other-language field since that one does not change behaviour
, checkVersion [1,10] (any isJust (buildInfoField defaultLanguage)) $
PackageBuildWarning $
"To use the 'default-language' field the package needs to specify "
++ "at least 'cabal-version: >= 1.10'."
, check (specVersion pkg >= Version [1,10] []
&& (any isNothing (buildInfoField defaultLanguage))) $
PackageBuildWarning $
"Packages using 'cabal-version: >= 1.10' must specify the "
++ "'default-language' field for each component (e.g. Haskell98 or "
++ "Haskell2010). If a component uses different languages in "
++ "different modules then list the other ones in the "
++ "'other-languages' field."
-- check use of reexported-modules sections
, checkVersion [1,21]
(maybe False (not.null.reexportedModules) (library pkg)) $
PackageDistInexcusable $
"To use the 'reexported-module' field the package needs to specify "
++ "at least 'cabal-version: >= 1.21'."
-- check use of thinning and renaming
, checkVersion [1,21] (not (null depsUsingThinningRenamingSyntax)) $
PackageDistInexcusable $
"The package uses "
++ "thinning and renaming in the 'build-depends' field: "
++ commaSep (map display depsUsingThinningRenamingSyntax)
++ ". To use this new syntax, the package needs to specify at least"
++ "'cabal-version: >= 1.21'."
-- check use of 'extra-framework-dirs' field
, checkVersion [1,23] (any (not . null) (buildInfoField extraFrameworkDirs)) $
-- Just a warning, because this won't break on old Cabal versions.
PackageDistSuspiciousWarn $
"To use the 'extra-framework-dirs' field the package needs to specify"
++ " at least 'cabal-version: >= 1.23'."
-- check use of default-extensions field
-- don't need to do the equivalent check for other-extensions
, checkVersion [1,10] (any (not . null) (buildInfoField defaultExtensions)) $
PackageBuildWarning $
"To use the 'default-extensions' field the package needs to specify "
++ "at least 'cabal-version: >= 1.10'."
-- check use of extensions field
, check (specVersion pkg >= Version [1,10] []
&& (any (not . null) (buildInfoField oldExtensions))) $
PackageBuildWarning $
"For packages using 'cabal-version: >= 1.10' the 'extensions' "
++ "field is deprecated. The new 'default-extensions' field lists "
++ "extensions that are used in all modules in the component, while "
++ "the 'other-extensions' field lists extensions that are used in "
++ "some modules, e.g. via the {-# LANGUAGE #-} pragma."
-- check use of "foo (>= 1.0 && < 1.4) || >=1.8 " version-range syntax
, checkVersion [1,8] (not (null versionRangeExpressions)) $
PackageDistInexcusable $
"The package uses full version-range expressions "
++ "in a 'build-depends' field: "
++ commaSep (map displayRawDependency versionRangeExpressions)
++ ". To use this new syntax the package needs to specify at least "
++ "'cabal-version: >= 1.8'. Alternatively, if broader compatibility "
++ "is important, then convert to conjunctive normal form, and use "
++ "multiple 'build-depends:' lines, one conjunct per line."
-- check use of "build-depends: foo == 1.*" syntax
, checkVersion [1,6] (not (null depsUsingWildcardSyntax)) $
PackageDistInexcusable $
"The package uses wildcard syntax in the 'build-depends' field: "
++ commaSep (map display depsUsingWildcardSyntax)
++ ". To use this new syntax the package need to specify at least "
++ "'cabal-version: >= 1.6'. Alternatively, if broader compatibility "
++ "is important then use: " ++ commaSep
[ display (Dependency name (eliminateWildcardSyntax versionRange))
| Dependency name versionRange <- depsUsingWildcardSyntax ]
-- check use of "tested-with: GHC (>= 1.0 && < 1.4) || >=1.8 " syntax
, checkVersion [1,8] (not (null testedWithVersionRangeExpressions)) $
PackageDistInexcusable $
"The package uses full version-range expressions "
++ "in a 'tested-with' field: "
++ commaSep (map displayRawDependency testedWithVersionRangeExpressions)
++ ". To use this new syntax the package needs to specify at least "
++ "'cabal-version: >= 1.8'."
-- check use of "tested-with: GHC == 6.12.*" syntax
, checkVersion [1,6] (not (null testedWithUsingWildcardSyntax)) $
PackageDistInexcusable $
"The package uses wildcard syntax in the 'tested-with' field: "
++ commaSep (map display testedWithUsingWildcardSyntax)
++ ". To use this new syntax the package need to specify at least "
++ "'cabal-version: >= 1.6'. Alternatively, if broader compatibility "
++ "is important then use: " ++ commaSep
[ display (Dependency name (eliminateWildcardSyntax versionRange))
| Dependency name versionRange <- testedWithUsingWildcardSyntax ]
-- check use of "data-files: data/*.txt" syntax
, checkVersion [1,6] (not (null dataFilesUsingGlobSyntax)) $
PackageDistInexcusable $
"Using wildcards like "
++ commaSep (map quote $ take 3 dataFilesUsingGlobSyntax)
++ " in the 'data-files' field requires 'cabal-version: >= 1.6'. "
++ "Alternatively if you require compatibility with earlier Cabal "
++ "versions then list all the files explicitly."
-- check use of "extra-source-files: mk/*.in" syntax
, checkVersion [1,6] (not (null extraSrcFilesUsingGlobSyntax)) $
PackageDistInexcusable $
"Using wildcards like "
++ commaSep (map quote $ take 3 extraSrcFilesUsingGlobSyntax)
++ " in the 'extra-source-files' field requires "
++ "'cabal-version: >= 1.6'. Alternatively if you require "
++ "compatibility with earlier Cabal versions then list all the files "
++ "explicitly."
-- check use of "source-repository" section
, checkVersion [1,6] (not (null (sourceRepos pkg))) $
PackageDistInexcusable $
"The 'source-repository' section is new in Cabal 1.6. "
++ "Unfortunately it messes up the parser in earlier Cabal versions "
++ "so you need to specify 'cabal-version: >= 1.6'."
-- check for new licenses
, checkVersion [1,4] (license pkg `notElem` compatLicenses) $
PackageDistInexcusable $
"Unfortunately the license " ++ quote (display (license pkg))
++ " messes up the parser in earlier Cabal versions so you need to "
++ "specify 'cabal-version: >= 1.4'. Alternatively if you require "
++ "compatibility with earlier Cabal versions then use 'OtherLicense'."
-- check for new language extensions
, checkVersion [1,2,3] (not (null mentionedExtensionsThatNeedCabal12)) $
PackageDistInexcusable $
"Unfortunately the language extensions "
++ commaSep (map (quote . display) mentionedExtensionsThatNeedCabal12)
++ " break the parser in earlier Cabal versions so you need to "
++ "specify 'cabal-version: >= 1.2.3'. Alternatively if you require "
++ "compatibility with earlier Cabal versions then you may be able to "
++ "use an equivalent compiler-specific flag."
, checkVersion [1,4] (not (null mentionedExtensionsThatNeedCabal14)) $
PackageDistInexcusable $
"Unfortunately the language extensions "
++ commaSep (map (quote . display) mentionedExtensionsThatNeedCabal14)
++ " break the parser in earlier Cabal versions so you need to "
++ "specify 'cabal-version: >= 1.4'. Alternatively if you require "
++ "compatibility with earlier Cabal versions then you may be able to "
++ "use an equivalent compiler-specific flag."
, check (specVersion pkg >= Version [1,23] []
&& isNothing (setupBuildInfo pkg)
&& buildType pkg == Just Custom) $
PackageBuildWarning $
"Packages using 'cabal-version: >= 1.23' with 'build-type: Custom' "
++ "must use a 'custom-setup' section with a 'setup-depends' field "
++ "that specifies the dependencies of the Setup.hs script itself. "
++ "The 'setup-depends' field uses the same syntax as 'build-depends', "
++ "so a simple example would be 'setup-depends: base, Cabal'."
, check (specVersion pkg < Version [1,23] []
&& isNothing (setupBuildInfo pkg)
&& buildType pkg == Just Custom) $
PackageDistSuspiciousWarn $
"From version 1.23 cabal supports specifiying explicit dependencies "
++ "for Custom setup scripts. Consider using cabal-version >= 1.23 and "
++ "adding a 'custom-setup' section with a 'setup-depends' field "
++ "that specifies the dependencies of the Setup.hs script itself. "
++ "The 'setup-depends' field uses the same syntax as 'build-depends', "
++ "so a simple example would be 'setup-depends: base, Cabal'."
]
where
-- Perform a check on packages that use a version of the spec less than
-- the version given. This is for cases where a new Cabal version adds
-- a new feature and we want to check that it is not used prior to that
-- version.
checkVersion :: [Int] -> Bool -> PackageCheck -> Maybe PackageCheck
checkVersion ver cond pc
| specVersion pkg >= Version ver [] = Nothing
| otherwise = check cond pc
buildInfoField field = map field (allBuildInfo pkg)
dataFilesUsingGlobSyntax = filter usesGlobSyntax (dataFiles pkg)
extraSrcFilesUsingGlobSyntax = filter usesGlobSyntax (extraSrcFiles pkg)
usesGlobSyntax str = case parseFileGlob str of
Just (FileGlob _ _) -> True
_ -> False
versionRangeExpressions =
[ dep | dep@(Dependency _ vr) <- buildDepends pkg
, usesNewVersionRangeSyntax vr ]
testedWithVersionRangeExpressions =
[ Dependency (PackageName (display compiler)) vr
| (compiler, vr) <- testedWith pkg
, usesNewVersionRangeSyntax vr ]
simpleSpecVersionRangeSyntax =
either (const True)
(foldVersionRange'
True
(\_ -> False)
(\_ -> False) (\_ -> False)
(\_ -> True) -- >=
(\_ -> False)
(\_ _ -> False)
(\_ _ -> False) (\_ _ -> False)
id)
(specVersionRaw pkg)
-- is the cabal-version field a simple version number, rather than a range
simpleSpecVersionSyntax =
either (const True) (const False) (specVersionRaw pkg)
usesNewVersionRangeSyntax :: VersionRange -> Bool
usesNewVersionRangeSyntax =
(> 2) -- uses the new syntax if depth is more than 2
. foldVersionRange'
(1 :: Int)
(const 1)
(const 1) (const 1)
(const 1) (const 1)
(const (const 1))
(+) (+)
(const 3) -- uses new ()'s syntax
depsUsingWildcardSyntax = [ dep | dep@(Dependency _ vr) <- buildDepends pkg
, usesWildcardSyntax vr ]
-- TODO: If the user writes build-depends: foo with (), this is
-- indistinguishable from build-depends: foo, so there won't be an
-- error even though there should be
depsUsingThinningRenamingSyntax =
[ name
| bi <- allBuildInfo pkg
, (name, _) <- Map.toList (targetBuildRenaming bi) ]
testedWithUsingWildcardSyntax =
[ Dependency (PackageName (display compiler)) vr
| (compiler, vr) <- testedWith pkg
, usesWildcardSyntax vr ]
usesWildcardSyntax :: VersionRange -> Bool
usesWildcardSyntax =
foldVersionRange'
False (const False)
(const False) (const False)
(const False) (const False)
(\_ _ -> True) -- the wildcard case
(||) (||) id
eliminateWildcardSyntax =
foldVersionRange'
anyVersion thisVersion
laterVersion earlierVersion
orLaterVersion orEarlierVersion
(\v v' -> intersectVersionRanges (orLaterVersion v) (earlierVersion v'))
intersectVersionRanges unionVersionRanges id
compatLicenses = [ GPL Nothing, LGPL Nothing, AGPL Nothing, BSD3, BSD4
, PublicDomain, AllRightsReserved
, UnspecifiedLicense, OtherLicense ]
mentionedExtensions = [ ext | bi <- allBuildInfo pkg
, ext <- allExtensions bi ]
mentionedExtensionsThatNeedCabal12 =
nub (filter (`elem` compatExtensionsExtra) mentionedExtensions)
-- As of Cabal-1.4 we can add new extensions without worrying about
-- breaking old versions of cabal.
mentionedExtensionsThatNeedCabal14 =
nub (filter (`notElem` compatExtensions) mentionedExtensions)
-- The known extensions in Cabal-1.2.3
compatExtensions =
map EnableExtension
[ OverlappingInstances, UndecidableInstances, IncoherentInstances
, RecursiveDo, ParallelListComp, MultiParamTypeClasses
, FunctionalDependencies, Rank2Types
, RankNTypes, PolymorphicComponents, ExistentialQuantification
, ScopedTypeVariables, ImplicitParams, FlexibleContexts
, FlexibleInstances, EmptyDataDecls, CPP, BangPatterns
, TypeSynonymInstances, TemplateHaskell, ForeignFunctionInterface
, Arrows, Generics, NamedFieldPuns, PatternGuards
, GeneralizedNewtypeDeriving, ExtensibleRecords, RestrictedTypeSynonyms
, HereDocuments] ++
map DisableExtension
[MonomorphismRestriction, ImplicitPrelude] ++
compatExtensionsExtra
-- The extra known extensions in Cabal-1.2.3 vs Cabal-1.1.6
-- (Cabal-1.1.6 came with ghc-6.6. Cabal-1.2 came with ghc-6.8)
compatExtensionsExtra =
map EnableExtension
[ KindSignatures, MagicHash, TypeFamilies, StandaloneDeriving
, UnicodeSyntax, PatternSignatures, UnliftedFFITypes, LiberalTypeSynonyms
, TypeOperators, RecordWildCards, RecordPuns, DisambiguateRecordFields
, OverloadedStrings, GADTs, RelaxedPolyRec
, ExtendedDefaultRules, UnboxedTuples, DeriveDataTypeable
, ConstrainedClassMethods
] ++
map DisableExtension
[MonoPatBinds]
-- | A variation on the normal 'Text' instance, shows any ()'s in the original
-- textual syntax. We need to show these otherwise it's confusing to users when
-- we complain of their presence but do not pretty print them!
--
displayRawVersionRange :: VersionRange -> String
displayRawVersionRange =
Disp.render
. fst
. foldVersionRange' -- precedence:
-- All the same as the usual pretty printer, except for the parens
( Disp.text "-any" , 0 :: Int)
(\v -> (Disp.text "==" <> disp v , 0))
(\v -> (Disp.char '>' <> disp v , 0))
(\v -> (Disp.char '<' <> disp v , 0))
(\v -> (Disp.text ">=" <> disp v , 0))
(\v -> (Disp.text "<=" <> disp v , 0))
(\v _ -> (Disp.text "==" <> dispWild v , 0))
(\(r1, p1) (r2, p2) ->
(punct 2 p1 r1 <+> Disp.text "||" <+> punct 2 p2 r2 , 2))
(\(r1, p1) (r2, p2) ->
(punct 1 p1 r1 <+> Disp.text "&&" <+> punct 1 p2 r2 , 1))
(\(r, _ ) -> (Disp.parens r, 0)) -- parens
where
dispWild (Version b _) =
Disp.hcat (Disp.punctuate (Disp.char '.') (map Disp.int b))
<> Disp.text ".*"
punct p p' | p < p' = Disp.parens
| otherwise = id
displayRawDependency :: Dependency -> String
displayRawDependency (Dependency pkg vr) =
display pkg ++ " " ++ displayRawVersionRange vr
-- ------------------------------------------------------------
-- * Checks on the GenericPackageDescription
-- ------------------------------------------------------------
-- | Check the build-depends fields for any weirdness or bad practise.
--
checkPackageVersions :: GenericPackageDescription -> [PackageCheck]
checkPackageVersions pkg =
catMaybes [
-- Check that the version of base is bounded above.
-- For example this bans "build-depends: base >= 3".
-- It should probably be "build-depends: base >= 3 && < 4"
-- which is the same as "build-depends: base == 3.*"
check (not (boundedAbove baseDependency)) $
PackageDistInexcusable $
"The dependency 'build-depends: base' does not specify an upper "
++ "bound on the version number. Each major release of the 'base' "
++ "package changes the API in various ways and most packages will "
++ "need some changes to compile with it. The recommended practise "
++ "is to specify an upper bound on the version of the 'base' "
++ "package. This ensures your package will continue to build when a "
++ "new major version of the 'base' package is released. If you are "
++ "not sure what upper bound to use then use the next major "
++ "version. For example if you have tested your package with 'base' "
++ "version 4.5 and 4.6 then use 'build-depends: base >= 4.5 && < 4.7'."
]
where
-- TODO: What we really want to do is test if there exists any
-- configuration in which the base version is unbounded above.
-- However that's a bit tricky because there are many possible
-- configurations. As a cheap easy and safe approximation we will
-- pick a single "typical" configuration and check if that has an
-- open upper bound. To get a typical configuration we finalise
-- using no package index and the current platform.
finalised = finalizePackageDescription
[] (const True) buildPlatform
(unknownCompilerInfo
(CompilerId buildCompilerFlavor (Version [] [])) NoAbiTag)
[] pkg
baseDependency = case finalised of
Right (pkg', _) | not (null baseDeps) ->
foldr intersectVersionRanges anyVersion baseDeps
where
baseDeps =
[ vr | Dependency (PackageName "base") vr <- buildDepends pkg' ]
-- Just in case finalizePackageDescription fails for any reason,
-- or if the package doesn't depend on the base package at all,
-- then we will just skip the check, since boundedAbove noVersion = True
_ -> noVersion
boundedAbove :: VersionRange -> Bool
boundedAbove vr = case asVersionIntervals vr of
[] -> True -- this is the inconsistent version range.
intervals -> case last intervals of
(_, UpperBound _ _) -> True
(_, NoUpperBound ) -> False
checkConditionals :: GenericPackageDescription -> [PackageCheck]
checkConditionals pkg =
catMaybes [
check (not $ null unknownOSs) $
PackageDistInexcusable $
"Unknown operating system name "
++ commaSep (map quote unknownOSs)
, check (not $ null unknownArches) $
PackageDistInexcusable $
"Unknown architecture name "
++ commaSep (map quote unknownArches)
, check (not $ null unknownImpls) $
PackageDistInexcusable $
"Unknown compiler name "
++ commaSep (map quote unknownImpls)
]
where
unknownOSs = [ os | OS (OtherOS os) <- conditions ]
unknownArches = [ arch | Arch (OtherArch arch) <- conditions ]
unknownImpls = [ impl | Impl (OtherCompiler impl) _ <- conditions ]
conditions = maybe [] fvs (condLibrary pkg)
++ concatMap (fvs . snd) (condExecutables pkg)
fvs (CondNode _ _ ifs) = concatMap compfv ifs -- free variables
compfv (c, ct, mct) = condfv c ++ fvs ct ++ maybe [] fvs mct
condfv c = case c of
Var v -> [v]
Lit _ -> []
CNot c1 -> condfv c1
COr c1 c2 -> condfv c1 ++ condfv c2
CAnd c1 c2 -> condfv c1 ++ condfv c2
checkDevelopmentOnlyFlagsBuildInfo :: BuildInfo -> [PackageCheck]
checkDevelopmentOnlyFlagsBuildInfo bi =
catMaybes [
check has_WerrorWall $
PackageDistInexcusable $
"'ghc-options: -Wall -Werror' makes the package very easy to "
++ "break with future GHC versions because new GHC versions often "
++ "add new warnings. Use just 'ghc-options: -Wall' instead."
++ extraExplanation
, check (not has_WerrorWall && has_Werror) $
PackageDistInexcusable $
"'ghc-options: -Werror' makes the package easy to "
++ "break with future GHC versions because new GHC versions often "
++ "add new warnings. "
++ extraExplanation
, checkFlags ["-fdefer-type-errors"] $
PackageDistInexcusable $
"'ghc-options: -fdefer-type-errors' is fine during development but "
++ "is not appropriate for a distributed package. "
++ extraExplanation
-- -dynamic is not a debug flag
, check (any (\opt -> "-d" `isPrefixOf` opt && opt /= "-dynamic")
ghc_options) $
PackageDistInexcusable $
"'ghc-options: -d*' debug flags are not appropriate "
++ "for a distributed package. "
++ extraExplanation
, checkFlags ["-fprof-auto", "-fprof-auto-top", "-fprof-auto-calls",
"-fprof-cafs", "-fno-prof-count-entries",
"-auto-all", "-auto", "-caf-all"] $
PackageDistSuspicious $
"'ghc-options: -fprof*' profiling flags are typically not "
++ "appropriate for a distributed library package. These flags are "
++ "useful to profile this package, but when profiling other packages "
++ "that use this one these flags clutter the profile output with "
++ "excessive detail. If you think other packages really want to see "
++ "cost centres from this package then use '-fprof-auto-exported' "
++ "which puts cost centres only on exported functions. "
++ extraExplanation
]
where
extraExplanation =
" Alternatively, if you want to use this, make it conditional based "
++ "on a Cabal configuration flag (with 'manual: True' and 'default: "
++ "False') and enable that flag during development."
has_WerrorWall = has_Werror && ( has_Wall || has_W )
has_Werror = "-Werror" `elem` ghc_options
has_Wall = "-Wall" `elem` ghc_options
has_W = "-W" `elem` ghc_options
ghc_options = hcOptions GHC bi ++ hcProfOptions GHC bi
++ hcSharedOptions GHC bi
checkFlags :: [String] -> PackageCheck -> Maybe PackageCheck
checkFlags flags = check (any (`elem` flags) ghc_options)
checkDevelopmentOnlyFlags :: GenericPackageDescription -> [PackageCheck]
checkDevelopmentOnlyFlags pkg =
concatMap checkDevelopmentOnlyFlagsBuildInfo
[ bi
| (conditions, bi) <- allConditionalBuildInfo
, not (any guardedByManualFlag conditions) ]
where
guardedByManualFlag = definitelyFalse
-- We've basically got three-values logic here: True, False or unknown
-- hence this pattern to propagate the unknown cases properly.
definitelyFalse (Var (Flag n)) = maybe False not (Map.lookup n manualFlags)
definitelyFalse (Var _) = False
definitelyFalse (Lit b) = not b
definitelyFalse (CNot c) = definitelyTrue c
definitelyFalse (COr c1 c2) = definitelyFalse c1 && definitelyFalse c2
definitelyFalse (CAnd c1 c2) = definitelyFalse c1 || definitelyFalse c2
definitelyTrue (Var (Flag n)) = fromMaybe False (Map.lookup n manualFlags)
definitelyTrue (Var _) = False
definitelyTrue (Lit b) = b
definitelyTrue (CNot c) = definitelyFalse c
definitelyTrue (COr c1 c2) = definitelyTrue c1 || definitelyTrue c2
definitelyTrue (CAnd c1 c2) = definitelyTrue c1 && definitelyTrue c2
manualFlags = Map.fromList
[ (flagName flag, flagDefault flag)
| flag <- genPackageFlags pkg
, flagManual flag ]
allConditionalBuildInfo :: [([Condition ConfVar], BuildInfo)]
allConditionalBuildInfo =
concatMap (collectCondTreePaths libBuildInfo)
(maybeToList (condLibrary pkg))
++ concatMap (collectCondTreePaths buildInfo . snd)
(condExecutables pkg)
++ concatMap (collectCondTreePaths testBuildInfo . snd)
(condTestSuites pkg)
++ concatMap (collectCondTreePaths benchmarkBuildInfo . snd)
(condBenchmarks pkg)
-- get all the leaf BuildInfo, paired up with the path (in the tree sense)
-- of if-conditions that guard it
collectCondTreePaths :: (a -> b)
-> CondTree v c a
-> [([Condition v], b)]
collectCondTreePaths mapData = go []
where
go conditions condNode =
-- the data at this level in the tree:
(reverse conditions, mapData (condTreeData condNode))
: concat
[ go (condition:conditions) ifThen
| (condition, ifThen, _) <- condTreeComponents condNode ]
++ concat
[ go (condition:conditions) elseThen
| (condition, _, Just elseThen) <- condTreeComponents condNode ]
-- ------------------------------------------------------------
-- * Checks involving files in the package
-- ------------------------------------------------------------
-- | Sanity check things that requires IO. It looks at the files in the
-- package and expects to find the package unpacked in at the given file path.
--
checkPackageFiles :: PackageDescription -> FilePath -> IO [PackageCheck]
checkPackageFiles pkg root = checkPackageContent checkFilesIO pkg
where
checkFilesIO = CheckPackageContentOps {
doesFileExist = System.doesFileExist . relative,
doesDirectoryExist = System.doesDirectoryExist . relative,
getDirectoryContents = System.Directory.getDirectoryContents . relative,
getFileContents = \f -> openBinaryFile (relative f) ReadMode >>= hGetContents
}
relative path = root </> path
-- | A record of operations needed to check the contents of packages.
-- Used by 'checkPackageContent'.
--
data CheckPackageContentOps m = CheckPackageContentOps {
doesFileExist :: FilePath -> m Bool,
doesDirectoryExist :: FilePath -> m Bool,
getDirectoryContents :: FilePath -> m [FilePath],
getFileContents :: FilePath -> m String
}
-- | Sanity check things that requires looking at files in the package.
-- This is a generalised version of 'checkPackageFiles' that can work in any
-- monad for which you can provide 'CheckPackageContentOps' operations.
--
-- The point of this extra generality is to allow doing checks in some virtual
-- file system, for example a tarball in memory.
--
checkPackageContent :: Monad m => CheckPackageContentOps m
-> PackageDescription
-> m [PackageCheck]
checkPackageContent ops pkg = do
cabalBomError <- checkCabalFileBOM ops
licenseErrors <- checkLicensesExist ops pkg
setupError <- checkSetupExists ops pkg
configureError <- checkConfigureExists ops pkg
localPathErrors <- checkLocalPathsExist ops pkg
vcsLocation <- checkMissingVcsInfo ops pkg
return $ licenseErrors
++ catMaybes [cabalBomError, setupError, configureError]
++ localPathErrors
++ vcsLocation
checkCabalFileBOM :: Monad m => CheckPackageContentOps m
-> m (Maybe PackageCheck)
checkCabalFileBOM ops = do
epdfile <- findPackageDesc ops
case epdfile of
Left pc -> return $ Just pc
Right pdfile -> (flip check pc . startsWithBOM . fromUTF8) `liftM` (getFileContents ops pdfile)
where pc = PackageDistInexcusable $
pdfile ++ " starts with an Unicode byte order mark (BOM). This may cause problems with older cabal versions."
-- |Find a package description file in the given directory. Looks for
-- @.cabal@ files. Like 'Distribution.Simple.Utils.findPackageDesc',
-- but generalized over monads.
findPackageDesc :: Monad m => CheckPackageContentOps m
-> m (Either PackageCheck FilePath) -- ^<pkgname>.cabal
findPackageDesc ops
= do let dir = "."
files <- getDirectoryContents ops dir
-- to make sure we do not mistake a ~/.cabal/ dir for a <pkgname>.cabal
-- file we filter to exclude dirs and null base file names:
cabalFiles <- filterM (doesFileExist ops)
[ dir </> file
| file <- files
, let (name, ext) = splitExtension file
, not (null name) && ext == ".cabal" ]
case cabalFiles of
[] -> return (Left $ PackageBuildImpossible noDesc)
[cabalFile] -> return (Right cabalFile)
multiple -> return (Left $ PackageBuildImpossible $ multiDesc multiple)
where
noDesc :: String
noDesc = "No cabal file found.\n"
++ "Please create a package description file <pkgname>.cabal"
multiDesc :: [String] -> String
multiDesc l = "Multiple cabal files found.\n"
++ "Please use only one of: "
++ intercalate ", " l
checkLicensesExist :: Monad m => CheckPackageContentOps m
-> PackageDescription
-> m [PackageCheck]
checkLicensesExist ops pkg = do
exists <- mapM (doesFileExist ops) (licenseFiles pkg)
return
[ PackageBuildWarning $
"The '" ++ fieldname ++ "' field refers to the file "
++ quote file ++ " which does not exist."
| (file, False) <- zip (licenseFiles pkg) exists ]
where
fieldname | length (licenseFiles pkg) == 1 = "license-file"
| otherwise = "license-files"
checkSetupExists :: Monad m => CheckPackageContentOps m
-> PackageDescription
-> m (Maybe PackageCheck)
checkSetupExists ops pkg = do
let simpleBuild = buildType pkg == Just Simple
hsexists <- doesFileExist ops "Setup.hs"
lhsexists <- doesFileExist ops "Setup.lhs"
return $ check (not simpleBuild && not hsexists && not lhsexists) $
PackageDistInexcusable $
"The package is missing a Setup.hs or Setup.lhs script."
checkConfigureExists :: Monad m => CheckPackageContentOps m
-> PackageDescription
-> m (Maybe PackageCheck)
checkConfigureExists ops PackageDescription { buildType = Just Configure } = do
exists <- doesFileExist ops "configure"
return $ check (not exists) $
PackageBuildWarning $
"The 'build-type' is 'Configure' but there is no 'configure' script. "
++ "You probably need to run 'autoreconf -i' to generate it."
checkConfigureExists _ _ = return Nothing
checkLocalPathsExist :: Monad m => CheckPackageContentOps m
-> PackageDescription
-> m [PackageCheck]
checkLocalPathsExist ops pkg = do
let dirs = [ (dir, kind)
| bi <- allBuildInfo pkg
, (dir, kind) <-
[ (dir, "extra-lib-dirs") | dir <- extraLibDirs bi ]
++ [ (dir, "extra-framework-dirs")
| dir <- extraFrameworkDirs bi ]
++ [ (dir, "include-dirs") | dir <- includeDirs bi ]
++ [ (dir, "hs-source-dirs") | dir <- hsSourceDirs bi ]
, isRelative dir ]
missing <- filterM (liftM not . doesDirectoryExist ops . fst) dirs
return [ PackageBuildWarning {
explanation = quote (kind ++ ": " ++ dir)
++ " directory does not exist."
}
| (dir, kind) <- missing ]
checkMissingVcsInfo :: Monad m => CheckPackageContentOps m
-> PackageDescription
-> m [PackageCheck]
checkMissingVcsInfo ops pkg | null (sourceRepos pkg) = do
vcsInUse <- liftM or $ mapM (doesDirectoryExist ops) repoDirnames
if vcsInUse
then return [ PackageDistSuspicious message ]
else return []
where
repoDirnames = [ dirname | repo <- knownRepoTypes
, dirname <- repoTypeDirname repo ]
message = "When distributing packages it is encouraged to specify source "
++ "control information in the .cabal file using one or more "
++ "'source-repository' sections. See the Cabal user guide for "
++ "details."
checkMissingVcsInfo _ _ = return []
repoTypeDirname :: RepoType -> [FilePath]
repoTypeDirname Darcs = ["_darcs"]
repoTypeDirname Git = [".git"]
repoTypeDirname SVN = [".svn"]
repoTypeDirname CVS = ["CVS"]
repoTypeDirname Mercurial = [".hg"]
repoTypeDirname GnuArch = [".arch-params"]
repoTypeDirname Bazaar = [".bzr"]
repoTypeDirname Monotone = ["_MTN"]
repoTypeDirname _ = []
-- ------------------------------------------------------------
-- * Checks involving files in the package
-- ------------------------------------------------------------
-- | Check the names of all files in a package for portability problems. This
-- should be done for example when creating or validating a package tarball.
--
checkPackageFileNames :: [FilePath] -> [PackageCheck]
checkPackageFileNames files =
(take 1 . mapMaybe checkWindowsPath $ files)
++ (take 1 . mapMaybe checkTarPath $ files)
-- If we get any of these checks triggering then we're likely to get
-- many, and that's probably not helpful, so return at most one.
checkWindowsPath :: FilePath -> Maybe PackageCheck
checkWindowsPath path =
check (not $ FilePath.Windows.isValid path') $
PackageDistInexcusable $
"Unfortunately, the file " ++ quote path ++ " is not a valid file "
++ "name on Windows which would cause portability problems for this "
++ "package. Windows file names cannot contain any of the characters "
++ "\":*?<>|\" and there are a few reserved names including \"aux\", "
++ "\"nul\", \"con\", \"prn\", \"com1-9\", \"lpt1-9\" and \"clock$\"."
where
path' = ".\\" ++ path
-- force a relative name to catch invalid file names like "f:oo" which
-- otherwise parse as file "oo" in the current directory on the 'f' drive.
-- | Check a file name is valid for the portable POSIX tar format.
--
-- The POSIX tar format has a restriction on the length of file names. It is
-- unfortunately not a simple restriction like a maximum length. The exact
-- restriction is that either the whole path be 100 characters or less, or it
-- be possible to split the path on a directory separator such that the first
-- part is 155 characters or less and the second part 100 characters or less.
--
checkTarPath :: FilePath -> Maybe PackageCheck
checkTarPath path
| length path > 255 = Just longPath
| otherwise = case pack nameMax (reverse (splitPath path)) of
Left err -> Just err
Right [] -> Nothing
Right (first:rest) -> case pack prefixMax remainder of
Left err -> Just err
Right [] -> Nothing
Right (_:_) -> Just noSplit
where
-- drop the '/' between the name and prefix:
remainder = init first : rest
where
nameMax, prefixMax :: Int
nameMax = 100
prefixMax = 155
pack _ [] = Left emptyName
pack maxLen (c:cs)
| n > maxLen = Left longName
| otherwise = Right (pack' maxLen n cs)
where n = length c
pack' maxLen n (c:cs)
| n' <= maxLen = pack' maxLen n' cs
where n' = n + length c
pack' _ _ cs = cs
longPath = PackageDistInexcusable $
"The following file name is too long to store in a portable POSIX "
++ "format tar archive. The maximum length is 255 ASCII characters.\n"
++ "The file in question is:\n " ++ path
longName = PackageDistInexcusable $
"The following file name is too long to store in a portable POSIX "
++ "format tar archive. The maximum length for the name part (including "
++ "extension) is 100 ASCII characters. The maximum length for any "
++ "individual directory component is 155.\n"
++ "The file in question is:\n " ++ path
noSplit = PackageDistInexcusable $
"The following file name is too long to store in a portable POSIX "
++ "format tar archive. While the total length is less than 255 ASCII "
++ "characters, there are unfortunately further restrictions. It has to "
++ "be possible to split the file path on a directory separator into "
++ "two parts such that the first part fits in 155 characters or less "
++ "and the second part fits in 100 characters or less. Basically you "
++ "have to make the file name or directory names shorter, or you could "
++ "split a long directory name into nested subdirectories with shorter "
++ "names.\nThe file in question is:\n " ++ path
emptyName = PackageDistInexcusable $
"Encountered a file with an empty name, something is very wrong! "
++ "Files with an empty name cannot be stored in a tar archive or in "
++ "standard file systems."
-- ------------------------------------------------------------
-- * Utils
-- ------------------------------------------------------------
quote :: String -> String
quote s = "'" ++ s ++ "'"
commaSep :: [String] -> String
commaSep = intercalate ", "
dups :: Ord a => [a] -> [a]
dups xs = [ x | (x:_:_) <- group (sort xs) ]
fileExtensionSupportedLanguage :: FilePath -> Bool
fileExtensionSupportedLanguage path =
isHaskell || isC
where
extension = takeExtension path
isHaskell = extension `elem` [".hs", ".lhs"]
isC = isJust (filenameCDialect extension)
|
garetxe/cabal
|
Cabal/Distribution/PackageDescription/Check.hs
|
Haskell
|
bsd-3-clause
| 74,822
|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Behave.Units (
module Export
, DMoisture
, DFraction
, DRatio
, DAzimuth
, FuelLoad
, SaToVolRatio
, HeatOfCombustion
, HeatPerUnitArea
, ReactionVelocity
, Ratio
, Length
, Dimensionless
, Fraction
, Moisture
, TotalMineralContent
, EffectiveMineralContent
, Speed
, ByramsIntensity
, RateOfSpread
, Azimuth
, ReactionIntensity
, Time
, lbSqFt
, lbCuFt
, btu
, btuLb
, btuFtSec
, btuSqFtMin
, btuSqFt
, perFoot
, footMin
, one
, perCent
, perOne
, _0
, _1
, (*~)
, (/~)
) where
import Numeric.Units.Dimensional
import Numeric.Units.Dimensional.UnitNames (atom)
import Numeric.Units.Dimensional.Prelude
import Numeric.Units.Dimensional.NonSI as Export hiding (btu)
import Numeric.Units.Dimensional.SIUnits as Export
import Numeric.Units.Dimensional.Quantities as Export
import Numeric.NumType.DK.Integers (TypeInt(..))
import Prelude () -- for instances
{-
1. Lóngitud
2. Masa
3. Tiempo
4. Corriente eléctrica
5. Temperatura termodinámica
6. Cantidad de substancia
7. Intensidad lumínica
-}
type DFuelLoad = 'Dim 'Neg2 'Pos1 'Zero 'Zero 'Zero 'Zero 'Zero
type DSaToVolRatio = 'Dim 'Neg1 'Zero 'Zero 'Zero 'Zero 'Zero 'Zero
type DHeatOfCombustion = 'Dim 'Pos2 'Zero 'Neg2 'Zero 'Zero 'Zero 'Zero
type DHeatPerUnitArea = 'Dim 'Zero 'Pos1 'Neg2 'Zero 'Zero 'Zero 'Zero
type DReactionVelocity = 'Dim 'Zero 'Zero 'Neg1 'Zero 'Zero 'Zero 'Zero
type DByramsIntensity = 'Dim 'Pos1 'Pos1 'Neg3 'Zero 'Zero 'Zero 'Zero
type DRatio = DOne
type DFraction = DOne
type DMoisture = DFraction
type DAzimuth = DPlaneAngle
type FuelLoad = Quantity DFuelLoad Double
type SaToVolRatio = Quantity DSaToVolRatio Double
type HeatOfCombustion = Quantity DHeatOfCombustion Double
type HeatPerUnitArea = Quantity DHeatPerUnitArea Double
type ReactionVelocity = Quantity DReactionVelocity Double
type ByramsIntensity = Quantity DByramsIntensity Double
type Ratio = Quantity DRatio Double
type Fraction = Quantity DFraction Double
type Moisture = Quantity DMoisture Double
type TotalMineralContent = Fraction
type EffectiveMineralContent = Fraction
type Speed = Quantity DVelocity Double
type RateOfSpread = Speed
type Azimuth = Quantity DAzimuth Double
type ReactionIntensity = HeatFluxDensity Double
perCent :: Fractional a => Unit 'NonMetric DOne a
perCent = mkUnitQ n 0.01 one
where n = atom "[%]" "%" "Per cent"
perOne :: Fractional a => Unit 'NonMetric DOne a
perOne = mkUnitQ n 1.0 one
where n = atom "[one]" "one" "Ratio"
btu :: Fractional a => Unit 'NonMetric DEnergy a
btu = mkUnitQ n 0.293071 (watt * hour)
where n = atom "[btu]" "btu" "British Thermal Unit"
lbSqFt :: Unit 'NonMetric DFuelLoad Double
lbSqFt = poundMass/(foot ^ pos2)
lbCuFt :: Unit 'NonMetric DDensity Double
lbCuFt = poundMass/(foot ^ pos3)
btuLb:: Unit 'NonMetric DHeatOfCombustion Double
btuLb = btu / poundMass
btuFtSec :: Unit 'NonMetric DByramsIntensity Double
btuFtSec = btu / foot / second
btuSqFtMin :: Unit 'NonMetric DHeatFluxDensity Double
btuSqFtMin = btuSqFt / minute
btuSqFt :: Unit 'NonMetric DHeatPerUnitArea Double
btuSqFt = btu / foot ^ pos2
perFoot :: Unit 'NonMetric DSaToVolRatio Double
perFoot = foot ^ neg1
footMin :: Unit 'NonMetric DVelocity Double
footMin = foot / minute
|
albertov/behave-hs
|
src/Behave/Units.hs
|
Haskell
|
bsd-3-clause
| 3,872
|
{-# LANGUAGE Haskell98 #-}
{-# LINE 1 "Data/Text/Internal/Read.hs" #-}
-- |
-- Module : Data.Text.Internal.Read
-- Copyright : (c) 2014 Bryan O'Sullivan
--
-- License : BSD-style
-- Maintainer : bos@serpentine.com
-- Stability : experimental
-- Portability : GHC
--
-- Common internal functions for reading textual data.
module Data.Text.Internal.Read
(
IReader
, IParser(..)
, T(..)
, digitToInt
, hexDigitToInt
, perhaps
) where
import Control.Applicative as App (Applicative(..))
import Control.Arrow (first)
import Control.Monad (ap)
import Data.Char (ord)
type IReader t a = t -> Either String (a,t)
newtype IParser t a = P {
runP :: IReader t a
}
instance Functor (IParser t) where
fmap f m = P $ fmap (first f) . runP m
instance Applicative (IParser t) where
pure a = P $ \t -> Right (a,t)
{-# INLINE pure #-}
(<*>) = ap
instance Monad (IParser t) where
return = App.pure
m >>= k = P $ \t -> case runP m t of
Left err -> Left err
Right (a,t') -> runP (k a) t'
{-# INLINE (>>=) #-}
fail msg = P $ \_ -> Left msg
data T = T !Integer !Int
perhaps :: a -> IParser t a -> IParser t a
perhaps def m = P $ \t -> case runP m t of
Left _ -> Right (def,t)
r@(Right _) -> r
hexDigitToInt :: Char -> Int
hexDigitToInt c
| c >= '0' && c <= '9' = ord c - ord '0'
| c >= 'a' && c <= 'f' = ord c - (ord 'a' - 10)
| otherwise = ord c - (ord 'A' - 10)
digitToInt :: Char -> Int
digitToInt c = ord c - ord '0'
|
phischu/fragnix
|
tests/packages/scotty/Data.Text.Internal.Read.hs
|
Haskell
|
bsd-3-clause
| 1,641
|
module Hint.Sandbox ( sandboxed ) where
import Hint.Base
import Hint.Context
import Hint.Configuration
import Hint.Util
import {-# SOURCE #-} Hint.Typecheck ( typeChecks_unsandboxed )
import Control.Monad.Catch
sandboxed :: MonadInterpreter m => (Expr -> m a) -> (Expr -> m a)
sandboxed = if ghcVersion >= 610 then id else old_sandboxed
old_sandboxed :: MonadInterpreter m => (Expr -> m a) -> (Expr -> m a)
old_sandboxed do_stuff = \expr -> do no_sandbox <- fromConf all_mods_in_scope
if no_sandbox
then do_stuff expr
else usingAModule do_stuff expr
usingAModule :: MonadInterpreter m => (Expr -> m a) -> (Expr -> m a)
usingAModule do_stuff_on = \expr ->
--
-- To avoid defaulting, we will evaluate this expression without the
-- monomorphism-restriction. This means that expressions that normally
-- would not typecheck, suddenly will. Thus, we first check if the
-- expression typechecks as is. If it doesn't, there is no need in
-- going on (if it does, it may not typecheck once we restrict the
-- context; that is the whole idea of this!)
--
do type_checks <- typeChecks_unsandboxed expr
case type_checks of
False -> do_stuff_on expr -- fail as you wish...
True ->
do (loaded, imports) <- allModulesInContext
zombies <- fromState zombie_phantoms
quals <- fromState qual_imports
--
let e = safeBndFor expr
let mod_text no_prel mod_name = textify [
["{-# LANGUAGE NoMonomorphismRestriction #-}"],
["{-# LANGUAGE NoImplicitPrelude #-}" | no_prel],
["module " ++ mod_name],
["where"],
["import " ++ m | m <- loaded ++ imports,
not $ m `elem` (map pm_name zombies)],
["import qualified " ++ m ++ " as " ++ q | (m,q) <- quals],
[e ++ " = " ++ expr] ]
--
let go no_prel = do pm <- addPhantomModule (mod_text no_prel)
setTopLevelModules [pm_name pm]
r <- do_stuff_on e
`catchIE` (\err ->
case err of
WontCompile _ ->
do removePhantomModule pm
throwM err
_ -> throwM err)
removePhantomModule pm
return r
-- If the Prelude was not explicitly imported but implicitly
-- imported in some interpreted module, then the user may
-- get very unintuitive errors when turning sandboxing on. Thus
-- we will import the Prelude if the operation fails...
-- I guess this may lead to even more obscure errors, but
-- hopefully in much less frequent situations...
r <- onAnEmptyContext $ go True
`catchIE` (\err -> case err of
WontCompile _ -> go False
_ -> throwM err)
--
return r
--
where textify = unlines . concat
|
konn/hint-forked
|
src/Hint/Sandbox.hs
|
Haskell
|
bsd-3-clause
| 3,665
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE PatternGuards #-}
#ifdef TRUSTWORTHY
{-# LANGUAGE Trustworthy #-}
#endif
-----------------------------------------------------------------------------
-- |
-- Module : Control.Lens.Internal.FieldTH
-- Copyright : (C) 2014-2015 Edward Kmett, (C) 2014 Eric Mertens
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Stability : experimental
-- Portability : non-portable
--
-----------------------------------------------------------------------------
module Control.Lens.Internal.FieldTH
( LensRules(..)
, DefName(..)
, makeFieldOptics
, makeFieldOpticsForDec
) where
import Control.Lens.At
import Control.Lens.Fold
import Control.Lens.Internal.TH
import Control.Lens.Plated
import Control.Lens.Prism
import Control.Lens.Setter
import Control.Lens.Getter
import Control.Lens.Traversal
import Control.Lens.Tuple
import Control.Applicative
import Control.Monad
import Language.Haskell.TH.Lens
import Language.Haskell.TH
import Data.Foldable (toList)
import Data.Maybe (isJust,maybeToList)
import Data.List (nub, findIndices)
import Data.Either (partitionEithers)
import Data.Set.Lens
import Data.Map ( Map )
import Data.Set ( Set )
import qualified Data.Set as Set
import qualified Data.Map as Map
import qualified Data.Traversable as T
import Prelude
------------------------------------------------------------------------
-- Field generation entry point
------------------------------------------------------------------------
-- | Compute the field optics for the type identified by the given type name.
-- Lenses will be computed when possible, Traversals otherwise.
makeFieldOptics :: LensRules -> Name -> DecsQ
makeFieldOptics rules tyName =
do info <- reify tyName
case info of
TyConI dec -> makeFieldOpticsForDec rules dec
_ -> fail "makeFieldOptics: Expected type constructor name"
makeFieldOpticsForDec :: LensRules -> Dec -> DecsQ
makeFieldOpticsForDec rules dec = case dec of
DataD _ tyName vars cons _ ->
makeFieldOpticsForDec' rules tyName (mkS tyName vars) cons
NewtypeD _ tyName vars con _ ->
makeFieldOpticsForDec' rules tyName (mkS tyName vars) [con]
DataInstD _ tyName args cons _ ->
makeFieldOpticsForDec' rules tyName (tyName `conAppsT` args) cons
NewtypeInstD _ tyName args con _ ->
makeFieldOpticsForDec' rules tyName (tyName `conAppsT` args) [con]
_ -> fail "makeFieldOptics: Expected data or newtype type-constructor"
where
mkS tyName vars = tyName `conAppsT` map VarT (toListOf typeVars vars)
-- | Compute the field optics for a deconstructed Dec
-- When possible build an Iso otherwise build one optic per field.
makeFieldOpticsForDec' :: LensRules -> Name -> Type -> [Con] -> DecsQ
makeFieldOpticsForDec' rules tyName s cons =
do fieldCons <- traverse normalizeConstructor cons
let allFields = toListOf (folded . _2 . folded . _1 . folded) fieldCons
let defCons = over normFieldLabels (expandName allFields) fieldCons
allDefs = setOf (normFieldLabels . folded) defCons
perDef <- T.sequenceA (fromSet (buildScaffold rules s defCons) allDefs)
let defs = Map.toList perDef
case _classyLenses rules tyName of
Just (className, methodName) ->
makeClassyDriver rules className methodName s defs
Nothing -> do decss <- traverse (makeFieldOptic rules) defs
return (concat decss)
where
-- Traverse the field labels of a normalized constructor
normFieldLabels :: Traversal [(Name,[(a,Type)])] [(Name,[(b,Type)])] a b
normFieldLabels = traverse . _2 . traverse . _1
-- Map a (possibly missing) field's name to zero-to-many optic definitions
expandName :: [Name] -> Maybe Name -> [DefName]
expandName allFields = concatMap (_fieldToDef rules tyName allFields) . maybeToList
-- | Normalized the Con type into a uniform positional representation,
-- eliminating the variance between records, infix constructors, and normal
-- constructors.
normalizeConstructor ::
Con ->
Q (Name, [(Maybe Name, Type)]) -- ^ constructor name, field name, field type
normalizeConstructor (RecC n xs) =
return (n, [ (Just fieldName, ty) | (fieldName,_,ty) <- xs])
normalizeConstructor (NormalC n xs) =
return (n, [ (Nothing, ty) | (_,ty) <- xs])
normalizeConstructor (InfixC (_,ty1) n (_,ty2)) =
return (n, [ (Nothing, ty1), (Nothing, ty2) ])
normalizeConstructor (ForallC _ _ con) =
do con' <- normalizeConstructor con
return (set (_2 . mapped . _1) Nothing con')
data OpticType = GetterType | LensType | IsoType
-- | Compute the positional location of the fields involved in
-- each constructor for a given optic definition as well as the
-- type of clauses to generate and the type to annotate the declaration
-- with.
buildScaffold ::
LensRules ->
Type {- ^ outer type -} ->
[(Name, [([DefName], Type)])] {- ^ normalized constructors -} ->
DefName {- ^ target definition -} ->
Q (OpticType, OpticStab, [(Name, Int, [Int])])
{- ^ optic type, definition type, field count, target fields -}
buildScaffold rules s cons defName =
do (s',t,a,b) <- buildStab s (concatMap snd consForDef)
let defType
| Just (_,cx,a') <- preview _ForallT a =
let optic | lensCase = getterTypeName
| otherwise = foldTypeName
in OpticSa cx optic s' a'
-- Getter and Fold are always simple
| not (_allowUpdates rules) =
let optic | lensCase = getterTypeName
| otherwise = foldTypeName
in OpticSa [] optic s' a
-- Generate simple Lens and Traversal where possible
| _simpleLenses rules || s' == t && a == b =
let optic | isoCase && _allowIsos rules = iso'TypeName
| lensCase = lens'TypeName
| otherwise = traversal'TypeName
in OpticSa [] optic s' a
-- Generate type-changing Lens and Traversal otherwise
| otherwise =
let optic | isoCase && _allowIsos rules = isoTypeName
| lensCase = lensTypeName
| otherwise = traversalTypeName
in OpticStab optic s' t a b
opticType | has _ForallT a = GetterType
| not (_allowUpdates rules) = GetterType
| isoCase = IsoType
| otherwise = LensType
return (opticType, defType, scaffolds)
where
consForDef :: [(Name, [Either Type Type])]
consForDef = over (mapped . _2 . mapped) categorize cons
scaffolds :: [(Name, Int, [Int])]
scaffolds = [ (n, length ts, rightIndices ts) | (n,ts) <- consForDef ]
rightIndices :: [Either Type Type] -> [Int]
rightIndices = findIndices (has _Right)
-- Right: types for this definition
-- Left : other types
categorize :: ([DefName], Type) -> Either Type Type
categorize (defNames, t)
| defName `elem` defNames = Right t
| otherwise = Left t
lensCase :: Bool
lensCase = all (\x -> lengthOf (_2 . folded . _Right) x == 1) consForDef
isoCase :: Bool
isoCase = case scaffolds of
[(_,1,[0])] -> True
_ -> False
data OpticStab = OpticStab Name Type Type Type Type
| OpticSa Cxt Name Type Type
stabToType :: OpticStab -> Type
stabToType (OpticStab c s t a b) = quantifyType [] (c `conAppsT` [s,t,a,b])
stabToType (OpticSa cx c s a ) = quantifyType cx (c `conAppsT` [s,a])
stabToContext :: OpticStab -> Cxt
stabToContext OpticStab{} = []
stabToContext (OpticSa cx _ _ _) = cx
stabToOptic :: OpticStab -> Name
stabToOptic (OpticStab c _ _ _ _) = c
stabToOptic (OpticSa _ c _ _) = c
stabToS :: OpticStab -> Type
stabToS (OpticStab _ s _ _ _) = s
stabToS (OpticSa _ _ s _) = s
stabToA :: OpticStab -> Type
stabToA (OpticStab _ _ _ a _) = a
stabToA (OpticSa _ _ _ a) = a
-- | Compute the s t a b types given the outer type 's' and the
-- categorized field types. Left for fixed and Right for visited.
-- These types are "raw" and will be packaged into an 'OpticStab'
-- shortly after creation.
buildStab :: Type -> [Either Type Type] -> Q (Type,Type,Type,Type)
buildStab s categorizedFields =
do (subA,a) <- unifyTypes targetFields
let s' = applyTypeSubst subA s
-- compute possible type changes
sub <- T.sequenceA (fromSet (newName . nameBase) unfixedTypeVars)
let (t,b) = over both (substTypeVars sub) (s',a)
return (s',t,a,b)
where
(fixedFields, targetFields) = partitionEithers categorizedFields
fixedTypeVars = setOf typeVars fixedFields
unfixedTypeVars = setOf typeVars s Set.\\ fixedTypeVars
-- | Build the signature and definition for a single field optic.
-- In the case of a singleton constructor irrefutable matches are
-- used to enable the resulting lenses to be used on a bottom value.
makeFieldOptic ::
LensRules ->
(DefName, (OpticType, OpticStab, [(Name, Int, [Int])])) ->
DecsQ
makeFieldOptic rules (defName, (opticType, defType, cons)) =
do cls <- mkCls
T.sequenceA (cls ++ sig ++ def)
where
mkCls = case defName of
MethodName c n | _generateClasses rules ->
do classExists <- isJust <$> lookupTypeName (show c)
return (if classExists then [] else [makeFieldClass defType c n])
_ -> return []
sig = case defName of
_ | not (_generateSigs rules) -> []
TopName n -> [sigD n (return (stabToType defType))]
MethodName{} -> []
fun n = funD n clauses : inlinePragma n
def = case defName of
TopName n -> fun n
MethodName c n -> [makeFieldInstance defType c (fun n)]
clauses = makeFieldClauses rules opticType cons
------------------------------------------------------------------------
-- Classy class generator
------------------------------------------------------------------------
makeClassyDriver ::
LensRules ->
Name ->
Name ->
Type {- ^ Outer 's' type -} ->
[(DefName, (OpticType, OpticStab, [(Name, Int, [Int])]))] ->
DecsQ
makeClassyDriver rules className methodName s defs = T.sequenceA (cls ++ inst)
where
cls | _generateClasses rules = [makeClassyClass className methodName s defs]
| otherwise = []
inst = [makeClassyInstance rules className methodName s defs]
makeClassyClass ::
Name ->
Name ->
Type {- ^ Outer 's' type -} ->
[(DefName, (OpticType, OpticStab, [(Name, Int, [Int])]))] ->
DecQ
makeClassyClass className methodName s defs = do
let ss = map (stabToS . view (_2 . _2)) defs
(sub,s') <- unifyTypes (s : ss)
c <- newName "c"
let vars = toListOf typeVars s'
fd | null vars = []
| otherwise = [FunDep [c] vars]
classD (cxt[]) className (map PlainTV (c:vars)) fd
$ sigD methodName (return (lens'TypeName `conAppsT` [VarT c, s']))
: concat
[ [sigD defName (return ty)
,valD (varP defName) (normalB body) []
] ++
inlinePragma defName
| (TopName defName, (_, stab, _)) <- defs
, let body = appsE [varE composeValName, varE methodName, varE defName]
, let ty = quantifyType' (Set.fromList (c:vars))
(stabToContext stab)
$ stabToOptic stab `conAppsT`
[VarT c, applyTypeSubst sub (stabToA stab)]
]
makeClassyInstance ::
LensRules ->
Name ->
Name ->
Type {- ^ Outer 's' type -} ->
[(DefName, (OpticType, OpticStab, [(Name, Int, [Int])]))] ->
DecQ
makeClassyInstance rules className methodName s defs = do
methodss <- traverse (makeFieldOptic rules') defs
instanceD (cxt[]) (return instanceHead)
$ valD (varP methodName) (normalB (varE idValName)) []
: map return (concat methodss)
where
instanceHead = className `conAppsT` (s : map VarT vars)
vars = toListOf typeVars s
rules' = rules { _generateSigs = False
, _generateClasses = False
}
------------------------------------------------------------------------
-- Field class generation
------------------------------------------------------------------------
makeFieldClass :: OpticStab -> Name -> Name -> DecQ
makeFieldClass defType className methodName =
classD (cxt []) className [PlainTV s, PlainTV a] [FunDep [s] [a]]
[sigD methodName (return methodType)]
where
methodType = quantifyType' (Set.fromList [s,a])
(stabToContext defType)
$ stabToOptic defType `conAppsT` [VarT s,VarT a]
s = mkName "s"
a = mkName "a"
makeFieldInstance :: OpticStab -> Name -> [DecQ] -> DecQ
makeFieldInstance defType className =
instanceD (cxt [])
(return (className `conAppsT` [stabToS defType, stabToA defType]))
------------------------------------------------------------------------
-- Optic clause generators
------------------------------------------------------------------------
makeFieldClauses :: LensRules -> OpticType -> [(Name, Int, [Int])] -> [ClauseQ]
makeFieldClauses rules opticType cons =
case opticType of
IsoType -> [ makeIsoClause conName | (conName, _, _) <- cons ]
GetterType -> [ makeGetterClause conName fieldCount fields
| (conName, fieldCount, fields) <- cons ]
LensType -> [ makeFieldOpticClause conName fieldCount fields irref
| (conName, fieldCount, fields) <- cons ]
where
irref = _lazyPatterns rules
&& length cons == 1
-- | Construct an optic clause that returns an unmodified value
-- given a constructor name and the number of fields on that
-- constructor.
makePureClause :: Name -> Int -> ClauseQ
makePureClause conName fieldCount =
do xs <- replicateM fieldCount (newName "x")
-- clause: _ (Con x1..xn) = pure (Con x1..xn)
clause [wildP, conP conName (map varP xs)]
(normalB (appE (varE pureValName) (appsE (conE conName : map varE xs))))
[]
-- | Construct an optic clause suitable for a Getter or Fold
-- by visited the fields identified by their 0 indexed positions
makeGetterClause :: Name -> Int -> [Int] -> ClauseQ
makeGetterClause conName fieldCount [] = makePureClause conName fieldCount
makeGetterClause conName fieldCount fields =
do f <- newName "f"
xs <- replicateM (length fields) (newName "x")
let pats (i:is) (y:ys)
| i `elem` fields = varP y : pats is ys
| otherwise = wildP : pats is (y:ys)
pats is _ = map (const wildP) is
fxs = [ appE (varE f) (varE x) | x <- xs ]
body = foldl (\a b -> appsE [varE apValName, a, b])
(appE (varE coerceValName) (head fxs))
(tail fxs)
-- clause f (Con x1..xn) = coerce (f x1) <*> ... <*> f xn
clause [varP f, conP conName (pats [0..fieldCount - 1] xs)]
(normalB body)
[]
-- | Build a clause that updates the field at the given indexes
-- When irref is 'True' the value with me matched with an irrefutable
-- pattern. This is suitable for Lens and Traversal construction
makeFieldOpticClause :: Name -> Int -> [Int] -> Bool -> ClauseQ
makeFieldOpticClause conName fieldCount [] _ =
makePureClause conName fieldCount
makeFieldOpticClause conName fieldCount (field:fields) irref =
do f <- newName "f"
xs <- replicateM fieldCount (newName "x")
ys <- replicateM (1 + length fields) (newName "y")
let xs' = foldr (\(i,x) -> set (ix i) x) xs (zip (field:fields) ys)
mkFx i = appE (varE f) (varE (xs !! i))
body0 = appsE [ varE fmapValName
, lamE (map varP ys) (appsE (conE conName : map varE xs'))
, mkFx field
]
body = foldl (\a b -> appsE [varE apValName, a, mkFx b]) body0 fields
let wrap = if irref then tildeP else id
clause [varP f, wrap (conP conName (map varP xs))]
(normalB body)
[]
-- | Build a clause that constructs an Iso
makeIsoClause :: Name -> ClauseQ
makeIsoClause conName = clause [] (normalB (appsE [varE isoValName, destruct, construct])) []
where
destruct = do x <- newName "x"
lam1E (conP conName [varP x]) (varE x)
construct = conE conName
------------------------------------------------------------------------
-- Unification logic
------------------------------------------------------------------------
-- The field-oriented optic generation supports incorporating fields
-- with distinct but unifiable types into a single definition.
-- | Unify the given list of types, if possible, and return the
-- substitution used to unify the types for unifying the outer
-- type when building a definition's type signature.
unifyTypes :: [Type] -> Q (Map Name Type, Type)
unifyTypes (x:xs) = foldM (uncurry unify1) (Map.empty, x) xs
unifyTypes [] = fail "unifyTypes: Bug: Unexpected empty list"
-- | Attempt to unify two given types using a running substitution
unify1 :: Map Name Type -> Type -> Type -> Q (Map Name Type, Type)
unify1 sub (VarT x) y
| Just r <- Map.lookup x sub = unify1 sub r y
unify1 sub x (VarT y)
| Just r <- Map.lookup y sub = unify1 sub x r
unify1 sub x y
| x == y = return (sub, x)
unify1 sub (AppT f1 x1) (AppT f2 x2) =
do (sub1, f) <- unify1 sub f1 f2
(sub2, x) <- unify1 sub1 x1 x2
return (sub2, AppT (applyTypeSubst sub2 f) x)
unify1 sub x (VarT y)
| elemOf typeVars y (applyTypeSubst sub x) =
fail "Failed to unify types: occurs check"
| otherwise = return (Map.insert y x sub, x)
unify1 sub (VarT x) y = unify1 sub y (VarT x)
-- TODO: Unify contexts
unify1 sub (ForallT v1 [] t1) (ForallT v2 [] t2) =
-- This approach works out because by the time this code runs
-- all of the type variables have been renamed. No risk of shadowing.
do (sub1,t) <- unify1 sub t1 t2
v <- fmap nub (traverse (limitedSubst sub1) (v1++v2))
return (sub1, ForallT v [] t)
unify1 _ x y = fail ("Failed to unify types: " ++ show (x,y))
-- | Perform a limited substitution on type variables. This is used
-- when unifying rank-2 fields when trying to achieve a Getter or Fold.
limitedSubst :: Map Name Type -> TyVarBndr -> Q TyVarBndr
limitedSubst sub (PlainTV n)
| Just r <- Map.lookup n sub =
case r of
VarT m -> limitedSubst sub (PlainTV m)
_ -> fail "Unable to unify exotic higher-rank type"
limitedSubst sub (KindedTV n k)
| Just r <- Map.lookup n sub =
case r of
VarT m -> limitedSubst sub (KindedTV m k)
_ -> fail "Unable to unify exotic higher-rank type"
limitedSubst _ tv = return tv
-- | Apply a substitution to a type. This is used after unifying
-- the types of the fields in unifyTypes.
applyTypeSubst :: Map Name Type -> Type -> Type
applyTypeSubst sub = rewrite aux
where
aux (VarT n) = Map.lookup n sub
aux _ = Nothing
------------------------------------------------------------------------
-- Field generation parameters
------------------------------------------------------------------------
data LensRules = LensRules
{ _simpleLenses :: Bool
, _generateSigs :: Bool
, _generateClasses :: Bool
, _allowIsos :: Bool
, _allowUpdates :: Bool -- ^ Allow Lens/Traversal (otherwise Getter/Fold)
, _lazyPatterns :: Bool
, _fieldToDef :: Name -> [Name] -> Name -> [DefName]
-- ^ Type Name -> Field Names -> Target Field Name -> Definition Names
, _classyLenses :: Name -> Maybe (Name,Name)
-- type name to class name and top method
}
-- | Name to give to generated field optics.
data DefName
= TopName Name -- ^ Simple top-level definiton name
| MethodName Name Name -- ^ makeFields-style class name and method name
deriving (Show, Eq, Ord)
------------------------------------------------------------------------
-- Miscellaneous utility functions
------------------------------------------------------------------------
-- | Template Haskell wants type variables declared in a forall, so
-- we find all free type variables in a given type and declare them.
quantifyType :: Cxt -> Type -> Type
quantifyType c t = ForallT vs c t
where
vs = map PlainTV (toList (setOf typeVars t))
-- | This function works like 'quantifyType' except that it takes
-- a list of variables to exclude from quantification.
quantifyType' :: Set Name -> Cxt -> Type -> Type
quantifyType' exclude c t = ForallT vs c t
where
vs = map PlainTV (toList (setOf typeVars t Set.\\ exclude))
------------------------------------------------------------------------
-- Support for generating inline pragmas
------------------------------------------------------------------------
inlinePragma :: Name -> [DecQ]
#ifdef INLINING
#if MIN_VERSION_template_haskell(2,8,0)
# ifdef OLD_INLINE_PRAGMAS
-- 7.6rc1?
inlinePragma methodName = [pragInlD methodName (inlineSpecNoPhase Inline False)]
# else
-- 7.7.20120830
inlinePragma methodName = [pragInlD methodName Inline FunLike AllPhases]
# endif
#else
-- GHC <7.6, TH <2.8.0
inlinePragma methodName = [pragInlD methodName (inlineSpecNoPhase True False)]
#endif
#else
inlinePragma _ = []
#endif
|
timjb/lens
|
src/Control/Lens/Internal/FieldTH.hs
|
Haskell
|
bsd-3-clause
| 21,608
|
module Test () where
{-@ foo :: {vv:[{v:[a]|((len v) = 1)}]|((len vv)= 1)} -> [[a]] @-}
foo [[x]] = [[x]]
|
abakst/liquidhaskell
|
tests/pos/grty2.hs
|
Haskell
|
bsd-3-clause
| 110
|
module Vec0 () where
import Language.Haskell.Liquid.Prelude
import Data.Vector hiding(map, concat, zipWith, filter, foldl, foldr, (++))
xs = [1,2,3,4] :: [Int]
vs = fromList xs
--prop0 = liquidAssertB (x >= 0)
-- where x = Prelude.head xs
--
--prop1 = liquidAssertB (n > 0)
-- where n = Prelude.length xs
--
--prop2 = liquidAssertB (Data.Vector.length vs > 0)
--prop3 = liquidAssertB (Data.Vector.length vs > 3)
prop6 = crash (0 == 1)
x0 = vs ! 0
|
mightymoose/liquidhaskell
|
tests/neg/vector0a.hs
|
Haskell
|
bsd-3-clause
| 472
|
module T5776 where
-- The point about this test is that we should get a rule like this:
-- "foo" [ALWAYS]
-- forall (@ a)
-- ($dEq :: Eq a)
-- ($dEq1 :: Eq a)
-- (x :: a)
-- (y :: a)
-- (z :: a).
-- T5776.f (g @ a $dEq1 x y)
-- (g @ a $dEq y z)
-- = GHC.Types.True
--
-- Note the *two* forall'd dEq parameters. This is important.
-- See Note [Simplifying RULE lhs constraints] in TcSimplify
{-# RULES "foo" forall x y z.
f (g x y) (g y z) = True
#-}
g :: Eq a => a -> a -> Bool
{-# NOINLINE g #-}
g = (==)
f :: Bool -> Bool -> Bool
{-# NOINLINE f #-}
f a b = False
blah :: Int -> Int -> Bool
blah x y = f (g x y) (g x y)
|
ezyang/ghc
|
testsuite/tests/simplCore/should_compile/T5776.hs
|
Haskell
|
bsd-3-clause
| 713
|
module Main where
import Control.Monad (forever, when)
import Data.List (intercalate)
import Data.Traversable (traverse)
import Morse (stringToMorse, morseToChar)
import System.Environment (getArgs)
import System.Exit (exitFailure,
exitSuccess)
import System.IO (hGetLine, hIsEOF, stdin)
convertToMorse :: IO ()
convertToMorse = forever $ do
weAreDone <- hIsEOF stdin
when weAreDone exitSuccess
line <- hGetLine stdin
convertLine line
where
convertLine line = do
let morse = stringToMorse line
case morse of
(Just str) -> putStrLn (intercalate " " str)
Nothing -> do
putStrLn $ "ERROR: " ++ line
exitFailure
convertFromMorse :: IO ()
convertFromMorse = forever $ do
weAreDone <- hIsEOF stdin
when weAreDone exitSuccess
line <- hGetLine stdin
convertLine line where
convertLine line = do
let decoded :: Maybe String
decoded = traverse morseToChar (words line)
case decoded of
(Just s) -> putStrLn s
Nothing -> do
putStrLn $ "ERROR: " ++ line
exitFailure
main :: IO ()
main = do
mode <- getArgs
case mode of
[arg] ->
case arg of
"from" -> convertFromMorse
"to" -> convertToMorse
_ -> argError
_ -> argError
where
argError = do
putStrLn "Please specify the\
\ first argument\
\ as being 'from' or\
\ 'to' morse,\
\ such as: morse to"
exitFailure
|
candu/haskellbook
|
ch14/morse/src/Main.hs
|
Haskell
|
mit
| 1,530
|
module Handler.Repo where
import Import
import Data.Maybe (fromJust)
import qualified GitHub as GH
getRepoR :: Text -> Text -> Handler Html
getRepoR ownerLogin name = do
-- TODO: Factor all this out.
userId <- requireAuthId
user <- runDB $ get userId
let token = userToken $ fromJust user
client <- GH.newClient token
repo <- GH.fetchRepo client ownerLogin name
milestones <- GH.fetchMilestones client repo GH.AllStates
defaultLayout $ do
setTitle "Milestones"
$(widgetFile "repository")
|
jspahrsummers/ScrumBut
|
Handler/Repo.hs
|
Haskell
|
mit
| 541
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE UnicodeSyntax #-}
module Main where
import Test.Hspec
import Test.QuickCheck
import Data.Word (Word8)
import Codec.Picture ( PixelRGBA8(..)
, Image(..)
, pixelAt)
import Pixs.Operations.Pixel ((⊕))
import qualified Pixs.Transformation as T
import qualified Data.Vector.Storable as VS
import qualified Pixs.Operations.Image as A
import Control.Monad (replicateM)
instance Arbitrary (Image PixelRGBA8) where
arbitrary = do
Positive size ← arbitrary ∷ Gen (Positive Int)
pixs ← listOfSize size
Positive w ← arbitrary ∷ Gen (Positive Int)
let w' = w `rem` size-1
return Image { imageWidth = w'
, imageHeight = w' `div` size-1
, imageData = VS.fromList pixs
}
listOfSize ∷ Int → Gen [Word8]
listOfSize x = fmap concat $ replicateM x genPixel
genPixel ∷ Gen [Word8]
genPixel = do
a ← arbitrary ∷ Gen Word8
b ← arbitrary ∷ Gen Word8
c ← arbitrary ∷ Gen Word8
d ← arbitrary ∷ Gen Word8
return [a,b,c,d]
instance Arbitrary PixelRGBA8 where
arbitrary = do
r ← arbitrary ∷ Gen Word8
g ← arbitrary ∷ Gen Word8
b ← arbitrary ∷ Gen Word8
a ← arbitrary ∷ Gen Word8
return $ PixelRGBA8 r g b a
deriving instance Eq (Image PixelRGBA8)
deriving instance Show (Image PixelRGBA8)
prop_reflexivity ∷ Image PixelRGBA8 → Bool
prop_reflexivity img = img == img
prop_double_reflect_ID ∷ Image PixelRGBA8 → Bool
prop_double_reflect_ID img = if imageWidth img >= 0 && imageHeight img >= 0
then T.reflectVertical (T.reflectVertical img) == img
else True
double_apply_ID ∷ (Image PixelRGBA8 -> Image PixelRGBA8)
→ Image PixelRGBA8
→ Bool
double_apply_ID f img = if imageWidth img >= 0 && imageHeight img >= 0
then (f $ f img) == img
else True
prop_pixel_comm ∷ (PixelRGBA8 → PixelRGBA8 → PixelRGBA8)
→ PixelRGBA8
→ PixelRGBA8
→ Bool
prop_pixel_comm op p₁ p₂ = p₁ `op` p₂ == p₂ `op` p₁
prop_pixel_assoc ∷ (PixelRGBA8 → PixelRGBA8 → PixelRGBA8)
→ PixelRGBA8
→ PixelRGBA8
→ PixelRGBA8
→ Bool
prop_pixel_assoc op p₁ p₂ p₃ = (p₁ `op` p₂) `op` p₃ == p₁ `op` (p₂ `op` p₃)
prop_pixel_dist ∷ (PixelRGBA8 → PixelRGBA8 → PixelRGBA8)
→ (PixelRGBA8 → PixelRGBA8 → PixelRGBA8)
→ PixelRGBA8
→ PixelRGBA8
→ PixelRGBA8
→ Bool
prop_pixel_dist op₁ op₂ p₁ p₂ p₃ =
p₁ `op₁` (p₂ `op₂` p₃) == (p₁ `op₁` p₂) `op₂` (p₁ `op₁` p₃)
&& (p₂ `op₂` p₃) `op₁` p₁ == (p₂ `op₁` p₁) `op₂` (p₃ `op₁` p₁)
prop_change_red_ID ∷ Int → Image PixelRGBA8 → Bool
prop_change_red_ID x img = if (imageWidth img) >= 0 && (imageHeight img) >= 0
then T.changeRed x (T.changeRed (-x) img) == img
else True
prop_red_correct ∷ Int → Positive Int → Positive Int → Image PixelRGBA8 → Bool
prop_red_correct a (Positive x) (Positive y) img
= if (imageWidth img) >= 0 && (imageHeight img) >= 0
then let (PixelRGBA8 r _ _ _) = pixelAt img x y
newImg = T.changeRed a img
(PixelRGBA8 r' _ _ _) = pixelAt newImg x y
in r' == (r ⊕ x)
else True
sides ∷ [Image a] → [Int]
sides = (>>= \x → [imageWidth x, imageHeight x])
prop_image_comm ∷ (Image PixelRGBA8 → Image PixelRGBA8 → Image PixelRGBA8)
→ Image PixelRGBA8
→ Image PixelRGBA8
→ Bool
prop_image_comm op img₁ img₂ =
(any (< 0) $ sides [img₁, img₂])
|| (img₁ `op` img₂) == (img₂ `op` img₁)
prop_image_assoc ∷ (Image PixelRGBA8 → Image PixelRGBA8 → Image PixelRGBA8)
→ Image PixelRGBA8
→ Image PixelRGBA8
→ Image PixelRGBA8
→ Bool
prop_image_assoc op img₁ img₂ img₃ =
(any (< 0) $ sides [img₁, img₂, img₃])
|| (img₁ `op` (img₂ `op` img₃)) == ((img₁ `op` img₂) `op` img₃)
main ∷ IO ()
main = hspec $ do
describe "Image equality" $ do
it "is reflexive" $ property
prop_reflexivity
describe "reflectVertical" $ do
it "gives identity when applied twice" $ property $
double_apply_ID T.reflectVertical
describe "reflectHorizontal" $ do
it "gives identity when applied twice" $ property $
double_apply_ID T.reflectHorizontal
describe "reflect" $ do
it "gives identity when applied twice" $ property $
double_apply_ID T.reflect
describe "Pixel addition" $ do
it "is commutative" $ property $
prop_pixel_comm (+)
it "is associative" $ property $
prop_pixel_assoc (+)
it "correctly adds two arbitrary pixels" $
let p₁ = PixelRGBA8 21 21 21 21
p₂ = PixelRGBA8 30 30 30 30
in p₁ + p₂ `shouldBe` PixelRGBA8 51 51 51 30
it "handles overflow" $
let p₁ = PixelRGBA8 250 250 250 250
p₂ = PixelRGBA8 20 20 20 20
in p₁ + p₂ `shouldBe` PixelRGBA8 255 255 255 250
describe "Pixel subtraction" $
it "handles underflow" $
let p₁ = PixelRGBA8 5 5 5 5
p₂ = PixelRGBA8 20 20 20 20
in p₁ - p₂ `shouldBe` PixelRGBA8 0 0 0 20
describe "Pixel negation" $
it "handles normal case" $
let p = PixelRGBA8 250 250 250 250
in negate p `shouldBe` PixelRGBA8 5 5 5 255
describe "Pixel multiplication" $ do
it "is commutative" $ property $
prop_pixel_comm (*)
it "is associative" $ property $
prop_pixel_assoc (*)
it "is distributive over addition" $ property $
prop_pixel_dist (*) (+)
describe "Image addition" $ do
it "is commutative" $ property $
prop_image_comm A.add
it "is associative" $ property $
prop_image_assoc A.add
describe "Image multiplication" $ do
it "is commutative" $ property $
prop_image_comm A.multiply
it "is associative" $ property $
prop_image_assoc A.multiply
describe "Red adjustment" $ do
it "is correct" $ property $
prop_red_correct
it "Gives ID when applied twice with x and -x" $ property $
prop_change_red_ID
describe "Negation" $ do
let prop_double_neg_ID ∷ Image PixelRGBA8 → Bool
prop_double_neg_ID img = if imageWidth img >= 0 && imageHeight img >= 0
then let img' = T.negateImage . T.negateImage $ img
in img' == img
else True
it "gives ID when applied twice." $ property $
prop_double_neg_ID
|
ayberkt/pixs
|
tests/Spec.hs
|
Haskell
|
mit
| 7,253
|
{-# LANGUAGE OverloadedStrings #-}
module JoScript.Util.JsonTest (tests) where
import Prelude (flip, String, ($), Int)
import Test.HUnit
import JoScript.Util.Json
import Data.Aeson hiding (withObject)
tests = [ TestLabel "JoScript.Util.JsonTest.withObject" withObjectUniques
, TestLabel "JoScript.Util.JsonTest.withObject" withObjectDups
]
withObjectUniques = TestCase $ do
let (a, b) = (1 :: Int, 2 :: Int)
let expected = object ["a" .= a, "b" .= b]
let resulted = withObject ["a" .= a] (object ["b" .= b])
assertEqual "withObject with no duplicated" expected resulted
withObjectDups = TestCase $ do
let (a, b) = (1 :: Int, 2 :: Int)
let expected = object ["a" .= b]
let resulted = withObject ["a" .= b] (object ["a" .= a])
assertEqual "withObject's left should replace values on the right" expected resulted
|
AKST/jo
|
source/test/JoScript/Util/JsonTest.hs
|
Haskell
|
mit
| 848
|
{-|
Module: Treb.Routes
Description: Trebuchet types.
Copyright: Travis Whitaker 2015
License: MIT
Maintainer: twhitak@its.jnj.com
Stability: Provisional
Portability: POSIX
-}
{-# LANGUAGE DataKinds, PolyKinds, RankNTypes, TypeFamilies, TypeOperators,
ScopedTypeVariables, OverloadedStrings, FlexibleContexts,
QuasiQuotes #-}
module Treb.Routes
( TrebApi
, trebApiProxy
, trebServer ) where
import Servant
import Treb.Routes.DataBlockUpload
--import Treb.Routes.DataBlockCreate
--import Treb.Routes.FileUpload
--import Treb.Routes.DataBlockFilter
--import Treb.Routes.DataBlockGet ( DataBlockGetH )
--import Treb.Routes.DataBlockGetMetadata ( DataBlockGetMetadataH )
--import Treb.Routes.DataBlockGetFilter ( DataBlockGetFilterH )
--import Treb.Routes.DataBlockPutMetadata ( DataBlockPutMetadataH )
--import Treb.Routes.JobCreate ( JobCreateH )
--import Treb.Routes.JobFilter ( JobFilterH )
--import Treb.Routes.UserFilter ( UserFilterH )
--import Treb.Routes.UserGet ( UserGetH )
--import Treb.Routes.JobTemplateFilter ( JobTemplateFilterH )
import Treb.Routes.Types
---- Trebuchet API ----
type TrebApi =
---- DataBlock ----
-- NOTE: The following requests captures the "datablock_id" in the URL. This is
-- used instead of DataBlockName because serializing that cleanly is tricky.
-- That ought to be done at a later point. This will require a query to
-- PostgreSQL to determine the DataBlockName so that it may be looked up in the
-- server DataBlockName to DataBlock mapping.
DataBlockUploadH
-- DataBlockCreateH
-- :<|> FileUploadH
-- :<|> DataBlockFilterH
-- :<|> DataBlockGetH
-- :<|> DataBlockGetMetadataH
-- :<|> DataBlockGetFilterH
-- :<|> DataBlockPutMetadataH
--
-- ---- Job ----
-- :<|> JobCreateH
-- :<|> JobFilterH
--
-- ---- User ----
-- :<|> UserFilterH
-- :<|> UserGetH
--
-- ---- Job Template ----
-- :<|> JobTemplateFilterH
trebServer :: TrebServer TrebApi
--trebServer = dataBlockCreateH :<|> fileUploadH
trebServer = dataBlockUploadH -- dataBlockCreateH :<|> fileUploadH :<|> dataBlockFilterH
trebApiProxy :: Proxy TrebApi
trebApiProxy = Proxy
|
MadSciGuys/trebuchet
|
src/Treb/Routes.hs
|
Haskell
|
mit
| 2,268
|
module Network.S3URLSpec
( main
, spec
) where
import Prelude
import Control.Lens
import Data.Aeson
import Data.Monoid ((<>))
import Network.S3URL
import Network.AWS
( Endpoint
, Region(..)
, _svcEndpoint
, endpointHost
, endpointPort
, endpointSecure
)
import Network.AWS.S3 (BucketName(..))
import Test.Hspec
import qualified Data.ByteString.Lazy.Char8 as C8
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "S3URL" $ do
it "parses from JSON" $
withDecoded "http://localhost:4569/my-bucket" $ \url -> do
let ep = serviceEndpoint url
view endpointSecure ep `shouldBe` False
view endpointHost ep `shouldBe` "localhost"
view endpointPort ep `shouldBe` 4569
s3Bucket url `shouldBe` BucketName "my-bucket"
it "parses from JSON without authority" $
withDecoded "http:///my-bucket" $ \url -> do
let ep = serviceEndpoint url
view endpointSecure ep `shouldBe` False
view endpointHost ep `shouldBe` "s3.amazonaws.com"
view endpointPort ep `shouldBe` 80
s3Bucket url `shouldBe` BucketName "my-bucket"
it "parses from JSON without port" $
withDecoded "https://localhost/my-bucket" $ \url -> do
let ep = serviceEndpoint url
view endpointSecure ep `shouldBe` True
view endpointHost ep `shouldBe` "localhost"
view endpointPort ep `shouldBe` 443
it "has nice parse errors" $ do
let Left err1 = eitherDecode "\"ftp://invalid\"" :: Either String S3URL
let Left err2 = eitherDecode "\"https://localhost\"" :: Either String S3URL
err1 `shouldEndWith` "Invalid S3 URL: cannot infer port"
err2 `shouldEndWith` "Invalid S3 URL: bucket not provided"
serviceEndpoint :: S3URL -> Endpoint
serviceEndpoint url = _svcEndpoint (s3Service url) NorthVirginia
withDecoded :: String -> (S3URL -> Expectation) -> Expectation
withDecoded str ex = either failure ex decoded
where
decoded = eitherDecode $ C8.pack $ "\"" <> str <> "\""
failure err = expectationFailure $ unlines
[ "Expected " <> str <> " to parse as JSON"
, "Error: " <> err
]
|
pbrisbin/tee-io
|
test/Network/S3URLSpec.hs
|
Haskell
|
mit
| 2,253
|
import Graphics.Gloss
import System.IO.Unsafe
import System.Environment
import Data.Char
-- | Main entry point to the application.
-- | module Main where
-- | The main entry point.
main = animate (InWindow "Sierpinski Triangles" (500, 650) (20, 20))
black (picture_sierpinski getDegree)
getDegree :: Int
getDegree = (digitToInt (head (head (unsafePerformIO (getArgs)))))
side :: Float
side = 100.0
-- Sierpinski Triangles
picture_sierpinski :: Int -> Float -> Picture
picture_sierpinski degree time
= sierpinski degree time (aquamarine)
-- Base of triangles
base_tri :: Color -> Picture
base_tri color
= Color color
$ Polygon [
((-(side/2)),0),
((side/2),0),
(0,(-(((sqrt 3.0)/2)*side)))]
sierpinski :: Int -> Float -> Color -> Picture
sierpinski 0 time color = base_tri color
sierpinski n time color
= let inner
= Scale 0.5 0.5
$ sierpinski (n-1) time (mix color)
in Pictures
[base_tri color
, Translate (-(side/2)) (-((((sqrt 3.0)/2)*side)/2)) $ inner
, Translate ((side/2)) (-((((sqrt 3.0)/2)*side)/2)) $ inner
, Translate (0) (((((sqrt 3.0)/2)*side)/2)) $ inner]
--
mix :: Color -> Color
mix c = mixColors 1 2 red c
|
kylegodbey/haskellProject
|
src/sierpinski.hs
|
Haskell
|
mit
| 1,256
|
module Util.TextPos (
TextPos(..), append
)
where
import qualified Data.ByteString.UTF8 as BS
import Data.Monoid
type Line = Int
type Column = Int
data TextPos =
TextPos !Line !Column
deriving (Eq,Show)
instance Monoid TextPos where
mempty = TextPos 0 0
mappend (TextPos l1 c1) (TextPos l2 c2) =
TextPos
(l1 + l2)
(if l2 == 0 then c1+c2 else c2)
append :: TextPos -> BS.ByteString -> TextPos
append = BS.foldr f
where
f :: Char -> TextPos -> TextPos
f '\n' (TextPos l c) =
TextPos (l + 1) 0
f _ (TextPos l c) =
TextPos l (c + 1)
|
DrNico/rhodium
|
tools/rhc-strap/Util/TextPos.hs
|
Haskell
|
mit
| 648
|
module Data.AER where
|
fhaust/aer
|
src/Data/AER.hs
|
Haskell
|
mit
| 29
|
module Decibel (Decibel,
mkDecibel,
toDecibel,
fromDecibel) where
data Decibel a = Decibel a
instance Show a => Show (Decibel a) where
show (Decibel a) = show a
mkDecibel :: a -> Decibel a
mkDecibel x = Decibel x
-- from linear to decibels
toDecibel :: (Floating a, Fractional a) => a -> a -> Decibel a
toDecibel p pRef = Decibel (10 * logBase 10 (p / pRef))
fromDecibel :: (Floating a, Fractional a) => Decibel a -> a
fromDecibel (Decibel x) = 10**(x / 10)
|
Vetii/SCFDMA
|
src/Decibel.hs
|
Haskell
|
mit
| 517
|
let timeAction action = getCurrentTime >>= (\t1 -> action >>= (\g -> getCurrentTime >>= (\t2 -> let timeInUnits = (realToFrac $ diffUTCTime t2 t1 :: Float) in return timeInUnits)))
let runData f = randomIO >>= (\randomChar -> if (last (show f)) == randomChar then return () else return ())
-- TODO: deepseq
let timeData d = timeAction (runData d)
seed <- newStdGen
let randomlist n = newStdGen >>= (return . take n . unfoldr (Just . random))
let n = 30 :: Int
ds1 <- mapM (\_ -> randomlist n >>= return . Set.fromList ) [1..n]
ds2 <- mapM (\_ -> randomlist n >>= return . Set.fromList ) [1..n]
let c1 = Set.fromList ds1
let c2 = Set.fromList ds2
timeData (conjunctionOr c1 c2)
|
jprider63/LMonad
|
benchmark/bench.hs
|
Haskell
|
mit
| 683
|
-- Generated by protobuf-simple. DO NOT EDIT!
module Types.Fixed64List where
import Control.Applicative ((<$>))
import Prelude ()
import qualified Data.ProtoBufInt as PB
newtype Fixed64List = Fixed64List
{ value :: PB.Seq PB.Word64
} deriving (PB.Show, PB.Eq, PB.Ord)
instance PB.Default Fixed64List where
defaultVal = Fixed64List
{ value = PB.defaultVal
}
instance PB.Mergeable Fixed64List where
merge a b = Fixed64List
{ value = PB.merge (value a) (value b)
}
instance PB.Required Fixed64List where
reqTags _ = PB.fromList []
instance PB.WireMessage Fixed64List where
fieldToValue (PB.WireTag 1 PB.Bit64) self = (\v -> self{value = PB.append (value self) v}) <$> PB.getFixed64
fieldToValue tag self = PB.getUnknown tag self
messageToFields self = do
PB.putFixed64List (PB.WireTag 1 PB.Bit64) (value self)
|
sru-systems/protobuf-simple
|
test/Types/Fixed64List.hs
|
Haskell
|
mit
| 852
|
-- This is a helper module, defining some commonly used code.
-- Other lessons can import this module.
module Helper
( module Lesson01
) where
import Lesson01 (Suit (..), Rank (..), Card (..), deck)
|
snoyberg/haskell-impatient-poker-players
|
src/Helper.hs
|
Haskell
|
mit
| 208
|
dopt_set dfs f = dfs{ dumpFlags = IntSet.insert (fromEnum f) (dumpFlags dfs) }
|
chreekat/vim-haskell-syntax
|
test/golden/toplevel/with-rec-update-after-eq.hs
|
Haskell
|
mit
| 79
|
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
tests :: TestTree
tests = testGroup "cabal-new"
[ -- testCase "something" specs
]
main :: IO ()
main = defaultMain tests
|
erochest/cabal-new
|
specs/Specs.hs
|
Haskell
|
apache-2.0
| 305
|
-- Defines a list of tests that test the "show" aspects of expressions
-- that is, how they are rendered in to strings by the "show" function
module UnitTests.Show
where
import Test.HUnit (Test(TestCase, TestLabel))
import CAS
import UnitTests.Base
tests = [
TestLabel "Rendering plain symbols" $
TestCase $ do
aE "test1" "x" $ show x
aE "test2" "y" $ show y
aE "test3" "z" $ show z
,
TestLabel "Rendering pre-ordered addition of symbols and constants" $
TestCase $ do
aE "test1" "(x + y)" $ show (x + y)
aE "test2" "(y + z)" $ show (y + z)
aE "test3" "(x + z)" $ show (x + z)
aE "test4" "(x + 2)" $ show (x + 2)
aE "test5" "(y + 3)" $ show (y + 3)
,
TestLabel "Rendering pre-ordered addition of more than two symbols and constants" $
TestCase $ do
aE "test1" "(x + y + z)" $ show (x + y + z)
aE "test2" "(x + y + 3)" $ show (x + y + 3)
,
TestLabel "Rendering subtraction of symbols and constants" $
TestCase $ do
aE "test1" "(x - y)" $ show (x - y)
aE "test2" "(x - 3)" $ show (x - 3)
aE "test3" "(x + y - z)" $ show (x + y - z)
aE "test4" "(x - y + z)" $ show (x - y + z)
,
TestLabel "Rendering addition and subtraction where the first symbol is negative" $
TestCase $ do
aE "test1" "(-x + y)" $ show (-x + y)
aE "test2" "(-x - y)" $ show (-x - y)
,
TestLabel "Rendering pre-ordered constants, symbols and sums being multiplied" $
TestCase $ do
aE "test1" "x y" $ show (x * y)
aE "test2" "2 z" $ show (2 * z)
aE "test3" "-3 x" $ show (-3 * x)
aE "test4" "2 (x + y)" $ show (2 * (x + y))
aE "test5" "2 (x + y) z" $ show (2 * (x + y) * z)
,
TestLabel "Rendering pre-ordered sum of products" $
TestCase $ do
aE "test1" "(2 x + y)" $ show (2 * x + y)
aE "test2" "(-3 x + z)" $ show (-3 * x + z)
aE "test3" "(2 x y + 3 z)" $ show (2 * x * y + 3 * z)
,
TestLabel "Rendering (pre-ordered) products of exponents" $
TestCase $ do
aE "test1" "x^2" $ show (x^2)
aE "test2" "x^3" $ show (x^3)
aE "test3" "x^2 y" $ show (x^2 * y)
aE "test4" "x y^2" $ show (x * y^2)
aE "test5" "x (y + z)" $ show (x * (y + z))
aE "test6" "(x + y)^2" $ show ((x + y)^2)
,
TestLabel "Rendering divided terms" $
TestCase $ do
aE "test1" "1 / x" $ show (1 / x)
aE "test2" "x / y" $ show (x / y)
aE "test3" "1 / x^2" $ show (1 / x^2)
aE "test4" "x / (y z)" $ show (x / (y*z))
aE "test5" "x / (y + z)" $ show (x / (y + z))
aE "test6" "x / 2" $ show (x / 2)
aE "test7" "(x + y) / 2" $ show ((x + y) / 2)
]
|
abid-mujtaba/haskell-cas
|
test/UnitTests/Show.hs
|
Haskell
|
apache-2.0
| 3,493
|
<?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>Getting started Guide</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>Индекс</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Поиск</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>
|
secdec/zap-extensions
|
addOns/gettingStarted/src/main/javahelp/org/zaproxy/zap/extension/gettingStarted/resources/help_ru_RU/helpset_ru_RU.hs
|
Haskell
|
apache-2.0
| 977
|
{-
Copyright 2018 The CodeWorld Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
{- |
This module encapsulates the logics behind the prediction code in the
multi-player setup. It is the “trivially correct” version.
-}
{-# LANGUAGE RecordWildCards, ViewPatterns #-}
module CodeWorld.Prediction.Trivial
( Timestamp
, AnimationRate
, StepFun
, Future
, initFuture
, currentTimePasses
, currentState
, addEvent
, eqFuture
, printInternalState
) where
import Data.Bifunctor (second)
import qualified Data.IntMap as IM
import Data.List (foldl', intercalate)
import qualified Data.MultiMap as M
import Text.Printf
type PlayerId = Int
type Timestamp = Double -- in seconds, relative to some arbitrary starting point
type AnimationRate = Double -- in seconds, e.g. 0.1
-- All we do with events is to apply them to the state. So let's just store the
-- function that does that.
type Event s = s -> s
-- A state and an event only make sense together with a time.
type TState s = (Timestamp, s)
type TEvent s = (Timestamp, Event s)
type StepFun s = Double -> s -> s
type EventQueue s = M.MultiMap (Timestamp, PlayerId) (Event s)
-- | Invariants about the time stamps in this data type:
-- * committed <= pending <= current < future
-- * The time is advanced with strictly ascending timestamps
-- * For each player, events come in with strictly ascending timestamps
-- * For each player, all events in pending or future are before the
-- corresponding lastEvents entry.
data Future s = Future
{ initial :: s
, events :: EventQueue s
}
initFuture :: s -> Int -> Future s
initFuture s _numPlayers = Future {initial = s, events = M.empty}
-- Time handling.
--
-- Move state forward in fixed animation rate steps, and get
-- the timestamp as close to the given target as possible (but possibly stop short)
timePassesBigStep ::
StepFun s -> AnimationRate -> Timestamp -> TState s -> TState s
timePassesBigStep step rate target (now, s)
| now + rate <= target =
timePassesBigStep step rate target (stepBy step rate (now, s))
| otherwise = (now, s)
-- Move state forward in fixed animation rate steps, and get
-- the timestamp as close to the given target as possible, and then do a final small step
timePasses :: StepFun s -> AnimationRate -> Timestamp -> TState s -> TState s
timePasses step rate target =
stepTo step target . timePassesBigStep step rate target
stepBy :: StepFun s -> Double -> TState s -> TState s
stepBy step diff (now, s) = (now + diff, step diff s)
stepTo :: StepFun s -> Timestamp -> TState s -> TState s
stepTo step target (now, s) = (target, step (target - now) s)
handleNextEvent ::
StepFun s -> AnimationRate -> TEvent s -> TState s -> TState s
handleNextEvent step rate (target, event) =
second event . timePasses step rate target
handleNextEvents ::
StepFun s -> AnimationRate -> EventQueue s -> TState s -> TState s
handleNextEvents step rate eq ts =
foldl' (flip (handleNextEvent step rate)) ts $
map (\((t, _p), h) -> (t, h)) $ M.toList eq
-- | This should be called shortly following 'currentTimePasses'
currentState :: StepFun s -> AnimationRate -> Timestamp -> Future s -> s
currentState step rate target f =
snd $
timePasses step rate target $
handleNextEvents step rate to_apply (0, initial f)
where
(to_apply, _) = M.spanAntitone (\(t, p) -> t <= target) (events f)
-- | This should be called regularly, to keep the current state up to date,
-- and to incorporate future events in it.
currentTimePasses ::
StepFun s -> AnimationRate -> Timestamp -> Future s -> Future s
currentTimePasses step rate target = id
-- | Take a new event into account, local or remote.
-- Invariant:
-- * The timestamp of the event is larger than the timestamp
-- of any event added for this player (which is the timestamp for the player
-- in `lastEvents`)
addEvent ::
StepFun s
-> AnimationRate
-> PlayerId
-> Timestamp
-> Maybe (Event s)
-> Future s
-> Future s-- A future event.
addEvent step rate player now mbEvent f =
f {events = maybe id (M.insertR (now, player)) mbEvent $ events f}
-- | Advances the current time (by big steps)
advanceCurrentTime ::
StepFun s -> AnimationRate -> Timestamp -> Future s -> Future s
advanceCurrentTime step rate target = id
eqFuture :: Eq s => Future s -> Future s -> Bool
eqFuture f1 f2 = M.keys (events f1) == M.keys (events f2)
printInternalState :: (s -> String) -> Future s -> IO ()
printInternalState showState f = do
printf " Event keys: %s\n" (show (M.keys (events f)))
|
tgdavies/codeworld
|
codeworld-prediction/src/CodeWorld/Prediction/Trivial.hs
|
Haskell
|
apache-2.0
| 5,164
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QTextEdit_h.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:15
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QTextEdit_h where
import Foreign.C.Types
import Qtc.Enums.Base
import Qtc.Enums.Gui.QPaintDevice
import Qtc.Enums.Core.Qt
import Qtc.Classes.Base
import Qtc.Classes.Qccs_h
import Qtc.Classes.Core_h
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui_h
import Qtc.ClassTypes.Gui
import Foreign.Marshal.Array
instance QunSetUserMethod (QTextEdit ()) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QTextEdit_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
foreign import ccall "qtc_QTextEdit_unSetUserMethod" qtc_QTextEdit_unSetUserMethod :: Ptr (TQTextEdit a) -> CInt -> CInt -> IO (CBool)
instance QunSetUserMethod (QTextEditSc a) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QTextEdit_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
instance QunSetUserMethodVariant (QTextEdit ()) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QTextEdit_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariant (QTextEditSc a) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QTextEdit_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariantList (QTextEdit ()) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QTextEdit_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QunSetUserMethodVariantList (QTextEditSc a) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QTextEdit_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QsetUserMethod (QTextEdit ()) (QTextEdit x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QTextEdit setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QTextEdit_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QTextEdit_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQTextEdit x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTextEdit_setUserMethod" qtc_QTextEdit_setUserMethod :: Ptr (TQTextEdit a) -> CInt -> Ptr (Ptr (TQTextEdit x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethod_QTextEdit :: (Ptr (TQTextEdit x0) -> IO ()) -> IO (FunPtr (Ptr (TQTextEdit x0) -> IO ()))
foreign import ccall "wrapper" wrapSetUserMethod_QTextEdit_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QTextEditSc a) (QTextEdit x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QTextEdit setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QTextEdit_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QTextEdit_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQTextEdit x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetUserMethod (QTextEdit ()) (QTextEdit x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QTextEdit setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QTextEdit_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QTextEdit_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQTextEdit x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTextEdit_setUserMethodVariant" qtc_QTextEdit_setUserMethodVariant :: Ptr (TQTextEdit a) -> CInt -> Ptr (Ptr (TQTextEdit x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethodVariant_QTextEdit :: (Ptr (TQTextEdit x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQTextEdit x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))))
foreign import ccall "wrapper" wrapSetUserMethodVariant_QTextEdit_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QTextEditSc a) (QTextEdit x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QTextEdit setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QTextEdit_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QTextEdit_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQTextEdit x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QunSetHandler (QTextEdit ()) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QTextEdit_unSetHandler cobj_qobj cstr_evid
foreign import ccall "qtc_QTextEdit_unSetHandler" qtc_QTextEdit_unSetHandler :: Ptr (TQTextEdit a) -> CWString -> IO (CBool)
instance QunSetHandler (QTextEditSc a) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QTextEdit_unSetHandler cobj_qobj cstr_evid
instance QsetHandler (QTextEdit ()) (QTextEdit x0 -> QObject t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTextEdit1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTextEdit1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTextEdit_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTextEdit x0) -> Ptr (TQObject t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qTextEditFromPtr x0
x1obj <- qObjectFromPtr x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTextEdit_setHandler1" qtc_QTextEdit_setHandler1 :: Ptr (TQTextEdit a) -> CWString -> Ptr (Ptr (TQTextEdit x0) -> Ptr (TQObject t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTextEdit1 :: (Ptr (TQTextEdit x0) -> Ptr (TQObject t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQTextEdit x0) -> Ptr (TQObject t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QTextEdit1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTextEditSc a) (QTextEdit x0 -> QObject t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTextEdit1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTextEdit1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTextEdit_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTextEdit x0) -> Ptr (TQObject t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qTextEditFromPtr x0
x1obj <- qObjectFromPtr x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QcanInsertFromMimeData_h (QTextEdit ()) ((QMimeData t1)) where
canInsertFromMimeData_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_canInsertFromMimeData cobj_x0 cobj_x1
foreign import ccall "qtc_QTextEdit_canInsertFromMimeData" qtc_QTextEdit_canInsertFromMimeData :: Ptr (TQTextEdit a) -> Ptr (TQMimeData t1) -> IO CBool
instance QcanInsertFromMimeData_h (QTextEditSc a) ((QMimeData t1)) where
canInsertFromMimeData_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_canInsertFromMimeData cobj_x0 cobj_x1
instance QsetHandler (QTextEdit ()) (QTextEdit x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTextEdit2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTextEdit2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTextEdit_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTextEdit x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTextEditFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTextEdit_setHandler2" qtc_QTextEdit_setHandler2 :: Ptr (TQTextEdit a) -> CWString -> Ptr (Ptr (TQTextEdit x0) -> Ptr (TQEvent t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTextEdit2 :: (Ptr (TQTextEdit x0) -> Ptr (TQEvent t1) -> IO ()) -> IO (FunPtr (Ptr (TQTextEdit x0) -> Ptr (TQEvent t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTextEdit2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTextEditSc a) (QTextEdit x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTextEdit2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTextEdit2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTextEdit_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTextEdit x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTextEditFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QchangeEvent_h (QTextEdit ()) ((QEvent t1)) where
changeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_changeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTextEdit_changeEvent" qtc_QTextEdit_changeEvent :: Ptr (TQTextEdit a) -> Ptr (TQEvent t1) -> IO ()
instance QchangeEvent_h (QTextEditSc a) ((QEvent t1)) where
changeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_changeEvent cobj_x0 cobj_x1
instance QcontextMenuEvent_h (QTextEdit ()) ((QContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_contextMenuEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTextEdit_contextMenuEvent" qtc_QTextEdit_contextMenuEvent :: Ptr (TQTextEdit a) -> Ptr (TQContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent_h (QTextEditSc a) ((QContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_contextMenuEvent cobj_x0 cobj_x1
instance QsetHandler (QTextEdit ()) (QTextEdit x0 -> IO (QObject t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTextEdit3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTextEdit3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTextEdit_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTextEdit x0) -> IO (Ptr (TQObject t0))
setHandlerWrapper x0
= do x0obj <- qTextEditFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTextEdit_setHandler3" qtc_QTextEdit_setHandler3 :: Ptr (TQTextEdit a) -> CWString -> Ptr (Ptr (TQTextEdit x0) -> IO (Ptr (TQObject t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTextEdit3 :: (Ptr (TQTextEdit x0) -> IO (Ptr (TQObject t0))) -> IO (FunPtr (Ptr (TQTextEdit x0) -> IO (Ptr (TQObject t0))))
foreign import ccall "wrapper" wrapSetHandler_QTextEdit3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTextEditSc a) (QTextEdit x0 -> IO (QObject t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTextEdit3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTextEdit3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTextEdit_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTextEdit x0) -> IO (Ptr (TQObject t0))
setHandlerWrapper x0
= do x0obj <- qTextEditFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QcreateMimeDataFromSelection_h (QTextEdit ()) (()) where
createMimeDataFromSelection_h x0 ()
= withQMimeDataResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextEdit_createMimeDataFromSelection cobj_x0
foreign import ccall "qtc_QTextEdit_createMimeDataFromSelection" qtc_QTextEdit_createMimeDataFromSelection :: Ptr (TQTextEdit a) -> IO (Ptr (TQMimeData ()))
instance QcreateMimeDataFromSelection_h (QTextEditSc a) (()) where
createMimeDataFromSelection_h x0 ()
= withQMimeDataResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextEdit_createMimeDataFromSelection cobj_x0
instance QdragEnterEvent_h (QTextEdit ()) ((QDragEnterEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_dragEnterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTextEdit_dragEnterEvent" qtc_QTextEdit_dragEnterEvent :: Ptr (TQTextEdit a) -> Ptr (TQDragEnterEvent t1) -> IO ()
instance QdragEnterEvent_h (QTextEditSc a) ((QDragEnterEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_dragEnterEvent cobj_x0 cobj_x1
instance QdragLeaveEvent_h (QTextEdit ()) ((QDragLeaveEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_dragLeaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTextEdit_dragLeaveEvent" qtc_QTextEdit_dragLeaveEvent :: Ptr (TQTextEdit a) -> Ptr (TQDragLeaveEvent t1) -> IO ()
instance QdragLeaveEvent_h (QTextEditSc a) ((QDragLeaveEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_dragLeaveEvent cobj_x0 cobj_x1
instance QdragMoveEvent_h (QTextEdit ()) ((QDragMoveEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_dragMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTextEdit_dragMoveEvent" qtc_QTextEdit_dragMoveEvent :: Ptr (TQTextEdit a) -> Ptr (TQDragMoveEvent t1) -> IO ()
instance QdragMoveEvent_h (QTextEditSc a) ((QDragMoveEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_dragMoveEvent cobj_x0 cobj_x1
instance QdropEvent_h (QTextEdit ()) ((QDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_dropEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTextEdit_dropEvent" qtc_QTextEdit_dropEvent :: Ptr (TQTextEdit a) -> Ptr (TQDropEvent t1) -> IO ()
instance QdropEvent_h (QTextEditSc a) ((QDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_dropEvent cobj_x0 cobj_x1
instance QsetHandler (QTextEdit ()) (QTextEdit x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTextEdit4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTextEdit4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTextEdit_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTextEdit x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qTextEditFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTextEdit_setHandler4" qtc_QTextEdit_setHandler4 :: Ptr (TQTextEdit a) -> CWString -> Ptr (Ptr (TQTextEdit x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTextEdit4 :: (Ptr (TQTextEdit x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQTextEdit x0) -> Ptr (TQEvent t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QTextEdit4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTextEditSc a) (QTextEdit x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTextEdit4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTextEdit4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTextEdit_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTextEdit x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qTextEditFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qevent_h (QTextEdit ()) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_event cobj_x0 cobj_x1
foreign import ccall "qtc_QTextEdit_event" qtc_QTextEdit_event :: Ptr (TQTextEdit a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent_h (QTextEditSc a) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_event cobj_x0 cobj_x1
instance QfocusInEvent_h (QTextEdit ()) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_focusInEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTextEdit_focusInEvent" qtc_QTextEdit_focusInEvent :: Ptr (TQTextEdit a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent_h (QTextEditSc a) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_focusInEvent cobj_x0 cobj_x1
instance QfocusOutEvent_h (QTextEdit ()) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_focusOutEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTextEdit_focusOutEvent" qtc_QTextEdit_focusOutEvent :: Ptr (TQTextEdit a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent_h (QTextEditSc a) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_focusOutEvent cobj_x0 cobj_x1
instance QsetHandler (QTextEdit ()) (QTextEdit x0 -> QObject t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTextEdit5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTextEdit5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTextEdit_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTextEdit x0) -> Ptr (TQObject t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTextEditFromPtr x0
x1obj <- qObjectFromPtr x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTextEdit_setHandler5" qtc_QTextEdit_setHandler5 :: Ptr (TQTextEdit a) -> CWString -> Ptr (Ptr (TQTextEdit x0) -> Ptr (TQObject t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTextEdit5 :: (Ptr (TQTextEdit x0) -> Ptr (TQObject t1) -> IO ()) -> IO (FunPtr (Ptr (TQTextEdit x0) -> Ptr (TQObject t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTextEdit5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTextEditSc a) (QTextEdit x0 -> QObject t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTextEdit5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTextEdit5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTextEdit_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTextEdit x0) -> Ptr (TQObject t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTextEditFromPtr x0
x1obj <- qObjectFromPtr x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QinsertFromMimeData_h (QTextEdit ()) ((QMimeData t1)) where
insertFromMimeData_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_insertFromMimeData cobj_x0 cobj_x1
foreign import ccall "qtc_QTextEdit_insertFromMimeData" qtc_QTextEdit_insertFromMimeData :: Ptr (TQTextEdit a) -> Ptr (TQMimeData t1) -> IO ()
instance QinsertFromMimeData_h (QTextEditSc a) ((QMimeData t1)) where
insertFromMimeData_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_insertFromMimeData cobj_x0 cobj_x1
instance QkeyPressEvent_h (QTextEdit ()) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_keyPressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTextEdit_keyPressEvent" qtc_QTextEdit_keyPressEvent :: Ptr (TQTextEdit a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent_h (QTextEditSc a) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_keyPressEvent cobj_x0 cobj_x1
instance QkeyReleaseEvent_h (QTextEdit ()) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_keyReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTextEdit_keyReleaseEvent" qtc_QTextEdit_keyReleaseEvent :: Ptr (TQTextEdit a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent_h (QTextEditSc a) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_keyReleaseEvent cobj_x0 cobj_x1
instance QsetHandler (QTextEdit ()) (QTextEdit x0 -> Int -> QUrl t2 -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTextEdit6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTextEdit6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTextEdit_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTextEdit x0) -> CInt -> Ptr (TQUrl t2) -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1 x2
= do x0obj <- qTextEditFromPtr x0
let x1int = fromCInt x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1int x2obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTextEdit_setHandler6" qtc_QTextEdit_setHandler6 :: Ptr (TQTextEdit a) -> CWString -> Ptr (Ptr (TQTextEdit x0) -> CInt -> Ptr (TQUrl t2) -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTextEdit6 :: (Ptr (TQTextEdit x0) -> CInt -> Ptr (TQUrl t2) -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQTextEdit x0) -> CInt -> Ptr (TQUrl t2) -> IO (Ptr (TQVariant t0))))
foreign import ccall "wrapper" wrapSetHandler_QTextEdit6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTextEditSc a) (QTextEdit x0 -> Int -> QUrl t2 -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTextEdit6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTextEdit6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTextEdit_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTextEdit x0) -> CInt -> Ptr (TQUrl t2) -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1 x2
= do x0obj <- qTextEditFromPtr x0
let x1int = fromCInt x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1int x2obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QloadResource_h (QTextEdit ()) ((Int, QUrl t2)) where
loadResource_h x0 (x1, x2)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTextEdit_loadResource cobj_x0 (toCInt x1) cobj_x2
foreign import ccall "qtc_QTextEdit_loadResource" qtc_QTextEdit_loadResource :: Ptr (TQTextEdit a) -> CInt -> Ptr (TQUrl t2) -> IO (Ptr (TQVariant ()))
instance QloadResource_h (QTextEditSc a) ((Int, QUrl t2)) where
loadResource_h x0 (x1, x2)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTextEdit_loadResource cobj_x0 (toCInt x1) cobj_x2
instance QmouseDoubleClickEvent_h (QTextEdit ()) ((QMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_mouseDoubleClickEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTextEdit_mouseDoubleClickEvent" qtc_QTextEdit_mouseDoubleClickEvent :: Ptr (TQTextEdit a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent_h (QTextEditSc a) ((QMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_mouseDoubleClickEvent cobj_x0 cobj_x1
instance QmouseMoveEvent_h (QTextEdit ()) ((QMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_mouseMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTextEdit_mouseMoveEvent" qtc_QTextEdit_mouseMoveEvent :: Ptr (TQTextEdit a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseMoveEvent_h (QTextEditSc a) ((QMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_mouseMoveEvent cobj_x0 cobj_x1
instance QmousePressEvent_h (QTextEdit ()) ((QMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_mousePressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTextEdit_mousePressEvent" qtc_QTextEdit_mousePressEvent :: Ptr (TQTextEdit a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmousePressEvent_h (QTextEditSc a) ((QMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_mousePressEvent cobj_x0 cobj_x1
instance QmouseReleaseEvent_h (QTextEdit ()) ((QMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_mouseReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTextEdit_mouseReleaseEvent" qtc_QTextEdit_mouseReleaseEvent :: Ptr (TQTextEdit a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseReleaseEvent_h (QTextEditSc a) ((QMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_mouseReleaseEvent cobj_x0 cobj_x1
instance QpaintEvent_h (QTextEdit ()) ((QPaintEvent t1)) where
paintEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_paintEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTextEdit_paintEvent" qtc_QTextEdit_paintEvent :: Ptr (TQTextEdit a) -> Ptr (TQPaintEvent t1) -> IO ()
instance QpaintEvent_h (QTextEditSc a) ((QPaintEvent t1)) where
paintEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_paintEvent cobj_x0 cobj_x1
instance QresizeEvent_h (QTextEdit ()) ((QResizeEvent t1)) where
resizeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_resizeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTextEdit_resizeEvent" qtc_QTextEdit_resizeEvent :: Ptr (TQTextEdit a) -> Ptr (TQResizeEvent t1) -> IO ()
instance QresizeEvent_h (QTextEditSc a) ((QResizeEvent t1)) where
resizeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_resizeEvent cobj_x0 cobj_x1
instance QsetHandler (QTextEdit ()) (QTextEdit x0 -> Int -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTextEdit7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTextEdit7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTextEdit_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTextEdit x0) -> CInt -> CInt -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- qTextEditFromPtr x0
let x1int = fromCInt x1
let x2int = fromCInt x2
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1int x2int
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTextEdit_setHandler7" qtc_QTextEdit_setHandler7 :: Ptr (TQTextEdit a) -> CWString -> Ptr (Ptr (TQTextEdit x0) -> CInt -> CInt -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTextEdit7 :: (Ptr (TQTextEdit x0) -> CInt -> CInt -> IO ()) -> IO (FunPtr (Ptr (TQTextEdit x0) -> CInt -> CInt -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTextEdit7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTextEditSc a) (QTextEdit x0 -> Int -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTextEdit7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTextEdit7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTextEdit_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTextEdit x0) -> CInt -> CInt -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- qTextEditFromPtr x0
let x1int = fromCInt x1
let x2int = fromCInt x2
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1int x2int
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QscrollContentsBy_h (QTextEdit ()) ((Int, Int)) where
scrollContentsBy_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextEdit_scrollContentsBy cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QTextEdit_scrollContentsBy" qtc_QTextEdit_scrollContentsBy :: Ptr (TQTextEdit a) -> CInt -> CInt -> IO ()
instance QscrollContentsBy_h (QTextEditSc a) ((Int, Int)) where
scrollContentsBy_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextEdit_scrollContentsBy cobj_x0 (toCInt x1) (toCInt x2)
instance QshowEvent_h (QTextEdit ()) ((QShowEvent t1)) where
showEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_showEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTextEdit_showEvent" qtc_QTextEdit_showEvent :: Ptr (TQTextEdit a) -> Ptr (TQShowEvent t1) -> IO ()
instance QshowEvent_h (QTextEditSc a) ((QShowEvent t1)) where
showEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_showEvent cobj_x0 cobj_x1
instance QwheelEvent_h (QTextEdit ()) ((QWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_wheelEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTextEdit_wheelEvent" qtc_QTextEdit_wheelEvent :: Ptr (TQTextEdit a) -> Ptr (TQWheelEvent t1) -> IO ()
instance QwheelEvent_h (QTextEditSc a) ((QWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_wheelEvent cobj_x0 cobj_x1
instance QsetHandler (QTextEdit ()) (QTextEdit x0 -> IO (QSize t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTextEdit8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTextEdit8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTextEdit_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTextEdit x0) -> IO (Ptr (TQSize t0))
setHandlerWrapper x0
= do x0obj <- qTextEditFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTextEdit_setHandler8" qtc_QTextEdit_setHandler8 :: Ptr (TQTextEdit a) -> CWString -> Ptr (Ptr (TQTextEdit x0) -> IO (Ptr (TQSize t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTextEdit8 :: (Ptr (TQTextEdit x0) -> IO (Ptr (TQSize t0))) -> IO (FunPtr (Ptr (TQTextEdit x0) -> IO (Ptr (TQSize t0))))
foreign import ccall "wrapper" wrapSetHandler_QTextEdit8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTextEditSc a) (QTextEdit x0 -> IO (QSize t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTextEdit8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTextEdit8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTextEdit_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTextEdit x0) -> IO (Ptr (TQSize t0))
setHandlerWrapper x0
= do x0obj <- qTextEditFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QqminimumSizeHint_h (QTextEdit ()) (()) where
qminimumSizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextEdit_minimumSizeHint cobj_x0
foreign import ccall "qtc_QTextEdit_minimumSizeHint" qtc_QTextEdit_minimumSizeHint :: Ptr (TQTextEdit a) -> IO (Ptr (TQSize ()))
instance QqminimumSizeHint_h (QTextEditSc a) (()) where
qminimumSizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextEdit_minimumSizeHint cobj_x0
instance QminimumSizeHint_h (QTextEdit ()) (()) where
minimumSizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextEdit_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QTextEdit_minimumSizeHint_qth" qtc_QTextEdit_minimumSizeHint_qth :: Ptr (TQTextEdit a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QminimumSizeHint_h (QTextEditSc a) (()) where
minimumSizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextEdit_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h
instance QqsizeHint_h (QTextEdit ()) (()) where
qsizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextEdit_sizeHint cobj_x0
foreign import ccall "qtc_QTextEdit_sizeHint" qtc_QTextEdit_sizeHint :: Ptr (TQTextEdit a) -> IO (Ptr (TQSize ()))
instance QqsizeHint_h (QTextEditSc a) (()) where
qsizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextEdit_sizeHint cobj_x0
instance QsizeHint_h (QTextEdit ()) (()) where
sizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextEdit_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QTextEdit_sizeHint_qth" qtc_QTextEdit_sizeHint_qth :: Ptr (TQTextEdit a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QsizeHint_h (QTextEditSc a) (()) where
sizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextEdit_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h
instance QviewportEvent_h (QTextEdit ()) ((QEvent t1)) where
viewportEvent_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_viewportEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTextEdit_viewportEvent" qtc_QTextEdit_viewportEvent :: Ptr (TQTextEdit a) -> Ptr (TQEvent t1) -> IO CBool
instance QviewportEvent_h (QTextEditSc a) ((QEvent t1)) where
viewportEvent_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_viewportEvent cobj_x0 cobj_x1
instance QactionEvent_h (QTextEdit ()) ((QActionEvent t1)) where
actionEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_actionEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTextEdit_actionEvent" qtc_QTextEdit_actionEvent :: Ptr (TQTextEdit a) -> Ptr (TQActionEvent t1) -> IO ()
instance QactionEvent_h (QTextEditSc a) ((QActionEvent t1)) where
actionEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_actionEvent cobj_x0 cobj_x1
instance QcloseEvent_h (QTextEdit ()) ((QCloseEvent t1)) where
closeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_closeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTextEdit_closeEvent" qtc_QTextEdit_closeEvent :: Ptr (TQTextEdit a) -> Ptr (TQCloseEvent t1) -> IO ()
instance QcloseEvent_h (QTextEditSc a) ((QCloseEvent t1)) where
closeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_closeEvent cobj_x0 cobj_x1
instance QsetHandler (QTextEdit ()) (QTextEdit x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTextEdit9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTextEdit9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTextEdit_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTextEdit x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- qTextEditFromPtr x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTextEdit_setHandler9" qtc_QTextEdit_setHandler9 :: Ptr (TQTextEdit a) -> CWString -> Ptr (Ptr (TQTextEdit x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTextEdit9 :: (Ptr (TQTextEdit x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQTextEdit x0) -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QTextEdit9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTextEditSc a) (QTextEdit x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTextEdit9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTextEdit9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTextEdit_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTextEdit x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- qTextEditFromPtr x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QdevType_h (QTextEdit ()) (()) where
devType_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextEdit_devType cobj_x0
foreign import ccall "qtc_QTextEdit_devType" qtc_QTextEdit_devType :: Ptr (TQTextEdit a) -> IO CInt
instance QdevType_h (QTextEditSc a) (()) where
devType_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextEdit_devType cobj_x0
instance QenterEvent_h (QTextEdit ()) ((QEvent t1)) where
enterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_enterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTextEdit_enterEvent" qtc_QTextEdit_enterEvent :: Ptr (TQTextEdit a) -> Ptr (TQEvent t1) -> IO ()
instance QenterEvent_h (QTextEditSc a) ((QEvent t1)) where
enterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_enterEvent cobj_x0 cobj_x1
instance QsetHandler (QTextEdit ()) (QTextEdit x0 -> Int -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTextEdit10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTextEdit10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTextEdit_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTextEdit x0) -> CInt -> IO (CInt)
setHandlerWrapper x0 x1
= do x0obj <- qTextEditFromPtr x0
let x1int = fromCInt x1
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj x1int
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTextEdit_setHandler10" qtc_QTextEdit_setHandler10 :: Ptr (TQTextEdit a) -> CWString -> Ptr (Ptr (TQTextEdit x0) -> CInt -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTextEdit10 :: (Ptr (TQTextEdit x0) -> CInt -> IO (CInt)) -> IO (FunPtr (Ptr (TQTextEdit x0) -> CInt -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QTextEdit10_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTextEditSc a) (QTextEdit x0 -> Int -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTextEdit10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTextEdit10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTextEdit_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTextEdit x0) -> CInt -> IO (CInt)
setHandlerWrapper x0 x1
= do x0obj <- qTextEditFromPtr x0
let x1int = fromCInt x1
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj x1int
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QheightForWidth_h (QTextEdit ()) ((Int)) where
heightForWidth_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextEdit_heightForWidth cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTextEdit_heightForWidth" qtc_QTextEdit_heightForWidth :: Ptr (TQTextEdit a) -> CInt -> IO CInt
instance QheightForWidth_h (QTextEditSc a) ((Int)) where
heightForWidth_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextEdit_heightForWidth cobj_x0 (toCInt x1)
instance QhideEvent_h (QTextEdit ()) ((QHideEvent t1)) where
hideEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_hideEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTextEdit_hideEvent" qtc_QTextEdit_hideEvent :: Ptr (TQTextEdit a) -> Ptr (TQHideEvent t1) -> IO ()
instance QhideEvent_h (QTextEditSc a) ((QHideEvent t1)) where
hideEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_hideEvent cobj_x0 cobj_x1
instance QleaveEvent_h (QTextEdit ()) ((QEvent t1)) where
leaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_leaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTextEdit_leaveEvent" qtc_QTextEdit_leaveEvent :: Ptr (TQTextEdit a) -> Ptr (TQEvent t1) -> IO ()
instance QleaveEvent_h (QTextEditSc a) ((QEvent t1)) where
leaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_leaveEvent cobj_x0 cobj_x1
instance QmoveEvent_h (QTextEdit ()) ((QMoveEvent t1)) where
moveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_moveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTextEdit_moveEvent" qtc_QTextEdit_moveEvent :: Ptr (TQTextEdit a) -> Ptr (TQMoveEvent t1) -> IO ()
instance QmoveEvent_h (QTextEditSc a) ((QMoveEvent t1)) where
moveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_moveEvent cobj_x0 cobj_x1
instance QsetHandler (QTextEdit ()) (QTextEdit x0 -> IO (QPaintEngine t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTextEdit11 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTextEdit11_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTextEdit_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTextEdit x0) -> IO (Ptr (TQPaintEngine t0))
setHandlerWrapper x0
= do x0obj <- qTextEditFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTextEdit_setHandler11" qtc_QTextEdit_setHandler11 :: Ptr (TQTextEdit a) -> CWString -> Ptr (Ptr (TQTextEdit x0) -> IO (Ptr (TQPaintEngine t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTextEdit11 :: (Ptr (TQTextEdit x0) -> IO (Ptr (TQPaintEngine t0))) -> IO (FunPtr (Ptr (TQTextEdit x0) -> IO (Ptr (TQPaintEngine t0))))
foreign import ccall "wrapper" wrapSetHandler_QTextEdit11_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTextEditSc a) (QTextEdit x0 -> IO (QPaintEngine t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTextEdit11 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTextEdit11_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTextEdit_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTextEdit x0) -> IO (Ptr (TQPaintEngine t0))
setHandlerWrapper x0
= do x0obj <- qTextEditFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QpaintEngine_h (QTextEdit ()) (()) where
paintEngine_h x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextEdit_paintEngine cobj_x0
foreign import ccall "qtc_QTextEdit_paintEngine" qtc_QTextEdit_paintEngine :: Ptr (TQTextEdit a) -> IO (Ptr (TQPaintEngine ()))
instance QpaintEngine_h (QTextEditSc a) (()) where
paintEngine_h x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextEdit_paintEngine cobj_x0
instance QsetHandler (QTextEdit ()) (QTextEdit x0 -> Bool -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTextEdit12 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTextEdit12_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTextEdit_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTextEdit x0) -> CBool -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTextEditFromPtr x0
let x1bool = fromCBool x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1bool
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTextEdit_setHandler12" qtc_QTextEdit_setHandler12 :: Ptr (TQTextEdit a) -> CWString -> Ptr (Ptr (TQTextEdit x0) -> CBool -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTextEdit12 :: (Ptr (TQTextEdit x0) -> CBool -> IO ()) -> IO (FunPtr (Ptr (TQTextEdit x0) -> CBool -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTextEdit12_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTextEditSc a) (QTextEdit x0 -> Bool -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTextEdit12 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTextEdit12_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTextEdit_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTextEdit x0) -> CBool -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTextEditFromPtr x0
let x1bool = fromCBool x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1bool
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetVisible_h (QTextEdit ()) ((Bool)) where
setVisible_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextEdit_setVisible cobj_x0 (toCBool x1)
foreign import ccall "qtc_QTextEdit_setVisible" qtc_QTextEdit_setVisible :: Ptr (TQTextEdit a) -> CBool -> IO ()
instance QsetVisible_h (QTextEditSc a) ((Bool)) where
setVisible_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextEdit_setVisible cobj_x0 (toCBool x1)
instance QtabletEvent_h (QTextEdit ()) ((QTabletEvent t1)) where
tabletEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_tabletEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTextEdit_tabletEvent" qtc_QTextEdit_tabletEvent :: Ptr (TQTextEdit a) -> Ptr (TQTabletEvent t1) -> IO ()
instance QtabletEvent_h (QTextEditSc a) ((QTabletEvent t1)) where
tabletEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextEdit_tabletEvent cobj_x0 cobj_x1
instance QsetHandler (QTextEdit ()) (QTextEdit x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTextEdit13 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTextEdit13_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTextEdit_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTextEdit x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qTextEditFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTextEdit_setHandler13" qtc_QTextEdit_setHandler13 :: Ptr (TQTextEdit a) -> CWString -> Ptr (Ptr (TQTextEdit x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTextEdit13 :: (Ptr (TQTextEdit x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQTextEdit x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QTextEdit13_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTextEditSc a) (QTextEdit x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTextEdit13 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTextEdit13_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTextEdit_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTextEdit x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qTextEditFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QeventFilter_h (QTextEdit ()) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTextEdit_eventFilter cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QTextEdit_eventFilter" qtc_QTextEdit_eventFilter :: Ptr (TQTextEdit a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter_h (QTextEditSc a) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTextEdit_eventFilter cobj_x0 cobj_x1 cobj_x2
|
keera-studios/hsQt
|
Qtc/Gui/QTextEdit_h.hs
|
Haskell
|
bsd-2-clause
| 72,016
|
module GTKInitialization
( initUI
, buildUI
, setupUI
, startUI
) where
import BattleContext
import GTKContext
import GTKMainWindow
import GTKButtonPanel
import GTKOverlay
import GTKUnit
import qualified Data.Text as DT
import Data.IORef
import Control.Monad.Trans
import Control.Monad.Trans.Reader
import qualified GI.Gtk as Gtk
-- import System.IO.Unsafe
-- import Data.IORef
-- import qualified Data.Text as DT
-- import System.FilePath
-- import Data.Maybe
-- import Control.Monad
-- import Data.GI.Base
-- import qualified GI.Gtk as Gtk
-- import qualified GI.GdkPixbuf as GP
-- -- cairo/gi-cairo stuff
-- import qualified GI.Cairo as GI.Cairo
-- import Graphics.Rendering.Cairo
-- import Graphics.Rendering.Cairo.Internal (Render(runRender))
-- import Graphics.Rendering.Cairo.Types (Cairo(Cairo))
-- import Foreign.Ptr (castPtr)
-- import Control.Monad.Trans.Reader
-- | Early initialization of GTK
initUI :: IO ()
initUI = Gtk.init Nothing
-- | Build GTK ui (both builder and manual widgets) and return its program context
buildUI :: BattleContext -> FilePath -> IO GTKContext
buildUI bctx datadir = do
let f = (uctxDataDir uctx) ++ "/ui-main.glade"
builder <- Gtk.builderNewFromFile (DT.pack f)
-- fetch and construct gtk units
let blueforce = bctxBlueForce bctx
let redforce = bctxRedForce bctx
let iconsdir = datadir ++ "/Icons"
bluegus <- liftIO $ constructForceUnitWidgets iconsdir blueforce
redgus <- liftIO $ constructForceUnitWidgets iconsdir redforce
-- mutable battle context
bctxref <- newIORef bctx
-- gtk units are stored in a mutable list to modify them on the fly
gunitsref <- newIORef $ bluegus ++ redgus
-- attach click events in the gtk context to all units' event boxes
-- _ <- liftIO $ Gtk.onWidgetButtonPressEvent evbox (runReaderT btnOrbatClicked gtkctx)
return $ GTKContext
{ gctxBattleContext = bctxref
, gctxDataDir = datadir
, gctxBuilder = builder
, gctxUnitWidgets = gunitsref
}
-- | Set up signal handlers, widgets, etc in GTK program context
setupUI :: ReaderT GTKContext IO ()
setupUI = do
setupMainWindow
setupButtons
setupOverlay
return ()
-- | Run the GTK program
startUI :: ReaderT GTKContext IO ()
startUI = do
liftIO $ Gtk.main
|
nbrk/ld
|
executable/GTK.hs
|
Haskell
|
bsd-2-clause
| 2,269
|
module TestImport
( module TestImport
, module X
) where
import Test.Hspec as X
import Data.Text as X (Text)
import Database.Persist.Sqlite as X
import Control.Monad.IO.Class as X (liftIO, MonadIO)
import Control.Monad as X (void, liftM)
import Control.Monad.Reader as X (ReaderT)
import Control.Monad.Logger
import Control.Monad.Trans.Resource (ResourceT, MonadBaseControl, runResourceT)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Database.OrgMode as Db
import qualified Database.OrgMode.Internal.Types as Db
-------------------------------------------------------------------------------
setupDb :: (MonadBaseControl IO m, MonadIO m) => ReaderT SqlBackend m ()
setupDb = void $ runMigrationSilent Db.migrateAll
runDb :: forall a. SqlPersistT (NoLoggingT (ResourceT IO)) a -> IO a
runDb a = liftIO $ runSqlite ":memory:" $ setupDb >> a
runDb' :: forall a. SqlPersistT (LoggingT (ResourceT IO)) a -> IO a
runDb' a = liftIO $ runSqlite' ":memory:" $ setupDb >> a
runSqlite' :: forall (m :: * -> *) a.
(MonadIO m, MonadBaseControl IO m)
=> Text
-> SqlPersistT (LoggingT (ResourceT m)) a
-> m a
runSqlite' connstr = runResourceT
. runStderrLoggingT
. withSqliteConn connstr
. runSqlConn
{-|
Imports the given example file to the database
-}
importExample :: (MonadIO m)
=> FilePath
-> ReaderT SqlBackend m (Key Db.Document)
importExample fname = do
contents <- liftIO (getExample fname)
parseImport (T.pack fname) allowedTags contents
where
allowedTags = ["TODO", "DONE"]
{-|
Helper for reading a org-mode example file from the `examples` directory in
test.
-}
getExample :: FilePath -> IO Text
getExample fname = T.readFile $ "test/examples/" ++ fname
{-|
Helper for parsing org-mode document contents and then importing the result
into the database. Does nothing on parsing failure, instead lets the database
test constraints handle the failure (since nothing will be inserted into the
database on parse failure).
-}
parseImport :: (MonadIO m)
=> Text -- ^ Name of the document
-> [Text] -- ^ Keywords to allow
-> Text -- ^ org-mode document contents
-> ReaderT SqlBackend m (Key Db.Document)
parseImport docName keywords contents
= getId `liftM` Db.textImportDocument docName keywords contents
where
getId (Right docId) = docId
getId (Left err) = error err
|
rzetterberg/orgmode-sql
|
test/TestImport.hs
|
Haskell
|
bsd-3-clause
| 2,708
|
import qualified Wigner.Transformations as T
import qualified Wigner.Symbols as S
import qualified Wigner.DefineExpression as D
import qualified Wigner.OperatorAlgebra as O
import Wigner.Texable
import Wigner.Expression
import qualified Data.Map as M
import qualified Data.List as L
index :: Integer -> Index
index i = S.index (fromInteger i :: Int)
a i = D.operatorIx S.a [index i]
b i = D.operatorIx S.b [index i]
s_rho = S.symbol "\\rho"
rho = D.operator s_rho
kappa i = D.constantIx (S.symbol "\\kappa") [index i]
g i j = D.constantIx (S.symbol "g") (L.sort [index i, index j])
gamma1 i = D.constantIx (S.symbol "\\gamma") [index i]
gamma2 i j = D.constantIx (S.symbol "\\gamma") (L.sort [index i, index j])
gamma3 i j k = D.constantIx (S.symbol "\\gamma") (L.sort [index i, index j, index k])
commutator x y = x * y - y * x
lossTerm x = 2 * x * rho * dagger x - dagger x * x * rho - rho * dagger x * x
hamiltonian =
sum (map
(\i -> kappa i * (dagger (a i) * b i + dagger (b i) * a i))
[1, 2])
+ sum (map
(\(i, j) -> g i j * (
dagger (a i) * dagger (a j) * a j * a i +
dagger (b i) * dagger (b j) * b j * b i
) / 2)
[(1,1), (1,2), (2,1), (2,2)])
loss_terms =
gamma1 1 * lossTerm (a 1) +
gamma1 1 * lossTerm (b 1) +
gamma2 1 2 * lossTerm (a 1 * a 2) +
gamma2 1 2 * lossTerm (b 1 * b 2) +
gamma2 2 2 * lossTerm (a 2 * a 2) +
gamma2 2 2 * lossTerm (b 2 * b 2)
--gamma3 1 1 1 * lossTerm (a 1 * a 1 * a 1) +
--gamma3 1 1 1 * lossTerm (b 1 * b 1 * b 1)
master_eqn = -D.i * commutator hamiltonian rho + loss_terms
fpe = T.wignerTransformation S.default_map s_rho master_eqn
main = do
putStrLn $ T.showTexByDifferentials (T.truncateDifferentials 2 fpe)
|
fjarri/wigner
|
examples/master_equation.hs
|
Haskell
|
bsd-3-clause
| 1,759
|
-- | https://github.com/eugenkiss/7guis/wiki#the-seven-tasks
module LGtk.Demos.SevenGuis.Timer (timer) where
import Control.Monad
import Control.Lens
import LGtk
import Numeric
timer :: Widget
timer = do
d <- newRef 10.0
e <- liftM (lensMap _2) $ extendRef d (lens fst $ \(_, t) d -> (d, min t d) ) (0, 0)
let ratio = liftM2 (/) (readRef e) (readRef d) <&> min 1 . max 0
_ <- onChange ratio $ const $ do
t <- readerToCreator $ readRef e
duration <- readerToCreator $ readRef d
when (t < duration) $ asyncWrite 20000 $ writeRef e $ min duration $ t + 0.02
vertically
[ horizontally
[ label (return "Elapsed Time: ")
, progress ratio
]
, horizontally
[ vertically
[ label $ liftM (\v -> showFFloat (Just 2) v $ "s") $ readRef e
, label $ return "Duration: "
]
, hscale 0.0 60.0 10.0 d
]
, button (return "Reset") $ return $ Just $ writeRef e 0
]
|
divipp/lgtk
|
lgtkdemo/LGtk/Demos/SevenGuis/Timer.hs
|
Haskell
|
bsd-3-clause
| 1,044
|
-- | Functions to create a Fragment for (parts of) an abstract syntax tree.
module Language.Python.TypeInference.CFG.ToFragment (
convertModule,
runConversion,
ConversionState
) where
import Control.Monad.State
import Data.Map (Map)
import Data.Maybe
import Data.Set (Set)
import Language.Python.Common.SrcLocation
import Language.Python.TypeInference.CFG.CFG
import Language.Python.TypeInference.CFG.Fragment
import Language.Python.TypeInference.Common
import Language.Python.TypeInference.Error
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Language.Python.Common.AST as AST
-- | Create a fragment for a module.
convertModule :: String -> AST.ModuleSpan
-> StateT ConversionState TypeInferenceMonad (Fragment, Set Identifier)
convertModule moduleName (AST.Module stmts) =
do bound <- lift $ namesBound stmts
moduleNames <- lift $ moduleNamesBound stmts
let bindings = [ (n, Name (ModuleScope moduleName) n)
| n <- Set.toList bound ]
identifiers = map snd bindings
env = Map.fromList bindings
fragment <- withStateT (\cs -> cs { csEnvironment = env,
csCurrentModule = moduleName,
csOtherModules = moduleNames } )
(convertAll stmts)
return (fragment, Set.fromList identifiers)
-- | Create a fragment for a sequence of statements.
convertAll :: [AST.Statement SrcSpan] -> Conversion
convertAll stmts = do fs <- mapM convert stmts
return $ mconcat fs
-- | The environment indicates which name binding a name refers to.
type Environment = Map String Identifier
-- | State maintained while converting from AST to Fragment.
data ConversionState =
ConversionState {
csNextLabel :: Int,
csNextIdentifier :: Int,
csNextFunctionId :: FunctionId,
csNextClassId :: ClassId,
csNextWithId :: Int,
csNextForLoopId :: Int,
csEnvironment :: Environment,
csCurrentModule :: String,
csOtherModules :: Set String,
csExternalModules :: Set String
}
-- | Given the module name and top-level environment, create an initial state.
initialState :: ConversionState
initialState = ConversionState 1 1 1 1 1 1 Map.empty "none" Set.empty Set.empty
-- | Type of a computation that converts from AST to Fragment.
type Conversion = StateT ConversionState TypeInferenceMonad Fragment
-- | Given the module name and top-level environment, run conversion.
runConversion :: Set String
-> Int
-> StateT ConversionState TypeInferenceMonad a
-> TypeInferenceMonad a
runConversion externalModules nextClassId c =
evalStateT c (initialState { csNextClassId = nextClassId
, csExternalModules = externalModules })
-- | Get a new, unique label.
newLabel :: StateT ConversionState TypeInferenceMonad Int
newLabel = do l <- gets csNextLabel
modify $ \s -> s { csNextLabel = l + 1 }
return l
-- | Get a new, unique identifier.
newIdentifier :: StateT ConversionState TypeInferenceMonad Identifier
newIdentifier = do i <- gets csNextIdentifier
modify $ \s -> s { csNextIdentifier = i + 1 }
return $ Generated i
-- | Get a new, unique function id.
newFunctionId :: StateT ConversionState TypeInferenceMonad FunctionId
newFunctionId = do l <- gets csNextFunctionId
modify $ \s -> s { csNextFunctionId = l + 1 }
return l
-- | Get a new, unique class id.
newClassId :: StateT ConversionState TypeInferenceMonad ClassId
newClassId = do l <- gets csNextClassId
modify $ \s -> s { csNextClassId = l + 1 }
return l
-- | Get a new, unique @with@ id.
newWithId :: StateT ConversionState TypeInferenceMonad Int
newWithId = do l <- gets csNextWithId
modify $ \s -> s { csNextWithId = l + 1 }
return l
-- | Get a new, unique @for@ loop id.
newForLoopId :: StateT ConversionState TypeInferenceMonad Int
newForLoopId = do l <- gets csNextForLoopId
modify $ \s -> s { csNextForLoopId = l + 1 }
return l
-- | Look up the given name in the current environment and return the
-- identifier it revers to.
getI :: String -> StateT ConversionState TypeInferenceMonad Identifier
getI name =
do env <- gets csEnvironment
return $ Map.findWithDefault (Name Global name) name env
mkIdentifier :: String -> String
-> StateT ConversionState TypeInferenceMonad Identifier
mkIdentifier moduleName identifierName =
do externalModules <- gets csExternalModules
let scope = if moduleName `Set.member` externalModules
then ExternalScope
else ModuleScope
return $ Name (scope moduleName) identifierName
-- | Execute an action on a state modified by adding a list of bindings to the
-- environment.
withBindings :: [(String, Identifier)]
-> StateT ConversionState TypeInferenceMonad a
-> StateT ConversionState TypeInferenceMonad a
withBindings list m =
do let setEnv env = modify $ \s -> s { csEnvironment = env }
env <- gets csEnvironment
setEnv $ Map.fromList list `Map.union` env
result <- m
setEnv env
return result
-- | Create a new fragment containing one program point.
newFragment :: ProgramPoint -> SrcSpan
-> StateT ConversionState TypeInferenceMonad (Label, Fragment)
newFragment pp srcSpan =
do l <- newLabel
pos <- lift $ toPosition srcSpan
let f = fragment (Map.singleton l (pp, pos))
Set.empty
(Set.singleton l)
(Set.singleton l)
return (l, f)
-- | Like 'newFragment', but don't return the label.
newFragment' :: ProgramPoint -> SrcSpan -> Conversion
newFragment' p s = do (_, f) <- newFragment p s
return f
-- | Create Fragment for a statement.
convert :: AST.Statement SrcSpan -> Conversion
-- Import statements.
convert (AST.Import items s) =
do imports <- mapM imported items
fs <- mapM (importNodes s) imports
return $ mconcat fs
convert (AST.FromImport m i s) =
do imports <- fromImported m i
importNodes s imports
-- While loop.
convert (AST.While cond body els _) =
do (fCondBefore, e) <- toExpression cond
fCondActual <- newFragment' (LoopCondition e) (AST.annot cond)
let fCond = fCondBefore `mappend` fCondActual
fBody <- convertAll body
fEls <- convertAll els
let fs = [fCond, fBody] ++ if nullF fEls then [] else [fEls]
nodes = Map.unions (map getNodes fs)
edges = Set.unions (map getEdges fs)
`Set.union` (fCond --> fBody)
`Set.union` (fBody --> fCond)
`Set.union` (fCond --> fEls)
`Set.union` continueEdges fBody fCond
initial = frInitial fCond
final = getBreak fBody
`Set.union` if nullF fEls
then getFinal fCond
`Set.union` getContinue fBody
else getFinal fEls
break = if nullF fEls then Set.empty else getBreak fEls
continu = if nullF fEls then Set.empty else getContinue fEls
ret = Set.unions $ map getReturn fs
imports = Map.unions $ map getImports fs
ft = Map.unions $ map getFunctionTable fs
return $ Fragment nodes edges initial final break continu ret imports ft
-- For loop.
convert (AST.For targets generator body els _) =
do forLoopId <- newForLoopId
let newBindings = [(n, Name (ForLoopScope forLoopId) n)
| n <- targetNames targets]
newIdentifiers = map snd newBindings
lookupName name = withBindings newBindings (getI name)
(fGenBefore, e) <- toExpression generator
i <- newIdentifier
let srcSpan = AST.annot generator
fGen <- newFragment' (Assignment [TargetIdentifier i] e) srcSpan
let fg = fGenBefore `mappend` fGen
targetList <- mapM (toTarget lookupName) targets
let (fts, ts) = unzip targetList
(lAssign, fAssign) <- newFragment (ForAssign (TargetList ts) i) srcSpan
fBody <- withBindings newBindings (convertAll body)
(sn, sx) <- scopeFragments newIdentifiers srcSpan
let fBefore = mconcat (fts ++ [sn])
fEls <- convertAll els
let fs = [fg, fBefore, fAssign, sx, fBody]
++ if nullF fEls then [] else [fEls]
nodes = Map.unions (map getNodes fs)
edges = Set.unions (map getEdges fs)
`Set.union` (fg --> fBefore)
`Set.union` (fBefore --> fAssign)
`Set.union` (fAssign --> fBody)
`Set.union` (fBody --> fAssign)
`Set.union` (fAssign --> sx)
`Set.union` (sx --> fEls)
`Set.union` continueEdges fBody fAssign
`Set.union`
Set.fromList
[(b, i) | b <- Set.toList (getBreak fBody),
i <- Set.toList (getInitial sx)]
initial = frInitial fg
final = getFinal (if nullF fEls then sx else fEls)
break = if nullF fEls then Set.empty else getBreak fEls
continu = if nullF fEls then Set.empty else getContinue fEls
ret = Set.unions $ map getReturn fs
imports = Map.unions $ map getImports fs
ft = Map.unions $ map getFunctionTable fs
return $ Fragment nodes edges initial final break continu ret imports ft
-- Function definition.
convert (AST.Fun (AST.Ident name _) params _ body s) =
do functionId <- newFunctionId
identifier <- getI name
list <- mapM (toParameter (FunctionScope functionId)) params
let (pfs, ps) = unzip (concat list)
fd <- newFragment' (Def identifier functionId) s
let fd' = mconcat $ pfs ++ [fd]
(ln, fn) <- newFragment (FunctionEntry ps) s
(lx, fx) <- newFragment (FunctionExit ps) s
bound <- lift $ namesBound body
nonlocal <- lift $ declaredNonlocal body
global <- lift $ declaredGlobal body
ps <- lift $ mapM paramName params
moduleName <- gets csCurrentModule
let paramNames = concat ps
newNames = (Set.fromList paramNames `Set.union` bound)
Set.\\ (nonlocal `Set.union` global)
moduleScope = ModuleScope moduleName
newBindings = [ (n, Name (FunctionScope functionId) n)
| n <- Set.toList newNames]
newIdentifiers = map snd newBindings
globalBindings = [(n, Name moduleScope n) | n <- Set.toList global]
fBody <- withBindings (newBindings ++ globalBindings) (convertAll body)
(sn, sx) <- scopeFragments newIdentifiers s
let fs = [fd', fn, fx, fBody, sn, sx]
nodes = Map.unions (map getNodes fs)
edges = getEdges fd'
`Set.union` getEdges fBody
`Set.union` (sn --> fn)
`Set.union` (fn --> fBody)
`Set.union` returnEdges fBody fx
`Set.union` (fx --> sx)
initial = frInitial fd'
final = getFinal fd'
break = Set.empty
continu = Set.empty
ret = Set.empty
imports = Map.unions $ map getImports fs
ft = Map.fromList [ (functionId, (a, b))
| a <- Set.toList (getInitial sn),
b <- Set.toList (getInitial sx) ]
`Map.union`
Map.unions (map getFunctionTable fs)
return $ Fragment nodes edges initial final break continu ret imports ft
-- Class definition.
convert (AST.Class (AST.Ident name _) args body s) =
do list <- mapM toArgument args
let (fs, as) = unzip list
identifier <- getI name
classId <- newClassId
(le, fe) <- newFragment (ClassEntry identifier classId as) s
(lx, fx) <- newFragment (ClassExit identifier classId as) s
bound <- lift $ namesBound body
nonlocal <- lift $ declaredNonlocal body
global <- lift $ declaredGlobal body
moduleName <- gets csCurrentModule
let newNames = bound Set.\\ (nonlocal `Set.union` global)
moduleScope = ModuleScope moduleName
newBindings = [ (n, Name (ClassScope classId) n)
| n <- Set.toList newNames]
newIdentifiers = map snd newBindings
globalBindings = [(n, Name moduleScope n) | n <- Set.toList global]
fb <- withBindings (newBindings ++ globalBindings) (convertAll body)
(sn, sx) <- scopeFragments newIdentifiers s
return $ mconcat (fs ++ [sn, fe, fb, fx, sx])
-- Conditional (if-elif-else).
convert (AST.Conditional ifs els _) =
do list <- mapM convertPair ifs
fEls <- if null els then return EmptyFragment else convertAll els
let (cs, bs) = unzip list
lastCond = last cs
fs = cs ++ bs ++ if null els then [] else [fEls]
nodes = Map.unions (map getNodes fs)
edgesL = map getEdges fs
++ [c --> b | (c, b) <- list]
++ [a --> b | (a, b) <- zip cs (tail cs)]
++ if null els then [] else [lastCond --> fEls]
edges = Set.unions edgesL
initial = frInitial (head cs)
finalL = (if null els then getFinal lastCond else getFinal fEls)
: map getFinal bs
final = Set.unions finalL
break = Set.unions $ map getBreak fs
continu = Set.unions $ map getContinue fs
ret = Set.unions $ map getReturn fs
imports = Map.unions $ map getImports fs
ft = Map.unions (map getFunctionTable fs)
return $ Fragment nodes edges initial final break continu ret imports ft
where convertPair (cond, body) =
do (fCondBefore, e) <- toExpression cond
fCond <- newFragment' (Condition e) (AST.annot cond)
fBody <- convertAll body
return (fCondBefore `mappend` fCond, fBody)
-- Assignment statement (= operator).
convert (AST.Assign lhs rhs s) =
do list <- mapM (toTarget getI) lhs
let (fs, ts) = unzip list
(f2, e) <- toExpression rhs
f3 <- newFragment' (Assignment ts e) s
return $ mconcat (fs ++ [f2, f3])
-- Augmented assignment statement (+=, -=, etc).
convert (AST.AugmentedAssign lhs op rhs s) =
do (f1, t) <- toAugTarget lhs
let o = toAssignmentOperator op
(f2, e) <- toExpression rhs
f3 <- newFragment' (AugmentedAssignment t o e) s
return $ f1 `mappend` f2 `mappend` f3
-- Decorated function or class definition. The decorator is ignored.
convert (AST.Decorated _ stmt _) = convert stmt
-- Return statement.
convert (AST.Return Nothing s) =
do (l, f) <- newFragment (Return Nothing) s
return $ f { frReturn = Set.singleton l,
frFinal = Set.empty }
convert (AST.Return (Just expr) s) =
do (fe, e) <- toExpression expr
(l, fr) <- newFragment (Return $ Just e) s
let f = fe `mappend` fr
return $ f { frReturn = Set.singleton l,
frFinal = Set.empty }
-- Try-catch-finally: We ignore exception handling, so the CFG for a try
-- statement is just the body, else and finally parts concatenated.
convert (AST.Try body _ els finally _) =
do fs <- mapM convertAll [body, els, finally]
return $ mconcat fs
-- Raise statement. Ignored since we don't support exception handling.
convert (AST.Raise _ _) = return EmptyFragment
-- With statement.
convert (AST.With ctx body s) =
do withId <- newWithId
let targets = mapMaybe snd ctx
newBindings = [(n, Name (WithScope withId) n)
| n <- targetNames targets]
newIdentifiers = map snd newBindings
lookupName name = withBindings newBindings (getI name)
list <- mapM (toTarget lookupName) targets
let (fs, ts) = unzip list
(lw, fw) <- newFragment (With ts) s
fBody <- withBindings newBindings (convertAll body)
(sn, sx) <- scopeFragments newIdentifiers s
return $ mconcat (fs ++ [sn, fw, fBody, sx])
-- Pass statement.
convert (AST.Pass s) = newFragment' Pass s
-- Break and continue.
convert (AST.Break s) = do (l, f) <- newFragment Break s
return $ f { frBreak = Set.singleton l,
frFinal = Set.empty }
convert (AST.Continue s) = do (l, f) <- newFragment Continue s
return $ f { frContinue = Set.singleton l,
frFinal = Set.empty }
-- Delete statement.
convert (AST.Delete lhs s) =
do list <- mapM (toTarget getI) lhs
let (fs, ts) = unzip list
f <- newFragment' (Del ts) s
return $ mconcat (fs ++ [f])
-- Statement containing only an expression.
convert (AST.StmtExpr e s) =
do (f, e) <- toExpression e
f' <- newFragment' (Expression e) s
return $ f `mappend` f'
-- Global and nonlocal statements.
convert (AST.Global _ _) = return EmptyFragment
convert (AST.NonLocal _ _) = return EmptyFragment
-- Assertion.
convert (AST.Assert _ s) = newFragment' Assert s
-- Statements that should not occur.
convert (AST.Print _ _ _ _) =
throwError $ CFGError "print statement does not exist in Python 3"
convert (AST.Exec _ _ _) =
throwError $ CFGError "exec statement does not exist in Python 3"
-- | Create 'ImportCall' and 'ImportReturn' nodes.
importNodes :: SrcSpan -> ImportedNames -> Conversion
importNodes s importedNames =
do (lc, fc) <- newFragment ImportCall s
(lr, fr) <- newFragment (ImportReturn importedNames) s
let fromModule = case importedNames of ModuleImport n _ _ -> n
FromImport n _ _ -> n
imports = Map.singleton lc (lr, fromModule)
f = fc `mappend` fr
return $ f { frImports = imports }
-- | Get the names imported by an 'ImportItem'.
imported :: AST.ImportItem SrcSpan
-> StateT ConversionState TypeInferenceMonad ImportedNames
imported (AST.ImportItem dotted as _) =
do currentModule <- gets csCurrentModule
return $ ModuleImport (dottedName dotted)
currentModule
(fmap (\(AST.Ident name _) -> name) as)
-- | Get the names imported by an 'ImportRelative'.
fromImported :: AST.ImportRelative SrcSpan -> AST.FromItems SrcSpan
-> StateT ConversionState TypeInferenceMonad ImportedNames
fromImported (AST.ImportRelative _ name _) (AST.ImportEverything _) =
do currentModule <- gets csCurrentModule
let m = maybeDottedName name
return $ FromImport m currentModule [] -- not really supported
fromImported (AST.ImportRelative _ name _) (AST.FromItems items _) =
do currentModule <- gets csCurrentModule
let m = maybeDottedName name
names = [ (n, fmap (\(AST.Ident name _) -> name) as)
| AST.FromItem (AST.Ident n _) as _ <- items ]
return $ FromImport m currentModule names
maybeDottedName :: Maybe (AST.DottedName SrcSpan) -> String
maybeDottedName Nothing = "__init__"
maybeDottedName (Just x) = dottedName x
-- | Turn a dotted name into a regular module name.
dottedName :: AST.DottedName SrcSpan -> String
dottedName [] = ""
dottedName xs = let AST.Ident name _ = last xs in name
-- | Connect @continue@ statements in the first fragment to the second fragment.
continueEdges :: Fragment -> Fragment -> Set Edge
continueEdges body loop =
Set.fromList [(c, i) | c <- Set.toList (getContinue body),
i <- Set.toList (getInitial loop)]
-- | Connect @return@ statements in the first fragment to the second fragment.
returnEdges :: Fragment -> Fragment -> Set Edge
returnEdges body fx =
Set.fromList [(rf, i) | rf <- Set.toList (getReturn body `Set.union`
getFinal body),
i <- Set.toList (getInitial fx) ]
-- | Find module names bound by @import@ statements.
moduleNamesBound :: AST.Suite SrcSpan -> TypeInferenceMonad (Set String)
moduleNamesBound stmts = collectInScope stmts find
where find (AST.Import items _) =
return $ Set.fromList $ importedModuleNames items
find _ = return Set.empty
-- | Extract the names imported into the environment by an @import ... from
-- ...@ statement.
importedModuleNames :: [AST.ImportItem SrcSpan] -> [String]
importedModuleNames items =
let getName (AST.ImportItem n Nothing _) = dottedName n
getName (AST.ImportItem _ (Just (AST.Ident n _)) _) = n
in map getName items
-- | Find names bound in the suite.
namesBound :: AST.Suite SrcSpan -> TypeInferenceMonad (Set String)
namesBound stmts = collectInScope stmts find
where find (AST.Import items _) =
return $ Set.fromList $ importedModuleNames items
find (AST.FromImport _ (AST.ImportEverything _) _) =
return Set.empty -- not really supported
find (AST.FromImport _ (AST.FromItems items _) _) =
let getName (AST.FromItem (AST.Ident n _) Nothing _) = n
getName (AST.FromItem _ (Just (AST.Ident n _)) _) = n
in return $ Set.fromList $ map getName items
find (AST.Assign lhs _ _) =
return $ Set.fromList (targetNames lhs)
find (AST.AugmentedAssign (AST.Var (AST.Ident name _) _) _ _ _) =
return $ Set.singleton name
find (AST.Delete exprs _) =
let f (AST.Var (AST.Ident name _) _) = Set.singleton name
f _ = Set.empty
in return $ Set.unions (map f exprs)
find (AST.Fun (AST.Ident name _) _ _ _ _) =
return $ Set.singleton name
find (AST.Class (AST.Ident name _) _ _ _) =
return $ Set.singleton name
find (AST.For targets _ body els _) =
do boundInside <- collectInScope (body ++ els) find
let boundByLoop = Set.fromList (targetNames targets)
return $ boundInside Set.\\ boundByLoop
find (AST.With ctx body _) =
do boundInside <- collectInScope body find
let boundByWith = Set.fromList (targetNames (mapMaybe snd ctx))
return $ boundInside Set.\\ boundByWith
find _ = return Set.empty
-- | Find names declared @nonlocal@ in the suite.
declaredNonlocal :: AST.Suite SrcSpan -> TypeInferenceMonad (Set String)
declaredNonlocal stmts = collectInScope stmts find
where find (AST.NonLocal ns _) =
return $ Set.fromList [n | AST.Ident n _ <- ns]
find (AST.For _ _ body els _) = collectInScope (body ++ els) find
find (AST.With _ body _) = collectInScope body find
find _ = return Set.empty
-- | Find names declared @global@ in the suite.
declaredGlobal :: AST.Suite SrcSpan -> TypeInferenceMonad (Set String)
declaredGlobal stmts = collectInScope stmts find
where find (AST.Global ns _) =
return $ Set.fromList [n | AST.Ident n _ <- ns]
find (AST.For _ _ body els _) = collectInScope (body ++ els) find
find (AST.With _ body _) = collectInScope body find
find _ = return Set.empty
-- | Apply a function to all simple statements, and @for@ and @with@
-- statements, in one scope and collect the results.
collectInScope :: Ord a => AST.Suite SrcSpan
-> (AST.Statement SrcSpan -> TypeInferenceMonad (Set a))
-> TypeInferenceMonad (Set a)
collectInScope stmts f =
do results <- mapM f' stmts
return $ Set.unions results
where f' (AST.While _ body els _) =
do list <- mapM f' (body ++ els)
return $ Set.unions list
f' (AST.Conditional guards els _) =
do list <- mapM f' (concatMap snd guards ++ els)
return $ Set.unions list
f' (AST.Try body _ els finally _) =
do list <- mapM f' (body ++ els ++ finally)
return $ Set.unions list
f' stmt = f stmt
-- | Assuming the given list is the target of an assignment, return the names
-- it binds.
targetNames :: [AST.Expr SrcSpan] -> [String]
targetNames targets =
concatMap f targets
where f (AST.Var (AST.Ident n _) _) = [n]
f (AST.Tuple exprs _) = concatMap f exprs
f (AST.List exprs _) = concatMap f exprs
f (AST.Paren expr _) = f expr
f _ = []
-- | Assuming the given expression is the target of an assignment, convert it
-- to the Target type.
toTarget :: (String -> StateT ConversionState TypeInferenceMonad Identifier)
-> AST.Expr SrcSpan
-> StateT ConversionState TypeInferenceMonad (Fragment, Target)
toTarget lookupName (AST.Var (AST.Ident name _) _) =
do identifier <- lookupName name
return (EmptyFragment, TargetIdentifier identifier)
toTarget _ (AST.BinaryOp (AST.Dot _) e (AST.Var (AST.Ident name _) _) _) =
do (f, e) <- toExpression e
return (f, TargetAttributeRef $ AttributeRef e name)
toTarget _ (AST.Subscript x e _) =
do (xf, xe) <- toExpression x
(ef, _) <- toExpression e
return (xf `mappend` ef, TargetSubscription $ Subscription xe)
toTarget _ (AST.SlicedExpr x s _) =
do (xf, xe) <- toExpression x
sf <- mapM fragmentForSlice s
return (mconcat (xf : sf), TargetSlicing $ Slicing xe)
toTarget lookupName (AST.Tuple es _) =
do list <- mapM (toTarget lookupName) es
let (fs, ts) = unzip list
return (mconcat fs, TargetList ts)
toTarget lookupName (AST.List es _) =
do list <- mapM (toTarget lookupName) es
let (fs, ts) = unzip list
return (mconcat fs, TargetList ts)
toTarget lookupName (AST.Starred e _) =
do (f, t) <- toTarget lookupName e
return (f, StarTarget t)
toTarget lookupName (AST.Paren e _) = toTarget lookupName e
toTarget _ e =
throwError $ CFGError $ "invalid expression in target: " ++ show e
-- | Assuming the given expression is the target of an augmented assignment,
-- convert it to the AugTarget type.
toAugTarget :: AST.Expr SrcSpan
-> StateT ConversionState TypeInferenceMonad (Fragment, AugTarget)
toAugTarget (AST.Var (AST.Ident name _) _) =
do identifier <- getI name
return (EmptyFragment, AugTargetIdentifier identifier)
toAugTarget (AST.BinaryOp (AST.Dot _) e (AST.Var (AST.Ident name _) _) _) =
do (f, e) <- toExpression e
return (f, AugTargetAttributeRef $ AttributeRef e name)
toAugTarget (AST.Subscript x e _) =
do (xf, xe) <- toExpression x
(ef, _) <- toExpression e
return (xf `mappend` ef, AugTargetSubscription $ Subscription xe)
toAugTarget (AST.SlicedExpr x s _) =
do (xf, xe) <- toExpression x
sf <- mapM fragmentForSlice s
return (mconcat (xf : sf), AugTargetSlicing $ Slicing xe)
toAugTarget (AST.Paren e _) = toAugTarget e
toAugTarget e =
throwError $ CFGError $ msg ++ show e
where msg = "invalid expression in target for augmented assignment: "
-- | Convert parameters.
toParameter :: Scope
-> AST.Parameter SrcSpan
-> StateT ConversionState TypeInferenceMonad [(Fragment, Parameter)]
toParameter scope (AST.Param (AST.Ident name _) _ Nothing _) =
returnP $ Parameter (Name scope name) Nothing
toParameter scope (AST.Param (AST.Ident name _) _ (Just d) srcSpan) =
do (f, e) <- toExpression d
i <- newIdentifier
fAssign <- newFragment' (Assignment [TargetIdentifier i] e) srcSpan
return [ (f `mappend` fAssign,
Parameter (Name scope name) (Just $ Identifier i)) ]
toParameter scope (AST.VarArgsPos (AST.Ident name _) _ _) =
returnP $ StarParameter (Name scope name)
toParameter scope (AST.VarArgsKeyword (AST.Ident name _) _ _) =
returnP $ StarStarParameter (Name scope name)
toParameter scope (AST.EndPositional _) = return []
toParameter scope (AST.UnPackTuple _ _ _) =
throwError $ CFGError "tuple unpack parameters don't exist in Python 3"
-- | Return the name the parameter, if any.
paramName :: AST.Parameter SrcSpan -> TypeInferenceMonad [String]
paramName (AST.Param (AST.Ident name _) _ _ _) = return [name]
paramName (AST.VarArgsPos (AST.Ident name _) _ _) = return [name]
paramName (AST.VarArgsKeyword (AST.Ident name _) _ _) = return [name]
paramName (AST.EndPositional _) = return []
paramName (AST.UnPackTuple _ _ _) =
throwError $ CFGError "tuple unpack parameters don't exist in Python 3"
-- | Convert expression.
toExpression :: AST.Expr SrcSpan
-> StateT ConversionState TypeInferenceMonad (Fragment, Expression)
-- Parenthesized expression.
toExpression (AST.Paren e _) = toExpression e
-- Variable.
toExpression (AST.Var (AST.Ident name _) _) =
do identifier <- getI name
returnExpression $ Identifier identifier
-- Literal constants.
toExpression (AST.Int val _ _) = returnLiteral $ IntegerLiteral val
toExpression (AST.Float val _ _) = returnLiteral $ FloatLiteral val
toExpression (AST.Imaginary val _ _) = returnLiteral $ ImagLiteral val
toExpression (AST.Bool val _) = returnLiteral $ BoolLiteral val
toExpression (AST.None _) = returnLiteral NoneLiteral
toExpression (AST.ByteStrings l _) = returnLiteral $ ByteStringLiteral $
concat l
toExpression (AST.Strings l _) = returnLiteral $ StringLiteral (concat l)
-- Function call.
toExpression (AST.Call e args s) =
do (f1, e1) <- toExpression e
list <- mapM toArgument args
let (fs, as) = unzip list
f2 = mconcat (f1 : fs)
i <- newIdentifier
lc <- newLabel
lr <- newLabel
pos <- lift $ toPosition s
let f3 = fragment (Map.fromList [(lc, (FunctionCall e1 as lr, pos)),
(lr, (FunctionReturn e1 i lc, pos))])
Set.empty
(Set.singleton lc)
(Set.singleton lr)
return (f2 `mappend` f3, Identifier i)
-- Subscription and slicing.
toExpression (AST.Subscript x e _) =
do (xf, xe) <- toExpression x
(ef, _) <- toExpression e
return (xf `mappend` ef, SubscriptionExpression $ Subscription xe)
toExpression (AST.SlicedExpr x s _) =
do (xf, xe) <- toExpression x
sf <- mapM fragmentForSlice s
return (mconcat (xf : sf), SlicingExpression $ Slicing xe)
-- Conditional expression ('left if cond else right')
toExpression (AST.CondExpr left cond right _) =
do (fcBefore, ec) <- toExpression cond
(flBefore, el) <- toExpression left
(frBefore, er) <- toExpression right
i <- newIdentifier
fc <- newFragment' (Condition ec) (AST.annot cond)
fl <- newFragment' (Assignment [TargetIdentifier i] el) (AST.annot left)
fr <- newFragment' (Assignment [TargetIdentifier i] er) (AST.annot right)
let c = fcBefore `mappend` fc
l = flBefore `mappend` fl
r = frBefore `mappend` fr
nodes = Map.unions $ map getNodes [c, l, r]
edges = Set.unions $ [c --> r, c --> l] ++ map getEdges [c, l, r]
final = getFinal l `Set.union` getFinal r
return (fragment nodes edges (frInitial c) final, Identifier i)
-- Binary operation.
toExpression (AST.BinaryOp (AST.Dot _)
(AST.Var (AST.Ident a _) _)
(AST.Var (AST.Ident b _) _) _) =
do otherModules <- gets csOtherModules
if a `Set.member` otherModules
then do identifier <- mkIdentifier a b
returnExpression $ Identifier identifier
else do identifier <- getI a
returnExpression $
AttributeReference $
AttributeRef (Identifier identifier) b
toExpression (AST.BinaryOp (AST.Dot _) a b _) =
do (f, e) <- toExpression a
case b of
AST.Var (AST.Ident name _) _ ->
return (f, AttributeReference (AttributeRef e name))
_ ->
throwError $ CFGError "invalid attribute reference"
toExpression (AST.BinaryOp op a b _) =
do (f, e) <- toExpression a
o <- lift $ toBinaryOperator op
(f', e') <- toExpression b
return (f `mappend` f', BinaryOperation e o e')
-- Unary operation.
toExpression (AST.UnaryOp op expr _) =
do o <- lift $ toUnaryOperator op
(f, e) <- toExpression expr
return (f, UnaryOperation o e)
-- Lambda expression (anonymous function).
toExpression (AST.Lambda params body s) =
do functionId <- newFunctionId
i <- newIdentifier
(ld, fd) <- newFragment (Def i functionId) s
list <- mapM (toParameter (FunctionScope functionId)) params
let (pfs, ps) = unzip (concat list)
(ln, fn) <- newFragment (FunctionEntry ps) s
(lx, fx) <- newFragment (FunctionExit ps) s
paramNames <- lift $ mapM paramName params
let newBindings = [(n, Name (FunctionScope functionId) n)
| n <- concat paramNames]
(fbBefore, be) <- withBindings newBindings (toExpression body)
(lb, fb) <- newFragment (Return $ Just be) s
let fBody = fbBefore `mappend` fb
let fs = pfs ++ [fd, fn, fx, fBody]
nodes = Map.unions (map getNodes fs)
edges = Set.singleton (lb, lx)
`Set.union` getEdges fBody
`Set.union` (fn --> fBody)
initial = Set.singleton ld
final = Set.singleton ld
break = Set.empty
continu = Set.empty
ret = Set.empty
imports = Map.empty
ft = Map.insert functionId (ln, lx) (getFunctionTable fBody)
return (Fragment nodes edges initial final break continu ret imports ft,
Identifier i)
-- | Tuples, lists, sets and dictionaries.
toExpression (AST.Tuple es _) =
do list <- mapM toExpression es
let (fs, exprs) = unzip list
return (mconcat fs, TupleExpression exprs)
toExpression (AST.List es _) =
do list <- mapM toExpression es
let (fs, exprs) = unzip list
return (mconcat fs, ListExpression exprs)
toExpression (AST.Set es _) =
do list <- mapM toExpression es
let (fs, exprs) = unzip list
return (mconcat fs, SetExpression exprs)
toExpression (AST.Dictionary es _) =
let pairToE (a, b) = do (f1, e1) <- toExpression a
(f2, e2) <- toExpression b
return (f1 `mappend` f2, (e1, e2))
in do list <- mapM pairToE es
let (fs, exprs) = unzip list
return (mconcat fs, DictionaryExpression exprs)
-- List, set and dictionary comprehensions.
toExpression (AST.ListComp comprehension s) =
convertCompr comprehension toExpression ListComprehension
toExpression (AST.SetComp comprehension _) =
convertCompr comprehension toExpression SetComprehension
toExpression (AST.DictComp comprehension _) =
convertCompr comprehension f DictComprehension
where f (a, b) = do (fa, ea) <- toExpression a
(fb, eb) <- toExpression b
return (fb `mappend` fb, (ea, eb))
-- Generator expression and yield statement -- not really supported.
toExpression (AST.Generator _ _) = returnExpression Generator
toExpression (AST.Yield Nothing _) = returnExpression $ Yield Nothing
toExpression (AST.Yield (Just e) _) =
do (f, exp) <- toExpression e
return (f, Yield $ Just exp)
-- Expressions that should not occur here.
toExpression (AST.Starred _ _) =
throwError $ CFGError "starred expression outside of assignment"
toExpression (AST.LongInt _ _ _) =
throwError $ CFGError "long ints don't exist in Python 3"
toExpression (AST.Ellipsis _) =
throwError $ CFGError "ellipsis in expression"
toExpression (AST.StringConversion _ _) =
throwError $ CFGError "backquotes don't exist in Python 3"
-- | Convert comprehension.
convertCompr :: AST.Comprehension a SrcSpan
-> (a -> StateT ConversionState TypeInferenceMonad (Fragment, b))
-> (Identifier -> b -> ProgramPoint)
-> StateT ConversionState TypeInferenceMonad (Fragment, Expression)
convertCompr (AST.Comprehension comprehensionExpr compFor s)
convertComprehensionExpr
pp =
do forLoopId <- newForLoopId
let newBindings = [(n, Name (ForLoopScope forLoopId) n)
| n <- compForNames compFor]
newIdentifiers = map snd newBindings
i <- newIdentifier
(eBefore, e) <- withBindings newBindings $
convertComprehensionExpr comprehensionExpr
fc <- newFragment' (pp i e) s
f <- withBindings newBindings $ compForToFragment compFor
(eBefore `mappend` fc)
(sn, sx) <- scopeFragments newIdentifiers s
return (sn `mappend` f `mappend` sx, Identifier i)
-- | Create fragment for the @for ... in ...@ part of a comprehension.
compForToFragment :: AST.CompFor SrcSpan -> Fragment -> Conversion
compForToFragment (AST.CompFor targets generator next s) inner =
do (gBefore, g) <- toExpression generator
i <- newIdentifier
gAssign <- newFragment' (Assignment [TargetIdentifier i] g) s
let g = gBefore `mappend` gAssign
targetList <- mapM (toTarget getI) targets
let (fts, ts) = unzip targetList
tBefore = mconcat fts
ft <- newFragment' (ForAssign (TargetList ts) i) s
inner' <- compIterToFragment next inner
let ft' = tBefore `mappend` ft
fs = [g, ft', inner']
nodes = Map.unions (map getNodes fs)
edges = Set.unions (map getEdges fs)
`Set.union` (g --> ft')
`Set.union` (ft' --> inner')
`Set.union` (inner' --> ft')
initial = frInitial $ if nullF g then ft' else g
final = frFinal ft'
return $ fragment nodes edges initial final
-- | Create fragment for the @if ...@ part of a comprehension.
compIfToFragment :: AST.CompIf SrcSpan -> Fragment -> Conversion
compIfToFragment (AST.CompIf cond next s) inner =
do (fcBefore, ec) <- toExpression cond
fc <- newFragment' (Condition ec) (AST.annot cond)
inner' <- compIterToFragment next inner
return $ fcBefore `mappend` fc `mappend` inner'
-- | Create fragment for part of a comprehension.
compIterToFragment :: Maybe (AST.CompIter SrcSpan) -> Fragment -> Conversion
compIterToFragment Nothing inner = return inner
compIterToFragment (Just (AST.IterFor f _)) inner = compForToFragment f inner
compIterToFragment (Just (AST.IterIf i _)) inner = compIfToFragment i inner
-- | Find names bound in a list comprehension.
compForNames :: AST.CompFor SrcSpan -> [String]
compForNames (AST.CompFor targets _ next _) = targetNames targets
++ compIterNames next
-- | Find names bound in a list comprehension.
compIfNames :: AST.CompIf SrcSpan -> [String]
compIfNames (AST.CompIf _ next _) = compIterNames next
-- | Find names bound in a list comprehension.
compIterNames :: Maybe (AST.CompIter SrcSpan) -> [String]
compIterNames (Just (AST.IterFor f _)) = compForNames f
compIterNames (Just (AST.IterIf f _)) = compIfNames f
compIterNames Nothing = []
-- | Convert funcation call argument.
toArgument :: AST.Argument SrcSpan
-> StateT ConversionState TypeInferenceMonad (Fragment, Argument)
toArgument (AST.ArgExpr expr _) =
do (f, e) <- toExpression expr
return (f, PositionalArgument e)
toArgument (AST.ArgKeyword (AST.Ident k _) expr _) =
do (f, e) <- toExpression expr
return (f, KeywordArgument k e)
toArgument (AST.ArgVarArgsPos expr _) =
do (f, e) <- toExpression expr
return (f, StarArgument e)
toArgument (AST.ArgVarArgsKeyword expr _) =
do (f, e) <- toExpression expr
return (f, StarStarArgument e)
-- | Convert a slice expression.
fragmentForSlice :: AST.Slice SrcSpan -> Conversion
fragmentForSlice (AST.SliceProper l u s _) =
do f1 <- f l
f2 <- f u
f3 <- case s of Nothing -> return EmptyFragment
Just e -> f e
return $ f1 `mappend` f2 `mappend` f3
where f Nothing = return EmptyFragment
f (Just e) = do (f, _) <- toExpression e
return f
fragmentForSlice (AST.SliceExpr e _) = do (f, _) <- toExpression e
return f
fragmentForSlice (AST.SliceEllipsis _) = return EmptyFragment
returnLiteral l = return (EmptyFragment, Literal l)
returnExpression e = return (EmptyFragment, e)
returnP p = return [(EmptyFragment, p)]
-- | Convert a unary operator.
toUnaryOperator :: AST.Op SrcSpan -> TypeInferenceMonad UnaryOperator
toUnaryOperator (AST.Not _) = return BooleanNot
toUnaryOperator (AST.Minus _) = return UnaryMinus
toUnaryOperator (AST.Plus _) = return UnaryPlus
toUnaryOperator (AST.Invert _) = return Invert
toUnaryOperator op =
throwError $ CFGError ("not a unary operator: " ++ show op)
-- | Convert a binary operator.
toBinaryOperator :: AST.Op SrcSpan -> TypeInferenceMonad BinaryOperator
toBinaryOperator (AST.And _) = return BooleanAnd
toBinaryOperator (AST.Or _) = return BooleanOr
toBinaryOperator (AST.Exponent _) = return Exponent
toBinaryOperator (AST.LessThan _) = return Lt
toBinaryOperator (AST.GreaterThan _) = return Gt
toBinaryOperator (AST.Equality _) = return Eq
toBinaryOperator (AST.GreaterThanEquals _) = return GEq
toBinaryOperator (AST.LessThanEquals _) = return LEq
toBinaryOperator (AST.NotEquals _) = return NEq
toBinaryOperator (AST.In _) = return In
toBinaryOperator (AST.Is _) = return Is
toBinaryOperator (AST.IsNot _) = return IsNot
toBinaryOperator (AST.NotIn _) = return NotIn
toBinaryOperator (AST.BinaryOr _) = return BitwiseOr
toBinaryOperator (AST.Xor _) = return BitwiseXor
toBinaryOperator (AST.BinaryAnd _) = return BitwiseAnd
toBinaryOperator (AST.ShiftLeft _) = return LeftShift
toBinaryOperator (AST.ShiftRight _) = return RightShift
toBinaryOperator (AST.Multiply _) = return Times
toBinaryOperator (AST.Plus _) = return Plus
toBinaryOperator (AST.Minus _) = return Minus
toBinaryOperator (AST.Divide _) = return Div
toBinaryOperator (AST.FloorDivide _) = return DivDiv
toBinaryOperator (AST.Modulo _) = return Modulo
toBinaryOperator (AST.NotEqualsV2 _) =
throwError $ CFGError "<> operator doesn't exist in Python 3"
toBinaryOperator op =
throwError $ CFGError ("not a binary operator: " ++ show op)
-- | Convert an assigment operator.
toAssignmentOperator :: AST.AssignOp SrcSpan -> AssignmentOperator
toAssignmentOperator (AST.PlusAssign _) = PlusGets
toAssignmentOperator (AST.MinusAssign _) = MinusGets
toAssignmentOperator (AST.MultAssign _) = TimesGets
toAssignmentOperator (AST.DivAssign _) = DivGets
toAssignmentOperator (AST.ModAssign _) = ModGets
toAssignmentOperator (AST.PowAssign _) = ExpGets
toAssignmentOperator (AST.BinAndAssign _) = AndGets
toAssignmentOperator (AST.BinOrAssign _) = OrGets
toAssignmentOperator (AST.BinXorAssign _) = XorGets
toAssignmentOperator (AST.LeftShiftAssign _) = LeftShiftGets
toAssignmentOperator (AST.RightShiftAssign _) = RightShiftGets
toAssignmentOperator (AST.FloorDivAssign _) = DivDivGets
-- | Convert a source code position.
toPosition :: SrcSpan -> TypeInferenceMonad Position
toPosition (SpanCoLinear filename row _ _) = return $ Position filename row
toPosition (SpanMultiLine filename row _ _ _) = return $ Position filename row
toPosition (SpanPoint filename row _) = return $ Position filename row
toPosition SpanEmpty =
throwError $ CFGError "missing source location information"
-- | Create ScopeEntry and ScopeExit fragments.
scopeFragments :: [Identifier] -> SrcSpan
-> StateT ConversionState TypeInferenceMonad (Fragment, Fragment)
scopeFragments newIdentifiers srcSpan =
do sn <- newFragment' (ScopeEntry newIdentifiers) srcSpan
sx <- newFragment' (ScopeExit newIdentifiers) srcSpan
return (sn, sx)
|
lfritz/python-type-inference
|
python-type-inference/src/Language/Python/TypeInference/CFG/ToFragment.hs
|
Haskell
|
bsd-3-clause
| 45,554
|
-----------------------------------------------------------------------------
-- |
-- Module : Text.Show.Functions
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- Optional instance of 'Text.Show.Show' for functions:
--
-- > instance Show (a -> b) where
-- > showsPrec _ _ = showString \"\<function\>\"
--
-----------------------------------------------------------------------------
module Text.Show.Functions () where
import Prelude
instance Show (a -> b) where
showsPrec _ _ = showString "<function>"
|
OS2World/DEV-UTIL-HUGS
|
libraries/Text/Show/Functions.hs
|
Haskell
|
bsd-3-clause
| 694
|
-- | Ch04a
module Ch04a where
multThree :: (Num a) => a -> a -> a -> a
multThree x y z = x * y * z
compareWithHundred :: (Num a, Ord a) => a -> Ordering
compareWithHundred = flip compare 100
divideByTen :: (Floating a) => a -> a
divideByTen = (/ 10)
isUpperAlphanum :: Char -> Bool
isUpperAlphanum = (`elem` ['A'..'Z'])
applyTwice :: (a -> a) -> a -> a
applyTwice f x = f (f x)
zipWith' :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith' _ [] _ = []
zipWith' _ _ [] = []
zipWith' f (x:xs) (y:ys) = f x y : zipWith' f xs ys
flip' :: (a -> b -> c) -> (b -> a -> c)
flip' f x y = f y x
map' :: (a -> b) -> [a] -> [b]
map' _ [] = []
map' f (x:xs) = f x : map' f xs
filter' :: (a -> Bool) -> [a] -> [a]
filter' _ [] = []
filter' p (x:xs)
| p x = x : filter' p xs
| otherwise = filter' p xs
quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) =
let smallerSorted = quicksort (filter (<=x) xs)
biggerSorted = quicksort (filter (>x) xs)
in smallerSorted ++ [x] ++ biggerSorted
largestDivisible :: (Integral a) => a
largestDivisible = head (filter' p [10000,9999])
where
p y = y `mod` 3829 == 0
findSum :: Integer
findSum = sum $ takeWhile (<10000) $ filter odd $ map (^ 2) [1..]
findSum' :: Integer
findSum' = sum $ takeWhile (<10000) [x ^ 2 | x <- [1..], odd (x ^ 2)]
chain :: (Integral a) => a -> [a]
chain 1 = [1]
chain x
| even x = x : chain (x `div` 2)
| otherwise = x : chain (x * 3 + 1)
numLongChains :: Int
numLongChains = sum [1 | x <- [1..100], isLong $ chain x]
where isLong xs = length xs > 15
flip'' :: (a -> b -> c) -> b -> a -> c
flip'' f = \x y -> f y x
sum' :: (Num a) => [a] -> a
sum' = foldl (\a x -> a + x) 0
elem' :: (Eq a) => a -> [a] -> Bool
elem' e = foldl (\a y -> if e == y then True else a) False
map'' :: (a -> b) -> [a] -> [b]
map'' f xs = foldr (\x a -> f x : a) [] xs
maximum' :: (Ord a) => [a] -> a
maximum' = foldr1 (\ x a -> if x > a then x else a)
reverse' :: [a] -> [a]
reverse' = foldl (\a x -> x : a) []
product' :: (Num a) => [a] -> a
product' = foldr1 (*)
filter'1 :: (a -> Bool) -> [a] -> [a]
filter'1 p = foldr (\x a -> if p x then x : a else a) []
appl :: [Double]
appl = map ($ 3) [(4+), (10*), (^2), sqrt]
comp :: (Enum b, Num b) => [b]
comp = map (negate . sum . tail) [[1..5],[3..6],[1..7]]
|
codingiam/sandbox-hs
|
src/Ch04a.hs
|
Haskell
|
bsd-3-clause
| 2,303
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
module Main where
#if !(MIN_VERSION_base(4,11,0))
import Data.Monoid ((<>))
#endif
import qualified Graphics.Vty as V
import Brick.Main (App(..), defaultMain, resizeOrQuit, neverShowCursor)
import Brick.Types
( Widget
, Padding(..)
)
import Brick.Widgets.Core
( (<=>)
, (<+>)
, padLeft
)
import Brick.Util (on, fg)
import Brick.Markup (markup, (@?))
import Brick.AttrMap (attrMap, AttrMap)
import Data.Text.Markup ((@@))
ui :: Widget ()
ui = (m1 <=> m2) <+> (padLeft (Pad 1) m3)
where
m1 = markup $ ("Hello" @@ fg V.blue) <> ", " <> ("world!" @@ fg V.red)
m2 = markup $ ("Hello" @? "keyword1") <> ", " <> ("world!" @? "keyword2")
m3 = markup $ ("Hello," @? "keyword1") <> "\n" <> ("world!" @? "keyword2")
theMap :: AttrMap
theMap = attrMap V.defAttr
[ ("keyword1", fg V.magenta)
, ("keyword2", V.white `on` V.blue)
]
app :: App () e ()
app =
App { appDraw = const [ui]
, appHandleEvent = resizeOrQuit
, appAttrMap = const theMap
, appStartEvent = return
, appChooseCursor = neverShowCursor
}
main :: IO ()
main = defaultMain app ()
|
sjakobi/brick
|
programs/MarkupDemo.hs
|
Haskell
|
bsd-3-clause
| 1,202
|
{-# LANGUAGE NoImplicitPrelude #-}
module Protocol.ROC.PointTypes.PointType48 where
import Data.Binary.Get (getByteString,getWord8,Get)
import Data.ByteString (ByteString)
import Data.Word (Word8)
import Prelude (($),
return,
Eq,
Float,
Read,
Show)
import Protocol.ROC.Float (getIeeeFloat32)
import Protocol.ROC.Utils (getTLP)
data PointType48 = PointType48 {
pointType48PointTag :: !PointType48PointTag
,pointType48ControlType :: !PointType48ControlType
,pointType48ActiveLoopStatus :: !PointType48ActiveLoopStatus
,pointType48LoopPeriod :: !PointType48LoopPeriod
,pointType48ActualLoopPeriod :: !PointType48ActualLoopPeriod
,pointType48PrimPVInputPnt :: !PointType48PrimPVInputPnt
,pointType48PrimStpnt :: !PointType48PrimStpnt
,pointType48PrimStpntChangeMax :: !PointType48PrimStpntChangeMax
,pointType48PrimPorpGain :: !PointType48PrimPorpGain
,pointType48PrimResetIntGain :: !PointType48PrimResetIntGain
,pointType48PrimRateDerivGain :: !PointType48PrimRateDerivGain
,pointType48PrimScaleFactor :: !PointType48PrimScaleFactor
,pointType48PrimIntDeadband :: !PointType48PrimIntDeadband
,pointType48PrimProcessVar :: !PointType48PrimProcessVar
,pointType48PrimChangeOutput :: !PointType48PrimChangeOutput
,pointType48OvrdPVInputPnt :: !PointType48OvrdPVInputPnt
,pointType48OvrdStpnt :: !PointType48OvrdStpnt
,pointType48OvrdStpntChangeMax :: !PointType48OvrdStpntChangeMax
,pointType48OvrdPropGain :: !PointType48OvrdPropGain
,pointType48OvrdResetIntGain :: !PointType48OvrdResetIntGain
,pointType48OvrdRateDerivGain :: !PointType48OvrdRateDerivGain
,pointType48OvrdScaleFactor :: !PointType48OvrdScaleFactor
,pointType48OvrdIntDeadband :: !PointType48OvrdIntDeadband
,pointType48OvrdProcessVar :: !PointType48OvrdProcessVar
,pointType48OvrdChangeOutput :: !PointType48OvrdChangeOutput
,pointType48PIDCurrentOutput :: !PointType48PIDCurrentOutput
,pointType48PIDOutputPnt :: !PointType48PIDOutputPnt
,pointType48PID2ndOutput :: !PointType48PID2ndOutput
,pointType48OutputLowLimitValue :: !PointType48OutputLowLimitValue
,pointType48OutputHighLimitValue :: !PointType48OutputHighLimitValue
,pointType48ControlLoopSelecion :: !PointType48ControlLoopSelecion
,pointType48OvrdLoopThreshSwitch :: !PointType48OvrdLoopThreshSwitch
,pointType48PrimLoopPVStpntUnits :: !PointType48PrimLoopPVStpntUnits
,pointType48OvrdPVLoopStpntUnits :: !PointType48OvrdPVLoopStpntUnits
,pointType48PIDOutputUnits :: !PointType48PIDOutputUnits
,pointType48PrimLoopProcessVarLowEu :: !PointType48PrimLoopProcessVarLowEu
,pointType48PrimLoopProcessVarHighEu :: !PointType48PrimLoopProcessVarHighEu
,pointType48OvrdLoopProcessVarLowEu :: !PointType48OvrdLoopProcessVarLowEu
,pointType48OvrdLoopProcessVarHighEu :: !PointType48OvrdLoopProcessVarHighEu
} deriving (Read,Eq, Show)
type PointType48PointTag = ByteString
type PointType48ControlType = Word8
type PointType48ActiveLoopStatus = Word8
type PointType48LoopPeriod = Float
type PointType48ActualLoopPeriod = Float
type PointType48PrimPVInputPnt = [Word8]
type PointType48PrimStpnt = Float
type PointType48PrimStpntChangeMax = Float
type PointType48PrimPorpGain = Float
type PointType48PrimResetIntGain = Float
type PointType48PrimRateDerivGain = Float
type PointType48PrimScaleFactor = Float
type PointType48PrimIntDeadband = Float
type PointType48PrimProcessVar = Float
type PointType48PrimChangeOutput = Float
type PointType48OvrdPVInputPnt = [Word8]
type PointType48OvrdStpnt = Float
type PointType48OvrdStpntChangeMax = Float
type PointType48OvrdPropGain = Float
type PointType48OvrdResetIntGain = Float
type PointType48OvrdRateDerivGain = Float
type PointType48OvrdScaleFactor = Float
type PointType48OvrdIntDeadband = Float
type PointType48OvrdProcessVar = Float
type PointType48OvrdChangeOutput = Float
type PointType48PIDCurrentOutput = Float
type PointType48PIDOutputPnt = [Word8]
type PointType48PID2ndOutput = [Word8]
type PointType48OutputLowLimitValue = Float
type PointType48OutputHighLimitValue = Float
type PointType48ControlLoopSelecion = Word8
type PointType48OvrdLoopThreshSwitch = Float
type PointType48PrimLoopPVStpntUnits = ByteString
type PointType48OvrdPVLoopStpntUnits = ByteString
type PointType48PIDOutputUnits = ByteString
type PointType48PrimLoopProcessVarLowEu = Float
type PointType48PrimLoopProcessVarHighEu = Float
type PointType48OvrdLoopProcessVarLowEu = Float
type PointType48OvrdLoopProcessVarHighEu = Float
pointType48Parser :: Get PointType48
pointType48Parser = do
pointTag <- getByteString 10
controlType <- getWord8
activeLoopStatus <- getWord8
loopPeriod <- getIeeeFloat32
actualLoopPeriod <- getIeeeFloat32
primPVInputPnt <- getTLP
primStpnt <- getIeeeFloat32
primStpntChangeMax <- getIeeeFloat32
primPorpGain <- getIeeeFloat32
primResetIntGain <- getIeeeFloat32
primRateDerivGain <- getIeeeFloat32
primScaleFactor <- getIeeeFloat32
primIntDeadband <- getIeeeFloat32
primProcessVar <- getIeeeFloat32
primChangeOutput <- getIeeeFloat32
ovrdPVInputPnt <- getTLP
ovrdStpnt <- getIeeeFloat32
ovrdStpntChangeMax <- getIeeeFloat32
ovrdPropGain <- getIeeeFloat32
ovrdResetIntGain <- getIeeeFloat32
ovrdRateDerivGain <- getIeeeFloat32
ovrdScaleFactor <- getIeeeFloat32
ovrdIntDeadband <- getIeeeFloat32
ovrdProcessVar <- getIeeeFloat32
ovrdChangeOutput <- getIeeeFloat32
pIDCurrentOutput <- getIeeeFloat32
pIDOutputPnt <- getTLP
pID2ndOutput <- getTLP
outputLowLimitValue <- getIeeeFloat32
outputHighLimitValue <- getIeeeFloat32
controlLoopSelecion <- getWord8
ovrdLoopThreshSwitch <- getIeeeFloat32
primLoopPVStpntUnits <- getByteString 10
ovrdPVLoopStpntUnits <- getByteString 10
pIDOutputUnits <- getByteString 10
primLoopProcessVarLowEu <- getIeeeFloat32
primLoopProcessVarHighEu <- getIeeeFloat32
ovrdLoopProcessVarLowEu <- getIeeeFloat32
ovrdLoopProcessVarHighEu <- getIeeeFloat32
return $ PointType48 pointTag controlType activeLoopStatus loopPeriod actualLoopPeriod primPVInputPnt primStpnt primStpntChangeMax primPorpGain primResetIntGain primRateDerivGain
primScaleFactor primIntDeadband primProcessVar primChangeOutput ovrdPVInputPnt ovrdStpnt ovrdStpntChangeMax ovrdPropGain ovrdResetIntGain ovrdRateDerivGain ovrdScaleFactor
ovrdIntDeadband ovrdProcessVar ovrdChangeOutput pIDCurrentOutput pIDOutputPnt pID2ndOutput outputLowLimitValue outputHighLimitValue controlLoopSelecion ovrdLoopThreshSwitch
primLoopPVStpntUnits ovrdPVLoopStpntUnits pIDOutputUnits primLoopProcessVarLowEu primLoopProcessVarHighEu ovrdLoopProcessVarLowEu ovrdLoopProcessVarHighEu
|
plow-technologies/roc-translator
|
src/Protocol/ROC/PointTypes/PointType48.hs
|
Haskell
|
bsd-3-clause
| 13,232
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DataKinds #-}
#if __GLASGOW_HASKELL__ < 800
{-# OPTIONS_GHC -fcontext-stack=26 #-}
#else
{-# OPTIONS_GHC -freduction-depth=0 #-}
#endif
--------------------------------------------------------------------------------
-- |
-- Module : Database.EventStore.Internal.Operation.ReadEvent.Message
-- Copyright : (C) 2015 Yorick Laupa
-- License : (see the file LICENSE)
--
-- Maintainer : Yorick Laupa <yo.eight@gmail.com>
-- Stability : provisional
-- Portability : non-portable
--
--------------------------------------------------------------------------------
module Database.EventStore.Internal.Operation.ReadEvent.Message where
--------------------------------------------------------------------------------
import Data.Int
--------------------------------------------------------------------------------
import Data.ProtocolBuffers
--------------------------------------------------------------------------------
import Database.EventStore.Internal.Prelude
import Database.EventStore.Internal.Types
--------------------------------------------------------------------------------
-- | Read event on a regular stream request.
data Request
= Request
{ _streamId :: Required 1 (Value Text)
, _eventNumber :: Required 2 (Value Int64)
, _resolveLinkTos :: Required 3 (Value Bool)
, _requireMaster :: Required 4 (Value Bool)
}
deriving (Generic, Show)
--------------------------------------------------------------------------------
instance Encode Request
--------------------------------------------------------------------------------
-- | 'Request' smart constructor.
newRequest :: Text -> Int64 -> Bool -> Bool -> Request
newRequest stream_id evt_num res_link_tos req_master =
Request
{ _streamId = putField stream_id
, _eventNumber = putField evt_num
, _resolveLinkTos = putField res_link_tos
, _requireMaster = putField req_master
}
--------------------------------------------------------------------------------
-- | Enumeration representing the status of a single event read operation.
data Result
= SUCCESS
| NOT_FOUND
| NO_STREAM
| STREAM_DELETED
| ERROR
| ACCESS_DENIED
deriving (Eq, Enum, Show)
--------------------------------------------------------------------------------
-- | Read event on a regular stream response.
data Response
= Response
{ _result :: Required 1 (Enumeration Result)
, _indexedEvent :: Required 2 (Message ResolvedIndexedEvent)
, _error :: Optional 3 (Value Text)
}
deriving (Generic, Show)
--------------------------------------------------------------------------------
instance Decode Response
instance Encode Response
|
YoEight/eventstore
|
Database/EventStore/Internal/Operation/ReadEvent/Message.hs
|
Haskell
|
bsd-3-clause
| 2,800
|
module Day11 where
import Control.Arrow
import Data.Function
import Data.List
import Data.Maybe
partOne = nextGoodPass input
partTwo = nextGoodPass partOne
nextGoodPass :: String -> String
nextGoodPass s = fromJust $ find goodPass $ filter (/= s) $ iterate nextWord s
nextWord :: String -> String
nextWord = reverse . revNextWord . reverse
revNextWord :: String -> String
revNextWord (x:xs)
| x < 'z' = nextChar x : xs
| otherwise = 'a' : revNextWord xs
nextChar :: Char -> Char
nextChar c = head $ dropWhile (c >=) ['a'..'z']
goodPass :: String -> Bool
goodPass s = stringOfThree s && noLetters "iol" s && twoNonOverlappingPairs s
stringOfThree :: String -> Bool
stringOfThree = any (`isInfixOf` ['a'..'z']) . filter ((==) 3 . length) . map (take 3) . tails
noLetters :: String -> String -> Bool
noLetters s = all (`notElem` s)
twoNonOverlappingPairs :: String -> Bool
twoNonOverlappingPairs = (> 1) . length . nubBy ((==) `on` fst) . filter (\cs -> snd cs > 1) . map (head &&& length) . group
input :: String
input = "hxbxwxba"
|
z0isch/advent-of-code
|
src/Day11.hs
|
Haskell
|
bsd-3-clause
| 1,085
|
-- | All types.
module Senza.Types
(Senza)
where
import Text.Blaze.Html (Markup)
-- | The type for an HTML value. In case blaze changes its type again.
type Senza = Markup
|
chrisdone/senza
|
src/Senza/Types.hs
|
Haskell
|
bsd-3-clause
| 179
|
module TestImportFile (tests) where
import Asserts
import Bucket.Import
import Bucket.Types
import Control.Exception
import Fixtures
import Prelude hiding (catch)
import System.FilePath
import Test.Hspec.HUnit()
import Test.Hspec.Monadic
import Test.Hspec.QuickCheck
import Test.HUnit
import Test.QuickCheck
tests = describe "importing a file" $ do
it "copies it inside the bucket" $ withBucket $ \((tmpDir, bucket)) -> do
aSourceFile <- createEmptyFile $ tmpDir </> "a-file.png"
importFile bucket aSourceFile
assertFileExists (bucketPath bucket </> "a-file-1" </> "a-file.png")
it "creates a meta.txt file" $ withBucket $ \((tmpDir, bucket)) -> do
aSourceFile <- createEmptyFile $ tmpDir </> "a-file.png"
importFile bucket aSourceFile
let metaFile = (bucketPath bucket </> "a-file-1" </> "meta.txt")
assertFileContains metaFile "name::a-file.png\n"
it "writes the current modification date to meta" $ withBucket $ \((tmpDir, bucket)) -> do
aSourceFile <- createEmptyFile $ tmpDir </> "a-file.png"
setModificationTime aSourceFile 2012 2 15
importFile bucket aSourceFile
let metaFile = (bucketPath bucket </> "a-file-1" </> "meta.txt")
assertFileContains metaFile "creationdate::2012-02-15\n"
it "copies modification time" $ withBucket $ \((tmpDir, bucket)) -> do
aSourceFile <- createEmptyFile $ tmpDir </> "a-file.png"
setModificationTime aSourceFile 2012 2 15
mtime1 <- getMtime aSourceFile
importFile bucket aSourceFile
mtime2 <- getMtime (bucketPath bucket </> "a-file-1" </> "a-file.png")
assertEqual "" mtime1 mtime2
it "updates the bucket" $ withBucket $ \((tmpDir, bucket)) -> do
file1 <- createEmptyFile $ tmpDir </> "file1.png"
file2 <- createEmptyFile $ tmpDir </> "file2.png"
bucket <- importFile bucket file1
bucket <- importFile bucket file2
bucket `assertHasItems` [bucketPath bucket </> "file1-1", bucketPath bucket </> "file2-1"]
it "does not leave a trace in bucket if importing fails" $ withBucket $ \((tmpDir, bucket)) -> do
let importNonExistingFile = do
importFile bucket (tmpDir </> "nonExistingFile.png")
assertFailure "importing should have thrown IOException"
let assertBucketHasNoTraceOfFile = \e -> do
let _ = (e :: IOException)
assertDirectoryDoesNotExist $ bucketPath bucket </> "nonExistingFile-1"
catch importNonExistingFile assertBucketHasNoTraceOfFile
describe "item name" $ do
prop "is unique" $
forAll ourListOfStrings $ \itemNames ->
let newItemName = createItemName itemNames ("/tmp/" ++ aItem ++ ".png")
aItem = itemPath $ head itemNames
in newItemName `notElem` map itemPath itemNames
it "when it's the only file" $
createItemName [] "/tmp/foo.png" @?= "foo-1"
it "when it's the third file with the same name" $
createItemName [anItemWithName "foo", anItemWithName "foo-1"] "/tmp/foo.png" @?= "foo-2"
it "when one of the existing items with same name has been deleted" $
createItemName [anItemWithName "foo", anItemWithName "foo-2"] "/tmp/foo.png" @?= "foo-1"
|
rickardlindberg/orgapp
|
tests/TestImportFile.hs
|
Haskell
|
bsd-3-clause
| 3,329
|
module MatchTheTypes where
import Data.List (sort)
i :: Num a => a
i = 1
f :: Fractional a => a
f = 1.0
g :: RealFrac a => a
g = 1.0
freud :: Ord a => a -> a
freud x = x
freud' :: Int -> Int
freud' x = x
myX = 1 :: Int
sigmund :: Int -> Int
sigmund x = myX
jung :: Ord a => [a] -> a
jung xs = head (sort xs)
jung' :: [Int] -> Int
jung' xs = head (sort xs)
young :: [Char] -> Char
young xs = head (sort xs)
young' :: Ord a => [a] -> a
young' xs = head (sort xs)
mysort :: [Char] -> [Char]
mysort = sort
signifier :: [Char] -> Char
signifier xs = head (mysort xs)
mysort' :: [Char] -> [Char]
mysort' = sort
-- won't type checked
signifier' :: Ord a => [a] -> a
signifier' xs = head (mysort' xs)
|
chengzh2008/hpffp
|
src/ch06-Typeclasses/matchTheTypes.hs
|
Haskell
|
bsd-3-clause
| 714
|
module RDSTests.EventSubscriptionTests
( runEventSubscriptionTests
)
where
import Control.Applicative ((<$>))
import Control.Monad.IO.Class (liftIO)
import Data.Text (Text)
import Test.Hspec
import Cloud.AWS.RDS
import Cloud.AWS.RDS.Types (SourceType(..), DBInstance(..))
import Util
import RDSTests.Util
region :: Text
region = "ap-northeast-1"
runEventSubscriptionTests :: IO ()
runEventSubscriptionTests = hspec $ do
describeEventSubscriptionsTest
createAndDeleteSubscriptionTest
modifySubscriptionTest
addSourceIdentifierToSubscriptionTest
describeEventSubscriptionsTest :: Spec
describeEventSubscriptionsTest = do
describe "describeEventSubscriptions doesn't fail" $ do
it "describeEventSubscriptions doesn't throw any exception" $ do
testRDS region (
describeEventSubscriptions Nothing Nothing Nothing
) `miss` anyConnectionException
createAndDeleteSubscriptionTest :: Spec
createAndDeleteSubscriptionTest = do
describe "{create,delete}EventSubscription doesn't fail" $ do
it "{create,delete}EventSubscription doesn't throw any excpetion" $ do
testRDS region (do
name <- liftIO $ getRandomText "hspec-test-subscription-"
withEventSubscription name snsTopicArn $
const $ return ()
) `miss` anyConnectionException
snsTopicArn :: Text
snsTopicArn = "arn:aws:sns:ap-northeast-1:049669284607:hspec-test-topic"
modifySubscriptionTest :: Spec
modifySubscriptionTest = do
describe "modifyEventSubscription doesn't fail" $ do
it "modifyEventSubscription doesn't throw any excpetion" $ do
testRDS region (do
name <- liftIO $ getRandomText "hspec-test-subscription-"
withEventSubscription name snsTopicArn $ \_ -> do
modifyEventSubscription
(Just False)
["creation","deletion"]
(Just snsTopicArn)
(Just SourceTypeDBInstance)
name
) `miss` anyConnectionException
addSourceIdentifierToSubscriptionTest :: Spec
addSourceIdentifierToSubscriptionTest = do
describe "addSourceIdentifierToEventSubscription doesn't fail" $ do
it "addSourceIdentifierToEventSubscription doesn't throw any excpetion" $ do
testRDS region (do
name <- liftIO $ getRandomText "hspec-test-subscription-"
withEventSubscription name snsTopicArn $ \_ -> do
modifyEventSubscription
(Just False)
["creation","deletion"]
(Just snsTopicArn)
(Just SourceTypeDBInstance)
name
dbiid <- dbInstanceIdentifier . head <$>
describeDBInstances Nothing Nothing Nothing
addSourceIdentifierToSubscription
dbiid name
) `miss` anyConnectionException
|
worksap-ate/aws-sdk
|
test/RDSTests/EventSubscriptionTests.hs
|
Haskell
|
bsd-3-clause
| 3,090
|
module Main where
import AOC2015.Day01
import AOC2015.Day02
import AOC2015.Day03
import AOC2015.Day04
import AOC2015.Day05
import AOC2015.Day06
import AOC2015.Day07
import AOC2015.Day08
import AOC2015.Day09
import AOC2015.Day10
import AOC2015.Day11
import AOC2015.Day12
import AOC2015.Day13
import AOC2015.Day14
import AOC2015.Day15
--import AOC2015.Day16
import AOC2015.Day17
import AOC2015.Day18
import AOC2015.Day19
import AOC2015.Day20
import AOC2015.Day21
import AOC2015.Day22
import AOC2015.Day23
import AOC2015.Day24
import AOC2015.Day25
main :: IO ()
main = do
putStrLn "Advent of Code"
|
bitrauser/aoc
|
src/Main.hs
|
Haskell
|
bsd-3-clause
| 599
|
module Main where
import ABS
(x:i:ni:num_div:obj:i_divides:f:n:primeb:reminder:res:the_end) = [1..]
main_ :: Method
main_ [] this wb k =
Assign n (Val (I 2500)) $
Assign x (Sync is_prime [n]) $
k
is_prime :: Method
is_prime [pn] this wb k =
Assign i (Val (I 1)) $
Assign ni (Val (I pn)) $
Assign num_div (Val (I 0)) $
While (ILTE (Attr i) (Attr ni)) (\k' ->
Assign obj New $
Assign f (Async obj divides [i,ni]) $
Await f $
Assign i_divides (Get f) $
Assign num_div (Val (Add (Attr num_div) (Attr i_divides))) $
Assign i (Val (Add (Attr i) (I 1))) $
k'
) $
If (IEq (Attr num_div) (I 2))
(\k' -> Assign primeb (Val (I 1)) k')
(\k' -> Assign primeb (Val (I 0)) k') $
Return primeb wb k
divides :: Method
divides [pd, pn] this wb k =
Assign reminder (Val (Mod (I pn) (I pd)) ) $
If (IEq (Attr reminder) (I 0))
(\k' -> Assign res (Val (I 1)) k')
(\k' -> Assign res (Val (I 0)) k' ) $
Return res wb k
main' :: IO ()
main' = run' 1000000 main_ (head the_end)
main :: IO ()
main = printHeap =<< run 1000000 main_ (head the_end)
|
abstools/abs-haskell-formal
|
benchmarks/2_primality_test/progs/2500.hs
|
Haskell
|
bsd-3-clause
| 1,111
|
module Prosper.Money where
type Money = Double
|
WraithM/prosper
|
src/Prosper/Money.hs
|
Haskell
|
bsd-3-clause
| 48
|
{-# LANGUAGE MultiParamTypeClasses #-}
module Physics.Falling2d.OrthonormalBasis2d
(
)
where
import Data.Vect.Double.Base
import Physics.Falling.Math.OrthonormalBasis
instance OrthonormalBasis Vec2 Normal2 where
canonicalBasis = [ toNormalUnsafe $ Vec2 1.0 0.0, toNormalUnsafe $ Vec2 0.0 1.0 ]
completeBasis n = let Vec2 x y = fromNormal n in
(n, [ toNormalUnsafe $ Vec2 (-y) x ])
|
sebcrozet/falling2d
|
Physics/Falling2d/OrthonormalBasis2d.hs
|
Haskell
|
bsd-3-clause
| 409
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ExtendedDefaultRules #-}
module Lucid.Foundation.Callouts.Joyride where
import Lucid.Base
import Lucid.Html5
import qualified Data.Text as T
import Data.Monoid
joyride_list_ :: T.Text
joyride_list_ = " joyride-list "
joyride_tip_guide_ :: T.Text
joyride_tip_guide_ = " joyride-tip-guide "
joyride_nub_ :: T.Text
joyride_nub_ = " joyride-nub "
joyride_content_wrapper_ :: T.Text
joyride_content_wrapper_ = " joyride-content-wrapper "
joyride_close_tip_ :: T.Text
joyride_close_tip_ = " joyride-close-tip "
joyride_next_tip_ :: T.Text
joyride_next_tip_ = " joyride-next-tip "
|
athanclark/lucid-foundation
|
src/Lucid/Foundation/Callouts/Joyride.hs
|
Haskell
|
bsd-3-clause
| 632
|
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE Rank2Types #-}
-----------------------------------------------------------------------------
-- |
-- Module : Indexed.Command
-- Copyright : (C) 2012 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Stability : experimental
-- Portability : non-portable
--
-----------------------------------------------------------------------------
module Indexed.Command
( (>>)(..)
) where
import Indexed.Types
import Indexed.Functor
infixr 8 >>
infixr 1 :&
data (p >> q) r i = p i :& (q ~> r)
instance IFunctor (p >> q) where
imap h (p :& k) = p :& (h . k)
|
ekmett/indexed
|
src/Indexed/Command.hs
|
Haskell
|
bsd-3-clause
| 734
|
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
-- |
-- Module : Codec.Rot13
-- Description : Fast ROT13 cipher for Haskell.
-- Copyright : (c) Kyle Van Berendonck, 2014
-- License : BSD3
-- Maintainer : kvanberendonck@gmail.com
-- Stability : experimental
-- Portability : portable
--
-- This module exposes the API for this package.
module Codec.Rot13
( -- * Typeclass Interfaces
Rot13(..)
, Rot13Bytes(..)
-- * Constraint Interfaces
, rot13enum
, rot13int
-- * Compatibility
, rot13word
, rot13word8
, rot13char
, rot13string
) where
import Data.Char
import Data.Word
import Data.Int
import qualified Data.ByteString as BS
import qualified Data.ByteString.Internal as BS
import qualified Data.Text as Text
import Foreign.Ptr
import Foreign.Storable
import qualified Foreign.C.Types as Foreign
-- | The 'Rot13' typeclass is intended to perform the ROT13 cipher on the provided data, as if it
-- were representing a single ANSI-encoded character. This interface doesn't consider the storage
-- behaviour of the type at all, but is the fastest implementation if you need to integrate the
-- transformation as part of a stream.
class Rot13 a where
rot13 :: a -> a
-- | The 'Rot13Bytes' typeclass is intended for when you need to perform the ROT13 cipher on some
-- data at the memory level. It stores the given data into a temporary buffer in memory, then runs
-- the cipher over the stored bytes to produce a new buffer. This operation is typically slower
-- than just using 'rot13' as part of a fusion pipeline.
class Rot13Bytes a where
rot13bs :: a -> BS.ByteString
-- | Perform the ROT13 cipher on the given 'Integral' instance (in the sense of 'Rot13').
rot13int :: Integral a => a -> a
rot13int x
| (fromIntegral x :: Word) - 97 < 26 = 97 + rem (x - 84) 26
| (fromIntegral x :: Word) - 65 < 26 = 65 + rem (x - 52) 26
| otherwise = x
{-# INLINE rot13int #-}
{-# SPECIALIZE rot13int :: Word -> Word #-}
{-# SPECIALIZE rot13int :: Word8 -> Word8 #-}
{-# SPECIALIZE rot13int :: Word16 -> Word16 #-}
{-# SPECIALIZE rot13int :: Word32 -> Word32 #-}
{-# SPECIALIZE rot13int :: Word64 -> Word64 #-}
{-# SPECIALIZE rot13int :: Int -> Int #-}
{-# SPECIALIZE rot13int :: Int8 -> Int8 #-}
{-# SPECIALIZE rot13int :: Int16 -> Int16 #-}
{-# SPECIALIZE rot13int :: Int32 -> Int32 #-}
{-# SPECIALIZE rot13int :: Int64 -> Int64 #-}
{-# SPECIALIZE rot13int :: Integer -> Integer #-}
{-# SPECIALIZE rot13int :: Foreign.CChar -> Foreign.CChar #-}
{-# SPECIALIZE rot13int :: Foreign.CSChar -> Foreign.CSChar #-}
{-# SPECIALIZE rot13int :: Foreign.CUChar -> Foreign.CUChar #-}
{-# SPECIALIZE rot13int :: Foreign.CShort -> Foreign.CShort #-}
{-# SPECIALIZE rot13int :: Foreign.CUShort -> Foreign.CUShort #-}
{-# SPECIALIZE rot13int :: Foreign.CInt -> Foreign.CInt #-}
{-# SPECIALIZE rot13int :: Foreign.CUInt -> Foreign.CUInt #-}
{-# SPECIALIZE rot13int :: Foreign.CLong -> Foreign.CLong #-}
{-# SPECIALIZE rot13int :: Foreign.CULong -> Foreign.CULong #-}
{-# SPECIALIZE rot13int :: Foreign.CWchar -> Foreign.CWchar #-}
{-# SPECIALIZE rot13int :: Foreign.CLLong -> Foreign.CLLong #-}
{-# SPECIALIZE rot13int :: Foreign.CULLong -> Foreign.CULLong #-}
-- | Perform the ROT13 cipher on the given 'Enum' instance (in the sense of 'Rot13').
{-# INLINE rot13enum #-}
rot13enum :: Enum a => a -> a
rot13enum = toEnum . (rot13int :: Int -> Int) . fromEnum
-- | Perform the ROT13 cipher on the given 'Storable' instance bytes to yield a 'BS.ByteString'.
{-# INLINE rot13stor #-}
rot13stor :: Storable a => a -> BS.ByteString
rot13stor x = rot13bs $! BS.unsafeCreate (sizeOf x) $ \ptr -> poke (castPtr ptr) x
--------------------------------------------------------------------------------------------------
-- Rot13 Instances
instance Rot13 Char where rot13 = rot13enum
instance Rot13 String where rot13 = map rot13
instance Rot13 BS.ByteString where rot13 = BS.map rot13
instance Rot13 Text.Text where rot13 = Text.map rot13
instance Rot13 Word where rot13 = rot13int
instance Rot13 Word8 where rot13 = rot13int
instance Rot13 Word16 where rot13 = rot13int
instance Rot13 Word32 where rot13 = rot13int
instance Rot13 Word64 where rot13 = rot13int
instance Rot13 Int where rot13 = rot13int
instance Rot13 Int8 where rot13 = rot13int
instance Rot13 Int16 where rot13 = rot13int
instance Rot13 Int32 where rot13 = rot13int
instance Rot13 Int64 where rot13 = rot13int
instance Rot13 Integer where rot13 = rot13int
instance Rot13 Foreign.CChar where rot13 = rot13
instance Rot13 Foreign.CSChar where rot13 = rot13
instance Rot13 Foreign.CUChar where rot13 = rot13
instance Rot13 Foreign.CShort where rot13 = rot13
instance Rot13 Foreign.CUShort where rot13 = rot13
instance Rot13 Foreign.CInt where rot13 = rot13
instance Rot13 Foreign.CUInt where rot13 = rot13
instance Rot13 Foreign.CLong where rot13 = rot13
instance Rot13 Foreign.CULong where rot13 = rot13
instance Rot13 Foreign.CWchar where rot13 = rot13
instance Rot13 Foreign.CLLong where rot13 = rot13
instance Rot13 Foreign.CULLong where rot13 = rot13
--------------------------------------------------------------------------------------------------
-- Rot13Bytes Instances
instance {-# OVERLAPPING #-} Rot13Bytes BS.ByteString where rot13bs = rot13
instance {-# OVERLAPPING #-} Storable a => Rot13Bytes a where rot13bs = rot13stor
--------------------------------------------------------------------------------------------------
-- Compatibility
{-# INLINE rot13word #-}
rot13word :: Word -> Word
rot13word = rot13
{-# INLINE rot13word8 #-}
rot13word8 :: Word8 -> Word8
rot13word8 = rot13
{-# INLINE rot13char #-}
rot13char :: Char -> Char
rot13char = rot13
{-# INLINE rot13string #-}
rot13string :: String -> String
rot13string = rot13
|
kvanberendonck/codec-rot13
|
src/Codec/Rot13.hs
|
Haskell
|
bsd-3-clause
| 6,251
|
{-# LANGUAGE OverloadedStrings #-}
module Graphics.Storyboard.Box where
import Data.Monoid
import qualified Data.Set as Set
import Data.Set (Set)
import Data.Text (Text)
import Graphics.Blank as Blank
import qualified Graphics.Blank.Style as Style
import Graphics.Storyboard.Act
import Graphics.Storyboard.Literals
import Graphics.Storyboard.Mosaic
import Graphics.Storyboard.Tile
import Graphics.Storyboard.Types
data TheBoxStyle = TheBoxStyle
{ theBorderWidth :: Double
, theBorderColor :: Color
, theBackground :: Background
, theShadowStyle :: Maybe TheShadowStyle
, theSharedBorders :: Set Side -- ^ a shared border is straight, and perhaps offset
} deriving Show
defaultBoxStyle :: TheBoxStyle
defaultBoxStyle = TheBoxStyle
{ theBorderWidth = 1
, theBorderColor = "black"
, theBackground = bgColor "white"
, theShadowStyle = Just defaultShadowStyle
, theSharedBorders = Set.empty
}
data TheShadowStyle = TheShadowStyle
{ theShadowColor :: Text
, theShadowOffsetX :: Double
, theShadowOffsetY :: Double
, theShadowBlur :: Double
} deriving Show
defaultShadowStyle :: TheShadowStyle
defaultShadowStyle = TheShadowStyle
{ theShadowColor = "#cccccc"
, theShadowOffsetX = 5
, theShadowOffsetY = 5
, theShadowBlur = 5
}
{-
-- Later support LinearGradients
data TheBackgroundStyle
= Background Text
| LinearGradient Text Text
deriving Show
-}
class BoxStyle a where
boxStyle :: (TheBoxStyle -> TheBoxStyle) -> a -> a
instance BoxStyle TheBoxStyle where
boxStyle f a = f a
{-
class ShadowStyle a where
shadowStyle :: (TheShadowStyle -> TheShadowStyle) -> a -> a
instance ShadowStyle TheShadowStyle where
shadowStyle f a = f a
class BackgroundStyle a where
backgroundStyle :: (TheBackgroundStyle -> TheBackgroundStyle) -> a -> a
instance BackgroundStyle TheBackgroundStyle where
backgroundStyle f a = f a
instance BackgroundStyle TheBoxStyle where
backgroundStyle f a = f a
-}
background :: BoxStyle a => Background -> a -> a
background bg = boxStyle $ \ m -> m { theBackground = bg }
shadows :: BoxStyle a => Bool -> a -> a
shadows s = boxStyle $ \ m -> m
{ theShadowStyle =
if s
then Just defaultShadowStyle
else Nothing
}
borderWidth :: BoxStyle a => Double -> a -> a
borderWidth w = boxStyle $ \ m -> m { theBorderWidth = w }
borderColor :: BoxStyle a => Color -> a -> a
borderColor c = boxStyle $ \ m -> m { theBorderColor = c }
box :: TheBoxStyle -> Tile a -> Tile a
box st (Tile (w,h) act) = Tile (w+wd*2,h+wd*2) $ \ (Cavity ps' sz') ->
action (before ps' sz') <>
during ps' sz' <>
action (after ps' sz')
where
wd = theBorderWidth st
before (x,y) (w',h') = saveRestore $ do
translate (x,y)
case theBackground st of
Background bg -> Style.fillStyle bg
-- Our backgrounds are scaled to ((0,0),(1,1))
scale(w',h')
beginPath()
rect(0,0,1,1)
closePath()
-- lineWidth wd
case theShadowStyle st of
Nothing -> return ()
Just s_st -> do
shadowColor (theShadowColor s_st)
shadowOffsetX (theShadowOffsetX s_st)
shadowOffsetY (theShadowOffsetY s_st)
shadowBlur (theShadowBlur s_st)
fill()
during (x,y) (w',h') =
act (Cavity (x+wd,y+wd) (w' - wd * 2,h' - wd * 2))
after (x,y) (w',h')
| wd == 0 = return ()
| otherwise = saveRestore $ do
translate (x,y)
beginPath()
rect(0,0,w',h')
closePath()
lineWidth wd
strokeStyle (theBorderColor st)
stroke()
-- Build a 2D table of boxes
boxes :: TheBoxStyle -> [[(TheBoxStyle -> TheBoxStyle,Tile ())]] -> Tile ()
boxes st tss = pack $ mconcat $
[ anchor top $ pack $ mconcat
[ anchor left $ box (f st) $ t
| (f,t) <- ts
]
| ts <- tss
]
|
tonymorris/story-board
|
src/Graphics/Storyboard/Box.hs
|
Haskell
|
bsd-3-clause
| 4,086
|
{-# LANGUAGE RankNTypes #-}
module Node.Message.Decoder
( Decoder (..)
, DecoderStep (..)
, ByteOffset
, continueDecoding
, hoistDecoder
, hoistDecoderStep
, pureDone
, pureFail
, purePartial
) where
import qualified Data.ByteString as BS
import Data.Int (Int64)
import qualified Data.Text as T
type ByteOffset = Int64
data DecoderStep m t =
Done !BS.ByteString !ByteOffset !t
| Fail !BS.ByteString !ByteOffset !T.Text
| Partial (Maybe BS.ByteString -> Decoder m t)
newtype Decoder m t = Decoder {
runDecoder :: m (DecoderStep m t)
}
hoistDecoder
:: ( Functor n )
=> (forall a . m a -> n a)
-> Decoder m t
-> Decoder n t
hoistDecoder nat (Decoder m) = Decoder (hoistDecoderStep nat <$> nat m)
hoistDecoderStep
:: ( Functor n )
=> (forall a . m a -> n a)
-> DecoderStep m t
-> DecoderStep n t
hoistDecoderStep nat step = case step of
Done trailing offset t -> Done trailing offset t
Fail trailing offset err -> Fail trailing offset err
Partial k -> Partial $ hoistDecoder nat . k
-- | Feed input through a decoder.
--
continueDecoding
:: ( Monad m )
=> DecoderStep m t
-> BS.ByteString
-> m (DecoderStep m t)
continueDecoding decoderStep bs = case decoderStep of
Done trailing offset t -> pure $ Done (BS.append trailing bs) offset t
Fail trailing offset err -> pure $ Fail (BS.append trailing bs) offset err
Partial k -> runDecoder (k (Just bs))
pureDone :: Monad m => BS.ByteString -> ByteOffset -> t -> Decoder m t
pureDone trailing offset t = Decoder . return $ Done trailing offset t
pureFail :: Monad m => BS.ByteString -> ByteOffset -> T.Text -> Decoder m t
pureFail trailing offset err = Decoder . return $ Fail trailing offset err
purePartial :: Monad m => (Maybe BS.ByteString -> Decoder m t) -> Decoder m t
purePartial k = Decoder . return $ Partial k
|
input-output-hk/pos-haskell-prototype
|
networking/src/Node/Message/Decoder.hs
|
Haskell
|
mit
| 1,954
|
module Data.String.Util (
split
) where
-- | /O(n)/ Splits a 'String' into components delimited by separators,
-- where the predicate returns True for a separator element. The
-- resulting components do not contain the separators. Two adjacent
-- separators result in an empty component in the output. eg.
--
-- >>> split (== 'a') "aabbaca"
-- ["","","bb","c",""]
-- >>> split (== 'a') ""
-- [""]
split :: (Char -> Bool) -> String -> [String]
split p = go
where
go xs = case break p xs of
(ys, []) -> [ys]
(ys, _:zs) -> ys : go zs
|
beni55/string
|
src/Data/String/Util.hs
|
Haskell
|
mit
| 557
|
module TypeConstraint where
{-- snippet OrdStack --}
data (Ord a) => OrdStack a = Bottom
| Item a (OrdStack a)
deriving (Show)
{-- /snippet OrdStack --}
{-- snippet isIncreasing --}
isIncreasing :: (Ord a) => OrdStack a -> Bool
isIncreasing (Item a rest@(Item b _))
| a < b = isIncreasing rest
| otherwise = False
isIncreasing _ = True
{-- /snippet isIncreasing --}
{-- snippet push --}
push :: (Ord a) => a -> OrdStack a -> OrdStack a
push a s = Item a s
{-- /snippet push --}
|
binesiyu/ifl
|
examples/ch10/TypeConstraint.hs
|
Haskell
|
mit
| 550
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : Glome.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:42
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qt.Glome (
module Qt.Glome.Glome
, module Qt.Glome.Scene
, module Qt.Glome.Trace
, module Qt.Glome.Spd
, module Qt.Glome.TestScene
)
where
import Qt.Glome.Glome
import Qt.Glome.Scene
import Qt.Glome.Trace
import Qt.Glome.Spd
import Qt.Glome.TestScene
|
keera-studios/hsQt
|
extra-pkgs/Glome/Qt/Glome.hs
|
Haskell
|
bsd-2-clause
| 682
|
module Main where
import Lib
main :: IO ()
main = someFunc
{-99 Haskell Problems-}
{-| Get the last element of a list-}
myLast :: [a] -> a
myLast [x] = x
myLast (_:xs) = myLast xs
{-| Get the second to last element of a list-}
myButtLast :: [a] -> a
myButtLast [x, _] = x
myButtLast (_:xs) = myButtLast xs
{-| Get the kth element of a list-}
elementAt :: [a] -> Int -> a
elementAt (x:_) 0 = x
elementAt (_:xs) k = elementAt xs (k - 1)
{-| Get the length of a list-}
myLength :: [a] -> Int
myLength [] = 0
myLength (_:xs) = 1 + (myLength xs)
{-| Reverse a list-}
myReverse :: [a] -> [a]
myReverse [] = []
myReverse (x:xs) = (myReverse xs) ++ [x]
{-| Checks if list is a palindrome.-}
myPalindrome :: (Eq a) => [a] -> Bool
myPalindrome x
| x == (reverse x) = True
| otherwise = False
{-| Remove dupes in list-}
compress :: (Eq a) => [a] -> [a]
compress [] = []
compress (x:xs) = [x] ++ compress (clean x xs)
where clean _ [] = []
clean y (x:xs)
| y == x = clean y xs
| otherwise = [x] ++ clean y xs
{-| Put duplicates in sublists-}
pack :: (Eq a) => [a] -> [[a]]
pack [] = []
pack [x] = [[x]]
pack (x:xs) = combine x xs ++ pack (clean x xs)
where
combine _ [] = []
combine x s = [[z | z <- x:s, z == x]]
clean _ [] = []
clean y (x:xs)
| y == x = clean y xs
| otherwise = [x] ++ clean y xs
{-| Does stuff-}
encode :: (Eq a) => [a] -> [(Int, a)]
encode [] = []
encode s = map (\(x:xs) -> (length (x:xs), x)) (pack s)
data List a = Single a | Multiple Int a
deriving Show
{-| Similar to before-}
encodeModified :: (Eq a) => [a] -> [List a]
encodeModified s = map f (encode s)
where f (1, x) = Single x
f (n, x) = Multiple n x
decode :: [List a] -> [a]
decode s = foldr (++) [] (map f s)
where f (Single x) = [x]
f (Multiple n x) = replicate n x
encodeDirect :: (Eq a) => [a] -> [List a]
encodeDirect [] = []
encodeDirect (x:xs) = [toList (count x (x:xs)) x] ++
encodeDirect (filter (x /=) xs)
where count x s = length (filter (x==) s)
toList 1 x = Single x
toList n x = Multiple n x
dupl :: [a] -> [a]
dupl [] = []
dupl (x:xs) = [x,x] ++ dupl xs
repli :: [a] -> Int -> [a]
repli [] _ = []
repli (x:xs) n = replicate n x ++ repli xs n
dropEvery :: [a] -> Int -> [a]
dropEvery [] _ = []
dropEvery s n = foldr (++) [] (map (f n) (zip [1..] s))
where f n (m, x)
| m `mod` n == 0 = []
| otherwise = [x]
spliter :: [a] -> Int -> [[a]]
spliter [] _ = []
spliter s n = [reverse (drop ((length s) - n) (reverse s))] ++ [drop n s]
slice :: [a] -> Int -> Int -> [a]
slice [] _ _ = []
slice s start stop = reverse (drop (((length s)) - stop) (reverse (drop (start - 1) s)))
rotate :: [a] -> Int -> [a]
rotate [] _ = []
rotate s n = slice s ((f n (length s)) + 1) (length s) ++ slice s 1 (f n (length s))
where f n m
| n > m = f (n - m) m
| n < 0 = f (m + n) m
| otherwise = n
removeAt :: [a] -> Int -> (a, [a])
removeAt s n = (elementAt (slice s (n + 1) (n + 2)) 0,
slice s 1 n ++ slice s (n+2) (length s))
insertAt :: [a] -> a -> Int -> [a]
insertAt xs x n = slice xs 1 (n-1) ++ [x] ++ slice xs n (length xs)
range :: Int -> Int -> [Int]
range n1 n2 = [n1..n2]
listEq :: (Eq a) => [a] -> [a] -> Bool
listEq [] [] = True
listEq [] _ = False
listEq _ [] = False
listEq s1 s2 = False `notElem` (map (`elem`s1) s2 ++ map (`elem`s2) s1)
listNeq :: (Eq a) => [a] -> [a] -> Bool
listNeq s1 s2
| listEq s1 s2 = False
| otherwise = True
listRemoveDupes :: (Eq a) => [[a]] -> [[a]]
listRemoveDupes [[]] = [[]]
listRemoveDupes [] = []
listRemoveDupes (x:xs) = [x] ++ listRemoveDupes (filter (listNeq x) xs)
combinations :: (Eq a) => Int -> [a] -> [[a]]
combinations 0 _ = [[]]
combinations _ [] = [[]]
combinations n s = f n 1 s (map (\x -> [x]) s)
where f n1 n2 s1 s2
| n1 == n2 = s2
| otherwise = f n1 (n2 + 1) s1 (listRemoveDupes
[x ++ [y] |
x <- s2,
y <- s1,
y `notElem` x])
{- TODO the second combinatorics problem on the haskell website.-}
isDisjoint :: (Eq a) => [a] -> [a] -> Bool
isDisjoint [] [] = False
isDisjoint [] _ = True
isDisjoint _ [] = True
isDisjoint (x:xs) s2
| x `elem` s2 = False
| otherwise = isDisjoint xs s2
{-| TODO Finish this.-}
{-grouper :: (Eq a) => [Int] -> [a] -> [[[a]]]
grouper n s = g (map (`combinations`s) n)
where f x s = filter (isDisjoint x) s
g (x:y:s)
|y == [] = []
|otherwise = map (\z -> g (f z y) (y:s)) x -}
sortOnLength :: [[a]] -> [[a]]
sortOnLength [] = []
sortOnLength (x:xs) =
sortOnLength [y | y <- xs, (length y) < (length x)]
++ [x]
++ sortOnLength [y | y <- xs, (length y) > (length x)]
sieveEratosthenes :: Int -> [Int]
sieveEratosthenes n = f n [2..n]
where f n [] = []
f n (x:xs) = [x] ++ f n [y | y <- xs,
y `notElem` (map (x*) [2..n])]
isPrime :: Int -> Bool
isPrime n = n `elem` (sieveEratosthenes n)
gcd' :: Int -> Int -> Int
gcd' n1 n2
| n1 == n2 = n1
| n1 > n2 = gcd' (n1 - n2) n2
| otherwise = gcd' (n2 - n1) n1
isCoPrime :: Int -> Int -> Bool
isCoPrime n1 n2
| (gcd' n1 n2) == 1 = True
| otherwise = False
eulerTotient :: Int -> Int
eulerTotient n = length (filter id (map (isCoPrime n) [1..n]))
primeFactors :: Int -> [Int]
primeFactors n
|isPrime n = [n]
|otherwise = [f] ++ primeFactors (n `div` f)
where f = fst (head (filter (\(x,y) ->
y == 0) (map (\x ->
(x, (n `mod` x)))
(sieveEratosthenes n))))
encodePrimeFactors :: Int -> [(Int, Int)]
encodePrimeFactors = encode . primeFactors
eulerTotient' :: Int -> Int
eulerTotient' n = foldr (*) 1
. map (\(x, y) ->
(y-1) * (y^(x - 1)))
. encodePrimeFactors $ n
primesRange :: Int -> Int -> [Int]
primesRange l u = filter (>=l) (sieveEratosthenes u)
combinationsWithDupes :: (Eq a) => Int -> [a] -> [[a]]
combinationsWithDupes 0 _ = [[]]
combinationsWithDupes _ [] = [[]]
combinationsWithDupes n s = f n 1 s (map (\x -> [x]) s)
where f n1 n2 s1 s2
| n1 == n2 = s2
| otherwise = f n1 (n2 + 1) s1 [x ++ [y] |
x <- s2,
y <- s1,
y `notElem` x]
{-| Fix empty list issue-}
goldbach :: Int -> (Int,Int)
goldbach n = snd
. head
. filter (\(x, _) -> x == n)
. map (\[x,y] -> ((x+y),(x,y)))
. combinationsWithDupes 2
. sieveEratosthenes $ n
goldbachList :: Int -> Int -> [(Int,Int)]
goldbachList l u = map goldbach
. dropWhile (<= l) $ [2,4 .. u]
grayC :: Int -> [String]
grayC n = combinationsWithDupes n
$ replicate n '1' ++ replicate n '0'
|
MauriceIsAG/HaskellScratch
|
.stack-work/intero/intero1846heo.hs
|
Haskell
|
bsd-3-clause
| 7,113
|
import Development.Shake
import Development.Shake.System
import System.FilePath
main :: IO ()
main = shake $ do
("subdirectory" </> "foo") *> \x -> do
system' $ ["touch",x]
want ["subdirectory/foo"]
|
beni55/openshake
|
tests/creates-directory-implicitly/Shakefile.hs
|
Haskell
|
bsd-3-clause
| 218
|
module ShallowVector where
import qualified Data.Vector.Unboxed as V
import Types
import Debug.Trace
{-# RULES "darkenBy.brightenBy" forall im1 n. darkenBy n (brightenBy n im1) = im1 #-}
{-# RULES "brightenBy.darkenBy" forall im1 n. brightenBy n (darkenBy n im1) = im1 #-}
-- TODO: overload + and - to be brightenBy and darkenBy
-- inline the blur functions so that they can be fused when used together,
-- using the fusion optimisations in the vector library.
{-# INLINE blurY #-}
blurY :: VectorImage -> VectorImage
blurY (VectorImage pixels w h) = VectorImage newPixels w h
where
newPixels = V.imap blurPixel pixels
normalise x = round (fromIntegral x / 4.0)
blurPixel i p
-- bottom of a column
| (i+1) `mod` h == 0 =
normalise ((pixels V.! (i-1)) + p*2 + p)
-- top of a column
| i `mod` h == 0 =
normalise (p + p*2 + (pixels V.! (i+1)))
-- somewhere in between
| otherwise =
normalise (pixels V.! (i-1) + p*2 + (pixels V.! (i+1)))
{-# INLINE blurX #-}
blurX :: VectorImage -> VectorImage
blurX (VectorImage pixels w h) = VectorImage newPixels w h
where
newPixels = V.imap blurPixel pixels
normalise x = round (fromIntegral x / 4.0)
blurPixel i p
-- right end of a row
| (i+1) `mod` w == 0 =
normalise ((pixels V.! (i-1)) + p*2 + p)
-- left start to a row
| i `mod` w == 0 =
normalise (p + p*2 + (pixels V.! (i+1)))
-- somewhere in between
| otherwise =
normalise (pixels V.! (i-1) + p*2 + (pixels V.! (i+1)))
-- don't inline, so they can be eliminated with the rewrite rule at the top.
{-# NOINLINE brightenBy #-}
{-# NOINLINE darkenBy #-}
brightenBy,darkenBy :: Int -> VectorImage -> VectorImage
brightenBy i (VectorImage pixels w h) = VectorImage (V.map ((\x -> min 255 (x+1))) pixels) w h
darkenBy i (VectorImage pixels w h) = VectorImage (V.map ((\x -> max 0 (x-1))) pixels) w h
|
robstewart57/small-image-processing-dsl-implementations
|
haskell/small-image-processing-dsl/src/ShallowVector.hs
|
Haskell
|
bsd-3-clause
| 2,036
|
{-# LANGUAGE PatternGuards #-}
module Main (main) where
import Network.HTTP hiding (password)
import Network.Browser
import Network.URI (URI(..), parseRelativeReference, relativeTo)
import Distribution.Client
import Distribution.Client.Cron (cron, rethrowSignalsAsExceptions,
Signal(..), ReceivedSignal(..))
import Distribution.Package
import Distribution.Text
import Distribution.Verbosity
import Distribution.Simple.Utils hiding (intercalate)
import Distribution.Version (Version(..))
import Data.List
import Data.Maybe
import Data.IORef
import Data.Time
import Control.Exception
import Control.Monad
import Control.Monad.Trans
import qualified Data.ByteString.Lazy as BS
import qualified Data.Set as S
import qualified Codec.Compression.GZip as GZip
import qualified Codec.Archive.Tar as Tar
import System.Environment
import System.Exit(exitFailure, ExitCode(..))
import System.FilePath
import System.Directory
import System.Console.GetOpt
import System.Process
import System.IO
import Paths_hackage_server (version)
import Data.Aeson (eitherDecode)
data Mode = Help [String]
| Init URI [URI]
| Stats
| Build [PackageId]
data BuildOpts = BuildOpts {
bo_verbosity :: Verbosity,
bo_runTime :: Maybe NominalDiffTime,
bo_stateDir :: FilePath,
bo_continuous :: Maybe Int,
bo_keepGoing :: Bool,
bo_dryRun :: Bool,
bo_prune :: Bool,
bo_username :: Maybe String,
bo_password :: Maybe String
}
data BuildConfig = BuildConfig {
bc_srcURI :: URI,
bc_auxURIs :: [URI],
bc_username :: String,
bc_password :: String
}
srcName :: URI -> String
srcName uri = fromMaybe (show uri) (uriHostName uri)
installDirectory :: BuildOpts -> FilePath
installDirectory bo = bo_stateDir bo </> "tmp-install"
resultsDirectory :: BuildOpts -> FilePath
resultsDirectory bo = bo_stateDir bo </> "results"
main :: IO ()
main = topHandler $ do
rethrowSignalsAsExceptions [SIGABRT, SIGINT, SIGQUIT, SIGTERM]
hSetBuffering stdout LineBuffering
args <- getArgs
(mode, opts) <- validateOpts args
case mode of
Help strs ->
do let usageHeader = intercalate "\n" [
"Usage: hackage-build init URL [auxiliary URLs] [options]",
" hackage-build build [packages] [options]",
" hackage-build stats",
"Options:"]
mapM_ putStrLn $ strs
putStrLn $ usageInfo usageHeader buildFlagDescrs
unless (null strs) exitFailure
Init uri auxUris -> initialise opts uri auxUris
Stats ->
do stateDir <- canonicalizePath $ bo_stateDir opts
let opts' = opts {
bo_stateDir = stateDir
}
stats opts'
Build pkgs ->
do stateDir <- canonicalizePath $ bo_stateDir opts
let opts' = opts {
bo_stateDir = stateDir
}
case bo_continuous opts' of
Nothing ->
buildOnce opts' pkgs
Just interval -> do
cron (bo_verbosity opts')
interval
(const (buildOnce opts' pkgs))
()
---------------------------------
-- Initialisation & config file
--
initialise :: BuildOpts -> URI -> [URI] -> IO ()
initialise opts uri auxUris
= do username <- readMissingOpt "Enter hackage username" (bo_username opts)
password <- readMissingOpt "Enter hackage password" (bo_password opts)
let config = BuildConfig {
bc_srcURI = uri,
bc_auxURIs = auxUris,
bc_username = username,
bc_password = password
}
createDirectoryIfMissing False $ bo_stateDir opts
createDirectoryIfMissing False $ resultsDirectory opts
writeConfig opts config
writeCabalConfig opts config
where
readMissingOpt prompt = maybe (putStrLn prompt >> getLine) return
writeConfig :: BuildOpts -> BuildConfig -> IO ()
writeConfig opts BuildConfig {
bc_srcURI = uri,
bc_auxURIs = auxUris,
bc_username = username,
bc_password = password
} =
-- [Note: Show/Read URI]
-- Ideally we'd just be showing a BuildConfig, but URI doesn't
-- have Show/Read, so that doesn't work. So instead, we write
-- out a tuple containing the uri as a string, and parse it
-- each time we read it.
let confStr = show (show uri, map show auxUris, username, password) in
writeFile (configFile opts) confStr
readConfig :: BuildOpts -> IO BuildConfig
readConfig opts = do
xs <- readFile $ configFile opts
case reads xs of
[((uriStr, auxUriStrs, username, password), _)] ->
case mapM validateHackageURI (uriStr : auxUriStrs) of
-- Shouldn't happen: We check that this
-- returns Right when we create the
-- config file. See [Note: Show/Read URI].
Left theError -> die theError
Right (uri : auxUris) ->
return $ BuildConfig {
bc_srcURI = uri,
bc_auxURIs = auxUris,
bc_username = username,
bc_password = password
}
Right _ -> error "The impossible happened"
_ ->
die "Can't parse config file (maybe re-run \"hackage-build init\")"
configFile :: BuildOpts -> FilePath
configFile opts = bo_stateDir opts </> "hackage-build-config"
writeCabalConfig :: BuildOpts -> BuildConfig -> IO ()
writeCabalConfig opts config = do
let tarballsDir = bo_stateDir opts </> "cached-tarballs"
writeFile (bo_stateDir opts </> "cabal-config") . unlines $
[ "remote-repo: " ++ srcName uri ++ ":" ++ show uri
| uri <- bc_srcURI config : bc_auxURIs config ]
++ [ "remote-repo-cache: " ++ tarballsDir ]
createDirectoryIfMissing False tarballsDir
----------------------
-- Displaying status
--
data StatResult = AllVersionsBuiltOk
| AllVersionsAttempted
| NoneBuilt
| SomeBuiltOk
| SomeFailed
deriving Eq
stats :: BuildOpts -> IO ()
stats opts = do
config <- readConfig opts
let verbosity = bo_verbosity opts
notice verbosity "Initialising"
(didFail, _, _) <- mkPackageFailed opts
pkgIdsHaveDocs <- getDocumentationStats verbosity config didFail
infoStats verbosity (Just statsFile) pkgIdsHaveDocs
where
statsFile = bo_stateDir opts </> "stats"
infoStats :: Verbosity -> Maybe FilePath -> [DocInfo] -> IO ()
infoStats verbosity mDetailedStats pkgIdsHaveDocs = do
nfo $ "There are "
++ show (length byPackage)
++ " packages with a total of "
++ show (length pkgIdsHaveDocs)
++ " package versions"
nfo $ "So far we have built or attempted to built "
++ show (length (filter ((/= DocsNotBuilt) . docInfoHasDocs) pkgIdsHaveDocs))
++ " packages; only "
++ show (length (filter ((== DocsNotBuilt) . docInfoHasDocs) pkgIdsHaveDocs))
++ " left!"
nfo "Considering the most recent version only:"
nfo . printTable . indent $ [
[show (length mostRecentBuilt) , "built succesfully"]
, [show (length mostRecentFailed) , "failed to build"]
, [show (length mostRecentNotBuilt), "not yet built"]
]
nfo "Considering all versions:"
nfo . printTable . indent $ [
[count AllVersionsBuiltOk, "all versions built successfully"]
, [count AllVersionsAttempted, "attempted to build all versions, but some failed"]
, [count SomeBuiltOk, "not all versions built yet, but those that did were ok"]
, [count SomeFailed, "not all versions built yet, and some failures"]
, [count NoneBuilt, "no versions built yet"]
]
case mDetailedStats of
Nothing -> return ()
Just statsFile -> do
writeFile statsFile $ printTable (["Package", "Version", "Has docs?"] : formattedStats)
notice verbosity $ "Detailed statistics written to " ++ statsFile
where
-- | We avoid 'info' here because it re-wraps the text
nfo :: String -> IO ()
nfo str = when (verbosity >= verbose) $ putStrLn str
byPackage :: [[DocInfo]]
byPackage = map (sortBy (flip (comparing docInfoPackageVersion)))
$ groupBy (equating docInfoPackageName)
$ sortBy (comparing docInfoPackageName) pkgIdsHaveDocs
mostRecentBuilt, mostRecentFailed, mostRecentNotBuilt :: [[DocInfo]]
mostRecentBuilt = filter ((== HasDocs) . docInfoHasDocs . head) byPackage
mostRecentFailed = filter ((== DocsFailed) . docInfoHasDocs . head) byPackage
mostRecentNotBuilt = filter ((== DocsNotBuilt) . docInfoHasDocs . head) byPackage
categorise :: [DocInfo] -> StatResult
categorise ps
| all (== HasDocs) hd = AllVersionsBuiltOk
| all (/= DocsNotBuilt) hd = AllVersionsAttempted
| all (== DocsNotBuilt) hd = NoneBuilt
| all (/= DocsFailed) hd = SomeBuiltOk
| otherwise = SomeFailed
where
hd = map docInfoHasDocs ps
categorised :: [StatResult]
categorised = map categorise byPackage
count :: StatResult -> String
count c = show (length (filter (c ==) categorised))
formatPkg :: [DocInfo] -> [[String]]
formatPkg = map $ \docInfo -> [
display (docInfoPackageName docInfo)
, display (docInfoPackageVersion docInfo)
, show (docInfoHasDocs docInfo)
]
formattedStats :: [[String]]
formattedStats = concatMap formatPkg byPackage
indent :: [[String]] -> [[String]]
indent = map (" " :)
-- | Formats a 2D table so that everything is nicely aligned
--
-- NOTE: Expects the same number of columns in every row!
printTable :: [[String]] -> String
printTable xss = intercalate "\n"
. map (intercalate " ")
. map padCols
$ xss
where
colWidths :: [[Int]]
colWidths = map (map length) $ xss
maxColWidths :: [Int]
maxColWidths = foldr1 (\xs ys -> map (uncurry max) (zip xs ys)) colWidths
padCols :: [String] -> [String]
padCols cols = map (uncurry padTo) (zip maxColWidths cols)
padTo :: Int -> String -> String
padTo len str = str ++ replicate (len - length str) ' '
data HasDocs = HasDocs | DocsNotBuilt | DocsFailed
deriving (Eq, Show)
data DocInfo = DocInfo {
docInfoPackage :: PackageIdentifier
, docInfoHasDocs :: HasDocs
, docInfoIsCandidate :: Bool
}
docInfoPackageName :: DocInfo -> PackageName
docInfoPackageName = pkgName . docInfoPackage
docInfoPackageVersion :: DocInfo -> Version
docInfoPackageVersion = pkgVersion . docInfoPackage
docInfoBaseURI :: BuildConfig -> DocInfo -> URI
docInfoBaseURI config docInfo =
if not (docInfoIsCandidate docInfo)
then bc_srcURI config <//> "package" </> display (docInfoPackage docInfo)
else bc_srcURI config <//> "package" </> display (docInfoPackage docInfo) </> "candidate"
docInfoDocsURI :: BuildConfig -> DocInfo -> URI
docInfoDocsURI config docInfo = docInfoBaseURI config docInfo <//> "docs"
docInfoTarGzURI :: BuildConfig -> DocInfo -> URI
docInfoTarGzURI config docInfo = docInfoBaseURI config docInfo <//> display (docInfoPackage docInfo) <.> "tar.gz"
docInfoReports :: BuildConfig -> DocInfo -> URI
docInfoReports config docInfo = docInfoBaseURI config docInfo <//> "reports/"
getDocumentationStats :: Verbosity
-> BuildConfig
-> (PackageId -> IO Bool)
-> IO [DocInfo]
getDocumentationStats verbosity config didFail = do
notice verbosity "Downloading documentation index"
httpSession verbosity "hackage-build" version $ do
mPackages <- liftM eitherDecode `liftM` requestGET' packagesUri
mCandidates <- liftM eitherDecode `liftM` requestGET' candidatesUri
case (mPackages, mCandidates) of
-- Download failure
(Nothing, _) -> fail $ "Could not download " ++ show packagesUri
(_, Nothing) -> fail $ "Could not download " ++ show candidatesUri
-- Decoding failure
(Just (Left e), _) -> fail $ "Could not decode " ++ show packagesUri ++ ": " ++ e
(_, Just (Left e)) -> fail $ "Could not decode " ++ show candidatesUri ++ ": " ++ e
-- Success
(Just (Right packages), Just (Right candidates)) -> do
packages' <- liftIO $ mapM checkFailed packages
candidates' <- liftIO $ mapM checkFailed candidates
return $ map (setIsCandidate False) packages'
++ map (setIsCandidate True) candidates'
where
packagesUri = bc_srcURI config <//> "packages" </> "docs.json"
candidatesUri = bc_srcURI config <//> "packages" </> "candidates" </> "docs.json"
checkFailed :: (String, Bool) -> IO (PackageIdentifier, HasDocs)
checkFailed (pkgId, docsBuilt) = do
let pkgId' = fromJust (simpleParse pkgId)
if docsBuilt
then return (pkgId', HasDocs)
else do failed <- didFail pkgId'
if failed then return (pkgId', DocsFailed)
else return (pkgId', DocsNotBuilt)
setIsCandidate :: Bool -> (PackageIdentifier, HasDocs) -> DocInfo
setIsCandidate isCandidate (pId, hasDocs) = DocInfo {
docInfoPackage = pId
, docInfoHasDocs = hasDocs
, docInfoIsCandidate = isCandidate
}
----------------------
-- Building packages
--
buildOnce :: BuildOpts -> [PackageId] -> IO ()
buildOnce opts pkgs = keepGoing $ do
config <- readConfig opts
notice verbosity "Initialising"
(has_failed, mark_as_failed, persist_failed) <- mkPackageFailed opts
flip finally persist_failed $ do
updatePackageIndex
pkgIdsHaveDocs <- getDocumentationStats verbosity config has_failed
infoStats verbosity Nothing pkgIdsHaveDocs
-- First build all of the latest versions of each package
-- Then go back and build all the older versions
-- NOTE: assumes all these lists are non-empty
let latestFirst :: [[DocInfo]] -> [DocInfo]
latestFirst ids = map head ids ++ concatMap tail ids
-- Find those files *not* marked as having documentation in our cache
let toBuild :: [DocInfo]
toBuild = filter shouldBuild
. latestFirst
. map (sortBy (flip (comparing docInfoPackageVersion)))
. groupBy (equating docInfoPackageName)
. sortBy (comparing docInfoPackageName)
$ pkgIdsHaveDocs
notice verbosity $ show (length toBuild) ++ " package(s) to build"
-- Try to build each of them, uploading the documentation and
-- build reports along the way. We mark each package as having
-- documentation in the cache even if the build fails because
-- we don't want to keep continually trying to build a failing
-- package!
startTime <- getCurrentTime
let go :: [DocInfo] -> IO ()
go [] = return ()
go (docInfo : toBuild') = do
(mTgz, mRpt, logfile) <- buildPackage verbosity opts config docInfo
case mTgz of
Nothing -> mark_as_failed (docInfoPackage docInfo)
Just _ -> return ()
case mRpt of
Just _ | bo_dryRun opts -> return ()
Just report -> uploadResults verbosity config docInfo
mTgz report logfile
_ -> return ()
-- We don't check the runtime until we've actually tried
-- to build a doc, so as to ensure we make progress.
outOfTime <- case bo_runTime opts of
Nothing -> return False
Just d -> do
currentTime <- getCurrentTime
return $ (currentTime `diffUTCTime` startTime) > d
if outOfTime then return ()
else go toBuild'
go toBuild
where
shouldBuild :: DocInfo -> Bool
shouldBuild docInfo =
case docInfoHasDocs docInfo of
DocsNotBuilt -> null pkgs || any (isSelectedPackage pkgid) pkgs
_ -> False
where
pkgid = docInfoPackage docInfo
-- do versionless matching if no version was given
isSelectedPackage pkgid pkgid'@(PackageIdentifier _ (Version [] _)) =
packageName pkgid == packageName pkgid'
isSelectedPackage pkgid pkgid' =
pkgid == pkgid'
keepGoing :: IO () -> IO ()
keepGoing act
| bo_keepGoing opts = Control.Exception.catch act showExceptionAsWarning
| otherwise = act
showExceptionAsWarning :: SomeException -> IO ()
showExceptionAsWarning e
-- except for signals telling us to really stop
| Just (ReceivedSignal {}) <- fromException e
= throwIO e
| Just UserInterrupt <- fromException e
= throwIO e
| otherwise
= do warn verbosity (show e)
notice verbosity "Abandoning this build attempt."
verbosity = bo_verbosity opts
updatePackageIndex = do
update_ec <- cabal opts "update" [] Nothing
unless (update_ec == ExitSuccess) $
die "Could not 'cabal update' from specified server"
-- Builds a little memoised function that can tell us whether a
-- particular package failed to build its documentation
mkPackageFailed :: BuildOpts
-> IO (PackageId -> IO Bool, PackageId -> IO (), IO ())
mkPackageFailed opts = do
init_failed <- readFailedCache (bo_stateDir opts)
cache_var <- newIORef init_failed
let mark_as_failed pkg_id = atomicModifyIORef cache_var $ \already_failed ->
(S.insert pkg_id already_failed, ())
has_failed pkg_id = liftM (pkg_id `S.member`) $ readIORef cache_var
persist = readIORef cache_var >>= writeFailedCache (bo_stateDir opts)
return (has_failed, mark_as_failed, persist)
where
readFailedCache :: FilePath -> IO (S.Set PackageId)
readFailedCache cache_dir = do
pkgstrs <- handleDoesNotExist [] $ liftM lines $ readFile (cache_dir </> "failed")
case validatePackageIds pkgstrs of
Left theError -> die theError
Right pkgs -> return (S.fromList pkgs)
writeFailedCache :: FilePath -> S.Set PackageId -> IO ()
writeFailedCache cache_dir pkgs =
writeFile (cache_dir </> "failed") $ unlines $ map display $ S.toList pkgs
-- | Build documentation and return @(Just tgz)@ for the built tgz file
-- on success, or @Nothing@ otherwise.
buildPackage :: Verbosity -> BuildOpts -> BuildConfig
-> DocInfo
-> IO (Maybe FilePath, Maybe FilePath, FilePath)
buildPackage verbosity opts config docInfo = do
let pkgid = docInfoPackage docInfo
notice verbosity ("Building " ++ display pkgid)
handleDoesNotExist () $
removeDirectoryRecursive $ installDirectory opts
createDirectory $ installDirectory opts
-- Create the local package db
let packageDb = installDirectory opts </> "packages.db"
-- TODO: use Distribution.Simple.Program.HcPkg
ph <- runProcess "ghc-pkg"
["init", packageDb]
Nothing Nothing Nothing Nothing Nothing
init_ec <- waitForProcess ph
unless (init_ec == ExitSuccess) $
die $ "Could not initialise the package db " ++ packageDb
-- The documentation is installed within the stateDir because we
-- set a prefix while installing
let doc_root = installDirectory opts </> "haddocks"
doc_dir_tmpl = doc_root </> "$pkgid-docs"
doc_dir_pkg = doc_root </> display pkgid ++ "-docs"
-- doc_dir_html = doc_dir </> "html"
-- deps_doc_dir = doc_dir </> "deps"
-- temp_doc_dir = doc_dir </> display (docInfoPackage docInfo) ++ "-docs"
pkg_url = "/package" </> "$pkg-$version"
pkg_flags =
["--enable-documentation",
"--htmldir=" ++ doc_dir_tmpl,
-- We only care about docs, so we want to build as
-- quickly as possible, and hence turn
-- optimisation off. Also explicitly pass -O0 as a
-- GHC option, in case it overrides a .cabal
-- setting or anything
"--disable-optimization", "--ghc-option", "-O0",
"--disable-library-for-ghci",
-- We don't want packages installed in the user
-- package.conf to affect things. In particular,
-- we don't want doc building to fail because
-- "packages are likely to be broken by the reinstalls"
"--package-db=clear", "--package-db=global",
"--package-db=" ++ packageDb,
-- Always build the package, even when it's been built
-- before. This lets us regenerate documentation when
-- dependencies are updated.
"--reinstall",
-- We know where this documentation will
-- eventually be hosted, bake that in.
-- The wiki claims we shouldn't include the
-- version in the hyperlinks so we don't have
-- to rehaddock some package when the dependent
-- packages get updated. However, this is NOT
-- what the Hackage v1 did, so ignore that:
"--haddock-html-location=" ++ pkg_url </> "docs",
-- Link "Contents" to the package page:
"--haddock-contents-location=" ++ pkg_url,
-- Link to colourised source code:
"--haddock-hyperlink-source",
"--prefix=" ++ installDirectory opts,
"--build-summary=" ++ installDirectory opts </> "reports" </> "$pkgid.report",
"--report-planning-failure",
-- We want both html documentation and hoogle database generated
"--haddock-html",
"--haddock-hoogle",
-- For candidates we need to use the full URL, because
-- otherwise cabal-install will not find the package.
-- For regular packages however we need to use just the
-- package name, otherwise cabal-install will not
-- generate a report
if docInfoIsCandidate docInfo
then show (docInfoTarGzURI config docInfo)
else display pkgid
]
-- The installDirectory is purely temporary, while the resultsDirectory is
-- more persistent. We will grab various outputs from the tmp dir and stash
-- them for safe keeping (for later upload or manual inspection) in the
-- results dir.
let resultDir = resultsDirectory opts
resultLogFile = resultDir </> display pkgid <.> "log"
resultReportFile = resultDir </> display pkgid <.> "report"
resultDocsTarball = resultDir </> (display pkgid ++ "-docs") <.> "tar.gz"
buildLogHnd <- openFile resultLogFile WriteMode
-- We ignore the result of calling @cabal install@ because
-- @cabal install@ succeeds even if the documentation fails to build.
void $ cabal opts "install" pkg_flags (Just buildLogHnd)
-- Grab the report for the package we want. Stash it for safe keeping.
report <- handleDoesNotExist Nothing $ do
renameFile (installDirectory opts </> "reports"
</> display pkgid <.> "report")
resultReportFile
appendFile resultReportFile "\ndoc-builder: True"
return (Just resultReportFile)
docs_generated <- fmap and $ sequence [
doesDirectoryExist doc_dir_pkg,
doesFileExist (doc_dir_pkg </> "doc-index.html"),
doesFileExist (doc_dir_pkg </> display (docInfoPackageName docInfo) <.> "haddock")]
docs <- if docs_generated
then do
when (bo_prune opts) (pruneHaddockFiles doc_dir_pkg)
BS.writeFile resultDocsTarball =<< tarGzDirectory doc_dir_pkg
return (Just resultDocsTarball)
else return Nothing
notice verbosity $ unlines
[ "Build results for " ++ display pkgid ++ ":"
, fromMaybe "no report" report
, fromMaybe "no docs" docs
, resultLogFile
]
return (docs, report, resultLogFile)
cabal :: BuildOpts -> String -> [String] -> Maybe Handle -> IO ExitCode
cabal opts cmd args moutput = do
let verbosity = bo_verbosity opts
cabalConfigFile = bo_stateDir opts </> "cabal-config"
verbosityArgs = if verbosity == silent
then ["-v0"]
else []
all_args = ("--config-file=" ++ cabalConfigFile)
: cmd
: verbosityArgs
++ args
info verbosity $ unwords ("cabal":all_args)
ph <- runProcess "cabal" all_args Nothing
Nothing Nothing moutput moutput
waitForProcess ph
pruneHaddockFiles :: FilePath -> IO ()
pruneHaddockFiles dir = do
-- Hackage doesn't support the haddock frames view, so remove it
-- both visually (no frames link) and save space too.
files <- getDirectoryContents dir
sequence_
[ removeFile (dir </> file)
| file <- files
, unwantedFile file ]
hackJsUtils
where
unwantedFile file
| "frames.html" == file = True
| "mini_" `isPrefixOf` file = True
-- The .haddock file is haddock-version specific
-- so it is not useful to make available for download
| ".haddock" <- takeExtension file = True
| otherwise = False
-- The "Frames" link is added by the JS, just comment it out.
hackJsUtils = do
content <- readFile (dir </> "haddock-util.js")
_ <- evaluate (length content)
writeFile (dir </> "haddock-util.js") (munge content)
where
munge = unlines
. map removeAddMenuItem
. lines
removeAddMenuItem l | (sp, l') <- span (==' ') l
, "addMenuItem" `isPrefixOf` l'
= sp ++ "//" ++ l'
removeAddMenuItem l = l
tarGzDirectory :: FilePath -> IO BS.ByteString
tarGzDirectory dir = do
res <- liftM (GZip.compress . Tar.write) $
Tar.pack containing_dir [nested_dir]
-- This seq is extremely important! Tar.pack is lazy, scanning
-- directories as entries are demanded.
-- This interacts very badly with the renameDirectory stuff with
-- which tarGzDirectory gets wrapped.
BS.length res `seq` return res
where (containing_dir, nested_dir) = splitFileName dir
uploadResults :: Verbosity -> BuildConfig -> DocInfo
-> Maybe FilePath -> FilePath -> FilePath -> IO ()
uploadResults verbosity config docInfo
mdocsTarballFile buildReportFile buildLogFile =
httpSession verbosity "hackage-build" version $ do
-- Make sure we authenticate to Hackage
setAuthorityGen (provideAuthInfo (bc_srcURI config)
(Just (bc_username config, bc_password config)))
case mdocsTarballFile of
Nothing -> return ()
Just docsTarballFile ->
putDocsTarball config docInfo docsTarballFile
buildId <- postBuildReport config docInfo buildReportFile
putBuildLog buildId buildLogFile
putDocsTarball :: BuildConfig -> DocInfo -> FilePath -> HttpSession ()
putDocsTarball config docInfo docsTarballFile =
requestPUTFile (docInfoDocsURI config docInfo)
"application/x-tar" (Just "gzip") docsTarballFile
type BuildReportId = URI
postBuildReport :: BuildConfig -> DocInfo -> FilePath -> HttpSession BuildReportId
postBuildReport config docInfo reportFile = do
let uri = docInfoReports config docInfo
body <- liftIO $ BS.readFile reportFile
setAllowRedirects False
(_, response) <- request Request {
rqURI = uri,
rqMethod = POST,
rqHeaders = [Header HdrContentType ("text/plain"),
Header HdrContentLength (show (BS.length body)),
Header HdrAccept ("text/plain")],
rqBody = body
}
case rspCode response of
--TODO: fix server to not do give 303, 201 is more appropriate
(3,0,3) | [Just buildId] <- [ do rel <- parseRelativeReference location
return $ relativeTo rel uri
| Header HdrLocation location <- rspHeaders response ]
-> return buildId
_ -> do checkStatus uri response
fail "Unexpected response from server."
putBuildLog :: BuildReportId -> FilePath -> HttpSession ()
putBuildLog reportId buildLogFile = do
body <- liftIO $ BS.readFile buildLogFile
let uri = reportId <//> "log"
setAllowRedirects False
(_, response) <- request Request {
rqURI = uri,
rqMethod = PUT,
rqHeaders = [Header HdrContentType ("text/plain"),
Header HdrContentLength (show (BS.length body)),
Header HdrAccept ("text/plain")],
rqBody = body
}
case rspCode response of
--TODO: fix server to not to give 303, 201 is more appropriate
(3,0,3) -> return ()
_ -> checkStatus uri response
-------------------------
-- Command line handling
-------------------------
data BuildFlags = BuildFlags {
flagCacheDir :: Maybe FilePath,
flagVerbosity :: Verbosity,
flagRunTime :: Maybe NominalDiffTime,
flagHelp :: Bool,
flagForce :: Bool,
flagContinuous :: Bool,
flagKeepGoing :: Bool,
flagDryRun :: Bool,
flagInterval :: Maybe String,
flagPrune :: Bool,
flagUsername :: Maybe String,
flagPassword :: Maybe String
}
emptyBuildFlags :: BuildFlags
emptyBuildFlags = BuildFlags {
flagCacheDir = Nothing
, flagVerbosity = normal
, flagRunTime = Nothing
, flagHelp = False
, flagForce = False
, flagContinuous = False
, flagKeepGoing = False
, flagDryRun = False
, flagInterval = Nothing
, flagPrune = False
, flagUsername = Nothing
, flagPassword = Nothing
}
buildFlagDescrs :: [OptDescr (BuildFlags -> BuildFlags)]
buildFlagDescrs =
[ Option ['h'] ["help"]
(NoArg (\opts -> opts { flagHelp = True }))
"Show this help text"
, Option ['s'] []
(NoArg (\opts -> opts { flagVerbosity = silent }))
"Silent mode"
, Option ['v'] []
(NoArg (\opts -> opts { flagVerbosity = moreVerbose (flagVerbosity opts) }))
"Verbose mode (can be listed multiple times e.g. -vv)"
, Option [] ["run-time"]
(ReqArg (\mins opts -> case reads mins of
[(mins', "")] -> opts { flagRunTime = Just (fromInteger mins' * 60) }
_ -> error "Can't parse minutes") "MINS")
"Limit the running time of the build client"
, Option [] ["cache-dir"]
(ReqArg (\dir opts -> opts { flagCacheDir = Just dir }) "DIR")
"Where to put files during building"
, Option [] ["continuous"]
(NoArg (\opts -> opts { flagContinuous = True }))
"Build continuously rather than just once"
, Option [] ["keep-going"]
(NoArg (\opts -> opts { flagKeepGoing = True }))
"Keep going after errors"
, Option [] ["dry-run"]
(NoArg (\opts -> opts { flagDryRun = True }))
"Don't record results or upload"
, Option [] ["interval"]
(ReqArg (\int opts -> opts { flagInterval = Just int }) "MIN")
"Set the building interval in minutes (default 30)"
, Option [] ["prune-haddock-files"]
(NoArg (\opts -> opts { flagPrune = True }))
"Remove unnecessary haddock files (frames, .haddock file)"
, Option [] ["init-username"]
(ReqArg (\uname opts -> opts { flagUsername = Just uname }) "USERNAME")
"The Hackage user to run the build as (used with init)"
, Option [] ["init-password"]
(ReqArg (\passwd opts -> opts { flagPassword = Just passwd }) "PASSWORD")
"The password of the Hackage user to run the build as (used with init)"
]
validateOpts :: [String] -> IO (Mode, BuildOpts)
validateOpts args = do
let (flags0, args', errs) = getOpt Permute buildFlagDescrs args
flags = accum flags0 emptyBuildFlags
stateDir = fromMaybe "build-cache" (flagCacheDir flags)
opts = BuildOpts {
bo_verbosity = flagVerbosity flags,
bo_runTime = flagRunTime flags,
bo_stateDir = stateDir,
bo_continuous = case (flagContinuous flags, flagInterval flags) of
(True, Just i) -> Just (read i)
(True, Nothing) -> Just 30 -- default interval
(False, _) -> Nothing,
bo_keepGoing = flagKeepGoing flags,
bo_dryRun = flagDryRun flags,
bo_prune = flagPrune flags,
bo_username = flagUsername flags,
bo_password = flagPassword flags
}
mode = case args' of
_ | flagHelp flags -> Help []
| not (null errs) -> Help errs
"init" : uriStr : auxUriStrs ->
-- We don't actually want the URI at this point
-- (see [Note: Show/Read URI])
case mapM validateHackageURI (uriStr : auxUriStrs) of
Left theError -> Help [theError]
Right (uri:auxUris) -> Init uri auxUris
Right _ -> error "impossible"
["stats"] ->
Stats
"stats" : _ ->
Help ["stats takes no arguments"]
"build" : pkgstrs ->
case validatePackageIds pkgstrs of
Left theError -> Help [theError]
Right pkgs -> Build pkgs
cmd : _ -> Help ["Unrecognised command: " ++ show cmd]
[] -> Help []
-- Ensure we store the absolute state_dir, because we might
-- change the CWD later and we don't want the stateDir to be
-- invalidated by such a change
--
-- We have to ensure the directory exists before we do
-- canonicalizePath, or otherwise we get an exception if it
-- does not yet exist
return (mode, opts)
where
accum flags = foldr (flip (.)) id flags
|
agrafix/hackage-server
|
BuildClient.hs
|
Haskell
|
bsd-3-clause
| 35,442
|
-----------------------------------------------------------------------------
--
-- Object-file symbols (called CLabel for histerical raisins).
--
-- (c) The University of Glasgow 2004-2006
--
-----------------------------------------------------------------------------
module CLabel (
CLabel, -- abstract type
ForeignLabelSource(..),
pprDebugCLabel,
mkClosureLabel,
mkSRTLabel,
mkInfoTableLabel,
mkEntryLabel,
mkSlowEntryLabel,
mkConEntryLabel,
mkStaticConEntryLabel,
mkRednCountsLabel,
mkConInfoTableLabel,
mkStaticInfoTableLabel,
mkLargeSRTLabel,
mkApEntryLabel,
mkApInfoTableLabel,
mkClosureTableLabel,
mkLocalClosureLabel,
mkLocalInfoTableLabel,
mkLocalEntryLabel,
mkLocalConEntryLabel,
mkLocalStaticConEntryLabel,
mkLocalConInfoTableLabel,
mkLocalStaticInfoTableLabel,
mkLocalClosureTableLabel,
mkReturnPtLabel,
mkReturnInfoLabel,
mkAltLabel,
mkDefaultLabel,
mkBitmapLabel,
mkStringLitLabel,
mkAsmTempLabel,
mkPlainModuleInitLabel,
mkSplitMarkerLabel,
mkDirty_MUT_VAR_Label,
mkUpdInfoLabel,
mkBHUpdInfoLabel,
mkIndStaticInfoLabel,
mkMainCapabilityLabel,
mkMAP_FROZEN_infoLabel,
mkMAP_DIRTY_infoLabel,
mkEMPTY_MVAR_infoLabel,
mkTopTickyCtrLabel,
mkCAFBlackHoleInfoTableLabel,
mkCAFBlackHoleEntryLabel,
mkRtsPrimOpLabel,
mkRtsSlowTickyCtrLabel,
mkSelectorInfoLabel,
mkSelectorEntryLabel,
mkCmmInfoLabel,
mkCmmEntryLabel,
mkCmmRetInfoLabel,
mkCmmRetLabel,
mkCmmCodeLabel,
mkCmmDataLabel,
mkCmmGcPtrLabel,
mkRtsApFastLabel,
mkPrimCallLabel,
mkForeignLabel,
addLabelSize,
foreignLabelStdcallInfo,
mkCCLabel, mkCCSLabel,
DynamicLinkerLabelInfo(..),
mkDynamicLinkerLabel,
dynamicLinkerLabelInfo,
mkPicBaseLabel,
mkDeadStripPreventer,
mkHpcTicksLabel,
hasCAF,
needsCDecl, isAsmTemp, maybeAsmTemp, externallyVisibleCLabel,
isMathFun,
isCFunctionLabel, isGcPtrLabel, labelDynamic,
-- * Conversions
toClosureLbl, toSlowEntryLbl, toEntryLbl, toInfoLbl, toRednCountsLbl,
pprCLabel
) where
import IdInfo
import StaticFlags
import BasicTypes
import Packages
import DataCon
import Module
import Name
import Unique
import PrimOp
import Config
import CostCentre
import Outputable
import FastString
import DynFlags
import Platform
import UniqSet
-- -----------------------------------------------------------------------------
-- The CLabel type
{-
| CLabel is an abstract type that supports the following operations:
- Pretty printing
- In a C file, does it need to be declared before use? (i.e. is it
guaranteed to be already in scope in the places we need to refer to it?)
- If it needs to be declared, what type (code or data) should it be
declared to have?
- Is it visible outside this object file or not?
- Is it "dynamic" (see details below)
- Eq and Ord, so that we can make sets of CLabels (currently only
used in outputting C as far as I can tell, to avoid generating
more than one declaration for any given label).
- Converting an info table label into an entry label.
-}
data CLabel
= -- | A label related to the definition of a particular Id or Con in a .hs file.
IdLabel
Name
CafInfo
IdLabelInfo -- encodes the suffix of the label
-- | A label from a .cmm file that is not associated with a .hs level Id.
| CmmLabel
PackageId -- what package the label belongs to.
FastString -- identifier giving the prefix of the label
CmmLabelInfo -- encodes the suffix of the label
-- | A label with a baked-in \/ algorithmically generated name that definitely
-- comes from the RTS. The code for it must compile into libHSrts.a \/ libHSrts.so
-- If it doesn't have an algorithmically generated name then use a CmmLabel
-- instead and give it an appropriate PackageId argument.
| RtsLabel
RtsLabelInfo
-- | A 'C' (or otherwise foreign) label.
--
| ForeignLabel
FastString -- name of the imported label.
(Maybe Int) -- possible '@n' suffix for stdcall functions
-- When generating C, the '@n' suffix is omitted, but when
-- generating assembler we must add it to the label.
ForeignLabelSource -- what package the foreign label is in.
FunctionOrData
-- | A family of labels related to a particular case expression.
| CaseLabel
{-# UNPACK #-} !Unique -- Unique says which case expression
CaseLabelInfo
| AsmTempLabel
{-# UNPACK #-} !Unique
| StringLitLabel
{-# UNPACK #-} !Unique
| PlainModuleInitLabel -- without the version & way info
Module
| CC_Label CostCentre
| CCS_Label CostCentreStack
-- | These labels are generated and used inside the NCG only.
-- They are special variants of a label used for dynamic linking
-- see module PositionIndependentCode for details.
| DynamicLinkerLabel DynamicLinkerLabelInfo CLabel
-- | This label is generated and used inside the NCG only.
-- It is used as a base for PIC calculations on some platforms.
-- It takes the form of a local numeric assembler label '1'; and
-- is pretty-printed as 1b, referring to the previous definition
-- of 1: in the assembler source file.
| PicBaseLabel
-- | A label before an info table to prevent excessive dead-stripping on darwin
| DeadStripPreventer CLabel
-- | Per-module table of tick locations
| HpcTicksLabel Module
-- | Label of an StgLargeSRT
| LargeSRTLabel
{-# UNPACK #-} !Unique
-- | A bitmap (function or case return)
| LargeBitmapLabel
{-# UNPACK #-} !Unique
deriving (Eq, Ord)
-- | Record where a foreign label is stored.
data ForeignLabelSource
-- | Label is in a named package
= ForeignLabelInPackage PackageId
-- | Label is in some external, system package that doesn't also
-- contain compiled Haskell code, and is not associated with any .hi files.
-- We don't have to worry about Haskell code being inlined from
-- external packages. It is safe to treat the RTS package as "external".
| ForeignLabelInExternalPackage
-- | Label is in the package currenly being compiled.
-- This is only used for creating hacky tmp labels during code generation.
-- Don't use it in any code that might be inlined across a package boundary
-- (ie, core code) else the information will be wrong relative to the
-- destination module.
| ForeignLabelInThisPackage
deriving (Eq, Ord)
-- | For debugging problems with the CLabel representation.
-- We can't make a Show instance for CLabel because lots of its components don't have instances.
-- The regular Outputable instance only shows the label name, and not its other info.
--
pprDebugCLabel :: Platform -> CLabel -> SDoc
pprDebugCLabel platform lbl
= case lbl of
IdLabel{} -> pprPlatform platform lbl <> (parens $ text "IdLabel")
CmmLabel pkg _name _info
-> pprPlatform platform lbl <> (parens $ text "CmmLabel" <+> ppr pkg)
RtsLabel{} -> pprPlatform platform lbl <> (parens $ text "RtsLabel")
ForeignLabel _name mSuffix src funOrData
-> pprPlatform platform lbl <> (parens
$ text "ForeignLabel"
<+> ppr mSuffix
<+> ppr src
<+> ppr funOrData)
_ -> pprPlatform platform lbl <> (parens $ text "other CLabel)")
data IdLabelInfo
= Closure -- ^ Label for closure
| SRT -- ^ Static reference table
| InfoTable -- ^ Info tables for closures; always read-only
| Entry -- ^ Entry point
| Slow -- ^ Slow entry point
| LocalInfoTable -- ^ Like InfoTable but not externally visible
| LocalEntry -- ^ Like Entry but not externally visible
| RednCounts -- ^ Label of place to keep Ticky-ticky info for this Id
| ConEntry -- ^ Constructor entry point
| ConInfoTable -- ^ Corresponding info table
| StaticConEntry -- ^ Static constructor entry point
| StaticInfoTable -- ^ Corresponding info table
| ClosureTable -- ^ Table of closures for Enum tycons
deriving (Eq, Ord)
data CaseLabelInfo
= CaseReturnPt
| CaseReturnInfo
| CaseAlt ConTag
| CaseDefault
deriving (Eq, Ord)
data RtsLabelInfo
= RtsSelectorInfoTable Bool{-updatable-} Int{-offset-} -- ^ Selector thunks
| RtsSelectorEntry Bool{-updatable-} Int{-offset-}
| RtsApInfoTable Bool{-updatable-} Int{-arity-} -- ^ AP thunks
| RtsApEntry Bool{-updatable-} Int{-arity-}
| RtsPrimOp PrimOp
| RtsApFast FastString -- ^ _fast versions of generic apply
| RtsSlowTickyCtr String
deriving (Eq, Ord)
-- NOTE: Eq on LitString compares the pointer only, so this isn't
-- a real equality.
-- | What type of Cmm label we're dealing with.
-- Determines the suffix appended to the name when a CLabel.CmmLabel
-- is pretty printed.
data CmmLabelInfo
= CmmInfo -- ^ misc rts info tabless, suffix _info
| CmmEntry -- ^ misc rts entry points, suffix _entry
| CmmRetInfo -- ^ misc rts ret info tables, suffix _info
| CmmRet -- ^ misc rts return points, suffix _ret
| CmmData -- ^ misc rts data bits, eg CHARLIKE_closure
| CmmCode -- ^ misc rts code
| CmmGcPtr -- ^ GcPtrs eg CHARLIKE_closure
| CmmPrimCall -- ^ a prim call to some hand written Cmm code
deriving (Eq, Ord)
data DynamicLinkerLabelInfo
= CodeStub -- MachO: Lfoo$stub, ELF: foo@plt
| SymbolPtr -- MachO: Lfoo$non_lazy_ptr, Windows: __imp_foo
| GotSymbolPtr -- ELF: foo@got
| GotSymbolOffset -- ELF: foo@gotoff
deriving (Eq, Ord)
-- -----------------------------------------------------------------------------
-- Constructing CLabels
-- -----------------------------------------------------------------------------
-- Constructing IdLabels
-- These are always local:
mkSlowEntryLabel :: Name -> CafInfo -> CLabel
mkSlowEntryLabel name c = IdLabel name c Slow
mkSRTLabel :: Name -> CafInfo -> CLabel
mkRednCountsLabel :: Name -> CafInfo -> CLabel
mkSRTLabel name c = IdLabel name c SRT
mkRednCountsLabel name c = IdLabel name c RednCounts
-- These have local & (possibly) external variants:
mkLocalClosureLabel :: Name -> CafInfo -> CLabel
mkLocalInfoTableLabel :: Name -> CafInfo -> CLabel
mkLocalEntryLabel :: Name -> CafInfo -> CLabel
mkLocalClosureTableLabel :: Name -> CafInfo -> CLabel
mkLocalClosureLabel name c = IdLabel name c Closure
mkLocalInfoTableLabel name c = IdLabel name c LocalInfoTable
mkLocalEntryLabel name c = IdLabel name c LocalEntry
mkLocalClosureTableLabel name c = IdLabel name c ClosureTable
mkClosureLabel :: Name -> CafInfo -> CLabel
mkInfoTableLabel :: Name -> CafInfo -> CLabel
mkEntryLabel :: Name -> CafInfo -> CLabel
mkClosureTableLabel :: Name -> CafInfo -> CLabel
mkLocalConInfoTableLabel :: CafInfo -> Name -> CLabel
mkLocalConEntryLabel :: CafInfo -> Name -> CLabel
mkLocalStaticInfoTableLabel :: CafInfo -> Name -> CLabel
mkLocalStaticConEntryLabel :: CafInfo -> Name -> CLabel
mkConInfoTableLabel :: Name -> CafInfo -> CLabel
mkStaticInfoTableLabel :: Name -> CafInfo -> CLabel
mkClosureLabel name c = IdLabel name c Closure
mkInfoTableLabel name c = IdLabel name c InfoTable
mkEntryLabel name c = IdLabel name c Entry
mkClosureTableLabel name c = IdLabel name c ClosureTable
mkLocalConInfoTableLabel c con = IdLabel con c ConInfoTable
mkLocalConEntryLabel c con = IdLabel con c ConEntry
mkLocalStaticInfoTableLabel c con = IdLabel con c StaticInfoTable
mkLocalStaticConEntryLabel c con = IdLabel con c StaticConEntry
mkConInfoTableLabel name c = IdLabel name c ConInfoTable
mkStaticInfoTableLabel name c = IdLabel name c StaticInfoTable
mkConEntryLabel :: Name -> CafInfo -> CLabel
mkStaticConEntryLabel :: Name -> CafInfo -> CLabel
mkConEntryLabel name c = IdLabel name c ConEntry
mkStaticConEntryLabel name c = IdLabel name c StaticConEntry
-- Constructing Cmm Labels
mkSplitMarkerLabel, mkDirty_MUT_VAR_Label, mkUpdInfoLabel,
mkBHUpdInfoLabel, mkIndStaticInfoLabel, mkMainCapabilityLabel,
mkMAP_FROZEN_infoLabel, mkMAP_DIRTY_infoLabel,
mkEMPTY_MVAR_infoLabel, mkTopTickyCtrLabel,
mkCAFBlackHoleInfoTableLabel, mkCAFBlackHoleEntryLabel :: CLabel
mkSplitMarkerLabel = CmmLabel rtsPackageId (fsLit "__stg_split_marker") CmmCode
mkDirty_MUT_VAR_Label = CmmLabel rtsPackageId (fsLit "dirty_MUT_VAR") CmmCode
mkUpdInfoLabel = CmmLabel rtsPackageId (fsLit "stg_upd_frame") CmmInfo
mkBHUpdInfoLabel = CmmLabel rtsPackageId (fsLit "stg_bh_upd_frame" ) CmmInfo
mkIndStaticInfoLabel = CmmLabel rtsPackageId (fsLit "stg_IND_STATIC") CmmInfo
mkMainCapabilityLabel = CmmLabel rtsPackageId (fsLit "MainCapability") CmmData
mkMAP_FROZEN_infoLabel = CmmLabel rtsPackageId (fsLit "stg_MUT_ARR_PTRS_FROZEN0") CmmInfo
mkMAP_DIRTY_infoLabel = CmmLabel rtsPackageId (fsLit "stg_MUT_ARR_PTRS_DIRTY") CmmInfo
mkEMPTY_MVAR_infoLabel = CmmLabel rtsPackageId (fsLit "stg_EMPTY_MVAR") CmmInfo
mkTopTickyCtrLabel = CmmLabel rtsPackageId (fsLit "top_ct") CmmData
mkCAFBlackHoleInfoTableLabel = CmmLabel rtsPackageId (fsLit "stg_CAF_BLACKHOLE") CmmInfo
mkCAFBlackHoleEntryLabel = CmmLabel rtsPackageId (fsLit "stg_CAF_BLACKHOLE") CmmEntry
-----
mkCmmInfoLabel, mkCmmEntryLabel, mkCmmRetInfoLabel, mkCmmRetLabel,
mkCmmCodeLabel, mkCmmDataLabel, mkCmmGcPtrLabel
:: PackageId -> FastString -> CLabel
mkCmmInfoLabel pkg str = CmmLabel pkg str CmmInfo
mkCmmEntryLabel pkg str = CmmLabel pkg str CmmEntry
mkCmmRetInfoLabel pkg str = CmmLabel pkg str CmmRetInfo
mkCmmRetLabel pkg str = CmmLabel pkg str CmmRet
mkCmmCodeLabel pkg str = CmmLabel pkg str CmmCode
mkCmmDataLabel pkg str = CmmLabel pkg str CmmData
mkCmmGcPtrLabel pkg str = CmmLabel pkg str CmmGcPtr
-- Constructing RtsLabels
mkRtsPrimOpLabel :: PrimOp -> CLabel
mkRtsPrimOpLabel primop = RtsLabel (RtsPrimOp primop)
mkSelectorInfoLabel :: Bool -> Int -> CLabel
mkSelectorEntryLabel :: Bool -> Int -> CLabel
mkSelectorInfoLabel upd off = RtsLabel (RtsSelectorInfoTable upd off)
mkSelectorEntryLabel upd off = RtsLabel (RtsSelectorEntry upd off)
mkApInfoTableLabel :: Bool -> Int -> CLabel
mkApEntryLabel :: Bool -> Int -> CLabel
mkApInfoTableLabel upd off = RtsLabel (RtsApInfoTable upd off)
mkApEntryLabel upd off = RtsLabel (RtsApEntry upd off)
-- A call to some primitive hand written Cmm code
mkPrimCallLabel :: PrimCall -> CLabel
mkPrimCallLabel (PrimCall str pkg)
= CmmLabel pkg str CmmPrimCall
-- Constructing ForeignLabels
-- | Make a foreign label
mkForeignLabel
:: FastString -- name
-> Maybe Int -- size prefix
-> ForeignLabelSource -- what package it's in
-> FunctionOrData
-> CLabel
mkForeignLabel str mb_sz src fod
= ForeignLabel str mb_sz src fod
-- | Update the label size field in a ForeignLabel
addLabelSize :: CLabel -> Int -> CLabel
addLabelSize (ForeignLabel str _ src fod) sz
= ForeignLabel str (Just sz) src fod
addLabelSize label _
= label
-- | Get the label size field from a ForeignLabel
foreignLabelStdcallInfo :: CLabel -> Maybe Int
foreignLabelStdcallInfo (ForeignLabel _ info _ _) = info
foreignLabelStdcallInfo _lbl = Nothing
-- Constructing Large*Labels
mkLargeSRTLabel :: Unique -> CLabel
mkBitmapLabel :: Unique -> CLabel
mkLargeSRTLabel uniq = LargeSRTLabel uniq
mkBitmapLabel uniq = LargeBitmapLabel uniq
-- Constructin CaseLabels
mkReturnPtLabel :: Unique -> CLabel
mkReturnInfoLabel :: Unique -> CLabel
mkAltLabel :: Unique -> ConTag -> CLabel
mkDefaultLabel :: Unique -> CLabel
mkReturnPtLabel uniq = CaseLabel uniq CaseReturnPt
mkReturnInfoLabel uniq = CaseLabel uniq CaseReturnInfo
mkAltLabel uniq tag = CaseLabel uniq (CaseAlt tag)
mkDefaultLabel uniq = CaseLabel uniq CaseDefault
-- Constructing Cost Center Labels
mkCCLabel :: CostCentre -> CLabel
mkCCSLabel :: CostCentreStack -> CLabel
mkCCLabel cc = CC_Label cc
mkCCSLabel ccs = CCS_Label ccs
mkRtsApFastLabel :: FastString -> CLabel
mkRtsApFastLabel str = RtsLabel (RtsApFast str)
mkRtsSlowTickyCtrLabel :: String -> CLabel
mkRtsSlowTickyCtrLabel pat = RtsLabel (RtsSlowTickyCtr pat)
-- Constructing Code Coverage Labels
mkHpcTicksLabel :: Module -> CLabel
mkHpcTicksLabel = HpcTicksLabel
-- Constructing labels used for dynamic linking
mkDynamicLinkerLabel :: DynamicLinkerLabelInfo -> CLabel -> CLabel
mkDynamicLinkerLabel = DynamicLinkerLabel
dynamicLinkerLabelInfo :: CLabel -> Maybe (DynamicLinkerLabelInfo, CLabel)
dynamicLinkerLabelInfo (DynamicLinkerLabel info lbl) = Just (info, lbl)
dynamicLinkerLabelInfo _ = Nothing
mkPicBaseLabel :: CLabel
mkPicBaseLabel = PicBaseLabel
-- Constructing miscellaneous other labels
mkDeadStripPreventer :: CLabel -> CLabel
mkDeadStripPreventer lbl = DeadStripPreventer lbl
mkStringLitLabel :: Unique -> CLabel
mkStringLitLabel = StringLitLabel
mkAsmTempLabel :: Uniquable a => a -> CLabel
mkAsmTempLabel a = AsmTempLabel (getUnique a)
mkPlainModuleInitLabel :: Module -> CLabel
mkPlainModuleInitLabel mod = PlainModuleInitLabel mod
-- -----------------------------------------------------------------------------
-- Convert between different kinds of label
toClosureLbl :: Platform -> CLabel -> CLabel
toClosureLbl _ (IdLabel n c _) = IdLabel n c Closure
toClosureLbl platform l = pprPanic "toClosureLbl" (pprCLabel platform l)
toSlowEntryLbl :: Platform -> CLabel -> CLabel
toSlowEntryLbl _ (IdLabel n c _) = IdLabel n c Slow
toSlowEntryLbl platform l = pprPanic "toSlowEntryLbl" (pprCLabel platform l)
toRednCountsLbl :: Platform -> CLabel -> CLabel
toRednCountsLbl _ (IdLabel n c _) = IdLabel n c RednCounts
toRednCountsLbl platform l = pprPanic "toRednCountsLbl" (pprCLabel platform l)
toEntryLbl :: Platform -> CLabel -> CLabel
toEntryLbl _ (IdLabel n c LocalInfoTable) = IdLabel n c LocalEntry
toEntryLbl _ (IdLabel n c ConInfoTable) = IdLabel n c ConEntry
toEntryLbl _ (IdLabel n c StaticInfoTable) = IdLabel n c StaticConEntry
toEntryLbl _ (IdLabel n c _) = IdLabel n c Entry
toEntryLbl _ (CaseLabel n CaseReturnInfo) = CaseLabel n CaseReturnPt
toEntryLbl _ (CmmLabel m str CmmInfo) = CmmLabel m str CmmEntry
toEntryLbl _ (CmmLabel m str CmmRetInfo) = CmmLabel m str CmmRet
toEntryLbl platform l = pprPanic "toEntryLbl" (pprCLabel platform l)
toInfoLbl :: Platform -> CLabel -> CLabel
toInfoLbl _ (IdLabel n c Entry) = IdLabel n c InfoTable
toInfoLbl _ (IdLabel n c LocalEntry) = IdLabel n c LocalInfoTable
toInfoLbl _ (IdLabel n c ConEntry) = IdLabel n c ConInfoTable
toInfoLbl _ (IdLabel n c StaticConEntry) = IdLabel n c StaticInfoTable
toInfoLbl _ (IdLabel n c _) = IdLabel n c InfoTable
toInfoLbl _ (CaseLabel n CaseReturnPt) = CaseLabel n CaseReturnInfo
toInfoLbl _ (CmmLabel m str CmmEntry) = CmmLabel m str CmmInfo
toInfoLbl _ (CmmLabel m str CmmRet) = CmmLabel m str CmmRetInfo
toInfoLbl platform l = pprPanic "CLabel.toInfoLbl" (pprCLabel platform l)
-- -----------------------------------------------------------------------------
-- Does a CLabel refer to a CAF?
hasCAF :: CLabel -> Bool
hasCAF (IdLabel _ MayHaveCafRefs _) = True
hasCAF _ = False
-- -----------------------------------------------------------------------------
-- Does a CLabel need declaring before use or not?
--
-- See wiki:Commentary/Compiler/Backends/PprC#Prototypes
needsCDecl :: CLabel -> Bool
-- False <=> it's pre-declared; don't bother
-- don't bother declaring SRT & Bitmap labels, we always make sure
-- they are defined before use.
needsCDecl (IdLabel _ _ SRT) = False
needsCDecl (LargeSRTLabel _) = False
needsCDecl (LargeBitmapLabel _) = False
needsCDecl (IdLabel _ _ _) = True
needsCDecl (CaseLabel _ _) = True
needsCDecl (PlainModuleInitLabel _) = True
needsCDecl (StringLitLabel _) = False
needsCDecl (AsmTempLabel _) = False
needsCDecl (RtsLabel _) = False
needsCDecl (CmmLabel pkgId _ _)
-- Prototypes for labels defined in the runtime system are imported
-- into HC files via includes/Stg.h.
| pkgId == rtsPackageId = False
-- For other labels we inline one into the HC file directly.
| otherwise = True
needsCDecl l@(ForeignLabel{}) = not (isMathFun l)
needsCDecl (CC_Label _) = True
needsCDecl (CCS_Label _) = True
needsCDecl (HpcTicksLabel _) = True
needsCDecl (DynamicLinkerLabel {}) = panic "needsCDecl DynamicLinkerLabel"
needsCDecl PicBaseLabel = panic "needsCDecl PicBaseLabel"
needsCDecl (DeadStripPreventer {}) = panic "needsCDecl DeadStripPreventer"
-- | Check whether a label is a local temporary for native code generation
isAsmTemp :: CLabel -> Bool
isAsmTemp (AsmTempLabel _) = True
isAsmTemp _ = False
-- | If a label is a local temporary used for native code generation
-- then return just its unique, otherwise nothing.
maybeAsmTemp :: CLabel -> Maybe Unique
maybeAsmTemp (AsmTempLabel uq) = Just uq
maybeAsmTemp _ = Nothing
-- | Check whether a label corresponds to a C function that has
-- a prototype in a system header somehere, or is built-in
-- to the C compiler. For these labels we avoid generating our
-- own C prototypes.
isMathFun :: CLabel -> Bool
isMathFun (ForeignLabel fs _ _ _) = fs `elementOfUniqSet` math_funs
isMathFun _ = False
math_funs :: UniqSet FastString
math_funs = mkUniqSet [
-- _ISOC99_SOURCE
(fsLit "acos"), (fsLit "acosf"), (fsLit "acosh"),
(fsLit "acoshf"), (fsLit "acoshl"), (fsLit "acosl"),
(fsLit "asin"), (fsLit "asinf"), (fsLit "asinl"),
(fsLit "asinh"), (fsLit "asinhf"), (fsLit "asinhl"),
(fsLit "atan"), (fsLit "atanf"), (fsLit "atanl"),
(fsLit "atan2"), (fsLit "atan2f"), (fsLit "atan2l"),
(fsLit "atanh"), (fsLit "atanhf"), (fsLit "atanhl"),
(fsLit "cbrt"), (fsLit "cbrtf"), (fsLit "cbrtl"),
(fsLit "ceil"), (fsLit "ceilf"), (fsLit "ceill"),
(fsLit "copysign"), (fsLit "copysignf"), (fsLit "copysignl"),
(fsLit "cos"), (fsLit "cosf"), (fsLit "cosl"),
(fsLit "cosh"), (fsLit "coshf"), (fsLit "coshl"),
(fsLit "erf"), (fsLit "erff"), (fsLit "erfl"),
(fsLit "erfc"), (fsLit "erfcf"), (fsLit "erfcl"),
(fsLit "exp"), (fsLit "expf"), (fsLit "expl"),
(fsLit "exp2"), (fsLit "exp2f"), (fsLit "exp2l"),
(fsLit "expm1"), (fsLit "expm1f"), (fsLit "expm1l"),
(fsLit "fabs"), (fsLit "fabsf"), (fsLit "fabsl"),
(fsLit "fdim"), (fsLit "fdimf"), (fsLit "fdiml"),
(fsLit "floor"), (fsLit "floorf"), (fsLit "floorl"),
(fsLit "fma"), (fsLit "fmaf"), (fsLit "fmal"),
(fsLit "fmax"), (fsLit "fmaxf"), (fsLit "fmaxl"),
(fsLit "fmin"), (fsLit "fminf"), (fsLit "fminl"),
(fsLit "fmod"), (fsLit "fmodf"), (fsLit "fmodl"),
(fsLit "frexp"), (fsLit "frexpf"), (fsLit "frexpl"),
(fsLit "hypot"), (fsLit "hypotf"), (fsLit "hypotl"),
(fsLit "ilogb"), (fsLit "ilogbf"), (fsLit "ilogbl"),
(fsLit "ldexp"), (fsLit "ldexpf"), (fsLit "ldexpl"),
(fsLit "lgamma"), (fsLit "lgammaf"), (fsLit "lgammal"),
(fsLit "llrint"), (fsLit "llrintf"), (fsLit "llrintl"),
(fsLit "llround"), (fsLit "llroundf"), (fsLit "llroundl"),
(fsLit "log"), (fsLit "logf"), (fsLit "logl"),
(fsLit "log10l"), (fsLit "log10"), (fsLit "log10f"),
(fsLit "log1pl"), (fsLit "log1p"), (fsLit "log1pf"),
(fsLit "log2"), (fsLit "log2f"), (fsLit "log2l"),
(fsLit "logb"), (fsLit "logbf"), (fsLit "logbl"),
(fsLit "lrint"), (fsLit "lrintf"), (fsLit "lrintl"),
(fsLit "lround"), (fsLit "lroundf"), (fsLit "lroundl"),
(fsLit "modf"), (fsLit "modff"), (fsLit "modfl"),
(fsLit "nan"), (fsLit "nanf"), (fsLit "nanl"),
(fsLit "nearbyint"), (fsLit "nearbyintf"), (fsLit "nearbyintl"),
(fsLit "nextafter"), (fsLit "nextafterf"), (fsLit "nextafterl"),
(fsLit "nexttoward"), (fsLit "nexttowardf"), (fsLit "nexttowardl"),
(fsLit "pow"), (fsLit "powf"), (fsLit "powl"),
(fsLit "remainder"), (fsLit "remainderf"), (fsLit "remainderl"),
(fsLit "remquo"), (fsLit "remquof"), (fsLit "remquol"),
(fsLit "rint"), (fsLit "rintf"), (fsLit "rintl"),
(fsLit "round"), (fsLit "roundf"), (fsLit "roundl"),
(fsLit "scalbln"), (fsLit "scalblnf"), (fsLit "scalblnl"),
(fsLit "scalbn"), (fsLit "scalbnf"), (fsLit "scalbnl"),
(fsLit "sin"), (fsLit "sinf"), (fsLit "sinl"),
(fsLit "sinh"), (fsLit "sinhf"), (fsLit "sinhl"),
(fsLit "sqrt"), (fsLit "sqrtf"), (fsLit "sqrtl"),
(fsLit "tan"), (fsLit "tanf"), (fsLit "tanl"),
(fsLit "tanh"), (fsLit "tanhf"), (fsLit "tanhl"),
(fsLit "tgamma"), (fsLit "tgammaf"), (fsLit "tgammal"),
(fsLit "trunc"), (fsLit "truncf"), (fsLit "truncl"),
-- ISO C 99 also defines these function-like macros in math.h:
-- fpclassify, isfinite, isinf, isnormal, signbit, isgreater,
-- isgreaterequal, isless, islessequal, islessgreater, isunordered
-- additional symbols from _BSD_SOURCE
(fsLit "drem"), (fsLit "dremf"), (fsLit "dreml"),
(fsLit "finite"), (fsLit "finitef"), (fsLit "finitel"),
(fsLit "gamma"), (fsLit "gammaf"), (fsLit "gammal"),
(fsLit "isinf"), (fsLit "isinff"), (fsLit "isinfl"),
(fsLit "isnan"), (fsLit "isnanf"), (fsLit "isnanl"),
(fsLit "j0"), (fsLit "j0f"), (fsLit "j0l"),
(fsLit "j1"), (fsLit "j1f"), (fsLit "j1l"),
(fsLit "jn"), (fsLit "jnf"), (fsLit "jnl"),
(fsLit "lgamma_r"), (fsLit "lgammaf_r"), (fsLit "lgammal_r"),
(fsLit "scalb"), (fsLit "scalbf"), (fsLit "scalbl"),
(fsLit "significand"), (fsLit "significandf"), (fsLit "significandl"),
(fsLit "y0"), (fsLit "y0f"), (fsLit "y0l"),
(fsLit "y1"), (fsLit "y1f"), (fsLit "y1l"),
(fsLit "yn"), (fsLit "ynf"), (fsLit "ynl")
]
-- -----------------------------------------------------------------------------
-- | Is a CLabel visible outside this object file or not?
-- From the point of view of the code generator, a name is
-- externally visible if it has to be declared as exported
-- in the .o file's symbol table; that is, made non-static.
externallyVisibleCLabel :: CLabel -> Bool -- not C "static"
externallyVisibleCLabel (CaseLabel _ _) = False
externallyVisibleCLabel (StringLitLabel _) = False
externallyVisibleCLabel (AsmTempLabel _) = False
externallyVisibleCLabel (PlainModuleInitLabel _)= True
externallyVisibleCLabel (RtsLabel _) = True
externallyVisibleCLabel (CmmLabel _ _ _) = True
externallyVisibleCLabel (ForeignLabel{}) = True
externallyVisibleCLabel (IdLabel name _ info) = isExternalName name && externallyVisibleIdLabel info
externallyVisibleCLabel (CC_Label _) = True
externallyVisibleCLabel (CCS_Label _) = True
externallyVisibleCLabel (DynamicLinkerLabel _ _) = False
externallyVisibleCLabel (HpcTicksLabel _) = True
externallyVisibleCLabel (LargeBitmapLabel _) = False
externallyVisibleCLabel (LargeSRTLabel _) = False
externallyVisibleCLabel (PicBaseLabel {}) = panic "externallyVisibleCLabel PicBaseLabel"
externallyVisibleCLabel (DeadStripPreventer {}) = panic "externallyVisibleCLabel DeadStripPreventer"
externallyVisibleIdLabel :: IdLabelInfo -> Bool
externallyVisibleIdLabel SRT = False
externallyVisibleIdLabel LocalInfoTable = False
externallyVisibleIdLabel LocalEntry = False
externallyVisibleIdLabel _ = True
-- -----------------------------------------------------------------------------
-- Finding the "type" of a CLabel
-- For generating correct types in label declarations:
data CLabelType
= CodeLabel -- Address of some executable instructions
| DataLabel -- Address of data, not a GC ptr
| GcPtrLabel -- Address of a (presumably static) GC object
isCFunctionLabel :: CLabel -> Bool
isCFunctionLabel lbl = case labelType lbl of
CodeLabel -> True
_other -> False
isGcPtrLabel :: CLabel -> Bool
isGcPtrLabel lbl = case labelType lbl of
GcPtrLabel -> True
_other -> False
-- | Work out the general type of data at the address of this label
-- whether it be code, data, or static GC object.
labelType :: CLabel -> CLabelType
labelType (CmmLabel _ _ CmmData) = DataLabel
labelType (CmmLabel _ _ CmmGcPtr) = GcPtrLabel
labelType (CmmLabel _ _ CmmCode) = CodeLabel
labelType (CmmLabel _ _ CmmInfo) = DataLabel
labelType (CmmLabel _ _ CmmEntry) = CodeLabel
labelType (CmmLabel _ _ CmmRetInfo) = DataLabel
labelType (CmmLabel _ _ CmmRet) = CodeLabel
labelType (RtsLabel (RtsSelectorInfoTable _ _)) = DataLabel
labelType (RtsLabel (RtsApInfoTable _ _)) = DataLabel
labelType (RtsLabel (RtsApFast _)) = CodeLabel
labelType (CaseLabel _ CaseReturnInfo) = DataLabel
labelType (CaseLabel _ _) = CodeLabel
labelType (PlainModuleInitLabel _) = CodeLabel
labelType (LargeSRTLabel _) = DataLabel
labelType (LargeBitmapLabel _) = DataLabel
labelType (ForeignLabel _ _ _ IsFunction) = CodeLabel
labelType (IdLabel _ _ info) = idInfoLabelType info
labelType _ = DataLabel
idInfoLabelType :: IdLabelInfo -> CLabelType
idInfoLabelType info =
case info of
InfoTable -> DataLabel
LocalInfoTable -> DataLabel
Closure -> GcPtrLabel
ConInfoTable -> DataLabel
StaticInfoTable -> DataLabel
ClosureTable -> DataLabel
RednCounts -> DataLabel
_ -> CodeLabel
-- -----------------------------------------------------------------------------
-- Does a CLabel need dynamic linkage?
-- When referring to data in code, we need to know whether
-- that data resides in a DLL or not. [Win32 only.]
-- @labelDynamic@ returns @True@ if the label is located
-- in a DLL, be it a data reference or not.
labelDynamic :: DynFlags -> PackageId -> CLabel -> Bool
labelDynamic dflags this_pkg lbl =
case lbl of
-- is the RTS in a DLL or not?
RtsLabel _ -> not opt_Static && (this_pkg /= rtsPackageId)
IdLabel n _ _ -> isDllName this_pkg n
-- When compiling in the "dyn" way, each package is to be linked into
-- its own shared library.
CmmLabel pkg _ _
| os == OSMinGW32 ->
not opt_Static && (this_pkg /= pkg)
| otherwise ->
True
ForeignLabel _ _ source _ ->
if os == OSMinGW32
then case source of
-- Foreign label is in some un-named foreign package (or DLL).
ForeignLabelInExternalPackage -> True
-- Foreign label is linked into the same package as the
-- source file currently being compiled.
ForeignLabelInThisPackage -> False
-- Foreign label is in some named package.
-- When compiling in the "dyn" way, each package is to be
-- linked into its own DLL.
ForeignLabelInPackage pkgId ->
(not opt_Static) && (this_pkg /= pkgId)
else -- On Mac OS X and on ELF platforms, false positives are OK,
-- so we claim that all foreign imports come from dynamic
-- libraries
True
PlainModuleInitLabel m -> not opt_Static && this_pkg /= (modulePackageId m)
-- Note that DynamicLinkerLabels do NOT require dynamic linking themselves.
_ -> False
where os = platformOS (targetPlatform dflags)
{-
OLD?: These GRAN functions are needed for spitting out GRAN_FETCH() at the
right places. It is used to detect when the abstractC statement of an
CCodeBlock actually contains the code for a slow entry point. -- HWL
We need at least @Eq@ for @CLabels@, because we want to avoid
duplicate declarations in generating C (see @labelSeenTE@ in
@PprAbsC@).
-}
-----------------------------------------------------------------------------
-- Printing out CLabels.
{-
Convention:
<name>_<type>
where <name> is <Module>_<name> for external names and <unique> for
internal names. <type> is one of the following:
info Info table
srt Static reference table
srtd Static reference table descriptor
entry Entry code (function, closure)
slow Slow entry code (if any)
ret Direct return address
vtbl Vector table
<n>_alt Case alternative (tag n)
dflt Default case alternative
btm Large bitmap vector
closure Static closure
con_entry Dynamic Constructor entry code
con_info Dynamic Constructor info table
static_entry Static Constructor entry code
static_info Static Constructor info table
sel_info Selector info table
sel_entry Selector entry code
cc Cost centre
ccs Cost centre stack
Many of these distinctions are only for documentation reasons. For
example, _ret is only distinguished from _entry to make it easy to
tell whether a code fragment is a return point or a closure/function
entry.
Note [Closure and info labels]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For a function 'foo, we have:
foo_info : Points to the info table describing foo's closure
(and entry code for foo with tables next to code)
foo_closure : Static (no-free-var) closure only:
points to the statically-allocated closure
For a data constructor (such as Just or Nothing), we have:
Just_con_info: Info table for the data constructor itself
the first word of a heap-allocated Just
Just_info: Info table for the *worker function*, an
ordinary Haskell function of arity 1 that
allocates a (Just x) box:
Just = \x -> Just x
Just_closure: The closure for this worker
Nothing_closure: a statically allocated closure for Nothing
Nothing_static_info: info table for Nothing_closure
All these must be exported symbol, EXCEPT Just_info. We don't need to
export this because in other modules we either have
* A reference to 'Just'; use Just_closure
* A saturated call 'Just x'; allocate using Just_con_info
Not exporting these Just_info labels reduces the number of symbols
somewhat.
-}
instance PlatformOutputable CLabel where
pprPlatform = pprCLabel
pprCLabel :: Platform -> CLabel -> SDoc
pprCLabel platform (AsmTempLabel u)
| cGhcWithNativeCodeGen == "YES"
= getPprStyle $ \ sty ->
if asmStyle sty then
ptext (asmTempLabelPrefix platform) <> pprUnique u
else
char '_' <> pprUnique u
pprCLabel platform (DynamicLinkerLabel info lbl)
| cGhcWithNativeCodeGen == "YES"
= pprDynamicLinkerAsmLabel platform info lbl
pprCLabel _ PicBaseLabel
| cGhcWithNativeCodeGen == "YES"
= ptext (sLit "1b")
pprCLabel platform (DeadStripPreventer lbl)
| cGhcWithNativeCodeGen == "YES"
= pprCLabel platform lbl <> ptext (sLit "_dsp")
pprCLabel platform lbl
= getPprStyle $ \ sty ->
if cGhcWithNativeCodeGen == "YES" && asmStyle sty
then maybe_underscore (pprAsmCLbl platform lbl)
else pprCLbl lbl
maybe_underscore :: SDoc -> SDoc
maybe_underscore doc
| underscorePrefix = pp_cSEP <> doc
| otherwise = doc
pprAsmCLbl :: Platform -> CLabel -> SDoc
pprAsmCLbl platform (ForeignLabel fs (Just sz) _ _)
| platformOS platform == OSMinGW32
-- In asm mode, we need to put the suffix on a stdcall ForeignLabel.
-- (The C compiler does this itself).
= ftext fs <> char '@' <> int sz
pprAsmCLbl _ lbl
= pprCLbl lbl
pprCLbl :: CLabel -> SDoc
pprCLbl (StringLitLabel u)
= pprUnique u <> ptext (sLit "_str")
pprCLbl (CaseLabel u CaseReturnPt)
= hcat [pprUnique u, ptext (sLit "_ret")]
pprCLbl (CaseLabel u CaseReturnInfo)
= hcat [pprUnique u, ptext (sLit "_info")]
pprCLbl (CaseLabel u (CaseAlt tag))
= hcat [pprUnique u, pp_cSEP, int tag, ptext (sLit "_alt")]
pprCLbl (CaseLabel u CaseDefault)
= hcat [pprUnique u, ptext (sLit "_dflt")]
pprCLbl (LargeSRTLabel u) = pprUnique u <> pp_cSEP <> ptext (sLit "srtd")
pprCLbl (LargeBitmapLabel u) = text "b" <> pprUnique u <> pp_cSEP <> ptext (sLit "btm")
-- Some bitsmaps for tuple constructors have a numeric tag (e.g. '7')
-- until that gets resolved we'll just force them to start
-- with a letter so the label will be legal assmbly code.
pprCLbl (CmmLabel _ str CmmCode) = ftext str
pprCLbl (CmmLabel _ str CmmData) = ftext str
pprCLbl (CmmLabel _ str CmmGcPtr) = ftext str
pprCLbl (CmmLabel _ str CmmPrimCall) = ftext str
pprCLbl (RtsLabel (RtsApFast str)) = ftext str <> ptext (sLit "_fast")
pprCLbl (RtsLabel (RtsSelectorInfoTable upd_reqd offset))
= hcat [ptext (sLit "stg_sel_"), text (show offset),
ptext (if upd_reqd
then (sLit "_upd_info")
else (sLit "_noupd_info"))
]
pprCLbl (RtsLabel (RtsSelectorEntry upd_reqd offset))
= hcat [ptext (sLit "stg_sel_"), text (show offset),
ptext (if upd_reqd
then (sLit "_upd_entry")
else (sLit "_noupd_entry"))
]
pprCLbl (RtsLabel (RtsApInfoTable upd_reqd arity))
= hcat [ptext (sLit "stg_ap_"), text (show arity),
ptext (if upd_reqd
then (sLit "_upd_info")
else (sLit "_noupd_info"))
]
pprCLbl (RtsLabel (RtsApEntry upd_reqd arity))
= hcat [ptext (sLit "stg_ap_"), text (show arity),
ptext (if upd_reqd
then (sLit "_upd_entry")
else (sLit "_noupd_entry"))
]
pprCLbl (CmmLabel _ fs CmmInfo)
= ftext fs <> ptext (sLit "_info")
pprCLbl (CmmLabel _ fs CmmEntry)
= ftext fs <> ptext (sLit "_entry")
pprCLbl (CmmLabel _ fs CmmRetInfo)
= ftext fs <> ptext (sLit "_info")
pprCLbl (CmmLabel _ fs CmmRet)
= ftext fs <> ptext (sLit "_ret")
pprCLbl (RtsLabel (RtsPrimOp primop))
= ptext (sLit "stg_") <> ppr primop
pprCLbl (RtsLabel (RtsSlowTickyCtr pat))
= ptext (sLit "SLOW_CALL_") <> text pat <> ptext (sLit "_ctr")
pprCLbl (ForeignLabel str _ _ _)
= ftext str
pprCLbl (IdLabel name _cafs flavor) = ppr name <> ppIdFlavor flavor
pprCLbl (CC_Label cc) = ppr cc
pprCLbl (CCS_Label ccs) = ppr ccs
pprCLbl (PlainModuleInitLabel mod)
= ptext (sLit "__stginit_") <> ppr mod
pprCLbl (HpcTicksLabel mod)
= ptext (sLit "_hpc_tickboxes_") <> ppr mod <> ptext (sLit "_hpc")
pprCLbl (AsmTempLabel {}) = panic "pprCLbl AsmTempLabel"
pprCLbl (DynamicLinkerLabel {}) = panic "pprCLbl DynamicLinkerLabel"
pprCLbl (PicBaseLabel {}) = panic "pprCLbl PicBaseLabel"
pprCLbl (DeadStripPreventer {}) = panic "pprCLbl DeadStripPreventer"
ppIdFlavor :: IdLabelInfo -> SDoc
ppIdFlavor x = pp_cSEP <>
(case x of
Closure -> ptext (sLit "closure")
SRT -> ptext (sLit "srt")
InfoTable -> ptext (sLit "info")
LocalInfoTable -> ptext (sLit "info")
Entry -> ptext (sLit "entry")
LocalEntry -> ptext (sLit "entry")
Slow -> ptext (sLit "slow")
RednCounts -> ptext (sLit "ct")
ConEntry -> ptext (sLit "con_entry")
ConInfoTable -> ptext (sLit "con_info")
StaticConEntry -> ptext (sLit "static_entry")
StaticInfoTable -> ptext (sLit "static_info")
ClosureTable -> ptext (sLit "closure_tbl")
)
pp_cSEP :: SDoc
pp_cSEP = char '_'
instance Outputable ForeignLabelSource where
ppr fs
= case fs of
ForeignLabelInPackage pkgId -> parens $ text "package: " <> ppr pkgId
ForeignLabelInThisPackage -> parens $ text "this package"
ForeignLabelInExternalPackage -> parens $ text "external package"
-- -----------------------------------------------------------------------------
-- Machine-dependent knowledge about labels.
underscorePrefix :: Bool -- leading underscore on assembler labels?
underscorePrefix = (cLeadingUnderscore == "YES")
asmTempLabelPrefix :: Platform -> LitString -- for formatting labels
asmTempLabelPrefix platform =
if platformOS platform == OSDarwin
then sLit "L"
else sLit ".L"
pprDynamicLinkerAsmLabel :: Platform -> DynamicLinkerLabelInfo -> CLabel -> SDoc
pprDynamicLinkerAsmLabel platform dllInfo lbl
= if platformOS platform == OSDarwin
then if platformArch platform == ArchX86_64
then case dllInfo of
CodeStub -> char 'L' <> pprCLabel platform lbl <> text "$stub"
SymbolPtr -> char 'L' <> pprCLabel platform lbl <> text "$non_lazy_ptr"
GotSymbolPtr -> pprCLabel platform lbl <> text "@GOTPCREL"
GotSymbolOffset -> pprCLabel platform lbl
else case dllInfo of
CodeStub -> char 'L' <> pprCLabel platform lbl <> text "$stub"
SymbolPtr -> char 'L' <> pprCLabel platform lbl <> text "$non_lazy_ptr"
_ -> panic "pprDynamicLinkerAsmLabel"
else if osElfTarget (platformOS platform)
then if platformArch platform == ArchPPC
then case dllInfo of
CodeStub -> pprCLabel platform lbl <> text "@plt"
SymbolPtr -> text ".LC_" <> pprCLabel platform lbl
_ -> panic "pprDynamicLinkerAsmLabel"
else if platformArch platform == ArchX86_64
then case dllInfo of
CodeStub -> pprCLabel platform lbl <> text "@plt"
GotSymbolPtr -> pprCLabel platform lbl <> text "@gotpcrel"
GotSymbolOffset -> pprCLabel platform lbl
SymbolPtr -> text ".LC_" <> pprCLabel platform lbl
else case dllInfo of
CodeStub -> pprCLabel platform lbl <> text "@plt"
SymbolPtr -> text ".LC_" <> pprCLabel platform lbl
GotSymbolPtr -> pprCLabel platform lbl <> text "@got"
GotSymbolOffset -> pprCLabel platform lbl <> text "@gotoff"
else if platformOS platform == OSMinGW32
then case dllInfo of
SymbolPtr -> text "__imp_" <> pprCLabel platform lbl
_ -> panic "pprDynamicLinkerAsmLabel"
else panic "pprDynamicLinkerAsmLabel"
|
mcmaniac/ghc
|
compiler/cmm/CLabel.hs
|
Haskell
|
bsd-3-clause
| 46,035
|
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
TcInstDecls: Typechecking instance declarations
-}
{-# LANGUAGE CPP #-}
module ETA.TypeCheck.TcInstDcls ( tcInstDecls1, tcInstDecls2 ) where
import ETA.HsSyn.HsSyn
import ETA.TypeCheck.TcBinds
import ETA.TypeCheck.TcTyClsDecls
import ETA.TypeCheck.TcClassDcl( tcClassDecl2,
HsSigFun, lookupHsSig, mkHsSigFun,
findMethodBind, instantiateMethod, tcInstanceMethodBody )
import ETA.TypeCheck.TcPat ( addInlinePrags )
import ETA.TypeCheck.TcRnMonad
import ETA.TypeCheck.TcValidity
import ETA.TypeCheck.TcMType
import ETA.TypeCheck.TcType
import ETA.Iface.BuildTyCl
import ETA.TypeCheck.Inst
import ETA.Types.InstEnv
import ETA.TypeCheck.FamInst
import ETA.Types.FamInstEnv
import ETA.TypeCheck.TcDeriv
import ETA.TypeCheck.TcEnv
import ETA.TypeCheck.TcHsType
import ETA.TypeCheck.TcUnify
import ETA.Types.Coercion ( pprCoAxiom )
import ETA.Core.MkCore ( nO_METHOD_BINDING_ERROR_ID )
import ETA.Types.Type
import ETA.TypeCheck.TcEvidence
import ETA.Types.TyCon
import ETA.Types.CoAxiom
import ETA.BasicTypes.DataCon
import ETA.Types.Class
import ETA.BasicTypes.Var
import qualified ETA.BasicTypes.Var as Var
import ETA.BasicTypes.VarEnv
import ETA.BasicTypes.VarSet
import ETA.Prelude.PrelNames ( typeableClassName, genericClassNames )
import ETA.Utils.Bag
import ETA.BasicTypes.BasicTypes
import ETA.Main.DynFlags
import ETA.Main.ErrUtils
import ETA.Utils.FastString
import ETA.Main.HscTypes ( isHsBootOrSig )
import ETA.BasicTypes.Id
import ETA.BasicTypes.MkId
import ETA.BasicTypes.Name
import ETA.BasicTypes.NameSet
import ETA.Utils.Outputable
import qualified ETA.Utils.Outputable as Outputable
import ETA.BasicTypes.SrcLoc
import ETA.Utils.Util
import ETA.Utils.BooleanFormula ( isUnsatisfied, pprBooleanFormulaNice )
import Control.Monad
import ETA.Utils.Maybes ( isNothing, isJust, whenIsJust )
import Data.List ( mapAccumL, partition )
#include "HsVersions.h"
{-
Typechecking instance declarations is done in two passes. The first
pass, made by @tcInstDecls1@, collects information to be used in the
second pass.
This pre-processed info includes the as-yet-unprocessed bindings
inside the instance declaration. These are type-checked in the second
pass, when the class-instance envs and GVE contain all the info from
all the instance and value decls. Indeed that's the reason we need
two passes over the instance decls.
Note [How instance declarations are translated]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Here is how we translation instance declarations into Core
Running example:
class C a where
op1, op2 :: Ix b => a -> b -> b
op2 = <dm-rhs>
instance C a => C [a]
{-# INLINE [2] op1 #-}
op1 = <rhs>
===>
-- Method selectors
op1,op2 :: forall a. C a => forall b. Ix b => a -> b -> b
op1 = ...
op2 = ...
-- Default methods get the 'self' dictionary as argument
-- so they can call other methods at the same type
-- Default methods get the same type as their method selector
$dmop2 :: forall a. C a => forall b. Ix b => a -> b -> b
$dmop2 = /\a. \(d:C a). /\b. \(d2: Ix b). <dm-rhs>
-- NB: type variables 'a' and 'b' are *both* in scope in <dm-rhs>
-- Note [Tricky type variable scoping]
-- A top-level definition for each instance method
-- Here op1_i, op2_i are the "instance method Ids"
-- The INLINE pragma comes from the user pragma
{-# INLINE [2] op1_i #-} -- From the instance decl bindings
op1_i, op2_i :: forall a. C a => forall b. Ix b => [a] -> b -> b
op1_i = /\a. \(d:C a).
let this :: C [a]
this = df_i a d
-- Note [Subtle interaction of recursion and overlap]
local_op1 :: forall b. Ix b => [a] -> b -> b
local_op1 = <rhs>
-- Source code; run the type checker on this
-- NB: Type variable 'a' (but not 'b') is in scope in <rhs>
-- Note [Tricky type variable scoping]
in local_op1 a d
op2_i = /\a \d:C a. $dmop2 [a] (df_i a d)
-- The dictionary function itself
{-# NOINLINE CONLIKE df_i #-} -- Never inline dictionary functions
df_i :: forall a. C a -> C [a]
df_i = /\a. \d:C a. MkC (op1_i a d) (op2_i a d)
-- But see Note [Default methods in instances]
-- We can't apply the type checker to the default-method call
-- Use a RULE to short-circuit applications of the class ops
{-# RULE "op1@C[a]" forall a, d:C a.
op1 [a] (df_i d) = op1_i a d #-}
Note [Instances and loop breakers]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Note that df_i may be mutually recursive with both op1_i and op2_i.
It's crucial that df_i is not chosen as the loop breaker, even
though op1_i has a (user-specified) INLINE pragma.
* Instead the idea is to inline df_i into op1_i, which may then select
methods from the MkC record, and thereby break the recursion with
df_i, leaving a *self*-recurisve op1_i. (If op1_i doesn't call op at
the same type, it won't mention df_i, so there won't be recursion in
the first place.)
* If op1_i is marked INLINE by the user there's a danger that we won't
inline df_i in it, and that in turn means that (since it'll be a
loop-breaker because df_i isn't), op1_i will ironically never be
inlined. But this is OK: the recursion breaking happens by way of
a RULE (the magic ClassOp rule above), and RULES work inside InlineRule
unfoldings. See Note [RULEs enabled in SimplGently] in SimplUtils
Note [ClassOp/DFun selection]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
One thing we see a lot is stuff like
op2 (df d1 d2)
where 'op2' is a ClassOp and 'df' is DFun. Now, we could inline *both*
'op2' and 'df' to get
case (MkD ($cop1 d1 d2) ($cop2 d1 d2) ... of
MkD _ op2 _ _ _ -> op2
And that will reduce to ($cop2 d1 d2) which is what we wanted.
But it's tricky to make this work in practice, because it requires us to
inline both 'op2' and 'df'. But neither is keen to inline without having
seen the other's result; and it's very easy to get code bloat (from the
big intermediate) if you inline a bit too much.
Instead we use a cunning trick.
* We arrange that 'df' and 'op2' NEVER inline.
* We arrange that 'df' is ALWAYS defined in the sylised form
df d1 d2 = MkD ($cop1 d1 d2) ($cop2 d1 d2) ...
* We give 'df' a magical unfolding (DFunUnfolding [$cop1, $cop2, ..])
that lists its methods.
* We make CoreUnfold.exprIsConApp_maybe spot a DFunUnfolding and return
a suitable constructor application -- inlining df "on the fly" as it
were.
* ClassOp rules: We give the ClassOp 'op2' a BuiltinRule that
extracts the right piece iff its argument satisfies
exprIsConApp_maybe. This is done in MkId mkDictSelId
* We make 'df' CONLIKE, so that shared uses still match; eg
let d = df d1 d2
in ...(op2 d)...(op1 d)...
Note [Single-method classes]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If the class has just one method (or, more accurately, just one element
of {superclasses + methods}), then we use a different strategy.
class C a where op :: a -> a
instance C a => C [a] where op = <blah>
We translate the class decl into a newtype, which just gives a
top-level axiom. The "constructor" MkC expands to a cast, as does the
class-op selector.
axiom Co:C a :: C a ~ (a->a)
op :: forall a. C a -> (a -> a)
op a d = d |> (Co:C a)
MkC :: forall a. (a->a) -> C a
MkC = /\a.\op. op |> (sym Co:C a)
The clever RULE stuff doesn't work now, because ($df a d) isn't
a constructor application, so exprIsConApp_maybe won't return
Just <blah>.
Instead, we simply rely on the fact that casts are cheap:
$df :: forall a. C a => C [a]
{-# INLINE df #-} -- NB: INLINE this
$df = /\a. \d. MkC [a] ($cop_list a d)
= $cop_list |> forall a. C a -> (sym (Co:C [a]))
$cop_list :: forall a. C a => [a] -> [a]
$cop_list = <blah>
So if we see
(op ($df a d))
we'll inline 'op' and '$df', since both are simply casts, and
good things happen.
Why do we use this different strategy? Because otherwise we
end up with non-inlined dictionaries that look like
$df = $cop |> blah
which adds an extra indirection to every use, which seems stupid. See
Trac #4138 for an example (although the regression reported there
wasn't due to the indirection).
There is an awkward wrinkle though: we want to be very
careful when we have
instance C a => C [a] where
{-# INLINE op #-}
op = ...
then we'll get an INLINE pragma on $cop_list but it's important that
$cop_list only inlines when it's applied to *two* arguments (the
dictionary and the list argument). So we must not eta-expand $df
above. We ensure that this doesn't happen by putting an INLINE
pragma on the dfun itself; after all, it ends up being just a cast.
There is one more dark corner to the INLINE story, even more deeply
buried. Consider this (Trac #3772):
class DeepSeq a => C a where
gen :: Int -> a
instance C a => C [a] where
gen n = ...
class DeepSeq a where
deepSeq :: a -> b -> b
instance DeepSeq a => DeepSeq [a] where
{-# INLINE deepSeq #-}
deepSeq xs b = foldr deepSeq b xs
That gives rise to these defns:
$cdeepSeq :: DeepSeq a -> [a] -> b -> b
-- User INLINE( 3 args )!
$cdeepSeq a (d:DS a) b (x:[a]) (y:b) = ...
$fDeepSeq[] :: DeepSeq a -> DeepSeq [a]
-- DFun (with auto INLINE pragma)
$fDeepSeq[] a d = $cdeepSeq a d |> blah
$cp1 a d :: C a => DeepSep [a]
-- We don't want to eta-expand this, lest
-- $cdeepSeq gets inlined in it!
$cp1 a d = $fDeepSep[] a (scsel a d)
$fC[] :: C a => C [a]
-- Ordinary DFun
$fC[] a d = MkC ($cp1 a d) ($cgen a d)
Here $cp1 is the code that generates the superclass for C [a]. The
issue is this: we must not eta-expand $cp1 either, or else $fDeepSeq[]
and then $cdeepSeq will inline there, which is definitely wrong. Like
on the dfun, we solve this by adding an INLINE pragma to $cp1.
Note [Subtle interaction of recursion and overlap]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this
class C a where { op1,op2 :: a -> a }
instance C a => C [a] where
op1 x = op2 x ++ op2 x
op2 x = ...
instance C [Int] where
...
When type-checking the C [a] instance, we need a C [a] dictionary (for
the call of op2). If we look up in the instance environment, we find
an overlap. And in *general* the right thing is to complain (see Note
[Overlapping instances] in InstEnv). But in *this* case it's wrong to
complain, because we just want to delegate to the op2 of this same
instance.
Why is this justified? Because we generate a (C [a]) constraint in
a context in which 'a' cannot be instantiated to anything that matches
other overlapping instances, or else we would not be executing this
version of op1 in the first place.
It might even be a bit disguised:
nullFail :: C [a] => [a] -> [a]
nullFail x = op2 x ++ op2 x
instance C a => C [a] where
op1 x = nullFail x
Precisely this is used in package 'regex-base', module Context.hs.
See the overlapping instances for RegexContext, and the fact that they
call 'nullFail' just like the example above. The DoCon package also
does the same thing; it shows up in module Fraction.hs.
Conclusion: when typechecking the methods in a C [a] instance, we want to
treat the 'a' as an *existential* type variable, in the sense described
by Note [Binding when looking up instances]. That is why isOverlappableTyVar
responds True to an InstSkol, which is the kind of skolem we use in
tcInstDecl2.
Note [Tricky type variable scoping]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In our example
class C a where
op1, op2 :: Ix b => a -> b -> b
op2 = <dm-rhs>
instance C a => C [a]
{-# INLINE [2] op1 #-}
op1 = <rhs>
note that 'a' and 'b' are *both* in scope in <dm-rhs>, but only 'a' is
in scope in <rhs>. In particular, we must make sure that 'b' is in
scope when typechecking <dm-rhs>. This is achieved by subFunTys,
which brings appropriate tyvars into scope. This happens for both
<dm-rhs> and for <rhs>, but that doesn't matter: the *renamer* will have
complained if 'b' is mentioned in <rhs>.
************************************************************************
* *
\subsection{Extracting instance decls}
* *
************************************************************************
Gather up the instance declarations from their various sources
-}
tcInstDecls1 -- Deal with both source-code and imported instance decls
:: [LTyClDecl Name] -- For deriving stuff
-> [LInstDecl Name] -- Source code instance decls
-> [LDerivDecl Name] -- Source code stand-alone deriving decls
-> TcM (TcGblEnv, -- The full inst env
[InstInfo Name], -- Source-code instance decls to process;
-- contains all dfuns for this module
HsValBinds Name) -- Supporting bindings for derived instances
tcInstDecls1 tycl_decls inst_decls deriv_decls
= checkNoErrs $
do { -- Stop if addInstInfos etc discovers any errors
-- (they recover, so that we get more than one error each
-- round)
-- Do class and family instance declarations
; stuff <- mapAndRecoverM tcLocalInstDecl inst_decls
; let (local_infos_s, fam_insts_s) = unzip stuff
fam_insts = concat fam_insts_s
local_infos' = concat local_infos_s
-- Handwritten instances of the poly-kinded Typeable class are
-- forbidden, so we handle those separately
(typeable_instances, local_infos)
= partition bad_typeable_instance local_infos'
; addClsInsts local_infos $
addFamInsts fam_insts $
do { -- Compute instances from "deriving" clauses;
-- This stuff computes a context for the derived instance
-- decl, so it needs to know about all the instances possible
-- NB: class instance declarations can contain derivings as
-- part of associated data type declarations
failIfErrsM -- If the addInsts stuff gave any errors, don't
-- try the deriving stuff, because that may give
-- more errors still
; traceTc "tcDeriving" Outputable.empty
; th_stage <- getStage -- See Note [Deriving inside TH brackets ]
; (gbl_env, deriv_inst_info, deriv_binds)
<- if isBrackStage th_stage
then do { gbl_env <- getGblEnv
; return (gbl_env, emptyBag, emptyValBindsOut) }
else tcDeriving tycl_decls inst_decls deriv_decls
-- Fail if there are any handwritten instance of poly-kinded Typeable
; mapM_ typeable_err typeable_instances
-- Check that if the module is compiled with -XSafe, there are no
-- hand written instances of old Typeable as then unsafe casts could be
-- performed. Derived instances are OK.
; dflags <- getDynFlags
; when (safeLanguageOn dflags) $ forM_ local_infos $ \x -> case x of
_ | genInstCheck x -> addErrAt (getSrcSpan $ iSpec x) (genInstErr x)
_ -> return ()
-- As above but for Safe Inference mode.
; when (safeInferOn dflags) $ forM_ local_infos $ \x -> case x of
_ | genInstCheck x -> recordUnsafeInfer
_ | overlapCheck x -> recordUnsafeInfer
_ -> return ()
; return ( gbl_env
, bagToList deriv_inst_info ++ local_infos
, deriv_binds)
}}
where
-- Separate the Typeable instances from the rest
bad_typeable_instance i
= typeableClassName == is_cls_nm (iSpec i)
overlapCheck ty = case overlapMode (is_flag $ iSpec ty) of
NoOverlap _ -> False
_ -> True
genInstCheck ty = is_cls_nm (iSpec ty) `elem` genericClassNames
genInstErr i = hang (ptext (sLit $ "Generic instances can only be "
++ "derived in Safe Haskell.") $+$
ptext (sLit "Replace the following instance:"))
2 (pprInstanceHdr (iSpec i))
-- Report an error or a warning for a `Typeable` instances.
-- If we are workikng on an .hs-boot file, we just report a warning,
-- and ignore the instance. We do this, to give users a chance to fix
-- their code.
typeable_err i =
setSrcSpan (getSrcSpan (iSpec i)) $
do env <- getGblEnv
if isHsBootOrSig (tcg_src env)
then
do warn <- woptM Opt_WarnDerivingTypeable
when warn $ addWarnTc $ vcat
[ ptext (sLit "`Typeable` instances in .hs-boot files are ignored.")
, ptext (sLit "This warning will become an error in future versions of the compiler.")
]
else addErrTc $ ptext (sLit "Class `Typeable` does not support user-specified instances.")
addClsInsts :: [InstInfo Name] -> TcM a -> TcM a
addClsInsts infos thing_inside
= tcExtendLocalInstEnv (map iSpec infos) thing_inside
addFamInsts :: [FamInst] -> TcM a -> TcM a
-- Extend (a) the family instance envt
-- (b) the type envt with stuff from data type decls
addFamInsts fam_insts thing_inside
= tcExtendLocalFamInstEnv fam_insts $
tcExtendGlobalEnv things $
do { traceTc "addFamInsts" (pprFamInsts fam_insts)
; tcg_env <- tcAddImplicits things
; setGblEnv tcg_env thing_inside }
where
axioms = map (toBranchedAxiom . famInstAxiom) fam_insts
tycons = famInstsRepTyCons fam_insts
things = map ATyCon tycons ++ map ACoAxiom axioms
{-
Note [Deriving inside TH brackets]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Given a declaration bracket
[d| data T = A | B deriving( Show ) |]
there is really no point in generating the derived code for deriving(
Show) and then type-checking it. This will happen at the call site
anyway, and the type check should never fail! Moreover (Trac #6005)
the scoping of the generated code inside the bracket does not seem to
work out.
The easy solution is simply not to generate the derived instances at
all. (A less brutal solution would be to generate them with no
bindings.) This will become moot when we shift to the new TH plan, so
the brutal solution will do.
-}
tcLocalInstDecl :: LInstDecl Name
-> TcM ([InstInfo Name], [FamInst])
-- A source-file instance declaration
-- Type-check all the stuff before the "where"
--
-- We check for respectable instance type, and context
tcLocalInstDecl (L loc (TyFamInstD { tfid_inst = decl }))
= do { fam_inst <- tcTyFamInstDecl Nothing (L loc decl)
; return ([], [fam_inst]) }
tcLocalInstDecl (L loc (DataFamInstD { dfid_inst = decl }))
= do { fam_inst <- tcDataFamInstDecl Nothing (L loc decl)
; return ([], [fam_inst]) }
tcLocalInstDecl (L loc (ClsInstD { cid_inst = decl }))
= do { (insts, fam_insts) <- tcClsInstDecl (L loc decl)
; return (insts, fam_insts) }
tcClsInstDecl :: LClsInstDecl Name -> TcM ([InstInfo Name], [FamInst])
tcClsInstDecl (L loc (ClsInstDecl { cid_poly_ty = poly_ty, cid_binds = binds
, cid_sigs = uprags, cid_tyfam_insts = ats
, cid_overlap_mode = overlap_mode
, cid_datafam_insts = adts }))
= setSrcSpan loc $
addErrCtxt (instDeclCtxt1 poly_ty) $
do { is_boot <- tcIsHsBootOrSig
; checkTc (not is_boot || (isEmptyLHsBinds binds && null uprags))
badBootDeclErr
; (tyvars, theta, clas, inst_tys) <- tcHsInstHead InstDeclCtxt poly_ty
; let mini_env = mkVarEnv (classTyVars clas `zip` inst_tys)
mini_subst = mkTvSubst (mkInScopeSet (mkVarSet tyvars)) mini_env
mb_info = Just (clas, mini_env)
-- Next, process any associated types.
; traceTc "tcLocalInstDecl" (ppr poly_ty)
; tyfam_insts0 <- tcExtendTyVarEnv tyvars $
mapAndRecoverM (tcTyFamInstDecl mb_info) ats
; datafam_insts <- tcExtendTyVarEnv tyvars $
mapAndRecoverM (tcDataFamInstDecl mb_info) adts
-- Check for missing associated types and build them
-- from their defaults (if available)
; let defined_ats = mkNameSet (map (tyFamInstDeclName . unLoc) ats)
`unionNameSet`
mkNameSet (map (unLoc . dfid_tycon . unLoc) adts)
; tyfam_insts1 <- mapM (tcATDefault mini_subst defined_ats)
(classATItems clas)
-- Finally, construct the Core representation of the instance.
-- (This no longer includes the associated types.)
; dfun_name <- newDFunName clas inst_tys (getLoc poly_ty)
-- Dfun location is that of instance *header*
; ispec <- newClsInst (fmap unLoc overlap_mode) dfun_name tyvars theta
clas inst_tys
; let inst_info = InstInfo { iSpec = ispec
, iBinds = InstBindings
{ ib_binds = binds
, ib_tyvars = map Var.varName tyvars -- Scope over bindings
, ib_pragmas = uprags
, ib_extensions = []
, ib_derived = False } }
; return ( [inst_info], tyfam_insts0 ++ concat tyfam_insts1 ++ datafam_insts) }
tcATDefault :: TvSubst -> NameSet -> ClassATItem -> TcM [FamInst]
-- ^ Construct default instances for any associated types that
-- aren't given a user definition
-- Returns [] or singleton
tcATDefault inst_subst defined_ats (ATI fam_tc defs)
-- User supplied instances ==> everything is OK
| tyConName fam_tc `elemNameSet` defined_ats
= return []
-- No user instance, have defaults ==> instatiate them
-- Example: class C a where { type F a b :: *; type F a b = () }
-- instance C [x]
-- Then we want to generate the decl: type F [x] b = ()
| Just (rhs_ty, _loc) <- defs
= do { let (subst', pat_tys') = mapAccumL subst_tv inst_subst
(tyConTyVars fam_tc)
rhs' = substTy subst' rhs_ty
tv_set' = tyVarsOfTypes pat_tys'
tvs' = varSetElemsKvsFirst tv_set'
; rep_tc_name <- newFamInstTyConName (noLoc (tyConName fam_tc)) pat_tys'
; let axiom = mkSingleCoAxiom rep_tc_name tvs' fam_tc pat_tys' rhs'
; traceTc "mk_deflt_at_instance" (vcat [ ppr fam_tc, ppr rhs_ty
, pprCoAxiom axiom ])
; fam_inst <- ASSERT( tyVarsOfType rhs' `subVarSet` tv_set' )
newFamInst SynFamilyInst axiom
; return [fam_inst] }
-- No defaults ==> generate a warning
| otherwise -- defs = Nothing
= do { warnMissingMethodOrAT "associated type" (tyConName fam_tc)
; return [] }
where
subst_tv subst tc_tv
| Just ty <- lookupVarEnv (getTvSubstEnv subst) tc_tv
= (subst, ty)
| otherwise
= (extendTvSubst subst tc_tv ty', ty')
where
ty' = mkTyVarTy (updateTyVarKind (substTy subst) tc_tv)
{-
************************************************************************
* *
Type checking family instances
* *
************************************************************************
Family instances are somewhat of a hybrid. They are processed together with
class instance heads, but can contain data constructors and hence they share a
lot of kinding and type checking code with ordinary algebraic data types (and
GADTs).
-}
tcFamInstDeclCombined :: Maybe (Class, VarEnv Type) -- the class & mini_env if applicable
-> Located Name -> TcM TyCon
tcFamInstDeclCombined mb_clsinfo fam_tc_lname
= do { -- Type family instances require -XTypeFamilies
-- and can't (currently) be in an hs-boot file
; traceTc "tcFamInstDecl" (ppr fam_tc_lname)
; type_families <- xoptM Opt_TypeFamilies
; is_boot <- tcIsHsBootOrSig -- Are we compiling an hs-boot file?
; checkTc type_families $ badFamInstDecl fam_tc_lname
; checkTc (not is_boot) $ badBootFamInstDeclErr
-- Look up the family TyCon and check for validity including
-- check that toplevel type instances are not for associated types.
; fam_tc <- tcLookupLocatedTyCon fam_tc_lname
; when (isNothing mb_clsinfo && -- Not in a class decl
isTyConAssoc fam_tc) -- but an associated type
(addErr $ assocInClassErr fam_tc_lname)
; return fam_tc }
tcTyFamInstDecl :: Maybe (Class, VarEnv Type) -- the class & mini_env if applicable
-> LTyFamInstDecl Name -> TcM FamInst
-- "type instance"
tcTyFamInstDecl mb_clsinfo (L loc decl@(TyFamInstDecl { tfid_eqn = eqn }))
= setSrcSpan loc $
tcAddTyFamInstCtxt decl $
do { let fam_lname = tfe_tycon (unLoc eqn)
; fam_tc <- tcFamInstDeclCombined mb_clsinfo fam_lname
-- (0) Check it's an open type family
; checkTc (isFamilyTyCon fam_tc) (notFamily fam_tc)
; checkTc (isTypeFamilyTyCon fam_tc) (wrongKindOfFamily fam_tc)
; checkTc (isOpenTypeFamilyTyCon fam_tc) (notOpenFamily fam_tc)
-- (1) do the work of verifying the synonym group
; co_ax_branch <- tcTyFamInstEqn (famTyConShape fam_tc) eqn
-- (2) check for validity
; checkValidTyFamInst mb_clsinfo fam_tc co_ax_branch
-- (3) construct coercion axiom
; rep_tc_name <- newFamInstAxiomName loc (unLoc fam_lname)
[co_ax_branch]
; let axiom = mkUnbranchedCoAxiom rep_tc_name fam_tc co_ax_branch
; newFamInst SynFamilyInst axiom }
tcDataFamInstDecl :: Maybe (Class, VarEnv Type)
-> LDataFamInstDecl Name -> TcM FamInst
-- "newtype instance" and "data instance"
tcDataFamInstDecl mb_clsinfo
(L loc decl@(DataFamInstDecl
{ dfid_pats = pats
, dfid_tycon = fam_tc_name
, dfid_defn = defn@HsDataDefn { dd_ND = new_or_data, dd_cType = cType
, dd_ctxt = ctxt, dd_cons = cons } }))
= setSrcSpan loc $
tcAddDataFamInstCtxt decl $
do { fam_tc <- tcFamInstDeclCombined mb_clsinfo fam_tc_name
-- Check that the family declaration is for the right kind
; checkTc (isFamilyTyCon fam_tc) (notFamily fam_tc)
; checkTc (isAlgTyCon fam_tc) (wrongKindOfFamily fam_tc)
-- Kind check type patterns
; tcFamTyPats (famTyConShape fam_tc) pats
(kcDataDefn defn) $
\tvs' pats' res_kind -> do
{ -- Check that left-hand side contains no type family applications
-- (vanilla synonyms are fine, though, and we checked for
-- foralls earlier)
checkValidFamPats fam_tc tvs' pats'
-- Check that type patterns match class instance head, if any
; checkConsistentFamInst mb_clsinfo fam_tc tvs' pats'
-- Result kind must be '*' (otherwise, we have too few patterns)
; checkTc (isLiftedTypeKind res_kind) $ tooFewParmsErr (tyConArity fam_tc)
; stupid_theta <- tcHsContext ctxt
; gadt_syntax <- dataDeclChecks (tyConName fam_tc) new_or_data stupid_theta cons
-- Construct representation tycon
; rep_tc_name <- newFamInstTyConName fam_tc_name pats'
; axiom_name <- newImplicitBinder rep_tc_name mkInstTyCoOcc
; let orig_res_ty = mkTyConApp fam_tc pats'
; (rep_tc, fam_inst) <- fixM $ \ ~(rec_rep_tc, _) ->
do { data_cons <- tcConDecls new_or_data rec_rep_tc
(tvs', orig_res_ty) cons
; tc_rhs <- case new_or_data of
DataType -> return (mkDataTyConRhs data_cons)
NewType -> ASSERT( not (null data_cons) )
mkNewTyConRhs rep_tc_name rec_rep_tc (head data_cons)
-- freshen tyvars
; let (eta_tvs, eta_pats) = eta_reduce tvs' pats'
axiom = mkSingleCoAxiom axiom_name eta_tvs fam_tc eta_pats
(mkTyConApp rep_tc (mkTyVarTys eta_tvs))
parent = FamInstTyCon axiom fam_tc pats'
roles = map (const Nominal) tvs'
rep_tc = buildAlgTyCon rep_tc_name tvs' roles
(fmap unLoc cType) stupid_theta
tc_rhs
Recursive
False -- No promotable to the kind level
gadt_syntax parent
-- We always assume that indexed types are recursive. Why?
-- (1) Due to their open nature, we can never be sure that a
-- further instance might not introduce a new recursive
-- dependency. (2) They are always valid loop breakers as
-- they involve a coercion.
; fam_inst <- newFamInst (DataFamilyInst rep_tc) axiom
; return (rep_tc, fam_inst) }
-- Remember to check validity; no recursion to worry about here
; checkValidTyCon rep_tc
; return fam_inst } }
where
-- See Note [Eta reduction for data family axioms]
-- [a,b,c,d].T [a] c Int c d ==> [a,b,c]. T [a] c Int c
eta_reduce tvs pats = go (reverse tvs) (reverse pats)
go (tv:tvs) (pat:pats)
| Just tv' <- getTyVar_maybe pat
, tv == tv'
, not (tv `elemVarSet` tyVarsOfTypes pats)
= go tvs pats
go tvs pats = (reverse tvs, reverse pats)
{-
Note [Eta reduction for data family axioms]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this
data family T a b :: *
newtype instance T Int a = MkT (IO a) deriving( Monad )
We'd like this to work. From the 'newtype instance' you might
think we'd get:
newtype TInt a = MkT (IO a)
axiom ax1 a :: T Int a ~ TInt a -- The type-instance part
axiom ax2 a :: TInt a ~ IO a -- The newtype part
But now what can we do? We have this problem
Given: d :: Monad IO
Wanted: d' :: Monad (T Int) = d |> ????
What coercion can we use for the ???
Solution: eta-reduce both axioms, thus:
axiom ax1 :: T Int ~ TInt
axiom ax2 :: TInt ~ IO
Now
d' = d |> Monad (sym (ax2 ; ax1))
This eta reduction happens both for data instances and newtype instances.
See Note [Newtype eta] in TyCon.
************************************************************************
* *
Type-checking instance declarations, pass 2
* *
************************************************************************
-}
tcInstDecls2 :: [LTyClDecl Name] -> [InstInfo Name]
-> TcM (LHsBinds Id)
-- (a) From each class declaration,
-- generate any default-method bindings
-- (b) From each instance decl
-- generate the dfun binding
tcInstDecls2 tycl_decls inst_decls
= do { -- (a) Default methods from class decls
let class_decls = filter (isClassDecl . unLoc) tycl_decls
; dm_binds_s <- mapM tcClassDecl2 class_decls
; let dm_binds = unionManyBags dm_binds_s
-- (b) instance declarations
; let dm_ids = collectHsBindsBinders dm_binds
-- Add the default method Ids (again)
-- See Note [Default methods and instances]
; inst_binds_s <- tcExtendLetEnv TopLevel TopLevel dm_ids $
mapM tcInstDecl2 inst_decls
-- Done
; return (dm_binds `unionBags` unionManyBags inst_binds_s) }
{-
See Note [Default methods and instances]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The default method Ids are already in the type environment (see Note
[Default method Ids and Template Haskell] in TcTyClsDcls), BUT they
don't have their InlinePragmas yet. Usually that would not matter,
because the simplifier propagates information from binding site to
use. But, unusually, when compiling instance decls we *copy* the
INLINE pragma from the default method to the method for that
particular operation (see Note [INLINE and default methods] below).
So right here in tcInstDecls2 we must re-extend the type envt with
the default method Ids replete with their INLINE pragmas. Urk.
-}
tcInstDecl2 :: InstInfo Name -> TcM (LHsBinds Id)
-- Returns a binding for the dfun
tcInstDecl2 (InstInfo { iSpec = ispec, iBinds = ibinds })
= recoverM (return emptyLHsBinds) $
setSrcSpan loc $
addErrCtxt (instDeclCtxt2 (idType dfun_id)) $
do { -- Instantiate the instance decl with skolem constants
; (inst_tyvars, dfun_theta, inst_head) <- tcSkolDFunType (idType dfun_id)
-- We instantiate the dfun_id with superSkolems.
-- See Note [Subtle interaction of recursion and overlap]
-- and Note [Binding when looking up instances]
; let (clas, inst_tys) = tcSplitDFunHead inst_head
(class_tyvars, sc_theta, _, op_items) = classBigSig clas
sc_theta' = substTheta (zipOpenTvSubst class_tyvars inst_tys) sc_theta
; dfun_ev_vars <- newEvVars dfun_theta
; sc_ev_vars <- tcSuperClasses dfun_id inst_tyvars dfun_ev_vars sc_theta'
-- Deal with 'SPECIALISE instance' pragmas
-- See Note [SPECIALISE instance pragmas]
; spec_inst_info@(spec_inst_prags,_) <- tcSpecInstPrags dfun_id ibinds
-- Typecheck the methods
; (meth_ids, meth_binds)
<- tcInstanceMethods dfun_id clas inst_tyvars dfun_ev_vars
inst_tys spec_inst_info
op_items ibinds
-- Create the result bindings
; self_dict <- newDict clas inst_tys
; let class_tc = classTyCon clas
[dict_constr] = tyConDataCons class_tc
dict_bind = mkVarBind self_dict (L loc con_app_args)
-- We don't produce a binding for the dict_constr; instead we
-- rely on the simplifier to unfold this saturated application
-- We do this rather than generate an HsCon directly, because
-- it means that the special cases (e.g. dictionary with only one
-- member) are dealt with by the common MkId.mkDataConWrapId
-- code rather than needing to be repeated here.
-- con_app_tys = MkD ty1 ty2
-- con_app_scs = MkD ty1 ty2 sc1 sc2
-- con_app_args = MkD ty1 ty2 sc1 sc2 op1 op2
con_app_tys = wrapId (mkWpTyApps inst_tys)
(dataConWrapId dict_constr)
con_app_scs = mkHsWrap (mkWpEvApps (map EvId sc_ev_vars)) con_app_tys
con_app_args = foldl app_to_meth con_app_scs meth_ids
app_to_meth :: HsExpr Id -> Id -> HsExpr Id
app_to_meth fun meth_id = L loc fun `HsApp` L loc (wrapId arg_wrapper meth_id)
inst_tv_tys = mkTyVarTys inst_tyvars
arg_wrapper = mkWpEvVarApps dfun_ev_vars <.> mkWpTyApps inst_tv_tys
-- Do not inline the dfun; instead give it a magic DFunFunfolding
dfun_spec_prags
| isNewTyCon class_tc = SpecPrags []
-- Newtype dfuns just inline unconditionally,
-- so don't attempt to specialise them
| otherwise
= SpecPrags spec_inst_prags
export = ABE { abe_wrap = idHsWrapper, abe_poly = dfun_id
, abe_mono = self_dict, abe_prags = dfun_spec_prags }
-- NB: see Note [SPECIALISE instance pragmas]
main_bind = AbsBinds { abs_tvs = inst_tyvars
, abs_ev_vars = dfun_ev_vars
, abs_exports = [export]
, abs_ev_binds = emptyTcEvBinds
, abs_binds = unitBag dict_bind }
; return (unitBag (L loc main_bind) `unionBags`
listToBag meth_binds)
}
where
dfun_id = instanceDFunId ispec
loc = getSrcSpan dfun_id
------------------------------
tcSuperClasses :: DFunId -> [TcTyVar] -> [EvVar] -> TcThetaType
-> TcM [EvVar]
-- See Note [Silent superclass arguments]
tcSuperClasses dfun_id inst_tyvars dfun_ev_vars sc_theta
| null inst_tyvars && null dfun_ev_vars
= emitWanteds ScOrigin sc_theta
| otherwise
= do { -- Check that all superclasses can be deduced from
-- the originally-specified dfun arguments
; _ <- checkConstraints InstSkol inst_tyvars orig_ev_vars $
emitWanteds ScOrigin sc_theta
; return (map (find dfun_ev_vars) sc_theta) }
where
n_silent = dfunNSilent dfun_id
orig_ev_vars = drop n_silent dfun_ev_vars
find [] pred
= pprPanic "tcInstDecl2" (ppr dfun_id $$ ppr (idType dfun_id) $$ ppr pred)
find (ev:evs) pred
| pred `eqPred` evVarPred ev = ev
| otherwise = find evs pred
----------------------
mkMethIds :: HsSigFun -> Class -> [TcTyVar] -> [EvVar]
-> [TcType] -> Id -> TcM (TcId, TcSigInfo, HsWrapper)
mkMethIds sig_fn clas tyvars dfun_ev_vars inst_tys sel_id
= do { poly_meth_name <- newName (mkClassOpAuxOcc sel_occ)
; local_meth_name <- newName sel_occ
-- Base the local_meth_name on the selector name, because
-- type errors from tcInstanceMethodBody come from here
; let poly_meth_id = mkLocalId poly_meth_name poly_meth_ty
local_meth_id = mkLocalId local_meth_name local_meth_ty
; case lookupHsSig sig_fn sel_name of
Just lhs_ty -- There is a signature in the instance declaration
-- See Note [Instance method signatures]
-> setSrcSpan (getLoc lhs_ty) $
do { inst_sigs <- xoptM Opt_InstanceSigs
; checkTc inst_sigs (misplacedInstSig sel_name lhs_ty)
; sig_ty <- tcHsSigType (FunSigCtxt sel_name) lhs_ty
; let poly_sig_ty = mkSigmaTy tyvars theta sig_ty
; tc_sig <- instTcTySig lhs_ty sig_ty Nothing [] local_meth_name
; hs_wrap <- addErrCtxtM (methSigCtxt sel_name poly_sig_ty poly_meth_ty) $
tcSubType (FunSigCtxt sel_name) poly_sig_ty poly_meth_ty
; return (poly_meth_id, tc_sig, hs_wrap) }
Nothing -- No type signature
-> do { tc_sig <- instTcTySigFromId local_meth_id
; return (poly_meth_id, tc_sig, idHsWrapper) } }
-- Absent a type sig, there are no new scoped type variables here
-- Only the ones from the instance decl itself, which are already
-- in scope. Example:
-- class C a where { op :: forall b. Eq b => ... }
-- instance C [c] where { op = <rhs> }
-- In <rhs>, 'c' is scope but 'b' is not!
where
sel_name = idName sel_id
sel_occ = nameOccName sel_name
local_meth_ty = instantiateMethod clas sel_id inst_tys
poly_meth_ty = mkSigmaTy tyvars theta local_meth_ty
theta = map idType dfun_ev_vars
methSigCtxt :: Name -> TcType -> TcType -> TidyEnv -> TcM (TidyEnv, MsgDoc)
methSigCtxt sel_name sig_ty meth_ty env0
= do { (env1, sig_ty) <- zonkTidyTcType env0 sig_ty
; (env2, meth_ty) <- zonkTidyTcType env1 meth_ty
; let msg = hang (ptext (sLit "When checking that instance signature for") <+> quotes (ppr sel_name))
2 (vcat [ ptext (sLit "is more general than its signature in the class")
, ptext (sLit "Instance sig:") <+> ppr sig_ty
, ptext (sLit " Class sig:") <+> ppr meth_ty ])
; return (env2, msg) }
misplacedInstSig :: Name -> LHsType Name -> SDoc
misplacedInstSig name hs_ty
= vcat [ hang (ptext (sLit "Illegal type signature in instance declaration:"))
2 (hang (pprPrefixName name)
2 (dcolon <+> ppr hs_ty))
, ptext (sLit "(Use InstanceSigs to allow this)") ]
------------------------------
tcSpecInstPrags :: DFunId -> InstBindings Name
-> TcM ([Located TcSpecPrag], PragFun)
tcSpecInstPrags dfun_id (InstBindings { ib_binds = binds, ib_pragmas = uprags })
= do { spec_inst_prags <- mapM (wrapLocM (tcSpecInst dfun_id)) $
filter isSpecInstLSig uprags
-- The filter removes the pragmas for methods
; return (spec_inst_prags, mkPragFun uprags binds) }
{-
Note [Instance method signatures]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
With -XInstanceSigs we allow the user to supply a signature for the
method in an instance declaration. Here is an artificial example:
data Age = MkAge Int
instance Ord Age where
compare :: a -> a -> Bool
compare = error "You can't compare Ages"
We achieve this by building a TcSigInfo for the method, whether or not
there is an instance method signature, and using that to typecheck
the declaration (in tcInstanceMethodBody). That means, conveniently,
that the type variables bound in the signature will scope over the body.
What about the check that the instance method signature is more
polymorphic than the instantiated class method type? We just do a
tcSubType call in mkMethIds, and use the HsWrapper thus generated in
the method AbsBind. It's very like the tcSubType impedence-matching
call in mkExport. We have to pass the HsWrapper into
tcInstanceMethodBody.
Note [Silent superclass arguments]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
See Trac #3731, #4809, #5751, #5913, #6117, which all
describe somewhat more complicated situations, but ones
encountered in practice.
THE PROBLEM
The problem is that it is all too easy to create a class whose
superclass is bottom when it should not be.
Consider the following (extreme) situation:
class C a => D a where ...
instance D [a] => D [a] where ... (dfunD)
instance C [a] => C [a] where ... (dfunC)
Although this looks wrong (assume D [a] to prove D [a]), it is only a
more extreme case of what happens with recursive dictionaries, and it
can, just about, make sense because the methods do some work before
recursing.
To implement the dfunD we must generate code for the superclass C [a],
which we had better not get by superclass selection from the supplied
argument:
dfunD :: forall a. D [a] -> D [a]
dfunD = \d::D [a] -> MkD (scsel d) ..
Otherwise if we later encounter a situation where
we have a [Wanted] dw::D [a] we might solve it thus:
dw := dfunD dw
Which is all fine except that now ** the superclass C is bottom **!
The instance we want is:
dfunD :: forall a. D [a] -> D [a]
dfunD = \d::D [a] -> MkD (dfunC (scsel d)) ...
THE SOLUTION
Our solution to this problem "silent superclass arguments". We pass
to each dfun some ``silent superclass arguments’’, which are the
immediate superclasses of the dictionary we are trying to
construct. In our example:
dfun :: forall a. C [a] -> D [a] -> D [a]
dfun = \(dc::C [a]) (dd::D [a]) -> DOrd dc ...
Notice the extra (dc :: C [a]) argument compared to the previous version.
This gives us:
-----------------------------------------------------------
DFun Superclass Invariant
~~~~~~~~~~~~~~~~~~~~~~~~
In the body of a DFun, every superclass argument to the
returned dictionary is
either * one of the arguments of the DFun,
or * constant, bound at top level
-----------------------------------------------------------
This net effect is that it is safe to treat a dfun application as
wrapping a dictionary constructor around its arguments (in particular,
a dfun never picks superclasses from the arguments under the
dictionary constructor). No superclass is hidden inside a dfun
application.
The extra arguments required to satisfy the DFun Superclass Invariant
always come first, and are called the "silent" arguments. You can
find out how many silent arguments there are using Id.dfunNSilent;
and then you can just drop that number of arguments to see the ones
that were in the original instance declaration.
DFun types are built (only) by MkId.mkDictFunId, so that is where we
decide what silent arguments are to be added.
In our example, if we had [Wanted] dw :: D [a] we would get via the instance:
dw := dfun d1 d2
[Wanted] (d1 :: C [a])
[Wanted] (d2 :: D [a])
And now, though we *can* solve:
d2 := dw
That's fine; and we solve d1:C[a] separately.
Test case SCLoop tests this fix.
Note [SPECIALISE instance pragmas]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
instance (Ix a, Ix b) => Ix (a,b) where
{-# SPECIALISE instance Ix (Int,Int) #-}
range (x,y) = ...
We make a specialised version of the dictionary function, AND
specialised versions of each *method*. Thus we should generate
something like this:
$dfIxPair :: (Ix a, Ix b) => Ix (a,b)
{-# DFUN [$crangePair, ...] #-}
{-# SPECIALISE $dfIxPair :: Ix (Int,Int) #-}
$dfIxPair da db = Ix ($crangePair da db) (...other methods...)
$crange :: (Ix a, Ix b) -> ((a,b),(a,b)) -> [(a,b)]
{-# SPECIALISE $crange :: ((Int,Int),(Int,Int)) -> [(Int,Int)] #-}
$crange da db = <blah>
The SPECIALISE pragmas are acted upon by the desugarer, which generate
dii :: Ix Int
dii = ...
$s$dfIxPair :: Ix ((Int,Int),(Int,Int))
{-# DFUN [$crangePair di di, ...] #-}
$s$dfIxPair = Ix ($crangePair di di) (...)
{-# RULE forall (d1,d2:Ix Int). $dfIxPair Int Int d1 d2 = $s$dfIxPair #-}
$s$crangePair :: ((Int,Int),(Int,Int)) -> [(Int,Int)]
$c$crangePair = ...specialised RHS of $crangePair...
{-# RULE forall (d1,d2:Ix Int). $crangePair Int Int d1 d2 = $s$crangePair #-}
Note that
* The specialised dictionary $s$dfIxPair is very much needed, in case we
call a function that takes a dictionary, but in a context where the
specialised dictionary can be used. See Trac #7797.
* The ClassOp rule for 'range' works equally well on $s$dfIxPair, because
it still has a DFunUnfolding. See Note [ClassOp/DFun selection]
* A call (range ($dfIxPair Int Int d1 d2)) might simplify two ways:
--> {ClassOp rule for range} $crangePair Int Int d1 d2
--> {SPEC rule for $crangePair} $s$crangePair
or thus:
--> {SPEC rule for $dfIxPair} range $s$dfIxPair
--> {ClassOpRule for range} $s$crangePair
It doesn't matter which way.
* We want to specialise the RHS of both $dfIxPair and $crangePair,
but the SAME HsWrapper will do for both! We can call tcSpecPrag
just once, and pass the result (in spec_inst_info) to tcInstanceMethods.
-}
tcSpecInst :: Id -> Sig Name -> TcM TcSpecPrag
tcSpecInst dfun_id prag@(SpecInstSig _src hs_ty)
= addErrCtxt (spec_ctxt prag) $
do { (tyvars, theta, clas, tys) <- tcHsInstHead SpecInstCtxt hs_ty
; let (_, spec_dfun_ty) = mkDictFunTy tyvars theta clas tys
; co_fn <- tcSubType SpecInstCtxt (idType dfun_id) spec_dfun_ty
; return (SpecPrag dfun_id co_fn defaultInlinePragma) }
where
spec_ctxt prag = hang (ptext (sLit "In the SPECIALISE pragma")) 2 (ppr prag)
tcSpecInst _ _ = panic "tcSpecInst"
{-
************************************************************************
* *
Type-checking an instance method
* *
************************************************************************
tcInstanceMethod
- Make the method bindings, as a [(NonRec, HsBinds)], one per method
- Remembering to use fresh Name (the instance method Name) as the binder
- Bring the instance method Ids into scope, for the benefit of tcInstSig
- Use sig_fn mapping instance method Name -> instance tyvars
- Ditto prag_fn
- Use tcValBinds to do the checking
-}
tcInstanceMethods :: DFunId -> Class -> [TcTyVar]
-> [EvVar]
-> [TcType]
-> ([Located TcSpecPrag], PragFun)
-> [(Id, DefMeth)]
-> InstBindings Name
-> TcM ([Id], [LHsBind Id])
-- The returned inst_meth_ids all have types starting
-- forall tvs. theta => ...
tcInstanceMethods dfun_id clas tyvars dfun_ev_vars inst_tys
(spec_inst_prags, prag_fn)
op_items (InstBindings { ib_binds = binds
, ib_tyvars = lexical_tvs
, ib_pragmas = sigs
, ib_extensions = exts
, ib_derived = is_derived })
= tcExtendTyVarEnv2 (lexical_tvs `zip` tyvars) $
-- The lexical_tvs scope over the 'where' part
do { traceTc "tcInstMeth" (ppr sigs $$ ppr binds)
; let hs_sig_fn = mkHsSigFun sigs
; checkMinimalDefinition
; set_exts exts $ mapAndUnzipM (tc_item hs_sig_fn) op_items }
where
set_exts :: [ExtensionFlag] -> TcM a -> TcM a
set_exts es thing = foldr setXOptM thing es
----------------------
tc_item :: HsSigFun -> (Id, DefMeth) -> TcM (Id, LHsBind Id)
tc_item sig_fn (sel_id, dm_info)
= case findMethodBind (idName sel_id) binds of
Just (user_bind, bndr_loc)
-> tc_body sig_fn sel_id user_bind bndr_loc
Nothing -> do { traceTc "tc_def" (ppr sel_id)
; tc_default sig_fn sel_id dm_info }
----------------------
tc_body :: HsSigFun -> Id -> LHsBind Name
-> SrcSpan -> TcM (TcId, LHsBind Id)
tc_body sig_fn sel_id rn_bind bndr_loc
= add_meth_ctxt sel_id rn_bind $
do { traceTc "tc_item" (ppr sel_id <+> ppr (idType sel_id))
; (meth_id, local_meth_sig, hs_wrap)
<- setSrcSpan bndr_loc $
mkMethIds sig_fn clas tyvars dfun_ev_vars
inst_tys sel_id
; let prags = prag_fn (idName sel_id)
; meth_id1 <- addInlinePrags meth_id prags
; spec_prags <- tcSpecPrags meth_id1 prags
; bind <- tcInstanceMethodBody InstSkol
tyvars dfun_ev_vars
meth_id1 local_meth_sig hs_wrap
(mk_meth_spec_prags meth_id1 spec_prags)
rn_bind
; return (meth_id1, bind) }
----------------------
tc_default :: HsSigFun -> Id -> DefMeth -> TcM (TcId, LHsBind Id)
tc_default sig_fn sel_id (GenDefMeth dm_name)
= do { meth_bind <- mkGenericDefMethBind clas inst_tys sel_id dm_name
; tc_body sig_fn sel_id meth_bind inst_loc }
tc_default sig_fn sel_id NoDefMeth -- No default method at all
= do { traceTc "tc_def: warn" (ppr sel_id)
; (meth_id, _, _) <- mkMethIds sig_fn clas tyvars dfun_ev_vars
inst_tys sel_id
; dflags <- getDynFlags
; return (meth_id,
mkVarBind meth_id $
mkLHsWrap lam_wrapper (error_rhs dflags)) }
where
error_rhs dflags = L inst_loc $ HsApp error_fun (error_msg dflags)
error_fun = L inst_loc $ wrapId (WpTyApp meth_tau) nO_METHOD_BINDING_ERROR_ID
error_msg dflags = L inst_loc (HsLit (HsStringPrim ""
(unsafeMkByteString (error_string dflags))))
meth_tau = funResultTy (applyTys (idType sel_id) inst_tys)
error_string dflags = showSDoc dflags (hcat [ppr inst_loc, text "|", ppr sel_id ])
lam_wrapper = mkWpTyLams tyvars <.> mkWpLams dfun_ev_vars
tc_default sig_fn sel_id (DefMeth dm_name) -- A polymorphic default method
= do { -- Build the typechecked version directly,
-- without calling typecheck_method;
-- see Note [Default methods in instances]
-- Generate /\as.\ds. let self = df as ds
-- in $dm inst_tys self
-- The 'let' is necessary only because HsSyn doesn't allow
-- you to apply a function to a dictionary *expression*.
; self_dict <- newDict clas inst_tys
; let self_ev_bind = EvBind self_dict
(EvDFunApp dfun_id (mkTyVarTys tyvars) (map EvId dfun_ev_vars))
; (meth_id, local_meth_sig, hs_wrap)
<- mkMethIds sig_fn clas tyvars dfun_ev_vars inst_tys sel_id
; dm_id <- tcLookupId dm_name
; let dm_inline_prag = idInlinePragma dm_id
rhs = HsWrap (mkWpEvVarApps [self_dict] <.> mkWpTyApps inst_tys) $
HsVar dm_id
local_meth_id = sig_id local_meth_sig
meth_bind = mkVarBind local_meth_id (L inst_loc rhs)
meth_id1 = meth_id `setInlinePragma` dm_inline_prag
-- Copy the inline pragma (if any) from the default
-- method to this version. Note [INLINE and default methods]
export = ABE { abe_wrap = hs_wrap, abe_poly = meth_id1
, abe_mono = local_meth_id
, abe_prags = mk_meth_spec_prags meth_id1 [] }
bind = AbsBinds { abs_tvs = tyvars, abs_ev_vars = dfun_ev_vars
, abs_exports = [export]
, abs_ev_binds = EvBinds (unitBag self_ev_bind)
, abs_binds = unitBag meth_bind }
-- Default methods in an instance declaration can't have their own
-- INLINE or SPECIALISE pragmas. It'd be possible to allow them, but
-- currently they are rejected with
-- "INLINE pragma lacks an accompanying binding"
; return (meth_id1, L inst_loc bind) }
----------------------
mk_meth_spec_prags :: Id -> [LTcSpecPrag] -> TcSpecPrags
-- Adapt the 'SPECIALISE instance' pragmas to work for this method Id
-- There are two sources:
-- * spec_prags_for_me: {-# SPECIALISE op :: <blah> #-}
-- * spec_prags_from_inst: derived from {-# SPECIALISE instance :: <blah> #-}
-- These ones have the dfun inside, but [perhaps surprisingly]
-- the correct wrapper.
mk_meth_spec_prags meth_id spec_prags_for_me
= SpecPrags (spec_prags_for_me ++ spec_prags_from_inst)
where
spec_prags_from_inst
| isInlinePragma (idInlinePragma meth_id)
= [] -- Do not inherit SPECIALISE from the instance if the
-- method is marked INLINE, because then it'll be inlined
-- and the specialisation would do nothing. (Indeed it'll provoke
-- a warning from the desugarer
| otherwise
= [ L inst_loc (SpecPrag meth_id wrap inl)
| L inst_loc (SpecPrag _ wrap inl) <- spec_inst_prags]
inst_loc = getSrcSpan dfun_id
-- For instance decls that come from deriving clauses
-- we want to print out the full source code if there's an error
-- because otherwise the user won't see the code at all
add_meth_ctxt sel_id rn_bind thing
| is_derived = addLandmarkErrCtxt (derivBindCtxt sel_id clas inst_tys rn_bind) thing
| otherwise = thing
----------------------
-- check if one of the minimal complete definitions is satisfied
checkMinimalDefinition
= whenIsJust (isUnsatisfied methodExists (classMinimalDef clas)) $
warnUnsatisifiedMinimalDefinition
where
methodExists meth = isJust (findMethodBind meth binds)
mkGenericDefMethBind :: Class -> [Type] -> Id -> Name -> TcM (LHsBind Name)
mkGenericDefMethBind clas inst_tys sel_id dm_name
= -- A generic default method
-- If the method is defined generically, we only have to call the
-- dm_name.
do { dflags <- getDynFlags
; liftIO (dumpIfSet_dyn dflags Opt_D_dump_deriv "Filling in method body"
(vcat [ppr clas <+> ppr inst_tys,
nest 2 (ppr sel_id <+> equals <+> ppr rhs)]))
; return (noLoc $ mkTopFunBind Generated (noLoc (idName sel_id))
[mkSimpleMatch [] rhs]) }
where
rhs = nlHsVar dm_name
----------------------
wrapId :: HsWrapper -> id -> HsExpr id
wrapId wrapper id = mkHsWrap wrapper (HsVar id)
derivBindCtxt :: Id -> Class -> [Type ] -> LHsBind Name -> SDoc
derivBindCtxt sel_id clas tys _bind
= vcat [ ptext (sLit "When typechecking the code for ") <+> quotes (ppr sel_id)
, nest 2 (ptext (sLit "in a derived instance for")
<+> quotes (pprClassPred clas tys) <> colon)
, nest 2 $ ptext (sLit "To see the code I am typechecking, use -ddump-deriv") ]
warnMissingMethodOrAT :: String -> Name -> TcM ()
warnMissingMethodOrAT what name
= do { warn <- woptM Opt_WarnMissingMethods
; traceTc "warn" (ppr name <+> ppr warn <+> ppr (not (startsWithUnderscore (getOccName name))))
; warnTc (warn -- Warn only if -fwarn-missing-methods
&& not (startsWithUnderscore (getOccName name)))
-- Don't warn about _foo methods
(ptext (sLit "No explicit") <+> text what <+> ptext (sLit "or default declaration for")
<+> quotes (ppr name)) }
warnUnsatisifiedMinimalDefinition :: ClassMinimalDef -> TcM ()
warnUnsatisifiedMinimalDefinition mindef
= do { warn <- woptM Opt_WarnMissingMethods
; warnTc warn message
}
where
message = vcat [ptext (sLit "No explicit implementation for")
,nest 2 $ pprBooleanFormulaNice mindef
]
{-
Note [Export helper functions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We arrange to export the "helper functions" of an instance declaration,
so that they are not subject to preInlineUnconditionally, even if their
RHS is trivial. Reason: they are mentioned in the DFunUnfolding of
the dict fun as Ids, not as CoreExprs, so we can't substitute a
non-variable for them.
We could change this by making DFunUnfoldings have CoreExprs, but it
seems a bit simpler this way.
Note [Default methods in instances]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this
class Baz v x where
foo :: x -> x
foo y = <blah>
instance Baz Int Int
From the class decl we get
$dmfoo :: forall v x. Baz v x => x -> x
$dmfoo y = <blah>
Notice that the type is ambiguous. That's fine, though. The instance
decl generates
$dBazIntInt = MkBaz fooIntInt
fooIntInt = $dmfoo Int Int $dBazIntInt
BUT this does mean we must generate the dictionary translation of
fooIntInt directly, rather than generating source-code and
type-checking it. That was the bug in Trac #1061. In any case it's
less work to generate the translated version!
Note [INLINE and default methods]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Default methods need special case. They are supposed to behave rather like
macros. For exmample
class Foo a where
op1, op2 :: Bool -> a -> a
{-# INLINE op1 #-}
op1 b x = op2 (not b) x
instance Foo Int where
-- op1 via default method
op2 b x = <blah>
The instance declaration should behave
just as if 'op1' had been defined with the
code, and INLINE pragma, from its original
definition.
That is, just as if you'd written
instance Foo Int where
op2 b x = <blah>
{-# INLINE op1 #-}
op1 b x = op2 (not b) x
So for the above example we generate:
{-# INLINE $dmop1 #-}
-- $dmop1 has an InlineCompulsory unfolding
$dmop1 d b x = op2 d (not b) x
$fFooInt = MkD $cop1 $cop2
{-# INLINE $cop1 #-}
$cop1 = $dmop1 $fFooInt
$cop2 = <blah>
Note carefully:
* We *copy* any INLINE pragma from the default method $dmop1 to the
instance $cop1. Otherwise we'll just inline the former in the
latter and stop, which isn't what the user expected
* Regardless of its pragma, we give the default method an
unfolding with an InlineCompulsory source. That means
that it'll be inlined at every use site, notably in
each instance declaration, such as $cop1. This inlining
must happen even though
a) $dmop1 is not saturated in $cop1
b) $cop1 itself has an INLINE pragma
It's vital that $dmop1 *is* inlined in this way, to allow the mutual
recursion between $fooInt and $cop1 to be broken
* To communicate the need for an InlineCompulsory to the desugarer
(which makes the Unfoldings), we use the IsDefaultMethod constructor
in TcSpecPrags.
************************************************************************
* *
\subsection{Error messages}
* *
************************************************************************
-}
instDeclCtxt1 :: LHsType Name -> SDoc
instDeclCtxt1 hs_inst_ty
= inst_decl_ctxt (case unLoc hs_inst_ty of
HsForAllTy _ _ _ _ (L _ ty') -> ppr ty'
_ -> ppr hs_inst_ty) -- Don't expect this
instDeclCtxt2 :: Type -> SDoc
instDeclCtxt2 dfun_ty
= inst_decl_ctxt (ppr (mkClassPred cls tys))
where
(_,_,cls,tys) = tcSplitDFunTy dfun_ty
inst_decl_ctxt :: SDoc -> SDoc
inst_decl_ctxt doc = hang (ptext (sLit "In the instance declaration for"))
2 (quotes doc)
badBootFamInstDeclErr :: SDoc
badBootFamInstDeclErr
= ptext (sLit "Illegal family instance in hs-boot file")
notFamily :: TyCon -> SDoc
notFamily tycon
= vcat [ ptext (sLit "Illegal family instance for") <+> quotes (ppr tycon)
, nest 2 $ parens (ppr tycon <+> ptext (sLit "is not an indexed type family"))]
tooFewParmsErr :: Arity -> SDoc
tooFewParmsErr arity
= ptext (sLit "Family instance has too few parameters; expected") <+>
ppr arity
assocInClassErr :: Located Name -> SDoc
assocInClassErr name
= ptext (sLit "Associated type") <+> quotes (ppr name) <+>
ptext (sLit "must be inside a class instance")
badFamInstDecl :: Located Name -> SDoc
badFamInstDecl tc_name
= vcat [ ptext (sLit "Illegal family instance for") <+>
quotes (ppr tc_name)
, nest 2 (parens $ ptext (sLit "Use TypeFamilies to allow indexed type families")) ]
notOpenFamily :: TyCon -> SDoc
notOpenFamily tc
= ptext (sLit "Illegal instance for closed family") <+> quotes (ppr tc)
|
pparkkin/eta
|
compiler/ETA/TypeCheck/TcInstDcls.hs
|
Haskell
|
bsd-3-clause
| 64,101
|
-- | This module defines 'TriggerEvent', which describes actions that may create
-- new 'Event's that can be triggered from 'IO'.
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE UndecidableInstances #-}
module Reflex.TriggerEvent.Class
( TriggerEvent (..)
) where
import Reflex.Class
import Control.Monad.Reader
import Control.Monad.State
import qualified Control.Monad.State.Strict as Strict
import Control.Monad.Trans.Maybe (MaybeT)
--TODO: Shouldn't have IO hard-coded
-- | 'TriggerEvent' represents actions that can create 'Event's that can be
-- triggered by 'IO' actions.
class Monad m => TriggerEvent t m | m -> t where
-- | Create a triggerable 'Event'. Whenever the resulting function is called,
-- the resulting 'Event' will fire at some point in the future. Note that
-- this may not be synchronous.
newTriggerEvent :: m (Event t a, a -> IO ())
-- | Like 'newTriggerEvent', but the callback itself takes another callback,
-- to be invoked once the requested 'Event' occurrence has finished firing.
-- This allows synchronous operation.
newTriggerEventWithOnComplete :: m (Event t a, a -> IO () -> IO ()) --TODO: This and newTriggerEvent should be unified somehow
-- | Like 'newTriggerEventWithOnComplete', but with setup and teardown. This
-- relatively complex type signature allows any external listeners to be
-- subscribed lazily and then removed whenever the returned 'Event' is no
-- longer being listened to. Note that the setup/teardown may happen multiple
-- times, and there is no guarantee that the teardown will be executed
-- promptly, or even at all, in the case of program termination.
newEventWithLazyTriggerWithOnComplete :: ((a -> IO () -> IO ()) -> IO (IO ())) -> m (Event t a)
instance TriggerEvent t m => TriggerEvent t (ReaderT r m) where
newTriggerEvent = lift newTriggerEvent
newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
instance TriggerEvent t m => TriggerEvent t (StateT s m) where
newTriggerEvent = lift newTriggerEvent
newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
instance TriggerEvent t m => TriggerEvent t (Strict.StateT s m) where
newTriggerEvent = lift newTriggerEvent
newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
instance TriggerEvent t m => TriggerEvent t (MaybeT m) where
newTriggerEvent = lift newTriggerEvent
newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
|
ryantrinkle/reflex
|
src/Reflex/TriggerEvent/Class.hs
|
Haskell
|
bsd-3-clause
| 2,839
|
module Dwarf.Types
( -- * Dwarf information
DwarfInfo(..)
, pprDwarfInfo
, pprAbbrevDecls
-- * Dwarf frame
, DwarfFrame(..), DwarfFrameProc(..), DwarfFrameBlock(..)
, pprDwarfFrame
-- * Utilities
, pprByte
, pprData4'
, pprDwWord
, pprWord
, pprLEBWord
, pprLEBInt
, wordAlign
, sectionOffset
)
where
import Debug
import CLabel
import CmmExpr ( GlobalReg(..) )
import Encoding
import FastString
import Outputable
import Platform
import Reg
import Dwarf.Constants
import Data.Bits
import Data.List ( mapAccumL )
import qualified Data.Map as Map
import Data.Word
import Data.Char
import CodeGen.Platform
-- | Individual dwarf records. Each one will be encoded as an entry in
-- the .debug_info section.
data DwarfInfo
= DwarfCompileUnit { dwChildren :: [DwarfInfo]
, dwName :: String
, dwProducer :: String
, dwCompDir :: String
, dwLineLabel :: LitString }
| DwarfSubprogram { dwChildren :: [DwarfInfo]
, dwName :: String
, dwLabel :: CLabel }
| DwarfBlock { dwChildren :: [DwarfInfo]
, dwLabel :: CLabel
, dwMarker :: CLabel }
-- | Abbreviation codes used for encoding above records in the
-- .debug_info section.
data DwarfAbbrev
= DwAbbrNull -- ^ Pseudo, used for marking the end of lists
| DwAbbrCompileUnit
| DwAbbrSubprogram
| DwAbbrBlock
deriving (Eq, Enum)
-- | Generate assembly for the given abbreviation code
pprAbbrev :: DwarfAbbrev -> SDoc
pprAbbrev = pprLEBWord . fromIntegral . fromEnum
-- | Abbreviation declaration. This explains the binary encoding we
-- use for representing @DwarfInfo@.
pprAbbrevDecls :: Bool -> SDoc
pprAbbrevDecls haveDebugLine =
let mkAbbrev abbr tag chld flds =
let fld (tag, form) = pprLEBWord tag $$ pprLEBWord form
in pprAbbrev abbr $$ pprLEBWord tag $$ pprByte chld $$
vcat (map fld flds) $$ pprByte 0 $$ pprByte 0
in dwarfAbbrevSection $$
ptext dwarfAbbrevLabel <> colon $$
mkAbbrev DwAbbrCompileUnit dW_TAG_compile_unit dW_CHILDREN_yes
([ (dW_AT_name, dW_FORM_string)
, (dW_AT_producer, dW_FORM_string)
, (dW_AT_language, dW_FORM_data4)
, (dW_AT_comp_dir, dW_FORM_string)
, (dW_AT_use_UTF8, dW_FORM_flag)
] ++
(if haveDebugLine
then [ (dW_AT_stmt_list, dW_FORM_data4) ]
else [])) $$
mkAbbrev DwAbbrSubprogram dW_TAG_subprogram dW_CHILDREN_yes
[ (dW_AT_name, dW_FORM_string)
, (dW_AT_MIPS_linkage_name, dW_FORM_string)
, (dW_AT_external, dW_FORM_flag)
, (dW_AT_low_pc, dW_FORM_addr)
, (dW_AT_high_pc, dW_FORM_addr)
, (dW_AT_frame_base, dW_FORM_block1)
] $$
mkAbbrev DwAbbrBlock dW_TAG_lexical_block dW_CHILDREN_yes
[ (dW_AT_name, dW_FORM_string)
, (dW_AT_low_pc, dW_FORM_addr)
, (dW_AT_high_pc, dW_FORM_addr)
] $$
pprByte 0
-- | Generate assembly for DWARF data
pprDwarfInfo :: Bool -> DwarfInfo -> SDoc
pprDwarfInfo haveSrc d
= pprDwarfInfoOpen haveSrc d $$
vcat (map (pprDwarfInfo haveSrc) (dwChildren d)) $$
pprDwarfInfoClose
-- | Prints assembler data corresponding to DWARF info records. Note
-- that the binary format of this is paramterized in @abbrevDecls@ and
-- has to be kept in synch.
pprDwarfInfoOpen :: Bool -> DwarfInfo -> SDoc
pprDwarfInfoOpen haveSrc (DwarfCompileUnit _ name producer compDir lineLbl) =
pprAbbrev DwAbbrCompileUnit
$$ pprString name
$$ pprString producer
$$ pprData4 dW_LANG_Haskell
$$ pprString compDir
$$ pprFlag True -- use UTF8
$$ if haveSrc
then sectionOffset lineLbl dwarfLineLabel
else empty
pprDwarfInfoOpen _ (DwarfSubprogram _ name label) = sdocWithDynFlags $ \df ->
pprAbbrev DwAbbrSubprogram
$$ pprString name
$$ pprString (renderWithStyle df (ppr label) (mkCodeStyle CStyle))
$$ pprFlag (externallyVisibleCLabel label)
$$ pprWord (ppr label)
$$ pprWord (ppr $ mkAsmTempEndLabel label)
$$ pprByte 1
$$ pprByte dW_OP_call_frame_cfa
pprDwarfInfoOpen _ (DwarfBlock _ label marker) = sdocWithDynFlags $ \df ->
pprAbbrev DwAbbrBlock
$$ pprString (renderWithStyle df (ppr label) (mkCodeStyle CStyle))
$$ pprWord (ppr marker)
$$ pprWord (ppr $ mkAsmTempEndLabel marker)
-- | Close a DWARF info record with children
pprDwarfInfoClose :: SDoc
pprDwarfInfoClose = pprAbbrev DwAbbrNull
-- | Information about unwind instructions for a procedure. This
-- corresponds to a "Common Information Entry" (CIE) in DWARF.
data DwarfFrame
= DwarfFrame
{ dwCieLabel :: CLabel
, dwCieInit :: UnwindTable
, dwCieProcs :: [DwarfFrameProc]
}
-- | Unwind instructions for an individual procedure. Corresponds to a
-- "Frame Description Entry" (FDE) in DWARF.
data DwarfFrameProc
= DwarfFrameProc
{ dwFdeProc :: CLabel
, dwFdeHasInfo :: Bool
, dwFdeBlocks :: [DwarfFrameBlock]
-- ^ List of blocks. Order must match asm!
}
-- | Unwind instructions for a block. Will become part of the
-- containing FDE.
data DwarfFrameBlock
= DwarfFrameBlock
{ dwFdeBlock :: CLabel
, dwFdeBlkHasInfo :: Bool
, dwFdeUnwind :: UnwindTable
}
-- | Header for the .debug_frame section. Here we emit the "Common
-- Information Entry" record that etablishes general call frame
-- parameters and the default stack layout.
pprDwarfFrame :: DwarfFrame -> SDoc
pprDwarfFrame DwarfFrame{dwCieLabel=cieLabel,dwCieInit=cieInit,dwCieProcs=procs}
= sdocWithPlatform $ \plat ->
let cieStartLabel= mkAsmTempDerivedLabel cieLabel (fsLit "_start")
cieEndLabel = mkAsmTempEndLabel cieLabel
length = ppr cieEndLabel <> char '-' <> ppr cieStartLabel
spReg = dwarfGlobalRegNo plat Sp
retReg = dwarfReturnRegNo plat
wordSize = platformWordSize plat
pprInit (g, uw) = pprSetUnwind plat g (Nothing, uw)
in vcat [ ppr cieLabel <> colon
, pprData4' length -- Length of CIE
, ppr cieStartLabel <> colon
, pprData4' (ptext (sLit "-1"))
-- Common Information Entry marker (-1 = 0xf..f)
, pprByte 3 -- CIE version (we require DWARF 3)
, pprByte 0 -- Augmentation (none)
, pprByte 1 -- Code offset multiplicator
, pprByte (128-fromIntegral wordSize)
-- Data offset multiplicator
-- (stacks grow down => "-w" in signed LEB128)
, pprByte retReg -- virtual register holding return address
] $$
-- Initial unwind table
vcat (map pprInit $ Map.toList cieInit) $$
vcat [ -- RET = *CFA
pprByte (dW_CFA_offset+retReg)
, pprByte 0
-- Sp' = CFA
-- (we need to set this manually as our Sp register is
-- often not the architecture's default stack register)
, pprByte dW_CFA_val_offset
, pprLEBWord (fromIntegral spReg)
, pprLEBWord 0
] $$
wordAlign $$
ppr cieEndLabel <> colon $$
-- Procedure unwind tables
vcat (map (pprFrameProc cieLabel cieInit) procs)
-- | Writes a "Frame Description Entry" for a procedure. This consists
-- mainly of referencing the CIE and writing state machine
-- instructions to describe how the frame base (CFA) changes.
pprFrameProc :: CLabel -> UnwindTable -> DwarfFrameProc -> SDoc
pprFrameProc frameLbl initUw (DwarfFrameProc procLbl hasInfo blocks)
= let fdeLabel = mkAsmTempDerivedLabel procLbl (fsLit "_fde")
fdeEndLabel = mkAsmTempDerivedLabel procLbl (fsLit "_fde_end")
procEnd = mkAsmTempEndLabel procLbl
ifInfo str = if hasInfo then text str else empty
-- see [Note: Info Offset]
in vcat [ pprData4' (ppr fdeEndLabel <> char '-' <> ppr fdeLabel)
, ppr fdeLabel <> colon
, pprData4' (ppr frameLbl <> char '-' <>
ptext dwarfFrameLabel) -- Reference to CIE
, pprWord (ppr procLbl <> ifInfo "-1") -- Code pointer
, pprWord (ppr procEnd <> char '-' <>
ppr procLbl <> ifInfo "+1") -- Block byte length
] $$
vcat (snd $ mapAccumL pprFrameBlock initUw blocks) $$
wordAlign $$
ppr fdeEndLabel <> colon
-- | Generates unwind information for a block. We only generate
-- instructions where unwind information actually changes. This small
-- optimisations saves a lot of space, as subsequent blocks often have
-- the same unwind information.
pprFrameBlock :: UnwindTable -> DwarfFrameBlock -> (UnwindTable, SDoc)
pprFrameBlock oldUws (DwarfFrameBlock blockLbl hasInfo uws)
| uws == oldUws
= (oldUws, empty)
| otherwise
= (,) uws $ sdocWithPlatform $ \plat ->
let lbl = ppr blockLbl <> if hasInfo then text "-1" else empty
-- see [Note: Info Offset]
isChanged g v | old == Just v = Nothing
| otherwise = Just (old, v)
where old = Map.lookup g oldUws
changed = Map.toList $ Map.mapMaybeWithKey isChanged uws
died = Map.toList $ Map.difference oldUws uws
in pprByte dW_CFA_set_loc $$ pprWord lbl $$
vcat (map (uncurry $ pprSetUnwind plat) changed) $$
vcat (map (pprUndefUnwind plat . fst) died)
-- [Note: Info Offset]
--
-- GDB was pretty much written with C-like programs in mind, and as a
-- result they assume that once you have a return address, it is a
-- good idea to look at (PC-1) to unwind further - as that's where the
-- "call" instruction is supposed to be.
--
-- Now on one hand, code generated by GHC looks nothing like what GDB
-- expects, and in fact going up from a return pointer is guaranteed
-- to land us inside an info table! On the other hand, that actually
-- gives us some wiggle room, as we expect IP to never *actually* end
-- up inside the info table, so we can "cheat" by putting whatever GDB
-- expects to see there. This is probably pretty safe, as GDB cannot
-- assume (PC-1) to be a valid code pointer in the first place - and I
-- have seen no code trying to correct this.
--
-- Note that this will not prevent GDB from failing to look-up the
-- correct function name for the frame, as that uses the symbol table,
-- which we can not manipulate as easily.
-- | Get DWARF register ID for a given GlobalReg
dwarfGlobalRegNo :: Platform -> GlobalReg -> Word8
dwarfGlobalRegNo p = maybe 0 (dwarfRegNo p . RegReal) . globalRegMaybe p
-- | Generate code for setting the unwind information for a register,
-- optimized using its known old value in the table. Note that "Sp" is
-- special: We see it as synonym for the CFA.
pprSetUnwind :: Platform -> GlobalReg -> (Maybe UnwindExpr, UnwindExpr) -> SDoc
pprSetUnwind _ Sp (Just (UwReg s _), UwReg s' o') | s == s'
= if o' >= 0
then pprByte dW_CFA_def_cfa_offset $$ pprLEBWord (fromIntegral o')
else pprByte dW_CFA_def_cfa_offset_sf $$ pprLEBInt o'
pprSetUnwind plat Sp (_, UwReg s' o')
= if o' >= 0
then pprByte dW_CFA_def_cfa $$
pprLEBWord (fromIntegral $ dwarfGlobalRegNo plat s') $$
pprLEBWord (fromIntegral o')
else pprByte dW_CFA_def_cfa_sf $$
pprLEBWord (fromIntegral $ dwarfGlobalRegNo plat s') $$
pprLEBInt o'
pprSetUnwind _ Sp (_, uw)
= pprByte dW_CFA_def_cfa_expression $$ pprUnwindExpr False uw
pprSetUnwind plat g (_, UwDeref (UwReg Sp o))
| o < 0 && ((-o) `mod` platformWordSize plat) == 0 -- expected case
= pprByte (dW_CFA_offset + dwarfGlobalRegNo plat g) $$
pprLEBWord (fromIntegral ((-o) `div` platformWordSize plat))
| otherwise
= pprByte dW_CFA_offset_extended_sf $$
pprLEBWord (fromIntegral (dwarfGlobalRegNo plat g)) $$
pprLEBInt o
pprSetUnwind plat g (_, UwDeref uw)
= pprByte dW_CFA_expression $$
pprLEBWord (fromIntegral (dwarfGlobalRegNo plat g)) $$
pprUnwindExpr True uw
pprSetUnwind plat g (_, uw)
= pprByte dW_CFA_val_expression $$
pprLEBWord (fromIntegral (dwarfGlobalRegNo plat g)) $$
pprUnwindExpr True uw
-- | Generates a DWARF expression for the given unwind expression. If
-- @spIsCFA@ is true, we see @Sp@ as the frame base CFA where it gets
-- mentioned.
pprUnwindExpr :: Bool -> UnwindExpr -> SDoc
pprUnwindExpr spIsCFA expr
= sdocWithPlatform $ \plat ->
let ppr (UwConst i)
| i >= 0 && i < 32 = pprByte (dW_OP_lit0 + fromIntegral i)
| otherwise = pprByte dW_OP_consts $$ pprLEBInt i -- lazy...
ppr (UwReg Sp i) | spIsCFA
= if i == 0
then pprByte dW_OP_call_frame_cfa
else ppr (UwPlus (UwReg Sp 0) (UwConst i))
ppr (UwReg g i) = pprByte (dW_OP_breg0+dwarfGlobalRegNo plat g) $$
pprLEBInt i
ppr (UwDeref u) = ppr u $$ pprByte dW_OP_deref
ppr (UwPlus u1 u2) = ppr u1 $$ ppr u2 $$ pprByte dW_OP_plus
ppr (UwMinus u1 u2) = ppr u1 $$ ppr u2 $$ pprByte dW_OP_minus
ppr (UwTimes u1 u2) = ppr u1 $$ ppr u2 $$ pprByte dW_OP_mul
in ptext (sLit "\t.byte 1f-.-1") $$
ppr expr $$
ptext (sLit "1:")
-- | Generate code for re-setting the unwind information for a
-- register to "undefined"
pprUndefUnwind :: Platform -> GlobalReg -> SDoc
pprUndefUnwind _ Sp = panic "pprUndefUnwind Sp" -- should never happen
pprUndefUnwind plat g = pprByte dW_CFA_undefined $$
pprLEBWord (fromIntegral $ dwarfGlobalRegNo plat g)
-- | Align assembly at (machine) word boundary
wordAlign :: SDoc
wordAlign = sdocWithPlatform $ \plat ->
ptext (sLit "\t.align ") <> case platformOS plat of
OSDarwin -> case platformWordSize plat of
8 -> text "3"
4 -> text "2"
_other -> error "wordAlign: Unsupported word size!"
_other -> ppr (platformWordSize plat)
-- | Assembly for a single byte of constant DWARF data
pprByte :: Word8 -> SDoc
pprByte x = ptext (sLit "\t.byte ") <> ppr (fromIntegral x :: Word)
-- | Assembly for a constant DWARF flag
pprFlag :: Bool -> SDoc
pprFlag f = pprByte (if f then 0xff else 0x00)
-- | Assembly for 4 bytes of dynamic DWARF data
pprData4' :: SDoc -> SDoc
pprData4' x = ptext (sLit "\t.long ") <> x
-- | Assembly for 4 bytes of constant DWARF data
pprData4 :: Word -> SDoc
pprData4 = pprData4' . ppr
-- | Assembly for a DWARF word of dynamic data. This means 32 bit, as
-- we are generating 32 bit DWARF.
pprDwWord :: SDoc -> SDoc
pprDwWord = pprData4'
-- | Assembly for a machine word of dynamic data. Depends on the
-- architecture we are currently generating code for.
pprWord :: SDoc -> SDoc
pprWord s = (<> s) . sdocWithPlatform $ \plat ->
case platformWordSize plat of
4 -> ptext (sLit "\t.long ")
8 -> ptext (sLit "\t.quad ")
n -> panic $ "pprWord: Unsupported target platform word length " ++
show n ++ "!"
-- | Prints a number in "little endian base 128" format. The idea is
-- to optimize for small numbers by stopping once all further bytes
-- would be 0. The highest bit in every byte signals whether there
-- are further bytes to read.
pprLEBWord :: Word -> SDoc
pprLEBWord x | x < 128 = pprByte (fromIntegral x)
| otherwise = pprByte (fromIntegral $ 128 .|. (x .&. 127)) $$
pprLEBWord (x `shiftR` 7)
-- | Same as @pprLEBWord@, but for a signed number
pprLEBInt :: Int -> SDoc
pprLEBInt x | x >= -64 && x < 64
= pprByte (fromIntegral (x .&. 127))
| otherwise = pprByte (fromIntegral $ 128 .|. (x .&. 127)) $$
pprLEBInt (x `shiftR` 7)
-- | Generates a dynamic null-terminated string. If required the
-- caller needs to make sure that the string is escaped properly.
pprString' :: SDoc -> SDoc
pprString' str = ptext (sLit "\t.asciz \"") <> str <> char '"'
-- | Generate a string constant. We take care to escape the string.
pprString :: String -> SDoc
pprString str
= pprString' $ hcat $ map escapeChar $
if utf8EncodedLength str == length str
then str
else map (chr . fromIntegral) $ bytesFS $ mkFastString str
-- | Escape a single non-unicode character
escapeChar :: Char -> SDoc
escapeChar '\\' = ptext (sLit "\\\\")
escapeChar '\"' = ptext (sLit "\\\"")
escapeChar '\n' = ptext (sLit "\\n")
escapeChar c
| isAscii c && isPrint c && c /= '?' -- prevents trigraph warnings
= char c
| otherwise
= char '\\' <> char (intToDigit (ch `div` 64)) <>
char (intToDigit ((ch `div` 8) `mod` 8)) <>
char (intToDigit (ch `mod` 8))
where ch = ord c
-- | Generate an offset into another section. This is tricky because
-- this is handled differently depending on platform: Mac Os expects
-- us to calculate the offset using assembler arithmetic. Linux expects
-- us to just reference the target directly, and will figure out on
-- their own that we actually need an offset. Finally, Windows has
-- a special directive to refer to relative offsets. Fun.
sectionOffset :: LitString -> LitString -> SDoc
sectionOffset target section = sdocWithPlatform $ \plat ->
case platformOS plat of
OSDarwin -> pprDwWord (ptext target <> char '-' <> ptext section)
OSMinGW32 -> text "\t.secrel32 " <> ptext target
_other -> pprDwWord (ptext target)
|
urbanslug/ghc
|
compiler/nativeGen/Dwarf/Types.hs
|
Haskell
|
bsd-3-clause
| 17,462
|
{-|
Module : Idris.Elab.Type
Description : Code to elaborate types.
Copyright :
License : BSD3
Maintainer : The Idris Community.
-}
{-# LANGUAGE PatternGuards #-}
module Idris.Elab.Type (
buildType, elabType, elabType'
, elabPostulate, elabExtern
) where
import Idris.AbsSyntax
import Idris.ASTUtils
import Idris.DSL
import Idris.Error
import Idris.Delaborate
import Idris.Imports
import Idris.Elab.Term
import Idris.Coverage
import Idris.DataOpts
import Idris.Providers
import Idris.Primitives
import Idris.Inliner
import Idris.PartialEval
import Idris.DeepSeq
import Idris.Output (iputStrLn, pshow, iWarn, sendHighlighting)
import IRTS.Lang
import Idris.Elab.Utils
import Idris.Elab.Value
import Idris.Core.TT
import Idris.Core.Elaborate hiding (Tactic(..))
import Idris.Core.Evaluate
import Idris.Core.Execute
import Idris.Core.Typecheck
import Idris.Core.CaseTree
import Idris.Docstrings (Docstring)
import Prelude hiding (id, (.))
import Control.Category
import Control.Applicative hiding (Const)
import Control.DeepSeq
import Control.Monad
import Control.Monad.State.Strict as State
import Data.List
import Data.Maybe
import Debug.Trace
import qualified Data.Traversable as Traversable
import qualified Data.Map as Map
import qualified Data.Set as S
import qualified Data.Text as T
import Data.Char(isLetter, toLower)
import Data.List.Split (splitOn)
import Util.Pretty(pretty, text)
buildType :: ElabInfo
-> SyntaxInfo
-> FC
-> FnOpts
-> Name
-> PTerm
-> Idris (Type, Type, PTerm, [(Int, Name)])
buildType info syn fc opts n ty' = do
ctxt <- getContext
i <- getIState
logElab 2 $ show n ++ " pre-type " ++ showTmImpls ty' ++ show (no_imp syn)
ty' <- addUsingConstraints syn fc ty'
ty' <- addUsingImpls syn n fc ty'
let ty = addImpl (imp_methods syn) i ty'
logElab 5 $ show n ++ " type pre-addimpl " ++ showTmImpls ty'
logElab 5 $ "with methods " ++ show (imp_methods syn)
logElab 2 $ show n ++ " type " ++ show (using syn) ++ "\n" ++ showTmImpls ty
((ElabResult tyT' defer is ctxt' newDecls highlights newGName, est), log) <-
tclift $ elaborate (constraintNS info) ctxt (idris_datatypes i) (idris_name i) n (TType (UVal 0)) initEState
(errAt "type of " n Nothing
(erunAux fc (build i info ETyDecl [] n ty)))
displayWarnings est
setContext ctxt'
processTacticDecls info newDecls
sendHighlighting highlights
updateIState $ \i -> i { idris_name = newGName }
let tyT = patToImp tyT'
logElab 3 $ show ty ++ "\nElaborated: " ++ show tyT'
ds <- checkAddDef True False info fc iderr True defer
-- if the type is not complete, note that we'll need to infer
-- things later (for solving metavariables)
when (length ds > length is) -- more deferred than case blocks
$ addTyInferred n
mapM_ (elabCaseBlock info opts) is
ctxt <- getContext
logElab 5 "Rechecking"
logElab 6 (show tyT)
logElab 10 $ "Elaborated to " ++ showEnvDbg [] tyT
(cty, ckind) <- recheckC (constraintNS info) fc id [] tyT
-- record the implicit and inaccessible arguments
i <- getIState
let (inaccData, impls) = unzip $ getUnboundImplicits i cty ty
let inacc = inaccessibleImps 0 cty inaccData
logElab 3 $ show n ++ ": inaccessible arguments: " ++ show inacc ++
" from " ++ show cty ++ "\n" ++ showTmImpls ty
putIState $ i { idris_implicits = addDef n impls (idris_implicits i) }
logElab 3 ("Implicit " ++ show n ++ " " ++ show impls)
addIBC (IBCImp n)
-- Add the names referenced to the call graph, and check we're not
-- referring to anything less visible
-- In particular, a public/export type can not refer to anything
-- private, but can refer to any public/export
let refs = freeNames cty
nvis <- getFromHideList n
case nvis of
Nothing -> return ()
Just acc -> mapM_ (checkVisibility fc n (max Frozen acc) acc) refs
addCalls n refs
addIBC (IBCCG n)
when (Constructor `notElem` opts) $ do
let pnames = getParamsInType i [] impls cty
let fninfo = FnInfo (param_pos 0 pnames cty)
setFnInfo n fninfo
addIBC (IBCFnInfo n fninfo)
return (cty, ckind, ty, inacc)
where
patToImp (Bind n (PVar t) sc) = Bind n (Pi Nothing t (TType (UVar [] 0))) (patToImp sc)
patToImp (Bind n b sc) = Bind n b (patToImp sc)
patToImp t = t
param_pos i ns (Bind n (Pi _ t _) sc)
| n `elem` ns = i : param_pos (i + 1) ns sc
| otherwise = param_pos (i + 1) ns sc
param_pos i ns t = []
-- | Elaborate a top-level type declaration - for example, "foo : Int -> Int".
elabType :: ElabInfo
-> SyntaxInfo
-> Docstring (Either Err PTerm)
-> [(Name, Docstring (Either Err PTerm))]
-> FC
-> FnOpts
-> Name
-> FC -- ^ The precise location of the name
-> PTerm
-> Idris Type
elabType = elabType' False
elabType' :: Bool -- normalise it
-> ElabInfo
-> SyntaxInfo
-> Docstring (Either Err PTerm)
-> [(Name, Docstring (Either Err PTerm))]
-> FC
-> FnOpts
-> Name
-> FC
-> PTerm
-> Idris Type
elabType' norm info syn doc argDocs fc opts n nfc ty' = {- let ty' = piBind (params info) ty_in
n = liftname info n_in in -}
do checkUndefined fc n
(cty, _, ty, inacc) <- buildType info syn fc opts n ty'
addStatics n cty ty
let nty = cty -- normalise ctxt [] cty
-- if the return type is something coinductive, freeze the definition
ctxt <- getContext
logElab 2 $ "Rechecked to " ++ show nty
let nty' = normalise ctxt [] nty
logElab 2 $ "Rechecked to " ++ show nty'
-- Add function name to internals (used for making :addclause know
-- the name unambiguously)
i <- getIState
rep <- useREPL
when rep $ do
addInternalApp (fc_fname fc) (fst . fc_start $ fc) (PTyped (PRef fc [] n) ty') -- (mergeTy ty' (delab i nty')) -- TODO: Should use span instead of line and filename?
addIBC (IBCLineApp (fc_fname fc) (fst . fc_start $ fc) (PTyped (PRef fc [] n) ty')) -- (mergeTy ty' (delab i nty')))
let (fam, _) = unApply (getRetTy nty')
let corec = case fam of
P _ rcty _ -> case lookupCtxt rcty (idris_datatypes i) of
[TI _ True _ _ _] -> True
_ -> False
_ -> False
-- Productivity checking now via checking for guarded 'Delay'
let opts' = opts -- if corec then (Coinductive : opts) else opts
let usety = if norm then nty' else nty
ds <- checkDef info fc iderr True [(n, (-1, Nothing, usety, []))]
addIBC (IBCDef n)
addDefinedName n
let ds' = map (\(n, (i, top, fam, ns)) -> (n, (i, top, fam, ns, True, True))) ds
addDeferred ds'
setFlags n opts'
checkDocs fc argDocs ty
doc' <- elabDocTerms info doc
argDocs' <- mapM (\(n, d) -> do d' <- elabDocTerms info d
return (n, d')) argDocs
addDocStr n doc' argDocs'
addIBC (IBCDoc n)
addIBC (IBCFlags n opts')
fputState (opt_inaccessible . ist_optimisation n) inacc
addIBC (IBCOpt n)
when (Implicit `elem` opts') $ do addCoercion n
addIBC (IBCCoercion n)
when (AutoHint `elem` opts') $
case fam of
P _ tyn _ -> do addAutoHint tyn n
addIBC (IBCAutoHint tyn n)
t -> ifail "Hints must return a data or record type"
-- If the function is declared as an error handler and the language
-- extension is enabled, then add it to the list of error handlers.
errorReflection <- fmap (elem ErrorReflection . idris_language_extensions) getIState
when (ErrorHandler `elem` opts) $ do
if errorReflection
then
-- Check that the declared type is the correct type for an error handler:
-- handler : List (TTName, TT) -> Err -> ErrorReport - for now no ctxt
if tyIsHandler nty'
then do i <- getIState
putIState $ i { idris_errorhandlers = idris_errorhandlers i ++ [n] }
addIBC (IBCErrorHandler n)
else ifail $ "The type " ++ show nty' ++ " is invalid for an error handler"
else ifail "Error handlers can only be defined when the ErrorReflection language extension is enabled."
-- Send highlighting information about the name being declared
sendHighlighting [(nfc, AnnName n Nothing Nothing Nothing)]
-- if it's an export list type, make a note of it
case (unApply usety) of
(P _ ut _, _)
| ut == ffiexport -> do addIBC (IBCExport n)
addExport n
_ -> return ()
return usety
where
-- for making an internalapp, we only want the explicit ones, and don't
-- want the parameters, so just take the arguments which correspond to the
-- user declared explicit ones
mergeTy (PPi e n fc ty sc) (PPi e' n' _ _ sc')
| e == e' = PPi e n fc ty (mergeTy sc sc')
| otherwise = mergeTy sc sc'
mergeTy _ sc = sc
ffiexport = sNS (sUN "FFI_Export") ["FFI_Export"]
err = txt "Err"
maybe = txt "Maybe"
lst = txt "List"
errrep = txt "ErrorReportPart"
tyIsHandler (Bind _ (Pi _ (P _ (NS (UN e) ns1) _) _)
(App _ (P _ (NS (UN m) ns2) _)
(App _ (P _ (NS (UN l) ns3) _)
(P _ (NS (UN r) ns4) _))))
| e == err && m == maybe && l == lst && r == errrep
, ns1 == map txt ["Errors","Reflection","Language"]
, ns2 == map txt ["Maybe", "Prelude"]
, ns3 == map txt ["List", "Prelude"]
, ns4 == map txt ["Reflection","Language"] = True
tyIsHandler _ = False
elabPostulate :: ElabInfo -> SyntaxInfo -> Docstring (Either Err PTerm) ->
FC -> FC -> FnOpts -> Name -> PTerm -> Idris ()
elabPostulate info syn doc fc nfc opts n ty = do
elabType info syn doc [] fc opts n NoFC ty
putIState . (\ist -> ist{ idris_postulates = S.insert n (idris_postulates ist) }) =<< getIState
addIBC (IBCPostulate n)
sendHighlighting [(nfc, AnnName n (Just PostulateOutput) Nothing Nothing)]
-- remove it from the deferred definitions list
solveDeferred fc n
elabExtern :: ElabInfo -> SyntaxInfo -> Docstring (Either Err PTerm) ->
FC -> FC -> FnOpts -> Name -> PTerm -> Idris ()
elabExtern info syn doc fc nfc opts n ty = do
cty <- elabType info syn doc [] fc opts n NoFC ty
ist <- getIState
let arity = length (getArgTys (normalise (tt_ctxt ist) [] cty))
putIState . (\ist -> ist{ idris_externs = S.insert (n, arity) (idris_externs ist) }) =<< getIState
addIBC (IBCExtern (n, arity))
-- remove it from the deferred definitions list
solveDeferred fc n
|
ozgurakgun/Idris-dev
|
src/Idris/Elab/Type.hs
|
Haskell
|
bsd-3-clause
| 11,785
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.