code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE DoAndIfThenElse #-}
{- |
Copyright : Galois, Inc. 2012-2015
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : non-portable (language extensions)
-}
module Main where
import Test.Tasty
import Test.Tasty.Options
import Test.Tasty.Ingredients
import Test.Tasty.Runners.AntXML
import Test.Tasty.QuickCheck
import Data.Proxy
import System.Exit
import Tests.Parser
import Tests.SharedTerm
import Tests.Rewriter
main :: IO ()
main = defaultMainWithIngredients ingrs tests
ingrs :: [Ingredient]
ingrs =
[ antXMLRunner
-- explicitly including this option keeps the test suite from failing due
-- to passing the '--quickcheck-tests' option on the command line
, includingOptions [ Option (Proxy :: Proxy QuickCheckTests) ]
]
++
defaultIngredients
tests :: TestTree
tests =
testGroup "SAWCore"
[ testGroup "SharedTerm" sharedTermTests
, testGroup "Parser" parserTests
, testGroup "Rewriter" rewriter_tests
]
| iblumenfeld/saw-core | tests/src/Tests.hs | bsd-3-clause | 1,000 | 0 | 11 | 172 | 163 | 95 | 68 | 26 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE MonadComprehensions #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RebindableSyntax #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ViewPatterns #-}
module Queries.AQuery.Trades
( bestProfit
, last10
) where
import Data.List.NonEmpty (NonEmpty ((:|)))
import qualified Data.List.NonEmpty as N
import Database.DSH
import qualified Prelude as P
import Schema.AQuery
--------------------------------------------------------------------------------
-- For a given date and stock, compute the best profit obtained by
-- buying the stock and selling it later.
mins :: (QA a, TA a, Ord a) => Q [a] -> Q [a]
mins xs = [ minimum [ y | (view -> (y, j)) <- number xs, j <= i ]
| (view -> (x, i)) <- number xs
]
margins :: (Ord a, Num (Q a), QA a, TA a) => Q [a] -> Q [a]
margins xs = [ x - y | (view -> (x,y)) <- zip xs (mins xs) ]
-- our profit is the maximum margin obtainable
profit :: (Ord a, Num a, Num (Q a), QA a, TA a) => Q [a] -> Q a
profit xs = maximum (margins xs)
-- best profit obtainable for stock on given date
bestProfit :: Integer -> Integer -> Q Double
bestProfit stock date =
profit [ t_priceQ t
| t <- sortWith t_timestampQ trades
, t_tidQ t == toQ stock
, t_tradeDateQ t == toQ date
]
--------------------------------------------------------------------------------
-- Compute the ten last stocks for each quote in a portfolio.
lastn :: QA a => Integer -> Q [a] -> Q [a]
lastn n xs = drop (length xs - toQ n) xs
last10 :: Integer -> Q [(Integer, [Double])]
last10 portfolioId =
map (\(view -> (tid, g)) -> pair tid (map snd $ lastn 10 g))
$ groupWithKey fst
[ pair (t_tidQ t) (t_priceQ t)
| t <- trades
, p <- portfolios
, t_tidQ t == po_tidQ p
, po_pidQ p == toQ portfolioId
]
| ulricha/dsh-aquery | Queries/AQuery/Trades.hs | bsd-3-clause | 2,132 | 0 | 12 | 560 | 650 | 348 | 302 | 43 | 1 |
{-|
This module provides a data structure for directed graphs
with weighted edges.
-}
module WeightedGraph
(
WeightedGraph(..),
LabelledGraph(..),
weight
) where
import Prelude hiding (foldr, lookup)
import Data.Map hiding (foldr)
import Data.Foldable
import GraphUtils
-- | Graph with labels associated to edges.
data LabelledGraph a = LGraph {
graph :: Graph,
labels :: Map (Vertex, Vertex) a
}
type WeightedGraph = LabelledGraph Float
instance Foldable LabelledGraph where
foldr f initial (LGraph _ labels) =
foldr f initial labels
instance Functor LabelledGraph where
fmap f (LGraph graph labels) =
LGraph graph $ fmap f labels
weight :: WeightedGraph -> (Vertex, Vertex) -> Maybe Float
weight (LGraph _ labels) (s,d) =
lookup (s,d) labels
| alexisVallet/ag44-graph-algorithms | WeightedGraph.hs | bsd-3-clause | 815 | 0 | 10 | 184 | 228 | 129 | 99 | 22 | 1 |
-- !!! Testing top level printer (note that this doesn't necessarily test show)
-- Test things of type String
test1, test2, test3 :: String
test1 = "abcd"
test2 = ""
test3 = "abcd\0efgh\0"
test4 = "abc" ++ error "def" ++ "hij"
test5 = "abc" ++ [error "def"] ++ "hij"
test6 = 'a' : 'b' : 'c' : error "foo"
test7 = 'a' : 'b' : 'c' : error "foo" : []
test8 = show (error "foo"::String)
test11, test12 :: String
test11 = case (error "foo") of _ -> "abcd"
test12 = case (error "foo") of [] -> "abcd"
test13, test14 :: String
test13 = error (error "foo")
test14 = error test14
-- Test things of type IO ()
{- can't include this in backwards compatability tests
-- Normal
test101, test102, test103 :: IO ()
test101 = putStr "abcd"
test102 = return ()
test103 = putChar 'a'
-- Errors
test111, test112, test113, test114 :: IO ()
test111 = error "foo"
test112 = putStr (error "foo")
test113 = putStr "abcd" >> putStr (error "foo") >> putStr "efgh"
test114 = putStr "abcd" >> error "foo" >> putStr "efgh"
test123, test124, test125 :: IO ()
test123 = error (error "foo")
test124 = error x where x = error x
test125 = error x where x = 'a' : error x
-}
-- Test things of type a
-- Unit
test241, test242 :: ()
test241 = ()
test242 = error "foo"
-- Ints
test251, test252 :: Int
test251 = 10
test252 = -10
test253, test254 :: Int
test253 = 42 + error "foo"
test254 = error "foo" + 42
-- Integers
test261, test262 :: Integer
test261 = 10
test262 = 10
-- Floats
test271, test272 :: Float
test271 = 10
test272 = -10
-- Doubles
test281, test282 :: Double
test281 = 10
test282 = -10
-- Char
test291, test292, test293 :: Char
test291 = 'a'
test292 = '\0'
test293 = '\DEL'
-- Lists
test301, test302 :: [Int]
test301 = []
test302 = [1]
-- Bool
test311 = True
test312 = False
-- Tuples
test321 = ('a','b')
test322 = ('a','b','c')
test323 :: (Int,Int, Int)
test323 = (1, error "foo", 3)
-- Datatypes
data E a b = L a | R b
test331 = R (1::Int)
test332 = L 'a'
data M a = N | J a
test333 = J True
test334 = N
-- No dialogue tests in this file
| FranklinChen/Hugs | tests/rts/print.hs | bsd-3-clause | 2,056 | 0 | 8 | 436 | 527 | 314 | 213 | 52 | 1 |
module Tests.Common
( assertFa
, assert2Fa
) where
import Test.Hspec
import Types.Fa (Fa, State, Symbol)
import Parsing.General (loadFa)
assertFa :: FilePath -> (Fa Symbol State -> Bool) -> Expectation
assertFa filePath condition =
loadFa ("tests/Examples/" ++ filePath) >>= \fa ->
case fa of
Left parseError -> expectationFailure parseError
Right fa -> fa `shouldSatisfy` condition
assert2Fa :: FilePath -> FilePath -> (Fa Symbol State -> Fa Symbol State -> Bool) -> Expectation
assert2Fa filePath1 filePath2 condition =
do
firstFa <- loadFa ("tests/Examples/" ++ filePath1)
secondFa <- loadFa ("tests/Examples/" ++ filePath2)
case firstFa of
Left parseError -> expectationFailure parseError
Right fa1 -> case secondFa of
Left parseError -> expectationFailure parseError
Right fa2 -> fa2 `shouldSatisfy` condition fa1
| jakubriha/automata | tests/Tests/Common.hs | bsd-3-clause | 916 | 0 | 14 | 212 | 276 | 140 | 136 | 22 | 3 |
{-# LANGUAGE ForeignFunctionInterface #-}
-- | Provides a thin wrapper for the FFI bindings to libexpect contained in
-- System.Expect.ExpectBindings.
module System.Expect.ExpectInterface
({-- The contents of the binding that are to be further exposed --}
ExpectType(ExpExact,ExpRegex,ExpGlob,ExpNull)
{-- The custom interface --}
,ExpectCase(ExpectCase,expectPattern,expectType,expectValue)
,ExpectProc(ExpectProc,expectHandle,expectFilePtr)
,muteExpect,unmuteExpect
,spawnExpect
,expectCases,expectSingle,expectExact,expectRegex,expectMultiple
,sendLine)
where
import System.Expect.ExpectBindings as EB
import Foreign
import Foreign.C.String
import Foreign.C.Types
import GHC.IO.Handle.FD
import System.IO
foreign import ccall "stdio.h fileno" fileno :: Ptr CFile -> IO CInt
-- * Types
-- | Denotes how a case's pattern is treated.
data ExpectType = ExpExact -- ^ Match against pattern exactly.
| ExpRegex -- ^ Compile the pattern string to a regex and match.
| ExpGlob -- ^ Pattern string is glob style.
| ExpNull
-- | Defines a case to match against.
data ExpectCase = ExpectCase { -- | Pattern to match against.
expectPattern ::String
-- | Type of pattern contained in the case.
, expectType :: ExpectType
-- | The value to return if the case is matched.
, expectValue :: Int
}
-- | Proc created by spawnExpect. Contains both the
-- CFile pointer and a Haskell handle, so the
-- translation needs only be done once.
data ExpectProc = ExpectProc { -- | Gets the pointer to the expect process file handle.
expectFilePtr :: Ptr CFile
-- | Gets a Handle to the expect process.
, expectHandle :: Handle }
-- | Child process does not echo output to stdout.
muteExpect :: IO ()
muteExpect = poke exp_loguser 0
-- | Child process echoes output to stdout.
unmuteExpect :: IO ()
unmuteExpect = poke exp_loguser 1
-- | Spawn a new expect process, running a specified program.
spawnExpect :: String -- ^ The command to be processed. eg. "adduser bob"
-> IO ExpectProc -- ^ Expect process.
spawnExpect cmd = do
cstr <- newCString cmd
cfileptr <- EB.exp_popen cstr
cfileno <- fileno cfileptr
handle <- fdToHandle $ fromIntegral cfileno
return $ ExpectProc cfileptr handle
expectCases :: ExpectProc -- ^ The process to expect on.
-> [ExpectCase] -- ^ The cases to match against.
-> IO (Maybe Int) -- ^ Nothing if there are no matches (timeout / EOF), the value field
-- of the case that matched.
-- Expect one of a list of cases
expectCases proc cases = do
scases <- mapM toStorableCase cases
sarray <- newArray (scases ++ [endStorableCase])
cval <- EB.exp_fexpectv (expectFilePtr proc) sarray
nlist <- peekArray (length scases + 1) sarray
mapM_ freeStorableCase nlist
if cval < 0 then return Nothing
else return $ Just $ fromEnum cval
-- | Expect a single case with a given type.
expectSingle :: ExpectProc -- ^ The process to expect on.
-> String -- ^ The pattern.
-> ExpectType -- ^ The type of the pattern.
-> IO (Maybe Int) -- ^ See expectCases.
expectSingle proc str ec = expectCases proc [ExpectCase str ec 1]
-- | Expect a single case with a type of ExpExact.
expectExact :: ExpectProc -- ^ The process to expect on.
-> String -- ^ The pattern.
-> IO (Maybe Int) -- ^ See expectCases.
expectExact proc exact = expectSingle proc exact ExpExact
-- | Expect a single case with a type of ExpExact.
expectRegex :: ExpectProc -- ^ The process to expect on.
-> String -- ^ The pattern.
-> IO (Maybe Int) -- ^ See expectCases.
expectRegex proc reg = expectSingle proc reg ExpRegex
-- | Expect multiple cases of a given type.
expectMultiple :: ExpectProc -- ^ The process to expect on.
-> [String] -- ^ The patterns.
-> ExpectType -- ^ The type of the pattern.
-> IO (Maybe Int) -- ^ See expectCases.
expectMultiple proc ss ec = expectCases proc cases
where cases = map (\(x,y) -> ExpectCase x ec y) (zip ss [1..])
-- | Send a line of input to the process.
sendLine :: ExpectProc -- ^ The process.
-> String -- ^ The line to send, without the '\n'
-> IO ()
sendLine proc line = hPutStrLn (expectHandle proc) line
{-------------------------
--- Private functions ---
-------------------------}
toStorableCase :: ExpectCase
-> IO ExpCase
toStorableCase cs = do
cstr <- newCString $ expectPattern cs
cval <- (return . toEnum . expectValue) cs
return $ ExpCase cstr nullPtr (expectTypeToExpType $ expectType cs) cval
endStorableCase :: ExpCase
endStorableCase = ExpCase nullPtr nullPtr expEnd 0
freeStorableCase :: ExpCase
-> IO ()
freeStorableCase cs = do
if (regexp cs) == nullPtr then free (regexp cs)
else return ()
expectTypeToExpType :: ExpectType -> ExpType
expectTypeToExpType ExpRegex = expRegexp
expectTypeToExpType ExpExact = expExact
expectTypeToExpType ExpGlob = expGlob
expectTypeToExpType ExpNull = expNull
| stroan/haskell-libexpect | System/Expect/ExpectInterface.hs | bsd-3-clause | 5,353 | 4 | 11 | 1,402 | 974 | 534 | 440 | 99 | 2 |
-- |
-- Module : $Header$
-- Copyright : (c) 2013-2015 Galois, Inc.
-- License : BSD3
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternGuards #-}
module Cryptol.Parser.LexerUtils where
import Cryptol.Parser.Position
import Cryptol.Parser.Unlit(PreProc(None))
import Cryptol.Utils.PP
import Cryptol.Utils.Panic
import Data.Char(toLower,generalCategory,isAscii,ord,isSpace)
import qualified Data.Char as Char
import Data.List(foldl')
import Data.Text.Lazy (Text)
import qualified Data.Text.Lazy as T
import Data.Word(Word8)
data Config = Config
{ cfgSource :: !FilePath -- ^ File that we are working on
, cfgLayout :: !Layout -- ^ Settings for layout processing
, cfgPreProc :: PreProc -- ^ Preprocessor settings
, cfgAutoInclude :: [FilePath] -- ^ Implicit includes
, cfgModuleScope :: Bool -- ^ When we do layout processing
-- should we add a vCurly (i.e., are
-- we parsing a list of things).
}
defaultConfig :: Config
defaultConfig = Config
{ cfgSource = ""
, cfgLayout = Layout
, cfgPreProc = None
, cfgAutoInclude = []
, cfgModuleScope = True
}
type Action = Config -> Position -> Text -> LexS
-> (Maybe (Located Token), LexS)
data LexS = Normal
| InComment Bool Position ![Position] [Text]
| InString Position Text
| InChar Position Text
startComment :: Bool -> Action
startComment isDoc _ p txt s = (Nothing, InComment d p stack chunks)
where (d,stack,chunks) = case s of
Normal -> (isDoc, [], [txt])
InComment doc q qs cs -> (doc, q : qs, txt : cs)
_ -> panic "[Lexer] startComment" ["in a string"]
endComent :: Action
endComent cfg p txt s =
case s of
InComment d f [] cs -> (Just (mkToken d f cs), Normal)
InComment d _ (q:qs) cs -> (Nothing, InComment d q qs (txt : cs))
_ -> panic "[Lexer] endComment" ["outside comment"]
where
mkToken isDoc f cs =
let r = Range { from = f, to = moves p txt, source = cfgSource cfg }
str = T.concat $ reverse $ txt : cs
tok = if isDoc then DocStr else BlockComment
in Located { srcRange = r, thing = Token (White tok) str }
addToComment :: Action
addToComment _ _ txt s = (Nothing, InComment doc p stack (txt : chunks))
where
(doc, p, stack, chunks) =
case s of
InComment d q qs cs -> (d,q,qs,cs)
_ -> panic "[Lexer] addToComment" ["outside comment"]
startEndComment :: Action
startEndComment cfg p txt s =
case s of
Normal -> (Just tok, Normal)
where tok = Located
{ srcRange = Range { from = p
, to = moves p txt
, source = cfgSource cfg
}
, thing = Token (White BlockComment) txt
}
InComment d p1 ps cs -> (Nothing, InComment d p1 ps (txt : cs))
_ -> panic "[Lexer] startEndComment" ["in string or char?"]
startString :: Action
startString _ p txt _ = (Nothing,InString p txt)
endString :: Action
endString cfg pe txt s = case s of
InString ps str -> (Just (mkToken ps str), Normal)
_ -> panic "[Lexer] endString" ["outside string"]
where
parseStr s1 = case reads s1 of
[(cs, "")] -> StrLit cs
_ -> Err InvalidString
mkToken ps str = Located { srcRange = Range
{ from = ps
, to = moves pe txt
, source = cfgSource cfg
}
, thing = Token
{ tokenType = parseStr (T.unpack tokStr)
, tokenText = tokStr
}
}
where
tokStr = str `T.append` txt
addToString :: Action
addToString _ _ txt s = case s of
InString p str -> (Nothing,InString p (str `T.append` txt))
_ -> panic "[Lexer] addToString" ["outside string"]
startChar :: Action
startChar _ p txt _ = (Nothing,InChar p txt)
endChar :: Action
endChar cfg pe txt s =
case s of
InChar ps str -> (Just (mkToken ps str), Normal)
_ -> panic "[Lexer] endString" ["outside character"]
where
parseChar s1 = case reads s1 of
[(cs, "")] -> ChrLit cs
_ -> Err InvalidChar
mkToken ps str = Located { srcRange = Range
{ from = ps
, to = moves pe txt
, source = cfgSource cfg
}
, thing = Token
{ tokenType = parseChar (T.unpack tokStr)
, tokenText = tokStr
}
}
where
tokStr = str `T.append` txt
addToChar :: Action
addToChar _ _ txt s = case s of
InChar p str -> (Nothing,InChar p (str `T.append` txt))
_ -> panic "[Lexer] addToChar" ["outside character"]
mkIdent :: Action
mkIdent cfg p s z = (Just Located { srcRange = r, thing = Token t s }, z)
where
r = Range { from = p, to = moves p s, source = cfgSource cfg }
t = Ident [] (T.unpack s)
mkQualIdent :: Action
mkQualIdent cfg p s z = (Just Located { srcRange = r, thing = Token t s}, z)
where
r = Range { from = p, to = moves p s, source = cfgSource cfg }
t = Ident (map T.unpack ns) (T.unpack i)
(ns,i) = splitQual s
mkQualOp :: Action
mkQualOp cfg p s z = (Just Located { srcRange = r, thing = Token t s}, z)
where
r = Range { from = p, to = moves p s, source = cfgSource cfg }
t = Op (Other (map T.unpack ns) (T.unpack i))
(ns,i) = splitQual s
emit :: TokenT -> Action
emit t cfg p s z = (Just Located { srcRange = r, thing = Token t s }, z)
where r = Range { from = p, to = moves p s, source = cfgSource cfg }
emitS :: (String -> TokenT) -> Action
emitS t cfg p s z = emit (t (T.unpack s)) cfg p s z
-- | Split out the prefix and name part of an identifier/operator.
splitQual :: T.Text -> ([T.Text], T.Text)
splitQual t =
case splitNS (T.filter (not . isSpace) t) of
[] -> panic "[Lexer] mkQualIdent" ["invalid qualified name", show t]
[i] -> ([], i)
xs -> (init xs, last xs)
where
-- split on the namespace separator, `::`
splitNS s =
case T.breakOn "::" s of
(l,r) | T.null r -> [l]
| otherwise -> l : splitNS (T.drop 2 r)
--------------------------------------------------------------------------------
numToken :: Integer -> String -> TokenT
numToken rad ds = Num (toVal ds) (fromInteger rad) (length ds)
where
toVal = foldl' (\x c -> rad * x + toDig c) 0
toDig = if rad == 16 then fromHexDigit else fromDecDigit
fromDecDigit :: Char -> Integer
fromDecDigit x = read [x]
fromHexDigit :: Char -> Integer
fromHexDigit x'
| 'a' <= x && x <= 'f' = fromIntegral (10 + fromEnum x - fromEnum 'a')
| otherwise = fromDecDigit x
where x = toLower x'
-------------------------------------------------------------------------------
data AlexInput = Inp { alexPos :: !Position
, alexInputPrevChar :: !Char
, input :: !Text
} deriving Show
alexGetByte :: AlexInput -> Maybe (Word8, AlexInput)
alexGetByte i =
do (c,rest) <- T.uncons (input i)
let i' = i { alexPos = move (alexPos i) c, input = rest }
b = byteForChar c
return (b,i')
data Layout = Layout | NoLayout
--------------------------------------------------------------------------------
-- | Drop white-space tokens from the input.
dropWhite :: [Located Token] -> [Located Token]
dropWhite = filter (notWhite . tokenType . thing)
where notWhite (White w) = w == DocStr
notWhite _ = True
data Block = Virtual Int -- ^ Virtual layout block
| Explicit TokenT -- ^ An explicit layout block, expecting this ending
-- token.
deriving (Show)
isExplicit :: Block -> Bool
isExplicit Explicit{} = True
isExplicit Virtual{} = False
startsLayout :: TokenT -> Bool
startsLayout (KW KW_where) = True
startsLayout (KW KW_private) = True
startsLayout _ = False
-- Add separators computed from layout
layout :: Config -> [Located Token] -> [Located Token]
layout cfg ts0 = loop False implicitScope [] ts0
where
(_pos0,implicitScope) = case ts0 of
t : _ -> (from (srcRange t), cfgModuleScope cfg && tokenType (thing t) /= KW KW_module)
_ -> (start,False)
loop :: Bool -> Bool -> [Block] -> [Located Token] -> [Located Token]
loop afterDoc startBlock stack (t : ts)
| startsLayout ty = toks ++ loop False True stack' ts
| Sym ParenL <- ty = toks ++ loop False False (Explicit (Sym ParenR) : stack') ts
| Sym CurlyL <- ty = toks ++ loop False False (Explicit (Sym CurlyR) : stack') ts
| Sym BracketL <- ty = toks ++ loop False False (Explicit (Sym BracketR) : stack') ts
| EOF <- ty = toks
| White DocStr <- ty = toks ++ loop True False stack' ts
| otherwise = toks ++ loop False False stack' ts
where
ty = tokenType (thing t)
pos = srcRange t
(toks,offStack)
| afterDoc = ([t], stack)
| otherwise = offsides startToks t stack
-- add any block start tokens, and push a level on the stack
(startToks,stack')
| startBlock && ty == EOF = ( [ virt cfg (to pos) VCurlyR
, virt cfg (to pos) VCurlyL ]
, offStack )
| startBlock = ( [ virt cfg (to pos) VCurlyL ], Virtual (col (from pos)) : offStack )
| otherwise = ( [], offStack )
loop _ _ _ [] = panic "[Lexer] layout" ["Missing EOF token"]
offsides :: [Located Token] -> Located Token -> [Block] -> ([Located Token], [Block])
offsides startToks t = go startToks
where
go virts stack = case stack of
-- delimit or close a layout block
Virtual c : rest
-- commas only close to an explicit marker, so if there is none, the
-- comma doesn't close anything
| Sym Comma == ty ->
if any isExplicit rest
then go (virt cfg (to pos) VCurlyR : virts) rest
else done virts stack
| closingToken -> go (virt cfg (to pos) VCurlyR : virts) rest
| col (from pos) == c -> done (virt cfg (to pos) VSemi : virts) stack
| col (from pos) < c -> go (virt cfg (to pos) VCurlyR : virts) rest
-- close an explicit block
Explicit close : rest | close == ty -> done virts rest
| Sym Comma == ty -> done virts stack
_ -> done virts stack
ty = tokenType (thing t)
pos = srcRange t
done ts s = (reverse (t:ts), s)
closingToken = ty `elem` [ Sym ParenR, Sym BracketR, Sym CurlyR ]
virt :: Config -> Position -> TokenV -> Located Token
virt cfg pos x = Located { srcRange = Range
{ from = pos
, to = pos
, source = cfgSource cfg
}
, thing = t }
where t = Token (Virt x) $ case x of
VCurlyL -> "beginning of layout block"
VCurlyR -> "end of layout block"
VSemi -> "layout block separator"
--------------------------------------------------------------------------------
data Token = Token { tokenType :: TokenT, tokenText :: Text }
deriving Show
-- | Virtual tokens, inserted by layout processing.
data TokenV = VCurlyL| VCurlyR | VSemi
deriving (Eq,Show)
data TokenW = BlockComment | LineComment | Space | DocStr
deriving (Eq,Show)
data TokenKW = KW_Arith
| KW_Bit
| KW_Cmp
| KW_else
| KW_Eq
| KW_extern
| KW_fin
| KW_if
| KW_private
| KW_include
| KW_inf
| KW_lg2
| KW_lengthFromThen
| KW_lengthFromThenTo
| KW_max
| KW_min
| KW_module
| KW_newtype
| KW_pragma
| KW_property
| KW_then
| KW_type
| KW_where
| KW_let
| KW_x
| KW_import
| KW_as
| KW_hiding
| KW_infixl
| KW_infixr
| KW_infix
| KW_primitive
deriving (Eq,Show)
-- | The named operators are a special case for parsing types, and 'Other' is
-- used for all other cases that lexed as an operator.
data TokenOp = Plus | Minus | Mul | Div | Exp | Mod
| Equal | LEQ | GEQ
| Complement | Hash
| Other [String] String
deriving (Eq,Show)
data TokenSym = Bar
| ArrL | ArrR | FatArrR
| Lambda
| EqDef
| Comma
| Semi
| Dot
| DotDot
| DotDotDot
| Colon
| BackTick
| ParenL | ParenR
| BracketL | BracketR
| CurlyL | CurlyR
| TriL | TriR
| Underscore
deriving (Eq,Show)
data TokenErr = UnterminatedComment
| UnterminatedString
| UnterminatedChar
| InvalidString
| InvalidChar
| LexicalError
deriving (Eq,Show)
data TokenT = Num Integer Int Int -- ^ value, base, number of digits
| ChrLit Char -- ^ character literal
| Ident [String] String -- ^ (qualified) identifier
| StrLit String -- ^ string literal
| KW TokenKW -- ^ keyword
| Op TokenOp -- ^ operator
| Sym TokenSym -- ^ symbol
| Virt TokenV -- ^ virtual token (for layout)
| White TokenW -- ^ white space token
| Err TokenErr -- ^ error token
| EOF
deriving (Eq,Show)
instance PP Token where
ppPrec _ (Token _ s) = text (T.unpack s)
-- | Collapse characters into a single Word8, identifying ASCII, and classes of
-- unicode. This came from:
--
-- https://github.com/glguy/config-value/blob/master/src/Config/LexerUtils.hs
--
-- Which adapted:
--
-- https://github.com/ghc/ghc/blob/master/compiler/parser/Lexer.x
byteForChar :: Char -> Word8
byteForChar c
| c <= '\6' = non_graphic
| isAscii c = fromIntegral (ord c)
| otherwise = case generalCategory c of
Char.LowercaseLetter -> lower
Char.OtherLetter -> lower
Char.UppercaseLetter -> upper
Char.TitlecaseLetter -> upper
Char.DecimalNumber -> digit
Char.OtherNumber -> digit
Char.ConnectorPunctuation -> symbol
Char.DashPunctuation -> symbol
Char.OtherPunctuation -> symbol
Char.MathSymbol -> symbol
Char.CurrencySymbol -> symbol
Char.ModifierSymbol -> symbol
Char.OtherSymbol -> symbol
Char.Space -> sp
Char.ModifierLetter -> other
Char.NonSpacingMark -> other
Char.SpacingCombiningMark -> other
Char.EnclosingMark -> other
Char.LetterNumber -> other
Char.OpenPunctuation -> other
Char.ClosePunctuation -> other
Char.InitialQuote -> other
Char.FinalQuote -> tick
_ -> non_graphic
where
non_graphic = 0
upper = 1
lower = 2
digit = 3
symbol = 4
sp = 5
other = 6
tick = 7
| ntc2/cryptol | src/Cryptol/Parser/LexerUtils.hs | bsd-3-clause | 17,054 | 0 | 19 | 6,800 | 4,649 | 2,506 | 2,143 | 359 | 24 |
module XWiiMote where
import XWiiMote.FFI
| sw17ch/hsxwiimote | XWiiMote.hs | bsd-3-clause | 43 | 0 | 4 | 6 | 9 | 6 | 3 | 2 | 0 |
{-# LANGUAGE RecordWildCards,ViewPatterns #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
module Math.Statistics.WCC_NEW(wcc,WCCParams(..)) where
import Math.Statistics(pearson)
import Math.Statistics.WCC.Types
import DebugUtils(dimension)
--import Data.List(genericLength)
--pearson x = (+(-1)) . (*2) . (o/genericLength x) . genericLength . filter (==True) . (zipWith (==) x)
wcc :: Floating a => WCCParams -> [a] -> [a] -> [[a]]
wcc (WCCParams {..}) xs ys = reverse $ wcc' (lagSplit $ reverse xs) (lagSplit $ reverse ys)
where wcc' [] _ = []
wcc' _ [] = []
wcc' (xs {- :nextxs -}) (ys {-:nextys-}) | length xsSplit < lagSteps+1 || length ysSplit < lagSteps+1 = []
| otherwise = lag : wcc' (next xs) (next ys)
where lag = wccZipper xsSplit ysSplit
--lag = (negLag ++ [zeroLag] ++ posLag)
negLag = reverse $ pearsonMap ys (tail xsSplit)
posLag = map (pearson (take windowSize xs)) (take lagSteps $ tail ysSplit)
zeroLag = pearson (take windowSize xs) (take windowSize ys)
pearsonMap xs ys = map (pearson (take windowSize xs))
(take lagSteps ys)
wccSplit =take (lagSteps+1) . splitDrop windowSize lagIncrement
next = drop windowIncrement
xsSplit = wccSplit xs
ysSplit = wccSplit ys
lagSize = windowSize+lagSteps*lagIncrement
lagSplit = id -- splitDrop lagSize windowIncrement
wccZipper :: Floating a => [[a]] -> [[a]] -> [a]
wccZipper [] _ = []
wccZipper _ [] = []
wccZipper (x:xs) (y:ys) = map (pearson x) (reverse ys) ++ (pearson x y : map (pearson y) xs)
wccMapper :: WCCParams -> [a] -> [[[a]]]
wccMapper (WCCParams {..}) = map (takeRows . splitDropInf windowSize lagIncrement)
. splitDrop lagSize windowIncrement
where lagSize = windowSize+lagSteps*lagIncrement
takeRows = take (lagSteps+1)
splitDrop :: Int -> Int -> [a] -> [[a]]
splitDrop n = takeWhile ((==n) . length) .: splitDropInf n
splitDropInf :: Int -> Int -> [a] -> [[a]]
splitDropInf n k l = take n l : splitDropInf n k (drop k l)
(.:) :: (c -> d) -> (a -> b -> c) -> a -> b -> d
(.:) = (.).(.)
infixr 8 .:
| runebak/wcc | Source/Math/Statistics/WCC_NEW.hs | bsd-3-clause | 2,296 | 1 | 15 | 643 | 851 | 452 | 399 | 40 | 3 |
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
module Finance.Exchange.Simulation
( SimulationEvent
, Event (..)
, SimulationError (..)
-- , fromFile
, candleToQuotes
) where
import Control.Monad
import Control.Monad.Base
import Data.Attoparsec.ByteString.Char8
import Data.ByteString as BS
import Finance.Exchange.Types
import Pipes
import Pipes.Control
-- | Type of simulation event depending on market
type family SimulationEvent market :: *
-- | Simulation event
data Event market = Event (Timestamp market) (SimulationEvent market) -- time should be ordered
| EndSimulation
-- it's likely I will use pipes for simulation. Pipes do not support end of stream detection natively.
-- I will need to use extensions (pipes for parser) or introduce special event to indicate end of simulation
-- the other alternative is to use conduids where end of event stream could be detected.
-- К вопросу об EndOfStream vs Event.
-- Если сообщение об окончании симуляции несет в себе какую-то полезную информацию, то его надо посылать яыно в виде сообщения симуляции,
-- а не иметь какой-то скрытый обработчик окончания симуляции. Другое дело, что возможно никакой полезной информации оно не несет, а результаты
-- симуляции должны быть доступны online. Тогда нам это сообщение вообще не надо посылать но нам важно какая часть трубы возвращает результат.
-- Можно попробовать сделать выходным значением трубы - промежуточный результат симуляции, а возвращаемым - информацию о причинах завершения
-- трубы. В Рipes все трубы должны иметь один тип возвращаемого значение, собственно он и определяет что с чем композится.
-- нужен инкрементальный парсинг для HR
deriving instance (Show (Timestamp market), Show (SimulationEvent market)) => Show (Event market)
deriving instance (Eq (Timestamp market), Eq (SimulationEvent market)) => Eq (Event market)
-- | Simulation source is basically producer of simulation events
--type SimulationSource market = Producer (Event market) (MarketMonad market)
-- | Parsing error
--data ParseError = ParseError ByteString [String] String
-- | Simulation errors
data SimulationError = SimulationDataError String
{-
-- | Create simulation source from file
fromFile :: ( MonadBase IO (MarketMonad market)
, MonadError ParseError (MarketMonad market) -- this will not work because m -> e
, MonadError SimulationError (MarketMonad market)
, Ord (Timestamp market)
, Show (Timestamp market) )
=> Parser (Event market)
-> FilePath
-> (SimulationSource market r)
fromFile parser filePath = do
byteString <- liftBase $ BS.readFile filePath
(event@(Event timeStamp _), remains) <- readEvent (parse parser) byteString
yield event
go timeStamp remains
where
readEvent p byteString = case p byteString of
Fail remains context msg -> throwError $ ParseError remains context msg
Partial p' -> readEvent p' BS.empty
Done remains event -> return $ (event, remains)
go prevStamp byteString = do
(event@(Event timeStamp _), remains) <- readEvent (parse parser) byteString
when (timeStamp > prevStamp) $ throwError $ SimulationDataError $ "Wrong timestamp order: " ++ (show timeStamp) ++ " is lager than " ++ (show prevStamp)
yield event
go timeStamp remains
-}
-- | Convert candles to quotes
-- Most markets provide historical data in form of candles (open, maximal, minimal and close prices)
-- This function allow to convert it to quotes needed for historical simulations.
candleToQuotes :: ( Ord (Money market)
, Fractional (Amount market)
, Fractional (Timestamp market)
) => Candle market -> [Quote market]
candleToQuotes (Candle instrumentId begin end open high low close amount) =
let quarterAmount = (amount / (fromInteger 4))
quarterPeriod = (end - begin) / (fromInteger 4)
quote t p = Quote instrumentId t quarterAmount p
(a, b) = if (open >= close) then (high, low)
else (low, high)
in [ quote begin open, quote (begin + quarterPeriod) a, quote (begin + (quarterPeriod * (fromInteger 2))) b, quote end close] | schernichkin/exchange | src/Finance/Exchange/Simulation.hs | bsd-3-clause | 5,251 | 0 | 14 | 1,135 | 473 | 275 | 198 | 36 | 2 |
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE DataKinds #-}
module Esquilo.Types.Keywords where
import GHC.TypeLits
-- http://www.postgresql.org/docs/9.0/static/sql-select.html
-- [ WITH [ RECURSIVE ] with_query [, ...] ]
-- SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ]
-- * | expression [ [ AS ] output_name ] [, ...]
-- [ FROM from_item [, ...] ]
-- [ WHERE condition ]
-- [ GROUP BY expression [, ...] ]
-- [ HAVING condition [, ...] ]
-- [ WINDOW window_name AS ( window_definition ) [, ...] ]
-- [ { UNION | INTERSECT | EXCEPT } [ ALL ] select ]
-- [ ORDER BY expression [ ASC | DESC | USING operator ] [ NULLS { FIRST | LAST } ] [, ...] ]
-- [ LIMIT { count | ALL } ]
-- [ OFFSET start [ ROW | ROWS ] ]
-- [ FETCH { FIRST | NEXT } [ count ] { ROW | ROWS } ONLY ]
-- [ FOR { UPDATE | SHARE } [ OF table_name [, ...] ] [ NOWAIT ] [...] ]
data SELECT (a :: k) from (tbl :: Symbol)
data FROM
data WHERE
data (:=)
| jkarni/esquilo | src/Esquilo/Types/Keywords.hs | bsd-3-clause | 970 | 0 | 5 | 249 | 58 | 46 | 12 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Main ( main ) where
import Control.Concurrent
import Control.Lens hiding ((*~))
import Control.Monad
import ETCS.DMI
import ETCS.DMI.StartupSequence
import ETCS.DMI.Types
import ETCS.DMI.Widgets.SpeedDial
import GHCJS.DOM (enableInspector,
runWebGUI,
webViewGetDomDocument)
import GHCJS.DOM.Document (getElementById)
import Numeric.Units.Dimensional.TF.Prelude
import Prelude ()
import Reactive.Banana
import Reactive.Banana.Frameworks
kmh :: (Fractional a) => Unit DVelocity a
kmh = kilo meter / hour
trainb :: TrainBehavior
trainb = TrainBehavior {
_trainVelocity = pure (162 *~ kmh),
_trainMode = pure FS,
_trainNonLeadingInput = pure False,
_trainLevel = pure (_UnknownData # ()),
_trainDriverID = pure (_UnknownData # ()),
_trainData = pure (_UnknownData # ()),
_trainRunningNumber = pure (_UnknownData # ()),
_trainEmergencyBreakActive = pure False,
_trainServiceBreakActive = pure False,
_trainIsNonLeading = pure False,
_trainModDriverIDAllowed = pure True,
_trainRadioSafeConnection = pure NoConnection,
_trainCommunicationSessionPending = pure False,
_trainPassiveShuntingInput = pure False,
_trainSpeedDial = pure SpeedDial400,
_trainSDMData = sdmd
}
sdmd :: SDMData
sdmd = SDMData {
_sdmVperm = pure $ 160 *~ kmh,
_sdmVrelease = pure $ Nothing,
_sdmVtarget = pure $ 80 *~ kmh,
_sdmVwarn = pure $ 165 *~ kmh,
_sdmVsbi = pure $ 170 *~ kmh,
_sdmVindication = pure $ 85 *~ kmh,
_sdmStatus = pure TSM
}
main :: IO ()
main = runWebGUI $ \ webView -> do
enableInspector webView
Just doc <- webViewGetDomDocument webView
Just dmiMain <- getElementById doc ("dmiMain" :: String)
network <- compile $ do
sd <- mkWidget dmiMain $ mkSpeedDial trainb
windowMain <- mkWidget dmiMain $ mkStartupSequence trainb
-- let (eClose, eValue) = split . widgetEvent . fromWidgetInstance $ windowMain
-- _ <- execute $ fmap (const $ removeWidget windowMain) eClose
-- reactimate $ fmap print eValue
{-
ovw <- mkOverrideWindow dmiMain (pure False)
spw <- mkSpecialWindow dmiMain (pure False)
sew <- mkSettingsWindow dmiMain (pure False)
rcw <- mkRBCContactWindow dmiMain (pure False)
-}
return ()
actuate network
print ("startup done" :: String)
forever $ do
threadDelay 10000000
| open-etcs/openetcs-dmi | app/main.hs | bsd-3-clause | 2,749 | 0 | 15 | 846 | 589 | 325 | 264 | 59 | 1 |
module Pos.Core.Common.CoinPortion
( CoinPortion (..)
, coinPortionDenominator
, checkCoinPortion
, unsafeCoinPortionFromDouble
, coinPortionToDouble
, applyCoinPortionDown
, applyCoinPortionUp
) where
import Universum
import Control.Monad.Except (MonadError (throwError))
import qualified Data.Aeson as Aeson (FromJSON (..), ToJSON (..))
import Data.SafeCopy (base, deriveSafeCopySimple)
import Formatting (bprint, float, int, sformat, (%))
import qualified Formatting.Buildable as Buildable
import Text.JSON.Canonical (FromJSON (..), ReportSchemaErrors,
ToJSON (..))
import Pos.Binary.Class (Bi, decode, encode)
import Pos.Core.Common.Coin
import Pos.Util.Json.Canonical ()
-- | CoinPortion is some portion of Coin; it is interpreted as a fraction
-- with denominator of 'coinPortionDenominator'. The numerator must be in the
-- interval of [0, coinPortionDenominator].
--
-- Usually 'CoinPortion' is used to determine some threshold expressed as
-- portion of total stake.
--
-- To multiply a coin portion by 'Coin', use 'applyCoinPortionDown' (when
-- calculating number of coins) or 'applyCoinPortionUp' (when calculating a
-- threshold).
newtype CoinPortion = CoinPortion
{ getCoinPortion :: Word64
} deriving (Show, Ord, Eq, Generic, Typeable, NFData, Hashable)
instance Bi CoinPortion where
encode = encode . getCoinPortion
decode = CoinPortion <$> decode
instance Monad m => ToJSON m CoinPortion where
toJSON = toJSON @_ @Word64 . getCoinPortion -- i. e. String
instance ReportSchemaErrors m => FromJSON m CoinPortion where
fromJSON val = do
number <- fromJSON val
pure $ CoinPortion number
instance Aeson.FromJSON CoinPortion where
parseJSON v = unsafeCoinPortionFromDouble <$> Aeson.parseJSON v
instance Aeson.ToJSON CoinPortion where
toJSON = Aeson.toJSON . coinPortionToDouble
-- | Denominator used by 'CoinPortion'.
coinPortionDenominator :: Word64
coinPortionDenominator = (10 :: Word64) ^ (15 :: Word64)
instance Bounded CoinPortion where
minBound = CoinPortion 0
maxBound = CoinPortion coinPortionDenominator
-- | Make 'CoinPortion' from 'Word64' checking whether it is not greater
-- than 'coinPortionDenominator'.
checkCoinPortion
:: MonadError Text m
=> CoinPortion -> m ()
checkCoinPortion (CoinPortion x)
| x <= coinPortionDenominator = pure ()
| otherwise = throwError err
where
err =
sformat
("CoinPortion: value is greater than coinPortionDenominator: "
%int) x
-- | Make CoinPortion from Double. Caller must ensure that value is in
-- [0..1]. Internally 'CoinPortion' stores 'Word64' which is divided by
-- 'coinPortionDenominator' to get actual value. So some rounding may take
-- place.
unsafeCoinPortionFromDouble :: Double -> CoinPortion
unsafeCoinPortionFromDouble x
| 0 <= x && x <= 1 = CoinPortion v
| otherwise = error "unsafeCoinPortionFromDouble: double not in [0, 1]"
where
v = round $ realToFrac coinPortionDenominator * x
{-# INLINE unsafeCoinPortionFromDouble #-}
instance Buildable CoinPortion where
build cp@(getCoinPortion -> x) =
bprint
(int%"/"%int%" (approx. "%float%")")
x
coinPortionDenominator
(coinPortionToDouble cp)
coinPortionToDouble :: CoinPortion -> Double
coinPortionToDouble (getCoinPortion -> x) =
realToFrac @_ @Double x / realToFrac coinPortionDenominator
{-# INLINE coinPortionToDouble #-}
-- | Apply CoinPortion to Coin (with rounding down).
--
-- Use it for calculating coin amounts.
applyCoinPortionDown :: CoinPortion -> Coin -> Coin
applyCoinPortionDown (getCoinPortion -> p) (unsafeGetCoin -> c) =
Coin . fromInteger $
(toInteger p * toInteger c) `div`
(toInteger coinPortionDenominator)
-- | Apply CoinPortion to Coin (with rounding up).
--
-- Use it for calculating thresholds.
applyCoinPortionUp :: CoinPortion -> Coin -> Coin
applyCoinPortionUp (getCoinPortion -> p) (unsafeGetCoin -> c) =
let (d, m) = divMod (toInteger p * toInteger c)
(toInteger coinPortionDenominator)
in if m > 0 then Coin (fromInteger (d + 1))
else Coin (fromInteger d)
deriveSafeCopySimple 0 'base ''CoinPortion
| input-output-hk/pos-haskell-prototype | core/src/Pos/Core/Common/CoinPortion.hs | mit | 4,390 | 0 | 12 | 964 | 909 | 503 | 406 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE DeriveDataTypeable #-}
-- | HTTP over SSL/TLS support for Warp via the TLS package.
module Network.Wai.Handler.WarpTLS (
-- * Settings
TLSSettings
, certFile
, keyFile
, onInsecure
, tlsLogging
, tlsAllowedVersions
, tlsCiphers
, defaultTlsSettings
, tlsSettings
, OnInsecure (..)
-- * Runner
, runTLS
, runTLSSocket
-- * Exception
, WarpTLSException (..)
) where
import qualified Network.TLS as TLS
import Network.Wai.Handler.Warp
import Network.Wai (Application)
import Network.Socket (Socket, sClose, withSocketsDo)
import qualified Data.ByteString.Lazy as L
import Control.Exception (bracket, finally, handle)
import qualified Network.TLS.Extra as TLSExtra
import qualified Data.ByteString as B
import Data.Streaming.Network (bindPortTCP, acceptSafe, safeRecv)
import Control.Applicative ((<$>))
import qualified Data.IORef as I
import Control.Exception (Exception, throwIO)
import Data.Typeable (Typeable)
import Data.Default.Class (def)
import qualified Crypto.Random.AESCtr
import Network.Wai.Handler.Warp.Buffer (allocateBuffer, bufferSize, freeBuffer)
import Network.Socket.ByteString (sendAll)
import Control.Monad (unless)
import Data.ByteString.Lazy.Internal (defaultChunkSize)
import qualified System.IO as IO
data TLSSettings = TLSSettings
{ certFile :: FilePath
-- ^ File containing the certificate.
, keyFile :: FilePath
-- ^ File containing the key
, onInsecure :: OnInsecure
-- ^ Do we allow insecure connections with this server as well? Default
-- is a simple text response stating that a secure connection is required.
--
-- Since 1.4.0
, tlsLogging :: TLS.Logging
-- ^ The level of logging to turn on.
--
-- Default: 'TLS.defaultLogging'.
--
-- Since 1.4.0
, tlsAllowedVersions :: [TLS.Version]
-- ^ The TLS versions this server accepts.
--
-- Default: '[TLS.SSL3,TLS.TLS10,TLS.TLS11,TLS.TLS12]'.
--
-- Since 1.4.2
, tlsCiphers :: [TLS.Cipher]
-- ^ The TLS ciphers this server accepts.
--
-- Default: '[TLSExtra.cipher_AES128_SHA1, TLSExtra.cipher_AES256_SHA1, TLSExtra.cipher_RC4_128_MD5, TLSExtra.cipher_RC4_128_SHA1]'
--
-- Since 1.4.2
}
-- | An action when a plain HTTP comes to HTTP over TLS/SSL port.
data OnInsecure = DenyInsecure L.ByteString
| AllowInsecure
-- | A smart constructor for 'TLSSettings'.
tlsSettings :: FilePath -- ^ Certificate file
-> FilePath -- ^ Key file
-> TLSSettings
tlsSettings cert key = defaultTlsSettings
{ certFile = cert
, keyFile = key
}
-- | Default 'TLSSettings'. Use this to create 'TLSSettings' with the field record name.
defaultTlsSettings :: TLSSettings
defaultTlsSettings = TLSSettings
{ certFile = "certificate.pem"
, keyFile = "key.pem"
, onInsecure = DenyInsecure "This server only accepts secure HTTPS connections."
, tlsLogging = def
, tlsAllowedVersions = [TLS.SSL3,TLS.TLS10,TLS.TLS11,TLS.TLS12]
, tlsCiphers = ciphers
}
-- | Running 'Application' with 'TLSSettings' and 'Settings' using
-- specified 'Socket'.
runTLSSocket :: TLSSettings -> Settings -> Socket -> Application -> IO ()
runTLSSocket TLSSettings {..} set sock app = do
credential <- either error id <$> TLS.credentialLoadX509 certFile keyFile
let params = def
{ TLS.serverWantClientCert = False
, TLS.serverSupported = def
{ TLS.supportedVersions = tlsAllowedVersions
, TLS.supportedCiphers = tlsCiphers
}
, TLS.serverShared = def
{ TLS.sharedCredentials = TLS.Credentials [credential]
}
}
runSettingsConnectionMakerSecure set (getter params) app
where
getter params = do
(s, sa) <- acceptSafe sock
let mkConn :: IO (Connection, Bool)
mkConn = do
firstBS <- safeRecv s 4096
cachedRef <- I.newIORef firstBS
let getNext size = do
cached <- I.readIORef cachedRef
loop cached
where
loop bs | B.length bs >= size = do
let (x, y) = B.splitAt size bs
I.writeIORef cachedRef y
return x
loop bs1 = do
bs2 <- safeRecv s 4096
if B.null bs2
then do
-- FIXME does this deserve an exception being thrown?
I.writeIORef cachedRef B.empty
return bs1
else loop $ B.append bs1 bs2
if not (B.null firstBS) && B.head firstBS == 0x16
then do
gen <- Crypto.Random.AESCtr.makeSystem
ctx <- TLS.contextNew
TLS.Backend
{ TLS.backendFlush = return ()
, TLS.backendClose = sClose s
, TLS.backendSend = sendAll s
, TLS.backendRecv = getNext
}
params
gen
TLS.contextHookSetLogging ctx tlsLogging
TLS.handshake ctx
readBuf <- allocateBuffer bufferSize
writeBuf <- allocateBuffer bufferSize
let conn = Connection
{ connSendMany = TLS.sendData ctx . L.fromChunks
, connSendAll = TLS.sendData ctx . L.fromChunks . return
, connSendFile = \fp offset len _th headers -> do
TLS.sendData ctx $ L.fromChunks headers
IO.withBinaryFile fp IO.ReadMode $ \h -> do
IO.hSeek h IO.AbsoluteSeek offset
let loop remaining | remaining <= 0 = return ()
loop remaining = do
bs <- B.hGetSome h defaultChunkSize
unless (B.null bs) $ do
let x = B.take remaining bs
TLS.sendData ctx $ L.fromChunks [x]
loop $ remaining - B.length x
loop $ fromIntegral len
, connClose =
freeBuffer readBuf `finally`
freeBuffer writeBuf `finally`
TLS.bye ctx `finally`
TLS.contextClose ctx
, connRecv =
let onEOF TLS.Error_EOF = return B.empty
onEOF e = throwIO e
go = do
x <- TLS.recvData ctx
if B.null x
then go
else return x
in handle onEOF go
, connSendFileOverride = NotOverride
, connReadBuffer = readBuf
, connWriteBuffer = writeBuf
, connBufferSize = bufferSize
}
return (conn, True)
else
case onInsecure of
AllowInsecure -> do
conn' <- socketConnection s
return (conn'
{ connRecv = getNext 4096
}, False)
DenyInsecure lbs -> do
sendAll s "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\n"
mapM_ (sendAll s) $ L.toChunks lbs
sClose s
throwIO InsecureConnectionDenied
return (mkConn, sa)
data WarpTLSException = InsecureConnectionDenied
deriving (Show, Typeable)
instance Exception WarpTLSException
-- | Running 'Application' with 'TLSSettings' and 'Settings'.
runTLS :: TLSSettings -> Settings -> Application -> IO ()
runTLS tset set app = withSocketsDo $
bracket
(bindPortTCP (getPort set) (getHost set))
sClose
(\sock -> runTLSSocket tset set sock app)
-- taken from stunnel example in tls-extra
ciphers :: [TLS.Cipher]
ciphers =
[ TLSExtra.cipher_AES128_SHA1
, TLSExtra.cipher_AES256_SHA1
, TLSExtra.cipher_RC4_128_MD5
, TLSExtra.cipher_RC4_128_SHA1
]
| beni55/wai | warp-tls/Network/Wai/Handler/WarpTLS.hs | mit | 9,080 | 3 | 42 | 3,717 | 1,687 | 909 | 778 | -1 | -1 |
-- | A simple Cofeescript library.
module Coffee.Bindings
( Coffee(..)
, coffeeCompile
, coffeeVersion
, coffeePrint
) where
import Data.Maybe (fromMaybe)
import System.Process (rawSystem, readProcess)
import System.Exit (ExitCode(..))
-- | The Coffee data structure
data Coffee = Coffee
{ customCompiler :: Maybe FilePath -- ^ Custom compiler path, set to Nothing for default
, bare :: Bool -- ^ set True to use '-b' option.
}
-- | Compile .coffee file(s)
coffeeCompile :: [FilePath] -- ^ List of .coffee files to compile
-> Maybe FilePath -- ^ Output directory, Nothing for default
-> Coffee -- ^ Coffee structure for more options
-> IO ExitCode -- ^ Exit code
coffeeCompile [] _ _ = return $ ExitFailure 1
coffeeCompile files output coffee =
rawSystem (getCompiler coffee) args
where args = outputPath output ++ ["-c"] ++ files
-- | Get the version of the coffee binary
coffeeVersion :: Coffee -> IO String
coffeeVersion c = coffeeRead c ["-v"]
-- | Print the coffee output
coffeePrint :: FilePath -> Coffee -> IO String
coffeePrint file c = coffeeRead c $ ["-v", file]
outputPath :: Maybe FilePath -> [FilePath]
outputPath (Just path) = ["-o", path]
outputPath Nothing = []
getCompiler :: Coffee -> FilePath
getCompiler = fromMaybe "coffee" . customCompiler
coffeeRead :: Coffee -> [String] -> IO String
coffeeRead coffee args =
readProcess (getCompiler coffee) args []
| AtticHacker/haskell-coffee | src/Coffee/Bindings.hs | gpl-3.0 | 1,521 | 0 | 9 | 370 | 364 | 200 | 164 | 31 | 1 |
#! /usr/bin/env nix-shell
#! nix-shell datahub-producer.hs.nix -i runghc
{-# LANGUAGE OverloadedStrings, FlexibleInstances, FlexibleContexts, ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
import System.Environment (getArgs)
import System.Directory (canonicalizePath)
import Data.Typeable (Typeable)
import Data.Functor ((<&>))
import Control.Arrow (left, right)
import Control.Monad ((>=>), when)
import Control.Monad.IO.Class (MonadIO(..))
import Control.Monad.Catch (Exception, MonadThrow(..))
import qualified Data.ByteString.Lazy as B
import qualified Data.ByteString.Lazy.Char8 as BC
import qualified Data.Text as T
import qualified Data.Aeson as J
import Data.String.Conversions (cs)
import qualified Data.Binary as BIN
import Data.HashMap.Strict ((!))
import qualified Data.HashMap.Strict as MS
import qualified Data.Vector as V
import Control.Lens ((^?), (^..), folded, _Just)
import Data.Aeson.Lens (key, _Array, _String)
import qualified Data.Avro.Types as A (Value(..))
import qualified Data.Avro as A (Schema, Result(..))
import qualified Data.Avro.Schema as AS (
Schema(..), resultToEither, buildTypeEnvironment
, renderFullname, parseFullname, typeName, parseAvroJSON
)
-- import Data.Avro.JSON (decodeAvroJSON)
import Data.Avro.Encode (encodeAvro)
import Data.Avro.Decode (decodeAvro)
-- import Data.Avro.Deriving (makeSchema)
import Kafka.Avro (
SchemaRegistry(..), Subject(..), SchemaId(..)
, schemaRegistry, sendSchema
, extractSchemaId, loadSchema
)
import Data.Conduit (ConduitT, ZipSink(..), getZipSink, runConduitRes, runConduit, bracketP, (.|), yield)
import qualified Data.Conduit.Combinators as C
import Kafka.Conduit.Sink (ProducerRecord(..), TopicName(..), ProducePartition(..), BrokerAddress(..), kafkaSink, brokersList)
import Network.URI (parseURI)
import Network.URI.Lens (uriAuthorityLens, uriRegNameLens, uriPortLens)
import System.Process (readProcess)
data StringException = StringException String deriving (Typeable, Show)
instance Exception StringException
decodeAvroJSON :: A.Schema -> J.Value -> A.Result (A.Value A.Schema)
decodeAvroJSON schema json =
AS.parseAvroJSON union env schema json
where
env =
AS.buildTypeEnvironment missing schema
missing name =
fail ("Type " <> show name <> " not in schema")
union (AS.Union schemas) J.Null
| AS.Null `elem` schemas =
pure $ A.Union schemas AS.Null A.Null
| otherwise =
fail "Null not in union."
union (AS.Union schemas) (J.Object obj)
| null obj =
fail "Invalid encoding of union: empty object ({})."
| length obj > 1 =
fail ("Invalid encoding of union: object with too many fields:" ++ show obj)
| otherwise =
let
canonicalize name
| isBuiltIn name = name
| otherwise = AS.renderFullname $ AS.parseFullname name
branch =
head $ MS.keys obj
names =
MS.fromList [(AS.typeName t, t) | t <- V.toList schemas]
in case MS.lookup (canonicalize branch) names of
Just t -> do
nested <- AS.parseAvroJSON union env t (obj ! branch)
return (A.Union schemas t nested)
Nothing -> fail ("Type '" <> T.unpack branch <> "' not in union: " <> show schemas)
union AS.Union{} _ =
A.Error "Invalid JSON representation for union: has to be a JSON object with exactly one field."
union _ _ =
error "Impossible: function given non-union schema."
isBuiltIn name = name `elem` [ "null", "boolean", "int", "long", "float"
, "double", "bytes", "string", "array", "map" ]
fromRight :: (MonadThrow m, Show a) => String -> Either a b -> m b
fromRight label = either (throwM . StringException . (label ++) . show) return
fromJust :: (MonadThrow m, Show a) => String -> Maybe a -> m a
fromJust label = maybe (throwM . StringException $ (label ++ "value is missing") ) return
encodeJsonWithSchema :: (MonadIO m, MonadThrow m)
=> SchemaRegistry
-> Subject
-> A.Schema
-> J.Value
-> m B.ByteString
encodeJsonWithSchema sr subj schema json = do
v <- fromRight "[decodeAvroJSON]" $ AS.resultToEither $ decodeAvroJSON schema json
mbSid <- fromRight "[SchemaRegistry.sendSchema]"=<< sendSchema sr subj schema
return $ appendSchemaId v mbSid
where appendSchemaId v (SchemaId sid)= B.cons (toEnum 0) (BIN.encode sid) <> (encodeAvro v)
decodeJsonWithSchema :: (MonadIO m, MonadThrow m)
=> SchemaRegistry
-> B.ByteString
-> m J.Value
decodeJsonWithSchema sr bs = do
(sid, payload) <- maybe (throwM . StringException $ "BadPayloadNoSchemaId") return $ extractSchemaId bs
schema <- fromRight "[SchemaRegistry.loadSchema]" =<< loadSchema sr sid
J.toJSON <$> (fromRight "[Avro.decodeAvro]" $ decodeAvro schema payload)
parseNixJson :: FilePath -> IO J.Value
parseNixJson f = do
stdout :: String <- read <$> readProcess "nix-instantiate" ["--eval", "--expr", "builtins.toJSON (import " ++ f ++ ")"] ""
fromRight "[Aeson.eitherDecode] parse nix json" (J.eitherDecode (cs stdout))
main :: IO ()
main = do
args <- getArgs
when (length args /= 1) $
error " datahub-producer.hs [config-dir]"
confDir <- canonicalizePath (head args)
putStrLn ("confDir:" <> confDir)
confJson <- parseNixJson (confDir <> "/" <> "datahub-config.nix")
-- putStrLn ("confJson: " ++ show confJson)
schema <- fromRight "[Aeson.eitherDecode] parse asvc file:" =<<
J.eitherDecode <$> B.readFile (confDir <> "/" <> "MetadataChangeEvent.avsc")
-- putStrLn ("schema: " ++ show schema)
let
topic = "MetadataChangeEvent"
-- schema = $(makeSchema "../MetadataChangeEvent.avsc")
sandboxL = key "services".key "linkedin-datahub-pipeline".key "sandbox"
urisL = key "uris". _Array.folded._String
brokers = confJson ^.. sandboxL.key "kafka".urisL
srs = confJson ^.. sandboxL.key "schema-registry".urisL
brokers' = map (\uriText -> BrokerAddress . cs . concat $ parseURI (cs uriText) ^.. _Just.uriAuthorityLens._Just.(uriRegNameLens <> uriPortLens)) brokers
contents <- B.getContents <&> BC.lines
sr <- schemaRegistry (cs (head srs))
putStrLn " ==> beginning to send data..."
runConduitRes $ C.yieldMany contents
.| C.mapM (fromRight "[JSON.eitherDecode] read json record:". J.eitherDecode)
-- .| C.iterM (liftIO . putStrLn. cs . J.encode)
.| C.mapM (encodeJsonWithSchema sr (Subject (topic <> "-value")) schema)
-- .| C.iterM (decodeJsonWithSchema sr >=> liftIO . print . J.encode)
.| C.map (mkRecord (TopicName topic))
.| getZipSink ( ZipSink (kafkaSink (brokersList brokers')) *>
ZipSink ((C.length >>= yield) .| C.iterM (\n -> liftIO $ putStrLn ("total table num:" <> show n)) .| C.sinkNull))
return ()
where
mkRecord :: TopicName -> B.ByteString -> ProducerRecord
mkRecord topic bs = ProducerRecord topic UnassignedPartition Nothing (Just (cs bs))
| mars-lan/WhereHows | contrib/metadata-ingestion/haskell/bin/datahub-producer.hs | apache-2.0 | 7,175 | 1 | 22 | 1,565 | 2,069 | 1,106 | 963 | -1 | -1 |
{-|
Module : IRTS.CodegenC
Description : The default code generator for Idris, generating C code.
Copyright :
License : BSD3
Maintainer : The Idris Community.
-}
{-# LANGUAGE FlexibleContexts #-}
module IRTS.CodegenC (codegenC) where
import Idris.AbsSyntax hiding (getBC)
import Idris.Core.TT
import IRTS.Bytecode
import IRTS.CodegenCommon
import IRTS.Defunctionalise
import IRTS.Lang
import IRTS.Simplified
import IRTS.System
import Util.System
import Control.Monad
import Control.Monad
import Control.Monad.RWS
import Data.Bits
import Data.Char
import Data.List (find, intercalate, nubBy, partition)
import qualified Data.Text as T
import Numeric
import System.Directory
import System.Exit
import System.FilePath ((<.>), (</>))
import System.IO
import System.Process
import Debug.Trace
codegenC :: CodeGenerator
codegenC ci = do codegenC' (simpleDecls ci)
(outputFile ci)
(outputType ci)
(includes ci)
(compileObjs ci)
(map mkLib (compileLibs ci) ++
map incdir (importDirs ci))
(compilerFlags ci)
(exportDecls ci)
(interfaces ci)
(debugLevel ci)
when (interfaces ci) $
codegenH (exportDecls ci)
where mkLib l = "-l" ++ l
incdir i = "-I" ++ i
codegenC' :: [(Name, SDecl)]
-> String -- ^ output file name
-> OutputType -- ^ generate executable if True, only .o if False
-> [FilePath] -- ^ include files
-> [String] -- ^ extra object files
-> [String] -- ^ extra compiler flags (libraries)
-> [String] -- ^ extra compiler flags (anything)
-> [ExportIFace]
-> Bool -- ^ interfaces too (so make a .o instead)
-> DbgLevel
-> IO ()
codegenC' defs out exec incs objs libs flags exports iface dbg
= do -- print defs
let bc = map toBC defs
let wrappers = genWrappers bc
let h = concatMap toDecl (map fst bc)
let (state, cc) = execRWS (generateSrc bc) 0
(CS { fnName = Nothing,
level = 1 })
let hi = concatMap ifaceC (concatMap getExp exports)
d <- getIdrisCRTSDir
mprog <- readFile (d </> "idris_main" <.> "c")
let cout = headers incs ++ debug dbg ++ h ++ wrappers ++ cc ++
(if (exec == Executable) then mprog else hi)
case exec of
Raw -> writeSource out cout
_ -> do
(tmpn, tmph) <- tempfile ".c"
hPutStr tmph cout
hFlush tmph
hClose tmph
comp <- getCC
libFlags <- getLibFlags
incFlags <- getIncFlags
envFlags <- getEnvFlags
let stackFlag = if isWindows then ["-Wl,--stack,16777216"] else []
let args = [gccDbg dbg] ++
gccFlags iface ++
-- # Any flags defined here which alter the RTS API must also be added to config.mk
["-DHAS_PTHREAD", "-DIDRIS_ENABLE_STATS",
"-I."] ++ objs ++ envFlags ++
(if (exec == Executable) then [] else ["-c"]) ++
[tmpn] ++
(if not iface then libFlags else []) ++
incFlags ++
(if not iface then libs else []) ++
flags ++ stackFlag ++
["-o", out]
-- putStrLn (show args)
exit <- rawSystem comp args
when (exit /= ExitSuccess) $
putStrLn ("FAILURE: " ++ show comp ++ " " ++ show args)
where
getExp (Export _ _ exp) = exp
headers xs =
concatMap
(\h -> "#include \"" ++ h ++ "\"\n")
(xs ++ ["idris_rts.h", "idris_bitstring.h", "idris_stdfgn.h"])
debug TRACE = "#define IDRIS_TRACE\n\n"
debug _ = ""
-- We're using signed integers now. Make sure we get consistent semantics
-- out of them from gcc. See e.g. http://thiemonagel.de/2010/01/signed-integer-overflow/
gccFlags i = if i then ["-fwrapv"]
else ["-fwrapv", "-fno-strict-overflow"]
gccDbg DEBUG = "-g"
gccDbg TRACE = "-O2"
gccDbg _ = "-O2"
cname :: Name -> String
cname n = "_idris_" ++ concatMap cchar (showCG n)
where cchar x | isAlpha x || isDigit x = [x]
| otherwise = "_" ++ show (fromEnum x) ++ "_"
indent :: Int -> String
indent n = replicate (n*4) ' '
creg RVal = "RVAL"
creg (L i) = "LOC(" ++ show i ++ ")"
creg (T i) = "TOP(" ++ show i ++ ")"
creg Tmp = "REG1"
toDecl :: Name -> String
toDecl f = "void " ++ cname f ++ "(VM*, VAL*);\n"
generateSrc :: [(Name, [BC])] -> RWS Int String CState ()
generateSrc bc = mapM_ toC bc
toC :: (Name, [BC]) -> RWS Int String CState ()
toC (f, code) = do
modify (\s -> s { fnName = Just f })
s <- get
tell $ "void " ++ cname f ++ "(VM* vm, VAL* oldbase) {\n"
tell $ indent (level s) ++ "INITFRAME;\n"
bcc code
tell $ "}\n\n"
showCStr :: String -> String
showCStr s = '"' : foldr ((++) . showChar) "\"" s
where
showChar :: Char -> String
showChar '"' = "\\\""
showChar '\\' = "\\\\"
showChar c
-- Note: we need the double quotes around the codes because otherwise
-- "\n3" would get encoded as "\x0a3", which is incorrect.
-- Instead, we opt for "\x0a""3" and let the C compiler deal with it.
| ord c < 0x20 = showUTF8 (ord c)
| ord c < 0x7f = [c] -- 0x7f = \DEL
| otherwise = showHexes (utf8bytes (ord c))
showUTF8 c = "\"\"\\x" ++ pad (showHex c "") ++ "\"\""
showHexes = foldr ((++) . showUTF8) ""
utf8bytes :: Int -> [Int]
utf8bytes x
| x <= 0x7f = [x]
| x <= 0x7ff = let (y : ys) = split [] 2 x in (y .|. 0xc0) : map (.|. 0x80) ys
| x <= 0xffff = let (y : ys) = split [] 3 x in (y .|. 0xe0) : map (.|. 0x80) ys
| x <= 0x10ffff = let (y : ys) = split [] 4 x in (y .|. 0xf0) : map (.|. 0x80) ys
| otherwise = error $ "Invalid Unicode code point U+" ++ showHex x ""
where
split acc 1 x = x : acc
split acc i x = split (x .&. 0x3f : acc) (i - 1) (shiftR x 6)
pad :: String -> String
pad s = case length s of
1 -> "0" ++ s
2 -> s
_ -> error $ "Can't happen: String of invalid length " ++ show s
data CState = CS {
fnName :: Maybe Name,
level :: Int
}
bcc :: [BC] -> RWS Int String CState ()
bcc [] = return ()
bcc ((ASSIGN l r):xs) = do
i <- get
tell $ indent (level i) ++ creg l ++ " = " ++ creg r ++ ";\n"
bcc xs
bcc ((ASSIGNCONST l c):xs) = do
i <- get
tell $ indent (level i) ++ creg l ++ " = " ++ mkConst c ++ ";\n"
bcc xs
where
mkConst (I i) = "MKINT(" ++ show i ++ ")"
mkConst (BI i) | i < (2^30) = "MKINT(" ++ show i ++ ")"
| otherwise = "MKBIGC(vm,\"" ++ show i ++ "\")"
mkConst (Fl f) = "MKFLOAT(vm, " ++ show f ++ ")"
mkConst (Ch c) = "MKINT(" ++ show (fromEnum c) ++ ")"
mkConst (Str s) = "MKSTR(vm, " ++ showCStr s ++ ")"
mkConst (B8 x) = "idris_b8const(vm, " ++ show x ++ "U)"
mkConst (B16 x) = "idris_b16const(vm, " ++ show x ++ "U)"
mkConst (B32 x) = "idris_b32const(vm, " ++ show x ++ "UL)"
mkConst (B64 x) = "idris_b64const(vm, " ++ show x ++ "ULL)"
-- if it's a type constant, we won't use it, but equally it shouldn't
-- report an error. These might creep into generated for various reasons
-- (especially if erasure is disabled).
mkConst c | isTypeConst c = "MKINT(42424242)"
mkConst c = error $ "mkConst of (" ++ show c ++ ") not implemented"
bcc ((UPDATE l r):xs) = do
i <- get
tell $ indent (level i) ++ creg l ++ " = " ++ creg r ++ ";\n"
bcc xs
bcc ((MKCON l loc tag []):xs) | tag < 256 = do
i <- get
tell $ indent (level i) ++ creg l ++ " = NULL_CON(" ++ show tag ++ ");\n"
bcc xs
bcc ((MKCON l loc tag args):xs) = do
i <- get
let tab = indent (level i)
tell $ tab ++ alloc loc tag ++
tab ++ setArgs 0 args ++ "\n" ++
tab ++ creg l ++ " = " ++ creg Tmp ++ ";\n"
bcc xs
where showArg r = ", " ++ creg r
setArgs i [] = ""
setArgs i (x : xs) = "SETARG(" ++ creg Tmp ++ ", " ++ show i ++ ", " ++ creg x ++
"); " ++ setArgs (i + 1) xs
alloc Nothing tag
= "allocCon(" ++ creg Tmp ++ ", vm, " ++ show tag ++ ", " ++
show (length args) ++ ", 0);\n"
alloc (Just old) tag
= "updateCon(" ++ creg Tmp ++ ", " ++ creg old ++ ", " ++ show tag ++ ", " ++
show (length args) ++ ");\n"
bcc ((PROJECT l loc a):xs) = do
i <- get
tell $ indent (level i) ++ "PROJECT(vm, " ++ creg l ++ ", "
++ show loc ++ ", " ++ show a ++ ");\n"
bcc xs
bcc ((PROJECTINTO r t idx):xs) = do
i <- get
tell $ indent (level i) ++ creg r ++ " = GETARG(" ++ creg t
++ ", " ++ show idx ++ ");\n"
bcc xs
bcc ((CASE True r code def):xs)
| length code < 4 = do
showCases def code
bcc xs
where
showCode bc = do
w <- getBC bc xs
i <- get
tell $ "{\n" ++ w ++ indent (level i) ++ "}\n"
showCases Nothing [(t, c)] = do
i <- get
tell $ indent (level i)
showCode c
showCases (Just def) [] = do
i <- get
tell $ indent (level i)
showCode def
showCases def ((t, c) : cs) = do
i <- get
tell $ indent (level i) ++ "if (CTAG(" ++ creg r ++ ") == "
++ show t ++ ") "
showCode c
tell $ indent (level i) ++ "else\n"
showCases def cs
bcc ((CASE safe r code def):xs) = do
i <- get
tell $ indent (level i) ++ "switch(" ++ ctag safe ++ "(" ++ creg r ++ ")) {\n"
mapM showCase code
showDef def
tell $ indent (level i) ++ "}\n"
bcc xs
where
ctag True = "CTAG"
ctag False = "TAG"
showCase (t, bc) = do
w <- getBC bc xs
is <- get
let i = level is
tell $ indent i ++ "case " ++ show t ++ ":\n"
++ w ++ indent (i + 1) ++ "break;\n"
showDef Nothing = return $ ()
showDef (Just c) = do
w <- getBC c xs
is <- get
let i = level is
tell $ indent i ++ "default:\n" ++ w ++ indent (i + 1) ++ "break;\n"
bcc ((CONSTCASE r code def):xs)
| intConsts code
= do
is <- get
let i = level is
codes <- mapM getCode code
defs <- showDefS def
tell $ concatMap (iCase i (creg r)) codes
tell $ indent i ++ "{\n" ++ defs ++ indent i ++ "}\n"
bcc xs
| strConsts code
= do
is <- get
let i = level is
codes <- mapM getCode code
defs <- showDefS def
tell $ concatMap (strCase i ("GETSTR(" ++ creg r ++ ")")) codes
++ indent i ++ "{\n" ++ defs ++ indent i ++ "}\n"
bcc xs
| bigintConsts code
= do
is <- get
let i = level is
codes <- mapM getCode code
defs <- showDefS def
tell $ concatMap (biCase i (creg r)) codes ++
indent i ++ "{\n" ++ defs ++ indent i ++ "}\n"
bcc xs
| otherwise = error $ "Can't happen: Can't compile const case " ++ show code
where
intConsts ((I _, _ ) : _) = True
intConsts ((Ch _, _ ) : _) = True
intConsts ((B8 _, _ ) : _) = True
intConsts ((B16 _, _ ) : _) = True
intConsts ((B32 _, _ ) : _) = True
intConsts ((B64 _, _ ) : _) = True
intConsts _ = False
bigintConsts ((BI _, _ ) : _) = True
bigintConsts _ = False
strConsts ((Str _, _ ) : _) = True
strConsts _ = False
getCode (x, code) = do
c <- getBC code xs
return (x, c)
strCase i sv (s, bc) =
indent i ++ "if (strcmp(" ++ sv ++ ", " ++ show s ++ ") == 0) {\n" ++
bc ++ indent i ++ "} else\n"
biCase i bv (BI b, bc) =
indent i ++ "if (bigEqConst(" ++ bv ++ ", " ++ show b ++ ")) {\n"
++ bc ++ indent i ++ "} else\n"
iCase i v (I b, bc) =
indent i ++ "if (GETINT(" ++ v ++ ") == " ++ show b ++ ") {\n"
++ bc ++ indent i ++ "} else\n"
iCase i v (Ch b, bc) =
indent i ++ "if (GETINT(" ++ v ++ ") == " ++ show (fromEnum b) ++ ") {\n"
++ bc ++ indent i ++ "} else\n"
iCase i v (B8 w, bc) =
indent i ++ "if (GETBITS8(" ++ v ++ ") == " ++ show (fromEnum w) ++ ") {\n"
++ bc ++ indent i ++ "} else\n"
iCase i v (B16 w, bc) =
indent i ++ "if (GETBITS16(" ++ v ++ ") == " ++ show (fromEnum w) ++ ") {\n"
++ bc ++ indent i ++ "} else\n"
iCase i v (B32 w, bc) =
indent i ++ "if (GETBITS32(" ++ v ++ ") == " ++ show (fromEnum w) ++ ") {\n"
++ bc ++ indent i ++ "} else\n"
iCase i v (B64 w, bc) =
indent i ++ "if (GETBITS64(" ++ v ++ ") == " ++ show (fromEnum w) ++ ") {\n"
++ bc ++ indent i ++ "} else\n"
showDefS Nothing = return ""
showDefS (Just c) = getBC c xs
bcc (CALL n:xs) = do
i <- get
tell $ indent (level i) ++ "CALL(" ++ cname n ++ ");\n"
bcc xs
bcc (TAILCALL n:xs) = do
i <- get
tell $ indent (level i) ++ "TAILCALL(" ++ cname n ++ ");\n"
bcc xs
bcc ((SLIDE n):xs) = do
i <- get
tell $ indent (level i) ++ "SLIDE(vm, " ++ show n ++ ");\n"
bcc xs
bcc (REBASE:xs) = do
i <- get
tell $ indent (level i)++ "REBASE;\n"
bcc xs
bcc ((RESERVE 0):xs) = bcc xs
bcc ((RESERVE n):xs) = do
i <- get
tell $ indent (level i) ++ "RESERVE(" ++ show n ++ ");\n"
bcc xs
bcc ((ADDTOP 0):xs) = bcc xs
bcc ((ADDTOP n):xs) = do
i <- get
tell $ indent (level i) ++ "ADDTOP(" ++ show n ++ ");\n"
bcc xs
bcc ((TOPBASE n):xs) = do
i <- get
tell $ indent (level i) ++ "TOPBASE(" ++ show n ++ ");\n"
bcc xs
bcc ((BASETOP n):xs) = do
i <- get
tell $ indent (level i) ++ "BASETOP(" ++ show n ++ ");\n"
bcc xs
bcc (STOREOLD:xs) = do
i <- get
tell $ indent (level i) ++ "STOREOLD;\n"
bcc xs
bcc ((OP l fn args):xs) = do
i <- get
tell $ indent (level i) ++ doOp (creg l ++ " = ") fn args ++ ";\n"
bcc xs
bcc ((FOREIGNCALL l rty (FStr fn@('&':name)) []):xs) = do
i <- get
tell $ indent (level i) ++ c_irts (toFType rty) (creg l ++ " = ") fn ++ ";\n"
bcc xs
bcc ((FOREIGNCALL l rty (FStr fn) (x:xs)):zs) | fn == "%wrapper"
= do
i <- get
tell $ indent (level i) ++ c_irts (toFType rty) (creg l ++ " = ")
("_idris_get_wrapper(" ++ creg (snd x) ++ ")") ++ ";\n"
bcc zs
bcc ((FOREIGNCALL l rty (FStr fn) (x:xs)):zs) | fn == "%dynamic"
= do
i <- get
tell $ indent (level i) ++ c_irts (toFType rty) (creg l ++ " = ")
("(*(" ++ cFnSig "" rty xs ++ ") GETPTR(" ++ creg (snd x) ++ "))" ++
"(" ++ showSep "," (map fcall xs) ++ ")") ++ ";\n"
bcc zs
bcc ((FOREIGNCALL l rty (FStr fn) args):xs) = do
i <- get
tell $ indent (level i) ++ c_irts (toFType rty) (creg l ++ " = ")
(fn ++ "(" ++ showSep "," (map fcall args) ++ ")") ++ ";\n"
bcc xs
bcc ((FOREIGNCALL l rty _ args):_) = error "Foreign Function calls cannot be partially applied, without being inlined."
bcc ((NULL r):xs) = do
i <- get
tell $ indent (level i) ++ creg r ++ " = NULL;\n" -- clear, so it'll be GCed
bcc xs
bcc ((ERROR str):xs) = do
i <- get
tell $ indent (level i) ++ "fprintf(stderr, "
++ show str ++ "); fprintf(stderr, \"\\n\"); exit(-1);\n"
bcc xs
-- bcc i c = error (show c) -- indent i ++ "// not done yet\n"
getBC code xs = do
i <- get
let (a, s, w) = runRWS (bcc code) 0 (i { level = level i + 1 })
return w
fcall (t, arg) = irts_c (toFType t) (creg arg)
-- Deconstruct the Foreign type in the defunctionalised expression and build
-- a foreign type description for c_irts and irts_c
toAType (FCon i)
| i == sUN "C_IntChar" = ATInt ITChar
| i == sUN "C_IntNative" = ATInt ITNative
| i == sUN "C_IntBits8" = ATInt (ITFixed IT8)
| i == sUN "C_IntBits16" = ATInt (ITFixed IT16)
| i == sUN "C_IntBits32" = ATInt (ITFixed IT32)
| i == sUN "C_IntBits64" = ATInt (ITFixed IT64)
toAType t = error (show t ++ " not defined in toAType")
toFType (FCon c)
| c == sUN "C_Str" = FString
| c == sUN "C_Float" = FArith ATFloat
| c == sUN "C_Ptr" = FPtr
| c == sUN "C_MPtr" = FManagedPtr
| c == sUN "C_CData" = FCData
| c == sUN "C_Unit" = FUnit
toFType (FApp c [_,ity])
| c == sUN "C_IntT" = FArith (toAType ity)
| c == sUN "C_FnT" = toFunType ity
toFType (FApp c [_])
| c == sUN "C_Any" = FAny
toFType t = FAny
toFunType (FApp c [_,ity])
| c == sUN "C_FnBase" = FFunction
| c == sUN "C_FnIO" = FFunctionIO
toFunType (FApp c [_,_,_,ity])
| c == sUN "C_Fn" = toFunType ity
toFunType _ = FAny
c_irts (FArith (ATInt ITNative)) l x = l ++ "MKINT((i_int)(" ++ x ++ "))"
c_irts (FArith (ATInt ITChar)) l x = c_irts (FArith (ATInt ITNative)) l x
c_irts (FArith (ATInt (ITFixed ity))) l x
= l ++ "idris_b" ++ show (nativeTyWidth ity) ++ "const(vm, " ++ x ++ ")"
c_irts FString l x = l ++ "MKSTR(vm, " ++ x ++ ")"
c_irts FUnit l x = x
c_irts FPtr l x = l ++ "MKPTR(vm, " ++ x ++ ")"
c_irts FManagedPtr l x = l ++ "MKMPTR(vm, " ++ x ++ ")"
c_irts (FArith ATFloat) l x = l ++ "MKFLOAT(vm, " ++ x ++ ")"
c_irts FCData l x = l ++ "MKCDATA(vm, " ++ x ++ ")"
c_irts FAny l x = l ++ x
c_irts FFunction l x = error "Return of function from foreign call is not supported"
c_irts FFunctionIO l x = error "Return of function from foreign call is not supported"
irts_c (FArith (ATInt ITNative)) x = "GETINT(" ++ x ++ ")"
irts_c (FArith (ATInt ITChar)) x = irts_c (FArith (ATInt ITNative)) x
irts_c (FArith (ATInt (ITFixed ity))) x
= "(" ++ x ++ "->info.bits" ++ show (nativeTyWidth ity) ++ ")"
irts_c FString x = "GETSTR(" ++ x ++ ")"
irts_c FUnit x = x
irts_c FPtr x = "GETPTR(" ++ x ++ ")"
irts_c FManagedPtr x = "GETMPTR(" ++ x ++ ")"
irts_c (FArith ATFloat) x = "GETFLOAT(" ++ x ++ ")"
irts_c FCData x = "GETCDATA(" ++ x ++ ")"
irts_c FAny x = x
irts_c FFunctionIO x = wrapped x
irts_c FFunction x = wrapped x
cFnSig name rty [] = ctype rty ++ " (*" ++ name ++ ")(void) "
cFnSig name rty args = ctype rty ++ " (*" ++ name ++ ")("
++ showSep "," (map (ctype . fst) args) ++ ") "
wrapped x = "_idris_get_wrapper(" ++ x ++ ")"
bitOp v op ty args = v ++ "idris_b" ++ show (nativeTyWidth ty) ++ op ++ "(vm, " ++ intercalate ", " (map creg args) ++ ")"
bitCoerce v op input output arg
= v ++ "idris_b" ++ show (nativeTyWidth input) ++ op ++ show (nativeTyWidth output) ++ "(vm, " ++ creg arg ++ ")"
signedTy :: NativeTy -> String
signedTy t = "int" ++ show (nativeTyWidth t) ++ "_t"
doOp v (LPlus (ATInt ITNative)) [l, r] = v ++ "ADD(" ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LMinus (ATInt ITNative)) [l, r] = v ++ "INTOP(-," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LTimes (ATInt ITNative)) [l, r] = v ++ "MULT(" ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LUDiv ITNative) [l, r] = v ++ "UINTOP(/," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSDiv (ATInt ITNative)) [l, r] = v ++ "INTOP(/," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LURem ITNative) [l, r] = v ++ "UINTOP(%," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSRem (ATInt ITNative)) [l, r] = v ++ "INTOP(%," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LAnd ITNative) [l, r] = v ++ "INTOP(&," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LOr ITNative) [l, r] = v ++ "INTOP(|," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LXOr ITNative) [l, r] = v ++ "INTOP(^," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSHL ITNative) [l, r] = v ++ "INTOP(<<," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LLSHR ITNative) [l, r] = v ++ "UINTOP(>>," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LASHR ITNative) [l, r] = v ++ "INTOP(>>," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LCompl ITNative) [x] = v ++ "INTOP(~," ++ creg x ++ ")"
doOp v (LEq (ATInt ITNative)) [l, r] = v ++ "INTOP(==," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSLt (ATInt ITNative)) [l, r] = v ++ "INTOP(<," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSLe (ATInt ITNative)) [l, r] = v ++ "INTOP(<=," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSGt (ATInt ITNative)) [l, r] = v ++ "INTOP(>," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSGe (ATInt ITNative)) [l, r] = v ++ "INTOP(>=," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LLt ITNative) [l, r] = v ++ "UINTOP(<," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LLe ITNative) [l, r] = v ++ "UINTOP(<=," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LGt ITNative) [l, r] = v ++ "UINTOP(>," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LGe ITNative) [l, r] = v ++ "UINTOP(>=," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LPlus (ATInt ITChar)) [l, r] = doOp v (LPlus (ATInt ITNative)) [l, r]
doOp v (LMinus (ATInt ITChar)) [l, r] = doOp v (LMinus (ATInt ITNative)) [l, r]
doOp v (LTimes (ATInt ITChar)) [l, r] = doOp v (LTimes (ATInt ITNative)) [l, r]
doOp v (LUDiv ITChar) [l, r] = doOp v (LUDiv ITNative) [l, r]
doOp v (LSDiv (ATInt ITChar)) [l, r] = doOp v (LSDiv (ATInt ITNative)) [l, r]
doOp v (LURem ITChar) [l, r] = doOp v (LURem ITNative) [l, r]
doOp v (LSRem (ATInt ITChar)) [l, r] = doOp v (LSRem (ATInt ITNative)) [l, r]
doOp v (LAnd ITChar) [l, r] = doOp v (LAnd ITNative) [l, r]
doOp v (LOr ITChar) [l, r] = doOp v (LOr ITNative) [l, r]
doOp v (LXOr ITChar) [l, r] = doOp v (LXOr ITNative) [l, r]
doOp v (LSHL ITChar) [l, r] = doOp v (LSHL ITNative) [l, r]
doOp v (LLSHR ITChar) [l, r] = doOp v (LLSHR ITNative) [l, r]
doOp v (LASHR ITChar) [l, r] = doOp v (LASHR ITNative) [l, r]
doOp v (LCompl ITChar) [x] = doOp v (LCompl ITNative) [x]
doOp v (LEq (ATInt ITChar)) [l, r] = doOp v (LEq (ATInt ITNative)) [l, r]
doOp v (LSLt (ATInt ITChar)) [l, r] = doOp v (LSLt (ATInt ITNative)) [l, r]
doOp v (LSLe (ATInt ITChar)) [l, r] = doOp v (LSLe (ATInt ITNative)) [l, r]
doOp v (LSGt (ATInt ITChar)) [l, r] = doOp v (LSGt (ATInt ITNative)) [l, r]
doOp v (LSGe (ATInt ITChar)) [l, r] = doOp v (LSGe (ATInt ITNative)) [l, r]
doOp v (LLt ITChar) [l, r] = doOp v (LLt ITNative) [l, r]
doOp v (LLe ITChar) [l, r] = doOp v (LLe ITNative) [l, r]
doOp v (LGt ITChar) [l, r] = doOp v (LGt ITNative) [l, r]
doOp v (LGe ITChar) [l, r] = doOp v (LGe ITNative) [l, r]
doOp v (LPlus ATFloat) [l, r] = v ++ "FLOATOP(+," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LMinus ATFloat) [l, r] = v ++ "FLOATOP(-," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LTimes ATFloat) [l, r] = v ++ "FLOATOP(*," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSDiv ATFloat) [l, r] = v ++ "FLOATOP(/," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LEq ATFloat) [l, r] = v ++ "FLOATBOP(==," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSLt ATFloat) [l, r] = v ++ "FLOATBOP(<," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSLe ATFloat) [l, r] = v ++ "FLOATBOP(<=," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSGt ATFloat) [l, r] = v ++ "FLOATBOP(>," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSGe ATFloat) [l, r] = v ++ "FLOATBOP(>=," ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LIntFloat ITBig) [x] = v ++ "idris_castBigFloat(vm, " ++ creg x ++ ")"
doOp v (LFloatInt ITBig) [x] = v ++ "idris_castFloatBig(vm, " ++ creg x ++ ")"
doOp v (LPlus (ATInt ITBig)) [l, r] = v ++ "idris_bigPlus(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LMinus (ATInt ITBig)) [l, r] = v ++ "idris_bigMinus(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LTimes (ATInt ITBig)) [l, r] = v ++ "idris_bigTimes(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSDiv (ATInt ITBig)) [l, r] = v ++ "idris_bigDivide(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSRem (ATInt ITBig)) [l, r] = v ++ "idris_bigMod(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LAnd ITBig) [l, r] = v ++ "idris_bigAnd(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LOr ITBig) [l, r] = v ++ "idris_bigOr(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSHL ITBig) [l, r] = v ++ "idris_bigShiftLeft(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LLSHR ITBig) [l, r] = v ++ "idris_bigLShiftRight(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LASHR ITBig) [l, r] = v ++ "idris_bigAShiftRight(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LEq (ATInt ITBig)) [l, r] = v ++ "idris_bigEq(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSLt (ATInt ITBig)) [l, r] = v ++ "idris_bigLt(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSLe (ATInt ITBig)) [l, r] = v ++ "idris_bigLe(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSGt (ATInt ITBig)) [l, r] = v ++ "idris_bigGt(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LSGe (ATInt ITBig)) [l, r] = v ++ "idris_bigGe(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v (LIntFloat ITNative) [x] = v ++ "idris_castIntFloat(" ++ creg x ++ ")"
doOp v (LFloatInt ITNative) [x] = v ++ "idris_castFloatInt(" ++ creg x ++ ")"
doOp v (LSExt ITNative ITBig) [x] = v ++ "idris_castIntBig(vm, " ++ creg x ++ ")"
doOp v (LTrunc ITBig ITNative) [x] = v ++ "idris_castBigInt(vm, " ++ creg x ++ ")"
doOp v (LStrInt ITBig) [x] = v ++ "idris_castStrBig(vm, " ++ creg x ++ ")"
doOp v (LIntStr ITBig) [x] = v ++ "idris_castBigStr(vm, " ++ creg x ++ ")"
doOp v (LIntStr ITNative) [x] = v ++ "idris_castIntStr(vm, " ++ creg x ++ ")"
doOp v (LStrInt ITNative) [x] = v ++ "idris_castStrInt(vm, " ++ creg x ++ ")"
doOp v (LIntStr (ITFixed _)) [x] = v ++ "idris_castBitsStr(vm, " ++ creg x ++ ")"
doOp v LFloatStr [x] = v ++ "idris_castFloatStr(vm, " ++ creg x ++ ")"
doOp v LStrFloat [x] = v ++ "idris_castStrFloat(vm, " ++ creg x ++ ")"
doOp v (LSLt (ATInt (ITFixed ty))) [x, y] = bitOp v "SLt" ty [x, y]
doOp v (LSLe (ATInt (ITFixed ty))) [x, y] = bitOp v "SLte" ty [x, y]
doOp v (LEq (ATInt (ITFixed ty))) [x, y] = bitOp v "Eq" ty [x, y]
doOp v (LSGe (ATInt (ITFixed ty))) [x, y] = bitOp v "SGte" ty [x, y]
doOp v (LSGt (ATInt (ITFixed ty))) [x, y] = bitOp v "SGt" ty [x, y]
doOp v (LLt (ITFixed ty)) [x, y] = bitOp v "Lt" ty [x, y]
doOp v (LLe (ITFixed ty)) [x, y] = bitOp v "Lte" ty [x, y]
doOp v (LGe (ITFixed ty)) [x, y] = bitOp v "Gte" ty [x, y]
doOp v (LGt (ITFixed ty)) [x, y] = bitOp v "Gt" ty [x, y]
doOp v (LSHL (ITFixed ty)) [x, y] = bitOp v "Shl" ty [x, y]
doOp v (LLSHR (ITFixed ty)) [x, y] = bitOp v "LShr" ty [x, y]
doOp v (LASHR (ITFixed ty)) [x, y] = bitOp v "AShr" ty [x, y]
doOp v (LAnd (ITFixed ty)) [x, y] = bitOp v "And" ty [x, y]
doOp v (LOr (ITFixed ty)) [x, y] = bitOp v "Or" ty [x, y]
doOp v (LXOr (ITFixed ty)) [x, y] = bitOp v "Xor" ty [x, y]
doOp v (LCompl (ITFixed ty)) [x] = bitOp v "Compl" ty [x]
doOp v (LPlus (ATInt (ITFixed ty))) [x, y] = bitOp v "Plus" ty [x, y]
doOp v (LMinus (ATInt (ITFixed ty))) [x, y] = bitOp v "Minus" ty [x, y]
doOp v (LTimes (ATInt (ITFixed ty))) [x, y] = bitOp v "Times" ty [x, y]
doOp v (LUDiv (ITFixed ty)) [x, y] = bitOp v "UDiv" ty [x, y]
doOp v (LSDiv (ATInt (ITFixed ty))) [x, y] = bitOp v "SDiv" ty [x, y]
doOp v (LURem (ITFixed ty)) [x, y] = bitOp v "URem" ty [x, y]
doOp v (LSRem (ATInt (ITFixed ty))) [x, y] = bitOp v "SRem" ty [x, y]
doOp v (LSExt (ITFixed from) ITBig) [x]
= v ++ "MKBIGSI(vm, (" ++ signedTy from ++ ")" ++ creg x ++ "->info.bits" ++ show (nativeTyWidth from) ++ ")"
doOp v (LSExt ITNative (ITFixed to)) [x]
= v ++ "idris_b" ++ show (nativeTyWidth to) ++ "const(vm, GETINT(" ++ creg x ++ "))"
doOp v (LSExt ITChar (ITFixed to)) [x]
= doOp v (LSExt ITNative (ITFixed to)) [x]
doOp v (LSExt (ITFixed from) ITNative) [x]
= v ++ "MKINT((i_int)((" ++ signedTy from ++ ")" ++ creg x ++ "->info.bits" ++ show (nativeTyWidth from) ++ "))"
doOp v (LSExt (ITFixed from) ITChar) [x]
= doOp v (LSExt (ITFixed from) ITNative) [x]
doOp v (LSExt (ITFixed from) (ITFixed to)) [x]
| nativeTyWidth from < nativeTyWidth to = bitCoerce v "S" from to x
doOp v (LZExt ITNative (ITFixed to)) [x]
= v ++ "idris_b" ++ show (nativeTyWidth to) ++ "const(vm, (uintptr_t)GETINT(" ++ creg x ++ "))"
doOp v (LZExt ITChar (ITFixed to)) [x]
= doOp v (LZExt ITNative (ITFixed to)) [x]
doOp v (LZExt (ITFixed from) ITNative) [x]
= v ++ "MKINT((i_int)" ++ creg x ++ "->info.bits" ++ show (nativeTyWidth from) ++ ")"
doOp v (LZExt (ITFixed from) ITChar) [x]
= doOp v (LZExt (ITFixed from) ITNative) [x]
doOp v (LZExt (ITFixed from) ITBig) [x]
= v ++ "MKBIGUI(vm, " ++ creg x ++ "->info.bits" ++ show (nativeTyWidth from) ++ ")"
doOp v (LZExt ITNative ITBig) [x]
= v ++ "MKBIGUI(vm, (uintptr_t)GETINT(" ++ creg x ++ "))"
doOp v (LZExt (ITFixed from) (ITFixed to)) [x]
| nativeTyWidth from < nativeTyWidth to = bitCoerce v "Z" from to x
doOp v (LTrunc ITNative (ITFixed to)) [x]
= v ++ "idris_b" ++ show (nativeTyWidth to) ++ "const(vm, GETINT(" ++ creg x ++ "))"
doOp v (LTrunc ITChar (ITFixed to)) [x]
= doOp v (LTrunc ITNative (ITFixed to)) [x]
doOp v (LTrunc (ITFixed from) ITNative) [x]
= v ++ "MKINT((i_int)" ++ creg x ++ "->info.bits" ++ show (nativeTyWidth from) ++ ")"
doOp v (LTrunc (ITFixed from) ITChar) [x]
= doOp v (LTrunc (ITFixed from) ITNative) [x]
doOp v (LTrunc ITBig (ITFixed IT64)) [x]
= v ++ "idris_b64const(vm, ISINT(" ++ creg x ++ ") ? GETINT(" ++ creg x ++ ") : idris_truncBigB64(GETMPZ(" ++ creg x ++ ")))"
doOp v (LTrunc ITBig (ITFixed to)) [x]
= v ++ "idris_b" ++ show (nativeTyWidth to) ++ "const(vm, ISINT(" ++ creg x ++ ") ? GETINT(" ++ creg x ++ ") : mpz_get_ui(GETMPZ(" ++ creg x ++ ")))"
doOp v (LTrunc (ITFixed from) (ITFixed to)) [x]
| nativeTyWidth from > nativeTyWidth to = bitCoerce v "T" from to x
doOp v LFExp [x] = v ++ flUnOp "exp" (creg x)
doOp v LFLog [x] = v ++ flUnOp "log" (creg x)
doOp v LFSin [x] = v ++ flUnOp "sin" (creg x)
doOp v LFCos [x] = v ++ flUnOp "cos" (creg x)
doOp v LFTan [x] = v ++ flUnOp "tan" (creg x)
doOp v LFASin [x] = v ++ flUnOp "asin" (creg x)
doOp v LFACos [x] = v ++ flUnOp "acos" (creg x)
doOp v LFATan [x] = v ++ flUnOp "atan" (creg x)
doOp v LFSqrt [x] = v ++ flUnOp "sqrt" (creg x)
doOp v LFFloor [x] = v ++ flUnOp "floor" (creg x)
doOp v LFCeil [x] = v ++ flUnOp "ceil" (creg x)
doOp v LFNegate [x] = v ++ "MKFLOAT(vm, -GETFLOAT(" ++ (creg x) ++ "))"
-- String functions which don't need to know we're UTF8
doOp v LStrConcat [l,r] = v ++ "idris_concat(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v LStrLt [l,r] = v ++ "idris_strlt(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v LStrEq [l,r] = v ++ "idris_streq(vm, " ++ creg l ++ ", " ++ creg r ++ ")"
doOp v LReadStr [_] = v ++ "idris_readStr(vm, stdin)"
doOp v LWriteStr [_,s]
= v ++ "MKINT((i_int)(idris_writeStr(stdout"
++ ",GETSTR("
++ creg s ++ "))))"
-- String functions which need to know we're UTF8
doOp v LStrHead [x] = v ++ "idris_strHead(vm, " ++ creg x ++ ")"
doOp v LStrTail [x] = v ++ "idris_strTail(vm, " ++ creg x ++ ")"
doOp v LStrCons [x, y] = v ++ "idris_strCons(vm, " ++ creg x ++ "," ++ creg y ++ ")"
doOp v LStrIndex [x, y] = v ++ "idris_strIndex(vm, " ++ creg x ++ "," ++ creg y ++ ")"
doOp v LStrRev [x] = v ++ "idris_strRev(vm, " ++ creg x ++ ")"
doOp v LStrLen [x] = v ++ "idris_strlen(vm, " ++ creg x ++ ")"
doOp v LStrSubstr [x,y,z] = v ++ "idris_substr(vm, " ++ creg x ++ "," ++ creg y ++ "," ++ creg z ++ ")"
doOp v LFork [x] = v ++ "MKPTR(vm, vmThread(vm, " ++ cname (sMN 0 "EVAL") ++ ", " ++ creg x ++ "))"
doOp v LPar [x] = v ++ creg x -- "MKPTR(vm, vmThread(vm, " ++ cname (MN 0 "EVAL") ++ ", " ++ creg x ++ "))"
doOp v (LChInt ITNative) args = v ++ creg (last args)
doOp v (LChInt ITChar) args = doOp v (LChInt ITNative) args
doOp v (LIntCh ITNative) args = v ++ creg (last args)
doOp v (LIntCh ITChar) args = doOp v (LIntCh ITNative) args
doOp v LSystemInfo [x] = v ++ "idris_systemInfo(vm, " ++ creg x ++ ")"
doOp v LCrash [x] = "idris_crash(GETSTR(" ++ creg x ++ "))"
doOp v LNoOp args = v ++ creg (last args)
-- Pointer primitives (declared as %extern in Builtins.idr)
doOp v (LExternal rf) [_,x]
| rf == sUN "prim__readFile"
= v ++ "idris_readStr(vm, GETPTR(" ++ creg x ++ "))"
doOp v (LExternal rf) [_,len,x]
| rf == sUN "prim__readChars"
= v ++ "idris_readChars(vm, GETINT(" ++ creg len ++
"), GETPTR(" ++ creg x ++ "))"
doOp v (LExternal wf) [_,x,s]
| wf == sUN "prim__writeFile"
= v ++ "MKINT((i_int)(idris_writeStr(GETPTR(" ++ creg x
++ "),GETSTR("
++ creg s ++ "))))"
doOp v (LExternal si) [] | si == sUN "prim__stdin" = v ++ "MKPTR(vm, stdin)"
doOp v (LExternal so) [] | so == sUN "prim__stdout" = v ++ "MKPTR(vm, stdout)"
doOp v (LExternal se) [] | se == sUN "prim__stderr" = v ++ "MKPTR(vm, stderr)"
doOp v (LExternal vm) [_] | vm == sUN "prim__vm" = v ++ "MKPTR(vm, vm)"
doOp v (LExternal nul) [] | nul == sUN "prim__null" = v ++ "MKPTR(vm, NULL)"
doOp v (LExternal eqp) [x, y] | eqp == sUN "prim__eqPtr"
= v ++ "MKINT((i_int)(GETPTR(" ++ creg x ++ ") == GETPTR(" ++ creg y ++ ")))"
doOp v (LExternal eqp) [x, y] | eqp == sUN "prim__eqManagedPtr"
= v ++ "MKINT((i_int)(GETMPTR(" ++ creg x ++ ") == GETMPTR(" ++ creg y ++ ")))"
doOp v (LExternal rp) [p, i] | rp == sUN "prim__registerPtr"
= v ++ "MKMPTR(vm, GETPTR(" ++ creg p ++ "), GETINT(" ++ creg i ++ "))"
doOp v (LExternal pk) [_, p, o] | pk == sUN "prim__peek8"
= v ++ "idris_peekB8(vm," ++ creg p ++ "," ++ creg o ++")"
doOp v (LExternal pk) [_, p, o, x] | pk == sUN "prim__poke8"
= v ++ "idris_pokeB8(" ++ creg p ++ "," ++ creg o ++ "," ++ creg x ++ ")"
doOp v (LExternal pk) [_, p, o] | pk == sUN "prim__peek16"
= v ++ "idris_peekB16(vm," ++ creg p ++ "," ++ creg o ++")"
doOp v (LExternal pk) [_, p, o, x] | pk == sUN "prim__poke16"
= v ++ "idris_pokeB16(" ++ creg p ++ "," ++ creg o ++ "," ++ creg x ++ ")"
doOp v (LExternal pk) [_, p, o] | pk == sUN "prim__peek32"
= v ++ "idris_peekB32(vm," ++ creg p ++ "," ++ creg o ++")"
doOp v (LExternal pk) [_, p, o, x] | pk == sUN "prim__poke32"
= v ++ "idris_pokeB32(" ++ creg p ++ "," ++ creg o ++ "," ++ creg x ++ ")"
doOp v (LExternal pk) [_, p, o] | pk == sUN "prim__peek64"
= v ++ "idris_peekB64(vm," ++ creg p ++ "," ++ creg o ++")"
doOp v (LExternal pk) [_, p, o, x] | pk == sUN "prim__poke64"
= v ++ "idris_pokeB64(" ++ creg p ++ "," ++ creg o ++ "," ++ creg x ++ ")"
doOp v (LExternal pk) [_, p, o] | pk == sUN "prim__peekPtr"
= v ++ "idris_peekPtr(vm," ++ creg p ++ "," ++ creg o ++")"
doOp v (LExternal pk) [_, p, o, x] | pk == sUN "prim__pokePtr"
= v ++ "idris_pokePtr(" ++ creg p ++ "," ++ creg o ++ "," ++ creg x ++ ")"
doOp v (LExternal pk) [_, p, o, x] | pk == sUN "prim__pokeDouble"
= v ++ "idris_pokeDouble(" ++ creg p ++ "," ++ creg o ++ "," ++ creg x ++ ")"
doOp v (LExternal pk) [_, p, o] | pk == sUN "prim__peekDouble"
= v ++ "idris_peekDouble(vm," ++ creg p ++ "," ++ creg o ++")"
doOp v (LExternal pk) [_, p, o, x] | pk == sUN "prim__pokeSingle"
= v ++ "idris_pokeSingle(" ++ creg p ++ "," ++ creg o ++ "," ++ creg x ++ ")"
doOp v (LExternal pk) [_, p, o] | pk == sUN "prim__peekSingle"
= v ++ "idris_peekSingle(vm," ++ creg p ++ "," ++ creg o ++")"
doOp v (LExternal pk) [] | pk == sUN "prim__sizeofPtr"
= v ++ "MKINT(sizeof(void*))"
doOp v (LExternal mpt) [p] | mpt == sUN "prim__asPtr"
= v ++ "MKPTR(vm, GETMPTR("++ creg p ++"))"
doOp v (LExternal offs) [p, n] | offs == sUN "prim__ptrOffset"
= v ++ "MKPTR(vm, (void *)((char *)GETPTR(" ++ creg p ++ ") + GETINT(" ++ creg n ++ ")))"
doOp _ op args = error $ "doOp not implemented (" ++ show (op, args) ++ ")"
flUnOp :: String -> String -> String
flUnOp name val = "MKFLOAT(vm, " ++ name ++ "(GETFLOAT(" ++ val ++ ")))"
-------------------- Interface file generation
-- First, the wrappers in the C file
ifaceC :: Export -> String
ifaceC (ExportData n) = "typedef VAL " ++ cdesc n ++ ";\n"
ifaceC (ExportFun n cn ret args)
= ctype ret ++ " " ++ cdesc cn ++
"(VM* vm" ++ showArgs (zip argNames args) ++ ") {\n"
++ mkBody n (zip argNames args) ret ++ "}\n\n"
where showArgs [] = ""
showArgs ((n, t) : ts) = ", " ++ ctype t ++ " " ++ n ++
showArgs ts
argNames = zipWith (++) (repeat "arg") (map show [0..])
mkBody n as t = indent 1 ++ "INITFRAME;\n" ++
indent 1 ++ "RESERVE(" ++ show (max (length as) 3) ++ ");\n" ++
push 0 as ++ call n ++ retval t
where push i [] = ""
push i ((n, t) : ts) = indent 1 ++ c_irts (toFType t)
("TOP(" ++ show i ++ ") = ") n
++ ";\n" ++ push (i + 1) ts
call _ = indent 1 ++ "STOREOLD;\n" ++
indent 1 ++ "BASETOP(0);\n" ++
indent 1 ++ "ADDTOP(" ++ show (length as) ++ ");\n" ++
indent 1 ++ "CALL(" ++ cname n ++ ");\n"
retval (FIO t)
= indent 1 ++ "TOP(0) = NULL;\n" ++
indent 1 ++ "TOP(1) = NULL;\n" ++
indent 1 ++ "TOP(2) = RVAL;\n" ++
indent 1 ++ "STOREOLD;\n" ++
indent 1 ++ "BASETOP(0);\n" ++
indent 1 ++ "ADDTOP(3);\n" ++
indent 1 ++ "CALL(" ++ cname (sUN "call__IO") ++ ");\n" ++
retval t
retval t = indent 1 ++ "return " ++ irts_c (toFType t) "RVAL" ++ ";\n"
ctype (FCon c)
| c == sUN "C_Str" = "char*"
| c == sUN "C_Float" = "float"
| c == sUN "C_Ptr" = "void*"
| c == sUN "C_MPtr" = "void*"
| c == sUN "C_Unit" = "void"
ctype (FApp c [_,ity])
| c == sUN "C_IntT" = carith ity
ctype (FApp c [_])
| c == sUN "C_Any" = "VAL"
ctype (FStr s) = s
ctype FUnknown = "void*"
ctype (FIO t) = ctype t
ctype t = error "Can't happen: Not a valid interface type " ++ show t
carith (FCon i)
| i == sUN "C_IntChar" = "char"
| i == sUN "C_IntNative" = "int"
| i == sUN "C_IntBits8" = "uint8_t"
| i == sUN "C_IntBits16" = "uint16_t"
| i == sUN "C_IntBits32" = "uint32_t"
| i == sUN "C_IntBits64" = "uint64_t"
carith t = error $ "Can't happen: Not an exportable arithmetic type " ++ show t
cdesc (FStr s) = s
cdesc s = error "Can't happen: Not a valid C name"
-- Then, the header files
codegenH :: [ExportIFace] -> IO ()
codegenH es = mapM_ writeIFace es
writeIFace :: ExportIFace -> IO ()
writeIFace (Export ffic hdr exps)
| ffic == sNS (sUN "FFI_C") ["FFI_C"]
= do let hfile = "#ifndef " ++ hdr_guard hdr ++ "\n" ++
"#define " ++ hdr_guard hdr ++ "\n\n" ++
"#include <idris_rts.h>\n\n" ++
concatMap hdr_export exps ++ "\n" ++
"#endif\n\n"
writeFile hdr hfile
| otherwise = return ()
hdr_guard x = "__" ++ map hchar x
where hchar x | isAlphaNum x = toUpper x
hchar _ = '_'
hdr_export :: Export -> String
hdr_export (ExportData n) = "typedef VAL " ++ cdesc n ++ ";\n"
hdr_export (ExportFun n cn ret args)
= ctype ret ++ " " ++ cdesc cn ++
"(VM* vm" ++ showArgs (zip argNames args) ++ ");\n"
where showArgs [] = ""
showArgs ((n, t) : ts) = ", " ++ ctype t ++ " " ++ n ++
showArgs ts
argNames = zipWith (++) (repeat "arg") (map show [0..])
------------------ Callback wrapper generation ----------------
-- Generate callback wrappers and a function to select the
-- correct wrapper function to pass.
-- TODO: This is limited to functions that are specified in
-- the foreign call. Otherwise we would have to generate wrappers for all
-- functions with correct arity or do flow analysis
-- to find all possible inputs to the foreign call.
genWrappers :: [(Name, [BC])] -> String
genWrappers bcs = let
tags = nubBy (\x y -> snd x == snd y) $ concatMap (getCallback . snd) bcs
in
case tags of
[] -> ""
t -> concatMap genWrapper t ++ genDispatcher t
genDispatcher :: [(FDesc, Int)] -> String
genDispatcher tags = "void* _idris_get_wrapper(VAL con)\n" ++
"{\n" ++
indent 1 ++ "switch(TAG(con)) {\n" ++
concatMap makeSwitch tags ++
indent 1 ++ "}\n" ++
indent 1 ++ "fprintf(stderr, \"No wrapper for callback\");\n" ++
indent 1 ++ "exit(-1);\n" ++
"}\n\n"
where
makeSwitch (_, tag) =
indent 1 ++ "case " ++ show tag ++ ":\n" ++
indent 2 ++ "return (void*) &" ++ wrapperName tag ++ ";\n"
genWrapper :: (FDesc, Int) -> String
genWrapper (desc, tag) | (toFType desc) == FFunctionIO =
error "Cannot create C callbacks for IO functions, wrap them with unsafePerformIO.\n"
genWrapper (desc, tag) = ret ++ " " ++ wrapperName tag ++ "(" ++
renderArgs argList ++")\n" ++
"{\n" ++
(if ret /= "void" then indent 1 ++ ret ++ " ret;\n" else "") ++
indent 1 ++ "VM* vm = get_vm();\n" ++
indent 1 ++ "if (vm == NULL) {\n" ++
indent 2 ++ "vm = idris_vm();\n" ++
indent 1 ++ "}\n" ++
indent 1 ++ "INITFRAME;\n" ++
indent 1 ++ "RESERVE(" ++ show (len + 1) ++ ");\n" ++
indent 1 ++ "allocCon(REG1, vm, " ++ show tag ++ ",0 , 0);\n" ++
indent 1 ++ "TOP(0) = REG1;\n" ++
applyArgs argList ++
if ret /= "void"
then indent 1 ++ "ret = " ++ irts_c (toFType ft) "RVAL" ++ ";\n"
++ indent 1 ++ "return ret;\n}\n\n"
else "}\n\n"
where
(ret, ft) = rty desc
argList = zip (args desc) [0..]
len = length argList
applyArgs (x:y:xs) = push 1 [x] ++
indent 1 ++ "STOREOLD;\n" ++
indent 1 ++ "BASETOP(0);\n" ++
indent 1 ++ "ADDTOP(2);\n" ++
indent 1 ++ "CALL(_idris__123_APPLY_95_0_125_);\n" ++
indent 1 ++ "TOP(0)=REG1;\n" ++
applyArgs (y:xs)
applyArgs x = push 1 x ++
indent 1 ++ "STOREOLD;\n" ++
indent 1 ++ "BASETOP(0);\n" ++
indent 1 ++ "ADDTOP(" ++ show (length x + 1) ++ ");\n" ++
indent 1 ++ "CALL(_idris__123_APPLY_95_0_125_);\n"
renderArgs [] = "void"
renderArgs [((s, _), n)] = s ++ " a" ++ (show n)
renderArgs (((s, _), n):xs) = s ++ " a" ++ (show n) ++ ", " ++
renderArgs xs
rty (FApp c [_,ty])
| c == sUN "C_FnBase" = (ctype ty, ty)
| c == sUN "C_FnIO" = (ctype ty, ty)
| c == sUN "C_FnT" = rty ty
rty (FApp c [_,_,ty,fn])
| c == sUN "C_Fn" = rty fn
rty x = ("", x)
args (FApp c [_,ty])
| c == sUN "C_FnBase" = []
| c == sUN "C_FnIO" = []
| c == sUN "C_FnT" = args ty
args (FApp c [_,_,ty,fn])
| toFType ty == FUnit = []
| c == sUN "C_Fn" = (ctype ty, ty) : args fn
args _ = []
push i [] = ""
push i (((c, t), n) : ts) = indent 1 ++ c_irts (toFType t)
("TOP(" ++ show i ++ ") = ") ("a" ++ show n)
++ ";\n" ++ push (i + 1) ts
wrapperName :: Int -> String
wrapperName tag = "_idris_wrapper_" ++ show tag
getCallback :: [BC] -> [(FDesc, Int)]
getCallback bc = getCallback' (reverse bc)
where
getCallback' (x:xs) = case hasCallback x of
[] -> getCallback' xs
cbs -> case findCons cbs xs of
[] -> error "Idris function couldn't be wrapped."
x -> x
getCallback' [] = []
findCons (c:cs) xs = findCon c xs ++ findCons cs xs
findCons [] _ = []
findCon c ((MKCON l loc tag args):xs) | snd c == l = [(fst c, tag)]
findCon c (_:xs) = findCon c xs
findCon c [] = []
hasCallback :: BC -> [(FDesc, Reg)]
hasCallback (FOREIGNCALL l rty (FStr fn) args) = filter isFn args
where
isFn (desc,_) = case toFType desc of
FFunction -> True
FFunctionIO -> True
_ -> False
hasCallback _ = []
| Heather/Idris-dev | src/IRTS/CodegenC.hs | bsd-3-clause | 45,557 | 0 | 33 | 14,483 | 20,039 | 9,886 | 10,153 | 883 | 31 |
{-# LANGUAGE CPP #-}
#include "fusion-phases.h"
-- | Closures.
-- Used when closure converting the source program during vectorisation.
module Data.Array.Parallel.Lifted.Closure
( -- * Closures.
(:->)(..)
, ($:)
-- * Array Closures.
, PData(..)
, ($:^), liftedApply
-- * Closure Construction.
, closure1, closure2, closure3, closure4, closure5, closure6, closure7, closure8
, closure1', closure2', closure3', closure4', closure5', closure6', closure7', closure8')
where
import Data.Array.Parallel.Pretty
import Data.Array.Parallel.PArray.PData.Base
import Data.Array.Parallel.PArray.PData.Unit
import Data.Array.Parallel.PArray.PData.Tuple2
import Data.Array.Parallel.PArray.PData.Tuple3
import Data.Array.Parallel.PArray.PData.Tuple4
import Data.Array.Parallel.PArray.PData.Tuple5
import Data.Array.Parallel.PArray.PData.Tuple6
import Data.Array.Parallel.PArray.PData.Tuple7
import Data.Array.Parallel.PArray.PRepr
import qualified Data.Typeable as T
import qualified Data.Vector as V
import GHC.Exts
-- Closures -------------------------------------------------------------------
-- | Define the fixity of the closure type constructor.
infixr 0 :->
infixl 1 $:, $:^
-- | The type of closures.
-- This bundles up:
--- 1) the 'vectorised' version of the function that takes an explicit environment
-- 2) the 'lifted' version, that works on arrays.
-- The first parameter of the lifted version is the 'lifting context'
-- that gives the length of the arrays being operated on.
-- 3) the environment of the closure.
--
-- The vectoriser closure-converts the source program so that all functions
-- are expressed in this form.
data (a :-> b)
= forall env. PA env
=> Clo (env -> a -> b)
(Int -> PData env -> PData a -> PData b)
env
deriving instance T.Typeable (:->)
-- | Closure application.
($:) :: (a :-> b) -> a -> b
($:) (Clo fv _fl env) x = fv env x
{-# INLINE_CLOSURE ($:) #-}
-- Array Closures -------------------------------------------------------------
-- | Arrays of closures (aka array closures)
-- We need to represent arrays of closures when vectorising partial applications.
--
-- For example, consider:
-- @mapP (+) xs :: [: Int -> Int :]@
--
-- Representing this an array of thunks doesn't work because we can't evaluate
-- it in a data parallel manner. Instead, we want *one* function applied to many
-- array elements.
--
-- Instead, such an array of closures is represented as the vectorised and
-- lifted versions of (+), along with an environment array xs that contains the
-- partially applied arguments.
--
-- @mapP (+) xs ==> AClo plus_v plus_l xs@
--
data instance PData (a :-> b)
= forall env. PA env
=> AClo (env -> a -> b)
(Int -> PData env -> PData a -> PData b)
(PData env)
data instance PDatas (a :-> b)
= forall env. PA env
=> AClos (env -> a -> b)
(Int -> PData env -> PData a -> PData b)
(PDatas env)
-- | Lifted closure application.
($:^) :: PArray (a :-> b) -> PArray a -> PArray b
PArray n# (AClo _ f es) $:^ PArray _ as
= PArray n# (f (I# n#) es as)
{-# INLINE ($:^) #-}
-- | Lifted closure application, taking an explicit lifting context.
liftedApply :: Int -> PData (a :-> b) -> PData a -> PData b
liftedApply n (AClo _ fl envs) as
= fl n envs as
{-# INLINE_CLOSURE liftedApply #-}
-- Closure Construction -------------------------------------------------------
-- These functions are used for building closure representations of primitive
-- functions. They're used in D.A.P.Lifted.Combinators where we define the
-- closure converted lifted array combinators that vectorised code uses.
-- | Construct an arity-1 closure,
-- from unlifted and lifted versions of a primitive function.
closure1
:: (a -> b)
-> (Int -> PData a -> PData b)
-> (a :-> b)
closure1 fv fl
= Clo (\_env -> fv)
(\n _env -> fl n)
()
{-# INLINE_CLOSURE closure1 #-}
-- | Construct an arity-2 closure,
-- from lifted and unlifted versions of a primitive function.
closure2
:: forall a b c. PA a
=> (a -> b -> c)
-> (Int -> PData a -> PData b -> PData c)
-> (a :-> b :-> c)
closure2 fv fl
= let fv_1 _ xa = Clo fv fl xa
fl_1 _ _ xs = AClo fv fl xs
in Clo fv_1 fl_1 ()
{-# INLINE_CLOSURE closure2 #-}
-- | Construct an arity-3 closure
-- from lifted and unlifted versions of a primitive function.
closure3
:: forall a b c d. (PA a, PA b)
=> (a -> b -> c -> d)
-> (Int -> PData a -> PData b -> PData c -> PData d)
-> (a :-> b :-> c :-> d)
closure3 fv fl
= let fv_1 _ xa = Clo fv_2 fl_2 xa
fl_1 _ _ xs = AClo fv_2 fl_2 xs
-----
fv_2 xa yb = Clo fv_3 fl_3 (xa, yb)
fl_2 _ xs ys = AClo fv_3 fl_3 (PTuple2 xs ys)
-----
fv_3 (xa, yb) zc = fv xa yb zc
fl_3 n (PTuple2 xs ys) zs = fl n xs ys zs
in Clo fv_1 fl_1 ()
{-# INLINE_CLOSURE closure3 #-}
-- | Construct an arity-4 closure
-- from lifted and unlifted versions of a primitive function.
closure4
:: forall a b c d e. (PA a, PA b, PA c)
=> (a -> b -> c -> d -> e)
-> (Int -> PData a -> PData b -> PData c -> PData d -> PData e)
-> (a :-> b :-> c :-> d :-> e)
closure4 fv fl
= let fv_1 _ xa = Clo fv_2 fl_2 xa
fl_1 _ _ xs = AClo fv_2 fl_2 xs
fv_2 xa yb = Clo fv_3 fl_3 (xa, yb)
fl_2 _ xs ys = AClo fv_3 fl_3 (PTuple2 xs ys)
fv_3 (xa, yb) zc = Clo fv_4 fl_4 (xa, yb, zc)
fl_3 _ (PTuple2 xs ys) zs = AClo fv_4 fl_4 (PTuple3 xs ys zs)
fv_4 (xa, yb, zc) ad = fv xa yb zc ad
fl_4 n (PTuple3 xs ys zs) as = fl n xs ys zs as
in Clo fv_1 fl_1 ()
{-# INLINE_CLOSURE closure4 #-}
-- | Construct an arity-5 closure
-- from lifted and unlifted versions of a primitive function.
closure5
:: forall a b c d e f. (PA a, PA b, PA c, PA d)
=> (a -> b -> c -> d -> e -> f)
-> (Int -> PData a -> PData b -> PData c -> PData d -> PData e -> PData f)
-> (a :-> b :-> c :-> d :-> e :-> f)
closure5 fv fl
= let fv_1 _ xa = Clo fv_2 fl_2 xa
fl_1 _ _ xs = AClo fv_2 fl_2 xs
fv_2 xa yb = Clo fv_3 fl_3 (xa, yb)
fl_2 _ xs ys = AClo fv_3 fl_3 (PTuple2 xs ys)
fv_3 (xa, yb) zc = Clo fv_4 fl_4 (xa, yb, zc)
fl_3 _ (PTuple2 xs ys) zs = AClo fv_4 fl_4 (PTuple3 xs ys zs)
fv_4 (xa, yb, zc) ad = Clo fv_5 fl_5 (xa, yb, zc, ad)
fl_4 _ (PTuple3 xs ys zs) as = AClo fv_5 fl_5 (PTuple4 xs ys zs as)
fv_5 (xa, yb, zc, ad) be = fv xa yb zc ad be
fl_5 n (PTuple4 xs ys zs as) bs = fl n xs ys zs as bs
in Clo fv_1 fl_1 ()
{-# INLINE_CLOSURE closure5 #-}
-- | Construct an arity-6 closure
-- from lifted and unlifted versions of a primitive function.
closure6
:: forall a b c d e f g. (PA a, PA b, PA c, PA d, PA e)
=> (a -> b -> c -> d -> e -> f -> g)
-> (Int -> PData a -> PData b -> PData c -> PData d -> PData e -> PData f -> PData g)
-> (a :-> b :-> c :-> d :-> e :-> f :-> g)
closure6 fv fl
= let fv_1 _ xa = Clo fv_2 fl_2 xa
fl_1 _ _ xs = AClo fv_2 fl_2 xs
fv_2 xa yb = Clo fv_3 fl_3 (xa, yb)
fl_2 _ xs ys = AClo fv_3 fl_3 (PTuple2 xs ys)
fv_3 (xa, yb) zc = Clo fv_4 fl_4 (xa, yb, zc)
fl_3 _ (PTuple2 xs ys) zs = AClo fv_4 fl_4 (PTuple3 xs ys zs)
fv_4 (wa, xb, yc) zd = Clo fv_5 fl_5 (wa, xb, yc, zd)
fl_4 _ (PTuple3 ws xs ys) zs = AClo fv_5 fl_5 (PTuple4 ws xs ys zs)
fv_5 (va, wb, xc, yd) ze = Clo fv_6 fl_6 (va, wb, xc, yd, ze)
fl_5 _ (PTuple4 vs ws xs ys) zs = AClo fv_6 fl_6 (PTuple5 vs ws xs ys zs)
fv_6 (ua, vb, wc, xd, ye) zf = fv ua vb wc xd ye zf
fl_6 n (PTuple5 us vs ws xs ys) zs = fl n us vs ws xs ys zs
in Clo fv_1 fl_1 ()
{-# INLINE_CLOSURE closure6 #-}
-- | Construct an arity-6 closure
-- from lifted and unlifted versions of a primitive function.
closure7
:: forall a b c d e f g h. (PA a, PA b, PA c, PA d, PA e, PA f)
=> (a -> b -> c -> d -> e -> f -> g -> h)
-> (Int -> PData a -> PData b -> PData c -> PData d -> PData e -> PData f -> PData g -> PData h)
-> (a :-> b :-> c :-> d :-> e :-> f :-> g :-> h)
closure7 fv fl
= let fv_1 _ xa = Clo fv_2 fl_2 xa
fl_1 _ _ xs = AClo fv_2 fl_2 xs
fv_2 xa yb = Clo fv_3 fl_3 (xa, yb)
fl_2 _ xs ys = AClo fv_3 fl_3 (PTuple2 xs ys)
fv_3 (xa, yb) zc = Clo fv_4 fl_4 (xa, yb, zc)
fl_3 _ (PTuple2 xs ys) zs = AClo fv_4 fl_4 (PTuple3 xs ys zs)
fv_4 (wa, xb, yc) zd = Clo fv_5 fl_5 (wa, xb, yc, zd)
fl_4 _ (PTuple3 ws xs ys) zs = AClo fv_5 fl_5 (PTuple4 ws xs ys zs)
fv_5 (va, wb, xc, yd) ze = Clo fv_6 fl_6 (va, wb, xc, yd, ze)
fl_5 _ (PTuple4 vs ws xs ys) zs = AClo fv_6 fl_6 (PTuple5 vs ws xs ys zs)
fv_6 (ua, vb, wc, xd, ye) zf = Clo fv_7 fl_7 (ua, vb, wc, xd, ye, zf)
fl_6 _ (PTuple5 us vs ws xs ys) zs = AClo fv_7 fl_7 (PTuple6 us vs ws xs ys zs)
fv_7 (ta, ub, vc, wd, xe, yf) zg = fv ta ub vc wd xe yf zg
fl_7 n (PTuple6 ts us vs ws xs ys) zs = fl n ts us vs ws xs ys zs
in Clo fv_1 fl_1 ()
{-# INLINE_CLOSURE closure7 #-}
-- | Construct an arity-6 closure
-- from lifted and unlifted versions of a primitive function.
closure8
:: forall a b c d e f g h i. (PA a, PA b, PA c, PA d, PA e, PA f, PA g)
=> (a -> b -> c -> d -> e -> f -> g -> h -> i)
-> (Int -> PData a -> PData b -> PData c -> PData d -> PData e -> PData f -> PData g -> PData h -> PData i)
-> (a :-> b :-> c :-> d :-> e :-> f :-> g :-> h :-> i)
closure8 fv fl
= let fv_1 _ xa = Clo fv_2 fl_2 xa
fl_1 _ _ xs = AClo fv_2 fl_2 xs
fv_2 xa yb = Clo fv_3 fl_3 (xa, yb)
fl_2 _ xs ys = AClo fv_3 fl_3 (PTuple2 xs ys)
fv_3 (xa, yb) zc = Clo fv_4 fl_4 (xa, yb, zc)
fl_3 _ (PTuple2 xs ys) zs = AClo fv_4 fl_4 (PTuple3 xs ys zs)
fv_4 (wa, xb, yc) zd = Clo fv_5 fl_5 (wa, xb, yc, zd)
fl_4 _ (PTuple3 ws xs ys) zs = AClo fv_5 fl_5 (PTuple4 ws xs ys zs)
fv_5 (va, wb, xc, yd) ze = Clo fv_6 fl_6 (va, wb, xc, yd, ze)
fl_5 _ (PTuple4 vs ws xs ys) zs = AClo fv_6 fl_6 (PTuple5 vs ws xs ys zs)
fv_6 (ua, vb, wc, xd, ye) zf = Clo fv_7 fl_7 (ua, vb, wc, xd, ye, zf)
fl_6 _ (PTuple5 us vs ws xs ys) zs = AClo fv_7 fl_7 (PTuple6 us vs ws xs ys zs)
fv_7 (ta, ub, vc, wd, xe, yf) zg = Clo fv_8 fl_8 (ta, ub, vc, wd, xe, yf, zg)
fl_7 _ (PTuple6 ts us vs ws xs ys) zs = AClo fv_8 fl_8 (PTuple7 ts us vs ws xs ys zs)
fv_8 (sa, tb, uc, vd, we, xf, yg) zh = fv sa tb uc vd we xf yg zh
fl_8 n (PTuple7 ss ts us vs ws xs ys) zs = fl n ss ts us vs ws xs ys zs
in Clo fv_1 fl_1 ()
{-# INLINE_CLOSURE closure8 #-}
-- Closure constructors that take PArrays -------------------------------------
-- These versions are useful when defining prelude functions such as in
-- D.A.P.Prelude.Int. They let us promote functions that work on PArrays
-- to closures, while inferring the lifting context from the first argument.
-- | Construct an arity-1 closure.
closure1'
:: forall a b
. (a -> b)
-> (PArray a -> PArray b)
-> (a :-> b)
closure1' fv fl
= let {-# INLINE fl' #-}
fl' (I# n#) pdata
= case fl (PArray n# pdata) of
PArray _ pdata' -> pdata'
in closure1 fv fl'
{-# INLINE_CLOSURE closure1' #-}
-- | Construct an arity-2 closure.
closure2'
:: forall a b c. PA a
=> (a -> b -> c)
-> (PArray a -> PArray b -> PArray c)
-> (a :-> b :-> c)
closure2' fv fl
= let {-# INLINE fl' #-}
fl' (I# n#) !pdata1 !pdata2
= case fl (PArray n# pdata1) (PArray n# pdata2) of
PArray _ pdata' -> pdata'
in closure2 fv fl'
{-# INLINE_CLOSURE closure2' #-}
-- | Construct an arity-3 closure.
closure3'
:: forall a b c d. (PA a, PA b)
=> (a -> b -> c -> d)
-> (PArray a -> PArray b -> PArray c -> PArray d)
-> (a :-> b :-> c :-> d)
closure3' fv fl
= let {-# INLINE fl' #-}
fl' (I# n#) !pdata1 !pdata2 !pdata3
= case fl (PArray n# pdata1) (PArray n# pdata2) (PArray n# pdata3) of
PArray _ pdata' -> pdata'
in closure3 fv fl'
{-# INLINE_CLOSURE closure3' #-}
-- | Construct an arity-4 closure.
closure4'
:: forall a b c d e. (PA a, PA b, PA c)
=> (a -> b -> c -> d -> e)
-> (PArray a -> PArray b -> PArray c -> PArray d -> PArray e)
-> (a :-> b :-> c :-> d :-> e)
closure4' fv fl
= let {-# INLINE fl' #-}
fl' (I# n#) !pdata1 !pdata2 !pdata3 !pdata4
= case fl (PArray n# pdata1) (PArray n# pdata2)
(PArray n# pdata3) (PArray n# pdata4) of
PArray _ pdata' -> pdata'
in closure4 fv fl'
{-# INLINE_CLOSURE closure4' #-}
-- | Construct an arity-5 closure.
closure5'
:: forall a b c d e f. (PA a, PA b, PA c, PA d)
=> (a -> b -> c -> d -> e -> f)
-> (PArray a -> PArray b -> PArray c -> PArray d -> PArray e -> PArray f)
-> (a :-> b :-> c :-> d :-> e :-> f)
closure5' fv fl
= let {-# INLINE fl' #-}
fl' (I# n#) !pdata1 !pdata2 !pdata3 !pdata4 !pdata5
= case fl (PArray n# pdata1) (PArray n# pdata2)
(PArray n# pdata3) (PArray n# pdata4)
(PArray n# pdata5) of
PArray _ pdata' -> pdata'
in closure5 fv fl'
{-# INLINE_CLOSURE closure5' #-}
-- | Construct an arity-6 closure.
closure6'
:: forall a b c d e f g. (PA a, PA b, PA c, PA d, PA e, PA f)
=> (a -> b -> c -> d -> e -> f -> g)
-> (PArray a -> PArray b -> PArray c -> PArray d -> PArray e -> PArray f -> PArray g)
-> (a :-> b :-> c :-> d :-> e :-> f :-> g)
closure6' fv fl
= let {-# INLINE fl' #-}
fl' (I# n#) !pdata1 !pdata2 !pdata3 !pdata4 !pdata5 !pdata6
= case fl (PArray n# pdata1) (PArray n# pdata2) (PArray n# pdata3) (PArray n# pdata4) (PArray n# pdata5) (PArray n# pdata6) of
PArray _ pdata' -> pdata'
in closure6 fv fl'
{-# INLINE_CLOSURE closure6' #-}
-- | Construct an arity-7 closure.
closure7'
:: forall a b c d e f g h. (PA a, PA b, PA c, PA d, PA e, PA f, PA g)
=> (a -> b -> c -> d -> e -> f -> g -> h)
-> (PArray a -> PArray b -> PArray c -> PArray d -> PArray e -> PArray f -> PArray g -> PArray h)
-> (a :-> b :-> c :-> d :-> e :-> f :-> g :-> h)
closure7' fv fl
= let {-# INLINE fl' #-}
fl' (I# n#) !pdata1 !pdata2 !pdata3 !pdata4 !pdata5 !pdata6 !pdata7
= case fl (PArray n# pdata1) (PArray n# pdata2) (PArray n# pdata3) (PArray n# pdata4)
(PArray n# pdata5) (PArray n# pdata6) (PArray n# pdata7) of
PArray _ pdata' -> pdata'
in closure7 fv fl'
{-# INLINE_CLOSURE closure7' #-}
-- | Construct an arity-8 closure.
closure8'
:: forall a b c d e f g h i. (PA a, PA b, PA c, PA d, PA e, PA f, PA g, PA h)
=> (a -> b -> c -> d -> e -> f -> g -> h -> i)
-> (PArray a -> PArray b -> PArray c -> PArray d -> PArray e -> PArray f ->
PArray g -> PArray h -> PArray i)
-> (a :-> b :-> c :-> d :-> e :-> f :-> g :-> h :-> i)
closure8' fv fl
= let {-# INLINE fl' #-}
fl' (I# n#) !pdata1 !pdata2 !pdata3 !pdata4 !pdata5 !pdata6 !pdata7 !pdata8
= case fl (PArray n# pdata1) (PArray n# pdata2) (PArray n# pdata3) (PArray n# pdata4)
(PArray n# pdata5) (PArray n# pdata6) (PArray n# pdata7) (PArray n# pdata8) of
PArray _ pdata' -> pdata'
in closure8 fv fl'
{-# INLINE_CLOSURE closure8' #-}
-- PData instance for closures ------------------------------------------------
-- This needs to be here instead of in a module D.A.P.PArray.PData.Closure
-- to break an import loop.
-- We use INLINE_CLOSURE for these bindings instead of INLINE_PDATA because
-- most of the functions return closure constructors, and we want to eliminate
-- these early in the compilation.
--
instance PR (a :-> b) where
{-# NOINLINE validPR #-}
validPR (AClo _ _ env)
= validPA env
{-# NOINLINE nfPR #-}
nfPR (AClo fv fl envs)
= fv `seq` fl `seq` nfPA envs `seq` ()
-- We can't test functions for equality.
-- We can't test the environments either, because they're existentially quantified.
-- Provided the closures have the same type, we just call them similar.
{-# NOINLINE similarPR #-}
similarPR _ _
= True
{-# NOINLINE coversPR #-}
coversPR weak (AClo _ _ envs) ix
= coversPA weak envs ix
{-# NOINLINE pprpPR #-}
pprpPR (Clo _ _ env)
= vcat
[ text "Clo"
, pprpPA env ]
{-# NOINLINE pprpDataPR #-}
pprpDataPR (AClo _ _ envs)
= vcat
[ text "AClo"
, pprpDataPA envs ]
{-# NOINLINE typeRepPR #-}
typeRepPR (Clo _ _ env)
= typeRepPA env
{-# NOINLINE typeRepDataPR #-}
typeRepDataPR (AClo _ _ envs)
= typeRepDataPA envs
-- Constructors -------------------------------
{-# INLINE_CLOSURE emptyPR #-}
emptyPR
= let die = error "emptydPR[:->]: no function in empty closure array"
in AClo die die (emptyPA :: PData ())
{-# INLINE_CLOSURE replicatePR #-}
replicatePR n (Clo fv fl envs)
= AClo fv fl (replicatePA n envs)
{-# INLINE_CLOSURE replicatesPR #-}
replicatesPR lens (AClo fv fl envs)
= AClo fv fl (replicatesPA lens envs)
-- Projections --------------------------------
{-# INLINE_CLOSURE lengthPR #-}
lengthPR (AClo _ _ envs)
= lengthPA envs
{-# INLINE_CLOSURE indexPR #-}
indexPR (AClo fv fl envs) ix
= Clo fv fl $ indexPA envs ix
{-# INLINE_CLOSURE indexsPR #-}
indexsPR (AClos fv fl envs) srcixs
= AClo fv fl $ indexsPA envs srcixs
{-# INLINE_CLOSURE extractPR #-}
extractPR (AClo fv fl envs) start len
= AClo fv fl $ extractPA envs start len
{-# INLINE_CLOSURE extractssPR #-}
extractssPR (AClos fv fl envs) ssegd
= AClo fv fl $ extractssPA envs ssegd
{-# INLINE_CLOSURE extractvsPR #-}
extractvsPR (AClos fv fl envs) vsegd
= AClo fv fl $ extractvsPA envs vsegd
-- Pack and Combine ---------------------------
{-# INLINE_CLOSURE packByTagPR #-}
packByTagPR (AClo fv fl envs) tags tag
= AClo fv fl $ packByTagPA envs tags tag
-- Conversions --------------------------------
{-# NOINLINE toVectorPR #-}
toVectorPR (AClo fv fl envs)
= V.map (Clo fv fl) $ toVectorPA envs
-- PDatas -------------------------------------
-- When constructing an empty array of closures, we don't know what
{-# INLINE_CLOSURE emptydPR #-}
emptydPR
= let die = error "emptydPR[:->]: no function in empty closure array"
in AClos die die (emptydPA :: PDatas ())
{-# INLINE_CLOSURE singletondPR #-}
singletondPR (AClo fv fl env)
= AClos fv fl $ singletondPA env
{-# INLINE_CLOSURE lengthdPR #-}
lengthdPR (AClos _ _ env)
= lengthdPA env
{-# INLINE_CLOSURE indexdPR #-}
indexdPR (AClos fv fl envs) ix
= AClo fv fl $ indexdPA envs ix
{-# NOINLINE toVectordPR #-}
toVectordPR (AClos fv fl envs)
= V.map (AClo fv fl) $ toVectordPA envs
-- Unsupported --------------------------------
-- To support these operators we'd need to manage closure arrays containing
-- multiple hetrogenous functions. But this is more work than we care for
-- right now. Note that the problematic functions are all constructors, and
-- we can't know that all the parameters contain the same function.
appendPR = dieHetroFunctions "appendPR"
appendvsPR = dieHetroFunctions "appendsPR"
combine2PR = dieHetroFunctions "combine2PR"
fromVectorPR = dieHetroFunctions "fromVectorPR"
appenddPR = dieHetroFunctions "appenddPR"
fromVectordPR = dieHetroFunctions "fromVectordPR"
dieHetroFunctions :: String -> a
dieHetroFunctions name
= error $ unlines
[ "Data.Array.Parallel.Lifted.Closure." ++ name
, " Unsupported Array Operation"
, " It looks like you're trying to define an array containing multiple"
, " hetrogenous functions, or trying to select between multiple arrays"
, " of functions in vectorised code. Although we could support this by"
, " constructing a new function that selects between them depending on"
, " what the array index is, to make that anywhere near efficient is"
, " more work than we care to do right now, and we expect this use case"
, " to be uncommon. If you want this to work then contact the DPH team"
, " and ask what you can do to help." ]
-- PRepr Instance -------------------------------------------------------------
-- This needs to be here instead of in D.A.P.PRepr.Instances
-- to break an import loop.
--
type instance PRepr (a :-> b)
= a :-> b
instance (PA a, PA b) => PA (a :-> b) where
toPRepr = id
fromPRepr = id
toArrPRepr = id
fromArrPRepr = id
toArrPReprs = id
fromArrPReprs = id
| mainland/dph | dph-lifted-vseg/Data/Array/Parallel/Lifted/Closure.hs | bsd-3-clause | 22,151 | 6 | 19 | 7,072 | 7,113 | 3,711 | 3,402 | -1 | -1 |
{-# LANGUAGE ExistentialQuantification, TypeFamilies, ParallelListComp, ScopedTypeVariables
#-}
-- | This module contains convenience functions for building deep embedding entities.
module Language.KansasLava.Entity where
import Language.KansasLava.Rep
import Language.KansasLava.Types
-- | A zero-input Entity.
entity0 :: forall o . (Rep o) => Id -> D o
entity0 nm = D $ Port "o0" $ E $
Entity nm [("o0",oTy)]
[]
where oTy = repType (Witness :: Witness o)
-- | A one-input Entity
entity1 :: forall a o . (Rep a, Rep o) => Id -> D a -> D o
entity1 nm (D w1) = D $ Port "o0" $ E $
Entity nm [("o0",oTy)]
[(inp,ty,val) | inp <- ["i0","i1"]
| ty <- [aTy]
| val <- [w1]
]
where aTy = repType (Witness :: Witness a)
oTy = repType (Witness :: Witness o)
-- | A two-input entity.
entity2 :: forall a b o . (Rep a, Rep b, Rep o) => Id -> D a -> D b -> D o
entity2 nm (D w1) (D w2) = D $ Port "o0" $ E $
Entity nm [("o0",oTy)]
[(inp,ty,val) | inp <- ["i0","i1"]
| ty <- [aTy,bTy]
| val <- [w1,w2]
]
where aTy = repType (Witness :: Witness a)
bTy = repType (Witness :: Witness b)
oTy = repType (Witness :: Witness o)
-- | A three-input entity.
entity3 :: forall a b c o . (Rep a, Rep b, Rep c, Rep o) => Id -> D a -> D b -> D c -> D o
entity3 nm (D w1) (D w2) (D w3) = D $ Port "o0" $ E $
Entity nm [("o0",oTy)]
[(inp,ty,val) | inp <- ["i0","i1","i2"]
| ty <- [aTy,bTy,cTy]
| val <- [w1,w2,w3]
]
where aTy = repType (Witness :: Witness a)
bTy = repType (Witness :: Witness b)
cTy = repType (Witness :: Witness c)
oTy = repType (Witness :: Witness o)
-- | An n-ary entity, with all of the inputs having the same type, passed in as a list.
entityN :: forall a o . (Rep a, Rep o) => Id -> [D a] -> D o
entityN nm ds = D $ Port "o0" $ E $
Entity nm [("o0",oTy)]
[(inp,ty,val) | inp <- ['i':show (n::Int) | n <- [0..]]
| ty <- repeat aTy
| val <- [w | D w <- ds]
]
where aTy = repType (Witness :: Witness a)
oTy = repType (Witness :: Witness o)
| andygill/kansas-lava | Language/KansasLava/Entity.hs | bsd-3-clause | 2,093 | 40 | 13 | 565 | 995 | 543 | 452 | 44 | 1 |
module Reddit.Routes
( module Routes ) where
import Reddit.Routes.Captcha as Routes
import Reddit.Routes.Comment as Routes
import Reddit.Routes.Flair as Routes
import Reddit.Routes.Message as Routes
import Reddit.Routes.Post as Routes
import Reddit.Routes.Subreddit as Routes
import Reddit.Routes.Thing as Routes
import Reddit.Routes.User as Routes
import Reddit.Routes.Vote as Routes
import Reddit.Routes.Wiki as Routes
| intolerable/reddit | src/Reddit/Routes.hs | bsd-2-clause | 424 | 0 | 4 | 50 | 92 | 68 | 24 | 12 | 0 |
{-# LANGUAGE PatternGuards #-}
module Main where
import System.IO
import GHC
import MonadUtils
import Outputable
import Bag (filterBag,isEmptyBag)
import System.Directory (removeFile)
import System.Environment( getArgs )
main::IO()
main = do
let c="module Test where\ndata DataT=MkData {name :: String}\n"
writeFile "Test.hs" c
[libdir] <- getArgs
ok<- runGhc (Just libdir) $ do
dflags <- getSessionDynFlags
setSessionDynFlags dflags
let mn =mkModuleName "Test"
addTarget Target { targetId = TargetModule mn, targetAllowObjCode = True, targetContents = Nothing }
load LoadAllTargets
modSum <- getModSummary mn
p <- parseModule modSum
t <- typecheckModule p
d <- desugarModule t
l <- loadModule d
let ts=typecheckedSource l
-- liftIO (putStr (showSDocDebug (ppr ts)))
let fs=filterBag (isDataCon . snd) ts
return $ not $ isEmptyBag fs
removeFile "Test.hs"
print ok
where
isDataCon (L _ (AbsBinds { abs_binds = bs }))
= not (isEmptyBag (filterBag (isDataCon . snd) bs))
isDataCon (L l (f@FunBind {}))
| (MG (m:_) _ _) <- fun_matches f,
(L _ (c@ConPatOut{}):_)<-hsLMatchPats m,
(L l _)<-pat_con c
= isGoodSrcSpan l -- Check that the source location is a good one
isDataCon _
= False
| lukexi/ghc-7.8-arm64 | testsuite/tests/ghc-api/T6145.hs | bsd-3-clause | 1,649 | 0 | 16 | 644 | 456 | 223 | 233 | 39 | 3 |
{-# LANGUAGE DeriveDataTypeable #-}
-- | A module to deal with verbosity, how \'chatty\' a program should be.
-- This module defines the 'Verbosity' data type, along with functions
-- for manipulating a global verbosity value.
module System.Console.CmdArgs.Verbosity(
Verbosity(..), setVerbosity, getVerbosity,
isNormal, isLoud,
whenNormal, whenLoud
) where
import Control.Monad
import Data.Data
import Data.IORef
import System.IO.Unsafe
-- | The verbosity data type
data Verbosity
= Quiet -- ^ Only output essential messages (typically errors)
| Normal -- ^ Output normal messages (typically errors and warnings)
| Loud -- ^ Output lots of messages (typically errors, warnings and status updates)
deriving (Eq,Ord,Bounded,Enum,Show,Read,Data,Typeable)
{-# NOINLINE ref #-}
ref :: IORef Verbosity
ref = unsafePerformIO $ newIORef Normal
-- | Set the global verbosity.
setVerbosity :: Verbosity -> IO ()
setVerbosity = writeIORef ref
-- | Get the global verbosity. Initially @Normal@ before any calls to 'setVerbosity'.
getVerbosity :: IO Verbosity
getVerbosity = readIORef ref
-- | Used to test if warnings should be output to the user.
-- @True@ if the verbosity is set to 'Normal' or 'Loud' (when @--quiet@ is /not/ specified).
isNormal :: IO Bool
isNormal = fmap (>=Normal) getVerbosity
-- | Used to test if status updates should be output to the user.
-- @True@ if the verbosity is set to 'Loud' (when @--verbose@ is specified).
isLoud :: IO Bool
isLoud = fmap (>=Loud) getVerbosity
-- | An action to perform if the verbosity is normal or higher, based on 'isNormal'.
whenNormal :: IO () -> IO ()
whenNormal act = do
b <- isNormal
when b act
-- | An action to perform if the verbosity is loud, based on 'isLoud'.
whenLoud :: IO () -> IO ()
whenLoud act = do
b <- isLoud
when b act
| copland/cmdargs | System/Console/CmdArgs/Verbosity.hs | bsd-3-clause | 1,863 | 0 | 7 | 367 | 307 | 171 | 136 | 33 | 1 |
--------------------------------------------------------------------------------
module Hakyll.Core.Runtime
( run
) where
--------------------------------------------------------------------------------
import Control.Applicative ((<$>))
import Control.Monad (unless)
import Control.Monad.Error (ErrorT, runErrorT, throwError)
import Control.Monad.Reader (ask)
import Control.Monad.RWS (RWST, runRWST)
import Control.Monad.State (get, modify)
import Control.Monad.Trans (liftIO)
import Data.List (intercalate)
import Data.Map (Map)
import qualified Data.Map as M
import Data.Monoid (mempty)
import Data.Set (Set)
import qualified Data.Set as S
import System.Exit (ExitCode (..))
import System.FilePath ((</>))
--------------------------------------------------------------------------------
import Hakyll.Core.Compiler.Internal
import Hakyll.Core.Compiler.Require
import Hakyll.Core.Configuration
import Hakyll.Core.Dependencies
import Hakyll.Core.Identifier
import Hakyll.Core.Item
import Hakyll.Core.Item.SomeItem
import Hakyll.Core.Logger (Logger)
import qualified Hakyll.Core.Logger as Logger
import Hakyll.Core.Provider
import Hakyll.Core.Routes
import Hakyll.Core.Rules.Internal
import Hakyll.Core.Store (Store)
import qualified Hakyll.Core.Store as Store
import Hakyll.Core.Util.File
import Hakyll.Core.Writable
--------------------------------------------------------------------------------
run :: Configuration -> Logger -> Rules a -> IO (ExitCode, RuleSet)
run config logger rules = do
-- Initialization
Logger.header logger "Initialising..."
Logger.message logger "Creating store..."
store <- Store.new (inMemoryCache config) $ storeDirectory config
Logger.message logger "Creating provider..."
provider <- newProvider store (shouldIgnoreFile config) $
providerDirectory config
Logger.message logger "Running rules..."
ruleSet <- runRules rules provider
-- Get old facts
mOldFacts <- Store.get store factsKey
let (oldFacts) = case mOldFacts of Store.Found f -> f
_ -> mempty
-- Build runtime read/state
let compilers = rulesCompilers ruleSet
read' = RuntimeRead
{ runtimeConfiguration = config
, runtimeLogger = logger
, runtimeProvider = provider
, runtimeStore = store
, runtimeRoutes = rulesRoutes ruleSet
, runtimeUniverse = M.fromList compilers
}
state = RuntimeState
{ runtimeDone = S.empty
, runtimeSnapshots = S.empty
, runtimeTodo = M.empty
, runtimeFacts = oldFacts
}
-- Run the program and fetch the resulting state
result <- runErrorT $ runRWST build read' state
case result of
Left e -> do
Logger.error logger e
Logger.flush logger
return (ExitFailure 1, ruleSet)
Right (_, s, _) -> do
Store.set store factsKey $ runtimeFacts s
Logger.debug logger "Removing tmp directory..."
removeDirectory $ tmpDirectory config
Logger.flush logger
return (ExitSuccess, ruleSet)
where
factsKey = ["Hakyll.Core.Runtime.run", "facts"]
--------------------------------------------------------------------------------
data RuntimeRead = RuntimeRead
{ runtimeConfiguration :: Configuration
, runtimeLogger :: Logger
, runtimeProvider :: Provider
, runtimeStore :: Store
, runtimeRoutes :: Routes
, runtimeUniverse :: Map Identifier (Compiler SomeItem)
}
--------------------------------------------------------------------------------
data RuntimeState = RuntimeState
{ runtimeDone :: Set Identifier
, runtimeSnapshots :: Set (Identifier, Snapshot)
, runtimeTodo :: Map Identifier (Compiler SomeItem)
, runtimeFacts :: DependencyFacts
}
--------------------------------------------------------------------------------
type Runtime a = RWST RuntimeRead () RuntimeState (ErrorT String IO) a
--------------------------------------------------------------------------------
build :: Runtime ()
build = do
logger <- runtimeLogger <$> ask
Logger.header logger "Checking for out-of-date items"
scheduleOutOfDate
Logger.header logger "Compiling"
pickAndChase
Logger.header logger "Success"
--------------------------------------------------------------------------------
scheduleOutOfDate :: Runtime ()
scheduleOutOfDate = do
logger <- runtimeLogger <$> ask
provider <- runtimeProvider <$> ask
universe <- runtimeUniverse <$> ask
facts <- runtimeFacts <$> get
todo <- runtimeTodo <$> get
let identifiers = M.keys universe
modified = S.fromList $ flip filter identifiers $
resourceModified provider
let (ood, facts', msgs) = outOfDate identifiers modified facts
todo' = M.filterWithKey
(\id' _ -> id' `S.member` ood) universe
-- Print messages
mapM_ (Logger.debug logger) msgs
-- Update facts and todo items
modify $ \s -> s
{ runtimeDone = runtimeDone s `S.union`
(S.fromList identifiers `S.difference` ood)
, runtimeTodo = todo `M.union` todo'
, runtimeFacts = facts'
}
--------------------------------------------------------------------------------
pickAndChase :: Runtime ()
pickAndChase = do
todo <- runtimeTodo <$> get
case M.minViewWithKey todo of
Nothing -> return ()
Just ((id', _), _) -> do
chase [] id'
pickAndChase
--------------------------------------------------------------------------------
chase :: [Identifier] -> Identifier -> Runtime ()
chase trail id'
| id' `elem` trail = throwError $ "Hakyll.Core.Runtime.chase: " ++
"Dependency cycle detected: " ++ intercalate " depends on "
(map show $ dropWhile (/= id') (reverse trail) ++ [id'])
| otherwise = do
logger <- runtimeLogger <$> ask
todo <- runtimeTodo <$> get
provider <- runtimeProvider <$> ask
universe <- runtimeUniverse <$> ask
routes <- runtimeRoutes <$> ask
store <- runtimeStore <$> ask
config <- runtimeConfiguration <$> ask
Logger.debug logger $ "Processing " ++ show id'
let compiler = todo M.! id'
read' = CompilerRead
{ compilerConfig = config
, compilerUnderlying = id'
, compilerProvider = provider
, compilerUniverse = M.keysSet universe
, compilerRoutes = routes
, compilerStore = store
, compilerLogger = logger
}
result <- liftIO $ runCompiler compiler read'
case result of
-- Rethrow error
CompilerError [] -> throwError
"Compiler failed but no info given, try running with -v?"
CompilerError es -> throwError $ intercalate "; " es
-- Signal that a snapshot was saved ->
CompilerSnapshot snapshot c -> do
-- Update info. The next 'chase' will pick us again at some
-- point so we can continue then.
modify $ \s -> s
{ runtimeSnapshots =
S.insert (id', snapshot) (runtimeSnapshots s)
, runtimeTodo = M.insert id' c (runtimeTodo s)
}
-- Huge success
CompilerDone (SomeItem item) cwrite -> do
-- Print some info
let facts = compilerDependencies cwrite
cacheHits
| compilerCacheHits cwrite <= 0 = "updated"
| otherwise = "cached "
Logger.message logger $ cacheHits ++ " " ++ show id'
-- Sanity check
unless (itemIdentifier item == id') $ throwError $
"The compiler yielded an Item with Identifier " ++
show (itemIdentifier item) ++ ", but we were expecting " ++
"an Item with Identifier " ++ show id' ++ " " ++
"(you probably want to call makeItem to solve this problem)"
-- Write if necessary
(mroute, _) <- liftIO $ runRoutes routes provider id'
case mroute of
Nothing -> return ()
Just route -> do
let path = destinationDirectory config </> route
liftIO $ makeDirectories path
liftIO $ write path item
Logger.debug logger $ "Routed to " ++ path
-- Save! (For load)
liftIO $ save store item
-- Update state
modify $ \s -> s
{ runtimeDone = S.insert id' (runtimeDone s)
, runtimeTodo = M.delete id' (runtimeTodo s)
, runtimeFacts = M.insert id' facts (runtimeFacts s)
}
-- Try something else first
CompilerRequire dep c -> do
-- Update the compiler so we don't execute it twice
let (depId, depSnapshot) = dep
done <- runtimeDone <$> get
snapshots <- runtimeSnapshots <$> get
-- Done if we either completed the entire item (runtimeDone) or
-- if we previously saved the snapshot (runtimeSnapshots).
let depDone =
depId `S.member` done ||
(depId, depSnapshot) `S.member` snapshots
modify $ \s -> s
{ runtimeTodo = M.insert id'
(if depDone then c else compilerResult result)
(runtimeTodo s)
}
-- If the required item is already compiled, continue, or, start
-- chasing that
Logger.debug logger $ "Require " ++ show depId ++
" (snapshot " ++ depSnapshot ++ "): " ++
(if depDone then "OK" else "chasing")
if depDone then chase trail id' else chase (id' : trail) depId
| Minoru/hakyll | src/Hakyll/Core/Runtime.hs | bsd-3-clause | 11,108 | 0 | 24 | 4,036 | 2,238 | 1,177 | 1,061 | 192 | 9 |
{-# LANGUAGE DeriveDataTypeable, MagicHash, PolymorphicComponents, RoleAnnotations, UnboxedTuples #-}
-----------------------------------------------------------------------------
-- |
-- Module : Language.Haskell.Syntax
-- Copyright : (c) The University of Glasgow 2003
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Abstract syntax definitions for Template Haskell.
--
-----------------------------------------------------------------------------
module Language.Haskell.TH.Syntax where
import GHC.Exts
import Data.Data (Data(..), Typeable, mkConstr, mkDataType, constrIndex)
import qualified Data.Data as Data
import Control.Applicative( Applicative(..) )
import Data.IORef
import System.IO.Unsafe ( unsafePerformIO )
import Control.Monad (liftM)
import System.IO ( hPutStrLn, stderr )
import Data.Char ( isAlpha, isAlphaNum, isUpper )
import Data.Word ( Word8 )
-----------------------------------------------------
--
-- The Quasi class
--
-----------------------------------------------------
class (Monad m, Applicative m) => Quasi m where
qNewName :: String -> m Name
-- ^ Fresh names
-- Error reporting and recovery
qReport :: Bool -> String -> m () -- ^ Report an error (True) or warning (False)
-- ...but carry on; use 'fail' to stop
qRecover :: m a -- ^ the error handler
-> m a -- ^ action which may fail
-> m a -- ^ Recover from the monadic 'fail'
-- Inspect the type-checker's environment
qLookupName :: Bool -> String -> m (Maybe Name)
-- True <=> type namespace, False <=> value namespace
qReify :: Name -> m Info
qReifyInstances :: Name -> [Type] -> m [Dec]
-- Is (n tys) an instance?
-- Returns list of matching instance Decs
-- (with empty sub-Decs)
-- Works for classes and type functions
qReifyRoles :: Name -> m [Role]
qReifyAnnotations :: Data a => AnnLookup -> m [a]
qReifyModule :: Module -> m ModuleInfo
qLocation :: m Loc
qRunIO :: IO a -> m a
-- ^ Input/output (dangerous)
qAddDependentFile :: FilePath -> m ()
qAddTopDecls :: [Dec] -> m ()
qAddModFinalizer :: Q () -> m ()
qGetQ :: Typeable a => m (Maybe a)
qPutQ :: Typeable a => a -> m ()
-----------------------------------------------------
-- The IO instance of Quasi
--
-- This instance is used only when running a Q
-- computation in the IO monad, usually just to
-- print the result. There is no interesting
-- type environment, so reification isn't going to
-- work.
--
-----------------------------------------------------
instance Quasi IO where
qNewName s = do { n <- readIORef counter
; writeIORef counter (n+1)
; return (mkNameU s n) }
qReport True msg = hPutStrLn stderr ("Template Haskell error: " ++ msg)
qReport False msg = hPutStrLn stderr ("Template Haskell error: " ++ msg)
qLookupName _ _ = badIO "lookupName"
qReify _ = badIO "reify"
qReifyInstances _ _ = badIO "reifyInstances"
qReifyRoles _ = badIO "reifyRoles"
qReifyAnnotations _ = badIO "reifyAnnotations"
qReifyModule _ = badIO "reifyModule"
qLocation = badIO "currentLocation"
qRecover _ _ = badIO "recover" -- Maybe we could fix this?
qAddDependentFile _ = badIO "addDependentFile"
qAddTopDecls _ = badIO "addTopDecls"
qAddModFinalizer _ = badIO "addModFinalizer"
qGetQ = badIO "getQ"
qPutQ _ = badIO "putQ"
qRunIO m = m
badIO :: String -> IO a
badIO op = do { qReport True ("Can't do `" ++ op ++ "' in the IO monad")
; fail "Template Haskell failure" }
-- Global variable to generate unique symbols
counter :: IORef Int
{-# NOINLINE counter #-}
counter = unsafePerformIO (newIORef 0)
-----------------------------------------------------
--
-- The Q monad
--
-----------------------------------------------------
newtype Q a = Q { unQ :: forall m. Quasi m => m a }
-- \"Runs\" the 'Q' monad. Normal users of Template Haskell
-- should not need this function, as the splice brackets @$( ... )@
-- are the usual way of running a 'Q' computation.
--
-- This function is primarily used in GHC internals, and for debugging
-- splices by running them in 'IO'.
--
-- Note that many functions in 'Q', such as 'reify' and other compiler
-- queries, are not supported when running 'Q' in 'IO'; these operations
-- simply fail at runtime. Indeed, the only operations guaranteed to succeed
-- are 'newName', 'runIO', 'reportError' and 'reportWarning'.
runQ :: Quasi m => Q a -> m a
runQ (Q m) = m
instance Monad Q where
return x = Q (return x)
Q m >>= k = Q (m >>= \x -> unQ (k x))
Q m >> Q n = Q (m >> n)
fail s = report True s >> Q (fail "Q monad failure")
instance Functor Q where
fmap f (Q x) = Q (fmap f x)
instance Applicative Q where
pure x = Q (pure x)
Q f <*> Q x = Q (f <*> x)
-----------------------------------------------------
--
-- The TExp type
--
-----------------------------------------------------
type role TExp nominal -- See Note [Role of TExp]
newtype TExp a = TExp { unType :: Exp }
unTypeQ :: Q (TExp a) -> Q Exp
unTypeQ m = do { TExp e <- m
; return e }
unsafeTExpCoerce :: Q Exp -> Q (TExp a)
unsafeTExpCoerce m = do { e <- m
; return (TExp e) }
{- Note [Role of TExp]
~~~~~~~~~~~~~~~~~~~~~~
TExp's argument must have a nominal role, not phantom as would
be inferred (Trac #8459). Consider
e :: TExp Age
e = MkAge 3
foo = $(coerce e) + 4::Int
The splice will evaluate to (MkAge 3) and you can't add that to
4::Int. So you can't coerce a (TExp Age) to a (TExp Int). -}
----------------------------------------------------
-- Packaged versions for the programmer, hiding the Quasi-ness
{- |
Generate a fresh name, which cannot be captured.
For example, this:
@f = $(do
nm1 <- newName \"x\"
let nm2 = 'mkName' \"x\"
return ('LamE' ['VarP' nm1] (LamE [VarP nm2] ('VarE' nm1)))
)@
will produce the splice
>f = \x0 -> \x -> x0
In particular, the occurrence @VarE nm1@ refers to the binding @VarP nm1@,
and is not captured by the binding @VarP nm2@.
Although names generated by @newName@ cannot /be captured/, they can
/capture/ other names. For example, this:
>g = $(do
> nm1 <- newName "x"
> let nm2 = mkName "x"
> return (LamE [VarP nm2] (LamE [VarP nm1] (VarE nm2)))
> )
will produce the splice
>g = \x -> \x0 -> x0
since the occurrence @VarE nm2@ is captured by the innermost binding
of @x@, namely @VarP nm1@.
-}
newName :: String -> Q Name
newName s = Q (qNewName s)
-- | Report an error (True) or warning (False),
-- but carry on; use 'fail' to stop.
report :: Bool -> String -> Q ()
report b s = Q (qReport b s)
{-# DEPRECATED report "Use reportError or reportWarning instead" #-} -- deprecated in 7.6
-- | Report an error to the user, but allow the current splice's computation to carry on. To abort the computation, use 'fail'.
reportError :: String -> Q ()
reportError = report True
-- | Report a warning to the user, and carry on.
reportWarning :: String -> Q ()
reportWarning = report False
-- | Recover from errors raised by 'reportError' or 'fail'.
recover :: Q a -- ^ handler to invoke on failure
-> Q a -- ^ computation to run
-> Q a
recover (Q r) (Q m) = Q (qRecover r m)
-- We don't export lookupName; the Bool isn't a great API
-- Instead we export lookupTypeName, lookupValueName
lookupName :: Bool -> String -> Q (Maybe Name)
lookupName ns s = Q (qLookupName ns s)
-- | Look up the given name in the (type namespace of the) current splice's scope. See "Language.Haskell.TH.Syntax#namelookup" for more details.
lookupTypeName :: String -> Q (Maybe Name)
lookupTypeName s = Q (qLookupName True s)
-- | Look up the given name in the (value namespace of the) current splice's scope. See "Language.Haskell.TH.Syntax#namelookup" for more details.
lookupValueName :: String -> Q (Maybe Name)
lookupValueName s = Q (qLookupName False s)
{-
Note [Name lookup]
~~~~~~~~~~~~~~~~~~
-}
{- $namelookup #namelookup#
The functions 'lookupTypeName' and 'lookupValueName' provide
a way to query the current splice's context for what names
are in scope. The function 'lookupTypeName' queries the type
namespace, whereas 'lookupValueName' queries the value namespace,
but the functions are otherwise identical.
A call @lookupValueName s@ will check if there is a value
with name @s@ in scope at the current splice's location. If
there is, the @Name@ of this value is returned;
if not, then @Nothing@ is returned.
The returned name cannot be \"captured\".
For example:
> f = "global"
> g = $( do
> Just nm <- lookupValueName "f"
> [| let f = "local" in $( varE nm ) |]
In this case, @g = \"global\"@; the call to @lookupValueName@
returned the global @f@, and this name was /not/ captured by
the local definition of @f@.
The lookup is performed in the context of the /top-level/ splice
being run. For example:
> f = "global"
> g = $( [| let f = "local" in
> $(do
> Just nm <- lookupValueName "f"
> varE nm
> ) |] )
Again in this example, @g = \"global\"@, because the call to
@lookupValueName@ queries the context of the outer-most @$(...)@.
Operators should be queried without any surrounding parentheses, like so:
> lookupValueName "+"
Qualified names are also supported, like so:
> lookupValueName "Prelude.+"
> lookupValueName "Prelude.map"
-}
{- | 'reify' looks up information about the 'Name'.
It is sometimes useful to construct the argument name using 'lookupTypeName' or 'lookupValueName'
to ensure that we are reifying from the right namespace. For instance, in this context:
> data D = D
which @D@ does @reify (mkName \"D\")@ return information about? (Answer: @D@-the-type, but don't rely on it.)
To ensure we get information about @D@-the-value, use 'lookupValueName':
> do
> Just nm <- lookupValueName "D"
> reify nm
and to get information about @D@-the-type, use 'lookupTypeName'.
-}
reify :: Name -> Q Info
reify v = Q (qReify v)
{- | @reifyInstances nm tys@ returns a list of visible instances of @nm tys@. That is,
if @nm@ is the name of a type class, then all instances of this class at the types @tys@
are returned. Alternatively, if @nm@ is the name of a data family or type family,
all instances of this family at the types @tys@ are returned.
-}
reifyInstances :: Name -> [Type] -> Q [InstanceDec]
reifyInstances cls tys = Q (qReifyInstances cls tys)
{- | @reifyRoles nm@ returns the list of roles associated with the parameters of
the tycon @nm@. Fails if @nm@ cannot be found or is not a tycon.
The returned list should never contain 'InferR'.
-}
reifyRoles :: Name -> Q [Role]
reifyRoles nm = Q (qReifyRoles nm)
-- | @reifyAnnotations target@ returns the list of annotations
-- associated with @target@. Only the annotations that are
-- appropriately typed is returned. So if you have @Int@ and @String@
-- annotations for the same target, you have to call this function twice.
reifyAnnotations :: Data a => AnnLookup -> Q [a]
reifyAnnotations an = Q (qReifyAnnotations an)
-- | @reifyModule mod@ looks up information about module @mod@. To
-- look up the current module, call this function with the return
-- value of @thisModule@.
reifyModule :: Module -> Q ModuleInfo
reifyModule m = Q (qReifyModule m)
-- | Is the list of instances returned by 'reifyInstances' nonempty?
isInstance :: Name -> [Type] -> Q Bool
isInstance nm tys = do { decs <- reifyInstances nm tys
; return (not (null decs)) }
-- | The location at which this computation is spliced.
location :: Q Loc
location = Q qLocation
-- |The 'runIO' function lets you run an I\/O computation in the 'Q' monad.
-- Take care: you are guaranteed the ordering of calls to 'runIO' within
-- a single 'Q' computation, but not about the order in which splices are run.
--
-- Note: for various murky reasons, stdout and stderr handles are not
-- necessarily flushed when the compiler finishes running, so you should
-- flush them yourself.
runIO :: IO a -> Q a
runIO m = Q (qRunIO m)
-- | Record external files that runIO is using (dependent upon).
-- The compiler can then recognize that it should re-compile the file using this TH when the external file changes.
-- Note that ghc -M will still not know about these dependencies - it does not execute TH.
-- Expects an absolute file path.
addDependentFile :: FilePath -> Q ()
addDependentFile fp = Q (qAddDependentFile fp)
-- | Add additional top-level declarations. The added declarations will be type
-- checked along with the current declaration group.
addTopDecls :: [Dec] -> Q ()
addTopDecls ds = Q (qAddTopDecls ds)
-- | Add a finalizer that will run in the Q monad after the current module has
-- been type checked. This only makes sense when run within a top-level splice.
addModFinalizer :: Q () -> Q ()
addModFinalizer act = Q (qAddModFinalizer (unQ act))
-- | Get state from the Q monad.
getQ :: Typeable a => Q (Maybe a)
getQ = Q qGetQ
-- | Replace the state in the Q monad.
putQ :: Typeable a => a -> Q ()
putQ x = Q (qPutQ x)
instance Quasi Q where
qNewName = newName
qReport = report
qRecover = recover
qReify = reify
qReifyInstances = reifyInstances
qReifyRoles = reifyRoles
qReifyAnnotations = reifyAnnotations
qReifyModule = reifyModule
qLookupName = lookupName
qLocation = location
qRunIO = runIO
qAddDependentFile = addDependentFile
qAddTopDecls = addTopDecls
qAddModFinalizer = addModFinalizer
qGetQ = getQ
qPutQ = putQ
----------------------------------------------------
-- The following operations are used solely in DsMeta when desugaring brackets
-- They are not necessary for the user, who can use ordinary return and (>>=) etc
returnQ :: a -> Q a
returnQ = return
bindQ :: Q a -> (a -> Q b) -> Q b
bindQ = (>>=)
sequenceQ :: [Q a] -> Q [a]
sequenceQ = sequence
-----------------------------------------------------
--
-- The Lift class
--
-----------------------------------------------------
class Lift t where
lift :: t -> Q Exp
instance Lift Integer where
lift x = return (LitE (IntegerL x))
instance Lift Int where
lift x= return (LitE (IntegerL (fromIntegral x)))
instance Lift Char where
lift x = return (LitE (CharL x))
instance Lift Bool where
lift True = return (ConE trueName)
lift False = return (ConE falseName)
instance Lift a => Lift (Maybe a) where
lift Nothing = return (ConE nothingName)
lift (Just x) = liftM (ConE justName `AppE`) (lift x)
instance (Lift a, Lift b) => Lift (Either a b) where
lift (Left x) = liftM (ConE leftName `AppE`) (lift x)
lift (Right y) = liftM (ConE rightName `AppE`) (lift y)
instance Lift a => Lift [a] where
lift xs = do { xs' <- mapM lift xs; return (ListE xs') }
liftString :: String -> Q Exp
-- Used in TcExpr to short-circuit the lifting for strings
liftString s = return (LitE (StringL s))
instance (Lift a, Lift b) => Lift (a, b) where
lift (a, b)
= liftM TupE $ sequence [lift a, lift b]
instance (Lift a, Lift b, Lift c) => Lift (a, b, c) where
lift (a, b, c)
= liftM TupE $ sequence [lift a, lift b, lift c]
instance (Lift a, Lift b, Lift c, Lift d) => Lift (a, b, c, d) where
lift (a, b, c, d)
= liftM TupE $ sequence [lift a, lift b, lift c, lift d]
instance (Lift a, Lift b, Lift c, Lift d, Lift e)
=> Lift (a, b, c, d, e) where
lift (a, b, c, d, e)
= liftM TupE $ sequence [lift a, lift b, lift c, lift d, lift e]
instance (Lift a, Lift b, Lift c, Lift d, Lift e, Lift f)
=> Lift (a, b, c, d, e, f) where
lift (a, b, c, d, e, f)
= liftM TupE $ sequence [lift a, lift b, lift c, lift d, lift e, lift f]
instance (Lift a, Lift b, Lift c, Lift d, Lift e, Lift f, Lift g)
=> Lift (a, b, c, d, e, f, g) where
lift (a, b, c, d, e, f, g)
= liftM TupE $ sequence [lift a, lift b, lift c, lift d, lift e, lift f, lift g]
-- TH has a special form for literal strings,
-- which we should take advantage of.
-- NB: the lhs of the rule has no args, so that
-- the rule will apply to a 'lift' all on its own
-- which happens to be the way the type checker
-- creates it.
{-# RULES "TH:liftString" lift = \s -> return (LitE (StringL s)) #-}
trueName, falseName :: Name
trueName = mkNameG DataName "ghc-prim" "GHC.Types" "True"
falseName = mkNameG DataName "ghc-prim" "GHC.Types" "False"
nothingName, justName :: Name
nothingName = mkNameG DataName "base" "Data.Maybe" "Nothing"
justName = mkNameG DataName "base" "Data.Maybe" "Just"
leftName, rightName :: Name
leftName = mkNameG DataName "base" "Data.Either" "Left"
rightName = mkNameG DataName "base" "Data.Either" "Right"
-----------------------------------------------------
-- Names and uniques
-----------------------------------------------------
newtype ModName = ModName String -- Module name
deriving (Show,Eq,Ord,Typeable,Data)
newtype PkgName = PkgName String -- package name
deriving (Show,Eq,Ord,Typeable,Data)
-- | Obtained from 'reifyModule' and 'thisModule'.
data Module = Module PkgName ModName -- package qualified module name
deriving (Show,Eq,Ord,Typeable,Data)
newtype OccName = OccName String
deriving (Show,Eq,Ord,Typeable,Data)
mkModName :: String -> ModName
mkModName s = ModName s
modString :: ModName -> String
modString (ModName m) = m
mkPkgName :: String -> PkgName
mkPkgName s = PkgName s
pkgString :: PkgName -> String
pkgString (PkgName m) = m
-----------------------------------------------------
-- OccName
-----------------------------------------------------
mkOccName :: String -> OccName
mkOccName s = OccName s
occString :: OccName -> String
occString (OccName occ) = occ
-----------------------------------------------------
-- Names
-----------------------------------------------------
--
-- For "global" names ('NameG') we need a totally unique name,
-- so we must include the name-space of the thing
--
-- For unique-numbered things ('NameU'), we've got a unique reference
-- anyway, so no need for name space
--
-- For dynamically bound thing ('NameS') we probably want them to
-- in a context-dependent way, so again we don't want the name
-- space. For example:
--
-- > let v = mkName "T" in [| data $v = $v |]
--
-- Here we use the same Name for both type constructor and data constructor
--
--
-- NameL and NameG are bound *outside* the TH syntax tree
-- either globally (NameG) or locally (NameL). Ex:
--
-- > f x = $(h [| (map, x) |])
--
-- The 'map' will be a NameG, and 'x' wil be a NameL
--
-- These Names should never appear in a binding position in a TH syntax tree
{- $namecapture #namecapture#
Much of 'Name' API is concerned with the problem of /name capture/, which
can be seen in the following example.
> f expr = [| let x = 0 in $expr |]
> ...
> g x = $( f [| x |] )
> h y = $( f [| y |] )
A naive desugaring of this would yield:
> g x = let x = 0 in x
> h y = let x = 0 in y
All of a sudden, @g@ and @h@ have different meanings! In this case,
we say that the @x@ in the RHS of @g@ has been /captured/
by the binding of @x@ in @f@.
What we actually want is for the @x@ in @f@ to be distinct from the
@x@ in @g@, so we get the following desugaring:
> g x = let x' = 0 in x
> h y = let x' = 0 in y
which avoids name capture as desired.
In the general case, we say that a @Name@ can be captured if
the thing it refers to can be changed by adding new declarations.
-}
{- |
An abstract type representing names in the syntax tree.
'Name's can be constructed in several ways, which come with different
name-capture guarantees (see "Language.Haskell.TH.Syntax#namecapture" for
an explanation of name capture):
* the built-in syntax @'f@ and @''T@ can be used to construct names,
The expression @'f@ gives a @Name@ which refers to the value @f@
currently in scope, and @''T@ gives a @Name@ which refers to the
type @T@ currently in scope. These names can never be captured.
* 'lookupValueName' and 'lookupTypeName' are similar to @'f@ and
@''T@ respectively, but the @Name@s are looked up at the point
where the current splice is being run. These names can never be
captured.
* 'newName' monadically generates a new name, which can never
be captured.
* 'mkName' generates a capturable name.
Names constructed using @newName@ and @mkName@ may be used in bindings
(such as @let x = ...@ or @\x -> ...@), but names constructed using
@lookupValueName@, @lookupTypeName@, @'f@, @''T@ may not.
-}
data Name = Name OccName NameFlavour deriving (Typeable, Data)
data NameFlavour
= NameS -- ^ An unqualified name; dynamically bound
| NameQ ModName -- ^ A qualified name; dynamically bound
| NameU Int# -- ^ A unique local name
| NameL Int# -- ^ Local name bound outside of the TH AST
| NameG NameSpace PkgName ModName -- ^ Global name bound outside of the TH AST:
-- An original name (occurrences only, not binders)
-- Need the namespace too to be sure which
-- thing we are naming
deriving ( Typeable )
-- |
-- Although the NameFlavour type is abstract, the Data instance is not. The reason for this
-- is that currently we use Data to serialize values in annotations, and in order for that to
-- work for Template Haskell names introduced via the 'x syntax we need gunfold on NameFlavour
-- to work. Bleh!
--
-- The long term solution to this is to use the binary package for annotation serialization and
-- then remove this instance. However, to do _that_ we need to wait on binary to become stable, since
-- boot libraries cannot be upgraded separately from GHC itself.
--
-- This instance cannot be derived automatically due to bug #2701
instance Data NameFlavour where
gfoldl _ z NameS = z NameS
gfoldl k z (NameQ mn) = z NameQ `k` mn
gfoldl k z (NameU i) = z (\(I# i') -> NameU i') `k` (I# i)
gfoldl k z (NameL i) = z (\(I# i') -> NameL i') `k` (I# i)
gfoldl k z (NameG ns p m) = z NameG `k` ns `k` p `k` m
gunfold k z c = case constrIndex c of
1 -> z NameS
2 -> k $ z NameQ
3 -> k $ z (\(I# i) -> NameU i)
4 -> k $ z (\(I# i) -> NameL i)
5 -> k $ k $ k $ z NameG
_ -> error "gunfold: NameFlavour"
toConstr NameS = con_NameS
toConstr (NameQ _) = con_NameQ
toConstr (NameU _) = con_NameU
toConstr (NameL _) = con_NameL
toConstr (NameG _ _ _) = con_NameG
dataTypeOf _ = ty_NameFlavour
con_NameS, con_NameQ, con_NameU, con_NameL, con_NameG :: Data.Constr
con_NameS = mkConstr ty_NameFlavour "NameS" [] Data.Prefix
con_NameQ = mkConstr ty_NameFlavour "NameQ" [] Data.Prefix
con_NameU = mkConstr ty_NameFlavour "NameU" [] Data.Prefix
con_NameL = mkConstr ty_NameFlavour "NameL" [] Data.Prefix
con_NameG = mkConstr ty_NameFlavour "NameG" [] Data.Prefix
ty_NameFlavour :: Data.DataType
ty_NameFlavour = mkDataType "Language.Haskell.TH.Syntax.NameFlavour"
[con_NameS, con_NameQ, con_NameU,
con_NameL, con_NameG]
data NameSpace = VarName -- ^ Variables
| DataName -- ^ Data constructors
| TcClsName -- ^ Type constructors and classes; Haskell has them
-- in the same name space for now.
deriving( Eq, Ord, Data, Typeable )
type Uniq = Int
-- | The name without its module prefix
nameBase :: Name -> String
nameBase (Name occ _) = occString occ
-- | Module prefix of a name, if it exists
nameModule :: Name -> Maybe String
nameModule (Name _ (NameQ m)) = Just (modString m)
nameModule (Name _ (NameG _ _ m)) = Just (modString m)
nameModule _ = Nothing
{- |
Generate a capturable name. Occurrences of such names will be
resolved according to the Haskell scoping rules at the occurrence
site.
For example:
> f = [| pi + $(varE (mkName "pi")) |]
> ...
> g = let pi = 3 in $f
In this case, @g@ is desugared to
> g = Prelude.pi + 3
Note that @mkName@ may be used with qualified names:
> mkName "Prelude.pi"
See also 'Language.Haskell.TH.Lib.dyn' for a useful combinator. The above example could
be rewritten using 'dyn' as
> f = [| pi + $(dyn "pi") |]
-}
mkName :: String -> Name
-- The string can have a '.', thus "Foo.baz",
-- giving a dynamically-bound qualified name,
-- in which case we want to generate a NameQ
--
-- Parse the string to see if it has a "." in it
-- so we know whether to generate a qualified or unqualified name
-- It's a bit tricky because we need to parse
--
-- > Foo.Baz.x as Qual Foo.Baz x
--
-- So we parse it from back to front
mkName str
= split [] (reverse str)
where
split occ [] = Name (mkOccName occ) NameS
split occ ('.':rev) | not (null occ)
, is_rev_mod_name rev
= Name (mkOccName occ) (NameQ (mkModName (reverse rev)))
-- The 'not (null occ)' guard ensures that
-- mkName "&." = Name "&." NameS
-- The 'is_rev_mod' guards ensure that
-- mkName ".&" = Name ".&" NameS
-- mkName "^.." = Name "^.." NameS -- Trac #8633
-- mkName "Data.Bits..&" = Name ".&" (NameQ "Data.Bits")
-- This rather bizarre case actually happened; (.&.) is in Data.Bits
split occ (c:rev) = split (c:occ) rev
-- Recognises a reversed module name xA.yB.C,
-- with at least one component,
-- and each component looks like a module name
-- (i.e. non-empty, starts with capital, all alpha)
is_rev_mod_name rev_mod_str
| (compt, rest) <- break (== '.') rev_mod_str
, not (null compt), isUpper (last compt), all is_mod_char compt
= case rest of
[] -> True
(_dot : rest') -> is_rev_mod_name rest'
| otherwise
= False
is_mod_char c = isAlphaNum c || c == '_' || c == '\''
-- | Only used internally
mkNameU :: String -> Uniq -> Name
mkNameU s (I# u) = Name (mkOccName s) (NameU u)
-- | Only used internally
mkNameL :: String -> Uniq -> Name
mkNameL s (I# u) = Name (mkOccName s) (NameL u)
-- | Used for 'x etc, but not available to the programmer
mkNameG :: NameSpace -> String -> String -> String -> Name
mkNameG ns pkg modu occ
= Name (mkOccName occ) (NameG ns (mkPkgName pkg) (mkModName modu))
mkNameG_v, mkNameG_tc, mkNameG_d :: String -> String -> String -> Name
mkNameG_v = mkNameG VarName
mkNameG_tc = mkNameG TcClsName
mkNameG_d = mkNameG DataName
instance Eq Name where
v1 == v2 = cmpEq (v1 `compare` v2)
instance Ord Name where
(Name o1 f1) `compare` (Name o2 f2) = (f1 `compare` f2) `thenCmp`
(o1 `compare` o2)
instance Eq NameFlavour where
f1 == f2 = cmpEq (f1 `compare` f2)
instance Ord NameFlavour where
-- NameS < NameQ < NameU < NameL < NameG
NameS `compare` NameS = EQ
NameS `compare` _ = LT
(NameQ _) `compare` NameS = GT
(NameQ m1) `compare` (NameQ m2) = m1 `compare` m2
(NameQ _) `compare` _ = LT
(NameU _) `compare` NameS = GT
(NameU _) `compare` (NameQ _) = GT
(NameU u1) `compare` (NameU u2) | isTrue# (u1 <# u2) = LT
| isTrue# (u1 ==# u2) = EQ
| otherwise = GT
(NameU _) `compare` _ = LT
(NameL _) `compare` NameS = GT
(NameL _) `compare` (NameQ _) = GT
(NameL _) `compare` (NameU _) = GT
(NameL u1) `compare` (NameL u2) | isTrue# (u1 <# u2) = LT
| isTrue# (u1 ==# u2) = EQ
| otherwise = GT
(NameL _) `compare` _ = LT
(NameG ns1 p1 m1) `compare` (NameG ns2 p2 m2) = (ns1 `compare` ns2) `thenCmp`
(p1 `compare` p2) `thenCmp`
(m1 `compare` m2)
(NameG _ _ _) `compare` _ = GT
data NameIs = Alone | Applied | Infix
showName :: Name -> String
showName = showName' Alone
showName' :: NameIs -> Name -> String
showName' ni nm
= case ni of
Alone -> nms
Applied
| pnam -> nms
| otherwise -> "(" ++ nms ++ ")"
Infix
| pnam -> "`" ++ nms ++ "`"
| otherwise -> nms
where
-- For now, we make the NameQ and NameG print the same, even though
-- NameQ is a qualified name (so what it means depends on what the
-- current scope is), and NameG is an original name (so its meaning
-- should be independent of what's in scope.
-- We may well want to distinguish them in the end.
-- Ditto NameU and NameL
nms = case nm of
Name occ NameS -> occString occ
Name occ (NameQ m) -> modString m ++ "." ++ occString occ
Name occ (NameG _ _ m) -> modString m ++ "." ++ occString occ
Name occ (NameU u) -> occString occ ++ "_" ++ show (I# u)
Name occ (NameL u) -> occString occ ++ "_" ++ show (I# u)
pnam = classify nms
-- True if we are function style, e.g. f, [], (,)
-- False if we are operator style, e.g. +, :+
classify "" = False -- shouldn't happen; . operator is handled below
classify (x:xs) | isAlpha x || (x `elem` "_[]()") =
case dropWhile (/='.') xs of
(_:xs') -> classify xs'
[] -> True
| otherwise = False
instance Show Name where
show = showName
-- Tuple data and type constructors
-- | Tuple data constructor
tupleDataName :: Int -> Name
-- | Tuple type constructor
tupleTypeName :: Int -> Name
tupleDataName 0 = mk_tup_name 0 DataName
tupleDataName 1 = error "tupleDataName 1"
tupleDataName n = mk_tup_name (n-1) DataName
tupleTypeName 0 = mk_tup_name 0 TcClsName
tupleTypeName 1 = error "tupleTypeName 1"
tupleTypeName n = mk_tup_name (n-1) TcClsName
mk_tup_name :: Int -> NameSpace -> Name
mk_tup_name n_commas space
= Name occ (NameG space (mkPkgName "ghc-prim") tup_mod)
where
occ = mkOccName ('(' : replicate n_commas ',' ++ ")")
tup_mod = mkModName "GHC.Tuple"
-- Unboxed tuple data and type constructors
-- | Unboxed tuple data constructor
unboxedTupleDataName :: Int -> Name
-- | Unboxed tuple type constructor
unboxedTupleTypeName :: Int -> Name
unboxedTupleDataName 0 = error "unboxedTupleDataName 0"
unboxedTupleDataName 1 = error "unboxedTupleDataName 1"
unboxedTupleDataName n = mk_unboxed_tup_name (n-1) DataName
unboxedTupleTypeName 0 = error "unboxedTupleTypeName 0"
unboxedTupleTypeName 1 = error "unboxedTupleTypeName 1"
unboxedTupleTypeName n = mk_unboxed_tup_name (n-1) TcClsName
mk_unboxed_tup_name :: Int -> NameSpace -> Name
mk_unboxed_tup_name n_commas space
= Name occ (NameG space (mkPkgName "ghc-prim") tup_mod)
where
occ = mkOccName ("(#" ++ replicate n_commas ',' ++ "#)")
tup_mod = mkModName "GHC.Tuple"
-----------------------------------------------------
-- Locations
-----------------------------------------------------
data Loc
= Loc { loc_filename :: String
, loc_package :: String
, loc_module :: String
, loc_start :: CharPos
, loc_end :: CharPos }
type CharPos = (Int, Int) -- ^ Line and character position
-----------------------------------------------------
--
-- The Info returned by reification
--
-----------------------------------------------------
-- | Obtained from 'reify' in the 'Q' Monad.
data Info
=
-- | A class, with a list of its visible instances
ClassI
Dec
[InstanceDec]
-- | A class method
| ClassOpI
Name
Type
ParentName
Fixity
-- | A \"plain\" type constructor. \"Fancier\" type constructors are returned using 'PrimTyConI' or 'FamilyI' as appropriate
| TyConI
Dec
-- | A type or data family, with a list of its visible instances. A closed
-- type family is returned with 0 instances.
| FamilyI
Dec
[InstanceDec]
-- | A \"primitive\" type constructor, which can't be expressed with a 'Dec'. Examples: @(->)@, @Int#@.
| PrimTyConI
Name
Arity
Unlifted
-- | A data constructor
| DataConI
Name
Type
ParentName
Fixity
{- |
A \"value\" variable (as opposed to a type variable, see 'TyVarI').
The @Maybe Dec@ field contains @Just@ the declaration which
defined the variable -- including the RHS of the declaration --
or else @Nothing@, in the case where the RHS is unavailable to
the compiler. At present, this value is _always_ @Nothing@:
returning the RHS has not yet been implemented because of
lack of interest.
-}
| VarI
Name
Type
(Maybe Dec)
Fixity
{- |
A type variable.
The @Type@ field contains the type which underlies the variable.
At present, this is always @'VarT' theName@, but future changes
may permit refinement of this.
-}
| TyVarI -- Scoped type variable
Name
Type -- What it is bound to
deriving( Show, Data, Typeable )
-- | Obtained from 'reifyModule' in the 'Q' Monad.
data ModuleInfo =
-- | Contains the import list of the module.
ModuleInfo [Module]
deriving( Show, Data, Typeable )
{- |
In 'ClassOpI' and 'DataConI', name of the parent class or type
-}
type ParentName = Name
-- | In 'PrimTyConI', arity of the type constructor
type Arity = Int
-- | In 'PrimTyConI', is the type constructor unlifted?
type Unlifted = Bool
-- | 'InstanceDec' desribes a single instance of a class or type function.
-- It is just a 'Dec', but guaranteed to be one of the following:
--
-- * 'InstanceD' (with empty @['Dec']@)
--
-- * 'DataInstD' or 'NewtypeInstD' (with empty derived @['Name']@)
--
-- * 'TySynInstD'
type InstanceDec = Dec
data Fixity = Fixity Int FixityDirection
deriving( Eq, Show, Data, Typeable )
data FixityDirection = InfixL | InfixR | InfixN
deriving( Eq, Show, Data, Typeable )
-- | Highest allowed operator precedence for 'Fixity' constructor (answer: 9)
maxPrecedence :: Int
maxPrecedence = (9::Int)
-- | Default fixity: @infixl 9@
defaultFixity :: Fixity
defaultFixity = Fixity maxPrecedence InfixL
{-
Note [Unresolved infix]
~~~~~~~~~~~~~~~~~~~~~~~
-}
{- $infix #infix#
When implementing antiquotation for quasiquoters, one often wants
to parse strings into expressions:
> parse :: String -> Maybe Exp
But how should we parse @a + b * c@? If we don't know the fixities of
@+@ and @*@, we don't know whether to parse it as @a + (b * c)@ or @(a
+ b) * c@.
In cases like this, use 'UInfixE' or 'UInfixP', which stand for
\"unresolved infix expression\" and \"unresolved infix pattern\". When
the compiler is given a splice containing a tree of @UInfixE@
applications such as
> UInfixE
> (UInfixE e1 op1 e2)
> op2
> (UInfixE e3 op3 e4)
it will look up and the fixities of the relevant operators and
reassociate the tree as necessary.
* trees will not be reassociated across 'ParensE' or 'ParensP',
which are of use for parsing expressions like
> (a + b * c) + d * e
* 'InfixE' and 'InfixP' expressions are never reassociated.
* The 'UInfixE' constructor doesn't support sections. Sections
such as @(a *)@ have no ambiguity, so 'InfixE' suffices. For longer
sections such as @(a + b * c -)@, use an 'InfixE' constructor for the
outer-most section, and use 'UInfixE' constructors for all
other operators:
> InfixE
> Just (UInfixE ...a + b * c...)
> op
> Nothing
Sections such as @(a + b +)@ and @((a + b) +)@ should be rendered
into 'Exp's differently:
> (+ a + b) ---> InfixE Nothing + (Just $ UInfixE a + b)
> -- will result in a fixity error if (+) is left-infix
> (+ (a + b)) ---> InfixE Nothing + (Just $ ParensE $ UInfixE a + b)
> -- no fixity errors
* Quoted expressions such as
> [| a * b + c |] :: Q Exp
> [p| a : b : c |] :: Q Pat
will never contain 'UInfixE', 'UInfixP', 'ParensE', or 'ParensP'
constructors.
-}
-----------------------------------------------------
--
-- The main syntax data types
--
-----------------------------------------------------
data Lit = CharL Char
| StringL String
| IntegerL Integer -- ^ Used for overloaded and non-overloaded
-- literals. We don't have a good way to
-- represent non-overloaded literals at
-- the moment. Maybe that doesn't matter?
| RationalL Rational -- Ditto
| IntPrimL Integer
| WordPrimL Integer
| FloatPrimL Rational
| DoublePrimL Rational
| StringPrimL [Word8] -- ^ A primitive C-style string, type Addr#
deriving( Show, Eq, Data, Typeable )
-- We could add Int, Float, Double etc, as we do in HsLit,
-- but that could complicate the
-- suppposedly-simple TH.Syntax literal type
-- | Pattern in Haskell given in @{}@
data Pat
= LitP Lit -- ^ @{ 5 or 'c' }@
| VarP Name -- ^ @{ x }@
| TupP [Pat] -- ^ @{ (p1,p2) }@
| UnboxedTupP [Pat] -- ^ @{ (# p1,p2 #) }@
| ConP Name [Pat] -- ^ @data T1 = C1 t1 t2; {C1 p1 p1} = e@
| InfixP Pat Name Pat -- ^ @foo ({x :+ y}) = e@
| UInfixP Pat Name Pat -- ^ @foo ({x :+ y}) = e@
--
-- See "Language.Haskell.TH.Syntax#infix"
| ParensP Pat -- ^ @{(p)}@
--
-- See "Language.Haskell.TH.Syntax#infix"
| TildeP Pat -- ^ @{ ~p }@
| BangP Pat -- ^ @{ !p }@
| AsP Name Pat -- ^ @{ x \@ p }@
| WildP -- ^ @{ _ }@
| RecP Name [FieldPat] -- ^ @f (Pt { pointx = x }) = g x@
| ListP [ Pat ] -- ^ @{ [1,2,3] }@
| SigP Pat Type -- ^ @{ p :: t }@
| ViewP Exp Pat -- ^ @{ e -> p }@
deriving( Show, Eq, Data, Typeable )
type FieldPat = (Name,Pat)
data Match = Match Pat Body [Dec] -- ^ @case e of { pat -> body where decs }@
deriving( Show, Eq, Data, Typeable )
data Clause = Clause [Pat] Body [Dec]
-- ^ @f { p1 p2 = body where decs }@
deriving( Show, Eq, Data, Typeable )
data Exp
= VarE Name -- ^ @{ x }@
| ConE Name -- ^ @data T1 = C1 t1 t2; p = {C1} e1 e2 @
| LitE Lit -- ^ @{ 5 or 'c'}@
| AppE Exp Exp -- ^ @{ f x }@
| InfixE (Maybe Exp) Exp (Maybe Exp) -- ^ @{x + y} or {(x+)} or {(+ x)} or {(+)}@
-- It's a bit gruesome to use an Exp as the
-- operator, but how else can we distinguish
-- constructors from non-constructors?
-- Maybe there should be a var-or-con type?
-- Or maybe we should leave it to the String itself?
| UInfixE Exp Exp Exp -- ^ @{x + y}@
--
-- See "Language.Haskell.TH.Syntax#infix"
| ParensE Exp -- ^ @{ (e) }@
--
-- See "Language.Haskell.TH.Syntax#infix"
| LamE [Pat] Exp -- ^ @{ \ p1 p2 -> e }@
| LamCaseE [Match] -- ^ @{ \case m1; m2 }@
| TupE [Exp] -- ^ @{ (e1,e2) } @
| UnboxedTupE [Exp] -- ^ @{ (# e1,e2 #) } @
| CondE Exp Exp Exp -- ^ @{ if e1 then e2 else e3 }@
| MultiIfE [(Guard, Exp)] -- ^ @{ if | g1 -> e1 | g2 -> e2 }@
| LetE [Dec] Exp -- ^ @{ let x=e1; y=e2 in e3 }@
| CaseE Exp [Match] -- ^ @{ case e of m1; m2 }@
| DoE [Stmt] -- ^ @{ do { p <- e1; e2 } }@
| CompE [Stmt] -- ^ @{ [ (x,y) | x <- xs, y <- ys ] }@
--
-- The result expression of the comprehension is
-- the /last/ of the @'Stmt'@s, and should be a 'NoBindS'.
--
-- E.g. translation:
--
-- > [ f x | x <- xs ]
--
-- > CompE [BindS (VarP x) (VarE xs), NoBindS (AppE (VarE f) (VarE x))]
| ArithSeqE Range -- ^ @{ [ 1 ,2 .. 10 ] }@
| ListE [ Exp ] -- ^ @{ [1,2,3] }@
| SigE Exp Type -- ^ @{ e :: t }@
| RecConE Name [FieldExp] -- ^ @{ T { x = y, z = w } }@
| RecUpdE Exp [FieldExp] -- ^ @{ (f x) { z = w } }@
deriving( Show, Eq, Data, Typeable )
type FieldExp = (Name,Exp)
-- Omitted: implicit parameters
data Body
= GuardedB [(Guard,Exp)] -- ^ @f p { | e1 = e2
-- | e3 = e4 }
-- where ds@
| NormalB Exp -- ^ @f p { = e } where ds@
deriving( Show, Eq, Data, Typeable )
data Guard
= NormalG Exp -- ^ @f x { | odd x } = x@
| PatG [Stmt] -- ^ @f x { | Just y <- x, Just z <- y } = z@
deriving( Show, Eq, Data, Typeable )
data Stmt
= BindS Pat Exp
| LetS [ Dec ]
| NoBindS Exp
| ParS [[Stmt]]
deriving( Show, Eq, Data, Typeable )
data Range = FromR Exp | FromThenR Exp Exp
| FromToR Exp Exp | FromThenToR Exp Exp Exp
deriving( Show, Eq, Data, Typeable )
data Dec
= FunD Name [Clause] -- ^ @{ f p1 p2 = b where decs }@
| ValD Pat Body [Dec] -- ^ @{ p = b where decs }@
| DataD Cxt Name [TyVarBndr]
[Con] [Name] -- ^ @{ data Cxt x => T x = A x | B (T x)
-- deriving (Z,W)}@
| NewtypeD Cxt Name [TyVarBndr]
Con [Name] -- ^ @{ newtype Cxt x => T x = A (B x)
-- deriving (Z,W)}@
| TySynD Name [TyVarBndr] Type -- ^ @{ type T x = (x,x) }@
| ClassD Cxt Name [TyVarBndr]
[FunDep] [Dec] -- ^ @{ class Eq a => Ord a where ds }@
| InstanceD Cxt Type [Dec] -- ^ @{ instance Show w => Show [w]
-- where ds }@
| SigD Name Type -- ^ @{ length :: [a] -> Int }@
| ForeignD Foreign -- ^ @{ foreign import ... }
--{ foreign export ... }@
| InfixD Fixity Name -- ^ @{ infix 3 foo }@
-- | pragmas
| PragmaD Pragma -- ^ @{ {\-# INLINE [1] foo #-\} }@
-- | type families (may also appear in [Dec] of 'ClassD' and 'InstanceD')
| FamilyD FamFlavour Name
[TyVarBndr] (Maybe Kind) -- ^ @{ type family T a b c :: * }@
| DataInstD Cxt Name [Type]
[Con] [Name] -- ^ @{ data instance Cxt x => T [x] = A x
-- | B (T x)
-- deriving (Z,W)}@
| NewtypeInstD Cxt Name [Type]
Con [Name] -- ^ @{ newtype instance Cxt x => T [x] = A (B x)
-- deriving (Z,W)}@
| TySynInstD Name TySynEqn -- ^ @{ type instance ... }@
| ClosedTypeFamilyD Name
[TyVarBndr] (Maybe Kind)
[TySynEqn] -- ^ @{ type family F a b :: * where ... }@
| RoleAnnotD Name [Role] -- ^ @{ type role T nominal representational }@
deriving( Show, Eq, Data, Typeable )
-- | One equation of a type family instance or closed type family. The
-- arguments are the left-hand-side type patterns and the right-hand-side
-- result.
data TySynEqn = TySynEqn [Type] Type
deriving( Show, Eq, Data, Typeable )
data FunDep = FunDep [Name] [Name]
deriving( Show, Eq, Data, Typeable )
data FamFlavour = TypeFam | DataFam
deriving( Show, Eq, Data, Typeable )
data Foreign = ImportF Callconv Safety String Name Type
| ExportF Callconv String Name Type
deriving( Show, Eq, Data, Typeable )
data Callconv = CCall | StdCall
deriving( Show, Eq, Data, Typeable )
data Safety = Unsafe | Safe | Interruptible
deriving( Show, Eq, Data, Typeable )
data Pragma = InlineP Name Inline RuleMatch Phases
| SpecialiseP Name Type (Maybe Inline) Phases
| SpecialiseInstP Type
| RuleP String [RuleBndr] Exp Exp Phases
| AnnP AnnTarget Exp
deriving( Show, Eq, Data, Typeable )
data Inline = NoInline
| Inline
| Inlinable
deriving (Show, Eq, Data, Typeable)
data RuleMatch = ConLike
| FunLike
deriving (Show, Eq, Data, Typeable)
data Phases = AllPhases
| FromPhase Int
| BeforePhase Int
deriving (Show, Eq, Data, Typeable)
data RuleBndr = RuleVar Name
| TypedRuleVar Name Type
deriving (Show, Eq, Data, Typeable)
data AnnTarget = ModuleAnnotation
| TypeAnnotation Name
| ValueAnnotation Name
deriving (Show, Eq, Data, Typeable)
type Cxt = [Pred] -- ^ @(Eq a, Ord b)@
-- | Since the advent of @ConstraintKinds@, constraints are really just types.
-- Equality constraints use the 'EqualityT' constructor. Constraints may also
-- be tuples of other constraints.
type Pred = Type
data Strict = IsStrict | NotStrict | Unpacked
deriving( Show, Eq, Data, Typeable )
data Con = NormalC Name [StrictType] -- ^ @C Int a@
| RecC Name [VarStrictType] -- ^ @C { v :: Int, w :: a }@
| InfixC StrictType Name StrictType -- ^ @Int :+ a@
| ForallC [TyVarBndr] Cxt Con -- ^ @forall a. Eq a => C [a]@
deriving( Show, Eq, Data, Typeable )
type StrictType = (Strict, Type)
type VarStrictType = (Name, Strict, Type)
data Type = ForallT [TyVarBndr] Cxt Type -- ^ @forall \<vars\>. \<ctxt\> -> \<type\>@
| AppT Type Type -- ^ @T a b@
| SigT Type Kind -- ^ @t :: k@
| VarT Name -- ^ @a@
| ConT Name -- ^ @T@
| PromotedT Name -- ^ @'T@
-- See Note [Representing concrete syntax in types]
| TupleT Int -- ^ @(,), (,,), etc.@
| UnboxedTupleT Int -- ^ @(#,#), (#,,#), etc.@
| ArrowT -- ^ @->@
| EqualityT -- ^ @~@
| ListT -- ^ @[]@
| PromotedTupleT Int -- ^ @'(), '(,), '(,,), etc.@
| PromotedNilT -- ^ @'[]@
| PromotedConsT -- ^ @(':)@
| StarT -- ^ @*@
| ConstraintT -- ^ @Constraint@
| LitT TyLit -- ^ @0,1,2, etc.@
deriving( Show, Eq, Data, Typeable )
data TyVarBndr = PlainTV Name -- ^ @a@
| KindedTV Name Kind -- ^ @(a :: k)@
deriving( Show, Eq, Data, Typeable )
data TyLit = NumTyLit Integer -- ^ @2@
| StrTyLit String -- ^ @"Hello"@
deriving ( Show, Eq, Data, Typeable )
-- | Role annotations
data Role = NominalR -- ^ @nominal@
| RepresentationalR -- ^ @representational@
| PhantomR -- ^ @phantom@
| InferR -- ^ @_@
deriving( Show, Eq, Data, Typeable )
-- | Annotation target for reifyAnnotations
data AnnLookup = AnnLookupModule Module
| AnnLookupName Name
deriving( Show, Eq, Data, Typeable )
-- | To avoid duplication between kinds and types, they
-- are defined to be the same. Naturally, you would never
-- have a type be 'StarT' and you would never have a kind
-- be 'SigT', but many of the other constructors are shared.
-- Note that the kind @Bool@ is denoted with 'ConT', not
-- 'PromotedT'. Similarly, tuple kinds are made with 'TupleT',
-- not 'PromotedTupleT'.
type Kind = Type
{- Note [Representing concrete syntax in types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Haskell has a rich concrete syntax for types, including
t1 -> t2, (t1,t2), [t], and so on
In TH we represent all of this using AppT, with a distinguished
type constructor at the head. So,
Type TH representation
-----------------------------------------------
t1 -> t2 ArrowT `AppT` t2 `AppT` t2
[t] ListT `AppT` t
(t1,t2) TupleT 2 `AppT` t1 `AppT` t2
'(t1,t2) PromotedTupleT 2 `AppT` t1 `AppT` t2
But if the original HsSyn used prefix application, we won't use
these special TH constructors. For example
[] t ConT "[]" `AppT` t
(->) t ConT "->" `AppT` t
In this way we can faithfully represent in TH whether the original
HsType used concrete syntax or not.
The one case that doesn't fit this pattern is that of promoted lists
'[ Maybe, IO ] PromotedListT 2 `AppT` t1 `AppT` t2
but it's very smelly because there really is no type constructor
corresponding to PromotedListT. So we encode HsExplicitListTy with
PromotedConsT and PromotedNilT (which *do* have underlying type
constructors):
'[ Maybe, IO ] PromotedConsT `AppT` Maybe `AppT`
(PromotedConsT `AppT` IO `AppT` PromotedNilT)
-}
-----------------------------------------------------
-- Internal helper functions
-----------------------------------------------------
cmpEq :: Ordering -> Bool
cmpEq EQ = True
cmpEq _ = False
thenCmp :: Ordering -> Ordering -> Ordering
thenCmp EQ o2 = o2
thenCmp o1 _ = o1
| frantisekfarka/ghc-dsi | libraries/template-haskell/Language/Haskell/TH/Syntax.hs | bsd-3-clause | 49,614 | 36 | 14 | 13,677 | 8,709 | 4,791 | 3,918 | 622 | 9 |
{-# LANGUAGE PatternGuards #-}
module Idris.Interactive(caseSplitAt, addClauseFrom, addProofClauseFrom,
addMissing, makeWith, makeCase, doProofSearch,
makeLemma) where
{- Bits and pieces for editing source files interactively, called from
the REPL -}
import Idris.Core.TT
import Idris.Core.Evaluate
import Idris.CaseSplit
import Idris.AbsSyntax
import Idris.ElabDecls
import Idris.Error
import Idris.Delaborate
import Idris.Output
import Idris.IdeMode hiding (IdeModeCommand(..))
import Idris.Elab.Value
import Idris.Elab.Term
import Util.Pretty
import Util.System
import System.FilePath
import System.Directory
import System.IO
import Data.Char
import Data.Maybe (fromMaybe)
import Data.List (isSuffixOf)
import Debug.Trace
caseSplitAt :: FilePath -> Bool -> Int -> Name -> Idris ()
caseSplitAt fn updatefile l n
= do src <- runIO $ readSource fn
(ok, res) <- splitOnLine l n fn
logLvl 1 (showSep "\n" (map show res))
let (before, (ap : later)) = splitAt (l-1) (lines src)
res' <- replaceSplits ap res (not ok)
let new = concat res'
if updatefile
then do let fb = fn ++ "~" -- make a backup!
runIO $ writeSource fb (unlines before ++ new ++ unlines later)
runIO $ copyFile fb fn
else -- do iputStrLn (show res)
iPrintResult new
addClauseFrom :: FilePath -> Bool -> Int -> Name -> Idris ()
addClauseFrom fn updatefile l n = do
-- if a definition already exists, add missing cases rather than
-- adding a new definition.
ist <- getIState
cl <- getInternalApp fn l
let fulln = getAppName cl
case lookup fulln (idris_metavars ist) of
Nothing -> addMissing fn updatefile l n
Just _ -> do
src <- runIO $ readSource fn
let (before, tyline : later) = splitAt (l-1) (lines src)
let indent = getIndent 0 (show n) tyline
cl <- getClause l fulln n fn
-- add clause before first blank line in 'later'
let (nonblank, rest) = span (not . all isSpace) (tyline:later)
if updatefile
then do let fb = fn ++ "~"
runIO $ writeSource fb (unlines (before ++ nonblank) ++
replicate indent ' ' ++
cl ++ "\n" ++
unlines rest)
runIO $ copyFile fb fn
else iPrintResult cl
where
getIndent i n [] = 0
getIndent i n xs | take 9 xs == "instance " = i
getIndent i n xs | take (length n) xs == n = i
getIndent i n (x : xs) = getIndent (i + 1) n xs
getAppName (PApp _ r _) = getAppName r
getAppName (PRef _ _ r) = r
getAppName (PTyped n _) = getAppName n
getAppName _ = n
addProofClauseFrom :: FilePath -> Bool -> Int -> Name -> Idris ()
addProofClauseFrom fn updatefile l n
= do src <- runIO $ readSource fn
let (before, tyline : later) = splitAt (l-1) (lines src)
let indent = getIndent 0 (show n) tyline
cl <- getProofClause l n fn
-- add clause before first blank line in 'later'
let (nonblank, rest) = span (not . all isSpace) (tyline:later)
if updatefile
then do let fb = fn ++ "~"
runIO $ writeSource fb (unlines (before ++ nonblank) ++
replicate indent ' ' ++
cl ++ "\n" ++
unlines rest)
runIO $ copyFile fb fn
else iPrintResult cl
where
getIndent i n [] = 0
getIndent i n xs | take (length n) xs == n = i
getIndent i n (x : xs) = getIndent (i + 1) n xs
addMissing :: FilePath -> Bool -> Int -> Name -> Idris ()
addMissing fn updatefile l n
= do src <- runIO $ readSource fn
let (before, tyline : later) = splitAt (l-1) (lines src)
let indent = getIndent 0 (show n) tyline
i <- getIState
cl <- getInternalApp fn l
let n' = getAppName cl
extras <- case lookupCtxtExact n' (idris_patdefs i) of
Nothing -> return ""
Just (_, tms) -> do tms' <- nameMissing tms
showNew (show n ++ "_rhs") 1 indent tms'
let (nonblank, rest) = span (not . all isSpace) (tyline:later)
if updatefile
then do let fb = fn ++ "~"
runIO $ writeSource fb (unlines (before ++ nonblank)
++ extras ++
(if null extras then ""
else "\n" ++ unlines rest))
runIO $ copyFile fb fn
else iPrintResult extras
where showPat = show . stripNS
stripNS tm = mapPT dens tm where
dens (PRef fc hls n) = PRef fc hls (nsroot n)
dens t = t
nsroot (NS n _) = nsroot n
nsroot (SN (WhereN _ _ n)) = nsroot n
nsroot n = n
getAppName (PApp _ r _) = getAppName r
getAppName (PRef _ _ r) = r
getAppName (PTyped n _) = getAppName n
getAppName _ = n
makeIndent ind | ".lidr" `isSuffixOf` fn = '>' : ' ' : replicate (ind-2) ' '
| otherwise = replicate ind ' '
showNew nm i ind (tm : tms)
= do (nm', i') <- getUniq nm i
rest <- showNew nm i' ind tms
return (makeIndent ind ++
showPat tm ++ " = ?" ++ nm' ++
(if null rest then "" else
"\n" ++ rest))
showNew nm i _ [] = return ""
getIndent i n [] = 0
getIndent i n xs | take (length n) xs == n = i
getIndent i n (x : xs) = getIndent (i + 1) n xs
makeWith :: FilePath -> Bool -> Int -> Name -> Idris ()
makeWith fn updatefile l n
= do src <- runIO $ readSource fn
let (before, tyline : later) = splitAt (l-1) (lines src)
let ind = getIndent tyline
let with = mkWith tyline n
-- add clause before first blank line in 'later',
-- or (TODO) before first line with same indentation as tyline
let (nonblank, rest) = span (\x -> not (all isSpace x) &&
not (ind == getIndent x)) later
if updatefile then
do let fb = fn ++ "~"
runIO $ writeSource fb (unlines (before ++ nonblank)
++ with ++ "\n" ++
unlines rest)
runIO $ copyFile fb fn
else iPrintResult with
where getIndent s = length (takeWhile isSpace s)
-- Replace the given metavariable on the given line with a 'case'
-- block, using a _ for the scrutinee
makeCase :: FilePath -> Bool -> Int -> Name -> Idris ()
makeCase fn updatefile l n
= do src <- runIO $ readSource fn
let (before, tyline : later) = splitAt (l-1) (lines src)
let newcase = addCaseSkel (show n) tyline
if updatefile then
do let fb = fn ++ "~"
runIO $ writeSource fb (unlines (before ++ newcase ++ later))
runIO $ copyFile fb fn
else iPrintResult (showSep "\n" newcase ++"\n")
where addCaseSkel n line =
let b = brackets False line in
case findSubstr ('?':n) line of
Just (before, pos, after) ->
[before ++ (if b then "(" else "") ++ "case _ of",
take (pos + (if b then 6 else 5)) (repeat ' ') ++
"case_val => ?" ++ n ++ (if b then ")" else "")
++ after]
Nothing -> fail "No such metavariable"
-- Assume case needs to be bracketed unless the metavariable is
-- on its own after an =
brackets eq line | line == '?' : show n = not eq
brackets eq ('=':ls) = brackets True ls
brackets eq (' ':ls) = brackets eq ls
brackets eq (l : ls) = brackets False ls
brackets eq [] = True
findSubstr n xs = findSubstr' [] 0 n xs
findSubstr' acc i n xs | take (length n) xs == n
= Just (reverse acc, i, drop (length n) xs)
findSubstr' acc i n [] = Nothing
findSubstr' acc i n (x : xs) = findSubstr' (x : acc) (i + 1) n xs
doProofSearch :: FilePath -> Bool -> Bool ->
Int -> Name -> [Name] -> Maybe Int -> Idris ()
doProofSearch fn updatefile rec l n hints Nothing
= doProofSearch fn updatefile rec l n hints (Just 20)
doProofSearch fn updatefile rec l n hints (Just depth)
= do src <- runIO $ readSource fn
let (before, tyline : later) = splitAt (l-1) (lines src)
ctxt <- getContext
mn <- case lookupNames n ctxt of
[x] -> return x
[] -> return n
ns -> ierror (CantResolveAlts ns)
i <- getIState
let (top, envlen, psnames, _)
= case lookup mn (idris_metavars i) of
Just (t, e, ns, False) -> (t, e, ns, False)
_ -> (Nothing, 0, [], True)
let fc = fileFC fn
let body t = PProof [Try (TSeq Intros (ProofSearch rec False depth t psnames hints))
(ProofSearch rec False depth t psnames hints)]
let def = PClause fc mn (PRef fc [] mn) [] (body top) []
newmv <- idrisCatch
(do elabDecl' EAll recinfo (PClauses fc [] mn [def])
(tm, ty) <- elabVal recinfo ERHS (PRef fc [] mn)
ctxt <- getContext
i <- getIState
return . flip displayS "" . renderPretty 1.0 80 $
pprintPTerm defaultPPOption [] [] (idris_infixes i)
(stripNS
(dropCtxt envlen
(delab i (fst (specialise ctxt [] [(mn, 1)] tm))))))
(\e -> return ("?" ++ show n))
if updatefile then
do let fb = fn ++ "~"
runIO $ writeSource fb (unlines before ++
updateMeta False tyline (show n) newmv ++ "\n"
++ unlines later)
runIO $ copyFile fb fn
else iPrintResult newmv
where dropCtxt 0 sc = sc
dropCtxt i (PPi _ _ _ _ sc) = dropCtxt (i - 1) sc
dropCtxt i (PLet _ _ _ _ _ sc) = dropCtxt (i - 1) sc
dropCtxt i (PLam _ _ _ _ sc) = dropCtxt (i - 1) sc
dropCtxt _ t = t
stripNS tm = mapPT dens tm where
dens (PRef fc hls n) = PRef fc hls (nsroot n)
dens t = t
nsroot (NS n _) = nsroot n
nsroot (SN (WhereN _ _ n)) = nsroot n
nsroot n = n
updateMeta brack ('?':cs) n new
| length cs >= length n
= case splitAt (length n) cs of
(mv, c:cs) ->
if ((isSpace c || c == ')' || c == '}') && mv == n)
then addBracket brack new ++ (c : cs)
else '?' : mv ++ c : updateMeta True cs n new
(mv, []) -> if (mv == n) then addBracket brack new else '?' : mv
updateMeta brack ('=':cs) n new = '=':updateMeta False cs n new
updateMeta brack (c:cs) n new
= c : updateMeta (brack || not (isSpace c)) cs n new
updateMeta brack [] n new = ""
checkProv line n = isProv' False line n
where
isProv' p cs n | take (length n) cs == n = p
isProv' _ ('?':cs) n = isProv' False cs n
isProv' _ ('{':cs) n = isProv' True cs n
isProv' _ ('}':cs) n = isProv' True cs n
isProv' p (_:cs) n = isProv' p cs n
isProv' _ [] n = False
addBracket False new = new
addBracket True new@('(':xs) | last xs == ')' = new
addBracket True new | any isSpace new = '(' : new ++ ")"
| otherwise = new
makeLemma :: FilePath -> Bool -> Int -> Name -> Idris ()
makeLemma fn updatefile l n
= do src <- runIO $ readSource fn
let (before, tyline : later) = splitAt (l-1) (lines src)
-- if the name is in braces, rather than preceded by a ?, treat it
-- as a lemma in a provisional definition
let isProv = checkProv tyline (show n)
ctxt <- getContext
(fname, mty) <- case lookupTyName n ctxt of
[t] -> return t
[] -> ierror (NoSuchVariable n)
ns -> ierror (CantResolveAlts (map fst ns))
i <- getIState
margs <- case lookup fname (idris_metavars i) of
Just (_, arity, _, _) -> return arity
_ -> return (-1)
if (not isProv) then do
let skip = guessImps i (tt_ctxt i) mty
let classes = guessClasses i (tt_ctxt i) mty
let lem = show n ++ " : " ++
constraints i classes mty ++
showTmOpts (defaultPPOption { ppopt_pinames = True })
(stripMNBind skip margs (delab i mty))
let lem_app = show n ++ appArgs skip margs mty
if updatefile then
do let fb = fn ++ "~"
runIO $ writeSource fb (addLem before tyline lem lem_app later)
runIO $ copyFile fb fn
else case idris_outputmode i of
RawOutput _ -> iPrintResult $ lem ++ "\n" ++ lem_app
IdeMode n h ->
let good = SexpList [SymbolAtom "ok",
SexpList [SymbolAtom "metavariable-lemma",
SexpList [SymbolAtom "replace-metavariable",
StringAtom lem_app],
SexpList [SymbolAtom "definition-type",
StringAtom lem]]]
in runIO . hPutStrLn h $ convSExp "return" good n
else do -- provisional definition
let lem_app = show n ++ appArgs [] (-1) mty ++
" = ?" ++ show n ++ "_rhs"
if updatefile then
do let fb = fn ++ "~"
runIO $ writeSource fb (addProv before tyline lem_app later)
runIO $ copyFile fb fn
else case idris_outputmode i of
RawOutput _ -> iPrintResult $ lem_app
IdeMode n h ->
let good = SexpList [SymbolAtom "ok",
SexpList [SymbolAtom "provisional-definition-lemma",
SexpList [SymbolAtom "definition-clause",
StringAtom lem_app]]]
in runIO . hPutStrLn h $ convSExp "return" good n
where getIndent s = length (takeWhile isSpace s)
appArgs skip 0 _ = ""
appArgs skip i (Bind n@(UN c) (Pi _ _ _) sc)
| (thead c /= '_' && n `notElem` skip)
= " " ++ show n ++ appArgs skip (i - 1) sc
appArgs skip i (Bind _ (Pi _ _ _) sc) = appArgs skip (i - 1) sc
appArgs skip i _ = ""
stripMNBind _ args t | args <= 0 = t
stripMNBind skip args (PPi b n@(UN c) _ ty sc)
| n `notElem` skip ||
take 4 (str c) == "__pi" -- keep in type, but not in app
= PPi b n NoFC ty (stripMNBind skip (args - 1) sc)
stripMNBind skip args (PPi b _ _ ty sc) = stripMNBind skip (args - 1) sc
stripMNBind skip args t = t
constraints :: IState -> [Name] -> Type -> String
constraints i [] ty = ""
constraints i [n] ty = showSep ", " (showConstraints i [n] ty) ++ " => "
constraints i ns ty = "(" ++ showSep ", " (showConstraints i ns ty) ++ ") => "
showConstraints i ns (Bind n (Pi _ ty _) sc)
| n `elem` ns = show (delab i ty) :
showConstraints i ns (substV (P Bound n Erased) sc)
| otherwise = showConstraints i ns (substV (P Bound n Erased) sc)
showConstraints _ _ _ = []
-- Guess which binders should be implicits in the generated lemma.
-- Make them implicit if they appear guarded by a top level constructor,
-- or at the top level themselves.
-- Also, make type class instances implicit
guessImps :: IState -> Context -> Term -> [Name]
-- machine names aren't lifted
guessImps ist ctxt (Bind n@(MN _ _) (Pi _ ty _) sc)
= n : guessImps ist ctxt sc
guessImps ist ctxt (Bind n (Pi _ ty _) sc)
| guarded ctxt n (substV (P Bound n Erased) sc)
= n : guessImps ist ctxt sc
| isClass ist ty
= n : guessImps ist ctxt sc
| TType _ <- ty = n : guessImps ist ctxt sc
| ignoreName n = n : guessImps ist ctxt sc
| otherwise = guessImps ist ctxt sc
guessImps ist ctxt _ = []
-- TMP HACK unusable name so don't lift
ignoreName n = case show n of
"_aX" -> True
_ -> False
guessClasses :: IState -> Context -> Term -> [Name]
guessClasses ist ctxt (Bind n (Pi _ ty _) sc)
| isParamClass ist ty
= n : guessClasses ist ctxt sc
| otherwise = guessClasses ist ctxt sc
guessClasses ist ctxt _ = []
isClass ist t
| (P _ n _, args) <- unApply t
= case lookupCtxtExact n (idris_classes ist) of
Just _ -> True
_ -> False
| otherwise = False
isParamClass ist t
| (P _ n _, args) <- unApply t
= case lookupCtxtExact n (idris_classes ist) of
Just _ -> any isV args
_ -> False
| otherwise = False
where isV (V _) = True
isV _ = False
guarded ctxt n (P _ n' _) | n == n' = True
guarded ctxt n ap@(App _ _ _)
| (P _ f _, args) <- unApply ap,
isConName f ctxt = any (guarded ctxt n) args
-- guarded ctxt n (Bind (UN cn) (Pi t) sc) -- ignore shadows
-- | thead cn /= '_' = guarded ctxt n t || guarded ctxt n sc
guarded ctxt n (Bind _ (Pi _ t _) sc)
= guarded ctxt n t || guarded ctxt n sc
guarded ctxt n _ = False
blank = all isSpace
addLem before tyline lem lem_app later
= let (bef_end, blankline : bef_start)
= case span (not . blank) (reverse before) of
(bef, []) -> (bef, "" : [])
x -> x
mvline = updateMeta False tyline (show n) lem_app in
unlines $ reverse bef_start ++
[blankline, lem, blankline] ++
reverse bef_end ++ mvline : later
addProv before tyline lem_app later
= let (later_bef, blankline : later_end)
= case span (not . blank) later of
(bef, []) -> (bef, "" : [])
x -> x in
unlines $ before ++ tyline :
(later_bef ++ [blankline, lem_app, blankline] ++
later_end)
| mrmonday/Idris-dev | src/Idris/Interactive.hs | bsd-3-clause | 19,791 | 3 | 25 | 8,264 | 6,817 | 3,348 | 3,469 | 381 | 30 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE TypeFamilies #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.String
-- Copyright : (c) The University of Glasgow 2007
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- The @String@ type and associated operations.
--
-----------------------------------------------------------------------------
module Data.String (
String
, IsString(..)
-- * Functions on strings
, lines
, words
, unlines
, unwords
) where
import GHC.Base
import Data.Functor.Const (Const (Const))
import Data.Functor.Identity (Identity (Identity))
import Data.List (lines, words, unlines, unwords)
-- | Class for string-like datastructures; used by the overloaded string
-- extension (-XOverloadedStrings in GHC).
class IsString a where
fromString :: String -> a
{- Note [IsString String]
~~~~~~~~~~~~~~~~~~~~~~~~~
Previously, the IsString instance that covered String was a flexible
instance for [Char]. This is in some sense the most accurate choice,
but there are cases where it can lead to an ambiguity, for instance:
show $ "foo" ++ "bar"
The use of (++) ensures that "foo" and "bar" must have type [t] for
some t, but a flexible instance for [Char] will _only_ match if
something further determines t to be Char, and nothing in the above
example actually does.
So, the above example generates an error about the ambiguity of t,
and what's worse, the above behavior can be generated by simply
typing:
"foo" ++ "bar"
into GHCi with the OverloadedStrings extension enabled.
The new instance fixes this by defining an instance that matches all
[a], and forces a to be Char. This instance, of course, overlaps
with things that the [Char] flexible instance doesn't, but this was
judged to be an acceptable cost, for the gain of providing a less
confusing experience for people experimenting with overloaded strings.
It may be possible to fix this via (extended) defaulting. Currently,
the rules are not able to default t to Char in the above example. If
a more flexible system that enabled this defaulting were put in place,
then it would probably make sense to revert to the flexible [Char]
instance, since extended defaulting is enabled in GHCi. However, it
is not clear at the time of this note exactly what such a system
would be, and it certainly hasn't been implemented.
A test case (should_run/overloadedstringsrun01.hs) has been added to
ensure the good behavior of the above example remains in the future.
-}
-- | @(a ~ Char)@ context was introduced in @4.9.0.0@
--
-- @since 2.01
instance (a ~ Char) => IsString [a] where
-- See Note [IsString String]
fromString xs = xs
-- | @since 4.9.0.0
deriving instance IsString a => IsString (Const a b)
-- | @since 4.9.0.0
deriving instance IsString a => IsString (Identity a)
| sdiehl/ghc | libraries/base/Data/String.hs | bsd-3-clause | 3,127 | 0 | 7 | 539 | 205 | 130 | 75 | 23 | 0 |
module ShouldSucceed where
w = a where a = y
y = 2
| ghc-android/ghc | testsuite/tests/typecheck/should_compile/tc018.hs | bsd-3-clause | 64 | 0 | 6 | 26 | 21 | 13 | 8 | 3 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE DeriveLift #-}
module Language.HigherRank.TH (exprQ, typeQ) where
import Language.Haskell.TH.Quote
import Language.Haskell.TH.Syntax (Lift(..))
import Language.HigherRank.Parse
import Language.HigherRank.Types
deriving instance Lift EVar
deriving instance Lift Expr
deriving instance Lift TEVar
deriving instance Lift TVar
deriving instance Lift Type
voidQ :: QuasiQuoter
voidQ = QuasiQuoter
{ quoteExp = fail "cannot be used in expression position"
, quotePat = fail "cannot be used in pattern position"
, quoteType = fail "cannot be used in type position"
, quoteDec = fail "cannot be used in declaration position"
}
exprQ :: QuasiQuoter
exprQ = voidQ { quoteExp = either fail lift . parseExpr }
typeQ :: QuasiQuoter
typeQ = voidQ { quoteExp = either fail lift . parseType }
| lexi-lambda/higher-rank | test-suite/Language/HigherRank/TH.hs | isc | 845 | 0 | 8 | 136 | 194 | 113 | 81 | -1 | -1 |
-- Sum of all the multiples of 3 or 5
-- https://www.codewars.com/kata/57f36495c0bb25ecf50000e7
module SumOfMultiples where
findSum n = f 5 n + f 3 n - f 15 n
where f d n = let a = (n `div` d) in (a * d * succ a) `div` 2
| gafiatulin/codewars | src/7 kyu/SumOfMultiples.hs | mit | 227 | 0 | 12 | 55 | 89 | 47 | 42 | 3 | 1 |
{-# LANGUAGE NoStarIsType #-}
{-# LANGUAGE TypeFamilies, KindSignatures, DataKinds, TypeOperators #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ForeignFunctionInterface #-}
module AI.Funn.Flat.LSTM (lstmDiff) where
import GHC.TypeLits
import Control.Applicative
import Data.Foldable
import Data.Traversable
import Data.Monoid
import Data.Proxy
import Data.Random
import Control.DeepSeq
import qualified Data.Vector.Generic as V
import qualified Data.Vector.Storable as S
import qualified Data.Vector.Storable.Mutable as M
import Foreign.C
import Foreign.Ptr
import System.IO.Unsafe
import AI.Funn.Diff.Diff (Derivable(..), Additive(..), Diff(..))
import AI.Funn.Flat.Blob (Blob(..), blob, getBlob)
import qualified AI.Funn.Flat.Blob as Blob
foreign import ccall "lstm_forward" lstmForwardFFI :: CInt -> Ptr Double -> Ptr Double -> Ptr Double -> Ptr Double -> Ptr Double -> Ptr Double -> IO ()
foreign import ccall "lstm_backward" lstmBackwardFFI :: CInt -> Ptr Double -> Ptr Double -> Ptr Double -> Ptr Double -> Ptr Double -> Ptr Double -> Ptr Double -> IO ()
{-# NOINLINE lstmForward #-}
lstmForward :: Int -> S.Vector Double -> S.Vector Double -> S.Vector Double ->
(S.Vector Double, S.Vector Double, S.Vector Double)
lstmForward n ps hs xs = unsafePerformIO $ do target_hs <- M.replicate n 0 :: IO (M.IOVector Double)
target_ys <- M.replicate n 0 :: IO (M.IOVector Double)
target_store <- M.replicate (8*n) 0 :: IO (M.IOVector Double)
S.unsafeWith hs $ \hbuf -> do
S.unsafeWith ps $ \pbuf -> do
S.unsafeWith xs $ \xbuf -> do
M.unsafeWith target_hs $ \thbuf -> do
M.unsafeWith target_ys $ \tybuf -> do
M.unsafeWith target_store $ \tsbuf -> do
lstmForwardFFI (fromIntegral n) pbuf hbuf xbuf thbuf tybuf tsbuf
new_hs <- V.unsafeFreeze target_hs
new_ys <- V.unsafeFreeze target_ys
store <- V.unsafeFreeze target_store
return (new_hs, new_ys, store)
{-# NOINLINE lstmBackward #-}
lstmBackward :: Int -> S.Vector Double -> S.Vector Double -> S.Vector Double -> S.Vector Double ->
(S.Vector Double, S.Vector Double, S.Vector Double)
lstmBackward n ps store delta_h delta_y = unsafePerformIO $ do
target_d_ws <- M.replicate (2*n) 0 :: IO (M.IOVector Double)
target_d_hs <- M.replicate n 0 :: IO (M.IOVector Double)
target_d_xs <- M.replicate (4*n) 0 :: IO (M.IOVector Double)
S.unsafeWith ps $ \pbuf -> do
S.unsafeWith store $ \sbuf -> do
S.unsafeWith delta_h $ \dbuf -> do
S.unsafeWith delta_y $ \dybuf -> do
M.unsafeWith target_d_ws $ \dwbuf -> do
M.unsafeWith target_d_hs $ \dhbuf -> do
M.unsafeWith target_d_xs $ \dxbuf -> do
lstmBackwardFFI (fromIntegral n) pbuf sbuf dbuf dybuf dwbuf dhbuf dxbuf
d_ws <- V.unsafeFreeze target_d_ws
d_hs <- V.unsafeFreeze target_d_hs
d_xs <- V.unsafeFreeze target_d_xs
return (d_ws, d_hs, d_xs)
lstmDiff :: forall n m. (Monad m, KnownNat n) => Diff m (Blob (2*n), (Blob n, Blob (4*n))) (Blob n, Blob n)
lstmDiff = Diff run
where
run (par, (hidden, inputs)) =
let (new_h, new_y, store) = (lstmForward n (getBlob par)
(getBlob hidden)
(getBlob inputs))
backward (dh, dy) = let (d_ws, d_hs, d_xs) = (lstmBackward n (getBlob par)
store (getBlob dh) (getBlob dy))
in return (blob d_ws, (blob d_hs, blob d_xs))
in return ((blob new_h, blob new_y), backward)
n :: Int
n = fromIntegral (natVal (Proxy :: Proxy n))
| nshepperd/funn | AI/Funn/Flat/LSTM.hs | mit | 4,367 | 0 | 38 | 1,567 | 1,331 | 680 | 651 | 73 | 1 |
module Y2016.M08.D04.Exercise where
{--
So, today we ask, "How do we solve a problem like Maria?"
No, wait. That's the wrong movie.
Okay, so, before we solved rows of sums that were either unconstrained or were
completely constrained, that is: we solved the summer-problem (unconstrained
values to sum to a total), or we solved the schema-problem that gave free slots
and slots that had a known value already.
Fine. Good.
Now we look at constraining a cell to a set of values. How do we do that?
Let's look at a particular example.
Let's say we have a sum 20 of three slots, ... easy enough.
But crossing that sum in the first column is a sum of 16 of two slots, ... okay
AND in the second column is a sum of 4 of two slots.
So, our simple sum 20 of three slots is a bit more constrained now
slot 1 can be 7 or 9 (because ...?)
slot 2 can be 1 or 3 (because ...?)
and slot 3 is unconstrained
given that no number is the same as any other in the sum.
How do we roll these constraints into our solver?
Let's do that today.
--}
data Cell = Unconstrained | ConstrainedTo [Int] | Known Int
deriving (Eq, Ord, Show)
type Schema = [Cell]
type Schemata = [Schema]
solver :: Schema -> Int -> Schemata
solver = undefined
-- Given the above definition of solver, what are the solutions for:
constrainedRows :: [(Schema, Int)]
constrainedRows =
[([ConstrainedTo [7,9], ConstrainedTo [1,3], Unconstrained], 20), -- 1
([Unconstrained, ConstrainedTo [8,9], ConstrainedTo [1,3]], 13), -- 2
([Unconstrained, ConstrainedTo [8,9], ConstrainedTo [1,3]], 20), -- 3
(replicate 4 Unconstrained, 25)] -- 4
-- The solution for -- 1 should return a value:
-- [[Known 9, Known 3, Known 8]]
| geophf/1HaskellADay | exercises/HAD/Y2016/M08/D04/Exercise.hs | mit | 1,735 | 0 | 9 | 370 | 228 | 142 | 86 | 13 | 1 |
-- |
-- Module : Toy.Cryptogram.Dictionary
-- Description : Cryptogram Dictionary
-- License : MIT License
-- Maintainer : Isaac Azuelos
{-# LANGUAGE OverloadedStrings #-}
module Toy.Cryptogram.Dictionary
( Dictionary (Dictionary)
, defaultPath
, empty
, fromWords
, toWords
, lookup
, Fingerprint
, fingerprint
)
where
import Prelude hiding (lookup)
import Data.Maybe (fromMaybe)
import qualified Data.Char as Char
import qualified Data.Map as Map
import qualified Data.Text as Text
import qualified Data.Vector as Vector
-- | The default dictionary location.
defaultPath :: FilePath
defaultPath = "/usr/share/dict/words"
-- | A dictionary is a data structure lets us look up all words which could
-- concieveably map to eachother by some substitution cypher.
data Dictionary = Dictionary (Map.Map Fingerprint [Text.Text]) deriving (Eq)
instance Show Dictionary where
show = (++) "toWords " . show . toWords
-- | An empty dictionary containing no words.
empty :: Dictionary
empty = Dictionary mempty
-- | Look up a word in the dictionary, to get all other words which it could be
-- under application of some key.
lookup :: Dictionary -> Text.Text -> [Text.Text]
lookup (Dictionary m) t = filter (/= t)
$ fromMaybe [] (fingerprint t >>= flip Map.lookup m)
-- | Build a dictionary from a list of words.
fromWords :: [Text.Text] -> Dictionary
fromWords ws = Dictionary $ foldr insertWord mempty ws
where insertWord w m = case fingerprint w of
Nothing -> m
Just f -> Map.insertWith mappend f (return w) m
-- | Pull out all the words in a @Dictionary@.
toWords :: Dictionary -> [Text.Text]
toWords (Dictionary d) = concat $ Map.elems d
-- | Fingerprints are just a vector where each character is mapped to the index
-- of it's first appearence.
newtype Fingerprint = FP (Vector.Vector Int) deriving (Show, Eq, Ord)
-- | Each word has a fingerprint, but they're not all unique. Two words which
-- can be made the same by the applicaiton of some key have the same
-- fingerprint.
fingerprint :: Text.Text -> Maybe Fingerprint
fingerprint t = FP <$> Vector.foldr ((=<<) . append) (Just mempty) chars
where
chars = Vector.fromList (Text.unpack t)
append c v
| Char.isAsciiUpper c = flip Vector.cons v <$> Vector.elemIndex c chars
| otherwise = Nothing
| isaacazuelos/cryptogram | src/Toy/Cryptogram/Dictionary.hs | mit | 2,442 | 0 | 12 | 564 | 528 | 294 | 234 | 43 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
module Console.GitHubStats
( fetchRepos
) where
import Control.Monad
import Data.Maybe
import Data.Text (Text)
import Network.HTTP.Req
import Numeric.Natural
import Console.GitHubStats.Types
fetchRepos :: MonadHttp m
=> Text -- ^ Github organization name
-> m [Repository]
fetchRepos orgName = do
numberOfRepos <- fetchNumberOfRepos orgName
let pages = countPages numberOfRepos
repos <- forM [1..pages] (fetchReposByPage orgName)
return $ concat repos
where
countPages numberOfRepos =
ceiling $ toFloat numberOfRepos / toFloat perPage
toFloat = fromIntegral :: (Natural -> Float)
fetchReposByPage :: MonadHttp m
=> Text
-> Natural
-> m [Repository]
fetchReposByPage orgName page = do
let listReposUrl = gitHubApiUrl /: "orgs" /: orgName /: "repos"
params = "per_page" =: perPage <>
"page" =: page <>
header "User-Agent" "github-stats"
repos <- req GET listReposUrl NoReqBody jsonResponse params
return $ responseBody repos
fetchNumberOfRepos :: MonadHttp m
=> Text
-> m Natural
fetchNumberOfRepos orgName = do
let listReposUrl = gitHubApiUrl /: "orgs" /: orgName
params = header "User-Agent" "github-stats"
repos <- req GET listReposUrl NoReqBody jsonResponse params
return $ fromMaybe 0 . orgPublicRepos $ responseBody repos
gitHubApiUrl :: Url 'Https
gitHubApiUrl = https "api.github.com"
perPage :: Natural
perPage = 100
| acamino/ghs | src/Console/GitHubStats.hs | mit | 1,614 | 0 | 13 | 418 | 407 | 203 | 204 | 44 | 1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.FontLoader
(js_checkFont, checkFont, js_loadFont, loadFont,
js_notifyWhenFontsReady, notifyWhenFontsReady, loading,
loadingDone, loadStart, load, error, js_getLoading, getLoading,
FontLoader, castToFontLoader, gTypeFontLoader)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSRef(..), JSString, castRef)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSRef(..), FromJSRef(..))
import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.Enums
foreign import javascript unsafe
"($1[\"checkFont\"]($2,\n$3) ? 1 : 0)" js_checkFont ::
JSRef FontLoader -> JSString -> JSString -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/FontLoader.checkFont Mozilla FontLoader.checkFont documentation>
checkFont ::
(MonadIO m, ToJSString font, ToJSString text) =>
FontLoader -> font -> text -> m Bool
checkFont self font text
= liftIO
(js_checkFont (unFontLoader self) (toJSString font)
(toJSString text))
foreign import javascript unsafe "$1[\"loadFont\"]($2)" js_loadFont
:: JSRef FontLoader -> JSRef Dictionary -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/FontLoader.loadFont Mozilla FontLoader.loadFont documentation>
loadFont ::
(MonadIO m, IsDictionary params) =>
FontLoader -> Maybe params -> m ()
loadFont self params
= liftIO
(js_loadFont (unFontLoader self)
(maybe jsNull (unDictionary . toDictionary) params))
foreign import javascript unsafe "$1[\"notifyWhenFontsReady\"]($2)"
js_notifyWhenFontsReady ::
JSRef FontLoader -> JSRef VoidCallback -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/FontLoader.notifyWhenFontsReady Mozilla FontLoader.notifyWhenFontsReady documentation>
notifyWhenFontsReady ::
(MonadIO m) => FontLoader -> Maybe VoidCallback -> m ()
notifyWhenFontsReady self callback
= liftIO
(js_notifyWhenFontsReady (unFontLoader self)
(maybe jsNull pToJSRef callback))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/FontLoader.onloading Mozilla FontLoader.onloading documentation>
loading :: EventName FontLoader Event
loading = unsafeEventName (toJSString "loading")
-- | <https://developer.mozilla.org/en-US/docs/Web/API/FontLoader.onloadingdone Mozilla FontLoader.onloadingdone documentation>
loadingDone :: EventName FontLoader Event
loadingDone = unsafeEventName (toJSString "loadingdone")
-- | <https://developer.mozilla.org/en-US/docs/Web/API/FontLoader.onloadstart Mozilla FontLoader.onloadstart documentation>
loadStart :: EventName FontLoader ProgressEvent
loadStart = unsafeEventName (toJSString "loadstart")
-- | <https://developer.mozilla.org/en-US/docs/Web/API/FontLoader.onload Mozilla FontLoader.onload documentation>
load :: EventName FontLoader UIEvent
load = unsafeEventName (toJSString "load")
-- | <https://developer.mozilla.org/en-US/docs/Web/API/FontLoader.onerror Mozilla FontLoader.onerror documentation>
error :: EventName FontLoader UIEvent
error = unsafeEventName (toJSString "error")
foreign import javascript unsafe "($1[\"loading\"] ? 1 : 0)"
js_getLoading :: JSRef FontLoader -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/FontLoader.loading Mozilla FontLoader.loading documentation>
getLoading :: (MonadIO m) => FontLoader -> m Bool
getLoading self = liftIO (js_getLoading (unFontLoader self)) | plow-technologies/ghcjs-dom | src/GHCJS/DOM/JSFFI/Generated/FontLoader.hs | mit | 4,077 | 32 | 11 | 587 | 844 | 481 | 363 | 62 | 1 |
{-# LANGUAGE Trustworthy #-}
{- |
Module : Surge
Copyright : (c) 2014 Kyle Van Berendonck
License : MIT
Maintainer : [email protected]
Stability : experimental
Portability : portable
This is a convenience module. Importing this module will automatically import in all the modules
you might require to build servers with Surge.
-}
module Surge
( -- * Exports
module Surge.Stage
, module Surge.Network
-- * Other
-- $other
, module Pipes
, module Pipes.Binary
) where
import Surge.Stage
import Surge.Network
import Pipes
(Pipe, Producer, Consumer, await, yield)
import Pipes.Binary
(Get, Put, Binary, get, put)
{- $other
[From "Pipes"]
'Pipe',
'Producer',
'Consumer',
'await',
'yield'.
[From "Pipes.Binary"]
'Get',
'Put',
'Binary',
'get',
'put'.
-}
| kvanberendonck/surge | src/Surge.hs | mit | 867 | 0 | 5 | 226 | 86 | 58 | 28 | 13 | 0 |
{- |
Module : ./Static/WACocone.hs
Description : heterogeneous signatures colimits approximations
Copyright : (c) Mihai Codescu, and Uni Bremen 2002-2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : non-portable
Heterogeneous version of weakly_amalgamable_cocones.
Needs some improvements (see TO DO).
-}
module Static.WACocone (isConnected,
isAcyclic,
isThin,
removeIdentities,
hetWeakAmalgCocone,
initDescList,
dijkstra,
buildStrMorphisms,
weakly_amalgamable_colimit
) where
import Control.Monad
import Data.List (nub)
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Graph.Inductive.Graph as Graph
import Common.Lib.Graph as Tree
import Common.ExtSign
import Common.Result
import Common.LogicT
import Logic.Logic
import Logic.Comorphism
import Logic.Modification
import Logic.Grothendieck
import Logic.Coerce
import Static.GTheory
import Comorphisms.LogicGraph
weakly_amalgamable_colimit :: StaticAnalysis lid
basic_spec sentence symb_items symb_map_items
sign morphism symbol raw_symbol
=> lid -> Tree.Gr sign (Int, morphism)
-> Result (sign, Map.Map Int morphism)
weakly_amalgamable_colimit l diag = do
(sig, sink) <- signature_colimit l diag
return (sig, sink)
{- until amalgamability check is fixed, just return a colimit
get (commented out) code from rev:11881 -}
-- | checks whether a graph is connected
isConnected :: Gr a b -> Bool
isConnected graph = let
nodeList = nodes graph
root = head nodeList
availNodes = Map.fromList $ zip nodeList (repeat True)
bfs queue avail = case queue of
[] -> avail
n : ns -> let
avail1 = Map.insert n False avail
nbs = filter (\ x -> Map.findWithDefault (error "isconnected") x avail)
$ neighbors graph n
in bfs (ns ++ nbs) avail1
in not $ any (\ x -> Map.findWithDefault (error "iscon 2") x
(bfs [root] availNodes)) nodeList
-- | checks whether the graph is thin
isThin :: Gr a b -> Bool
isThin = checkThinness Map.empty . edges
checkThinness :: Map.Map Edge Int -> [Edge] -> Bool
checkThinness paths eList =
case eList of
[] -> True
(sn, tn) : eList' ->
(sn, tn) `notElem` Map.keys paths &&
-- multiple paths between (sn, tn)
let pathsToS = filter (\ (_, y) -> y == sn) $ Map.keys paths
updatePaths pathF dest pList =
case pList of
[] -> Just pathF
(x, _) : pList' ->
if (x, dest) `elem` Map.keys pathF then Nothing
else updatePaths (Map.insert (x, dest) 1 pathF) dest pList'
in case updatePaths paths tn pathsToS of
Nothing -> False
Just paths' -> checkThinness (Map.insert (sn, tn) 1 paths') eList'
-- | checks whether a graph is acyclic
isAcyclic :: (Eq b) => Gr a b -> Bool
isAcyclic graph = let
filterIns gr = filter (\ x -> indeg gr x == 0)
queue = filterIns graph $ nodes graph
topologicalSort q gr = case q of
[] -> null $ edges gr
n : ns -> let
oEdges = lsuc gr n
graph1 = foldl (flip Graph.delLEdge) gr
$ map (\ (y, label) -> (n, y, label)) oEdges
succs = filterIns graph1 $ suc gr n
in topologicalSort (ns ++ succs) graph1
in topologicalSort queue graph
-- | auxiliary for removing the identity edges from a graph
removeIdentities :: Gr a b -> Gr a b
removeIdentities graph = let
addEdges gr eList = case eList of
[] -> gr
(sn, tn, label) : eList1 -> if sn == tn then addEdges gr eList1
else addEdges (insEdge (sn, tn, label) gr) eList1
in addEdges (insNodes (labNodes graph) Graph.empty) $ labEdges graph
-- assigns to a node all proper descendents
initDescList :: (Eq a, Eq b) => Gr a b -> Map.Map Node [(Node, a)]
initDescList graph = let
descsOf n = let
nodeList = filter (n /=) $ pre graph n
f = Map.fromList $ zip nodeList (repeat False)
precs nList nList' avail =
case nList of
[] -> nList'
_ -> let
nList'' = concatMap (\ y -> filter
(\ x -> x `notElem` Map.keys avail ||
Map.findWithDefault (error "iDL") x avail) $
filter (y /=) $ pre graph y) nList
avail' = Map.union avail $
Map.fromList $ zip nList'' (repeat False)
in precs (nub nList'') (nub $ nList' ++ nList'') avail'
in precs nodeList nodeList f
in Map.fromList $ map (\ node -> (node, filter (\ x -> fst x `elem`
descsOf node)
$ labNodes graph )) $ nodes graph
commonBounds :: (Eq a) => Map.Map Node [(Node, a)] -> Node -> Node -> [(Node, a)]
commonBounds funDesc n1 n2 = filter
(\ x -> x `elem` (Map.!) funDesc n1 && x `elem` (Map.!) funDesc n2 )
$ nub $ (Map.!) funDesc n1 ++ (Map.!) funDesc n2
-- returns the greatest lower bound of two maximal nodes,if it exists
glb :: (Eq a) => Map.Map Node [(Node, a)] -> Node -> Node -> Maybe (Node, a)
glb funDesc n1 n2 = let
cDescs = commonBounds funDesc n1 n2
subList [] _ = True
subList (x : xs) l2 = x `elem` l2 && subList xs l2
glbList = filter (\ (n, x) -> subList
(filter (\ (n0, x0) -> (n, x) /= (n0, x0)) cDescs) (funDesc Map.! n)
) cDescs
{- a node n is glb of n1 and n2 iff
all common bounds of n1 and n2 are also descendants of n -}
in case glbList of
[] -> Nothing
x : _ -> Just x -- because if it exists, there can be only one
-- if no greatest lower bound exists, compute all maximal bounds of the nodes
maxBounds :: (Eq a) => Map.Map Node [(Node, a)] -> Node -> Node -> [(Node, a)]
maxBounds funDesc n1 n2 = let
cDescs = commonBounds funDesc n1 n2
isDesc n0 (n, y) = (n, y) `elem` funDesc Map.! n0
noDescs (n, y) = not $ any (\ (n0, _) -> isDesc n0 (n, y)) cDescs
in filter noDescs cDescs
-- dijsktra algorithm for finding the the shortest path between two nodes
dijkstra :: GDiagram -> Node -> Node -> Result GMorphism
dijkstra graph source target = do
let
dist = Map.insert source 0 $ Map.fromList $
zip (nodes graph) $ repeat $ 2 * length (edges graph)
prev = if source == target then Map.insert source source Map.empty
else Map.empty
q = nodes graph
com = case lab graph source of
Nothing -> Map.empty -- shouldnt be the case
Just gt -> Map.insert source (ide $ signOf gt) Map.empty
extractMin queue dMap = let
u = head $
filter (\ x -> Map.findWithDefault (error "dijkstra") x dMap ==
minimum
(map (\ x1 -> Map.findWithDefault (error "dijkstra") x1 dMap)
queue))
queue
in ( Set.toList $ Set.difference (Set.fromList queue) (Set.fromList [u]) , u)
updateNeighbors d p c u gr = let
outEdges = out gr u
upNeighbor dMap pMap cMap uNode edgeList = case edgeList of
[] -> (dMap, pMap, cMap)
(_, v, (_, gmor)) : edgeL -> let
alt = Map.findWithDefault (error "dijkstra") uNode dMap + 1
in
if alt >= Map.findWithDefault (error "dijsktra") v dMap then
upNeighbor dMap pMap cMap uNode edgeL
else let
d1 = Map.insert v alt dMap
p1 = Map.insert v uNode pMap
c1 = Map.insert v gmor cMap
in upNeighbor d1 p1 c1 uNode edgeL
in upNeighbor d p c u outEdges
-- for each neighbor of u, if d(u)+1 < d(v), modify p(v) = u, d(v) = d(u)+1
mainloop gr sn tn qL d p c = let
(q1, u) = extractMin qL d
(d1, p1, c1) = updateNeighbors d p c u gr
in if u == tn then shortPath sn p1 c1 [] tn
else mainloop gr sn tn q1 d1 p1 c1
shortPath sn p1 c s u =
if u `notElem` Map.keys p1 then fail "path not found"
else let
x = Map.findWithDefault (error $ show u) u p1 in
if x == sn then return (u : s, c)
else shortPath sn p1 c (u : s) x
(nodeList, com1) <- mainloop graph source target q dist prev com
foldM comp ((Map.!) com1 source) . map ((Map.!) com1) $ nodeList
{- builds the arrows from the nodes of the original graph
to the unique maximal node of the obtained graph -}
buildStrMorphisms :: GDiagram -> GDiagram
-> Result (G_theory, Map.Map Node GMorphism)
buildStrMorphisms initGraph newGraph = do
let (maxNode, sigma) = head $ filter (\ (node, _) -> outdeg newGraph node == 0) $
labNodes newGraph
buildMor pairList solList =
case pairList of
(n, _) : pairs -> do nMor <- dijkstra newGraph n maxNode
buildMor pairs (solList ++ [(n, nMor)])
[] -> return solList
morList <- buildMor (labNodes initGraph) []
return (sigma, Map.fromList morList)
-- computes the colimit and inserts it into the graph
addNodeToGraph :: GDiagram -> G_theory -> G_theory -> G_theory -> Int -> Int
-> Int -> GMorphism -> GMorphism
-> Map.Map Node [(Node, G_theory)] -> [(Int, G_theory)]
-> Result (GDiagram, Map.Map Node [(Node, G_theory)])
addNodeToGraph oldGraph
(G_theory lid _ extSign _ _ _)
gt1@(G_theory lid1 _ extSign1 idx1 _ _)
gt2@(G_theory lid2 _ extSign2 idx2 _ _)
n
n1
n2
(GMorphism cid1 ss1 _ mor1 _)
(GMorphism cid2 ss2 _ mor2 _)
funDesc maxNodes = do
let newNode = 1 + maximum (nodes oldGraph) -- get a new node
s1 <- coerceSign lid1 lid "addToNodeGraph" extSign1
s2 <- coerceSign lid2 lid "addToNodeGraph" extSign2
m1 <- coerceMorphism (targetLogic cid1) lid "addToNodeGraph" mor1
m2 <- coerceMorphism (targetLogic cid2) lid "addToNodeGraph" mor2
let spanGr = Graph.mkGraph
[(n, plainSign extSign), (n1, plainSign s1), (n2, plainSign s2)]
[(n, n1, (1, m1)), (n, n2, (1, m2))]
(sig, morMap) <- weakly_amalgamable_colimit lid spanGr
-- must coerce here
m11 <- coerceMorphism lid (targetLogic cid1) "addToNodeGraph" $
morMap Map.! n1
m22 <- coerceMorphism lid (targetLogic cid2) "addToNodeGraph" $
morMap Map.! n2
let gth = noSensGTheory lid (mkExtSign sig) startSigId
gmor1 = GMorphism cid1 ss1 idx1 m11 startMorId
gmor2 = GMorphism cid2 ss2 idx2 m22 startMorId
case maxNodes of
[] -> do
let newGraph = insEdges [(n1, newNode, (1, gmor1)), (n2, newNode, (1, gmor2))] $
insNode (newNode, gth) oldGraph
funDesc1 = Map.insert newNode
(nub $ (Map.!) funDesc n1 ++ (Map.!) funDesc n2 ) funDesc
return (newGraph, funDesc1)
_ -> computeCoeqs oldGraph funDesc (n1, gt1) (n2, gt2)
(newNode, gth) gmor1 gmor2 maxNodes
{- for each node in the list, check whether the coequalizer can be computed
if so, modify the maximal node of graph and the edges to it from n1 and n2 -}
computeCoeqs :: GDiagram -> Map.Map Node [(Node, G_theory)]
-> (Node, G_theory) -> (Node, G_theory) -> (Node, G_theory)
-> GMorphism -> GMorphism -> [(Node, G_theory)] ->
Result (GDiagram, Map.Map Node [(Node, G_theory)])
computeCoeqs oldGraph funDesc (n1, _) (n2, _) (newN, newGt) gmor1 gmor2 [] = do
let newGraph = insEdges [(n1, newN, (1, gmor1)), (n2, newN, (1, gmor2))] $
insNode (newN, newGt) oldGraph
descFun1 = Map.insert newN
(nub $ (Map.!) funDesc n1 ++ (Map.!) funDesc n2 ) funDesc
return (newGraph, descFun1)
computeCoeqs graph funDesc (n1, gt1) (n2, gt2)
(newN, _newGt@(G_theory tlid _ tsign _ _ _))
_gmor1@(GMorphism cid1 sig1 idx1 mor1 _ )
_gmor2@(GMorphism cid2 sig2 idx2 mor2 _ ) ((n, gt) : descs) = do
_rho1@(GMorphism cid3 _ _ mor3 _) <- dijkstra graph n n1
_rho2@(GMorphism cid4 _ _ mor4 _) <- dijkstra graph n n2
com1 <- compComorphism (Comorphism cid1) (Comorphism cid3)
com2 <- compComorphism (Comorphism cid1) (Comorphism cid3)
if com1 /= com2 then fail "Unable to compute coequalizer" else do
_gtM@(G_theory lidM _ signM _idxM _ _) <- mapG_theory False com1 gt
s1 <- coerceSign lidM tlid "coequalizers" signM
mor3' <- coerceMorphism (targetLogic cid3) (sourceLogic cid1) "coeqs" mor3
mor4' <- coerceMorphism (targetLogic cid4) (sourceLogic cid2) "coeqs" mor4
m1 <- map_morphism cid1 mor3'
m2 <- map_morphism cid2 mor4'
phi1' <- comp m1 mor1
phi2' <- comp m2 mor2
phi1 <- coerceMorphism (targetLogic cid1) tlid "coeqs" phi1'
phi2 <- coerceMorphism (targetLogic cid2) tlid "coeqs" phi2'
-- build the double arrow for computing the coequalizers
let doubleArrow = Graph.mkGraph
[(n, plainSign s1), (newN, plainSign tsign)]
[(n, newN, (1, phi1)), (n, newN, (1, phi2))]
(colS, colM) <- weakly_amalgamable_colimit tlid doubleArrow
let newGt1 = noSensGTheory tlid (mkExtSign colS) startSigId
mor11' <- coerceMorphism tlid (targetLogic cid1) "coeqs" $ (Map.!) colM newN
mor11 <- comp mor1 mor11'
mor22' <- coerceMorphism tlid (targetLogic cid2) "coeqs" $ (Map.!) colM newN
mor22 <- comp mor2 mor22'
let gMor11 = GMorphism cid1 sig1 idx1 mor11 startMorId
let gMor22 = GMorphism cid2 sig2 idx2 mor22 startMorId
computeCoeqs graph funDesc (n1, gt1) (n2, gt2) (newN, newGt1)
gMor11 gMor22 descs
-- returns a maximal node available
pickMaxNode :: (MonadPlus t) => Gr a b -> t (Node, a)
pickMaxNode graph = msum $ map return $
filter (\ (node, _) -> outdeg graph node == 0) $
labNodes graph
{- returns a list of common descendants of two maximal nodes:
one node if a glb exists, or all maximal descendants otherwise -}
commonDesc :: Map.Map Node [(Node, G_theory)] -> Node -> Node
-> [(Node, G_theory)]
commonDesc funDesc n1 n2 = case glb funDesc n1 n2 of
Just x -> [x]
Nothing -> maxBounds funDesc n1 n2
-- returns a weakly amalgamable square of lax triangles
pickSquare :: (MonadPlus t) => Result GMorphism -> Result GMorphism -> t Square
pickSquare (Result _ (Just phi1@(GMorphism cid1 _ _ _ _)))
(Result _ (Just phi2@(GMorphism cid2 _ _ _ _))) =
if isHomogeneous phi1 && isHomogeneous phi2 then
return $ mkIdSquare $ Logic $ sourceLogic cid1
-- since they have the same target, both homogeneous implies same logic
else do
{- if one of them is homogeneous, build the square
with identity modification of the other comorphism -}
let defaultSquare
| isHomogeneous phi1 = [mkDefSquare $ Comorphism cid2]
| isHomogeneous phi2 = [mirrorSquare $ mkDefSquare $ Comorphism cid1]
| otherwise = []
case maybeResult $ lookupSquare_in_LG (Comorphism cid1) (Comorphism cid2) of
Nothing -> msum $ map return defaultSquare
Just sqList -> msum $ map return $ sqList ++ defaultSquare
pickSquare (Result _ Nothing) _ = fail "Error computing comorphisms"
pickSquare _ (Result _ Nothing) = fail "Error computing comorphisms"
-- builds the span for which the colimit is computed
buildSpan :: GDiagram ->
Map.Map Node [(Node, G_theory)] ->
AnyComorphism ->
AnyComorphism ->
AnyComorphism ->
AnyComorphism ->
AnyComorphism ->
AnyModification ->
AnyModification ->
G_theory ->
G_theory ->
G_theory ->
GMorphism ->
GMorphism ->
Int -> Int -> Int ->
[(Int, G_theory)] ->
Result (GDiagram, Map.Map Node [(Node, G_theory)])
buildSpan graph
funDesc
d@(Comorphism _cidD)
e1@(Comorphism cidE1)
e2@(Comorphism cidE2)
_d1@(Comorphism _cidD1)
_d2@(Comorphism _cidD2)
_m1@(Modification cidM1)
_m2@(Modification cidM2)
gt@(G_theory lid _ sign _ _ _)
gt1@(G_theory lid1 _ sign1 _ _ _)
gt2@(G_theory lid2 _ sign2 _ _ _)
_phi1@(GMorphism cid1 _ _ mor1 _)
_phi2@(GMorphism cid2 _ _ mor2 _)
n n1 n2
maxNodes
= do
sig@(G_theory _lid0 _ _sign0 _ _ _) <- mapG_theory False d gt -- phi^d(Sigma)
sig1 <- mapG_theory False e1 gt1 -- phi^e1(Sigma1)
sig2 <- mapG_theory False e2 gt2 -- phi^e2(Sigma2)
mor1' <- coerceMorphism (targetLogic cid1) (sourceLogic cidE1) "buildSpan" mor1
eps1 <- map_morphism cidE1 mor1' -- phi^e1(sigma1)
sign' <- coerceSign lid (sourceLogic $ sourceComorphism cidM1) "buildSpan" sign
tau1 <- tauSigma cidM1 (plainSign sign') -- I^u1_Sigma
tau1' <- coerceMorphism (targetLogic $ sourceComorphism cidM1)
(targetLogic cidE1) "buildSpan" tau1
rho1 <- comp tau1' eps1
mor2' <- coerceMorphism (targetLogic cid2) (sourceLogic cidE2) "buildSpan" mor2
eps2 <- map_morphism cidE2 mor2' -- phi^e2(sigma2)
sign'' <- coerceSign lid (sourceLogic $ sourceComorphism cidM2) "buildSpan" sign
tau2 <- tauSigma cidM2 (plainSign sign'') -- I^u2_Sigma
tau2' <- coerceMorphism (targetLogic $ sourceComorphism cidM2)
(targetLogic cidE2) "buildSpan" tau2
rho2 <- comp tau2' eps2
signE1 <- coerceSign lid1 (sourceLogic cidE1) " " sign1
signE2 <- coerceSign lid2 (sourceLogic cidE2) " " sign2
(graph1, funDesc1) <- addNodeToGraph graph sig sig1 sig2 n n1 n2
(GMorphism cidE1 signE1 startSigId rho1 startMorId)
(GMorphism cidE2 signE2 startSigId rho2 startMorId)
funDesc maxNodes
return (graph1, funDesc1)
pickMaximalDesc :: (MonadPlus t) => [(Node, G_theory)] -> t (Node, G_theory)
pickMaximalDesc descList = msum $ map return descList
nrMaxNodes :: Gr a b -> Int
nrMaxNodes graph = length $ filter (\ n -> outdeg graph n == 0) $ nodes graph
-- | backtracking function for heterogeneous weak amalgamable cocones
hetWeakAmalgCocone :: (Monad m, LogicT t, MonadPlus (t m)) =>
GDiagram -> Map.Map Int [(Int, G_theory)] -> t m GDiagram
hetWeakAmalgCocone graph funDesc =
if nrMaxNodes graph == 1 then return graph
else once $ do
(n1, gt1) <- pickMaxNode graph
(n2, gt2) <- pickMaxNode graph
guard (n1 < n2) -- to consider each pair of maximal nodes only once
let descList = commonDesc funDesc n1 n2
case length descList of
0 -> mzero -- no common descendants for n1 and n2
_ -> do {- just one common descendant implies greatest lower bound
for several, the tail is not empty and we compute coequalizers -}
(n, gt) <- pickMaximalDesc descList
let phi1 = dijkstra graph n n1
phi2 = dijkstra graph n n2
square <- pickSquare phi1 phi2
let d = laxTarget $ leftTriangle square
e1 = laxFst $ leftTriangle square
d1 = laxSnd $ leftTriangle square
e2 = laxFst $ rightTriangle square
d2 = laxSnd $ rightTriangle square
m1 = laxModif $ leftTriangle square
m2 = laxModif $ rightTriangle square
case maybeResult phi1 of
Nothing -> mzero
Just phi1' -> case maybeResult phi2 of
Nothing -> mzero
Just phi2' -> do
let mGraph = buildSpan graph funDesc d e1 e2 d1 d2 m1 m2 gt gt1 gt2
phi1' phi2' n n1 n2 $ filter (\ (nx, _) -> nx /= n) descList
case maybeResult mGraph of
Nothing -> mzero
Just (graph1, funDesc1) -> hetWeakAmalgCocone graph1 funDesc1
| spechub/Hets | Static/WACocone.hs | gpl-2.0 | 19,615 | 2 | 32 | 5,554 | 6,563 | 3,367 | 3,196 | 384 | 8 |
{-# LANGUAGE GADTs #-}
-- | Syntax of GADT's explained with examples.
module GADTSyntax where
-- | How do we write the following data types using GADT's?
--
-- Maybe:
--
-- > data Maybe a = Nothing | Just a
--
-- List:
--
-- > data List a = Nil | Cons a (List a)
--
-- Rose tree:
--
-- > data RoseTree a = RoseTree a [RoseTree a]
--
data GMaybe a where
GNothing :: GMaybe a
GJust :: a -> GMaybe a
data GList a where
GNil :: GList a
GCons :: a -> GList a -> GList a
data GRoseTree a where
GRoseTree :: a -> [GRoseTree a] -> GRoseTree a
-- | When working with GADT's it is useful to think of constructors as
-- functions.
-- | So far in this file we haven't seen anything we cannot do without GADT's:
-- functions for constructor 'Foo a' have 'Foo a' has its return type. GADT's
-- let us control the type of 'Foo' we return (how 'a' gets instantiated).
--
-- Now consider:
--
data TrueGadtFoo a where
MkTrueGadtFoo :: a -> TrueGadtFoo Int
-- This has no Haskell 98 equivalent.
-- | And remember that you must return the same datatype you're defining!
--
-- > data Foo where
-- > MkFoo :: Bar Int-- This will not typecheck
--
| capitanbatata/apath-slfp | competent/gadts/src/GADTSyntax.hs | gpl-3.0 | 1,145 | 0 | 9 | 250 | 135 | 89 | 46 | 12 | 0 |
{-|
Module : Network.Ricochet.Testing.Crypto
Description : The tests for Network.Ricochet.Crypto
"Network.Ricochet.Testing.Crypto" contains all of the tests for
"Network.Ricochet.Crypto".
-}
module Network.Ricochet.Testing.Crypto where
import Network.Ricochet
import Network.Ricochet.Monad
import Network.Ricochet.Crypto
import Test.QuickCheck
import Test.QuickCheck.Monadic
import Test.HUnit hiding (assert)
import Data.Maybe
import Data.ByteString
import Control.Lens
import Control.Monad
import Control.Monad.IO.Class
import Control.Concurrent.MVar
import Network
import OpenSSL.EVP.Verify hiding (verify)
-- | Check the base64 Prism
base64Check :: ByteString -> Bool
base64Check bs = let tested = bs ^? re base64 . base64
in fromJust tested == bs
-- | Check the sign and verify functions
signCheck :: ByteString -> ByteString -> Property
signCheck bs bs' = monadicIO $ do
key <- run generate1024BitRSA
let signature = sign key bs
assert . verify key bs $ signature
assert . not . verify key bs' $ signature
-- | Check the raw sign and verify functions
rawSignCheck :: ByteString -> ByteString -> Property
rawSignCheck bs bs' = monadicIO $ do
key <- run generate1024BitRSA
let signature = rawRSASign key bs
assert . rawRSAVerify key bs $ signature
assert . not . rawRSAVerify key bs' $ signature
-- | Assert that torDomain computes the correct domain
torDomainAssertion :: Assertion
torDomainAssertion = do
key <- generate1024BitRSA
mVar <- newEmptyMVar
let privKey = base64 . privateDER # key
config = RicochetConfig
{ rcPort = PortNumber 9879
, rcPrivKey = Just privKey
, rcControlPort = PortNumber 9051
, rcSocksPort = PortNumber 9050
, rcHandlers = []
}
startRicochet config [] (use hiddenDomain >>= liftIO . putMVar mVar)
domain <- readMVar mVar
assertEqual "" domain $ torDomain key
| Jugendhackt/haskell-ricochet | test/Network/Ricochet/Testing/Crypto.hs | gpl-3.0 | 1,960 | 0 | 12 | 424 | 466 | 241 | 225 | -1 | -1 |
{-# LANGUAGE DeriveGeneric, OverloadedStrings, OverloadedLists #-}
module Modernator.RequestBodies where
import Modernator.Types()
import Data.Text
import Data.Time.Clock
import Data.Aeson
import GHC.Generics (Generic)
import Data.Swagger.Schema
import Control.Lens
import Data.Swagger.Internal
import Data.Swagger.Lens
import Data.Proxy
data SessionReq = SessionReq
{ sessionName :: Text
, sessionExpiration :: Maybe UTCTime
}
deriving (Generic, Show, Eq)
instance ToJSON SessionReq
instance FromJSON SessionReq
instance ToSchema SessionReq
data JoinReq = JoinReq
{ questionerName :: Maybe Text
}
deriving (Generic, Show, Eq)
instance ToJSON JoinReq
-- TODO input like { "ques": "foo" } parses correctly as Nothing. It should not.
instance FromJSON JoinReq
instance ToSchema JoinReq where
declareNamedSchema _ = do
textSchema <- declareSchemaRef (Proxy :: Proxy Text)
return $ NamedSchema (Just "JoinReq") $ mempty
& type_ .~ SwaggerObject
& properties .~ [("questionerName", textSchema)]
data QuestionReq = QuestionReq
{ question :: Text
}
deriving (Generic, Show, Eq)
instance ToJSON QuestionReq
instance FromJSON QuestionReq
instance ToSchema QuestionReq
data UserReq = UserReq
{ userName :: Text
, userPassword :: Text
}
deriving (Generic, Show, Eq)
instance ToJSON UserReq
instance FromJSON UserReq
instance ToSchema UserReq
data LoginReq = LoginReq
{ loginName:: Text
, loginPassword :: Text
}
deriving (Generic, Show, Eq)
-- ToJSON needed to pass tests, I don't actually want it as it poses a security risk
instance ToJSON LoginReq
instance FromJSON LoginReq
instance ToSchema LoginReq
| mojotech/modernator-haskell | src/Modernator/RequestBodies.hs | gpl-3.0 | 1,721 | 0 | 16 | 340 | 423 | 227 | 196 | 50 | 0 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Main where
import Control.Applicative
import Language.Landler
import Test.QuickCheck
instance Arbitrary Term where
arbitrary = choose (1, 9) >>= go
where
go :: Int -> Gen Term
go 0 = Var <$> name
go n = oneof [Var <$> name, ab n, app n]
ab :: Int -> Gen Term
ab n = Ab <$> name <*> (go (n - 1))
app :: Int -> Gen Term
app n = App <$> (go (n - 1)) <*> (go (n - 1))
instance Arbitrary Statement where
arbitrary = choose (0, 1) >>= go
where
go :: Int -> Gen Statement
go 0 = LetS <$> name <*> arbitrary
go _ = CallS <$> arbitrary
main :: IO ()
main = do
quickCheck prop_IdemParseShow
quickCheck prop_IdemParseShowStatement
prop_IdemParseShow :: Term -> Property
prop_IdemParseShow x = not (isVar x) ==> x == toTerm (show x)
where
isVar :: Term -> Bool
isVar (Var _) = True
isVar _ = False
prop_IdemParseShowStatement :: Statement -> Bool
prop_IdemParseShowStatement x = x == parseStatement (show x)
name :: Gen String
name = choose (0, 100) >>= \i -> return (allVars !! i)
where
allVars = let vs = "" : [v ++ [s] | v <- vs, s <- ['a'..'z']]
in tail vs
| scvalex/landler | Test/QC.hs | gpl-3.0 | 1,252 | 0 | 15 | 368 | 495 | 255 | 240 | 34 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.ContainerBuilder.Types.Sum
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.ContainerBuilder.Types.Sum where
import Network.Google.Prelude hiding (Bytes)
-- | Output only. Status of the build step. At this time, build step status
-- is only updated on build completion; step status is not updated in
-- real-time as the build progresses.
data BuildStepStatus
= StatusUnknown
-- ^ @STATUS_UNKNOWN@
-- Status of the build is unknown.
| Queued
-- ^ @QUEUED@
-- Build or step is queued; work has not yet begun.
| Working
-- ^ @WORKING@
-- Build or step is being executed.
| Success
-- ^ @SUCCESS@
-- Build or step finished successfully.
| Failure
-- ^ @FAILURE@
-- Build or step failed to complete successfully.
| InternalError
-- ^ @INTERNAL_ERROR@
-- Build or step failed due to an internal cause.
| Timeout
-- ^ @TIMEOUT@
-- Build or step took longer than was allowed.
| Cancelled
-- ^ @CANCELLED@
-- Build or step was canceled by a user.
| Expired
-- ^ @EXPIRED@
-- Build was enqueued for longer than the value of \`queue_ttl\`.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BuildStepStatus
instance FromHttpApiData BuildStepStatus where
parseQueryParam = \case
"STATUS_UNKNOWN" -> Right StatusUnknown
"QUEUED" -> Right Queued
"WORKING" -> Right Working
"SUCCESS" -> Right Success
"FAILURE" -> Right Failure
"INTERNAL_ERROR" -> Right InternalError
"TIMEOUT" -> Right Timeout
"CANCELLED" -> Right Cancelled
"EXPIRED" -> Right Expired
x -> Left ("Unable to parse BuildStepStatus from: " <> x)
instance ToHttpApiData BuildStepStatus where
toQueryParam = \case
StatusUnknown -> "STATUS_UNKNOWN"
Queued -> "QUEUED"
Working -> "WORKING"
Success -> "SUCCESS"
Failure -> "FAILURE"
InternalError -> "INTERNAL_ERROR"
Timeout -> "TIMEOUT"
Cancelled -> "CANCELLED"
Expired -> "EXPIRED"
instance FromJSON BuildStepStatus where
parseJSON = parseJSONText "BuildStepStatus"
instance ToJSON BuildStepStatus where
toJSON = toJSONText
-- | Configure builds to run whether a repository owner or collaborator need
-- to comment \`\/gcbrun\`.
data PullRequestFilterCommentControl
= CommentsDisabled
-- ^ @COMMENTS_DISABLED@
-- Do not require comments on Pull Requests before builds are triggered.
| CommentsEnabled
-- ^ @COMMENTS_ENABLED@
-- Enforce that repository owners or collaborators must comment on Pull
-- Requests before builds are triggered.
| CommentsEnabledForExternalContributorsOnly
-- ^ @COMMENTS_ENABLED_FOR_EXTERNAL_CONTRIBUTORS_ONLY@
-- Enforce that repository owners or collaborators must comment on external
-- contributors\' Pull Requests before builds are triggered.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PullRequestFilterCommentControl
instance FromHttpApiData PullRequestFilterCommentControl where
parseQueryParam = \case
"COMMENTS_DISABLED" -> Right CommentsDisabled
"COMMENTS_ENABLED" -> Right CommentsEnabled
"COMMENTS_ENABLED_FOR_EXTERNAL_CONTRIBUTORS_ONLY" -> Right CommentsEnabledForExternalContributorsOnly
x -> Left ("Unable to parse PullRequestFilterCommentControl from: " <> x)
instance ToHttpApiData PullRequestFilterCommentControl where
toQueryParam = \case
CommentsDisabled -> "COMMENTS_DISABLED"
CommentsEnabled -> "COMMENTS_ENABLED"
CommentsEnabledForExternalContributorsOnly -> "COMMENTS_ENABLED_FOR_EXTERNAL_CONTRIBUTORS_ONLY"
instance FromJSON PullRequestFilterCommentControl where
parseJSON = parseJSONText "PullRequestFilterCommentControl"
instance ToJSON PullRequestFilterCommentControl where
toJSON = toJSONText
-- | Potential issues with the underlying Pub\/Sub subscription
-- configuration. Only populated on get requests.
data PubsubConfigState
= StateUnspecified
-- ^ @STATE_UNSPECIFIED@
-- The subscription configuration has not been checked.
| OK
-- ^ @OK@
-- The Pub\/Sub subscription is properly configured.
| SubscriptionDeleted
-- ^ @SUBSCRIPTION_DELETED@
-- The subscription has been deleted.
| TopicDeleted
-- ^ @TOPIC_DELETED@
-- The topic has been deleted.
| SubscriptionMisConfigured
-- ^ @SUBSCRIPTION_MISCONFIGURED@
-- Some of the subscription\'s field are misconfigured.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PubsubConfigState
instance FromHttpApiData PubsubConfigState where
parseQueryParam = \case
"STATE_UNSPECIFIED" -> Right StateUnspecified
"OK" -> Right OK
"SUBSCRIPTION_DELETED" -> Right SubscriptionDeleted
"TOPIC_DELETED" -> Right TopicDeleted
"SUBSCRIPTION_MISCONFIGURED" -> Right SubscriptionMisConfigured
x -> Left ("Unable to parse PubsubConfigState from: " <> x)
instance ToHttpApiData PubsubConfigState where
toQueryParam = \case
StateUnspecified -> "STATE_UNSPECIFIED"
OK -> "OK"
SubscriptionDeleted -> "SUBSCRIPTION_DELETED"
TopicDeleted -> "TOPIC_DELETED"
SubscriptionMisConfigured -> "SUBSCRIPTION_MISCONFIGURED"
instance FromJSON PubsubConfigState where
parseJSON = parseJSONText "PubsubConfigState"
instance ToJSON PubsubConfigState where
toJSON = toJSONText
-- | See RepoType below.
data GitRepoSourceRepoType
= Unknown
-- ^ @UNKNOWN@
-- The default, unknown repo type.
| CloudSourceRepositories
-- ^ @CLOUD_SOURCE_REPOSITORIES@
-- A Google Cloud Source Repositories-hosted repo.
| Github
-- ^ @GITHUB@
-- A GitHub-hosted repo not necessarily on \"github.com\" (i.e. GitHub
-- Enterprise).
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable GitRepoSourceRepoType
instance FromHttpApiData GitRepoSourceRepoType where
parseQueryParam = \case
"UNKNOWN" -> Right Unknown
"CLOUD_SOURCE_REPOSITORIES" -> Right CloudSourceRepositories
"GITHUB" -> Right Github
x -> Left ("Unable to parse GitRepoSourceRepoType from: " <> x)
instance ToHttpApiData GitRepoSourceRepoType where
toQueryParam = \case
Unknown -> "UNKNOWN"
CloudSourceRepositories -> "CLOUD_SOURCE_REPOSITORIES"
Github -> "GITHUB"
instance FromJSON GitRepoSourceRepoType where
parseJSON = parseJSONText "GitRepoSourceRepoType"
instance ToJSON GitRepoSourceRepoType where
toJSON = toJSONText
-- | Requested verifiability options.
data BuildOptionsRequestedVerifyOption
= NotVerified
-- ^ @NOT_VERIFIED@
-- Not a verifiable build. (default)
| Verified
-- ^ @VERIFIED@
-- Verified build.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BuildOptionsRequestedVerifyOption
instance FromHttpApiData BuildOptionsRequestedVerifyOption where
parseQueryParam = \case
"NOT_VERIFIED" -> Right NotVerified
"VERIFIED" -> Right Verified
x -> Left ("Unable to parse BuildOptionsRequestedVerifyOption from: " <> x)
instance ToHttpApiData BuildOptionsRequestedVerifyOption where
toQueryParam = \case
NotVerified -> "NOT_VERIFIED"
Verified -> "VERIFIED"
instance FromJSON BuildOptionsRequestedVerifyOption where
parseJSON = parseJSONText "BuildOptionsRequestedVerifyOption"
instance ToJSON BuildOptionsRequestedVerifyOption where
toJSON = toJSONText
-- | Option to configure network egress for the workers.
data NetworkConfigEgressOption
= EgressOptionUnspecified
-- ^ @EGRESS_OPTION_UNSPECIFIED@
-- If set, defaults to PUBLIC_EGRESS.
| NoPublicEgress
-- ^ @NO_PUBLIC_EGRESS@
-- If set, workers are created without any public address, which prevents
-- network egress to public IPs unless a network proxy is configured.
| PublicEgress
-- ^ @PUBLIC_EGRESS@
-- If set, workers are created with a public address which allows for
-- public internet egress.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable NetworkConfigEgressOption
instance FromHttpApiData NetworkConfigEgressOption where
parseQueryParam = \case
"EGRESS_OPTION_UNSPECIFIED" -> Right EgressOptionUnspecified
"NO_PUBLIC_EGRESS" -> Right NoPublicEgress
"PUBLIC_EGRESS" -> Right PublicEgress
x -> Left ("Unable to parse NetworkConfigEgressOption from: " <> x)
instance ToHttpApiData NetworkConfigEgressOption where
toQueryParam = \case
EgressOptionUnspecified -> "EGRESS_OPTION_UNSPECIFIED"
NoPublicEgress -> "NO_PUBLIC_EGRESS"
PublicEgress -> "PUBLIC_EGRESS"
instance FromJSON NetworkConfigEgressOption where
parseJSON = parseJSONText "NetworkConfigEgressOption"
instance ToJSON NetworkConfigEgressOption where
toJSON = toJSONText
-- | V1 error format.
data Xgafv
= X1
-- ^ @1@
-- v1 error format
| X2
-- ^ @2@
-- v2 error format
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable Xgafv
instance FromHttpApiData Xgafv where
parseQueryParam = \case
"1" -> Right X1
"2" -> Right X2
x -> Left ("Unable to parse Xgafv from: " <> x)
instance ToHttpApiData Xgafv where
toQueryParam = \case
X1 -> "1"
X2 -> "2"
instance FromJSON Xgafv where
parseJSON = parseJSONText "Xgafv"
instance ToJSON Xgafv where
toJSON = toJSONText
-- | Output only. Status of the build.
data BuildStatus
= BSStatusUnknown
-- ^ @STATUS_UNKNOWN@
-- Status of the build is unknown.
| BSQueued
-- ^ @QUEUED@
-- Build or step is queued; work has not yet begun.
| BSWorking
-- ^ @WORKING@
-- Build or step is being executed.
| BSSuccess
-- ^ @SUCCESS@
-- Build or step finished successfully.
| BSFailure
-- ^ @FAILURE@
-- Build or step failed to complete successfully.
| BSInternalError
-- ^ @INTERNAL_ERROR@
-- Build or step failed due to an internal cause.
| BSTimeout
-- ^ @TIMEOUT@
-- Build or step took longer than was allowed.
| BSCancelled
-- ^ @CANCELLED@
-- Build or step was canceled by a user.
| BSExpired
-- ^ @EXPIRED@
-- Build was enqueued for longer than the value of \`queue_ttl\`.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BuildStatus
instance FromHttpApiData BuildStatus where
parseQueryParam = \case
"STATUS_UNKNOWN" -> Right BSStatusUnknown
"QUEUED" -> Right BSQueued
"WORKING" -> Right BSWorking
"SUCCESS" -> Right BSSuccess
"FAILURE" -> Right BSFailure
"INTERNAL_ERROR" -> Right BSInternalError
"TIMEOUT" -> Right BSTimeout
"CANCELLED" -> Right BSCancelled
"EXPIRED" -> Right BSExpired
x -> Left ("Unable to parse BuildStatus from: " <> x)
instance ToHttpApiData BuildStatus where
toQueryParam = \case
BSStatusUnknown -> "STATUS_UNKNOWN"
BSQueued -> "QUEUED"
BSWorking -> "WORKING"
BSSuccess -> "SUCCESS"
BSFailure -> "FAILURE"
BSInternalError -> "INTERNAL_ERROR"
BSTimeout -> "TIMEOUT"
BSCancelled -> "CANCELLED"
BSExpired -> "EXPIRED"
instance FromJSON BuildStatus where
parseJSON = parseJSONText "BuildStatus"
instance ToJSON BuildStatus where
toJSON = toJSONText
-- | Option to specify behavior when there is an error in the substitution
-- checks. NOTE: this is always set to ALLOW_LOOSE for triggered builds and
-- cannot be overridden in the build configuration file.
data BuildOptionsSubstitutionOption
= MustMatch
-- ^ @MUST_MATCH@
-- Fails the build if error in substitutions checks, like missing a
-- substitution in the template or in the map.
| AllowLoose
-- ^ @ALLOW_LOOSE@
-- Do not fail the build if error in substitutions checks.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BuildOptionsSubstitutionOption
instance FromHttpApiData BuildOptionsSubstitutionOption where
parseQueryParam = \case
"MUST_MATCH" -> Right MustMatch
"ALLOW_LOOSE" -> Right AllowLoose
x -> Left ("Unable to parse BuildOptionsSubstitutionOption from: " <> x)
instance ToHttpApiData BuildOptionsSubstitutionOption where
toQueryParam = \case
MustMatch -> "MUST_MATCH"
AllowLoose -> "ALLOW_LOOSE"
instance FromJSON BuildOptionsSubstitutionOption where
parseJSON = parseJSONText "BuildOptionsSubstitutionOption"
instance ToJSON BuildOptionsSubstitutionOption where
toJSON = toJSONText
-- | The type of hash that was performed.
data HashType
= None
-- ^ @NONE@
-- No hash requested.
| SHA256
-- ^ @SHA256@
-- Use a sha256 hash.
| MD5
-- ^ @MD5@
-- Use a md5 hash.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable HashType
instance FromHttpApiData HashType where
parseQueryParam = \case
"NONE" -> Right None
"SHA256" -> Right SHA256
"MD5" -> Right MD5
x -> Left ("Unable to parse HashType from: " <> x)
instance ToHttpApiData HashType where
toQueryParam = \case
None -> "NONE"
SHA256 -> "SHA256"
MD5 -> "MD5"
instance FromJSON HashType where
parseJSON = parseJSONText "HashType"
instance ToJSON HashType where
toJSON = toJSONText
-- | Option to define build log streaming behavior to Google Cloud Storage.
data BuildOptionsLogStreamingOption
= StreamDefault
-- ^ @STREAM_DEFAULT@
-- Service may automatically determine build log streaming behavior.
| StreamOn
-- ^ @STREAM_ON@
-- Build logs should be streamed to Google Cloud Storage.
| StreamOff
-- ^ @STREAM_OFF@
-- Build logs should not be streamed to Google Cloud Storage; they will be
-- written when the build is completed.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BuildOptionsLogStreamingOption
instance FromHttpApiData BuildOptionsLogStreamingOption where
parseQueryParam = \case
"STREAM_DEFAULT" -> Right StreamDefault
"STREAM_ON" -> Right StreamOn
"STREAM_OFF" -> Right StreamOff
x -> Left ("Unable to parse BuildOptionsLogStreamingOption from: " <> x)
instance ToHttpApiData BuildOptionsLogStreamingOption where
toQueryParam = \case
StreamDefault -> "STREAM_DEFAULT"
StreamOn -> "STREAM_ON"
StreamOff -> "STREAM_OFF"
instance FromJSON BuildOptionsLogStreamingOption where
parseJSON = parseJSONText "BuildOptionsLogStreamingOption"
instance ToJSON BuildOptionsLogStreamingOption where
toJSON = toJSONText
data BuildOptionsSourceProvenanceHashItem
= BOSPHINone
-- ^ @NONE@
-- No hash requested.
| BOSPHISHA256
-- ^ @SHA256@
-- Use a sha256 hash.
| BOSPHIMD5
-- ^ @MD5@
-- Use a md5 hash.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BuildOptionsSourceProvenanceHashItem
instance FromHttpApiData BuildOptionsSourceProvenanceHashItem where
parseQueryParam = \case
"NONE" -> Right BOSPHINone
"SHA256" -> Right BOSPHISHA256
"MD5" -> Right BOSPHIMD5
x -> Left ("Unable to parse BuildOptionsSourceProvenanceHashItem from: " <> x)
instance ToHttpApiData BuildOptionsSourceProvenanceHashItem where
toQueryParam = \case
BOSPHINone -> "NONE"
BOSPHISHA256 -> "SHA256"
BOSPHIMD5 -> "MD5"
instance FromJSON BuildOptionsSourceProvenanceHashItem where
parseJSON = parseJSONText "BuildOptionsSourceProvenanceHashItem"
instance ToJSON BuildOptionsSourceProvenanceHashItem where
toJSON = toJSONText
-- | Option to specify the logging mode, which determines if and where build
-- logs are stored.
data BuildOptionsLogging
= BOLLoggingUnspecified
-- ^ @LOGGING_UNSPECIFIED@
-- The service determines the logging mode. The default is \`LEGACY\`. Do
-- not rely on the default logging behavior as it may change in the future.
| BOLLegacy
-- ^ @LEGACY@
-- Cloud Logging and Cloud Storage logging are enabled.
| BOLGcsOnly
-- ^ @GCS_ONLY@
-- Only Cloud Storage logging is enabled.
| BOLStackdriverOnly
-- ^ @STACKDRIVER_ONLY@
-- This option is the same as CLOUD_LOGGING_ONLY.
| BOLCloudLoggingOnly
-- ^ @CLOUD_LOGGING_ONLY@
-- Only Cloud Logging is enabled. Note that logs for both the Cloud Console
-- UI and Cloud SDK are based on Cloud Storage logs, so neither will
-- provide logs if this option is chosen.
| BOLNone
-- ^ @NONE@
-- Turn off all logging. No build logs will be captured.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BuildOptionsLogging
instance FromHttpApiData BuildOptionsLogging where
parseQueryParam = \case
"LOGGING_UNSPECIFIED" -> Right BOLLoggingUnspecified
"LEGACY" -> Right BOLLegacy
"GCS_ONLY" -> Right BOLGcsOnly
"STACKDRIVER_ONLY" -> Right BOLStackdriverOnly
"CLOUD_LOGGING_ONLY" -> Right BOLCloudLoggingOnly
"NONE" -> Right BOLNone
x -> Left ("Unable to parse BuildOptionsLogging from: " <> x)
instance ToHttpApiData BuildOptionsLogging where
toQueryParam = \case
BOLLoggingUnspecified -> "LOGGING_UNSPECIFIED"
BOLLegacy -> "LEGACY"
BOLGcsOnly -> "GCS_ONLY"
BOLStackdriverOnly -> "STACKDRIVER_ONLY"
BOLCloudLoggingOnly -> "CLOUD_LOGGING_ONLY"
BOLNone -> "NONE"
instance FromJSON BuildOptionsLogging where
parseJSON = parseJSONText "BuildOptionsLogging"
instance ToJSON BuildOptionsLogging where
toJSON = toJSONText
-- | Output only. \`WorkerPool\` state.
data WorkerPoolState
= WPSStateUnspecified
-- ^ @STATE_UNSPECIFIED@
-- State of the \`WorkerPool\` is unknown.
| WPSCreating
-- ^ @CREATING@
-- \`WorkerPool\` is being created.
| WPSRunning
-- ^ @RUNNING@
-- \`WorkerPool\` is running.
| WPSDeleting
-- ^ @DELETING@
-- \`WorkerPool\` is being deleted: cancelling builds and draining workers.
| WPSDeleted
-- ^ @DELETED@
-- \`WorkerPool\` is deleted.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable WorkerPoolState
instance FromHttpApiData WorkerPoolState where
parseQueryParam = \case
"STATE_UNSPECIFIED" -> Right WPSStateUnspecified
"CREATING" -> Right WPSCreating
"RUNNING" -> Right WPSRunning
"DELETING" -> Right WPSDeleting
"DELETED" -> Right WPSDeleted
x -> Left ("Unable to parse WorkerPoolState from: " <> x)
instance ToHttpApiData WorkerPoolState where
toQueryParam = \case
WPSStateUnspecified -> "STATE_UNSPECIFIED"
WPSCreating -> "CREATING"
WPSRunning -> "RUNNING"
WPSDeleting -> "DELETING"
WPSDeleted -> "DELETED"
instance FromJSON WorkerPoolState where
parseJSON = parseJSONText "WorkerPoolState"
instance ToJSON WorkerPoolState where
toJSON = toJSONText
-- | The priority for this warning.
data WarningPriority
= WPPriorityUnspecified
-- ^ @PRIORITY_UNSPECIFIED@
-- Should not be used.
| WPInfo
-- ^ @INFO@
-- e.g. deprecation warnings and alternative feature highlights.
| WPWarning
-- ^ @WARNING@
-- e.g. automated detection of possible issues with the build.
| WPAlert
-- ^ @ALERT@
-- e.g. alerts that a feature used in the build is pending removal
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable WarningPriority
instance FromHttpApiData WarningPriority where
parseQueryParam = \case
"PRIORITY_UNSPECIFIED" -> Right WPPriorityUnspecified
"INFO" -> Right WPInfo
"WARNING" -> Right WPWarning
"ALERT" -> Right WPAlert
x -> Left ("Unable to parse WarningPriority from: " <> x)
instance ToHttpApiData WarningPriority where
toQueryParam = \case
WPPriorityUnspecified -> "PRIORITY_UNSPECIFIED"
WPInfo -> "INFO"
WPWarning -> "WARNING"
WPAlert -> "ALERT"
instance FromJSON WarningPriority where
parseJSON = parseJSONText "WarningPriority"
instance ToJSON WarningPriority where
toJSON = toJSONText
-- | Compute Engine machine type on which to run the build.
data BuildOptionsMachineType
= Unspecified
-- ^ @UNSPECIFIED@
-- Standard machine type.
| N1Highcpu8
-- ^ @N1_HIGHCPU_8@
-- Highcpu machine with 8 CPUs.
| N1Highcpu32
-- ^ @N1_HIGHCPU_32@
-- Highcpu machine with 32 CPUs.
| E2Highcpu8
-- ^ @E2_HIGHCPU_8@
-- Highcpu e2 machine with 8 CPUs.
| E2Highcpu32
-- ^ @E2_HIGHCPU_32@
-- Highcpu e2 machine with 32 CPUs.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BuildOptionsMachineType
instance FromHttpApiData BuildOptionsMachineType where
parseQueryParam = \case
"UNSPECIFIED" -> Right Unspecified
"N1_HIGHCPU_8" -> Right N1Highcpu8
"N1_HIGHCPU_32" -> Right N1Highcpu32
"E2_HIGHCPU_8" -> Right E2Highcpu8
"E2_HIGHCPU_32" -> Right E2Highcpu32
x -> Left ("Unable to parse BuildOptionsMachineType from: " <> x)
instance ToHttpApiData BuildOptionsMachineType where
toQueryParam = \case
Unspecified -> "UNSPECIFIED"
N1Highcpu8 -> "N1_HIGHCPU_8"
N1Highcpu32 -> "N1_HIGHCPU_32"
E2Highcpu8 -> "E2_HIGHCPU_8"
E2Highcpu32 -> "E2_HIGHCPU_32"
instance FromJSON BuildOptionsMachineType where
parseJSON = parseJSONText "BuildOptionsMachineType"
instance ToJSON BuildOptionsMachineType where
toJSON = toJSONText
-- | The name of the failure.
data FailureInfoType
= FailureTypeUnspecified
-- ^ @FAILURE_TYPE_UNSPECIFIED@
-- Type unspecified
| PushFailed
-- ^ @PUSH_FAILED@
-- Unable to push the image to the repository.
| PushImageNotFound
-- ^ @PUSH_IMAGE_NOT_FOUND@
-- Final image not found.
| PushNotAuthorized
-- ^ @PUSH_NOT_AUTHORIZED@
-- Unauthorized push of the final image.
| LoggingFailure
-- ^ @LOGGING_FAILURE@
-- Backend logging failures. Should retry.
| UserBuildStep
-- ^ @USER_BUILD_STEP@
-- A build step has failed.
| FetchSourceFailed
-- ^ @FETCH_SOURCE_FAILED@
-- The source fetching has failed.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable FailureInfoType
instance FromHttpApiData FailureInfoType where
parseQueryParam = \case
"FAILURE_TYPE_UNSPECIFIED" -> Right FailureTypeUnspecified
"PUSH_FAILED" -> Right PushFailed
"PUSH_IMAGE_NOT_FOUND" -> Right PushImageNotFound
"PUSH_NOT_AUTHORIZED" -> Right PushNotAuthorized
"LOGGING_FAILURE" -> Right LoggingFailure
"USER_BUILD_STEP" -> Right UserBuildStep
"FETCH_SOURCE_FAILED" -> Right FetchSourceFailed
x -> Left ("Unable to parse FailureInfoType from: " <> x)
instance ToHttpApiData FailureInfoType where
toQueryParam = \case
FailureTypeUnspecified -> "FAILURE_TYPE_UNSPECIFIED"
PushFailed -> "PUSH_FAILED"
PushImageNotFound -> "PUSH_IMAGE_NOT_FOUND"
PushNotAuthorized -> "PUSH_NOT_AUTHORIZED"
LoggingFailure -> "LOGGING_FAILURE"
UserBuildStep -> "USER_BUILD_STEP"
FetchSourceFailed -> "FETCH_SOURCE_FAILED"
instance FromJSON FailureInfoType where
parseJSON = parseJSONText "FailureInfoType"
instance ToJSON FailureInfoType where
toJSON = toJSONText
-- | Potential issues with the underlying Pub\/Sub subscription
-- configuration. Only populated on get requests.
data WebhookConfigState
= WCSStateUnspecified
-- ^ @STATE_UNSPECIFIED@
-- The webhook auth configuration not been checked.
| WCSOK
-- ^ @OK@
-- The auth configuration is properly setup.
| WCSSecretDeleted
-- ^ @SECRET_DELETED@
-- The secret provided in auth_method has been deleted.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable WebhookConfigState
instance FromHttpApiData WebhookConfigState where
parseQueryParam = \case
"STATE_UNSPECIFIED" -> Right WCSStateUnspecified
"OK" -> Right WCSOK
"SECRET_DELETED" -> Right WCSSecretDeleted
x -> Left ("Unable to parse WebhookConfigState from: " <> x)
instance ToHttpApiData WebhookConfigState where
toQueryParam = \case
WCSStateUnspecified -> "STATE_UNSPECIFIED"
WCSOK -> "OK"
WCSSecretDeleted -> "SECRET_DELETED"
instance FromJSON WebhookConfigState where
parseJSON = parseJSONText "WebhookConfigState"
instance ToJSON WebhookConfigState where
toJSON = toJSONText
| brendanhay/gogol | gogol-containerbuilder/gen/Network/Google/ContainerBuilder/Types/Sum.hs | mpl-2.0 | 25,788 | 0 | 11 | 6,081 | 3,788 | 2,027 | 1,761 | 455 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.AdExchangeBuyer2.Bidders.FilterSets.FilteredBidRequests.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- List all reasons that caused a bid request not to be sent for an
-- impression, with the number of bid requests not sent for each reason.
--
-- /See:/ <https://developers.google.com/authorized-buyers/apis/reference/rest/ Ad Exchange Buyer API II Reference> for @adexchangebuyer2.bidders.filterSets.filteredBidRequests.list@.
module Network.Google.Resource.AdExchangeBuyer2.Bidders.FilterSets.FilteredBidRequests.List
(
-- * REST Resource
BiddersFilterSetsFilteredBidRequestsListResource
-- * Creating a Request
, biddersFilterSetsFilteredBidRequestsList
, BiddersFilterSetsFilteredBidRequestsList
-- * Request Lenses
, bfsfbrlXgafv
, bfsfbrlUploadProtocol
, bfsfbrlFilterSetName
, bfsfbrlAccessToken
, bfsfbrlUploadType
, bfsfbrlPageToken
, bfsfbrlPageSize
, bfsfbrlCallback
) where
import Network.Google.AdExchangeBuyer2.Types
import Network.Google.Prelude
-- | A resource alias for @adexchangebuyer2.bidders.filterSets.filteredBidRequests.list@ method which the
-- 'BiddersFilterSetsFilteredBidRequestsList' request conforms to.
type BiddersFilterSetsFilteredBidRequestsListResource
=
"v2beta1" :>
Capture "filterSetName" Text :>
"filteredBidRequests" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListFilteredBidRequestsResponse
-- | List all reasons that caused a bid request not to be sent for an
-- impression, with the number of bid requests not sent for each reason.
--
-- /See:/ 'biddersFilterSetsFilteredBidRequestsList' smart constructor.
data BiddersFilterSetsFilteredBidRequestsList =
BiddersFilterSetsFilteredBidRequestsList'
{ _bfsfbrlXgafv :: !(Maybe Xgafv)
, _bfsfbrlUploadProtocol :: !(Maybe Text)
, _bfsfbrlFilterSetName :: !Text
, _bfsfbrlAccessToken :: !(Maybe Text)
, _bfsfbrlUploadType :: !(Maybe Text)
, _bfsfbrlPageToken :: !(Maybe Text)
, _bfsfbrlPageSize :: !(Maybe (Textual Int32))
, _bfsfbrlCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'BiddersFilterSetsFilteredBidRequestsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'bfsfbrlXgafv'
--
-- * 'bfsfbrlUploadProtocol'
--
-- * 'bfsfbrlFilterSetName'
--
-- * 'bfsfbrlAccessToken'
--
-- * 'bfsfbrlUploadType'
--
-- * 'bfsfbrlPageToken'
--
-- * 'bfsfbrlPageSize'
--
-- * 'bfsfbrlCallback'
biddersFilterSetsFilteredBidRequestsList
:: Text -- ^ 'bfsfbrlFilterSetName'
-> BiddersFilterSetsFilteredBidRequestsList
biddersFilterSetsFilteredBidRequestsList pBfsfbrlFilterSetName_ =
BiddersFilterSetsFilteredBidRequestsList'
{ _bfsfbrlXgafv = Nothing
, _bfsfbrlUploadProtocol = Nothing
, _bfsfbrlFilterSetName = pBfsfbrlFilterSetName_
, _bfsfbrlAccessToken = Nothing
, _bfsfbrlUploadType = Nothing
, _bfsfbrlPageToken = Nothing
, _bfsfbrlPageSize = Nothing
, _bfsfbrlCallback = Nothing
}
-- | V1 error format.
bfsfbrlXgafv :: Lens' BiddersFilterSetsFilteredBidRequestsList (Maybe Xgafv)
bfsfbrlXgafv
= lens _bfsfbrlXgafv (\ s a -> s{_bfsfbrlXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
bfsfbrlUploadProtocol :: Lens' BiddersFilterSetsFilteredBidRequestsList (Maybe Text)
bfsfbrlUploadProtocol
= lens _bfsfbrlUploadProtocol
(\ s a -> s{_bfsfbrlUploadProtocol = a})
-- | Name of the filter set that should be applied to the requested metrics.
-- For example: - For a bidder-level filter set for bidder 123:
-- \`bidders\/123\/filterSets\/abc\` - For an account-level filter set for
-- the buyer account representing bidder 123:
-- \`bidders\/123\/accounts\/123\/filterSets\/abc\` - For an account-level
-- filter set for the child seat buyer account 456 whose bidder is 123:
-- \`bidders\/123\/accounts\/456\/filterSets\/abc\`
bfsfbrlFilterSetName :: Lens' BiddersFilterSetsFilteredBidRequestsList Text
bfsfbrlFilterSetName
= lens _bfsfbrlFilterSetName
(\ s a -> s{_bfsfbrlFilterSetName = a})
-- | OAuth access token.
bfsfbrlAccessToken :: Lens' BiddersFilterSetsFilteredBidRequestsList (Maybe Text)
bfsfbrlAccessToken
= lens _bfsfbrlAccessToken
(\ s a -> s{_bfsfbrlAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
bfsfbrlUploadType :: Lens' BiddersFilterSetsFilteredBidRequestsList (Maybe Text)
bfsfbrlUploadType
= lens _bfsfbrlUploadType
(\ s a -> s{_bfsfbrlUploadType = a})
-- | A token identifying a page of results the server should return.
-- Typically, this is the value of
-- ListFilteredBidRequestsResponse.nextPageToken returned from the previous
-- call to the filteredBidRequests.list method.
bfsfbrlPageToken :: Lens' BiddersFilterSetsFilteredBidRequestsList (Maybe Text)
bfsfbrlPageToken
= lens _bfsfbrlPageToken
(\ s a -> s{_bfsfbrlPageToken = a})
-- | Requested page size. The server may return fewer results than requested.
-- If unspecified, the server will pick an appropriate default.
bfsfbrlPageSize :: Lens' BiddersFilterSetsFilteredBidRequestsList (Maybe Int32)
bfsfbrlPageSize
= lens _bfsfbrlPageSize
(\ s a -> s{_bfsfbrlPageSize = a})
. mapping _Coerce
-- | JSONP
bfsfbrlCallback :: Lens' BiddersFilterSetsFilteredBidRequestsList (Maybe Text)
bfsfbrlCallback
= lens _bfsfbrlCallback
(\ s a -> s{_bfsfbrlCallback = a})
instance GoogleRequest
BiddersFilterSetsFilteredBidRequestsList
where
type Rs BiddersFilterSetsFilteredBidRequestsList =
ListFilteredBidRequestsResponse
type Scopes BiddersFilterSetsFilteredBidRequestsList
=
'["https://www.googleapis.com/auth/adexchange.buyer"]
requestClient
BiddersFilterSetsFilteredBidRequestsList'{..}
= go _bfsfbrlFilterSetName _bfsfbrlXgafv
_bfsfbrlUploadProtocol
_bfsfbrlAccessToken
_bfsfbrlUploadType
_bfsfbrlPageToken
_bfsfbrlPageSize
_bfsfbrlCallback
(Just AltJSON)
adExchangeBuyer2Service
where go
= buildClient
(Proxy ::
Proxy
BiddersFilterSetsFilteredBidRequestsListResource)
mempty
| brendanhay/gogol | gogol-adexchangebuyer2/gen/Network/Google/Resource/AdExchangeBuyer2/Bidders/FilterSets/FilteredBidRequests/List.hs | mpl-2.0 | 7,543 | 0 | 18 | 1,576 | 891 | 520 | 371 | 135 | 1 |
{-# LANGUAGE OverloadedStrings, TemplateHaskell, TypeFamilies, RecordWildCards #-}
module Model.Volume.Types
( VolumeRow(..)
, Volume(..)
, VolumeOwner
, blankVolume
, toPolicyDefaulting
, volumeAccessPolicyWithDefault
, coreVolumeId
) where
import qualified Data.ByteString as BS
import Data.Maybe (fromMaybe)
import qualified Data.Text as T
import Data.Time.Clock.POSIX (posixSecondsToUTCTime)
import Language.Haskell.TH.Lift (deriveLiftMany)
import Has (Has(..))
import Model.Time
import Model.Kind
import Model.Permission.Types
import Model.Id.Types
import Model.Party.Types
type instance IdType Volume = Int32
data VolumeRow = VolumeRow
{ volumeId :: Id Volume
, volumeName :: T.Text
, volumeBody :: Maybe T.Text
, volumeAlias :: Maybe T.Text
, volumeDOI :: Maybe BS.ByteString
}
type VolumeOwner = (Id Party, T.Text)
data Volume = Volume
{ volumeRow :: !VolumeRow
, volumeCreation :: Timestamp
, volumeOwners :: [VolumeOwner]
, volumeRolePolicy :: VolumeRolePolicy
}
instance Kinded Volume where
kindOf _ = "volume"
{- instance Has (Id Volume) Volume where
view = (volumeId . volumeRow) -}
instance Has Permission Volume where
view = extractPermissionIgnorePolicy . volumeRolePolicy
deriveLiftMany [''VolumeRow, ''Volume]
-- | Convert shareFull value read from db into a policy
-- value, applying a default if needed.
toPolicyDefaulting :: Maybe Bool -> a -> a -> a
toPolicyDefaulting mShareFull noPolicy restrictedPolicy =
let
-- in the rare circumstance that a volume access
-- entry in db improperly contains null for public/shared group,
-- arbitrarily use True to follow old convention before sharefull
-- was introduced.
shareFull = fromMaybe True mShareFull
in
if shareFull then noPolicy else restrictedPolicy
volumeAccessPolicyWithDefault :: Permission -> Maybe Bool -> VolumeRolePolicy
volumeAccessPolicyWithDefault perm1 mShareFull =
case perm1 of
PermissionNONE ->
RoleNone
PermissionPUBLIC ->
RolePublicViewer (toPolicyDefaulting mShareFull PublicNoPolicy PublicRestrictedPolicy)
PermissionSHARED ->
RoleSharedViewer (toPolicyDefaulting mShareFull SharedNoPolicy SharedRestrictedPolicy)
PermissionREAD ->
RoleReader
PermissionEDIT ->
RoleEditor
PermissionADMIN ->
RoleAdmin
blankVolume :: Volume
blankVolume = Volume
{ volumeRow = VolumeRow
{ volumeId = error "blankVolume"
, volumeName = ""
, volumeAlias = Nothing
, volumeBody = Nothing
, volumeDOI = Nothing
}
, volumeCreation = posixSecondsToUTCTime 1357900000
, volumeOwners = []
, volumeRolePolicy = RoleNone
}
coreVolumeId :: Id Volume
coreVolumeId = Id 0
| databrary/databrary | src/Model/Volume/Types.hs | agpl-3.0 | 2,739 | 0 | 10 | 534 | 550 | 320 | 230 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
import Database.PostgreSQL.Migrations
import Database.PostgreSQL.Simple
up :: Connection -> IO ()
up = migrate $
create_table "hostname"
[ column "id" "serial PRIMARY KEY"
, column "hostname" "text NOT NULL UNIQUE"
, column "blog_id" "integer references blog(id)"]
down :: Connection -> IO ()
down = migrate $ do
drop_table "hostname"
main :: IO ()
main = defaultMain up down
| alevy/mappend | db/migrations/20151206190013_custom_hostnames.hs | agpl-3.0 | 425 | 0 | 8 | 75 | 115 | 59 | 56 | 14 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
import Graphics.UI.Gtk
import Control.Monad.IO.Class (liftIO)
import Data.Text (Text)
-- A function like this can be used to tag string literals for i18n.
-- It also avoids a lot of type annotations.
__ :: Text -> Text
__ = id -- Replace with getText from the hgettext package in localised versions
uiDef =
"<ui>\
\ <menubar>\
\ <menu name=\"File\" action=\"FileAction\">\
\ <menuitem name=\"New\" action=\"NewAction\" />\
\ <menuitem name=\"Open\" action=\"OpenAction\" />\
\ <menuitem name=\"Save\" action=\"SaveAction\" />\
\ <menuitem name=\"SaveAs\" action=\"SaveAsAction\" />\
\ <separator/>\
\ <menuitem name=\"Exit\" action=\"ExitAction\"/>\
\ <placeholder name=\"FileMenuAdditions\" />\
\ </menu>\
\ <menu name=\"Edit\" action=\"EditAction\">\
\ <menuitem name=\"Cut\" action=\"CutAction\"/>\
\ <menuitem name=\"Copy\" action=\"CopyAction\"/>\
\ <menuitem name=\"Paste\" action=\"PasteAction\"/>\
\ </menu>\
\ </menubar>\
\ <toolbar>\
\ <placeholder name=\"FileToolItems\">\
\ <separator/>\
\ <toolitem name=\"New\" action=\"NewAction\"/>\
\ <toolitem name=\"Open\" action=\"OpenAction\"/>\
\ <toolitem name=\"Save\" action=\"SaveAction\"/>\
\ <separator/>\
\ </placeholder>\
\ <placeholder name=\"EditToolItems\">\
\ <separator/>\
\ <toolitem name=\"Cut\" action=\"CutAction\"/>\
\ <toolitem name=\"Copy\" action=\"CopyAction\"/>\
\ <toolitem name=\"Paste\" action=\"PasteAction\"/>\
\ <separator/>\
\ </placeholder>\
\ </toolbar>\
\</ui>" :: Text
main = do
initGUI
-- Create the menus
fileAct <- actionNew "FileAction" (__"File") Nothing Nothing
editAct <- actionNew "EditAction" (__"Edit") Nothing Nothing
-- Create menu items
newAct <- actionNew "NewAction" (__"New")
(Just (__"Clear the spreadsheet area."))
(Just stockNew)
on newAct actionActivated $ putStrLn "New activated."
openAct <- actionNew "OpenAction" (__"Open")
(Just (__"Open an existing spreadsheet."))
(Just stockOpen)
on openAct actionActivated $ putStrLn "Open activated."
saveAct <- actionNew "SaveAction" (__"Save")
(Just (__"Save the current spreadsheet."))
(Just stockSave)
on saveAct actionActivated $ putStrLn "Save activated."
saveAsAct <- actionNew "SaveAsAction" (__"SaveAs")
(Just (__"Save spreadsheet under new name."))
(Just stockSaveAs)
on saveAsAct actionActivated $ putStrLn "SaveAs activated."
exitAct <- actionNew "ExitAction" (__"Exit")
(Just (__"Exit this application."))
(Just stockSaveAs)
on exitAct actionActivated $ mainQuit
cutAct <- actionNew "CutAction" (__"Cut")
(Just (__"Cut out the current selection."))
(Just stockCut)
on cutAct actionActivated $ putStrLn "Cut activated."
copyAct <- actionNew "CopyAction" (__"Copy")
(Just (__"Copy the current selection."))
(Just stockCopy)
on copyAct actionActivated $ putStrLn "Copy activated."
pasteAct <- actionNew "PasteAction" (__"Paste")
(Just (__"Paste the current selection."))
(Just stockPaste)
on pasteAct actionActivated $ putStrLn "Paste activated."
standardGroup <- actionGroupNew ("standard"::Text)
mapM_ (actionGroupAddAction standardGroup) [fileAct, editAct]
mapM_ (\act -> actionGroupAddActionWithAccel standardGroup act (Nothing::Maybe Text))
[newAct, openAct, saveAct, saveAsAct, exitAct, cutAct, copyAct, pasteAct]
ui <- uiManagerNew
mid <- uiManagerAddUiFromString ui uiDef
uiManagerInsertActionGroup ui standardGroup 0
win <- windowNew
on win objectDestroy mainQuit
on win sizeRequest $ return (Requisition 200 100)
(Just menuBar) <- uiManagerGetWidget ui ("/ui/menubar"::Text)
(Just toolBar) <- uiManagerGetWidget ui ("/ui/toolbar"::Text)
edit <- textViewNew
vBox <- vBoxNew False 0
set vBox [boxHomogeneous := False]
boxPackStart vBox menuBar PackNatural 0
boxPackStart vBox toolBar PackNatural 0
boxPackStart vBox edit PackGrow 0
containerAdd win vBox
widgetShowAll win
mainGUI
| juhp/gtk2hs | gtk/demo/actionMenu/ActionMenu.hs | lgpl-3.0 | 4,307 | 0 | 12 | 928 | 843 | 400 | 443 | 67 | 1 |
-- Simple Fibonacii
fib :: Int -> Int
fib x
| x < 3 = 1
| otherwise = fib (x - 1) + fib (x - 2)
| gnclmorais/interview-prep | recursion/04april/01fib.hs | unlicense | 108 | 0 | 9 | 40 | 62 | 30 | 32 | 4 | 1 |
module Main where
import Test.QuickCheck
import Data.Semigroup
------------------------------------------------------
-- Trivial
data Trivial = Trivial deriving (Eq, Show)
instance Semigroup Trivial where
_ <> _ = Trivial
instance Arbitrary Trivial where
arbitrary = return Trivial
semigroupAssoc :: (Eq m, Semigroup m) => m -> m -> m -> Bool
semigroupAssoc a b c = (a <> (b <> c)) == ((a <> b) <> c)
type TrivialAssoc = Trivial -> Trivial -> Trivial -> Bool
------------------------------------------------------
-- Identity a
newtype Identity a = Identity a deriving (Eq, Show)
instance Semigroup a => Semigroup (Identity a) where
(Identity x) <> (Identity y) = Identity (x <> y)
instance Arbitrary a => Arbitrary (Identity a) where
arbitrary = do
a <- arbitrary
return (Identity a)
type IdentityAssoc a = Identity a -> Identity a -> Identity a -> Bool
------------------------------------------------------
-- Combine a b
newtype Combine a b =
Combine { unCombine :: a -> b }
instance (Semigroup b) => Semigroup (Combine a b) where
Combine { unCombine = f } <> Combine { unCombine = g } = Combine (f <> g)
main :: IO ()
main = do
quickCheck (semigroupAssoc :: TrivialAssoc)
quickCheck (semigroupAssoc :: IdentityAssoc Trivial)
| thewoolleyman/haskellbook | 15/14/haskell-club/chapter-exercises/src/Main.hs | unlicense | 1,269 | 0 | 10 | 236 | 439 | 233 | 206 | 27 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-- Copyright 2014 (c) Diego Souza <[email protected]>
--
-- 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.
module Leela.Data.Types
( GUID (..)
, Kind (..)
, Mode (..)
, Node (..)
, Tree (..)
, User (..)
, Attr (..)
, Label (..)
, Value (..)
, Option (..)
, Journal (..)
, Matcher (..)
, TimeRange (..)
, AsLazyByteString (..)
, glob
, nextPage
, setOpt
, isPutNode
, isPutLink
, isDelLink
, isPutTAttr
, isPutLabel
, isPutKAttr
, isDelKAttr
, attrFromBS
, guidFromBS
, kindFromBS
, nodeFromBS
, treeFromBS
, userFromBS
, labelFromBS
, getMaxDataPoints
) where
import Data.Int
import Data.Word
import Control.Monad
import Data.Hashable
import Data.Serialize
import Control.DeepSeq
import qualified Data.ByteString as B
import Leela.Data.Time
import Control.Exception
import Leela.Data.Excepts
import Control.Applicative
import qualified Data.ByteString.Lazy as L
newtype GUID = GUID { unGUID :: L.ByteString }
deriving (Eq, Ord, Show)
newtype Label = Label L.ByteString
deriving (Eq, Ord, Show)
newtype Node = Node L.ByteString
deriving (Eq, Ord, Show)
newtype User = User L.ByteString
deriving (Eq, Ord, Show)
newtype Tree = Tree L.ByteString
deriving (Eq, Ord, Show)
newtype Kind = Kind L.ByteString
deriving (Eq, Ord, Show)
newtype Attr = Attr L.ByteString
deriving (Eq, Ord, Show)
data Value = Bool Bool
| Text L.ByteString
| Int32 Int32
| Int64 Int64
| Double Double
| UInt32 Word32
| UInt64 Word64
deriving (Show, Eq)
data TimeRange = Range Time Time
deriving (Eq)
data Matcher = ByLabel Label GUID
| ByNode GUID
deriving (Eq)
data Journal = PutLink GUID Label GUID
| PutLabel GUID Label
| PutNode User Tree Kind Node
| DelLink GUID Label (Maybe GUID)
| DelNode GUID
| DelKAttr GUID Attr
| PutKAttr GUID Attr Value [Option]
| DelTAttr GUID Attr TimeRange
| PutTAttr GUID Attr Time Value [Option]
deriving (Eq)
data Option = TTL Int
| Indexing
| MaxDataPoints Int
| Data L.ByteString L.ByteString
deriving (Show, Eq)
data Mode a = All (Maybe a)
| Prefix a a
| Precise a
class AsLazyByteString a where
asLazyByteString :: a -> L.ByteString
guidFromBS :: B.ByteString -> GUID
guidFromBS = GUID . L.fromStrict
kindFromBS :: B.ByteString -> Kind
kindFromBS = Kind . L.fromStrict
treeFromBS :: B.ByteString -> Tree
treeFromBS = Tree . L.fromStrict
labelFromBS :: B.ByteString -> Label
labelFromBS = Label . L.fromStrict
nodeFromBS :: B.ByteString -> Node
nodeFromBS = Node . L.fromStrict
userFromBS :: B.ByteString -> User
userFromBS = User . L.fromStrict
attrFromBS :: B.ByteString -> Attr
attrFromBS = Attr . L.fromStrict
isDelKAttr :: Journal -> Bool
isDelKAttr (DelKAttr {}) = True
isDelKAttr _ = False
isPutKAttr :: Journal -> Bool
isPutKAttr (PutKAttr {}) = True
isPutKAttr _ = False
isDelLink :: Journal -> Bool
isDelLink (DelLink {}) = True
isDelLink _ = False
isPutLink :: Journal -> Bool
isPutLink (PutLink {}) = True
isPutLink _ = False
isPutLabel :: Journal -> Bool
isPutLabel (PutLabel _ _) = True
isPutLabel _ = False
isPutNode :: Journal -> Bool
isPutNode (PutNode {}) = True
isPutNode _ = False
isPutTAttr :: Journal -> Bool
isPutTAttr (PutTAttr {}) = True
isPutTAttr _ = False
getMaxDataPoints :: [Option] -> Maybe Int
getMaxDataPoints [] = Nothing
getMaxDataPoints (MaxDataPoints n:_) = Just n
getMaxDataPoints (_:xs) = getMaxDataPoints xs
setOpt :: Option -> [Option] -> [Option]
setOpt o1 [] = [o1]
setOpt o1 (o : xs)
| o `same` o1 = o1 : xs
| otherwise = o : setOpt o1 xs
where
same (TTL _) (TTL _) = True
same (MaxDataPoints _) (MaxDataPoints _) = True
same Indexing Indexing = True
same _ _ = False
glob :: L.ByteString -> Mode L.ByteString
glob s
| "*" == s = All Nothing
| L.isSuffixOf "*" s = uncurry Prefix (range $ L.init s)
| otherwise = Precise s
where
range str = (str, L.init str `L.snoc` (L.last str + 1))
nextPage :: Mode a -> a -> Mode a
nextPage (All _) l = All (Just l)
nextPage (Prefix _ b) l = Prefix l b
nextPage _ _ = throw (SystemExcept (Just "Types/nextPage: precise mode has no pagination"))
instance Serialize Value where
put (Bool v) = do
putWord8 0
putWord8 (fromIntegral $ fromEnum v)
put (Text v) = do
putWord8 1
putWord16be (fromIntegral $ L.length v)
putLazyByteString v
put (Int32 v) = do
putWord8 2
putWord32be (fromIntegral v)
put (UInt32 v) = do
putWord8 3
putWord32be v
put (Int64 v) = do
putWord8 4
putWord64be (fromIntegral v)
put (UInt64 v) = do
putWord8 5
putWord64be v
put (Double v) = do
putWord8 6
putFloat64be v
get = do
magic <- getWord8
case magic of
0 -> fmap (Bool . toEnum . fromIntegral) getWord8
1 -> fmap Text (getWord16be >>= getLazyByteString . fromIntegral)
2 -> fmap (Int32 . fromIntegral) getWord32be
3 -> fmap UInt32 getWord32be
4 -> fmap (Int64 . fromIntegral) getWord64be
5 -> fmap UInt64 getWord64be
6 -> fmap Double getFloat64be
_ -> throw (SystemExcept (Just "Types/get: error decoding Value type"))
instance Serialize GUID where
get = GUID <$> get
put (GUID g) = put g
instance Serialize User where
get = User <$> get
put (User g) = put g
instance Serialize Tree where
get = Tree <$> get
put (Tree g) = put g
instance Serialize Label where
get = Label <$> get
put (Label l) = put l
instance Serialize Kind where
get = Kind <$> get
put (Kind k) = put k
instance Serialize Node where
get = Node <$> get
put (Node n) = put n
instance Serialize Attr where
get = Attr <$> get
put (Attr a) = put a
instance Serialize Option where
get = getWord8 >>= \ty ->
case ty of
0 -> TTL <$> get
1 -> return Indexing
2 -> MaxDataPoints <$> get
3 -> Data <$> get <*> get
_ -> mzero
put (TTL t) = putWord8 0 >> put t
put Indexing = putWord8 1
put (MaxDataPoints m) = putWord8 2 >> put m
put (Data k v) = putWord8 3 >> put k >> put v
instance Functor Mode where
fmap f (All ma) = All (fmap f ma)
fmap f (Prefix a b) = Prefix (f a) (f b)
fmap f (Precise a) = Precise (f a)
instance AsLazyByteString User where
asLazyByteString (User u) = u
instance AsLazyByteString Tree where
asLazyByteString (Tree t) = t
instance AsLazyByteString GUID where
asLazyByteString (GUID g) = g
instance AsLazyByteString Label where
asLazyByteString (Label l) = l
instance AsLazyByteString Kind where
asLazyByteString (Kind k) = k
instance AsLazyByteString Node where
asLazyByteString (Node n) = n
instance AsLazyByteString Attr where
asLazyByteString (Attr a) = a
instance NFData Value where
rnf (Bool v) = rnf v
rnf (Text v) = rnf v
rnf (Double v) = rnf v
rnf (Int32 v) = rnf v
rnf (Int64 v) = rnf v
rnf (UInt32 v) = rnf v
rnf (UInt64 v) = rnf v
instance Hashable GUID where
hashWithSalt salt (GUID v) = hashWithSalt salt v
instance Hashable Label where
hashWithSalt salt (Label v) = hashWithSalt salt v
instance Hashable Node where
hashWithSalt salt (Node v) = hashWithSalt salt v
instance Hashable User where
hashWithSalt salt (User v) = hashWithSalt salt v
instance Hashable Tree where
hashWithSalt salt (Tree v) = hashWithSalt salt v
instance Hashable Kind where
hashWithSalt salt (Kind v) = hashWithSalt salt v
instance Hashable Attr where
hashWithSalt salt (Attr v) = hashWithSalt salt v
| locaweb/leela | src/warpdrive/src/Leela/Data/Types.hs | apache-2.0 | 8,933 | 0 | 15 | 2,754 | 2,884 | 1,501 | 1,383 | 258 | 4 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Camfort.Specification.Stencils.Consistency ( consistent
, ConsistencyResult(..) ) where
import qualified Camfort.Helpers.Vec as V
import Camfort.Specification.Stencils.DenotationalSemantics
import Camfort.Specification.Stencils.Model
import Camfort.Specification.Stencils.Syntax
data ConsistencyResult =
Consistent
| Inconsistent String
deriving (Eq, Show)
-- | This function checks multiplicity consistency and then delegates the
-- spatial consistency to |consistent'| function.
consistent :: forall n .
Specification
-> Multiplicity (UnionNF n Offsets)
-> ConsistencyResult
consistent (Specification mult) observedIxs =
-- First do the linearity check
case (specModel, observedIxs) of
(Mult a, Mult b) -> a `consistent'` b
(Once a, Once b) -> a `consistent'` b
(Once _, Mult _) ->Inconsistent
"Specification is readOnce, but there are repeated indices."
(Mult _, Once _) -> Inconsistent
"Specification lacks readOnce, but the indices are inuque."
where
specModel :: Multiplicity (Approximation (UnionNF n (Interval Standard)))
specModel =
case sequence $ (sequence . fmap (regionsToIntervals nOfDims)) <$> mult of
Right model -> model
Left msg -> error msg
nOfDims :: V.Natural n
nOfDims = vecLength . peel $ observedIxs
-- | This is the actual consistency check using set comparison supplied in
-- the model.
consistent' :: Approximation (UnionNF n (Interval Standard))
-> UnionNF n Offsets
-> ConsistencyResult
consistent' (Exact unf) ixs =
case unfCompare unf ixs of
EQ -> Consistent
LT ->
Inconsistent "The specification covers a smaller area than the indices."
GT ->
Inconsistent "The specification covers a larger area than the indices."
consistent' (Bound (Just unf) Nothing) ixs =
case unfCompare unf ixs of
EQ -> Consistent
LT -> Consistent
GT -> Inconsistent $
"There are indices covered by the lower bound specification, but " ++
"could not observed in the indices."
consistent' (Bound Nothing (Just unf)) ixs =
case unfCompare unf ixs of
EQ -> Consistent
GT -> Consistent
LT -> Inconsistent
"There are indices outside the upper bound specification."
consistent' (Bound lb ub) ixs =
case (cLower, cUpper) of
(Consistent, Consistent) -> Consistent
(Consistent, inconsistent) -> inconsistent
(inconsistent, Consistent) -> inconsistent
(Inconsistent{}, Inconsistent{}) -> Inconsistent
"Neither the lower nor ther upper bound conform with the indices."
where
cLower = Bound lb Nothing `consistent'` ixs
cUpper = Bound Nothing ub `consistent'` ixs
| mrd/camfort | src/Camfort/Specification/Stencils/Consistency.hs | apache-2.0 | 2,846 | 0 | 14 | 672 | 650 | 346 | 304 | 63 | 10 |
-- Copyright 2018-2021 Google LLC
--
-- 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 ScopedTypeVariables #-}
module Main(main) where
import qualified Data.List.NonEmpty as NE
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.QuickCheck ((===), arbitrary, forAll)
import Test.Framework(defaultMain)
import Data.Collate
main :: IO ()
main = defaultMain
[ testProperty "sample equivalent to indexing" $
forAll ((NE.:|) <$> arbitrary <*> arbitrary) $
\ (xs :: NE.NonEmpty Int) i0 ->
let n = length xs
i = i0 `mod` n
in xs NE.!! i === collate (sample i id) xs
, testProperty "bulkSample equivalent to indexing" $
forAll ((NE.:|) <$> arbitrary <*> arbitrary) $
\ (xs :: NE.NonEmpty Int) (is0 :: [Int]) ->
let n = length xs
is = map (`mod` n) is0
in map (xs NE.!!) is === collate (bulkSample is id) xs
, testProperty "not quadratic" $
collate (bulkSample (replicate 10000 999999) id) [0..1000000] ===
replicate 10000 (999999 :: Integer)
]
| google/hs-collate | test/CollateTest.hs | apache-2.0 | 1,582 | 0 | 14 | 344 | 364 | 205 | 159 | 24 | 1 |
-- | Includes functions providing command line I/O
module Lycopene.Option
( module Lycopene.Option.Command
, module Lycopene.Option.Common
, module Lycopene.Option.Parser
) where
import Lycopene.Option.Common
import Lycopene.Option.Command
import Lycopene.Option.Parser
| utky/lycopene | src/Lycopene/Option.hs | apache-2.0 | 350 | 0 | 5 | 107 | 48 | 33 | 15 | 7 | 0 |
{-# LANGUAGE FlexibleContexts, RankNTypes, RecordWildCards #-}
module Cloud.AWS.CloudWatch.Internal
where
import Cloud.AWS.Lib.Parser.Unordered (XmlElement, (.<))
import Control.Applicative
import Control.Monad.Trans.Resource (MonadThrow, MonadResource, MonadBaseControl)
import Data.ByteString (ByteString)
import Cloud.AWS.Class
import Cloud.AWS.Lib.Query
import Cloud.AWS.CloudWatch.Types
-- | Ver.2010-08-01
apiVersion :: ByteString
apiVersion = "2010-08-01"
type CloudWatch m a = AWS AWSContext m a
cloudWatchQuery
:: (MonadBaseControl IO m, MonadResource m)
=> ByteString -- ^ Action
-> [QueryParam]
-> (XmlElement -> m a)
-> CloudWatch m a
cloudWatchQuery = commonQuery apiVersion
sinkDimension :: (MonadThrow m, Applicative m)
=> XmlElement -> m Dimension
sinkDimension xml = Dimension <$> xml .< "Name" <*> xml .< "Value"
fromDimension :: Dimension -> [QueryParam]
fromDimension Dimension{..} =
[ "Name" |= dimensionName
, "Value" |= dimensionValue
]
| worksap-ate/aws-sdk | Cloud/AWS/CloudWatch/Internal.hs | bsd-3-clause | 1,008 | 0 | 11 | 162 | 258 | 151 | 107 | 26 | 1 |
module Numeric.Carbonara.Format where
import Data.Text.Lazy.Builder.RealFloat ( formatRealFloat, FPFormat(..)) --text pkg
import Data.Text.Lazy.Builder (toLazyText)
import Data.Text.Lazy (unpack)
-- | round in decimal places
-- > pi -> 3.141592653589793
-- > roundTo 20 pi -> 3.141592653589793
-- > roundTo 4 pi -> 3.1416 --round up 5-9
-- > roundTo 3 pi -> 3.142
-- > roundTo 2 pi -> 3.14 --round down 0-4
-- > roundTo 1 pi -> 3.1
-- > roundTo 0 3141592.65 -> 3141593.0
-- > roundTo (-1) 3141592.65 -> 3141590.0
-- > roundTo (-2) 3141592.65 -> 3141600.0
-- > roundTo (-3) 3141592.65 -> 3142000.0
-- > roundTo (-4) 3141592.65 -> 3140000.0
roundTo :: (RealFrac a, Integral b) => b -> a -> a
roundTo i = let n = 10^^i in
(/n) . fromIntegral . round . (*n)
-- | eliminate trailing zeros
formatF :: (RealFloat a) => Int -> a -> String
formatF i = unpack . toLazyText . formatRealFloat Fixed (Just i)
| szehk/Haskell-Carbonara-Library | src/Numeric/Carbonara/Format.hs | bsd-3-clause | 1,003 | 0 | 10 | 263 | 184 | 111 | 73 | 9 | 1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import ClassyPrelude
import Data.Aeson.Text
import Data.Aeson.Types hiding (parse, Result)
import qualified Data.Char as Char
import Control.Concurrent.Async (waitBoth)
import Data.ByteString (breakSubstring)
import Network.URI (URI (..))
import qualified Network.URI as URI
import Text.HTML.TagSoup (parseTags)
-- import Text.StringLike (StringLike)
-- import qualified Text.StringLike as TS
import Text.HTML.TagSoup.Selection as TS
import Text.HTML.TagSoup.Tree (TagTree)
import Text.StringLike.Matchable (Matchable(..))
import qualified Data.Text as T
import System.IO (BufferMode (..), hSetBuffering,
stdout)
import GHC.Generics (Generic)
-- Library in the works
import Lens.Micro.Platform
import Charlotte
-- import qualified Charlotte.Request as Request
-- import qualified Charlotte.Response as CResponse
linkSelector :: Selector
Right linkSelector = parseSelector "a"
checkNull :: (s -> Bool) -> (s -> s -> Bool) -> (s -> s -> Bool)
checkNull null' comp s1 s2 = not (null' s1) && comp s1 s2
-- newtype MatchableText = MatchableText {unMatchableText :: Text} deriving (Show)
-- instance StringLike where
-- TODO: I'm pretty sure this unwrap/wrap is a Profunctor
-- figure out if I'm right. if so, badass.
-- uncons = second MatchableText <$> (uncons . unMatchableText)
-- uncons (MatchableText t) = (,) . fst <*> (MatchableText $ snd) <$> uncons t
-- toString MatchableText t) = MatchableText (unpack t)
-- fromChar = singleton . unMatchableText
-- strConcat = concat . unMatchableText
-- empty = MatchableText ""
-- strNull = null . unMatchableText
-- cons = cons . unMatchableText
-- append = append . unMatchableText
instance Matchable Text where
matchesExactly = (==)
matchesPrefixOf = checkNull null isPrefixOf
matchesInfixOf = checkNull null isInfixOf
matchesSuffixOf = checkNull null isSuffixOf
matchesWordOf s = any (`matchesExactly` s) . T.splitOn " \t\n\r"
data SearchPattern = SearchPattern
{ spPattern :: Text
, spInvertMatch :: Bool
} deriving (Show, Generic)
instance ToJSON SearchPattern where
toJSON = genericToJSON (mkOptions 2)
mkOptions :: Int -> Options
mkOptions n = defaultOptions {fieldLabelModifier = lowerOne . drop n}
where
lowerOne (x:xs) = Char.toLower x : xs
lowerOne [] = ""
data PageType = ScrapedPage Int Text
deriving (Show, Eq, Ord, Generic)
data Match = Match
{ matchPath :: Text
, matchPattern :: SearchPattern
, matchDepth :: Int
, matchRef :: Text
, matchInfo :: [MatchInfo]
} deriving (Show, Generic)
instance ToJSON Match where
toJSON = genericToJSON (mkOptions 5)
data MatchInfo = MatchInfo
{ matchInfoLine :: Int
, matchInfoColumn :: Int
} deriving (Show, Generic)
instance ToJSON MatchInfo where
toJSON = genericToJSON (mkOptions 9)
siteSearchSpider :: SpiderDefinition PageType Match
siteSearchSpider = let
Just crawlHostURI = URI.parseURI "http://local.lasvegassun.com"
in defaultSpider (ScrapedPage 0 mempty)
& name .~ "wfind-spider"
& startUrl .~ (ScrapedPage 1 "START", "http://local.lasvegassun.com")
& extract .~ parse 0 [] crawlHostURI
main :: IO ()
main = do
chan <- newTChanIO
a1 <- async $ wfind "http://local.lasvegassun.com" 2 [SearchPattern "<h1" False] chan
a2 <- async $ loop chan
_ <- waitBoth a1 a2
return ()
where
loop chan = do
mtext <- atomically $ readTChan chan
case mtext of
Nothing -> return ()
Just txt -> do
print txt
loop chan
wfind :: Text -> Int -> [SearchPattern] -> TChan (Maybe Text) -> IO ()
wfind uri' depth patterns chan = do
hSetBuffering stdout LineBuffering
let suri = unpack uri'
Just crawlHostURI = URI.parseURI suri
spider = defaultSpider (ScrapedPage 0 mempty)
& name .~ "wfind-spider"
& startUrl .~ (ScrapedPage 1 "START", uri')
& extract .~ parse depth patterns crawlHostURI
& load .~ Just (\x -> do
let payload = encodeToLazyText x :: LText
atomically $ writeTChan chan $ Just (toStrict payload)
return ())
_ <- atomically $ writeTChan chan $ Just "Starting Search..."
_ <- runSpider spider
_ <- atomically $ writeTChan chan Nothing
return ()
parse :: Int -> [SearchPattern] -> URI -> PageType -> CharlotteResponse -> [Result PageType Match]
parse maxDepth patterns crawlHostURI (ScrapedPage depth ref) resp = let
nextDepth = succ depth
tagTree = parseTagTree resp
links = parseLinks crawlHostURI tagTree
responsePath = resp ^. uri & URI.uriPath & pack
reqs = catMaybes $ mkRequest <$> map (pack . show) links
results = map (\r->Request (ScrapedPage nextDepth responsePath, r)) reqs
items = map Item $ mapMaybe (performPatternMatch resp responsePath depth ref) patterns
in if depth < maxDepth then results <> items else items
performPatternMatch :: CharlotteResponse -> Text -> Int -> Text -> SearchPattern -> Maybe Match
performPatternMatch resp curPath depth ref pat = do
let body = responseBody resp
pat' = spPattern pat
pat'' = encodeUtf8 pat' :: ByteString
body' = toStrict body
hasMatch = pat'' `isInfixOf` body'
invertMatch = spInvertMatch pat
if hasMatch && not invertMatch
then Just $ Match curPath pat depth ref (mkMatchInfo pat'' body')
else if invertMatch && not hasMatch then
Just $ Match curPath pat depth ref []
else Nothing
mkMatchInfo :: ByteString -> ByteString -> [MatchInfo]
mkMatchInfo pat body = let
patT = decodeUtf8 pat
bodyT = decodeUtf8 body
linesWithIndexes = [(i, encodeUtf8 p) | (p, i) <- zip (lines bodyT) [1..], patT `isInfixOf` p]
colIndex xs = length . fst $ breakSubstring pat xs
infoItems = [(i, colIndex txt) | (i, txt) <- linesWithIndexes]
in [MatchInfo l c | (l, c) <- infoItems]
parseTagTree :: CharlotteResponse -> [TagTree Text]
parseTagTree resp = let
r = decodeUtf8 $ toStrict $ responseBody resp :: Text
tags = parseTags r
in filter TS.isTagBranch $ TS.tagTree' tags
parseLinks :: URI -> [TagTree Text] -> [URI]
parseLinks crawlHostURI tt = let
maybeHostName l = URI.uriRegName <$> URI.uriAuthority l
setHostName l = l {
URI.uriAuthority=URI.uriAuthority crawlHostURI
, URI.uriScheme = URI.uriScheme crawlHostURI}
getHref = (TS.findTagBranchAttr "href" . TS.content)
links = mapMaybe getHref $ join $ TS.select linkSelector <$> tt
relLinks = filter ((==) (maybeHostName crawlHostURI) . maybeHostName) $
map setHostName $
mapMaybe URI.parseRelativeReference $
filter URI.isRelativeReference $
map unpack links
absLinks = filter ((==) (maybeHostName crawlHostURI) . maybeHostName) $
mapMaybe URI.parseAbsoluteURI $
filter URI.isAbsoluteURI $
map unpack links
in (absLinks <> relLinks)
| kitdallege/charlotte | app/Main.hs | bsd-3-clause | 7,270 | 0 | 20 | 1,786 | 2,030 | 1,060 | 970 | 151 | 3 |
module Test.Helper where
class C a where
method :: a -> Bool
instance C Int where
method _ = True
| bmillwood/notcpp | Test/Helper.hs | bsd-3-clause | 104 | 0 | 7 | 26 | 40 | 21 | 19 | 5 | 0 |
{-|
Module : RTable
Description : Implements the relational Table concept. Defines all necessary data types like RTable and RTuple and basic relational algebra operations on RTables.
Copyright : (c) Nikos Karagiannidis, 2017
License : GPL-3
Maintainer : [email protected]
Stability : experimental
Portability : POSIX
Here is a longer description of this module, containing some
commentary with @some markup@.
-}
{-# LANGUAGE OverloadedStrings #-}
-- :set -XOverloadedStrings
-- :set -XRecordWildCards
{-# LANGUAGE GeneralizedNewtypeDeriving -- In order to be able to derive from non-standard derivable classes (such as Num)
,BangPatterns
,RecordWildCards
,DeriveGeneric -- Allow automatic deriving of instances for the Generic typeclass (see Text.PrettyPrint.Tabulate.Example)
,DeriveDataTypeable -- Enable automatic deriving of instances for the Data typeclass (see Text.PrettyPrint.Tabulate.Example)
{--
:set -XDeriveGeneric
:set -XDeriveDataTypeable
--}
-- Allow definition of type class instances for type synonyms. (used for RTuple instance of Tabulate)
--,TypeSynonymInstances
--,FlexibleInstances
#-}
-- {-# LANGUAGE DuplicateRecordFields #-}
module Data.RTable
(
-- Relation(..)
RTable (..)
,RTuple (..)
,RTupleFormat (..)
,ColFormatMap
,FormatSpecifier (..)
,RPredicate
,RGroupPredicate
,RJoinPredicate
,UnaryRTableOperation
,BinaryRTableOperation
,Name
,ColumnName
,RTableName
,ColumnDType (..)
,RTableMData (..)
,RTupleMData
,RTimestamp (..)
,ColumnInfo (..)
,RDataType (..)
,ROperation (..)
,RAggOperation (..)
,IgnoreDefault (..)
,RTuplesRet
,RTabResult
,OrderingSpec (..)
,raggSum
,raggCount
,raggAvg
,raggMax
,raggMin
,emptyRTable
,emptyRTuple
,isRTabEmpty
,isRTupEmpty
,createSingletonRTable
,getColumnNamesfromRTab
,getColumnNamesfromRTuple
,createRDataType
,createNullRTuple
,createRtuple
,isNullRTuple
,restrictNrows
,createRTableMData
,createRTimeStamp
,getRTupColValue
,rtupLookup
,rtupLookupDefault
, (<!>)
,headRTup
,upsertRTuple
,rTimeStampToRText
,stdTimestampFormat
,stdDateFormat
,listOfColInfoRDataType
,toListColumnName
,toListColumnInfo
,toListRDataType
,rtupleToList
,rtupleFromList
,rtableToList
,rtableFromList
--,runRfilter
,f
--,runInnerJoin
,iJ
--,runLeftJoin
,lJ
--,runRightJoin
,rJ
-- full outer join
,foJ
-- ,runUnaryROperation
,ropU
-- ,runBinaryROperation
,ropB
--,runUnion
,u
--,runIntersect
,i
--,runDiff
,d
--,runProjection
,p
--,runAggregation
,rAgg
--,runGroupBy
,rG
,rO
--,runCombinedROp
,rComb
,stripRText
,removeCharAroundRText
,removeColumn
,addColumn
,isNull
,isNotNull
,nvl
,nvlColValue
,nvlRTuple
,nvlRTable
,decodeColValue
,decodeRTable
,rtabResult
,runRTabResult
,execRTabResult
,rtuplesRet
,getRTuplesRet
,printRTable
,printfRTable
,rtupleToList
,joinRTuples
,insertPrependRTab
,insertAppendRTab
,updateRTab
,rtabFoldr'
,rtabFoldl'
,rtabMap
,genDefaultColFormatMap
,genColFormatMap
,genRTupleFormat
,genRTupleFormatDefault
) where
import Debug.Trace
-- Data.Serialize (Cereal package)
-- https://hackage.haskell.org/package/cereal
-- https://hackage.haskell.org/package/cereal-0.5.4.0/docs/Data-Serialize.html
-- http://stackoverflow.com/questions/2283119/how-to-convert-a-integer-to-a-bytestring-in-haskell
import Data.Serialize (decode, encode)
-- Vector
import qualified Data.Vector as V
-- HashMap -- https://hackage.haskell.org/package/unordered-containers-0.2.7.2/docs/Data-HashMap-Strict.html
import Data.HashMap.Strict as HM
-- Text
import Data.Text as T
-- ByteString
import qualified Data.ByteString as BS
-- Typepable -- https://hackage.haskell.org/package/base-4.9.1.0/docs/Data-Typeable.html
-- http://stackoverflow.com/questions/6600380/what-is-haskells-data-typeable
-- http://alvinalexander.com/source-code/haskell/how-determine-type-object-haskell-program
import qualified Data.Typeable as TB --(typeOf, Typeable)
-- Dynamic
import qualified Data.Dynamic as D -- https://hackage.haskell.org/package/base-4.9.1.0/docs/Data-Dynamic.html
-- Data.List
import Data.List (last, all, elem, map, zip, zipWith, elemIndex, sortOn, union, intersect, (\\), take, length, repeat, groupBy, sort, sortBy, foldl', foldr, foldr1, foldl',head)
-- Data.Maybe
import Data.Maybe (fromJust)
-- Data.Char
import Data.Char (toUpper,digitToInt, isDigit)
-- Data.Monoid
import Data.Monoid as M
-- Control.Monad.Trans.Writer.Strict
import Control.Monad.Trans.Writer.Strict (Writer, writer, runWriter, execWriter)
-- Text.Printf
import Text.Printf (printf)
-- import Control.Monad.IO.Class (liftIO)
{--- Text.PrettyPrint.Tabulate
import qualified Text.PrettyPrint.Tabulate as PP
import qualified GHC.Generics as G
import Data.Data
-}
--import qualified Text.PrettyPrint.Boxes as BX
--import Data.Map (fromList)
--import qualified Data.Map.Strict as Map -- Data.Map.Strict https://www.stackage.org/haddock/lts-7.4/containers-0.5.7.1/Data-Map-Strict.html
--import qualified Data.Set as Set -- https://www.stackage.org/haddock/lts-7.4/containers-0.5.7.1/Data-Set.html#t:Set
--import qualified Data.ByteString as BS -- Data.ByteString https://www.stackage.org/haddock/lts-7.4/bytestring-0.10.8.1/Data-ByteString.html
{--
-- | Definition of the Relation entity
data Relation
-- = RelToBeDefined deriving (Show)
= Relation -- ^ A Relation is essentially a set of tuples
{
relname :: String -- ^ The name of the Relation (metadata)
,fields :: [RelationField] -- ^ The list of fields (i.e., attributes) of the relation (metadata)
,tuples :: Set.Set Rtuple -- ^ A relation is essentially a set o tuples (data)
}
| EmptyRel -- ^ An empty relation
deriving Show
--}
-- * ########## Data Types ##############
-- | Definition of the Relational Table entity
-- An RTable is essentially a vector of RTuples.
type RTable = V.Vector RTuple
-- | Definition of the Relational Tuple
-- An RTuple is implemented as a hash map (colummname, RDataType). This ensures fast access of the column value by column name.
-- Note that this implies that the RTuple CANNOT have more than one columns with the same name (i.e. hashmap key) and more importantly that
-- it DOES NOT have a fixed order of columns, as it is usual in RDBMS implementations.
-- This gives us the freedom to perform column changes operations very fast.
-- The only place were we need fixed column order is when we try to load an RTable from a fixed-column structure such as a CSV file.
-- For this reason, we have embedded the notion of a fixed column-order in the RTuple metadata. See 'RTupleMData'.
type RTuple = HM.HashMap ColumnName RDataType
-- | Turns a RTable to a list
rtableToList :: RTable -> [RTuple]
rtableToList = V.toList
-- | Creates an RTable from a list of RTuples
rtableFromList :: [RTuple] -> RTable
rtableFromList = V.fromList
-- | Turns an RTuple to a List
rtupleToList :: RTuple -> [(ColumnName, RDataType)]
rtupleToList = HM.toList
-- | Create an RTuple from a list
rtupleFromList :: [(ColumnName, RDataType)] -> RTuple
rtupleFromList = HM.fromList
{-
instance Data RTuple
instance G.Generic RTuple
instance PP.Tabulate RTuple
-}
-- | Definitioin of the Name type
type Name = String
-- | Definition of the Column Name
type ColumnName = Name
-- instance PP.Tabulate ColumnName
-- | Definition of the Table Name
type RTableName = Name
-- | This is used only for metadata purposes. The actual data type of a value is an RDataType
-- The String component of Date data constructor is the date format e.g., "DD/MM/YYYY"
data ColumnDType = Integer | Varchar | Date String | Timestamp String | Double deriving (Show, Eq)
-- | Definition of the Relational Data Types
-- These will be the data types supported by the RTable.
-- Essentially an RDataType is a wrpapper of Haskell common data types.
data RDataType =
RInt { rint :: Integer }
-- RChar { rchar :: Char }
| RText { rtext :: T.Text }
-- RString {rstring :: [Char]}
| RDate {
rdate :: T.Text
,dtformat :: String -- ^ e.g., "DD/MM/YYYY"
}
| RTime { rtime :: RTimestamp }
| RDouble { rdouble :: Double }
-- RFloat { rfloat :: Float }
| Null
deriving (Show,TB.Typeable, Read) -- http://stackoverflow.com/questions/6600380/what-is-haskells-data-typeable
-- | We need to explicitly specify due to NULL logic (anything compared to NULL returns false)
-- @
-- Null == _ = False
-- _ == Null = False
-- Null /= _ = False
-- _ /= Null = False
-- @
-- IMPORTANT NOTE:
-- Of course this means that anywhere in your code where you have something like this x == Null or x /= Null, will always return False and
-- thus it is futile to do this comparison. You have to use the is isNull function instead.
--
instance Eq RDataType where
RInt i1 == RInt i2 = i1 == i2
-- RInt i == _ = False
RText t1 == RText t2 = t1 == t2
-- RText t1 == _ = False
RDate t1 s1 == RDate t2 s2 = (t1 == t1) && (s1 == s2)
-- RDate t1 s1 == _ = False
RTime t1 == RTime t2 = t1 == t2
-- RTime t1 == _ = False
RDouble d1 == RDouble d2 = d1 == d2
-- RDouble d1 == _ = False
-- Watch out: NULL logic (anything compared to NULL returns false)
Null == Null = False
_ == Null = False
Null == _ = False
-- anything else is just False
_ == _ = False
Null /= Null = False
_ /= Null = False
Null /= _ = False
x /= y = not (x == y)
-- Need to explicitly specify due to "Null logic" (see Eq)
instance Ord RDataType where
Null <= _ = False
_ <= Null = False
Null <= Null = False
RInt i1 <= RInt i2 = i1 <= i2
RText t1 <= RText t2 = t1 <= t2
RDate t1 s1 <= RDate t2 s2 = (t1 <= t1) && (s1 == s2)
RTime t1 <= RTime t2 = t1 <= t2
RTime t1 <= _ = False
RDouble d1 <= RDouble d2 = d1 <= d2
-- anything else is just False
_ <= _ = False
-- | Use this function to compare an RDataType with the Null value because due to Null logic
-- x == Null or x /= Null, will always return False.
-- It returns True if input value is Null
isNull :: RDataType -> Bool
isNull x =
case x of
Null -> True
_ -> False
-- | Use this function to compare an RDataType with the Null value because deu to Null logic
-- x == Null or x /= Null, will always return False.
-- It returns True if input value is Not Null
isNotNull = not . isNull
instance Num RDataType where
(+) (RInt i1) (RInt i2) = RInt (i1 + i2)
(+) (RDouble d1) (RDouble d2) = RDouble (d1 + d2)
(+) (RDouble d1) (RInt i2) = RDouble (d1 + fromIntegral i2)
(+) (RInt i1) (RDouble d2) = RDouble (fromIntegral i1 + d2)
-- (+) (RInt i1) (Null) = RInt i1 -- ignore Null - just like in SQL
-- (+) (Null) (RInt i2) = RInt i2 -- ignore Null - just like in SQL
-- (+) (RDouble d1) (Null) = RDouble d1 -- ignore Null - just like in SQL
-- (+) (Null) (RDouble d2) = RDouble d2 -- ignore Null - just like in SQL
(+) (RInt i1) (Null) = Null
(+) (Null) (RInt i2) = Null
(+) (RDouble d1) (Null) = Null
(+) (Null) (RDouble d2) = Null
(+) _ _ = Null
(*) (RInt i1) (RInt i2) = RInt (i1 * i2)
(*) (RDouble d1) (RDouble d2) = RDouble (d1 * d2)
(*) (RDouble d1) (RInt i2) = RDouble (d1 * fromIntegral i2)
(*) (RInt i1) (RDouble d2) = RDouble (fromIntegral i1 * d2)
-- (*) (RInt i1) (Null) = RInt i1 -- ignore Null - just like in SQL
-- (*) (Null) (RInt i2) = RInt i2 -- ignore Null - just like in SQL
-- (*) (RDouble d1) (Null) = RDouble d1 -- ignore Null - just like in SQL
-- (*) (Null) (RDouble d2) = RDouble d2 -- ignore Null - just like in SQL
(*) (RInt i1) (Null) = Null
(*) (Null) (RInt i2) = Null
(*) (RDouble d1) (Null) = Null
(*) (Null) (RDouble d2) = Null
(*) _ _ = Null
abs (RInt i) = RInt (abs i)
abs (RDouble i) = RDouble (abs i)
abs _ = Null
signum (RInt i) = RInt (signum i)
signum (RDouble i) = RDouble (signum i)
signum _ = Null
fromInteger i = RInt i
negate (RInt i) = RInt (negate i)
negate (RDouble i) = RDouble (negate i)
negate _ = Null
-- | In order to be able to use (/) with RDataType
instance Fractional RDataType where
(/) (RInt i1) (RInt i2) = RDouble $ (fromIntegral i1)/(fromIntegral i2)
(/) (RDouble d1) (RInt i2) = RDouble $ (d1)/(fromIntegral i2)
(/) (RInt i1) (RDouble d2) = RDouble $ (fromIntegral i1)/(d2)
(/) (RDouble d1) (RDouble d2) = RDouble $ d1/d2
(/) _ _ = Null
-- In order to be able to turn a Rational number into an RDataType, e.g. in the case: totamnt / 12.0
-- where totamnt = RDouble amnt
-- fromRational :: Rational -> a
fromRational r = RDouble (fromRational r)
-- | Standard date format
stdDateFormat = "DD/MM/YYYY"
-- | Get the Column Names of an RTable
getColumnNamesfromRTab :: RTable -> [ColumnName]
getColumnNamesfromRTab rtab = getColumnNamesfromRTuple $ headRTup rtab
-- | Get the first RTuple from an RTable
headRTup ::
RTable
-> RTuple
headRTup = V.head
-- | Returns the Column Names of an RTuple
getColumnNamesfromRTuple :: RTuple -> [ColumnName]
getColumnNamesfromRTuple t = HM.keys t
-- | Returns the value of an RTuple column based on the ColumnName key
-- if the column name is not found, then it returns Nothing
rtupLookup ::
ColumnName -- ^ ColumnName key
-> RTuple -- ^ Input RTuple
-> Maybe RDataType -- ^ Output value
rtupLookup = HM.lookup
-- | Returns the value of an RTuple column based on the ColumnName key
-- if the column name is not found, then it returns a default value
rtupLookupDefault ::
RDataType -- ^ Default value to return in the case the column name does not exist in the RTuple
-> ColumnName -- ^ ColumnName key
-> RTuple -- ^ Input RTuple
-> RDataType -- ^ Output value
rtupLookupDefault = HM.lookupDefault
-- | getRTupColValue :: Returns the value of an RTuple column based on the ColumnName key
-- if the column name is not found, then it returns Null.
-- !!!Note that this might be confusing since there might be an existing column name with a Null value!!!
getRTupColValue ::
ColumnName -- ^ ColumnName key
-> RTuple -- ^ Input RTuple
-> RDataType -- ^ Output value
getRTupColValue = rtupLookupDefault Null -- HM.lookupDefault Null
-- | Operator for getting a column value from an RTuple
-- Calls error if this map contains no mapping for the key.
(<!>) ::
RTuple -- ^ Input RTuple
-> ColumnName -- ^ ColumnName key
-> RDataType -- ^ Output value
(<!>) t c = -- flip getRTupColValue
-- (HM.!)
case rtupLookup c t of
Just v -> v
Nothing -> error $ "*** Error in function Data.RTable.(<!>): Column \"" ++ c ++ "\" does not exist! ***"
-- | Returns the 1st parameter if this is not Null, otherwise it returns the 2nd.
nvl ::
RDataType -- ^ input value
-> RDataType -- ^ default value returned if input value is Null
-> RDataType -- ^ output value
nvl v defaultVal =
if isNull v
then defaultVal
else v
-- | Returns the value of a specific column (specified by name) if this is not Null.
-- If this value is Null, then it returns the 2nd parameter.
-- If you pass an empty RTuple, then it returns Null.
-- Calls error if this map contains no mapping for the key.
nvlColValue ::
ColumnName -- ^ ColumnName key
-> RDataType -- ^ value returned if original value is Null
-> RTuple -- ^ input RTuple
-> RDataType -- ^ output value
nvlColValue col defaultVal tup =
if isRTupEmpty tup
then Null
else
case tup <!> col of
Null -> defaultVal
val -> val
data IgnoreDefault = Ignore | NotIgnore deriving (Eq, Show)
-- | It receives an RTuple and lookups the value at a specfic column name.
-- Then it compares this value with the specified search value. If it is eaqual to the search value
-- then it returns the specified Return Value. If not, the it returns the specified default Value (if the ignore indicator is not set).
-- If you pass an empty RTuple, then it returns Null.
-- Calls error if this map contains no mapping for the key.
decodeColValue ::
ColumnName -- ^ ColumnName key
-> RDataType -- ^ Search value
-> RDataType -- ^ Return value
-> RDataType -- ^ Default value
-> IgnoreDefault -- ^ Ignore default indicator
-> RTuple -- ^ input RTuple
-> RDataType
decodeColValue cname searchVal returnVal defaultVal ignoreInd tup =
if isRTupEmpty tup
then Null
else
case tup <!> cname of
searchVal -> returnVal
v -> if ignoreInd == Ignore then v else defaultVal
-- | It receives an RTuple and a default value. It returns a new RTuple which is identical to the source one
-- but every Null value in the specified colummn has been replaced by a default value
nvlRTuple ::
ColumnName -- ^ ColumnName key
-> RDataType -- ^ Default value in the case of Null column values
-> RTuple -- ^ input RTuple
-> RTuple -- ^ output RTuple
nvlRTuple c defaultVal tup =
if isRTupEmpty tup
then emptyRTuple
else HM.map (\v -> nvl v defaultVal) tup
-- | It receives an RTable and a default value. It returns a new RTable which is identical to the source one
-- but for each RTuple, for the specified column every Null value in every RTuple has been replaced by a default value
-- If you pass an empty RTable, then it returns an empty RTable
-- Calls error if the column does not exist
nvlRTable ::
ColumnName -- ^ ColumnName key
-> RDataType -- ^ Default value
-> RTable -- ^ input RTable
-> RTable
nvlRTable c defaultVal tab =
if isRTabEmpty tab
then emptyRTable
else
V.map (\t -> upsertRTuple c (nvlColValue c defaultVal t) t) tab
--V.map (\t -> nvlRTuple c defaultVal t) tab
-- | It receives an RTable, a search value and a default value. It returns a new RTable which is identical to the source one
-- but for each RTuple, for the specified column:
-- * if the search value was found then the specified Return Value is returned
-- * else the default value is returned (if the ignore indicator is not set)
-- If you pass an empty RTable, then it returns an empty RTable
-- Calls error if the column does not exist
decodeRTable ::
ColumnName -- ^ ColumnName key
-> RDataType -- ^ Search value
-> RDataType -- ^ Return value
-> RDataType -- ^ Default value
-> IgnoreDefault -- ^ Ignore default indicator
-> RTable -- ^ input RTable
-> RTable
decodeRTable cName searchVal returnVal defaultVal ignoreInd tab =
if isRTabEmpty tab
then emptyRTable
else
V.map (\t -> upsertRTuple cName (decodeColValue cName searchVal returnVal defaultVal ignoreInd t) t) tab
-- | Upsert (update/insert) an RTuple at a specific column specified by name with a value
-- If the cname key is not found then the (columnName, value) pair is inserted. If it exists
-- then the value is updated with the input value.
upsertRTuple ::
ColumnName -- ^ key where the upset will take place
-> RDataType -- ^ new value
-> RTuple -- ^ input RTuple
-> RTuple -- ^ output RTuple
upsertRTuple cname newVal tupsrc = HM.insert cname newVal tupsrc
-- newtype NumericRDT = NumericRDT { getRDataType :: RDataType } deriving (Eq, Ord, Read, Show, Num)
-- | stripRText : O(n) Remove leading and trailing white space from a string.
-- If the input RDataType is not an RText, then Null is returned
stripRText ::
RDataType -- ^ input string
-> RDataType
stripRText (RText t) = RText $ T.strip t
stripRText _ = Null
-- | Helper function to remove a character around (from both beginning and end) of an (RText t) value
removeCharAroundRText :: Char -> RDataType -> RDataType
removeCharAroundRText ch (RText t) = RText $ T.dropAround (\c -> c == ch) t
removeCharAroundRText ch _ = Null
-- | RTimestamp data type
data RTimestamp = RTimestampVal {
year :: Int
,month :: Int
,day :: Int
,hours24 :: Int
,minutes :: Int
,seconds :: Int
} deriving (Show, Read)
instance Eq RTimestamp where
RTimestampVal y1 m1 d1 h1 mi1 s1 == RTimestampVal y2 m2 d2 h2 mi2 s2 =
y1 == y2 && m1 == m2 && d1 == d2 && h1 == h2 && mi1 == mi2 && s1 == s2
instance Ord RTimestamp where
-- compare :: a -> a -> Ordering
compare (RTimestampVal y1 m1 d1 h1 mi1 s1) (RTimestampVal y2 m2 d2 h2 mi2 s2) =
if compare y1 y2 /= EQ
then compare y1 y2
else
if compare m1 m2 /= EQ
then compare m1 m2
else if compare d1 d2 /= EQ
then compare d1 d2
else if compare h1 h2 /= EQ
then compare h1 h2
else if compare mi1 mi2 /= EQ
then compare mi1 mi2
else if compare s1 s2 /= EQ
then compare s1 s2
else EQ
-- | Creates an RTimestamp data type from an input timestamp format string and a timestamp value represented as Text.
createRTimeStamp ::
String -- ^ Format string e.g., "DD/MM/YYYY HH24:MI:SS"
-> String -- ^ Timestamp string
-> RTimestamp
createRTimeStamp fmt timeVal =
case Prelude.map (Data.Char.toUpper) fmt of
"DD/MM/YYYY HH24:MI:SS" -> parseTime timeVal
"\"DD/MM/YYYY HH24:MI:SS\"" -> parseTime timeVal
where
parseTime :: String -> RTimestamp
parseTime (d1:d2:'/':m1:m2:'/':y1:y2:y3:y4:' ':h1:h2:':':mi1:mi2:':':s1:s2:_) = RTimestampVal {
year = (digitToInt y1) * 1000 + (digitToInt y2) * 100 + (digitToInt y3) * 10 + (digitToInt y4)
,month = (digitToInt m1) * 10 + (digitToInt m2)
,day = (digitToInt d1) * 10 + (digitToInt d2)
,hours24 = (digitToInt h1) * 10 + (digitToInt h2)
,minutes = (digitToInt mi1) * 10 + (digitToInt mi2)
,seconds = (digitToInt s1) * 10 + (digitToInt s2)
}
parseTime (d1:'/':m1:m2:'/':y1:y2:y3:y4:' ':h1:h2:':':mi1:mi2:':':s1:s2:_) = RTimestampVal {
year = (digitToInt y1) * 1000 + (digitToInt y2) * 100 + (digitToInt y3) * 10 + (digitToInt y4)
,month = (digitToInt m1) * 10 + (digitToInt m2)
,day = (digitToInt d1)
,hours24 = (digitToInt h1) * 10 + (digitToInt h2)
,minutes = (digitToInt mi1) * 10 + (digitToInt mi2)
,seconds = (digitToInt s1) * 10 + (digitToInt s2)
}
parseTime (d1:'/':m1:'/':y1:y2:y3:y4:' ':h1:h2:':':mi1:mi2:':':s1:s2:_) = RTimestampVal {
year = (digitToInt y1) * 1000 + (digitToInt y2) * 100 + (digitToInt y3) * 10 + (digitToInt y4)
,month = (digitToInt m1)
,day = (digitToInt d1)
,hours24 = (digitToInt h1) * 10 + (digitToInt h2)
,minutes = (digitToInt mi1) * 10 + (digitToInt mi2)
,seconds = (digitToInt s1) * 10 + (digitToInt s2)
}
parseTime (d1:d2:'/':m1:'/':y1:y2:y3:y4:' ':h1:h2:':':mi1:mi2:':':s1:s2:_) = RTimestampVal {
year = (digitToInt y1) * 1000 + (digitToInt y2) * 100 + (digitToInt y3) * 10 + (digitToInt y4)
,month = (digitToInt m1)
,day = (digitToInt d1) * 10 + (digitToInt d2)
,hours24 = (digitToInt h1) * 10 + (digitToInt h2)
,minutes = (digitToInt mi1) * 10 + (digitToInt mi2)
,seconds = (digitToInt s1) * 10 + (digitToInt s2)
}
parseTime _ = RTimestampVal {year = 2999, month = 12, day = 31, hours24 = 11, minutes = 59, seconds = 59}
-- | Standard timestamp format
stdTimestampFormat = "DD/MM/YYYY HH24:MI:SS"
-- | rTimeStampToText: converts an RTimestamp value to RText
rTimeStampToRText ::
String -- ^ Output format e.g., DD/MM/YYYY HH24:MI:SS
-> RTimestamp -- ^ Input RTimestamp
-> RDataType -- ^ Output RText
rTimeStampToRText "DD/MM/YYYY HH24:MI:SS" ts = let -- timeString = show (day ts) ++ "/" ++ show (month ts) ++ "/" ++ show (year ts) ++ " " ++ show (hours24 ts) ++ ":" ++ show (minutes ts) ++ ":" ++ show (seconds ts)
timeString = expand (day ts) ++ "/" ++ expand (month ts) ++ "/" ++ expand (year ts) ++ " " ++ expand (hours24 ts) ++ ":" ++ expand (minutes ts) ++ ":" ++ expand (seconds ts)
expand i = if i < 10 then "0"++ (show i) else show i
in RText $ T.pack timeString
rTimeStampToRText "YYYYMMDD-HH24.MI.SS" ts = let -- timeString = show (year ts) ++ show (month ts) ++ show (day ts) ++ "-" ++ show (hours24 ts) ++ "." ++ show (minutes ts) ++ "." ++ show (seconds ts)
timeString = expand (year ts) ++ expand (month ts) ++ expand (day ts) ++ "-" ++ expand (hours24 ts) ++ "." ++ expand (minutes ts) ++ "." ++ expand (seconds ts)
expand i = if i < 10 then "0"++ (show i) else show i
{-
!dummy1 = trace ("expand (year ts) : " ++ expand (year ts)) True
!dummy2 = trace ("expand (month ts) : " ++ expand (month ts)) True
!dummy3 = trace ("expand (day ts) : " ++ expand (day ts)) True
!dummy4 = trace ("expand (hours24 ts) : " ++ expand (hours24 ts)) True
!dummy5 = trace ("expand (minutes ts) : " ++ expand (minutes ts)) True
!dummy6 = trace ("expand (seconds ts) : " ++ expand (seconds ts)) True-}
in RText $ T.pack timeString
rTimeStampToRText "YYYYMMDD" ts = let
timeString = expand (year ts) ++ expand (month ts) ++ expand (day ts)
expand i = if i < 10 then "0"++ (show i) else show i
in RText $ T.pack timeString
rTimeStampToRText "YYYYMM" ts = let
timeString = expand (year ts) ++ expand (month ts)
expand i = if i < 10 then "0"++ (show i) else show i
in RText $ T.pack timeString
rTimeStampToRText "YYYY" ts = let
timeString = show $ year ts -- expand (year ts)
-- expand i = if i < 10 then "0"++ (show i) else show i
in RText $ T.pack timeString
-- | Metadata for an RTable
data RTableMData = RTableMData {
rtname :: RTableName
,rtuplemdata :: RTupleMData -- ^ Tuple-level metadata
-- other metadata
,pkColumns :: [ColumnName] -- ^ Primary Key
,uniqueKeys :: [[ColumnName]] -- ^ List of unique keys i.e., each sublist is a unique key column combination
} deriving (Show, Eq)
-- | createRTableMData : creates RTableMData from input given in the form of a list
-- We assume that the column order of the input list defines the fixed column order of the RTuple.
createRTableMData ::
(RTableName, [(ColumnName, ColumnDType)])
-> [ColumnName] -- ^ Primary Key. [] if no PK exists
-> [[ColumnName]] -- ^ list of unique keys. [] if no unique keys exists
-> RTableMData
createRTableMData (n, cdts) pk uks =
RTableMData { rtname = n, rtuplemdata = createRTupleMdata cdts, pkColumns = pk, uniqueKeys = uks }
-- | createRTupleMdata : Creates an RTupleMData instance based on a list of (Column name, Column Data type) pairs.
-- The order in the input list defines the fixed column order of the RTuple
createRTupleMdata :: [(ColumnName, ColumnDType)] -> RTupleMData
-- createRTupleMdata clist = Prelude.map (\(n,t) -> (n, ColumnInfo{name = n, colorder = fromJust (elemIndex (n,t) clist), dtype = t })) clist
--HM.fromList $ Prelude.map (\(n,t) -> (n, ColumnInfo{name = n, colorder = fromJust (elemIndex (n,t) clist), dtype = t })) clist
createRTupleMdata clist =
let colNamecolInfo = Prelude.map (\(n,t) -> (n, ColumnInfo{ name = n
--,colorder = fromJust (elemIndex (n,t) clist)
,dtype = t
})) clist
colOrdercolName = Prelude.map (\(n,t) -> (fromJust (elemIndex (n,t) clist), n)) clist
in (HM.fromList colOrdercolName, HM.fromList colNamecolInfo)
-- Old - Obsolete:
-- Basic Metadata of an RTuple
-- Initially design with a HashMap, but HashMaps dont guarantee a specific ordering when turned into a list.
-- We implement the fixed column order logic for an RTuple, only at metadata level and not at the RTuple implementation, which is a HashMap (see @ RTuple)
-- So the fixed order of this list equals the fixed column order of the RTuple.
--type RTupleMData = [(ColumnName, ColumnInfo)] -- HM.HashMap ColumnName ColumnInfo
-- | Basic Metadata of an RTuple.
-- The RTuple metadata are accessed through a HashMap ColumnName ColumnInfo structure. I.e., for each column of the RTuple,
-- we access the ColumnInfo structure to get Column-level metadata. This access is achieved by ColumnName.
-- However, in order to provide the "impression" of a fixed column order per tuple (see 'RTuple' definition), we provide another HashMap,
-- the HashMap ColumnOrder ColumnName. So if we want to access the RTupleMData tupmdata ColumnInfo by column order, we have to do the following:
--
-- @
-- (snd tupmdata)!((fst tupmdata)!0)
-- (snd tupmdata)!((fst tupmdata)!1)
-- ...
-- (snd tupmdata)!((fst tupmdata)!N)
-- @
--
-- In the same manner in order to access the column of an RTuple (e.g., tup) by column order we do the following:
--
-- @
-- tup!((fst tupmdata)!0)
-- tup!((fst tupmdata)!1)
-- ...
-- tup!((fst tupmdata)!N)
-- @
--
type RTupleMData = (HM.HashMap ColumnOrder ColumnName, HM.HashMap ColumnName ColumnInfo)
type ColumnOrder = Int
-- | toListColumnName: returns a list of RTuple column names, in the fixed column order of the RTuple.
toListColumnName ::
RTupleMData
-> [ColumnName]
toListColumnName rtupmd =
let mapColOrdColName = fst rtupmd
listColOrdColName = HM.toList mapColOrdColName -- generate a list of [ColumnOrdr, ColumnName] in random order
-- order list based on ColumnOrder
ordlistColOrdColName = sortOn (\(o,c) -> o) listColOrdColName -- Data.List.sortOn :: Ord b => (a -> b) -> [a] -> [a]. Sort a list by comparing the results of a key function applied to each element.
in Prelude.map (snd) ordlistColOrdColName
-- | toListColumnInfo: returns a list of RTuple columnInfo, in the fixed column order of the RTuple
toListColumnInfo ::
RTupleMData
-> [ColumnInfo]
toListColumnInfo rtupmd =
let mapColNameColInfo = snd rtupmd
in Prelude.map (\cname -> mapColNameColInfo HM.! cname) (toListColumnName rtupmd)
-- | toListRDataType: returns a list of RDataType values of an RTuple, in the fixed column order of the RTuple
toListRDataType ::
RTupleMData
-> RTuple
-> [RDataType]
toListRDataType rtupmd rtup = Prelude.map (\cname -> rtup <!> cname) (toListColumnName rtupmd)
-- | Basic metadata for a column of an RTuple
data ColumnInfo = ColumnInfo {
name :: ColumnName
-- ,colorder :: Int -- ^ ordering of column within the RTuple (each new column added takes colorder+1)
-- Since an RTuple is implemented as a HashMap ColumnName RDataType, ordering of columns has no meaning.
-- However, with this columns we can "pretend" that there is a fixed column order in each RTuple.
,dtype :: ColumnDType
} deriving (Show, Eq)
-- | Creates a list of the form [(ColumnInfo, RDataType)] from a list of ColumnInfo and an RTuple. The returned list respects the order of the [ColumnInfo]
-- Prelude.zip listOfColInfo (Prelude.map (snd) $ HM.toList rtup) -- this code does NOT guarantee that HM.toList will return the same column order as [ColumnInfo]
listOfColInfoRDataType :: [ColumnInfo] -> RTuple -> [(ColumnInfo, RDataType)] -- this code does guarantees that RDataTypes will be in the same column order as [ColumnInfo], i.e., the correct RDataType for the correct column
listOfColInfoRDataType (ci:[]) rtup = [(ci, rtup HM.!(name ci))] -- rt HM.!(name ci) -> this returns the RDataType by column name
listOfColInfoRDataType (ci:colInfos) rtup = (ci, rtup HM.!(name ci)):listOfColInfoRDataType colInfos rtup
-- | createRDataType: Get a value of type a and return the corresponding RDataType.
-- The input value data type must be an instance of the Typepable typeclass from Data.Typeable
createRDataType ::
TB.Typeable a
=> a -- ^ input value
-> RDataType -- ^ output RDataType
createRDataType val =
case show (TB.typeOf val) of
--"Int" -> RInt $ D.fromDyn (D.toDyn val) 0
"Int" -> case (D.fromDynamic (D.toDyn val)) of -- toDyn :: Typeable a => a -> Dynamic
Just v -> RInt v -- fromDynamic :: Typeable a => Dynamic -> Maybe a
Nothing -> Null
--"Char" -> RChar $ D.fromDyn (D.toDyn val) 'a'
{-- "Char" -> case (D.fromDynamic (D.toDyn val)) of
Just v -> RChar v
Nothing -> Null --}
--"Text" -> RText $ D.fromDyn (D.toDyn val) ""
"Text" -> case (D.fromDynamic (D.toDyn val)) of
Just v -> RText v
Nothing -> Null
--"[Char]" -> RString $ D.fromDyn (D.toDyn val) ""
{-- "[Char]" -> case (D.fromDynamic (D.toDyn val)) of
Just v -> RString v
Nothing -> Null --}
--"Double" -> RDouble $ D.fromDyn (D.toDyn val) 0.0
"Double" -> case (D.fromDynamic (D.toDyn val)) of
Just v -> RDouble v
Nothing -> Null
--"Float" -> RFloat $ D.fromDyn (D.toDyn val) 0.0
{-- "Float" -> case (D.fromDynamic (D.toDyn val)) of
Just v -> RFloat v
Nothing -> Null --}
_ -> Null
{--createRDataType ::
TB.Typeable a
=> a -- ^ input value
-> RDataType -- ^ output RDataType
createRDataType val =
case show (TB.typeOf val) of
--"Int" -> RInt $ D.fromDyn (D.toDyn val) 0
"Int" -> case (D.fromDynamic (D.toDyn val)) of -- toDyn :: Typeable a => a -> Dynamic
Just v -> v -- fromDynamic :: Typeable a => Dynamic -> Maybe a
Nothing -> Null
--"Char" -> RChar $ D.fromDyn (D.toDyn val) 'a'
"Char" -> case (D.fromDynamic (D.toDyn val)) of
Just v -> v
Nothing -> Null
--"Text" -> RText $ D.fromDyn (D.toDyn val) ""
"Text" -> case (D.fromDynamic (D.toDyn val)) of
Just v -> v
Nothing -> Null
--"[Char]" -> RString $ D.fromDyn (D.toDyn val) ""
"[Char]" -> case (D.fromDynamic (D.toDyn val)) of
Just v -> v
Nothing -> Null
--"Double" -> RDouble $ D.fromDyn (D.toDyn val) 0.0
"Double" -> case (D.fromDynamic (D.toDyn val)) of
Just v -> v
Nothing -> Null
--"Float" -> RFloat $ D.fromDyn (D.toDyn val) 0.0
"Float" -> case (D.fromDynamic (D.toDyn val)) of
Just v -> v
Nothing -> Null
_ -> Null
--}
{--
-- | Definition of a relational tuple
data Rtuple
-- = TupToBeDefined deriving (Show)
= Rtuple {
fieldMap :: Map.Map RelationField Int -- ^ provides a key,value mapping between the field and the Index (i.e., the offset) in the bytestring
,fieldValues :: BS.ByteString -- ^ tuple values are stored in a bytestring
}
deriving Show
--}
{--
-- | Definition of a relation's field
data RelationField
= RelationField {
fldname :: String
,dataType :: DataType
}
deriving Show
-- | Definition of a data type
data DataType
= Rinteger -- ^ an integer data type
| Rstring -- ^ a string data type
| Rdate -- ^ a date data type
deriving Show
-- | Definition of a predicate
type Predicate a
= a -> Bool -- ^ a predicate is a polymorphic type, which is a function that evaluates an expression over an 'a'
-- (e.g., a can be an Rtuple, thus Predicate Rtuple) and returns either true or false.
-- | The selection operator.
-- It filters the tuples of a relation based on a predicate
-- and returns a new relation with the tuple that satisfy the predicate
selection ::
Relation -- ^ input relation
-> Predicate Rtuple -- ^ input predicate
-> Relation -- ^ output relation
selection r p = undefined
--}
-- | Definition of a Predicate
type RPredicate = RTuple -> Bool
-- | Definition of Relational Algebra operations.
-- These are the valid operations between RTables
data ROperation =
ROperationEmpty
| RUnion -- ^ Union
| RInter -- ^ Intersection
| RDiff -- ^ Difference
| RPrj { colPrjList :: [ColumnName] } -- ^ Projection
| RFilter { fpred :: RPredicate } -- ^ Filter
| RInJoin { jpred :: RJoinPredicate } -- ^ Inner Join (any type of join predicate allowed)
| RLeftJoin { jpred :: RJoinPredicate } -- ^ Left Outer Join (any type of join predicate allowed)
| RRightJoin { jpred :: RJoinPredicate } -- ^ Right Outer Join (any type of join predicate allowed)
| RAggregate { aggList :: [RAggOperation] } -- Performs some aggregation operations on specific columns and returns a singleton RTable
| RGroupBy { gpred :: RGroupPredicate, aggList :: [RAggOperation], colGrByList :: [ColumnName] } -- ^ A GroupBy operation
-- An SQL equivalent: SELECT colGrByList, aggList FROM... GROUP BY colGrByList
-- Note that compared to SQL, we can have a more generic grouping predicate (i.e.,
-- when two RTuples should belong in the same group) than just the equality of
-- values on the common columns between two RTuples.
-- Also note, that in the case of an aggregation without grouping (equivalent to
-- a single group group by), then the grouping predicate should be:
-- @
-- \_ _ -> True
-- @
| RCombinedOp { rcombOp :: UnaryRTableOperation } -- ^ A combination of unary ROperations e.g., (p plist).(f pred) (i.e., RPrj . RFilter), in the form of an RTable -> RTable function.
-- In this sense we can also include a binary operation (e.g. join), if we partially apply the join to one RTable
-- e.g., (ij jpred rtab) . (p plist) . (f pred)
| RBinOp { rbinOp :: BinaryRTableOperation } -- ^ A generic binary ROperation.
| ROrderBy { colOrdList :: [(ColumnName, OrderingSpec)] } -- ^ Order the RTuples of the RTable acocrding to the specified list of Columns.
-- First column in the input list has the highest priority in the sorting order
-- | A sum type to help the specification of a column ordering (Ascending, or Descending)
data OrderingSpec = Asc | Desc deriving (Show, Eq)
-- | A generic unary operation on a RTable
type UnaryRTableOperation = RTable -> RTable
-- | A generic binary operation on RTable
type BinaryRTableOperation = RTable -> RTable -> RTable
--deriving (Eq,Show)
-- | RFieldRenaming
-- | RAggregation
-- | RExtension
-- | Definition of a Join Predicate
type RJoinPredicate = RTuple -> RTuple -> Bool
-- | Definition of a Group By Predicate
-- It defines the condition for two RTuples to be included in the same group.
type RGroupPredicate = RTuple -> RTuple -> Bool
-- | This data type represents all possible aggregate operations over an RTable.
-- Examples are : Sum, Count, Average, Min, Max but it can be any other "aggregation".
-- The essential property of an aggregate operation is that it acts on an RTable (or on
-- a group of RTuples - in the case of the RGroupBy operation) and produces a single RTuple.
--
-- An aggregate operation is applied on a specific column (source column) and the aggregated result
-- will be stored in the target column. It is important to understand that the produced aggregated RTuple
-- is different from the input RTuples. It is a totally new RTuple, that will consist of the
-- aggregated column(s) (and the grouping columns in the case of an RGroupBy).
-- Also, note that following SQL semantics, an aggregate operation ignores Null values.
-- So for example, a SUM(column) will just ignore them and also will COUNT(column), i.e., it
-- will not sum or count the Nulls. If all columns are Null, then a Null will be returned.
--
data RAggOperation = RAggOperation {
sourceCol :: ColumnName -- ^ Source column
,targetCol :: ColumnName -- ^ Target column
,aggFunc :: RTable -> RTuple -- ^ here we define the aggegate function to be applied on an RTable
}
-- | The following are all common aggregate operations
-- | The Sum aggregate operation
raggSum ::
ColumnName -- ^ source column
-> ColumnName -- ^ target column
-> RAggOperation
raggSum src trg = RAggOperation {
sourceCol = src
,targetCol = trg
,aggFunc = \rtab -> createRtuple [(trg, sumFold src trg rtab)]
}
-- | A helper function in raggSum that implements the basic fold for sum aggregation
sumFold :: ColumnName -> ColumnName -> RTable -> RDataType
sumFold src trg rtab =
V.foldr' ( \rtup accValue ->
--if (getRTupColValue src) rtup /= Null && accValue /= Null
if (isNotNull $ (getRTupColValue src) rtup) && (isNotNull accValue)
then
(getRTupColValue src) rtup + accValue
else
--if (getRTupColValue src) rtup == Null && accValue /= Null
if (isNull $ (getRTupColValue src) rtup) && (isNotNull accValue)
then
accValue -- ignore Null value
else
--if (getRTupColValue src) rtup /= Null && accValue == Null
if (isNotNull $ (getRTupColValue src) rtup) && (isNull accValue)
then
(getRTupColValue src) rtup + RInt 0 -- ignore so far Null agg result
-- add RInt 0, so in the case of a non-numeric rtup value, the result will be a Null
-- while if rtup value is numeric the addition of RInt 0 does not cause a problem
else
Null -- agg of Nulls is Null
) (Null) rtab
-- | The Count aggregate operation
raggCount ::
ColumnName -- ^ source column
-> ColumnName -- ^ target column
-> RAggOperation
raggCount src trg = RAggOperation {
sourceCol = src
,targetCol = trg
,aggFunc = \rtab -> createRtuple [(trg, countFold src trg rtab)]
}
-- | A helper function in raggCount that implements the basic fold for Count aggregation
countFold :: ColumnName -> ColumnName -> RTable -> RDataType
countFold src trg rtab =
V.foldr' ( \rtup accValue ->
--if (getRTupColValue src) rtup /= Null && accValue /= Null
if (isNotNull $ (getRTupColValue src) rtup) && (isNotNull accValue)
then
RInt 1 + accValue
else
--if (getRTupColValue src) rtup == Null && accValue /= Null
if (isNull $ (getRTupColValue src) rtup) && (isNotNull accValue)
then
accValue -- ignore Null value
else
--if (getRTupColValue src) rtup /= Null && accValue == Null
if (isNotNull $ (getRTupColValue src) rtup) && (isNull accValue)
then
RInt 1 -- ignore so far Null agg result
else
Null -- agg of Nulls is Null
) (Null) rtab
-- | The Average aggregate operation
raggAvg ::
ColumnName -- ^ source column
-> ColumnName -- ^ target column
-> RAggOperation
raggAvg src trg = RAggOperation {
sourceCol = src
,targetCol = trg
,aggFunc = \rtab -> createRtuple [(trg, let
sum = sumFold src trg rtab
cnt = countFold src trg rtab
in case (sum,cnt) of
(RInt s, RInt c) -> RDouble (fromIntegral s / fromIntegral c)
(RDouble s, RInt c) -> RDouble (s / fromIntegral c)
(_, _) -> Null
)]
}
-- | The Max aggregate operation
raggMax ::
ColumnName -- ^ source column
-> ColumnName -- ^ target column
-> RAggOperation
raggMax src trg = RAggOperation {
sourceCol = src
,targetCol = trg
,aggFunc = \rtab -> createRtuple [(trg, maxFold src trg rtab)]
}
-- | A helper function in raggMax that implements the basic fold for Max aggregation
maxFold :: ColumnName -> ColumnName -> RTable -> RDataType
maxFold src trg rtab =
V.foldr' ( \rtup accValue ->
--if (getRTupColValue src) rtup /= Null && accValue /= Null
if (isNotNull $ (getRTupColValue src) rtup) && (isNotNull accValue)
then
max ((getRTupColValue src) rtup) accValue
else
--if (getRTupColValue src) rtup == Null && accValue /= Null
if (isNull $ (getRTupColValue src) rtup) && (isNotNull accValue)
then
accValue -- ignore Null value
else
--if (getRTupColValue src) rtup /= Null && accValue == Null
if (isNotNull $ (getRTupColValue src) rtup) && (isNull accValue)
then
(getRTupColValue src) rtup -- ignore so far Null agg result
else
Null -- agg of Nulls is Null
) Null rtab
-- | The Min aggregate operation
raggMin ::
ColumnName -- ^ source column
-> ColumnName -- ^ target column
-> RAggOperation
raggMin src trg = RAggOperation {
sourceCol = src
,targetCol = trg
,aggFunc = \rtab -> createRtuple [(trg, minFold src trg rtab)]
}
-- | A helper function in raggMin that implements the basic fold for Min aggregation
minFold :: ColumnName -> ColumnName -> RTable -> RDataType
minFold src trg rtab =
V.foldr' ( \rtup accValue ->
--if (getRTupColValue src) rtup /= Null && accValue /= Null
if (isNotNull $ (getRTupColValue src) rtup) && (isNotNull accValue)
then
min ((getRTupColValue src) rtup) accValue
else
--if (getRTupColValue src) rtup == Null && accValue /= Null
if (isNull $ (getRTupColValue src) rtup) && (isNotNull accValue)
then
accValue -- ignore Null value
else
--if (getRTupColValue src) rtup /= Null && accValue == Null
if (isNotNull $ (getRTupColValue src) rtup) && (isNull accValue)
then
(getRTupColValue src) rtup -- ignore so far Null agg result
else
Null -- agg of Nulls is Null
) Null rtab
{--
data RAggOperation =
RSum ColumnName -- ^ sums values in the specific column
| RCount ColumnName -- ^ count of values in the specific column
| RCountDist ColumnName -- ^ distinct count of values in the specific column
| RAvg ColumnName -- ^ average of values in the specific column
| RMin ColumnName -- ^ minimum of values in the specific column
| RMax ColumnName -- ^ maximum of values in the specific column
--}
-- | ropU operator executes a unary ROperation
ropU = runUnaryROperation
-- | Execute a Unary ROperation
runUnaryROperation ::
ROperation -- ^ input ROperation
-> RTable -- ^ input RTable
-> RTable -- ^ output RTable
runUnaryROperation rop irtab =
case rop of
RFilter { fpred = rpredicate } -> runRfilter rpredicate irtab
RPrj { colPrjList = colNames } -> runProjection colNames irtab
RAggregate { aggList = aggFunctions } -> runAggregation aggFunctions irtab
RGroupBy { gpred = groupingpred, aggList = aggFunctions, colGrByList = cols } -> runGroupBy groupingpred aggFunctions cols irtab
RCombinedOp { rcombOp = comb } -> runCombinedROp comb irtab
ROrderBy { colOrdList = colist } -> runOrderBy colist irtab
-- | ropB operator executes a binary ROperation
ropB = runBinaryROperation
-- | Execute a Binary ROperation
runBinaryROperation ::
ROperation -- ^ input ROperation
-> RTable -- ^ input RTable1
-> RTable -- ^ input RTable2
-> RTable -- ^ output RTabl
runBinaryROperation rop irtab1 irtab2 =
case rop of
RInJoin { jpred = jpredicate } -> runInnerJoin jpredicate irtab1 irtab2
RLeftJoin { jpred = jpredicate } -> runLeftJoin jpredicate irtab1 irtab2
RRightJoin { jpred = jpredicate } -> runRightJoin jpredicate irtab1 irtab2
RUnion -> runUnion irtab1 irtab2
RInter -> runIntersect irtab1 irtab2
RDiff -> runDiff irtab1 irtab2
RBinOp { rbinOp = bop } -> bop irtab1 irtab2
-- * ######### Construction ##########
-- | Test whether an RTable is empty
isRTabEmpty :: RTable -> Bool
isRTabEmpty = V.null
-- | Test whether an RTuple is empty
isRTupEmpty :: RTuple -> Bool
isRTupEmpty = HM.null
-- | emptyRTable: Create an empty RTable
emptyRTable :: RTable
emptyRTable = V.empty :: RTable
-- | Creates an empty RTuple (i.e., one with no column,value mappings)
emptyRTuple :: RTuple
emptyRTuple = HM.empty
-- | Creates an RTable with a single RTuple
createSingletonRTable ::
RTuple
-> RTable
createSingletonRTable rt = V.singleton rt
-- | createRTuple: Create an Rtuple from a list of column names and values
createRtuple ::
[(ColumnName, RDataType)] -- ^ input list of (columnname,value) pairs
-> RTuple
createRtuple l = HM.fromList l
-- | Creates a Null RTuple based on a list of input Column Names.
-- A Null RTuple is an RTuple where all column names correspond to a Null value (Null is a data constructor of RDataType)
createNullRTuple ::
[ColumnName]
-> RTuple
createNullRTuple cnames = HM.fromList $ zipped
where zipped = Data.List.zip cnames (Data.List.take (Data.List.length cnames) (repeat Null))
-- | Returns True if the input RTuple is a Null RTuple, otherwise it returns False
isNullRTuple ::
RTuple
-> Bool
isNullRTuple t =
let -- if t is really Null, then the following must return an empty RTuple (since a Null RTuple has all its values equal with Null)
checkt = HM.filter (\v -> isNotNull v) t --v /= Null) t
in if isRTupEmpty checkt
then True
else False
-- * ########## RTable "Functional" Operations ##############
-- | This is a fold operation on a RTable.
-- It is similar with :
-- @
-- foldr' :: (a -> b -> b) -> b -> Vector a -> b Source #
-- @
-- of Vector, which is an O(n) Right fold with a strict accumulator
rtabFoldr' :: (RTuple -> RTable -> RTable) -> RTable -> RTable -> RTable
rtabFoldr' f accum rtab = V.foldr' f accum rtab
-- | This is a fold operation on a RTable.
-- It is similar with :
-- @
-- foldl' :: (a -> b -> a) -> a -> Vector b -> a
-- @
-- of Vector, which is an O(n) Left fold with a strict accumulator
rtabFoldl' :: (RTable -> RTuple -> RTable) -> RTable -> RTable -> RTable
rtabFoldl' f accum rtab = V.foldl' f accum rtab
-- | Map function over an RTable
rtabMap :: (RTuple -> RTuple) -> RTable -> RTable
rtabMap f rtab = V.map f rtab
-- * ########## RTable Relational Operations ##############
-- | Number of RTuples returned by an RTable operation
type RTuplesRet = Sum Int
-- | Creates an RTuplesRet type
rtuplesRet :: Int -> RTuplesRet
rtuplesRet i = (M.Sum i) :: RTuplesRet
-- | Return the number embedded in the RTuplesRet data type
getRTuplesRet :: RTuplesRet -> Int
getRTuplesRet = M.getSum
-- | RTabResult is the result of an RTable operation and is a Writer Monad, that includes the new RTable,
-- as well as the number of RTuples returned by the operation.
type RTabResult = Writer RTuplesRet RTable
-- | Creates an RTabResult (i.e., a Writer Monad) from a result RTable and the number of RTuples that it returned
rtabResult ::
(RTable, RTuplesRet) -- ^ input pair
-> RTabResult -- ^ output Writer Monad
rtabResult (rtab, rtupRet) = writer (rtab, rtupRet)
-- | Returns the info "stored" in the RTabResult Writer Monad
runRTabResult ::
RTabResult
-> (RTable, RTuplesRet)
runRTabResult rtr = runWriter rtr
-- | Returns the "log message" in the RTabResult Writer Monad, which is the number of returned RTuples
execRTabResult ::
RTabResult
-> RTuplesRet
execRTabResult rtr = execWriter rtr
-- | removeColumn : removes a column from an RTable.
-- The column is specified by ColumnName.
-- If this ColumnName does not exist in the RTuple of the input RTable
-- then nothing is happened, the RTuple remains intact.
removeColumn ::
ColumnName -- ^ Column to be removed
-> RTable -- ^ input RTable
-> RTable -- ^ output RTable
removeColumn col rtabSrc = do
srcRtup <- rtabSrc
let targetRtup = HM.delete col srcRtup
return targetRtup
-- | addColumn: adds a column to an RTable
addColumn ::
ColumnName -- ^ name of the column to be added
-> RDataType -- ^ Default value of the new column. All RTuples will initially have this value in this column
-> RTable -- ^ Input RTable
-> RTable -- ^ Output RTable
addColumn name initVal rtabSrc = do
srcRtup <- rtabSrc
let targetRtup = HM.insert name initVal srcRtup
return targetRtup
-- | RTable Filter operator
f = runRfilter
-- | Executes an RFilter operation
runRfilter ::
RPredicate
-> RTable
-> RTable
runRfilter rpred rtab =
if isRTabEmpty rtab
then emptyRTable
else
V.filter rpred rtab
-- | RTable Projection operator
p = runProjection
-- | Implements RTable projection operation.
-- If a column name does not exist, then an empty RTable is returned.
runProjection ::
[ColumnName] -- ^ list of column names to be included in the final result RTable
-> RTable
-> RTable
runProjection colNamList irtab =
if isRTabEmpty irtab
then
emptyRTable
else
do -- RTable is a Monad
srcRtuple <- irtab
let
-- 1. get original column value (in this case it is a list of values :: Maybe RDataType)
srcValueL = Data.List.map (\colName -> rtupLookup colName srcRtuple) colNamList
-- if there is at least one Nothing value then an non-existing column name has been asked.
if Data.List.elem Nothing srcValueL
then -- return an empty RTable
emptyRTable
else
let
-- 2. create the new RTuple
valList = Data.List.map (\(Just v) -> v) srcValueL -- get rid of Maybe
targetRtuple = rtupleFromList (Data.List.zip colNamList valList) -- HM.fromList
in return targetRtuple
-- | Implements RTable projection operation.
-- If a column name does not exist, then the returned RTable includes this column with a Null
-- value. This projection implementation allows missed hits.
runProjectionMissedHits ::
[ColumnName] -- ^ list of column names to be included in the final result RTable
-> RTable
-> RTable
runProjectionMissedHits colNamList irtab =
if isRTabEmpty irtab
then
emptyRTable
else
do -- RTable is a Monad
srcRtuple <- irtab
let
-- 1. get original column value (in this case it is a list of values)
srcValueL = Data.List.map (\src -> HM.lookupDefault Null -- return Null if value cannot be found based on column name
src -- column name to look for (source) - i.e., the key in the HashMap
srcRtuple -- source RTuple (i.e., a HashMap ColumnName RDataType)
) colNamList
-- 2. create the new RTuple
targetRtuple = HM.fromList (Data.List.zip colNamList srcValueL)
return targetRtuple
-- | restrictNrows: returns the N first rows of an RTable
restrictNrows ::
Int -- ^ number of N rows to select
-> RTable -- ^ input RTable
-> RTable -- ^ output RTable
restrictNrows n r1 = V.take n r1
-- | RTable Inner Join Operator
iJ = runInnerJoinO
-- | Implements an Inner Join operation between two RTables (any type of join predicate is allowed)
-- Note that this operation is implemented as a 'Data.HashMap.Strict' union, which means "the first
-- Map (i.e., the left RTuple) will be prefered when dublicate keys encountered with different values. That is, in the context of
-- joining two RTuples the value of the first (i.e., left) RTuple on the common key will be prefered.
runInnerJoin ::
RJoinPredicate
-> RTable
-> RTable
-> RTable
runInnerJoin jpred irtab1 irtab2 =
if (isRTabEmpty irtab1) || (isRTabEmpty irtab2)
then
emptyRTable
else
do
rtup1 <- irtab1
rtup2 <- irtab2
let targetRtuple =
if (jpred rtup1 rtup2)
then HM.union rtup1 rtup2
else HM.empty
removeEmptyRTuples (return targetRtuple)
where removeEmptyRTuples = f (not.isRTupEmpty)
-- Inner Join with Oracle DB's convention for common column names.
-- When we have two tuples t1 and t2 with a common column name (lets say "Common"), then the resulting tuple after a join
-- will be "Common", "Common_1", so a "_1" suffix is appended. The tuple from the left table by convention retains the original column name.
-- So "Column_1" is the column from the right table. If "Column_1" already exists, then "Column_2" is used.
runInnerJoinO ::
RJoinPredicate
-> RTable
-> RTable
-> RTable
runInnerJoinO jpred tabDriver tabProbed =
if isRTabEmpty tabDriver || isRTabEmpty tabProbed
then
emptyRTable
else
do
rtupDrv <- tabDriver
-- this is the equivalent of a nested loop with tabDriver playing the role of the driving table and tabProbed the probed table
V.foldr' (\t accum ->
if (jpred rtupDrv t)
then
-- insert joined tuple to result table (i.e. the accumulator)
insertAppendRTab (joinRTuples rtupDrv t) accum
else
-- keep the accumulator unchanged
accum
) emptyRTable tabProbed
-- | Joins two RTuples into one.
-- In this join we follow Oracle DB's convention when joining two tuples with some common column names.
-- When we have two tuples t1 and t2 with a common column name (lets say "Common"), then the resulitng tuple after a join
-- will be "Common", "Common_1", so a "_1" suffix is appended. The tuple from the left table by convention retains the original column name.
-- So "Column_1" is the column from the right table.
-- If "Column_1" already exists, then "Column_2" is used.
joinRTuples :: RTuple -> RTuple -> RTuple
joinRTuples tleft tright =
let
-- change keys in tright what needs to be renamed because also appear in tleft
-- first keep a copy of the tright pairs that dont need a key change
dontNeedChange = HM.difference tright tleft
changedPart = changeKeys tleft tright
-- create a new version of tright, with no common keys with tleft
new_tright = HM.union dontNeedChange changedPart
in HM.union tleft new_tright
where
-- rename keys of right rtuple until there no more common keys with the left rtuple
changeKeys :: RTuple -> RTuple -> RTuple
changeKeys tleft changedPart =
if isRTupEmpty (HM.intersection changedPart tleft)
then -- we are done, no more common keys
changedPart
else
-- there are still common keys to change
let
needChange = HM.intersection changedPart tleft -- (k,v) pairs that exist in changedPart and the keys also appear in tleft. Thus these keys have to be renamed
dontNeedChange = HM.difference changedPart tleft -- (k,v) pairs that exist in changedPart and the keys dont appear in tleft. Thus these keys DONT have to be renamed
new_changedPart = fromList $ Data.List.map (\(k,v) -> (newKey k, v)) $ toList needChange
in HM.union dontNeedChange (changeKeys tleft new_changedPart)
-- generate a new key as this:
-- "hello" -> "hello_1"
-- "hello_1" -> "hello_2"
-- "hello_2" -> "hello_3"
newKey :: ColumnName -> ColumnName
newKey name =
let
lastChar = Data.List.last name
beforeLastChar = name !! (Data.List.length name - 2)
in
if beforeLastChar == '_' && Data.Char.isDigit lastChar
then (Data.List.take (Data.List.length name - 2) name) ++ ( '_' : (show $ (read (lastChar : "") :: Int) + 1) )
else name ++ "_1"
-- | RTable Left Outer Join Operator
lJ = runLeftJoin
-- | Implements a Left Outer Join operation between two RTables (any type of join predicate is allowed),
-- i.e., the rows of the left RTable will be preserved.
-- Note that when dublicate keys encountered that is, since the underlying structure for an RTuple is a Data.HashMap.Strict,
-- only one value per key is allowed. So in the context of joining two RTuples the value of the left RTuple on the common key will be prefered.
{-runLeftJoin ::
RJoinPredicate
-> RTable
-> RTable
-> RTable
runLeftJoin jpred leftRTab rtab = do
rtupLeft <- leftRTab
rtup <- rtab
let targetRtuple =
if (jpred rtupLeft rtup)
then HM.union rtupLeft rtup
else HM.union rtupLeft (createNullRTuple colNamesList)
where colNamesList = HM.keys rtup
--return targetRtuple
-- remove repeated rtuples and keep just the rtuples of the preserving rtable
iJ (jpred2) (return targetRtuple) leftRTab
where
-- the left tuple is the extended (result of the outer join)
-- the right tuple is from the preserving table
-- we need to return True for those who are equal in the common set of columns
jpred2 tL tR =
let left = HM.toList tL
right = HM.toList tR
-- in order to satisfy the join pred, all elements of right must exist in left
in Data.List.all (\(k,v) -> Data.List.elem (k,v) left) right
-}
-- | Implements a Left Outer Join operation between two RTables (any type of join predicate is allowed),
-- i.e., the rows of the left RTable will be preserved.
-- A Left Join :
-- @
-- tabLeft LEFT JOIN tabRight ON joinPred
-- @
-- where tabLeft is the preserving table can be defined as:
-- the Union between the following two RTables:
-- A. The result of the inner join: tabLeft INNER JOIN tabRight ON joinPred
-- B. The rows from the preserving table (tabLeft) that DONT satisfy the join condition, enhanced with the columns
-- of tabRight returning Null values.
-- The common columns will appear from both tables but only the left table column's will retain their original name.
runLeftJoin ::
RJoinPredicate
-> RTable
-> RTable
-> RTable
runLeftJoin jpred preservingTab tab =
if isRTabEmpty preservingTab
then
emptyRTable
else
if isRTabEmpty tab
then
-- return the preserved tab
preservingTab
else
-- we know that both the preservingTab and tab are non empty
let
unionFstPart = iJ jpred preservingTab tab
-- project only the preserving tab's columns
fstPartProj = p (getColumnNamesfromRTab preservingTab) unionFstPart
-- the second part are the rows from the preserving table that dont join
-- we will use the Difference operations for this
unionSndPart =
let
difftab = d preservingTab fstPartProj -- unionFstPart
-- now enhance the result with the columns of the right table
in iJ (\t1 t2 -> True) difftab (createSingletonRTable $ createNullRTuple $ (getColumnNamesfromRTab tab))
in u unionFstPart unionSndPart
-- | RTable Right Outer Join Operator
rJ = runRightJoin
-- | Implements a Right Outer Join operation between two RTables (any type of join predicate is allowed),
-- i.e., the rows of the right RTable will be preserved.
-- A Right Join :
-- @
-- tabLeft RIGHT JOIN tabRight ON joinPred
-- @
-- where tabRight is the preserving table can be defined as:
-- the Union between the following two RTables:
-- A. The result of the inner join: tabLeft INNER JOIN tabRight ON joinPred
-- B. The rows from the preserving table (tabRight) that DONT satisfy the join condition, enhanced with the columns
-- of tabLeft returning Null values.
-- The common columns will appear from both tables but only the right table column's will retain their original name.
runRightJoin ::
RJoinPredicate
-> RTable
-> RTable
-> RTable
runRightJoin jpred tab preservingTab =
if isRTabEmpty preservingTab
then
emptyRTable
else
if isRTabEmpty tab
then
preservingTab
else
-- we know that both the preservingTab and tab are non empty
let
unionFstPart =
iJ (flip jpred) preservingTab tab --tab -- we used the preserving table as the left table in the inner join,
-- in order to retain the original column names for the common columns
-- debug
-- !dummy1 = trace ("unionFstPart:\n" ++ show unionFstPart) True
-- project only the preserving tab's columns
fstPartProj =
p (getColumnNamesfromRTab preservingTab) unionFstPart
-- the second part are the rows from the preserving table that dont join
-- we will use the Difference operations for this
unionSndPart =
let
difftab =
d preservingTab fstPartProj -- unionFstPart
-- now enhance the result with the columns of the left table
in iJ (\t1 t2 -> True) difftab (createSingletonRTable $ createNullRTuple $ (getColumnNamesfromRTab tab))
-- debug
-- !dummy2 = trace ("unionSndPart :\n" ++ show unionSndPart) True
-- !dummy3 = trace ("u unionFstPart unionSndPart :\n" ++ (show $ u unionFstPart unionSndPart)) True
in u unionFstPart unionSndPart
-- | Implements a Right Outer Join operation between two RTables (any type of join predicate is allowed)
-- i.e., the rows of the right RTable will be preserved.
-- Note that when dublicate keys encountered that is, since the underlying structure for an RTuple is a Data.HashMap.Strict,
-- only one value per key is allowed. So in the context of joining two RTuples the value of the right RTuple on the common key will be prefered.
{-runRightJoin ::
RJoinPredicate
-> RTable
-> RTable
-> RTable
runRightJoin jpred rtab rightRTab = do
rtupRight <- rightRTab
rtup <- rtab
let targetRtuple =
if (jpred rtup rtupRight)
then HM.union rtupRight rtup
else HM.union rtupRight (createNullRTuple colNamesList)
where colNamesList = HM.keys rtup
return targetRtuple-}
-- | RTable Full Outer Join Operator
foJ = runFullOuterJoin
-- | Implements a Full Outer Join operation between two RTables (any type of join predicate is allowed)
-- A full outer join is the union of the left and right outer joins respectively.
-- The common columns will appear from both tables but only the left table column's will retain their original name (just by convention).
runFullOuterJoin ::
RJoinPredicate
-> RTable
-> RTable
-> RTable
runFullOuterJoin jpred leftRTab rightRTab = -- (lJ jpred leftRTab rightRTab) `u` (rJ jpred leftRTab rightRTab) -- (note that `u` eliminates dublicates)
let
--
-- we want to get to this union:
-- (lJ jpred leftRTab rightRTab) `u` (d (rJ jpred leftRTab rightRTab) (ij (flip jpred) rightRTab leftRTab))
--
-- The problem is with the change of column names that are common in both tables. In the right part of the union
-- rightTab has preserved its original column names while in the left part the have changed to "_1" suffix.
-- So we cant do the union as is, we need to change the second part of the union (right one) to have the same column names
-- as the firts part, i.e., original names for leftTab and changed names for rightTab.
--
unionFstPart = lJ jpred leftRTab rightRTab -- in unionFstPart rightTab's columns have changed names
-- we need to construct the 2nd part of the union with leftTab columns unchanged and rightTab changed
unionSndPartTemp1 = d (rJ jpred leftRTab rightRTab) (iJ (flip jpred) rightRTab leftRTab)
-- isolate the columns of the rightTab
unionSndPartTemp2 = p (getColumnNamesfromRTab rightRTab) unionSndPartTemp1
-- this join is a trick in order to change names of the rightTab
unionSndPart = iJ (\t1 t2 -> True) (createSingletonRTable $ createNullRTuple $ (getColumnNamesfromRTab leftRTab)) unionSndPartTemp2
in unionFstPart `u` unionSndPart
-- | RTable Union Operator
u = runUnion
-- We cannot implement Union like the following (i.e., union of lists) because when two identical RTuples that contain Null values are checked for equality
-- equality comparison between Null returns always false. So we have to implement our own union using the isNull function.
-- | Implements the union of two RTables as a union of two lists (see 'Data.List').
-- Duplicates, and elements of the first list, are removed from the the second list, but if the first list contains duplicates, so will the result
{-runUnion ::
RTable
-> RTable
-> RTable
runUnion rt1 rt2 =
let ls1 = V.toList rt1
ls2 = V.toList rt2
resultLs = Data.List.union ls1 ls2
in V.fromList resultLs
-}
-- | Implements the union of two RTables as a union of two lists (see 'Data.List').
runUnion ::
RTable
-> RTable
-> RTable
runUnion rt1 rt2 =
if isRTabEmpty rt1 && isRTabEmpty rt2
then
emptyRTable
else
if isRTabEmpty rt1
then rt2
else
if isRTabEmpty rt2
then rt1
else
-- construct the union result by concatenating the left table with the subset of tuple from the right table that do
-- not appear in the left table (i.e, remove dublicates)
rt1 V.++ (V.foldr (un) emptyRTable rt2)
where
un :: RTuple -> RTable -> RTable
un tupRight acc =
-- Can we find tupRight in the left table?
if didYouFindIt tupRight rt1
then acc -- then discard tuplRight ,leave result unchanged
else V.snoc acc tupRight -- else insert tupRight into final result
-- | RTable Intersection Operator
i = runIntersect
-- | Implements the intersection of two RTables
runIntersect ::
RTable
-> RTable
-> RTable
runIntersect rt1 rt2 =
if isRTabEmpty rt1 || isRTabEmpty rt2
then
emptyRTable
else
-- construct the intersect result by traversing the left table and checking if each tuple exists in the right table
V.foldr (intsect) emptyRTable rt1
where
intsect :: RTuple -> RTable -> RTable
intsect tupLeft acc =
-- Can we find tupLeft in the right table?
if didYouFindIt tupLeft rt2
then V.snoc acc tupLeft -- then insert tupLeft into final result
else acc -- else discard tuplLeft ,leave result unchanged
{-
runIntersect rt1 rt2 =
let ls1 = V.toList rt1
ls2 = V.toList rt2
resultLs = Data.List.intersect ls1 ls2
in V.fromList resultLs
-}
-- | RTable Difference Operator
d = runDiff
-- Test it with this, from ghci:
-- ---------------------------------
-- :set -XOverloadedStrings
-- :m + Data.HashMap.Strict
--
-- let t1 = fromList [("c1",RInt 1),("c2", Null)]
-- let t2 = fromList [("c1",RInt 2),("c2", Null)]
-- let t3 = fromList [("c1",RInt 3),("c2", Null)]
-- let t4 = fromList [("c1",RInt 4),("c2", Null)]
-- :m + Data.Vector
-- let tab1 = Data.Vector.fromList [t1,t2,t3,t4]
-- let tab2 = Data.Vector.fromList [t1,t2]
-- > d tab1 tab2
-- ---------------------------------
-- | Implements the set Difference of two RTables as the diff of two lists (see 'Data.List').
runDiff ::
RTable
-> RTable
-> RTable
runDiff rt1 rt2 =
if isRTabEmpty rt1
then
emptyRTable
else
if isRTabEmpty rt2
then
rt1
else
-- construct the diff result by traversing the left table and checking if each tuple exists in the right table
V.foldr (diff) emptyRTable rt1
where
diff :: RTuple -> RTable -> RTable
diff tupLeft acc =
-- Can we find tupLeft in the right table?
if didYouFindIt tupLeft rt2
then acc -- then discard tuplLeft ,leave result unchanged
else V.snoc acc tupLeft -- else insert tupLeft into final result
-- Important Note:
-- we need to implement are own equality comparison function "areTheyEqual" and not rely on the instance of Eq defined for RDataType above
-- because of "Null Logic". If we compare two RTuples that have Null values in any column, then these can never be equal, because
-- Null == Null returns False.
-- However, in SQL when you run a minus or interesection between two tables containing Nulls, it works! For example:
-- with q1
-- as (
-- select rownum c1, Null c2
-- from dual
-- connect by level < 5
-- ),
-- q2
-- as (
-- select rownum c1, Null c2
-- from dual
-- connect by level < 3
-- )
-- select *
-- from q1
-- minus
-- select *
-- from q2
--
-- q1:
-- C1 | C2
-- --- ---
-- 1 |
-- 2 |
-- 3 |
-- 4 |
--
-- q2:
-- C1 | C2
-- --- ---
-- 1 |
-- 2 |
--
-- And it will return:
-- C1 | C2
-- --- ---
-- 3 |
-- 4 |
-- So for Minus and Intersection, when we compare RTuples we need to "bypass" the Null Logic
didYouFindIt :: RTuple -> RTable -> Bool
didYouFindIt searchTup tab =
V.foldr (\t acc -> (areTheyEqual searchTup t) || acc) False tab
areTheyEqual :: RTuple -> RTuple -> Bool
areTheyEqual t1 t2 = -- foldrWithKey :: (k -> v -> a -> a) -> a -> HashMap k v -> a
HM.foldrWithKey (accumulator) True t1
where
accumulator :: ColumnName -> RDataType -> Bool -> Bool
accumulator colName val acc =
case val of
Null ->
case (t2<!>colName) of
Null -> acc -- -- i.e., True && acc ,if both columns are Null then return equality
_ -> False -- i.e., False && acc
_ -> case (t2<!>colName) of
Null -> False -- i.e., False && acc
_ -> (val == t2<!>colName) && acc -- else compare them as normal
-- *** NOTE ***
-- the following piece of code does not work because val == Null always returns False !!!!
-- if (val == Null) && (t2<!>colName == Null)
-- then acc -- i.e., True && acc
-- -- else compare them as normal
-- else (val == t2<!>colName) && acc
{-
runDiff rt1 rt2 =
let ls1 = V.toList rt1
ls2 = V.toList rt2
resultLs = ls1 Data.List.\\ ls2
in V.fromList resultLs
-}
rAgg = runAggregation
-- | Implements the aggregation operation on an RTable
-- It aggregates the specific columns in each AggOperation and returns a singleton RTable
-- i.e., an RTable with a single RTuple that includes only the agg columns and their aggregated value.
runAggregation ::
[RAggOperation] -- ^ Input Aggregate Operations
-> RTable -- ^ Input RTable
-> RTable -- ^ Output singleton RTable
runAggregation [] rtab = rtab
runAggregation aggOps rtab =
if isRTabEmpty rtab
then emptyRTable
else
createSingletonRTable (getResultRTuple aggOps rtab)
where
-- creates the final aggregated RTuple by applying all agg operations in the list
-- and UNIONs all the intermediate agg RTuples to a final aggregated Rtuple
getResultRTuple :: [RAggOperation] -> RTable -> RTuple
getResultRTuple [] _ = emptyRTuple
getResultRTuple (agg:aggs) rt =
let RAggOperation { sourceCol = src, targetCol = trg, aggFunc = aggf } = agg
in (getResultRTuple aggs rt) `HM.union` (aggf rt) -- (aggf rt) `HM.union` (getResultRTuple aggs rt)
rO = runOrderBy
-- | Implements the ORDER BY operation.
-- First column in the input list has the highest priority in the sorting order
-- We treat Null as the maximum value (anything compared to Null is smaller).
-- This way Nulls are send at the end (i.e., "Nulls Last" in SQL parlance). This is for Asc ordering.
-- For Desc ordering, we have the opposite. Nulls go first and so anything compared to Null is greater.
-- @
-- SQL example
-- with q
-- as (select case when level < 4 then level else NULL end c1 -- , level c2
-- from dual
-- connect by level < 7
-- )
-- select *
-- from q
-- order by c1
--
-- C1
-- ----
-- 1
-- 2
-- 3
-- Null
-- Null
-- Null
--
-- with q
-- as (select case when level < 4 then level else NULL end c1 -- , level c2
-- from dual
-- connect by level < 7
-- )
-- select *
-- from q
-- order by c1 desc
-- C1
-- --
-- Null
-- Null
-- Null
-- 3
-- 2
-- 1
-- @
runOrderBy ::
[(ColumnName, OrderingSpec)] -- ^ Input ordering specification
-> RTable -- ^ Input RTable
-> RTable -- ^ Output RTable
runOrderBy ordSpec rtab =
if isRTabEmpty rtab
then emptyRTable
else
let unsortedRTupList = rtableToList rtab
sortedRTupList = Data.List.sortBy (\t1 t2 -> compareTuples ordSpec t1 t2) unsortedRTupList
in rtableFromList sortedRTupList
where
compareTuples :: [(ColumnName, OrderingSpec)] -> RTuple -> RTuple -> Ordering
compareTuples [] t1 t2 = EQ
compareTuples ((col, colordspec) : rest) t1 t2 =
-- if they are equal or both Null on the column in question, then go to the next column
if nvl (t1 <!> col) (RText "I am Null baby!") == nvl (t2 <!> col) (RText "I am Null baby!")
then compareTuples rest t1 t2
else -- Either one of the two is Null or are Not Equal
-- so we need to compare t1 versus t2
-- the GT, LT below refer to t1 wrt to t2
-- In the following we treat Null as the maximum value (anything compared to Null is smaller).
-- This way Nulls are send at the end (i.e., the default is "Nulls Last" in SQL parlance)
if isNull (t1 <!> col)
then
case colordspec of
Asc -> GT -- t1 is GT than t2 (Nulls go to the end)
Desc -> LT
else
if isNull (t2 <!> col)
then
case colordspec of
Asc -> LT -- t1 is LT than t2 (Nulls go to the end)
Desc -> GT
else
-- here we cant have Nulls
case compare (t1 <!> col) (t2 <!> col) of
GT -> if colordspec == Asc
then GT else LT
LT -> if colordspec == Asc
then LT else GT
rG = runGroupBy
-- RGroupBy { gpred :: RGroupPredicate, aggList :: [RAggOperation], colGrByList :: [ColumnName] }
-- hint: use Data.List.GroupBy for the grouping and Data.List.foldl' for the aggregation in each group
{--type RGroupPredicate = RTuple -> RTuple -> Bool
data RAggOperation =
RSum ColumnName -- ^ sums values in the specific column
| RCount ColumnName -- ^ count of values in the specific column
| RCountDist ColumnName -- ^ distinct count of values in the specific column
| RAvg ColumnName -- ^ average of values in the specific column
| RMin ColumnName -- ^ minimum of values in the specific column
| RMax ColumnName
--}
-- | Implements the GROUP BY operation over an RTable.
runGroupBy ::
RGroupPredicate -- ^ Grouping predicate, in order to form the groups of RTuples (it defines when two RTuples should be included in the same group)
-> [RAggOperation] -- ^ Aggregations to be applied on specific columns
-> [ColumnName] -- ^ List of grouping column names (GROUP BY clause in SQL)
-- We assume that all RTuples in the same group have the same value in these columns
-> RTable -- ^ input RTable
-> RTable -- ^ output RTable
runGroupBy gpred aggOps cols rtab =
if isRTabEmpty rtab
then emptyRTable
else
let -- rtupList = V.toList rtab
-- 1. form the groups of RTuples
-- a. first sort the Rtuples based on the grouping columns
-- This is a very important step if we want the groupBy operation to work. This is because grouping on lists is
-- implemented like this: group "Mississippi" = ["M","i","ss","i","ss","i","pp","i"]
-- So we have to sort the list first in order to get the right grouping:
-- group (sort "Mississippi") = ["M","iiii","pp","ssss"]
listOfRTupSorted = rtableToList $ runOrderBy (createOrderingSpec cols) rtab
-- debug
-- !dummy1 = trace (show listOfRTupSorted) True
-- Data.List.sortBy (\t1 t2 -> if (gpred t1 t2) then EQ else compare (rtupleToList t1) (rtupleToList t2) ) rtupList --(t1!(Data.List.head . HM.keys $ t1)) (t2!(Data.List.head . HM.keys $ t2)) ) rtupList
-- Data.List.map (HM.fromList) $ Data.List.sort $ Data.List.map (HM.toList) rtupList
--(t1!(Data.List.head . HM.keys $ t1)) (t2!(Data.List.head . HM.keys $ t2)) ) rtupList
-- b then produce the groups
listOfRTupGroupLists = Data.List.groupBy gpred listOfRTupSorted
-- debug
-- !dummy2 = trace (show listOfRTupGroupLists) True
-- 2. turn each (sub)list of Rtuples representing a Group into an RTable in order to apply aggregation
-- Note: each RTable in this list will hold a group of RTuples that all have the same values in the input grouping columns
-- (which must be compatible with the input grouping predicate)
listofGroupRtabs = Data.List.map (rtableFromList) listOfRTupGroupLists
-- 3. We need to keep the values of the grouping columns (e.g., by selecting the fisrt row) from each one of these RTables,
-- in order to "join them" with the aggregated RTuples that will be produced by the aggregation operations
-- The following will produce a list of singleton RTables.
listOfGroupingColumnsRtabs = Data.List.map ( (restrictNrows 1) . (p cols) ) listofGroupRtabs
-- debug
-- !dummy3 = trace (show listOfGroupingColumnsRtabs) True
-- 4. Aggregate each group according to input and produce a list of (aggregated singleton RTables)
listOfAggregatedRtabs = Data.List.map (rAgg aggOps) listofGroupRtabs
-- debug
-- !dummy4 = trace (show listOfAggregatedRtabs ) True
-- 5. Join the two list of singleton RTables
listOfFinalRtabs = Data.List.zipWith (iJ (\t1 t2 -> True)) listOfGroupingColumnsRtabs listOfAggregatedRtabs
-- debug
-- !dummy5 = trace (show listOfFinalRtabs) True
-- 6. Union all individual singleton RTables into the final RTable
in Data.List.foldr1 (u) listOfFinalRtabs
where
createOrderingSpec :: [ColumnName] -> [(ColumnName, OrderingSpec)]
createOrderingSpec cols = Data.List.zip cols (Data.List.take (Data.List.length cols) $ Data.List.repeat Asc)
rComb = runCombinedROp
-- | runCombinedROp: A Higher Order function that accepts as input a combination of unary ROperations e.g., (p plist).(f pred)
-- expressed in the form of a function (RTable -> Rtable) and applies this function to the input RTable.
-- In this sense we can also include a binary operation (e.g. join), if we partially apply the join to one RTable
-- e.g., (ij jpred rtab) . (p plist) . (f pred)
runCombinedROp ::
(RTable -> RTable) -- ^ input combined RTable operation
-> RTable -- ^ input RTable that the input function will be applied to
-> RTable -- ^ output RTable
runCombinedROp f rtab = f rtab
-- * ########## RTable DML Operations ##############
-- | O(n) append an RTuple to an RTable
insertAppendRTab :: RTuple -> RTable -> RTable
insertAppendRTab rtup rtab = V.snoc rtab rtup
-- | O(n) prepend an RTuple to an RTable
insertPrependRTab :: RTuple -> RTable -> RTable
insertPrependRTab rtup rtab = V.cons rtup rtab
-- | Update an RTable. Input includes a list of (ColumnName, new Value) pairs.
-- Also a filter predicate is specified in order to restrict the update only to those
-- rtuples that fulfill the predicate
updateRTab ::
[(ColumnName, RDataType)] -- ^ List of column names to be updated with the corresponding new values
-> RPredicate -- ^ An RTuple -> Bool function that specifies the RTuples to be updated
-> RTable -- ^ Input RTable
-> RTable -- ^ Output RTable
updateRTab [] _ inputRtab = inputRtab
updateRTab ((colName, newVal) : rest) rpred inputRtab =
{-
Here is the update algorithm:
FinalRTable = UNION (Table A) (Table B)
where
Table A = the subset of input RTable that includes the rtuples that satisfy the input RPredicate, with updated values in the
corresponding columns
Table B = the subset of input RTable that includes all the rtuples that DONT satisfy the input RPredicate
-}
if isRTabEmpty inputRtab
then emptyRTable
else
let
tabA = rtabMap (upsertRTuple colName newVal) (f rpred inputRtab)
tabB = f (not . rpred) inputRtab
in updateRTab rest rpred (u tabA tabB)
-- * ########## RTable IO Operations ##############
-- | Basic data type for defining the desired formatting of an Rtuple
data RTupleFormat = RTupleFormat {
-- | For defining the column ordering (i.e., the SELECT clause in SQL)
colSelectList :: [ColumnName]
-- | For defining the formating per Column (in printf style)
,colFormatMap :: ColFormatMap
} deriving (Eq, Show)
-- | A map of ColumnName to Format Specification
type ColFormatMap = HM.HashMap ColumnName FormatSpecifier
-- | Generates a default Column Format Specification
genDefaultColFormatMap :: ColFormatMap
genDefaultColFormatMap = HM.empty
-- | Generates a Column Format Specification
genColFormatMap ::
[(ColumnName, FormatSpecifier)]
-> ColFormatMap
genColFormatMap fs = HM.fromList fs
-- | Format specifier of Text.Printf.printf style.(see https://hackage.haskell.org/package/base-4.10.1.0/docs/Text-Printf.html)
data FormatSpecifier = DefaultFormat | Format String deriving (Eq, Show)
-- | Generate an RTupleFormat data type instance
genRTupleFormat ::
[ColumnName] -- ^ Column Select list
-> ColFormatMap -- ^ Column Format Map
-> RTupleFormat -- ^ Output
genRTupleFormat colNames colfMap = RTupleFormat { colSelectList = colNames, colFormatMap = colfMap}
-- | Generate a default RTupleFormat data type instance.
-- In this case the returned column order (Select list), will be unspecified
-- and dependant only by the underlying structure of the RTuple (HashMap)
genRTupleFormatDefault :: RTupleFormat
genRTupleFormatDefault = RTupleFormat { colSelectList = [], colFormatMap = genDefaultColFormatMap }
-- | prints an RTable with an RTuple format specification
printfRTable :: RTupleFormat -> RTable -> IO()
printfRTable rtupFmt rtab = -- undefined
if isRTabEmpty rtab
then
do
putStrLn "-------------------------------------------"
putStrLn " 0 rows returned"
putStrLn "-------------------------------------------"
else
do
-- find the max value-length for each column, this will be the width of the box for this column
let listOfLengths = getMaxLengthPerColumnFmt rtupFmt rtab
--debug
--putStrLn $ "List of Lengths: " ++ show listOfLengths
printContLineFmt rtupFmt listOfLengths '-' rtab
-- print the Header
printRTableHeaderFmt rtupFmt listOfLengths rtab
-- print the body
printRTabBodyFmt rtupFmt listOfLengths $ V.toList rtab
-- print number of rows returned
let numrows = V.length rtab
if numrows == 1
then
putStrLn $ "\n"++ (show $ numrows) ++ " row returned"
else
putStrLn $ "\n"++ (show $ numrows) ++ " rows returned"
printContLineFmt rtupFmt listOfLengths '-' rtab
where
-- [Int] a List of width per column to be used in the box definition
printRTabBodyFmt :: RTupleFormat -> [Int] -> [RTuple] -> IO()
printRTabBodyFmt _ _ [] = putStrLn ""
printRTabBodyFmt rtupf ws (rtup : rest) = do
printRTupleFmt rtupf ws rtup
printRTabBodyFmt rtupf ws rest
-- | printRTable : Print the input RTable on screen
printRTable ::
RTable
-> IO ()
printRTable rtab =
if isRTabEmpty rtab
then
do
putStrLn "-------------------------------------------"
putStrLn " 0 rows returned"
putStrLn "-------------------------------------------"
else
do
-- find the max value-length for each column, this will be the width of the box for this column
let listOfLengths = getMaxLengthPerColumn rtab
--debug
--putStrLn $ "List of Lengths: " ++ show listOfLengths
printContLine listOfLengths '-' rtab
-- print the Header
printRTableHeader listOfLengths rtab
-- print the body
printRTabBody listOfLengths $ V.toList rtab
-- print number of rows returned
let numrows = V.length rtab
if numrows == 1
then
putStrLn $ "\n"++ (show $ numrows) ++ " row returned"
else
putStrLn $ "\n"++ (show $ numrows) ++ " rows returned"
printContLine listOfLengths '-' rtab
where
-- [Int] a List of width per column to be used in the box definition
printRTabBody :: [Int] -> [RTuple] -> IO()
printRTabBody _ [] = putStrLn ""
printRTabBody ws (rtup : rest) = do
printRTuple ws rtup
printRTabBody ws rest
-- | Returns the max length of the String representation of each value, for each column of the input RTable.
-- It returns the lengths in the column order specified by the input RTupleFormat parameter
getMaxLengthPerColumnFmt :: RTupleFormat -> RTable -> [Int]
getMaxLengthPerColumnFmt rtupFmt rtab =
let
-- Create an RTable where all the values of the columns will be the length of the String representations of the original values
lengthRTab = do
rtup <- rtab
let ls = Data.List.map (\(c, v) -> (c, RInt $ fromIntegral $ Data.List.length . rdataTypeToString $ v) ) (rtupleToList rtup)
-- create an RTuple with the column names lengths
headerLengths = Data.List.zip (getColumnNamesfromRTab rtab) (Data.List.map (\c -> RInt $ fromIntegral $ Data.List.length c) (getColumnNamesfromRTab rtab))
-- append to the rtable also the tuple corresponding to the header (i.e., the values will be the names of the column) in order
-- to count them also in the width calculation
(return $ createRtuple ls) V.++ (return $ createRtuple headerLengths)
-- Get the max length for each column
resultRTab = findMaxLengthperColumn lengthRTab
where
findMaxLengthperColumn :: RTable -> RTable
findMaxLengthperColumn rt =
let colNames = (getColumnNamesfromRTab rt) -- [ColumnName]
aggOpsList = Data.List.map (\c -> raggMax c c) colNames -- [AggOp]
in runAggregation aggOpsList rt
-- get the RTuple with the results
resultRTuple = headRTup resultRTab
in
-- transform it to [Int]
if rtupFmt /= genRTupleFormatDefault
then
-- generate [Int] in the column order specified by the format parameter
Data.List.map (\(RInt i) -> fromIntegral i) $
Data.List.map (\colname -> resultRTuple <!> colname) $ colSelectList rtupFmt -- [RInt i]
else
-- else just choose the default column order (i.e., unspecified)
Data.List.map (\(colname, RInt i) -> fromIntegral i) (rtupleToList resultRTuple)
-- | Returns the max length of the String representation of each value, for each column of the input RTable.
getMaxLengthPerColumn :: RTable -> [Int]
getMaxLengthPerColumn rtab =
let
-- Create an RTable where all the values of the columns will be the length of the String representations of the original values
lengthRTab = do
rtup <- rtab
let ls = Data.List.map (\(c, v) -> (c, RInt $ fromIntegral $ Data.List.length . rdataTypeToString $ v) ) (rtupleToList rtup)
-- create an RTuple with the column names lengths
headerLengths = Data.List.zip (getColumnNamesfromRTab rtab) (Data.List.map (\c -> RInt $ fromIntegral $ Data.List.length c) (getColumnNamesfromRTab rtab))
-- append to the rtable also the tuple corresponding to the header (i.e., the values will be the names of the column) in order
-- to count them also in the width calculation
(return $ createRtuple ls) V.++ (return $ createRtuple headerLengths)
-- Get the max length for each column
resultRTab = findMaxLengthperColumn lengthRTab
where
findMaxLengthperColumn :: RTable -> RTable
findMaxLengthperColumn rt =
let colNames = (getColumnNamesfromRTab rt) -- [ColumnName]
aggOpsList = Data.List.map (\c -> raggMax c c) colNames -- [AggOp]
in runAggregation aggOpsList rt
{-
-- create a Julius expression to evaluate the max length per column
julexpr = EtlMapStart
-- Turn each value to an (RInt i) that correposnd to the length of the String representation of the value
:-> (EtlC $
Source (getColumnNamesfromRTab rtab)
Target (getColumnNamesfromRTab rtab)
By (\[value] -> [RInt $ Data.List.length . rdataTypeToString $ value] )
(On $ Tab rtab)
RemoveSrc $
FilterBy (\rtuple -> True)
)
-- Get the max length for each column
:-> (EtlR $
ROpStart
:. (GenUnaryOp (On Previous) $ ByUnaryOp findMaxLengthperColumn)
)
where
findMaxLengthperColumn :: RTable -> RTable
findMaxLengthperColumn rt =
let colNames = (getColumnNamesfromRTab rt) -- [ColumnName]
aggOpsList = V.map (\c -> raggMax c c) colNames -- [AggOp]
in runAggregation aggOpsList rt
-- evaluate the xpression and get the result in an RTable
resultRTab = juliusToRTable julexpr
-}
-- get the RTuple with the results
resultRTuple = headRTup resultRTab
in
-- transform it to a [Int]
Data.List.map (\(colname, RInt i) -> fromIntegral i) (rtupleToList resultRTuple)
spaceSeparatorWidth :: Int
spaceSeparatorWidth = 5
-- | helper function in order to format the value of a column
-- It will append at the end of the string n number of spaces.
addSpace ::
Int -- ^ number of spaces to add
-> String -- ^ input String
-> String -- ^ output string
addSpace i s = s ++ Data.List.take i (repeat ' ')
-- | helper function in order to format the value of a column
-- It will append at the end of the string n number of spaces.
addCharacter ::
Int -- ^ number of spaces to add
-> Char -- ^ character to add
-> String -- ^ input String
-> String -- ^ output string
addCharacter i c s = s ++ Data.List.take i (repeat c)
-- | helper function that prints a continuous line adjusted to the size of the input RTable
-- The column order is specified by the input RTupleFormat parameter
printContLineFmt ::
RTupleFormat -- ^ Specifies the appropriate column order
-> [Int] -- ^ a List of width per column to be used in the box definition
-> Char -- ^ the char with which the line will be drawn
-> RTable
-> IO ()
printContLineFmt rtupFmt widths ch rtab = do
let listOfColNames = if rtupFmt /= genRTupleFormatDefault
then
colSelectList rtupFmt
else
getColumnNamesfromRTab rtab -- [ColumnName]
listOfLinesCont = Data.List.map (\c -> Data.List.take (Data.List.length c) (repeat ch)) listOfColNames
formattedLinesCont = Data.List.map (\(w,l) -> addCharacter (w - (Data.List.length l) + spaceSeparatorWidth) ch l) (Data.List.zip widths listOfLinesCont)
formattedRowOfLinesCont = Data.List.foldr (\line accum -> line ++ accum) "" formattedLinesCont
putStrLn formattedRowOfLinesCont
-- | helper function that prints a continuous line adjusted to the size of the input RTable
printContLine ::
[Int] -- ^ a List of width per column to be used in the box definition
-> Char -- ^ the char with which the line will be drawn
-> RTable
-> IO ()
printContLine widths ch rtab = do
let listOfColNames = getColumnNamesfromRTab rtab -- [ColumnName]
listOfLinesCont = Data.List.map (\c -> Data.List.take (Data.List.length c) (repeat ch)) listOfColNames
formattedLinesCont = Data.List.map (\(w,l) -> addCharacter (w - (Data.List.length l) + spaceSeparatorWidth) ch l) (Data.List.zip widths listOfLinesCont)
formattedRowOfLinesCont = Data.List.foldr (\line accum -> line ++ accum) "" formattedLinesCont
putStrLn formattedRowOfLinesCont
-- | Prints the input RTable's header (i.e., column names) on screen.
-- The column order is specified by the corresponding RTupleFormat parameter.
printRTableHeaderFmt ::
RTupleFormat -- ^ Specifies Column order
-> [Int] -- ^ a List of width per column to be used in the box definition
-> RTable
-> IO ()
printRTableHeaderFmt rtupFmt widths rtab = do -- undefined
let listOfColNames = if rtupFmt /= genRTupleFormatDefault then colSelectList rtupFmt else getColumnNamesfromRTab rtab -- [ColumnName]
-- format each column name according the input width and return a list of Boxes [Box]
-- formattedList = Data.List.map (\(w,c) -> BX.para BX.left (w + spaceSeparatorWidth) c) (Data.List.zip widths listOfColNames) -- listOfColNames -- map (\c -> BX.render . BX.text $ c) listOfColNames
formattedList = Data.List.map (\(w,c) -> addSpace (w - (Data.List.length c) + spaceSeparatorWidth) c) (Data.List.zip widths listOfColNames)
-- Paste all boxes together horizontally
-- formattedRow = BX.render $ Data.List.foldr (\colname_box accum -> accum BX.<+> colname_box) BX.nullBox formattedList
formattedRow = Data.List.foldr (\colname accum -> colname ++ accum) "" formattedList
listOfLines = Data.List.map (\c -> Data.List.take (Data.List.length c) (repeat '~')) listOfColNames
-- listOfLinesCont = Data.List.map (\c -> Data.List.take (Data.List.length c) (repeat '-')) listOfColNames
--formattedLines = Data.List.map (\(w,l) -> BX.para BX.left (w +spaceSeparatorWidth) l) (Data.List.zip widths listOfLines)
formattedLines = Data.List.map (\(w,l) -> addSpace (w - (Data.List.length l) + spaceSeparatorWidth) l) (Data.List.zip widths listOfLines)
-- formattedLinesCont = Data.List.map (\(w,l) -> addCharacter (w - (Data.List.length l) + spaceSeparatorWidth) '-' l) (Data.List.zip widths listOfLinesCont)
-- formattedRowOfLines = BX.render $ Data.List.foldr (\line_box accum -> accum BX.<+> line_box) BX.nullBox formattedLines
formattedRowOfLines = Data.List.foldr (\line accum -> line ++ accum) "" formattedLines
--- formattedRowOfLinesCont = Data.List.foldr (\line accum -> line ++ accum) "" formattedLinesCont
-- printUnderlines formattedRowOfLinesCont
printHeader formattedRow
printUnderlines formattedRowOfLines
where
printHeader :: String -> IO()
printHeader h = putStrLn h
printUnderlines :: String -> IO()
printUnderlines l = putStrLn l
-- | printRTableHeader : Prints the input RTable's header (i.e., column names) on screen
printRTableHeader ::
[Int] -- ^ a List of width per column to be used in the box definition
-> RTable
-> IO ()
printRTableHeader widths rtab = do -- undefined
let listOfColNames = getColumnNamesfromRTab rtab -- [ColumnName]
-- format each column name according the input width and return a list of Boxes [Box]
-- formattedList = Data.List.map (\(w,c) -> BX.para BX.left (w + spaceSeparatorWidth) c) (Data.List.zip widths listOfColNames) -- listOfColNames -- map (\c -> BX.render . BX.text $ c) listOfColNames
formattedList = Data.List.map (\(w,c) -> addSpace (w - (Data.List.length c) + spaceSeparatorWidth) c) (Data.List.zip widths listOfColNames)
-- Paste all boxes together horizontally
-- formattedRow = BX.render $ Data.List.foldr (\colname_box accum -> accum BX.<+> colname_box) BX.nullBox formattedList
formattedRow = Data.List.foldr (\colname accum -> colname ++ accum) "" formattedList
listOfLines = Data.List.map (\c -> Data.List.take (Data.List.length c) (repeat '~')) listOfColNames
-- listOfLinesCont = Data.List.map (\c -> Data.List.take (Data.List.length c) (repeat '-')) listOfColNames
--formattedLines = Data.List.map (\(w,l) -> BX.para BX.left (w +spaceSeparatorWidth) l) (Data.List.zip widths listOfLines)
formattedLines = Data.List.map (\(w,l) -> addSpace (w - (Data.List.length l) + spaceSeparatorWidth) l) (Data.List.zip widths listOfLines)
-- formattedLinesCont = Data.List.map (\(w,l) -> addCharacter (w - (Data.List.length l) + spaceSeparatorWidth) '-' l) (Data.List.zip widths listOfLinesCont)
-- formattedRowOfLines = BX.render $ Data.List.foldr (\line_box accum -> accum BX.<+> line_box) BX.nullBox formattedLines
formattedRowOfLines = Data.List.foldr (\line accum -> line ++ accum) "" formattedLines
--- formattedRowOfLinesCont = Data.List.foldr (\line accum -> line ++ accum) "" formattedLinesCont
-- printUnderlines formattedRowOfLinesCont
printHeader formattedRow
printUnderlines formattedRowOfLines
where
printHeader :: String -> IO()
printHeader h = putStrLn h
printUnderlines :: String -> IO()
printUnderlines l = putStrLn l
{- printHeader :: [String] -> IO ()
printHeader [] = putStrLn ""
printHeader (x:xs) = do
putStr $ x ++ "\t"
printHeader xs
printUnderlines :: [String] -> IO ()
printUnderlines [] = putStrLn ""
printUnderlines (x:xs) = do
putStr $ (Data.List.take (Data.List.length x) (repeat '~')) ++ "\t"
printUnderlines xs
-}
-- | Prints an RTuple on screen (only the values of the columns)
-- [Int] is a List of width per column to be used in the box definition
-- The column order as well as the formatting specifications are specified by the first parameter.
-- We assume that the order in [Int] corresponds to that of the RTupleFormat parameter.
printRTupleFmt :: RTupleFormat -> [Int] -> RTuple -> IO()
printRTupleFmt rtupFmt widths rtup = do
-- take list of values of each column and convert to String
let rtupList = if rtupFmt == genRTupleFormatDefault
then -- then no column ordering is specified nore column formatting
Data.List.map (rdataTypeToString . snd) (rtupleToList rtup) -- [RDataType] --> [String]
else
if (colFormatMap rtupFmt) == genDefaultColFormatMap
then -- col ordering is specified but no formatting per column
Data.List.map (\colname -> rdataTypeToStringFmt DefaultFormat $ rtup <!> colname ) $ colSelectList rtupFmt
else -- both column ordering, as well as formatting per column is specified
Data.List.map (\colname -> rdataTypeToStringFmt ((colFormatMap rtupFmt) ! colname) $ rtup <!> colname ) $ colSelectList rtupFmt
-- format each column value according the input width and return a list of [Box]
-- formattedValueList = Data.List.map (\(w,v) -> BX.para BX.left w v) (Data.List.zip widths rtupList)
formattedValueList = Data.List.map (\(w,v) -> addSpace (w - (Data.List.length v) + spaceSeparatorWidth) v) (Data.List.zip widths rtupList)
-- Data.List.map (\(c,r) -> BX.text . rdataTypeToString $ r) rtupList
-- Data.List.map (\(c,r) -> rdataTypeToString $ r) rtupList -- -- [String]
-- Paste all boxes together horizontally
-- formattedRow = BX.render $ Data.List.foldr (\value_box accum -> accum BX.<+> value_box) BX.nullBox formattedValueList
formattedRow = Data.List.foldr (\value_box accum -> value_box ++ accum) "" formattedValueList
putStrLn formattedRow
-- | Prints an RTuple on screen (only the values of the columns)
-- [Int] is a List of width per column to be used in the box definition
printRTuple :: [Int] -> RTuple -> IO()
printRTuple widths rtup = do
-- take list of values of each column and convert to String
let rtupList = Data.List.map (rdataTypeToString . snd) (rtupleToList rtup) -- [RDataType] --> [String]
-- format each column value according the input width and return a list of [Box]
-- formattedValueList = Data.List.map (\(w,v) -> BX.para BX.left w v) (Data.List.zip widths rtupList)
formattedValueList = Data.List.map (\(w,v) -> addSpace (w - (Data.List.length v) + spaceSeparatorWidth) v) (Data.List.zip widths rtupList)
-- Data.List.map (\(c,r) -> BX.text . rdataTypeToString $ r) rtupList
-- Data.List.map (\(c,r) -> rdataTypeToString $ r) rtupList -- -- [String]
-- Paste all boxes together horizontally
-- formattedRow = BX.render $ Data.List.foldr (\value_box accum -> accum BX.<+> value_box) BX.nullBox formattedValueList
formattedRow = Data.List.foldr (\value_box accum -> value_box ++ accum) "" formattedValueList
putStrLn formattedRow
{- printList formattedValueList
where
printList :: [String] -> IO()
printList [] = putStrLn ""
printList (x:xs) = do
putStr $ x ++ "\t"
printList xs
-}
-- | Turn the value stored in a RDataType into a String in order to be able to print it wrt to the specified format
rdataTypeToStringFmt :: FormatSpecifier -> RDataType -> String
rdataTypeToStringFmt fmt rdt =
case fmt of
DefaultFormat -> rdataTypeToString rdt
Format fspec ->
case rdt of
RInt i -> printf fspec i
RText t -> printf fspec (unpack t)
RDate {rdate = d, dtformat = f} -> printf fspec (unpack d)
RTime t -> printf fspec $ unpack $ rtext (rTimeStampToRText "DD/MM/YYYY HH24:MI:SS" t)
-- Round to only two decimal digits after the decimal point
RDouble db -> printf fspec db -- show db
Null -> "NULL"
-- | Turn the value stored in a RDataType into a String in order to be able to print it
-- Values are transformed with a default formatting.
rdataTypeToString :: RDataType -> String
rdataTypeToString rdt =
case rdt of
RInt i -> show i
RText t -> unpack t
RDate {rdate = d, dtformat = f} -> unpack d
RTime t -> unpack $ rtext (rTimeStampToRText "DD/MM/YYYY HH24:MI:SS" t)
-- Round to only two decimal digits after the decimal point
RDouble db -> printf "%.2f" db -- show db
Null -> "NULL"
{-
-- | This data type is used in order to be able to print the value of a column of an RTuple
data ColPrint = ColPrint { colName :: String, val :: String } deriving (Data, G.Generic)
instance PP.Tabulate ColPrint
data PrintableRTuple = PrintableRTuple [ColPrint] deriving (Data, G.Generic)
instance PP.Tabulate PrintableRTuple
instance PP.CellValueFormatter PrintableRTuple where
-- ppFormatter :: a -> String
ppFormatter [] = ""
ppFormatter (colpr:rest) = (BX.render $ BX.text (val colpr)) ++ "\t" ++ ppFormatter rest
-- | Turn an RTuple to a list of RTuplePrint
rtupToPrintableRTup :: RTuple -> PrintableRTuple
rtupToPrintableRTup rtup =
let rtupList = rtupleToList rtup -- [(ColumnName, RDataType)]
in PrintableRTuple $ Data.List.map (\(c,r) -> ColPrint { colName = c, val = rdataTypeToString r }) rtupList -- [ColPrint]
-- | Turn the value stored in a RDataType into a String in order to be able to print it
rdataTypeToString :: RDataType -> String
rdataTypeToString rdt = undefined
-- | printRTable : Print the input RTable on screen
printRTable ::
RTable
-> IO ()
printRTable rtab = -- undefined
do
let vectorOfprintableRTups = do
rtup <- rtab
let rtupPrint = rtupToPrintableRTup rtup
return rtupPrint
{-
let rtupList = rtupleToList rtup -- [(ColumnName, RDataType)]
colNamesList = Data.List.map (show . fst) rtupList -- [String]
rdatatypesStringfied = Data.List.map (rdataTypeToString . snd) rtupList -- [String]
map = Data.Map.fromList $ Data.List.zip colNamesList rdatatypesStringfied -- [(String, String)]
return colNamesList -- map -}
PP.ppTable vectorOfprintableRTups
-} | nkarag/haskell-CSVDB | src/Data/RTable.hs | bsd-3-clause | 129,913 | 0 | 27 | 48,996 | 15,304 | 8,522 | 6,782 | 1,217 | 11 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-}
{-# LANGUAGE CPP, DeriveDataTypeable, DeriveFunctor #-}
-- | CoreSyn holds all the main data types for use by for the Glasgow Haskell Compiler midsection
module CoreSyn (
-- * Main data types
Expr(..), Alt, Bind(..), AltCon(..), Arg,
Tickish(..), TickishScoping(..), TickishPlacement(..),
CoreProgram, CoreExpr, CoreAlt, CoreBind, CoreArg, CoreBndr,
TaggedExpr, TaggedAlt, TaggedBind, TaggedArg, TaggedBndr(..), deTagExpr,
-- ** 'Expr' construction
mkLets, mkLams,
mkApps, mkTyApps, mkCoApps, mkVarApps,
mkIntLit, mkIntLitInt,
mkWordLit, mkWordLitWord,
mkWord64LitWord64, mkInt64LitInt64,
mkCharLit, mkStringLit,
mkFloatLit, mkFloatLitFloat,
mkDoubleLit, mkDoubleLitDouble,
mkConApp, mkConApp2, mkTyBind, mkCoBind,
varToCoreExpr, varsToCoreExprs,
isId, cmpAltCon, cmpAlt, ltAlt,
-- ** Simple 'Expr' access functions and predicates
bindersOf, bindersOfBinds, rhssOfBind, rhssOfAlts,
collectBinders, collectTyBinders, collectTyAndValBinders,
collectArgs, collectArgsTicks, flattenBinds,
exprToType, exprToCoercion_maybe,
applyTypeToArg,
isValArg, isTypeArg, isTyCoArg, valArgCount, valBndrCount,
isRuntimeArg, isRuntimeVar,
tickishCounts, tickishScoped, tickishScopesLike, tickishFloatable,
tickishCanSplit, mkNoCount, mkNoScope,
tickishIsCode, tickishPlace,
tickishContains,
-- * Unfolding data types
Unfolding(..), UnfoldingGuidance(..), UnfoldingSource(..),
-- ** Constructing 'Unfolding's
noUnfolding, bootUnfolding, evaldUnfolding, mkOtherCon,
unSaturatedOk, needSaturated, boringCxtOk, boringCxtNotOk,
-- ** Predicates and deconstruction on 'Unfolding'
unfoldingTemplate, expandUnfolding_maybe,
maybeUnfoldingTemplate, otherCons,
isValueUnfolding, isEvaldUnfolding, isCheapUnfolding,
isExpandableUnfolding, isConLikeUnfolding, isCompulsoryUnfolding,
isStableUnfolding, hasStableCoreUnfolding_maybe,
isClosedUnfolding, hasSomeUnfolding,
isBootUnfolding,
canUnfold, neverUnfoldGuidance, isStableSource,
-- * Annotated expression data types
AnnExpr, AnnExpr'(..), AnnBind(..), AnnAlt,
-- ** Operations on annotated expressions
collectAnnArgs, collectAnnArgsTicks,
-- ** Operations on annotations
deAnnotate, deAnnotate', deAnnAlt, collectAnnBndrs,
-- * Orphanhood
IsOrphan(..), isOrphan, notOrphan, chooseOrphanAnchor,
-- * Core rule data types
CoreRule(..), RuleBase,
RuleName, RuleFun, IdUnfoldingFun, InScopeEnv,
RuleEnv(..), mkRuleEnv, emptyRuleEnv,
-- ** Operations on 'CoreRule's
ruleArity, ruleName, ruleIdName, ruleActivation,
setRuleIdName,
isBuiltinRule, isLocalRule, isAutoRule,
-- * Core vectorisation declarations data type
CoreVect(..)
) where
#include "HsVersions.h"
import CostCentre
import VarEnv( InScopeSet )
import Var
import Type
import Coercion
import Name
import NameSet
import NameEnv( NameEnv, emptyNameEnv )
import Literal
import DataCon
import Module
import TyCon
import BasicTypes
import DynFlags
import Outputable
import Util
import UniqFM
import SrcLoc ( RealSrcSpan, containsSpan )
import Binary
import Data.Data hiding (TyCon)
import Data.Int
import Data.Word
infixl 4 `mkApps`, `mkTyApps`, `mkVarApps`, `App`, `mkCoApps`
-- Left associative, so that we can say (f `mkTyApps` xs `mkVarApps` ys)
{-
************************************************************************
* *
\subsection{The main data types}
* *
************************************************************************
These data types are the heart of the compiler
-}
-- | This is the data type that represents GHCs core intermediate language. Currently
-- GHC uses System FC <http://research.microsoft.com/~simonpj/papers/ext-f/> for this purpose,
-- which is closely related to the simpler and better known System F <http://en.wikipedia.org/wiki/System_F>.
--
-- We get from Haskell source to this Core language in a number of stages:
--
-- 1. The source code is parsed into an abstract syntax tree, which is represented
-- by the data type 'HsExpr.HsExpr' with the names being 'RdrName.RdrNames'
--
-- 2. This syntax tree is /renamed/, which attaches a 'Unique.Unique' to every 'RdrName.RdrName'
-- (yielding a 'Name.Name') to disambiguate identifiers which are lexically identical.
-- For example, this program:
--
-- @
-- f x = let f x = x + 1
-- in f (x - 2)
-- @
--
-- Would be renamed by having 'Unique's attached so it looked something like this:
--
-- @
-- f_1 x_2 = let f_3 x_4 = x_4 + 1
-- in f_3 (x_2 - 2)
-- @
-- But see Note [Shadowing] below.
--
-- 3. The resulting syntax tree undergoes type checking (which also deals with instantiating
-- type class arguments) to yield a 'HsExpr.HsExpr' type that has 'Id.Id' as it's names.
--
-- 4. Finally the syntax tree is /desugared/ from the expressive 'HsExpr.HsExpr' type into
-- this 'Expr' type, which has far fewer constructors and hence is easier to perform
-- optimization, analysis and code generation on.
--
-- The type parameter @b@ is for the type of binders in the expression tree.
--
-- The language consists of the following elements:
--
-- * Variables
--
-- * Primitive literals
--
-- * Applications: note that the argument may be a 'Type'.
--
-- See "CoreSyn#let_app_invariant" for another invariant
--
-- * Lambda abstraction
--
-- * Recursive and non recursive @let@s. Operationally
-- this corresponds to allocating a thunk for the things
-- bound and then executing the sub-expression.
--
-- #top_level_invariant#
-- #letrec_invariant#
--
-- The right hand sides of all top-level and recursive @let@s
-- /must/ be of lifted type (see "Type#type_classification" for
-- the meaning of /lifted/ vs. /unlifted/).
--
-- See Note [CoreSyn let/app invariant]
--
-- #type_let#
-- We allow a /non-recursive/ let to bind a type variable, thus:
--
-- > Let (NonRec tv (Type ty)) body
--
-- This can be very convenient for postponing type substitutions until
-- the next run of the simplifier.
--
-- At the moment, the rest of the compiler only deals with type-let
-- in a Let expression, rather than at top level. We may want to revist
-- this choice.
--
-- * Case split. Operationally this corresponds to evaluating
-- the scrutinee (expression examined) to weak head normal form
-- and then examining at most one level of resulting constructor (i.e. you
-- cannot do nested pattern matching directly with this).
--
-- The binder gets bound to the value of the scrutinee,
-- and the 'Type' must be that of all the case alternatives
--
-- #case_invariants#
-- This is one of the more complicated elements of the Core language,
-- and comes with a number of restrictions:
--
-- 1. The list of alternatives may be empty;
-- See Note [Empty case alternatives]
--
-- 2. The 'DEFAULT' case alternative must be first in the list,
-- if it occurs at all.
--
-- 3. The remaining cases are in order of increasing
-- tag (for 'DataAlts') or
-- lit (for 'LitAlts').
-- This makes finding the relevant constructor easy,
-- and makes comparison easier too.
--
-- 4. The list of alternatives must be exhaustive. An /exhaustive/ case
-- does not necessarily mention all constructors:
--
-- @
-- data Foo = Red | Green | Blue
-- ... case x of
-- Red -> True
-- other -> f (case x of
-- Green -> ...
-- Blue -> ... ) ...
-- @
--
-- The inner case does not need a @Red@ alternative, because @x@
-- can't be @Red@ at that program point.
--
-- 5. Floating-point values must not be scrutinised against literals.
-- See Trac #9238 and Note [Rules for floating-point comparisons]
-- in PrelRules for rationale.
--
-- * Cast an expression to a particular type.
-- This is used to implement @newtype@s (a @newtype@ constructor or
-- destructor just becomes a 'Cast' in Core) and GADTs.
--
-- * Notes. These allow general information to be added to expressions
-- in the syntax tree
--
-- * A type: this should only show up at the top level of an Arg
--
-- * A coercion
-- If you edit this type, you may need to update the GHC formalism
-- See Note [GHC Formalism] in coreSyn/CoreLint.hs
data Expr b
= Var Id
| Lit Literal
| App (Expr b) (Arg b)
| Lam b (Expr b)
| Let (Bind b) (Expr b)
| Case (Expr b) b Type [Alt b] -- See #case_invariant#
| Cast (Expr b) Coercion
| Tick (Tickish Id) (Expr b)
| Type Type
| Coercion Coercion
deriving Data
-- | Type synonym for expressions that occur in function argument positions.
-- Only 'Arg' should contain a 'Type' at top level, general 'Expr' should not
type Arg b = Expr b
-- | A case split alternative. Consists of the constructor leading to the alternative,
-- the variables bound from the constructor, and the expression to be executed given that binding.
-- The default alternative is @(DEFAULT, [], rhs)@
-- If you edit this type, you may need to update the GHC formalism
-- See Note [GHC Formalism] in coreSyn/CoreLint.hs
type Alt b = (AltCon, [b], Expr b)
-- | A case alternative constructor (i.e. pattern match)
-- If you edit this type, you may need to update the GHC formalism
-- See Note [GHC Formalism] in coreSyn/CoreLint.hs
data AltCon
= DataAlt DataCon -- ^ A plain data constructor: @case e of { Foo x -> ... }@.
-- Invariant: the 'DataCon' is always from a @data@ type, and never from a @newtype@
| LitAlt Literal -- ^ A literal: @case e of { 1 -> ... }@
-- Invariant: always an *unlifted* literal
-- See Note [Literal alternatives]
| DEFAULT -- ^ Trivial alternative: @case e of { _ -> ... }@
deriving (Eq, Data)
-- | Binding, used for top level bindings in a module and local bindings in a @let@.
-- If you edit this type, you may need to update the GHC formalism
-- See Note [GHC Formalism] in coreSyn/CoreLint.hs
data Bind b = NonRec b (Expr b)
| Rec [(b, (Expr b))]
deriving Data
{-
Note [Shadowing]
~~~~~~~~~~~~~~~~
While various passes attempt to rename on-the-fly in a manner that
avoids "shadowing" (thereby simplifying downstream optimizations),
neither the simplifier nor any other pass GUARANTEES that shadowing is
avoided. Thus, all passes SHOULD work fine even in the presence of
arbitrary shadowing in their inputs.
In particular, scrutinee variables `x` in expressions of the form
`Case e x t` are often renamed to variables with a prefix
"wild_". These "wild" variables may appear in the body of the
case-expression, and further, may be shadowed within the body.
So the Unique in an Var is not really unique at all. Still, it's very
useful to give a constant-time equality/ordering for Vars, and to give
a key that can be used to make sets of Vars (VarSet), or mappings from
Vars to other things (VarEnv). Moreover, if you do want to eliminate
shadowing, you can give a new Unique to an Id without changing its
printable name, which makes debugging easier.
Note [Literal alternatives]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Literal alternatives (LitAlt lit) are always for *un-lifted* literals.
We have one literal, a literal Integer, that is lifted, and we don't
allow in a LitAlt, because LitAlt cases don't do any evaluation. Also
(see Trac #5603) if you say
case 3 of
S# x -> ...
J# _ _ -> ...
(where S#, J# are the constructors for Integer) we don't want the
simplifier calling findAlt with argument (LitAlt 3). No no. Integer
literals are an opaque encoding of an algebraic data type, not of
an unlifted literal, like all the others.
Also, we do not permit case analysis with literal patterns on floating-point
types. See Trac #9238 and Note [Rules for floating-point comparisons] in
PrelRules for the rationale for this restriction.
-------------------------- CoreSyn INVARIANTS ---------------------------
Note [CoreSyn top-level invariant]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
See #toplevel_invariant#
Note [CoreSyn letrec invariant]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
See #letrec_invariant#
Note [CoreSyn let/app invariant]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The let/app invariant
the right hand side of a non-recursive 'Let', and
the argument of an 'App',
/may/ be of unlifted type, but only if
the expression is ok-for-speculation.
This means that the let can be floated around
without difficulty. For example, this is OK:
y::Int# = x +# 1#
But this is not, as it may affect termination if the
expression is floated out:
y::Int# = fac 4#
In this situation you should use @case@ rather than a @let@. The function
'CoreUtils.needsCaseBinding' can help you determine which to generate, or
alternatively use 'MkCore.mkCoreLet' rather than this constructor directly,
which will generate a @case@ if necessary
Th let/app invariant is initially enforced by DsUtils.mkCoreLet and mkCoreApp
Note [CoreSyn case invariants]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
See #case_invariants#
Note [CoreSyn let goal]
~~~~~~~~~~~~~~~~~~~~~~~
* The simplifier tries to ensure that if the RHS of a let is a constructor
application, its arguments are trivial, so that the constructor can be
inlined vigorously.
Note [Type let]
~~~~~~~~~~~~~~~
See #type_let#
Note [Empty case alternatives]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The alternatives of a case expression should be exhaustive. But
this exhaustive list can be empty!
* A case expression can have empty alternatives if (and only if) the
scrutinee is bound to raise an exception or diverge. When do we know
this? See Note [Bottoming expressions] in CoreUtils.
* The possiblity of empty alternatives is one reason we need a type on
the case expression: if the alternatives are empty we can't get the
type from the alternatives!
* In the case of empty types (see Note [Bottoming expressions]), say
data T
we do NOT want to replace
case (x::T) of Bool {} --> error Bool "Inaccessible case"
because x might raise an exception, and *that*'s what we want to see!
(Trac #6067 is an example.) To preserve semantics we'd have to say
x `seq` error Bool "Inaccessible case"
but the 'seq' is just a case, so we are back to square 1. Or I suppose
we could say
x |> UnsafeCoerce T Bool
but that loses all trace of the fact that this originated with an empty
set of alternatives.
* We can use the empty-alternative construct to coerce error values from
one type to another. For example
f :: Int -> Int
f n = error "urk"
g :: Int -> (# Char, Bool #)
g x = case f x of { 0 -> ..., n -> ... }
Then if we inline f in g's RHS we get
case (error Int "urk") of (# Char, Bool #) { ... }
and we can discard the alternatives since the scrutinee is bottom to give
case (error Int "urk") of (# Char, Bool #) {}
This is nicer than using an unsafe coerce between Int ~ (# Char,Bool #),
if for no other reason that we don't need to instantiate the (~) at an
unboxed type.
* We treat a case expression with empty alternatives as trivial iff
its scrutinee is (see CoreUtils.exprIsTrivial). This is actually
important; see Note [Empty case is trivial] in CoreUtils
* An empty case is replaced by its scrutinee during the CoreToStg
conversion; remember STG is un-typed, so there is no need for
the empty case to do the type conversion.
************************************************************************
* *
Ticks
* *
************************************************************************
-}
-- | Allows attaching extra information to points in expressions
-- If you edit this type, you may need to update the GHC formalism
-- See Note [GHC Formalism] in coreSyn/CoreLint.hs
data Tickish id =
-- | An @{-# SCC #-}@ profiling annotation, either automatically
-- added by the desugarer as a result of -auto-all, or added by
-- the user.
ProfNote {
profNoteCC :: CostCentre, -- ^ the cost centre
profNoteCount :: !Bool, -- ^ bump the entry count?
profNoteScope :: !Bool -- ^ scopes over the enclosed expression
-- (i.e. not just a tick)
}
-- | A "tick" used by HPC to track the execution of each
-- subexpression in the original source code.
| HpcTick {
tickModule :: Module,
tickId :: !Int
}
-- | A breakpoint for the GHCi debugger. This behaves like an HPC
-- tick, but has a list of free variables which will be available
-- for inspection in GHCi when the program stops at the breakpoint.
--
-- NB. we must take account of these Ids when (a) counting free variables,
-- and (b) substituting (don't substitute for them)
| Breakpoint
{ breakpointId :: !Int
, breakpointFVs :: [id] -- ^ the order of this list is important:
-- it matches the order of the lists in the
-- appropriate entry in HscTypes.ModBreaks.
--
-- Careful about substitution! See
-- Note [substTickish] in CoreSubst.
}
-- | A source note.
--
-- Source notes are pure annotations: Their presence should neither
-- influence compilation nor execution. The semantics are given by
-- causality: The presence of a source note means that a local
-- change in the referenced source code span will possibly provoke
-- the generated code to change. On the flip-side, the functionality
-- of annotated code *must* be invariant against changes to all
-- source code *except* the spans referenced in the source notes
-- (see "Causality of optimized Haskell" paper for details).
--
-- Therefore extending the scope of any given source note is always
-- valid. Note that it is still undesirable though, as this reduces
-- their usefulness for debugging and profiling. Therefore we will
-- generally try only to make use of this property where it is
-- neccessary to enable optimizations.
| SourceNote
{ sourceSpan :: RealSrcSpan -- ^ Source covered
, sourceName :: String -- ^ Name for source location
-- (uses same names as CCs)
}
deriving (Eq, Ord, Data)
-- | A "counting tick" (where tickishCounts is True) is one that
-- counts evaluations in some way. We cannot discard a counting tick,
-- and the compiler should preserve the number of counting ticks as
-- far as possible.
--
-- However, we still allow the simplifier to increase or decrease
-- sharing, so in practice the actual number of ticks may vary, except
-- that we never change the value from zero to non-zero or vice versa.
tickishCounts :: Tickish id -> Bool
tickishCounts n@ProfNote{} = profNoteCount n
tickishCounts HpcTick{} = True
tickishCounts Breakpoint{} = True
tickishCounts _ = False
-- | Specifies the scoping behaviour of ticks. This governs the
-- behaviour of ticks that care about the covered code and the cost
-- associated with it. Important for ticks relating to profiling.
data TickishScoping =
-- | No scoping: The tick does not care about what code it
-- covers. Transformations can freely move code inside as well as
-- outside without any additional annotation obligations
NoScope
-- | Soft scoping: We want all code that is covered to stay
-- covered. Note that this scope type does not forbid
-- transformations from happening, as as long as all results of
-- the transformations are still covered by this tick or a copy of
-- it. For example
--
-- let x = tick<...> (let y = foo in bar) in baz
-- ===>
-- let x = tick<...> bar; y = tick<...> foo in baz
--
-- Is a valid transformation as far as "bar" and "foo" is
-- concerned, because both still are scoped over by the tick.
--
-- Note though that one might object to the "let" not being
-- covered by the tick any more. However, we are generally lax
-- with this - constant costs don't matter too much, and given
-- that the "let" was effectively merged we can view it as having
-- lost its identity anyway.
--
-- Also note that this scoping behaviour allows floating a tick
-- "upwards" in pretty much any situation. For example:
--
-- case foo of x -> tick<...> bar
-- ==>
-- tick<...> case foo of x -> bar
--
-- While this is always leagl, we want to make a best effort to
-- only make us of this where it exposes transformation
-- opportunities.
| SoftScope
-- | Cost centre scoping: We don't want any costs to move to other
-- cost-centre stacks. This means we not only want no code or cost
-- to get moved out of their cost centres, but we also object to
-- code getting associated with new cost-centre ticks - or
-- changing the order in which they get applied.
--
-- A rule of thumb is that we don't want any code to gain new
-- annotations. However, there are notable exceptions, for
-- example:
--
-- let f = \y -> foo in tick<...> ... (f x) ...
-- ==>
-- tick<...> ... foo[x/y] ...
--
-- In-lining lambdas like this is always legal, because inlining a
-- function does not change the cost-centre stack when the
-- function is called.
| CostCentreScope
deriving (Eq)
-- | Returns the intended scoping rule for a Tickish
tickishScoped :: Tickish id -> TickishScoping
tickishScoped n@ProfNote{}
| profNoteScope n = CostCentreScope
| otherwise = NoScope
tickishScoped HpcTick{} = NoScope
tickishScoped Breakpoint{} = CostCentreScope
-- Breakpoints are scoped: eventually we're going to do call
-- stacks, but also this helps prevent the simplifier from moving
-- breakpoints around and changing their result type (see #1531).
tickishScoped SourceNote{} = SoftScope
-- | Returns whether the tick scoping rule is at least as permissive
-- as the given scoping rule.
tickishScopesLike :: Tickish id -> TickishScoping -> Bool
tickishScopesLike t scope = tickishScoped t `like` scope
where NoScope `like` _ = True
_ `like` NoScope = False
SoftScope `like` _ = True
_ `like` SoftScope = False
CostCentreScope `like` _ = True
-- | Returns @True@ for ticks that can be floated upwards easily even
-- where it might change execution counts, such as:
--
-- Just (tick<...> foo)
-- ==>
-- tick<...> (Just foo)
--
-- This is a combination of @tickishSoftScope@ and
-- @tickishCounts@. Note that in principle splittable ticks can become
-- floatable using @mkNoTick@ -- even though there's currently no
-- tickish for which that is the case.
tickishFloatable :: Tickish id -> Bool
tickishFloatable t = t `tickishScopesLike` SoftScope && not (tickishCounts t)
-- | Returns @True@ for a tick that is both counting /and/ scoping and
-- can be split into its (tick, scope) parts using 'mkNoScope' and
-- 'mkNoTick' respectively.
tickishCanSplit :: Tickish id -> Bool
tickishCanSplit ProfNote{profNoteScope = True, profNoteCount = True}
= True
tickishCanSplit _ = False
mkNoCount :: Tickish id -> Tickish id
mkNoCount n | not (tickishCounts n) = n
| not (tickishCanSplit n) = panic "mkNoCount: Cannot split!"
mkNoCount n@ProfNote{} = n {profNoteCount = False}
mkNoCount _ = panic "mkNoCount: Undefined split!"
mkNoScope :: Tickish id -> Tickish id
mkNoScope n | tickishScoped n == NoScope = n
| not (tickishCanSplit n) = panic "mkNoScope: Cannot split!"
mkNoScope n@ProfNote{} = n {profNoteScope = False}
mkNoScope _ = panic "mkNoScope: Undefined split!"
-- | Return @True@ if this source annotation compiles to some backend
-- code. Without this flag, the tickish is seen as a simple annotation
-- that does not have any associated evaluation code.
--
-- What this means that we are allowed to disregard the tick if doing
-- so means that we can skip generating any code in the first place. A
-- typical example is top-level bindings:
--
-- foo = tick<...> \y -> ...
-- ==>
-- foo = \y -> tick<...> ...
--
-- Here there is just no operational difference between the first and
-- the second version. Therefore code generation should simply
-- translate the code as if it found the latter.
tickishIsCode :: Tickish id -> Bool
tickishIsCode SourceNote{} = False
tickishIsCode _tickish = True -- all the rest for now
-- | Governs the kind of expression that the tick gets placed on when
-- annotating for example using @mkTick@. If we find that we want to
-- put a tickish on an expression ruled out here, we try to float it
-- inwards until we find a suitable expression.
data TickishPlacement =
-- | Place ticks exactly on run-time expressions. We can still
-- move the tick through pure compile-time constructs such as
-- other ticks, casts or type lambdas. This is the most
-- restrictive placement rule for ticks, as all tickishs have in
-- common that they want to track runtime processes. The only
-- legal placement rule for counting ticks.
PlaceRuntime
-- | As @PlaceRuntime@, but we float the tick through all
-- lambdas. This makes sense where there is little difference
-- between annotating the lambda and annotating the lambda's code.
| PlaceNonLam
-- | In addition to floating through lambdas, cost-centre style
-- tickishs can also be moved from constructors, non-function
-- variables and literals. For example:
--
-- let x = scc<...> C (scc<...> y) (scc<...> 3) in ...
--
-- Neither the constructor application, the variable or the
-- literal are likely to have any cost worth mentioning. And even
-- if y names a thunk, the call would not care about the
-- evaluation context. Therefore removing all annotations in the
-- above example is safe.
| PlaceCostCentre
deriving (Eq)
-- | Placement behaviour we want for the ticks
tickishPlace :: Tickish id -> TickishPlacement
tickishPlace n@ProfNote{}
| profNoteCount n = PlaceRuntime
| otherwise = PlaceCostCentre
tickishPlace HpcTick{} = PlaceRuntime
tickishPlace Breakpoint{} = PlaceRuntime
tickishPlace SourceNote{} = PlaceNonLam
-- | Returns whether one tick "contains" the other one, therefore
-- making the second tick redundant.
tickishContains :: Eq b => Tickish b -> Tickish b -> Bool
tickishContains (SourceNote sp1 n1) (SourceNote sp2 n2)
= n1 == n2 && containsSpan sp1 sp2
tickishContains t1 t2
= t1 == t2
{-
************************************************************************
* *
Orphans
* *
************************************************************************
-}
-- | Is this instance an orphan? If it is not an orphan, contains an 'OccName'
-- witnessing the instance's non-orphanhood.
-- See Note [Orphans]
data IsOrphan
= IsOrphan
| NotOrphan OccName -- The OccName 'n' witnesses the instance's non-orphanhood
-- In that case, the instance is fingerprinted as part
-- of the definition of 'n's definition
deriving Data
-- | Returns true if 'IsOrphan' is orphan.
isOrphan :: IsOrphan -> Bool
isOrphan IsOrphan = True
isOrphan _ = False
-- | Returns true if 'IsOrphan' is not an orphan.
notOrphan :: IsOrphan -> Bool
notOrphan NotOrphan{} = True
notOrphan _ = False
chooseOrphanAnchor :: NameSet -> IsOrphan
-- Something (rule, instance) is relate to all the Names in this
-- list. Choose one of them to be an "anchor" for the orphan. We make
-- the choice deterministic to avoid gratuitious changes in the ABI
-- hash (Trac #4012). Specficially, use lexicographic comparison of
-- OccName rather than comparing Uniques
--
-- NB: 'minimum' use Ord, and (Ord OccName) works lexicographically
--
chooseOrphanAnchor local_names
| isEmptyNameSet local_names = IsOrphan
| otherwise = NotOrphan (minimum occs)
where
occs = map nameOccName $ nonDetEltsUFM local_names
-- It's OK to use nonDetEltsUFM here, see comments above
instance Binary IsOrphan where
put_ bh IsOrphan = putByte bh 0
put_ bh (NotOrphan n) = do
putByte bh 1
put_ bh n
get bh = do
h <- getByte bh
case h of
0 -> return IsOrphan
_ -> do
n <- get bh
return $ NotOrphan n
{-
Note [Orphans]
~~~~~~~~~~~~~~
Class instances, rules, and family instances are divided into orphans
and non-orphans. Roughly speaking, an instance/rule is an orphan if
its left hand side mentions nothing defined in this module. Orphan-hood
has two major consequences
* A module that contains orphans is called an "orphan module". If
the module being compiled depends (transitively) on an oprhan
module M, then M.hi is read in regardless of whether M is oherwise
needed. This is to ensure that we don't miss any instance decls in
M. But it's painful, because it means we need to keep track of all
the orphan modules below us.
* A non-orphan is not finger-printed separately. Instead, for
fingerprinting purposes it is treated as part of the entity it
mentions on the LHS. For example
data T = T1 | T2
instance Eq T where ....
The instance (Eq T) is incorprated as part of T's fingerprint.
In constrast, orphans are all fingerprinted together in the
mi_orph_hash field of the ModIface.
See MkIface.addFingerprints.
Orphan-hood is computed
* For class instances:
when we make a ClsInst
(because it is needed during instance lookup)
* For rules and family instances:
when we generate an IfaceRule (MkIface.coreRuleToIfaceRule)
or IfaceFamInst (MkIface.instanceToIfaceInst)
-}
{-
************************************************************************
* *
\subsection{Transformation rules}
* *
************************************************************************
The CoreRule type and its friends are dealt with mainly in CoreRules,
but CoreFVs, Subst, PprCore, CoreTidy also inspect the representation.
-}
-- | Gathers a collection of 'CoreRule's. Maps (the name of) an 'Id' to its rules
type RuleBase = NameEnv [CoreRule]
-- The rules are unordered;
-- we sort out any overlaps on lookup
-- | A full rule environment which we can apply rules from. Like a 'RuleBase',
-- but it also includes the set of visible orphans we use to filter out orphan
-- rules which are not visible (even though we can see them...)
data RuleEnv
= RuleEnv { re_base :: RuleBase
, re_visible_orphs :: ModuleSet
}
mkRuleEnv :: RuleBase -> [Module] -> RuleEnv
mkRuleEnv rules vis_orphs = RuleEnv rules (mkModuleSet vis_orphs)
emptyRuleEnv :: RuleEnv
emptyRuleEnv = RuleEnv emptyNameEnv emptyModuleSet
-- | A 'CoreRule' is:
--
-- * \"Local\" if the function it is a rule for is defined in the
-- same module as the rule itself.
--
-- * \"Orphan\" if nothing on the LHS is defined in the same module
-- as the rule itself
data CoreRule
= Rule {
ru_name :: RuleName, -- ^ Name of the rule, for communication with the user
ru_act :: Activation, -- ^ When the rule is active
-- Rough-matching stuff
-- see comments with InstEnv.ClsInst( is_cls, is_rough )
ru_fn :: Name, -- ^ Name of the 'Id.Id' at the head of this rule
ru_rough :: [Maybe Name], -- ^ Name at the head of each argument to the left hand side
-- Proper-matching stuff
-- see comments with InstEnv.ClsInst( is_tvs, is_tys )
ru_bndrs :: [CoreBndr], -- ^ Variables quantified over
ru_args :: [CoreExpr], -- ^ Left hand side arguments
-- And the right-hand side
ru_rhs :: CoreExpr, -- ^ Right hand side of the rule
-- Occurrence info is guaranteed correct
-- See Note [OccInfo in unfoldings and rules]
-- Locality
ru_auto :: Bool, -- ^ @True@ <=> this rule is auto-generated
-- (notably by Specialise or SpecConstr)
-- @False@ <=> generated at the users behest
-- See Note [Trimming auto-rules] in TidyPgm
-- for the sole purpose of this field.
ru_origin :: !Module, -- ^ 'Module' the rule was defined in, used
-- to test if we should see an orphan rule.
ru_orphan :: !IsOrphan, -- ^ Whether or not the rule is an orphan.
ru_local :: Bool -- ^ @True@ iff the fn at the head of the rule is
-- defined in the same module as the rule
-- and is not an implicit 'Id' (like a record selector,
-- class operation, or data constructor). This
-- is different from 'ru_orphan', where a rule
-- can avoid being an orphan if *any* Name in
-- LHS of the rule was defined in the same
-- module as the rule.
}
-- | Built-in rules are used for constant folding
-- and suchlike. They have no free variables.
-- A built-in rule is always visible (there is no such thing as
-- an orphan built-in rule.)
| BuiltinRule {
ru_name :: RuleName, -- ^ As above
ru_fn :: Name, -- ^ As above
ru_nargs :: Int, -- ^ Number of arguments that 'ru_try' consumes,
-- if it fires, including type arguments
ru_try :: RuleFun
-- ^ This function does the rewrite. It given too many
-- arguments, it simply discards them; the returned 'CoreExpr'
-- is just the rewrite of 'ru_fn' applied to the first 'ru_nargs' args
}
-- See Note [Extra args in rule matching] in Rules.hs
type RuleFun = DynFlags -> InScopeEnv -> Id -> [CoreExpr] -> Maybe CoreExpr
type InScopeEnv = (InScopeSet, IdUnfoldingFun)
type IdUnfoldingFun = Id -> Unfolding
-- A function that embodies how to unfold an Id if you need
-- to do that in the Rule. The reason we need to pass this info in
-- is that whether an Id is unfoldable depends on the simplifier phase
isBuiltinRule :: CoreRule -> Bool
isBuiltinRule (BuiltinRule {}) = True
isBuiltinRule _ = False
isAutoRule :: CoreRule -> Bool
isAutoRule (BuiltinRule {}) = False
isAutoRule (Rule { ru_auto = is_auto }) = is_auto
-- | The number of arguments the 'ru_fn' must be applied
-- to before the rule can match on it
ruleArity :: CoreRule -> Int
ruleArity (BuiltinRule {ru_nargs = n}) = n
ruleArity (Rule {ru_args = args}) = length args
ruleName :: CoreRule -> RuleName
ruleName = ru_name
ruleActivation :: CoreRule -> Activation
ruleActivation (BuiltinRule { }) = AlwaysActive
ruleActivation (Rule { ru_act = act }) = act
-- | The 'Name' of the 'Id.Id' at the head of the rule left hand side
ruleIdName :: CoreRule -> Name
ruleIdName = ru_fn
isLocalRule :: CoreRule -> Bool
isLocalRule = ru_local
-- | Set the 'Name' of the 'Id.Id' at the head of the rule left hand side
setRuleIdName :: Name -> CoreRule -> CoreRule
setRuleIdName nm ru = ru { ru_fn = nm }
{-
************************************************************************
* *
\subsection{Vectorisation declarations}
* *
************************************************************************
Representation of desugared vectorisation declarations that are fed to the vectoriser (via
'ModGuts').
-}
data CoreVect = Vect Id CoreExpr
| NoVect Id
| VectType Bool TyCon (Maybe TyCon)
| VectClass TyCon -- class tycon
| VectInst Id -- instance dfun (always SCALAR) !!!FIXME: should be superfluous now
{-
************************************************************************
* *
Unfoldings
* *
************************************************************************
The @Unfolding@ type is declared here to avoid numerous loops
-}
-- | Records the /unfolding/ of an identifier, which is approximately the form the
-- identifier would have if we substituted its definition in for the identifier.
-- This type should be treated as abstract everywhere except in "CoreUnfold"
data Unfolding
= NoUnfolding -- ^ We have no information about the unfolding.
| BootUnfolding -- ^ We have no information about the unfolding, because
-- this 'Id' came from an @hi-boot@ file.
-- See Note [Inlining and hs-boot files] for what
-- this is used for.
| OtherCon [AltCon] -- ^ It ain't one of these constructors.
-- @OtherCon xs@ also indicates that something has been evaluated
-- and hence there's no point in re-evaluating it.
-- @OtherCon []@ is used even for non-data-type values
-- to indicated evaluated-ness. Notably:
--
-- > data C = C !(Int -> Int)
-- > case x of { C f -> ... }
--
-- Here, @f@ gets an @OtherCon []@ unfolding.
| DFunUnfolding { -- The Unfolding of a DFunId
-- See Note [DFun unfoldings]
-- df = /\a1..am. \d1..dn. MkD t1 .. tk
-- (op1 a1..am d1..dn)
-- (op2 a1..am d1..dn)
df_bndrs :: [Var], -- The bound variables [a1..m],[d1..dn]
df_con :: DataCon, -- The dictionary data constructor (never a newtype datacon)
df_args :: [CoreExpr] -- Args of the data con: types, superclasses and methods,
} -- in positional order
| CoreUnfolding { -- An unfolding for an Id with no pragma,
-- or perhaps a NOINLINE pragma
-- (For NOINLINE, the phase, if any, is in the
-- InlinePragInfo for this Id.)
uf_tmpl :: CoreExpr, -- Template; occurrence info is correct
uf_src :: UnfoldingSource, -- Where the unfolding came from
uf_is_top :: Bool, -- True <=> top level binding
uf_is_value :: Bool, -- exprIsHNF template (cached); it is ok to discard
-- a `seq` on this variable
uf_is_conlike :: Bool, -- True <=> applicn of constructor or CONLIKE function
-- Cached version of exprIsConLike
uf_is_work_free :: Bool, -- True <=> doesn't waste (much) work to expand
-- inside an inlining
-- Cached version of exprIsCheap
uf_expandable :: Bool, -- True <=> can expand in RULE matching
-- Cached version of exprIsExpandable
uf_guidance :: UnfoldingGuidance -- Tells about the *size* of the template.
}
-- ^ An unfolding with redundant cached information. Parameters:
--
-- uf_tmpl: Template used to perform unfolding;
-- NB: Occurrence info is guaranteed correct:
-- see Note [OccInfo in unfoldings and rules]
--
-- uf_is_top: Is this a top level binding?
--
-- uf_is_value: 'exprIsHNF' template (cached); it is ok to discard a 'seq' on
-- this variable
--
-- uf_is_work_free: Does this waste only a little work if we expand it inside an inlining?
-- Basically this is a cached version of 'exprIsWorkFree'
--
-- uf_guidance: Tells us about the /size/ of the unfolding template
------------------------------------------------
data UnfoldingSource
= -- See also Note [Historical note: unfoldings for wrappers]
InlineRhs -- The current rhs of the function
-- Replace uf_tmpl each time around
| InlineStable -- From an INLINE or INLINABLE pragma
-- INLINE if guidance is UnfWhen
-- INLINABLE if guidance is UnfIfGoodArgs/UnfoldNever
-- (well, technically an INLINABLE might be made
-- UnfWhen if it was small enough, and then
-- it will behave like INLINE outside the current
-- module, but that is the way automatic unfoldings
-- work so it is consistent with the intended
-- meaning of INLINABLE).
--
-- uf_tmpl may change, but only as a result of
-- gentle simplification, it doesn't get updated
-- to the current RHS during compilation as with
-- InlineRhs.
--
-- See Note [InlineRules]
| InlineCompulsory -- Something that *has* no binding, so you *must* inline it
-- Only a few primop-like things have this property
-- (see MkId.hs, calls to mkCompulsoryUnfolding).
-- Inline absolutely always, however boring the context.
-- | 'UnfoldingGuidance' says when unfolding should take place
data UnfoldingGuidance
= UnfWhen { -- Inline without thinking about the *size* of the uf_tmpl
-- Used (a) for small *and* cheap unfoldings
-- (b) for INLINE functions
-- See Note [INLINE for small functions] in CoreUnfold
ug_arity :: Arity, -- Number of value arguments expected
ug_unsat_ok :: Bool, -- True <=> ok to inline even if unsaturated
ug_boring_ok :: Bool -- True <=> ok to inline even if the context is boring
-- So True,True means "always"
}
| UnfIfGoodArgs { -- Arose from a normal Id; the info here is the
-- result of a simple analysis of the RHS
ug_args :: [Int], -- Discount if the argument is evaluated.
-- (i.e., a simplification will definitely
-- be possible). One elt of the list per *value* arg.
ug_size :: Int, -- The "size" of the unfolding.
ug_res :: Int -- Scrutinee discount: the discount to substract if the thing is in
} -- a context (case (thing args) of ...),
-- (where there are the right number of arguments.)
| UnfNever -- The RHS is big, so don't inline it
deriving (Eq)
{-
Note [Historical note: unfoldings for wrappers]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We used to have a nice clever scheme in interface files for
wrappers. A wrapper's unfolding can be reconstructed from its worker's
id and its strictness. This decreased .hi file size (sometimes
significantly, for modules like GHC.Classes with many high-arity w/w
splits) and had a slight corresponding effect on compile times.
However, when we added the second demand analysis, this scheme lead to
some Core lint errors. The second analysis could change the strictness
signatures, which sometimes resulted in a wrapper's regenerated
unfolding applying the wrapper to too many arguments.
Instead of repairing the clever .hi scheme, we abandoned it in favor
of simplicity. The .hi sizes are usually insignificant (excluding the
+1M for base libraries), and compile time barely increases (~+1% for
nofib). The nicer upshot is that the UnfoldingSource no longer mentions
an Id, so, eg, substitutions need not traverse them.
Note [DFun unfoldings]
~~~~~~~~~~~~~~~~~~~~~~
The Arity in a DFunUnfolding is total number of args (type and value)
that the DFun needs to produce a dictionary. That's not necessarily
related to the ordinary arity of the dfun Id, esp if the class has
one method, so the dictionary is represented by a newtype. Example
class C a where { op :: a -> Int }
instance C a -> C [a] where op xs = op (head xs)
The instance translates to
$dfCList :: forall a. C a => C [a] -- Arity 2!
$dfCList = /\a.\d. $copList {a} d |> co
$copList :: forall a. C a => [a] -> Int -- Arity 2!
$copList = /\a.\d.\xs. op {a} d (head xs)
Now we might encounter (op (dfCList {ty} d) a1 a2)
and we want the (op (dfList {ty} d)) rule to fire, because $dfCList
has all its arguments, even though its (value) arity is 2. That's
why we record the number of expected arguments in the DFunUnfolding.
Note that although it's an Arity, it's most convenient for it to give
the *total* number of arguments, both type and value. See the use
site in exprIsConApp_maybe.
-}
-- Constants for the UnfWhen constructor
needSaturated, unSaturatedOk :: Bool
needSaturated = False
unSaturatedOk = True
boringCxtNotOk, boringCxtOk :: Bool
boringCxtOk = True
boringCxtNotOk = False
------------------------------------------------
noUnfolding :: Unfolding
-- ^ There is no known 'Unfolding'
evaldUnfolding :: Unfolding
-- ^ This unfolding marks the associated thing as being evaluated
noUnfolding = NoUnfolding
evaldUnfolding = OtherCon []
-- | There is no known 'Unfolding', because this came from an
-- hi-boot file.
bootUnfolding :: Unfolding
bootUnfolding = BootUnfolding
mkOtherCon :: [AltCon] -> Unfolding
mkOtherCon = OtherCon
isStableSource :: UnfoldingSource -> Bool
-- Keep the unfolding template
isStableSource InlineCompulsory = True
isStableSource InlineStable = True
isStableSource InlineRhs = False
-- | Retrieves the template of an unfolding: panics if none is known
unfoldingTemplate :: Unfolding -> CoreExpr
unfoldingTemplate = uf_tmpl
-- | Retrieves the template of an unfolding if possible
-- maybeUnfoldingTemplate is used mainly wnen specialising, and we do
-- want to specialise DFuns, so it's important to return a template
-- for DFunUnfoldings
maybeUnfoldingTemplate :: Unfolding -> Maybe CoreExpr
maybeUnfoldingTemplate (CoreUnfolding { uf_tmpl = expr })
= Just expr
maybeUnfoldingTemplate (DFunUnfolding { df_bndrs = bndrs, df_con = con, df_args = args })
= Just (mkLams bndrs (mkApps (Var (dataConWorkId con)) args))
maybeUnfoldingTemplate _
= Nothing
-- | The constructors that the unfolding could never be:
-- returns @[]@ if no information is available
otherCons :: Unfolding -> [AltCon]
otherCons (OtherCon cons) = cons
otherCons _ = []
-- | Determines if it is certainly the case that the unfolding will
-- yield a value (something in HNF): returns @False@ if unsure
isValueUnfolding :: Unfolding -> Bool
-- Returns False for OtherCon
isValueUnfolding (CoreUnfolding { uf_is_value = is_evald }) = is_evald
isValueUnfolding _ = False
-- | Determines if it possibly the case that the unfolding will
-- yield a value. Unlike 'isValueUnfolding' it returns @True@
-- for 'OtherCon'
isEvaldUnfolding :: Unfolding -> Bool
-- Returns True for OtherCon
isEvaldUnfolding (OtherCon _) = True
isEvaldUnfolding (CoreUnfolding { uf_is_value = is_evald }) = is_evald
isEvaldUnfolding _ = False
-- | @True@ if the unfolding is a constructor application, the application
-- of a CONLIKE function or 'OtherCon'
isConLikeUnfolding :: Unfolding -> Bool
isConLikeUnfolding (OtherCon _) = True
isConLikeUnfolding (CoreUnfolding { uf_is_conlike = con }) = con
isConLikeUnfolding _ = False
-- | Is the thing we will unfold into certainly cheap?
isCheapUnfolding :: Unfolding -> Bool
isCheapUnfolding (CoreUnfolding { uf_is_work_free = is_wf }) = is_wf
isCheapUnfolding _ = False
isExpandableUnfolding :: Unfolding -> Bool
isExpandableUnfolding (CoreUnfolding { uf_expandable = is_expable }) = is_expable
isExpandableUnfolding _ = False
expandUnfolding_maybe :: Unfolding -> Maybe CoreExpr
-- Expand an expandable unfolding; this is used in rule matching
-- See Note [Expanding variables] in Rules.hs
-- The key point here is that CONLIKE things can be expanded
expandUnfolding_maybe (CoreUnfolding { uf_expandable = True, uf_tmpl = rhs }) = Just rhs
expandUnfolding_maybe _ = Nothing
hasStableCoreUnfolding_maybe :: Unfolding -> Maybe Bool
-- Just True <=> has stable inlining, very keen to inline (eg. INLINE pragma)
-- Just False <=> has stable inlining, open to inlining it (eg. INLINABLE pragma)
-- Nothing <=> not stable, or cannot inline it anyway
hasStableCoreUnfolding_maybe (CoreUnfolding { uf_src = src, uf_guidance = guide })
| isStableSource src
= case guide of
UnfWhen {} -> Just True
UnfIfGoodArgs {} -> Just False
UnfNever -> Nothing
hasStableCoreUnfolding_maybe _ = Nothing
isCompulsoryUnfolding :: Unfolding -> Bool
isCompulsoryUnfolding (CoreUnfolding { uf_src = InlineCompulsory }) = True
isCompulsoryUnfolding _ = False
isStableUnfolding :: Unfolding -> Bool
-- True of unfoldings that should not be overwritten
-- by a CoreUnfolding for the RHS of a let-binding
isStableUnfolding (CoreUnfolding { uf_src = src }) = isStableSource src
isStableUnfolding (DFunUnfolding {}) = True
isStableUnfolding _ = False
isClosedUnfolding :: Unfolding -> Bool -- No free variables
isClosedUnfolding (CoreUnfolding {}) = False
isClosedUnfolding (DFunUnfolding {}) = False
isClosedUnfolding _ = True
-- | Only returns False if there is no unfolding information available at all
hasSomeUnfolding :: Unfolding -> Bool
hasSomeUnfolding NoUnfolding = False
hasSomeUnfolding BootUnfolding = False
hasSomeUnfolding _ = True
isBootUnfolding :: Unfolding -> Bool
isBootUnfolding BootUnfolding = True
isBootUnfolding _ = False
neverUnfoldGuidance :: UnfoldingGuidance -> Bool
neverUnfoldGuidance UnfNever = True
neverUnfoldGuidance _ = False
canUnfold :: Unfolding -> Bool
canUnfold (CoreUnfolding { uf_guidance = g }) = not (neverUnfoldGuidance g)
canUnfold _ = False
{-
Note [InlineRules]
~~~~~~~~~~~~~~~~~
When you say
{-# INLINE f #-}
f x = <rhs>
you intend that calls (f e) are replaced by <rhs>[e/x] So we
should capture (\x.<rhs>) in the Unfolding of 'f', and never meddle
with it. Meanwhile, we can optimise <rhs> to our heart's content,
leaving the original unfolding intact in Unfolding of 'f'. For example
all xs = foldr (&&) True xs
any p = all . map p {-# INLINE any #-}
We optimise any's RHS fully, but leave the InlineRule saying "all . map p",
which deforests well at the call site.
So INLINE pragma gives rise to an InlineRule, which captures the original RHS.
Moreover, it's only used when 'f' is applied to the
specified number of arguments; that is, the number of argument on
the LHS of the '=' sign in the original source definition.
For example, (.) is now defined in the libraries like this
{-# INLINE (.) #-}
(.) f g = \x -> f (g x)
so that it'll inline when applied to two arguments. If 'x' appeared
on the left, thus
(.) f g x = f (g x)
it'd only inline when applied to three arguments. This slightly-experimental
change was requested by Roman, but it seems to make sense.
See also Note [Inlining an InlineRule] in CoreUnfold.
Note [OccInfo in unfoldings and rules]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In unfoldings and rules, we guarantee that the template is occ-analysed,
so that the occurrence info on the binders is correct. This is important,
because the Simplifier does not re-analyse the template when using it. If
the occurrence info is wrong
- We may get more simpifier iterations than necessary, because
once-occ info isn't there
- More seriously, we may get an infinite loop if there's a Rec
without a loop breaker marked
************************************************************************
* *
AltCon
* *
************************************************************************
-}
-- The Ord is needed for the FiniteMap used in the lookForConstructor
-- in SimplEnv. If you declared that lookForConstructor *ignores*
-- constructor-applications with LitArg args, then you could get
-- rid of this Ord.
instance Outputable AltCon where
ppr (DataAlt dc) = ppr dc
ppr (LitAlt lit) = ppr lit
ppr DEFAULT = text "__DEFAULT"
cmpAlt :: (AltCon, a, b) -> (AltCon, a, b) -> Ordering
cmpAlt (con1, _, _) (con2, _, _) = con1 `cmpAltCon` con2
ltAlt :: (AltCon, a, b) -> (AltCon, a, b) -> Bool
ltAlt a1 a2 = (a1 `cmpAlt` a2) == LT
cmpAltCon :: AltCon -> AltCon -> Ordering
-- ^ Compares 'AltCon's within a single list of alternatives
cmpAltCon DEFAULT DEFAULT = EQ
cmpAltCon DEFAULT _ = LT
cmpAltCon (DataAlt d1) (DataAlt d2) = dataConTag d1 `compare` dataConTag d2
cmpAltCon (DataAlt _) DEFAULT = GT
cmpAltCon (LitAlt l1) (LitAlt l2) = l1 `compare` l2
cmpAltCon (LitAlt _) DEFAULT = GT
cmpAltCon con1 con2 = WARN( True, text "Comparing incomparable AltCons" <+>
ppr con1 <+> ppr con2 )
LT
{-
************************************************************************
* *
\subsection{Useful synonyms}
* *
************************************************************************
Note [CoreProgram]
~~~~~~~~~~~~~~~~~~
The top level bindings of a program, a CoreProgram, are represented as
a list of CoreBind
* Later bindings in the list can refer to earlier ones, but not vice
versa. So this is OK
NonRec { x = 4 }
Rec { p = ...q...x...
; q = ...p...x }
Rec { f = ...p..x..f.. }
NonRec { g = ..f..q...x.. }
But it would NOT be ok for 'f' to refer to 'g'.
* The occurrence analyser does strongly-connected component analysis
on each Rec binding, and splits it into a sequence of smaller
bindings where possible. So the program typically starts life as a
single giant Rec, which is then dependency-analysed into smaller
chunks.
-}
-- If you edit this type, you may need to update the GHC formalism
-- See Note [GHC Formalism] in coreSyn/CoreLint.hs
type CoreProgram = [CoreBind] -- See Note [CoreProgram]
-- | The common case for the type of binders and variables when
-- we are manipulating the Core language within GHC
type CoreBndr = Var
-- | Expressions where binders are 'CoreBndr's
type CoreExpr = Expr CoreBndr
-- | Argument expressions where binders are 'CoreBndr's
type CoreArg = Arg CoreBndr
-- | Binding groups where binders are 'CoreBndr's
type CoreBind = Bind CoreBndr
-- | Case alternatives where binders are 'CoreBndr's
type CoreAlt = Alt CoreBndr
{-
************************************************************************
* *
\subsection{Tagging}
* *
************************************************************************
-}
-- | Binders are /tagged/ with a t
data TaggedBndr t = TB CoreBndr t -- TB for "tagged binder"
type TaggedBind t = Bind (TaggedBndr t)
type TaggedExpr t = Expr (TaggedBndr t)
type TaggedArg t = Arg (TaggedBndr t)
type TaggedAlt t = Alt (TaggedBndr t)
instance Outputable b => Outputable (TaggedBndr b) where
ppr (TB b l) = char '<' <> ppr b <> comma <> ppr l <> char '>'
instance Outputable b => OutputableBndr (TaggedBndr b) where
pprBndr _ b = ppr b -- Simple
pprInfixOcc b = ppr b
pprPrefixOcc b = ppr b
deTagExpr :: TaggedExpr t -> CoreExpr
deTagExpr (Var v) = Var v
deTagExpr (Lit l) = Lit l
deTagExpr (Type ty) = Type ty
deTagExpr (Coercion co) = Coercion co
deTagExpr (App e1 e2) = App (deTagExpr e1) (deTagExpr e2)
deTagExpr (Lam (TB b _) e) = Lam b (deTagExpr e)
deTagExpr (Let bind body) = Let (deTagBind bind) (deTagExpr body)
deTagExpr (Case e (TB b _) ty alts) = Case (deTagExpr e) b ty (map deTagAlt alts)
deTagExpr (Tick t e) = Tick t (deTagExpr e)
deTagExpr (Cast e co) = Cast (deTagExpr e) co
deTagBind :: TaggedBind t -> CoreBind
deTagBind (NonRec (TB b _) rhs) = NonRec b (deTagExpr rhs)
deTagBind (Rec prs) = Rec [(b, deTagExpr rhs) | (TB b _, rhs) <- prs]
deTagAlt :: TaggedAlt t -> CoreAlt
deTagAlt (con, bndrs, rhs) = (con, [b | TB b _ <- bndrs], deTagExpr rhs)
{-
************************************************************************
* *
\subsection{Core-constructing functions with checking}
* *
************************************************************************
-}
-- | Apply a list of argument expressions to a function expression in a nested fashion. Prefer to
-- use 'MkCore.mkCoreApps' if possible
mkApps :: Expr b -> [Arg b] -> Expr b
-- | Apply a list of type argument expressions to a function expression in a nested fashion
mkTyApps :: Expr b -> [Type] -> Expr b
-- | Apply a list of coercion argument expressions to a function expression in a nested fashion
mkCoApps :: Expr b -> [Coercion] -> Expr b
-- | Apply a list of type or value variables to a function expression in a nested fashion
mkVarApps :: Expr b -> [Var] -> Expr b
-- | Apply a list of argument expressions to a data constructor in a nested fashion. Prefer to
-- use 'MkCore.mkCoreConApps' if possible
mkConApp :: DataCon -> [Arg b] -> Expr b
mkApps f args = foldl App f args
mkCoApps f args = foldl (\ e a -> App e (Coercion a)) f args
mkVarApps f vars = foldl (\ e a -> App e (varToCoreExpr a)) f vars
mkConApp con args = mkApps (Var (dataConWorkId con)) args
mkTyApps f args = foldl (\ e a -> App e (typeOrCoercion a)) f args
where
typeOrCoercion ty
| Just co <- isCoercionTy_maybe ty = Coercion co
| otherwise = Type ty
mkConApp2 :: DataCon -> [Type] -> [Var] -> Expr b
mkConApp2 con tys arg_ids = Var (dataConWorkId con)
`mkApps` map Type tys
`mkApps` map varToCoreExpr arg_ids
-- | Create a machine integer literal expression of type @Int#@ from an @Integer@.
-- If you want an expression of type @Int@ use 'MkCore.mkIntExpr'
mkIntLit :: DynFlags -> Integer -> Expr b
-- | Create a machine integer literal expression of type @Int#@ from an @Int@.
-- If you want an expression of type @Int@ use 'MkCore.mkIntExpr'
mkIntLitInt :: DynFlags -> Int -> Expr b
mkIntLit dflags n = Lit (mkMachInt dflags n)
mkIntLitInt dflags n = Lit (mkMachInt dflags (toInteger n))
-- | Create a machine word literal expression of type @Word#@ from an @Integer@.
-- If you want an expression of type @Word@ use 'MkCore.mkWordExpr'
mkWordLit :: DynFlags -> Integer -> Expr b
-- | Create a machine word literal expression of type @Word#@ from a @Word@.
-- If you want an expression of type @Word@ use 'MkCore.mkWordExpr'
mkWordLitWord :: DynFlags -> Word -> Expr b
mkWordLit dflags w = Lit (mkMachWord dflags w)
mkWordLitWord dflags w = Lit (mkMachWord dflags (toInteger w))
mkWord64LitWord64 :: Word64 -> Expr b
mkWord64LitWord64 w = Lit (mkMachWord64 (toInteger w))
mkInt64LitInt64 :: Int64 -> Expr b
mkInt64LitInt64 w = Lit (mkMachInt64 (toInteger w))
-- | Create a machine character literal expression of type @Char#@.
-- If you want an expression of type @Char@ use 'MkCore.mkCharExpr'
mkCharLit :: Char -> Expr b
-- | Create a machine string literal expression of type @Addr#@.
-- If you want an expression of type @String@ use 'MkCore.mkStringExpr'
mkStringLit :: String -> Expr b
mkCharLit c = Lit (mkMachChar c)
mkStringLit s = Lit (mkMachString s)
-- | Create a machine single precision literal expression of type @Float#@ from a @Rational@.
-- If you want an expression of type @Float@ use 'MkCore.mkFloatExpr'
mkFloatLit :: Rational -> Expr b
-- | Create a machine single precision literal expression of type @Float#@ from a @Float@.
-- If you want an expression of type @Float@ use 'MkCore.mkFloatExpr'
mkFloatLitFloat :: Float -> Expr b
mkFloatLit f = Lit (mkMachFloat f)
mkFloatLitFloat f = Lit (mkMachFloat (toRational f))
-- | Create a machine double precision literal expression of type @Double#@ from a @Rational@.
-- If you want an expression of type @Double@ use 'MkCore.mkDoubleExpr'
mkDoubleLit :: Rational -> Expr b
-- | Create a machine double precision literal expression of type @Double#@ from a @Double@.
-- If you want an expression of type @Double@ use 'MkCore.mkDoubleExpr'
mkDoubleLitDouble :: Double -> Expr b
mkDoubleLit d = Lit (mkMachDouble d)
mkDoubleLitDouble d = Lit (mkMachDouble (toRational d))
-- | Bind all supplied binding groups over an expression in a nested let expression. Assumes
-- that the rhs satisfies the let/app invariant. Prefer to use 'MkCore.mkCoreLets' if
-- possible, which does guarantee the invariant
mkLets :: [Bind b] -> Expr b -> Expr b
-- | Bind all supplied binders over an expression in a nested lambda expression. Prefer to
-- use 'MkCore.mkCoreLams' if possible
mkLams :: [b] -> Expr b -> Expr b
mkLams binders body = foldr Lam body binders
mkLets binds body = foldr Let body binds
-- | Create a binding group where a type variable is bound to a type. Per "CoreSyn#type_let",
-- this can only be used to bind something in a non-recursive @let@ expression
mkTyBind :: TyVar -> Type -> CoreBind
mkTyBind tv ty = NonRec tv (Type ty)
-- | Create a binding group where a type variable is bound to a type. Per "CoreSyn#type_let",
-- this can only be used to bind something in a non-recursive @let@ expression
mkCoBind :: CoVar -> Coercion -> CoreBind
mkCoBind cv co = NonRec cv (Coercion co)
-- | Convert a binder into either a 'Var' or 'Type' 'Expr' appropriately
varToCoreExpr :: CoreBndr -> Expr b
varToCoreExpr v | isTyVar v = Type (mkTyVarTy v)
| isCoVar v = Coercion (mkCoVarCo v)
| otherwise = ASSERT( isId v ) Var v
varsToCoreExprs :: [CoreBndr] -> [Expr b]
varsToCoreExprs vs = map varToCoreExpr vs
{-
************************************************************************
* *
Getting a result type
* *
************************************************************************
These are defined here to avoid a module loop between CoreUtils and CoreFVs
-}
applyTypeToArg :: Type -> CoreExpr -> Type
-- ^ Determines the type resulting from applying an expression with given type
-- to a given argument expression
applyTypeToArg fun_ty arg = piResultTy fun_ty (exprToType arg)
-- | If the expression is a 'Type', converts. Otherwise,
-- panics. NB: This does /not/ convert 'Coercion' to 'CoercionTy'.
exprToType :: CoreExpr -> Type
exprToType (Type ty) = ty
exprToType _bad = pprPanic "exprToType" empty
-- | If the expression is a 'Coercion', converts.
exprToCoercion_maybe :: CoreExpr -> Maybe Coercion
exprToCoercion_maybe (Coercion co) = Just co
exprToCoercion_maybe _ = Nothing
{-
************************************************************************
* *
\subsection{Simple access functions}
* *
************************************************************************
-}
-- | Extract every variable by this group
bindersOf :: Bind b -> [b]
-- If you edit this function, you may need to update the GHC formalism
-- See Note [GHC Formalism] in coreSyn/CoreLint.hs
bindersOf (NonRec binder _) = [binder]
bindersOf (Rec pairs) = [binder | (binder, _) <- pairs]
-- | 'bindersOf' applied to a list of binding groups
bindersOfBinds :: [Bind b] -> [b]
bindersOfBinds binds = foldr ((++) . bindersOf) [] binds
rhssOfBind :: Bind b -> [Expr b]
rhssOfBind (NonRec _ rhs) = [rhs]
rhssOfBind (Rec pairs) = [rhs | (_,rhs) <- pairs]
rhssOfAlts :: [Alt b] -> [Expr b]
rhssOfAlts alts = [e | (_,_,e) <- alts]
-- | Collapse all the bindings in the supplied groups into a single
-- list of lhs\/rhs pairs suitable for binding in a 'Rec' binding group
flattenBinds :: [Bind b] -> [(b, Expr b)]
flattenBinds (NonRec b r : binds) = (b,r) : flattenBinds binds
flattenBinds (Rec prs1 : binds) = prs1 ++ flattenBinds binds
flattenBinds [] = []
-- | We often want to strip off leading lambdas before getting down to
-- business. Variants are 'collectTyBinders', 'collectValBinders',
-- and 'collectTyAndValBinders'
collectBinders :: Expr b -> ([b], Expr b)
collectTyBinders :: CoreExpr -> ([TyVar], CoreExpr)
collectValBinders :: CoreExpr -> ([Id], CoreExpr)
collectTyAndValBinders :: CoreExpr -> ([TyVar], [Id], CoreExpr)
collectBinders expr
= go [] expr
where
go bs (Lam b e) = go (b:bs) e
go bs e = (reverse bs, e)
collectTyBinders expr
= go [] expr
where
go tvs (Lam b e) | isTyVar b = go (b:tvs) e
go tvs e = (reverse tvs, e)
collectValBinders expr
= go [] expr
where
go ids (Lam b e) | isId b = go (b:ids) e
go ids body = (reverse ids, body)
collectTyAndValBinders expr
= (tvs, ids, body)
where
(tvs, body1) = collectTyBinders expr
(ids, body) = collectValBinders body1
-- | Takes a nested application expression and returns the the function
-- being applied and the arguments to which it is applied
collectArgs :: Expr b -> (Expr b, [Arg b])
collectArgs expr
= go expr []
where
go (App f a) as = go f (a:as)
go e as = (e, as)
-- | Like @collectArgs@, but also collects looks through floatable
-- ticks if it means that we can find more arguments.
collectArgsTicks :: (Tickish Id -> Bool) -> Expr b
-> (Expr b, [Arg b], [Tickish Id])
collectArgsTicks skipTick expr
= go expr [] []
where
go (App f a) as ts = go f (a:as) ts
go (Tick t e) as ts
| skipTick t = go e as (t:ts)
go e as ts = (e, as, reverse ts)
{-
************************************************************************
* *
\subsection{Predicates}
* *
************************************************************************
At one time we optionally carried type arguments through to runtime.
@isRuntimeVar v@ returns if (Lam v _) really becomes a lambda at runtime,
i.e. if type applications are actual lambdas because types are kept around
at runtime. Similarly isRuntimeArg.
-}
-- | Will this variable exist at runtime?
isRuntimeVar :: Var -> Bool
isRuntimeVar = isId
-- | Will this argument expression exist at runtime?
isRuntimeArg :: CoreExpr -> Bool
isRuntimeArg = isValArg
-- | Returns @True@ for value arguments, false for type args
-- NB: coercions are value arguments (zero width, to be sure,
-- like State#, but still value args).
isValArg :: Expr b -> Bool
isValArg e = not (isTypeArg e)
-- | Returns @True@ iff the expression is a 'Type' or 'Coercion'
-- expression at its top level
isTyCoArg :: Expr b -> Bool
isTyCoArg (Type {}) = True
isTyCoArg (Coercion {}) = True
isTyCoArg _ = False
-- | Returns @True@ iff the expression is a 'Type' expression at its
-- top level. Note this does NOT include 'Coercion's.
isTypeArg :: Expr b -> Bool
isTypeArg (Type {}) = True
isTypeArg _ = False
-- | The number of binders that bind values rather than types
valBndrCount :: [CoreBndr] -> Int
valBndrCount = count isId
-- | The number of argument expressions that are values rather than types at their top level
valArgCount :: [Arg b] -> Int
valArgCount = count isValArg
{-
************************************************************************
* *
\subsection{Annotated core}
* *
************************************************************************
-}
-- | Annotated core: allows annotation at every node in the tree
type AnnExpr bndr annot = (annot, AnnExpr' bndr annot)
-- | A clone of the 'Expr' type but allowing annotation at every tree node
data AnnExpr' bndr annot
= AnnVar Id
| AnnLit Literal
| AnnLam bndr (AnnExpr bndr annot)
| AnnApp (AnnExpr bndr annot) (AnnExpr bndr annot)
| AnnCase (AnnExpr bndr annot) bndr Type [AnnAlt bndr annot]
| AnnLet (AnnBind bndr annot) (AnnExpr bndr annot)
| AnnCast (AnnExpr bndr annot) (annot, Coercion)
-- Put an annotation on the (root of) the coercion
| AnnTick (Tickish Id) (AnnExpr bndr annot)
| AnnType Type
| AnnCoercion Coercion
-- | A clone of the 'Alt' type but allowing annotation at every tree node
type AnnAlt bndr annot = (AltCon, [bndr], AnnExpr bndr annot)
-- | A clone of the 'Bind' type but allowing annotation at every tree node
data AnnBind bndr annot
= AnnNonRec bndr (AnnExpr bndr annot)
| AnnRec [(bndr, AnnExpr bndr annot)]
-- | Takes a nested application expression and returns the the function
-- being applied and the arguments to which it is applied
collectAnnArgs :: AnnExpr b a -> (AnnExpr b a, [AnnExpr b a])
collectAnnArgs expr
= go expr []
where
go (_, AnnApp f a) as = go f (a:as)
go e as = (e, as)
collectAnnArgsTicks :: (Tickish Var -> Bool) -> AnnExpr b a
-> (AnnExpr b a, [AnnExpr b a], [Tickish Var])
collectAnnArgsTicks tickishOk expr
= go expr [] []
where
go (_, AnnApp f a) as ts = go f (a:as) ts
go (_, AnnTick t e) as ts | tickishOk t
= go e as (t:ts)
go e as ts = (e, as, reverse ts)
deAnnotate :: AnnExpr bndr annot -> Expr bndr
deAnnotate (_, e) = deAnnotate' e
deAnnotate' :: AnnExpr' bndr annot -> Expr bndr
deAnnotate' (AnnType t) = Type t
deAnnotate' (AnnCoercion co) = Coercion co
deAnnotate' (AnnVar v) = Var v
deAnnotate' (AnnLit lit) = Lit lit
deAnnotate' (AnnLam binder body) = Lam binder (deAnnotate body)
deAnnotate' (AnnApp fun arg) = App (deAnnotate fun) (deAnnotate arg)
deAnnotate' (AnnCast e (_,co)) = Cast (deAnnotate e) co
deAnnotate' (AnnTick tick body) = Tick tick (deAnnotate body)
deAnnotate' (AnnLet bind body)
= Let (deAnnBind bind) (deAnnotate body)
where
deAnnBind (AnnNonRec var rhs) = NonRec var (deAnnotate rhs)
deAnnBind (AnnRec pairs) = Rec [(v,deAnnotate rhs) | (v,rhs) <- pairs]
deAnnotate' (AnnCase scrut v t alts)
= Case (deAnnotate scrut) v t (map deAnnAlt alts)
deAnnAlt :: AnnAlt bndr annot -> Alt bndr
deAnnAlt (con,args,rhs) = (con,args,deAnnotate rhs)
-- | As 'collectBinders' but for 'AnnExpr' rather than 'Expr'
collectAnnBndrs :: AnnExpr bndr annot -> ([bndr], AnnExpr bndr annot)
collectAnnBndrs e
= collect [] e
where
collect bs (_, AnnLam b body) = collect (b:bs) body
collect bs body = (reverse bs, body)
| snoyberg/ghc | compiler/coreSyn/CoreSyn.hs | bsd-3-clause | 73,820 | 0 | 14 | 20,075 | 8,567 | 4,874 | 3,693 | 608 | 5 |
-- | Simple forward automatic differentiation. The main reason for supplying this
-- module rather than using one of several similar alternatives available on Hackage
-- is that they all seem to use the following implementation of differentiation of
-- products (in our notation):
--
-- x * y = mkDif (val x * val y) (df 1 x * y + x * df 1 y)
--
-- This is elegant but exponential in the order of differentiation, and hence
-- unsuitable for much of validated numerics, which often uses moderately high
-- order derivatives.
--
-- In our implementation, high order derivatives are still slow, but not as bad.
-- Derivatives of order several hundred can be handled, but in type 'Double' this is often
-- useless; rounding errors dominate the result. In type 'IReal', results are reliable, but the
-- deep nesting of the resulting expressions may lead to excessive precision requirements. Often
-- 'Data.Number.IReal.Rounded' is preferrable from an efficiency point of view.
--
-- No attempt is made to handle functions of several variables or perturbation confusion.
module Data.Number.IReal.FAD where
import Data.Number.IReal.Scalable
import Data.Number.IReal.Powers
-- | A 'Dif' value is an infinite list consisting of the values of an infinitely differentiable
-- function and all its derivatives, all evaluated at a common point. Polynomials are represented
-- by finite lists, omitting zero derivatives.
newtype Dif a = D [a] deriving Show
-- constructing Dif values -----------------------------------------------------
con, var :: Num a => a -> Dif a
con c = D [c]
var x = D [x,1]
mkDif :: a -> Dif a -> Dif a
mkDif x (D xs) = D (x:xs)
-- selectors ------------------------------------------------------------------
val :: Num a => Dif a -> a
val (D []) = 0
val (D (x:_)) = x
fromDif :: Num a => Dif a -> [a]
fromDif (D xs) = xs
unDif :: (Num a, Num b) => (Dif a -> Dif b) -> a -> b
unDif f = val . f . var
-- differentiation ------------------------------------------------------------
df :: Int -> Dif a -> Dif a
df n (D xs) = D (drop n xs)
-- | deriv n f is the n'th derivative of f (with derivative information omitted)
deriv :: (Num a, Num b) => Int -> (Dif a -> Dif b) -> a -> b
deriv n f = unDif (df n . f)
-- | derivs f a is the list of allderivatives of f, evaluated at a.
derivs :: (Num a, Num b) => (Dif a -> Dif b) -> a -> [b]
derivs f = fromDif . f . var
chain, rchain :: Num a => (a -> a) -> (Dif a -> Dif a) -> Dif a -> Dif a
chain f f' g = mkDif (f (val g)) (df 1 g * f' g)
rchain f f' g = r where r = mkDif (f (val g)) (df 1 g * f' r)
r2chain :: Num a => (a -> a) -> (a -> a) -> (Dif a -> Dif a) ->
(Dif a -> Dif a) -> Dif a -> Dif a
r2chain f1 f2 f1' f2' g = x
where g' = df 1 g
x = mkDif (f1 (val g)) (g' * f1' y)
y = mkDif (f2 (val g)) (g' * f2' x)
-- instances -------------------------------------------------------------------
instance VarPrec a => VarPrec (Dif a) where
precB b (D xs) = D (map (precB b) xs)
instance (Num a, Eq a) => Eq (Dif a) where
x==y = val x == val y
instance (Num a, Ord a) => Ord (Dif a) where
compare x y = compare (val x) (val y)
instance Num a => Num (Dif a) where
x + y = mkDif (val x + val y) (df 1 x + df 1 y)
x * y = D (convs (fromDif x) (fromDif y))
abs = chain abs signum -- wrong for argument 0
negate = chain negate (const (-1))
signum = chain signum (const 0) -- wrong for argument 0
fromInteger = con . fromInteger
instance (Fractional a, Powers a) => Fractional (Dif a) where
recip = rchain recip (negate . sq)
fromRational = con . fromRational
instance (Floating a, Powers a) => Floating (Dif a) where
pi = con pi
exp = rchain exp id
log = chain log recip
sqrt = rchain sqrt (recip . (*2))
sin = r2chain sin cos id negate
cos = r2chain cos sin negate id
tan = rchain tan ((1+) . sq)
asin = chain asin (recip . sqrt . (1-) . sq)
acos = chain acos (negate . recip . sqrt . (1-) . sq)
atan = chain atan (recip . (1+) . sq)
sinh = r2chain sinh cosh id id
cosh = r2chain cosh sinh id id
asinh = chain asinh (recip . sqrt . (1+) . sq)
acosh = chain acosh (recip . sqrt . (\x -> x-1) . sq)
atanh = chain atanh (recip . (1-) . sq)
instance (Num a, Powers a) => Powers (Dif a) where
pow x 0 = con 1
pow x n = chain (flip pow n) ((fromIntegral n *) . flip pow (n-1)) x
-- Note: This is linear in n, but behaves correctly on intervals
instance Real a => Real (Dif a) where
toRational = toRational . val
instance (Powers a, RealFrac a) => RealFrac (Dif a) where
-- discontinuities ignored
properFraction x = (i, x - fromIntegral i) where (i, _) = properFraction (val x)
truncate = truncate . val
round = round . val
ceiling = ceiling . val
floor = floor . val
instance ( Powers a, RealFloat a) => RealFloat (Dif a) where
floatRadix = floatRadix . val
floatDigits = floatDigits . val
floatRange = floatRange . val
exponent = exponent . val
scaleFloat n (D xs) = D (map (scaleFloat n) xs)
isNaN = isNaN . val
isInfinite = isInfinite . val
isDenormalized = isDenormalized . val
isNegativeZero = isNegativeZero . val
isIEEE = isIEEE . val
decodeFloat = decodeFloat . val
encodeFloat m e = con (encodeFloat m e)
-- convs xs ys = [ sum [xs!!j * ys!!(k-j)*bin k j | j <- [0..k]] | k <- [0..]]
-- adapted for efficiency and to handle finite lists xs, ys
convs [] _ = []
convs (a:as) bs = convs' [1] [a] as bs
where convs' _ _ _ [] = []
convs' ps ars as bs = sumProd3 ps ars bs :
case as of
[] -> convs'' (next' ps) ars bs
a:as -> convs' (next ps) (a:ars) as bs
convs'' ps ars [_] = []
convs'' ps ars (_:bs) = sumProd3 ps ars bs : convs'' (next' ps) ars bs
next xs = 1 : zipWith (+) xs (tail xs) ++ [1] -- next row in Pascal's triangle
next' xs = zipWith (+) xs (tail xs) ++ [1] -- end part of next row in Pascal's triangle
sumProd3 as bs cs = sum (zipWith3 (\x y z -> x*y*z) as bs cs) | sydow/ireal | Data/Number/IReal/FAD.hs | bsd-3-clause | 6,211 | 0 | 13 | 1,651 | 2,238 | 1,163 | 1,075 | 99 | 4 |
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
{-# LANGUAGE TemplateHaskell #-}
module Grover.Tests where
import Ernie
import Multiarg.Examples.Grover
import Control.Applicative
import Test.QuickCheck hiding (Result)
import Multiarg.Mode
import Test.Tasty
import Test.Tasty.TH
import Test.Tasty.QuickCheck
tests :: TestTree
tests = $(testGroupGenerator)
genGlobal :: Gen Global
genGlobal = oneof
[ return Help
, Verbose <$> arbitrary
, return Version
]
data GroverOpts
= GOInts [GroverOpt Int]
| GOStrings [GroverOpt String]
| GOMaybes [GroverOpt (Maybe Int)]
deriving (Eq, Ord, Show)
instance Arbitrary GroverOpts where
arbitrary = oneof
[ fmap GOInts . listOf . genGroverOpt $ arbitrary
, fmap GOStrings . listOf . genGroverOpt $ arbitrary
, fmap GOMaybes . listOf . genGroverOpt $ arbitrary
]
-- | Generates a mode option. Does not generate positional arguments.
genGroverOpt
:: Gen a
-- ^ Generates arguments
-> Gen (GroverOpt a)
genGroverOpt g = oneof
[ return Zero
, Single <$> g
, Double <$> g <*> g
, Triple <$> g <*> g <*> g
]
globalToNestedList :: Global -> [[String]]
globalToNestedList glbl = case glbl of
Help -> long "help" [] ++ short 'h' []
Verbose i -> long "verbose" [show i] ++ short 'v' [show i]
Version -> long "version" []
groverOptToNestedList :: Show a => GroverOpt a -> [[String]]
groverOptToNestedList gvr = case gvr of
Zero -> long "zero" [] ++ short 'z' []
Single a -> long "single" ls ++ short 's' ls
where
ls = [show a]
Double a b -> long "double" ls ++ short 'd' ls
where
ls = [show a, show b]
Triple a b c -> long "triple" ls ++ short 't' ls
where
ls = [show a, show b, show c]
PosArg s -> [[s]]
-- | A valid Grover AST, combined with a set of strings that, when
-- parsed, should yield that AST.
data ValidGrover
= ValidGrover [Global] (Either [String] Result) [String]
-- ^ @ValidGrover a b c@, where
--
-- @a@ is the list of global options
--
-- @b@ is either a list of strings (indicates that the user entered
-- no mode), or the mode, and its associated options
--
-- @c@ is a list of strings that, when parsed, should return @a@ and @b@.
deriving (Eq, Ord, Show)
instance Arbitrary ValidGrover where
arbitrary = do
globals <- listOf genGlobal
glblStrings <- fmap concat . mapM pickItem
. map globalToNestedList $ globals
(ei, endStrings) <- oneof
[ resultAndStrings Ints "int"
, resultAndStrings Strings "string"
, resultAndStrings Maybes "maybe"
]
return $ ValidGrover globals ei (glblStrings ++ endStrings)
-- | Generates a list of String, where the first String will not be
-- interpreted as a mode.
genNonModePosArg :: Gen [String]
genNonModePosArg = frequency ([ (1, return []), (3, nonEmpty)])
where
nonEmpty = (:) <$> firstWord <*> listOf arbitrary
where
firstWord = arbitrary `suchThat`
(\s -> not (s `elem` ["int", "string", "maybe"])
&& not (startsWithHyphen s))
startsWithHyphen s = case s of
'-':_ -> True
_ -> False
resultAndStrings
:: (Arbitrary a, Show a)
=> ([Either String (GroverOpt a)] -> Result)
-- ^ Function that creates a Result
-> String
-- ^ Name of mode
-> Gen (Either [String] Result, [String])
resultAndStrings fRes modeName = frequency [(1, nonMode), (4, withMode)]
where
nonMode = fmap (\ls -> (Left ls, ls)) genNonModePosArg
withMode = do
ispLine <- interspersedLine (genGroverOpt arbitrary) PosArg
strings <- interspersedLineToStrings ispLine groverOptToNestedList
return ( Right . fRes . map Right $ fst ispLine ++ snd ispLine
, modeName : strings )
prop_ValidGrover (ValidGrover globals ei strings) = result === expected
where
result = parseModeLine globalOptSpecs modes strings
expected = Right (ModeResult (map Right globals) ei)
prop_alwaysTrue = True
| massysett/multiarg | tests/Grover/Tests.hs | bsd-3-clause | 3,952 | 0 | 16 | 917 | 1,201 | 629 | 572 | 89 | 5 |
module Exercises106 where
import Data.Time
import Data.List
data DatabaseItem = DbString String
| DbNumber Integer
| DbDate UTCTime
deriving (Eq, Ord, Show)
theDatabase :: [DatabaseItem]
theDatabase =
[ DbDate (UTCTime
(fromGregorian 1911 5 1)
(secondsToDiffTime 34123))
, DbNumber 9001
, DbString "Hello, world!"
, DbDate (UTCTime
(fromGregorian 1921 5 1)
(secondsToDiffTime 34123))
, DbNumber 8005
]
-- 1.
filterDbDate :: [DatabaseItem] -> [UTCTime]
filterDbDate = foldr f []
where f (DbDate x) xs = x : xs
f _ xs = xs
-- 2.
filterDbNumber :: [DatabaseItem] -> [Integer]
filterDbNumber = foldr f []
where f (DbNumber x) xs = x : xs
f _ xs = xs
-- 3.
mostRecent :: [DatabaseItem] -> UTCTime
mostRecent = maximum . filterDbDate
-- 4.
sumDb :: [DatabaseItem] -> Integer
sumDb = sum . filterDbNumber
-- 5.
avgDb :: [DatabaseItem] -> Double
avgDb = average . filterDbNumber
average :: (Real a, Fractional b) => [a] -> b
average [] = 0.0
average xs = realToFrac (sum xs) / genericLength xs
| pdmurray/haskell-book-ex | src/ch10/Exercises10.6.hs | bsd-3-clause | 1,139 | 0 | 10 | 320 | 386 | 209 | 177 | 35 | 2 |
{-# LANGUAGE OverloadedStrings, TypeFamilies #-}
module QueryArrow.RPC.Service.Service.Common where
import QueryArrow.DB.DB
import Data.Time
import QueryArrow.Serialization
import System.Log.Logger
import QueryArrow.Control.Monad.Logger.HSLogger ()
import QueryArrow.RPC.Message
import Control.Monad.Trans.Except
import QueryArrow.RPC.DB
import System.IO (Handle)
import QueryArrow.Syntax.Type
import QueryArrow.Semantics.TypeChecker
import QueryArrow.FFI.Auxiliary
worker :: (IDatabase db, DBFormulaType db ~ FormulaT, RowType (StatementType (ConnectionType db)) ~ MapResultRow) => Handle -> db -> ConnectionType db -> IO ()
worker handle tdb conn = do
t0 <- getCurrentTime
req <- receiveMsgPack handle
infoM "RPC_TCP_SERVER" ("received message " ++ show req)
(t2, t3, b) <- case req of
Nothing -> do
sendMsgPack handle (errorSet (-1, "cannot parser request"))
t2 <- getCurrentTime
t3 <- getCurrentTime
return (t2, t3, False)
Just qs -> do
let qu = qsquery qs
hdr = qsheaders qs
par = qsparams qs
case qu of
Quit -> do -- disconnect when qu field is null
t2 <- getCurrentTime
t3 <- getCurrentTime
return (t2, t3, True)
Static qu -> do
t2 <- getCurrentTime
ret <- runExceptT (run3 hdr qu par tdb conn)
t3 <- getCurrentTime
case ret of
Left e ->
sendMsgPack handle (errorSet (convertException e))
Right rep ->
sendMsgPack handle (resultSet rep)
return (t2, t3, False)
Dynamic qu -> do
t2 <- getCurrentTime
infoM "RPC_TCP_SERVER" "**************"
ret <- runExceptT (run hdr qu par tdb conn)
infoM "RPC_TCP_SERVER" "**************"
t3 <- getCurrentTime
case ret of
Left e -> do
infoM "RPC_TCP_SERVER" "**************1"
sendMsgPack handle (errorSet (convertException e))
infoM "RPC_TCP_SERVER" "**************2"
Right rep -> do
infoM "RPC_TCP_SERVER" "**************3"
sendMsgPack handle (resultSet rep)
infoM "RPC_TCP_SERVER" "**************4"
return (t2, t3, False)
t1 <- getCurrentTime
infoM "RPC_TCP_SERVER" (show (diffUTCTime t1 t0) ++ "\npre: " ++ show (diffUTCTime t2 t0) ++ "\nquery: " ++ show (diffUTCTime t3 t2) ++ "\npost: " ++ show (diffUTCTime t1 t3))
if b
then return ()
else worker handle tdb conn
| xu-hao/QueryArrow | QueryArrow-rpc-socket/src/QueryArrow/RPC/Service/Service/Common.hs | bsd-3-clause | 3,532 | 5 | 22 | 1,714 | 740 | 367 | 373 | 65 | 7 |
{-# LANGUAGE OverloadedStrings #-}
-- |
-- Module : BlazeVsBinary
-- Copyright : (c) 2010 Jasper Van der Jeught & Simon Meier
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Simon Meier <[email protected]>
-- Stability : experimental
-- Portability : tested on GHC only
--
-- A comparison between 'blaze-builder' and the Data.Binary.Builder from
-- 'binary'. The goal is to measure the performance on serializing dynamic
-- data referenced by a list.
--
-- Note that some of the benchmarks are a bit unfair with respect to
-- blaze-builder, as it does more than 'binary':
--
-- 1. It encodes chars as utf-8 strings and does not just truncate character
-- value to one byte.
--
-- 2. It copies the contents of the lazy bytestring chunks if they are
-- shorter than 4kb. This ensures efficient processing of the resulting
-- lazy bytestring. 'binary' just inserts the chunks directly in the
-- resulting output stream.
--
module BlazeVsBinary where
import Data.Char (ord)
import Data.Monoid (mconcat)
import Data.Word (Word8)
import qualified Data.Binary.Builder as Binary
import Criterion.Main
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString as S
import Data.Text (Text)
import Data.Text.Encoding (encodeUtf8)
import qualified Blaze.ByteString.Builder as Blaze
import qualified Blaze.ByteString.Builder.Char.Utf8 as Blaze
main :: IO ()
main = defaultMain $ concat
[ benchmark "[String]"
(mconcat . map (mconcat . (map $ Binary.singleton . fromIntegral . ord)))
(mconcat . map Blaze.fromString)
strings
, benchmark "L.ByteString"
(Binary.fromLazyByteString)
(Blaze.fromLazyByteString)
byteStrings
, benchmark "[Text]"
(mconcat . map (Binary.fromByteString . encodeUtf8))
(mconcat . map Blaze.fromText)
texts
, benchmark "[Word8]"
(mconcat . map Binary.singleton)
(Blaze.fromWord8s)
word8s
]
where
benchmark name binaryF blazeF x =
[ bench (name ++ " (Data.Binary builder)") $
whnf (L.length . Binary.toLazyByteString . binaryF) x
, bench (name ++ " (blaze builder)") $
whnf (L.length . Blaze.toLazyByteString . blazeF) x
]
strings :: [String]
strings = replicate 10000 "<img>"
{-# NOINLINE strings #-}
byteStrings :: L.ByteString
byteStrings = L.fromChunks $ replicate 10000 "<img>"
{-# NOINLINE byteStrings #-}
texts :: [Text]
texts = replicate 10000 "<img>"
{-# NOINLINE texts #-}
word8s :: [Word8]
word8s = replicate 10000 $ fromIntegral $ ord 'a'
{-# NOINLINE word8s #-}
| meiersi/blaze-builder | benchmarks/BlazeVsBinary.hs | bsd-3-clause | 2,639 | 0 | 18 | 583 | 485 | 284 | 201 | 48 | 1 |
module Keyboard
( requestFromKey
) where
import Model (Request (..))
requestFromKey :: Char -> Maybe Request
requestFromKey 'h' = Just MoveLeft
requestFromKey 'j' = Just MoveDown
requestFromKey 'k' = Just MoveUp
requestFromKey 'l' = Just MoveRight
requestFromKey _ = Nothing
| camelpunch/rhascal | src/Keyboard.hs | bsd-3-clause | 297 | 0 | 6 | 62 | 85 | 44 | 41 | 9 | 1 |
module Process.DownloadProcess where
import Control.Concurrent
import Data.List
import qualified Data.Set as Set
import Graphics.GD
import Network.Curl
import System.Directory
import System.FilePath
import System.IO.Unsafe
import Text.HTML.TagSoup
import Text.HTML.TagSoup.Match
import Settings.Settings
import qualified Utils.Url as URL
-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-- HTML
-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
getContenidoURL :: String -> IO (String, String)
getContenidoURL url
= do (CurlResponse cCode _ _ _ content fvalue) <- getResponse url
putStrLn $ show cCode ++ " at " ++ url
(IString eurl) <- fvalue EffectiveUrl
if cCode == CurlOK
then do let base = URL.getBaseUrl eurl
forkIO (downloadImages base content)
forkIO (downloadHTMLStyleSheet base content)
forkIO (downloadXMLStyleSheet base content)
return (eurl,content)
else return $ (url,pageNoDisponible (show cCode) url)
getResponse :: String -> IO (CurlResponse_ [(String, String)] String)
getResponse url = curlGetResponse_ url [CurlFollowLocation True, CurlUserAgent "3SWebBrowser"]
pageNoDisponible :: String -> String -> String
pageNoDisponible error link
= "<html>\
\<head> <style> span {text-decoration: underline}</style></head>\
\<body>\
\<h1> This webpage is not available.</h1>\
\<p> Error returned: " ++ error ++ " </p>\
\<p> The webpage at <span>" ++ link ++ "</span> might be temporarily down or it may have moved permanently to a new web address. </p>\
\</body>\
\</html>"
-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-- stylesheet
-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
downloadXMLStyleSheet base stringHTML
= do let html = parseTags stringHTML
xmlTags = map (fromAttrib "href") $ filter (tagOpen (=="?xml-stylesheet") funAttrs) html
xmlHref = Set.toList $ Set.fromList xmlTags -- elimina los repetidos
funName = map getUrlFileName xmlHref
mapM_ downloadprocess funName
where funAttrs attrs = let pr1 = (=="href")
pr2 = [(\(n,v) -> n == "type" && v == "text/css")]
href = any (pr1 . fst) attrs
others = and $ map (\f -> any f attrs) pr2
in href && others
downloadprocess (url,name)
= do css <- download base url
tmpDir <- retrieveTempDir
let path = tmpDir </> name
writeFile path css
putStrLn $ "File saved at " ++ path
return ()
downloadHTMLStyleSheet base stringHTML
= do let html = parseTags stringHTML
linkTags = map (fromAttrib "href") $ filter (tagOpen (=="link") funAttrs) html
linkHref = Set.toList $ Set.fromList linkTags -- elimina los repetidos
funName = map getUrlFileName linkHref
mapM_ downloadprocess funName
where funAttrs attrs = let pr1 = (=="href")
pr2 = [ (\(n,v) -> n == "rel" && v == "stylesheet")
, (\(n,v) -> n == "type" && v == "text/css")
]
href = any (pr1 . fst) attrs
others = and $ map (\f -> any f attrs) pr2
in href && others
downloadprocess (url,name)
= do css <- download base url
tmpDir <- retrieveTempDir
let path = tmpDir </> name
writeFile path css
putStrLn $ "File saved at " ++ path
return ()
getUrlFileName url
= let name = takeFileName url
in case takeExtension url of
".css" -> (url, name)
otherwise -> error $ "[DownloadProcess] error with bad extension file, at: " ++ url
download base url
= do let url' = if URL.isAbsolute url
then url
else if URL.isHostRelative url
then base ++ url
else base ++ "/" ++ url
(cod,obj) <- curlGetString_ url' []
putStrLn $ show cod ++ " at " ++ url'
return obj
{-
La verificacion de si existe o no el archivo lo dejo al parser.
-}
getStylePath :: String -> String
getStylePath url = let name = takeFileName url
tmpDir = unsafePerformIO (retrieveTempDir)
path = tmpDir </> name
in path
-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-- images
-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
downloadImages base stringHTML
= do let imgTags = [ fromAttrib "src" tag
| tag <- parseTags stringHTML
, tagOpen (=="img") (anyAttrName (== "src")) tag
]
imgSRCs = nub imgTags -- elimina los repetidos
--html = parseTags stringHTML
--imgTags = map (fromAttrib "src") $ filter (tagOpen (=="img") (anyAttrName (=="src"))) html
--imgSRCs = Set.toList $ Set.fromList imgTags -- elimina los repetidos
imgfuns = map getImageFunctionNameType imgSRCs
mapM_ downloadprocess imgfuns
where downloadprocess (url,name,fload,fsave)
= do img <- download base url
gdimg <- fload img
tmpDir <- retrieveTempDir
let path = tmpDir </> name
fsave path gdimg
putStrLn $ "image saved at " ++ path
downloadImage url = unsafePerformIO $ downloadImage' url
where downloadImage' url = do let (_, name,fload,fsave) = getImageFunctionNameType url
(cod,img) <- curlGetString_ url []
putStrLn $ show cod ++ " at " ++ url
gdimg <- fload img
(w,h) <- imageSize gdimg
tmpDir <- retrieveTempDir
let path = tmpDir </> name
fsave path gdimg
putStrLn $ "image saved at " ++ path
return (w,h)
getImageWidth url = let (w,_) = getImageSize url
in w
getImageHeight url = let (_,h) = getImageSize url
in h
getImageSize url = unsafePerformIO $ getImageSize' url
where getImageSize' url = do let (name,fload) = getSimpleFunctionNameType url
tmpDir <- retrieveTempDir
let path = tmpDir </> name
bool <- doesFileExist path
if bool
then do gdimg <- fload path
(w,h) <- imageSize gdimg
return (w,h)
else return (50,50) -- default (width, height), usually because the dowloading process of images is not completed
getSimpleFunctionNameType url = let name = takeFileName url
in case takeExtension url of
".jpg" -> (name, loadJpegFile)
".png" -> (name, loadPngFile )
".gif" -> (name, loadGifFile )
otherwise -> error $ "[ImageProcess] error with unsuported image, at: " ++ url
getImageFunctionNameType url
= let name = takeFileName url
in case takeExtension url of
".jpg" -> (url, name, loadJpegByteString, saveJpegFile (-1))
".png" -> (url, name, loadPngByteString , savePngFile)
".gif" -> (url, name, loadGifByteString , saveGifFile)
otherwise -> error $ "[DownloadProcess] error with unsuported image, at: " ++ url
getImagePath :: String -> IO String
getImagePath url = do let name = takeFileName url
tmpDir <- retrieveTempDir
let path = tmpDir </> name
bool <- doesFileExist path
if bool
then return path
else return $ tmpDir </> "default.jpg"
| carliros/Simple-San-Simon-Functional-Web-Browser | src/Process/DownloadProcess.hs | bsd-3-clause | 8,639 | 2 | 16 | 3,543 | 1,951 | 983 | 968 | 148 | 4 |
-- | An umbrella module for views concerning users and authorisation.
module Guide.Views.Auth
(
module Guide.Views.Auth.Login,
module Guide.Views.Auth.Register,
)
where
import Guide.Views.Auth.Login
import Guide.Views.Auth.Register
| aelve/guide | back/src/Guide/Views/Auth.hs | bsd-3-clause | 237 | 0 | 5 | 29 | 41 | 30 | 11 | 6 | 0 |
module OuterInner where
import Control.Monad.Trans.Except
import Control.Monad.Trans.Maybe
import Control.Monad.Trans.Reader
embedded :: MaybeT (ExceptT String (ReaderT () IO)) Int
embedded = return 1
maybeUnwrap :: ExceptT String (ReaderT () IO) (Maybe Int)
maybeUnwrap = runMaybeT embedded
eitherUnwrap :: ReaderT () IO (Either String (Maybe Int))
eitherUnwrap = runExceptT maybeUnwrap
readerUnwrap :: () -> IO (Either String (Maybe Int))
readerUnwrap = runReaderT eitherUnwrap
out = readerUnwrap ()
readerRewrapped :: ReaderT () IO (Either String (Maybe Int))
readerRewrapped = ReaderT readerUnwrap
eitherRewrapped :: ExceptT String (ReaderT () IO) (Maybe Int)
eitherRewrapped = ExceptT readerRewrapped
embedded' :: MaybeT (ExceptT String (ReaderT () IO)) Int
embedded' = MaybeT eitherRewrapped
| peterbecich/haskell-programming-first-principles | src/OuterInner.hs | bsd-3-clause | 807 | 0 | 10 | 113 | 287 | 149 | 138 | 19 | 1 |
{-# LANGUAGE ScopedTypeVariables, RecordWildCards, OverloadedStrings, CPP, PatternGuards #-}
module General.Web(
Input(..), Output(..), readInput, server, downloadFile
) where
-- #define PROFILE
-- For some reason, profiling stops working if I import warp
-- Tracked as https://github.com/yesodweb/wai/issues/311
#ifndef PROFILE
import Network.Wai.Handler.Warp hiding (Port, Handle)
#endif
import Network.Wai.Logger
import Network.Wai
import Control.DeepSeq
import System.IO
import Network.HTTP.Types.Status
import qualified Data.Text as Text
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as LBS
import Data.Conduit.Binary (sinkFile)
import qualified Network.HTTP.Conduit as C
import qualified Data.Conduit as C
import Control.Concurrent.Extra
import Network
import Data.List.Extra
import Data.Tuple.Extra
import Data.Monoid
import Data.Time.Clock
import System.FilePath
import Control.Exception.Extra
import System.Time.Extra
import General.Util
data Input = Input
{inputURL :: [String]
,inputArgs :: [(String, String)]
,inputBody :: String
} deriving Show
readInput :: String -> Input
readInput x = Input (dropWhile null $ splitOn "/" a) (map (second drop1 . breakOn "=") $ splitOn "&" $ drop1 b) ""
where (a,b) = breakOn "?" x
data Output
= OutputString String
| OutputHTML String
| OutputFile FilePath
deriving Show
instance NFData Output where
rnf (OutputString x) = rnf x
rnf (OutputHTML x) = rnf x
rnf (OutputFile x) = rnf x
downloadFile :: FilePath -> String -> IO ()
downloadFile file url = withSocketsDo $ do
request <- C.parseUrl url
C.withManager $ \manager -> do
response <- C.http request manager
C.responseBody response C.$$+- sinkFile file
showTime :: UTCTime -> String
showTime = showUTCTime "%Y-%m-%dT%H:%M:%S%Q"
server :: Handle -> Int -> (Input -> IO Output) -> IO ()
#ifdef PROFILE
server hlog port act = return ()
#else
server hlog port act = do
lock <- newLock
now <- getCurrentTime
hPutStrLn hlog $ "\n" ++ showTime now ++ " - Server started on port " ++ show port
hFlush hlog
runSettings (setOnException exception $ setPort port defaultSettings) $ \req reply -> do
bod <- strictRequestBody req
let pay = Input
(map Text.unpack $ pathInfo req)
[(BS.unpack a, maybe "" BS.unpack b) | (a,b) <- queryString req]
(LBS.unpack bod)
(time,res) <- duration $ try_ $ do s <- act pay; evaluate $ rnf s; return s
res <- either (fmap Left . showException) (return . Right) res
now <- getCurrentTime
withLock lock $ hPutStrLn hlog $ unwords $
[showTime now
,showSockAddr $ remoteHost req
,show $ ceiling $ time * 1000
,BS.unpack $ rawPathInfo req <> rawQueryString req] ++
["ERROR: " ++ s | Left s <- [res]]
case res of
Left s -> reply $ responseLBS status500 [] $ LBS.pack s
Right v -> reply $ case v of
OutputFile file -> responseFile status200
[("content-type",c) | Just c <- [lookup (takeExtension file) contentType]] file Nothing
OutputString msg -> responseLBS status200 [] $ LBS.pack msg
OutputHTML msg -> responseLBS status200 [("content-type","text/html")] $ LBS.pack msg
contentType = [(".html","text/html"),(".css","text/css"),(".js","text/javascript")]
exception :: Maybe Request -> SomeException -> IO ()
exception r e
| Just (_ :: InvalidRequest) <- fromException e = return ()
| otherwise = putStrLn $ "Error when processing " ++ maybe "Nothing" (show . rawPathInfo) r ++
"\n " ++ show e
#endif
| ndmitchell/hogle-dead | src/General/Web.hs | bsd-3-clause | 3,779 | 0 | 14 | 912 | 562 | 321 | 241 | 84 | 4 |
import Allegro
import Allegro.Display
import Allegro.EventQueue
import Allegro.Font
import Allegro.Keyboard
import Allegro.Graphics
red :: Color
red = Color 1 0 0 0
main :: IO ()
main =
allegro $
do f <- loadFont "../resources/font.ttf" 12 defaultFontFlags
putStr $ unlines [ "lineHeight = " ++ show (fontLineHeight f)
, "ascent = " ++ show (fontAscent f)
, "descent = " ++ show (fontDescent f)
]
withDisplay FixedWindow 640 480 $ \d ->
do setWindowTitle d "Hello"
q <- createEventQueue
registerEventSource q =<< installKeyboard
let go n =
do ev <- waitForEvent q
drawText f red (fromIntegral (div n 20 * 2 * textWidth f "m"))
(fromIntegral $ mod n 20 * fontLineHeight f)
AlignLeft $ show $ evType ev
flipDisplay
print $ evType ev
case ev of
KeyDown k | evKey k == key_ESCAPE -> return ()
_ -> go (n + 1)
go 0
| yav/allegro | examples/hs/font.hs | bsd-3-clause | 1,143 | 2 | 24 | 478 | 360 | 163 | 197 | 30 | 2 |
module Juno.Monitoring.EkgJson
(
encodeAll
, encodeOne
) where
import qualified Data.Aeson.Encode as A
import qualified Data.ByteString.Lazy as L
import System.Metrics
import qualified System.Metrics.Json as Json
-- | Encode metrics as nested JSON objects. See 'Json.sampleToJson'
-- for a description of the encoding.
encodeAll :: Sample -> L.ByteString
encodeAll = A.encode . Json.sampleToJson
-- | Encode metric a JSON object. See 'Json.valueToJson'
-- for a description of the encoding.
encodeOne :: Value -> L.ByteString
encodeOne = A.encode . Json.valueToJson
| buckie/juno | src/Juno/Monitoring/EkgJson.hs | bsd-3-clause | 588 | 0 | 6 | 100 | 99 | 64 | 35 | 12 | 1 |
module Main where
main
= do { putStrLn "Hello World"
; putStrLn "Yes?"
; input <- getLine
; case input of
"a" -> putStrLn "A"
"b" -> putStrLn "B"
_ -> putStrLn "Other"
; putStrLn "Done"
}
| dterei/Scraps | haskell/myIndent.hs | bsd-3-clause | 207 | 6 | 10 | 56 | 80 | 39 | 41 | 10 | 3 |
#!/usr/bin/env stack
{- stack runghc --verbosity info
--package pandoc
-}
-- Replace a table of contents marker
-- (a bullet list item containing "toc[-N[-M]]")
-- with a table of contents based on headings.
-- toc means full contents, toc-N means contents to depth N
-- and toc-N-M means contents from depth N to depth M.
-- Based on code from https://github.com/blaenk/blaenk.github.io
{-# LANGUAGE OverloadedStrings #-}
import Data.Char (isDigit)
import Data.List (groupBy)
import Data.List.Split
import Data.Tree (Forest, Tree(Node))
import Data.Monoid ((<>), mconcat)
import Data.Function (on)
import Data.Maybe (fromMaybe)
import Safe
import Text.Blaze.Html (preEscapedToHtml, (!))
import Text.Blaze.Html.Renderer.String (renderHtml)
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
import Text.Pandoc
import Text.Pandoc.JSON
import Text.Pandoc.Walk (walk, query)
main :: IO ()
main = toJSONFilter tableOfContents
tableOfContents :: Pandoc -> Pandoc
tableOfContents doc =
let headers = query collectHeaders doc
in walk (generateTOC headers) doc
collectHeaders :: Block -> [Block]
collectHeaders header@(Header _ (_, classes, _) _)
| "notoc" `elem` classes = []
| otherwise = [header]
collectHeaders _ = []
generateTOC :: [Block] -> Block -> Block
generateTOC [] x = x
generateTOC headers x@(BulletList (( (( Plain ((Str txt):_)):_)):_)) =
case tocParams txt of
Just (mstartlevel, mendlevel) ->
render .
forestDrop mstartlevel .
forestPrune mendlevel .
groupByHierarchy $
headers -- (! A.class_ "right-toc") .
where
render = (RawBlock "html") . renderHtml . createTable
Nothing -> x
generateTOC _ x = x
tocParams :: String -> Maybe (Maybe Int, Maybe Int)
tocParams s =
case splitOn "-" s of
["toc"] -> Just (Nothing, Nothing)
["toc",a] | all isDigit a -> Just (Nothing, readMay a)
["toc",a,b] | all isDigit a, all isDigit b -> Just (readMay a, readMay b)
_ -> Nothing
forestDrop :: Maybe Int -> Forest a -> Forest a
forestDrop Nothing f = f
forestDrop (Just n) ts = concatMap (treeDrop n) ts
treeDrop :: Int -> Tree a -> Forest a
treeDrop n t | n < 1 = [t]
treeDrop n (Node _ ts) = concatMap (treeDrop (n-1)) ts
forestPrune :: Maybe Int -> Forest a -> Forest a
forestPrune Nothing f = f
forestPrune (Just n) ts = map (treePrune n) ts
treePrune :: Int -> Tree a -> Tree a
treePrune n t | n < 1 = t
treePrune n (Node v ts) = Node v $ map (treePrune (n-1)) ts
-- | remove all nodes past a certain depth
-- treeprune :: Int -> Tree a -> Tree a
-- treeprune 0 t = Node (root t) []
-- treeprune d t = Node (root t) (map (treeprune $ d-1) $ branches t)
groupByHierarchy :: [Block] -> Forest Block
groupByHierarchy = map (\(x:xs) -> Node x (groupByHierarchy xs)) . groupBy ((<) `on` headerLevel)
headerLevel :: Block -> Int
headerLevel (Header level _ _) = level
headerLevel _ = error "not a header"
createTable :: Forest Block -> H.Html
createTable headers =
(H.nav ! A.id "toc") $ do
H.p "Contents"
H.ol $ markupHeaders headers
markupHeader :: Tree Block -> H.Html
markupHeader (Node (Header _ (ident, _, keyvals) inline) headers)
| headers == [] = H.li $ link
| otherwise = H.li $ link <> (H.ol $ markupHeaders headers)
where render x = writeHtmlString def (Pandoc nullMeta [(Plain x)])
section = fromMaybe (render inline) (lookup "toc" keyvals)
link = H.a ! A.href (H.toValue $ "#" ++ ident) $ preEscapedToHtml section
markupHeader _ = error "what"
markupHeaders :: Forest Block -> H.Html
markupHeaders = mconcat . map markupHeader
-- ignoreTOC :: Block -> Block
-- ignoreTOC (Header level (ident, classes, params) inline) =
-- Header level (ident, "notoc" : classes, params) inline
-- ignoreTOC x = x
-- removeTOCMarker :: Block -> Block
-- removeTOCMarker (BulletList (( (( Plain ((Str "toc"):_)):_)):_)) = Null
-- removeTOCMarker x = x
| mstksg/hledger | tools/pandoc-add-toc.hs | gpl-3.0 | 4,010 | 5 | 19 | 850 | 1,365 | 697 | 668 | 79 | 4 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- -*-haskell-*-
-- GIMP Toolkit (GTK) Interface CellLayout
--
-- Author : Axel Simon
--
-- Created: 23 January 2006
--
-- Copyright (C) 2016-2016 Axel Simon, Hamish Mackenzie
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- |
-- Stability : provisional
-- Portability : portable (depends on GHC)
--
-- An interface for packing cells
--
-- * Module available since Gtk+ version 2.4
--
module Data.GI.Gtk.ModelView.CellLayout (
-- * Detail
--
-- | 'CellLayout' is an interface which is implemented by all objects which
-- provide a 'TreeViewColumn' API for packing cells, setting attributes and data funcs.
-- * Class Hierarchy
-- |
-- @
-- | Interface CellLayout
-- | +----'TreeViewColumn'
-- | +----'CellView'
-- | +----'IconView'
-- | +----'EntryCompletion'
-- | +----'ComboBox'
-- | +----'ComboBoxEntry'
-- @
module GI.Gtk.Interfaces.CellLayout
-- , cellLayoutAddColumnAttribute
, cellLayoutSetAttributes
, cellLayoutSetDataFunction
, cellLayoutSetDataFunc'
, convertIterFromParentToChildModel
) where
import Control.Monad.IO.Class (MonadIO(..))
import Foreign.Ptr (castPtr)
import Foreign.Storable (peek)
import Data.GI.Base.Attributes (AttrOp, AttrOpTag(..), set)
import Data.GI.Base.ManagedPtr (castTo, withManagedPtr)
import GI.Gtk.Interfaces.CellLayout
import GI.Gtk.Objects.TreeModelFilter (TreeModelFilter(..), getTreeModelFilterChildModel, treeModelFilterConvertIterToChildIter)
import GI.Gtk.Objects.TreeModelSort (TreeModelSort(..), getTreeModelSortModel, treeModelSortConvertIterToChildIter)
import GI.Gtk.Structs.TreeIter
(getTreeIterStamp, getTreeIterUserData3, getTreeIterUserData2,
getTreeIterUserData, TreeIter(..))
import GI.Gtk.Objects.CellRenderer (IsCellRenderer, CellRenderer(..), toCellRenderer)
import Data.GI.Gtk.ModelView.Types
import Data.GI.Gtk.ModelView.TreeModel
import Data.GI.Gtk.ModelView.CustomStore (customStoreGetRow)
import Data.GI.Base (get)
import Data.GI.Base.BasicTypes (ManagedPtr(..))
--------------------
-- Methods
-- | Adds an attribute mapping to the renderer @cell@. The @column@ is
-- the 'ColumnId' of the model to get a value from, and the @attribute@ is the
-- parameter on @cell@ to be set from the value. So for example if column 2 of
-- the model contains strings, you could have the \"text\" attribute of a
-- 'CellRendererText' get its values from column 2.
--
-- cellLayoutAddColumnAttribute :: (MonadIO m, IsCellLayout self, IsCellRenderer cell) => self
-- -> cell -- ^ @cell@ - A 'CellRenderer'.
-- -> ReadWriteAttr cell a v -- ^ @attribute@ - An attribute of a renderer.
-- -> ColumnId row v -- ^ @column@ - The virtual column of the model from which to
-- -- retrieve the attribute.
-- -> m ()
-- cellLayoutAddColumnAttribute self cell attr column =
-- cellLayoutAddAttribute self cell (T.pack $ show attr) (columnIdToNumber column)
-- | Specify how a row of the @model@ defines the
-- attributes of the 'CellRenderer' @cell@. This is a convenience wrapper
-- around 'cellLayoutSetAttributeFunc' in that it sets the cells of the @cell@
-- with the data retrieved from the model.
--
-- * Note on using 'Data.GI.Gtk.ModelView.TreeModelSort.TreeModelSort' and
-- 'Data.GI.Gtk.ModelView.TreeModelFilter.TreeModelFilter': These two models
-- wrap another model, the so-called child model, instead of storing their own
-- data. This raises the problem that the data of cell renderers must be set
-- using the child model, while the 'TreeIter's that the view works with refer to
-- the model that encapsulates the child model. For convenience, this function
-- transparently translates an iterator to the child model before extracting the
-- data using e.g. 'Data.GI.Gtk.TreeModel.TreeModelSort.treeModelSortConvertIterToChildIter'.
-- Hence, it is possible to install the encapsulating model in the view and to
-- pass the child model to this function.
--
cellLayoutSetAttributes :: (MonadIO m,
IsCellLayout self,
IsCellRenderer cell,
IsTreeModel (model row),
IsTypedTreeModel model)
=> self
-> cell -- ^ @cell@ - A 'CellRenderer'.
-> model row -- ^ @model@ - A model containing rows of type @row@.
-> (row -> [AttrOp cell 'AttrSet]) -- ^ Function to set attributes on the cell renderer.
-> m ()
cellLayoutSetAttributes self cell model attributes =
cellLayoutSetDataFunc' self cell model $ \iter -> do
row <- customStoreGetRow model iter
set cell (attributes row)
-- | Like 'cellLayoutSetAttributes', but allows any IO action to be used
cellLayoutSetDataFunction :: (MonadIO m,
IsCellLayout self,
IsCellRenderer cell,
IsTreeModel (model row),
IsTypedTreeModel model)
=> self
-> cell -- ^ @cell@ - A 'CellRenderer'.
-> model row -- ^ @model@ - A model containing rows of type @row@.
-> (row -> IO ()) -- ^ Function to set data on the cell renderer.
-> m ()
cellLayoutSetDataFunction self cell model callback =
cellLayoutSetDataFunc' self cell model $ \iter -> do
row <- customStoreGetRow model iter
callback row
-- | Install a function that looks up a row in the model and sets the
-- attributes of the 'CellRenderer' @cell@ using the row's content.
--
cellLayoutSetDataFunc' :: (MonadIO m,
IsCellLayout self,
IsCellRenderer cell,
IsTreeModel model)
=> self
-> cell -- ^ @cell@ - A 'CellRenderer'.
-> model -- ^ @model@ - A model from which to draw data.
-> (TreeIter -> IO ()) -- ^ Function to set attributes on the cell renderer.
-> m ()
cellLayoutSetDataFunc' self cell model func = liftIO $
cellLayoutSetCellDataFunc self cell . Just $ \_ (CellRenderer cellPtr') model' iter -> do
iter <- convertIterFromParentToChildModel iter model' =<< toTreeModel model
CellRenderer cellPtr <- toCellRenderer cell
if managedForeignPtr cellPtr /= managedForeignPtr cellPtr' then
error ("cellLayoutSetAttributeFunc: attempt to set attributes of "++
"a different CellRenderer.")
else func iter
-- Given a 'TreeModelFilter' or a 'TreeModelSort' and a 'TreeIter', get the
-- child model of these models and convert the iter to an iter of the child
-- model. This is an ugly internal function that is needed for some widgets
-- which pass iterators to the callback function of set_cell_data_func that
-- refer to some internal TreeModelFilter models that they create around the
-- user model. This is a bug but since C programs mostly use the columns
-- rather than the cell_layout way to extract attributes, this bug does not
-- show up in many programs. Reported in the case of EntryCompletion as bug
-- \#551202.
--
convertIterFromParentToChildModel ::
TreeIter -- ^ the iterator
-> TreeModel -- ^ the model that we got from the all back
-> TreeModel -- ^ the model that we actually want
-> IO TreeIter
convertIterFromParentToChildModel iter parentModel@(TreeModel parentModelPtr) childModel =
let (TreeModel modelPtr) = childModel in
if managedForeignPtr modelPtr == managedForeignPtr parentModelPtr
then return iter
else
castTo TreeModelFilter parentModel >>= \case
Just tmFilter -> do
childIter <- treeModelFilterConvertIterToChildIter tmFilter iter
Just child@(TreeModel childPtr) <- getTreeModelFilterChildModel tmFilter
if managedForeignPtr childPtr == managedForeignPtr modelPtr
then return childIter
else convertIterFromParentToChildModel childIter child childModel
Nothing -> do
castTo TreeModelSort parentModel >>= \case
Just tmSort -> do
childIter <- treeModelSortConvertIterToChildIter tmSort iter
child@(TreeModel childPtr) <- getTreeModelSortModel tmSort
if managedForeignPtr childPtr == managedForeignPtr modelPtr
then return childIter
else convertIterFromParentToChildModel childIter child childModel
Nothing -> do
stamp <- getTreeIterStamp iter
ud1 <- getTreeIterUserData iter
ud2 <- getTreeIterUserData2 iter
ud3 <- getTreeIterUserData3 iter
error ("CellLayout: don't know how to convert iter "++show (stamp, ud1, ud2, ud3)++
" from model "++show (managedForeignPtr parentModelPtr)++" to model "++
show (managedForeignPtr modelPtr)++". Is it possible that you are setting the "++
"attributes of a CellRenderer using a different model than "++
"that which was set in the view?")
| gtk2hs/gi-gtk-hs | src/Data/GI/Gtk/ModelView/CellLayout.hs | lgpl-2.1 | 9,580 | 0 | 31 | 2,275 | 1,189 | 673 | 516 | 105 | 6 |
{- |
Module : Data.DRS.Binding
Copyright : (c) Harm Brouwer and Noortje Venhuizen
License : Apache-2.0
Maintainer : [email protected], [email protected]
Stability : provisional
Portability : portable
DRS binding
-}
module Data.DRS.Binding
(
drsBoundRef
, drsFreeRefs
) where
import Data.DRS.DataType
import Data.DRS.Structure
import Data.List (partition, union)
---------------------------------------------------------------------------
-- * Exported
---------------------------------------------------------------------------
---------------------------------------------------------------------------
-- | Returns whether 'DRSRef' @d@ in local 'DRS' @ld@ is bound in the
-- global 'DRS' @gd@.
---------------------------------------------------------------------------
drsBoundRef :: DRSRef -> DRS -> DRS -> Bool
drsBoundRef _ (LambdaDRS _) _ = False
drsBoundRef r (Merge d1 d2) gd = drsBoundRef r d1 gd || drsBoundRef r d2 gd
drsBoundRef _ _ (LambdaDRS _) = False
drsBoundRef r ld (Merge d1 d2) = drsBoundRef r ld d1 || drsBoundRef r ld d2
drsBoundRef r ld@(DRS lu _) (DRS gu gc)
| r `elem` lu = True
| r `elem` gu = True
| hasAntecedent r ld gc = True
| otherwise = False
where hasAntecedent :: DRSRef -> DRS -> [DRSCon] -> Bool
hasAntecedent r' ld' = any antecedent
where antecedent :: DRSCon -> Bool
antecedent (Rel _ _) = False
antecedent (Neg d1) = isSubDRS ld' d1 && drsBoundRef r' ld' d1
antecedent (Imp d1 d2) = (r' `elem` drsUniverse d1 && isSubDRS ld' d2)
|| (isSubDRS ld' d1 && drsBoundRef r' ld' d1)
|| (isSubDRS ld' d2 && drsBoundRef r' ld' d2)
antecedent (Or d1 d2) = (isSubDRS ld' d1 && drsBoundRef r' ld' d1)
|| (isSubDRS ld' d2 && drsBoundRef r ld' d2)
antecedent (Prop _ d1) = isSubDRS ld' d1 && drsBoundRef r' ld' d1
antecedent (Diamond d1) = isSubDRS ld' d1 && drsBoundRef r' ld' d1
antecedent (Box d1) = isSubDRS ld' d1 && drsBoundRef r' ld' d1
---------------------------------------------------------------------------
-- | Returns the list of all free 'DRSRef's in a 'DRS'.
---------------------------------------------------------------------------
drsFreeRefs :: DRS -> DRS -> [DRSRef]
drsFreeRefs (LambdaDRS _) _ = []
drsFreeRefs (Merge d1 d2) gd = drsFreeRefs d1 gd `union` drsFreeRefs d2 gd
drsFreeRefs ld@(DRS _ c) gd = free c
where free :: [DRSCon] -> [DRSRef]
free [] = []
free (Rel _ d:cs) = snd (partition (flip (`drsBoundRef` ld) gd) d) `union` free cs
free (Neg d1:cs) = drsFreeRefs d1 gd `union` free cs
free (Imp d1 d2:cs) = drsFreeRefs d1 gd `union` drsFreeRefs d2 gd `union` free cs
free (Or d1 d2:cs) = drsFreeRefs d1 gd `union` drsFreeRefs d2 gd `union` free cs
free (Prop r d1:cs) = snd (partition (flip (`drsBoundRef` ld) gd) [r]) `union` drsFreeRefs d1 gd `union` free cs
free (Diamond d1:cs) = drsFreeRefs d1 gd `union` free cs
free (Box d1:cs) = drsFreeRefs d1 gd `union` free cs
| hbrouwer/pdrt-sandbox | src/Data/DRS/Binding.hs | apache-2.0 | 3,206 | 0 | 14 | 813 | 1,017 | 522 | 495 | 43 | 8 |
-- | Provides a way of adding text to notes.
module Music.Score.Text (
-- * Text
HasText(..),
TextT(..),
text,
textLast,
) where
import Control.Applicative
import Control.Comonad
import Control.Lens hiding (transform)
import Data.Foldable
import Data.Foldable
import Data.Functor.Couple
import Data.Ratio
import Data.Semigroup
import Data.Typeable
import Data.Word
import Music.Dynamics.Literal
import Music.Pitch.Alterable
import Music.Pitch.Augmentable
import Music.Pitch.Literal
import Music.Score.Part
import Music.Score.Phrases
import Music.Time
class HasText a where
addText :: String -> a -> a
newtype TextT a = TextT { getTextT :: Couple [String] a }
deriving (
Eq, Show, Ord, Functor, Foldable, Typeable,
Applicative, Monad, Comonad
)
instance HasText a => HasText (b, a) where
addText s = fmap (addText s)
instance HasText a => HasText (Couple b a) where
addText s = fmap (addText s)
instance HasText a => HasText [a] where
addText s = fmap (addText s)
instance HasText a => HasText (Note a) where
addText s = fmap (addText s)
instance HasText a => HasText (Voice a) where
addText s = fmap (addText s)
instance HasText a => HasText (Score a) where
addText s = fmap (addText s)
instance Wrapped (TextT a) where
type Unwrapped (TextT a) = Couple [String] a
_Wrapped' = iso getTextT TextT
instance Rewrapped (TextT a) (TextT b)
instance HasText (TextT a) where
addText s (TextT (Couple (t,x))) = TextT (Couple (t ++ [s],x))
-- Lifted instances
deriving instance Num a => Num (TextT a)
deriving instance Fractional a => Fractional (TextT a)
deriving instance Floating a => Floating (TextT a)
deriving instance Enum a => Enum (TextT a)
deriving instance Bounded a => Bounded (TextT a)
deriving instance (Num a, Ord a, Real a) => Real (TextT a)
deriving instance (Real a, Enum a, Integral a) => Integral (TextT a)
-- |
-- Attach the given text to the first note.
--
text :: (HasPhrases' s a, HasText a) => String -> s -> s
text s = over (phrases' . _head) (addText s)
-- |
-- Attach the given text to the last note.
--
textLast :: (HasPhrases' s a, HasText a) => String -> s -> s
textLast s = over (phrases' . _last) (addText s)
| music-suite/music-score | src/Music/Score/Text.hs | bsd-3-clause | 2,416 | 0 | 11 | 634 | 866 | 458 | 408 | -1 | -1 |
-- | Debugging infrastructure for the parallel arrays library.
module Data.Array.Parallel.Base.Debug
( check
, checkCritical
, checkLen
, checkSlice
, checkEq
, checkNotEmpty
, uninitialised)
where
import Data.Array.Parallel.Base.Config (debug, debugCritical)
-- | Throw an index-out-of-bounds error.
errorOfBounds :: String -> Int -> Int -> a
errorOfBounds loc n i
= error $ loc ++ ": Out of bounds "
++ "(vector length = " ++ show n
++ "; index = " ++ show i ++ ")"
-- | Throw a bad slice error.
errorBadSlice :: String -> Int -> Int -> Int -> a
errorBadSlice loc vecLen sliceStart sliceLen
= error $ loc ++ ": Bad slice "
++ "(vecLen = " ++ show vecLen
++ "; sliceStart = " ++ show sliceStart
++ "; sliceLen = " ++ show sliceLen ++ ")"
-- | Bounds check, enabled when `debug` = `True`.
--
-- The first integer is the length of the array, and the second
-- is the index. The second must be greater or equal to '0' and less than
-- the first integer. If the not then `error` with the `String`.
--
check :: String -> Int -> Int -> a -> a
check loc n i v
| debug
= if i >= 0 && i < n
then v
else errorOfBounds loc n i
| otherwise = v
{-# INLINE check #-}
-- | Bounds check, enabled when `debugCritical` = `True`.
--
-- This version is used to check operations that could corrupt the heap.
--
-- The first integer is the length of the array, and the second
-- is the index. The second must be greater or equal to '0' and less than
-- the first integer. If the not then `error` with the `String`.
--
checkCritical :: String -> Int -> Int -> a -> a
checkCritical loc n i v
| debugCritical
= if i >= 0 && i < n
then v
else errorOfBounds loc n i
| otherwise = v
{-# INLINE checkCritical #-}
-- | Length check, enabled when `debug` = `True`.
--
-- Check that the second integer is greater or equal to `0' and less or equal
-- than the first integer. If the not then `error` with the `String`.
--
checkLen :: String -> Int -> Int -> a -> a
checkLen loc n i v
| debug
= if i >= 0 && i <= n
then v
else errorOfBounds loc n i
| otherwise = v
{-# INLINE checkLen #-}
-- | Slice check, enable when `debug` = `True`.
--
-- The vector must contain at least `sliceStart` + `sliceLen` elements.
--
checkSlice :: String -> Int -> Int -> Int -> a -> a
checkSlice loc vecLen sliceStart sliceLen v
| debug
= if ( sliceStart >= 0 && sliceStart <= vecLen
&& sliceStart + sliceLen >= 0 && sliceStart + sliceLen <= vecLen )
then v
else errorBadSlice loc vecLen sliceStart sliceLen
| otherwise = v
{-# INLINE checkSlice #-}
-- | Equality check, enabled when `debug` = `True`.
--
-- The two `a` values must be equal, else `error`.
--
-- The first `String` gives the location of the error,
-- and the second some helpful message.
--
checkEq :: (Eq a, Show a) => String -> String -> a -> a -> b -> b
checkEq loc msg x y v
| debug
= if x == y
then v
else error $ loc ++ ": " ++ msg
++ " (first = " ++ show x
++ "; second = " ++ show y ++ ")"
| otherwise = v
{-# INLINE checkEq #-}
-- | Given an array length, check it is not zero.
checkNotEmpty :: String -> Int -> a -> a
checkNotEmpty loc n v
| debug
= if n /= 0
then v
else error $ loc ++ ": Empty array"
| otherwise = v
{-# INLINE checkNotEmpty #-}
-- | Throw an error saying something was not intitialised.
--
-- The `String` must contain a helpful message saying what module
-- the error occured in, and the possible reasons for it.
-- If not then a puppy dies at compile time.
--
uninitialised :: String -> a
uninitialised loc
= error $ loc ++ ": Touched an uninitialised value"
| mainland/dph | dph-base/Data/Array/Parallel/Base/Debug.hs | bsd-3-clause | 4,017 | 0 | 16 | 1,229 | 790 | 424 | 366 | 74 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Hi.Types
( Option(..)
, File(..)
, Files
, TemplateSource (..)
) where
import Data.ByteString (ByteString)
data File = TemplateFile { getFilePath :: FilePath, getFileContents :: ByteString } |
RegularFile { getFilePath :: FilePath, getFileContents :: ByteString } deriving (Eq,Ord,Show)
data TemplateSource = FromRepo String deriving (Eq,Ord,Show)
type Files = [File]
data Option = Option
{ moduleName :: String
, packageName :: String
, directoryName :: String
, author :: String
, email :: String
, year :: String
, templateSource :: TemplateSource
, afterCommands :: [String]
} deriving (Eq,Ord,Show)
| jonathankochems/hi | src/Hi/Types.hs | bsd-3-clause | 802 | 0 | 9 | 250 | 204 | 127 | 77 | 21 | 0 |
{-
(c) The University of Glasgow 2006
(c) The AQUA Project, Glasgow University, 1994-1998
Core-syntax unfoldings
Unfoldings (which can travel across module boundaries) are in Core
syntax (namely @CoreExpr@s).
The type @Unfolding@ sits ``above'' simply-Core-expressions
unfoldings, capturing ``higher-level'' things we know about a binding,
usually things that the simplifier found out (e.g., ``it's a
literal''). In the corner of a @CoreUnfolding@ unfolding, you will
find, unsurprisingly, a Core expression.
-}
{-# LANGUAGE CPP #-}
module CoreUnfold (
Unfolding, UnfoldingGuidance, -- Abstract types
noUnfolding, mkImplicitUnfolding,
mkUnfolding, mkCoreUnfolding,
mkTopUnfolding, mkSimpleUnfolding, mkWorkerUnfolding,
mkInlineUnfolding, mkInlinableUnfolding, mkWwInlineRule,
mkCompulsoryUnfolding, mkDFunUnfolding,
specUnfolding,
ArgSummary(..),
couldBeSmallEnoughToInline, inlineBoringOk,
certainlyWillInline, smallEnoughToInline,
callSiteInline, CallCtxt(..),
-- Reexport from CoreSubst (it only live there so it can be used
-- by the Very Simple Optimiser)
exprIsConApp_maybe, exprIsLiteral_maybe
) where
#include "HsVersions.h"
import DynFlags
import CoreSyn
import PprCore () -- Instances
import OccurAnal ( occurAnalyseExpr )
import CoreSubst hiding( substTy )
import CoreArity ( manifestArity, exprBotStrictness_maybe )
import CoreUtils
import Id
import DataCon
import Literal
import PrimOp
import IdInfo
import BasicTypes ( Arity )
import Type
import PrelNames
import TysPrim ( realWorldStatePrimTy )
import Bag
import Util
import FastTypes
import FastString
import Outputable
import ForeignCall
import qualified Data.ByteString as BS
import Data.Maybe
{-
************************************************************************
* *
\subsection{Making unfoldings}
* *
************************************************************************
-}
mkTopUnfolding :: DynFlags -> Bool -> CoreExpr -> Unfolding
mkTopUnfolding dflags = mkUnfolding dflags InlineRhs True {- Top level -}
mkImplicitUnfolding :: DynFlags -> CoreExpr -> Unfolding
-- For implicit Ids, do a tiny bit of optimising first
mkImplicitUnfolding dflags expr
= mkTopUnfolding dflags False (simpleOptExpr expr)
-- Note [Top-level flag on inline rules]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Slight hack: note that mk_inline_rules conservatively sets the
-- top-level flag to True. It gets set more accurately by the simplifier
-- Simplify.simplUnfolding.
mkSimpleUnfolding :: DynFlags -> CoreExpr -> Unfolding
mkSimpleUnfolding dflags = mkUnfolding dflags InlineRhs False False
mkDFunUnfolding :: [Var] -> DataCon -> [CoreExpr] -> Unfolding
mkDFunUnfolding bndrs con ops
= DFunUnfolding { df_bndrs = bndrs
, df_con = con
, df_args = map occurAnalyseExpr ops }
-- See Note [Occurrrence analysis of unfoldings]
mkWwInlineRule :: CoreExpr -> Arity -> Unfolding
mkWwInlineRule expr arity
= mkCoreUnfolding InlineStable True
(simpleOptExpr expr)
(UnfWhen { ug_arity = arity, ug_unsat_ok = unSaturatedOk
, ug_boring_ok = boringCxtNotOk })
mkCompulsoryUnfolding :: CoreExpr -> Unfolding
mkCompulsoryUnfolding expr -- Used for things that absolutely must be unfolded
= mkCoreUnfolding InlineCompulsory True
(simpleOptExpr expr)
(UnfWhen { ug_arity = 0 -- Arity of unfolding doesn't matter
, ug_unsat_ok = unSaturatedOk, ug_boring_ok = boringCxtOk })
mkWorkerUnfolding :: DynFlags -> (CoreExpr -> CoreExpr) -> Unfolding -> Unfolding
-- See Note [Worker-wrapper for INLINABLE functions] in WorkWrap
mkWorkerUnfolding dflags work_fn
(CoreUnfolding { uf_src = src, uf_tmpl = tmpl
, uf_is_top = top_lvl })
| isStableSource src
= mkCoreUnfolding src top_lvl new_tmpl guidance
where
new_tmpl = simpleOptExpr (work_fn tmpl)
guidance = calcUnfoldingGuidance dflags new_tmpl
mkWorkerUnfolding _ _ _ = noUnfolding
mkInlineUnfolding :: Maybe Arity -> CoreExpr -> Unfolding
mkInlineUnfolding mb_arity expr
= mkCoreUnfolding InlineStable
True -- Note [Top-level flag on inline rules]
expr' guide
where
expr' = simpleOptExpr expr
guide = case mb_arity of
Nothing -> UnfWhen { ug_arity = manifestArity expr'
, ug_unsat_ok = unSaturatedOk
, ug_boring_ok = boring_ok }
Just arity -> UnfWhen { ug_arity = arity
, ug_unsat_ok = needSaturated
, ug_boring_ok = boring_ok }
boring_ok = inlineBoringOk expr'
mkInlinableUnfolding :: DynFlags -> CoreExpr -> Unfolding
mkInlinableUnfolding dflags expr
= mkUnfolding dflags InlineStable True is_bot expr'
where
expr' = simpleOptExpr expr
is_bot = isJust (exprBotStrictness_maybe expr')
specUnfolding :: DynFlags -> Subst -> [Var] -> [CoreExpr] -> Unfolding -> Unfolding
-- See Note [Specialising unfoldings]
specUnfolding _ subst new_bndrs spec_args
df@(DFunUnfolding { df_bndrs = bndrs, df_con = con , df_args = args })
= ASSERT2( length bndrs >= length spec_args, ppr df $$ ppr spec_args $$ ppr new_bndrs )
mkDFunUnfolding (new_bndrs ++ extra_bndrs) con
(map (substExpr spec_doc subst2) args)
where
subst1 = extendSubstList subst (bndrs `zip` spec_args)
(subst2, extra_bndrs) = substBndrs subst1 (dropList spec_args bndrs)
specUnfolding _dflags subst new_bndrs spec_args
(CoreUnfolding { uf_src = src, uf_tmpl = tmpl
, uf_is_top = top_lvl
, uf_guidance = old_guidance })
| isStableSource src -- See Note [Specialising unfoldings]
, UnfWhen { ug_arity = old_arity
, ug_unsat_ok = unsat_ok
, ug_boring_ok = boring_ok } <- old_guidance
= let guidance = UnfWhen { ug_arity = old_arity - count isValArg spec_args
+ count isId new_bndrs
, ug_unsat_ok = unsat_ok
, ug_boring_ok = boring_ok }
new_tmpl = simpleOptExpr $ mkLams new_bndrs $
mkApps (substExpr spec_doc subst tmpl) spec_args
-- The beta-redexes created here will be simplified
-- away by simplOptExpr in mkUnfolding
in mkCoreUnfolding src top_lvl new_tmpl guidance
specUnfolding _ _ _ _ _ = noUnfolding
spec_doc :: SDoc
spec_doc = ptext (sLit "specUnfolding")
{-
Note [Specialising unfoldings]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we specialise a function for some given type-class arguments, we use
specUnfolding to specialise its unfolding. Some important points:
* If the original function has a DFunUnfolding, the specialised one
must do so too! Otherwise we lose the magic rules that make it
interact with ClassOps
* There is a bit of hack for INLINABLE functions:
f :: Ord a => ....
f = <big-rhs>
{- INLINEABLE f #-}
Now if we specialise f, should the specialised version still have
an INLINEABLE pragma? If it does, we'll capture a specialised copy
of <big-rhs> as its unfolding, and that probaby won't inline. But
if we don't, the specialised version of <big-rhs> might be small
enough to inline at a call site. This happens with Control.Monad.liftM3,
and can cause a lot more allocation as a result (nofib n-body shows this).
Moreover, keeping the INLINEABLE thing isn't much help, because
the specialised function (probaby) isn't overloaded any more.
Conclusion: drop the INLINEALE pragma. In practice what this means is:
if a stable unfolding has UnfoldingGuidance of UnfWhen,
we keep it (so the specialised thing too will always inline)
if a stable unfolding has UnfoldingGuidance of UnfIfGoodArgs
(which arises from INLINEABLE), we discard it
-}
mkCoreUnfolding :: UnfoldingSource -> Bool -> CoreExpr
-> UnfoldingGuidance -> Unfolding
-- Occurrence-analyses the expression before capturing it
mkCoreUnfolding src top_lvl expr guidance
= CoreUnfolding { uf_tmpl = occurAnalyseExpr expr,
-- See Note [Occurrrence analysis of unfoldings]
uf_src = src,
uf_is_top = top_lvl,
uf_is_value = exprIsHNF expr,
uf_is_conlike = exprIsConLike expr,
uf_is_work_free = exprIsWorkFree expr,
uf_expandable = exprIsExpandable expr,
uf_guidance = guidance }
mkUnfolding :: DynFlags -> UnfoldingSource -> Bool -> Bool -> CoreExpr
-> Unfolding
-- Calculates unfolding guidance
-- Occurrence-analyses the expression before capturing it
mkUnfolding dflags src top_lvl is_bottoming expr
| top_lvl && is_bottoming
, not (exprIsTrivial expr)
= NoUnfolding -- See Note [Do not inline top-level bottoming functions]
| otherwise
= CoreUnfolding { uf_tmpl = occurAnalyseExpr expr,
-- See Note [Occurrrence analysis of unfoldings]
uf_src = src,
uf_is_top = top_lvl,
uf_is_value = exprIsHNF expr,
uf_is_conlike = exprIsConLike expr,
uf_expandable = exprIsExpandable expr,
uf_is_work_free = exprIsWorkFree expr,
uf_guidance = guidance }
where
guidance = calcUnfoldingGuidance dflags expr
-- NB: *not* (calcUnfoldingGuidance (occurAnalyseExpr expr))!
-- See Note [Calculate unfolding guidance on the non-occ-anal'd expression]
{-
Note [Occurrence analysis of unfoldings]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We do occurrence-analysis of unfoldings once and for all, when the
unfolding is built, rather than each time we inline them.
But given this decision it's vital that we do
*always* do it. Consider this unfolding
\x -> letrec { f = ...g...; g* = f } in body
where g* is (for some strange reason) the loop breaker. If we don't
occ-anal it when reading it in, we won't mark g as a loop breaker, and
we may inline g entirely in body, dropping its binding, and leaving
the occurrence in f out of scope. This happened in Trac #8892, where
the unfolding in question was a DFun unfolding.
But more generally, the simplifier is designed on the
basis that it is looking at occurrence-analysed expressions, so better
ensure that they acutally are.
Note [Calculate unfolding guidance on the non-occ-anal'd expression]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Notice that we give the non-occur-analysed expression to
calcUnfoldingGuidance. In some ways it'd be better to occur-analyse
first; for example, sometimes during simplification, there's a large
let-bound thing which has been substituted, and so is now dead; so
'expr' contains two copies of the thing while the occurrence-analysed
expression doesn't.
Nevertheless, we *don't* and *must not* occ-analyse before computing
the size because
a) The size computation bales out after a while, whereas occurrence
analysis does not.
b) Residency increases sharply if you occ-anal first. I'm not
100% sure why, but it's a large effect. Compiling Cabal went
from residency of 534M to over 800M with this one change.
This can occasionally mean that the guidance is very pessimistic;
it gets fixed up next round. And it should be rare, because large
let-bound things that are dead are usually caught by preInlineUnconditionally
************************************************************************
* *
\subsection{The UnfoldingGuidance type}
* *
************************************************************************
-}
inlineBoringOk :: CoreExpr -> Bool
-- See Note [INLINE for small functions]
-- True => the result of inlining the expression is
-- no bigger than the expression itself
-- eg (\x y -> f y x)
-- This is a quick and dirty version. It doesn't attempt
-- to deal with (\x y z -> x (y z))
-- The really important one is (x `cast` c)
inlineBoringOk e
= go 0 e
where
go :: Int -> CoreExpr -> Bool
go credit (Lam x e) | isId x = go (credit+1) e
| otherwise = go credit e
go credit (App f (Type {})) = go credit f
go credit (App f a) | credit > 0
, exprIsTrivial a = go (credit-1) f
go credit (Tick _ e) = go credit e -- dubious
go credit (Cast e _) = go credit e
go _ (Var {}) = boringCxtOk
go _ _ = boringCxtNotOk
calcUnfoldingGuidance
:: DynFlags
-> CoreExpr -- Expression to look at
-> UnfoldingGuidance
calcUnfoldingGuidance dflags (Tick t expr)
| not (tickishIsCode t) -- non-code ticks don't matter for unfolding
= calcUnfoldingGuidance dflags expr
calcUnfoldingGuidance dflags expr
= case sizeExpr dflags (iUnbox bOMB_OUT_SIZE) val_bndrs body of
TooBig -> UnfNever
SizeIs size cased_bndrs scrut_discount
| uncondInline expr n_val_bndrs (iBox size)
-> UnfWhen { ug_unsat_ok = unSaturatedOk
, ug_boring_ok = boringCxtOk
, ug_arity = n_val_bndrs } -- Note [INLINE for small functions]
| otherwise
-> UnfIfGoodArgs { ug_args = map (mk_discount cased_bndrs) val_bndrs
, ug_size = iBox size
, ug_res = iBox scrut_discount }
where
(bndrs, body) = collectBinders expr
bOMB_OUT_SIZE = ufCreationThreshold dflags
-- Bomb out if size gets bigger than this
val_bndrs = filter isId bndrs
n_val_bndrs = length val_bndrs
mk_discount :: Bag (Id,Int) -> Id -> Int
mk_discount cbs bndr = foldlBag combine 0 cbs
where
combine acc (bndr', disc)
| bndr == bndr' = acc `plus_disc` disc
| otherwise = acc
plus_disc :: Int -> Int -> Int
plus_disc | isFunTy (idType bndr) = max
| otherwise = (+)
-- See Note [Function and non-function discounts]
{-
Note [Computing the size of an expression]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The basic idea of sizeExpr is obvious enough: count nodes. But getting the
heuristics right has taken a long time. Here's the basic strategy:
* Variables, literals: 0
(Exception for string literals, see litSize.)
* Function applications (f e1 .. en): 1 + #value args
* Constructor applications: 1, regardless of #args
* Let(rec): 1 + size of components
* Note, cast: 0
Examples
Size Term
--------------
0 42#
0 x
0 True
2 f x
1 Just x
4 f (g x)
Notice that 'x' counts 0, while (f x) counts 2. That's deliberate: there's
a function call to account for. Notice also that constructor applications
are very cheap, because exposing them to a caller is so valuable.
[25/5/11] All sizes are now multiplied by 10, except for primops
(which have sizes like 1 or 4. This makes primops look fantastically
cheap, and seems to be almost unversally beneficial. Done partly as a
result of #4978.
Note [Do not inline top-level bottoming functions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The FloatOut pass has gone to some trouble to float out calls to 'error'
and similar friends. See Note [Bottoming floats] in SetLevels.
Do not re-inline them! But we *do* still inline if they are very small
(the uncondInline stuff).
Note [INLINE for small functions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider {-# INLINE f #-}
f x = Just x
g y = f y
Then f's RHS is no larger than its LHS, so we should inline it into
even the most boring context. In general, f the function is
sufficiently small that its body is as small as the call itself, the
inline unconditionally, regardless of how boring the context is.
Things to note:
(1) We inline *unconditionally* if inlined thing is smaller (using sizeExpr)
than the thing it's replacing. Notice that
(f x) --> (g 3) -- YES, unconditionally
(f x) --> x : [] -- YES, *even though* there are two
-- arguments to the cons
x --> g 3 -- NO
x --> Just v -- NO
It's very important not to unconditionally replace a variable by
a non-atomic term.
(2) We do this even if the thing isn't saturated, else we end up with the
silly situation that
f x y = x
...map (f 3)...
doesn't inline. Even in a boring context, inlining without being
saturated will give a lambda instead of a PAP, and will be more
efficient at runtime.
(3) However, when the function's arity > 0, we do insist that it
has at least one value argument at the call site. (This check is
made in the UnfWhen case of callSiteInline.) Otherwise we find this:
f = /\a \x:a. x
d = /\b. MkD (f b)
If we inline f here we get
d = /\b. MkD (\x:b. x)
and then prepareRhs floats out the argument, abstracting the type
variables, so we end up with the original again!
(4) We must be much more cautious about arity-zero things. Consider
let x = y +# z in ...
In *size* terms primops look very small, because the generate a
single instruction, but we do not want to unconditionally replace
every occurrence of x with (y +# z). So we only do the
unconditional-inline thing for *trivial* expressions.
NB: you might think that PostInlineUnconditionally would do this
but it doesn't fire for top-level things; see SimplUtils
Note [Top level and postInlineUnconditionally]
-}
uncondInline :: CoreExpr -> Arity -> Int -> Bool
-- Inline unconditionally if there no size increase
-- Size of call is arity (+1 for the function)
-- See Note [INLINE for small functions]
uncondInline rhs arity size
| arity > 0 = size <= 10 * (arity + 1) -- See Note [INLINE for small functions] (1)
| otherwise = exprIsTrivial rhs -- See Note [INLINE for small functions] (4)
sizeExpr :: DynFlags
-> FastInt -- Bomb out if it gets bigger than this
-> [Id] -- Arguments; we're interested in which of these
-- get case'd
-> CoreExpr
-> ExprSize
-- Note [Computing the size of an expression]
sizeExpr dflags bOMB_OUT_SIZE top_args expr
= size_up expr
where
size_up (Cast e _) = size_up e
size_up (Tick _ e) = size_up e
size_up (Type _) = sizeZero -- Types cost nothing
size_up (Coercion _) = sizeZero
size_up (Lit lit) = sizeN (litSize lit)
size_up (Var f) | isRealWorldId f = sizeZero
-- Make sure we get constructor discounts even
-- on nullary constructors
| otherwise = size_up_call f [] 0
size_up (App fun arg)
| isTyCoArg arg = size_up fun
| otherwise = size_up arg `addSizeNSD`
size_up_app fun [arg] (if isRealWorldExpr arg then 1 else 0)
size_up (Lam b e)
| isId b && not (isRealWorldId b) = lamScrutDiscount dflags (size_up e `addSizeN` 10)
| otherwise = size_up e
size_up (Let (NonRec binder rhs) body)
= size_up rhs `addSizeNSD`
size_up body `addSizeN`
(if isUnLiftedType (idType binder) then 0 else 10)
-- For the allocation
-- If the binder has an unlifted type there is no allocation
size_up (Let (Rec pairs) body)
= foldr (addSizeNSD . size_up . snd)
(size_up body `addSizeN` (10 * length pairs)) -- (length pairs) for the allocation
pairs
size_up (Case (Var v) _ _ alts)
| v `elem` top_args -- We are scrutinising an argument variable
= alts_size (foldr addAltSize sizeZero alt_sizes)
(foldr maxSize sizeZero alt_sizes)
-- Good to inline if an arg is scrutinised, because
-- that may eliminate allocation in the caller
-- And it eliminates the case itself
where
alt_sizes = map size_up_alt alts
-- alts_size tries to compute a good discount for
-- the case when we are scrutinising an argument variable
alts_size (SizeIs tot tot_disc tot_scrut) -- Size of all alternatives
(SizeIs max _ _) -- Size of biggest alternative
= SizeIs tot (unitBag (v, iBox (_ILIT(20) +# tot -# max)) `unionBags` tot_disc) tot_scrut
-- If the variable is known, we produce a discount that
-- will take us back to 'max', the size of the largest alternative
-- The 1+ is a little discount for reduced allocation in the caller
--
-- Notice though, that we return tot_disc, the total discount from
-- all branches. I think that's right.
alts_size tot_size _ = tot_size
size_up (Case e _ _ alts) = size_up e `addSizeNSD`
foldr (addAltSize . size_up_alt) case_size alts
where
case_size
| is_inline_scrut e, not (lengthExceeds alts 1) = sizeN (-10)
| otherwise = sizeZero
-- Normally we don't charge for the case itself, but
-- we charge one per alternative (see size_up_alt,
-- below) to account for the cost of the info table
-- and comparisons.
--
-- However, in certain cases (see is_inline_scrut
-- below), no code is generated for the case unless
-- there are multiple alts. In these cases we
-- subtract one, making the first alt free.
-- e.g. case x# +# y# of _ -> ... should cost 1
-- case touch# x# of _ -> ... should cost 0
-- (see #4978)
--
-- I would like to not have the "not (lengthExceeds alts 1)"
-- condition above, but without that some programs got worse
-- (spectral/hartel/event and spectral/para). I don't fully
-- understand why. (SDM 24/5/11)
-- unboxed variables, inline primops and unsafe foreign calls
-- are all "inline" things:
is_inline_scrut (Var v) = isUnLiftedType (idType v)
is_inline_scrut scrut
| (Var f, _) <- collectArgs scrut
= case idDetails f of
FCallId fc -> not (isSafeForeignCall fc)
PrimOpId op -> not (primOpOutOfLine op)
_other -> False
| otherwise
= False
------------
-- size_up_app is used when there's ONE OR MORE value args
size_up_app (App fun arg) args voids
| isTyCoArg arg = size_up_app fun args voids
| isRealWorldExpr arg = size_up_app fun (arg:args) (voids + 1)
| otherwise = size_up arg `addSizeNSD`
size_up_app fun (arg:args) voids
size_up_app (Var fun) args voids = size_up_call fun args voids
size_up_app (Tick _ expr) args voids = size_up_app expr args voids
size_up_app other args voids = size_up other `addSizeN` (length args - voids)
------------
size_up_call :: Id -> [CoreExpr] -> Int -> ExprSize
size_up_call fun val_args voids
= case idDetails fun of
FCallId _ -> sizeN (10 * (1 + length val_args))
DataConWorkId dc -> conSize dc (length val_args)
PrimOpId op -> primOpSize op (length val_args)
ClassOpId _ -> classOpSize dflags top_args val_args
_ -> funSize dflags top_args fun (length val_args) voids
------------
size_up_alt (_con, _bndrs, rhs) = size_up rhs `addSizeN` 10
-- Don't charge for args, so that wrappers look cheap
-- (See comments about wrappers with Case)
--
-- IMPORATANT: *do* charge 1 for the alternative, else we
-- find that giant case nests are treated as practically free
-- A good example is Foreign.C.Error.errrnoToIOError
------------
-- These addSize things have to be here because
-- I don't want to give them bOMB_OUT_SIZE as an argument
addSizeN TooBig _ = TooBig
addSizeN (SizeIs n xs d) m = mkSizeIs bOMB_OUT_SIZE (n +# iUnbox m) xs d
-- addAltSize is used to add the sizes of case alternatives
addAltSize TooBig _ = TooBig
addAltSize _ TooBig = TooBig
addAltSize (SizeIs n1 xs d1) (SizeIs n2 ys d2)
= mkSizeIs bOMB_OUT_SIZE (n1 +# n2)
(xs `unionBags` ys)
(d1 +# d2) -- Note [addAltSize result discounts]
-- This variant ignores the result discount from its LEFT argument
-- It's used when the second argument isn't part of the result
addSizeNSD TooBig _ = TooBig
addSizeNSD _ TooBig = TooBig
addSizeNSD (SizeIs n1 xs _) (SizeIs n2 ys d2)
= mkSizeIs bOMB_OUT_SIZE (n1 +# n2)
(xs `unionBags` ys)
d2 -- Ignore d1
isRealWorldId id = idType id `eqType` realWorldStatePrimTy
-- an expression of type State# RealWorld must be a variable
isRealWorldExpr (Var id) = isRealWorldId id
isRealWorldExpr (Tick _ e) = isRealWorldExpr e
isRealWorldExpr _ = False
-- | Finds a nominal size of a string literal.
litSize :: Literal -> Int
-- Used by CoreUnfold.sizeExpr
litSize (LitInteger {}) = 100 -- Note [Size of literal integers]
litSize (MachStr str) = 10 + 10 * ((BS.length str + 3) `div` 4)
-- If size could be 0 then @f "x"@ might be too small
-- [Sept03: make literal strings a bit bigger to avoid fruitless
-- duplication of little strings]
litSize _other = 0 -- Must match size of nullary constructors
-- Key point: if x |-> 4, then x must inline unconditionally
-- (eg via case binding)
classOpSize :: DynFlags -> [Id] -> [CoreExpr] -> ExprSize
-- See Note [Conlike is interesting]
classOpSize _ _ []
= sizeZero
classOpSize dflags top_args (arg1 : other_args)
= SizeIs (iUnbox size) arg_discount (_ILIT(0))
where
size = 20 + (10 * length other_args)
-- If the class op is scrutinising a lambda bound dictionary then
-- give it a discount, to encourage the inlining of this function
-- The actual discount is rather arbitrarily chosen
arg_discount = case arg1 of
Var dict | dict `elem` top_args
-> unitBag (dict, ufDictDiscount dflags)
_other -> emptyBag
funSize :: DynFlags -> [Id] -> Id -> Int -> Int -> ExprSize
-- Size for functions that are not constructors or primops
-- Note [Function applications]
funSize dflags top_args fun n_val_args voids
| fun `hasKey` buildIdKey = buildSize
| fun `hasKey` augmentIdKey = augmentSize
| otherwise = SizeIs (iUnbox size) arg_discount (iUnbox res_discount)
where
some_val_args = n_val_args > 0
size | some_val_args = 10 * (1 + n_val_args - voids)
| otherwise = 0
-- The 1+ is for the function itself
-- Add 1 for each non-trivial arg;
-- the allocation cost, as in let(rec)
-- DISCOUNTS
-- See Note [Function and non-function discounts]
arg_discount | some_val_args && fun `elem` top_args
= unitBag (fun, ufFunAppDiscount dflags)
| otherwise = emptyBag
-- If the function is an argument and is applied
-- to some values, give it an arg-discount
res_discount | idArity fun > n_val_args = ufFunAppDiscount dflags
| otherwise = 0
-- If the function is partially applied, show a result discount
conSize :: DataCon -> Int -> ExprSize
conSize dc n_val_args
| n_val_args == 0 = SizeIs (_ILIT(0)) emptyBag (_ILIT(10)) -- Like variables
-- See Note [Unboxed tuple size and result discount]
| isUnboxedTupleCon dc = SizeIs (_ILIT(0)) emptyBag (iUnbox (10 * (1 + n_val_args)))
-- See Note [Constructor size and result discount]
| otherwise = SizeIs (_ILIT(10)) emptyBag (iUnbox (10 * (1 + n_val_args)))
{-
Note [Constructor size and result discount]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Treat a constructors application as size 10, regardless of how many
arguments it has; we are keen to expose them (and we charge separately
for their args). We can't treat them as size zero, else we find that
(Just x) has size 0, which is the same as a lone variable; and hence
'v' will always be replaced by (Just x), where v is bound to Just x.
The "result discount" is applied if the result of the call is
scrutinised (say by a case). For a constructor application that will
mean the constructor application will disappear, so we don't need to
charge it to the function. So the discount should at least match the
cost of the constructor application, namely 10. But to give a bit
of extra incentive we give a discount of 10*(1 + n_val_args).
Simon M tried a MUCH bigger discount: (10 * (10 + n_val_args)),
and said it was an "unambiguous win", but its terribly dangerous
because a fuction with many many case branches, each finishing with
a constructor, can have an arbitrarily large discount. This led to
terrible code bloat: see Trac #6099.
Note [Unboxed tuple size and result discount]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
However, unboxed tuples count as size zero. I found occasions where we had
f x y z = case op# x y z of { s -> (# s, () #) }
and f wasn't getting inlined.
I tried giving unboxed tuples a *result discount* of zero (see the
commented-out line). Why? When returned as a result they do not
allocate, so maybe we don't want to charge so much for them If you
have a non-zero discount here, we find that workers often get inlined
back into wrappers, because it look like
f x = case $wf x of (# a,b #) -> (a,b)
and we are keener because of the case. However while this change
shrank binary sizes by 0.5% it also made spectral/boyer allocate 5%
more. All other changes were very small. So it's not a big deal but I
didn't adopt the idea.
Note [Function and non-function discounts]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We want a discount if the function is applied. A good example is
monadic combinators with continuation arguments, where inlining is
quite important.
But we don't want a big discount when a function is called many times
(see the detailed comments with Trac #6048) because if the function is
big it won't be inlined at its many call sites and no benefit results.
Indeed, we can get exponentially big inlinings this way; that is what
Trac #6048 is about.
On the other hand, for data-valued arguments, if there are lots of
case expressions in the body, each one will get smaller if we apply
the function to a constructor application, so we *want* a big discount
if the argument is scrutinised by many case expressions.
Conclusion:
- For functions, take the max of the discounts
- For data values, take the sum of the discounts
Note [Literal integer size]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Literal integers *can* be big (mkInteger [...coefficients...]), but
need not be (S# n). We just use an aribitrary big-ish constant here
so that, in particular, we don't inline top-level defns like
n = S# 5
There's no point in doing so -- any optimisations will see the S#
through n's unfolding. Nor will a big size inhibit unfoldings functions
that mention a literal Integer, because the float-out pass will float
all those constants to top level.
-}
primOpSize :: PrimOp -> Int -> ExprSize
primOpSize op n_val_args
= if primOpOutOfLine op
then sizeN (op_size + n_val_args)
else sizeN op_size
where
op_size = primOpCodeSize op
buildSize :: ExprSize
buildSize = SizeIs (_ILIT(0)) emptyBag (_ILIT(40))
-- We really want to inline applications of build
-- build t (\cn -> e) should cost only the cost of e (because build will be inlined later)
-- Indeed, we should add a result_discount becuause build is
-- very like a constructor. We don't bother to check that the
-- build is saturated (it usually is). The "-2" discounts for the \c n,
-- The "4" is rather arbitrary.
augmentSize :: ExprSize
augmentSize = SizeIs (_ILIT(0)) emptyBag (_ILIT(40))
-- Ditto (augment t (\cn -> e) ys) should cost only the cost of
-- e plus ys. The -2 accounts for the \cn
-- When we return a lambda, give a discount if it's used (applied)
lamScrutDiscount :: DynFlags -> ExprSize -> ExprSize
lamScrutDiscount dflags (SizeIs n vs _) = SizeIs n vs (iUnbox (ufFunAppDiscount dflags))
lamScrutDiscount _ TooBig = TooBig
{-
Note [addAltSize result discounts]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When adding the size of alternatives, we *add* the result discounts
too, rather than take the *maximum*. For a multi-branch case, this
gives a discount for each branch that returns a constructor, making us
keener to inline. I did try using 'max' instead, but it makes nofib
'rewrite' and 'puzzle' allocate significantly more, and didn't make
binary sizes shrink significantly either.
Note [Discounts and thresholds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Constants for discounts and thesholds are defined in main/DynFlags,
all of form ufXxxx. They are:
ufCreationThreshold
At a definition site, if the unfolding is bigger than this, we
may discard it altogether
ufUseThreshold
At a call site, if the unfolding, less discounts, is smaller than
this, then it's small enough inline
ufKeenessFactor
Factor by which the discounts are multiplied before
subtracting from size
ufDictDiscount
The discount for each occurrence of a dictionary argument
as an argument of a class method. Should be pretty small
else big functions may get inlined
ufFunAppDiscount
Discount for a function argument that is applied. Quite
large, because if we inline we avoid the higher-order call.
ufDearOp
The size of a foreign call or not-dupable PrimOp
Note [Function applications]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In a function application (f a b)
- If 'f' is an argument to the function being analysed,
and there's at least one value arg, record a FunAppDiscount for f
- If the application if a PAP (arity > 2 in this example)
record a *result* discount (because inlining
with "extra" args in the call may mean that we now
get a saturated application)
Code for manipulating sizes
-}
data ExprSize = TooBig
| SizeIs FastInt -- Size found
!(Bag (Id,Int)) -- Arguments cased herein, and discount for each such
FastInt -- Size to subtract if result is scrutinised
-- by a case expression
instance Outputable ExprSize where
ppr TooBig = ptext (sLit "TooBig")
ppr (SizeIs a _ c) = brackets (int (iBox a) <+> int (iBox c))
-- subtract the discount before deciding whether to bale out. eg. we
-- want to inline a large constructor application into a selector:
-- tup = (a_1, ..., a_99)
-- x = case tup of ...
--
mkSizeIs :: FastInt -> FastInt -> Bag (Id, Int) -> FastInt -> ExprSize
mkSizeIs max n xs d | (n -# d) ># max = TooBig
| otherwise = SizeIs n xs d
maxSize :: ExprSize -> ExprSize -> ExprSize
maxSize TooBig _ = TooBig
maxSize _ TooBig = TooBig
maxSize s1@(SizeIs n1 _ _) s2@(SizeIs n2 _ _) | n1 ># n2 = s1
| otherwise = s2
sizeZero :: ExprSize
sizeN :: Int -> ExprSize
sizeZero = SizeIs (_ILIT(0)) emptyBag (_ILIT(0))
sizeN n = SizeIs (iUnbox n) emptyBag (_ILIT(0))
{-
************************************************************************
* *
\subsection[considerUnfolding]{Given all the info, do (not) do the unfolding}
* *
************************************************************************
We use 'couldBeSmallEnoughToInline' to avoid exporting inlinings that
we ``couldn't possibly use'' on the other side. Can be overridden w/
flaggery. Just the same as smallEnoughToInline, except that it has no
actual arguments.
-}
couldBeSmallEnoughToInline :: DynFlags -> Int -> CoreExpr -> Bool
couldBeSmallEnoughToInline dflags threshold rhs
= case sizeExpr dflags (iUnbox threshold) [] body of
TooBig -> False
_ -> True
where
(_, body) = collectBinders rhs
----------------
smallEnoughToInline :: DynFlags -> Unfolding -> Bool
smallEnoughToInline dflags (CoreUnfolding {uf_guidance = UnfIfGoodArgs {ug_size = size}})
= size <= ufUseThreshold dflags
smallEnoughToInline _ _
= False
----------------
certainlyWillInline :: DynFlags -> Unfolding -> Maybe Unfolding
-- Sees if the unfolding is pretty certain to inline
-- If so, return a *stable* unfolding for it, that will always inline
certainlyWillInline dflags unf@(CoreUnfolding { uf_guidance = guidance, uf_tmpl = expr })
= case guidance of
UnfNever -> Nothing
UnfWhen {} -> Just (unf { uf_src = InlineStable })
-- The UnfIfGoodArgs case seems important. If we w/w small functions
-- binary sizes go up by 10%! (This is with SplitObjs.) I'm not totally
-- sure whyy.
UnfIfGoodArgs { ug_size = size, ug_args = args }
| not (null args) -- See Note [certainlyWillInline: be careful of thunks]
, let arity = length args
, size - (10 * (arity + 1)) <= ufUseThreshold dflags
-> Just (unf { uf_src = InlineStable
, uf_guidance = UnfWhen { ug_arity = arity
, ug_unsat_ok = unSaturatedOk
, ug_boring_ok = inlineBoringOk expr } })
-- Note the "unsaturatedOk". A function like f = \ab. a
-- will certainly inline, even if partially applied (f e), so we'd
-- better make sure that the transformed inlining has the same property
_ -> Nothing
certainlyWillInline _ unf@(DFunUnfolding {})
= Just unf
certainlyWillInline _ _
= Nothing
{-
Note [certainlyWillInline: be careful of thunks]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Don't claim that thunks will certainly inline, because that risks work
duplication. Even if the work duplication is not great (eg is_cheap
holds), it can make a big difference in an inner loop In Trac #5623 we
found that the WorkWrap phase thought that
y = case x of F# v -> F# (v +# v)
was certainlyWillInline, so the addition got duplicated.
************************************************************************
* *
\subsection{callSiteInline}
* *
************************************************************************
This is the key function. It decides whether to inline a variable at a call site
callSiteInline is used at call sites, so it is a bit more generous.
It's a very important function that embodies lots of heuristics.
A non-WHNF can be inlined if it doesn't occur inside a lambda,
and occurs exactly once or
occurs once in each branch of a case and is small
If the thing is in WHNF, there's no danger of duplicating work,
so we can inline if it occurs once, or is small
NOTE: we don't want to inline top-level functions that always diverge.
It just makes the code bigger. Tt turns out that the convenient way to prevent
them inlining is to give them a NOINLINE pragma, which we do in
StrictAnal.addStrictnessInfoToTopId
-}
callSiteInline :: DynFlags
-> Id -- The Id
-> Bool -- True <=> unfolding is active
-> Bool -- True if there are no arguments at all (incl type args)
-> [ArgSummary] -- One for each value arg; True if it is interesting
-> CallCtxt -- True <=> continuation is interesting
-> Maybe CoreExpr -- Unfolding, if any
data ArgSummary = TrivArg -- Nothing interesting
| NonTrivArg -- Arg has structure
| ValueArg -- Arg is a con-app or PAP
-- ..or con-like. Note [Conlike is interesting]
instance Outputable ArgSummary where
ppr TrivArg = ptext (sLit "TrivArg")
ppr NonTrivArg = ptext (sLit "NonTrivArg")
ppr ValueArg = ptext (sLit "ValueArg")
nonTriv :: ArgSummary -> Bool
nonTriv TrivArg = False
nonTriv _ = True
data CallCtxt
= BoringCtxt
| RhsCtxt -- Rhs of a let-binding; see Note [RHS of lets]
| DiscArgCtxt -- Argument of a fuction with non-zero arg discount
| RuleArgCtxt -- We are somewhere in the argument of a function with rules
| ValAppCtxt -- We're applied to at least one value arg
-- This arises when we have ((f x |> co) y)
-- Then the (f x) has argument 'x' but in a ValAppCtxt
| CaseCtxt -- We're the scrutinee of a case
-- that decomposes its scrutinee
instance Outputable CallCtxt where
ppr CaseCtxt = ptext (sLit "CaseCtxt")
ppr ValAppCtxt = ptext (sLit "ValAppCtxt")
ppr BoringCtxt = ptext (sLit "BoringCtxt")
ppr RhsCtxt = ptext (sLit "RhsCtxt")
ppr DiscArgCtxt = ptext (sLit "DiscArgCtxt")
ppr RuleArgCtxt = ptext (sLit "RuleArgCtxt")
callSiteInline dflags id active_unfolding lone_variable arg_infos cont_info
= case idUnfolding id of
-- idUnfolding checks for loop-breakers, returning NoUnfolding
-- Things with an INLINE pragma may have an unfolding *and*
-- be a loop breaker (maybe the knot is not yet untied)
CoreUnfolding { uf_tmpl = unf_template, uf_is_top = is_top
, uf_is_work_free = is_wf
, uf_guidance = guidance, uf_expandable = is_exp }
| active_unfolding -> tryUnfolding dflags id lone_variable
arg_infos cont_info unf_template is_top
is_wf is_exp guidance
| otherwise -> traceInline dflags "Inactive unfolding:" (ppr id) Nothing
NoUnfolding -> Nothing
OtherCon {} -> Nothing
DFunUnfolding {} -> Nothing -- Never unfold a DFun
traceInline :: DynFlags -> String -> SDoc -> a -> a
traceInline dflags str doc result
| dopt Opt_D_dump_inlinings dflags && dopt Opt_D_verbose_core2core dflags
= pprTrace str doc result
| otherwise
= result
tryUnfolding :: DynFlags -> Id -> Bool -> [ArgSummary] -> CallCtxt
-> CoreExpr -> Bool -> Bool -> Bool -> UnfoldingGuidance
-> Maybe CoreExpr
tryUnfolding dflags id lone_variable
arg_infos cont_info unf_template is_top
is_wf is_exp guidance
= case guidance of
UnfNever -> traceInline dflags str (ptext (sLit "UnfNever")) Nothing
UnfWhen { ug_arity = uf_arity, ug_unsat_ok = unsat_ok, ug_boring_ok = boring_ok }
| enough_args && (boring_ok || some_benefit)
-- See Note [INLINE for small functions (3)]
-> traceInline dflags str (mk_doc some_benefit empty True) (Just unf_template)
| otherwise
-> traceInline dflags str (mk_doc some_benefit empty False) Nothing
where
some_benefit = calc_some_benefit uf_arity
enough_args = (n_val_args >= uf_arity) || (unsat_ok && n_val_args > 0)
UnfIfGoodArgs { ug_args = arg_discounts, ug_res = res_discount, ug_size = size }
| is_wf && some_benefit && small_enough
-> traceInline dflags str (mk_doc some_benefit extra_doc True) (Just unf_template)
| otherwise
-> traceInline dflags str (mk_doc some_benefit extra_doc False) Nothing
where
some_benefit = calc_some_benefit (length arg_discounts)
extra_doc = text "discounted size =" <+> int discounted_size
discounted_size = size - discount
small_enough = discounted_size <= ufUseThreshold dflags
discount = computeDiscount dflags arg_discounts
res_discount arg_infos cont_info
where
mk_doc some_benefit extra_doc yes_or_no
= vcat [ text "arg infos" <+> ppr arg_infos
, text "interesting continuation" <+> ppr cont_info
, text "some_benefit" <+> ppr some_benefit
, text "is exp:" <+> ppr is_exp
, text "is work-free:" <+> ppr is_wf
, text "guidance" <+> ppr guidance
, extra_doc
, text "ANSWER =" <+> if yes_or_no then text "YES" else text "NO"]
str = "Considering inlining: " ++ showSDocDump dflags (ppr id)
n_val_args = length arg_infos
-- some_benefit is used when the RHS is small enough
-- and the call has enough (or too many) value
-- arguments (ie n_val_args >= arity). But there must
-- be *something* interesting about some argument, or the
-- result context, to make it worth inlining
calc_some_benefit :: Arity -> Bool -- The Arity is the number of args
-- expected by the unfolding
calc_some_benefit uf_arity
| not saturated = interesting_args -- Under-saturated
-- Note [Unsaturated applications]
| otherwise = interesting_args -- Saturated or over-saturated
|| interesting_call
where
saturated = n_val_args >= uf_arity
over_saturated = n_val_args > uf_arity
interesting_args = any nonTriv arg_infos
-- NB: (any nonTriv arg_infos) looks at the
-- over-saturated args too which is "wrong";
-- but if over-saturated we inline anyway.
interesting_call
| over_saturated
= True
| otherwise
= case cont_info of
CaseCtxt -> not (lone_variable && is_wf) -- Note [Lone variables]
ValAppCtxt -> True -- Note [Cast then apply]
RuleArgCtxt -> uf_arity > 0 -- See Note [Unfold info lazy contexts]
DiscArgCtxt -> uf_arity > 0 --
RhsCtxt -> uf_arity > 0 --
_ -> not is_top && uf_arity > 0 -- Note [Nested functions]
-- Note [Inlining in ArgCtxt]
{-
Note [Unfold into lazy contexts], Note [RHS of lets]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When the call is the argument of a function with a RULE, or the RHS of a let,
we are a little bit keener to inline. For example
f y = (y,y,y)
g y = let x = f y in ...(case x of (a,b,c) -> ...) ...
We'd inline 'f' if the call was in a case context, and it kind-of-is,
only we can't see it. Also
x = f v
could be expensive whereas
x = case v of (a,b) -> a
is patently cheap and may allow more eta expansion.
So we treat the RHS of a let as not-totally-boring.
Note [Unsaturated applications]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When a call is not saturated, we *still* inline if one of the
arguments has interesting structure. That's sometimes very important.
A good example is the Ord instance for Bool in Base:
Rec {
$fOrdBool =GHC.Classes.D:Ord
@ Bool
...
$cmin_ajX
$cmin_ajX [Occ=LoopBreaker] :: Bool -> Bool -> Bool
$cmin_ajX = GHC.Classes.$dmmin @ Bool $fOrdBool
}
But the defn of GHC.Classes.$dmmin is:
$dmmin :: forall a. GHC.Classes.Ord a => a -> a -> a
{- Arity: 3, HasNoCafRefs, Strictness: SLL,
Unfolding: (\ @ a $dOrd :: GHC.Classes.Ord a x :: a y :: a ->
case @ a GHC.Classes.<= @ a $dOrd x y of wild {
GHC.Types.False -> y GHC.Types.True -> x }) -}
We *really* want to inline $dmmin, even though it has arity 3, in
order to unravel the recursion.
Note [Things to watch]
~~~~~~~~~~~~~~~~~~~~~~
* { y = I# 3; x = y `cast` co; ...case (x `cast` co) of ... }
Assume x is exported, so not inlined unconditionally.
Then we want x to inline unconditionally; no reason for it
not to, and doing so avoids an indirection.
* { x = I# 3; ....f x.... }
Make sure that x does not inline unconditionally!
Lest we get extra allocation.
Note [Inlining an InlineRule]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
An InlineRules is used for
(a) programmer INLINE pragmas
(b) inlinings from worker/wrapper
For (a) the RHS may be large, and our contract is that we *only* inline
when the function is applied to all the arguments on the LHS of the
source-code defn. (The uf_arity in the rule.)
However for worker/wrapper it may be worth inlining even if the
arity is not satisfied (as we do in the CoreUnfolding case) so we don't
require saturation.
Note [Nested functions]
~~~~~~~~~~~~~~~~~~~~~~~
If a function has a nested defn we also record some-benefit, on the
grounds that we are often able to eliminate the binding, and hence the
allocation, for the function altogether; this is good for join points.
But this only makes sense for *functions*; inlining a constructor
doesn't help allocation unless the result is scrutinised. UNLESS the
constructor occurs just once, albeit possibly in multiple case
branches. Then inlining it doesn't increase allocation, but it does
increase the chance that the constructor won't be allocated at all in
the branches that don't use it.
Note [Cast then apply]
~~~~~~~~~~~~~~~~~~~~~~
Consider
myIndex = __inline_me ( (/\a. <blah>) |> co )
co :: (forall a. a -> a) ~ (forall a. T a)
... /\a.\x. case ((myIndex a) |> sym co) x of { ... } ...
We need to inline myIndex to unravel this; but the actual call (myIndex a) has
no value arguments. The ValAppCtxt gives it enough incentive to inline.
Note [Inlining in ArgCtxt]
~~~~~~~~~~~~~~~~~~~~~~~~~~
The condition (arity > 0) here is very important, because otherwise
we end up inlining top-level stuff into useless places; eg
x = I# 3#
f = \y. g x
This can make a very big difference: it adds 16% to nofib 'integer' allocs,
and 20% to 'power'.
At one stage I replaced this condition by 'True' (leading to the above
slow-down). The motivation was test eyeball/inline1.hs; but that seems
to work ok now.
NOTE: arguably, we should inline in ArgCtxt only if the result of the
call is at least CONLIKE. At least for the cases where we use ArgCtxt
for the RHS of a 'let', we only profit from the inlining if we get a
CONLIKE thing (modulo lets).
Note [Lone variables] See also Note [Interaction of exprIsWorkFree and lone variables]
~~~~~~~~~~~~~~~~~~~~~ which appears below
The "lone-variable" case is important. I spent ages messing about
with unsatisfactory varaints, but this is nice. The idea is that if a
variable appears all alone
as an arg of lazy fn, or rhs BoringCtxt
as scrutinee of a case CaseCtxt
as arg of a fn ArgCtxt
AND
it is bound to a cheap expression
then we should not inline it (unless there is some other reason,
e.g. is is the sole occurrence). That is what is happening at
the use of 'lone_variable' in 'interesting_call'.
Why? At least in the case-scrutinee situation, turning
let x = (a,b) in case x of y -> ...
into
let x = (a,b) in case (a,b) of y -> ...
and thence to
let x = (a,b) in let y = (a,b) in ...
is bad if the binding for x will remain.
Another example: I discovered that strings
were getting inlined straight back into applications of 'error'
because the latter is strict.
s = "foo"
f = \x -> ...(error s)...
Fundamentally such contexts should not encourage inlining because the
context can ``see'' the unfolding of the variable (e.g. case or a
RULE) so there's no gain. If the thing is bound to a value.
However, watch out:
* Consider this:
foo = _inline_ (\n. [n])
bar = _inline_ (foo 20)
baz = \n. case bar of { (m:_) -> m + n }
Here we really want to inline 'bar' so that we can inline 'foo'
and the whole thing unravels as it should obviously do. This is
important: in the NDP project, 'bar' generates a closure data
structure rather than a list.
So the non-inlining of lone_variables should only apply if the
unfolding is regarded as cheap; because that is when exprIsConApp_maybe
looks through the unfolding. Hence the "&& is_wf" in the
InlineRule branch.
* Even a type application or coercion isn't a lone variable.
Consider
case $fMonadST @ RealWorld of { :DMonad a b c -> c }
We had better inline that sucker! The case won't see through it.
For now, I'm treating treating a variable applied to types
in a *lazy* context "lone". The motivating example was
f = /\a. \x. BIG
g = /\a. \y. h (f a)
There's no advantage in inlining f here, and perhaps
a significant disadvantage. Hence some_val_args in the Stop case
Note [Interaction of exprIsWorkFree and lone variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The lone-variable test says "don't inline if a case expression
scrutines a lone variable whose unfolding is cheap". It's very
important that, under these circumstances, exprIsConApp_maybe
can spot a constructor application. So, for example, we don't
consider
let x = e in (x,x)
to be cheap, and that's good because exprIsConApp_maybe doesn't
think that expression is a constructor application.
In the 'not (lone_variable && is_wf)' test, I used to test is_value
rather than is_wf, which was utterly wrong, because the above
expression responds True to exprIsHNF, which is what sets is_value.
This kind of thing can occur if you have
{-# INLINE foo #-}
foo = let x = e in (x,x)
which Roman did.
-}
computeDiscount :: DynFlags -> [Int] -> Int -> [ArgSummary] -> CallCtxt
-> Int
computeDiscount dflags arg_discounts res_discount arg_infos cont_info
-- We multiple the raw discounts (args_discount and result_discount)
-- ty opt_UnfoldingKeenessFactor because the former have to do with
-- *size* whereas the discounts imply that there's some extra
-- *efficiency* to be gained (e.g. beta reductions, case reductions)
-- by inlining.
= 10 -- Discount of 10 because the result replaces the call
-- so we count 10 for the function itself
+ 10 * length actual_arg_discounts
-- Discount of 10 for each arg supplied,
-- because the result replaces the call
+ round (ufKeenessFactor dflags *
fromIntegral (total_arg_discount + res_discount'))
where
actual_arg_discounts = zipWith mk_arg_discount arg_discounts arg_infos
total_arg_discount = sum actual_arg_discounts
mk_arg_discount _ TrivArg = 0
mk_arg_discount _ NonTrivArg = 10
mk_arg_discount discount ValueArg = discount
res_discount'
| LT <- arg_discounts `compareLength` arg_infos
= res_discount -- Over-saturated
| otherwise
= case cont_info of
BoringCtxt -> 0
CaseCtxt -> res_discount -- Presumably a constructor
ValAppCtxt -> res_discount -- Presumably a function
_ -> 40 `min` res_discount
-- ToDo: this 40 `min` res_discount doesn't seem right
-- for DiscArgCtxt it shouldn't matter because the function will
-- get the arg discount for any non-triv arg
-- for RuleArgCtxt we do want to be keener to inline; but not only
-- constructor results
-- for RhsCtxt I suppose that exposing a data con is good in general
-- And 40 seems very arbitrary
--
-- res_discount can be very large when a function returns
-- constructors; but we only want to invoke that large discount
-- when there's a case continuation.
-- Otherwise we, rather arbitrarily, threshold it. Yuk.
-- But we want to aovid inlining large functions that return
-- constructors into contexts that are simply "interesting"
| urbanslug/ghc | compiler/coreSyn/CoreUnfold.hs | bsd-3-clause | 58,043 | 0 | 19 | 16,858 | 6,625 | 3,510 | 3,115 | 499 | 32 |
{-# LANGUAGE CPP, GADTs #-}
-----------------------------------------------------------------------------
--
-- Pretty-printing of Cmm as C, suitable for feeding gcc
--
-- (c) The University of Glasgow 2004-2006
--
-- Print Cmm as real C, for -fvia-C
--
-- See wiki:Commentary/Compiler/Backends/PprC
--
-- This is simpler than the old PprAbsC, because Cmm is "macro-expanded"
-- relative to the old AbstractC, and many oddities/decorations have
-- disappeared from the data type.
--
-- This code generator is only supported in unregisterised mode.
--
-----------------------------------------------------------------------------
module PprC (
writeCs,
pprStringInCStyle
) where
#include "HsVersions.h"
-- Cmm stuff
import BlockId
import CLabel
import ForeignCall
import Cmm hiding (pprBBlock)
import PprCmm ()
import Hoopl
import CmmUtils
import CmmSwitch
-- Utils
import CPrim
import DynFlags
import FastString
import Outputable
import Platform
import UniqSet
import Unique
import Util
-- The rest
import Control.Monad.ST
import Data.Bits
import Data.Char
import Data.List
import Data.Map (Map)
import Data.Word
import System.IO
import qualified Data.Map as Map
import Control.Monad (liftM, ap)
#if __GLASGOW_HASKELL__ < 709
import Control.Applicative (Applicative(..))
#endif
import qualified Data.Array.Unsafe as U ( castSTUArray )
import Data.Array.ST
-- --------------------------------------------------------------------------
-- Top level
pprCs :: DynFlags -> [RawCmmGroup] -> SDoc
pprCs dflags cmms
= pprCode CStyle (vcat $ map (\c -> split_marker $$ pprC c) cmms)
where
split_marker
| gopt Opt_SplitObjs dflags = ptext (sLit "__STG_SPLIT_MARKER")
| otherwise = empty
writeCs :: DynFlags -> Handle -> [RawCmmGroup] -> IO ()
writeCs dflags handle cmms
= printForC dflags handle (pprCs dflags cmms)
-- --------------------------------------------------------------------------
-- Now do some real work
--
-- for fun, we could call cmmToCmm over the tops...
--
pprC :: RawCmmGroup -> SDoc
pprC tops = vcat $ intersperse blankLine $ map pprTop tops
--
-- top level procs
--
pprTop :: RawCmmDecl -> SDoc
pprTop (CmmProc infos clbl _ graph) =
(case mapLookup (g_entry graph) infos of
Nothing -> empty
Just (Statics info_clbl info_dat) -> pprDataExterns info_dat $$
pprWordArray info_clbl info_dat) $$
(vcat [
blankLine,
extern_decls,
(if (externallyVisibleCLabel clbl)
then mkFN_ else mkIF_) (ppr clbl) <+> lbrace,
nest 8 temp_decls,
vcat (map pprBBlock blocks),
rbrace ]
)
where
blocks = toBlockListEntryFirst graph
(temp_decls, extern_decls) = pprTempAndExternDecls blocks
-- Chunks of static data.
-- We only handle (a) arrays of word-sized things and (b) strings.
pprTop (CmmData _section (Statics lbl [CmmString str])) =
hcat [
pprLocalness lbl, ptext (sLit "char "), ppr lbl,
ptext (sLit "[] = "), pprStringInCStyle str, semi
]
pprTop (CmmData _section (Statics lbl [CmmUninitialised size])) =
hcat [
pprLocalness lbl, ptext (sLit "char "), ppr lbl,
brackets (int size), semi
]
pprTop (CmmData _section (Statics lbl lits)) =
pprDataExterns lits $$
pprWordArray lbl lits
-- --------------------------------------------------------------------------
-- BasicBlocks are self-contained entities: they always end in a jump.
--
-- Like nativeGen/AsmCodeGen, we could probably reorder blocks to turn
-- as many jumps as possible into fall throughs.
--
pprBBlock :: CmmBlock -> SDoc
pprBBlock block =
nest 4 (pprBlockId (entryLabel block) <> colon) $$
nest 8 (vcat (map pprStmt (blockToList nodes)) $$ pprStmt last)
where
(_, nodes, last) = blockSplit block
-- --------------------------------------------------------------------------
-- Info tables. Just arrays of words.
-- See codeGen/ClosureInfo, and nativeGen/PprMach
pprWordArray :: CLabel -> [CmmStatic] -> SDoc
pprWordArray lbl ds
= sdocWithDynFlags $ \dflags ->
hcat [ pprLocalness lbl, ptext (sLit "StgWord")
, space, ppr lbl, ptext (sLit "[] = {") ]
$$ nest 8 (commafy (pprStatics dflags ds))
$$ ptext (sLit "};")
--
-- has to be static, if it isn't globally visible
--
pprLocalness :: CLabel -> SDoc
pprLocalness lbl | not $ externallyVisibleCLabel lbl = ptext (sLit "static ")
| otherwise = empty
-- --------------------------------------------------------------------------
-- Statements.
--
pprStmt :: CmmNode e x -> SDoc
pprStmt stmt =
sdocWithDynFlags $ \dflags ->
case stmt of
CmmEntry{} -> empty
CmmComment _ -> empty -- (hang (ptext (sLit "/*")) 3 (ftext s)) $$ ptext (sLit "*/")
-- XXX if the string contains "*/", we need to fix it
-- XXX we probably want to emit these comments when
-- some debugging option is on. They can get quite
-- large.
CmmTick _ -> empty
CmmAssign dest src -> pprAssign dflags dest src
CmmStore dest src
| typeWidth rep == W64 && wordWidth dflags /= W64
-> (if isFloatType rep then ptext (sLit "ASSIGN_DBL")
else ptext (sLit ("ASSIGN_Word64"))) <>
parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
| otherwise
-> hsep [ pprExpr (CmmLoad dest rep), equals, pprExpr src <> semi ]
where
rep = cmmExprType dflags src
CmmUnsafeForeignCall target@(ForeignTarget fn conv) results args ->
fnCall
where
(res_hints, arg_hints) = foreignTargetHints target
hresults = zip results res_hints
hargs = zip args arg_hints
ForeignConvention cconv _ _ ret = conv
cast_fn = parens (cCast (pprCFunType (char '*') cconv hresults hargs) fn)
-- See wiki:Commentary/Compiler/Backends/PprC#Prototypes
fnCall =
case fn of
CmmLit (CmmLabel lbl)
| StdCallConv <- cconv ->
pprCall (ppr lbl) cconv hresults hargs
-- stdcall functions must be declared with
-- a function type, otherwise the C compiler
-- doesn't add the @n suffix to the label. We
-- can't add the @n suffix ourselves, because
-- it isn't valid C.
| CmmNeverReturns <- ret ->
pprCall cast_fn cconv hresults hargs <> semi
| not (isMathFun lbl) ->
pprForeignCall (ppr lbl) cconv hresults hargs
_ ->
pprCall cast_fn cconv hresults hargs <> semi
-- for a dynamic call, no declaration is necessary.
CmmUnsafeForeignCall (PrimTarget MO_Touch) _results _args -> empty
CmmUnsafeForeignCall (PrimTarget (MO_Prefetch_Data _)) _results _args -> empty
CmmUnsafeForeignCall target@(PrimTarget op) results args ->
fn_call
where
cconv = CCallConv
fn = pprCallishMachOp_for_C op
(res_hints, arg_hints) = foreignTargetHints target
hresults = zip results res_hints
hargs = zip args arg_hints
fn_call
-- The mem primops carry an extra alignment arg.
-- We could maybe emit an alignment directive using this info.
-- We also need to cast mem primops to prevent conflicts with GCC
-- builtins (see bug #5967).
| Just _align <- machOpMemcpyishAlign op
= (ptext (sLit ";EF_(") <> fn <> char ')' <> semi) $$
pprForeignCall fn cconv hresults hargs
| otherwise
= pprCall fn cconv hresults hargs
CmmBranch ident -> pprBranch ident
CmmCondBranch expr yes no _ -> pprCondBranch expr yes no
CmmCall { cml_target = expr } -> mkJMP_ (pprExpr expr) <> semi
CmmSwitch arg ids -> sdocWithDynFlags $ \dflags ->
pprSwitch dflags arg ids
_other -> pprPanic "PprC.pprStmt" (ppr stmt)
type Hinted a = (a, ForeignHint)
pprForeignCall :: SDoc -> CCallConv -> [Hinted CmmFormal] -> [Hinted CmmActual]
-> SDoc
pprForeignCall fn cconv results args = fn_call
where
fn_call = braces (
pprCFunType (char '*' <> text "ghcFunPtr") cconv results args <> semi
$$ text "ghcFunPtr" <+> equals <+> cast_fn <> semi
$$ pprCall (text "ghcFunPtr") cconv results args <> semi
)
cast_fn = parens (parens (pprCFunType (char '*') cconv results args) <> fn)
pprCFunType :: SDoc -> CCallConv -> [Hinted CmmFormal] -> [Hinted CmmActual] -> SDoc
pprCFunType ppr_fn cconv ress args
= sdocWithDynFlags $ \dflags ->
let res_type [] = ptext (sLit "void")
res_type [(one, hint)] = machRepHintCType (localRegType one) hint
res_type _ = panic "pprCFunType: only void or 1 return value supported"
arg_type (expr, hint) = machRepHintCType (cmmExprType dflags expr) hint
in res_type ress <+>
parens (ccallConvAttribute cconv <> ppr_fn) <>
parens (commafy (map arg_type args))
-- ---------------------------------------------------------------------
-- unconditional branches
pprBranch :: BlockId -> SDoc
pprBranch ident = ptext (sLit "goto") <+> pprBlockId ident <> semi
-- ---------------------------------------------------------------------
-- conditional branches to local labels
pprCondBranch :: CmmExpr -> BlockId -> BlockId -> SDoc
pprCondBranch expr yes no
= hsep [ ptext (sLit "if") , parens(pprExpr expr) ,
ptext (sLit "goto"), pprBlockId yes <> semi,
ptext (sLit "else goto"), pprBlockId no <> semi ]
-- ---------------------------------------------------------------------
-- a local table branch
--
-- we find the fall-through cases
--
pprSwitch :: DynFlags -> CmmExpr -> SwitchTargets -> SDoc
pprSwitch dflags e ids
= (hang (ptext (sLit "switch") <+> parens ( pprExpr e ) <+> lbrace)
4 (vcat ( map caseify pairs ) $$ def)) $$ rbrace
where
(pairs, mbdef) = switchTargetsFallThrough ids
-- fall through case
caseify (ix:ixs, ident) = vcat (map do_fallthrough ixs) $$ final_branch ix
where
do_fallthrough ix =
hsep [ ptext (sLit "case") , pprHexVal ix (wordWidth dflags) <> colon ,
ptext (sLit "/* fall through */") ]
final_branch ix =
hsep [ ptext (sLit "case") , pprHexVal ix (wordWidth dflags) <> colon ,
ptext (sLit "goto") , (pprBlockId ident) <> semi ]
caseify (_ , _ ) = panic "pprSwitch: switch with no cases!"
def | Just l <- mbdef = ptext (sLit "default: goto") <+> pprBlockId l <> semi
| otherwise = empty
-- ---------------------------------------------------------------------
-- Expressions.
--
-- C Types: the invariant is that the C expression generated by
--
-- pprExpr e
--
-- has a type in C which is also given by
--
-- machRepCType (cmmExprType e)
--
-- (similar invariants apply to the rest of the pretty printer).
pprExpr :: CmmExpr -> SDoc
pprExpr e = case e of
CmmLit lit -> pprLit lit
CmmLoad e ty -> sdocWithDynFlags $ \dflags -> pprLoad dflags e ty
CmmReg reg -> pprCastReg reg
CmmRegOff reg 0 -> pprCastReg reg
CmmRegOff reg i
| i < 0 && negate_ok -> pprRegOff (char '-') (-i)
| otherwise -> pprRegOff (char '+') i
where
pprRegOff op i' = pprCastReg reg <> op <> int i'
negate_ok = negate (fromIntegral i :: Integer) <
fromIntegral (maxBound::Int)
-- overflow is undefined; see #7620
CmmMachOp mop args -> pprMachOpApp mop args
CmmStackSlot _ _ -> panic "pprExpr: CmmStackSlot not supported!"
pprLoad :: DynFlags -> CmmExpr -> CmmType -> SDoc
pprLoad dflags e ty
| width == W64, wordWidth dflags /= W64
= (if isFloatType ty then ptext (sLit "PK_DBL")
else ptext (sLit "PK_Word64"))
<> parens (mkP_ <> pprExpr1 e)
| otherwise
= case e of
CmmReg r | isPtrReg r && width == wordWidth dflags && not (isFloatType ty)
-> char '*' <> pprAsPtrReg r
CmmRegOff r 0 | isPtrReg r && width == wordWidth dflags && not (isFloatType ty)
-> char '*' <> pprAsPtrReg r
CmmRegOff r off | isPtrReg r && width == wordWidth dflags
, off `rem` wORD_SIZE dflags == 0 && not (isFloatType ty)
-- ToDo: check that the offset is a word multiple?
-- (For tagging to work, I had to avoid unaligned loads. --ARY)
-> pprAsPtrReg r <> brackets (ppr (off `shiftR` wordShift dflags))
_other -> cLoad e ty
where
width = typeWidth ty
pprExpr1 :: CmmExpr -> SDoc
pprExpr1 (CmmLit lit) = pprLit1 lit
pprExpr1 e@(CmmReg _reg) = pprExpr e
pprExpr1 other = parens (pprExpr other)
-- --------------------------------------------------------------------------
-- MachOp applications
pprMachOpApp :: MachOp -> [CmmExpr] -> SDoc
pprMachOpApp op args
| isMulMayOfloOp op
= ptext (sLit "mulIntMayOflo") <> parens (commafy (map pprExpr args))
where isMulMayOfloOp (MO_U_MulMayOflo _) = True
isMulMayOfloOp (MO_S_MulMayOflo _) = True
isMulMayOfloOp _ = False
pprMachOpApp mop args
| Just ty <- machOpNeedsCast mop
= ty <> parens (pprMachOpApp' mop args)
| otherwise
= pprMachOpApp' mop args
-- Comparisons in C have type 'int', but we want type W_ (this is what
-- resultRepOfMachOp says). The other C operations inherit their type
-- from their operands, so no casting is required.
machOpNeedsCast :: MachOp -> Maybe SDoc
machOpNeedsCast mop
| isComparisonMachOp mop = Just mkW_
| otherwise = Nothing
pprMachOpApp' :: MachOp -> [CmmExpr] -> SDoc
pprMachOpApp' mop args
= case args of
-- dyadic
[x,y] -> pprArg x <+> pprMachOp_for_C mop <+> pprArg y
-- unary
[x] -> pprMachOp_for_C mop <> parens (pprArg x)
_ -> panic "PprC.pprMachOp : machop with wrong number of args"
where
-- Cast needed for signed integer ops
pprArg e | signedOp mop = sdocWithDynFlags $ \dflags ->
cCast (machRep_S_CType (typeWidth (cmmExprType dflags e))) e
| needsFCasts mop = sdocWithDynFlags $ \dflags ->
cCast (machRep_F_CType (typeWidth (cmmExprType dflags e))) e
| otherwise = pprExpr1 e
needsFCasts (MO_F_Eq _) = False
needsFCasts (MO_F_Ne _) = False
needsFCasts (MO_F_Neg _) = True
needsFCasts (MO_F_Quot _) = True
needsFCasts mop = floatComparison mop
-- --------------------------------------------------------------------------
-- Literals
pprLit :: CmmLit -> SDoc
pprLit lit = case lit of
CmmInt i rep -> pprHexVal i rep
CmmFloat f w -> parens (machRep_F_CType w) <> str
where d = fromRational f :: Double
str | isInfinite d && d < 0 = ptext (sLit "-INFINITY")
| isInfinite d = ptext (sLit "INFINITY")
| isNaN d = ptext (sLit "NAN")
| otherwise = text (show d)
-- these constants come from <math.h>
-- see #1861
CmmVec {} -> panic "PprC printing vector literal"
CmmBlock bid -> mkW_ <> pprCLabelAddr (infoTblLbl bid)
CmmHighStackMark -> panic "PprC printing high stack mark"
CmmLabel clbl -> mkW_ <> pprCLabelAddr clbl
CmmLabelOff clbl i -> mkW_ <> pprCLabelAddr clbl <> char '+' <> int i
CmmLabelDiffOff clbl1 _ i
-- WARNING:
-- * the lit must occur in the info table clbl2
-- * clbl1 must be an SRT, a slow entry point or a large bitmap
-> mkW_ <> pprCLabelAddr clbl1 <> char '+' <> int i
where
pprCLabelAddr lbl = char '&' <> ppr lbl
pprLit1 :: CmmLit -> SDoc
pprLit1 lit@(CmmLabelOff _ _) = parens (pprLit lit)
pprLit1 lit@(CmmLabelDiffOff _ _ _) = parens (pprLit lit)
pprLit1 lit@(CmmFloat _ _) = parens (pprLit lit)
pprLit1 other = pprLit other
-- ---------------------------------------------------------------------------
-- Static data
pprStatics :: DynFlags -> [CmmStatic] -> [SDoc]
pprStatics _ [] = []
pprStatics dflags (CmmStaticLit (CmmFloat f W32) : rest)
-- floats are padded to a word, see #1852
| wORD_SIZE dflags == 8, CmmStaticLit (CmmInt 0 W32) : rest' <- rest
= pprLit1 (floatToWord dflags f) : pprStatics dflags rest'
| wORD_SIZE dflags == 4
= pprLit1 (floatToWord dflags f) : pprStatics dflags rest
| otherwise
= pprPanic "pprStatics: float" (vcat (map ppr' rest))
where ppr' (CmmStaticLit l) = sdocWithDynFlags $ \dflags ->
ppr (cmmLitType dflags l)
ppr' _other = ptext (sLit "bad static!")
pprStatics dflags (CmmStaticLit (CmmFloat f W64) : rest)
= map pprLit1 (doubleToWords dflags f) ++ pprStatics dflags rest
pprStatics dflags (CmmStaticLit (CmmInt i W64) : rest)
| wordWidth dflags == W32
= if wORDS_BIGENDIAN dflags
then pprStatics dflags (CmmStaticLit (CmmInt q W32) :
CmmStaticLit (CmmInt r W32) : rest)
else pprStatics dflags (CmmStaticLit (CmmInt r W32) :
CmmStaticLit (CmmInt q W32) : rest)
where r = i .&. 0xffffffff
q = i `shiftR` 32
pprStatics dflags (CmmStaticLit (CmmInt _ w) : _)
| w /= wordWidth dflags
= panic "pprStatics: cannot emit a non-word-sized static literal"
pprStatics dflags (CmmStaticLit lit : rest)
= pprLit1 lit : pprStatics dflags rest
pprStatics _ (other : _)
= pprPanic "pprWord" (pprStatic other)
pprStatic :: CmmStatic -> SDoc
pprStatic s = case s of
CmmStaticLit lit -> nest 4 (pprLit lit)
CmmUninitialised i -> nest 4 (mkC_ <> brackets (int i))
-- these should be inlined, like the old .hc
CmmString s' -> nest 4 (mkW_ <> parens(pprStringInCStyle s'))
-- ---------------------------------------------------------------------------
-- Block Ids
pprBlockId :: BlockId -> SDoc
pprBlockId b = char '_' <> ppr (getUnique b)
-- --------------------------------------------------------------------------
-- Print a MachOp in a way suitable for emitting via C.
--
pprMachOp_for_C :: MachOp -> SDoc
pprMachOp_for_C mop = case mop of
-- Integer operations
MO_Add _ -> char '+'
MO_Sub _ -> char '-'
MO_Eq _ -> ptext (sLit "==")
MO_Ne _ -> ptext (sLit "!=")
MO_Mul _ -> char '*'
MO_S_Quot _ -> char '/'
MO_S_Rem _ -> char '%'
MO_S_Neg _ -> char '-'
MO_U_Quot _ -> char '/'
MO_U_Rem _ -> char '%'
-- & Floating-point operations
MO_F_Add _ -> char '+'
MO_F_Sub _ -> char '-'
MO_F_Neg _ -> char '-'
MO_F_Mul _ -> char '*'
MO_F_Quot _ -> char '/'
-- Signed comparisons
MO_S_Ge _ -> ptext (sLit ">=")
MO_S_Le _ -> ptext (sLit "<=")
MO_S_Gt _ -> char '>'
MO_S_Lt _ -> char '<'
-- & Unsigned comparisons
MO_U_Ge _ -> ptext (sLit ">=")
MO_U_Le _ -> ptext (sLit "<=")
MO_U_Gt _ -> char '>'
MO_U_Lt _ -> char '<'
-- & Floating-point comparisons
MO_F_Eq _ -> ptext (sLit "==")
MO_F_Ne _ -> ptext (sLit "!=")
MO_F_Ge _ -> ptext (sLit ">=")
MO_F_Le _ -> ptext (sLit "<=")
MO_F_Gt _ -> char '>'
MO_F_Lt _ -> char '<'
-- Bitwise operations. Not all of these may be supported at all
-- sizes, and only integral MachReps are valid.
MO_And _ -> char '&'
MO_Or _ -> char '|'
MO_Xor _ -> char '^'
MO_Not _ -> char '~'
MO_Shl _ -> ptext (sLit "<<")
MO_U_Shr _ -> ptext (sLit ">>") -- unsigned shift right
MO_S_Shr _ -> ptext (sLit ">>") -- signed shift right
-- Conversions. Some of these will be NOPs, but never those that convert
-- between ints and floats.
-- Floating-point conversions use the signed variant.
-- We won't know to generate (void*) casts here, but maybe from
-- context elsewhere
-- noop casts
MO_UU_Conv from to | from == to -> empty
MO_UU_Conv _from to -> parens (machRep_U_CType to)
MO_SS_Conv from to | from == to -> empty
MO_SS_Conv _from to -> parens (machRep_S_CType to)
MO_FF_Conv from to | from == to -> empty
MO_FF_Conv _from to -> parens (machRep_F_CType to)
MO_SF_Conv _from to -> parens (machRep_F_CType to)
MO_FS_Conv _from to -> parens (machRep_S_CType to)
MO_S_MulMayOflo _ -> pprTrace "offending mop:"
(ptext $ sLit "MO_S_MulMayOflo")
(panic $ "PprC.pprMachOp_for_C: MO_S_MulMayOflo"
++ " should have been handled earlier!")
MO_U_MulMayOflo _ -> pprTrace "offending mop:"
(ptext $ sLit "MO_U_MulMayOflo")
(panic $ "PprC.pprMachOp_for_C: MO_U_MulMayOflo"
++ " should have been handled earlier!")
MO_V_Insert {} -> pprTrace "offending mop:"
(ptext $ sLit "MO_V_Insert")
(panic $ "PprC.pprMachOp_for_C: MO_V_Insert"
++ " should have been handled earlier!")
MO_V_Extract {} -> pprTrace "offending mop:"
(ptext $ sLit "MO_V_Extract")
(panic $ "PprC.pprMachOp_for_C: MO_V_Extract"
++ " should have been handled earlier!")
MO_V_Add {} -> pprTrace "offending mop:"
(ptext $ sLit "MO_V_Add")
(panic $ "PprC.pprMachOp_for_C: MO_V_Add"
++ " should have been handled earlier!")
MO_V_Sub {} -> pprTrace "offending mop:"
(ptext $ sLit "MO_V_Sub")
(panic $ "PprC.pprMachOp_for_C: MO_V_Sub"
++ " should have been handled earlier!")
MO_V_Mul {} -> pprTrace "offending mop:"
(ptext $ sLit "MO_V_Mul")
(panic $ "PprC.pprMachOp_for_C: MO_V_Mul"
++ " should have been handled earlier!")
MO_VS_Quot {} -> pprTrace "offending mop:"
(ptext $ sLit "MO_VS_Quot")
(panic $ "PprC.pprMachOp_for_C: MO_VS_Quot"
++ " should have been handled earlier!")
MO_VS_Rem {} -> pprTrace "offending mop:"
(ptext $ sLit "MO_VS_Rem")
(panic $ "PprC.pprMachOp_for_C: MO_VS_Rem"
++ " should have been handled earlier!")
MO_VS_Neg {} -> pprTrace "offending mop:"
(ptext $ sLit "MO_VS_Neg")
(panic $ "PprC.pprMachOp_for_C: MO_VS_Neg"
++ " should have been handled earlier!")
MO_VU_Quot {} -> pprTrace "offending mop:"
(ptext $ sLit "MO_VU_Quot")
(panic $ "PprC.pprMachOp_for_C: MO_VU_Quot"
++ " should have been handled earlier!")
MO_VU_Rem {} -> pprTrace "offending mop:"
(ptext $ sLit "MO_VU_Rem")
(panic $ "PprC.pprMachOp_for_C: MO_VU_Rem"
++ " should have been handled earlier!")
MO_VF_Insert {} -> pprTrace "offending mop:"
(ptext $ sLit "MO_VF_Insert")
(panic $ "PprC.pprMachOp_for_C: MO_VF_Insert"
++ " should have been handled earlier!")
MO_VF_Extract {} -> pprTrace "offending mop:"
(ptext $ sLit "MO_VF_Extract")
(panic $ "PprC.pprMachOp_for_C: MO_VF_Extract"
++ " should have been handled earlier!")
MO_VF_Add {} -> pprTrace "offending mop:"
(ptext $ sLit "MO_VF_Add")
(panic $ "PprC.pprMachOp_for_C: MO_VF_Add"
++ " should have been handled earlier!")
MO_VF_Sub {} -> pprTrace "offending mop:"
(ptext $ sLit "MO_VF_Sub")
(panic $ "PprC.pprMachOp_for_C: MO_VF_Sub"
++ " should have been handled earlier!")
MO_VF_Neg {} -> pprTrace "offending mop:"
(ptext $ sLit "MO_VF_Neg")
(panic $ "PprC.pprMachOp_for_C: MO_VF_Neg"
++ " should have been handled earlier!")
MO_VF_Mul {} -> pprTrace "offending mop:"
(ptext $ sLit "MO_VF_Mul")
(panic $ "PprC.pprMachOp_for_C: MO_VF_Mul"
++ " should have been handled earlier!")
MO_VF_Quot {} -> pprTrace "offending mop:"
(ptext $ sLit "MO_VF_Quot")
(panic $ "PprC.pprMachOp_for_C: MO_VF_Quot"
++ " should have been handled earlier!")
signedOp :: MachOp -> Bool -- Argument type(s) are signed ints
signedOp (MO_S_Quot _) = True
signedOp (MO_S_Rem _) = True
signedOp (MO_S_Neg _) = True
signedOp (MO_S_Ge _) = True
signedOp (MO_S_Le _) = True
signedOp (MO_S_Gt _) = True
signedOp (MO_S_Lt _) = True
signedOp (MO_S_Shr _) = True
signedOp (MO_SS_Conv _ _) = True
signedOp (MO_SF_Conv _ _) = True
signedOp _ = False
floatComparison :: MachOp -> Bool -- comparison between float args
floatComparison (MO_F_Eq _) = True
floatComparison (MO_F_Ne _) = True
floatComparison (MO_F_Ge _) = True
floatComparison (MO_F_Le _) = True
floatComparison (MO_F_Gt _) = True
floatComparison (MO_F_Lt _) = True
floatComparison _ = False
-- ---------------------------------------------------------------------
-- tend to be implemented by foreign calls
pprCallishMachOp_for_C :: CallishMachOp -> SDoc
pprCallishMachOp_for_C mop
= case mop of
MO_F64_Pwr -> ptext (sLit "pow")
MO_F64_Sin -> ptext (sLit "sin")
MO_F64_Cos -> ptext (sLit "cos")
MO_F64_Tan -> ptext (sLit "tan")
MO_F64_Sinh -> ptext (sLit "sinh")
MO_F64_Cosh -> ptext (sLit "cosh")
MO_F64_Tanh -> ptext (sLit "tanh")
MO_F64_Asin -> ptext (sLit "asin")
MO_F64_Acos -> ptext (sLit "acos")
MO_F64_Atan -> ptext (sLit "atan")
MO_F64_Log -> ptext (sLit "log")
MO_F64_Exp -> ptext (sLit "exp")
MO_F64_Sqrt -> ptext (sLit "sqrt")
MO_F32_Pwr -> ptext (sLit "powf")
MO_F32_Sin -> ptext (sLit "sinf")
MO_F32_Cos -> ptext (sLit "cosf")
MO_F32_Tan -> ptext (sLit "tanf")
MO_F32_Sinh -> ptext (sLit "sinhf")
MO_F32_Cosh -> ptext (sLit "coshf")
MO_F32_Tanh -> ptext (sLit "tanhf")
MO_F32_Asin -> ptext (sLit "asinf")
MO_F32_Acos -> ptext (sLit "acosf")
MO_F32_Atan -> ptext (sLit "atanf")
MO_F32_Log -> ptext (sLit "logf")
MO_F32_Exp -> ptext (sLit "expf")
MO_F32_Sqrt -> ptext (sLit "sqrtf")
MO_WriteBarrier -> ptext (sLit "write_barrier")
MO_Memcpy _ -> ptext (sLit "memcpy")
MO_Memset _ -> ptext (sLit "memset")
MO_Memmove _ -> ptext (sLit "memmove")
(MO_BSwap w) -> ptext (sLit $ bSwapLabel w)
(MO_PopCnt w) -> ptext (sLit $ popCntLabel w)
(MO_Clz w) -> ptext (sLit $ clzLabel w)
(MO_Ctz w) -> ptext (sLit $ ctzLabel w)
(MO_AtomicRMW w amop) -> ptext (sLit $ atomicRMWLabel w amop)
(MO_Cmpxchg w) -> ptext (sLit $ cmpxchgLabel w)
(MO_AtomicRead w) -> ptext (sLit $ atomicReadLabel w)
(MO_AtomicWrite w) -> ptext (sLit $ atomicWriteLabel w)
(MO_UF_Conv w) -> ptext (sLit $ word2FloatLabel w)
MO_S_QuotRem {} -> unsupported
MO_U_QuotRem {} -> unsupported
MO_U_QuotRem2 {} -> unsupported
MO_Add2 {} -> unsupported
MO_AddIntC {} -> unsupported
MO_SubIntC {} -> unsupported
MO_U_Mul2 {} -> unsupported
MO_Touch -> unsupported
(MO_Prefetch_Data _ ) -> unsupported
--- we could support prefetch via "__builtin_prefetch"
--- Not adding it for now
where unsupported = panic ("pprCallishMachOp_for_C: " ++ show mop
++ " not supported!")
-- ---------------------------------------------------------------------
-- Useful #defines
--
mkJMP_, mkFN_, mkIF_ :: SDoc -> SDoc
mkJMP_ i = ptext (sLit "JMP_") <> parens i
mkFN_ i = ptext (sLit "FN_") <> parens i -- externally visible function
mkIF_ i = ptext (sLit "IF_") <> parens i -- locally visible
-- from includes/Stg.h
--
mkC_,mkW_,mkP_ :: SDoc
mkC_ = ptext (sLit "(C_)") -- StgChar
mkW_ = ptext (sLit "(W_)") -- StgWord
mkP_ = ptext (sLit "(P_)") -- StgWord*
-- ---------------------------------------------------------------------
--
-- Assignments
--
-- Generating assignments is what we're all about, here
--
pprAssign :: DynFlags -> CmmReg -> CmmExpr -> SDoc
-- dest is a reg, rhs is a reg
pprAssign _ r1 (CmmReg r2)
| isPtrReg r1 && isPtrReg r2
= hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, semi ]
-- dest is a reg, rhs is a CmmRegOff
pprAssign dflags r1 (CmmRegOff r2 off)
| isPtrReg r1 && isPtrReg r2 && (off `rem` wORD_SIZE dflags == 0)
= hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, op, int off', semi ]
where
off1 = off `shiftR` wordShift dflags
(op,off') | off >= 0 = (char '+', off1)
| otherwise = (char '-', -off1)
-- dest is a reg, rhs is anything.
-- We can't cast the lvalue, so we have to cast the rhs if necessary. Casting
-- the lvalue elicits a warning from new GCC versions (3.4+).
pprAssign _ r1 r2
| isFixedPtrReg r1 = mkAssign (mkP_ <> pprExpr1 r2)
| Just ty <- strangeRegType r1 = mkAssign (parens ty <> pprExpr1 r2)
| otherwise = mkAssign (pprExpr r2)
where mkAssign x = if r1 == CmmGlobal BaseReg
then ptext (sLit "ASSIGN_BaseReg") <> parens x <> semi
else pprReg r1 <> ptext (sLit " = ") <> x <> semi
-- ---------------------------------------------------------------------
-- Registers
pprCastReg :: CmmReg -> SDoc
pprCastReg reg
| isStrangeTypeReg reg = mkW_ <> pprReg reg
| otherwise = pprReg reg
-- True if (pprReg reg) will give an expression with type StgPtr. We
-- need to take care with pointer arithmetic on registers with type
-- StgPtr.
isFixedPtrReg :: CmmReg -> Bool
isFixedPtrReg (CmmLocal _) = False
isFixedPtrReg (CmmGlobal r) = isFixedPtrGlobalReg r
-- True if (pprAsPtrReg reg) will give an expression with type StgPtr
-- JD: THIS IS HORRIBLE AND SHOULD BE RENAMED, AT THE VERY LEAST.
-- THE GARBAGE WITH THE VNonGcPtr HELPS MATCH THE OLD CODE GENERATOR'S OUTPUT;
-- I'M NOT SURE IF IT SHOULD REALLY STAY THAT WAY.
isPtrReg :: CmmReg -> Bool
isPtrReg (CmmLocal _) = False
isPtrReg (CmmGlobal (VanillaReg _ VGcPtr)) = True -- if we print via pprAsPtrReg
isPtrReg (CmmGlobal (VanillaReg _ VNonGcPtr)) = False -- if we print via pprAsPtrReg
isPtrReg (CmmGlobal reg) = isFixedPtrGlobalReg reg
-- True if this global reg has type StgPtr
isFixedPtrGlobalReg :: GlobalReg -> Bool
isFixedPtrGlobalReg Sp = True
isFixedPtrGlobalReg Hp = True
isFixedPtrGlobalReg HpLim = True
isFixedPtrGlobalReg SpLim = True
isFixedPtrGlobalReg _ = False
-- True if in C this register doesn't have the type given by
-- (machRepCType (cmmRegType reg)), so it has to be cast.
isStrangeTypeReg :: CmmReg -> Bool
isStrangeTypeReg (CmmLocal _) = False
isStrangeTypeReg (CmmGlobal g) = isStrangeTypeGlobal g
isStrangeTypeGlobal :: GlobalReg -> Bool
isStrangeTypeGlobal CCCS = True
isStrangeTypeGlobal CurrentTSO = True
isStrangeTypeGlobal CurrentNursery = True
isStrangeTypeGlobal BaseReg = True
isStrangeTypeGlobal r = isFixedPtrGlobalReg r
strangeRegType :: CmmReg -> Maybe SDoc
strangeRegType (CmmGlobal CCCS) = Just (ptext (sLit "struct CostCentreStack_ *"))
strangeRegType (CmmGlobal CurrentTSO) = Just (ptext (sLit "struct StgTSO_ *"))
strangeRegType (CmmGlobal CurrentNursery) = Just (ptext (sLit "struct bdescr_ *"))
strangeRegType (CmmGlobal BaseReg) = Just (ptext (sLit "struct StgRegTable_ *"))
strangeRegType _ = Nothing
-- pprReg just prints the register name.
--
pprReg :: CmmReg -> SDoc
pprReg r = case r of
CmmLocal local -> pprLocalReg local
CmmGlobal global -> pprGlobalReg global
pprAsPtrReg :: CmmReg -> SDoc
pprAsPtrReg (CmmGlobal (VanillaReg n gcp))
= WARN( gcp /= VGcPtr, ppr n ) char 'R' <> int n <> ptext (sLit ".p")
pprAsPtrReg other_reg = pprReg other_reg
pprGlobalReg :: GlobalReg -> SDoc
pprGlobalReg gr = case gr of
VanillaReg n _ -> char 'R' <> int n <> ptext (sLit ".w")
-- pprGlobalReg prints a VanillaReg as a .w regardless
-- Example: R1.w = R1.w & (-0x8UL);
-- JMP_(*R1.p);
FloatReg n -> char 'F' <> int n
DoubleReg n -> char 'D' <> int n
LongReg n -> char 'L' <> int n
Sp -> ptext (sLit "Sp")
SpLim -> ptext (sLit "SpLim")
Hp -> ptext (sLit "Hp")
HpLim -> ptext (sLit "HpLim")
CCCS -> ptext (sLit "CCCS")
CurrentTSO -> ptext (sLit "CurrentTSO")
CurrentNursery -> ptext (sLit "CurrentNursery")
HpAlloc -> ptext (sLit "HpAlloc")
BaseReg -> ptext (sLit "BaseReg")
EagerBlackholeInfo -> ptext (sLit "stg_EAGER_BLACKHOLE_info")
GCEnter1 -> ptext (sLit "stg_gc_enter_1")
GCFun -> ptext (sLit "stg_gc_fun")
other -> panic $ "pprGlobalReg: Unsupported register: " ++ show other
pprLocalReg :: LocalReg -> SDoc
pprLocalReg (LocalReg uniq _) = char '_' <> ppr uniq
-- -----------------------------------------------------------------------------
-- Foreign Calls
pprCall :: SDoc -> CCallConv -> [Hinted CmmFormal] -> [Hinted CmmActual] -> SDoc
pprCall ppr_fn cconv results args
| not (is_cishCC cconv)
= panic $ "pprCall: unknown calling convention"
| otherwise
=
ppr_assign results (ppr_fn <> parens (commafy (map pprArg args))) <> semi
where
ppr_assign [] rhs = rhs
ppr_assign [(one,hint)] rhs
= pprLocalReg one <> ptext (sLit " = ")
<> pprUnHint hint (localRegType one) <> rhs
ppr_assign _other _rhs = panic "pprCall: multiple results"
pprArg (expr, AddrHint)
= cCast (ptext (sLit "void *")) expr
-- see comment by machRepHintCType below
pprArg (expr, SignedHint)
= sdocWithDynFlags $ \dflags ->
cCast (machRep_S_CType $ typeWidth $ cmmExprType dflags expr) expr
pprArg (expr, _other)
= pprExpr expr
pprUnHint AddrHint rep = parens (machRepCType rep)
pprUnHint SignedHint rep = parens (machRepCType rep)
pprUnHint _ _ = empty
-- Currently we only have these two calling conventions, but this might
-- change in the future...
is_cishCC :: CCallConv -> Bool
is_cishCC CCallConv = True
is_cishCC CApiConv = True
is_cishCC StdCallConv = True
is_cishCC PrimCallConv = False
is_cishCC JavaScriptCallConv = False
-- ---------------------------------------------------------------------
-- Find and print local and external declarations for a list of
-- Cmm statements.
--
pprTempAndExternDecls :: [CmmBlock] -> (SDoc{-temps-}, SDoc{-externs-})
pprTempAndExternDecls stmts
= (vcat (map pprTempDecl (uniqSetToList temps)),
vcat (map (pprExternDecl False{-ToDo-}) (Map.keys lbls)))
where (temps, lbls) = runTE (mapM_ te_BB stmts)
pprDataExterns :: [CmmStatic] -> SDoc
pprDataExterns statics
= vcat (map (pprExternDecl False{-ToDo-}) (Map.keys lbls))
where (_, lbls) = runTE (mapM_ te_Static statics)
pprTempDecl :: LocalReg -> SDoc
pprTempDecl l@(LocalReg _ rep)
= hcat [ machRepCType rep, space, pprLocalReg l, semi ]
pprExternDecl :: Bool -> CLabel -> SDoc
pprExternDecl _in_srt lbl
-- do not print anything for "known external" things
| not (needsCDecl lbl) = empty
| Just sz <- foreignLabelStdcallInfo lbl = stdcall_decl sz
| otherwise =
hcat [ visibility, label_type lbl,
lparen, ppr lbl, text ");" ]
where
label_type lbl | isCFunctionLabel lbl = ptext (sLit "F_")
| otherwise = ptext (sLit "I_")
visibility
| externallyVisibleCLabel lbl = char 'E'
| otherwise = char 'I'
-- If the label we want to refer to is a stdcall function (on Windows) then
-- we must generate an appropriate prototype for it, so that the C compiler will
-- add the @n suffix to the label (#2276)
stdcall_decl sz = sdocWithDynFlags $ \dflags ->
ptext (sLit "extern __attribute__((stdcall)) void ") <> ppr lbl
<> parens (commafy (replicate (sz `quot` wORD_SIZE dflags) (machRep_U_CType (wordWidth dflags))))
<> semi
type TEState = (UniqSet LocalReg, Map CLabel ())
newtype TE a = TE { unTE :: TEState -> (a, TEState) }
instance Functor TE where
fmap = liftM
instance Applicative TE where
pure = return
(<*>) = ap
instance Monad TE where
TE m >>= k = TE $ \s -> case m s of (a, s') -> unTE (k a) s'
return a = TE $ \s -> (a, s)
te_lbl :: CLabel -> TE ()
te_lbl lbl = TE $ \(temps,lbls) -> ((), (temps, Map.insert lbl () lbls))
te_temp :: LocalReg -> TE ()
te_temp r = TE $ \(temps,lbls) -> ((), (addOneToUniqSet temps r, lbls))
runTE :: TE () -> TEState
runTE (TE m) = snd (m (emptyUniqSet, Map.empty))
te_Static :: CmmStatic -> TE ()
te_Static (CmmStaticLit lit) = te_Lit lit
te_Static _ = return ()
te_BB :: CmmBlock -> TE ()
te_BB block = mapM_ te_Stmt (blockToList mid) >> te_Stmt last
where (_, mid, last) = blockSplit block
te_Lit :: CmmLit -> TE ()
te_Lit (CmmLabel l) = te_lbl l
te_Lit (CmmLabelOff l _) = te_lbl l
te_Lit (CmmLabelDiffOff l1 _ _) = te_lbl l1
te_Lit _ = return ()
te_Stmt :: CmmNode e x -> TE ()
te_Stmt (CmmAssign r e) = te_Reg r >> te_Expr e
te_Stmt (CmmStore l r) = te_Expr l >> te_Expr r
te_Stmt (CmmUnsafeForeignCall target rs es)
= do te_Target target
mapM_ te_temp rs
mapM_ te_Expr es
te_Stmt (CmmCondBranch e _ _ _) = te_Expr e
te_Stmt (CmmSwitch e _) = te_Expr e
te_Stmt (CmmCall { cml_target = e }) = te_Expr e
te_Stmt _ = return ()
te_Target :: ForeignTarget -> TE ()
te_Target (ForeignTarget e _) = te_Expr e
te_Target (PrimTarget{}) = return ()
te_Expr :: CmmExpr -> TE ()
te_Expr (CmmLit lit) = te_Lit lit
te_Expr (CmmLoad e _) = te_Expr e
te_Expr (CmmReg r) = te_Reg r
te_Expr (CmmMachOp _ es) = mapM_ te_Expr es
te_Expr (CmmRegOff r _) = te_Reg r
te_Expr (CmmStackSlot _ _) = panic "te_Expr: CmmStackSlot not supported!"
te_Reg :: CmmReg -> TE ()
te_Reg (CmmLocal l) = te_temp l
te_Reg _ = return ()
-- ---------------------------------------------------------------------
-- C types for MachReps
cCast :: SDoc -> CmmExpr -> SDoc
cCast ty expr = parens ty <> pprExpr1 expr
cLoad :: CmmExpr -> CmmType -> SDoc
cLoad expr rep
= sdocWithPlatform $ \platform ->
if bewareLoadStoreAlignment (platformArch platform)
then let decl = machRepCType rep <+> ptext (sLit "x") <> semi
struct = ptext (sLit "struct") <+> braces (decl)
packed_attr = ptext (sLit "__attribute__((packed))")
cast = parens (struct <+> packed_attr <> char '*')
in parens (cast <+> pprExpr1 expr) <> ptext (sLit "->x")
else char '*' <> parens (cCast (machRepPtrCType rep) expr)
where -- On these platforms, unaligned loads are known to cause problems
bewareLoadStoreAlignment ArchAlpha = True
bewareLoadStoreAlignment ArchMipseb = True
bewareLoadStoreAlignment ArchMipsel = True
bewareLoadStoreAlignment (ArchARM {}) = True
bewareLoadStoreAlignment ArchARM64 = True
-- Pessimistically assume that they will also cause problems
-- on unknown arches
bewareLoadStoreAlignment ArchUnknown = True
bewareLoadStoreAlignment _ = False
isCmmWordType :: DynFlags -> CmmType -> Bool
-- True of GcPtrReg/NonGcReg of native word size
isCmmWordType dflags ty = not (isFloatType ty)
&& typeWidth ty == wordWidth dflags
-- This is for finding the types of foreign call arguments. For a pointer
-- argument, we always cast the argument to (void *), to avoid warnings from
-- the C compiler.
machRepHintCType :: CmmType -> ForeignHint -> SDoc
machRepHintCType _ AddrHint = ptext (sLit "void *")
machRepHintCType rep SignedHint = machRep_S_CType (typeWidth rep)
machRepHintCType rep _other = machRepCType rep
machRepPtrCType :: CmmType -> SDoc
machRepPtrCType r
= sdocWithDynFlags $ \dflags ->
if isCmmWordType dflags r then ptext (sLit "P_")
else machRepCType r <> char '*'
machRepCType :: CmmType -> SDoc
machRepCType ty | isFloatType ty = machRep_F_CType w
| otherwise = machRep_U_CType w
where
w = typeWidth ty
machRep_F_CType :: Width -> SDoc
machRep_F_CType W32 = ptext (sLit "StgFloat") -- ToDo: correct?
machRep_F_CType W64 = ptext (sLit "StgDouble")
machRep_F_CType _ = panic "machRep_F_CType"
machRep_U_CType :: Width -> SDoc
machRep_U_CType w
= sdocWithDynFlags $ \dflags ->
case w of
_ | w == wordWidth dflags -> ptext (sLit "W_")
W8 -> ptext (sLit "StgWord8")
W16 -> ptext (sLit "StgWord16")
W32 -> ptext (sLit "StgWord32")
W64 -> ptext (sLit "StgWord64")
_ -> panic "machRep_U_CType"
machRep_S_CType :: Width -> SDoc
machRep_S_CType w
= sdocWithDynFlags $ \dflags ->
case w of
_ | w == wordWidth dflags -> ptext (sLit "I_")
W8 -> ptext (sLit "StgInt8")
W16 -> ptext (sLit "StgInt16")
W32 -> ptext (sLit "StgInt32")
W64 -> ptext (sLit "StgInt64")
_ -> panic "machRep_S_CType"
-- ---------------------------------------------------------------------
-- print strings as valid C strings
pprStringInCStyle :: [Word8] -> SDoc
pprStringInCStyle s = doubleQuotes (text (concatMap charToC s))
-- ---------------------------------------------------------------------------
-- Initialising static objects with floating-point numbers. We can't
-- just emit the floating point number, because C will cast it to an int
-- by rounding it. We want the actual bit-representation of the float.
-- This is a hack to turn the floating point numbers into ints that we
-- can safely initialise to static locations.
big_doubles :: DynFlags -> Bool
big_doubles dflags
| widthInBytes W64 == 2 * wORD_SIZE dflags = True
| widthInBytes W64 == wORD_SIZE dflags = False
| otherwise = panic "big_doubles"
castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int)
castFloatToIntArray = U.castSTUArray
castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int)
castDoubleToIntArray = U.castSTUArray
-- floats are always 1 word
floatToWord :: DynFlags -> Rational -> CmmLit
floatToWord dflags r
= runST (do
arr <- newArray_ ((0::Int),0)
writeArray arr 0 (fromRational r)
arr' <- castFloatToIntArray arr
i <- readArray arr' 0
return (CmmInt (toInteger i) (wordWidth dflags))
)
doubleToWords :: DynFlags -> Rational -> [CmmLit]
doubleToWords dflags r
| big_doubles dflags -- doubles are 2 words
= runST (do
arr <- newArray_ ((0::Int),1)
writeArray arr 0 (fromRational r)
arr' <- castDoubleToIntArray arr
i1 <- readArray arr' 0
i2 <- readArray arr' 1
return [ CmmInt (toInteger i1) (wordWidth dflags)
, CmmInt (toInteger i2) (wordWidth dflags)
]
)
| otherwise -- doubles are 1 word
= runST (do
arr <- newArray_ ((0::Int),0)
writeArray arr 0 (fromRational r)
arr' <- castDoubleToIntArray arr
i <- readArray arr' 0
return [ CmmInt (toInteger i) (wordWidth dflags) ]
)
-- ---------------------------------------------------------------------------
-- Utils
wordShift :: DynFlags -> Int
wordShift dflags = widthInLog (wordWidth dflags)
commafy :: [SDoc] -> SDoc
commafy xs = hsep $ punctuate comma xs
-- Print in C hex format: 0x13fa
pprHexVal :: Integer -> Width -> SDoc
pprHexVal w rep
| w < 0 = parens (char '-' <>
ptext (sLit "0x") <> intToDoc (-w) <> repsuffix rep)
| otherwise = ptext (sLit "0x") <> intToDoc w <> repsuffix rep
where
-- type suffix for literals:
-- Integer literals are unsigned in Cmm/C. We explicitly cast to
-- signed values for doing signed operations, but at all other
-- times values are unsigned. This also helps eliminate occasional
-- warnings about integer overflow from gcc.
repsuffix W64 = sdocWithDynFlags $ \dflags ->
if cINT_SIZE dflags == 8 then char 'U'
else if cLONG_SIZE dflags == 8 then ptext (sLit "UL")
else if cLONG_LONG_SIZE dflags == 8 then ptext (sLit "ULL")
else panic "pprHexVal: Can't find a 64-bit type"
repsuffix _ = char 'U'
intToDoc :: Integer -> SDoc
intToDoc i = case truncInt i of
0 -> char '0'
v -> go v
-- We need to truncate value as Cmm backend does not drop
-- redundant bits to ease handling of negative values.
-- Thus the following Cmm code on 64-bit arch, like amd64:
-- CInt v;
-- v = {something};
-- if (v == %lobits32(-1)) { ...
-- leads to the following C code:
-- StgWord64 v = (StgWord32)({something});
-- if (v == 0xFFFFffffFFFFffffU) { ...
-- Such code is incorrect as it promotes both operands to StgWord64
-- and the whole condition is always false.
truncInt :: Integer -> Integer
truncInt i =
case rep of
W8 -> i `rem` (2^(8 :: Int))
W16 -> i `rem` (2^(16 :: Int))
W32 -> i `rem` (2^(32 :: Int))
W64 -> i `rem` (2^(64 :: Int))
_ -> panic ("pprHexVal/truncInt: C backend can't encode "
++ show rep ++ " literals")
go 0 = empty
go w' = go q <> dig
where
(q,r) = w' `quotRem` 16
dig | r < 10 = char (chr (fromInteger r + ord '0'))
| otherwise = char (chr (fromInteger r - 10 + ord 'a'))
| ml9951/ghc | compiler/cmm/PprC.hs | bsd-3-clause | 48,276 | 0 | 20 | 14,615 | 12,623 | 6,256 | 6,367 | 824 | 63 |
module Interpreter where
{-@ LIQUID "--totality" @-}
{-@ LIQUID "--real" @-}
data BinOp a = Plus | Times
data Exp a = EConst Int | EBinOp (BinOp a) (Exp a) (Exp a)
data Instr a = IConst Int | IBinOp (BinOp a)
data List a = Nil | Cons a (List a)
{-@ autosize Prog @-}
data Prog a = Emp | PInst (Instr a) (Prog a)
type Stack = List Int
data SMaybe a = SNothing a | SJust a
{-@ measure binOpDenote @-}
binOpDenote :: Int -> Int -> BinOp a -> Int
binOpDenote x y Plus = (x+y)
binOpDenote x y Times = (x*y)
{-@ measure expDenote @-}
expDenote :: Exp a -> Int
expDenote (EConst n) = n
expDenote (EBinOp b e1 e2) = binOpDenote (expDenote e1) (expDenote e2) b
{- HERE HERE -}
{-@foo :: s:Stack -> {v:SMaybe Stack| v = SNothing s || v = SJust s } @-}
foo :: Stack -> SMaybe Stack
foo = undefined
{-@ measure instrDenote @-}
instrDenote :: Stack -> Instr a -> SMaybe Stack
{-@ instrDenote :: s:Stack -> i:{v:Instr a | isIBinOp v => lenL s >= 2}
-> {v:SMaybe {st:Stack | if (isIBinOp i) then (lenL st = lenL s - 1) else (lenL st = lenL s + 1)} | v = instrDenote s i} @-}
instrDenote s (IConst n) = SJust (Cons n s)
instrDenote s (IBinOp b) =
let x = headL s in
let s1 = tailL s in
let y = headL s1 in
let s2 = tailL s1 in
SJust (Cons (binOpDenote x y b) s2)
{-@ invariant {v:Prog a | binOps v >= 0} @-}
{-@ measure binOps @-}
binOps :: Prog a -> Int
binOps Emp = 0
binOps (PInst x xs) = if isIBinOp x then 1 + (binOps xs) else binOps xs
{- measure progDenote :: Stack -> Prog -> SMaybe Stack @-}
{-@ Decrease progDenote 2 @-}
progDenote :: Stack -> Prog a -> SMaybe Stack
{-@ progDenote :: s:Stack -> {v:Prog a | lenL s >= 2 * binOps v } -> SMaybe Stack @-}
progDenote s Emp = SJust s
progDenote s (PInst x xs) | SJust s' <- instrDenote s x = progDenote s' xs
| otherwise = SNothing s
{-
{- compile :: e:Exp -> {v:Prog | (progDenote Nil v) == Nothing } @-}
{- compile :: e:Exp -> {v:Prog | (progDenote Nil v) == Just (Cons (expDenote e) Nil)} @-}
compile :: Exp -> Prog
compile (EConst n) = single (IConst n)
compile (EBinOp b e1 e2) = compile e2 `append` compile e1 `append` (single $ IBinOp b)
-}
-- Hard Wire the measures so that I can provide exact types for Nil and Cons
{-@ SNothing :: s:s -> {v:SMaybe s | v = SNothing s && not (isSJust v)} @-}
{-@ SJust :: s:s -> {v:SMaybe s | v = SJust s && (isSJust v) && (fromSJust v = s)} @-}
{-@ Cons :: x:a -> xs:List a -> {v:List a | v = Cons x xs && headL v = x && tailL v = xs && lenL v = 1 + lenL xs} @-}
{-@ Nil :: {v:List a | v = Nil && lenL v = 0} @-}
iconst = IConst
{-@ measure isSJust :: SMaybe a -> Prop @-}
{-@ isSJust :: x:SMaybe a -> {v:Bool | Prop v <=> isSJust x} @-}
isSJust (SJust _) = True
isSJust (SNothing _ ) = False
{-@ measure fromSJust :: SMaybe a -> a @-}
{-@ fromSJust :: x:{v:SMaybe a | isSJust v} -> {v:a | v = fromSJust x} @-}
fromSJust (SJust x) = x
{-@ measure isIBinOp @-}
isIBinOp (IBinOp _) = True
isIBinOp _ = False
{-@ measure headL :: List a -> a @-}
{-@ headL :: xs:{v:List a | lenL v > 0} -> {v:a | v = headL xs} @-}
headL :: List a -> a
headL (Cons x _) = x
{-@ measure tailL :: List a -> List a @-}
{-@ tailL :: xs:{v:List a | lenL v > 0} -> {v: List a | v = tailL xs && lenL v = lenL xs - 1} @-}
tailL :: List a -> List a
tailL (Cons _ xs) = xs
{-@ measure lenL :: List a -> Int @-}
{-@ invariant {v:List a | lenL v >= 0 } @-}
lenL :: List a -> Int
lenL (Cons _ xs) = 1 + lenL xs
lenL Nil = 0
-- List operations
{-@ autosize Exp @-}
{-@ data List [lenL] @-}
(Cons x xs) `append` ys = cons x $ append xs ys
Nil `append` ys = ys
emp = Nil
single x = Cons x Nil
cons x xs = Cons x xs
| mightymoose/liquidhaskell | tests/todo/Interpreter.hs | bsd-3-clause | 3,744 | 10 | 17 | 981 | 861 | 448 | 413 | 49 | 2 |
module Reddit.Types.ListingSpec where
import Reddit.Types.Comment
import Reddit.Types.Listing
import Control.Monad
import Data.Aeson (eitherDecode)
import Network.API.Builder
import Test.Hspec
import Test.Hspec.QuickCheck
import qualified Data.ByteString.Lazy.Char8 as ByteString
isRight :: Either a b -> Bool
isRight = const False `either` const True
isLeft :: Either a b -> Bool
isLeft = const True `either` const False
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "Reddit.Types.Listing" $ do
describe "Listing" $ do
getUserCommentsExample <- runIO $ ByteString.readFile "test/data/getUserComments_example.json"
it "can read the example" $
getUserCommentsExample `shouldSatisfy` not . ByteString.null
it "can parse a listing from json" $ do
let decoded = eitherDecode getUserCommentsExample :: Either String CommentListing
decoded `shouldSatisfy` isRight
case decoded of
Left _ -> expectationFailure "json parse failed"
Right (Listing b a _) -> do
a `shouldBe` Just (CommentID "cl1royq")
b `shouldBe` Nothing
describe "has a valid Functor instance" $ do
prop "length l = length (fmap f l)" $ \xs ->
let l = Listing Nothing Nothing (xs :: [()]) in
length (contents (l :: Listing () ())) == length (contents (void l))
prop "fmap id x == x" $ \xs ->
let l = Listing Nothing Nothing (xs :: [String]) in
fmap id l == (l :: Listing () String)
it "can parse listings from empty strings" $ do
let decoded :: Either String CommentListing
decoded = eitherDecode "\"\""
decoded `shouldBe` Right (Listing Nothing Nothing [])
it "can parse listings from null" $ do
let decoded :: Either String CommentListing
decoded = eitherDecode "null"
decoded `shouldBe` Right (Listing Nothing Nothing [])
describe "ListingType" $
it "should have a valid ToQuery instance" $ do
toQuery "type" Hot `shouldBe` [("type", "hot")]
toQuery "type" New `shouldBe` [("type", "new")]
toQuery "type" Rising `shouldBe` [("type", "rising")]
toQuery "type" Controversial `shouldBe` [("type", "controversial")]
toQuery "type" Top `shouldBe` [("type", "top")]
| FranklinChen/reddit | test/Reddit/Types/ListingSpec.hs | bsd-2-clause | 2,261 | 0 | 24 | 522 | 715 | 365 | 350 | -1 | -1 |
{-# LANGUAGE CPP, ScopedTypeVariables, MagicHash, UnboxedTuples #-}
-----------------------------------------------------------------------------
--
-- GHC Interactive support for inspecting arbitrary closures at runtime
--
-- Pepe Iborra (supported by Google SoC) 2006
--
-----------------------------------------------------------------------------
module RtClosureInspect(
cvObtainTerm, -- :: HscEnv -> Int -> Bool -> Maybe Type -> HValue -> IO Term
cvReconstructType,
improveRTTIType,
Term(..),
isTerm, isSuspension, isPrim, isFun, isFunLike, isNewtypeWrap,
isFullyEvaluated, isFullyEvaluatedTerm,
termType, mapTermType, termTyVars,
foldTerm, TermFold(..), foldTermM, TermFoldM(..), idTermFold,
pprTerm, cPprTerm, cPprTermBase, CustomTermPrinter,
-- unsafeDeepSeq,
Closure(..), getClosureData, ClosureType(..), isConstr, isIndirection
) where
#include "HsVersions.h"
import DebuggerUtils
import ByteCodeItbls ( StgInfoTable, peekItbl )
import qualified ByteCodeItbls as BCI( StgInfoTable(..) )
import BasicTypes ( HValue )
import HscTypes
import DataCon
import Type
import qualified Unify as U
import Var
import TcRnMonad
import TcType
import TcMType
import TcHsSyn ( zonkTcTypeToType, mkEmptyZonkEnv )
import TcUnify
import TcEnv
import TyCon
import Name
import VarEnv
import Util
import VarSet
import BasicTypes ( TupleSort(UnboxedTuple) )
import TysPrim
import PrelNames
import TysWiredIn
import DynFlags
import Outputable as Ppr
import GHC.Arr ( Array(..) )
import GHC.Exts
import GHC.IO ( IO(..) )
import StaticFlags( opt_PprStyle_Debug )
import Control.Monad
import Data.Maybe
import Data.Array.Base
import Data.Ix
import Data.List
import qualified Data.Sequence as Seq
#if __GLASGOW_HASKELL__ < 709
import Data.Monoid (mappend)
#endif
import Data.Sequence (viewl, ViewL(..))
#if __GLASGOW_HASKELL__ >= 709
import Foreign
#else
import Foreign.Safe
#endif
import System.IO.Unsafe
---------------------------------------------
-- * A representation of semi evaluated Terms
---------------------------------------------
data Term = Term { ty :: RttiType
, dc :: Either String DataCon
-- Carries a text representation if the datacon is
-- not exported by the .hi file, which is the case
-- for private constructors in -O0 compiled libraries
, val :: HValue
, subTerms :: [Term] }
| Prim { ty :: RttiType
, value :: [Word] }
| Suspension { ctype :: ClosureType
, ty :: RttiType
, val :: HValue
, bound_to :: Maybe Name -- Useful for printing
}
| NewtypeWrap{ -- At runtime there are no newtypes, and hence no
-- newtype constructors. A NewtypeWrap is just a
-- made-up tag saying "heads up, there used to be
-- a newtype constructor here".
ty :: RttiType
, dc :: Either String DataCon
, wrapped_term :: Term }
| RefWrap { -- The contents of a reference
ty :: RttiType
, wrapped_term :: Term }
isTerm, isSuspension, isPrim, isFun, isFunLike, isNewtypeWrap :: Term -> Bool
isTerm Term{} = True
isTerm _ = False
isSuspension Suspension{} = True
isSuspension _ = False
isPrim Prim{} = True
isPrim _ = False
isNewtypeWrap NewtypeWrap{} = True
isNewtypeWrap _ = False
isFun Suspension{ctype=Fun} = True
isFun _ = False
isFunLike s@Suspension{ty=ty} = isFun s || isFunTy ty
isFunLike _ = False
termType :: Term -> RttiType
termType t = ty t
isFullyEvaluatedTerm :: Term -> Bool
isFullyEvaluatedTerm Term {subTerms=tt} = all isFullyEvaluatedTerm tt
isFullyEvaluatedTerm Prim {} = True
isFullyEvaluatedTerm NewtypeWrap{wrapped_term=t} = isFullyEvaluatedTerm t
isFullyEvaluatedTerm RefWrap{wrapped_term=t} = isFullyEvaluatedTerm t
isFullyEvaluatedTerm _ = False
instance Outputable (Term) where
ppr t | Just doc <- cPprTerm cPprTermBase t = doc
| otherwise = panic "Outputable Term instance"
-------------------------------------------------------------------------
-- Runtime Closure Datatype and functions for retrieving closure related stuff
-------------------------------------------------------------------------
data ClosureType = Constr
| Fun
| Thunk Int
| ThunkSelector
| Blackhole
| AP
| PAP
| Indirection Int
| MutVar Int
| MVar Int
| Other Int
deriving (Show, Eq)
data Closure = Closure { tipe :: ClosureType
, infoPtr :: Ptr ()
, infoTable :: StgInfoTable
, ptrs :: Array Int HValue
, nonPtrs :: [Word]
}
instance Outputable ClosureType where
ppr = text . show
#include "../includes/rts/storage/ClosureTypes.h"
aP_CODE, pAP_CODE :: Int
aP_CODE = AP
pAP_CODE = PAP
#undef AP
#undef PAP
getClosureData :: DynFlags -> a -> IO Closure
getClosureData dflags a =
case unpackClosure# a of
(# iptr, ptrs, nptrs #) -> do
let iptr'
| ghciTablesNextToCode =
Ptr iptr
| otherwise =
-- the info pointer we get back from unpackClosure#
-- is to the beginning of the standard info table,
-- but the Storable instance for info tables takes
-- into account the extra entry pointer when
-- !ghciTablesNextToCode, so we must adjust here:
Ptr iptr `plusPtr` negate (wORD_SIZE dflags)
itbl <- peekItbl dflags iptr'
let tipe = readCType (BCI.tipe itbl)
elems = fromIntegral (BCI.ptrs itbl)
ptrsList = Array 0 (elems - 1) elems ptrs
nptrs_data = [W# (indexWordArray# nptrs i)
| I# i <- [0.. fromIntegral (BCI.nptrs itbl)-1] ]
ASSERT(elems >= 0) return ()
ptrsList `seq`
return (Closure tipe (Ptr iptr) itbl ptrsList nptrs_data)
readCType :: Integral a => a -> ClosureType
readCType i
| i >= CONSTR && i <= CONSTR_NOCAF_STATIC = Constr
| i >= FUN && i <= FUN_STATIC = Fun
| i >= THUNK && i < THUNK_SELECTOR = Thunk i'
| i == THUNK_SELECTOR = ThunkSelector
| i == BLACKHOLE = Blackhole
| i >= IND && i <= IND_STATIC = Indirection i'
| i' == aP_CODE = AP
| i == AP_STACK = AP
| i' == pAP_CODE = PAP
| i == MUT_VAR_CLEAN || i == MUT_VAR_DIRTY= MutVar i'
| i == MVAR_CLEAN || i == MVAR_DIRTY = MVar i'
| otherwise = Other i'
where i' = fromIntegral i
isConstr, isIndirection, isThunk :: ClosureType -> Bool
isConstr Constr = True
isConstr _ = False
isIndirection (Indirection _) = True
isIndirection _ = False
isThunk (Thunk _) = True
isThunk ThunkSelector = True
isThunk AP = True
isThunk _ = False
isFullyEvaluated :: DynFlags -> a -> IO Bool
isFullyEvaluated dflags a = do
closure <- getClosureData dflags a
case tipe closure of
Constr -> do are_subs_evaluated <- amapM (isFullyEvaluated dflags) (ptrs closure)
return$ and are_subs_evaluated
_ -> return False
where amapM f = sequence . amap' f
-- TODO: Fix it. Probably the otherwise case is failing, trace/debug it
{-
unsafeDeepSeq :: a -> b -> b
unsafeDeepSeq = unsafeDeepSeq1 2
where unsafeDeepSeq1 0 a b = seq a $! b
unsafeDeepSeq1 i a b -- 1st case avoids infinite loops for non reducible thunks
| not (isConstr tipe) = seq a $! unsafeDeepSeq1 (i-1) a b
-- | unsafePerformIO (isFullyEvaluated a) = b
| otherwise = case unsafePerformIO (getClosureData a) of
closure -> foldl' (flip unsafeDeepSeq) b (ptrs closure)
where tipe = unsafePerformIO (getClosureType a)
-}
-----------------------------------
-- * Traversals for Terms
-----------------------------------
type TermProcessor a b = RttiType -> Either String DataCon -> HValue -> [a] -> b
data TermFold a = TermFold { fTerm :: TermProcessor a a
, fPrim :: RttiType -> [Word] -> a
, fSuspension :: ClosureType -> RttiType -> HValue
-> Maybe Name -> a
, fNewtypeWrap :: RttiType -> Either String DataCon
-> a -> a
, fRefWrap :: RttiType -> a -> a
}
data TermFoldM m a =
TermFoldM {fTermM :: TermProcessor a (m a)
, fPrimM :: RttiType -> [Word] -> m a
, fSuspensionM :: ClosureType -> RttiType -> HValue
-> Maybe Name -> m a
, fNewtypeWrapM :: RttiType -> Either String DataCon
-> a -> m a
, fRefWrapM :: RttiType -> a -> m a
}
foldTerm :: TermFold a -> Term -> a
foldTerm tf (Term ty dc v tt) = fTerm tf ty dc v (map (foldTerm tf) tt)
foldTerm tf (Prim ty v ) = fPrim tf ty v
foldTerm tf (Suspension ct ty v b) = fSuspension tf ct ty v b
foldTerm tf (NewtypeWrap ty dc t) = fNewtypeWrap tf ty dc (foldTerm tf t)
foldTerm tf (RefWrap ty t) = fRefWrap tf ty (foldTerm tf t)
foldTermM :: Monad m => TermFoldM m a -> Term -> m a
foldTermM tf (Term ty dc v tt) = mapM (foldTermM tf) tt >>= fTermM tf ty dc v
foldTermM tf (Prim ty v ) = fPrimM tf ty v
foldTermM tf (Suspension ct ty v b) = fSuspensionM tf ct ty v b
foldTermM tf (NewtypeWrap ty dc t) = foldTermM tf t >>= fNewtypeWrapM tf ty dc
foldTermM tf (RefWrap ty t) = foldTermM tf t >>= fRefWrapM tf ty
idTermFold :: TermFold Term
idTermFold = TermFold {
fTerm = Term,
fPrim = Prim,
fSuspension = Suspension,
fNewtypeWrap = NewtypeWrap,
fRefWrap = RefWrap
}
mapTermType :: (RttiType -> Type) -> Term -> Term
mapTermType f = foldTerm idTermFold {
fTerm = \ty dc hval tt -> Term (f ty) dc hval tt,
fSuspension = \ct ty hval n ->
Suspension ct (f ty) hval n,
fNewtypeWrap= \ty dc t -> NewtypeWrap (f ty) dc t,
fRefWrap = \ty t -> RefWrap (f ty) t}
mapTermTypeM :: Monad m => (RttiType -> m Type) -> Term -> m Term
mapTermTypeM f = foldTermM TermFoldM {
fTermM = \ty dc hval tt -> f ty >>= \ty' -> return $ Term ty' dc hval tt,
fPrimM = (return.) . Prim,
fSuspensionM = \ct ty hval n ->
f ty >>= \ty' -> return $ Suspension ct ty' hval n,
fNewtypeWrapM= \ty dc t -> f ty >>= \ty' -> return $ NewtypeWrap ty' dc t,
fRefWrapM = \ty t -> f ty >>= \ty' -> return $ RefWrap ty' t}
termTyVars :: Term -> TyVarSet
termTyVars = foldTerm TermFold {
fTerm = \ty _ _ tt ->
tyVarsOfType ty `plusVarEnv` concatVarEnv tt,
fSuspension = \_ ty _ _ -> tyVarsOfType ty,
fPrim = \ _ _ -> emptyVarEnv,
fNewtypeWrap= \ty _ t -> tyVarsOfType ty `plusVarEnv` t,
fRefWrap = \ty t -> tyVarsOfType ty `plusVarEnv` t}
where concatVarEnv = foldr plusVarEnv emptyVarEnv
----------------------------------
-- Pretty printing of terms
----------------------------------
type Precedence = Int
type TermPrinter = Precedence -> Term -> SDoc
type TermPrinterM m = Precedence -> Term -> m SDoc
app_prec,cons_prec, max_prec ::Int
max_prec = 10
app_prec = max_prec
cons_prec = 5 -- TODO Extract this info from GHC itself
pprTerm :: TermPrinter -> TermPrinter
pprTerm y p t | Just doc <- pprTermM (\p -> Just . y p) p t = doc
pprTerm _ _ _ = panic "pprTerm"
pprTermM, ppr_termM, pprNewtypeWrap :: Monad m => TermPrinterM m -> TermPrinterM m
pprTermM y p t = pprDeeper `liftM` ppr_termM y p t
ppr_termM y p Term{dc=Left dc_tag, subTerms=tt} = do
tt_docs <- mapM (y app_prec) tt
return $ cparen (not (null tt) && p >= app_prec)
(text dc_tag <+> pprDeeperList fsep tt_docs)
ppr_termM y p Term{dc=Right dc, subTerms=tt}
{- | dataConIsInfix dc, (t1:t2:tt') <- tt --TODO fixity
= parens (ppr_term1 True t1 <+> ppr dc <+> ppr_term1 True ppr t2)
<+> hsep (map (ppr_term1 True) tt)
-} -- TODO Printing infix constructors properly
| null sub_terms_to_show
= return (ppr dc)
| otherwise
= do { tt_docs <- mapM (y app_prec) sub_terms_to_show
; return $ cparen (p >= app_prec) $
sep [ppr dc, nest 2 (pprDeeperList fsep tt_docs)] }
where
sub_terms_to_show -- Don't show the dictionary arguments to
-- constructors unless -dppr-debug is on
| opt_PprStyle_Debug = tt
| otherwise = dropList (dataConTheta dc) tt
ppr_termM y p t@NewtypeWrap{} = pprNewtypeWrap y p t
ppr_termM y p RefWrap{wrapped_term=t} = do
contents <- y app_prec t
return$ cparen (p >= app_prec) (text "GHC.Prim.MutVar#" <+> contents)
-- The constructor name is wired in here ^^^ for the sake of simplicity.
-- I don't think mutvars are going to change in a near future.
-- In any case this is solely a presentation matter: MutVar# is
-- a datatype with no constructors, implemented by the RTS
-- (hence there is no way to obtain a datacon and print it).
ppr_termM _ _ t = ppr_termM1 t
ppr_termM1 :: Monad m => Term -> m SDoc
ppr_termM1 Prim{value=words, ty=ty} =
return $ repPrim (tyConAppTyCon ty) words
ppr_termM1 Suspension{ty=ty, bound_to=Nothing} =
return (char '_' <+> ifPprDebug (text "::" <> ppr ty))
ppr_termM1 Suspension{ty=ty, bound_to=Just n}
-- | Just _ <- splitFunTy_maybe ty = return$ ptext (sLit("<function>")
| otherwise = return$ parens$ ppr n <> text "::" <> ppr ty
ppr_termM1 Term{} = panic "ppr_termM1 - Term"
ppr_termM1 RefWrap{} = panic "ppr_termM1 - RefWrap"
ppr_termM1 NewtypeWrap{} = panic "ppr_termM1 - NewtypeWrap"
pprNewtypeWrap y p NewtypeWrap{ty=ty, wrapped_term=t}
| Just (tc,_) <- tcSplitTyConApp_maybe ty
, ASSERT(isNewTyCon tc) True
, Just new_dc <- tyConSingleDataCon_maybe tc = do
real_term <- y max_prec t
return $ cparen (p >= app_prec) (ppr new_dc <+> real_term)
pprNewtypeWrap _ _ _ = panic "pprNewtypeWrap"
-------------------------------------------------------
-- Custom Term Pretty Printers
-------------------------------------------------------
-- We can want to customize the representation of a
-- term depending on its type.
-- However, note that custom printers have to work with
-- type representations, instead of directly with types.
-- We cannot use type classes here, unless we employ some
-- typerep trickery (e.g. Weirich's RepLib tricks),
-- which I didn't. Therefore, this code replicates a lot
-- of what type classes provide for free.
type CustomTermPrinter m = TermPrinterM m
-> [Precedence -> Term -> (m (Maybe SDoc))]
-- | Takes a list of custom printers with a explicit recursion knot and a term,
-- and returns the output of the first successful printer, or the default printer
cPprTerm :: Monad m => CustomTermPrinter m -> Term -> m SDoc
cPprTerm printers_ = go 0 where
printers = printers_ go
go prec t = do
let default_ = Just `liftM` pprTermM go prec t
mb_customDocs = [pp prec t | pp <- printers] ++ [default_]
Just doc <- firstJustM mb_customDocs
return$ cparen (prec>app_prec+1) doc
firstJustM (mb:mbs) = mb >>= maybe (firstJustM mbs) (return . Just)
firstJustM [] = return Nothing
-- Default set of custom printers. Note that the recursion knot is explicit
cPprTermBase :: forall m. Monad m => CustomTermPrinter m
cPprTermBase y =
[ ifTerm (isTupleTy.ty) (\_p -> liftM (parens . hcat . punctuate comma)
. mapM (y (-1))
. subTerms)
, ifTerm (\t -> isTyCon listTyCon (ty t) && subTerms t `lengthIs` 2)
ppr_list
, ifTerm (isTyCon intTyCon . ty) ppr_int
, ifTerm (isTyCon charTyCon . ty) ppr_char
, ifTerm (isTyCon floatTyCon . ty) ppr_float
, ifTerm (isTyCon doubleTyCon . ty) ppr_double
, ifTerm (isIntegerTy . ty) ppr_integer
]
where
ifTerm :: (Term -> Bool)
-> (Precedence -> Term -> m SDoc)
-> Precedence -> Term -> m (Maybe SDoc)
ifTerm pred f prec t@Term{}
| pred t = Just `liftM` f prec t
ifTerm _ _ _ _ = return Nothing
isTupleTy ty = fromMaybe False $ do
(tc,_) <- tcSplitTyConApp_maybe ty
return (isBoxedTupleTyCon tc)
isTyCon a_tc ty = fromMaybe False $ do
(tc,_) <- tcSplitTyConApp_maybe ty
return (a_tc == tc)
isIntegerTy ty = fromMaybe False $ do
(tc,_) <- tcSplitTyConApp_maybe ty
return (tyConName tc == integerTyConName)
ppr_int, ppr_char, ppr_float, ppr_double, ppr_integer
:: Precedence -> Term -> m SDoc
ppr_int _ v = return (Ppr.int (unsafeCoerce# (val v)))
ppr_char _ v = return (Ppr.char '\'' <> Ppr.char (unsafeCoerce# (val v)) <> Ppr.char '\'')
ppr_float _ v = return (Ppr.float (unsafeCoerce# (val v)))
ppr_double _ v = return (Ppr.double (unsafeCoerce# (val v)))
ppr_integer _ v = return (Ppr.integer (unsafeCoerce# (val v)))
--Note pprinting of list terms is not lazy
ppr_list :: Precedence -> Term -> m SDoc
ppr_list p (Term{subTerms=[h,t]}) = do
let elems = h : getListTerms t
isConsLast = not(termType(last elems) `eqType` termType h)
is_string = all (isCharTy . ty) elems
print_elems <- mapM (y cons_prec) elems
if is_string
then return (Ppr.doubleQuotes (Ppr.text (unsafeCoerce# (map val elems))))
else if isConsLast
then return $ cparen (p >= cons_prec)
$ pprDeeperList fsep
$ punctuate (space<>colon) print_elems
else return $ brackets
$ pprDeeperList fcat
$ punctuate comma print_elems
where getListTerms Term{subTerms=[h,t]} = h : getListTerms t
getListTerms Term{subTerms=[]} = []
getListTerms t@Suspension{} = [t]
getListTerms t = pprPanic "getListTerms" (ppr t)
ppr_list _ _ = panic "doList"
repPrim :: TyCon -> [Word] -> SDoc
repPrim t = rep where
rep x
| t == charPrimTyCon = text $ show (build x :: Char)
| t == intPrimTyCon = text $ show (build x :: Int)
| t == wordPrimTyCon = text $ show (build x :: Word)
| t == floatPrimTyCon = text $ show (build x :: Float)
| t == doublePrimTyCon = text $ show (build x :: Double)
| t == int32PrimTyCon = text $ show (build x :: Int32)
| t == word32PrimTyCon = text $ show (build x :: Word32)
| t == int64PrimTyCon = text $ show (build x :: Int64)
| t == word64PrimTyCon = text $ show (build x :: Word64)
| t == addrPrimTyCon = text $ show (nullPtr `plusPtr` build x)
| t == stablePtrPrimTyCon = text "<stablePtr>"
| t == stableNamePrimTyCon = text "<stableName>"
| t == statePrimTyCon = text "<statethread>"
| t == proxyPrimTyCon = text "<proxy>"
| t == realWorldTyCon = text "<realworld>"
| t == threadIdPrimTyCon = text "<ThreadId>"
| t == weakPrimTyCon = text "<Weak>"
| t == arrayPrimTyCon = text "<array>"
| t == smallArrayPrimTyCon = text "<smallArray>"
| t == byteArrayPrimTyCon = text "<bytearray>"
| t == mutableArrayPrimTyCon = text "<mutableArray>"
| t == smallMutableArrayPrimTyCon = text "<smallMutableArray>"
| t == mutableByteArrayPrimTyCon = text "<mutableByteArray>"
| t == mutVarPrimTyCon = text "<mutVar>"
| t == mVarPrimTyCon = text "<mVar>"
| t == tVarPrimTyCon = text "<tVar>"
| otherwise = char '<' <> ppr t <> char '>'
where build ww = unsafePerformIO $ withArray ww (peek . castPtr)
-- This ^^^ relies on the representation of Haskell heap values being
-- the same as in a C array.
-----------------------------------
-- Type Reconstruction
-----------------------------------
{-
Type Reconstruction is type inference done on heap closures.
The algorithm walks the heap generating a set of equations, which
are solved with syntactic unification.
A type reconstruction equation looks like:
<datacon reptype> = <actual heap contents>
The full equation set is generated by traversing all the subterms, starting
from a given term.
The only difficult part is that newtypes are only found in the lhs of equations.
Right hand sides are missing them. We can either (a) drop them from the lhs, or
(b) reconstruct them in the rhs when possible.
The function congruenceNewtypes takes a shot at (b)
-}
-- A (non-mutable) tau type containing
-- existentially quantified tyvars.
-- (since GHC type language currently does not support
-- existentials, we leave these variables unquantified)
type RttiType = Type
-- An incomplete type as stored in GHCi:
-- no polymorphism: no quantifiers & all tyvars are skolem.
type GhciType = Type
-- The Type Reconstruction monad
--------------------------------
type TR a = TcM a
runTR :: HscEnv -> TR a -> IO a
runTR hsc_env thing = do
mb_val <- runTR_maybe hsc_env thing
case mb_val of
Nothing -> error "unable to :print the term"
Just x -> return x
runTR_maybe :: HscEnv -> TR a -> IO (Maybe a)
runTR_maybe hsc_env thing_inside
= do { (_errs, res) <- initTc hsc_env HsSrcFile False
(icInteractiveModule (hsc_IC hsc_env))
thing_inside
; return res }
-- | Term Reconstruction trace
traceTR :: SDoc -> TR ()
traceTR = liftTcM . traceOptTcRn Opt_D_dump_rtti
-- Semantically different to recoverM in TcRnMonad
-- recoverM retains the errors in the first action,
-- whereas recoverTc here does not
recoverTR :: TR a -> TR a -> TR a
recoverTR recover thing = do
(_,mb_res) <- tryTcErrs thing
case mb_res of
Nothing -> recover
Just res -> return res
trIO :: IO a -> TR a
trIO = liftTcM . liftIO
liftTcM :: TcM a -> TR a
liftTcM = id
newVar :: Kind -> TR TcType
newVar = liftTcM . newFlexiTyVarTy
instTyVars :: [TyVar] -> TR (TvSubst, [TcTyVar])
-- Instantiate fresh mutable type variables from some TyVars
-- This function preserves the print-name, which helps error messages
instTyVars = liftTcM . tcInstTyVars
type RttiInstantiation = [(TcTyVar, TyVar)]
-- Associates the typechecker-world meta type variables
-- (which are mutable and may be refined), to their
-- debugger-world RuntimeUnk counterparts.
-- If the TcTyVar has not been refined by the runtime type
-- elaboration, then we want to turn it back into the
-- original RuntimeUnk
-- | Returns the instantiated type scheme ty', and the
-- mapping from new (instantiated) -to- old (skolem) type variables
instScheme :: QuantifiedType -> TR (TcType, RttiInstantiation)
instScheme (tvs, ty)
= liftTcM $ do { (subst, tvs') <- tcInstTyVars tvs
; let rtti_inst = [(tv',tv) | (tv',tv) <- tvs' `zip` tvs]
; return (substTy subst ty, rtti_inst) }
applyRevSubst :: RttiInstantiation -> TR ()
-- Apply the *reverse* substitution in-place to any un-filled-in
-- meta tyvars. This recovers the original debugger-world variable
-- unless it has been refined by new information from the heap
applyRevSubst pairs = liftTcM (mapM_ do_pair pairs)
where
do_pair (tc_tv, rtti_tv)
= do { tc_ty <- zonkTcTyVar tc_tv
; case tcGetTyVar_maybe tc_ty of
Just tv | isMetaTyVar tv -> writeMetaTyVar tv (mkTyVarTy rtti_tv)
_ -> return () }
-- Adds a constraint of the form t1 == t2
-- t1 is expected to come from walking the heap
-- t2 is expected to come from a datacon signature
-- Before unification, congruenceNewtypes needs to
-- do its magic.
addConstraint :: TcType -> TcType -> TR ()
addConstraint actual expected = do
traceTR (text "add constraint:" <+> fsep [ppr actual, equals, ppr expected])
recoverTR (traceTR $ fsep [text "Failed to unify", ppr actual,
text "with", ppr expected]) $
do { (ty1, ty2) <- congruenceNewtypes actual expected
; _ <- captureConstraints $ unifyType ty1 ty2
; return () }
-- TOMDO: what about the coercion?
-- we should consider family instances
-- Type & Term reconstruction
------------------------------
cvObtainTerm :: HscEnv -> Int -> Bool -> RttiType -> HValue -> IO Term
cvObtainTerm hsc_env max_depth force old_ty hval = runTR hsc_env $ do
-- we quantify existential tyvars as universal,
-- as this is needed to be able to manipulate
-- them properly
let quant_old_ty@(old_tvs, old_tau) = quantifyType old_ty
sigma_old_ty = mkForAllTys old_tvs old_tau
traceTR (text "Term reconstruction started with initial type " <> ppr old_ty)
term <-
if null old_tvs
then do
term <- go max_depth sigma_old_ty sigma_old_ty hval
term' <- zonkTerm term
return $ fixFunDictionaries $ expandNewtypes term'
else do
(old_ty', rev_subst) <- instScheme quant_old_ty
my_ty <- newVar openTypeKind
when (check1 quant_old_ty) (traceTR (text "check1 passed") >>
addConstraint my_ty old_ty')
term <- go max_depth my_ty sigma_old_ty hval
new_ty <- zonkTcType (termType term)
if isMonomorphic new_ty || check2 (quantifyType new_ty) quant_old_ty
then do
traceTR (text "check2 passed")
addConstraint new_ty old_ty'
applyRevSubst rev_subst
zterm' <- zonkTerm term
return ((fixFunDictionaries . expandNewtypes) zterm')
else do
traceTR (text "check2 failed" <+> parens
(ppr term <+> text "::" <+> ppr new_ty))
-- we have unsound types. Replace constructor types in
-- subterms with tyvars
zterm' <- mapTermTypeM
(\ty -> case tcSplitTyConApp_maybe ty of
Just (tc, _:_) | tc /= funTyCon
-> newVar openTypeKind
_ -> return ty)
term
zonkTerm zterm'
traceTR (text "Term reconstruction completed." $$
text "Term obtained: " <> ppr term $$
text "Type obtained: " <> ppr (termType term))
return term
where
dflags = hsc_dflags hsc_env
go :: Int -> Type -> Type -> HValue -> TcM Term
-- I believe that my_ty should not have any enclosing
-- foralls, nor any free RuntimeUnk skolems;
-- that is partly what the quantifyType stuff achieved
--
-- [SPJ May 11] I don't understand the difference between my_ty and old_ty
go max_depth _ _ _ | seq max_depth False = undefined
go 0 my_ty _old_ty a = do
traceTR (text "Gave up reconstructing a term after" <>
int max_depth <> text " steps")
clos <- trIO $ getClosureData dflags a
return (Suspension (tipe clos) my_ty a Nothing)
go max_depth my_ty old_ty a = do
let monomorphic = not(isTyVarTy my_ty)
-- This ^^^ is a convention. The ancestor tests for
-- monomorphism and passes a type instead of a tv
clos <- trIO $ getClosureData dflags a
case tipe clos of
-- Thunks we may want to force
t | isThunk t && force -> traceTR (text "Forcing a " <> text (show t)) >>
seq a (go (pred max_depth) my_ty old_ty a)
-- Blackholes are indirections iff the payload is not TSO or BLOCKING_QUEUE. So we
-- treat them like indirections; if the payload is TSO or BLOCKING_QUEUE, we'll end up
-- showing '_' which is what we want.
Blackhole -> do traceTR (text "Following a BLACKHOLE")
appArr (go max_depth my_ty old_ty) (ptrs clos) 0
-- We always follow indirections
Indirection i -> do traceTR (text "Following an indirection" <> parens (int i) )
go max_depth my_ty old_ty $! (ptrs clos ! 0)
-- We also follow references
MutVar _ | Just (tycon,[world,contents_ty]) <- tcSplitTyConApp_maybe old_ty
-> do
-- Deal with the MutVar# primitive
-- It does not have a constructor at all,
-- so we simulate the following one
-- MutVar# :: contents_ty -> MutVar# s contents_ty
traceTR (text "Following a MutVar")
contents_tv <- newVar liftedTypeKind
contents <- trIO$ IO$ \w -> readMutVar# (unsafeCoerce# a) w
ASSERT(isUnliftedTypeKind $ typeKind my_ty) return ()
(mutvar_ty,_) <- instScheme $ quantifyType $ mkFunTy
contents_ty (mkTyConApp tycon [world,contents_ty])
addConstraint (mkFunTy contents_tv my_ty) mutvar_ty
x <- go (pred max_depth) contents_tv contents_ty contents
return (RefWrap my_ty x)
-- The interesting case
Constr -> do
traceTR (text "entering a constructor " <>
if monomorphic
then parens (text "already monomorphic: " <> ppr my_ty)
else Ppr.empty)
Right dcname <- dataConInfoPtrToName (infoPtr clos)
(_,mb_dc) <- tryTcErrs (tcLookupDataCon dcname)
case mb_dc of
Nothing -> do -- This can happen for private constructors compiled -O0
-- where the .hi descriptor does not export them
-- In such case, we return a best approximation:
-- ignore the unpointed args, and recover the pointeds
-- This preserves laziness, and should be safe.
traceTR (text "Not constructor" <+> ppr dcname)
let dflags = hsc_dflags hsc_env
tag = showPpr dflags dcname
vars <- replicateM (length$ elems$ ptrs clos)
(newVar liftedTypeKind)
subTerms <- sequence [appArr (go (pred max_depth) tv tv) (ptrs clos) i
| (i, tv) <- zip [0..] vars]
return (Term my_ty (Left ('<' : tag ++ ">")) a subTerms)
Just dc -> do
traceTR (text "Is constructor" <+> (ppr dc $$ ppr my_ty))
subTtypes <- getDataConArgTys dc my_ty
subTerms <- extractSubTerms (\ty -> go (pred max_depth) ty ty) clos subTtypes
return (Term my_ty (Right dc) a subTerms)
-- The otherwise case: can be a Thunk,AP,PAP,etc.
tipe_clos ->
return (Suspension tipe_clos my_ty a Nothing)
-- insert NewtypeWraps around newtypes
expandNewtypes = foldTerm idTermFold { fTerm = worker } where
worker ty dc hval tt
| Just (tc, args) <- tcSplitTyConApp_maybe ty
, isNewTyCon tc
, wrapped_type <- newTyConInstRhs tc args
, Just dc' <- tyConSingleDataCon_maybe tc
, t' <- worker wrapped_type dc hval tt
= NewtypeWrap ty (Right dc') t'
| otherwise = Term ty dc hval tt
-- Avoid returning types where predicates have been expanded to dictionaries.
fixFunDictionaries = foldTerm idTermFold {fSuspension = worker} where
worker ct ty hval n | isFunTy ty = Suspension ct (dictsView ty) hval n
| otherwise = Suspension ct ty hval n
extractSubTerms :: (Type -> HValue -> TcM Term)
-> Closure -> [Type] -> TcM [Term]
extractSubTerms recurse clos = liftM thirdOf3 . go 0 (nonPtrs clos)
where
go ptr_i ws [] = return (ptr_i, ws, [])
go ptr_i ws (ty:tys)
| Just (tc, elem_tys) <- tcSplitTyConApp_maybe ty
, isUnboxedTupleTyCon tc
= do (ptr_i, ws, terms0) <- go ptr_i ws elem_tys
(ptr_i, ws, terms1) <- go ptr_i ws tys
return (ptr_i, ws, unboxedTupleTerm ty terms0 : terms1)
| otherwise
= case repType ty of
UnaryRep rep_ty -> do
(ptr_i, ws, term0) <- go_rep ptr_i ws ty (typePrimRep rep_ty)
(ptr_i, ws, terms1) <- go ptr_i ws tys
return (ptr_i, ws, term0 : terms1)
UbxTupleRep rep_tys -> do
(ptr_i, ws, terms0) <- go_unary_types ptr_i ws rep_tys
(ptr_i, ws, terms1) <- go ptr_i ws tys
return (ptr_i, ws, unboxedTupleTerm ty terms0 : terms1)
go_unary_types ptr_i ws [] = return (ptr_i, ws, [])
go_unary_types ptr_i ws (rep_ty:rep_tys) = do
tv <- newVar liftedTypeKind
(ptr_i, ws, term0) <- go_rep ptr_i ws tv (typePrimRep rep_ty)
(ptr_i, ws, terms1) <- go_unary_types ptr_i ws rep_tys
return (ptr_i, ws, term0 : terms1)
go_rep ptr_i ws ty rep = case rep of
PtrRep -> do
t <- appArr (recurse ty) (ptrs clos) ptr_i
return (ptr_i + 1, ws, t)
_ -> do
dflags <- getDynFlags
let (ws0, ws1) = splitAt (primRepSizeW dflags rep) ws
return (ptr_i, ws1, Prim ty ws0)
unboxedTupleTerm ty terms = Term ty (Right (tupleCon UnboxedTuple (length terms)))
(error "unboxedTupleTerm: no HValue for unboxed tuple") terms
-- Fast, breadth-first Type reconstruction
------------------------------------------
cvReconstructType :: HscEnv -> Int -> GhciType -> HValue -> IO (Maybe Type)
cvReconstructType hsc_env max_depth old_ty hval = runTR_maybe hsc_env $ do
traceTR (text "RTTI started with initial type " <> ppr old_ty)
let sigma_old_ty@(old_tvs, _) = quantifyType old_ty
new_ty <-
if null old_tvs
then return old_ty
else do
(old_ty', rev_subst) <- instScheme sigma_old_ty
my_ty <- newVar openTypeKind
when (check1 sigma_old_ty) (traceTR (text "check1 passed") >>
addConstraint my_ty old_ty')
search (isMonomorphic `fmap` zonkTcType my_ty)
(\(ty,a) -> go ty a)
(Seq.singleton (my_ty, hval))
max_depth
new_ty <- zonkTcType my_ty
if isMonomorphic new_ty || check2 (quantifyType new_ty) sigma_old_ty
then do
traceTR (text "check2 passed" <+> ppr old_ty $$ ppr new_ty)
addConstraint my_ty old_ty'
applyRevSubst rev_subst
zonkRttiType new_ty
else traceTR (text "check2 failed" <+> parens (ppr new_ty)) >>
return old_ty
traceTR (text "RTTI completed. Type obtained:" <+> ppr new_ty)
return new_ty
where
dflags = hsc_dflags hsc_env
-- search :: m Bool -> ([a] -> [a] -> [a]) -> [a] -> m ()
search _ _ _ 0 = traceTR (text "Failed to reconstruct a type after " <>
int max_depth <> text " steps")
search stop expand l d =
case viewl l of
EmptyL -> return ()
x :< xx -> unlessM stop $ do
new <- expand x
search stop expand (xx `mappend` Seq.fromList new) $! (pred d)
-- returns unification tasks,since we are going to want a breadth-first search
go :: Type -> HValue -> TR [(Type, HValue)]
go my_ty a = do
traceTR (text "go" <+> ppr my_ty)
clos <- trIO $ getClosureData dflags a
case tipe clos of
Blackhole -> appArr (go my_ty) (ptrs clos) 0 -- carefully, don't eval the TSO
Indirection _ -> go my_ty $! (ptrs clos ! 0)
MutVar _ -> do
contents <- trIO$ IO$ \w -> readMutVar# (unsafeCoerce# a) w
tv' <- newVar liftedTypeKind
world <- newVar liftedTypeKind
addConstraint my_ty (mkTyConApp mutVarPrimTyCon [world,tv'])
return [(tv', contents)]
Constr -> do
Right dcname <- dataConInfoPtrToName (infoPtr clos)
traceTR (text "Constr1" <+> ppr dcname)
(_,mb_dc) <- tryTcErrs (tcLookupDataCon dcname)
case mb_dc of
Nothing-> do
-- TODO: Check this case
forM [0..length (elems $ ptrs clos)] $ \i -> do
tv <- newVar liftedTypeKind
return$ appArr (\e->(tv,e)) (ptrs clos) i
Just dc -> do
arg_tys <- getDataConArgTys dc my_ty
(_, itys) <- findPtrTyss 0 arg_tys
traceTR (text "Constr2" <+> ppr dcname <+> ppr arg_tys)
return $ [ appArr (\e-> (ty,e)) (ptrs clos) i
| (i,ty) <- itys]
_ -> return []
findPtrTys :: Int -- Current pointer index
-> Type -- Type
-> TR (Int, [(Int, Type)])
findPtrTys i ty
| Just (tc, elem_tys) <- tcSplitTyConApp_maybe ty
, isUnboxedTupleTyCon tc
= findPtrTyss i elem_tys
| otherwise
= case repType ty of
UnaryRep rep_ty | typePrimRep rep_ty == PtrRep -> return (i + 1, [(i, ty)])
| otherwise -> return (i, [])
UbxTupleRep rep_tys -> foldM (\(i, extras) rep_ty -> if typePrimRep rep_ty == PtrRep
then newVar liftedTypeKind >>= \tv -> return (i + 1, extras ++ [(i, tv)])
else return (i, extras))
(i, []) rep_tys
findPtrTyss :: Int
-> [Type]
-> TR (Int, [(Int, Type)])
findPtrTyss i tys = foldM step (i, []) tys
where step (i, discovered) elem_ty = findPtrTys i elem_ty >>= \(i, extras) -> return (i, discovered ++ extras)
-- Compute the difference between a base type and the type found by RTTI
-- improveType <base_type> <rtti_type>
-- The types can contain skolem type variables, which need to be treated as normal vars.
-- In particular, we want them to unify with things.
improveRTTIType :: HscEnv -> RttiType -> RttiType -> Maybe TvSubst
improveRTTIType _ base_ty new_ty = U.tcUnifyTy base_ty new_ty
getDataConArgTys :: DataCon -> Type -> TR [Type]
-- Given the result type ty of a constructor application (D a b c :: ty)
-- return the types of the arguments. This is RTTI-land, so 'ty' might
-- not be fully known. Moreover, the arg types might involve existentials;
-- if so, make up fresh RTTI type variables for them
--
-- I believe that con_app_ty should not have any enclosing foralls
getDataConArgTys dc con_app_ty
= do { let UnaryRep rep_con_app_ty = repType con_app_ty
; traceTR (text "getDataConArgTys 1" <+> (ppr con_app_ty $$ ppr rep_con_app_ty
$$ ppr (tcSplitTyConApp_maybe rep_con_app_ty)))
; (subst, _) <- instTyVars (univ_tvs ++ ex_tvs)
; addConstraint rep_con_app_ty (substTy subst (dataConOrigResTy dc))
-- See Note [Constructor arg types]
; let con_arg_tys = substTys subst (dataConRepArgTys dc)
; traceTR (text "getDataConArgTys 2" <+> (ppr rep_con_app_ty $$ ppr con_arg_tys $$ ppr subst))
; return con_arg_tys }
where
univ_tvs = dataConUnivTyVars dc
ex_tvs = dataConExTyVars dc
{- Note [Constructor arg types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider a GADT (cf Trac #7386)
data family D a b
data instance D [a] a where
MkT :: a -> D [a] (Maybe a)
...
In getDataConArgTys
* con_app_ty is the known type (from outside) of the constructor application,
say D [Int] Int
* The data constructor MkT has a (representation) dataConTyCon = DList,
say where
data DList a where
MkT :: a -> DList a (Maybe a)
...
So the dataConTyCon of the data constructor, DList, differs from
the "outside" type, D. So we can't straightforwardly decompose the
"outside" type, and we end up in the "_" branch of the case.
Then we match the dataConOrigResTy of the data constructor against the
outside type, hoping to get a substitution that tells how to instantiate
the *representation* type constructor. This looks a bit delicate to
me, but it seems to work.
-}
-- Soundness checks
--------------------
{-
This is not formalized anywhere, so hold to your seats!
RTTI in the presence of newtypes can be a tricky and unsound business.
Example:
~~~~~~~~~
Suppose we are doing RTTI for a partially evaluated
closure t, the real type of which is t :: MkT Int, for
newtype MkT a = MkT [Maybe a]
The table below shows the results of RTTI and the improvement
calculated for different combinations of evaluatedness and :type t.
Regard the two first columns as input and the next two as output.
# | t | :type t | rtti(t) | improv. | result
------------------------------------------------------------
1 | _ | t b | a | none | OK
2 | _ | MkT b | a | none | OK
3 | _ | t Int | a | none | OK
If t is not evaluated at *all*, we are safe.
4 | (_ : _) | t b | [a] | t = [] | UNSOUND
5 | (_ : _) | MkT b | MkT a | none | OK (compensating for the missing newtype)
6 | (_ : _) | t Int | [Int] | t = [] | UNSOUND
If a is a minimal whnf, we run into trouble. Note that
row 5 above does newtype enrichment on the ty_rtty parameter.
7 | (Just _:_)| t b |[Maybe a] | t = [], | UNSOUND
| | | b = Maybe a|
8 | (Just _:_)| MkT b | MkT a | none | OK
9 | (Just _:_)| t Int | FAIL | none | OK
And if t is any more evaluated than whnf, we are still in trouble.
Because constraints are solved in top-down order, when we reach the
Maybe subterm what we got is already unsound. This explains why the
row 9 fails to complete.
10 | (Just _:_)| t Int | [Maybe a] | FAIL | OK
11 | (Just 1:_)| t Int | [Maybe Int] | FAIL | OK
We can undo the failure in row 9 by leaving out the constraint
coming from the type signature of t (i.e., the 2nd column).
Note that this type information is still used
to calculate the improvement. But we fail
when trying to calculate the improvement, as there is no unifier for
t Int = [Maybe a] or t Int = [Maybe Int].
Another set of examples with t :: [MkT (Maybe Int)] \equiv [[Maybe (Maybe Int)]]
# | t | :type t | rtti(t) | improvement | result
---------------------------------------------------------------------
1 |(Just _:_) | [t (Maybe a)] | [[Maybe b]] | t = [] |
| | | | b = Maybe a |
The checks:
~~~~~~~~~~~
Consider a function obtainType that takes a value and a type and produces
the Term representation and a substitution (the improvement).
Assume an auxiliar rtti' function which does the actual job if recovering
the type, but which may produce a false type.
In pseudocode:
rtti' :: a -> IO Type -- Does not use the static type information
obtainType :: a -> Type -> IO (Maybe (Term, Improvement))
obtainType v old_ty = do
rtti_ty <- rtti' v
if monomorphic rtti_ty || (check rtti_ty old_ty)
then ...
else return Nothing
where check rtti_ty old_ty = check1 rtti_ty &&
check2 rtti_ty old_ty
check1 :: Type -> Bool
check2 :: Type -> Type -> Bool
Now, if rtti' returns a monomorphic type, we are safe.
If that is not the case, then we consider two conditions.
1. To prevent the class of unsoundness displayed by
rows 4 and 7 in the example: no higher kind tyvars
accepted.
check1 (t a) = NO
check1 (t Int) = NO
check1 ([] a) = YES
2. To prevent the class of unsoundness shown by row 6,
the rtti type should be structurally more
defined than the old type we are comparing it to.
check2 :: NewType -> OldType -> Bool
check2 a _ = True
check2 [a] a = True
check2 [a] (t Int) = False
check2 [a] (t a) = False -- By check1 we never reach this equation
check2 [Int] a = True
check2 [Int] (t Int) = True
check2 [Maybe a] (t Int) = False
check2 [Maybe Int] (t Int) = True
check2 (Maybe [a]) (m [Int]) = False
check2 (Maybe [Int]) (m [Int]) = True
-}
check1 :: QuantifiedType -> Bool
check1 (tvs, _) = not $ any isHigherKind (map tyVarKind tvs)
where
isHigherKind = not . null . fst . splitKindFunTys
check2 :: QuantifiedType -> QuantifiedType -> Bool
check2 (_, rtti_ty) (_, old_ty)
| Just (_, rttis) <- tcSplitTyConApp_maybe rtti_ty
= case () of
_ | Just (_,olds) <- tcSplitTyConApp_maybe old_ty
-> and$ zipWith check2 (map quantifyType rttis) (map quantifyType olds)
_ | Just _ <- splitAppTy_maybe old_ty
-> isMonomorphicOnNonPhantomArgs rtti_ty
_ -> True
| otherwise = True
-- Dealing with newtypes
--------------------------
{-
congruenceNewtypes does a parallel fold over two Type values,
compensating for missing newtypes on both sides.
This is necessary because newtypes are not present
in runtime, but sometimes there is evidence available.
Evidence can come from DataCon signatures or
from compile-time type inference.
What we are doing here is an approximation
of unification modulo a set of equations derived
from newtype definitions. These equations should be the
same as the equality coercions generated for newtypes
in System Fc. The idea is to perform a sort of rewriting,
taking those equations as rules, before launching unification.
The caller must ensure the following.
The 1st type (lhs) comes from the heap structure of ptrs,nptrs.
The 2nd type (rhs) comes from a DataCon type signature.
Rewriting (i.e. adding/removing a newtype wrapper) can happen
in both types, but in the rhs it is restricted to the result type.
Note that it is very tricky to make this 'rewriting'
work with the unification implemented by TcM, where
substitutions are operationally inlined. The order in which
constraints are unified is vital as we cannot modify
anything that has been touched by a previous unification step.
Therefore, congruenceNewtypes is sound only if the types
recovered by the RTTI mechanism are unified Top-Down.
-}
congruenceNewtypes :: TcType -> TcType -> TR (TcType,TcType)
congruenceNewtypes lhs rhs = go lhs rhs >>= \rhs' -> return (lhs,rhs')
where
go l r
-- TyVar lhs inductive case
| Just tv <- getTyVar_maybe l
, isTcTyVar tv
, isMetaTyVar tv
= recoverTR (return r) $ do
Indirect ty_v <- readMetaTyVar tv
traceTR $ fsep [text "(congruence) Following indirect tyvar:",
ppr tv, equals, ppr ty_v]
go ty_v r
-- FunTy inductive case
| Just (l1,l2) <- splitFunTy_maybe l
, Just (r1,r2) <- splitFunTy_maybe r
= do r2' <- go l2 r2
r1' <- go l1 r1
return (mkFunTy r1' r2')
-- TyconApp Inductive case; this is the interesting bit.
| Just (tycon_l, _) <- tcSplitTyConApp_maybe lhs
, Just (tycon_r, _) <- tcSplitTyConApp_maybe rhs
, tycon_l /= tycon_r
= upgrade tycon_l r
| otherwise = return r
where upgrade :: TyCon -> Type -> TR Type
upgrade new_tycon ty
| not (isNewTyCon new_tycon) = do
traceTR (text "(Upgrade) Not matching newtype evidence: " <>
ppr new_tycon <> text " for " <> ppr ty)
return ty
| otherwise = do
traceTR (text "(Upgrade) upgraded " <> ppr ty <>
text " in presence of newtype evidence " <> ppr new_tycon)
(_, vars) <- instTyVars (tyConTyVars new_tycon)
let ty' = mkTyConApp new_tycon (mkTyVarTys vars)
UnaryRep rep_ty = repType ty'
_ <- liftTcM (unifyType ty rep_ty)
-- assumes that reptype doesn't ^^^^ touch tyconApp args
return ty'
zonkTerm :: Term -> TcM Term
zonkTerm = foldTermM (TermFoldM
{ fTermM = \ty dc v tt -> zonkRttiType ty >>= \ty' ->
return (Term ty' dc v tt)
, fSuspensionM = \ct ty v b -> zonkRttiType ty >>= \ty ->
return (Suspension ct ty v b)
, fNewtypeWrapM = \ty dc t -> zonkRttiType ty >>= \ty' ->
return$ NewtypeWrap ty' dc t
, fRefWrapM = \ty t -> return RefWrap `ap`
zonkRttiType ty `ap` return t
, fPrimM = (return.) . Prim })
zonkRttiType :: TcType -> TcM Type
-- Zonk the type, replacing any unbound Meta tyvars
-- by skolems, safely out of Meta-tyvar-land
zonkRttiType = zonkTcTypeToType (mkEmptyZonkEnv zonk_unbound_meta)
where
zonk_unbound_meta tv
= ASSERT( isTcTyVar tv )
do { tv' <- skolemiseUnboundMetaTyVar tv RuntimeUnk
-- This is where RuntimeUnks are born:
-- otherwise-unconstrained unification variables are
-- turned into RuntimeUnks as they leave the
-- typechecker's monad
; return (mkTyVarTy tv') }
--------------------------------------------------------------------------------
-- Restore Class predicates out of a representation type
dictsView :: Type -> Type
dictsView ty = ty
-- Use only for RTTI types
isMonomorphic :: RttiType -> Bool
isMonomorphic ty = noExistentials && noUniversals
where (tvs, _, ty') = tcSplitSigmaTy ty
noExistentials = isEmptyVarSet (tyVarsOfType ty')
noUniversals = null tvs
-- Use only for RTTI types
isMonomorphicOnNonPhantomArgs :: RttiType -> Bool
isMonomorphicOnNonPhantomArgs ty
| UnaryRep rep_ty <- repType ty
, Just (tc, all_args) <- tcSplitTyConApp_maybe rep_ty
, phantom_vars <- tyConPhantomTyVars tc
, concrete_args <- [ arg | (tyv,arg) <- tyConTyVars tc `zip` all_args
, tyv `notElem` phantom_vars]
= all isMonomorphicOnNonPhantomArgs concrete_args
| Just (ty1, ty2) <- splitFunTy_maybe ty
= all isMonomorphicOnNonPhantomArgs [ty1,ty2]
| otherwise = isMonomorphic ty
tyConPhantomTyVars :: TyCon -> [TyVar]
tyConPhantomTyVars tc
| isAlgTyCon tc
, Just dcs <- tyConDataCons_maybe tc
, dc_vars <- concatMap dataConUnivTyVars dcs
= tyConTyVars tc \\ dc_vars
tyConPhantomTyVars _ = []
type QuantifiedType = ([TyVar], Type)
-- Make the free type variables explicit
-- The returned Type should have no top-level foralls (I believe)
quantifyType :: Type -> QuantifiedType
-- Generalize the type: find all free and forall'd tyvars
-- and return them, together with the type inside, which
-- should not be a forall type.
--
-- Thus (quantifyType (forall a. a->[b]))
-- returns ([a,b], a -> [b])
quantifyType ty = (varSetElems (tyVarsOfType rho), rho)
where
(_tvs, rho) = tcSplitForAllTys ty
unlessM :: Monad m => m Bool -> m () -> m ()
unlessM condM acc = condM >>= \c -> unless c acc
-- Strict application of f at index i
appArr :: Ix i => (e -> a) -> Array i e -> Int -> a
appArr f a@(Array _ _ _ ptrs#) i@(I# i#)
= ASSERT2(i < length(elems a), ppr(length$ elems a, i))
case indexArray# ptrs# i# of
(# e #) -> f e
amap' :: (t -> b) -> Array Int t -> [b]
amap' f (Array i0 i _ arr#) = map g [0 .. i - i0]
where g (I# i#) = case indexArray# arr# i# of
(# e #) -> f e
| forked-upstream-packages-for-ghcjs/ghc | compiler/ghci/RtClosureInspect.hs | bsd-3-clause | 52,483 | 12 | 27 | 16,045 | 12,172 | 6,180 | 5,992 | -1 | -1 |
module Module where
data Foo = Foo | Foo
| hvr/jhc | regress/tests/1_typecheck/4_fail/1_fixed_bugs/multiple_constructors.hs | mit | 42 | 0 | 5 | 10 | 14 | 9 | 5 | 2 | 0 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.PackageIndex
-- Copyright : (c) David Himmelstrup 2005,
-- Bjorn Bringert 2007,
-- Duncan Coutts 2008
--
-- Maintainer : [email protected]
-- Portability : portable
--
-- An index of packages.
--
module Distribution.Client.PackageIndex (
-- * Package index data type
PackageIndex,
-- * Creating an index
fromList,
-- * Updates
merge,
insert,
deletePackageName,
deletePackageId,
deleteDependency,
-- * Queries
-- ** Precise lookups
elemByPackageId,
elemByPackageName,
lookupPackageName,
lookupPackageId,
lookupDependency,
-- ** Case-insensitive searches
searchByName,
SearchResult(..),
searchByNameSubstring,
-- ** Bulk queries
allPackages,
allPackagesByName,
) where
import Prelude hiding (lookup)
import Control.Exception (assert)
import qualified Data.Map as Map
import Data.Map (Map)
import Data.List (groupBy, sortBy, isInfixOf)
#if !MIN_VERSION_base(4,8,0)
import Data.Monoid (Monoid(..))
#endif
import Data.Maybe (isJust, fromMaybe)
import GHC.Generics (Generic)
import Distribution.Compat.Binary (Binary)
import Distribution.Compat.Semigroup (Semigroup((<>)))
import Distribution.Package
( PackageName(..), PackageIdentifier(..)
, Package(..), packageName, packageVersion
, Dependency(Dependency) )
import Distribution.Version
( withinRange )
import Distribution.Simple.Utils
( lowercase, comparing )
-- | The collection of information about packages from one or more 'PackageDB's.
--
-- It can be searched efficiently by package name and version.
--
newtype PackageIndex pkg = PackageIndex
-- This index package names to all the package records matching that package
-- name case-sensitively. It includes all versions.
--
-- This allows us to find all versions satisfying a dependency.
-- Most queries are a map lookup followed by a linear scan of the bucket.
--
(Map PackageName [pkg])
deriving (Eq, Show, Read, Functor, Generic)
--FIXME: the Functor instance here relies on no package id changes
instance Package pkg => Semigroup (PackageIndex pkg) where
(<>) = merge
instance Package pkg => Monoid (PackageIndex pkg) where
mempty = PackageIndex Map.empty
mappend = (<>)
--save one mappend with empty in the common case:
mconcat [] = mempty
mconcat xs = foldr1 mappend xs
instance Binary pkg => Binary (PackageIndex pkg)
invariant :: Package pkg => PackageIndex pkg -> Bool
invariant (PackageIndex m) = all (uncurry goodBucket) (Map.toList m)
where
goodBucket _ [] = False
goodBucket name (pkg0:pkgs0) = check (packageId pkg0) pkgs0
where
check pkgid [] = packageName pkgid == name
check pkgid (pkg':pkgs) = packageName pkgid == name
&& pkgid < pkgid'
&& check pkgid' pkgs
where pkgid' = packageId pkg'
--
-- * Internal helpers
--
mkPackageIndex :: Package pkg => Map PackageName [pkg] -> PackageIndex pkg
mkPackageIndex index = assert (invariant (PackageIndex index))
(PackageIndex index)
internalError :: String -> a
internalError name = error ("PackageIndex." ++ name ++ ": internal error")
-- | Lookup a name in the index to get all packages that match that name
-- case-sensitively.
--
lookup :: PackageIndex pkg -> PackageName -> [pkg]
lookup (PackageIndex m) name = fromMaybe [] $ Map.lookup name m
--
-- * Construction
--
-- | Build an index out of a bunch of packages.
--
-- If there are duplicates, later ones mask earlier ones.
--
fromList :: Package pkg => [pkg] -> PackageIndex pkg
fromList pkgs = mkPackageIndex
. Map.map fixBucket
. Map.fromListWith (++)
$ [ (packageName pkg, [pkg])
| pkg <- pkgs ]
where
fixBucket = -- out of groups of duplicates, later ones mask earlier ones
-- but Map.fromListWith (++) constructs groups in reverse order
map head
-- Eq instance for PackageIdentifier is wrong, so use Ord:
. groupBy (\a b -> EQ == comparing packageId a b)
-- relies on sortBy being a stable sort so we
-- can pick consistently among duplicates
. sortBy (comparing packageId)
--
-- * Updates
--
-- | Merge two indexes.
--
-- Packages from the second mask packages of the same exact name
-- (case-sensitively) from the first.
--
merge :: Package pkg => PackageIndex pkg -> PackageIndex pkg -> PackageIndex pkg
merge i1@(PackageIndex m1) i2@(PackageIndex m2) =
assert (invariant i1 && invariant i2) $
mkPackageIndex (Map.unionWith mergeBuckets m1 m2)
-- | Elements in the second list mask those in the first.
mergeBuckets :: Package pkg => [pkg] -> [pkg] -> [pkg]
mergeBuckets [] ys = ys
mergeBuckets xs [] = xs
mergeBuckets xs@(x:xs') ys@(y:ys') =
case packageId x `compare` packageId y of
GT -> y : mergeBuckets xs ys'
EQ -> y : mergeBuckets xs' ys'
LT -> x : mergeBuckets xs' ys
-- | Inserts a single package into the index.
--
-- This is equivalent to (but slightly quicker than) using 'mappend' or
-- 'merge' with a singleton index.
--
insert :: Package pkg => pkg -> PackageIndex pkg -> PackageIndex pkg
insert pkg (PackageIndex index) = mkPackageIndex $
Map.insertWith (\_ -> insertNoDup) (packageName pkg) [pkg] index
where
pkgid = packageId pkg
insertNoDup [] = [pkg]
insertNoDup pkgs@(pkg':pkgs') = case compare pkgid (packageId pkg') of
LT -> pkg : pkgs
EQ -> pkg : pkgs'
GT -> pkg' : insertNoDup pkgs'
-- | Internal delete helper.
--
delete :: Package pkg => PackageName -> (pkg -> Bool) -> PackageIndex pkg -> PackageIndex pkg
delete name p (PackageIndex index) = mkPackageIndex $
Map.update filterBucket name index
where
filterBucket = deleteEmptyBucket
. filter (not . p)
deleteEmptyBucket [] = Nothing
deleteEmptyBucket remaining = Just remaining
-- | Removes a single package from the index.
--
deletePackageId :: Package pkg => PackageIdentifier -> PackageIndex pkg -> PackageIndex pkg
deletePackageId pkgid =
delete (packageName pkgid) (\pkg -> packageId pkg == pkgid)
-- | Removes all packages with this (case-sensitive) name from the index.
--
deletePackageName :: Package pkg => PackageName -> PackageIndex pkg -> PackageIndex pkg
deletePackageName name =
delete name (\pkg -> packageName pkg == name)
-- | Removes all packages satisfying this dependency from the index.
--
deleteDependency :: Package pkg => Dependency -> PackageIndex pkg -> PackageIndex pkg
deleteDependency (Dependency name verstionRange) =
delete name (\pkg -> packageVersion pkg `withinRange` verstionRange)
--
-- * Bulk queries
--
-- | Get all the packages from the index.
--
allPackages :: PackageIndex pkg -> [pkg]
allPackages (PackageIndex m) = concat (Map.elems m)
-- | Get all the packages from the index.
--
-- They are grouped by package name, case-sensitively.
--
allPackagesByName :: PackageIndex pkg -> [[pkg]]
allPackagesByName (PackageIndex m) = Map.elems m
--
-- * Lookups
--
elemByPackageId :: Package pkg => PackageIndex pkg -> PackageIdentifier -> Bool
elemByPackageId index = isJust . lookupPackageId index
elemByPackageName :: Package pkg => PackageIndex pkg -> PackageName -> Bool
elemByPackageName index = not . null . lookupPackageName index
-- | Does a lookup by package id (name & version).
--
-- Since multiple package DBs mask each other case-sensitively by package name,
-- then we get back at most one package.
--
lookupPackageId :: Package pkg => PackageIndex pkg -> PackageIdentifier -> Maybe pkg
lookupPackageId index pkgid =
case [ pkg | pkg <- lookup index (packageName pkgid)
, packageId pkg == pkgid ] of
[] -> Nothing
[pkg] -> Just pkg
_ -> internalError "lookupPackageIdentifier"
-- | Does a case-sensitive search by package name.
--
lookupPackageName :: Package pkg => PackageIndex pkg -> PackageName -> [pkg]
lookupPackageName index name =
[ pkg | pkg <- lookup index name
, packageName pkg == name ]
-- | Does a case-sensitive search by package name and a range of versions.
--
-- We get back any number of versions of the specified package name, all
-- satisfying the version range constraint.
--
lookupDependency :: Package pkg => PackageIndex pkg -> Dependency -> [pkg]
lookupDependency index (Dependency name versionRange) =
[ pkg | pkg <- lookup index name
, packageName pkg == name
, packageVersion pkg `withinRange` versionRange ]
--
-- * Case insensitive name lookups
--
-- | Does a case-insensitive search by package name.
--
-- If there is only one package that compares case-insensitively to this name
-- then the search is unambiguous and we get back all versions of that package.
-- If several match case-insensitively but one matches exactly then it is also
-- unambiguous.
--
-- If however several match case-insensitively and none match exactly then we
-- have an ambiguous result, and we get back all the versions of all the
-- packages. The list of ambiguous results is split by exact package name. So
-- it is a non-empty list of non-empty lists.
--
searchByName :: PackageIndex pkg
-> String -> [(PackageName, [pkg])]
searchByName (PackageIndex m) name =
[ pkgs
| pkgs@(PackageName name',_) <- Map.toList m
, lowercase name' == lname ]
where
lname = lowercase name
data SearchResult a = None | Unambiguous a | Ambiguous [a]
-- | Does a case-insensitive substring search by package name.
--
-- That is, all packages that contain the given string in their name.
--
searchByNameSubstring :: PackageIndex pkg
-> String -> [(PackageName, [pkg])]
searchByNameSubstring (PackageIndex m) searchterm =
[ pkgs
| pkgs@(PackageName name, _) <- Map.toList m
, lsearchterm `isInfixOf` lowercase name ]
where
lsearchterm = lowercase searchterm
| tolysz/prepare-ghcjs | spec-lts8/cabal/cabal-install/Distribution/Client/PackageIndex.hs | bsd-3-clause | 10,243 | 0 | 13 | 2,289 | 2,255 | 1,229 | 1,026 | 152 | 4 |
{-# LANGUAGE Unsafe #-}
{-# LANGUAGE NoImplicitPrelude, MagicHash, UnboxedTuples #-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
{-# OPTIONS_HADDOCK not-home #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.MVar
-- Copyright : (c) The University of Glasgow 2008
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- The MVar type
--
-----------------------------------------------------------------------------
module GHC.MVar (
-- * MVars
MVar(..)
, newMVar
, newEmptyMVar
, takeMVar
, readMVar
, putMVar
, tryTakeMVar
, tryPutMVar
, tryReadMVar
, isEmptyMVar
, addMVarFinalizer
) where
import GHC.Base
data MVar a = MVar (MVar# RealWorld a)
{- ^
An 'MVar' (pronounced \"em-var\") is a synchronising variable, used
for communication between concurrent threads. It can be thought of
as a box, which may be empty or full.
-}
-- pull in Eq (Mvar a) too, to avoid GHC.Conc being an orphan-instance module
-- | @since 4.1.0.0
instance Eq (MVar a) where
(MVar mvar1#) == (MVar mvar2#) = isTrue# (sameMVar# mvar1# mvar2#)
{-
M-Vars are rendezvous points for concurrent threads. They begin
empty, and any attempt to read an empty M-Var blocks. When an M-Var
is written, a single blocked thread may be freed. Reading an M-Var
toggles its state from full back to empty. Therefore, any value
written to an M-Var may only be read once. Multiple reads and writes
are allowed, but there must be at least one read between any two
writes.
-}
--Defined in IOBase to avoid cycle: data MVar a = MVar (SynchVar# RealWorld a)
-- |Create an 'MVar' which is initially empty.
newEmptyMVar :: IO (MVar a)
newEmptyMVar = IO $ \ s# ->
case newMVar# s# of
(# s2#, svar# #) -> (# s2#, MVar svar# #)
-- |Create an 'MVar' which contains the supplied value.
newMVar :: a -> IO (MVar a)
newMVar value =
newEmptyMVar >>= \ mvar ->
putMVar mvar value >>
return mvar
-- |Return the contents of the 'MVar'. If the 'MVar' is currently
-- empty, 'takeMVar' will wait until it is full. After a 'takeMVar',
-- the 'MVar' is left empty.
--
-- There are two further important properties of 'takeMVar':
--
-- * 'takeMVar' is single-wakeup. That is, if there are multiple
-- threads blocked in 'takeMVar', and the 'MVar' becomes full,
-- only one thread will be woken up. The runtime guarantees that
-- the woken thread completes its 'takeMVar' operation.
--
-- * When multiple threads are blocked on an 'MVar', they are
-- woken up in FIFO order. This is useful for providing
-- fairness properties of abstractions built using 'MVar's.
--
takeMVar :: MVar a -> IO a
takeMVar (MVar mvar#) = IO $ \ s# -> takeMVar# mvar# s#
-- |Atomically read the contents of an 'MVar'. If the 'MVar' is
-- currently empty, 'readMVar' will wait until it is full.
-- 'readMVar' is guaranteed to receive the next 'putMVar'.
--
-- 'readMVar' is multiple-wakeup, so when multiple readers are
-- blocked on an 'MVar', all of them are woken up at the same time.
--
-- /Compatibility note:/ Prior to base 4.7, 'readMVar' was a combination
-- of 'takeMVar' and 'putMVar'. This mean that in the presence of
-- other threads attempting to 'putMVar', 'readMVar' could block.
-- Furthermore, 'readMVar' would not receive the next 'putMVar' if there
-- was already a pending thread blocked on 'takeMVar'. The old behavior
-- can be recovered by implementing 'readMVar as follows:
--
-- @
-- readMVar :: MVar a -> IO a
-- readMVar m =
-- mask_ $ do
-- a <- takeMVar m
-- putMVar m a
-- return a
-- @
readMVar :: MVar a -> IO a
readMVar (MVar mvar#) = IO $ \ s# -> readMVar# mvar# s#
-- |Put a value into an 'MVar'. If the 'MVar' is currently full,
-- 'putMVar' will wait until it becomes empty.
--
-- There are two further important properties of 'putMVar':
--
-- * 'putMVar' is single-wakeup. That is, if there are multiple
-- threads blocked in 'putMVar', and the 'MVar' becomes empty,
-- only one thread will be woken up. The runtime guarantees that
-- the woken thread completes its 'putMVar' operation.
--
-- * When multiple threads are blocked on an 'MVar', they are
-- woken up in FIFO order. This is useful for providing
-- fairness properties of abstractions built using 'MVar's.
--
putMVar :: MVar a -> a -> IO ()
putMVar (MVar mvar#) x = IO $ \ s# ->
case putMVar# mvar# x s# of
s2# -> (# s2#, () #)
-- |A non-blocking version of 'takeMVar'. The 'tryTakeMVar' function
-- returns immediately, with 'Nothing' if the 'MVar' was empty, or
-- @'Just' a@ if the 'MVar' was full with contents @a@. After 'tryTakeMVar',
-- the 'MVar' is left empty.
tryTakeMVar :: MVar a -> IO (Maybe a)
tryTakeMVar (MVar m) = IO $ \ s ->
case tryTakeMVar# m s of
(# s', 0#, _ #) -> (# s', Nothing #) -- MVar is empty
(# s', _, a #) -> (# s', Just a #) -- MVar is full
-- |A non-blocking version of 'putMVar'. The 'tryPutMVar' function
-- attempts to put the value @a@ into the 'MVar', returning 'True' if
-- it was successful, or 'False' otherwise.
tryPutMVar :: MVar a -> a -> IO Bool
tryPutMVar (MVar mvar#) x = IO $ \ s# ->
case tryPutMVar# mvar# x s# of
(# s, 0# #) -> (# s, False #)
(# s, _ #) -> (# s, True #)
-- |A non-blocking version of 'readMVar'. The 'tryReadMVar' function
-- returns immediately, with 'Nothing' if the 'MVar' was empty, or
-- @'Just' a@ if the 'MVar' was full with contents @a@.
--
-- @since 4.7.0.0
tryReadMVar :: MVar a -> IO (Maybe a)
tryReadMVar (MVar m) = IO $ \ s ->
case tryReadMVar# m s of
(# s', 0#, _ #) -> (# s', Nothing #) -- MVar is empty
(# s', _, a #) -> (# s', Just a #) -- MVar is full
-- |Check whether a given 'MVar' is empty.
--
-- Notice that the boolean value returned is just a snapshot of
-- the state of the MVar. By the time you get to react on its result,
-- the MVar may have been filled (or emptied) - so be extremely
-- careful when using this operation. Use 'tryTakeMVar' instead if possible.
isEmptyMVar :: MVar a -> IO Bool
isEmptyMVar (MVar mv#) = IO $ \ s# ->
case isEmptyMVar# mv# s# of
(# s2#, flg #) -> (# s2#, isTrue# (flg /=# 0#) #)
-- |Add a finalizer to an 'MVar' (GHC only). See "Foreign.ForeignPtr" and
-- "System.Mem.Weak" for more about finalizers.
addMVarFinalizer :: MVar a -> IO () -> IO ()
addMVarFinalizer (MVar m) (IO finalizer) =
IO $ \s -> case mkWeak# m () finalizer s of { (# s1, _ #) -> (# s1, () #) }
| sdiehl/ghc | libraries/base/GHC/MVar.hs | bsd-3-clause | 6,746 | 0 | 13 | 1,549 | 913 | 521 | 392 | 59 | 2 |
module T13568 where
import T13568a
data S = A
foo :: A -> ()
foo = undefined
| ezyang/ghc | testsuite/tests/rename/should_fail/T13568.hs | bsd-3-clause | 80 | 0 | 6 | 20 | 30 | 18 | 12 | 5 | 1 |
{-# LANGUAGE MagicHash, UnboxedTuples #-}
{-# OPTIONS_GHC -funfolding-use-threshold=10 #-}
module T13155 where
import GHC.Ptr
import GHC.Prim
import GHC.Exts
foo :: Ptr Float -> State# RealWorld -> (# State# RealWorld, Float #)
foo p s = case q :: Ptr Float of { Ptr a1 ->
case readFloatOffAddr# a1 0# s of { (# s1, f1 #) ->
case q :: Ptr Float of { Ptr a2 ->
case readFloatOffAddr# a2 1# s of { (# s2, f2 #) ->
(# s2, F# (plusFloat# f1 f2) #) }}}}
where
q :: Ptr a -- Polymorphic
q = p `plusPtr` 4
| ezyang/ghc | testsuite/tests/simplCore/should_compile/T13155.hs | bsd-3-clause | 553 | 0 | 20 | 153 | 186 | 101 | 85 | 14 | 1 |
module Parallel where
import Control.Monad (foldM, when)
import Data.Foldable (traverse_)
import Control.Exception
import Control.Concurrent
import Control.Concurrent.Chan
import qualified Data.IntMap as IntMap
import Data.IntMap (IntMap)
data TaskStatus a
= Running ThreadId
| Failed SomeException
| Completed a
deriving Show
-- | Return true if and only if a task is in running state
isRunning Running{} = True
isRunning _ = False
-- | Terminate a task if it is still running
cleanup :: TaskStatus a -> IO ()
cleanup (Running threadId) = killThread threadId
cleanup _ = return ()
parallelSearch ::
Int {- ^ number of tasks to run in parallel -} ->
(a -> Bool) {- ^ predicate for success -} ->
[IO a] {- ^ list of all tasks -} ->
(IntMap (TaskStatus a) -> IO ()) ->
IO ()
parallelSearch n isDone tasks onChange =
do let (startup, delayed) = splitAt n (zip [0..] tasks)
chan <- newChan
statuses <- foldM (launch chan) IntMap.empty startup
loop chan delayed statuses
where
isDoneStatus (Completed x) = isDone x
isDoneStatus _ = False
-- handle all events until no tasks are running
loop chan delayed statuses =
do (i, event) <- readChan chan
loopLaunch chan delayed =<< handleEvent i event statuses
-- process a single task completion event, return updated statuses
handleEvent i event statuses =
case event of
Left e -> return (IntMap.insert i (Failed e) statuses)
Right x ->
do let statuses' = IntMap.insert i (Completed x) statuses
(earlier,later) = IntMap.split i statuses'
traverse_ cleanup (if isDone x then later else earlier)
onChange statuses'
return statuses'
-- launch the next task if appropriate and return to event loop
loopLaunch chan (task:tasks) statuses | not (any isDoneStatus statuses) =
loop chan tasks =<< launch chan statuses task
loopLaunch chan _ statuses =
when (any isRunning statuses) (loop chan [] statuses)
launch chan statuses (i, task) =
do taskId <- forkFinally task (\res -> writeChan chan (i, res))
let statuses' = IntMap.insert i (Running taskId) statuses
onChange statuses'
return statuses'
| glguy/5puzzle | src/Parallel.hs | isc | 2,317 | 0 | 17 | 619 | 684 | 343 | 341 | 52 | 5 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE GADTs #-}
module Data.Coord where
import Data.Positive
import Control.Applicative (liftA2)
import Control.Comonad
import Control.Lens
data Vector n a where
SingleVector :: a -> Vector One a
AddVector :: a -> Vector n a -> Vector (Succ n) a
vectorHead :: Vector n a -> a
vectorHead (SingleVector a) = a
vectorHead (AddVector a _) = a
vectorTail :: Vector (Succ n) a -> Vector n a
vectorTail (AddVector _ n) = n
vectorAddToBack :: a -> Vector n a -> Vector (Succ n) a
vectorAddToBack a (SingleVector b) = b *: a
vectorAddToBack a (AddVector b n) =
AddVector b (vectorAddToBack a n)
vectorCycle :: Vector (Succ n) a -> Vector (Succ n) a
vectorCycle a = vectorHead a `vectorAddToBack` vectorTail a
class IterVector n where
iterateVector :: (a -> a) -> a -> Vector n a
instance IterVector One where
iterateVector func a = SingleVector a
instance IterVector n =>
IterVector (Succ n) where
iterateVector func a = AddVector a (iterateVector func (func a))
instance (IterVector (Succ n)) =>
Comonad (Vector (Succ n)) where
extract = vectorHead
duplicate
:: forall n a.
IterVector (Succ n)
=> Vector (Succ n) a -> Vector (Succ n) (Vector (Succ n) a)
duplicate = iterateVector @(Succ n) vectorCycle
coordHead :: Lens' (Vector n a) a
coordHead = lens getter setter
where
getter :: Vector n a -> a
getter (SingleVector a) = a
getter (AddVector a _) = a
setter :: Vector n a -> a -> Vector n a
setter (SingleVector _) a = SingleVector a
setter (AddVector _ n) a = AddVector a n
coordNext :: Lens' (Vector (Succ n) a) (Vector n a)
coordNext = lens getter setter
where
getter :: Vector (Succ n) a -> Vector n a
getter (AddVector _ n) = n
setter :: Vector (Succ n) a -> Vector n a -> Vector (Succ n) a
setter (AddVector a _) n = AddVector a n
instance Field1 (Vector n a) (Vector n a) a a where
_1 = coordHead
instance Field2 (Vector (Succ n) a) (Vector (Succ n) a) a a where
_2 = coordNext . _1
instance Field3 (Vector (Succ (Succ n)) a) (Vector (Succ (Succ n)) a) a a where
_3 = coordNext . _2
instance Field4 (Vector (Succ (Succ (Succ n))) a) (Vector (Succ (Succ (Succ n))) a) a a where
_4 = coordNext . _3
instance Field5 (Vector (Succ (Succ (Succ (Succ n)))) a) (Vector (Succ (Succ (Succ (Succ n)))) a) a a where
_5 = coordNext . _4
instance Field6 (Vector (Succ (Succ (Succ (Succ (Succ n))))) a) (Vector (Succ (Succ (Succ (Succ (Succ n))))) a) a a where
_6 = coordNext . _5
instance Field7 (Vector (Succ (Succ (Succ (Succ (Succ (Succ n)))))) a) (Vector (Succ (Succ (Succ (Succ (Succ (Succ n)))))) a) a a where
_7 = coordNext . _6
instance Field8 (Vector (Succ (Succ (Succ (Succ (Succ (Succ (Succ n))))))) a) (Vector (Succ (Succ (Succ (Succ (Succ (Succ (Succ n))))))) a) a a where
_8 = coordNext . _7
instance Field9 (Vector (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ n)))))))) a) (Vector (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ n)))))))) a) a a where
_9 = coordNext . _8
deriving instance Eq a => Eq (Vector n a)
deriving instance Functor (Vector n)
deriving instance Foldable (Vector n)
deriving instance Traversable (Vector n)
instance Show a =>
Show (Vector n a) where
show (AddVector a (SingleVector b)) = show a ++ " *: " ++ show b
show (AddVector a n) = show a ++ " *:* " ++ show n
show (SingleVector a) = show a
instance Applicative (Vector One) where
pure = SingleVector
SingleVector a <*> SingleVector b = SingleVector $ a b
instance Applicative (Vector n) =>
Applicative (Vector (Succ n)) where
pure a = AddVector a (pure a)
AddVector a na <*> AddVector b nb = AddVector (a b) (na <*> nb)
instance (Num a, Applicative (Vector n)) =>
Num (Vector n a) where
(+) = liftA2 (+)
(*) = liftA2 (*)
abs = fmap abs
signum = fmap signum
fromInteger = pure . fromInteger
negate = fmap negate
(*:*) :: a -> Vector n a -> Vector (Succ n) a
(*:*) = AddVector
infixr 4 *:*
(*:) :: a -> a -> Vector Two a
(*:) a b = AddVector a (SingleVector b)
infixr 4 *:
newtype Coord n a =
Coord (Vector n a)
deriving (Eq, Show, Functor, Foldable, Traversable)
makeWrapped ''Coord
singleCoord :: a -> Coord One a
singleCoord = Coord . SingleVector
addCoord :: a -> Coord n a -> Coord (Succ n) a
addCoord a (Coord n) = Coord (AddVector a n)
deriving instance Applicative (Coord One)
instance Applicative (Vector n) =>
Applicative (Coord n) where
pure = Coord . pure
Coord a <*> Coord b = Coord $ a <*> b
instance Field1 (Coord n a) (Coord n a) a a where
_1 = _Wrapped' . coordHead
instance Field2 (Coord (Succ n) a) (Coord (Succ n) a) a a where
_2 = _Wrapped' . coordNext . _1
instance Field3 (Coord (Succ (Succ n)) a) (Coord (Succ (Succ n)) a) a a where
_3 = _Wrapped' . coordNext . _2
instance Field4 (Coord (Succ (Succ (Succ n))) a) (Coord (Succ (Succ (Succ n))) a) a a where
_4 = _Wrapped' . coordNext . _3
instance Field5 (Coord (Succ (Succ (Succ (Succ n)))) a) (Coord (Succ (Succ (Succ (Succ n)))) a) a a where
_5 = _Wrapped' . coordNext . _4
instance Field6 (Coord (Succ (Succ (Succ (Succ (Succ n))))) a) (Coord (Succ (Succ (Succ (Succ (Succ n))))) a) a a where
_6 = _Wrapped' . coordNext . _5
instance Field7 (Coord (Succ (Succ (Succ (Succ (Succ (Succ n)))))) a) (Coord (Succ (Succ (Succ (Succ (Succ (Succ n)))))) a) a a where
_7 = _Wrapped' . coordNext . _6
instance Field8 (Coord (Succ (Succ (Succ (Succ (Succ (Succ (Succ n))))))) a) (Coord (Succ (Succ (Succ (Succ (Succ (Succ (Succ n))))))) a) a a where
_8 = _Wrapped' . coordNext . _7
instance Field9 (Coord (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ n)))))))) a) (Coord (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ n)))))))) a) a a where
_9 = _Wrapped' . coordNext . _8
| edwardwas/dimensional-cellular-automata | src/Data/Coord.hs | isc | 6,238 | 0 | 23 | 1,342 | 3,111 | 1,572 | 1,539 | 141 | 3 |
import Data.List (sortBy)
main = putStrLn $ show solve
solve :: Int
solve = head $ sortBy (\x y -> compare y x) $ palindromeProducts 100 999
palindromeProducts :: Int -> Int -> [Int]
palindromeProducts l h = map read $ filter isPalindrome $ map show [x*y | x <- [l..h], y <- [x..h]]
isPalindrome :: (Eq a) => [a] -> Bool
isPalindrome x = x == reverse x
| pshendry/project-euler-solutions | 0004/solution.hs | mit | 357 | 5 | 10 | 73 | 195 | 94 | 101 | 8 | 1 |
module ProjectEuler.Problem139
( problem
) where
import Control.Monad
import ProjectEuler.Types
problem :: Problem
problem = pureProblem 139 Solved result
{-
Get some initial search going.
for m > n > 0, we can generate pythagorean triples through:
a = m^2 - n^2
b = 2*m*n
c = m^2 + n^2
For the tuple to be tile-able, we need: c `mod` abs(a-b) == 0.
Perimeter:
a + b + c = 2*m*(m+n)*k < 100,000,000.
since m > n: 2*m*(m+n)*k < 4 * m^2 * k
this might overshoot but nonetheless gives us a rough bound to work with:
we can guesstimate upperbound of m to be somewhere around sqrt(100,000,000 / 4) = 5000
-}
result :: Int
result = sum $ do
-- was 5000, but then we have (m, n, k) = (5741,2378,1) ...
m <- [1 .. 5800]
{-
by generating n this way, we make sure that m and n are not both odd
without guarding.
-}
n <- if even m
then [1 .. m-1]
else [2,4 .. m-1]
-- it is important that m and n are not both odd.
guard $ gcd m n == 1
let a = m * m - n * n
b = 2 * m * n
c = m * m + n * n
guard $ c `rem` (a - b) == 0
let k = 100000000 `quot` (a + b + c)
{-
at this point this list monad is generating primitive pythagorean triples.
as we only cares about how many of them are valid,
we choose to only return the counting k,
so that we can get the final answer by simply doing summation on the resulting list.
-}
pure k
| Javran/Project-Euler | src/ProjectEuler/Problem139.hs | mit | 1,432 | 0 | 14 | 408 | 234 | 127 | 107 | 19 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Greek.Parsers.MorphologyParser (
nounParser
, verbParser
, adjParser
, partParser
, pronounParser
, infParser
, advParser
, entryParser
, parseHeader
, morphParser
) where
import qualified Data.Text as T
import Data.Attoparsec.Text
import Control.Applicative
import Greek.Dictionary.Types
morphParser :: Parser [MorphEntry]
morphParser = do
parseHeader
many' entryParser
parseHeader :: Parser ()
parseHeader = do
manyTill anyChar $ string "analyses>"
skipSpace
dialectParser :: Parser [Dialect]
dialectParser = xmlWrapper "dialect" $
T.words <$> takeTill (=='<')
featureParser :: Parser Feature
featureParser = xmlWrapper "feature" $ takeTill (=='<')
numParser :: Parser (Maybe NumberGr)
numParser = option Nothing
$ xmlWrapper "number"
$ Just <$> parserMap [
("sg" , Singular)
, ("dual", Dual )
, ("pl" , Plural )
]
genderParser :: Parser (Maybe Gender)
genderParser = option Nothing
$ xmlWrapper "gender"
$ Just <$> parserMap [
("masc", Masculine)
, ("fem" , Feminine )
, ("neut", Neuter )
]
caseParser :: Parser (Maybe Case)
caseParser = option Nothing
$ xmlWrapper "case"
$ Just <$> parserMap [
("nom" , Nominative)
, ("acc" , Accusative)
, ("gen" , Genitive )
, ("voc" , Vocative )
, ("dat" , Dative )
]
personParser :: Parser (Maybe Person)
personParser = option Nothing
$ xmlWrapper "person"
$ Just <$> parserMap [
("1st" , First)
, ("2nd" , Second)
, ("3rd" , Third)
]
tenseParser :: Parser (Maybe Tense)
tenseParser = option Nothing
$ xmlWrapper "tense"
$ Just <$> parserMap [
("pres" , Present)
, ("imperf" , Imperfect)
, ("futperf", FuturePerfect)
, ("fut" , Future)
, ("aor" , Aorist)
, ("perf" , Perfect)
, ("plup" , Pluperfect)
]
moodParser :: Parser (Maybe Mood)
moodParser = option Nothing
$ xmlWrapper "mood"
$ Just <$> parserMap [
("ind" , Indicative )
, ("imperat" , Imperative )
, ("subj" , Subjunctive)
, ("opt" , Optative )
]
voiceParser :: Parser (Maybe Voice)
voiceParser = option Nothing
$ xmlWrapper "voice"
$ Just <$> parserMap [
("act" , Active )
, ("pass", Passive)
, ("mid" , Middle )
, ("mp" , MidPass)
]
degParser :: Parser (Maybe Degree)
degParser = option Nothing
$ xmlWrapper "degree"
$ Just <$> parserMap [
("comp" , Comparative )
, ("superl" , Superlative)
]
entryParser :: Parser MorphEntry
entryParser = tok $ xmlWrapper "analysis" $ tok $ do
frm <- xmlWrapper "form" $ takeTill (=='<')
lma <- xmlWrapper "lemma" $ takeTill (=='<')
mrph <- tok $ (MorphNoun <$> nounParser)
<|> (MorphInf <$> infParser)
<|> (MorphVerb <$> verbParser)
<|> (MorphPron <$> pronounParser)
<|> (MorphAdj <$> adjParser)
<|> (MorphPart <$> partParser)
<|> (MorphAdv <$> advParser)
<|> (MorphPrep <$> prepParser)
<|> (MorphExcl <$> exclParser)
<|> (MorphAdvl <$> advlParser)
<|> (MorphConj <$> conjParser)
<|> (MorphParc <$> parcParser)
<|> (MorphArt <$> artParser)
<|> (MorphNum <$> numeralParser)
<|> (MorphIrr <$> irrParser)
d <- option [T.empty] dialectParser
f <- option T.empty featureParser
return $ MorphEntry frm lma mrph d f
verbParser :: Parser Verb
verbParser = string "<pos>verb</pos>" >>
Verb <$> personParser
<*> numParser
<*> tenseParser
<*> moodParser
<*> (voiceParser <* (genderParser >> caseParser)) --for *)/aracon
infParser :: Parser Infinitive
infParser = string "<pos>verb</pos>" >>
Infinitive <$> tenseParser
<*> (string "<mood>inf</mood>" >> voiceParser)
nounParser :: Parser Noun
nounParser = string "<pos>noun</pos>" >>
Noun <$> numParser
<*> genderParser
<*> caseParser
adjParser :: Parser Adjective
adjParser = string "<pos>adj</pos>" >>
Adjective <$> numParser
<*> genderParser
<*> caseParser
<*> degParser
partParser :: Parser Participle
partParser = string "<pos>part</pos>" >>
Participle <$> numParser
<*> tenseParser
<*> voiceParser
<*> genderParser
<*> caseParser
pronounParser :: Parser Pronoun
pronounParser = string "<pos>pron</pos>" >>
Pronoun <$> personParser
<*> numParser
<*> genderParser
<*> caseParser
artParser :: Parser Article
artParser = string "<pos>article</pos>" >>
Article <$> numParser
<*> genderParser
<*> caseParser
advParser :: Parser Adverb
advParser = string "<pos>adv</pos>" >>
Adverb <$> (degParser <* (numParser >> genderParser >> caseParser)) -- for be/nqosde / o(/n
prepParser :: Parser Preposition
prepParser = string "<pos>prep</pos>" >>
Preposition <$> degParser
exclParser :: Parser Exclamation
exclParser = "<pos>exclam</pos>" *> return Exclamation
advlParser :: Parser Adverbial
advlParser = string "<pos>adverbial</pos>" >>
Adverbial <$> degParser
conjParser :: Parser Conjunction
conjParser = "<pos>conj</pos>" *> return Conjunction
parcParser :: Parser Particle
parcParser = "<pos>partic</pos>" *> return Particle
irrParser :: Parser Irregular
irrParser = do
string "<pos>irreg</pos>"
numParser
genderParser
caseParser
return Irregular
numeralParser :: Parser Numeral
numeralParser = do
string "<pos>numeral</pos>"
Numeral <$> numParser
<*> genderParser
<*> caseParser
xmlWrapper :: T.Text -> Parser a -> Parser a
xmlWrapper st p = do
char '<'
string st
char '>'
val <- p
string "</"
string st
char '>'
return val
parserMap :: (Monad f, Alternative f) => [(f a1, a)] -> f a
parserMap xs = choice $ map (\(a,b) -> a *> return b) xs
tok :: Parser a -> Parser a
tok p = do
skipSpace
x <- p
skipSpace
return x | boundedvariation/ntbible | Greek/Parsers/MorphologyParser.hs | mit | 6,155 | 0 | 25 | 1,698 | 1,761 | 924 | 837 | 200 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell, CPP #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE PatternGuards #-}
-- | Static file serving for WAI.
module Network.Wai.Application.Static
( -- * WAI application
staticApp
-- ** Default Settings
, defaultWebAppSettings
, webAppSettingsWithLookup
, defaultFileServerSettings
, embeddedSettings
-- ** Settings
, StaticSettings
, ssLookupFile
, ssMkRedirect
, ssGetMimeType
, ssListing
, ssIndices
, ssMaxAge
, ssRedirectToIndex
) where
import Prelude hiding (FilePath)
import qualified Network.Wai as W
import qualified Network.HTTP.Types as H
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as S8
import qualified Data.ByteString.Lazy as L
import Data.ByteString.Lazy.Char8 ()
import Control.Monad.IO.Class (liftIO)
import Blaze.ByteString.Builder (toByteString)
import Data.FileEmbed (embedFile)
import Data.Text (Text)
import qualified Data.Text as T
import Data.Either (rights)
import Network.HTTP.Date (parseHTTPDate, epochTimeToHTTPDate, formatHTTPDate)
import Data.Monoid (First (First, getFirst), mconcat)
import WaiAppStatic.Types
import Util
import WaiAppStatic.Storage.Filesystem
import WaiAppStatic.Storage.Embedded
import Network.Mime (MimeType)
data StaticResponse =
-- | Just the etag hash or Nothing for no etag hash
Redirect Pieces (Maybe ByteString)
| RawRedirect ByteString
| NotFound
| FileResponse File H.ResponseHeaders
| NotModified
-- TODO: add file size
| SendContent MimeType L.ByteString
| WaiResponse W.Response
safeInit :: [a] -> [a]
safeInit [] = []
safeInit xs = init xs
filterButLast :: (a -> Bool) -> [a] -> [a]
filterButLast _ [] = []
filterButLast _ [x] = [x]
filterButLast f (x:xs)
| f x = x : filterButLast f xs
| otherwise = filterButLast f xs
-- | Serve an appropriate response for a folder request.
serveFolder :: StaticSettings -> Pieces -> W.Request -> Folder -> IO StaticResponse
serveFolder ss@StaticSettings {..} pieces req folder@Folder {..} =
-- first check if there is an index file in this folder
case getFirst $ mconcat $ map (findIndex $ rights folderContents) ssIndices of
Just index ->
let pieces' = setLast pieces index in
case () of
() | ssRedirectToIndex -> return $ Redirect pieces' Nothing
| Just path <- addTrailingSlash req ->
return $ RawRedirect path
| otherwise ->
-- start the checking process over, with a new set
checkPieces ss pieces' req
Nothing ->
case ssListing of
Just _ | Just path <- addTrailingSlash req ->
return $ RawRedirect path
Just listing -> do
-- directory listings turned on, display it
builder <- listing pieces folder
return $ WaiResponse $ W.responseBuilder H.status200
[ ("Content-Type", "text/html; charset=utf-8")
] builder
Nothing -> return $ WaiResponse $ W.responseLBS H.status403
[ ("Content-Type", "text/plain")
] "Directory listings disabled"
where
setLast :: Pieces -> Piece -> Pieces
setLast [] x = [x]
setLast [t] x
| fromPiece t == "" = [x]
setLast (a:b) x = a : setLast b x
addTrailingSlash :: W.Request -> Maybe ByteString
addTrailingSlash req
| S8.null rp = Just "/"
| S8.last rp == '/' = Nothing
| otherwise = Just $ S8.snoc rp '/'
where
rp = W.rawPathInfo req
noTrailingSlash :: Pieces -> Bool
noTrailingSlash [] = False
noTrailingSlash [x] = fromPiece x /= ""
noTrailingSlash (_:xs) = noTrailingSlash xs
findIndex :: [File] -> Piece -> First Piece
findIndex files index
| index `elem` map fileName files = First $ Just index
| otherwise = First Nothing
checkPieces :: StaticSettings
-> Pieces -- ^ parsed request
-> W.Request
-> IO StaticResponse
-- If we have any empty pieces in the middle of the requested path, generate a
-- redirect to get rid of them.
checkPieces _ pieces _ | any (T.null . fromPiece) $ safeInit pieces =
return $ Redirect (filterButLast (not . T.null . fromPiece) pieces) Nothing
checkPieces ss@StaticSettings {..} pieces req = do
res <- ssLookupFile pieces
case res of
LRNotFound -> return NotFound
LRFile file -> serveFile ss req file
LRFolder folder -> serveFolder ss pieces req folder
serveFile :: StaticSettings -> W.Request -> File -> IO StaticResponse
serveFile StaticSettings {..} req file
-- First check etag values, if turned on
| ssUseHash = do
mHash <- fileGetHash file
case (mHash, lookup "if-none-match" $ W.requestHeaders req) of
-- if-none-match matches the actual hash, return a 304
(Just hash, Just lastHash) | hash == lastHash -> return NotModified
-- Didn't match, but we have a hash value. Send the file contents
-- with an ETag header.
--
-- Note: It would be arguably better to next check
-- if-modified-since and return a 304 if that indicates a match as
-- well. However, the circumstances under which such a situation
-- could arise would be very anomolous, and should likely warrant a
-- new file being sent anyway.
(Just hash, _) -> respond [("ETag", hash)]
-- No hash value available, fall back to last modified support.
(Nothing, _) -> lastMod
-- etag turned off, so jump straight to last modified
| otherwise = lastMod
where
mLastSent = lookup "if-modified-since" (W.requestHeaders req) >>= parseHTTPDate
lastMod =
case (fmap epochTimeToHTTPDate $ fileGetModified file, mLastSent) of
-- File modified time is equal to the if-modified-since header,
-- return a 304.
--
-- Question: should the comparison be, date <= lastSent?
(Just mdate, Just lastSent)
| mdate == lastSent -> return NotModified
-- Did not match, but we have a new last-modified header
(Just mdate, _) -> respond [("last-modified", formatHTTPDate mdate)]
-- No modification time available
(Nothing, _) -> respond []
-- Send a file response with the additional weak headers provided.
respond headers = return $ FileResponse file $ cacheControl ssMaxAge headers
-- | Return a difference list of headers based on the specified MaxAge.
--
-- This function will return both Cache-Control and Expires headers, as
-- relevant.
cacheControl :: MaxAge -> (H.ResponseHeaders -> H.ResponseHeaders)
cacheControl maxage =
headerCacheControl . headerExpires
where
ccInt =
case maxage of
NoMaxAge -> Nothing
MaxAgeSeconds i -> Just i
MaxAgeForever -> Just oneYear
oneYear :: Int
oneYear = 60 * 60 * 24 * 365
headerCacheControl =
case ccInt of
Nothing -> id
Just i -> (:) ("Cache-Control", S8.append "public, max-age=" $ S8.pack $ show i)
headerExpires =
case maxage of
NoMaxAge -> id
MaxAgeSeconds _ -> id -- FIXME
MaxAgeForever -> (:) ("Expires", "Thu, 31 Dec 2037 23:55:55 GMT")
-- | Turn a @StaticSettings@ into a WAI application.
staticApp :: StaticSettings -> W.Application
staticApp set req = staticAppPieces set (W.pathInfo req) req
staticAppPieces :: StaticSettings -> [Text] -> W.Application
staticAppPieces _ _ req sendResponse
| W.requestMethod req /= "GET" = sendResponse $ W.responseLBS
H.status405
[("Content-Type", "text/plain")]
"Only GET is supported"
staticAppPieces _ [".hidden", "folder.png"] _ sendResponse = sendResponse $ W.responseLBS H.status200 [("Content-Type", "image/png")] $ L.fromChunks [$(embedFile "images/folder.png")]
staticAppPieces _ [".hidden", "haskell.png"] _ sendResponse = sendResponse $ W.responseLBS H.status200 [("Content-Type", "image/png")] $ L.fromChunks [$(embedFile "images/haskell.png")]
staticAppPieces ss rawPieces req sendResponse = liftIO $ do
case toPieces rawPieces of
Just pieces -> checkPieces ss pieces req >>= response
Nothing -> sendResponse $ W.responseLBS H.status403
[ ("Content-Type", "text/plain")
] "Forbidden"
where
response :: StaticResponse -> IO W.ResponseReceived
response (FileResponse file ch) = do
mimetype <- ssGetMimeType ss file
let filesize = fileGetSize file
let headers = ("Content-Type", mimetype)
-- Let Warp provide the content-length, since it takes
-- range requests into account
-- : ("Content-Length", S8.pack $ show filesize)
: ch
sendResponse $ fileToResponse file H.status200 headers
response NotModified =
sendResponse $ W.responseLBS H.status304 [] ""
response (SendContent mt lbs) = do
-- TODO: set caching headers
sendResponse $ W.responseLBS H.status200
[ ("Content-Type", mt)
-- TODO: set Content-Length
] lbs
response (Redirect pieces' mHash) = do
let loc = (ssMkRedirect ss) pieces' $ toByteString (H.encodePathSegments $ map fromPiece pieces')
let qString = case mHash of
Just hash -> replace "etag" (Just hash) (W.queryString req)
Nothing -> remove "etag" (W.queryString req)
sendResponse $ W.responseLBS H.status301
[ ("Content-Type", "text/plain")
, ("Location", S8.append loc $ H.renderQuery True qString)
] "Redirect"
response (RawRedirect path) =
sendResponse $ W.responseLBS H.status301
[ ("Content-Type", "text/plain")
, ("Location", path)
] "Redirect"
response NotFound = sendResponse $ W.responseLBS H.status404
[ ("Content-Type", "text/plain")
] "File not found"
response (WaiResponse r) = sendResponse r
| ygale/wai | wai-app-static/Network/Wai/Application/Static.hs | mit | 10,506 | 0 | 18 | 3,038 | 2,482 | 1,294 | 1,188 | 194 | 9 |
module Expr where
import Combinators
import Test.HUnit
import Data.Char
-- 5.5 баллов
data Value = I Int | B Bool deriving (Eq, Show)
data BinOp = Plus | Mul | Minus | Less | Greater | Equals deriving (Eq, Show)
data UnOp = Neg | Not deriving (Eq, Show)
data Expr = BinOp BinOp Expr Expr | UnOp UnOp Expr | Const Value | If Expr Expr Expr | Var String deriving (Eq, Show)
data Statement = Assign String Expr | While Expr Statement | Compound [Statement] deriving (Eq, Show)
infixr 0 @=
(@=) = Assign
(.+) = BinOp Plus
(.-) = BinOp Minus
(.*) = BinOp Mul
(.<) = BinOp Less
(.>) = BinOp Greater
int = Const . I
bool = Const . B
neg = UnOp Neg
--------------------------------------------------
-- Лексический анализ
data Lexeme
= Ident String
| NumberConst Int | BoolConst Bool
| BinOpSign BinOp
| NotKeyword | WhileKeyword | IfKeyword | ThenKeyword | ElseKeyword | AssignmentSign | SemicolonSign
| LPSign | RPSign | LBSign | RBSign
| UnknownLexeme String
deriving (Eq, Show)
lexer :: String -> [Lexeme]
lexer "" = []
lexer (x:xs) | isSpace x = lexer xs
lexer xs@(x:_) | isAlpha x || x == '_' =
let (ident, rest) = span (\x -> isAlphaNum x || x == '_') xs
in case ident of
"true" -> BoolConst True : lexer rest
"false" -> BoolConst False : lexer rest
"while" -> WhileKeyword : lexer rest
"if" -> IfKeyword : lexer rest
"then" -> ThenKeyword : lexer rest
"else" -> ElseKeyword : lexer rest
"not" -> NotKeyword : lexer rest
_ -> Ident ident : lexer rest
lexer xs@(x:_) | isDigit x =
let (number, rest) = span isDigit xs
in NumberConst (read number) : lexer rest
lexer xs@(x:_) | isOpSymbol x =
let (op, rest) = span isOpSymbol xs
in case op of
"+" -> BinOpSign Plus : lexer rest
"*" -> BinOpSign Mul : lexer rest
"-" -> BinOpSign Minus : lexer rest
"<" -> BinOpSign Less : lexer rest
">" -> BinOpSign Greater : lexer rest
"==" -> BinOpSign Equals : lexer rest
":=" -> AssignmentSign : lexer rest
";" -> SemicolonSign : lexer rest
_ -> UnknownLexeme op : lexer rest
lexer ('(':xs) = LPSign : lexer xs
lexer (')':xs) = RPSign : lexer xs
lexer ('{':xs) = LBSign : lexer xs
lexer ('}':xs) = RBSign : lexer xs
lexer (x:xs) =
let (lex, rest) = span (not . isValid) xs
in UnknownLexeme (x:lex) : lexer rest
getErrors :: [Lexeme] -> ([Lexeme], [String])
getErrors [] = ([], [])
getErrors (UnknownLexeme e : ls) =
let (rs, es) = getErrors ls
in (rs, e:es)
getErrors (l:ls) =
let (rs, es) = getErrors ls
in (l:rs, es)
isOpSymbol :: Char -> Bool
isOpSymbol c = elem c "~!@#$%^&*-+=<>?/:;"
isValid :: Char -> Bool
isValid c = isOpSymbol c || isAlphaNum c || isSpace c || elem c "(){}"
--------------------------------------------------
-- Синтаксический анализ
pValue :: Parser Lexeme Value
pValue = undefined
pExpr :: Parser Lexeme Expr
pExpr = undefined
pStatement :: Parser Lexeme Statement
pStatement = undefined
-- tests
testsValue = [ parserTestOK pValue (lexer "123") === (I 123, [])
, parserTestOK pValue (lexer "-123") === (I (-123), [])
, parserTestOK pValue (lexer "true") === (B True, [])
, parserTestOK pValue (lexer "false") === (B False, [])
]
testsExpr = [ parserTestOK pExpr (lexer "123 * x") === (int 123 .* Var "x", [])
, parserTestOK pExpr (lexer "123 + x * 5") === (int 123 .+ (Var "x" .* int 5), [])
, parserTestOK pExpr (lexer "if x > 0 then x else -x") === (If (Var "x" .> int 0) (Var "x") (neg (Var "x")), [])
]
testsStatement = [ parserTestOK pStatement (lexer "x := 3;") === ("x" @= int 3, [])
, parserTestOK pStatement (lexer "while (x > 0) x := x - 1;") === (While (Var "x" .> int 0) $ "x" @= Var "x" .- int 1, [])
, parserTestOK pStatement (lexer "r := 1; i := 0; while (i < n) { i := i + 1; r := r * i; }") === (fac, [])
]
where
fac = Compound
[ "r" @= int 1
, "i" @= int 0
, While (Var "i" .< Var "n") $ Compound
[ "i" @= Var "i" .+ int 1
, "r" @= Var "r" .* Var "i"
]
]
(===) = id
main = fmap (const ()) $ runTestTT $ test
$ label "Value" testsValue
++ label "Expr" testsExpr
++ label "Statement" testsStatement
where
label :: String -> [Test] -> [Test]
label l = map (\(i,t) -> TestLabel (l ++ " [" ++ show i ++ "]") t) . zip [1..]
| SergeyKrivohatskiy/fp_haskell | hw08/Expr.hs | mit | 4,684 | 0 | 15 | 1,373 | 1,878 | 966 | 912 | 104 | 16 |
{-# htermination (compareTup0 :: Tup0 -> Tup0 -> Ordering) #-}
import qualified Prelude
data MyBool = MyTrue | MyFalse
data List a = Cons a (List a) | Nil
data Tup0 = Tup0 ;
data Ordering = LT | EQ | GT ;
compareTup0 :: Tup0 -> Tup0 -> Ordering
compareTup0 Tup0 Tup0 = EQ;
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/basic_haskell/compare_1.hs | mit | 290 | 5 | 8 | 72 | 94 | 46 | 48 | 7 | 1 |
{-#LANGUAGE OverloadedStrings#-}
module Yesod.Raml.Routes.Internal where
import Control.Applicative
import Control.Monad
import qualified Data.Yaml as Y
import qualified Data.Yaml.Include as YI
import qualified Data.ByteString.Char8 as B
import qualified Data.Text as T
import qualified Data.Char as C
import qualified Data.Map as M
import Data.Maybe
import Data.Monoid
import Yesod.Raml.Type
import Yesod.Raml.Parser()
import Text.Regex.Posix hiding (empty)
import Language.Haskell.TH.Syntax
import Language.Haskell.TH.Quote
import Yesod.Routes.TH.Types
import Network.URI hiding (path)
routesFromRaml :: Raml -> Either String [RouteEx]
routesFromRaml raml = do
let buri = T.replace "{version}" (version raml) (baseUri raml)
uripaths <- case parsePath buri of
(Just uri) -> return $ fmap ("/" <> ) $ T.split (== '/') $ if T.isPrefixOf "/" uri then T.tail uri else uri
Nothing -> Left $ "can not parse: " ++ (T.unpack buri)
v <- forM (M.toList (paths raml)) $ \(k,v) -> do
routesFromRamlResource v $ uripaths ++ splitPath k
return $ concat v
where
parsePath uri = fmap T.pack $ fmap uriPath $ parseURI (T.unpack uri)
splitPath :: T.Text -> [T.Text]
splitPath path =
case T.split (== '/') path of
(_:xs) -> map (T.append "/") xs
_ -> [path]
methodExFromRamlMethod :: (Method,RamlMethod) -> MethodEx
methodExFromRamlMethod (method,val) =
let example = do
response <- M.lookup "200" (m_responses val)
(contentType,body) <- listToMaybe (M.toList (res_body response))
ex <- res_example body
return (contentType,ex)
in MethodEx (T.unpack (T.toUpper (method))) example
routesFromRamlResource :: RamlResource -> [Path] -> Either String [RouteEx]
routesFromRamlResource raml paths' = do
rrlist <- forM (M.toList (r_paths raml)) $ \(k,v) -> do
routesFromRamlResource v (paths' ++ splitPath k)
let rlist = concat rrlist
case toHandler Nothing raml of
Right handle -> do
let methods = flip map (M.toList (r_methods raml)) methodExFromRamlMethod
route = RouteEx {
re_pieces = toPieces paths'
, re_handler = T.unpack handle
, re_methods = methods
}
return $ route : rlist
Left err -> do
case rrlist of
[] -> Left err
_ -> return rlist
toHandler :: Maybe HandlerHint -> RamlResource -> Either String Handler
toHandler mhint ramlMethod =
(fromHandlerTag ramlMethod) <|>
(fromDescription (fromMaybe "handler: *(.*)" mhint) ramlMethod)
where
fromHandlerTag :: RamlResource -> Either String Handler
fromHandlerTag ramlMethod' = do
handler <- case r_handler ramlMethod' of
Nothing -> Left "handler of method is empty"
(Just desc') -> return desc'
return handler
fromRegex :: T.Text -> T.Text -> Maybe T.Text
fromRegex pattern str =
let v = (T.unpack str) =~ (T.unpack pattern) :: (String,String,String,[String])
in case v of
(_,_,_,[]) -> Nothing
(_,_,_,h:_) -> Just $ T.pack h
fromDescription :: HandlerHint -> RamlResource -> Either String Handler
fromDescription hint ramlMethod' = do
desc <- case r_description ramlMethod' of
Nothing -> Left "Description of method is empty"
(Just desc') -> return desc'
case (foldr (<|>) empty $ map (fromRegex hint) $ T.lines $ desc) of
Nothing -> Left "Can not find Handler"
Just handler -> return handler
toYesodResource :: RouteEx -> Resource String
toYesodResource route =
Resource {
resourceName = re_handler route
, resourcePieces = re_pieces route
, resourceDispatch =
Methods {
methodsMulti = Nothing
, methodsMethods = map me_method (re_methods route)
}
, resourceAttrs = []
, resourceCheck = True
}
toRoutesFromString :: String -> [ResourceTree String]
toRoutesFromString ramlStr =
let eRaml = Y.decodeEither (B.pack ramlStr) :: Either String Raml
raml = case eRaml of
Right v -> v
Left e -> error $ "Invalid raml :" ++ e
routes = case (routesFromRaml raml) of
Right v -> v
Left e -> error $ "Invalid resource : " ++ e
in map ResourceLeaf $ map toYesodResource routes
toRoutesFromFile :: String -> IO [ResourceTree String]
toRoutesFromFile file = do
eRaml <- YI.decodeFileEither file
let raml = case eRaml of
Right v -> v
Left e -> error $ "Invalid raml :" ++ show e
routes = case (routesFromRaml raml) of
Right v -> v
Left e -> error $ "Invalid resource : " ++ e
return $ map ResourceLeaf $ map toYesodResource routes
capitalize :: String -> String
capitalize [] = []
capitalize (h:str) = C.toUpper h:str
toPiece :: T.Text -> Piece String
toPiece str | T.isPrefixOf "/{" str && T.isSuffixOf "}" str= Dynamic $ capitalize $ T.unpack $ T.takeWhile (/= '}') $ T.tail $ T.dropWhile (/= '{') str
| T.isPrefixOf "/" str = Static $ T.unpack $ T.tail str
| otherwise = error "Prefix is not '/'."
fromPiece :: Piece String -> T.Text
fromPiece (Static str) = "/" <> T.pack str
fromPiece (Dynamic str) = "/#" <> T.pack str
toPieces :: [Path] -> [Piece String]
toPieces paths' = map toPiece paths'
fromPieces :: [Piece String] -> [Path]
fromPieces paths' = map fromPiece paths'
toYesodRoutes :: [RouteEx] -> T.Text
toYesodRoutes routes = foldr (\a b -> toRoute a <> "\n" <> b ) "" routes
where
toRoute :: RouteEx -> T.Text
toRoute r = foldr (<>) "" (fromPieces (re_pieces r)) <> " " <>
T.pack (re_handler r) <> " " <>
T.intercalate " " (map (T.pack.me_method) (re_methods r))
parseRamlRoutes :: QuasiQuoter
parseRamlRoutes = QuasiQuoter
{ quoteExp = lift . toRoutesFromString
, quotePat = undefined
, quoteType = undefined
, quoteDec = undefined
}
parseRamlRoutesFile :: FilePath -> Q Exp
parseRamlRoutesFile file = do
qAddDependentFile file
s <- qRunIO $ toRoutesFromFile file
lift s
| junjihashimoto/yesod-raml | yesod-raml/Yesod/Raml/Routes/Internal.hs | mit | 6,025 | 0 | 19 | 1,462 | 2,125 | 1,083 | 1,042 | 145 | 5 |
module Language.UHC.JScript.SafeTypes where
import Language.UHC.JScript.ECMA.String (JSString)
foreign import js "typeof(%1)"
typeof :: a -> JSString
-- | Would like fun dep here
class FromJS a b => FromJSPlus a b where
jsType :: a -> b -> String
check :: a -> b -> Bool
check a b = jsType a b == fromJS (typeof a)
fromJSP :: a -> Maybe b
fromJSP a = let (v::b) = fromJS a
in if check a v then
Just v
else
Nothing | kjgorman/melchior | Language/UHC/JScript/SafeTypes.hs | mit | 501 | 1 | 12 | 167 | 164 | 86 | 78 | -1 | -1 |
module Language.Astview.Languages.Haskell (haskellExts) where
import Prelude hiding (span)
import Language.Astview.Language hiding (parse)
import Language.Astview.DataTree (dataToAstIgnoreByExample)
import Data.Generics (Data,extQ)
import Data.Generics.Zipper(toZipper,down',query)
import Language.Haskell.Exts.Parser
import Language.Haskell.Exts.Annotated.Syntax
import qualified Language.Haskell.Exts.SrcLoc as HsSrcLoc
haskellExts :: Language
haskellExts = Language "Haskell" "Haskell" [".hs"] parsehs
parsehs :: String -> Either Error Ast
parsehs s = case parse s :: ParseResult (Module HsSrcLoc.SrcSpan) of
ParseOk t -> Right $ dataToAstIgnoreByExample getSrcLoc
(undefined::HsSrcLoc.SrcSpan)
t
ParseFailed (HsSrcLoc.SrcLoc _ l c) m -> Left $ ErrLocation (position l c) m
getSrcLoc :: Data t => t -> Maybe SrcSpan
getSrcLoc t = down' (toZipper t) >>= query (def `extQ` atSpan) where
def :: a -> Maybe SrcSpan
def _ = Nothing
atSpan :: HsSrcLoc.SrcSpan -> Maybe SrcSpan
atSpan (HsSrcLoc.SrcSpan _ c1 c2 c3 c4) = Just $ span c1 c2 c3 c4
| jokusi/Astview | src/core/Language/Astview/Languages/Haskell.hs | mit | 1,159 | 0 | 11 | 251 | 358 | 196 | 162 | 23 | 2 |
module Proxygen
(
) where
| Dryvnt/proxygen-hs | src/Proxygen.hs | mit | 35 | 0 | 3 | 14 | 7 | 5 | 2 | 2 | 0 |
{-
- todo bobjflong: move this to Types.hs
-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}
module Web.Stellar.Internal where
import Control.Applicative
import Control.Monad
import Data.Aeson
import Data.Monoid
import Data.Text
data APIMoney = ExtractedText {
innerMoney :: Text
} deriving (Show, Eq)
emptyAPIMoney :: APIMoney
emptyAPIMoney = ExtractedText mempty
instance FromJSON APIMoney where
parseJSON (Object o) = ExtractedText <$> (o .: "value")
parseJSON (String s) = return $ ExtractedText s
parseJSON _ = mzero
data APICurrency = ExtractedCurrency {
innerCurrency :: Text
} deriving (Show, Eq)
defaultAPICurrency :: APICurrency
defaultAPICurrency = ExtractedCurrency mempty
instance FromJSON APICurrency where
parseJSON (Object o) = ExtractedCurrency <$> (o .: "currency")
parseJSON _ = return defaultAPICurrency
| bobjflong/stellar-haskell | src/Web/Stellar/Internal.hs | mit | 957 | 0 | 8 | 199 | 220 | 121 | 99 | 26 | 1 |
module Euler.E16 where
import Data.Char
base :: Integer
base = 2
euler16 :: Int -> Int
euler16 n = sum $ map digitToInt $ show $ base^n
main :: IO ()
main = print $ euler16 1000
| D4r1/project-euler | Euler/E16.hs | mit | 181 | 0 | 9 | 40 | 79 | 42 | 37 | 8 | 1 |
Subsets and Splits