code
stringlengths 2
1.05M
| repo_name
stringlengths 5
101
| path
stringlengths 4
991
| language
stringclasses 3
values | license
stringclasses 5
values | size
int64 2
1.05M
|
|---|---|---|---|---|---|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
module Betfair.StreamingAPI.API.ToRequest
( ToRequest
, toRequest
) where
-- import Protolude
import Betfair.StreamingAPI.API.Request
import qualified Betfair.StreamingAPI.Requests.AuthenticationMessage as A
import qualified Betfair.StreamingAPI.Requests.HeartbeatMessage as H
import qualified Betfair.StreamingAPI.Requests.MarketSubscriptionMessage as M
import qualified Betfair.StreamingAPI.Requests.OrderSubscriptionMessage as O
class ToRequest a where
toRequest :: a -> Request
instance ToRequest A.AuthenticationMessage where
toRequest a = Authentication a
instance ToRequest H.HeartbeatMessage where
toRequest a = Heartbeat a
instance ToRequest M.MarketSubscriptionMessage where
toRequest a = MarketSubscribe a
instance ToRequest O.OrderSubscriptionMessage where
toRequest a = OrderSubscribe a
|
joe9/streaming-betfair-api
|
src/Betfair/StreamingAPI/API/ToRequest.hs
|
Haskell
|
mit
| 917
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
import Data.Attoparsec.ByteString.Char8 hiding (take)
import qualified Data.ByteString as B
import Control.Applicative
import Data.List (sortBy, groupBy, maximumBy, transpose)
import Data.Ord (comparing)
import Data.Function (on)
import qualified Data.MultiSet as MS
main :: IO ()
main = do
deer <- parseAssert pHerd <$> B.readFile "input.txt"
let time = 2503
print . snd . maxOccur $ scores time deer
maxOccur :: Ord a => MS.MultiSet a -> (a, Int)
maxOccur = maximumBy (comparing snd) . MS.toOccurList
scores :: Time -> [Reindeer] -> MS.MultiSet Reindeer
scores time deer = MS.fromList . concat . take time . zipManyWith best $ deer_dists
where best = map fst . last . groupBy ((==) `on` snd) . sortBy (comparing snd)
best :: [(Reindeer, Distance)] -> [Reindeer]
deer_dists = map single_dists deer
deer_dists :: [[(Reindeer, Distance)]]
single_dists d = map ((,) d) $ distances d
single_dists :: Reindeer -> [(Reindeer, Distance)]
zipManyWith :: ([a] -> b) -> [[a]] -> [b]
zipManyWith f = map f . transpose
distances :: Reindeer -> [Distance]
distances = tail . scanl (+) 0 . gains
traveled :: Time -> Reindeer -> Distance
traveled t = sum . take t . gains
gains :: Reindeer -> [Distance]
gains Reindeer{..} = cycle $ replicate flyTime speed ++ replicate restTime 0
pHerd :: Parser [Reindeer]
pHerd = pReindeer `sepBy` endOfLine <* ending
where ending = many endOfLine <* endOfInput
pReindeer :: Parser Reindeer
pReindeer = Reindeer <$>
pName <* " can fly " <*>
decimal <* " km/s for " <*>
decimal <* " seconds, but then must rest for " <*>
decimal <* " seconds."
where pName = many letter_ascii
data Reindeer = Reindeer {
name :: String,
speed :: Int,
flyTime :: Int,
restTime :: Int
} deriving (Eq, Show, Ord)
type Distance = Int
type Time = Int
parseAssert :: Parser a -> B.ByteString -> a
parseAssert parser input =
case parseOnly parser input of
Right p -> p
Left err -> error $ "Bad parse: " ++ err
|
devonhollowood/adventofcode
|
2015/day14/day14.hs
|
Haskell
|
mit
| 2,114
|
lucky :: Int -> String
lucky 7 = "LUCKY NUMBER SEVEN!"
lucky x = "Sorry, you're out of luck, pal!"
sayMe :: Int -> String
sayMe 1 = "One!"
sayMe 2 = "Two!"
sayMe 3 = "Three!"
sayMe 4 = "Four!"
sayMe 5 = "Five!"
sayMe x = "Not between 1 and 5"
factrial :: Int -> Int
factrial 0 = 1
factrial n = n * factrial (n - 1)
addVectors :: (Double, Double) -> (Double, Double) -> (Double, Double)
addVectors (x1, y1) (x2, y2) = (x1 + x2, y1 + y2)
first :: (a, b, c) -> a
first (x, _, _) = x
second :: (a, b, c) -> b
second (_, y, _) = y
third :: (a, b, c) -> c
third (_, _, z) = z
xs = [(1, 3), (4, 3), (2, 4)]
{- [a + b | (a, b) <- xs] -}
{- head' :: [a] -> a -}
{- head' [] = error "Can't call head on an empty list." -}
{- head' (x:_) = x -}
head' :: [a] -> a
head' xs = case xs of [] -> error "Can't call head on an empty list."
(x:_) -> x
tell :: (Show a) => [a] -> String
tell [] = "The list is empty"
tell (x:[]) = "The list is one element: " ++ show x
tell (x:y:[]) = "The list is two elements: " ++ show x ++ " and " ++ show y
tell (x:y:_) = "This list is long. The first two elements are: " ++ show x ++ " and " ++ show y
firstLetter :: String -> String
firstLetter "" = "Empty string, whoops!"
firstLetter all@(x:xs) = "The first letter of " ++ all ++ " is " ++ [x]
bmiTell :: Double -> Double -> String
bmiTell weight height
| weight / height ^ 2 <= 18.5 = "You're underweight!"
| weight / height ^ 2 <= 25.0 = "You're supposedly normal."
| weight / height ^ 2 <= 30.0 = "You're overweight!"
| otherwise = "You're a whale, congratulations!"
{- bmiTell' :: Double -> Double -> String -}
{- bmiTell' weight height -}
{- | bmi <= 18.5 = "You're underweight!" -}
{- | bmi <= 25.0 = "You're supposedly normal." -}
{- | bmi <= 30.0 = "You're overweight!" -}
{- | otherwise = "You're a whale, congratulations!" -}
{- where bmi = weight / height ^ 2 -}
{- bmiTell' :: Double -> Double -> String -}
{- bmiTell' weight height -}
{- | bmi <= underweight = "You're underweight!" -}
{- | bmi <= normal = "You're supposedly normal." -}
{- | bmi <= overweight = "You're overweight!" -}
{- | otherwise = "You're a whale, congratulations!" -}
{- where bmi = weight / height ^ 2 -}
{- underweight = 18.5 -}
{- normal = 25.0 -}
{- overweight = 30.0 -}
bmiTell' :: Double -> Double -> String
bmiTell' weight height
| bmi <= underweight = "You're underweight!"
| bmi <= normal = "You're supposedly normal."
| bmi <= overweight = "You're overweight!"
| otherwise = "You're a whale, congratulations!"
where bmi = weight / height ^ 2
(underweight, normal, overweight) = (18.5, 25.0, 30.0)
max' :: (Ord a) => a -> a -> a
max' a b
| a <= b = b
| otherwise = a
myCompare :: (Ord a) => a -> a -> Ordering
a `myCompare` b
| a == b = EQ
| a <= b = LT
| otherwise = GT
badGreeting :: String
badGreeting = "Who are you?"
niceGreeting :: String
niceGreeting = "Hello!"
greet :: String -> String
greet "Juan" = niceGreeting ++ " Juan!"
greet "Fernando" = niceGreeting ++ " Fernando!"
greet name = badGreeting ++ " " ++ name
initials :: String -> String -> String
initials firstname lastname = [f] ++ ". " ++ [l] ++ "."
where (f:_) = firstname
(l:_) = lastname
calcBmis :: [(Double, Double)] -> [Double]
calcBmis xs = [bmi w h | (w, h) <- xs]
where bmi weight height = weight / height ^ 2
{- calcBmis' :: [(Double, Double)] -> [Double] -}
{- calcBmis' xs = [bmi | (w, h) <- xs, let bmi = w / h ^ 2] -}
calcBmis' :: [(Double, Double)] -> [Double]
calcBmis' xs = [bmi | (w, h) <- xs, let bmi = w / h ^ 2, bmi > 25.0]
cylinder :: Double -> Double -> Double
cylinder r h =
let sideArea = 2 * pi * r * h
topArea = pi * r ^ 2
in sideArea * topArea
{- 4 * (let a = 9 in a + 1) + 2 -}
{- 42 -}
{- [let square x = x * x in (square 5, square 3, square 2)] -}
{- [(25,9,4)] -}
{- (let a = 100; b = 200; c = 300 in a * b * c, -}
{- let foo = "Hey "; bar = "there!" in foo ++ bar) -}
{- (6000000,"Hey there!") -}
{- (let (a, b, c) = (1, 2, 3) in a + b + c) * 100 -}
{- 600 -}
describeList :: [a] -> String
describeList ls = "The list is "
++ case ls of [] -> "empty."
[x] -> "a singleton list."
xs -> "a longer list."
describeList' :: [a] -> String
describeList' ls = "The list is " ++ what ls
where what [] = "empty."
what [x] = "a singleton list."
what xs = "a longer list."
|
yhoshino11/learning_haskell
|
ch3.hs
|
Haskell
|
mit
| 4,601
|
module Compiler.GCC.JIT.Monad.Result where
import Compiler.GCC.JIT.Monad.Utilities
import Compiler.GCC.JIT.Monad.Types
import Compiler.GCC.JIT.Foreign.Types
import Compiler.GCC.JIT.Foreign.Context
import Foreign.Ptr
import Data.ByteString (ByteString)
import Control.Monad.IO.Class (liftIO)
-- * Result functions
-- | Create a result from the current context
withResult :: (JITResult -> JITState s a) -> JITState s a
withResult f = do
rez <- compile
ret <- f rez
release rez
return ret
-- | Compile the current context and return the result, it is recomend to use 'withResult' instead since you will have to manually free the result from this function with 'releaseResult'
compile :: JITState s JITResult
compile = inContext contextCompile
-- | gcc_jit_result_get_code
getCode :: JITResult
-> ByteString -- ^ Function name
-> JITState s (FunPtr a)
getCode = liftIO2 resultGetCode
-- | gcc_jit_result_get_global
getGlobal :: JITResult
-> ByteString -- ^ Global name
-> JITState s (Ptr a)
getGlobal = liftIO2 resultGetGlobal
-- | Compile the current context to a file
compileToFile :: JITOutputKind -- ^ Output file type
-> ByteString -- ^ Output file path
-> JITState s ()
compileToFile = inContext2 contextCompileToFile
|
Slowki/hgccjit
|
src/Compiler/GCC/JIT/Monad/Result.hs
|
Haskell
|
mit
| 1,311
|
-----------------------------------------------------------------------------
-- |
-- Module : Aether.Parser
-- Copyright : (c) Allen Guo 2013
-- License : MIT
--
-- Maintainer : Allen Guo <guoguo12@gmail.com>
-- Stability : alpha
--
-- This module contains several simple XML-parsing regex
-- functions, as well as other text utility functions.
--
-----------------------------------------------------------------------------
module Aether.Parser ( extractBetween
, extractAllAttrValues
, extractAttrValue
, trim
) where
import Data.Text (pack, strip, unpack)
import Text.Regex (matchRegex, mkRegex, mkRegexWithOpts, splitRegex)
-- | Given a list of strings, returns those strings that are
-- non-null as a list.
nonNull :: [String] -> [String]
nonNull = filter (/= [])
-- | Returns the given string with whitespace trimmed.
trim :: String -> String
trim = unpack . strip . pack
-- | A utility regex function that returns the first match found with
-- the given text and regex string. Returns an empty string if no matches
-- are found.
stdRegex :: String -> String -> String
stdRegex text regex =
case matchRegex (mkRegexWithOpts regex False False) text of
Nothing -> ""
Just matches -> head matches
-- | @extractBetween text start end@ will return the portion of @text@ between
-- @start@ and @end@ as a string.
extractBetween :: String -> String -> String -> String
extractBetween start end text = stdRegex text $ start ++ "(.*)" ++ end
-- | @extractAttrValue text attr@, where @text@ is a XML string, returns
-- the value of the first instance of the XML attribute @attr@. Returns
-- an empty string If no instances of @attr@ exist in the given XML string.
extractAttrValue :: String -> String -> String
extractAttrValue attr text =
case extractAllAttrValues attr text of
[] -> ""
xs -> head xs
-- | @extractAllAttrValues text attr@, where @text@ is a XML string, returns
-- the values of all instances of the XML attribute @attr@.
extractAllAttrValues :: String -> String -> [String]
extractAllAttrValues attr text = nonNull $ map extract chunks where
extract = flip stdRegex (attr ++ "=\"([^\"]*)\"")
chunks = splitRegex (mkRegex "<") text
|
guoguo12/aether
|
src/Aether/Parser.hs
|
Haskell
|
mit
| 2,275
|
module Main where
import Primes
import Digits
import Data.List
isPandigital :: Int -> Bool
isPandigital num = [1..length numDigits] == (sort numDigits)
where
numDigits = digits num
biggestPandigitalPrime = head [ x | x <- downwards(7654321), isPandigital x, isPrime x ]
where
downwards num = num:downwards(num-1)
main = print $ biggestPandigitalPrime
|
kliuchnikau/project-euler
|
041/Main.hs
|
Haskell
|
apache-2.0
| 367
|
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TupleSections #-}
module Tetris.Board where
import Control.Lens
import Data.Bool
import Data.Maybe
import Data.Monoid
import Data.Eq
import Data.Function (($),flip)
import Data.Functor (fmap)
import Data.Int
import Data.Ord (compare)
import qualified Data.List as List
import Data.Set
import Data.String
import GHC.Num
import GHC.Show
import Prelude (error)
import Tetris.Coord
-- | The board is a Set that contains occupied coords
type Board = Set Coord
-- Check if a row of the board is full, ie if all the columns are in the board
isFull :: Board -> Row -> Bool
isFull board row = List.all (\col -> (row,col) `member` board) allColumns
-- Erase rows by removing them from the board
eraseRows :: [Row] -> Board -> Board
eraseRows rows = (\\ coordsToRemove)
where coordsToRemove = fromList $ List.concatMap (\c -> fmap (,c) rows) allColumns
-- the game is over when the highest row is not empty (ie we touched the ceil)
isGameOver :: Board -> Bool
isGameOver board = List.any (\c -> (Digit Zero,c) `member` board) allColumns
-- We start from the row with the highest "toInt" value (that is the lowest
-- row that change in the board) and the we replace each line when we encounter
-- it.
--
-- We then clean the first n rows where n is the number of rows to remove
collapseRows :: [Row] -> Board -> Board
collapseRows [] board = board
collapseRows uFullRows board =
let (i,board',_) = List.foldl' collapseRow (0,board,sFullRows) rowsToChange
-- i - 1 because, e.g., if all rows must be removed then i == 22 but we need 21 (the maxBound)
in case fromInt (i-1) of
-- this error should never occur because i should always be in the
-- rows range, if happens then raise error
Nothing -> throwError $ "The row to erase cannot have number " <> show (i-1)
-- remove the first rows because they fell below
Just lastRow -> eraseRows (fromTo (Digit Zero) lastRow) board'
where
sFullRows = List.sortBy (flip compare) uFullRows -- reverse sorting
rowsToChange = List.reverse $ fromTo (Digit Zero) $ List.head sFullRows
collapseRow :: (Int,Board,[Row]) -> Row -> (Int,Board,[Row])
collapseRow (i,cBoard,frs) currRow =
case uncons frs of
-- when cr == h, the row should be eliminated:
-- skip it and replace it later
Just (h,t) -> if currRow == h then (i+1,cBoard,t)
else collapseRow' i cBoard currRow `extendWith` frs
Nothing -> collapseRow' i cBoard currRow `extendWith` frs
extendWith :: (a,b) -> c -> (a,b,c)
(x,y) `extendWith` z = (x,y,z)
-- row to keep but move => copy this row i rows below
collapseRow' :: Int -> Board -> Row -> (Int,Board)
collapseRow' i cBoard currRow =
let maybeRowToReplace = fromInt (i + toInt currRow)
in case maybeRowToReplace of
-- should not happen because we start from a row to replace,
-- if happens then raise error
Nothing -> throwError $ "The row to replace cannot have number " <> show (i + toInt currRow)
Just rowToReplace ->
-- remove the row to replace and then shift the current row
let cBoard' = cBoard \\ makeFullRow rowToReplace
newRow = fromList $ fmap (rowToReplace,) $
List.foldl' (\l c -> if (currRow,c) `member` cBoard
then c:l
else l)
[] allColumns
in (i,cBoard' `union` newRow)
makeFullRow :: Row -> Set Coord
makeFullRow row = fromList $ fmap (row,) allColumns
-- this will be used for "impossible" state errors to exit asap from the
-- program
throwError :: String -> a
throwError = error
|
melrief/tetris
|
src/Tetris/Board.hs
|
Haskell
|
apache-2.0
| 3,981
|
{-# LANGUAGE TemplateHaskell #-}
{-| PyType helper for Ganeti Haskell code.
-}
{-
Copyright (C) 2013 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.THH.PyType
( PyType(..)
, pyType
, pyOptionalType
) where
import Control.Applicative
import Control.Monad
import Data.List (intercalate)
import Language.Haskell.TH
import Language.Haskell.TH.Syntax (Lift(..))
import Ganeti.PyValue
-- | Represents a Python encoding of types.
data PyType
= PTMaybe PyType
| PTApp PyType [PyType]
| PTOther String
| PTAny
| PTDictOf
| PTListOf
| PTNone
| PTObject
| PTOr
| PTSetOf
| PTTupleOf
deriving (Show, Eq, Ord)
-- TODO: We could use th-lift to generate this instance automatically.
instance Lift PyType where
lift (PTMaybe x) = [| PTMaybe x |]
lift (PTApp tf as) = [| PTApp tf as |]
lift (PTOther i) = [| PTOther i |]
lift PTAny = [| PTAny |]
lift PTDictOf = [| PTDictOf |]
lift PTListOf = [| PTListOf |]
lift PTNone = [| PTNone |]
lift PTObject = [| PTObject |]
lift PTOr = [| PTOr |]
lift PTSetOf = [| PTSetOf |]
lift PTTupleOf = [| PTTupleOf |]
instance PyValue PyType where
-- Use lib/ht.py type aliases to avoid Python creating redundant
-- new match functions for commonly used OpCode param types.
showValue (PTMaybe (PTOther "NonEmptyString")) = ht "MaybeString"
showValue (PTMaybe (PTOther "Bool")) = ht "MaybeBool"
showValue (PTMaybe PTDictOf) = ht "MaybeDict"
showValue (PTMaybe PTListOf) = ht "MaybeList"
showValue (PTMaybe x) = ptApp (ht "Maybe") [x]
showValue (PTApp tf as) = ptApp (showValue tf) as
showValue (PTOther i) = ht i
showValue PTAny = ht "Any"
showValue PTDictOf = ht "DictOf"
showValue PTListOf = ht "ListOf"
showValue PTNone = ht "None"
showValue PTObject = ht "Object"
showValue PTOr = ht "Or"
showValue PTSetOf = ht "SetOf"
showValue PTTupleOf = ht "TupleOf"
ht :: String -> String
ht = ("ht.T" ++)
ptApp :: String -> [PyType] -> String
ptApp name ts = name ++ "(" ++ intercalate ", " (map showValue ts) ++ ")"
-- | Converts a Haskell type name into a Python type name.
pyTypeName :: Name -> PyType
pyTypeName name =
case nameBase name of
"()" -> PTNone
"Map" -> PTDictOf
"Set" -> PTSetOf
"ListSet" -> PTSetOf
"Either" -> PTOr
"GenericContainer" -> PTDictOf
"JSValue" -> PTAny
"JSObject" -> PTObject
str -> PTOther str
-- | Converts a Haskell type into a Python type.
pyType :: Type -> Q PyType
pyType t | not (null args) = PTApp `liftM` pyType fn `ap` mapM pyType args
where (fn, args) = pyAppType t
pyType (ConT name) = return $ pyTypeName name
pyType ListT = return PTListOf
pyType (TupleT 0) = return PTNone
pyType (TupleT _) = return PTTupleOf
pyType typ = fail $ "unhandled case for type " ++ show typ
-- | Returns a type and its type arguments.
pyAppType :: Type -> (Type, [Type])
pyAppType = g []
where
g as (AppT typ1 typ2) = g (typ2 : as) typ1
g as typ = (typ, as)
-- | @pyType opt typ@ converts Haskell type @typ@ into a Python type,
-- where @opt@ determines if the converted type is optional (i.e.,
-- Maybe).
pyOptionalType :: Bool -> Type -> Q PyType
pyOptionalType True typ = PTMaybe <$> pyType typ
pyOptionalType False typ = pyType typ
|
yiannist/ganeti
|
src/Ganeti/THH/PyType.hs
|
Haskell
|
bsd-2-clause
| 4,876
|
{-# LANGUAGE TypeFamilies, TypeOperators, TupleSections #-}
{-# OPTIONS_GHC -Wall #-}
----------------------------------------------------------------------
-- |
-- Module : FunctorCombo.Holey
-- Copyright : (c) Conal Elliott 2010
-- License : BSD3
--
-- Maintainer : conal@conal.net
-- Stability : experimental
--
-- Filling and extracting derivatives (one-hole contexts)
----------------------------------------------------------------------
module FunctorCombo.Holey (Loc,Holey(..),fill) where
import Control.Arrow (first,second)
import FunctorCombo.Functor
import FunctorCombo.Derivative
{--------------------------------------------------------------------
Extraction
--------------------------------------------------------------------}
-- | Location, i.e., one-hole context and a value for the hole.
type Loc f a = (Der f a, a)
-- | Alternative interface for 'fillC'.
fill :: Holey f => Loc f a -> f a
fill = uncurry fillC
-- | Filling and creating one-hole contexts
class Functor f => Holey f where
fillC :: Der f a -> a -> f a -- ^ Fill a hole
extract :: f a -> f (Loc f a) -- ^ All extractions
-- The Functor constraint simplifies several signatures below.
instance Holey (Const z) where
fillC = voidF
extract (Const z) = Const z
instance Holey Id where
fillC (Const ()) = Id
extract (Id a) = Id (Const (), a)
-- fillC (Const ()) a = Id a
-- fill (Const (), a) = Id a
instance (Holey f, Holey g) => Holey (f :+: g) where
fillC (InL df) = InL . fillC df
fillC (InR df) = InR . fillC df
extract (InL fa) = InL ((fmap.first) InL (extract fa))
extract (InR ga) = InR ((fmap.first) InR (extract ga))
-- fillC (InL df) a) = InL (fillC df a)
-- fillC (InR df) a) = InR (fillC df a)
-- fill (InL df, a) = InL (fill (df, a))
-- fill (InR df, a) = InR (fill (df, a))
-- fillC = eitherF ((result.result) InL fillC) ((result.result) InR fillC)
{-
InL fa :: (f :+: g) a
fa :: f a
extract fa :: f (Loc f a)
(fmap.first) InL (extract fa) :: f ((Der f :+: Der g) a, a)
(fmap.first) InL (extract fa) :: f ((Der (f :+: g) a), a)
InL ((fmap.first) InL (extract fa)) :: (f :+: g) ((Der (f :+: g) a), a)
-}
-- Der (f :*: g) = Der f :*: g :+: f :*: Der g
instance (Holey f, Holey g) => Holey (f :*: g) where
fillC (InL (dfa :*: ga)) = (:*: ga) . fillC dfa
fillC (InR ( fa :*: dga)) = (fa :*:) . fillC dga
extract (fa :*: ga) = (fmap.first) (InL . (:*: ga)) (extract fa) :*:
(fmap.first) (InR . (fa :*:)) (extract ga)
-- fillC (InL (dfa :*: ga)) a = fillC dfa a :*: ga
-- fillC (InR ( fa :*: dga)) a = fa :*: fillC dga a
-- fill (InL (dfa :*: ga), a) = fill (dfa, a) :*: ga
-- fill (InR ( fa :*: dga), a) = fa :*: fill (dga, a)
{-
fa :*: ga :: (f :*: g) a
fa :: f a
extract fa :: f (Loc f a)
(fmap.first) (:*: ga) (extract fa) :: f ((Der f :*: g) a, a)
(fmap.first) (InL . (:*: ga)) (extract fa)
:: f (((Der f :*: g) :+: (f :*: Der g)) a, a)
(fmap.first) (InL . (:*: ga)) (extract fa) :: f ((Der (f :*: g)) a, a)
(fmap.first) (InR . (fa :*:)) (extract ga) :: g ((Der (f :*: g)) a, a)
(fmap.first) (InL . (:*: ga)) (extract fa) :*: (fmap.first) (InR . (fa :*:)) (extract ga)
:: (f :*: g) (Der (f :*: g) a, a)
-}
-- type instance Der (g :. f) = Der g :. f :*: Der f
lassoc :: (p,(q,r)) -> ((p,q),r)
lassoc (p,(q,r)) = ((p,q),r)
squishP :: Functor f => (a, f b) -> f (a,b)
squishP (a,fb) = fmap (a,) fb
tweak1 :: Functor f => (dg (fa), f (dfa, a)) -> f ((dg (fa), dfa), a)
tweak1 = fmap lassoc . squishP
chainRule :: (dg (f a), df a) -> ((dg :. f) :*: df) a
chainRule (dgfa, dfa) = O dgfa :*: dfa
tweak2 :: Functor f => (dg (f a), f (df a, a)) -> f (((dg :. f) :*: df) a, a)
tweak2 = (fmap.first) chainRule . tweak1
-- And more specifically,
--
-- tweak2 :: Functor f => (Der g (f a), f (Loc f a)) -> f (((Der g :. f) :*: Der f) a, a)
-- tweak2 :: Functor f => (Der g (f a), f (Loc f a)) -> f (Der (g :. f) a, a)
-- tweak2 :: Functor f => (Der g (f a), f (Loc f a)) -> f (Loc (g :. f) a)
{-
(dg fa, f (dfa,a))
f (dg fa, (df,a))
f ((dg fa, dfa), a)
-}
extractGF :: (Holey f, Holey g) =>
g (f a) -> g (f (Loc (g :. f) a))
extractGF = fmap (tweak2 . second extract) . extract
{-
gfa :: g (f a)
extract gfa :: g (Der g (f a), f a)
fmap (second extract) (extract gfa) :: g (Der g (f a), f (Loc f a))
fmap (tweak2 . second extract) (extract gfa)
:: g (f (Loc (g :. f) a))
-}
-- Der (g :. f) = Der g :. f :*: Der f
instance (Holey f, Holey g) => Holey (g :. f) where
fillC (O dgfa :*: dfa) = O. fillC dgfa . fillC dfa
-- fillC (O dgfa :*: dfa) a = O (fillC dgfa (fillC dfa a))
-- extract (O gfa) = O (extractGF gfa)
extract = inO extractGF
-- fill (O dgfa :*: dfa, a) = O (fill (dgfa, fill (dfa, a)))
{-
O dgfa :*: dfa :: Der (g :. f) a
O dgfa :*: dfa :: (Der g :. f :*: Der f) a
dgfa :: Der g (f a)
dfa :: Der f a
fillC dfa a :: f a
fillC dgfa (fillC dfa a) :: g (f a)
O (fillC dgfa (fillC dfa a)) :: (g :. f) a
-}
|
conal/functor-combo
|
src/FunctorCombo/Holey.hs
|
Haskell
|
bsd-3-clause
| 5,004
|
{-# LANGUAGE ViewPatterns, RecordWildCards #-}
module Cabal(
Cabal(..), CabalSection(..), CabalSectionType,
parseCabal,
selectCabalFile,
selectHiFiles
) where
import System.IO.Extra
import System.Directory.Extra
import System.FilePath
import qualified Data.HashMap.Strict as Map
import Util
import Data.Char
import Data.Maybe
import Data.List.Extra
import Data.Tuple.Extra
import Data.Either.Extra
import Data.Semigroup
import Prelude
selectCabalFile :: FilePath -> IO FilePath
selectCabalFile dir = do
xs <- listFiles dir
case filter ((==) ".cabal" . takeExtension) xs of
[x] -> return x
_ -> fail $ "Didn't find exactly 1 cabal file in " ++ dir
-- | Return the (exposed Hi files, internal Hi files, not found)
selectHiFiles :: FilePath -> Map.HashMap FilePathEq a -> CabalSection -> ([a], [a], [ModuleName])
selectHiFiles distDir his sect@CabalSection{..} = (external, internal, bad1++bad2)
where
(bad1, external) = partitionEithers $
[findHi his sect $ Left cabalMainIs | cabalMainIs /= ""] ++
[findHi his sect $ Right x | x <- cabalExposedModules]
(bad2, internal) = partitionEithers
[findHi his sect $ Right x | x <- filter (not . isPathsModule) cabalOtherModules]
findHi :: Map.HashMap FilePathEq a -> CabalSection -> Either FilePath ModuleName -> Either ModuleName a
findHi his cabal@CabalSection{..} name =
-- error $ show (poss, Map.keys his)
maybe (Left mname) Right $ firstJust (`Map.lookup` his) poss
where
mname = either takeFileName id name
poss = map filePathEq $ possibleHi distDir cabalSourceDirs cabalSectionType $ either (return . dropExtension) (splitOn ".") name
-- | This code is fragile and keeps going wrong, should probably try a less "guess everything"
-- and a more refined filter and test.
possibleHi :: FilePath -> [FilePath] -> CabalSectionType -> [String] -> [FilePath]
possibleHi distDir sourceDirs sectionType components =
[ joinPath (root : x : components) <.> "dump-hi"
| extra <- [".",distDir]
, root <- concat [["build" </> extra </> x </> (x ++ "-tmp")
,"build" </> extra </> x </> x
,"build" </> extra </> x </> (x ++ "-tmp") </> distDir </> "build" </> x </> (x ++ "-tmp")]
| Just x <- [cabalSectionTypeName sectionType]] ++
["build", "build" </> distDir </> "build"]
, x <- sourceDirs ++ ["."]]
data Cabal = Cabal
{cabalName :: PackageName
,cabalSections :: [CabalSection]
} deriving Show
instance Semigroup Cabal where
Cabal x1 x2 <> Cabal y1 y2 = Cabal (x1?:y1) (x2++y2)
instance Monoid Cabal where
mempty = Cabal "" []
mappend = (<>)
data CabalSectionType = Library (Maybe String) | Executable String | TestSuite String | Benchmark String
deriving (Eq,Ord)
cabalSectionTypeName :: CabalSectionType -> Maybe String
cabalSectionTypeName (Library x) = x
cabalSectionTypeName (Executable x) = Just x
cabalSectionTypeName (TestSuite x) = Just x
cabalSectionTypeName (Benchmark x) = Just x
instance Show CabalSectionType where
show (Library Nothing) = "library"
show (Library (Just x)) = "library:" ++ x
show (Executable x) = "exe:" ++ x
show (TestSuite x) = "test:" ++ x
show (Benchmark x) = "bench:" ++ x
instance Read CabalSectionType where
readsPrec _ "library" = [(Library Nothing,"")]
readsPrec _ x
| Just x <- stripPrefix "exe:" x = [(Executable x, "")]
| Just x <- stripPrefix "test:" x = [(TestSuite x, "")]
| Just x <- stripPrefix "bench:" x = [(Benchmark x, "")]
| Just x <- stripPrefix "library:" x = [(Library (Just x), "")]
readsPrec _ _ = []
data CabalSection = CabalSection
{cabalSectionType :: CabalSectionType
,cabalMainIs :: FilePath
,cabalExposedModules :: [ModuleName]
,cabalOtherModules :: [ModuleName]
,cabalSourceDirs :: [FilePath]
,cabalPackages :: [PackageName]
} deriving Show
instance Semigroup CabalSection where
CabalSection x1 x2 x3 x4 x5 x6 <> CabalSection y1 y2 y3 y4 y5 y6 =
CabalSection x1 (x2?:y2) (x3<>y3) (x4<>y4) (x5<>y5) (x6<>y6)
instance Monoid CabalSection where
mempty = CabalSection (Library Nothing) "" [] [] [] []
mappend = (<>)
parseCabal :: FilePath -> IO Cabal
parseCabal = fmap parseTop . readFile'
parseTop = mconcatMap f . parseHanging . filter (not . isComment) . lines
where
isComment = isPrefixOf "--" . trimStart
keyName = (lower *** fst . word1) . word1
f (keyName -> (key, name), xs) = case key of
"name:" -> mempty{cabalName=name}
"library" -> case name of
"" -> mempty{cabalSections=[parseSection (Library Nothing) xs]}
x -> mempty{cabalSections=[parseSection (Library (Just x)) xs]}
"executable" -> mempty{cabalSections=[parseSection (Executable name) xs]}
"test-suite" -> mempty{cabalSections=[parseSection (TestSuite name) xs]}
"benchmark" -> mempty{cabalSections=[parseSection (Benchmark name) xs]}
_ -> mempty
parseSection typ xs = mempty{cabalSectionType=typ} <> parse xs
where
parse = mconcatMap f . parseHanging
keyValues (x,xs) = let (x1,x2) = word1 x in (lower x1, trimEqual $ filter (not . null) $ x2:xs)
trimEqual xs = map (drop n) xs
where n = minimum $ 0 : map (length . takeWhile isSpace) xs
listSplit = concatMap (wordsBy (`elem` " ,"))
isPackageNameChar x = isAlphaNum x || x == '-'
parsePackage = dropSuffix "-any" . takeWhile isPackageNameChar . trim
f (keyValues -> (k,vs)) = case k of
"if" -> parse vs
"else" -> parse vs
"build-depends:" -> mempty{cabalPackages = map parsePackage . splitOn "," $ unwords vs}
"hs-source-dirs:" -> mempty{cabalSourceDirs=listSplit vs}
"exposed-modules:" -> mempty{cabalExposedModules=listSplit vs}
"other-modules:" -> mempty{cabalOtherModules=listSplit vs}
"main-is:" -> mempty{cabalMainIs=headDef "" vs}
_ -> mempty
|
ndmitchell/weeder
|
src/Cabal.hs
|
Haskell
|
bsd-3-clause
| 6,213
|
module Data.TTask.File.Compatibility.V0_0_1_0
( readProject
) where
import Data.Functor
import Safe
import Data.Time
import Control.Lens
import qualified Data.TTask.Types.Types as T
data Task = Task
{ taskId :: T.Id
, taskDescription :: String
, taskPoint :: Int
, taskStatus :: T.TStatus
, taskWorkTimes :: [T.WorkTime]
} deriving (Show, Read, Eq)
data UserStory = UserStory
{ storyId :: T.Id
, storyDescription :: String
, storyTasks :: [Task]
, storyStatus :: T.TStatus
} deriving (Show, Read, Eq)
data Sprint = Sprint
{ sprintId :: T.Id
, sprintDescription :: String
, sprintStorys :: [UserStory]
, sprintStatus :: T.TStatus
} deriving (Show, Read, Eq)
data Project = Project
{ projectName :: String
, projectBacklog :: [UserStory]
, projectSprints :: [Sprint]
, projectStatus :: T.TStatus
} deriving (Show, Read, Eq)
data TTaskContents
= TTaskProject Project
| TTaskSprint Sprint
| TTaskStory UserStory
| TTaskTask Task
-------
readProject :: String -> Maybe T.Project
readProject = (convert <$>) . readOldProject
readOldProject :: String -> Maybe Project
readOldProject s = readMay s
convert :: Project -> T.Project
convert p = T.Project
{ T._projectName = projectName p
, T._projectBacklog = map convertStory $ projectBacklog p
, T._projectSprints = map convertSprint $ projectSprints p
, T._projectStatus = projectStatus p
}
-------
convertTask :: Task -> T.Task
convertTask t = T.Task
{ T._taskId = taskId t
, T._taskDescription = taskDescription t
, T._taskPoint = taskPoint t
, T._taskStatus = taskStatus t
, T._taskWorkTimes = taskWorkTimes t
}
convertStory :: UserStory -> T.UserStory
convertStory u = T.UserStory
{ T._storyId = storyId u
, T._storyDescription = storyDescription u
, T._storyTasks = map convertTask $ storyTasks u
, T._storyStatus = storyStatus u
}
convertSprint :: Sprint -> T.Sprint
convertSprint s = T.Sprint
{ T._sprintId = sprintId s
, T._sprintDescription = sprintDescription s
, T._sprintStorys = map convertStory $ sprintStorys s
, T._sprintStatus = sprintStatus s
}
|
tokiwoousaka/ttask
|
src/Data/TTask/File/Compatibility/V0_0_1_0.hs
|
Haskell
|
bsd-3-clause
| 2,120
|
module DataParsers where
import CSV
import Text.ParserCombinators.Parsec hiding (labels)
import DataTypes
import Control.Monad.Except
import Data.IORef
import Data.Char
import Text.Read hiding (String)
fromRight :: Either a b -> b
fromRight (Right b) = b
maybeToTop :: Maybe WVal -> WVal
maybeToTop (Just w) = w
maybeToTop Nothing = Top
zipSingle :: a -> [b] -> [(a, b)]
zipSingle a [] = []
zipSingle a (b:bs) = (a, b) : zipSingle a bs
readMaybeInteger str = readMaybe fixedStr :: Maybe Integer
where fixedStr = if last str == '.' then init str else str
readMaybeDouble str = readMaybe fixedStr :: Maybe Double
where fixedStr = if last str == '.' then init str else str
parseTyped :: WType -> String -> Maybe WVal
parseTyped TString str = Just $ String str
parseTyped TBool boolStr
| str `elem` ["true", "1", "yes"] = Just $ Bool True
| str `elem` ["false", "0", "no"] = Just $ Bool False
| otherwise = Nothing
where str = map toLower boolStr
parseTyped TIntegral str = fmap Integral (readMaybeInteger str)
parseTyped TFloat str = fmap Float (readMaybeDouble str)
-- [IOThrowsError [Maybe WVal]]
parseTypedRow :: [WType] -> [String] -> IOThrowsError [WVal]
parseTypedRow types rows
| (length types == length rows) = return $ map maybeToTop $ zipWith parseTyped types rows --map (uncurry parseTyped) (zip types rows)
| otherwise = throwError $ CSVParseError $ "Inconsistent number of columns, " ++ show (length types) ++ " vs. " ++ show (length rows)
parseTypedStringTable :: [WType] -> [[String]] -> IOThrowsError [[WVal]]
parseTypedStringTable types strTable = sequenceA (map (parseTypedRow types) strTable)
parseCSVDelim :: Char -> Table -> String -> IOThrowsError WVal
parseCSVDelim delim table toParseFile = do
result <- liftIO $ parseFromFile (csvFile delim) toParseFile
case result of
Left err -> throwError $ CSVParseError (show err)
Right _ -> return Unit
let tableStrings = fromRight result
table' <- liftIO $ readIORef table
let tableTypes = format table'
let (tableValueStrings, newLabels) = if hasHeader table'
then (tail tableStrings, head tableStrings)
else (tableStrings, labels table')
if (hasHeader table') && length tableTypes /= length newLabels
then throwError $ CSVParseError $ "Inconsistent number of columns, " ++ show (length newLabels) ++ " vs. " ++ show (length tableTypes)
else return Unit
newRows <- parseTypedStringTable tableTypes tableValueStrings
let newTable' = table' { rows = newRows, labels = newLabels }
liftIO $ writeIORef table newTable'
return Unit
|
knalbant/wrangell
|
DataParsers.hs
|
Haskell
|
bsd-3-clause
| 2,658
|
{-# LANGUAGE FlexibleContexts #-}
module Cologne.Shaders.Debug (
debug
) where
import Control.Monad.ST
import Data.STRef (newSTRef, readSTRef, writeSTRef)
import Control.Monad.State (State, runState)
import Data.Vect (Vec3(Vec3), (&+), (&*), (&.), (&^), len, normalize)
import Data.Vector.Mutable (MVector, new, read, write)
import Data.Vector (Vector, unsafeFreeze, forM_, enumFromN)
import Graphics.Formats.Assimp (lookAt, position, horizontalFOV, aspect, up,
Camera(Camera))
import Cologne.Primitives hiding (intersect)
import Cologne.AssimpImport (ColorInfo)
-- Just return the color we intersect multiplied by the cosine of the angle of
-- intersection.
radiance :: (AccelStruct a (Vec3 , Vec3, ReflectionType)) =>
a
-> Ray
-> Int
-> Vec3
radiance scene ray _ = do
case aIntersect scene ray of
Miss -> Vec3 0 0 0
Intersection _ (color, _, _) nrm ->
color &* (abs (((direction ray) &. nrm) / ((len (direction ray)) * (len nrm))))
debug :: Context [Primitive ColorInfo] ColorInfo
-> Vector (Vector Vec3)
debug (Context options cams scene) = runST generatePicture
where
generatePicture :: ST s (Vector (Vector Vec3))
generatePicture = do
pic <- new h
forM_ (enumFromN 0 h) $ \row -> do
vec <- new w
forM_ (enumFromN 0 w) $ \column -> do
let val = radiance scene (ray column row) 0
write vec column val
unsafeFreeze vec >>= write pic (h-row-1)
unsafeFreeze pic
w = width options
h = height options
samp = samples options
cam | length cams > 0 = head cams
| otherwise = Camera "" (Vec3 0 0 500) (Vec3 0 1 0)
(Vec3 0 0.1 (-1)) 0.5 1e-2 1e5 1
dir x y = (cx &* (((fromIntegral x) / fromIntegral w) - 0.5))
&+ (cy &* (((fromIntegral y) / fromIntegral h) - 0.5))
&+ (lookAt cam)
ray x y = Ray ((position cam) &+ ((dir x y) &* 140.0)) (normalize (dir x y))
cx = Vec3 (0.5135 * fromIntegral w / fromIntegral h) 0 0
cy = normalize (cx &^ (lookAt cam)) &* 0.5135
|
joelburget/Cologne
|
Cologne/Shaders/Debug.hs
|
Haskell
|
bsd-3-clause
| 2,120
|
-- | Settings are centralized, as much as possible, into this file. This
-- includes database connection settings, static file locations, etc.
-- In addition, you can configure a number of different aspects of Yesod
-- by overriding methods in the Yesod typeclass. That instance is
-- declared in the Foundation.hs file.
module Settings where
import ClassyPrelude.Yesod
import Control.Exception (throw)
import Data.Aeson (Result (..), fromJSON, withObject, (.!=),
(.:?))
import Data.FileEmbed (embedFile)
import Data.Yaml (decodeEither')
import Database.Persist.Sqlite (SqliteConf)
import Language.Haskell.TH.Syntax (Exp, Name, Q)
import Network.Wai.Handler.Warp (HostPreference)
import Yesod.Default.Config2 (applyEnvValue, configSettingsYml)
import Yesod.Default.Util (WidgetFileSettings, widgetFileNoReload,
widgetFileReload)
-- | Runtime settings to configure this application. These settings can be
-- loaded from various sources: defaults, environment variables, config files,
-- theoretically even a database.
data AppSettings = AppSettings
{ appStaticDir :: String
-- ^ Directory from which to serve static files.
, appDatabaseConf :: SqliteConf
-- ^ Configuration settings for accessing the database.
, appRoot :: Text
-- ^ Base for all generated URLs.
, appHost :: HostPreference
-- ^ Host/interface the server should bind to.
, appPort :: Int
-- ^ Port to listen on
, appIpFromHeader :: Bool
-- ^ Get the IP address from the header when logging. Useful when sitting
-- behind a reverse proxy.
, appOauthClientSecret :: Text
-- ^ Oauth2 client secret
, appDetailedRequestLogging :: Bool
-- ^ Use detailed request logging system
, appShouldLogAll :: Bool
-- ^ Should all log messages be displayed?
, appReloadTemplates :: Bool
-- ^ Use the reload version of templates
, appMutableStatic :: Bool
-- ^ Assume that files in the static dir may change after compilation
, appSkipCombining :: Bool
-- ^ Perform no stylesheet/script combining
-- Example app-specific configuration values.
, appCopyright :: Text
-- ^ Copyright text to appear in the footer of the page
, appAnalytics :: Maybe Text
-- ^ Google Analytics code
}
instance FromJSON AppSettings where
parseJSON = withObject "AppSettings" $ \o -> do
let defaultDev =
#if DEVELOPMENT
True
#else
False
#endif
appStaticDir <- o .: "static-dir"
appDatabaseConf <- o .: "database"
appRoot <- o .: "approot"
appHost <- fromString <$> o .: "host"
appPort <- o .: "port"
appIpFromHeader <- o .: "ip-from-header"
appOauthClientSecret <- o .: "oauth-client-secret"
appDetailedRequestLogging <- o .:? "detailed-logging" .!= defaultDev
appShouldLogAll <- o .:? "should-log-all" .!= defaultDev
appReloadTemplates <- o .:? "reload-templates" .!= defaultDev
appMutableStatic <- o .:? "mutable-static" .!= defaultDev
appSkipCombining <- o .:? "skip-combining" .!= defaultDev
appCopyright <- o .: "copyright"
appAnalytics <- o .:? "analytics"
return AppSettings {..}
-- | Settings for 'widgetFile', such as which template languages to support and
-- default Hamlet settings.
--
-- For more information on modifying behavior, see:
--
-- https://github.com/yesodweb/yesod/wiki/Overriding-widgetFile
widgetFileSettings :: WidgetFileSettings
widgetFileSettings = def
-- | How static files should be combined.
combineSettings :: CombineSettings
combineSettings = def
-- The rest of this file contains settings which rarely need changing by a
-- user.
widgetFile :: String -> Q Exp
widgetFile = (if appReloadTemplates compileTimeAppSettings
then widgetFileReload
else widgetFileNoReload)
widgetFileSettings
-- | Raw bytes at compile time of @config/settings.yml@
configSettingsYmlBS :: ByteString
configSettingsYmlBS = $(embedFile configSettingsYml)
-- | @config/settings.yml@, parsed to a @Value@.
configSettingsYmlValue :: Value
configSettingsYmlValue = either throw id $ decodeEither' configSettingsYmlBS
-- | A version of @AppSettings@ parsed at compile time from @config/settings.yml@.
compileTimeAppSettings :: AppSettings
compileTimeAppSettings =
case fromJSON $ applyEnvValue False mempty configSettingsYmlValue of
Error e -> error e
Success settings -> settings
-- The following two functions can be used to combine multiple CSS or JS files
-- at compile time to decrease the number of http requests.
-- Sample usage (inside a Widget):
--
-- > $(combineStylesheets 'StaticR [style1_css, style2_css])
combineStylesheets :: Name -> [Route Static] -> Q Exp
combineStylesheets = combineStylesheets'
(appSkipCombining compileTimeAppSettings)
combineSettings
combineScripts :: Name -> [Route Static] -> Q Exp
combineScripts = combineScripts'
(appSkipCombining compileTimeAppSettings)
combineSettings
|
mitchellwrosen/dohaskell
|
src/Settings.hs
|
Haskell
|
bsd-3-clause
| 5,495
|
-- -----------------------------------------------------------------------------
--
-- Info.hs, part of Alex
--
-- (c) Simon Marlow 2003
--
-- Generate a human-readable rendition of the state machine.
--
-- ----------------------------------------------------------------------------}
module Text.Luthor.Info ( infoDFA ) where
import Text.Luthor.Syntax
import qualified Data.Map
import Text.Luthor.Pretty
import Data.CharSet
import Data.Array
-- -----------------------------------------------------------------------------
-- Generate a human readable dump of the state machine
infoDFA :: Int -> String -> DFA SNum Code -> ShowS
infoDFA _ func_nm dfa
= str "Scanner : " . str func_nm . nl
. str "States : " . shows (length dfa_list) . nl
. nl . infoDFA'
where
dfa_list = Map.toAscList (dfa_states dfa)
infoDFA' = interleave_shows nl (map infoStateN dfa_list)
infoStateN (i,s) = str "State " . shows i . nl . infoState s
infoState :: State SNum Code -> ShowS
infoState (State accs out)
= foldr (.) id (map infoAccept accs)
. infoArr out . nl
infoArr out
= char '\t' . interleave_shows (str "\n\t")
(map infoTransition (Map.toAscList out))
infoAccept (Acc p act lctx rctx)
= str "\tAccept" . paren (shows p) . space
. outputLCtx lctx . space
. showRCtx rctx
. (case act of
Nothing -> id
Just code -> str " { " . str code . str " }")
. nl
infoTransition (char',state)
= str (ljustify 8 (show char'))
. str " -> "
. shows state
outputLCtx Nothing
= id
outputLCtx (Just set)
= paren (outputArr (charSetToArray set)) . char '^'
outputArr arr
= str "Array.array " . shows (bounds arr) . space
. shows (assocs arr)
|
ekmett/luthor
|
Text/Luthor/Info.hs
|
Haskell
|
bsd-3-clause
| 1,781
|
module Network.Kafka.Protocol where
|
iand675/hs-kafka
|
src/Network/Kafka/Protocol.hs
|
Haskell
|
bsd-3-clause
| 36
|
{-# LANGUAGE DeriveDataTypeable #-}
module Main where
import System.Console.CmdArgs
import Com.DiagClient(sendData)
import DiagnosticConfig
import Control.Monad (when)
import Network.Socket
import Script.ErrorMemory
import Script.LoggingFramework
import Numeric(showHex,readHex)
import Util.Encoding
import Data.Word
import LuaTester(executeLuaScript)
import Diagnoser.DiagScriptTester(runTestScript)
import Text.ParserCombinators.Parsec hiding (many, optional, (<|>))
import Text.Parsec.Token
import Control.Applicative
data DiagTool = Diagsend { ip :: String, diagId :: String, message :: String }
| ReadDtc { ip :: String, dtcKind :: Int }
| Logging { logIp :: String, enableLogging :: Bool, showLogging :: Bool }
| DiagTest { ip :: String, script :: String }
| LuaTest { script :: String }
deriving (Show, Data, Typeable)
defaultIp = "127.0.0.1"
diagSend = Diagsend {ip = defaultIp &= help "ip address",
diagId = "10" &= help "diagnosis id",
message = "[0x22,0xF1,0x90]" &= help "diagnostic message to be sent"}
dtc = ReadDtc { ip = defaultIp &= help "ip address",
dtcKind = 1 &= name "k" &= help "[primary = 1, secondary = 2]" } &= help "read DTCs in ecu"
logging = Logging { logIp = defaultIp &= name "i" &= help "ip address",
enableLogging = def &= help "enable logging",
showLogging = def &= help "show mapping"
} &= help "change logging settings"
diagTest = DiagTest { ip = defaultIp &= help "ip address",
script = def &= help "diagnoser script to run" }
luaTest = LuaTest { script = def &= help "lua script to run" }
parseTesterId :: String -> Either ParseError Word8
parseTesterId = parse hexnumber "(unknown)"
parseDiagMsg :: String -> Either ParseError [Word8]
parseDiagMsg = parse hexlist "(unknown)"
hexlist :: CharParser () [Word8]
hexlist = between (char '[') (char ']') (hexnumber `sepBy` char ',')
hexnumber = fst . head . readHex <$> (skipMany (string "0x") *> many1 hexDigit)
main :: IO ()
main = withSocketsDo $ do
actions <- cmdArgs $ (modes [diagSend,dtc,logging,diagTest,luaTest]
&= summary "DiagnosisTool 0.3.0, (c) Oliver Mueller 2010-2011")
&= verbosity
execute actions
execute :: DiagTool -> IO ()
execute (ReadDtc ip x)
| x == 1 = readPrimaryErrorMemory c
| x == 2 = readSecondaryErrorMemory c
where c = femConfig ip
execute (Logging logIp e m) = do
when e enable
when m $ showMappingWithConf conf
execute (DiagTest ip s) = do
-- print $ "running script " ++ s
-- runTestScript s ip
return ()
execute (Diagsend ip diagid m) =
case parseTesterId diagid of
(Right tid) -> do let config = mkConf tid ip
case parseDiagMsg m of
(Right msg) -> sendData config msg >> return ()
_ -> print "diag message format not correct (use s.th. like 0x22,0xF1)" >> return ()
_ -> return ()
|
marcmo/hsDiagnosis
|
Main.hs
|
Haskell
|
bsd-3-clause
| 3,113
|
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE RankNTypes #-}
module Test.Themis.Keyword (
Keyword
, runKeyword
, Context(..)
, Action
, safeAction
, safeActionRollback
, action
, actionRollback
, Interpretation(..)
, step
, info
, assertEquals
, satisfies
) where
import Control.Monad.Error
import Control.Monad.State
import Control.Monad.Trans
import qualified Control.Monad.Trans.Error as CME
import qualified Control.Monad.Trans.State as CMS
{-
Every testeable system with test steps can be represented by keywords.
Keywords are composable actions. These actions has optional backup steps.
Keywords represents a script which can be evaluated with the given
context of the interpretation of each keyword. This way multiple
reusable scripts can be written in the haskell do notation.
-}
data Keyword k a where
KRet :: a -> Keyword k a
KWord :: k a -> Keyword k a
KInfo :: k a -> Keyword k a
KLog :: String -> Keyword k ()
KAssert :: Bool -> String -> Keyword k ()
KBind :: Keyword k a -> (a -> Keyword k b) -> Keyword k b
instance Monad (Keyword k) where
return = KRet
m >>= k = KBind m k
-- | The 'k' step that will be interpreted in some action.
step :: k a -> Keyword k a
step = KWord
-- | The 'k' information what has no rollback
info :: k a -> Keyword k a
info = KInfo
-- | Assertion on the first value, the assertion fails if the
-- first value is False. After the failure the revering actions
-- will be computed.
assertion :: Bool -> String -> Keyword k ()
assertion = KAssert
-- | Logs a message
log :: String -> Keyword k ()
log = KLog
-- | The action consits of a computation that can fail
-- and possibly a revert action.
newtype Action m e a = Action (m (Either e a), Maybe (a -> m ()))
-- | The interpretation of a 'k' basic keyword consists of a pair
-- the first is a computation which computes an error result or a
-- unit, and a revert action of the computation.
newtype Interpretation k m e = Interpretation { unInterpret :: forall a . k a -> Action m e a }
safeAction :: (Functor m, Monad m, Error e) => m a -> Action m e a
safeAction action = Action (fmap Right action, Nothing)
safeActionRollback :: (Functor m, Monad m, Error e) => m a -> (a -> m b) -> Action m e a
safeActionRollback action rollback = Action (fmap Right action, Just (void . rollback))
-- The action has no rollback but the action can fail.
action :: (Functor m, Monad m, Error e) => m (Either e a) -> Action m e a
action act = Action (act, Nothing)
-- The action has a given rollback and the action can fail
actionRollback :: (Functor m, Monad m, Error e) => m (Either e a) -> (a -> m b) -> Action m e a
actionRollback action rollback = Action (action, Just (void . rollback))
-- | The keyword evaluation context consists of an interpretation
-- function, which turns every 'k' command into a monadic computation
data Context k m e = Context {
keywordInterpretation :: Interpretation k m e
, logInterpretation :: String -> m ()
}
newtype Interpreter m e a = KI { unKI :: CME.ErrorT e (CMS.StateT [m ()] m) a }
deriving (Monad, MonadState [m ()], MonadError e)
evalStage0 :: (Monad m, Error e) => Context k m e -> Keyword k a -> Interpreter m e a
evalStage0 ctx (KRet a) = return a
evalStage0 ctx (KInfo k) = do
let Action (step,revert) = (unInterpret $ keywordInterpretation ctx) k
x <- KI . lift $ lift step
case x of
Left e -> throwError e
Right y -> return y
evalStage0 ctx (KLog m) = KI . lift . lift $ logInterpretation ctx m
evalStage0 ctx (KWord k) = do
let Action (step,revert) = (unInterpret $ keywordInterpretation ctx) k
x <- KI . lift $ lift step
case x of
Left e -> throwError e
Right y -> do
maybe (return ()) (\r -> modify (r y:)) revert
return y
evalStage0 ctx (KBind m k) = do
x <- evalStage0 ctx m
evalStage0 ctx (k x)
evalStage0 ctx (KAssert a msg) = unless a . throwError $ strMsg msg
evalStage1 :: (Functor m, Monad m, Error e) => Interpreter m e a -> m (Either e a)
evalStage1 m = do
(result, revert) <- flip CMS.runStateT [] . CME.runErrorT $ unKI m
case result of
Left err -> do sequence_ revert
return (Left err)
Right a -> return (Right a)
-- | The 'runKeyword' interprets the given keyword in a computational context, and
-- reverts the steps if any error occurs.
runKeyword :: (Functor m, Monad m, Error e) => Context k m e -> Keyword k a -> m (Either e a)
runKeyword ctx k = evalStage1 $ evalStage0 ctx k
-- * Helpers
voide :: (Functor m, Monad m, Error e) => m a -> m (Either e ())
voide m = do m >> return (Right ())
-- * Assertions
-- | Checks if the found value equals to the expected one, if it differs
-- the test will fail
assertEquals :: (Show a, Eq a) => a -> a -> String -> Keyword k ()
assertEquals expected found msg =
assertion (found == expected) (concat [msg, " found: ", show found, " expected: ", show expected])
-- | Checks if the found value satisfies the given predicate, it not the test will fail
satisfies :: (Show a) => a -> (a -> Bool) -> String -> Keyword k ()
satisfies value pred msg =
assertion (pred value) (concat [msg, " value: ", show value, " does not satisfies the predicate."])
|
andorp/themis
|
src/Test/Themis/Keyword.hs
|
Haskell
|
bsd-3-clause
| 5,287
|
module Config where
import Data.List
import HSH
-- put any custom default excluded directories or aliased filetypes here etc
sourceFiles :: [String] -> String -> IO [String]
sourceFiles ftypes dir = run ("find", dir:args) where
args = intercalate ["-or"] [["-iname", "*." ++ ftype] | ftype <- ftypes]
|
facebookarchive/lex-pass
|
src/Config.hs
|
Haskell
|
bsd-3-clause
| 306
|
{-# LANGUAGE CPP, DisambiguateRecordFields, RecordWildCards, NamedFieldPuns #-}
{-# LANGUAGE BangPatterns #-}
-- | This module implements parsing and unparsing functions for
-- OpenFlow messages. It exports a driver that can be used to read messages
-- from a file handle and write messages to a handle.
module Nettle.OpenFlow.MessagesBinary (
-- messageDriver2
-- * Parsing and unparsing methods
getHeader
, getSCMessage
, getSCMessageBody
, putSCMessage
, getCSMessage
, getCSMessageBody
, putCSMessage
, OFPHeader(..)
) where
import qualified Data.ByteString as BS
import Data.ByteString (ByteString)
import Nettle.Ethernet.EthernetAddress
import Nettle.Ethernet.EthernetFrame
import Nettle.IPv4.IPAddress
import Nettle.IPv4.IPPacket
import qualified Nettle.OpenFlow.Messages as M
import Nettle.OpenFlow.Port
import Nettle.OpenFlow.Action
import Nettle.OpenFlow.Switch
import Nettle.OpenFlow.Match
import Nettle.OpenFlow.Packet
import Nettle.OpenFlow.FlowTable
import qualified Nettle.OpenFlow.FlowTable as FlowTable
import Nettle.OpenFlow.Statistics
import Nettle.OpenFlow.Error
import Control.Monad (when)
import Control.Exception
import Data.Word
import Data.Bits
import Nettle.OpenFlow.StrictPut
import Data.Binary.Strict.Get
import qualified Data.ByteString as B
import Data.Maybe (fromJust, isJust)
import Data.List as List
import Data.Char (chr)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Bimap (Bimap, (!), (!>))
import qualified Data.Bimap as Bimap
import System.IO
import Control.Concurrent (yield)
import Data.IORef
import Data.Char (ord)
import Debug.Trace
type MessageTypeCode = Word8
ofptHello :: MessageTypeCode
ofptHello = 0
ofptError :: MessageTypeCode
ofptError = 1
ofptEchoRequest :: MessageTypeCode
ofptEchoRequest = 2
ofptEchoReply :: MessageTypeCode
ofptEchoReply = 3
ofptVendor :: MessageTypeCode
ofptVendor = 4
ofptFeaturesRequest :: MessageTypeCode
ofptFeaturesRequest = 5
ofptFeaturesReply :: MessageTypeCode
ofptFeaturesReply = 6
ofptGetConfigRequest :: MessageTypeCode
ofptGetConfigRequest = 7
ofptGetConfigReply :: MessageTypeCode
ofptGetConfigReply = 8
ofptSetConfig :: MessageTypeCode
ofptSetConfig = 9
ofptPacketIn :: MessageTypeCode
ofptPacketIn = 10
ofptFlowRemoved :: MessageTypeCode
ofptFlowRemoved = 11
ofptPortStatus :: MessageTypeCode
ofptPortStatus = 12
ofptPacketOut :: MessageTypeCode
ofptPacketOut = 13
ofptFlowMod :: MessageTypeCode
ofptFlowMod = 14
ofptPortMod :: MessageTypeCode
ofptPortMod = 15
ofptStatsRequest :: MessageTypeCode
ofptStatsRequest = 16
ofptStatsReply :: MessageTypeCode
ofptStatsReply = 17
ofptBarrierRequest :: MessageTypeCode
ofptBarrierRequest = 18
ofptBarrierReply :: MessageTypeCode
ofptBarrierReply = 19
ofptQueueGetConfigRequest :: MessageTypeCode
ofptQueueGetConfigRequest = 20
ofptQueueGetConfigReply :: MessageTypeCode
ofptQueueGetConfigReply = 21
-- | Parser for @SCMessage@s
getSCMessage :: Get (M.TransactionID, M.SCMessage)
getSCMessage = do hdr <- getHeader
getSCMessageBody hdr
-- | Parser for @CSMessage@s
getCSMessage :: Get (M.TransactionID, M.CSMessage)
getCSMessage = do hdr <- getHeader
getCSMessageBody hdr
-- | Unparser for @SCMessage@s
putSCMessage :: (M.TransactionID, M.SCMessage) -> Put
putSCMessage (xid, msg) =
case msg of
M.SCHello -> putH ofptHello headerSize
M.SCEchoRequest bytes -> do putH ofptEchoRequest (headerSize + length bytes)
putWord8s bytes
M.SCEchoReply bytes -> do putH ofptEchoReply (headerSize + length bytes)
putWord8s bytes
M.PacketIn pktInfo -> do let bodyLen = packetInMessageBodyLen pktInfo
putH ofptPacketIn (headerSize + bodyLen)
putPacketInRecord pktInfo
M.Features features -> do putH ofptFeaturesReply (headerSize + 24 + 48 * length (ports features))
putSwitchFeaturesRecord features
M.Error error -> do putH ofptError (headerSize + 2 + 2)
putSwitchError error
where vid = ofpVersion
putH tcode len = putHeader (OFPHeader vid tcode (fromIntegral len) xid)
packetInMessageBodyLen :: PacketInfo -> Int
packetInMessageBodyLen pktInfo = 10 + fromIntegral (packetLength pktInfo)
putPacketInRecord :: PacketInfo -> Put
putPacketInRecord pktInfo@(PacketInfo {..}) =
do putWord32be $ maybe (-1) id bufferID
putWord16be $ fromIntegral packetLength
putWord16be receivedOnPort
putWord8 $ reason2Code reasonSent
putWord8 0
putByteString packetData
{- Header -}
type OpenFlowVersionID = Word8
ofpVersion :: OpenFlowVersionID
#if OPENFLOW_VERSION == 1
ofpVersion = 0x01
#endif
#if OPENFLOW_VERSION == 152
ofpVersion = 0x98
#endif
#if OPENFLOW_VERSION == 151
ofpVersion = 0x97
#endif
-- | OpenFlow message header
data OFPHeader =
OFPHeader { msgVersion :: !OpenFlowVersionID
, msgType :: !MessageTypeCode
, msgLength :: !Word16
, msgTransactionID :: !M.TransactionID
} deriving (Show,Eq)
headerSize :: Int
headerSize = 8
-- | Unparser for OpenFlow message header
putHeader :: OFPHeader -> Put
putHeader (OFPHeader {..}) = do putWord8 msgVersion
putWord8 msgType
putWord16be msgLength
putWord32be msgTransactionID
-- | Parser for the OpenFlow message header
getHeader :: Get OFPHeader
getHeader = do v <- getWord8
t <- getWord8
l <- getWord16be
x <- getWord32be
return $ OFPHeader v t l x
{-# INLINE getHeader #-}
-- Get SCMessage body
{-# INLINE getSCMessageBody #-}
getSCMessageBody :: OFPHeader -> Get (M.TransactionID, M.SCMessage)
getSCMessageBody hdr@(OFPHeader {..}) =
if msgType == ofptPacketIn
then do packetInRecord <- getPacketInRecord len
return (msgTransactionID, M.PacketIn packetInRecord)
else if msgType == ofptEchoRequest
then do bytes <- getWord8s (len - headerSize)
return (msgTransactionID, M.SCEchoRequest bytes)
else if msgType == ofptEchoReply
then do bytes <- getWord8s (len - headerSize)
return (msgTransactionID, M.SCEchoReply bytes)
else if msgType == ofptFeaturesReply
then do switchFeaturesRecord <- getSwitchFeaturesRecord len
return (msgTransactionID, M.Features switchFeaturesRecord)
else if msgType == ofptHello
then return (msgTransactionID, M.SCHello)
else if msgType == ofptPortStatus
then do body <- getPortStatus
return (msgTransactionID, M.PortStatus body)
else if msgType == ofptError
then do body <- getSwitchError len
return (msgTransactionID, M.Error body)
else if msgType == ofptFlowRemoved
then do body <- getFlowRemovedRecord
return (msgTransactionID, M.FlowRemoved body)
else if msgType == ofptBarrierReply
then return (msgTransactionID, M.BarrierReply)
else if msgType == ofptStatsReply
then do body <- getStatsReply len
return (msgTransactionID, M.StatsReply body)
else if msgType == ofptQueueGetConfigReply
then do qcReply <- getQueueConfigReply len
return (msgTransactionID, M.QueueConfigReply qcReply)
else error ("Unrecognized message header: " ++ show hdr)
where len = fromIntegral msgLength
getCSMessageBody :: OFPHeader -> Get (M.TransactionID, M.CSMessage)
getCSMessageBody header@(OFPHeader {..}) =
if msgType == ofptPacketOut
then do packetOut <- getPacketOut len
return (msgTransactionID, M.PacketOut packetOut)
else if msgType == ofptFlowMod
then do mod <- getFlowMod len
return (msgTransactionID, M.FlowMod mod)
else if msgType == ofptHello
then return (msgTransactionID, M.CSHello)
else if msgType == ofptEchoRequest
then do bytes <- getWord8s (len - headerSize)
return (msgTransactionID, M.CSEchoRequest bytes)
else if msgType == ofptEchoReply
then do bytes <- getWord8s (len - headerSize)
return (msgTransactionID, M.CSEchoReply bytes)
else if msgType == ofptFeaturesRequest
then return (msgTransactionID, M.FeaturesRequest)
else if msgType == ofptSetConfig
then do _ <- getSetConfig
return (msgTransactionID, M.SetConfig)
else if msgType == ofptVendor
then do vMsg <- getVendorMessage
return (msgTransactionID, M.Vendor vMsg)
else error ("Unrecognized message type with header: " ++ show header)
where len = fromIntegral msgLength
-----------------------
-- Queue Config parser
-----------------------
getQueueConfigReply :: Int -> Get QueueConfigReply
getQueueConfigReply len =
do portID <- getWord16be
skip 6
qs <- getQueues 16 []
return (PortQueueConfig portID qs)
where
getQueues pos acc =
if pos < len
then do (q, n) <- getQueue
let pos' = pos + n
pos' `seq` getQueues pos' (q:acc)
else return acc
getQueue =
do qid <- getWord32be
qdlen <- getWord16be
skip 2
qprops <- getQueueProps qdlen 8 [] -- at byte 8 because of ofp_packet_queue header and len includes header (my guess).
return (QueueConfig qid qprops, fromIntegral qdlen)
where
getQueueProps qdlen pos acc =
if pos < qdlen
then do (prop, propLen) <- getQueueProp
let pos' = pos + propLen
pos' `seq` getQueueProps qdlen pos' (prop : acc)
else return acc
getQueueProp =
do propType <- getWord16be
propLen <- getWord16be
skip 4
rate <- getWord16be
skip 6
let rate' = if rate > 1000 then Disabled else Enabled rate
let prop
| propType == ofpqtMinRate = MinRateQueue rate'
| propType == ofpqtMaxRate = MaxRateQueue rate'
| otherwise = error ("Unexpected queue property type code " ++ show propType)
return (prop, propLen)
ofpqtMinRate :: Word16
ofpqtMinRate = 1
ofpqtMaxRate :: Word16 -- Indigo switches support max rate this way
ofpqtMaxRate = 2
----------------------
-- Set Config parser
----------------------
getSetConfig :: Get (Word16, Word16)
getSetConfig = do flags <- getWord16be
missSendLen <- getWord16be
return (flags, missSendLen)
-------------------------------------------
-- Vendor parser
-------------------------------------------
getVendorMessage :: Get ByteString
getVendorMessage = do
r <- remaining
getByteString r
-------------------------------------------
-- SWITCH FEATURES PARSER
-------------------------------------------
putSwitchFeaturesRecord (SwitchFeatures {..}) = do
putWord64be switchID
putWord32be $ fromIntegral packetBufferSize
putWord8 $ fromIntegral numberFlowTables
sequence_ $ replicate 3 (putWord8 0)
putWord32be $ switchCapabilitiesBitVector capabilities
putWord32be $ actionTypesBitVector supportedActions
sequence_ [ putPhyPort p | p <- ports ]
getSwitchFeaturesRecord len = do
dpid <- getWord64be
nbufs <- getWord32be
ntables <- getWord8
skip 3
caps <- getWord32be
acts <- getWord32be
ports <- sequence (replicate num_ports getPhyPort)
return (SwitchFeatures dpid (fromIntegral nbufs) (fromIntegral ntables) (bitMap2SwitchCapabilitySet caps) (bitMap2SwitchActionSet acts) ports)
where ports_offset = 32
num_ports = (len - ports_offset) `div` size_ofp_phy_port
size_ofp_phy_port = 48
putPhyPort :: Port -> Put
putPhyPort (Port {..}) =
do putWord16be portID
putEthernetAddress portAddress
mapM_ putWord8 $ take ofpMaxPortNameLen (map (fromIntegral . ord) portName ++ repeat 0)
putWord32be $ portConfigsBitVector portConfig
putWord32be $ portState2Code portLinkDown portSTPState
putWord32be $ featuresBitVector $ maybe [] id portCurrentFeatures
putWord32be $ featuresBitVector $ maybe [] id portAdvertisedFeatures
putWord32be $ featuresBitVector $ maybe [] id portSupportedFeatures
putWord32be $ featuresBitVector $ maybe [] id portPeerFeatures
getPhyPort :: Get Port
getPhyPort = do
port_no <- getWord16be
hw_addr <- getEthernetAddress
name_arr <- getWord8s ofpMaxPortNameLen
let port_name = [ chr (fromIntegral b) | b <- takeWhile (/=0) name_arr ]
cfg <- getWord32be
st <- getWord32be
let (linkDown, stpState) = code2PortState st
curr <- getWord32be
adv <- getWord32be
supp <- getWord32be
peer <- getWord32be
return $ Port { portID = port_no,
portName = port_name,
portAddress = hw_addr,
portConfig = bitMap2PortConfigAttributeSet cfg,
portLinkDown = linkDown,
portSTPState = stpState,
portCurrentFeatures = decodePortFeatureSet curr,
portAdvertisedFeatures = decodePortFeatureSet adv,
portSupportedFeatures = decodePortFeatureSet supp,
portPeerFeatures = decodePortFeatureSet peer
}
ofpMaxPortNameLen = 16
featuresBitVector :: [PortFeature] -> Word32
featuresBitVector = foldl (\v f -> v .|. featureBitMask f) 0
featureBitMask :: PortFeature -> Word32
featureBitMask feat =
case lookup feat featurePositions of
Nothing -> error "unexpected port feature"
Just i -> bit i
decodePortFeatureSet :: Word32 -> Maybe [PortFeature]
decodePortFeatureSet word
| word == 0 = Nothing
| otherwise = Just $ concat [ if word `testBit` position then [feat] else [] | (feat, position) <- featurePositions ]
featurePositions :: [(PortFeature, Int)]
featurePositions = [ (Rate10MbHD, 0),
(Rate10MbFD, 1),
(Rate100MbHD, 2),
(Rate100MbFD, 3),
(Rate1GbHD, 4),
(Rate1GbFD, 5),
(Rate10GbFD, 6),
(Copper, 7),
(Fiber, 8),
(AutoNegotiation, 9),
(Pause, 10),
(AsymmetricPause, 11) ]
ofppsLinkDown, ofppsStpListen, ofppsStpLearn, ofppsStpForward :: Word32
ofppsLinkDown = 1 `shiftL` 0 -- 1 << 0
ofppsStpListen = 0 `shiftL` 8 -- 0 << 8
ofppsStpLearn = 1 `shiftL` 8 -- 1 << 8
ofppsStpForward = 2 `shiftL` 8 -- 2 << 8
ofppsStpBlock = 3 `shiftL` 8 -- 3 << 8
ofppsStpMask = 3 `shiftL` 8 -- 3 << 8
code2PortState :: Word32 -> (Bool, SpanningTreePortState)
code2PortState w = (w .&. ofppsLinkDown /= 0, stpState)
where stpState
| flag == ofppsStpListen = STPListening
| flag == ofppsStpLearn = STPLearning
| flag == ofppsStpForward = STPForwarding
| flag == ofppsStpBlock = STPBlocking
| otherwise = error "Unrecognized port status code."
flag = w .&. ofppsStpMask
portState2Code :: Bool -> SpanningTreePortState -> Word32
portState2Code isUp stpState =
let b1 = if isUp then ofppsLinkDown else 0
b2 = case stpState of
STPListening -> ofppsStpListen
STPLearning -> ofppsStpLearn
STPForwarding -> ofppsStpForward
STPBlocking -> ofppsStpBlock
in b1 .|. b2
bitMap2PortConfigAttributeSet :: Word32 -> [PortConfigAttribute]
bitMap2PortConfigAttributeSet bmap = filter inBMap $ enumFrom $ toEnum 0
where inBMap attr = let mask = portAttribute2BitMask attr
in mask .&. bmap == mask
portConfigsBitVector :: [PortConfigAttribute] -> Word32
portConfigsBitVector = foldl (\v a -> v .|. portAttribute2BitMask a) 0
portAttribute2BitMask :: PortConfigAttribute -> Word32
portAttribute2BitMask PortDown = shiftL 1 0
portAttribute2BitMask STPDisabled = shiftL 1 1
portAttribute2BitMask OnlySTPackets = shiftL 1 2
portAttribute2BitMask NoSTPackets = shiftL 1 3
portAttribute2BitMask NoFlooding = shiftL 1 4
portAttribute2BitMask DropForwarded = shiftL 1 5
portAttribute2BitMask NoPacketInMsg = shiftL 1 6
portAttributeSet2BitMask :: [PortConfigAttribute] -> Word32
portAttributeSet2BitMask = foldl f 0
where f mask b = mask .|. portAttribute2BitMask b
bitMap2SwitchCapabilitySet :: Word32 -> [SwitchCapability]
bitMap2SwitchCapabilitySet bmap = filter inBMap $ enumFrom $ toEnum 0
where inBMap attr = let mask = switchCapability2BitMask attr
in mask .&. bmap == mask
switchCapabilitiesBitVector :: [SwitchCapability] -> Word32
switchCapabilitiesBitVector =
foldl (\vector c -> vector .|. switchCapability2BitMask c) 0
switchCapability2BitMask :: SwitchCapability -> Word32
switchCapability2BitMask HasFlowStats = shiftL 1 0
switchCapability2BitMask HasTableStats = shiftL 1 1
switchCapability2BitMask HasPortStats = shiftL 1 2
switchCapability2BitMask SpanningTree = shiftL 1 3
-- #if OPENFLOW_VERSION==151 || OPENFLOW_VERSION==152
switchCapability2BitMask MayTransmitOverMultiplePhysicalInterfaces = shiftL 1 4
-- #endif
switchCapability2BitMask CanReassembleIPFragments = shiftL 1 5
-- #if OPENFLOW_VERSION==1
switchCapability2BitMask HasQueueStatistics = shiftL 1 6
switchCapability2BitMask CanMatchIPAddressesInARPPackets = shiftL 1 7
-- #endif
bitMap2SwitchActionSet :: Word32 -> [ActionType]
bitMap2SwitchActionSet bmap = filter inBMap $ enumFrom $ toEnum 0
where inBMap attr = let mask = actionType2BitMask attr
in mask .&. bmap == mask
actionTypesBitVector :: [ActionType] -> Word32
actionTypesBitVector = foldl (\v a -> v .|. actionType2BitMask a) 0
{-
code2ActionType :: Word16 -> ActionType
code2ActionType code =
case Bimap.lookupR code $ actionType2CodeBijection of
Just x -> x
Nothing -> error ("In code2ActionType: encountered unknown action type code: " ++ show code)
-}
code2ActionType :: Word16 -> ActionType
code2ActionType !code =
case code of
0 -> OutputToPortType
1 -> SetVlanVIDType
2 -> SetVlanPriorityType
3 -> StripVlanHeaderType
4 -> SetEthSrcAddrType
5 -> SetEthDstAddrType
6 -> SetIPSrcAddrType
7 -> SetIPDstAddrType
8 -> SetIPTypeOfServiceType
9 -> SetTransportSrcPortType
10 -> SetTransportDstPortType
11 -> EnqueueType
0xffff -> VendorActionType
{-# INLINE code2ActionType #-}
actionType2Code :: ActionType -> Word16
actionType2Code OutputToPortType = 0
actionType2Code SetVlanVIDType = 1
actionType2Code SetVlanPriorityType = 2
actionType2Code StripVlanHeaderType = 3
actionType2Code SetEthSrcAddrType = 4
actionType2Code SetEthDstAddrType = 5
actionType2Code SetIPSrcAddrType = 6
actionType2Code SetIPDstAddrType = 7
actionType2Code SetIPTypeOfServiceType = 8
actionType2Code SetTransportSrcPortType = 9
actionType2Code SetTransportDstPortType = 10
actionType2Code EnqueueType = 11
actionType2Code VendorActionType = 0xffff
{-# INLINE actionType2Code #-}
{-
actionType2Code a =
case Bimap.lookup a actionType2CodeBijection of
Just x -> x
Nothing -> error ("In actionType2Code: encountered unknown action type: " ++ show a)
-}
actionType2CodeBijection :: Bimap ActionType Word16
actionType2CodeBijection =
Bimap.fromList [(OutputToPortType, 0)
, (SetVlanVIDType, 1)
, (SetVlanPriorityType, 2)
, (StripVlanHeaderType, 3)
, (SetEthSrcAddrType, 4)
, (SetEthDstAddrType, 5)
, (SetIPSrcAddrType, 6)
, (SetIPDstAddrType, 7)
, (SetIPTypeOfServiceType, 8)
, (SetTransportSrcPortType, 9)
, (SetTransportDstPortType, 10)
, (EnqueueType, 11)
, (VendorActionType, 0xffff)
]
actionType2BitMask :: ActionType -> Word32
actionType2BitMask = shiftL 1 . fromIntegral . actionType2Code
------------------------------------------
-- Packet In Parser
------------------------------------------
{-# INLINE getPacketInRecord #-}
getPacketInRecord :: Int -> Get PacketInfo
getPacketInRecord len = do
bufID <- getWord32be
totalLen <- getWord16be
in_port <- getWord16be
reasonCode <- getWord8
skip 1
bytes <- getByteString (fromIntegral data_len)
let reason = code2Reason reasonCode
let mbufID = if (bufID == maxBound) then Nothing else Just bufID
let frame = {-# SCC "getPacketInRecord1" #-} fst (runGet getEthernetFrame bytes)
return $ PacketInfo mbufID (fromIntegral totalLen) in_port reason bytes frame
where data_offset = 18 -- 8 + 4 + 2 + 2 + 1 + 1
data_len = len - data_offset
{-# INLINE code2Reason #-}
code2Reason :: Word8 -> PacketInReason
code2Reason !code
| code == 0 = NotMatched
| code == 1 = ExplicitSend
| otherwise = error ("Received unknown packet-in reason code: " ++ show code ++ ".")
{-# INLINE reason2Code #-}
reason2Code :: PacketInReason -> Word8
reason2Code NotMatched = 0
reason2Code ExplicitSend = 1
------------------------------------------
-- Port Status parser
------------------------------------------
getPortStatus :: Get PortStatus
getPortStatus = do
reasonCode <- getWord8
skip 7
portDesc <- getPhyPort
return $ (code2PortStatusUpdateReason reasonCode, portDesc)
code2PortStatusUpdateReason code =
if code == 0
then PortAdded
else if code == 1
then PortDeleted
else if code == 2
then PortModified
else error ("Unkown port status update reason code: " ++ show code)
------------------------------------------
-- Switch Error parser
------------------------------------------
getSwitchError :: Int -> Get SwitchError
getSwitchError len = do
typ <- getWord16be
code <- getWord16be
bytes <- getWord8s (len - headerSize - 4)
return (code2ErrorType typ code bytes)
putSwitchError :: SwitchError -> Put
putSwitchError (BadRequest VendorNotSupported []) =
do putWord16be 1
putWord16be 3
code2ErrorType :: Word16 -> Word16 -> [Word8] -> SwitchError
#if OPENFLOW_VERSION==151
code2ErrorType typ code bytes
| typ == 0 = HelloFailed (helloErrorCodesMap ! code) [ chr (fromIntegral b) | b <- takeWhile (/=0) bytes ]
| typ == 1 = BadRequest (requestErrorCodeMap ! code) bytes
| typ == 2 = BadAction code bytes
| typ == 3 = FlowModFailed code bytes
#endif
#if OPENFLOW_VERSION==152
code2ErrorType typ code bytes
| typ == 0 = HelloFailed (helloErrorCodesMap ! code) [ chr (fromIntegral b) | b <- takeWhile (/=0) bytes ]
| typ == 1 = BadRequest (requestErrorCodeMap ! code) bytes
| typ == 2 = BadAction (actionErrorCodeMap ! code) bytes
| typ == 3 = FlowModFailed (flowModErrorCodeMap ! code) bytes
#endif
#if OPENFLOW_VERSION==1
code2ErrorType typ code bytes
| typ == 0 = HelloFailed (helloErrorCodesMap ! code) [ chr (fromIntegral b) | b <- takeWhile (/=0) bytes ]
| typ == 1 = BadRequest (requestErrorCodeMap ! code) bytes
| typ == 2 = BadAction (actionErrorCodeMap ! code) bytes
| typ == 3 = FlowModFailed (flowModErrorCodeMap ! code) bytes
| typ == 4 = PortModFailed (portModErrorCodeMap ! code) bytes
| typ == 5 = QueueOperationFailed (queueOpErrorCodeMap ! code) bytes
#endif
helloErrorCodesMap = Bimap.fromList [ (0, IncompatibleVersions)
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
, (1 , HelloPermissionsError)
#endif
]
requestErrorCodeMap = Bimap.fromList [ (0, VersionNotSupported),
(1 , MessageTypeNotSupported),
(2 , StatsRequestTypeNotSupported),
(3 , VendorNotSupported),
(4, VendorSubtypeNotSupported)
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
, (5 , RequestPermissionsError)
#endif
#if OPENFLOW_VERSION==1
, (6 , BadRequestLength)
, (7, BufferEmpty)
, (8, UnknownBuffer)
#endif
]
actionErrorCodeMap = Bimap.fromList [ (0, UnknownActionType),
(1, BadActionLength),
(2, UnknownVendorID),
(3, UnknownActionTypeForVendor),
(4, BadOutPort),
(5, BadActionArgument)
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
, (6, ActionPermissionsError)
#endif
#if OPENFLOW_VERSION==1
, (7, TooManyActions)
, (8, InvalidQueue)
#endif
]
flowModErrorCodeMap = Bimap.fromList [ (0, TablesFull)
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
, (1, OverlappingFlow)
, (2, FlowModPermissionsError)
, (3, EmergencyModHasTimeouts)
#endif
#if OPENFLOW_VERSION==1
, (4, BadCommand)
, (5, UnsupportedActionList)
#endif
]
portModErrorCodeMap = Bimap.fromList [ (0, BadPort)
, (1, BadHardwareAddress)
]
queueOpErrorCodeMap = Bimap.fromList [ (0, QueueOpBadPort)
, (1, QueueDoesNotExist)
, (2, QueueOpPermissionsError)
]
------------------------------------------
-- FlowRemoved parser
------------------------------------------
#if OPENFLOW_VERSION==151
getFlowRemovedRecord :: Get FlowRemoved
getFlowRemovedRecord = do
m <- getMatch
p <- get
rcode <- get
skip 1
dur <- getWord32be
skip 4
pktCount <- getWord64be
byteCount <- getWord64be
return $ FlowRemoved m p (code2FlowRemovalReason rcode) (fromIntegral dur) (fromIntegral pktCount) (fromIntegral byteCount)
#endif
#if OPENFLOW_VERSION==152
getFlowRemovedRecord :: Get FlowRemoved
getFlowRemovedRecord = do
m <- getMatch
p <- getWord16be
rcode <- getWord8
skip 1
dur <- getWord32be
idle_timeout <- getWord16be
skip 6
pktCount <- getWord64be
byteCount <- getWord64be
return $ FlowRemoved m p (code2FlowRemovalReason rcode) (fromIntegral dur) (fromIntegral idle_timeout) (fromIntegral pktCount) (fromIntegral byteCount)
#endif
#if OPENFLOW_VERSION==1
getFlowRemovedRecord :: Get FlowRemoved
getFlowRemovedRecord = do
m <- getMatch
cookie <- getWord64be
p <- getWord16be
rcode <- getWord8
skip 1
dur <- getWord32be
dur_nsec <- getWord32be
idle_timeout <- getWord16be
skip 2
pktCount <- getWord64be
byteCount <- getWord64be
return $ FlowRemovedRecord m cookie p (code2FlowRemovalReason rcode) (fromIntegral dur) (fromIntegral dur_nsec) (fromIntegral idle_timeout) (fromIntegral pktCount) (fromIntegral byteCount)
#endif
#if OPENFLOW_VERSION==151
flowRemovalReason2CodeBijection :: Bimap FlowRemovalReason Word8
flowRemovalReason2CodeBijection =
Bimap.fromList [(IdleTimerExpired, 0),
(HardTimerExpired, 1) ]
#endif
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
flowRemovalReason2CodeBijection :: Bimap FlowRemovalReason Word8
flowRemovalReason2CodeBijection =
Bimap.fromList [(IdleTimerExpired, 0),
(HardTimerExpired, 1),
(DeletedByController, 2) ]
#endif
code2FlowRemovalReason rcode = (Bimap.!>) flowRemovalReason2CodeBijection rcode
-----------------------------------------
-- Stats Reply parser
-----------------------------------------
getStatsReply :: Int -> Get StatsReply
getStatsReply headerLen = do
statsType <- getWord16be
flags <- getWord16be
let bodyLen = headerLen - (headerSize + 4)
let moreFlag = flags == 0x0001
if statsType == ofpstFlow
then do flowStats <- getFlowStatsReplies bodyLen
return (FlowStatsReply moreFlag flowStats)
else if statsType == ofpstPort
then do portStats <- getPortStatsReplies bodyLen
return (PortStatsReply moreFlag portStats)
else if statsType == ofpstAggregate
then do aggStats <- getAggregateStatsReplies bodyLen
return (AggregateFlowStatsReply aggStats)
else if statsType == ofpstTable
then do tableStats <- getTableStatsReplies bodyLen
return (TableStatsReply moreFlag tableStats)
else if statsType == ofpstDesc
then do desc <- getDescriptionReply
return (DescriptionReply desc)
else
#if OPENFLOW_VERSION==1
if statsType == ofpstQueue
then do queueStats <- getQueueStatsReplies bodyLen
return (QueueStatsReply moreFlag queueStats)
else
#endif
error ("unhandled stats reply message with type: " ++ show statsType)
#if OPENFLOW_VERSION==1
getQueueStatsReplies :: Int -> Get [QueueStats]
getQueueStatsReplies bodyLen = do
sequence (replicate cnt getQueueStatsReply)
where cnt = let (d,m) = bodyLen `divMod` queueStatsLength
in if m == 0
then d
else error ("Body of queue stats reply must be a multiple of " ++ show queueStatsLength)
queueStatsLength = 32
getQueueStatsReply = do
portNo <- getWord16be
skip 2
qid <- getWord32be
tx_bytes <- getWord64be
tx_packets <- getWord64be
tx_errs <- getWord64be
return (QueueStats { queueStatsPortID = portNo,
queueStatsQueueID = qid,
queueStatsTransmittedBytes = fromIntegral tx_bytes,
queueStatsTransmittedPackets = fromIntegral tx_packets,
queueStatsTransmittedErrors = fromIntegral tx_errs })
#endif
getDescriptionReply :: Get Description
getDescriptionReply = do
mfr <- getCharsRightPadded descLen
hw <- getCharsRightPadded descLen
sw <- getCharsRightPadded descLen
serial <- getCharsRightPadded descLen
dp <- getCharsRightPadded serialNumLen
return ( Description { manufacturerDesc = mfr
, hardwareDesc = hw
, softwareDesc = sw
, serialNumber = serial
#if OPENFLOW_VERSION==1
, datapathDesc = dp
#endif
} )
where descLen = 256
serialNumLen = 32
getCharsRightPadded :: Int -> Get String
getCharsRightPadded n = do
bytes <- getWord8s n
return [ chr (fromIntegral b) | b <- takeWhile (/=0) bytes]
getTableStatsReplies :: Int -> Get [TableStats]
getTableStatsReplies bodyLen = sequence (replicate cnt getTableStatsReply)
where cnt = let (d,m) = bodyLen `divMod` tableStatsLength
in if m == 0
then d
else error ("Body of Table stats reply must be a multiple of " ++ show tableStatsLength)
tableStatsLength = 64
getTableStatsReply :: Get TableStats
getTableStatsReply = do
tableID <- getWord8
skip 3
name_bytes <- getWord8s maxTableNameLen
let name = [ chr (fromIntegral b) | b <- name_bytes ]
wcards <- getWord32be
maxEntries <- getWord32be
activeCount <- getWord32be
lookupCount <- getWord64be
matchedCount <- getWord64be
return ( TableStats { tableStatsTableID = tableID,
tableStatsTableName = name,
tableStatsMaxEntries = fromIntegral maxEntries,
tableStatsActiveCount = fromIntegral activeCount,
tableStatsLookupCount = fromIntegral lookupCount,
tableStatsMatchedCount = fromIntegral matchedCount } )
where maxTableNameLen = 32
getFlowStatsReplies :: Int -> Get [FlowStats]
getFlowStatsReplies bodyLen
| bodyLen == 0 = return []
| otherwise = do (fs,fsLen) <- getFlowStatsReply
rest <- getFlowStatsReplies (bodyLen - fsLen)
return (fs : rest)
getFlowStatsReply :: Get (FlowStats, Int)
getFlowStatsReply = do len <- getWord16be
tid <- getWord8
skip 1
match <- getMatch
dur_sec <- getWord32be
#if OPENFLOW_VERSION==1
dur_nanosec <- getWord32be
#endif
priority <- getWord16be
idle_to <- getWord16be
hard_to <- getWord16be
#if OPENFLOW_VERSION==151
skip 6
#endif
#if OPENFLOW_VERSION==152
skip 2
#endif
#if OPENFLOW_VERSION==1
skip 6
cookie <- getWord64be
#endif
packet_count <- getWord64be
byte_count <- getWord64be
let numActions = (fromIntegral len - flowStatsReplySize) `div` actionSize
actions <- sequence (replicate numActions getAction)
let stats = FlowStats { flowStatsTableID = tid,
flowStatsMatch = match,
flowStatsDurationSeconds = fromIntegral dur_sec,
#if OPENFLOW_VERSION==1
flowStatsDurationNanoseconds = fromIntegral dur_nanosec,
#endif
flowStatsPriority = priority,
flowStatsIdleTimeout = fromIntegral idle_to,
flowStatsHardTimeout = fromIntegral hard_to,
#if OPENFLOW_VERSION==1
flowStatsCookie = cookie,
#endif
flowStatsPacketCount = fromIntegral packet_count,
flowStatsByteCount = fromIntegral byte_count,
flowStatsActions = actions }
return (stats, fromIntegral len)
where actionSize = 8
#if OPENFLOW_VERSION==151 || OPENFLOW_VERSION==152
flowStatsReplySize = 72
#endif
#if OPENFLOW_VERSION==1
flowStatsReplySize = 88
#endif
getAction :: Get Action
getAction = do
action_type <- getWord16be
action_len <- getWord16be
getActionForType (code2ActionType action_type) action_len
getActionForType :: ActionType -> Word16 -> Get Action
getActionForType OutputToPortType _ =
do port <- getWord16be
max_len <- getWord16be
return (SendOutPort (action port max_len))
where action !port !max_len
| port <= 0xff00 = PhysicalPort port
| port == ofppInPort = InPort
| port == ofppFlood = Flood
| port == ofppAll = AllPhysicalPorts
| port == ofppController = ToController max_len
| port == ofppTable = WithTable
{-# INLINE action #-}
getActionForType SetVlanVIDType _ =
do vlanid <- getWord16be
skip 2
return (SetVlanVID vlanid)
getActionForType SetVlanPriorityType _ =
do pcp <- getWord8
skip 3
return (SetVlanPriority pcp)
getActionForType StripVlanHeaderType _ =
do skip 4
return StripVlanHeader
getActionForType SetEthSrcAddrType _ =
do addr <- getEthernetAddress
skip 6
return (SetEthSrcAddr addr)
getActionForType SetEthDstAddrType _ =
do addr <- getEthernetAddress
skip 6
return (SetEthDstAddr addr)
getActionForType SetIPSrcAddrType _ =
do addr <- getIPAddress
return (SetIPSrcAddr addr)
getActionForType SetIPDstAddrType _ =
do addr <- getIPAddress
return (SetIPDstAddr addr)
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
getActionForType SetIPTypeOfServiceType _ =
do tos <- getWord8
skip 3
return (SetIPToS tos)
#endif
getActionForType SetTransportSrcPortType _ =
do port <- getWord16be
return (SetTransportSrcPort port)
getActionForType SetTransportDstPortType _ =
do port <- getWord16be
return (SetTransportDstPort port)
#if OPENFLOW_VERSION==1
getActionForType EnqueueType _ =
do port <- getWord16be
skip 6
qid <- getWord32be
return (Enqueue port qid)
getActionForType VendorActionType action_len =
do vendorid <- getWord32be
bytes <- getWord8s (fromIntegral action_len - 2 - 2 - 4)
return (VendorAction vendorid bytes)
#endif
getAggregateStatsReplies :: Int -> Get AggregateFlowStats
getAggregateStatsReplies bodyLen = do
pkt_cnt <- getWord64be
byte_cnt <- getWord64be
flow_cnt <- getWord32be
skip 4
return (AggregateFlowStats (fromIntegral pkt_cnt) (fromIntegral byte_cnt) (fromIntegral flow_cnt))
getPortStatsReplies :: Int -> Get [(PortID,PortStats)]
getPortStatsReplies bodyLen = sequence (replicate numPorts getPortStatsReply)
where numPorts = bodyLen `div` portStatsSize
portStatsSize = 104
getPortStatsReply :: Get (PortID, PortStats)
getPortStatsReply = do port_no <- getWord16be
skip 6
rx_packets <- getWord64be
tx_packets <- getWord64be
rx_bytes <- getWord64be
tx_bytes <- getWord64be
rx_dropped <- getWord64be
tx_dropped <- getWord64be
rx_errors <- getWord64be
tx_errors <- getWord64be
rx_frame_err <- getWord64be
rx_over_err <- getWord64be
rx_crc_err <- getWord64be
collisions <- getWord64be
return $ (port_no,
PortStats {
portStatsReceivedPackets = checkValid rx_packets,
portStatsSentPackets = checkValid tx_packets,
portStatsReceivedBytes = checkValid rx_bytes,
portStatsSentBytes = checkValid tx_bytes,
portStatsReceiverDropped = checkValid rx_dropped,
portStatsSenderDropped = checkValid tx_dropped,
portStatsReceiveErrors = checkValid rx_errors,
portStatsTransmitError = checkValid tx_errors,
portStatsReceivedFrameErrors = checkValid rx_frame_err,
portStatsReceiverOverrunError = checkValid rx_over_err,
portStatsReceiverCRCError = checkValid rx_crc_err,
portStatsCollisions = checkValid collisions }
)
where checkValid :: Word64 -> Maybe Double
checkValid x = if x == -1
then Nothing
else Just (fromIntegral x)
----------------------------------------------
-- Unparsers for CSMessages
----------------------------------------------
-- | Unparser for @CSMessage@s
putCSMessage :: (M.TransactionID, M.CSMessage) -> Put
putCSMessage (xid, msg) =
case msg of
M.FlowMod mod -> do let mod'@(FlowModRecordInternal {..}) = flowModToFlowModInternal mod
putH ofptFlowMod (flowModSizeInBytes' actions')
putFlowMod mod'
M.PacketOut packetOut -> {-# SCC "putCSMessage1" #-}
do putH ofptPacketOut (sendPacketSizeInBytes packetOut)
putSendPacket packetOut
M.CSHello -> putH ofptHello headerSize
M.CSEchoRequest bytes -> do putH ofptEchoRequest (headerSize + length bytes)
putWord8s bytes
M.CSEchoReply bytes -> do putH ofptEchoReply (headerSize + length bytes)
putWord8s bytes
M.FeaturesRequest -> putH ofptFeaturesRequest headerSize
M.PortMod portModRecord -> do putH ofptPortMod portModLength
putPortMod portModRecord
M.BarrierRequest -> do putH ofptBarrierRequest headerSize
M.StatsRequest request -> do putH ofptStatsRequest (statsRequestSize request)
putStatsRequest request
M.GetQueueConfig request -> do putH ofptQueueGetConfigRequest 12
putQueueConfigRequest request
M.ExtQueueModify p qCfgs -> do
putH ofptVendor (headerSize + 16 + sum (map lenQueueConfig qCfgs))
putWord32be 0x000026e1 -- OPENFLOW_VENDOR_ID
putWord32be 0 -- OFP_EXT_QUEUE_MODIFY
putWord16be p
putWord32be 0 >> putWord16be 0
mapM_ putQueueConfig qCfgs
M.ExtQueueDelete p qCfgs -> do
putH ofptVendor (headerSize + 16 + sum(map lenQueueConfig qCfgs))
putWord32be 0x000026e1 -- OPENFLOW_VENDOR_ID
putWord32be 1 -- OFP_EXT_QUEUE_DELETE
putWord16be p
putWord32be 0 >> putWord16be 0
mapM_ putQueueConfig qCfgs
M.Vendor bytes -> do
putH ofptVendor (headerSize + BS.length bytes)
putByteString bytes
where vid = ofpVersion
putH tcode len = putHeader (OFPHeader vid tcode (fromIntegral len) xid)
{-# INLINE putCSMessage #-}
putQueueConfigRequest :: QueueConfigRequest -> Put
putQueueConfigRequest (QueueConfigRequest portID) =
do putWord16be portID
putWord16be 0 --padding
------------------------------------------
-- Unparser for packet out message
------------------------------------------
sendPacketSizeInBytes :: PacketOut -> Int
sendPacketSizeInBytes (PacketOutRecord bufferIDData _ actions) =
headerSize + 4 + 2 + 2 + sum (map actionSizeInBytes actions) + fromIntegral (either (const 0) B.length bufferIDData)
{-# INLINE putSendPacket #-}
putSendPacket :: PacketOut -> Put
putSendPacket (PacketOutRecord {..}) = do
{-# SCC "putSendPacket1" #-} putWord32be $ either id (const (-1)) bufferIDData
{-# SCC "putSendPacket2" #-} putWord16be (maybe ofppNone id packetInPort)
{-# SCC "putSendPacket3" #-} putWord16be (fromIntegral actionArraySize)
{-# SCC "putSendPacket4" #-} mapM_ putAction packetActions
{-# SCC "putSendPacket5" #-} either (const $ return ()) putByteString bufferIDData
where actionArraySize = {-# SCC "putSendPacket6" #-} sum $ map actionSizeInBytes packetActions
getPacketOut :: Int -> Get PacketOut
getPacketOut len = do
bufID' <- getWord32be
port' <- getWord16be
actionArraySize' <- getWord16be
actions <- getActionsOfSize (fromIntegral actionArraySize')
x <- remaining
packetData <- if bufID' == -1
then let bytesOfData = len - headerSize - 4 - 2 - 2 - fromIntegral actionArraySize'
in getByteString (fromIntegral bytesOfData)
else return B.empty
return $ PacketOutRecord { bufferIDData = if bufID' == -1
then Right packetData
else Left bufID'
, packetInPort = if port' == ofppNone then Nothing else Just port'
, packetActions = actions
}
getActionsOfSize :: Int -> Get [Action]
getActionsOfSize n
| n > 0 = do a <- getAction
as <- getActionsOfSize (n - actionSizeInBytes a)
return (a : as)
| n == 0 = return []
| n < 0 = error "bad number of actions or bad action size"
{-# INLINE getActionsOfSize #-}
------------------------------------------
-- Unparser for flow mod message
------------------------------------------
#if OPENFLOW_VERSION==151
flowModSizeInBytes' :: [Action] -> Int
flowModSizeInBytes' actions =
headerSize + matchSize + 20 + sum (map actionSizeInBytes actions)
#endif
#if OPENFLOW_VERSION==152
flowModSizeInBytes' :: [Action] -> Int
flowModSizeInBytes' actions =
headerSize + matchSize + 20 + sum (map actionSizeInBytes actions)
#endif
#if OPENFLOW_VERSION==1
flowModSizeInBytes' :: [Action] -> Int
flowModSizeInBytes' actions =
headerSize + matchSize + 24 + sum (map actionSizeInBytes actions)
#endif
data FlowModRecordInternal = FlowModRecordInternal {
command' :: FlowModType
, match' :: Match
, actions' :: [Action]
, priority' :: Priority
, idleTimeOut' :: Maybe TimeOut
, hardTimeOut' :: Maybe TimeOut
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
, flags' :: [FlowModFlag]
#endif
, bufferID' :: Maybe BufferID
, outPort' :: Maybe PseudoPort
#if OPENFLOW_VERSION==1
, cookie' :: Cookie
#endif
} deriving (Eq,Show)
-- | Specification: @ofp_flow_mod_command@.
data FlowModType
= FlowAddType
| FlowModifyType
| FlowModifyStrictType
| FlowDeleteType
| FlowDeleteStrictType
deriving (Show,Eq,Ord)
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
-- | A set of flow mod attributes can be added to a flow modification command.
data FlowModFlag = SendFlowRemoved | CheckOverlap | Emergency deriving (Show,Eq,Ord,Enum)
#endif
flowModToFlowModInternal :: FlowMod -> FlowModRecordInternal
flowModToFlowModInternal (DeleteFlows {..}) =
FlowModRecordInternal {match' = match,
#if OPENFLOW_VERSION==1
cookie' = 0,
#endif
command' = FlowDeleteType,
idleTimeOut' = Nothing,
hardTimeOut' = Nothing,
priority' = 0,
bufferID' = Nothing,
outPort' = outPort,
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
flags' = [],
#endif
actions' = []
}
flowModToFlowModInternal (DeleteExactFlow {..}) =
FlowModRecordInternal {match' = match,
#if OPENFLOW_VERSION==1
cookie' = 0,
#endif
command' = FlowDeleteStrictType,
idleTimeOut' = Nothing,
hardTimeOut' = Nothing,
priority' = priority,
bufferID' = Nothing,
outPort' = outPort,
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
flags' = [],
#endif
actions' = []
}
flowModToFlowModInternal (AddFlow {..}) =
FlowModRecordInternal { match' = match,
#if OPENFLOW_VERSION==1
cookie' = cookie,
#endif
command' = FlowAddType,
idleTimeOut' = Just idleTimeOut,
hardTimeOut' = Just hardTimeOut,
priority' = priority,
bufferID' = applyToPacket,
outPort' = Nothing,
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
flags' = concat [ if not overlapAllowed then [CheckOverlap] else [],
if notifyWhenRemoved then [SendFlowRemoved] else []] ,
#endif
actions' = actions
}
flowModToFlowModInternal (AddEmergencyFlow {..}) =
FlowModRecordInternal { match' = match,
#if OPENFLOW_VERSION==1
cookie' = cookie,
#endif
command' = FlowAddType,
idleTimeOut' = Nothing,
hardTimeOut' = Nothing,
priority' = priority,
bufferID' = Nothing,
outPort' = Nothing,
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
flags' = Emergency : if not overlapAllowed then [CheckOverlap] else [],
#endif
actions' = actions
}
flowModToFlowModInternal (ModifyFlows {..}) =
FlowModRecordInternal {match' = match,
#if OPENFLOW_VERSION==1
cookie' = ifMissingCookie,
#endif
command' = FlowModifyType,
idleTimeOut' = Just ifMissingIdleTimeOut,
hardTimeOut' = Just ifMissingHardTimeOut,
priority' = ifMissingPriority,
bufferID' = Nothing,
outPort' = Nothing,
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
flags' = concat [ if not ifMissingOverlapAllowed then [CheckOverlap] else [],
if ifMissingNotifyWhenRemoved then [SendFlowRemoved] else []] ,
#endif
actions' = newActions
}
flowModToFlowModInternal (ModifyExactFlow {..}) =
FlowModRecordInternal {match' = match,
#if OPENFLOW_VERSION==1
cookie' = ifMissingCookie,
#endif
command' = FlowModifyStrictType,
idleTimeOut' = Just ifMissingIdleTimeOut,
hardTimeOut' = Just ifMissingHardTimeOut,
priority' = priority,
bufferID' = Nothing,
outPort' = Nothing,
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
flags' = concat [ if not ifMissingOverlapAllowed then [CheckOverlap] else [],
if ifMissingNotifyWhenRemoved then [SendFlowRemoved] else []] ,
#endif
actions' = newActions
}
#if OPENFLOW_VERSION==151
putFlowMod :: FlowModRecordInternal -> Put
putFlowMod (FlowModRecordInternal {..}) = do
putMatch match'
putWord16be $ flowModTypeBimap ! command'
putWord16be $ maybeTimeOutToCode idleTimeOut'
putWord16be $ maybeTimeOutToCode hardTimeOut'
putWord16be priority'
putWord32be $ maybe (-1) id bufferID'
putWord16be $ maybe ofppNone fakePort2Code outPort'
putWord16be 0
putWord32be 0
sequence_ [putAction a | a <- actions']
#endif
#if OPENFLOW_VERSION==152
putFlowMod :: FlowModRecordInternal -> Put
putFlowMod (FlowModRecordInternal {..}) = do
putMatch match'
putWord16be $ flowModTypeBimap ! command'
putWord16be $ maybeTimeOutToCode idleTimeOut'
putWord16be $ maybeTimeOutToCode hardTimeOut'
putWord16be priority'
putWord32be $ maybe (-1) id bufferID'
putWord16be $ maybe ofppNone fakePort2Code outPort'
putWord16be $ flagSet2BitMap flags'
putWord32be 0
sequence_ [putAction a | a <- actions']
#endif
#if OPENFLOW_VERSION==1
putFlowMod :: FlowModRecordInternal -> Put
putFlowMod (FlowModRecordInternal {..}) = do
putMatch match'
putWord64be cookie'
putWord16be $ flowModTypeBimap ! command'
putWord16be $ maybeTimeOutToCode idleTimeOut'
putWord16be $ maybeTimeOutToCode hardTimeOut'
putWord16be priority'
putWord32be $ maybe (-1) id bufferID'
putWord16be $ maybe ofppNone fakePort2Code outPort'
putWord16be $ flagSet2BitMap flags'
sequence_ [putAction a | a <- actions']
getBufferID :: Get (Maybe BufferID)
getBufferID = do w <- getWord32be
if w == -1
then return Nothing
else return (Just w)
getOutPort :: Get (Maybe PseudoPort)
getOutPort = do w <- getWord16be
if w == ofppNone
then return Nothing
else return (Just (code2FakePort w))
getFlowModInternal :: Int -> Get FlowModRecordInternal
getFlowModInternal len =
do match <- getMatch
cookie <- getWord64be
modType <- getFlowModType
idleTimeOut <- getTimeOutFromCode
hardTimeOut <- getTimeOutFromCode
priority <- getWord16be
mBufferID <- getBufferID
outPort <- getOutPort
flags <- getFlowModFlags
let bytesInActionList = len - 72
actions <- getActionsOfSize (fromIntegral bytesInActionList)
return $ FlowModRecordInternal { command' = modType
, match' = match
, actions' = actions
, priority' = priority
, idleTimeOut' = idleTimeOut
, hardTimeOut' = hardTimeOut
, flags' = flags
, bufferID' = mBufferID
, outPort' = outPort
, cookie' = cookie
}
getFlowMod :: Int -> Get FlowMod
getFlowMod len = getFlowModInternal len >>= return . flowModInternal2FlowMod
flowModInternal2FlowMod :: FlowModRecordInternal -> FlowMod
flowModInternal2FlowMod (FlowModRecordInternal {..}) =
case command' of
FlowDeleteType -> DeleteFlows { match = match', outPort = outPort' }
FlowDeleteStrictType -> DeleteExactFlow { match = match', outPort = outPort', priority = priority' }
FlowAddType ->
if elem Emergency flags'
then AddEmergencyFlow { match = match'
, priority = priority'
, actions = actions'
, cookie = cookie'
, overlapAllowed = elem CheckOverlap flags'
}
else AddFlow { match = match'
, priority = priority'
, actions = actions'
, cookie = cookie'
, idleTimeOut = fromJust idleTimeOut'
, hardTimeOut = fromJust hardTimeOut'
, notifyWhenRemoved = elem SendFlowRemoved flags'
, applyToPacket = bufferID'
, overlapAllowed = elem CheckOverlap flags'
}
FlowModifyType -> ModifyFlows { match = match'
, newActions = actions'
, ifMissingPriority = priority'
, ifMissingCookie = cookie'
, ifMissingIdleTimeOut = fromJust idleTimeOut'
, ifMissingHardTimeOut = fromJust hardTimeOut'
, ifMissingOverlapAllowed = CheckOverlap `elem` flags'
, ifMissingNotifyWhenRemoved = SendFlowRemoved `elem` flags'
}
FlowModifyStrictType -> ModifyExactFlow { match = match'
, newActions = actions'
, priority = priority'
, ifMissingCookie = cookie'
, ifMissingIdleTimeOut = fromJust idleTimeOut'
, ifMissingHardTimeOut = fromJust hardTimeOut'
, ifMissingOverlapAllowed = CheckOverlap `elem` flags'
, ifMissingNotifyWhenRemoved = SendFlowRemoved `elem` flags'
}
#endif
maybeTimeOutToCode :: Maybe TimeOut -> Word16
maybeTimeOutToCode Nothing = 0
maybeTimeOutToCode (Just to) =
case to of
Permanent -> 0
ExpireAfter t -> t
{-# INLINE maybeTimeOutToCode #-}
getTimeOutFromCode :: Get (Maybe TimeOut)
getTimeOutFromCode = do code <- getWord16be
if code == 0
then return Nothing
else return (Just (ExpireAfter code))
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
flagSet2BitMap :: [FlowModFlag] -> Word16
flagSet2BitMap flagSet = foldl (.|.) 0 bitMasks
where bitMasks = map (\f -> fromJust $ lookup f flowModFlagToBitMaskBijection) flagSet
flowModFlagToBitMaskBijection :: [(FlowModFlag,Word16)]
flowModFlagToBitMaskBijection = [(SendFlowRemoved, shiftL 1 0),
(CheckOverlap, shiftL 1 1),
(Emergency, shiftL 1 2) ]
bitMap2FlagSet :: Word16 -> [FlowModFlag]
bitMap2FlagSet w = [ flag | (flag,mask) <- flowModFlagToBitMaskBijection, mask .&. w /= 0 ]
getFlowModFlags :: Get [FlowModFlag]
getFlowModFlags = do w <- getWord16be
return (bitMap2FlagSet w)
#endif
ofpfcAdd, ofpfcModify, ofpfcModifyStrict, ofpfcDelete, ofpfcDeleteStrict :: Word16
ofpfcAdd = 0
ofpfcModify = 1
ofpfcModifyStrict = 2
ofpfcDelete = 3
ofpfcDeleteStrict = 4
flowModTypeBimap :: Bimap FlowModType Word16
flowModTypeBimap =
Bimap.fromList [
(FlowAddType, ofpfcAdd),
(FlowModifyType, ofpfcModify),
(FlowModifyStrictType, ofpfcModifyStrict),
(FlowDeleteType, ofpfcDelete),
(FlowDeleteStrictType, ofpfcDeleteStrict)
]
getFlowModType :: Get FlowModType
getFlowModType = do code <- getWord16be
return (flowModTypeBimap !> code)
putAction :: Action -> Put
putAction act =
case act of
(SendOutPort port) ->
do -- putWord16be 0
-- putWord16be 8
putWord32be 8
putPseudoPort port
(SetVlanVID vlanid) ->
do putWord16be 1
putWord16be 8
putWord16be vlanid
putWord16be 0
(SetVlanPriority priority) ->
do putWord16be 2
putWord16be 8
putWord8 priority
putWord8 0
putWord8 0
putWord8 0
(StripVlanHeader) ->
do putWord16be 3
putWord16be 8
putWord32be 0
(SetEthSrcAddr addr) ->
do putWord16be 4
putWord16be 16
putEthernetAddress addr
sequence_ (replicate 6 (putWord8 0))
(SetEthDstAddr addr) ->
do putWord16be 5
putWord16be 16
putEthernetAddress addr
sequence_ (replicate 6 (putWord8 0))
(SetIPSrcAddr addr) ->
do putWord16be 6
putWord16be 8
putWord32be (ipAddressToWord32 addr)
(SetIPDstAddr addr) ->
do putWord16be 7
putWord16be 8
putWord32be (ipAddressToWord32 addr)
(SetIPToS tos) ->
do putWord16be 8
putWord16be 8
putWord8 tos
sequence_ (replicate 3 (putWord8 0))
(SetTransportSrcPort port) ->
do putWord16be 9
putWord16be 8
putWord16be port
putWord16be 0
(SetTransportDstPort port) ->
do putWord16be 10
putWord16be 8
putWord16be port
putWord16be 0
(Enqueue port qid) ->
do putWord16be 11
putWord16be 16
putWord16be port
sequence_ (replicate 6 (putWord8 0))
putWord32be qid
(VendorAction vendorID bytes) ->
do let l = 2 + 2 + 4 + length bytes
when (l `mod` 8 /= 0) (error "Vendor action must have enough data to make the action length a multiple of 8 bytes")
putWord16be 0xffff
putWord16be (fromIntegral l)
putWord32be vendorID
mapM_ putWord8 bytes
putPseudoPort :: PseudoPort -> Put
putPseudoPort (ToController maxLen) =
do putWord16be ofppController
putWord16be maxLen
putPseudoPort port =
do putWord16be (fakePort2Code port)
putWord16be 0
{-# INLINE putPseudoPort #-}
actionSizeInBytes :: Action -> Int
actionSizeInBytes (SendOutPort _) = 8
actionSizeInBytes (SetVlanVID _) = 8
actionSizeInBytes (SetVlanPriority _) = 8
actionSizeInBytes StripVlanHeader = 8
actionSizeInBytes (SetEthSrcAddr _) = 16
actionSizeInBytes (SetEthDstAddr _) = 16
actionSizeInBytes (SetIPSrcAddr _) = 8
actionSizeInBytes (SetIPDstAddr _) = 8
actionSizeInBytes (SetIPToS _) = 8
actionSizeInBytes (SetTransportSrcPort _) = 8
actionSizeInBytes (SetTransportDstPort _) = 8
actionSizeInBytes (Enqueue _ _) = 16
actionSizeInBytes (VendorAction _ bytes) = let l = 2 + 2 + 4 + length bytes
in if l `mod` 8 /= 0
then error "Vendor action must have enough data to make the action length a multiple of 8 bytes"
else l
{-# INLINE actionSizeInBytes #-}
typeOfAction :: Action -> ActionType
typeOfAction !a =
case a of
SendOutPort _ -> OutputToPortType
SetVlanVID _ -> SetVlanVIDType
SetVlanPriority _ -> SetVlanPriorityType
StripVlanHeader -> StripVlanHeaderType
SetEthSrcAddr _ -> SetEthSrcAddrType
SetEthDstAddr _ -> SetEthDstAddrType
SetIPSrcAddr _ -> SetIPSrcAddrType
SetIPDstAddr _ -> SetIPDstAddrType
SetIPToS _ -> SetIPTypeOfServiceType
SetTransportSrcPort _ -> SetTransportSrcPortType
SetTransportDstPort _ -> SetTransportDstPortType
Enqueue _ _ -> EnqueueType
VendorAction _ _ -> VendorActionType
{-# INLINE typeOfAction #-}
------------------------------------------
-- Port mod unparser
------------------------------------------
portModLength :: Word16
portModLength = 32
putPortMod :: PortMod -> Put
putPortMod (PortModRecord {..} ) =
do putWord16be portNumber
putEthernetAddress hwAddr
putConfigBitMap
putMaskBitMap
putAdvertiseBitMap
putPad
where putConfigBitMap = putWord32be (portAttributeSet2BitMask onAttrs)
putMaskBitMap = putWord32be (portAttributeSet2BitMask offAttrs)
putAdvertiseBitMap = putWord32be 0
putPad = putWord32be 0
attrsChanging = List.union onAttrs offAttrs
onAttrs = Map.keys $ Map.filter (==True) attributesToSet
offAttrs = Map.keys $ Map.filter (==False) attributesToSet
----------------------------------------
-- Stats requests unparser
----------------------------------------
statsRequestSize :: StatsRequest -> Int
statsRequestSize (FlowStatsRequest _ _ _) = headerSize + 2 + 2 + matchSize + 1 + 1 + 2
#if OPENFLOW_VERSION==151 || OPENFLOW_VERSION==152
statsRequestSize (PortStatsRequest) = headerSize + 2 + 2
#endif
#if OPENFLOW_VERSION==1
statsRequestSize (PortStatsRequest _) = headerSize + 2 + 2 + 2 + 6
#endif
statsRequestSize (DescriptionRequest) = headerSize + 2 + 2
putStatsRequest :: StatsRequest -> Put
putStatsRequest (FlowStatsRequest match tableQuery mPort) =
do putWord16be ofpstFlow
putWord16be 0
putMatch match
putWord8 (tableQueryToCode tableQuery)
putWord8 0 --pad
putWord16be $ maybe ofppNone fakePort2Code mPort
putStatsRequest (AggregateFlowStatsRequest match tableQuery mPort) =
do putWord16be ofpstAggregate
putWord16be 0
putMatch match
putWord8 (tableQueryToCode tableQuery)
putWord8 0 --pad
putWord16be $ maybe ofppNone fakePort2Code mPort
putStatsRequest TableStatsRequest =
do putWord16be ofpstTable
putWord16be 0
putStatsRequest DescriptionRequest =
do putWord16be ofpstDesc
putWord16be 0
#if OPENFLOW_VERSION==151 || OPENFLOW_VERSION==152
putStatsRequest PortStatsRequest =
do putWord16be ofpstPort
putWord16be 0
#endif
#if OPENFLOW_VERSION==1
putStatsRequest (QueueStatsRequest portQuery queueQuery) =
do putWord16be ofpstQueue
putWord16be 0
putWord16be (queryToPortNumber portQuery)
putWord16be 0 --padding
putWord32be (queryToQueueID queueQuery)
putStatsRequest (PortStatsRequest query) =
do putWord16be ofpstPort
putWord16be 0
putWord16be (queryToPortNumber query)
sequence_ (replicate 6 (putWord8 0))
queryToPortNumber :: PortQuery -> Word16
queryToPortNumber AllPorts = ofppNone
queryToPortNumber (SinglePort p) = p
queryToQueueID :: QueueQuery -> QueueID
queryToQueueID AllQueues = 0xffffffff
queryToQueueID (SingleQueue q) = q
#endif
ofppInPort, ofppTable, ofppNormal, ofppFlood, ofppAll, ofppController, ofppLocal, ofppNone :: Word16
ofppInPort = 0xfff8
ofppTable = 0xfff9
ofppNormal = 0xfffa
ofppFlood = 0xfffb
ofppAll = 0xfffc
ofppController = 0xfffd
ofppLocal = 0xfffe
ofppNone = 0xffff
fakePort2Code :: PseudoPort -> Word16
fakePort2Code (PhysicalPort portID) = portID
fakePort2Code InPort = ofppInPort
fakePort2Code Flood = ofppFlood
fakePort2Code AllPhysicalPorts = ofppAll
fakePort2Code (ToController _) = ofppController
fakePort2Code NormalSwitching = ofppNormal
fakePort2Code WithTable = ofppTable
{-# INLINE fakePort2Code #-}
code2FakePort :: Word16 -> PseudoPort
code2FakePort w
| w <= 0xff00 = PhysicalPort w
| w == ofppInPort = InPort
| w == ofppFlood = Flood
| w == ofppAll = AllPhysicalPorts
| w == ofppController = ToController 0
| w == ofppNormal = NormalSwitching
| w == ofppTable = WithTable
| otherwise = error ("unknown pseudo port number: " ++ show w)
tableQueryToCode :: TableQuery -> Word8
tableQueryToCode AllTables = 0xff
#if OPENFLOW_VERSION==1
tableQueryToCode EmergencyTable = 0xfe
#endif
tableQueryToCode (Table t) = t
#if OPENFLOW_VERSION==151 || OPENFLOW_VERSION==152
ofpstDesc, ofpstFlow, ofpstAggregate, ofpstTable, ofpstPort, ofpstVendor :: Word16
ofpstDesc = 0
ofpstFlow = 1
ofpstAggregate = 2
ofpstTable = 3
ofpstPort = 4
ofpstVendor = 0xffff
#endif
#if OPENFLOW_VERSION==1
ofpstDesc, ofpstFlow, ofpstAggregate, ofpstTable, ofpstPort, ofpstQueue, ofpstVendor :: Word16
ofpstDesc = 0
ofpstFlow = 1
ofpstAggregate = 2
ofpstTable = 3
ofpstPort = 4
ofpstQueue = 5
ofpstVendor = 0xffff
#endif
---------------------------------------------
-- Parser and Unparser for Match
---------------------------------------------
matchSize :: Int
matchSize = 40
getMatch :: Get Match
getMatch = do
wcards <- getWord32be
inport <- getWord16be
srcEthAddr <- getEthernetAddress
dstEthAddr <- getEthernetAddress
dl_vlan <- getWord16be
dl_vlan_pcp <- getWord8
skip 1
dl_type <- getWord16be
nw_tos <- getWord8
nw_proto <- getWord8
skip 2
nw_src <- getWord32be
nw_dst <- getWord32be
tp_src <- getWord16be
tp_dst <- getWord16be
return $ ofpMatch2Match $ OFPMatch wcards inport srcEthAddr dstEthAddr dl_vlan dl_vlan_pcp dl_type nw_tos nw_proto nw_src nw_dst tp_src tp_dst
putMatch :: Match -> Put
putMatch m = do
putWord32be $ ofpm_wildcards m'
putWord16be $ ofpm_in_port m'
putEthernetAddress $ ofpm_dl_src m'
putEthernetAddress $ ofpm_dl_dst m'
putWord16be $ ofpm_dl_vlan m'
putWord8 $ ofpm_dl_vlan_pcp m'
putWord8 0 -- padding
putWord16be $ ofpm_dl_type m'
putWord8 $ ofpm_nw_tos m'
putWord8 $ ofpm_nw_proto m'
putWord16be 0 -- padding
putWord32be $ ofpm_nw_src m'
putWord32be $ ofpm_nw_dst m'
putWord16be $ ofpm_tp_src m'
putWord16be $ ofpm_tp_dst m'
where m' = match2OFPMatch m
data OFPMatch = OFPMatch { ofpm_wildcards :: !Word32,
ofpm_in_port :: !Word16,
ofpm_dl_src, ofpm_dl_dst :: !EthernetAddress,
ofpm_dl_vlan :: !Word16,
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
ofpm_dl_vlan_pcp :: !Word8,
#endif
ofpm_dl_type :: !Word16,
#if OPENFLOW_VERSION==1
ofpm_nw_tos :: !Word8,
#endif
ofpm_nw_proto :: !Word8,
ofpm_nw_src, ofpm_nw_dst :: !Word32,
ofpm_tp_src, ofpm_tp_dst :: !Word16 } deriving (Show,Eq)
ofpMatch2Match :: OFPMatch -> Match
ofpMatch2Match ofpm = Match
(getField 0 ofpm_in_port)
(getField 2 ofpm_dl_src)
(getField 3 ofpm_dl_dst)
(getField 1 ofpm_dl_vlan)
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
(getField 20 ofpm_dl_vlan_pcp)
#endif
(getField 4 ofpm_dl_type)
#if OPENFLOW_VERSION==1
(getField 21 ofpm_nw_tos)
#endif
(getField 5 ofpm_nw_proto)
(IPAddress (ofpm_nw_src ofpm) // src_prefix_len)
(IPAddress (ofpm_nw_dst ofpm) // dst_prefix_len)
(getField 6 ofpm_tp_src)
(getField 7 ofpm_tp_dst)
where getField wcindex getter = if testBit (ofpm_wildcards ofpm) wcindex
then Nothing
else Just (getter ofpm)
nw_src_shift = 8
nw_dst_shift = 14
nw_src_mask = shiftL ((shiftL 1 6) - 1) nw_src_shift
nw_dst_mask = shiftL ((shiftL 1 6) - 1) nw_dst_shift
nw_src_num_ignored = fromIntegral (shiftR (ofpm_wildcards ofpm .&. nw_src_mask) nw_src_shift)
nw_dst_num_ignored = fromIntegral (shiftR (ofpm_wildcards ofpm .&. nw_dst_mask) nw_dst_shift)
src_prefix_len = 32 - min 32 nw_src_num_ignored
dst_prefix_len = 32 - min 32 nw_dst_num_ignored
match2OFPMatch :: Match -> OFPMatch
match2OFPMatch (Match {..})
= OFPMatch { ofpm_wildcards = wildcard',
ofpm_in_port = maybe 0 id inPort,
ofpm_dl_src = maybe nullEthAddr id srcEthAddress,
ofpm_dl_dst = maybe nullEthAddr id dstEthAddress,
ofpm_dl_vlan = maybe 0 id vLANID,
ofpm_dl_vlan_pcp = maybe 0 id vLANPriority,
ofpm_dl_type = maybe 0 id ethFrameType,
ofpm_nw_tos = maybe 0 id ipTypeOfService,
ofpm_nw_proto = maybe 0 id matchIPProtocol,
ofpm_nw_src = fromIntegral $ ipAddressToWord32 $ addressPart srcIPAddress,
ofpm_nw_dst = fromIntegral $ ipAddressToWord32 $ addressPart dstIPAddress,
ofpm_tp_src = maybe 0 id srcTransportPort,
ofpm_tp_dst = maybe 0 id dstTransportPort }
where
wildcard' :: Word32
wildcard' = shiftL (fromIntegral numIgnoredBitsSrc) 8 .|.
shiftL (fromIntegral numIgnoredBitsDst) 14 .|.
(maybe (flip setBit 0) (const id) inPort $
maybe (flip setBit 1) (const id) vLANID $
maybe (flip setBit 2) (const id) srcEthAddress $
maybe (flip setBit 3) (const id) dstEthAddress $
maybe (flip setBit 4) (const id) ethFrameType $
maybe (flip setBit 5) (const id) matchIPProtocol $
maybe (flip setBit 6) (const id) srcTransportPort $
maybe (flip setBit 7) (const id) dstTransportPort $
maybe (flip setBit 20) (const id) vLANPriority $
maybe (flip setBit 21) (const id) ipTypeOfService $
0
)
numIgnoredBitsSrc = 32 - (prefixLength srcIPAddress)
numIgnoredBitsDst = 32 - (prefixLength dstIPAddress)
nullEthAddr = ethernetAddress 0 0 0 0 0 0
lenQueueProp (MinRateQueue _) = 16
lenQueueProp (MaxRateQueue _) = 16
putQueueProp (MinRateQueue (Enabled rate)) = putQueueProp' ofpqtMinRate rate
putQueueProp (MaxRateQueue (Enabled rate)) = putQueueProp' ofpqtMaxRate rate
-- struct ofp_queue_prop_min_rate
putQueueProp' propType rate = do
putWord16be propType
putWord16be 16 -- length
putWord32be 0 -- padding
putWord16be rate
putWord32be 0 -- padding
putWord16be 0 --padding
lenQueueConfig (QueueConfig _ props) = 8 + sum (map lenQueueProp props)
-- struct ofp_packet_queue
putQueueConfig (QueueConfig qid props) = do
putWord32be qid
putWord16be (8 + sum (map lenQueueProp props))
putWord16be 0 -- padding
mapM_ putQueueProp props
-----------------------------------
-- Utilities
-----------------------------------
getWord8s :: Int -> Get [Word8]
getWord8s n = sequence $ replicate n getWord8
putWord8s :: [Word8] -> Put
putWord8s bytes = sequence_ [putWord8 b | b <- bytes]
|
brownsys/nettle-openflow
|
src/Nettle/OpenFlow/MessagesBinary.hs
|
Haskell
|
bsd-3-clause
| 76,633
|
module Main where
import Data.List (intersperse)
import Data.List.Split (splitOn)
import System.Environment (getArgs)
import Control.Distributed.Task.Distribution.LogConfiguration (initDefaultLogging)
import Control.Distributed.Task.Distribution.RunComputation
import Control.Distributed.Task.Distribution.TaskDistribution (startSlaveNode, showSlaveNodes, showSlaveNodesWithData, shutdownSlaveNodes)
import Control.Distributed.Task.TaskSpawning.RemoteExecutionSupport
import Control.Distributed.Task.Types.HdfsConfigTypes
import Control.Distributed.Task.Types.TaskTypes
import FullBinaryExamples
import RemoteExecutable
import DemoTask
main :: IO ()
main = withRemoteExecutionSupport calculateRatio $ do
initDefaultLogging ""
args <- getArgs
case args of
("master" : masterArgs) -> runMaster (parseMasterOpts masterArgs)
["slave", slaveHost, slavePort] -> startSlaveNode (slaveHost, (read slavePort))
["showslaves"] -> showSlaveNodes localConfig
["slaveswithhdfsdata", host, port, hdfsFilePath] -> showSlaveNodesWithData (host, read port) hdfsFilePath
["shutdown"] -> shutdownSlaveNodes localConfig
_ -> userSyntaxError "unknown mode"
-- note: assumes no nodes with that configuration, should be read as parameters
localConfig :: HdfsConfig
localConfig = ("localhost", 44440)
userSyntaxError :: String -> undefined
userSyntaxError reason = error $ usageInfo ++ reason ++ "\n"
usageInfo :: String
usageInfo = "Syntax: master"
++ " <host>"
++ " <port>"
++ " <module:<module path>|fullbinary|serializethunkdemo:<demo function>:<demo arg>|objectcodedemo>"
++ " <simpledata:numDBs|hdfs:<file path>[:<subdir depth>[:<filename filter prefix>]]"
++ " <collectonmaster|discard|storeinhdfs:<outputprefix>[:<outputsuffix>]>\n"
++ "| slave <slave host> <slave port>\n"
++ "| showslaves\n"
++ "| slaveswithhdfsdata <thrift host> <thrift port> <hdfs file path>\n"
++ "| shutdown\n"
++ "\n"
++ "demo functions (with demo arg description): append:<suffix> | filter:<infixfilter> | visitcalc:unused \n"
parseMasterOpts :: [String] -> MasterOptions
parseMasterOpts args =
case args of
[masterHost, port, taskSpec, dataSpec, resultSpec] -> MasterOptions masterHost (read port) (parseTaskSpec taskSpec) (parseDataSpec dataSpec) (parseResultSpec resultSpec)
_ -> userSyntaxError "wrong number of master options"
where
parseTaskSpec :: String -> TaskSpec
parseTaskSpec taskArgs =
case splitOn ":" taskArgs of
["module", modulePath] -> SourceCodeSpec modulePath
["fullbinary"] -> FullBinaryDeployment
["serializethunkdemo", demoFunction, demoArg] -> mkSerializeThunkDemoArgs demoFunction demoArg
["objectcodedemo"] -> ObjectCodeModuleDeployment remoteExecutable
_ -> userSyntaxError $ "unknown task specification: " ++ taskArgs
where
mkSerializeThunkDemoArgs :: String -> String -> TaskSpec
mkSerializeThunkDemoArgs "append" demoArg = SerializedThunk (appendDemo demoArg)
mkSerializeThunkDemoArgs "filter" demoArg = SerializedThunk (filterDemo demoArg)
mkSerializeThunkDemoArgs "visitcalc" _ = SerializedThunk calculateRatio
mkSerializeThunkDemoArgs d a = userSyntaxError $ "unknown demo: " ++ d ++ ":" ++ a
parseDataSpec :: String -> DataSpec
parseDataSpec inputArgs =
case splitOn ":" inputArgs of
["simpledata", numDBs] -> SimpleDataSpec $ read numDBs
("hdfs": hdfsPath: rest) -> HdfsDataSpec hdfsPath depth filter'
where depth = if length rest > 0 then read (rest !! 0) else 0; filter' = if length rest > 1 then Just (rest !! 1) else Nothing
_ -> userSyntaxError $ "unknown data specification: " ++ inputArgs
parseResultSpec resultArgs =
case splitOn ":" resultArgs of
["collectonmaster"] -> CollectOnMaster resultProcessor
("storeinhdfs":outputPrefix:rest) -> StoreInHdfs outputPrefix $ if null rest then "" else head rest
["discard"] -> Discard
_ -> userSyntaxError $ "unknown result specification: " ++ resultArgs
resultProcessor :: [TaskResult] -> IO ()
resultProcessor res = do
putStrLn $ joinStrings "\n" $ map show $ concat res
putStrLn $ "got " ++ (show $ length $ concat res) ++ " results in total"
joinStrings :: String -> [String] -> String
joinStrings separator = concat . intersperse separator
|
michaxm/task-distribution
|
app/Main.hs
|
Haskell
|
bsd-3-clause
| 4,444
|
module Mistral.TypeCheck.Interface (
genIface
) where
import Mistral.ModuleSystem.Interface
import Mistral.TypeCheck.AST
import Mistral.Utils.SCC ( groupElems )
import Data.Foldable ( foldMap )
import qualified Data.Map as Map
-- | Generate an interface from a core module.
genIface :: Module -> Iface
genIface m = Iface { ifaceModName = modName m
, ifaceDeps = modDeps m
, ifaceDatas = modDatas m
, ifaceBinds = modTypes m
, ifaceTySyns = Map.empty
, ifaceTypes = Map.empty
, ifaceInsts = modInsts m }
-- | Generate the binding map for a core module.
modTypes :: Module -> Map.Map Name IfaceBind
modTypes m = foldMap Map.fromList [ concatMap (map modBindType . groupElems) (modBinds m) ]
modBindType :: Bind a -> (Name, IfaceBind)
modBindType b = (bName b, IfaceBind (bType b))
|
GaloisInc/mistral
|
src/Mistral/TypeCheck/Interface.hs
|
Haskell
|
bsd-3-clause
| 927
|
module ETA.TypeCheck.TcFlatten(
FlattenEnv(..), FlattenMode(..), mkFlattenEnv,
flatten, flattenMany, flatten_many,
flattenFamApp, flattenTyVarOuter,
unflatten,
eqCanRewrite, eqCanRewriteFR, canRewriteOrSame,
CtFlavourRole, ctEvFlavourRole, ctFlavourRole
) where
import ETA.TypeCheck.TcRnTypes
import ETA.TypeCheck.TcType
import ETA.Types.Type
import ETA.TypeCheck.TcEvidence
import ETA.Types.TyCon
import ETA.Types.TypeRep
import ETA.Types.Kind( isSubKind )
import ETA.Types.Coercion ( tyConRolesX )
import ETA.BasicTypes.Var
import ETA.BasicTypes.VarEnv
import ETA.BasicTypes.NameEnv
import ETA.Utils.Outputable
import ETA.BasicTypes.VarSet
import ETA.TypeCheck.TcSMonad as TcS
import ETA.Main.DynFlags( DynFlags )
import ETA.Utils.Util
import ETA.Utils.Bag
import ETA.Utils.FastString
import Control.Monad( when, liftM )
import ETA.Utils.MonadUtils ( zipWithAndUnzipM )
import GHC.Exts ( inline )
{-
Note [The flattening story]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* A CFunEqCan is either of form
[G] <F xis> : F xis ~ fsk -- fsk is a FlatSkol
[W] x : F xis ~ fmv -- fmv is a unification variable,
-- but untouchable,
-- with MetaInfo = FlatMetaTv
where
x is the witness variable
fsk/fmv is a flatten skolem
xis are function-free
CFunEqCans are always [Wanted], or [Given], never [Derived]
fmv untouchable just means that in a CTyVarEq, say,
fmv ~ Int
we do NOT unify fmv.
* KEY INSIGHTS:
- A given flatten-skolem, fsk, is known a-priori to be equal to
F xis (the LHS), with <F xis> evidence
- A unification flatten-skolem, fmv, stands for the as-yet-unknown
type to which (F xis) will eventually reduce
* Inert set invariant: if F xis1 ~ fsk1, F xis2 ~ fsk2
then xis1 /= xis2
i.e. at most one CFunEqCan with a particular LHS
* Each canonical CFunEqCan x : F xis ~ fsk/fmv has its own
distinct evidence variable x and flatten-skolem fsk/fmv.
Why? We make a fresh fsk/fmv when the constraint is born;
and we never rewrite the RHS of a CFunEqCan.
* Function applications can occur in the RHS of a CTyEqCan. No reason
not allow this, and it reduces the amount of flattening that must occur.
* Flattening a type (F xis):
- If we are flattening in a Wanted/Derived constraint
then create new [W] x : F xis ~ fmv
else create new [G] x : F xis ~ fsk
with fresh evidence variable x and flatten-skolem fsk/fmv
- Add it to the work list
- Replace (F xis) with fsk/fmv in the type you are flattening
- You can also add the CFunEqCan to the "flat cache", which
simply keeps track of all the function applications you
have flattened.
- If (F xis) is in the cache already, just
use its fsk/fmv and evidence x, and emit nothing.
- No need to substitute in the flat-cache. It's not the end
of the world if we start with, say (F alpha ~ fmv1) and
(F Int ~ fmv2) and then find alpha := Int. Athat will
simply give rise to fmv1 := fmv2 via [Interacting rule] below
* Canonicalising a CFunEqCan [G/W] x : F xis ~ fsk/fmv
- Flatten xis (to substitute any tyvars; there are already no functions)
cos :: xis ~ flat_xis
- New wanted x2 :: F flat_xis ~ fsk/fmv
- Add new wanted to flat cache
- Discharge x = F cos ; x2
* Unification flatten-skolems, fmv, ONLY get unified when either
a) The CFunEqCan takes a step, using an axiom
b) During un-flattening
They are never unified in any other form of equality.
For example [W] ffmv ~ Int is stuck; it does not unify with fmv.
* We *never* substitute in the RHS (i.e. the fsk/fmv) of a CFunEqCan.
That would destroy the invariant about the shape of a CFunEqCan,
and it would risk wanted/wanted interactions. The only way we
learn information about fsk is when the CFunEqCan takes a step.
However we *do* substitute in the LHS of a CFunEqCan (else it
would never get to fire!)
* [Interacting rule]
(inert) [W] x1 : F tys ~ fmv1
(work item) [W] x2 : F tys ~ fmv2
Just solve one from the other:
x2 := x1
fmv2 := fmv1
This just unites the two fsks into one.
Always solve given from wanted if poss.
* [Firing rule: wanteds]
(work item) [W] x : F tys ~ fmv
instantiate axiom: ax_co : F tys ~ rhs
Dischard fmv:
fmv := alpha
x := ax_co ; sym x2
[W] x2 : alpha ~ rhs (Non-canonical)
discharging the work item. This is the way that fmv's get
unified; even though they are "untouchable".
NB: this deals with the case where fmv appears in xi, which can
happen; it just happens through the non-canonical stuff
Possible short cut (shortCutReduction) if rhs = G rhs_tys,
where G is a type function. Then
- Flatten rhs_tys (cos : rhs_tys ~ rhs_xis)
- Add G rhs_xis ~ fmv to flat cache
- New wanted [W] x2 : G rhs_xis ~ fmv
- Discharge x := co ; G cos ; x2
* [Firing rule: givens]
(work item) [G] g : F tys ~ fsk
instantiate axiom: co : F tys ~ rhs
Now add non-canonical (since rhs is not flat)
[G] (sym g ; co) : fsk ~ rhs
Short cut (shortCutReduction) for when rhs = G rhs_tys and G is a type function
[G] (co ; g) : G tys ~ fsk
But need to flatten tys: flat_cos : tys ~ flat_tys
[G] (sym (G flat_cos) ; co ; g) : G flat_tys ~ fsk
Why given-fsks, alone, doesn't work
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Could we get away with only flatten meta-tyvars, with no flatten-skolems? No.
[W] w : alpha ~ [F alpha Int]
---> flatten
w = ...w'...
[W] w' : alpha ~ [fsk]
[G] <F alpha Int> : F alpha Int ~ fsk
--> unify (no occurs check)
alpha := [fsk]
But since fsk = F alpha Int, this is really an occurs check error. If
that is all we know about alpha, we will succeed in constraint
solving, producing a program with an infinite type.
Even if we did finally get (g : fsk ~ Boo)l by solving (F alpha Int ~ fsk)
using axiom, zonking would not see it, so (x::alpha) sitting in the
tree will get zonked to an infinite type. (Zonking always only does
refl stuff.)
Why flatten-meta-vars, alone doesn't work
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Look at Simple13, with unification-fmvs only
[G] g : a ~ [F a]
---> Flatten given
g' = g;[x]
[G] g' : a ~ [fmv]
[W] x : F a ~ fmv
--> subst a in x
x = F g' ; x2
[W] x2 : F [fmv] ~ fmv
And now we have an evidence cycle between g' and x!
If we used a given instead (ie current story)
[G] g : a ~ [F a]
---> Flatten given
g' = g;[x]
[G] g' : a ~ [fsk]
[G] <F a> : F a ~ fsk
---> Substitute for a
[G] g' : a ~ [fsk]
[G] F (sym g'); <F a> : F [fsk] ~ fsk
Why is it right to treat fmv's differently to ordinary unification vars?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
f :: forall a. a -> a -> Bool
g :: F Int -> F Int -> Bool
Consider
f (x:Int) (y:Bool)
This gives alpha~Int, alpha~Bool. There is an inconsistency,
but really only one error. SherLoc may tell you which location
is most likely, based on other occurrences of alpha.
Consider
g (x:Int) (y:Bool)
Here we get (F Int ~ Int, F Int ~ Bool), which flattens to
(fmv ~ Int, fmv ~ Bool)
But there are really TWO separate errors. We must not complain
about Int~Bool. Moreover these two errors could arise in entirely
unrelated parts of the code. (In the alpha case, there must be
*some* connection (eg v:alpha in common envt).)
Note [Orient equalities with flatten-meta-vars on the left]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This example comes from IndTypesPerfMerge
From the ambiguity check for
f :: (F a ~ a) => a
we get:
[G] F a ~ a
[W] F alpha ~ alpha, alpha ~ a
From Givens we get
[G] F a ~ fsk, fsk ~ a
Now if we flatten we get
[W] alpha ~ fmv, F alpha ~ fmv, alpha ~ a
Now, processing the first one first, choosing alpha := fmv
[W] F fmv ~ fmv, fmv ~ a
And now we are stuck. We must either *unify* fmv := a, or
use the fmv ~ a to rewrite F fmv ~ fmv, so we can make it
meet up with the given F a ~ blah.
Solution: always put fmvs on the left, so we get
[W] fmv ~ alpha, F alpha ~ fmv, alpha ~ a
The point is that fmvs are very uninformative, so doing alpha := fmv
is a bad idea. We want to use other constraints on alpha first.
Note [Derived constraints from wanted CTyEqCans]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Is this type ambiguous: (Foo e ~ Maybe e) => Foo e
(indexed-types/should_fail/T4093a)
[G] Foo e ~ Maybe e
[W] Foo e ~ Foo ee -- ee is a unification variable
[W] Foo ee ~ Maybe ee)
---
[G] Foo e ~ fsk
[G] fsk ~ Maybe e
[W] Foo e ~ fmv1
[W] Foo ee ~ fmv2
[W] fmv1 ~ fmv2
[W] fmv2 ~ Maybe ee
---> fmv1 := fsk by matching LHSs
[W] Foo ee ~ fmv2
[W] fsk ~ fmv2
[W] fmv2 ~ Maybe ee
--->
[W] Foo ee ~ fmv2
[W] fmv2 ~ Maybe e
[W] fmv2 ~ Maybe ee
Now maybe we shuld get [D] e ~ ee, and then we'd solve it entirely.
But if in a smilar situation we got [D] Int ~ Bool we'd be back
to complaining about wanted/wanted interactions. Maybe this arises
also for fundeps?
Here's another example:
f :: [a] -> [b] -> blah
f (e1 :: F Int) (e2 :: F Int)
we get
F Int ~ fmv
fmv ~ [alpha]
fmv ~ [beta]
We want: alpha := beta (which might unlock something else). If we
generated [D] [alpha] ~ [beta] we'd be good here.
Current story: we don't generate these derived constraints. We could, but
we'd want to make them very weak, so we didn't get the Int~Bool complaint.
************************************************************************
* *
* Other notes (Oct 14)
I have not revisted these, but I didn't want to discard them
* *
************************************************************************
Try: rewrite wanted with wanted only for fmvs (not all meta-tyvars)
But: fmv ~ alpha[0]
alpha[0] ~ fmv’
Now we don’t see that fmv ~ fmv’, which is a problem for injectivity detection.
Conclusion: rewrite wanteds with wanted for all untouchables.
skol ~ untch, must re-orieint to untch ~ skol, so that we can use it to rewrite.
************************************************************************
* *
* Examples
Here is a long series of examples I had to work through
* *
************************************************************************
Simple20
~~~~~~~~
axiom F [a] = [F a]
[G] F [a] ~ a
-->
[G] fsk ~ a
[G] [F a] ~ fsk (nc)
-->
[G] F a ~ fsk2
[G] fsk ~ [fsk2]
[G] fsk ~ a
-->
[G] F a ~ fsk2
[G] a ~ [fsk2]
[G] fsk ~ a
-----------------------------------
----------------------------------------
indexed-types/should_compile/T44984
[W] H (F Bool) ~ H alpha
[W] alpha ~ F Bool
-->
F Bool ~ fmv0
H fmv0 ~ fmv1
H alpha ~ fmv2
fmv1 ~ fmv2
fmv0 ~ alpha
flatten
~~~~~~~
fmv0 := F Bool
fmv1 := H (F Bool)
fmv2 := H alpha
alpha := F Bool
plus
fmv1 ~ fmv2
But these two are equal under the above assumptions.
Solve by Refl.
--- under plan B, namely solve fmv1:=fmv2 eagerly ---
[W] H (F Bool) ~ H alpha
[W] alpha ~ F Bool
-->
F Bool ~ fmv0
H fmv0 ~ fmv1
H alpha ~ fmv2
fmv1 ~ fmv2
fmv0 ~ alpha
-->
F Bool ~ fmv0
H fmv0 ~ fmv1
H alpha ~ fmv2 fmv2 := fmv1
fmv0 ~ alpha
flatten
fmv0 := F Bool
fmv1 := H fmv0 = H (F Bool)
retain H alpha ~ fmv2
because fmv2 has been filled
alpha := F Bool
----------------------------
indexed-types/should_failt/T4179
after solving
[W] fmv_1 ~ fmv_2
[W] A3 (FCon x) ~ fmv_1 (CFunEqCan)
[W] A3 (x (aoa -> fmv_2)) ~ fmv_2 (CFunEqCan)
----------------------------------------
indexed-types/should_fail/T7729a
a) [W] BasePrimMonad (Rand m) ~ m1
b) [W] tt m1 ~ BasePrimMonad (Rand m)
---> process (b) first
BasePrimMonad (Ramd m) ~ fmv_atH
fmv_atH ~ tt m1
---> now process (a)
m1 ~ s_atH ~ tt m1 -- An obscure occurs check
----------------------------------------
typecheck/TcTypeNatSimple
Original constraint
[W] x + y ~ x + alpha (non-canonical)
==>
[W] x + y ~ fmv1 (CFunEqCan)
[W] x + alpha ~ fmv2 (CFuneqCan)
[W] fmv1 ~ fmv2 (CTyEqCan)
(sigh)
----------------------------------------
indexed-types/should_fail/GADTwrong1
[G] Const a ~ ()
==> flatten
[G] fsk ~ ()
work item: Const a ~ fsk
==> fire top rule
[G] fsk ~ ()
work item fsk ~ ()
Surely the work item should rewrite to () ~ ()? Well, maybe not;
it'a very special case. More generally, our givens look like
F a ~ Int, where (F a) is not reducible.
----------------------------------------
indexed_types/should_fail/T8227:
Why using a different can-rewrite rule in CFunEqCan heads
does not work.
Assuming NOT rewriting wanteds with wanteds
Inert: [W] fsk_aBh ~ fmv_aBk -> fmv_aBk
[W] fmv_aBk ~ fsk_aBh
[G] Scalar fsk_aBg ~ fsk_aBh
[G] V a ~ f_aBg
Worklist includes [W] Scalar fmv_aBi ~ fmv_aBk
fmv_aBi, fmv_aBk are flatten unificaiton variables
Work item: [W] V fsk_aBh ~ fmv_aBi
Note that the inert wanteds are cyclic, because we do not rewrite
wanteds with wanteds.
Then we go into a loop when normalise the work-item, because we
use rewriteOrSame on the argument of V.
Conclusion: Don't make canRewrite context specific; instead use
[W] a ~ ty to rewrite a wanted iff 'a' is a unification variable.
----------------------------------------
Here is a somewhat similar case:
type family G a :: *
blah :: (G a ~ Bool, Eq (G a)) => a -> a
blah = error "urk"
foo x = blah x
For foo we get
[W] Eq (G a), G a ~ Bool
Flattening
[W] G a ~ fmv, Eq fmv, fmv ~ Bool
We can't simplify away the Eq Bool unless we substitute for fmv.
Maybe that doesn't matter: we would still be left with unsolved
G a ~ Bool.
--------------------------
Trac #9318 has a very simple program leading to
[W] F Int ~ Int
[W] F Int ~ Bool
We don't want to get "Error Int~Bool". But if fmv's can rewrite
wanteds, we will
[W] fmv ~ Int
[W] fmv ~ Bool
--->
[W] Int ~ Bool
************************************************************************
* *
* The main flattening functions
* *
************************************************************************
Note [Flattening]
~~~~~~~~~~~~~~~~~~~~
flatten ty ==> (xi, cc)
where
xi has no type functions, unless they appear under ForAlls
cc = Auxiliary given (equality) constraints constraining
the fresh type variables in xi. Evidence for these
is always the identity coercion, because internally the
fresh flattening skolem variables are actually identified
with the types they have been generated to stand in for.
Note that it is flatten's job to flatten *every type function it sees*.
flatten is only called on *arguments* to type functions, by canEqGiven.
Recall that in comments we use alpha[flat = ty] to represent a
flattening skolem variable alpha which has been generated to stand in
for ty.
----- Example of flattening a constraint: ------
flatten (List (F (G Int))) ==> (xi, cc)
where
xi = List alpha
cc = { G Int ~ beta[flat = G Int],
F beta ~ alpha[flat = F beta] }
Here
* alpha and beta are 'flattening skolem variables'.
* All the constraints in cc are 'given', and all their coercion terms
are the identity.
NB: Flattening Skolems only occur in canonical constraints, which
are never zonked, so we don't need to worry about zonking doing
accidental unflattening.
Note that we prefer to leave type synonyms unexpanded when possible,
so when the flattener encounters one, it first asks whether its
transitive expansion contains any type function applications. If so,
it expands the synonym and proceeds; if not, it simply returns the
unexpanded synonym.
Note [Flattener EqRels]
~~~~~~~~~~~~~~~~~~~~~~~
When flattening, we need to know which equality relation -- nominal
or representation -- we should be respecting. The only difference is
that we rewrite variables by representational equalities when fe_eq_rel
is ReprEq.
-}
data FlattenEnv
= FE { fe_mode :: FlattenMode
, fe_loc :: CtLoc
, fe_flavour :: CtFlavour
, fe_eq_rel :: EqRel } -- See Note [Flattener EqRels]
data FlattenMode -- Postcondition for all three: inert wrt the type substitution
= FM_FlattenAll -- Postcondition: function-free
| FM_Avoid TcTyVar Bool -- See Note [Lazy flattening]
-- Postcondition:
-- * tyvar is only mentioned in result under a rigid path
-- e.g. [a] is ok, but F a won't happen
-- * If flat_top is True, top level is not a function application
-- (but under type constructors is ok e.g. [F a])
| FM_SubstOnly -- See Note [Flattening under a forall]
mkFlattenEnv :: FlattenMode -> CtEvidence -> FlattenEnv
mkFlattenEnv fm ctev = FE { fe_mode = fm
, fe_loc = ctEvLoc ctev
, fe_flavour = ctEvFlavour ctev
, fe_eq_rel = ctEvEqRel ctev }
feRole :: FlattenEnv -> Role
feRole = eqRelRole . fe_eq_rel
{-
Note [Lazy flattening]
~~~~~~~~~~~~~~~~~~~~~~
The idea of FM_Avoid mode is to flatten less aggressively. If we have
a ~ [F Int]
there seems to be no great merit in lifting out (F Int). But if it was
a ~ [G a Int]
then we *do* want to lift it out, in case (G a Int) reduces to Bool, say,
which gets rid of the occurs-check problem. (For the flat_top Bool, see
comments above and at call sites.)
HOWEVER, the lazy flattening actually seems to make type inference go
*slower*, not faster. perf/compiler/T3064 is a case in point; it gets
*dramatically* worse with FM_Avoid. I think it may be because
floating the types out means we normalise them, and that often makes
them smaller and perhaps allows more re-use of previously solved
goals. But to be honest I'm not absolutely certain, so I am leaving
FM_Avoid in the code base. What I'm removing is the unique place
where it is *used*, namely in TcCanonical.canEqTyVar.
See also Note [Conservative unification check] in TcUnify, which gives
other examples where lazy flattening caused problems.
Bottom line: FM_Avoid is unused for now (Nov 14).
Note: T5321Fun got faster when I disabled FM_Avoid
T5837 did too, but it's pathalogical anyway
Note [Phantoms in the flattener]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have
data Proxy p = Proxy
and we're flattening (Proxy ty) w.r.t. ReprEq. Then, we know that `ty`
is really irrelevant -- it will be ignored when solving for representational
equality later on. So, we omit flattening `ty` entirely. This may
violate the expectation of "xi"s for a bit, but the canonicaliser will
soon throw out the phantoms when decomposing a TyConApp. (Or, the
canonicaliser will emit an insoluble, in which case the unflattened version
yields a better error message anyway.)
Note [flatten_many performance]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In programs with lots of type-level evaluation, flatten_many becomes
part of a tight loop. For example, see test perf/compiler/T9872a, which
calls flatten_many a whopping 7,106,808 times. It is thus important
that flatten_many be efficient.
Performance testing showed that the current implementation is indeed
efficient. It's critically important that zipWithAndUnzipM be
specialized to TcS, and it's also quite helpful to actually `inline`
it. On test T9872a, here are the allocation stats (Dec 16, 2014):
* Unspecialized, uninlined: 8,472,613,440 bytes allocated in the heap
* Specialized, uninlined: 6,639,253,488 bytes allocated in the heap
* Specialized, inlined: 6,281,539,792 bytes allocated in the heap
To improve performance even further, flatten_many_nom is split off
from flatten_many, as nominal equality is the common case. This would
be natural to write using mapAndUnzipM, but even inlined, that function
is not as performant as a hand-written loop.
* mapAndUnzipM, inlined: 7,463,047,432 bytes allocated in the heap
* hand-written recursion: 5,848,602,848 bytes allocated in the heap
If you make any change here, pay close attention to the T9872{a,b,c} tests
and T5321Fun.
If we need to make this yet more performant, a possible way forward is to
duplicate the flattener code for the nominal case, and make that case
faster. This doesn't seem quite worth it, yet.
-}
------------------
flatten :: FlattenMode -> CtEvidence -> TcType -> TcS (Xi, TcCoercion)
flatten mode ev ty
= runFlatten (flatten_one fmode ty)
where
fmode = mkFlattenEnv mode ev
flattenMany :: FlattenMode -> CtEvidence -> [Role]
-> [TcType] -> TcS ([Xi], [TcCoercion])
-- Flatten a bunch of types all at once. Roles on the coercions returned
-- always match the corresponding roles passed in.
flattenMany mode ev roles tys
= runFlatten (flatten_many fmode roles tys)
where
fmode = mkFlattenEnv mode ev
flattenFamApp :: FlattenMode -> CtEvidence
-> TyCon -> [TcType] -> TcS (Xi, TcCoercion)
flattenFamApp mode ev tc tys
= runFlatten (flatten_fam_app fmode tc tys)
where
fmode = mkFlattenEnv mode ev
------------------
flatten_many :: FlattenEnv -> [Role] -> [Type] -> TcS ([Xi], [TcCoercion])
-- Coercions :: Xi ~ Type, at roles given
-- Returns True iff (no flattening happened)
-- NB: The EvVar inside the 'fe_ev :: CtEvidence' is unused,
-- we merely want (a) Given/Solved/Derived/Wanted info
-- (b) the GivenLoc/WantedLoc for when we create new evidence
flatten_many fmode roles tys
-- See Note [flatten_many performance]
= inline zipWithAndUnzipM go roles tys
where
go Nominal ty = flatten_one (setFEEqRel fmode NomEq) ty
go Representational ty = flatten_one (setFEEqRel fmode ReprEq) ty
go Phantom ty = -- See Note [Phantoms in the flattener]
return (ty, mkTcPhantomCo ty ty)
-- | Like 'flatten_many', but assumes that every role is nominal.
flatten_many_nom :: FlattenEnv -> [Type] -> TcS ([Xi], [TcCoercion])
flatten_many_nom _ [] = return ([], [])
-- See Note [flatten_many performance]
flatten_many_nom fmode (ty:tys)
= --ASSERT( fe_eq_rel fmode == NomEq )
do { (xi, co) <- flatten_one fmode ty
; (xis, cos) <- flatten_many_nom fmode tys
; return (xi:xis, co:cos) }
------------------
flatten_one :: FlattenEnv -> TcType -> TcS (Xi, TcCoercion)
-- Flatten a type to get rid of type function applications, returning
-- the new type-function-free type, and a collection of new equality
-- constraints. See Note [Flattening] for more detail.
--
-- Postcondition: Coercion :: Xi ~ TcType
-- The role on the result coercion matches the EqRel in the FlattenEnv
flatten_one fmode xi@(LitTy {}) = return (xi, mkTcReflCo (feRole fmode) xi)
flatten_one fmode (TyVarTy tv)
= flattenTyVar fmode tv
flatten_one fmode (AppTy ty1 ty2)
= do { (xi1,co1) <- flatten_one fmode ty1
; case (fe_eq_rel fmode, nextRole xi1) of
(NomEq, _) -> flatten_rhs xi1 co1 NomEq
(ReprEq, Nominal) -> flatten_rhs xi1 co1 NomEq
(ReprEq, Representational) -> flatten_rhs xi1 co1 ReprEq
(ReprEq, Phantom) ->
return (mkAppTy xi1 ty2, co1 `mkTcAppCo` mkTcNomReflCo ty2) }
where
flatten_rhs xi1 co1 eq_rel2
= do { (xi2,co2) <- flatten_one (setFEEqRel fmode eq_rel2) ty2
; traceTcS "flatten/appty"
(ppr ty1 $$ ppr ty2 $$ ppr xi1 $$
ppr co1 $$ ppr xi2 $$ ppr co2)
; let role1 = feRole fmode
role2 = eqRelRole eq_rel2
; return ( mkAppTy xi1 xi2
, mkTcTransAppCo role1 co1 xi1 ty1
role2 co2 xi2 ty2
role1 ) } -- output should match fmode
flatten_one fmode (FunTy ty1 ty2)
= do { (xi1,co1) <- flatten_one fmode ty1
; (xi2,co2) <- flatten_one fmode ty2
; return (mkFunTy xi1 xi2, mkTcFunCo (feRole fmode) co1 co2) }
flatten_one fmode (TyConApp tc tys)
-- Expand type synonyms that mention type families
-- on the RHS; see Note [Flattening synonyms]
| Just (tenv, rhs, tys') <- tcExpandTyCon_maybe tc tys
, let expanded_ty = mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys'
= case fe_mode fmode of
FM_FlattenAll | anyNameEnv isTypeFamilyTyCon (tyConsOfType rhs)
-> flatten_one fmode expanded_ty
| otherwise
-> flattenTyConApp fmode tc tys
_ -> flattenTyConApp fmode tc tys
-- Otherwise, it's a type function application, and we have to
-- flatten it away as well, and generate a new given equality constraint
-- between the application and a newly generated flattening skolem variable.
| isTypeFamilyTyCon tc
= flatten_fam_app fmode tc tys
-- For * a normal data type application
-- * data family application
-- we just recursively flatten the arguments.
| otherwise
-- FM_Avoid stuff commented out; see Note [Lazy flattening]
-- , let fmode' = case fmode of -- Switch off the flat_top bit in FM_Avoid
-- FE { fe_mode = FM_Avoid tv _ }
-- -> fmode { fe_mode = FM_Avoid tv False }
-- _ -> fmode
= flattenTyConApp fmode tc tys
flatten_one fmode ty@(ForAllTy {})
-- We allow for-alls when, but only when, no type function
-- applications inside the forall involve the bound type variables.
= do { let (tvs, rho) = splitForAllTys ty
; (rho', co) <- flatten_one (setFEMode fmode FM_SubstOnly) rho
-- Substitute only under a forall
-- See Note [Flattening under a forall]
; return (mkForAllTys tvs rho', foldr mkTcForAllCo co tvs) }
flattenTyConApp :: FlattenEnv -> TyCon -> [TcType] -> TcS (Xi, TcCoercion)
flattenTyConApp fmode tc tys
= do { (xis, cos) <- case fe_eq_rel fmode of
NomEq -> flatten_many_nom fmode tys
ReprEq -> flatten_many fmode (tyConRolesX role tc) tys
; return (mkTyConApp tc xis, mkTcTyConAppCo role tc cos) }
where
role = feRole fmode
{-
Note [Flattening synonyms]
~~~~~~~~~~~~~~~~~~~~~~~~~~
Not expanding synonyms aggressively improves error messages, and
keeps types smaller. But we need to take care.
Suppose
type T a = a -> a
and we want to flatten the type (T (F a)). Then we can safely flatten
the (F a) to a skolem, and return (T fsk). We don't need to expand the
synonym. This works because TcTyConAppCo can deal with synonyms
(unlike TyConAppCo), see Note [TcCoercions] in TcEvidence.
But (Trac #8979) for
type T a = (F a, a) where F is a type function
we must expand the synonym in (say) T Int, to expose the type function
to the flattener.
Note [Flattening under a forall]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Under a forall, we
(a) MUST apply the inert substitution
(b) MUST NOT flatten type family applications
Hence FMSubstOnly.
For (a) consider c ~ a, a ~ T (forall b. (b, [c]))
If we don't apply the c~a substitution to the second constraint
we won't see the occurs-check error.
For (b) consider (a ~ forall b. F a b), we don't want to flatten
to (a ~ forall b.fsk, F a b ~ fsk)
because now the 'b' has escaped its scope. We'd have to flatten to
(a ~ forall b. fsk b, forall b. F a b ~ fsk b)
and we have not begun to think about how to make that work!
************************************************************************
* *
Flattening a type-family application
* *
************************************************************************
-}
flatten_fam_app, flatten_exact_fam_app, flatten_exact_fam_app_fully
:: FlattenEnv -> TyCon -> [TcType] -> TcS (Xi, TcCoercion)
-- flatten_fam_app can be over-saturated
-- flatten_exact_fam_app is exactly saturated
-- flatten_exact_fam_app_fully lifts out the application to top level
-- Postcondition: Coercion :: Xi ~ F tys
flatten_fam_app fmode tc tys -- Can be over-saturated
= --ASSERT( tyConArity tc <= length tys ) -- Type functions are saturated
-- The type function might be *over* saturated
-- in which case the remaining arguments should
-- be dealt with by AppTys
do { let (tys1, tys_rest) = splitAt (tyConArity tc) tys
; (xi1, co1) <- flatten_exact_fam_app fmode tc tys1
-- co1 :: xi1 ~ F tys1
-- all Nominal roles b/c the tycon is oversaturated
; (xis_rest, cos_rest) <- flatten_many fmode (repeat Nominal) tys_rest
-- cos_res :: xis_rest ~ tys_rest
; return ( mkAppTys xi1 xis_rest -- NB mkAppTys: rhs_xi might not be a type variable
-- cf Trac #5655
, mkTcAppCos co1 cos_rest -- (rhs_xi :: F xis) ; (F cos :: F xis ~ F tys)
) }
flatten_exact_fam_app fmode tc tys
= case fe_mode fmode of
FM_FlattenAll -> flatten_exact_fam_app_fully fmode tc tys
FM_SubstOnly -> do { (xis, cos) <- flatten_many fmode roles tys
; return ( mkTyConApp tc xis
, mkTcTyConAppCo (feRole fmode) tc cos ) }
FM_Avoid tv flat_top ->
do { (xis, cos) <- flatten_many fmode roles tys
; if flat_top || tv `elemVarSet` tyVarsOfTypes xis
then flatten_exact_fam_app_fully fmode tc tys
else return ( mkTyConApp tc xis
, mkTcTyConAppCo (feRole fmode) tc cos ) }
where
-- These are always going to be Nominal for now,
-- but not if #8177 is implemented
roles = tyConRolesX (feRole fmode) tc
flatten_exact_fam_app_fully fmode tc tys
-- See Note [Reduce type family applications eagerly]
= try_to_reduce tc tys False id $
do { (xis, cos) <- flatten_many_nom (setFEEqRel (setFEMode fmode FM_FlattenAll) NomEq) tys
; let ret_co = mkTcTyConAppCo (feRole fmode) tc cos
-- ret_co :: F xis ~ F tys
; mb_ct <- lookupFlatCache tc xis
; case mb_ct of
Just (co, rhs_ty, flav) -- co :: F xis ~ fsk
| (flav, NomEq) `canRewriteOrSameFR` (feFlavourRole fmode)
-> -- Usable hit in the flat-cache
-- We certainly *can* use a Wanted for a Wanted
do { traceTcS "flatten/flat-cache hit" $ (ppr tc <+> ppr xis $$ ppr rhs_ty $$ ppr co)
; (fsk_xi, fsk_co) <- flatten_one fmode rhs_ty
-- The fsk may already have been unified, so flatten it
-- fsk_co :: fsk_xi ~ fsk
; return (fsk_xi, fsk_co `mkTcTransCo`
maybeTcSubCo (fe_eq_rel fmode)
(mkTcSymCo co) `mkTcTransCo`
ret_co) }
-- :: fsk_xi ~ F xis
-- Try to reduce the family application right now
-- See Note [Reduce type family applications eagerly]
_ -> try_to_reduce tc xis True (`mkTcTransCo` ret_co) $
do { let fam_ty = mkTyConApp tc xis
; (ev, fsk) <- newFlattenSkolem (fe_flavour fmode)
(fe_loc fmode)
fam_ty
; let fsk_ty = mkTyVarTy fsk
co = ctEvCoercion ev
; extendFlatCache tc xis (co, fsk_ty, ctEvFlavour ev)
-- The new constraint (F xis ~ fsk) is not necessarily inert
-- (e.g. the LHS may be a redex) so we must put it in the work list
; let ct = CFunEqCan { cc_ev = ev
, cc_fun = tc
, cc_tyargs = xis
, cc_fsk = fsk }
; emitFlatWork ct
; traceTcS "flatten/flat-cache miss" $ (ppr fam_ty $$ ppr fsk $$ ppr ev)
; return (fsk_ty, maybeTcSubCo (fe_eq_rel fmode)
(mkTcSymCo co)
`mkTcTransCo` ret_co) }
}
where
try_to_reduce :: TyCon -- F, family tycon
-> [Type] -- args, not necessarily flattened
-> Bool -- add to the flat cache?
-> ( TcCoercion -- :: xi ~ F args
-> TcCoercion ) -- what to return from outer function
-> TcS (Xi, TcCoercion) -- continuation upon failure
-> TcS (Xi, TcCoercion)
try_to_reduce tc tys cache update_co k
= do { mb_match <- matchFam tc tys
; case mb_match of
Just (norm_co, norm_ty)
-> do { traceTcS "Eager T.F. reduction success" $
vcat [ppr tc, ppr tys, ppr norm_ty, ppr cache]
; (xi, final_co) <- flatten_one fmode norm_ty
; let co = norm_co `mkTcTransCo` mkTcSymCo final_co
; when cache $
extendFlatCache tc tys (co, xi, fe_flavour fmode)
; return (xi, update_co $ mkTcSymCo co) }
Nothing -> k }
{- Note [Reduce type family applications eagerly]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we come across a type-family application like (Append (Cons x Nil) t),
then, rather than flattening to a skolem etc, we may as well just reduce
it on the spot to (Cons x t). This saves a lot of intermediate steps.
Examples that are helped are tests T9872, and T5321Fun.
Performance testing indicates that it's best to try this *twice*, once
before flattening arguments and once after flattening arguments.
Adding the extra reduction attempt before flattening arguments cut
the allocation amounts for the T9872{a,b,c} tests by half. Testing
also indicated that the early reduction should not use the flat-cache,
but that the later reduction should. It's possible that with more
examples, we might learn that these knobs should be set differently.
Once we've got a flat rhs, we extend the flatten-cache to record the
result. Doing so can save lots of work when the same redex shows up
more than once. Note that we record the link from the redex all the
way to its *final* value, not just the single step reduction.
************************************************************************
* *
Flattening a type variable
* *
************************************************************************
Note [The inert equalities]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Definition [Can-rewrite relation]
A "can-rewrite" relation between flavours, written f1 >= f2, is a
binary relation with the following properties
R1. >= is transitive
R2. If f1 >= f, and f2 >= f,
then either f1 >= f2 or f2 >= f1
Lemma. If f1 >= f then f1 >= f1
Proof. By property (R2), with f1=f2
Definition [Generalised substitution]
A "generalised substitution" S is a set of triples (a -f-> t), where
a is a type variable
t is a type
f is a flavour
such that
(WF1) if (a -f1-> t1) in S
(a -f2-> t2) in S
then neither (f1 >= f2) nor (f2 >= f1) hold
(WF2) if (a -f-> t) is in S, then t /= a
Definition [Applying a generalised substitution]
If S is a generalised substitution
S(f,a) = t, if (a -fs-> t) in S, and fs >= f
= a, otherwise
Application extends naturally to types S(f,t), modulo roles.
See Note [Flavours with roles].
Theorem: S(f,a) is well defined as a function.
Proof: Suppose (a -f1-> t1) and (a -f2-> t2) are both in S,
and f1 >= f and f2 >= f
Then by (R2) f1 >= f2 or f2 >= f1, which contradicts (WF)
Notation: repeated application.
S^0(f,t) = t
S^(n+1)(f,t) = S(f, S^n(t))
Definition: inert generalised substitution
A generalised substitution S is "inert" iff
(IG1) there is an n such that
for every f,t, S^n(f,t) = S^(n+1)(f,t)
(IG2) if (b -f-> t) in S, and f >= f, then S(f,t) = t
that is, each individual binding is "self-stable"
----------------------------------------------------------------
Our main invariant:
the inert CTyEqCans should be an inert generalised substitution
----------------------------------------------------------------
Note that inertness is not the same as idempotence. To apply S to a
type, you may have to apply it recursive. But inertness does
guarantee that this recursive use will terminate.
---------- The main theorem --------------
Suppose we have a "work item"
a -fw-> t
and an inert generalised substitution S,
such that
(T1) S(fw,a) = a -- LHS of work-item is a fixpoint of S(fw,_)
(T2) S(fw,t) = t -- RHS of work-item is a fixpoint of S(fw,_)
(T3) a not in t -- No occurs check in the work item
(K1) if (a -fs-> s) is in S then not (fw >= fs)
(K2) if (b -fs-> s) is in S, where b /= a, then
(K2a) not (fs >= fs)
or (K2b) not (fw >= fs)
or (K2c) a not in s
(K3) If (b -fs-> s) is in S with (fw >= fs), then
(K3a) If the role of fs is nominal: s /= a
(K3b) If the role of fs is representational: EITHER
a not in s, OR
the path from the top of s to a includes at least one non-newtype
then the extended substition T = S+(a -fw-> t)
is an inert generalised substitution.
The idea is that
* (T1-2) are guaranteed by exhaustively rewriting the work-item
with S(fw,_).
* T3 is guaranteed by a simple occurs-check on the work item.
* (K1-3) are the "kick-out" criteria. (As stated, they are really the
"keep" criteria.) If the current inert S contains a triple that does
not satisfy (K1-3), then we remove it from S by "kicking it out",
and re-processing it.
* Note that kicking out is a Bad Thing, because it means we have to
re-process a constraint. The less we kick out, the better.
TODO: Make sure that kicking out really *is* a Bad Thing. We've assumed
this but haven't done the empirical study to check.
* Assume we have G>=G, G>=W, D>=D, and that's all. Then, when performing
a unification we add a new given a -G-> ty. But doing so does NOT require
us to kick out an inert wanted that mentions a, because of (K2a). This
is a common case, hence good not to kick out.
* Lemma (L1): The conditions of the Main Theorem imply that there is no
(a fs-> t) in S, s.t. (fs >= fw).
Proof. Suppose the contrary (fs >= fw). Then because of (T1),
S(fw,a)=a. But since fs>=fw, S(fw,a) = s, hence s=a. But now we
have (a -fs-> a) in S, which contradicts (WF2).
* The extended substitution satisfies (WF1) and (WF2)
- (K1) plus (L1) guarantee that the extended substiution satisfies (WF1).
- (T3) guarantees (WF2).
* (K2) is about inertness. Intuitively, any infinite chain T^0(f,t),
T^1(f,t), T^2(f,T).... must pass through the new work item infnitely
often, since the substution without the work item is inert; and must
pass through at least one of the triples in S infnitely often.
- (K2a): if not(fs>=fs) then there is no f that fs can rewrite (fs>=f),
and hence this triple never plays a role in application S(f,a).
It is always safe to extend S with such a triple.
(NB: we could strengten K1) in this way too, but see K3.
- (K2b): If this holds, we can't pass through this triple infinitely
often, because if we did then fs>=f, fw>=f, hence fs>=fw,
contradicting (L1), or fw>=fs contradicting K2b.
- (K2c): if a not in s, we hae no further opportunity to apply the
work item.
NB: this reasoning isn't water tight.
Key lemma to make it watertight.
Under the conditions of the Main Theorem,
forall f st fw >= f, a is not in S^k(f,t), for any k
Also, consider roles more carefully. See Note [Flavours with roles].
Completeness
~~~~~~~~~~~~~
K3: completeness. (K3) is not necessary for the extended substitution
to be inert. In fact K1 could be made stronger by saying
... then (not (fw >= fs) or not (fs >= fs))
But it's not enough for S to be inert; we also want completeness.
That is, we want to be able to solve all soluble wanted equalities.
Suppose we have
work-item b -G-> a
inert-item a -W-> b
Assuming (G >= W) but not (W >= W), this fulfills all the conditions,
so we could extend the inerts, thus:
inert-items b -G-> a
a -W-> b
But if we kicked-out the inert item, we'd get
work-item a -W-> b
inert-item b -G-> a
Then rewrite the work-item gives us (a -W-> a), which is soluble via Refl.
So we add one more clause to the kick-out criteria
Another way to understand (K3) is that we treat an inert item
a -f-> b
in the same way as
b -f-> a
So if we kick out one, we should kick out the other. The orientation
is somewhat accidental.
When considering roles, we also need the second clause (K3b). Consider
inert-item a -W/R-> b c
work-item c -G/N-> a
The work-item doesn't get rewritten by the inert, because (>=) doesn't hold.
We've satisfied conditions (T1)-(T3) and (K1) and (K2). If all we had were
condition (K3a), then we would keep the inert around and add the work item.
But then, consider if we hit the following:
work-item2 b -G/N-> Id
where
newtype Id x = Id x
For similar reasons, if we only had (K3a), we wouldn't kick the
representational inert out. And then, we'd miss solving the inert, which
now reduced to reflexivity. The solution here is to kick out representational
inerts whenever the tyvar of a work item is "exposed", where exposed means
not under some proper data-type constructor, like [] or Maybe. See
isTyVarExposed in TcType. This is encoded in (K3b).
Note [Flavours with roles]
~~~~~~~~~~~~~~~~~~~~~~~~~~
The system described in Note [The inert equalities] discusses an abstract
set of flavours. In GHC, flavours have two components: the flavour proper,
taken from {Wanted, Derived, Given}; and the equality relation (often called
role), taken from {NomEq, ReprEq}. When substituting w.r.t. the inert set,
as described in Note [The inert equalities], we must be careful to respect
roles. For example, if we have
inert set: a -G/R-> Int
b -G/R-> Bool
type role T nominal representational
and we wish to compute S(W/R, T a b), the correct answer is T a Bool, NOT
T Int Bool. The reason is that T's first parameter has a nominal role, and
thus rewriting a to Int in T a b is wrong. Indeed, this non-congruence of
subsitution means that the proof in Note [The inert equalities] may need
to be revisited, but we don't think that the end conclusion is wrong.
-}
flattenTyVar :: FlattenEnv -> TcTyVar -> TcS (Xi, TcCoercion)
-- "Flattening" a type variable means to apply the substitution to it
-- The substitution is actually the union of
-- * the unifications that have taken place (either before the
-- solver started, or in TcInteract.solveByUnification)
-- * the CTyEqCans held in the inert set
--
-- Postcondition: co : xi ~ tv
flattenTyVar fmode tv
= do { mb_yes <- flattenTyVarOuter fmode tv
; case mb_yes of
Left tv' -> -- Done
do { traceTcS "flattenTyVar1" (ppr tv $$ ppr (tyVarKind tv'))
; return (ty', mkTcReflCo (feRole fmode) ty') }
where
ty' = mkTyVarTy tv'
Right (ty1, co1) -- Recurse
-> do { (ty2, co2) <- flatten_one fmode ty1
; traceTcS "flattenTyVar3" (ppr tv $$ ppr ty2)
; return (ty2, co2 `mkTcTransCo` co1) }
}
flattenTyVarOuter :: FlattenEnv -> TcTyVar
-> TcS (Either TyVar (TcType, TcCoercion))
-- Look up the tyvar in
-- a) the internal MetaTyVar box
-- b) the tyvar binds
-- c) the inerts
-- Return (Left tv') if it is not found, tv' has a properly zonked kind
-- (Right (ty, co) if found, with co :: ty ~ tv;
flattenTyVarOuter fmode tv
| not (isTcTyVar tv) -- Happens when flatten under a (forall a. ty)
= Left `liftM` flattenTyVarFinal fmode tv
-- So ty contains refernces to the non-TcTyVar a
| otherwise
= do { mb_ty <- isFilledMetaTyVar_maybe tv
; case mb_ty of {
Just ty -> do { traceTcS "Following filled tyvar" (ppr tv <+> equals <+> ppr ty)
; return (Right (ty, mkTcReflCo (feRole fmode) ty)) } ;
Nothing ->
-- Try in the inert equalities
-- See Definition [Applying a generalised substitution]
do { ieqs <- getInertEqs
; case lookupVarEnv ieqs tv of
Just (ct:_) -- If the first doesn't work,
-- the subsequent ones won't either
| CTyEqCan { cc_ev = ctev, cc_tyvar = tv, cc_rhs = rhs_ty } <- ct
, ctEvFlavourRole ctev `eqCanRewriteFR` feFlavourRole fmode
-> do { traceTcS "Following inert tyvar" (ppr tv <+> equals <+> ppr rhs_ty $$ ppr ctev)
; let rewrite_co1 = mkTcSymCo (ctEvCoercion ctev)
rewrite_co = case (ctEvEqRel ctev, fe_eq_rel fmode) of
(ReprEq, _rel) -> --ASSERT( _rel == ReprEq )
-- if this ASSERT fails, then
-- eqCanRewriteFR answered incorrectly
rewrite_co1
(NomEq, NomEq) -> rewrite_co1
(NomEq, ReprEq) -> mkTcSubCo rewrite_co1
; return (Right (rhs_ty, rewrite_co)) }
-- NB: ct is Derived then fmode must be also, hence
-- we are not going to touch the returned coercion
-- so ctEvCoercion is fine.
_other -> Left `liftM` flattenTyVarFinal fmode tv
} } }
flattenTyVarFinal :: FlattenEnv -> TcTyVar -> TcS TyVar
flattenTyVarFinal fmode tv
= -- Done, but make sure the kind is zonked
do { let kind = tyVarKind tv
kind_fmode = setFEMode fmode FM_SubstOnly
; (new_knd, _kind_co) <- flatten_one kind_fmode kind
; return (setVarType tv new_knd) }
{-
Note [An alternative story for the inert substitution]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
(This entire note is just background, left here in case we ever want
to return the the previousl state of affairs)
We used (GHC 7.8) to have this story for the inert substitution inert_eqs
* 'a' is not in fvs(ty)
* They are *inert* in the weaker sense that there is no infinite chain of
(i1 `eqCanRewrite` i2), (i2 `eqCanRewrite` i3), etc
This means that flattening must be recursive, but it does allow
[G] a ~ [b]
[G] b ~ Maybe c
This avoids "saturating" the Givens, which can save a modest amount of work.
It is easy to implement, in TcInteract.kick_out, by only kicking out an inert
only if (a) the work item can rewrite the inert AND
(b) the inert cannot rewrite the work item
This is signifcantly harder to think about. It can save a LOT of work
in occurs-check cases, but we don't care about them much. Trac #5837
is an example; all the constraints here are Givens
[G] a ~ TF (a,Int)
-->
work TF (a,Int) ~ fsk
inert fsk ~ a
--->
work fsk ~ (TF a, TF Int)
inert fsk ~ a
--->
work a ~ (TF a, TF Int)
inert fsk ~ a
---> (attempting to flatten (TF a) so that it does not mention a
work TF a ~ fsk2
inert a ~ (fsk2, TF Int)
inert fsk ~ (fsk2, TF Int)
---> (substitute for a)
work TF (fsk2, TF Int) ~ fsk2
inert a ~ (fsk2, TF Int)
inert fsk ~ (fsk2, TF Int)
---> (top-level reduction, re-orient)
work fsk2 ~ (TF fsk2, TF Int)
inert a ~ (fsk2, TF Int)
inert fsk ~ (fsk2, TF Int)
---> (attempt to flatten (TF fsk2) to get rid of fsk2
work TF fsk2 ~ fsk3
work fsk2 ~ (fsk3, TF Int)
inert a ~ (fsk2, TF Int)
inert fsk ~ (fsk2, TF Int)
--->
work TF fsk2 ~ fsk3
inert fsk2 ~ (fsk3, TF Int)
inert a ~ ((fsk3, TF Int), TF Int)
inert fsk ~ ((fsk3, TF Int), TF Int)
Because the incoming given rewrites all the inert givens, we get more and
more duplication in the inert set. But this really only happens in pathalogical
casee, so we don't care.
-}
eqCanRewrite :: CtEvidence -> CtEvidence -> Bool
eqCanRewrite ev1 ev2 = ctEvFlavourRole ev1 `eqCanRewriteFR` ctEvFlavourRole ev2
-- | Whether or not one 'Ct' can rewrite another is determined by its
-- flavour and its equality relation
type CtFlavourRole = (CtFlavour, EqRel)
-- | Extract the flavour and role from a 'CtEvidence'
ctEvFlavourRole :: CtEvidence -> CtFlavourRole
ctEvFlavourRole ev = (ctEvFlavour ev, ctEvEqRel ev)
-- | Extract the flavour and role from a 'Ct'
ctFlavourRole :: Ct -> CtFlavourRole
ctFlavourRole = ctEvFlavourRole . cc_ev
-- | Extract the flavour and role from a 'FlattenEnv'
feFlavourRole :: FlattenEnv -> CtFlavourRole
feFlavourRole (FE { fe_flavour = flav, fe_eq_rel = eq_rel })
= (flav, eq_rel)
eqCanRewriteFR :: CtFlavourRole -> CtFlavourRole -> Bool
-- Very important function!
-- See Note [eqCanRewrite]
eqCanRewriteFR (Given, NomEq) (_, _) = True
eqCanRewriteFR (Given, ReprEq) (_, ReprEq) = True
eqCanRewriteFR _ _ = False
canRewriteOrSame :: CtEvidence -> CtEvidence -> Bool
-- See Note [canRewriteOrSame]
canRewriteOrSame ev1 ev2 = ev1 `eqCanRewrite` ev2 ||
ctEvFlavourRole ev1 == ctEvFlavourRole ev2
canRewriteOrSameFR :: CtFlavourRole -> CtFlavourRole -> Bool
canRewriteOrSameFR fr1 fr2 = fr1 `eqCanRewriteFR` fr2 || fr1 == fr2
{-
Note [eqCanRewrite]
~~~~~~~~~~~~~~~~~~~
(eqCanRewrite ct1 ct2) holds if the constraint ct1 (a CTyEqCan of form
tv ~ ty) can be used to rewrite ct2. It must satisfy the properties of
a can-rewrite relation, see Definition [Can-rewrite relation]
At the moment we don't allow Wanteds to rewrite Wanteds, because that can give
rise to very confusing type error messages. A good example is Trac #8450.
Here's another
f :: a -> Bool
f x = ( [x,'c'], [x,True] ) `seq` True
Here we get
[W] a ~ Char
[W] a ~ Bool
but we do not want to complain about Bool ~ Char!
Accordingly, we also don't let Deriveds rewrite Deriveds.
With the solver handling Coercible constraints like equality constraints,
the rewrite conditions must take role into account, never allowing
a representational equality to rewrite a nominal one.
Note [canRewriteOrSame]
~~~~~~~~~~~~~~~~~~~~~~~
canRewriteOrSame is similar but
* returns True for Wanted/Wanted.
* works for all kinds of constraints, not just CTyEqCans
See the call sites for explanations.
************************************************************************
* *
Unflattening
* *
************************************************************************
An unflattening example:
[W] F a ~ alpha
flattens to
[W] F a ~ fmv (CFunEqCan)
[W] fmv ~ alpha (CTyEqCan)
We must solve both!
-}
unflatten :: Cts -> Cts -> TcS Cts
unflatten tv_eqs funeqs
= do { dflags <- getDynFlags
; tclvl <- getTcLevel
; traceTcS "Unflattening" $ braces $
vcat [ ptext (sLit "Funeqs =") <+> pprCts funeqs
, ptext (sLit "Tv eqs =") <+> pprCts tv_eqs ]
-- Step 1: unflatten the CFunEqCans, except if that causes an occurs check
-- See Note [Unflatten using funeqs first]
; funeqs <- foldrBagM (unflatten_funeq dflags) emptyCts funeqs
; traceTcS "Unflattening 1" $ braces (pprCts funeqs)
-- Step 2: unify the irreds, if possible
; tv_eqs <- foldrBagM (unflatten_eq dflags tclvl) emptyCts tv_eqs
; traceTcS "Unflattening 2" $ braces (pprCts tv_eqs)
-- Step 3: fill any remaining fmvs with fresh unification variables
; funeqs <- mapBagM finalise_funeq funeqs
; traceTcS "Unflattening 3" $ braces (pprCts funeqs)
-- Step 4: remove any irreds that look like ty ~ ty
; tv_eqs <- foldrBagM finalise_eq emptyCts tv_eqs
; let all_flat = tv_eqs `andCts` funeqs
; traceTcS "Unflattening done" $ braces (pprCts all_flat)
; return all_flat }
where
----------------
unflatten_funeq :: DynFlags -> Ct -> Cts -> TcS Cts
unflatten_funeq dflags ct@(CFunEqCan { cc_fun = tc, cc_tyargs = xis
, cc_fsk = fmv, cc_ev = ev }) rest
= do { -- fmv should be a flatten meta-tv; we now fix its final
-- value, and then zonking will eliminate it
filled <- tryFill dflags fmv (mkTyConApp tc xis) ev
; return (if filled then rest else ct `consCts` rest) }
unflatten_funeq _ other_ct _
= pprPanic "unflatten_funeq" (ppr other_ct)
----------------
finalise_funeq :: Ct -> TcS Ct
finalise_funeq (CFunEqCan { cc_fsk = fmv, cc_ev = ev })
= do { demoteUnfilledFmv fmv
; return (mkNonCanonical ev) }
finalise_funeq ct = pprPanic "finalise_funeq" (ppr ct)
----------------
unflatten_eq :: DynFlags -> TcLevel -> Ct -> Cts -> TcS Cts
unflatten_eq dflags tclvl ct@(CTyEqCan { cc_ev = ev, cc_tyvar = tv, cc_rhs = rhs }) rest
| isFmvTyVar tv
= do { lhs_elim <- tryFill dflags tv rhs ev
; if lhs_elim then return rest else
do { rhs_elim <- try_fill dflags tclvl ev rhs (mkTyVarTy tv)
; if rhs_elim then return rest else
return (ct `consCts` rest) } }
| otherwise
= return (ct `consCts` rest)
unflatten_eq _ _ ct _ = pprPanic "unflatten_irred" (ppr ct)
----------------
finalise_eq :: Ct -> Cts -> TcS Cts
finalise_eq (CTyEqCan { cc_ev = ev, cc_tyvar = tv
, cc_rhs = rhs, cc_eq_rel = eq_rel }) rest
| isFmvTyVar tv
= do { ty1 <- zonkTcTyVar tv
; ty2 <- zonkTcType rhs
; let is_refl = ty1 `tcEqType` ty2
; if is_refl then do { when (isWanted ev) $
setEvBind (ctEvId ev)
(EvCoercion $
mkTcReflCo (eqRelRole eq_rel) rhs)
; return rest }
else return (mkNonCanonical ev `consCts` rest) }
| otherwise
= return (mkNonCanonical ev `consCts` rest)
finalise_eq ct _ = pprPanic "finalise_irred" (ppr ct)
----------------
try_fill dflags tclvl ev ty1 ty2
| Just tv1 <- tcGetTyVar_maybe ty1
, isTouchableOrFmv tclvl tv1
, typeKind ty1 `isSubKind` tyVarKind tv1
= tryFill dflags tv1 ty2 ev
| otherwise
= return False
tryFill :: DynFlags -> TcTyVar -> TcType -> CtEvidence -> TcS Bool
-- (tryFill tv rhs ev) sees if 'tv' is an un-filled MetaTv
-- If so, and if tv does not appear in 'rhs', set tv := rhs
-- bind the evidence (which should be a CtWanted) to Refl<rhs>
-- and return True. Otherwise return False
tryFill dflags tv rhs ev
= --ASSERT2( not (isGiven ev), ppr ev )
do { is_filled <- isFilledMetaTyVar tv
; if is_filled then return False else
do { rhs' <- zonkTcType rhs
; case occurCheckExpand dflags tv rhs' of
OC_OK rhs'' -- Normal case: fill the tyvar
-> do { when (isWanted ev) $
setEvBind (ctEvId ev)
(EvCoercion (mkTcReflCo (ctEvRole ev) rhs''))
; setWantedTyBind tv rhs''
; return True }
_ -> -- Occurs check
return False } }
{-
Note [Unflatten using funeqs first]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[W] G a ~ Int
[W] F (G a) ~ G a
do not want to end up with
[W} F Int ~ Int
because that might actually hold! Better to end up with the two above
unsolved constraints. The flat form will be
G a ~ fmv1 (CFunEqCan)
F fmv1 ~ fmv2 (CFunEqCan)
fmv1 ~ Int (CTyEqCan)
fmv1 ~ fmv2 (CTyEqCan)
Flatten using the fun-eqs first.
-}
-- | Change the 'EqRel' in a 'FlattenEnv'. Avoids allocating a
-- new 'FlattenEnv' where possible.
setFEEqRel :: FlattenEnv -> EqRel -> FlattenEnv
setFEEqRel fmode@(FE { fe_eq_rel = old_eq_rel }) new_eq_rel
| old_eq_rel == new_eq_rel = fmode
| otherwise = fmode { fe_eq_rel = new_eq_rel }
-- | Change the 'FlattenMode' in a 'FlattenEnv'. Avoids allocating
-- a new 'FlattenEnv' where possible.
setFEMode :: FlattenEnv -> FlattenMode -> FlattenEnv
setFEMode fmode@(FE { fe_mode = old_mode }) new_mode
| old_mode `eq` new_mode = fmode
| otherwise = fmode { fe_mode = new_mode }
where
FM_FlattenAll `eq` FM_FlattenAll = True
FM_SubstOnly `eq` FM_SubstOnly = True
FM_Avoid tv1 b1 `eq` FM_Avoid tv2 b2 = tv1 == tv2 && b1 == b2
_ `eq` _ = False
|
alexander-at-github/eta
|
compiler/ETA/TypeCheck/TcFlatten.hs
|
Haskell
|
bsd-3-clause
| 58,244
|
{-# LANGUAGE OverloadedStrings #-}
module Spin
( SourceID
, Source (..)
, session
, yield
, dedup
, Sink (..)
, sinkFile
, sinkYarn
, spin
) where
import Control.Monad (ap, liftM)
import Control.Monad.IO.Class (MonadIO (..), liftIO)
import Control.Monad.Trans.Class (MonadTrans (..))
import Control.Monad.Trans.Resource (MonadResource (..), allocate)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import System.IO
import Fiber
import qualified Yarn
type SourceID = Text
data Source m a = Init (Source m a) (Source m a) SourceID
| HaveOutput (Source m a) Fiber
| NeedIO (m (Source m a))
| Finishing (Source m a) SourceID
| Done a
instance Monad m => Functor (Source m) where
fmap = liftM
instance Monad m => Applicative (Source m) where
pure = return
(<*>) = ap
instance Monad m => Monad (Source m) where
return = Done
Init src1 src2 sid >>= f = Init (src1 >>= f) (src2 >>= f) sid
HaveOutput src fib >>= f = HaveOutput (src >>= f) fib
NeedIO msrc >>= f = NeedIO ((>>= f) `liftM` msrc)
Finishing src sid >>= f = Finishing (src >>= f) sid
Done x >>= f = f x
instance MonadTrans Source where
lift = NeedIO . (Done `liftM`)
instance MonadIO m => MonadIO (Source m) where
liftIO = lift . liftIO
session :: Monad m => SourceID -> Source m () -> Source m ()
session sid src = Init src (Done ()) sid >> Finishing (Done ()) sid
yield :: Fiber -> Source m ()
yield = HaveOutput (Done ())
dedup :: MonadIO m => Source m a -> Source m a
dedup = go
where
go (Init s1 s2 sid) = NeedIO $ do
ls <- liftIO $ T.lines <$> T.readFile "known_sources.list"
return $ if sid `elem` ls
then go s2
else Init (go s1) (error "impossible case") sid
go (HaveOutput src o) = HaveOutput (go src) o
go (NeedIO a) = NeedIO $ go `liftM` a
go (Finishing src sid) = NeedIO $ do
liftIO $ withFile "known_sources.list" AppendMode $ \h ->
T.hPutStrLn h sid
return $ Finishing (go src) sid
go src@(Done _) = src
data Sink m = NeedInput (Fiber -> m (Sink m))
| DoIO (m (Sink m))
| Closed
sinkFile :: MonadResource m => FilePath -> Sink m
sinkFile fp = DoIO $ do
(relKey, y) <- allocate (Yarn.openFile fp Yarn.ReadWriteMode) Yarn.close
return $ go relKey y
where
go relKey y = NeedInput $ \fib -> do
liftIO $ Yarn.insert fib y
return $ go relKey y
sinkYarn :: MonadIO m => Yarn.Yarn -> Sink m
sinkYarn y = self
where
self = NeedInput $ \fib -> do
liftIO $ Yarn.insert fib y
return self
spin :: Monad m => Source m a -> Sink m -> m ()
spin = go []
where
go stk (Init s _ sid) sink = go (sid : stk) s sink
go [] (Finishing _ _) _ = fail "nothing to pop"
go (sid:stk) (Finishing s sid') sink
| sid /= sid' = fail "failed to pop"
| otherwise = go stk s sink
go _ (Done _) _ = return ()
go stk (NeedIO a) sink = do
src <- a
go stk src sink
go stk src@(HaveOutput src' fib) sink = case sink of
Closed -> return ()
DoIO a -> do
sink' <- a
go stk src sink'
NeedInput put -> do
sink' <- put fib
go stk src' sink'
|
yuttie/fibers
|
Spin.hs
|
Haskell
|
bsd-3-clause
| 3,531
|
-- Copyright (c) 2015 Eric McCorkle. All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions
-- are met:
--
-- 1. Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
--
-- 2. Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
--
-- 3. Neither the name of the author nor the names of any contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS''
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
-- TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
-- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS
-- OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
-- USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
-- OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
-- SUCH DAMAGE.
{-# OPTIONS_GHC -Wall -Werror #-}
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}
-- | This module defines a class for things that can be alpha-renamed.
module IR.Common.Rename.Class(
Rename(..)
) where
import Data.Array.IArray(IArray, Ix)
import qualified Data.Array.IArray as IArray
-- | Class of things that can be alpha-renamed.
class Rename id syntax where
-- | Rename all ids in the given syntax construct.
rename :: (id -> id)
-- ^ A function which renames ids.
-> syntax
-- ^ The syntax construct to rename.
-> syntax
-- ^ The input, with the renaming function applied to all
-- ids.
instance (Rename id syntax) => Rename id (Maybe syntax) where
rename f (Just t) = Just (rename f t)
rename _ Nothing = Nothing
instance (Rename id syntax) => Rename id [syntax] where
rename f = map (rename f)
instance (Rename id syntax, Ix idx, IArray arr syntax) =>
Rename id (arr idx syntax) where
rename f = IArray.amap (rename f)
|
emc2/iridium
|
src/IR/Common/Rename/Class.hs
|
Haskell
|
bsd-3-clause
| 2,588
|
fibs :: [Integer]
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
main :: IO ()
main = print $ fst $ head $ dropWhile not1000 $ zip [0..] fibs
where not1000 (_,x) = (length $ show x) /= 1000
|
stulli/projectEuler
|
eu25.hs
|
Haskell
|
bsd-3-clause
| 192
|
module RefacWhereLet(whereToLet) where
import PrettyPrint
import PosSyntax
import AbstractIO
import Maybe
import TypedIds
import UniqueNames hiding (srcLoc)
import PNT
import TiPNT
import List
import RefacUtils hiding (getParams)
import PFE0 (findFile)
import MUtils (( # ))
import RefacLocUtils
import System
import IO
{- This refactoring converts a where into a let. Could potentially narrow the scrope of those involved bindings.
Copyright : (c) Christopher Brown 2008
Maintainer : cmb21@kent.ac.uk
Stability : provisional
Portability : portable
-}
whereToLet args
= do let fileName = ghead "filename" args
--fileName'= moduleName fileName
--modName = Module fileName'
row = read (args!!1)::Int
col = read (args!!2)::Int
modName <-fileNameToModName fileName
(inscps, exps, mod, tokList)<-parseSourceFile fileName
let pnt = locToPNT fileName (row, col) mod
if not (checkInFun pnt mod)
then error "Please select a definition within a where clause!"
else do
if (pnt /= defaultPNT)
then do
((_,m), (newToks, newMod))<-applyRefac (doWhereToLet pnt)
(Just (inscps, exps, mod, tokList)) fileName
writeRefactoredFiles False [((fileName,m), (newToks,newMod))]
AbstractIO.putStrLn "Completed.\n"
else error "\nInvalid cursor position!"
doWhereToLet pnt (_,_,t)
= do
mod <- convertToWhere pnt t
return mod
convertToWhere pnt t
= applyTP (full_tdTP (idTP `adhocTP` conInMatch
`adhocTP` conInPat
`adhocTP` conInAlt
)) t
where
conInMatch (match@(HsMatch loc name pats (HsBody e) ds)::HsMatchP)
| canBeConverted ds pnt
= do
let decl = definingDecls [pNTtoPN pnt] ds True True
let updateRHS = (Exp (HsLet decl e))
ds' <- rmDecl (pNTtoPN pnt) True ds
-- we need to check that nothing else in the where
-- clause depends on this entity...
allDecs <- mapM hsFreeAndDeclaredPNs ds'
if (declToPName2 $ ghead "conInMatch" decl) `elem` (concat (map fst allDecs))
then error "Entity cannot be converted as another declaration in the where clause depends on it!"
else do e' <- update e updateRHS e
return (HsMatch loc name pats (HsBody e') ds')
conInMatch (match@(HsMatch loc name pats g@(HsGuard e) ds)::HsMatchP)
| canBeConverted ds pnt
= do let decl = definingDecls [pNTtoPN pnt] ds True True
let updateRHS = (HsBody (Exp (HsLet decl (rmGuard g))))
ds' <- rmDecl (pNTtoPN pnt) True ds
allDecs <- mapM hsFreeAndDeclaredPNs ds'
if (declToPName2 $ ghead "conInMatch Guard" decl) `elem` (concat (map fst allDecs))
then error "Entity cannot be converted as another declaration in the where clause depends on it!"
else do e' <- update g updateRHS g
return (HsMatch loc name pats e' ds')
conInMatch x = return x
conInPat (pat@(Dec (HsPatBind loc p (HsBody e) ds))::HsDeclP)
| canBeConverted ds pnt
= do
let decl = definingDecls [pNTtoPN pnt] ds True True
let updateRHS = (Exp (HsLet decl e))
ds' <- rmDecl (pNTtoPN pnt) True ds
allDecs <- mapM hsFreeAndDeclaredPNs ds'
if (declToPName2 $ ghead "conInPat" decl) `elem` (concat (map fst allDecs))
then error "Entity cannot be converted as another declaration in the where clause depends on it!"
else do e' <- update e updateRHS e
return (Dec (HsPatBind loc p (HsBody e') ds'))
conInPat (pat@(Dec (HsPatBind loc p g@(HsGuard e) ds))::HsDeclP)
| canBeConverted ds pnt
= do let decl = definingDecls [pNTtoPN pnt] ds True True
let updateRHS = (HsBody (Exp (HsLet decl (rmGuard g))))
ds' <- rmDecl (pNTtoPN pnt) True ds
allDecs <- mapM hsFreeAndDeclaredPNs ds'
if (declToPName2 $ ghead "conInPat" decl) `elem` (concat (map fst allDecs))
then error "Entity cannot be converted as another declaration in the where clause depends on it!"
else do e' <- update g updateRHS g
return (Dec (HsPatBind loc p e' ds'))
conInPat x = return x
conInAlt (alt@(HsAlt loc p (HsBody e) ds)::HsAltP)
| canBeConverted ds pnt
= do let decl = definingDecls [pNTtoPN pnt] ds True True
let updateRHS = (Exp (HsLet decl e))
ds' <- rmDecl (pNTtoPN pnt) True ds
e' <- update e updateRHS e
return (HsAlt loc p (HsBody e') ds')
conInAlt (alt@(HsAlt loc p g@(HsGuard e) ds)::HsAltP)
| canBeConverted ds pnt
= do let decl = definingDecls [pNTtoPN pnt] ds True True
let updateRHS = (HsBody (Exp (HsLet decl (rmGuard g))))
ds' <- rmDecl (pNTtoPN pnt) True ds
e' <- updateGuardAlt g updateRHS g
return (HsAlt loc p e' ds')
conInAlt x = return x
updateGuardAlt oldRhs newRhs t
= applyTP (once_tdTP (failTP `adhocTP` inRhs)) t
where
inRhs (r::RhsP)
| r == oldRhs && srcLocs r == srcLocs oldRhs
= do (newRhs',_) <- updateToks oldRhs newRhs prettyprintGuardsAlt
return newRhs'
inRhs r = mzero
rmGuard ((HsGuard gs)::RhsP)
= let (_,e1,e2)=glast "guardToIfThenElse" gs
in if ((pNtoName.expToPN) e1)=="otherwise"
then (foldl mkIfThenElse e2 (tail(reverse gs)))
else (foldl mkIfThenElse defaultElse (reverse gs))
mkIfThenElse e (_,e1, e2)=(Exp (HsIf e1 e2 e))
defaultElse=(Exp (HsApp (Exp (HsId (HsVar (PNT (PN (UnQual "error") (G (PlainModule "Prelude") "error"
(N (Just loc0)))) Value (N (Just loc0)))))) (Exp (HsLit loc0 (HsString "UnMatched Pattern")))))
canBeConverted :: [HsDeclP] -> PNT -> Bool
canBeConverted ds pnt
= pnt `elem` map declToPNT ds
checkInFun :: Term t => PNT -> t -> Bool
checkInFun pnt t
= checkInMatch pnt t || checkInPat pnt t || checkInAlt pnt t
where
checkInAlt pnt t
= fromMaybe (False)
(applyTU (once_tdTU (failTU `adhocTU` inAlt)) t)
checkInPat pnt t
= fromMaybe (False)
(applyTU (once_tdTU (failTU `adhocTU` inPat)) t)
checkInMatch pnt t
= fromMaybe (False)
(applyTU (once_tdTU (failTU `adhocTU` inMatch)) t)
inAlt (alt@(HsAlt loc p rhs ds)::HsAltP)
| findPNT pnt ds = Just True
inAlt _ = Nothing
--The selected sub-expression is in the rhs of a match
inMatch (match@(HsMatch loc1 _ pats rhs ds)::HsMatchP)
| findPNT pnt ds
= Just True
inMatch _ = Nothing
--The selected sub-expression is in the rhs of a pattern-binding
inPat (pat@(Dec (HsPatBind loc1 ps rhs ds))::HsDeclP)
| findPNT pnt ds
= Just True
inPat _ = Nothing
|
forste/haReFork
|
refactorer/RefacWhereLet.hs
|
Haskell
|
bsd-3-clause
| 7,907
|
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
module Iso where
import Data.Functor.Contravariant (Contravariant, (>$<), contramap)
import Person
import Control.Monad.Reader
import Data.Profunctor
import Data.Functor.Identity
import Getter (view)
-- | Exchange an ContraExchange types which are useful to define Isos
-- It like the container for two isomorphic functions
data Exchange a b s t = Exchange (s -> a) (b -> t)
data ContraExchange a b t s = ContraExchange (s -> a) (b -> t)
instance Functor (Exchange a b s) where
fmap f (Exchange sa bt) = Exchange sa (f . bt)
instance Contravariant (ContraExchange a b t) where
contramap f (ContraExchange sa bt) = ContraExchange (sa . f) bt
fromContraEx :: ContraExchange a b t s -> Exchange a b s t
fromContraEx (ContraExchange sa bt) = Exchange sa bt
toContraEx :: Exchange a b s t -> ContraExchange a b t s
toContraEx (Exchange sa bt) = ContraExchange sa bt
-- | Profuctor (Exchange a b)
instance Profunctor (Exchange a b) where
lmap f ex = fromContraEx $ f >$< toContraEx ex
rmap f ex = f <$> ex
dimap f g ex = fromContraEx $ f >$< toContraEx (g <$> ex)
-- | Iso Type
type Iso s t a b =
forall p f . (Profunctor p, Functor f) => p a (f b) -> p s (f t)
type AnIso s t a b =
(Exchange a b) a (Identity b) -> (Exchange a b) s (Identity t)
iso :: (s -> a) -> (b -> t) -> Iso s t a b
iso sa bt = dimap sa (fmap bt)
withIso :: AnIso s t a b -> ((s -> a) -> (b -> t) -> r) -> r
withIso ai k =
let Exchange sa bt = ai $ Exchange id Identity
in k sa (runIdentity . bt)
from :: AnIso s t a b -> Iso b a t s
from ai = withIso ai $ \sa bt -> iso bt sa
-- | Value examples
type HTuple = ( String
, Int
, Gender
, Ethnicity
, Maybe String
, Maybe SuperPower)
makeHuman :: HTuple -> Human
makeHuman (name', age', gender', eth', heroNm', supPower') =
Human name' age' gender' eth' heroNm' supPower'
unmakeHuman :: Human -> HTuple
unmakeHuman Human{..} = (name, age, gender, ethnicity, heroName, superPower)
unmakeHumanIso :: Iso Human Human HTuple HTuple
unmakeHumanIso = iso unmakeHuman makeHuman
makeHumanIso :: Iso HTuple HTuple Human Human
makeHumanIso = from unmakeHumanIso
-- An Iso is a Lens and thus a Getter
humanTuple :: IO HTuple
humanTuple = (runReaderT $ view unmakeHumanIso) human2
aHuman :: IO Human
aHuman = humanTuple >>= runReaderT (view makeHumanIso)
|
sebashack/LensPlayground
|
src/Iso.hs
|
Haskell
|
bsd-3-clause
| 2,440
|
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, TupleSections, ScopedTypeVariables #-}
{-|
A module defining an interface for type attribution, the process by which
nodes in an AST are assigned constrained types.
-}
module Language.K3.TypeSystem.Monad.Iface.TypeAttribution
( TypeVarAttrI(..)
) where
import Language.K3.Core.Common
import Language.K3.TypeSystem.Data
-- |The typeclass defining the interface of monads supporting type variable
-- attribution. This allows UIDs to be matched with the type variables which
-- will represent them. The relevant constraints are assumed to be available
-- in context.
class (Monad m) => TypeVarAttrI m where
attributeVar :: UID -> AnyTVar -> m ()
attributeConstraints :: ConstraintSet -> m ()
|
DaMSL/K3
|
src/Language/K3/TypeSystem/Monad/Iface/TypeAttribution.hs
|
Haskell
|
apache-2.0
| 761
|
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
module Kalium.Nucleus.Vector.Program where
import Kalium.Prelude
import Kalium.Util
import Control.Monad.Rename
data NameSpecial
= OpAdd
| OpSubtract
| OpMultiply
| OpDivide
| OpDiv
| OpMod
| OpLess
| OpMore
| OpLessEquals
| OpMoreEquals
| OpEquals
| OpNotEquals
| OpAnd
| OpOr
| OpNot
| OpTrue
| OpFalse
| OpRange
| OpElem
| OpShow
| OpNegate
| OpIf
| OpFold
| OpFoldTainted
| OpFlipMapTaintedIgnore
| OpMapTaintedIgnore
| OpProduct
| OpSum
| OpAnd'
| OpOr'
| OpPrintLn
| OpReadLn
| OpPutLn
| OpPut
| OpChr
| OpChrOrd
| OpGetLn
| OpGetChar
| OpId
| OpUnit
| OpPair
| OpFst
| OpSnd
| OpSwap
| OpNil
| OpCons
| OpSingleton
| OpIx
| OpIxSet
| OpLength
| OpTaint
| OpBind
| OpBindIgnore
| OpFmap
| OpFmapIgnore
| OpIgnore
| OpWhen
| OpConcat
| OpTake
| OpReplicate
| OpRepeat
| OpIntToDouble
| OpUndefined
| OpMain
| OpTypeInteger
| OpTypeDouble
| OpTypeBoolean
| OpTypeChar
| OpTypeUnit
| OpTypeList
| OpTypePair
| OpTypeFunction
| OpTypeTaint
deriving (Eq, Ord)
data Name = NameSpecial NameSpecial
| NameGen Integer
deriving (Eq, Ord)
alias :: (MonadNameGen m) => EndoKleisli' m Name
alias (NameGen m) = NameGen <$> rename m
alias _ = NameGen <$> mkname Nothing
data Type
= TypeBeta Type Type
| TypeAccess Name
deriving (Eq, Ord)
pattern TypeInteger = TypeAccess (NameSpecial OpTypeInteger)
pattern TypeDouble = TypeAccess (NameSpecial OpTypeDouble)
pattern TypeBoolean = TypeAccess (NameSpecial OpTypeBoolean)
pattern TypeChar = TypeAccess (NameSpecial OpTypeChar)
pattern TypeUnit = TypeAccess (NameSpecial OpTypeUnit)
pattern TypeList = TypeAccess (NameSpecial OpTypeList)
pattern TypePair = TypeAccess (NameSpecial OpTypePair)
pattern TypeFunction= TypeAccess (NameSpecial OpTypeFunction)
pattern TypeTaint = TypeAccess (NameSpecial OpTypeTaint)
data Literal
= LitInteger Integer
| LitDouble Rational
| LitChar Char
deriving (Eq)
data Program
= Program
{ _programFuncs :: Map Name Func
} deriving (Eq)
data Func
= Func
{ _funcType :: Type
, _funcExpression :: Expression
} deriving (Eq)
data Expression' pext ext
= Access Name
| Primary Literal
| Lambda (Pattern' pext) (Expression' pext ext)
| Beta (Expression' pext ext) (Expression' pext ext)
| Ext ext
deriving (Eq)
type Expression = Expression' Void Void
data Pattern' pext
= PTuple (Pattern' pext) (Pattern' pext)
| PAccess Name Type
| PWildCard
| PUnit
| PExt pext
deriving (Eq)
type Pattern = Pattern' Void
pattern OpAccess op = Access (NameSpecial op)
pattern LitUnit = OpAccess OpUnit
pattern App1 op a = op `Beta` a
pattern App2 op a1 a2 = op `Beta` a1 `Beta` a2
pattern App3 op a1 a2 a3 = op `Beta` a1 `Beta` a2 `Beta` a3
pattern AppOp1 op a = App1 (OpAccess op) a
pattern AppOp2 op a1 a2 = App2 (OpAccess op) a1 a2
pattern AppOp3 op a1 a2 a3 = App3 (OpAccess op) a1 a2 a3
pattern Lambda2 p1 p2 a = Lambda p1 (Lambda p2 a)
pattern Into p x a = Beta (Lambda p a) x
pattern Eta p x a = Lambda p (Beta x a)
pattern Ignore a = AppOp1 OpIgnore a
pattern Taint a = AppOp1 OpTaint a
pattern Bind a1 a2 = AppOp2 OpBind a1 a2
pattern Follow p x a = Bind x (Lambda p a)
lambda :: [Pattern' pext] -> Expression' pext ext -> Expression' pext ext
lambda = flip (foldr Lambda)
unlambda :: Expression' pext ext -> ([Pattern' pext], Expression' pext ext)
unlambda = \case
Lambda p a -> let (ps, b) = unlambda a in (p:ps, b)
e -> ([], e)
pattern TypeApp1 t t1 = t `TypeBeta` t1
pattern TypeApp2 t t1 t2 = t `TypeBeta` t1 `TypeBeta` t2
tyfun :: [Type] -> Type -> Type
tyfun = flip (foldr (TypeApp2 TypeFunction))
untyfun :: Type -> ([Type], Type)
untyfun = \case
TypeApp2 TypeFunction tyArg tyRes ->
let (tyArgs, tyRes') = untyfun tyRes
in (tyArg:tyArgs, tyRes')
ty -> ([], ty)
beta :: [Expression' pext ext] -> Expression' pext ext
beta = foldl1 Beta
unbeta :: Expression' pext ext -> [Expression' pext ext]
unbeta = reverse . go where
go = \case
Beta a b -> b : go a
e -> [e]
etaExpand
:: (MonadNameGen m)
=> [Type] -> EndoKleisli' m (Expression' pext ext)
etaExpand tys e = do
(unzip -> (exps, pats)) <- forM tys $ \ty -> do
name <- NameGen <$> mkname Nothing
return (Access name, PAccess name ty)
return $ lambda pats $ beta (e:exps)
typeDrivenUnlambda
:: (MonadNameGen m)
=> Type -> Expression -> m ( ([Pattern],[Type]) , (Expression,Type) )
typeDrivenUnlambda ty a =
let (tys, ty') = untyfun ty
( ps, a') = unlambda a
tysLength = length tys
psLength = length ps
in if | tysLength < psLength -> do
error "lambda-abstraction with non-function type"
| tysLength > psLength -> do
let tys' = drop psLength tys
b <- etaExpand tys' a -- TODO: or is it a'?
typeDrivenUnlambda ty b
| otherwise -> return ( (ps,tys) , (a',ty') )
makeLenses ''Func
makeLenses ''Program
|
rscprof/kalium
|
src/Kalium/Nucleus/Vector/Program.hs
|
Haskell
|
bsd-3-clause
| 5,397
|
{-# LANGUAGE Haskell98, BangPatterns #-}
{-# LINE 1 "Data/ByteString/Lazy/Search.hs" #-}
-- |
-- Module : Data.ByteString.Lazy.Search
-- Copyright : Daniel Fischer
-- Chris Kuklewicz
-- Licence : BSD3
-- Maintainer : Daniel Fischer <daniel.is.fischer@googlemail.com>
-- Stability : Provisional
-- Portability : non-portable (BangPatterns)
--
-- Fast overlapping Boyer-Moore search of lazy
-- 'L.ByteString' values. Breaking, splitting and replacing
-- using the Boyer-Moore algorithm.
--
-- Descriptions of the algorithm can be found at
-- <http://www-igm.univ-mlv.fr/~lecroq/string/node14.html#SECTION00140>
-- and
-- <http://en.wikipedia.org/wiki/Boyer-Moore_string_search_algorithm>
--
-- Original authors: Daniel Fischer (daniel.is.fischer at googlemail.com) and
-- Chris Kuklewicz (haskell at list.mightyreason.com).
module Data.ByteString.Lazy.Search( -- * Overview
-- $overview
-- ** Performance
-- $performance
-- ** Caution
-- $caution
-- ** Complexity
-- $complexity
-- ** Partial application
-- $partial
-- ** Integer overflow
-- $overflow
-- * Finding substrings
indices
, nonOverlappingIndices
-- * Breaking on substrings
, breakOn
, breakAfter
, breakFindAfter
-- * Replacing
, replace
-- * Splitting
, split
, splitKeepEnd
, splitKeepFront
-- * Convenience
, strictify
) where
import qualified Data.ByteString.Lazy.Search.Internal.BoyerMoore as BM
import Data.ByteString.Search.Substitution
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import Data.Int (Int64)
-- $overview
--
-- This module provides functions related to searching a substring within
-- a string, using the Boyer-Moore algorithm with minor modifications
-- to improve the overall performance and ameliorate the worst case
-- performance degradation of the original Boyer-Moore algorithm for
-- periodic patterns.
--
-- Efficiency demands that the pattern be a strict 'S.ByteString',
-- to work with a lazy pattern, convert it to a strict 'S.ByteString'
-- first via 'strictify' (provided it is not too long).
-- If support for long lazy patterns is needed, mail a feature-request.
--
-- When searching a pattern in a UTF-8-encoded 'S.ByteString', be aware that
-- these functions work on bytes, not characters, so the indices are
-- byte-offsets, not character offsets.
-- $performance
--
-- In general, the Boyer-Moore algorithm is the most efficient method to
-- search for a pattern inside a string. The advantage over other algorithms
-- (e.g. Naïve, Knuth-Morris-Pratt, Horspool, Sunday) can be made
-- arbitrarily large for specially selected patterns and targets, but
-- usually, it's a factor of 2–3 versus Knuth-Morris-Pratt and of
-- 6–10 versus the naïve algorithm. The Horspool and Sunday
-- algorithms, which are simplified variants of the Boyer-Moore algorithm,
-- typically have performance between Boyer-Moore and Knuth-Morris-Pratt,
-- mostly closer to Boyer-Moore. The advantage of the Boyer-moore variants
-- over other algorithms generally becomes larger for longer patterns. For
-- very short patterns (or patterns with a very short period), other
-- algorithms, e.g. "Data.ByteString.Lazy.Search.DFA" can be faster (my
-- tests suggest that \"very short\" means two, maybe three bytes).
--
-- In general, searching in a strict 'S.ByteString' is slightly faster
-- than searching in a lazy 'L.ByteString', but for long targets the
-- smaller memory footprint of lazy 'L.ByteString's can make searching
-- those (sometimes much) faster. On the other hand, there are cases
-- where searching in a strict target is much faster, even for long targets.
--
-- On 32-bit systems, 'Int'-arithmetic is much faster than 'Int64'-arithmetic,
-- so when there are many matches, that can make a significant difference.
--
-- Also, the modification to ameliorate the case of periodic patterns
-- is defeated by chunk-boundaries, so long patterns with a short period
-- and many matches exhibit poor behaviour (consider using @indices@ from
-- "Data.ByteString.Lazy.Search.DFA" or "Data.ByteString.Lazy.Search.KMP"
-- in those cases, the former for medium-length patterns, the latter for
-- long patterns; none of the functions except 'indices' suffer from
-- this problem, though).
-- $caution
--
-- When working with a lazy target string, the relation between the pattern
-- length and the chunk size can play a big rôle.
-- Crossing chunk boundaries is relatively expensive, so when that becomes
-- a frequent occurrence, as may happen when the pattern length is close
-- to or larger than the chunk size, performance is likely to degrade.
-- If it is needed, steps can be taken to ameliorate that effect, but unless
-- entirely separate functions are introduced, that would hurt the
-- performance for the more common case of patterns much shorter than
-- the default chunk size.
-- $complexity
--
-- Preprocessing the pattern is /O/(@patternLength@ + σ) in time and
-- space (σ is the alphabet size, 256 here) for all functions.
-- The time complexity of the searching phase for 'indices'
-- is /O/(@targetLength@ \/ @patternLength@) in the best case.
-- For non-periodic patterns, the worst case complexity is
-- /O/(@targetLength@), but for periodic patterns, the worst case complexity
-- is /O/(@targetLength@ * @patternLength@) for the original Boyer-Moore
-- algorithm.
--
-- The searching functions in this module contain a modification which
-- drastically improves the performance for periodic patterns, although
-- less for lazy targets than for strict ones.
-- If I'm not mistaken, the worst case complexity for periodic patterns
-- is /O/(@targetLength@ * (1 + @patternLength@ \/ @chunkSize@)).
--
-- The other functions don't have to deal with possible overlapping
-- patterns, hence the worst case complexity for the processing phase
-- is /O/(@targetLength@) (respectively /O/(@firstIndex + patternLength@)
-- for the breaking functions if the pattern occurs).
-- $partial
--
-- All functions can usefully be partially applied. Given only a pattern,
-- the pattern is preprocessed only once, allowing efficient re-use.
-- $overflow
--
-- The current code uses @Int@ to keep track of the locations in the
-- target string. If the length of the pattern plus the length of any
-- strict chunk of the target string is greater or equal to
-- @'maxBound' :: 'Int'@ then this will overflow causing an error. We try
-- to detect this and call 'error' before a segfault occurs.
------------------------------------------------------------------------------
-- Exported Functions --
------------------------------------------------------------------------------
-- | @'indices'@ finds the starting indices of all possibly overlapping
-- occurrences of the pattern in the target string.
-- If the pattern is empty, the result is @[0 .. 'length' target]@.
{-# INLINE indices #-}
indices :: S.ByteString -- ^ Strict pattern to find
-> L.ByteString -- ^ Lazy string to search
-> [Int64] -- ^ Offsets of matches
indices = BM.matchSL
-- | @'nonOverlappingIndices'@ finds the starting indices of all
-- non-overlapping occurrences of the pattern in the target string.
-- It is more efficient than removing indices from the list produced
-- by 'indices'.
{-# INLINE nonOverlappingIndices #-}
nonOverlappingIndices :: S.ByteString -- ^ Strict pattern to find
-> L.ByteString -- ^ Lazy string to search
-> [Int64] -- ^ Offsets of matches
nonOverlappingIndices = BM.matchNOL
-- | @'breakOn' pattern target@ splits @target@ at the first occurrence
-- of @pattern@. If the pattern does not occur in the target, the
-- second component of the result is empty, otherwise it starts with
-- @pattern@. If the pattern is empty, the first component is empty.
-- For a non-empty pattern, the first component is generated lazily,
-- thus the first parts of it can be available before the pattern has
-- been found or determined to be absent.
--
-- @
-- 'uncurry' 'L.append' . 'breakOn' pattern = 'id'
-- @
{-# INLINE breakOn #-}
breakOn :: S.ByteString -- ^ Strict pattern to search for
-> L.ByteString -- ^ Lazy string to search in
-> (L.ByteString, L.ByteString)
-- ^ Head and tail of string broken at substring
breakOn = BM.breakSubstringL
-- | @'breakAfter' pattern target@ splits @target@ behind the first occurrence
-- of @pattern@. An empty second component means that either the pattern
-- does not occur in the target or the first occurrence of pattern is at
-- the very end of target. If you need to discriminate between those cases,
-- use breakFindAfter.
-- If the pattern is empty, the first component is empty.
-- For a non-empty pattern, the first component is generated lazily,
-- thus the first parts of it can be available before the pattern has
-- been found or determined to be absent.
--
-- @
-- 'uncurry' 'L.append' . 'breakAfter' pattern = 'id'
-- @
{-# INLINE breakAfter #-}
breakAfter :: S.ByteString -- ^ Strict pattern to search for
-> L.ByteString -- ^ Lazy string to search in
-> (L.ByteString, L.ByteString)
-- ^ Head and tail of string broken after substring
breakAfter = BM.breakAfterL
-- | @'breakFindAfter'@ does the same as 'breakAfter' but additionally indicates
-- whether the pattern is present in the target.
--
-- @
-- 'fst' . 'breakFindAfter' pat = 'breakAfter' pat
-- @
{-# INLINE breakFindAfter #-}
breakFindAfter :: S.ByteString -- ^ Strict pattern to search for
-> L.ByteString -- ^ Lazy string to search in
-> ((L.ByteString, L.ByteString), Bool)
-- ^ Head and tail of string broken after substring
-- and presence of pattern
breakFindAfter = BM.breakFindAfterL
-- | @'replace' pat sub text@ replaces all (non-overlapping) occurrences of
-- @pat@ in @text@ with @sub@. If occurrences of @pat@ overlap, the first
-- occurrence that does not overlap with a replaced previous occurrence
-- is substituted. Occurrences of @pat@ arising from a substitution
-- will not be substituted. For example:
--
-- @
-- 'replace' \"ana\" \"olog\" \"banana\" = \"bologna\"
-- 'replace' \"ana\" \"o\" \"bananana\" = \"bono\"
-- 'replace' \"aab\" \"abaa\" \"aaabb\" = \"aabaab\"
-- @
--
-- The result is a lazy 'L.ByteString',
-- which is lazily produced, without copying.
-- Equality of pattern and substitution is not checked, but
--
-- @
-- 'replace' pat pat text == text
-- @
--
-- holds (the internal structure is generally different).
-- If the pattern is empty but not the substitution, the result
-- is equivalent to (were they 'String's) @cycle sub@.
--
-- For non-empty @pat@ and @sub@ a lazy 'L.ByteString',
--
-- @
-- 'L.concat' . 'Data.List.intersperse' sub . 'split' pat = 'replace' pat sub
-- @
--
-- and analogous relations hold for other types of @sub@.
{-# INLINE replace #-}
replace :: Substitution rep
=> S.ByteString -- ^ Strict pattern to replace
-> rep -- ^ Replacement string
-> L.ByteString -- ^ Lazy string to modify
-> L.ByteString -- ^ Lazy result
replace = BM.replaceAllL
-- | @'split' pattern target@ splits @target@ at each (non-overlapping)
-- occurrence of @pattern@, removing @pattern@. If @pattern@ is empty,
-- the result is an infinite list of empty 'L.ByteString's, if @target@
-- is empty but not @pattern@, the result is an empty list, otherwise
-- the following relations hold (where @patL@ is the lazy 'L.ByteString'
-- corresponding to @pat@):
--
-- @
-- 'L.concat' . 'Data.List.intersperse' patL . 'split' pat = 'id',
-- 'length' ('split' pattern target) ==
-- 'length' ('nonOverlappingIndices' pattern target) + 1,
-- @
--
-- no fragment in the result contains an occurrence of @pattern@.
{-# INLINE split #-}
split :: S.ByteString -- ^ Strict pattern to split on
-> L.ByteString -- ^ Lazy string to split
-> [L.ByteString] -- ^ Fragments of string
split = BM.splitDropL
-- | @'splitKeepEnd' pattern target@ splits @target@ after each (non-overlapping)
-- occurrence of @pattern@. If @pattern@ is empty, the result is an
-- infinite list of empty 'L.ByteString's, otherwise the following
-- relations hold:
--
-- @
-- 'L.concat' . 'splitKeepEnd' pattern = 'id',
-- @
--
-- all fragments in the result except possibly the last end with
-- @pattern@, no fragment contains more than one occurrence of @pattern@.
{-# INLINE splitKeepEnd #-}
splitKeepEnd :: S.ByteString -- ^ Strict pattern to split on
-> L.ByteString -- ^ Lazy string to split
-> [L.ByteString] -- ^ Fragments of string
splitKeepEnd = BM.splitKeepEndL
-- | @'splitKeepFront'@ is like 'splitKeepEnd', except that @target@ is split
-- before each occurrence of @pattern@ and hence all fragments
-- with the possible exception of the first begin with @pattern@.
-- No fragment contains more than one non-overlapping occurrence
-- of @pattern@.
{-# INLINE splitKeepFront #-}
splitKeepFront :: S.ByteString -- ^ Strict pattern to split on
-> L.ByteString -- ^ Lazy string to split
-> [L.ByteString] -- ^ Fragments of string
splitKeepFront = BM.splitKeepFrontL
-- | @'strictify'@ converts a lazy 'L.ByteString' to a strict 'S.ByteString'
-- to make it a suitable pattern.
strictify :: L.ByteString -> S.ByteString
strictify = S.concat . L.toChunks
|
phischu/fragnix
|
tests/packages/scotty/Data.ByteString.Lazy.Search.hs
|
Haskell
|
bsd-3-clause
| 14,655
|
{-# LANGUAGE Haskell98, MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}
{-# LINE 1 "Control/Monad/Cont/Class.hs" #-}
{- |
Module : Control.Monad.Cont.Class
Copyright : (c) The University of Glasgow 2001,
(c) Jeff Newbern 2003-2007,
(c) Andriy Palamarchuk 2007
License : BSD-style (see the file LICENSE)
Maintainer : libraries@haskell.org
Stability : experimental
Portability : portable
[Computation type:] Computations which can be interrupted and resumed.
[Binding strategy:] Binding a function to a monadic value creates
a new continuation which uses the function as the continuation of the monadic
computation.
[Useful for:] Complex control structures, error handling,
and creating co-routines.
[Zero and plus:] None.
[Example type:] @'Cont' r a@
The Continuation monad represents computations in continuation-passing style
(CPS).
In continuation-passing style function result is not returned,
but instead is passed to another function,
received as a parameter (continuation).
Computations are built up from sequences
of nested continuations, terminated by a final continuation (often @id@)
which produces the final result.
Since continuations are functions which represent the future of a computation,
manipulation of the continuation functions can achieve complex manipulations
of the future of the computation,
such as interrupting a computation in the middle, aborting a portion
of a computation, restarting a computation, and interleaving execution of
computations.
The Continuation monad adapts CPS to the structure of a monad.
Before using the Continuation monad, be sure that you have
a firm understanding of continuation-passing style
and that continuations represent the best solution to your particular
design problem.
Many algorithms which require continuations in other languages do not require
them in Haskell, due to Haskell's lazy semantics.
Abuse of the Continuation monad can produce code that is impossible
to understand and maintain.
-}
module Control.Monad.Cont.Class (
MonadCont(..),
) where
import Control.Monad.Trans.Cont (ContT)
import qualified Control.Monad.Trans.Cont as ContT
import Control.Monad.Trans.Error as Error
import Control.Monad.Trans.Except as Except
import Control.Monad.Trans.Identity as Identity
import Control.Monad.Trans.List as List
import Control.Monad.Trans.Maybe as Maybe
import Control.Monad.Trans.Reader as Reader
import Control.Monad.Trans.RWS.Lazy as LazyRWS
import Control.Monad.Trans.RWS.Strict as StrictRWS
import Control.Monad.Trans.State.Lazy as LazyState
import Control.Monad.Trans.State.Strict as StrictState
import Control.Monad.Trans.Writer.Lazy as LazyWriter
import Control.Monad.Trans.Writer.Strict as StrictWriter
import Control.Monad
import Data.Monoid
class Monad m => MonadCont m where
{- | @callCC@ (call-with-current-continuation)
calls a function with the current continuation as its argument.
Provides an escape continuation mechanism for use with Continuation monads.
Escape continuations allow to abort the current computation and return
a value immediately.
They achieve a similar effect to 'Control.Monad.Error.throwError'
and 'Control.Monad.Error.catchError'
within an 'Control.Monad.Error.Error' monad.
Advantage of this function over calling @return@ is that it makes
the continuation explicit,
allowing more flexibility and better control
(see examples in "Control.Monad.Cont").
The standard idiom used with @callCC@ is to provide a lambda-expression
to name the continuation. Then calling the named continuation anywhere
within its scope will escape from the computation,
even if it is many layers deep within nested computations.
-}
callCC :: ((a -> m b) -> m a) -> m a
instance MonadCont (ContT r m) where
callCC = ContT.callCC
-- ---------------------------------------------------------------------------
-- Instances for other mtl transformers
instance (Error e, MonadCont m) => MonadCont (ErrorT e m) where
callCC = Error.liftCallCC callCC
instance MonadCont m => MonadCont (ExceptT e m) where
callCC = Except.liftCallCC callCC
instance MonadCont m => MonadCont (IdentityT m) where
callCC = Identity.liftCallCC callCC
instance MonadCont m => MonadCont (ListT m) where
callCC = List.liftCallCC callCC
instance MonadCont m => MonadCont (MaybeT m) where
callCC = Maybe.liftCallCC callCC
instance MonadCont m => MonadCont (ReaderT r m) where
callCC = Reader.liftCallCC callCC
instance (Monoid w, MonadCont m) => MonadCont (LazyRWS.RWST r w s m) where
callCC = LazyRWS.liftCallCC' callCC
instance (Monoid w, MonadCont m) => MonadCont (StrictRWS.RWST r w s m) where
callCC = StrictRWS.liftCallCC' callCC
instance MonadCont m => MonadCont (LazyState.StateT s m) where
callCC = LazyState.liftCallCC' callCC
instance MonadCont m => MonadCont (StrictState.StateT s m) where
callCC = StrictState.liftCallCC' callCC
instance (Monoid w, MonadCont m) => MonadCont (LazyWriter.WriterT w m) where
callCC = LazyWriter.liftCallCC callCC
instance (Monoid w, MonadCont m) => MonadCont (StrictWriter.WriterT w m) where
callCC = StrictWriter.liftCallCC callCC
|
phischu/fragnix
|
tests/packages/scotty/Control.Monad.Cont.Class.hs
|
Haskell
|
bsd-3-clause
| 5,256
|
{-#LANGUAGE RecordWildCards, ScopedTypeVariables, TypeFamilies#-}
module CV.Features (SURFParams, defaultSURFParams, mkSURFParams, getSURF
,moments,Moments,getSpatialMoment,getCentralMoment,getNormalizedCentralMoment) where
import CV.Image
import CV.Bindings.Types
import CV.Bindings.Features
import Foreign.Ptr
import Control.Monad
import Foreign.Storable
import Foreign.Marshal.Array
import Foreign.Marshal.Utils
import Utils.GeometryClass
import System.IO.Unsafe
-- TODO: Move this to some utility module
-- withMask :: Maybe (Image GrayScale D8) -> (Ptr C'CvArr -> IO α) -> IO α
-- withMask m f = case m of
-- Just m -> withImage m (f.castPtr)
-- Nothing -> f nullPtr
-- | Parameters for SURF feature extraction
newtype SURFParams = SP C'CvSURFParams deriving Show
mkSURFParams :: Double
-- ^ only features with keypoint.hessian
-- larger than that are extracted.
-- good default value is ~300-500 (can depend on the
-- average local contrast and sharpness of the image).
-- user can further filter out some features based on
-- their hessian values and other characteristics.
-> Int
-- ^ The number of octaves to be used for extraction.
-- With each next octave the feature size is doubled
-- (3 by default)
-> Int
-- ^ The number of layers within each octave (4 by default)
-> Bool
-- ^ If true, getSurf returns extended descriptors of 128 floats. Otherwise
-- returns 64 floats.
-> SURFParams
mkSURFParams a b c d = SP $ C'CvSURFParams (fromBool d)
(realToFrac a)
(fromIntegral b)
(fromIntegral c)
-- | Default parameters for getSURF
defaultSURFParams :: SURFParams
defaultSURFParams = mkSURFParams 400 3 4 False
-- | Extract Speeded Up Robust Features from an image.
getSURF :: SURFParams
-- ^ Method parameters. See `defaultSURFParams` and `mkSURFParams`
-> Image GrayScale D8
-- ^ Input GrayScale image
-> Maybe (Image GrayScale D8)
-- ^ Optional Binary mask image
-> [(C'CvSURFPoint,[Float])]
getSURF (SP params) image mask = unsafePerformIO $
withNewMemory $ \ptr_mem ->
withMask mask $ \ptr_mask ->
with nullPtr $ \ptr_ptr_keypoints ->
with nullPtr $ \ptr_ptr_descriptors ->
with params $ \ptr_params ->
withImage image $ \ptr_image -> do
ptr_keypoints' <- peek ptr_ptr_keypoints
c'wrapExtractSURF (castPtr ptr_image) ptr_mask ptr_ptr_keypoints
ptr_ptr_descriptors ptr_mem ptr_params 0
ptr_keypoints <- peek ptr_ptr_keypoints
ptr_descriptors <- peek ptr_ptr_descriptors
a <- cvSeqToList ptr_keypoints
b <- if c'CvSURFParams'extended params == 1
then do
es :: [FloatBlock128] <- cvSeqToList ptr_descriptors
return (map (\(FP128 e) -> e) es)
else do
es :: [FloatBlock64] <- cvSeqToList ptr_descriptors
return (map (\(FP64 e) -> e) es)
return (zip a b)
newtype FloatBlock64 = FP64 [Float] deriving (Show)
newtype FloatBlock128 = FP128 [Float] deriving (Show)
instance Storable FloatBlock64 where
sizeOf _ = sizeOf (undefined :: Float) * 64
alignment _ = 4
peek ptr = FP64 `fmap` peekArray 64 (castPtr ptr)
poke ptr (FP64 e) = pokeArray (castPtr ptr) e
instance Storable FloatBlock128 where
sizeOf _ = sizeOf (undefined :: Float) * 128
alignment _ = 4
peek ptr = FP128 `fmap` peekArray 128 (castPtr ptr)
poke ptr (FP128 e) = pokeArray (castPtr ptr) e
type Moments = C'CvMoments
moments :: Image GrayScale D32 -> Moments
moments img = unsafePerformIO $
withGenImage img $ \c_img ->
with (C'CvMoments 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) $ \res -> do
c'cvMoments c_img res 0
peek res
getSpatialMoment :: (Int,Int) -> Moments -> Double
getSpatialMoment (x,y) m = realToFrac $
unsafePerformIO $
with m $ \c_m ->
c'cvGetSpatialMoment c_m (fromIntegral x) (fromIntegral y)
getCentralMoment :: (Int,Int) -> Moments -> Double
getCentralMoment (x,y) m = realToFrac $
unsafePerformIO $
with m $ \c_m ->
c'cvGetCentralMoment c_m (fromIntegral x) (fromIntegral y)
getNormalizedCentralMoment :: (Int,Int) -> Moments -> Double
getNormalizedCentralMoment (x,y) m = realToFrac $
unsafePerformIO $
with m $ \c_m ->
c'cvGetNormalizedCentralMoment c_m (fromIntegral x) (fromIntegral y)
|
BeautifulDestinations/CV
|
CV/Features.hs
|
Haskell
|
bsd-3-clause
| 5,004
|
-- -----------------------------------------------------------------------------
--
-- (c) The University of Glasgow 1994-2004
--
-- -----------------------------------------------------------------------------
{-# OPTIONS_GHC -fno-warn-tabs #-}
-- The above warning supression flag is a temporary kludge.
-- While working on this module you are encouraged to remove it and
-- detab the module (please do the detabbing in a separate patch). See
-- http://ghc.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
-- for details
module SPARC.Regs (
-- registers
showReg,
virtualRegSqueeze,
realRegSqueeze,
classOfRealReg,
allRealRegs,
-- machine specific info
gReg, iReg, lReg, oReg, fReg,
fp, sp, g0, g1, g2, o0, o1, f0, f1, f6, f8, f22, f26, f27,
-- allocatable
allocatableRegs,
-- args
argRegs,
allArgRegs,
callClobberedRegs,
--
mkVirtualReg,
regDotColor
)
where
import CodeGen.Platform.SPARC
import Reg
import RegClass
import Size
import Unique
import Outputable
import FastTypes
import FastBool
{-
The SPARC has 64 registers of interest; 32 integer registers and 32
floating point registers. The mapping of STG registers to SPARC
machine registers is defined in StgRegs.h. We are, of course,
prepared for any eventuality.
The whole fp-register pairing thing on sparcs is a huge nuisance. See
includes/stg/MachRegs.h for a description of what's going on
here.
-}
-- | Get the standard name for the register with this number.
showReg :: RegNo -> String
showReg n
| n >= 0 && n < 8 = "%g" ++ show n
| n >= 8 && n < 16 = "%o" ++ show (n-8)
| n >= 16 && n < 24 = "%l" ++ show (n-16)
| n >= 24 && n < 32 = "%i" ++ show (n-24)
| n >= 32 && n < 64 = "%f" ++ show (n-32)
| otherwise = panic "SPARC.Regs.showReg: unknown sparc register"
-- Get the register class of a certain real reg
classOfRealReg :: RealReg -> RegClass
classOfRealReg reg
= case reg of
RealRegSingle i
| i < 32 -> RcInteger
| otherwise -> RcFloat
RealRegPair{} -> RcDouble
-- | regSqueeze_class reg
-- Calculuate the maximum number of register colors that could be
-- denied to a node of this class due to having this reg
-- as a neighbour.
--
{-# INLINE virtualRegSqueeze #-}
virtualRegSqueeze :: RegClass -> VirtualReg -> FastInt
virtualRegSqueeze cls vr
= case cls of
RcInteger
-> case vr of
VirtualRegI{} -> _ILIT(1)
VirtualRegHi{} -> _ILIT(1)
_other -> _ILIT(0)
RcFloat
-> case vr of
VirtualRegF{} -> _ILIT(1)
VirtualRegD{} -> _ILIT(2)
_other -> _ILIT(0)
RcDouble
-> case vr of
VirtualRegF{} -> _ILIT(1)
VirtualRegD{} -> _ILIT(1)
_other -> _ILIT(0)
_other -> _ILIT(0)
{-# INLINE realRegSqueeze #-}
realRegSqueeze :: RegClass -> RealReg -> FastInt
realRegSqueeze cls rr
= case cls of
RcInteger
-> case rr of
RealRegSingle regNo
| regNo < 32 -> _ILIT(1)
| otherwise -> _ILIT(0)
RealRegPair{} -> _ILIT(0)
RcFloat
-> case rr of
RealRegSingle regNo
| regNo < 32 -> _ILIT(0)
| otherwise -> _ILIT(1)
RealRegPair{} -> _ILIT(2)
RcDouble
-> case rr of
RealRegSingle regNo
| regNo < 32 -> _ILIT(0)
| otherwise -> _ILIT(1)
RealRegPair{} -> _ILIT(1)
_other -> _ILIT(0)
-- | All the allocatable registers in the machine,
-- including register pairs.
allRealRegs :: [RealReg]
allRealRegs
= [ (RealRegSingle i) | i <- [0..63] ]
++ [ (RealRegPair i (i+1)) | i <- [32, 34 .. 62 ] ]
-- | Get the regno for this sort of reg
gReg, lReg, iReg, oReg, fReg :: Int -> RegNo
gReg x = x -- global regs
oReg x = (8 + x) -- output regs
lReg x = (16 + x) -- local regs
iReg x = (24 + x) -- input regs
fReg x = (32 + x) -- float regs
-- | Some specific regs used by the code generator.
g0, g1, g2, fp, sp, o0, o1, f0, f1, f6, f8, f22, f26, f27 :: Reg
f6 = RegReal (RealRegSingle (fReg 6))
f8 = RegReal (RealRegSingle (fReg 8))
f22 = RegReal (RealRegSingle (fReg 22))
f26 = RegReal (RealRegSingle (fReg 26))
f27 = RegReal (RealRegSingle (fReg 27))
-- g0 is always zero, and writes to it vanish.
g0 = RegReal (RealRegSingle (gReg 0))
g1 = RegReal (RealRegSingle (gReg 1))
g2 = RegReal (RealRegSingle (gReg 2))
-- FP, SP, int and float return (from C) regs.
fp = RegReal (RealRegSingle (iReg 6))
sp = RegReal (RealRegSingle (oReg 6))
o0 = RegReal (RealRegSingle (oReg 0))
o1 = RegReal (RealRegSingle (oReg 1))
f0 = RegReal (RealRegSingle (fReg 0))
f1 = RegReal (RealRegSingle (fReg 1))
-- | Produce the second-half-of-a-double register given the first half.
{-
fPair :: Reg -> Maybe Reg
fPair (RealReg n)
| n >= 32 && n `mod` 2 == 0 = Just (RealReg (n+1))
fPair (VirtualRegD u)
= Just (VirtualRegHi u)
fPair reg
= trace ("MachInstrs.fPair: can't get high half of supposed double reg " ++ showPpr reg)
Nothing
-}
-- | All the regs that the register allocator can allocate to,
-- with the the fixed use regs removed.
--
allocatableRegs :: [RealReg]
allocatableRegs
= let isFree rr
= case rr of
RealRegSingle r
-> isFastTrue (freeReg r)
RealRegPair r1 r2
-> isFastTrue (freeReg r1)
&& isFastTrue (freeReg r2)
in filter isFree allRealRegs
-- | The registers to place arguments for function calls,
-- for some number of arguments.
--
argRegs :: RegNo -> [Reg]
argRegs r
= case r of
0 -> []
1 -> map (RegReal . RealRegSingle . oReg) [0]
2 -> map (RegReal . RealRegSingle . oReg) [0,1]
3 -> map (RegReal . RealRegSingle . oReg) [0,1,2]
4 -> map (RegReal . RealRegSingle . oReg) [0,1,2,3]
5 -> map (RegReal . RealRegSingle . oReg) [0,1,2,3,4]
6 -> map (RegReal . RealRegSingle . oReg) [0,1,2,3,4,5]
_ -> panic "MachRegs.argRegs(sparc): don't know about >6 arguments!"
-- | All all the regs that could possibly be returned by argRegs
--
allArgRegs :: [Reg]
allArgRegs
= map (RegReal . RealRegSingle) [oReg i | i <- [0..5]]
-- These are the regs that we cannot assume stay alive over a C call.
-- TODO: Why can we assume that o6 isn't clobbered? -- BL 2009/02
--
callClobberedRegs :: [Reg]
callClobberedRegs
= map (RegReal . RealRegSingle)
( oReg 7 :
[oReg i | i <- [0..5]] ++
[gReg i | i <- [1..7]] ++
[fReg i | i <- [0..31]] )
-- | Make a virtual reg with this size.
mkVirtualReg :: Unique -> Size -> VirtualReg
mkVirtualReg u size
| not (isFloatSize size)
= VirtualRegI u
| otherwise
= case size of
FF32 -> VirtualRegF u
FF64 -> VirtualRegD u
_ -> panic "mkVReg"
regDotColor :: RealReg -> SDoc
regDotColor reg
= case classOfRealReg reg of
RcInteger -> text "blue"
RcFloat -> text "red"
_other -> text "green"
|
ryantm/ghc
|
compiler/nativeGen/SPARC/Regs.hs
|
Haskell
|
bsd-3-clause
| 6,744
|
<?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="pl-PL">
<title>Common Library</title>
<maps>
<homeID>commonlib</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/commonlib/src/main/javahelp/help_pl_PL/helpset_pl_PL.hs
|
Haskell
|
apache-2.0
| 965
|
{-# OPTIONS_GHC -cpp #-}
{-+
This module implements environments (symbol tables) as finite maps.
Finite maps are not necessarily faster than simple association lists, since
although lookups change from O(n) to O(log n), extension changes from
O(1) to O(log n), and the latter cost can be the dominating cost...
-}
module TiEnvFM(Env,extenv1,extenv,empty,lookup,domain,range) where
import Prelude hiding (lookup) -- for Hugs
import qualified Prelude -- Haskell report change workaround
import Map60204
--import PrettyPrint(Printable(..),fsep) -- for debugging
#if __GLASGOW_HASKELL__ >= 604
import qualified Data.Map as M (Map)
newtype Env key info = Env (M.Map key info)
#else
import qualified Data.FiniteMap as M (FiniteMap)
newtype Env key info = Env (M.FiniteMap key info)
#endif
extenv1 x t (Env bs) = Env (insertM x t bs)
extenv bs1 (Env bs2) = Env (addListToM bs2 bs1)
empty = Env emptyM
lookup (Env env) x = lookupM x env
domain (Env env) = keysM env
range (Env env) = elemsM env
-- Why isn't there a Show instance for FiniteMap?!
instance (Show key,Show info) => Show (Env key info) where
showsPrec n (Env env) = showsPrec n (toListM env)
-- Why isn't there a Functor instance for FiniteMap?!
instance Functor (Env key) where
fmap f (Env bs) = Env (mapM' f bs)
{-
-- For debugging:
instance (Printable key,Printable info) => Printable (Env key info) where
ppi (Env env) = fsep (keysFM env)
-}
|
kmate/HaRe
|
old/tools/base/TI/TiEnvFM.hs
|
Haskell
|
bsd-3-clause
| 1,422
|
module B (name) where
name :: String
name = "Samantha"
|
sdiehl/ghc
|
testsuite/tests/driver/T16511/B1.hs
|
Haskell
|
bsd-3-clause
| 56
|
module Mod120_A(T) where
data T = Foo
|
urbanslug/ghc
|
testsuite/tests/module/Mod120_A.hs
|
Haskell
|
bsd-3-clause
| 39
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Main where
import Turtle
import qualified Data.Maybe as Maybe
import qualified Search as Search
main :: IO ()
main = sh $ do
boss <- options "Day 21" parser
let minimal = Loadout 0 Nothing Nothing Nothing
let won_fight load = battle (makePlayer load) boss == "Player"
cheapest_steps <-
case Search.djikstra upgrade won_fight [] minimal of
Just victory -> return (snd victory)
Nothing -> die "Victory is impossible!"
let cheapest = snd $ last cheapest_steps
let cheapest_cost = loadoutCost cheapest
printf "Cheapest winning loadout (part 1):\n"
printf (" "%s%"\n") . itemName $ weapons !! weaponIdx cheapest
printf (" "%s%"\n") $
maybe "No armor" (itemName . (armors !!)) (armorIdx cheapest)
printf (" "%s%"\n") $
maybe "No left ring" (itemName . (rings !!)) (leftRingIdx cheapest)
printf (" "%s%"\n") $
maybe "No right ring" (itemName . (rings !!)) (rightRingIdx cheapest)
printf ("Total cost (part 1): "%d%"\n") cheapest_cost
let maximal = Loadout 4 (Just 4) (Just 4) (Just 5)
most_expensive_steps <-
case Search.djikstra downgrade (not . won_fight) [] maximal of
Just victory -> return (snd victory)
Nothing -> die "Victory is certain!"
let most_expensive = snd $ last most_expensive_steps
let most_expensive_cost = loadoutCost most_expensive
printf "Most expensive losing loadout (part 2):\n"
printf (" "%s%"\n") . itemName $ weapons !! weaponIdx most_expensive
printf (" "%s%"\n") $
maybe "No armor" (itemName . (armors !!)) (armorIdx most_expensive)
printf (" "%s%"\n") $
maybe "No left ring" (itemName . (rings !!)) (leftRingIdx most_expensive)
printf (" "%s%"\n") $
maybe "No right ring" (itemName . (rings !!)) (rightRingIdx most_expensive)
printf ("Total cost (part 2): "%d%"\n") most_expensive_cost
battle :: Character -> Character -> PlayerName
battle p1 p2
| hp p1 <= 0 = name p2
| otherwise = battle damaged_p2 p1
where
damaged_p2 =
let raw_damage = damage p1 - armor p2
in p2 {hp = hp p2 - if raw_damage < 1 then 1 else raw_damage}
upgrade ::
Loadout -- current loadout
-> [(Int, Loadout)] -- [(incremental cost, new loadout)]
upgrade loadout =
Maybe.catMaybes [
(\idx -> loadout { weaponIdx = idx })
<$> try_upgrade (Just $ weaponIdx loadout) weapons,
(\idx -> loadout { armorIdx = Just idx })
<$> try_upgrade (armorIdx loadout) armors,
do
ridx <- rightRingIdx loadout
lidx <- try_upgrade (leftRingIdx loadout) rings
if lidx < ridx
then Just $ loadout {leftRingIdx = Just lidx}
else Nothing
,
(\idx -> loadout { rightRingIdx = Just idx })
<$> try_upgrade (rightRingIdx loadout) rings
]
& map (\new -> (loadoutCost new - loadoutCost loadout, new))
where
try_upgrade Nothing table = Just 0
try_upgrade (Just idx) table =
if idx + 1 >= length table
then Nothing
else Just (idx + 1)
downgrade ::
Loadout -- current loadout
-> [(Int, Loadout)] -- [(incremental savings, new loadout)]
downgrade loadout =
Maybe.catMaybes [
do
wmidx <- try_downgrade (Just $ weaponIdx loadout) weapons
(\idx -> loadout { weaponIdx = idx }) <$> wmidx,
(\midx -> loadout { armorIdx = midx })
<$> try_downgrade (armorIdx loadout) armors,
(\midx -> loadout { leftRingIdx = midx })
<$> try_downgrade (leftRingIdx loadout) rings,
do
rmidx <- try_downgrade (rightRingIdx loadout) rings
let lmidx = leftRingIdx loadout
if Maybe.isNothing lmidx && Maybe.isNothing rmidx || lmidx < rmidx
then Just $ loadout {rightRingIdx = rmidx}
else Nothing
]
& map (\new -> (loadoutCost loadout - loadoutCost new, new))
where
try_downgrade Nothing table = Nothing
try_downgrade (Just idx) table =
if idx == 0
then Just Nothing
else Just . Just $ idx - 1
loadoutCost :: Loadout -> Int
loadoutCost Loadout{..} =
cost (weapons !! weaponIdx)
+ maybe 0 (cost . (armors !!)) armorIdx
+ maybe 0 (cost . (rings !!)) leftRingIdx
+ maybe 0 (cost . (rings !!)) rightRingIdx
makePlayer :: Loadout -> Character
makePlayer Loadout{..} =
Character {
name = "Player",
hp = 100,
damage =
damageBonus (weapons !! weaponIdx)
+ maybe 0 (damageBonus . (rings !!)) leftRingIdx
+ maybe 0 (damageBonus . (rings !!)) rightRingIdx,
armor =
maybe 0 (armorBonus . (armors !!)) armorIdx
+ maybe 0 (armorBonus . (rings !!)) leftRingIdx
+ maybe 0 (armorBonus . (rings !!)) rightRingIdx
}
type PlayerName = Text
data Character = Character {
name :: Text,
hp :: Int,
damage :: Int,
armor :: Int
} deriving (Show)
data Item = Item {
itemName :: Text,
cost :: Int,
damageBonus :: Int,
armorBonus :: Int
} deriving (Eq, Ord, Show)
data Loadout = Loadout {
weaponIdx :: Int,
armorIdx :: Maybe Int,
leftRingIdx :: Maybe Int,
rightRingIdx :: Maybe Int
} deriving (Eq, Ord, Show)
weapons = [
Item "Dagger" 8 4 0,
Item "Shortsword" 10 5 0,
Item "Warhammer" 25 6 0,
Item "Longsword" 40 7 0,
Item "Greataxe" 74 8 0
]
armors = [
Item "Leather" 13 0 1,
Item "Chainmail" 31 0 2,
Item "Splintmail" 53 0 3,
Item "Bandedmail" 75 0 4,
Item "Platemail" 102 0 5
]
rings = [
Item "Defense +1" 20 0 1,
Item "Damage +1" 25 1 0,
Item "Defense +2" 40 0 2,
Item "Damage +2" 50 2 0,
Item "Defense +3" 80 0 3,
Item "Damage +3" 100 3 0
]
parser =
Character "Boss"
<$> (fromIntegral <$> optInteger "health" 'p' "Boss health")
<*> (fromIntegral <$> optInteger "damage" 'd' "Boss damage")
<*> (fromIntegral <$> optInteger "armor" 'a' "Boss armor")
|
devonhollowood/adventofcode
|
2015/day21/day21.hs
|
Haskell
|
mit
| 5,700
|
module Three where
import Test.QuickCheck
import Test.QuickCheck.Checkers
data Three a b c = Three a b c
deriving (Eq, Ord, Show)
--
instance Functor (Three a b) where
fmap f (Three a b c) = Three a b (f c)
instance Foldable (Three a b) where
foldMap f (Three a b c) = f c
instance Traversable (Three a b) where
traverse f (Three a b c) = Three a b <$> f c
--
instance (Arbitrary a, Arbitrary b, Arbitrary c) => Arbitrary (Three a b c) where
arbitrary = Three <$> arbitrary <*> arbitrary <*> arbitrary
instance (Eq a, Eq b, Eq c) => EqProp (Three a b c) where
(=-=) = eq
|
NickAger/LearningHaskell
|
HaskellProgrammingFromFirstPrinciples/Chapter21/Exercises/src/Three.hs
|
Haskell
|
mit
| 593
|
module Gen.Core
( surroundWith
, smallArbitrary
, maybeGen
, genNothing
, module Language.GoLite.Syntax
, module Control.Monad
, module Test.Hspec
, module Test.Hspec.QuickCheck
, module Test.QuickCheck
) where
import Language.GoLite.Syntax
import Control.Monad
import Test.Hspec
import Test.Hspec.QuickCheck
import Test.QuickCheck hiding ( Positive ) -- Conflicts with Types.Positive
import Test.QuickCheck.Gen ( Gen(MkGen) )
-- | Creates a function which will surround a string with the given string.
surroundWith :: String -> (String -> String)
surroundWith s = (\x -> s ++ x ++ s)
-- | Generates a size-1 arbitrary value.
smallArbitrary :: Arbitrary a => Gen a
smallArbitrary = (resize 1 arbitrary)
-- | Generates either just a value from the given generator, or nothing.
-- The body is the same as the instance for Arbitrary (Maybe a)
-- (https://goo.gl/zimSLs), -- but available as a standalone function.
maybeGen :: Gen a -> Gen (Maybe a)
maybeGen g = frequency [(1, pure Nothing), (3, liftM Just g)]
-- | Generates Nothing.
genNothing :: Gen (Maybe a)
genNothing = (MkGen $ \_ _ -> Nothing)
|
djeik/goto
|
test/Gen/Core.hs
|
Haskell
|
mit
| 1,104
|
module
Foo
|
chreekat/vim-haskell-syntax
|
test/golden/module-firstline.hs
|
Haskell
|
mit
| 11
|
--
-- Find the greatest product of five consecutive digits in the 1000-digit number.
--
number
= "73167176531330624919225119674426574742355349194934"
++ "96983520312774506326239578318016984801869478851843"
++ "85861560789112949495459501737958331952853208805511"
++ "12540698747158523863050715693290963295227443043557"
++ "66896648950445244523161731856403098711121722383113"
++ "62229893423380308135336276614282806444486645238749"
++ "30358907296290491560440772390713810515859307960866"
++ "70172427121883998797908792274921901699720888093776"
++ "65727333001053367881220235421809751254540594752243"
++ "52584907711670556013604839586446706324415722155397"
++ "53697817977846174064955149290862569321978468622482"
++ "83972241375657056057490261407972968652414535100474"
++ "82166370484403199890008895243450658541227588666881"
++ "16427171479924442928230863465674813919123162824586"
++ "17866458359124566529476545682848912883142607690042"
++ "24219022671055626321111109370544217506941658960408"
++ "07198403850962455444362981230987879927244284909188"
++ "84580156166097919133875499200524063689912560717606"
++ "05886116467109405077541002256983155200055935729725"
++ "71636269561882670428252483600823257530420752963450"
chunkSize = 5
chunks
= map (\ x -> take chunkSize $ drop x number) [0 .. length number - chunkSize]
toNumbers :: String -> [Int]
toNumbers
= map (\ x -> read [x] :: Int)
main = print $ maximum $ map (product . toNumbers) chunks
|
stu-smith/project-euler-haskell
|
Euler-008.hs
|
Haskell
|
mit
| 1,556
|
{-# LANGUAGE FlexibleContexts #-}
module Dissent.Protocol.Shuffle.Leader where
import Control.Monad.Error
import Control.Monad.Trans.Resource
import Data.List (sortBy)
import qualified Network.Socket as NS
import qualified Dissent.Crypto.Rsa as R
import qualified Dissent.Network.Quorum as NQ
import qualified Dissent.Network.Socket as NS
import qualified Dissent.Types.Quorum as TQ
import qualified Dissent.Types.Peer as TP
run :: TQ.Quorum -> IO ()
run quorum = runResourceT $ do
result <- runErrorT $ do
sockets <- phase1 quorum
ciphers <- phase2 sockets
_ <- phase3 sockets ciphers
return ()
case result of
Left e -> error ("Something went wrong: " ++ e)
Right b -> return b
-- | In the first phase, our leader will open a socket that
-- slaves can connect to, and will wait for all slaves to
-- connect to the quorum.
--
-- This is a blocking operation.
phase1 :: ( MonadIO m
, MonadError String m
, MonadResource m)
=> TQ.Quorum -- ^ The Quorum we operate on
-> m [NS.Socket] -- ^ The sockets we accepted
phase1 quorum =
let accepted = NQ.accept quorum TP.Leader
-- Returns all accepted sockets from all slaves.
--
-- This is a blocking operation.
sockets = (return . map fst) =<< accepted
-- After a connection has been established with a slave, we
-- expect a handshake to occur. At the present moment, this
-- handshake only involves a peer telling us his id, so we know
-- which socket to associate with which peer.
--
-- This is a blocking operation.
handShake socket = do
peerId <- liftIO $ NS.receiveAndDecode socket
either throwError return peerId
-- Now, after this process, we have a list of sockets, and a list
-- of peer ids. Once we put them in a zipped list, we have a convenient
-- way to sort them by peer id, thus allowing us to easily look up a
-- socket by a peer's id.
sortSockets :: [(TP.Id, NS.Socket)] -> [(TP.Id, NS.Socket)]
sortSockets =
let predicate lhs rhs | fst lhs < fst rhs = LT
| fst lhs > fst rhs = GT
| otherwise = EQ
in sortBy predicate
in do
unorderedSockets <- liftResourceT sockets
-- Retrieve all peer ids
peerIds <- mapM handShake unorderedSockets
-- Combine the sockets with the peer ids, sort them based on the peer id,
-- and get a list of the sockets out of it.
return (map snd (sortSockets (zip peerIds unorderedSockets)))
-- | In the second phase, the leader receives all the encrypted messages from all
-- the slaves.
--
-- This is a blocking operation.
phase2 :: ( MonadIO m
, MonadError String m)
=> [NS.Socket] -- ^ The Sockets we accepted
-> m [R.Encrypted] -- ^ All the encrypted messages we received from the
-- slaves.
phase2 sockets = do
ciphers <- liftIO $ mapM NS.receiveAndDecode sockets
either throwError return (sequence ciphers)
-- | In the third phase, the leader sends all the ciphers to the first node
-- in the quorum.
--
-- Note that in our implementation, the first node is always the leader
-- itself.
phase3 :: MonadIO m
=> [NS.Socket] -- ^ All connections to all slaves
-> [R.Encrypted] -- ^ The ciphers we received from all slaves
-> m ()
phase3 sockets ciphers =
let firstSocket :: NS.Socket
firstSocket = head sockets
in do
liftIO $ NS.encodeAndSend firstSocket ciphers
return ()
|
solatis/dissent
|
src/Dissent/Protocol/Shuffle/Leader.hs
|
Haskell
|
mit
| 3,730
|
#!/usr/bin/env stack
-- stack --install-ghc runghc --package turtle
{-# LANGUAGE OverloadedStrings #-}
import Turtle
main = stdout $ grep ((star dot) <> "monads" <> (star dot)) $ input "README.md"
|
JoshuaGross/haskell-learning-log
|
Code/turtle/grep.hs
|
Haskell
|
mit
| 210
|
Config
{ font = "xft:Inconsolata:size=13"
, bgColor = "#3a3a3a"
, fgColor = "#dcdccc"
, position = Top
, commands =
[ Run MPD
[ "--template", "<statei> <fc=#8cd0d3><title></fc> - <fc=#f0dfaf><artist></fc> - <lapsed>/<remaining>"
, "--"
, "-P", "<fc=#bfebbf>>></fc>"
, "-Z", "<fc=#dca3a3>##</fc>"
, "-S", "<fc=#dca3a3>##</fc>"
] 5
, Run CoreTemp
[ "--Low", "40"
, "--High", "60"
, "--low", "#87af87"
, "--normal", "#ffd7af"
, "--high", "#dca3a3"
, "--template", "T: <core0>°C"
] 10
, Run MultiCpu
[ "--Low", "5"
, "--High", "50"
, "--low", "#87af87"
, "--normal", "#ffd7af"
, "--high", "#dca3a3"
, "--template", "P: <total>%"
] 10
, Run Memory
[ "--Low", "33"
, "--High", "66"
, "--low", "#87af87"
, "--normal", "#ffd7af"
, "--high", "#dca3a3"
, "--template", "M: <usedratio>%"
] 10
, Run DynNetwork
[ "--Low", "16384"
, "--High", "1048576"
, "--low", "#87af87"
, "--normal", "#ffd7af"
, "--high", "#dca3a3"
, "--template", "N: <rx>KB/<tx>KB"
] 10
, Run Volume "default" "Master"
[ "--template", "V: <volume>% <status>"
, "--"
, "--on", "[on]"
, "--off", "[mu]"
, "--onc", "#87af87"
, "--offc", "#dca3a3"
] 5
, Run Date "<fc=#ffd7af>%a %b %_d</fc> <fc=#8cd0d3>%l:%M</fc>" "date" 10
, Run StdinReader
]
, alignSep = "}{"
, template = "%StdinReader% }{ %mpd% | %default:Master% | %dynnetwork% | %coretemp% | %multicpu% | %memory% %date% "
}
|
randalloveson/dotfiles
|
xmonad/.xmonad/xmobar.hs
|
Haskell
|
mit
| 2,230
|
module Rebase.Data.Functor.Sum
(
module Data.Functor.Sum
)
where
import Data.Functor.Sum
|
nikita-volkov/rebase
|
library/Rebase/Data/Functor/Sum.hs
|
Haskell
|
mit
| 92
|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TypeFamilies #-}
module App.State
( ServerState(..)
, HasConnections
, GameState
, IsConnection(..)
, defaultInitialState
, defaultInitialStateWithRandomPositions
) where
import App.ConnectionMgnt
import ClassyPrelude
import Config.GameConfig (defaultConfig, defaultConfigWithRandomPositions)
import GameNg (GameState (..), initialStateFromConfig)
import Network.Protocol (Player)
data ServerState conn =
ServerState
{ stateConnections :: ClientConnections conn
, gameState :: GameState
, playerMap :: Map Player ConnectionId
}
instance IsConnection conn => HasConnections (ServerState conn) where
type Conn (ServerState conn) = conn
getConnections =
stateConnections
setConnections conns state =
state
{ stateConnections = conns
}
defaultInitialStateWithRandomPositions :: IO (ServerState conn)
defaultInitialStateWithRandomPositions = do
config <- defaultConfigWithRandomPositions
return ServerState
{ stateConnections = ClientConnections mempty 0
, gameState = GameRunning_ $ initialStateFromConfig config
, playerMap = mempty
}
defaultInitialState :: ServerState conn
defaultInitialState =
ServerState
{ stateConnections = ClientConnections mempty 0
, gameState = GameRunning_ $ initialStateFromConfig defaultConfig
, playerMap = mempty
}
|
Haskell-Praxis/core-catcher
|
src/App/State.hs
|
Haskell
|
mit
| 1,560
|
{-|
Module : TrackParameter
Description : Short description
Copyright : (c) Laurent Bulteau, Romeo Rizzi, Stéphane Vialette, 2016-1017
License : MIT
Maintainer : vialette@gmail.com
Stability : experimental
Here is a longer description of this module, containing some
commentary with @some markup@.
-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
import qualified Data.Foldable as Foldable
import System.Console.CmdArgs
import System.Random
import qualified Data.Algorithm.PPattern.Perm.Monotone as Perm.Monotone
import qualified Data.Algorithm.PPattern.Perm.Random as Perm.Random
data Options = Options { size :: Int
, trials :: Int
, seed :: Int
} deriving (Data, Typeable)
options :: Options
options = Options { size = def &= help "The permutation size"
, trials = def &= help "The number of trials"
, seed = def &= help "The seed of the random generator"
}
&= verbosity
&= summary "split-parameter v0.1.0.0, (C) Laurent Bulteau, Romeo Rizzi, Stéphane Vialette, 2016-1017"
&= program "split-parameter"
-- Estimate distribution
trackParamter :: RandomGen g => Int -> Int -> g -> [Int]
trackParamter n t = aux [] 1
where
aux acc i g
| i > t = acc
| otherwise = aux (k : acc) (i+1) g'
where
(p, g') = Perm.Random.rand' n g
k = Perm.Monotone.longestDecreasingLength p
go :: RandomGen g => Int -> Int -> g -> IO ()
go n t g = Foldable.mapM_ putStr $ fmap (\k -> show n ++ "," ++ show k ++ "\n") ks
where
ks = trackParamter n t g
main :: IO ()
main = do
opts <- cmdArgs options
go (size opts) (trials opts)$ mkStdGen (seed opts)
|
vialette/ppattern-tmp
|
src/TrackParameter.hs
|
Haskell
|
mit
| 1,823
|
{-# LANGUAGE DeriveGeneric #-}
module Kantour.KcData.Map.Image where
import Data.Aeson
import GHC.Generics
import qualified Data.HashMap.Strict as HM
import Kantour.KcData.Map.Sprite
import qualified Data.Text as T
data Image = Image
{ frames :: HM.HashMap T.Text Sprite
, meta :: Maybe Value
} deriving (Generic)
instance FromJSON Image
|
Javran/tuppence
|
src/Kantour/KcData/Map/Image.hs
|
Haskell
|
mit
| 347
|
pertenece :: a -> ArbolG a -> Bool
pertenece a AVG = False
pertenece a (AG r s) = if ( a == r) then true else (aux a s)
aux :: (Eq a) => a -> [ArbolG a] -> Bool
aux a [] = False;
aux a (h:t) if pertenece a h then True else aux a t
|
josegury/HaskellFuntions
|
Arboles/HojaPerteneceArbol.hs
|
Haskell
|
mit
| 234
|
module Language.MSH.BuiltIn where
newClassName :: String
newClassName = "New"
newArgsTypeName :: String
newArgsTypeName = "Args"
newKwdName :: String
newKwdName = "new"
|
mbg/monadic-state-hierarchies
|
Language/MSH/BuiltIn.hs
|
Haskell
|
mit
| 173
|
module TypeKwonDo where
chk :: Eq b => (a -> b) -> a -> b -> Bool
chk aToB a b = aToB a == b
arith :: Num b => (a -> b) -> Integer -> a -> b
arith aToB int a = aToB a + fromInteger int
|
rasheedja/HaskellFromFirstPrinciples
|
Chapter6/typeKwonDo.hs
|
Haskell
|
mit
| 187
|
module CostasLikeArrays.A320574 where
import Helpers.CostasLikeArrays (distinctDistances, countPermutationsUpToDihedralSymmetry)
import Helpers.Records (allMax)
import Data.List (permutations)
a320574 :: Int -> Int
a320574 n = countPermutationsUpToDihedralSymmetry n $ allMax distinctDistances $ permutations [0..n-1]
|
peterokagey/haskellOEIS
|
src/CostasLikeArrays/A320574.hs
|
Haskell
|
apache-2.0
| 319
|
module Permutations.A329851Spec (main, spec) where
import Test.Hspec
import Permutations.A329851 (a329851)
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "A329851" $
it "correctly computes the first six elements" $
map a329851 [0..5] `shouldBe` expectedValue where
expectedValue = [0, 2, 12, 120, 1320, 17856]
|
peterokagey/haskellOEIS
|
test/Permutations/A329851Spec.hs
|
Haskell
|
apache-2.0
| 338
|
{-# LANGUAGE OverloadedStrings, CPP #-}
module FormStructure.Countries where
#ifndef __HASTE__
import Data.Text.Lazy (Text)
#else
type Text = String
#endif
countries :: [(Text, Text)]
countries =
[ ("", "--select--")
, ("AF", "Afghanistan")
, ("AX", "Åland Islands")
, ("AL", "Albania")
, ("DZ", "Algeria")
, ("AS", "American Samoa")
, ("AD", "Andorra")
, ("AO", "Angola")
, ("AI", "Anguilla")
, ("AQ", "Antarctica")
, ("AG", "Antigua and Barbuda")
, ("AR", "Argentina")
, ("AM", "Armenia")
, ("AW", "Aruba")
, ("AU", "Australia")
, ("AT", "Austria")
, ("AZ", "Azerbaijan")
, ("BS", "Bahamas")
, ("BH", "Bahrain")
, ("BD", "Bangladesh")
, ("BB", "Barbados")
, ("BY", "Belarus")
, ("BE", "Belgium")
, ("BZ", "Belize")
, ("BJ", "Benin")
, ("BM", "Bermuda")
, ("BT", "Bhutan")
, ("BO", "Bolivia, Plurinational State of")
, ("BQ", "Bonaire, Sint Eustatius and Saba")
, ("BA", "Bosnia and Herzegovina")
, ("BW", "Botswana")
, ("BV", "Bouvet Island")
, ("BR", "Brazil")
, ("IO", "British Indian Ocean Territory")
, ("BN", "Brunei Darussalam")
, ("BG", "Bulgaria")
, ("BF", "Burkina Faso")
, ("BI", "Burundi")
, ("KH", "Cambodia")
, ("CM", "Cameroon")
, ("CA", "Canada")
, ("CV", "Cape Verde")
, ("KY", "Cayman Islands")
, ("CF", "Central African Republic")
, ("TD", "Chad")
, ("CL", "Chile")
, ("CN", "China")
, ("CX", "Christmas Island")
, ("CC", "Cocos (Keeling) Islands")
, ("CO", "Colombia")
, ("KM", "Comoros")
, ("CG", "Congo")
, ("CD", "Congo, the Democratic Republic of the")
, ("CK", "Cook Islands")
, ("CR", "Costa Rica")
, ("CI", "Côte d'Ivoire")
, ("HR", "Croatia")
, ("CU", "Cuba")
, ("CW", "Curaçao")
, ("CY", "Cyprus")
, ("CZ", "Czech Republic")
, ("DK", "Denmark")
, ("DJ", "Djibouti")
, ("DM", "Dominica")
, ("DO", "Dominican Republic")
, ("EC", "Ecuador")
, ("EG", "Egypt")
, ("SV", "El Salvador")
, ("GQ", "Equatorial Guinea")
, ("ER", "Eritrea")
, ("EE", "Estonia")
, ("ET", "Ethiopia")
, ("FK", "Falkland Islands (Malvinas)")
, ("FO", "Faroe Islands")
, ("FJ", "Fiji")
, ("FI", "Finland")
, ("FR", "France")
, ("GF", "French Guiana")
, ("PF", "French Polynesia")
, ("TF", "French Southern Territories")
, ("GA", "Gabon")
, ("GM", "Gambia")
, ("GE", "Georgia")
, ("DE", "Germany")
, ("GH", "Ghana")
, ("GI", "Gibraltar")
, ("GR", "Greece")
, ("GL", "Greenland")
, ("GD", "Grenada")
, ("GP", "Guadeloupe")
, ("GU", "Guam")
, ("GT", "Guatemala")
, ("GG", "Guernsey")
, ("GN", "Guinea")
, ("GW", "Guinea-Bissau")
, ("GY", "Guyana")
, ("HT", "Haiti")
, ("HM", "Heard Island and McDonald Islands")
, ("VA", "Holy See (Vatican City State)")
, ("HN", "Honduras")
, ("HK", "Hong Kong")
, ("HU", "Hungary")
, ("IS", "Iceland")
, ("IN", "India")
, ("ID", "Indonesia")
, ("IR", "Iran, Islamic Republic of")
, ("IQ", "Iraq")
, ("IE", "Ireland")
, ("IM", "Isle of Man")
, ("IL", "Israel")
, ("IT", "Italy")
, ("JM", "Jamaica")
, ("JP", "Japan")
, ("JE", "Jersey")
, ("JO", "Jordan")
, ("KZ", "Kazakhstan")
, ("KE", "Kenya")
, ("KI", "Kiribati")
, ("KP", "Korea, Democratic People's Republic of")
, ("KR", "Korea, Republic of")
, ("KW", "Kuwait")
, ("KG", "Kyrgyzstan")
, ("LA", "Lao People's Democratic Republic")
, ("LV", "Latvia")
, ("LB", "Lebanon")
, ("LS", "Lesotho")
, ("LR", "Liberia")
, ("LY", "Libya")
, ("LI", "Liechtenstein")
, ("LT", "Lithuania")
, ("LU", "Luxembourg")
, ("MO", "Macao")
, ("MK", "Macedonia, the former Yugoslav Republic of")
, ("MG", "Madagascar")
, ("MW", "Malawi")
, ("MY", "Malaysia")
, ("MV", "Maldives")
, ("ML", "Mali")
, ("MT", "Malta")
, ("MH", "Marshall Islands")
, ("MQ", "Martinique")
, ("MR", "Mauritania")
, ("MU", "Mauritius")
, ("YT", "Mayotte")
, ("MX", "Mexico")
, ("FM", "Micronesia, Federated States of")
, ("MD", "Moldova, Republic of")
, ("MC", "Monaco")
, ("MN", "Mongolia")
, ("ME", "Montenegro")
, ("MS", "Montserrat")
, ("MA", "Morocco")
, ("MZ", "Mozambique")
, ("MM", "Myanmar")
, ("NA", "Namibia")
, ("NR", "Nauru")
, ("NP", "Nepal")
, ("NL", "Netherlands")
, ("NC", "New Caledonia")
, ("NZ", "New Zealand")
, ("NI", "Nicaragua")
, ("NE", "Niger")
, ("NG", "Nigeria")
, ("NU", "Niue")
, ("NF", "Norfolk Island")
, ("MP", "Northern Mariana Islands")
, ("NO", "Norway")
, ("OM", "Oman")
, ("PK", "Pakistan")
, ("PW", "Palau")
, ("PS", "Palestinian Territory, Occupied")
, ("PA", "Panama")
, ("PG", "Papua New Guinea")
, ("PY", "Paraguay")
, ("PE", "Peru")
, ("PH", "Philippines")
, ("PN", "Pitcairn")
, ("PL", "Poland")
, ("PT", "Portugal")
, ("PR", "Puerto Rico")
, ("QA", "Qatar")
, ("RE", "Réunion")
, ("RO", "Romania")
, ("RU", "Russian Federation")
, ("RW", "Rwanda")
, ("BL", "Saint Barthélemy")
, ("SH", "Saint Helena, Ascension and Tristan da Cunha")
, ("KN", "Saint Kitts and Nevis")
, ("LC", "Saint Lucia")
, ("MF", "Saint Martin (French part)")
, ("PM", "Saint Pierre and Miquelon")
, ("VC", "Saint Vincent and the Grenadines")
, ("WS", "Samoa")
, ("SM", "San Marino")
, ("ST", "Sao Tome and Principe")
, ("SA", "Saudi Arabia")
, ("SN", "Senegal")
, ("RS", "Serbia")
, ("SC", "Seychelles")
, ("SL", "Sierra Leone")
, ("SG", "Singapore")
, ("SX", "Sint Maarten (Dutch part)")
, ("SK", "Slovakia")
, ("SI", "Slovenia")
, ("SB", "Solomon Islands")
, ("SO", "Somalia")
, ("ZA", "South Africa")
, ("GS", "South Georgia and the South Sandwich Islands")
, ("SS", "South Sudan")
, ("ES", "Spain")
, ("LK", "Sri Lanka")
, ("SD", "Sudan")
, ("SR", "Suriname")
, ("SJ", "Svalbard and Jan Mayen")
, ("SZ", "Swaziland")
, ("SE", "Sweden")
, ("CH", "Switzerland")
, ("SY", "Syrian Arab Republic")
, ("TW", "Taiwan, Province of China")
, ("TJ", "Tajikistan")
, ("TZ", "Tanzania, United Republic of")
, ("TH", "Thailand")
, ("TL", "Timor-Leste")
, ("TG", "Togo")
, ("TK", "Tokelau")
, ("TO", "Tonga")
, ("TT", "Trinidad and Tobago")
, ("TN", "Tunisia")
, ("TR", "Turkey")
, ("TM", "Turkmenistan")
, ("TC", "Turks and Caicos Islands")
, ("TV", "Tuvalu")
, ("UG", "Uganda")
, ("UA", "Ukraine")
, ("AE", "United Arab Emirates")
, ("GB", "United Kingdom")
, ("US", "United States")
, ("UM", "United States Minor Outlying Islands")
, ("UY", "Uruguay")
, ("UZ", "Uzbekistan")
, ("VU", "Vanuatu")
, ("VE", "Venezuela, Bolivarian Republic of")
, ("VN", "Viet Nam")
, ("VG", "Virgin Islands, British")
, ("VI", "Virgin Islands, U.S.")
, ("WF", "Wallis and Futuna")
, ("EH", "Western Sahara")
, ("YE", "Yemen")
, ("ZM", "Zambia")
, ("ZW", "Zimbabwe")
]
|
DataStewardshipPortal/ds-elixir-cz
|
FormStructure/Countries.hs
|
Haskell
|
apache-2.0
| 6,814
|
module HuttonSScript where
import HERMIT.API
script :: Shell ()
script = return ()
|
ku-fpg/better-life
|
examples/HERMIT/HuttonSScript.hs
|
Haskell
|
bsd-2-clause
| 85
|
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-}
{-|
Module : Numeric.AERN.RmToRn.Plot.FnView.State
Description : internal state of a FnView widget
Copyright : (c) Michal Konecny
License : BSD3
Maintainer : mikkonecny@gmail.com
Stability : experimental
Portability : portable
Internal module for FnView.
Internal state of a FnView widget.
-}
module Numeric.AERN.RmToRn.Plot.FnView.State
--(
--)
where
import Numeric.AERN.RmToRn.Plot.FnView.FnData
import Numeric.AERN.RmToRn.Plot.Params
import Numeric.AERN.RmToRn.Domain
import qualified Numeric.AERN.RealArithmetic.RefinementOrderRounding as ArithInOut
import qualified Numeric.AERN.RefinementOrder as RefOrd
data FnViewState f =
FnViewState
{
favstActiveFns :: [[Bool]],
favstTrackingDefaultEvalPt :: Bool,
favstCanvasParams :: CanvasParams (Domain f),
favstZoomPercent :: Double,
favstPanCentre :: (Domain f, Domain f)
}
initState ::
(ArithInOut.RoundedReal (Domain f))
=>
(ArithInOut.RoundedRealEffortIndicator (Domain f)) ->
(t, FnMetaData f) ->
FnViewState f
initState effReal (_, fnmeta) =
FnViewState
{
favstActiveFns = activeFns,
favstTrackingDefaultEvalPt = True,
favstCanvasParams =
(dataDefaultCanvasParams fnmeta)
{
cnvprmCoordSystem =
linearCoordsWithZoomAndCentre effReal defaultZoom centre $
getFnExtents fnmeta
},
favstZoomPercent = defaultZoom,
favstPanCentre = centre
}
where
centre = getDefaultCentre effReal fnmeta
activeFns = mergeDefaults (mergeDefaults $ \ _a b -> b) allTrue $ dataDefaultActiveFns fnmeta
allTrue = map (map $ const True) $ dataFnNames fnmeta
mergeDefaults :: (a -> a -> a) -> [a] -> [a] -> [a]
mergeDefaults _ [] _ = []
mergeDefaults _ list1 [] = list1
mergeDefaults mergeElems (h1:t1) (h2:t2) =
(mergeElems h1 h2) : (mergeDefaults mergeElems t1 t2)
updateShowAxes ::
Bool ->
(FnViewState f) ->
(FnViewState f)
updateShowAxes showAxes state =
state
{
favstCanvasParams =
(favstCanvasParams state)
{ cnvprmShowAxes = showAxes }
}
updateFontSize ::
Maybe Double ->
(FnViewState f) ->
(FnViewState f)
updateFontSize maybeFontSize state =
state
{
favstCanvasParams =
(favstCanvasParams state)
{ cnvprmShowSampleValuesFontSize = maybeFontSize }
}
defaultZoom :: Double
defaultZoom = 90
updateZoomPanCentreCoordSystem ::
Double ->
(Domain f, Domain f) ->
(CoordSystem (Domain f)) ->
(FnViewState f) ->
(FnViewState f)
updateZoomPanCentreCoordSystem zoomPercent panCentre coordSystem state =
state
{
favstCanvasParams =
(favstCanvasParams state)
{ cnvprmCoordSystem = coordSystem },
favstZoomPercent = zoomPercent,
favstPanCentre = panCentre
}
updatePanCentreCoordSystem ::
(Domain f, Domain f) ->
(CoordSystem (Domain f)) ->
(FnViewState f) ->
(FnViewState f)
updatePanCentreCoordSystem = updateZoomPanCentreCoordSystem defaultZoom
updateZoomPercentAndFnExtents ::
ArithInOut.RoundedReal (Domain f)
=>
ArithInOut.RoundedRealEffortIndicator (Domain f)
-> Double
-> (Domain f, Domain f, Domain f, Domain f)
-> FnViewState f
-> FnViewState f
updateZoomPercentAndFnExtents effFromDouble zoomPercent fnExtents state =
state
{
favstCanvasParams =
(favstCanvasParams state)
{ cnvprmCoordSystem = newCoordSystem },
favstZoomPercent = zoomPercent
}
where
newCoordSystem =
case cnvprmCoordSystem (favstCanvasParams state) of
csys@(CoordSystemLogSqueeze _) ->
csys
CoordSystemLinear _ ->
linearCoordsWithZoomAndCentre effFromDouble zoomPercent centre fnExtents
centre = favstPanCentre state
updateCentreByRatio ::
(ArithInOut.RoundedReal (Domain f),
RefOrd.IntervalLike (Domain f),
Show (Domain f))
=>
(ArithInOut.RoundedRealEffortIndicator (Domain f)) ->
(Double, Double) ->
FnViewState f ->
FnViewState f
updateCentreByRatio effReal (ratX, ratY) state =
case cnvprmCoordSystem (favstCanvasParams state) of
CoordSystemLogSqueeze _ -> state
CoordSystemLinear (Rectangle hi lo l r) ->
-- unsafePrint (
-- "updateCentreByRatio: CoordSystemLinear: "
-- ++ "\n ratX = " ++ show ratX
-- ++ "; ratY = " ++ show ratY
-- ++ "\n shiftX = " ++ show shiftX
-- ++ "; shiftY = " ++ show shiftY
-- ++ "\n old cX = " ++ show cX
-- ++ "; old cY = " ++ show cY
-- ++ "\n old Rect = " ++ show (hi,lo,l,r)
-- ++ "\n new system = " ++ show coordSystem
-- ) $
state
{
favstCanvasParams =
(favstCanvasParams state)
{ cnvprmCoordSystem = coordSystem },
favstPanCentre = (shiftX cX, shiftY cY)
}
where
(cX,cY) = favstPanCentre state
shiftX a =
fst $ RefOrd.getEndpointsOut $
a <-> (ratX |<*> fnDomWidth)
shiftY a =
fst $ RefOrd.getEndpointsOut $
a <-> (ratY |<*> fnRangeHeight)
fnDomWidth =
r <-> l
fnRangeHeight =
lo <-> hi
coordSystem =
CoordSystemLinear
(Rectangle
(shiftY hi) (shiftY lo)
(shiftX l) (shiftX r))
(<->) = ArithInOut.subtrOutEff effAdd
(|<*>) = flip $ ArithInOut.mixedMultOutEff effMultDbl
effAdd =
ArithInOut.fldEffortAdd sampleDom $ ArithInOut.rrEffortField sampleDom effReal
effMultDbl =
ArithInOut.mxfldEffortMult sampleDom (1::Double) $ ArithInOut.rrEffortDoubleMixedField sampleDom effReal
sampleDom = cX
updateFnActive ::
Int ->
Int ->
Bool ->
(FnViewState f) ->
(FnViewState f)
updateFnActive fnNo dimNo isActive state =
state
{
favstActiveFns = updateDim $ favstActiveFns state
}
where
updateDim activeDims =
listUpdate fnNo activeFnDims activeDims
where
activeFnDims =
listUpdate dimNo isActive (activeDims !! fnNo)
linearCoordsWithZoom ::
(ArithInOut.RoundedReal t)
=>
ArithInOut.RoundedRealEffortIndicator t ->
Double {-^ zoom level in percent -} ->
(t,t,t,t)
{-^ upper, lower, left, right bounds of the function graph -} ->
CoordSystem t
linearCoordsWithZoom effReal zoomPercent fnExtents@(fnHI, fnLO, fnL, fnR) =
linearCoordsWithZoomAndCentre effReal zoomPercent (cX,cY) fnExtents
where
cX =
(fnL <+> fnR) </>| (2 :: Int)
cY =
(fnLO <+> fnHI) </>| (2 :: Int)
(<+>) = ArithInOut.addOutEff effAdd
(</>|) = ArithInOut.mixedDivOutEff effDivInt
effAdd =
ArithInOut.fldEffortAdd sampleDom $ ArithInOut.rrEffortField sampleDom effReal
effDivInt =
ArithInOut.mxfldEffortDiv sampleDom (1::Int) $
ArithInOut.rrEffortIntMixedField sampleDom effReal
sampleDom = fnL
linearCoordsWithZoomAndCentre ::
(ArithInOut.RoundedReal t)
=>
ArithInOut.RoundedRealEffortIndicator t ->
Double {-^ zoom level in percent -} ->
(t, t) {-^ x,y coordinates of the centre -} ->
(t, t, t, t)
{-^ upper, lower, left, right bounds of the function graph -} ->
CoordSystem (t)
linearCoordsWithZoomAndCentre effReal zoomPercent (cX,cY) (fnHI, fnLO, fnL, fnR) =
CoordSystemLinear $ Rectangle hi lo l r
where
hi =
cY <+> heighHalf
lo =
cY <-> heighHalf
l =
cX <-> widthHalf
r =
cX <+> widthHalf
heighHalf =
zoomRatio |<*> fnHeightHalf
widthHalf =
zoomRatio |<*> fnWidthHalf
zoomRatio = 100 / zoomPercent
fnWidthHalf =
(fnR <-> fnL) </>| (2 :: Int)
fnHeightHalf =
(fnHI <-> fnLO) </>| (2 :: Int)
(<+>) = ArithInOut.addOutEff effAdd
(<->) = ArithInOut.subtrOutEff effAdd
(|<*>) = flip $ ArithInOut.mixedMultOutEff effMultDbl
(</>|) = ArithInOut.mixedDivOutEff effDivInt
effAdd =
ArithInOut.fldEffortAdd sampleDom $ ArithInOut.rrEffortField sampleDom effReal
effMultDbl =
ArithInOut.mxfldEffortMult sampleDom (1::Double) $
ArithInOut.rrEffortDoubleMixedField sampleDom effReal
effDivInt =
ArithInOut.mxfldEffortDiv sampleDom (1::Int) $
ArithInOut.rrEffortIntMixedField sampleDom effReal
sampleDom = cX
listUpdate :: Int -> a -> [a] -> [a]
listUpdate _ _ [] = error "FV: listUpdate: invalid index"
listUpdate i newx (x:xs)
| i == 0 = newx : xs
| i > 0 = x : (listUpdate (i - 1) newx xs)
| otherwise = error "FV: listUpdate: invalid index"
|
michalkonecny/aern
|
aern-realfn-plot-gtk/src/Numeric/AERN/RmToRn/Plot/FnView/State.hs
|
Haskell
|
bsd-3-clause
| 9,417
|
module Sesyrel.FaultTree.Elimination (findOrdering, pretend, Algorithm(..)) where
import Sesyrel.FaultTree.Base (Variable)
import Data.Function (on)
import Data.Foldable
import Data.Maybe (fromMaybe)
import Data.List (partition)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.Set (Set)
import qualified Data.Set as S
type Clique = Set Variable
type Graph = Map Variable (Set Variable)
data Algorithm = GraphMinFill | GraphMinNeighbors
pretend :: [Variable] -> [[Variable]] -> [[[Variable]]]
pretend vs = map (map S.toList) . pretend' vs . map S.fromList
pretend' :: [Variable] -> [Clique] -> [[Clique]]
pretend' [] cliques = [cliques]
pretend' (v : vs) cliques =
let (c, rest) = escapeClique v cliques
in cliques : pretend' vs (if null c then rest else c : rest)
escapeClique :: Variable -> [Clique] -> (Clique, [Clique])
escapeClique v cliques =
let (yes, no) = partition (elem v) cliques
c = S.delete v $ fold yes
in (c, no)
findOrdering :: Maybe Algorithm -> [Variable] -> [[Variable]] -> [(Variable, Int)]
findOrdering alg vs cs = findOrdering' alg (S.fromList vs) $ map S.fromList cs
findOrdering' :: Maybe Algorithm -> Set Variable -> [Clique] -> [(Variable, Int)]
findOrdering' Nothing = findOrdering' (Just GraphMinNeighbors)
findOrdering' (Just GraphMinFill) = findGraphOrdering costFunctionMinFill
findOrdering' (Just GraphMinNeighbors) = findGraphOrdering costFunctionMinNeighbors
findGraphOrdering :: (Graph -> Variable -> Int) -> Set Variable -> [Clique] -> [(Variable, Int)]
findGraphOrdering costFunction vars cliques = go vars (makeGraph cliques)
where
go vs g | S.null vs = []
| otherwise = let v = getNextVertex (costFunction g) vs
(g', sz) = removeVertex v g
in v `seq` sz `seq` ((v, sz) : go (S.delete v vs) g')
getNextVertex :: (Variable -> Int) -> Set Variable -> Variable
getNextVertex f vs = let costs = S.mapMonotonic (\v -> (v, f v)) vs
in fst $ minimumBy (compare `on` snd) costs
addClique :: Graph -> Clique -> Graph
addClique graph clique = foldl' (flip addEdge) graph edges
where
f = S.toList clique
edges = [(v1, v2) | v1 <- f, v2 <- f, v1 /= v2]
addEdge :: (Variable, Variable) -> Graph -> Graph
addEdge (a, b) = M.insertWith S.union a (S.singleton b)
removeEdge :: (Variable, Variable) -> Graph -> Graph
removeEdge (a, b) = M.adjust (S.delete b) a
removeVertex :: Variable -> Graph -> (Graph, Int)
removeVertex a g = let ns = fromMaybe S.empty (M.lookup a g)
sz = length ns
in ((`addClique` ns) . M.delete a $ foldl' (\g' b -> removeEdge (b, a) $ removeEdge (a, b) g') g ns, sz)
makeGraph :: [Clique] -> Graph
makeGraph cliques = foldl' addClique M.empty cliques
costFunctionMinFill :: Graph -> Variable -> Int
costFunctionMinFill g v =
let neighs = fromMaybe S.empty (M.lookup v g)
edgeNum k = S.size $ S.difference neighs (g M.! k)
in sum . map edgeNum . S.toList $ neighs
costFunctionMinNeighbors :: Graph -> Variable -> Int
costFunctionMinNeighbors g v = S.size . fromMaybe S.empty . M.lookup v $ g
|
balodja/sesyrel
|
src/Sesyrel/FaultTree/Elimination.hs
|
Haskell
|
bsd-3-clause
| 3,159
|
import TCPServer(setupSocket)
import Prelude hiding (lookup)
import Network.Socket
import NaiveHttpRequestParser(naiveHttpRequestParser, Request(..), RequestType(..))
import Control.Concurrent(forkIO, threadDelay, MVar, newMVar, takeMVar, putMVar)
import Control.Monad(forM_, forever)
import Data.Map.Strict(Map, empty, lookup, insert)
newtype Database = Database (MVar (Map String String) )
createDB :: IO Database
createDB = Database <$> newMVar empty
threadPoolSize :: Int
threadPoolSize = 5000
main :: IO ()
main = do
listeningSocket <- setupSocket 3001
db <- createDB
forM_ [1..threadPoolSize] $ \num -> do
putStrLn $ "Forking thread " ++ show num
forkIO (runServer db num listeningSocket)
forever (threadDelay 10000000)
runServer :: Database -> Int -> Socket -> IO ()
runServer database num socket =
forever $ do
(connection, _) <- accept socket
erequest <- naiveHttpRequestParser <$> recv connection 4096
case erequest of
Right (Request GET _ path _) -> do
result <- runQuery path database
send connection result
Right (Request POST body _ _) -> do
newStore <- storeParams database body
send connection ("" ++ show newStore)
Left _ -> send connection "Invalid response"
close connection
runQuery :: String -> Database -> IO String
runQuery path (Database mvar) = do
db <- takeMVar mvar
putMVar mvar db
case lookup path db of
Just value -> return $ "Retrieved Value: " ++ value
Nothing -> return $ "No Value stored at: " ++ path
storeParams ::Database -> [(String, String)] -> IO ()
storeParams (Database mvar) params = do
db <- takeMVar mvar
let newDB = foldr (\(key, val) storage -> insert key val storage) db params
putMVar mvar newDB
|
jvans1/haskell_servers
|
src/ThreadPool.hs
|
Haskell
|
bsd-3-clause
| 1,758
|
-----------------------------------------------------------------------------
-- |
-- Module : Data.SBV.Provers.SExpr
-- Copyright : (c) Levent Erkok
-- License : BSD3
-- Maintainer : erkokl@gmail.com
-- Stability : experimental
--
-- Parsing of S-expressions (mainly used for parsing SMT-Lib get-value output)
-----------------------------------------------------------------------------
module Data.SBV.Provers.SExpr where
import Data.Char (isDigit, ord)
import Data.List (isPrefixOf)
import Numeric (readInt, readDec, readHex, fromRat)
import Data.SBV.BitVectors.AlgReals
import Data.SBV.BitVectors.Data (nan, infinity)
-- | ADT S-Expression format, suitable for representing get-model output of SMT-Lib
data SExpr = ECon String
| ENum Integer
| EReal AlgReal
| EFloat Float
| EDouble Double
| EApp [SExpr]
deriving Show
-- | Parse a string into an SExpr, potentially failing with an error message
parseSExpr :: String -> Either String SExpr
parseSExpr inp = do (sexp, extras) <- parse inpToks
if null extras
then return sexp
else die "Extra tokens after valid input"
where inpToks = let cln "" sofar = sofar
cln ('(':r) sofar = cln r (" ( " ++ sofar)
cln (')':r) sofar = cln r (" ) " ++ sofar)
cln (':':':':r) sofar = cln r (" :: " ++ sofar)
cln (c:r) sofar = cln r (c:sofar)
in reverse (map reverse (words (cln inp "")))
die w = fail $ "SBV.Provers.SExpr: Failed to parse S-Expr: " ++ w
++ "\n*** Input : <" ++ inp ++ ">"
parse [] = die "ran out of tokens"
parse ("(":toks) = do (f, r) <- parseApp toks []
f' <- cvt (EApp f)
return (f', r)
parse (")":_) = die "extra tokens after close paren"
parse [tok] = do t <- pTok tok
return (t, [])
parse _ = die "ill-formed s-expr"
parseApp [] _ = die "failed to grab s-expr application"
parseApp (")":toks) sofar = return (reverse sofar, toks)
parseApp ("(":toks) sofar = do (f, r) <- parse ("(":toks)
parseApp r (f : sofar)
parseApp (tok:toks) sofar = do t <- pTok tok
parseApp toks (t : sofar)
pTok "false" = return $ ENum 0
pTok "true" = return $ ENum 1
pTok ('0':'b':r) = mkNum $ readInt 2 (`elem` "01") (\c -> ord c - ord '0') r
pTok ('b':'v':r) = mkNum $ readDec (takeWhile (/= '[') r)
pTok ('#':'b':r) = mkNum $ readInt 2 (`elem` "01") (\c -> ord c - ord '0') r
pTok ('#':'x':r) = mkNum $ readHex r
pTok n
| not (null n) && isDigit (head n)
= if '.' `elem` n then getReal n
else mkNum $ readDec n
pTok n = return $ ECon n
mkNum [(n, "")] = return $ ENum n
mkNum _ = die "cannot read number"
getReal n = return $ EReal $ mkPolyReal (Left (exact, n'))
where exact = not ("?" `isPrefixOf` reverse n)
n' | exact = n
| True = init n
-- simplify numbers and root-obj values
cvt (EApp [ECon "/", EReal a, EReal b]) = return $ EReal (a / b)
cvt (EApp [ECon "/", EReal a, ENum b]) = return $ EReal (a / fromInteger b)
cvt (EApp [ECon "/", ENum a, EReal b]) = return $ EReal (fromInteger a / b)
cvt (EApp [ECon "/", ENum a, ENum b]) = return $ EReal (fromInteger a / fromInteger b)
cvt (EApp [ECon "-", EReal a]) = return $ EReal (-a)
cvt (EApp [ECon "-", ENum a]) = return $ ENum (-a)
-- bit-vector value as CVC4 prints: (_ bv0 16) for instance
cvt (EApp [ECon "_", ENum a, ENum _b]) = return $ ENum a
cvt (EApp [ECon "root-obj", EApp (ECon "+":trms), ENum k]) = do ts <- mapM getCoeff trms
return $ EReal $ mkPolyReal (Right (k, ts))
cvt (EApp [ECon "as", n, EApp [ECon "_", ECon "FP", ENum 11, ENum 53]]) = getDouble n
cvt (EApp [ECon "as", n, EApp [ECon "_", ECon "FP", ENum 8, ENum 24]]) = getFloat n
cvt x = return x
getCoeff (EApp [ECon "*", ENum k, EApp [ECon "^", ECon "x", ENum p]]) = return (k, p) -- kx^p
getCoeff (EApp [ECon "*", ENum k, ECon "x" ] ) = return (k, 1) -- kx
getCoeff ( EApp [ECon "^", ECon "x", ENum p] ) = return (1, p) -- x^p
getCoeff ( ECon "x" ) = return (1, 1) -- x
getCoeff ( ENum k ) = return (k, 0) -- k
getCoeff x = die $ "Cannot parse a root-obj,\nProcessing term: " ++ show x
getDouble (ECon s) = case (s, rdFP (dropWhile (== '+') s)) of
("plusInfinity", _ ) -> return $ EDouble infinity
("minusInfinity", _ ) -> return $ EDouble (-infinity)
("NaN", _ ) -> return $ EDouble nan
(_, Just v) -> return $ EDouble v
_ -> die $ "Cannot parse a double value from: " ++ s
getDouble (EReal r) = return $ EDouble $ fromRat $ toRational r
getDouble x = die $ "Cannot parse a double value from: " ++ show x
getFloat (ECon s) = case (s, rdFP (dropWhile (== '+') s)) of
("plusInfinity", _ ) -> return $ EFloat infinity
("minusInfinity", _ ) -> return $ EFloat (-infinity)
("NaN", _ ) -> return $ EFloat nan
(_, Just v) -> return $ EFloat v
_ -> die $ "Cannot parse a float value from: " ++ s
getFloat (EReal r) = return $ EFloat $ fromRat $ toRational r
getFloat x = die $ "Cannot parse a float value from: " ++ show x
-- | Parses the Z3 floating point formatted numbers like so: 1.321p5/1.2123e9 etc.
rdFP :: (Read a, RealFloat a) => String -> Maybe a
rdFP s = case break (`elem` "pe") s of
(m, 'p':e) -> rd m >>= \m' -> rd e >>= \e' -> return $ m' * ( 2 ** e')
(m, 'e':e) -> rd m >>= \m' -> rd e >>= \e' -> return $ m' * (10 ** e')
(m, "") -> rd m
_ -> Nothing
where rd v = case reads v of
[(n, "")] -> Just n
_ -> Nothing
|
TomMD/cryptol
|
sbv/Data/SBV/Provers/SExpr.hs
|
Haskell
|
bsd-3-clause
| 7,211
|
module Arhelk.Russian.Lemma.Adverb(
adverb
) where
import Arhelk.Core.Rule
import Arhelk.Russian.Lemma.Common
import Arhelk.Russian.Lemma.Data
import Control.Monad
import Data.Text as T
adverb :: Text -> Rule AdverbProperties
adverb w = do
when (w `endsWith` ["о"]) $ imply adverbDegree PositiveDegree
when (w `endsWith` ["е"]) $ imply adverbDegree ComparitiveDegree
|
Teaspot-Studio/arhelk-russian
|
src/Arhelk/Russian/Lemma/Adverb.hs
|
Haskell
|
bsd-3-clause
| 382
|
{-# LANGUAGE ScopedTypeVariables, RecursiveDo #-}
import Data.Char
import System.Environment
import Control.Applicative
import Text.Earley
data Expr
= Expr :+: Expr
| Expr :*: Expr
| Var String
| Lit Int
deriving (Show)
grammar :: forall r. Grammar r String (Prod r String Char Expr)
grammar = mdo
whitespace <- rule $ many $ satisfy isSpace
let token :: Prod r String Char a -> Prod r String Char a
token p = whitespace *> p
sym x = token $ symbol x <?> [x]
ident = token $ (:) <$> satisfy isAlpha <*> many (satisfy isAlphaNum) <?> "identifier"
num = token $ some (satisfy isDigit) <?> "number"
expr0 <- rule
$ (Lit . read) <$> num
<|> Var <$> ident
<|> sym '(' *> expr2 <* sym ')'
expr1 <- rule
$ (:*:) <$> expr1 <* sym '*' <*> expr0
<|> expr0
expr2 <- rule
$ (:+:) <$> expr2 <* sym '+' <*> expr1
<|> expr1
return $ expr2 <* whitespace
main :: IO ()
main = do
x:_ <- getArgs
print $ fullParses $ parser grammar x
|
Axure/Earley
|
examples/Expr2.hs
|
Haskell
|
bsd-3-clause
| 1,013
|
{-
SkewHeap.hs
by Russell Bentley
A Haskell Implementation of a skew heap.
-}
module SkewHeap (Heap, emptyHeap, merge, insert, delete, minKey, minKeyValue, deleteMin ) where
-- | A binary tree data type.
data Heap k v = Nil | Node (k, v) (Heap k v) (Heap k v)
-- | Blank
emptyHeap :: Heap k v
emptyHeap = Nil
-- | The 'merge' function merges two scew heaps.
merge :: Ord k => Heap k v -> Heap k v -> Heap k v
merge t1 Nil = t1
merge Nil t2 = t2
merge (Node (k1, v1) lt1 rt1) (Node (k2, v2) lt2 rt2) = case compare k1 k2 of
LT -> Node (k1, v1) (merge rt1 (Node (k2, v2) lt2 rt2)) lt1
EQ -> Node (k1, v1) (merge rt1 (Node (k2, v2) lt2 rt2)) lt1
GT -> Node (k2, v2) (merge rt2 (Node (k1, v1) lt1 rt1)) lt2
-- | The insert method is used to put an element in the heap.
insert :: Ord k => (k, v) -> Heap k v -> Heap k v
insert (k, v) = merge (Node (k, v) Nil Nil)
-- | The `delete` method removes an element from a heap.
delete :: Ord k => k -> Heap k v -> Heap k v
delete _ Nil = Nil
delete k1 (Node (k2, v) tl tr) = case compare k1 k2 of
LT -> Node (k2, v) (delete k1 tl) (delete k1 tr)
GT -> Node (k2, v) tl tr
EQ -> tl `merge` tr
-- | NOTE! pattern mathing is non-exhaustive
minKey :: Heap k v -> k
minKey (Node (k, _) _ _) = k
-- | NOTE! pattern mathing is non-exhaustive
minKeyValue :: Heap k v -> (k, v)
minKeyValue (Node (k,v) _ _) = (k, v)
-- | Consider adding a deleteMinandInsert
deleteMin :: Ord k => Heap k v -> Heap k v
deleteMin Nil = Nil
deleteMin (Node _ tl tr) = tl `merge` tr
|
ThermalSpan/haskell-euler
|
src/SkewHeap.hs
|
Haskell
|
bsd-3-clause
| 1,914
|
-- | A module to contain the magnitude of s-expression parsing.
module Data.AttoLisp.Easy
(fromLispString
,module L)
where
import qualified Data.AttoLisp as L
import qualified Data.Attoparsec as P
import qualified Data.ByteString as B
-- | Parse a single s-expr followed by optional whitespace and end of
-- file.
parseLispOnly :: B.ByteString -> Either String L.Lisp
parseLispOnly b =
case P.parseOnly lisp b of
Left err -> Left ("Bad s-expression: " ++ err)
Right ok -> Right ok
where
lisp = L.lisp
-- | Parse a single s-expr.
fromLispString :: L.FromLisp a => B.ByteString -> Either String a
fromLispString str = L.parseEither L.parseLisp =<< parseLispOnly str
|
kini/ghc-server
|
src/Data/AttoLisp/Easy.hs
|
Haskell
|
bsd-3-clause
| 725
|
main = print (foldl lcm 1 [1 .. 20])
|
foreverbell/project-euler-solutions
|
src/5.hs
|
Haskell
|
bsd-3-clause
| 36
|
-- | This module performs the translation of a parsed XML DTD into the
-- internal representation of corresponding Haskell data\/newtypes.
module Text.XML.HaXml.DtdToHaskell.Convert
( dtd2TypeDef
) where
import List (intersperse)
import Text.XML.HaXml.Types hiding (Name)
import Text.XML.HaXml.DtdToHaskell.TypeDef
---- Internal representation for database of DTD decls ----
data Record = R [AttDef] ContentSpec
type Db = [(String,Record)]
---- Build a database of DTD decls then convert them to typedefs ----
---- (Done in two steps because we need to merge ELEMENT and ATTLIST decls.)
---- Apparently multiple ATTLIST decls for the same element are permitted,
---- although only one ELEMENT decl for it is allowed.
dtd2TypeDef :: [MarkupDecl] -> [TypeDef]
dtd2TypeDef mds =
(concatMap convert . reverse . database []) mds
where
database db [] = db
database db (m:ms) =
case m of
(Element (ElementDecl n cs)) ->
case lookup n db of
Nothing -> database ((n, R [] cs):db) ms
(Just (R as _)) -> database (replace n (R as cs) db) ms
(AttList (AttListDecl n as)) ->
case lookup n db of
Nothing -> database ((n, R as EMPTY):db) ms
(Just (R a cs)) -> database (replace n (R (a++as) cs) db) ms
-- (MarkupPE _ m') -> database db (m':ms)
_ -> database db ms
replace n v [] = error "dtd2TypeDef.replace: no element to replace"
replace n v (x@(n0,_):db)
| n==n0 = (n,v): db
| otherwise = x: replace n v db
---- Convert DTD record to typedef ----
convert :: (String, Record) -> [TypeDef]
convert (n, R as cs) =
case cs of
EMPTY -> modifier None []
ANY -> modifier None [[Any]]
--error "NYI: contentspec of ANY"
(Mixed PCDATA) -> modifier None [[String]]
(Mixed (PCDATAplus ns)) -> modifier Star ([String]: map ((:[]) . Defined . name) ns)
(ContentSpec cp) ->
case cp of
(TagName n' m) -> modifier m [[Defined (name n')]]
(Choice cps m) -> modifier m (map ((:[]).inner) cps)
(Seq cps m) -> modifier m [map inner cps]
++ concatMap (mkAttrDef n) as
where
attrs :: AttrFields
attrs = map (mkAttrField n) as
modifier None sts = mkData sts attrs False (name n)
modifier m [[st]] = mkData [[modf m st]] attrs False (name n)
modifier m sts = mkData [[modf m (Defined (name_ n))]]
attrs False (name n) ++
mkData sts [] True (name_ n)
inner :: CP -> StructType
inner (TagName n' m) = modf m (Defined (name n'))
inner (Choice cps m) = modf m (OneOf (map inner cps))
inner (Seq cps None) = Tuple (map inner cps)
inner (Seq cps m) = modf m (Tuple (map inner cps))
modf None x = x
modf Query x = Maybe x
modf Star x = List x
modf Plus x = List1 x
mkData :: [[StructType]] -> AttrFields -> Bool -> Name -> [TypeDef]
mkData [] fs aux n = [DataDef aux n fs []]
mkData [ts] fs aux n = [DataDef aux n fs [(n, ts)]]
mkData tss fs aux n = [DataDef aux n fs (map (mkConstr n) tss)]
where
mkConstr n ts = (mkConsName n ts, ts)
mkConsName (Name x n) sts = Name x (n++concat (intersperse "_" (map flatten sts)))
flatten (Maybe st) = {-"Maybe_" ++ -} flatten st
flatten (List st) = {-"List_" ++ -} flatten st
flatten (List1 st) = {-"List1_" ++ -} flatten st
flatten (Tuple sts) = {-"Tuple" ++ show (length sts) ++ "_" ++ -}
concat (intersperse "_" (map flatten sts))
flatten String = "Str"
flatten (OneOf sts) = {-"OneOf" ++ show (length sts) ++ "_" ++ -}
concat (intersperse "_" (map flatten sts))
flatten Any = "Any"
flatten (Defined (Name _ n)) = n
mkAttrDef e (AttDef n StringType def) =
[]
mkAttrDef e (AttDef n (TokenizedType t) def) =
[] -- mkData [[String]] [] False (name n)
mkAttrDef e (AttDef n (EnumeratedType (NotationType nt)) def) =
[EnumDef (name_a e n) (map (name_ac e n) nt)]
mkAttrDef e (AttDef n (EnumeratedType (Enumeration es)) def) =
[EnumDef (name_a e n) (map (name_ac e n) es)]
-- Default attribute values not handled here
mkAttrField :: String -> AttDef -> (Name,StructType)
mkAttrField e (AttDef n typ req) = (name_f e n, mkType typ req)
where
mkType StringType REQUIRED = String
mkType StringType IMPLIED = Maybe String
mkType StringType (DefaultTo (AttValue [Left s]) f) = Defaultable String s
mkType (TokenizedType _) REQUIRED = String
mkType (TokenizedType _) IMPLIED = Maybe String
mkType (TokenizedType _) (DefaultTo (AttValue [Left s]) f) =
Defaultable String s
mkType (EnumeratedType _) REQUIRED = Defined (name_a e n)
mkType (EnumeratedType _) IMPLIED = Maybe (Defined (name_a e n))
mkType (EnumeratedType _) (DefaultTo (AttValue [Left s]) f) =
Defaultable (Defined (name_a e n)) (hName (name_ac e n s))
|
FranklinChen/hugs98-plus-Sep2006
|
packages/HaXml/src/Text/XML/HaXml/DtdToHaskell/Convert.hs
|
Haskell
|
bsd-3-clause
| 5,118
|
{-# LANGUAGE OverloadedStrings #-}
module Templates.Home where
import Core
import Templates
import Templates.CoreForm
import Data.Int
import Text.Blaze ((!))
import qualified Text.Blaze.Html4.Strict as H
import qualified Text.Blaze.Html4.Strict.Attributes as A
homeHtml :: CoreId -> H.Html
homeHtml nbCores = template "core-online: easily generate and share GHC Core for your haskell codeo"
[]
((H.h1 ! A.class_ "header" $ "core-online - get the GHC Core for your haskell code and share it")
>>
(H.p $ coreForm)
>>
(H.p ! A.class_ "footer" $ do
"The database currently contains "
>>
(H.b . H.toHtml $ show nbCores)
>>
" cores.")
)
|
alpmestan/core-online
|
src/Templates/Home.hs
|
Haskell
|
bsd-3-clause
| 941
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{- | The replay monad, for computations that can be replayed using traces
Example usage:
> running :: Replay Question Answer a -> IO a
> running prog = play emptyTrace
> where
> play t = do
> (eqa,t') <- run prog t this is the same prog every time!
> case eqa of
> Left q -> do
> putStr ("Question: " ++ q ++ " ")
> r <- getLine
> play (addAnswer t' r)
> Right x -> return x
>
> askAge :: Replay String String Int
> askAge = cut $ do
> birth <- ask "What is your birth year?"
> now <- ask "What is the current year?"
> return (read now - read birth)
>
> getTime :: IO Integer
> getTime = do
> TOD secs _ <- getClockTime
> return secs
>
> example1 :: Replay Question Answer Int
> example1 = do
> t0 <- lift getTime
> lift (putStrLn "Hello!")
> age <- ask "What is your age?"
> lift (putStrLn ("You are " ++ age))
> name <- ask "What is your name?"
> lift (putStrLn (name ++ " is " ++ age ++ " years old"))
> t1 <- lift getTime
> lift (putStrLn ("Total time: " ++ show (t1 - t0) ++ " seconds"))
> return (read age)
>
> example2 :: Replay Question Answer Int
> example2 = do
> t0 <- lift getTime
> age <- askAge
> lift (putStrLn ("You are " ++ (show age)))
> name <- ask "What is your name?"
> lift (putStrLn (name ++ " is " ++ (show age) ++ " years old"))
> t1 <- lift getTime
> lift (putStrLn ("Total time: " ++ show (t1 - t0) ++ " seconds"))
> return age
>
-}
module Control.Monad.Replay
( Replay, lift, ask, run, cut
, emptyTrace, addAnswer
, Trace, Question, Answer, Item(..)) where
import Control.Monad
import Control.Monad.Error (ErrorT)
import qualified Control.Monad.Error as CME
import Control.Monad.IO.Class
import Control.Monad.Supply
import Control.Monad.Writer (WriterT)
import qualified Control.Monad.Writer as CMW
import Data.List
{- | The `Replay` monad is parametrized over two types:
* q - The type of questions (usually `String`)
* r - The type of answers (usually `String`)
-}
newtype Replay q r a = R { replay :: ErrorT q (WriterT (Trace r) (SupplyT (Item r) IO)) a }
deriving (Monad, MonadSupply (Item r), MonadIO
, CME.MonadError q, CMW.MonadWriter (Trace r))
type Trace r = [Item r]
type Question = String
type Answer = String
data Item r = Answer r
| Result String
| Cut Bool String
deriving (Show,Read)
supplyM :: MonadSupply s m => m (Maybe s)
supplyM = do
x <- exhausted
if x then return Nothing else
liftM Just supply
lift :: (CME.Error q, Show a, Read a) => IO a -> Replay q r a
lift a = do
x <- supplyM
case x of
Nothing -> do
res <- liftIO a
CMW.tell [Result (show res)]
return res
Just (Result r) -> return (read r)
Just _ -> error "Expecting result"
ask :: (CME.Error q) => q -> Replay q r r
ask q = do
x <- supplyM
case x of
Nothing -> CME.throwError q
Just (Answer a) -> return a
Just _ -> error "Expecting answer"
cut :: (Read a, Show a, CME.Error q) => Replay q r a -> Replay q r a
cut m = do
x <- supplyM
case x of
Just (Cut True r) -> return (read r)
Just (Cut False _) -> do
res <- CMW.censor (const []) m
CMW.tell [Cut True (show res)]
return res
_ -> do
CMW.tell [Cut False ""]
res <- CMW.censor (const []) m
CMW.tell [Cut True (show res)]
return res
emptyTrace :: Trace r
emptyTrace = []
addAnswer :: Trace r -> r -> Trace r
addAnswer tr t = tr ++ [Answer t]
run :: Replay q r a -> Trace r -> IO (Either q a, Trace r)
run r tr = do
(res, tr') <- evalSupplyT (CMW.runWriterT (CME.runErrorT $ replay r)) tr
return (res, filterCuts (tr ++ tr'))
isFinal :: Item r -> Bool
isFinal (Cut x _) = x
isFinal _ = False
filterCuts :: Trace r -> Trace r
filterCuts xs =
case findIndex isFinal xs of
Nothing -> xs
Just i -> filterCuts' xs i
filterCuts' :: Trace r -> Int -> Trace r
filterCuts' [] _ = []
filterCuts' ((Cut False _):xs) i = filterCuts (drop (i-1) xs)
filterCuts' (x:xs) i = x:filterCuts' xs (i-1)
|
co-dan/warm_fuzzy_things
|
src/Control/Monad/Replay.hs
|
Haskell
|
bsd-3-clause
| 4,350
|
{-
OnYourOwn1.hs (adapted from OpenGLApplication which is (c) 2004 Astle/Hawkins)
Copyright (c) Sven Panne 2004-2005 <sven.panne@aedion.de>
This file is part of HOpenGL and distributed under a BSD-style license
See the file libraries/GLUT/LICENSE
-}
import Control.Monad ( when, unless )
import Data.IORef ( IORef, newIORef )
import Data.Maybe ( isJust )
import Graphics.UI.GLUT hiding ( initialize )
import System.Console.GetOpt
import System.Environment ( getProgName )
import System.Exit ( exitWith, ExitCode(..) )
import System.IO ( hPutStr, stderr )
--------------------------------------------------------------------------------
-- Setup GLUT and OpenGL, drop into the event loop.
--------------------------------------------------------------------------------
main :: IO ()
main = do
-- Setup the basic GLUT stuff
(_, args) <- getArgsAndInitialize
opts <- parseOptions args
initialDisplayMode $= [ DoubleBuffered, RGBMode, WithDepthBuffer ]
(if useFullscreen opts then fullscreenMode else windowedMode) opts
state <- initialize
-- Register the event callback functions
displayCallback $= do render state; swapBuffers
reshapeCallback $= Just setupProjection
keyboardMouseCallback $= Just keyboardMouseHandler
idleCallback $= Just (do prepare state; postRedisplay Nothing)
-- At this point, control is relinquished to the GLUT event handler.
-- Control is returned as events occur, via the callback functions.
mainLoop
fullscreenMode :: Options -> IO ()
fullscreenMode opts = do
let addCapability c = maybe id (\x -> (Where' c IsEqualTo x :))
gameModeCapabilities $=
(addCapability GameModeWidth (Just (windowWidth opts)) .
addCapability GameModeHeight (Just (windowHeight opts)) .
addCapability GameModeBitsPerPlane (bpp opts) .
addCapability GameModeRefreshRate (refreshRate opts)) []
enterGameMode
maybeWin <- get currentWindow
if isJust maybeWin
then cursor $= None
else do
hPutStr stderr "Could not enter fullscreen mode, using windowed mode\n"
windowedMode (opts { useFullscreen = False } )
windowedMode :: Options -> IO ()
windowedMode opts = do
initialWindowSize $=
Size (fromIntegral (windowWidth opts)) (fromIntegral (windowHeight opts))
createWindow "BOGLGP - Chapter 2 - On Your Own 1"
return ()
--------------------------------------------------------------------------------
-- Option handling
--------------------------------------------------------------------------------
data Options = Options {
useFullscreen :: Bool,
windowWidth :: Int,
windowHeight :: Int,
bpp :: Maybe Int,
refreshRate :: Maybe Int
}
startOpt :: Options
startOpt = Options {
useFullscreen = False,
windowWidth = 800,
windowHeight = 600,
bpp = Nothing,
refreshRate = Nothing
}
options :: [OptDescr (Options -> IO Options)]
options = [
Option ['f'] ["fullscreen"]
(NoArg (\opt -> return opt { useFullscreen = True }))
"use fullscreen mode if possible",
Option ['w'] ["width"]
(ReqArg (\arg opt -> do w <- readInt "WIDTH" arg
return opt { windowWidth = w })
"WIDTH")
"use window width WIDTH",
Option ['h'] ["height"]
(ReqArg (\arg opt -> do h <- readInt "HEIGHT" arg
return opt { windowHeight = h })
"HEIGHT")
"use window height HEIGHT",
Option ['b'] ["bpp"]
(ReqArg (\arg opt -> do b <- readInt "BPP" arg
return opt { bpp = Just b })
"BPP")
"use BPP bits per plane (ignored in windowed mode)",
Option ['r'] ["refresh-rate"]
(ReqArg (\arg opt -> do r <- readInt "HZ" arg
return opt { refreshRate = Just r })
"HZ")
"use refresh rate HZ (ignored in windowed mode)",
Option ['?'] ["help"]
(NoArg (\_ -> do usage >>= putStr
safeExitWith ExitSuccess))
"show help" ]
readInt :: String -> String -> IO Int
readInt name arg =
case reads arg of
((x,[]) : _) -> return x
_ -> dieWith ["Can't parse " ++ name ++ " argument '" ++ arg ++ "'\n"]
usage :: IO String
usage = do
progName <- getProgName
return $ usageInfo ("Usage: " ++ progName ++ " [OPTION...]") options
parseOptions :: [String] -> IO Options
parseOptions args = do
let (optsActions, nonOptions, errs) = getOpt Permute options args
unless (null nonOptions && null errs) (dieWith errs)
foldl (>>=) (return startOpt) optsActions
dieWith :: [String] -> IO a
dieWith errs = do
u <- usage
mapM_ (hPutStr stderr) (errs ++ [u])
safeExitWith (ExitFailure 1)
--------------------------------------------------------------------------------
-- Handle mouse and keyboard events. For this simple demo, just exit when
-- ESCAPE is pressed.
--------------------------------------------------------------------------------
keyboardMouseHandler :: KeyboardMouseCallback
keyboardMouseHandler (Char '\27') Down _ _ = safeExitWith ExitSuccess
keyboardMouseHandler _ _ _ _ = return ()
safeExitWith :: ExitCode -> IO a
safeExitWith code = do
gma <- get gameModeActive
when gma leaveGameMode
exitWith code
--------------------------------------------------------------------------------
-- The globale state, which is only the current angle in this simple demo.
-- We don't need the window dimensions here, they are not used and would
-- be easily available via GLUT anyway.
--------------------------------------------------------------------------------
data State = State { angle :: IORef GLfloat }
makeState :: IO State
makeState = do
a <- newIORef 0
return $ State { angle = a }
--------------------------------------------------------------------------------
-- Do one time setup, i.e. set the clear color and create the global state.
--------------------------------------------------------------------------------
initialize :: IO State
initialize = do
-- clear to white background
clearColor $= Color4 1 1 1 0
makeState
--------------------------------------------------------------------------------
-- Reset the viewport for window changes.
--------------------------------------------------------------------------------
setupProjection :: ReshapeCallback
setupProjection (Size width height) = do
-- don't want a divide by zero
let h = max 1 height
-- reset the viewport to new dimensions
viewport $= (Position 0 0, Size width h)
-- set projection matrix as the current matrix
matrixMode $= Projection
-- reset projection matrix
loadIdentity
-- calculate aspect ratio of window
perspective 52 (fromIntegral width / fromIntegral h) 1 1000
-- set modelview matrix
matrixMode $= Modelview 0
-- reset modelview matrix
loadIdentity
--------------------------------------------------------------------------------
-- Perform any data-specific updates for a frame. Here we only increment the
-- angle for the rotation of the triangle.
--------------------------------------------------------------------------------
prepare :: State -> IdleCallback
prepare state = do
angle state $~ (+ 0.1)
--------------------------------------------------------------------------------
-- Clear and redraw the scene.
--------------------------------------------------------------------------------
render :: State -> DisplayCallback
render state = do
-- clear screen and depth buffer
clear [ ColorBuffer, DepthBuffer ]
loadIdentity
-- resolve overloading, not needed in "real" programs
let translate3f = translate :: Vector3 GLfloat -> IO ()
color3f = color :: Color3 GLfloat -> IO ()
vertex3f = vertex :: Vertex3 GLfloat -> IO ()
-- move back 5 units and rotate about all 3 axes
translate3f (Vector3 0 0 (-5))
a <- get (angle state)
rotate a (Vector3 1 0 0)
rotate a (Vector3 0 1 0)
rotate a (Vector3 0 0 1)
-- red color
color3f (Color3 1 0 0)
-- draw the triangle such that the rotation point is in the center
renderPrimitive Triangles $ do
vertex3f (Vertex3 1 (-1) 0)
vertex3f (Vertex3 (-1) (-1) 0)
vertex3f (Vertex3 0 1 0)
|
FranklinChen/hugs98-plus-Sep2006
|
packages/GLUT/examples/BOGLGP/Chapter02/OnYourOwn1.hs
|
Haskell
|
bsd-3-clause
| 8,277
|
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-}
module ETA.Iface.BuildTyCl (
buildSynonymTyCon,
buildFamilyTyCon,
buildAlgTyCon,
buildDataCon,
buildPatSyn,
TcMethInfo, buildClass,
distinctAbstractTyConRhs, totallyAbstractTyConRhs,
mkNewTyConRhs, mkDataTyConRhs,
newImplicitBinder
) where
import ETA.Iface.IfaceEnv
import ETA.Types.FamInstEnv( FamInstEnvs )
import ETA.BasicTypes.DataCon
import ETA.BasicTypes.PatSyn
import ETA.BasicTypes.Var
import ETA.BasicTypes.VarSet
import ETA.BasicTypes.BasicTypes
import ETA.BasicTypes.Name
import ETA.BasicTypes.MkId
import ETA.Types.Class
import ETA.Types.TyCon
import ETA.Types.Type
import ETA.BasicTypes.Id
import ETA.Types.Coercion
import ETA.TypeCheck.TcType
import ETA.Main.DynFlags
import ETA.TypeCheck.TcRnMonad
import ETA.BasicTypes.UniqSupply
import ETA.Utils.Util
import ETA.Utils.Outputable
------------------------------------------------------
buildSynonymTyCon :: Name -> [TyVar] -> [Role]
-> Type
-> Kind -- ^ Kind of the RHS
-> TcRnIf m n TyCon
buildSynonymTyCon tc_name tvs roles rhs rhs_kind
= return (mkSynonymTyCon tc_name kind tvs roles rhs)
where kind = mkPiKinds tvs rhs_kind
buildFamilyTyCon :: Name -> [TyVar]
-> FamTyConFlav
-> Kind -- ^ Kind of the RHS
-> TyConParent
-> TcRnIf m n TyCon
buildFamilyTyCon tc_name tvs rhs rhs_kind parent
= return (mkFamilyTyCon tc_name kind tvs rhs parent)
where kind = mkPiKinds tvs rhs_kind
------------------------------------------------------
distinctAbstractTyConRhs, totallyAbstractTyConRhs :: AlgTyConRhs
distinctAbstractTyConRhs = AbstractTyCon True
totallyAbstractTyConRhs = AbstractTyCon False
mkDataTyConRhs :: [DataCon] -> AlgTyConRhs
mkDataTyConRhs cons
= DataTyCon {
data_cons = cons,
is_enum = not (null cons) && all is_enum_con cons
-- See Note [Enumeration types] in TyCon
}
where
is_enum_con con
| (_tvs, theta, arg_tys, _res) <- dataConSig con
= null theta && null arg_tys
mkNewTyConRhs :: Name -> TyCon -> DataCon -> TcRnIf m n AlgTyConRhs
-- ^ Monadic because it makes a Name for the coercion TyCon
-- We pass the Name of the parent TyCon, as well as the TyCon itself,
-- because the latter is part of a knot, whereas the former is not.
mkNewTyConRhs tycon_name tycon con
= do { co_tycon_name <- newImplicitBinder tycon_name mkNewTyCoOcc
; let co_tycon = mkNewTypeCo co_tycon_name tycon etad_tvs etad_roles etad_rhs
; traceIf (text "mkNewTyConRhs" <+> ppr co_tycon)
; return (NewTyCon { data_con = con,
nt_rhs = rhs_ty,
nt_etad_rhs = (etad_tvs, etad_rhs),
nt_co = co_tycon } ) }
-- Coreview looks through newtypes with a Nothing
-- for nt_co, or uses explicit coercions otherwise
where
tvs = tyConTyVars tycon
roles = tyConRoles tycon
inst_con_ty = applyTys (dataConUserType con) (mkTyVarTys tvs)
rhs_ty = {-ASSERT( isFunTy inst_con_ty )-} funArgTy inst_con_ty
-- Instantiate the data con with the
-- type variables from the tycon
-- NB: a newtype DataCon has a type that must look like
-- forall tvs. <arg-ty> -> T tvs
-- Note that we *can't* use dataConInstOrigArgTys here because
-- the newtype arising from class Foo a => Bar a where {}
-- has a single argument (Foo a) that is a *type class*, so
-- dataConInstOrigArgTys returns [].
etad_tvs :: [TyVar] -- Matched lazily, so that mkNewTypeCo can
etad_roles :: [Role] -- return a TyCon without pulling on rhs_ty
etad_rhs :: Type -- See Note [Tricky iface loop] in LoadIface
(etad_tvs, etad_roles, etad_rhs) = eta_reduce (reverse tvs) (reverse roles) rhs_ty
eta_reduce :: [TyVar] -- Reversed
-> [Role] -- also reversed
-> Type -- Rhs type
-> ([TyVar], [Role], Type) -- Eta-reduced version
-- (tyvars in normal order)
eta_reduce (a:as) (_:rs) ty | Just (fun, arg) <- splitAppTy_maybe ty,
Just tv <- getTyVar_maybe arg,
tv == a,
not (a `elemVarSet` tyVarsOfType fun)
= eta_reduce as rs fun
eta_reduce tvs rs ty = (reverse tvs, reverse rs, ty)
------------------------------------------------------
buildDataCon :: FamInstEnvs
-> Name -> Bool
-> [HsBang]
-> [Name] -- Field labels
-> [TyVar] -> [TyVar] -- Univ and ext
-> [(TyVar,Type)] -- Equality spec
-> ThetaType -- Does not include the "stupid theta"
-- or the GADT equalities
-> [Type] -> Type -- Argument and result types
-> TyCon -- Rep tycon
-> TcRnIf m n DataCon
-- A wrapper for DataCon.mkDataCon that
-- a) makes the worker Id
-- b) makes the wrapper Id if necessary, including
-- allocating its unique (hence monadic)
buildDataCon fam_envs src_name declared_infix arg_stricts field_lbls
univ_tvs ex_tvs eq_spec ctxt arg_tys res_ty rep_tycon
= do { wrap_name <- newImplicitBinder src_name mkDataConWrapperOcc
; work_name <- newImplicitBinder src_name mkDataConWorkerOcc
-- This last one takes the name of the data constructor in the source
-- code, which (for Haskell source anyway) will be in the DataName name
-- space, and puts it into the VarName name space
; us <- newUniqueSupply
; dflags <- getDynFlags
; let
stupid_ctxt = mkDataConStupidTheta rep_tycon arg_tys univ_tvs
data_con = mkDataCon src_name declared_infix
arg_stricts field_lbls
univ_tvs ex_tvs eq_spec ctxt
arg_tys res_ty rep_tycon
stupid_ctxt dc_wrk dc_rep
dc_wrk = mkDataConWorkId work_name data_con
dc_rep = initUs_ us (mkDataConRep dflags fam_envs wrap_name data_con)
; return data_con }
-- The stupid context for a data constructor should be limited to
-- the type variables mentioned in the arg_tys
-- ToDo: Or functionally dependent on?
-- This whole stupid theta thing is, well, stupid.
mkDataConStupidTheta :: TyCon -> [Type] -> [TyVar] -> [PredType]
mkDataConStupidTheta tycon arg_tys univ_tvs
| null stupid_theta = [] -- The common case
| otherwise = filter in_arg_tys stupid_theta
where
tc_subst = zipTopTvSubst (tyConTyVars tycon) (mkTyVarTys univ_tvs)
stupid_theta = substTheta tc_subst (tyConStupidTheta tycon)
-- Start by instantiating the master copy of the
-- stupid theta, taken from the TyCon
arg_tyvars = tyVarsOfTypes arg_tys
in_arg_tys pred = not $ isEmptyVarSet $
tyVarsOfType pred `intersectVarSet` arg_tyvars
------------------------------------------------------
buildPatSyn :: Name -> Bool
-> (Id,Bool) -> Maybe (Id, Bool)
-> ([TyVar], ThetaType) -- ^ Univ and req
-> ([TyVar], ThetaType) -- ^ Ex and prov
-> [Type] -- ^ Argument types
-> Type -- ^ Result type
-> PatSyn
buildPatSyn src_name declared_infix matcher@(matcher_id,_) builder
(univ_tvs, req_theta) (ex_tvs, prov_theta) arg_tys pat_ty
= -- ASSERT((and [ univ_tvs == univ_tvs'
-- , ex_tvs == ex_tvs'
-- , pat_ty `eqType` pat_ty'
-- , prov_theta `eqTypes` prov_theta'
-- , req_theta `eqTypes` req_theta'
-- , arg_tys `eqTypes` arg_tys'
-- ]))
mkPatSyn src_name declared_infix
(univ_tvs, req_theta) (ex_tvs, prov_theta)
arg_tys pat_ty
matcher builder
where
((_:univ_tvs'), req_theta', tau) = tcSplitSigmaTy $ idType matcher_id
([pat_ty', cont_sigma, _], _) = tcSplitFunTys tau
(ex_tvs', prov_theta', cont_tau) = tcSplitSigmaTy cont_sigma
(arg_tys', _) = tcSplitFunTys cont_tau
-- ------------------------------------------------------
type TcMethInfo = (Name, DefMethSpec, Type)
-- A temporary intermediate, to communicate between
-- tcClassSigs and buildClass.
buildClass :: Name -> [TyVar] -> [Role] -> ThetaType
-> [FunDep TyVar] -- Functional dependencies
-> [ClassATItem] -- Associated types
-> [TcMethInfo] -- Method info
-> ClassMinimalDef -- Minimal complete definition
-> RecFlag -- Info for type constructor
-> TcRnIf m n Class
buildClass tycon_name tvs roles sc_theta fds at_items sig_stuff mindef tc_isrec
= fixM $ \ rec_clas -> -- Only name generation inside loop
do { traceIf (text "buildClass")
; datacon_name <- newImplicitBinder tycon_name mkClassDataConOcc
-- The class name is the 'parent' for this datacon, not its tycon,
-- because one should import the class to get the binding for
-- the datacon
; op_items <- mapM (mk_op_item rec_clas) sig_stuff
-- Build the selector id and default method id
-- Make selectors for the superclasses
; sc_sel_names <- mapM (newImplicitBinder tycon_name . mkSuperDictSelOcc)
[1..length sc_theta]
; let sc_sel_ids = [ mkDictSelId sc_name rec_clas
| sc_name <- sc_sel_names]
-- We number off the Dict superclass selectors, 1, 2, 3 etc so that we
-- can construct names for the selectors. Thus
-- class (C a, C b) => D a b where ...
-- gives superclass selectors
-- D_sc1, D_sc2
-- (We used to call them D_C, but now we can have two different
-- superclasses both called C!)
; let use_newtype = isSingleton arg_tys
-- Use a newtype if the data constructor
-- (a) has exactly one value field
-- i.e. exactly one operation or superclass taken together
-- (b) that value is of lifted type (which they always are, because
-- we box equality superclasses)
-- See note [Class newtypes and equality predicates]
-- We treat the dictionary superclasses as ordinary arguments.
-- That means that in the case of
-- class C a => D a
-- we don't get a newtype with no arguments!
args = sc_sel_names ++ op_names
op_tys = [ty | (_,_,ty) <- sig_stuff]
op_names = [op | (op,_,_) <- sig_stuff]
arg_tys = sc_theta ++ op_tys
rec_tycon = classTyCon rec_clas
; dict_con <- buildDataCon (panic "buildClass: FamInstEnvs")
datacon_name
False -- Not declared infix
(map (const HsNoBang) args)
[{- No fields -}]
tvs [{- no existentials -}]
[{- No GADT equalities -}]
[{- No theta -}]
arg_tys
(mkTyConApp rec_tycon (mkTyVarTys tvs))
rec_tycon
; rhs <- if use_newtype
then mkNewTyConRhs tycon_name rec_tycon dict_con
else return (mkDataTyConRhs [dict_con])
; let { clas_kind = mkPiKinds tvs constraintKind
; tycon = mkClassTyCon tycon_name clas_kind tvs roles
rhs rec_clas tc_isrec
-- A class can be recursive, and in the case of newtypes
-- this matters. For example
-- class C a where { op :: C b => a -> b -> Int }
-- Because C has only one operation, it is represented by
-- a newtype, and it should be a *recursive* newtype.
-- [If we don't make it a recursive newtype, we'll expand the
-- newtype like a synonym, but that will lead to an infinite
-- type]
; result = mkClass tvs fds
sc_theta sc_sel_ids at_items
op_items mindef tycon
}
; traceIf (text "buildClass" <+> ppr tycon)
; return result }
where
mk_op_item :: Class -> TcMethInfo -> TcRnIf n m ClassOpItem
mk_op_item rec_clas (op_name, dm_spec, _)
= do { dm_info <- case dm_spec of
NoDM -> return NoDefMeth
GenericDM -> do { dm_name <- newImplicitBinder op_name mkGenDefMethodOcc
; return (GenDefMeth dm_name) }
VanillaDM -> do { dm_name <- newImplicitBinder op_name mkDefaultMethodOcc
; return (DefMeth dm_name) }
; return (mkDictSelId op_name rec_clas, dm_info) }
{-
Note [Class newtypes and equality predicates]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
class (a ~ F b) => C a b where
op :: a -> b
We cannot represent this by a newtype, even though it's not
existential, because there are two value fields (the equality
predicate and op. See Trac #2238
Moreover,
class (a ~ F b) => C a b where {}
Here we can't use a newtype either, even though there is only
one field, because equality predicates are unboxed, and classes
are boxed.
-}
|
alexander-at-github/eta
|
compiler/ETA/Iface/BuildTyCl.hs
|
Haskell
|
bsd-3-clause
| 14,445
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
#ifdef DataPolyKinds
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE PolyKinds #-}
#endif
#if __GLASGOW_HASKELL__ >= 706
{-# LANGUAGE ExplicitNamespaces #-}
#endif
module GHC.Generics.Compat
( V1
, U1 (U1)
, Par1 (Par1, unPar1)
, Rec1 (Rec1, unRec1)
, K1 (K1, unK1)
, M1 (M1, unM1)
, (:+:) (L1, R1)
, (:*:) ((:*:))
, (:.:) (Comp1, unComp1)
#if MIN_VERSION_base(4, 9, 0)
, URec
( UAddr
, UChar
, UDouble
, UFloat
, UInt
, UWord
, uAddr#
, uChar#
, uDouble#
, uFloat#
, uInt#
, uWord#
)
, UAddr
, UChar
, UDouble
, UFloat
, UInt
, UWord
#endif
, Rec0
, R
, D1
, C1
, S1
, D
, C
, S
, Datatype (..)
, Constructor (..)
, Selector (..)
, Fixity (Prefix, Infix)
, FixityI (PrefixI, InfixI)
, PrefixI
, InfixI
, Associativity (LeftAssociative, RightAssociative, NotAssociative)
, LeftAssociative
, RightAssociative
, NotAssociative
, prec
, Meta (MetaData, MetaCons, MetaSel)
, MetaData
, MetaCons
, MetaSel
, DecidedStrictness (DecidedLazy, DecidedStrict, DecidedUnpack)
, DecidedLazy
, DecidedStrict
, DecidedUnpack
, SourceStrictness (NoSourceStrictness, SourceLazy, SourceStrict)
, NoSourceStrictness
, SourceLazy
, SourceStrict
, SourceUnpackedness (NoSourceUnpackedness, SourceNoUnpack, SourceUnpack)
, NoSourceUnpackedness
, SourceNoUnpack
, SourceUnpack
, Generic (type Rep, from, to)
, Generic1 (type Rep1, from1, to1)
)
where
-- base ----------------------------------------------------------------------
#if !MIN_VERSION_base(4, 9, 0)
import Data.Ix (Ix)
#endif
import GHC.Generics
#if MIN_VERSION_base(4, 8, 0)
import Numeric.Natural (Natural)
#endif
-- types ---------------------------------------------------------------------
#if defined(DataPolyKinds) && !MIN_VERSION_base(4, 9, 0)
import GHC.TypeLits.Compat (Nat, Symbol)
#endif
#if !MIN_VERSION_base(4, 9, 0)
import Type.Maybe (Just, Nothing)
#endif
import Type.Meta (Known, Val, val)
import Type.Meta.Proxy (Proxy (Proxy))
------------------------------------------------------------------------------
#if MIN_VERSION_base(4, 8, 0)
type NatVal = Natural
#else
type NatVal = Integer
#endif
#ifndef DataPolyKinds
------------------------------------------------------------------------------
type Nat = NatVal
type Symbol = String
#endif
#if !MIN_VERSION_base(4, 9, 0)
------------------------------------------------------------------------------
data FixityI = PrefixI | InfixI Associativity Nat
------------------------------------------------------------------------------
data Meta
= MetaData Symbol Symbol Symbol Bool
| MetaCons Symbol FixityI Bool
| MetaSel
(Maybe Symbol)
SourceUnpackedness
SourceStrictness
DecidedStrictness
------------------------------------------------------------------------------
data DecidedStrictness
= DecidedLazy
| DecidedStrict
| DecidedUnpack
deriving (Eq, Ord, Read, Show, Enum, Bounded, Ix, Generic)
------------------------------------------------------------------------------
data SourceStrictness
= NoSourceStrictness
| SourceStrict
| SourceLazy
deriving (Eq, Ord, Read, Show, Enum, Bounded, Ix, Generic)
------------------------------------------------------------------------------
data SourceUnpackedness
= NoSourceUnpackedness
| SourceNoUnpack
| SourceUnpack
deriving (Eq, Ord, Read, Show, Enum, Bounded, Ix, Generic)
#endif
------------------------------------------------------------------------------
#ifdef DataPolyKinds
type PrefixI = 'PrefixI
type InfixI = 'InfixI
type LeftAssociative = 'LeftAssociative
type RightAssociative = 'RightAssociative
type NotAssociative = 'NotAssociative
#if MIN_VERSION_base(4, 9, 0)
type MetaData = 'MetaData
type MetaCons = 'MetaCons
type MetaSel = 'MetaSel
#else
-- D1 etc will want a *-kinded type argument on GHC < 8; use Proxy to get this
type MetaData n m p nt = Proxy ('MetaData n m p nt)
type MetaCons n f s = Proxy ('MetaCons n f s)
type MetaSel mn su ss ds = Proxy ('MetaSel mn su ss ds)
#endif
type DecidedLazy = 'DecidedLazy
type DecidedStrict = 'DecidedStrict
type DecidedUnpack = 'DecidedUnpack
type NoSourceStrictness = 'NoSourceStrictness
type SourceLazy = 'SourceLazy
type SourceStrict = 'SourceStrict
type NoSourceUnpackedness = 'NoSourceUnpackedness
type SourceNoUnpack = 'SourceNoUnpack
type SourceUnpack = 'SourceUnpack
#else
data PrefixI
data InfixI a n
data LeftAssociative
data RightAssociative
data NotAssociative
data MetaData n m p nt
data MetaCons n f s
data MetaSel mn su ss ds
data DecidedLazy
data DecidedStrict
data DecidedUnpack
data NoSourceStrictness
data SourceLazy
data SourceStrict
data NoSourceUnpackedness
data SourceNoUnpack
data SourceUnpack
#endif
------------------------------------------------------------------------------
instance (Known PrefixI) where
type Val PrefixI = Fixity
val _ = Prefix
instance (Known a, Val a ~ Associativity, Known n, Val n ~ NatVal) =>
Known (InfixI a n)
where
type Val (InfixI a n) = Fixity
val _ =
Infix (val (Proxy :: Proxy a)) (fromIntegral (val (Proxy :: Proxy n)))
instance Known LeftAssociative where
type Val LeftAssociative = Associativity
val _ = LeftAssociative
instance Known RightAssociative where
type Val RightAssociative = Associativity
val _ = RightAssociative
instance Known NotAssociative where
type Val NotAssociative = Associativity
val _ = NotAssociative
instance Known DecidedLazy where
type Val DecidedLazy = DecidedStrictness
val _ = DecidedLazy
instance Known DecidedStrict where
type Val DecidedStrict = DecidedStrictness
val _ = DecidedStrict
instance Known DecidedUnpack where
type Val DecidedUnpack = DecidedStrictness
val _ = DecidedUnpack
instance Known NoSourceStrictness where
type Val NoSourceStrictness = SourceStrictness
val _ = NoSourceStrictness
instance Known SourceLazy where
type Val SourceLazy = SourceStrictness
val _ = SourceLazy
instance Known SourceStrict where
type Val SourceStrict = SourceStrictness
val _ = SourceStrict
instance Known NoSourceUnpackedness where
type Val NoSourceUnpackedness = SourceUnpackedness
val _ = NoSourceUnpackedness
instance Known SourceNoUnpack where
type Val SourceNoUnpack = SourceUnpackedness
val _ = SourceNoUnpack
instance Known SourceUnpack where
type Val SourceUnpack = SourceUnpackedness
val _ = SourceUnpack
#if !MIN_VERSION_base(4, 9, 0)
------------------------------------------------------------------------------
instance
( Known n, Val n ~ String, Known m, Val m ~ String, Known nt
, Val nt ~ Bool
)
=>
Datatype (MetaData n m p nt)
where
datatypeName _ = val (Proxy :: Proxy n)
moduleName _ = val (Proxy :: Proxy m)
#if MIN_VERSION_base(4, 7, 0)
isNewtype _ = val (Proxy :: Proxy nt)
#endif
------------------------------------------------------------------------------
instance
(Known n, Val n ~ String, Known f, Val f ~ Fixity, Known r, Val r ~ Bool)
=>
Constructor (MetaCons n f r)
where
conName _ = val (Proxy :: Proxy n)
conFixity _ = val (Proxy :: Proxy f)
conIsRecord _ = val (Proxy :: Proxy r)
------------------------------------------------------------------------------
instance (Known s, Val s ~ String) =>
Selector (MetaSel (Just s) su ss ds)
where
selName _ = val (Proxy :: Proxy s)
------------------------------------------------------------------------------
instance Selector (MetaSel Nothing su ss ds) where
selName _ = ""
#endif
|
duairc/symbols
|
types/src/GHC/Generics/Compat.hs
|
Haskell
|
bsd-3-clause
| 8,221
|
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE StandaloneDeriving #-}
module GRIN.GrinCase where
import GRIN.GrinIdentifiers
import GRIN.GrinLiteral
import GRIN.GrinValue
import GRIN.GrinTag
import Data.Data
data GrinAlternative f expr where
Alternative :: {pat :: GrinConstantPattern f , expr :: expr } -> GrinAlternative f expr
deriving instance (Show expr, Show (f GrinIdentifier)) => Show (GrinAlternative f expr)
deriving instance Functor (GrinAlternative f )
deriving instance Foldable (GrinAlternative f )
deriving instance Traversable (GrinAlternative f )
deriving instance (Data expr, Typeable f, Data (f GrinIdentifier)) => Data (GrinAlternative f expr)
deriving instance Typeable (GrinAlternative)
data GrinConstantPattern f where
LiteralPattern :: GrinLiteral -> GrinConstantPattern f
TagPattern :: Tag -> GrinConstantPattern f
ConstantNodePattern :: Tag -> f GrinIdentifier -> GrinConstantPattern f
deriving (Typeable)
deriving instance (Data (f GrinIdentifier), Typeable f) => Data (GrinConstantPattern f)
deriving instance (Show (f GrinIdentifier)) => Show (GrinConstantPattern f)
|
spacekitteh/libgrin
|
src/GRIN/GrinCase.hs
|
Haskell
|
bsd-3-clause
| 1,288
|
module Nut.Color.Spectrum.XYZ
( XYZ(..)
) where
import Control.Applicative
import Data.Foldable
import Data.Traversable
import Data.Monoid
import Nut.Numeric.Double
import Nut.Numeric.Float
data XYZ a = XYZ a a a deriving (Eq,Ord,Show,Read)
instance Functor XYZ where
fmap f (XYZ x y z) = XYZ (f x) (f y) (f z)
instance Applicative XYZ where
pure a = XYZ a a a
XYZ fx fy fz <*> XYZ x y z = XYZ (fx x) (fy y) (fz z)
instance Traversable XYZ where
traverse f (XYZ x y z) = XYZ <$> f x <*> f y <*> f z
instance Foldable XYZ where
foldMap f (XYZ x y z) = f x `mappend` f y `mappend` f z
instance Num a => Num (XYZ a) where
(+) = liftA2 (+)
(*) = liftA2 (*)
(-) = liftA2 (-)
abs = fmap abs
signum = fmap signum
fromInteger = pure . fromInteger
instance Fractional a => Fractional (XYZ a) where
(/) = liftA2 (/)
recip = fmap recip
fromRational = pure . fromRational
instance Floating a => Floating (XYZ a) where
pi = pure pi
exp = fmap exp
sqrt = fmap sqrt
log = fmap log
(**) = liftA2 (**)
logBase = liftA2 logBase
sin = fmap sin
cos = fmap cos
tan = fmap tan
asin = fmap asin
acos = fmap acos
atan = fmap atan
sinh = fmap sinh
cosh = fmap cosh
tanh = fmap tanh
asinh = fmap asinh
acosh = fmap acosh
atanh = fmap atanh
instance FromFloat a => FromFloat (XYZ a) where
fromFloat = pure . fromFloat
instance FromDouble a => FromDouble (XYZ a) where
fromDouble = pure . fromDouble
|
ekmett/colorimetry
|
Colorimetry/Spectrum/XYZ.hs
|
Haskell
|
bsd-3-clause
| 1,454
|
-----------------------------------------------------------------------
--
-- Haskell: The Craft of Functional Programming, 3e
-- Simon Thompson
-- (c) Addison-Wesley, 1996-2011.
--
-- Chapter 14, part 1
-- Also covers the properties in Section 14.7
--
-----------------------------------------------------------------------
module Craft.Chapter14_1 where
import Prelude hiding (Either(..),either,Maybe(..),maybe)
import Test.QuickCheck
import Control.Monad
-- Algebraic types
-- ^^^^^^^^^^^^^^^
-- Introducing algebraic types
-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^
-- We give a sequence of examples of increasing complexity ...
-- Enumerated types
-- ^^^^^^^^^^^^^^^^
-- Two enumerated types
data Temp = Cold | Hot
deriving (Show)
data Season = Spring | Summer | Autumn | Winter
deriving (Show,Eq,Enum)
-- A function over Season, defined using pattern matching.
weather :: Season -> Temp
weather Summer = Hot
weather _ = Cold
-- The Ordering type, as used in the class Ord.
-- data Ordering = LT | EQ | GT
-- Declaring Temp an instance of Eq.
instance Eq Temp where
Cold == Cold = True
Hot == Hot = True
_ == _ = False
-- Recursive algebraic types
-- ^^^^^^^^^^^^^^^^^^^^^^^^^
-- Expressions -- ^^^^^^^^^^^
-- Representing an integer expression.
data Expr = Lit Integer |
Add Expr Expr |
Sub Expr Expr |
If BExp Expr Expr
deriving (Show,Eq)
-- Three examples from Expr.
expr1 = Lit 2
expr2 = Add (Lit 2) (Lit 3)
expr3 = Add (Sub (Lit 3) (Lit 1)) (Lit 3)
-- Evaluating an expression.
eval :: Expr -> Integer
eval (Lit n) = n
eval (Add e1 e2) = (eval e1) + (eval e2)
eval (Sub e1 e2) = (eval e1) - (eval e2)
eval (If b e1 e2)
| bEval b = eval e1
| otherwise = eval e2
-- Showing an expression.
-- instance Show Expr where
--
-- show (Lit n) = show n
-- show (Add e1 e2)
-- = "(" ++ show e1 ++ "+" ++ show e2 ++ ")"
-- show (Sub e1 e2)
-- = "(" ++ show e1 ++ "-" ++ show e2 ++ ")"
-- Trees of integers
-- ^^^^^^^^^^^^^^^^^
-- The type definition.
data NTree = NilT |
Node Integer NTree NTree
deriving (Show,Eq,Read,Ord)
-- Example trees
treeEx1 = Node 10 NilT NilT
treeEx2 = Node 17 (Node 14 NilT NilT) (Node 20 NilT NilT)
-- Definitions of many functions are primitive recursive. For instance,
sumTree,depth :: NTree -> Integer
sumTree NilT = 0
sumTree (Node n t1 t2) = n + sumTree t1 + sumTree t2
depth NilT = 0
depth (Node n t1 t2) = 1 + max (depth t1) (depth t2)
-- How many times does an integer occur in a tree?
occurs :: NTree -> Integer -> Integer
occurs NilT p = 0
occurs (Node n t1 t2) p
| n==p = 1 + occurs t1 p + occurs t2 p
| otherwise = occurs t1 p + occurs t2 p
-- Rearranging expressions
-- ^^^^^^^^^^^^^^^^^^^^^^^
-- Right-associating additions in expressions.
assoc :: Expr -> Expr
assoc (Add (Add e1 e2) e3)
= assoc (Add e1 (Add e2 e3))
assoc (Add e1 e2)
= Add (assoc e1) (assoc e2)
assoc (Sub e1 e2)
= Sub (assoc e1) (assoc e2)
assoc (Lit n)
= Lit n
assoc' (e1 `Add` (e2 `Add` e3))
= assoc' (e1 `Add` e2 `Add` e3)
-- Infix constructors
-- ^^^^^^^^^^^^^^^^^^
-- An alternative definition of Expr.
data Expr' = Lit' Integer |
Expr' :+: Expr' |
Expr' :-: Expr'
-- Mutual Recursion
-- ^^^^^^^^^^^^^^^^
-- Mutually recursive types ...
data Person = Adult Name Address Biog |
Child Name
data Biog = Parent String [Person] |
NonParent String
type Name = String
type Address = [String]
-- ... and functions.
showPerson (Adult nm ad bio)
= show nm ++ show ad ++ showBiog bio
showBiog (Parent st perList)
= st ++ concat (map showPerson perList)
-- Alternative definition of Expr (as used later in the calculator case
-- study.
-- data Expr = Lit Int |
-- Op Ops Expr Expr
-- data Ops = Add | Sub | Mul | Div
-- It is possible to extend the type Expr so that it contains
-- conditional expressions, \texttt{If b e1 e2}.
-- data Expr = Lit Int |
-- Op Ops Expr Expr |
-- If BExp Expr Expr
-- Boolean expressions.
data BExp = BoolLit Bool |
And BExp BExp |
Not BExp |
Equal Expr Expr |
Greater Expr Expr
deriving (Show, Eq)
bEval :: BExp -> Bool
bEval (BoolLit a) = a
bEval (And a b) = and [bEval a, bEval b]
bEval (Not a) = not (bEval a)
bEval (Equal a b) = eval a == eval b
bEval (Greater a b) = eval a >= eval b
infixl 5 :::&
data L' a = N | a :::& L' a
-- QuickCheck for algebraic types
instance Arbitrary NTree where
arbitrary = sized arbNTree
arbNTree :: Int -> Gen NTree
arbNTree 0 = return NilT
arbNTree n
| n>0
= frequency[(1, return NilT),
(3, liftM3 Node arbitrary bush bush)]
where
bush = arbNTree (div n 2)
instance Arbitrary Expr where
arbitrary = sized arbExpr
arbExpr :: Int -> Gen Expr
arbExpr 0 = liftM Lit arbitrary
arbExpr n
| n>0
= frequency[(1, liftM Lit arbitrary),
(2, liftM2 Add bush bush),
(2, liftM2 Sub bush bush)]
where
bush = arbExpr (div n 2)
prop_assoc :: Expr -> Bool
prop_assoc expr =
eval expr == eval (assoc expr)
prop_depth :: NTree -> Bool
prop_depth t =
size t < 2^(depth t)
size :: NTree -> Integer
size NilT = 0
size (Node n t1 t2) = 1 + (size t1) + (depth t2)
|
Numberartificial/workflow
|
snipets/src/Craft/Chapter14_1.hs
|
Haskell
|
mit
| 5,523
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module LambdaCms.Core.Classes
( PageHeadProperties (..)
) where
import LambdaCms.Core.Import
import Data.Text (intercalate)
type Follow = Bool
type Index = Bool
class PageHeadProperties res where
title :: res -> Text
author :: res -> Maybe Text
author _ = Nothing
editor :: res -> Maybe Text
editor _ = Nothing
description :: res -> Maybe Text
description _ = Nothing
keywords :: res -> [Text]
keywords _ = []
robots :: res -> Maybe (Index, Follow)
robots _ = Nothing
otherMetas :: res -> [[(Text, Text)]]
otherMetas _ = []
facebook :: res -> [(Text, Text)]
facebook _ = []
twitter :: res -> [(Text, Text)]
twitter _ = []
googlePlus :: res -> [(Text, Text)]
googlePlus _ = []
pageHeadTags :: LambdaCmsAdmin master => res -> WidgetT master IO ()
pageHeadTags res = toWidgetHead $(hamletFile "templates/pagehead.hamlet")
where
robotsText :: Maybe Text
robotsText = case robots res of
Just (index, follow) -> Just $ (if index then "Index" else "NoIndex")
<> ", "
<> (if follow then "Follow" else "NoFollow")
Nothing -> Nothing
|
lambdacms/lambdacms
|
lambdacms-core/LambdaCms/Core/Classes.hs
|
Haskell
|
mit
| 1,358
|
{-# LANGUAGE LambdaCase #-}
module Cardano.Wallet.Kernel.Addresses (
createAddress
, newHdAddress
, importAddresses
-- * Errors
, CreateAddressError(..)
, ImportAddressError(..)
) where
import qualified Prelude
import Universum
import Control.Lens (to)
import Control.Monad.Except (throwError)
import Formatting (bprint, build, formatToString, (%))
import qualified Formatting as F
import qualified Formatting.Buildable
import System.Random.MWC (GenIO, createSystemRandom, uniformR)
import Data.Acid (update)
import Pos.Core (Address, IsBootstrapEraAddr (..), deriveLvl2KeyPair)
import Pos.Core.NetworkMagic (NetworkMagic, makeNetworkMagic)
import Pos.Crypto (EncryptedSecretKey, PassPhrase,
ShouldCheckPassphrase (..))
import Cardano.Wallet.Kernel.DB.AcidState (CreateHdAddress (..))
import Cardano.Wallet.Kernel.DB.HdWallet (HdAccountId,
HdAccountIx (..), HdAddress, HdAddressId (..),
HdAddressIx (..), HdRootId (..), IsOurs (..),
hdAccountIdIx, hdAccountIdParent, hdAddressIdIx)
import Cardano.Wallet.Kernel.DB.HdWallet.Create
(CreateHdAddressError (..), initHdAddress)
import Cardano.Wallet.Kernel.DB.HdWallet.Derivation
(HardeningMode (..), deriveIndex)
import Cardano.Wallet.Kernel.Internal (PassiveWallet, walletKeystore,
walletProtocolMagic, wallets)
import qualified Cardano.Wallet.Kernel.Keystore as Keystore
import Cardano.Wallet.Kernel.Types (AccountId (..), WalletId (..))
import Cardano.Wallet.WalletLayer.Kernel.Conv (toCardanoAddress)
import Test.QuickCheck (Arbitrary (..), oneof)
data CreateAddressError =
CreateAddressUnknownHdAccount HdAccountId
-- ^ When trying to create the 'Address', the parent 'Account' was not
-- there.
| CreateAddressKeystoreNotFound AccountId
-- ^ When trying to create the 'Address', the 'Keystore' didn't have
-- any secret associated with this 'Account'.
-- there.
| CreateAddressHdRndGenerationFailed HdAccountId
-- ^ The crypto-related part of address generation failed. This is
-- likely to happen if the 'PassPhrase' does not match the one used
-- to encrypt the 'EncryptedSecretKey'.
| CreateAddressHdRndAddressSpaceSaturated HdAccountId
-- ^ The available number of HD addresses in use in such that trying
-- to find another random index would be too expensive
deriving Eq
instance Arbitrary CreateAddressError where
arbitrary = oneof
[ CreateAddressUnknownHdAccount <$> arbitrary
, CreateAddressKeystoreNotFound . AccountIdHdRnd <$> arbitrary
, CreateAddressHdRndGenerationFailed <$> arbitrary
, CreateAddressHdRndAddressSpaceSaturated <$> arbitrary
]
instance Buildable CreateAddressError where
build (CreateAddressUnknownHdAccount uAccount) =
bprint ("CreateAddressUnknownHdAccount " % F.build) uAccount
build (CreateAddressKeystoreNotFound accId) =
bprint ("CreateAddressKeystoreNotFound " % F.build) accId
build (CreateAddressHdRndGenerationFailed hdAcc) =
bprint ("CreateAddressHdRndGenerationFailed " % F.build) hdAcc
build (CreateAddressHdRndAddressSpaceSaturated hdAcc) =
bprint ("CreateAddressHdRndAddressSpaceSaturated " % F.build) hdAcc
instance Show CreateAddressError where
show = formatToString build
-- | Creates a new 'Address' for the input account.
createAddress :: PassPhrase
-- ^ The 'Passphrase' (a.k.a the \"Spending Password\").
-> AccountId
-- ^ An abstract notion of an 'Account' identifier
-> PassiveWallet
-> IO (Either CreateAddressError Address)
createAddress spendingPassword accId pw = do
let nm = makeNetworkMagic (pw ^. walletProtocolMagic)
keystore = pw ^. walletKeystore
case accId of
-- \"Standard\" HD random derivation. The strategy is as follows:
--
-- 1. Generate the Address' @index@ and @HdAddress@ structure outside
-- of an atomic acid-state transaction. This could lead to data
-- races in the sense that an index is picked and such index
-- is already claimed, but if this happens we simply try again.
-- 2. Perform the actual creation of the 'HdAddress' as an atomic
-- transaction in acid-state.
--
-- The reason why we do this is because:
-- 1. We cannot do IO (thus index derivation) in an acid-state
-- transaction
-- 2. In order to create an 'HdAddress' we need a proper 'Address',
-- but this cannot be derived with having access to the
-- 'EncryptedSecretKey' and the 'PassPhrase', and we do not want
-- these exposed in the acid-state transaction log.
(AccountIdHdRnd hdAccId) -> do
mbEsk <- Keystore.lookup nm
(WalletIdHdRnd (hdAccId ^. hdAccountIdParent))
keystore
case mbEsk of
Nothing -> return (Left $ CreateAddressKeystoreNotFound accId)
Just esk -> createHdRndAddress spendingPassword esk hdAccId pw
-- | Creates a new 'Address' using the random HD derivation under the hood.
-- Being this an operation bound not only by the number of available derivation
-- indexes \"left\" in the account, some form of short-circuiting is necessary.
-- Currently, the algorithm is as follows:
--
-- 1. Try to generate an 'Address' by picking a random index;
-- 2. If the operation succeeds, return the 'Address';
-- 3. If the DB operation fails due to a collision, try again, up to a max of
-- 1024 attempts.
-- 4. If after 1024 attempts there is still no result, flag this upstream.
createHdRndAddress :: PassPhrase
-> EncryptedSecretKey
-> HdAccountId
-> PassiveWallet
-> IO (Either CreateAddressError Address)
createHdRndAddress spendingPassword esk accId pw = do
gen <- createSystemRandom
go gen 0
where
go :: GenIO -> Word32 -> IO (Either CreateAddressError Address)
go gen collisions =
case collisions >= maxAllowedCollisions of
True -> return $ Left (CreateAddressHdRndAddressSpaceSaturated accId)
False -> tryGenerateAddress gen collisions
tryGenerateAddress :: GenIO
-> Word32
-- ^ The current number of collisions
-> IO (Either CreateAddressError Address)
tryGenerateAddress gen collisions = do
newIndex <- deriveIndex (flip uniformR gen) HdAddressIx HardDerivation
let hdAddressId = HdAddressId accId newIndex
nm = makeNetworkMagic $ pw ^. walletProtocolMagic
mbAddr = newHdAddress nm esk spendingPassword accId hdAddressId
case mbAddr of
Nothing -> return (Left $ CreateAddressHdRndGenerationFailed accId)
Just hdAddress -> do
let db = pw ^. wallets
res <- update db (CreateHdAddress hdAddress)
case res of
(Left (CreateHdAddressExists _)) ->
go gen (succ collisions)
(Left (CreateHdAddressUnknown _)) ->
return (Left $ CreateAddressUnknownHdAccount accId)
Right () -> return (Right $ toCardanoAddress hdAddress)
-- The maximum number of allowed collisions.
maxAllowedCollisions :: Word32
maxAllowedCollisions = 1024
-- | Generates a new 'HdAddress' by performing the HD crypto derivation
-- underneath. Returns 'Nothing' if the cryptographic derivation fails.
newHdAddress :: NetworkMagic
-> EncryptedSecretKey
-> PassPhrase
-> HdAccountId
-> HdAddressId
-> Maybe HdAddress
newHdAddress nm esk spendingPassword accId hdAddressId =
let mbAddr = deriveLvl2KeyPair nm
(IsBootstrapEraAddr True)
(ShouldCheckPassphrase True)
spendingPassword
esk
(accId ^. hdAccountIdIx . to getHdAccountIx)
(hdAddressId ^. hdAddressIdIx . to getHdAddressIx)
in case mbAddr of
Nothing -> Nothing
Just (newAddress, _) -> Just $ initHdAddress hdAddressId newAddress
data ImportAddressError
= ImportAddressKeystoreNotFound HdRootId
-- ^ When trying to import the 'Address', the parent root was not there.
deriving Eq
instance Arbitrary ImportAddressError where
arbitrary = oneof
[ ImportAddressKeystoreNotFound <$> arbitrary
]
instance Buildable ImportAddressError where
build = \case
ImportAddressKeystoreNotFound rootId ->
bprint ("ImportAddressError" % F.build) rootId
instance Show ImportAddressError where
show = formatToString build
-- | Import already existing addresses into the DB. A typical use-case for that
-- is backend migration, where users (e.g. exchanges) want to import unused
-- addresses they've generated in the past (and likely communicated to their
-- users). Because Addresses in the old scheme are generated randomly, there's
-- no guarantee that addresses would be generated in the same order on a new
-- node (they better not actually!).
importAddresses
:: HdRootId
-> [Address]
-> PassiveWallet
-> IO (Either ImportAddressError [Either Address ()])
importAddresses rootId addrs pw = runExceptT $ do
esk <- lookupSecretKey rootId
lift $ forM addrs (flip importOneAddress [(rootId, esk)])
where
lookupSecretKey
:: HdRootId
-> ExceptT ImportAddressError IO EncryptedSecretKey
lookupSecretKey k = do
let nm = makeNetworkMagic (pw ^. walletProtocolMagic)
let keystore = pw ^. walletKeystore
lift (Keystore.lookup nm (WalletIdHdRnd k) keystore) >>= \case
Nothing -> throwError (ImportAddressKeystoreNotFound rootId)
Just esk -> return esk
importOneAddress
:: Address
-> [(HdRootId, EncryptedSecretKey)]
-> IO (Either Address ())
importOneAddress addr = evalStateT $ do
let updateLifted = fmap Just . lift . update (pw ^. wallets)
res <- state (isOurs addr) >>= \case
Nothing -> return Nothing
Just hdAddr -> updateLifted $ CreateHdAddress hdAddr
return $ case res of
Just (Right _) -> Right ()
_ -> Left addr
|
input-output-hk/pos-haskell-prototype
|
wallet/src/Cardano/Wallet/Kernel/Addresses.hs
|
Haskell
|
mit
| 11,037
|
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
-- | Primitive Feldspar expressions
module Feldspar.Primitive.Representation where
import Data.Array
import Data.Bits
import Data.Complex
import Data.Int
import Data.Typeable
import Data.Word
import Data.Constraint (Dict (..))
import Language.Embedded.Expression
import Language.Embedded.Imperative.CMD (IArr (..))
import Language.Syntactic
import Language.Syntactic.TH
import Language.Syntactic.Functional
--------------------------------------------------------------------------------
-- * Types
--------------------------------------------------------------------------------
type Length = Word32
type Index = Word32
-- | Representation of primitive supported types
data PrimTypeRep a
where
BoolT :: PrimTypeRep Bool
Int8T :: PrimTypeRep Int8
Int16T :: PrimTypeRep Int16
Int32T :: PrimTypeRep Int32
Int64T :: PrimTypeRep Int64
Word8T :: PrimTypeRep Word8
Word16T :: PrimTypeRep Word16
Word32T :: PrimTypeRep Word32
Word64T :: PrimTypeRep Word64
FloatT :: PrimTypeRep Float
DoubleT :: PrimTypeRep Double
ComplexFloatT :: PrimTypeRep (Complex Float)
ComplexDoubleT :: PrimTypeRep (Complex Double)
data IntTypeRep a
where
Int8Type :: IntTypeRep Int8
Int16Type :: IntTypeRep Int16
Int32Type :: IntTypeRep Int32
Int64Type :: IntTypeRep Int64
data WordTypeRep a
where
Word8Type :: WordTypeRep Word8
Word16Type :: WordTypeRep Word16
Word32Type :: WordTypeRep Word32
Word64Type :: WordTypeRep Word64
data IntWordTypeRep a
where
IntType :: IntTypeRep a -> IntWordTypeRep a
WordType :: WordTypeRep a -> IntWordTypeRep a
data FloatingTypeRep a
where
FloatType :: FloatingTypeRep Float
DoubleType :: FloatingTypeRep Double
data ComplexTypeRep a
where
ComplexFloatType :: ComplexTypeRep (Complex Float)
ComplexDoubleType :: ComplexTypeRep (Complex Double)
-- | A different view of 'PrimTypeRep' that allows matching on similar types
data PrimTypeView a
where
PrimTypeBool :: PrimTypeView Bool
PrimTypeIntWord :: IntWordTypeRep a -> PrimTypeView a
PrimTypeFloating :: FloatingTypeRep a -> PrimTypeView a
PrimTypeComplex :: ComplexTypeRep a -> PrimTypeView a
deriving instance Show (PrimTypeRep a)
deriving instance Show (IntTypeRep a)
deriving instance Show (WordTypeRep a)
deriving instance Show (IntWordTypeRep a)
deriving instance Show (FloatingTypeRep a)
deriving instance Show (ComplexTypeRep a)
deriving instance Show (PrimTypeView a)
viewPrimTypeRep :: PrimTypeRep a -> PrimTypeView a
viewPrimTypeRep BoolT = PrimTypeBool
viewPrimTypeRep Int8T = PrimTypeIntWord $ IntType $ Int8Type
viewPrimTypeRep Int16T = PrimTypeIntWord $ IntType $ Int16Type
viewPrimTypeRep Int32T = PrimTypeIntWord $ IntType $ Int32Type
viewPrimTypeRep Int64T = PrimTypeIntWord $ IntType $ Int64Type
viewPrimTypeRep Word8T = PrimTypeIntWord $ WordType $ Word8Type
viewPrimTypeRep Word16T = PrimTypeIntWord $ WordType $ Word16Type
viewPrimTypeRep Word32T = PrimTypeIntWord $ WordType $ Word32Type
viewPrimTypeRep Word64T = PrimTypeIntWord $ WordType $ Word64Type
viewPrimTypeRep FloatT = PrimTypeFloating FloatType
viewPrimTypeRep DoubleT = PrimTypeFloating DoubleType
viewPrimTypeRep ComplexFloatT = PrimTypeComplex ComplexFloatType
viewPrimTypeRep ComplexDoubleT = PrimTypeComplex ComplexDoubleType
unviewPrimTypeRep :: PrimTypeView a -> PrimTypeRep a
unviewPrimTypeRep PrimTypeBool = BoolT
unviewPrimTypeRep (PrimTypeIntWord (IntType Int8Type)) = Int8T
unviewPrimTypeRep (PrimTypeIntWord (IntType Int16Type)) = Int16T
unviewPrimTypeRep (PrimTypeIntWord (IntType Int32Type)) = Int32T
unviewPrimTypeRep (PrimTypeIntWord (IntType Int64Type)) = Int64T
unviewPrimTypeRep (PrimTypeIntWord (WordType Word8Type)) = Word8T
unviewPrimTypeRep (PrimTypeIntWord (WordType Word16Type)) = Word16T
unviewPrimTypeRep (PrimTypeIntWord (WordType Word32Type)) = Word32T
unviewPrimTypeRep (PrimTypeIntWord (WordType Word64Type)) = Word64T
unviewPrimTypeRep (PrimTypeFloating FloatType) = FloatT
unviewPrimTypeRep (PrimTypeFloating DoubleType) = DoubleT
unviewPrimTypeRep (PrimTypeComplex ComplexFloatType) = ComplexFloatT
unviewPrimTypeRep (PrimTypeComplex ComplexDoubleType) = ComplexDoubleT
primTypeIntWidth :: PrimTypeRep a -> Maybe Int
primTypeIntWidth Int8T = Just 8
primTypeIntWidth Int16T = Just 16
primTypeIntWidth Int32T = Just 32
primTypeIntWidth Int64T = Just 64
primTypeIntWidth Word8T = Just 8
primTypeIntWidth Word16T = Just 16
primTypeIntWidth Word32T = Just 32
primTypeIntWidth Word64T = Just 64
primTypeIntWidth _ = Nothing
-- | Primitive supported types
class (Eq a, Show a, Typeable a) => PrimType' a
where
-- | Reify a primitive type
primTypeRep :: PrimTypeRep a
instance PrimType' Bool where primTypeRep = BoolT
instance PrimType' Int8 where primTypeRep = Int8T
instance PrimType' Int16 where primTypeRep = Int16T
instance PrimType' Int32 where primTypeRep = Int32T
instance PrimType' Int64 where primTypeRep = Int64T
instance PrimType' Word8 where primTypeRep = Word8T
instance PrimType' Word16 where primTypeRep = Word16T
instance PrimType' Word32 where primTypeRep = Word32T
instance PrimType' Word64 where primTypeRep = Word64T
instance PrimType' Float where primTypeRep = FloatT
instance PrimType' Double where primTypeRep = DoubleT
instance PrimType' (Complex Float) where primTypeRep = ComplexFloatT
instance PrimType' (Complex Double) where primTypeRep = ComplexDoubleT
-- | Convenience function; like 'primTypeRep' but with an extra argument to
-- constrain the type parameter. The extra argument is ignored.
primTypeOf :: PrimType' a => a -> PrimTypeRep a
primTypeOf _ = primTypeRep
-- | Check whether two type representations are equal
primTypeEq :: PrimTypeRep a -> PrimTypeRep b -> Maybe (Dict (a ~ b))
primTypeEq BoolT BoolT = Just Dict
primTypeEq Int8T Int8T = Just Dict
primTypeEq Int16T Int16T = Just Dict
primTypeEq Int32T Int32T = Just Dict
primTypeEq Int64T Int64T = Just Dict
primTypeEq Word8T Word8T = Just Dict
primTypeEq Word16T Word16T = Just Dict
primTypeEq Word32T Word32T = Just Dict
primTypeEq Word64T Word64T = Just Dict
primTypeEq FloatT FloatT = Just Dict
primTypeEq DoubleT DoubleT = Just Dict
primTypeEq ComplexFloatT ComplexFloatT = Just Dict
primTypeEq ComplexDoubleT ComplexDoubleT = Just Dict
primTypeEq _ _ = Nothing
-- | Reflect a 'PrimTypeRep' to a 'PrimType'' constraint
witPrimType :: PrimTypeRep a -> Dict (PrimType' a)
witPrimType BoolT = Dict
witPrimType Int8T = Dict
witPrimType Int16T = Dict
witPrimType Int32T = Dict
witPrimType Int64T = Dict
witPrimType Word8T = Dict
witPrimType Word16T = Dict
witPrimType Word32T = Dict
witPrimType Word64T = Dict
witPrimType FloatT = Dict
witPrimType DoubleT = Dict
witPrimType ComplexFloatT = Dict
witPrimType ComplexDoubleT = Dict
--------------------------------------------------------------------------------
-- * Expressions
--------------------------------------------------------------------------------
-- | Primitive operations
data Primitive sig
where
FreeVar :: PrimType' a => String -> Primitive (Full a)
Lit :: (Eq a, Show a) => a -> Primitive (Full a)
Add :: (Num a, PrimType' a) => Primitive (a :-> a :-> Full a)
Sub :: (Num a, PrimType' a) => Primitive (a :-> a :-> Full a)
Mul :: (Num a, PrimType' a) => Primitive (a :-> a :-> Full a)
Neg :: (Num a, PrimType' a) => Primitive (a :-> Full a)
Abs :: (Num a, PrimType' a) => Primitive (a :-> Full a)
Sign :: (Num a, PrimType' a) => Primitive (a :-> Full a)
Quot :: (Integral a, PrimType' a) => Primitive (a :-> a :-> Full a)
Rem :: (Integral a, PrimType' a) => Primitive (a :-> a :-> Full a)
Div :: (Integral a, PrimType' a) => Primitive (a :-> a :-> Full a)
Mod :: (Integral a, PrimType' a) => Primitive (a :-> a :-> Full a)
FDiv :: (Fractional a, PrimType' a) => Primitive (a :-> a :-> Full a)
Pi :: (Floating a, PrimType' a) => Primitive (Full a)
Exp :: (Floating a, PrimType' a) => Primitive (a :-> Full a)
Log :: (Floating a, PrimType' a) => Primitive (a :-> Full a)
Sqrt :: (Floating a, PrimType' a) => Primitive (a :-> Full a)
Pow :: (Floating a, PrimType' a) => Primitive (a :-> a :-> Full a)
Sin :: (Floating a, PrimType' a) => Primitive (a :-> Full a)
Cos :: (Floating a, PrimType' a) => Primitive (a :-> Full a)
Tan :: (Floating a, PrimType' a) => Primitive (a :-> Full a)
Asin :: (Floating a, PrimType' a) => Primitive (a :-> Full a)
Acos :: (Floating a, PrimType' a) => Primitive (a :-> Full a)
Atan :: (Floating a, PrimType' a) => Primitive (a :-> Full a)
Sinh :: (Floating a, PrimType' a) => Primitive (a :-> Full a)
Cosh :: (Floating a, PrimType' a) => Primitive (a :-> Full a)
Tanh :: (Floating a, PrimType' a) => Primitive (a :-> Full a)
Asinh :: (Floating a, PrimType' a) => Primitive (a :-> Full a)
Acosh :: (Floating a, PrimType' a) => Primitive (a :-> Full a)
Atanh :: (Floating a, PrimType' a) => Primitive (a :-> Full a)
Complex :: (Num a, PrimType' a, PrimType' (Complex a)) => Primitive (a :-> a :-> Full (Complex a))
Polar :: (Floating a, PrimType' a, PrimType' (Complex a)) => Primitive (a :-> a :-> Full (Complex a))
Real :: (PrimType' a, PrimType' (Complex a)) => Primitive (Complex a :-> Full a)
Imag :: (PrimType' a, PrimType' (Complex a)) => Primitive (Complex a :-> Full a)
Magnitude :: (RealFloat a, PrimType' a, PrimType' (Complex a)) => Primitive (Complex a :-> Full a)
Phase :: (RealFloat a, PrimType' a, PrimType' (Complex a)) => Primitive (Complex a :-> Full a)
Conjugate :: (Num a, PrimType' (Complex a)) => Primitive (Complex a :-> Full (Complex a))
I2N :: (Integral a, Num b, PrimType' a, PrimType' b) => Primitive (a :-> Full b)
I2B :: (Integral a, PrimType' a) => Primitive (a :-> Full Bool)
B2I :: (Integral a, PrimType' a) => Primitive (Bool :-> Full a)
Round :: (RealFrac a, Num b, PrimType' a, PrimType' b) => Primitive (a :-> Full b)
Not :: Primitive (Bool :-> Full Bool)
And :: Primitive (Bool :-> Bool :-> Full Bool)
Or :: Primitive (Bool :-> Bool :-> Full Bool)
Eq :: (Eq a, PrimType' a) => Primitive (a :-> a :-> Full Bool)
NEq :: (Eq a, PrimType' a) => Primitive (a :-> a :-> Full Bool)
Lt :: (Ord a, PrimType' a) => Primitive (a :-> a :-> Full Bool)
Gt :: (Ord a, PrimType' a) => Primitive (a :-> a :-> Full Bool)
Le :: (Ord a, PrimType' a) => Primitive (a :-> a :-> Full Bool)
Ge :: (Ord a, PrimType' a) => Primitive (a :-> a :-> Full Bool)
BitAnd :: (Bits a, PrimType' a) => Primitive (a :-> a :-> Full a)
BitOr :: (Bits a, PrimType' a) => Primitive (a :-> a :-> Full a)
BitXor :: (Bits a, PrimType' a) => Primitive (a :-> a :-> Full a)
BitCompl :: (Bits a, PrimType' a) => Primitive (a :-> Full a)
ShiftL :: (Bits a, PrimType' a, Integral b, PrimType' b) => Primitive (a :-> b :-> Full a)
ShiftR :: (Bits a, PrimType' a, Integral b, PrimType' b) => Primitive (a :-> b :-> Full a)
ArrIx :: PrimType' a => IArr Index a -> Primitive (Index :-> Full a)
Cond :: Primitive (Bool :-> a :-> a :-> Full a)
deriving instance Show (Primitive a)
-- The `PrimType'` constraints on certain symbols require an explanation: The
-- constraints are actually not needed for anything in the modules in
-- `Feldspar.Primitive.*`, but they are needed by `Feldspar.Run.Compile`. They
-- guarantee to the compiler that these symbols don't operate on tuples.
--
-- It would seem more consistent to have a `PrimType'` constraint on all
-- polymorphic symbols. However, this would prevent using some symbols for
-- non-primitive types in `Feldspar.Representation`. For example, `Lit` and
-- `Cond` are used `Feldspar.Representation`, and there they can also be used
-- for tuple types. The current design was chosen because it "just works".
deriveSymbol ''Primitive
instance Render Primitive
where
renderSym (FreeVar v) = v
renderSym (Lit a) = show a
renderSym (ArrIx (IArrComp arr)) = "ArrIx " ++ arr
renderSym (ArrIx _) = "ArrIx ..."
renderSym s = show s
renderArgs = renderArgsSmart
instance StringTree Primitive
instance Eval Primitive
where
evalSym (FreeVar v) = error $ "evaluating free variable " ++ show v
evalSym (Lit a) = a
evalSym Add = (+)
evalSym Sub = (-)
evalSym Mul = (*)
evalSym Neg = negate
evalSym Abs = abs
evalSym Sign = signum
evalSym Quot = quot
evalSym Rem = rem
evalSym Div = div
evalSym Mod = mod
evalSym FDiv = (/)
evalSym Pi = pi
evalSym Exp = exp
evalSym Log = log
evalSym Sqrt = sqrt
evalSym Pow = (**)
evalSym Sin = sin
evalSym Cos = cos
evalSym Tan = tan
evalSym Asin = asin
evalSym Acos = acos
evalSym Atan = atan
evalSym Sinh = sinh
evalSym Cosh = cosh
evalSym Tanh = tanh
evalSym Asinh = asinh
evalSym Acosh = acosh
evalSym Atanh = atanh
evalSym Complex = (:+)
evalSym Polar = mkPolar
evalSym Real = realPart
evalSym Imag = imagPart
evalSym Magnitude = magnitude
evalSym Phase = phase
evalSym Conjugate = conjugate
evalSym I2N = fromInteger . toInteger
evalSym I2B = (/=0)
evalSym B2I = \a -> if a then 1 else 0
evalSym Round = fromInteger . round
evalSym Not = not
evalSym And = (&&)
evalSym Or = (||)
evalSym Eq = (==)
evalSym NEq = (/=)
evalSym Lt = (<)
evalSym Gt = (>)
evalSym Le = (<=)
evalSym Ge = (>=)
evalSym BitAnd = (.&.)
evalSym BitOr = (.|.)
evalSym BitXor = xor
evalSym BitCompl = complement
evalSym ShiftL = \a -> shiftL a . fromIntegral
evalSym ShiftR = \a -> shiftR a . fromIntegral
evalSym Cond = \c t f -> if c then t else f
evalSym (ArrIx (IArrRun arr)) = \i ->
if i<l || i>h
then error $ "ArrIx: index "
++ show (toInteger i)
++ " out of bounds "
++ show (toInteger l, toInteger h)
else arr!i
where
(l,h) = bounds arr
evalSym (ArrIx (IArrComp arr)) = error $ "evaluating symbolic array " ++ arr
-- | Assumes no occurrences of 'FreeVar' and concrete representation of arrays
instance EvalEnv Primitive env
instance Equality Primitive
where
equal s1 s2 = show s1 == show s2
-- NOTE: It is very important not to use `renderSym` here, because it will
-- render all concrete arrays equal.
-- This method uses string comparison. It is probably slightly more
-- efficient to pattern match directly on the constructors. Unfortunately
-- `deriveEquality ''Primitive` doesn't work, so it gets quite tedious to
-- write it with pattern matching.
type PrimDomain = Primitive :&: PrimTypeRep
-- | Primitive expressions
newtype Prim a = Prim { unPrim :: ASTF PrimDomain a }
instance Syntactic (Prim a)
where
type Domain (Prim a) = PrimDomain
type Internal (Prim a) = a
desugar = unPrim
sugar = Prim
-- | Evaluate a closed expression
evalPrim :: Prim a -> a
evalPrim = go . unPrim
where
go :: AST PrimDomain sig -> Denotation sig
go (Sym (s :&: _)) = evalSym s
go (f :$ a) = go f $ go a
sugarSymPrim
:: ( Signature sig
, fi ~ SmartFun dom sig
, sig ~ SmartSig fi
, dom ~ SmartSym fi
, dom ~ PrimDomain
, SyntacticN f fi
, sub :<: Primitive
, PrimType' (DenResult sig)
)
=> sub sig -> f
sugarSymPrim = sugarSymDecor primTypeRep
instance FreeExp Prim
where
type FreePred Prim = PrimType'
constExp = sugarSymPrim . Lit
varExp = sugarSymPrim . FreeVar
instance EvalExp Prim
where
evalExp = evalPrim
--------------------------------------------------------------------------------
-- * Interface
--------------------------------------------------------------------------------
instance (Num a, PrimType' a) => Num (Prim a)
where
fromInteger = constExp . fromInteger
(+) = sugarSymPrim Add
(-) = sugarSymPrim Sub
(*) = sugarSymPrim Mul
negate = sugarSymPrim Neg
abs = sugarSymPrim Abs
signum = sugarSymPrim Sign
|
kmate/raw-feldspar
|
src/Feldspar/Primitive/Representation.hs
|
Haskell
|
bsd-3-clause
| 17,478
|
-- A simple let statement, to ensure the layout is detected
module Layout.LetStmt where
foo = do
{- ffo -}let x = 1
y = 2 -- baz
x+y
|
mpickering/ghc-exactprint
|
tests/examples/ghc710/LetStmt.hs
|
Haskell
|
bsd-3-clause
| 158
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}
{- |
Module : Verifier.SAW.Change
Copyright : Galois, Inc. 2012-2015
License : BSD3
Maintainer : jhendrix@galois.com
Stability : experimental
Portability : non-portable (language extensions)
-}
module Verifier.SAW.Change
( ChangeMonad(..)
, Change(..)
, ChangeT(..)
, change
, changeList
, commitChange
, commitChangeT
, preserveChangeT
, flatten
) where
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative
#endif
import Control.Monad (liftM, liftM2)
import Control.Monad.Trans
----------------------------------------------------------------------
-- Monads for tracking whether values have changed
class (Monad m, Applicative m) => ChangeMonad m where
preserve :: a -> m a -> m a
taint :: m a -> m a
taint m = m >>= modified
modified :: a -> m a
modified x = taint (pure x)
-- Laws (not a minimal set):
-- taint (taint m) = taint m
-- taint (pure x) = modified x
-- fmap f (taint m) = taint (fmap f m)
-- taint m1 <*> m2 = taint (m1 <*> m2)
-- m1 <*> taint m2 = taint (m1 <*> m2)
-- fmap f (modified x) = modified (f x)
-- modified x >>= k = taint (k x)
-- m >>= modified = taint m
-- taint (modified x) = modified x
-- taint (return x) = modified x
-- taint (m >>= k) = taint m >>= k
-- taint (m >>= k) = m >>= (taint . k)
-- preserve x (pure _) = pure x
-- preserve _ (modified y) = modified y
-- preserve _ (taint m) = taint m
change :: ChangeMonad m => (a -> Maybe a) -> a -> m a
change f a =
case f a of
Nothing -> pure a
Just x -> modified x
changeList :: ChangeMonad m => (a -> m a) -> [a] -> m [a]
changeList f xs =
preserve xs $
case xs of
[] -> pure []
y : ys -> (:) <$> f y <*> changeList f ys
----------------------------------------------------------------------
-- Change monad
data Change a = Original a | Modified a
deriving (Show, Functor)
instance Applicative Change where
pure x = Original x
Original f <*> Original x = Original (f x)
Original f <*> Modified x = Modified (f x)
Modified f <*> Original x = Modified (f x)
Modified f <*> Modified x = Modified (f x)
instance Monad Change where
return x = Original x
Original x >>= k = k x
Modified x >>= k = taint (k x)
instance ChangeMonad Change where
preserve x (Original _) = Original x
preserve _ c@(Modified _) = c
taint (Original x) = Modified x
taint c@(Modified _) = c
modified x = Modified x
commitChange :: Change a -> a
commitChange (Original x) = x
commitChange (Modified x) = x
-- ^ Satisfies the following laws:
-- @commitChange (fmap f m) = f (commitChange m)@
-- @commitChange (taint m) = commitChange m@
-- @commitChange (m >>= k) = commitChange (k (commitChange m))@
----------------------------------------------------------------------
-- Change monad transformer
newtype ChangeT m a = ChangeT { runChangeT :: m (Change a) }
instance Monad m => Functor (ChangeT m) where
fmap f (ChangeT m) = ChangeT (liftM (fmap f) m)
instance Monad m => Applicative (ChangeT m) where
pure x = ChangeT (return (Original x))
ChangeT m1 <*> ChangeT m2 = ChangeT (liftM2 (<*>) m1 m2)
instance Monad m => Monad (ChangeT m) where
return x = ChangeT (return (Original x))
ChangeT m >>= k = ChangeT (m >>= f)
where f (Original x) = runChangeT (k x)
f (Modified x) = runChangeT (k x) >>= (return . taint)
instance MonadTrans ChangeT where
lift m = ChangeT (liftM Original m)
instance MonadIO m => MonadIO (ChangeT m) where
liftIO m = lift (liftIO m)
instance Monad m => ChangeMonad (ChangeT m) where
preserve x (ChangeT m) = ChangeT (liftM (preserve x) m)
taint (ChangeT m) = ChangeT (liftM taint m)
modified x = ChangeT (return (modified x))
commitChangeT :: Monad m => ChangeT m a -> m a
commitChangeT (ChangeT m) = liftM commitChange m
-- ^ Is a natural transformation from @ChangeT m@ to @m@:
-- @commitChangeT (fmap f m) = fmap f (commitChangeT m)@
-- @commitChangeT (lift m) = m@
-- @commitChangeT (m >>= k) = commitChangeT m >>= (commitChangeT . k)@
-- @commitChangeT (return x) = return x@
-- @commitChangeT (taint m) = commitChangeT m@
preserveChangeT :: Monad m => a -> ChangeT m (m a) -> ChangeT m a
preserveChangeT x (ChangeT c) = ChangeT (c >>= k)
where k (Original _) = return (Original x)
k (Modified m) = liftM Modified m
-- ^ Satisfies @preserveChangeT x (return _) = return x@ and
-- @preserveChangeT _ (modified m) = taint (lift m)@.
flatten :: Monad m => (a -> ChangeT m (m a)) -> a -> ChangeT m a
flatten f x = ChangeT (runChangeT (f x) >>= k)
where k (Original _) = return (Original x)
k (Modified m) = liftM Modified m
-- ^ @flatten f x = preserveChangeT x (f x)@
|
GaloisInc/saw-script
|
saw-core/src/Verifier/SAW/Change.hs
|
Haskell
|
bsd-3-clause
| 4,832
|
{-# LANGUAGE CPP #-}
module Test(main) where
import Development.Shake.Command
import System.Directory.Extra
import System.IO.Extra
import System.Time.Extra
import System.Environment.Extra
import System.FilePath
import Control.Monad.Extra
import Control.Exception.Extra
import Control.Concurrent
import System.Process
import Data.List.Extra
import Data.IORef
import Data.Char
import Control.Applicative
import qualified Example
import Prelude
import Development.Bake.Test.Simulate
main :: IO ()
main = do
args <- getArgs
if args /= [] then Example.main else do
simulate
dir <- getCurrentDirectory
test $ dir ++ "/.bake-test"
test :: FilePath -> IO ()
test dir = do
let repo = "file:///" ++ dropWhile (== '/') (replace "\\" "/" dir) ++ "/repo"
b <- doesDirectoryExist dir
when b $ do
unit $ cmd "chmod -R 755 .bake-test"
unit $ cmd "rm -rf .bake-test"
return ()
#if __GLASGOW_HASKELL__ >= 708
setEnv "http_proxy" ""
#endif
createDirectoryIfMissing True (dir </> "repo")
withCurrentDirectory (dir </> "repo") $ do
unit $ cmd "git init"
unit $ cmd "git config user.email" ["gwen@example.com"]
unit $ cmd "git config user.name" ["Ms Gwen"]
writeFile "Main.hs" "module Main where\n\n-- Entry point\nmain = print 1\n"
unit $ cmd "git add Main.hs"
unit $ cmd "git commit -m" ["Initial version"]
unit $ cmd "git checkout -b none" -- so I can git push to master
forM_ ["bob","tony"] $ \s -> do
createDirectoryIfMissing True (dir </> "repo-" ++ s)
withCurrentDirectory (dir </> "repo-" ++ s) $ do
print "clone"
unit $ cmd "git clone" repo "."
unit $ cmd "git config user.email" [s ++ "@example.com"]
unit $ cmd "git config user.name" ["Mr " ++ toUpper (head s) : map toLower (tail s)]
unit $ cmd "git checkout -b" s
aborting <- newIORef False
let createProcessAlive p = do
t <- myThreadId
(_,_,_,pid) <- createProcess p
forkIO $ do
waitForProcess pid
b <- readIORef aborting
when (not b) $ throwTo t $ ErrorCall "Process died"
sleep 2
return pid
exe <- getExecutablePath
createDirectoryIfMissing True $ dir </> "server"
curdir <- getCurrentDirectory
environment <- (\env -> ("REPO",repo):("bake_datadir",curdir):env) <$> getEnvironment
p0 <- createProcessAlive (proc exe ["server","--author=admin"])
{cwd=Just $ dir </> "server", env=Just environment}
sleep 5
ps <- forM (zip [1..] Example.platforms) $ \(i,p) -> do
sleep 0.5 -- so they don't ping at the same time
createDirectoryIfMissing True $ dir </> "client-" ++ show p
createProcessAlive (proc exe $
["client","--ping=1","--name=" ++ show p,"--threads=" ++ show i,"--provide=" ++ show p])
{cwd=Just $ dir </> "client-" ++ show p,env=Just environment}
flip finally (do writeIORef aborting True; mapM_ terminateProcess $ p0 : ps) $ do
let edit name act = withCurrentDirectory (dir </> "repo-" ++ name) $ do
act
unit $ cmd "git add *"
unit $ cmd "git commit -m" ["Update from " ++ name]
unit $ cmd "git push origin" name
Stdout sha1 <- cmd "git rev-parse HEAD"
unit $ cmd exe "addpatch" ("--name=" ++ name ++ "=" ++ sha1) ("--author=" ++ name)
putStrLn "% MAKING EDIT AS BOB"
edit "bob" $
writeFile "Main.hs" "module Main(main) where\n\n-- Entry point\nmain = print 1\n"
sleep 2
putStrLn "% MAKING EDIT AS TONY"
edit "tony" $
writeFile "Main.hs" "module Main where\n\n-- Entry point\nmain :: IO ()\nmain = print 1\n"
retry 10 $ do
sleep 10
withTempDir $ \d -> withCurrentDirectory d $ do
unit $ cmd "git clone" repo "."
unit $ cmd "git checkout master"
src <- readFile "Main.hs"
let expect = "module Main(main) where\n\n-- Entry point\nmain :: IO ()\nmain = print 1\n"
when (src /= expect) $ do
error $ "Expected to have updated Main, but got:\n" ++ src
unit $ cmd exe "pause"
putStrLn "% MAKING A GOOD EDIT AS BOB"
edit "bob" $ do
unit $ cmd "git fetch origin"
unit $ cmd "git merge origin/master"
writeFile "Main.hs" "module Main(main) where\n\n-- Entry point\nmain :: IO ()\nmain = print 1\n\n"
putStrLn "% MAKING A BAD EDIT AS BOB"
edit "bob" $
writeFile "Main.hs" "module Main(main) where\nimport System.Environment\n-- Entry point\nmain :: IO ()\nmain = do [[_]] <- getArgs; print 1\n\n"
putStrLn "% MAKING A GOOD EDIT AS TONY"
edit "tony" $ do
unit $ cmd "git fetch origin"
unit $ cmd "git merge origin/master"
writeFile "Main.hs" "-- Tony waz ere\nmodule Main(main) where\n\n-- Entry point\nmain :: IO ()\nmain = print 1\n"
putStrLn "% MAKING A MERGE CONFLICT AS BOB"
edit "bob" $
writeFile "Main.hs" "-- Bob waz ere\nmodule Main(main) where\nimport System.Environment\n-- Entry point\nmain :: IO ()\nmain = do [[_]] <- getArgs; print 1\n\n"
putStrLn "% MAKING ANOTHER GOOD EDIT AS TONY"
edit "tony" $ do
writeFile "Main.hs" "-- Tony waz ere 1981\nmodule Main(main) where\n\n-- Entry point\nmain :: IO ()\nmain = print 1\n"
unit $ cmd exe "unpause"
retry 15 $ do
sleep 10
withTempDir $ \d -> withCurrentDirectory d $ do
unit $ cmd "git clone" repo "."
unit $ cmd "git checkout master"
src <- readFile "Main.hs"
let expect = "-- Tony waz ere 1981\nmodule Main(main) where\n\n-- Entry point\nmain :: IO ()\nmain = print 1\n\n"
when (src /= expect) $ do
error $ "Expected to have updated Main, but got:\n" ++ src
putStrLn "Completed successfully!"
-- putStrLn "Waiting (time to view webpage)..." >> sleep 120
|
Pitometsu/bake
|
src/Test.hs
|
Haskell
|
bsd-3-clause
| 6,242
|
{-
Copyright 2015 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE NoImplicitPrelude #-}
module GHC.IO.Handle.FD (module M) where
import "base" GHC.IO.Handle.FD as M
|
Ye-Yong-Chi/codeworld
|
codeworld-base/src/GHC/IO/Handle/FD.hs
|
Haskell
|
apache-2.0
| 747
|
{-# LANGUAGE CPP #-}
module TcInteract (
solveSimpleGivens, -- Solves [EvVar],GivenLoc
solveSimpleWanteds -- Solves Cts
) where
#include "HsVersions.h"
import BasicTypes ( infinity, IntWithInf, intGtLimit )
import HsTypes ( hsIPNameFS )
import FastString
import TcCanonical
import TcFlatten
import VarSet
import Type
import Kind ( isKind )
import InstEnv( DFunInstType, lookupInstEnv, instanceDFunId )
import CoAxiom(sfInteractTop, sfInteractInert)
import Var
import TcType
import PrelNames ( knownNatClassName, knownSymbolClassName,
callStackTyConKey, typeableClassName )
import TysWiredIn ( ipClass, typeNatKind, typeSymbolKind )
import Id( idType )
import CoAxiom ( Eqn, CoAxiom(..), CoAxBranch(..), fromBranches )
import Class
import TyCon
import DataCon( dataConWrapId )
import FunDeps
import FamInst
import FamInstEnv
import Inst( tyVarsOfCt )
import Unify ( tcUnifyTyWithTFs )
import TcEvidence
import Outputable
import TcRnTypes
import TcSMonad
import Bag
import MonadUtils ( concatMapM )
import Data.List( partition, foldl', deleteFirstsBy )
import SrcLoc
import VarEnv
import Control.Monad
import Maybes( isJust )
import Pair (Pair(..))
import Unique( hasKey )
import DynFlags
import Util
{-
**********************************************************************
* *
* Main Interaction Solver *
* *
**********************************************************************
Note [Basic Simplifier Plan]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1. Pick an element from the WorkList if there exists one with depth
less than our context-stack depth.
2. Run it down the 'stage' pipeline. Stages are:
- canonicalization
- inert reactions
- spontaneous reactions
- top-level intreactions
Each stage returns a StopOrContinue and may have sideffected
the inerts or worklist.
The threading of the stages is as follows:
- If (Stop) is returned by a stage then we start again from Step 1.
- If (ContinueWith ct) is returned by a stage, we feed 'ct' on to
the next stage in the pipeline.
4. If the element has survived (i.e. ContinueWith x) the last stage
then we add him in the inerts and jump back to Step 1.
If in Step 1 no such element exists, we have exceeded our context-stack
depth and will simply fail.
Note [Unflatten after solving the simple wanteds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We unflatten after solving the wc_simples of an implication, and before attempting
to float. This means that
* The fsk/fmv flatten-skolems only survive during solveSimples. We don't
need to worry about them across successive passes over the constraint tree.
(E.g. we don't need the old ic_fsk field of an implication.
* When floating an equality outwards, we don't need to worry about floating its
associated flattening constraints.
* Another tricky case becomes easy: Trac #4935
type instance F True a b = a
type instance F False a b = b
[w] F c a b ~ gamma
(c ~ True) => a ~ gamma
(c ~ False) => b ~ gamma
Obviously this is soluble with gamma := F c a b, and unflattening
will do exactly that after solving the simple constraints and before
attempting the implications. Before, when we were not unflattening,
we had to push Wanted funeqs in as new givens. Yuk!
Another example that becomes easy: indexed_types/should_fail/T7786
[W] BuriedUnder sub k Empty ~ fsk
[W] Intersect fsk inv ~ s
[w] xxx[1] ~ s
[W] forall[2] . (xxx[1] ~ Empty)
=> Intersect (BuriedUnder sub k Empty) inv ~ Empty
Note [Running plugins on unflattened wanteds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There is an annoying mismatch between solveSimpleGivens and
solveSimpleWanteds, because the latter needs to fiddle with the inert
set, unflatten and zonk the wanteds. It passes the zonked wanteds
to runTcPluginsWanteds, which produces a replacement set of wanteds,
some additional insolubles and a flag indicating whether to go round
the loop again. If so, prepareInertsForImplications is used to remove
the previous wanteds (which will still be in the inert set). Note
that prepareInertsForImplications will discard the insolubles, so we
must keep track of them separately.
-}
solveSimpleGivens :: CtLoc -> [EvVar] -> TcS Cts
-- Solves the givens, adding them to the inert set
-- Returns any insoluble givens, which represent inaccessible code,
-- taking those ones out of the inert set
solveSimpleGivens loc givens
| null givens -- Shortcut for common case
= return emptyCts
| otherwise
= do { go (map mk_given_ct givens)
; takeGivenInsolubles }
where
mk_given_ct ev_id = mkNonCanonical (CtGiven { ctev_evar = ev_id
, ctev_pred = evVarPred ev_id
, ctev_loc = loc })
go givens = do { solveSimples (listToBag givens)
; new_givens <- runTcPluginsGiven
; when (notNull new_givens) (go new_givens)
}
solveSimpleWanteds :: Cts -> TcS WantedConstraints
-- NB: 'simples' may contain /derived/ equalities, floated
-- out from a nested implication. So don't discard deriveds!
solveSimpleWanteds simples
= do { traceTcS "solveSimples {" (ppr simples)
; dflags <- getDynFlags
; (n,wc) <- go 1 (solverIterations dflags) (emptyWC { wc_simple = simples })
; traceTcS "solveSimples end }" $
vcat [ ptext (sLit "iterations =") <+> ppr n
, ptext (sLit "residual =") <+> ppr wc ]
; return wc }
where
go :: Int -> IntWithInf -> WantedConstraints -> TcS (Int, WantedConstraints)
go n limit wc
| n `intGtLimit` limit
= failTcS (hang (ptext (sLit "solveSimpleWanteds: too many iterations")
<+> parens (ptext (sLit "limit =") <+> ppr limit))
2 (vcat [ ptext (sLit "Set limit with -fsolver-iterations=n; n=0 for no limit")
, ptext (sLit "Simples =") <+> ppr simples
, ptext (sLit "WC =") <+> ppr wc ]))
| isEmptyBag (wc_simple wc)
= return (n,wc)
| otherwise
= do { -- Solve
(unif_count, wc1) <- solve_simple_wanteds wc
-- Run plugins
; (rerun_plugin, wc2) <- runTcPluginsWanted wc1
-- See Note [Running plugins on unflattened wanteds]
; if unif_count == 0 && not rerun_plugin
then return (n, wc2) -- Done
else do { traceTcS "solveSimple going round again:" (ppr rerun_plugin)
; go (n+1) limit wc2 } } -- Loop
solve_simple_wanteds :: WantedConstraints -> TcS (Int, WantedConstraints)
-- Try solving these constraints
-- Affects the unification state (of course) but not the inert set
solve_simple_wanteds (WC { wc_simple = simples1, wc_insol = insols1, wc_impl = implics1 })
= nestTcS $
do { solveSimples simples1
; (implics2, tv_eqs, fun_eqs, insols2, others) <- getUnsolvedInerts
; (unif_count, unflattened_eqs) <- reportUnifications $
unflatten tv_eqs fun_eqs
-- See Note [Unflatten after solving the simple wanteds]
; return ( unif_count
, WC { wc_simple = others `andCts` unflattened_eqs
, wc_insol = insols1 `andCts` insols2
, wc_impl = implics1 `unionBags` implics2 }) }
{- Note [The solveSimpleWanteds loop]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Solving a bunch of simple constraints is done in a loop,
(the 'go' loop of 'solveSimpleWanteds'):
1. Try to solve them; unflattening may lead to improvement that
was not exploitable during solving
2. Try the plugin
3. If step 1 did improvement during unflattening; or if the plugin
wants to run again, go back to step 1
Non-obviously, improvement can also take place during
the unflattening that takes place in step (1). See TcFlatten,
See Note [Unflattening can force the solver to iterate]
-}
-- The main solver loop implements Note [Basic Simplifier Plan]
---------------------------------------------------------------
solveSimples :: Cts -> TcS ()
-- Returns the final InertSet in TcS
-- Has no effect on work-list or residual-implications
-- The constraints are initially examined in left-to-right order
solveSimples cts
= {-# SCC "solveSimples" #-}
do { updWorkListTcS (\wl -> foldrBag extendWorkListCt wl cts)
; solve_loop }
where
solve_loop
= {-# SCC "solve_loop" #-}
do { sel <- selectNextWorkItem
; case sel of
Nothing -> return ()
Just ct -> do { runSolverPipeline thePipeline ct
; solve_loop } }
-- | Extract the (inert) givens and invoke the plugins on them.
-- Remove solved givens from the inert set and emit insolubles, but
-- return new work produced so that 'solveSimpleGivens' can feed it back
-- into the main solver.
runTcPluginsGiven :: TcS [Ct]
runTcPluginsGiven
= do { plugins <- getTcPlugins
; if null plugins then return [] else
do { givens <- getInertGivens
; if null givens then return [] else
do { p <- runTcPlugins plugins (givens,[],[])
; let (solved_givens, _, _) = pluginSolvedCts p
; updInertCans (removeInertCts solved_givens)
; mapM_ emitInsoluble (pluginBadCts p)
; return (pluginNewCts p) } } }
-- | Given a bag of (flattened, zonked) wanteds, invoke the plugins on
-- them and produce an updated bag of wanteds (possibly with some new
-- work) and a bag of insolubles. The boolean indicates whether
-- 'solveSimpleWanteds' should feed the updated wanteds back into the
-- main solver.
runTcPluginsWanted :: WantedConstraints -> TcS (Bool, WantedConstraints)
runTcPluginsWanted wc@(WC { wc_simple = simples1, wc_insol = insols1, wc_impl = implics1 })
| isEmptyBag simples1
= return (False, wc)
| otherwise
= do { plugins <- getTcPlugins
; if null plugins then return (False, wc) else
do { given <- getInertGivens
; simples1 <- zonkSimples simples1 -- Plugin requires zonked inputs
; let (wanted, derived) = partition isWantedCt (bagToList simples1)
; p <- runTcPlugins plugins (given, derived, wanted)
; let (_, _, solved_wanted) = pluginSolvedCts p
(_, unsolved_derived, unsolved_wanted) = pluginInputCts p
new_wanted = pluginNewCts p
-- SLPJ: I'm deeply suspicious of this
-- ; updInertCans (removeInertCts $ solved_givens ++ solved_deriveds)
; mapM_ setEv solved_wanted
; return ( notNull (pluginNewCts p)
, WC { wc_simple = listToBag new_wanted `andCts` listToBag unsolved_wanted
`andCts` listToBag unsolved_derived
, wc_insol = listToBag (pluginBadCts p) `andCts` insols1
, wc_impl = implics1 } ) } }
where
setEv :: (EvTerm,Ct) -> TcS ()
setEv (ev,ct) = case ctEvidence ct of
CtWanted {ctev_evar = evar} -> setWantedEvBind evar ev
_ -> panic "runTcPluginsWanted.setEv: attempt to solve non-wanted!"
-- | A triple of (given, derived, wanted) constraints to pass to plugins
type SplitCts = ([Ct], [Ct], [Ct])
-- | A solved triple of constraints, with evidence for wanteds
type SolvedCts = ([Ct], [Ct], [(EvTerm,Ct)])
-- | Represents collections of constraints generated by typechecker
-- plugins
data TcPluginProgress = TcPluginProgress
{ pluginInputCts :: SplitCts
-- ^ Original inputs to the plugins with solved/bad constraints
-- removed, but otherwise unmodified
, pluginSolvedCts :: SolvedCts
-- ^ Constraints solved by plugins
, pluginBadCts :: [Ct]
-- ^ Constraints reported as insoluble by plugins
, pluginNewCts :: [Ct]
-- ^ New constraints emitted by plugins
}
getTcPlugins :: TcS [TcPluginSolver]
getTcPlugins = do { tcg_env <- getGblEnv; return (tcg_tc_plugins tcg_env) }
-- | Starting from a triple of (given, derived, wanted) constraints,
-- invoke each of the typechecker plugins in turn and return
--
-- * the remaining unmodified constraints,
-- * constraints that have been solved,
-- * constraints that are insoluble, and
-- * new work.
--
-- Note that new work generated by one plugin will not be seen by
-- other plugins on this pass (but the main constraint solver will be
-- re-invoked and they will see it later). There is no check that new
-- work differs from the original constraints supplied to the plugin:
-- the plugin itself should perform this check if necessary.
runTcPlugins :: [TcPluginSolver] -> SplitCts -> TcS TcPluginProgress
runTcPlugins plugins all_cts
= foldM do_plugin initialProgress plugins
where
do_plugin :: TcPluginProgress -> TcPluginSolver -> TcS TcPluginProgress
do_plugin p solver = do
result <- runTcPluginTcS (uncurry3 solver (pluginInputCts p))
return $ progress p result
progress :: TcPluginProgress -> TcPluginResult -> TcPluginProgress
progress p (TcPluginContradiction bad_cts) =
p { pluginInputCts = discard bad_cts (pluginInputCts p)
, pluginBadCts = bad_cts ++ pluginBadCts p
}
progress p (TcPluginOk solved_cts new_cts) =
p { pluginInputCts = discard (map snd solved_cts) (pluginInputCts p)
, pluginSolvedCts = add solved_cts (pluginSolvedCts p)
, pluginNewCts = new_cts ++ pluginNewCts p
}
initialProgress = TcPluginProgress all_cts ([], [], []) [] []
discard :: [Ct] -> SplitCts -> SplitCts
discard cts (xs, ys, zs) =
(xs `without` cts, ys `without` cts, zs `without` cts)
without :: [Ct] -> [Ct] -> [Ct]
without = deleteFirstsBy eqCt
eqCt :: Ct -> Ct -> Bool
eqCt c c' = case (ctEvidence c, ctEvidence c') of
(CtGiven pred _ _, CtGiven pred' _ _) -> pred `eqType` pred'
(CtWanted pred _ _, CtWanted pred' _ _) -> pred `eqType` pred'
(CtDerived pred _ , CtDerived pred' _ ) -> pred `eqType` pred'
(_ , _ ) -> False
add :: [(EvTerm,Ct)] -> SolvedCts -> SolvedCts
add xs scs = foldl' addOne scs xs
addOne :: SolvedCts -> (EvTerm,Ct) -> SolvedCts
addOne (givens, deriveds, wanteds) (ev,ct) = case ctEvidence ct of
CtGiven {} -> (ct:givens, deriveds, wanteds)
CtDerived{} -> (givens, ct:deriveds, wanteds)
CtWanted {} -> (givens, deriveds, (ev,ct):wanteds)
type WorkItem = Ct
type SimplifierStage = WorkItem -> TcS (StopOrContinue Ct)
runSolverPipeline :: [(String,SimplifierStage)] -- The pipeline
-> WorkItem -- The work item
-> TcS ()
-- Run this item down the pipeline, leaving behind new work and inerts
runSolverPipeline pipeline workItem
= do { initial_is <- getTcSInerts
; traceTcS "Start solver pipeline {" $
vcat [ ptext (sLit "work item = ") <+> ppr workItem
, ptext (sLit "inerts = ") <+> ppr initial_is]
; bumpStepCountTcS -- One step for each constraint processed
; final_res <- run_pipeline pipeline (ContinueWith workItem)
; final_is <- getTcSInerts
; case final_res of
Stop ev s -> do { traceFireTcS ev s
; traceTcS "End solver pipeline (discharged) }"
(ptext (sLit "inerts =") <+> ppr final_is)
; return () }
ContinueWith ct -> do { traceFireTcS (ctEvidence ct) (ptext (sLit "Kept as inert"))
; traceTcS "End solver pipeline (kept as inert) }" $
vcat [ ptext (sLit "final_item =") <+> ppr ct
, pprTvBndrs (varSetElems $ tyVarsOfCt ct)
, ptext (sLit "inerts =") <+> ppr final_is]
; addInertCan ct }
}
where run_pipeline :: [(String,SimplifierStage)] -> StopOrContinue Ct
-> TcS (StopOrContinue Ct)
run_pipeline [] res = return res
run_pipeline _ (Stop ev s) = return (Stop ev s)
run_pipeline ((stg_name,stg):stgs) (ContinueWith ct)
= do { traceTcS ("runStage " ++ stg_name ++ " {")
(text "workitem = " <+> ppr ct)
; res <- stg ct
; traceTcS ("end stage " ++ stg_name ++ " }") empty
; run_pipeline stgs res }
{-
Example 1:
Inert: {c ~ d, F a ~ t, b ~ Int, a ~ ty} (all given)
Reagent: a ~ [b] (given)
React with (c~d) ==> IR (ContinueWith (a~[b])) True []
React with (F a ~ t) ==> IR (ContinueWith (a~[b])) False [F [b] ~ t]
React with (b ~ Int) ==> IR (ContinueWith (a~[Int]) True []
Example 2:
Inert: {c ~w d, F a ~g t, b ~w Int, a ~w ty}
Reagent: a ~w [b]
React with (c ~w d) ==> IR (ContinueWith (a~[b])) True []
React with (F a ~g t) ==> IR (ContinueWith (a~[b])) True [] (can't rewrite given with wanted!)
etc.
Example 3:
Inert: {a ~ Int, F Int ~ b} (given)
Reagent: F a ~ b (wanted)
React with (a ~ Int) ==> IR (ContinueWith (F Int ~ b)) True []
React with (F Int ~ b) ==> IR Stop True [] -- after substituting we re-canonicalize and get nothing
-}
thePipeline :: [(String,SimplifierStage)]
thePipeline = [ ("canonicalization", TcCanonical.canonicalize)
, ("interact with inerts", interactWithInertsStage)
, ("top-level reactions", topReactionsStage) ]
{-
*********************************************************************************
* *
The interact-with-inert Stage
* *
*********************************************************************************
Note [The Solver Invariant]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
We always add Givens first. So you might think that the solver has
the invariant
If the work-item is Given,
then the inert item must Given
But this isn't quite true. Suppose we have,
c1: [W] beta ~ [alpha], c2 : [W] blah, c3 :[W] alpha ~ Int
After processing the first two, we get
c1: [G] beta ~ [alpha], c2 : [W] blah
Now, c3 does not interact with the the given c1, so when we spontaneously
solve c3, we must re-react it with the inert set. So we can attempt a
reaction between inert c2 [W] and work-item c3 [G].
It *is* true that [Solver Invariant]
If the work-item is Given,
AND there is a reaction
then the inert item must Given
or, equivalently,
If the work-item is Given,
and the inert item is Wanted/Derived
then there is no reaction
-}
-- Interaction result of WorkItem <~> Ct
type StopNowFlag = Bool -- True <=> stop after this interaction
interactWithInertsStage :: WorkItem -> TcS (StopOrContinue Ct)
-- Precondition: if the workitem is a CTyEqCan then it will not be able to
-- react with anything at this stage.
interactWithInertsStage wi
= do { inerts <- getTcSInerts
; let ics = inert_cans inerts
; case wi of
CTyEqCan {} -> interactTyVarEq ics wi
CFunEqCan {} -> interactFunEq ics wi
CIrredEvCan {} -> interactIrred ics wi
CDictCan {} -> interactDict ics wi
_ -> pprPanic "interactWithInerts" (ppr wi) }
-- CHoleCan are put straight into inert_frozen, so never get here
-- CNonCanonical have been canonicalised
data InteractResult
= IRKeep -- Keep the existing inert constraint in the inert set
| IRReplace -- Replace the existing inert constraint with the work item
| IRDelete -- Delete the existing inert constraint from the inert set
instance Outputable InteractResult where
ppr IRKeep = ptext (sLit "keep")
ppr IRReplace = ptext (sLit "replace")
ppr IRDelete = ptext (sLit "delete")
solveOneFromTheOther :: CtEvidence -- Inert
-> CtEvidence -- WorkItem
-> TcS (InteractResult, StopNowFlag)
-- Preconditions:
-- 1) inert and work item represent evidence for the /same/ predicate
-- 2) ip/class/irred evidence (no coercions) only
solveOneFromTheOther ev_i ev_w
| isDerived ev_w -- Work item is Derived; just discard it
= return (IRKeep, True)
| isDerived ev_i -- The inert item is Derived, we can just throw it away,
= return (IRDelete, False) -- The ev_w is inert wrt earlier inert-set items,
-- so it's safe to continue on from this point
| CtWanted { ctev_loc = loc_w } <- ev_w
, prohibitedSuperClassSolve (ctEvLoc ev_i) loc_w
= return (IRDelete, False)
| CtWanted { ctev_evar = ev_id } <- ev_w -- Inert is Given or Wanted
= do { setWantedEvBind ev_id (ctEvTerm ev_i)
; return (IRKeep, True) }
| CtWanted { ctev_loc = loc_i } <- ev_i -- Work item is Given
, prohibitedSuperClassSolve (ctEvLoc ev_w) loc_i
= return (IRKeep, False) -- Just discard the un-usable Given
-- This never actually happens because
-- Givens get processed first
| CtWanted { ctev_evar = ev_id } <- ev_i -- Work item is Given
= do { setWantedEvBind ev_id (ctEvTerm ev_w)
; return (IRReplace, True) }
-- So they are both Given
-- See Note [Replacement vs keeping]
| lvl_i == lvl_w
= do { binds <- getTcEvBindsMap
; return (same_level_strategy binds, True) }
| otherwise -- Both are Given, levels differ
= return (different_level_strategy, True)
where
pred = ctEvPred ev_i
loc_i = ctEvLoc ev_i
loc_w = ctEvLoc ev_w
lvl_i = ctLocLevel loc_i
lvl_w = ctLocLevel loc_w
different_level_strategy
| isIPPred pred, lvl_w > lvl_i = IRReplace
| lvl_w < lvl_i = IRReplace
| otherwise = IRKeep
same_level_strategy binds -- Both Given
| GivenOrigin (InstSC s_i) <- ctLocOrigin loc_i
= case ctLocOrigin loc_w of
GivenOrigin (InstSC s_w) | s_w < s_i -> IRReplace
| otherwise -> IRKeep
_ -> IRReplace
| GivenOrigin (InstSC {}) <- ctLocOrigin loc_w
= IRKeep
| has_binding binds ev_w
, not (has_binding binds ev_i)
= IRReplace
| otherwise = IRKeep
has_binding binds ev = isJust (lookupEvBind binds (ctEvId ev))
{-
Note [Replacement vs keeping]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we have two Given constraints both of type (C tys), say, which should
we keep? More subtle than you might think!
* Constraints come from different levels (different_level_strategy)
- For implicit parameters we want to keep the innermost (deepest)
one, so that it overrides the outer one.
See Note [Shadowing of Implicit Parameters]
- For everything else, we want to keep the outermost one. Reason: that
makes it more likely that the inner one will turn out to be unused,
and can be reported as redundant. See Note [Tracking redundant constraints]
in TcSimplify.
It transpires that using the outermost one is reponsible for an
8% performance improvement in nofib cryptarithm2, compared to
just rolling the dice. I didn't investigate why.
* Constaints coming from the same level (i.e. same implication)
- Always get rid of InstSC ones if possible, since they are less
useful for solving. If both are InstSC, choose the one with
the smallest TypeSize
See Note [Solving superclass constraints] in TcInstDcls
- Keep the one that has a non-trivial evidence binding.
Note [Tracking redundant constraints] again.
Example: f :: (Eq a, Ord a) => blah
then we may find [G] sc_sel (d1::Ord a) :: Eq a
[G] d2 :: Eq a
We want to discard d2 in favour of the superclass selection from
the Ord dictionary.
* Finally, when there is still a choice, use IRKeep rather than
IRReplace, to avoid unnecessary munging of the inert set.
Doing the depth-check for implicit parameters, rather than making the work item
always overrride, is important. Consider
data T a where { T1 :: (?x::Int) => T Int; T2 :: T a }
f :: (?x::a) => T a -> Int
f T1 = ?x
f T2 = 3
We have a [G] (?x::a) in the inert set, and at the pattern match on T1 we add
two new givens in the work-list: [G] (?x::Int)
[G] (a ~ Int)
Now consider these steps
- process a~Int, kicking out (?x::a)
- process (?x::Int), the inner given, adding to inert set
- process (?x::a), the outer given, overriding the inner given
Wrong! The depth-check ensures that the inner implicit parameter wins.
(Actually I think that the order in which the work-list is processed means
that this chain of events won't happen, but that's very fragile.)
*********************************************************************************
* *
interactIrred
* *
*********************************************************************************
-}
-- Two pieces of irreducible evidence: if their types are *exactly identical*
-- we can rewrite them. We can never improve using this:
-- if we want ty1 :: Constraint and have ty2 :: Constraint it clearly does not
-- mean that (ty1 ~ ty2)
interactIrred :: InertCans -> Ct -> TcS (StopOrContinue Ct)
interactIrred inerts workItem@(CIrredEvCan { cc_ev = ev_w })
| let pred = ctEvPred ev_w
(matching_irreds, others) = partitionBag (\ct -> ctPred ct `tcEqType` pred)
(inert_irreds inerts)
, (ct_i : rest) <- bagToList matching_irreds
, let ctev_i = ctEvidence ct_i
= ASSERT( null rest )
do { (inert_effect, stop_now) <- solveOneFromTheOther ctev_i ev_w
; case inert_effect of
IRKeep -> return ()
IRDelete -> updInertIrreds (\_ -> others)
IRReplace -> updInertIrreds (\_ -> others `snocCts` workItem)
-- These const upd's assume that solveOneFromTheOther
-- has no side effects on InertCans
; if stop_now then
return (Stop ev_w (ptext (sLit "Irred equal") <+> parens (ppr inert_effect)))
; else
continueWith workItem }
| otherwise
= continueWith workItem
interactIrred _ wi = pprPanic "interactIrred" (ppr wi)
{-
*********************************************************************************
* *
interactDict
* *
*********************************************************************************
-}
interactDict :: InertCans -> Ct -> TcS (StopOrContinue Ct)
interactDict inerts workItem@(CDictCan { cc_ev = ev_w, cc_class = cls, cc_tyargs = tys })
-- don't ever try to solve CallStack IPs directly from other dicts,
-- we always build new dicts instead.
-- See Note [Overview of implicit CallStacks]
| Just mkEvCs <- isCallStackIP (ctEvLoc ev_w) cls tys
, isWanted ev_w
= do let ev_cs =
case lookupInertDict inerts cls tys of
Just ev | isGiven ev -> mkEvCs (ctEvTerm ev)
_ -> mkEvCs (EvCallStack EvCsEmpty)
-- now we have ev_cs :: CallStack, but the evidence term should
-- be a dictionary, so we have to coerce ev_cs to a
-- dictionary for `IP ip CallStack`
let ip_ty = mkClassPred cls tys
let ev_tm = mkEvCast (EvCallStack ev_cs) (TcCoercion $ wrapIP ip_ty)
addSolvedDict ev_w cls tys
setWantedEvBind (ctEvId ev_w) ev_tm
stopWith ev_w "Wanted CallStack IP"
| Just ctev_i <- lookupInertDict inerts cls tys
= do { (inert_effect, stop_now) <- solveOneFromTheOther ctev_i ev_w
; case inert_effect of
IRKeep -> return ()
IRDelete -> updInertDicts $ \ ds -> delDict ds cls tys
IRReplace -> updInertDicts $ \ ds -> addDict ds cls tys workItem
; if stop_now then
return (Stop ev_w (ptext (sLit "Dict equal") <+> parens (ppr inert_effect)))
else
continueWith workItem }
| cls == ipClass
, isGiven ev_w
= interactGivenIP inerts workItem
| otherwise
= do { addFunDepWork inerts ev_w cls
; continueWith workItem }
interactDict _ wi = pprPanic "interactDict" (ppr wi)
addFunDepWork :: InertCans -> CtEvidence -> Class -> TcS ()
-- Add derived constraints from type-class functional dependencies.
addFunDepWork inerts work_ev cls
= mapBagM_ add_fds (findDictsByClass (inert_dicts inerts) cls)
-- No need to check flavour; fundeps work between
-- any pair of constraints, regardless of flavour
-- Importantly we don't throw workitem back in the
-- worklist because this can cause loops (see #5236)
where
work_pred = ctEvPred work_ev
work_loc = ctEvLoc work_ev
add_fds inert_ct
= emitFunDepDeriveds $
improveFromAnother derived_loc inert_pred work_pred
-- We don't really rewrite tys2, see below _rewritten_tys2, so that's ok
-- NB: We do create FDs for given to report insoluble equations that arise
-- from pairs of Givens, and also because of floating when we approximate
-- implications. The relevant test is: typecheck/should_fail/FDsFromGivens.hs
where
inert_pred = ctPred inert_ct
inert_loc = ctLoc inert_ct
derived_loc = work_loc { ctl_origin = FunDepOrigin1 work_pred work_loc
inert_pred inert_loc }
{-
*********************************************************************************
* *
Implicit parameters
* *
*********************************************************************************
-}
interactGivenIP :: InertCans -> Ct -> TcS (StopOrContinue Ct)
-- Work item is Given (?x:ty)
-- See Note [Shadowing of Implicit Parameters]
interactGivenIP inerts workItem@(CDictCan { cc_ev = ev, cc_class = cls
, cc_tyargs = tys@(ip_str:_) })
= do { updInertCans $ \cans -> cans { inert_dicts = addDict filtered_dicts cls tys workItem }
; stopWith ev "Given IP" }
where
dicts = inert_dicts inerts
ip_dicts = findDictsByClass dicts cls
other_ip_dicts = filterBag (not . is_this_ip) ip_dicts
filtered_dicts = addDictsByClass dicts cls other_ip_dicts
-- Pick out any Given constraints for the same implicit parameter
is_this_ip (CDictCan { cc_ev = ev, cc_tyargs = ip_str':_ })
= isGiven ev && ip_str `tcEqType` ip_str'
is_this_ip _ = False
interactGivenIP _ wi = pprPanic "interactGivenIP" (ppr wi)
{-
Note [Shadowing of Implicit Parameters]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider the following example:
f :: (?x :: Char) => Char
f = let ?x = 'a' in ?x
The "let ?x = ..." generates an implication constraint of the form:
?x :: Char => ?x :: Char
Furthermore, the signature for `f` also generates an implication
constraint, so we end up with the following nested implication:
?x :: Char => (?x :: Char => ?x :: Char)
Note that the wanted (?x :: Char) constraint may be solved in
two incompatible ways: either by using the parameter from the
signature, or by using the local definition. Our intention is
that the local definition should "shadow" the parameter of the
signature, and we implement this as follows: when we add a new
*given* implicit parameter to the inert set, it replaces any existing
givens for the same implicit parameter.
This works for the normal cases but it has an odd side effect
in some pathological programs like this:
-- This is accepted, the second parameter shadows
f1 :: (?x :: Int, ?x :: Char) => Char
f1 = ?x
-- This is rejected, the second parameter shadows
f2 :: (?x :: Int, ?x :: Char) => Int
f2 = ?x
Both of these are actually wrong: when we try to use either one,
we'll get two incompatible wnated constraints (?x :: Int, ?x :: Char),
which would lead to an error.
I can think of two ways to fix this:
1. Simply disallow multiple constratits for the same implicit
parameter---this is never useful, and it can be detected completely
syntactically.
2. Move the shadowing machinery to the location where we nest
implications, and add some code here that will produce an
error if we get multiple givens for the same implicit parameter.
*********************************************************************************
* *
interactFunEq
* *
*********************************************************************************
-}
interactFunEq :: InertCans -> Ct -> TcS (StopOrContinue Ct)
-- Try interacting the work item with the inert set
interactFunEq inerts workItem@(CFunEqCan { cc_ev = ev, cc_fun = tc
, cc_tyargs = args, cc_fsk = fsk })
| Just (CFunEqCan { cc_ev = ev_i, cc_fsk = fsk_i }) <- matching_inerts
= if ev_i `canDischarge` ev
then -- Rewrite work-item using inert
do { traceTcS "reactFunEq (discharge work item):" $
vcat [ text "workItem =" <+> ppr workItem
, text "inertItem=" <+> ppr ev_i ]
; reactFunEq ev_i fsk_i ev fsk
; stopWith ev "Inert rewrites work item" }
else -- Rewrite inert using work-item
ASSERT2( ev `canDischarge` ev_i, ppr ev $$ ppr ev_i )
do { traceTcS "reactFunEq (rewrite inert item):" $
vcat [ text "workItem =" <+> ppr workItem
, text "inertItem=" <+> ppr ev_i ]
; updInertFunEqs $ \ feqs -> insertFunEq feqs tc args workItem
-- Do the updInertFunEqs before the reactFunEq, so that
-- we don't kick out the inertItem as well as consuming it!
; reactFunEq ev fsk ev_i fsk_i
; stopWith ev "Work item rewrites inert" }
| otherwise -- Try improvement
= do { improveLocalFunEqs loc inerts tc args fsk
; continueWith workItem }
where
loc = ctEvLoc ev
funeqs = inert_funeqs inerts
matching_inerts = findFunEqs funeqs tc args
interactFunEq _ workItem = pprPanic "interactFunEq" (ppr workItem)
improveLocalFunEqs :: CtLoc -> InertCans -> TyCon -> [TcType] -> TcTyVar
-> TcS ()
-- Generate derived improvement equalities, by comparing
-- the current work item with inert CFunEqs
-- E.g. x + y ~ z, x + y' ~ z => [D] y ~ y'
improveLocalFunEqs loc inerts fam_tc args fsk
| not (null improvement_eqns)
= do { traceTcS "interactFunEq improvements: " $
vcat [ ptext (sLit "Eqns:") <+> ppr improvement_eqns
, ptext (sLit "Candidates:") <+> ppr funeqs_for_tc
, ptext (sLit "TvEqs:") <+> ppr tv_eqs ]
; mapM_ (unifyDerived loc Nominal) improvement_eqns }
| otherwise
= return ()
where
tv_eqs = inert_model inerts
funeqs = inert_funeqs inerts
funeqs_for_tc = findFunEqsByTyCon funeqs fam_tc
rhs = lookupFlattenTyVar tv_eqs fsk
--------------------
improvement_eqns
| Just ops <- isBuiltInSynFamTyCon_maybe fam_tc
= -- Try built-in families, notably for arithmethic
concatMap (do_one_built_in ops) funeqs_for_tc
| Injective injective_args <- familyTyConInjectivityInfo fam_tc
= -- Try improvement from type families with injectivity annotations
concatMap (do_one_injective injective_args) funeqs_for_tc
| otherwise
= []
--------------------
do_one_built_in ops (CFunEqCan { cc_tyargs = iargs, cc_fsk = ifsk })
= sfInteractInert ops args rhs iargs (lookupFlattenTyVar tv_eqs ifsk)
do_one_built_in _ _ = pprPanic "interactFunEq 1" (ppr fam_tc)
--------------------
-- See Note [Type inference for type families with injectivity]
do_one_injective injective_args
(CFunEqCan { cc_tyargs = iargs, cc_fsk = ifsk })
| rhs `tcEqType` lookupFlattenTyVar tv_eqs ifsk
= [Pair arg iarg | (arg, iarg, True)
<- zip3 args iargs injective_args ]
| otherwise
= []
do_one_injective _ _ = pprPanic "interactFunEq 2" (ppr fam_tc)
-------------
lookupFlattenTyVar :: InertModel -> TcTyVar -> TcType
-- ^ Look up a flatten-tyvar in the inert nominal TyVarEqs;
-- this is used only when dealing with a CFunEqCan
lookupFlattenTyVar model ftv
= case lookupVarEnv model ftv of
Just (CTyEqCan { cc_rhs = rhs, cc_eq_rel = NomEq }) -> rhs
_ -> mkTyVarTy ftv
reactFunEq :: CtEvidence -> TcTyVar -- From this :: F tys ~ fsk1
-> CtEvidence -> TcTyVar -- Solve this :: F tys ~ fsk2
-> TcS ()
reactFunEq from_this fsk1 (CtGiven { ctev_evar = evar, ctev_loc = loc }) fsk2
= do { let fsk_eq_co = mkTcSymCo (mkTcCoVarCo evar)
`mkTcTransCo` ctEvCoercion from_this
-- :: fsk2 ~ fsk1
fsk_eq_pred = mkTcEqPred (mkTyVarTy fsk2) (mkTyVarTy fsk1)
; new_ev <- newGivenEvVar loc (fsk_eq_pred, EvCoercion fsk_eq_co)
; emitWorkNC [new_ev] }
reactFunEq from_this fuv1 ev fuv2
= do { traceTcS "reactFunEq" (ppr from_this $$ ppr fuv1 $$ ppr ev $$ ppr fuv2)
; dischargeFmv ev fuv2 (ctEvCoercion from_this) (mkTyVarTy fuv1)
; traceTcS "reactFunEq done" (ppr from_this $$ ppr fuv1 $$ ppr ev $$ ppr fuv2) }
{-
Note [Type inference for type families with injectivity]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have a type family with an injectivity annotation:
type family F a b = r | r -> b
Then if we have two CFunEqCan constraints for F with the same RHS
F s1 t1 ~ rhs
F s2 t2 ~ rhs
then we can use the injectivity to get a new Derived constraint on
the injective argument
[D] t1 ~ t2
That in turn can help GHC solve constraints that would otherwise require
guessing. For example, consider the ambiguity check for
f :: F Int b -> Int
We get the constraint
[W] F Int b ~ F Int beta
where beta is a unification variable. Injectivity lets us pick beta ~ b.
Injectivity information is also used at the call sites. For example:
g = f True
gives rise to
[W] F Int b ~ Bool
from which we can derive b. This requires looking at the defining equations of
a type family, ie. finding equation with a matching RHS (Bool in this example)
and infering values of type variables (b in this example) from the LHS patterns
of the matching equation. For closed type families we have to perform
additional apartness check for the selected equation to check that the selected
is guaranteed to fire for given LHS arguments.
These new constraints are simply *Derived* constraints; they have no evidence.
We could go further and offer evidence from decomposing injective type-function
applications, but that would require new evidence forms, and an extension to
FC, so we don't do that right now (Dec 14).
See also Note [Injective type families] in TyCon
Note [Cache-caused loops]
~~~~~~~~~~~~~~~~~~~~~~~~~
It is very dangerous to cache a rewritten wanted family equation as 'solved' in our
solved cache (which is the default behaviour or xCtEvidence), because the interaction
may not be contributing towards a solution. Here is an example:
Initial inert set:
[W] g1 : F a ~ beta1
Work item:
[W] g2 : F a ~ beta2
The work item will react with the inert yielding the _same_ inert set plus:
i) Will set g2 := g1 `cast` g3
ii) Will add to our solved cache that [S] g2 : F a ~ beta2
iii) Will emit [W] g3 : beta1 ~ beta2
Now, the g3 work item will be spontaneously solved to [G] g3 : beta1 ~ beta2
and then it will react the item in the inert ([W] g1 : F a ~ beta1). So it
will set
g1 := g ; sym g3
and what is g? Well it would ideally be a new goal of type (F a ~ beta2) but
remember that we have this in our solved cache, and it is ... g2! In short we
created the evidence loop:
g2 := g1 ; g3
g3 := refl
g1 := g2 ; sym g3
To avoid this situation we do not cache as solved any workitems (or inert)
which did not really made a 'step' towards proving some goal. Solved's are
just an optimization so we don't lose anything in terms of completeness of
solving.
Note [Efficient Orientation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we are interacting two FunEqCans with the same LHS:
(inert) ci :: (F ty ~ xi_i)
(work) cw :: (F ty ~ xi_w)
We prefer to keep the inert (else we pass the work item on down
the pipeline, which is a bit silly). If we keep the inert, we
will (a) discharge 'cw'
(b) produce a new equality work-item (xi_w ~ xi_i)
Notice the orientation (xi_w ~ xi_i) NOT (xi_i ~ xi_w):
new_work :: xi_w ~ xi_i
cw := ci ; sym new_work
Why? Consider the simplest case when xi1 is a type variable. If
we generate xi1~xi2, porcessing that constraint will kick out 'ci'.
If we generate xi2~xi1, there is less chance of that happening.
Of course it can and should still happen if xi1=a, xi1=Int, say.
But we want to avoid it happening needlessly.
Similarly, if we *can't* keep the inert item (because inert is Wanted,
and work is Given, say), we prefer to orient the new equality (xi_i ~
xi_w).
Note [Carefully solve the right CFunEqCan]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
---- OLD COMMENT, NOW NOT NEEDED
---- because we now allow multiple
---- wanted FunEqs with the same head
Consider the constraints
c1 :: F Int ~ a -- Arising from an application line 5
c2 :: F Int ~ Bool -- Arising from an application line 10
Suppose that 'a' is a unification variable, arising only from
flattening. So there is no error on line 5; it's just a flattening
variable. But there is (or might be) an error on line 10.
Two ways to combine them, leaving either (Plan A)
c1 :: F Int ~ a -- Arising from an application line 5
c3 :: a ~ Bool -- Arising from an application line 10
or (Plan B)
c2 :: F Int ~ Bool -- Arising from an application line 10
c4 :: a ~ Bool -- Arising from an application line 5
Plan A will unify c3, leaving c1 :: F Int ~ Bool as an error
on the *totally innocent* line 5. An example is test SimpleFail16
where the expected/actual message comes out backwards if we use
the wrong plan.
The second is the right thing to do. Hence the isMetaTyVarTy
test when solving pairwise CFunEqCan.
*********************************************************************************
* *
interactTyVarEq
* *
*********************************************************************************
-}
interactTyVarEq :: InertCans -> Ct -> TcS (StopOrContinue Ct)
-- CTyEqCans are always consumed, so always returns Stop
interactTyVarEq inerts workItem@(CTyEqCan { cc_tyvar = tv
, cc_rhs = rhs
, cc_ev = ev
, cc_eq_rel = eq_rel })
| (ev_i : _) <- [ ev_i | CTyEqCan { cc_ev = ev_i, cc_rhs = rhs_i }
<- findTyEqs inerts tv
, ev_i `canDischarge` ev
, rhs_i `tcEqType` rhs ]
= -- Inert: a ~ b
-- Work item: a ~ b
do { setEvBindIfWanted ev (ctEvTerm ev_i)
; stopWith ev "Solved from inert" }
| Just tv_rhs <- getTyVar_maybe rhs
, (ev_i : _) <- [ ev_i | CTyEqCan { cc_ev = ev_i, cc_rhs = rhs_i }
<- findTyEqs inerts tv_rhs
, ev_i `canDischarge` ev
, rhs_i `tcEqType` mkTyVarTy tv ]
= -- Inert: a ~ b
-- Work item: b ~ a
do { setEvBindIfWanted ev
(EvCoercion (mkTcSymCo (ctEvCoercion ev_i)))
; stopWith ev "Solved from inert (r)" }
| otherwise
= do { tclvl <- getTcLevel
; if canSolveByUnification tclvl ev eq_rel tv rhs
then do { solveByUnification ev tv rhs
; n_kicked <- kickOutAfterUnification tv
; return (Stop ev (ptext (sLit "Solved by unification") <+> ppr_kicked n_kicked)) }
else do { traceTcS "Can't solve tyvar equality"
(vcat [ text "LHS:" <+> ppr tv <+> dcolon <+> ppr (tyVarKind tv)
, ppWhen (isMetaTyVar tv) $
nest 4 (text "TcLevel of" <+> ppr tv
<+> text "is" <+> ppr (metaTyVarTcLevel tv))
, text "RHS:" <+> ppr rhs <+> dcolon <+> ppr (typeKind rhs)
, text "TcLevel =" <+> ppr tclvl ])
; addInertEq workItem
; return (Stop ev (ptext (sLit "Kept as inert"))) } }
interactTyVarEq _ wi = pprPanic "interactTyVarEq" (ppr wi)
-- @trySpontaneousSolve wi@ solves equalities where one side is a
-- touchable unification variable.
-- Returns True <=> spontaneous solve happened
canSolveByUnification :: TcLevel -> CtEvidence -> EqRel
-> TcTyVar -> Xi -> Bool
canSolveByUnification tclvl gw eq_rel tv xi
| ReprEq <- eq_rel -- we never solve representational equalities this way.
= False
| isGiven gw -- See Note [Touchables and givens]
= False
| isTouchableMetaTyVar tclvl tv
= case metaTyVarInfo tv of
SigTv -> is_tyvar xi
_ -> True
| otherwise -- Untouchable
= False
where
is_tyvar xi
= case tcGetTyVar_maybe xi of
Nothing -> False
Just tv -> case tcTyVarDetails tv of
MetaTv { mtv_info = info }
-> case info of
SigTv -> True
_ -> False
SkolemTv {} -> True
FlatSkol {} -> False
RuntimeUnk -> True
solveByUnification :: CtEvidence -> TcTyVar -> Xi -> TcS ()
-- Solve with the identity coercion
-- Precondition: kind(xi) is a sub-kind of kind(tv)
-- Precondition: CtEvidence is Wanted or Derived
-- Precondition: CtEvidence is nominal
-- Returns: workItem where
-- workItem = the new Given constraint
--
-- NB: No need for an occurs check here, because solveByUnification always
-- arises from a CTyEqCan, a *canonical* constraint. Its invariants
-- say that in (a ~ xi), the type variable a does not appear in xi.
-- See TcRnTypes.Ct invariants.
--
-- Post: tv is unified (by side effect) with xi;
-- we often write tv := xi
solveByUnification wd tv xi
= do { let tv_ty = mkTyVarTy tv
; traceTcS "Sneaky unification:" $
vcat [text "Unifies:" <+> ppr tv <+> ptext (sLit ":=") <+> ppr xi,
text "Coercion:" <+> pprEq tv_ty xi,
text "Left Kind is:" <+> ppr (typeKind tv_ty),
text "Right Kind is:" <+> ppr (typeKind xi) ]
; let xi' = defaultKind xi
-- We only instantiate kind unification variables
-- with simple kinds like *, not OpenKind or ArgKind
-- cf TcUnify.uUnboundKVar
; unifyTyVar tv xi'
; setEvBindIfWanted wd (EvCoercion (mkTcNomReflCo xi')) }
ppr_kicked :: Int -> SDoc
ppr_kicked 0 = empty
ppr_kicked n = parens (int n <+> ptext (sLit "kicked out"))
{- Note [Avoid double unifications]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The spontaneous solver has to return a given which mentions the unified unification
variable *on the left* of the equality. Here is what happens if not:
Original wanted: (a ~ alpha), (alpha ~ Int)
We spontaneously solve the first wanted, without changing the order!
given : a ~ alpha [having unified alpha := a]
Now the second wanted comes along, but he cannot rewrite the given, so we simply continue.
At the end we spontaneously solve that guy, *reunifying* [alpha := Int]
We avoid this problem by orienting the resulting given so that the unification
variable is on the left. [Note that alternatively we could attempt to
enforce this at canonicalization]
See also Note [No touchables as FunEq RHS] in TcSMonad; avoiding
double unifications is the main reason we disallow touchable
unification variables as RHS of type family equations: F xis ~ alpha.
************************************************************************
* *
* Functional dependencies, instantiation of equations
* *
************************************************************************
When we spot an equality arising from a functional dependency,
we now use that equality (a "wanted") to rewrite the work-item
constraint right away. This avoids two dangers
Danger 1: If we send the original constraint on down the pipeline
it may react with an instance declaration, and in delicate
situations (when a Given overlaps with an instance) that
may produce new insoluble goals: see Trac #4952
Danger 2: If we don't rewrite the constraint, it may re-react
with the same thing later, and produce the same equality
again --> termination worries.
To achieve this required some refactoring of FunDeps.hs (nicer
now!).
-}
emitFunDepDeriveds :: [FunDepEqn CtLoc] -> TcS ()
emitFunDepDeriveds fd_eqns
= mapM_ do_one_FDEqn fd_eqns
where
do_one_FDEqn (FDEqn { fd_qtvs = tvs, fd_eqs = eqs, fd_loc = loc })
| null tvs -- Common shortcut
= mapM_ (unifyDerived loc Nominal) eqs
| otherwise
= do { (subst, _) <- instFlexiTcS tvs -- Takes account of kind substitution
; mapM_ (do_one_eq loc subst) eqs }
do_one_eq loc subst (Pair ty1 ty2)
= unifyDerived loc Nominal $
Pair (Type.substTy subst ty1) (Type.substTy subst ty2)
{-
*********************************************************************************
* *
The top-reaction Stage
* *
*********************************************************************************
-}
topReactionsStage :: WorkItem -> TcS (StopOrContinue Ct)
topReactionsStage wi
= do { tir <- doTopReact wi
; case tir of
ContinueWith wi -> continueWith wi
Stop ev s -> return (Stop ev (ptext (sLit "Top react:") <+> s)) }
doTopReact :: WorkItem -> TcS (StopOrContinue Ct)
-- The work item does not react with the inert set, so try interaction with top-level
-- instances. Note:
--
-- (a) The place to add superclasses in not here in doTopReact stage.
-- Instead superclasses are added in the worklist as part of the
-- canonicalization process. See Note [Adding superclasses].
doTopReact work_item
= do { traceTcS "doTopReact" (ppr work_item)
; case work_item of
CDictCan {} -> do { inerts <- getTcSInerts
; doTopReactDict inerts work_item }
CFunEqCan {} -> doTopReactFunEq work_item
_ -> -- Any other work item does not react with any top-level equations
continueWith work_item }
--------------------
doTopReactDict :: InertSet -> Ct -> TcS (StopOrContinue Ct)
-- Try to use type-class instance declarations to simplify the constraint
doTopReactDict inerts work_item@(CDictCan { cc_ev = fl, cc_class = cls
, cc_tyargs = xis })
| isGiven fl -- Never use instances for Given constraints
= do { try_fundep_improvement
; continueWith work_item }
| Just ev <- lookupSolvedDict inerts cls xis -- Cached
= do { setEvBindIfWanted fl (ctEvTerm ev);
; stopWith fl "Dict/Top (cached)" }
| isDerived fl -- Use type-class instances for Deriveds, in the hope
-- of generating some improvements
-- C.f. Example 3 of Note [The improvement story]
-- It's easy because no evidence is involved
= do { dflags <- getDynFlags
; lkup_inst_res <- matchClassInst dflags inerts cls xis dict_loc
; case lkup_inst_res of
GenInst preds _ s -> do { emitNewDeriveds dict_loc preds
; unless s $
insertSafeOverlapFailureTcS work_item
; stopWith fl "Dict/Top (solved)" }
NoInstance -> do { -- If there is no instance, try improvement
try_fundep_improvement
; continueWith work_item } }
| otherwise -- Wanted, but not cached
= do { dflags <- getDynFlags
; lkup_inst_res <- matchClassInst dflags inerts cls xis dict_loc
; case lkup_inst_res of
GenInst theta mk_ev s -> do { addSolvedDict fl cls xis
; unless s $
insertSafeOverlapFailureTcS work_item
; solve_from_instance theta mk_ev }
NoInstance -> do { try_fundep_improvement
; continueWith work_item } }
where
dict_pred = mkClassPred cls xis
dict_loc = ctEvLoc fl
dict_origin = ctLocOrigin dict_loc
deeper_loc = zap_origin (bumpCtLocDepth dict_loc)
zap_origin loc -- After applying an instance we can set ScOrigin to
-- infinity, so that prohibitedSuperClassSolve never fires
| ScOrigin {} <- dict_origin
= setCtLocOrigin loc (ScOrigin infinity)
| otherwise
= loc
solve_from_instance :: [TcPredType] -> ([EvId] -> EvTerm) -> TcS (StopOrContinue Ct)
-- Precondition: evidence term matches the predicate workItem
solve_from_instance theta mk_ev
| null theta
= do { traceTcS "doTopReact/found nullary instance for" $ ppr fl
; setWantedEvBind (ctEvId fl) (mk_ev [])
; stopWith fl "Dict/Top (solved, no new work)" }
| otherwise
= do { checkReductionDepth deeper_loc dict_pred
; traceTcS "doTopReact/found non-nullary instance for" $ ppr fl
; evc_vars <- mapM (newWantedEvVar deeper_loc) theta
; setWantedEvBind (ctEvId fl) (mk_ev (map (ctEvId . fst) evc_vars))
; emitWorkNC (freshGoals evc_vars)
; stopWith fl "Dict/Top (solved, more work)" }
-- We didn't solve it; so try functional dependencies with
-- the instance environment, and return
-- See also Note [Weird fundeps]
try_fundep_improvement
= do { traceTcS "try_fundeps" (ppr work_item)
; instEnvs <- getInstEnvs
; emitFunDepDeriveds $
improveFromInstEnv instEnvs mk_ct_loc dict_pred }
mk_ct_loc :: PredType -- From instance decl
-> SrcSpan -- also from instance deol
-> CtLoc
mk_ct_loc inst_pred inst_loc
= dict_loc { ctl_origin = FunDepOrigin2 dict_pred dict_origin
inst_pred inst_loc }
doTopReactDict _ w = pprPanic "doTopReactDict" (ppr w)
--------------------
doTopReactFunEq :: Ct -> TcS (StopOrContinue Ct)
doTopReactFunEq work_item = do { fam_envs <- getFamInstEnvs
; do_top_fun_eq fam_envs work_item }
do_top_fun_eq :: FamInstEnvs -> Ct -> TcS (StopOrContinue Ct)
do_top_fun_eq fam_envs work_item@(CFunEqCan { cc_ev = old_ev, cc_fun = fam_tc
, cc_tyargs = args , cc_fsk = fsk })
| Just (ax_co, rhs_ty) <- reduceTyFamApp_maybe fam_envs Nominal fam_tc args
-- Look up in top-level instances, or built-in axiom
-- See Note [MATCHING-SYNONYMS]
= reduce_top_fun_eq old_ev fsk (TcCoercion ax_co) rhs_ty
| otherwise
= do { improveTopFunEqs (ctEvLoc old_ev) fam_envs fam_tc args fsk
; continueWith work_item }
do_top_fun_eq _ w = pprPanic "doTopReactFunEq" (ppr w)
reduce_top_fun_eq :: CtEvidence -> TcTyVar -> TcCoercion -> TcType
-> TcS (StopOrContinue Ct)
-- Found an applicable top-level axiom: use it to reduce
reduce_top_fun_eq old_ev fsk ax_co rhs_ty
| Just (tc, tc_args) <- tcSplitTyConApp_maybe rhs_ty
, isTypeFamilyTyCon tc
, tc_args `lengthIs` tyConArity tc -- Short-cut
= shortCutReduction old_ev fsk ax_co tc tc_args
-- Try shortcut; see Note [Short cut for top-level reaction]
| isGiven old_ev -- Not shortcut
= do { let final_co = mkTcSymCo (ctEvCoercion old_ev) `mkTcTransCo` ax_co
-- final_co :: fsk ~ rhs_ty
; new_ev <- newGivenEvVar deeper_loc (mkTcEqPred (mkTyVarTy fsk) rhs_ty,
EvCoercion final_co)
; emitWorkNC [new_ev] -- Non-cannonical; that will mean we flatten rhs_ty
; stopWith old_ev "Fun/Top (given)" }
-- So old_ev is Wanted or Derived
| not (fsk `elemVarSet` tyVarsOfType rhs_ty)
= do { dischargeFmv old_ev fsk ax_co rhs_ty
; traceTcS "doTopReactFunEq" $
vcat [ text "old_ev:" <+> ppr old_ev
, nest 2 (text ":=") <+> ppr ax_co ]
; stopWith old_ev "Fun/Top (wanted)" }
| otherwise -- We must not assign ufsk := ...ufsk...!
= do { alpha_ty <- newFlexiTcSTy (tyVarKind fsk)
; let pred = mkTcEqPred alpha_ty rhs_ty
; new_ev <- case old_ev of
CtWanted {} -> do { ev <- newWantedEvVarNC loc pred
; updWorkListTcS (extendWorkListEq (mkNonCanonical ev))
; return ev }
CtDerived {} -> do { ev <- newDerivedNC loc pred
; updWorkListTcS (extendWorkListDerived loc ev)
; return ev }
_ -> pprPanic "reduce_top_fun_eq" (ppr old_ev)
-- By emitting this as non-canonical, we deal with all
-- flattening, occurs-check, and ufsk := ufsk issues
; let final_co = ax_co `mkTcTransCo` mkTcSymCo (ctEvCoercion new_ev)
-- ax_co :: fam_tc args ~ rhs_ty
-- ev :: alpha ~ rhs_ty
-- ufsk := alpha
-- final_co :: fam_tc args ~ alpha
; dischargeFmv old_ev fsk final_co alpha_ty
; traceTcS "doTopReactFunEq (occurs)" $
vcat [ text "old_ev:" <+> ppr old_ev
, nest 2 (text ":=") <+> ppr final_co
, text "new_ev:" <+> ppr new_ev ]
; stopWith old_ev "Fun/Top (wanted)" }
where
loc = ctEvLoc old_ev
deeper_loc = bumpCtLocDepth loc
improveTopFunEqs :: CtLoc -> FamInstEnvs
-> TyCon -> [TcType] -> TcTyVar -> TcS ()
improveTopFunEqs loc fam_envs fam_tc args fsk
= do { model <- getInertModel
; eqns <- improve_top_fun_eqs fam_envs fam_tc args
(lookupFlattenTyVar model fsk)
; mapM_ (unifyDerived loc Nominal) eqns }
improve_top_fun_eqs :: FamInstEnvs
-> TyCon -> [TcType] -> TcType
-> TcS [Eqn]
improve_top_fun_eqs fam_envs fam_tc args rhs_ty
| Just ops <- isBuiltInSynFamTyCon_maybe fam_tc
= return (sfInteractTop ops args rhs_ty)
-- see Note [Type inference for type families with injectivity]
| isOpenTypeFamilyTyCon fam_tc
, Injective injective_args <- familyTyConInjectivityInfo fam_tc
= -- it is possible to have several compatible equations in an open type
-- family but we only want to derive equalities from one such equation.
concatMapM (injImproveEqns injective_args) (take 1 $
buildImprovementData (lookupFamInstEnvByTyCon fam_envs fam_tc)
fi_tys fi_rhs (const Nothing))
| Just ax <- isClosedSynFamilyTyConWithAxiom_maybe fam_tc
, Injective injective_args <- familyTyConInjectivityInfo fam_tc
= concatMapM (injImproveEqns injective_args) $
buildImprovementData (fromBranches (co_ax_branches ax))
cab_lhs cab_rhs Just
| otherwise
= return []
where
buildImprovementData
:: [a] -- axioms for a TF (FamInst or CoAxBranch)
-> (a -> [Type]) -- get LHS of an axiom
-> (a -> Type) -- get RHS of an axiom
-> (a -> Maybe CoAxBranch) -- Just => apartness check required
-> [( [Type], TvSubst, TyVarSet, Maybe CoAxBranch )]
-- Result:
-- ( [arguments of a matching axiom]
-- , RHS-unifying substitution
-- , axiom variables without substitution
-- , Maybe matching axiom [Nothing - open TF, Just - closed TF ] )
buildImprovementData axioms axiomLHS axiomRHS wrap =
[ (ax_args, subst, unsubstTvs, wrap axiom)
| axiom <- axioms
, let ax_args = axiomLHS axiom
, let ax_rhs = axiomRHS axiom
, Just subst <- [tcUnifyTyWithTFs False ax_rhs rhs_ty]
, let tvs = tyVarsOfTypes ax_args
notInSubst tv = not (tv `elemVarEnv` getTvSubstEnv subst)
unsubstTvs = filterVarSet notInSubst tvs ]
injImproveEqns :: [Bool]
-> ([Type], TvSubst, TyVarSet, Maybe CoAxBranch)
-> TcS [Eqn]
injImproveEqns inj_args (ax_args, theta, unsubstTvs, cabr) = do
(theta', _) <- instFlexiTcS (varSetElems unsubstTvs)
let subst = theta `unionTvSubst` theta'
return [ Pair arg (substTy subst ax_arg)
| case cabr of
Just cabr' -> apartnessCheck (substTys subst ax_args) cabr'
_ -> True
, (arg, ax_arg, True) <- zip3 args ax_args inj_args ]
shortCutReduction :: CtEvidence -> TcTyVar -> TcCoercion
-> TyCon -> [TcType] -> TcS (StopOrContinue Ct)
-- See Note [Top-level reductions for type functions]
shortCutReduction old_ev fsk ax_co fam_tc tc_args
| isGiven old_ev
= ASSERT( ctEvEqRel old_ev == NomEq )
do { (xis, cos) <- flattenManyNom old_ev tc_args
-- ax_co :: F args ~ G tc_args
-- cos :: xis ~ tc_args
-- old_ev :: F args ~ fsk
-- G cos ; sym ax_co ; old_ev :: G xis ~ fsk
; new_ev <- newGivenEvVar deeper_loc
( mkTcEqPred (mkTyConApp fam_tc xis) (mkTyVarTy fsk)
, EvCoercion (mkTcTyConAppCo Nominal fam_tc cos
`mkTcTransCo` mkTcSymCo ax_co
`mkTcTransCo` ctEvCoercion old_ev) )
; let new_ct = CFunEqCan { cc_ev = new_ev, cc_fun = fam_tc, cc_tyargs = xis, cc_fsk = fsk }
; emitWorkCt new_ct
; stopWith old_ev "Fun/Top (given, shortcut)" }
| otherwise
= ASSERT( not (isDerived old_ev) ) -- Caller ensures this
ASSERT( ctEvEqRel old_ev == NomEq )
do { (xis, cos) <- flattenManyNom old_ev tc_args
-- ax_co :: F args ~ G tc_args
-- cos :: xis ~ tc_args
-- G cos ; sym ax_co ; old_ev :: G xis ~ fsk
-- new_ev :: G xis ~ fsk
-- old_ev :: F args ~ fsk := ax_co ; sym (G cos) ; new_ev
; new_ev <- newWantedEvVarNC deeper_loc
(mkTcEqPred (mkTyConApp fam_tc xis) (mkTyVarTy fsk))
; setWantedEvBind (ctEvId old_ev)
(EvCoercion (ax_co `mkTcTransCo` mkTcSymCo (mkTcTyConAppCo Nominal fam_tc cos)
`mkTcTransCo` ctEvCoercion new_ev))
; let new_ct = CFunEqCan { cc_ev = new_ev, cc_fun = fam_tc, cc_tyargs = xis, cc_fsk = fsk }
; emitWorkCt new_ct
; stopWith old_ev "Fun/Top (wanted, shortcut)" }
where
loc = ctEvLoc old_ev
deeper_loc = bumpCtLocDepth loc
dischargeFmv :: CtEvidence -> TcTyVar -> TcCoercion -> TcType -> TcS ()
-- (dischargeFmv x fmv co ty)
-- [W] ev :: F tys ~ fmv
-- co :: F tys ~ xi
-- Precondition: fmv is not filled, and fuv `notElem` xi
--
-- Then set fmv := xi,
-- set ev := co
-- kick out any inert things that are now rewritable
--
-- Does not evaluate 'co' if 'ev' is Derived
dischargeFmv ev fmv co xi
= ASSERT2( not (fmv `elemVarSet` tyVarsOfType xi), ppr ev $$ ppr fmv $$ ppr xi )
do { setEvBindIfWanted ev (EvCoercion co)
; unflattenFmv fmv xi
; n_kicked <- kickOutAfterUnification fmv
; traceTcS "dischargeFmv" (ppr fmv <+> equals <+> ppr xi $$ ppr_kicked n_kicked) }
{- Note [Top-level reductions for type functions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
c.f. Note [The flattening story] in TcFlatten
Suppose we have a CFunEqCan F tys ~ fmv/fsk, and a matching axiom.
Here is what we do, in four cases:
* Wanteds: general firing rule
(work item) [W] x : F tys ~ fmv
instantiate axiom: ax_co : F tys ~ rhs
Then:
Discharge fmv := alpha
Discharge x := ax_co ; sym x2
New wanted [W] x2 : alpha ~ rhs (Non-canonical)
This is *the* way that fmv's get unified; even though they are
"untouchable".
NB: it can be the case that fmv appears in the (instantiated) rhs.
In that case the new Non-canonical wanted will be loopy, but that's
ok. But it's good reason NOT to claim that it is canonical!
* Wanteds: short cut firing rule
Applies when the RHS of the axiom is another type-function application
(work item) [W] x : F tys ~ fmv
instantiate axiom: ax_co : F tys ~ G rhs_tys
It would be a waste to create yet another fmv for (G rhs_tys).
Instead (shortCutReduction):
- Flatten rhs_tys (cos : rhs_tys ~ rhs_xis)
- Add G rhs_xis ~ fmv to flat cache (note: the same old fmv)
- New canonical wanted [W] x2 : G rhs_xis ~ fmv (CFunEqCan)
- Discharge x := ax_co ; G cos ; x2
* Givens: general firing rule
(work item) [G] g : F tys ~ fsk
instantiate axiom: ax_co : F tys ~ rhs
Now add non-canonical given (since rhs is not flat)
[G] (sym g ; ax_co) : fsk ~ rhs (Non-canonical)
* Givens: short cut firing rule
Applies when the RHS of the axiom is another type-function application
(work item) [G] g : F tys ~ fsk
instantiate axiom: ax_co : F tys ~ G rhs_tys
It would be a waste to create yet another fsk for (G rhs_tys).
Instead (shortCutReduction):
- Flatten rhs_tys: flat_cos : tys ~ flat_tys
- Add new Canonical given
[G] (sym (G flat_cos) ; co ; g) : G flat_tys ~ fsk (CFunEqCan)
Note [Cached solved FunEqs]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
When trying to solve, say (FunExpensive big-type ~ ty), it's important
to see if we have reduced (FunExpensive big-type) before, lest we
simply repeat it. Hence the lookup in inert_solved_funeqs. Moreover
we must use `canDischarge` because both uses might (say) be Wanteds,
and we *still* want to save the re-computation.
Note [MATCHING-SYNONYMS]
~~~~~~~~~~~~~~~~~~~~~~~~
When trying to match a dictionary (D tau) to a top-level instance, or a
type family equation (F taus_1 ~ tau_2) to a top-level family instance,
we do *not* need to expand type synonyms because the matcher will do that for us.
Note [RHS-FAMILY-SYNONYMS]
~~~~~~~~~~~~~~~~~~~~~~~~~~
The RHS of a family instance is represented as yet another constructor which is
like a type synonym for the real RHS the programmer declared. Eg:
type instance F (a,a) = [a]
Becomes:
:R32 a = [a] -- internal type synonym introduced
F (a,a) ~ :R32 a -- instance
When we react a family instance with a type family equation in the work list
we keep the synonym-using RHS without expansion.
Note [FunDep and implicit parameter reactions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Currently, our story of interacting two dictionaries (or a dictionary
and top-level instances) for functional dependencies, and implicit
paramters, is that we simply produce new Derived equalities. So for example
class D a b | a -> b where ...
Inert:
d1 :g D Int Bool
WorkItem:
d2 :w D Int alpha
We generate the extra work item
cv :d alpha ~ Bool
where 'cv' is currently unused. However, this new item can perhaps be
spontaneously solved to become given and react with d2,
discharging it in favour of a new constraint d2' thus:
d2' :w D Int Bool
d2 := d2' |> D Int cv
Now d2' can be discharged from d1
We could be more aggressive and try to *immediately* solve the dictionary
using those extra equalities, but that requires those equalities to carry
evidence and derived do not carry evidence.
If that were the case with the same inert set and work item we might dischard
d2 directly:
cv :w alpha ~ Bool
d2 := d1 |> D Int cv
But in general it's a bit painful to figure out the necessary coercion,
so we just take the first approach. Here is a better example. Consider:
class C a b c | a -> b
And:
[Given] d1 : C T Int Char
[Wanted] d2 : C T beta Int
In this case, it's *not even possible* to solve the wanted immediately.
So we should simply output the functional dependency and add this guy
[but NOT its superclasses] back in the worklist. Even worse:
[Given] d1 : C T Int beta
[Wanted] d2: C T beta Int
Then it is solvable, but its very hard to detect this on the spot.
It's exactly the same with implicit parameters, except that the
"aggressive" approach would be much easier to implement.
Note [Weird fundeps]
~~~~~~~~~~~~~~~~~~~~
Consider class Het a b | a -> b where
het :: m (f c) -> a -> m b
class GHet (a :: * -> *) (b :: * -> *) | a -> b
instance GHet (K a) (K [a])
instance Het a b => GHet (K a) (K b)
The two instances don't actually conflict on their fundeps,
although it's pretty strange. So they are both accepted. Now
try [W] GHet (K Int) (K Bool)
This triggers fundeps from both instance decls;
[D] K Bool ~ K [a]
[D] K Bool ~ K beta
And there's a risk of complaining about Bool ~ [a]. But in fact
the Wanted matches the second instance, so we never get as far
as the fundeps.
Trac #7875 is a case in point.
Note [Overriding implicit parameters]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
f :: (?x::a) -> Bool -> a
g v = let ?x::Int = 3
in (f v, let ?x::Bool = True in f v)
This should probably be well typed, with
g :: Bool -> (Int, Bool)
So the inner binding for ?x::Bool *overrides* the outer one.
Hence a work-item Given overrides an inert-item Given.
-}
-- | Indicates if Instance met the Safe Haskell overlapping instances safety
-- check.
--
-- See Note [Safe Haskell Overlapping Instances] in TcSimplify
-- See Note [Safe Haskell Overlapping Instances Implementation] in TcSimplify
type SafeOverlapping = Bool
data LookupInstResult
= NoInstance
| GenInst [TcPredType] ([EvId] -> EvTerm) SafeOverlapping
instance Outputable LookupInstResult where
ppr NoInstance = text "NoInstance"
ppr (GenInst ev _ s) = text "GenInst" <+> ppr ev <+> ss
where ss = text $ if s then "[safe]" else "[unsafe]"
matchClassInst, match_class_inst
:: DynFlags -> InertSet -> Class -> [Type] -> CtLoc -> TcS LookupInstResult
matchClassInst dflags inerts clas tys loc
= do { traceTcS "matchClassInst" $ vcat [ text "pred =" <+> ppr (mkClassPred clas tys) ]
; res <- match_class_inst dflags inerts clas tys loc
; traceTcS "matchClassInst result" $ ppr res
; return res }
-- First check whether there is an in-scope Given that could
-- match this constraint. In that case, do not use top-level
-- instances. See Note [Instance and Given overlap]
match_class_inst dflags inerts clas tys loc
| not (xopt Opt_IncoherentInstances dflags)
, let matchable_givens = matchableGivens loc pred inerts
, not (isEmptyBag matchable_givens)
= do { traceTcS "Delaying instance application" $
vcat [ text "Work item=" <+> pprType pred
, text "Potential matching givens:" <+> ppr matchable_givens ]
; return NoInstance }
where
pred = mkClassPred clas tys
match_class_inst _ _ clas [ ty ] _
| className clas == knownNatClassName
, Just n <- isNumLitTy ty = makeDict (EvNum n)
| className clas == knownSymbolClassName
, Just s <- isStrLitTy ty = makeDict (EvStr s)
where
{- This adds a coercion that will convert the literal into a dictionary
of the appropriate type. See Note [KnownNat & KnownSymbol and EvLit]
in TcEvidence. The coercion happens in 2 steps:
Integer -> SNat n -- representation of literal to singleton
SNat n -> KnownNat n -- singleton to dictionary
The process is mirrored for Symbols:
String -> SSymbol n
SSymbol n -> KnownSymbol n
-}
makeDict evLit
| Just (_, co_dict) <- tcInstNewTyCon_maybe (classTyCon clas) [ty]
-- co_dict :: KnownNat n ~ SNat n
, [ meth ] <- classMethods clas
, Just tcRep <- tyConAppTyCon_maybe -- SNat
$ funResultTy -- SNat n
$ dropForAlls -- KnownNat n => SNat n
$ idType meth -- forall n. KnownNat n => SNat n
, Just (_, co_rep) <- tcInstNewTyCon_maybe tcRep [ty]
-- SNat n ~ Integer
, let ev_tm = mkEvCast (EvLit evLit) (mkTcSymCo (mkTcTransCo co_dict co_rep))
= return $ GenInst [] (\_ -> ev_tm) True
| otherwise
= panicTcS (text "Unexpected evidence for" <+> ppr (className clas)
$$ vcat (map (ppr . idType) (classMethods clas)))
match_class_inst _ _ clas ts _
| isCTupleClass clas
, let data_con = tyConSingleDataCon (classTyCon clas)
tuple_ev = EvDFunApp (dataConWrapId data_con) ts
= return (GenInst ts tuple_ev True)
-- The dfun is the data constructor!
match_class_inst _ _ clas [k,t] _
| className clas == typeableClassName
= matchTypeableClass clas k t
match_class_inst dflags _ clas tys loc
= do { instEnvs <- getInstEnvs
; let safeOverlapCheck = safeHaskell dflags `elem` [Sf_Safe, Sf_Trustworthy]
(matches, unify, unsafeOverlaps) = lookupInstEnv True instEnvs clas tys
safeHaskFail = safeOverlapCheck && not (null unsafeOverlaps)
; case (matches, unify, safeHaskFail) of
-- Nothing matches
([], _, _)
-> do { traceTcS "matchClass not matching" $
vcat [ text "dict" <+> ppr pred ]
; return NoInstance }
-- A single match (& no safe haskell failure)
([(ispec, inst_tys)], [], False)
-> do { let dfun_id = instanceDFunId ispec
; traceTcS "matchClass success" $
vcat [text "dict" <+> ppr pred,
text "witness" <+> ppr dfun_id
<+> ppr (idType dfun_id) ]
-- Record that this dfun is needed
; match_one (null unsafeOverlaps) dfun_id inst_tys }
-- More than one matches (or Safe Haskell fail!). Defer any
-- reactions of a multitude until we learn more about the reagent
(matches, _, _)
-> do { traceTcS "matchClass multiple matches, deferring choice" $
vcat [text "dict" <+> ppr pred,
text "matches" <+> ppr matches]
; return NoInstance } }
where
pred = mkClassPred clas tys
match_one :: SafeOverlapping -> DFunId -> [DFunInstType] -> TcS LookupInstResult
-- See Note [DFunInstType: instantiating types] in InstEnv
match_one so dfun_id mb_inst_tys
= do { checkWellStagedDFun pred dfun_id loc
; (tys, theta) <- instDFunType dfun_id mb_inst_tys
; return $ GenInst theta (EvDFunApp dfun_id tys) so }
{- Note [Instance and Given overlap]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Example, from the OutsideIn(X) paper:
instance P x => Q [x]
instance (x ~ y) => R y [x]
wob :: forall a b. (Q [b], R b a) => a -> Int
g :: forall a. Q [a] => [a] -> Int
g x = wob x
This will generate the impliation constraint:
Q [a] => (Q [beta], R beta [a])
If we react (Q [beta]) with its top-level axiom, we end up with a
(P beta), which we have no way of discharging. On the other hand,
if we react R beta [a] with the top-level we get (beta ~ a), which
is solvable and can help us rewrite (Q [beta]) to (Q [a]) which is
now solvable by the given Q [a].
The solution is that:
In matchClassInst (and thus in topReact), we return a matching
instance only when there is no Given in the inerts which is
unifiable to this particular dictionary.
We treat any meta-tyvar as "unifiable" for this purpose,
*including* untouchable ones
The end effect is that, much as we do for overlapping instances, we
delay choosing a class instance if there is a possibility of another
instance OR a given to match our constraint later on. This fixes
Trac #4981 and #5002.
Other notes:
* The check is done *first*, so that it also covers classes
with built-in instance solving, such as
- constraint tuples
- natural numbers
- Typeable
* The given-overlap problem is arguably not easy to appear in practice
due to our aggressive prioritization of equality solving over other
constraints, but it is possible. I've added a test case in
typecheck/should-compile/GivenOverlapping.hs
* Another "live" example is Trac #10195; another is #10177.
* We ignore the overlap problem if -XIncoherentInstances is in force:
see Trac #6002 for a worked-out example where this makes a
difference.
* Moreover notice that our goals here are different than the goals of
the top-level overlapping checks. There we are interested in
validating the following principle:
If we inline a function f at a site where the same global
instance environment is available as the instance environment at
the definition site of f then we should get the same behaviour.
But for the Given Overlap check our goal is just related to completeness of
constraint solving.
-}
-- | Is the constraint for an implicit CallStack parameter?
-- i.e. (IP "name" CallStack)
isCallStackIP :: CtLoc -> Class -> [Type] -> Maybe (EvTerm -> EvCallStack)
isCallStackIP loc cls tys
| cls == ipClass
, [_ip_name, ty] <- tys
, Just (tc, _) <- splitTyConApp_maybe ty
, tc `hasKey` callStackTyConKey
= occOrigin (ctLocOrigin loc)
| otherwise
= Nothing
where
locSpan = ctLocSpan loc
-- We only want to grab constraints that arose due to the use of an IP or a
-- function call. See Note [Overview of implicit CallStacks]
occOrigin (OccurrenceOf n) = Just (EvCsPushCall n locSpan)
occOrigin (IPOccOrigin n) = Just (EvCsTop ('?' `consFS` hsIPNameFS n) locSpan)
occOrigin _ = Nothing
-- | Assumes that we've checked that this is the 'Typeable' class,
-- and it was applied to the correct argument.
matchTypeableClass :: Class -> Kind -> Type -> TcS LookupInstResult
matchTypeableClass clas k t
-- See Note [No Typeable for qualified types]
| isForAllTy t = return NoInstance
-- Is the type of the form `C => t`?
| isJust (tcSplitPredFunTy_maybe t) = return NoInstance
| eqType k typeNatKind = doTyLit knownNatClassName
| eqType k typeSymbolKind = doTyLit knownSymbolClassName
| Just (tc, ks) <- splitTyConApp_maybe t
, all isKind ks = doTyCon tc ks
| Just (f,kt) <- splitAppTy_maybe t = doTyApp f kt
| otherwise = return NoInstance
where
-- Representation for type constructor applied to some kinds
doTyCon tc ks =
case mapM kindRep ks of
Nothing -> return NoInstance
Just kReps ->
return $ GenInst [] (\_ -> EvTypeable (EvTypeableTyCon tc kReps) ) True
{- Representation for an application of a type to a type-or-kind.
This may happen when the type expression starts with a type variable.
Example (ignoring kind parameter):
Typeable (f Int Char) -->
(Typeable (f Int), Typeable Char) -->
(Typeable f, Typeable Int, Typeable Char) --> (after some simp. steps)
Typeable f
-}
doTyApp f tk
| isKind tk
= return NoInstance -- We can't solve until we know the ctr.
| otherwise
= return $ GenInst [mk_typeable_pred f, mk_typeable_pred tk]
(\[t1,t2] -> EvTypeable $ EvTypeableTyApp (EvId t1,f) (EvId t2,tk))
True
-- Representation for concrete kinds. We just use the kind itself,
-- but first check to make sure that it is "simple" (i.e., made entirely
-- out of kind constructors).
kindRep ki = do (_,ks) <- splitTyConApp_maybe ki
mapM_ kindRep ks
return ki
-- Emit a `Typeable` constraint for the given type.
mk_typeable_pred ty = mkClassPred clas [ typeKind ty, ty ]
-- Given KnownNat / KnownSymbol, generate appropriate sub-goal
-- and make evidence for a type-level literal.
doTyLit c = do clas <- tcLookupClass c
let p = mkClassPred clas [ t ]
return $ GenInst [p] (\[i] -> EvTypeable
$ EvTypeableTyLit (EvId i,t)) True
{- Note [No Typeable for polytype or for constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We do not support impredicative typeable, such as
Typeable (forall a. a->a)
Typeable (Eq a => a -> a)
Typeable (() => Int)
Typeable (((),()) => Int)
See Trac #9858. For forall's the case is clear: we simply don't have
a TypeRep for them. For qualified but not polymorphic types, like
(Eq a => a -> a), things are murkier. But:
* We don't need a TypeRep for these things. TypeReps are for
monotypes only.
* Perhaps we could treat `=>` as another type constructor for `Typeable`
purposes, and thus support things like `Eq Int => Int`, however,
at the current state of affairs this would be an odd exception as
no other class works with impredicative types.
For now we leave it off, until we have a better story for impredicativity.
-}
|
ml9951/ghc
|
compiler/typecheck/TcInteract.hs
|
Haskell
|
bsd-3-clause
| 83,885
|
{-# OPTIONS_GHC -Wall -fno-warn-unused-do-bind #-}
module Parse.Type where
import Control.Applicative ((<$>),(<*>),(<*))
import Data.List (intercalate)
import Text.Parsec ((<|>), (<?>), char, many, optionMaybe, string, try)
import qualified AST.Type as T
import qualified AST.Variable as Var
import Parse.Helpers
tvar :: IParser T.RawType
tvar =
T.Var <$> lowVar <?> "type variable"
tuple :: IParser T.RawType
tuple =
do ts <- parens (commaSep expr)
case ts of
[t] -> return t
_ -> return (T.tupleOf ts)
record :: IParser T.RawType
record =
do char '{'
whitespace
rcrd <- extended <|> normal
dumbWhitespace
char '}'
return rcrd
where
normal = flip T.Record Nothing <$> commaSep field
-- extended record types require at least one field
extended = do
ext <- try (lowVar <* (whitespace >> string "|"))
whitespace
flip T.Record (Just (T.Var ext)) <$> commaSep1 field
field = do
lbl <- rLabel
whitespace >> hasType >> whitespace
(,) lbl <$> expr
capTypeVar :: IParser String
capTypeVar =
intercalate "." <$> dotSep1 capVar
constructor0 :: IParser T.RawType
constructor0 =
do name <- capTypeVar
return (T.Type (Var.Raw name))
term :: IParser T.RawType
term =
tuple <|> record <|> tvar <|> constructor0
app :: IParser T.RawType
app =
do f <- constructor0 <|> try tupleCtor <?> "type constructor"
args <- spacePrefix term
case args of
[] -> return f
_ -> return (T.App f args)
where
tupleCtor = do
n <- length <$> parens (many (char ','))
let ctor = "_Tuple" ++ show (if n == 0 then 0 else n+1)
return (T.Type (Var.Raw ctor))
expr :: IParser T.RawType
expr =
do t1 <- app <|> term
arr <- optionMaybe $ try (whitespace >> arrow)
case arr of
Just _ -> T.Lambda t1 <$> (whitespace >> expr)
Nothing -> return t1
constructor :: IParser (String, [T.RawType])
constructor =
(,) <$> (capTypeVar <?> "another type constructor")
<*> spacePrefix term
|
avh4/elm-compiler
|
src/Parse/Type.hs
|
Haskell
|
bsd-3-clause
| 2,080
|
module KeepCafs2 where
import KeepCafsBase
foreign export ccall "getX"
getX :: IO Int
getX :: IO Int
getX = return (x + 1)
|
sdiehl/ghc
|
testsuite/tests/rts/KeepCafs2.hs
|
Haskell
|
bsd-3-clause
| 128
|
{-# LANGUAGE ForeignFunctionInterface #-}
{-@ LIQUID "--c-files=../ffi-include/foo.c" @-}
{-@ LIQUID "-i../ffi-include" @-}
module Main where
import Foreign.C.Types
{-@ embed CInt as int @-}
{-@ embed Integer as int @-}
{-@ assume c_foo :: x:{CInt | x > 0} -> IO {v:CInt | v = x} @-}
foreign import ccall unsafe "foo.c foo" c_foo
:: CInt -> IO CInt
main :: IO ()
main = print . fromIntegral =<< c_foo 1
|
mightymoose/liquidhaskell
|
tests/pos/FFI.hs
|
Haskell
|
bsd-3-clause
| 409
|
{-# LANGUAGE DataKinds, PolyKinds #-}
module T14209 where
data MyProxy k (a :: k) = MyProxy
data Foo (z :: MyProxy k (a :: k))
|
sdiehl/ghc
|
testsuite/tests/polykinds/T14209.hs
|
Haskell
|
bsd-3-clause
| 128
|
{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
{-# LANGUAGE RankNTypes #-}
module ShouldSucceed where
data Empty q = Empty (forall a. Ord a => q a)
q :: (Ord a) => [a]
q = []
e0, e1, e2 :: Empty []
e0 = Empty []
e1 = Empty ([] :: (Ord a) => [a])
e2 = Empty q
|
olsner/ghc
|
testsuite/tests/typecheck/should_compile/tc092.hs
|
Haskell
|
bsd-3-clause
| 458
|
-----------------------------------------------------------------------------
-- |
-- Module : GHC.ExecutionStack
-- Copyright : (c) The University of Glasgow 2013-2015
-- License : see libraries/base/LICENSE
--
-- Maintainer : cvs-ghc@haskell.org
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- This is a module for efficient stack traces. This stack trace implementation
-- is considered low overhead. Basic usage looks like this:
--
-- @
-- import GHC.ExecutionStack
--
-- myFunction :: IO ()
-- myFunction = do
-- putStrLn =<< showStackTrace
-- @
--
-- Your GHC must have been built with @libdw@ support for this to work.
--
-- @
-- user@host:~$ ghc --info | grep libdw
-- ,("RTS expects libdw","YES")
-- @
--
-- @since 4.9.0.0
-----------------------------------------------------------------------------
module GHC.ExecutionStack (
Location (..)
, SrcLoc (..)
, getStackTrace
, showStackTrace
) where
import Control.Monad (join)
import GHC.ExecutionStack.Internal
-- | Get a trace of the current execution stack state.
--
-- Returns @Nothing@ if stack trace support isn't available on host machine.
getStackTrace :: IO (Maybe [Location])
getStackTrace = (join . fmap stackFrames) `fmap` collectStackTrace
-- | Get a string representation of the current execution stack state.
showStackTrace :: IO (Maybe String)
showStackTrace = fmap (\st -> showStackFrames st "") `fmap` getStackTrace
|
tolysz/prepare-ghcjs
|
spec-lts8/base/GHC/ExecutionStack.hs
|
Haskell
|
bsd-3-clause
| 1,463
|
{-# LANGUAGE TypeFamilies #-}
module T11408 where
type family UL a
type family UR a
type family MT a b
mkMerge :: a -> UL a -> UR a -> Int
mkMerge = undefined
merger :: a -> b -> MT a b
merger = undefined
{-
merge ::
forall a b. (UL (MT a b) ~ a, UR (MT a b) ~ b) => a -> b -> Int
or
forall t. (MT (UL t) (UR t) ~ t) => UL t -> UR t -> Int
These types are equivalent, and in fact neither is ambiguous,
but the solver has to work quite hard to prove that.
-}
merge x y = mkMerge (merger x y) x y
|
ezyang/ghc
|
testsuite/tests/indexed-types/should_compile/T11408.hs
|
Haskell
|
bsd-3-clause
| 502
|
module T7312 where
-- this works
mac :: Double -> (Double->Double) -> (Double-> Double)
mac ac m = \ x -> ac + x * m x
-- this doesn't
mac2 :: Double -> (->) Double Double -> (->) Double Double
mac2 ac m = \ x -> ac + x * m x
|
wxwxwwxxx/ghc
|
testsuite/tests/typecheck/should_compile/T7312.hs
|
Haskell
|
bsd-3-clause
| 228
|
module Main where
import GHC.Conc
-- Create a new TVar, update it and check that it contains the expected value after the
-- transaction
main = do
putStr "Before\n"
t <- atomically ( newTVar 42 )
atomically ( writeTVar t 17 )
r <- atomically ( readTVar t )
putStr ("After " ++ (show r) ++ "\n")
|
wxwxwwxxx/ghc
|
testsuite/tests/concurrent/should_run/conc043.hs
|
Haskell
|
bsd-3-clause
| 318
|
{-# LANGUAGE CPP, MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module System.Process.Text.Lazy where
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative ((<$>))
#endif
import Control.DeepSeq (force)
import qualified Control.Exception as C (evaluate)
import Data.ListLike.IO (hGetContents)
import Data.Text.Lazy (Text, fromStrict, toChunks)
import Prelude hiding (null)
import System.Process
import System.Process.Common
import System.Exit (ExitCode)
instance ProcessText Text Char
-- | Like 'System.Process.readProcessWithExitCode', but using 'Text'
instance ListLikeProcessIO Text Char where
forceOutput = C.evaluate . force
readChunks h = (map fromStrict . toChunks) <$> hGetContents h
-- | Specialized version for backwards compatibility.
readProcessWithExitCode
:: FilePath -- ^ command to run
-> [String] -- ^ any arguments
-> Text -- ^ standard input
-> IO (ExitCode, Text, Text) -- ^ exitcode, stdout, stderr
readProcessWithExitCode = System.Process.Common.readProcessWithExitCode
readCreateProcessWithExitCode
:: CreateProcess -- ^ command and arguments to run
-> Text -- ^ standard input
-> IO (ExitCode, Text, Text) -- ^ exitcode, stdout, stderr
readCreateProcessWithExitCode = System.Process.Common.readCreateProcessWithExitCode
|
seereason/process-extras
|
src/System/Process/Text/Lazy.hs
|
Haskell
|
mit
| 1,392
|
module Exercises where
tensDigit :: Integral a => a -> a
tensDigit x = d
where
(xLast, _) = x `divMod` 10
d = xLast `mod` 10
foldBool :: a -> a -> Bool -> a
foldBool x y z =
case z of
True -> x
False -> y
foldBool2 :: a -> a -> Bool -> a
foldBool2 x y z
| z == True = x
| otherwise = y
g :: (a -> b) -> (a, c) -> (b, c)
g aTob (a, c) = (aTob a, c)
|
andrewMacmurray/haskell-book-solutions
|
src/ch7/exercises.hs
|
Haskell
|
mit
| 388
|
{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}
module Main where
import System.Random.TF.Init
import Types
import Encode
import Mix
import Melody.GameOfThrones
import Generator.Sin
import Generator.Rand
import Generator.KarplusStrong
import Envelope.ADSR
settings :: MixSettings
settings = MixSettings
{ mixGenerator = generatorKarplusStrong
, mixTempo = 0.35
, mixLoudness = 0.1
, mixEnvelope = envelopeADSR 0.01 0.2 0.7 2.5
}
main = do
g <- initTFGen
encodeAndWrite "test.pcm" . mix settings g $ gameOfThrones
|
feuerbach/music
|
Main.hs
|
Haskell
|
mit
| 556
|
scoreToLetter :: Int -> Char
scoreToLetter n
| n > 90 = 'A'
| n > 80 = 'B'
| n > 70 = 'C'
| otherwise = 'F'
len [] = 0
len (x:s) = 1 + len s
listCopy [] = []
listCopy (x:s) = x : listCopy s
ones = 1 : ones
twos = 2 : twos
lists = [ones, twos]
front :: Int -> [a] -> [a]
front _ [] = []
front 0 (x:s) = []
front n (x:s) = x : front (n-1) s
tB :: [String] -> [Int] -> [(String, Int)]
tB [] _ = []
tB (f:fs) (b:bs) = (f,b) : tB fs bs
timeBonuses finishers =
tB finishers ([20, 12, 8] ++ cycle[0])
zipOp :: (a -> b -> c) -> [a] -> [b] -> [c]
zipOp f [] _ = []
zipOp f _ [] = []
zipOp f (a:as) (b:bs) = (f a b) : zipOp f as bs
myZip = zipOp (\ a b -> (a,b))
seed = [1, 1]
ouput = zipOp (+) seed (tail seed)
fibs = 1 : 1 : zipOp (+) fibs (tail fibs)
type Identifier = String
type Value = Int
type Env = [(Identifier, Value)]
data WAE = Num Int
| Add WAE WAE
| Id Identifier
| With Identifier WAE WAE
mlookup :: Identifier -> Env -> Value
mlookup var ((i,v):r)
| (var == i) = v
| otherwise = mlookup var r
extend :: Env -> Identifier -> Value -> Env
extend env i v = (i,v):env
--interp :: WAE -> Env -> Value
interp (Num n) env = n
interp (Add lhs rhs) env = interp lhs env + interp rhs env
interp (Id i) env = mlookup i env
interp (With bound_id named_expr bound_body) env =
interp bound_body
(extend env bound_id (interp named_expr env))
|
hectoregm/lenguajes
|
class-notes/class-notes-30-september.hs
|
Haskell
|
mit
| 1,452
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Gaia.SearchEngine (
runQuery2,
runQuery3
) where
import qualified Data.ByteString.Lazy.Char8 as Char8
import qualified Data.List as D
import qualified Gaia.AesonValuesFileSystemCorrespondance as XP1
import qualified Gaia.AesonValuesAionPointAbstractionsCorrespondance as XP2
import qualified Gaia.Directives as GD
import qualified Gaia.FSRootsManagement as FSM
import qualified Gaia.GeneralUtils as GU
import qualified Gaia.ScanningAndRecordingManager as SRM
import Gaia.Types
import qualified PStorageServices.ContentAddressableStore as CAS
import qualified System.FilePath as FS
import System.IO.Unsafe (unsafePerformIO)
-- -----------------------------------------------------------
-- Utils
-- -----------------------------------------------------------
isInfixOfCaseIndependent2 :: String -> String -> Bool
isInfixOfCaseIndependent2 pattern name = D.isInfixOf (GU.stringToLower pattern) (GU.stringToLower name)
shouldRetainThisLocationPathAsDirectoryGivenTheseGaiaDirectives :: LocationPath -> [GD.GaiaFileDirective] -> String -> Bool
shouldRetainThisLocationPathAsDirectoryGivenTheseGaiaDirectives _ parsedirectives pattern =
any (\directive ->
case directive of
GaiaFileDirective GaiaFileTag body -> isInfixOfCaseIndependent2 pattern body
) parsedirectives
casKeyToAionName :: String -> IO (Maybe String)
casKeyToAionName key = do
aionPointAsByteString <- CAS.get key
case aionPointAsByteString of
Nothing -> return Nothing
Just aionPointAsByteString' -> do
let aesonValue = XP1.convertJSONStringIntoAesonValue (Char8.unpack aionPointAsByteString')
case aesonValue of
Nothing -> return Nothing
Just aesonValue' -> do
let x1 = XP2.extendedAesonValueToExtendedAionPointAbstractionGeneric (ExtendedAesonValue aesonValue' key)
return $ Just (extractNameFromAionExtendedPointAbstractionGeneric x1)
where
extractNameFromAionExtendedPointAbstractionGeneric (ExtendedAionPointAbstractionGeneric (AionPointAbstractionGenericFromFile (AionPointAbstractionFile filename _ _)) _) = filename
extractNameFromAionExtendedPointAbstractionGeneric (ExtendedAionPointAbstractionGeneric (AionPointAbstractionGenericFromDirectory (AionPointAbstractionDirectory foldername _)) _) = foldername
-- -----------------------------------------------------------
-- Aion Points Recursive Analysis
-- -----------------------------------------------------------
{-
Each Aion point is a location of the File System
Therefore each Aeson Value is a location of the file system
In the below <current path> is the full FS path to the object (which is not known by the object itself and must be computed recursively from some root)
-}
{-
extractLocationPathsForAesonValueFileAndPatternAndLocationPath :: A.Value -> String -> LocationPath -> IO [ LocationPath ]
extractLocationPathsForAesonValueFileAndPatternAndLocationPath aesonValueFile pattern locationpath =
do
let tap = XP2.extendedAesonValueToExtendedAionPointAbstractionGeneric aesonValueFile
if name1 tap =="gaia"
then do
-- parseDirectivesFile :: FilePath -> MaybeT IO [Directive]
directives <- GD.parseDirectivesFile locationpath
if shouldRetainThisLocationPathAsDirectoryGivenTheseGaiaDirectives locationpath directives pattern
then
return [ FS.takeDirectory locationpath ]
else
return []
else
if isInfixOfCaseIndependent2 pattern (name1 tap)
then
return [ locationpath ]
else
return []
-}
extractLocationPathsForAionPointAbstractionFileAndPatternAndLocationPath :: AionPointAbstractionFile -> String -> LocationPath -> String -> IO [SEAtom]
extractLocationPathsForAionPointAbstractionFileAndPatternAndLocationPath (AionPointAbstractionFile filename _ _) pattern locationpath caskey = do
if isInfixOfCaseIndependent2 pattern filename
then
return [ SEAtom locationpath caskey ]
else
return []
extractLocationPathsForAionPointAbstractionDirectoryAndPatternAndLocationPath :: AionPointAbstractionDirectory -> String -> LocationPath -> String -> IO [SEAtom]
extractLocationPathsForAionPointAbstractionDirectoryAndPatternAndLocationPath (AionPointAbstractionDirectory foldername caskeys) pattern locationpath caskey = do
let x1 = map (\xcaskey -> do
maybename <- casKeyToAionName xcaskey
case maybename of
Nothing -> return []
-- extractSEAtomForAionCASKeyAndPatternAndLocationPath :: String -> String -> LocationPath -> IO [LocationPath]
-- extractSEAtomForAionCASKeyAndPatternAndLocationPath <aion cas hash> <search pattern> <current path>
Just name -> extractSEAtomForAionCASKeyAndPatternAndLocationPath xcaskey pattern (FS.normalise $ FS.joinPath [locationpath, name])
) caskeys
-- x1 :: [IO [SEAtom]]
let x2 = sequence x1
-- x2 :: IO [[SEAtom]]
let x3 = fmap concat x2
-- x3 :: IO [SEAtom]
if isInfixOfCaseIndependent2 pattern foldername
then do
x4 <- x3
return $ (SEAtom locationpath caskey) : x4
else
x3
extractLocationPathsForAionPointAbstractionGenericAndPatternAndLocationPath2 :: ExtendedAionPointAbstractionGeneric -> String -> LocationPath -> IO [SEAtom]
extractLocationPathsForAionPointAbstractionGenericAndPatternAndLocationPath2 (ExtendedAionPointAbstractionGeneric (AionPointAbstractionGenericFromFile taionpointfile) caskey) pattern locationpath = extractLocationPathsForAionPointAbstractionFileAndPatternAndLocationPath taionpointfile pattern locationpath caskey
extractLocationPathsForAionPointAbstractionGenericAndPatternAndLocationPath2 (ExtendedAionPointAbstractionGeneric (AionPointAbstractionGenericFromDirectory taionpointdirectory) caskey) pattern locationpath = extractLocationPathsForAionPointAbstractionDirectoryAndPatternAndLocationPath taionpointdirectory pattern locationpath caskey
extractSEAtomForAionCASKeyAndPatternAndLocationPath :: String -> String -> LocationPath -> IO [SEAtom]
extractSEAtomForAionCASKeyAndPatternAndLocationPath aion_cas_hash pattern locationpath = do
aionJSONValueAsString <- XP1.getAionJSONStringForCASKey3 aion_cas_hash
case aionJSONValueAsString of
Nothing -> return []
Just aionJSONValueAsString' -> do
let aionJSONValue = XP1.convertJSONStringIntoAesonValue aionJSONValueAsString'
case aionJSONValue of
Nothing -> return []
Just aionJSONValue' -> extractLocationPathsForAionPointAbstractionGenericAndPatternAndLocationPath2 (XP2.extendedAesonValueToExtendedAionPointAbstractionGeneric (ExtendedAesonValue aionJSONValue' aion_cas_hash)) pattern locationpath
-- -----------------------------------------------------------
-- Running queries against Merkle Roots
-- -----------------------------------------------------------
{-
The Merkle root refers to a particular aion snapshot of the file system.
The fsroot is used to recursively construct paths.
Paths returned by the process are essentially the fsroot and recursively locationnames constructed by looking up the aion points.
This is due to the fact that the Merkle root doesn't know which node of the file system (fsroot) it represents.
The pattern is the search query.
-}
runQueryAgainMerkleRootUsingStoredData :: LocationPath -> String -> String -> IO [SEAtom]
runQueryAgainMerkleRootUsingStoredData fsroot merkleroot pattern =
extractSEAtomForAionCASKeyAndPatternAndLocationPath merkleroot pattern fsroot
-- -----------------------------------------------------------
-- Search Engine Interface
-- -----------------------------------------------------------
runQuery1 :: String -> IO [SEAtom]
runQuery1 pattern = do
-- getFSScanRoots :: IO [String]
scanroots <- FSM.getFSScanRoots
let x = map (\scanroot -> do
merkleroot <- SRM.getCurrentMerkleRootForFSScanRoot scanroot
case merkleroot of
Nothing -> return []
Just merkleroot' -> runQueryAgainMerkleRootUsingStoredData scanroot merkleroot' pattern
) scanroots
-- x :: [IO [SEAtom]]
fmap concat ( sequence x )
runQuery2 :: String -> [SEAtom]
runQuery2 pattern = unsafePerformIO $ runQuery1 pattern
runQuery3 :: String -> [SEAtom]
runQuery3 pattern = unsafePerformIO $ runQuery1 pattern
|
shtukas/Gaia
|
src/Gaia/SearchEngine.hs
|
Haskell
|
mit
| 9,015
|
main = putStrLn "Hello World"
//added some comments
//showing how to do stuff
|
Yelmogus/Lambda_Interpreter
|
HW1.hs
|
Haskell
|
mit
| 78
|
{- Copyright (C) 2015 Calvin Beck
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 Text.MathForm.Readers.Sage where
import Text.MathForm.MathTypes
import Text.MathForm.Readers.SageTokens
import Text.Parsec
import Text.Parsec.Expr
import Text.Parsec.Text
import Control.Monad
import Control.Monad.Identity
import qualified Data.Text as T
parseSage :: Parser MathForm
parseSage = buildExpressionParser table term
term :: Parser MathForm
term = parens parseSage
<|> fmap (either IntLit FloatLit) naturalOrFloat
<|> liftM Symbol identifier
-- | https://hackage.haskell.org/package/parsec-3.1.9/docs/Text-Parsec-Expr.html
-- is pretty much exactly what we need here.
table :: OperatorTable T.Text st Identity MathForm
table = [ [binary "**" Pow AssocLeft, binary "^" Pow AssocLeft]
, [prefix "-" Neg, prefix "+" Pos]
, [binary "*" Mult AssocLeft, binary "/" Div AssocLeft]
, [binary "+" Plus AssocLeft, binary "-" Sub AssocLeft]
]
binary name fun = Infix (do { reservedOp name; return fun })
prefix name fun = Prefix (do { reservedOp name; return fun })
postfix name fun = Postfix (do { reservedOp name; return fun })
|
Chobbes/mathform
|
src/Text/MathForm/Readers/Sage.hs
|
Haskell
|
mit
| 2,207
|
module HaskellBook.Case where
funcZ x =
case x + 1 == 1 of
True -> "AWESOME"
False -> "wut"
pal xs =
case xs == reverse xs of
True -> "yes"
False -> "no"
pal' xs =
case y of
True -> "yes"
False -> "no"
where y = xs == reverse xs
|
brodyberg/Notes
|
ProjectRosalind.hsproj/LearnHaskell/lib/HaskellBook/Case.hs
|
Haskell
|
mit
| 278
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.