code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE CPP, BangPatterns #-}
{-# OPTIONS_GHC -Wall -fno-warn-name-shadowing #-}
module Main ( main, test {-, maxDistances -} ) where
import Prelude
import System.Environment
import Data.Array.Accelerate as A
import Data.Array.Accelerate.Interpreter
-- <<Graph
type Weight = Int32
type Graph = Array DIM2 Weight
-- >>
-- -----------------------------------------------------------------------------
-- shortestPaths
-- <<shortestPaths
shortestPaths :: Graph -> Graph
shortestPaths g0 = run (shortestPathsAcc n (use g0))
where
Z :. _ :. n = arrayShape g0
-- >>
-- <<shortestPathsAcc
shortestPathsAcc :: Int -> Acc Graph -> Acc Graph
shortestPathsAcc n g0 = foldl1 (>->) steps g0 -- <3>
where
steps :: [ Acc Graph -> Acc Graph ] -- <1>
steps = [ step (unit (constant k)) | k <- [0 .. n-1] ] -- <2>
-- >>
-- <<step
step :: Acc (Scalar Int) -> Acc Graph -> Acc Graph
step k g = generate (shape g) sp -- <1>
where
k' = the k -- <2>
sp :: Exp DIM2 -> Exp Weight
sp ix = let
(Z :. i :. j) = unlift ix -- <3>
in
A.min (g ! (index2 i j)) -- <4>
(g ! (index2 i k') + g ! (index2 k' j))
-- >>
-- -----------------------------------------------------------------------------
-- Testing
-- <<inf
inf :: Weight
inf = 999
-- >>
testGraph :: Graph
testGraph = toAdjMatrix $
[[ 0, inf, inf, 13, inf, inf],
[inf, 0, inf, inf, 4, 9],
[ 11, inf, 0, inf, inf, inf],
[inf, 3, inf, 0, inf, 7],
[ 15, 5, inf, 1, 0, inf],
[ 11, inf, inf, 14, inf, 0]]
-- correct result:
expectedResult :: Graph
expectedResult = toAdjMatrix $
[[0, 16, inf, 13, 20, 20],
[19, 0, inf, 5, 4, 9],
[11, 27, 0, 24, 31, 31],
[18, 3, inf, 0, 7, 7],
[15, 4, inf, 1, 0, 8],
[11, 17, inf, 14, 21, 0] ]
test :: Bool
test = toList (shortestPaths testGraph) == toList expectedResult
toAdjMatrix :: [[Weight]] -> Graph
toAdjMatrix xs = A.fromList (Z :. k :. k) (concat xs)
where k = length xs
main :: IO ()
main = do
(n:_) <- fmap (fmap read) getArgs
print (run (let g :: Acc Graph
g = generate (constant (Z:.n:.n) :: Exp DIM2) f
f :: Exp DIM2 -> Exp Weight
f ix = let i,j :: Exp Int
Z:.i:.j = unlift ix
in
A.fromIntegral j +
A.fromIntegral i * constant (Prelude.fromIntegral n)
in
A.foldAll (+) (constant 0) (shortestPathsAcc n g)))
|
mono0926/ParallelConcurrentHaskell
|
fwaccel.hs
|
bsd-3-clause
| 2,783 | 0 | 21 | 1,006 | 975 | 550 | 425 | 58 | 1 |
module Applicatives where
import Control.Applicative
import Data.List (elemIndex)
import Data.Monoid
import Test.QuickCheck
import Test.QuickCheck.Checkers
import Test.QuickCheck.Classes
added :: Maybe Integer
added = (+3) <$> lookup 3 (zip [1, 2, 3] [4, 5, 6])
y' :: Maybe Integer
y' = lookup 3 $ zip [1, 2, 3] [4, 5, 6]
z :: Maybe Integer
z = lookup 2 $ zip [1, 2, 3] [4, 5, 6]
tupled :: Maybe (Integer, Integer)
tupled = (,) <$> y' <*> z
x :: Maybe Int
x = elemIndex 3 [1..5]
y :: Maybe Int
y = elemIndex 4 [1..5]
max' :: Int -> Int -> Int
max' = max
maxed :: Maybe Int
maxed = max' <$> x <*> y
xs = [1..3]
ys = [4..6]
x' :: Maybe Integer
x' = lookup 3 $ zip xs ys
y'' :: Maybe Integer
y'' = lookup 2 $ zip xs ys
summed :: Maybe Integer
summed = sum <$> ((,) <$> x' <*> y'')
newtype Identity a = Identity a deriving (Eq, Ord, Show)
instance Functor Identity where
fmap f (Identity a) = Identity $ f a
instance Applicative Identity where
pure = Identity
(Identity f) <*> (Identity a) = Identity $ f a
newtype Constant a b = Constant { getConstant :: a } deriving Show
instance Functor (Constant a) where
fmap _ (Constant a) = Constant a
instance Monoid a => Applicative (Constant a) where
pure _ = Constant mempty
(Constant a) <*> (Constant b) = Constant $ a <> b
validateLength :: Int -> String -> Maybe String
validateLength maxLen s =
if length s > maxLen then Nothing else Just s
newtype Name = Name String deriving (Eq, Show)
newtype Address = Address String deriving (Eq, Show)
mkName :: String -> Maybe Name
mkName s = Name <$> validateLength 25 s
mkAddress :: String -> Maybe Address
mkAddress a = Address <$> validateLength 100 a
data Person = Person Name Address deriving (Eq, Show)
mkPerson :: String -> String -> Maybe Person
mkPerson n a = Person <$> mkName n <*> mkAddress a
xx = const <$> Just "Hello" <*> pure "World"
yy =
(,,,)
<$> Just 90
<*> Just 10
<*> Just "Tierness"
<*> Just [1, 2, 3]
-- Lows
data Bull
= Fools
| Twoo
deriving (Eq, Show)
instance Arbitrary Bull where
arbitrary =
frequency [ (1, return Fools)
, (1, return Twoo) ]
instance Monoid Bull where
mempty = Fools
mappend _ _ = Fools
instance EqProp Bull where (=-=) = eq
-- ZipList
instance Monoid a => Monoid (ZipList a) where
mempty = pure mempty
mappend = liftA2 mappend
instance Arbitrary a => Arbitrary (ZipList a) where
arbitrary = ZipList <$> arbitrary
instance Arbitrary a => Arbitrary (Sum a) where
arbitrary = Sum <$> arbitrary
instance Eq a => EqProp (ZipList a) where (=-=) = eq
-- List
data List a
= Nil
| Cons a (List a)
deriving (Eq, Show)
instance Functor List where
fmap _ Nil = Nil
fmap f (Cons a l) = Cons (f a) (fmap f l)
append :: List a -> List a -> List a
append Nil ys = ys
append (Cons x xs) ys = Cons x $ xs `append` ys
fold :: (a -> b -> b) -> b -> List a -> b
fold _ b Nil = b
fold f b (Cons h t) = f h (fold f b t)
concat' :: List (List a) -> List a
concat' = fold append Nil
flatMap :: (a -> List b) -> List a -> List b
flatMap f as = concat' (fmap f as)
zip' :: List a -> List b -> List (a, b)
zip' Nil _ = Nil
zip' _ Nil = Nil
zip' (Cons x xs) (Cons y ys) = Cons (x, y) (zip' xs ys)
instance Applicative List where
pure a = Cons a Nil
Nil <*> _ = Nil
_ <*> Nil = Nil
(<*>) fs as = flatMap (`fmap` as) fs
instance Arbitrary a => Arbitrary (List a) where
arbitrary = do
a <- arbitrary
elements [Nil, Cons a Nil]
instance Eq a => EqProp (List a) where (=-=) = eq
newtype ZipList' a = ZipList' (List a) deriving (Eq, Show)
instance Functor ZipList' where
fmap f (ZipList' xs) = ZipList' $ fmap f xs
instance Applicative ZipList' where
pure a = ZipList' $ Cons a Nil
ZipList' l <*> ZipList' l' =
ZipList' (fmap (\(f, x) -> f x) (zip' l l'))
take' :: Int -> List a -> List a
take' _ Nil = Nil
take' 0 _ = Nil
take' n (Cons x t) = Cons x (take' (n - 1) t)
instance Eq a => EqProp (ZipList' a) where
xs =-= ys = xs' `eq` ys'
where xs' = let (ZipList' l) = xs in take' 3000 l
ys' = let (ZipList' l) = ys in take' 3000 l
instance Arbitrary a => Arbitrary (ZipList' a) where
arbitrary = ZipList' <$> arbitrary
-- Variations of Either
data Sum' a b
= First' a
| Second' b
deriving (Eq, Show)
data Validation e a
= Error' e
| Success' a
deriving (Eq, Show)
instance Functor (Sum' a) where
fmap _ (First' a) = First' a
fmap f (Second' b) = Second' (f b)
instance Applicative (Sum' a) where
pure = Second'
First' a <*> _ = First' a
_ <*> First' a = First' a
Second' f <*> Second' b = Second' $ f b
instance (Eq a, Eq b) => EqProp (Sum' a b) where (=-=) = eq
instance (Arbitrary a, Arbitrary b) => Arbitrary (Sum' a b) where
arbitrary = do
a <- arbitrary
b <- arbitrary
elements [First' a, Second' b]
instance Functor (Validation e) where
fmap _ (Error' e) = Error' e
fmap f (Success' a) = Success' (f a)
instance Monoid e => Applicative (Validation e) where
pure = Success'
Error' e <*> Error' e' = Error' $ e <> e'
Error' e <*> _ = Error' e
_ <*> Error' e = Error' e
Success' f <*> Success' a = Success' $ f a
instance (Eq a, Eq b) => EqProp (Validation a b) where (=-=) = eq
instance (Arbitrary a, Arbitrary b) => Arbitrary (Validation a b) where
arbitrary = do
a <- arbitrary
b <- arbitrary
elements [Error' a, Success' b]
----- Chapter exercises
instance (Eq a) => EqProp (Identity a) where (=-=) = eq
instance Arbitrary a => Arbitrary (Identity a) where
arbitrary = Identity <$> arbitrary
-- Pair
data Pair a = Pair a a deriving (Eq, Show)
instance Functor Pair where
fmap f (Pair x y) = Pair (f x) (f y)
instance Applicative Pair where
pure a = Pair a a
(Pair f f') <*> (Pair a a') = Pair (f a) (f' a')
instance Eq a => EqProp (Pair a) where (=-=) = eq
instance Arbitrary a => Arbitrary (Pair a) where
arbitrary = do
a <- arbitrary
a' <- arbitrary
return $ Pair a a'
-- Two
data Two a b = Two a b deriving (Eq, Show)
instance Functor (Two a) where
fmap f (Two a b) = Two a (f b)
instance (Arbitrary a, Arbitrary b) => Arbitrary (Two a b) where
arbitrary = do
a <- arbitrary
b <- arbitrary
return $ Two a b
instance Monoid a => Applicative (Two a) where
pure = Two mempty
Two a f <*> Two a' x = Two (a <> a') (f x)
instance (Eq a, Eq b) => EqProp (Two a b) where (=-=) = eq
-- Four
data Four a b c d = Four a b c d deriving (Eq, Show)
instance Functor (Four a b c) where
fmap f (Four a b c d) = Four a b c (f d)
instance (Monoid a, Monoid b, Monoid c) => Applicative (Four a b c) where
pure = Four mempty mempty mempty
Four a b c f <*> Four a' b' c' x =
Four (a <> a') (b <> b') (c <> c') (f x)
instance (Arbitrary a, Arbitrary b, Arbitrary c, Arbitrary d) =>
Arbitrary (Four a b c d) where
arbitrary = do
a <- arbitrary
b <- arbitrary
c <- arbitrary
d <- arbitrary
return $ Four a b c d
instance (Eq a, Eq b, Eq c, Eq d) => EqProp (Four a b c d) where
(=-=) = eq
-- Four'
data Four' a b = Four' a a a b deriving (Eq, Show)
instance Functor (Four' a) where
fmap f (Four' a a' a'' b) = Four' a a' a'' (f b)
instance Monoid a => Applicative (Four' a) where
pure = Four' mempty mempty mempty
Four' a b c f <*> Four' a' b' c' x =
Four' (a <> a') (b <> b') (c <> c') (f x)
instance (Arbitrary a, Arbitrary b) => Arbitrary (Four' a b) where
arbitrary = do
a <- arbitrary
a' <- arbitrary
a'' <- arbitrary
b <- arbitrary
return $ Four' a a' a'' b
instance (Eq a, Eq b) => EqProp (Four' a b) where (=-=) = eq
-- Vowels
stops :: String
stops = "pbtdkg"
vowels :: String
vowels = "aeiou"
combos :: [a] -> [b] -> [c] -> [(a, b, c)]
combos = liftA3 (,,)
main :: IO ()
main = do
quickBatch $ monoid (ZipList [1 :: Sum Int])
quickBatch $ applicative (Cons (1 :: Int, 2 :: Int, 3 :: Int) Nil)
quickBatch $
applicative (ZipList' (Cons (1 :: Int, 2 :: Int, 3 :: Int) Nil))
quickBatch $
applicative (First' (1, 2, 3) :: Sum' (Int, Int, Int) (Int, Int, Int))
quickBatch $
applicative (Error' ("a", "b", "c")
:: Validation (String, String, String)
(String, String, String))
quickBatch $ applicative (Identity (1 :: Int, 2 :: Int, 3 :: Int))
quickBatch $ applicative (Pair (1 :: Int, 1 :: Int, 1 :: Int)
(2 :: Int, 2 :: Int, 2 :: Int))
quickBatch $ applicative (Two ("a", "b", "c")
(2 :: Int, 2 :: Int, 2 :: Int))
quickBatch $ applicative (Four ("a", "b", "c")
("a", "b", "c")
("a", "b", "c")
("a", "b", "c"))
quickBatch $ applicative (Four' ("a", "b", "c")
("a", "b", "c")
("a", "b", "c")
("a", "b", "c"))
|
vasily-kirichenko/haskell-book
|
src/Applicatives.hs
|
bsd-3-clause
| 9,021 | 0 | 13 | 2,530 | 4,254 | 2,201 | 2,053 | 257 | 2 |
{-|
Module : OpenLayersFunc
Description : OpenLayers JavaScript and Haskell functions (using FFI)
-}
module OpenLayers.Func where
import Prelude hiding (void)
import JQuery
import Fay.Text hiding (head, tail, map)
import OpenLayers.Html
import OpenLayers.Internal
import OpenLayers.Types
import Fay.FFI
-- * NEW FUNCTION
-- | new MapQuest layer
newLayerMqt :: String -- ^ map type
-> Object -- ^ new layer (Tile)
newLayerMqt = ffi "new ol.layer.Tile({source: new ol.source.MapQuest({layer: %1})})"
-- | new OpenStreetMap layer
newLayerOSM :: Object -- ^ new layer (Tile)
newLayerOSM = ffi "new ol.layer.Tile({source: new ol.source.OSM()})"
-- | new Layer as vector
newVector :: Object -- ^ vectorsource
-> Opacity -- ^ opacity
-> Fay Object -- ^ new layer (Vector)
newVector = ffi "new ol.layer.Vector({source: %1, opacity: %2.slot1*0.01})"
-- | new 'GeoFeature' ('GeoPoint' or 'GeoLine')
newFeature :: GeoFeature -> Fay Object
newFeature f = case f of
GeoPoint p id s -> newFeaturePoint $ transformPoint p
GeoLine pts id s -> newFeatureLine $ transformPoints pts
_ -> error "newStyledFeature: the GeoFeature is not implemented yet"
-- | new map source GeoJSON as LineString
newFeatureLine :: [(Double, Double)] -- ^ input coordinates
-> Fay Object
newFeatureLine = ffi "new ol.source.GeoJSON({object:{'type':'Feature','geometry':{'type':'LineString','coordinates': %1}}})"
-- | new map source GeoJSON as Point
newFeaturePoint :: (Double, Double) -- ^ an input coordinate
-> Fay Object
newFeaturePoint = ffi "new ol.source.GeoJSON({object:{'type':'Feature','geometry':{'type':'Point','coordinates': %1}}})"
-- | new styled 'GeoLine'
newLineStyle :: GeoLineStyle -> Object
newLineStyle = ffi "[new ol.style.Style({stroke: new ol.style.Stroke({color: %1.color, width: %1.width})})]"
-- | new styled 'GeoPoint'
newPointStyle :: GeoPointStyle -> Object
newPointStyle = ffi "[new ol.style.Style({image: new ol.style.Circle({radius: %1.radius, fill: new ol.style.Fill({color:(%1.fillcolor == 'null' ? 'rgba(0,0,0,0)' : %1.fillcolor)}), stroke: %1.outcolor == 'null' ? null : new ol.style.Stroke({color: %1.outcolor, width: %1.outwidth})})})]"
-- | new OpenLayers DOM binding
newOlInput :: JQuery -- ^ element to bind to
-> String -- ^ case (f.e. \"checked\" by Checkbox)
-> Object -- ^ map object (f.e. 'getLayerByIndex 0')
-> String -- ^ attribute of map object to change (f.e. \"visible\")
-> Fay () -- ^ return type is void
newOlInput = ffi "(new ol.dom.Input(%1[0])).bindTo(%2, %3, %4)"
-- * ADD FUNCTION
-- | add an event on \"singleclick\" to display pop-up with coordinates in mercator and custom projection
addSingleClickEventAlertCoo :: String -- ^ EPSG-Code of custom projection (f.e. \"EPSG:4326\")
-> Fay () -- ^ return type is void
addSingleClickEventAlertCoo = ffi "olc.on('singleclick', function (evt) {alert(%1 + ': ' + ol.proj.transform([evt.coordinate[0], evt.coordinate[1]], 'EPSG:3857', %1) + '\\nEPSG:3857: ' + evt.coordinate)})"
-- | add a layer to the map, and remove all layers before inserting (baselayer has now index 0)
addBaseLayer :: MapSource -> Fay ()
addBaseLayer s = void $ do
removeLayers
addMapLayer s
-- | add a MapSource to the map
addMapLayer :: MapSource -> Fay ()
addMapLayer s
| s == OSM = addLayer newLayerOSM
| Prelude.any(s==)mapQuests = addLayer ( newLayerMqt $ showMapSource s)
| otherwise = error ("wrong MapSource allowed is OSM and " ++ show mapQuests)
-- | add a layer to the map
addLayer :: Object -> Fay ()
addLayer = ffi "olc.addLayer(%1)"
-- | add a 'GeoFeature' to a new layer to the map (first add coordinates to a new feature and then add the style and the id to this new feature, at least create a layer with the feature and add the layer to the map)
addStyledFeature :: GeoFeature -- ^ input ('GeoPoint' or 'GeoLine')
-> Opacity -- ^ opacity for the GeoFeature
-> Fay ()
addStyledFeature f o = do
feature <- newFeature f
styleFeature feature f
setFeatureId feature f
vector <- newVector feature o
addLayer vector
-- | add more than one 'GeoFeature' to a new layer (similar to the 'addStyledFeature' function)
addStyledFeatures :: [GeoFeature] -- ^ input ('GeoPoint' and/or 'GeoLine')
-> Opacity -- ^ global opacity for the GeoFeatures
-> Fay ()
addStyledFeatures f o = do
features <- mapS newFeature f
zipWithS styleFeature features f
zipWithS setFeatureId features f
vectors <- zipWithS newVector features [ o | x <- [0..(Prelude.length features)-1]]
addLayer (head vectors)
sources <- return $ zipWith getVectorFeatureAt ( vectors) [ 0 | x <- [0..(Prelude.length features)-1]]
addFeatures (head vectors) (tail sources)
-- | add an array with features to a layer
addFeatures :: Object -- ^ layer
-> [Object] -- ^ featurearray
-> Fay ()
addFeatures = ffi "%1.getSource().addFeatures(%2)"
-- | add a new point feature (and a new layer) by defining from HTML elements
addPointFromLabels :: String -- ^ id of the HTML element for the first coordinate (element need value, must be a double, see 'Coordinate')
-> String -- ^ id of the HTML element for the seconde coordinate (element need value, must be a double, see 'Coordinate')
-> String -- ^ id of the HTML element for the opacity (element need value, must be an integer, see 'Opacity')
-> String -- ^ id of the HTML element for the feature id (element need value, must be a positive integer, see 'OpenLayers.Types.id')
-> GeoPointStyle -- ^ define the style of the feature
-> Fay () -- ^
addPointFromLabels xId yId oId idId s = void $ do
xinput <- selectId xId
xcoor <- getVal xinput
yinput <- selectId yId
ycoor <- getVal yinput
o <- getInputInt oId
i <- getInputInt idId
addStyledFeature (GeoPoint (Coordinate (toDouble xcoor) (toDouble ycoor) (Projection "EPSG:3857")) i s) (Opacity o)
-- | add a map event listener (f.e. when zoom or pan)
addMapWindowEvent :: String -- ^ the event trigger (f.e. \"moveend\")
-> Fay JQuery -- ^ action on the event
-> Fay ()
addMapWindowEvent = ffi "olc.on(%1, %2)"
-- | add a connection between HTML and OpenLayers to manipulate layer attributes
addOlDomInput :: String -- ^ id of the HTML element which triggers
-> String -- ^ HTML value to trigger (f.e. \"checked\")
-> String -- ^ layer attribute to manipulate (f.e. \"visible\")
-> Object -- ^ layer to manipulate
-> Fay ()
addOlDomInput id typehtml value method = void $ do
element <- selectId id
newOlInput element typehtml method value
-- * REMOVE FUNCTION
-- | remove all layers from the map
removeLayers :: Fay ()
removeLayers = void $ do
layers <- getLayers
mapM removeLayer layers
-- | remove a layer object (only use with layers)
removeLayer :: a -- ^ layer to remove
-> Fay ()
removeLayer = ffi "olc.removeLayer(%1)"
-- * CHANGE FUNCTION
-- | zoom IN and specify levels to change
zoomIn :: Integer -- ^ number of zoomlevels to change
-> Fay ()
zoomIn = ffi "olc.getView().setZoom(olc.getView().getZoom()+%1)"
-- | zoom OUT and specify levels to change
zoomOut :: Integer -- ^ number of zoomlevels to change
-> Fay ()
zoomOut = ffi "olc.getView().setZoom(olc.getView().getZoom()-%1)"
-- | style a feature @/after/@ creating a new feature and @/before/@ adding to a new layer (this is an internal function for 'addStyledFeature' and 'addStyledFeatures')
styleFeature :: Object -- ^ the prevoiusly created new feature
-> GeoFeature -- ^ the GeoFeature object of the prevoiusly created feature
-> Fay ()
styleFeature object feature = case feature of
GeoPoint p id s -> styleFeature' object $ newPointStyle s
GeoLine pts id s -> styleFeature' object $ newLineStyle s
_ -> error "styleFeature: the GeoFeature is not implemented"
-- | style a feature FFI function
styleFeature' :: Object -> Object -> Fay ()
styleFeature' = ffi "%1.getFeatures()[0].setStyle(%2)"
-- | change the baselayer at layerindex 0
changeBaseLayer :: MapSource -- ^ new 'MapSource' for the baselayer
-> Fay ()
changeBaseLayer s = void $ do
layers <- getLayers
addBaseLayer s
mapS addLayer $ tail layers
-- * SET FUNCTION
-- | set the id of a feature, get the feature by layer and featureindex
setId :: Object -- ^ layer with the requested feature
-> Integer -- ^ new id for the feature ( > 0)
-> Integer -- ^ index of the feature in the layer (Layer.getFeatures()[i] , i >= 0)
-> Fay ()
setId = ffi "(%2 < 1 || %3 < 0) ? '' : %1.getSource().getFeatures()[%3].setId(%2)"
-- | set the id of the first feature of the vector
setFeatureId :: Object -- ^ vector
-> GeoFeature -- ^ input for the id
-> Fay ()
setFeatureId = ffi "%1.getFeatures()[0].setId(%2.id)"
-- | set map center with a 'Coordinate'
setCenter :: Coordinate -> Fay ()
setCenter c = setCenter' $ transformPoint c
-- | set map center FFI function
setCenter' :: (Double, Double) -> Fay ()
setCenter' = ffi "olc.getView().setCenter(%1)"
-- | set the map center and the zoomlevel at the same time
setCenterZoom :: Coordinate -- ^ center position
-> Integer -- ^ zoomlevel
-> Fay () -- ^ return type is void
setCenterZoom c z = void $ do
setCenter c
setZoom z
-- | set the zoomlevel of the map
setZoom :: Integer -> Fay ()
setZoom = ffi "olc.getView().setZoom(%1)"
-- * GET FUNCTION
-- | get map center in requested projection with n decimal places
getCenter :: Projectionlike -- ^ requested projection
-> Integer -- ^ decimal places
-> Fay Text
getCenter proj fixed = do
c <- getCenter'
coordFixed (transformPointTo proj c) fixed
-- | get map center FFI function
getCenter' :: Fay (Double, Double)
getCenter' = ffi "olc.getView().getCenter()"
-- | get map zoom level
getZoom :: Fay Text
getZoom = ffi "olc.getView().getZoom()"
-- | get an array of all layers in the map
getLayers :: Fay [Object]
getLayers = ffi "olc.getLayers().getArray()"
-- | get a layer by index and return a object
getLayerByIndex :: Integer -> Object
getLayerByIndex = ffi "olc.getLayers().item(%1)"
-- | get a layer by index and return a fay object
getLayerByIndex' :: Integer -> Fay Object
getLayerByIndex' = ffi "olc.getLayers().item(%1)"
-- | get the id of a feature (<http://openlayers.org/en/v3.1.1/apidoc/ol.Feature.html OpenLayers Feature>)
getFeatureId :: Object
-> Integer
getFeatureId = ffi "%1.getId()"
-- | get a feature from a vector at index position
getVectorFeatureAt :: Object -- ^ Vector
-> Integer -- ^ index of vector features
-> Object
getVectorFeatureAt = ffi "%1.getSource().getFeatures()[%2]"
-- | get the number of features in a vector
getVectorFeatureLength :: Object -- ^ Vector
-> Integer -- ^ number of features in vector
getVectorFeatureLength = ffi "%1.getSource().getFeatures().length"
-- * TRANSFORM FUNCTION
-- | transform coordinates from mercator to requested projection
transformPointTo :: Projectionlike -- ^ target projection
-> (Double, Double) -- ^ input
-> (Double, Double) -- ^ output
transformPointTo = ffi "ol.proj.transform(%2, 'EPSG:3857', %1.slot1)"
-- | transform 'Coordinate' to mercator (EPSG:3857)
transformPoint :: Coordinate -- ^ input
-> (Double, Double) -- ^ output
transformPoint = ffi "ol.proj.transform([%1.x, %1.y], %1.from.slot1, 'EPSG:3857')"
-- | transform 'Coordinate's to mercator (EPSG:3857)
transformPoints :: [Coordinate] -> [(Double, Double)]
transformPoints c = [transformPoint x | x <- c]
-- * OTHER FUNCTION
-- | create a Text from a tuple of doubles with fixed decimal places and seperator \",\"
coordFixed :: (Double, Double) -> Integer -> Fay Text
coordFixed = ffi "%1[0].toFixed(%2) + ',' + %1[1].toFixed(%2)"
-- | change Text to Double
toDouble :: Text -> Double
toDouble = ffi "%1"
-- | 'sequence' the 'map'-function
mapS :: (a -> Fay b) -> [a] -> Fay [b]
mapS f x = sequence (map f x)
-- | 'sequence' the 'zipWith'-function
zipWithS :: (a -> b -> Fay c) -> [a] -> [b] -> Fay [c]
zipWithS f x y = sequence $ zipWith f x y
-- zipWithS3 :: (a -> b -> c -> Fay d) -> [a] -> [b] -> [c] -> Fay [d]
-- zipWithS3 f x y z = sequence $ zipWith3 f x y z
|
olwrapper/olwrapper
|
wrapper/OpenLayers/Func.hs
|
bsd-3-clause
| 12,894 | 0 | 17 | 3,057 | 2,042 | 1,069 | 973 | 194 | 3 |
module Math.LinearRecursive.Internal.Polynomial
( Polynomial
, polynomial
, unPoly
, fromList
, toList
, singleton
, x
, degree
, evalPoly
) where
import qualified Data.IntMap as IntMap
import Math.LinearRecursive.Internal.Vector
newtype Polynomial a = Polynomial { unPoly :: Vector a }
polynomial :: Num a => Vector a -> Polynomial a
polynomial = Polynomial
toList :: (Eq a, Num a) => Polynomial a -> [(Int, a)]
toList (Polynomial a) = IntMap.assocs (unVector a)
fromList :: (Eq a, Num a) => [(Int, a)] -> Polynomial a
fromList lst = polynomial (vector (IntMap.fromListWith (+) lst))
singleton :: (Eq a, Num a) => a -> Polynomial a
singleton v = polynomial (vector (IntMap.singleton 0 v))
x :: (Eq a, Num a) => Polynomial a
x = polynomial (vector (IntMap.singleton 1 1))
degree :: (Eq a, Num a) => Polynomial a -> Int
degree p = maximum $ (-1) : map fst (toList p)
evalPoly :: (Eq a, Num a) => Polynomial a -> a -> a
evalPoly p v = sum [ci * v ^ i | (i, ci) <- toList p]
instance (Show a, Eq a, Num a) => Show (Polynomial a) where
show a = "Polynomial " ++ show (toList a)
instance Eq a => Eq (Polynomial a) where
Polynomial a == Polynomial b = a == b
instance (Eq a, Num a) => Num (Polynomial a) where
Polynomial a + Polynomial b = polynomial (a <+> b)
Polynomial a - Polynomial b = polynomial (a <-> b)
negate (Polynomial a) = polynomial (vmap negate a)
a * b = fromList [(i + j, ai * bj) | (i, ai) <- toList a , (j, bj) <- toList b]
abs = error "Polynomial : absolute value undefined"
signum = error "Polynomial : signum undefined"
fromInteger = singleton . fromInteger
|
bjin/monad-lrs
|
Math/LinearRecursive/Internal/Polynomial.hs
|
bsd-3-clause
| 1,648 | 0 | 10 | 371 | 750 | 390 | 360 | 39 | 1 |
import System.Directory
import PocParser
import PocStrategy
import StrategyTest
-- Test GENERATE --
main :: IO ()
main = do
--mapM_ (uncurry generateTest) genTests
--plusTest
--generateAllTest
chooseStrategyTest
-- PARSER AND PROGRAMS STUFF --
--main :: IO ()
--main = do
-- files <- getDirectoryContents "test/basic_programs"
-- mapM_ (progTest "test/basic_programs/") files
--
--progTest :: FilePath -> FilePath -> IO ()
--progTest _ "." = return ()
--progTest _ ".." = return ()
--progTest p f = do
-- program <- readFile (p++f)
-- print ("Parsing " ++ (p++f))
-- let p = parseProg f program
-- print p
|
NicolaiNebel/Bachelor-Poc
|
test/Spec.hs
|
bsd-3-clause
| 624 | 0 | 6 | 114 | 51 | 36 | 15 | 7 | 1 |
module CallByReference.Data where
import Control.Monad.Trans.State.Lazy
import qualified Data.Map as M
import Data.Maybe (fromMaybe)
type Try = Either String
type Environment = M.Map String DenotedValue
empty :: Environment
empty = M.empty
initEnvironment :: [(String, DenotedValue)] -> Environment
initEnvironment = M.fromList
extend :: String -> DenotedValue -> Environment -> Environment
extend = M.insert
extendRec :: String -> [String] -> Expression -> Environment
-> StatedTry Environment
extendRec name params body = extendRecMany [(name, params, body)]
extendRecMany :: [(String, [String], Expression)] -> Environment
-> StatedTry Environment
extendRecMany lst env = do
refs <- allocMany (length lst)
let denoVals = fmap DenoRef refs
let names = fmap (\(n, _, _) -> n) lst
let newEnv = extendMany (zip names denoVals) env
extendRecMany' lst refs newEnv
where
extendRecMany' [] [] env = return env
extendRecMany' ((name, params, body):triples) (ref:refs) env = do
setRef ref (ExprProc $ Procedure params body env)
extendRecMany' triples refs env
allocMany 0 = return []
allocMany x = do
ref <- newRef (ExprBool False) -- dummy value false for allocating space
(ref:) <$> allocMany (x - 1)
apply :: Environment -> String -> Maybe DenotedValue
apply = flip M.lookup
extendMany :: [(String, DenotedValue)] -> Environment -> Environment
extendMany = flip (foldl func)
where
func env (var, val) = extend var val env
applyForce :: Environment -> String -> DenotedValue
applyForce env var = fromMaybe
(error $ "Var " `mappend` var `mappend` " is not in environment!")
(apply env var)
newtype Ref = Ref { addr::Integer } deriving(Show, Eq)
newtype Store = Store { refs::[ExpressedValue] } deriving(Show)
type StatedTry = StateT Store (Either String)
throwError :: String -> StatedTry a
throwError msg = StateT (\s -> Left msg)
initStore :: Store
initStore = Store []
newRef :: ExpressedValue -> StatedTry Ref
newRef val = do
store <- get
let refList = refs store
put $ Store (val:refList)
return . Ref . toInteger . length $ refList
deRef :: Ref -> StatedTry ExpressedValue
deRef (Ref r) = do
store <- get
let refList = refs store
findVal r (reverse refList)
where
findVal 0 (x:_) = return x
findVal 0 [] = throwError "Index out of bound when calling deref!"
findVal i (_:xs) = findVal (i - 1) xs
setRef :: Ref -> ExpressedValue -> StatedTry ()
setRef ref val = do
store <- get
let refList = refs store
let i = addr ref
newList <- reverse <$> setRefVal i (reverse refList) val
put $ Store newList
return ()
where
setRefVal _ [] _ = throwError "Index out of bound when calling setref!"
setRefVal 0 (_:xs) val = return (val:xs)
setRefVal i (x:xs) val = (x:) <$> setRefVal (i - 1) xs val
data Program = Prog Expression
deriving (Show, Eq)
data Expression =
ConstExpr ExpressedValue
| VarExpr String
| LetExpr [(String, Expression)] Expression
| BinOpExpr BinOp Expression Expression
| UnaryOpExpr UnaryOp Expression
| CondExpr [(Expression, Expression)]
| ProcExpr [String] Expression
| CallExpr Expression [Expression]
| LetRecExpr [(String, [String], Expression)] Expression
| BeginExpr [Expression]
| AssignExpr String Expression
| SetDynamicExpr String Expression Expression
deriving(Show, Eq)
data BinOp =
Add | Sub | Mul | Div | Gt | Le | Eq
deriving(Show, Eq)
data UnaryOp = Minus | IsZero
deriving(Show, Eq)
data Procedure = Procedure [String] Expression Environment
instance Show Procedure where
show _ = "<procedure>"
data ExpressedValue = ExprNum Integer
| ExprBool Bool
| ExprProc Procedure
instance Show ExpressedValue where
show (ExprNum i) = show i
show (ExprBool b) = show b
show (ExprProc p) = show p
instance Eq ExpressedValue where
(ExprNum i1) == (ExprNum i2) = i1 == i2
(ExprBool b1) == (ExprBool b2) = b1 == b2
_ == _ = False
data DenotedValue = DenoRef Ref
instance Show DenotedValue where
show (DenoRef v) = show v
instance Eq DenotedValue where
DenoRef v1 == DenoRef v2 = v1 == v2
|
li-zhirui/EoplLangs
|
src/CallByReference/Data.hs
|
bsd-3-clause
| 4,242 | 0 | 13 | 970 | 1,555 | 812 | 743 | 112 | 3 |
{-# LANGUAGE ExtendedDefaultRules, FlexibleInstances, MultiParamTypeClasses, OverloadedStrings, TypeFamilies, RankNTypes #-}
module Web.ISO.HSX where
import Data.Monoid ((<>))
import Data.Text (Text, pack, unpack)
import GHCJS.Marshal.Pure (pFromJSVal)
import GHCJS.Types (JSVal(..), JSString(..))
import Web.ISO.Types (Attr(Attr, Event), HTML(Element, CDATA), FormEvent(Change, Input), MouseEvent(Click), descendants)
default (Text)
{- HSX2HS -}
genElement (d, t) a c =
let c' = (concat c)
in Element t {- [] -} a Nothing (descendants c') c'
genEElement (d, t) a = genElement (d, t) a []
fromStringLit = pack
class AsChild action c where
asChild :: c -> [HTML action]
instance AsChild action Text where
asChild t = [CDATA True t]
instance AsChild action String where
asChild t = [CDATA True (pack t)]
instance (parentAction ~ action) => AsChild parentAction (HTML action) where
asChild t = [t]
instance (parentAction ~ action) => AsChild parentAction [HTML action] where
asChild t = t
data KV k v = k := v
class AsAttr action a where
asAttr :: a -> Attr action
instance AsAttr action (KV Text Text) where
asAttr (k := v) = Attr k v
instance AsAttr action (KV Text action) where
asAttr (type' := action) =
case type' of
"onchange" -> Event Change (const $ pure action)
"onclick" -> Event Click (const $ pure action)
"oninput" -> Event Input (const $ pure action)
-- "onblur" -> Event Blur (const $ pure action)
_ -> error $ "unsupported event: " ++ (unpack type')
{-
instance AsAttr action (KV Text (JSVal -> action)) where
asAttr (type' := action) =
case type' of
"onchange" -> Event Change (action . pFromJSVal)
-- "onclick" -> Event Click action
-- "oninput" -> Event Input action
-- "onblur" -> Event Blur action
_ -> error $ "unsupported event: " ++ (unpack type')
-}
{-
instance AsAttr action (KV Text (IO String, (String -> action), action)) where
asAttr (type' := action) =
case type' of
"onchange" -> Event (Change, action)
"onclick" -> Event (Click, action)
"oninput" -> Event (Input, action)
_ -> error $ "unsupported event: " ++ (unpack type')
-}
instance (action' ~ action) => AsAttr action' (Attr action) where
asAttr a = a
|
stepcut/isomaniac
|
Web/ISO/HSX.hs
|
bsd-3-clause
| 2,383 | 0 | 12 | 591 | 598 | 328 | 270 | 37 | 1 |
{-# LANGUAGE FlexibleInstances, TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
import Control.Applicative
import Data.IP
import Data.Text
import Data.Time
import Test.Hspec
import Test.HUnit
import Test.Hspec.QuickCheck
import Test.QuickCheck
import Cloud.AWS.Lib.FromText
import Cloud.AWS.Lib.ToText
prop_class :: (Eq a, FromText a, ToText a) => a -> Bool
prop_class a = fromText (toText a) == Just a
instance Arbitrary Day where
arbitrary = ModifiedJulianDay <$> arbitrary
instance Arbitrary DiffTime where
arbitrary = secondsToDiffTime <$> choose (0, 60*60*24-1)
instance Arbitrary UTCTime where
arbitrary = UTCTime <$> arbitrary <*> arbitrary
instance Arbitrary IPv4 where
arbitrary = toIPv4 <$> vectorOf 4 (choose (0,255))
instance Arbitrary (AddrRange IPv4) where
arbitrary = makeAddrRange <$> arbitrary <*> choose (0, 32)
instance Arbitrary Text where
arbitrary = pack <$> arbitrary
prop_mclass :: (Eq a, FromText a, ToText a) => a -> Bool
prop_mclass a = fromText (toText a) == Just (Just a)
testNothing :: IO ()
testNothing = (fromText "" :: Maybe Int) @=? Nothing
testConvertNothingToUnit :: IO ()
testConvertNothingToUnit = fromNamedText "unit" Nothing @=? Just ()
data A = B | C deriving (Eq, Show)
deriveToText "A" ["ab", "ac"]
deriveFromText "A" ["ab", "ac"]
instance Arbitrary A where
arbitrary = elements [B, C]
main :: IO ()
main = hspec $ do
describe "Cloud.AWS.Lib.{FromText,ToText}" $ do
prop "Int" (prop_class :: Int -> Bool)
prop "Integer" (prop_class :: Integer -> Bool)
prop "Double" (prop_class :: Double -> Bool)
prop "Bool" (prop_class :: Bool -> Bool)
prop "UTCTime" (prop_class :: UTCTime -> Bool)
prop "IPv4" (prop_class :: IPv4 -> Bool)
prop "AddrRange IPv4" (prop_class :: AddrRange IPv4 -> Bool)
prop "Maybe Int" (prop_mclass :: Int -> Bool)
it "convert Nothing" testNothing
prop "deriveFromText/deriveToText" (prop_class :: A -> Bool)
prop "Unit" (\t -> fromText t == Just ())
it "convert Nothing to Unit" testConvertNothingToUnit
|
worksap-ate/aws-sdk-text-converter
|
test/Spec.hs
|
bsd-3-clause
| 2,120 | 0 | 16 | 431 | 704 | 363 | 341 | 52 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeFamilies #-}
-----------------------------------------------------------------------------
-- |
-- Module : Generics.Regular.Functions
-- Copyright : (c) 2010 Universiteit Utrecht
-- License : BSD3
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : non-portable
--
-- Summary: All of the generic functionality for regular dataypes: mapM,
-- flatten, zip, equality, value generation, fold and unfold.
-- Generic show ("Generics.Regular.Functions.Show"), generic read
-- ("Generics.Regular.Functions.Read") and generic equality
-- ("Generics.Regular.Functions.Eq") are not exported to prevent clashes
-- with @Prelude@.
-----------------------------------------------------------------------------
module Generics.Regular.Functions (
-- * Constructor names
module Generics.Regular.Functions.ConNames,
-- * Crush
module Generics.Regular.Functions.Crush,
-- * Generic folding
module Generics.Regular.Functions.Fold,
-- * Functorial map
module Generics.Regular.Functions.GMap,
-- * Generating values that are different on top-level
module Generics.Regular.Functions.LR,
-- * Zipping
module Generics.Regular.Functions.Zip
) where
import Generics.Regular.Functions.ConNames
import Generics.Regular.Functions.Crush
import Generics.Regular.Functions.Fold
import Generics.Regular.Functions.GMap
import Generics.Regular.Functions.LR
import Generics.Regular.Functions.Zip
|
dreixel/regular
|
src/Generics/Regular/Functions.hs
|
bsd-3-clause
| 1,626 | 0 | 5 | 262 | 126 | 99 | 27 | 17 | 0 |
module Jade.Jumper where
import Jade.Common
import qualified Jade.Decode.Coord as Coord
getEnds :: Jumper -> ((Integer, Integer), (Integer, Integer))
getEnds (Jumper (Coord3 x y r)) = Coord.coord5ends (Coord5 x y r 8 0)
points (Jumper (Coord3 x y r)) = [Point x y]
|
drhodes/jade2hdl
|
src/Jade/Jumper.hs
|
bsd-3-clause
| 268 | 0 | 9 | 45 | 122 | 68 | 54 | 6 | 1 |
module DiceSpec ( main, spec ) where
import System.Random
import Test.Hspec
import Test.QuickCheck
import TestHelpers
import Dice
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "d4" $
it "is within range" $ property $ \seed n ->
let rolls = take n $ rollsOf (D4 $ mkStdGen seed)
in all (`elem` [1..4]) rolls
describe "d20" $
it "is within range" $ property $ \seed n ->
let rolls = take n $ rollsOf (D20 $ mkStdGen seed)
in all (`elem` [1..20]) rolls
|
camelpunch/rhascal
|
test/DiceSpec.hs
|
bsd-3-clause
| 562 | 0 | 17 | 183 | 211 | 110 | 101 | 18 | 1 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
module Duckling.Ordinal.DA.Tests
( tests ) where
import Prelude
import Data.String
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.Ordinal.DA.Corpus
import Duckling.Testing.Asserts
tests :: TestTree
tests = testGroup "DA Tests"
[ makeCorpusTest [Seal Ordinal] corpus
]
|
facebookincubator/duckling
|
tests/Duckling/Ordinal/DA/Tests.hs
|
bsd-3-clause
| 504 | 0 | 9 | 78 | 79 | 50 | 29 | 11 | 1 |
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.NV.VertexProgram2Option
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.NV.VertexProgram2Option (
-- * Extension Support
glGetNVVertexProgram2Option,
gl_NV_vertex_program2_option,
-- * Enums
pattern GL_MAX_PROGRAM_CALL_DEPTH_NV,
pattern GL_MAX_PROGRAM_EXEC_INSTRUCTIONS_NV
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
|
haskell-opengl/OpenGLRaw
|
src/Graphics/GL/NV/VertexProgram2Option.hs
|
bsd-3-clause
| 731 | 0 | 5 | 95 | 52 | 39 | 13 | 8 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module HaskellStorm.Internal
( BoltIn (..)
, EmitCommand (..)
, Handshake (..)
, PidOut (..)
, SpoutIn
, StormConfig (..)
, StormOut (..)
) where
import Control.Applicative ((<$>), (<*>))
import Control.Monad (mzero)
import Data.Aeson ((.:), (.:?), (.=), Array (..), decode, FromJSON (..), Object, object, ToJSON(..), Value(..))
import qualified Data.Aeson as A
import Data.Aeson.Types (Parser)
import Data.Maybe (catMaybes)
import Data.Scientific (scientific)
import Data.Text (Text)
import Data.Vector (fromList)
type StormConfig = Value
type StormContext = Value
type StormTuples = Array
-----
data Handshake = Handshake { getConf :: StormConfig
, getContext :: StormContext
, getPidDir :: Text
} deriving (Eq, Show)
instance FromJSON Handshake where
parseJSON (Object v) =
Handshake <$> v .: "conf"
<*> v .: "context"
<*> v .: "pidDir"
parseJSON _ = mzero
instance ToJSON Handshake where
toJSON (Handshake config context pidDir) =
object [ "conf" .= toJSON config
, "context" .= toJSON context
, "pidDir" .= pidDir
]
---
data PidOut = PidOut { getPid :: Integer } deriving (Show, Eq)
instance FromJSON PidOut where
parseJSON (Object v) =
PidOut <$> v .: "pid"
parseJSON _ = mzero
instance ToJSON PidOut where
toJSON (PidOut pid) = object [ "pid" .= pid ]
---
data EmitCommand = EmitNext | EmitAck | EmitFail deriving (Show, Eq)
instance FromJSON EmitCommand where
parseJSON (A.String "next") = return EmitNext
parseJSON (A.String "ack") = return EmitAck
parseJSON (A.String "fail") = return EmitFail
parseJSON _ = mzero
instance ToJSON EmitCommand where
toJSON EmitNext = A.String "next"
toJSON EmitAck = A.String "ack"
toJSON EmitFail = A.String "fail"
---
data BoltIn = BoltIn { tupleId :: Text
, boltComponent :: Text
, boltStream :: Text
, boltTask :: Integer
, inputTuples :: StormTuples
}
deriving (Eq, Show)
instance FromJSON BoltIn where
parseJSON (Object v) =
BoltIn <$> v .: "id"
<*> v .: "comp"
<*> v .: "stream"
<*> v .: "task"
<*> v .: "tuple"
parseJSON _ = mzero
instance ToJSON BoltIn where
toJSON (BoltIn tupleId boltComponent boltStream boltTask inputTuples) =
object [ "id" .= toJSON tupleId
, "comp" .= toJSON boltComponent
, "stream" .= toJSON boltStream
, "task" .= toJSON boltTask
, "tuple" .= toJSON inputTuples
]
---
data StormOut = Emit { anchors :: [Text]
, stream :: Maybe Text
, task :: Maybe Integer
, tuples :: StormTuples
}
| Ack { ackTupleId :: Text }
| Fail { failTupleId :: Text }
| Log { logMsg :: Text }
deriving (Eq, Show)
instance ToJSON StormOut where
toJSON (Emit anchors stream task tuples) =
object $ [ "anchors" .= fromList anchors
, "command" .= A.String "emit"
, "tuple" .= tuples
] ++ catMaybes [ ("stream" .=) . A.String <$> stream
, ("task" .=) <$> (flip scientific 0) <$> task ]
toJSON (Ack tupleId) =
object $ [ "command" .= A.String "ack"
, "id" .= A.String tupleId ]
toJSON (Fail tupleId) =
object $ [ "command" .= A.String "fail"
, "id" .= A.String tupleId ]
toJSON (Log msg) =
object $ [ "command" .= A.String "log"
, "msg" .= A.String msg ]
---
data SpoutIn = SpoutNext
| SpoutAck { spoutAckId :: Text }
| SpoutFail { spoutFailId :: Text }
deriving (Eq, Show)
instance FromJSON SpoutIn where
parseJSON (Object v) =
(v .: "command") >>= (go v)
where
go :: Object -> Text -> Parser SpoutIn
go o t = case t of
"next" -> return SpoutNext
"ack" -> SpoutAck <$> o .: "id"
"fail" -> SpoutFail <$> o .: "id"
_ -> mzero
parseJSON _ = mzero
|
aaronlevin/pipes-storm
|
src/HaskellStorm/Internal.hs
|
bsd-3-clause
| 4,546 | 0 | 15 | 1,699 | 1,296 | 716 | 580 | 112 | 0 |
module Interpreter
(Program, run, verify, programFromText, testProgram, failingProgram
) where
import Color
import Evaluator
import Program
import qualified Data.Map as Map
import Data.Maybe
import qualified System.IO as System
import System.Console.ANSI
import System.Console.Regions
import Control.Concurrent.STM
import System.Console.Concurrent
-- Monads we'll use
import Data.Functor.Identity
import Control.Monad.Trans.State
import Control.Monad.Trans.Writer
import Control.Monad.Trans
import Control.Monad.Except
type Run a = StateT ProgramState (ExceptT String IO) a
runRun p = runExcept (runStateT p initialProgramState)
set :: (Name, Val) -> Run ()
set (s,i) = state $ (\st ->
let updatedCurrentEnv = Map.insert s i (currentEnv st)
tailEnvs = tail $ envs st
statements' = statements st
outputs' = outputs st
in ((), ProgramState{envs = updatedCurrentEnv : tailEnvs, statements = statements', outputs = outputs'}))
exec :: Statement -> Run ()
exec (Assign s v) = do st <- get
Right val <- return $ runEval (currentEnv st) (eval v)
set (s,val)
exec (Seq s0 s1) = do exec (Debug s0) >> exec (Debug s1)
exec (Print e) = do st <- get
Right val <- return $ runEval (currentEnv st) (eval e)
put $ ProgramState{ envs = (envs st), statements = (statements st), outputs = val:(outputs st) }
return ()
exec (If cond s0 s1) = do st <- get
Right (B val) <- return $ runEval (currentEnv st) (eval cond)
if val then do exec (Debug s0) else do exec (Debug s1)
exec (While cond s) = do st <- get
Right (B val) <- return $ runEval (currentEnv st) (eval cond)
if val then do exec (Debug s) >> exec DebugTidyTree >> exec (Debug (While cond s)) else return()
exec (Try s0 s1) = do catchError (exec s0) (\_ -> exec s1)
exec Pass = return ()
exec (Debug (Seq s0 s1)) = exec (Seq s0 s1) -- Ignore this case as it's just chaining
exec (Debug s) = do tick s
printTree s
printInstructions
prompt s
exec DebugTidyTree = do st <- get
clearFromTree (lastStatement st)
-- Executing a "program" means compiling it and then running the
-- resulting Statement with an empty variable map.
run :: Program -> IO ()
run p = do result <- runExceptT $ (runStateT (exec (compile p)) initialProgramState)
case result of
Right ((), _) -> return ()
Left exn -> System.print $ "Uncaught exception: " ++ exn
-- ** Prompts **
-- Pattern match on input and first character so we can ensure the inspect command starts with a colon.
-- Re-prompt if string is empty (this also prevents head input from failing because of lazy evaluation)
prompt :: Statement -> Run ()
prompt s = do input <- liftIO $ getLine
case (input, head input) of
("",_) -> prompt s
("next",_) -> exec s
("back",_) -> do stepback
exec (Debug s)
(_,':') -> do inspect $ tail input
printHistoryInstructions
historyprompt s
(_,'|') -> do exec (read (tail input) :: Statement)
prompt s
(_,_) -> do liftIO $ putStrLn . red $ "Unknown command " ++ input
printInstructions
prompt s
historyprompt :: Statement -> Run ()
historyprompt s = do input <- liftIO $ getLine
case input of
"done" -> do printTree s
printInstructions
prompt s
_ -> return ()
-- ** Operations **
tick :: Statement -> Run ()
tick s = do st <- get
put $ ProgramState{ envs = (currentEnv st):(envs st), statements = s:(statements st), outputs = (outputs st) }
stepback :: Run ()
stepback = do st <- get
let statement = lastStatement st
put $ ProgramState{ envs = (tail $ (tail $ envs st)), statements = (tail $ (tail $ statements st)), outputs = (outputs st) }
exec (Debug statement)
inspect :: String -> Run ()
inspect v = printVarHistory v
clearFromTree :: Statement -> Run ()
clearFromTree s = do st <- get
put $ ProgramState{ envs = (envs st), statements = (tail $ statements st), outputs = (outputs st) }
case s of
(While _ _) -> return ()
_ -> clearFromTree $ lastStatement st
-- ** Print operations **
printInstructions :: Run ()
printInstructions = liftIO $ putStrLn "Enter 'next' to proceed, 'back' to step back and ':<variablename>' to view a variable's value"
printHistoryInstructions :: Run ()
printHistoryInstructions = liftIO $ putStrLn "Enter 'done' to return."
-- Takes in next statement and prints it with the rest of the history tree
printTree :: Statement -> Run ()
printTree s = do st <- get
let statements' = tail $ statements st
let list = zipWithPadding Pass ("", Null) Null (reverse statements') (Map.toList (currentEnv st)) (reverse (outputs st))
clearTerminal
liftIO $ printTreeHeader
liftIO $ mapM_ (putStrLn . printTreeLine) $ list
liftIO $ putStrLn $ printCurrentStatement s
printVarHistory :: Name -> Run()
printVarHistory v = do st <- get
let statements' = tail $ statements st
let envs' = tail $ envs st
let varhist = reverse $ map (variableFromEnv v) envs'
let list = zipWithPadding Pass ("", Null) Null (reverse statements') varhist []
clearTerminal
liftIO $ printTreeHeader'
liftIO $ mapM_ (putStrLn . printTreeLine) $ list
-- Tree header for normal tree
printTreeHeader :: IO ()
printTreeHeader = do liftIO $ putStrLn $ "Statements" ++ (nspaces (60-10)) ++ "Variables" ++ (nspaces (60-9)) ++ "Output"
liftIO $ putStrLn $ "==========" ++ (nspaces (60-10)) ++ "=========" ++ (nspaces (60-9)) ++ "======"
-- Tree header for history tree
printTreeHeader' :: IO ()
printTreeHeader' = do liftIO $ putStrLn $ "Statements" ++ (nspaces (60-10)) ++ "Value at Point of execution"
liftIO $ putStrLn $ "==========" ++ (nspaces (60-10)) ++ "==========================="
printTreeLine :: (Statement, (Name, Val), Val) -> String
printTreeLine (s, var, val) = (cyan $ statementToString s) ++ spaces ++ (printVariable var) ++ spaces' ++ (printOutput val)
where spaces = nspaces (60 - l)
spaces' = nspaces (60 - l')
l = length $ statementToString s
l' = length $ printVariable var
printCurrentStatement :: Statement -> String
printCurrentStatement s = green $ "> " ++ statementToString s
printVariable :: (Name, Val) -> String
printVariable (_, Null) = ""
printVariable (n, v) = "Variable: " ++ (blue n) ++ " Value: " ++ (blue (show v))
printOutput :: Val -> String
printOutput Null = ""
printOutput s = show s
-- ** Utils **
variableFromEnv :: Name -> Env -> (Name, Val)
variableFromEnv var env = case Map.lookup var env of
Just val -> (var, val)
Nothing -> ("", Null)
statementToString :: Statement -> String
statementToString (While cond _) = "While " ++ (show cond) ++ " do"
statementToString (If cond _ _) = "If " ++ (show cond) ++ " do"
statementToString Pass = "" -- Don't bother printing pass statements
statementToString s = show s
-- Clear screen twice ensures we are at the bottom of the screen.
clearTerminal :: Run ()
clearTerminal = do liftIO $ clearScreen
liftIO $ clearScreen
-- Normalize's lengths of zipped lists (So will fill with standard defaults)
zipWithPadding :: a -> b -> c -> [a] -> [b] -> [c] -> [(a,b,c)]
zipWithPadding a b c (x:xs) (y:ys) (z:zs) = (x,y,z) : zipWithPadding a b c xs ys zs
zipWithPadding _ _ _ [] [] [] = []
zipWithPadding a b c [] ys zs = zipWithPadding a b c [a] ys zs
zipWithPadding a b c xs [] zs = zipWithPadding a b c xs [b] zs
zipWithPadding a b c xs ys [] = zipWithPadding a b c xs ys [c]
nspaces :: Int -> String
nspaces n = take n (repeat ' ')
|
paterson/interpreter
|
src/Interpreter.hs
|
bsd-3-clause
| 9,090 | 0 | 16 | 3,211 | 2,896 | 1,470 | 1,426 | 154 | 6 |
{-# LANGUAGE CPP, Rank2Types, ConstraintKinds, PatternGuards, ViewPatterns #-}
{-# LANGUAGE FlexibleContexts, FlexibleInstances, MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables, TupleSections #-}
{-# LANGUAGE DeriveDataTypeable, DeriveFunctor, DeriveFoldable, TypeFamilies #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE UndecidableInstances #-} -- see below
-- {-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -Wall #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-} -- TEMP
-- {-# OPTIONS_GHC -fno-warn-unused-binds #-} -- TEMP
----------------------------------------------------------------------
-- |
-- Module : HERMIT.Extras
--
-- Maintainer : [email protected]
-- Stability : experimental
--
-- Some definitions useful with HERMIT.
----------------------------------------------------------------------
-- #define WatchFailures
module HERMIT.Extras
( -- * Misc
Unop, Binop
-- * Core utilities
, unsafeShowPpr
, isType, exprType',exprTypeT, pairTy
, tcFind0, tcFind, tcFind2
, tcApp0, tcApp1, tcApp2
, isPairTC, isPairTy, isEitherTy
, isUnitTy, isBoolTy, isIntTy
, onCaseAlts, onAltRhs, unliftedType
, apps, apps', apps1', callSplitT, callNameSplitT, unCall, unCall1
, collectForalls, subst, isTyLam, setNominalRole_maybe
, isVarT, isLitT
, repr, varOccCount, oneOccT, castOccsSame
, exprAsConApp
-- * HERMIT utilities
, moduledName
, newIdT
, liftedKind, unliftedKind
, ReType, ReExpr, ReBind, ReAlt, ReProg, ReCore
, FilterH, FilterE, FilterTy, OkCM, TransformU
, findTyConT, tyConApp1T
, isTypeE, isCastE, isDictE, isCoercionE
, mkUnit, mkPair, mkLeft, mkRight, mkEither
, InCoreTC
, Observing, observeR', tries, triesL, scopeR, labeled
, lintExprR -- , lintExprDieR
, lintingExprR
, varLitE, uqVarName, fqVarName, typeEtaLong, simplifyE
, walkE , alltdE, anytdE, anybuE, onetdE, onebuE
, inAppTys, isAppTy, inlineWorkerR
, letFloatToProg
, concatProgs
, rejectR , rejectTypeR
, simplifyExprR, changedSynR, changedArrR
, showPprT, stashLabel, tweakLabel, saveDefT, findDefT
, unJustT, tcViewT, unFunCo
, lamFloatCastR, castFloatLamR, castCastR, unCastCastR, castTransitiveUnivR
, castFloatAppR',castFloatAppUnivR, castFloatCaseR, caseFloatR'
, caseWildR
, bashExtendedWithE, bashUsingE, bashE
, buildDictionaryT', buildTypeableT', simpleDict
, TransformM, RewriteM
, repeatN
, saveDefNoFloatT, dumpStashR, dropStashedLetR
, progRhsAnyR
, ($*), pairT, listT, unPairR
, externC
, normaliseTypeT, normalizeTypeT, optimizeCoercionR, optimizeCastR
, bindUnLetIntroR
-- , letFloatCaseAltR
, trivialExpr, letSubstTrivialR, betaReduceTrivialR
-- , pruneAltsExpr, pruneAltsR -- might remove
, extendTvSubstVars
, retypeExprR
, Tree(..), toTree, foldMapT, foldT
, SyntaxEq(..)
, regularizeType
) where
import Prelude hiding (id,(.),foldr)
import Data.Monoid (Monoid(..),(<>))
import Control.Category (Category(..),(>>>))
import Data.Functor ((<$>),(<$))
import Data.Foldable (Foldable(..))
import Control.Applicative (Applicative(..),liftA2,(<|>))
import Control.Monad ((<=<),unless)
import Control.Arrow (Arrow(..))
import Data.Maybe (catMaybes,fromMaybe)
import Data.List (intercalate,isPrefixOf)
import Text.Printf (printf)
import Data.Typeable (Typeable)
import Control.Monad.IO.Class (MonadIO)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Char (isUpper,isSpace)
import Data.String (fromString)
-- GHC
import Unique(hasKey)
import PrelNames (
liftedTypeKindTyConKey,unliftedTypeKindTyConKey,constraintKindTyConKey,
eitherTyConName)
import SimplCore (simplifyExpr)
import FamInstEnv (normaliseType)
import qualified Coercion
import OptCoercion (optCoercion)
import Type (substTy,substTyWith)
import TcType (isUnitTy,isBoolTy,isIntTy)
import Unify (tcUnifyTy)
-- import Language.KURE.Transform (apply)
import HERMIT.Core
( CoreProg(..),Crumb,bindsToProg,progToBinds,freeVarsExpr
, progSyntaxEq,bindSyntaxEq,defSyntaxEq,exprSyntaxEq
, altSyntaxEq,typeSyntaxEq,coercionSyntaxEq
, CoreDef(..),defToIdExpr, coercionAlphaEq,localFreeVarsExpr)
import HERMIT.Name (newIdH)
import HERMIT.Monad
(HermitM,HasHscEnv(..),HasHermitMEnv,getModGuts,RememberedName(..),saveDef,lookupDef,getStash)
import HERMIT.Context
( BoundVars(..),AddBindings(..),ReadBindings(..)
, HasEmptyContext(..), HasCoreRules(..)
, HermitC )
-- Note that HERMIT.Dictionary re-exports HERMIT.Dictionary.*
import HERMIT.Dictionary
( findIdT, findTyConT, callT, callNameT, simplifyR, letFloatTopR, letSubstR, betaReduceR
, observeR, bracketR, bashExtendedWithR, bashUsingR, bashR, wrongExprForm
, castFloatAppR
, caseFloatCastR, caseFloatCaseR, caseFloatAppR, caseFloatLetR
, unshadowR, lintExprT, inScope, inlineR, buildDictionaryT
, buildTypeable
, traceR
)
-- import HERMIT.Dictionary (traceR)
import HERMIT.GHC hiding (FastString(..),(<>),substTy)
import HERMIT.Kure hiding (apply)
import HERMIT.External (External,Extern(..),external,ExternalName)
import HERMIT.Name (HermitName)
{--------------------------------------------------------------------
Misc
--------------------------------------------------------------------}
-- | Unary transformation
type Unop a = a -> a
-- | Binary transformation
type Binop a = a -> Unop a
{--------------------------------------------------------------------
Core utilities
--------------------------------------------------------------------}
-- | 'showPpr' with global dynamic flags
unsafeShowPpr :: Outputable a => a -> String
unsafeShowPpr = showPpr unsafeGlobalDynFlags
onCaseAlts :: (ExtendCrumb c, ReadCrumb c, AddBindings c, Monad m) =>
Rewrite c m CoreAlt -> Rewrite c m CoreExpr
onCaseAlts r = caseAllR id id id (const r)
-- | Rewrite a case alternative right-hand side.
onAltRhs :: (Functor m, Monad m) =>
Rewrite c m CoreExpr -> Rewrite c m CoreAlt
onAltRhs r = do (con,vs,rhs) <- id
(con,vs,) <$> r $* rhs
-- Form an application to type and value arguments.
apps :: Id -> [Type] -> [CoreExpr] -> CoreExpr
apps f ts es
| tyArity f /= length ts =
error $ printf "apps: Id %s wants %d type arguments but got %d."
(fqVarName f) arity ntys
| otherwise = mkApps (varToCoreExpr f) (map Type ts ++ es)
where
arity = tyArity f
ntys = length ts
-- Note: With unlifted types, mkCoreApps might make a case expression.
-- If we don't want to, maybe use mkApps.
-- Number of type arguments.
tyArity :: Id -> Int
tyArity = length . fst . splitForAllTys . varType
-- exprType gives an obscure warning when given a Type expression.
exprType' :: CoreExpr -> Type
exprType' (Type {}) = error "exprType': given a Type"
exprType' e = exprType e
-- Like 'exprType', but fails if given a type.
exprTypeT :: Monad m => Transform c m CoreExpr Type
exprTypeT =
do e <- idR
guardMsg (not (isType e)) "exprTypeT: given a Type"
return (exprType' e)
isType :: CoreExpr -> Bool
isType (Type {}) = True
isType _ = False
pairTy :: Binop Type
pairTy a b = mkBoxedTupleTy [a,b]
tcApp0 :: TyCon -> Type
tcApp0 tc = TyConApp tc []
tcApp1 :: TyCon -> Unop Type
tcApp1 tc a = TyConApp tc [a]
tcApp2 :: TyCon -> Binop Type
tcApp2 tc a b = TyConApp tc [a,b]
isPairTC :: TyCon -> Bool
isPairTC tc = isBoxedTupleTyCon tc && tupleTyConArity tc == 2
isPairTy :: Type -> Bool
isPairTy (TyConApp tc [_,_]) = isBoxedTupleTyCon tc
isPairTy _ = False
isEitherTy :: Type -> Bool
isEitherTy (TyConApp tc [_,_]) = tyConName tc == eitherTyConName
isEitherTy _ = False
-- Found in TcType
#if 0
isUnitTy :: Type -> Bool
isUnitTy (coreView -> Just t) = isUnitTy t -- experiment
isUnitTy (TyConApp tc []) = tc == unitTyCon
isUnitTy _ = False
isBoolTy :: Type -> Bool
isBoolTy (TyConApp tc []) = tc == boolTyCon
isBoolTy _ = False
#endif
liftedKind :: Kind -> Bool
liftedKind (TyConApp tc []) =
any (tc `hasKey`) [liftedTypeKindTyConKey, constraintKindTyConKey]
liftedKind _ = False
unliftedKind :: Kind -> Bool
unliftedKind (TyConApp tc []) = tc `hasKey` unliftedTypeKindTyConKey
unliftedKind _ = False
-- TODO: Switch to isLiftedTypeKind and isUnliftedTypeKind from Kind (in GHC).
-- When I tried earlier, I lost my inlinings. Investigate!
-- <https://github.com/conal/type-encode/issues/1>
unliftedType :: Type -> Bool
unliftedType = unliftedKind . typeKind
splitTysVals :: [Expr b] -> ([Type], [Expr b])
splitTysVals (Type ty : rest) = first (ty :) (splitTysVals rest)
splitTysVals rest = ([],rest)
collectForalls :: Type -> ([Var], Type)
collectForalls ty = go [] ty
where
go vs (ForAllTy v t') = go (v:vs) t'
go vs t = (reverse vs, t)
-- TODO: Rewrite collectTypeArgs and collectForalls as unfolds and refactor.
-- | Substitute new subexpressions for variables in an expression
subst :: [(Id,CoreExpr)] -> Unop CoreExpr
subst ps = substExpr (error "subst: no SDoc") (foldr add emptySubst ps)
where
add (v,new) sub = extendIdSubst sub v new
isTyLam :: CoreExpr -> Bool
isTyLam (Lam v _) = isTyVar v
isTyLam _ = False
type ExtendCrumb c = ExtendPath c Crumb
type ReadCrumb c = ReadPath c Crumb
isVarT :: (Monad m, ExtendCrumb c) =>
Transform c m CoreExpr ()
isVarT = varT successT
isLitT :: (Monad m, ExtendCrumb c) =>
Transform c m CoreExpr ()
isLitT = litT successT
#if __GLASGOW_HASKELL__ < 709
-- | Abbreviation for the 'Representational' role
repr :: Role
repr = Representational
-- | Number of occurrences of a non-type variable
varOccCount :: Var -> CoreExpr -> Int
varOccCount v = occs
where
occs :: CoreExpr -> Int
occs (Var u) | u == v = 1
| otherwise = 0
occs (Lit _) = 0
occs (App p q) = occs p + occs q
occs (Lam _ e) = occs e -- assumes no shadowning
occs (Let b e) = bindOccs b + occs e
occs (Case e _ _ alts) = occs e + sum (map altOccs alts)
occs (Cast e _) = occs e
occs (Tick _ e) = occs e
occs (Type _) = 0
occs (Coercion _) = 0
altOccs (_,_,e) = occs e
bindOccs (NonRec _ e) = occs e
bindOccs (Rec bs) = sum (map (occs . snd) bs)
-- TODO: stricter version
#if 0
-- | Number of occurrences of a non-type variable
varOccCount :: Var -> CoreExpr -> Int
varOccCount v = occs 0
where
occs !n (Var u) | u == v = n+1
occs !n (App p q) = occs (occs n p) q
occs !n (Lam _ e) = occs n e -- assumes no shadowning
occs !n (Cast e _) = occs n e
occs !n (Tick _ e) = occs n e
occs !n _ = n
#endif
-- | Matches a let binding with exactly one occurrence of the variable.
oneOccT :: FilterE
oneOccT =
do Let (NonRec v _) body <- id
guardMsg (varOccCount v body <= 1) "oneOccT: multiple occurrences"
data VarCasts = NoCast | Casts Coercion | FailCast
instance Monoid VarCasts where
mempty = NoCast
NoCast `mappend` c = c
c `mappend` NoCast = c
FailCast `mappend` _ = FailCast
_ `mappend` FailCast = FailCast
Casts co `mappend` Casts co'
| co `coreEqCoercion` co' = Casts co
| otherwise = FailCast
-- | See if the given variable occurs only with casts having the same coercion.
-- If so, yield that coercion.
castOccsSame :: Var -> CoreExpr -> Maybe Coercion
castOccsSame v e =
case castOccsSame' v e of
Casts co -> Just co
_ -> Nothing
castOccsSame' :: Var -> CoreExpr -> VarCasts
castOccsSame' v = occs
where
occs :: CoreExpr -> VarCasts
occs (Var _) = mempty
occs (Lit _) = mempty
occs (App p q) = occs p <> occs q
occs (Lam _ e) = occs e -- assumes no shadowning
occs (Let b e) = bindOccs b <> occs e
occs (Case e _ _ alts) = occs e <> foldMap altOccs alts
occs (Cast (Var u) co) | u == v = Casts co
occs (Cast e _) = occs e
occs (Tick _ e) = occs e
occs (Type _) = mempty
occs (Coercion _) = mempty
altOccs (_,_,e) = occs e
bindOccs (NonRec _ e) = occs e
bindOccs (Rec bs) = foldMap (occs . snd) bs
{--------------------------------------------------------------------
Borrowed from GHC HEAD >= 7.9
--------------------------------------------------------------------}
-- Converts a coercion to be nominal, if possible.
-- See also Note [Role twiddling functions]
setNominalRole_maybe :: Coercion -> Maybe Coercion
setNominalRole_maybe co
| Nominal <- coercionRole co = Just co
setNominalRole_maybe (SubCo co) = Just co
setNominalRole_maybe (Refl _ ty) = Just $ Refl Nominal ty
setNominalRole_maybe (TyConAppCo Representational tc coes)
= do { cos' <- mapM setNominalRole_maybe coes
; return $ TyConAppCo Nominal tc cos' }
setNominalRole_maybe (UnivCo Representational ty1 ty2) = Just $ UnivCo Nominal ty1 ty2
-- We do *not* promote UnivCo Phantom, as that's unsafe.
-- UnivCo Nominal is no more unsafe than UnivCo Representational
setNominalRole_maybe (TransCo co1 co2)
= TransCo <$> setNominalRole_maybe co1 <*> setNominalRole_maybe co2
setNominalRole_maybe (AppCo co1 co2)
= AppCo <$> setNominalRole_maybe co1 <*> pure co2
setNominalRole_maybe (ForAllCo tv co)
= ForAllCo tv <$> setNominalRole_maybe co
setNominalRole_maybe (NthCo n co)
= NthCo n <$> setNominalRole_maybe co
setNominalRole_maybe (InstCo co ty)
= InstCo <$> setNominalRole_maybe co <*> pure ty
setNominalRole_maybe _ = Nothing
#else
#endif
-- | Succeeds if we are looking at an application of a data constructor.
exprAsConApp :: CoreExpr -> Maybe (DataCon, [Type], [CoreExpr])
exprAsConApp e = exprIsConApp_maybe (in_scope, idUnfolding) e
where
in_scope =mkInScopeSet
(mkVarEnv [ (v,v) | v <- varSetElems (localFreeVarsExpr e) ])
{--------------------------------------------------------------------
HERMIT utilities
--------------------------------------------------------------------}
newIdT :: String -> TransformM c Type Id
newIdT nm = do ty <- id
constT (newIdH nm ty)
-- Common context & monad constraints
-- type OkCM c m =
-- ( HasDynFlags m, Functor m, MonadThings m, MonadCatch m
-- , BoundVars c, HasModGuts m )
type OkCM c m =
( BoundVars c, HasDynFlags m, HasHscEnv m, HasHermitMEnv m
, Functor m, MonadCatch m, MonadIO m, MonadThings m )
type TransformU b = forall c m a. OkCM c m => Transform c m a b
type TransformM c a b = Transform c HermitM a b
type RewriteM c a = TransformM c a a
-- Apply a named id to type and value arguments.
apps' :: HermitName -> [Type] -> [CoreExpr] -> TransformU CoreExpr
apps' s ts es = (\ i -> apps i ts es) <$> findIdT s
-- Apply a named id to type and value arguments.
apps1' :: HermitName -> [Type] -> CoreExpr -> TransformU CoreExpr
apps1' s ts = apps' s ts . (:[])
type ReType = RewriteH Type
type ReProg = RewriteH CoreProg
type ReBind = RewriteH CoreBind
type ReExpr = RewriteH CoreExpr
type ReAlt = RewriteH CoreAlt
type ReCore = RewriteH Core
#if 0
-- | Lookup the name in the context first, then, failing that, in GHC's global
-- reader environment.
findTyConT :: String -> TransformU TyCon
findTyConT nm =
prefixFailMsg ("Cannot resolve name " ++ nm ++ "; ") $
contextonlyT (findTyConMG nm)
findTyConMG :: OkCM c m => String -> c -> m TyCon
findTyConMG nm _ =
do rdrEnv <- mg_rdr_env <$> getModGuts
case filter isTyConName $ findNamesFromString rdrEnv nm of
[n] -> lookupTyCon n
ns -> do dynFlags <- getDynFlags
fail $ show (length ns)
++ " matches found: "
++ intercalate ", " (showPpr dynFlags <$> ns)
#endif
-- TODO: remove context argument, simplify OkCM, etc. See where it leads.
-- <https://github.com/conal/type-encode/issues/2>
-- TODO: Use findTyConT in HERMIT.Dictionary.Name instead of above.
tcFind :: (TyCon -> b) -> HermitName -> TransformU b
tcFind h = fmap h . findTyConT
tcFind0 :: HermitName -> TransformU Type
tcFind0 = tcFind tcApp0
tcFind2 :: HermitName -> TransformU (Binop Type)
tcFind2 = tcFind tcApp2
callSplitT :: MonadCatch m =>
Transform c m CoreExpr (CoreExpr, [Type], [CoreExpr])
callSplitT = do (f,args) <- callT
let (tyArgs,valArgs) = splitTysVals args
return (f,tyArgs,valArgs)
callNameSplitT ::
( MonadCatch m, MonadIO m, MonadThings m, HasHscEnv m, HasHermitMEnv m
, BoundVars c ) =>
HermitName -> Transform c m CoreExpr (CoreExpr, [Type], [Expr CoreBndr])
callNameSplitT name = do (f,args) <- callNameT name
let (tyArgs,valArgs) = splitTysVals args
return (f,tyArgs,valArgs)
-- TODO: refactor with something like HERMIT's callPredT
-- | Uncall a named function
unCall :: ( MonadCatch m, MonadIO m, MonadThings m, HasHscEnv m, HasHermitMEnv m
, BoundVars c ) =>
HermitName -> Transform c m CoreExpr [CoreExpr]
unCall f = do (_f,_tys,args) <- callNameSplitT f
return args
-- | Uncall a named function of one value argument, dropping initial type args.
unCall1 :: HermitName -> ReExpr
unCall1 f = do [e] <- unCall f
return e
mkUnit :: TransformU CoreExpr
mkUnit = return (mkCoreTup [])
mkPair :: TransformU (Binop CoreExpr)
mkPair = return $ \ u v -> mkCoreTup [u,v]
moduledName :: String -> String -> HermitName
moduledName modName = fromString . (modName ++) . ('.' :)
eitherName :: String -> HermitName
eitherName = moduledName "Data.Either"
mkLR :: String -> TransformU (Type -> Type -> Unop CoreExpr)
mkLR name = do f <- findIdT (eitherName name)
return $ \ tu tv a -> apps f [tu,tv] [a]
mkLeft :: TransformU (Type -> Type -> Unop CoreExpr)
mkLeft = mkLR "Left"
mkRight :: TransformU (Type -> Type -> Unop CoreExpr)
mkRight = mkLR "Right"
mkEither :: TransformU (Binop Type)
mkEither = tcFind2 (eitherName "Either")
type InCoreTC t = Injection t CoreTC
-- Whether we're observing rewrites
type Observing = Bool
observeR' :: (ReadBindings c, ReadCrumb c) =>
Observing -> InCoreTC t => String -> RewriteM c t
observeR' True = observeR
observeR' False = const idR
tries :: (MonadCatch m, InCoreTC t) =>
[Rewrite c m t] -> Rewrite c m t
tries = foldr (<+) ({- observeR' "Unhandled" >>> -} fail "unhandled")
triesL :: (ReadBindings c, ReadCrumb c, InCoreTC t) =>
Observing -> [(String,RewriteM c t)] -> RewriteM c t
triesL observing = tries . map (labeled observing)
-- scopeR :: InCoreTC a => String -> Unop (RewriteM c a)
scopeR :: String -> Unop (TransformM c a b)
scopeR label r = traceR ("Try " ++ label ) >>>
-- r
(r <+ (traceR (label ++ " failed") >>> fail "scopeR"))
labeled :: (ReadBindings c, ReadCrumb c, InCoreTC a) =>
Observing -> (String, RewriteM c a) -> RewriteM c a
labeled observing (label,r) =
#ifdef WatchFailures
scopeR label $
#endif
(if observing then bracketR label else id) r
lintExprR :: (Functor m, Monad m, HasDynFlags m, BoundVars c) =>
Rewrite c m CoreExpr
-- lintExprR = (id &&& lintExprT) >>> arr fst
lintExprR = lintExprT >> id
#if 0
-- lintExprR = ifM (True <$ lintExprT) id (fail "lint failure")
lintExprDieR :: (Functor m, MonadCatch m, HasDynFlags m, BoundVars c) =>
Rewrite c m CoreExpr
lintExprDieR = lintExprR `catchM` error
-- lintExprT :: (BoundVars c, Monad m, HasDynFlags m) =>
-- Transform c m CoreExpr String
#endif
-- | Apply a rewrite rule. If it succeeds but the result fails to pass
-- core-lint, show the before and after (via 'bracketR') and die with the
-- core-lint error message.
lintingExprR :: ( ReadBindings c, ReadCrumb c
, BoundVars c, AddBindings c, ExtendCrumb c, HasEmptyContext c -- for unshadowR
) =>
String -> Unop (Rewrite c HermitM CoreExpr)
lintingExprR msg rr =
do e <- idR
e' <- rr'
res <- attemptM (lintExprT $* e')
either (\ lintMsg -> do _ <- bracketR ("Lint check " ++ msg) rr' $* e
error ("Lint failure: " ++ lintMsg)
-- traceR lintMsg
)
(const $ do unless (isType e || isType e') (
do let t = exprType' e
t' = exprType' e'
unless ({- True || -} t `eqType` t') $ -- See 2015-11-27 notes
do _ <- bracketR ("Type changed! " ++ msg) rr' $* e
st <- showPprT $* t
st' <- showPprT $* t'
error (printf "OOPS! Type changed.\n Old: %s\n New: %s"
(dropModules st) (dropModules st')))
return e')
res
where
rr' = rr >>> extractR (tryR unshadowR)
-- -- Lint both before and after
-- lintingExprR2 :: ( ReadBindings c, ReadCrumb c
-- , BoundVars c, AddBindings c, ExtendCrumb c, HasEmptyContext c -- for unshadowR
-- ) =>
-- String -> Unop (Rewrite c HermitM CoreExpr)
-- lintingExprR2 msg rr =
-- lintingExprR ("Before " ++ msg) id >> lintingExprR ("After " ++ msg) rr
-- TODO: Compare types before and after.
-- TODO: Eliminate labeled.
-- labeledR' :: InCoreTC a => Bool -> String -> Unop (RewriteH a)
-- labeledR' debug label r =
-- do c <- contextT
-- labeled debug (label,r)
-- mkVarName :: MonadThings m => Transform c m Var (CoreExpr,Type)
-- mkVarName = contextfreeT (mkStringExpr . uqName . varName) &&& arr varType
varLitE :: Var -> CoreExpr
varLitE = Lit . mkMachString . uqVarName
uqVarName :: Var -> String
uqVarName = unqualifiedName . varName
fqVarName :: Var -> String
fqVarName = qualifiedName . varName
-- Fully type-eta-expand, i.e., ensure that every leading forall has a matching
-- (type) lambdas.
typeEtaLong :: ReExpr
typeEtaLong = readerT $ \ e ->
if isTyLam e then
lamAllR idR typeEtaLong
else
expand
where
-- Eta-expand enough for lambdas to match foralls.
expand = do e@(collectForalls . exprType' -> (tvs,_)) <- idR
return $ mkLams tvs (mkApps e ((Type . TyVarTy) <$> tvs))
simplifyE :: ReExpr
simplifyE = extractR simplifyR
walkE :: Unop ReCore -> Unop ReExpr
walkE trav r = extractR (trav (promoteR r :: ReCore))
alltdE, anytdE, anybuE, onetdE, onebuE :: Unop ReExpr
alltdE = walkE alltdR
anytdE = walkE anytdR
anybuE = walkE anybuR
onetdE = walkE onetdR
onebuE = walkE onebuR
-- TODO: Try rewriting more gracefully, testing isForAllTy first and
-- maybeEtaExpandR
isWorkerT :: FilterE
isWorkerT = do Var (isWorker -> True) <- id
return ()
isWorker :: Id -> Bool
isWorker = ("$W" `isPrefixOf`) . uqVarName
inlineWorkerR :: ReExpr
inlineWorkerR = isWorkerT >> inlineR
-- Apply a rewriter inside type lambdas.
inAppTys :: Unop ReExpr
inAppTys r = r'
where
r' = readerT $ \ e -> if isAppTy e then appAllR r' idR else r
isAppTy :: CoreExpr -> Bool
isAppTy (App _ (Type _)) = True
isAppTy _ = False
letFloatToProg :: (BoundVars c, AddBindings c, ReadCrumb c, ExtendCrumb c) =>
TransformM c CoreBind CoreProg
letFloatToProg = arr (flip ProgCons ProgNil) >>> tryR letFloatTopR
-- TODO: alias for these c constraints.
concatProgs :: [CoreProg] -> CoreProg
concatProgs = bindsToProg . concatMap progToBinds
-- | Reject if condition holds. Opposite of 'acceptR'
rejectR :: Monad m => (a -> Bool) -> Rewrite c m a
rejectR f = acceptR (not . f)
-- | Reject if condition holds on an expression's type.
rejectTypeR :: Monad m => (Type -> Bool) -> Rewrite c m CoreExpr
rejectTypeR f = rejectR (f . exprType')
-- | Succeed only if the given rewrite actually changes the term
changedSynR :: (MonadCatch m, SyntaxEq a) => Unop (Rewrite c m a)
changedSynR = changedByR (=~=)
-- | Succeed only if the given rewrite actually changes the term
changedArrR :: (MonadCatch m, SyntaxEq a) => Unop a -> Rewrite c m a
changedArrR = changedSynR . arr
-- | Use GHC expression simplifier and succeed if different. Sadly, the check
-- gives false positives, which spoils its usefulness.
simplifyExprR :: ReExpr
simplifyExprR = changedSynR $
prefixFailMsg "simplify-expr failed: " $
contextfreeT $ \ e ->
do dflags <- getDynFlags
liftIO $ simplifyExpr dflags e
-- | Get a GHC pretty-printing
showPprT :: (HasDynFlags m, Outputable a, Monad m) =>
Transform c m a String
showPprT = do a <- id
dynFlags <- constT getDynFlags
return (showPpr dynFlags a)
-- | Make a stash label out of an outputtable
stashLabel :: (Functor m, Monad m, HasDynFlags m, Outputable a) =>
Transform c m a String
stashLabel = tweakLabel <$> showPprT
-- Replace whitespace runs with underscores
tweakLabel :: Unop String
tweakLabel = intercalate "_" . words
dropModules :: Unop String
dropModules = unwords . map dropMods . words
where
dropMods (c:rest) | not (isUpper c) = c : dropMods rest
dropMods (break (== '.') -> (_,'.':rest)) = dropMods rest
dropMods s = s
memoChat :: (ReadBindings c, ReadCrumb c, Injection a CoreTC) =>
Bool -> String -> String -> RewriteM c a
memoChat brag pre lab =
if brag then
chat ("memo " ++ pre ++ ": " ++ lab)
else
id
where
chat = traceR
-- observeR
-- | Save a definition for future use.
saveDefT :: (ReadBindings c, ReadCrumb c) =>
Observing -> String -> TransformM c CoreDef ()
saveDefT brag lab =
do def@(Def _ e) <- id
constT (saveDef (RememberedName lab) def) >>> (memoChat brag "save" lab $* e >> return ())
findDefT :: (ReadBindings c, ReadCrumb c) =>
Observing -> String -> TransformM c a CoreExpr
findDefT brag lab =
constT (defExpr <$> lookupDef (RememberedName lab)) >>> memoChat brag "hit" lab
where
defExpr (Def _ expr) = expr
saveDefNoFloatT :: (ReadBindings c, ReadCrumb c) =>
Observing -> String -> TransformM c CoreExpr ()
saveDefNoFloatT brag lab =
do e <- id
v <- newIdT bogusDefName $* exprType' e
saveDefT brag lab $* Def v e
-- | unJust as transform. Fails on Nothing.
-- Already in Kure?
unJustT :: Monad m => Transform c m (Maybe a) a
unJustT = do Just x <- idR
return x
-- | GHC's tcView as a rewrite
tcViewT :: RewriteM c Type
tcViewT = unJustT . arr tcView
-- | Dissect a function coercion into role, domain, and range
unFunCo :: Coercion -> Maybe (Role,Coercion,Coercion)
unFunCo (TyConAppCo role tc [domCo,ranCo])
| isFunTyCon tc = Just (role,domCo,ranCo)
unFunCo _ = Nothing
-- | cast (\ v -> e) (domCo -> ranCo)
-- ==> (\ v' -> cast (e[Var v <- cast (Var v') (SymCo domCo)]) ranCo)
-- where v' :: a' if the whole expression had type a' -> b'.
-- Warning, to avoid looping, don't combine with 'castFloatLamR'.
lamFloatCastR :: ReExpr
lamFloatCastR = -- labelR "lamFloatCastR" $
do Cast (Lam v e) (unFunCo -> Just (_,domCo,ranCo)) <- idR
Just (domTy,_) <- arr (splitFunTy_maybe . exprType')
v' <- constT $ newIdH (uqVarName v) domTy
let e' = subst [(v, Cast (Var v') (SymCo domCo))] e
return (Lam v' (Cast e' ranCo))
-- | (\ x :: a -> u `cast` co) ==> (\ x -> u) `cast` (<a> -> co)
-- Warning, to avoid looping, don't combine with 'lamFloatCastR'.
castFloatLamR :: ReExpr
castFloatLamR =
do Lam x (u `Cast` co) <- id
return $
Lam x u `mkCast` (mkFunCo repr (mkReflCo repr (varType x)) co)
-- TODO: Should I check the role?
-- | cast (cast e co) co' ==> cast e (mkTransCo co co')
castCastR :: ReExpr
castCastR = -- labelR "castCastR" $
do Cast (Cast e co) co' <- idR
return (Cast e (mkTransCo co co'))
-- e `cast` (co1 ; co2) ==> (e `cast` co1) `cast` co2
-- Handle with care. Don't mix with its inverse, 'castCastR'.
unCastCastR :: Monad m => Rewrite c m CoreExpr
unCastCastR = do e `Cast` (co1 `TransCo` co2) <- idR
return ((e `Cast` co1) `Cast` co2)
-- Collapse transitive coercions when the latter is universal.
-- TODO: Maybe re-associate.
castTransitiveUnivR :: ReExpr
castTransitiveUnivR =
do Cast e (TransCo (coercionKind -> Pair t _) (UnivCo r _ t')) <- id
return $ mkCast e (mkUnivCo r t t')
-- Like 'castFloatAppR', but handles transitivy coercions.
castFloatAppR' :: (MonadCatch m, ExtendCrumb c) =>
Rewrite c m CoreExpr
castFloatAppR' = castFloatAppR <+
-- castFloatAppUnivR <+
(appAllR unCastCastR id >>> castFloatAppR')
-- | Like castFloatApp but handles *all* coercions, and makes universal coercions.
-- (f `cast` (co :: (a -> b) ~ (a' -> b'))) e ==>
-- f (e `cast` (univ :: a' ~ a)) `cast` (univ :: b ~ b')
-- or
-- (f `cast` (co :: (forall a. b) ~ (forall a. b'))) (Type t) ==
-- f e `cast` (univ :: [a := t]b ~ [a := t]b')
castFloatAppUnivR :: MonadCatch m => Rewrite c m CoreExpr
castFloatAppUnivR =
do App (Cast fun co) arg <- id
let Pair ty ty' = coercionKind co
role = coercionRole co
(do Just (a ,b ) <- return $ splitFunTy_maybe ty
Just (a',b') <- return $ splitFunTy_maybe ty'
-- guardMsg (a =~= a')
-- "castFloatAppUnivR: cast changes domain types"
return $
mkCast (App fun (mkCast arg (mkUnivCo role a' a)))
(mkUnivCo role b b'))
<+
(do Just (a ,b ) <- return $ splitForAllTy_maybe ty
Just (a',b') <- return $ splitForAllTy_maybe ty'
Type tyArg <- return arg
guardMsg (a =~= a')
"castFloatAppUnivR: cast changes type argument"
return $
let sub = substTyWith [a] [tyArg] in
mkCast (App fun arg) (mkUnivCo role (sub b) (sub b')))
-- | case e of p -> (rhs `cast` co) ==> (case e of p -> rhs) `cast` co
-- Inverse to 'caseFloatCastR', so don't use both rules!
castFloatCaseR :: ReExpr
castFloatCaseR =
do Case scrut wild _ [(con,binds,rhs `Cast` co)] <- id
return $
Case scrut wild (pFst (coercionKind co)) [(con,binds,rhs)]
`Cast` co
-- | Like caseFloatR, but excludes caseFloatCastR, so we can use castFloatCaseR
-- Note: does NOT include caseFloatArg
caseFloatR' :: (ExtendCrumb c, ReadCrumb c, AddBindings c, ReadBindings c) => Rewrite c HermitM CoreExpr
caseFloatR' = setFailMsg "Unsuitable expression for Case floating." $
caseFloatAppR <+ caseFloatCaseR <+ caseFloatLetR
-- | case scrut of wild t { _ -> body }
-- ==> let wild = scrut in body
-- May be followed by let-elimination.
-- Warning: does not capture GHC's intent to reduce scrut to WHNF.
caseWildR :: ReExpr
caseWildR = -- labeledR "reifyCaseWild" $
do Case scrut wild _bodyTy [(DEFAULT,[],body)] <- idR
return $ Let (NonRec wild scrut) body
-- | Like bashExtendedWithR, but for expressions
bashExtendedWithE :: [ReExpr] -> ReExpr
bashExtendedWithE rs = extractR (bashExtendedWithR (promoteR <$> rs))
-- | Like bashUsingR, but for expressions
bashUsingE :: [ReExpr] -> ReExpr
bashUsingE rs = extractR (bashUsingR (promoteR <$> rs))
-- | bashE for expressions
bashE :: ReExpr
bashE = extractR bashR
type FilterH a = TransformH a ()
type FilterE = FilterH CoreExpr
type FilterTy = FilterH Type
-- | Is the expression a type?
isTypeE :: FilterE
isTypeE = typeT successT
-- | Is the expression a cast?
isCastE :: FilterE
isCastE = castT id id mempty
-- | Is the expression a dictionary?
isDictE :: FilterE
isDictE = guardT . (isDictTy <$> exprTypeT)
-- | Is the expression a coercion?
isCoercionE :: FilterE
isCoercionE = coercionT mempty
-- | Like tyConAppT, but for single type argument.
tyConApp1T :: (ExtendCrumb c, Monad m) =>
Transform c m TyCon a -> Transform c m KindOrType b -> (a -> b -> z)
-> Transform c m Type z
tyConApp1T ra rb h =
do TyConApp _ [_] <- id
tyConAppT ra (const rb) (\ a [b] -> h a b)
modFailMsgM :: MonadCatch m => (String -> m String) -> m a -> m a
modFailMsgM f ma = ma `catchM` (fail <=< f)
setFailMsgM :: MonadCatch m => m String -> m a -> m a
setFailMsgM msgM = modFailMsgM (const msgM)
-- | Like 'buildDictionaryT' but simplifies with 'bashE'.
buildDictionaryT' :: TransformH Type CoreExpr
buildDictionaryT' =
{- observeR "buildDictionaryT' (pre)" >>> -}
( setFailMsgM (("Couldn't build dictionary for "++) <$> showPprT ) $
tryR bashE . {- scopeR "buildDictionaryT" -} buildDictionaryT )
-- buildDictionaryT' = setFailMsg "Couldn't build dictionary" $
-- tryR bashE . buildDictionaryT
-- Try again but with multiple type arguments.
simpleDict :: HermitName -> TransformH [Type] CoreExpr
simpleDict name =
do tc <- findTyConT name
buildDictionaryT' . arr (TyConApp tc)
-- simpleDict1 :: HermitName -> TransformH Type CoreExpr
-- simpleDict1 name = simpleDict name . arr (:[])
-- | Build and simplify a 'Typeable' instance
buildTypeableT' :: TransformH Type CoreExpr
#if 0
buildTypeableT' =
do ty <- id
tc <- findTyConT "Data.Typeable.Typeable"
buildDictionaryT' $* TyConApp tc [typeKind ty, ty]
-- The findTyConT is failing. Hm!
#else
-- Adapted from buildDictionaryT
buildTypeableT' =
tryR bashE .
prefixFailMsg "buildTypeableT failed: " (
contextfreeT $ \ ty ->
do (i,bnds) <- buildTypeable ty
guardMsg (notNull bnds) "no dictionary bindings generated."
return $ mkCoreLets bnds (varToCoreExpr i) )
#endif
-- | Repeat a rewriter exactly @n@ times.
repeatN :: Monad m => Int -> Unop (Rewrite c m a)
repeatN n = serialise . replicate n
-- | Use in a stashed 'Def' to say that we don't want to dump.
bogusDefName :: String
bogusDefName = "$bogus-def-name$"
dropBogus :: Unop (Map Id CoreExpr)
dropBogus = Map.filterWithKey (\ v _ -> uqVarName v /= bogusDefName)
-- | Dump the stash of definitions.
dumpStashR :: RewriteH CoreProg
dumpStashR = do stashed <- stashIdMapT
already <- arr progBound
let new = dropBogus (Map.difference stashed already)
-- Drop these let bindings from program before extending.
progRhsAnyR (anybuE (dropLets new)) -- or anytdR (repeat (dropLets new))
>>> arr (\ prog -> foldr add prog (Map.toList new))
where
add (v,rhs) = ProgCons (NonRec v rhs)
-- We only remove let bindings from the top-level of a definition.
-- They get floated there.
-- TODO: Drop unused stashed bindings.
dropStashedLetR :: ReExpr
dropStashedLetR = stashIdMapT >>= dropLets
-- Rewrite the right-hand sides of top-level definitions
progRhsAnyR :: ReExpr -> RewriteH CoreProg
progRhsAnyR r = progBindsAnyR (const (nonRecOrRecAllR id r))
where
nonRecOrRecAllR p q =
recAllR (const (defAllR p q)) <+ nonRecAllR p q
-- (anybuE (dropLets new))
-- TODO: Handle recursive definition groups also.
-- reifyProg = progBindsT (const (tryR reifyDef >>> letFloatToProg)) concatProgs
-- progBindsAllR :: (ExtendPath c Crumb, ReadPath c Crumb, AddBindings c, MonadCatch m) => (Int -> Rewrite c m CoreBind) -> Rewrite c m CoreProg
-- NOTE: I'm converting the stash from a map over RememberedName to a map over Id.
-- Look for a better way.
progBound :: CoreProg -> Map Id CoreExpr
progBound = foldMap bindNames . progToBinds
where
bindNames (NonRec v e) = Map.singleton v e
bindNames (Rec bs) = Map.fromList bs
stashIdMapT :: TransformM c a (Map Id CoreExpr)
stashIdMapT =
(Map.fromList . Map.elems . fmap defToIdExpr) <$> constT getStash
#if 1
dropLets :: Monad m => Map Id CoreExpr -> Rewrite c m CoreExpr
dropLets defs = dropLetPred (flip Map.member defs)
dropLetPred :: Monad m => (Id -> Bool) -> Rewrite c m CoreExpr
dropLetPred f =
do Let (NonRec v _) body <- id
guardMsg (f v) "dropLets: doesn't satisfy predicate"
return body
#else
-- | Drop a 'let' binding if the variable is already bound. Assumes that the
-- outer matches the inner, but doesn't check. Useful with 'dumpStash'.
dropRedundantLetR :: ReExpr
dropRedundantLetR =
do Let (NonRec v _) body <- id
contextonlyT $ \ c ->
guardMsg (inScope c v) "dropRedundantLet: out of scope"
return body
#endif
-- Experimental utilities
infixr 8 $*
($*) :: Monad m => Transform c m a b -> a -> Transform c m q b
t $* x = t . return x
pairT :: ReExpr -> ReExpr -> ReExpr
pairT ra rb =
do [_,_,a,b] <- snd <$> callNameT "GHC.Tuple.(,)"
liftA2 pair (ra $* a) (rb $* b)
where
pair x y = mkCoreTup [x,y]
listT :: Monad m => [Transform c m a b] -> Transform c m [a] [b]
listT rs =
do es <- id
guardMsg (length rs == length es) "listT: length mismatch"
sequence (zipWith ($*) rs es)
unPairR :: ( Functor m, MonadCatch m, MonadThings m, MonadIO m
, HasHermitMEnv m, HasHscEnv m, BoundVars c ) =>
Transform c m CoreExpr (CoreExpr,CoreExpr)
unPairR = do [_,_,a,b] <- snd <$> callNameT "GHC.Tuple.(,)"
return (a,b)
externC :: Injection a Core =>
ExternalName -> RewriteH a -> String -> External
externC name rew help =
external name (promoteR rew :: ReCore) [help]
-- | Normalize a type, giving coercion and result type.
-- Fails if already normalized (rather than returning 'ReflCo').
normaliseTypeT :: (MonadIO m, HasHscEnv m, HasHermitMEnv m) =>
Role -> Transform c m Type (Coercion, Type)
normaliseTypeT r = do
envs <- constT $
do guts <- getModGuts
eps <- getHscEnv >>= liftIO . hscEPS
return (eps_fam_inst_env eps, mg_fam_inst_env guts)
res@(co,_) <- arr (normaliseType envs r)
guardMsg (not (isReflCo co)) "normaliseTypeT: already normal"
return res
-- Adapted from Andrew Farmer's code.
-- | Alias for 'normalizeTypeT'.
normalizeTypeT :: (MonadIO m, HasHscEnv m, HasHermitMEnv m) =>
Role -> Transform c m Type (Coercion, Type)
normalizeTypeT = normaliseTypeT
-- | Optimize a coercion.
optimizeCoercionR :: RewriteM c Coercion
optimizeCoercionR = changedArrR (optCoercion emptyCvSubst)
-- | Optimize a cast.
optimizeCastR :: ExtendCrumb c => RewriteM c CoreExpr
optimizeCastR = castAllR id optimizeCoercionR
-- | x = (let y = e in y) ==> x = e
bindUnLetIntroR :: ReBind
bindUnLetIntroR =
do NonRec x (Let (NonRec y e) (Var ((== y) -> True))) <- id
return (NonRec x e)
-- Now in HERMIT
#if 0
-- | Float a let out of a case alternative:
--
-- case foo of { ... ; p -> let x = u in v ; ... } ==>
-- let x = u in case foo of { ... ; p -> v ; ... }
--
-- where no variable in `p` occurs freely in `u`, and where `x` is not one of
-- the variables in `p`.
letFloatCaseAltR :: ReExpr
letFloatCaseAltR =
do Case scrut w ty alts <- id
(b,alts') <- letFloatOneAltR alts
return $ Let b (Case scrut w ty alts')
-- Perform the first safe let-floating out of a case alternative
letFloatOneAltR :: [CoreAlt] -> TransformH x (CoreBind,[CoreAlt])
letFloatOneAltR [] = fail "no alternatives safe to let-float"
letFloatOneAltR (alt:rest) =
(do (bind,alt') <- letFloatAltR alt
return (bind,alt':rest))
<+
(second (alt :) <$> letFloatOneAltR rest)
-- (p -> let bind in e) ==> (bind, p -> e)
letFloatAltR :: CoreAlt -> TransformH x (CoreBind,CoreAlt)
letFloatAltR (con,vs,Let bind@(NonRec x a) body)
| isEmptyVarSet (vset `intersectVarSet` freeVarsExpr a)
&& not (x `elemVarSet` vset)
= return (bind,(con,vs,body))
where
vset = mkVarSet vs
letFloatAltR _ = fail "letFloatAltR: not applicable"
-- TODO: consider variable occurrence conditions more carefully
#endif
{--------------------------------------------------------------------
Triviality
--------------------------------------------------------------------}
-- exprIsTrivial :: CoreExpr -> Bool
-- exprIsTrivial (Var {}) = True
-- exprIsTrivial (Lit {}) = True
-- exprIsTrivial (App {}) = False
-- exprIsTrivial (Lam _ e) = exprIsTrivial e
-- exprIsTrivial (Case {}) = False
-- exprIsTrivial (Cast e _) = exprIsTrivial e
-- exprIsTrivial (Tick _ e) = exprIsTrivial e
-- exprIsTrivial (Type {}) = True
-- exprIsTrivial (Coercion _) = True
-- Instead use exprIsTrivial from GHC's CoreUtils
-- | Trivial expression: for now, literals, variables, casts of trivial.
trivialExpr :: FilterE
trivialExpr = setFailMsg "Non-trivial" $
isTypeE <+ isVarT <+ isCoercionE <+ isDictE <+ isLitT
<+ trivialLam
<+ castT trivialExpr id mempty
-- TODO: Maybe use a guardM variant and GHC's exprIsTrivial
trivialBind :: FilterH CoreBind
trivialBind = nonRecT successT trivialExpr mempty
trivialLet :: FilterE
trivialLet = letT trivialBind successT mempty
trivialLam :: FilterE
trivialLam = lamT id trivialExpr mempty
trivialBetaRedex :: FilterE
trivialBetaRedex = appT trivialLam successT mempty
-- These filters could instead be predicates. Then use acceptR.
letSubstTrivialR :: ReExpr
letSubstTrivialR = -- watchR "trivialLet" $
trivialLet >> letSubstR
betaReduceTrivialR :: ReExpr
betaReduceTrivialR = -- watchR "betaReduceTrivialR" $
trivialBetaRedex >> betaReduceR
{--------------------------------------------------------------------
Case alternative pruning
--------------------------------------------------------------------}
type InTvM a = TvSubst -> a
type ReTv a = a -> InTvM a
pruneBound :: Var -> Unop TvSubst
pruneBound v =
fromMaybe (error "pruneBound: contradiction") . extendTvSubstVar v
extendTvSubstVar :: Var -> InTvM (Maybe TvSubst)
extendTvSubstVar v | isCoVar v && coVarRole v == Nominal =
extendTvSubstTys (coVarKind v)
| otherwise = pure
extendTvSubstVars :: [Id] -> TvSubst -> Maybe TvSubst
extendTvSubstVars = foldr (\ v q -> q <=< extendTvSubstVar v) pure
extendTvSubstTys :: (Type,Type) -> TvSubst -> Maybe TvSubst
extendTvSubstTys (a,b) sub =
unionTvSubst sub <$> tcUnifyTy (substTy sub a) (substTy sub b)
-- TODO: Can I really use unionTvSubst here? Note comment "Works when the ranges
-- are disjoint"
-- TODO: Maybe use normaliseType and check that the resulting coercion is
-- nominal TODO: Handle Representational coercions?
#if 0
pruneAltsR :: ReExpr
pruneAltsR = changedArrR (flip pruneAltsExpr emptyTvSubst)
pruneAltsExpr :: ReTv CoreExpr
pruneAltsExpr e@(Var _) = pure e
pruneAltsExpr e@(Lit _) = pure e
pruneAltsExpr (App u v) = liftA2 App (pruneAltsExpr u) (pruneAltsExpr v)
pruneAltsExpr (Lam x e) = Lam x <$> (pruneAltsExpr e . pruneBound x)
pruneAltsExpr (Let b e) = liftA2 Let (pruneAltsBind b) (pruneAltsExpr e)
pruneAltsExpr (Case e w ty alts) =
Case <$> (pruneAltsExpr e)
<*> pure w
<*> pure ty
<*> (catMaybes <$> mapM pruneAltsAlt alts)
pruneAltsExpr (Cast e co) = Cast <$> pruneAltsExpr e <*> pure co
pruneAltsExpr (Tick t e) = Tick t <$> pruneAltsExpr e
pruneAltsExpr e@(Type _) = pure e
pruneAltsExpr e@(Coercion _) = pure e
pruneAltsBind :: ReTv CoreBind
pruneAltsBind (NonRec x e) = NonRec x <$> (pruneAltsExpr e . pruneBound x)
pruneAltsBind (Rec ves) =
\ env -> Rec ((fmap.second) (flip pruneAltsExpr env) ves)
-- For Rec, I'm not gathering any info about the variables, so some pruning may
-- be missed. TODO: Reconsider.
-- TODO: Use an applicative or monadic style for Rec.
pruneAltsAlt :: CoreAlt -> InTvM (Maybe CoreAlt)
pruneAltsAlt (con,vs0,e) =
-- \ env -> case prune vs0 env of
-- Nothing -> Nothing
-- Just env' -> Just (con,vs0,pruneAltsExpr e env')
(fmap.fmap) ((con,vs0,) . pruneAltsExpr e) (extendTvSubstVars vs0)
-- I think I'll want to combine pruneBound and consistentVar, yielding a Maybe
-- TvSubst. What do I do for pruneAltsExpr etc if a lambda binding proves
-- impossible? What about a let binding?
#else
{--------------------------------------------------------------------
Type localization
--------------------------------------------------------------------}
-- Eliminate type variables determined by coercions, so that other
-- transformations can use local information.
-- Subsumes pruneAlt*
-- TODO: Make retypeFoo into a class
-- TODO: Still needed?
retypeExprR :: ReExpr
retypeExprR = changedArrR (flip retypeExpr emptyTvSubst)
retypeType :: ReTv Type
retypeType = flip substTy
retypeVar :: ReTv Var
retypeVar x = \ sub -> setVarType x (substTy sub (varType x))
retypeExpr :: ReTv CoreExpr
-- retypeExpr (Var x) = Var . retypeVar x
retypeExpr (Var x) = \ sub -> let ty = varType x
ty' = substTy sub ty
in
mkCast (Var x) (mkUnivCo Representational ty ty')
retypeExpr e@(Lit _) = pure e
retypeExpr (App u v) = App <$> retypeExpr u <*> retypeExpr v
-- retypeExpr (Lam x e) = Lam <$> retypeVar x <*> (retypeExpr e . pruneBound x)
retypeExpr (Lam x e) = Lam x <$> retypeExpr e
retypeExpr (Let b e) = Let <$> retypeBind b <*> retypeExpr e
retypeExpr (Case e w ty alts) =
Case <$> retypeExpr e
<*> retypeVar w
<*> retypeType ty
<*> (catMaybes <$> mapM retypeAlt alts)
retypeExpr (Cast e co) = mkCast <$> retypeExpr e <*> retypeCoercion co
retypeExpr (Tick t e) = Tick t <$> retypeExpr e
retypeExpr (Type t) = Type <$> retypeType t
retypeExpr (Coercion co) = Coercion <$> retypeCoercion co
retypeBind :: ReTv CoreBind
retypeBind (NonRec x e) = NonRec <$> retypeVar x <*> (retypeExpr e . pruneBound x)
retypeBind (Rec ves) =
Rec <$> mapM (\ (x,e) -> (,) <$> retypeVar x <*> retypeExpr e) ves
-- retypeAlt :: CoreAlt -> InTvM (Maybe CoreAlt)
-- retypeAlt (con,vs0,e) = go vs0 []
-- where
-- go :: [Var] -> [Var] -> TvSubst -> Maybe (CoreAlt)
-- go [] acc sub = return (con, reverse acc, retypeExpr e sub)
-- go (v:vs) acc sub | isCoVar v && coVarRole v == Nominal
-- = extendTvSubstTys (coVarKind v) sub >>= go vs (v:acc)
-- | otherwise
-- = go vs (retypeVar v sub : acc) sub
-- -- Gather substitutions for all of coercion variables.
-- -- Then substitute in the parameters and the body.
-- retypeAlt :: CoreAlt -> InTvM (Maybe CoreAlt)
-- retypeAlt (con,vs,e) sub =
-- do sub' <- extendTvSubstVars vs sub
-- return (con, tyToPat (lookupTvSubst sub') <$> vs, retypeExpr e sub')
-- Gather substitutions for all of coercion variables.
-- Then substitute in the the body.
retypeAlt :: CoreAlt -> InTvM (Maybe CoreAlt)
retypeAlt (con,vs,e) sub =
do sub' <- extendTvSubstVars vs sub
return (con, vs, retypeExpr e sub')
-- retypeAlt (con,vs,e) sub =
-- extendTvSubstVars vs sub >>=
-- (con,,) <$> mapM retypeVar vs <*> retypeExpr e
-- TODO: Consider coercions in let and lambda.
-- For now, convert coercions to universal.
retypeCoercion :: ReTv Coercion
retypeCoercion co =
-- optCoercion emptyCvSubst <$>
(mkUnivCo (coercionRole co) <$> retypeType ty <*> retypeType ty')
where
Pair ty ty' = coercionKind co
#endif
{--------------------------------------------------------------------
Balanced binary trees, for type constructions
--------------------------------------------------------------------}
-- Binary leaf tree. Used to construct balanced nested sum and product types.
data Tree a = Empty | Leaf a | Branch (Tree a) (Tree a)
deriving (Show,Functor,Foldable)
toTree :: [a] -> Tree a
toTree [] = Empty
toTree [a] = Leaf a
toTree xs = Branch (toTree l) (toTree r)
where
(l,r) = splitAt (length xs `div` 2) xs
foldMapT :: b -> (a -> b) -> Binop b -> Tree a -> b
foldMapT e l b = h
where
h Empty = e
h (Leaf a) = l a
h (Branch u v) = b (h u) (h v)
foldT :: a -> Binop a -> Tree a -> a
foldT e b = foldMapT e id b
{--------------------------------------------------------------------
Syntactic equality
--------------------------------------------------------------------}
-- Syntactic equality tests, taking care to check var types for change.
infix 4 =~=
class SyntaxEq a where
(=~=) :: a -> a -> Bool
instance (SyntaxEq a, SyntaxEq b) => SyntaxEq (a,b) where
(a,b) =~= (a',b') = a =~= a' && b =~= b'
instance (SyntaxEq a, SyntaxEq b, SyntaxEq c) => SyntaxEq (a,b,c) where
(a,b,c) =~= (a',b',c') = a =~= a' && b =~= b' && c =~= c'
instance SyntaxEq a => SyntaxEq [a] where (=~=) = all2 (=~=)
instance SyntaxEq Var where (=~=) = varSyntaxEq'
varSyntaxEq' :: Var -> Var -> Bool
varSyntaxEq' x y = x == y && varType x =~= varType y
instance SyntaxEq CoreProg where
ProgNil =~= ProgNil = True
ProgCons bnd1 p1 =~= ProgCons bnd2 p2 = bnd1 =~= bnd2 && p1 =~= p2
_ =~= _ = False
instance SyntaxEq CoreBind where
NonRec v1 e1 =~= NonRec v2 e2 = v1 =~= v2 && e1 =~= e2
Rec ies1 =~= Rec ies2 = ies1 =~= ies2
_ =~= _ = False
instance SyntaxEq CoreDef where
Def i1 e1 =~= Def i2 e2 = i1 =~= i2 && e1 =~= e2
instance SyntaxEq CoreExpr where
Var x =~= Var y = x =~= y
Lit l1 =~= Lit l2 = l1 == l2
App f1 e1 =~= App f2 e2 = f1 =~= f2 && e1 =~= e2
Lam v1 e1 =~= Lam v2 e2 = v1 == v2 && e1 =~= e2
Let b1 e1 =~= Let b2 e2 = b1 =~= b2 && e1 =~= e2
Case s1 w1 ty1 as1 =~= Case s2 w2 ty2 as2 =
w1 == w2 && s1 =~= s2 && all2 (=~=) as1 as2 && ty1 =~= ty2
Cast e1 co1 =~= Cast e2 co2 = e1 =~= e2 && co1 =~= co2
Tick t1 e1 =~= Tick t2 e2 = t1 == t2 && e1 =~= e2
Type ty1 =~= Type ty2 = ty1 =~= ty2
Coercion co1 =~= Coercion co2 = co1 =~= co2
_ =~= _ = False
instance SyntaxEq AltCon where (=~=) = (==)
instance SyntaxEq Type where (=~=) = typeSyntaxEq
instance SyntaxEq Coercion where (=~=) = coercionSyntaxEq
regularizeType :: Unop Type
regularizeType (coreView -> Just ty) = regularizeType ty
regularizeType ty@(TyVarTy _) = ty
regularizeType (AppTy u v) = AppTy (regularizeType u) (regularizeType v)
regularizeType (TyConApp tc tys) = TyConApp tc (regularizeType <$> tys)
regularizeType (FunTy u v) = FunTy (regularizeType u) (regularizeType v)
regularizeType (ForAllTy x ty) = ForAllTy x (regularizeType ty)
regularizeType ty@(LitTy _) = ty
|
conal/hermit-extras
|
src/HERMIT/Extras.hs
|
bsd-3-clause
| 50,562 | 0 | 23 | 11,996 | 13,014 | 6,863 | 6,151 | 784 | 12 |
{-# LANGUAGE DeriveDataTypeable #-}
{- |
Module : $Header$
Description : Maude Sentences
Copyright : (c) Martin Kuehl, Uni Bremen 2008-2009
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : experimental
Portability : portable
Definition of sentences for Maude.
-}
module Maude.Sentence (
-- * The Sentence type
Sentence (..),
-- * Contruction
fromSpec,
fromStatements,
-- * Testing
isRule,
) where
import Maude.AS_Maude
import Maude.Meta
import Maude.Printing ()
import Common.Id (mkSimpleId, GetRange)
import Common.Doc (vcat)
import Common.DocUtils (Pretty (..))
import Data.Data
-- * The Sentence type
-- | A 'Membership', 'Equation' or 'Rule'.
data Sentence = Membership Membership
| Equation Equation
| Rule Rule
deriving (Show, Read, Ord, Eq, Typeable, Data)
-- ** Sentence Instances
instance GetRange Sentence
instance Pretty Sentence where
pretty sent = case sent of
Membership mb -> pretty mb
Equation eq -> pretty eq
Rule rl -> pretty rl
pretties = vcat . map pretty
instance HasSorts Sentence where
getSorts sen = case sen of
Membership mb -> getSorts mb
Equation eq -> getSorts eq
Rule rl -> getSorts rl
mapSorts mp sen = case sen of
Membership mb -> Membership $ mapSorts mp mb
Equation eq -> Equation $ mapSorts mp eq
Rule rl -> Rule $ mapSorts mp rl
instance HasOps Sentence where
getOps sen = case sen of
Membership mb -> getOps mb
Equation eq -> getOps eq
Rule rl -> getOps rl
mapOps mp sen = case sen of
Membership mb -> Membership $ mapOps mp mb
Equation eq -> Equation $ mapOps mp eq
Rule rl -> Rule $ mapOps mp rl
instance HasLabels Sentence where
getLabels sen = case sen of
Membership mb -> getLabels mb
Equation eq -> getLabels eq
Rule rl -> getLabels rl
mapLabels mp sen = case sen of
Membership mb -> Membership $ mapLabels mp mb
Equation eq -> Equation $ mapLabels mp eq
Rule rl -> Rule $ mapLabels mp rl
-- * Contruction
-- | Extract the 'Sentence's from the given 'Module'.
fromSpec :: Module -> [Sentence]
fromSpec (Module _ _ stmts) = fromStatements stmts
-- | Extract the 'Sentence's from the given 'Statement's.
fromStatements :: [Statement] -> [Sentence]
fromStatements stmts = let
convert stmt = case stmt of
-- SubsortStmnt sub -> [fromSubsort sub]
OpStmnt op -> fromOperator op
MbStmnt mb -> [Membership mb]
EqStmnt eq -> [Equation eq]
RlStmnt rl -> [Rule rl]
_ -> []
in concatMap convert stmts
{-
fromSubsort :: SubsortDecl -> Sentence
fromSubsort (Subsort s1 s2) = Membership mb
where var = mkVar "V" (TypeSort s1)
cond = MbCond var s1
mb = Mb var s2 [cond] []
-}
fromOperator :: Operator -> [Sentence]
fromOperator (Op op dom cod attrs) = let
name = getName op
first : second : _ = dom
convert attr = case attr of
Assoc -> assocEq name first second cod
Comm -> commEq name first second cod
Idem -> idemEq name first cod
Id term -> identityEq name first term cod
LeftId term -> leftIdEq name first term cod
RightId term -> rightIdEq name first term cod
_ -> []
in concatMap convert attrs
commEq :: Qid -> Type -> Type -> Type -> [Sentence]
commEq op ar1 ar2 co = [Equation $ Eq t1 t2 [] []]
where v1 = mkVar "v1" $ type2Kind ar1
v2 = mkVar "v2" $ type2Kind ar2
t1 = Apply op [v1, v2] $ type2Kind co
t2 = Apply op [v2, v1] $ type2Kind co
assocEq :: Qid -> Type -> Type -> Type -> [Sentence]
assocEq op ar1 ar2 co = [eq]
where v1 = mkVar "v1" $ type2Kind ar1
v2 = mkVar "v2" $ type2Kind ar2
v3 = mkVar "v3" $ type2Kind ar2
t1 = Apply op [v1, v2] $ type2Kind co
t2 = Apply op [t1, v3] $ type2Kind co
t3 = Apply op [v2, v3] $ type2Kind co
t4 = Apply op [v1, t3] $ type2Kind co
eq = Equation $ Eq t2 t4 [] []
idemEq :: Qid -> Type -> Type -> [Sentence]
idemEq op ar co = [Equation $ Eq t v [] []]
where v = Apply (mkSimpleId "v") [] $ type2Kind ar
t = Apply op [v, v] $ type2Kind co
identityEq :: Qid -> Type -> Term -> Type -> [Sentence]
identityEq op ar1 idt co = [eq1, eq2]
where idt' = const2kind idt
v = mkVar "v" $ type2Kind ar1
t1 = Apply op [v, idt'] $ type2Kind co
t2 = Apply op [idt', v] $ type2Kind co
eq1 = Equation $ Eq t1 v [] []
eq2 = Equation $ Eq t2 v [] []
leftIdEq :: Qid -> Type -> Term -> Type -> [Sentence]
leftIdEq op ar1 idt co = [eq1, eq2]
where idt' = const2kind idt
v = mkVar "v" $ type2Kind ar1
t = Apply op [idt', v] $ type2Kind co
eq1 = Equation $ Eq t v [] []
eq2 = Equation $ Eq v t [] []
rightIdEq :: Qid -> Type -> Term -> Type -> [Sentence]
rightIdEq op ar1 idt co = [eq1, eq2]
where idt' = const2kind idt
v = mkVar "v" $ type2Kind ar1
t = Apply op [v, idt'] $ type2Kind co
eq1 = Equation $ Eq t v [] []
eq2 = Equation $ Eq v t [] []
type2Kind :: Type -> Type
type2Kind (TypeSort (SortId s)) = TypeKind $ KindId s
type2Kind k = k
const2kind :: Term -> Term
const2kind (Const q ty) = Const q $ type2Kind ty
const2kind t = t
-- * Testing
-- | True iff the given 'Sentence' is a 'Rule'.
isRule :: Sentence -> Bool
isRule sent = case sent of
Rule _ -> True
_ -> False
|
mariefarrell/Hets
|
Maude/Sentence.hs
|
gpl-2.0
| 5,625 | 0 | 13 | 1,693 | 1,913 | 959 | 954 | 127 | 7 |
{-# LANGUAGE OverloadedStrings #-}
{-
Created : 2015 Sep 05 (Sat) 11:05:00 by Harold Carr.
Last Modified : 2015 Sep 13 (Sun) 16:52:43 by Harold Carr.
-}
module Client where
import Control.Lens
import Data.Aeson (toJSON)
import Msg
import Network.Wreq
epAddr = "http://127.0.0.1:3000"
mkMsg = Msg "H"
msgs = [ mkMsg 0 "hello"
, mkMsg 1 "Just \"application/json; charset=utf-8\""
, mkMsg 19 "Just \"Warp/3.0.13.1\"" -- wrong id, right answer
, mkMsg 2 "WRONG ANSWER" -- right id, wrong answer
, mkMsg 2 "Just \"Warp/3.0.13.1\""
, mkMsg 3 "Just (Number 3.0)"
, mkMsg 4 "4"
, mkMsg 5 "15"
, mkMsg 6 "15"
, mkMsg 7 "120"
, mkMsg 8 "120"
, mkMsg 9 "[1,2,3,4]"
, mkMsg 10 "[1,2,3,4]"
, mkMsg 11 "3"
, mkMsg 12 "3"
, mkMsg 13 "8"
, mkMsg 14 "203"
, mkMsg 15 "23"
, mkMsg 16 "winner"
, mkMsg 25 "whatever"
]
test = do
rs <- mapM (post epAddr . toJSON) msgs
mapM_ (\(m, r) -> do putStrLn $ "--> " ++ show m
putStrLn $ "<-- " ++ show (r ^? responseBody))
(zip msgs rs)
|
ryoia/utah-haskell
|
2015-09-17-solution/Client.hs
|
apache-2.0
| 1,238 | 0 | 15 | 461 | 301 | 156 | 145 | 33 | 1 |
{-# LANGUAGE CPP, NondecreasingIndentation, TupleSections #-}
{-# OPTIONS -fno-warn-incomplete-patterns -optc-DNON_POSIX_SOURCE #-}
-----------------------------------------------------------------------------
--
-- GHC Driver program
--
-- (c) The University of Glasgow 2005
--
-----------------------------------------------------------------------------
module Main (main) where
-- The official GHC API
import qualified GHC
import GHC ( -- DynFlags(..), HscTarget(..),
-- GhcMode(..), GhcLink(..),
Ghc, GhcMonad(..),
LoadHowMuch(..) )
import CmdLineParser
-- Implementations of the various modes (--show-iface, mkdependHS. etc.)
import LoadIface ( showIface )
import HscMain ( newHscEnv )
import DriverPipeline ( oneShot, compileFile, mergeRequirement )
import DriverMkDepend ( doMkDependHS )
#ifdef GHCI
import InteractiveUI ( interactiveUI, ghciWelcomeMsg, defaultGhciSettings )
#endif
-- Various other random stuff that we need
import Config
import Constants
import HscTypes
import Packages ( pprPackages, pprPackagesSimple, pprModuleMap )
import DriverPhases
import BasicTypes ( failed )
import StaticFlags
import DynFlags
import ErrUtils
import FastString
import Outputable
import SrcLoc
import Util
import Panic
import UniqSupply
import MonadUtils ( liftIO )
-- Imports for --abi-hash
import LoadIface ( loadUserInterface )
import Module ( mkModuleName )
import Finder ( findImportedModule, cannotFindInterface )
import TcRnMonad ( initIfaceCheck )
import Binary ( openBinMem, put_, fingerprintBinMem )
-- Standard Haskell libraries
import System.IO
import System.Environment
import System.Exit
import System.FilePath
import Control.Monad
import Data.Char
import Data.List
import Data.Maybe
-----------------------------------------------------------------------------
-- ToDo:
-- time commands when run with -v
-- user ways
-- Win32 support: proper signal handling
-- reading the package configuration file is too slow
-- -K<size>
-----------------------------------------------------------------------------
-- GHC's command-line interface
main :: IO ()
main = do
initGCStatistics -- See Note [-Bsymbolic and hooks]
hSetBuffering stdout LineBuffering
hSetBuffering stderr LineBuffering
-- Handle GHC-specific character encoding flags, allowing us to control how
-- GHC produces output regardless of OS.
env <- getEnvironment
case lookup "GHC_CHARENC" env of
Just "UTF-8" -> do
hSetEncoding stdout utf8
hSetEncoding stderr utf8
_ -> do
-- Avoid GHC erroring out when trying to display unhandled characters
hSetTranslit stdout
hSetTranslit stderr
GHC.defaultErrorHandler defaultFatalMessager defaultFlushOut $ do
-- 1. extract the -B flag from the args
argv0 <- getArgs
let (minusB_args, argv1) = partition ("-B" `isPrefixOf`) argv0
mbMinusB | null minusB_args = Nothing
| otherwise = Just (drop 2 (last minusB_args))
let argv1' = map (mkGeneralLocated "on the commandline") argv1
(argv2, staticFlagWarnings) <- parseStaticFlags argv1'
-- 2. Parse the "mode" flags (--make, --interactive etc.)
(mode, argv3, modeFlagWarnings) <- parseModeFlags argv2
let flagWarnings = staticFlagWarnings ++ modeFlagWarnings
-- If all we want to do is something like showing the version number
-- then do it now, before we start a GHC session etc. This makes
-- getting basic information much more resilient.
-- In particular, if we wait until later before giving the version
-- number then bootstrapping gets confused, as it tries to find out
-- what version of GHC it's using before package.conf exists, so
-- starting the session fails.
case mode of
Left preStartupMode ->
do case preStartupMode of
ShowSupportedExtensions -> showSupportedExtensions
ShowVersion -> showVersion
ShowNumVersion -> putStrLn cProjectVersion
ShowOptions isInteractive -> showOptions isInteractive
Right postStartupMode ->
-- start our GHC session
GHC.runGhc mbMinusB $ do
dflags <- GHC.getSessionDynFlags
case postStartupMode of
Left preLoadMode ->
liftIO $ do
case preLoadMode of
ShowInfo -> showInfo dflags
ShowGhcUsage -> showGhcUsage dflags
ShowGhciUsage -> showGhciUsage dflags
PrintWithDynFlags f -> putStrLn (f dflags)
Right postLoadMode ->
main' postLoadMode dflags argv3 flagWarnings
main' :: PostLoadMode -> DynFlags -> [Located String] -> [Located String]
-> Ghc ()
main' postLoadMode dflags0 args flagWarnings = do
-- set the default GhcMode, HscTarget and GhcLink. The HscTarget
-- can be further adjusted on a module by module basis, using only
-- the -fvia-C and -fasm flags. If the default HscTarget is not
-- HscC or HscAsm, -fvia-C and -fasm have no effect.
let dflt_target = hscTarget dflags0
(mode, lang, link)
= case postLoadMode of
DoInteractive -> (CompManager, HscInterpreted, LinkInMemory)
DoEval _ -> (CompManager, HscInterpreted, LinkInMemory)
DoMake -> (CompManager, dflt_target, LinkBinary)
DoMkDependHS -> (MkDepend, dflt_target, LinkBinary)
DoAbiHash -> (OneShot, dflt_target, LinkBinary)
DoMergeRequirements -> (OneShot, dflt_target, LinkBinary)
_ -> (OneShot, dflt_target, LinkBinary)
let dflags1 = case lang of
HscInterpreted ->
let platform = targetPlatform dflags0
dflags0a = updateWays $ dflags0 { ways = interpWays }
dflags0b = foldl gopt_set dflags0a
$ concatMap (wayGeneralFlags platform)
interpWays
dflags0c = foldl gopt_unset dflags0b
$ concatMap (wayUnsetGeneralFlags platform)
interpWays
in dflags0c
_ ->
dflags0
dflags2 = dflags1{ ghcMode = mode,
hscTarget = lang,
ghcLink = link,
verbosity = case postLoadMode of
DoEval _ -> 0
_other -> 1
}
-- turn on -fimplicit-import-qualified for GHCi now, so that it
-- can be overriden from the command-line
-- XXX: this should really be in the interactive DynFlags, but
-- we don't set that until later in interactiveUI
dflags3 | DoInteractive <- postLoadMode = imp_qual_enabled
| DoEval _ <- postLoadMode = imp_qual_enabled
| otherwise = dflags2
where imp_qual_enabled = dflags2 `gopt_set` Opt_ImplicitImportQualified
-- The rest of the arguments are "dynamic"
-- Leftover ones are presumably files
(dflags4, fileish_args, dynamicFlagWarnings) <- GHC.parseDynamicFlags dflags3 args
GHC.prettyPrintGhcErrors dflags4 $ do
let flagWarnings' = flagWarnings ++ dynamicFlagWarnings
handleSourceError (\e -> do
GHC.printException e
liftIO $ exitWith (ExitFailure 1)) $ do
liftIO $ handleFlagWarnings dflags4 flagWarnings'
-- make sure we clean up after ourselves
GHC.defaultCleanupHandler dflags4 $ do
liftIO $ showBanner postLoadMode dflags4
let
-- To simplify the handling of filepaths, we normalise all filepaths right
-- away - e.g., for win32 platforms, backslashes are converted
-- into forward slashes.
normal_fileish_paths = map (normalise . unLoc) fileish_args
(srcs, objs) = partition_args normal_fileish_paths [] []
dflags5 = dflags4 { ldInputs = map (FileOption "") objs
++ ldInputs dflags4 }
-- we've finished manipulating the DynFlags, update the session
_ <- GHC.setSessionDynFlags dflags5
dflags6 <- GHC.getSessionDynFlags
hsc_env <- GHC.getSession
---------------- Display configuration -----------
case verbosity dflags6 of
v | v == 4 -> liftIO $ dumpPackagesSimple dflags6
| v >= 5 -> liftIO $ dumpPackages dflags6
| otherwise -> return ()
when (verbosity dflags6 >= 3) $ do
liftIO $ hPutStrLn stderr ("Hsc static flags: " ++ unwords staticFlags)
when (dopt Opt_D_dump_mod_map dflags6) . liftIO $
printInfoForUser (dflags6 { pprCols = 200 })
(pkgQual dflags6) (pprModuleMap dflags6)
liftIO $ initUniqSupply (initialUnique dflags6) (uniqueIncrement dflags6)
---------------- Final sanity checking -----------
liftIO $ checkOptions postLoadMode dflags6 srcs objs
---------------- Do the business -----------
handleSourceError (\e -> do
GHC.printException e
liftIO $ exitWith (ExitFailure 1)) $ do
case postLoadMode of
ShowInterface f -> liftIO $ doShowIface dflags6 f
DoMake -> doMake srcs
DoMkDependHS -> doMkDependHS (map fst srcs)
StopBefore p -> liftIO (oneShot hsc_env p srcs)
DoInteractive -> ghciUI srcs Nothing
DoEval exprs -> ghciUI srcs $ Just $ reverse exprs
DoAbiHash -> abiHash (map fst srcs)
DoMergeRequirements -> doMergeRequirements (map fst srcs)
ShowPackages -> liftIO $ showPackages dflags6
liftIO $ dumpFinalStats dflags6
ghciUI :: [(FilePath, Maybe Phase)] -> Maybe [String] -> Ghc ()
#ifndef GHCI
ghciUI _ _ = throwGhcException (CmdLineError "not built for interactive use")
#else
ghciUI = interactiveUI defaultGhciSettings
#endif
-- -----------------------------------------------------------------------------
-- Splitting arguments into source files and object files. This is where we
-- interpret the -x <suffix> option, and attach a (Maybe Phase) to each source
-- file indicating the phase specified by the -x option in force, if any.
partition_args :: [String] -> [(String, Maybe Phase)] -> [String]
-> ([(String, Maybe Phase)], [String])
partition_args [] srcs objs = (reverse srcs, reverse objs)
partition_args ("-x":suff:args) srcs objs
| "none" <- suff = partition_args args srcs objs
| StopLn <- phase = partition_args args srcs (slurp ++ objs)
| otherwise = partition_args rest (these_srcs ++ srcs) objs
where phase = startPhase suff
(slurp,rest) = break (== "-x") args
these_srcs = zip slurp (repeat (Just phase))
partition_args (arg:args) srcs objs
| looks_like_an_input arg = partition_args args ((arg,Nothing):srcs) objs
| otherwise = partition_args args srcs (arg:objs)
{-
We split out the object files (.o, .dll) and add them
to ldInputs for use by the linker.
The following things should be considered compilation manager inputs:
- haskell source files (strings ending in .hs, .lhs or other
haskellish extension),
- module names (not forgetting hierarchical module names),
- things beginning with '-' are flags that were not recognised by
the flag parser, and we want them to generate errors later in
checkOptions, so we class them as source files (#5921)
- and finally we consider everything not containing a '.' to be
a comp manager input, as shorthand for a .hs or .lhs filename.
Everything else is considered to be a linker object, and passed
straight through to the linker.
-}
looks_like_an_input :: String -> Bool
looks_like_an_input m = isSourceFilename m
|| looksLikeModuleName m
|| "-" `isPrefixOf` m
|| '.' `notElem` m
-- -----------------------------------------------------------------------------
-- Option sanity checks
-- | Ensure sanity of options.
--
-- Throws 'UsageError' or 'CmdLineError' if not.
checkOptions :: PostLoadMode -> DynFlags -> [(String,Maybe Phase)] -> [String] -> IO ()
-- Final sanity checking before kicking off a compilation (pipeline).
checkOptions mode dflags srcs objs = do
-- Complain about any unknown flags
let unknown_opts = [ f | (f@('-':_), _) <- srcs ]
when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
when (notNull (filter wayRTSOnly (ways dflags))
&& isInterpretiveMode mode) $
hPutStrLn stderr ("Warning: -debug, -threaded and -ticky are ignored by GHCi")
-- -prof and --interactive are not a good combination
when ((filter (not . wayRTSOnly) (ways dflags) /= interpWays)
&& isInterpretiveMode mode) $
do throwGhcException (UsageError
"--interactive can't be used with -prof or -static.")
-- -ohi sanity check
if (isJust (outputHi dflags) &&
(isCompManagerMode mode || srcs `lengthExceeds` 1))
then throwGhcException (UsageError "-ohi can only be used when compiling a single source file")
else do
-- -o sanity checking
if (srcs `lengthExceeds` 1 && isJust (outputFile dflags)
&& not (isLinkMode mode))
then throwGhcException (UsageError "can't apply -o to multiple source files")
else do
let not_linking = not (isLinkMode mode) || isNoLink (ghcLink dflags)
when (not_linking && not (null objs)) $
hPutStrLn stderr ("Warning: the following files would be used as linker inputs, but linking is not being done: " ++ unwords objs)
-- Check that there are some input files
-- (except in the interactive case)
if null srcs && (null objs || not_linking) && needsInputsMode mode
then throwGhcException (UsageError "no input files")
else do
case mode of
StopBefore HCc | hscTarget dflags /= HscC
-> throwGhcException $ UsageError $
"the option -C is only available with an unregisterised GHC"
_ -> return ()
-- Verify that output files point somewhere sensible.
verifyOutputFiles dflags
-- Compiler output options
-- Called to verify that the output files point somewhere valid.
--
-- The assumption is that the directory portion of these output
-- options will have to exist by the time 'verifyOutputFiles'
-- is invoked.
--
-- We create the directories for -odir, -hidir, -outputdir etc. ourselves if
-- they don't exist, so don't check for those here (#2278).
verifyOutputFiles :: DynFlags -> IO ()
verifyOutputFiles dflags = do
let ofile = outputFile dflags
when (isJust ofile) $ do
let fn = fromJust ofile
flg <- doesDirNameExist fn
when (not flg) (nonExistentDir "-o" fn)
let ohi = outputHi dflags
when (isJust ohi) $ do
let hi = fromJust ohi
flg <- doesDirNameExist hi
when (not flg) (nonExistentDir "-ohi" hi)
where
nonExistentDir flg dir =
throwGhcException (CmdLineError ("error: directory portion of " ++
show dir ++ " does not exist (used with " ++
show flg ++ " option.)"))
-----------------------------------------------------------------------------
-- GHC modes of operation
type Mode = Either PreStartupMode PostStartupMode
type PostStartupMode = Either PreLoadMode PostLoadMode
data PreStartupMode
= ShowVersion -- ghc -V/--version
| ShowNumVersion -- ghc --numeric-version
| ShowSupportedExtensions -- ghc --supported-extensions
| ShowOptions Bool {- isInteractive -} -- ghc --show-options
showVersionMode, showNumVersionMode, showSupportedExtensionsMode, showOptionsMode :: Mode
showVersionMode = mkPreStartupMode ShowVersion
showNumVersionMode = mkPreStartupMode ShowNumVersion
showSupportedExtensionsMode = mkPreStartupMode ShowSupportedExtensions
showOptionsMode = mkPreStartupMode (ShowOptions False)
mkPreStartupMode :: PreStartupMode -> Mode
mkPreStartupMode = Left
isShowVersionMode :: Mode -> Bool
isShowVersionMode (Left ShowVersion) = True
isShowVersionMode _ = False
isShowNumVersionMode :: Mode -> Bool
isShowNumVersionMode (Left ShowNumVersion) = True
isShowNumVersionMode _ = False
data PreLoadMode
= ShowGhcUsage -- ghc -?
| ShowGhciUsage -- ghci -?
| ShowInfo -- ghc --info
| PrintWithDynFlags (DynFlags -> String) -- ghc --print-foo
showGhcUsageMode, showGhciUsageMode, showInfoMode :: Mode
showGhcUsageMode = mkPreLoadMode ShowGhcUsage
showGhciUsageMode = mkPreLoadMode ShowGhciUsage
showInfoMode = mkPreLoadMode ShowInfo
printSetting :: String -> Mode
printSetting k = mkPreLoadMode (PrintWithDynFlags f)
where f dflags = fromMaybe (panic ("Setting not found: " ++ show k))
$ lookup k (compilerInfo dflags)
mkPreLoadMode :: PreLoadMode -> Mode
mkPreLoadMode = Right . Left
isShowGhcUsageMode :: Mode -> Bool
isShowGhcUsageMode (Right (Left ShowGhcUsage)) = True
isShowGhcUsageMode _ = False
isShowGhciUsageMode :: Mode -> Bool
isShowGhciUsageMode (Right (Left ShowGhciUsage)) = True
isShowGhciUsageMode _ = False
data PostLoadMode
= ShowInterface FilePath -- ghc --show-iface
| DoMkDependHS -- ghc -M
| StopBefore Phase -- ghc -E | -C | -S
-- StopBefore StopLn is the default
| DoMake -- ghc --make
| DoInteractive -- ghc --interactive
| DoEval [String] -- ghc -e foo -e bar => DoEval ["bar", "foo"]
| DoAbiHash -- ghc --abi-hash
| ShowPackages -- ghc --show-packages
| DoMergeRequirements -- ghc --merge-requirements
doMkDependHSMode, doMakeMode, doInteractiveMode,
doAbiHashMode, showPackagesMode, doMergeRequirementsMode :: Mode
doMkDependHSMode = mkPostLoadMode DoMkDependHS
doMakeMode = mkPostLoadMode DoMake
doInteractiveMode = mkPostLoadMode DoInteractive
doAbiHashMode = mkPostLoadMode DoAbiHash
showPackagesMode = mkPostLoadMode ShowPackages
doMergeRequirementsMode = mkPostLoadMode DoMergeRequirements
showInterfaceMode :: FilePath -> Mode
showInterfaceMode fp = mkPostLoadMode (ShowInterface fp)
stopBeforeMode :: Phase -> Mode
stopBeforeMode phase = mkPostLoadMode (StopBefore phase)
doEvalMode :: String -> Mode
doEvalMode str = mkPostLoadMode (DoEval [str])
mkPostLoadMode :: PostLoadMode -> Mode
mkPostLoadMode = Right . Right
isDoInteractiveMode :: Mode -> Bool
isDoInteractiveMode (Right (Right DoInteractive)) = True
isDoInteractiveMode _ = False
isStopLnMode :: Mode -> Bool
isStopLnMode (Right (Right (StopBefore StopLn))) = True
isStopLnMode _ = False
isDoMakeMode :: Mode -> Bool
isDoMakeMode (Right (Right DoMake)) = True
isDoMakeMode _ = False
isDoEvalMode :: Mode -> Bool
isDoEvalMode (Right (Right (DoEval _))) = True
isDoEvalMode _ = False
#ifdef GHCI
isInteractiveMode :: PostLoadMode -> Bool
isInteractiveMode DoInteractive = True
isInteractiveMode _ = False
#endif
-- isInterpretiveMode: byte-code compiler involved
isInterpretiveMode :: PostLoadMode -> Bool
isInterpretiveMode DoInteractive = True
isInterpretiveMode (DoEval _) = True
isInterpretiveMode _ = False
needsInputsMode :: PostLoadMode -> Bool
needsInputsMode DoMkDependHS = True
needsInputsMode (StopBefore _) = True
needsInputsMode DoMake = True
needsInputsMode _ = False
-- True if we are going to attempt to link in this mode.
-- (we might not actually link, depending on the GhcLink flag)
isLinkMode :: PostLoadMode -> Bool
isLinkMode (StopBefore StopLn) = True
isLinkMode DoMake = True
isLinkMode DoInteractive = True
isLinkMode (DoEval _) = True
isLinkMode _ = False
isCompManagerMode :: PostLoadMode -> Bool
isCompManagerMode DoMake = True
isCompManagerMode DoInteractive = True
isCompManagerMode (DoEval _) = True
isCompManagerMode _ = False
-- -----------------------------------------------------------------------------
-- Parsing the mode flag
parseModeFlags :: [Located String]
-> IO (Mode,
[Located String],
[Located String])
parseModeFlags args = do
let ((leftover, errs1, warns), (mModeFlag, errs2, flags')) =
runCmdLine (processArgs mode_flags args)
(Nothing, [], [])
mode = case mModeFlag of
Nothing -> doMakeMode
Just (m, _) -> m
-- See Note [Handling errors when parsing commandline flags]
unless (null errs1 && null errs2) $ throwGhcException $ errorsToGhcException $
map (("on the commandline", )) $ map unLoc errs1 ++ errs2
return (mode, flags' ++ leftover, warns)
type ModeM = CmdLineP (Maybe (Mode, String), [String], [Located String])
-- mode flags sometimes give rise to new DynFlags (eg. -C, see below)
-- so we collect the new ones and return them.
mode_flags :: [Flag ModeM]
mode_flags =
[ ------- help / version ----------------------------------------------
defFlag "?" (PassFlag (setMode showGhcUsageMode))
, defFlag "-help" (PassFlag (setMode showGhcUsageMode))
, defFlag "V" (PassFlag (setMode showVersionMode))
, defFlag "-version" (PassFlag (setMode showVersionMode))
, defFlag "-numeric-version" (PassFlag (setMode showNumVersionMode))
, defFlag "-info" (PassFlag (setMode showInfoMode))
, defFlag "-show-options" (PassFlag (setMode showOptionsMode))
, defFlag "-supported-languages" (PassFlag (setMode showSupportedExtensionsMode))
, defFlag "-supported-extensions" (PassFlag (setMode showSupportedExtensionsMode))
, defFlag "-show-packages" (PassFlag (setMode showPackagesMode))
] ++
[ defFlag k' (PassFlag (setMode (printSetting k)))
| k <- ["Project version",
"Project Git commit id",
"Booter version",
"Stage",
"Build platform",
"Host platform",
"Target platform",
"Have interpreter",
"Object splitting supported",
"Have native code generator",
"Support SMP",
"Unregisterised",
"Tables next to code",
"RTS ways",
"Leading underscore",
"Debug on",
"LibDir",
"Global Package DB",
"C compiler flags",
"Gcc Linker flags",
"Ld Linker flags"],
let k' = "-print-" ++ map (replaceSpace . toLower) k
replaceSpace ' ' = '-'
replaceSpace c = c
] ++
------- interfaces ----------------------------------------------------
[ defFlag "-show-iface" (HasArg (\f -> setMode (showInterfaceMode f)
"--show-iface"))
------- primary modes ------------------------------------------------
, defFlag "c" (PassFlag (\f -> do setMode (stopBeforeMode StopLn) f
addFlag "-no-link" f))
, defFlag "M" (PassFlag (setMode doMkDependHSMode))
, defFlag "E" (PassFlag (setMode (stopBeforeMode anyHsc)))
, defFlag "C" (PassFlag (setMode (stopBeforeMode HCc)))
, defFlag "S" (PassFlag (setMode (stopBeforeMode (As False))))
, defFlag "-make" (PassFlag (setMode doMakeMode))
, defFlag "-merge-requirements" (PassFlag (setMode doMergeRequirementsMode))
, defFlag "-interactive" (PassFlag (setMode doInteractiveMode))
, defFlag "-abi-hash" (PassFlag (setMode doAbiHashMode))
, defFlag "e" (SepArg (\s -> setMode (doEvalMode s) "-e"))
]
setMode :: Mode -> String -> EwM ModeM ()
setMode newMode newFlag = liftEwM $ do
(mModeFlag, errs, flags') <- getCmdLineState
let (modeFlag', errs') =
case mModeFlag of
Nothing -> ((newMode, newFlag), errs)
Just (oldMode, oldFlag) ->
case (oldMode, newMode) of
-- -c/--make are allowed together, and mean --make -no-link
_ | isStopLnMode oldMode && isDoMakeMode newMode
|| isStopLnMode newMode && isDoMakeMode oldMode ->
((doMakeMode, "--make"), [])
-- If we have both --help and --interactive then we
-- want showGhciUsage
_ | isShowGhcUsageMode oldMode &&
isDoInteractiveMode newMode ->
((showGhciUsageMode, oldFlag), [])
| isShowGhcUsageMode newMode &&
isDoInteractiveMode oldMode ->
((showGhciUsageMode, newFlag), [])
-- If we have both -e and --interactive then -e always wins
_ | isDoEvalMode oldMode &&
isDoInteractiveMode newMode ->
((oldMode, oldFlag), [])
| isDoEvalMode newMode &&
isDoInteractiveMode oldMode ->
((newMode, newFlag), [])
-- Otherwise, --help/--version/--numeric-version always win
| isDominantFlag oldMode -> ((oldMode, oldFlag), [])
| isDominantFlag newMode -> ((newMode, newFlag), [])
-- We need to accumulate eval flags like "-e foo -e bar"
(Right (Right (DoEval esOld)),
Right (Right (DoEval [eNew]))) ->
((Right (Right (DoEval (eNew : esOld))), oldFlag),
errs)
-- Saying e.g. --interactive --interactive is OK
_ | oldFlag == newFlag -> ((oldMode, oldFlag), errs)
-- --interactive and --show-options are used together
(Right (Right DoInteractive), Left (ShowOptions _)) ->
((Left (ShowOptions True),
"--interactive --show-options"), errs)
(Left (ShowOptions _), (Right (Right DoInteractive))) ->
((Left (ShowOptions True),
"--show-options --interactive"), errs)
-- Otherwise, complain
_ -> let err = flagMismatchErr oldFlag newFlag
in ((oldMode, oldFlag), err : errs)
putCmdLineState (Just modeFlag', errs', flags')
where isDominantFlag f = isShowGhcUsageMode f ||
isShowGhciUsageMode f ||
isShowVersionMode f ||
isShowNumVersionMode f
flagMismatchErr :: String -> String -> String
flagMismatchErr oldFlag newFlag
= "cannot use `" ++ oldFlag ++ "' with `" ++ newFlag ++ "'"
addFlag :: String -> String -> EwM ModeM ()
addFlag s flag = liftEwM $ do
(m, e, flags') <- getCmdLineState
putCmdLineState (m, e, mkGeneralLocated loc s : flags')
where loc = "addFlag by " ++ flag ++ " on the commandline"
-- ----------------------------------------------------------------------------
-- Run --make mode
doMake :: [(String,Maybe Phase)] -> Ghc ()
doMake srcs = do
let (hs_srcs, non_hs_srcs) = partition haskellish srcs
haskellish (f,Nothing) =
looksLikeModuleName f || isHaskellSrcFilename f || '.' `notElem` f
haskellish (_,Just phase) =
phase `notElem` [ As True, As False, Cc, Cobjc, Cobjcxx, CmmCpp, Cmm
, StopLn]
hsc_env <- GHC.getSession
-- if we have no haskell sources from which to do a dependency
-- analysis, then just do one-shot compilation and/or linking.
-- This means that "ghc Foo.o Bar.o -o baz" links the program as
-- we expect.
if (null hs_srcs)
then liftIO (oneShot hsc_env StopLn srcs)
else do
o_files <- mapM (\x -> liftIO $ compileFile hsc_env StopLn x)
non_hs_srcs
dflags <- GHC.getSessionDynFlags
let dflags' = dflags { ldInputs = map (FileOption "") o_files
++ ldInputs dflags }
_ <- GHC.setSessionDynFlags dflags'
targets <- mapM (uncurry GHC.guessTarget) hs_srcs
GHC.setTargets targets
ok_flag <- GHC.load LoadAllTargets
when (failed ok_flag) (liftIO $ exitWith (ExitFailure 1))
return ()
-- ----------------------------------------------------------------------------
-- Run --merge-requirements mode
doMergeRequirements :: [String] -> Ghc ()
doMergeRequirements srcs = mapM_ doMergeRequirement srcs
doMergeRequirement :: String -> Ghc ()
doMergeRequirement src = do
hsc_env <- getSession
liftIO $ mergeRequirement hsc_env (mkModuleName src)
-- ---------------------------------------------------------------------------
-- --show-iface mode
doShowIface :: DynFlags -> FilePath -> IO ()
doShowIface dflags file = do
hsc_env <- newHscEnv dflags
showIface hsc_env file
-- ---------------------------------------------------------------------------
-- Various banners and verbosity output.
showBanner :: PostLoadMode -> DynFlags -> IO ()
showBanner _postLoadMode dflags = do
let verb = verbosity dflags
#ifdef GHCI
-- Show the GHCi banner
when (isInteractiveMode _postLoadMode && verb >= 1) $ putStrLn ghciWelcomeMsg
#endif
-- Display details of the configuration in verbose mode
when (verb >= 2) $
do hPutStr stderr "Glasgow Haskell Compiler, Version "
hPutStr stderr cProjectVersion
hPutStr stderr ", stage "
hPutStr stderr cStage
hPutStr stderr " booted by GHC version "
hPutStrLn stderr cBooterVersion
-- We print out a Read-friendly string, but a prettier one than the
-- Show instance gives us
showInfo :: DynFlags -> IO ()
showInfo dflags = do
let sq x = " [" ++ x ++ "\n ]"
putStrLn $ sq $ intercalate "\n ," $ map show $ compilerInfo dflags
showSupportedExtensions :: IO ()
showSupportedExtensions = mapM_ putStrLn supportedLanguagesAndExtensions
showVersion :: IO ()
showVersion = putStrLn (cProjectName ++ ", version " ++ cProjectVersion)
showOptions :: Bool -> IO ()
showOptions isInteractive = putStr (unlines availableOptions)
where
availableOptions = concat [
flagsForCompletion isInteractive,
map ('-':) (concat [
getFlagNames mode_flags
, (filterUnwantedStatic . getFlagNames $ flagsStatic)
, flagsStaticNames
])
]
getFlagNames opts = map flagName opts
-- this is a hack to get rid of two unwanted entries that get listed
-- as static flags. Hopefully this hack will disappear one day together
-- with static flags
filterUnwantedStatic = filter (`notElem`["f", "fno-"])
showGhcUsage :: DynFlags -> IO ()
showGhcUsage = showUsage False
showGhciUsage :: DynFlags -> IO ()
showGhciUsage = showUsage True
showUsage :: Bool -> DynFlags -> IO ()
showUsage ghci dflags = do
let usage_path = if ghci then ghciUsagePath dflags
else ghcUsagePath dflags
usage <- readFile usage_path
dump usage
where
dump "" = return ()
dump ('$':'$':s) = putStr progName >> dump s
dump (c:s) = putChar c >> dump s
dumpFinalStats :: DynFlags -> IO ()
dumpFinalStats dflags =
when (gopt Opt_D_faststring_stats dflags) $ dumpFastStringStats dflags
dumpFastStringStats :: DynFlags -> IO ()
dumpFastStringStats dflags = do
buckets <- getFastStringTable
let (entries, longest, has_z) = countFS 0 0 0 buckets
msg = text "FastString stats:" $$
nest 4 (vcat [text "size: " <+> int (length buckets),
text "entries: " <+> int entries,
text "longest chain: " <+> int longest,
text "has z-encoding: " <+> (has_z `pcntOf` entries)
])
-- we usually get more "has z-encoding" than "z-encoded", because
-- when we z-encode a string it might hash to the exact same string,
-- which will is not counted as "z-encoded". Only strings whose
-- Z-encoding is different from the original string are counted in
-- the "z-encoded" total.
putMsg dflags msg
where
x `pcntOf` y = int ((x * 100) `quot` y) <> char '%'
countFS :: Int -> Int -> Int -> [[FastString]] -> (Int, Int, Int)
countFS entries longest has_z [] = (entries, longest, has_z)
countFS entries longest has_z (b:bs) =
let
len = length b
longest' = max len longest
entries' = entries + len
has_zs = length (filter hasZEncoding b)
in
countFS entries' longest' (has_z + has_zs) bs
showPackages, dumpPackages, dumpPackagesSimple :: DynFlags -> IO ()
showPackages dflags = putStrLn (showSDoc dflags (pprPackages dflags))
dumpPackages dflags = putMsg dflags (pprPackages dflags)
dumpPackagesSimple dflags = putMsg dflags (pprPackagesSimple dflags)
-- -----------------------------------------------------------------------------
-- ABI hash support
{-
ghc --abi-hash Data.Foo System.Bar
Generates a combined hash of the ABI for modules Data.Foo and
System.Bar. The modules must already be compiled, and appropriate -i
options may be necessary in order to find the .hi files.
This is used by Cabal for generating the ComponentId for a
package. The ComponentId must change when the visible ABI of
the package chagnes, so during registration Cabal calls ghc --abi-hash
to get a hash of the package's ABI.
-}
-- | Print ABI hash of input modules.
--
-- The resulting hash is the MD5 of the GHC version used (Trac #5328,
-- see 'hiVersion') and of the existing ABI hash from each module (see
-- 'mi_mod_hash').
abiHash :: [String] -- ^ List of module names
-> Ghc ()
abiHash strs = do
hsc_env <- getSession
let dflags = hsc_dflags hsc_env
liftIO $ do
let find_it str = do
let modname = mkModuleName str
r <- findImportedModule hsc_env modname Nothing
case r of
Found _ m -> return m
_error -> throwGhcException $ CmdLineError $ showSDoc dflags $
cannotFindInterface dflags modname r
mods <- mapM find_it strs
let get_iface modl = loadUserInterface False (text "abiHash") modl
ifaces <- initIfaceCheck hsc_env $ mapM get_iface mods
bh <- openBinMem (3*1024) -- just less than a block
put_ bh hiVersion
-- package hashes change when the compiler version changes (for now)
-- see #5328
mapM_ (put_ bh . mi_mod_hash) ifaces
f <- fingerprintBinMem bh
putStrLn (showPpr dflags f)
-- -----------------------------------------------------------------------------
-- Util
unknownFlagsErr :: [String] -> a
unknownFlagsErr fs = throwGhcException $ UsageError $ concatMap oneError fs
where
oneError f =
"unrecognised flag: " ++ f ++ "\n" ++
(case fuzzyMatch f (nub allFlags) of
[] -> ""
suggs -> "did you mean one of:\n" ++ unlines (map (" " ++) suggs))
{- Note [-Bsymbolic and hooks]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Bsymbolic is a flag that prevents the binding of references to global
symbols to symbols outside the shared library being compiled (see `man
ld`). When dynamically linking, we don't use -Bsymbolic on the RTS
package: that is because we want hooks to be overridden by the user,
we don't want to constrain them to the RTS package.
Unfortunately this seems to have broken somehow on OS X: as a result,
defaultHooks (in hschooks.c) is not called, which does not initialize
the GC stats. As a result, this breaks things like `:set +s` in GHCi
(#8754). As a hacky workaround, we instead call 'defaultHooks'
directly to initalize the flags in the RTS.
A byproduct of this, I believe, is that hooks are likely broken on OS
X when dynamically linking. But this probably doesn't affect most
people since we're linking GHC dynamically, but most things themselves
link statically.
-}
foreign import ccall safe "initGCStatistics"
initGCStatistics :: IO ()
|
AlexanderPankiv/ghc
|
ghc/Main.hs
|
bsd-3-clause
| 36,717 | 0 | 27 | 10,206 | 7,504 | 3,867 | 3,637 | 577 | 17 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- | This module implements predicate pushdown on comprehensions.
module Database.DSH.CL.Opt.PredPushdown
( predpushdownR
) where
import Control.Arrow
import qualified Data.List.NonEmpty as N
import qualified Data.Set as S
import Database.DSH.CL.Kure
import Database.DSH.CL.Lang
import Database.DSH.CL.Opt.Auxiliary
import qualified Database.DSH.CL.Primitives as P
import Database.DSH.Common.Lang
import Database.DSH.Common.Nat
import Database.DSH.Common.Kure
{-# ANN module "HLint: ignore Reduce duplication" #-}
--------------------------------------------------------------------------------
-- Auxiliary functions
-- | Return path to occurence of variable x
varPathT :: Ident -> TransformC CL PathC
varPathT x = do
Var _ x' <- promoteT idR
guardM $ x == x'
snocPathToPath <$> absPathT
-- | Collect all paths to variable x in the current expression and
-- turn them into relative paths.
allVarPathsT :: Ident -> TransformC CL [PathC]
allVarPathsT x = do
varPaths <- collectT $ varPathT x
guardM $ not $ null varPaths
parentPathLen <- length . snocPathToPath <$> absPathT
let localPaths = map (init . drop parentPathLen) varPaths
return localPaths
--------------------------------------------------------------------------
-- Push a guard into a branch of a join operator
-- | Try to push predicate into the left input of a binary operator
-- which produces tuples: equijoin, nestjoin
pushLeftTupleR :: Ident -> Expr -> RewriteC CL
pushLeftTupleR x p = do
AppE2 t op xs ys <- promoteT idR
let predTrans = constT $ return $ inject p
localPaths <- predTrans >>> allVarPathsT x
ExprCL p' <- predTrans >>> andR (map (unTuplifyPathR (== TupElem First)) localPaths)
let xst = typeOf xs
let filterComp = Comp xst (Var (elemT xst) x) (BindQ x xs :* S (GuardQ p'))
return $ inject $ AppE2 t op filterComp ys
-- | Try to push predicate into the right input of a binary operator
-- which produces tuples: equijoin
pushRightTupleR :: Ident -> Expr -> RewriteC CL
pushRightTupleR x p = do
AppE2 t op xs ys <- promoteT idR
let predTrans = constT $ return $ inject p
localPaths <- predTrans >>> allVarPathsT x
ExprCL p' <- predTrans >>> andR (map (unTuplifyPathR (== TupElem (Next First))) localPaths)
let yst = typeOf ys
let filterComp = Comp yst (Var (elemT yst) x) (BindQ x ys :* S (GuardQ p'))
return $ inject $ AppE2 t op xs filterComp
pushLeftOrRightTupleR :: Ident -> Expr -> RewriteC CL
pushLeftOrRightTupleR x p = pushLeftTupleR x p <+ pushRightTupleR x p
-- | Try to push predicates into the left input of a binary operator
-- which produces only the left input, i.e. semijoin, antijoin
pushLeftR :: Ident -> Expr -> RewriteC CL
pushLeftR x p = do
AppE2 ty op xs ys <- promoteT idR
let xst = typeOf xs
let xs' = Comp xst (Var (elemT xst) x) (BindQ x xs :* (S $ GuardQ p))
return $ inject $ AppE2 ty op xs' ys
--------------------------------------------------------------------------
-- Merging of join predicates into already established theta-join
-- operators
--
-- A predicate can be merged into a theta-join as an additional
-- conjunct if it has the shape of a join predicate and if its left
-- expression refers only to the fst component of the join pair and
-- the right expression refers only to the snd component (or vice
-- versa).
mkMergeableJoinPredT :: Ident -> Expr -> BinRelOp -> Expr -> TransformC CL (JoinConjunct ScalarExpr)
mkMergeableJoinPredT x leftExpr op rightExpr = do
let constLeftExpr = constT $ return $ inject leftExpr
constRightExpr = constT $ return $ inject rightExpr
leftVarPaths <- constLeftExpr >>> allVarPathsT x
rightVarPaths <- constRightExpr >>> allVarPathsT x
leftExpr' <- constLeftExpr
>>> andR (map (unTuplifyPathR (== TupElem First)) leftVarPaths)
>>> projectT
>>> toScalarExprT x
rightExpr' <- constRightExpr
>>> andR (map (unTuplifyPathR (== TupElem (Next First))) rightVarPaths)
>>> projectT
>>> toScalarExprT x
return $ JoinConjunct leftExpr' op rightExpr'
mirrorRelOp :: BinRelOp -> BinRelOp
mirrorRelOp Eq = Eq
mirrorRelOp Gt = Lt
mirrorRelOp GtE = LtE
mirrorRelOp Lt = Gt
mirrorRelOp LtE = GtE
mirrorRelOp NEq = NEq
splitMergeablePredT :: Ident -> Expr -> TransformC CL (JoinConjunct ScalarExpr)
splitMergeablePredT x p = do
ExprCL (BinOp _ (SBRelOp op) leftExpr rightExpr) <- return $ inject p
guardM $ freeVars p == [x]
-- We might have e1(fst x) op e2(snd x) or e1(snd x) op e2(fst x)
mkMergeableJoinPredT x leftExpr op rightExpr
<+ mkMergeableJoinPredT x rightExpr (mirrorRelOp op) leftExpr
-- | If a predicate can be turned into a join predicate, merge it into
-- the current theta join.
mergePredIntoJoinR :: Ident -> Expr -> RewriteC CL
mergePredIntoJoinR x p = do
AppE2 t (ThetaJoin (JoinPred ps)) xs ys <- promoteT idR
joinConjunct <- splitMergeablePredT x p
let extendedJoin = ThetaJoin (JoinPred $ joinConjunct N.<| ps)
return $ inject $ AppE2 t extendedJoin xs ys
-- | Push into the /first/ argument (input) of some operator that
-- commutes with selection.
-- This was nicer with a higher-order 'sortWith'. With first-order
-- 'sort', we have to push the predicate into both arguments, which
-- works only if the comprehension for the sorting criteria is still
-- in its original form.
pushSortInputR :: Ident -> Expr -> RewriteC CL
pushSortInputR x p = do
AppE1 t Sort xs <- promoteT idR
let xst = typeOf xs
xt = elemT xt
genVar = Var xt x
p' <- substM x (P.fst genVar) p
let restrictedInput = Comp xst genVar (BindQ x xs :* S (GuardQ p'))
return $ inject $ AppE1 t Sort restrictedInput
--------------------------------------------------------------------------
-- Take remaining comprehension guards and try to push them into the
-- generator. This might be accomplished by either merging it into a
-- join, pushing it into a join input or pushing it through some other
-- operator that commutes with selection (e.g. sorting).
pushPredicateR :: Ident -> Expr -> RewriteC CL
pushPredicateR x p =
readerT $ \e -> case e of
-- First, try to merge the predicate into the join. For
-- regular joins and products, non-join predicates might apply
-- to the left or right input.
ExprCL (AppE2 _ (ThetaJoin _) _ _) -> mergePredIntoJoinR x p
<+ pushLeftOrRightTupleR x p
ExprCL (AppE2 _ CartProduct _ _) -> pushLeftOrRightTupleR x p
-- For nesting operators, a guard can only refer to the left
-- input, i.e. the original outer generator.
ExprCL NestJoinP{} -> pushLeftTupleR x p
ExprCL GroupJoinP{} -> pushLeftTupleR x p
-- Semi- and Antijoin operators produce a subset of their left
-- input. A filter can only apply to the left input,
-- consequently.
ExprCL (AppE2 _ (SemiJoin _) _ _) -> pushLeftR x p
ExprCL (AppE2 _ (AntiJoin _) _ _) -> pushLeftR x p
-- Sorting commutes with selection
ExprCL (AppE1 _ Sort _) -> pushSortInputR x p
_ -> fail "expression does not allow predicate pushing"
pushQualsR :: RewriteC CL
pushQualsR = do
BindQ x _ :* GuardQ p :* qs <- promoteT idR
[x'] <- return $ freeVars p
guardM $ x == x'
ExprCL gen' <- pathT [QualsHead, BindQualExpr] (pushPredicateR x p)
return $ inject $ BindQ x gen' :* qs
pushQualsEndR :: RewriteC CL
pushQualsEndR = do
BindQ x _ :* S (GuardQ p) <- promoteT idR
[x'] <- return $ freeVars p
guardM $ x == x'
ExprCL gen' <- pathT [QualsHead, BindQualExpr] (pushPredicateR x p)
return $ inject $ S $ BindQ x gen'
pushDownSinglePredR :: RewriteC CL
pushDownSinglePredR = do
Comp{} <- promoteT idR
childR CompQuals (promoteR $ pushQualsR <+ pushQualsEndR)
pushDownPredsR :: MergeGuard
pushDownPredsR comp guard guardsToTry leftOverGuards = do
let C ty h qs = comp
env <- S.fromList . inScopeNames <$> contextT
let compExpr = ExprCL $ Comp ty h (insertGuard guard env qs)
ExprCL (Comp _ _ qs') <- constT (return compExpr) >>> pushDownSinglePredR
return (C ty h qs', guardsToTry, leftOverGuards)
-- | Push down all guards in a qualifier list, if possible.
predpushdownR :: RewriteC CL
predpushdownR = logR "predpushdown" $ mergeGuardsIterR pushDownPredsR
|
ulricha/dsh
|
src/Database/DSH/CL/Opt/PredPushdown.hs
|
bsd-3-clause
| 8,803 | 0 | 19 | 2,169 | 2,207 | 1,081 | 1,126 | 135 | 8 |
-- print information about the current package
-- (reads the cached build info, so only works after 'cabal configure')
import Prelude hiding (print)
import Distribution.Simple
import Distribution.Simple.LocalBuildInfo
import Distribution.Text
import System.Environment
readLocalBuildInfo :: IO LocalBuildInfo
readLocalBuildInfo = do
text <- readFile "dist/setup-config"
let body = dropWhile (/= '\n') text
return (read body)
print :: Text a => a -> IO ()
print x = putStrLn (display x)
main = do
arg <- getArgs
lbi <- readLocalBuildInfo
let lpc = localPkgDescr lbi
let pid = packageId lpc
case arg of
["--package"] -> print pid
["--package-name"] -> print (pkgName pid)
["--package-version"] -> print (pkgVersion pid)
|
Toxaris/pts
|
src-tools/package-info.hs
|
bsd-3-clause
| 768 | 0 | 12 | 153 | 222 | 110 | 112 | 21 | 3 |
module Spotify.Error (
Error(..),
spotifyError
) where
import qualified Bindings.Spotify.Error as SP
data Error = Ok
| ClientTooOld
| UnableToContactServer
| BadUsernameOrPassword
| UserBanned
| UserNeedsPremium
spotifyError :: SP.Error -> Error
spotifyError err | err == SP.ok = Ok
| err == SP.clientTooOld = ClientTooOld
| err == SP.unableToContactServer = UnableToContactServer
| err == SP.userBanned = UserBanned
| err == SP.userNeedsPremium = UserNeedsPremium
|
mrehayden1/harmony
|
Spotify/Error.hs
|
bsd-3-clause
| 639 | 0 | 9 | 237 | 140 | 76 | 64 | 16 | 1 |
-- | Immediate operand
module Haskus.Arch.X86_64.ISA.Immediate
( X86ImmFamP
, X86ImmFamT
, X86ImmFam
, X86Imm
, Imm (..)
, immFamFixedSize
, immFamOpSize
, immFamOpSizeSE
, immFamConst
)
where
import Haskus.Arch.X86_64.ISA.Size
import Haskus.Arch.X86_64.ISA.Solver
import Haskus.Arch.Common.Immediate
import Haskus.Utils.Solver
import Haskus.Format.Binary.Word
data ImmType
= ImmGeneric
deriving (Show,Eq,Ord)
type X86ImmFamP = ImmFamP X86Pred X86Err ImmType OperandSize
type X86ImmFamT = ImmFamT ImmType OperandSize
type X86ImmFam t = ImmFam t ImmType OperandSize
type X86Imm = Imm ImmType OperandSize
-- | Fixed size immediate
immFamFixedSize :: OperandSize -> X86ImmFamP
immFamFixedSize s = ImmFam
{ immFamSize = Terminal s
, immFamSignExtended = Terminal Nothing
, immFamValue = Terminal Nothing
, immFamType = Terminal Nothing
}
-- | Operand-sized immediate
immFamOpSize :: X86ImmFamP
immFamOpSize = ImmFam
{ immFamSize = pOpSize64 OpSize8 OpSize16 OpSize32 OpSize64
, immFamSignExtended = Terminal Nothing
, immFamValue = Terminal Nothing
, immFamType = Terminal (Just ImmGeneric)
}
-- | Operand-sized immediate (size-extendable if the bit is set or in 64-bit
-- mode)
immFamOpSizeSE :: X86ImmFamP
immFamOpSizeSE = ImmFam
{ immFamSize = orderedNonTerminal
[ (pForce8bit , Terminal OpSize8)
, (pSignExtendBit , Terminal OpSize8)
, (pOverriddenOperationSize64 OpSize16, Terminal OpSize16)
, (pOverriddenOperationSize64 OpSize32, Terminal OpSize32)
, (pOverriddenOperationSize64 OpSize64, Terminal OpSize32) -- sign-extend
]
, immFamSignExtended = orderedNonTerminal
[ (pOverriddenOperationSize64 OpSize64, Terminal $ Just OpSize64)
, (pSignExtendBit , NonTerminal
[ (pOverriddenOperationSize64 OpSize16, Terminal $ Just OpSize16)
, (pOverriddenOperationSize64 OpSize32, Terminal $ Just OpSize32)
])
, (CBool True , Terminal Nothing)
]
, immFamValue = Terminal Nothing
, immFamType = Terminal (Just ImmGeneric)
}
-- | Constant immediate
immFamConst :: OperandSize -> Word64 -> X86ImmFamP
immFamConst s v = ImmFam
{ immFamSize = Terminal s
, immFamSignExtended = Terminal Nothing
, immFamValue = Terminal (Just v)
, immFamType = Terminal Nothing
}
|
hsyl20/ViperVM
|
haskus-system/src/lib/Haskus/Arch/X86_64/ISA/Immediate.hs
|
bsd-3-clause
| 2,513 | 0 | 14 | 644 | 547 | 314 | 233 | 56 | 1 |
{-# OPTIONS -Wall -Werror #-}
module Test.TestEaster where
import Data.Time.Calendar.Easter
import Data.Time.Calendar
import Data.Time.Format
import Test.TestUtil
import Test.TestEasterRef
--
days :: [Day]
days = [ModifiedJulianDay 53000 .. ModifiedJulianDay 53014]
showWithWDay :: Day -> String
showWithWDay = formatTime defaultTimeLocale "%F %A"
testEaster :: Test
testEaster = pureTest "testEaster" $ let
ds = unlines $ map (\day ->
unwords [ showWithWDay day, "->"
, showWithWDay (sundayAfter day)]) days
f y = unwords [ show y ++ ", Gregorian: moon,"
, show (gregorianPaschalMoon y) ++ ": Easter,"
, showWithWDay (gregorianEaster y)]
++ "\n"
g y = unwords [ show y ++ ", Orthodox : moon,"
, show (orthodoxPaschalMoon y) ++ ": Easter,"
, showWithWDay (orthodoxEaster y)]
++ "\n"
in diff testEasterRef $ ds ++ concatMap (\y -> f y ++ g y) [2000..2020]
|
bergmark/time
|
test/Test/TestEaster.hs
|
bsd-3-clause
| 1,068 | 0 | 18 | 343 | 295 | 155 | 140 | 25 | 1 |
{-# LANGUAGE BangPatterns, CPP, MagicHash #-}
module Main ( main ) where
import Data.Bits
import GHC.Prim
import GHC.Word
#include "MachDeps.h"
main = putStr
(test_popCnt ++ "\n"
++ test_popCnt8 ++ "\n"
++ test_popCnt16 ++ "\n"
++ test_popCnt32 ++ "\n"
++ test_popCnt64 ++ "\n"
++ "\n"
)
popcnt :: Word -> Word
popcnt (W# w#) = W# (popCnt# w#)
popcnt8 :: Word -> Word
popcnt8 (W# w#) = W# (popCnt8# w#)
popcnt16 :: Word -> Word
popcnt16 (W# w#) = W# (popCnt16# w#)
popcnt32 :: Word -> Word
popcnt32 (W# w#) = W# (popCnt32# w#)
popcnt64 :: Word64 -> Word
popcnt64 (W64# w#) =
#if SIZEOF_HSWORD == 4
W# (popCnt64# w#)
#else
W# (popCnt# w#)
#endif
-- Cribbed from https://gitlab.haskell.org/ghc/ghc/issues/3563
slowPopcnt :: Word -> Word
slowPopcnt x = count' (bitSize x) x 0
where
count' 0 _ !acc = acc
count' n x acc = count' (n-1) (x `shiftR` 1)
(acc + if x .&. 1 == 1 then 1 else 0)
test_popCnt = test popcnt slowPopcnt
test_popCnt8 = test popcnt8 (slowPopcnt . fromIntegral . (mask 8 .&.))
test_popCnt16 = test popcnt16 (slowPopcnt . fromIntegral . (mask 16 .&.))
test_popCnt32 = test popcnt32 (slowPopcnt . fromIntegral . (mask 32 .&.))
test_popCnt64 = test popcnt64 (slowPopcnt . fromIntegral . (mask 64 .&.))
mask n = (2 ^ n) - 1
test :: (Show a, Num a) => (a -> Word) -> (a -> Word) -> String
test fast slow = case failing of
[] -> "OK"
((_, e, a, i):xs) ->
"FAIL\n" ++ " Input: " ++ show i ++ "\nExpected: " ++ show e ++
"\n Actual: " ++ show a
where
failing = dropWhile ( \(b,_,_,_) -> b)
. map (\ x -> (slow x == fast x, slow x, fast x, x)) $ cases
expected = map slow cases
actual = map fast cases
-- 10 random numbers
#if SIZEOF_HSWORD == 4
cases = [1480294021,1626858410,2316287658,1246556957,3806579062,65945563,
1521588071,791321966,1355466914,2284998160]
#elif SIZEOF_HSWORD == 8
cases = [11004539497957619752,5625461252166958202,1799960778872209546,
16979826074020750638,12789915432197771481,11680809699809094550,
13208678822802632247,13794454868797172383,13364728999716654549,
17516539991479925226]
#else
# error Unexpected word size
#endif
|
sdiehl/ghc
|
testsuite/tests/codeGen/should_run/cgrun071.hs
|
bsd-3-clause
| 2,285 | 0 | 16 | 560 | 743 | 399 | 344 | -1 | -1 |
{-
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
************************************************************************
* *
\section[FloatIn]{Floating Inwards pass}
* *
************************************************************************
The main purpose of @floatInwards@ is floating into branches of a
case, so that we don't allocate things, save them on the stack, and
then discover that they aren't needed in the chosen branch.
-}
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -fprof-auto #-}
module FloatIn ( floatInwards ) where
#include "HsVersions.h"
import GhcPrelude
import CoreSyn
import MkCore
import HscTypes ( ModGuts(..) )
import CoreUtils
import CoreFVs
import CoreMonad ( CoreM )
import Id ( isOneShotBndr, idType, isJoinId, isJoinId_maybe )
import Var
import Type
import VarSet
import Util
import DynFlags
import Outputable
-- import Data.List ( mapAccumL )
import BasicTypes ( RecFlag(..), isRec )
{-
Top-level interface function, @floatInwards@. Note that we do not
actually float any bindings downwards from the top-level.
-}
floatInwards :: ModGuts -> CoreM ModGuts
floatInwards pgm@(ModGuts { mg_binds = binds })
= do { dflags <- getDynFlags
; return (pgm { mg_binds = map (fi_top_bind dflags) binds }) }
where
fi_top_bind dflags (NonRec binder rhs)
= NonRec binder (fiExpr dflags [] (freeVars rhs))
fi_top_bind dflags (Rec pairs)
= Rec [ (b, fiExpr dflags [] (freeVars rhs)) | (b, rhs) <- pairs ]
{-
************************************************************************
* *
\subsection{Mail from Andr\'e [edited]}
* *
************************************************************************
{\em Will wrote: What??? I thought the idea was to float as far
inwards as possible, no matter what. This is dropping all bindings
every time it sees a lambda of any kind. Help! }
You are assuming we DO DO full laziness AFTER floating inwards! We
have to [not float inside lambdas] if we don't.
If we indeed do full laziness after the floating inwards (we could
check the compilation flags for that) then I agree we could be more
aggressive and do float inwards past lambdas.
Actually we are not doing a proper full laziness (see below), which
was another reason for not floating inwards past a lambda.
This can easily be fixed. The problem is that we float lets outwards,
but there are a few expressions which are not let bound, like case
scrutinees and case alternatives. After floating inwards the
simplifier could decide to inline the let and the laziness would be
lost, e.g.
\begin{verbatim}
let a = expensive ==> \b -> case expensive of ...
in \ b -> case a of ...
\end{verbatim}
The fix is
\begin{enumerate}
\item
to let bind the algebraic case scrutinees (done, I think) and
the case alternatives (except the ones with an
unboxed type)(not done, I think). This is best done in the
SetLevels.hs module, which tags things with their level numbers.
\item
do the full laziness pass (floating lets outwards).
\item
simplify. The simplifier inlines the (trivial) lets that were
created but were not floated outwards.
\end{enumerate}
With the fix I think Will's suggestion that we can gain even more from
strictness by floating inwards past lambdas makes sense.
We still gain even without going past lambdas, as things may be
strict in the (new) context of a branch (where it was floated to) or
of a let rhs, e.g.
\begin{verbatim}
let a = something case x of
in case x of alt1 -> case something of a -> a + a
alt1 -> a + a ==> alt2 -> b
alt2 -> b
let a = something let b = case something of a -> a + a
in let b = a + a ==> in (b,b)
in (b,b)
\end{verbatim}
Also, even if a is not found to be strict in the new context and is
still left as a let, if the branch is not taken (or b is not entered)
the closure for a is not built.
************************************************************************
* *
\subsection{Main floating-inwards code}
* *
************************************************************************
-}
type FreeVarSet = DIdSet
type BoundVarSet = DIdSet
data FloatInBind = FB BoundVarSet FreeVarSet FloatBind
-- The FreeVarSet is the free variables of the binding. In the case
-- of recursive bindings, the set doesn't include the bound
-- variables.
type FloatInBinds = [FloatInBind]
-- In reverse dependency order (innermost binder first)
fiExpr :: DynFlags
-> FloatInBinds -- Binds we're trying to drop
-- as far "inwards" as possible
-> CoreExprWithFVs -- Input expr
-> CoreExpr -- Result
fiExpr _ to_drop (_, AnnLit lit) = ASSERT( null to_drop ) Lit lit
fiExpr _ to_drop (_, AnnType ty) = ASSERT( null to_drop ) Type ty
fiExpr _ to_drop (_, AnnVar v) = wrapFloats to_drop (Var v)
fiExpr _ to_drop (_, AnnCoercion co) = wrapFloats to_drop (Coercion co)
fiExpr dflags to_drop (_, AnnCast expr (co_ann, co))
= wrapFloats (drop_here ++ co_drop) $
Cast (fiExpr dflags e_drop expr) co
where
[drop_here, e_drop, co_drop]
= sepBindsByDropPoint dflags False
[freeVarsOf expr, freeVarsOfAnn co_ann]
to_drop
{-
Applications: we do float inside applications, mainly because we
need to get at all the arguments. The next simplifier run will
pull out any silly ones.
-}
fiExpr dflags to_drop ann_expr@(_,AnnApp {})
= wrapFloats drop_here $ wrapFloats extra_drop $
mkTicks ticks $
mkApps (fiExpr dflags fun_drop ann_fun)
(zipWith (fiExpr dflags) arg_drops ann_args)
where
(ann_fun, ann_args, ticks) = collectAnnArgsTicks tickishFloatable ann_expr
fun_ty = exprType (deAnnotate ann_fun)
fun_fvs = freeVarsOf ann_fun
arg_fvs = map freeVarsOf ann_args
(drop_here : extra_drop : fun_drop : arg_drops)
= sepBindsByDropPoint dflags False
(extra_fvs : fun_fvs : arg_fvs)
to_drop
-- Shortcut behaviour: if to_drop is empty,
-- sepBindsByDropPoint returns a suitable bunch of empty
-- lists without evaluating extra_fvs, and hence without
-- peering into each argument
(_, extra_fvs) = foldl add_arg (fun_ty, extra_fvs0) ann_args
extra_fvs0 = case ann_fun of
(_, AnnVar _) -> fun_fvs
_ -> emptyDVarSet
-- Don't float the binding for f into f x y z; see Note [Join points]
-- for why we *can't* do it when f is a join point. (If f isn't a
-- join point, floating it in isn't especially harmful but it's
-- useless since the simplifier will immediately float it back out.)
add_arg :: (Type,FreeVarSet) -> CoreExprWithFVs -> (Type,FreeVarSet)
add_arg (fun_ty, extra_fvs) (_, AnnType ty)
= (piResultTy fun_ty ty, extra_fvs)
add_arg (fun_ty, extra_fvs) (arg_fvs, arg)
| noFloatIntoArg arg arg_ty
= (res_ty, extra_fvs `unionDVarSet` arg_fvs)
| otherwise
= (res_ty, extra_fvs)
where
(arg_ty, res_ty) = splitFunTy fun_ty
{-
Note [Do not destroy the let/app invariant]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Watch out for
f (x +# y)
We don't want to float bindings into here
f (case ... of { x -> x +# y })
because that might destroy the let/app invariant, which requires
unlifted function arguments to be ok-for-speculation.
Note [Join points]
~~~~~~~~~~~~~~~~~~
Generally, we don't need to worry about join points - there are places we're
not allowed to float them, but since they can't have occurrences in those
places, we're not tempted.
We do need to be careful about jumps, however:
joinrec j x y z = ... in
jump j a b c
Previous versions often floated the definition of a recursive function into its
only non-recursive occurrence. But for a join point, this is a disaster:
(joinrec j x y z = ... in
jump j) a b c -- wrong!
Every jump must be exact, so the jump to j must have three arguments. Hence
we're careful not to float into the target of a jump (though we can float into
the arguments just fine).
Note [Floating in past a lambda group]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* We must be careful about floating inside a value lambda.
That risks losing laziness.
The float-out pass might rescue us, but then again it might not.
* We must be careful about type lambdas too. At one time we did, and
there is no risk of duplicating work thereby, but we do need to be
careful. In particular, here is a bad case (it happened in the
cichelli benchmark:
let v = ...
in let f = /\t -> \a -> ...
==>
let f = /\t -> let v = ... in \a -> ...
This is bad as now f is an updatable closure (update PAP)
and has arity 0.
* Hack alert! We only float in through one-shot lambdas,
not (as you might guess) through lone big lambdas.
Reason: we float *out* past big lambdas (see the test in the Lam
case of FloatOut.floatExpr) and we don't want to float straight
back in again.
It *is* important to float into one-shot lambdas, however;
see the remarks with noFloatIntoRhs.
So we treat lambda in groups, using the following rule:
Float in if (a) there is at least one Id,
and (b) there are no non-one-shot Ids
Otherwise drop all the bindings outside the group.
This is what the 'go' function in the AnnLam case is doing.
(Join points are handled similarly: a join point is considered one-shot iff
it's non-recursive, so we float only into non-recursive join points.)
Urk! if all are tyvars, and we don't float in, we may miss an
opportunity to float inside a nested case branch
Note [Floating coercions]
~~~~~~~~~~~~~~~~~~~~~~~~~
We could, in principle, have a coercion binding like
case f x of co { DEFAULT -> e1 e2 }
It's not common to have a function that returns a coercion, but nothing
in Core prohibits it. If so, 'co' might be mentioned in e1 or e2
/only in a type/. E.g. suppose e1 was
let (x :: Int |> co) = blah in blah2
But, with coercions appearing in types, there is a complication: we
might be floating in a "strict let" -- that is, a case. Case expressions
mention their return type. We absolutely can't float a coercion binding
inward to the point that the type of the expression it's about to wrap
mentions the coercion. So we include the union of the sets of free variables
of the types of all the drop points involved. If any of the floaters
bind a coercion variable mentioned in any of the types, that binder must
be dropped right away.
-}
fiExpr dflags to_drop lam@(_, AnnLam _ _)
| noFloatIntoLam bndrs -- Dump it all here
-- NB: Must line up with noFloatIntoRhs (AnnLam...); see Trac #7088
= wrapFloats to_drop (mkLams bndrs (fiExpr dflags [] body))
| otherwise -- Float inside
= mkLams bndrs (fiExpr dflags to_drop body)
where
(bndrs, body) = collectAnnBndrs lam
{-
We don't float lets inwards past an SCC.
ToDo: keep info on current cc, and when passing
one, if it is not the same, annotate all lets in binds with current
cc, change current cc to the new one and float binds into expr.
-}
fiExpr dflags to_drop (_, AnnTick tickish expr)
| tickish `tickishScopesLike` SoftScope
= Tick tickish (fiExpr dflags to_drop expr)
| otherwise -- Wimp out for now - we could push values in
= wrapFloats to_drop (Tick tickish (fiExpr dflags [] expr))
{-
For @Lets@, the possible ``drop points'' for the \tr{to_drop}
bindings are: (a)~in the body, (b1)~in the RHS of a NonRec binding,
or~(b2), in each of the RHSs of the pairs of a @Rec@.
Note that we do {\em weird things} with this let's binding. Consider:
\begin{verbatim}
let
w = ...
in {
let v = ... w ...
in ... v .. w ...
}
\end{verbatim}
Look at the inner \tr{let}. As \tr{w} is used in both the bind and
body of the inner let, we could panic and leave \tr{w}'s binding where
it is. But \tr{v} is floatable further into the body of the inner let, and
{\em then} \tr{w} will also be only in the body of that inner let.
So: rather than drop \tr{w}'s binding here, we add it onto the list of
things to drop in the outer let's body, and let nature take its
course.
Note [extra_fvs (1): avoid floating into RHS]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider let x=\y....t... in body. We do not necessarily want to float
a binding for t into the RHS, because it'll immediately be floated out
again. (It won't go inside the lambda else we risk losing work.)
In letrec, we need to be more careful still. We don't want to transform
let x# = y# +# 1#
in
letrec f = \z. ...x#...f...
in ...
into
letrec f = let x# = y# +# 1# in \z. ...x#...f... in ...
because now we can't float the let out again, because a letrec
can't have unboxed bindings.
So we make "extra_fvs" which is the rhs_fvs of such bindings, and
arrange to dump bindings that bind extra_fvs before the entire let.
Note [extra_fvs (2): free variables of rules]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
let x{rule mentioning y} = rhs in body
Here y is not free in rhs or body; but we still want to dump bindings
that bind y outside the let. So we augment extra_fvs with the
idRuleAndUnfoldingVars of x. No need for type variables, hence not using
idFreeVars.
-}
fiExpr dflags to_drop (_,AnnLet bind body)
= fiExpr dflags (after ++ new_float : before) body
-- to_drop is in reverse dependency order
where
(before, new_float, after) = fiBind dflags to_drop bind body_fvs
body_fvs = freeVarsOf body
{- Note [Floating primops]
~~~~~~~~~~~~~~~~~~~~~~~~~~
We try to float-in a case expression over an unlifted type. The
motivating example was Trac #5658: in particular, this change allows
array indexing operations, which have a single DEFAULT alternative
without any binders, to be floated inward.
SIMD primops for unpacking SIMD vectors into an unboxed tuple of unboxed
scalars also need to be floated inward, but unpacks have a single non-DEFAULT
alternative that binds the elements of the tuple. We now therefore also support
floating in cases with a single alternative that may bind values.
But there are wrinkles
* Which unlifted cases do we float? See PrimOp.hs
Note [PrimOp can_fail and has_side_effects] which explains:
- We can float-in can_fail primops, but we can't float them out.
- But we can float a has_side_effects primop, but NOT inside a lambda,
so for now we don't float them at all.
Hence exprOkForSideEffects
* Because we can float can-fail primops (array indexing, division) inwards
but not outwards, we must be careful not to transform
case a /# b of r -> f (F# r)
===>
f (case a /# b of r -> F# r)
because that creates a new thunk that wasn't there before. And
because it can't be floated out (can_fail), the thunk will stay
there. Disaster! (This happened in nofib 'simple' and 'scs'.)
Solution: only float cases into the branches of other cases, and
not into the arguments of an application, or the RHS of a let. This
is somewhat conservative, but it's simple. And it still hits the
cases like Trac #5658. This is implemented in sepBindsByJoinPoint;
if is_case is False we dump all floating cases right here.
* Trac #14511 is another example of why we want to restrict float-in
of case-expressions. Consider
case indexArray# a n of (# r #) -> writeArray# ma i (f r)
Now, floating that indexing operation into the (f r) thunk will
not create any new thunks, but it will keep the array 'a' alive
for much longer than the programmer expected.
So again, not floating a case into a let or argument seems like
the Right Thing
For @Case@, the possible drop points for the 'to_drop'
bindings are:
(a) inside the scrutinee
(b) inside one of the alternatives/default (default FVs always /first/!).
-}
fiExpr dflags to_drop (_, AnnCase scrut case_bndr _ [(con,alt_bndrs,rhs)])
| isUnliftedType (idType case_bndr)
, exprOkForSideEffects (deAnnotate scrut)
-- See Note [Floating primops]
= wrapFloats shared_binds $
fiExpr dflags (case_float : rhs_binds) rhs
where
case_float = FB (mkDVarSet (case_bndr : alt_bndrs)) scrut_fvs
(FloatCase scrut' case_bndr con alt_bndrs)
scrut' = fiExpr dflags scrut_binds scrut
rhs_fvs = freeVarsOf rhs `delDVarSetList` (case_bndr : alt_bndrs)
scrut_fvs = freeVarsOf scrut
[shared_binds, scrut_binds, rhs_binds]
= sepBindsByDropPoint dflags False
[scrut_fvs, rhs_fvs]
to_drop
fiExpr dflags to_drop (_, AnnCase scrut case_bndr ty alts)
= wrapFloats drop_here1 $
wrapFloats drop_here2 $
Case (fiExpr dflags scrut_drops scrut) case_bndr ty
(zipWith fi_alt alts_drops_s alts)
where
-- Float into the scrut and alts-considered-together just like App
[drop_here1, scrut_drops, alts_drops]
= sepBindsByDropPoint dflags False
[scrut_fvs, all_alts_fvs]
to_drop
-- Float into the alts with the is_case flag set
(drop_here2 : alts_drops_s)
| [ _ ] <- alts = [] : [alts_drops]
| otherwise = sepBindsByDropPoint dflags True alts_fvs alts_drops
scrut_fvs = freeVarsOf scrut
alts_fvs = map alt_fvs alts
all_alts_fvs = unionDVarSets alts_fvs
alt_fvs (_con, args, rhs)
= foldl delDVarSet (freeVarsOf rhs) (case_bndr:args)
-- Delete case_bndr and args from free vars of rhs
-- to get free vars of alt
fi_alt to_drop (con, args, rhs) = (con, args, fiExpr dflags to_drop rhs)
------------------
fiBind :: DynFlags
-> FloatInBinds -- Binds we're trying to drop
-- as far "inwards" as possible
-> CoreBindWithFVs -- Input binding
-> DVarSet -- Free in scope of binding
-> ( FloatInBinds -- Land these before
, FloatInBind -- The binding itself
, FloatInBinds) -- Land these after
fiBind dflags to_drop (AnnNonRec id ann_rhs@(rhs_fvs, rhs)) body_fvs
= ( extra_binds ++ shared_binds -- Land these before
-- See Note [extra_fvs (1,2)]
, FB (unitDVarSet id) rhs_fvs' -- The new binding itself
(FloatLet (NonRec id rhs'))
, body_binds ) -- Land these after
where
body_fvs2 = body_fvs `delDVarSet` id
rule_fvs = bndrRuleAndUnfoldingVarsDSet id -- See Note [extra_fvs (2): free variables of rules]
extra_fvs | noFloatIntoRhs NonRecursive id rhs
= rule_fvs `unionDVarSet` rhs_fvs
| otherwise
= rule_fvs
-- See Note [extra_fvs (1): avoid floating into RHS]
-- No point in floating in only to float straight out again
-- We *can't* float into ok-for-speculation unlifted RHSs
-- But do float into join points
[shared_binds, extra_binds, rhs_binds, body_binds]
= sepBindsByDropPoint dflags False
[extra_fvs, rhs_fvs, body_fvs2]
to_drop
-- Push rhs_binds into the right hand side of the binding
rhs' = fiRhs dflags rhs_binds id ann_rhs
rhs_fvs' = rhs_fvs `unionDVarSet` floatedBindsFVs rhs_binds `unionDVarSet` rule_fvs
-- Don't forget the rule_fvs; the binding mentions them!
fiBind dflags to_drop (AnnRec bindings) body_fvs
= ( extra_binds ++ shared_binds
, FB (mkDVarSet ids) rhs_fvs'
(FloatLet (Rec (fi_bind rhss_binds bindings)))
, body_binds )
where
(ids, rhss) = unzip bindings
rhss_fvs = map freeVarsOf rhss
-- See Note [extra_fvs (1,2)]
rule_fvs = mapUnionDVarSet bndrRuleAndUnfoldingVarsDSet ids
extra_fvs = rule_fvs `unionDVarSet`
unionDVarSets [ rhs_fvs | (bndr, (rhs_fvs, rhs)) <- bindings
, noFloatIntoRhs Recursive bndr rhs ]
(shared_binds:extra_binds:body_binds:rhss_binds)
= sepBindsByDropPoint dflags False
(extra_fvs:body_fvs:rhss_fvs)
to_drop
rhs_fvs' = unionDVarSets rhss_fvs `unionDVarSet`
unionDVarSets (map floatedBindsFVs rhss_binds) `unionDVarSet`
rule_fvs -- Don't forget the rule variables!
-- Push rhs_binds into the right hand side of the binding
fi_bind :: [FloatInBinds] -- one per "drop pt" conjured w/ fvs_of_rhss
-> [(Id, CoreExprWithFVs)]
-> [(Id, CoreExpr)]
fi_bind to_drops pairs
= [ (binder, fiRhs dflags to_drop binder rhs)
| ((binder, rhs), to_drop) <- zipEqual "fi_bind" pairs to_drops ]
------------------
fiRhs :: DynFlags -> FloatInBinds -> CoreBndr -> CoreExprWithFVs -> CoreExpr
fiRhs dflags to_drop bndr rhs
| Just join_arity <- isJoinId_maybe bndr
, let (bndrs, body) = collectNAnnBndrs join_arity rhs
= mkLams bndrs (fiExpr dflags to_drop body)
| otherwise
= fiExpr dflags to_drop rhs
------------------
noFloatIntoLam :: [Var] -> Bool
noFloatIntoLam bndrs = any bad bndrs
where
bad b = isId b && not (isOneShotBndr b)
-- Don't float inside a non-one-shot lambda
noFloatIntoRhs :: RecFlag -> Id -> CoreExprWithFVs' -> Bool
-- ^ True if it's a bad idea to float bindings into this RHS
noFloatIntoRhs is_rec bndr rhs
| isJoinId bndr
= isRec is_rec -- Joins are one-shot iff non-recursive
| otherwise
= noFloatIntoArg rhs (idType bndr)
noFloatIntoArg :: CoreExprWithFVs' -> Type -> Bool
noFloatIntoArg expr expr_ty
| isUnliftedType expr_ty
= True -- See Note [Do not destroy the let/app invariant]
| AnnLam bndr e <- expr
, (bndrs, _) <- collectAnnBndrs e
= noFloatIntoLam (bndr:bndrs) -- Wrinkle 1 (a)
|| all isTyVar (bndr:bndrs) -- Wrinkle 1 (b)
-- See Note [noFloatInto considerations] wrinkle 2
| otherwise -- Note [noFloatInto considerations] wrinkle 2
= exprIsTrivial deann_expr || exprIsHNF deann_expr
where
deann_expr = deAnnotate' expr
{- Note [noFloatInto considerations]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When do we want to float bindings into
- noFloatIntoRHs: the RHS of a let-binding
- noFloatIntoArg: the argument of a function application
Definitely don't float in if it has unlifted type; that
would destroy the let/app invariant.
* Wrinkle 1: do not float in if
(a) any non-one-shot value lambdas
or (b) all type lambdas
In both cases we'll float straight back out again
NB: Must line up with fiExpr (AnnLam...); see Trac #7088
(a) is important: we /must/ float into a one-shot lambda group
(which includes join points). This makes a big difference
for things like
f x# = let x = I# x#
in let j = \() -> ...x...
in if <condition> then normal-path else j ()
If x is used only in the error case join point, j, we must float the
boxing constructor into it, else we box it every time which is very
bad news indeed.
* Wrinkle 2: for RHSs, do not float into a HNF; we'll just float right
back out again... not tragic, but a waste of time.
For function arguments we will still end up with this
in-then-out stuff; consider
letrec x = e in f x
Here x is not a HNF, so we'll produce
f (letrec x = e in x)
which is OK... it's not that common, and we'll end up
floating out again, in CorePrep if not earlier.
Still, we use exprIsTrivial to catch this case (sigh)
************************************************************************
* *
\subsection{@sepBindsByDropPoint@}
* *
************************************************************************
This is the crucial function. The idea is: We have a wad of bindings
that we'd like to distribute inside a collection of {\em drop points};
insides the alternatives of a \tr{case} would be one example of some
drop points; the RHS and body of a non-recursive \tr{let} binding
would be another (2-element) collection.
So: We're given a list of sets-of-free-variables, one per drop point,
and a list of floating-inwards bindings. If a binding can go into
only one drop point (without suddenly making something out-of-scope),
in it goes. If a binding is used inside {\em multiple} drop points,
then it has to go in a you-must-drop-it-above-all-these-drop-points
point.
We have to maintain the order on these drop-point-related lists.
-}
-- pprFIB :: FloatInBinds -> SDoc
-- pprFIB fibs = text "FIB:" <+> ppr [b | FB _ _ b <- fibs]
sepBindsByDropPoint
:: DynFlags
-> Bool -- True <=> is case expression
-> [FreeVarSet] -- One set of FVs per drop point
-- Always at least two long!
-> FloatInBinds -- Candidate floaters
-> [FloatInBinds] -- FIRST one is bindings which must not be floated
-- inside any drop point; the rest correspond
-- one-to-one with the input list of FV sets
-- Every input floater is returned somewhere in the result;
-- none are dropped, not even ones which don't seem to be
-- free in *any* of the drop-point fvs. Why? Because, for example,
-- a binding (let x = E in B) might have a specialised version of
-- x (say x') stored inside x, but x' isn't free in E or B.
type DropBox = (FreeVarSet, FloatInBinds)
sepBindsByDropPoint dflags is_case drop_pts floaters
| null floaters -- Shortcut common case
= [] : [[] | _ <- drop_pts]
| otherwise
= ASSERT( drop_pts `lengthAtLeast` 2 )
go floaters (map (\fvs -> (fvs, [])) (emptyDVarSet : drop_pts))
where
n_alts = length drop_pts
go :: FloatInBinds -> [DropBox] -> [FloatInBinds]
-- The *first* one in the argument list is the drop_here set
-- The FloatInBinds in the lists are in the reverse of
-- the normal FloatInBinds order; that is, they are the right way round!
go [] drop_boxes = map (reverse . snd) drop_boxes
go (bind_w_fvs@(FB bndrs bind_fvs bind) : binds) drop_boxes@(here_box : fork_boxes)
= go binds new_boxes
where
-- "here" means the group of bindings dropped at the top of the fork
(used_here : used_in_flags) = [ fvs `intersectsDVarSet` bndrs
| (fvs, _) <- drop_boxes]
drop_here = used_here || cant_push
n_used_alts = count id used_in_flags -- returns number of Trues in list.
cant_push
| is_case = n_used_alts == n_alts -- Used in all, don't push
-- Remember n_alts > 1
|| (n_used_alts > 1 && not (floatIsDupable dflags bind))
-- floatIsDupable: see Note [Duplicating floats]
| otherwise = floatIsCase bind || n_used_alts > 1
-- floatIsCase: see Note [Floating primops]
new_boxes | drop_here = (insert here_box : fork_boxes)
| otherwise = (here_box : new_fork_boxes)
new_fork_boxes = zipWithEqual "FloatIn.sepBinds" insert_maybe
fork_boxes used_in_flags
insert :: DropBox -> DropBox
insert (fvs,drops) = (fvs `unionDVarSet` bind_fvs, bind_w_fvs:drops)
insert_maybe box True = insert box
insert_maybe box False = box
go _ _ = panic "sepBindsByDropPoint/go"
{- Note [Duplicating floats]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For case expressions we duplicate the binding if it is reasonably
small, and if it is not used in all the RHSs This is good for
situations like
let x = I# y in
case e of
C -> error x
D -> error x
E -> ...not mentioning x...
If the thing is used in all RHSs there is nothing gained,
so we don't duplicate then.
-}
floatedBindsFVs :: FloatInBinds -> FreeVarSet
floatedBindsFVs binds = mapUnionDVarSet fbFVs binds
fbFVs :: FloatInBind -> DVarSet
fbFVs (FB _ fvs _) = fvs
wrapFloats :: FloatInBinds -> CoreExpr -> CoreExpr
-- Remember FloatInBinds is in *reverse* dependency order
wrapFloats [] e = e
wrapFloats (FB _ _ fl : bs) e = wrapFloats bs (wrapFloat fl e)
floatIsDupable :: DynFlags -> FloatBind -> Bool
floatIsDupable dflags (FloatCase scrut _ _ _) = exprIsDupable dflags scrut
floatIsDupable dflags (FloatLet (Rec prs)) = all (exprIsDupable dflags . snd) prs
floatIsDupable dflags (FloatLet (NonRec _ r)) = exprIsDupable dflags r
floatIsCase :: FloatBind -> Bool
floatIsCase (FloatCase {}) = True
floatIsCase (FloatLet {}) = False
|
ezyang/ghc
|
compiler/simplCore/FloatIn.hs
|
bsd-3-clause
| 29,172 | 0 | 15 | 7,505 | 3,336 | 1,787 | 1,549 | 242 | 4 |
-----------------------------------------------------------------------------
-- |
-- Module : Control.Monad.RWS
-- Copyright : (c) Andy Gill 2001,
-- (c) Oregon Graduate Institute of Science and Technology, 2001
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : non-portable (multi-param classes, functional dependencies)
--
-- Declaration of the MonadRWS class.
--
-- Inspired by the paper
-- /Functional Programming with Overloading and Higher-Order Polymorphism/,
-- Mark P Jones (<http://web.cecs.pdx.edu/~mpj/>)
-- Advanced School of Functional Programming, 1995.
-----------------------------------------------------------------------------
module Control.Monad.RWS (
module Control.Monad.RWS.Lazy
) where
import Control.Monad.RWS.Lazy
|
johanneshilden/principle
|
public/mtl-2.2.1/Control/Monad/RWS.hs
|
bsd-3-clause
| 895 | 0 | 5 | 162 | 42 | 35 | 7 | 3 | 0 |
module Syntax where
type Name = String
data Expr
= Var Name
| Lit Ground
| App Expr Expr
| Lam Name Type Expr
deriving (Eq, Show)
data Ground
= LInt Int
| LBool Bool
deriving (Show, Eq, Ord)
data Type
= TInt
| TBool
| TArr Type Type
deriving (Eq, Read, Show)
|
yupferris/write-you-a-haskell
|
chapter5/stlc/Syntax.hs
|
mit
| 287 | 0 | 6 | 81 | 112 | 64 | 48 | 17 | 0 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="si-LK">
<title>Passive Scan Rules | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
thc202/zap-extensions
|
addOns/pscanrules/src/main/javahelp/org/zaproxy/zap/extension/pscanrules/resources/help_si_LK/helpset_si_LK.hs
|
apache-2.0
| 979 | 78 | 66 | 160 | 415 | 210 | 205 | -1 | -1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ro-RO">
<title>All In One Notes Add-On</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
thc202/zap-extensions
|
addOns/allinonenotes/src/main/javahelp/org/zaproxy/zap/extension/allinonenotes/resources/help_ro_RO/helpset_ro_RO.hs
|
apache-2.0
| 968 | 77 | 67 | 159 | 417 | 211 | 206 | -1 | -1 |
module HLearn.Optimization.StepSize
(
-- * fancy step sizes
-- ** Almeida Langlois
lrAlmeidaLanglois
-- * simple step sizes
-- ** linear decrease
, lrLinear
, eta
-- , gamma
-- ** constant step size
, lrConst
-- , step
)
where
import HLearn.Optimization.StepSize.Linear
import HLearn.Optimization.StepSize.Const
import HLearn.Optimization.StepSize.AlmeidaLanglois
|
mikeizbicki/HLearn
|
src/HLearn/Optimization/StepSize.hs
|
bsd-3-clause
| 427 | 0 | 4 | 110 | 49 | 36 | 13 | 9 | 0 |
module PatBindIn3 where
--A definition can be lifted from a where or let to the top level binding group.
--Lifting a definition widens the scope of the definition.
--In this example, lift 'sq' defined in 'sumSquares'
--This example aims to test changing a constant to a function.
sumSquares x = (sq x pow) + (sq x pow)
where
pow =2
sq x pow = x^pow
anotherFun 0 y = sq y
where sq x = x^2
|
kmate/HaRe
|
old/testing/liftToToplevel/PatBindIn3_TokOut.hs
|
bsd-3-clause
| 454 | 0 | 7 | 142 | 84 | 45 | 39 | 6 | 1 |
module HAD.Y2014.M04.D09.Exercise where
-- $setup
-- >>> import Data.List
data Foo = Foo {x :: Int, y :: String, z :: String}
deriving (Read, Show, Eq)
{- | orderXYZ
Order Foo by x then by y and then by z
prop> sort xs == (map x . orderXYZ . map (\v -> Foo v "y" "z")) xs
prop> sort xs == (map y . orderXYZ . map (\v -> Foo 42 v "z")) xs
prop> sort xs == (map z . orderXYZ . map (\v -> Foo 42 "y" v )) xs
-}
orderXYZ :: [Foo] -> [Foo]
orderXYZ = undefined
|
1HaskellADay/1HAD
|
exercises/HAD/Y2014/M04/D09/Exercise.hs
|
mit
| 481 | 0 | 8 | 126 | 74 | 47 | 27 | 5 | 1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP, NoImplicitPrelude, BangPatterns, MagicHash, UnboxedTuples #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Word
-- Copyright : (c) The University of Glasgow, 1997-2002
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- Sized unsigned integral types: 'Word', 'Word8', 'Word16', 'Word32', and
-- 'Word64'.
--
-----------------------------------------------------------------------------
#include "MachDeps.h"
module GHC.Word (
Word(..), Word8(..), Word16(..), Word32(..), Word64(..),
uncheckedShiftL64#,
uncheckedShiftRL64#,
byteSwap16,
byteSwap32,
byteSwap64
) where
import Data.Bits
import Data.Maybe
#if WORD_SIZE_IN_BITS < 64
import GHC.IntWord64
#endif
-- import {-# SOURCE #-} GHC.Exception
import GHC.Base
import GHC.Enum
import GHC.Num
import GHC.Real
import GHC.Read
import GHC.Arr
import GHC.Show
import GHC.Float () -- for RealFrac methods
------------------------------------------------------------------------
-- type Word8
------------------------------------------------------------------------
-- Word8 is represented in the same way as Word. Operations may assume
-- and must ensure that it holds only values from its logical range.
data {-# CTYPE "HsWord8" #-} Word8 = W8# Word# deriving (Eq, Ord)
-- ^ 8-bit unsigned integer type
instance Show Word8 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
instance Num Word8 where
(W8# x#) + (W8# y#) = W8# (narrow8Word# (x# `plusWord#` y#))
(W8# x#) - (W8# y#) = W8# (narrow8Word# (x# `minusWord#` y#))
(W8# x#) * (W8# y#) = W8# (narrow8Word# (x# `timesWord#` y#))
negate (W8# x#) = W8# (narrow8Word# (int2Word# (negateInt# (word2Int# x#))))
abs x = x
signum 0 = 0
signum _ = 1
fromInteger i = W8# (narrow8Word# (integerToWord i))
instance Real Word8 where
toRational x = toInteger x % 1
instance Enum Word8 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Word8"
pred x
| x /= minBound = x - 1
| otherwise = predError "Word8"
toEnum i@(I# i#)
| i >= 0 && i <= fromIntegral (maxBound::Word8)
= W8# (int2Word# i#)
| otherwise = toEnumError "Word8" i (minBound::Word8, maxBound::Word8)
fromEnum (W8# x#) = I# (word2Int# x#)
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
instance Integral Word8 where
quot (W8# x#) y@(W8# y#)
| y /= 0 = W8# (x# `quotWord#` y#)
| otherwise = divZeroError
rem (W8# x#) y@(W8# y#)
| y /= 0 = W8# (x# `remWord#` y#)
| otherwise = divZeroError
div (W8# x#) y@(W8# y#)
| y /= 0 = W8# (x# `quotWord#` y#)
| otherwise = divZeroError
mod (W8# x#) y@(W8# y#)
| y /= 0 = W8# (x# `remWord#` y#)
| otherwise = divZeroError
quotRem (W8# x#) y@(W8# y#)
| y /= 0 = case x# `quotRemWord#` y# of
(# q, r #) ->
(W8# q, W8# r)
| otherwise = divZeroError
divMod (W8# x#) y@(W8# y#)
| y /= 0 = (W8# (x# `quotWord#` y#), W8# (x# `remWord#` y#))
| otherwise = divZeroError
toInteger (W8# x#) = smallInteger (word2Int# x#)
instance Bounded Word8 where
minBound = 0
maxBound = 0xFF
instance Ix Word8 where
range (m,n) = [m..n]
unsafeIndex (m,_) i = fromIntegral (i - m)
inRange (m,n) i = m <= i && i <= n
instance Read Word8 where
readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]
instance Bits Word8 where
{-# INLINE shift #-}
{-# INLINE bit #-}
{-# INLINE testBit #-}
(W8# x#) .&. (W8# y#) = W8# (x# `and#` y#)
(W8# x#) .|. (W8# y#) = W8# (x# `or#` y#)
(W8# x#) `xor` (W8# y#) = W8# (x# `xor#` y#)
complement (W8# x#) = W8# (x# `xor#` mb#)
where !(W8# mb#) = maxBound
(W8# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = W8# (narrow8Word# (x# `shiftL#` i#))
| otherwise = W8# (x# `shiftRL#` negateInt# i#)
(W8# x#) `shiftL` (I# i#) = W8# (narrow8Word# (x# `shiftL#` i#))
(W8# x#) `unsafeShiftL` (I# i#) =
W8# (narrow8Word# (x# `uncheckedShiftL#` i#))
(W8# x#) `shiftR` (I# i#) = W8# (x# `shiftRL#` i#)
(W8# x#) `unsafeShiftR` (I# i#) = W8# (x# `uncheckedShiftRL#` i#)
(W8# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#) = W8# x#
| otherwise = W8# (narrow8Word# ((x# `uncheckedShiftL#` i'#) `or#`
(x# `uncheckedShiftRL#` (8# -# i'#))))
where
!i'# = word2Int# (int2Word# i# `and#` 7##)
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
isSigned _ = False
popCount (W8# x#) = I# (word2Int# (popCnt8# x#))
bit = bitDefault
testBit = testBitDefault
instance FiniteBits Word8 where
finiteBitSize _ = 8
{-# RULES
"fromIntegral/Word8->Word8" fromIntegral = id :: Word8 -> Word8
"fromIntegral/Word8->Integer" fromIntegral = toInteger :: Word8 -> Integer
"fromIntegral/a->Word8" fromIntegral = \x -> case fromIntegral x of W# x# -> W8# (narrow8Word# x#)
"fromIntegral/Word8->a" fromIntegral = \(W8# x#) -> fromIntegral (W# x#)
#-}
{-# RULES
"properFraction/Float->(Word8,Float)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word8) n, y :: Float) }
"truncate/Float->Word8"
truncate = (fromIntegral :: Int -> Word8) . (truncate :: Float -> Int)
"floor/Float->Word8"
floor = (fromIntegral :: Int -> Word8) . (floor :: Float -> Int)
"ceiling/Float->Word8"
ceiling = (fromIntegral :: Int -> Word8) . (ceiling :: Float -> Int)
"round/Float->Word8"
round = (fromIntegral :: Int -> Word8) . (round :: Float -> Int)
#-}
{-# RULES
"properFraction/Double->(Word8,Double)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word8) n, y :: Double) }
"truncate/Double->Word8"
truncate = (fromIntegral :: Int -> Word8) . (truncate :: Double -> Int)
"floor/Double->Word8"
floor = (fromIntegral :: Int -> Word8) . (floor :: Double -> Int)
"ceiling/Double->Word8"
ceiling = (fromIntegral :: Int -> Word8) . (ceiling :: Double -> Int)
"round/Double->Word8"
round = (fromIntegral :: Int -> Word8) . (round :: Double -> Int)
#-}
------------------------------------------------------------------------
-- type Word16
------------------------------------------------------------------------
-- Word16 is represented in the same way as Word. Operations may assume
-- and must ensure that it holds only values from its logical range.
data {-# CTYPE "HsWord16" #-} Word16 = W16# Word# deriving (Eq, Ord)
-- ^ 16-bit unsigned integer type
instance Show Word16 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
instance Num Word16 where
(W16# x#) + (W16# y#) = W16# (narrow16Word# (x# `plusWord#` y#))
(W16# x#) - (W16# y#) = W16# (narrow16Word# (x# `minusWord#` y#))
(W16# x#) * (W16# y#) = W16# (narrow16Word# (x# `timesWord#` y#))
negate (W16# x#) = W16# (narrow16Word# (int2Word# (negateInt# (word2Int# x#))))
abs x = x
signum 0 = 0
signum _ = 1
fromInteger i = W16# (narrow16Word# (integerToWord i))
instance Real Word16 where
toRational x = toInteger x % 1
instance Enum Word16 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Word16"
pred x
| x /= minBound = x - 1
| otherwise = predError "Word16"
toEnum i@(I# i#)
| i >= 0 && i <= fromIntegral (maxBound::Word16)
= W16# (int2Word# i#)
| otherwise = toEnumError "Word16" i (minBound::Word16, maxBound::Word16)
fromEnum (W16# x#) = I# (word2Int# x#)
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
instance Integral Word16 where
quot (W16# x#) y@(W16# y#)
| y /= 0 = W16# (x# `quotWord#` y#)
| otherwise = divZeroError
rem (W16# x#) y@(W16# y#)
| y /= 0 = W16# (x# `remWord#` y#)
| otherwise = divZeroError
div (W16# x#) y@(W16# y#)
| y /= 0 = W16# (x# `quotWord#` y#)
| otherwise = divZeroError
mod (W16# x#) y@(W16# y#)
| y /= 0 = W16# (x# `remWord#` y#)
| otherwise = divZeroError
quotRem (W16# x#) y@(W16# y#)
| y /= 0 = case x# `quotRemWord#` y# of
(# q, r #) ->
(W16# q, W16# r)
| otherwise = divZeroError
divMod (W16# x#) y@(W16# y#)
| y /= 0 = (W16# (x# `quotWord#` y#), W16# (x# `remWord#` y#))
| otherwise = divZeroError
toInteger (W16# x#) = smallInteger (word2Int# x#)
instance Bounded Word16 where
minBound = 0
maxBound = 0xFFFF
instance Ix Word16 where
range (m,n) = [m..n]
unsafeIndex (m,_) i = fromIntegral (i - m)
inRange (m,n) i = m <= i && i <= n
instance Read Word16 where
readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]
instance Bits Word16 where
{-# INLINE shift #-}
{-# INLINE bit #-}
{-# INLINE testBit #-}
(W16# x#) .&. (W16# y#) = W16# (x# `and#` y#)
(W16# x#) .|. (W16# y#) = W16# (x# `or#` y#)
(W16# x#) `xor` (W16# y#) = W16# (x# `xor#` y#)
complement (W16# x#) = W16# (x# `xor#` mb#)
where !(W16# mb#) = maxBound
(W16# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = W16# (narrow16Word# (x# `shiftL#` i#))
| otherwise = W16# (x# `shiftRL#` negateInt# i#)
(W16# x#) `shiftL` (I# i#) = W16# (narrow16Word# (x# `shiftL#` i#))
(W16# x#) `unsafeShiftL` (I# i#) =
W16# (narrow16Word# (x# `uncheckedShiftL#` i#))
(W16# x#) `shiftR` (I# i#) = W16# (x# `shiftRL#` i#)
(W16# x#) `unsafeShiftR` (I# i#) = W16# (x# `uncheckedShiftRL#` i#)
(W16# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#) = W16# x#
| otherwise = W16# (narrow16Word# ((x# `uncheckedShiftL#` i'#) `or#`
(x# `uncheckedShiftRL#` (16# -# i'#))))
where
!i'# = word2Int# (int2Word# i# `and#` 15##)
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
isSigned _ = False
popCount (W16# x#) = I# (word2Int# (popCnt16# x#))
bit = bitDefault
testBit = testBitDefault
instance FiniteBits Word16 where
finiteBitSize _ = 16
-- | Swap bytes in 'Word16'.
--
-- /Since: 4.7.0.0/
byteSwap16 :: Word16 -> Word16
byteSwap16 (W16# w#) = W16# (narrow16Word# (byteSwap16# w#))
{-# RULES
"fromIntegral/Word8->Word16" fromIntegral = \(W8# x#) -> W16# x#
"fromIntegral/Word16->Word16" fromIntegral = id :: Word16 -> Word16
"fromIntegral/Word16->Integer" fromIntegral = toInteger :: Word16 -> Integer
"fromIntegral/a->Word16" fromIntegral = \x -> case fromIntegral x of W# x# -> W16# (narrow16Word# x#)
"fromIntegral/Word16->a" fromIntegral = \(W16# x#) -> fromIntegral (W# x#)
#-}
{-# RULES
"properFraction/Float->(Word16,Float)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word16) n, y :: Float) }
"truncate/Float->Word16"
truncate = (fromIntegral :: Int -> Word16) . (truncate :: Float -> Int)
"floor/Float->Word16"
floor = (fromIntegral :: Int -> Word16) . (floor :: Float -> Int)
"ceiling/Float->Word16"
ceiling = (fromIntegral :: Int -> Word16) . (ceiling :: Float -> Int)
"round/Float->Word16"
round = (fromIntegral :: Int -> Word16) . (round :: Float -> Int)
#-}
{-# RULES
"properFraction/Double->(Word16,Double)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word16) n, y :: Double) }
"truncate/Double->Word16"
truncate = (fromIntegral :: Int -> Word16) . (truncate :: Double -> Int)
"floor/Double->Word16"
floor = (fromIntegral :: Int -> Word16) . (floor :: Double -> Int)
"ceiling/Double->Word16"
ceiling = (fromIntegral :: Int -> Word16) . (ceiling :: Double -> Int)
"round/Double->Word16"
round = (fromIntegral :: Int -> Word16) . (round :: Double -> Int)
#-}
------------------------------------------------------------------------
-- type Word32
------------------------------------------------------------------------
-- Word32 is represented in the same way as Word.
#if WORD_SIZE_IN_BITS > 32
-- Operations may assume and must ensure that it holds only values
-- from its logical range.
-- We can use rewrite rules for the RealFrac methods
{-# RULES
"properFraction/Float->(Word32,Float)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word32) n, y :: Float) }
"truncate/Float->Word32"
truncate = (fromIntegral :: Int -> Word32) . (truncate :: Float -> Int)
"floor/Float->Word32"
floor = (fromIntegral :: Int -> Word32) . (floor :: Float -> Int)
"ceiling/Float->Word32"
ceiling = (fromIntegral :: Int -> Word32) . (ceiling :: Float -> Int)
"round/Float->Word32"
round = (fromIntegral :: Int -> Word32) . (round :: Float -> Int)
#-}
{-# RULES
"properFraction/Double->(Word32,Double)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word32) n, y :: Double) }
"truncate/Double->Word32"
truncate = (fromIntegral :: Int -> Word32) . (truncate :: Double -> Int)
"floor/Double->Word32"
floor = (fromIntegral :: Int -> Word32) . (floor :: Double -> Int)
"ceiling/Double->Word32"
ceiling = (fromIntegral :: Int -> Word32) . (ceiling :: Double -> Int)
"round/Double->Word32"
round = (fromIntegral :: Int -> Word32) . (round :: Double -> Int)
#-}
#endif
data {-# CTYPE "HsWord32" #-} Word32 = W32# Word# deriving (Eq, Ord)
-- ^ 32-bit unsigned integer type
instance Num Word32 where
(W32# x#) + (W32# y#) = W32# (narrow32Word# (x# `plusWord#` y#))
(W32# x#) - (W32# y#) = W32# (narrow32Word# (x# `minusWord#` y#))
(W32# x#) * (W32# y#) = W32# (narrow32Word# (x# `timesWord#` y#))
negate (W32# x#) = W32# (narrow32Word# (int2Word# (negateInt# (word2Int# x#))))
abs x = x
signum 0 = 0
signum _ = 1
fromInteger i = W32# (narrow32Word# (integerToWord i))
instance Enum Word32 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Word32"
pred x
| x /= minBound = x - 1
| otherwise = predError "Word32"
toEnum i@(I# i#)
| i >= 0
#if WORD_SIZE_IN_BITS > 32
&& i <= fromIntegral (maxBound::Word32)
#endif
= W32# (int2Word# i#)
| otherwise = toEnumError "Word32" i (minBound::Word32, maxBound::Word32)
#if WORD_SIZE_IN_BITS == 32
fromEnum x@(W32# x#)
| x <= fromIntegral (maxBound::Int)
= I# (word2Int# x#)
| otherwise = fromEnumError "Word32" x
enumFrom = integralEnumFrom
enumFromThen = integralEnumFromThen
enumFromTo = integralEnumFromTo
enumFromThenTo = integralEnumFromThenTo
#else
fromEnum (W32# x#) = I# (word2Int# x#)
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
#endif
instance Integral Word32 where
quot (W32# x#) y@(W32# y#)
| y /= 0 = W32# (x# `quotWord#` y#)
| otherwise = divZeroError
rem (W32# x#) y@(W32# y#)
| y /= 0 = W32# (x# `remWord#` y#)
| otherwise = divZeroError
div (W32# x#) y@(W32# y#)
| y /= 0 = W32# (x# `quotWord#` y#)
| otherwise = divZeroError
mod (W32# x#) y@(W32# y#)
| y /= 0 = W32# (x# `remWord#` y#)
| otherwise = divZeroError
quotRem (W32# x#) y@(W32# y#)
| y /= 0 = case x# `quotRemWord#` y# of
(# q, r #) ->
(W32# q, W32# r)
| otherwise = divZeroError
divMod (W32# x#) y@(W32# y#)
| y /= 0 = (W32# (x# `quotWord#` y#), W32# (x# `remWord#` y#))
| otherwise = divZeroError
toInteger (W32# x#)
#if WORD_SIZE_IN_BITS == 32
| isTrue# (i# >=# 0#) = smallInteger i#
| otherwise = wordToInteger x#
where
!i# = word2Int# x#
#else
= smallInteger (word2Int# x#)
#endif
instance Bits Word32 where
{-# INLINE shift #-}
{-# INLINE bit #-}
{-# INLINE testBit #-}
(W32# x#) .&. (W32# y#) = W32# (x# `and#` y#)
(W32# x#) .|. (W32# y#) = W32# (x# `or#` y#)
(W32# x#) `xor` (W32# y#) = W32# (x# `xor#` y#)
complement (W32# x#) = W32# (x# `xor#` mb#)
where !(W32# mb#) = maxBound
(W32# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = W32# (narrow32Word# (x# `shiftL#` i#))
| otherwise = W32# (x# `shiftRL#` negateInt# i#)
(W32# x#) `shiftL` (I# i#) = W32# (narrow32Word# (x# `shiftL#` i#))
(W32# x#) `unsafeShiftL` (I# i#) =
W32# (narrow32Word# (x# `uncheckedShiftL#` i#))
(W32# x#) `shiftR` (I# i#) = W32# (x# `shiftRL#` i#)
(W32# x#) `unsafeShiftR` (I# i#) = W32# (x# `uncheckedShiftRL#` i#)
(W32# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#) = W32# x#
| otherwise = W32# (narrow32Word# ((x# `uncheckedShiftL#` i'#) `or#`
(x# `uncheckedShiftRL#` (32# -# i'#))))
where
!i'# = word2Int# (int2Word# i# `and#` 31##)
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
isSigned _ = False
popCount (W32# x#) = I# (word2Int# (popCnt32# x#))
bit = bitDefault
testBit = testBitDefault
instance FiniteBits Word32 where
finiteBitSize _ = 32
{-# RULES
"fromIntegral/Word8->Word32" fromIntegral = \(W8# x#) -> W32# x#
"fromIntegral/Word16->Word32" fromIntegral = \(W16# x#) -> W32# x#
"fromIntegral/Word32->Word32" fromIntegral = id :: Word32 -> Word32
"fromIntegral/Word32->Integer" fromIntegral = toInteger :: Word32 -> Integer
"fromIntegral/a->Word32" fromIntegral = \x -> case fromIntegral x of W# x# -> W32# (narrow32Word# x#)
"fromIntegral/Word32->a" fromIntegral = \(W32# x#) -> fromIntegral (W# x#)
#-}
instance Show Word32 where
#if WORD_SIZE_IN_BITS < 33
showsPrec p x = showsPrec p (toInteger x)
#else
showsPrec p x = showsPrec p (fromIntegral x :: Int)
#endif
instance Real Word32 where
toRational x = toInteger x % 1
instance Bounded Word32 where
minBound = 0
maxBound = 0xFFFFFFFF
instance Ix Word32 where
range (m,n) = [m..n]
unsafeIndex (m,_) i = fromIntegral (i - m)
inRange (m,n) i = m <= i && i <= n
instance Read Word32 where
#if WORD_SIZE_IN_BITS < 33
readsPrec p s = [(fromInteger x, r) | (x, r) <- readsPrec p s]
#else
readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]
#endif
-- | Reverse order of bytes in 'Word32'.
--
-- /Since: 4.7.0.0/
byteSwap32 :: Word32 -> Word32
byteSwap32 (W32# w#) = W32# (narrow32Word# (byteSwap32# w#))
------------------------------------------------------------------------
-- type Word64
------------------------------------------------------------------------
#if WORD_SIZE_IN_BITS < 64
data {-# CTYPE "HsWord64" #-} Word64 = W64# Word64#
-- ^ 64-bit unsigned integer type
instance Eq Word64 where
(W64# x#) == (W64# y#) = isTrue# (x# `eqWord64#` y#)
(W64# x#) /= (W64# y#) = isTrue# (x# `neWord64#` y#)
instance Ord Word64 where
(W64# x#) < (W64# y#) = isTrue# (x# `ltWord64#` y#)
(W64# x#) <= (W64# y#) = isTrue# (x# `leWord64#` y#)
(W64# x#) > (W64# y#) = isTrue# (x# `gtWord64#` y#)
(W64# x#) >= (W64# y#) = isTrue# (x# `geWord64#` y#)
instance Num Word64 where
(W64# x#) + (W64# y#) = W64# (int64ToWord64# (word64ToInt64# x# `plusInt64#` word64ToInt64# y#))
(W64# x#) - (W64# y#) = W64# (int64ToWord64# (word64ToInt64# x# `minusInt64#` word64ToInt64# y#))
(W64# x#) * (W64# y#) = W64# (int64ToWord64# (word64ToInt64# x# `timesInt64#` word64ToInt64# y#))
negate (W64# x#) = W64# (int64ToWord64# (negateInt64# (word64ToInt64# x#)))
abs x = x
signum 0 = 0
signum _ = 1
fromInteger i = W64# (integerToWord64 i)
instance Enum Word64 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Word64"
pred x
| x /= minBound = x - 1
| otherwise = predError "Word64"
toEnum i@(I# i#)
| i >= 0 = W64# (wordToWord64# (int2Word# i#))
| otherwise = toEnumError "Word64" i (minBound::Word64, maxBound::Word64)
fromEnum x@(W64# x#)
| x <= fromIntegral (maxBound::Int)
= I# (word2Int# (word64ToWord# x#))
| otherwise = fromEnumError "Word64" x
enumFrom = integralEnumFrom
enumFromThen = integralEnumFromThen
enumFromTo = integralEnumFromTo
enumFromThenTo = integralEnumFromThenTo
instance Integral Word64 where
quot (W64# x#) y@(W64# y#)
| y /= 0 = W64# (x# `quotWord64#` y#)
| otherwise = divZeroError
rem (W64# x#) y@(W64# y#)
| y /= 0 = W64# (x# `remWord64#` y#)
| otherwise = divZeroError
div (W64# x#) y@(W64# y#)
| y /= 0 = W64# (x# `quotWord64#` y#)
| otherwise = divZeroError
mod (W64# x#) y@(W64# y#)
| y /= 0 = W64# (x# `remWord64#` y#)
| otherwise = divZeroError
quotRem (W64# x#) y@(W64# y#)
| y /= 0 = (W64# (x# `quotWord64#` y#), W64# (x# `remWord64#` y#))
| otherwise = divZeroError
divMod (W64# x#) y@(W64# y#)
| y /= 0 = (W64# (x# `quotWord64#` y#), W64# (x# `remWord64#` y#))
| otherwise = divZeroError
toInteger (W64# x#) = word64ToInteger x#
instance Bits Word64 where
{-# INLINE shift #-}
{-# INLINE bit #-}
{-# INLINE testBit #-}
(W64# x#) .&. (W64# y#) = W64# (x# `and64#` y#)
(W64# x#) .|. (W64# y#) = W64# (x# `or64#` y#)
(W64# x#) `xor` (W64# y#) = W64# (x# `xor64#` y#)
complement (W64# x#) = W64# (not64# x#)
(W64# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = W64# (x# `shiftL64#` i#)
| otherwise = W64# (x# `shiftRL64#` negateInt# i#)
(W64# x#) `shiftL` (I# i#) = W64# (x# `shiftL64#` i#)
(W64# x#) `unsafeShiftL` (I# i#) = W64# (x# `uncheckedShiftL64#` i#)
(W64# x#) `shiftR` (I# i#) = W64# (x# `shiftRL64#` i#)
(W64# x#) `unsafeShiftR` (I# i#) = W64# (x# `uncheckedShiftRL64#` i#)
(W64# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#) = W64# x#
| otherwise = W64# ((x# `uncheckedShiftL64#` i'#) `or64#`
(x# `uncheckedShiftRL64#` (64# -# i'#)))
where
!i'# = word2Int# (int2Word# i# `and#` 63##)
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
isSigned _ = False
popCount (W64# x#) = I# (word2Int# (popCnt64# x#))
bit = bitDefault
testBit = testBitDefault
-- give the 64-bit shift operations the same treatment as the 32-bit
-- ones (see GHC.Base), namely we wrap them in tests to catch the
-- cases when we're shifting more than 64 bits to avoid unspecified
-- behaviour in the C shift operations.
shiftL64#, shiftRL64# :: Word64# -> Int# -> Word64#
a `shiftL64#` b | isTrue# (b >=# 64#) = wordToWord64# 0##
| otherwise = a `uncheckedShiftL64#` b
a `shiftRL64#` b | isTrue# (b >=# 64#) = wordToWord64# 0##
| otherwise = a `uncheckedShiftRL64#` b
{-# RULES
"fromIntegral/Int->Word64" fromIntegral = \(I# x#) -> W64# (int64ToWord64# (intToInt64# x#))
"fromIntegral/Word->Word64" fromIntegral = \(W# x#) -> W64# (wordToWord64# x#)
"fromIntegral/Word64->Int" fromIntegral = \(W64# x#) -> I# (word2Int# (word64ToWord# x#))
"fromIntegral/Word64->Word" fromIntegral = \(W64# x#) -> W# (word64ToWord# x#)
"fromIntegral/Word64->Word64" fromIntegral = id :: Word64 -> Word64
#-}
#else
-- Word64 is represented in the same way as Word.
-- Operations may assume and must ensure that it holds only values
-- from its logical range.
data {-# CTYPE "HsWord64" #-} Word64 = W64# Word# deriving (Eq, Ord)
-- ^ 64-bit unsigned integer type
instance Num Word64 where
(W64# x#) + (W64# y#) = W64# (x# `plusWord#` y#)
(W64# x#) - (W64# y#) = W64# (x# `minusWord#` y#)
(W64# x#) * (W64# y#) = W64# (x# `timesWord#` y#)
negate (W64# x#) = W64# (int2Word# (negateInt# (word2Int# x#)))
abs x = x
signum 0 = 0
signum _ = 1
fromInteger i = W64# (integerToWord i)
instance Enum Word64 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Word64"
pred x
| x /= minBound = x - 1
| otherwise = predError "Word64"
toEnum i@(I# i#)
| i >= 0 = W64# (int2Word# i#)
| otherwise = toEnumError "Word64" i (minBound::Word64, maxBound::Word64)
fromEnum x@(W64# x#)
| x <= fromIntegral (maxBound::Int)
= I# (word2Int# x#)
| otherwise = fromEnumError "Word64" x
enumFrom = integralEnumFrom
enumFromThen = integralEnumFromThen
enumFromTo = integralEnumFromTo
enumFromThenTo = integralEnumFromThenTo
instance Integral Word64 where
quot (W64# x#) y@(W64# y#)
| y /= 0 = W64# (x# `quotWord#` y#)
| otherwise = divZeroError
rem (W64# x#) y@(W64# y#)
| y /= 0 = W64# (x# `remWord#` y#)
| otherwise = divZeroError
div (W64# x#) y@(W64# y#)
| y /= 0 = W64# (x# `quotWord#` y#)
| otherwise = divZeroError
mod (W64# x#) y@(W64# y#)
| y /= 0 = W64# (x# `remWord#` y#)
| otherwise = divZeroError
quotRem (W64# x#) y@(W64# y#)
| y /= 0 = case x# `quotRemWord#` y# of
(# q, r #) ->
(W64# q, W64# r)
| otherwise = divZeroError
divMod (W64# x#) y@(W64# y#)
| y /= 0 = (W64# (x# `quotWord#` y#), W64# (x# `remWord#` y#))
| otherwise = divZeroError
toInteger (W64# x#)
| isTrue# (i# >=# 0#) = smallInteger i#
| otherwise = wordToInteger x#
where
!i# = word2Int# x#
instance Bits Word64 where
{-# INLINE shift #-}
{-# INLINE bit #-}
{-# INLINE testBit #-}
(W64# x#) .&. (W64# y#) = W64# (x# `and#` y#)
(W64# x#) .|. (W64# y#) = W64# (x# `or#` y#)
(W64# x#) `xor` (W64# y#) = W64# (x# `xor#` y#)
complement (W64# x#) = W64# (x# `xor#` mb#)
where !(W64# mb#) = maxBound
(W64# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = W64# (x# `shiftL#` i#)
| otherwise = W64# (x# `shiftRL#` negateInt# i#)
(W64# x#) `shiftL` (I# i#) = W64# (x# `shiftL#` i#)
(W64# x#) `unsafeShiftL` (I# i#) = W64# (x# `uncheckedShiftL#` i#)
(W64# x#) `shiftR` (I# i#) = W64# (x# `shiftRL#` i#)
(W64# x#) `unsafeShiftR` (I# i#) = W64# (x# `uncheckedShiftRL#` i#)
(W64# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#) = W64# x#
| otherwise = W64# ((x# `uncheckedShiftL#` i'#) `or#`
(x# `uncheckedShiftRL#` (64# -# i'#)))
where
!i'# = word2Int# (int2Word# i# `and#` 63##)
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
isSigned _ = False
popCount (W64# x#) = I# (word2Int# (popCnt64# x#))
bit = bitDefault
testBit = testBitDefault
{-# RULES
"fromIntegral/a->Word64" fromIntegral = \x -> case fromIntegral x of W# x# -> W64# x#
"fromIntegral/Word64->a" fromIntegral = \(W64# x#) -> fromIntegral (W# x#)
#-}
uncheckedShiftL64# :: Word# -> Int# -> Word#
uncheckedShiftL64# = uncheckedShiftL#
uncheckedShiftRL64# :: Word# -> Int# -> Word#
uncheckedShiftRL64# = uncheckedShiftRL#
#endif
instance FiniteBits Word64 where
finiteBitSize _ = 64
instance Show Word64 where
showsPrec p x = showsPrec p (toInteger x)
instance Real Word64 where
toRational x = toInteger x % 1
instance Bounded Word64 where
minBound = 0
maxBound = 0xFFFFFFFFFFFFFFFF
instance Ix Word64 where
range (m,n) = [m..n]
unsafeIndex (m,_) i = fromIntegral (i - m)
inRange (m,n) i = m <= i && i <= n
instance Read Word64 where
readsPrec p s = [(fromInteger x, r) | (x, r) <- readsPrec p s]
-- | Reverse order of bytes in 'Word64'.
--
-- /Since: 4.7.0.0/
#if WORD_SIZE_IN_BITS < 64
byteSwap64 :: Word64 -> Word64
byteSwap64 (W64# w#) = W64# (byteSwap64# w#)
#else
byteSwap64 :: Word64 -> Word64
byteSwap64 (W64# w#) = W64# (byteSwap# w#)
#endif
|
frantisekfarka/ghc-dsi
|
libraries/base/GHC/Word.hs
|
bsd-3-clause
| 31,190 | 0 | 15 | 10,149 | 7,329 | 3,805 | 3,524 | 473 | 1 |
-- | Some helpers for interrogating a WAI 'Request'.
module Network.Wai.Request
( appearsSecure
, guessApproot
) where
import Data.ByteString (ByteString)
import Data.Maybe (fromMaybe)
import Network.HTTP.Types (HeaderName)
import Network.Wai (Request, isSecure, requestHeaders, requestHeaderHost)
import qualified Data.ByteString as S
import qualified Data.ByteString.Char8 as C
-- | Does this request appear to have been made over an SSL connection?
--
-- This function first checks @'isSecure'@, but also checks for headers that may
-- indicate a secure connection even in the presence of reverse proxies.
--
-- Note: these headers can be easily spoofed, so decisions which require a true
-- SSL connection (i.e. sending sensitive information) should only use
-- @'isSecure'@. This is not always the case though: for example, deciding to
-- force a non-SSL request to SSL by redirect. One can safely choose not to
-- redirect when the request /appears/ secure, even if it's actually not.
--
-- Since 3.0.7
appearsSecure :: Request -> Bool
appearsSecure request = isSecure request || any (uncurry matchHeader)
[ ("HTTPS" , (== "on"))
, ("HTTP_X_FORWARDED_SSL" , (== "on"))
, ("HTTP_X_FORWARDED_SCHEME", (== "https"))
, ("HTTP_X_FORWARDED_PROTO" , ((== ["https"]) . take 1 . C.split ','))
, ("X-Forwarded-Proto" , (== "https")) -- Used by Nginx and AWS ELB.
]
where
matchHeader :: HeaderName -> (ByteString -> Bool) -> Bool
matchHeader h f = maybe False f $ lookup h $ requestHeaders request
-- | Guess the \"application root\" based on the given request.
--
-- The application root is the basis for forming URLs pointing at the current
-- application. For more information and relevant caveats, please see
-- "Network.Wai.Middleware.Approot".
--
-- Since 3.0.7
guessApproot :: Request -> ByteString
guessApproot req =
(if appearsSecure req then "https://" else "http://") `S.append`
(fromMaybe "localhost" $ requestHeaderHost req)
|
dylex/wai
|
wai-extra/Network/Wai/Request.hs
|
mit
| 2,017 | 0 | 13 | 373 | 328 | 201 | 127 | 22 | 2 |
{-| A data structure for measuring how many of a number of available slots are
taken.
-}
{-
Copyright (C) 2014 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.SlotMap
( Slot(..)
, SlotMap
, CountMap
, toCountMap
, isOverfull
, occupySlots
, hasSlotsFor
) where
import Data.Map (Map)
import qualified Data.Map as Map
{-# ANN module "HLint: ignore Avoid lambda" #-} -- to not suggest (`Slot` 0)
-- | A resource with [limit] available units and [occupied] of them taken.
data Slot = Slot
{ slotOccupied :: Int
, slotLimit :: Int
} deriving (Eq, Ord, Show)
-- | A set of keys of type @a@ and how many slots are available and (to be)
-- occupied per key.
--
-- Some keys can be overfull (more slots occupied than available).
type SlotMap a = Map a Slot
-- | A set of keys of type @a@ and how many there are of each.
type CountMap a = Map a Int
-- | Turns a `SlotMap` into a `CountMap` by throwing away the limits.
toCountMap :: SlotMap a -> CountMap a
toCountMap = Map.map slotOccupied
-- | Whether any more slots are occupied than available.
isOverfull :: SlotMap a -> Bool
isOverfull m = or [ occup > limit | Slot occup limit <- Map.elems m ]
-- | Fill slots of a `SlotMap`s by adding the given counts.
-- Keys with counts that don't appear in the `SlotMap` get a limit of 0.
occupySlots :: (Ord a) => SlotMap a -> CountMap a -> SlotMap a
occupySlots sm counts = Map.unionWith
(\(Slot o l) (Slot n _) -> Slot (o + n) l)
sm
(Map.map (\n -> Slot n 0) counts)
-- | Whether the `SlotMap` has enough slots free to accomodate the given
-- counts.
--
-- The `SlotMap` is allowed to be overfull in some keys; this function
-- still returns True as long as as adding the counts to the `SlotMap` would
-- not *create or increase* overfull keys.
--
-- Adding counts > 0 for a key which is not in the `SlotMap` does create
-- overfull keys.
hasSlotsFor :: (Ord a) => SlotMap a -> CountMap a -> Bool
slotMap `hasSlotsFor` counts =
let relevantSlots = slotMap `Map.intersection` counts
in not $ isOverfull (relevantSlots `occupySlots` counts)
|
grnet/snf-ganeti
|
src/Ganeti/SlotMap.hs
|
bsd-2-clause
| 3,394 | 0 | 10 | 700 | 394 | 223 | 171 | 30 | 1 |
-- !!! Testing the Word Enum instances.
{-# LANGUAGE CPP #-}
module Main(main) where
import Control.Exception
import Data.Word
import Data.Int
main = do
putStrLn "Testing Enum Word8:"
testEnumWord8
putStrLn "Testing Enum Word16:"
testEnumWord16
putStrLn "Testing Enum Word32:"
testEnumWord32
putStrLn "Testing Enum Word64:"
testEnumWord64
#define printTest(x) (do{ putStr ( " " ++ "x" ++ " = " ) ; print (x) })
testEnumWord8 :: IO ()
testEnumWord8 = do
-- succ
printTest ((succ (0::Word8)))
printTest ((succ (minBound::Word8)))
mayBomb (printTest ((succ (maxBound::Word8))))
-- pred
printTest (pred (1::Word8))
printTest (pred (maxBound::Word8))
mayBomb (printTest (pred (minBound::Word8)))
-- toEnum
printTest ((map (toEnum::Int->Word8) [1, fromIntegral (minBound::Word8)::Int, fromIntegral (maxBound::Word8)::Int]))
mayBomb (printTest ((toEnum (maxBound::Int))::Word8))
-- fromEnum
printTest ((map fromEnum [(1::Word8),minBound,maxBound]))
-- [x..] aka enumFrom
printTest ((take 7 [(1::Word8)..]))
printTest ((take 7 [((maxBound::Word8)-5)..])) -- just in case it doesn't catch the upper bound..
-- [x,y..] aka enumFromThen
printTest ((take 7 [(1::Word8),2..]))
printTest ((take 7 [(1::Word8),7..]))
printTest ((take 7 [(1::Word8),1..]))
printTest ((take 7 [(1::Word8),0..]))
printTest ((take 7 [(5::Word8),2..]))
let x = (minBound::Word8) + 1
printTest ((take 7 [x, x-1 ..]))
let x = (minBound::Word8) + 5
printTest ((take 7 [x, x-1 ..]))
let x = (maxBound::Word8) - 5
printTest ((take 7 [x, (x+1) ..]))
-- [x..y] aka enumFromTo
printTest ((take 7 ([(1::Word8) .. 5])))
printTest ((take 4 ([(1::Word8) .. 1])))
printTest ((take 7 ([(1::Word8) .. 0])))
printTest ((take 7 ([(5::Word8) .. 0])))
printTest ((take 7 ([(maxBound-(5::Word8)) .. maxBound])))
printTest ((take 7 ([(minBound+(5::Word8)) .. minBound])))
-- [x,y..z] aka enumFromThenTo
printTest ((take 7 [(5::Word8),4..1]))
printTest ((take 7 [(5::Word8),3..1]))
printTest ((take 7 [(5::Word8),3..2]))
printTest ((take 7 [(1::Word8),2..1]))
printTest ((take 7 [(2::Word8),1..2]))
printTest ((take 7 [(2::Word8),1..1]))
printTest ((take 7 [(2::Word8),3..1]))
let x = (maxBound::Word8) - 4
printTest ((take 7 [x,(x+1)..maxBound]))
let x = (minBound::Word8) + 5
printTest ((take 7 [x,(x-1)..minBound]))
testEnumWord16 :: IO ()
testEnumWord16 = do
-- succ
printTest ((succ (0::Word16)))
printTest ((succ (minBound::Word16)))
mayBomb (printTest ((succ (maxBound::Word16))))
-- pred
printTest (pred (1::Word16))
printTest (pred (maxBound::Word16))
mayBomb (printTest (pred (minBound::Word16)))
-- toEnum
printTest ((map (toEnum::Int->Word16) [1, fromIntegral (minBound::Word16)::Int, fromIntegral (maxBound::Word16)::Int]))
mayBomb (printTest ((toEnum (maxBound::Int))::Word16))
-- fromEnum
printTest ((map fromEnum [(1::Word16),minBound,maxBound]))
-- [x..] aka enumFrom
printTest ((take 7 [(1::Word16)..]))
printTest ((take 7 [((maxBound::Word16)-5)..])) -- just in case it doesn't catch the upper bound..
-- [x,y..] aka enumFromThen
printTest ((take 7 [(1::Word16),2..]))
printTest ((take 7 [(1::Word16),7..]))
printTest ((take 7 [(1::Word16),1..]))
printTest ((take 7 [(1::Word16),0..]))
printTest ((take 7 [(5::Word16),2..]))
let x = (minBound::Word16) + 1
printTest ((take 7 [x, x-1 ..]))
let x = (minBound::Word16) + 5
printTest ((take 7 [x, x-1 ..]))
let x = (maxBound::Word16) - 5
printTest ((take 7 [x, (x+1) ..]))
-- [x..y] aka enumFromTo
printTest ((take 7 ([(1::Word16) .. 5])))
printTest ((take 4 ([(1::Word16) .. 1])))
printTest ((take 7 ([(1::Word16) .. 0])))
printTest ((take 7 ([(5::Word16) .. 0])))
printTest ((take 7 ([(maxBound-(5::Word16)) .. maxBound])))
printTest ((take 7 ([(minBound+(5::Word16)) .. minBound])))
-- [x,y..z] aka enumFromThenTo
printTest ((take 7 [(5::Word16),4..1]))
printTest ((take 7 [(5::Word16),3..1]))
printTest ((take 7 [(5::Word16),3..2]))
printTest ((take 7 [(1::Word16),2..1]))
printTest ((take 7 [(2::Word16),1..2]))
printTest ((take 7 [(2::Word16),1..1]))
printTest ((take 7 [(2::Word16),3..1]))
let x = (maxBound::Word16) - 4
printTest ((take 7 [x,(x+1)..maxBound]))
let x = (minBound::Word16) + 5
printTest ((take 7 [x,(x-1)..minBound]))
testEnumWord32 :: IO ()
testEnumWord32 = do
-- succ
printTest ((succ (0::Word32)))
printTest ((succ (minBound::Word32)))
mayBomb (printTest ((succ (maxBound::Word32))))
-- pred
printTest (pred (1::Word32))
printTest (pred (maxBound::Word32))
mayBomb (printTest (pred (minBound::Word32)))
-- toEnum
printTest ((map (toEnum::Int->Word32) [1, fromIntegral (minBound::Word32)::Int, fromIntegral (maxBound::Int32)::Int]))
mayBomb (printTest ((toEnum (maxBound::Int))::Word32))
-- fromEnum
printTest ((map fromEnum [(1::Word32),minBound,fromIntegral (maxBound::Int)]))
mayBomb (printTest (fromEnum (maxBound::Word32)))
-- [x..] aka enumFrom
printTest ((take 7 [(1::Word32)..]))
printTest ((take 7 [((maxBound::Word32)-5)..])) -- just in case it doesn't catch the upper bound..
-- [x,y..] aka enumFromThen
printTest ((take 7 [(1::Word32),2..]))
printTest ((take 7 [(1::Word32),7..]))
printTest ((take 7 [(1::Word32),1..]))
printTest ((take 7 [(1::Word32),0..]))
printTest ((take 7 [(5::Word32),2..]))
let x = (minBound::Word32) + 1
printTest ((take 7 [x, x-1 ..]))
let x = (minBound::Word32) + 5
printTest ((take 7 [x, x-1 ..]))
let x = (maxBound::Word32) - 5
printTest ((take 7 [x, (x+1) ..]))
-- [x..y] aka enumFromTo
printTest ((take 7 ([(1::Word32) .. 5])))
printTest ((take 4 ([(1::Word32) .. 1])))
printTest ((take 7 ([(1::Word32) .. 0])))
printTest ((take 7 ([(5::Word32) .. 0])))
printTest ((take 7 ([(maxBound-(5::Word32)) .. maxBound])))
printTest ((take 7 ([(minBound+(5::Word32)) .. minBound])))
-- [x,y..z] aka enumFromThenTo
printTest ((take 7 [(5::Word32),4..1]))
printTest ((take 7 [(5::Word32),3..1]))
printTest ((take 7 [(5::Word32),3..2]))
printTest ((take 7 [(1::Word32),2..1]))
printTest ((take 7 [(2::Word32),1..2]))
printTest ((take 7 [(2::Word32),1..1]))
printTest ((take 7 [(2::Word32),3..1]))
let x = (maxBound::Word32) - 4
printTest ((take 7 [x,(x+1)..maxBound]))
let x = (minBound::Word32) + 5
printTest ((take 7 [x,(x-1)..minBound]))
testEnumWord64 :: IO ()
testEnumWord64 = do
-- succ
printTest ((succ (0::Word64)))
printTest ((succ (minBound::Word64)))
mayBomb (printTest ((succ (maxBound::Word64))))
-- pred
printTest (pred (1::Word64))
printTest (pred (maxBound::Word64))
mayBomb (printTest (pred (minBound::Word64)))
-- toEnum
mayBomb (printTest ((map (toEnum::Int->Word64) [1, fromIntegral (minBound::Word64)::Int, maxBound::Int])))
mayBomb (printTest ((toEnum (maxBound::Int))::Word64))
-- fromEnum
printTest ((map fromEnum [(1::Word64),minBound,fromIntegral (maxBound::Int)]))
mayBomb (printTest (fromEnum (maxBound::Word64)))
-- [x..] aka enumFrom
printTest ((take 7 [(1::Word64)..]))
printTest ((take 7 [((maxBound::Word64)-5)..])) -- just in case it doesn't catch the upper bound..
-- [x,y..] aka enumFromThen
printTest ((take 7 [(1::Word64),2..]))
printTest ((take 7 [(1::Word64),7..]))
printTest ((take 7 [(1::Word64),1..]))
printTest ((take 7 [(1::Word64),0..]))
printTest ((take 7 [(5::Word64),2..]))
let x = (minBound::Word64) + 1
printTest ((take 7 [x, x-1 ..]))
let x = (minBound::Word64) + 5
printTest ((take 7 [x, x-1 ..]))
let x = (maxBound::Word64) - 5
printTest ((take 7 [x, (x+1) ..]))
-- [x..y] aka enumFromTo
printTest ((take 7 ([(1::Word64) .. 5])))
printTest ((take 4 ([(1::Word64) .. 1])))
printTest ((take 7 ([(1::Word64) .. 0])))
printTest ((take 7 ([(5::Word64) .. 0])))
printTest ((take 7 ([(maxBound-(5::Word64)) .. maxBound])))
printTest ((take 7 ([(minBound+(5::Word64)) .. minBound])))
-- [x,y..z] aka enumFromThenTo
printTest ((take 7 [(5::Word64),4..1]))
printTest ((take 7 [(5::Word64),3..1]))
printTest ((take 7 [(5::Word64),3..2]))
printTest ((take 7 [(1::Word64),2..1]))
printTest ((take 7 [(2::Word64),1..2]))
printTest ((take 7 [(2::Word64),1..1]))
printTest ((take 7 [(2::Word64),3..1]))
let x = (maxBound::Word64) - 4
printTest ((take 7 [x,(x+1)..maxBound]))
let x = (minBound::Word64) + 5
printTest ((take 7 [x,(x-1)..minBound]))
--
--
-- Utils
--
--
mayBomb x = catch x (\(ErrorCall e) -> putStrLn ("error " ++ show e))
`catch` (\e -> putStrLn ("Fail: " ++ show (e :: SomeException)))
|
green-haskell/ghc
|
libraries/base/tests/enum03.hs
|
bsd-3-clause
| 8,784 | 0 | 15 | 1,583 | 4,801 | 2,625 | 2,176 | 182 | 1 |
{-# LANGUAGE DeriveTraversable #-}
import Data.Monoid (Endo (..))
import Control.Exception (evaluate)
data Tree a = Bin !(Tree a) a !(Tree a) | Tip
deriving (Functor, Foldable)
t1, t2, t3, t4, t5 :: Tree ()
t1 = Bin Tip () Tip
t2 = Bin t1 () t1
t3 = Bin t2 () t2
t4 = Bin t3 () t3
t5 = Bin t4 () t4
t6 = Bin t5 () t5
t7 = Bin t6 () t6
replaceManyTimes :: Functor f => f a -> f Int
replaceManyTimes xs = appEndo
(foldMap (\x -> Endo (x <$)) [1..20000])
(0 <$ xs)
main :: IO ()
main = do
evaluate $ sum $ replaceManyTimes t7
pure ()
|
ezyang/ghc
|
testsuite/tests/perf/should_run/T13218.hs
|
bsd-3-clause
| 546 | 0 | 11 | 130 | 291 | 153 | 138 | 25 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.JHC
-- Copyright : Isaac Jones 2003-2006
-- License : BSD3
--
-- Maintainer : [email protected]
-- Portability : portable
--
-- This module contains most of the JHC-specific code for configuring, building
-- and installing packages.
module Distribution.Simple.JHC (
configure, getInstalledPackages,
buildLib, buildExe,
installLib, installExe
) where
import Distribution.PackageDescription as PD
( PackageDescription(..), BuildInfo(..), Executable(..)
, Library(..), libModules, hcOptions, usedExtensions )
import Distribution.InstalledPackageInfo
( emptyInstalledPackageInfo, )
import qualified Distribution.InstalledPackageInfo as InstalledPackageInfo
import Distribution.Simple.PackageIndex (InstalledPackageIndex)
import qualified Distribution.Simple.PackageIndex as PackageIndex
import Distribution.Simple.LocalBuildInfo
( LocalBuildInfo(..), ComponentLocalBuildInfo(..) )
import Distribution.Simple.BuildPaths
( autogenModulesDir, exeExtension )
import Distribution.Simple.Compiler
( CompilerFlavor(..), CompilerId(..), Compiler(..), AbiTag(..)
, PackageDBStack, Flag, languageToFlags, extensionsToFlags )
import Language.Haskell.Extension
( Language(Haskell98), Extension(..), KnownExtension(..))
import Distribution.Simple.Program
( ConfiguredProgram(..), jhcProgram, ProgramConfiguration
, userMaybeSpecifyPath, requireProgramVersion, lookupProgram
, rawSystemProgram, rawSystemProgramStdoutConf )
import Distribution.Version
( Version(..), orLaterVersion )
import Distribution.Package
( Package(..), InstalledPackageId(InstalledPackageId),
pkgName, pkgVersion, )
import Distribution.Simple.Utils
( createDirectoryIfMissingVerbose, writeFileAtomic
, installOrdinaryFile, installExecutableFile
, intercalate )
import System.FilePath ( (</>) )
import Distribution.Verbosity
import Distribution.Text
( Text(parse), display )
import Distribution.Compat.ReadP
( readP_to_S, string, skipSpaces )
import Distribution.System ( Platform )
import Data.List ( nub )
import Data.Char ( isSpace )
import qualified Data.Map as M ( empty )
import Data.Maybe ( fromMaybe )
import qualified Data.ByteString.Lazy.Char8 as BS.Char8
-- -----------------------------------------------------------------------------
-- Configuring
configure :: Verbosity -> Maybe FilePath -> Maybe FilePath
-> ProgramConfiguration -> IO (Compiler, Maybe Platform, ProgramConfiguration)
configure verbosity hcPath _hcPkgPath conf = do
(jhcProg, _, conf') <- requireProgramVersion verbosity
jhcProgram (orLaterVersion (Version [0,7,2] []))
(userMaybeSpecifyPath "jhc" hcPath conf)
let Just version = programVersion jhcProg
comp = Compiler {
compilerId = CompilerId JHC version,
compilerAbiTag = NoAbiTag,
compilerCompat = [],
compilerLanguages = jhcLanguages,
compilerExtensions = jhcLanguageExtensions,
compilerProperties = M.empty
}
compPlatform = Nothing
return (comp, compPlatform, conf')
jhcLanguages :: [(Language, Flag)]
jhcLanguages = [(Haskell98, "")]
-- | The flags for the supported extensions
jhcLanguageExtensions :: [(Extension, Flag)]
jhcLanguageExtensions =
[(EnableExtension TypeSynonymInstances , "")
,(DisableExtension TypeSynonymInstances , "")
,(EnableExtension ForeignFunctionInterface , "")
,(DisableExtension ForeignFunctionInterface , "")
,(EnableExtension ImplicitPrelude , "") -- Wrong
,(DisableExtension ImplicitPrelude , "--noprelude")
,(EnableExtension CPP , "-fcpp")
,(DisableExtension CPP , "-fno-cpp")
]
getInstalledPackages :: Verbosity -> PackageDBStack -> ProgramConfiguration
-> IO InstalledPackageIndex
getInstalledPackages verbosity _packageDBs conf = do
-- jhc --list-libraries lists all available libraries.
-- How shall I find out, whether they are global or local
-- without checking all files and locations?
str <- rawSystemProgramStdoutConf verbosity jhcProgram conf ["--list-libraries"]
let pCheck :: [(a, String)] -> [a]
pCheck rs = [ r | (r,s) <- rs, all isSpace s ]
let parseLine ln =
pCheck (readP_to_S
(skipSpaces >> string "Name:" >> skipSpaces >> parse) ln)
return $
PackageIndex.fromList $
map (\p -> emptyInstalledPackageInfo {
InstalledPackageInfo.installedPackageId =
InstalledPackageId (display p),
InstalledPackageInfo.sourcePackageId = p
}) $
concatMap parseLine $
lines str
-- -----------------------------------------------------------------------------
-- Building
-- | Building a package for JHC.
-- Currently C source files are not supported.
buildLib :: Verbosity -> PackageDescription -> LocalBuildInfo
-> Library -> ComponentLocalBuildInfo -> IO ()
buildLib verbosity pkg_descr lbi lib clbi = do
let Just jhcProg = lookupProgram jhcProgram (withPrograms lbi)
let libBi = libBuildInfo lib
let args = constructJHCCmdLine lbi libBi clbi (buildDir lbi) verbosity
let pkgid = display (packageId pkg_descr)
pfile = buildDir lbi </> "jhc-pkg.conf"
hlfile= buildDir lbi </> (pkgid ++ ".hl")
writeFileAtomic pfile . BS.Char8.pack $ jhcPkgConf pkg_descr
rawSystemProgram verbosity jhcProg $
["--build-hl="++pfile, "-o", hlfile] ++
args ++ map display (libModules lib)
-- | Building an executable for JHC.
-- Currently C source files are not supported.
buildExe :: Verbosity -> PackageDescription -> LocalBuildInfo
-> Executable -> ComponentLocalBuildInfo -> IO ()
buildExe verbosity _pkg_descr lbi exe clbi = do
let Just jhcProg = lookupProgram jhcProgram (withPrograms lbi)
let exeBi = buildInfo exe
let out = buildDir lbi </> exeName exe
let args = constructJHCCmdLine lbi exeBi clbi (buildDir lbi) verbosity
rawSystemProgram verbosity jhcProg (["-o",out] ++ args ++ [modulePath exe])
constructJHCCmdLine :: LocalBuildInfo -> BuildInfo -> ComponentLocalBuildInfo
-> FilePath -> Verbosity -> [String]
constructJHCCmdLine lbi bi clbi _odir verbosity =
(if verbosity >= deafening then ["-v"] else [])
++ hcOptions JHC bi
++ languageToFlags (compiler lbi) (defaultLanguage bi)
++ extensionsToFlags (compiler lbi) (usedExtensions bi)
++ ["--noauto","-i-"]
++ concat [["-i", l] | l <- nub (hsSourceDirs bi)]
++ ["-i", autogenModulesDir lbi]
++ ["-optc" ++ opt | opt <- PD.ccOptions bi]
-- It would be better if JHC would accept package names with versions,
-- but JHC-0.7.2 doesn't accept this.
-- Thus, we have to strip the version with 'pkgName'.
++ (concat [ ["-p", display (pkgName pkgid)]
| (_, pkgid) <- componentPackageDeps clbi ])
jhcPkgConf :: PackageDescription -> String
jhcPkgConf pd =
let sline name sel = name ++ ": "++sel pd
lib = fromMaybe (error "no library available") . library
comma = intercalate "," . map display
in unlines [sline "name" (display . pkgName . packageId)
,sline "version" (display . pkgVersion . packageId)
,sline "exposed-modules" (comma . PD.exposedModules . lib)
,sline "hidden-modules" (comma . otherModules . libBuildInfo . lib)
]
installLib :: Verbosity -> FilePath -> FilePath -> PackageDescription -> Library -> IO ()
installLib verb dest build_dir pkg_descr _ = do
let p = display (packageId pkg_descr)++".hl"
createDirectoryIfMissingVerbose verb True dest
installOrdinaryFile verb (build_dir </> p) (dest </> p)
installExe :: Verbosity -> FilePath -> FilePath -> (FilePath,FilePath) -> PackageDescription -> Executable -> IO ()
installExe verb dest build_dir (progprefix,progsuffix) _ exe = do
let exe_name = exeName exe
src = exe_name </> exeExtension
out = (progprefix ++ exe_name ++ progsuffix) </> exeExtension
createDirectoryIfMissingVerbose verb True dest
installExecutableFile verb (build_dir </> src) (dest </> out)
|
DavidAlphaFox/ghc
|
libraries/Cabal/Cabal/Distribution/Simple/JHC.hs
|
bsd-3-clause
| 8,608 | 0 | 17 | 2,006 | 2,059 | 1,135 | 924 | 147 | 2 |
module Main where
import CommandLine
import Control.Monad
import Data.Char
import Expense
import Parser
import PetParser
import System.Environment
import System.Exit
import System.IO
main :: IO ()
main = do opts <- getArgs >>= parseCmdLine
logF opts LogInfo "Parsed command-line arguments"
contents <- input opts
logF opts LogInfo "Read file contents"
exps <- execParser opts contents
_ <- execIOCmds exps $ cmds opts
return ()
where execIOCmds = foldM (\a f -> f a)
execParser :: Options -> String -> IO [Expense]
execParser opts cts =
case runParser parseManyExpenses cts (1, 1) updatePos of
Left (m, (l, c)) ->
let msg = failedParse "Parse error" l c (Just m) cts
in hPutStr stderr msg >> exitFailure
Right (e, r, (l, c), _) ->
if not $ null r
then let msg = failedParse "Incomplete parse" l c Nothing cts
in hPutStr stderr msg >> exitFailure
else logF opts LogInfo (successfulParse $ length e) >> return e
where successfulParse l = "Successful parse: " ++ show l ++ " expenses"
failedParse :: String -> Int -> Int -> Maybe [String] -> String -> String
failedParse t l c m i =
unlines $ [concat [t, " at line ", show l, ", column ", show c]]
++ maybe [] (map (" >> " ++)) m
++ maybe [] (const [""]) line
++ maybe [] (\x -> [" " ++ dropWhile isSpace x]) line
++ maybe [] (const ["--" ++ replicate (c - 1) '-' ++ "^"]) line
where line = let ls = lines i in if length ls <= l - 1 then Nothing
else Just $ ls !! (l - 1)
|
fredmorcos/attic
|
projects/pet/archive/pet_haskell_simpleparse_2/Main.hs
|
isc
| 1,615 | 0 | 14 | 466 | 634 | 321 | 313 | 40 | 3 |
{-# LANGUAGE OverloadedStrings #-}
import Github.Issues
import Data.Either
import Data.Maybe
import Data.Time.Clock
import Data.Time.Calendar (addDays)
import Data.Aeson
import Data.Monoid
import Data.Configurator
import qualified Data.Configurator.Types as DCTypes (Value)
import Web.Scotty
import Network.HTTP.Types.Status
import Data.List (intersect)
import Data.IORef
import Control.Monad.IO.Class (liftIO)
import Control.Concurrent
data CrossThreadData = CrossThreadData {
issues :: Either [(String, Error)] [Issue],
prs :: Either [(String, Error)] [Issue],
recentlyClosedIssues :: Either [(String, Error)] [Issue],
recentlyClosedCount :: Int,
recentlyOpenedCount :: Int
}
data TruncatedIssue = TruncatedIssue {
whenOpened :: UTCTime,
whenClosed :: Maybe UTCTime,
priority :: String,
issueURL :: Maybe String,
title :: String,
createdBy :: String,
ownedBy :: String
} deriving Show
instance ToJSON TruncatedIssue where
toJSON (TruncatedIssue whenOpened whenClosed priority issueURL title createdBy ownedBy) = object ["description" .= title,
"when_opened" .= whenOpened,
"when_closed" .= whenClosed,
"url" .= issueURL,
"raiser" .= createdBy,
"owner" .= ownedBy,
"priority" .= priority
]
getFortnightAgo :: IO UTCTime
getFortnightAgo = do
now <- getCurrentTime
return $ UTCTime (addDays (-14) (utctDay now)) (utctDayTime now)
convertJSON
:: Either a [Issue]
-> Either a Value
convertJSON (Left errs) = Left errs
convertJSON (Right issues) = Right (toJSON (map summariseIssue issues))
summariseIssue :: Issue -> TruncatedIssue
summariseIssue issue =
TruncatedIssue (fromGithubDate $ issueCreatedAt issue)
(fmap fromGithubDate $ issueClosedAt issue)
(priorityFromLabels (map labelName $ issueLabels issue))
(issueHtmlUrl issue)
(issueTitle issue)
(githubOwnerLogin $ issueUser issue)
(fromMaybe "nobody" $ fmap githubOwnerLogin $ issueAssignee issue)
doToLeft :: (a -> c) -> (Either a b) -> (Either c b)
doToLeft fn (Left a) = Left (fn a)
doToLeft _ (Right a) = Right a
getOpenIssues :: Maybe GithubAuth -> [IssueLimitation] -> String -> String -> IO (Either (String, Error) [Issue])
getOpenIssues auth limitations user name = fmap (doToLeft (\x -> (name, x))) (issuesForRepo' auth user name limitations)
onlyPRs :: Either a [Issue] -> Either a [Issue]
onlyPRs (Right issues) = Right (filter isPullRequest issues)
onlyPRs (Left errs) = Left errs
notPRs :: Either a [Issue] -> Either a [Issue]
notPRs (Right issues) = Right (filter (not . isPullRequest) issues)
notPRs (Left errs) = Left errs
multiGetIssues :: String -> [String] -> Maybe GithubAuth -> [IssueLimitation] -> IO (Either [(String, Error)] [Issue])
multiGetIssues user names auth limitations = fmap issuesTransform $ sequence $ map (getOpenIssues auth limitations user) names
issuesTransform :: [Either a [b]] -> Either [a] [b]
issuesTransform input =
if null $ lefts input then
Right (concat $ rights input)
else
Left (lefts input)
overlap list1 list2 = not $ null (intersect list1 list2)
priorityFromLabels_base highPriorityLabels mediumPriorityLabels lowPriorityLabels labels =
if (overlap labels highPriorityLabels) then "1 - high" else
if (overlap labels mediumPriorityLabels) then "2 - medium" else
if (overlap labels lowPriorityLabels) then "4 - low" else
"3 - unknown"
priorityFromLabels = priorityFromLabels_base ["high-priority", "priority:high"] ["medium-priority", "priority:medium"] ["low-priority", "priority:low"]
isPullRequest :: Issue -> Bool
isPullRequest issue = isJust $ issuePullRequest issue
scottyPRs :: Either [(String, Error)] [Issue] -> Int -> Int -> ActionM ()
scottyPRs (Left a) _ _ = do
status status503
Web.Scotty.json $ object ["errors" .= (show a)]
scottyPRs (Right a) ro rc = do
setHeader "Access-Control-Allow-Methods" "POST, GET, OPTIONS"
setHeader "Access-Control-Allow-Headers" "X-PINGOTHER"
setHeader "Access-Control-Max-Age" "1728000"
setHeader "Access-Control-Allow-Origin" "*"
Web.Scotty.json $ object ["issues" .= (map summariseIssue a),
"recentlyOpened" .= toJSON ro,
"recentlyClosed" .= toJSON rc
]
openedSince :: UTCTime -> Issue -> Bool
openedSince when issue = (fromGithubDate (issueCreatedAt issue)) > when
closedSince :: UTCTime -> Issue -> Bool
closedSince when issue = case (issueClosedAt issue) of
Nothing -> False
Just date -> (fromGithubDate date) > when
updateIssues:: String -> [String] -> Maybe GithubAuth -> IORef (CrossThreadData) -> IO ()
updateIssues repoOwner repoNames auth resultRef = do
putStrLn "Updating issues from Github"
fortnightAgo <- getFortnightAgo
everything <- multiGetIssues repoOwner repoNames auth [Open]
closedIssues <- fmap notPRs $ multiGetIssues repoOwner repoNames auth [OnlyClosed, (Since fortnightAgo)]
let openPRs = onlyPRs everything
let openIssues = notPRs everything
let openIssueCount = (either length (length . filter (openedSince fortnightAgo)) openIssues) + (either length (length . filter (openedSince fortnightAgo)) closedIssues)
let recentlyClosedIssues = either Left (Right . (filter (closedSince fortnightAgo))) closedIssues
let closedIssueCount = either length length recentlyClosedIssues
writeIORef resultRef (CrossThreadData openIssues openPRs recentlyClosedIssues closedIssueCount openIssueCount)
putStrLn "Updated issues from Github"
updateIssuesLoop :: String -> [String] -> Maybe GithubAuth -> IORef (CrossThreadData) -> IO ()
updateIssuesLoop repoOwner repoNames auth resultRef = do
updateIssues repoOwner repoNames auth resultRef
threadDelay (1000 * 1000 * 60 * 30)
updateIssuesLoop repoOwner repoNames auth resultRef
main =
do
cfg <- load [Required "./githubissues.cfg"]
lst <- require cfg "repoNames"
user <- require cfg "repoOwner"
oauthToken <- Data.Configurator.lookup cfg "oauthToken"
let oauth = fmap GithubOAuth oauthToken
ctd <- newIORef $ CrossThreadData (Right []) (Right []) (Right []) (-1) (-1)
forkIO $ updateIssuesLoop user lst oauth ctd
scotty 3005 $ do
get "/prs" $ do
openPRs <- liftIO $ fmap prs $ readIORef ctd
scottyPRs openPRs (-1) (-1)
get "/issues" $ do
openIssues <- liftIO $ fmap issues $ readIORef ctd
ro <- liftIO $ fmap recentlyOpenedCount $ readIORef ctd
rc <- liftIO $ fmap recentlyClosedCount $ readIORef ctd
scottyPRs openIssues ro rc
get "/recentlyClosed" $ do
issues <- liftIO $ fmap recentlyClosedIssues $ readIORef ctd
scottyPRs issues 0 0
get "/dashboard" $ file "./dashboard.html"
get "/dashboard.js" $ file "./dashboard.js"
|
rkday/github-dashboard
|
github-dashboard.hs
|
mit
| 7,983 | 0 | 17 | 2,492 | 2,240 | 1,126 | 1,114 | 143 | 4 |
{-|
Module : Utils.Tuple
Description : Utilities for working with tuples
Copyright : (c) Tessa Belder 2015-2016
This module contains useful functions for working with tuples.
-}
module Utils.Tuple (
unzipConcat,
mapFst, mapSnd,
tmap, tmap2,
swap,
fst3, snd3, thrd3,
fst4, snd4, thrd4, frth4
) where
import qualified Data.Graph.Inductive.Query.Monad as T (mapFst, mapSnd)
-- | Unzip a list of tuples of lists, and concatenate the resulting lists of lists
unzipConcat :: [([a], [b])] -> ([a], [b])
unzipConcat = mapFst concat . mapSnd concat . unzip
-- | Map a function to the first element in a tuple
mapFst :: (a -> a') -> (a, b) -> (a', b)
mapFst = T.mapFst
-- | Map a function to the first element in a tuple
mapSnd :: (b -> b') -> (a, b) -> (a, b')
mapSnd = T.mapSnd
-- | Map a function to both elements in a tuple
tmap :: (a -> b) -> (a, a) -> (b, b)
tmap f = mapFst f . mapSnd f
-- | Map functions to both elements in a tuple
tmap2 :: (a -> a') -> (b -> b') -> (a, b) -> (a', b')
tmap2 f g = mapFst f . mapSnd g
-- | Swap the elements of a tuple
swap :: (a, b) -> (b, a)
swap (a, b) = (b, a)
-- | Obtain the first element of a 3-tuple
fst3 :: (a, b, c) -> a
fst3 (x, _, _) = x
-- | Obtain the second element of 3-tuple
snd3 :: (a, b, c) -> b
snd3 (_, x, _) = x
-- | Obtain the third element of a 3-tuple
thrd3 :: (a, b, c) -> c
thrd3 (_, _, x) = x
-- | Obtain the first element of a 4-tuple
fst4 :: (a, b, c, d) -> a
fst4 (x, _, _, _) = x
-- | Obtain the second element of a 4-tuple
snd4 :: (a, b, c, d) -> b
snd4 (_, x, _, _) = x
-- | Obtain the third element of a 4-tuple
thrd4 :: (a, b, c, d) -> c
thrd4 (_, _, x, _) = x
-- | Obtain the fourth element of a 4-tuple
frth4 :: (a, b, c, d) -> d
frth4 (_, _, _, x) = x
|
julienschmaltz/madl
|
src/Utils/Tuple.hs
|
mit
| 1,805 | 0 | 8 | 464 | 636 | 386 | 250 | 34 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Control.AFSM.CoreType
-- Copyright : (c) Hanzhong Xu, Meng Meng 2016,
-- License : MIT License
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
-----------------------------------------------------------------------------
-- {-# LANGUAGE ExistentialQuantification #-}
module Control.AFSM.CoreType where
-- | 'TF' is a type representing a transition function.
-- s: storage, a: input, b: output
-- Let's explain more about 'TF'. When a state gets an input a,
-- it should do three things base on the storage and input:
-- find the next state, update storage and output b.
-- That's why it looks like this:
-- (storage -> a -> (SM newState newStorage, b))
-- type TF storage input output = (storage -> input -> (SM storage input output, output))
-- Also, it is an instance of Arrow, it represents a machine without initial storage.
-- composing two TF represents that two SM shares the same storage
newtype TF s a b = TF (s -> a -> (SM s a b, b))
-- | STF is the type of simple transition function.
-- type STF s a b = (s -> a -> (s, b))
-- | 'SM' is a type representing a state machine.
-- (TF s a b): initial state(transition function), s: initial storage
-- SM storage input output = SM (TF storage input output) storage
data SM s a b = SM (TF s a b) s
tf :: SM s a b -> (s -> a -> (SM s a b, b))
{-# INLINE tf #-}
tf (SM (TF f) _) = f
st :: SM s a b -> s
{-# INLINE st #-}
st (SM _ s) = s
-- Constructors
-- | It is the same with the SM constructor.
newSM :: (s -> a -> (SM s a b, b)) -> s -> SM s a b
{-# INLINE newSM #-}
newSM tf s = SM (TF tf) s
-- | build a simple SM which have only one TF.
simpleSM :: (s -> a -> (s, b)) -> s -> SM s a b
{-# INLINE simpleSM #-}
simpleSM f s = newSM f' s
where
f' s' a' = (newSM f' s'', b)
where
(s'', b) = f s' a'
{-
-- | build a SM which can choose STF based on the input
simplChcSM :: (s -> a -> STF s a b) -> s -> SM s a b
simplChcSM cf s = simpleSM f s
where
f s a = (s', b)
where
(s', b) = (cf s a) s a
-}
instance (Show s) => Show (SM s a b) where
show (SM f s) = show s
-- | 'SMH' is the type of the state machine with hidden or no storage.
-- It is the same type with
-- Circuit a b = Circuit (a -> Circuit a b, b)
type SMH a b = SM () a b
-- | 'Event' type, there are 4 different events: event a, no event, error event string and exit event.
data Event a
= Event a
| NoEvent
| ErrEvent String
| ExitEvent
deriving (Show, Eq, Ord)
|
PseudoPower/AFSM
|
src/Control/AFSM/CoreType.hs
|
mit
| 2,652 | 0 | 10 | 662 | 456 | 262 | 194 | 26 | 1 |
{-# htermination max :: Int -> Int -> Int #-}
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/Prelude_max_5.hs
|
mit
| 46 | 0 | 2 | 10 | 3 | 2 | 1 | 1 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module OptionsSpec(spec) where
import Control.Lens
import System.NotifySend
import Test.Hspec
import Test.QuickCheck
import Data.Text
spec :: Spec
spec = do
describe "Command line options to notify-send" $ do
it "should encode correctly" $ do
property $ \x -> (commandOptions x) `shouldBe` ["-u", (Data.Text.toLower . pack. show) $ x ^. urgency, "-t", (pack . show) $ max 0 (x ^. expireTime), "-i", pack $ x ^. icon]
it "should default correctly" $ do
(commandOptions defaultNotification) `shouldBe` ["-u", "low", "-t", "1000", "-i", " "]
|
bobjflong/notify-send
|
test/OptionsSpec.hs
|
mit
| 640 | 0 | 22 | 151 | 203 | 113 | 90 | 14 | 1 |
import Data.List (intersect)
import GHC.Exts (sortWith)
type Value = Int
type Board = [Value]
type Col = Int
type Row = Int
type Index = Int
type Block = Int
easy, hard, evil :: String
easy = "530070000600195000098000060800060003400803001700020006060000280000419005000080079"
hard = "000003020200019000001008097600000070709601804030000006360800700000950003080100000"
evil = "502000008000800030000407060700010600040206090006040001050701000080002000900000806"
colValues :: Col -> Board -> [Value]
colValues _ [] = []
colValues col board =
board !! col : colValues col (drop 9 board)
rowValues :: Row -> Board -> [Value]
rowValues row board =
take 9 $ drop (row * 9) board
blockValues :: Block -> Board -> [Value]
blockValues block board =
let cells = [0, 1, 2, 9, 10, 11, 18, 19, 20]
offset = block `quot` 3 * 27 + (block `mod` 3 * 3)
offsetCells = map (+offset) cells
in map (board !!) offsetCells
blockNum :: Col -> Row -> Block
blockNum col row =
let x = col `quot` 3
y = row `quot` 3
in y * 3 + x
freeByCol :: Col -> Board -> [Value]
freeByCol col board =
let vs = colValues col board
in filter (`notElem` vs) [1..9]
freeByRow :: Row -> Board -> [Value]
freeByRow row board =
let vs = rowValues row board
in filter (`notElem` vs) [1..9]
freeByBlock :: Block -> Board -> [Value]
freeByBlock block board =
let vs = blockValues block board
in filter (`notElem` vs) [1..9]
freeByIndex :: Index -> Board -> [Value]
freeByIndex i board =
let col = i `mod` 9
row = i `quot` 9
block = blockNum col row
colFree = freeByCol col board
rowFree = freeByRow row board
blockFree = freeByBlock block board
in intersect colFree $ intersect rowFree blockFree
moveList :: Board -> [(Index, [Value])]
moveList board =
let freeIndexes = map fst $ filter ((==0) . snd) $ zip [0..] board
movesAt i = (i, freeByIndex i board)
moves = map movesAt freeIndexes
in sortWith (length . snd) moves
applyMove :: Index -> Value -> Board -> Board
applyMove i value board =
take i board ++ [value] ++ drop (i + 1) board
solveWith :: [(Index, [Value])] -> Board -> [Board]
solveWith [] board = [board]
solveWith ((_, []):_) _ = []
solveWith ((i, [v]):_) board =
let board' = applyMove i v board
moves = moveList board'
in solveWith moves board'
solveWith ((i, v:vs):_) board =
solveWith [(i, [v])] board ++ solveWith [(i, vs)] board
solve :: Board -> [Board]
solve board = solveWith (moveList board) board
boardStr :: Board -> String
boardStr [] = []
boardStr board =
boardStr' 0 board
where boardStr' _ [] = "|\n+---+---+---+"
boardStr' i (v:vs) =
decorationAt i ++ valueStr v ++ boardStr' (i + 1) vs
valueStr 0 = " "
valueStr v = show v
decorationAt :: Index -> String
decorationAt n
| n == 0 = "+---+---+---+\n|"
| n `mod` 27 == 0 = "|\n+---+---+---+\n|"
| n `mod` 9 == 0 = "|\n|"
| n `mod` 3 == 0 = "|"
| otherwise = ""
printBoard :: Board -> IO ()
printBoard board =
putStrLn $ boardStr board
readBoard :: String -> Board
readBoard = map (\c -> read [c])
doSolve :: String -> IO ()
doSolve s = do
let board = readBoard s
putStrLn "Initial:"
printBoard board
putStrLn "Solutions:"
mapM_ printBoard $ solve board
putStrLn ""
main :: IO ()
main = do
doSolve easy
doSolve hard
doSolve evil
|
derkyjadex/sudoku-solver
|
Main.hs
|
mit
| 3,651 | 0 | 14 | 1,055 | 1,406 | 741 | 665 | 105 | 3 |
--The MIT License (MIT)
--
--Copyright (c) 2017 Steffen Michels ([email protected])
--
--Permission is hereby granted, free of charge, to any person obtaining a copy of
--this software and associated documentation files (the "Software"), to deal in
--the Software without restriction, including without limitation the rights to use,
--copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
--Software, and to permit persons to whom the Software is furnished to do so,
--subject to the following conditions:
--
--The above copyright notice and this permission notice shall be included in all
--copies or substantial portions of the Software.
--
--THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
--IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
--FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
--COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
--IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
--CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
module AstPreprocessor
( substitutePfsWithPfArgs
) where
import AST (AST)
import qualified AST
import IdNrMap (IdNrMap)
import qualified IdNrMap
import Data.HashMap (Map)
import qualified Data.HashMap as Map
import Data.HashSet (Set)
import qualified Data.HashSet as Set
import Data.Text (Text)
import TextShow
import Data.Monoid ((<>))
import qualified Data.List as List
import Data.Traversable (mapAccumR)
import Data.Foldable (foldl')
substitutePfsWithPfArgs :: AST -> IdNrMap Text -> (AST, IdNrMap Text)
substitutePfsWithPfArgs ast identIds = (ast', identIds')
where
(ast', identIds') = Map.foldWithKey addUsagePreds (ast2, identIds2) pfsWithPfArgsUsages
where
-- add predicates for each usage of predicates, of which at least one arg is a PF in at least one usage
addUsagePreds :: (AST.PFuncLabel, Int) -> Map [AST.Expr] AST.PredicateLabel -> (AST, IdNrMap Text) -> (AST, IdNrMap Text)
addUsagePreds (_, nArgs) uses ast'' = res
where
(res, _, _, _) = Map.foldWithKey addUsagePreds' (ast'', 0, [], []) uses
addUsagePreds' :: [AST.Expr]
-> AST.PredicateLabel
-> ((AST, IdNrMap Text), Int, [(AST.PredicateLabel, [AST.Expr])], [[(AST.Expr, AST.Expr)]])
-> ((AST, IdNrMap Text), Int, [(AST.PredicateLabel, [AST.Expr])], [[(AST.Expr, AST.Expr)]])
addUsagePreds' args usagePred ((ast''', identIds''), n, prevUsages, conditions) = ((ast'''', identIds'''), succ n, prevUsages', conditions')
where
ast'''' = ast'''
{ AST.rules =
foldl'
(\x (head', bodies'') -> Map.insert (head', 0) (([],) <$> bodies'') x)
(Map.insert (usagePred, nArgs) bodies' $ AST.rules ast''')
auxRules
}
(bodies', auxRules, identIds''') = bodies prevUsages ([], []) identIds''
conditions' = conditions
prevUsages' = (usagePred, args) : prevUsages
bodies :: [(AST.PredicateLabel, [AST.Expr])]
-> ([([AST.HeadArgument], AST.RuleBody)], [(AST.PredicateLabel, [AST.RuleBody])])
-> IdNrMap Text
-> ([([AST.HeadArgument], AST.RuleBody)], [(AST.PredicateLabel, [AST.RuleBody])], IdNrMap Text)
-- handle cases that usage actually equals one of previous usage
bodies ((prevUsagePred, prevUsageArgs) : prevUsages'') (accBodies, accAuxRules) identIds'''' =
bodies prevUsages'' (body : accBodies, unequalAuxRule : accAuxRules) identIds'''''
where
body = (usagePredArgsHead, AST.RuleBody (AST.UserPredicate prevUsagePred usagePredArgs : equalToPrev))
usagePredArgsHead = [AST.ArgVariable $ AST.TempVar $ -x | x <- [1..nArgs]]
usagePredArgs = [AST.Variable $ AST.TempVar $ -x | x <- [1..nArgs]]
equalToPrev = [ AST.BuildInPredicate $ AST.Equality True arg argPrev
| arg <- args | argPrev <- prevUsageArgs
]
-- add aux rule, which is negation of 'equalToPrev', used to restrict last body to cases no rules matches
unequalAuxRule = ( unequalAuxRuleHead
, [ AST.RuleBody [AST.BuildInPredicate $ AST.Equality False arg argPrev]
| arg <- args | argPrev <- prevUsageArgs
]
)
unequalAuxRuleHead = AST.PredicateLabel unequalAuxRuleLabel
(unequalAuxRuleLabel, identIds''''') = IdNrMap.getIdNr usagePredAuxLabel identIds''''
where
AST.PredicateLabel pfId = usagePred
usagePredAuxLabel = toText $ fromText (Map.findWithDefault undefined pfId (IdNrMap.fromIdNrMap identIds'')) <>
"_" <> showb (length accBodies)
-- add last case: no previous usage equals current one
bodies [] (accBodies, accAuxRules) identIds'''' =
( ([AST.ArgVariable $ AST.TempVar $ -x | x <- [1..nArgs]], AST.RuleBody body) : accBodies
, accAuxRules
, identIds''''
)
where
body = argValueEqs ++ uneqPrevious
argValueEqs = [ AST.BuildInPredicate $ AST.Equality True (AST.Variable $ AST.TempVar $ -v) (pfs2placeh arg)
| v <- [1..nArgs] | arg <- args
]
uneqPrevious = [AST.UserPredicate label [] | (label, _) <- accAuxRules]
pfs2placeh (AST.PFunc (AST.PFuncLabel pf) []) = AST.ConstantExpr $
AST.Placeholder (Map.findWithDefault undefined pf (IdNrMap.fromIdNrMap identIds''))
pfs2placeh arg = arg
-- predicates for which pfsWithPfArgs are used -> all usages with generated predicate label to compute arguments of that usage
pfsWithPfArgsUsages :: Map (AST.PFuncLabel, Int) (Map [AST.Expr] AST.PredicateLabel)
pfsWithPfArgsUsages = pfsWithPfArgsUsages'
((pfsWithPfArgsUsages', identIds2, _), ast2) = mapAccumAddRuleElemsPfs pfsWithPfArgsUsages'' (Map.empty, identIds, 1) ast
where
pfsWithPfArgsUsages'' :: (Map (AST.PFuncLabel, Int) (Map [AST.Expr] AST.PredicateLabel), IdNrMap Text, Int)
-> ((AST.PFuncLabel, Int), [AST.Expr])
-> ([AST.Expr], (Map (AST.PFuncLabel, Int) (Map [AST.Expr] AST.PredicateLabel), IdNrMap Text, Int), [AST.RuleBodyElement])
pfsWithPfArgsUsages'' st@(pfUses, identIds'', tmpVarCounter) (sign@(AST.PFuncLabel pfId, _), args)
| Set.member sign pfsWithPfArgs =
let usesArgs = Map.findWithDefault Map.empty sign pfUses
in case Map.lookup args usesArgs of
Just prd -> (argsWithSubstPfs, (pfUses, identIds'', tmpVarCounter'), [AST.UserPredicate prd argsWithSubstPfs])
Nothing ->
let (prdId, identIds''') = IdNrMap.getIdNr (predIdent $ Map.size usesArgs) identIds''
prdLabel = AST.PredicateLabel prdId
in ( argsWithSubstPfs
, (Map.insert sign (Map.insert args prdLabel usesArgs) pfUses, identIds''', tmpVarCounter')
, [AST.UserPredicate prdLabel argsWithSubstPfs]
)
| otherwise = (args, st, [])
where
-- substitute all Pfs used as args with fresh variables
(tmpVarCounter', argsWithSubstPfs) = mapAccumR substPfs tmpVarCounter args
where
substPfs counter (AST.PFunc _ _) = (succ counter, AST.Variable $ AST.TempVar $ -counter)
substPfs counter a = (counter, a)
predIdent n = toText $
"~" <>
fromText (Map.findWithDefault undefined pfId (IdNrMap.fromIdNrMap identIds)) <>
"@" <>
showb n
-- all pfs which have pfs as args
pfsWithPfArgs :: Set (AST.PFuncLabel, Int)
pfsWithPfArgs = fst $ mapAccumAddRuleElemsPfs pfsWithPfArgs' Set.empty ast
where
pfsWithPfArgs' :: Set (AST.PFuncLabel, Int)
-> ((AST.PFuncLabel, Int), [AST.Expr])
-> ([AST.Expr], Set (AST.PFuncLabel, Int), [a])
pfsWithPfArgs' pfs (sign, args)
| any (AST.foldExpr (\b e -> b || AST.exprIsPFunc e) False) args = (args, Set.insert sign pfs, [])
| otherwise = (args, pfs, [])
mapAccumAddRuleElemsPfs :: (a -> ((AST.PFuncLabel, Int), [AST.Expr]) -> ([AST.Expr], a, [AST.RuleBodyElement])) -> a -> AST -> (a, AST)
mapAccumAddRuleElemsPfs f acc ast = (acc', ast{AST.rules = rules})
where
(acc', rules) = Map.mapAccumWithKey
(\acc'' _ -> List.mapAccumL mapAccumAddRuleElemsPfs' acc'')
acc
(AST.rules ast)
mapAccumAddRuleElemsPfs' acc'' (args, AST.RuleBody body) = (acc''', (args, AST.RuleBody $ concat body'))
where
(acc''', body') = List.mapAccumL mapAccumAddRuleElemsPfs'' acc'' body
mapAccumAddRuleElemsPfs'' acc'' el@(AST.UserPredicate _ _) = (acc'', [el])
mapAccumAddRuleElemsPfs'' acc'' (AST.BuildInPredicate bip) = case bip of
AST.Equality op exprX exprY -> mapAccumAddRuleElemsPfs''' (AST.Equality op) exprX exprY
AST.Ineq op exprX exprY -> mapAccumAddRuleElemsPfs''' (AST.Ineq op) exprX exprY
where
mapAccumAddRuleElemsPfs''' constr exprX exprY = (acc'''', AST.BuildInPredicate (constr exprX' exprY') : toAdd)
where
(acc''', exprX') = AST.mapAccExpr mapAccumAddRuleElemsPfs'''' (acc'', []) exprX
((acc'''', toAdd), exprY') = AST.mapAccExpr mapAccumAddRuleElemsPfs'''' acc''' exprY
mapAccumAddRuleElemsPfs'''' (acc'', toAdd) (AST.PFunc label args) = ((acc''', toAdd ++ toAdd'), AST.PFunc label args')
where
(args', acc''', toAdd') = f acc'' ((label, length args), args)
mapAccumAddRuleElemsPfs'''' acc'' expr = (acc'', expr)
|
SteffenMichels/IHPMC
|
src/AstPreprocessor.hs
|
mit
| 10,833 | 3 | 25 | 3,453 | 2,684 | 1,495 | 1,189 | -1 | -1 |
module GeneratorSpec where
import TestImport
import qualified Data.Map as M
import Data.List.NonEmpty (NonEmpty(..))
type UserId = Int
type NonEmptyUserId = NonEmpty UserId
resources :: [ResourceTree String]
resources = [parseRoutes|
/api ApiP:
/users/#UserId UsersR GET
/users/#Int/foo UsersFooR GET
/users/#NonEmptyUserId/bar UsersBarR GET
/users/#Other/baz UsersBazR GET
|]
spec :: Spec
spec = do
describe "genFlowClasses" $ do
it "should generate classes" $ do
let classes = genFlowClasses M.empty [] [] resources
map className classes
`shouldBe`
[ "PATHS_TYPE_paths"
, "PATHS_TYPE_paths_static_pages"
, "PATHS_TYPE_paths_api"
]
it "should identify path variable types" $ do
let
classes = genFlowClasses M.empty [] [] resources
apiClass = find ((== "PATHS_TYPE_paths_api") . className) classes
map classMembers apiClass
`shouldBe`
Just
[ Method
"users"
[ Path "api"
, Path "users"
, Dyn NumberT
]
, Method
"users_bar"
[ Path "api"
, Path "users"
, Dyn (NonEmptyT NumberT)
, Path "bar"
]
, Method
"users_baz"
[ Path "api"
, Path "users"
, Dyn StringT
, Path "baz"
]
, Method
"users_foo"
[ Path "api"
, Path "users"
, Dyn NumberT
, Path "foo"
]
]
it "should respect overrides " $ do
let
classes = genFlowClasses (M.fromList [("UserId", StringT)]) [] [] resources
apiClass = find ((== "PATHS_TYPE_paths_api") . className) classes
map classMembers apiClass
`shouldBe`
Just
[ Method
"users"
[ Path "api"
, Path "users"
, Dyn StringT
]
, Method
"users_bar"
[ Path "api"
, Path "users"
, Dyn (NonEmptyT StringT)
, Path "bar"
]
, Method
"users_baz"
[ Path "api"
, Path "users"
, Dyn StringT
, Path "baz"
]
, Method
"users_foo"
[ Path "api"
, Path "users"
, Dyn NumberT
, Path "foo"
]
]
describe "classesToFlow" $ do
it "should generate formal parameters for each path variable" $ do
let
cls =
[ Class
"x"
[ Method
"y"
[ Path "x"
, Dyn StringT
, Path "y"
, Dyn NumberT
, Path "z"
, Dyn StringT
]
]
]
normalizeText (classesToFlow cls)
`shouldBe`
normalizeText [st|
class x {
y(a: string, aa: number, aaa: string): string { return this.root + '/x/' + a + '/y/' + aa.toString() + '/z/' + aaa + ''; }
root: string;
constructor(root: string) {
this.root = root;
}
}
|]
it "should avoid name shadowing in nested binders" $ do
let
cls =
[ Class
"x"
[ Method
"y"
[ Path "x"
, Dyn (NonEmptyT (NonEmptyT NumberT))
, Path "y"
]
]
]
normalizeText (classesToFlow cls)
`shouldBe`
normalizeText [st|
class x {
y(a: Array<Array<number>>): string { return this.root + '/x/' + a.map(function(a1) { return a1.map(function(a2) { return a2.toString() }).join(',') }).join(',') + '/y'; }
root: string;
constructor(root: string) {
this.root = root;
}
}
|]
describe "genFlowSource" $
it "should work end-to-end" $ do
let source = genFlowSource M.empty [] [] "'test'" resources
normalizeText source
`shouldBe`
normalizeText [st|
/* @flow */
class PATHS_TYPE_paths {
api : PATHS_TYPE_paths_api;
static_pages : PATHS_TYPE_paths_static_pages;
root: string;
constructor(root: string) {
this.root = root;
this.api = new PATHS_TYPE_paths_api(root);
this.static_pages = new PATHS_TYPE_paths_static_pages(root);
}
}
class PATHS_TYPE_paths_static_pages {
root: string;
constructor(root: string) {
this.root = root;
}
}
class PATHS_TYPE_paths_api {
users(a: number): string { return this.root + '/api/users/' + a.toString() + ''; }
users_bar(a: Array<number>): string { return this.root + '/api/users/' + a.map(function(a1) { return a1.toString() }).join(',') + '/bar'; }
users_baz(a: string): string { return this.root + '/api/users/' + a + '/baz'; }
users_foo(a: number): string { return this.root + '/api/users/' + a.toString() + '/foo'; }
root: string;
constructor(root: string) {
this.root = root;
}
}
var PATHS: PATHS_TYPE_paths = new PATHS_TYPE_paths('test');
|]
|
frontrowed/yesod-routes-flow
|
test/GeneratorSpec.hs
|
mit
| 5,708 | 0 | 25 | 2,548 | 815 | 415 | 400 | -1 | -1 |
module System.Logging.Facade.Types where
data LogLevel = TRACE | DEBUG | INFO | WARN | ERROR
deriving (Eq, Show, Ord, Bounded, Enum)
data Location = Location {
locationPackage :: String
, locationModule :: String
, locationFile :: String
, locationLine :: Int
, locationColumn :: Int
} deriving (Eq, Show)
data LogRecord = LogRecord {
logRecordLevel :: LogLevel
, logRecordLocation :: Maybe Location
, logRecordMessage :: String
} deriving (Eq, Show)
|
beni55/logging-facade
|
src/System/Logging/Facade/Types.hs
|
mit
| 460 | 0 | 9 | 79 | 141 | 85 | 56 | 15 | 0 |
{-|
Module : TestPrint.Problen.BSP.CNF
Description : The CNF type Printer tests
Copyright : (c) Andrew Burnett 2014-2015
Maintainer : [email protected]
Stability : experimental
Portability : Unknown
The Test Tree Node for the CNF type's Printer Tests
-}
module TestPrint.Problem.BSP.CNF (
printer, -- TestTree
cnfList -- :: [CNF]
) where
import HSat.Problem.BSP.CNF
import HSat.Problem.BSP.Common
import TestPrint
import qualified TestPrint.Problem.BSP.CNF.Builder as CNFBuilder
name :: String
name = "CNF"
printer :: TestTree
printer =
testGroup name [
printList "CNF" cnfList,
CNFBuilder.printer
]
cnfList :: [CNF]
cnfList = map (mkCNFFromClauses . mkClausesFromIntegers) [
[],
[[-1,-2,-3],[],[1,2,3]],
[
[-53,-345,234,237],
[-24,24,675,1346],
[2467,860,-1,2]
]
]
|
aburnett88/HSat
|
tests-src/TestPrint/Problem/BSP/CNF.hs
|
mit
| 867 | 0 | 9 | 192 | 209 | 133 | 76 | 22 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Web.Twitter.PleaseCaption.Status ( getExtendedEntities
, hasPhotoEntities
, hasAltText
, asText
) where
import Data.Maybe (fromMaybe, isJust)
import qualified Data.Text as Text
import Web.Twitter.Types (Status(..), ExtendedEntities(..),
ExtendedEntity(..), Entity(..), User(..))
getExtendedEntities :: Status -> [ExtendedEntity]
getExtendedEntities status =
fromMaybe [] $ map entityBody . exeMedia <$> statusExtendedEntities status
hasPhotoEntities :: Status -> Bool
hasPhotoEntities status =
let entities = getExtendedEntities status in
(not $ null entities) && all (=="photo") (map exeType entities)
hasAltText :: Status -> Bool
hasAltText status =
let entities = getExtendedEntities status in
all (isJust . exeExtAltText) entities
asText :: Status -> Text.Text
asText Status { statusText = text,
statusUser = User { userScreenName = screenName }} =
Text.concat [ "@", screenName, ":", text ]
|
stillinbeta/pleasecaption
|
src/Web/Twitter/PleaseCaption/Status.hs
|
mit
| 1,169 | 0 | 11 | 351 | 295 | 167 | 128 | 24 | 1 |
module TruthTable.Entry where
import TruthTable.Logic
import TruthTable.Parser
import TruthTable.Printing
import System.Environment
import Data.List
entry :: IO ()
entry = getArgs >>= return . intercalate " " >>=
putStrLn . printResultOrErrorWithDefaultConfig .
genTruthTable . parseGrammar . lexer
|
tjakway/truth-table-generator
|
src/TruthTable/Entry.hs
|
mit
| 323 | 0 | 11 | 60 | 77 | 42 | 35 | 10 | 1 |
{- Alec Snyder
- hw 10 Globber Test Suite
- github repo: https://github.com/allonsy/globber
-}
module Main (main) where
import Test.Hspec
import Globber
main :: IO ()
main = hspec $ describe "Testing Globber" $ do
describe "empty pattern" $ do
it "matches empty string" $
matchGlob "" "" `shouldBe` True
it "shouldn't match non-empty string" $
matchGlob "" "string" `shouldBe` False
describe "String literals" $ do
it "matches literal string" $
matchGlob "hello" "hello" `shouldBe` True
it "shouldn't match literal string" $
matchGlob "hello" "string" `shouldBe` False
describe "Question Marks" $ do
it "should match question mark" $
matchGlob "h?llo" "hallo" `shouldBe` True
it "Shouldn't match the empty string" $
matchGlob "?" "" `shouldBe` False
it "Shouldn't match more empty strings" $
matchGlob "hello?" "hello" `shouldBe` False
it "shouldn't match question mark" $
matchGlob "hel?o" "hallo" `shouldBe` False
describe "Asterisks" $ do
it "Matches everything" $
matchGlob "*" "" `shouldBe` True
it "matches trailing asterisks" $
matchGlob "he*" "hello" `shouldBe` True
it "matches leading asterisk" $
matchGlob "*.txt" "file.txt" `shouldBe` True
it "matches double asterisk" $
matchGlob "*l*" "hello" `shouldBe` True
it "should fail on bad non asterisk match" $
matchGlob "*.txt" "file.tar" `shouldBe` False
describe "Escape Sequences" $ do --Note that when we encode strings here, the backslash is escaped so that the backslash is part of the string"
it "matches escaped regular character" $
matchGlob "\\h\\e\\l\\l\\o" "hello" `shouldBe` True
it "matches escaped questions" $
matchGlob "hello\\?" "hello?" `shouldBe` True
it "matches escaped asterisk" $
matchGlob "\\*hello\\*" "*hello*" `shouldBe` True
it "matches escaped backslash" $
matchGlob "\\\\hello" "\\hello" `shouldBe` True
it "shouldn't glob on escaped asterisk" $
matchGlob "\\*.txt" "file.txt" `shouldBe` False
|
allonsy/globber
|
TestGlobber.hs
|
mit
| 2,210 | 0 | 13 | 600 | 473 | 226 | 247 | 46 | 1 |
module Tyle.Parsers where
import Text.Parsec
import Text.Parsec.Char
import Text.Parsec.String
import Text.Parsec.Combinator
import Control.Monad (liftM)
import Tyle.Grammar
lambda :: Parser String
lambda = choice $ map string [ "lambda"
, "\\"
, "\955"
]
term :: Parser Term
term = do
x <- lower
xs <- many (alphaNum <|> oneOf "_-><")
return (x:xs)
variable :: Parser Expr
variable = liftM Var term
application :: Parser Expr
application = try $ do
t0 <- term
spaces
t1 <- term
return (App t0 t1)
typeTerm :: Parser Term
typeTerm = try $ do
t <- upper
ts <- many alphaNum
return (t:ts)
tyleType :: Parser Type
tyleType = char ':'
>> spaces
>> liftM Type typeTerm
function :: Parser Expr
function = try $ do
lambda >> spaces
t0 <- term
t1 <- tyleType
char '.' >> spaces
exp <- expression
return (Fun t0 t1 exp)
expression :: Parser Expr
expression = choice [ function
, application
, variable
]
program :: Parser [Expr]
program = many1 $ expression <* (spaces >> char '#')
|
gambogi/tyle
|
Tyle/Parsers.hs
|
mit
| 1,188 | 0 | 11 | 386 | 400 | 201 | 199 | 47 | 1 |
{-# htermination enumFromThen :: () -> () -> [()] #-}
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/Prelude_enumFromThen_2.hs
|
mit
| 54 | 0 | 2 | 10 | 3 | 2 | 1 | 1 | 0 |
-- Getting the last element from a list of n numbers using recursion
my_last n = if length n == 0
then (error "Empty list has no end defined")
else if length n == 1
then head []
else my_last (tail n)
main = print (my_last [1,2,3,4])
|
creativcoder/recurse
|
99Problems/last_element.hs
|
mit
| 285 | 0 | 9 | 99 | 86 | 45 | 41 | 6 | 3 |
-----------------------------------------------------------------------------
--
-- Module : Drool.UI.GLWindow
-- Copyright : Tobias Fuchs
-- License : AllRightsReserved
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : POSIX
--
-- |
--
-----------------------------------------------------------------------------
{-# OPTIONS -O2 -Wall #-}
module Drool.UI.GLWindow (
initComponent
) where
import Debug.Trace
import Data.IORef(IORef, readIORef, newIORef, modifyIORef, writeIORef )
import Data.Array.IO
import Control.Monad.Trans ( liftIO )
import qualified Graphics.UI.Gtk.Builder as GtkBuilder
import Graphics.Rendering.OpenGL as GL
import qualified Graphics.Rendering.FTGL as FTGL
import Graphics.UI.Gtk as Gtk
import qualified Graphics.UI.GLUT as GLUT ( initialize )
import qualified Graphics.UI.Gtk.OpenGL as GtkGL
import qualified Drool.Utils.SigGen as SigGen ( SignalGenerator(..) )
import qualified Drool.Utils.Conversions as Conv
import qualified Drool.Utils.RenderHelpers as RH
import qualified Drool.Utils.FeatureExtraction as FE ( SignalFeaturesList(..), FeatureTarget(..) )
import qualified Drool.Types as DT
import qualified Drool.ApplicationContext as AC
import qualified Drool.ContextObjects as AC
import qualified Control.Monad as M ( forever, forM )
import qualified Control.Concurrent as C
import qualified Control.Concurrent.MVar as MV ( MVar, swapMVar, takeMVar, putMVar )
import qualified Control.Concurrent.Chan as CC ( readChan )
import qualified Drool.UI.Visuals as Visuals
import Graphics.UI.GLUT ( Object(Sphere'), renderObject, Flavour(..) )
display :: IORef AC.ContextSettings -> IORef RH.RenderSettings -> [ IORef (Visuals.Visual) ] -> IO ()
display contextSettingsIORef renderSettingsIORef visualIORefs = do
contextSettings <- readIORef contextSettingsIORef
let blendModeFMSource = Conv.blendModeSourceFromIndex $ AC.blendModeFMSourceIdx contextSettings
blendModeFMFrameBuffer = Conv.blendModeFrameBufferFromIndex $ AC.blendModeFMFrameBufferIdx contextSettings
blendModeMBSource = Conv.blendModeSourceFromIndex $ AC.blendModeMBSourceIdx contextSettings
blendModeMBFrameBuffer = Conv.blendModeFrameBufferFromIndex $ AC.blendModeMBFrameBufferIdx contextSettings
clear [ColorBuffer, DepthBuffer]
preservingMatrix $ do
-- Render foreground model:
displayModel contextSettingsIORef renderSettingsIORef (visualIORefs !! 0)
blendFunc $= (blendModeMBSource, blendModeMBFrameBuffer)
preservingMatrix $ do
-- Render middleground model:
displayModel contextSettingsIORef renderSettingsIORef (visualIORefs !! 1)
blendFunc $= (blendModeFMSource, blendModeFMFrameBuffer)
preservingMatrix $ do
-- Render middleground model:
displayModel contextSettingsIORef renderSettingsIORef (visualIORefs !! 2)
return ()
displayModel :: IORef AC.ContextSettings -> IORef RH.RenderSettings -> IORef (Visuals.Visual) -> IO ()
displayModel contextSettingsIORef renderSettingsIORef visualIORef = do
-- {{{
-- renderSettingsPrev <- readIORef renderSettingsIORef
contextSettings <- readIORef contextSettingsIORef
renderSettingsPrev <- readIORef renderSettingsIORef
visual <- readIORef visualIORef
let timeoutMs = (Conv.freqToMs $ AC.renderingFrequency contextSettings)
let tick = RH.tick renderSettingsPrev
let tickMs = tick * timeoutMs
let renderSettingsCurr = renderSettingsPrev { RH.tick = (tick+1) `mod` 1000 }
let samplingSem = RH.samplingSem renderSettingsCurr
signalBuf <- readIORef (RH.signalBuf renderSettingsCurr)
featuresBuf <- readIORef (RH.featuresBuf renderSettingsCurr)
let featuresCurr = head (FE.signalFeaturesList featuresBuf)
-- Wait until there is at least one signal ready for rendering.
let nNewSignals = RH.numNewSignals renderSettingsCurr
-- Load most recent signal from buffer (last signal in list):
let recentSignal = DT.getRecentSignal signalBuf
let lastSignal = DT.getLastSignal signalBuf
-- Get length of most recent signal (= number of samples per signal):
numSamplesCurr <- case recentSignal of
Just s -> do signalBounds <- getBounds $ DT.signalArray s
return $ rangeSize signalBounds
Nothing -> return 0
numSamplesLast <- case lastSignal of
Just s -> do signalBounds <- getBounds $ DT.signalArray s
return $ rangeSize signalBounds
Nothing -> return 0
let nSamples = min numSamplesCurr numSamplesLast
let nSignals = length $ DT.signalList signalBuf
modifyIORef renderSettingsIORef ( \_ -> renderSettingsCurr { RH.numSignals = nSignals,
RH.numNewSignals = nNewSignals,
RH.numSamples = nSamples } )
renderSettings <- readIORef renderSettingsIORef
let accIncRotation = (AC.incRotationAccum contextSettings)
let incRotationStep = (AC.incRotation contextSettings)
let nextIncRotation = DT.CRotationVector { DT.rotY = (DT.rotY accIncRotation + DT.rotY incRotationStep),
DT.rotX = (DT.rotX accIncRotation + DT.rotX incRotationStep),
DT.rotZ = (DT.rotZ accIncRotation + DT.rotZ incRotationStep) }
modifyIORef contextSettingsIORef (\settings -> settings { AC.incRotationAccum = nextIncRotation } )
-- Push new signal(s) to visual:
(Visuals.update visual) renderSettings tick
visualUpdated <- readIORef visualIORef
matrixMode $= Projection
loadIdentity
perspective (realToFrac (AC.viewAngle contextSettings)) (fromIntegral canvasInitWidth / fromIntegral canvasInitHeight) 0.1 100
matrixMode $= Modelview 0
loadIdentity
let hScale = (AC.scaling contextSettings) / (100.0::Float)
surfOpacity = (AC.surfaceOpacity contextSettings) / (100.0::GLfloat)
fixedRotation = AC.fixedRotation contextSettings
accIncRotation = AC.incRotationAccum contextSettings
viewDistance = AC.viewDistance contextSettings
maxNumSignals = AC.signalBufferSize contextSettings
lightPos0 = RH.lightPos0 renderSettingsCurr
lightPos1 = RH.lightPos1 renderSettingsCurr
vPerspective = AC.renderPerspective contextSettings
let updatePerspective p = if AC.autoPerspectiveSwitch contextSettings && tickMs >= AC.autoPerspectiveSwitchInterval contextSettings then ( do
let nextPerspective = RH.nextPerspective p
modifyIORef contextSettingsIORef ( \_ -> contextSettings { AC.renderPerspective = nextPerspective } )
modifyIORef renderSettingsIORef ( \_ -> renderSettingsCurr { RH.tick = 0 } )
return nextPerspective )
else return p
curPerspective <- updatePerspective vPerspective
let blendModeSource = Conv.blendModeSourceFromIndex $ AC.blendModeSourceIdx contextSettings
let blendModeFrameBuffer = Conv.blendModeFrameBufferFromIndex $ AC.blendModeFrameBufferIdx contextSettings
-- blendFunc $= (blendModeSource, blendModeFrameBuffer)
clear [DepthBuffer]
preservingMatrix $ do
let lightIntensity = lCoeff + bCoeff
where (lCoeff,bCoeff) = RH.featuresToIntensity featuresCurr FE.GlobalTarget contextSettings
RH.useLight $ (AC.light0 contextSettings) { AC.lightIntensity = lightIntensity }
RH.useLight $ (AC.light1 contextSettings) { AC.lightIntensity = lightIntensity }
GL.position (Light 0) $= lightPos0
GL.position (Light 1) $= lightPos1
---------------------------------------------------------------------------------------------------
-- Perspective transformations
---------------------------------------------------------------------------------------------------
GL.translate $ Vector3 0 0 viewDistance
RH.applyPerspective curPerspective
RH.applyGlobalRotation fixedRotation accIncRotation
---------------------------------------------------------------------------------------------------
-- End of perspective transformations
---------------------------------------------------------------------------------------------------
-- (visWidth,visHeight,visDepth) <- (Visuals.dimensions visualUpdated)
-- fogMode $= Linear 0.0 (visDepth * 20.0)
-- fogColor $= (Color4 0.0 0.0 0.0 1.0)
-- GL.translate $ Vector3 (-0.5 * visWidth) 0 0
-- GL.translate $ Vector3 0 0 (-0.5 * visDepth)
Visuals.render visualUpdated
-- }}}
reshape :: IORef AC.ContextSettings -> Gtk.Rectangle -> IO ()
reshape settingsIORef allocation = do
let rectangleWidthHeight (Gtk.Rectangle _ _ w' h') = (w',h')
let (w,h) = rectangleWidthHeight allocation
settings <- readIORef settingsIORef
let viewAngle = AC.viewAngle settings
matrixMode $= Projection
viewport $= (Position 0 0, Size (fromIntegral w) (fromIntegral h))
perspective (realToFrac viewAngle) (fromIntegral w / fromIntegral h) 0.1 100
matrixMode $= Modelview 0
return ()
-- Component init interface for main UI.
initComponent :: GtkBuilder.Builder -> IORef AC.ContextSettings -> IORef AC.ContextObjects -> IO ()
initComponent _ contextSettingsIORef contextObjectsIORef = do
-- {{{
window <- Gtk.windowNew
_ <- GLUT.initialize "drool visualizer" []
Gtk.set window [ Gtk.containerBorderWidth := 0,
Gtk.windowTitle := "drool visualizer" ]
putStrLn "Initializing OpenGL viewport"
glConfig <- GtkGL.glConfigNew [GtkGL.GLModeRGBA, GtkGL.GLModeMultiSample, GtkGL.GLModeStencil,
GtkGL.GLModeDouble, GtkGL.GLModeDepth, GtkGL.GLModeAlpha]
_ <- GtkGL.initGL
canvas <- GtkGL.glDrawingAreaNew glConfig
cObjects <- readIORef contextObjectsIORef
cSettings <- readIORef contextSettingsIORef
let sigGen = AC.signalGenerator cObjects
let renderSettings = RH.RenderSettings { RH.signalGenerator = sigGen,
RH.samplingSem = AC.samplingSem cObjects,
RH.numNewSignalsChan = AC.numNewSignalsChan cObjects,
RH.signalBuf = AC.signalBuf cObjects,
RH.featuresBuf = AC.featuresBuf cObjects,
RH.lightPos0 = (Vertex4 (-1.0) 3.0 (-2.0) 0.0),
RH.lightPos1 = (Vertex4 1.0 3.0 2.0 0.0),
RH.numSignals = 0,
RH.numNewSignals = 0,
RH.numSamples = SigGen.numSamples sigGen,
RH.tick = 0 }
renderSettingsIORef <- newIORef renderSettings
let visualForegroundIORef = AC.visualForeground cObjects
visualMiddlegroundIORef = AC.visualMiddleground cObjects
visualBackgroundIORef = AC.visualBackground cObjects
-- Initialise some GL setting just before the canvas first gets shown
-- (We can't initialise these things earlier since the GL resources that
-- we are using wouldn't have been setup yet)
_ <- Gtk.onRealize canvas $ GtkGL.withGLDrawingArea canvas $ \_ -> do
-- {{{
-- depthMask $= Disabled
-- dither $= Enabled
normalize $= Enabled -- Automatically normaliye normal vectors to (-1.0,1.0)
shadeModel $= Smooth
depthFunc $= Just Less
-- polygonSmooth $= Enabled
-- lineSmooth $= Enabled
lighting $= Enabled
light (Light 0) $= Enabled
light (Light 1) $= Enabled
frontFace $= CCW
blend $= Enabled
multisample $= Enabled
sampleAlphaToCoverage $= Enabled
-- fog $= Enabled
lineWidthRange <- GL.get smoothLineWidthRange
lineWidth $= fst lineWidthRange -- use thinnest possible lines
colorMaterial $= Just (FrontAndBack, AmbientAndDiffuse)
let blendModeSource = Conv.blendModeSourceFromIndex $ AC.blendModeSourceIdx cSettings
let blendModeFrameBuffer = Conv.blendModeFrameBufferFromIndex $ AC.blendModeFrameBufferIdx cSettings
blendFunc $= (blendModeSource, blendModeFrameBuffer)
hint PerspectiveCorrection $= Nicest
-- hint PolygonSmooth $= Nicest
-- hint LineSmooth $= Nicest
matrixMode $= Projection
loadIdentity
viewport $= (Position 0 0, Size (fromIntegral canvasInitWidth) (fromIntegral canvasInitHeight))
perspective (realToFrac $ AC.viewAngle cSettings) (fromIntegral canvasInitWidth / fromIntegral canvasInitHeight) 0.1 10
matrixMode $= Modelview 0
loadIdentity
return ()
-- }}}
-- OnShow handler for GL canvas:
_ <- Gtk.onExpose canvas $ \_ -> do
GtkGL.withGLDrawingArea canvas $ \glwindow -> do
let visualModels = [ visualBackgroundIORef, visualMiddlegroundIORef, visualForegroundIORef ]
display contextSettingsIORef renderSettingsIORef visualModels
GtkGL.glDrawableSwapBuffers glwindow
return True
-- Resize handler:
_ <- Gtk.onSizeAllocate canvas (reshape contextSettingsIORef)
-- Add canvas (OpenGL drawing area) to GUI:
Gtk.widgetSetSizeRequest canvas canvasInitWidth canvasInitHeight
Gtk.set window [ Gtk.containerChild := canvas ]
-- Fullscreen mode:
_ <- Gtk.on window Gtk.keyPressEvent $ Gtk.tryEvent $ do
[Gtk.Control] <- Gtk.eventModifier
"f" <- Gtk.eventKeyName
liftIO $ Gtk.windowSetKeepAbove window True
liftIO $ Gtk.windowFullscreen window
_ <- Gtk.on window Gtk.keyPressEvent $ Gtk.tryEvent $ do
"Escape" <- Gtk.eventKeyName
liftIO $ Gtk.windowUnfullscreen window
liftIO $ Gtk.windowSetKeepAbove window False
let timeoutMs = (Conv.freqToMs $ AC.renderingFrequency cSettings)
{-
-- Redraw canvas according to rendering frequency:
updateCanvasTimer <- Gtk.timeoutAddFull (do
Gtk.widgetQueueDraw canvas
return True)
Gtk.priorityDefaultIdle timeoutMs
-- Remove timer for redrawing canvas when closing window:
_ <- Gtk.onDestroy window (Gtk.timeoutRemove updateCanvasTimer)
-}
-- Try to redraw canvas on every new signal:
sampleThread <- C.forkOS . M.forever $ do nNewSignals <- MV.takeMVar $ AC.samplingSem cObjects
modifyIORef renderSettingsIORef ( \rs -> rs { RH.numNewSignals = nNewSignals } )
Gtk.postGUISync $ Gtk.widgetQueueDraw canvas
Gtk.widgetShowAll window
-- }}}
canvasInitWidth :: Int
canvasInitWidth = 800
canvasInitHeight :: Int
canvasInitHeight = 600
mulColor4Value :: Color4 GLfloat -> GLfloat -> Color4 GLfloat
mulColor4Value (Color4 r g b a) value = Color4 r' g' b' a'
where r' = r * value
g' = g * value
b' = b * value
a' = a * value
|
fuchsto/drool
|
src/Drool/UI/GLWindow.hs
|
mit
| 15,073 | 0 | 19 | 3,564 | 3,198 | 1,619 | 1,579 | 214 | 4 |
import System.IO
-- For now, only takes one line
-- Curried function, predicate (Char -> Bool) on String results in List of Strings
splitBy :: (Char -> Bool) -> String -> [String]
-- p is predicate, s is string
-- dropWhile is the remains of taking while (takeWhile) p is satisfied
splitBy p s = case dropWhile p s of
-- Empty string, return empty List
"" -> []
-- String? then do
-- concatenate w and result of (splitBy p s'')
-- where w is the longest prefix that continuously fails p
-- and s'' is the remainder
s' -> w : splitBy p s''
where (w, s'') = break p s'
main = do
name <- getLine
-- Dollar sign is syntactic sugar for avoiding parenthesis
-- in this case, equivalent to (splitBy (==' ') name)
print $ splitBy (==' ') name
|
michaelx11/multilingo
|
StringOperations/src/splitBySpace.hs
|
mit
| 929 | 0 | 10 | 338 | 129 | 71 | 58 | 9 | 2 |
module Examples.Reader where
import Control.Effects.Eff
import Control.Effects.Reader
import Control.Effects.Exception
prg1 = ask
prg1run x = runPure . handle (readerHandler x)
prg1res :: Int -> Int
prg1res x = prg1run x prg1
|
edofic/effect-handlers
|
test/Examples/Reader.hs
|
mit
| 231 | 0 | 8 | 36 | 72 | 40 | 32 | 8 | 1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE ScopedTypeVariables #-}
{- | This module exports a class 'Groups' that policy modules
must define an instance of to define groups, or mappings
between a group 'Principal'and the principals in the group.
An app may then relabel a labeled value by using 'labelRewrite'.
-}
module Hails.PolicyModule.Groups ( Groups(..)
, labelRewrite ) where
import Data.Monoid
import qualified Data.Set as Set
import qualified Data.Map as Map
import Control.Monad
import LIO
import LIO.DCLabel
import Hails.Database
import Hails.Database.TCB (dbActionPriv, getActionStateTCB)
import Hails.PolicyModule
class PolicyModule pm => Groups pm where
-- | Typically, the action should expand a principal such as @#group@ to
-- list of group members @[alice, bob]@.
groups :: pm -- ^ Unused type-enforcing param
-> DCPriv -- ^ Policy module privs
-> Principal -- ^ Group
-> DBAction [Principal] -- ^ (Policy module, group members)
-- | Endorse the implementation of this instance. Note that this is
-- reduced to WHNF to catch invalid instances that use 'undefined'.
--
-- Example implementation:
--
-- > groupsInstanceEndorse _ = MyPolicyModuleTCB {- Leave other values undefined -}
groupsInstanceEndorse :: pm
-- | Given the policy module (which is used to invoke the right
-- 'groups' function) and labeled value, relabel the value according
-- to the 'Groups' of the policy module. Note that the first argument
-- may be bottom since it is solely used for typing purposes.
labelRewrite :: forall unused_pm a. Groups unused_pm
=> unused_pm
-- ^ Policy module
-> DCLabeled a
-- ^ Label
-> DBAction (DCLabeled a)
labelRewrite pm lx = withDBContext "labelRewrite" $ do
-- Make sure that 'groupsInstanceEndorse' is not bottom
_ <- liftLIO $ evaluate (groupsInstanceEndorse :: unused_pm)
pmPriv <- getPMPriv
-- Build map from principals to list of princpals
pMap <- Set.fold (\p act -> act >>= \m -> do
ps <- groups pm pmPriv p
return (Map.insert p ps m)) (return Map.empty) principals
-- Apply map to all principals in the label
let lnew = (expandPrincipals pMap s) %% (expandPrincipals pMap i)
-- Relabel labeled value
liftLIO $ withPMClearanceP pmPriv $ relabelLabeledP pmPriv lnew lx
where getPMPriv = do
pmPriv <- dbActionPriv `liftM` getActionStateTCB
-- Make sure that the underlying policy module
-- and one named in the first parameter are the same
case Map.lookup (policyModuleTypeName pm) availablePolicyModules of
Nothing -> return mempty
Just (p,_,_) -> return $ if toCNF p == privDesc pmPriv
then pmPriv
else mempty
-- Modify label by expanding principals according to the map
expandPrincipals pMap origPrincipals =
-- Function to fold over disjunctions in a CNF, expanding each
-- principal with the groups map
let cFoldF :: Disjunction -> CNF -> CNF
cFoldF disj accm =
(Set.foldr expandOne cFalse $ dToSet disj) /\ accm
-- Inner fold function, expands a single principal and adds
-- to a CNF (that represents a Disjunction
expandOne :: Principal -> CNF -> CNF
expandOne princ accm =
(dFromList $ pMap Map.! princ) \/ accm
in Set.foldr cFoldF cTrue $ cToSet origPrincipals
-- Label components
s = dcSecrecy $ labelOf lx
i = dcIntegrity $ labelOf lx
-- All unique principals in the labe
principals = getPrincipals s <> getPrincipals i
-- Get principals form component
getPrincipals = mconcat . (map dToSet) . Set.elems . cToSet
|
scslab/hails
|
Hails/PolicyModule/Groups.hs
|
mit
| 4,087 | 0 | 19 | 1,270 | 630 | 340 | 290 | 50 | 3 |
{- |
Module : ./OWL2/Translate.hs
Description : translate string to OWL2 valid names
Copyright : (c) C. Maeder, DFKI GmbH 2012
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : portable
-}
module OWL2.Translate where
import Common.IRI
import Common.Id
import Common.ProofUtils
import Data.Char
import OWL2.Parse
-- now provided in Common.IRI
--idToIRI :: Id -> IRI
--idToIRI = idToAnonIRI False
idToAnonIRI :: Bool -> Id -> IRI
idToAnonIRI = idToAnonNumberedIRI (-1)
idToNumberedIRI :: Id -> Int -> IRI
idToNumberedIRI i n = idToAnonNumberedIRI n False i
idToAnonNumberedIRI :: Int -> Bool -> Id -> IRI
idToAnonNumberedIRI n b i = nullIRI
{ iriPath = stringToId ((if b then ('_' :) else id) $ transString (show i)
++ if n < 0 then "" else '_' : show n)
, iriPos = rangeOfId i
, isAbbrev = True }
-- | translate to a valid OWL string
transString :: String -> String
transString str = let
x = 'x'
replaceChar1 d | d == x = [x, x] -- code out existing x!
| iunreserved d = [d]
| otherwise = x : replaceChar d
in case str of
"" -> [x]
c : s -> let l = replaceChar1 c in
(if isDigit c || c == '_' then [x, c]
else l) ++ concatMap replaceChar1 s
-- | injective replacement of special characters
replaceChar :: Char -> String
-- <http://www.htmlhelp.com/reference/charset/>
replaceChar c = if isAlphaNum c then [c] else lookupCharMap c
|
spechub/Hets
|
OWL2/Translate.hs
|
gpl-2.0
| 1,528 | 0 | 17 | 377 | 395 | 212 | 183 | 29 | 3 |
-- xmonad: Personal module: Hook Startup
-- Author: Simon L. J. Robin | https://sljrobin.org
--------------------------------------------------------------------------------
module Hook_Startup where
--------------------------------------------------------------------------------
-- * `XMonad.Hooks.SetWMName` -> Sets the WM name
--------------------------------------------------------------------------------
import XMonad.Hooks.SetWMName
--------------------------------------------------------------------------------
-- Hook Startup
--------------------------------------------------------------------------------
myStartupHook = do
setWMName "LG3D" -- Detect `_NET_SUPPORTING_WM_CHECK` protocol
|
sljrobin/dotfiles
|
xmonad/.xmonad/lib/Hook_Startup.hs
|
gpl-2.0
| 710 | 0 | 7 | 52 | 31 | 22 | 9 | 4 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module IniParserTest where
import Data.Map (Map)
import qualified Data.Map as M
import Text.Trifecta
import Test.Hspec
import IniParser
maybeSuccess :: Result a -> Maybe a
maybeSuccess (Success a) = Just a
maybeSuccess _ = Nothing
iniParserTest :: IO ()
iniParserTest = hspec $ do
describe "Assignment Parsing" $
it "can parse a simple assignment" $ do
let m = parseByteString parseAssignment mempty assignmentEx
r' = maybeSuccess m
print m
r' `shouldBe` Just ("woot", "1")
describe "Header Parsing" $
it "can parse a simple header" $ do
let m = parseByteString parseHeader mempty headerEx
r' = maybeSuccess m
print m
r' `shouldBe` Just (Header "blah")
describe "Comment parsing" $
it "Skips comment before header" $ do
let p = skipComments >> parseHeader
i = "; woot\n[blah]"
m = parseByteString p mempty i
r' = maybeSuccess m
print m
r' `shouldBe` Just (Header "blah")
describe "Section parsing" $
it "can parse a simple section" $ do
let m = parseByteString parseSection mempty sectionEx
r' = maybeSuccess m
states = M.fromList [("Chris", "Texas")]
expected' = Just (Section (Header "states") states)
print m
r' `shouldBe` expected'
describe "INI parsing" $
it "Can parse multiple sections" $ do
let m = parseByteString parseIni mempty sectionEx''
r' = maybeSuccess m
sectionValues = M.fromList [("alias", "claw"), ("host", "wikipedia.org")]
whatisitValues = M.fromList [("red", "intoothandclaw")]
expected' = Just (Config (M.fromList [ (Header "section", sectionValues), (Header "whatisit", whatisitValues)]))
print m
r' `shouldBe` expected'
|
nirvinm/Solving-Exercises-in-Haskell-Programming-From-First-Principles
|
ParserCombinators/test/IniParserTest.hs
|
gpl-3.0
| 1,968 | 0 | 21 | 623 | 550 | 274 | 276 | 49 | 1 |
main :: IO ()
main = do
putStrLn "Running tests"
|
jerhoud/true-real
|
test/Test.hs
|
gpl-3.0
| 51 | 0 | 7 | 12 | 22 | 10 | 12 | 3 | 1 |
<?xml version='1.0' encoding='ISO-8859-1' ?>
<!DOCTYPE helpset
PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN"
"http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0">
<title>Sentinel-2 Toolbox Help</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view mergetype="javax.help.UniteAppendMerge">
<name>TOC</name>
<label>Contents</label>
<type>javax.help.TOCView</type>
<data>toc.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">JavaHelpSearch</data>
</view>
<presentation default="true">
<name>Sentinel-2 Toolbox Help</name>
<size width="800" height="600"/>
<location x="100" y="100"/>
</presentation>
</helpset>
|
corinavaduva/s2tbx-s2tbx-1.0.2
|
s2tbx-help/src/main/resources/doc/help/beam.hs
|
gpl-3.0
| 956 | 69 | 53 | 210 | 367 | 183 | 184 | -1 | -1 |
module Selection where
import System.Exit
import System.IO
import System.Process
-- | If no selector command is given, then the options are displayed on stdout
-- and the user is prompted to enter one of them on stdin. If a selector command
-- (such as `dmenu') is given, then the options are sent to selector command by
-- stdin (each on a separate line)
select :: Maybe String -- ^ Selector command
-> String -- ^ Selector prompt
-> [String] -- ^ Options to the selector
-> IO String
select Nothing prompt opts =
do _ <- mapM putStrLn opts
putStr $ prompt ++ " "
hFlush stdout
getLine
select (Just command) _ opts =
do let cp = CreateProcess
{ cmdspec = ShellCommand command
, cwd = Nothing
, env = Nothing
, std_in = CreatePipe
, std_out = CreatePipe
, std_err = Inherit
, close_fds = True
, create_group = False
, delegate_ctlc = False
, detach_console = False -- I don't Windows
, create_new_console = False -- I don't Windows
, new_session = False
, child_group = Nothing
, child_user = Nothing
}
(Just i, Just o, Nothing, p) <- createProcess cp
_ <- mapM (hPutStrLn i) opts
hClose i
ec <- waitForProcess p
case ec of
ExitSuccess -> do r <- hGetLine o
hClose o
return r
ExitFailure _ -> error $ "Selector command (" ++ command ++ ") failed."
|
frozencemetery/haskey
|
src/Selection.hs
|
gpl-3.0
| 1,556 | 0 | 13 | 541 | 332 | 176 | 156 | 38 | 2 |
-- {-# LANGUAGE GADTs #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Symdiff (diff) where
import Data.Array.Accelerate.Smart (Exp)
import Data.Array.Accelerate (foreignExp)
import Types
import qualified AST.Diff
-- import qualified AST.Grad
import qualified AST.PrimFun
import Differentiate -- (Differentiate, DifferentiateValue, ToolsT)
import System.Random
import System.IO.Unsafe
-- Differentiating a function is intuitive
-- Differentiating an AST that looks like a result less so.
data Tools = Tools
-- TODO - prove properly that this is pure, since it uses unsafePerformIO
-- It's used to tag differentiation variables rather than traversing the AST
-- and removing them after use
instance ToolsT Tools where
diffF tk f (x::Exp a) = diffast where
diffast = diffT tk (f fakex) fakex
fakex = foreignExp (WithRespectTo marker) id x :: Exp a
marker = (unsafePerformIO randomIO)
diffT = diffVT
diffprimfun = AST.PrimFun.diffprimfun'
diff' = AST.Diff.diff'
-- gradF :: (Elt e, IsFloating e)
-- => Tools
-- -> (Acc (Vector e) -> Exp e)
-- -> Acc (Vector e)
-- -> Exp e
-- gradF tk f (vx :: Acc (Vector a)) = diffast where
-- diffast = gradT tk (f fakevx)
-- fakevx = foreignAcc (WithRespectToA marker) id vx
-- marker = (unsafePerformIO randomIO)
--grad = gradF tools
diff :: (DifferentiateValue a dx) => (Exp dx -> Exp a) -> Exp dx -> Exp a
diff = diffF Tools
|
johncant/accelerate-symdiff
|
src/Symdiff.hs
|
gpl-3.0
| 1,421 | 0 | 10 | 279 | 244 | 144 | 100 | 21 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.SafeBrowsing.Types.Product
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.SafeBrowsing.Types.Product where
import Network.Google.Prelude
import Network.Google.SafeBrowsing.Types.Sum
--
-- /See:/ 'googleSecuritySafebrowsingV4ThreatHit' smart constructor.
data GoogleSecuritySafebrowsingV4ThreatHit =
GoogleSecuritySafebrowsingV4ThreatHit'
{ _gssvthUserInfo :: !(Maybe GoogleSecuritySafebrowsingV4ThreatHitUserInfo)
, _gssvthThreatType :: !(Maybe GoogleSecuritySafebrowsingV4ThreatHitThreatType)
, _gssvthResources :: !(Maybe [GoogleSecuritySafebrowsingV4ThreatHitThreatSource])
, _gssvthEntry :: !(Maybe GoogleSecuritySafebrowsingV4ThreatEntry)
, _gssvthClientInfo :: !(Maybe GoogleSecuritySafebrowsingV4ClientInfo)
, _gssvthPlatformType :: !(Maybe GoogleSecuritySafebrowsingV4ThreatHitPlatformType)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleSecuritySafebrowsingV4ThreatHit' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gssvthUserInfo'
--
-- * 'gssvthThreatType'
--
-- * 'gssvthResources'
--
-- * 'gssvthEntry'
--
-- * 'gssvthClientInfo'
--
-- * 'gssvthPlatformType'
googleSecuritySafebrowsingV4ThreatHit
:: GoogleSecuritySafebrowsingV4ThreatHit
googleSecuritySafebrowsingV4ThreatHit =
GoogleSecuritySafebrowsingV4ThreatHit'
{ _gssvthUserInfo = Nothing
, _gssvthThreatType = Nothing
, _gssvthResources = Nothing
, _gssvthEntry = Nothing
, _gssvthClientInfo = Nothing
, _gssvthPlatformType = Nothing
}
-- | Details about the user that encountered the threat.
gssvthUserInfo :: Lens' GoogleSecuritySafebrowsingV4ThreatHit (Maybe GoogleSecuritySafebrowsingV4ThreatHitUserInfo)
gssvthUserInfo
= lens _gssvthUserInfo
(\ s a -> s{_gssvthUserInfo = a})
-- | The threat type reported.
gssvthThreatType :: Lens' GoogleSecuritySafebrowsingV4ThreatHit (Maybe GoogleSecuritySafebrowsingV4ThreatHitThreatType)
gssvthThreatType
= lens _gssvthThreatType
(\ s a -> s{_gssvthThreatType = a})
-- | The resources related to the threat hit.
gssvthResources :: Lens' GoogleSecuritySafebrowsingV4ThreatHit [GoogleSecuritySafebrowsingV4ThreatHitThreatSource]
gssvthResources
= lens _gssvthResources
(\ s a -> s{_gssvthResources = a})
. _Default
. _Coerce
-- | The threat entry responsible for the hit. Full hash should be reported
-- for hash-based hits.
gssvthEntry :: Lens' GoogleSecuritySafebrowsingV4ThreatHit (Maybe GoogleSecuritySafebrowsingV4ThreatEntry)
gssvthEntry
= lens _gssvthEntry (\ s a -> s{_gssvthEntry = a})
-- | Client-reported identification.
gssvthClientInfo :: Lens' GoogleSecuritySafebrowsingV4ThreatHit (Maybe GoogleSecuritySafebrowsingV4ClientInfo)
gssvthClientInfo
= lens _gssvthClientInfo
(\ s a -> s{_gssvthClientInfo = a})
-- | The platform type reported.
gssvthPlatformType :: Lens' GoogleSecuritySafebrowsingV4ThreatHit (Maybe GoogleSecuritySafebrowsingV4ThreatHitPlatformType)
gssvthPlatformType
= lens _gssvthPlatformType
(\ s a -> s{_gssvthPlatformType = a})
instance FromJSON
GoogleSecuritySafebrowsingV4ThreatHit
where
parseJSON
= withObject "GoogleSecuritySafebrowsingV4ThreatHit"
(\ o ->
GoogleSecuritySafebrowsingV4ThreatHit' <$>
(o .:? "userInfo") <*> (o .:? "threatType") <*>
(o .:? "resources" .!= mempty)
<*> (o .:? "entry")
<*> (o .:? "clientInfo")
<*> (o .:? "platformType"))
instance ToJSON GoogleSecuritySafebrowsingV4ThreatHit
where
toJSON GoogleSecuritySafebrowsingV4ThreatHit'{..}
= object
(catMaybes
[("userInfo" .=) <$> _gssvthUserInfo,
("threatType" .=) <$> _gssvthThreatType,
("resources" .=) <$> _gssvthResources,
("entry" .=) <$> _gssvthEntry,
("clientInfo" .=) <$> _gssvthClientInfo,
("platformType" .=) <$> _gssvthPlatformType])
-- | A set of raw indices to remove from a local list.
--
-- /See:/ 'googleSecuritySafebrowsingV4RawIndices' smart constructor.
newtype GoogleSecuritySafebrowsingV4RawIndices =
GoogleSecuritySafebrowsingV4RawIndices'
{ _gssvriIndices :: Maybe [Textual Int32]
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleSecuritySafebrowsingV4RawIndices' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gssvriIndices'
googleSecuritySafebrowsingV4RawIndices
:: GoogleSecuritySafebrowsingV4RawIndices
googleSecuritySafebrowsingV4RawIndices =
GoogleSecuritySafebrowsingV4RawIndices' {_gssvriIndices = Nothing}
-- | The indices to remove from a lexicographically-sorted local list.
gssvriIndices :: Lens' GoogleSecuritySafebrowsingV4RawIndices [Int32]
gssvriIndices
= lens _gssvriIndices
(\ s a -> s{_gssvriIndices = a})
. _Default
. _Coerce
instance FromJSON
GoogleSecuritySafebrowsingV4RawIndices
where
parseJSON
= withObject "GoogleSecuritySafebrowsingV4RawIndices"
(\ o ->
GoogleSecuritySafebrowsingV4RawIndices' <$>
(o .:? "indices" .!= mempty))
instance ToJSON
GoogleSecuritySafebrowsingV4RawIndices
where
toJSON GoogleSecuritySafebrowsingV4RawIndices'{..}
= object
(catMaybes [("indices" .=) <$> _gssvriIndices])
-- | Describes a Safe Browsing API update request. Clients can request
-- updates for multiple lists in a single request. The server may not
-- respond to all requests, if the server has no updates for that list.
-- NOTE: Field index 2 is unused. NEXT: 5
--
-- /See:/ 'googleSecuritySafebrowsingV4FetchThreatListUpdatesRequest' smart constructor.
data GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequest =
GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequest'
{ _gssvftlurListUpdateRequests :: !(Maybe [GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequest])
, _gssvftlurClient :: !(Maybe GoogleSecuritySafebrowsingV4ClientInfo)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gssvftlurListUpdateRequests'
--
-- * 'gssvftlurClient'
googleSecuritySafebrowsingV4FetchThreatListUpdatesRequest
:: GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequest
googleSecuritySafebrowsingV4FetchThreatListUpdatesRequest =
GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequest'
{_gssvftlurListUpdateRequests = Nothing, _gssvftlurClient = Nothing}
-- | The requested threat list updates.
gssvftlurListUpdateRequests :: Lens' GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequest [GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequest]
gssvftlurListUpdateRequests
= lens _gssvftlurListUpdateRequests
(\ s a -> s{_gssvftlurListUpdateRequests = a})
. _Default
. _Coerce
-- | The client metadata.
gssvftlurClient :: Lens' GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequest (Maybe GoogleSecuritySafebrowsingV4ClientInfo)
gssvftlurClient
= lens _gssvftlurClient
(\ s a -> s{_gssvftlurClient = a})
instance FromJSON
GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequest
where
parseJSON
= withObject
"GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequest"
(\ o ->
GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequest'
<$>
(o .:? "listUpdateRequests" .!= mempty) <*>
(o .:? "client"))
instance ToJSON
GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequest
where
toJSON
GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequest'{..}
= object
(catMaybes
[("listUpdateRequests" .=) <$>
_gssvftlurListUpdateRequests,
("client" .=) <$> _gssvftlurClient])
-- | Request to return full hashes matched by the provided hash prefixes.
--
-- /See:/ 'googleSecuritySafebrowsingV4FindFullHashesRequest' smart constructor.
data GoogleSecuritySafebrowsingV4FindFullHashesRequest =
GoogleSecuritySafebrowsingV4FindFullHashesRequest'
{ _gssvffhrThreatInfo :: !(Maybe GoogleSecuritySafebrowsingV4ThreatInfo)
, _gssvffhrAPIClient :: !(Maybe GoogleSecuritySafebrowsingV4ClientInfo)
, _gssvffhrClientStates :: !(Maybe [Bytes])
, _gssvffhrClient :: !(Maybe GoogleSecuritySafebrowsingV4ClientInfo)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleSecuritySafebrowsingV4FindFullHashesRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gssvffhrThreatInfo'
--
-- * 'gssvffhrAPIClient'
--
-- * 'gssvffhrClientStates'
--
-- * 'gssvffhrClient'
googleSecuritySafebrowsingV4FindFullHashesRequest
:: GoogleSecuritySafebrowsingV4FindFullHashesRequest
googleSecuritySafebrowsingV4FindFullHashesRequest =
GoogleSecuritySafebrowsingV4FindFullHashesRequest'
{ _gssvffhrThreatInfo = Nothing
, _gssvffhrAPIClient = Nothing
, _gssvffhrClientStates = Nothing
, _gssvffhrClient = Nothing
}
-- | The lists and hashes to be checked.
gssvffhrThreatInfo :: Lens' GoogleSecuritySafebrowsingV4FindFullHashesRequest (Maybe GoogleSecuritySafebrowsingV4ThreatInfo)
gssvffhrThreatInfo
= lens _gssvffhrThreatInfo
(\ s a -> s{_gssvffhrThreatInfo = a})
-- | Client metadata associated with callers of higher-level APIs built on
-- top of the client\'s implementation.
gssvffhrAPIClient :: Lens' GoogleSecuritySafebrowsingV4FindFullHashesRequest (Maybe GoogleSecuritySafebrowsingV4ClientInfo)
gssvffhrAPIClient
= lens _gssvffhrAPIClient
(\ s a -> s{_gssvffhrAPIClient = a})
-- | The current client states for each of the client\'s local threat lists.
gssvffhrClientStates :: Lens' GoogleSecuritySafebrowsingV4FindFullHashesRequest [ByteString]
gssvffhrClientStates
= lens _gssvffhrClientStates
(\ s a -> s{_gssvffhrClientStates = a})
. _Default
. _Coerce
-- | The client metadata.
gssvffhrClient :: Lens' GoogleSecuritySafebrowsingV4FindFullHashesRequest (Maybe GoogleSecuritySafebrowsingV4ClientInfo)
gssvffhrClient
= lens _gssvffhrClient
(\ s a -> s{_gssvffhrClient = a})
instance FromJSON
GoogleSecuritySafebrowsingV4FindFullHashesRequest
where
parseJSON
= withObject
"GoogleSecuritySafebrowsingV4FindFullHashesRequest"
(\ o ->
GoogleSecuritySafebrowsingV4FindFullHashesRequest'
<$>
(o .:? "threatInfo") <*> (o .:? "apiClient") <*>
(o .:? "clientStates" .!= mempty)
<*> (o .:? "client"))
instance ToJSON
GoogleSecuritySafebrowsingV4FindFullHashesRequest
where
toJSON
GoogleSecuritySafebrowsingV4FindFullHashesRequest'{..}
= object
(catMaybes
[("threatInfo" .=) <$> _gssvffhrThreatInfo,
("apiClient" .=) <$> _gssvffhrAPIClient,
("clientStates" .=) <$> _gssvffhrClientStates,
("client" .=) <$> _gssvffhrClient])
-- | A set of threats that should be added or removed from a client\'s local
-- database.
--
-- /See:/ 'googleSecuritySafebrowsingV4ThreatEntrySet' smart constructor.
data GoogleSecuritySafebrowsingV4ThreatEntrySet =
GoogleSecuritySafebrowsingV4ThreatEntrySet'
{ _gssvtesRiceHashes :: !(Maybe GoogleSecuritySafebrowsingV4RiceDeltaEncoding)
, _gssvtesRiceIndices :: !(Maybe GoogleSecuritySafebrowsingV4RiceDeltaEncoding)
, _gssvtesRawHashes :: !(Maybe GoogleSecuritySafebrowsingV4RawHashes)
, _gssvtesRawIndices :: !(Maybe GoogleSecuritySafebrowsingV4RawIndices)
, _gssvtesCompressionType :: !(Maybe GoogleSecuritySafebrowsingV4ThreatEntrySetCompressionType)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleSecuritySafebrowsingV4ThreatEntrySet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gssvtesRiceHashes'
--
-- * 'gssvtesRiceIndices'
--
-- * 'gssvtesRawHashes'
--
-- * 'gssvtesRawIndices'
--
-- * 'gssvtesCompressionType'
googleSecuritySafebrowsingV4ThreatEntrySet
:: GoogleSecuritySafebrowsingV4ThreatEntrySet
googleSecuritySafebrowsingV4ThreatEntrySet =
GoogleSecuritySafebrowsingV4ThreatEntrySet'
{ _gssvtesRiceHashes = Nothing
, _gssvtesRiceIndices = Nothing
, _gssvtesRawHashes = Nothing
, _gssvtesRawIndices = Nothing
, _gssvtesCompressionType = Nothing
}
-- | The encoded 4-byte prefixes of SHA256-formatted entries, using a
-- Golomb-Rice encoding. The hashes are converted to uint32, sorted in
-- ascending order, then delta encoded and stored as encoded_data.
gssvtesRiceHashes :: Lens' GoogleSecuritySafebrowsingV4ThreatEntrySet (Maybe GoogleSecuritySafebrowsingV4RiceDeltaEncoding)
gssvtesRiceHashes
= lens _gssvtesRiceHashes
(\ s a -> s{_gssvtesRiceHashes = a})
-- | The encoded local, lexicographically-sorted list indices, using a
-- Golomb-Rice encoding. Used for sending compressed removal indices. The
-- removal indices (uint32) are sorted in ascending order, then delta
-- encoded and stored as encoded_data.
gssvtesRiceIndices :: Lens' GoogleSecuritySafebrowsingV4ThreatEntrySet (Maybe GoogleSecuritySafebrowsingV4RiceDeltaEncoding)
gssvtesRiceIndices
= lens _gssvtesRiceIndices
(\ s a -> s{_gssvtesRiceIndices = a})
-- | The raw SHA256-formatted entries.
gssvtesRawHashes :: Lens' GoogleSecuritySafebrowsingV4ThreatEntrySet (Maybe GoogleSecuritySafebrowsingV4RawHashes)
gssvtesRawHashes
= lens _gssvtesRawHashes
(\ s a -> s{_gssvtesRawHashes = a})
-- | The raw removal indices for a local list.
gssvtesRawIndices :: Lens' GoogleSecuritySafebrowsingV4ThreatEntrySet (Maybe GoogleSecuritySafebrowsingV4RawIndices)
gssvtesRawIndices
= lens _gssvtesRawIndices
(\ s a -> s{_gssvtesRawIndices = a})
-- | The compression type for the entries in this set.
gssvtesCompressionType :: Lens' GoogleSecuritySafebrowsingV4ThreatEntrySet (Maybe GoogleSecuritySafebrowsingV4ThreatEntrySetCompressionType)
gssvtesCompressionType
= lens _gssvtesCompressionType
(\ s a -> s{_gssvtesCompressionType = a})
instance FromJSON
GoogleSecuritySafebrowsingV4ThreatEntrySet
where
parseJSON
= withObject
"GoogleSecuritySafebrowsingV4ThreatEntrySet"
(\ o ->
GoogleSecuritySafebrowsingV4ThreatEntrySet' <$>
(o .:? "riceHashes") <*> (o .:? "riceIndices") <*>
(o .:? "rawHashes")
<*> (o .:? "rawIndices")
<*> (o .:? "compressionType"))
instance ToJSON
GoogleSecuritySafebrowsingV4ThreatEntrySet
where
toJSON
GoogleSecuritySafebrowsingV4ThreatEntrySet'{..}
= object
(catMaybes
[("riceHashes" .=) <$> _gssvtesRiceHashes,
("riceIndices" .=) <$> _gssvtesRiceIndices,
("rawHashes" .=) <$> _gssvtesRawHashes,
("rawIndices" .=) <$> _gssvtesRawIndices,
("compressionType" .=) <$> _gssvtesCompressionType])
--
-- /See:/ 'googleSecuritySafebrowsingV4FindThreatMatchesResponse' smart constructor.
newtype GoogleSecuritySafebrowsingV4FindThreatMatchesResponse =
GoogleSecuritySafebrowsingV4FindThreatMatchesResponse'
{ _gssvftmrMatches :: Maybe [GoogleSecuritySafebrowsingV4ThreatMatch]
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleSecuritySafebrowsingV4FindThreatMatchesResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gssvftmrMatches'
googleSecuritySafebrowsingV4FindThreatMatchesResponse
:: GoogleSecuritySafebrowsingV4FindThreatMatchesResponse
googleSecuritySafebrowsingV4FindThreatMatchesResponse =
GoogleSecuritySafebrowsingV4FindThreatMatchesResponse'
{_gssvftmrMatches = Nothing}
-- | The threat list matches.
gssvftmrMatches :: Lens' GoogleSecuritySafebrowsingV4FindThreatMatchesResponse [GoogleSecuritySafebrowsingV4ThreatMatch]
gssvftmrMatches
= lens _gssvftmrMatches
(\ s a -> s{_gssvftmrMatches = a})
. _Default
. _Coerce
instance FromJSON
GoogleSecuritySafebrowsingV4FindThreatMatchesResponse
where
parseJSON
= withObject
"GoogleSecuritySafebrowsingV4FindThreatMatchesResponse"
(\ o ->
GoogleSecuritySafebrowsingV4FindThreatMatchesResponse'
<$> (o .:? "matches" .!= mempty))
instance ToJSON
GoogleSecuritySafebrowsingV4FindThreatMatchesResponse
where
toJSON
GoogleSecuritySafebrowsingV4FindThreatMatchesResponse'{..}
= object
(catMaybes [("matches" .=) <$> _gssvftmrMatches])
-- | The constraints for this update.
--
-- /See:/ 'googleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequestConstraints' smart constructor.
data GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequestConstraints =
GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequestConstraints'
{ _gssvftlurlurcMaxUpdateEntries :: !(Maybe (Textual Int32))
, _gssvftlurlurcDeviceLocation :: !(Maybe Text)
, _gssvftlurlurcLanguage :: !(Maybe Text)
, _gssvftlurlurcRegion :: !(Maybe Text)
, _gssvftlurlurcSupportedCompressions :: !(Maybe [GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequestConstraintsSupportedCompressionsItem])
, _gssvftlurlurcMaxDatabaseEntries :: !(Maybe (Textual Int32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequestConstraints' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gssvftlurlurcMaxUpdateEntries'
--
-- * 'gssvftlurlurcDeviceLocation'
--
-- * 'gssvftlurlurcLanguage'
--
-- * 'gssvftlurlurcRegion'
--
-- * 'gssvftlurlurcSupportedCompressions'
--
-- * 'gssvftlurlurcMaxDatabaseEntries'
googleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequestConstraints
:: GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequestConstraints
googleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequestConstraints =
GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequestConstraints'
{ _gssvftlurlurcMaxUpdateEntries = Nothing
, _gssvftlurlurcDeviceLocation = Nothing
, _gssvftlurlurcLanguage = Nothing
, _gssvftlurlurcRegion = Nothing
, _gssvftlurlurcSupportedCompressions = Nothing
, _gssvftlurlurcMaxDatabaseEntries = Nothing
}
-- | The maximum size in number of entries. The update will not contain more
-- entries than this value. This should be a power of 2 between 2**10 and
-- 2**20. If zero, no update size limit is set.
gssvftlurlurcMaxUpdateEntries :: Lens' GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequestConstraints (Maybe Int32)
gssvftlurlurcMaxUpdateEntries
= lens _gssvftlurlurcMaxUpdateEntries
(\ s a -> s{_gssvftlurlurcMaxUpdateEntries = a})
. mapping _Coerce
-- | A client\'s physical location, expressed as a ISO 31166-1 alpha-2 region
-- code.
gssvftlurlurcDeviceLocation :: Lens' GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequestConstraints (Maybe Text)
gssvftlurlurcDeviceLocation
= lens _gssvftlurlurcDeviceLocation
(\ s a -> s{_gssvftlurlurcDeviceLocation = a})
-- | Requests the lists for a specific language. Expects ISO 639 alpha-2
-- format.
gssvftlurlurcLanguage :: Lens' GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequestConstraints (Maybe Text)
gssvftlurlurcLanguage
= lens _gssvftlurlurcLanguage
(\ s a -> s{_gssvftlurlurcLanguage = a})
-- | Requests the list for a specific geographic location. If not set the
-- server may pick that value based on the user\'s IP address. Expects ISO
-- 3166-1 alpha-2 format.
gssvftlurlurcRegion :: Lens' GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequestConstraints (Maybe Text)
gssvftlurlurcRegion
= lens _gssvftlurlurcRegion
(\ s a -> s{_gssvftlurlurcRegion = a})
-- | The compression types supported by the client.
gssvftlurlurcSupportedCompressions :: Lens' GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequestConstraints [GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequestConstraintsSupportedCompressionsItem]
gssvftlurlurcSupportedCompressions
= lens _gssvftlurlurcSupportedCompressions
(\ s a -> s{_gssvftlurlurcSupportedCompressions = a})
. _Default
. _Coerce
-- | Sets the maximum number of entries that the client is willing to have in
-- the local database for the specified list. This should be a power of 2
-- between 2**10 and 2**20. If zero, no database size limit is set.
gssvftlurlurcMaxDatabaseEntries :: Lens' GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequestConstraints (Maybe Int32)
gssvftlurlurcMaxDatabaseEntries
= lens _gssvftlurlurcMaxDatabaseEntries
(\ s a -> s{_gssvftlurlurcMaxDatabaseEntries = a})
. mapping _Coerce
instance FromJSON
GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequestConstraints
where
parseJSON
= withObject
"GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequestConstraints"
(\ o ->
GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequestConstraints'
<$>
(o .:? "maxUpdateEntries") <*>
(o .:? "deviceLocation")
<*> (o .:? "language")
<*> (o .:? "region")
<*> (o .:? "supportedCompressions" .!= mempty)
<*> (o .:? "maxDatabaseEntries"))
instance ToJSON
GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequestConstraints
where
toJSON
GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequestConstraints'{..}
= object
(catMaybes
[("maxUpdateEntries" .=) <$>
_gssvftlurlurcMaxUpdateEntries,
("deviceLocation" .=) <$>
_gssvftlurlurcDeviceLocation,
("language" .=) <$> _gssvftlurlurcLanguage,
("region" .=) <$> _gssvftlurlurcRegion,
("supportedCompressions" .=) <$>
_gssvftlurlurcSupportedCompressions,
("maxDatabaseEntries" .=) <$>
_gssvftlurlurcMaxDatabaseEntries])
-- | The metadata associated with a specific threat entry. The client is
-- expected to know the metadata key\/value pairs associated with each
-- threat type.
--
-- /See:/ 'googleSecuritySafebrowsingV4ThreatEntryMetadata' smart constructor.
newtype GoogleSecuritySafebrowsingV4ThreatEntryMetadata =
GoogleSecuritySafebrowsingV4ThreatEntryMetadata'
{ _gssvtemEntries :: Maybe [GoogleSecuritySafebrowsingV4ThreatEntryMetadataMetadataEntry]
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleSecuritySafebrowsingV4ThreatEntryMetadata' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gssvtemEntries'
googleSecuritySafebrowsingV4ThreatEntryMetadata
:: GoogleSecuritySafebrowsingV4ThreatEntryMetadata
googleSecuritySafebrowsingV4ThreatEntryMetadata =
GoogleSecuritySafebrowsingV4ThreatEntryMetadata' {_gssvtemEntries = Nothing}
-- | The metadata entries.
gssvtemEntries :: Lens' GoogleSecuritySafebrowsingV4ThreatEntryMetadata [GoogleSecuritySafebrowsingV4ThreatEntryMetadataMetadataEntry]
gssvtemEntries
= lens _gssvtemEntries
(\ s a -> s{_gssvtemEntries = a})
. _Default
. _Coerce
instance FromJSON
GoogleSecuritySafebrowsingV4ThreatEntryMetadata
where
parseJSON
= withObject
"GoogleSecuritySafebrowsingV4ThreatEntryMetadata"
(\ o ->
GoogleSecuritySafebrowsingV4ThreatEntryMetadata' <$>
(o .:? "entries" .!= mempty))
instance ToJSON
GoogleSecuritySafebrowsingV4ThreatEntryMetadata
where
toJSON
GoogleSecuritySafebrowsingV4ThreatEntryMetadata'{..}
= object
(catMaybes [("entries" .=) <$> _gssvtemEntries])
-- | Request to check entries against lists.
--
-- /See:/ 'googleSecuritySafebrowsingV4FindThreatMatchesRequest' smart constructor.
data GoogleSecuritySafebrowsingV4FindThreatMatchesRequest =
GoogleSecuritySafebrowsingV4FindThreatMatchesRequest'
{ _gssvftmrThreatInfo :: !(Maybe GoogleSecuritySafebrowsingV4ThreatInfo)
, _gssvftmrClient :: !(Maybe GoogleSecuritySafebrowsingV4ClientInfo)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleSecuritySafebrowsingV4FindThreatMatchesRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gssvftmrThreatInfo'
--
-- * 'gssvftmrClient'
googleSecuritySafebrowsingV4FindThreatMatchesRequest
:: GoogleSecuritySafebrowsingV4FindThreatMatchesRequest
googleSecuritySafebrowsingV4FindThreatMatchesRequest =
GoogleSecuritySafebrowsingV4FindThreatMatchesRequest'
{_gssvftmrThreatInfo = Nothing, _gssvftmrClient = Nothing}
-- | The lists and entries to be checked for matches.
gssvftmrThreatInfo :: Lens' GoogleSecuritySafebrowsingV4FindThreatMatchesRequest (Maybe GoogleSecuritySafebrowsingV4ThreatInfo)
gssvftmrThreatInfo
= lens _gssvftmrThreatInfo
(\ s a -> s{_gssvftmrThreatInfo = a})
-- | The client metadata.
gssvftmrClient :: Lens' GoogleSecuritySafebrowsingV4FindThreatMatchesRequest (Maybe GoogleSecuritySafebrowsingV4ClientInfo)
gssvftmrClient
= lens _gssvftmrClient
(\ s a -> s{_gssvftmrClient = a})
instance FromJSON
GoogleSecuritySafebrowsingV4FindThreatMatchesRequest
where
parseJSON
= withObject
"GoogleSecuritySafebrowsingV4FindThreatMatchesRequest"
(\ o ->
GoogleSecuritySafebrowsingV4FindThreatMatchesRequest'
<$> (o .:? "threatInfo") <*> (o .:? "client"))
instance ToJSON
GoogleSecuritySafebrowsingV4FindThreatMatchesRequest
where
toJSON
GoogleSecuritySafebrowsingV4FindThreatMatchesRequest'{..}
= object
(catMaybes
[("threatInfo" .=) <$> _gssvftmrThreatInfo,
("client" .=) <$> _gssvftmrClient])
-- | Describes an individual threat list. A list is defined by three
-- parameters: the type of threat posed, the type of platform targeted by
-- the threat, and the type of entries in the list.
--
-- /See:/ 'googleSecuritySafebrowsingV4ThreatListDescriptor' smart constructor.
data GoogleSecuritySafebrowsingV4ThreatListDescriptor =
GoogleSecuritySafebrowsingV4ThreatListDescriptor'
{ _gssvtldThreatEntryType :: !(Maybe GoogleSecuritySafebrowsingV4ThreatListDescriptorThreatEntryType)
, _gssvtldThreatType :: !(Maybe GoogleSecuritySafebrowsingV4ThreatListDescriptorThreatType)
, _gssvtldPlatformType :: !(Maybe GoogleSecuritySafebrowsingV4ThreatListDescriptorPlatformType)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleSecuritySafebrowsingV4ThreatListDescriptor' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gssvtldThreatEntryType'
--
-- * 'gssvtldThreatType'
--
-- * 'gssvtldPlatformType'
googleSecuritySafebrowsingV4ThreatListDescriptor
:: GoogleSecuritySafebrowsingV4ThreatListDescriptor
googleSecuritySafebrowsingV4ThreatListDescriptor =
GoogleSecuritySafebrowsingV4ThreatListDescriptor'
{ _gssvtldThreatEntryType = Nothing
, _gssvtldThreatType = Nothing
, _gssvtldPlatformType = Nothing
}
-- | The entry types contained in the list.
gssvtldThreatEntryType :: Lens' GoogleSecuritySafebrowsingV4ThreatListDescriptor (Maybe GoogleSecuritySafebrowsingV4ThreatListDescriptorThreatEntryType)
gssvtldThreatEntryType
= lens _gssvtldThreatEntryType
(\ s a -> s{_gssvtldThreatEntryType = a})
-- | The threat type posed by the list\'s entries.
gssvtldThreatType :: Lens' GoogleSecuritySafebrowsingV4ThreatListDescriptor (Maybe GoogleSecuritySafebrowsingV4ThreatListDescriptorThreatType)
gssvtldThreatType
= lens _gssvtldThreatType
(\ s a -> s{_gssvtldThreatType = a})
-- | The platform type targeted by the list\'s entries.
gssvtldPlatformType :: Lens' GoogleSecuritySafebrowsingV4ThreatListDescriptor (Maybe GoogleSecuritySafebrowsingV4ThreatListDescriptorPlatformType)
gssvtldPlatformType
= lens _gssvtldPlatformType
(\ s a -> s{_gssvtldPlatformType = a})
instance FromJSON
GoogleSecuritySafebrowsingV4ThreatListDescriptor
where
parseJSON
= withObject
"GoogleSecuritySafebrowsingV4ThreatListDescriptor"
(\ o ->
GoogleSecuritySafebrowsingV4ThreatListDescriptor' <$>
(o .:? "threatEntryType") <*> (o .:? "threatType")
<*> (o .:? "platformType"))
instance ToJSON
GoogleSecuritySafebrowsingV4ThreatListDescriptor
where
toJSON
GoogleSecuritySafebrowsingV4ThreatListDescriptor'{..}
= object
(catMaybes
[("threatEntryType" .=) <$> _gssvtldThreatEntryType,
("threatType" .=) <$> _gssvtldThreatType,
("platformType" .=) <$> _gssvtldPlatformType])
-- | The client metadata associated with Safe Browsing API requests.
--
-- /See:/ 'googleSecuritySafebrowsingV4ClientInfo' smart constructor.
data GoogleSecuritySafebrowsingV4ClientInfo =
GoogleSecuritySafebrowsingV4ClientInfo'
{ _gssvciClientId :: !(Maybe Text)
, _gssvciClientVersion :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleSecuritySafebrowsingV4ClientInfo' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gssvciClientId'
--
-- * 'gssvciClientVersion'
googleSecuritySafebrowsingV4ClientInfo
:: GoogleSecuritySafebrowsingV4ClientInfo
googleSecuritySafebrowsingV4ClientInfo =
GoogleSecuritySafebrowsingV4ClientInfo'
{_gssvciClientId = Nothing, _gssvciClientVersion = Nothing}
-- | A client ID that (hopefully) uniquely identifies the client
-- implementation of the Safe Browsing API.
gssvciClientId :: Lens' GoogleSecuritySafebrowsingV4ClientInfo (Maybe Text)
gssvciClientId
= lens _gssvciClientId
(\ s a -> s{_gssvciClientId = a})
-- | The version of the client implementation.
gssvciClientVersion :: Lens' GoogleSecuritySafebrowsingV4ClientInfo (Maybe Text)
gssvciClientVersion
= lens _gssvciClientVersion
(\ s a -> s{_gssvciClientVersion = a})
instance FromJSON
GoogleSecuritySafebrowsingV4ClientInfo
where
parseJSON
= withObject "GoogleSecuritySafebrowsingV4ClientInfo"
(\ o ->
GoogleSecuritySafebrowsingV4ClientInfo' <$>
(o .:? "clientId") <*> (o .:? "clientVersion"))
instance ToJSON
GoogleSecuritySafebrowsingV4ClientInfo
where
toJSON GoogleSecuritySafebrowsingV4ClientInfo'{..}
= object
(catMaybes
[("clientId" .=) <$> _gssvciClientId,
("clientVersion" .=) <$> _gssvciClientVersion])
-- | A generic empty message that you can re-use to avoid defining duplicated
-- empty messages in your APIs. A typical example is to use it as the
-- request or the response type of an API method. For instance: service Foo
-- { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The
-- JSON representation for \`Empty\` is empty JSON object \`{}\`.
--
-- /See:/ 'googleProtobufEmpty' smart constructor.
data GoogleProtobufEmpty =
GoogleProtobufEmpty'
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleProtobufEmpty' with the minimum fields required to make a request.
--
googleProtobufEmpty
:: GoogleProtobufEmpty
googleProtobufEmpty = GoogleProtobufEmpty'
instance FromJSON GoogleProtobufEmpty where
parseJSON
= withObject "GoogleProtobufEmpty"
(\ o -> pure GoogleProtobufEmpty')
instance ToJSON GoogleProtobufEmpty where
toJSON = const emptyObject
-- | Details about the user that encountered the threat.
--
-- /See:/ 'googleSecuritySafebrowsingV4ThreatHitUserInfo' smart constructor.
data GoogleSecuritySafebrowsingV4ThreatHitUserInfo =
GoogleSecuritySafebrowsingV4ThreatHitUserInfo'
{ _gssvthuiRegionCode :: !(Maybe Text)
, _gssvthuiUserId :: !(Maybe Bytes)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleSecuritySafebrowsingV4ThreatHitUserInfo' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gssvthuiRegionCode'
--
-- * 'gssvthuiUserId'
googleSecuritySafebrowsingV4ThreatHitUserInfo
:: GoogleSecuritySafebrowsingV4ThreatHitUserInfo
googleSecuritySafebrowsingV4ThreatHitUserInfo =
GoogleSecuritySafebrowsingV4ThreatHitUserInfo'
{_gssvthuiRegionCode = Nothing, _gssvthuiUserId = Nothing}
-- | The UN M.49 region code associated with the user\'s location.
gssvthuiRegionCode :: Lens' GoogleSecuritySafebrowsingV4ThreatHitUserInfo (Maybe Text)
gssvthuiRegionCode
= lens _gssvthuiRegionCode
(\ s a -> s{_gssvthuiRegionCode = a})
-- | Unique user identifier defined by the client.
gssvthuiUserId :: Lens' GoogleSecuritySafebrowsingV4ThreatHitUserInfo (Maybe ByteString)
gssvthuiUserId
= lens _gssvthuiUserId
(\ s a -> s{_gssvthuiUserId = a})
. mapping _Bytes
instance FromJSON
GoogleSecuritySafebrowsingV4ThreatHitUserInfo
where
parseJSON
= withObject
"GoogleSecuritySafebrowsingV4ThreatHitUserInfo"
(\ o ->
GoogleSecuritySafebrowsingV4ThreatHitUserInfo' <$>
(o .:? "regionCode") <*> (o .:? "userId"))
instance ToJSON
GoogleSecuritySafebrowsingV4ThreatHitUserInfo
where
toJSON
GoogleSecuritySafebrowsingV4ThreatHitUserInfo'{..}
= object
(catMaybes
[("regionCode" .=) <$> _gssvthuiRegionCode,
("userId" .=) <$> _gssvthuiUserId])
-- | An update to an individual list.
--
-- /See:/ 'googleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponse' smart constructor.
data GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponse =
GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponse'
{ _gssvftlurlurAdditions :: !(Maybe [GoogleSecuritySafebrowsingV4ThreatEntrySet])
, _gssvftlurlurThreatEntryType :: !(Maybe GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponseThreatEntryType)
, _gssvftlurlurChecksum :: !(Maybe GoogleSecuritySafebrowsingV4Checksum)
, _gssvftlurlurThreatType :: !(Maybe GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponseThreatType)
, _gssvftlurlurPlatformType :: !(Maybe GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponsePlatformType)
, _gssvftlurlurNewClientState :: !(Maybe Bytes)
, _gssvftlurlurRemovals :: !(Maybe [GoogleSecuritySafebrowsingV4ThreatEntrySet])
, _gssvftlurlurResponseType :: !(Maybe GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponseResponseType)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gssvftlurlurAdditions'
--
-- * 'gssvftlurlurThreatEntryType'
--
-- * 'gssvftlurlurChecksum'
--
-- * 'gssvftlurlurThreatType'
--
-- * 'gssvftlurlurPlatformType'
--
-- * 'gssvftlurlurNewClientState'
--
-- * 'gssvftlurlurRemovals'
--
-- * 'gssvftlurlurResponseType'
googleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponse
:: GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponse
googleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponse =
GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponse'
{ _gssvftlurlurAdditions = Nothing
, _gssvftlurlurThreatEntryType = Nothing
, _gssvftlurlurChecksum = Nothing
, _gssvftlurlurThreatType = Nothing
, _gssvftlurlurPlatformType = Nothing
, _gssvftlurlurNewClientState = Nothing
, _gssvftlurlurRemovals = Nothing
, _gssvftlurlurResponseType = Nothing
}
-- | A set of entries to add to a local threat type\'s list. Repeated to
-- allow for a combination of compressed and raw data to be sent in a
-- single response.
gssvftlurlurAdditions :: Lens' GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponse [GoogleSecuritySafebrowsingV4ThreatEntrySet]
gssvftlurlurAdditions
= lens _gssvftlurlurAdditions
(\ s a -> s{_gssvftlurlurAdditions = a})
. _Default
. _Coerce
-- | The format of the threats.
gssvftlurlurThreatEntryType :: Lens' GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponse (Maybe GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponseThreatEntryType)
gssvftlurlurThreatEntryType
= lens _gssvftlurlurThreatEntryType
(\ s a -> s{_gssvftlurlurThreatEntryType = a})
-- | The expected SHA256 hash of the client state; that is, of the sorted
-- list of all hashes present in the database after applying the provided
-- update. If the client state doesn\'t match the expected state, the
-- client must disregard this update and retry later.
gssvftlurlurChecksum :: Lens' GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponse (Maybe GoogleSecuritySafebrowsingV4Checksum)
gssvftlurlurChecksum
= lens _gssvftlurlurChecksum
(\ s a -> s{_gssvftlurlurChecksum = a})
-- | The threat type for which data is returned.
gssvftlurlurThreatType :: Lens' GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponse (Maybe GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponseThreatType)
gssvftlurlurThreatType
= lens _gssvftlurlurThreatType
(\ s a -> s{_gssvftlurlurThreatType = a})
-- | The platform type for which data is returned.
gssvftlurlurPlatformType :: Lens' GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponse (Maybe GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponsePlatformType)
gssvftlurlurPlatformType
= lens _gssvftlurlurPlatformType
(\ s a -> s{_gssvftlurlurPlatformType = a})
-- | The new client state, in encrypted format. Opaque to clients.
gssvftlurlurNewClientState :: Lens' GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponse (Maybe ByteString)
gssvftlurlurNewClientState
= lens _gssvftlurlurNewClientState
(\ s a -> s{_gssvftlurlurNewClientState = a})
. mapping _Bytes
-- | A set of entries to remove from a local threat type\'s list. In
-- practice, this field is empty or contains exactly one ThreatEntrySet.
gssvftlurlurRemovals :: Lens' GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponse [GoogleSecuritySafebrowsingV4ThreatEntrySet]
gssvftlurlurRemovals
= lens _gssvftlurlurRemovals
(\ s a -> s{_gssvftlurlurRemovals = a})
. _Default
. _Coerce
-- | The type of response. This may indicate that an action is required by
-- the client when the response is received.
gssvftlurlurResponseType :: Lens' GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponse (Maybe GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponseResponseType)
gssvftlurlurResponseType
= lens _gssvftlurlurResponseType
(\ s a -> s{_gssvftlurlurResponseType = a})
instance FromJSON
GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponse
where
parseJSON
= withObject
"GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponse"
(\ o ->
GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponse'
<$>
(o .:? "additions" .!= mempty) <*>
(o .:? "threatEntryType")
<*> (o .:? "checksum")
<*> (o .:? "threatType")
<*> (o .:? "platformType")
<*> (o .:? "newClientState")
<*> (o .:? "removals" .!= mempty)
<*> (o .:? "responseType"))
instance ToJSON
GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponse
where
toJSON
GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponse'{..}
= object
(catMaybes
[("additions" .=) <$> _gssvftlurlurAdditions,
("threatEntryType" .=) <$>
_gssvftlurlurThreatEntryType,
("checksum" .=) <$> _gssvftlurlurChecksum,
("threatType" .=) <$> _gssvftlurlurThreatType,
("platformType" .=) <$> _gssvftlurlurPlatformType,
("newClientState" .=) <$>
_gssvftlurlurNewClientState,
("removals" .=) <$> _gssvftlurlurRemovals,
("responseType" .=) <$> _gssvftlurlurResponseType])
-- | A single list update request.
--
-- /See:/ 'googleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequest' smart constructor.
data GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequest =
GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequest'
{ _gState :: !(Maybe Bytes)
, _gThreatEntryType :: !(Maybe GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequestThreatEntryType)
, _gConstraints :: !(Maybe GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequestConstraints)
, _gThreatType :: !(Maybe GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequestThreatType)
, _gPlatformType :: !(Maybe GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequestPlatformType)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gState'
--
-- * 'gThreatEntryType'
--
-- * 'gConstraints'
--
-- * 'gThreatType'
--
-- * 'gPlatformType'
googleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequest
:: GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequest
googleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequest =
GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequest'
{ _gState = Nothing
, _gThreatEntryType = Nothing
, _gConstraints = Nothing
, _gThreatType = Nothing
, _gPlatformType = Nothing
}
-- | The current state of the client for the requested list (the encrypted
-- client state that was received from the last successful list update).
gState :: Lens' GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequest (Maybe ByteString)
gState
= lens _gState (\ s a -> s{_gState = a}) .
mapping _Bytes
-- | The types of entries present in the list.
gThreatEntryType :: Lens' GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequest (Maybe GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequestThreatEntryType)
gThreatEntryType
= lens _gThreatEntryType
(\ s a -> s{_gThreatEntryType = a})
-- | The constraints associated with this request.
gConstraints :: Lens' GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequest (Maybe GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequestConstraints)
gConstraints
= lens _gConstraints (\ s a -> s{_gConstraints = a})
-- | The type of threat posed by entries present in the list.
gThreatType :: Lens' GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequest (Maybe GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequestThreatType)
gThreatType
= lens _gThreatType (\ s a -> s{_gThreatType = a})
-- | The type of platform at risk by entries present in the list.
gPlatformType :: Lens' GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequest (Maybe GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequestPlatformType)
gPlatformType
= lens _gPlatformType
(\ s a -> s{_gPlatformType = a})
instance FromJSON
GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequest
where
parseJSON
= withObject
"GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequest"
(\ o ->
GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequest'
<$>
(o .:? "state") <*> (o .:? "threatEntryType") <*>
(o .:? "constraints")
<*> (o .:? "threatType")
<*> (o .:? "platformType"))
instance ToJSON
GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequest
where
toJSON
GoogleSecuritySafebrowsingV4FetchThreatListUpdatesRequestListUpdateRequest'{..}
= object
(catMaybes
[("state" .=) <$> _gState,
("threatEntryType" .=) <$> _gThreatEntryType,
("constraints" .=) <$> _gConstraints,
("threatType" .=) <$> _gThreatType,
("platformType" .=) <$> _gPlatformType])
-- | The information regarding one or more threats that a client submits when
-- checking for matches in threat lists.
--
-- /See:/ 'googleSecuritySafebrowsingV4ThreatInfo' smart constructor.
data GoogleSecuritySafebrowsingV4ThreatInfo =
GoogleSecuritySafebrowsingV4ThreatInfo'
{ _gssvtiThreatEntries :: !(Maybe [GoogleSecuritySafebrowsingV4ThreatEntry])
, _gssvtiThreatTypes :: !(Maybe [GoogleSecuritySafebrowsingV4ThreatInfoThreatTypesItem])
, _gssvtiPlatformTypes :: !(Maybe [GoogleSecuritySafebrowsingV4ThreatInfoPlatformTypesItem])
, _gssvtiThreatEntryTypes :: !(Maybe [GoogleSecuritySafebrowsingV4ThreatInfoThreatEntryTypesItem])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleSecuritySafebrowsingV4ThreatInfo' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gssvtiThreatEntries'
--
-- * 'gssvtiThreatTypes'
--
-- * 'gssvtiPlatformTypes'
--
-- * 'gssvtiThreatEntryTypes'
googleSecuritySafebrowsingV4ThreatInfo
:: GoogleSecuritySafebrowsingV4ThreatInfo
googleSecuritySafebrowsingV4ThreatInfo =
GoogleSecuritySafebrowsingV4ThreatInfo'
{ _gssvtiThreatEntries = Nothing
, _gssvtiThreatTypes = Nothing
, _gssvtiPlatformTypes = Nothing
, _gssvtiThreatEntryTypes = Nothing
}
-- | The threat entries to be checked.
gssvtiThreatEntries :: Lens' GoogleSecuritySafebrowsingV4ThreatInfo [GoogleSecuritySafebrowsingV4ThreatEntry]
gssvtiThreatEntries
= lens _gssvtiThreatEntries
(\ s a -> s{_gssvtiThreatEntries = a})
. _Default
. _Coerce
-- | The threat types to be checked.
gssvtiThreatTypes :: Lens' GoogleSecuritySafebrowsingV4ThreatInfo [GoogleSecuritySafebrowsingV4ThreatInfoThreatTypesItem]
gssvtiThreatTypes
= lens _gssvtiThreatTypes
(\ s a -> s{_gssvtiThreatTypes = a})
. _Default
. _Coerce
-- | The platform types to be checked.
gssvtiPlatformTypes :: Lens' GoogleSecuritySafebrowsingV4ThreatInfo [GoogleSecuritySafebrowsingV4ThreatInfoPlatformTypesItem]
gssvtiPlatformTypes
= lens _gssvtiPlatformTypes
(\ s a -> s{_gssvtiPlatformTypes = a})
. _Default
. _Coerce
-- | The entry types to be checked.
gssvtiThreatEntryTypes :: Lens' GoogleSecuritySafebrowsingV4ThreatInfo [GoogleSecuritySafebrowsingV4ThreatInfoThreatEntryTypesItem]
gssvtiThreatEntryTypes
= lens _gssvtiThreatEntryTypes
(\ s a -> s{_gssvtiThreatEntryTypes = a})
. _Default
. _Coerce
instance FromJSON
GoogleSecuritySafebrowsingV4ThreatInfo
where
parseJSON
= withObject "GoogleSecuritySafebrowsingV4ThreatInfo"
(\ o ->
GoogleSecuritySafebrowsingV4ThreatInfo' <$>
(o .:? "threatEntries" .!= mempty) <*>
(o .:? "threatTypes" .!= mempty)
<*> (o .:? "platformTypes" .!= mempty)
<*> (o .:? "threatEntryTypes" .!= mempty))
instance ToJSON
GoogleSecuritySafebrowsingV4ThreatInfo
where
toJSON GoogleSecuritySafebrowsingV4ThreatInfo'{..}
= object
(catMaybes
[("threatEntries" .=) <$> _gssvtiThreatEntries,
("threatTypes" .=) <$> _gssvtiThreatTypes,
("platformTypes" .=) <$> _gssvtiPlatformTypes,
("threatEntryTypes" .=) <$> _gssvtiThreatEntryTypes])
-- | A single resource related to a threat hit.
--
-- /See:/ 'googleSecuritySafebrowsingV4ThreatHitThreatSource' smart constructor.
data GoogleSecuritySafebrowsingV4ThreatHitThreatSource =
GoogleSecuritySafebrowsingV4ThreatHitThreatSource'
{ _gssvthtsRemoteIP :: !(Maybe Text)
, _gssvthtsURL :: !(Maybe Text)
, _gssvthtsReferrer :: !(Maybe Text)
, _gssvthtsType :: !(Maybe GoogleSecuritySafebrowsingV4ThreatHitThreatSourceType)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleSecuritySafebrowsingV4ThreatHitThreatSource' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gssvthtsRemoteIP'
--
-- * 'gssvthtsURL'
--
-- * 'gssvthtsReferrer'
--
-- * 'gssvthtsType'
googleSecuritySafebrowsingV4ThreatHitThreatSource
:: GoogleSecuritySafebrowsingV4ThreatHitThreatSource
googleSecuritySafebrowsingV4ThreatHitThreatSource =
GoogleSecuritySafebrowsingV4ThreatHitThreatSource'
{ _gssvthtsRemoteIP = Nothing
, _gssvthtsURL = Nothing
, _gssvthtsReferrer = Nothing
, _gssvthtsType = Nothing
}
-- | The remote IP of the resource in ASCII format. Either IPv4 or IPv6.
gssvthtsRemoteIP :: Lens' GoogleSecuritySafebrowsingV4ThreatHitThreatSource (Maybe Text)
gssvthtsRemoteIP
= lens _gssvthtsRemoteIP
(\ s a -> s{_gssvthtsRemoteIP = a})
-- | The URL of the resource.
gssvthtsURL :: Lens' GoogleSecuritySafebrowsingV4ThreatHitThreatSource (Maybe Text)
gssvthtsURL
= lens _gssvthtsURL (\ s a -> s{_gssvthtsURL = a})
-- | Referrer of the resource. Only set if the referrer is available.
gssvthtsReferrer :: Lens' GoogleSecuritySafebrowsingV4ThreatHitThreatSource (Maybe Text)
gssvthtsReferrer
= lens _gssvthtsReferrer
(\ s a -> s{_gssvthtsReferrer = a})
-- | The type of source reported.
gssvthtsType :: Lens' GoogleSecuritySafebrowsingV4ThreatHitThreatSource (Maybe GoogleSecuritySafebrowsingV4ThreatHitThreatSourceType)
gssvthtsType
= lens _gssvthtsType (\ s a -> s{_gssvthtsType = a})
instance FromJSON
GoogleSecuritySafebrowsingV4ThreatHitThreatSource
where
parseJSON
= withObject
"GoogleSecuritySafebrowsingV4ThreatHitThreatSource"
(\ o ->
GoogleSecuritySafebrowsingV4ThreatHitThreatSource'
<$>
(o .:? "remoteIp") <*> (o .:? "url") <*>
(o .:? "referrer")
<*> (o .:? "type"))
instance ToJSON
GoogleSecuritySafebrowsingV4ThreatHitThreatSource
where
toJSON
GoogleSecuritySafebrowsingV4ThreatHitThreatSource'{..}
= object
(catMaybes
[("remoteIp" .=) <$> _gssvthtsRemoteIP,
("url" .=) <$> _gssvthtsURL,
("referrer" .=) <$> _gssvthtsReferrer,
("type" .=) <$> _gssvthtsType])
-- | The uncompressed threat entries in hash format of a particular prefix
-- length. Hashes can be anywhere from 4 to 32 bytes in size. A large
-- majority are 4 bytes, but some hashes are lengthened if they collide
-- with the hash of a popular URL. Used for sending ThreatEntrySet to
-- clients that do not support compression, or when sending non-4-byte
-- hashes to clients that do support compression.
--
-- /See:/ 'googleSecuritySafebrowsingV4RawHashes' smart constructor.
data GoogleSecuritySafebrowsingV4RawHashes =
GoogleSecuritySafebrowsingV4RawHashes'
{ _gssvrhPrefixSize :: !(Maybe (Textual Int32))
, _gssvrhRawHashes :: !(Maybe Bytes)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleSecuritySafebrowsingV4RawHashes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gssvrhPrefixSize'
--
-- * 'gssvrhRawHashes'
googleSecuritySafebrowsingV4RawHashes
:: GoogleSecuritySafebrowsingV4RawHashes
googleSecuritySafebrowsingV4RawHashes =
GoogleSecuritySafebrowsingV4RawHashes'
{_gssvrhPrefixSize = Nothing, _gssvrhRawHashes = Nothing}
-- | The number of bytes for each prefix encoded below. This field can be
-- anywhere from 4 (shortest prefix) to 32 (full SHA256 hash).
gssvrhPrefixSize :: Lens' GoogleSecuritySafebrowsingV4RawHashes (Maybe Int32)
gssvrhPrefixSize
= lens _gssvrhPrefixSize
(\ s a -> s{_gssvrhPrefixSize = a})
. mapping _Coerce
-- | The hashes, in binary format, concatenated into one long string. Hashes
-- are sorted in lexicographic order. For JSON API users, hashes are
-- base64-encoded.
gssvrhRawHashes :: Lens' GoogleSecuritySafebrowsingV4RawHashes (Maybe ByteString)
gssvrhRawHashes
= lens _gssvrhRawHashes
(\ s a -> s{_gssvrhRawHashes = a})
. mapping _Bytes
instance FromJSON
GoogleSecuritySafebrowsingV4RawHashes
where
parseJSON
= withObject "GoogleSecuritySafebrowsingV4RawHashes"
(\ o ->
GoogleSecuritySafebrowsingV4RawHashes' <$>
(o .:? "prefixSize") <*> (o .:? "rawHashes"))
instance ToJSON GoogleSecuritySafebrowsingV4RawHashes
where
toJSON GoogleSecuritySafebrowsingV4RawHashes'{..}
= object
(catMaybes
[("prefixSize" .=) <$> _gssvrhPrefixSize,
("rawHashes" .=) <$> _gssvrhRawHashes])
-- | The expected state of a client\'s local database.
--
-- /See:/ 'googleSecuritySafebrowsingV4Checksum' smart constructor.
newtype GoogleSecuritySafebrowsingV4Checksum =
GoogleSecuritySafebrowsingV4Checksum'
{ _gssvcSha256 :: Maybe Bytes
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleSecuritySafebrowsingV4Checksum' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gssvcSha256'
googleSecuritySafebrowsingV4Checksum
:: GoogleSecuritySafebrowsingV4Checksum
googleSecuritySafebrowsingV4Checksum =
GoogleSecuritySafebrowsingV4Checksum' {_gssvcSha256 = Nothing}
-- | The SHA256 hash of the client state; that is, of the sorted list of all
-- hashes present in the database.
gssvcSha256 :: Lens' GoogleSecuritySafebrowsingV4Checksum (Maybe ByteString)
gssvcSha256
= lens _gssvcSha256 (\ s a -> s{_gssvcSha256 = a}) .
mapping _Bytes
instance FromJSON
GoogleSecuritySafebrowsingV4Checksum
where
parseJSON
= withObject "GoogleSecuritySafebrowsingV4Checksum"
(\ o ->
GoogleSecuritySafebrowsingV4Checksum' <$>
(o .:? "sha256"))
instance ToJSON GoogleSecuritySafebrowsingV4Checksum
where
toJSON GoogleSecuritySafebrowsingV4Checksum'{..}
= object (catMaybes [("sha256" .=) <$> _gssvcSha256])
-- | A match when checking a threat entry in the Safe Browsing threat lists.
--
-- /See:/ 'googleSecuritySafebrowsingV4ThreatMatch' smart constructor.
data GoogleSecuritySafebrowsingV4ThreatMatch =
GoogleSecuritySafebrowsingV4ThreatMatch'
{ _gssvtmThreatEntryMetadata :: !(Maybe GoogleSecuritySafebrowsingV4ThreatEntryMetadata)
, _gssvtmThreatEntryType :: !(Maybe GoogleSecuritySafebrowsingV4ThreatMatchThreatEntryType)
, _gssvtmThreatType :: !(Maybe GoogleSecuritySafebrowsingV4ThreatMatchThreatType)
, _gssvtmPlatformType :: !(Maybe GoogleSecuritySafebrowsingV4ThreatMatchPlatformType)
, _gssvtmCacheDuration :: !(Maybe GDuration)
, _gssvtmThreat :: !(Maybe GoogleSecuritySafebrowsingV4ThreatEntry)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleSecuritySafebrowsingV4ThreatMatch' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gssvtmThreatEntryMetadata'
--
-- * 'gssvtmThreatEntryType'
--
-- * 'gssvtmThreatType'
--
-- * 'gssvtmPlatformType'
--
-- * 'gssvtmCacheDuration'
--
-- * 'gssvtmThreat'
googleSecuritySafebrowsingV4ThreatMatch
:: GoogleSecuritySafebrowsingV4ThreatMatch
googleSecuritySafebrowsingV4ThreatMatch =
GoogleSecuritySafebrowsingV4ThreatMatch'
{ _gssvtmThreatEntryMetadata = Nothing
, _gssvtmThreatEntryType = Nothing
, _gssvtmThreatType = Nothing
, _gssvtmPlatformType = Nothing
, _gssvtmCacheDuration = Nothing
, _gssvtmThreat = Nothing
}
-- | Optional metadata associated with this threat.
gssvtmThreatEntryMetadata :: Lens' GoogleSecuritySafebrowsingV4ThreatMatch (Maybe GoogleSecuritySafebrowsingV4ThreatEntryMetadata)
gssvtmThreatEntryMetadata
= lens _gssvtmThreatEntryMetadata
(\ s a -> s{_gssvtmThreatEntryMetadata = a})
-- | The threat entry type matching this threat.
gssvtmThreatEntryType :: Lens' GoogleSecuritySafebrowsingV4ThreatMatch (Maybe GoogleSecuritySafebrowsingV4ThreatMatchThreatEntryType)
gssvtmThreatEntryType
= lens _gssvtmThreatEntryType
(\ s a -> s{_gssvtmThreatEntryType = a})
-- | The threat type matching this threat.
gssvtmThreatType :: Lens' GoogleSecuritySafebrowsingV4ThreatMatch (Maybe GoogleSecuritySafebrowsingV4ThreatMatchThreatType)
gssvtmThreatType
= lens _gssvtmThreatType
(\ s a -> s{_gssvtmThreatType = a})
-- | The platform type matching this threat.
gssvtmPlatformType :: Lens' GoogleSecuritySafebrowsingV4ThreatMatch (Maybe GoogleSecuritySafebrowsingV4ThreatMatchPlatformType)
gssvtmPlatformType
= lens _gssvtmPlatformType
(\ s a -> s{_gssvtmPlatformType = a})
-- | The cache lifetime for the returned match. Clients must not cache this
-- response for more than this duration to avoid false positives.
gssvtmCacheDuration :: Lens' GoogleSecuritySafebrowsingV4ThreatMatch (Maybe Scientific)
gssvtmCacheDuration
= lens _gssvtmCacheDuration
(\ s a -> s{_gssvtmCacheDuration = a})
. mapping _GDuration
-- | The threat matching this threat.
gssvtmThreat :: Lens' GoogleSecuritySafebrowsingV4ThreatMatch (Maybe GoogleSecuritySafebrowsingV4ThreatEntry)
gssvtmThreat
= lens _gssvtmThreat (\ s a -> s{_gssvtmThreat = a})
instance FromJSON
GoogleSecuritySafebrowsingV4ThreatMatch
where
parseJSON
= withObject
"GoogleSecuritySafebrowsingV4ThreatMatch"
(\ o ->
GoogleSecuritySafebrowsingV4ThreatMatch' <$>
(o .:? "threatEntryMetadata") <*>
(o .:? "threatEntryType")
<*> (o .:? "threatType")
<*> (o .:? "platformType")
<*> (o .:? "cacheDuration")
<*> (o .:? "threat"))
instance ToJSON
GoogleSecuritySafebrowsingV4ThreatMatch
where
toJSON GoogleSecuritySafebrowsingV4ThreatMatch'{..}
= object
(catMaybes
[("threatEntryMetadata" .=) <$>
_gssvtmThreatEntryMetadata,
("threatEntryType" .=) <$> _gssvtmThreatEntryType,
("threatType" .=) <$> _gssvtmThreatType,
("platformType" .=) <$> _gssvtmPlatformType,
("cacheDuration" .=) <$> _gssvtmCacheDuration,
("threat" .=) <$> _gssvtmThreat])
-- | An individual threat; for example, a malicious URL or its hash
-- representation. Only one of these fields should be set.
--
-- /See:/ 'googleSecuritySafebrowsingV4ThreatEntry' smart constructor.
data GoogleSecuritySafebrowsingV4ThreatEntry =
GoogleSecuritySafebrowsingV4ThreatEntry'
{ _gssvteHash :: !(Maybe Bytes)
, _gssvteURL :: !(Maybe Text)
, _gssvteDigest :: !(Maybe Bytes)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleSecuritySafebrowsingV4ThreatEntry' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gssvteHash'
--
-- * 'gssvteURL'
--
-- * 'gssvteDigest'
googleSecuritySafebrowsingV4ThreatEntry
:: GoogleSecuritySafebrowsingV4ThreatEntry
googleSecuritySafebrowsingV4ThreatEntry =
GoogleSecuritySafebrowsingV4ThreatEntry'
{_gssvteHash = Nothing, _gssvteURL = Nothing, _gssvteDigest = Nothing}
-- | A hash prefix, consisting of the most significant 4-32 bytes of a SHA256
-- hash. This field is in binary format. For JSON requests, hashes are
-- base64-encoded.
gssvteHash :: Lens' GoogleSecuritySafebrowsingV4ThreatEntry (Maybe ByteString)
gssvteHash
= lens _gssvteHash (\ s a -> s{_gssvteHash = a}) .
mapping _Bytes
-- | A URL.
gssvteURL :: Lens' GoogleSecuritySafebrowsingV4ThreatEntry (Maybe Text)
gssvteURL
= lens _gssvteURL (\ s a -> s{_gssvteURL = a})
-- | The digest of an executable in SHA256 format. The API supports both
-- binary and hex digests. For JSON requests, digests are base64-encoded.
gssvteDigest :: Lens' GoogleSecuritySafebrowsingV4ThreatEntry (Maybe ByteString)
gssvteDigest
= lens _gssvteDigest (\ s a -> s{_gssvteDigest = a})
. mapping _Bytes
instance FromJSON
GoogleSecuritySafebrowsingV4ThreatEntry
where
parseJSON
= withObject
"GoogleSecuritySafebrowsingV4ThreatEntry"
(\ o ->
GoogleSecuritySafebrowsingV4ThreatEntry' <$>
(o .:? "hash") <*> (o .:? "url") <*>
(o .:? "digest"))
instance ToJSON
GoogleSecuritySafebrowsingV4ThreatEntry
where
toJSON GoogleSecuritySafebrowsingV4ThreatEntry'{..}
= object
(catMaybes
[("hash" .=) <$> _gssvteHash,
("url" .=) <$> _gssvteURL,
("digest" .=) <$> _gssvteDigest])
--
-- /See:/ 'googleSecuritySafebrowsingV4FindFullHashesResponse' smart constructor.
data GoogleSecuritySafebrowsingV4FindFullHashesResponse =
GoogleSecuritySafebrowsingV4FindFullHashesResponse'
{ _gssvffhrMatches :: !(Maybe [GoogleSecuritySafebrowsingV4ThreatMatch])
, _gssvffhrNegativeCacheDuration :: !(Maybe GDuration)
, _gssvffhrMinimumWaitDuration :: !(Maybe GDuration)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleSecuritySafebrowsingV4FindFullHashesResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gssvffhrMatches'
--
-- * 'gssvffhrNegativeCacheDuration'
--
-- * 'gssvffhrMinimumWaitDuration'
googleSecuritySafebrowsingV4FindFullHashesResponse
:: GoogleSecuritySafebrowsingV4FindFullHashesResponse
googleSecuritySafebrowsingV4FindFullHashesResponse =
GoogleSecuritySafebrowsingV4FindFullHashesResponse'
{ _gssvffhrMatches = Nothing
, _gssvffhrNegativeCacheDuration = Nothing
, _gssvffhrMinimumWaitDuration = Nothing
}
-- | The full hashes that matched the requested prefixes.
gssvffhrMatches :: Lens' GoogleSecuritySafebrowsingV4FindFullHashesResponse [GoogleSecuritySafebrowsingV4ThreatMatch]
gssvffhrMatches
= lens _gssvffhrMatches
(\ s a -> s{_gssvffhrMatches = a})
. _Default
. _Coerce
-- | For requested entities that did not match the threat list, how long to
-- cache the response.
gssvffhrNegativeCacheDuration :: Lens' GoogleSecuritySafebrowsingV4FindFullHashesResponse (Maybe Scientific)
gssvffhrNegativeCacheDuration
= lens _gssvffhrNegativeCacheDuration
(\ s a -> s{_gssvffhrNegativeCacheDuration = a})
. mapping _GDuration
-- | The minimum duration the client must wait before issuing any find hashes
-- request. If this field is not set, clients can issue a request as soon
-- as they want.
gssvffhrMinimumWaitDuration :: Lens' GoogleSecuritySafebrowsingV4FindFullHashesResponse (Maybe Scientific)
gssvffhrMinimumWaitDuration
= lens _gssvffhrMinimumWaitDuration
(\ s a -> s{_gssvffhrMinimumWaitDuration = a})
. mapping _GDuration
instance FromJSON
GoogleSecuritySafebrowsingV4FindFullHashesResponse
where
parseJSON
= withObject
"GoogleSecuritySafebrowsingV4FindFullHashesResponse"
(\ o ->
GoogleSecuritySafebrowsingV4FindFullHashesResponse'
<$>
(o .:? "matches" .!= mempty) <*>
(o .:? "negativeCacheDuration")
<*> (o .:? "minimumWaitDuration"))
instance ToJSON
GoogleSecuritySafebrowsingV4FindFullHashesResponse
where
toJSON
GoogleSecuritySafebrowsingV4FindFullHashesResponse'{..}
= object
(catMaybes
[("matches" .=) <$> _gssvffhrMatches,
("negativeCacheDuration" .=) <$>
_gssvffhrNegativeCacheDuration,
("minimumWaitDuration" .=) <$>
_gssvffhrMinimumWaitDuration])
--
-- /See:/ 'googleSecuritySafebrowsingV4FetchThreatListUpdatesResponse' smart constructor.
data GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponse =
GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponse'
{ _gssvftlurListUpdateResponses :: !(Maybe [GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponse])
, _gssvftlurMinimumWaitDuration :: !(Maybe GDuration)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gssvftlurListUpdateResponses'
--
-- * 'gssvftlurMinimumWaitDuration'
googleSecuritySafebrowsingV4FetchThreatListUpdatesResponse
:: GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponse
googleSecuritySafebrowsingV4FetchThreatListUpdatesResponse =
GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponse'
{ _gssvftlurListUpdateResponses = Nothing
, _gssvftlurMinimumWaitDuration = Nothing
}
-- | The list updates requested by the clients. The number of responses here
-- may be less than the number of requests sent by clients. This is the
-- case, for example, if the server has no updates for a particular list.
gssvftlurListUpdateResponses :: Lens' GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponse [GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponseListUpdateResponse]
gssvftlurListUpdateResponses
= lens _gssvftlurListUpdateResponses
(\ s a -> s{_gssvftlurListUpdateResponses = a})
. _Default
. _Coerce
-- | The minimum duration the client must wait before issuing any update
-- request. If this field is not set clients may update as soon as they
-- want.
gssvftlurMinimumWaitDuration :: Lens' GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponse (Maybe Scientific)
gssvftlurMinimumWaitDuration
= lens _gssvftlurMinimumWaitDuration
(\ s a -> s{_gssvftlurMinimumWaitDuration = a})
. mapping _GDuration
instance FromJSON
GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponse
where
parseJSON
= withObject
"GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponse"
(\ o ->
GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponse'
<$>
(o .:? "listUpdateResponses" .!= mempty) <*>
(o .:? "minimumWaitDuration"))
instance ToJSON
GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponse
where
toJSON
GoogleSecuritySafebrowsingV4FetchThreatListUpdatesResponse'{..}
= object
(catMaybes
[("listUpdateResponses" .=) <$>
_gssvftlurListUpdateResponses,
("minimumWaitDuration" .=) <$>
_gssvftlurMinimumWaitDuration])
-- | A single metadata entry.
--
-- /See:/ 'googleSecuritySafebrowsingV4ThreatEntryMetadataMetadataEntry' smart constructor.
data GoogleSecuritySafebrowsingV4ThreatEntryMetadataMetadataEntry =
GoogleSecuritySafebrowsingV4ThreatEntryMetadataMetadataEntry'
{ _gssvtemmeValue :: !(Maybe Bytes)
, _gssvtemmeKey :: !(Maybe Bytes)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleSecuritySafebrowsingV4ThreatEntryMetadataMetadataEntry' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gssvtemmeValue'
--
-- * 'gssvtemmeKey'
googleSecuritySafebrowsingV4ThreatEntryMetadataMetadataEntry
:: GoogleSecuritySafebrowsingV4ThreatEntryMetadataMetadataEntry
googleSecuritySafebrowsingV4ThreatEntryMetadataMetadataEntry =
GoogleSecuritySafebrowsingV4ThreatEntryMetadataMetadataEntry'
{_gssvtemmeValue = Nothing, _gssvtemmeKey = Nothing}
-- | The metadata entry value. For JSON requests, the value is
-- base64-encoded.
gssvtemmeValue :: Lens' GoogleSecuritySafebrowsingV4ThreatEntryMetadataMetadataEntry (Maybe ByteString)
gssvtemmeValue
= lens _gssvtemmeValue
(\ s a -> s{_gssvtemmeValue = a})
. mapping _Bytes
-- | The metadata entry key. For JSON requests, the key is base64-encoded.
gssvtemmeKey :: Lens' GoogleSecuritySafebrowsingV4ThreatEntryMetadataMetadataEntry (Maybe ByteString)
gssvtemmeKey
= lens _gssvtemmeKey (\ s a -> s{_gssvtemmeKey = a})
. mapping _Bytes
instance FromJSON
GoogleSecuritySafebrowsingV4ThreatEntryMetadataMetadataEntry
where
parseJSON
= withObject
"GoogleSecuritySafebrowsingV4ThreatEntryMetadataMetadataEntry"
(\ o ->
GoogleSecuritySafebrowsingV4ThreatEntryMetadataMetadataEntry'
<$> (o .:? "value") <*> (o .:? "key"))
instance ToJSON
GoogleSecuritySafebrowsingV4ThreatEntryMetadataMetadataEntry
where
toJSON
GoogleSecuritySafebrowsingV4ThreatEntryMetadataMetadataEntry'{..}
= object
(catMaybes
[("value" .=) <$> _gssvtemmeValue,
("key" .=) <$> _gssvtemmeKey])
--
-- /See:/ 'googleSecuritySafebrowsingV4ListThreatListsResponse' smart constructor.
newtype GoogleSecuritySafebrowsingV4ListThreatListsResponse =
GoogleSecuritySafebrowsingV4ListThreatListsResponse'
{ _gssvltlrThreatLists :: Maybe [GoogleSecuritySafebrowsingV4ThreatListDescriptor]
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleSecuritySafebrowsingV4ListThreatListsResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gssvltlrThreatLists'
googleSecuritySafebrowsingV4ListThreatListsResponse
:: GoogleSecuritySafebrowsingV4ListThreatListsResponse
googleSecuritySafebrowsingV4ListThreatListsResponse =
GoogleSecuritySafebrowsingV4ListThreatListsResponse'
{_gssvltlrThreatLists = Nothing}
-- | The lists available for download by the client.
gssvltlrThreatLists :: Lens' GoogleSecuritySafebrowsingV4ListThreatListsResponse [GoogleSecuritySafebrowsingV4ThreatListDescriptor]
gssvltlrThreatLists
= lens _gssvltlrThreatLists
(\ s a -> s{_gssvltlrThreatLists = a})
. _Default
. _Coerce
instance FromJSON
GoogleSecuritySafebrowsingV4ListThreatListsResponse
where
parseJSON
= withObject
"GoogleSecuritySafebrowsingV4ListThreatListsResponse"
(\ o ->
GoogleSecuritySafebrowsingV4ListThreatListsResponse'
<$> (o .:? "threatLists" .!= mempty))
instance ToJSON
GoogleSecuritySafebrowsingV4ListThreatListsResponse
where
toJSON
GoogleSecuritySafebrowsingV4ListThreatListsResponse'{..}
= object
(catMaybes
[("threatLists" .=) <$> _gssvltlrThreatLists])
-- | The Rice-Golomb encoded data. Used for sending compressed 4-byte hashes
-- or compressed removal indices.
--
-- /See:/ 'googleSecuritySafebrowsingV4RiceDeltaEncoding' smart constructor.
data GoogleSecuritySafebrowsingV4RiceDeltaEncoding =
GoogleSecuritySafebrowsingV4RiceDeltaEncoding'
{ _gssvrdeFirstValue :: !(Maybe (Textual Int64))
, _gssvrdeRiceParameter :: !(Maybe (Textual Int32))
, _gssvrdeNumEntries :: !(Maybe (Textual Int32))
, _gssvrdeEncodedData :: !(Maybe Bytes)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleSecuritySafebrowsingV4RiceDeltaEncoding' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gssvrdeFirstValue'
--
-- * 'gssvrdeRiceParameter'
--
-- * 'gssvrdeNumEntries'
--
-- * 'gssvrdeEncodedData'
googleSecuritySafebrowsingV4RiceDeltaEncoding
:: GoogleSecuritySafebrowsingV4RiceDeltaEncoding
googleSecuritySafebrowsingV4RiceDeltaEncoding =
GoogleSecuritySafebrowsingV4RiceDeltaEncoding'
{ _gssvrdeFirstValue = Nothing
, _gssvrdeRiceParameter = Nothing
, _gssvrdeNumEntries = Nothing
, _gssvrdeEncodedData = Nothing
}
-- | The offset of the first entry in the encoded data, or, if only a single
-- integer was encoded, that single integer\'s value. If the field is empty
-- or missing, assume zero.
gssvrdeFirstValue :: Lens' GoogleSecuritySafebrowsingV4RiceDeltaEncoding (Maybe Int64)
gssvrdeFirstValue
= lens _gssvrdeFirstValue
(\ s a -> s{_gssvrdeFirstValue = a})
. mapping _Coerce
-- | The Golomb-Rice parameter, which is a number between 2 and 28. This
-- field is missing (that is, zero) if \`num_entries\` is zero.
gssvrdeRiceParameter :: Lens' GoogleSecuritySafebrowsingV4RiceDeltaEncoding (Maybe Int32)
gssvrdeRiceParameter
= lens _gssvrdeRiceParameter
(\ s a -> s{_gssvrdeRiceParameter = a})
. mapping _Coerce
-- | The number of entries that are delta encoded in the encoded data. If
-- only a single integer was encoded, this will be zero and the single
-- value will be stored in \`first_value\`.
gssvrdeNumEntries :: Lens' GoogleSecuritySafebrowsingV4RiceDeltaEncoding (Maybe Int32)
gssvrdeNumEntries
= lens _gssvrdeNumEntries
(\ s a -> s{_gssvrdeNumEntries = a})
. mapping _Coerce
-- | The encoded deltas that are encoded using the Golomb-Rice coder.
gssvrdeEncodedData :: Lens' GoogleSecuritySafebrowsingV4RiceDeltaEncoding (Maybe ByteString)
gssvrdeEncodedData
= lens _gssvrdeEncodedData
(\ s a -> s{_gssvrdeEncodedData = a})
. mapping _Bytes
instance FromJSON
GoogleSecuritySafebrowsingV4RiceDeltaEncoding
where
parseJSON
= withObject
"GoogleSecuritySafebrowsingV4RiceDeltaEncoding"
(\ o ->
GoogleSecuritySafebrowsingV4RiceDeltaEncoding' <$>
(o .:? "firstValue") <*> (o .:? "riceParameter") <*>
(o .:? "numEntries")
<*> (o .:? "encodedData"))
instance ToJSON
GoogleSecuritySafebrowsingV4RiceDeltaEncoding
where
toJSON
GoogleSecuritySafebrowsingV4RiceDeltaEncoding'{..}
= object
(catMaybes
[("firstValue" .=) <$> _gssvrdeFirstValue,
("riceParameter" .=) <$> _gssvrdeRiceParameter,
("numEntries" .=) <$> _gssvrdeNumEntries,
("encodedData" .=) <$> _gssvrdeEncodedData])
|
brendanhay/gogol
|
gogol-safebrowsing/gen/Network/Google/SafeBrowsing/Types/Product.hs
|
mpl-2.0
| 78,630 | 0 | 19 | 15,579 | 10,244 | 5,878 | 4,366 | 1,326 | 1 |
-- split "asdf" 2 = "as", "df"
split :: [a] -> Int -> ([a], [a])
split [] _ = ([], [])
split xs 0 = ([], xs)
split (x:xs) n =
let yy = split xs (n-1) in
([x] ++ fst yy, snd yy)
|
ekalosak/haskell-practice
|
pr17.hs
|
lgpl-3.0
| 190 | 0 | 11 | 57 | 129 | 70 | 59 | 6 | 1 |
import Ring_7
main = do print $ take 10 [Z 6, Z 8..]
print $ [Z 1, Z 3..Z 6]
print $ [Z 1, Z 1..Z 1]
|
bestian/haskell-sandbox
|
r7_test1.hs
|
unlicense
| 121 | 0 | 10 | 47 | 81 | 38 | 43 | 4 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
-- import Lib
-- main :: IO ()
-- main = someFunc
import Control.Applicative
import App
main :: IO ()
main = run
|
DominikDitoIvosevic/yafebe
|
back/app/Main.hs
|
apache-2.0
| 170 | 0 | 6 | 34 | 31 | 20 | 11 | 6 | 1 |
module Main where
import MonteCarloGui
main :: IO ()
main = monteCarloGui
|
alexandersgreen/alex-haskell
|
MonteCarloPi/Main.hs
|
apache-2.0
| 76 | 0 | 6 | 14 | 22 | 13 | 9 | 4 | 1 |
-- | The fully-qualified HaskellExpr representation of some functions from base.
module Data.HaskellExpr.Base where
import Data.HaskellExpr
eId :: HaskellExpr (a -> a)
eId = qualified "Prelude" "id"
eConst :: HaskellExpr (a -> b -> a)
eConst = qualified "Prelude" "const"
eFlip :: HaskellExpr ((a -> b -> c) -> b -> a -> c)
eFlip = qualified "Prelude" "flip"
eMap :: HaskellExpr ((a -> b) -> [a] -> [b])
eMap = qualified "Prelude" "map"
eHead :: HaskellExpr ([a] -> a)
eHead = qualified "Prelude" "head"
eComp :: HaskellExpr (b -> c) -> HaskellExpr (a -> b) -> HaskellExpr (a -> c)
eComp = qualifiedInfix "Prelude" "."
|
gelisam/hawk
|
src/Data/HaskellExpr/Base.hs
|
apache-2.0
| 627 | 0 | 10 | 114 | 234 | 125 | 109 | 14 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QStyleHintReturn.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:35
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Enums.Gui.QStyleHintReturn (
HintReturnType, eSH_Default, eSH_Mask, eSH_Variant
, QStyleHintReturnStyleOptionType
, QStyleHintReturnStyleOptionVersion
)
where
import Qtc.Classes.Base
import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr)
import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int)
import Qtc.Enums.Base
import Qtc.Enums.Classes.Core
data CHintReturnType a = CHintReturnType a
type HintReturnType = QEnum(CHintReturnType Int)
ieHintReturnType :: Int -> HintReturnType
ieHintReturnType x = QEnum (CHintReturnType x)
instance QEnumC (CHintReturnType Int) where
qEnum_toInt (QEnum (CHintReturnType x)) = x
qEnum_fromInt x = QEnum (CHintReturnType x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> HintReturnType -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
eSH_Default :: HintReturnType
eSH_Default
= ieHintReturnType $ 61440
eSH_Mask :: HintReturnType
eSH_Mask
= ieHintReturnType $ 61441
eSH_Variant :: HintReturnType
eSH_Variant
= ieHintReturnType $ 61442
data CQStyleHintReturnStyleOptionType a = CQStyleHintReturnStyleOptionType a
type QStyleHintReturnStyleOptionType = QEnum(CQStyleHintReturnStyleOptionType Int)
ieQStyleHintReturnStyleOptionType :: Int -> QStyleHintReturnStyleOptionType
ieQStyleHintReturnStyleOptionType x = QEnum (CQStyleHintReturnStyleOptionType x)
instance QEnumC (CQStyleHintReturnStyleOptionType Int) where
qEnum_toInt (QEnum (CQStyleHintReturnStyleOptionType x)) = x
qEnum_fromInt x = QEnum (CQStyleHintReturnStyleOptionType x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> QStyleHintReturnStyleOptionType -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
instance QeType QStyleHintReturnStyleOptionType where
eType
= ieQStyleHintReturnStyleOptionType $ 61440
data CQStyleHintReturnStyleOptionVersion a = CQStyleHintReturnStyleOptionVersion a
type QStyleHintReturnStyleOptionVersion = QEnum(CQStyleHintReturnStyleOptionVersion Int)
ieQStyleHintReturnStyleOptionVersion :: Int -> QStyleHintReturnStyleOptionVersion
ieQStyleHintReturnStyleOptionVersion x = QEnum (CQStyleHintReturnStyleOptionVersion x)
instance QEnumC (CQStyleHintReturnStyleOptionVersion Int) where
qEnum_toInt (QEnum (CQStyleHintReturnStyleOptionVersion x)) = x
qEnum_fromInt x = QEnum (CQStyleHintReturnStyleOptionVersion x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> QStyleHintReturnStyleOptionVersion -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
instance QeVersion QStyleHintReturnStyleOptionVersion where
eVersion
= ieQStyleHintReturnStyleOptionVersion $ 1
|
uduki/hsQt
|
Qtc/Enums/Gui/QStyleHintReturn.hs
|
bsd-2-clause
| 6,376 | 0 | 18 | 1,350 | 1,610 | 789 | 821 | 136 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Data.SBV.Compilers.C
-- Copyright : (c) Levent Erkok
-- License : BSD3
-- Maintainer : [email protected]
-- Stability : experimental
--
-- Compilation of symbolic programs to C
-----------------------------------------------------------------------------
{-# LANGUAGE PatternGuards #-}
module Data.SBV.Compilers.C(compileToC, compileToCLib, compileToC', compileToCLib') where
import Control.DeepSeq (rnf)
import Data.Char (isSpace)
import Data.List (nub, intercalate)
import Data.Maybe (isJust, isNothing, fromJust)
import qualified Data.Foldable as F (toList)
import qualified Data.Set as Set (member, toList)
import System.FilePath (takeBaseName, replaceExtension)
import System.Random
import Text.PrettyPrint.HughesPJ
import Data.SBV.BitVectors.Data
import Data.SBV.BitVectors.AlgReals
import Data.SBV.BitVectors.PrettyNum (shex, showCFloat, showCDouble)
import Data.SBV.Compilers.CodeGen
---------------------------------------------------------------------------
-- * API
---------------------------------------------------------------------------
-- | Given a symbolic computation, render it as an equivalent collection of files
-- that make up a C program:
--
-- * The first argument is the directory name under which the files will be saved. To save
-- files in the current directory pass @'Just' \".\"@. Use 'Nothing' for printing to stdout.
--
-- * The second argument is the name of the C function to generate.
--
-- * The final argument is the function to be compiled.
--
-- Compilation will also generate a @Makefile@, a header file, and a driver (test) program, etc.
compileToC :: Maybe FilePath -> String -> SBVCodeGen () -> IO ()
compileToC mbDirName nm f = compileToC' nm f >>= renderCgPgmBundle mbDirName
-- | Lower level version of 'compileToC', producing a 'CgPgmBundle'
compileToC' :: String -> SBVCodeGen () -> IO CgPgmBundle
compileToC' nm f = do rands <- randoms `fmap` newStdGen
codeGen SBVToC (defaultCgConfig { cgDriverVals = rands }) nm f
-- | Create code to generate a library archive (.a) from given symbolic functions. Useful when generating code
-- from multiple functions that work together as a library.
--
-- * The first argument is the directory name under which the files will be saved. To save
-- files in the current directory pass @'Just' \".\"@. Use 'Nothing' for printing to stdout.
--
-- * The second argument is the name of the archive to generate.
--
-- * The third argument is the list of functions to include, in the form of function-name/code pairs, similar
-- to the second and third arguments of 'compileToC', except in a list.
compileToCLib :: Maybe FilePath -> String -> [(String, SBVCodeGen ())] -> IO ()
compileToCLib mbDirName libName comps = compileToCLib' libName comps >>= renderCgPgmBundle mbDirName
-- | Lower level version of 'compileToCLib', producing a 'CgPgmBundle'
compileToCLib' :: String -> [(String, SBVCodeGen ())] -> IO CgPgmBundle
compileToCLib' libName comps = mergeToLib libName `fmap` mapM (uncurry compileToC') comps
---------------------------------------------------------------------------
-- * Implementation
---------------------------------------------------------------------------
-- token for the target language
data SBVToC = SBVToC
instance CgTarget SBVToC where
targetName _ = "C"
translate _ = cgen
-- Unexpected input, or things we will probably never support
die :: String -> a
die msg = error $ "SBV->C: Unexpected: " ++ msg
-- Unsupported features, or features TBD
tbd :: String -> a
tbd msg = error $ "SBV->C: Not yet supported: " ++ msg
cgen :: CgConfig -> String -> CgState -> Result -> CgPgmBundle
cgen cfg nm st sbvProg
-- we rnf the main pg and the sig to make sure any exceptions in type conversion pop-out early enough
-- this is purely cosmetic, of course..
= rnf (render sig) `seq` rnf (render (vcat body)) `seq` result
where result = CgPgmBundle bundleKind
$ filt [ ("Makefile", (CgMakefile flags, [genMake (cgGenDriver cfg) nm nmd flags]))
, (nm ++ ".h", (CgHeader [sig], [genHeader bundleKind nm [sig] extProtos]))
, (nmd ++ ".c", (CgDriver, genDriver cfg randVals nm ins outs mbRet))
, (nm ++ ".c", (CgSource, body))
]
body = genCProg cfg nm sig sbvProg ins outs mbRet extDecls
bundleKind = (cgInteger cfg, cgReal cfg)
randVals = cgDriverVals cfg
filt xs = [c | c@(_, (k, _)) <- xs, need k]
where need k | isCgDriver k = cgGenDriver cfg
| isCgMakefile k = cgGenMakefile cfg
| True = True
nmd = nm ++ "_driver"
sig = pprCFunHeader nm ins outs mbRet
ins = cgInputs st
outs = cgOutputs st
mbRet = case cgReturns st of
[] -> Nothing
[CgAtomic o] -> Just o
[CgArray _] -> tbd "Non-atomic return values"
_ -> tbd "Multiple return values"
extProtos = case cgPrototypes st of
[] -> empty
xs -> vcat $ text "/* User given prototypes: */" : map text xs
extDecls = case cgDecls st of
[] -> empty
xs -> vcat $ text "/* User given declarations: */" : map text xs ++ [text ""]
flags = cgLDFlags st
-- | Pretty print a functions type. If there is only one output, we compile it
-- as a function that returns that value. Otherwise, we compile it as a void function
-- that takes return values as pointers to be updated.
pprCFunHeader :: String -> [(String, CgVal)] -> [(String, CgVal)] -> Maybe SW -> Doc
pprCFunHeader fn ins outs mbRet = retType <+> text fn <> parens (fsep (punctuate comma (map mkParam ins ++ map mkPParam outs)))
where retType = case mbRet of
Nothing -> text "void"
Just sw -> pprCWord False sw
mkParam, mkPParam :: (String, CgVal) -> Doc
mkParam (n, CgAtomic sw) = pprCWord True sw <+> text n
mkParam (_, CgArray []) = die "mkParam: CgArray with no elements!"
mkParam (n, CgArray (sw:_)) = pprCWord True sw <+> text "*" <> text n
mkPParam (n, CgAtomic sw) = pprCWord False sw <+> text "*" <> text n
mkPParam (_, CgArray []) = die "mPkParam: CgArray with no elements!"
mkPParam (n, CgArray (sw:_)) = pprCWord False sw <+> text "*" <> text n
-- | Renders as "const SWord8 s0", etc. the first parameter is the width of the typefield
declSW :: Int -> SW -> Doc
declSW w sw = text "const" <+> pad (showCType sw) <+> text (show sw)
where pad s = text $ s ++ replicate (w - length s) ' '
-- | Renders as "s0", etc, or the corresponding constant
showSW :: CgConfig -> [(SW, CW)] -> SW -> Doc
showSW cfg consts sw
| sw == falseSW = text "false"
| sw == trueSW = text "true"
| Just cw <- sw `lookup` consts = mkConst cfg cw
| True = text $ show sw
-- | Words as it would map to a C word
pprCWord :: HasKind a => Bool -> a -> Doc
pprCWord cnst v = (if cnst then text "const" else empty) <+> text (showCType v)
showCType :: HasKind a => a -> String
showCType = show . kindOf
-- | The printf specifier for the type
specifier :: CgConfig -> SW -> Doc
specifier cfg sw = case kindOf sw of
KBounded b i -> spec (b, i)
KUnbounded -> spec (True, fromJust (cgInteger cfg))
KReal -> specF (fromJust (cgReal cfg))
KFloat -> specF CgFloat
KDouble -> specF CgDouble
KUninterpreted s -> die $ "uninterpreted sort: " ++ s
where spec :: (Bool, Int) -> Doc
spec (False, 1) = text "%d"
spec (False, 8) = text "%\"PRIu8\""
spec (True, 8) = text "%\"PRId8\""
spec (False, 16) = text "0x%04\"PRIx16\"U"
spec (True, 16) = text "%\"PRId16\""
spec (False, 32) = text "0x%08\"PRIx32\"UL"
spec (True, 32) = text "%\"PRId32\"L"
spec (False, 64) = text "0x%016\"PRIx64\"ULL"
spec (True, 64) = text "%\"PRId64\"LL"
spec (s, sz) = die $ "Format specifier at type " ++ (if s then "SInt" else "SWord") ++ show sz
specF :: CgSRealType -> Doc
specF CgFloat = text "%f"
specF CgDouble = text "%f"
specF CgLongDouble = text "%Lf"
-- | Make a constant value of the given type. We don't check for out of bounds here, as it should not be needed.
-- There are many options here, using binary, decimal, etc. We simply
-- 8-bit or less constants using decimal; otherwise we use hex.
-- Note that this automatically takes care of the boolean (1-bit) value problem, since it
-- shows the result as an integer, which is OK as far as C is concerned.
mkConst :: CgConfig -> CW -> Doc
mkConst cfg (CW KReal (CWAlgReal (AlgRational _ r))) = double (fromRational r :: Double) <> sRealSuffix (fromJust (cgReal cfg))
where sRealSuffix CgFloat = text "F"
sRealSuffix CgDouble = empty
sRealSuffix CgLongDouble = text "L"
mkConst cfg (CW KUnbounded (CWInteger i)) = showSizedConst i (True, fromJust (cgInteger cfg))
mkConst _ (CW (KBounded sg sz) (CWInteger i)) = showSizedConst i (sg, sz)
mkConst _ (CW KFloat (CWFloat f)) = text $ showCFloat f
mkConst _ (CW KDouble (CWDouble d)) = text $ showCDouble d
mkConst _ cw = die $ "mkConst: " ++ show cw
showSizedConst :: Integer -> (Bool, Int) -> Doc
showSizedConst i (False, 1) = text (if i == 0 then "false" else "true")
showSizedConst i (False, 8) = integer i
showSizedConst i (True, 8) = integer i
showSizedConst i t@(False, 16) = text (shex False True t i) <> text "U"
showSizedConst i t@(True, 16) = text (shex False True t i)
showSizedConst i t@(False, 32) = text (shex False True t i) <> text "UL"
showSizedConst i t@(True, 32) = text (shex False True t i) <> text "L"
showSizedConst i t@(False, 64) = text (shex False True t i) <> text "ULL"
showSizedConst i t@(True, 64) = text (shex False True t i) <> text "LL"
showSizedConst i (True, 1) = die $ "Signed 1-bit value " ++ show i
showSizedConst i (s, sz) = die $ "Constant " ++ show i ++ " at type " ++ (if s then "SInt" else "SWord") ++ show sz
-- | Generate a makefile. The first argument is True if we have a driver.
genMake :: Bool -> String -> String -> [String] -> Doc
genMake ifdr fn dn ldFlags = foldr1 ($$) [l | (True, l) <- lns]
where ifld = not (null ldFlags)
ld | ifld = text "${LDFLAGS}"
| True = empty
lns = [ (True, text "# Makefile for" <+> nm <> text ". Automatically generated by SBV. Do not edit!")
, (True, text "")
, (True, text "# include any user-defined .mk file in the current directory.")
, (True, text "-include *.mk")
, (True, text "")
, (True, text "CC=gcc")
, (True, text "CCFLAGS?=-Wall -O3 -DNDEBUG -fomit-frame-pointer")
, (ifld, text "LDFLAGS?=" <> text (unwords ldFlags))
, (True, text "")
, (ifdr, text "all:" <+> nmd)
, (ifdr, text "")
, (True, nmo <> text (": " ++ ppSameLine (hsep [nmc, nmh])))
, (True, text "\t${CC} ${CCFLAGS}" <+> text "-c $< -o $@")
, (True, text "")
, (ifdr, nmdo <> text ":" <+> nmdc)
, (ifdr, text "\t${CC} ${CCFLAGS}" <+> text "-c $< -o $@")
, (ifdr, text "")
, (ifdr, nmd <> text (": " ++ ppSameLine (hsep [nmo, nmdo])))
, (ifdr, text "\t${CC} ${CCFLAGS}" <+> text "$^ -o $@" <+> ld)
, (ifdr, text "")
, (True, text "clean:")
, (True, text "\trm -f *.o")
, (True, text "")
, (ifdr, text "veryclean: clean")
, (ifdr, text "\trm -f" <+> nmd)
, (ifdr, text "")
]
nm = text fn
nmd = text dn
nmh = nm <> text ".h"
nmc = nm <> text ".c"
nmo = nm <> text ".o"
nmdc = nmd <> text ".c"
nmdo = nmd <> text ".o"
-- | Generate the header
genHeader :: (Maybe Int, Maybe CgSRealType) -> String -> [Doc] -> Doc -> Doc
genHeader (ik, rk) fn sigs protos =
text "/* Header file for" <+> nm <> text ". Automatically generated by SBV. Do not edit! */"
$$ text ""
$$ text "#ifndef" <+> tag
$$ text "#define" <+> tag
$$ text ""
$$ text "#include <inttypes.h>"
$$ text "#include <stdint.h>"
$$ text "#include <stdbool.h>"
$$ text "#include <math.h>"
$$ text ""
$$ text "/* The boolean type */"
$$ text "typedef bool SBool;"
$$ text ""
$$ text "/* The float type */"
$$ text "typedef float SFloat;"
$$ text ""
$$ text "/* The double type */"
$$ text "typedef double SDouble;"
$$ text ""
$$ text "/* Unsigned bit-vectors */"
$$ text "typedef uint8_t SWord8 ;"
$$ text "typedef uint16_t SWord16;"
$$ text "typedef uint32_t SWord32;"
$$ text "typedef uint64_t SWord64;"
$$ text ""
$$ text "/* Signed bit-vectors */"
$$ text "typedef int8_t SInt8 ;"
$$ text "typedef int16_t SInt16;"
$$ text "typedef int32_t SInt32;"
$$ text "typedef int64_t SInt64;"
$$ text ""
$$ imapping
$$ rmapping
$$ text ("/* Entry point prototype" ++ plu ++ ": */")
$$ vcat (map (<> semi) sigs)
$$ text ""
$$ protos
$$ text "#endif /*" <+> tag <+> text "*/"
$$ text ""
where nm = text fn
tag = text "__" <> nm <> text "__HEADER_INCLUDED__"
plu = if length sigs /= 1 then "s" else ""
imapping = case ik of
Nothing -> empty
Just i -> text "/* User requested mapping for SInteger. */"
$$ text "/* NB. Loss of precision: Target type is subject to modular arithmetic. */"
$$ text ("typedef SInt" ++ show i ++ " SInteger;")
$$ text ""
rmapping = case rk of
Nothing -> empty
Just t -> text "/* User requested mapping for SReal. */"
$$ text "/* NB. Loss of precision: Target type is subject to rounding. */"
$$ text ("typedef " ++ show t ++ " SReal;")
$$ text ""
sepIf :: Bool -> Doc
sepIf b = if b then text "" else empty
-- | Generate an example driver program
genDriver :: CgConfig -> [Integer] -> String -> [(String, CgVal)] -> [(String, CgVal)] -> Maybe SW -> [Doc]
genDriver cfg randVals fn inps outs mbRet = [pre, header, body, post]
where pre = text "/* Example driver program for" <+> nm <> text ". */"
$$ text "/* Automatically generated by SBV. Edit as you see fit! */"
$$ text ""
$$ text "#include <inttypes.h>"
$$ text "#include <stdint.h>"
$$ text "#include <stdbool.h>"
$$ text "#include <math.h>"
$$ text "#include <stdio.h>"
header = text "#include" <+> doubleQuotes (nm <> text ".h")
$$ text ""
$$ text "int main(void)"
$$ text "{"
body = text ""
$$ nest 2 ( vcat (map mkInp pairedInputs)
$$ vcat (map mkOut outs)
$$ sepIf (not (null [() | (_, _, CgArray{}) <- pairedInputs]) || not (null outs))
$$ call
$$ text ""
$$ (case mbRet of
Just sw -> text "printf" <> parens (printQuotes (fcall <+> text "=" <+> specifier cfg sw <> text "\\n")
<> comma <+> resultVar) <> semi
Nothing -> text "printf" <> parens (printQuotes (fcall <+> text "->\\n")) <> semi)
$$ vcat (map display outs)
)
post = text ""
$+$ nest 2 (text "return 0" <> semi)
$$ text "}"
$$ text ""
nm = text fn
pairedInputs = matchRands (map abs randVals) inps
matchRands _ [] = []
matchRands [] _ = die "Run out of driver values!"
matchRands (r:rs) ((n, CgAtomic sw) : cs) = ([mkRVal sw r], n, CgAtomic sw) : matchRands rs cs
matchRands _ ((n, CgArray []) : _ ) = die $ "Unsupported empty array input " ++ show n
matchRands rs ((n, a@(CgArray sws@(sw:_))) : cs)
| length frs /= l = die "Run out of driver values!"
| True = (map (mkRVal sw) frs, n, a) : matchRands srs cs
where l = length sws
(frs, srs) = splitAt l rs
mkRVal sw r = mkConst cfg $ mkConstCW (kindOf sw) r
mkInp (_, _, CgAtomic{}) = empty -- constant, no need to declare
mkInp (_, n, CgArray []) = die $ "Unsupported empty array value for " ++ show n
mkInp (vs, n, CgArray sws@(sw:_)) = pprCWord True sw <+> text n <> brackets (int (length sws)) <+> text "= {"
$$ nest 4 (fsep (punctuate comma (align vs)))
$$ text "};"
$$ text ""
$$ text "printf" <> parens (printQuotes (text "Contents of input array" <+> text n <> text ":\\n")) <> semi
$$ display (n, CgArray sws)
$$ text ""
mkOut (v, CgAtomic sw) = pprCWord False sw <+> text v <> semi
mkOut (v, CgArray []) = die $ "Unsupported empty array value for " ++ show v
mkOut (v, CgArray sws@(sw:_)) = pprCWord False sw <+> text v <> brackets (int (length sws)) <> semi
resultVar = text "__result"
call = case mbRet of
Nothing -> fcall <> semi
Just sw -> pprCWord True sw <+> resultVar <+> text "=" <+> fcall <> semi
fcall = nm <> parens (fsep (punctuate comma (map mkCVal pairedInputs ++ map mkOVal outs)))
mkCVal ([v], _, CgAtomic{}) = v
mkCVal (vs, n, CgAtomic{}) = die $ "Unexpected driver value computed for " ++ show n ++ render (hcat vs)
mkCVal (_, n, CgArray{}) = text n
mkOVal (n, CgAtomic{}) = text "&" <> text n
mkOVal (n, CgArray{}) = text n
display (n, CgAtomic sw) = text "printf" <> parens (printQuotes (text " " <+> text n <+> text "=" <+> specifier cfg sw
<> text "\\n") <> comma <+> text n) <> semi
display (n, CgArray []) = die $ "Unsupported empty array value for " ++ show n
display (n, CgArray sws@(sw:_)) = text "int" <+> nctr <> semi
$$ text "for(" <> nctr <+> text "= 0;" <+> nctr <+> text "<" <+> int (length sws) <+> text "; ++" <> nctr <> text ")"
$$ nest 2 (text "printf" <> parens (printQuotes (text " " <+> entrySpec <+> text "=" <+> spec <> text "\\n")
<> comma <+> nctr <+> comma <> entry) <> semi)
where nctr = text n <> text "_ctr"
entry = text n <> text "[" <> nctr <> text "]"
entrySpec = text n <> text "[%d]"
spec = specifier cfg sw
-- | Generate the C program
genCProg :: CgConfig -> String -> Doc -> Result -> [(String, CgVal)] -> [(String, CgVal)] -> Maybe SW -> Doc -> [Doc]
genCProg cfg fn proto (Result kindInfo _tvals cgs ins preConsts tbls arrs _ _ (SBVPgm asgns) cstrs _) inVars outVars mbRet extDecls
| isNothing (cgInteger cfg) && KUnbounded `Set.member` kindInfo
= error $ "SBV->C: Unbounded integers are not supported by the C compiler."
++ "\nUse 'cgIntegerSize' to specify a fixed size for SInteger representation."
| isNothing (cgReal cfg) && KReal `Set.member` kindInfo
= error $ "SBV->C: SReal values are not supported by the C compiler."
++ "\nUse 'cgSRealType' to specify a custom type for SReal representation."
| not (null usorts)
= error $ "SBV->C: Cannot compile functions with uninterpreted sorts: " ++ intercalate ", " usorts
| not (null cstrs)
= tbd "Explicit constraints"
| not (null arrs)
= tbd "User specified arrays"
| needsExistentials (map fst ins)
= error "SBV->C: Cannot compile functions with existentially quantified variables."
| True
= [pre, header, post]
where usorts = [s | KUninterpreted s <- Set.toList kindInfo]
pre = text "/* File:" <+> doubleQuotes (nm <> text ".c") <> text ". Automatically generated by SBV. Do not edit! */"
$$ text ""
$$ text "#include <inttypes.h>"
$$ text "#include <stdint.h>"
$$ text "#include <stdbool.h>"
$$ text "#include <math.h>"
header = text "#include" <+> doubleQuotes (nm <> text ".h")
post = text ""
$$ vcat (map codeSeg cgs)
$$ extDecls
$$ proto
$$ text "{"
$$ text ""
$$ nest 2 ( vcat (concatMap (genIO True) inVars)
$$ vcat (merge (map genTbl tbls) (map genAsgn assignments))
$$ sepIf (not (null assignments) || not (null tbls))
$$ vcat (concatMap (genIO False) outVars)
$$ maybe empty mkRet mbRet
)
$$ text "}"
$$ text ""
nm = text fn
assignments = F.toList asgns
codeSeg (fnm, ls) = text "/* User specified custom code for" <+> doubleQuotes (text fnm) <+> text "*/"
$$ vcat (map text ls)
$$ text ""
typeWidth = getMax 0 [len (kindOf s) | (s, _) <- assignments]
where len (KReal{}) = 5
len (KFloat{}) = 6 -- SFloat
len (KDouble{}) = 7 -- SDouble
len (KUnbounded{}) = 8
len (KBounded False 1) = 5 -- SBool
len (KBounded False n) = 5 + length (show n) -- SWordN
len (KBounded True n) = 4 + length (show n) -- SIntN
len (KUninterpreted s) = die $ "Uninterpreted sort: " ++ s
getMax 8 _ = 8 -- 8 is the max we can get with SInteger, so don't bother looking any further
getMax m [] = m
getMax m (x:xs) = getMax (m `max` x) xs
consts = (falseSW, falseCW) : (trueSW, trueCW) : preConsts
isConst s = isJust (lookup s consts)
genIO :: Bool -> (String, CgVal) -> [Doc]
genIO True (cNm, CgAtomic sw) = [declSW typeWidth sw <+> text "=" <+> text cNm <> semi]
genIO False (cNm, CgAtomic sw) = [text "*" <> text cNm <+> text "=" <+> showSW cfg consts sw <> semi]
genIO isInp (cNm, CgArray sws) = zipWith genElt sws [(0::Int)..]
where genElt sw i
| isInp = declSW typeWidth sw <+> text "=" <+> text entry <> semi
| True = text entry <+> text "=" <+> showSW cfg consts sw <> semi
where entry = cNm ++ "[" ++ show i ++ "]"
mkRet sw = text "return" <+> showSW cfg consts sw <> semi
genTbl :: ((Int, Kind, Kind), [SW]) -> (Int, Doc)
genTbl ((i, _, k), elts) = (location, static <+> text "const" <+> text (show k) <+> text ("table" ++ show i) <> text "[] = {"
$$ nest 4 (fsep (punctuate comma (align (map (showSW cfg consts) elts))))
$$ text "};")
where static = if location == -1 then text "static" else empty
location = maximum (-1 : map getNodeId elts)
getNodeId s@(SW _ (NodeId n)) | isConst s = -1
| True = n
genAsgn :: (SW, SBVExpr) -> (Int, Doc)
genAsgn (sw, n) = (getNodeId sw, declSW typeWidth sw <+> text "=" <+> ppExpr cfg consts n <> semi)
-- merge tables intermixed with assignments, paying attention to putting tables as
-- early as possible.. Note that the assignment list (second argument) is sorted on its order
merge :: [(Int, Doc)] -> [(Int, Doc)] -> [Doc]
merge [] as = map snd as
merge ts [] = map snd ts
merge ts@((i, t):trest) as@((i', a):arest)
| i < i' = t : merge trest as
| True = a : merge ts arest
ppExpr :: CgConfig -> [(SW, CW)] -> SBVExpr -> Doc
ppExpr cfg consts (SBVApp op opArgs) = p op (map (showSW cfg consts) opArgs)
where rtc = cgRTC cfg
cBinOps = [ (Plus, "+"), (Times, "*"), (Minus, "-")
, (Equal, "=="), (NotEqual, "!="), (LessThan, "<"), (GreaterThan, ">"), (LessEq, "<="), (GreaterEq, ">=")
, (And, "&"), (Or, "|"), (XOr, "^")
]
p (ArrRead _) _ = tbd "User specified arrays (ArrRead)"
p (ArrEq _ _) _ = tbd "User specified arrays (ArrEq)"
p (Uninterpreted s) [] = text "/* Uninterpreted constant */" <+> text s
p (Uninterpreted s) as = text "/* Uninterpreted function */" <+> text s <> parens (fsep (punctuate comma as))
p (Extract i j) [a] = extract i j (head opArgs) a
p Join [a, b] = join (let (s1 : s2 : _) = opArgs in (s1, s2, a, b))
p (Rol i) [a] = rotate True i a (head opArgs)
p (Ror i) [a] = rotate False i a (head opArgs)
p (Shl i) [a] = shift True i a (head opArgs)
p (Shr i) [a] = shift False i a (head opArgs)
p Not [a] = case kindOf (head opArgs) of
-- be careful about booleans, bitwise complement is not correct for them!
KBounded False 1 -> text "!" <> a
_ -> text "~" <> a
p Ite [a, b, c] = a <+> text "?" <+> b <+> text ":" <+> c
p (LkUp (t, k, _, len) ind def) []
| not rtc = lkUp -- ignore run-time-checks per user request
| needsCheckL && needsCheckR = cndLkUp checkBoth
| needsCheckL = cndLkUp checkLeft
| needsCheckR = cndLkUp checkRight
| True = lkUp
where [index, defVal] = map (showSW cfg consts) [ind, def]
lkUp = text "table" <> int t <> brackets (showSW cfg consts ind)
cndLkUp cnd = cnd <+> text "?" <+> defVal <+> text ":" <+> lkUp
checkLeft = index <+> text "< 0"
checkRight = index <+> text ">=" <+> int len
checkBoth = parens (checkLeft <+> text "||" <+> checkRight)
canOverflow True sz = (2::Integer)^(sz-1)-1 >= fromIntegral len
canOverflow False sz = (2::Integer)^sz -1 >= fromIntegral len
(needsCheckL, needsCheckR) = case k of
KBounded sg sz -> (sg, canOverflow sg sz)
KReal -> die "array index with real value"
KFloat -> die "array index with float value"
KDouble -> die "array index with double value"
KUnbounded -> case cgInteger cfg of
Nothing -> (True, True) -- won't matter, it'll be rejected later
Just i -> (True, canOverflow True i)
KUninterpreted s -> die $ "Uninterpreted sort: " ++ s
-- Div/Rem should be careful on 0, in the SBV world x `div` 0 is 0, x `rem` 0 is x
-- NB: Quot is supposed to truncate toward 0; Not clear to me if C guarantees this behavior.
-- Brief googling suggests C99 does indeed truncate toward 0, but other C compilers might differ.
p Quot [a, b] = parens (b <+> text "== 0") <+> text "?" <+> text "0" <+> text ":" <+> parens (a <+> text "/" <+> b)
p Rem [a, b] = parens (b <+> text "== 0") <+> text "?" <+> a <+> text ":" <+> parens (a <+> text "%" <+> b)
p o [a, b]
| Just co <- lookup o cBinOps
= a <+> text co <+> b
p o args = die $ "Received operator " ++ show o ++ " applied to " ++ show args
shift toLeft i a s
| i < 0 = shift (not toLeft) (-i) a s
| i == 0 = a
| True = case kindOf s of
KBounded _ sz | i >= sz -> mkConst cfg $ mkConstCW (kindOf s) (0::Integer)
KReal -> tbd $ "Shift for real quantity: " ++ show (toLeft, i, s)
_ -> a <+> text cop <+> int i
where cop | toLeft = "<<"
| True = ">>"
rotate toLeft i a s
| i < 0 = rotate (not toLeft) (-i) a s
| i == 0 = a
| True = case kindOf s of
KBounded True _ -> tbd $ "Rotation of signed quantities: " ++ show (toLeft, i, s)
KBounded False sz | i >= sz -> rotate toLeft (i `mod` sz) a s
KBounded False sz -> parens (a <+> text cop <+> int i)
<+> text "|"
<+> parens (a <+> text cop' <+> int (sz - i))
KUnbounded -> shift toLeft i a s -- For SInteger, rotate is the same as shift in Haskell
_ -> tbd $ "Rotation for unbounded quantity: " ++ show (toLeft, i, s)
where (cop, cop') | toLeft = ("<<", ">>")
| True = (">>", "<<")
-- TBD: below we only support the values that SBV actually currently generates.
-- we would need to add new ones if we generate others. (Check instances in Data/SBV/BitVectors/Splittable.hs).
extract hi lo i a = case (hi, lo, kindOf i) of
( 0, 0, KUnbounded) -> text "(SReal)" <+> a -- special SInteger -> SReal conversion
(63, 32, KBounded False 64) -> text "(SWord32)" <+> parens (a <+> text ">> 32")
(31, 0, KBounded False 64) -> text "(SWord32)" <+> a
(31, 16, KBounded False 32) -> text "(SWord16)" <+> parens (a <+> text ">> 16")
(15, 0, KBounded False 32) -> text "(SWord16)" <+> a
(15, 8, KBounded False 16) -> text "(SWord8)" <+> parens (a <+> text ">> 8")
( 7, 0, KBounded False 16) -> text "(SWord8)" <+> a
-- the followings are used by sign-conversions. (Check instances in Data/SBV/BitVectors/SignCast.hs).
(63, 0, KBounded False 64) -> text "(SInt64)" <+> a
(63, 0, KBounded True 64) -> text "(SWord64)" <+> a
(31, 0, KBounded False 32) -> text "(SInt32)" <+> a
(31, 0, KBounded True 32) -> text "(SWord32)" <+> a
(15, 0, KBounded False 16) -> text "(SInt16)" <+> a
(15, 0, KBounded True 16) -> text "(SWord16)" <+> a
( 7, 0, KBounded False 8) -> text "(SInt8)" <+> a
( 7, 0, KBounded True 8) -> text "(SWord8)" <+> a
( _, _, k ) -> tbd $ "extract with " ++ show (hi, lo, k, i)
-- TBD: ditto here for join, just like extract above
join (i, j, a, b) = case (kindOf i, kindOf j) of
(KBounded False 8, KBounded False 8) -> parens (parens (text "(SWord16)" <+> a) <+> text "<< 8") <+> text "|" <+> parens (text "(SWord16)" <+> b)
(KBounded False 16, KBounded False 16) -> parens (parens (text "(SWord32)" <+> a) <+> text "<< 16") <+> text "|" <+> parens (text "(SWord32)" <+> b)
(KBounded False 32, KBounded False 32) -> parens (parens (text "(SWord64)" <+> a) <+> text "<< 32") <+> text "|" <+> parens (text "(SWord64)" <+> b)
(k1, k2) -> tbd $ "join with " ++ show ((k1, i), (k2, j))
-- same as doubleQuotes, except we have to make sure there are no line breaks..
-- Otherwise breaks the generated code.. sigh
printQuotes :: Doc -> Doc
printQuotes d = text $ '"' : ppSameLine d ++ "\""
-- Remove newlines.. Useful when generating Makefile and such
ppSameLine :: Doc -> String
ppSameLine = trim . render
where trim "" = ""
trim ('\n':cs) = ' ' : trim (dropWhile isSpace cs)
trim (c:cs) = c : trim cs
-- Align a bunch of docs to occupy the exact same length by padding in the left by space
-- this is ugly and inefficient, but easy to code..
align :: [Doc] -> [Doc]
align ds = map (text . pad) ss
where ss = map render ds
l = maximum (0 : map length ss)
pad s = replicate (l - length s) ' ' ++ s
-- | Merge a bunch of bundles to generate code for a library
mergeToLib :: String -> [CgPgmBundle] -> CgPgmBundle
mergeToLib libName bundles
| length nubKinds /= 1
= error $ "Cannot merge programs with differing SInteger/SReal mappings. Received the following kinds:\n"
++ unlines (map show nubKinds)
| True
= CgPgmBundle bundleKind $ sources ++ libHeader : [libDriver | anyDriver] ++ [libMake | anyMake]
where kinds = [k | CgPgmBundle k _ <- bundles]
nubKinds = nub kinds
bundleKind = head nubKinds
files = concat [fs | CgPgmBundle _ fs <- bundles]
sigs = concat [ss | (_, (CgHeader ss, _)) <- files]
anyMake = not (null [() | (_, (CgMakefile{}, _)) <- files])
drivers = [ds | (_, (CgDriver, ds)) <- files]
anyDriver = not (null drivers)
mkFlags = nub (concat [xs | (_, (CgMakefile xs, _)) <- files])
sources = [(f, (CgSource, [pre, libHInclude, post])) | (f, (CgSource, [pre, _, post])) <- files]
sourceNms = map fst sources
libHeader = (libName ++ ".h", (CgHeader sigs, [genHeader bundleKind libName sigs empty]))
libHInclude = text "#include" <+> text (show (libName ++ ".h"))
libMake = ("Makefile", (CgMakefile mkFlags, [genLibMake anyDriver libName sourceNms mkFlags]))
libDriver = (libName ++ "_driver.c", (CgDriver, mergeDrivers libName libHInclude (zip (map takeBaseName sourceNms) drivers)))
-- | Create a Makefile for the library
genLibMake :: Bool -> String -> [String] -> [String] -> Doc
genLibMake ifdr libName fs ldFlags = foldr1 ($$) [l | (True, l) <- lns]
where ifld = not (null ldFlags)
ld | ifld = text "${LDFLAGS}"
| True = empty
lns = [ (True, text "# Makefile for" <+> nm <> text ". Automatically generated by SBV. Do not edit!")
, (True, text "")
, (True, text "# include any user-defined .mk file in the current directory.")
, (True, text "-include *.mk")
, (True, text "")
, (True, text "CC=gcc")
, (True, text "CCFLAGS?=-Wall -O3 -DNDEBUG -fomit-frame-pointer")
, (ifld, text "LDFLAGS?=" <> text (unwords ldFlags))
, (True, text "AR=ar")
, (True, text "ARFLAGS=cr")
, (True, text "")
, (not ifdr, text ("all: " ++ liba))
, (ifdr, text ("all: " ++ unwords [liba, libd]))
, (True, text "")
, (True, text liba <> text (": " ++ unwords os))
, (True, text "\t${AR} ${ARFLAGS} $@ $^")
, (True, text "")
, (ifdr, text libd <> text (": " ++ unwords [libd ++ ".c", libh]))
, (ifdr, text ("\t${CC} ${CCFLAGS} $< -o $@ " ++ liba) <+> ld)
, (ifdr, text "")
, (True, vcat (zipWith mkObj os fs))
, (True, text "clean:")
, (True, text "\trm -f *.o")
, (True, text "")
, (True, text "veryclean: clean")
, (not ifdr, text "\trm -f" <+> text liba)
, (ifdr, text "\trm -f" <+> text (unwords [liba, libd]))
, (True, text "")
]
nm = text libName
liba = libName ++ ".a"
libh = libName ++ ".h"
libd = libName ++ "_driver"
os = map (`replaceExtension` ".o") fs
mkObj o f = text o <> text (": " ++ unwords [f, libh])
$$ text "\t${CC} ${CCFLAGS} -c $< -o $@"
$$ text ""
-- | Create a driver for a library
mergeDrivers :: String -> Doc -> [(FilePath, [Doc])] -> [Doc]
mergeDrivers libName inc ds = pre : concatMap mkDFun ds ++ [callDrivers (map fst ds)]
where pre = text "/* Example driver program for" <+> text libName <> text ". */"
$$ text "/* Automatically generated by SBV. Edit as you see fit! */"
$$ text ""
$$ text "#include <inttypes.h>"
$$ text "#include <stdint.h>"
$$ text "#include <stdbool.h>"
$$ text "#include <math.h>"
$$ text "#include <stdio.h>"
$$ inc
mkDFun (f, [_pre, _header, body, _post]) = [header, body, post]
where header = text ""
$$ text ("void " ++ f ++ "_driver(void)")
$$ text "{"
post = text "}"
mkDFun (f, _) = die $ "mergeDrivers: non-conforming driver program for " ++ show f
callDrivers fs = text ""
$$ text "int main(void)"
$$ text "{"
$+$ nest 2 (vcat (map call fs))
$$ nest 2 (text "return 0;")
$$ text "}"
call f = text psep
$$ text ptag
$$ text psep
$$ text (f ++ "_driver();")
$$ text ""
where tag = "** Driver run for " ++ f ++ ":"
ptag = "printf(\"" ++ tag ++ "\\n\");"
lsep = replicate (length tag) '='
psep = "printf(\"" ++ lsep ++ "\\n\");"
|
dylanmc/cryptol
|
sbv/Data/SBV/Compilers/C.hs
|
bsd-3-clause
| 39,515 | 0 | 49 | 14,462 | 11,883 | 6,097 | 5,786 | 586 | 49 |
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE TupleSections #-}
module Algw.Infer where
import Algw.Ast
import Algw.Type
import Algw.Env
import State
import Data.IORef
import Data.Maybe
import Control.Monad
import qualified Data.Map as M
import qualified Data.Set as S
makeNewVar :: Infer (Infer TName)
makeNewVar =
do r <- newIORef 'a'
-- return a closure like structure to mock a generator
return $ do
v <- readIORef r
modifyIORef r succ
return [v]
generalize :: Env -> T -> Scheme
generalize env t = let fvs = freeVars t `S.difference` freeVars env
-- cause poly type here can only hold single quantified type var
in S.fold Poly (Mono t) fvs
replaceFreeVars :: Scheme -> Subrule -> T
replaceFreeVars (Mono t) s = subst s t
replaceFreeVars (Poly _ t) s = replaceFreeVars t s
-- just replace quantified type variables by fresh ones to make it monomorphic
instantiate :: Infer TName -> Scheme -> Infer T
-- each poly type hold single quantified type variable is not really a good design, but just to be compatible with the origin paper
-- τ ::= α | ι | τ → τ
-- σ ::= τ | ∀α. σ
instantiate newVar t = let boundVars = allVars t `S.difference` freeVars t
-- update quantified type variable with fresh one
update acc a = do
fresh <- fmap TVar newVar
return $ M.insert a fresh acc
replace = foldM update M.empty boundVars
-- applicative functor
in pure (replaceFreeVars t) <*> replace
occurs :: TName -> T -> Bool
occurs a t = a `S.member` freeVars t
makeSingleSubrule :: TName -> T -> Infer Subrule
makeSingleSubrule a t
| t == TVar a = return emptyRule
| occurs a t = error "occurs check fails"
| otherwise = return $ M.singleton a t
-- find mgu(most general unifier) of two types
unify :: T -> T -> Infer Subrule
unify TInt TInt = return emptyRule
unify TBool TBool = return emptyRule
unify (TVar n) t = makeSingleSubrule n t
unify t (TVar n) = makeSingleSubrule n t
unify (TArrow tl1 tr1) (TArrow tl2 tr2) = do
s1 <- unify tl1 tl2
s2 <- subst s1 tr1 `unify` subst s1 tr2
return $ s2 `compose` s1
unify t1 t2 = error $ "types do not unify: " ++ show t1 ++ " vs. " ++ show t2
-- just like assoc in clojure
assocEnv :: TName -> Scheme -> Env -> Env
assocEnv n v env = M.insert n v $ M.delete n env
algw :: Infer TName -> Env -> Expr -> IO (Subrule, T)
algw newVar env (EVar name) = (emptyRule,) <$> instantiate newVar t -- pure (emptyRule,) <*> instantiate newVar t is also fine
where t = fromMaybe (error $ "unbound variable: " ++ name) $ M.lookup name env
{-
t <- fmap TVar newVar will work because
instance Functor IO where
fmap f action = do
result <- action
return (f result)
-}
algw newVar env (EAbs name expr) = do
fresh <- fmap TVar newVar
let env' = assocEnv name (Mono fresh) env
(subrule, mono) <- algw newVar env' expr
return (subrule, subst subrule fresh `TArrow` mono)
algw newVar env (EApp e1 e2) = do
(s1, m1) <- algw newVar env e1
(s2, m2) <- algw newVar (subst s1 env) e2
fresh <- fmap TVar newVar
s3 <- unify (subst s2 m1) (TArrow m2 fresh)
return (s3 `compose` s2 `compose` s1, subst s3 fresh)
algw newVar env (ELet name value body) = do
(s1, vmono) <- algw newVar env value
let env' = subst s1 env
g = generalize env' vmono
env'' = assocEnv name g env'
(s2, bmono) <- algw newVar env'' body
return (s2 `compose` s1, bmono)
-- environment is assumptions at the initial state
infer :: Env -> Expr -> IO T
infer env expr =
do newVar <- makeNewVar
(_, t) <- algw newVar env expr
return t
|
zjhmale/HMF
|
src/Algw/Infer.hs
|
bsd-3-clause
| 3,788 | 0 | 13 | 1,028 | 1,223 | 609 | 614 | 77 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
module Mismi.SQS.Core.Data (
QueueName (..)
, Queue (..)
, QueueUrl (..)
, MessageId (..)
) where
import Mismi.Kernel.Data (MismiRegion)
import P
-- Queue names are limited to 80 characters. Alphanumeric characters
-- plus hyphens (-) and underscores (_) are allowed. Queue names must
-- be unique within an AWS account. After you delete a queue, you can
-- reuse the queue name.
newtype QueueName =
QueueName {
renderQueueName :: Text
} deriving (Eq, Show)
data Queue =
Queue {
queueName :: QueueName
, queueRegion :: MismiRegion
} deriving (Eq, Show)
newtype QueueUrl =
QueueUrl {
renderQueueUrl :: Text
} deriving (Eq, Show)
newtype MessageId =
MessageId {
renderMessageId :: Text
} deriving (Eq, Show)
|
ambiata/mismi
|
mismi-sqs-core/src/Mismi/SQS/Core/Data.hs
|
bsd-3-clause
| 867 | 0 | 8 | 213 | 162 | 106 | 56 | 26 | 0 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE DataKinds #-} -- these two needed for help output
{-# LANGUAGE TypeOperators #-}
module Types where
import Data.Hashable
import qualified Data.HashMap.Strict as H
import Data.Csv hiding (lookup)
import Data.Text (Text, pack)
import GHC.Generics
import Data.List (intercalate)
import Options.Generic
import Data.FixedList
import qualified Data.ByteString.Lazy as B
import Data.ByteString.Internal as I
-- type FilePath = String
-- , geneSource :: Maybe GenBankSource <?> "Genbank ID, Genbank file, or csv file"
-- commandline stuff
data Seperator = Tab | Comma
deriving (Show, Eq, Generic)
deriving instance Read Seperator
instance ParseField Seperator
deriving instance Read RowType
instance ParseField RowType
data Options = Options { rowFilter :: [RowType] <?> "What show -- Insert, etc.."
, sep :: First Seperator <?> "Comma or Tab output"
, fasta :: FilePath <?> "Input aligned fasta file"
, align :: Bool <?> "Align the sequence first?"
, syn :: Bool <?> "Display synonymous AAs?"}
deriving (Generic, Show)
instance ParseRecord Options
-- Primary types
type Index = Int
newtype Id = Id String
data AA = K | N | T | R | S | I | M | Q | H | P | L | E | D | A | G | V | Z | Y | C | W | F
deriving (Show, Eq, Enum, Generic)
aaShow Z = "!"
aaShow x = show x
newtype Codon = Codon String
deriving (Eq, Show)
instance Hashable Codon where
hashWithSalt salt (Codon s) = hashWithSalt salt s
type CodonTable = H.HashMap Codon AA
data RowType = Is_Gap | Has_N | Stop_Codon | Synonymous | Non_Synonymous
deriving (Show, Eq, Generic)
data Degen = Insert Codon Index
| WithN Codon Index
| StopCodon AA Index Codon [Index]
| Synonymous' AA Index Codon [Index]
| NonSynonymous [AA] Index Codon [Index] -- Codon index or AA Index? Should make newtypes
| NormalCodon
deriving (Show, Eq)
-- type for the csv row list
type FieldList = FixedList6
--instance ToRecord Degen where
-- toRecord = record . toList . fieldList
--data GenBankSource = GBFile FilePath | CSVFile FilePath | GBID String
-- deriving (Show, Generic, ParseRecord)
-- unused newtype CodonIndex = CodonIndex Int -- make this part of codon?
-- unused newtype AAIndex = AAIndex Int -- make this part of codon?
-- *** Exception: Data.Csv.Encoding.namedRecordToRecord: header contains name "RowType" which is not present in the named record
|
VDBWRAIR/Haskell-MAAPs
|
src/Types.hs
|
bsd-3-clause
| 2,660 | 0 | 10 | 656 | 538 | 322 | 216 | 50 | 1 |
module Stream
( tests -- :: Int -> Tests
) where
import Control.Monad
import Data.Bits
import Data.ByteString (ByteString)
import qualified Data.ByteString as S
import Crypto.Encrypt.Stream
import Crypto.Key
import Crypto.Nonce
import Test.QuickCheck
import Util
--------------------------------------------------------------------------------
-- Streaming encryption
streamProp :: (SecretKey Stream -> Nonce Stream -> Bool) -> Property
streamProp k = ioProperty $ liftM2 k randomKey randomNonce
roundtrip :: ByteString -> Property
roundtrip xs
= streamProp $ \key nonce ->
let enc = encrypt nonce xs key
dec = decrypt nonce enc key
in dec == xs
streamXor :: ByteString -> Property
streamXor xs
= streamProp $ \key nonce ->
let
xorBS x1 x2 = S.pack $ S.zipWith xor x1 x2
enc = encrypt nonce xs key
str = stream nonce (S.length xs) key
in enc == (str `xorBS` xs)
tests :: Int -> Tests
tests ntests =
[ ("xsalsa20 roundtrip", wrap roundtrip)
, ("xsalsa20 stream/enc equiv", wrap streamXor)
]
where
wrap :: Testable prop => prop -> IO (Bool, Int)
wrap = mkArgTest ntests
|
thoughtpolice/hs-nacl
|
tests/Stream.hs
|
bsd-3-clause
| 1,246 | 0 | 14 | 343 | 351 | 189 | 162 | 33 | 1 |
module Network.Email.Parser
( -- | Encodings
quotedPrintable
, base64
, crlfText
, -- | Mail
headers
, mail
) where
import Prelude hiding (takeWhile)
import Data.List hiding (takeWhile)
import Data.Maybe
import Data.Monoid
import Control.Applicative
import Control.Monad.Catch
import qualified Data.Map as M
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Builder as BL
import qualified Data.ByteString.Base64.Lazy as B64
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TL
import qualified Data.Text.Encoding.Error as T
import qualified Data.Text.Lazy.Builder as TB
import qualified Data.Attoparsec.Text.Lazy as TL
import Data.Attoparsec.ByteString.Char8
import qualified Data.Attoparsec.Text as T
import qualified Network.Email.Header.Parser as E
import qualified Network.Email.Header.Read as E
import Debug.Trace
import Network.Email.Types
eof :: Parser ()
eof = () <$ string "\r\n" <|> endOfInput
-- | Parses lines delimited by @delim@. The builder is concatenated to each string.
-- When @delim@ returns Nothing, read the next line, otherwise return its last
-- state.
delimited :: Show a => Parser (BL.Builder, Maybe a) -> Parser (BL.Builder, a)
delimited delim = do
this <- BL.byteString <$> takeTill (== '\r')
(del, r') <- delim
case r' of
Nothing -> do
(next, r) <- delimited delim
return (this <> del <> next, r)
Just r -> return (this <> del, r)
-- | Run a 'Text' parser for a UTF-8 encoded 'ByteString' inside a 'ByteString' 'Parser'.
parseUtf8 :: Show a => TL.Parser a -> BL.ByteString -> Parser a
parseUtf8 p s = do
t <- case TL.decodeUtf8' s of
Left (T.DecodeError e _) -> fail e
Right r -> return r
case TL.parse (p <* T.endOfInput) t of
TL.Fail _ ctx e -> let e' = fromMaybe e (stripPrefix "Failed reading: " e)
in foldl (<?>) (fail e') ctx
TL.Done _ r -> return r
-- | Parse e-mail headers in bulk. Does not support obsolete quoting style
-- (which allows \r\n to be quoted).
headers :: Parser BL.Builder
headers = fst <$> delimited newline
where newline = (,) <$> (BL.byteString <$> string "\r\n") <*> optional (string "\r\n")
-- | Parses MIME boundary. Returns 'True' if the end of multipart message was
-- met, 'False' otherwise.
boundary :: B.ByteString -> Parser (BL.Builder, Maybe Bool)
boundary delim = do
r <- string "\r\n"
(mempty, ) <$> Just <$> bnd
<|> return (BL.byteString r, Nothing)
where bnd = do
_ <- string "--"
_ <- string delim
False <$ eof
<|> True <$ string "--" <* eof
-- | Parses a part of a multi-part e-mail, reading body and final delimiter with @body@.
mailPart :: Parser (BL.Builder, a) -> Parser (Mail, a)
mailPart body = do
hdr' <- BL.toLazyByteString <$> headers
mailHeaders <- parseUtf8 E.headers hdr'
case E.boundary mailHeaders of
Nothing -> do
(dat, r) <- body
let mail = SimpleMail { mailBody = BL.toLazyByteString dat
, ..
}
return (mail, r)
Just bnd -> do
let parser = delimited $ boundary bnd
read True = return []
read False = do
(part, r) <- mailPart parser
(part:) <$> read r
(_, r') <- parser
mailParts <- read r'
(_, r) <- body
let mail = MultipartMail { .. }
return (mail, r)
-- | Parses e-mail according to RFC 5322.
mail :: Parser Mail
mail = fst <$> mailPart ((, ()) <$> BL.lazyByteString <$> takeLazyByteString)
-- | Parses quoted-printable encoded bytestring.
quotedPrintable :: Parser BL.Builder
quotedPrintable = mconcat <$> intersperse (BL.byteString "\r\n") <$> line `sepBy` string "\r\n"
where line = mconcat <$> (padding >> body) `sepBy` (char '=' >> padding >> string "\r\n")
padding = skipWhile (inClass " \t")
body = BL.byteString <$> takeWhile1 (/= '=')
<|> BL.word8 <$ char '=' <*> E.hexPair
-- | Parses base64 encoded bytestring.
base64 :: Parser BL.ByteString
base64 = do
str <- BL.toLazyByteString <$> mconcat <$> (BL.byteString <$> takeWhile (/= '\r')) `sepBy` string "\r\n"
E.parseEither $ B64.decode str
-- | Parses Unicode text with CRLF endings, converting them to LF.
crlfText :: T.Parser TL.Text
crlfText = TB.toLazyText <$> mconcat <$> intersperse (TB.singleton '\n') <$> line `sepBy` T.string "\r\n"
where line = TB.fromText <$> T.takeWhile1 (/= '\r')
|
abbradar/email
|
src/Network/Email/Parser.hs
|
bsd-3-clause
| 4,533 | 0 | 18 | 1,051 | 1,360 | 731 | 629 | -1 | -1 |
-- |
-- Copyright : Anders Claesson 2013-2016
-- Maintainer : Anders Claesson <[email protected]>
--
-- Components of permutations.
--
module Sym.Perm.Component
(
components
, skewComponents
, leftMaxima
, leftMinima
, rightMaxima
, rightMinima
) where
import Foreign
import System.IO.Unsafe
import Sym.Perm
import qualified Sym.Perm.D8 as D8
-- Positions /i/ such that /max{ w[j] : j <= i } = i/. These positions
-- mark the boundaries of components.
comps :: Perm -> [Int]
comps w = unsafePerformIO . unsafeWith w $ go [] 0 0
where
n = size w
go ks m i p
| i >= n = return (reverse ks)
| otherwise =
do y <- fromIntegral `fmap` peek p
let p' = advancePtr p 1
let i' = i+1
let m' = if y > m then y else m
let ks' = if m' == i then i:ks else ks
go ks' m' i' p'
-- | The list of (plus) components.
components :: Perm -> [Perm]
components w =
let ds = 0 : map (+1) (comps w)
ks = zipWith (-) (tail ds) ds
ws = slices ks w
in zipWith (\d v -> imap (\_ x -> x - fromIntegral d) v) ds ws
-- | The list of skew components, also called minus components.
skewComponents :: Perm -> [Perm]
skewComponents = map D8.complement . components . D8.complement
records :: (a -> a -> Bool) -> [a] -> [a]
records _ [] = []
records f (x:xs) = recs [x] xs
where
recs rs@(r:_) (y:ys) = recs ((if f r y then y else r):rs) ys
recs rs _ = rs
-- | For each position, left-to-right, records the largest value seen
-- thus far.
leftMaxima :: Perm -> [Int]
leftMaxima w = map fromIntegral . reverse $ records (<) (toList w)
-- | For each position, left-to-right, records the smallest value seen
-- thus far.
leftMinima :: Perm -> [Int]
leftMinima w = map fromIntegral . reverse $ records (>) (toList w)
-- | For each position, /right-to-left/, records the largest value seen
-- thus far.
rightMaxima :: Perm -> [Int]
rightMaxima w = map fromIntegral $ records (<) (reverse (toList w))
-- | For each position, /right-to-left/, records the smallest value seen
-- thus far.
rightMinima :: Perm -> [Int]
rightMinima w = map fromIntegral $ records (>) (reverse (toList w))
|
akc/sym
|
Sym/Perm/Component.hs
|
bsd-3-clause
| 2,272 | 0 | 14 | 617 | 728 | 391 | 337 | 45 | 3 |
#define IncludedcatIndices
#ifdef IncludedmakeIndicesNull
#else
#include "../Proofs/makeIndicesNull.hs"
#endif
#ifdef IncludedmergeIndices
#else
#include "../Proofs/mergeIndices.hs"
#endif
#ifdef IncludedconcatMakeIndices
#else
#include "../Proofs/concatMakeIndices.hs"
#endif
catIndices :: RString -> RString -> RString -> Integer -> Integer -> Proof
{-@ catIndices
:: input:RString -> x:RString
-> target:{RString | 0 <= stringLen input - stringLen target + 1}
-> lo:{INat | lo <= stringLen input - stringLen target }
-> hi:{Integer | (stringLen input - stringLen target) <= hi}
-> { makeIndices input target lo hi == makeIndices (input <+> x) target lo (stringLen input - stringLen target) }
@-}
catIndices input x target lo hi
= makeIndices input target lo hi
==. append (makeIndices input target lo (stringLen input - stringLen target))
(makeIndices input target (stringLen input - stringLen target + 1) hi)
?mergeIndices input target lo (stringLen input - stringLen target) hi
==. append (makeIndices input target lo (stringLen input - stringLen target)) N
?makeIndicesNull input target (stringLen input - stringLen target + 1) hi
==. makeIndices input target lo (stringLen input - stringLen target)
?listLeftId (makeIndices input target lo (stringLen input - stringLen target))
==. makeIndices (input <+> x) target lo (stringLen input - stringLen target)
?concatMakeIndices lo (stringLen input - stringLen target) target input x
*** QED
|
nikivazou/verified_string_matching
|
src/Proofs/catIndices.hs
|
bsd-3-clause
| 1,558 | 0 | 16 | 318 | 328 | 163 | 165 | 13 | 1 |
{-
(c) The GRASP/AQUA Project, Glasgow University, 1992-2006
\section[RnEnv]{Environment manipulation for the renamer monad}
-}
{-# LANGUAGE CPP #-}
module ETA.Rename.RnEnv (
newTopSrcBinder,
lookupLocatedTopBndrRn, lookupTopBndrRn,
lookupLocatedOccRn, lookupOccRn, lookupOccRn_maybe,
lookupLocalOccRn_maybe, lookupInfoOccRn,
lookupLocalOccThLvl_maybe,
lookupTypeOccRn, lookupKindOccRn,
lookupGlobalOccRn, lookupGlobalOccRn_maybe,
reportUnboundName,
HsSigCtxt(..), lookupLocalTcNames, lookupSigOccRn,
lookupSigCtxtOccRn,
lookupFixityRn, lookupTyFixityRn,
lookupInstDeclBndr, lookupSubBndrOcc, lookupFamInstName,
greRdrName,
lookupSubBndrGREs, lookupConstructorFields,
lookupSyntaxName, lookupSyntaxNames, lookupIfThenElse,
lookupGreRn, lookupGreRn_maybe,
lookupGreLocalRn_maybe,
getLookupOccRn, addUsedRdrNames,
newLocalBndrRn, newLocalBndrsRn,
bindLocalNames, bindLocalNamesFV,
MiniFixityEnv,
addLocalFixities,
bindLocatedLocalsFV, bindLocatedLocalsRn,
extendTyVarEnvFVRn,
checkDupRdrNames, checkShadowedRdrNames,
checkDupNames, checkDupAndShadowedNames, checkTupSize,
addFvRn, mapFvRn, mapMaybeFvRn, mapFvRnCPS,
warnUnusedMatches,
warnUnusedTopBinds, warnUnusedLocalBinds,
dataTcOccs, kindSigErr, perhapsForallMsg,
HsDocContext(..), docOfHsDocContext
) where
import ETA.Iface.LoadIface ( loadInterfaceForName, loadSrcInterface_maybe )
import ETA.Iface.IfaceEnv
import ETA.HsSyn.HsSyn
import ETA.BasicTypes.RdrName
import ETA.Main.HscTypes
import ETA.TypeCheck.TcEnv ( tcLookupDataCon, tcLookupField, isBrackStage )
import ETA.TypeCheck.TcRnMonad
import ETA.BasicTypes.Id ( isRecordSelector )
import ETA.BasicTypes.Name
import ETA.BasicTypes.NameSet
import ETA.BasicTypes.NameEnv
import ETA.BasicTypes.Avail
import ETA.BasicTypes.Module
import ETA.BasicTypes.ConLike
import ETA.BasicTypes.DataCon ( dataConFieldLabels, dataConTyCon )
import ETA.Types.TyCon ( isTupleTyCon, tyConArity )
import ETA.Prelude.PrelNames ( mkUnboundName, isUnboundName, rOOT_MAIN, forall_tv_RDR )
import ETA.Main.ErrUtils ( MsgDoc )
import ETA.BasicTypes.BasicTypes ( Fixity(..), FixityDirection(..), minPrecedence, defaultFixity )
import ETA.BasicTypes.SrcLoc
import ETA.Utils.Outputable
import qualified ETA.Utils.Outputable as Outputable
import ETA.Utils.Util
import ETA.Utils.Maybes
import ETA.BasicTypes.BasicTypes ( TopLevelFlag(..) )
import ETA.Utils.ListSetOps ( removeDups )
import ETA.Main.DynFlags
import ETA.Utils.FastString
import Control.Monad
import Data.List
import qualified Data.Set as Set
import ETA.Utils.ListSetOps ( minusList )
import ETA.Main.Constants ( mAX_TUPLE_SIZE )
{-
*********************************************************
* *
Source-code binders
* *
*********************************************************
Note [Signature lazy interface loading]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GHC's lazy interface loading can be a bit confusing, so this Note is an
empirical description of what happens in one interesting case. When
compiling a signature module against an its implementation, we do NOT
load interface files associated with its names until after the type
checking phase. For example:
module ASig where
data T
f :: T -> T
Suppose we compile this with -sig-of "A is ASig":
module B where
data T = T
f T = T
module A(module B) where
import B
During type checking, we'll load A.hi because we need to know what the
RdrEnv for the module is, but we DO NOT load the interface for B.hi!
It's wholly unnecessary: our local definition 'data T' in ASig is all
the information we need to finish type checking. This is contrast to
type checking of ordinary Haskell files, in which we would not have the
local definition "data T" and would need to consult B.hi immediately.
(Also, this situation never occurs for hs-boot files, since you're not
allowed to reexport from another module.)
After type checking, we then check that the types we provided are
consistent with the backing implementation (in checkHiBootOrHsigIface).
At this point, B.hi is loaded, because we need something to compare
against.
I discovered this behavior when trying to figure out why type class
instances for Data.Map weren't in the EPS when I was type checking a
test very much like ASig (sigof02dm): the associated interface hadn't
been loaded yet! (The larger issue is a moot point, since an instance
declared in a signature can never be a duplicate.)
This behavior might change in the future. Consider this
alternate module B:
module B where
{-# DEPRECATED T, f "Don't use" #-}
data T = T
f T = T
One might conceivably want to report deprecation warnings when compiling
ASig with -sig-of B, in which case we need to look at B.hi to find the
deprecation warnings during renaming. At the moment, you don't get any
warning until you use the identifier further downstream. This would
require adjusting addUsedRdrName so that during signature compilation,
we do not report deprecation warnings for LocalDef. See also
Note [Handling of deprecations]
-}
newTopSrcBinder :: Located RdrName -> RnM Name
newTopSrcBinder (L loc rdr_name)
| Just name <- isExact_maybe rdr_name
= -- This is here to catch
-- (a) Exact-name binders created by Template Haskell
-- (b) The PrelBase defn of (say) [] and similar, for which
-- the parser reads the special syntax and returns an Exact RdrName
-- We are at a binding site for the name, so check first that it
-- the current module is the correct one; otherwise GHC can get
-- very confused indeed. This test rejects code like
-- data T = (,) Int Int
-- unless we are in GHC.Tup
if isExternalName name then
do { this_mod <- getModule
; unless (this_mod == nameModule name)
(addErrAt loc (badOrigBinding rdr_name))
; return name }
else -- See Note [Binders in Template Haskell] in Convert.hs
do { let occ = nameOccName name
; occ `seq` return () -- c.f. seq in newGlobalBinder
; this_mod <- getModule
; updNameCache $ \ ns ->
let name' = mkExternalName (nameUnique name) this_mod occ loc
ns' = ns { nsNames = extendNameCache (nsNames ns) this_mod occ name' }
in (ns', name') }
| Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
= do { this_mod <- getModule
; unless (rdr_mod == this_mod || rdr_mod == rOOT_MAIN)
(addErrAt loc (badOrigBinding rdr_name))
-- When reading External Core we get Orig names as binders,
-- but they should agree with the module gotten from the monad
--
-- We can get built-in syntax showing up here too, sadly. If you type
-- data T = (,,,)
-- the constructor is parsed as a type, and then RdrHsSyn.tyConToDataCon
-- uses setRdrNameSpace to make it into a data constructors. At that point
-- the nice Exact name for the TyCon gets swizzled to an Orig name.
-- Hence the badOrigBinding error message.
--
-- Except for the ":Main.main = ..." definition inserted into
-- the Main module; ugh!
-- Because of this latter case, we call newGlobalBinder with a module from
-- the RdrName, not from the environment. In principle, it'd be fine to
-- have an arbitrary mixture of external core definitions in a single module,
-- (apart from module-initialisation issues, perhaps).
; newGlobalBinder rdr_mod rdr_occ loc }
| otherwise
= do { unless (not (isQual rdr_name))
(addErrAt loc (badQualBndrErr rdr_name))
-- Binders should not be qualified; if they are, and with a different
-- module name, we we get a confusing "M.T is not in scope" error later
; stage <- getStage
; env <- getGblEnv
; if isBrackStage stage then
-- We are inside a TH bracket, so make an *Internal* name
-- See Note [Top-level Names in Template Haskell decl quotes] in RnNames
do { uniq <- newUnique
; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }
else case tcg_impl_rdr_env env of
Just gr ->
-- We're compiling --sig-of, so resolve with respect to this
-- module.
-- See Note [Signature parameters in TcGblEnv and DynFlags]
do { case lookupGlobalRdrEnv gr (rdrNameOcc rdr_name) of
-- Be sure to override the loc so that we get accurate
-- information later
[GRE{ gre_name = n }] -> do
-- NB: Just adding this line will not work:
-- addUsedRdrName True gre rdr_name
-- see Note [Signature lazy interface loading] for
-- more details.
return (setNameLoc n loc)
_ -> do
{ -- NB: cannot use reportUnboundName rdr_name
-- because it looks up in the wrong RdrEnv
-- ToDo: more helpful error messages
; addErr (unknownNameErr (pprNonVarNameSpace
(occNameSpace (rdrNameOcc rdr_name))) rdr_name)
; return (mkUnboundName rdr_name)
}
}
Nothing ->
-- Normal case
do { this_mod <- getModule
; newGlobalBinder this_mod (rdrNameOcc rdr_name) loc } }
{-
*********************************************************
* *
Source code occurrences
* *
*********************************************************
Looking up a name in the RnEnv.
Note [Type and class operator definitions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We want to reject all of these unless we have -XTypeOperators (Trac #3265)
data a :*: b = ...
class a :*: b where ...
data (:*:) a b = ....
class (:*:) a b where ...
The latter two mean that we are not just looking for a
*syntactically-infix* declaration, but one that uses an operator
OccName. We use OccName.isSymOcc to detect that case, which isn't
terribly efficient, but there seems to be no better way.
-}
lookupTopBndrRn :: RdrName -> RnM Name
lookupTopBndrRn n = do nopt <- lookupTopBndrRn_maybe n
case nopt of
Just n' -> return n'
Nothing -> do traceRn $ (text "lookupTopBndrRn fail" <+> ppr n)
unboundName WL_LocalTop n
lookupLocatedTopBndrRn :: Located RdrName -> RnM (Located Name)
lookupLocatedTopBndrRn = wrapLocM lookupTopBndrRn
lookupTopBndrRn_maybe :: RdrName -> RnM (Maybe Name)
-- Look up a top-level source-code binder. We may be looking up an unqualified 'f',
-- and there may be several imported 'f's too, which must not confuse us.
-- For example, this is OK:
-- import Foo( f )
-- infix 9 f -- The 'f' here does not need to be qualified
-- f x = x -- Nor here, of course
-- So we have to filter out the non-local ones.
--
-- A separate function (importsFromLocalDecls) reports duplicate top level
-- decls, so here it's safe just to choose an arbitrary one.
--
-- There should never be a qualified name in a binding position in Haskell,
-- but there can be if we have read in an external-Core file.
-- The Haskell parser checks for the illegal qualified name in Haskell
-- source files, so we don't need to do so here.
lookupTopBndrRn_maybe rdr_name
| Just name <- isExact_maybe rdr_name
= do { name' <- lookupExactOcc name; return (Just name') }
| Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
-- This deals with the case of derived bindings, where
-- we don't bother to call newTopSrcBinder first
-- We assume there is no "parent" name
= do { loc <- getSrcSpanM
; n <- newGlobalBinder rdr_mod rdr_occ loc
; return (Just n)}
| otherwise
= do { -- Check for operators in type or class declarations
-- See Note [Type and class operator definitions]
let occ = rdrNameOcc rdr_name
; when (isTcOcc occ && isSymOcc occ)
(do { op_ok <- xoptM Opt_TypeOperators
; unless op_ok (addErr (opDeclErr rdr_name)) })
; mb_gre <- lookupGreLocalRn_maybe rdr_name
; case mb_gre of
Nothing -> return Nothing
Just gre -> return (Just $ gre_name gre) }
-----------------------------------------------
-- | Lookup an @Exact@ @RdrName@. See Note [Looking up Exact RdrNames].
-- This adds an error if the name cannot be found.
lookupExactOcc :: Name -> RnM Name
lookupExactOcc name
= do { result <- lookupExactOcc_either name
; case result of
Left err -> do { addErr err
; return name }
Right name' -> return name' }
-- | Lookup an @Exact@ @RdrName@. See Note [Looking up Exact RdrNames].
-- This never adds an error, but it may return one.
lookupExactOcc_either :: Name -> RnM (Either MsgDoc Name)
-- See Note [Looking up Exact RdrNames]
lookupExactOcc_either name
| Just thing <- wiredInNameTyThing_maybe name
, Just tycon <- case thing of
ATyCon tc -> Just tc
AConLike (RealDataCon dc) -> Just (dataConTyCon dc)
_ -> Nothing
, isTupleTyCon tycon
= do { checkTupSize (tyConArity tycon)
; return (Right name) }
| isExternalName name
= return (Right name)
| otherwise
= do { env <- getGlobalRdrEnv
; let -- See Note [Splicing Exact names]
main_occ = nameOccName name
demoted_occs = case demoteOccName main_occ of
Just occ -> [occ]
Nothing -> []
gres = [ gre | occ <- main_occ : demoted_occs
, gre <- lookupGlobalRdrEnv env occ
, gre_name gre == name ]
; case gres of
[] -> -- See Note [Splicing Exact names]
do { lcl_env <- getLocalRdrEnv
; if name `inLocalRdrEnvScope` lcl_env
then return (Right name)
else
#ifdef GHCI
do { th_topnames_var <- fmap tcg_th_topnames getGblEnv
; th_topnames <- readTcRef th_topnames_var
; if name `elemNameSet` th_topnames
then return (Right name)
else return (Left exact_nm_err)
}
#else /* !GHCI */
return (Left exact_nm_err)
#endif /* !GHCI */
}
[gre] -> return (Right (gre_name gre))
_ -> return (Left dup_nm_err)
-- We can get more than one GRE here, if there are multiple
-- bindings for the same name. Sometimes they are caught later
-- by findLocalDupsRdrEnv, like in this example (Trac #8932):
-- $( [d| foo :: a->a; foo x = x |])
-- foo = True
-- But when the names are totally identical, we panic (Trac #7241):
-- $(newName "Foo" >>= \o -> return [DataD [] o [] [RecC o []] [''Show]])
-- So, let's emit an error here, even if it will lead to duplication in some cases.
}
where
exact_nm_err = hang (ptext (sLit "The exact Name") <+> quotes (ppr name) <+> ptext (sLit "is not in scope"))
2 (vcat [ ptext (sLit "Probable cause: you used a unique Template Haskell name (NameU), ")
, ptext (sLit "perhaps via newName, but did not bind it")
, ptext (sLit "If that's it, then -ddump-splices might be useful") ])
dup_nm_err = hang (ptext (sLit "Duplicate exact Name") <+> quotes (ppr $ nameOccName name))
2 (vcat [ ptext (sLit "Probable cause: you used a unique Template Haskell name (NameU), ")
, ptext (sLit "perhaps via newName, but bound it multiple times")
, ptext (sLit "If that's it, then -ddump-splices might be useful") ])
-----------------------------------------------
lookupInstDeclBndr :: Name -> SDoc -> RdrName -> RnM Name
-- This is called on the method name on the left-hand side of an
-- instance declaration binding. eg. instance Functor T where
-- fmap = ...
-- ^^^^ called on this
-- Regardless of how many unqualified fmaps are in scope, we want
-- the one that comes from the Functor class.
--
-- Furthermore, note that we take no account of whether the
-- name is only in scope qualified. I.e. even if method op is
-- in scope as M.op, we still allow plain 'op' on the LHS of
-- an instance decl
--
-- The "what" parameter says "method" or "associated type",
-- depending on what we are looking up
lookupInstDeclBndr cls what rdr
= do { when (isQual rdr)
(addErr (badQualBndrErr rdr))
-- In an instance decl you aren't allowed
-- to use a qualified name for the method
-- (Although it'd make perfect sense.)
; lookupSubBndrOcc False -- False => we don't give deprecated
-- warnings when a deprecated class
-- method is defined. We only warn
-- when it's used
(ParentIs cls) doc rdr }
where
doc = what <+> ptext (sLit "of class") <+> quotes (ppr cls)
-----------------------------------------------
lookupFamInstName :: Maybe Name -> Located RdrName -> RnM (Located Name)
-- Used for TyData and TySynonym family instances only,
-- See Note [Family instance binders]
lookupFamInstName (Just cls) tc_rdr -- Associated type; c.f RnBinds.rnMethodBind
= wrapLocM (lookupInstDeclBndr cls (ptext (sLit "associated type"))) tc_rdr
lookupFamInstName Nothing tc_rdr -- Family instance; tc_rdr is an *occurrence*
= lookupLocatedOccRn tc_rdr
-----------------------------------------------
lookupConstructorFields :: Name -> RnM [Name]
-- Look up the fields of a given constructor
-- * For constructors from this module, use the record field env,
-- which is itself gathered from the (as yet un-typechecked)
-- data type decls
--
-- * For constructors from imported modules, use the *type* environment
-- since imported modles are already compiled, the info is conveniently
-- right there
lookupConstructorFields con_name
= do { this_mod <- getModule
; if nameIsLocalOrFrom this_mod con_name then
do { RecFields field_env _ <- getRecFieldEnv
; return (lookupNameEnv field_env con_name `orElse` []) }
else
do { con <- tcLookupDataCon con_name
; return (dataConFieldLabels con) } }
-----------------------------------------------
-- Used for record construction and pattern matching
-- When the -XDisambiguateRecordFields flag is on, take account of the
-- constructor name to disambiguate which field to use; it's just the
-- same as for instance decls
--
-- NB: Consider this:
-- module Foo where { data R = R { fld :: Int } }
-- module Odd where { import Foo; fld x = x { fld = 3 } }
-- Arguably this should work, because the reference to 'fld' is
-- unambiguous because there is only one field id 'fld' in scope.
-- But currently it's rejected.
lookupSubBndrOcc :: Bool
-> Parent -- NoParent => just look it up as usual
-- ParentIs p => use p to disambiguate
-> SDoc -> RdrName
-> RnM Name
lookupSubBndrOcc warnIfDeprec parent doc rdr_name
| Just n <- isExact_maybe rdr_name -- This happens in derived code
= lookupExactOcc n
| Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
= lookupOrig rdr_mod rdr_occ
| otherwise -- Find all the things the rdr-name maps to
= do { -- and pick the one with the right parent namep
env <- getGlobalRdrEnv
; case lookupSubBndrGREs env parent rdr_name of
-- NB: lookupGlobalRdrEnv, not lookupGRE_RdrName!
-- The latter does pickGREs, but we want to allow 'x'
-- even if only 'M.x' is in scope
[gre] -> do { addUsedRdrName warnIfDeprec gre (used_rdr_name gre)
-- Add a usage; this is an *occurrence* site
; return (gre_name gre) }
[] -> do { addErr (unknownSubordinateErr doc rdr_name)
; return (mkUnboundName rdr_name) }
gres -> do { addNameClashErrRn rdr_name gres
; return (gre_name (head gres)) } }
where
-- Note [Usage for sub-bndrs]
used_rdr_name gre
| isQual rdr_name = rdr_name
| otherwise = greRdrName gre
greRdrName :: GlobalRdrElt -> RdrName
greRdrName gre
= case gre_prov gre of
LocalDef -> unqual_rdr
Imported is -> used_rdr_name_from_is is
where
occ = nameOccName (gre_name gre)
unqual_rdr = mkRdrUnqual occ
used_rdr_name_from_is imp_specs -- rdr_name is unqualified
| not (all (is_qual . is_decl) imp_specs)
= unqual_rdr -- An unqualified import is available
| otherwise
= -- Only qualified imports available, so make up
-- a suitable qualifed name from the first imp_spec
--ASSERT( not (null imp_specs) )
mkRdrQual (is_as (is_decl (head imp_specs))) occ
lookupSubBndrGREs :: GlobalRdrEnv -> Parent -> RdrName -> [GlobalRdrElt]
-- If Parent = NoParent, just do a normal lookup
-- If Parent = Parent p then find all GREs that
-- (a) have parent p
-- (b) for Unqual, are in scope qualified or unqualified
-- for Qual, are in scope with that qualification
lookupSubBndrGREs env parent rdr_name
= case parent of
NoParent -> pickGREs rdr_name gres
ParentIs p
| isUnqual rdr_name -> filter (parent_is p) gres
| otherwise -> filter (parent_is p) (pickGREs rdr_name gres)
where
gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
parent_is p (GRE { gre_par = ParentIs p' }) = p == p'
parent_is _ _ = False
{-
Note [Family instance binders]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
data family F a
data instance F T = X1 | X2
The 'data instance' decl has an *occurrence* of F (and T), and *binds*
X1 and X2. (This is unlike a normal data type declaration which would
bind F too.) So we want an AvailTC F [X1,X2].
Now consider a similar pair:
class C a where
data G a
instance C S where
data G S = Y1 | Y2
The 'data G S' *binds* Y1 and Y2, and has an *occurrence* of G.
But there is a small complication: in an instance decl, we don't use
qualified names on the LHS; instead we use the class to disambiguate.
Thus:
module M where
import Blib( G )
class C a where
data G a
instance C S where
data G S = Y1 | Y2
Even though there are two G's in scope (M.G and Blib.G), the occurrence
of 'G' in the 'instance C S' decl is unambiguous, because C has only
one associated type called G. This is exactly what happens for methods,
and it is only consistent to do the same thing for types. That's the
role of the function lookupTcdName; the (Maybe Name) give the class of
the encloseing instance decl, if any.
Note [Looking up Exact RdrNames]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Exact RdrNames are generated by Template Haskell. See Note [Binders
in Template Haskell] in Convert.
For data types and classes have Exact system Names in the binding
positions for constructors, TyCons etc. For example
[d| data T = MkT Int |]
when we splice in and Convert to HsSyn RdrName, we'll get
data (Exact (system Name "T")) = (Exact (system Name "MkT")) ...
These System names are generated by Convert.thRdrName
But, constructors and the like need External Names, not System Names!
So we do the following
* In RnEnv.newGlobalBinder we spot Exact RdrNames that wrap a
non-External Name, and make an External name for it. This is
the name that goes in the GlobalRdrEnv
* When looking up an occurrence of an Exact name, done in
RnEnv.lookupExactOcc, we find the Name with the right unique in the
GlobalRdrEnv, and use the one from the envt -- it will be an
External Name in the case of the data type/constructor above.
* Exact names are also use for purely local binders generated
by TH, such as \x_33. x_33
Both binder and occurrence are Exact RdrNames. The occurrence
gets looked up in the LocalRdrEnv by RnEnv.lookupOccRn, and
misses, because lookupLocalRdrEnv always returns Nothing for
an Exact Name. Now we fall through to lookupExactOcc, which
will find the Name is not in the GlobalRdrEnv, so we just use
the Exact supplied Name.
Note [Splicing Exact names]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider the splice $(do { x <- newName "x"; return (VarE x) })
This will generate a (HsExpr RdrName) term that mentions the
Exact RdrName "x_56" (or whatever), but does not bind it. So
when looking such Exact names we want to check that it's in scope,
otherwise the type checker will get confused. To do this we need to
keep track of all the Names in scope, and the LocalRdrEnv does just that;
we consult it with RdrName.inLocalRdrEnvScope.
There is another wrinkle. With TH and -XDataKinds, consider
$( [d| data Nat = Zero
data T = MkT (Proxy 'Zero) |] )
After splicing, but before renaming we get this:
data Nat_77{tc} = Zero_78{d}
data T_79{tc} = MkT_80{d} (Proxy 'Zero_78{tc}) |] )
The occurrence of 'Zero in the data type for T has the right unique,
but it has a TcClsName name-space in its OccName. (This is set by
the ctxt_ns argument of Convert.thRdrName.) When we check that is
in scope in the GlobalRdrEnv, we need to look up the DataName namespace
too. (An alternative would be to make the GlobalRdrEnv also have
a Name -> GRE mapping.)
Note [Usage for sub-bndrs]
~~~~~~~~~~~~~~~~~~~~~~~~~~
If you have this
import qualified M( C( f ) )
instance M.C T where
f x = x
then is the qualified import M.f used? Obviously yes.
But the RdrName used in the instance decl is unqualified. In effect,
we fill in the qualification by looking for f's whose class is M.C
But when adding to the UsedRdrNames we must make that qualification
explicit (saying "used M.f"), otherwise we get "Redundant import of M.f".
So we make up a suitable (fake) RdrName. But be careful
import qualifed M
import M( C(f) )
instance C T where
f x = x
Here we want to record a use of 'f', not of 'M.f', otherwise
we'll miss the fact that the qualified import is redundant.
--------------------------------------------------
-- Occurrences
--------------------------------------------------
-}
getLookupOccRn :: RnM (Name -> Maybe Name)
getLookupOccRn
= do local_env <- getLocalRdrEnv
return (lookupLocalRdrOcc local_env . nameOccName)
lookupLocatedOccRn :: Located RdrName -> RnM (Located Name)
lookupLocatedOccRn = wrapLocM lookupOccRn
lookupLocalOccRn_maybe :: RdrName -> RnM (Maybe Name)
-- Just look in the local environment
lookupLocalOccRn_maybe rdr_name
= do { local_env <- getLocalRdrEnv
; return (lookupLocalRdrEnv local_env rdr_name) }
lookupLocalOccThLvl_maybe :: Name -> RnM (Maybe (TopLevelFlag, ThLevel))
-- Just look in the local environment
lookupLocalOccThLvl_maybe name
= do { lcl_env <- getLclEnv
; return (lookupNameEnv (tcl_th_bndrs lcl_env) name) }
-- lookupOccRn looks up an occurrence of a RdrName
lookupOccRn :: RdrName -> RnM Name
lookupOccRn rdr_name
= do { mb_name <- lookupOccRn_maybe rdr_name
; case mb_name of
Just name -> return name
Nothing -> reportUnboundName rdr_name }
lookupKindOccRn :: RdrName -> RnM Name
-- Looking up a name occurring in a kind
lookupKindOccRn rdr_name
= do { mb_name <- lookupOccRn_maybe rdr_name
; case mb_name of
Just name -> return name
Nothing -> reportUnboundName rdr_name }
-- lookupPromotedOccRn looks up an optionally promoted RdrName.
lookupTypeOccRn :: RdrName -> RnM Name
-- see Note [Demotion]
lookupTypeOccRn rdr_name
= do { mb_name <- lookupOccRn_maybe rdr_name
; case mb_name of {
Just name -> return name ;
Nothing -> lookup_demoted rdr_name } }
lookup_demoted :: RdrName -> RnM Name
lookup_demoted rdr_name
| Just demoted_rdr <- demoteRdrName rdr_name
-- Maybe it's the name of a *data* constructor
= do { data_kinds <- xoptM Opt_DataKinds
; mb_demoted_name <- lookupOccRn_maybe demoted_rdr
; case mb_demoted_name of
Nothing -> reportUnboundName rdr_name
Just demoted_name
| data_kinds ->
do { whenWOptM Opt_WarnUntickedPromotedConstructors $
addWarn (untickedPromConstrWarn demoted_name)
; return demoted_name }
| otherwise -> unboundNameX WL_Any rdr_name suggest_dk }
| otherwise
= reportUnboundName rdr_name
where
suggest_dk = ptext (sLit "A data constructor of that name is in scope; did you mean DataKinds?")
untickedPromConstrWarn name =
text "Unticked promoted constructor" <> colon <+> quotes (ppr name) <> dot
$$
hsep [ text "Use"
, quotes (char '\'' <> ppr name)
, text "instead of"
, quotes (ppr name) <> dot ]
{-
Note [Demotion]
~~~~~~~~~~~~~~~
When the user writes:
data Nat = Zero | Succ Nat
foo :: f Zero -> Int
'Zero' in the type signature of 'foo' is parsed as:
HsTyVar ("Zero", TcClsName)
When the renamer hits this occurrence of 'Zero' it's going to realise
that it's not in scope. But because it is renaming a type, it knows
that 'Zero' might be a promoted data constructor, so it will demote
its namespace to DataName and do a second lookup.
The final result (after the renamer) will be:
HsTyVar ("Zero", DataName)
-}
-- Use this version to get tracing
--
-- lookupOccRn_maybe, lookupOccRn_maybe' :: RdrName -> RnM (Maybe Name)
-- lookupOccRn_maybe rdr_name
-- = do { mb_res <- lookupOccRn_maybe' rdr_name
-- ; gbl_rdr_env <- getGlobalRdrEnv
-- ; local_rdr_env <- getLocalRdrEnv
-- ; traceRn $ text "lookupOccRn_maybe" <+>
-- vcat [ ppr rdr_name <+> ppr (getUnique (rdrNameOcc rdr_name))
-- , ppr mb_res
-- , text "Lcl env" <+> ppr local_rdr_env
-- , text "Gbl env" <+> ppr [ (getUnique (nameOccName (gre_name (head gres'))),gres') | gres <- occEnvElts gbl_rdr_env
-- , let gres' = filter isLocalGRE gres, not (null gres') ] ]
-- ; return mb_res }
lookupOccRn_maybe :: RdrName -> RnM (Maybe Name)
-- lookupOccRn looks up an occurrence of a RdrName
lookupOccRn_maybe rdr_name
= do { local_env <- getLocalRdrEnv
; case lookupLocalRdrEnv local_env rdr_name of {
Just name -> return (Just name) ;
Nothing -> do
{ mb_name <- lookupGlobalOccRn_maybe rdr_name
; case mb_name of {
Just name -> return (Just name) ;
Nothing -> do
{ ns <- lookupQualifiedNameGHCi rdr_name
-- This test is not expensive,
-- and only happens for failed lookups
; case ns of
(n:_) -> return (Just n) -- Unlikely to be more than one...?
[] -> return Nothing } } } } }
lookupGlobalOccRn :: RdrName -> RnM Name
-- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
-- environment. Adds an error message if the RdrName is not in scope.
lookupGlobalOccRn rdr_name
= do { mb_name <- lookupGlobalOccRn_maybe rdr_name
; case mb_name of
Just n -> return n
Nothing -> do { traceRn (text "lookupGlobalOccRn" <+> ppr rdr_name)
; unboundName WL_Global rdr_name } }
lookupInfoOccRn :: RdrName -> RnM [Name]
-- lookupInfoOccRn is intended for use in GHCi's ":info" command
-- It finds all the GREs that RdrName could mean, not complaining
-- about ambiguity, but rather returning them all
-- C.f. Trac #9881
lookupInfoOccRn rdr_name
| Just n <- isExact_maybe rdr_name -- e.g. (->)
= return [n]
| Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
= do { n <- lookupOrig rdr_mod rdr_occ
; return [n] }
| otherwise
= do { rdr_env <- getGlobalRdrEnv
; let ns = map gre_name (lookupGRE_RdrName rdr_name rdr_env)
; qual_ns <- lookupQualifiedNameGHCi rdr_name
; return (ns ++ (qual_ns `minusList` ns)) }
lookupGlobalOccRn_maybe :: RdrName -> RnM (Maybe Name)
-- No filter function; does not report an error on failure
lookupGlobalOccRn_maybe rdr_name
| Just n <- isExact_maybe rdr_name -- This happens in derived code
= do { n' <- lookupExactOcc n; return (Just n') }
| Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
= do { n <- lookupOrig rdr_mod rdr_occ
; return (Just n) }
| otherwise
= do { mb_gre <- lookupGreRn_maybe rdr_name
; case mb_gre of
Nothing -> return Nothing
Just gre -> return (Just (gre_name gre)) }
--------------------------------------------------
-- Lookup in the Global RdrEnv of the module
--------------------------------------------------
lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
-- Just look up the RdrName in the GlobalRdrEnv
lookupGreRn_maybe rdr_name
= lookupGreRn_help rdr_name (lookupGRE_RdrName rdr_name)
lookupGreRn :: RdrName -> RnM GlobalRdrElt
-- If not found, add error message, and return a fake GRE
lookupGreRn rdr_name
= do { mb_gre <- lookupGreRn_maybe rdr_name
; case mb_gre of {
Just gre -> return gre ;
Nothing -> do
{ traceRn (text "lookupGreRn" <+> ppr rdr_name)
; name <- unboundName WL_Global rdr_name
; return (GRE { gre_name = name, gre_par = NoParent,
gre_prov = LocalDef }) }}}
lookupGreLocalRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
-- Similar, but restricted to locally-defined things
lookupGreLocalRn_maybe rdr_name
= lookupGreRn_help rdr_name lookup_fn
where
lookup_fn env = filter isLocalGRE (lookupGRE_RdrName rdr_name env)
lookupGreRn_help :: RdrName -- Only used in error message
-> (GlobalRdrEnv -> [GlobalRdrElt]) -- Lookup function
-> RnM (Maybe GlobalRdrElt)
-- Checks for exactly one match; reports deprecations
-- Returns Nothing, without error, if too few
lookupGreRn_help rdr_name lookup
= do { env <- getGlobalRdrEnv
; case lookup env of
[] -> return Nothing
[gre] -> do { addUsedRdrName True gre rdr_name
; return (Just gre) }
gres -> do { addNameClashErrRn rdr_name gres
; return (Just (head gres)) } }
{-
*********************************************************
* *
Deprecations
* *
*********************************************************
Note [Handling of deprecations]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* We report deprecations at each *occurrence* of the deprecated thing
(see Trac #5867)
* We do not report deprectations for locally-definded names. For a
start, we may be exporting a deprecated thing. Also we may use a
deprecated thing in the defn of another deprecated things. We may
even use a deprecated thing in the defn of a non-deprecated thing,
when changing a module's interface.
* addUsedRdrNames: we do not report deprecations for sub-binders:
- the ".." completion for records
- the ".." in an export item 'T(..)'
- the things exported by a module export 'module M'
-}
addUsedRdrName :: Bool -> GlobalRdrElt -> RdrName -> RnM ()
-- Record usage of imported RdrNames
addUsedRdrName warnIfDeprec gre rdr
| isLocalGRE gre = return () -- No call to warnIfDeprecated
-- See Note [Handling of deprecations]
| otherwise = do { env <- getGblEnv
; when warnIfDeprec $ warnIfDeprecated gre
; updMutVar (tcg_used_rdrnames env)
(\s -> Set.insert rdr s) }
addUsedRdrNames :: [RdrName] -> RnM ()
-- Record used sub-binders
-- We don't check for imported-ness here, because it's inconvenient
-- and not stritly necessary.
-- NB: no call to warnIfDeprecated; see Note [Handling of deprecations]
addUsedRdrNames rdrs
= do { env <- getGblEnv
; updMutVar (tcg_used_rdrnames env)
(\s -> foldr Set.insert s rdrs) }
warnIfDeprecated :: GlobalRdrElt -> RnM ()
warnIfDeprecated gre@(GRE { gre_name = name, gre_prov = Imported (imp_spec : _) })
= do { dflags <- getDynFlags
; when (wopt Opt_WarnWarningsDeprecations dflags) $
do { iface <- loadInterfaceForName doc name
; case lookupImpDeprec iface gre of
Just txt -> addWarn (mk_msg txt)
Nothing -> return () } }
where
mk_msg txt = sep [ sep [ ptext (sLit "In the use of")
<+> pprNonVarNameSpace (occNameSpace (nameOccName name))
<+> quotes (ppr name)
, parens imp_msg <> colon ]
, ppr txt ]
name_mod = {-ASSERT2( isExternalName name, ppr name )-} nameModule name
imp_mod = importSpecModule imp_spec
imp_msg = ptext (sLit "imported from") <+> ppr imp_mod <> extra
extra | imp_mod == moduleName name_mod = Outputable.empty
| otherwise = ptext (sLit ", but defined in") <+> ppr name_mod
doc = ptext (sLit "The name") <+> quotes (ppr name) <+> ptext (sLit "is mentioned explicitly")
warnIfDeprecated _ = return () -- No deprecations for things defined locally
lookupImpDeprec :: ModIface -> GlobalRdrElt -> Maybe WarningTxt
lookupImpDeprec iface gre
= mi_warn_fn iface (gre_name gre) `mplus` -- Bleat if the thing,
case gre_par gre of -- or its parent, is warn'd
ParentIs p -> mi_warn_fn iface p
NoParent -> Nothing
{-
Note [Used names with interface not loaded]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It's (just) possible to find a used
Name whose interface hasn't been loaded:
a) It might be a WiredInName; in that case we may not load
its interface (although we could).
b) It might be GHC.Real.fromRational, or GHC.Num.fromInteger
These are seen as "used" by the renamer (if -XRebindableSyntax)
is on), but the typechecker may discard their uses
if in fact the in-scope fromRational is GHC.Read.fromRational,
(see tcPat.tcOverloadedLit), and the typechecker sees that the type
is fixed, say, to GHC.Base.Float (see Inst.lookupSimpleInst).
In that obscure case it won't force the interface in.
In both cases we simply don't permit deprecations;
this is, after all, wired-in stuff.
*********************************************************
* *
GHCi support
* *
*********************************************************
A qualified name on the command line can refer to any module at
all: we try to load the interface if we don't already have it, just
as if there was an "import qualified M" declaration for every
module.
If we fail we just return Nothing, rather than bleating
about "attempting to use module ‘D’ (./D.hs) which is not loaded"
which is what loadSrcInterface does.
Note [Safe Haskell and GHCi]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We DONT do this Safe Haskell as we need to check imports. We can
and should instead check the qualified import but at the moment
this requires some refactoring so leave as a TODO
-}
lookupQualifiedNameGHCi :: RdrName -> RnM [Name]
lookupQualifiedNameGHCi rdr_name
= -- We want to behave as we would for a source file import here,
-- and respect hiddenness of modules/packages, hence loadSrcInterface.
do { dflags <- getDynFlags
; is_ghci <- getIsGHCi
; go_for_it dflags is_ghci }
where
go_for_it dflags is_ghci
| Just (mod,occ) <- isQual_maybe rdr_name
, is_ghci
, gopt Opt_ImplicitImportQualified dflags -- Enables this GHCi behaviour
, not (safeDirectImpsReq dflags) -- See Note [Safe Haskell and GHCi]
= do { res <- loadSrcInterface_maybe doc mod False Nothing
; case res of
Succeeded ifaces
-> return [ name
| iface <- ifaces
, avail <- mi_exports iface
, name <- availNames avail
, nameOccName name == occ ]
_ -> -- Either we couldn't load the interface, or
-- we could but we didn't find the name in it
do { traceRn (text "lookupQualifiedNameGHCi" <+> ppr rdr_name)
; return [] } }
| otherwise
= return []
doc = ptext (sLit "Need to find") <+> ppr rdr_name
{-
Note [Looking up signature names]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
lookupSigOccRn is used for type signatures and pragmas
Is this valid?
module A
import M( f )
f :: Int -> Int
f x = x
It's clear that the 'f' in the signature must refer to A.f
The Haskell98 report does not stipulate this, but it will!
So we must treat the 'f' in the signature in the same way
as the binding occurrence of 'f', using lookupBndrRn
However, consider this case:
import M( f )
f :: Int -> Int
g x = x
We don't want to say 'f' is out of scope; instead, we want to
return the imported 'f', so that later on the reanamer will
correctly report "misplaced type sig".
Note [Signatures for top level things]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
data HsSigCtxt = ... | TopSigCtxt NameSet Bool | ....
* The NameSet says what is bound in this group of bindings.
We can't use isLocalGRE from the GlobalRdrEnv, because of this:
f x = x
$( ...some TH splice... )
f :: Int -> Int
When we encounter the signature for 'f', the binding for 'f'
will be in the GlobalRdrEnv, and will be a LocalDef. Yet the
signature is mis-placed
* The Bool says whether the signature is ok for a class method
or record selector. Consider
infix 3 `f` -- Yes, ok
f :: C a => a -> a -- No, not ok
class C a where
f :: a -> a
-}
data HsSigCtxt
= TopSigCtxt NameSet Bool -- At top level, binding these names
-- See Note [Signatures for top level things]
-- Bool <=> ok to give sig for
-- class method or record selctor
| LocalBindCtxt NameSet -- In a local binding, binding these names
| ClsDeclCtxt Name -- Class decl for this class
| InstDeclCtxt Name -- Intsance decl for this class
| HsBootCtxt -- Top level of a hs-boot file
| RoleAnnotCtxt NameSet -- A role annotation, with the names of all types
-- in the group
lookupSigOccRn :: HsSigCtxt
-> Sig RdrName
-> Located RdrName -> RnM (Located Name)
lookupSigOccRn ctxt sig = lookupSigCtxtOccRn ctxt (hsSigDoc sig)
-- | Lookup a name in relation to the names in a 'HsSigCtxt'
lookupSigCtxtOccRn :: HsSigCtxt
-> SDoc -- ^ description of thing we're looking up,
-- like "type family"
-> Located RdrName -> RnM (Located Name)
lookupSigCtxtOccRn ctxt what
= wrapLocM $ \ rdr_name ->
do { mb_name <- lookupBindGroupOcc ctxt what rdr_name
; case mb_name of
Left err -> do { addErr err; return (mkUnboundName rdr_name) }
Right name -> return name }
lookupBindGroupOcc :: HsSigCtxt
-> SDoc
-> RdrName -> RnM (Either MsgDoc Name)
-- Looks up the RdrName, expecting it to resolve to one of the
-- bound names passed in. If not, return an appropriate error message
--
-- See Note [Looking up signature names]
lookupBindGroupOcc ctxt what rdr_name
| Just n <- isExact_maybe rdr_name
= lookupExactOcc_either n -- allow for the possibility of missing Exacts;
-- see Note [dataTcOccs and Exact Names]
-- Maybe we should check the side conditions
-- but it's a pain, and Exact things only show
-- up when you know what you are doing
| Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
= do { n' <- lookupOrig rdr_mod rdr_occ
; return (Right n') }
| otherwise
= case ctxt of
HsBootCtxt -> lookup_top (const True) True
TopSigCtxt ns meth_ok -> lookup_top (`elemNameSet` ns) meth_ok
RoleAnnotCtxt ns -> lookup_top (`elemNameSet` ns) False
LocalBindCtxt ns -> lookup_group ns
ClsDeclCtxt cls -> lookup_cls_op cls
InstDeclCtxt cls -> lookup_cls_op cls
where
lookup_cls_op cls
= do { env <- getGlobalRdrEnv
; let gres = lookupSubBndrGREs env (ParentIs cls) rdr_name
; case gres of
[] -> return (Left (unknownSubordinateErr doc rdr_name))
(gre:_) -> return (Right (gre_name gre)) }
-- If there is more than one local GRE for the
-- same OccName 'f', that will be reported separately
-- as a duplicate top-level binding for 'f'
where
doc = ptext (sLit "method of class") <+> quotes (ppr cls)
lookup_top keep_me meth_ok
= do { env <- getGlobalRdrEnv
; let all_gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
; case filter (keep_me . gre_name) all_gres of
[] | null all_gres -> bale_out_with Outputable.empty
| otherwise -> bale_out_with local_msg
(gre:_)
| ParentIs {} <- gre_par gre
, not meth_ok
-> bale_out_with sub_msg
| otherwise
-> return (Right (gre_name gre)) }
lookup_group bound_names -- Look in the local envt (not top level)
= do { local_env <- getLocalRdrEnv
; case lookupLocalRdrEnv local_env rdr_name of
Just n
| n `elemNameSet` bound_names -> return (Right n)
| otherwise -> bale_out_with local_msg
Nothing -> bale_out_with Outputable.empty }
bale_out_with msg
= return (Left (sep [ ptext (sLit "The") <+> what
<+> ptext (sLit "for") <+> quotes (ppr rdr_name)
, nest 2 $ ptext (sLit "lacks an accompanying binding")]
$$ nest 2 msg))
local_msg = parens $ ptext (sLit "The") <+> what <+> ptext (sLit "must be given where")
<+> quotes (ppr rdr_name) <+> ptext (sLit "is declared")
sub_msg = parens $ ptext (sLit "You cannot give a") <+> what
<+> ptext (sLit "for a record selector or class method")
---------------
lookupLocalTcNames :: HsSigCtxt -> SDoc -> RdrName -> RnM [Name]
-- GHC extension: look up both the tycon and data con or variable.
-- Used for top-level fixity signatures and deprecations.
-- Complain if neither is in scope.
-- See Note [Fixity signature lookup]
lookupLocalTcNames ctxt what rdr_name
= do { mb_gres <- mapM lookup (dataTcOccs rdr_name)
; let (errs, names) = splitEithers mb_gres
; when (null names) $ addErr (head errs) -- Bleat about one only
; return names }
where
lookup = lookupBindGroupOcc ctxt what
dataTcOccs :: RdrName -> [RdrName]
-- Return both the given name and the same name promoted to the TcClsName
-- namespace. This is useful when we aren't sure which we are looking at.
-- See also Note [dataTcOccs and Exact Names]
dataTcOccs rdr_name
| isDataOcc occ || isVarOcc occ
= [rdr_name, rdr_name_tc]
| otherwise
= [rdr_name]
where
occ = rdrNameOcc rdr_name
rdr_name_tc = setRdrNameSpace rdr_name tcName
{-
Note [dataTcOccs and Exact Names]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Exact RdrNames can occur in code generated by Template Haskell, and generally
those references are, well, exact. However, the TH `Name` type isn't expressive
enough to always track the correct namespace information, so we sometimes get
the right Unique but wrong namespace. Thus, we still have to do the double-lookup
for Exact RdrNames.
There is also an awkward situation for built-in syntax. Example in GHCi
:info []
This parses as the Exact RdrName for nilDataCon, but we also want
the list type constructor.
Note that setRdrNameSpace on an Exact name requires the Name to be External,
which it always is for built in syntax.
*********************************************************
* *
Fixities
* *
*********************************************************
Note [Fixity signature lookup]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A fixity declaration like
infixr 2 ?
can refer to a value-level operator, e.g.:
(?) :: String -> String -> String
or a type-level operator, like:
data (?) a b = A a | B b
so we extend the lookup of the reader name '?' to the TcClsName namespace, as
well as the original namespace.
The extended lookup is also used in other places, like resolution of
deprecation declarations, and lookup of names in GHCi.
-}
--------------------------------
type MiniFixityEnv = FastStringEnv (Located Fixity)
-- Mini fixity env for the names we're about
-- to bind, in a single binding group
--
-- It is keyed by the *FastString*, not the *OccName*, because
-- the single fixity decl infix 3 T
-- affects both the data constructor T and the type constrctor T
--
-- We keep the location so that if we find
-- a duplicate, we can report it sensibly
--------------------------------
-- Used for nested fixity decls to bind names along with their fixities.
-- the fixities are given as a UFM from an OccName's FastString to a fixity decl
addLocalFixities :: MiniFixityEnv -> [Name] -> RnM a -> RnM a
addLocalFixities mini_fix_env names thing_inside
= extendFixityEnv (mapMaybe find_fixity names) thing_inside
where
find_fixity name
= case lookupFsEnv mini_fix_env (occNameFS occ) of
Just (L _ fix) -> Just (name, FixItem occ fix)
Nothing -> Nothing
where
occ = nameOccName name
{-
--------------------------------
lookupFixity is a bit strange.
* Nested local fixity decls are put in the local fixity env, which we
find with getFixtyEnv
* Imported fixities are found in the HIT or PIT
* Top-level fixity decls in this module may be for Names that are
either Global (constructors, class operations)
or Local/Exported (everything else)
(See notes with RnNames.getLocalDeclBinders for why we have this split.)
We put them all in the local fixity environment
-}
lookupFixityRn :: Name -> RnM Fixity
lookupFixityRn name
| isUnboundName name
= return (Fixity minPrecedence InfixL)
-- Minimise errors from ubound names; eg
-- a>0 `foo` b>0
-- where 'foo' is not in scope, should not give an error (Trac #7937)
| otherwise
= do { local_fix_env <- getFixityEnv
; case lookupNameEnv local_fix_env name of {
Just (FixItem _ fix) -> return fix ;
Nothing ->
do { this_mod <- getModule
; if nameIsLocalOrFrom this_mod name
-- Local (and interactive) names are all in the
-- fixity env, and don't have entries in the HPT
then return defaultFixity
else lookup_imported } } }
where
lookup_imported
-- For imported names, we have to get their fixities by doing a
-- loadInterfaceForName, and consulting the Ifaces that comes back
-- from that, because the interface file for the Name might not
-- have been loaded yet. Why not? Suppose you import module A,
-- which exports a function 'f', thus;
-- module CurrentModule where
-- import A( f )
-- module A( f ) where
-- import B( f )
-- Then B isn't loaded right away (after all, it's possible that
-- nothing from B will be used). When we come across a use of
-- 'f', we need to know its fixity, and it's then, and only
-- then, that we load B.hi. That is what's happening here.
--
-- loadInterfaceForName will find B.hi even if B is a hidden module,
-- and that's what we want.
= do { iface <- loadInterfaceForName doc name
; traceRn (text "lookupFixityRn: looking up name in iface cache and found:" <+>
vcat [ppr name, ppr $ mi_fix_fn iface (nameOccName name)])
; return (mi_fix_fn iface (nameOccName name)) }
doc = ptext (sLit "Checking fixity for") <+> ppr name
---------------
lookupTyFixityRn :: Located Name -> RnM Fixity
lookupTyFixityRn (L _ n) = lookupFixityRn n
{-
************************************************************************
* *
Rebindable names
Dealing with rebindable syntax is driven by the
Opt_RebindableSyntax dynamic flag.
In "deriving" code we don't want to use rebindable syntax
so we switch off the flag locally
* *
************************************************************************
Haskell 98 says that when you say "3" you get the "fromInteger" from the
Standard Prelude, regardless of what is in scope. However, to experiment
with having a language that is less coupled to the standard prelude, we're
trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
happens to be in scope. Then you can
import Prelude ()
import MyPrelude as Prelude
to get the desired effect.
At the moment this just happens for
* fromInteger, fromRational on literals (in expressions and patterns)
* negate (in expressions)
* minus (arising from n+k patterns)
* "do" notation
We store the relevant Name in the HsSyn tree, in
* HsIntegral/HsFractional/HsIsString
* NegApp
* NPlusKPat
* HsDo
respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
fromRationalName etc), but the renamer changes this to the appropriate user
name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
We treat the orignal (standard) names as free-vars too, because the type checker
checks the type of the user thing against the type of the standard thing.
-}
lookupIfThenElse :: RnM (Maybe (SyntaxExpr Name), FreeVars)
-- Different to lookupSyntaxName because in the non-rebindable
-- case we desugar directly rather than calling an existing function
-- Hence the (Maybe (SyntaxExpr Name)) return type
lookupIfThenElse
= do { rebind <- xoptM Opt_RebindableSyntax
; if not rebind
then return (Nothing, emptyFVs)
else do { ite <- lookupOccRn (mkVarUnqual (fsLit "ifThenElse"))
; return (Just (HsVar ite), unitFV ite) } }
lookupSyntaxName :: Name -- The standard name
-> RnM (SyntaxExpr Name, FreeVars) -- Possibly a non-standard name
lookupSyntaxName std_name
= do { rebindable_on <- xoptM Opt_RebindableSyntax
; if not rebindable_on then
return (HsVar std_name, emptyFVs)
else
-- Get the similarly named thing from the local environment
do { usr_name <- lookupOccRn (mkRdrUnqual (nameOccName std_name))
; return (HsVar usr_name, unitFV usr_name) } }
lookupSyntaxNames :: [Name] -- Standard names
-> RnM ([HsExpr Name], FreeVars) -- See comments with HsExpr.ReboundNames
lookupSyntaxNames std_names
= do { rebindable_on <- xoptM Opt_RebindableSyntax
; if not rebindable_on then
return (map HsVar std_names, emptyFVs)
else
do { usr_names <- mapM (lookupOccRn . mkRdrUnqual . nameOccName) std_names
; return (map HsVar usr_names, mkFVs usr_names) } }
{-
*********************************************************
* *
\subsection{Binding}
* *
*********************************************************
-}
newLocalBndrRn :: Located RdrName -> RnM Name
-- Used for non-top-level binders. These should
-- never be qualified.
newLocalBndrRn (L loc rdr_name)
| Just name <- isExact_maybe rdr_name
= return name -- This happens in code generated by Template Haskell
-- See Note [Binders in Template Haskell] in Convert.lhs
| otherwise
= do { unless (isUnqual rdr_name)
(addErrAt loc (badQualBndrErr rdr_name))
; uniq <- newUnique
; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }
newLocalBndrsRn :: [Located RdrName] -> RnM [Name]
newLocalBndrsRn = mapM newLocalBndrRn
---------------------
bindLocatedLocalsRn :: [Located RdrName]
-> ([Name] -> RnM a)
-> RnM a
bindLocatedLocalsRn rdr_names_w_loc enclosed_scope
= do { checkDupRdrNames rdr_names_w_loc
; checkShadowedRdrNames rdr_names_w_loc
-- Make fresh Names and extend the environment
; names <- newLocalBndrsRn rdr_names_w_loc
; bindLocalNames names (enclosed_scope names) }
bindLocalNames :: [Name] -> RnM a -> RnM a
bindLocalNames names enclosed_scope
= do { lcl_env <- getLclEnv
; let th_level = thLevel (tcl_th_ctxt lcl_env)
th_bndrs' = extendNameEnvList (tcl_th_bndrs lcl_env)
[ (n, (NotTopLevel, th_level)) | n <- names ]
rdr_env' = extendLocalRdrEnvList (tcl_rdr lcl_env) names
; setLclEnv (lcl_env { tcl_th_bndrs = th_bndrs'
, tcl_rdr = rdr_env' })
enclosed_scope }
bindLocalNamesFV :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
bindLocalNamesFV names enclosed_scope
= do { (result, fvs) <- bindLocalNames names enclosed_scope
; return (result, delFVs names fvs) }
-------------------------------------
-- binLocalsFVRn is the same as bindLocalsRn
-- except that it deals with free vars
bindLocatedLocalsFV :: [Located RdrName]
-> ([Name] -> RnM (a,FreeVars)) -> RnM (a, FreeVars)
bindLocatedLocalsFV rdr_names enclosed_scope
= bindLocatedLocalsRn rdr_names $ \ names ->
do (thing, fvs) <- enclosed_scope names
return (thing, delFVs names fvs)
-------------------------------------
extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
-- This function is used only in rnSourceDecl on InstDecl
extendTyVarEnvFVRn tyvars thing_inside = bindLocalNamesFV tyvars thing_inside
-------------------------------------
checkDupRdrNames :: [Located RdrName] -> RnM ()
-- Check for duplicated names in a binding group
checkDupRdrNames rdr_names_w_loc
= mapM_ (dupNamesErr getLoc) dups
where
(_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc
checkDupNames :: [Name] -> RnM ()
-- Check for duplicated names in a binding group
checkDupNames names = check_dup_names (filterOut isSystemName names)
-- See Note [Binders in Template Haskell] in Convert
check_dup_names :: [Name] -> RnM ()
check_dup_names names
= mapM_ (dupNamesErr nameSrcSpan) dups
where
(_, dups) = removeDups (\n1 n2 -> nameOccName n1 `compare` nameOccName n2) names
---------------------
checkShadowedRdrNames :: [Located RdrName] -> RnM ()
checkShadowedRdrNames loc_rdr_names
= do { envs <- getRdrEnvs
; checkShadowedOccs envs get_loc_occ filtered_rdrs }
where
filtered_rdrs = filterOut (isExact . unLoc) loc_rdr_names
-- See Note [Binders in Template Haskell] in Convert
get_loc_occ (L loc rdr) = (loc,rdrNameOcc rdr)
checkDupAndShadowedNames :: (GlobalRdrEnv, LocalRdrEnv) -> [Name] -> RnM ()
checkDupAndShadowedNames envs names
= do { check_dup_names filtered_names
; checkShadowedOccs envs get_loc_occ filtered_names }
where
filtered_names = filterOut isSystemName names
-- See Note [Binders in Template Haskell] in Convert
get_loc_occ name = (nameSrcSpan name, nameOccName name)
-------------------------------------
checkShadowedOccs :: (GlobalRdrEnv, LocalRdrEnv)
-> (a -> (SrcSpan, OccName))
-> [a] -> RnM ()
checkShadowedOccs (global_env,local_env) get_loc_occ ns
= whenWOptM Opt_WarnNameShadowing $
do { traceRn (text "shadow" <+> ppr (map get_loc_occ ns))
; mapM_ check_shadow ns }
where
check_shadow n
| startsWithUnderscore occ = return () -- Do not report shadowing for "_x"
-- See Trac #3262
| Just n <- mb_local = complain [ptext (sLit "bound at") <+> ppr (nameSrcLoc n)]
| otherwise = do { gres' <- filterM is_shadowed_gre gres
; complain (map pprNameProvenance gres') }
where
(loc,occ) = get_loc_occ n
mb_local = lookupLocalRdrOcc local_env occ
gres = lookupGRE_RdrName (mkRdrUnqual occ) global_env
-- Make an Unqualified RdrName and look that up, so that
-- we don't find any GREs that are in scope qualified-only
complain [] = return ()
complain pp_locs = addWarnAt loc (shadowedNameWarn occ pp_locs)
is_shadowed_gre :: GlobalRdrElt -> RnM Bool
-- Returns False for record selectors that are shadowed, when
-- punning or wild-cards are on (cf Trac #2723)
is_shadowed_gre gre@(GRE { gre_par = ParentIs _ })
= do { dflags <- getDynFlags
; if (xopt Opt_RecordPuns dflags || xopt Opt_RecordWildCards dflags)
then do { is_fld <- is_rec_fld gre; return (not is_fld) }
else return True }
is_shadowed_gre _other = return True
is_rec_fld gre -- Return True for record selector ids
| isLocalGRE gre = do { RecFields _ fld_set <- getRecFieldEnv
; return (gre_name gre `elemNameSet` fld_set) }
| otherwise = do { sel_id <- tcLookupField (gre_name gre)
; return (isRecordSelector sel_id) }
{-
************************************************************************
* *
What to do when a lookup fails
* *
************************************************************************
-}
data WhereLooking = WL_Any -- Any binding
| WL_Global -- Any top-level binding (local or imported)
| WL_LocalTop -- Any top-level binding in this module
reportUnboundName :: RdrName -> RnM Name
reportUnboundName rdr = unboundName WL_Any rdr
unboundName :: WhereLooking -> RdrName -> RnM Name
unboundName wl rdr = unboundNameX wl rdr Outputable.empty
unboundNameX :: WhereLooking -> RdrName -> SDoc -> RnM Name
unboundNameX where_look rdr_name extra
= do { show_helpful_errors <- goptM Opt_HelpfulErrors
; let what = pprNonVarNameSpace (occNameSpace (rdrNameOcc rdr_name))
err = unknownNameErr what rdr_name $$ extra
; if not show_helpful_errors
then addErr err
else do { suggestions <- unknownNameSuggestErr where_look rdr_name
; addErr (err $$ suggestions) }
; return (mkUnboundName rdr_name) }
unknownNameErr :: SDoc -> RdrName -> SDoc
unknownNameErr what rdr_name
= vcat [ hang (ptext (sLit "Not in scope:"))
2 (what <+> quotes (ppr rdr_name))
, extra ]
where
extra | rdr_name == forall_tv_RDR = perhapsForallMsg
| otherwise = Outputable.empty
type HowInScope = Either SrcSpan ImpDeclSpec
-- Left loc => locally bound at loc
-- Right ispec => imported as specified by ispec
unknownNameSuggestErr :: WhereLooking -> RdrName -> RnM SDoc
unknownNameSuggestErr where_look tried_rdr_name
= do { local_env <- getLocalRdrEnv
; global_env <- getGlobalRdrEnv
; dflags <- getDynFlags
; let all_possibilities :: [(String, (RdrName, HowInScope))]
all_possibilities
= [ (showPpr dflags r, (r, Left loc))
| (r,loc) <- local_possibilities local_env ]
++ [ (showPpr dflags r, rp) | (r, rp) <- global_possibilities global_env ]
suggest = fuzzyLookup (showPpr dflags tried_rdr_name) all_possibilities
perhaps = ptext (sLit "Perhaps you meant")
extra_err = case suggest of
[] -> Outputable.empty
[p] -> perhaps <+> pp_item p
ps -> sep [ perhaps <+> ptext (sLit "one of these:")
, nest 2 (pprWithCommas pp_item ps) ]
; return extra_err }
where
pp_item :: (RdrName, HowInScope) -> SDoc
pp_item (rdr, Left loc) = pp_ns rdr <+> quotes (ppr rdr) <+> loc' -- Locally defined
where loc' = case loc of
UnhelpfulSpan l -> parens (ppr l)
RealSrcSpan l -> parens (ptext (sLit "line") <+> int (srcSpanStartLine l))
pp_item (rdr, Right is) = pp_ns rdr <+> quotes (ppr rdr) <+> -- Imported
parens (ptext (sLit "imported from") <+> ppr (is_mod is))
pp_ns :: RdrName -> SDoc
pp_ns rdr | ns /= tried_ns = pprNameSpace ns
| otherwise = Outputable.empty
where ns = rdrNameSpace rdr
tried_occ = rdrNameOcc tried_rdr_name
tried_is_sym = isSymOcc tried_occ
tried_ns = occNameSpace tried_occ
tried_is_qual = isQual tried_rdr_name
correct_name_space occ = nameSpacesRelated (occNameSpace occ) tried_ns
&& isSymOcc occ == tried_is_sym
-- Treat operator and non-operators as non-matching
-- This heuristic avoids things like
-- Not in scope 'f'; perhaps you meant '+' (from Prelude)
local_ok = case where_look of { WL_Any -> True; _ -> False }
local_possibilities :: LocalRdrEnv -> [(RdrName, SrcSpan)]
local_possibilities env
| tried_is_qual = []
| not local_ok = []
| otherwise = [ (mkRdrUnqual occ, nameSrcSpan name)
| name <- localRdrEnvElts env
, let occ = nameOccName name
, correct_name_space occ]
gre_ok :: GlobalRdrElt -> Bool
gre_ok = case where_look of
WL_LocalTop -> isLocalGRE
_ -> \_ -> True
global_possibilities :: GlobalRdrEnv -> [(RdrName, (RdrName, HowInScope))]
global_possibilities global_env
| tried_is_qual = [ (rdr_qual, (rdr_qual, how))
| gre <- globalRdrEnvElts global_env
, gre_ok gre
, let name = gre_name gre
occ = nameOccName name
, correct_name_space occ
, (mod, how) <- quals_in_scope name (gre_prov gre)
, let rdr_qual = mkRdrQual mod occ ]
| otherwise = [ (rdr_unqual, pair)
| gre <- globalRdrEnvElts global_env
, gre_ok gre
, let name = gre_name gre
prov = gre_prov gre
occ = nameOccName name
rdr_unqual = mkRdrUnqual occ
, correct_name_space occ
, pair <- case (unquals_in_scope name prov, quals_only occ prov) of
(how:_, _) -> [ (rdr_unqual, how) ]
([], pr:_) -> [ pr ] -- See Note [Only-quals]
([], []) -> [] ]
-- Note [Only-quals]
-- The second alternative returns those names with the same
-- OccName as the one we tried, but live in *qualified* imports
-- e.g. if you have:
--
-- > import qualified Data.Map as Map
-- > foo :: Map
--
-- then we suggest @Map.Map@.
--------------------
unquals_in_scope :: Name -> Provenance -> [HowInScope]
unquals_in_scope n LocalDef = [ Left (nameSrcSpan n) ]
unquals_in_scope _ (Imported is) = [ Right ispec
| i <- is, let ispec = is_decl i
, not (is_qual ispec) ]
--------------------
quals_in_scope :: Name -> Provenance -> [(ModuleName, HowInScope)]
-- Ones for which the qualified version is in scope
quals_in_scope n LocalDef = case nameModule_maybe n of
Nothing -> []
Just m -> [(moduleName m, Left (nameSrcSpan n))]
quals_in_scope _ (Imported is) = [ (is_as ispec, Right ispec)
| i <- is, let ispec = is_decl i ]
--------------------
quals_only :: OccName -> Provenance -> [(RdrName, HowInScope)]
-- Ones for which *only* the qualified version is in scope
quals_only _ LocalDef = []
quals_only occ (Imported is) = [ (mkRdrQual (is_as ispec) occ, Right ispec)
| i <- is, let ispec = is_decl i, is_qual ispec ]
{-
************************************************************************
* *
\subsection{Free variable manipulation}
* *
************************************************************************
-}
-- A useful utility
addFvRn :: FreeVars -> RnM (thing, FreeVars) -> RnM (thing, FreeVars)
addFvRn fvs1 thing_inside = do { (res, fvs2) <- thing_inside
; return (res, fvs1 `plusFV` fvs2) }
mapFvRn :: (a -> RnM (b, FreeVars)) -> [a] -> RnM ([b], FreeVars)
mapFvRn f xs = do stuff <- mapM f xs
case unzip stuff of
(ys, fvs_s) -> return (ys, plusFVs fvs_s)
mapMaybeFvRn :: (a -> RnM (b, FreeVars)) -> Maybe a -> RnM (Maybe b, FreeVars)
mapMaybeFvRn _ Nothing = return (Nothing, emptyFVs)
mapMaybeFvRn f (Just x) = do { (y, fvs) <- f x; return (Just y, fvs) }
-- because some of the rename functions are CPSed:
-- maps the function across the list from left to right;
-- collects all the free vars into one set
mapFvRnCPS :: (a -> (b -> RnM c) -> RnM c)
-> [a] -> ([b] -> RnM c) -> RnM c
mapFvRnCPS _ [] cont = cont []
mapFvRnCPS f (x:xs) cont = f x $ \ x' ->
mapFvRnCPS f xs $ \ xs' ->
cont (x':xs')
{-
************************************************************************
* *
\subsection{Envt utility functions}
* *
************************************************************************
-}
warnUnusedTopBinds :: [GlobalRdrElt] -> RnM ()
warnUnusedTopBinds gres
= whenWOptM Opt_WarnUnusedBinds
$ do env <- getGblEnv
let isBoot = tcg_src env == HsBootFile
let noParent gre = case gre_par gre of
NoParent -> True
ParentIs _ -> False
-- Don't warn about unused bindings with parents in
-- .hs-boot files, as you are sometimes required to give
-- unused bindings (trac #3449).
-- HOWEVER, in a signature file, you are never obligated to put a
-- definition in the main text. Thus, if you define something
-- and forget to export it, we really DO want to warn.
gres' = if isBoot then filter noParent gres
else gres
warnUnusedGREs gres'
warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> FreeVars -> RnM ()
warnUnusedLocalBinds = check_unused Opt_WarnUnusedBinds
warnUnusedMatches = check_unused Opt_WarnUnusedMatches
check_unused :: WarningFlag -> [Name] -> FreeVars -> RnM ()
check_unused flag bound_names used_names
= whenWOptM flag (warnUnusedLocals (filterOut (`elemNameSet` used_names) bound_names))
-------------------------
-- Helpers
warnUnusedGREs :: [GlobalRdrElt] -> RnM ()
warnUnusedGREs gres
= warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
warnUnusedLocals :: [Name] -> RnM ()
warnUnusedLocals names
= warnUnusedBinds [(n,LocalDef) | n<-names]
warnUnusedBinds :: [(Name,Provenance)] -> RnM ()
warnUnusedBinds names = mapM_ warnUnusedName (filter reportable names)
where reportable (name,_)
| isWiredInName name = False -- Don't report unused wired-in names
-- Otherwise we get a zillion warnings
-- from Data.Tuple
| otherwise = not (startsWithUnderscore (nameOccName name))
-------------------------
warnUnusedName :: (Name, Provenance) -> RnM ()
warnUnusedName (name, LocalDef)
= addUnusedWarning name (nameSrcSpan name)
(ptext (sLit "Defined but not used"))
warnUnusedName (name, Imported is)
= mapM_ warn is
where
warn spec = addUnusedWarning name span msg
where
span = importSpecLoc spec
pp_mod = quotes (ppr (importSpecModule spec))
msg = ptext (sLit "Imported from") <+> pp_mod <+> ptext (sLit "but not used")
addUnusedWarning :: Name -> SrcSpan -> SDoc -> RnM ()
addUnusedWarning name span msg
= addWarnAt span $
sep [msg <> colon,
nest 2 $ pprNonVarNameSpace (occNameSpace (nameOccName name))
<+> quotes (ppr name)]
addNameClashErrRn :: RdrName -> [GlobalRdrElt] -> RnM ()
addNameClashErrRn rdr_name gres
| all isLocalGRE gres -- If there are two or more *local* defns, we'll have reported
= return () -- that already, and we don't want an error cascade
| otherwise
= addErr (vcat [ptext (sLit "Ambiguous occurrence") <+> quotes (ppr rdr_name),
ptext (sLit "It could refer to") <+> vcat (msg1 : msgs)])
where
(np1:nps) = gres
msg1 = ptext (sLit "either") <+> mk_ref np1
msgs = [ptext (sLit " or") <+> mk_ref np | np <- nps]
mk_ref gre = sep [quotes (ppr (gre_name gre)) <> comma, pprNameProvenance gre]
shadowedNameWarn :: OccName -> [SDoc] -> SDoc
shadowedNameWarn occ shadowed_locs
= sep [ptext (sLit "This binding for") <+> quotes (ppr occ)
<+> ptext (sLit "shadows the existing binding") <> plural shadowed_locs,
nest 2 (vcat shadowed_locs)]
perhapsForallMsg :: SDoc
perhapsForallMsg
= vcat [ ptext (sLit "Perhaps you intended to use ExplicitForAll or similar flag")
, ptext (sLit "to enable explicit-forall syntax: forall <tvs>. <type>")]
unknownSubordinateErr :: SDoc -> RdrName -> SDoc
unknownSubordinateErr doc op -- Doc is "method of class" or
-- "field of constructor"
= quotes (ppr op) <+> ptext (sLit "is not a (visible)") <+> doc
badOrigBinding :: RdrName -> SDoc
badOrigBinding name
= ptext (sLit "Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
-- The rdrNameOcc is because we don't want to print Prelude.(,)
dupNamesErr :: Outputable n => (n -> SrcSpan) -> [n] -> RnM ()
dupNamesErr get_loc names
= addErrAt big_loc $
vcat [ptext (sLit "Conflicting definitions for") <+> quotes (ppr (head names)),
locations]
where
locs = map get_loc names
big_loc = foldr1 combineSrcSpans locs
locations = ptext (sLit "Bound at:") <+> vcat (map ppr (sort locs))
kindSigErr :: Outputable a => a -> SDoc
kindSigErr thing
= hang (ptext (sLit "Illegal kind signature for") <+> quotes (ppr thing))
2 (ptext (sLit "Perhaps you intended to use KindSignatures"))
badQualBndrErr :: RdrName -> SDoc
badQualBndrErr rdr_name
= ptext (sLit "Qualified name in binding position:") <+> ppr rdr_name
opDeclErr :: RdrName -> SDoc
opDeclErr n
= hang (ptext (sLit "Illegal declaration of a type or class operator") <+> quotes (ppr n))
2 (ptext (sLit "Use TypeOperators to declare operators in type and declarations"))
checkTupSize :: Int -> RnM ()
checkTupSize tup_size
| tup_size <= mAX_TUPLE_SIZE
= return ()
| otherwise
= addErr (sep [ptext (sLit "A") <+> int tup_size <> ptext (sLit "-tuple is too large for GHC"),
nest 2 (parens (ptext (sLit "max size is") <+> int mAX_TUPLE_SIZE)),
nest 2 (ptext (sLit "Workaround: use nested tuples or define a data type"))])
{-
************************************************************************
* *
\subsection{Contexts for renaming errors}
* *
************************************************************************
-}
data HsDocContext
= TypeSigCtx SDoc
| PatCtx
| SpecInstSigCtx
| DefaultDeclCtx
| ForeignDeclCtx (Located RdrName)
| DerivDeclCtx
| RuleCtx FastString
| TyDataCtx (Located RdrName)
| TySynCtx (Located RdrName)
| TyFamilyCtx (Located RdrName)
| ConDeclCtx [Located RdrName]
| ClassDeclCtx (Located RdrName)
| ExprWithTySigCtx
| TypBrCtx
| HsTypeCtx
| GHCiCtx
| SpliceTypeCtx (LHsType RdrName)
| ClassInstanceCtx
| VectDeclCtx (Located RdrName)
| GenericCtx SDoc -- Maybe we want to use this more!
docOfHsDocContext :: HsDocContext -> SDoc
docOfHsDocContext (GenericCtx doc) = doc
docOfHsDocContext (TypeSigCtx doc) = text "In the type signature for" <+> doc
docOfHsDocContext PatCtx = text "In a pattern type-signature"
docOfHsDocContext SpecInstSigCtx = text "In a SPECIALISE instance pragma"
docOfHsDocContext DefaultDeclCtx = text "In a `default' declaration"
docOfHsDocContext (ForeignDeclCtx name) = ptext (sLit "In the foreign declaration for") <+> ppr name
docOfHsDocContext DerivDeclCtx = text "In a deriving declaration"
docOfHsDocContext (RuleCtx name) = text "In the transformation rule" <+> ftext name
docOfHsDocContext (TyDataCtx tycon) = text "In the data type declaration for" <+> quotes (ppr tycon)
docOfHsDocContext (TySynCtx name) = text "In the declaration for type synonym" <+> quotes (ppr name)
docOfHsDocContext (TyFamilyCtx name) = text "In the declaration for type family" <+> quotes (ppr name)
docOfHsDocContext (ConDeclCtx [name])
= text "In the definition of data constructor" <+> quotes (ppr name)
docOfHsDocContext (ConDeclCtx names)
= text "In the definition of data constructors" <+> interpp'SP names
docOfHsDocContext (ClassDeclCtx name) = text "In the declaration for class" <+> ppr name
docOfHsDocContext ExprWithTySigCtx = text "In an expression type signature"
docOfHsDocContext TypBrCtx = ptext (sLit "In a Template-Haskell quoted type")
docOfHsDocContext HsTypeCtx = text "In a type argument"
docOfHsDocContext GHCiCtx = ptext (sLit "In GHCi input")
docOfHsDocContext (SpliceTypeCtx hs_ty) = ptext (sLit "In the spliced type") <+> ppr hs_ty
docOfHsDocContext ClassInstanceCtx = ptext (sLit "TcSplice.reifyInstances")
docOfHsDocContext (VectDeclCtx tycon) = ptext (sLit "In the VECTORISE pragma for type constructor") <+> quotes (ppr tycon)
|
alexander-at-github/eta
|
compiler/ETA/Rename/RnEnv.hs
|
bsd-3-clause
| 81,249 | 105 | 31 | 23,655 | 12,635 | 6,696 | 5,939 | 932 | 13 |
{-# OPTIONS_GHC -W #-}
module Type.Inference where
import qualified Data.Map as Map
import qualified Type.Type as T
import qualified Type.Environment as Env
import qualified Type.Constrain.Expression as TcExpr
import qualified Type.Solve as Solve
import SourceSyntax.Module as Module
import SourceSyntax.Annotation (noneNoDocs)
import SourceSyntax.Type (Type)
import Text.PrettyPrint
import qualified Type.State as TS
import qualified Type.ExtraChecks as Check
import Control.Monad.State (execStateT, forM)
import Control.Monad.Error (runErrorT, liftIO)
import qualified Type.Alias as Alias
import System.IO.Unsafe -- Possible to switch over to the ST monad instead of
-- the IO monad. I don't think that'd be worthwhile.
infer :: Interfaces -> MetadataModule -> Either [Doc] (Map.Map String Type)
infer interfaces modul = unsafePerformIO $ do
env <- Env.initialEnvironment
(datatypes modul ++ concatMap iAdts (Map.elems interfaces))
(aliases modul ++ concatMap iAliases (Map.elems interfaces))
ctors <- forM (Map.keys (Env.constructor env)) $ \name ->
do (_, vars, args, result) <- Env.freshDataScheme env name
return (name, (vars, foldr (T.==>) result args))
attemptConstraint <- runErrorT $ do
importedVars <-
forM (concatMap (Map.toList . iTypes) $ Map.elems interfaces) $ \(name,tipe) ->
(,) name `fmap` Env.instantiateType env tipe Map.empty
let allTypes = ctors ++ importedVars
vars = concatMap (fst . snd) allTypes
header = Map.map snd (Map.fromList allTypes)
environ = noneNoDocs . T.CLet [ T.Scheme vars [] (noneNoDocs T.CTrue) header ]
fvar <- liftIO $ T.var T.Flexible
c <- TcExpr.constrain env (program modul) (T.VarN fvar)
return (header, environ c)
case attemptConstraint of
Left err -> return $ Left err
Right (header, constraint) -> do
state <- execStateT (Solve.solve constraint) TS.initialState
let rules = Alias.rules interfaces (aliases modul) (imports modul)
case TS.sErrors state of
errors@(_:_) -> Left `fmap` sequence (map ($ rules) (reverse errors))
[] -> case Check.portTypes rules (program modul) of
Right () -> Check.mainType rules (Map.difference (TS.sSavedEnv state) header)
Left err -> return (Left err)
|
deadfoxygrandpa/Elm
|
compiler/Type/Inference.hs
|
bsd-3-clause
| 2,377 | 0 | 24 | 533 | 793 | 419 | 374 | 46 | 4 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE OverloadedStrings #-}
module Lazyfoo.Lesson15 (main) where
import Control.Applicative
import Control.Monad
import Data.Foldable
import Data.Monoid
import Data.Maybe
import Foreign.C.Types
import Linear
import Linear.Affine
import SDL (($=))
import qualified SDL
import Paths_sdl2 (getDataFileName)
screenWidth, screenHeight :: CInt
(screenWidth, screenHeight) = (640, 480)
data Texture = Texture SDL.Texture (V2 CInt)
loadTexture :: SDL.Renderer -> FilePath -> IO Texture
loadTexture r filePath = do
surface <- getDataFileName filePath >>= SDL.loadBMP
size <- SDL.surfaceDimensions surface
format <- SDL.surfaceFormat surface
key <- SDL.mapRGB format (V3 0 maxBound maxBound)
SDL.colorKey surface $= Just key
t <- SDL.createTextureFromSurface r surface
SDL.freeSurface surface
return (Texture t size)
renderTexture :: SDL.Renderer -> Texture -> Point V2 CInt -> Maybe (SDL.Rectangle CInt) -> Maybe CDouble -> Maybe (Point V2 CInt) -> Maybe (V2 Bool) -> IO ()
renderTexture r (Texture t size) xy clip theta center flips =
let dstSize =
maybe size (\(SDL.Rectangle _ size') -> size') clip
in SDL.renderCopyEx r
t
clip
(Just (SDL.Rectangle xy dstSize))
(fromMaybe 0 theta)
center
(fromMaybe (pure False) flips)
textureSize :: Texture -> V2 CInt
textureSize (Texture _ sz) = sz
main :: IO ()
main = do
SDL.initialize [SDL.InitVideo]
SDL.HintRenderScaleQuality $= SDL.ScaleLinear
do renderQuality <- SDL.get SDL.HintRenderScaleQuality
when (renderQuality /= SDL.ScaleLinear) $
putStrLn "Warning: Linear texture filtering not enabled!"
window <-
SDL.createWindow
"SDL Tutorial"
SDL.defaultWindow {SDL.windowInitialSize = V2 screenWidth screenHeight}
SDL.showWindow window
renderer <-
SDL.createRenderer
window
(-1)
(SDL.RendererConfig
{ SDL.rendererAccelerated = True
, SDL.rendererSoftware = False
, SDL.rendererTargetTexture = False
, SDL.rendererPresentVSync = True
})
SDL.renderDrawColor renderer $= V4 maxBound maxBound maxBound maxBound
arrowTexture <- loadTexture renderer "examples/lazyfoo/arrow.bmp"
let loop theta flips = do
let collectEvents = do
e <- SDL.pollEvent
case e of
Nothing -> return []
Just e' -> (e' :) <$> collectEvents
events <- collectEvents
let (Any quit, Sum phi, Last newFlips) =
foldMap (\case
SDL.QuitEvent -> (Any True, mempty, mempty)
SDL.KeyboardEvent{..} ->
(\(x,y) -> (mempty, x,y)) $
if | keyboardEventKeyMotion == SDL.KeyDown ->
let scancode = SDL.keysymScancode keyboardEventKeysym
in if | scancode == SDL.ScancodeQ -> (mempty, Last (Just (V2 True False)))
| scancode == SDL.ScancodeW -> (mempty, Last (Just (V2 False False)))
| scancode == SDL.ScancodeE -> (mempty, Last (Just (V2 False True)))
| scancode == SDL.ScancodeA -> (Sum (-60), mempty)
| scancode == SDL.ScancodeD -> (Sum 60, mempty)
| otherwise -> mempty
| otherwise -> mempty
_ -> mempty) $
map SDL.eventPayload events
SDL.renderDrawColor renderer $= V4 maxBound maxBound maxBound maxBound
SDL.renderClear renderer
let theta' = theta + phi
flips' = fromMaybe flips newFlips
renderTexture renderer arrowTexture (P (fmap (`div` 2) (V2 screenWidth screenHeight) - fmap (`div` 2) (textureSize arrowTexture))) Nothing (Just theta') Nothing (Just flips')
SDL.renderPresent renderer
unless quit (loop theta' flips')
loop 0 (pure False)
SDL.destroyRenderer renderer
SDL.destroyWindow window
SDL.quit
|
svenkeidel/sdl2
|
examples/lazyfoo/Lesson15.hs
|
bsd-3-clause
| 4,292 | 0 | 33 | 1,360 | 1,293 | 640 | 653 | 99 | 10 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE TypeOperators #-}
module Numeric.Subroutine.Sort
( SortBy (..), sortBy, sort
, SortableDataFrame
) where
import Control.Monad
import Control.Monad.ST
import Control.Monad.ST.Unsafe
import Data.Kind
import Data.Type.Lits
import Numeric.DataFrame.Internal.PrimArray
import Numeric.DataFrame.ST
import Numeric.DataFrame.Type
import Numeric.Dimensions
import Unsafe.Coerce
-- | Sort a @DataFrame@ along the first dimension.
--
-- Note: the elements (which are of type @DataFrame t ns@) are compared
-- lexicographically.
sort :: forall (t :: Type) n ns
. ( SortableDataFrame t (n ': ns), Ord t, SortBy n)
=> DataFrame t (n ': ns)
-> DataFrame t (n ': ns)
sort df = case dimKind @(KindOf n) of
DimKNat -> case uniqueOrCumulDims df of
Left _ -> df -- all equal, no need for sorting.
Right steps
| SomeDims (Dims :: Dims ms) <- fromSteps steps
, Dict <- (unsafeCoerce (Dict @(ns ~ ns)) :: Dict (ns ~ ms))
-> sortBy compare df
| otherwise
-> error "sort/DimNat/uniqueOrCumulDims -- impossible pattern"
DimKXNat
| XFrame (df' :: DataFrame t ms) <- df
, D :* Dims <- dims @ms
-> XFrame (sortBy compare df')
| otherwise
-> error "sort/DimXNat -- impossible pattern"
{-# ANN sort "HLint: ignore Use sort" #-}
-- | Sort a @DataFrame@ along the first dimension using given comparison function.
sortBy :: forall (t :: Type) n ns
. ( SortableDataFrame t (n ': ns)
, SortBy n)
=> (DataFrame t ns -> DataFrame t ns -> Ordering)
-> DataFrame t (n ': ns)
-> DataFrame t (n ': ns)
sortBy cmp df = case dimKind @(KindOf n) of
DimKNat -> runST $
flip (withThawDataFrame (const $ pure df)) df $ \mdf -> do
sortByInplace
(\x y -> cmp <$> unsafeFreezeDataFrame x <*> unsafeFreezeDataFrame y)
mdf
unsafeFreezeDataFrame mdf
DimKXNat
| XFrame dfN <- df
, D :* Dims <- dims `inSpaceOf` dfN
-> XFrame (sortBy (\a b -> cmp (XFrame a) (XFrame b)) dfN)
| otherwise
-> error "sortBy/DimXNat -- impossible pattern"
-- | The required context for sorting a DataFrame is slightly different
-- for @Nat@ and @XNat@ indexed arrays.
-- This type family abstracts away the difference.
type family SortableDataFrame (t :: Type) (ns :: [k]) :: Constraint where
SortableDataFrame t ((n ': ns) :: [Nat])
= (PrimArray t (DataFrame t ns), PrimArray t (DataFrame t (n ': ns)))
SortableDataFrame t ((n ': ns) :: [XNat])
= PrimBytes t
class BoundedDim n => SortBy n where
-- | Note, "Inplace" here means the input frame is modified.
-- It does not mean the algorithm does not use extra space (it does use).
sortByInplace :: PrimBytes t
=> (STDataFrame s t ns -> STDataFrame s t ns -> ST s Ordering)
-- ^ must not modify state!
-> STDataFrame s t (n ': ns)
-> ST s ()
instance SortBy 0 where
sortByInplace _ _ = pure ()
instance SortBy 1 where
sortByInplace _ _ = pure ()
instance SortBy 2 where
sortByInplace cmp xs = cmp a b >>= \case
GT -> do
tmp <- oneMoreDataFrame a
swapDF tmp a b
_ -> pure ()
where
a = subDataFrameView' (Idx 0 :* U) xs
b = subDataFrameView' (Idx 1 :* U) xs
instance SortBy 3 where
sortByInplace cmp xs = join $
go <$> unsafeDupableInterleaveST (oneMoreDataFrame a)
<*> cmp a b <*> cmp b c <*> cmp a c
where
a = subDataFrameView' (Idx 0 :* U) xs
b = subDataFrameView' (Idx 1 :* U) xs
c = subDataFrameView' (Idx 2 :* U) xs
go tmp GT LT GT -- b < c < a
= swap3DF tmp a b c
go tmp LT GT GT -- c < a < b
= swap3DF tmp b a c
go tmp GT bc ac | bc /= GT && ac /= GT
= swapDF tmp a b
go tmp ab GT ac | ab /= GT && ac /= GT
= swapDF tmp b c
go tmp ab bc GT | ab /= LT && bc /= LT
= swapDF tmp a c
go _ _ _ _ = pure ()
instance SortBy 4 where
sortByInplace cmp xs = do
tmp <- unsafeDupableInterleaveST (oneMoreDataFrame a)
cmpSwap tmp a c
cmpSwap tmp b d
cmpSwap tmp a b
cmpSwap tmp c d
cmpSwap tmp b c
where
a = subDataFrameView' (Idx 0 :* U) xs
b = subDataFrameView' (Idx 1 :* U) xs
c = subDataFrameView' (Idx 2 :* U) xs
d = subDataFrameView' (Idx 3 :* U) xs
cmpSwap tmp x y = cmp x y >>= \case
GT -> swapDF tmp x y
_ -> pure ()
instance {-# INCOHERENT #-}
KnownDim n => SortBy (n :: Nat) where
sortByInplace cmp (xs :: STDataFrame s t (n ': ns)) = do
tmp <- oneMoreDataFrame xs
copyMutableDataFrame' U xs tmp
mergeSort D tmp xs
where
mergeSort :: Dim (d :: Nat)
-> STDataFrame s t (d ': ns)
-> STDataFrame s t (d ': ns)
-> ST s ()
mergeSort D0 _ _ = pure ()
mergeSort D1 _ _ = pure ()
mergeSort (d@D :: Dim d) b a = do
d2l@D <- pure $ divDim d D2
Just d2r@D <- pure $ minusDimM d d2l
d2li@D <- pure $ plusDim d2l D1
d2ri@D <- pure $ plusDim d2r D1
Just Dict <- pure $ sameDim (plusDim d D1) (plusDim d2li d2r)
Just Dict <- pure $ sameDim (plusDim d D1) (plusDim d2ri d2l)
let leA = subDataFrameView @t @d @(d - Div d 2 + 1) @(Div d 2) @'[]
(Idx 0 :* U) a
riA = subDataFrameView @t @d @(Div d 2 + 1) @(d - Div d 2) @'[]
(Idx (dimVal d2l) :* U) a
leB = subDataFrameView @t @d @(d - Div d 2 + 1) @(Div d 2) @'[]
(Idx 0 :* U) b
riB = subDataFrameView @t @d @(Div d 2 + 1) @(d - Div d 2) @'[]
(Idx (dimVal d2l) :* U) b
mergeSort d2l leA leB
mergeSort d2r riA riB
merge d2l d2r d leB riB a
merge :: forall (a :: Nat) (b :: Nat) (ab :: Nat)
. Dim a -> Dim b -> Dim ab
-> STDataFrame s t (a ': ns)
-> STDataFrame s t (b ': ns)
-> STDataFrame s t (ab ': ns)
-> ST s ()
merge da@D db@D dab@D a b ab = foldM_ f (Just (0,0)) [0 .. dimVal dab - 1]
where
f Nothing _ = pure Nothing
f (Just (i,j)) k
| i >= dimVal da
, Dx dj@(D :: Dim j) <- someDimVal j
, D <- plusDim dj D1
, Just bmj@D <- minusDimM db dj
, Just bmji@D <- minusDimM (plusDim dab D1) bmj
, Just Dict <- sameDim (plusDim dab D1) (plusDim bmji bmj)
, Just Dict <- sameDim (plusDim db D1) (dj `plusDim` D1 `plusDim` bmj)
= Nothing <$ copyMutableDataFrame @t @ab @(ab + 1 - (b - j))
@(b - j) (Idx k :* U)
(subDataFrameView @t @b @(j + 1) @(b - j) (Idx j :* U) b) ab
| j >= dimVal db
, Dx di@(D :: Dim i) <- someDimVal i
, D <- plusDim di D1
, Just bmi@D <- minusDimM da di
, Just bmii@D <- minusDimM (plusDim dab D1) bmi
, Just Dict <- sameDim (plusDim dab D1) (plusDim bmii bmi)
, Just Dict <- sameDim (plusDim da D1) (di `plusDim` D1 `plusDim` bmi)
= Nothing <$ copyMutableDataFrame (Idx k :* U)
(subDataFrameView @t @a @(i + 1) @(a - i) (Idx i :* U) a) ab
| otherwise
= cmp (subDataFrameView' (Idx i :* U) a)
(subDataFrameView' (Idx j :* U) b) >>= \case
GT -> Just (i, j + 1)
<$ copyMutableDataFrame' (Idx k :* U)
(subDataFrameView' (Idx j :* U) b) ab
_ -> Just (i + 1, j)
<$ copyMutableDataFrame' (Idx k :* U)
(subDataFrameView' (Idx i :* U) a) ab
instance BoundedDim xn => SortBy (xn :: XNat) where
sortByInplace cmp (XSTFrame xs)
| D :* _ <- dims `inSpaceOf` xs
= sortByInplace (\x y -> cmp (castDataFrame x) (castDataFrame y)) xs
#if !MIN_VERSION_GLASGOW_HASKELL(9,0,0,0)
| otherwise = error "sortByInplace: impossible pattern"
#endif
-- | Swap contents of two DataFrames
swapDF :: forall (s :: Type) (t :: Type) (ns :: [Nat])
. PrimBytes t
=> STDataFrame s t ns -- ^ Temporary buffer
-> STDataFrame s t ns
-> STDataFrame s t ns
-> ST s ()
swapDF tmp a b = do
copyMutableDataFrame' U a tmp
copyMutableDataFrame' U b a
copyMutableDataFrame' U tmp b
-- | Rotate left contents of three DataFrames
swap3DF :: forall (s :: Type) (t :: Type) (ns :: [Nat])
. PrimBytes t
=> STDataFrame s t ns -- ^ Temporary buffer
-> STDataFrame s t ns
-> STDataFrame s t ns
-> STDataFrame s t ns
-> ST s ()
swap3DF tmp a b c = do
copyMutableDataFrame' U a tmp
copyMutableDataFrame' U b a
copyMutableDataFrame' U c b
copyMutableDataFrame' U tmp c
|
achirkin/easytensor
|
easytensor/src/Numeric/Subroutine/Sort.hs
|
bsd-3-clause
| 9,742 | 2 | 21 | 3,571 | 3,549 | 1,775 | 1,774 | 213 | 3 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
-- |
-- Module : Data.Array.Repa.Mutable
-- Copyright : (c) Geoffrey Mainland 2012
-- License : BSD-style
--
-- Maintainer : Geoffrey Mainland <[email protected]>
-- Stability : experimental
-- Portability : non-portable
--
-- This module provides an interface for mutable arrays. It is like the 'Target'
-- type class, but maintains shape information.
module Data.Array.Repa.Mutable (Mutable(..)) where
import Data.Array.Repa
class Mutable r sh e where
-- | Mutable representation of an array
data MArray r sh e
-- | Get extent of the mutable array.
mextent :: MArray r sh e -> sh
-- | Allocate a new mutable array of the given size.
newMArray :: sh -> IO (MArray r sh e)
-- | Write an element into the mutable array.
unsafeWriteMArray :: MArray r sh e -> sh -> e -> IO ()
-- | Freeze the mutable array into an immutable Repa array.
unsafeFreezeMArray :: MArray r sh e -> IO (Array r sh e)
|
mainland/nikola
|
src/Data/Array/Repa/Mutable.hs
|
bsd-3-clause
| 1,025 | 0 | 11 | 229 | 156 | 92 | 64 | 10 | 0 |
-- typeInference2.hs
module TypeInference2 where
f x y = x + y + 3
|
renevp/hello-haskell
|
src/typeInference2.hs
|
bsd-3-clause
| 67 | 0 | 6 | 14 | 23 | 13 | 10 | 2 | 1 |
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE CPP #-}
module Language.Sh.Glob ( expandGlob, matchPattern,
removePrefix, removeSuffix ) where
import Control.Monad.Trans ( MonadIO )
import Control.Monad.State ( runState, put )
import Data.List ( isPrefixOf, partition )
import Data.Maybe ( isJust, listToMaybe )
import Text.Regex.PCRE.Light.Char8 ( Regex, compileM, match, ungreedy )
import Language.Sh.Syntax ( Lexeme(..), Word )
-- we might get a bit fancier if older glob libraries will support
-- a subset of what we want to do...?
import Control.Monad.Trans ( liftIO )
#ifdef HAVE_GLOB
import System.FilePath.Glob ( compileWith, compPosix,
globDir, commonDirectory )
#else
import Data.List ( sort, tails )
import System.Directory ( getDirectoryContents )
#endif
expandGlob :: MonadIO m => Word -> m [FilePath]
#ifdef HAVE_GLOB
expandGlob w = case mkGlob w of
Nothing -> return []
Just g -> let g' = compileWith compPosix g
in liftIO $
do let (dir,g'') = commonPrefix g'
liftIO $ putStrLn $ show (dir,g'')
hits <- globDir [g''] dir
return $ head $ fst $ hits
-- By the time this is called, we should only have quotes and quoted
-- literals to worry about. In the event of finding an unquoted glob
-- char (and if the glob matches) we'll automatically remove quotes, etc.
-- (since the next stage is, after all, quote removal).
-- mkGlob :: Word -> Maybe String
-- mkGlob w = case runState (mkG w) False of
-- (s,True) -> Just s
-- _ -> Nothing
-- where mkG [] = return []
-- mkG (Literal '[':xs) = case mkClass xs of
-- Just (g,xs') -> fmap (g++) $ mkG xs'
-- Nothing -> fmap ((mkLit '[')++) $ mkG xs
-- mkG (Literal '*':Literal '*':xs) = mkG $ Literal '*':xs
-- mkG (Literal '*':xs) = put True >> fmap ('*':) (mkG xs)
-- mkG (Literal '?':xs) = put True >> fmap ('?':) (mkG xs)
-- mkG (Literal c:xs) = fmap (mkLit c++) $ mkG xs
-- mkG (Quoted (Literal c):xs) = fmap (mkLit c++) $ mkG xs
-- mkG (Quoted q:xs) = mkG $ q:xs
-- mkG (Quote _:xs) = mkG xs
-- mkG l = error $ "bad lexeme: "++show l
-- mkLit c | c `elem` "[*?<" = ['[',c,']']
-- | otherwise = [c]
#else
expandGlob [] = return []
expandGlob w = do let breakd [] = []
breakd x = case break isd x of
(p,[]) -> [p]
(p,ps) -> p : breakd (dropWhile isd ps)
isd (Literal '/') = True
isd (Quoted l) = isd l
isd _ = False
l2c (Literal c) = c
l2c (Quoted l) = l2c l
l2c l = error $ "bad lexeme in l2gs: "++ show l
isclose (Literal ']') = True
isclose _ = False
w2g [] = []
w2g (Literal '[':Literal '!':r) =
case break isclose r of
(m,_:r') -> NoneOf (map l2c m) : w2g r'
_ -> Lit '[' : Lit '!' : w2g r -- not a range
w2g (Literal '[':Literal '^':r) =
case break isclose r of
(m,_:r') -> NoneOf (map l2c m) : w2g r'
_ -> Lit '[' : Lit '^' : w2g r
w2g (Literal '[':r) =
case break isclose r of
(m,_:r') -> Alt (map l2c m) : w2g r'
_ -> Lit '[' : w2g r
w2g (Literal '*':r) = Many : w2g r
w2g (Literal '?':r) = One : w2g r
w2g (Literal c:r) = Lit c : w2g r
w2g (Quote _:r) = w2g r
w2g (Quoted (Quoted q):r) = w2g (Quoted q:r)
w2g (Quoted (Literal c):r) = Lit c : w2g r
w2g (Quoted (Quote _):r) = w2g r
w2g (Quoted x:r) = w2g (x:r) -- only expansions left
w2g l = error $ "bad lexeme: "++show l
whichd = if isd $ head w
then "/"
else "."
liftIO $ filePathMatches (map w2g $ breakd w) whichd
data Glob = Lit Char | Many | One | Alt [Char] | NoneOf [Char]
deriving ( Show )
simpleMatch :: [Glob] -> String -> Bool
simpleMatch [] "" = True
simpleMatch (Many:rest) s = any (simpleMatch rest) $ tails s
simpleMatch (One:rest) (_:s) = simpleMatch rest s
simpleMatch (Lit x:rest) (c:cs) | x == c = simpleMatch rest cs
simpleMatch (Alt xs:rest) (c:cs) | c `elem` xs = simpleMatch rest cs
simpleMatch (NoneOf xs:rest) (c:cs) | c `notElem` xs = simpleMatch rest cs
simpleMatch _ _ = False
filePathMatches :: [[Glob]] -> FilePath -> IO [FilePath]
filePathMatches [] _ = return []
filePathMatches (g:gs) d = do xs <- filter (`notElem` [".",".."])
`fmap` (getDirectoryContents d
`catch` \_ -> return [])
let xs' = filter (simpleMatch g) $ case g of
Lit _:_ -> xs
_ -> filter notdot xs
notdot ('.':_) = False
notdot _ = True
fpm x = map ((x++"/")++)
`fmap` filePathMatches gs (d++'/':x)
case gs of
[] -> return $ sort xs'
_ -> (sort . concat) `fmap` mapM fpm xs'
#endif
-- This is basically gratuitously copied from Glob's internals.
mkClass :: Word -> Maybe (String,Word)
mkClass xs = let (range, rest) = break (isLit ']') xs
in if null rest then Nothing
else if null range
then let (range', rest') = break (isLit ']') (tail rest)
in if null rest' then Nothing
else do x <- cr' range'
return (x,tail rest')
else do x <- cr' range
return (x,tail rest)
where cr' s = Just $ "["++movedash (filter (not . isQuot) s)++"]"
isLit c x = case x of { Literal c' -> c==c'; _ -> False }
isQuot x = case x of { Quote _ -> True; _ -> False }
quoted c x = case x of Quoted (Quoted x') -> quoted c $ Quoted x'
Quoted (Literal c') -> c==c'
_ -> False
movedash s = let (d,nd) = partition (quoted '-') s
bad = null d || (isLit '-' $ head $ reverse s)
in map fromLexeme $ if bad then nd else nd++d
fromLexeme x = case x of { Literal c -> c; Quoted q -> fromLexeme q;
l -> error $ "bad lexeme "++show l }
{-
expandGlob :: MonadIO m => Word -> m [FilePath]
expandGlob w = case mkGlob w of
Nothing -> return []
Just g -> case G.unPattern g of
(G.PathSeparator:_) -> liftIO $
do hits <- G.globDir [g] "/" -- unix...?
let ps = [pathSeparator]
return $ head $ fst $ hits
_ -> liftIO $
do cwd <- getCurrentDirectory
hits <- G.globDir [g] cwd
let ps = [pathSeparator]
return $ map (removePrefix $ cwd++ps) $
head $ fst $ hits
where removePrefix pre s | pre `isPrefixOf` s = drop (length pre) s
| otherwise = s
-}
-- Two issues: we can deal with them here...
-- 1. if glob starts with a dirsep then we need to go relative to root...
-- (what about in windows?)
-- 2. if not, then we should remove the absolute path from the beginning of
-- the results (should be easy w/ a map)
{-
-- This is a sort of default matcher, but needn't be used...
matchGlob :: MonadIO m => Glob -> m [FilePath]
matchGlob g = matchG' [] $ splitDir return $ do -- now we're in the list monad...
where d = splitDir g
splitDir (c:xs) | ips c = []:splitDir (dropWhile ips xs)
splitDir xs = filter (not . null) $
filter (not . all ips) $
groupBy ((==) on ips) xs
ips x = case x of { Lit c -> isPathSeparator c; _ -> False }
-}
----------------------------------------------------------------------
-- This is copied from above, but it's used separately for non-glob --
-- pattern matching. Maybe we'll combine them someday. --
----------------------------------------------------------------------
match' :: Regex -> String -> Maybe String
match' regex s = listToMaybe =<< match regex s []
matchPattern :: Word -> String -> Bool
matchPattern w s = case mkRegex False False "^" "$" w of
Just r -> isJust $ match r s []
Nothing -> fromLit w == s
removePrefix :: Bool -- ^greediness
-> Word -- ^pattern
-> String -- ^haystack
-> String
removePrefix g n h = case mkRegex g False "^" "" n of
Just r -> case match' r h of
Just m -> drop (length m) h
Nothing -> h
Nothing -> if l `isPrefixOf` h
then drop (length l) h
else h
where l = fromLit n
removeSuffix :: Bool -- ^greediness
-> Word -- ^pattern
-> String -- ^haystack
-> String
removeSuffix g n h = case mkRegex g True "^" "" n of
Just r -> case match' r hr of
Just m -> reverse $ drop (length m) hr
Nothing -> h
Nothing -> if l `isPrefixOf` hr
then reverse $ drop (length l) hr
else h
where l = reverse $ fromLit n
hr = reverse h
mkRegex :: Bool -- ^greedy?
-> Bool -- ^reverse? (before adding pre/suff)
-> String -- ^prefix
-> String -- ^suffix
-> Word -- ^pattern
-> Maybe Regex
mkRegex g r pre suf w
= case runState (mkR w) False of
(s,True) -> mk' $ concat $ affix $ (if r then reverse else id) s
_ -> Nothing
where mkR [] = return []
mkR (Literal '[':xs) = case mkClass xs of
Just (c,xs') -> fmap (c:) $ mkR xs'
Nothing -> fmap ((mkLit '['):) $ mkR xs
mkR (Literal '*':Literal '*':xs) = mkR $ Literal '*':xs
mkR (Literal '*':xs) = put True >> fmap (".*":) (mkR xs)
mkR (Literal '?':xs) = put True >> fmap (".":) (mkR xs)
mkR (Literal c:xs) = fmap (mkLit c:) $ mkR xs
mkR (Quoted (Literal c):xs) = fmap (mkLit c:) $ mkR xs
mkR (Quoted q:xs) = mkR $ q:xs
mkR (Quote _:xs) = mkR xs
mkR l = error $ "bad lexeme: "++show l
mkLit c | c `elem` "[](){}|^$.*+?\\" = ['\\',c]
| otherwise = [c]
affix s = pre:s++[suf]
mk' s = case compileM s (if g then [] else [ungreedy]) of
Left _ -> Nothing
Right regex -> Just regex
fromLit :: Word -> String
fromLit = concatMap $ \l -> case l of Literal c -> [c]
Quoted q -> fromLit [q]
_ -> []
|
shicks/shsh
|
Language/Sh/Glob.hs
|
bsd-3-clause
| 12,285 | 0 | 16 | 5,425 | 1,847 | 964 | 883 | 162 | 24 |
import Data.Array
import Data.List
import Data.Ord (comparing)
syrs n = a
where
a = listArray (1,n) $ 0:[1 + syr n x | x <- [2..n]]
syr n x = if x' <= n then a ! x' else 1 + syr n x'
where
x' = if even x then x `div` 2 else 3 * x + 1
main = print $ maximumBy (comparing snd) $ assocs $ syrs 1000000
|
dterei/Scraps
|
euler/p14/p14_mem.hs
|
bsd-3-clause
| 352 | 1 | 10 | 125 | 176 | 92 | 84 | 8 | 3 |
{- |
Module : ./Omega/Export.hs
Description : export a development graph to an omega library
Copyright : (c) Ewaryst Schulz, DFKI Bremen 2009
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : non-portable(Logic)
A given development graph will be exported to an omega library.
The structure of the development graph is expected to satisfy additional
requirements. The form of the specs should be the following:
spec <name> = spec-ref_1 and ... and spec-ref_n then basic-spec
n can also be 0 or 1.
-}
module Omega.Export
( exportDGraph
, exportNodeLab
) where
import Logic.Coerce
import qualified Logic.Prover as P
{- import Logic.Logic
import Logic.Grothendieck
import Logic.Comorphism -}
import HasCASL.Logic_HasCASL
import qualified HasCASL.Le as Le
import Static.DevGraph
import Static.GTheory
import Common.Id
import Common.ExtSign
import Common.LibName
import Common.AS_Annotation
import Omega.DataTypes
import Omega.Terms
import Data.Graph.Inductive.Graph
import Data.List
import Data.Maybe
import qualified Data.Map as Map
-- | DGraph to Omega Library translation
exportDGraph :: LibName -> DGraph -> Library
exportDGraph ln dg =
let libid = getLibId ln
in
Library (show libid)
$ mapMaybe (exportNodeLab libid dg)
$ topsortedNodes dg
-- | DGNodeLab to Theory translation
exportNodeLab :: LibId -> DGraph -> LNode DGNodeLab -> Maybe Theory
exportNodeLab _ dg (n, lb) =
justWhen (not $ isDGRef lb) $
case dgn_theory lb of
G_theory lid _ (ExtSign sign _) _ sens _ ->
let theoryname = getDGNodeName lb
msg = "Omega Export: Try to coerce to HasCASL!"
e = error msg
(signature, sentences) =
fromMaybe e $
coerceBasicTheory lid HasCASL msg (sign, P.toNamedList sens)
in Theory theoryname
(mapMaybe (makeImport dg) $ innDG dg n)
$ exportSign signature ++ exportSens sentences
exportSign :: Le.Env -> [TCElement]
-- need to filter the elements which are not locally defined but imported!
exportSign Le.Env { Le.assumps = ops } = map (TCSymbol . show) $ Map.keys ops
exportSens :: [Named Le.Sentence] -> [TCElement]
exportSens = mapMaybe exportSen
exportSen :: Named Le.Sentence -> Maybe TCElement
exportSen SenAttr
{ senAttr = name
, isAxiom = isAx
, sentence = (Le.Formula t) }
= Just $ TCAxiomOrTheorem (not isAx) name $ toTerm t
exportSen _ = Nothing
makeImport :: DGraph -> LEdge DGLinkLab -> Maybe String
makeImport dg (from, _, lbl) =
justWhen (isGlobalDef $ dgl_type lbl) $ getDGNodeName $ labDG dg from
|
spechub/Hets
|
Omega/Export.hs
|
gpl-2.0
| 2,732 | 0 | 18 | 634 | 606 | 319 | 287 | 53 | 1 |
f :: IO
f = putStrLn "hello, world!"
|
roberth/uu-helium
|
test/kinderrors/KindError3.hs
|
gpl-3.0
| 37 | 0 | 6 | 8 | 20 | 8 | 12 | 2 | 1 |
module PTS.Syntax.Algebra
( PreAlgebra
, Algebra
, fold
, strip
, allvars
, allvarsAlgebra
, freevars
, freevarsAlgebra
, freshvar
, depZip
) where
import Data.Set (Set)
import qualified Data.Set as Set
import PTS.Syntax.Names
import PTS.Syntax.Term
-- algebras
type PreAlgebra alpha beta
= TermStructure alpha -> beta
type Algebra alpha
= PreAlgebra alpha alpha
fold :: Structure term => Algebra alpha -> term -> alpha
fold algebra term = algebra (fmap (fold algebra) (structure term))
strip :: Structure term => term -> Term
strip t = fold MkTerm t
allvars :: Structure term => term -> Names
allvars t = fold allvarsAlgebra t
allvarsAlgebra :: Algebra Names
allvarsAlgebra (Var x) = Set.singleton x
allvarsAlgebra (App t1 t2) = t1 `Set.union` t2
allvarsAlgebra (IntOp _ t1 t2) = t1 `Set.union` t2
allvarsAlgebra (IfZero t1 t2 t3) = t1 `Set.union` t2 `Set.union` t3
allvarsAlgebra (Lam x t1 t2) = Set.insert x (t1 `Set.union` t2)
allvarsAlgebra (Pi x t1 t2 _) = Set.insert x (t1 `Set.union` t2)
allvarsAlgebra (Pos p t) = t
allvarsAlgebra _ = Set.empty
freevarsAlgebra :: Algebra Names
freevarsAlgebra t = case t of
Var x -> Set.singleton x
App t1 t2 -> t1 `Set.union` t2
IntOp _ t1 t2 -> t1 `Set.union` t2
IfZero t1 t2 t3 -> Set.unions [t1, t2, t3]
Lam x t1 t2 -> t1 `Set.union` (Set.delete x t2)
Pi x t1 t2 _ -> t1 `Set.union` (Set.delete x t2)
Pos p t -> t
_ -> Set.empty
freevars :: Structure term => term -> Names
freevars = fold freevarsAlgebra
freshvar :: Structure term => term -> Name -> Name
freshvar t x = freshvarl (freevars t) x
-- instance Arrow PreAlgebra?
depZip :: PreAlgebra alpha alpha -> PreAlgebra (alpha, beta) beta -> PreAlgebra (alpha, beta) (alpha, beta)
depZip f g x = (f (fmap fst x), g x)
|
Toxaris/pts
|
src-lib/PTS/Syntax/Algebra.hs
|
bsd-3-clause
| 1,900 | 0 | 11 | 485 | 750 | 396 | 354 | 50 | 8 |
module Main where
import Prelude hiding ((+),(-))
import System.Environment
import DeepGADT
import IO
main = do
args <- getArgs
let [inImg,outImg] = args
img1 <- readImgAsVector inImg
newImg <- printTimeDeep (run ((integer 30) + (blurY (blurX (image img1)))))
writeVectorImage outImg newImg
|
robstewart57/small-image-processing-dsl-implementations
|
haskell/small-image-processing-dsl/app/deep-gadt/prog5.hs
|
bsd-3-clause
| 314 | 0 | 18 | 64 | 124 | 66 | 58 | 11 | 1 |
{-|
Module : Database.Test.MultiConnect
Copyright : (c) 2004 Oleg Kiselyov, Alistair Bayley
License : BSD-style
Maintainer : [email protected], [email protected]
Stability : experimental
Portability : non-portable
Tests Database.Enumerator code in the context of multiple
database connections to different DBMS products.
We should add tests to shift data between databases, too.
-}
{-# LANGUAGE OverlappingInstances #-}
module Database.Test.MultiConnect (runTest) where
import qualified Database.Sqlite.Enumerator as Sqlite
import qualified Database.PostgreSQL.Enumerator as PG
import Database.Sqlite.Test.Enumerator as SqlTest
import Database.PostgreSQL.Test.Enumerator as PGTest
import Database.Test.Performance as Perf
import Database.Enumerator
import System.Environment (getArgs)
runTest :: Perf.ShouldRunTests -> [String] -> IO ()
runTest runPerf args = catchDB ( do
let [ user, pswd, dbname ] = args
withSession (PG.connect user pswd dbname) $ \sessPG -> do
withSession (Sqlite.connect user pswd dbname) $ \sessSql -> do
SqlTest.runTest runPerf args
PGTest.runTest runPerf args
) basicDBExceptionReporter
|
bagl/takusen-oracle
|
Database/Test/MultiConnect.hs
|
bsd-3-clause
| 1,200 | 0 | 18 | 222 | 207 | 118 | 89 | -1 | -1 |
module StoryMode.Paths where
import System.Directory
import System.FilePath
import Utils
getStoryModePath :: IO (Maybe FilePath)
getStoryModePath = do
dir <- getAppUserDataDirectory "nikki-story-mode"
exists <- doesDirectoryExist dir
return $ if exists then Just dir else Nothing
createStoryModePath :: IO FilePath
createStoryModePath = do
dir <- getAppUserDataDirectory "nikki-story-mode"
createDirectory dir
return dir
getStoryModeDataFileName :: FilePath -> IO (Maybe FilePath)
getStoryModeDataFileName path =
fmap (</> ("data" </> path)) <$> getStoryModePath
getStoryModeDataFiles :: FilePath -> Maybe String -> IO (Maybe [FilePath])
getStoryModeDataFiles path_ extension = do
mPath <- getStoryModeDataFileName path_
case mPath of
Nothing -> return Nothing
Just path -> Just <$> map (path </>) <$> io (getFiles path extension)
getStoryModeLevelsPath :: IO (Maybe FilePath)
getStoryModeLevelsPath =
fmap (</> "levels") <$> getStoryModePath
getStoryModeLoginDataFile :: IO (Maybe FilePath)
getStoryModeLoginDataFile =
fmap (</> "loginData") <$> getStoryModePath
getStoryModeVersionFile :: IO (Maybe FilePath)
getStoryModeVersionFile =
fmap (</> "version") <$> getStoryModePath
|
changlinli/nikki
|
src/StoryMode/Paths.hs
|
lgpl-3.0
| 1,255 | 0 | 13 | 217 | 344 | 172 | 172 | 32 | 2 |
-----------------------------------------------------------------------------
-- |
-- Module : Tuura.Plato.Translate.Translation
-- Copyright : (c) 2015-2018, Tuura authors
-- License : BSD (see the file LICENSE)
-- Maintainer : [email protected]
-- Stability : experimental
--
-- Plato is a tool which embeds the Asynchronous Concepts language in Haskell.
-- This language is used for the specification of asynchronous circuits, and
-- is fully compositional and highly reusable, from individual concepts to
-- entire concepts specifications.
-- Plato can also compile and validate Asynchronous Concepts, with the help of
-- the GHC. Compiled concepts can then be translated to existing modelling
-- formalisms of Signal Transition Graphs (STGs) and State Graphs. These models
-- feature a long history of theory and therefore several tools which can be
-- used for verification and synthesis. STGs and State Graphs can be visualized
-- in Workcraft (https://workcraft.org), where Plato and the tools for these
-- models are all integrated.
--
-- This module defines several functions which are common to the translation
-- of Asynchronous Concepts to either STGs or State Graphs.
--
-----------------------------------------------------------------------------
module Tuura.Plato.Translate.Translation where
import Data.Char
import Data.Monoid
import Tuura.Concept.Circuit.Basic
import Tuura.Concept.Circuit.Derived
{- | 'ValidationResult' is a data type used to define whether the validation,
performed by several functions in this module, was successful or not.
'Valid' indicates that validation was succesful.
'Invalid' indicates that validation failed, and contains a list of the
errors which can then be reported back to the user.
The 'Monoid' instance is used to compose results. It contains some simple rules
for the compositions, i.e. If two 'ValidationResults' objects are 'Valid' then
the result of the composition is valid. If at least one is 'Invalid', then the
result must be 'Invalid'. If both are 'Invalid' then the result is 'Invalid'
and the list of errors is combined, to ensure that all errors are reported to
the user.
-}
data ValidationResult a = Valid | Invalid [ValidationError a] deriving Eq
instance Monoid (ValidationResult a) where
mempty = mempty
mappend Valid x = x
mappend x Valid = x
mappend (Invalid es) (Invalid fs) = Invalid (fs ++ es)
{-| 'ValidationError' is a type used to define the type of error found during
the validation performed by several functions in this module.
'UnusedSignal' occurs when a signal in the provided concept specification is
not provided with an interface, i.e. It is not declared as either an 'Input',
'Output' or 'Internal' signal. The affected signals are stored as part of this.
'InconsistentInitialState' occurs when a signal has its initial state defined
as both 'High' and 'Low'. The affected signals are stored as part of this.
'UndefinedInitialState' occurs when a signal has no initial state defined.
The affected signals are stored as part of this.
'InvariantViolated' occurs when a state can be reached which is defined,
using a 'never' concept, to not be part of the invariant. The transitions
which are part of the associated 'never' concept are stored as part of this.
-}
data ValidationError a = UnusedSignal a
| InconsistentInitialState a
| UndefinedInitialState a
| InvariantViolated [Transition a]
deriving Eq
{-| 'Signal' is a type which is used to refer to signals as defined in a
Concept specification. The number of signals in the specification is known
and a signal can be referenced by an integer.
The 'Show' instance converts the integer value of a signal to a letter for
reference. This follows the alphabet for the first 26 signals, and then will
be referred to as 'S' and the integer value after this.
'Ord' is used to compare the integer value of signals, to determine whether
two signals are infact the same signal.
-}
data Signal = Signal Int deriving Eq
instance Show Signal where
show (Signal i)
| i < 26 = [chr (ord 'A' + i)]
| otherwise = 'S' : show i
instance Ord Signal
where
compare (Signal x) (Signal y) = compare x y
-- TODO: Tidy up function, it looks ugly.
-- | Prepare output explaining errors found during validation to users.
addErrors :: (Eq a, Show a) => [ValidationError a] -> String
addErrors errs = "Error\n" ++
(if unused /= []
then "The following signals are not declared as input, "
++ "output or internal: \n" ++ unlines (map show unused) ++ "\n"
else "") ++
(if incons /= []
then "The following signals have inconsistent inital states: \n"
++ unlines (map show incons) ++ "\n"
else "") ++
(if undefd /= []
then "The following signals have undefined initial states: \n"
++ unlines (map show undefd) ++ "\n"
else "") ++
(if invVio /= []
then "The following state(s) are reachable " ++
"but the invariant does not hold for them:\n" ++
unlines (map show invVio) ++ "\n"
else "")
where
unused = [ a | UnusedSignal a <- errs ]
incons = [ a | InconsistentInitialState a <- errs ]
undefd = [ a | UndefinedInitialState a <- errs ]
invVio = [ a | InvariantViolated a <- errs ]
-- | Validate initial states and interface.
validate :: [a] -> CircuitConcept a -> ValidationResult a
validate signs circuit = validateInitialState signs circuit
<> validateInterface signs circuit
-- | Validate initial state - If there are any undefined or inconsistent
-- initial states, then these will populate the list.
validateInitialState :: [a] -> CircuitConcept a -> ValidationResult a
validateInitialState signs circuit
| null (undef ++ inconsistent) = Valid
| otherwise = Invalid (map UndefinedInitialState undef
++ map InconsistentInitialState inconsistent)
where
undef = filter ((==Undefined) . initial circuit) signs
inconsistent = filter ((==Inconsistent) . initial circuit) signs
-- | Validate interface - If there are any unused signals then these
-- will populate the list.
validateInterface :: [a] -> CircuitConcept a -> ValidationResult a
validateInterface signs circuit
| null unused = Valid
| otherwise = Invalid (map UnusedSignal unused)
where
unused = filter ((==Unused) . interface circuit) signs
-- | Converts a 'Transition' to a 'Literal', a data type which is used by the
--Tuura Boolean library.
toLiteral :: [Transition a] -> [Literal a]
toLiteral = map (\t -> Literal (signal t) (newValue t))
-- | Converts a 'Literal' to 'Transitions'.
toTransitions :: [Literal a] -> [Transition a]
toTransitions = map (\l -> Transition (variable l) (polarity l))
-- | Converts 'Causality' concepts into a tuple, containing a list of possible
-- causes, for each effect.
arcLists :: [Causality (Transition a)] -> [([Transition a], Transition a)]
arcLists xs = [ (f, t) | Causality f t <- xs ]
-- | Converts from a 'CircuitConcept' using the polymorphic @a@ type, to a
-- CircuitConcept using the 'Signal' type.
convert :: Enum a => CircuitConcept a -> CircuitConcept Signal
convert c = mempty
{
initial = convertFunction (initial c),
arcs = fmap convertCausality (arcs c),
interface = convertFunction (interface c),
invariant = fmap convertInvariant (invariant c)
}
-- | For every function, such as the 'initial' function or 'interface'
-- function, Convert from using the polymorphic @a@ type to using the 'Signal'
-- type.
convertFunction :: Enum a => (a -> b) -> (Signal -> b)
convertFunction f (Signal i) = f $ toEnum i
-- | Converts all causalities from using the polymorphic @a@ type, to using the
-- 'Signal' type.
convertCausality :: Enum a => Causality (Transition a) -> Causality (Transition Signal)
convertCausality (Causality f t) = Causality (map convertTrans f) (convertTrans t)
-- | Converts all invariant concepts from using the polymorphic @a@ type, to
-- using the 'Signal' type.
convertInvariant :: Enum a => Invariant (Transition a) -> Invariant (Transition Signal)
convertInvariant (NeverAll es) = NeverAll (map convertTrans es)
-- | Converts an individual 'Transition' from using the polymorphic @a@ type,
-- to using the 'Signal' type.
convertTrans :: Enum a => Transition a -> Transition Signal
convertTrans t = Transition (Signal $ fromEnum $ signal t) (newValue t)
|
tuura/concepts
|
src/Tuura/Plato/Translate/Translation.hs
|
bsd-3-clause
| 8,661 | 0 | 15 | 1,854 | 1,373 | 727 | 646 | 81 | 5 |
module Dotnet.System.Xml.XmlProcessingInstruction where
import Dotnet
import qualified Dotnet.System.Xml.XmlLinkedNode
import Dotnet.System.Xml.XmlWriter
import Dotnet.System.Xml.XmlNode
import Dotnet.System.Xml.XmlNodeType
data XmlProcessingInstruction_ a
type XmlProcessingInstruction a = Dotnet.System.Xml.XmlLinkedNode.XmlLinkedNode (XmlProcessingInstruction_ a)
foreign import dotnet
"method Dotnet.System.Xml.XmlProcessingInstruction.WriteContentTo"
writeContentTo :: Dotnet.System.Xml.XmlWriter.XmlWriter a0 -> XmlProcessingInstruction obj -> IO (())
foreign import dotnet
"method Dotnet.System.Xml.XmlProcessingInstruction.WriteTo"
writeTo :: Dotnet.System.Xml.XmlWriter.XmlWriter a0 -> XmlProcessingInstruction obj -> IO (())
foreign import dotnet
"method Dotnet.System.Xml.XmlProcessingInstruction.set_InnerText"
set_InnerText :: String -> XmlProcessingInstruction obj -> IO (())
foreign import dotnet
"method Dotnet.System.Xml.XmlProcessingInstruction.get_InnerText"
get_InnerText :: XmlProcessingInstruction obj -> IO (String)
foreign import dotnet
"method Dotnet.System.Xml.XmlProcessingInstruction.get_LocalName"
get_LocalName :: XmlProcessingInstruction obj -> IO (String)
foreign import dotnet
"method Dotnet.System.Xml.XmlProcessingInstruction.CloneNode"
cloneNode :: Bool -> XmlProcessingInstruction obj -> IO (Dotnet.System.Xml.XmlNode.XmlNode a1)
foreign import dotnet
"method Dotnet.System.Xml.XmlProcessingInstruction.get_NodeType"
get_NodeType :: XmlProcessingInstruction obj -> IO (Dotnet.System.Xml.XmlNodeType.XmlNodeType a0)
foreign import dotnet
"method Dotnet.System.Xml.XmlProcessingInstruction.set_Value"
set_Value :: String -> XmlProcessingInstruction obj -> IO (())
foreign import dotnet
"method Dotnet.System.Xml.XmlProcessingInstruction.get_Value"
get_Value :: XmlProcessingInstruction obj -> IO (String)
foreign import dotnet
"method Dotnet.System.Xml.XmlProcessingInstruction.get_Name"
get_Name :: XmlProcessingInstruction obj -> IO (String)
foreign import dotnet
"method Dotnet.System.Xml.XmlProcessingInstruction.get_Target"
get_Target :: XmlProcessingInstruction obj -> IO (String)
foreign import dotnet
"method Dotnet.System.Xml.XmlProcessingInstruction.get_Data"
get_Data :: XmlProcessingInstruction obj -> IO (String)
foreign import dotnet
"method Dotnet.System.Xml.XmlProcessingInstruction.set_Data"
set_Data :: String -> XmlProcessingInstruction obj -> IO (())
|
alekar/hugs
|
dotnet/lib/Dotnet/System/Xml/XmlProcessingInstruction.hs
|
bsd-3-clause
| 2,475 | 0 | 11 | 265 | 456 | 251 | 205 | -1 | -1 |
{-# LANGUAGE BangPatterns #-}
foo = case v of !(x : xs) -> x
|
mpickering/hlint-refactor
|
tests/examples/Structure19.hs
|
bsd-3-clause
| 61 | 0 | 10 | 14 | 25 | 13 | 12 | 2 | 1 |
{-
BackendCommon: Common code used by most backends
Part of Flounder: a message passing IDL for Barrelfish
Copyright (c) 2007-2010, ETH Zurich.
All rights reserved.
This file is distributed under the terms in the attached LICENSE file.
If you do not find this file, copies can be found by writing to:
ETH Zurich D-INFK, Universit\"atstr. 6, CH-8092 Zurich. Attn: Systems Group.
-}
module BackendCommon where
import qualified CAbsSyntax as C
import Syntax
data Direction = TX | RX
deriving (Show, Eq)
------------------------------------------------------------------------
-- Language mapping: C identifier names
------------------------------------------------------------------------
-- Scope a list of strings
ifscope :: String -> String -> String
--ifscope ifn s = ifn ++ "$" ++ s
ifscope ifn s = ifn ++ "_" ++ s
idscope :: String -> String -> String -> String
idscope ifn s suffix = ifscope ifn (s ++ "__" ++ suffix)
drvscope :: String -> String -> String -> String
drvscope drv ifn s = ifscope ifn (drv ++ "_" ++ s)
-- Name of the binding struct for an interface type
intf_bind_type :: String -> String
intf_bind_type ifn = ifscope ifn "binding"
-- Variable used to refer to a binding
intf_bind_var = "_binding"
-- Name of the binding struct for an interface type
intf_frameinfo_type :: String -> String
intf_frameinfo_type ifn = ifscope ifn "frameinfo"
-- Variable used to refer to a continuation
intf_frameinfo_var = "_frameinfo"
-- Name of the bind continuation function type for an interface type
intf_bind_cont_type :: String -> String
intf_bind_cont_type ifn = ifscope ifn "bind_continuation_fn"
-- Variable used to refer to a continuation
intf_cont_var = "_continuation"
-- name of the export state struct
export_type n = ifscope n "export"
-- Name of the enumeration of message numbers
msg_enum_name :: String -> String
msg_enum_name ifn = ifscope ifn "msg_enum"
-- Name of each element of the message number enumeration
msg_enum_elem_name :: String -> String -> String
msg_enum_elem_name ifn mn = idscope ifn mn "msgnum"
-- Name of the type of a message function
msg_sig_type :: String -> MessageDef -> Direction -> String
msg_sig_type ifn m@(RPC _ _ _) _ = idscope ifn (msg_name m) "rpc_method_fn"
msg_sig_type ifn m TX = idscope ifn (msg_name m) "tx_method_fn"
msg_sig_type ifn m RX = idscope ifn (msg_name m) "rx_method_fn"
-- Name of a given message definition
msg_name :: MessageDef -> String
msg_name (Message _ n _ _) = n
msg_name (RPC n _ _) = n
-- Name of the static inline wrapper for sending messages
tx_wrapper_name :: String -> String -> String
tx_wrapper_name ifn mn = idscope ifn mn "tx"
-- Names of the underlying messages that are constructed from an RPC
rpc_call_name n = n ++ "_call"
rpc_resp_name n = n ++ "_response"
-- Name of the struct holding message args for SAR
msg_argstruct_name :: String -> String -> String
msg_argstruct_name ifn n = idscope ifn n "args"
-- Name of the union type holding all the arguments for a message
binding_arg_union_type :: String -> String
binding_arg_union_type ifn = ifscope ifn "arg_union"
-- Name of the C type for a concrete flounder type, struct, or enum
type_c_struct, type_c_enum :: String -> String -> String
type_c_struct ifn n = "_" ++ idscope ifn n "struct"
type_c_enum ifn e = ifscope ifn e
type_c_name :: String -> TypeRef -> String
type_c_name ifn (Builtin Cap) = undefined
type_c_name ifn (Builtin GiveAwayCap) = undefined
type_c_name ifn (Builtin String) = undefined
type_c_name ifn (Builtin t) = (show t) ++ "_t"
type_c_name ifn (TypeVar t) = type_c_name1 ifn t
type_c_name ifn (TypeAlias t _) = type_c_name1 ifn t
type_c_name1 :: String -> String -> String
type_c_name1 ifn tn = (ifscope ifn tn) ++ "_t"
type_c_type :: String -> TypeRef -> C.TypeSpec
type_c_type ifn (Builtin Cap) = C.Struct "capref"
type_c_type ifn (Builtin GiveAwayCap) = C.Struct "capref"
type_c_type ifn (Builtin Char) = C.TypeName "char"
type_c_type ifn (Builtin Bool) = C.TypeName "bool"
type_c_type ifn (Builtin String) = C.Ptr $ C.TypeName "char"
type_c_type ifn t = C.TypeName $ type_c_name ifn t
-- TX pointers should be const
type_c_type_dir :: Direction -> String -> TypeRef -> C.TypeSpec
type_c_type_dir TX ifn tr = case type_c_type ifn tr of
C.Ptr t -> C.Ptr $ C.ConstT t
t -> t
type_c_type_dir RX ifn tr = type_c_type ifn tr
-- Array types in the msg args struct should only be pointers to the storage
type_c_type_msgstruct :: String -> [TypeDef] -> TypeRef -> C.TypeSpec
type_c_type_msgstruct ifn typedefs t
= case lookup_typeref typedefs t of
TArray tr n _ -> C.Ptr $ type_c_type ifn t
_ -> type_c_type ifn t
-- Name of the struct type for the method vtable
intf_vtbl_type :: String -> Direction -> String
intf_vtbl_type ifn TX = ifscope ifn "tx_vtbl"
intf_vtbl_type ifn RX = ifscope ifn "rx_vtbl"
connect_callback_name n = ifscope n "connect_fn"
drv_connect_handler_name drv n = drvscope drv n "connect_handler"
drv_connect_fn_name drv n = drvscope drv n "connect"
drv_accept_fn_name drv n = drvscope drv n "accept"
can_send_fn_name drv n = drvscope drv n "can_send"
register_send_fn_name drv n = drvscope drv n "register_send"
default_error_handler_fn_name drv n = drvscope drv n "default_error_handler"
generic_control_fn_name drv n = drvscope drv n "control"
can_send_fn_type ifn = ifscope ifn "can_send_fn"
register_send_fn_type ifn = ifscope ifn "register_send_fn"
change_waitset_fn_type ifn = ifscope ifn "change_waitset_fn"
control_fn_type ifn = ifscope ifn "control_fn"
error_handler_fn_type ifn = ifscope ifn "error_handler_fn"
------------------------------------------------------------------------
-- Code shared by backend implementations
------------------------------------------------------------------------
intf_preamble :: String -> String -> Maybe String -> C.Unit
intf_preamble infile name descr =
let dstr = case descr of
Nothing -> "not specified"
Just s -> s
in
C.MultiComment [
"Copyright (c) 2010, ETH Zurich.",
"All rights reserved.",
"",
"INTERFACE NAME: " ++ name,
"INTEFACE FILE: " ++ infile,
"INTERFACE DESCRIPTION: " ++ dstr,
"",
"This file is distributed under the terms in the attached LICENSE",
"file. If you do not find this file, copies can be found by",
"writing to:",
"ETH Zurich D-INFK, Universitaetstr.6, CH-8092 Zurich.",
"Attn: Systems Group.",
"",
"THIS FILE IS AUTOMATICALLY GENERATED BY FLOUNDER: DO NOT EDIT!" ]
--
-- Convert each RPC definition to a pair of underlying call/response messages
--
rpcs_to_msgs :: [MessageDef] -> [MessageDef]
rpcs_to_msgs ml = concat $ map rpc_to_msgs ml
rpc_to_msgs :: MessageDef -> [MessageDef]
rpc_to_msgs (RPC n rpcargs bckargs) = [Message MCall (rpc_call_name n) inargs bckargs,
Message MResponse (rpc_resp_name n) outargs bckargs]
where
(inargs, outargs) = partition_rpc_args rpcargs
rpc_to_msgs m = [m]
-- partition a list of RPC arguments to lists of input and output arguments
partition_rpc_args :: [RPCArgument] -> ([MessageArgument], [MessageArgument])
partition_rpc_args [] = ([], [])
partition_rpc_args (first:rest) = case first of
RPCArgIn t v -> ((Arg t v):restin, restout)
RPCArgOut t v -> (restin, (Arg t v):restout)
where
(restin, restout) = partition_rpc_args rest
msg_argdecl :: Direction -> String -> MessageArgument -> [C.Param]
msg_argdecl dir ifn (Arg tr (Name n)) =
[ C.Param (type_c_type_dir dir ifn tr) n ]
msg_argdecl RX ifn (Arg tr (DynamicArray n l)) =
[ C.Param (C.Ptr $ type_c_type_dir RX ifn tr) n,
C.Param (type_c_type_dir RX ifn size) l ]
msg_argdecl TX ifn (Arg tr (DynamicArray n l)) =
[ C.Param (C.Ptr $ C.ConstT $ type_c_type_dir TX ifn tr) n,
C.Param (type_c_type_dir TX ifn size) l ]
msg_argstructdecl :: String -> [TypeDef] -> MessageArgument -> [C.Param]
msg_argstructdecl ifn typedefs (Arg tr (Name n)) =
[ C.Param (type_c_type_msgstruct ifn typedefs tr) n ]
msg_argstructdecl ifn typedefs a = msg_argdecl RX ifn a
rpc_argdecl :: String -> RPCArgument -> [C.Param]
rpc_argdecl ifn (RPCArgIn tr v) = msg_argdecl TX ifn (Arg tr v)
rpc_argdecl ifn (RPCArgOut tr (Name n)) = [ C.Param (C.Ptr $ type_c_type ifn tr) n ]
rpc_argdecl ifn (RPCArgOut tr (DynamicArray n l)) =
[ C.Param (C.Ptr $ C.Ptr $ type_c_type ifn tr) n,
C.Param (C.Ptr $ type_c_type ifn size) l ]
-- XXX: kludge wrapper to pass array types by reference in RPC
rpc_argdecl2 :: String -> [TypeDef] -> RPCArgument -> [C.Param]
rpc_argdecl2 ifn typedefs arg@(RPCArgOut tr (Name n))
= case lookup_typeref typedefs tr of
TArray _ _ _ -> [ C.Param (C.Ptr $ C.Ptr $ type_c_type ifn tr) n ]
_ -> rpc_argdecl ifn arg
rpc_argdecl2 ifn _ arg = rpc_argdecl ifn arg
-- binding parameter for a function
binding_param ifname = C.Param (C.Ptr $ C.Struct $ intf_bind_type ifname) intf_bind_var
--
-- Generate the code to initialise/destroy a binding structure instance
--
binding_struct_init :: String -> String -> C.Expr -> C.Expr -> C.Expr -> [C.Stmt]
binding_struct_init drv ifn binding_var waitset_ex tx_vtbl_ex = [
C.Ex $ C.Assignment (C.FieldOf binding_var "st") (C.Variable "NULL"),
C.Ex $ C.Assignment (C.FieldOf binding_var "waitset") waitset_ex,
C.Ex $ C.Call "event_mutex_init" [C.AddressOf $ C.FieldOf binding_var "mutex", waitset_ex],
C.Ex $ C.Assignment (C.FieldOf binding_var "can_send")
(C.Variable $ can_send_fn_name drv ifn),
C.Ex $ C.Assignment (C.FieldOf binding_var "register_send")
(C.Variable $ register_send_fn_name drv ifn),
C.Ex $ C.Assignment (C.FieldOf binding_var "error_handler")
(C.Variable $ default_error_handler_fn_name drv ifn),
C.Ex $ C.Assignment (C.FieldOf binding_var "tx_vtbl") tx_vtbl_ex,
C.Ex $ C.Call "memset" [C.AddressOf $ C.FieldOf binding_var "rx_vtbl",
C.NumConstant 0,
C.Call "sizeof" [C.FieldOf binding_var "rx_vtbl"]],
C.Ex $ C.Call "flounder_support_waitset_chanstate_init"
[C.AddressOf $ C.FieldOf binding_var "register_chanstate"],
C.Ex $ C.Call "flounder_support_waitset_chanstate_init"
[C.AddressOf $ C.FieldOf binding_var "tx_cont_chanstate"],
C.StmtList
[C.Ex $ C.Assignment (C.FieldOf binding_var f) (C.NumConstant 0)
| f <- ["tx_msgnum", "rx_msgnum", "tx_msg_fragment", "rx_msg_fragment",
"tx_str_pos", "rx_str_pos", "tx_str_len", "rx_str_len"]],
C.Ex $ C.Assignment (C.FieldOf binding_var "bind_cont") (C.Variable "NULL")]
binding_struct_destroy :: String -> C.Expr -> [C.Stmt]
binding_struct_destroy ifn binding_var
= [C.Ex $ C.Call "flounder_support_waitset_chanstate_destroy"
[C.AddressOf $ C.FieldOf binding_var "register_chanstate"],
C.Ex $ C.Call "flounder_support_waitset_chanstate_destroy"
[C.AddressOf $ C.FieldOf binding_var "tx_cont_chanstate"]]
--
-- Generate a generic can_send function
--
can_send_fn_def :: String -> String -> C.Unit
can_send_fn_def drv ifn =
C.FunctionDef C.Static (C.TypeName "bool") (can_send_fn_name drv ifn) params [
C.Return $ C.Binary C.Equals (bindvar `C.DerefField` "tx_msgnum") (C.NumConstant 0)
]
where
params = [ C.Param (C.Ptr $ C.Struct $ intf_bind_type ifn) "b" ]
bindvar = C.Variable "b"
--
-- generate a generic register_send function
--
register_send_fn_def :: String -> String -> C.Unit
register_send_fn_def drv ifn =
C.FunctionDef C.Static (C.TypeName "errval_t") (register_send_fn_name drv ifn) params [
C.Return $ C.Call "flounder_support_register"
[C.Variable "ws",
C.AddressOf $ bindvar `C.DerefField` "register_chanstate",
C.Variable intf_cont_var,
C.Call (can_send_fn_name drv ifn) [bindvar]]
]
where
params = [ C.Param (C.Ptr $ C.Struct $ intf_bind_type ifn) "b",
C.Param (C.Ptr $ C.Struct "waitset") "ws",
C.Param (C.Struct "event_closure") intf_cont_var ]
bindvar = C.Variable "b"
--
-- generate a default error handler (which the user should replace!)
--
default_error_handler_fn_def :: String -> String -> C.Unit
default_error_handler_fn_def drv ifn =
C.FunctionDef C.Static C.Void (default_error_handler_fn_name drv ifn) params [
C.Ex $ C.Call "DEBUG_ERR"
[errvar, C.StringConstant $
"asynchronous error in Flounder-generated " ++
ifn ++ " " ++ drv ++ " binding (default handler)" ],
C.Ex $ C.Call "abort" []
]
where
params = [ C.Param (C.Ptr $ C.Struct $ intf_bind_type ifn) "b",
C.Param (C.TypeName "errval_t") "err" ]
--
-- generate a generic control function that does nothing
--
generic_control_fn_def :: String -> String -> C.Unit
generic_control_fn_def drv ifn =
C.FunctionDef C.Static (C.TypeName "errval_t") (generic_control_fn_name drv ifn) params [
C.SComment "no control flags are supported",
C.Return $ C.Variable "SYS_ERR_OK"
]
where
params = [C.Param (C.Ptr $ C.Struct $ intf_bind_type ifn) intf_bind_var,
C.Param (C.TypeName "idc_control_t") "control"]
-- register a transmit continuation
register_txcont :: C.Expr -> [C.Stmt]
register_txcont cont_ex = [
C.If (C.Binary C.NotEquals (cont_ex `C.FieldOf` "handler") (C.Variable "NULL"))
[localvar (C.TypeName "errval_t") "_err" Nothing,
C.Ex $ C.Assignment errvar $ C.Call "flounder_support_register"
[bindvar `C.DerefField` "waitset",
C.AddressOf $ bindvar `C.DerefField` "tx_cont_chanstate",
cont_ex,
C.Variable "false"],
C.SComment "may fail if previous continuation hasn't fired yet",
C.If (C.Call "err_is_fail" [errvar])
[C.If (C.Binary C.Equals (C.Call "err_no" [errvar])
(C.Variable "LIB_ERR_CHAN_ALREADY_REGISTERED"))
[C.Return $ C.Variable "FLOUNDER_ERR_TX_BUSY"]
[C.Ex $ C.Call "assert" [C.Unary C.Not $ C.StringConstant "shouldn't happen"],
C.Return $ errvar] ] []
] []
] where
errvar = C.Variable "_err"
-- starting a send: just a debug hook
start_send :: String -> String -> String -> [MessageArgument] -> [C.Stmt]
start_send drvn ifn mn msgargs
= [C.Ex $ C.Call "FL_DEBUG" [C.StringConstant $
drvn ++ " TX " ++ ifn ++ "." ++ mn ++ "\n"]]
-- finished a send: clear msgnum, trigger pending waitsets/events
finished_send :: [C.Stmt]
finished_send = [
C.Ex $ C.Assignment tx_msgnum_field (C.NumConstant 0)] ++
[C.Ex $ C.Call "flounder_support_trigger_chan" [wsaddr ws]
| ws <- ["tx_cont_chanstate", "register_chanstate"]]
where
tx_msgnum_field = C.DerefField bindvar "tx_msgnum"
wsaddr ws = C.AddressOf $ bindvar `C.DerefField` ws
-- start receiving: allocate space for any static arrays in message
start_recv :: String -> String -> [TypeDef] -> String -> [MessageArgument] -> [C.Stmt]
start_recv drvn ifn typedefs mn msgargs
= concat [
[C.Ex $ C.Assignment (field fn)
$ C.Call "malloc" [C.SizeOfT $ type_c_type ifn tr],
C.Ex $ C.Call "assert" [C.Binary C.NotEquals (field fn) (C.Variable "NULL")]
] | Arg tr (Name fn) <- msgargs, is_array tr]
where
field fn = rx_union_elem mn fn
is_array tr = case lookup_typeref typedefs tr of
TArray _ _ _ -> True
_ -> False
-- finished recv: debug, run handler and clean up
finished_recv :: String -> String -> [TypeDef] -> String -> [MessageArgument] -> [C.Stmt]
finished_recv drvn ifn typedefs mn msgargs
= [C.Ex $ C.Call "FL_DEBUG" [C.StringConstant $
drvn ++ " RX " ++ ifn ++ "." ++ mn ++ "\n"],
C.Ex $ C.Call "assert" [C.Binary C.NotEquals handler (C.Variable "NULL")],
C.Ex $ C.CallInd handler (bindvar:args),
C.Ex $ C.Assignment rx_msgnum_field (C.NumConstant 0)]
where
rx_msgnum_field = C.DerefField bindvar "rx_msgnum"
handler = C.DerefField bindvar "rx_vtbl" `C.FieldOf` mn
args = concat [mkargs tr a | Arg tr a <- msgargs]
mkargs tr (Name n) = case lookup_typeref typedefs tr of
TArray _ _ _ -> [C.DerefPtr $ rx_union_elem mn n]
_ -> [rx_union_elem mn n]
mkargs _ (DynamicArray n l) = [rx_union_elem mn n, rx_union_elem mn l]
tx_arg_assignment :: String -> [TypeDef] -> String -> MessageArgument -> C.Stmt
tx_arg_assignment ifn typedefs mn (Arg tr v) = case v of
Name an -> C.Ex $ C.Assignment (tx_union_elem mn an) (srcarg an)
DynamicArray an len -> C.StmtList [
C.Ex $ C.Assignment (tx_union_elem mn an) (C.Cast (C.Ptr typespec) (C.Variable an)),
C.Ex $ C.Assignment (tx_union_elem mn len) (C.Variable len)]
where
typespec = type_c_type ifn tr
srcarg an =
case lookup_typeref typedefs tr of
-- XXX: I have no idea why GCC requires a cast for the array type
TArray _ _ _ -> C.Cast (C.Ptr typespec) (C.Variable an)
_ -> case typespec of
-- we may need to cast away the const on a pointer
C.Ptr _ -> C.Cast typespec (C.Variable an)
_ -> C.Variable an
tx_union_elem :: String -> String -> C.Expr
tx_union_elem mn fn
= bindvar `C.DerefField` "tx_union" `C.FieldOf` mn `C.FieldOf` fn
rx_union_elem :: String -> String -> C.Expr
rx_union_elem mn fn
= bindvar `C.DerefField` "rx_union" `C.FieldOf` mn `C.FieldOf` fn
-- misc common bits of C
localvar = C.VarDecl C.NoScope C.NonConst
errvar = C.Variable "err"
bindvar = C.Variable intf_bind_var
report_user_err ex = C.Ex $ C.CallInd (C.DerefField bindvar "error_handler") [bindvar, ex]
report_user_tx_err ex = C.StmtList [
report_user_err ex,
C.Ex $ C.Assignment tx_msgnum_field (C.NumConstant 0),
C.Ex $ C.Call "flounder_support_trigger_chan" [wsaddr "register_chanstate"],
C.Ex $ C.Call "flounder_support_deregister_chan" [wsaddr "tx_cont_chanstate"]
] where
tx_msgnum_field = C.DerefField bindvar "tx_msgnum"
wsaddr ws = C.AddressOf $ bindvar `C.DerefField` ws
|
utsav2601/cmpe295A
|
tools/flounder/BackendCommon.hs
|
mit
| 18,497 | 0 | 17 | 4,135 | 5,365 | 2,754 | 2,611 | 293 | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.