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 OverloadedStrings #-}
module Main where
import Data.Monoid.Colorful
import Data.Foldable
import Text.Printf
ansiColors :: [Color]
ansiColors = [ DefaultColor
, Black
, Red
, Green
, Yellow
, Blue
, Magenta
, Cyan
, White
, DullBlack
, DullRed
, DullGreen
, DullYellow
, DullBlue
, DullMagenta
, DullCyan
, DullWhite
]
ansiColorsExample :: IO ()
ansiColorsExample = do
term <- getTerm
printColoredS term $ Style Underline $ Style Bold "ANSI Example\n"
for_ ansiColors $ \c -> do
printColoredIO term $ Bg c (Value $ printf "%-15s" $ show c)
<> Fg c (Value $ printf "%-15s" $ show c)
<> Bg c (Style Invert $ Value $ printf " %-15s" $ show c)
<> Fg c (Style Invert $ Value $ printf " %-15s" $ show c)
printColoredS term $ Bg c (Value $ printf "%-15s" $ show c)
<> Fg c (Value $ printf "%-15s" $ show c)
<> Bg c (Style Invert $ Value $ printf " %-15s" $ show c)
<> Fg c (Style Invert $ Value $ printf " %-15s" $ show c)
putChar '\n'
colors256Example :: IO ()
colors256Example = do
term <- getTerm
printColoredS term $ Style Underline $ Style Bold "Color256 Example\n"
for_ [0..255] $ \c -> do
printColoredS term $ Bg (Color256 c) (Value $ printf "%02x" c)
<> Fg (Color256 c) (Value $ printf " %02x" c)
<> Bg (Color256 c) (Style Invert $ Value $ printf " %02x" c)
<> Fg (Color256 c) (Style Invert $ Value $ printf " %02x" c)
putChar '\n'
rgbExample :: IO ()
rgbExample = do
term <- getTerm
printColoredS term $ Style Underline $ Style Bold "RGB Example\n"
for_ [0,64..255] $ \r ->
for_ [0,64..255] $ \g ->
for_ [0,64..255] $ \b -> do
let c = RGB r g b
printColoredS term $ Bg c (Value $ printf "%-20s" $ show c)
<> Fg c (Value $ printf " %-20s" $ show c)
<> Bg c (Style Invert $ Value $ printf " %-20s" $ show c)
<> Fg c (Style Invert $ Value $ printf " %-20s" $ show c)
putChar '\n'
specialExample :: IO ()
specialExample = do
term <- getTerm
printColoredS term $ Style Underline $ Style Bold "Special Example\n"
for_ [Bold,Italic,Underline,Invert,Blink] $ \a -> do
printColoredS term $
Style a (Value (printf "%-20s" $ show a) <>
Unstyle a (Value $ printf " %-20s" $ "Not" ++ show a) <>
Value (printf "%-20s" $ show a))
putChar '\n'
stackExample :: IO ()
stackExample = do
term <- getTerm
printColoredS term $ Style Underline (Style Bold "Stack Example\n") <> loop 0
putChar '\n'
where
loop 8 = mempty
loop n =
Bg (Color256 n) $
Value (replicate (fromIntegral n) ' ') <>
loop (n + 1) <>
Value (replicate (fromIntegral n) ' ')
basicExample :: IO ()
basicExample = do
term <- getTerm
printColoredS term $ Style Underline (Style Bold "Basic Example\n")
<> Style Bold "Bold"
<> Style Italic (Bg Red "Italic Red")
<> Style Underline "Underline"
putChar '\n'
reduceExample :: IO ()
reduceExample = do
printColoredS Term8 $ Style Underline $ Style Bold "Reduction Example\n"
for_ [0..255] $ \c -> do
printColoredS Term256 $ Bg (Color256 c) $ Value $ printf "%02x" c
printColoredS Term8 $ Bg (Color256 c) $ Value $ printf "%02x" c
putChar '\n'
for_ [0,64..255] $ \r ->
for_ [0,64..255] $ \g ->
for_ [0,64..255] $ \b -> do
let c = RGB r g b
printColoredS TermRGB $ Bg c $ Value $ printf "%20s" $ show c
printColoredS Term256 $ Bg c $ Value $ printf "%20s" $ show c
printColoredS Term8 $ Bg c $ Value $ printf "%20s" $ show c
putChar '\n'
main :: IO ()
main = do
putStrLn "\n"
ansiColorsExample
colors256Example
rgbExample
specialExample
stackExample
basicExample
reduceExample
putStrLn "\n"
| minad/colorful-monoids | example.hs | mit | 3,982 | 0 | 23 | 1,223 | 1,593 | 748 | 845 | 115 | 2 |
import Control.Monad.Except
import System.IO
import System.Environment
import PISA
import Parser
import ClassAnalyzer
import ScopeAnalyzer
import TypeChecker
import CodeGenerator
import MacroExpander
import Data.List.Split
type Error = String
main :: IO ()
main =
do args <- getArgs
when (null args) (error "Supply input filename.\nUsage: ROOPLPPC input.rplpp output.pal\n")
when (length args > 2) (error "Too many arguments.\nUsage: ROOPLPPC input.rplpp output.pal\n")
handle <- openFile (head args) ReadMode
input <- hGetContents handle
let output = if length args == 2 then last args else head (splitOn "." (head args)) ++ ".pal"
either (hPutStrLn stderr) (writeProgram output) $ compileProgram input
compileProgram :: String -> Either Error PISA.Program
compileProgram s =
runExcept $
parseString s
>>= classAnalysis
>>= scopeAnalysis
>>= typeCheck
>>= generatePISA
>>= expandMacros
| cservenka/ROOPLPPC | src/ROOPLPPC.hs | mit | 967 | 0 | 16 | 199 | 270 | 135 | 135 | 30 | 2 |
{-# LANGUAGE OverlappingInstances, TemplateHaskell, DeriveDataTypeable, StandaloneDeriving #-}
module HeapSort.Data where
import HeapSort.Tree
import HeapSort.Operation
import Autolib.ToDoc
import Autolib.Reader
import Autolib.Size
import Data.Typeable
import Data.Derive.All
$(derives [makeEq,makeOrd] [''Operation,''Richtung])
data Feedback = Verbose
| OnFailure
| None
deriving ( Eq, Ord, Typeable)
data QuizConfig = QuizConfig
{ quizFeedback :: Feedback -- ^ Type of feedback
, chunks :: Int -- ^ Number of chunks during numbers sequence generation (use 1 to deactivate)
, numbers :: Int -- ^ Length of the number sequence
, min :: Int -- ^ Lower bound for random number generation
, max :: Int -- ^ Upper bound for random number generation
}
deriving ( Eq, Ord, Typeable)
data Config = Config
{ feedback :: Feedback
, unsortedNumbers :: [Int]
}
deriving ( Eq, Ord, Typeable)
$(derives [makeReader] [''Operation])
data Solution = Solution [Operation]
deriving ( Eq, Ord, Typeable, Read, Show )
instance ToDoc Operation where
toDoc = text . show
$(derives [makeReader, makeToDoc] [''Richtung,''Feedback,''QuizConfig,''Config,''Solution])
instance Size Config where size _ = 0
instance Size Solution where size _ = 0
| Erdwolf/autotool-bonn | src/HeapSort/Data.hs | gpl-2.0 | 1,341 | 0 | 9 | 296 | 344 | 197 | 147 | 33 | 0 |
{- |
Module : $Header$
Description : create legal THF mixfix identifier
Copyright : (c) A. Tsogias, DFKI Bremen 2011
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Alexis.Tsogias@dfki.de
Stability : provisional
Portability : portable
translations for the buildins of HasCasl
-}
module THF.HasCASL2THF0Buildins where
import Common.AS_Annotation
import Common.DocUtils
import Common.Result
import Common.Id
import HasCASL.Builtin
import THF.As
import THF.Cons
import THF.Sign
import THF.ParseTHF0
import THF.Translate
import THF.PrintTHF ()
import Text.ParserCombinators.Parsec
import Data.Maybe
import qualified Data.Set as Set
import qualified Data.Map as Map
--------------------------------------------------------------------------------
-- Assumps
--------------------------------------------------------------------------------
preDefHCAssumps :: Set.Set Id -> ConstMap
preDefHCAssumps ids =
let asl = [ (botId, botci)
, (defId, defci)
, (notId, o2ci)
, (negId, o2ci)
{- , (whenElse, "hcc" ++ show whenElse) -}
, (trueId, o1ci)
, (falseId, o1ci)
, (eqId, a2o1ci)
, (exEq, a2o1ci)
, (resId, resci)
, (andId, o3ci)
, (orId, o3ci)
, (eqvId, o3ci)
, (implId, o3ci)
, (infixIf, o3ci) ]
in Map.fromList $ map
(\ (i, tf) -> let c = (fromJust . maybeResult . transAssumpId) i
in (c , tf c))
(filter (\ (i, _) -> Set.member i ids) asl)
o1ci :: Constant -> ConstInfo
o1ci c = ConstInfo
{ constId = c
, constName = mkConstsName c
, constType = OType
, constDef = Nothing
, constAnno = Null }
o2ci :: Constant -> ConstInfo
o2ci c = ConstInfo
{ constId = c
, constName = mkConstsName c
, constType = MapType OType OType
, constDef = Nothing
, constAnno = Null }
o3ci :: Constant -> ConstInfo
o3ci c = ConstInfo
{ constId = c
, constName = mkConstsName c
, constType = MapType OType (MapType OType OType)
, constDef = Nothing
, constAnno = Null }
a2o1ci :: Constant -> ConstInfo
a2o1ci c = ConstInfo
{ constId = c
, constName = mkConstsName c
, constType = MapType (VType "A") (MapType (VType "A") OType)
, constDef = Nothing
, constAnno = Null }
resci :: Constant -> ConstInfo
resci c = ConstInfo
{ constId = c
, constName = mkConstsName c
, constType = MapType (VType "A") (MapType (VType "B") (VType "A"))
, constDef = Nothing
, constAnno = Null }
botci :: Constant -> ConstInfo
botci c = ConstInfo
{ constId = c
, constName = mkConstsName c
, constType = OType
, constDef = Nothing
, constAnno = Null }
defci :: Constant -> ConstInfo
defci c = ConstInfo
{ constId = c
, constName = mkConstsName c
, constType = MapType (VType "A") OType
, constDef = Nothing
, constAnno = Null }
--------------------------------------------------------------------------------
-- Axioms
--------------------------------------------------------------------------------
preDefAxioms :: Set.Set Id -> [Named SentenceTHF]
preDefAxioms ids =
let axl = [ (notId, notFS)
, (negId, notFS)
, (trueId, trueFS)
, (falseId, falseFS)
, (andId, andFS)
, (orId, orFS)
, (eqvId, eqvFS)
, (implId, implFS)
, (infixIf, ifFS)
, (eqId, eqFS)
, (exEq, eqFS)
, (resId, resFS)
, (botId, botFS)
, (defId, defFS)
{- , (whenElse, "hcc" ++ show whenElse) -} ]
in map (\ (i, fs) -> mkNSD
(fromJust $ maybeResult $ transAssumpId i) fs)
(filter (\ (i, _) -> Set.member i ids) axl)
mkNSD :: Constant -> (Constant -> String) -> Named SentenceTHF
mkNSD c f =
let s = Sentence
{ senRole = Definition
, senFormula = genTHFFormula c f
, senAnno = Null }
in SenAttr
{ senAttr = (show . pretty . mkDefName) c
, isAxiom = True
, isDef = True
, wasTheorem = False
, simpAnno = Nothing
, attrOrigin = Nothing
, sentence = s }
genTHFFormula :: Constant -> (Constant -> String) -> THFFormula
genTHFFormula c f = case parse parseTHF0 "" (f c) of
Left _ -> error ("Fatal error while generating the predefinied Sentence"
++ " for: " ++ show (pretty c))
Right x -> thfFormulaAF $ head x
--------------------------------------------------------------------------------
-- formulas as Strings
--------------------------------------------------------------------------------
notFS :: Constant -> String
notFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = (^ [A : $o] : ~(A))")
falseFS :: Constant -> String
falseFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = $false")
trueFS :: Constant -> String
trueFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = $true")
andFS :: Constant -> String
andFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = (^ [X : $o, Y : $o] : (X & Y))")
orFS :: Constant -> String
orFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = (^ [X : $o, Y : $o] : (X | Y))")
eqvFS :: Constant -> String
eqvFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = (^ [X : $o, Y : $o] : (X <=> Y))")
implFS :: Constant -> String
implFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = (^ [X : $o, Y : $o] : (X => Y))")
ifFS :: Constant -> String
ifFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = (^ [X : $o, Y : $o] : (Y => X))")
eqFS :: Constant -> String
eqFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = (^ [X : A, Y : A] : (X = Y))")
resFS :: Constant -> String
resFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = (^ [X : A, Y : B] : X)")
botFS :: Constant -> String
botFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = $false")
defFS :: Constant -> String
defFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = (^ [X : A] : $true)")
defnS :: String
defnS = ", definition, "
encTHF :: String -> String
encTHF s = "thf(" ++ s ++ ")."
| nevrenato/Hets_Fork | THF/HasCASL2THF0Buildins.hs | gpl-2.0 | 7,250 | 0 | 18 | 2,349 | 2,188 | 1,207 | 981 | 187 | 2 |
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable #-}
module Modular.Config where
import Network.XmlRpc.Internals
import Autolib.ToDoc
import Data.Typeable
data Config =
Config { contents :: String
}
deriving Typeable
instance XmlRpcType ( Config ) where
toValue d = toValue [("contents",toValue (contents d))
]
fromValue v = do
t <- fromValue v
c <- getField "contents" t
return $ Config { contents = c }
getType _ = TStruct
$(derives [makeToDoc] [''Config])
-- local variables:
-- mode: haskell
-- end
| Erdwolf/autotool-bonn | src/Modular/Config.hs | gpl-2.0 | 554 | 5 | 11 | 126 | 163 | 87 | 76 | 16 | 0 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
module Diagram where
import GHC.TypeLits
--
import Control.Applicative
import Data.Hashable
import qualified Data.HashSet as H
import Data.List (find)
import qualified Data.Map as M
import Data.Maybe (mapMaybe)
import Data.Traversable (sequenceA)
--
import Graph
import McKay
-- | direction of line (in,out,undirected)
data Direction = I | O | U deriving (Show,Eq,Ord)
instance Hashable Direction where
hashWithSalt salt dir = case dir of
I -> hashWithSalt salt (1 :: Int)
O -> hashWithSalt salt (2 :: Int)
U -> hashWithSalt salt (3 :: Int)
fst3 :: (a,b,c) -> a
fst3 (a,_,_) = a
snd3 :: (a,b,c) -> b
snd3 (_,b,_) = b
trd3 :: (a,b,c) -> c
trd3 (_,_,c) = c
data VertexKind = VK { vertexKindId :: Int
, vertexKindName :: String
, vertexKindEdgeList :: [ (Int, Direction, Int) ] -- (edge id, direction, multiplicity)
} deriving (Eq, Ord)
instance Show VertexKind where
show = vertexKindName
vertexKindDeg :: VertexKind -> Int
vertexKindDeg = sum . map trd3 . vertexKindEdgeList
instance Hashable VertexKind where
hashWithSalt salt (VK i n d) = hashWithSalt salt (i,n,d)
data EdgeKind = EK { edgeKindId :: Int
, edgeKindName :: String
, edgeKindIsDirected :: Bool
}
type VertexKindSet = H.HashSet VertexKind
type EdgeKindSet = H.HashSet EdgeKind
-- |
isCompatibleWith :: (KnownNat n) => VertexKindSet -> AssocMap n -> Bool
isCompatibleWith vkinds asc = let d1 = H.map vertexKindDeg vkinds
d2 = (H.fromList . map fst . globalVertexDegree) asc
in H.null (H.difference d2 d1)
-- |
vertexCandidates :: (KnownNat n) => VertexKindSet -> AssocMap n -> [ (VertexKind, [Vertex n]) ]
vertexCandidates vkinds asc = (mapMaybe f . H.toList) vkinds
where dlst = globalVertexDegree asc
f x = let d = vertexKindDeg x
mx = find ((== d) . fst) dlst
in (\y->(x,snd y)) <$> mx
-- |
transpose :: (Eq a, Eq b, Ord a, Ord b) => [ (a, [b]) ] -> [ (b, [a]) ]
transpose olst = let lst1 = [ (k,v) | (k,vs) <- olst, v <- vs ]
f (k,v) = M.insertWith (.) v (k:)
map2 = foldr f M.empty lst1
in (M.toAscList . fmap ((flip ($) []) )) map2
generateVertexMapping :: (KnownNat n) => VertexKindSet -> AssocMap n -> [ [ (Vertex n, VertexKind) ] ]
generateVertexMapping vkinds asc = sequenceA vks
where vc = transpose (vertexCandidates vkinds asc)
f (v,ks) = [(v,k)| k <- ks ]
vks = map f vc
vertexMapToString :: [ (Vertex n, VertexKind) ] -> M.Map (Vertex n) String
vertexMapToString = fmap vertexKindName . M.fromList
| wavewave/qft | old/lib/Diagram.hs | gpl-3.0 | 2,983 | 0 | 14 | 956 | 1,039 | 579 | 460 | 62 | 1 |
module NESDL (sdlInit, draw, getKeys, quitHandler) where
import Graphics.UI.SDL as SDL
import Control.Monad (forM_, forever)
import Data.Word
import System.IO.Unsafe (unsafeInterleaveIO)
import Types hiding (Pixel)
import Prelude hiding (Left, Right)
-- Initialize the system.
sdlInit :: IO ()
sdlInit = do
SDL.init [InitVideo,InitEventthread]
enableKeyRepeat 500 20
setVideoMode 256 240 24 [DoubleBuf]
return ()
-- listens for quit messages
quitHandler :: IO ()
quitHandler = do
e <- waitEvent
case e of
Quit -> quit
_ -> quitHandler
-- Called once every frame
draw :: [Word32] -> IO ()
draw ps = draw' $ zipWith (\p (x,y) -> (Pixel p,x,y)) ps
-- [ (x,y) | y <- [0,2..478], x <- [0,2..510] ]
[ (x,y) | y <- [0..239], x <- [0..255] ]
where
draw' :: [(Pixel, Int, Int)] -> IO ()
draw' pxs = do
sur <- getVideoSurface
forM_ pxs $ \(p,x,y) -> fillRect sur (Just $ Rect x y 1 1) p
SDL.flip sur
-- Lazy list of inputs
getKeys :: IO [Maybe Input]
getKeys = unsafeInterleaveIO $ do
ev <- pollEvent
case ev of
KeyDown key -> do
let result = checkKey KeyPress key
ks <- getKeys
return (result : ks)
KeyUp key -> do
let result = checkKey KeyRelease key
ks <- getKeys
return (result : ks)
_ -> do
ks <- getKeys
return (Nothing : ks)
-- Translates a keypress to a maybe input
checkKey t (Keysym k _ _) = case k of
SDLK_z -> Just $ Input t P1 A
SDLK_x -> Just $ Input t P1 B
SDLK_c -> Just $ Input t P1 Start
SDLK_v -> Just $ Input t P1 Select
SDLK_LEFT -> Just $ Input t P1 Left
SDLK_UP -> Just $ Input t P1 Up
SDLK_DOWN -> Just $ Input t P1 Down
SDLK_RIGHT -> Just $ Input t P1 Right
SDLK_q -> Just $ Input t P2 A
SDLK_e -> Just $ Input t P2 B
SDLK_1 -> Just $ Input t P2 Start
SDLK_2 -> Just $ Input t P2 Select
SDLK_a -> Just $ Input t P2 Left
SDLK_w -> Just $ Input t P2 Up
SDLK_s -> Just $ Input t P2 Down
SDLK_d -> Just $ Input t P2 Right
_ -> Nothing
| tobsan/yane | NESDL.hs | gpl-3.0 | 2,244 | 0 | 16 | 765 | 831 | 420 | 411 | 60 | 17 |
module Main (main) where
import Cli (main)
| ciderpunx/rsstwit | app/Main.hs | gpl-3.0 | 44 | 0 | 5 | 8 | 17 | 11 | 6 | 2 | 0 |
{-# LANGUAGE FlexibleInstances, UndecidableInstances,BangPatterns#-}
module HPseudoBool
(Var(..),
Sum(..),
Line(..),
emptySum,
(|==|),
(|>=|),
(|<=|),
(|*|),
(|<|),
(|>|),
getEncoding,
newVar,
newVars,
sumC,
Constraint(..),
PBencM,
PBencState(..),
add,
comment,
addAll,
minimize
) where
import Control.Monad.State.Strict
import Control.Monad
import qualified Data.Map as M
import Data.Map(Map)
import Data.List
import qualified Data.Set as S
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Lazy.Char8 as C
import Data.ByteString.Builder
import Data.Monoid hiding (Sum)
data Var = X Int deriving (Ord,Eq)
instance Show Var where
show (X a) = "x" ++ show a
instance Show Line where
show (Cons c) = show c
show (Comment str) = "* "++ (intercalate "* \n" . lines $ str)
data Sum = S {
vars :: Map Var Int,
consts :: Int} deriving Eq
emptySum = S (M.empty) 0
data Line = Cons Constraint | Comment String
infixl 3 |*|
a |*| v = S (M.singleton v a) 0
instance Show Sum where
show (S m i) | i < 0 = (unwords . map printSum . M.assocs $ m) ++ " " ++ show i
| i == 0 = (unwords . map printSum . M.assocs $ m)
| otherwise = (unwords . map printSum . M.assocs $ m) ++ " +" ++ show i
where
printSum (a,b) | b == 0 = ""
| b > 0 = "+" ++ show b ++ " " ++ show a
| otherwise = show b ++ " " ++ show a
instance Num Sum where
a - b = a + (negate b)
(+) = addS
negate (S xs i) = (S (M.map negate xs) (negate i))
abs = undefined
signum = undefined
(*) = undefined
fromInteger i = (S M.empty (fromInteger i))
addS (S xs i) (S ys j) =
foldl (\ m (x,y) -> m `g` ( x,y)) (S ys (i+j)) (M.assocs xs)
where
g :: Sum -> (Var,Int) -> Sum
g (S m i) (var,c)
| var `M.member` m = S (M.adjust (+c) var m) i
| otherwise = S (M.insert var c m) i
sumC :: [Sum] -> Sum
sumC = foldr (+) emptySum
data Constraint = Geq Sum Int | E Sum Int
getSum :: Constraint -> Sum
getSum (Geq s _) = s
getSum (E s _) = s
instance Show Constraint where
show (Geq (S m i) t) | i /= 0 = error "Can't print Unbalanced Constraint"
| otherwise = show (S m i) ++ " >= " ++ show t ++ ";"
show (E (S m i) t) | i /= 0 = error "Can't print Unbalanced Constraint"
| otherwise = show (S m i) ++ " = " ++ show t ++ ";"
(|>=|) :: Sum -> Sum -> Constraint
infix 1 |>=|
(S m c) |>=| (S m' c') = Geq ((S m 0) - (S m' 0)) (c' - c)
(|==|) :: Sum -> Sum -> Constraint
infix 1 |==|
(S m c) |==| (S m' c') = E ((S m 0) - S m' 0) (c' - c)
(|<=|) :: Sum -> Sum -> Constraint
infix 1 |<=|
a |<=| b = (b - a) |>=| 0
(|>|) :: Sum -> Sum -> Constraint
infix 1 |>|
(S m c) |>| (S m' c') = Geq (S m 0 - S m' 0) (c'- c + 1)
(|<|) :: Sum -> Sum -> Constraint
infix 1 |<|
(S m c) |<| (S m' c') = Geq ((S m 0) - (S m' 0)) (c' - c -1)
data PBencState = PBS {
nextFresh :: {-# UNPACK #-} !Int,
numConstr :: {-# UNPACK #-} !Int,
constraints :: Builder,
objective :: Sum
}
type PBencM = State PBencState
newVar :: PBencM Sum
newVar = do
i <- gets nextFresh
modify (\p -> p{nextFresh = i + 1})
return (S (M.singleton (X i) 1) 0)
newVars :: Int -> PBencM [Sum]
newVars i = do
n <- gets nextFresh
modify (\p -> p{nextFresh = n + i})
return [(S (M.singleton (X j) 1) 0) | j <- [n..n+i-1]]
add :: Constraint -> PBencM ()
add c = modify (\s -> s{numConstr = numConstr s + 1,
constraints = constraints s <> constrToBldr c})
comment :: String -> PBencM ()
comment str = modify (\s -> s{constraints = constraints s <> commentToBldr str})
addAll xs = mapM_ add xs
minimize :: Sum -> PBencM ()
minimize c = modify (\s -> s{objective = c})
getEncoding :: PBencM a -> L.ByteString
getEncoding p = toLazyByteString (pr (execState p (PBS 1 0 mempty emptySum)))
where
pr (PBS i j cs s) = varBldr <> conBldr <> charUtf8 '\n' <> minBldr <> cs
where
varBldr = stringUtf8 "* #variable= " <> intDec (i-1)
conBldr = stringUtf8 " #constraint= " <> intDec j
minBldr = if s /= S M.empty 0 then
stringUtf8 "min: " <>
sumToBldr s <> stringUtf8 ";\n" else mempty
f (Cons _ ) = 1
f _ = 0
sumToBldr (S m i)
| i < 0 = mconcat
[mconcat . map printSum . M.assocs $ m,
intDec i]
| i == 0 = mconcat . map printSum . M.assocs $ m
| otherwise = mconcat
[mconcat . map printSum . M.assocs $ m,
charUtf8 '+',
intDec i]
where
printSum (X a,b)
| b == 0 = mempty
| b > 0 = charUtf8 '+' <> intDec b <> stringUtf8 " x" <> intDec a <> charUtf8 ' '
| otherwise = intDec b <> stringUtf8 " x" <> intDec a <> charUtf8 ' '
commentToBldr str = stringUtf8 "* " <> stringUtf8 str <> charUtf8 '\n'
lineToBldr (Comment str) = commentToBldr str
lineToBldr (Cons c) = constrToBldr c
constrToBldr (Geq (S m i) t) =
sumToBldr (S m i) <> stringUtf8 ">= " <> intDec t <> stringUtf8 ";\n"
constrToBldr (E (S m i) t) =
sumToBldr (S m i) <> stringUtf8 "= " <> intDec t <> stringUtf8 ";\n"
test = do
c <- newVar
add ( c |<=| 1)
[a,b] <- replicateM 2 newVar
add (c |>=| a + b)
minimize(a - b)
| EJahren/HPseudoBool | src/HPseudoBool.hs | gpl-3.0 | 5,282 | 0 | 14 | 1,519 | 2,585 | 1,332 | 1,253 | 153 | 3 |
-- Simple Fay program for drawing a barnsley fern
-- values are hardcoded because I'm lazy and still
-- trying to work out how to use Fay
--
-- Robert 'Probie' Offner
import Prelude
import FFI
data IFS = IFS [(Probability, Transition)]
deriving Show
data Transition = Affine Double Double Double Double Double Double
-- | Möbius (Complex Double) (Complex Double) (Complex Double) (Complex Double)
-- Fay doesn't support complex numbers
deriving Show
type Probability = Double
buildIFS :: [(Probability, Transition)] -> IFS
buildIFS trans = IFS $ (\(x,y) -> zip (cdf x) y) $ unzip trans
where cdf [] = []
cdf (x:xs) = x : map (+ x) (cdf xs)
simulateIFS :: IFS -> (Double,Double) -> [Probability] -> [(Double,Double)]
simulateIFS _ _ [] = []
simulateIFS ifs xn (p:ps) = let xn' = applyTransition (chooseTransition p ifs) xn in
xn' : simulateIFS ifs xn' ps
sierpinksi = buildIFS $
[ (1/3, Affine 0.5 0 0 0.5 0 0)
, (1/3, Affine 0.5 0 0 0.5 0.25 ((sqrt 3) / 4))
, (1/3, Affine 0.5 0 0 0.5 0.5 0)
]
chooseTransition :: Probability -> IFS -> Transition
chooseTransition p (IFS x) = chooseTransition' p x
chooseTransition' _ [(_,x)] = x
chooseTransition' p ((p',x):xs) = if p <= p' then x else chooseTransition' p xs
applyTransition :: Transition -> (Double,Double) -> (Double,Double)
applyTransition (Affine a b c d e f) (x,y) = (a*x + b*y + e, c*x + d*y + f)
randDouble :: Fay Double
randDouble = ffi "Math.random()"
main = do
x <- newRef 0
y <- newRef 0
setFillStyle "#FF00FF"
setInterval 400 (drawStuff 1000 x y )
drawStuff :: Int -> Ref Double -> Ref Double -> Fay ()
drawStuff 0 x y = return ()
drawStuff n x y = do
p <- randDouble
xval <- readRef x
yval <- readRef y
let (x', y') = applyTransition (chooseTransition p sierpinksi) (xval, yval)
drawDot x' y'
writeRef x x'
writeRef y y'
drawStuff (n-1) x y
drawDot :: Double -> Double -> Fay ()
drawDot = ffi "document.getElementById(\"fractal\").getContext(\"2d\").fillRect((%1)*600+100, 540 - %2*600, 1, 1)"
setFillStyle :: String -> Fay ()
setFillStyle = ffi "document.getElementById(\"fractal\").getContext(\"2d\").fillStyle=%1"
setInterval :: Int -> Fay () -> Fay ()
setInterval = ffi "setInterval(%2,%1)"
alert :: String -> Fay ()
alert = ffi "window.alert(%1)"
-- Refs
-- This will be provided in the fay package by default.
data Canvas
data Context
data Ref a
instance Show (Ref a)
newRef :: a -> Fay (Ref a)
newRef = ffi "new Fay$$Ref(%1)"
writeRef :: Ref a -> a -> Fay ()
writeRef = ffi "Fay$$writeRef(%1,%2)"
readRef :: Ref a -> Fay a
readRef = ffi "Fay$$readRef(%1)"
| LudvikGalois/Fay-IFS | Sierpinski.hs | gpl-3.0 | 2,729 | 0 | 12 | 641 | 995 | 515 | 480 | -1 | -1 |
{-# LANGUAGE TemplateHaskell #-}
-- Copyright (C) 2010-2012 John Millikin <john@john-millikin.com>
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- any later version.
--
-- This program 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 General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
module DBusTests.InterfaceName (test_InterfaceName) where
import Test.Chell
import Test.Chell.QuickCheck
import Test.QuickCheck hiding (property)
import Data.List (intercalate)
import DBus
import DBusTests.Util
test_InterfaceName :: Suite
test_InterfaceName = suite "InterfaceName"
[ test_Parse
, test_ParseInvalid
, test_IsVariant
]
test_Parse :: Test
test_Parse = property "parse" prop where
prop = forAll gen_InterfaceName check
check x = case parseInterfaceName x of
Nothing -> False
Just parsed -> formatInterfaceName parsed == x
test_ParseInvalid :: Test
test_ParseInvalid = assertions "parse-invalid" $ do
-- empty
$expect (nothing (parseInterfaceName ""))
-- one element
$expect (nothing (parseInterfaceName "foo"))
-- element starting with a digit
$expect (nothing (parseInterfaceName "foo.0bar"))
-- trailing characters
$expect (nothing (parseInterfaceName "foo.bar!"))
-- at most 255 characters
$expect (just (parseInterfaceName ("f." ++ replicate 252 'y')))
$expect (just (parseInterfaceName ("f." ++ replicate 253 'y')))
$expect (nothing (parseInterfaceName ("f." ++ replicate 254 'y')))
test_IsVariant :: Test
test_IsVariant = assertions "IsVariant" $ do
assertVariant TypeString (interfaceName_ "foo.bar")
gen_InterfaceName :: Gen String
gen_InterfaceName = trim chunks where
alpha = ['a'..'z'] ++ ['A'..'Z'] ++ "_"
alphanum = alpha ++ ['0'..'9']
trim gen = do
x <- gen
if length x > 255
then return (dropWhileEnd (== '.') (take 255 x))
else return x
chunks = do
x <- chunk
xs <- listOf1 chunk
return (intercalate "." (x:xs))
chunk = do
x <- elements alpha
xs <- listOf (elements alphanum)
return (x:xs)
instance Arbitrary InterfaceName where
arbitrary = fmap interfaceName_ gen_InterfaceName
| jotrk/haskell-dbus | tests/DBusTests/InterfaceName.hs | gpl-3.0 | 2,574 | 14 | 15 | 483 | 609 | 311 | 298 | 50 | 2 |
{-# 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.AppEngine.Apps.Services.Versions.Instances.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Stops a running instance.
--
-- /See:/ <https://cloud.google.com/appengine/docs/admin-api/ Google App Engine Admin API Reference> for @appengine.apps.services.versions.instances.delete@.
module Network.Google.Resource.AppEngine.Apps.Services.Versions.Instances.Delete
(
-- * REST Resource
AppsServicesVersionsInstancesDeleteResource
-- * Creating a Request
, appsServicesVersionsInstancesDelete
, AppsServicesVersionsInstancesDelete
-- * Request Lenses
, aXgafv
, aInstancesId
, aUploadProtocol
, aPp
, aAccessToken
, aUploadType
, aVersionsId
, aBearerToken
, aAppsId
, aServicesId
, aCallback
) where
import Network.Google.AppEngine.Types
import Network.Google.Prelude
-- | A resource alias for @appengine.apps.services.versions.instances.delete@ method which the
-- 'AppsServicesVersionsInstancesDelete' request conforms to.
type AppsServicesVersionsInstancesDeleteResource =
"v1" :>
"apps" :>
Capture "appsId" Text :>
"services" :>
Capture "servicesId" Text :>
"versions" :>
Capture "versionsId" Text :>
"instances" :>
Capture "instancesId" Text :>
QueryParam "$.xgafv" Text :>
QueryParam "upload_protocol" Text :>
QueryParam "pp" Bool :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "bearer_token" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Delete '[JSON] Operation
-- | Stops a running instance.
--
-- /See:/ 'appsServicesVersionsInstancesDelete' smart constructor.
data AppsServicesVersionsInstancesDelete = AppsServicesVersionsInstancesDelete'
{ _aXgafv :: !(Maybe Text)
, _aInstancesId :: !Text
, _aUploadProtocol :: !(Maybe Text)
, _aPp :: !Bool
, _aAccessToken :: !(Maybe Text)
, _aUploadType :: !(Maybe Text)
, _aVersionsId :: !Text
, _aBearerToken :: !(Maybe Text)
, _aAppsId :: !Text
, _aServicesId :: !Text
, _aCallback :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'AppsServicesVersionsInstancesDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'aXgafv'
--
-- * 'aInstancesId'
--
-- * 'aUploadProtocol'
--
-- * 'aPp'
--
-- * 'aAccessToken'
--
-- * 'aUploadType'
--
-- * 'aVersionsId'
--
-- * 'aBearerToken'
--
-- * 'aAppsId'
--
-- * 'aServicesId'
--
-- * 'aCallback'
appsServicesVersionsInstancesDelete
:: Text -- ^ 'aInstancesId'
-> Text -- ^ 'aVersionsId'
-> Text -- ^ 'aAppsId'
-> Text -- ^ 'aServicesId'
-> AppsServicesVersionsInstancesDelete
appsServicesVersionsInstancesDelete pAInstancesId_ pAVersionsId_ pAAppsId_ pAServicesId_ =
AppsServicesVersionsInstancesDelete'
{ _aXgafv = Nothing
, _aInstancesId = pAInstancesId_
, _aUploadProtocol = Nothing
, _aPp = True
, _aAccessToken = Nothing
, _aUploadType = Nothing
, _aVersionsId = pAVersionsId_
, _aBearerToken = Nothing
, _aAppsId = pAAppsId_
, _aServicesId = pAServicesId_
, _aCallback = Nothing
}
-- | V1 error format.
aXgafv :: Lens' AppsServicesVersionsInstancesDelete (Maybe Text)
aXgafv = lens _aXgafv (\ s a -> s{_aXgafv = a})
-- | Part of \`name\`. See documentation of \`appsId\`.
aInstancesId :: Lens' AppsServicesVersionsInstancesDelete Text
aInstancesId
= lens _aInstancesId (\ s a -> s{_aInstancesId = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
aUploadProtocol :: Lens' AppsServicesVersionsInstancesDelete (Maybe Text)
aUploadProtocol
= lens _aUploadProtocol
(\ s a -> s{_aUploadProtocol = a})
-- | Pretty-print response.
aPp :: Lens' AppsServicesVersionsInstancesDelete Bool
aPp = lens _aPp (\ s a -> s{_aPp = a})
-- | OAuth access token.
aAccessToken :: Lens' AppsServicesVersionsInstancesDelete (Maybe Text)
aAccessToken
= lens _aAccessToken (\ s a -> s{_aAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
aUploadType :: Lens' AppsServicesVersionsInstancesDelete (Maybe Text)
aUploadType
= lens _aUploadType (\ s a -> s{_aUploadType = a})
-- | Part of \`name\`. See documentation of \`appsId\`.
aVersionsId :: Lens' AppsServicesVersionsInstancesDelete Text
aVersionsId
= lens _aVersionsId (\ s a -> s{_aVersionsId = a})
-- | OAuth bearer token.
aBearerToken :: Lens' AppsServicesVersionsInstancesDelete (Maybe Text)
aBearerToken
= lens _aBearerToken (\ s a -> s{_aBearerToken = a})
-- | Part of \`name\`. Name of the resource requested. Example:
-- apps\/myapp\/services\/default\/versions\/v1\/instances\/instance-1.
aAppsId :: Lens' AppsServicesVersionsInstancesDelete Text
aAppsId = lens _aAppsId (\ s a -> s{_aAppsId = a})
-- | Part of \`name\`. See documentation of \`appsId\`.
aServicesId :: Lens' AppsServicesVersionsInstancesDelete Text
aServicesId
= lens _aServicesId (\ s a -> s{_aServicesId = a})
-- | JSONP
aCallback :: Lens' AppsServicesVersionsInstancesDelete (Maybe Text)
aCallback
= lens _aCallback (\ s a -> s{_aCallback = a})
instance GoogleRequest
AppsServicesVersionsInstancesDelete where
type Rs AppsServicesVersionsInstancesDelete =
Operation
type Scopes AppsServicesVersionsInstancesDelete =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient
AppsServicesVersionsInstancesDelete'{..}
= go _aAppsId _aServicesId _aVersionsId _aInstancesId
_aXgafv
_aUploadProtocol
(Just _aPp)
_aAccessToken
_aUploadType
_aBearerToken
_aCallback
(Just AltJSON)
appEngineService
where go
= buildClient
(Proxy ::
Proxy AppsServicesVersionsInstancesDeleteResource)
mempty
| rueshyna/gogol | gogol-appengine/gen/Network/Google/Resource/AppEngine/Apps/Services/Versions/Instances/Delete.hs | mpl-2.0 | 7,135 | 0 | 24 | 1,821 | 1,093 | 633 | 460 | 157 | 1 |
{-# 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.Games.Applications.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves the metadata of the application with the given ID. If the
-- requested application is not available for the specified
-- \`platformType\`, the returned response will not include any instance
-- data.
--
-- /See:/ <https://developers.google.com/games/ Google Play Game Services Reference> for @games.applications.get@.
module Network.Google.Resource.Games.Applications.Get
(
-- * REST Resource
ApplicationsGetResource
-- * Creating a Request
, applicationsGet
, ApplicationsGet
-- * Request Lenses
, agXgafv
, agUploadProtocol
, agAccessToken
, agUploadType
, agApplicationId
, agPlatformType
, agLanguage
, agCallback
) where
import Network.Google.Games.Types
import Network.Google.Prelude
-- | A resource alias for @games.applications.get@ method which the
-- 'ApplicationsGet' request conforms to.
type ApplicationsGetResource =
"games" :>
"v1" :>
"applications" :>
Capture "applicationId" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "platformType" ApplicationsGetPlatformType
:>
QueryParam "language" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] Application
-- | Retrieves the metadata of the application with the given ID. If the
-- requested application is not available for the specified
-- \`platformType\`, the returned response will not include any instance
-- data.
--
-- /See:/ 'applicationsGet' smart constructor.
data ApplicationsGet =
ApplicationsGet'
{ _agXgafv :: !(Maybe Xgafv)
, _agUploadProtocol :: !(Maybe Text)
, _agAccessToken :: !(Maybe Text)
, _agUploadType :: !(Maybe Text)
, _agApplicationId :: !Text
, _agPlatformType :: !(Maybe ApplicationsGetPlatformType)
, _agLanguage :: !(Maybe Text)
, _agCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ApplicationsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'agXgafv'
--
-- * 'agUploadProtocol'
--
-- * 'agAccessToken'
--
-- * 'agUploadType'
--
-- * 'agApplicationId'
--
-- * 'agPlatformType'
--
-- * 'agLanguage'
--
-- * 'agCallback'
applicationsGet
:: Text -- ^ 'agApplicationId'
-> ApplicationsGet
applicationsGet pAgApplicationId_ =
ApplicationsGet'
{ _agXgafv = Nothing
, _agUploadProtocol = Nothing
, _agAccessToken = Nothing
, _agUploadType = Nothing
, _agApplicationId = pAgApplicationId_
, _agPlatformType = Nothing
, _agLanguage = Nothing
, _agCallback = Nothing
}
-- | V1 error format.
agXgafv :: Lens' ApplicationsGet (Maybe Xgafv)
agXgafv = lens _agXgafv (\ s a -> s{_agXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
agUploadProtocol :: Lens' ApplicationsGet (Maybe Text)
agUploadProtocol
= lens _agUploadProtocol
(\ s a -> s{_agUploadProtocol = a})
-- | OAuth access token.
agAccessToken :: Lens' ApplicationsGet (Maybe Text)
agAccessToken
= lens _agAccessToken
(\ s a -> s{_agAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
agUploadType :: Lens' ApplicationsGet (Maybe Text)
agUploadType
= lens _agUploadType (\ s a -> s{_agUploadType = a})
-- | The application ID from the Google Play developer console.
agApplicationId :: Lens' ApplicationsGet Text
agApplicationId
= lens _agApplicationId
(\ s a -> s{_agApplicationId = a})
-- | Restrict application details returned to the specific platform.
agPlatformType :: Lens' ApplicationsGet (Maybe ApplicationsGetPlatformType)
agPlatformType
= lens _agPlatformType
(\ s a -> s{_agPlatformType = a})
-- | The preferred language to use for strings returned by this method.
agLanguage :: Lens' ApplicationsGet (Maybe Text)
agLanguage
= lens _agLanguage (\ s a -> s{_agLanguage = a})
-- | JSONP
agCallback :: Lens' ApplicationsGet (Maybe Text)
agCallback
= lens _agCallback (\ s a -> s{_agCallback = a})
instance GoogleRequest ApplicationsGet where
type Rs ApplicationsGet = Application
type Scopes ApplicationsGet =
'["https://www.googleapis.com/auth/games"]
requestClient ApplicationsGet'{..}
= go _agApplicationId _agXgafv _agUploadProtocol
_agAccessToken
_agUploadType
_agPlatformType
_agLanguage
_agCallback
(Just AltJSON)
gamesService
where go
= buildClient
(Proxy :: Proxy ApplicationsGetResource)
mempty
| brendanhay/gogol | gogol-games/gen/Network/Google/Resource/Games/Applications/Get.hs | mpl-2.0 | 5,707 | 0 | 19 | 1,368 | 868 | 505 | 363 | 125 | 1 |
{-# 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.IAM.Organizations.Roles.Patch
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Updates the definition of a custom Role.
--
-- /See:/ <https://cloud.google.com/iam/ Identity and Access Management (IAM) API Reference> for @iam.organizations.roles.patch@.
module Network.Google.Resource.IAM.Organizations.Roles.Patch
(
-- * REST Resource
OrganizationsRolesPatchResource
-- * Creating a Request
, organizationsRolesPatch
, OrganizationsRolesPatch
-- * Request Lenses
, orpXgafv
, orpUploadProtocol
, orpUpdateMask
, orpAccessToken
, orpUploadType
, orpPayload
, orpName
, orpCallback
) where
import Network.Google.IAM.Types
import Network.Google.Prelude
-- | A resource alias for @iam.organizations.roles.patch@ method which the
-- 'OrganizationsRolesPatch' request conforms to.
type OrganizationsRolesPatchResource =
"v1" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "updateMask" GFieldMask :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] Role :> Patch '[JSON] Role
-- | Updates the definition of a custom Role.
--
-- /See:/ 'organizationsRolesPatch' smart constructor.
data OrganizationsRolesPatch =
OrganizationsRolesPatch'
{ _orpXgafv :: !(Maybe Xgafv)
, _orpUploadProtocol :: !(Maybe Text)
, _orpUpdateMask :: !(Maybe GFieldMask)
, _orpAccessToken :: !(Maybe Text)
, _orpUploadType :: !(Maybe Text)
, _orpPayload :: !Role
, _orpName :: !Text
, _orpCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'OrganizationsRolesPatch' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'orpXgafv'
--
-- * 'orpUploadProtocol'
--
-- * 'orpUpdateMask'
--
-- * 'orpAccessToken'
--
-- * 'orpUploadType'
--
-- * 'orpPayload'
--
-- * 'orpName'
--
-- * 'orpCallback'
organizationsRolesPatch
:: Role -- ^ 'orpPayload'
-> Text -- ^ 'orpName'
-> OrganizationsRolesPatch
organizationsRolesPatch pOrpPayload_ pOrpName_ =
OrganizationsRolesPatch'
{ _orpXgafv = Nothing
, _orpUploadProtocol = Nothing
, _orpUpdateMask = Nothing
, _orpAccessToken = Nothing
, _orpUploadType = Nothing
, _orpPayload = pOrpPayload_
, _orpName = pOrpName_
, _orpCallback = Nothing
}
-- | V1 error format.
orpXgafv :: Lens' OrganizationsRolesPatch (Maybe Xgafv)
orpXgafv = lens _orpXgafv (\ s a -> s{_orpXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
orpUploadProtocol :: Lens' OrganizationsRolesPatch (Maybe Text)
orpUploadProtocol
= lens _orpUploadProtocol
(\ s a -> s{_orpUploadProtocol = a})
-- | A mask describing which fields in the Role have changed.
orpUpdateMask :: Lens' OrganizationsRolesPatch (Maybe GFieldMask)
orpUpdateMask
= lens _orpUpdateMask
(\ s a -> s{_orpUpdateMask = a})
-- | OAuth access token.
orpAccessToken :: Lens' OrganizationsRolesPatch (Maybe Text)
orpAccessToken
= lens _orpAccessToken
(\ s a -> s{_orpAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
orpUploadType :: Lens' OrganizationsRolesPatch (Maybe Text)
orpUploadType
= lens _orpUploadType
(\ s a -> s{_orpUploadType = a})
-- | Multipart request metadata.
orpPayload :: Lens' OrganizationsRolesPatch Role
orpPayload
= lens _orpPayload (\ s a -> s{_orpPayload = a})
-- | The \`name\` parameter\'s value depends on the target resource for the
-- request, namely
-- [\`projects\`](\/iam\/reference\/rest\/v1\/projects.roles) or
-- [\`organizations\`](\/iam\/reference\/rest\/v1\/organizations.roles).
-- Each resource type\'s \`name\` value format is described below: *
-- [\`projects.roles.patch()\`](\/iam\/reference\/rest\/v1\/projects.roles\/patch):
-- \`projects\/{PROJECT_ID}\/roles\/{CUSTOM_ROLE_ID}\`. This method updates
-- only [custom roles](\/iam\/docs\/understanding-custom-roles) that have
-- been created at the project level. Example request URL:
-- \`https:\/\/iam.googleapis.com\/v1\/projects\/{PROJECT_ID}\/roles\/{CUSTOM_ROLE_ID}\`
-- *
-- [\`organizations.roles.patch()\`](\/iam\/reference\/rest\/v1\/organizations.roles\/patch):
-- \`organizations\/{ORGANIZATION_ID}\/roles\/{CUSTOM_ROLE_ID}\`. This
-- method updates only [custom
-- roles](\/iam\/docs\/understanding-custom-roles) that have been created
-- at the organization level. Example request URL:
-- \`https:\/\/iam.googleapis.com\/v1\/organizations\/{ORGANIZATION_ID}\/roles\/{CUSTOM_ROLE_ID}\`
-- Note: Wildcard (*) values are invalid; you must specify a complete
-- project ID or organization ID.
orpName :: Lens' OrganizationsRolesPatch Text
orpName = lens _orpName (\ s a -> s{_orpName = a})
-- | JSONP
orpCallback :: Lens' OrganizationsRolesPatch (Maybe Text)
orpCallback
= lens _orpCallback (\ s a -> s{_orpCallback = a})
instance GoogleRequest OrganizationsRolesPatch where
type Rs OrganizationsRolesPatch = Role
type Scopes OrganizationsRolesPatch =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient OrganizationsRolesPatch'{..}
= go _orpName _orpXgafv _orpUploadProtocol
_orpUpdateMask
_orpAccessToken
_orpUploadType
_orpCallback
(Just AltJSON)
_orpPayload
iAMService
where go
= buildClient
(Proxy :: Proxy OrganizationsRolesPatchResource)
mempty
| brendanhay/gogol | gogol-iam/gen/Network/Google/Resource/IAM/Organizations/Roles/Patch.hs | mpl-2.0 | 6,507 | 0 | 17 | 1,331 | 873 | 515 | 358 | 122 | 1 |
-- Example 11 - the union of a square and a circle.
import Graphics.Implicit
out = union [
rectR 0 (-40,-40) (40,40),
translate (40,40) (circle 30) ]
main = writeSVG 2 "example11.svg" out
| krakrjak/ImplicitCAD | Examples/example11.hs | agpl-3.0 | 205 | 0 | 9 | 50 | 73 | 40 | 33 | 5 | 1 |
{-# LANGUAGE FlexibleInstances #-}
-- | REPL Parser
-- parses interpret commands
--
module CoALPj.REPL.Parser (
parseCmd
, cmdInfo
, replCompletion
) where
import Control.Applicative
import Control.Monad.IO.Class (MonadIO)
import Control.Arrow ((***))
import Data.Maybe (fromJust)
import Data.Monoid (Monoid,mempty,mappend,mconcat)
import Text.Parsec (parse,many1,digit,eof)
import Text.Parsec.Char (char,space,spaces,anyChar,noneOf,string,hexDigit)
import Text.Parsec.Combinator (sepBy)
import Text.Parsec.Error (ParseError)
import Text.Parsec.String (Parser)
import System.Console.Haskeline.Completion -- (Completion(..), CompletionFunc, noCompletion)
import CoALPj.REPL.Commands (Command(..))
parseCmd :: String -> Either ParseError Command
-- TODO input name
parseCmd cmd = parse (
(
(spaces *> pure Empty <* eof)
<|> toCmdParser dCmd
<|> (Resolve <$> many anyChar)
) <* spaces <* eof) "(input)" cmd
cmdInfo :: String
cmdInfo = toCmdInfo dCmd
--dCmd :: Parser Command
dCmd :: CommandDescr String String (Parser Command)
dCmd = toCmdDescr [
(
":load"
, spaces *> (Load <$> many (noneOf " \t\\" <|> (char '\\' *> anyChar)))
, "\n\t:load <file>\n\t\tLoad a new program\n"
), (
":reload"
, pure Reload
, "\n\t:reload\n\t\tReload the current program\n"
), (
":print"
, pure Print
, "\n\t:print\n\t\tPrint contents of the loaded program\n"
), (
":quit"
, pure Quit
, "" -- \n\t:quit\n\t\tExit the interpreter\n"
), (
":transform"
, spaces *> (pure Transform)
, "\n\t:transform\n\t\tTransforms the loaded program\n"
), (
":annotate"
, spaces *> (pure Annotate)
, "\n\t:annotate\n\t\tAnnotates the loaded program\n\t\tDo not transform before annotation as" ++
"this transform the loaded program and then annotates it\n"
), (
":convert"
, spaces *> (pure Convert)
, "\n\t:convert\n\t\tConverts the loaded program so it is ready for transformation or annotation.\n"
), (
":antiUnify"
, spaces *> (AntiUnify <$> many anyChar)
, "\n\t:antiUnify <query>\n\t\tAttempt to antiunify the two terms in the body of the query.\n" ++
"\t\t'? :- BODY . '\n"
), (
":signature"
, spaces *> (Sig <$> many anyChar)
, "\n\t:signature <identifier>\n\t\tPrint signatture for a predicate.\n"
), (
":gc1"
, pure GC1
, "\n\t:gc1\n\t\tGuardednes check 1\n"
), (
":gc2"
, spaces *> (GC2 <$> many anyChar)
, "\n\t:gc2 <query>\n\t\tGuardedness check 2, query bas the form\n" ++
"\t\t'? :- BODY . '\n"
), (
":cgc3"
, spaces *> (GC3One <$> many anyChar)
, "\n\t:cgc3\n\t\tGuardedness check 3 for a clause of the form\n" ++
"\t\t'? :- BODY . '\n"
), (
":gc3"
, spaces *> (pure GC3)
, "\n\t:gc3\n\t\tGuardedness check 3 for the loaded program\n"
), (
":drawTerms"
, pure DrawProgram
, "\n\t:drawTerms\n\t\tDraw terms in the program\n"
), (
":drawRew"
, spaces *> (DrawRew <$> (read <$> digits1 <* spaces1) <*> many anyChar)
, "\n\t:drawRew <depth> <query>\n\t\tDraw rewriting tree, depth is an integer, query has the form\n" ++
"\t\t'? :- BODY . '\n"
), (
":drawTrans"
, spaces *> (DrawTrans
<$> (read <$> digits1 <* spaces1)
<*> (fmap readHex <$>
(
string "[" *>
((spaces *> string "0x" *> hexDigits1 <* spaces) `sepBy` (string ","))
<* string "]" <* spaces1
)) <*> many anyChar)
, "\n\t:drawTrans <depth> '[' <transvar_1>, ... ']' <query>\n\t\tDraw transition between rewriting trees, depth is an integer,\n" ++
"\t\ttransvars are the transition variable, and query has the form\n" ++
"\t\t'? :- BODY . '\n"
), (
":drawDer"
, spaces *> (DrawDer
<$> (read <$> digits1 <* spaces1)
<*> (read <$> digits1 <* spaces1)
<*> many anyChar)
, "\n\t:drawDer <depthDer> <depthRew> <query>\n\t\tDraw derivation tree, depth is an integer, and query has the form\n" ++
"\t\t'? :- BODY . '\n"
), (
":drawUnsafe"
, spaces *> (DrawUnsafe
<$> (read <$> digits1 <* spaces1)
<*> (read <$> digits1 <* spaces1)
<*> many anyChar)
, "\n\t:drawUnsafe <depthDer> <depthRew> <query>\n\t\tDraw derivation tree ignoring unguarded rewriting trees, depth is an integer, and query has the form\n" ++
"\t\t'? :- BODY . '\n"
), (
":drawInf"
, spaces *> (DrawInf
<$> (read <$> digits1 <* spaces1)
<*> (read <$> digits1 <* spaces1)
<*> many anyChar)
, "\n\t:drawInf <depthDer> <depthRew> <query>\n\t\tDraw the branch of the derivation tree " ++
"that is not closed in the\n\t\tdepth depthDer. Depth is an integer, and query has the form\n" ++
"\t\t'? :- BODY . '\n"
), (
":drawUng"
, spaces *> (DrawUng
<$> (read <$> digits1 <* spaces1)
<*> (read <$> digits1 <* spaces1)
<*> many anyChar)
, "\n\t:drawUng <depthDer> <depthRew> <query>\n\t\tDraw a branch of the derivation tree " ++
"that has an unguarded\n\t\tRewTree in depthD. Depth is an integer, and query has the form\n" ++
"\t\t'? :- BODY . '\n"
), (
":help"
, pure Help
, "\n\t:help\n\t\tShow the help\n"
), (
";"
, pure Next
, "\n\t;\n\t\tShow next result\n"
)
]
-- | Just a helpers
spaces1,digits1,hexDigits1 :: Parser String
spaces1 = many1 space
digits1 = many1 digit
hexDigits1 = many1 hexDigit
readHex :: (Integral a, Read a) => String -> a
readHex s = foldl (\x y -> 16 * x + toH y) 0 s
where
toH x = fromJust $ lookup x
[ ('0', 0), ('1', 1), ('2', 2), ('3', 3), ('4', 4)
, ('5', 5), ('6', 6), ('7', 7), ('8', 8), ('9', 9)
, ('a', 10), ('b', 11), ('c', 12), ('d', 13), ('e', 14), ('f', 15)
, ('A', 10), ('B', 11), ('C', 12), ('D', 13), ('E', 14), ('F', 15)
]
-- | Command Decription Trie
-- use Data - trie
data CommandDescr a b c = Sep [(a,CommandDescr a b c)] | Cmd b c String
deriving Show
instance Ord a => Monoid (CommandDescr a [a] c) where
mempty = emptyCmds
mappend = joinCmds
emptyCmds :: CommandDescr a b c
emptyCmds = Sep []
joinCmds :: (Ord a) => CommandDescr a [a] c -> CommandDescr a [a] c -> CommandDescr a [a] c
joinCmds (Sep []) y = y
joinCmds x (Sep []) = x
--joinCmds (Cmd [] _) (Cmd [] _) = error "multiple commands with same string"
joinCmds (Cmd (x1:xs1) y1 desc1) (Cmd (x2:xs2) y2 desc2)
| x1 == x2 = Sep [(x1,joinCmds (Cmd xs1 y1 desc1) (Cmd xs2 y2 desc2))]
| x1 < x2 = Sep [(x1,Cmd xs1 y1 desc1),(x2,Cmd xs2 y2 desc2)]
| otherwise = Sep [(x2,Cmd xs2 y2 desc1),(x1,Cmd xs1 y1 desc2)]
joinCmds (Sep s1) (Sep s2) = Sep $ joinS (s1) s2
where
joinS [] x = x
joinS x [] = x
joinS (a@((x,xc):xcs)) (b@((y,yc):ycs))
| x < y = (x,xc):(joinS xcs b)
| x == y = (x, joinCmds xc yc):(joinS xcs ycs)
| x > y = (y,yc):(joinS a ycs)
joinS _ _ = error "Impssible pattern2?"
joinCmds a@(Sep _) (Cmd (x:xs) xc d) = joinCmds a (Sep [(x,Cmd xs xc d)])
joinCmds a@(Cmd (_:_) _ _) b@(Sep _) = joinCmds b a
joinCmds _ _ = error "Impossible pattern?" -- $ show x ++ "\n" ++ show y
-- | pack the trie
pack :: CommandDescr a [a] c -> CommandDescr [a] [a] c
pack (Cmd x c d) = Cmd x c d
pack (Sep [(x,Cmd xs c d)]) = Cmd (x:xs) c d
pack (Sep s) = Sep $ ((:[]) *** pack) <$> s
-- | concat partial parsers
toCmdDescr :: Ord a => [([a],c,String)] -> CommandDescr [a] [a] c
toCmdDescr p = pack $ mconcat $ u <$> p
where
u (a, b, c) = Cmd a b c
toCmdParser :: CommandDescr String String (Parser a) -> Parser a
toCmdParser (Cmd c cmd _) = optional (string c) *> cmd
toCmdParser (Sep s) = foldr (<|>) empty (step <$> s)
where
step (sep, c) = string sep *> toCmdParser c
toCmdInfo :: CommandDescr a b c -> String
toCmdInfo (Cmd _ _ d) = d
toCmdInfo (Sep s) = foldr mappend empty (map (toCmdInfo . snd) s)
-- | Complete REPL commands and defined identifiers
-- TODO proper implemnetation
replCompletion :: MonadIO m => CompletionFunc m
{-replCompletion (prev, next) = return ( "", fmap compl [
" -- TODO implement completion"
, " -- you can always try other comletions ..."
])
where
compl x = Completion {
replacement = x
, display = "try " ++ x
, isFinished = False
}
-}
replCompletion = completeFilename
--replCompletion = completeWord (Nothing) " " replcs
where
{- replcs _ = do
return [
simpleCompletion "none"
, simpleCompletion "nil"
]
-}
| frantisekfarka/CoALP | inter/CoALPj/REPL/Parser.hs | lgpl-3.0 | 8,197 | 168 | 24 | 1,780 | 2,702 | 1,493 | 1,209 | 201 | 4 |
cnst :: [String] -> (String,[Int])
cnst [n,b,w] =
let b' = read b :: Int
w' = read w :: Int
in
(n, [w' - b' + 1, w'])
solv :: [(String,[Int])] -> Int -> String
solv t w =
let f = filter (\ (n,[s,e]) -> (w >= s) && (e >= w) ) t
in
if f == []
then "Unknown"
else
let (n,[ws,wl]) = head f
in
unwords [ n, show (w - ws + 1) ]
ans :: [[String]] -> [[String]]
ans (["0","0"]:_) = []
ans ([n,q]:x) =
let n'= read n :: Int
q'= read q :: Int
t = map cnst $ take n' x
w = map (read . head) $ take q' $ drop n' x :: [Int]
a = map (solv t) w
r = drop (n'+q') x
in
a:(ans r)
main = do
c <- getContents
let i = map words $ lines c
o = ans i
mapM_ putStrLn $ concat o
| a143753/AOJ | 2242.hs | apache-2.0 | 827 | 0 | 15 | 337 | 482 | 257 | 225 | 27 | 2 |
-- Copyright 2016 David Edwards
--
-- 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 Token (
Token(..),
lexeme,
charIsToken,
charToToken,
asToken
) where
data Token =
PlusToken
| MinusToken
| StarToken
| SlashToken
| PercentToken
| CaretToken
| LeftParenToken
| RightParenToken
| MinToken
| MaxToken
| SymbolToken String
| NumberToken String
| EOSToken
deriving (Eq, Show)
lexeme :: Token -> String
lexeme PlusToken = "+"
lexeme MinusToken = "-"
lexeme StarToken = "*"
lexeme SlashToken = "/"
lexeme PercentToken = "%"
lexeme CaretToken = "^"
lexeme LeftParenToken = "("
lexeme RightParenToken = ")"
lexeme MinToken = "min"
lexeme MaxToken = "max"
lexeme EOSToken = "<EOS>"
lexeme (SymbolToken lex) = lex
lexeme (NumberToken lex) = lex
charIsToken :: Char -> Bool
charIsToken c = elem c ['+', '-', '*', '/', '%', '^', '(', ')']
charToToken :: Char -> Token
charToToken '+' = PlusToken
charToToken '-' = MinusToken
charToToken '*' = StarToken
charToToken '/' = SlashToken
charToToken '%' = PercentToken
charToToken '^' = CaretToken
charToToken '(' = LeftParenToken
charToToken ')' = RightParenToken
asToken :: String -> Token
asToken "min" = MinToken
asToken "max" = MaxToken
asToken lex = SymbolToken lex
| davidledwards/rpn-haskell | src/Token.hs | apache-2.0 | 1,759 | 0 | 7 | 316 | 376 | 211 | 165 | 50 | 1 |
module Web.Socdiff.FB.FB where
import qualified Data.Text as T
import Facebook
import Haxl.Core
import Web.Socdiff.FB.DataSource
-- | Fetch a list of friends for the given user id
getFriends :: T.Text -> GenHaxl u [T.Text]
getFriends u = dataFetch (GetFriends (Id u))
| relrod/socdiff | src/Web/Socdiff/FB/FB.hs | bsd-2-clause | 270 | 0 | 9 | 42 | 76 | 45 | 31 | 7 | 1 |
module Data.ConstIndex where
newtype ConstIndex f k a = ConstIndex { runConstIndex :: f a }
instance (Functor f) => Functor (ConstIndex f a) where
fmap f (ConstIndex ls) = ConstIndex (fmap f ls)
instance Foldable f => Foldable (ConstIndex f a) where
foldMap f (ConstIndex ls) = foldMap f ls
instance (Foldable f, Traversable f) => Traversable (ConstIndex f a) where
traverse f (ConstIndex ls) = fmap ConstIndex (traverse f ls)
| esmolanka/struct-parse | Data/ConstIndex.hs | bsd-3-clause | 438 | 0 | 8 | 83 | 181 | 94 | 87 | 8 | 0 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.Config
-- Copyright : (c) David Himmelstrup 2005
-- License : BSD-like
--
-- Maintainer : lemmih@gmail.com
-- Stability : provisional
-- Portability : portable
--
-- Utilities for handling saved state such as known packages, known servers and
-- downloaded packages.
-----------------------------------------------------------------------------
module Distribution.Client.Config (
SavedConfig(..),
loadConfig,
showConfig,
showConfigWithComments,
parseConfig,
defaultCabalDir,
defaultConfigFile,
defaultCacheDir,
defaultCompiler,
defaultLogsDir,
defaultPatchesDir,
defaultUserInstall,
baseSavedConfig,
commentSavedConfig,
initialSavedConfig,
configFieldDescriptions,
haddockFlagsFields,
installDirsFields,
withProgramsFields,
withProgramOptionsFields,
userConfigDiff,
userConfigUpdate
) where
import Distribution.Client.Types
( RemoteRepo(..), Username(..), Password(..) )
import Distribution.Client.BuildReports.Types
( ReportLevel(..) )
import Distribution.Client.Setup
( GlobalFlags(..), globalCommand, defaultGlobalFlags
, ConfigExFlags(..), configureExOptions, defaultConfigExFlags
, InstallFlags(..), installOptions, defaultInstallFlags
, UploadFlags(..), uploadCommand
, ReportFlags(..), reportCommand
, showRepo, parseRepo )
import Distribution.Utils.NubList
( NubList, fromNubList, toNubList)
import Distribution.Simple.Compiler
( DebugInfoLevel(..), OptimisationLevel(..) )
import Distribution.Simple.Setup
( ConfigFlags(..), configureOptions, defaultConfigFlags
, HaddockFlags(..), haddockOptions, defaultHaddockFlags
, installDirsOptions
, programConfigurationPaths', programConfigurationOptions
, Flag(..), toFlag, flagToMaybe, fromFlagOrDefault )
import Distribution.Simple.InstallDirs
( InstallDirs(..), defaultInstallDirs
, PathTemplate, toPathTemplate )
import Distribution.ParseUtils
( FieldDescr(..), liftField
, ParseResult(..), PError(..), PWarning(..)
, locatedErrorMsg, showPWarning
, readFields, warning, lineNo
, simpleField, listField, parseFilePathQ, parseTokenQ )
import Distribution.Client.ParseUtils
( parseFields, ppFields, ppSection )
import qualified Distribution.ParseUtils as ParseUtils
( Field(..) )
import qualified Distribution.Text as Text
( Text(..) )
import Distribution.Simple.Command
( CommandUI(commandOptions), commandDefaultFlags, ShowOrParseArgs(..)
, viewAsFieldDescr )
import Distribution.Simple.Program
( defaultProgramConfiguration )
import Distribution.Simple.Utils
( die, notice, warn, lowercase, cabalVersion )
import Distribution.Compiler
( CompilerFlavor(..), defaultCompilerFlavor )
import Distribution.Verbosity
( Verbosity, normal )
import Data.List
( partition, find, foldl' )
import Data.Maybe
( fromMaybe )
#if !MIN_VERSION_base(4,8,0)
import Data.Monoid
( Monoid(..) )
#endif
import Control.Monad
( unless, foldM, liftM, liftM2 )
import qualified Distribution.Compat.ReadP as Parse
( option )
import qualified Text.PrettyPrint as Disp
( render, text, empty )
import Text.PrettyPrint
( ($+$) )
import System.Directory
( createDirectoryIfMissing, getAppUserDataDirectory, renameFile )
import Network.URI
( URI(..), URIAuth(..) )
import System.FilePath
( (<.>), (</>), takeDirectory )
import System.IO.Error
( isDoesNotExistError )
import Distribution.Compat.Environment
( getEnvironment )
import Distribution.Compat.Exception
( catchIO )
import qualified Paths_epm
( version )
import Data.Version
( showVersion )
import Data.Char
( isSpace )
import qualified Data.Map as M
--
-- * Configuration saved in the config file
--
data SavedConfig = SavedConfig {
savedGlobalFlags :: GlobalFlags,
savedInstallFlags :: InstallFlags,
savedConfigureFlags :: ConfigFlags,
savedConfigureExFlags :: ConfigExFlags,
savedUserInstallDirs :: InstallDirs (Flag PathTemplate),
savedGlobalInstallDirs :: InstallDirs (Flag PathTemplate),
savedUploadFlags :: UploadFlags,
savedReportFlags :: ReportFlags,
savedHaddockFlags :: HaddockFlags
}
instance Monoid SavedConfig where
mempty = SavedConfig {
savedGlobalFlags = mempty,
savedInstallFlags = mempty,
savedConfigureFlags = mempty,
savedConfigureExFlags = mempty,
savedUserInstallDirs = mempty,
savedGlobalInstallDirs = mempty,
savedUploadFlags = mempty,
savedReportFlags = mempty,
savedHaddockFlags = mempty
}
mappend a b = SavedConfig {
savedGlobalFlags = combinedSavedGlobalFlags,
savedInstallFlags = combinedSavedInstallFlags,
savedConfigureFlags = combinedSavedConfigureFlags,
savedConfigureExFlags = combinedSavedConfigureExFlags,
savedUserInstallDirs = combinedSavedUserInstallDirs,
savedGlobalInstallDirs = combinedSavedGlobalInstallDirs,
savedUploadFlags = combinedSavedUploadFlags,
savedReportFlags = combinedSavedReportFlags,
savedHaddockFlags = combinedSavedHaddockFlags
}
where
-- This is ugly, but necessary. If we're mappending two config files, we
-- want the values of the *non-empty* list fields from the second one to
-- *override* the corresponding values from the first one. Default
-- behaviour (concatenation) is confusing and makes some use cases (see
-- #1884) impossible.
--
-- However, we also want to allow specifying multiple values for a list
-- field in a *single* config file. For example, we want the following to
-- continue to work:
--
-- remote-repo: hackage.haskell.org:http://hackage.haskell.org/
-- remote-repo: private-collection:http://hackage.local/
--
-- So we can't just wrap the list fields inside Flags; we have to do some
-- special-casing just for SavedConfig.
-- NB: the signature prevents us from using 'combine' on lists.
combine' :: (SavedConfig -> flags) -> (flags -> Flag a) -> Flag a
combine' field subfield =
(subfield . field $ a) `mappend` (subfield . field $ b)
lastNonEmpty' :: (SavedConfig -> flags) -> (flags -> [a]) -> [a]
lastNonEmpty' field subfield =
let a' = subfield . field $ a
b' = subfield . field $ b
in case b' of [] -> a'
_ -> b'
lastNonEmptyNL' :: (SavedConfig -> flags) -> (flags -> NubList a)
-> NubList a
lastNonEmptyNL' field subfield =
let a' = subfield . field $ a
b' = subfield . field $ b
in case fromNubList b' of [] -> a'
_ -> b'
combinedSavedGlobalFlags = GlobalFlags {
globalVersion = combine globalVersion,
globalNumericVersion = combine globalNumericVersion,
globalConfigFile = combine globalConfigFile,
globalSandboxConfigFile = combine globalSandboxConfigFile,
globalRemoteRepos = lastNonEmptyNL globalRemoteRepos,
globalCacheDir = combine globalCacheDir,
globalLocalRepos = lastNonEmptyNL globalLocalRepos,
globalLogsDir = combine globalLogsDir,
globalWorldFile = combine globalWorldFile,
globalRequireSandbox = combine globalRequireSandbox,
globalIgnoreSandbox = combine globalIgnoreSandbox
}
where
combine = combine' savedGlobalFlags
lastNonEmptyNL = lastNonEmptyNL' savedGlobalFlags
combinedSavedInstallFlags = InstallFlags {
installDocumentation = combine installDocumentation,
installHaddockIndex = combine installHaddockIndex,
installDryRun = combine installDryRun,
installMaxBackjumps = combine installMaxBackjumps,
installReorderGoals = combine installReorderGoals,
installIndependentGoals = combine installIndependentGoals,
installShadowPkgs = combine installShadowPkgs,
installStrongFlags = combine installStrongFlags,
installReinstall = combine installReinstall,
installEtaPatchesDirectory = combine installEtaPatchesDirectory,
installAvoidReinstalls = combine installAvoidReinstalls,
installOverrideReinstall = combine installOverrideReinstall,
installUpgradeDeps = combine installUpgradeDeps,
installOnly = combine installOnly,
installOnlyDeps = combine installOnlyDeps,
installRootCmd = combine installRootCmd,
installSummaryFile = lastNonEmptyNL installSummaryFile,
installLogFile = combine installLogFile,
installBuildReports = combine installBuildReports,
installReportPlanningFailure = combine installReportPlanningFailure,
installSymlinkBinDir = combine installSymlinkBinDir,
installOneShot = combine installOneShot,
installNumJobs = combine installNumJobs,
installRunTests = combine installRunTests
}
where
combine = combine' savedInstallFlags
lastNonEmptyNL = lastNonEmptyNL' savedInstallFlags
combinedSavedConfigureFlags = ConfigFlags {
configPrograms = configPrograms . savedConfigureFlags $ b,
-- TODO: NubListify
configProgramPaths = lastNonEmpty configProgramPaths,
-- TODO: NubListify
configProgramArgs = lastNonEmpty configProgramArgs,
configProgramPathExtra = lastNonEmptyNL configProgramPathExtra,
configHcFlavor = combine configHcFlavor,
configHcPath = combine configHcPath,
configHcPkg = combine configHcPkg,
configVanillaLib = combine configVanillaLib,
configProfLib = combine configProfLib,
configSharedLib = combine configSharedLib,
configDynExe = combine configDynExe,
configProfExe = combine configProfExe,
-- TODO: NubListify
configConfigureArgs = lastNonEmpty configConfigureArgs,
configOptimization = combine configOptimization,
configDebugInfo = combine configDebugInfo,
configProgPrefix = combine configProgPrefix,
configProgSuffix = combine configProgSuffix,
-- Parametrised by (Flag PathTemplate), so safe to use 'mappend'.
configInstallDirs =
(configInstallDirs . savedConfigureFlags $ a)
`mappend` (configInstallDirs . savedConfigureFlags $ b),
configScratchDir = combine configScratchDir,
-- TODO: NubListify
configExtraLibDirs = lastNonEmpty configExtraLibDirs,
-- TODO: NubListify
configExtraIncludeDirs = lastNonEmpty configExtraIncludeDirs,
configDistPref = combine configDistPref,
configVerbosity = combine configVerbosity,
configUserInstall = combine configUserInstall,
-- TODO: NubListify
configPackageDBs = lastNonEmpty configPackageDBs,
configGHCiLib = combine configGHCiLib,
configSplitObjs = combine configSplitObjs,
configStripExes = combine configStripExes,
configStripLibs = combine configStripLibs,
-- TODO: NubListify
configConstraints = lastNonEmpty configConstraints,
-- TODO: NubListify
configDependencies = lastNonEmpty configDependencies,
configInstantiateWith = lastNonEmpty configInstantiateWith,
-- TODO: NubListify
configConfigurationsFlags = lastNonEmpty configConfigurationsFlags,
configTests = combine configTests,
configBenchmarks = combine configBenchmarks,
configCoverage = combine configCoverage,
configLibCoverage = combine configLibCoverage,
configExactConfiguration = combine configExactConfiguration,
configFlagError = combine configFlagError,
configRelocatable = combine configRelocatable
}
where
combine = combine' savedConfigureFlags
lastNonEmpty = lastNonEmpty' savedConfigureFlags
lastNonEmptyNL = lastNonEmptyNL' savedConfigureFlags
combinedSavedConfigureExFlags = ConfigExFlags {
configCabalVersion = combine configCabalVersion,
-- TODO: NubListify
configExConstraints = lastNonEmpty configExConstraints,
-- TODO: NubListify
configPreferences = lastNonEmpty configPreferences,
configSolver = combine configSolver,
configAllowNewer = combine configAllowNewer
}
where
combine = combine' savedConfigureExFlags
lastNonEmpty = lastNonEmpty' savedConfigureExFlags
-- Parametrised by (Flag PathTemplate), so safe to use 'mappend'.
combinedSavedUserInstallDirs = savedUserInstallDirs a
`mappend` savedUserInstallDirs b
-- Parametrised by (Flag PathTemplate), so safe to use 'mappend'.
combinedSavedGlobalInstallDirs = savedGlobalInstallDirs a
`mappend` savedGlobalInstallDirs b
combinedSavedUploadFlags = UploadFlags {
uploadCheck = combine uploadCheck,
uploadUsername = combine uploadUsername,
uploadPassword = combine uploadPassword,
uploadVerbosity = combine uploadVerbosity
}
where
combine = combine' savedUploadFlags
combinedSavedReportFlags = ReportFlags {
reportUsername = combine reportUsername,
reportPassword = combine reportPassword,
reportVerbosity = combine reportVerbosity
}
where
combine = combine' savedReportFlags
combinedSavedHaddockFlags = HaddockFlags {
-- TODO: NubListify
haddockProgramPaths = lastNonEmpty haddockProgramPaths,
-- TODO: NubListify
haddockProgramArgs = lastNonEmpty haddockProgramArgs,
haddockHoogle = combine haddockHoogle,
haddockHtml = combine haddockHtml,
haddockHtmlLocation = combine haddockHtmlLocation,
haddockExecutables = combine haddockExecutables,
haddockTestSuites = combine haddockTestSuites,
haddockBenchmarks = combine haddockBenchmarks,
haddockInternal = combine haddockInternal,
haddockCss = combine haddockCss,
haddockHscolour = combine haddockHscolour,
haddockHscolourCss = combine haddockHscolourCss,
haddockContents = combine haddockContents,
haddockDistPref = combine haddockDistPref,
haddockKeepTempFiles = combine haddockKeepTempFiles,
haddockVerbosity = combine haddockVerbosity
}
where
combine = combine' savedHaddockFlags
lastNonEmpty = lastNonEmpty' savedHaddockFlags
updateInstallDirs :: Flag Bool -> SavedConfig -> SavedConfig
updateInstallDirs userInstallFlag
savedConfig@SavedConfig {
savedConfigureFlags = configureFlags,
savedUserInstallDirs = userInstallDirs,
savedGlobalInstallDirs = globalInstallDirs
} =
savedConfig {
savedConfigureFlags = configureFlags {
configInstallDirs = installDirs
}
}
where
installDirs | userInstall = userInstallDirs
| otherwise = globalInstallDirs
userInstall = fromFlagOrDefault defaultUserInstall $
configUserInstall configureFlags `mappend` userInstallFlag
--
-- * Default config
--
-- | These are the absolute basic defaults. The fields that must be
-- initialised. When we load the config from the file we layer the loaded
-- values over these ones, so any missing fields in the file take their values
-- from here.
--
baseSavedConfig :: IO SavedConfig
baseSavedConfig = do
userPrefix <- defaultCabalDir
logsDir <- defaultLogsDir
worldFile <- defaultWorldFile
return mempty {
savedConfigureFlags = mempty {
configHcFlavor = toFlag defaultCompiler,
configUserInstall = toFlag defaultUserInstall,
configVerbosity = toFlag normal
},
savedUserInstallDirs = mempty {
prefix = toFlag (toPathTemplate userPrefix)
},
savedGlobalFlags = mempty {
globalLogsDir = toFlag logsDir,
globalWorldFile = toFlag worldFile
}
}
-- | This is the initial configuration that we write out to to the config file
-- if the file does not exist (or the config we use if the file cannot be read
-- for some other reason). When the config gets loaded it gets layered on top
-- of 'baseSavedConfig' so we do not need to include it into the initial
-- values we save into the config file.
--
initialSavedConfig :: IO SavedConfig
initialSavedConfig = do
cacheDir <- defaultCacheDir
logsDir <- defaultLogsDir
worldFile <- defaultWorldFile
extraPath <- defaultExtraPath
return mempty {
savedGlobalFlags = mempty {
globalCacheDir = toFlag cacheDir,
globalRemoteRepos = toNubList defaultRemoteRepos,
globalWorldFile = toFlag worldFile
},
savedConfigureFlags = mempty {
configProgramPathExtra = toNubList extraPath
},
savedInstallFlags = mempty {
installSummaryFile = toNubList [toPathTemplate (logsDir </> "build.log")],
installBuildReports= toFlag AnonymousReports,
installNumJobs = toFlag Nothing
}
}
--TODO: misleading, there's no way to override this default
-- either make it possible or rename to simply getCabalDir.
defaultCabalDir :: IO FilePath
defaultCabalDir = getAppUserDataDirectory "epm"
defaultConfigFile :: IO FilePath
defaultConfigFile = do
dir <- defaultCabalDir
return $ dir </> "config"
defaultCacheDir :: IO FilePath
defaultCacheDir = do
dir <- defaultCabalDir
return $ dir </> "packages"
defaultLogsDir :: IO FilePath
defaultLogsDir = do
dir <- defaultCabalDir
return $ dir </> "logs"
defaultPatchesDir :: IO FilePath
defaultPatchesDir = do
dir <- defaultCabalDir
return $ dir </> "patches"
-- | Default position of the world file
defaultWorldFile :: IO FilePath
defaultWorldFile = do
dir <- defaultCabalDir
return $ dir </> "world"
defaultExtraPath :: IO [FilePath]
defaultExtraPath = do
dir <- defaultCabalDir
return [dir </> "bin"]
defaultCompiler :: CompilerFlavor
defaultCompiler = fromMaybe ETA defaultCompilerFlavor
defaultUserInstall :: Bool
defaultUserInstall = True
-- We do per-user installs by default on all platforms. We used to default to
-- global installs on Windows but that no longer works on Windows Vista or 7.
defaultRemoteRepos :: [RemoteRepo]
defaultRemoteRepos = [RemoteRepo hackageName hackageUri
,RemoteRepo etlasName etlasUri]
where
hackageName = "hackage.haskell.org"
hackageUri = URI "http:" (Just (URIAuth "" hackageName ""))
"/packages/archive" "" ""
etlasName = "git.etlas.eta-lang.org"
etlasUri = URI "http:" (Just (URIAuth "" "github.com" ""))
"/typelead/etlas-index" "" ""
--
-- * Config file reading
--
loadConfig :: Verbosity -> Flag FilePath -> Flag Bool -> IO SavedConfig
loadConfig verbosity configFileFlag userInstallFlag = addBaseConf $ do
let sources = [
("commandline option", return . flagToMaybe $ configFileFlag),
("env var CABAL_CONFIG", lookup "CABAL_CONFIG" `liftM` getEnvironment),
("default config file", Just `liftM` defaultConfigFile) ]
getSource [] = error "no config file path candidate found."
getSource ((msg,action): xs) =
action >>= maybe (getSource xs) (return . (,) msg)
(source, configFile) <- getSource sources
minp <- readConfigFile mempty configFile
case minp of
Nothing -> do
notice verbosity $ "Config file path source is " ++ source ++ "."
notice verbosity $ "Config file " ++ configFile ++ " not found."
notice verbosity $ "Writing default configuration to " ++ configFile
commentConf <- commentSavedConfig
initialConf <- initialSavedConfig
writeConfigFile configFile commentConf initialConf
return initialConf
Just (ParseOk ws conf) -> do
unless (null ws) $ warn verbosity $
unlines (map (showPWarning configFile) ws)
return conf
Just (ParseFailed err) -> do
let (line, msg) = locatedErrorMsg err
die $
"Error parsing config file " ++ configFile
++ maybe "" (\n -> ':' : show n) line ++ ":\n" ++ msg
where
addBaseConf body = do
base <- baseSavedConfig
extra <- body
return (updateInstallDirs userInstallFlag (base `mappend` extra))
readConfigFile :: SavedConfig -> FilePath -> IO (Maybe (ParseResult SavedConfig))
readConfigFile initial file = handleNotExists $
fmap (Just . parseConfig initial) (readFile file)
where
handleNotExists action = catchIO action $ \ioe ->
if isDoesNotExistError ioe
then return Nothing
else ioError ioe
writeConfigFile :: FilePath -> SavedConfig -> SavedConfig -> IO ()
writeConfigFile file comments vals = do
let tmpFile = file <.> "tmp"
createDirectoryIfMissing True (takeDirectory file)
writeFile tmpFile $ explanation ++ showConfigWithComments comments vals ++ "\n"
renameFile tmpFile file
where
explanation = unlines
["-- This is the configuration file for the 'epm' command line tool."
,""
,"-- The available configuration options are listed below."
,"-- Some of them have default values listed."
,""
,"-- Lines (like this one) beginning with '--' are comments."
,"-- Be careful with spaces and indentation because they are"
,"-- used to indicate layout for nested sections."
,""
,"-- Cabal library version: " ++ showVersion cabalVersion
,"-- epm version: " ++ showVersion Paths_epm.version
,"",""
]
-- | These are the default values that get used in Cabal if a no value is
-- given. We use these here to include in comments when we write out the
-- initial config file so that the user can see what default value they are
-- overriding.
--
commentSavedConfig :: IO SavedConfig
commentSavedConfig = do
userInstallDirs <- defaultInstallDirs defaultCompiler True True
globalInstallDirs <- defaultInstallDirs defaultCompiler False True
return SavedConfig {
savedGlobalFlags = defaultGlobalFlags,
savedInstallFlags = defaultInstallFlags,
savedConfigureExFlags = defaultConfigExFlags,
savedConfigureFlags = (defaultConfigFlags defaultProgramConfiguration) {
configUserInstall = toFlag defaultUserInstall
},
savedUserInstallDirs = fmap toFlag userInstallDirs,
savedGlobalInstallDirs = fmap toFlag globalInstallDirs,
savedUploadFlags = commandDefaultFlags uploadCommand,
savedReportFlags = commandDefaultFlags reportCommand,
savedHaddockFlags = defaultHaddockFlags
}
-- | All config file fields.
--
configFieldDescriptions :: [FieldDescr SavedConfig]
configFieldDescriptions =
toSavedConfig liftGlobalFlag
(commandOptions (globalCommand []) ParseArgs)
["version", "numeric-version", "config-file", "sandbox-config-file"] []
++ toSavedConfig liftConfigFlag
(configureOptions ParseArgs)
(["builddir", "constraint", "dependency"]
++ map fieldName installDirsFields)
--FIXME: this is only here because viewAsFieldDescr gives us a parser
-- that only recognises 'ghc' etc, the case-sensitive flag names, not
-- what the normal case-insensitive parser gives us.
[simpleField "compiler"
(fromFlagOrDefault Disp.empty . fmap Text.disp) (optional Text.parse)
configHcFlavor (\v flags -> flags { configHcFlavor = v })
-- TODO: The following is a temporary fix. The "optimization"
-- and "debug-info" fields are OptArg, and viewAsFieldDescr
-- fails on that. Instead of a hand-written hackaged parser
-- and printer, we should handle this case properly in the
-- library.
,liftField configOptimization (\v flags -> flags { configOptimization = v }) $
let name = "optimization" in
FieldDescr name
(\f -> case f of
Flag NoOptimisation -> Disp.text "False"
Flag NormalOptimisation -> Disp.text "True"
Flag MaximumOptimisation -> Disp.text "2"
_ -> Disp.empty)
(\line str _ -> case () of
_ | str == "False" -> ParseOk [] (Flag NoOptimisation)
| str == "True" -> ParseOk [] (Flag NormalOptimisation)
| str == "0" -> ParseOk [] (Flag NoOptimisation)
| str == "1" -> ParseOk [] (Flag NormalOptimisation)
| str == "2" -> ParseOk [] (Flag MaximumOptimisation)
| lstr == "false" -> ParseOk [caseWarning] (Flag NoOptimisation)
| lstr == "true" -> ParseOk [caseWarning] (Flag NormalOptimisation)
| otherwise -> ParseFailed (NoParse name line)
where
lstr = lowercase str
caseWarning = PWarning $
"The '" ++ name ++ "' field is case sensitive, use 'True' or 'False'.")
,liftField configDebugInfo (\v flags -> flags { configDebugInfo = v }) $
let name = "debug-info" in
FieldDescr name
(\f -> case f of
Flag NoDebugInfo -> Disp.text "False"
Flag MinimalDebugInfo -> Disp.text "1"
Flag NormalDebugInfo -> Disp.text "True"
Flag MaximalDebugInfo -> Disp.text "3"
_ -> Disp.empty)
(\line str _ -> case () of
_ | str == "False" -> ParseOk [] (Flag NoDebugInfo)
| str == "True" -> ParseOk [] (Flag NormalDebugInfo)
| str == "0" -> ParseOk [] (Flag NoDebugInfo)
| str == "1" -> ParseOk [] (Flag MinimalDebugInfo)
| str == "2" -> ParseOk [] (Flag NormalDebugInfo)
| str == "3" -> ParseOk [] (Flag MaximalDebugInfo)
| lstr == "false" -> ParseOk [caseWarning] (Flag NoDebugInfo)
| lstr == "true" -> ParseOk [caseWarning] (Flag NormalDebugInfo)
| otherwise -> ParseFailed (NoParse name line)
where
lstr = lowercase str
caseWarning = PWarning $
"The '" ++ name ++ "' field is case sensitive, use 'True' or 'False'.")
]
++ toSavedConfig liftConfigExFlag
(configureExOptions ParseArgs)
[] []
++ toSavedConfig liftInstallFlag
(installOptions ParseArgs)
["dry-run", "only", "only-dependencies", "dependencies-only"] []
++ toSavedConfig liftUploadFlag
(commandOptions uploadCommand ParseArgs)
["verbose", "check"] []
++ toSavedConfig liftReportFlag
(commandOptions reportCommand ParseArgs)
["verbose", "username", "password"] []
--FIXME: this is a hack, hiding the user name and password.
-- But otherwise it masks the upload ones. Either need to
-- share the options or make then distinct. In any case
-- they should probably be per-server.
where
toSavedConfig lift options exclusions replacements =
[ lift (fromMaybe field replacement)
| opt <- options
, let field = viewAsFieldDescr opt
name = fieldName field
replacement = find ((== name) . fieldName) replacements
, name `notElem` exclusions ]
optional = Parse.option mempty . fmap toFlag
-- TODO: next step, make the deprecated fields elicit a warning.
--
deprecatedFieldDescriptions :: [FieldDescr SavedConfig]
deprecatedFieldDescriptions =
[ liftGlobalFlag $
listField "repos"
(Disp.text . showRepo) parseRepo
(fromNubList . globalRemoteRepos)
(\rs cfg -> cfg { globalRemoteRepos = toNubList rs })
, liftGlobalFlag $
simpleField "cachedir"
(Disp.text . fromFlagOrDefault "") (optional parseFilePathQ)
globalCacheDir (\d cfg -> cfg { globalCacheDir = d })
, liftUploadFlag $
simpleField "hackage-username"
(Disp.text . fromFlagOrDefault "" . fmap unUsername)
(optional (fmap Username parseTokenQ))
uploadUsername (\d cfg -> cfg { uploadUsername = d })
, liftUploadFlag $
simpleField "hackage-password"
(Disp.text . fromFlagOrDefault "" . fmap unPassword)
(optional (fmap Password parseTokenQ))
uploadPassword (\d cfg -> cfg { uploadPassword = d })
]
++ map (modifyFieldName ("user-"++) . liftUserInstallDirs) installDirsFields
++ map (modifyFieldName ("global-"++) . liftGlobalInstallDirs) installDirsFields
where
optional = Parse.option mempty . fmap toFlag
modifyFieldName :: (String -> String) -> FieldDescr a -> FieldDescr a
modifyFieldName f d = d { fieldName = f (fieldName d) }
liftUserInstallDirs :: FieldDescr (InstallDirs (Flag PathTemplate))
-> FieldDescr SavedConfig
liftUserInstallDirs = liftField
savedUserInstallDirs (\flags conf -> conf { savedUserInstallDirs = flags })
liftGlobalInstallDirs :: FieldDescr (InstallDirs (Flag PathTemplate))
-> FieldDescr SavedConfig
liftGlobalInstallDirs = liftField
savedGlobalInstallDirs (\flags conf -> conf { savedGlobalInstallDirs = flags })
liftGlobalFlag :: FieldDescr GlobalFlags -> FieldDescr SavedConfig
liftGlobalFlag = liftField
savedGlobalFlags (\flags conf -> conf { savedGlobalFlags = flags })
liftConfigFlag :: FieldDescr ConfigFlags -> FieldDescr SavedConfig
liftConfigFlag = liftField
savedConfigureFlags (\flags conf -> conf { savedConfigureFlags = flags })
liftConfigExFlag :: FieldDescr ConfigExFlags -> FieldDescr SavedConfig
liftConfigExFlag = liftField
savedConfigureExFlags (\flags conf -> conf { savedConfigureExFlags = flags })
liftInstallFlag :: FieldDescr InstallFlags -> FieldDescr SavedConfig
liftInstallFlag = liftField
savedInstallFlags (\flags conf -> conf { savedInstallFlags = flags })
liftUploadFlag :: FieldDescr UploadFlags -> FieldDescr SavedConfig
liftUploadFlag = liftField
savedUploadFlags (\flags conf -> conf { savedUploadFlags = flags })
liftReportFlag :: FieldDescr ReportFlags -> FieldDescr SavedConfig
liftReportFlag = liftField
savedReportFlags (\flags conf -> conf { savedReportFlags = flags })
parseConfig :: SavedConfig -> String -> ParseResult SavedConfig
parseConfig initial = \str -> do
fields <- readFields str
let (knownSections, others) = partition isKnownSection fields
config <- parse others
let user0 = savedUserInstallDirs config
global0 = savedGlobalInstallDirs config
(haddockFlags, user, global, paths, args) <-
foldM parseSections
(savedHaddockFlags config, user0, global0, [], [])
knownSections
return config {
savedConfigureFlags = (savedConfigureFlags config) {
configProgramPaths = paths,
configProgramArgs = args
},
savedHaddockFlags = haddockFlags,
savedUserInstallDirs = user,
savedGlobalInstallDirs = global
}
where
isKnownSection (ParseUtils.Section _ "haddock" _ _) = True
isKnownSection (ParseUtils.Section _ "install-dirs" _ _) = True
isKnownSection (ParseUtils.Section _ "program-locations" _ _) = True
isKnownSection (ParseUtils.Section _ "program-default-options" _ _) = True
isKnownSection _ = False
parse = parseFields (configFieldDescriptions
++ deprecatedFieldDescriptions) initial
parseSections accum@(h,u,g,p,a)
(ParseUtils.Section _ "haddock" name fs)
| name == "" = do h' <- parseFields haddockFlagsFields h fs
return (h', u, g, p, a)
| otherwise = do
warning "The 'haddock' section should be unnamed"
return accum
parseSections accum@(h,u,g,p,a)
(ParseUtils.Section _ "install-dirs" name fs)
| name' == "user" = do u' <- parseFields installDirsFields u fs
return (h, u', g, p, a)
| name' == "global" = do g' <- parseFields installDirsFields g fs
return (h, u, g', p, a)
| otherwise = do
warning "The 'install-paths' section should be for 'user' or 'global'"
return accum
where name' = lowercase name
parseSections accum@(h,u,g,p,a)
(ParseUtils.Section _ "program-locations" name fs)
| name == "" = do p' <- parseFields withProgramsFields p fs
return (h, u, g, p', a)
| otherwise = do
warning "The 'program-locations' section should be unnamed"
return accum
parseSections accum@(h, u, g, p, a)
(ParseUtils.Section _ "program-default-options" name fs)
| name == "" = do a' <- parseFields withProgramOptionsFields a fs
return (h, u, g, p, a')
| otherwise = do
warning "The 'program-default-options' section should be unnamed"
return accum
parseSections accum f = do
warning $ "Unrecognized stanza on line " ++ show (lineNo f)
return accum
showConfig :: SavedConfig -> String
showConfig = showConfigWithComments mempty
showConfigWithComments :: SavedConfig -> SavedConfig -> String
showConfigWithComments comment vals = Disp.render $
ppFields configFieldDescriptions mcomment vals
$+$ Disp.text ""
$+$ ppSection "haddock" "" haddockFlagsFields
(fmap savedHaddockFlags mcomment) (savedHaddockFlags vals)
$+$ Disp.text ""
$+$ installDirsSection "user" savedUserInstallDirs
$+$ Disp.text ""
$+$ installDirsSection "global" savedGlobalInstallDirs
$+$ Disp.text ""
$+$ configFlagsSection "program-locations" withProgramsFields
configProgramPaths
$+$ Disp.text ""
$+$ configFlagsSection "program-default-options" withProgramOptionsFields
configProgramArgs
where
mcomment = Just comment
installDirsSection name field =
ppSection "install-dirs" name installDirsFields
(fmap field mcomment) (field vals)
configFlagsSection name fields field =
ppSection name "" fields
(fmap (field . savedConfigureFlags) mcomment)
((field . savedConfigureFlags) vals)
-- | Fields for the 'install-dirs' sections.
installDirsFields :: [FieldDescr (InstallDirs (Flag PathTemplate))]
installDirsFields = map viewAsFieldDescr installDirsOptions
-- | Fields for the 'haddock' section.
haddockFlagsFields :: [FieldDescr HaddockFlags]
haddockFlagsFields = [ field
| opt <- haddockOptions ParseArgs
, let field = viewAsFieldDescr opt
name = fieldName field
, name `notElem` exclusions ]
where
exclusions = ["verbose", "builddir"]
-- | Fields for the 'program-locations' section.
withProgramsFields :: [FieldDescr [(String, FilePath)]]
withProgramsFields =
map viewAsFieldDescr $
programConfigurationPaths' (++ "-location") defaultProgramConfiguration
ParseArgs id (++)
-- | Fields for the 'program-default-options' section.
withProgramOptionsFields :: [FieldDescr [(String, [String])]]
withProgramOptionsFields =
map viewAsFieldDescr $
programConfigurationOptions defaultProgramConfiguration ParseArgs id (++)
-- | Get the differences (as a pseudo code diff) between the user's
-- '~/.cabal/config' and the one that cabal would generate if it didn't exist.
userConfigDiff :: GlobalFlags -> IO [String]
userConfigDiff globalFlags = do
userConfig <- loadConfig normal (globalConfigFile globalFlags) mempty
testConfig <- liftM2 mappend baseSavedConfig initialSavedConfig
return $ reverse . foldl' createDiff [] . M.toList
$ M.unionWith combine
(M.fromList . map justFst $ filterShow testConfig)
(M.fromList . map justSnd $ filterShow userConfig)
where
justFst (a, b) = (a, (Just b, Nothing))
justSnd (a, b) = (a, (Nothing, Just b))
combine (Nothing, Just b) (Just a, Nothing) = (Just a, Just b)
combine (Just a, Nothing) (Nothing, Just b) = (Just a, Just b)
combine x y = error $ "Can't happen : userConfigDiff " ++ show x ++ " " ++ show y
createDiff :: [String] -> (String, (Maybe String, Maybe String)) -> [String]
createDiff acc (key, (Just a, Just b))
| a == b = acc
| otherwise = ("+ " ++ key ++ ": " ++ b) : ("- " ++ key ++ ": " ++ a) : acc
createDiff acc (key, (Nothing, Just b)) = ("+ " ++ key ++ ": " ++ b) : acc
createDiff acc (key, (Just a, Nothing)) = ("- " ++ key ++ ": " ++ a) : acc
createDiff acc (_, (Nothing, Nothing)) = acc
filterShow :: SavedConfig -> [(String, String)]
filterShow cfg = map keyValueSplit
. filter (\s -> not (null s) && any (== ':') s)
. map nonComment
. lines
$ showConfig cfg
nonComment [] = []
nonComment ('-':'-':_) = []
nonComment (x:xs) = x : nonComment xs
topAndTail = reverse . dropWhile isSpace . reverse . dropWhile isSpace
keyValueSplit s =
let (left, right) = break (== ':') s
in (topAndTail left, topAndTail (drop 1 right))
-- | Update the user's ~/.cabal/config' keeping the user's customizations.
userConfigUpdate :: Verbosity -> GlobalFlags -> IO ()
userConfigUpdate verbosity globalFlags = do
userConfig <- loadConfig normal (globalConfigFile globalFlags) mempty
newConfig <- liftM2 mappend baseSavedConfig initialSavedConfig
commentConf <- commentSavedConfig
cabalFile <- defaultConfigFile
let backup = cabalFile ++ ".backup"
notice verbosity $ "Renaming " ++ cabalFile ++ " to " ++ backup ++ "."
renameFile cabalFile backup
notice verbosity $ "Writing merged config to " ++ cabalFile ++ "."
writeConfigFile cabalFile commentConf (newConfig `mappend` userConfig)
| typelead/epm | epm/Distribution/Client/Config.hs | bsd-3-clause | 39,196 | 83 | 28 | 10,555 | 7,840 | 4,262 | 3,578 | 712 | 9 |
-----------------------------------------------------------------------------
--
-- Stg to C-- code generation: bindings
--
-- (c) The University of Glasgow 2004-2006
--
-----------------------------------------------------------------------------
module GHC.StgToCmm.Bind (
cgTopRhsClosure,
cgBind,
emitBlackHoleCode,
pushUpdateFrame, emitUpdateFrame
) where
import GhcPrelude hiding ((<*>))
import GHC.StgToCmm.Expr
import GHC.StgToCmm.Monad
import GHC.StgToCmm.Env
import GHC.StgToCmm.DataCon
import GHC.StgToCmm.Heap
import GHC.StgToCmm.Prof (ldvEnterClosure, enterCostCentreFun, enterCostCentreThunk,
initUpdFrameProf)
import GHC.StgToCmm.Ticky
import GHC.StgToCmm.Layout
import GHC.StgToCmm.Utils
import GHC.StgToCmm.Closure
import GHC.StgToCmm.Foreign (emitPrimCall)
import GHC.Cmm.Graph
import CoreSyn ( AltCon(..), tickishIsCode )
import GHC.Cmm.BlockId
import GHC.Runtime.Layout
import GHC.Cmm
import GHC.Cmm.Info
import GHC.Cmm.Utils
import GHC.Cmm.CLabel
import GHC.Stg.Syntax
import CostCentre
import Id
import IdInfo
import Name
import Module
import ListSetOps
import Util
import VarSet
import BasicTypes
import Outputable
import FastString
import DynFlags
import Control.Monad
------------------------------------------------------------------------
-- Top-level bindings
------------------------------------------------------------------------
-- For closures bound at top level, allocate in static space.
-- They should have no free variables.
cgTopRhsClosure :: DynFlags
-> RecFlag -- member of a recursive group?
-> Id
-> CostCentreStack -- Optional cost centre annotation
-> UpdateFlag
-> [Id] -- Args
-> CgStgExpr
-> (CgIdInfo, FCode ())
cgTopRhsClosure dflags rec id ccs upd_flag args body =
let closure_label = mkLocalClosureLabel (idName id) (idCafInfo id)
cg_id_info = litIdInfo dflags id lf_info (CmmLabel closure_label)
lf_info = mkClosureLFInfo dflags id TopLevel [] upd_flag args
in (cg_id_info, gen_code dflags lf_info closure_label)
where
-- special case for a indirection (f = g). We create an IND_STATIC
-- closure pointing directly to the indirectee. This is exactly
-- what the CAF will eventually evaluate to anyway, we're just
-- shortcutting the whole process, and generating a lot less code
-- (#7308). Eventually the IND_STATIC closure will be eliminated
-- by assembly '.equiv' directives, where possible (#15155).
-- See note [emit-time elimination of static indirections] in CLabel.
--
-- Note: we omit the optimisation when this binding is part of a
-- recursive group, because the optimisation would inhibit the black
-- hole detection from working in that case. Test
-- concurrent/should_run/4030 fails, for instance.
--
gen_code _ _ closure_label
| StgApp f [] <- body, null args, isNonRec rec
= do
cg_info <- getCgIdInfo f
emitDataCon closure_label indStaticInfoTable ccs [unLit (idInfoToAmode cg_info)]
gen_code dflags lf_info _closure_label
= do { let name = idName id
; mod_name <- getModuleName
; let descr = closureDescription dflags mod_name name
closure_info = mkClosureInfo dflags True id lf_info 0 0 descr
-- We don't generate the static closure here, because we might
-- want to add references to static closures to it later. The
-- static closure is generated by GHC.Cmm.Info.Build.updInfoSRTs,
-- See Note [SRTs], specifically the [FUN] optimisation.
; let fv_details :: [(NonVoid Id, ByteOff)]
header = if isLFThunk lf_info then ThunkHeader else StdHeader
(_, _, fv_details) = mkVirtHeapOffsets dflags header []
-- Don't drop the non-void args until the closure info has been made
; forkClosureBody (closureCodeBody True id closure_info ccs
(nonVoidIds args) (length args) body fv_details)
; return () }
unLit (CmmLit l) = l
unLit _ = panic "unLit"
------------------------------------------------------------------------
-- Non-top-level bindings
------------------------------------------------------------------------
cgBind :: CgStgBinding -> FCode ()
cgBind (StgNonRec name rhs)
= do { (info, fcode) <- cgRhs name rhs
; addBindC info
; init <- fcode
; emit init }
-- init cannot be used in body, so slightly better to sink it eagerly
cgBind (StgRec pairs)
= do { r <- sequence $ unzipWith cgRhs pairs
; let (id_infos, fcodes) = unzip r
; addBindsC id_infos
; (inits, body) <- getCodeR $ sequence fcodes
; emit (catAGraphs inits <*> body) }
{- Note [cgBind rec]
Recursive let-bindings are tricky.
Consider the following pseudocode:
let x = \_ -> ... y ...
y = \_ -> ... z ...
z = \_ -> ... x ...
in ...
For each binding, we need to allocate a closure, and each closure must
capture the address of the other closures.
We want to generate the following C-- code:
// Initialization Code
x = hp - 24; // heap address of x's closure
y = hp - 40; // heap address of x's closure
z = hp - 64; // heap address of x's closure
// allocate and initialize x
m[hp-8] = ...
m[hp-16] = y // the closure for x captures y
m[hp-24] = x_info;
// allocate and initialize y
m[hp-32] = z; // the closure for y captures z
m[hp-40] = y_info;
// allocate and initialize z
...
For each closure, we must generate not only the code to allocate and
initialize the closure itself, but also some initialization Code that
sets a variable holding the closure pointer.
We could generate a pair of the (init code, body code), but since
the bindings are recursive we also have to initialise the
environment with the CgIdInfo for all the bindings before compiling
anything. So we do this in 3 stages:
1. collect all the CgIdInfos and initialise the environment
2. compile each binding into (init, body) code
3. emit all the inits, and then all the bodies
We'd rather not have separate functions to do steps 1 and 2 for
each binding, since in practice they share a lot of code. So we
have just one function, cgRhs, that returns a pair of the CgIdInfo
for step 1, and a monadic computation to generate the code in step
2.
The alternative to separating things in this way is to use a
fixpoint. That's what we used to do, but it introduces a
maintenance nightmare because there is a subtle dependency on not
being too strict everywhere. Doing things this way means that the
FCode monad can be strict, for example.
-}
cgRhs :: Id
-> CgStgRhs
-> FCode (
CgIdInfo -- The info for this binding
, FCode CmmAGraph -- A computation which will generate the
-- code for the binding, and return an
-- assignment of the form "x = Hp - n"
-- (see above)
)
cgRhs id (StgRhsCon cc con args)
= withNewTickyCounterCon (idName id) $
buildDynCon id True cc con (assertNonVoidStgArgs args)
-- con args are always non-void,
-- see Note [Post-unarisation invariants] in GHC.Stg.Unarise
{- See Note [GC recovery] in compiler/GHC.StgToCmm/Closure.hs -}
cgRhs id (StgRhsClosure fvs cc upd_flag args body)
= do dflags <- getDynFlags
mkRhsClosure dflags id cc (nonVoidIds (dVarSetElems fvs)) upd_flag args body
------------------------------------------------------------------------
-- Non-constructor right hand sides
------------------------------------------------------------------------
mkRhsClosure :: DynFlags -> Id -> CostCentreStack
-> [NonVoid Id] -- Free vars
-> UpdateFlag
-> [Id] -- Args
-> CgStgExpr
-> FCode (CgIdInfo, FCode CmmAGraph)
{- mkRhsClosure looks for two special forms of the right-hand side:
a) selector thunks
b) AP thunks
If neither happens, it just calls mkClosureLFInfo. You might think
that mkClosureLFInfo should do all this, but it seems wrong for the
latter to look at the structure of an expression
Note [Selectors]
~~~~~~~~~~~~~~~~
We look at the body of the closure to see if it's a selector---turgid,
but nothing deep. We are looking for a closure of {\em exactly} the
form:
... = [the_fv] \ u [] ->
case the_fv of
con a_1 ... a_n -> a_i
Note [Ap thunks]
~~~~~~~~~~~~~~~~
A more generic AP thunk of the form
x = [ x_1...x_n ] \.. [] -> x_1 ... x_n
A set of these is compiled statically into the RTS, so we just use
those. We could extend the idea to thunks where some of the x_i are
global ids (and hence not free variables), but this would entail
generating a larger thunk. It might be an option for non-optimising
compilation, though.
We only generate an Ap thunk if all the free variables are pointers,
for semi-obvious reasons.
-}
---------- Note [Selectors] ------------------
mkRhsClosure dflags bndr _cc
[NonVoid the_fv] -- Just one free var
upd_flag -- Updatable thunk
[] -- A thunk
expr
| let strip = stripStgTicksTopE (not . tickishIsCode)
, StgCase (StgApp scrutinee [{-no args-}])
_ -- ignore bndr
(AlgAlt _)
[(DataAlt _, params, sel_expr)] <- strip expr
, StgApp selectee [{-no args-}] <- strip sel_expr
, the_fv == scrutinee -- Scrutinee is the only free variable
, let (_, _, params_w_offsets) = mkVirtConstrOffsets dflags (addIdReps (assertNonVoidIds params))
-- pattern binders are always non-void,
-- see Note [Post-unarisation invariants] in GHC.Stg.Unarise
, Just the_offset <- assocMaybe params_w_offsets (NonVoid selectee)
, let offset_into_int = bytesToWordsRoundUp dflags the_offset
- fixedHdrSizeW dflags
, offset_into_int <= mAX_SPEC_SELECTEE_SIZE dflags -- Offset is small enough
= -- NOT TRUE: ASSERT(is_single_constructor)
-- The simplifier may have statically determined that the single alternative
-- is the only possible case and eliminated the others, even if there are
-- other constructors in the datatype. It's still ok to make a selector
-- thunk in this case, because we *know* which constructor the scrutinee
-- will evaluate to.
--
-- srt is discarded; it must be empty
let lf_info = mkSelectorLFInfo bndr offset_into_int (isUpdatable upd_flag)
in cgRhsStdThunk bndr lf_info [StgVarArg the_fv]
---------- Note [Ap thunks] ------------------
mkRhsClosure dflags bndr _cc
fvs
upd_flag
[] -- No args; a thunk
(StgApp fun_id args)
-- We are looking for an "ApThunk"; see data con ApThunk in GHC.StgToCmm.Closure
-- of form (x1 x2 .... xn), where all the xi are locals (not top-level)
-- So the xi will all be free variables
| args `lengthIs` (n_fvs-1) -- This happens only if the fun_id and
-- args are all distinct local variables
-- The "-1" is for fun_id
-- Missed opportunity: (f x x) is not detected
, all (isGcPtrRep . idPrimRep . fromNonVoid) fvs
, isUpdatable upd_flag
, n_fvs <= mAX_SPEC_AP_SIZE dflags
, not (gopt Opt_SccProfilingOn dflags)
-- not when profiling: we don't want to
-- lose information about this particular
-- thunk (e.g. its type) (#949)
, idArity fun_id == unknownArity -- don't spoil a known call
-- Ha! an Ap thunk
= cgRhsStdThunk bndr lf_info payload
where
n_fvs = length fvs
lf_info = mkApLFInfo bndr upd_flag n_fvs
-- the payload has to be in the correct order, hence we can't
-- just use the fvs.
payload = StgVarArg fun_id : args
---------- Default case ------------------
mkRhsClosure dflags bndr cc fvs upd_flag args body
= do { let lf_info = mkClosureLFInfo dflags bndr NotTopLevel fvs upd_flag args
; (id_info, reg) <- rhsIdInfo bndr lf_info
; return (id_info, gen_code lf_info reg) }
where
gen_code lf_info reg
= do { -- LAY OUT THE OBJECT
-- If the binder is itself a free variable, then don't store
-- it in the closure. Instead, just bind it to Node on entry.
-- NB we can be sure that Node will point to it, because we
-- haven't told mkClosureLFInfo about this; so if the binder
-- _was_ a free var of its RHS, mkClosureLFInfo thinks it *is*
-- stored in the closure itself, so it will make sure that
-- Node points to it...
; let reduced_fvs = filter (NonVoid bndr /=) fvs
-- MAKE CLOSURE INFO FOR THIS CLOSURE
; mod_name <- getModuleName
; dflags <- getDynFlags
; let name = idName bndr
descr = closureDescription dflags mod_name name
fv_details :: [(NonVoid Id, ByteOff)]
header = if isLFThunk lf_info then ThunkHeader else StdHeader
(tot_wds, ptr_wds, fv_details)
= mkVirtHeapOffsets dflags header (addIdReps reduced_fvs)
closure_info = mkClosureInfo dflags False -- Not static
bndr lf_info tot_wds ptr_wds
descr
-- BUILD ITS INFO TABLE AND CODE
; forkClosureBody $
-- forkClosureBody: (a) ensure that bindings in here are not seen elsewhere
-- (b) ignore Sequel from context; use empty Sequel
-- And compile the body
closureCodeBody False bndr closure_info cc (nonVoidIds args)
(length args) body fv_details
-- BUILD THE OBJECT
-- ; (use_cc, blame_cc) <- chooseDynCostCentres cc args body
; let use_cc = cccsExpr; blame_cc = cccsExpr
; emit (mkComment $ mkFastString "calling allocDynClosure")
; let toVarArg (NonVoid a, off) = (NonVoid (StgVarArg a), off)
; let info_tbl = mkCmmInfo closure_info bndr currentCCS
; hp_plus_n <- allocDynClosure (Just bndr) info_tbl lf_info use_cc blame_cc
(map toVarArg fv_details)
-- RETURN
; return (mkRhsInit dflags reg lf_info hp_plus_n) }
-------------------------
cgRhsStdThunk
:: Id
-> LambdaFormInfo
-> [StgArg] -- payload
-> FCode (CgIdInfo, FCode CmmAGraph)
cgRhsStdThunk bndr lf_info payload
= do { (id_info, reg) <- rhsIdInfo bndr lf_info
; return (id_info, gen_code reg)
}
where
gen_code reg -- AHA! A STANDARD-FORM THUNK
= withNewTickyCounterStdThunk (lfUpdatable lf_info) (idName bndr) $
do
{ -- LAY OUT THE OBJECT
mod_name <- getModuleName
; dflags <- getDynFlags
; let header = if isLFThunk lf_info then ThunkHeader else StdHeader
(tot_wds, ptr_wds, payload_w_offsets)
= mkVirtHeapOffsets dflags header
(addArgReps (nonVoidStgArgs payload))
descr = closureDescription dflags mod_name (idName bndr)
closure_info = mkClosureInfo dflags False -- Not static
bndr lf_info tot_wds ptr_wds
descr
-- ; (use_cc, blame_cc) <- chooseDynCostCentres cc [{- no args-}] body
; let use_cc = cccsExpr; blame_cc = cccsExpr
-- BUILD THE OBJECT
; let info_tbl = mkCmmInfo closure_info bndr currentCCS
; hp_plus_n <- allocDynClosure (Just bndr) info_tbl lf_info
use_cc blame_cc payload_w_offsets
-- RETURN
; return (mkRhsInit dflags reg lf_info hp_plus_n) }
mkClosureLFInfo :: DynFlags
-> Id -- The binder
-> TopLevelFlag -- True of top level
-> [NonVoid Id] -- Free vars
-> UpdateFlag -- Update flag
-> [Id] -- Args
-> LambdaFormInfo
mkClosureLFInfo dflags bndr top fvs upd_flag args
| null args =
mkLFThunk (idType bndr) top (map fromNonVoid fvs) upd_flag
| otherwise =
mkLFReEntrant top (map fromNonVoid fvs) args (mkArgDescr dflags args)
------------------------------------------------------------------------
-- The code for closures
------------------------------------------------------------------------
closureCodeBody :: Bool -- whether this is a top-level binding
-> Id -- the closure's name
-> ClosureInfo -- Lots of information about this closure
-> CostCentreStack -- Optional cost centre attached to closure
-> [NonVoid Id] -- incoming args to the closure
-> Int -- arity, including void args
-> CgStgExpr
-> [(NonVoid Id, ByteOff)] -- the closure's free vars
-> FCode ()
{- There are two main cases for the code for closures.
* If there are *no arguments*, then the closure is a thunk, and not in
normal form. So it should set up an update frame (if it is
shared). NB: Thunks cannot have a primitive type!
* If there is *at least one* argument, then this closure is in
normal form, so there is no need to set up an update frame.
-}
closureCodeBody top_lvl bndr cl_info cc _args arity body fv_details
| arity == 0 -- No args i.e. thunk
= withNewTickyCounterThunk
(isStaticClosure cl_info)
(closureUpdReqd cl_info)
(closureName cl_info) $
emitClosureProcAndInfoTable top_lvl bndr lf_info info_tbl [] $
\(_, node, _) -> thunkCode cl_info fv_details cc node arity body
where
lf_info = closureLFInfo cl_info
info_tbl = mkCmmInfo cl_info bndr cc
closureCodeBody top_lvl bndr cl_info cc args arity body fv_details
= -- Note: args may be [], if all args are Void
withNewTickyCounterFun
(closureSingleEntry cl_info)
(closureName cl_info)
args $ do {
; let
lf_info = closureLFInfo cl_info
info_tbl = mkCmmInfo cl_info bndr cc
-- Emit the main entry code
; emitClosureProcAndInfoTable top_lvl bndr lf_info info_tbl args $
\(_offset, node, arg_regs) -> do
-- Emit slow-entry code (for entering a closure through a PAP)
{ mkSlowEntryCode bndr cl_info arg_regs
; dflags <- getDynFlags
; let node_points = nodeMustPointToIt dflags lf_info
node' = if node_points then Just node else Nothing
; loop_header_id <- newBlockId
-- Extend reader monad with information that
-- self-recursive tail calls can be optimized into local
-- jumps. See Note [Self-recursive tail calls] in GHC.StgToCmm.Expr.
; withSelfLoop (bndr, loop_header_id, arg_regs) $ do
{
-- Main payload
; entryHeapCheck cl_info node' arity arg_regs $ do
{ -- emit LDV code when profiling
when node_points (ldvEnterClosure cl_info (CmmLocal node))
-- ticky after heap check to avoid double counting
; tickyEnterFun cl_info
; enterCostCentreFun cc
(CmmMachOp (mo_wordSub dflags)
[ CmmReg (CmmLocal node) -- See [NodeReg clobbered with loopification]
, mkIntExpr dflags (funTag dflags cl_info) ])
; fv_bindings <- mapM bind_fv fv_details
-- Load free vars out of closure *after*
-- heap check, to reduce live vars over check
; when node_points $ load_fvs node lf_info fv_bindings
; void $ cgExpr body
}}}
}
-- Note [NodeReg clobbered with loopification]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--
-- Previously we used to pass nodeReg (aka R1) here. With profiling, upon
-- entering a closure, enterFunCCS was called with R1 passed to it. But since R1
-- may get clobbered inside the body of a closure, and since a self-recursive
-- tail call does not restore R1, a subsequent call to enterFunCCS received a
-- possibly bogus value from R1. The solution is to not pass nodeReg (aka R1) to
-- enterFunCCS. Instead, we pass node, the callee-saved temporary that stores
-- the original value of R1. This way R1 may get modified but loopification will
-- not care.
-- A function closure pointer may be tagged, so we
-- must take it into account when accessing the free variables.
bind_fv :: (NonVoid Id, ByteOff) -> FCode (LocalReg, ByteOff)
bind_fv (id, off) = do { reg <- rebindToReg id; return (reg, off) }
load_fvs :: LocalReg -> LambdaFormInfo -> [(LocalReg, ByteOff)] -> FCode ()
load_fvs node lf_info = mapM_ (\ (reg, off) ->
do dflags <- getDynFlags
let tag = lfDynTag dflags lf_info
emit $ mkTaggedObjectLoad dflags reg node off tag)
-----------------------------------------
-- The "slow entry" code for a function. This entry point takes its
-- arguments on the stack. It loads the arguments into registers
-- according to the calling convention, and jumps to the function's
-- normal entry point. The function's closure is assumed to be in
-- R1/node.
--
-- The slow entry point is used for unknown calls: eg. stg_PAP_entry
mkSlowEntryCode :: Id -> ClosureInfo -> [LocalReg] -> FCode ()
-- If this function doesn't have a specialised ArgDescr, we need
-- to generate the function's arg bitmap and slow-entry code.
-- Here, we emit the slow-entry code.
mkSlowEntryCode bndr cl_info arg_regs -- function closure is already in `Node'
| Just (_, ArgGen _) <- closureFunInfo cl_info
= do dflags <- getDynFlags
let node = idToReg dflags (NonVoid bndr)
slow_lbl = closureSlowEntryLabel cl_info
fast_lbl = closureLocalEntryLabel dflags cl_info
-- mkDirectJump does not clobber `Node' containing function closure
jump = mkJump dflags NativeNodeCall
(mkLblExpr fast_lbl)
(map (CmmReg . CmmLocal) (node : arg_regs))
(initUpdFrameOff dflags)
tscope <- getTickScope
emitProcWithConvention Slow Nothing slow_lbl
(node : arg_regs) (jump, tscope)
| otherwise = return ()
-----------------------------------------
thunkCode :: ClosureInfo -> [(NonVoid Id, ByteOff)] -> CostCentreStack
-> LocalReg -> Int -> CgStgExpr -> FCode ()
thunkCode cl_info fv_details _cc node arity body
= do { dflags <- getDynFlags
; let node_points = nodeMustPointToIt dflags (closureLFInfo cl_info)
node' = if node_points then Just node else Nothing
; ldvEnterClosure cl_info (CmmLocal node) -- NB: Node always points when profiling
-- Heap overflow check
; entryHeapCheck cl_info node' arity [] $ do
{ -- Overwrite with black hole if necessary
-- but *after* the heap-overflow check
; tickyEnterThunk cl_info
; when (blackHoleOnEntry cl_info && node_points)
(blackHoleIt node)
-- Push update frame
; setupUpdate cl_info node $
-- We only enter cc after setting up update so
-- that cc of enclosing scope will be recorded
-- in update frame CAF/DICT functions will be
-- subsumed by this enclosing cc
do { enterCostCentreThunk (CmmReg nodeReg)
; let lf_info = closureLFInfo cl_info
; fv_bindings <- mapM bind_fv fv_details
; load_fvs node lf_info fv_bindings
; void $ cgExpr body }}}
------------------------------------------------------------------------
-- Update and black-hole wrappers
------------------------------------------------------------------------
blackHoleIt :: LocalReg -> FCode ()
-- Only called for closures with no args
-- Node points to the closure
blackHoleIt node_reg
= emitBlackHoleCode (CmmReg (CmmLocal node_reg))
emitBlackHoleCode :: CmmExpr -> FCode ()
emitBlackHoleCode node = do
dflags <- getDynFlags
-- Eager blackholing is normally disabled, but can be turned on with
-- -feager-blackholing. When it is on, we replace the info pointer
-- of the thunk with stg_EAGER_BLACKHOLE_info on entry.
-- If we wanted to do eager blackholing with slop filling, we'd need
-- to do it at the *end* of a basic block, otherwise we overwrite
-- the free variables in the thunk that we still need. We have a
-- patch for this from Andy Cheadle, but not incorporated yet. --SDM
-- [6/2004]
--
-- Previously, eager blackholing was enabled when ticky-ticky was
-- on. But it didn't work, and it wasn't strictly necessary to bring
-- back minimal ticky-ticky, so now EAGER_BLACKHOLING is
-- unconditionally disabled. -- krc 1/2007
-- Note the eager-blackholing check is here rather than in blackHoleOnEntry,
-- because emitBlackHoleCode is called from GHC.Cmm.Parser.
let eager_blackholing = not (gopt Opt_SccProfilingOn dflags)
&& gopt Opt_EagerBlackHoling dflags
-- Profiling needs slop filling (to support LDV
-- profiling), so currently eager blackholing doesn't
-- work with profiling.
when eager_blackholing $ do
whenUpdRemSetEnabled dflags $ emitUpdRemSetPushThunk node
emitStore (cmmOffsetW dflags node (fixedHdrSizeW dflags)) currentTSOExpr
-- See Note [Heap memory barriers] in SMP.h.
emitPrimCall [] MO_WriteBarrier []
emitStore node (CmmReg (CmmGlobal EagerBlackholeInfo))
setupUpdate :: ClosureInfo -> LocalReg -> FCode () -> FCode ()
-- Nota Bene: this function does not change Node (even if it's a CAF),
-- so that the cost centre in the original closure can still be
-- extracted by a subsequent enterCostCentre
setupUpdate closure_info node body
| not (lfUpdatable (closureLFInfo closure_info))
= body
| not (isStaticClosure closure_info)
= if not (closureUpdReqd closure_info)
then do tickyUpdateFrameOmitted; body
else do
tickyPushUpdateFrame
dflags <- getDynFlags
let
bh = blackHoleOnEntry closure_info &&
not (gopt Opt_SccProfilingOn dflags) &&
gopt Opt_EagerBlackHoling dflags
lbl | bh = mkBHUpdInfoLabel
| otherwise = mkUpdInfoLabel
pushUpdateFrame lbl (CmmReg (CmmLocal node)) body
| otherwise -- A static closure
= do { tickyUpdateBhCaf closure_info
; if closureUpdReqd closure_info
then do -- Blackhole the (updatable) CAF:
{ upd_closure <- link_caf node
; pushUpdateFrame mkBHUpdInfoLabel upd_closure body }
else do {tickyUpdateFrameOmitted; body}
}
-----------------------------------------------------------------------------
-- Setting up update frames
-- Push the update frame on the stack in the Entry area,
-- leaving room for the return address that is already
-- at the old end of the area.
--
pushUpdateFrame :: CLabel -> CmmExpr -> FCode () -> FCode ()
pushUpdateFrame lbl updatee body
= do
updfr <- getUpdFrameOff
dflags <- getDynFlags
let
hdr = fixedHdrSize dflags
frame = updfr + hdr + sIZEOF_StgUpdateFrame_NoHdr dflags
--
emitUpdateFrame dflags (CmmStackSlot Old frame) lbl updatee
withUpdFrameOff frame body
emitUpdateFrame :: DynFlags -> CmmExpr -> CLabel -> CmmExpr -> FCode ()
emitUpdateFrame dflags frame lbl updatee = do
let
hdr = fixedHdrSize dflags
off_updatee = hdr + oFFSET_StgUpdateFrame_updatee dflags
--
emitStore frame (mkLblExpr lbl)
emitStore (cmmOffset dflags frame off_updatee) updatee
initUpdFrameProf frame
-----------------------------------------------------------------------------
-- Entering a CAF
--
-- See Note [CAF management] in rts/sm/Storage.c
link_caf :: LocalReg -- pointer to the closure
-> FCode CmmExpr -- Returns amode for closure to be updated
-- This function returns the address of the black hole, so it can be
-- updated with the new value when available.
link_caf node = do
{ dflags <- getDynFlags
-- Call the RTS function newCAF, returning the newly-allocated
-- blackhole indirection closure
; let newCAF_lbl = mkForeignLabel (fsLit "newCAF") Nothing
ForeignLabelInExternalPackage IsFunction
; bh <- newTemp (bWord dflags)
; emitRtsCallGen [(bh,AddrHint)] newCAF_lbl
[ (baseExpr, AddrHint),
(CmmReg (CmmLocal node), AddrHint) ]
False
-- see Note [atomic CAF entry] in rts/sm/Storage.c
; updfr <- getUpdFrameOff
; let target = entryCode dflags (closureInfoPtr dflags (CmmReg (CmmLocal node)))
; emit =<< mkCmmIfThen
(cmmEqWord dflags (CmmReg (CmmLocal bh)) (zeroExpr dflags))
-- re-enter the CAF
(mkJump dflags NativeNodeCall target [] updfr)
; return (CmmReg (CmmLocal bh)) }
------------------------------------------------------------------------
-- Profiling
------------------------------------------------------------------------
-- For "global" data constructors the description is simply occurrence
-- name of the data constructor itself. Otherwise it is determined by
-- @closureDescription@ from the let binding information.
closureDescription :: DynFlags
-> Module -- Module
-> Name -- Id of closure binding
-> String
-- Not called for StgRhsCon which have global info tables built in
-- CgConTbls.hs with a description generated from the data constructor
closureDescription dflags mod_name name
= showSDocDump dflags (char '<' <>
(if isExternalName name
then ppr name -- ppr will include the module name prefix
else pprModule mod_name <> char '.' <> ppr name) <>
char '>')
-- showSDocDump, because we want to see the unique on the Name.
| sdiehl/ghc | compiler/GHC/StgToCmm/Bind.hs | bsd-3-clause | 30,935 | 4 | 24 | 8,840 | 4,607 | 2,427 | 2,180 | 367 | 4 |
module Distribution.Client.Dependency.Modular.IndexConversion where
import Data.List as L
import Data.Map as M
import Data.Maybe
import Prelude hiding (pi)
import qualified Distribution.Client.PackageIndex as CI
import Distribution.Client.Types
import Distribution.Compiler
import Distribution.InstalledPackageInfo as IPI
import Distribution.Package -- from Cabal
import Distribution.PackageDescription as PD -- from Cabal
import qualified Distribution.Simple.PackageIndex as SI
import Distribution.System
import Distribution.Client.Dependency.Modular.Dependency as D
import Distribution.Client.Dependency.Modular.Flag as F
import Distribution.Client.Dependency.Modular.Index
import Distribution.Client.Dependency.Modular.Package
import Distribution.Client.Dependency.Modular.Version
-- | Convert both the installed package index and the source package
-- index into one uniform solver index.
convPIs :: OS -> Arch -> CompilerId ->
SI.PackageIndex -> CI.PackageIndex SourcePackage -> Index
convPIs os arch cid iidx sidx =
mkIndex (L.concatMap (convIP iidx) (SI.allPackages iidx) ++
L.map (convSP os arch cid) (CI.allPackages sidx))
-- | Convert a Cabal installed package index to the simpler,
-- more uniform index format of the solver.
convIPI :: SI.PackageIndex -> Index
convIPI idx = mkIndex . L.concatMap (convIP idx) . SI.allPackages $ idx
-- | Convert a single installed package into the solver-specific format.
--
-- May return the empty list if the installed package is broken.
convIP :: SI.PackageIndex -> InstalledPackageInfo -> [(PN, I, PInfo)]
convIP idx ipi =
let ipid = installedPackageId ipi
i = I (pkgVersion (sourcePackageId ipi)) (Inst ipid)
pn = pkgName (sourcePackageId ipi)
in maybeToList $ do
fds <- mapM (convIPId pn idx) (IPI.depends ipi)
return (pn, i, PInfo fds M.empty [])
-- TODO: Installed packages should also store their encapsulations!
-- | Convert dependencies specified by an installed package id into
-- flagged dependencies of the solver.
--
-- May return Nothing if the package can't be found in the index. That
-- indicates that the original package having this dependency is broken
-- and should be ignored.
convIPId :: PN -> SI.PackageIndex -> InstalledPackageId -> Maybe (FlaggedDep PN)
convIPId pn' idx ipid =
case SI.lookupInstalledPackageId idx ipid of
Nothing -> Nothing
Just ipi -> let i = I (pkgVersion (sourcePackageId ipi)) (Inst ipid)
pn = pkgName (sourcePackageId ipi)
in Just (D.Simple (Dep pn (Fixed i (Goal (P pn') []))))
-- | Convert a faction source package index to the simpler,
-- more uniform index format of the solver.
convSPI :: OS -> Arch -> CompilerId ->
CI.PackageIndex SourcePackage -> Index
convSPI os arch cid = mkIndex . L.map (convSP os arch cid) . CI.allPackages
-- | Convert a single source package into the solver-specific format.
convSP :: OS -> Arch -> CompilerId -> SourcePackage -> (PN, I, PInfo)
convSP os arch cid (SourcePackage (PackageIdentifier pn pv) gpd _pl) =
let i = I pv InRepo
in (pn, i, convGPD os arch cid (PI pn i) gpd)
-- We do not use 'flattenPackageDescription' or 'finalizePackageDescription'
-- from 'Distribution.PackageDescription.Configuration' here, because we
-- want to keep the condition tree, but simplify much of the test.
-- | Convert a generic package description to a solver-specific 'PInfo'.
--
-- TODO: We currently just take all dependencies from all specified library,
-- executable and test components. This does not quite seem fair.
convGPD :: OS -> Arch -> CompilerId ->
PI PN -> GenericPackageDescription -> PInfo
convGPD os arch cid
pi@(PI _pn _i)
(GenericPackageDescription _ flags libs exes apps tests benchs) =
let
fds = flagDefaults flags
in
PInfo
(maybe [] (convCondTree os arch cid pi fds (const True) ) libs ++
concatMap (convCondTree os arch cid pi fds (const True) . snd) exes ++
concatMap (convCondTree os arch cid pi fds (const True) . snd) apps
++
concatMap (convCondTree os arch cid pi fds testEnabled . snd) tests ++
concatMap (convCondTree os arch cid pi fds benchmarkEnabled . snd) benchs)
fds
[] -- TODO: add encaps
-- | Convert flag information.
flagDefaults :: [PD.Flag] -> FlagDefaults
flagDefaults = M.fromList . L.map (\ (MkFlag fn _ b _) -> (fn, b))
-- | Convert condition trees to flagged dependencies.
convCondTree :: OS -> Arch -> CompilerId -> PI PN -> FlagDefaults ->
(a -> Bool) -> -- how to detect if a branch is active
CondTree ConfVar [Dependency] a -> FlaggedDeps PN
convCondTree os arch cid pi@(PI pn _) fds p (CondNode info ds branches)
| p info = L.map (D.Simple . convDep pn) ds -- unconditional dependencies
++ concatMap (convBranch os arch cid pi fds p) branches
| otherwise = []
-- | Branch interpreter.
--
-- Here, we try to simplify one of Cabal's condition tree branches into the
-- solver's flagged dependency format, which is weaker. Condition trees can
-- contain complex logical expression composed from flag choices and special
-- flags (such as architecture, or compiler flavour). We try to evaluate the
-- special flags and subsequently simplify to a tree that only depends on
-- simple flag choices.
convBranch :: OS -> Arch -> CompilerId ->
PI PN -> FlagDefaults ->
(a -> Bool) -> -- how to detect if a branch is active
(Condition ConfVar,
CondTree ConfVar [Dependency] a,
Maybe (CondTree ConfVar [Dependency] a)) -> FlaggedDeps PN
convBranch os arch cid@(CompilerId cf cv) pi fds p (c', t', mf') =
go c' ( convCondTree os arch cid pi fds p t')
(maybe [] (convCondTree os arch cid pi fds p) mf')
where
go :: Condition ConfVar ->
FlaggedDeps PN -> FlaggedDeps PN -> FlaggedDeps PN
go (Lit True) t _ = t
go (Lit False) _ f = f
go (CNot c) t f = go c f t
go (CAnd c d) t f = go c (go d t f) f
go (COr c d) t f = go c t (go d t f)
go (Var (Flag fn)) t f = [Flagged (FN pi fn) (fds ! fn) t f]
go (Var (OS os')) t f
| os == os' = t
| otherwise = f
go (Var (Arch arch')) t f
| arch == arch' = t
| otherwise = f
go (Var (Impl cf' cvr')) t f
| cf == cf' && checkVR cvr' cv = t
| otherwise = f
-- | Convert a Cabal dependency to a solver-specific dependency.
convDep :: PN -> Dependency -> Dep PN
convDep pn' (Dependency pn vr) = Dep pn (Constrained [(vr, Goal (P pn') [])])
-- | Convert a Cabal package identifier to a solver-specific dependency.
convPI :: PN -> PackageIdentifier -> Dep PN
convPI pn' (PackageIdentifier pn v) = Dep pn (Constrained [(eqVR v, Goal (P pn') [])])
| IreneKnapp/Faction | faction/Distribution/Client/Dependency/Modular/IndexConversion.hs | bsd-3-clause | 6,904 | 0 | 20 | 1,617 | 1,947 | 1,016 | 931 | 102 | 9 |
{-# LANGUAGE OverloadedStrings #-}
module Data.FieldML.InitialModel (initialModel, blankNamespaceContents, nsBuiltinMain, nsSpecial, nsMain, biSrcSpan, nsNatural, nsInteger, reservedIDs)
where
import qualified Data.Map as M
import Data.FieldML.Level2Structure
import qualified Data.FieldML.Level1Structure as L1
biSrcSpan :: L1.SrcSpan
biSrcSpan = L1.SrcSpan "built-in" 0 0 0 0
-- We reserve IDs 0-99 of certain counters for builtin use.
reservedIDs = 100
nsSpecial = L2NamespaceID 0 -- ^ Pseudo-namespace ID for 'symbols' not reachable by the user.
nsBuiltinMain = L2NamespaceID 1 -- ^ Namespace for builtin symbols.
nsNatural = L2NamespaceID 2 -- ^ Namespace 'N', for natural numbers.
nsInteger = L2NamespaceID 3 -- ^ Namespace 'Z', for integers.
nsBoolean = L2NamespaceID 4 -- ^ Namespace 'Boolean', for booleans.
nsMain = L2NamespaceID 5 -- ^ The top user-defined namespace.
dNatural = L2DomainID 0
dInteger = L2DomainID 1
dBoolean = L2DomainID 2
vFalse = L2ValueID 0
vTrue = L2ValueID 1
vUndefined = L2ValueID 2
-- Basic arithmetic on reals.
vRealPlus = L2ValueID 3
vRealMinus = L2ValueID 4
vRealTimes = L2ValueID 5
vRealDivide = L2ValueID 6
vRealPow = L2ValueID 7
-- Basic arithmetic on ints.
vIntPlus = L2ValueID 8
vIntMinus = L2ValueID 9
vIntTimes = L2ValueID 10
vIntDivide = L2ValueID 11
vIntPow = L2ValueID 12
vIntMod = L2ValueID 13
-- Real value symbols.
vRealExpE = L2ValueID 14
vRealPi = L2ValueID 15
vRealEulerGamma = L2ValueID 16
-- Real trigonometry.
vRealSin = L2ValueID 17
vRealCos = L2ValueID 18
vRealTan = L2ValueID 19
vRealSinh = L2ValueID 20
vRealCosh = L2ValueID 21
vRealTanh = L2ValueID 22
vRealASin = L2ValueID 23
vRealACos = L2ValueID 24
vRealATan = L2ValueID 25
vRealASinh = L2ValueID 26
vRealACosh = L2ValueID 27
vRealATanh = L2ValueID 28
-- Logic.
vAnd = L2ValueID 30
vOr = L2ValueID 31
vXor = L2ValueID 32
vNot = L2ValueID 33
-- Comparisons
vRealLess = L2ValueID 34
vRealLessEqual = L2ValueID 35
vIntLess = L2ValueID 36
vIntLessEqual = L2ValueID 37
-- Casts...
vUnsafeCastUnits = L2ValueID 40
cAllTypes = L2ClassID 0
cIsClone = L2ClassID 1
cIsSubset = L2ClassID 2
cvEquals = L2ClassValueID 0
cvAsClone = L2ClassValueID 1
cvFromClone = L2ClassValueID 2
cvUnsafeToSubset = L2ClassValueID 3
cvFromSubset = L2ClassValueID 4
dfClonedFrom = L2DomainFunctionID 0
dfSubsetFrom = L2DomainFunctionID 1
sdidATParam = L2ScopedDomainID "a" 0
sdidAny = L2ScopedDomainID "a" 1
suidAny1 = L2ScopedUnitID "u" 0
suidAny2 = L2ScopedUnitID "v" 1
blankNamespaceContents :: SrcSpan -> L2NamespaceID -> L2NamespaceContents
blankNamespaceContents ss p =
L2NamespaceContents {
l2nsSrcSpan = ss, l2nsNamespaces = M.empty,
l2nsDomains = M.empty, l2nsNamedValues = M.empty,
l2nsClassValues = M.empty, l2nsUnits = M.empty,
l2nsClasses = M.empty, l2nsDomainFunctions = M.empty,
l2nsLabels = M.empty, l2nsParent = p, l2nsNextLabel = 0
}
rdim :: L2DomainExpression
rdim = L2DomainExpressionReal biSrcSpan (L2UnitExDimensionless biSrcSpan)
initialModel = L2Model {
l2ToplevelNamespace = nsMain,
l2AllNamespaces = M.fromList [
(nsBuiltinMain,
(blankNamespaceContents biSrcSpan nsSpecial) {
l2nsNamespaces = M.fromList [("Builtin", nsBuiltinMain),
("N", nsNatural),
("Z", nsInteger),
("Boolean", nsBoolean)],
l2nsDomains = M.fromList [("N", L2DomainReference biSrcSpan dNatural),
("Z", L2DomainReference biSrcSpan dInteger),
("Boolean", L2DomainReference biSrcSpan dBoolean)],
l2nsNamedValues = M.fromList [("true", vTrue), ("false", vFalse), ("undefined", vUndefined),
("realPlus", vRealPlus), ("realMinus", vRealMinus),
("realTimes", vRealTimes), ("realDivide", vRealDivide),
("realPow", vRealPow), ("intPlus", vIntPlus),
("intMinus", vIntMinus), ("intTimes", vIntTimes),
("intDivide", vIntDivide), ("intPow", vIntPow),
("intMod", vIntMod),
("realExpE", vRealExpE), ("realPi", vRealPi),
("realEulerGamma", vRealEulerGamma), ("sin", vRealSin),
("cos", vRealCos), ("tan", vRealTan), ("sinh", vRealSinh),
("cosh", vRealCosh), ("tanh", vRealTanh), ("asin", vRealASin),
("acos", vRealACos), ("atan", vRealATan), ("asinh", vRealASinh),
("acosh", vRealACosh), ("atanh", vRealATanh),
("&&", vAnd), ("||", vOr), ("xor", vXor), ("not", vNot),
("realLess", vRealLess), ("realLessEqual", vRealLessEqual),
("intLess", vIntLess), ("intLessEqual", vIntLessEqual),
("unsafeCastUnits", vUnsafeCastUnits)],
l2nsClasses = M.fromList [("AllTypes", cAllTypes),
("IsClone", cIsClone),
("IsSubset", cIsSubset)],
l2nsClassValues = M.fromList [("==", cvEquals)],
l2nsLabels = M.fromList [("false", L2Label nsBoolean 0), ("true", L2Label nsBoolean 1)]
}
),
(nsNatural, blankNamespaceContents biSrcSpan nsBuiltinMain {-
l2nsLabels = M.empty, -- Natural labels 0..inf are handled elsewhere.
l2nsNextLabel = 0 -- Infinitely many labels.
-}),
(nsInteger, blankNamespaceContents biSrcSpan nsBuiltinMain {-
l2nsLabels = M.empty, -- Integer labels are handled elsewhere.
l2nsNextLabel = 0 -- Infinitely many labels.
-}),
(nsBoolean, (blankNamespaceContents biSrcSpan nsBuiltinMain) {
l2nsNamespaces = M.empty, -- Should we have Boolean.true & Boolean.false namespaces?
l2nsLabels = M.fromList [("false", L2Label nsBoolean 0), ("true", L2Label nsBoolean 1)],
l2nsNextLabel = 2
}),
(nsMain, blankNamespaceContents biSrcSpan nsBuiltinMain)
],
l2NextNamespace = L2NamespaceID reservedIDs,
l2AllDomains = M.fromList [(dNatural, L2BuiltinDomainContents biSrcSpan "naturals"),
(dInteger, L2BuiltinDomainContents biSrcSpan "integer"),
(dBoolean, L2BuiltinDomainContents biSrcSpan "boolean")],
l2NextDomain = L2DomainID reservedIDs,
l2AllValues = M.fromList [(vFalse, L2ValueContents biSrcSpan $ Just $ L2DomainReference biSrcSpan dBoolean),
(vTrue, L2ValueContents biSrcSpan $ Just $ L2DomainReference biSrcSpan dBoolean),
(vUndefined, L2ValueContents biSrcSpan $ Just $ L2DomainVariableRef biSrcSpan sdidAny),
(vRealPlus, L2ValueContents biSrcSpan $
Just $ L2DomainExpressionFieldSignature biSrcSpan rdim
(L2DomainExpressionFieldSignature biSrcSpan rdim rdim)
),
(vRealMinus, L2ValueContents biSrcSpan $ Just $
L2DomainExpressionFieldSignature biSrcSpan rdim
(L2DomainExpressionFieldSignature biSrcSpan rdim rdim)
),
(vRealTimes, L2ValueContents biSrcSpan $ Just $
L2DomainExpressionFieldSignature biSrcSpan rdim
(L2DomainExpressionFieldSignature biSrcSpan rdim rdim)
),
(vRealDivide, L2ValueContents biSrcSpan $
Just $ L2DomainExpressionFieldSignature biSrcSpan rdim
(L2DomainExpressionFieldSignature biSrcSpan rdim rdim)
),
(vRealPow, L2ValueContents biSrcSpan $
Just $ L2DomainExpressionFieldSignature biSrcSpan rdim
(L2DomainExpressionFieldSignature biSrcSpan rdim rdim)
),
(vIntPlus, L2ValueContents biSrcSpan $
Just $ L2DomainExpressionFieldSignature biSrcSpan (L2DomainReference biSrcSpan dInteger)
(L2DomainExpressionFieldSignature biSrcSpan (L2DomainReference biSrcSpan dInteger) (L2DomainReference biSrcSpan dInteger))
),
(vIntMinus, L2ValueContents biSrcSpan $
Just $ L2DomainExpressionFieldSignature biSrcSpan (L2DomainReference biSrcSpan dInteger)
(L2DomainExpressionFieldSignature biSrcSpan (L2DomainReference biSrcSpan dInteger) (L2DomainReference biSrcSpan dInteger))
),
(vIntTimes, L2ValueContents biSrcSpan $
Just $ L2DomainExpressionFieldSignature biSrcSpan (L2DomainReference biSrcSpan dInteger)
(L2DomainExpressionFieldSignature biSrcSpan (L2DomainReference biSrcSpan dInteger) (L2DomainReference biSrcSpan dInteger))
),
(vIntDivide, L2ValueContents biSrcSpan $
Just $ L2DomainExpressionFieldSignature biSrcSpan (L2DomainReference biSrcSpan dInteger)
(L2DomainExpressionFieldSignature biSrcSpan (L2DomainReference biSrcSpan dInteger) (L2DomainReference biSrcSpan dInteger))
),
(vIntPow, L2ValueContents biSrcSpan $
Just $ L2DomainExpressionFieldSignature biSrcSpan (L2DomainReference biSrcSpan dInteger)
(L2DomainExpressionFieldSignature biSrcSpan (L2DomainReference biSrcSpan dInteger) (L2DomainReference biSrcSpan dInteger))
),
(vRealExpE, L2ValueContents biSrcSpan $ Just $ rdim),
(vRealPi, L2ValueContents biSrcSpan $ Just $ rdim),
(vRealEulerGamma, L2ValueContents biSrcSpan $ Just $ rdim),
(vRealSin, L2ValueContents biSrcSpan $
Just $ L2DomainExpressionFieldSignature biSrcSpan rdim rdim),
(vRealCos, L2ValueContents biSrcSpan $
Just $ L2DomainExpressionFieldSignature biSrcSpan rdim rdim),
(vRealTan, L2ValueContents biSrcSpan $
Just $ L2DomainExpressionFieldSignature biSrcSpan rdim rdim),
(vRealSinh, L2ValueContents biSrcSpan $
Just $ L2DomainExpressionFieldSignature biSrcSpan rdim rdim),
(vRealCosh, L2ValueContents biSrcSpan $
Just $ L2DomainExpressionFieldSignature biSrcSpan rdim rdim),
(vRealTanh, L2ValueContents biSrcSpan $
Just $ L2DomainExpressionFieldSignature biSrcSpan rdim rdim),
(vRealASin, L2ValueContents biSrcSpan $
Just $ L2DomainExpressionFieldSignature biSrcSpan rdim rdim),
(vRealACos, L2ValueContents biSrcSpan $
Just $ L2DomainExpressionFieldSignature biSrcSpan rdim rdim),
(vRealATan, L2ValueContents biSrcSpan $
Just $ L2DomainExpressionFieldSignature biSrcSpan rdim rdim),
(vRealASinh, L2ValueContents biSrcSpan $
Just $ L2DomainExpressionFieldSignature biSrcSpan rdim rdim),
(vRealACosh, L2ValueContents biSrcSpan $
Just $ L2DomainExpressionFieldSignature biSrcSpan rdim rdim),
(vRealATanh, L2ValueContents biSrcSpan $
Just $ L2DomainExpressionFieldSignature biSrcSpan rdim rdim),
(vAnd, L2ValueContents biSrcSpan $
Just $ L2DomainExpressionFieldSignature biSrcSpan (L2DomainReference biSrcSpan dBoolean)
(L2DomainExpressionFieldSignature biSrcSpan (L2DomainReference biSrcSpan dBoolean) (L2DomainReference biSrcSpan dBoolean))),
(vOr, L2ValueContents biSrcSpan $
Just $ L2DomainExpressionFieldSignature biSrcSpan (L2DomainReference biSrcSpan dBoolean)
(L2DomainExpressionFieldSignature biSrcSpan (L2DomainReference biSrcSpan dBoolean) (L2DomainReference biSrcSpan dBoolean))),
(vXor, L2ValueContents biSrcSpan $
Just $ L2DomainExpressionFieldSignature biSrcSpan (L2DomainReference biSrcSpan dBoolean)
(L2DomainExpressionFieldSignature biSrcSpan (L2DomainReference biSrcSpan dBoolean) (L2DomainReference biSrcSpan dBoolean))),
(vNot, L2ValueContents biSrcSpan $
Just $ L2DomainExpressionFieldSignature biSrcSpan (L2DomainReference biSrcSpan dBoolean) (L2DomainReference biSrcSpan dBoolean)),
(vRealLess, L2ValueContents biSrcSpan $ Just $
L2DomainExpressionFieldSignature biSrcSpan rdim (L2DomainExpressionFieldSignature biSrcSpan rdim (L2DomainReference biSrcSpan dBoolean))
),
(vRealLessEqual, L2ValueContents biSrcSpan $ Just $
L2DomainExpressionFieldSignature biSrcSpan rdim (L2DomainExpressionFieldSignature biSrcSpan rdim (L2DomainReference biSrcSpan dBoolean))
),
(vIntLess, L2ValueContents biSrcSpan $ Just $
L2DomainExpressionFieldSignature biSrcSpan (L2DomainReference biSrcSpan dInteger) (L2DomainExpressionFieldSignature biSrcSpan (L2DomainReference biSrcSpan dInteger) (L2DomainReference biSrcSpan dBoolean))
),
(vIntLessEqual, L2ValueContents biSrcSpan $ Just $
L2DomainExpressionFieldSignature biSrcSpan (L2DomainReference biSrcSpan dInteger) (L2DomainExpressionFieldSignature biSrcSpan (L2DomainReference biSrcSpan dInteger) (L2DomainReference biSrcSpan dBoolean))
),
(vUnsafeCastUnits, L2ValueContents biSrcSpan $ Just $
(L2DomainExpressionLambda biSrcSpan [] [suidAny1, suidAny2] [] [] []
(L2DomainExpressionFieldSignature biSrcSpan (L2DomainExpressionReal biSrcSpan (L2UnitScopedVar biSrcSpan suidAny1)) (L2DomainExpressionReal biSrcSpan (L2UnitScopedVar biSrcSpan suidAny2)))))
],
l2NextValue = L2ValueID reservedIDs,
l2AllAssertions = [],
l2AllBaseUnits = M.empty, -- Should SI units come built-in?
l2NextBaseUnits = L2BaseUnitsID reservedIDs,
l2AllClasses = M.fromList [(cAllTypes,
L2ClassContents biSrcSpan [(sdidATParam, L1.Kind [] [])] M.empty
(M.fromList [("==", cvEquals)])
),
(cIsClone,
L2ClassContents biSrcSpan [(sdidAny, L1.Kind [] [])]
(M.fromList [("ClonedFrom", dfClonedFrom)])
(M.fromList [("asClone", cvAsClone),
("fromClone", cvFromClone)])
),
(cIsSubset,
L2ClassContents biSrcSpan [(sdidAny, L1.Kind [] [])]
(M.fromList [("SubsetFrom", dfSubsetFrom)])
(M.fromList [("unsafeToSubset", cvUnsafeToSubset),
("fromClone", cvFromSubset)])
)],
l2NextClassID = L2ClassID reservedIDs,
l2AllInstances = [],
l2NextScopedValueID = L2ScopedValueID reservedIDs,
l2NextScopedUnitID = L2ScopedUnitID "!unnamed" reservedIDs,
l2NextScopedDomainID = L2ScopedDomainID "!unnamed" reservedIDs,
l2AllDomainFunctions = M.fromList [(dfClonedFrom, L2DomainFunctionContents biSrcSpan 1),
(dfSubsetFrom, L2DomainFunctionContents biSrcSpan 1)],
l2NextDomainFunctionID = L2DomainFunctionID reservedIDs,
l2AllClassValues = M.fromList [(cvEquals, L2ClassValueContents biSrcSpan
(L2DomainExpressionFieldSignature biSrcSpan
(L2DomainVariableRef biSrcSpan sdidATParam)
(L2DomainExpressionFieldSignature biSrcSpan
(L2DomainVariableRef biSrcSpan sdidATParam)
(L2DomainReference biSrcSpan dBoolean)
))),
(cvAsClone, L2ClassValueContents biSrcSpan
(L2DomainExpressionFieldSignature biSrcSpan
(L2DomainFunctionEvaluate biSrcSpan dfClonedFrom
[L2DomainVariableRef biSrcSpan sdidAny])
(L2DomainVariableRef biSrcSpan sdidAny))),
(cvFromClone, L2ClassValueContents biSrcSpan
(L2DomainExpressionFieldSignature biSrcSpan
(L2DomainVariableRef biSrcSpan sdidAny)
(L2DomainFunctionEvaluate biSrcSpan dfClonedFrom
[L2DomainVariableRef biSrcSpan sdidAny]))),
(cvUnsafeToSubset,
L2ClassValueContents biSrcSpan
(L2DomainExpressionFieldSignature biSrcSpan
(L2DomainFunctionEvaluate biSrcSpan dfSubsetFrom
[L2DomainVariableRef biSrcSpan sdidAny])
(L2DomainVariableRef biSrcSpan sdidAny))),
(cvFromSubset, L2ClassValueContents biSrcSpan
(L2DomainExpressionFieldSignature biSrcSpan
(L2DomainVariableRef biSrcSpan sdidAny)
(L2DomainFunctionEvaluate biSrcSpan dfSubsetFrom
[L2DomainVariableRef biSrcSpan sdidAny])))
],
l2NextClassValueID = L2ClassValueID reservedIDs
}
| A1kmm/declarative-fieldml-prototype | src/Data/FieldML/InitialModel.hs | bsd-3-clause | 20,326 | 0 | 18 | 8,031 | 3,640 | 2,002 | 1,638 | 260 | 1 |
module Data.Csv.Conversion.Internal
( decimal
, realFloat
) where
import Blaze.ByteString.Builder
import Blaze.ByteString.Builder.Char8
import Data.Array.Base (unsafeAt)
import Data.Array.IArray
import qualified Data.ByteString as B
import Data.Char (ord)
import Data.Int
import Data.Monoid
import Data.Word
------------------------------------------------------------------------
-- Integers
decimal :: Integral a => a -> B.ByteString
decimal = toByteString . formatDecimal
{-# INLINE decimal #-}
-- TODO: Add an optimized version for Integer.
formatDecimal :: Integral a => a -> Builder
{-# SPECIALIZE formatDecimal :: Int8 -> Builder #-}
{-# RULES "formatDecimal/Int" formatDecimal = formatBoundedSigned
:: Int -> Builder #-}
{-# RULES "formatDecimal/Int16" formatDecimal = formatBoundedSigned
:: Int16 -> Builder #-}
{-# RULES "formatDecimal/Int32" formatDecimal = formatBoundedSigned
:: Int32 -> Builder #-}
{-# RULES "formatDecimal/Int64" formatDecimal = formatBoundedSigned
:: Int64 -> Builder #-}
{-# RULES "formatDecimal/Word" formatDecimal = formatPositive
:: Word -> Builder #-}
{-# RULES "formatDecimal/Word8" formatDecimal = formatPositive
:: Word8 -> Builder #-}
{-# RULES "formatDecimal/Word16" formatDecimal = formatPositive
:: Word16 -> Builder #-}
{-# RULES "formatDecimal/Word32" formatDecimal = formatPositive
:: Word32 -> Builder #-}
{-# RULES "formatDecimal/Word64" formatDecimal = formatPositive
:: Word64 -> Builder #-}
formatDecimal i
| i < 0 = minus <>
if i <= -128
then formatPositive (-(i `quot` 10)) <> digit (-(i `rem` 10))
else formatPositive (-i)
| otherwise = formatPositive i
formatBoundedSigned :: (Integral a, Bounded a) => a -> Builder
{-# SPECIALIZE formatBoundedSigned :: Int -> Builder #-}
{-# SPECIALIZE formatBoundedSigned :: Int8 -> Builder #-}
{-# SPECIALIZE formatBoundedSigned :: Int16 -> Builder #-}
{-# SPECIALIZE formatBoundedSigned :: Int32 -> Builder #-}
{-# SPECIALIZE formatBoundedSigned :: Int64 -> Builder #-}
formatBoundedSigned i
| i < 0 = minus <>
if i == minBound
then formatPositive (-(i `quot` 10)) <> digit (-(i `rem` 10))
else formatPositive (-i)
| otherwise = formatPositive i
formatPositive :: Integral a => a -> Builder
{-# SPECIALIZE formatPositive :: Int -> Builder #-}
{-# SPECIALIZE formatPositive :: Int8 -> Builder #-}
{-# SPECIALIZE formatPositive :: Int16 -> Builder #-}
{-# SPECIALIZE formatPositive :: Int32 -> Builder #-}
{-# SPECIALIZE formatPositive :: Int64 -> Builder #-}
{-# SPECIALIZE formatPositive :: Word -> Builder #-}
{-# SPECIALIZE formatPositive :: Word8 -> Builder #-}
{-# SPECIALIZE formatPositive :: Word16 -> Builder #-}
{-# SPECIALIZE formatPositive :: Word32 -> Builder #-}
{-# SPECIALIZE formatPositive :: Word64 -> Builder #-}
formatPositive = go
where go n | n < 10 = digit n
| otherwise = go (n `quot` 10) <> digit (n `rem` 10)
minus :: Builder
minus = fromWord8 45
zero :: Word8
zero = 48
digit :: Integral a => a -> Builder
digit n = fromWord8 $! i2w (fromIntegral n)
{-# INLINE digit #-}
i2w :: Int -> Word8
i2w i = zero + fromIntegral i
{-# INLINE i2w #-}
------------------------------------------------------------------------
-- Floating point numbers
realFloat :: RealFloat a => a -> B.ByteString
{-# SPECIALIZE realFloat :: Float -> B.ByteString #-}
{-# SPECIALIZE realFloat :: Double -> B.ByteString #-}
realFloat = toByteString . formatRealFloat Generic
-- | Control the rendering of floating point numbers.
data FPFormat = Exponent
-- ^ Scientific notation (e.g. @2.3e123@).
| Fixed
-- ^ Standard decimal notation.
| Generic
-- ^ Use decimal notation for values between @0.1@ and
-- @9,999,999@, and scientific notation otherwise.
deriving (Enum, Read, Show)
formatRealFloat :: RealFloat a => FPFormat -> a -> Builder
{-# SPECIALIZE formatRealFloat :: FPFormat -> Float -> Builder #-}
{-# SPECIALIZE formatRealFloat :: FPFormat -> Double -> Builder #-}
formatRealFloat fmt x
| isNaN x = fromString "NaN"
| isInfinite x = if x < 0
then fromString "-Infinity"
else fromString "Infinity"
| x < 0 || isNegativeZero x = minus <> doFmt fmt (floatToDigits (-x))
| otherwise = doFmt fmt (floatToDigits x)
where
doFmt format (is, e) =
let ds = map i2d is in
case format of
Generic ->
doFmt (if e < 0 || e > 7 then Exponent else Fixed)
(is,e)
Exponent ->
let show_e' = formatDecimal (e-1) in
case ds of
[48] -> fromString "0.0e0"
[d] -> fromWord8 d <> fromString ".0e" <> show_e'
(d:ds') -> fromWord8 d <> fromChar '.' <> fromWord8s ds' <>
fromChar 'e' <> show_e'
[] -> error "formatRealFloat/doFmt/Exponent: []"
Fixed
| e <= 0 -> fromString "0." <>
fromByteString (B.replicate (-e) zero) <>
fromWord8s ds
| otherwise ->
let
f 0 s rs = mk0 (reverse s) <> fromChar '.' <> mk0 rs
f n s [] = f (n-1) (zero:s) []
f n s (r:rs) = f (n-1) (r:s) rs
in
f e [] ds
where mk0 ls = case ls of { [] -> fromWord8 zero ; _ -> fromWord8s ls}
-- Based on "Printing Floating-Point Numbers Quickly and Accurately"
-- by R.G. Burger and R.K. Dybvig in PLDI 96.
-- This version uses a much slower logarithm estimator. It should be improved.
-- | 'floatToDigits' takes a base and a non-negative 'RealFloat' number,
-- and returns a list of digits and an exponent.
-- In particular, if @x>=0@, and
--
-- > floatToDigits base x = ([d1,d2,...,dn], e)
--
-- then
--
-- (1) @n >= 1@
--
-- (2) @x = 0.d1d2...dn * (base**e)@
--
-- (3) @0 <= di <= base-1@
floatToDigits :: (RealFloat a) => a -> ([Int], Int)
{-# SPECIALIZE floatToDigits :: Float -> ([Int], Int) #-}
{-# SPECIALIZE floatToDigits :: Double -> ([Int], Int) #-}
floatToDigits 0 = ([0], 0)
floatToDigits x =
let
(f0, e0) = decodeFloat x
(minExp0, _) = floatRange x
p = floatDigits x
b = floatRadix x
minExp = minExp0 - p -- the real minimum exponent
-- Haskell requires that f be adjusted so denormalized numbers
-- will have an impossibly low exponent. Adjust for this.
(f, e) =
let n = minExp - e0 in
if n > 0 then (f0 `quot` (expt b n), e0+n) else (f0, e0)
(r, s, mUp, mDn) =
if e >= 0 then
let be = expt b e in
if f == expt b (p-1) then
(f*be*b*2, 2*b, be*b, be) -- according to Burger and Dybvig
else
(f*be*2, 2, be, be)
else
if e > minExp && f == expt b (p-1) then
(f*b*2, expt b (-e+1)*2, b, 1)
else
(f*2, expt b (-e)*2, 1, 1)
k :: Int
k =
let
k0 :: Int
k0 =
if b == 2 then
-- logBase 10 2 is very slightly larger than 8651/28738
-- (about 5.3558e-10), so if log x >= 0, the approximation
-- k1 is too small, hence we add one and need one fixup step less.
-- If log x < 0, the approximation errs rather on the high side.
-- That is usually more than compensated for by ignoring the
-- fractional part of logBase 2 x, but when x is a power of 1/2
-- or slightly larger and the exponent is a multiple of the
-- denominator of the rational approximation to logBase 10 2,
-- k1 is larger than logBase 10 x. If k1 > 1 + logBase 10 x,
-- we get a leading zero-digit we don't want.
-- With the approximation 3/10, this happened for
-- 0.5^1030, 0.5^1040, ..., 0.5^1070 and values close above.
-- The approximation 8651/28738 guarantees k1 < 1 + logBase 10 x
-- for IEEE-ish floating point types with exponent fields
-- <= 17 bits and mantissae of several thousand bits, earlier
-- convergents to logBase 10 2 would fail for long double.
-- Using quot instead of div is a little faster and requires
-- fewer fixup steps for negative lx.
let lx = p - 1 + e0
k1 = (lx * 8651) `quot` 28738
in if lx >= 0 then k1 + 1 else k1
else
-- f :: Integer, log :: Float -> Float,
-- ceiling :: Float -> Int
ceiling ((log (fromInteger (f+1) :: Float) +
fromIntegral e * log (fromInteger b)) /
log 10)
--WAS: fromInt e * log (fromInteger b))
fixup n =
if n >= 0 then
if r + mUp <= expt 10 n * s then n else fixup (n+1)
else
if expt 10 (-n) * (r + mUp) <= s then n else fixup (n+1)
in
fixup k0
gen ds rn sN mUpN mDnN =
let
(dn, rn') = (rn * 10) `quotRem` sN
mUpN' = mUpN * 10
mDnN' = mDnN * 10
in
case (rn' < mDnN', rn' + mUpN' > sN) of
(True, False) -> dn : ds
(False, True) -> dn+1 : ds
(True, True) -> if rn' * 2 < sN then dn : ds else dn+1 : ds
(False, False) -> gen (dn:ds) rn' sN mUpN' mDnN'
rds =
if k >= 0 then
gen [] r (s * expt 10 k) mUp mDn
else
let bk = expt 10 (-k) in
gen [] (r * bk) s (mUp * bk) (mDn * bk)
in
(map fromIntegral (reverse rds), k)
-- Exponentiation with a cache for the most common numbers.
minExpt, maxExpt :: Int
minExpt = 0
maxExpt = 1100
expt :: Integer -> Int -> Integer
expt base n
| base == 2 && n >= minExpt && n <= maxExpt = expts `unsafeAt` n
| base == 10 && n <= maxExpt10 = expts10 `unsafeAt` n
| otherwise = base^n
expts :: Array Int Integer
expts = array (minExpt,maxExpt) [(n,2^n) | n <- [minExpt .. maxExpt]]
maxExpt10 :: Int
maxExpt10 = 324
expts10 :: Array Int Integer
expts10 = array (minExpt,maxExpt10) [(n,10^n) | n <- [minExpt .. maxExpt10]]
-- | Unsafe conversion for decimal digits.
{-# INLINE i2d #-}
i2d :: Int -> Word8
i2d i = fromIntegral (ord '0' + i)
| sjoerdvisscher/cassava | Data/Csv/Conversion/Internal.hs | bsd-3-clause | 10,128 | 0 | 24 | 2,889 | 2,408 | 1,309 | 1,099 | 193 | 15 |
-- This is a model of the Furnace. It is described in different sources [1, 2].
--
-- [1] A. Alan B. Pritsker, Simulation with Visual SLAM and AweSim, 2nd ed.
--
-- [2] Труб И.И., Объектно-ориентированное моделирование на C++: Учебный курс. - СПб.: Питер, 2006
import Data.Maybe
import Control.Monad
import Control.Monad.Trans
import Simulation.Aivika.Trans
import Simulation.Aivika.Trans.Queue.Infinite
import Simulation.Aivika.Branch
type DES = BR IO
-- | The simulation specs.
specs = Specs { spcStartTime = 0.0,
-- spcStopTime = 1000.0,
spcStopTime = 300.0,
spcDT = 0.1,
spcMethod = RungeKutta4,
spcGeneratorType = SimpleGenerator }
-- | Return a random initial temperature of the item.
randomTemp :: Parameter DES Double
randomTemp = randomUniform 400 600
-- | Represents the furnace.
data Furnace =
Furnace { furnacePits :: [Pit],
-- ^ The pits for ingots.
furnacePitCount :: Ref DES Int,
-- ^ The count of active pits with ingots.
furnaceQueue :: FCFSQueue DES Ingot,
-- ^ The furnace queue.
furnaceUnloadedSource :: SignalSource DES (),
-- ^ Notifies when the ingots have been
-- unloaded from the furnace.
furnaceHeatingTime :: Ref DES (SamplingStats Double),
-- ^ The heating time for the ready ingots.
furnaceTemp :: Ref DES Double,
-- ^ The furnace temperature.
furnaceReadyCount :: Ref DES Int,
-- ^ The count of ready ingots.
furnaceReadyTemps :: Ref DES [Double]
-- ^ The temperatures of all ready ingots.
}
-- | Notifies when the ingots have been unloaded from the furnace.
furnaceUnloaded :: Furnace -> Signal DES ()
furnaceUnloaded = publishSignal . furnaceUnloadedSource
-- | A pit in the furnace to place the ingots.
data Pit =
Pit { pitIngot :: Ref DES (Maybe Ingot),
-- ^ The ingot in the pit.
pitTemp :: Ref DES Double
-- ^ The ingot temperature in the pit.
}
data Ingot =
Ingot { ingotFurnace :: Furnace,
-- ^ The furnace.
ingotReceiveTime :: Double,
-- ^ The time at which the ingot was received.
ingotReceiveTemp :: Double,
-- ^ The temperature with which the ingot was received.
ingotLoadTime :: Double,
-- ^ The time of loading in the furnace.
ingotLoadTemp :: Double,
-- ^ The temperature when the ingot was loaded in the furnace.
ingotCoeff :: Double
-- ^ The heating coefficient.
}
-- | Create a furnace.
newFurnace :: Simulation DES Furnace
newFurnace =
do pits <- sequence [newPit | i <- [1..10]]
pitCount <- newRef 0
queue <- runEventInStartTime newFCFSQueue
heatingTime <- newRef emptySamplingStats
h <- newRef 1650.0
readyCount <- newRef 0
readyTemps <- newRef []
s <- newSignalSource
return Furnace { furnacePits = pits,
furnacePitCount = pitCount,
furnaceQueue = queue,
furnaceUnloadedSource = s,
furnaceHeatingTime = heatingTime,
furnaceTemp = h,
furnaceReadyCount = readyCount,
furnaceReadyTemps = readyTemps }
-- | Create a new pit.
newPit :: Simulation DES Pit
newPit =
do ingot <- newRef Nothing
h' <- newRef 0.0
return Pit { pitIngot = ingot,
pitTemp = h' }
-- | Create a new ingot.
newIngot :: Furnace -> Event DES Ingot
newIngot furnace =
do t <- liftDynamics time
xi <- liftParameter $ randomNormal 0.05 0.01
h' <- liftParameter randomTemp
let c = 0.1 + xi
return Ingot { ingotFurnace = furnace,
ingotReceiveTime = t,
ingotReceiveTemp = h',
ingotLoadTime = t,
ingotLoadTemp = h',
ingotCoeff = c }
-- | Heat the ingot up in the pit if there is such an ingot.
heatPitUp :: Pit -> Event DES ()
heatPitUp pit =
do ingot <- readRef (pitIngot pit)
case ingot of
Nothing ->
return ()
Just ingot -> do
-- update the temperature of the ingot.
let furnace = ingotFurnace ingot
dt' <- liftParameter dt
h' <- readRef (pitTemp pit)
h <- readRef (furnaceTemp furnace)
writeRef (pitTemp pit) $
h' + dt' * (h - h') * ingotCoeff ingot
-- | Check whether there are ready ingots in the pits.
ingotsReady :: Furnace -> Event DES Bool
ingotsReady furnace =
fmap (not . null) $
filterM (fmap (>= 2200.0) . readRef . pitTemp) $
furnacePits furnace
-- | Try to unload the ready ingot from the specified pit.
tryUnloadPit :: Furnace -> Pit -> Event DES ()
tryUnloadPit furnace pit =
do h' <- readRef (pitTemp pit)
when (h' >= 2000.0) $
do Just ingot <- readRef (pitIngot pit)
unloadIngot furnace ingot pit
-- | Try to load an awaiting ingot in the specified empty pit.
tryLoadPit :: Furnace -> Pit -> Event DES ()
tryLoadPit furnace pit =
do ingot <- tryDequeue (furnaceQueue furnace)
case ingot of
Nothing ->
return ()
Just ingot ->
do t' <- liftDynamics time
loadIngot furnace (ingot { ingotLoadTime = t',
ingotLoadTemp = 400.0 }) pit
-- | Unload the ingot from the specified pit.
unloadIngot :: Furnace -> Ingot -> Pit -> Event DES ()
unloadIngot furnace ingot pit =
do h' <- readRef (pitTemp pit)
writeRef (pitIngot pit) Nothing
writeRef (pitTemp pit) 0.0
-- count the active pits
modifyRef (furnacePitCount furnace) (+ (- 1))
-- how long did we heat the ingot up?
t' <- liftDynamics time
modifyRef (furnaceHeatingTime furnace) $
addSamplingStats (t' - ingotLoadTime ingot)
-- what is the temperature of the unloaded ingot?
modifyRef (furnaceReadyTemps furnace) (h' :)
-- count the ready ingots
modifyRef (furnaceReadyCount furnace) (+ 1)
-- | Load the ingot in the specified pit
loadIngot :: Furnace -> Ingot -> Pit -> Event DES ()
loadIngot furnace ingot pit =
do writeRef (pitIngot pit) $ Just ingot
writeRef (pitTemp pit) $ ingotLoadTemp ingot
-- count the active pits
modifyRef (furnacePitCount furnace) (+ 1)
count <- readRef (furnacePitCount furnace)
-- decrease the furnace temperature
h <- readRef (furnaceTemp furnace)
let h' = ingotLoadTemp ingot
dh = - (h - h') / fromIntegral count
writeRef (furnaceTemp furnace) $ h + dh
-- | Start iterating the furnace processing through the event queue.
startIteratingFurnace :: Furnace -> Event DES ()
startIteratingFurnace furnace =
let pits = furnacePits furnace
in enqueueEventWithIntegTimes $
do -- try to unload ready ingots
ready <- ingotsReady furnace
when ready $
do mapM_ (tryUnloadPit furnace) pits
triggerSignal (furnaceUnloadedSource furnace) ()
-- heat up
mapM_ heatPitUp pits
-- update the temperature of the furnace
dt' <- liftParameter dt
h <- readRef (furnaceTemp furnace)
writeRef (furnaceTemp furnace) $
h + dt' * (2600.0 - h) * 0.2
-- | Return all empty pits.
emptyPits :: Furnace -> Event DES [Pit]
emptyPits furnace =
filterM (fmap isNothing . readRef . pitIngot) $
furnacePits furnace
-- | This process takes ingots from the queue and then
-- loads them in the furnace.
loadingProcess :: Furnace -> Process DES ()
loadingProcess furnace =
do ingot <- dequeue (furnaceQueue furnace)
let wait =
do count <- liftEvent $ readRef (furnacePitCount furnace)
when (count >= 10) $
do processAwait (furnaceUnloaded furnace)
wait
wait
-- take any empty pit and load it
liftEvent $
do pit: _ <- emptyPits furnace
loadIngot furnace ingot pit
-- repeat it again
loadingProcess furnace
-- | The input process that adds new ingots to the queue.
inputProcess :: Furnace -> Process DES ()
inputProcess furnace =
do delay <- liftParameter $
randomExponential 2.5
holdProcess delay
-- we have got a new ingot
liftEvent $
do ingot <- newIngot furnace
enqueue (furnaceQueue furnace) ingot
-- repeat it again
inputProcess furnace
-- | Initialize the furnace.
initializeFurnace :: Furnace -> Event DES ()
initializeFurnace furnace =
do x1 <- newIngot furnace
x2 <- newIngot furnace
x3 <- newIngot furnace
x4 <- newIngot furnace
x5 <- newIngot furnace
x6 <- newIngot furnace
let p1 : p2 : p3 : p4 : p5 : p6 : ps =
furnacePits furnace
loadIngot furnace (x1 { ingotLoadTemp = 550.0 }) p1
loadIngot furnace (x2 { ingotLoadTemp = 600.0 }) p2
loadIngot furnace (x3 { ingotLoadTemp = 650.0 }) p3
loadIngot furnace (x4 { ingotLoadTemp = 700.0 }) p4
loadIngot furnace (x5 { ingotLoadTemp = 750.0 }) p5
loadIngot furnace (x6 { ingotLoadTemp = 800.0 }) p6
writeRef (furnaceTemp furnace) 1650.0
-- | The simulation model.
model :: Simulation DES (Results DES)
model =
do furnace <- newFurnace
-- initialize the furnace and start its iterating in start time
runEventInStartTime $
do initializeFurnace furnace
startIteratingFurnace furnace
-- generate randomly new input ingots
runProcessInStartTime $
inputProcess furnace
-- load permanently the input ingots in the furnace
runProcessInStartTime $
loadingProcess furnace
-- return the simulation results
return $
resultSummary $
results
[resultSource "inputIngotCount" "the input ingot count" $
enqueueStoreCount (furnaceQueue furnace),
--
resultSource "loadedIngotCount" "the loaded ingot count" $
dequeueCount (furnaceQueue furnace),
--
resultSource "outputIngotCount" "the output ingot count" $
furnaceReadyCount furnace,
--
resultSource "outputIngotTemp" "the output ingot temperature" $
fmap listSamplingStats $ readRef $ furnaceReadyTemps furnace,
--
resultSource "heatingTime" "the heating time" $
furnaceHeatingTime furnace,
--
resultSource "pitCount" "the number of ingots in pits" $
furnacePitCount furnace,
--
resultSource "furnaceQueue" "the furnace queue" $
furnaceQueue furnace]
-- | The main program.
main =
runBR $
printSimulationResultsInStopTime
printResultSourceInEnglish
model specs
| dsorokin/aivika-branches | tests/Furnace.hs | bsd-3-clause | 10,983 | 0 | 18 | 3,362 | 2,419 | 1,209 | 1,210 | 215 | 2 |
module Main where
import ClassyPrelude.Yesod hiding (Proxy, join)
import Control.Monad.Logger
import Database.Esqueleto
import Database.Persist.Sqlite
import Database.Esqueleto.Join
import Ents1
import Ents2
import Ents3
main :: IO ()
main =
runStderrLoggingT . withSqliteConn ":memory:" $ \backend ->
flip runSqlConn backend $ do
runMigration $ do
Ents1.migrateAll
Ents2.migrateAll
Ents3.migrateAll
void three
void four
three :: MonadIO m => ReaderT SqlBackend m [Entity Student]
three =
select . from $ \(ents@(_ `InnerJoin` _ `InnerJoin` student) :: Joins [School, Teacher, Student]) -> do
join ents
return student
type SEnt a = SqlExpr (Entity a)
four :: MonadIO m => ReaderT SqlBackend m [Maybe (Entity Pencil)]
four =
select . from $ \ents@((_ :: SEnt School) `InnerJoin` (_ :: SEnt Teacher) `LeftOuterJoin` (_ :: SqlExpr (Maybe (Entity Student))) `LeftOuterJoin` pencil) -> do
join ents
return pencil
| pseudonom/dovetail | test/Spec.hs | bsd-3-clause | 984 | 0 | 18 | 206 | 359 | 190 | 169 | -1 | -1 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
--
-- Generating machine code (instruction selection)
--
-- (c) The University of Glasgow 1996-2013
--
-----------------------------------------------------------------------------
{-# LANGUAGE GADTs #-}
module SPARC.CodeGen (
cmmTopCodeGen,
generateJumpTableForInstr,
InstrBlock
)
where
#include "HsVersions.h"
#include "nativeGen/NCG.h"
#include "../includes/MachDeps.h"
-- NCG stuff:
import GhcPrelude
import SPARC.Base
import SPARC.CodeGen.Sanity
import SPARC.CodeGen.Amode
import SPARC.CodeGen.CondCode
import SPARC.CodeGen.Gen64
import SPARC.CodeGen.Gen32
import SPARC.CodeGen.Base
import SPARC.Ppr ()
import SPARC.Instr
import SPARC.Imm
import SPARC.AddrMode
import SPARC.Regs
import SPARC.Stack
import Instruction
import Format
import NCGMonad
-- Our intermediate code:
import BlockId
import Cmm
import CmmUtils
import CmmSwitch
import Hoopl.Block
import Hoopl.Graph
import PIC
import Reg
import CLabel
import CPrim
-- The rest:
import BasicTypes
import DynFlags
import FastString
import OrdList
import Outputable
import Platform
import Control.Monad ( mapAndUnzipM )
-- | Top level code generation
cmmTopCodeGen :: RawCmmDecl
-> NatM [NatCmmDecl CmmStatics Instr]
cmmTopCodeGen (CmmProc info lab live graph)
= do let blocks = toBlockListEntryFirst graph
(nat_blocks,statics) <- mapAndUnzipM basicBlockCodeGen blocks
let proc = CmmProc info lab live (ListGraph $ concat nat_blocks)
let tops = proc : concat statics
return tops
cmmTopCodeGen (CmmData sec dat) = do
return [CmmData sec dat] -- no translation, we just use CmmStatic
-- | Do code generation on a single block of CMM code.
-- code generation may introduce new basic block boundaries, which
-- are indicated by the NEWBLOCK instruction. We must split up the
-- instruction stream into basic blocks again. Also, we extract
-- LDATAs here too.
basicBlockCodeGen :: CmmBlock
-> NatM ( [NatBasicBlock Instr]
, [NatCmmDecl CmmStatics Instr])
basicBlockCodeGen block = do
let (_, nodes, tail) = blockSplit block
id = entryLabel block
stmts = blockToList nodes
mid_instrs <- stmtsToInstrs stmts
tail_instrs <- stmtToInstrs tail
let instrs = mid_instrs `appOL` tail_instrs
let
(top,other_blocks,statics)
= foldrOL mkBlocks ([],[],[]) instrs
mkBlocks (NEWBLOCK id) (instrs,blocks,statics)
= ([], BasicBlock id instrs : blocks, statics)
mkBlocks (LDATA sec dat) (instrs,blocks,statics)
= (instrs, blocks, CmmData sec dat:statics)
mkBlocks instr (instrs,blocks,statics)
= (instr:instrs, blocks, statics)
-- do intra-block sanity checking
blocksChecked
= map (checkBlock block)
$ BasicBlock id top : other_blocks
return (blocksChecked, statics)
-- | Convert some Cmm statements to SPARC instructions.
stmtsToInstrs :: [CmmNode e x] -> NatM InstrBlock
stmtsToInstrs stmts
= do instrss <- mapM stmtToInstrs stmts
return (concatOL instrss)
stmtToInstrs :: CmmNode e x -> NatM InstrBlock
stmtToInstrs stmt = do
dflags <- getDynFlags
case stmt of
CmmComment s -> return (unitOL (COMMENT s))
CmmTick {} -> return nilOL
CmmUnwind {} -> return nilOL
CmmAssign reg src
| isFloatType ty -> assignReg_FltCode format reg src
| isWord64 ty -> assignReg_I64Code reg src
| otherwise -> assignReg_IntCode format reg src
where ty = cmmRegType dflags reg
format = cmmTypeFormat ty
CmmStore addr src
| isFloatType ty -> assignMem_FltCode format addr src
| isWord64 ty -> assignMem_I64Code addr src
| otherwise -> assignMem_IntCode format addr src
where ty = cmmExprType dflags src
format = cmmTypeFormat ty
CmmUnsafeForeignCall target result_regs args
-> genCCall target result_regs args
CmmBranch id -> genBranch id
CmmCondBranch arg true false _ -> do
b1 <- genCondJump true arg
b2 <- genBranch false
return (b1 `appOL` b2)
CmmSwitch arg ids -> do dflags <- getDynFlags
genSwitch dflags arg ids
CmmCall { cml_target = arg } -> genJump arg
_
-> panic "stmtToInstrs: statement should have been cps'd away"
{-
Now, given a tree (the argument to a CmmLoad) that references memory,
produce a suitable addressing mode.
A Rule of the Game (tm) for Amodes: use of the addr bit must
immediately follow use of the code part, since the code part puts
values in registers which the addr then refers to. So you can't put
anything in between, lest it overwrite some of those registers. If
you need to do some other computation between the code part and use of
the addr bit, first store the effective address from the amode in a
temporary, then do the other computation, and then use the temporary:
code
LEA amode, tmp
... other computation ...
... (tmp) ...
-}
-- | Convert a BlockId to some CmmStatic data
jumpTableEntry :: DynFlags -> Maybe BlockId -> CmmStatic
jumpTableEntry dflags Nothing = CmmStaticLit (CmmInt 0 (wordWidth dflags))
jumpTableEntry _ (Just blockid) = CmmStaticLit (CmmLabel blockLabel)
where blockLabel = blockLbl blockid
-- -----------------------------------------------------------------------------
-- Generating assignments
-- Assignments are really at the heart of the whole code generation
-- business. Almost all top-level nodes of any real importance are
-- assignments, which correspond to loads, stores, or register
-- transfers. If we're really lucky, some of the register transfers
-- will go away, because we can use the destination register to
-- complete the code generation for the right hand side. This only
-- fails when the right hand side is forced into a fixed register
-- (e.g. the result of a call).
assignMem_IntCode :: Format -> CmmExpr -> CmmExpr -> NatM InstrBlock
assignMem_IntCode pk addr src = do
(srcReg, code) <- getSomeReg src
Amode dstAddr addr_code <- getAmode addr
return $ code `appOL` addr_code `snocOL` ST pk srcReg dstAddr
assignReg_IntCode :: Format -> CmmReg -> CmmExpr -> NatM InstrBlock
assignReg_IntCode _ reg src = do
dflags <- getDynFlags
r <- getRegister src
let dst = getRegisterReg (targetPlatform dflags) reg
return $ case r of
Any _ code -> code dst
Fixed _ freg fcode -> fcode `snocOL` OR False g0 (RIReg freg) dst
-- Floating point assignment to memory
assignMem_FltCode :: Format -> CmmExpr -> CmmExpr -> NatM InstrBlock
assignMem_FltCode pk addr src = do
dflags <- getDynFlags
Amode dst__2 code1 <- getAmode addr
(src__2, code2) <- getSomeReg src
tmp1 <- getNewRegNat pk
let
pk__2 = cmmExprType dflags src
code__2 = code1 `appOL` code2 `appOL`
if formatToWidth pk == typeWidth pk__2
then unitOL (ST pk src__2 dst__2)
else toOL [ FxTOy (cmmTypeFormat pk__2) pk src__2 tmp1
, ST pk tmp1 dst__2]
return code__2
-- Floating point assignment to a register/temporary
assignReg_FltCode :: Format -> CmmReg -> CmmExpr -> NatM InstrBlock
assignReg_FltCode pk dstCmmReg srcCmmExpr = do
dflags <- getDynFlags
let platform = targetPlatform dflags
srcRegister <- getRegister srcCmmExpr
let dstReg = getRegisterReg platform dstCmmReg
return $ case srcRegister of
Any _ code -> code dstReg
Fixed _ srcFixedReg srcCode -> srcCode `snocOL` FMOV pk srcFixedReg dstReg
genJump :: CmmExpr{-the branch target-} -> NatM InstrBlock
genJump (CmmLit (CmmLabel lbl))
= return (toOL [CALL (Left target) 0 True, NOP])
where
target = ImmCLbl lbl
genJump tree
= do
(target, code) <- getSomeReg tree
return (code `snocOL` JMP (AddrRegReg target g0) `snocOL` NOP)
-- -----------------------------------------------------------------------------
-- Unconditional branches
genBranch :: BlockId -> NatM InstrBlock
genBranch = return . toOL . mkJumpInstr
-- -----------------------------------------------------------------------------
-- Conditional jumps
{-
Conditional jumps are always to local labels, so we can use branch
instructions. We peek at the arguments to decide what kind of
comparison to do.
SPARC: First, we have to ensure that the condition codes are set
according to the supplied comparison operation. We generate slightly
different code for floating point comparisons, because a floating
point operation cannot directly precede a @BF@. We assume the worst
and fill that slot with a @NOP@.
SPARC: Do not fill the delay slots here; you will confuse the register
allocator.
-}
genCondJump
:: BlockId -- the branch target
-> CmmExpr -- the condition on which to branch
-> NatM InstrBlock
genCondJump bid bool = do
CondCode is_float cond code <- getCondCode bool
return (
code `appOL`
toOL (
if is_float
then [NOP, BF cond False bid, NOP]
else [BI cond False bid, NOP]
)
)
-- -----------------------------------------------------------------------------
-- Generating a table-branch
genSwitch :: DynFlags -> CmmExpr -> SwitchTargets -> NatM InstrBlock
genSwitch dflags expr targets
| positionIndependent dflags
= error "MachCodeGen: sparc genSwitch PIC not finished\n"
| otherwise
= do (e_reg, e_code) <- getSomeReg (cmmOffset dflags expr offset)
base_reg <- getNewRegNat II32
offset_reg <- getNewRegNat II32
dst <- getNewRegNat II32
label <- getNewLabelNat
return $ e_code `appOL`
toOL
[ -- load base of jump table
SETHI (HI (ImmCLbl label)) base_reg
, OR False base_reg (RIImm $ LO $ ImmCLbl label) base_reg
-- the addrs in the table are 32 bits wide..
, SLL e_reg (RIImm $ ImmInt 2) offset_reg
-- load and jump to the destination
, LD II32 (AddrRegReg base_reg offset_reg) dst
, JMP_TBL (AddrRegImm dst (ImmInt 0)) ids label
, NOP ]
where (offset, ids) = switchTargetsToTable targets
generateJumpTableForInstr :: DynFlags -> Instr
-> Maybe (NatCmmDecl CmmStatics Instr)
generateJumpTableForInstr dflags (JMP_TBL _ ids label) =
let jumpTable = map (jumpTableEntry dflags) ids
in Just (CmmData (Section ReadOnlyData label) (Statics label jumpTable))
generateJumpTableForInstr _ _ = Nothing
-- -----------------------------------------------------------------------------
-- Generating C calls
{-
Now the biggest nightmare---calls. Most of the nastiness is buried in
@get_arg@, which moves the arguments to the correct registers/stack
locations. Apart from that, the code is easy.
The SPARC calling convention is an absolute
nightmare. The first 6x32 bits of arguments are mapped into
%o0 through %o5, and the remaining arguments are dumped to the
stack, beginning at [%sp+92]. (Note that %o6 == %sp.)
If we have to put args on the stack, move %o6==%sp down by
the number of words to go on the stack, to ensure there's enough space.
According to Fraser and Hanson's lcc book, page 478, fig 17.2,
16 words above the stack pointer is a word for the address of
a structure return value. I use this as a temporary location
for moving values from float to int regs. Certainly it isn't
safe to put anything in the 16 words starting at %sp, since
this area can get trashed at any time due to window overflows
caused by signal handlers.
A final complication (if the above isn't enough) is that
we can't blithely calculate the arguments one by one into
%o0 .. %o5. Consider the following nested calls:
fff a (fff b c)
Naive code moves a into %o0, and (fff b c) into %o1. Unfortunately
the inner call will itself use %o0, which trashes the value put there
in preparation for the outer call. Upshot: we need to calculate the
args into temporary regs, and move those to arg regs or onto the
stack only immediately prior to the call proper. Sigh.
-}
genCCall
:: ForeignTarget -- function to call
-> [CmmFormal] -- where to put the result
-> [CmmActual] -- arguments (of mixed type)
-> NatM InstrBlock
-- On SPARC under TSO (Total Store Ordering), writes earlier in the instruction stream
-- are guaranteed to take place before writes afterwards (unlike on PowerPC).
-- Ref: Section 8.4 of the SPARC V9 Architecture manual.
--
-- In the SPARC case we don't need a barrier.
--
genCCall (PrimTarget MO_WriteBarrier) _ _
= return $ nilOL
genCCall (PrimTarget (MO_Prefetch_Data _)) _ _
= return $ nilOL
genCCall target dest_regs args
= do -- work out the arguments, and assign them to integer regs
argcode_and_vregs <- mapM arg_to_int_vregs args
let (argcodes, vregss) = unzip argcode_and_vregs
let vregs = concat vregss
let n_argRegs = length allArgRegs
let n_argRegs_used = min (length vregs) n_argRegs
-- deal with static vs dynamic call targets
callinsns <- case target of
ForeignTarget (CmmLit (CmmLabel lbl)) _ ->
return (unitOL (CALL (Left (litToImm (CmmLabel lbl))) n_argRegs_used False))
ForeignTarget expr _
-> do (dyn_c, [dyn_r]) <- arg_to_int_vregs expr
return (dyn_c `snocOL` CALL (Right dyn_r) n_argRegs_used False)
PrimTarget mop
-> do res <- outOfLineMachOp mop
lblOrMopExpr <- case res of
Left lbl -> do
return (unitOL (CALL (Left (litToImm (CmmLabel lbl))) n_argRegs_used False))
Right mopExpr -> do
(dyn_c, [dyn_r]) <- arg_to_int_vregs mopExpr
return (dyn_c `snocOL` CALL (Right dyn_r) n_argRegs_used False)
return lblOrMopExpr
let argcode = concatOL argcodes
let (move_sp_down, move_sp_up)
= let diff = length vregs - n_argRegs
nn = if odd diff then diff + 1 else diff -- keep 8-byte alignment
in if nn <= 0
then (nilOL, nilOL)
else (unitOL (moveSp (-1*nn)), unitOL (moveSp (1*nn)))
let transfer_code
= toOL (move_final vregs allArgRegs extraStackArgsHere)
dflags <- getDynFlags
return
$ argcode `appOL`
move_sp_down `appOL`
transfer_code `appOL`
callinsns `appOL`
unitOL NOP `appOL`
move_sp_up `appOL`
assign_code (targetPlatform dflags) dest_regs
-- | Generate code to calculate an argument, and move it into one
-- or two integer vregs.
arg_to_int_vregs :: CmmExpr -> NatM (OrdList Instr, [Reg])
arg_to_int_vregs arg = do dflags <- getDynFlags
arg_to_int_vregs' dflags arg
arg_to_int_vregs' :: DynFlags -> CmmExpr -> NatM (OrdList Instr, [Reg])
arg_to_int_vregs' dflags arg
-- If the expr produces a 64 bit int, then we can just use iselExpr64
| isWord64 (cmmExprType dflags arg)
= do (ChildCode64 code r_lo) <- iselExpr64 arg
let r_hi = getHiVRegFromLo r_lo
return (code, [r_hi, r_lo])
| otherwise
= do (src, code) <- getSomeReg arg
let pk = cmmExprType dflags arg
case cmmTypeFormat pk of
-- Load a 64 bit float return value into two integer regs.
FF64 -> do
v1 <- getNewRegNat II32
v2 <- getNewRegNat II32
let code2 =
code `snocOL`
FMOV FF64 src f0 `snocOL`
ST FF32 f0 (spRel 16) `snocOL`
LD II32 (spRel 16) v1 `snocOL`
ST FF32 f1 (spRel 16) `snocOL`
LD II32 (spRel 16) v2
return (code2, [v1,v2])
-- Load a 32 bit float return value into an integer reg
FF32 -> do
v1 <- getNewRegNat II32
let code2 =
code `snocOL`
ST FF32 src (spRel 16) `snocOL`
LD II32 (spRel 16) v1
return (code2, [v1])
-- Move an integer return value into its destination reg.
_ -> do
v1 <- getNewRegNat II32
let code2 =
code `snocOL`
OR False g0 (RIReg src) v1
return (code2, [v1])
-- | Move args from the integer vregs into which they have been
-- marshalled, into %o0 .. %o5, and the rest onto the stack.
--
move_final :: [Reg] -> [Reg] -> Int -> [Instr]
-- all args done
move_final [] _ _
= []
-- out of aregs; move to stack
move_final (v:vs) [] offset
= ST II32 v (spRel offset)
: move_final vs [] (offset+1)
-- move into an arg (%o[0..5]) reg
move_final (v:vs) (a:az) offset
= OR False g0 (RIReg v) a
: move_final vs az offset
-- | Assign results returned from the call into their
-- destination regs.
--
assign_code :: Platform -> [LocalReg] -> OrdList Instr
assign_code _ [] = nilOL
assign_code platform [dest]
= let rep = localRegType dest
width = typeWidth rep
r_dest = getRegisterReg platform (CmmLocal dest)
result
| isFloatType rep
, W32 <- width
= unitOL $ FMOV FF32 (regSingle $ fReg 0) r_dest
| isFloatType rep
, W64 <- width
= unitOL $ FMOV FF64 (regSingle $ fReg 0) r_dest
| not $ isFloatType rep
, W32 <- width
= unitOL $ mkRegRegMoveInstr platform (regSingle $ oReg 0) r_dest
| not $ isFloatType rep
, W64 <- width
, r_dest_hi <- getHiVRegFromLo r_dest
= toOL [ mkRegRegMoveInstr platform (regSingle $ oReg 0) r_dest_hi
, mkRegRegMoveInstr platform (regSingle $ oReg 1) r_dest]
| otherwise
= panic "SPARC.CodeGen.GenCCall: no match"
in result
assign_code _ _
= panic "SPARC.CodeGen.GenCCall: no match"
-- | Generate a call to implement an out-of-line floating point operation
outOfLineMachOp
:: CallishMachOp
-> NatM (Either CLabel CmmExpr)
outOfLineMachOp mop
= do let functionName
= outOfLineMachOp_table mop
dflags <- getDynFlags
mopExpr <- cmmMakeDynamicReference dflags CallReference
$ mkForeignLabel functionName Nothing ForeignLabelInExternalPackage IsFunction
let mopLabelOrExpr
= case mopExpr of
CmmLit (CmmLabel lbl) -> Left lbl
_ -> Right mopExpr
return mopLabelOrExpr
-- | Decide what C function to use to implement a CallishMachOp
--
outOfLineMachOp_table
:: CallishMachOp
-> FastString
outOfLineMachOp_table mop
= case mop of
MO_F32_Exp -> fsLit "expf"
MO_F32_Log -> fsLit "logf"
MO_F32_Sqrt -> fsLit "sqrtf"
MO_F32_Fabs -> unsupported
MO_F32_Pwr -> fsLit "powf"
MO_F32_Sin -> fsLit "sinf"
MO_F32_Cos -> fsLit "cosf"
MO_F32_Tan -> fsLit "tanf"
MO_F32_Asin -> fsLit "asinf"
MO_F32_Acos -> fsLit "acosf"
MO_F32_Atan -> fsLit "atanf"
MO_F32_Sinh -> fsLit "sinhf"
MO_F32_Cosh -> fsLit "coshf"
MO_F32_Tanh -> fsLit "tanhf"
MO_F64_Exp -> fsLit "exp"
MO_F64_Log -> fsLit "log"
MO_F64_Sqrt -> fsLit "sqrt"
MO_F64_Fabs -> unsupported
MO_F64_Pwr -> fsLit "pow"
MO_F64_Sin -> fsLit "sin"
MO_F64_Cos -> fsLit "cos"
MO_F64_Tan -> fsLit "tan"
MO_F64_Asin -> fsLit "asin"
MO_F64_Acos -> fsLit "acos"
MO_F64_Atan -> fsLit "atan"
MO_F64_Sinh -> fsLit "sinh"
MO_F64_Cosh -> fsLit "cosh"
MO_F64_Tanh -> fsLit "tanh"
MO_UF_Conv w -> fsLit $ word2FloatLabel w
MO_Memcpy _ -> fsLit "memcpy"
MO_Memset _ -> fsLit "memset"
MO_Memmove _ -> fsLit "memmove"
MO_Memcmp _ -> fsLit "memcmp"
MO_BSwap w -> fsLit $ bSwapLabel w
MO_PopCnt w -> fsLit $ popCntLabel w
MO_Clz w -> fsLit $ clzLabel w
MO_Ctz w -> fsLit $ ctzLabel w
MO_AtomicRMW w amop -> fsLit $ atomicRMWLabel w amop
MO_Cmpxchg w -> fsLit $ cmpxchgLabel w
MO_AtomicRead w -> fsLit $ atomicReadLabel w
MO_AtomicWrite w -> fsLit $ atomicWriteLabel w
MO_S_QuotRem {} -> unsupported
MO_U_QuotRem {} -> unsupported
MO_U_QuotRem2 {} -> unsupported
MO_Add2 {} -> unsupported
MO_SubWordC {} -> unsupported
MO_AddIntC {} -> unsupported
MO_SubIntC {} -> unsupported
MO_U_Mul2 {} -> unsupported
MO_WriteBarrier -> unsupported
MO_Touch -> unsupported
(MO_Prefetch_Data _) -> unsupported
where unsupported = panic ("outOfLineCmmOp: " ++ show mop
++ " not supported here")
| ezyang/ghc | compiler/nativeGen/SPARC/CodeGen.hs | bsd-3-clause | 22,667 | 0 | 29 | 7,368 | 4,663 | 2,315 | 2,348 | 390 | 52 |
module Punk where
import Control.Exception.Base
import Network.Socket
main' port = do
hostaddr <- inet_addr "0.0.0.0"
asocket <- socket AF_INET Stream defaultProtocol
let sockaddr = SockAddrInet port hostaddr
bindSocket asocket sockaddr
listen asocket 1
bracket (accept asocket) (\(conn, address) -> do
print conn
print address)
(\(conn, _) ->
close conn)
main = do
main' 3000
| hlian/punk | src/Punk.hs | bsd-3-clause | 471 | 0 | 12 | 148 | 147 | 71 | 76 | 16 | 1 |
-- File created: 2009-08-05 20:14:14
module Haschoo.Evaluator.Standard.Strings (procedures, isString, strToList)
where
import Control.Applicative ((<$>))
import Control.Arrow ((&&&))
import Control.Monad (join, liftM2)
import Data.Array.IArray ((!), bounds, elems)
import Data.Array.IO (IOUArray)
import Data.Array.MArray ( readArray, writeArray
, newArray, newListArray
, getBounds, getElems
, freeze, thaw)
import Data.Array.Unboxed (UArray)
import Data.Array.Unsafe (unsafeFreeze, unsafeThaw)
import Data.Char (isLetter, toLower)
import Data.Foldable (foldrM)
import Data.Function (on)
import Haschoo.Types ( ScmValue(..), toScmMString
, listToPair, pairToList)
import Haschoo.Utils (ErrOr, ($<), (.:), mapOnPairs)
import Haschoo.Evaluator.Utils ( tooFewArgs, tooManyArgs, immutable
, notChar, notInt, notList, notString)
procedures :: [(String, ScmValue)]
procedures = map (\(a,b) -> (a, ScmFunc a b))
[ ("string?", return . fmap ScmBool . scmIsString)
, ("make-string", scmMakeString)
, ("string", scmString)
, ("string-length", scmLength)
, ("string-ref", scmRef)
, ("string-set!", scmSet)
, "string=?" $< id &&& fmap (fmap ScmBool) .: scmCompare (==) (,)
, "string<?" $< id &&& fmap (fmap ScmBool) .: scmCompare (<) (,)
, "string>?" $< id &&& fmap (fmap ScmBool) .: scmCompare (>) (,)
, "string<=?" $< id &&& fmap (fmap ScmBool) .: scmCompare (<=) (,)
, "string>=?" $< id &&& fmap (fmap ScmBool) .: scmCompare (>=) (,)
, "string-ci=?" $< id &&& fmap (fmap ScmBool) .: scmCompare (==) lower
, "string-ci<?" $< id &&& fmap (fmap ScmBool) .: scmCompare (<) lower
, "string-ci>?" $< id &&& fmap (fmap ScmBool) .: scmCompare (>) lower
, "string-ci<=?" $< id &&& fmap (fmap ScmBool) .: scmCompare (<=) lower
, "string-ci>=?" $< id &&& fmap (fmap ScmBool) .: scmCompare (>=) lower
, ("substring", scmSubstring)
, ("string-append", scmAppend)
, ("string->list", scmToList)
, ("list->string", scmFromList)
, ("string-copy", scmCopy)
, ("string-fill!", scmFill)
]
where
lower a b = if isLetter a && isLetter b
then (toLower a, toLower b)
else (a,b)
scmIsString :: [ScmValue] -> ErrOr Bool
scmIsString [x] = Right (isString x)
scmIsString [] = tooFewArgs "string?"
scmIsString _ = tooManyArgs "string?"
scmMakeString, scmString :: [ScmValue] -> IO (ErrOr ScmValue)
scmMakeString (ScmInt l : xs) =
case xs of
[] -> f (flip newArray '*')
[ScmChar c] -> f (flip newArray c)
[_] -> return$ notChar "make-string"
_ -> return$ tooManyArgs "make-string"
where
f mk = tryToLen "make-string" l $ \i -> ScmMString <$> mk (0, i-1)
scmMakeString [_, ScmChar _] = return$ notInt "make-string"
scmMakeString (_:_:_:_) = return$ tooManyArgs "make-string"
scmMakeString [] = return$ tooFewArgs "make-string"
scmMakeString _ = return$ notChar "make-string"
scmString xs = case mapM (fromChar "string") xs of
Left e -> return$ Left e
Right s -> fmap Right $ toScmMString s
scmLength :: [ScmValue] -> IO (ErrOr ScmValue)
scmLength [x] = case x of
ScmString s -> Right . ScmInt . toInteger <$> sLen s
ScmMString s -> Right . ScmInt . toInteger <$> msLen s
_ -> return$ notString "string-length"
scmLength [] = return$ tooFewArgs "string-length"
scmLength _ = return$ tooManyArgs "string-length"
scmRef, scmSet :: [ScmValue] -> IO (ErrOr ScmValue)
scmRef [x, ScmInt i] = case x of
ScmString s -> f (sLen s) (return . (s!))
ScmMString s -> f (msLen s) (readArray s)
_ -> return$ notString "string-ref"
where
f len = fmap (fmap ScmChar) . tryToIdx "string-ref" len i
scmRef [_,_] = return$ notInt "string-ref"
scmRef (_:_:_) = return$ tooManyArgs "string-ref"
scmRef _ = return$ tooFewArgs "string-ref"
scmSet [x, ScmInt idx, ScmChar c] =
case x of
ScmMString s -> do
tryToIdx "string-set!" (msLen s) idx (\i -> writeArray s i c)
return (Right ScmVoid)
ScmString _ -> return$ immutable "string-set!"
_ -> return$ notString "string-set!"
scmSet [_, _, ScmChar _] = return$ notInt "string-set!"
scmSet [_, _, _] = return$ notChar "string-set!"
scmSet (_:_:_:_) = return$ tooManyArgs "string-set!"
scmSet _ = return$ tooFewArgs "string-set!"
scmCompare :: (String -> String -> Bool)
-> (Char -> Char -> (Char, Char))
-> String
-> [ScmValue] -> IO (ErrOr Bool)
scmCompare p f s [a, b] =
if isString a && isString b
then Right <$> (liftM2 (uncurry p .: mapOnPairs f `on` elems) `on` conv)
a b
else return$ notString s
where
conv (ScmString x) = return x
conv (ScmMString x) = unsafeFreeze x
conv _ = error $ s ++ " :: the impossible happpened"
scmCompare _ _ s (_:_:_) = return$ tooManyArgs s
scmCompare _ _ s _ = return$ tooFewArgs s
scmSubstring :: [ScmValue] -> IO (ErrOr ScmValue)
scmSubstring [x, ScmInt a, ScmInt b] =
case x of
ScmMString s -> f (msLen s) (getElems s)
ScmString s -> f (sLen s) (return $ elems s)
_ -> return$ notString "substring"
where
f mlen els = mlen >>= \len ->
fmap join $
tryRange 0 (toInteger len) "substring" b $ \b' ->
tryRange 0 (toInteger b') "substring" a $ \a' ->
fmap ScmMString $ els >>= newListArray (0, b'-a'-1) . drop a'
scmSubstring [_, _, _] = return$ notInt "substring"
scmSubstring (_:_:_:_) = return$ tooManyArgs "substring"
scmSubstring _ = return$ tooFewArgs "substring"
scmAppend :: [ScmValue] -> IO (ErrOr ScmValue)
scmAppend args = do
x <- foldrM f (Right (0, "")) args
case x of
Left err -> return (Left err)
Right (len, cat) -> Right . ScmMString <$> newListArray (0, len-1) cat
where
f (ScmString a) (Right x) = make (sLen a) (return $ elems a) x
f (ScmMString a) (Right x) = make (msLen a) (getElems a) x
f _ (Left err) = return (Left err)
f _ _ = return$ notString "string-append"
make ml me (n,s) = ml >>= \l -> me >>= \e -> return.Right $ (n+l, e++s)
scmToList, scmFromList :: [ScmValue] -> IO (ErrOr ScmValue)
scmToList [x] | isString x =
fmap (Right . fst) . listToPair . map ScmChar =<< strToList x
scmToList [_] = return$ notString "string->list"
scmToList [] = return$ tooFewArgs "string->list"
scmToList _ = return$ tooManyArgs "string->list"
scmFromList [x] =
case x of
ScmList l -> f l
p@(ScmPair _ _) -> do
l <- pairToList p
case l of
Left _ -> return$ notList "list->string"
Right (ScmList l') -> f l'
_ -> error "list->string :: the impossible happened"
_ -> return$ notList "list->string"
where
f l = case mapM (fromChar "list->string") l of
Left e -> return$ Left e
Right s -> Right <$> toScmMString s
scmFromList [] = return$ tooFewArgs "list->string"
scmFromList _ = return$ tooManyArgs "list->string"
scmCopy :: [ScmValue] -> IO (ErrOr ScmValue)
scmCopy [ScmString s] = Right . ScmMString <$> thaw s
scmCopy [ScmMString s] =
Right . ScmMString <$>
(freeze s >>= \a -> unsafeThaw (a :: UArray Int Char))
scmCopy [_] = return$ notString "string-copy"
scmCopy [] = return$ tooFewArgs "string-copy"
scmCopy _ = return$ tooManyArgs "string-copy"
scmFill :: [ScmValue] -> IO (ErrOr ScmValue)
scmFill [x, ScmChar c] =
case x of
ScmMString s -> do
(a,b) <- getBounds s
mapM_ (\i -> writeArray s i c) [a..b]
return (Right ScmVoid)
ScmString _ -> return$ immutable "string-fill!"
_ -> return$ notString "string-fill!"
scmFill [_, _] = return$ notChar "string-fill!"
scmFill (_:_:_) = return$ tooManyArgs "string-fill!"
scmFill _ = return$ tooFewArgs "string-fill!"
------
isString :: ScmValue -> Bool
isString (ScmString _) = True
isString (ScmMString _) = True
isString _ = False
strToList :: ScmValue -> IO String
strToList (ScmString s) = return (elems s)
strToList (ScmMString s) = getElems s
strToList _ = error "strToList :: the impossible happened"
tryToLen :: String -> Integer -> (Int -> IO a) -> IO (ErrOr a)
tryToLen = tryRange 0 (toInteger (maxBound :: Int))
tryToIdx :: String -> IO Int -> Integer -> (Int -> IO a) -> IO (ErrOr a)
tryToIdx s mlen i f = mlen >>= \len -> tryRange 0 (toInteger len - 1) s i f
tryRange :: Integer -> Integer -> String -> Integer -> (Int -> IO a)
-> IO (ErrOr a)
tryRange a b s i f = if i >= a && i <= b
then Right <$> f (fromInteger i)
else return.Left $ "Out-of-range integer to " ++ s
fromChar :: String -> ScmValue -> ErrOr Char
fromChar _ (ScmChar c) = Right c
fromChar s _ = notChar s
sLen :: UArray Int Char -> IO Int
sLen = return . (+1) . snd . bounds
msLen :: IOUArray Int Char -> IO Int
msLen = fmap ((+1) . snd) . getBounds
| Deewiant/haschoo | Haschoo/Evaluator/Standard/Strings.hs | bsd-3-clause | 9,576 | 2 | 18 | 2,806 | 3,705 | 1,905 | 1,800 | 197 | 6 |
module Scheme.Evaluator (
eval, evalMacro,
runScm, Scm,
initScmStates,
initScmEnv,
initScmRef,
) where
import Scheme.DataType
import Scheme.Evaluator.Micro
import Scheme.Evaluator.Prelude
import Scheme.Evaluator.Prelude2
import Scheme.Evaluator.IO
import Scheme.Evaluator.Chaitin
import qualified Data.Map as M
initGEnv :: GEnv
initGEnv = microGEnv
`M.union` preludeGEnv
`M.union` prelude2GEnv
`M.union` chaitinGEnv
`M.union` ioGEnv
initScmStates :: ScmStates
initScmStates = (initGEnv, initMetaData)
where
initMetaData :: MetaData
initMetaData = MetaData [] initStackTrace
initScmEnv :: ScmEnv
initScmEnv = (Nothing, initMetaInfo)
where
initMetaInfo :: MetaInfo
initMetaInfo = MetaInfo initConfig Nothing
initScmRef :: ScmRef
initScmRef = initReference "Scm"
| ocean0yohsuke/Scheme | src/Scheme/Evaluator.hs | bsd-3-clause | 834 | 0 | 8 | 156 | 196 | 121 | 75 | 29 | 1 |
--------------------------------------------------------------------------------
-- |
-- Module : Database.EventStore
-- Copyright : (C) 2019 Yorick Laupa
-- License : (see the file LICENSE)
--
-- Maintainer : Yorick Laupa <yo.eight@gmail.com>
-- Stability : provisional
-- Portability : non-portable
--
--------------------------------------------------------------------------------
module Database.EventStore
( -- * Connection
Connection
, ConnectionType(..)
, Credentials
, Settings(..)
, Retry
, atMost
, keepRetrying
, credentials
, defaultSettings
, defaultSSLSettings
, connect
, shutdown
, waitTillClosed
, connectionSettings
-- * Cluster Connection
, ClusterSettings(..)
, DnsServer(..)
, GossipSeed
, gossipSeed
, gossipSeedWithHeader
, gossipSeedHost
, gossipSeedHeader
, gossipSeedPort
, gossipSeedClusterSettings
, dnsClusterSettings
-- * Event
, Event
, EventData
, EventType(..)
, createEvent
, withJson
, withJsonAndMetadata
, withBinary
, withBinaryAndMetadata
-- * Event number
, EventNumber
, streamStart
, streamEnd
, eventNumber
, rawEventNumber
, eventNumberToInt64
-- * Read Operations
, StreamMetadataResult(..)
, BatchResult
, ResolveLink(..)
, readEvent
, readEventsBackward
, readEventsForward
, getStreamMetadata
-- * Write Operations
, StreamACL(..)
, StreamMetadata(..)
, getCustomPropertyValue
, getCustomProperty
, emptyStreamACL
, emptyStreamMetadata
, deleteStream
, sendEvent
, sendEvents
, setStreamMetadata
-- * Builder
, Builder
-- * Stream ACL Builder
, StreamACLBuilder
, buildStreamACL
, modifyStreamACL
, setReadRoles
, setReadRole
, setWriteRoles
, setWriteRole
, setDeleteRoles
, setDeleteRole
, setMetaReadRoles
, setMetaReadRole
, setMetaWriteRoles
, setMetaWriteRole
-- * Stream Metadata Builder
, StreamMetadataBuilder
, buildStreamMetadata
, modifyStreamMetadata
, setMaxCount
, setMaxAge
, setTruncateBefore
, setCacheControl
, setACL
, modifyACL
, setCustomProperty
-- * Transaction
, Transaction
, TransactionId
, startTransaction
, transactionId
, transactionCommit
, transactionRollback
, transactionWrite
-- * Subscription
, SubscriptionClosed(..)
, SubscriptionStream(..)
, Subscription
, SubDropReason(..)
, SubDetails
, SubAction(..)
, unsubscribe
, nextSubEvent
, streamSubEvents
, streamSubResolvedEvents
-- * Volatile Subscription
, RegularSubscription
, subscribe
-- * Catch-up Subscription
, CatchupSubscription
, subscribeFrom
-- * Persistent Subscription
, PersistentSubscription
, PersistentSubscriptionSettings(..)
, SystemConsumerStrategy(..)
, NakAction(..)
, PersistActionException(..)
, acknowledge
, acknowledgeEvents
, failed
, eventsFailed
, notifyEventsProcessed
, notifyEventsFailed
, defaultPersistentSubscriptionSettings
, createPersistentSubscription
, updatePersistentSubscription
, deletePersistentSubscription
, connectToPersistentSubscription
-- * Results
, Slice(..)
, sliceEvents
, sliceEOS
, sliceNext
, emptySlice
, AllSlice
, Op.DeleteResult(..)
, WriteResult(..)
, ReadResult(..)
, RecordedEvent(..)
, Op.ReadEvent(..)
, StreamSlice
, Position(..)
, ReadDirection(..)
, ResolvedEvent(..)
, OperationError(..)
, StreamId(..)
, StreamName
, isAllStream
, isEventResolvedLink
, resolvedEventOriginal
, resolvedEventDataAsJson
, resolvedEventOriginalStreamId
, resolvedEventOriginalId
, resolvedEventOriginalEventNumber
, recordedEventDataAsJson
, positionStart
, positionEnd
-- * Logging
, LogLevel(..)
, LogType(..)
, LoggerFilter(..)
-- * Monitoring
, MonitoringBackend(..)
, noopMonitoringBackend
-- * Misc
, Command
, DropReason(..)
, ExpectedVersion
, anyVersion
, noStreamVersion
, emptyStreamVersion
, exactEventVersion
, streamExists
, msDiffTime
-- * Re-export
, (<>)
, NonEmpty(..)
, nonEmpty
, TLSSettings
, NominalDiffTime
) where
--------------------------------------------------------------------------------
import Data.List.NonEmpty(NonEmpty(..), nonEmpty)
--------------------------------------------------------------------------------
import Network.Connection (TLSSettings)
--------------------------------------------------------------------------------
import Database.EventStore.Internal
import Database.EventStore.Internal.Command
import Database.EventStore.Internal.Discovery
import Database.EventStore.Internal.Logger
import Database.EventStore.Internal.Prelude
import Database.EventStore.Internal.Operation (OperationError(..))
import qualified Database.EventStore.Internal.Operations as Op
import Database.EventStore.Internal.Operation.Read.Common
import Database.EventStore.Internal.Operation.Write.Common
import Database.EventStore.Internal.Settings
import Database.EventStore.Internal.Stream
import Database.EventStore.Internal.Subscription.Api
import Database.EventStore.Internal.Subscription.Catchup
import Database.EventStore.Internal.Subscription.Message
import Database.EventStore.Internal.Subscription.Persistent
import Database.EventStore.Internal.Subscription.Types
import Database.EventStore.Internal.Subscription.Regular
import Database.EventStore.Internal.Types
| YoEight/eventstore | Database/EventStore.hs | bsd-3-clause | 5,931 | 0 | 6 | 1,424 | 847 | 596 | 251 | 185 | 0 |
module PropToBdd
( evalBdd
, synthesizeBdd
) where
import qualified Cudd
import Prop
import PropCSE
import PropEval
import HsCuddPrelude
import qualified Data.Map as Map
import Data.Map (Map, (!))
--import Debug.Trace (trace)
--import Text.Printf (printf)
evalBdd :: Assignment Int -> Cudd.Mgr -> Cudd.Bdd -> IO Bool
evalBdd assigns mgr bdd = do
nVars <- Cudd.numVars mgr
true' <- Cudd.bddTrue mgr
assigns' <- foldM (\b i -> do i' <- Cudd.bddIthVar mgr i
if isTrue i assigns
then Cudd.bddAnd b i'
else Cudd.bddAnd b =<< Cudd.bddNot i')
true' [0..nVars - 1]
res <- Cudd.bddRestrict bdd assigns'
Cudd.bddToBool res
---- | Synthesize the sentence of propositional logic into a BDD.
--synthesizeBdd :: Cudd.Mgr -> Prop Int -> IO Cudd.Bdd
--synthesizeBdd mgr = synthesizeBdd'
-- where
-- synthesizeBdd' prop =
-- case prop of
-- PFalse -> Cudd.bddFalse mgr
-- PTrue -> Cudd.bddTrue mgr
-- PVar i -> Cudd.bddIthVar mgr i
-- PNot p -> Cudd.bddNot =<< synthesizeBdd' p
-- PAnd p1 p2 -> bin Cudd.bddAnd p1 p2
-- POr p1 p2 -> bin Cudd.bddOr p1 p2
-- PXor p1 p2 -> bin Cudd.bddXor p1 p2
-- PNand p1 p2 -> bin Cudd.bddNand p1 p2
-- PNor p1 p2 -> bin Cudd.bddNor p1 p2
-- PXnor p1 p2 -> bin Cudd.bddXnor p1 p2
-- PIte p1 p2 p3 -> bin Cudd.bddIte p1 p2 p3
-- bin f p1 p2 = join $ f <$> synthesizeBdd' p1 <*> synthesizeBdd' p2
type SynthesisMap = Map Idx Cudd.Bdd
-- | Synthesize the sentence of propositional logic into a BDD,
-- with a CSE pass first, and lowest-first scheduling.
synthesizeBdd :: Cudd.Mgr -> Prop Int -> IO Cudd.Bdd
synthesizeBdd mgr prop = do
--trace (printf "prop: %s" (show prop)) $ do
--trace (printf "schedule: %s" (show schedule)) $ do
--trace (printf "root: %s" (show root)) $ do
endMap <- foldM synthesize Map.empty (lowestFirstSchedule prop')
return (endMap ! rootIndex prop')
where
prop' :: CSEProp Int
prop' = cse prop
synthesize :: SynthesisMap -> (Idx, Prop' Int) -> IO SynthesisMap
synthesize done (i, p) =
--trace (printf "synthesizing %s" (show (i, p))) $
(\v -> Map.insert i v done) <$> case p of
PHCFalse -> Cudd.bddFalse mgr
PHCTrue -> Cudd.bddTrue mgr
PHCVar v -> Cudd.bddIthVar mgr v
PHCNot i1 -> Cudd.bddNot (done!i1)
PHCAnd i1 i2 -> Cudd.bddAnd (done!i1) (done!i2)
PHCNand i1 i2 -> Cudd.bddNot =<< Cudd.bddAnd (done!i1) (done!i2)
PHCOr i1 i2 -> Cudd.bddOr (done!i1) (done!i2)
PHCNor i1 i2 -> Cudd.bddNot =<< Cudd.bddOr (done!i1) (done!i2)
PHCXor i1 i2 -> Cudd.bddXor (done!i1) (done!i2)
PHCXnor i1 i2 -> Cudd.bddXnor (done!i1) (done!i2)
PHCIte i1 i2 i3 -> Cudd.bddIte (done!i1) (done!i2) (done!i3)
| bradlarsen/hs-cudd | test/PropToBdd.hs | bsd-3-clause | 3,009 | 0 | 16 | 910 | 720 | 374 | 346 | 42 | 11 |
import Data.List
import Network
import System.IO
import System.Exit
import Control.Arrow
import Control.Monad.Reader
import Control.Exception
import Text.Printf
import Bot
import Index
server = "irc.freenode.org"
port = 6667
chan = "#tutbot-testing"
nick = "tutbot"
-- The 'Net' monad, a wrapper over IO, carrying the bot's immutable state.
type Net = ReaderT Bot IO
data Bot = Bot { socket :: Handle }
-- Set up actions to run on start and end, and run the main loop
main :: IO ()
main = bracket connect disconnect loop
where
disconnect = hClose . socket
loop st = runReaderT run st
-- Connect to the server and return the initial bot state
connect :: IO Bot
connect = notify $ do
h <- connectTo server (PortNumber (fromIntegral port))
hSetBuffering h NoBuffering
return (Bot h)
where
notify a = bracket_
(printf "Connecting to %s ... " server >> hFlush stdout)
(putStrLn "done.")
a
-- We're in the Net monad now, so we've connected successfully
-- Join a channel, and start processing commands
run :: Net ()
run = do
write "NICK" nick
write "USER" (nick++" 0 * :tutorial bot")
write "JOIN" chan
asks socket >>= listen
-- Process each line from the server
listen :: Handle -> Net ()
listen h = forever $ do
s <- init `fmap` io (hGetLine h)
io (putStrLn s)
if ping s then pong s else eval (clean s)
where
forever a = a >> forever a
clean = drop 1 . dropWhile (/= ':') . drop 1
ping x = "PING :" `isPrefixOf` x
pong x = write "PONG" (':' : drop 6 x)
-- Dispatch a command
eval :: String -> Net ()
eval "!quit" = write "QUIT" ":Exiting" >> io (exitWith ExitSuccess)
eval x | "!id " `isPrefixOf` x = privmsg (drop 4 x)
eval x | "!index" `isPrefixOf` x = tryIndex x
eval _ = return () -- ignore everything else
-- Send a privmsg to the current chan + server
privmsg :: String -> Net ()
privmsg s = write "PRIVMSG" (chan ++ " :" ++ s)
-- Send a message out to the server we're currently connected to
write :: String -> String -> Net ()
write s t = do
h <- asks socket
io $ hPrintf h "%s %s\r\n" s t
io $ printf "> %s %s\n" s t
-- Convenience.
io :: IO a -> Net a
io = liftIO
| redfish64/IrcScanner | src/IrcScanner/IRCBot.hs | bsd-3-clause | 2,261 | 0 | 13 | 591 | 705 | 353 | 352 | 58 | 2 |
{-# LANGUAGE EmptyDataDecls, TypeSynonymInstances #-}
{-# OPTIONS_GHC -fcontext-stack52 #-}
module Games.Chaos2010.Database.Live_wizards where
import Games.Chaos2010.Database.Fields
import Games.Chaos2010.Database.Fields
import Games.Chaos2010.Database.Fields
import Games.Chaos2010.Database.Fields
import Database.HaskellDB.DBLayout
type Live_wizards =
Record
(HCons (LVPair Wizard_name (Expr (Maybe String)))
(HCons (LVPair Shadow_form (Expr (Maybe Bool)))
(HCons (LVPair Magic_sword (Expr (Maybe Bool)))
(HCons (LVPair Magic_knife (Expr (Maybe Bool)))
(HCons (LVPair Magic_shield (Expr (Maybe Bool)))
(HCons (LVPair Magic_wings (Expr (Maybe Bool)))
(HCons (LVPair Magic_armour (Expr (Maybe Bool)))
(HCons (LVPair Magic_bow (Expr (Maybe Bool)))
(HCons (LVPair Computer_controlled (Expr (Maybe Bool)))
(HCons (LVPair Original_place (Expr (Maybe Int)))
(HCons (LVPair Expired (Expr (Maybe Bool)))
(HCons (LVPair Place (Expr (Maybe Int))) HNil))))))))))))
live_wizards :: Table Live_wizards
live_wizards = baseTable "live_wizards" | JakeWheat/Chaos-2010 | Games/Chaos2010/Database/Live_wizards.hs | bsd-3-clause | 1,324 | 0 | 35 | 401 | 405 | 213 | 192 | 24 | 1 |
{-# LANGUAGE CPP #-}
-- | A @TimeZoneSeries@ describes a timezone by specifying the various
-- clock settings that occurred in the past and are scheduled to occur
-- in the future for the timezone.
module Data.Time.LocalTime.TimeZone.Series
(
-- * Representing a timezone
-- $abouttzs
TimeZoneSeries(..),
timeZoneFromSeries,
isValidLocalTime,
isRedundantLocalTime,
latestNonSummer,
-- ** Converting between UTC and local time
-- $aboutfuncs
utcToLocalTime',
localTimeToUTC',
-- * Representing a moment in a timezone
ZoneSeriesTime(..),
zonedTimeToZoneSeriesTime,
zoneSeriesTimeToLocalTime,
zoneSeriesTimeZone,
localTimeToZoneSeriesTime
)
where
import Data.Time (UTCTime, LocalTime, TimeZone(timeZoneSummerOnly),
ZonedTime(ZonedTime),
utcToLocalTime, localTimeToUTC)
#if MIN_VERSION_time(1,9,1)
import Data.Time.Format.Internal
( FormatTime(formatCharacter)
, ParseTime( buildTime
, parseTimeSpecifier
, substituteTimeSpecifier
)
)
#else
import Data.Time (FormatTime(formatCharacter), ParseTime(buildTime))
#endif
import Data.List (partition)
import Data.Maybe (listToMaybe, fromMaybe)
import Data.Proxy (Proxy(Proxy))
import Data.Typeable (Typeable)
import Control.Arrow (first)
import Control.DeepSeq (NFData(..))
-- $abouttzs
-- A @TimeZoneSeries@ describes a timezone with a set of 'TimeZone'
-- objects. Each @TimeZone@ object describes the clock setting in the
-- timezone for a specific period of history during which the clocks
-- do not change.
--
-- Most operating systems provide information about timezone series
-- for the local timezone and for many other timezones of the world.
-- On MS Windows systems, this information can be read from the
-- registry. On other systems, this information is typically provided
-- in the form of Olson timezone files: \/etc\/localtime (or some
-- other file) for the local timezone, and files located in
-- \/usr\/share\/zoneinfo\/ or \/etc\/zoneinfo\/ (or some other
-- directory) for other timezones.
-- | A @TimeZoneSeries@ consists of a default @TimeZone@ object and a
-- sequence of pairs of a @UTCTime@ and a @TimeZone@ object. Each
-- @UTCTime@ indicates a moment at which the clocks changed, and the
-- corresponding @TimeZone@ object describes the new state of the
-- clocks after the change. The default @TimeZone@ object is used for
-- times preceding the earliest @UTCTime@, or if the sequence of pairs
-- is empty. The times in the sequence are in order from latest to
-- earlist (note that this is the opposite of the way that they are
-- stored in an Olson timezone file).
data TimeZoneSeries =
TimeZoneSeries {
tzsTimeZone :: TimeZone,
-- ^ The default timezone state
tzsTransitions :: [(UTCTime, TimeZone)]
-- ^ A list of pairs of the time of a
-- change of clocks and the new timezone
-- state after the change
}
deriving (Eq, Ord, Typeable)
instance Show TimeZoneSeries where
show = show . latestNonSummer
instance Read TimeZoneSeries where
readsPrec n = map (first $ flip TimeZoneSeries []) . readsPrec n
instance NFData TimeZoneSeries where
rnf tzs = rnf (tzsTimeZone tzs, tzsTransitions tzs)
instance ParseTime TimeZoneSeries where
buildTime locale = mapBuiltTime (flip TimeZoneSeries []) . buildTime locale
#if MIN_VERSION_time(1,9,1)
parseTimeSpecifier _ = parseTimeSpecifier (Proxy :: Proxy TimeZone)
substituteTimeSpecifier _ =
substituteTimeSpecifier (Proxy :: Proxy TimeZone)
#endif
#if MIN_VERSION_time(1,6,0)
mapBuiltTime :: Functor f => (a -> b) -> f a -> f b
mapBuiltTime = fmap
#else
mapBuiltTime :: a -> a
mapBuiltTime = id
#endif
-- | The latest non-summer @TimeZone@ in a @TimeZoneSeries@ is in some
-- sense representative of the timezone.
latestNonSummer :: TimeZoneSeries -> TimeZone
latestNonSummer (TimeZoneSeries d cs) = fromMaybe d . listToMaybe $
filter (not . timeZoneSummerOnly) tzs ++ tzs
where
tzs = map snd cs
instance FormatTime TimeZoneSeries where
formatCharacter =
fmap (mapFormatCharacter latestNonSummer) .
formatCharacter
#if MIN_VERSION_time(1,9,1)
mapFormatCharacter ::
(a -> b) -> Maybe (x -> b -> String) -> Maybe (x -> a -> String)
mapFormatCharacter f = fmap (\g x -> g x . f)
#elif MIN_VERSION_time(1,8,0)
mapFormatCharacter ::
(a -> b) -> (c -> d -> e -> b -> z) -> c -> d -> e -> a -> z
mapFormatCharacter f g locale mpado mwidth = g locale mpado mwidth . f
#else
mapFormatCharacter :: (a -> b) -> (c -> d -> b -> z) -> c -> d -> a -> z
mapFormatCharacter f g locale mpado = g locale mpado . f
#endif
-- | Given a timezone represented by a @TimeZoneSeries@, and a @UTCTime@,
-- provide the state of the timezone's clocks at that time.
timeZoneFromSeries :: TimeZoneSeries -> UTCTime -> TimeZone
timeZoneFromSeries (TimeZoneSeries dfault changes) t = fromMaybe dfault .
fmap snd . listToMaybe . dropWhile ((> t) . fst) $ changes
-- The following functions attempt to deal correctly with corner cases
-- where multiple clock changes overlap with each other, even though
-- as far as I know such weird cases have never actually occurred in
-- any timezone. So far.
--
-- The theorem is that if G is the set of individual time changes
-- for which t is invalid ("in the Gap"), and O is the set of
-- individual time changes for which t is redundant ("in the Overlap"),
-- then t is invalid for the full set of changes iff #G > #O, and
-- t is redundant for the full set of changes iff #G < #O.
-- A proof for this theorem, supplied by Aristid Breitkreuz,
-- is available at:
-- http://projects.haskell.org/time-ng/gaps_and_overlaps.html
-- | When a clock change moves the clock forward, local times that
-- are between the wall clock time before the change and the wall
-- clock time after the change cannot occur.
isValidLocalTime :: TimeZoneSeries -> LocalTime -> Bool
isValidLocalTime tzs lt = gapsVsOverlaps tzs lt /= GT
-- | When a clock change moves the clock backward, local times that
-- are between the wall clock time before the change and the wall
-- clock time after the change occur twice.
isRedundantLocalTime :: TimeZoneSeries -> LocalTime -> Bool
isRedundantLocalTime tzs lt = gapsVsOverlaps tzs lt == LT
-- Compare the number of gaps to the number of overlaps in the
-- timezone series for the given local time, as described above.
gapsVsOverlaps :: TimeZoneSeries -> LocalTime -> Ordering
gapsVsOverlaps tzs@(TimeZoneSeries d cs) lt = compareLengths gaps overlaps
where
(gaps, overlaps) = partition (uncurry (<)) relevantIntervals
relevantIntervals = takeWhile notTooEarly . dropWhile tooLate $
gapsAndOverlaps tzs
tooLate (a, b) = a > lt && b > lt
notTooEarly (a, b) = a > lt || b > lt
-- Each pair (ltBefore, ltAfter) represents a time change
-- where the clock is moved from ltBefore to ltAfter. If
-- ltBefore < ltAfter the clock moves forward for that clock
-- change, and otherwise backward.
gapsAndOverlaps :: TimeZoneSeries -> [(LocalTime, LocalTime)]
gapsAndOverlaps (TimeZoneSeries d cs) = zip
(zipWith utcToLocalTime (map snd (drop 1 cs) ++ [d]) (map fst cs))
(map (uncurry $ flip utcToLocalTime) cs)
-- Fast lazy comparison of list lengths
compareLengths :: [a] -> [a] -> Ordering
compareLengths (_:xs) (_:ys) = compareLengths xs ys
compareLengths (_:_ ) _ = GT
compareLengths _ (_:_ ) = LT
compareLengths _ _ = EQ
-- | A @ZoneSeriesTime@ represents a moment of time in the context of
-- a particular timezone.
data ZoneSeriesTime = ZoneSeriesTime {
zoneSeriesTimeToUTC :: UTCTime,
zoneSeriesTimeSeries :: TimeZoneSeries
}
deriving (Eq, Ord, Typeable)
instance Show ZoneSeriesTime where
show tzs = show $ ZonedTime (zoneSeriesTimeToLocalTime tzs)
(zoneSeriesTimeZone tzs)
instance Read ZoneSeriesTime where
readsPrec n = map (first zonedTimeToZoneSeriesTime) . readsPrec n
instance ParseTime ZoneSeriesTime where
buildTime locale = mapBuiltTime zonedTimeToZoneSeriesTime . buildTime locale
#if MIN_VERSION_time(1,9,1)
parseTimeSpecifier _ = parseTimeSpecifier (Proxy :: Proxy ZonedTime)
substituteTimeSpecifier _ =
substituteTimeSpecifier (Proxy :: Proxy ZonedTime)
#endif
instance FormatTime ZoneSeriesTime where
formatCharacter =
fmap (mapFormatCharacter zoneSeriesTimeToZonedTime) .
formatCharacter
-- | The @ZonedTime@ of a @ZoneSeriesTime@.
zoneSeriesTimeToZonedTime :: ZoneSeriesTime -> ZonedTime
zoneSeriesTimeToZonedTime zst =
ZonedTime (zoneSeriesTimeToLocalTime zst) (zoneSeriesTimeZone zst)
-- | Use a trivial @TimeZoneSeries@ containing only the @TimeZone@
-- of the @ZonedTime@, and use it to define a @ZoneSeriesTime@.
zonedTimeToZoneSeriesTime :: ZonedTime -> ZoneSeriesTime
zonedTimeToZoneSeriesTime (ZonedTime t tz) =
ZoneSeriesTime (localTimeToUTC tz t) (TimeZoneSeries tz [])
-- | The local time represented by a @ZoneSeriesTime@
zoneSeriesTimeToLocalTime :: ZoneSeriesTime -> LocalTime
zoneSeriesTimeToLocalTime (ZoneSeriesTime t tzs) = utcToLocalTime' tzs t
-- | The @TimeZone@ that is in effect at the moment represented by
-- a @ZoneSeriesTime@.
zoneSeriesTimeZone :: ZoneSeriesTime -> TimeZone
zoneSeriesTimeZone (ZoneSeriesTime t tzs) = timeZoneFromSeries tzs t
-- | The @ZoneSeriesTime@ that represents the given local time in the
-- given timezone. Local times that are invalid or redundant are treated
-- as described below.
localTimeToZoneSeriesTime :: TimeZoneSeries -> LocalTime -> ZoneSeriesTime
localTimeToZoneSeriesTime tzs lt = ZoneSeriesTime (localTimeToUTC' tzs lt) tzs
-- $aboutfuncs
-- The following functions are variants on functions in
-- "Data.Time.LocalTime" that convert between UTC and local time. The
-- originals can give a wrong result if the 'TimeZone' used for the
-- conversion is not actually in effect at the specified time. These
-- variants use a 'TimeZoneSeries' instead of a 'TimeZone'.
--
-- When converting from an invalid local time, the local time is
-- interpreted as if the time change that made it invalid never
-- happened. When converting from a redundant local time, the latest
-- possible interpretation is used. Use the functions
-- 'isValidLocalTime' and 'isRedundantLocalTime' to detect these
-- conditions.
-- | Convert a UTC time to local time using the "TimeZone" that is in
-- effect at that time in the timezone represented by TimeZoneSeries.
utcToLocalTime' :: TimeZoneSeries -> UTCTime -> LocalTime
utcToLocalTime' tzs utc = utcToLocalTime (timeZoneFromSeries tzs utc) utc
-- | Convert a local time to UTC using the "TimeZone" that is in
-- effect at that time in the timezone represented by TimeZoneSeries.
-- Local times that are invalid or redundant are treated as described above.
localTimeToUTC' :: TimeZoneSeries -> LocalTime -> UTCTime
localTimeToUTC' (TimeZoneSeries dfault changes) lt =
fromMaybe (localTimeToUTC dfault lt) . fmap snd . listToMaybe .
dropWhile (uncurry (>)) $
zip (map fst changes) (map (flip localTimeToUTC lt . snd) changes)
| ygale/timezone-series | Data/Time/LocalTime/TimeZone/Series.hs | bsd-3-clause | 11,177 | 0 | 12 | 2,108 | 1,684 | 939 | 745 | 107 | 1 |
{-# LANGUAGE Arrows #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE OverloadedStrings #-}
module Playlistach.Model.Track where
import GHC.Generics (Generic)
import Data.Aeson
import Data.Profunctor.Product.TH
import Control.Arrow
import Database.PostgreSQL.Simple (Connection)
import Database.PostgreSQL.Simple.FromField
import Opaleye
import Playlistach.Model.WithId
import Playlistach.Model.Origin as Origin
data Track' a b c d e f = Track
{ externalId :: a
, title :: b
, duration :: c
, streamUrl :: d
, permalinkUrl :: e
, origin :: f }
makeAdaptorAndInstance "pTrack" ''Track'
type Track = Track' String String Int (Maybe String) (Maybe String) Origin
type TrackColumn = Track'
(Column PGText) (Column PGText) (Column PGInt4)
(Column (Nullable PGText)) (Column (Nullable PGText)) (Column PGInt4)
newtype ClientTrack = ClientTrack Track
instance ToJSON ClientTrack where
toJSON (ClientTrack Track{..}) = object
[ "externalId" .= externalId
, "title" .= title
, "duration" .= duration
, "permalinkUrl" .= permalinkUrl
, "origin" .= toJSON origin ]
instance FromField Origin where
fromField field mbBS = fmap f (fromField field mbBS)
where
f :: Int -> Origin
f 0 = Origin.VK
f 1 = Origin.SC
instance QueryRunnerColumnDefault PGInt4 Origin where
queryRunnerColumnDefault = fieldQueryRunnerColumn
table :: Table (WithIdColumn TrackColumn) (WithIdColumn TrackColumn)
table = Table "tracks" $ withId $ pTrack Track
{ externalId = required "external_id"
, title = required "title"
, duration = required "duration"
, streamUrl = required "stream_url"
, permalinkUrl = required "permalink_url"
, origin = required "origin" }
queryAll :: Query (WithIdColumn TrackColumn)
queryAll = queryTable table
runQ :: Connection -> Query TrackColumn -> IO [Track]
runQ = runQuery
| aemxdp/playlistach | backend/Playlistach/Model/Track.hs | bsd-3-clause | 2,222 | 0 | 10 | 544 | 536 | 299 | 237 | 57 | 1 |
module Servant.API.Vault
( -- $vault
Vault
) where
import Data.Vault.Lazy (Vault)
-- $vault
--
-- | Use 'Vault' in your API types to provide access to the 'Vault'
-- of the request, which is a location shared by middlewares and applications
-- to store arbitrary data. See <https://hackage.haskell.org/package/vault vault>
-- for more details on how to actually use the vault in your handlers
--
-- Example:
--
-- >>> type API = Vault :> Get '[JSON] String
-- $setup
-- >>> import Servant.API
| zerobuzz/servant | servant/src/Servant/API/Vault.hs | bsd-3-clause | 520 | 0 | 5 | 110 | 36 | 28 | 8 | 4 | 0 |
module ExpertData where
b1 = map (0 <) y1
b2 = map (0 <) y2
b3 = expand 1 3001 z1
b4 = expand 1 3001 z2
expand :: Int -> Int -> [Int] -> [Bool]
expand a b [] = replicate (b - a) False
expand a b (x:xs)
| a == b = []
| a == x = True : expand (a+1) b xs
| otherwise = False : expand (a+1) b (x:xs)
y1 =
[1,1,0,0,0,1,1,0,0,0,0,1,1,1,1,1,1,0,0,0
,0,0,1,1,0,1,0,0,1,1,0,0,1,1,0,0,1,1,1,0
,0,0,1,1,1,0,0,1,1,1,0,0,0,1,1,0,1,0,0,1
,1,0,0,1,1,0,0,0,1,1,1,0,0,1,1,0,0,1,1,0
,0,1,1,1,1,1,1,0,0,0,1,1,0,0,0,1,1,0,0,1
,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,0,1,1,1,0
,0,0,1,1,0,0,0,0,1,1,1,1,0,0,1,1,1,0,0,0
,1,1,0,0,1,1,1,1,0,0,0,1,1,0,0,0,1,1,0,0
,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0
,0,1,1,0,0,0,1,1,0,0,1,1,0,0,0,1,1,0,0,1
,1,0,0,1,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,1
,1,0,0,1,1,0,0,1,0,1,1,0,0,0,0,1,0,1,0,0
,1,1,0,0,0,1,1,1,0,0,1,1,0,0,0,1,1,1,1,0
,1,1,0,0,1,1,1,1,1,1,1,0,0,0,1,1,0,0,1,1
,0,0,1,1,0,0,0,0,1,1,0,0,0,1,1,1,0,1,1,0
,0,1,1,1,1,1,1,1,1,0,0,1,1,0,0,0,1,1,0,0
,0,1,1,0,0,1,1,0,0,0,0,1,1,0,0,0,1,1,0,0
,0,1,1,0,0,1,1,1,1,1,1,0,0,1,1,0,0,1,1,1
,0,1,1,0,0,0,1,1,0,0,1,1,0,0,0,1,0,0,0,1
,1,0,0,0,1,1,1,0,0,0,1,1,1,0,1,1,1,1,1,0
,0,0,0,1,1,0,1,0,1,0,0,1,1,1,0,0,1,1,0,0
,0,1,1,1,0,0,1,1,0,0,0,1,0,0,0,1,1,0,0,1
,1,1,0,0,0,0,0,1,1,0,0,0,1,1,0,0,0,1,1,0
,0,0,0,1,1,1,1,1,1,0,0,1,1,1,0,0,1,1,1,0
,0,0,1,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,1,1
]
y2 =
[1,1,0,1,1,0,0,0,1,1,1,0,0,0,1,0,1,0,0,0
,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,0,1,1,1,0
,0,0,1,1,0,0,1,1,0,1,0,0,0,0,1,0,0,0,0,0
,1,1,0,0,0,0,1,0,0,0,0,1,1,0,1,0,1,0,0,0
,1,1,0,1,0,0,1,1,1,0,0,1,1,1,0,0,0,0,1,1
,0,0,0,1,0,0,0,0,1,0,1,0,1,1,0,1,0,0,0,0
,1,1,1,1,0,0,0,1,0,0,0,1,0,1,0,1,1,0,0,0
,1,1,0,1,1,0,1,0,0,0,1,1,0,0,0,1,1,1,0,0
,0,1,1,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,0
,0,0,1,1,0,0,0,1,1,1,1,0,0,0,0,0,0,1,0,0
,0,0,0,1,1,1,1,0,0,0,0,1,0,1,1,0,1,1,0,0
,0,1,0,0,0,0,0,0,1,1,0,0,1,1,1,1,0,1,0,0
,1,1,0,0,1,1,0,0,1,0,1,0,1,0,1,0,0,1,0,0
,0,1,0,0,0,1,1,0,0,0,1,1,1,1,0,1,1,0,0,0
,1,1,0,1,0,1,0,0,0,0,1,0,1,0,0,0,1,1,0,0
,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,0,0,0,1,1
,0,1,0,0,1,1,1,1,1,0,0,1,0,1,0,0,0,1,1,0
,0,0,1,0,1,0,0,0,1,1,0,1,0,0,0,1,0,0,0,0
,1,0,0,0,1,1,0,0,0,1,1,1,0,0,0,1,0,1,0,1
,0,1,0,0,0,1,1,0,1,0,0,1,1,0,0,0,1,0,1,0
,0,0,1,1,0,0,0,1,0,0,1,1,0,0,0,1,0,0,0,0
,1,1,0,1,0,0,0,0,1,1,0,0,0,0,1,1,1,0,0,0
,1,1,1,0,1,0,1,0,1,0,0,0,1,1,1,1,0,0,0,0
,1,1,0,1,0,1,0,0,0,0,0,1,0,1,0,0,0,1,0,0
,0,0,1,0,0,0,1,0,0,0,1,1,0,0,0,1,1,1,0,0
]
z1 :: [Int]
z1 = [2,
8,
11,
14,
17,
20,
23,
24,
27,
30,
31,
34,
37,
40,
43,
54,
57,
60,
80,
83,
86,
89,
92,
95,
98,
101,
104,
107,
113,
116,
119,
122,
125,
146,
149,
152,
155,
194,
197,
200,
203,
206,
221,
271,
274,
276,
279,
282,
285,
288,
291,
300,
303,
306,
309,
312,
315,
318,
324,
330,
331,
334,
337,
340,
343,
355,
361,
364,
366,
375,
381,
384,
387,
390,
393,
396,
399,
402,
405,
408,
411,
414,
417,
420,
423,
426,
429,
432,
435,
438,
441,
442,
445,
448,
451,
454,
457,
460,
463,
466,
469,
472,
475,
478,
491,
493,
496,
499,
502,
505,
506,
509,
512,
515,
521,
525,
544,
547,
556,
557,
560,
567,
570,
579,
582,
591,
608,
611,
625,
628,
638,
641,
651,
653,
656,
659,
682,
710,
713,
716,
719,
722,
725,
728,
737,
740,
743,
764,
786,
789,
806,
820,
823,
825,
850,
853,
868,
871,
874,
880,
904,
907,
919,
922,
923,
926,
937,
939,
959,
962,
965,
974,
986,
989,
992,
1005,
1008,
1027,
1033,
1036,
1039,
1042,
1054,
1060,
1062,
1065,
1068,
1078,
1081,
1084,
1102,
1105,
1108,
1111,
1113,
1115,
1125,
1128,
1130,
1131,
1134,
1149,
1153,
1156,
1168,
1178,
1184,
1193,
1207,
1213,
1216,
1219,
1222,
1223,
1226,
1229,
1232,
1235,
1238,
1241,
1244,
1247,
1262,
1265,
1268,
1271,
1283,
1286,
1292,
1298,
1301,
1304,
1307,
1310,
1313,
1316,
1317,
1329,
1332,
1390,
1391,
1392,
1395,
1398,
1399,
1402,
1404,
1407,
1413,
1416,
1425,
1426,
1432,
1434,
1435,
1449,
1452,
1476,
1482,
1485,
1501,
1504,
1507,
1510,
1513,
1516,
1519,
1521,
1524,
1527,
1530,
1564,
1566,
1569,
1572,
1575,
1585,
1587,
1593,
1594,
1597,
1600,
1603,
1606,
1612,
1613,
1616,
1619,
1622,
1625,
1628,
1650,
1663,
1666,
1669,
1672,
1675,
1681,
1692,
1705,
1708,
1720,
1732,
1735,
1748,
1751,
1760,
1766,
1778,
1822,
1825,
1867,
1870,
1876,
1879,
1883,
1886,
1889,
1907,
1910,
1913,
1916,
1925,
1943,
1946,
1948,
1951,
1954,
1986,
1996,
2012,
2018,
2021,
2024,
2027,
2030,
2033,
2036,
2039,
2042,
2045,
2064,
2070,
2073,
2084,
2085,
2086,
2095,
2099,
2102,
2104,
2114,
2117,
2120,
2123,
2129,
2132,
2134,
2135,
2137,
2140,
2143,
2146,
2149,
2152,
2158,
2161,
2164,
2182,
2188,
2191,
2199,
2202,
2205,
2208,
2214,
2226,
2232,
2235,
2236,
2239,
2242,
2245,
2248,
2259,
2262,
2271,
2272,
2287,
2294,
2297,
2312,
2315,
2318,
2321,
2324,
2327,
2330,
2333,
2336,
2339,
2340,
2343,
2352,
2355,
2358,
2361,
2364,
2370,
2410,
2434,
2437,
2441,
2452,
2455,
2458,
2466,
2484,
2485,
2489,
2494,
2508,
2511,
2519,
2534,
2537,
2540,
2549,
2552,
2555,
2556,
2558,
2561,
2564,
2567,
2570,
2573,
2642,
2661,
2664,
2667,
2670,
2673,
2687,
2709,
2721,
2724,
2730,
2733,
2736,
2741,
2753,
2756,
2772,
2779,
2782,
2788,
2789,
2792,
2795,
2798,
2801,
2802,
2805,
2808,
2810,
2813,
2816,
2819,
2822,
2825,
2828,
2831,
2834,
2837,
2840,
2843,
2846,
2849,
2852,
2855,
2858,
2861,
2890,
2893,
2896,
2908,
2911,
2914,
2917,
2920]
z2 :: [Int]
z2 = [5,
46,
48,
51,
63,
66,
68,
71,
74,
77,
110,
128,
131,
134,
137,
140,
143,
158,
161,
163,
165,
167,
168,
171,
172,
175,
178,
179,
180,
183,
186,
188,
191,
209,
211,
214,
215,
218,
224,
227,
230,
233,
236,
239,
242,
243,
246,
249,
252,
255,
258,
261,
264,
265,
268,
294,
297,
321,
327,
346,
349,
352,
358,
369,
371,
373,
378,
481,
482,
485,
488,
518,
524,
526,
529,
532,
535,
538,
541,
550,
553,
563,
564,
573,
576,
585,
588,
594,
597,
598,
601,
604,
605,
614,
615,
618,
619,
622,
631,
632,
635,
644,
645,
648,
662,
664,
667,
670,
673,
676,
679,
685,
686,
689,
692,
695,
698,
701,
704,
707,
725,
731,
734,
746,
749,
752,
755,
758,
761,
767,
770,
772,
775,
778,
780,
783,
792,
795,
798,
800,
803,
809,
811,
814,
817,
828,
829,
832,
835,
838,
841,
844,
847,
856,
859,
862,
864,
865,
877,
883,
884,
887,
890,
893,
896,
898,
901,
910,
913,
916,
929,
932,
933,
934,
942,
944,
947,
950,
951,
954,
955,
958,
968,
971,
977,
980,
983,
995,
996,
999,
1002,
1011,
1014,
1017,
1019,
1020,
1021,
1024,
1030,
1045,
1048,
1051,
1057,
1071,
1074,
1075,
1087,
1090,
1093,
1096,
1099,
1118,
1121,
1123,
1127,
1137,
1140,
1143,
1146,
1152,
1153,
1159,
1162,
1165,
1171,
1172,
1175,
1181,
1187,
1190,
1196,
1197,
1200,
1203,
1204,
1210,
1250,
1253,
1256,
1259,
1274,
1277,
1280,
1289,
1295,
1298,
1320,
1323,
1326,
1335,
1338,
1341,
1344,
1347,
1350,
1353,
1356,
1359,
1362,
1365,
1368,
1371,
1374,
1375,
1378,
1381,
1384,
1387,
1410,
1419,
1422,
1429,
1438,
1441,
1443,
1446,
1455,
1458,
1461,
1464,
1467,
1470,
1473,
1479,
1486,
1489,
1492,
1495,
1498,
1533,
1536,
1539,
1540,
1543,
1546,
1549,
1552,
1553,
1555,
1558,
1561,
1578,
1579,
1582,
1590,
1609,
1631,
1634,
1637,
1640,
1641,
1644,
1646,
1648,
1649,
1650,
1653,
1655,
1656,
1657,
1660,
1678,
1683,
1686,
1689,
1695,
1696,
1699,
1702,
1711,
1714,
1717,
1723,
1726,
1729,
1738,
1740,
1743,
1745,
1754,
1757,
1763,
1769,
1772,
1775,
1781,
1784,
1787,
1790,
1792,
1795,
1798,
1801,
1804,
1805,
1807,
1808,
1811,
1814,
1817,
1819,
1828,
1831,
1834,
1837,
1840,
1843,
1846,
1849,
1852,
1853,
1856,
1859,
1862,
1864,
1873,
1882,
1892,
1895,
1898,
1901,
1904,
1919,
1922,
1928,
1931,
1934,
1937,
1940,
1957,
1960,
1963,
1966,
1969,
1972,
1975,
1977,
1978,
1980,
1983,
1989,
1990,
1993,
1999,
2002,
2004,
2006,
2009,
2015,
2048,
2051,
2054,
2057,
2058,
2061,
2067,
2076,
2078,
2081,
2089,
2092,
2098,
2107,
2108,
2111,
2126,
2155,
2167,
2168,
2170,
2173,
2176,
2179,
2185,
2194,
2195,
2198,
2211,
2217,
2220,
2223,
2229,
2251,
2252,
2255,
2256,
2265,
2268,
2272,
2275,
2278,
2280,
2283,
2284,
2290,
2293,
2300,
2303,
2306,
2309,
2346,
2349,
2367,
2373,
2376,
2379,
2382,
2385,
2388,
2391,
2394,
2397,
2398,
2399,
2402,
2405,
2407,
2413,
2416,
2419,
2422,
2425,
2428,
2431,
2440,
2443,
2446,
2449,
2461,
2463,
2469,
2472,
2474,
2477,
2480,
2481,
2488,
2491,
2497,
2500,
2502,
2505,
2514,
2516,
2522,
2525,
2528,
2531,
2543,
2546,
2576,
2578,
2581,
2584,
2587,
2588,
2589,
2592,
2595,
2598,
2601,
2604,
2605,
2606,
2609,
2612,
2615,
2618,
2621,
2624,
2627,
2630,
2633,
2634,
2637,
2639,
2645,
2648,
2651,
2654,
2657,
2659,
2676,
2679,
2682,
2684,
2690,
2691,
2694,
2697,
2700,
2703,
2706,
2712,
2713,
2715,
2718,
2727,
2739,
2744,
2747,
2750,
2759,
2760,
2763,
2766,
2769,
2775,
2776,
2785,
2864,
2866,
2869,
2872,
2873,
2876,
2878,
2881,
2884,
2887,
2899,
2902,
2905]
| cullina/Extractor | src/ExpertData.hs | bsd-3-clause | 10,630 | 0 | 9 | 3,409 | 6,459 | 4,274 | 2,185 | 1,139 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
-- | Resolving a build plan for a set of packages in a given Stackage
-- snapshot.
module Stack.BuildPlan
( BuildPlanException (..)
, MiniBuildPlan(..)
, MiniPackageInfo(..)
, Snapshots (..)
, getSnapshots
, loadMiniBuildPlan
, resolveBuildPlan
, findBuildPlan
, ToolMap
, getToolMap
, shadowMiniBuildPlan
, parseCustomMiniBuildPlan
) where
import Control.Applicative
import Control.Exception (assert)
import Control.Monad (liftM, forM)
import Control.Monad.Catch
import Control.Monad.IO.Class
import Control.Monad.Logger
import Control.Monad.Reader (asks)
import Control.Monad.State.Strict (State, execState, get, modify,
put)
import Control.Monad.Trans.Control (MonadBaseControl)
import qualified Crypto.Hash.SHA256 as SHA256
import Data.Aeson.Extended (FromJSON (..), withObject, withText, (.:), (.:?), (.!=))
import Data.Binary.VersionTagged (taggedDecodeOrLoad)
import Data.ByteString (ByteString)
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString as S
import qualified Data.ByteString.Char8 as S8
import Data.Either (partitionEithers)
import qualified Data.Foldable as F
import qualified Data.HashMap.Strict as HM
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.List (intercalate)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe (fromMaybe, mapMaybe)
import Data.Monoid
import Data.Set (Set)
import qualified Data.Set as Set
import qualified Data.Text as T
import Data.Text.Encoding (encodeUtf8)
import Data.Time (Day)
import qualified Data.Traversable as Tr
import Data.Typeable (Typeable)
import Data.Yaml (decodeEither', decodeFileEither)
import Distribution.PackageDescription (GenericPackageDescription,
flagDefault, flagManual,
flagName, genPackageFlags,
executables, exeName, library, libBuildInfo, buildable)
import qualified Distribution.Package as C
import qualified Distribution.PackageDescription as C
import qualified Distribution.Version as C
import Distribution.Text (display)
import Network.HTTP.Download
import Network.HTTP.Types (Status(..))
import Network.HTTP.Client (checkStatus)
import Path
import Path.IO
import Prelude -- Fix AMP warning
import Stack.Constants
import Stack.Fetch
import Stack.Package
import Stack.Types
import Stack.Types.StackT
import System.Directory (canonicalizePath)
import qualified System.FilePath as FP
data BuildPlanException
= UnknownPackages
(Path Abs File) -- stack.yaml file
(Map PackageName (Maybe Version, (Set PackageName))) -- truly unknown
(Map PackageName (Set PackageIdentifier)) -- shadowed
| SnapshotNotFound SnapName
deriving (Typeable)
instance Exception BuildPlanException
instance Show BuildPlanException where
show (SnapshotNotFound snapName) = unlines
[ "SnapshotNotFound " ++ snapName'
, "Non existing resolver: " ++ snapName' ++ "."
, "For a complete list of available snapshots see https://www.stackage.org/snapshots"
]
where snapName' = show $ renderSnapName snapName
show (UnknownPackages stackYaml unknown shadowed) =
unlines $ unknown' ++ shadowed'
where
unknown' :: [String]
unknown'
| Map.null unknown = []
| otherwise = concat
[ ["The following packages do not exist in the build plan:"]
, map go (Map.toList unknown)
, case mapMaybe goRecommend $ Map.toList unknown of
[] -> []
rec ->
("Recommended action: modify the extra-deps field of " ++
toFilePath stackYaml ++
" to include the following:")
: (rec
++ ["Note: further dependencies may need to be added"])
, case mapMaybe getNoKnown $ Map.toList unknown of
[] -> []
noKnown ->
[ "There are no known versions of the following packages:"
, intercalate ", " $ map packageNameString noKnown
]
]
where
go (dep, (_, users)) | Set.null users = packageNameString dep
go (dep, (_, users)) = concat
[ packageNameString dep
, " (used by "
, intercalate ", " $ map packageNameString $ Set.toList users
, ")"
]
goRecommend (name, (Just version, _)) =
Just $ "- " ++ packageIdentifierString (PackageIdentifier name version)
goRecommend (_, (Nothing, _)) = Nothing
getNoKnown (name, (Nothing, _)) = Just name
getNoKnown (_, (Just _, _)) = Nothing
shadowed' :: [String]
shadowed'
| Map.null shadowed = []
| otherwise = concat
[ ["The following packages are shadowed by local packages:"]
, map go (Map.toList shadowed)
, ["Recommended action: modify the extra-deps field of " ++
toFilePath stackYaml ++
" to include the following:"]
, extraDeps
, ["Note: further dependencies may need to be added"]
]
where
go (dep, users) | Set.null users = concat
[ packageNameString dep
, " (internal stack error: this should never be null)"
]
go (dep, users) = concat
[ packageNameString dep
, " (used by "
, intercalate ", "
$ map (packageNameString . packageIdentifierName)
$ Set.toList users
, ")"
]
extraDeps = map (\ident -> "- " ++ packageIdentifierString ident)
$ Set.toList
$ Set.unions
$ Map.elems shadowed
-- | Determine the necessary packages to install to have the given set of
-- packages available.
--
-- This function will not provide test suite and benchmark dependencies.
--
-- This may fail if a target package is not present in the @BuildPlan@.
resolveBuildPlan :: (MonadThrow m, MonadIO m, MonadReader env m, HasBuildConfig env, MonadLogger m, HasHttpManager env, MonadBaseControl IO m,MonadCatch m)
=> MiniBuildPlan
-> (PackageName -> Bool) -- ^ is it shadowed by a local package?
-> Map PackageName (Set PackageName) -- ^ required packages, and users of it
-> m ( Map PackageName (Version, Map FlagName Bool)
, Map PackageName (Set PackageName)
)
resolveBuildPlan mbp isShadowed packages
| Map.null (rsUnknown rs) && Map.null (rsShadowed rs) = return (rsToInstall rs, rsUsedBy rs)
| otherwise = do
bconfig <- asks getBuildConfig
let maxVer =
Map.fromListWith max $
map toTuple $
Map.keys (bcPackageCaches bconfig)
unknown = flip Map.mapWithKey (rsUnknown rs) $ \ident x ->
(Map.lookup ident maxVer, x)
throwM $ UnknownPackages
(bcStackYaml bconfig)
unknown
(rsShadowed rs)
where
rs = getDeps mbp isShadowed packages
data ResolveState = ResolveState
{ rsVisited :: Map PackageName (Set PackageName) -- ^ set of shadowed dependencies
, rsUnknown :: Map PackageName (Set PackageName)
, rsShadowed :: Map PackageName (Set PackageIdentifier)
, rsToInstall :: Map PackageName (Version, Map FlagName Bool)
, rsUsedBy :: Map PackageName (Set PackageName)
}
toMiniBuildPlan :: (MonadIO m, MonadLogger m, MonadReader env m, HasHttpManager env, MonadThrow m, HasConfig env, MonadBaseControl IO m, MonadCatch m)
=> CompilerVersion -- ^ Compiler version
-> Map PackageName Version -- ^ cores
-> Map PackageName (Version, Map FlagName Bool) -- ^ non-core packages
-> m MiniBuildPlan
toMiniBuildPlan compilerVersion corePackages packages = do
$logInfo "Caching build plan"
-- Determine the dependencies of all of the packages in the build plan. We
-- handle core packages specially, because some of them will not be in the
-- package index. For those, we allow missing packages to exist, and then
-- remove those from the list of dependencies, since there's no way we'll
-- ever reinstall them anyway.
(cores, missingCores) <- addDeps True compilerVersion
$ fmap (, Map.empty) corePackages
(extras, missing) <- addDeps False compilerVersion packages
assert (Set.null missing) $ return MiniBuildPlan
{ mbpCompilerVersion = compilerVersion
, mbpPackages = Map.unions
[ fmap (removeMissingDeps (Map.keysSet cores)) cores
, extras
, Map.fromList $ map goCore $ Set.toList missingCores
]
}
where
goCore (PackageIdentifier name version) = (name, MiniPackageInfo
{ mpiVersion = version
, mpiFlags = Map.empty
, mpiPackageDeps = Set.empty
, mpiToolDeps = Set.empty
, mpiExes = Set.empty
, mpiHasLibrary = True
})
removeMissingDeps cores mpi = mpi
{ mpiPackageDeps = Set.intersection cores (mpiPackageDeps mpi)
}
-- | Add in the resolved dependencies from the package index
addDeps :: (MonadIO m, MonadLogger m, MonadReader env m, HasHttpManager env, MonadThrow m, HasConfig env, MonadBaseControl IO m, MonadCatch m)
=> Bool -- ^ allow missing
-> CompilerVersion -- ^ Compiler version
-> Map PackageName (Version, Map FlagName Bool)
-> m (Map PackageName MiniPackageInfo, Set PackageIdentifier)
addDeps allowMissing compilerVersion toCalc = do
menv <- getMinimalEnvOverride
platform <- asks $ configPlatform . getConfig
(resolvedMap, missingIdents) <-
if allowMissing
then do
(missingNames, missingIdents, m) <-
resolvePackagesAllowMissing menv (Map.keysSet idents0) Set.empty
assert (Set.null missingNames)
$ return (m, missingIdents)
else do
m <- resolvePackages menv (Map.keysSet idents0) Set.empty
return (m, Set.empty)
let byIndex = Map.fromListWith (++) $ flip map (Map.toList resolvedMap)
$ \(ident, rp) ->
(indexName $ rpIndex rp,
[( ident
, rpCache rp
, maybe Map.empty snd $ Map.lookup (packageIdentifierName ident) toCalc
)])
res <- forM (Map.toList byIndex) $ \(indexName', pkgs) -> withCabalFiles indexName' pkgs
$ \ident flags cabalBS -> do
(_warnings,gpd) <- readPackageUnresolvedBS Nothing cabalBS
let packageConfig = PackageConfig
{ packageConfigEnableTests = False
, packageConfigEnableBenchmarks = False
, packageConfigFlags = flags
, packageConfigCompilerVersion = compilerVersion
, packageConfigPlatform = platform
}
name = packageIdentifierName ident
pd = resolvePackageDescription packageConfig gpd
exes = Set.fromList $ map (ExeName . S8.pack . exeName) $ executables pd
notMe = Set.filter (/= name) . Map.keysSet
return (name, MiniPackageInfo
{ mpiVersion = packageIdentifierVersion ident
, mpiFlags = flags
, mpiPackageDeps = notMe $ packageDependencies pd
, mpiToolDeps = Map.keysSet $ packageToolDependencies pd
, mpiExes = exes
, mpiHasLibrary = maybe
False
(buildable . libBuildInfo)
(library pd)
})
return (Map.fromList $ concat res, missingIdents)
where
idents0 = Map.fromList
$ map (\(n, (v, f)) -> (PackageIdentifier n v, Left f))
$ Map.toList toCalc
-- | Resolve all packages necessary to install for
getDeps :: MiniBuildPlan
-> (PackageName -> Bool) -- ^ is it shadowed by a local package?
-> Map PackageName (Set PackageName)
-> ResolveState
getDeps mbp isShadowed packages =
execState (mapM_ (uncurry goName) $ Map.toList packages) ResolveState
{ rsVisited = Map.empty
, rsUnknown = Map.empty
, rsShadowed = Map.empty
, rsToInstall = Map.empty
, rsUsedBy = Map.empty
}
where
toolMap = getToolMap mbp
-- | Returns a set of shadowed packages we depend on.
goName :: PackageName -> Set PackageName -> State ResolveState (Set PackageName)
goName name users = do
-- Even though we could check rsVisited first and short-circuit things
-- earlier, lookup in mbpPackages first so that we can produce more
-- usable error information on missing dependencies
rs <- get
put rs
{ rsUsedBy = Map.insertWith Set.union name users $ rsUsedBy rs
}
case Map.lookup name $ mbpPackages mbp of
Nothing -> do
modify $ \rs' -> rs'
{ rsUnknown = Map.insertWith Set.union name users $ rsUnknown rs'
}
return Set.empty
Just mpi -> case Map.lookup name (rsVisited rs) of
Just shadowed -> return shadowed
Nothing -> do
put rs { rsVisited = Map.insert name Set.empty $ rsVisited rs }
let depsForTools = Set.unions $ mapMaybe (flip Map.lookup toolMap) (Set.toList $ mpiToolDeps mpi)
let deps = Set.filter (/= name) (mpiPackageDeps mpi <> depsForTools)
shadowed <- fmap F.fold $ Tr.forM (Set.toList deps) $ \dep ->
if isShadowed dep
then do
modify $ \rs' -> rs'
{ rsShadowed = Map.insertWith
Set.union
dep
(Set.singleton $ PackageIdentifier name (mpiVersion mpi))
(rsShadowed rs')
}
return $ Set.singleton dep
else do
shadowed <- goName dep (Set.singleton name)
let m = Map.fromSet (\_ -> Set.singleton $ PackageIdentifier name (mpiVersion mpi)) shadowed
modify $ \rs' -> rs'
{ rsShadowed = Map.unionWith Set.union m $ rsShadowed rs'
}
return shadowed
modify $ \rs' -> rs'
{ rsToInstall = Map.insert name (mpiVersion mpi, mpiFlags mpi) $ rsToInstall rs'
, rsVisited = Map.insert name shadowed $ rsVisited rs'
}
return shadowed
-- | Look up with packages provide which tools.
type ToolMap = Map ByteString (Set PackageName)
-- | Map from tool name to package providing it
getToolMap :: MiniBuildPlan -> Map ByteString (Set PackageName)
getToolMap mbp =
Map.unionsWith Set.union
{- We no longer do this, following discussion at:
https://github.com/commercialhaskell/stack/issues/308#issuecomment-112076704
-- First grab all of the package names, for times where a build tool is
-- identified by package name
$ Map.fromList (map (packageNameByteString &&& Set.singleton) (Map.keys ps))
-}
-- And then get all of the explicit executable names
$ concatMap goPair (Map.toList ps)
where
ps = mbpPackages mbp
goPair (pname, mpi) =
map (flip Map.singleton (Set.singleton pname) . unExeName)
$ Set.toList
$ mpiExes mpi
-- | Download the 'Snapshots' value from stackage.org.
getSnapshots :: (MonadThrow m, MonadIO m, MonadReader env m, HasHttpManager env, HasStackRoot env, HasConfig env)
=> m Snapshots
getSnapshots = askLatestSnapshotUrl >>= parseUrl . T.unpack >>= downloadJSON
-- | Most recent Nightly and newest LTS version per major release.
data Snapshots = Snapshots
{ snapshotsNightly :: !Day
, snapshotsLts :: !(IntMap Int)
}
deriving Show
instance FromJSON Snapshots where
parseJSON = withObject "Snapshots" $ \o -> Snapshots
<$> (o .: "nightly" >>= parseNightly)
<*> (fmap IntMap.unions
$ mapM parseLTS
$ map snd
$ filter (isLTS . fst)
$ HM.toList o)
where
parseNightly t =
case parseSnapName t of
Left e -> fail $ show e
Right (LTS _ _) -> fail "Unexpected LTS value"
Right (Nightly d) -> return d
isLTS = ("lts-" `T.isPrefixOf`)
parseLTS = withText "LTS" $ \t ->
case parseSnapName t of
Left e -> fail $ show e
Right (LTS x y) -> return $ IntMap.singleton x y
Right (Nightly _) -> fail "Unexpected nightly value"
-- | Load up a 'MiniBuildPlan', preferably from cache
loadMiniBuildPlan
:: (MonadIO m, MonadThrow m, MonadLogger m, MonadReader env m, HasHttpManager env, HasConfig env, HasGHCVariant env, MonadBaseControl IO m, MonadCatch m)
=> SnapName
-> m MiniBuildPlan
loadMiniBuildPlan name = do
path <- configMiniBuildPlanCache name
taggedDecodeOrLoad path $ liftM buildPlanFixes $ do
bp <- loadBuildPlan name
toMiniBuildPlan
(siCompilerVersion $ bpSystemInfo bp)
(siCorePackages $ bpSystemInfo bp)
(fmap goPP $ bpPackages bp)
where
goPP pp =
( ppVersion pp
, pcFlagOverrides $ ppConstraints pp
)
-- | Some hard-coded fixes for build plans, hopefully to be irrelevant over
-- time.
buildPlanFixes :: MiniBuildPlan -> MiniBuildPlan
buildPlanFixes mbp = mbp
{ mbpPackages = Map.fromList $ map go $ Map.toList $ mbpPackages mbp
}
where
go (name, mpi) =
(name, mpi
{ mpiFlags = goF (packageNameString name) (mpiFlags mpi)
})
goF "persistent-sqlite" = Map.insert $(mkFlagName "systemlib") False
goF "yaml" = Map.insert $(mkFlagName "system-libyaml") False
goF _ = id
-- | Load the 'BuildPlan' for the given snapshot. Will load from a local copy
-- if available, otherwise downloading from Github.
loadBuildPlan :: (MonadIO m, MonadThrow m, MonadLogger m, MonadReader env m, HasHttpManager env, HasStackRoot env)
=> SnapName
-> m BuildPlan
loadBuildPlan name = do
env <- ask
let stackage = getStackRoot env
file' <- parseRelFile $ T.unpack file
let fp = buildPlanDir stackage </> file'
$logDebug $ "Decoding build plan from: " <> T.pack (toFilePath fp)
eres <- liftIO $ decodeFileEither $ toFilePath fp
case eres of
Right bp -> return bp
Left e -> do
$logDebug $ "Decoding build plan from file failed: " <> T.pack (show e)
createTree (parent fp)
req <- parseUrl $ T.unpack url
$logSticky $ "Downloading " <> renderSnapName name <> " build plan ..."
$logDebug $ "Downloading build plan from: " <> url
_ <- download req { checkStatus = handle404 } fp
$logStickyDone $ "Downloaded " <> renderSnapName name <> " build plan."
liftIO (decodeFileEither $ toFilePath fp) >>= either throwM return
where
file = renderSnapName name <> ".yaml"
reponame =
case name of
LTS _ _ -> "lts-haskell"
Nightly _ -> "stackage-nightly"
url = rawGithubUrl "fpco" reponame "master" file
handle404 (Status 404 _) _ _ = Just $ SomeException $ SnapshotNotFound name
handle404 _ _ _ = Nothing
-- | Find the set of @FlagName@s necessary to get the given
-- @GenericPackageDescription@ to compile against the given @BuildPlan@. Will
-- only modify non-manual flags, and will prefer default values for flags.
-- Returns @Nothing@ if no combination exists.
checkBuildPlan :: (MonadLogger m, MonadThrow m, MonadIO m, MonadReader env m, HasConfig env, MonadCatch m)
=> Map PackageName Version -- ^ locally available packages
-> MiniBuildPlan
-> GenericPackageDescription
-> m (Either DepErrors (Map PackageName (Map FlagName Bool)))
checkBuildPlan locals mbp gpd = do
platform <- asks (configPlatform . getConfig)
return $ loop platform flagOptions
where
packages = Map.union locals $ fmap mpiVersion $ mbpPackages mbp
loop _ [] = assert False $ Left Map.empty
loop platform (flags:rest)
| Map.null errs = Right $
if Map.null flags
then Map.empty
else Map.singleton (packageName pkg) flags
| null rest = Left errs
| otherwise = loop platform rest
where
errs = checkDeps (packageName pkg) (packageDeps pkg) packages
pkg = resolvePackage pkgConfig gpd
pkgConfig = PackageConfig
{ packageConfigEnableTests = True
, packageConfigEnableBenchmarks = True
, packageConfigFlags = flags
, packageConfigCompilerVersion = compilerVersion
, packageConfigPlatform = platform
}
compilerVersion = mbpCompilerVersion mbp
flagName' = fromCabalFlagName . flagName
-- Avoid exponential complexity in flag combinations making us sad pandas.
-- See: https://github.com/commercialhaskell/stack/issues/543
maxFlagOptions = 128
flagOptions = take maxFlagOptions $ map Map.fromList $ mapM getOptions $ genPackageFlags gpd
getOptions f
| flagManual f = [(flagName' f, flagDefault f)]
| flagDefault f =
[ (flagName' f, True)
, (flagName' f, False)
]
| otherwise =
[ (flagName' f, False)
, (flagName' f, True)
]
-- | Checks if the given package dependencies can be satisfied by the given set
-- of packages. Will fail if a package is either missing or has a version
-- outside of the version range.
checkDeps :: PackageName -- ^ package using dependencies, for constructing DepErrors
-> Map PackageName VersionRange
-> Map PackageName Version
-> DepErrors
checkDeps myName deps packages =
Map.unionsWith mappend $ map go $ Map.toList deps
where
go :: (PackageName, VersionRange) -> DepErrors
go (name, range) =
case Map.lookup name packages of
Nothing -> Map.singleton name DepError
{ deVersion = Nothing
, deNeededBy = Map.singleton myName range
}
Just v
| withinRange v range -> Map.empty
| otherwise -> Map.singleton name DepError
{ deVersion = Just v
, deNeededBy = Map.singleton myName range
}
type DepErrors = Map PackageName DepError
data DepError = DepError
{ deVersion :: !(Maybe Version)
, deNeededBy :: !(Map PackageName VersionRange)
}
instance Monoid DepError where
mempty = DepError Nothing Map.empty
mappend (DepError a x) (DepError b y) = DepError
(maybe a Just b)
(Map.unionWith C.intersectVersionRanges x y)
-- | Find a snapshot and set of flags that is compatible with the given
-- 'GenericPackageDescription'. Returns 'Nothing' if no such snapshot is found.
findBuildPlan :: (MonadIO m, MonadCatch m, MonadLogger m, MonadReader env m, HasHttpManager env, HasConfig env, HasGHCVariant env, MonadBaseControl IO m)
=> [GenericPackageDescription]
-> [SnapName]
-> m (Maybe (SnapName, Map PackageName (Map FlagName Bool)))
findBuildPlan gpds0 =
loop
where
loop [] = return Nothing
loop (name:names') = do
mbp <- loadMiniBuildPlan name
$logInfo $ "Checking against build plan " <> renderSnapName name
res <- mapM (checkBuildPlan localNames mbp) gpds0
case partitionEithers res of
([], flags) -> return $ Just (name, Map.unions flags)
(errs, _) -> do
$logInfo ""
$logInfo "* Build plan did not match your requirements:"
displayDepErrors $ Map.unionsWith mappend errs
$logInfo ""
loop names'
localNames = Map.fromList $ map (fromCabalIdent . C.package . C.packageDescription) gpds0
fromCabalIdent (C.PackageIdentifier name version) =
(fromCabalPackageName name, fromCabalVersion version)
displayDepErrors :: MonadLogger m => DepErrors -> m ()
displayDepErrors errs =
F.forM_ (Map.toList errs) $ \(depName, DepError mversion neededBy) -> do
$logInfo $ T.concat
[ " "
, T.pack $ packageNameString depName
, case mversion of
Nothing -> " not found"
Just version -> T.concat
[ " version "
, T.pack $ versionString version
, " found"
]
]
F.forM_ (Map.toList neededBy) $ \(user, range) -> $logInfo $ T.concat
[ " - "
, T.pack $ packageNameString user
, " requires "
, T.pack $ display range
]
$logInfo ""
shadowMiniBuildPlan :: MiniBuildPlan
-> Set PackageName
-> (MiniBuildPlan, Map PackageName MiniPackageInfo)
shadowMiniBuildPlan (MiniBuildPlan cv pkgs0) shadowed =
(MiniBuildPlan cv $ Map.fromList met, Map.fromList unmet)
where
pkgs1 = Map.difference pkgs0 $ Map.fromSet (\_ -> ()) shadowed
depsMet = flip execState Map.empty $ mapM_ (check Set.empty) (Map.keys pkgs1)
check visited name
| name `Set.member` visited =
error $ "shadowMiniBuildPlan: cycle detected, your MiniBuildPlan is broken: " ++ show (visited, name)
| otherwise = do
m <- get
case Map.lookup name m of
Just x -> return x
Nothing ->
case Map.lookup name pkgs1 of
Nothing
| name `Set.member` shadowed -> return False
-- In this case, we have to assume that we're
-- constructing a build plan on a different OS or
-- architecture, and therefore different packages
-- are being chosen. The common example of this is
-- the Win32 package.
| otherwise -> return True
Just mpi -> do
let visited' = Set.insert name visited
ress <- mapM (check visited') (Set.toList $ mpiPackageDeps mpi)
let res = and ress
modify $ \m' -> Map.insert name res m'
return res
(met, unmet) = partitionEithers $ map toEither $ Map.toList pkgs1
toEither pair@(name, _) =
wrapper pair
where
wrapper =
case Map.lookup name depsMet of
Just True -> Left
Just False -> Right
Nothing -> assert False Right
parseCustomMiniBuildPlan :: (MonadIO m, MonadCatch m, MonadLogger m, MonadReader env m, HasHttpManager env, HasConfig env, MonadBaseControl IO m)
=> Path Abs File -- ^ stack.yaml file location
-> T.Text -> m MiniBuildPlan
parseCustomMiniBuildPlan stackYamlFP url0 = do
yamlFP <- getYamlFP url0
yamlBS <- liftIO $ S.readFile $ toFilePath yamlFP
let yamlHash = S8.unpack $ B16.encode $ SHA256.hash yamlBS
binaryFilename <- parseRelFile $ yamlHash ++ ".bin"
customPlanDir <- getCustomPlanDir
let binaryFP = customPlanDir </> $(mkRelDir "bin") </> binaryFilename
taggedDecodeOrLoad binaryFP $ do
cs <- either throwM return $ decodeEither' yamlBS
let addFlags :: PackageIdentifier -> (PackageName, (Version, Map FlagName Bool))
addFlags (PackageIdentifier name ver) =
(name, (ver, fromMaybe Map.empty $ Map.lookup name $ csFlags cs))
toMiniBuildPlan
(csCompilerVersion cs)
Map.empty
(Map.fromList $ map addFlags $ Set.toList $ csPackages cs)
where
getCustomPlanDir = do
root <- asks $ configStackRoot . getConfig
return $ root </> $(mkRelDir "custom-plan")
-- Get the path to the YAML file
getYamlFP url =
case parseUrl $ T.unpack url of
Just req -> getYamlFPFromReq url req
Nothing -> getYamlFPFromFile url
getYamlFPFromReq url req = do
let hashStr = S8.unpack $ B16.encode $ SHA256.hash $ encodeUtf8 url
hashFP <- parseRelFile $ hashStr ++ ".yaml"
customPlanDir <- getCustomPlanDir
let cacheFP = customPlanDir </> $(mkRelDir "yaml") </> hashFP
_ <- download req cacheFP
return cacheFP
getYamlFPFromFile url = do
fp <- liftIO $ canonicalizePath $ toFilePath (parent stackYamlFP) FP.</> T.unpack (fromMaybe url $
T.stripPrefix "file://" url <|> T.stripPrefix "file:" url)
parseAbsFile fp
data CustomSnapshot = CustomSnapshot
{ csCompilerVersion :: !CompilerVersion
, csPackages :: !(Set PackageIdentifier)
, csFlags :: !(Map PackageName (Map FlagName Bool))
}
instance FromJSON CustomSnapshot where
parseJSON = withObject "CustomSnapshot" $ \o -> CustomSnapshot
<$> ((o .: "compiler") >>= \t ->
case parseCompilerVersion t of
Nothing -> fail $ "Invalid compiler: " ++ T.unpack t
Just compilerVersion -> return compilerVersion)
<*> o .: "packages"
<*> o .:? "flags" .!= Map.empty
| rvion/stack | src/Stack/BuildPlan.hs | bsd-3-clause | 31,182 | 0 | 32 | 10,548 | 7,454 | 3,824 | 3,630 | 586 | 5 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.ElastiCache.CreateSnapshot
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- The /CreateSnapshot/ action creates a copy of an entire cache cluster at
-- a specific moment in time.
--
-- /See:/ <http://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/API_CreateSnapshot.html AWS API Reference> for CreateSnapshot.
module Network.AWS.ElastiCache.CreateSnapshot
(
-- * Creating a Request
createSnapshot
, CreateSnapshot
-- * Request Lenses
, csCacheClusterId
, csSnapshotName
-- * Destructuring the Response
, createSnapshotResponse
, CreateSnapshotResponse
-- * Response Lenses
, crersSnapshot
, crersResponseStatus
) where
import Network.AWS.ElastiCache.Types
import Network.AWS.ElastiCache.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | Represents the input of a /CreateSnapshot/ action.
--
-- /See:/ 'createSnapshot' smart constructor.
data CreateSnapshot = CreateSnapshot'
{ _csCacheClusterId :: !Text
, _csSnapshotName :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateSnapshot' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'csCacheClusterId'
--
-- * 'csSnapshotName'
createSnapshot
:: Text -- ^ 'csCacheClusterId'
-> Text -- ^ 'csSnapshotName'
-> CreateSnapshot
createSnapshot pCacheClusterId_ pSnapshotName_ =
CreateSnapshot'
{ _csCacheClusterId = pCacheClusterId_
, _csSnapshotName = pSnapshotName_
}
-- | The identifier of an existing cache cluster. The snapshot will be
-- created from this cache cluster.
csCacheClusterId :: Lens' CreateSnapshot Text
csCacheClusterId = lens _csCacheClusterId (\ s a -> s{_csCacheClusterId = a});
-- | A name for the snapshot being created.
csSnapshotName :: Lens' CreateSnapshot Text
csSnapshotName = lens _csSnapshotName (\ s a -> s{_csSnapshotName = a});
instance AWSRequest CreateSnapshot where
type Rs CreateSnapshot = CreateSnapshotResponse
request = postQuery elastiCache
response
= receiveXMLWrapper "CreateSnapshotResult"
(\ s h x ->
CreateSnapshotResponse' <$>
(x .@? "Snapshot") <*> (pure (fromEnum s)))
instance ToHeaders CreateSnapshot where
toHeaders = const mempty
instance ToPath CreateSnapshot where
toPath = const "/"
instance ToQuery CreateSnapshot where
toQuery CreateSnapshot'{..}
= mconcat
["Action" =: ("CreateSnapshot" :: ByteString),
"Version" =: ("2015-02-02" :: ByteString),
"CacheClusterId" =: _csCacheClusterId,
"SnapshotName" =: _csSnapshotName]
-- | /See:/ 'createSnapshotResponse' smart constructor.
data CreateSnapshotResponse = CreateSnapshotResponse'
{ _crersSnapshot :: !(Maybe Snapshot)
, _crersResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateSnapshotResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'crersSnapshot'
--
-- * 'crersResponseStatus'
createSnapshotResponse
:: Int -- ^ 'crersResponseStatus'
-> CreateSnapshotResponse
createSnapshotResponse pResponseStatus_ =
CreateSnapshotResponse'
{ _crersSnapshot = Nothing
, _crersResponseStatus = pResponseStatus_
}
-- | Undocumented member.
crersSnapshot :: Lens' CreateSnapshotResponse (Maybe Snapshot)
crersSnapshot = lens _crersSnapshot (\ s a -> s{_crersSnapshot = a});
-- | The response status code.
crersResponseStatus :: Lens' CreateSnapshotResponse Int
crersResponseStatus = lens _crersResponseStatus (\ s a -> s{_crersResponseStatus = a});
| fmapfmapfmap/amazonka | amazonka-elasticache/gen/Network/AWS/ElastiCache/CreateSnapshot.hs | mpl-2.0 | 4,502 | 0 | 13 | 923 | 625 | 375 | 250 | 81 | 1 |
module FasionShow where
import Data.Char
import Data.Sequence(Seq)
import qualified Data.Sequence as S
import Control.Monad.ST
import Data.STRef
import Control.Monad
import System.Random
import Data.Vector.Unboxed (freeze, toList)
import qualified Data.Vector.Unboxed.Mutable as V
import Control.Monad.State
import Data.Vector.Unboxed ((!), (//))
import Control.Monad.Primitive (PrimMonad, PrimState)
import qualified Data.Vector.Algorithms.Merge as M
getBathroomStalls :: String -> String
getBathroomStalls xs =
let inputs = words xs
ys = [read (head inputs)::Int]
y = read (last inputs)::Int
in show 1 ++ " " ++ (show 2)
fibST :: Int -> Int
fibST n
| n < 2 = n
| otherwise = runST (test2 n)
test :: Int -> ST s (V.MVector s Int)
test n = do
v <- V.new (n+1)
return v
test2 :: Int -> ST s Int
test2 n = do
v <- test n -- call test, which performs the allocation
fibST' n v
fibST' :: Int -> (V.MVector s Int) -> ST s Int
fibST' n v
| n < 2 = do
V.write v n n
return n
| otherwise = do
fibST' (n-1) v
nMinus1 <- V.read v (n-1)
nMinus2 <- V.read v (n-2)
V.write v n (nMinus2 + nMinus1)
return (nMinus2 + nMinus1)
printRandomArry s n = runST (printRandomArry' s n)
printRandomArry' :: StdGen -> Int -> ST s [Int]
printRandomArry' g n = do
v <- test n
printRun g v 0 n
M.sort v
v' <- freeze v
return (toList v')
printRun :: StdGen -> (V.MVector s Int) -> Int -> Int -> ST s ()
printRun g v x y
| x < y = do
let (r,g') = randomR (1,100) g
V.write v x r
printRun g' v (x+1) y
return ()
| otherwise = do
return ()
| lihlcnkr/codejam | src/QR/FasionShow.hs | apache-2.0 | 1,696 | 0 | 12 | 470 | 761 | 383 | 378 | -1 | -1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Database.DSH.VSL
( module Database.DSH.VSL.Lang
, module Database.DSH.VSL.VirtualSegmentAlgebra
, module Database.DSH.Common.VectorLang
, module Database.DSH.Translate.VSL2Algebra
) where
import Database.DSH.Common.VectorLang
import Database.DSH.Translate.Vectorize
import Database.DSH.VSL.Lang (VSL, TVSL, RVSL, SegmentLookup(..))
import Database.DSH.VSL.Opt.OptimizeVSL
import Database.DSH.VSL.Vectorize
import Database.DSH.VSL.VirtualSegmentAlgebra
import Database.DSH.Translate.VSL2Algebra
instance VectorLang VSL where
vectorize = vectorizeDelayed
optimizeVectorPlan = optimizeVSLDefault
| ulricha/dsh | src/Database/DSH/VSL.hs | bsd-3-clause | 794 | 0 | 6 | 173 | 129 | 90 | 39 | 17 | 0 |
-- |
-- Module : Foundation.Collection.List
-- License : BSD-style
-- Maintainer : Vincent Hanquez <vincent@snarc.org>
-- Stability : experimental
-- Portability : portable
--
module Foundation.Collection.List
( wordsWhen
, revTake
, revDrop
, revSplitAt
, breakEnd
, uncons
, unsnoc
) where
import qualified Data.List
import Data.Tuple (swap)
import Basement.Compat.Base
import Foundation.Numerical
-- | Simple helper to split a list repeatly when the predicate match
wordsWhen :: (x -> Bool) -> [x] -> [[x]]
wordsWhen _ [] = [[]]
wordsWhen p is = loop is
where
loop s =
let (w, s') = Data.List.break p s
in case s' of
[] -> [w]
_:xs -> w : loop xs
revTake :: Int -> [a] -> [a]
revTake n l = Data.List.drop (len - n) l
where
len = Data.List.length l
revDrop :: Int -> [a] -> [a]
revDrop n l = Data.List.take (len - n) l
where
len = Data.List.length l
revSplitAt :: Int -> [a] -> ([a],[a])
revSplitAt n l = swap $ Data.List.splitAt (len - n) l
where
len = Data.List.length l
breakEnd :: (a -> Bool) -> [a] -> ([a], [a])
breakEnd predicate l =
let (l1,l2) = Data.List.break predicate (Data.List.reverse l)
in if Data.List.null l2 then (l, []) else (Data.List.reverse l2, Data.List.reverse l1)
uncons :: [a] -> Maybe (a, [a])
uncons [] = Nothing
uncons (x:xs) = Just (x,xs)
unsnoc :: [a] -> Maybe ([a], a)
unsnoc [] = Nothing
unsnoc [x] = Just ([], x)
unsnoc [x,y] = Just ([x], y)
unsnoc (x:xs@(_:_)) = Just $ loop [x] xs
where
loop acc [y] = (Data.List.reverse acc, y)
loop acc (y:ys) = loop (y:acc) ys
loop _ _ = error "impossible"
| vincenthz/hs-foundation | foundation/Foundation/Collection/List.hs | bsd-3-clause | 1,744 | 0 | 13 | 488 | 742 | 413 | 329 | 44 | 3 |
{-# OPTIONS_GHC -Wall -fno-warn-unused-do-bind #-}
module Parse.Type where
import Data.List (intercalate)
import Text.Parsec ((<|>), (<?>), char, choice, many, optionMaybe, string, try)
import qualified AST.Type as Type
import qualified AST.Variable as Var
import Parse.Helpers
import qualified Reporting.Annotation as A
import qualified Reporting.Region as R
tvar :: IParser Type.Raw
tvar =
addLocation
(Type.RVar <$> lowVar <?> "a type variable")
tuple :: IParser Type.Raw
tuple =
do (start, types, end) <- located (parens (commaSep expr))
case types of
[t] -> return t
_ -> return (Type.tuple (R.Region start end) types)
record :: IParser Type.Raw
record =
addLocation $
do char '{'
whitespace
rcrd <- extended <|> normal
dumbWhitespace
char '}'
return rcrd
where
normal = flip Type.RRecord Nothing <$> commaSep field
-- extended record types require at least one field
extended =
do ext <- try (addLocation lowVar <* (whitespace >> string "|"))
whitespace
fields <- commaSep1 field
return (Type.RRecord fields (Just (A.map Type.RVar ext)))
field =
do lbl <- rLabel
whitespace >> hasType >> whitespace
(,) lbl <$> expr
capTypeVar :: IParser String
capTypeVar =
intercalate "." <$> dotSep1 capVar
constructor0 :: IParser Type.Raw
constructor0 =
addLocation $
do name <- capTypeVar
return (Type.RType (Var.Raw name))
term :: IParser Type.Raw
term =
choice [ tuple, record, tvar, constructor0 ]
app :: IParser Type.Raw
app =
do start <- getMyPosition
f <- constructor0 <|> try tupleCtor <?> "a type constructor"
args <- spacePrefix term
end <- getMyPosition
case args of
[] -> return f
_ -> return (A.A (R.Region start end) (Type.RApp f args))
where
tupleCtor =
addLocation $
do n <- length <$> parens (many (char ','))
let ctor = "_Tuple" ++ show (if n == 0 then 0 else n+1)
return (Type.RType (Var.Raw ctor))
expr :: IParser Type.Raw
expr =
do start <- getMyPosition
t1 <- app <|> term
arr <- optionMaybe $ try (whitespace >> rightArrow)
case arr of
Nothing ->
return t1
Just _ ->
do whitespace
t2 <- expr
end <- getMyPosition
return (A.A (R.Region start end) (Type.RLambda t1 t2))
constructor :: IParser (String, [Type.Raw])
constructor =
(,) <$> (capTypeVar <?> "another type constructor")
<*> spacePrefix term
| mgold/Elm | src/Parse/Type.hs | bsd-3-clause | 2,603 | 0 | 17 | 737 | 894 | 450 | 444 | 80 | 3 |
-- | Parsers for IMAP server responses
module Network.HaskellNet.IMAP.Parsers
( eval
, eval'
, pNone
, pCapability
, pSelect
, pList
, pLsub
, pStatus
, pExpunge
, pSearch
, pFetch
)
where
import Text.Packrat.Parse hiding (space, spaces)
import Text.Packrat.Pos
import Data.Maybe
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as BS
import Network.HaskellNet.IMAP.Types
eval :: (RespDerivs -> Result RespDerivs r) -> String -> ByteString -> r
eval pMain tag s = case pMain (parse tag (Pos tag 1 1) s) of
Parsed v _ _ -> v
NoParse e -> error (show e)
parse :: String -> Pos -> ByteString -> RespDerivs
parse tagstr pos s = d
where d = RespDerivs flag tag chr pos
flag = pParenFlags d
tag = Parsed tagstr d (nullError d)
chr = if BS.null s
then NoParse (eofError d)
else let (c, s') = (BS.head s, BS.tail s)
in Parsed c (parse tagstr (nextPos pos c) s')
(nullError d)
eval' :: (RespDerivs -> Result RespDerivs r) -> String -> String -> r
eval' pMain tag s = case pMain (parse' tag (Pos tag 1 1) s) of
Parsed v _ _ -> v
NoParse e -> error (show e)
parse' :: String -> Pos -> String -> RespDerivs
parse' tagstr pos s = d
where d = RespDerivs flag tag chr pos
flag = pParenFlags d
tag = Parsed tagstr d (nullError d)
chr = case s of
(c:s') -> Parsed c (parse' tagstr (nextPos pos c) s')
(nullError d)
_ -> NoParse (eofError d)
mkMboxUpdate :: [Either (String, Integer) b] -> (MboxUpdate, [b])
mkMboxUpdate untagged = (MboxUpdate exists' recent', others)
where exists' = lookup "EXISTS" $ catLefts untagged
recent' = lookup "RECENT" $ catLefts untagged
others = catRights untagged
pNone :: RespDerivs -> Result RespDerivs (ServerResponse, MboxUpdate, ())
Parser pNone =
do untagged <- many pOtherLine
resp <- Parser pDone
let (mboxUp, _) = mkMboxUpdate untagged
return (resp, mboxUp, ())
pCapability :: RespDerivs -> Result RespDerivs (ServerResponse, MboxUpdate, [String])
Parser pCapability =
do untagged <- many (pCapabilityLine <|> pOtherLine)
resp <- Parser pDone
let (mboxUp, caps) = mkMboxUpdate untagged
return (resp, mboxUp, concat caps)
pList :: RespDerivs -> Result RespDerivs (ServerResponse, MboxUpdate, [([Attribute], String, MailboxName)])
Parser pList =
do untagged <- many (pListLine "LIST" <|> pOtherLine)
resp <- Parser pDone
let (mboxUp, listRes) = mkMboxUpdate untagged
return (resp, mboxUp, listRes)
pLsub :: RespDerivs -> Result RespDerivs (ServerResponse, MboxUpdate, [([Attribute], String, MailboxName)])
Parser pLsub =
do untagged <- many (pListLine "LSUB" <|> pOtherLine)
resp <- Parser pDone
let (mboxUp, listRes) = mkMboxUpdate untagged
return (resp, mboxUp, listRes)
pStatus :: RespDerivs -> Result RespDerivs (ServerResponse, MboxUpdate, [(MailboxStatus, Integer)])
Parser pStatus =
do untagged <- many (pStatusLine <|> pOtherLine)
resp <- Parser pDone
let (mboxUp, statRes) = mkMboxUpdate untagged
return (resp, mboxUp, concat statRes)
pExpunge :: RespDerivs -> Result RespDerivs (ServerResponse, MboxUpdate, [Integer])
Parser pExpunge =
do untagged <- many ((do string "* "
n <- pExpungeLine
return $ Right ("EXPUNGE", n))
<|> pOtherLine)
resp <- Parser pDone
let (mboxUp, expunges) = mkMboxUpdate untagged
return (resp, mboxUp, lookups "EXPUNGE" expunges)
pSearch :: RespDerivs -> Result RespDerivs (ServerResponse, MboxUpdate, [UID])
Parser pSearch =
do untagged <- many (pSearchLine <|> pOtherLine)
resp <- Parser pDone
let (mboxUp, searchRes) = mkMboxUpdate untagged
return (resp, mboxUp, concat searchRes)
pSelect :: RespDerivs -> Result RespDerivs (ServerResponse, MboxUpdate, MailboxInfo)
Parser pSelect =
do untagged <- many (pSelectLine
<|> (do string "* "
anyChar `manyTill` crlfP
return id))
resp <- Parser pDone
let box = case resp of
OK writable _ ->
emptyBox { _isWritable = isJust writable && fromJust writable == READ_WRITE }
_ -> emptyBox
return (resp, MboxUpdate Nothing Nothing, foldl (flip ($)) box untagged)
where emptyBox = MboxInfo "" 0 0 [] [] False False 0 0
pFetch :: RespDerivs -> Result RespDerivs (ServerResponse, MboxUpdate, [(Integer, [(String, String)])])
Parser pFetch =
do untagged <- many (pFetchLine <|> pOtherLine)
resp <- Parser pDone
let (mboxUp, fetchRes) = mkMboxUpdate untagged
return (resp, mboxUp, fetchRes)
pDone :: RespDerivs -> Result RespDerivs ServerResponse
Parser pDone = do tag <- Parser advTag
string tag >> space
respCode <- parseCode
space
stat <- optional (do s <- parseStatusCode
space >> return s)
body <- anyChar `manyTill` crlfP
return $ respCode stat body
where parseCode = choice $ [ string "OK" >> return OK
, string "NO" >> return NO
, string "BAD" >> return BAD
, string "PREAUTH" >> return PREAUTH
]
parseStatusCode =
between (char '[') (char ']') $
choice [ string "ALERT" >> return ALERT
, do { string "BADCHARSET"
; ws <- optional parenWords
; return $ BADCHARSET $ fromMaybe [] ws }
, do { string "CAPABILITY"
; space
; ws <- (many1 $ noneOf " ]") `sepBy1` space
; return $ CAPABILITY_sc ws }
, string "PARSE" >> return PARSE
, do { string "PERMANENTFLAGS" >> space >> char '('
; fs <- pFlag `sepBy1` spaces1
; char ')'
; return $ PERMANENTFLAGS fs }
, string "READ-ONLY" >> return READ_ONLY
, string "READ-WRITE" >> return READ_WRITE
, string "TRYCREATE" >> return TRYCREATE
, do { string "UNSEEN" >> space
; num <- many1 digit
; return $ UNSEEN_sc $ read num }
, do { string "UIDNEXT" >> space
; num <- many1 digit
; return $ UIDNEXT_sc $ read num }
, do { string "UIDVALIDITY" >> space
; num <- many1 digit
; return $ UIDVALIDITY_sc $ read num }
]
parenWords = between (space >> char '(') (char ')')
(many1 (noneOf " )") `sepBy1` space)
pFlag :: Parser RespDerivs Flag
pFlag = do char '\\'
choice [ string "Seen" >> return Seen
, string "Answered" >> return Answered
, string "Flagged" >> return Flagged
, string "Deleted" >> return Deleted
, string "Draft" >> return Draft
, string "Recent" >> return Recent
, char '*' >> return (Keyword "*")
, many1 atomChar >>= return . Keyword ]
<|> (many1 atomChar >>= return . Keyword)
pParenFlags :: RespDerivs -> Result RespDerivs [Flag]
Parser pParenFlags = do char '('
fs <- pFlag `sepBy` space
char ')'
return fs
atomChar :: Derivs d => Parser d Char
atomChar = noneOf " (){%*\"\\]"
pNumberedLine :: String -> Parser RespDerivs Integer
pNumberedLine str = do num <- many1 digit
space
string str
crlfP
return $ read num
pExistsLine, pRecentLine, pExpungeLine :: Parser RespDerivs Integer
pExistsLine = pNumberedLine "EXISTS"
pRecentLine = pNumberedLine "RECENT"
pExpungeLine = pNumberedLine "EXPUNGE"
pOtherLine :: Parser RespDerivs (Either (String, Integer) b)
pOtherLine = do string "* "
choice [ pExistsLine >>= \n -> return (Left ("EXISTS", n))
, pRecentLine >>= \n -> return (Left ("RECENT", n))
, blankLine >> return (Left ("", 0))]
where blankLine = anyChar `manyTill` crlfP
pCapabilityLine :: Parser RespDerivs (Either a [String])
pCapabilityLine = do string "* CAPABILITY "
ws <- many1 (noneOf " \r") `sepBy` space
crlfP
return $ Right ws
pListLine :: String
-> Parser RespDerivs (Either a ([Attribute], String, MailboxName))
pListLine list =
do string "* " >> string list >> space
attrs <- parseAttrs
sep <- parseSep
mbox <- parseMailbox
return $ Right (attrs, sep, mbox)
where parseAttr =
do char '\\'
choice [ string "Noinferior" >> return Noinferiors
, string "Noselect" >> return Noselect
, string "Marked" >> return Marked
, string "Unmarked" >> return Unmarked
, many atomChar >>= return . OtherAttr
]
parseAttrs = do char '('
attrs <- parseAttr `sepBy` space
char ')'
return attrs
parseSep = space >> char '"' >> anyChar `manyTill` char '"'
parseMailbox = do space
q <- optional $ char '"'
case q of
Just _ -> do mbox <- anyChar `manyTill` char '"'
anyChar `manyTill` crlfP
return mbox
Nothing -> anyChar `manyTill` crlfP
pStatusLine :: Parser RespDerivs (Either a [(MailboxStatus, Integer)])
pStatusLine =
do string "* STATUS "
_ <- anyChar `manyTill` space
stats <- between (char '(') (char ')') (parseStat `sepBy1` space)
crlfP
return $ Right stats
where parseStat =
do cons <- choice [ string "MESSAGES" >>= return . read
, string "RECENT" >>= return . read
, string "UIDNEXT" >>= return . read
, string "UIDVALIDITY" >>= return . read
]
space
num <- many1 digit >>= return . read
return (cons, num)
pSearchLine :: Parser RespDerivs (Either a [UID])
pSearchLine = do string "* SEARCH "
nums <- (many1 digit) `sepBy` space
crlfP
return $ Right $ map read nums
pSelectLine :: Parser RespDerivs (MailboxInfo -> MailboxInfo)
pSelectLine =
do string "* "
choice [ pExistsLine >>= \n -> return (\mbox -> mbox { _exists = n })
, pRecentLine >>= \n -> return (\mbox -> mbox { _recent = n })
, pFlags >>= \fs -> return (\mbox -> mbox { _flags = fs })
, string "OK " >> okResps ]
where pFlags = do string "FLAGS "
char '('
fs <- pFlag `sepBy` space
char ')' >> crlfP
return fs
okResps =
do char '['
v <- choice [ do { string "UNSEEN "
; many1 digit
; return id }
, do { string "PERMANENTFLAGS ("
; fs <- pFlag `sepBy` space
; char ')'
; return $ \mbox ->
mbox { _isFlagWritable =
Keyword "*" `elem` fs
, _permanentFlags =
filter (/= Keyword "*") fs } }
, do { string "UIDNEXT "
; n <- many1 digit
; return $ \mbox ->
mbox { _uidNext = read n } }
, do { string "UIDVALIDITY "
; n <- many1 digit
; return $ \mbox ->
mbox { _uidValidity = read n } }
]
char ']'
anyChar `manyTill` crlfP
return v
pFetchLine :: Parser RespDerivs (Either a (Integer, [(String, String)]))
pFetchLine =
do string "* "
num <- many1 digit
string " FETCH" >> spaces
char '('
pairs <- pPair `sepBy` space
char ')'
crlfP
return $ Right $ (read num, pairs)
where pPair = do key <- (do k <- anyChar `manyTill` char '['
ps <- anyChar `manyTill` char ']'
space
return (k++"["++ps++"]"))
<|> anyChar `manyTill` space
value <- (do char '('
v <- pParen `sepBy` space
char ')'
return ("("++unwords v++")"))
<|> (do char '{'
num <- many1 digit >>= return . read
char '}' >> crlfP
sequence $ replicate num anyChar)
<|> (do char '"'
v <- noneOf "\"" `manyTill` char '"'
return ("\""++v++"\""))
<|> many1 atomChar
return (key, value)
pParen = (do char '"'
v <- noneOf "\"" `manyTill` char '"'
return ("\""++v++"\""))
<|> (do char '('
v <- pParen `sepBy` space
char ')'
return ("("++unwords v++")"))
<|> (do char '\\'
v <- many1 atomChar
return ('\\':v))
<|> many1 atomChar
----------------------------------------------------------------------
-- auxiliary parsers
space :: Parser RespDerivs Char
space = char ' '
spaces, spaces1 :: Parser RespDerivs String
spaces = many space
spaces1 = many1 space
crlf :: String
crlf = "\r\n"
crlfP :: Derivs d => Parser d String
crlfP = string crlf
lookups :: Eq a => a -> [(a, b)] -> [b]
lookups _ [] = []
lookups k ((k', v):tl) | k == k' = v : lookups k tl
| otherwise = lookups k tl
---- Either handling
catRights :: [Either a b] -> [b]
catRights [] = []
catRights (Right r:tl) = r : catRights tl
catRights (_:tl) = catRights tl
catLefts :: [Either a b] -> [a]
catLefts [] = []
catLefts (Left r:tl) = r : catLefts tl
catLefts (_:tl) = catLefts tl
| lemol/HaskellNet | src/Network/HaskellNet/IMAP/Parsers.hs | bsd-3-clause | 15,800 | 0 | 20 | 6,739 | 4,729 | 2,352 | 2,377 | 338 | 2 |
-----------------------------------------------------------------------------
-- |
-- Module : Data.Ranged.Boundaries
-- Copyright : (c) Paul Johnson 2006
-- License : BSD-style
-- Maintainer : paul@cogito.org.uk
-- Stability : experimental
-- Portability : portable
--
-----------------------------------------------------------------------------
module Data.Ranged.Boundaries (
DiscreteOrdered (..),
enumAdjacent,
boundedAdjacent,
boundedBelow,
Boundary (..),
above,
(/>/)
) where
import Data.Ratio
import Test.QuickCheck
infix 4 />/
{- |
Distinguish between dense and sparse ordered types. A dense type is
one in which any two values @v1 < v2@ have a third value @v3@ such that
@v1 < v3 < v2@.
In theory the floating types are dense, although in practice they can only have
finitely many values. This class treats them as dense.
Tuples up to 4 members are declared as instances. Larger tuples may be added
if necessary.
Most values of sparse types have an @adjacentBelow@, such that, for all x:
> case adjacentBelow x of
> Just x1 -> adjacent x1 x
> Nothing -> True
The exception is for bounded types when @x == lowerBound@. For dense types
@adjacentBelow@ always returns 'Nothing'.
This approach was suggested by Ben Rudiak-Gould on comp.lang.functional.
-}
class Ord a => DiscreteOrdered a where
-- | Two values @x@ and @y@ are adjacent if @x < y@ and there does not
-- exist a third value between them. Always @False@ for dense types.
adjacent :: a -> a -> Bool
-- | The value immediately below the argument, if it can be determined.
adjacentBelow :: a -> Maybe a
-- Implementation note: the precise rules about unbounded enumerated vs
-- bounded enumerated types are difficult to express using Haskell 98, so
-- the prelude types are listed individually here.
instance DiscreteOrdered Bool where
adjacent = boundedAdjacent
adjacentBelow = boundedBelow
instance DiscreteOrdered Ordering where
adjacent = boundedAdjacent
adjacentBelow = boundedBelow
instance DiscreteOrdered Char where
adjacent = boundedAdjacent
adjacentBelow = boundedBelow
instance DiscreteOrdered Int where
adjacent = boundedAdjacent
adjacentBelow = boundedBelow
instance DiscreteOrdered Integer where
adjacent = enumAdjacent
adjacentBelow = Just . pred
instance DiscreteOrdered Double where
adjacent _ _ = False
adjacentBelow = const Nothing
instance DiscreteOrdered Float where
adjacent _ _ = False
adjacentBelow = const Nothing
instance (Integral a) => DiscreteOrdered (Ratio a) where
adjacent _ _ = False
adjacentBelow = const Nothing
instance Ord a => DiscreteOrdered [a] where
adjacent _ _ = False
adjacentBelow = const Nothing
instance (Ord a, DiscreteOrdered b) => DiscreteOrdered (a, b)
where
adjacent (x1, x2) (y1, y2) = (x1 == y1) && adjacent x2 y2
adjacentBelow (x1, x2) = do -- Maybe monad
x2' <- adjacentBelow x2
return (x1, x2')
instance (Ord a, Ord b, DiscreteOrdered c) => DiscreteOrdered (a, b, c)
where
adjacent (x1, x2, x3) (y1, y2, y3) =
(x1 == y1) && (x2 == y2) && adjacent x3 y3
adjacentBelow (x1, x2, x3) = do -- Maybe monad
x3' <- adjacentBelow x3
return (x1, x2, x3')
instance (Ord a, Ord b, Ord c, DiscreteOrdered d) =>
DiscreteOrdered (a, b, c, d)
where
adjacent (x1, x2, x3, x4) (y1, y2, y3, y4) =
(x1 == y1) && (x2 == y2) && (x3 == y3) && adjacent x4 y4
adjacentBelow (x1, x2, x3, x4) = do -- Maybe monad
x4' <- adjacentBelow x4
return (x1, x2, x3, x4')
-- | Check adjacency for sparse enumerated types (i.e. where there
-- is no value between @x@ and @succ x@).
enumAdjacent :: (Ord a, Enum a) => a -> a -> Bool
enumAdjacent x y = (succ x == y)
-- | Check adjacency, allowing for case where x = maxBound. Use as the
-- definition of "adjacent" for bounded enumerated types such as Int and Char.
boundedAdjacent :: (Ord a, Enum a) => a -> a -> Bool
boundedAdjacent x y = if x < y then succ x == y else False
-- | The usual implementation of 'adjacentBelow' for bounded enumerated types.
boundedBelow :: (Eq a, Enum a, Bounded a) => a -> Maybe a
boundedBelow x = if x == minBound then Nothing else Just $ pred x
{- |
A Boundary is a division of an ordered type into values above
and below the boundary. No value can sit on a boundary.
Known bug: for Bounded types
* @BoundaryAbove maxBound < BoundaryAboveAll@
* @BoundaryBelow minBound > BoundaryBelowAll@
This is incorrect because there are no possible values in
between the left and right sides of these inequalities.
-}
data Boundary a =
-- | The argument is the highest value below the boundary.
BoundaryAbove a |
-- | The argument is the lowest value above the boundary.
BoundaryBelow a |
-- | The boundary above all values.
BoundaryAboveAll |
-- | The boundary below all values.
BoundaryBelowAll
deriving (Show)
-- | True if the value is above the boundary, false otherwise.
above :: Ord v => Boundary v -> v -> Bool
above (BoundaryAbove b) v = v > b
above (BoundaryBelow b) v = v >= b
above BoundaryAboveAll _ = False
above BoundaryBelowAll _ = True
-- | Same as 'above', but with the arguments reversed for more intuitive infix
-- usage.
(/>/) :: Ord v => v -> Boundary v -> Bool
(/>/) = flip above
instance (DiscreteOrdered a) => Eq (Boundary a) where
b1 == b2 = compare b1 b2 == EQ
instance (DiscreteOrdered a) => Ord (Boundary a) where
-- Comparison alogrithm based on brute force and ignorance:
-- enumerate all combinations.
compare boundary1 boundary2 =
case boundary1 of
BoundaryAbove b1 ->
case boundary2 of
BoundaryAbove b2 -> compare b1 b2
BoundaryBelow b2 ->
if b1 < b2
then
if adjacent b1 b2 then EQ else LT
else GT
BoundaryAboveAll -> LT
BoundaryBelowAll -> GT
BoundaryBelow b1 ->
case boundary2 of
BoundaryAbove b2 ->
if b1 > b2
then
if adjacent b2 b1 then EQ else GT
else LT
BoundaryBelow b2 -> compare b1 b2
BoundaryAboveAll -> LT
BoundaryBelowAll -> GT
BoundaryAboveAll ->
case boundary2 of
BoundaryAboveAll -> EQ
_ -> GT
BoundaryBelowAll ->
case boundary2 of
BoundaryBelowAll -> EQ
_ -> LT
-- QuickCheck Generator
instance Arbitrary a => Arbitrary (Boundary a) where
arbitrary = frequency [
(1, return BoundaryAboveAll),
(1, return BoundaryBelowAll),
(18, do
v <- arbitrary
oneof [return $ BoundaryAbove v, return $ BoundaryBelow v]
)]
instance CoArbitrary a => CoArbitrary (Boundary a) where
coarbitrary BoundaryBelowAll = variant (0 :: Int)
coarbitrary BoundaryAboveAll = variant (1 :: Int)
coarbitrary (BoundaryBelow v) = variant (2 :: Int) . coarbitrary v
coarbitrary (BoundaryAbove v) = variant (3 :: Int) . coarbitrary v
| beni55/alex | src/Data/Ranged/Boundaries.hs | bsd-3-clause | 7,294 | 0 | 14 | 1,961 | 1,551 | 836 | 715 | 121 | 2 |
f x = y
where
y = 2 * x
| ruchee/vimrc | vimfiles/bundle/vim-haskell/tests/indent/test015/test.hs | mit | 24 | 0 | 5 | 10 | 21 | 10 | 11 | -1 | -1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE TupleSections #-}
module Stack.Setup
( setupEnv
, ensureGHC
, SetupOpts (..)
, defaultStackSetupYaml
) where
import Control.Applicative
import Control.Exception.Enclosed (catchIO, tryAny)
import Control.Monad (liftM, when, join, void, unless)
import Control.Monad.Catch
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Logger
import Control.Monad.Reader (MonadReader, ReaderT (..), asks)
import Control.Monad.State (get, put, modify)
import Control.Monad.Trans.Control
import Crypto.Hash (SHA1(SHA1))
import Data.Aeson.Extended
import Data.ByteString (ByteString)
import qualified Data.ByteString as S
import qualified Data.ByteString.Char8 as S8
import Data.Conduit (Conduit, ($$), (=$), await, yield, awaitForever)
import Data.Conduit.Lift (evalStateC)
import qualified Data.Conduit.List as CL
import Data.Either
import Data.Foldable hiding (concatMap, or)
import Data.IORef
import Data.IORef.RunOnce (runOnce)
import Data.List hiding (concat, elem, maximumBy)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import Data.Monoid
import Data.Ord (comparing)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Encoding.Error as T
import Data.Time.Clock (NominalDiffTime, diffUTCTime, getCurrentTime)
import Data.Typeable (Typeable)
import qualified Data.Yaml as Yaml
import Distribution.System (OS, Arch (..), Platform (..))
import qualified Distribution.System as Cabal
import Distribution.Text (simpleParse)
import Network.HTTP.Client.Conduit
import Network.HTTP.Download.Verified
import Path
import Path.IO
import Prelude hiding (concat, elem) -- Fix AMP warning
import Safe (headMay, readMay)
import Stack.Types.Build
import Stack.Config (resolvePackageEntry)
import Stack.Constants (distRelativeDir)
import Stack.Fetch
import Stack.GhcPkg (createDatabase, getCabalPkgVer, getGlobalDB, mkGhcPackagePath)
import Stack.Solver (getCompilerVersion)
import Stack.Types
import Stack.Types.StackT
import qualified System.Directory as D
import System.Environment (getExecutablePath)
import System.Exit (ExitCode (ExitSuccess))
import System.FilePath (searchPathSeparator)
import qualified System.FilePath as FP
import System.IO.Temp (withSystemTempDirectory)
import System.Process (rawSystem)
import System.Process.Read
import System.Process.Run (runIn)
import Text.Printf (printf)
-- | Default location of the stack-setup.yaml file
defaultStackSetupYaml :: String
defaultStackSetupYaml =
"https://raw.githubusercontent.com/fpco/stackage-content/master/stack/stack-setup-2.yaml"
data SetupOpts = SetupOpts
{ soptsInstallIfMissing :: !Bool
, soptsUseSystem :: !Bool
, soptsWantedCompiler :: !CompilerVersion
, soptsCompilerCheck :: !VersionCheck
, soptsStackYaml :: !(Maybe (Path Abs File))
-- ^ If we got the desired GHC version from that file
, soptsForceReinstall :: !Bool
, soptsSanityCheck :: !Bool
-- ^ Run a sanity check on the selected GHC
, soptsSkipGhcCheck :: !Bool
-- ^ Don't check for a compatible GHC version/architecture
, soptsSkipMsys :: !Bool
-- ^ Do not use a custom msys installation on Windows
, soptsUpgradeCabal :: !Bool
-- ^ Upgrade the global Cabal library in the database to the newest
-- version. Only works reliably with a stack-managed installation.
, soptsResolveMissingGHC :: !(Maybe Text)
-- ^ Message shown to user for how to resolve the missing GHC
, soptsStackSetupYaml :: !String
}
deriving Show
data SetupException = UnsupportedSetupCombo OS Arch
| MissingDependencies [String]
| UnknownCompilerVersion Text CompilerVersion (Set Version)
| UnknownOSKey Text
| GHCSanityCheckCompileFailed ReadProcessException (Path Abs File)
deriving Typeable
instance Exception SetupException
instance Show SetupException where
show (UnsupportedSetupCombo os arch) = concat
[ "I don't know how to install GHC for "
, show (os, arch)
, ", please install manually"
]
show (MissingDependencies tools) =
"The following executables are missing and must be installed: " ++
intercalate ", " tools
show (UnknownCompilerVersion oskey wanted known) = concat
[ "No information found for "
, T.unpack (compilerVersionName wanted)
, ".\nSupported versions for OS key '" ++ T.unpack oskey ++ "': "
, intercalate ", " (map show $ Set.toList known)
]
show (UnknownOSKey oskey) =
"Unable to find installation URLs for OS key: " ++
T.unpack oskey
show (GHCSanityCheckCompileFailed e ghc) = concat
[ "The GHC located at "
, toFilePath ghc
, " failed to compile a sanity check. Please see:\n\n"
, " https://github.com/commercialhaskell/stack/wiki/Downloads\n\n"
, "for more information. Exception was:\n"
, show e
]
-- | Modify the environment variables (like PATH) appropriately, possibly doing installation too
setupEnv :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasBuildConfig env, HasHttpManager env, MonadBaseControl IO m)
=> Maybe Text -- ^ Message to give user when necessary GHC is not available
-> m EnvConfig
setupEnv mResolveMissingGHC = do
bconfig <- asks getBuildConfig
let platform = getPlatform bconfig
wc = whichCompiler (bcWantedCompiler bconfig)
sopts = SetupOpts
{ soptsInstallIfMissing = configInstallGHC $ bcConfig bconfig
, soptsUseSystem = configSystemGHC $ bcConfig bconfig
, soptsWantedCompiler = bcWantedCompiler bconfig
, soptsCompilerCheck = configCompilerCheck $ bcConfig bconfig
, soptsStackYaml = Just $ bcStackYaml bconfig
, soptsForceReinstall = False
, soptsSanityCheck = False
, soptsSkipGhcCheck = configSkipGHCCheck $ bcConfig bconfig
, soptsSkipMsys = configSkipMsys $ bcConfig bconfig
, soptsUpgradeCabal = False
, soptsResolveMissingGHC = mResolveMissingGHC
, soptsStackSetupYaml = defaultStackSetupYaml
}
mghcBin <- ensureGHC sopts
-- Modify the initial environment to include the GHC path, if a local GHC
-- is being used
menv0 <- getMinimalEnvOverride
let env = removeHaskellEnvVars
$ augmentPathMap (maybe [] edBins mghcBin)
$ unEnvOverride menv0
menv <- mkEnvOverride platform env
compilerVer <- getCompilerVersion menv wc
cabalVer <- getCabalPkgVer menv wc
packages <- mapM
(resolvePackageEntry menv (bcRoot bconfig))
(bcPackageEntries bconfig)
let envConfig0 = EnvConfig
{ envConfigBuildConfig = bconfig
, envConfigCabalVersion = cabalVer
, envConfigCompilerVersion = compilerVer
, envConfigPackages = Map.fromList $ concat packages
}
-- extra installation bin directories
mkDirs <- runReaderT extraBinDirs envConfig0
let mpath = Map.lookup "PATH" env
mkDirs' = map toFilePath . mkDirs
depsPath = augmentPath (mkDirs' False) mpath
localsPath = augmentPath (mkDirs' True) mpath
deps <- runReaderT packageDatabaseDeps envConfig0
createDatabase menv wc deps
localdb <- runReaderT packageDatabaseLocal envConfig0
createDatabase menv wc localdb
globaldb <- getGlobalDB menv wc
let mkGPP locals = mkGhcPackagePath locals localdb deps globaldb
distDir <- runReaderT distRelativeDir envConfig0
executablePath <- liftIO getExecutablePath
utf8EnvVars <- getUtf8LocaleVars menv
envRef <- liftIO $ newIORef Map.empty
let getEnvOverride' es = do
m <- readIORef envRef
case Map.lookup es m of
Just eo -> return eo
Nothing -> do
eo <- mkEnvOverride platform
$ Map.insert "PATH" (if esIncludeLocals es then localsPath else depsPath)
$ (if esIncludeGhcPackagePath es
then Map.insert
(case wc of { Ghc -> "GHC_PACKAGE_PATH"; Ghcjs -> "GHCJS_PACKAGE_PATH" })
(mkGPP (esIncludeLocals es))
else id)
$ (if esStackExe es
then Map.insert "STACK_EXE" (T.pack executablePath)
else id)
$ (if esLocaleUtf8 es
then Map.union utf8EnvVars
else id)
-- For reasoning and duplication, see: https://github.com/fpco/stack/issues/70
$ Map.insert "HASKELL_PACKAGE_SANDBOX" (T.pack $ toFilePathNoTrailingSlash deps)
$ Map.insert "HASKELL_PACKAGE_SANDBOXES"
(T.pack $ if esIncludeLocals es
then intercalate [searchPathSeparator]
[ toFilePathNoTrailingSlash localdb
, toFilePathNoTrailingSlash deps
, ""
]
else intercalate [searchPathSeparator]
[ toFilePathNoTrailingSlash deps
, ""
])
$ Map.insert "HASKELL_DIST_DIR" (T.pack $ toFilePathNoTrailingSlash distDir)
$ env
!() <- atomicModifyIORef envRef $ \m' ->
(Map.insert es eo m', ())
return eo
return EnvConfig
{ envConfigBuildConfig = bconfig
{ bcConfig = maybe id addIncludeLib mghcBin
(bcConfig bconfig)
{ configEnvOverride = getEnvOverride' }
}
, envConfigCabalVersion = cabalVer
, envConfigCompilerVersion = compilerVer
, envConfigPackages = envConfigPackages envConfig0
}
-- | Add the include and lib paths to the given Config
addIncludeLib :: ExtraDirs -> Config -> Config
addIncludeLib (ExtraDirs _bins includes libs) config = config
{ configExtraIncludeDirs = Set.union
(configExtraIncludeDirs config)
(Set.fromList $ map T.pack includes)
, configExtraLibDirs = Set.union
(configExtraLibDirs config)
(Set.fromList $ map T.pack libs)
}
data ExtraDirs = ExtraDirs
{ edBins :: ![FilePath]
, edInclude :: ![FilePath]
, edLib :: ![FilePath]
}
instance Monoid ExtraDirs where
mempty = ExtraDirs [] [] []
mappend (ExtraDirs a b c) (ExtraDirs x y z) = ExtraDirs
(a ++ x)
(b ++ y)
(c ++ z)
-- | Ensure GHC is installed and provide the PATHs to add if necessary
ensureGHC :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m)
=> SetupOpts
-> m (Maybe ExtraDirs)
ensureGHC sopts = do
let wc = whichCompiler (soptsWantedCompiler sopts)
ghcVersion = case soptsWantedCompiler sopts of
GhcVersion v -> v
GhcjsVersion _ v -> v
when (ghcVersion < $(mkVersion "7.8")) $ do
$logWarn "stack will almost certainly fail with GHC below version 7.8"
$logWarn "Valiantly attempting to run anyway, but I know this is doomed"
$logWarn "For more information, see: https://github.com/commercialhaskell/stack/issues/648"
$logWarn ""
-- Check the available GHCs
menv0 <- getMinimalEnvOverride
msystem <-
if soptsUseSystem sopts
then getSystemCompiler menv0 wc
else return Nothing
Platform expectedArch _ <- asks getPlatform
let needLocal = case msystem of
Nothing -> True
Just _ | soptsSkipGhcCheck sopts -> False
Just (system, arch) ->
not (isWanted system) ||
arch /= expectedArch
isWanted = isWantedCompiler (soptsCompilerCheck sopts) (soptsWantedCompiler sopts)
-- If we need to install a GHC, try to do so
mpaths <- if needLocal
then do
getSetupInfo' <- runOnce (getSetupInfo sopts =<< asks getHttpManager)
config <- asks getConfig
installed <- runReaderT listInstalled config
-- Install GHC
ghcIdent <- case getInstalledTool installed $(mkPackageName "ghc") (isWanted . GhcVersion) of
Just ident -> return ident
Nothing
| soptsInstallIfMissing sopts -> do
si <- getSetupInfo'
downloadAndInstallGHC menv0 si (soptsWantedCompiler sopts) (soptsCompilerCheck sopts)
| otherwise -> do
Platform arch _ <- asks getPlatform
throwM $ CompilerVersionMismatch
msystem
(soptsWantedCompiler sopts, arch)
(soptsCompilerCheck sopts)
(soptsStackYaml sopts)
(fromMaybe
"Try running \"stack setup\" to locally install the correct GHC"
$ soptsResolveMissingGHC sopts)
-- Install msys2 on windows, if necessary
mmsys2Ident <- case configPlatform config of
Platform _ os | isWindows os && not (soptsSkipMsys sopts) ->
case getInstalledTool installed $(mkPackageName "msys2") (const True) of
Just ident -> return (Just ident)
Nothing
| soptsInstallIfMissing sopts -> do
si <- getSetupInfo'
osKey <- getOSKey menv0
VersionedDownloadInfo version info <-
case Map.lookup osKey $ siMsys2 si of
Just x -> return x
Nothing -> error $ "MSYS2 not found for " ++ T.unpack osKey
Just <$> downloadAndInstallTool si info $(mkPackageName "msys2") version (installMsys2Windows osKey)
| otherwise -> do
$logWarn "Continuing despite missing tool: msys2"
return Nothing
_ -> return Nothing
let idents = catMaybes [Just ghcIdent, mmsys2Ident]
paths <- runReaderT (mapM extraDirs idents) config
return $ Just $ mconcat paths
else return Nothing
menv <-
case mpaths of
Nothing -> return menv0
Just ed -> do
config <- asks getConfig
let m0 = unEnvOverride menv0
path0 = Map.lookup "PATH" m0
path = augmentPath (edBins ed) path0
m = Map.insert "PATH" path m0
mkEnvOverride (configPlatform config) (removeHaskellEnvVars m)
when (soptsUpgradeCabal sopts) $ do
unless needLocal $ do
$logWarn "Trying to upgrade Cabal library on a GHC not installed by stack."
$logWarn "This may fail, caveat emptor!"
upgradeCabal menv wc
when (soptsSanityCheck sopts) $ sanityCheck menv
return mpaths
-- | Install the newest version of Cabal globally
upgradeCabal :: (MonadIO m, MonadLogger m, MonadReader env m, HasHttpManager env, HasConfig env, MonadBaseControl IO m, MonadMask m)
=> EnvOverride
-> WhichCompiler
-> m ()
upgradeCabal menv wc = do
let name = $(mkPackageName "Cabal")
rmap <- resolvePackages menv Set.empty (Set.singleton name)
newest <-
case Map.keys rmap of
[] -> error "No Cabal library found in index, cannot upgrade"
[PackageIdentifier name' version]
| name == name' -> return version
x -> error $ "Unexpected results for resolvePackages: " ++ show x
installed <- getCabalPkgVer menv wc
if installed >= newest
then $logInfo $ T.concat
[ "Currently installed Cabal is "
, T.pack $ versionString installed
, ", newest is "
, T.pack $ versionString newest
, ". I'm not upgrading Cabal."
]
else withSystemTempDirectory "stack-cabal-upgrade" $ \tmpdir -> do
$logInfo $ T.concat
[ "Installing Cabal-"
, T.pack $ versionString newest
, " to replace "
, T.pack $ versionString installed
]
tmpdir' <- parseAbsDir tmpdir
let ident = PackageIdentifier name newest
m <- unpackPackageIdents menv tmpdir' Nothing (Set.singleton ident)
compilerPath <- join $ findExecutable menv (compilerExeName wc)
newestDir <- parseRelDir $ versionString newest
let installRoot = toFilePath $ parent (parent compilerPath)
</> $(mkRelDir "new-cabal")
</> newestDir
dir <-
case Map.lookup ident m of
Nothing -> error $ "upgradeCabal: Invariant violated, dir missing"
Just dir -> return dir
runIn dir (compilerExeName wc) menv ["Setup.hs"] Nothing
let setupExe = toFilePath $ dir </> $(mkRelFile "Setup")
dirArgument name' = concat
[ "--"
, name'
, "dir="
, installRoot FP.</> name'
]
runIn dir setupExe menv
( "configure"
: map dirArgument (words "lib bin data doc")
)
Nothing
runIn dir setupExe menv ["build"] Nothing
runIn dir setupExe menv ["install"] Nothing
$logInfo "New Cabal library installed"
-- | Get the version of the system compiler, if available
getSystemCompiler :: (MonadIO m, MonadLogger m, MonadBaseControl IO m, MonadCatch m) => EnvOverride -> WhichCompiler -> m (Maybe (CompilerVersion, Arch))
getSystemCompiler menv wc = do
let exeName = case wc of
Ghc -> "ghc"
Ghcjs -> "ghcjs"
exists <- doesExecutableExist menv exeName
if exists
then do
eres <- tryProcessStdout Nothing menv exeName ["--info"]
let minfo = do
Right bs <- Just eres
pairs <- readMay $ S8.unpack bs :: Maybe [(String, String)]
version <- lookup "Project version" pairs >>= parseVersionFromString
arch <- lookup "Target platform" pairs >>= simpleParse . takeWhile (/= '-')
return (version, arch)
case (wc, minfo) of
(Ghc, Just (version, arch)) -> return (Just (GhcVersion version, arch))
(Ghcjs, Just (_, arch)) -> do
eversion <- tryAny $ getCompilerVersion menv Ghcjs
case eversion of
Left _ -> return Nothing
Right version -> return (Just (version, arch))
(_, Nothing) -> return Nothing
else return Nothing
data DownloadInfo = DownloadInfo
{ downloadInfoUrl :: Text
, downloadInfoContentLength :: Int
, downloadInfoSha1 :: Maybe ByteString
}
deriving Show
data VersionedDownloadInfo = VersionedDownloadInfo
{ vdiVersion :: Version
, vdiDownloadInfo :: DownloadInfo
}
deriving Show
parseDownloadInfoFromObject :: Yaml.Object -> Yaml.Parser DownloadInfo
parseDownloadInfoFromObject o = do
url <- o .: "url"
contentLength <- o .: "content-length"
sha1TextMay <- o .:? "sha1"
return DownloadInfo
{ downloadInfoUrl = url
, downloadInfoContentLength = contentLength
, downloadInfoSha1 = fmap T.encodeUtf8 sha1TextMay
}
instance FromJSON DownloadInfo where
parseJSON = withObject "DownloadInfo" parseDownloadInfoFromObject
instance FromJSON VersionedDownloadInfo where
parseJSON = withObject "VersionedDownloadInfo" $ \o -> do
version <- o .: "version"
downloadInfo <- parseDownloadInfoFromObject o
return VersionedDownloadInfo
{ vdiVersion = version
, vdiDownloadInfo = downloadInfo
}
data SetupInfo = SetupInfo
{ siSevenzExe :: DownloadInfo
, siSevenzDll :: DownloadInfo
, siMsys2 :: Map Text VersionedDownloadInfo
, siGHCs :: Map Text (Map Version DownloadInfo)
}
deriving Show
instance FromJSON SetupInfo where
parseJSON = withObject "SetupInfo" $ \o -> SetupInfo
<$> o .: "sevenzexe-info"
<*> o .: "sevenzdll-info"
<*> o .: "msys2"
<*> o .: "ghc"
-- | Download the most recent SetupInfo
getSetupInfo :: (MonadIO m, MonadThrow m) => SetupOpts -> Manager -> m SetupInfo
getSetupInfo sopts manager = do
bs <-
case parseUrl $ soptsStackSetupYaml sopts of
Just req -> do
bss <- liftIO $ flip runReaderT manager
$ withResponse req $ \res -> responseBody res $$ CL.consume
return $ S8.concat bss
Nothing -> liftIO $ S.readFile $ soptsStackSetupYaml sopts
either throwM return $ Yaml.decodeEither' bs
markInstalled :: (MonadIO m, MonadReader env m, HasConfig env, MonadThrow m)
=> PackageIdentifier -- ^ e.g., ghc-7.8.4, msys2-20150512
-> m ()
markInstalled ident = do
dir <- asks $ configLocalPrograms . getConfig
fpRel <- parseRelFile $ packageIdentifierString ident ++ ".installed"
liftIO $ writeFile (toFilePath $ dir </> fpRel) "installed"
unmarkInstalled :: (MonadIO m, MonadReader env m, HasConfig env, MonadThrow m)
=> PackageIdentifier
-> m ()
unmarkInstalled ident = do
dir <- asks $ configLocalPrograms . getConfig
fpRel <- parseRelFile $ packageIdentifierString ident ++ ".installed"
removeFileIfExists $ dir </> fpRel
listInstalled :: (MonadIO m, MonadReader env m, HasConfig env, MonadThrow m)
=> m [PackageIdentifier]
listInstalled = do
dir <- asks $ configLocalPrograms . getConfig
createTree dir
(_, files) <- listDirectory dir
return $ mapMaybe toIdent files
where
toIdent fp = do
x <- T.stripSuffix ".installed" $ T.pack $ toFilePath $ filename fp
parsePackageIdentifierFromString $ T.unpack x
installDir :: (MonadReader env m, HasConfig env, MonadThrow m, MonadLogger m)
=> PackageIdentifier
-> m (Path Abs Dir)
installDir ident = do
config <- asks getConfig
reldir <- parseRelDir $ packageIdentifierString ident
return $ configLocalPrograms config </> reldir
-- | Binary directories for the given installed package
extraDirs :: (MonadReader env m, HasConfig env, MonadThrow m, MonadLogger m)
=> PackageIdentifier
-> m ExtraDirs
extraDirs ident = do
config <- asks getConfig
dir <- installDir ident
case (configPlatform config, packageNameString $ packageIdentifierName ident) of
(Platform _ (isWindows -> True), "ghc") -> return mempty
{ edBins = goList
[ dir </> $(mkRelDir "bin")
, dir </> $(mkRelDir "mingw") </> $(mkRelDir "bin")
]
}
(Platform _ (isWindows -> True), "msys2") -> return mempty
{ edBins = goList
[ dir </> $(mkRelDir "usr") </> $(mkRelDir "bin")
]
, edInclude = goList
[ dir </> $(mkRelDir "mingw64") </> $(mkRelDir "include")
, dir </> $(mkRelDir "mingw32") </> $(mkRelDir "include")
]
, edLib = goList
[ dir </> $(mkRelDir "mingw64") </> $(mkRelDir "lib")
, dir </> $(mkRelDir "mingw32") </> $(mkRelDir "lib")
]
}
(_, "ghc") -> return mempty
{ edBins = goList
[ dir </> $(mkRelDir "bin")
]
}
(Platform _ x, tool) -> do
$logWarn $ "binDirs: unexpected OS/tool combo: " <> T.pack (show (x, tool))
return mempty
where
goList = map toFilePathNoTrailingSlash
getInstalledTool :: [PackageIdentifier] -- ^ already installed
-> PackageName -- ^ package to find
-> (Version -> Bool) -- ^ which versions are acceptable
-> Maybe PackageIdentifier
getInstalledTool installed name goodVersion =
if null available
then Nothing
else Just $ maximumBy (comparing packageIdentifierVersion) available
where
available = filter goodPackage installed
goodPackage pi' =
packageIdentifierName pi' == name &&
goodVersion (packageIdentifierVersion pi')
downloadAndInstallTool :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m)
=> SetupInfo
-> DownloadInfo
-> PackageName
-> Version
-> (SetupInfo -> Path Abs File -> ArchiveType -> Path Abs Dir -> PackageIdentifier -> m ())
-> m PackageIdentifier
downloadAndInstallTool si downloadInfo name version installer = do
let ident = PackageIdentifier name version
(file, at) <- downloadFromInfo downloadInfo ident
dir <- installDir ident
unmarkInstalled ident
installer si file at dir ident
markInstalled ident
return ident
downloadAndInstallGHC :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m)
=> EnvOverride
-> SetupInfo
-> CompilerVersion
-> VersionCheck
-> m PackageIdentifier
downloadAndInstallGHC menv si wanted versionCheck = do
osKey <- getOSKey menv
pairs <-
case Map.lookup osKey $ siGHCs si of
Nothing -> throwM $ UnknownOSKey osKey
Just pairs -> return pairs
let mpair =
listToMaybe $
sortBy (flip (comparing fst)) $
filter (\(v, _) -> isWantedCompiler versionCheck wanted (GhcVersion v)) (Map.toList pairs)
(selectedVersion, downloadInfo) <-
case mpair of
Just pair -> return pair
Nothing -> throwM $ UnknownCompilerVersion osKey wanted (Map.keysSet pairs)
platform <- asks $ configPlatform . getConfig
let installer =
case platform of
Platform _ os | isWindows os -> installGHCWindows
_ -> installGHCPosix
$logInfo "Preparing to install GHC to an isolated location."
$logInfo "This will not interfere with any system-level installation."
downloadAndInstallTool si downloadInfo $(mkPackageName "ghc") selectedVersion installer
getOSKey :: (MonadReader env m, MonadThrow m, HasConfig env, MonadLogger m, MonadIO m, MonadCatch m, MonadBaseControl IO m)
=> EnvOverride -> m Text
getOSKey menv = do
platform <- asks $ configPlatform . getConfig
case platform of
Platform I386 Cabal.Linux -> ("linux32" <>) <$> getLinuxSuffix
Platform X86_64 Cabal.Linux -> ("linux64" <>) <$> getLinuxSuffix
Platform I386 Cabal.OSX -> return "macosx"
Platform X86_64 Cabal.OSX -> return "macosx"
Platform I386 Cabal.FreeBSD -> return "freebsd32"
Platform X86_64 Cabal.FreeBSD -> return "freebsd64"
Platform I386 Cabal.OpenBSD -> return "openbsd32"
Platform X86_64 Cabal.OpenBSD -> return "openbsd64"
Platform I386 Cabal.Windows -> return "windows32"
Platform X86_64 Cabal.Windows -> return "windows64"
Platform I386 (Cabal.OtherOS "windowsintegersimple") -> return "windowsintegersimple32"
Platform X86_64 (Cabal.OtherOS "windowsintegersimple") -> return "windowsintegersimple64"
Platform arch os -> throwM $ UnsupportedSetupCombo os arch
where
getLinuxSuffix = do
executablePath <- liftIO getExecutablePath
elddOut <- tryProcessStdout Nothing menv "ldd" [executablePath]
return $ case elddOut of
Left _ -> ""
Right lddOut -> if hasLineWithFirstWord "libgmp.so.3" lddOut then "-gmp4" else ""
hasLineWithFirstWord w =
elem (Just w) . map (headMay . T.words) . T.lines . T.decodeUtf8With T.lenientDecode
downloadFromInfo :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m)
=> DownloadInfo
-> PackageIdentifier
-> m (Path Abs File, ArchiveType)
downloadFromInfo downloadInfo ident = do
config <- asks getConfig
at <-
case extension of
".tar.xz" -> return TarXz
".tar.bz2" -> return TarBz2
".7z.exe" -> return SevenZ
_ -> error $ "Unknown extension: " ++ extension
relfile <- parseRelFile $ packageIdentifierString ident ++ extension
let path = configLocalPrograms config </> relfile
chattyDownload (packageIdentifierText ident) downloadInfo path
return (path, at)
where
url = downloadInfoUrl downloadInfo
extension =
loop $ T.unpack url
where
loop fp
| ext `elem` [".tar", ".bz2", ".xz", ".exe", ".7z"] = loop fp' ++ ext
| otherwise = ""
where
(fp', ext) = FP.splitExtension fp
data ArchiveType
= TarBz2
| TarXz
| SevenZ
installGHCPosix :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m)
=> SetupInfo
-> Path Abs File
-> ArchiveType
-> Path Abs Dir
-> PackageIdentifier
-> m ()
installGHCPosix _ archiveFile archiveType destDir ident = do
platform <- asks getPlatform
menv0 <- getMinimalEnvOverride
menv <- mkEnvOverride platform (removeHaskellEnvVars (unEnvOverride menv0))
$logDebug $ "menv = " <> T.pack (show (unEnvOverride menv))
zipTool' <-
case archiveType of
TarXz -> return "xz"
TarBz2 -> return "bzip2"
SevenZ -> error "Don't know how to deal with .7z files on non-Windows"
(zipTool, makeTool, tarTool) <- checkDependencies $ (,,)
<$> checkDependency zipTool'
<*> (checkDependency "gmake" <|> checkDependency "make")
<*> checkDependency "tar"
$logDebug $ "ziptool: " <> T.pack zipTool
$logDebug $ "make: " <> T.pack makeTool
$logDebug $ "tar: " <> T.pack tarTool
withSystemTempDirectory "stack-setup" $ \root' -> do
root <- parseAbsDir root'
dir <- liftM (root Path.</>) $ parseRelDir $ packageIdentifierString ident
$logSticky $ T.concat ["Unpacking GHC into ", (T.pack . toFilePath $ root), " ..."]
$logDebug $ "Unpacking " <> T.pack (toFilePath archiveFile)
readInNull root tarTool menv ["xf", toFilePath archiveFile] Nothing
$logSticky "Configuring GHC ..."
readInNull dir (toFilePath $ dir Path.</> $(mkRelFile "configure"))
menv ["--prefix=" ++ toFilePath destDir] Nothing
$logSticky "Installing GHC ..."
readInNull dir makeTool menv ["install"] Nothing
$logStickyDone $ "Installed GHC."
$logDebug $ "GHC installed to " <> T.pack (toFilePath destDir)
where
-- | Check if given processes appear to be present, throwing an exception if
-- missing.
checkDependencies :: (MonadIO m, MonadThrow m, MonadReader env m, HasConfig env)
=> CheckDependency a -> m a
checkDependencies (CheckDependency f) = do
menv <- getMinimalEnvOverride
liftIO (f menv) >>= either (throwM . MissingDependencies) return
checkDependency :: String -> CheckDependency String
checkDependency tool = CheckDependency $ \menv -> do
exists <- doesExecutableExist menv tool
return $ if exists then Right tool else Left [tool]
newtype CheckDependency a = CheckDependency (EnvOverride -> IO (Either [String] a))
deriving Functor
instance Applicative CheckDependency where
pure x = CheckDependency $ \_ -> return (Right x)
CheckDependency f <*> CheckDependency x = CheckDependency $ \menv -> do
f' <- f menv
x' <- x menv
return $
case (f', x') of
(Left e1, Left e2) -> Left $ e1 ++ e2
(Left e, Right _) -> Left e
(Right _, Left e) -> Left e
(Right f'', Right x'') -> Right $ f'' x''
instance Alternative CheckDependency where
empty = CheckDependency $ \_ -> return $ Left []
CheckDependency x <|> CheckDependency y = CheckDependency $ \menv -> do
res1 <- x menv
case res1 of
Left _ -> y menv
Right x' -> return $ Right x'
installGHCWindows :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m)
=> SetupInfo
-> Path Abs File
-> ArchiveType
-> Path Abs Dir
-> PackageIdentifier
-> m ()
installGHCWindows si archiveFile archiveType destDir _ = do
suffix <-
case archiveType of
TarXz -> return ".xz"
TarBz2 -> return ".bz2"
_ -> error $ "GHC on Windows must be a tarball file"
tarFile <-
case T.stripSuffix suffix $ T.pack $ toFilePath archiveFile of
Nothing -> error $ "Invalid GHC filename: " ++ show archiveFile
Just x -> parseAbsFile $ T.unpack x
config <- asks getConfig
run7z <- setup7z si config
run7z (parent archiveFile) archiveFile
run7z (parent archiveFile) tarFile
removeFile tarFile `catchIO` \e ->
$logWarn (T.concat
[ "Exception when removing "
, T.pack $ toFilePath tarFile
, ": "
, T.pack $ show e
])
$logInfo $ "GHC installed to " <> T.pack (toFilePath destDir)
installMsys2Windows :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m)
=> Text -- ^ OS Key
-> SetupInfo
-> Path Abs File
-> ArchiveType
-> Path Abs Dir
-> PackageIdentifier
-> m ()
installMsys2Windows osKey si archiveFile archiveType destDir _ = do
suffix <-
case archiveType of
TarXz -> return ".xz"
TarBz2 -> return ".bz2"
_ -> error $ "MSYS2 must be a .tar.xz archive"
tarFile <-
case T.stripSuffix suffix $ T.pack $ toFilePath archiveFile of
Nothing -> error $ "Invalid MSYS2 filename: " ++ show archiveFile
Just x -> parseAbsFile $ T.unpack x
config <- asks getConfig
run7z <- setup7z si config
exists <- liftIO $ D.doesDirectoryExist $ toFilePath destDir
when exists $ liftIO (D.removeDirectoryRecursive $ toFilePath destDir) `catchIO` \e -> do
$logError $ T.pack $
"Could not delete existing msys directory: " ++
toFilePath destDir
throwM e
run7z (parent archiveFile) archiveFile
run7z (parent archiveFile) tarFile
removeFile tarFile `catchIO` \e ->
$logWarn (T.concat
[ "Exception when removing "
, T.pack $ toFilePath tarFile
, ": "
, T.pack $ show e
])
msys <- parseRelDir $ "msys" ++ T.unpack (fromMaybe "32" $ T.stripPrefix "windows" osKey)
liftIO $ D.renameDirectory
(toFilePath $ parent archiveFile </> msys)
(toFilePath destDir)
platform <- asks getPlatform
menv0 <- getMinimalEnvOverride
let oldEnv = unEnvOverride menv0
newEnv = augmentPathMap
[toFilePath $ destDir </> $(mkRelDir "usr") </> $(mkRelDir "bin")]
oldEnv
menv <- mkEnvOverride platform newEnv
-- I couldn't find this officially documented anywhere, but you need to run
-- the shell once in order to initialize some pacman stuff. Once that run
-- happens, you can just run commands as usual.
runIn destDir "sh" menv ["--login", "-c", "true"] Nothing
-- Install git. We could install other useful things in the future too.
runIn destDir "pacman" menv ["-Sy", "--noconfirm", "git"] Nothing
-- | Download 7z as necessary, and get a function for unpacking things.
--
-- Returned function takes an unpack directory and archive.
setup7z :: (MonadReader env m, HasHttpManager env, MonadThrow m, MonadIO m, MonadIO n, MonadLogger m, MonadBaseControl IO m)
=> SetupInfo
-> Config
-> m (Path Abs Dir -> Path Abs File -> n ())
setup7z si config = do
chattyDownload "7z.dll" (siSevenzDll si) dll
chattyDownload "7z.exe" (siSevenzExe si) exe
return $ \outdir archive -> liftIO $ do
ec <- rawSystem (toFilePath exe)
[ "x"
, "-o" ++ toFilePath outdir
, "-y"
, toFilePath archive
]
when (ec /= ExitSuccess)
$ error $ "Problem while decompressing " ++ toFilePath archive
where
dir = configLocalPrograms config </> $(mkRelDir "7z")
exe = dir </> $(mkRelFile "7z.exe")
dll = dir </> $(mkRelFile "7z.dll")
chattyDownload :: (MonadReader env m, HasHttpManager env, MonadIO m, MonadLogger m, MonadThrow m, MonadBaseControl IO m)
=> Text -- ^ label
-> DownloadInfo -- ^ URL, content-length, and sha1
-> Path Abs File -- ^ destination
-> m ()
chattyDownload label downloadInfo path = do
let url = downloadInfoUrl downloadInfo
req <- parseUrl $ T.unpack url
$logSticky $ T.concat
[ "Preparing to download "
, label
, " ..."
]
$logDebug $ T.concat
[ "Downloading from "
, url
, " to "
, T.pack $ toFilePath path
, " ..."
]
hashChecks <- case downloadInfoSha1 downloadInfo of
Just sha1ByteString -> do
let sha1 = CheckHexDigestByteString sha1ByteString
$logDebug $ T.concat
[ "Will check against sha1 hash: "
, T.decodeUtf8With T.lenientDecode sha1ByteString
]
return [HashCheck SHA1 sha1]
Nothing -> do
$logWarn $ T.concat
[ "No sha1 found in metadata,"
, " download hash won't be checked."
]
return []
let dReq = DownloadRequest
{ drRequest = req
, drHashChecks = hashChecks
, drLengthCheck = Just totalSize
, drRetryPolicy = drRetryPolicyDefault
}
runInBase <- liftBaseWith $ \run -> return (void . run)
x <- verifiedDownload dReq path (chattyDownloadProgress runInBase)
if x
then $logStickyDone ("Downloaded " <> label <> ".")
else $logStickyDone "Already downloaded."
where
totalSize = downloadInfoContentLength downloadInfo
chattyDownloadProgress runInBase _ = do
_ <- liftIO $ runInBase $ $logSticky $
label <> ": download has begun"
CL.map (Sum . S.length)
=$ chunksOverTime 1
=$ go
where
go = evalStateC 0 $ awaitForever $ \(Sum size) -> do
modify (+ size)
totalSoFar <- get
liftIO $ runInBase $ $logSticky $ T.pack $
chattyProgressWithTotal totalSoFar totalSize
-- Note(DanBurton): Total size is now always known in this file.
-- However, printing in the case where it isn't known may still be
-- useful in other parts of the codebase.
-- So I'm just commenting out the code rather than deleting it.
-- case mcontentLength of
-- Nothing -> chattyProgressNoTotal totalSoFar
-- Just 0 -> chattyProgressNoTotal totalSoFar
-- Just total -> chattyProgressWithTotal totalSoFar total
---- Example: ghc: 42.13 KiB downloaded...
--chattyProgressNoTotal totalSoFar =
-- printf ("%s: " <> bytesfmt "%7.2f" totalSoFar <> " downloaded...")
-- (T.unpack label)
-- Example: ghc: 50.00 MiB / 100.00 MiB (50.00%) downloaded...
chattyProgressWithTotal totalSoFar total =
printf ("%s: " <>
bytesfmt "%7.2f" totalSoFar <> " / " <>
bytesfmt "%.2f" total <>
" (%6.2f%%) downloaded...")
(T.unpack label)
percentage
where percentage :: Double
percentage = (fromIntegral totalSoFar / fromIntegral total * 100)
-- | Given a printf format string for the decimal part and a number of
-- bytes, formats the bytes using an appropiate unit and returns the
-- formatted string.
--
-- >>> bytesfmt "%.2" 512368
-- "500.359375 KiB"
bytesfmt :: Integral a => String -> a -> String
bytesfmt formatter bs = printf (formatter <> " %s")
(fromIntegral (signum bs) * dec :: Double)
(bytesSuffixes !! i)
where
(dec,i) = getSuffix (abs bs)
getSuffix n = until p (\(x,y) -> (x / 1024, y+1)) (fromIntegral n,0)
where p (n',numDivs) = n' < 1024 || numDivs == (length bytesSuffixes - 1)
bytesSuffixes :: [String]
bytesSuffixes = ["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"]
-- Await eagerly (collect with monoidal append),
-- but space out yields by at least the given amount of time.
-- The final yield may come sooner, and may be a superfluous mempty.
-- Note that Integer and Float literals can be turned into NominalDiffTime
-- (these literals are interpreted as "seconds")
chunksOverTime :: (Monoid a, MonadIO m) => NominalDiffTime -> Conduit a m a
chunksOverTime diff = do
currentTime <- liftIO getCurrentTime
evalStateC (currentTime, mempty) go
where
-- State is a tuple of:
-- * the last time a yield happened (or the beginning of the sink)
-- * the accumulated awaits since the last yield
go = await >>= \case
Nothing -> do
(_, acc) <- get
yield acc
Just a -> do
(lastTime, acc) <- get
let acc' = acc <> a
currentTime <- liftIO getCurrentTime
if diff < diffUTCTime currentTime lastTime
then put (currentTime, mempty) >> yield acc'
else put (lastTime, acc')
go
-- | Perform a basic sanity check of GHC
sanityCheck :: (MonadIO m, MonadMask m, MonadLogger m, MonadBaseControl IO m)
=> EnvOverride
-> m ()
sanityCheck menv = withSystemTempDirectory "stack-sanity-check" $ \dir -> do
dir' <- parseAbsDir dir
let fp = toFilePath $ dir' </> $(mkRelFile "Main.hs")
liftIO $ writeFile fp $ unlines
[ "import Distribution.Simple" -- ensure Cabal library is present
, "main = putStrLn \"Hello World\""
]
ghc <- join $ findExecutable menv "ghc"
$logDebug $ "Performing a sanity check on: " <> T.pack (toFilePath ghc)
eres <- tryProcessStdout (Just dir') menv "ghc"
[ fp
, "-no-user-package-db"
]
case eres of
Left e -> throwM $ GHCSanityCheckCompileFailed e ghc
Right _ -> return () -- TODO check that the output of running the command is correct
toFilePathNoTrailingSlash :: Path loc Dir -> FilePath
toFilePathNoTrailingSlash = FP.dropTrailingPathSeparator . toFilePath
-- Remove potentially confusing environment variables
removeHaskellEnvVars :: Map Text Text -> Map Text Text
removeHaskellEnvVars =
Map.delete "GHCJS_PACKAGE_PATH" .
Map.delete "GHC_PACKAGE_PATH" .
Map.delete "HASKELL_PACKAGE_SANDBOX" .
Map.delete "HASKELL_PACKAGE_SANDBOXES" .
Map.delete "HASKELL_DIST_DIR"
-- | Get map of environment variables to set to change the locale's encoding to UTF-8
getUtf8LocaleVars
:: forall m env.
(MonadReader env m, HasPlatform env, MonadLogger m, MonadCatch m, MonadBaseControl IO m, MonadIO m)
=> EnvOverride -> m (Map Text Text)
getUtf8LocaleVars menv = do
Platform _ os <- asks getPlatform
if isWindows os
then
-- On Windows, locale is controlled by the code page, so we don't set any environment
-- variables.
return
Map.empty
else do
let checkedVars = map checkVar (Map.toList $ eoTextMap menv)
-- List of environment variables that will need to be updated to set UTF-8 (because
-- they currently do not specify UTF-8).
needChangeVars = concatMap fst checkedVars
-- Set of locale-related environment variables that have already have a value.
existingVarNames = Set.unions (map snd checkedVars)
-- True if a locale is already specified by one of the "global" locale variables.
hasAnyExisting =
or $
map
(`Set.member` existingVarNames)
["LANG", "LANGUAGE", "LC_ALL"]
if null needChangeVars && hasAnyExisting
then
-- If no variables need changes and at least one "global" variable is set, no
-- changes to environment need to be made.
return
Map.empty
else do
-- Get a list of known locales by running @locale -a@.
elocales <- tryProcessStdout Nothing menv "locale" ["-a"]
let
-- Filter the list to only include locales with UTF-8 encoding.
utf8Locales =
case elocales of
Left _ -> []
Right locales ->
filter
isUtf8Locale
(T.lines $
T.decodeUtf8With
T.lenientDecode
locales)
mfallback = getFallbackLocale utf8Locales
when
(isNothing mfallback)
($logWarn
"Warning: unable to set locale to UTF-8 encoding; GHC may fail with 'invalid character'")
let
-- Get the new values of variables to adjust.
changes =
Map.unions $
map
(adjustedVarValue utf8Locales mfallback)
needChangeVars
-- Get the values of variables to add.
adds
| hasAnyExisting =
-- If we already have a "global" variable, then nothing needs
-- to be added.
Map.empty
| otherwise =
-- If we don't already have a "global" variable, then set LANG to the
-- fallback.
case mfallback of
Nothing -> Map.empty
Just fallback ->
Map.singleton "LANG" fallback
return (Map.union changes adds)
where
-- Determines whether an environment variable is locale-related and, if so, whether it needs to
-- be adjusted.
checkVar
:: (Text, Text) -> ([Text], Set Text)
checkVar (k,v) =
if k `elem` ["LANG", "LANGUAGE"] || "LC_" `T.isPrefixOf` k
then if isUtf8Locale v
then ([], Set.singleton k)
else ([k], Set.singleton k)
else ([], Set.empty)
-- Adjusted value of an existing locale variable. Looks for valid UTF-8 encodings with
-- same language /and/ territory, then with same language, and finally the first UTF-8 locale
-- returned by @locale -a@.
adjustedVarValue
:: [Text] -> Maybe Text -> Text -> Map Text Text
adjustedVarValue utf8Locales mfallback k =
case Map.lookup k (eoTextMap menv) of
Nothing -> Map.empty
Just v ->
case concatMap
(matchingLocales utf8Locales)
[ T.takeWhile (/= '.') v <> "."
, T.takeWhile (/= '_') v <> "_"] of
(v':_) -> Map.singleton k v'
[] ->
case mfallback of
Just fallback -> Map.singleton k fallback
Nothing -> Map.empty
-- Determine the fallback locale, by looking for any UTF-8 locale prefixed with the list in
-- @fallbackPrefixes@, and if not found, picking the first UTF-8 encoding returned by @locale
-- -a@.
getFallbackLocale
:: [Text] -> Maybe Text
getFallbackLocale utf8Locales = do
case concatMap (matchingLocales utf8Locales) fallbackPrefixes of
(v:_) -> Just v
[] ->
case utf8Locales of
[] -> Nothing
(v:_) -> Just v
-- Filter the list of locales for any with the given prefixes (case-insitive).
matchingLocales
:: [Text] -> Text -> [Text]
matchingLocales utf8Locales prefix =
filter
(\v ->
(T.toLower prefix) `T.isPrefixOf` T.toLower v)
utf8Locales
-- Does the locale have one of the encodings in @utf8Suffixes@ (case-insensitive)?
isUtf8Locale locale =
or $
map
(\v ->
T.toLower v `T.isSuffixOf` T.toLower locale)
utf8Suffixes
-- Prefixes of fallback locales (case-insensitive)
fallbackPrefixes = ["C.", "en_US.", "en_"]
-- Suffixes of UTF-8 locales (case-insensitive)
utf8Suffixes = [".UTF-8", ".utf8"]
| tedkornish/stack | src/Stack/Setup.hs | bsd-3-clause | 51,741 | 0 | 31 | 17,485 | 11,878 | 5,935 | 5,943 | 1,015 | 15 |
-- Test purpose:
-- Ensure that -Wno-compat disables a previously set -Wcompat
{-# OPTIONS_GHC -Wcompat #-}
{-# OPTIONS_GHC -Wno-compat #-}
module WCompatWarningsOnOff where
import qualified Data.Semigroup as Semi
monadFail :: Monad m => m a
monadFail = do
Just _ <- undefined
undefined
(<>) = undefined -- Semigroup warnings
-- -fwarn-noncanonical-monoid-instances
newtype S = S Int
instance Semi.Semigroup S where
(<>) = mappend
instance Monoid S where
S a `mappend` S b = S (a+b)
mempty = S 0
| ezyang/ghc | testsuite/tests/wcompat-warnings/WCompatWarningsOnOff.hs | bsd-3-clause | 518 | 0 | 8 | 101 | 128 | 72 | 56 | 15 | 1 |
{-# LANGUAGE PatternGuards #-}
module Idris.CaseSplit(splitOnLine, replaceSplits,
getClause, getProofClause,
mkWith,
nameMissing,
getUniq, nameRoot) where
-- splitting a variable in a pattern clause
import Idris.AbsSyntax
import Idris.AbsSyntaxTree (Idris, IState, PTerm)
import Idris.ElabDecls
import Idris.Delaborate
import Idris.Parser
import Idris.Error
import Idris.Output
import Idris.Elab.Value
import Idris.Elab.Term
import Idris.Core.TT
import Idris.Core.Typecheck
import Idris.Core.Evaluate
import Data.Maybe
import Data.Char
import Data.List (isPrefixOf, isSuffixOf)
import Control.Monad
import Control.Monad.State.Strict
import Text.Parser.Combinators
import Text.Parser.Char(anyChar)
import Text.Trifecta(Result(..), parseString)
import Text.Trifecta.Delta
import Debug.Trace
{-
Given a pattern clause and a variable 'n', elaborate the clause and find the
type of 'n'.
Make new pattern clauses by replacing 'n' with all the possibly constructors
applied to '_', and replacing all other variables with '_' in order to
resolve other dependencies.
Finally, merge the generated patterns with the original, by matching.
Always take the "more specific" argument when there is a discrepancy, i.e.
names over '_', patterns over names, etc.
-}
-- Given a variable to split, and a term application, return a list of
-- variable updates, paired with a flag to say whether the given update
-- typechecks (False = impossible)
-- if the flag is 'False' the splits should be output with the 'impossible'
-- flag, otherwise they should be output as normal
split :: Name -> PTerm -> Idris (Bool, [[(Name, PTerm)]])
split n t'
= do ist <- getIState
-- Make sure all the names in the term are accessible
mapM_ (\n -> setAccessibility n Public) (allNamesIn t')
-- ETyDecl rather then ELHS because there'll be explicit type
-- matching
(tm, ty, pats) <- elabValBind recinfo ETyDecl True (addImplPat ist t')
-- ASSUMPTION: tm is in normal form after elabValBind, so we don't
-- need to do anything special to find out what family each argument
-- is in
logLvl 4 ("Elaborated:\n" ++ show tm ++ " : " ++ show ty ++ "\n" ++ show pats)
-- iputStrLn (show (delab ist tm) ++ " : " ++ show (delab ist ty))
-- iputStrLn (show pats)
let t = mergeUserImpl (addImplPat ist t') (delab ist tm)
let ctxt = tt_ctxt ist
case lookup n pats of
Nothing -> ifail $ show n ++ " is not a pattern variable"
Just ty ->
do let splits = findPats ist ty
logLvl 1 ("New patterns " ++ showSep ", "
(map showTmImpls splits))
let newPats_in = zipWith (replaceVar ctxt n) splits (repeat t)
logLvl 4 ("Working from " ++ show t)
logLvl 4 ("Trying " ++ showSep "\n"
(map (showTmImpls) newPats_in))
newPats_in <- mapM elabNewPat newPats_in
case anyValid [] [] newPats_in of
Left fails -> do
let fails' = mergeAllPats ist n t fails
return (False, (map snd fails'))
Right newPats -> do
logLvl 3 ("Original:\n" ++ show t)
logLvl 3 ("Split:\n" ++
(showSep "\n" (map show newPats)))
logLvl 3 "----"
let newPats' = mergeAllPats ist n t newPats
logLvl 1 ("Name updates " ++ showSep "\n"
(map (\ (p, u) -> show u ++ " " ++ show p) newPats'))
return (True, (map snd newPats'))
where
anyValid ok bad [] = if null ok then Left (reverse bad)
else Right (reverse ok)
anyValid ok bad ((tc, p) : ps)
| tc = anyValid (p : ok) bad ps
| otherwise = anyValid ok (p : bad) ps
data MergeState = MS { namemap :: [(Name, Name)],
invented :: [(Name, Name)],
explicit :: [Name],
updates :: [(Name, PTerm)] }
addUpdate :: Name -> Idris.AbsSyntaxTree.PTerm -> State MergeState ()
addUpdate n tm = do ms <- get
put (ms { updates = ((n, stripNS tm) : updates ms) } )
inventName :: Idris.AbsSyntaxTree.IState -> Maybe Name -> Name -> State MergeState Name
inventName ist ty n =
do ms <- get
let supp = case ty of
Nothing -> []
Just t -> getNameHints ist t
let nsupp = case n of
MN i n | not (tnull n) && thead n == '_'
-> mkSupply (supp ++ varlist)
MN i n -> mkSupply (UN n : supp ++ varlist)
UN n | thead n == '_'
-> mkSupply (supp ++ varlist)
x -> mkSupply (x : supp)
let badnames = map snd (namemap ms) ++ map snd (invented ms) ++
explicit ms
case lookup n (invented ms) of
Just n' -> return n'
Nothing ->
do let n' = uniqueNameFrom nsupp badnames
put (ms { invented = (n, n') : invented ms })
return n'
mkSupply :: [Name] -> [Name]
mkSupply ns = mkSupply' ns (map nextName ns)
where mkSupply' xs ns' = xs ++ mkSupply ns'
varlist :: [Name]
varlist = map (sUN . (:[])) "xyzwstuv" -- EB's personal preference :)
stripNS :: Idris.AbsSyntaxTree.PTerm -> Idris.AbsSyntaxTree.PTerm
stripNS tm = mapPT dens tm where
dens (PRef fc hls n) = PRef fc hls (nsroot n)
dens t = t
mergeAllPats :: IState -> Name -> PTerm -> [PTerm] -> [(PTerm, [(Name, PTerm)])]
mergeAllPats ist cv t [] = []
mergeAllPats ist cv t (p : ps)
= let (p', MS _ _ _ u) = runState (mergePat ist t p Nothing)
(MS [] [] (filter (/=cv) (patvars t)) [])
ps' = mergeAllPats ist cv t ps in
((p', u) : ps')
where patvars (PRef _ _ n) = [n]
patvars (PApp _ _ as) = concatMap (patvars . getTm) as
patvars (PPatvar _ n) = [n]
patvars _ = []
mergePat :: IState -> PTerm -> PTerm -> Maybe Name -> State MergeState PTerm
-- If any names are unified, make sure they stay unified. Always prefer
-- user provided name (first pattern)
mergePat ist (PPatvar fc n) new t
= mergePat ist (PRef fc [] n) new t
mergePat ist old (PPatvar fc n) t
= mergePat ist old (PRef fc [] n) t
mergePat ist orig@(PRef fc _ n) new@(PRef _ _ n') t
| isDConName n' (tt_ctxt ist) = do addUpdate n new
return new
| otherwise
= do ms <- get
case lookup n' (namemap ms) of
Just x -> do addUpdate n (PRef fc [] x)
return (PRef fc [] x)
Nothing -> do put (ms { namemap = ((n', n) : namemap ms) })
return (PRef fc [] n)
mergePat ist (PApp _ _ args) (PApp fc f args') t
= do newArgs <- zipWithM mergeArg args (zip args' (argTys ist f))
return (PApp fc f newArgs)
where mergeArg x (y, t)
= do tm' <- mergePat ist (getTm x) (getTm y) t
case x of
(PImp _ _ _ _ _) ->
return (y { machine_inf = machine_inf x,
getTm = tm' })
_ -> return (y { getTm = tm' })
mergePat ist (PRef fc _ n) tm ty = do tm <- tidy ist tm ty
addUpdate n tm
return tm
mergePat ist x y t = return y
mergeUserImpl :: PTerm -> PTerm -> PTerm
mergeUserImpl x y = x
argTys :: IState -> PTerm -> [Maybe Name]
argTys ist (PRef fc hls n)
= case lookupTy n (tt_ctxt ist) of
[ty] -> map (tyName . snd) (getArgTys ty) ++ repeat Nothing
_ -> repeat Nothing
where tyName (Bind _ (Pi _ _ _) _) = Just (sUN "->")
tyName t | (P _ n _, _) <- unApply t = Just n
| otherwise = Nothing
argTys _ _ = repeat Nothing
tidy :: IState -> PTerm -> Maybe Name -> State MergeState PTerm
tidy ist orig@(PRef fc hls n) ty
= do ms <- get
case lookup n (namemap ms) of
Just x -> return (PRef fc [] x)
Nothing -> case n of
(UN _) -> return orig
_ -> do n' <- inventName ist ty n
return (PRef fc [] n')
tidy ist (PApp fc f args) ty
= do args' <- zipWithM tidyArg args (argTys ist f)
return (PApp fc f args')
where tidyArg x ty' = do tm' <- tidy ist (getTm x) ty'
return (x { getTm = tm' })
tidy ist tm ty = return tm
-- mapPT tidyVar tm
-- where tidyVar (PRef _ _) = Placeholder
-- tidyVar t = t
elabNewPat :: PTerm -> Idris (Bool, PTerm)
elabNewPat t = idrisCatch (do (tm, ty) <- elabVal recinfo ELHS t
i <- getIState
return (True, delab i tm))
(\e -> do i <- getIState
logLvl 5 $ "Not a valid split:\n" ++ pshow i e
return (False, t))
findPats :: IState -> Type -> [PTerm]
findPats ist t | (P _ n _, _) <- unApply t
= case lookupCtxt n (idris_datatypes ist) of
[ti] -> map genPat (con_names ti)
_ -> [Placeholder]
where genPat n = case lookupCtxt n (idris_implicits ist) of
[args] -> PApp emptyFC (PRef emptyFC [] n)
(map toPlaceholder args)
_ -> error $ "Can't happen (genPat) " ++ show n
toPlaceholder tm = tm { getTm = Placeholder }
findPats ist t = [Placeholder]
replaceVar :: Context -> Name -> PTerm -> PTerm -> PTerm
replaceVar ctxt n t (PApp fc f pats) = PApp fc f (map substArg pats)
where subst :: PTerm -> PTerm
subst orig@(PPatvar _ v) | v == n = t
| otherwise = Placeholder
subst orig@(PRef _ _ v) | v == n = t
| isDConName v ctxt = orig
subst (PRef _ _ _) = Placeholder
subst (PApp fc (PRef _ _ t) pats)
| isTConName t ctxt = Placeholder -- infer types
subst (PApp fc f pats) = PApp fc f (map substArg pats)
subst x = x
substArg arg = arg { getTm = subst (getTm arg) }
replaceVar ctxt n t pat = pat
splitOnLine :: Int -- ^ line number
-> Name -- ^ variable
-> FilePath -- ^ name of file
-> Idris (Bool, [[(Name, PTerm)]])
splitOnLine l n fn = do
cl <- getInternalApp fn l
logLvl 3 ("Working with " ++ showTmImpls cl)
tms <- split n cl
return tms
replaceSplits :: String -> [[(Name, PTerm)]] -> Bool -> Idris [String]
replaceSplits l ups impossible
= updateRHSs 1 (map (rep (expandBraces l)) ups)
where
rep str [] = str ++ "\n"
rep str ((n, tm) : ups) = rep (updatePat False (show n) (nshow tm) str) ups
updateRHSs i [] = return []
updateRHSs i (x : xs)
| impossible = do xs' <- updateRHSs i xs
return (setImpossible False x : xs')
| otherwise = do (x', i') <- updateRHS (null xs) i x
xs' <- updateRHSs i' xs
return (x' : xs')
updateRHS last i ('?':'=':xs) = do (xs', i') <- updateRHS last i xs
return ("?=" ++ xs', i')
updateRHS last i ('?':xs)
= do let (nm, rest_in) = span (not . (\x -> isSpace x || x == ')'
|| x == '(')) xs
let rest = if last then rest_in else
case span (not . (=='\n')) rest_in of
(_, restnl) -> restnl
(nm', i') <- getUniq nm i
return ('?':nm' ++ rest, i')
updateRHS last i (x : xs) = do (xs', i') <- updateRHS last i xs
return (x : xs', i')
updateRHS last i [] = return ("", i)
setImpossible brace ('}':xs) = '}' : setImpossible False xs
setImpossible brace ('{':xs) = '{' : setImpossible True xs
setImpossible False ('=':xs) = "impossible\n"
setImpossible brace (x : xs) = x : setImpossible brace xs
setImpossible brace [] = ""
-- TMP HACK: If there are Nats, we don't want to show as numerals since
-- this isn't supported in a pattern, so special case here
nshow (PRef _ _ (UN z)) | z == txt "Z" = "Z"
nshow (PApp _ (PRef _ _ (UN s)) [x]) | s == txt "S" =
"(S " ++ addBrackets (nshow (getTm x)) ++ ")"
nshow t = show t
-- if there's any {n} replace with {n=n}
-- but don't replace it in comments
expandBraces ('{' : '-' : xs) = '{' : '-' : xs
expandBraces ('{' : xs)
= let (brace, (_:rest)) = span (/= '}') xs in
if (not ('=' `elem` brace))
then ('{' : brace ++ " = " ++ brace ++ "}") ++
expandBraces rest
else ('{' : brace ++ "}") ++ expandBraces rest
expandBraces (x : xs) = x : expandBraces xs
expandBraces [] = []
updatePat start n tm [] = []
updatePat start n tm ('{':rest) =
let (space, rest') = span isSpace rest in
'{' : space ++ updatePat False n tm rest'
updatePat start n tm done@('?':rest) = done
updatePat True n tm xs@(c:rest) | length xs > length n
= let (before, after@(next:_)) = splitAt (length n) xs in
if (before == n && not (isAlphaNum next))
then addBrackets tm ++ updatePat False n tm after
else c : updatePat (not (isAlphaNum c)) n tm rest
updatePat start n tm (c:rest) = c : updatePat (not ((isAlphaNum c) || c == '_')) n tm rest
addBrackets tm | ' ' `elem` tm
, not (isPrefixOf "(" tm)
, not (isSuffixOf ")" tm) = "(" ++ tm ++ ")"
| otherwise = tm
getUniq :: (Show t, Num t) => [Char] -> t -> Idris ([Char], t)
getUniq nm i
= do ist <- getIState
let n = nameRoot [] nm ++ "_" ++ show i
case lookupTy (sUN n) (tt_ctxt ist) of
[] -> return (n, i+1)
_ -> getUniq nm (i+1)
nameRoot acc nm | all isDigit nm = showSep "_" acc
nameRoot acc nm =
case span (/='_') nm of
(before, ('_' : after)) -> nameRoot (acc ++ [before]) after
_ -> showSep "_" (acc ++ [nm])
getClause :: Int -- ^ line number that the type is declared on
-> Name -- ^ Function name
-> Name -- ^ User given name
-> FilePath -- ^ Source file name
-> Idris String
getClause l fn un fp
= do i <- getIState
case lookupCtxt fn (idris_classes i) of
[c] -> return (mkClassBodies i (class_methods c))
_ -> do ty_in <- getInternalApp fp l
let ty = case ty_in of
PTyped n t -> t
x -> x
ist <- get
let ap = mkApp ist ty []
return (show un ++ " " ++ ap ++ "= ?"
++ show un ++ "_rhs")
where mkApp :: IState -> PTerm -> [Name] -> String
mkApp i (PPi (Exp _ _ False) (MN _ _) _ ty sc) used
= let n = getNameFrom i used ty in
show n ++ " " ++ mkApp i sc (n : used)
mkApp i (PPi (Exp _ _ False) (UN n) _ ty sc) used
| thead n == '_'
= let n = getNameFrom i used ty in
show n ++ " " ++ mkApp i sc (n : used)
mkApp i (PPi (Exp _ _ False) n _ _ sc) used
= show n ++ " " ++ mkApp i sc (n : used)
mkApp i (PPi _ _ _ _ sc) used = mkApp i sc used
mkApp i _ _ = ""
getNameFrom i used (PPi _ _ _ _ _)
= uniqueNameFrom (mkSupply [sUN "f", sUN "g"]) used
getNameFrom i used (PApp fc f as) = getNameFrom i used f
getNameFrom i used (PRef fc _ f)
= case getNameHints i f of
[] -> uniqueNameFrom (mkSupply [sUN "x", sUN "y",
sUN "z"]) used
ns -> uniqueNameFrom (mkSupply ns) used
getNameFrom i used _ = uniqueNameFrom (mkSupply [sUN "x", sUN "y",
sUN "z"]) used
-- write method declarations, indent with 4 spaces
mkClassBodies :: IState -> [(Name, (FnOpts, PTerm))] -> String
mkClassBodies i ns
= showSep "\n"
(zipWith (\(n, (_, ty)) m -> " " ++
def (show (nsroot n)) ++ " "
++ mkApp i ty []
++ "= ?"
++ show un ++ "_rhs_" ++ show m) ns [1..])
def n@(x:xs) | not (isAlphaNum x) = "(" ++ n ++ ")"
def n = n
getProofClause :: Int -- ^ line number that the type is declared
-> Name -- ^ Function name
-> FilePath -- ^ Source file name
-> Idris String
getProofClause l fn fp
= do ty_in <- getInternalApp fp l
let ty = case ty_in of
PTyped n t -> t
x -> x
return (mkApp ty ++ " = ?" ++ show fn ++ "_rhs")
where mkApp (PPi _ _ _ _ sc) = mkApp sc
mkApp rt = "(" ++ show rt ++ ") <== " ++ show fn
-- Purely syntactic - turn a pattern match clause into a with and a new
-- match clause
mkWith :: String -> Name -> String
mkWith str n = let str' = replaceRHS str "with (_)"
in str' ++ "\n" ++ newpat str
where replaceRHS [] str = str
replaceRHS ('?':'=': rest) str = str
replaceRHS ('=': rest) str
| not ('=' `elem` rest) = str
replaceRHS (x : rest) str = x : replaceRHS rest str
newpat ('>':patstr) = '>':newpat patstr
newpat patstr =
" " ++
replaceRHS patstr "| with_pat = ?" ++ show n ++ "_rhs"
-- Replace _ with names in missing clauses
nameMissing :: [PTerm] -> Idris [PTerm]
nameMissing ps = do ist <- get
newPats <- mapM nm ps
let newPats' = mergeAllPats ist (sUN "_") (base (head ps))
newPats
return (map fst newPats')
where
base (PApp fc f args) = PApp fc f (map (fmap (const (PRef fc [] (sUN "_")))) args)
base t = t
nm ptm = do mptm <- elabNewPat ptm
case mptm of
(False, _) -> return ptm
(True, ptm') -> return ptm'
| adnelson/Idris-dev | src/Idris/CaseSplit.hs | bsd-3-clause | 19,205 | 0 | 27 | 7,604 | 6,726 | 3,358 | 3,368 | 364 | 22 |
import Test.HUnit (Assertion, (@=?), runTestTT, Test(..), Counts(..))
import System.Exit (ExitCode(..), exitWith)
import Bob (responseFor)
exitProperly :: IO Counts -> IO ()
exitProperly m = do
counts <- m
exitWith $ if failures counts /= 0 || errors counts /= 0 then ExitFailure 1 else ExitSuccess
testCase :: String -> Assertion -> Test
testCase label assertion = TestLabel label (TestCase assertion)
test_respondsToSomething :: Assertion
test_respondsToSomething =
"Whatever." @=? responseFor "Tom-ay-to, tom-aaaah-to."
test_respondsToShouts :: Assertion
test_respondsToShouts =
"Whoa, chill out!" @=? responseFor "WATCH OUT!"
test_respondsToQuestions :: Assertion
test_respondsToQuestions =
"Sure." @=? responseFor "Does this cryogenic chamber make me look fat?"
test_respondsToForcefulTalking :: Assertion
test_respondsToForcefulTalking =
"Whatever." @=? responseFor "Let's go make out behind the gym!"
test_respondsToAcronyms :: Assertion
test_respondsToAcronyms =
"Whatever." @=? responseFor "It's OK if you don't want to go to the DMV."
test_respondsToForcefulQuestions :: Assertion
test_respondsToForcefulQuestions =
"Whoa, chill out!" @=? responseFor "WHAT THE HELL WERE YOU THINKING?"
test_respondsToShoutingWithSpecialCharacters :: Assertion
test_respondsToShoutingWithSpecialCharacters =
"Whoa, chill out!" @=? responseFor (
"ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!")
test_respondsToShoutingNumbers :: Assertion
test_respondsToShoutingNumbers =
"Whoa, chill out!" @=? responseFor "1, 2, 3 GO!"
test_respondsToShoutingWithNoExclamationMark :: Assertion
test_respondsToShoutingWithNoExclamationMark =
"Whoa, chill out!" @=? responseFor "I HATE YOU"
test_respondsToStatementContainingQuestionMark :: Assertion
test_respondsToStatementContainingQuestionMark =
"Whatever." @=? responseFor "Ending with ? means a question."
test_respondsToSilence :: Assertion
test_respondsToSilence =
"Fine. Be that way!" @=? responseFor ""
test_respondsToProlongedSilence :: Assertion
test_respondsToProlongedSilence =
"Fine. Be that way!" @=? responseFor " "
test_respondsToNonLettersWithQuestion :: Assertion
test_respondsToNonLettersWithQuestion =
"Sure." @=? responseFor ":) ?"
test_respondsToMultipleLineQuestions :: Assertion
test_respondsToMultipleLineQuestions =
"Whatever." @=? responseFor "\nDoes this cryogenic chamber make me look fat? \nno"
test_respondsToOtherWhitespace :: Assertion
test_respondsToOtherWhitespace =
"Fine. Be that way!" @=? responseFor "\n\r \t\v\xA0\x2002" -- \xA0 No-break space, \x2002 En space
test_respondsToOnlyNumbers :: Assertion
test_respondsToOnlyNumbers =
"Whatever." @=? responseFor "1, 2, 3"
test_respondsToQuestionWithOnlyNumbers :: Assertion
test_respondsToQuestionWithOnlyNumbers =
"Sure." @=? responseFor "4?"
test_respondsToUnicodeShout :: Assertion
test_respondsToUnicodeShout =
"Whoa, chill out!" @=? responseFor "\xdcML\xc4\xdcTS!"
test_respondsToUnicodeNonShout :: Assertion
test_respondsToUnicodeNonShout =
"Whatever." @=? responseFor "\xdcML\xe4\xdcTS!"
respondsToTests :: [Test]
respondsToTests =
[ testCase "something" test_respondsToSomething
, testCase "shouts" test_respondsToShouts
, testCase "questions" test_respondsToQuestions
, testCase "forceful talking" test_respondsToForcefulTalking
, testCase "acronyms" test_respondsToAcronyms
, testCase "forceful questions" test_respondsToForcefulQuestions
, testCase "shouting with special characters"
test_respondsToShoutingWithSpecialCharacters
, testCase "shouting numbers" test_respondsToShoutingNumbers
, testCase "shouting with no exclamation mark"
test_respondsToShoutingWithNoExclamationMark
, testCase "statement containing question mark"
test_respondsToStatementContainingQuestionMark
, testCase "silence" test_respondsToSilence
, testCase "prolonged silence" test_respondsToProlongedSilence
, testCase "questioned nonsense" test_respondsToNonLettersWithQuestion
, testCase "multiple-line statement containing question mark"
test_respondsToMultipleLineQuestions
, testCase "all whitespace is silence" test_respondsToOtherWhitespace
, testCase "only numbers" test_respondsToOnlyNumbers
, testCase "question with only numbers" test_respondsToQuestionWithOnlyNumbers
, testCase "unicode shout" test_respondsToUnicodeShout
, testCase "unicode non-shout" test_respondsToUnicodeNonShout
]
main :: IO ()
main = exitProperly (runTestTT (TestList respondsToTests))
| Sgoettschkes/learning | haskell/exercism/bob/bob_test.hs | mit | 4,500 | 0 | 12 | 566 | 682 | 360 | 322 | 94 | 2 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ro-RO">
<title>Form Handler | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | thc202/zap-extensions | addOns/formhandler/src/main/javahelp/org/zaproxy/zap/extension/formhandler/resources/help_ro_RO/helpset_ro_RO.hs | apache-2.0 | 973 | 78 | 66 | 159 | 413 | 209 | 204 | -1 | -1 |
module WhereIn1 where
f = (case (x,z) of
(1,2) -> "First Branch"
_ -> "Second Branch")
where
(x,z) = (1,2) | SAdams601/HaRe | old/testing/simplifyExpr/WhereIn1.hs | bsd-3-clause | 139 | 0 | 9 | 52 | 60 | 36 | 24 | 5 | 2 |
module Util.Pretty (
module Text.PrettyPrint.Annotated.Leijen,
Sized(..), nestingSize,
Pretty(..)
) where
--import Text.PrettyPrint.HughesPJ
import Text.PrettyPrint.Annotated.Leijen
-- A rough notion of size for pretty printing various types.
class Sized a where
size :: a -> Int
instance (Sized a, Sized b) => Sized (a, b) where
size (left, right) = 1 + size left + size right
instance Sized a => Sized [a] where
size = sum . map size
nestingSize :: Int
nestingSize = 1
class Pretty a ty where
pretty :: a -> Doc ty
| mrmonday/Idris-dev | src/Util/Pretty.hs | bsd-3-clause | 539 | 0 | 8 | 107 | 180 | 101 | 79 | -1 | -1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP, MagicHash, UnboxedTuples, NoImplicitPrelude #-}
{-# OPTIONS_GHC -O2 #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Float.ConversionUtils
-- Copyright : (c) Daniel Fischer 2010
-- License : see libraries/base/LICENSE
--
-- Maintainer : cvs-ghc@haskell.org
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- Utilities for conversion between Double/Float and Rational
--
-----------------------------------------------------------------------------
#include "MachDeps.h"
module GHC.Float.ConversionUtils ( elimZerosInteger, elimZerosInt# ) where
import GHC.Base
import GHC.Integer
#if WORD_SIZE_IN_BITS < 64
import GHC.IntWord64
#endif
default ()
#if WORD_SIZE_IN_BITS < 64
#define TO64 integerToInt64
toByte64# :: Int64# -> Int#
toByte64# i = word2Int# (and# 255## (int2Word# (int64ToInt# i)))
-- Double mantissae have 53 bits, too much for Int#
elim64# :: Int64# -> Int# -> (# Integer, Int# #)
elim64# n e =
case zeroCount (toByte64# n) of
t | isTrue# (e <=# t) -> (# int64ToInteger (uncheckedIShiftRA64# n e), 0# #)
| isTrue# (t <# 8#) -> (# int64ToInteger (uncheckedIShiftRA64# n t), e -# t #)
| otherwise -> elim64# (uncheckedIShiftRA64# n 8#) (e -# 8#)
#else
#define TO64 integerToInt
-- Double mantissae fit it Int#
elim64# :: Int# -> Int# -> (# Integer, Int# #)
elim64# = elimZerosInt#
#endif
{-# INLINE elimZerosInteger #-}
elimZerosInteger :: Integer -> Int# -> (# Integer, Int# #)
elimZerosInteger m e = elim64# (TO64 m) e
elimZerosInt# :: Int# -> Int# -> (# Integer, Int# #)
elimZerosInt# n e =
case zeroCount (toByte# n) of
t | isTrue# (e <=# t) -> (# smallInteger (uncheckedIShiftRA# n e), 0# #)
| isTrue# (t <# 8#) -> (# smallInteger (uncheckedIShiftRA# n t), e -# t #)
| otherwise -> elimZerosInt# (uncheckedIShiftRA# n 8#) (e -# 8#)
{-# INLINE zeroCount #-}
zeroCount :: Int# -> Int#
zeroCount i =
case zeroCountArr of
BA ba -> indexInt8Array# ba i
toByte# :: Int# -> Int#
toByte# i = word2Int# (and# 255## (int2Word# i))
data BA = BA ByteArray#
-- Number of trailing zero bits in a byte
zeroCountArr :: BA
zeroCountArr =
let mkArr s =
case newByteArray# 256# s of
(# s1, mba #) ->
case writeInt8Array# mba 0# 8# s1 of
s2 ->
let fillA step val idx st
| isTrue# (idx <# 256#) =
case writeInt8Array# mba idx val st of
nx -> fillA step val (idx +# step) nx
| isTrue# (step <# 256#) =
fillA (2# *# step) (val +# 1#) step st
| otherwise = st
in case fillA 2# 0# 1# s2 of
s3 -> case unsafeFreezeByteArray# mba s3 of
(# _, ba #) -> ba
in case mkArr realWorld# of
b -> BA b
| tolysz/prepare-ghcjs | spec-lts8/base/GHC/Float/ConversionUtils.hs | bsd-3-clause | 3,119 | 0 | 25 | 913 | 753 | 388 | 365 | 53 | 1 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE TypeApplications #-}
-- | Lazy write-only state
module Control.Eff.Writer.Lazy ( Writer(..)
, withWriter
, tell
, censor
, runWriter
, runFirstWriter
, runLastWriter
, runListWriter
, runMonoidWriter
, execWriter
, execFirstWriter
, execLastWriter
, execListWriter
, execMonoidWriter
) where
import Control.Eff
import Control.Eff.Extend
import Control.Applicative ((<|>))
import Control.Monad.Base
import Control.Monad.Trans.Control
#if __GLASGOW_HASKELL__ < 804
import Data.Monoid
#endif
import Data.Function (fix)
-- ------------------------------------------------------------------------
-- | The Writer monad
--
-- In MTL's Writer monad, the told value must have a |Monoid| type. Our
-- writer has no such constraints. If we write a |Writer|-like
-- interpreter to accumulate the told values in a monoid, it will have
-- the |Monoid w| constraint then
data Writer w v where
Tell :: w -> Writer w ()
-- | How to interpret a pure value in a writer context, given the
-- value for mempty.
withWriter :: Monad m => a -> b -> (w -> b -> b) -> m (a, b)
withWriter x empty _append = return (x, empty)
-- | Given a value to write, and a callback (which includes empty and
-- append), respond to requests.
instance Monad m => Handle (Writer w) r a (b -> (w -> b -> b) -> m (a, b)) where
handle h q (Tell w) e append = h (q ^$ ()) e append >>=
\(x, l) -> return (x, w `append` l)
instance ( MonadBase m m
, LiftedBase m r
) => MonadBaseControl m (Eff (Writer w ': r)) where
type StM (Eff (Writer w ': r)) a = StM (Eff r) (a, [w])
liftBaseWith f = raise $ liftBaseWith $ \runInBase ->
f (runInBase . runListWriter)
restoreM x = do (a, ws :: [w]) <- raise (restoreM x)
mapM_ tell ws
return a
-- | Write a new value.
tell :: Member (Writer w) r => w -> Eff r ()
tell w = send $ Tell w
-- | Transform the state being produced.
censor :: forall w a r. Member (Writer w) r => (w -> w) -> Eff r a -> Eff r a
censor f = fix (respond_relay' hdl return)
where
hdl :: (Eff r b -> Eff r b) -> Arrs r v b -> Writer w v -> Eff r b
hdl h q (Tell w) = tell (f w) >>= \x -> h (q ^$ x)
-- | Handle Writer requests, using a user-provided function to accumulate
-- values, hence no Monoid constraints.
runWriter :: (w -> b -> b) -> b -> Eff (Writer w ': r) a -> Eff r (a, b)
runWriter accum b m = fix (handle_relay withWriter) m b accum
-- | Handle Writer requests, using a List to accumulate values.
runListWriter :: Eff (Writer w ': r) a -> Eff r (a,[w])
runListWriter = runWriter (:) []
-- | Handle Writer requests, using a Monoid instance to accumulate values.
runMonoidWriter :: (Monoid w) => Eff (Writer w ': r) a -> Eff r (a, w)
runMonoidWriter = runWriter (<>) mempty
-- | Handle Writer requests by taking the first value provided.
runFirstWriter :: Eff (Writer w ': r) a -> Eff r (a, Maybe w)
runFirstWriter = runWriter (\w b -> Just w <|> b) Nothing
-- | Handle Writer requests by overwriting previous values.
runLastWriter :: Eff (Writer w ': r) a -> Eff r (a, Maybe w)
runLastWriter = runWriter (\w b -> b <|> Just w) Nothing
-- | Handle Writer requests, using a user-provided function to accumulate
-- values and returning the final accumulated values.
execWriter :: (w -> b -> b) -> b -> Eff (Writer w ': r) a -> Eff r b
execWriter accum b = fmap snd . runWriter accum b
{-# INLINE execWriter #-}
-- | Handle Writer requests, using a List to accumulate values and returning
-- the final accumulated values.
execListWriter :: Eff (Writer w ': r) a -> Eff r [w]
execListWriter = fmap snd . runListWriter
{-# INLINE execListWriter #-}
-- | Handle Writer requests, using a Monoid instance to accumulate values and
-- returning the final accumulated values.
execMonoidWriter :: (Monoid w) => Eff (Writer w ': r) a -> Eff r w
execMonoidWriter = fmap snd . runMonoidWriter
{-# INLINE execMonoidWriter #-}
-- | Handle Writer requests by taking the first value provided and and returning
-- the final accumulated values.
execFirstWriter :: Eff (Writer w ': r) a -> Eff r (Maybe w)
execFirstWriter = fmap snd . runFirstWriter
{-# INLINE execFirstWriter #-}
-- | Handle Writer requests by overwriting previous values and returning
-- the final accumulated values.
execLastWriter :: Eff (Writer w ': r) a -> Eff r (Maybe w)
execLastWriter = fmap snd . runLastWriter
{-# INLINE execLastWriter #-}
| suhailshergill/extensible-effects | src/Control/Eff/Writer/Lazy.hs | mit | 5,172 | 0 | 11 | 1,409 | 1,359 | 731 | 628 | -1 | -1 |
module Main (main) where
import ODIS.Core ()
-- | Entry point of the application.
main :: IO ()
main = print "Hello :)"
| odis-project/odis-core | executable/Main.hs | mit | 132 | 0 | 6 | 35 | 36 | 21 | 15 | 4 | 1 |
{-# LANGUAGE JavaScriptFFI, GHCForeignImportPrim #-}
-----------------------------------------------------------------------------
-- |
-- Module : JsHs.Callback
-- Copyright : Artem Chirkin
-- License : MIT
--
-- Maintainer : Artem Chirkin
-- Stability : experimental
--
--
-----------------------------------------------------------------------------
module JsHs.Callback
( Callback
, OnBlocked(..)
, releaseCallback
-- * asynchronous callbacks
, asyncCallback
, asyncCallback1
, asyncCallback2
, asyncCallback3
-- * synchronous callbacks
, syncCallback
, syncCallback1
, syncCallback2
, syncCallback3
-- * synchronous callbacks that return a value
, syncCallback'
, syncCallback1'
, syncCallback2'
, syncCallback3'
-- * Really unsafe synchronous callbacks that could not be interrupted in any way
, syncCallbackUnsafe1
, syncCallbackUnsafe2
, syncCallbackUnsafe3
, syncCallbackUnsafeIO1
, syncCallbackUnsafeIO2
, syncCallbackUnsafeIO3
) where
import Unsafe.Coerce (unsafeCoerce)
import GHC.Exts (Any)
import GHCJS.Foreign.Callback
( Callback
, OnBlocked(..)
, releaseCallback
, asyncCallback
, asyncCallback1
, asyncCallback2
, asyncCallback3
, syncCallback
, syncCallback1
, syncCallback2
, syncCallback3
, syncCallback'
, syncCallback1'
, syncCallback2'
, syncCallback3'
)
import JsHs.Types (JSVal)
{-# INLINE syncCallbackUnsafe1 #-}
syncCallbackUnsafe1 :: (JSVal -> JSVal) -> IO (Callback f)
syncCallbackUnsafe1 x = js_syncCallbackApplyReturnUnsafe 1 (unsafeCoerce x)
{-# INLINE syncCallbackUnsafeIO1 #-}
syncCallbackUnsafeIO1 :: (JSVal -> IO JSVal) -> IO (Callback f)
syncCallbackUnsafeIO1 x = js_syncCallbackApplyReturnUnsafe 1 (unsafeCoerce x)
{-# INLINE syncCallbackUnsafe2 #-}
syncCallbackUnsafe2 :: (JSVal -> JSVal -> JSVal) -> IO (Callback f)
syncCallbackUnsafe2 x = js_syncCallbackApplyReturnUnsafe 2 (unsafeCoerce x)
{-# INLINE syncCallbackUnsafeIO2 #-}
syncCallbackUnsafeIO2 :: (JSVal -> JSVal -> IO JSVal) -> IO (Callback f)
syncCallbackUnsafeIO2 x = js_syncCallbackApplyReturnUnsafe 2 (unsafeCoerce x)
{-# INLINE syncCallbackUnsafe3 #-}
syncCallbackUnsafe3 :: (JSVal -> JSVal -> JSVal -> JSVal) -> IO (Callback f)
syncCallbackUnsafe3 x = js_syncCallbackApplyReturnUnsafe 3 (unsafeCoerce x)
{-# INLINE syncCallbackUnsafeIO3 #-}
syncCallbackUnsafeIO3 :: (JSVal -> JSVal -> JSVal -> IO JSVal) -> IO (Callback f)
syncCallbackUnsafeIO3 x = js_syncCallbackApplyReturnUnsafe 3 (unsafeCoerce x)
foreign import javascript unsafe
"h$makeCallbackApply($1, h$runSyncReturnUnsafe, [false], $2)"
js_syncCallbackApplyReturnUnsafe :: Int -> Any -> IO (Callback f)
| mb21/qua-kit | libs/hs/ghcjs-hs-interop/src/JsHs/Callback.hs | mit | 2,775 | 5 | 11 | 513 | 513 | 291 | 222 | 62 | 1 |
-- |
-- Utilities for dealing with 'FilePath'.
--
module GraphDB.Util.FileSystem
(
module Filesystem,
module Filesystem.Path.CurrentOS,
Status(..),
getStatus,
getExists,
getTemporaryDirectory,
remove,
removeIfExists,
removeTreeIfExists,
move,
copy,
resolve,
Lock,
withLock,
acquireLock,
releaseLock,
listFilesByExtension,
)
where
import GraphDB.Util.Prelude hiding (stripPrefix, last)
import Filesystem.Path.CurrentOS
import Filesystem
import qualified System.Directory as Directory
import qualified Data.List as List
import qualified System.IO.Error as IOError
import qualified System.FileLock as Lock
data Status = File | Directory | NotExists
deriving (Show, Eq, Ord, Enum)
getStatus :: FilePath -> IO Status
getStatus path = do
z <- isFile path
if z
then return File
else do
z <- isDirectory path
if z
then return Directory
else return NotExists
getExists :: FilePath -> IO Bool
getExists path = getStatus path >>= return . (/= NotExists)
getTemporaryDirectory :: IO FilePath
getTemporaryDirectory =
Directory.getTemporaryDirectory >>= return . decodeString
remove :: FilePath -> IO ()
remove path = do
status <- getStatus path
case status of
File -> removeFile path
Directory -> removeTree path
NotExists -> IOError.ioError $ IOError.mkIOError IOError.doesNotExistErrorType "" Nothing (Just $ encodeString path)
removeIfExists :: FilePath -> IO ()
removeIfExists path = do
status <- getStatus path
case status of
File -> removeFile path
Directory -> removeTree path
NotExists -> return ()
removeTreeIfExists :: FilePath -> IO ()
removeTreeIfExists path = removeTree path `catch` \e -> case e of
_ | IOError.isDoesNotExistError e -> return ()
| otherwise -> throwIO e
move :: FilePath -> FilePath -> IO ()
move from to = do
copy from to
remove from
copy :: FilePath -> FilePath -> IO ()
copy from to = do
isDir <- isDirectory from
if isDir
then do
createTree to
copyDirectory from to
else do
createTree $ directory to
copyFile from to
copyDirectory :: FilePath -> FilePath -> IO ()
copyDirectory path path' = do
members <- listDirectory path
let members' = do
member <- members
let relative =
fromMaybe (error "Unexpectedly empty member path") $
last member
return $ path' <> relative
sequence_ $ zipWith copy members members'
last :: FilePath -> Maybe FilePath
last p = case splitDirectories p of
[] -> Nothing
l -> Just $ List.last l
resolve :: FilePath -> IO FilePath
resolve path = case splitDirectories path of
h:t | h == "~" -> do
home <- getHomeDirectory
return $ mconcat $ home : t
_ -> return path
type Lock = Lock.FileLock
-- |
-- Execute an IO action while using a file as an interprocess lock,
-- thus ensuring that only a single action executes across all processes
-- of the running system.
--
-- If a file exists already it checks whether it is locked on by any running process,
-- including the current one,
-- and acquires it if it's not.
--
-- Releases the lock in case of any failure in executed action or when the action is executed.
withLock :: FilePath -> IO a -> IO a
withLock file io = bracket (acquireLock file) releaseLock (const io)
acquireLock :: FilePath -> IO Lock
acquireLock path =
Lock.tryLockFile (encodeString path) Lock.Exclusive >>= \case
Just lock -> return lock
_ -> error $ "Lock `" ++ show path ++ "` is already in use"
releaseLock :: Lock -> IO ()
releaseLock = Lock.unlockFile
listFilesByExtension :: FilePath -> Text -> IO [FilePath]
listFilesByExtension dir extension =
listDirectory dir >>=
return . filter (flip hasExtension extension)
| nikita-volkov/graph-db | library/GraphDB/Util/FileSystem.hs | mit | 3,806 | 0 | 18 | 874 | 1,095 | 553 | 542 | -1 | -1 |
{- |
Module : Exception
Copyright : Zeqing Guo
Licence : MIT (see LICENSE in the distribution)
Maintainer : github.com/zeqing-guo
Stability : experimental
Portability : portable
This file contains all things about exception.
-}
module Exception
( GinError(..)
, ThrowsError
) where
import Control.Monad.Error
data GinError = Parser String
| BlogsMissed
| Default String
showError :: GinError -> String
showError (Parser message) = "Parse error at" ++ message
showError (Default message) = message
showError BlogsMissed = "Records of old posts missed, please gin rebuild to fetch your posts' records from github."
instance Show GinError where
show = showError
instance Error GinError where
noMsg = Default "An error has occurred"
strMsg = Default
type ThrowsError = Either GinError
| zeqing-guo/gin-haskell | src/Exception.hs | mit | 859 | 0 | 7 | 195 | 132 | 74 | 58 | 17 | 1 |
-- |All type conversion to and from the PostgreSQL server is handled here.
module Database.TemplatePG.Types ( PGType(..)
, pgTypeFromOID
, pgStringToType
, pgTypeToString
) where
import Data.Time.Calendar
import Data.Time.Clock
import Data.Time.Format
import Language.Haskell.TH
import Text.Regex
-- |TemplatePG currenly only supports a handful of types. It also doesn't
-- distinguish between numeric types with different ranges. More types are the
-- most likely feature of future TemplatePG releases.
data PGType = PGBoolean -- ^ bool
| PGInteger -- ^ integer
| PGReal -- ^ float
| PGText -- ^ text/varchar
| PGTimestampTZ -- ^ timestamptz (timestamp with time zone)
| PGDate -- ^ date (day without time)
| PGInterval -- ^ interval (a time interval), send-only
deriving (Eq, Show)
-- |Convert a type OID from PostgreSQL's catalog to a TemplatePG
-- representation. To get a list of types: @SELECT typname, oid FROM pg_type@
-- Note that I have assumed, but not tested, that type OIDs for these basic
-- types are consistent across installations. If not, I'm going to have to
-- switch to using the text descriptions
pgTypeFromOID :: Int -- ^ PostgreSQL type OID
-> PGType
pgTypeFromOID 16 = PGBoolean -- bool
-- treating all ints alike for now
pgTypeFromOID 20 = PGInteger -- int8
pgTypeFromOID 21 = PGInteger -- int2
pgTypeFromOID 23 = PGInteger -- int4
pgTypeFromOID 25 = PGText -- text
-- as with ints, sacrificing precision/safety for floats
pgTypeFromOID 700 = PGReal -- float4
pgTypeFromOID 701 = PGReal -- float8
-- I don't currently treat varchars differently from text. It would make sense
-- to do so if I could enforce length limits at compile time.
pgTypeFromOID 1043 = PGText -- varchar
pgTypeFromOID 1082 = PGDate -- date
pgTypeFromOID 1184 = PGTimestampTZ -- timestamptz
pgTypeFromOID 1186 = PGInterval -- interval
pgTypeFromOID n = error $ "Unknown PostgreSQL type: " ++ show n
-- |This is PostgreSQL's canonical timestamp format.
-- Time conversions are complicated a bit because PostgreSQL doesn't support
-- timezones with minute parts, and Haskell only supports timezones with
-- minutes parts. We'll need to truncate and pad timestamp strings accordingly.
-- This means with minute parts will not work.
pgTimestampTZFormat :: String
pgTimestampTZFormat = "%F %T%z"
readIntegral :: (Read a, Integral a) => String -> a
readIntegral = read
readReal :: (Read a, Real a) => String -> a
readReal = read
showIntegral :: (Show a, Integral a) => a -> String
showIntegral = show
showReal :: (Show a, Real a) => a -> String
showReal = show
-- |Convert a Haskell value to a string of the given PostgreSQL type. Or, more
-- accurately, given a PostgreSQL type, create a function for converting
-- compatible Haskell values into a string of that type.
-- @pgTypeToString :: PGType -> (? -> String)@
pgTypeToString :: PGType -> Q Exp
pgTypeToString PGInteger = [| showIntegral |]
pgTypeToString PGReal = [| showReal |]
pgTypeToString PGText = [| escapeString |]
pgTypeToString PGBoolean = [| (\ b -> if b then "'t'" else "'f'") |]
pgTypeToString PGTimestampTZ = [| \t -> let ts = formatTime defaultTimeLocale pgTimestampTZFormat t in
"TIMESTAMP WITH TIME ZONE '" ++
(take (length ts - 2) ts) ++ "'" |]
pgTypeToString PGDate = [| \d -> "'" ++ showGregorian d ++ "'" |]
pgTypeToString PGInterval = [| \s -> "'" ++ show (s::DiffTime) ++ "'" |]
-- |Convert a string from PostgreSQL of the given type into an appropriate
-- Haskell value. Or, more accurately, given a PostgreSQL type, create a
-- function for converting a string of that type into a compatible Haskell
-- value.
-- @pgStringToType :: PGType -> (String -> ?)@
pgStringToType :: PGType -> Q Exp
-- TODO: Is reading to any integral type too unsafe to justify the convenience?
pgStringToType PGInteger = [| readIntegral |]
pgStringToType PGReal = [| readReal |]
pgStringToType PGText = [| id |]
pgStringToType PGBoolean = [| \s -> case s of
"t" -> True
"f" -> False
_ -> error "unrecognized boolean type from PostgreSQL" |]
pgStringToType PGTimestampTZ = [| \t -> readTime defaultTimeLocale pgTimestampTZFormat (t ++ "00") |]
pgStringToType PGDate = [| readTime defaultTimeLocale "%F" |]
pgStringToType PGInterval = error "Reading PostgreSQL intervals isn't supported (yet)."
-- |Make a string safe for interpolation (escape single-quotes). This relies on
-- standard_conforming_strings = on in postgresql.conf. I'm not 100% sure that
-- this makes all strings safe for execution. I don't know if it's possible to
-- inject SQL with strange (possibly Unicode) characters.
escapeString :: String -> String
escapeString s = "'" ++ (subRegex (mkRegex "'") s "''") ++ "'"
| jekor/templatepg | Database/TemplatePG/Types.hs | mit | 5,250 | 0 | 10 | 1,371 | 602 | 366 | 236 | -1 | -1 |
module Scrabble (scoreLetter, scoreWord) where
import Data.Char (toUpper)
import Data.Map (findWithDefault, fromList)
scoreLetter :: Num a => Char -> a
scoreLetter letter = findWithDefault 0 (toUpper letter) scoreMap
where
scoreMap = fromList [(k,v) | (ks, v) <- scoreTable, k <- ks]
scoreTable = [ ("AEIOULNRST", 1)
, ("DG" , 2)
, ("BCMP" , 3)
, ("FHVWY" , 4)
, ("K" , 5)
, ("JX" , 8)
, ("QZ" , 10) ]
scoreWord :: Num a => String -> a
scoreWord = sum . map scoreLetter
| exercism/xhaskell | exercises/practice/scrabble-score/.meta/examples/success-standard/src/Scrabble.hs | mit | 632 | 0 | 11 | 247 | 209 | 122 | 87 | 15 | 1 |
main :: IO ()
main = putStrLn "Not yet implemented"
| justanotherdot/advent-linguist | 2016/Haskell/AdventOfCode/test/Spec.hs | mit | 52 | 0 | 6 | 10 | 19 | 9 | 10 | 2 | 1 |
import GameOfLife
main = do
print $ step $ setAlive 3 1 $ setAlive 2 1 $ setAlive 1 1 newGame
| tsujigiri/Game-of-Life-Haskell | src/Main.hs | mit | 102 | 0 | 10 | 29 | 45 | 21 | 24 | 3 | 1 |
-- vim: ts=2:sw=2:sts=2
module XMonad.Config.Amer.Mouse (myMouseBindings) where
import XMonad
import qualified Data.Map.Strict as M
import qualified XMonad.StackSet as W
import qualified XMonad.Actions.FlexibleManipulate as Flex
myMouseBindings :: XConfig Layout -> M.Map (KeyMask, Button) (Window -> X ())
myMouseBindings XConfig {XMonad.modMask = modMask} = M.fromList
-- mod-button1 %! Set the window to floating mode and move by dragging
-- [ ((modMask, button1), \w -> focus w >> mouseMoveWindow w >> windows W.shiftMaster)
-- mod-button2 %! Raise the window to the top of the stack
[ ((modMask, button2), windows . (W.shiftMaster .) . W.focusWindow)
-- mod-button3 %! Set the window to floating mode and resize by dragging
-- , ((modMask, button3), \w -> focus w >> mouseResizeWindow w >> windows W.shiftMaster)
-- optional. but nicer than normal mouse move and size
-- , ((mod4Mask, button3), \w -> focus w >> Flex.mouseWindow Flex.discrete w)
, ((mod4Mask, button3), Flex.mouseWindow Flex.discrete)
-- scroll wheel window focusing
, ((mod4Mask, button4), const $ windows W.swapDown)
, ((mod4Mask, button5), const $ windows W.swapUp)
]
| amerlyq/airy | xmonad/cfg/Mouse.hs | mit | 1,172 | 0 | 11 | 194 | 213 | 131 | 82 | 11 | 1 |
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE CPP #-}
#define DERIVING Generic, Default, Show, FromJSON, Eq, Ord
module Buchhaltung.Types
(module Control.Monad.Except
,module Buchhaltung.Types
)where
import Buchhaltung.Utils
import Control.Applicative
import Control.Arrow
import Control.DeepSeq
import Control.Monad.Except
import Control.Monad.Identity
import Control.Monad.RWS.Strict
import Control.Monad.Reader
import qualified Data.Aeson as A
import qualified Data.Aeson.Text as A
import qualified Data.Aeson.Types as A
import Data.Char
import Data.Default
import Data.Foldable
import Data.Function
import Data.Functor
import qualified Data.HashMap.Strict as HM
import Data.Hashable
import qualified Data.ListLike as L
import qualified Data.Map.Strict as M
import Data.Maybe
import Data.String
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified Data.Vector as V
import Data.Yaml
import Formatting
import Formatting.Internal (Format)
import qualified Formatting.ShortFormatters as F
import GHC.Generics
import Hledger.Data
import Prelude hiding (lookup)
import System.FilePath
import Text.Printf
import qualified Text.Regex.TDFA as R
import Text.Regex.TDFA.Text () -- for instances
-- * Monad used for most of the funtionality
type CommonM env = RWST (FullOptions env) () () (ErrorT IO)
-- * The Source of an imported transaction
type Version = T.Text
data SFormat a = SFormat { fName :: T.Text
, fVersion :: a
}
deriving (Generic, Show, Eq, Ord, Read, Hashable, Functor)
-- | represents a key value store and a protocol
data Source = Source { sFormat :: SFormat Version
, sStore :: M.Map T.Text T.Text }
deriving (Generic, Show, Eq, Ord, Read)
-- | Creates a 'Source' from non null values of a HashMap (e.g. from
-- 'MyRecord')
fromMapToSource :: SFormat Version -> HM.HashMap T.Text T.Text -> Source
fromMapToSource format = Source format . M.fromList .
filter (not . L.null . snd) . HM.toList
-- | produces a map that includes 'sFormat' under the keys @"formatName"@
-- and @"formatVersion"@
sourceToMap :: Source -> M.Map T.Text T.Text
sourceToMap s = M.unionWith (\x y -> x <> ", " <> y)
(sStore s)
$ M.fromList $ formatToAssoc $ sFormat s
formatToAssoc f = [("formatName", fName f)
,("formatVersion", fVersion f)]
json :: Source -> TL.Text
json = A.encodeToLazyText
instance FromJSON Source where
parseJSON (Object v) = do
Source <$>
(SFormat <$> v .: "formatName" <*> v .: "formatVersion")
<*> v.: "store"
parseJSON invalid = A.typeMismatch "Source" invalid
instance ToJSON Source where
toJSON s = Object $ HM.insert "store" (toJSON $ sStore s) $ toJSON
<$> HM.fromList (formatToAssoc $ sFormat s)
stripPrefixOptions n = A.defaultOptions{A.fieldLabelModifier = g}
where g = drop n . fmap toLower
-- * Import Tag
newtype ImportTag = ImportTag { fromImportTag :: T.Text }
deriving ( Generic, Show)
instance Default ImportTag where
def = "SOURCE"
instance IsString ImportTag where
fromString = ImportTag . fromString
-- * Error handling
type Msg = T.Text
type Error = Either Msg
type ErrorT = ExceptT Msg
throwFormat
:: MonadError Msg m => Format T.Text t -> (t -> Msg) -> m b
throwFormat msg a = throwError $ a $ sformat msg
maybeThrow
:: MonadError Msg m => Format T.Text t
-> (t -> Msg) -> (a1 -> m b) -> Maybe a1 -> m b
maybeThrow msg a = maybe (throwFormat msg a)
lookupErrD
:: Show t => [Char] -- ^ additional description
-> (t -> t1 -> Maybe a) -- ^ lookup function
-> t -- ^ lookup arg2
-> t1 -- ^ lookup arg2
-> a
lookupErrD d l k m =
either (error . T.unpack) id $ runExcept $ lookupErrM d l k m
lookupErrM
:: (MonadError Msg m, Show a) =>
String -> (a -> t -> Maybe b) -> a -> t -> m b
lookupErrM description lookup k container =
maybeThrow ("lookupErr: " %F.sh% " not found: " %F.s)
(\f -> f k description) return
$ lookup k container
fromListUnique :: (MonadError Msg m, Show k, Ord k)
=> [(k, a)] -> m (M.Map k a)
fromListUnique = sequence . M.fromListWithKey
(\k _ _ -> throwFormat ("Duplicate key '"%shown%"' in M.fromList") ($ k))
. fmap (second pure)
-- * Options
data Options user config env = Options
{ oUser :: user
, oProfile :: FilePath
, oAction :: Action
, oConfig :: config
, oEnv :: env
}
deriving (Show, Generic, NFData)
-- instance Functor (Options user config) where
-- fmap f o = o{oEnv = f $ oEnv o}
type FullOptions = Options User Config
type RawOptions = Options (Maybe Username) ()
toFull :: MonadError Msg m
=> RawOptions env
-> Config
-> m (FullOptions env)
toFull opts1@Options{oUser=user} config =
(\u -> opts2{oUser = u}) <$>
runReaderT (maybe (defaultUser 0) lookupUser user) opts2
where opts2 = opts1 { oConfig = config }
-- ** Reading options
readConfig :: MonadReader (Options user config env) m => (config -> a) -> m a
readConfig f = reader $ f. oConfig
readUser :: MonadReader (Options user config env) m => (user -> a) -> m a
readUser f = reader $ f . oUser
user :: MonadReader (Options user config env) m => m user
user = readUser id
readLedger
:: MonadReader (Options User config env) m =>
(Ledgers -> a) -> m a
readLedger = (<$> readUser ledgers)
-- | get absolute paths in profile dir
absolute
:: MonadReader (Options user config env) m =>
FilePath -> m FilePath
absolute f = do prof <- reader oProfile
return $ prof </> f
-- * Config
data Config = Config
{
cUsers :: Users
, cUserList :: V.Vector Username
, cImportTag :: ImportTag
, cTodoAccount :: AccountName
-- ^ account for unmatched imported transactions
, cDbaclExecutable :: FilePath
, cLedgerExecutable :: FilePath
, cHledgerExecutable :: FilePath
-- , cFormats :: HM.HashMap T.Text [T.Text]
-- -- ^ for every format a list of columns used in the bayesian
-- -- classifier used in match
}
deriving ( Generic, Show )
askTag :: MonadReader (Options user Config env) m => m ImportTag
askTag = readConfig $ cImportTag
askTodoFilter :: MonadReader (Options user Config env) m
=> m (AccountName -> Bool)
askTodoFilter = return . L.isPrefixOf =<< readConfig cTodoAccount
instance FromJSON Config where
parseJSON (Object v) = do
-- Users are configured as list, to have a defined order
users <- parseJSON =<< v .: "users" :: A.Parser (V.Vector User)
-- formats <- v .:? "formats" .!= mempty
dbEx <- v .:? "dbaclExecutable" .!= "dbacl" :: Parser FilePath
[lEx, hlEx] <- forM ["", "h"] $ \pfx ->
v .:? (T.pack pfx <> "ledgerExecutable") .!= (pfx <> "ledger")
:: Parser FilePath
return Config
{ cUsers = HM.fromList $ (\u -> (name u, u)) <$> V.toList users
, cUserList = name <$> users
, cImportTag = def
, cTodoAccount = "TODO"
-- , cFormats = formats
, cDbaclExecutable = dbEx
, cLedgerExecutable = lEx
, cHledgerExecutable = hlEx
}
parseJSON invalid = A.typeMismatch "Config" invalid
readConfigFromFile :: FilePath -> IO Config
readConfigFromFile path = either (error . prettyPrintParseException) id <$>
decodeFileEither (path </> "config" <.> "yml") :: IO Config
-- * User
data User = User
{ name :: Username
, ledgers :: Ledgers
, accountPrefixOthers :: Maybe AccountName
-- ^ the account prefix for accounts receivable or payable
-- (depending on current balance) to other users
, aqBanking :: Maybe AQBankingConf
, bankAccounts :: Maybe BankAccounts
, ignoredAccountsOnAdd :: Maybe [Regex]
, ignoredAccountsOnMatch :: Maybe [Regex]
, numSuggestedAccounts :: Maybe Int
, reverseAccountInput :: Maybe Bool
}
deriving ( Generic, Show, FromJSON)
type Users = HM.HashMap Username User
newtype Username = Username T.Text
deriving ( Generic, FromJSON, NFData, Eq, Hashable, A.FromJSONKey, Ord)
fromUsername :: Username -> T.Text
fromUsername (Username n) = n
instance Show Username where
show = T.unpack . fromUsername
instance Eq User where
(==) = (==) `on` name
-- ** Reading User settings
-- | Looks up a user and throws an error if they do not exist.
lookupUser :: ( MonadError Msg m
, MonadReader (Options user Config e) m)
=> Username
-> m User
lookupUser user = do
maybeThrow msg ($ user) return . HM.lookup user . cUsers =<< reader oConfig
where msg = "User '"%F.sh%"' not found"
defaultUser :: ( MonadError Msg m
, MonadReader (Options user Config e) m)
=> Int -- ^ default position in user list
-> m User
defaultUser ix = do
config <- reader oConfig
maybeThrow msg ($ succ ix) lookupUser $ cUserList config V.!? ix
where msg = "There are less than "%F.d%
" users configured. Please add a user to the config file."
-- ** A User's ledger files
data Ledgers = Ledgers
{ imported :: FilePath
, addedByThisUser :: FilePath
, addedByOthers :: Maybe FilePath
, mainLedger :: FilePath -- ^ ledger file for 'ledger' CLI
, mainHledger :: Maybe FilePath -- ^ ledger file for 'hledger' CLI
}
deriving (Generic, Default, Show, FromJSON, Eq, Ord)
-- | generates the receiable/payable account for between two users
-- (suffixed by the current, the recording, user)
receivablePayable
:: (MonadError Msg m, MonadReader (FullOptions env) m)
=> Bool
-- ^ TRUE | FALSE = for (this | the other) user's ledger
-> User -- ^ the other user
-> m T.Text
receivablePayable forThis other = do
this <- readUser id
let (ledgerU, accountU) =
if forThis then (this, other) else (other, this)
let full pref = return $ intercalateL ":" $ pref :
(fromUsername . name <$> [accountU, this])
maybeThrow msg ($ name ledgerU) full
$ accountPrefixOthers ledgerU
where msg = "User '"%F.sh%"' has no accountPrefixOthers configured"
-- ** A user's bank accounts
askAccountMap :: MonadReader (Options User config env) m => m AccountMap
askAccountMap = readUser $ maybe mempty fromBankAccounts . bankAccounts
newtype BankAccounts = BankAccounts
{ fromBankAccounts :: AccountMap }
deriving (Generic, Default, Show, Eq)
isIgnored :: Maybe [Regex] -> AccountName -> Bool
isIgnored regexes acc = or $ maybe [] (fmap g) $ regexes
where g ign = R.match (rRegex ign) acc
data Regex = Regex
{rShow :: T.Text
, rRegex :: R.Regex
}
instance FromJSON Regex where
parseJSON (String v) = Regex v <$> R.makeRegexM v
parseJSON invalid = A.typeMismatch "regex string" invalid
instance Show Regex where
show = T.unpack . rShow
data AccountId = AccountId { aBank :: T.Text
, aAccount :: T.Text }
deriving (Generic, Eq, Ord, Hashable, Show)
type AccountMap = HM.HashMap AccountId AccountName
instance (Hashable a, Eq a) => Default (HM.HashMap a b) where
def = mempty
instance FromJSON BankAccounts where
parseJSON (Object v) = BankAccounts . HM.fromList . concat
<$> traverse parseAccountMap (HM.toList v)
parseJSON invalid = A.typeMismatch "BankAccounts" invalid
parseAccountMap :: FromJSON b => (T.Text, Value) -> Parser [(AccountId, b)]
parseAccountMap (bank, (Object m)) = traverse f $ HM.toList m
where f (acc,v) = (,) (AccountId bank acc) <$> parseJSON v
parseAccountMap (_, invalid) = A.typeMismatch "parseAccountMap" invalid
-- * AQBanking
data AQBankingConf = AQBankingConf
{ connections :: [AQConnection]
, configDir :: FilePath
, aqBankingExecutable :: Maybe FilePath
, aqhbciToolExecutable :: Maybe FilePath
}
deriving ( DERIVING )
data AQConnection = AQConnection
{ aqUser :: String
, aqBlz :: String
, aqUrl :: String
, aqHbciv :: HBCIv
, aqName :: String
, aqType :: AQType
}
deriving ( Generic, Show, Eq, Ord)
instance FromJSON AQConnection where
parseJSON = A.genericParseJSON $ stripPrefixOptions 2
instance ToJSON AQConnection where
toEncoding = A.genericToEncoding $ stripPrefixOptions 2
-- -- | workaround yaml problem, where 46549 does not parse as a string.
-- newtype String2 = String2 String
-- deriving ( Generic, Show)
-- instance FromJSON String2 where
-- parseJSON (String v) = String2 v
-- parseJSON (Number v) = String2 v
-- | other modes have to be setup manually. Refer to the AQBanking
-- manual. Use the '-C' to point to the configured 'configDir'.
data AQType = PinTan
| Other
deriving ( Generic, Show, FromJSON, ToJSON, Eq, Ord )
data HBCIv = HBCI201
| HBCI210
| HBCI220
| HBCI300
deriving ( Generic, Show, FromJSON, ToJSON, Eq, Ord )
toArg HBCI201 = "201"
toArg HBCI210 = "210"
toArg HBCI220 = "220"
toArg HBCI300 = "300"
-- readAQ
-- :: (MonadError Msg m, MonadReader (Options User config env) m) =>
-- (AQBankingConf -> m b) -> m b
-- readAQ f = do
-- * Actions
type PaypalUsername = T.Text
data Action = Add { aPartners :: [Username] }
| Match
| Import { iVersion :: Maybe Version
, iPath :: FilePath
, iAction :: ImportAction }
| Update { aqVersion :: Maybe Version
, aqMatch :: Bool
-- ^ run match after import
, aqRequest :: Bool
-- ^ request new transactions
}
| Commit { hledger :: Bool, cArgs :: [String] }
| ListBalances
| Setup
| Ledger { lArgs :: [String] }
| HLedger { hlArgs :: [String] }
| AQBanking { aqArgs :: [String] }
deriving (Show, Generic, NFData)
data ImportAction = Paypal PaypalUsername
| AQBankingImport
| ComdirectVisa { comdirectVisaBlz :: T.Text }
| BarclaycardUs
| NatwestIntl
| BarclaysUk
| Pncbank { pncAccountIdentifier :: T.Text }
| Monefy MonefySettings
| Revolut (RevolutSettings ())
deriving (Show, Generic, NFData)
data MonefySettings = MonefySettings
{ monefyInstallation :: T.Text
, monefyCategorySuffix :: Bool }
deriving (Show, Generic, NFData)
data RevolutSettings a = RevolutSettings
{ revolutCurrency :: a
, revolutUser :: T.Text }
deriving (Show, Generic, NFData, Functor)
-- * Misc
type Comment = T.Text
| johannesgerer/buchhaltung | src/Buchhaltung/Types.hs | mit | 15,019 | 7 | 16 | 3,854 | 4,109 | 2,255 | 1,854 | 332 | 2 |
module NLP100.Chapter01Spec where
import NLP100.Chapter01
import Test.Hspec
spec :: Spec
spec = do
describe "第1章: 準備運動" $ do
describe "00. 文字列の逆順" $ do
-- 文字列"stressed"の文字を逆に(末尾から先頭に向かって)並べた文字列を得よ.
it "should return correct value" $ do
knock00 "stressed" `shouldBe` "desserts"
describe "01. 「パタトクカシーー」" $ do
-- 「パタトクカシーー」という文字列の1,3,5,7文字目を取り出して
-- 連結した文字列を得よ.
it "should return correct value" $ do
knock01 "パタトクカシーー" `shouldBe` "パトカー"
describe "02. 「パトカー」+「タクシー」=「パタトクカシーー」" $ do
-- パトカー」+「タクシー」の文字を先頭から交互に連結して
-- 文字列「パタトクカシーー」を得よ.
it "should return correct value" $ do
knock02 "パトカー" "タクシー" `shouldBe` "パタトクカシーー"
describe "03. 円周率" $ do
-- Now I need a drink, alcoholic of course,
-- after the heavy lectures involving quantum mechanics.
--
-- という文を単語に分解し,各単語の(アルファベットの)文字数を
-- 先頭から出現順に並べたリストを作成せよ.
it "should return correct value" $ do
let
row1 = "Now I need a drink, alcoholic of course, "
row2 = "after the heavy lectures involving quantum mechanics."
sentence = row1 ++ row2
knock03 sentence `shouldBe` "3.14159265358979"
describe "04. 元素記号" $ do
-- Hi He Lied Because Boron Could Not Oxidize Fluorine.
-- New Nations Might Also Sign Peace Security Clause.
-- Arthur King Can.
--
-- という文を単語に分解し,1, 5, 6, 7, 8, 9, 15, 16, 19番目の単語は
-- 先頭の1文字,それ以外の単語は先頭に2文字を取り出し,
-- 取り出した文字列から単語の位置(先頭から何番目の単語か)への
-- 連想配列(辞書型もしくはマップ型)を作成せよ.
it "should return correct value" $ do
let
row1 = "Hi He Lied Because Boron Could Not Oxidize Fluorine. "
row2 = "New Nations Might Also Sign Peace Security Clause. "
row3 = "Arthur King Can."
sentence = row1 ++ row2 ++ row3
knock04 sentence `shouldBe` [
(1,"H"),(2,"He"),(3,"Li"),(4,"Be"),(5,"B"),(6,"C"),(7,"N"),
(8,"Ox"),(9,"F"),(10,"Ne"),(11,"Na"),(12,"Mi"),(13,"Al"),(14,"Si"),
(15,"P"),(16,"S"),(17,"Cl"),(18,"Ar"),(19,"Ki"),(20,"Ca")
]
describe "05. n-gram" $ do
-- 与えられたシーケンス(文字列やリストなど)からn-gramを作る関数を作成せよ.
-- この関数を用い,"I am an NLPer"という文から単語bi-gram,文字bi-gramを得よ.
it "should return correct value" $ do
let
text = "I am an NLPer"
words = splitWords text
knock05 text `shouldBe` [
"I "," a", "am","m "," a","an","n "," N","NL","LP","Pe","er"
]
knock05 words `shouldBe` [
["I","am"],["am","an"],["an","NLPer"]
]
describe "06. 集合" $ do
-- "paraparaparadise"と"paragraph"に含まれる文字bi-gramの集合を,
-- それぞれ, XとYとして求め,XとYの和集合,積集合,差集合を求めよ.
-- さらに,'se'というbi-gramがXおよびYに含まれるかどうかを調べよ.
it "should return correct value" $ do
let
x = "paraparaparadise"
y = "paragraph"
k = "se"
knock06union x y `shouldBe` [
"pa","ar","ra","ap","ad","di","is","se","ag","gr","ph"
]
knock06intersect x y `shouldBe` [
"pa","ar","ra","ap"
]
knock06difference x y `shouldBe` [
"ad","di","is","se"
]
knock06contains x k `shouldBe` True
knock06contains y k `shouldBe` False
describe "07. テンプレートによる文生成" $ do
-- 引数x, y, zを受け取り「x時のyはz」という文字列を返す関数を実装せよ.
-- さらに,x=12, y="気温", z=22.4として,実行結果を確認せよ.
it "should return correct value" $ do
knock07 12 "気温" 22.4 `shouldBe` "12時の気温は22.4"
describe "08. 暗号文" $ do
-- 与えられた文字列の各文字を,以下の仕様で変換する関数cipherを実装せよ.
--
-- ・英小文字ならば(219 - 文字コード)の文字に置換
-- ・その他の文字はそのまま出力
--
-- この関数を用い,英語のメッセージを暗号化・復号化せよ.
it "should return correct value" $ do
knock08encode "Test08-`Z`" `shouldBe` "Tvhg08-`Z`"
knock08decode "Tvhg08-`Z`" `shouldBe` "Test08-`Z`"
describe "09. Typoglycemia" $ do
-- スペースで区切られた単語列に対して,各単語の先頭と末尾の文字は残し,
-- それ以外の文字の順序をランダムに並び替えるプログラムを作成せよ.
-- ただし,長さが4以下の単語は並び替えないこととする.
--
-- I couldn't believe that I could actually understand what
-- I was reading : the phenomenal power of the human mind .
--
-- を与え,その実行結果を確認せよ.
it "should return correct value" $ do
let
row1 = "I couldn't believe that I could actually understand what "
row2 = "I was reading : the phenomenal power of the human mind ."
sentence = row1 ++ row2
row3 = "I col'ndut blveiee that I cluod acullaty uesnatrdnd what "
row4 = "I was ranideg : the pnmaneoehl pewor of the hamun mind ."
answer = row3 ++ row4
knock09 sentence `shouldBe` answer
| namikingsoft/nlp100knock | test/NLP100/Chapter01Spec.hs | mit | 6,138 | 0 | 32 | 1,353 | 920 | 513 | 407 | 73 | 1 |
{- This module was generated from data in the Kate syntax
highlighting file texinfo.xml, version 0.2, by Daniel Franke (franke.daniel@gmail.com) -}
module Text.Highlighting.Kate.Syntax.Texinfo
(highlight, parseExpression, syntaxName, syntaxExtensions)
where
import Text.Highlighting.Kate.Types
import Text.Highlighting.Kate.Common
import qualified Text.Highlighting.Kate.Syntax.Alert
import Text.ParserCombinators.Parsec hiding (State)
import Control.Monad.State
import Data.Char (isSpace)
-- | Full name of language.
syntaxName :: String
syntaxName = "Texinfo"
-- | Filename extensions for this language.
syntaxExtensions :: String
syntaxExtensions = "*.texi"
-- | Highlight source code using this syntax definition.
highlight :: String -> [SourceLine]
highlight input = evalState (mapM parseSourceLine $ lines input) startingState
parseSourceLine :: String -> State SyntaxState SourceLine
parseSourceLine = mkParseSourceLine (parseExpression Nothing)
-- | Parse an expression using appropriate local context.
parseExpression :: Maybe (String,String)
-> KateParser Token
parseExpression mbcontext = do
(lang,cont) <- maybe currentContext return mbcontext
result <- parseRules (lang,cont)
optional $ do eof
updateState $ \st -> st{ synStPrevChar = '\n' }
pEndLine
return result
startingState = SyntaxState {synStContexts = [("Texinfo","Normal Text")], synStLineNumber = 0, synStPrevChar = '\n', synStPrevNonspace = False, synStContinuation = False, synStCaseSensitive = True, synStKeywordCaseSensitive = True, synStCaptures = []}
pEndLine = do
updateState $ \st -> st{ synStPrevNonspace = False }
context <- currentContext
contexts <- synStContexts `fmap` getState
st <- getState
if length contexts >= 2
then case context of
_ | synStContinuation st -> updateState $ \st -> st{ synStContinuation = False }
("Texinfo","Normal Text") -> return ()
("Texinfo","singleLineComment") -> (popContext) >> pEndLine
("Texinfo","multiLineComment") -> return ()
("Texinfo","nodeFolding") -> return ()
("Texinfo","folding") -> return ()
_ -> return ()
else return ()
withAttribute attr txt = do
when (null txt) $ fail "Parser matched no text"
updateState $ \st -> st { synStPrevChar = last txt
, synStPrevNonspace = synStPrevNonspace st || not (all isSpace txt) }
return (attr, txt)
regex_'40c'28omment'29'3f'5cb = compileRegex True "@c(omment)?\\b"
regex_'40ignore'5cb = compileRegex True "@ignore\\b"
regex_'40node'5cb = compileRegex True "@node\\b"
regex_'40'28menu'7csmallexample'7ctable'7cmultitable'29'5cb = compileRegex True "@(menu|smallexample|table|multitable)\\b"
regex_'40'5b'5cw'5d'2b'28'5c'7b'28'5b'5cw'5d'2b'5b'5cs'5d'2a'29'2b'5c'7d'29'3f = compileRegex True "@[\\w]+(\\{([\\w]+[\\s]*)+\\})?"
regex_'40end_'28menu'7csmallexample'7ctable'7cmultitable'29'5cb = compileRegex True "@end (menu|smallexample|table|multitable)\\b"
parseRules ("Texinfo","Normal Text") =
(((pRegExpr regex_'40c'28omment'29'3f'5cb >>= withAttribute CommentTok) >>~ pushContext ("Texinfo","singleLineComment"))
<|>
((pRegExpr regex_'40ignore'5cb >>= withAttribute CommentTok) >>~ pushContext ("Texinfo","multiLineComment"))
<|>
((pRegExpr regex_'40node'5cb >>= withAttribute FunctionTok) >>~ pushContext ("Texinfo","nodeFolding"))
<|>
((pRegExpr regex_'40'28menu'7csmallexample'7ctable'7cmultitable'29'5cb >>= withAttribute FunctionTok) >>~ pushContext ("Texinfo","folding"))
<|>
((pRegExpr regex_'40'5b'5cw'5d'2b'28'5c'7b'28'5b'5cw'5d'2b'5b'5cs'5d'2a'29'2b'5c'7d'29'3f >>= withAttribute FunctionTok))
<|>
(currentContext >>= \x -> guard (x == ("Texinfo","Normal Text")) >> pDefault >>= withAttribute NormalTok))
parseRules ("Texinfo","singleLineComment") =
(((Text.Highlighting.Kate.Syntax.Alert.parseExpression (Just ("Alerts","")) >>= ((withAttribute CommentTok) . snd)))
<|>
(currentContext >>= \x -> guard (x == ("Texinfo","singleLineComment")) >> pDefault >>= withAttribute CommentTok))
parseRules ("Texinfo","multiLineComment") =
(((pString False "@end ignore" >>= withAttribute CommentTok) >>~ (popContext))
<|>
((Text.Highlighting.Kate.Syntax.Alert.parseExpression (Just ("Alerts","")) >>= ((withAttribute CommentTok) . snd)))
<|>
(currentContext >>= \x -> guard (x == ("Texinfo","multiLineComment")) >> pDefault >>= withAttribute CommentTok))
parseRules ("Texinfo","nodeFolding") =
(((lookAhead (pRegExpr regex_'40node'5cb) >> (popContext) >> currentContext >>= parseRules))
<|>
((parseRules ("Texinfo","Normal Text")))
<|>
(currentContext >>= \x -> guard (x == ("Texinfo","nodeFolding")) >> pDefault >>= withAttribute NormalTok))
parseRules ("Texinfo","folding") =
(((pRegExpr regex_'40end_'28menu'7csmallexample'7ctable'7cmultitable'29'5cb >>= withAttribute FunctionTok) >>~ (popContext))
<|>
((parseRules ("Texinfo","Normal Text")))
<|>
(currentContext >>= \x -> guard (x == ("Texinfo","folding")) >> pDefault >>= withAttribute NormalTok))
parseRules ("Alerts", _) = Text.Highlighting.Kate.Syntax.Alert.parseExpression Nothing
parseRules x = parseRules ("Texinfo","Normal Text") <|> fail ("Unknown context" ++ show x)
| ambiata/highlighting-kate | Text/Highlighting/Kate/Syntax/Texinfo.hs | gpl-2.0 | 5,266 | 0 | 15 | 781 | 1,405 | 765 | 640 | 88 | 8 |
{-# LANGUAGE OverloadedStrings #-}
module Tests where
import Test.HUnit
import Types
import Parse
-- Parse
testGrabLine = TestCase $ assertEqual
"Should accept 0+ anyChar followed by newline" "\n" (textP grabLine "\n")
testDef = TestCase $ assertEqual
"Simplest Def chunk"
[Def 1 "asdf" [Code "ass\n",Code "sd\n",Code " 4\n"]] $
encode " << asdf >>=\n ass\n sd\n 4\n"
testDefWithNewLines = TestCase $ assertEqual
"Def chunk with newlines in between code"
[Def 1 "asdf" [Code "ass\n",Code "\n",Code "\n",Code "sd\n",Code " 4\n"]] $
encode " << asdf >>=\n ass\n\n\n sd\n 4\n"
testDefFollowedByTitle = TestCase $ assertEqual
"Def chunk followed by chunk"
[Def 1 "asdf" [Code "ass\n"],Def 3 "bb" []] $
encode " << asdf >>=\n ass\n << bb >>=\n"
testProse = TestCase $ assertEqual
"Prose with newlines"
[Prose "asdfasd\n", Prose "\n", Prose " asdf\n",Def 4 "asdf" []] $
encode "asdfasd\n\n asdf\n <<asdf>>=\n"
testProseOnlyNL = TestCase $ assertEqual
"Prose with newlines"
[Prose "\n",Prose "\n",Prose "\n"] $
encode "\n\n\n"
testDefPrecedeWithNL = TestCase $ assertEqual
"Def preceded by newlines"
[Prose "\n",Prose "\n",Prose "\n",Def 4 "asdf" [Code "durp\n"]] $
encode "\n\n\n <<asdf>>=\n durp\n"
-- Processing
-- Pretty
-- Parse
main = runTestTT $ TestList
[ testGrabLine, testTitle
, testDef, testDefFollowedByTitle, testDefWithNewLines, testDefPrecedeWithNL
, testProse, testProseOnlyNL ]
| tcrs/lit | test/Tests.hs | gpl-2.0 | 1,523 | 0 | 11 | 332 | 384 | 198 | 186 | 35 | 1 |
-- -- {{{1
--
-- File : Flx/TODO.hs
-- Maintainer : Felix C. Stegerman <flx@obfusk.net>
-- Date : 2012-06-28
--
-- Copyright : Copyright (C) 2012 Felix C. Stegerman
-- Licence : GPLv2
--
-- Depends : ...
-- Description : ...
--
-- TODO : ...
--
-- -- }}}1
module Flx.TODO ( -- {{{1
cart, diagCart, diagChoose, pairs, pairsWith
) where -- }}}1
--
import Data.List.Ordered (insertSet, mergeAllBy, unionAllBy)
--
cart :: [[a]] -> [[a]]
cart [] = error "cart: empty list"
cart [xs] = map (:[]) xs
cart (xs:xss) = let ys = cart xss in concat [ map (x:) ys | x <- xs ]
diagCart :: ([a] -> [a] -> Ordering) -> [[a]] -> [[a]]
diagCart _ [] = error "diagCart: empty list"
diagCart _ [xs] = map (:[]) xs
diagCart f (xs:xss)
= let ys = diagCart f xss in mergeAllBy f [ map (x:) ys | x <- xs ]
diagChoose :: (Ord a, Ord b) => ([a] -> b) -> Int -> [a] -> [[a]]
diagChoose _ 1 xs = map (:[]) xs
diagChoose f n xs
= let ys = diagChoose f (n - 1) xs
in unionAllBy (\x y -> compare (f x,x) (f y,y))
$ map (filter ((== n) . length))
[ map (insertSet x) ys | x <- xs ]
pairs :: [a] -> [[(a,a)]]
pairs = pairsWith (,)
pairsWith :: (a -> a -> b) -> [a] -> [[b]]
pairsWith f [] = []
pairsWith f [_] = []
pairsWith f (x:xt) = map (f x) xt : pairsWith f xt
-- vim: set tw=70 sw=2 sts=2 et fdm=marker :
| obfusk/hs-flx | src/Flx/TODO.hs | gpl-2.0 | 1,606 | 0 | 13 | 601 | 636 | 353 | 283 | 25 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE LambdaCase #-}
-----------------------------------------------------------------------------
--
-- Module : IDE.PaneGroups
-- Copyright : 2007-2011 Juergen Nicklisch-Franken, Hamish Mackenzie
-- License : GPL
--
-- Maintainer : maintainer@leksah.org
-- Stability : provisional
-- Portability :
--
-- |
--
-----------------------------------------------------------------------------
module IDE.PaneGroups (
showBrowser
, setSensitivityDebugger
, showDebugger
) where
import IDE.Core.State (IDEM(..), readIDE, IDEAction(..))
import Graphics.UI.Frame.Panes
(RecoverablePane, PanePath, getTopWidget, getPane, getOrBuildPane,
PaneDirection(..), PanePathElement(..), layout, panePathForGroup)
import Graphics.UI.Frame.ViewFrame
(viewMoveTo, getBestPanePath, getNotebook, viewSplit',
newGroupOrBringToFront)
import Control.Monad (void, unless, when, liftM)
import IDE.Core.Types (frameState)
import Graphics.UI.Editor.Parameters (Direction(..))
import IDE.Pane.Modules (IDEModules(..))
import IDE.Pane.Info (IDEInfo(..))
import IDE.Pane.SourceBuffer
(newTextBuffer, bufferName, allBuffers)
import IDE.Pane.Breakpoints (IDEBreakpoints(..))
import IDE.Pane.Variables (IDEVariables(..))
import IDE.Pane.Trace (IDETrace(..))
import IDE.Pane.Workspace (WorkspacePane(..))
import Control.Monad.IO.Class (MonadIO(..))
import IDE.Pane.WebKit.Output (IDEOutput(..))
import GI.Gtk.Objects.Notebook
(notebookSetShowTabs, notebookSetTabPos)
import GI.Gtk.Enums (PositionType(..))
import GI.Gtk.Objects.Widget (widgetSetSensitive)
moveOrBuildPane :: RecoverablePane alpha beta delta => PanePath -> delta (Maybe alpha)
moveOrBuildPane path = do
mbPane <- getOrBuildPane (Left path)
case mbPane of
Just pane -> viewMoveTo path pane
Nothing -> return ()
return mbPane
showBrowser :: IDEAction
showBrowser = do
pp <- panePathForGroup "*Browser"
ret <- newGroupOrBringToFront "Browser" pp
layout' <- liftM layout (readIDE frameState)
case ret of
(Just rpp, True) -> do
viewSplit' rpp Horizontal
viewSplit' (rpp ++ [SplitP BottomP]) Horizontal
let lowerP = rpp ++ [SplitP BottomP, SplitP BottomP]
let upperP = rpp ++ [SplitP BottomP, SplitP TopP]
let topP = rpp ++ [SplitP TopP]
lower <- getNotebook lowerP
upper <- getNotebook upperP
top <- getNotebook topP
notebookSetTabPos lower PositionTypeBottom
notebookSetTabPos upper PositionTypeTop
notebookSetTabPos top PositionTypeTop
notebookSetShowTabs upper False
notebookSetShowTabs lower False
notebookSetShowTabs top False
getOrBuildBrowserPanes upperP lowerP topP
(Just rpp, False) -> do
let lowerP = getBestPanePath (rpp ++ [SplitP BottomP, SplitP BottomP]) layout'
let upperP = getBestPanePath (rpp ++ [SplitP BottomP, SplitP TopP]) layout'
let topP = getBestPanePath (rpp ++ [SplitP TopP]) layout'
getOrBuildBrowserPanes upperP lowerP topP
_ -> return ()
where
getOrBuildBrowserPanes upperP lowerP topP = do
moveOrBuildPane upperP :: IDEM (Maybe IDEModules)
moveOrBuildPane lowerP :: IDEM (Maybe IDEInfo)
moveOrBuildPane topP :: IDEM (Maybe WorkspacePane)
return ()
setSensitivityDebugger :: Bool -> IDEAction
setSensitivityDebugger sens = do
mbBreakpoints :: Maybe IDEBreakpoints <- getPane
mbVariables :: Maybe IDEVariables <- getPane
mbTrace :: Maybe IDETrace <- getPane
case mbBreakpoints of
Nothing -> return ()
Just idePane -> getTopWidget idePane >>= (`widgetSetSensitive` sens)
case mbVariables of
Nothing -> return ()
Just idePane -> getTopWidget idePane >>= (`widgetSetSensitive` sens)
case mbTrace of
Nothing -> return ()
Just idePane -> getTopWidget idePane >>= (`widgetSetSensitive` sens)
showDebugger :: IDEAction
showDebugger = do
pp <- panePathForGroup "*Debug"
ret <- newGroupOrBringToFront "Debug" pp
layout' <- liftM layout (readIDE frameState)
bufs <- allBuffers
case ret of
(Just rpp, True) -> do
viewSplit' rpp Horizontal
let lowerP = rpp ++ [SplitP BottomP]
let upperP = rpp ++ [SplitP TopP]
lower <- getNotebook lowerP
upper <- getNotebook upperP
notebookSetTabPos lower PositionTypeTop
notebookSetTabPos upper PositionTypeTop
notebookSetShowTabs upper False
getOrBuildDebugPanes upperP lowerP bufs
(Just rpp, False) -> do
let lowerP = getBestPanePath (rpp ++ [SplitP BottomP]) layout'
let upperP = getBestPanePath (rpp ++ [SplitP TopP]) layout'
getOrBuildDebugPanes upperP lowerP bufs
_ -> return ()
where
getOrBuildDebugPanes upperP lowerP bufs = do
moveOrBuildPane lowerP :: IDEM (Maybe IDEBreakpoints)
moveOrBuildPane lowerP :: IDEM (Maybe IDEVariables)
moveOrBuildPane lowerP :: IDEM (Maybe IDETrace)
moveOrBuildPane lowerP :: IDEM (Maybe IDEOutput)
unless (any (\ b -> bufferName b == "_Eval.hs") bufs) $
newTextBuffer upperP "_Eval.hs" Nothing >>= \case
Nothing -> return ()
Just pane -> viewMoveTo upperP pane
return ()
| JPMoresmau/leksah | src/IDE/PaneGroups.hs | gpl-2.0 | 5,580 | 0 | 19 | 1,381 | 1,520 | 776 | 744 | 117 | 4 |
#!/user/bin/env stack
-- stack --resolver lts-11.8 script --package process --package directory --package filepath --package mtl
--
-- Copyright (c) 2014-18 Nicola Bonelli <nicola@pfq.io>
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program 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 General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
--
{-# LANGUAGE OverloadedStrings #-}
import Development.SimpleBuilder
import System.Environment
import Control.Monad(when)
options = defaultOptions { stack = True }
script :: BuilderScript
script = do
-- PFQ kernel module
objective "pfq.ko" "kernel/" $ do
config $ empty
build $ make
install $ make_install `req` buildOf "pfq.ko"
clean $ make_clean
distclean $ make_clean
-- PFQ C library
objective "pfq-clib" "user/lib/C/" $ do
config $ cmake
build $ make `req` configOf "pfq-clib" `req` installOf "pfq.ko"
install $ make_install `req` buildOf "pfq-clib" >> ldconfig
clean $ make_clean `req` configOf "pfq-clib"
distclean $ cmake_distclean `req` cleanOf "pfq-clib"
-- PFQ C++ library
objective "pfq-cpplib" "user/lib/C++/pfq/" $ do
config $ empty
build $ empty
install $ make_install `req` installOf "pfq-clib" `req` installOf "pfq.ko"
clean $ empty
-- PFQ Haskell library
objective "pfq-haskell-lib" "user/lib/Haskell/" $ do
config $ cabalConfigure `req` installOf "pfq-clib"
build $ cabalBuild `req` installOf "pfq.ko" `req` configOf "pfq-haskell-lib"
install $ cabalInstall `req` buildOf "pfq-haskell-lib"
clean $ cabalClean
distclean $ cabalDistClean
-- PFQ pcap library 1.8.1
objective "pfq-pcap" "user/lib/libpcap-1.8.1-fanout/" $ do
config $ cmd "autoconf" `req` installOf "pfq-clib" >> configure
build $ make `req` installOf "pfq.ko" `req` configOf "pfq-pcap"
install $ empty `req` buildOf "pfq-pcap"
clean $ make_clean `req` configOf "pfq-pcap"
distclean $ make_distclean `req` cleanOf "pfq-pcap"
-- PFQ hcounters (exmaple)
objective "pfq-hcounters" "user/pfq-hcounters/" $ do
config $ cabalConfigure `req` installOf "pfq-haskell-lib"
build $ cabalBuild `req` configOf "pfq-hcounters"
install $ cabalInstall `req` buildOf "pfq-hcounters"
clean $ cabalClean
distclean $ cabalDistClean
-- pfq-lang compiler:
objective "pfq-lang" "user/pfq-lang/" $ do
config $ cabalConfigure `req` installOf "pfq-haskell-lib"
build $ cabalBuild `req` configOf "pfq-lang"
install $ cabalInstall `req` buildOf "pfq-lang"
clean $ cabalClean
distclean $ cabalDistClean
-- PFQ user tools
objective "pfq-affinity" "user/pfq-affinity/" $ do
config $ cabalConfigure `req` installOf "pfq-haskell-lib"
build $ cabalBuild `req` configOf "pfq-affinity"
install $ cabalInstall `req` buildOf "pfq-affinity"
clean $ cabalClean
distclean $ cabalDistClean
objective "pfq-omatic" "user/pfq-omatic/" $ do
config $ cabalConfigure `req` installOf "pfq-haskell-lib"
build $ cabalBuild `req` configOf "pfq-omatic"
install $ cabalInstall `req` buildOf "pfq-omatic"
clean $ cabalClean
distclean $ cabalDistClean
objective "pfq-load" "user/pfq-load/" $ do
config $ cabalConfigure
build $ cabalBuild `req` installOf "pfq-affinity" `req` configOf "pfq-load"
install $ cabalInstall `req` buildOf "pfq-load"
clean $ cabalClean
distclean $ cabalDistClean
objective "pfq-stress" "user/pfq-stress/" $ do
config $ cabalConfigure
build $ cabalBuild `reqs` [installOf "pfq-affinity", installOf "pfq-load", configOf "pfq-stress"]
install $ cabalInstall `req` buildOf "pfq-stress"
clean $ cabalClean
distclean $ cabalDistClean
objective "pfqd" "user/pfqd/" $ do
config $ cabalConfigure `req` installOf "pfq-haskell-lib"
build $ cabalBuild `req` installOf "pfq.ko" `req` configOf "pfqd"
install $ cabalInstall `req` buildOf "pfqd"
clean $ cabalClean
distclean $ cabalDistClean
objective "pfq-regression" "user/pfq-regression/C/" $ do
config $ cmake
build $ make `reqs` [installOf "pfq-clib", installOf "pfq-cpplib", configOf "pfq-regression"]
install $ empty `req` buildOf "pfq-regression"
clean $ make_clean `req` configOf "pfq-regression"
distclean $ cmake_distclean `req` cleanOf "pfq-regression"
-- PFQ htest (misc tests)
objective "h-regression" "user/pfq-regression/Haskell/" $ do
config $ cabalConfigure `req` installOf "pfq-haskell-lib"
build $ cabalBuild `req` configOf "h-regression"
install $ empty `req` buildOf "h-regression"
clean $ cabalClean
distclean $ cabalDistClean
objective "pfq-tools" "user/pfq-tools/" $ do
config $ cmake
build $ make `reqs` [installOf "pfq-clib", configOf "pfq-tools"]
install $ make_install `req` buildOf "pfq-tools"
clean $ make_clean `req` configOf "pfq-tools"
distclean $ cmake_distclean `req` cleanOf "pfq-tools"
main = simpleBuilder script options =<< getArgs
| pfq/PFQ | Build.hs | gpl-2.0 | 6,349 | 0 | 13 | 1,867 | 1,285 | 635 | 650 | 97 | 1 |
module GetExpression
{-
(getExpression)
-}
where
import Language.Haskell.TH
import Language.Haskell.Meta.Parse
import Data.Either
getExpression string = head $ rights [parseExp string]
getExpressionAndLine string = (makeGhciLine string,head $ rights [parseExp string])
makeGhciLine x = ghciLinePrompt ++ "putStr $ concat $ map hConcat ("++x++")"
makeGhciLine'' x = ghciLinePrompt ++ "putStr (concat . concat . map intersperse \"\\n\") ("++x++")"
makeGhciLine' x = ghciLinePrompt ++ "putStrLn ("++x++")"
makeGhciLine''' x = ghciLinePrompt ++ "putStr $ " ++ x
ghciLinePrompt = "Prelude Music.Instrument.Chord> "
{-
-
renderGuitarConcept
allowOpens
controlAnnotation
annotateFrets
firstTuningLast
orientationVertical
tuning
chord
maxHeight
from
utilizeAllStrings
rootNoteLowest
selectionMask
renderAllFrets
renderPressedFrets
utilizeAllNotes
strictIntervals
- -}
expressions = [
"renderGuitarConcept True AnnotatePositionVertical False True False standardTuning (minorChord C) 4 1 True False [] False False False False False"
,"renderGuitarConcept True AnnotatePositionVertical True True True standardTuning (minorChord C) 4 1 True False [] False False False False False"
,"renderGuitarConcept False AnnotateMarking False True True dropD (majorChord F) 4 0 True False [] False False False False False"
,"renderGuitarConcept False AnnotatePositionVertical False True True standardTuning (harmony (majorScale A)) 4 0 True False [] True True False False False"
,"concat . map hConcat $ renderGuitarConcept False AnnotatePositionVertical False True True standardTuning [majorChord D,majorChord A,minorChord B,majorChord G] 4 0 True False [] False False False False False"
,"renderGuitarConcept False AnnotateNote False True True standardTuning (majorScale F) 4 0 False False [] True False True True False"
,"renderGuitarConcept False AnnotateNote False True True standardTuning (shiftOctave 1 $ convertToSteps $ majorScale F) 4 0 False False [] True False True True False"
,"renderGuitarConcept False AnnotateNote False True True standardTuning (chordToScale (majorChord F)) 4 0 False False [] False False True True False"
,"renderGuitarConcept False AnnotatePositionHorizontal False False True (reverse standardTuning) (majorChord G) 4 0 True False [] False False False False False"
,"renderGuitarConcept False AnnotateNote False True True standardTuning (sus 4 $ dominant7thChord G) 4 3 False True [] False False True False False"
,"renderGuitarConcept False AnnotateNote False True True standardTuning (minorChord G) 4 1 False False lightChord False False False False False"
,"renderGuitarConcept False AnnotateNote False True True standardTuning (minor7thChord A) 4 2 False False lightChord False False True False False"
,"renderGuitarConcept False AnnotateMarking False True True standardTuning (slash C (majorChord D)) 4 0 False True [] False False False False False"
,"renderGuitarConcept False AnnotateMarking True True True standardTuning (fifthChord B) 4 0 False True powerChord True False False False False"
,"renderGuitarConcept False AnnotateNote False True True standardTuning (majorChord (flat A)) 4 0 False False [] False False False False False"
,"renderGuitarConcept False AnnotatePositionVertical False True True ukelele (majorChord C) 4 0 True False [] False False False False False"
,"renderGuitarConcept False AnnotateNote False True True standardTuning (minorPentatonicScale A) 4 5 True False [] False False False False False"
,"renderGuitarConcept False AnnotateNote True True True standardTuning E 13 0 True False [] False False False False False"
,"renderPianoConcept 0 AnnotateMarking (majorChord C)"
,"renderPianoConcept 1 AnnotateNote (majorScale A)"
,"map head $ findPositionPatterns True (majorChord C) standardTuning 4 True False [] False False"
]
| xpika/chord | GetExpression.hs | gpl-3.0 | 3,825 | 0 | 9 | 541 | 224 | 128 | 96 | 33 | 1 |
{-# LANGUAGE Trustworthy #-}
-----------------------------------------------------------------------------
-- |
-- Module : System.Exit
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- Exiting the program.
--
-----------------------------------------------------------------------------
module System.Exit
(
ExitCode(ExitSuccess,ExitFailure)
, exitWith
, exitFailure
, exitSuccess
) where
import Prelude
import GHC.IO
import GHC.IO.Exception
-- ---------------------------------------------------------------------------
-- exitWith
-- | Computation 'exitWith' @code@ throws 'ExitCode' @code@.
-- Normally this terminates the program, returning @code@ to the
-- program's caller.
--
-- On program termination, the standard 'Handle's 'stdout' and
-- 'stderr' are flushed automatically; any other buffered 'Handle's
-- need to be flushed manually, otherwise the buffered data will be
-- discarded.
--
-- A program that fails in any other way is treated as if it had
-- called 'exitFailure'.
-- A program that terminates successfully without calling 'exitWith'
-- explicitly is treated as it it had called 'exitWith' 'ExitSuccess'.
--
-- As an 'ExitCode' is not an 'IOError', 'exitWith' bypasses
-- the error handling in the 'IO' monad and cannot be intercepted by
-- 'catch' from the "Prelude". However it is a 'SomeException', and can
-- be caught using the functions of "Control.Exception". This means
-- that cleanup computations added with 'Control.Exception.bracket'
-- (from "Control.Exception") are also executed properly on 'exitWith'.
--
-- Note: in GHC, 'exitWith' should be called from the main program
-- thread in order to exit the process. When called from another
-- thread, 'exitWith' will throw an 'ExitException' as normal, but the
-- exception will not cause the process itself to exit.
--
exitWith :: ExitCode -> IO a
exitWith ExitSuccess = throwIO ExitSuccess
exitWith code@(ExitFailure n)
| n /= 0 = throwIO code
| otherwise = ioError (IOError Nothing InvalidArgument "exitWith" "ExitFailure 0" Nothing Nothing)
-- | The computation 'exitFailure' is equivalent to
-- 'exitWith' @(@'ExitFailure' /exitfail/@)@,
-- where /exitfail/ is implementation-dependent.
exitFailure :: IO a
exitFailure = exitWith (ExitFailure 1)
-- | The computation 'exitSuccess' is equivalent to
-- 'exitWith' 'ExitSuccess', It terminates the program
-- successfully.
exitSuccess :: IO a
exitSuccess = exitWith ExitSuccess
| jwiegley/ghc-release | libraries/base/System/Exit.hs | gpl-3.0 | 2,640 | 0 | 8 | 417 | 207 | 132 | 75 | 22 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Types.LocalConfig where
import Types.Base
import Prelude hiding(FilePath)
data LocalConfig = LocalConfig
{ saveFile :: Maybe FilePath
, verbose :: Maybe Bool
} deriving(Show)
| diegospd/pol | app/Types/LocalConfig.hs | gpl-3.0 | 227 | 0 | 9 | 38 | 55 | 33 | 22 | 8 | 0 |
module LambdaLine.Shells.Base
( appendSpace
, mkSegment
, plain
, prependSpace
, stringToSegment
, stylePrompt
) where
import LambdaLine.Segment
appendSpace :: String -> String
appendSpace = stylePrompt (++ " ")
plain :: String -> String
plain = id
prependSpace :: String -> String
prependSpace = stylePrompt (' ':)
stylePrompt :: (String -> String) -> String -> String
stylePrompt f prompt = if null prompt
then prompt
else f prompt
| josiah14/lambdaline | LambdaLine/Shells/Base.hs | gpl-3.0 | 485 | 0 | 7 | 119 | 132 | 76 | 56 | 18 | 2 |
{-# LANGUAGE NoMonomorphismRestriction #-}
import Graphics.X11.Xlib
import Graphics.X11.Xlib.Extras
actions dpy win gc = do
drawInWin 12 dpy win gc
liveMain = do
putStrLn ""
return actions
drawInWin x dpy win gc = do
bgcolor <- initColor dpy "green"
fgcolor <- initColor dpy "blue"
setForeground dpy gc bgcolor
fillRectangle dpy win gc 0 0 200 200
setForeground dpy gc fgcolor
let q = 96 * 1
fillRectangle dpy win gc ((2+fromIntegral x)) 2 (round $ q) (round q)
initColor :: Display -> String -> IO Pixel
initColor dpy color = do
let colormap = defaultColormap dpy (defaultScreen dpy)
(apros,real) <- allocNamedColor dpy colormap color
return $ color_pixel apros
| xpika/live-source | examples/live-x11/liveX11Source.hs | gpl-3.0 | 688 | 0 | 12 | 132 | 265 | 125 | 140 | 21 | 1 |
-- Copyright 2014 Joris Rehm
--
-- 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 Parsing(runBParser) where
import Control.Applicative((<*),(*>))
import Data.Functor.Identity
import Text.Parsec
import Text.Parsec.String
import Text.Parsec.Token
import Text.Parsec.Expr
import Data.List(nub, isPrefixOf)
import BTree
def = LanguageDef
{ commentStart = "/*"
, commentEnd = "*/"
, commentLine = "//"
, nestedComments = False
, identStart = letter
, identLetter = alphaNum <|> char '_' <|> char '.'
--TODO restrict use of . in indentLetter
, caseSensitive = True
, opStart = oneOf $ nub $ map head allOp
, opLetter = oneOf $ nub $ concat $ map tail $ allOp
, reservedOpNames = allOp
, reservedNames = allKw
}
TokenParser
{ parens = m_parens
, identifier = m_identifier
, reserved = m_reserved
--, reservedOp = m_reservedOp
, natural = m_natural
, whiteSpace = m_whiteSpace
, lexeme = m_lexeme
} = makeTokenParser def
-- I do not use the vanilla Parsec reservedOp because there
-- are too many operators that are prefix of other operators.
-- instead my m_reservedOp only accept operators from the
-- list allOp.
m_reservedOp name =
m_lexeme $ try $
do{ string name
; notFollowedBy (possibleLongerOpe name) <?> ("end of " ++ show name)
}
-- This thing is probably not very fast.
-- I think it should be possible to do some pre-computation.
-- like a map from the name to the suffixes list
possibleLongerOpe name = choice (map (try.string) suffixes)
where
suffixes = filter (""/=) $ map (drop (length name)) (filter (name `isPrefixOf`) allOp)
----------------------------------------------------------------
-- I need a particular state to resolve some ambiguities of the
-- B language:
-- * I use acceptCommaPair to discriminate between the comma used
-- in the list of expressions and the comma used in the pairs.
-- The rule I use is: the pair inside a expression list must
-- be surrounded by parenthesis.
-- * Same idea for the ";" and "||" used to separate sequence of
-- substution (and also separate operations for ";") and to combine
-- relations in expressions (see acceptRelOpe).
-- The rule: the relation expression operators ";" and "||" must
-- appears inside a parenthesis "()", bracket "{}" or square bracket "[]".
type ParsingType = Parsec String ParsingState
data ParsingState = ParsingState
{ acceptCommaPair :: Bool
, acceptRelOpe :: Bool
} deriving (Show)
startParsingState = ParsingState
{ acceptCommaPair = True
, acceptRelOpe = False
}
runBParser :: SourceName -> String -> Either ParseError BComponent
runBParser = runParser readBFile startParsingState
----------------------------------------------------------------
readBFile = m_whiteSpace >> readComponent <* eof
readIdent = do
ident <- m_identifier
return $ BIdent ident
readIdentList =
readIdent `sepBy1` m_reservedOp ","
readComponent :: ParsingType BComponent
readComponent = do
componentType <- m_reserved "MACHINE" *> return BMachine <|>
m_reserved "REFINEMENT" *> return BRefinement <|>
m_reserved "IMPLEMENTATION" *> return BImplementation
name <- readIdent
clauses <- readClauses
m_reserved "END"
return $ BComponent componentType name clauses
-- TODO use Text.Parsec.Perm instead of many
readClauses = many $
readRefines <|>
readImports <|>
readSees <|>
readConcreteConstants <|>
readAbstractConstants <|>
readConcreteVariables <|>
readAbstractVariables <|>
readPromotes <|>
readSets <|>
readProperties <|>
readInvariant <|>
readAssertions <|>
readValues <|>
readInitialisation <|>
readOperations <|>
readLocalOperations
readRefines = do
m_reserved "REFINES"
name <- readIdent
return $ BRefines name
readImports = do
m_reserved "IMPORTS"
names <- readIdentList
return $ BImports names
readSees = do
m_reserved "SEES"
names <- readIdentList
return $ BSees names
readConcreteConstants = do
m_reserved "CONSTANTS" <|> m_reserved "CONCRETE_CONSTANTS"
names <- readIdentList
return $ BConcreteConstants names
readAbstractConstants = do
m_reserved "ABSTRACT_CONSTANTS"
names <- readIdentList
return $ BAbstractConstants names
readConcreteVariables = do
m_reserved "CONCRETE_VARIABLES"
names <- readIdentList
return $ BConcreteVariables names
readAbstractVariables = do
m_reserved "VARIABLES" <|> m_reserved "ABSTRACT_VARIABLES"
names <- readIdentList
return $ BAbstractVariables names
readPromotes = do
m_reserved "PROMOTES"
names <- readIdentList
return $ BPromotes names
readProperties = do
m_reserved "PROPERTIES"
p <- readPredicate
return $ BProperties p
readInvariant = do
m_reserved "INVARIANT"
p <- readPredicate
return $ BInvariant p
readAssertions = do
m_reserved "ASSERTIONS"
ps <- readPredicateList
return $ BAssertions ps
readValues = do
m_reserved "VALUES"
ps <- readPredicateList
return $ BValues ps
readInitialisation = do
m_reserved "INITIALISATION"
sub <- readSub
return $ BInitialisation sub
readOperations = do
m_reserved "OPERATIONS"
ops <- readOperationList
return $ BOperations ops
readLocalOperations = do
m_reserved "LOCAL_OPERATIONS"
ops <- readOperationList
return $ BLocalOperations ops
readSets = do
m_reserved "SETS"
decls <- readSetsDecl
return $ BSetClause decls
where
readSetsDecl = (try enumerated <|> carrier) `sepBy1` m_reservedOp ";"
carrier = do
name <- readIdent
return $ BCarrierSet name
enumerated = do
name <- readIdent
m_reservedOp "="
m_reservedOp "{"
names <- readIdentList
m_reservedOp "}"
return $ BEnumeratedSet name names
readOperationList =
readOperation `sepBy1` (m_reservedOp ";")
readOperation = do
outputs <- option [] (try readOutputs)
name <- readIdent
inputs <- option [] readInputs
m_reservedOp "="
sub <- readFirstSub
return $ BOperation outputs name inputs sub
where
readOutputs = do
xs <- readIdentList
m_reservedOp "<--"
return xs
readInputs = do
xs <- m_parens readIdentList
return xs
----------------------------------------------------------------
-- This is all the substitutions but ";".
-- It's needed as the body of an operation because of the
-- ambiguity of the ";" (";" is used to separate both operation and
-- instruction).
-- TODO check if the AtelierbB parser accept somethink like
-- "MACHINE xx OPERATIONS op= x:=2 ; x:=3 END"
-- --> no, it don't
readFirstSub =
readBlockishSub `chainl1` (
m_reservedOp "||" *> return (BSubstitutionCompo BOpSubParal) )
readSub =
readBlockishSub `chainl1` (
m_reservedOp ";" *> return (BSubstitutionCompo BOpSubSeq)
<|> m_reservedOp "||" *> return (BSubstitutionCompo BOpSubParal) )
-- TODO this name is inacurate
readBlockishSub =
readSubSkip <|>
readSubBlock <|>
readSubPre <|>
readSubAssert <|>
readSubChoice <|>
readSubIf <|>
readSubSelect <|>
readSubCase <|>
readSubAnyOrLet <|>
readSubVar <|>
readSubWhile <|>
try readSubSimple <|>
try readSubBecomeIn <|>
try readSubBecomeSuchThat <|>
try readSubOpeCall
-- TODO those 4 "try" give bad error reporting: should factorize?
readSubSkip = do
m_reserved "skip"
return BSubstitutionSkip
readSubBlock = do
m_reserved "BEGIN"
sub <- readSub
m_reserved "END"
return $ BSubstitutionBlock sub
readSubPre = do
m_reserved "PRE"
p <- readPredicate
m_reserved "THEN"
sub <- readSub
m_reserved "END"
return $ BSubstitutionPreCondition p sub
readSubAssert = do
m_reserved "ASSERT"
p <- readPredicate
m_reserved "THEN"
sub <- readSub
m_reserved "END"
return $ BSubstitutionAssert p sub
readSubChoice = do
m_reserved "CHOICE"
subs <- readSub `sepBy1` (m_reserved "OR")
m_reserved "END"
return $ BSubstitutionChoice subs
readSubCond kind kwIf kwElsif = do
m_reserved kwIf
p <- readPredicate
m_reserved "THEN"
sub <- readSub
elsif <- many readElseIf
els <- option Nothing readElse
m_reserved "END"
return $ BSubstitutionCond kind ((p,sub):elsif) els
where
readElse = do
m_reserved "ELSE"
sub <- readSub
return $ Just sub
readElseIf = do
m_reserved kwElsif
p <- readPredicate
m_reserved "THEN"
sub <- readSub
return (p,sub)
readSubIf = readSubCond BIf "IF" "ELSIF"
readSubSelect = readSubCond BSelect "SELECT" "WHEN"
readSubCase = do
m_reserved "CASE"
var <- readExpr
m_reserved "OF"
m_reserved "EITHER"
e <- readExpr
m_reserved "THEN"
sub <- readSub
orThen <- many readOrThen
els <- option Nothing readElse
m_reserved "END"
m_reserved "END"
return $ BSubstitutionCase var ((e,sub):orThen) els
where
readElse = do
m_reserved "ELSE"
sub <- readSub
return $ Just sub
readOrThen = do
m_reserved "OR"
e <- readExpr
m_reserved "THEN"
sub <- readSub
return (e,sub)
readSubAnyOrLet = do
(kind,kw,kw') <- m_reserved "ANY" *> return (BAny, "WHERE", "THEN") <|>
m_reserved "LET" *> return (BLet, "BE", "IN")
vars <- readIdentList
m_reserved kw
p <- readPredicate
m_reserved kw'
sub <- readSub
m_reserved "END"
return $ BSubstitutionSpecVar kind vars p sub
readSubVar = do
m_reserved "VAR"
vars <- readIdentList
m_reserved "IN"
sub <- readSub
m_reserved "END"
return $ BSubstitutionVar vars sub
readSubWhile = do
m_reserved "WHILE"
p <- readPredicate
m_reserved "DO"
sub <- readSub
m_reserved "INVARIANT"
inv <- readPredicate
m_reserved "VARIANT"
var <- readExpr
m_reserved "END"
return $ BSubstitutionWhile p sub inv var
readSubSimple = do
vars <- readIdentList
m_reservedOp ":="
exprs <- readExprList
return $ BSubstitutionSimple vars exprs
readSubBecomeIn = do
vars <- readIdentList
m_reservedOp "::"
exprs <- readExpr
return $ BSubstitutionBecomeIn vars exprs
readSubBecomeSuchThat = do
vars <- readIdentList
m_reservedOp ":("
p <- readPredicate
m_reservedOp ")"
return $ BSubstitutionSuchThat vars p
readSubOpeCall = do
outs <- option [] (try (readIdentList <* m_reservedOp "<--"))
name <- readIdent
ins <- option [] (m_parens readExprList)
return $ BSubstitutionOpeCall outs name ins
----------------------------------------------------------------
readIdentListProtected =
do { i <- readIdent; return [i] } <|>
m_parens (readIdent `sepBy` m_reservedOp ",")
readPredicateList =
readPredicate `sepBy1` m_reservedOp ";"
readPredicate =
buildExpressionParser predTable readPredTerm <?> "predicate"
readQuantPred = do
kind <- m_reservedOp "!" *> return BUniversal <|>
m_reservedOp "#" *> return BExistential
vars <- readIdentListProtected
m_reservedOp "."
p <- m_parens readPredicate
return $ BQuantifiedPredicate kind vars p
-- allow repeating of unary operator
-- copied from http://stackoverflow.com/questions/10475337
-- "Parsec.Expr repeated Prefix/Postfix operator not supported"
prefix p = Prefix . chainl1 p $ return (.)
postfix p = Postfix . chainl1 p $ return (flip (.))
predTable =
[
-- ??
[prefix (m_reserved "not" >> (return $ BNegation))]
-- 60
, [Infix (m_reservedOp "<=>" >> (return $ BBinaryPredicate BEquivalence) ) AssocLeft]
-- 40
, [Infix (m_reservedOp "&" >> (return $ BBinaryPredicate BConjunction) ) AssocLeft
,Infix (m_reserved "or" >> (return $ BBinaryPredicate BDisjunction) ) AssocLeft]
-- 30
, [Infix (m_reservedOp "=>" >> (return $ BBinaryPredicate BImplication) ) AssocLeft]
]
readPredTerm =
try readParenPred <|>
readQuantPred <|>
readComp
readParenPred = do
p <- m_parens readPredicate
return $ BParenExpression p
readComp = do
left <- readExpr
kind <- readOpe
right <- readExpr
return $ BComparisonPredicate kind left right
where
readOpe =
m_reservedOp "=" *> return BEquality <|>
m_reservedOp "/=" *> return BNonEquality <|>
m_reservedOp ":" *> return BMembership <|>
m_reservedOp "/:" *> return BNonMembership <|>
m_reservedOp "<:" *> return BInclusion <|>
m_reservedOp "<<:" *> return BStrictInclusion <|>
m_reservedOp "/<:" *> return BNonInclusion <|>
m_reservedOp "/<<:" *> return BNonStrictInclusion <|>
m_reservedOp "<=" *> return BInequality <|>
m_reservedOp "<" *> return BStrictInequality <|>
m_reservedOp ">=" *> return BReverseInequality <|>
m_reservedOp ">" *> return BStrictReverseInequality
----------------------------------------------------------------
readExprList = do
s <- getState
let previous = acceptCommaPair s
updateState $ \s -> s { acceptCommaPair = False }
es <- readExpr `sepBy1` m_reservedOp ","
updateState $ \s -> s { acceptCommaPair = previous }
return es
-- TODO explain this
chainl1WithTail p rec op = do { x <- p; rest x }
where
rest x = do { (f,q) <- op
; y <- rec
; res <- rest (f x y)
; q
; return res
}
<|> return x
opApply = do
s <- getState
let prevComma = acceptCommaPair s
let prevRelProd = acceptRelOpe s
(kind,tailOp) <- m_reservedOp "(" *> return (BApplication, tailParen ")" prevComma prevRelProd) <|>
m_reservedOp "[" *> return (BImage, tailParen "]" prevComma prevRelProd)
updateState $ \s -> s { acceptCommaPair = True, acceptRelOpe = True }
return (BApply kind, tailOp)
where
tailParen op prevC prevRP = do
m_reservedOp op
updateState $ \s -> s { acceptCommaPair = prevC, acceptRelOpe = prevRP }
readExpr = buildExpressionParser exprTable termAndCall <?> "expression"
where termAndCall = chainl1WithTail exprTerm readExpr opApply
exprTable =
[
-- ???:
[prefix (m_reservedOp "-" *> return (BUnaryExpression BOpposite))
,postfix (m_reservedOp "~" *> return (BUnaryExpression BInverse))]
-- 200:
, [Infix (m_reservedOp "**" *> return (BBinaryExpression BPower)) AssocRight]
-- 190:
, [Infix (m_reservedOp "*" *> return (BBinaryExpression BAsterisk)) AssocLeft
,Infix (m_reservedOp "/" *> return (BBinaryExpression BDivision)) AssocLeft
,Infix (m_reserved "mod" *> return (BBinaryExpression BModulo)) AssocLeft]
-- 180:
, [Infix (m_reservedOp "+" *> return (BBinaryExpression BAddition)) AssocLeft
,Infix (m_reservedOp "-" *> return (BBinaryExpression BSubstration)) AssocLeft]
-- 170:
, [Infix (m_reservedOp ".." *> return (BBinaryExpression BInterval)) AssocLeft]
-- 160:
, [Infix (m_reservedOp "|->" *> return (BBinaryExpression BMapsToPair)) AssocLeft
,Infix (m_reservedOp "\\/" *> return (BBinaryExpression BUnion)) AssocLeft
,Infix (m_reservedOp "/\\" *> return (BBinaryExpression BIntersection)) AssocLeft
,Infix (m_reservedOp "><" *> return (BBinaryExpression BDirectProduct)) AssocLeft
,Infix (m_reservedOp "<|" *> return (BBinaryExpression BDomainRestriction)) AssocLeft
,Infix (m_reservedOp "<<|" *> return (BBinaryExpression BDomainSubstraction)) AssocLeft
,Infix (m_reservedOp "|>" *> return (BBinaryExpression BRangeRestriction)) AssocLeft
,Infix (m_reservedOp "|>>" *> return (BBinaryExpression BRangeSubstraction)) AssocLeft
,Infix (m_reservedOp "<+" *> return (BBinaryExpression BOverloading)) AssocLeft
,Infix (m_reservedOp "^" *> return (BBinaryExpression BConcatenation)) AssocLeft
,Infix (m_reservedOp "->" *> return (BBinaryExpression BHeadInsertion)) AssocLeft
,Infix (m_reservedOp "<-" *> return (BBinaryExpression BTailInsertion)) AssocLeft
,Infix (m_reservedOp "/|\\" *> return (BBinaryExpression BHeadRestriction)) AssocLeft
,Infix (m_reservedOp "\\|/" *> return (BBinaryExpression BTailRestriction)) AssocLeft]
-- 125:
, [Infix (m_reservedOp "<->" *> return (BBinaryExpression BRelation)) AssocLeft
,Infix (m_reservedOp "+->" *> return (BBinaryExpression BPartialFunction)) AssocLeft
,Infix (m_reservedOp "-->" *> return (BBinaryExpression BTotalFunction)) AssocLeft
,Infix (m_reservedOp ">+>" *> return (BBinaryExpression BPartialInjection)) AssocLeft
,Infix (m_reservedOp ">->" *> return (BBinaryExpression BTotalInjection)) AssocLeft
,Infix (m_reservedOp "+->>" *> return (BBinaryExpression BPartialSurjection)) AssocLeft
,Infix (m_reservedOp "-->>" *> return (BBinaryExpression BTotalSurjection)) AssocLeft
,Infix (m_reservedOp ">->>" *> return (BBinaryExpression BTotalBijection)) AssocLeft]
-- 115:
, [Infix readCommaPair AssocLeft]
-- 20:
, [Infix readRelationComposition AssocLeft
,Infix readRelationDirectProduct AssocLeft
]
] where
readCommaPair = do
s <- getState
if acceptCommaPair s
then do
m_reservedOp "," *> return (BBinaryExpression BCommaPair)
else do
-- this message will never be seen (normally) because all failures
-- will be backtracked by a Parsec "try" combinator somewhere
parserFail "Pairs with comma are forbidden here."
readRelationComposition = do
s <- getState
if acceptRelOpe s
then do
m_reservedOp ";" *> return (BBinaryExpression BComposition)
else do
parserFail "Relation composition is forbidden here."
readRelationDirectProduct = do
s <- getState
if acceptRelOpe s
then do
m_reservedOp "||" *> return (BBinaryExpression BParallelProduct)
else do
parserFail "Relation direct product is forbidden here."
exprTerm =
readValueIdent <|>
readParenExpr <|>
readNumber <|>
readBoolConv <|>
readQuantExpr <|>
readSetExpr <|>
readListExpr
where
readParenExpr = do
s <- getState
let prevComma = acceptCommaPair s
let prevRelProd = acceptRelOpe s
updateState $ \s -> s { acceptCommaPair = True, acceptRelOpe = True }
e <- m_parens readExpr
updateState $ \s -> s { acceptCommaPair = prevComma, acceptRelOpe = prevRelProd}
return $ BParenExpression e
readValueIdent = do
x <- readIdent
suffix <- option BCurrent (m_reservedOp "$0" *> return BPrevious)
return $ BIdentifier x suffix
readNumber = do
n <- m_natural
return $ BNumber n
readBoolConv = do
m_reserved "bool"
s <- getState
let prevComma = acceptCommaPair s
updateState $ \s -> s { acceptCommaPair = True }
m_reservedOp "("
p <- readPredicate
m_reservedOp ")"
updateState $ \s -> s { acceptCommaPair = prevComma }
return $ BBoolConversion p
readQuantExpr = do
kind <- m_reserved "SIGMA" *> return BSum <|>
m_reserved "PI" *> return BProduct <|>
m_reserved "UNION" *> return BQuantifiedUnion <|>
m_reserved "INTER" *> return BQuantifiedIntersection <|>
m_reservedOp "%" *> return BLambdaExpression
xs <- readIdentListProtected
m_reservedOp "."
s <- getState
let previous = acceptCommaPair s
updateState $ \s -> s { acceptCommaPair = True }
m_reservedOp "("
p <- readPredicate
m_reservedOp "|"
e <- readExpr
m_reservedOp ")"
updateState $ \s -> s { acceptCommaPair = previous }
return $ BQuantifiedExpression kind xs p e
readSetExpr =
try readSetExprCompr <|>
readSetExprExtens
readSetExprCompr = do
m_reservedOp "{"
xs <- readIdentList
m_reservedOp "|"
s <- getState
let prevRelProd = acceptRelOpe s
let prevComma = acceptCommaPair s
updateState $ \s -> s { acceptRelOpe = True, acceptCommaPair = True }
p <- readPredicate
updateState $ \s -> s { acceptRelOpe = prevRelProd, acceptCommaPair = prevComma }
m_reservedOp "}"
return $ BSetComprehension xs p
readSetExprExtens = do
m_reservedOp "{"
s <- getState
let prevRelProd = acceptRelOpe s
updateState $ \s -> s { acceptRelOpe = True }
es <- readExprList
updateState $ \s -> s { acceptRelOpe = prevRelProd }
m_reservedOp "}"
return $ BSetExtension es
readListExpr = do
m_reservedOp "["
xs <- readExprList
m_reservedOp "]"
return $ BSequenceExtension xs --TODO factorize BTree with BSetExtension
----------------------------------------------------------------
allKw = nub $ kwClauses ++ kwSubst ++ kwPred ++ kwExpr
allOp = nub $ opVarious ++ opSubst ++ opPred ++ opComp ++ opExpr
kwClauses =
[ "MACHINE"
, "REFINEMENT"
, "IMPLEMENTATION"
, "REFINES"
, "SEES"
, "IMPORTS"
, "PROMOTES"
, "USES" -- TODO clause
, "EXTENDS" -- TODO clause
, "INCLUDES" -- TODO clause
, "CONSTRAINTS" -- TODO clause
, "SETS"
, "CONSTANTS"
, "ABSTRACT_CONSTANTS"
, "CONCRETE_CONSTANTS"
, "PROPERTIES"
, "VALUES"
, "VARIABLES"
, "ABSTRACT_VARIABLES"
, "CONCRETE_VARIABLES"
, "INVARIANT"
, "ASSERTIONS"
, "INITIALISATION"
, "OPERATIONS"
, "LOCAL_OPERATIONS"
]
opVarious =
[ "$0"
, "="
, ","
, "("
, ")"
, ";"
, "||"
, "*"
, "-"
]
kwSubst =
[ "skip"
, "BEGIN"
, "END"
, "IF"
, "THEN"
, "ELSE"
, "ELSIF"
, "PRE"
, "ASSERT"
, "WHEN"
, "WHERE"
, "SELECT"
, "CASE"
, "OF"
, "EITHER"
, "VAR"
, "ANY"
, "CHOICE"
, "OR"
, "LET"
, "BE"
, "IN"
, "WHILE"
, "DO"
, "VARIANT"
]
opSubst =
[ "<--"
, "::"
, ":="
, ":(" -- TODO split this lexem in two (as AtelierB)
]
kwPred =
[ "not"
, "or"
]
opPred =
[ "&"
, "!"
, "#"
, "=>"
, "<=>"
]
opComp =
[ "/="
, ":"
, "/:"
, "<:"
, "/<:"
, "<<:"
, "/<<:"
, "<"
, "<="
, ">"
, ">="
]
kwExpr =
[ "bool"
, "mod"
, "SIGMA"
, "PI"
, "UNION"
, "INTER"
, "struct"
, "rec"
]
opExpr =
[ "+"
, "/"
, "**"
, "|->"
, "{"
, "}"
, "|"
, ".."
, "\\/"
, "/\\"
, "<->"
, "~"
, "><"
, "["
, "]"
, "<|"
, "<<|"
, "|>"
, "|>>"
, "<+"
, "+->"
, "-->"
, ">+>"
, ">->"
, "+->>"
, "-->>"
, ">+>>"
, ">->>"
, "%"
, "{}"
, "[]"
, "^"
, "->"
, "<-"
, "/|\\"
, "\\|/"
, "'"
]
| joris-r/labaskel | Parsing.hs | apache-2.0 | 22,770 | 0 | 30 | 5,287 | 5,882 | 2,907 | 2,975 | 660 | 4 |
{-| Ganeti monitoring agent daemon
-}
{-
Copyright (C) 2013 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Main (main) where
import qualified Ganeti.Monitoring.Server
import Ganeti.Daemon
import Ganeti.Runtime
import qualified Ganeti.Constants as C
-- | Options list and functions.
options :: [OptType]
options =
[ oNoDaemonize
, oNoUserChecks
, oDebug
, oPort C.defaultMondPort
]
-- | Main function.
main :: IO ()
main =
genericMain GanetiMond options
Ganeti.Monitoring.Server.checkMain
Ganeti.Monitoring.Server.prepMain
Ganeti.Monitoring.Server.main
| apyrgio/snf-ganeti | src/ganeti-mond.hs | bsd-2-clause | 1,817 | 0 | 7 | 290 | 106 | 67 | 39 | 17 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Application
( makeApplication
, getApplicationDev
, makeFoundation
) where
import Import
import Settings
import Yesod.Default.Config
import Yesod.Default.Main
import Yesod.Default.Handlers
import Yesod.Logger (Logger, logBS, toProduction)
import Network.Wai.Middleware.RequestLogger (logCallback, logCallbackDev)
import qualified Database.Persist.Store
import Database.Persist.GenericSql (runMigration)
import Network.HTTP.Conduit (newManager, def)
-- Import all relevant handler modules here.
-- Don't forget to add new modules to your cabal file!
import Handler.Home
import Handler.Update
-- This line actually creates our YesodSite instance. It is the second half
-- of the call to mkYesodData which occurs in Foundation.hs. Please see
-- the comments there for more details.
mkYesodDispatch "App" resourcesApp
-- This function allocates resources (such as a database connection pool),
-- performs initialization and creates a WAI application. This is also the
-- place to put your migrate statements to have automatic database
-- migrations handled by Yesod.
makeApplication :: AppConfig DefaultEnv Extra -> Logger -> IO Application
makeApplication conf logger = do
foundation <- makeFoundation conf setLogger
app <- toWaiAppPlain foundation
return $ logWare app
where
setLogger = if development then logger else toProduction logger
logWare = if development then logCallbackDev (logBS setLogger)
else logCallback (logBS setLogger)
makeFoundation :: AppConfig DefaultEnv Extra -> Logger -> IO App
makeFoundation conf setLogger = do
manager <- newManager def
s <- staticSite
dbconf <- withYamlEnvironment "config/sqlite.yml" (appEnv conf)
Database.Persist.Store.loadConfig >>=
Database.Persist.Store.applyEnv
p <- Database.Persist.Store.createPoolConfig (dbconf :: Settings.PersistConfig)
Database.Persist.Store.runPool dbconf (runMigration migrateAll) p
return $ App conf setLogger s p manager dbconf
-- for yesod devel
getApplicationDev :: IO (Int, Application)
getApplicationDev =
defaultDevelApp loader makeApplication
where
loader = loadConfig (configSettings Development)
{ csParseExtra = parseExtra
}
| erochest/NeatlineUpdate | Application.hs | bsd-2-clause | 2,313 | 0 | 11 | 423 | 433 | 237 | 196 | -1 | -1 |
{-# LANGUAGE TemplateHaskell, CPP, ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-| Unittests for ganeti-htools.
-}
{-
Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Test.Ganeti.Utils (testUtils) where
import Test.QuickCheck hiding (Result)
import Test.HUnit
import Data.Char (isSpace)
import qualified Data.Either as Either
import Data.List
import Data.Maybe (listToMaybe)
import qualified Data.Set as S
import System.Time
import qualified Text.JSON as J
#ifdef VERSION_regex_pcre
import Text.Regex.PCRE
#endif
import Test.Ganeti.TestHelper
import Test.Ganeti.TestCommon
import Ganeti.BasicTypes
import qualified Ganeti.Constants as C
import qualified Ganeti.JSON as JSON
import Ganeti.Utils
{-# ANN module "HLint: ignore Use camelCase" #-}
-- | Helper to generate a small string that doesn't contain commas.
genNonCommaString :: Gen String
genNonCommaString = do
size <- choose (0, 20) -- arbitrary max size
vectorOf size (arbitrary `suchThat` (/=) ',')
-- | If the list is not just an empty element, and if the elements do
-- not contain commas, then join+split should be idempotent.
prop_commaJoinSplit :: Property
prop_commaJoinSplit =
forAll (choose (0, 20)) $ \llen ->
forAll (vectorOf llen genNonCommaString `suchThat` (/=) [""]) $ \lst ->
sepSplit ',' (commaJoin lst) ==? lst
-- | Split and join should always be idempotent.
prop_commaSplitJoin :: String -> Property
prop_commaSplitJoin s =
commaJoin (sepSplit ',' s) ==? s
-- | Test 'findFirst' on several possible inputs.
prop_findFirst :: Property
prop_findFirst =
forAll (genSublist [0..5 :: Int]) $ \xs ->
forAll (choose (-2, 7)) $ \base ->
counterexample "findFirst utility function" $
let r = findFirst base (S.fromList xs)
(ss, es) = partition (< r) $ dropWhile (< base) xs
-- the prefix must be a range of numbers
-- and the suffix must not start with 'r'
in conjoin [ and $ zipWith ((==) . (+ 1)) ss (drop 1 ss)
, maybe True (> r) (listToMaybe es)
]
-- | fromObjWithDefault, we test using the Maybe monad and an integer
-- value.
prop_fromObjWithDefault :: Integer -> String -> Bool
prop_fromObjWithDefault def_value random_key =
-- a missing key will be returned with the default
JSON.fromObjWithDefault [] random_key def_value == Just def_value &&
-- a found key will be returned as is, not with default
JSON.fromObjWithDefault [(random_key, J.showJSON def_value)]
random_key (def_value+1) == Just def_value
-- | Test that functional if' behaves like the syntactic sugar if.
prop_if'if :: Bool -> Int -> Int -> Property
prop_if'if cnd a b =
if' cnd a b ==? if cnd then a else b
-- | Test basic select functionality
prop_select :: Int -- ^ Default result
-> [Int] -- ^ List of False values
-> [Int] -- ^ List of True values
-> Property -- ^ Test result
prop_select def lst1 lst2 =
select def (flist ++ tlist) ==? expectedresult
where expectedresult = defaultHead def lst2
flist = zip (repeat False) lst1
tlist = zip (repeat True) lst2
{-# ANN prop_select_undefd "HLint: ignore Use alternative" #-}
-- | Test basic select functionality with undefined default
prop_select_undefd :: [Int] -- ^ List of False values
-> NonEmptyList Int -- ^ List of True values
-> Property -- ^ Test result
prop_select_undefd lst1 (NonEmpty lst2) =
-- head is fine as NonEmpty "guarantees" a non-empty list, but not
-- via types
select undefined (flist ++ tlist) ==? head lst2
where flist = zip (repeat False) lst1
tlist = zip (repeat True) lst2
{-# ANN prop_select_undefv "HLint: ignore Use alternative" #-}
-- | Test basic select functionality with undefined list values
prop_select_undefv :: [Int] -- ^ List of False values
-> NonEmptyList Int -- ^ List of True values
-> Property -- ^ Test result
prop_select_undefv lst1 (NonEmpty lst2) =
-- head is fine as NonEmpty "guarantees" a non-empty list, but not
-- via types
select undefined cndlist ==? head lst2
where flist = zip (repeat False) lst1
tlist = zip (repeat True) lst2
cndlist = flist ++ tlist ++ [undefined]
prop_parseUnit :: NonNegative Int -> Property
prop_parseUnit (NonNegative n) =
conjoin
[ parseUnit (show n) ==? (Ok n::Result Int)
, parseUnit (show n ++ "m") ==? (Ok n::Result Int)
, parseUnit (show n ++ "M") ==? (Ok (truncate n_mb)::Result Int)
, parseUnit (show n ++ "g") ==? (Ok (n*1024)::Result Int)
, parseUnit (show n ++ "G") ==? (Ok (truncate n_gb)::Result Int)
, parseUnit (show n ++ "t") ==? (Ok (n*1048576)::Result Int)
, parseUnit (show n ++ "T") ==? (Ok (truncate n_tb)::Result Int)
, counterexample "Internal error/overflow?"
(n_mb >=0 && n_gb >= 0 && n_tb >= 0)
, property (isBad (parseUnit (show n ++ "x")::Result Int))
]
where n_mb = (fromIntegral n::Rational) * 1000 * 1000 / 1024 / 1024
n_gb = n_mb * 1000
n_tb = n_gb * 1000
{-# ANN case_niceSort_static "HLint: ignore Use camelCase" #-}
case_niceSort_static :: Assertion
case_niceSort_static = do
assertEqual "empty list" [] $ niceSort []
assertEqual "punctuation" [",", "."] $ niceSort [",", "."]
assertEqual "decimal numbers" ["0.1", "0.2"] $ niceSort ["0.1", "0.2"]
assertEqual "various numbers" ["0,099", "0.1", "0.2", "0;099"] $
niceSort ["0;099", "0,099", "0.1", "0.2"]
assertEqual "simple concat" ["0000", "a0", "a1", "a2", "a20", "a99",
"b00", "b10", "b70"] $
niceSort ["a0", "a1", "a99", "a20", "a2", "b10", "b70", "b00", "0000"]
assertEqual "ranges" ["A", "Z", "a0-0", "a0-4", "a1-0", "a9-1", "a09-2",
"a20-3", "a99-3", "a99-10", "b"] $
niceSort ["a0-0", "a1-0", "a99-10", "a20-3", "a0-4", "a99-3", "a09-2",
"Z", "a9-1", "A", "b"]
assertEqual "large"
["3jTwJPtrXOY22bwL2YoW", "Eegah9ei", "KOt7vn1dWXi",
"KVQqLPDjcPjf8T3oyzjcOsfkb", "WvNJd91OoXvLzdEiEXa6",
"Z8Ljf1Pf5eBfNg171wJR", "a07h8feON165N67PIE", "bH4Q7aCu3PUPjK3JtH",
"cPRi0lM7HLnSuWA2G9", "guKJkXnkULealVC8CyF1xefym",
"pqF8dkU5B1cMnyZuREaSOADYx", "uHXAyYYftCSG1o7qcCqe",
"xij88brTulHYAv8IEOyU", "xpIUJeVT1Rp"] $
niceSort ["Eegah9ei", "xij88brTulHYAv8IEOyU", "3jTwJPtrXOY22bwL2YoW",
"Z8Ljf1Pf5eBfNg171wJR", "WvNJd91OoXvLzdEiEXa6",
"uHXAyYYftCSG1o7qcCqe", "xpIUJeVT1Rp", "KOt7vn1dWXi",
"a07h8feON165N67PIE", "bH4Q7aCu3PUPjK3JtH",
"cPRi0lM7HLnSuWA2G9", "KVQqLPDjcPjf8T3oyzjcOsfkb",
"guKJkXnkULealVC8CyF1xefym", "pqF8dkU5B1cMnyZuREaSOADYx"]
assertEqual "hostnames"
["host1.example.com", "host2.example.com", "host03.example.com",
"host11.example.com", "host255.example.com"] $
niceSort ["host2.example.com", "host11.example.com", "host03.example.com",
"host1.example.com", "host255.example.com"]
-- | Tests single-string behaviour of 'niceSort'.
prop_niceSort_single :: Property
prop_niceSort_single =
forAll genName $ \name ->
conjoin
[ counterexample "single string" $ [name] ==? niceSort [name]
, counterexample "single plus empty" $ ["", name] ==? niceSort [name, ""]
]
-- | Tests some generic 'niceSort' properties. Note that the last test
-- must add a non-digit prefix; a digit one might change ordering.
prop_niceSort_generic :: Property
prop_niceSort_generic =
forAll (resize 20 arbitrary) $ \names ->
let n_sorted = niceSort names in
conjoin [ counterexample "length" $ length names ==? length n_sorted
, counterexample "same strings" $ sort names ==? sort n_sorted
, counterexample "idempotence" $ n_sorted ==? niceSort n_sorted
, counterexample "static prefix" $ n_sorted ==?
map tail (niceSort $ map (" "++) names)
]
-- | Tests that niceSorting numbers is identical to actual sorting
-- them (in numeric form).
prop_niceSort_numbers :: Property
prop_niceSort_numbers =
forAll (listOf (arbitrary::Gen (NonNegative Int))) $ \numbers ->
map show (sort numbers) ==? niceSort (map show numbers)
-- | Tests that 'niceSort' and 'niceSortKey' are equivalent.
prop_niceSortKey_equiv :: Property
prop_niceSortKey_equiv =
forAll (resize 20 arbitrary) $ \names ->
forAll (vectorOf (length names) (arbitrary::Gen Int)) $ \numbers ->
let n_sorted = niceSort names in
conjoin
[ counterexample "key id" $ n_sorted ==? niceSortKey id names
, counterexample "key rev" $ niceSort (map reverse names) ==?
map reverse (niceSortKey reverse names)
, counterexample "key snd" $ n_sorted ==? map snd (niceSortKey snd $
zip numbers names)
]
-- | Tests 'rStripSpace'.
prop_rStripSpace :: NonEmptyList Char -> Property
prop_rStripSpace (NonEmpty str) =
forAll (resize 50 $ listOf1 (arbitrary `suchThat` isSpace)) $ \whitespace ->
conjoin [ counterexample "arb. string last char is not space" $
case rStripSpace str of
[] -> True
xs -> not . isSpace $ last xs
, counterexample "whitespace suffix is stripped" $
rStripSpace str ==? rStripSpace (str ++ whitespace)
, counterexample "whitespace reduced to null" $
rStripSpace whitespace ==? ""
, counterexample "idempotent on empty strings" $
rStripSpace "" ==? ""
]
-- | Tests that the newUUID function produces valid UUIDs.
case_new_uuid :: Assertion
case_new_uuid = do
uuid <- newUUID
assertBool "newUUID" $ isUUID uuid
#ifdef VERSION_regex_pcre
{-# ANN case_new_uuid_regex "HLint: ignore Use camelCase" #-}
-- | Tests that the newUUID function produces valid UUIDs.
case_new_uuid_regex :: Assertion
case_new_uuid_regex = do
uuid <- newUUID
assertBool "newUUID" $ uuid =~ C.uuidRegex
#endif
prop_clockTimeToString :: Integer -> Integer -> Property
prop_clockTimeToString ts pico =
clockTimeToString (TOD ts pico) ==? show ts
-- | Test normal operation for 'chompPrefix'.
--
-- Any random prefix of a string must be stripped correctly, including the empty
-- prefix, and the whole string.
prop_chompPrefix_normal :: String -> Property
prop_chompPrefix_normal str =
forAll (choose (0, length str)) $ \size ->
chompPrefix (take size str) str ==? (Just $ drop size str)
-- | Test that 'chompPrefix' correctly allows the last char (the separator) to
-- be absent if the string terminates there.
prop_chompPrefix_last :: Property
prop_chompPrefix_last =
forAll (choose (1, 20)) $ \len ->
forAll (vectorOf len arbitrary) $ \pfx ->
chompPrefix pfx pfx ==? Just "" .&&.
chompPrefix pfx (init pfx) ==? Just ""
-- | Test that chompPrefix on the empty string always returns Nothing for
-- prefixes of length 2 or more.
prop_chompPrefix_empty_string :: Property
prop_chompPrefix_empty_string =
forAll (choose (2, 20)) $ \len ->
forAll (vectorOf len arbitrary) $ \pfx ->
chompPrefix pfx "" ==? Nothing
-- | Test 'chompPrefix' returns Nothing when the prefix doesn't match.
prop_chompPrefix_nothing :: Property
prop_chompPrefix_nothing =
forAll (choose (1, 20)) $ \len ->
forAll (vectorOf len arbitrary) $ \pfx ->
forAll (arbitrary `suchThat`
(\s -> not (pfx `isPrefixOf` s) && s /= init pfx)) $ \str ->
chompPrefix pfx str ==? Nothing
-- | Tests 'trim'.
prop_trim :: NonEmptyList Char -> Property
prop_trim (NonEmpty str) =
forAll (listOf1 $ elements " \t\n\r\f") $ \whitespace ->
forAll (choose (0, length whitespace)) $ \n ->
let (preWS, postWS) = splitAt n whitespace in
conjoin [ counterexample "arb. string first and last char are not space" $
case trim str of
[] -> True
xs -> (not . isSpace . head) xs && (not . isSpace . last) xs
, counterexample "whitespace is striped" $
trim str ==? trim (preWS ++ str ++ postWS)
, counterexample "whitespace reduced to null" $
trim whitespace ==? ""
, counterexample "idempotent on empty strings" $
trim "" ==? ""
]
-- | Tests 'splitEithers' and 'recombineEithers'.
prop_splitRecombineEithers :: [Either Int Int] -> Property
prop_splitRecombineEithers es =
conjoin
[ counterexample "only lefts are mapped correctly" $
splitEithers (map Left lefts) ==? (reverse lefts, emptylist, falses)
, counterexample "only rights are mapped correctly" $
splitEithers (map Right rights) ==? (emptylist, reverse rights, trues)
, counterexample "recombination is no-op" $
recombineEithers splitleft splitright trail ==? Ok es
, counterexample "fail on too long lefts" $
isBad (recombineEithers (0:splitleft) splitright trail)
, counterexample "fail on too long rights" $
isBad (recombineEithers splitleft (0:splitright) trail)
, counterexample "fail on too long trail" $
isBad (recombineEithers splitleft splitright (True:trail))
]
where (lefts, rights) = Either.partitionEithers es
falses = map (const False) lefts
trues = map (const True) rights
(splitleft, splitright, trail) = splitEithers es
emptylist = []::[Int]
-- | Tests 'isSubsequenceOf'.
prop_isSubsequenceOf :: Property
prop_isSubsequenceOf = do
-- isSubsequenceOf only has access to Eq so restricting to a small
-- set of numbers and short lists still covers everything it can do.
let num = choose (0, 5)
forAll (choose (0, 4)) $ \n1 ->
forAll (choose (0, 4)) $ \n2 ->
forAll (vectorOf n1 num) $ \(a :: [Int]) ->
forAll (vectorOf n2 num) $ \b ->
let subs = S.fromList $ subsequences b
in a `isSubsequenceOf` b == a `S.member` subs
testSuite "Utils"
[ 'prop_commaJoinSplit
, 'prop_commaSplitJoin
, 'prop_findFirst
, 'prop_fromObjWithDefault
, 'prop_if'if
, 'prop_select
, 'prop_select_undefd
, 'prop_select_undefv
, 'prop_parseUnit
, 'case_niceSort_static
, 'prop_niceSort_single
, 'prop_niceSort_generic
, 'prop_niceSort_numbers
, 'prop_niceSortKey_equiv
, 'prop_rStripSpace
, 'prop_trim
, 'case_new_uuid
#ifdef VERSION_regex_pcre
, 'case_new_uuid_regex
#endif
, 'prop_clockTimeToString
, 'prop_chompPrefix_normal
, 'prop_chompPrefix_last
, 'prop_chompPrefix_empty_string
, 'prop_chompPrefix_nothing
, 'prop_splitRecombineEithers
, 'prop_isSubsequenceOf
]
| apyrgio/ganeti | test/hs/Test/Ganeti/Utils.hs | bsd-2-clause | 15,971 | 0 | 21 | 3,651 | 3,634 | 1,955 | 1,679 | 264 | 2 |
{-# LANGUAGE RecordWildCards #-}
module Main where
import Options (Config(..),getConfig,genLocationsFile)
import Protocol
(getRequest,putResponse,Request(..),Response(..)
,respondResult,Instance(..),showPosition)
import SITL
(withSitlServer,ServerHandle,isArmed,getObstacles
,getPositions,moveTo,followWaypoints)
import Control.Concurrent.Async (wait)
import Control.Monad (forever,zipWithM)
import Data.IORef (newIORef,readIORef,writeIORef)
import Network (listenOn,PortID(..),accept)
import System.FilePath ((</>))
import System.IO (Handle)
import System.Random (randomRIO)
-- Server ----------------------------------------------------------------------
main :: IO ()
main =
do cfg <- getConfig
-- create the locations.txt file
writeFile (cfgArduPilotPath cfg </> "Tools" </> "autotest" </> "locations.txt")
(genLocationsFile (cfgSimConfig cfg))
putStrLn "Starting SITL instances..."
withSitlServer cfg $ \ server ->
do insts <- getObstacles server
sock <- listenOn (PortNumber (cfgPort cfg))
putStrLn "Waiting for control connection..."
(h,_,_) <- accept sock
putStrLn "Controller connected"
handleClient cfg server insts h
-- | Handle a connection from the controller, proxying all of its commands to
-- the controlled instance.
handleClient :: Config -> ServerHandle -> [Instance] -> Handle -> IO ()
handleClient Config { .. } server obstacles client =
do positions <- newIORef []
forever (processMsg positions)
where
processMsg oldPs =
do req <- getRequest client
case req of
GetStatus ->
do putStrLn "Checking status"
b <- isArmed Controlled server
putResponse client (respondResult (Status b))
StartObstacles ->
do putStrLn "Starting obstacles"
mapM_ (`followWaypoints` server) obstacles
putResponse client (respondResult Ack)
MoveTo loc ->
do putStrLn $ showString "Moving the controlled instance to: "
$ showPosition loc ""
wait =<< moveTo Controlled loc server
putResponse client (respondResult Ack)
GetPositions ->
do putStrLn "Returning positions"
ps <- adjustPositions oldPs =<< getPositions server
putResponse client (respondResult (Positions ps))
adjustPositions =
case cfgDrop of
Just p -> adjustPositions' p
Nothing -> \ _ curPs -> return curPs
adjustPositions' p posCache curPs =
do prev <- readIORef posCache
newPs <- case prev of
[] -> return curPs
_ -> zipWithM (pickPos p) prev curPs
writeIORef posCache newPs
return newPs
-- As the positions that come from the ServerHandle are in a stable order,
-- zipping the two lists with a chance to drop is sufficient. Additionally,
-- the controlled instance never has its position delayed.
pickPos _ (Controlled,_,_) pos@(Controlled,_,_) = return pos
pickPos p old new =
do s <- randomRIO (0,1)
if s >= p
then return new
else return old
| GaloisInc/planning-synthesis | sitl_server/server/src/Main.hs | bsd-2-clause | 3,397 | 0 | 18 | 1,046 | 828 | 421 | 407 | 70 | 8 |
module System.Random.Lehmer.Util (
(//)
, coerce
, stdUniform
, expDist
) where
-- import Data.Function (on)
import System.Random.Lehmer.Constants
-- | Division of Int values into Floating.
(//) :: (Integral a, Integral b, Floating c) => a -> b -> c
a // b = (fromIntegral a) / (fromIntegral b)
-- Why doesn't this work
-- a // b = (/) `on` fromIntegral
-- It places a type Restriction of Integer, so Ints do not work
-- | Turns an Int in the range (0, m) where m = 2^31 - 1, into a Floating in the range (0,1).
stdUniform :: (Integral a, Floating b) => a -> b
stdUniform = (// modulus)
-- | Takes a value in the range (0,1) and expands it into the range (a,b).
coerce :: (Floating a, Ord a)
=> a -- ^ Lower bound (a)
-> a -- ^ Upper bound (b)
-> a -- ^ Uniform(0,1)
-> a -- ^ Uniform(a,b)
coerce a b u
| a < b = low + a
| a > b = low + b
| otherwise = error "Zero Range"
where rng = abs $ b - a
low = rng * u
expDist :: (Floating a)
=> a -- ^ λ
-> a -- ^ Uniform(0,1)
-> a -- ^ Exp(λ)
expDist l u = (negate l) * log (1 - u)
| zirrostig/haskell-lehmer | System/Random/Lehmer/Util.hs | bsd-3-clause | 1,135 | 0 | 8 | 335 | 304 | 170 | 134 | -1 | -1 |
{-# LANGUAGE MonadComprehensions #-}
{-# LANGUAGE TemplateHaskell #-}
-- | Infer functional dependencies from table algebra operators.
module Database.DSH.Backend.Sql.Opt.Properties.FD
( inferFDNullOp
, inferFDUnOp
, inferFDBinOp
) where
import qualified Data.Map as M
import Data.Maybe
import qualified Data.Set.Monad as S
import Data.Tuple
import Database.Algebra.Table.Lang
import Database.DSH.Backend.Sql.Opt.Properties.Auxiliary
import Database.DSH.Backend.Sql.Opt.Properties.Types
import Database.DSH.Common.Impossible
inferFDNullOp :: S.Set TypedAttr -> S.Set PKey -> NullOp -> FDSet
inferFDNullOp tcs ks op =
case op of
LitTable _ -> FDSet $ foldr (\k m -> M.insert k (cs S.\\ k) m) M.empty ks
TableRef _ -> FDSet $ foldr (\k m -> M.insert k (cs S.\\ k) m) M.empty ks
where
cs = fmap fst tcs
-- | Update an attribute set with new names. All attributes must find
-- a new name.
updateSetAll :: [(Attr, Attr)] -> S.Set Attr -> Maybe (S.Set Attr)
updateSetAll colMap =
S.foldr' (\c mcs -> S.insert <$> lookup c colMap <*> mcs)
(Just S.empty)
-- | Update an attribute set with new names. Attributes for which no
-- new name exists are removed.
updateSet :: [(Attr, Attr)] -> S.Set Attr -> S.Set Attr
updateSet colMap cs = unionss $ fmap (\c -> maybe S.empty ss $ lookup c colMap) cs
updateFD :: [(Attr, Attr)] -> S.Set Attr -> S.Set Attr -> FDSet -> FDSet
updateFD colMap dets deps (FDSet m) =
case (updateSetAll colMap dets, updateSet colMap deps) of
(Just dets', deps') | deps' /= S.empty -> FDSet $ M.insert dets' deps' m
_ -> FDSet m
-- | Update a set of functional dependencies with new names from a
-- projection. A functional dependency is kept if all attributes from
-- the determinant set can be mapped and if at least one attribute
-- from the dependent set can be mapped.
updateFDSet :: [(Attr, Attr)] -> FDSet -> FDSet
updateFDSet colMap (FDSet m) = M.foldrWithKey (updateFD colMap) emptyFDSet m
-- -- | Add a functional dependency for a single attribute to a set of FDs.
-- addFunDep :: S.Set Attr -> Attr -> FDSet -> FDSet
-- addFunDep cs c (FDSet m) = FDSet $ M.insertWith S.union cs (ss c) m
-- | Add a dependency for a set of attributes to a set of FDs.
addFunDeps :: S.Set Attr -> S.Set Attr -> FDSet -> FDSet
addFunDeps cs cs' (FDSet m) = FDSet $ M.insertWith S.union cs cs' m
cols :: BottomUpProps -> S.Set Attr
cols p = fst <$> pCols p
inferFDUnOp :: BottomUpProps -> UnOp -> FDSet
inferFDUnOp p op =
case op of
Distinct _ -> pFunDeps p
Select _ -> pFunDeps p
RowNum (r, _, []) -> addFunDeps (ss r) (cols p) (pFunDeps p)
-- FIXME the combination of sorting and grouping cols propably
-- determines r.
RowNum (_, _, _) -> pFunDeps p
-- FIXME dependency r -> sortcols
RowRank _ -> pFunDeps p
Aggr (_, []) -> emptyFDSet
-- Dependencies among grouping columns stay intact and are
-- updated in the same way as for projections.
Aggr (as, gs) ->
let colMap = S.toList $ S.map swap $ S.fromList $ mapMaybe mapCol gs
in addFunDeps (ls $ map fst gs)
(S.fromList $ map snd as)
(updateFDSet colMap (pFunDeps p))
Project ps ->
let colMap = S.toList $ S.map swap $ S.fromList $ mapMaybe mapCol ps
in updateFDSet colMap (pFunDeps p)
Serialize _ -> pFunDeps p
-- FIXME add FDs for the new columns.
WinFun _ -> pFunDeps p
Rank _ -> $unimplemented
inferFDBinOp :: BottomUpProps -- ^ Properties of the left child
-> BottomUpProps -- ^ Properties of the right child
-> S.Set PKey -- ^ The keys of the operator itself
-> S.Set TypedAttr -- ^ The cols of the operator itself
-> BinOp -- ^ The operator
-> FDSet
inferFDBinOp p1 p2 ks cs op =
case op of
-- Determine functional dependency of a cartesian
-- product. Note: As we know that attribute sets of left and
-- right inputs are disjunct, we don't have to care for
-- collisions in the functional dependencies during unioning.
Cross _ -> FDSet $
-- Dependencies from either side are still valid after the product
fdsRep (pFunDeps p1)
`M.union`
fdsRep (pFunDeps p2)
`M.union`
-- The new combined keys determine all result columns of the product.
foldr (\k m -> M.insert k (fmap fst cs S.\\ k) m) M.empty ks
ThetaJoin _ -> FDSet $
fdsRep (pFunDeps p1)
`M.union`
fdsRep (pFunDeps p2)
`M.union`
foldr (\k m -> M.insert k (fmap fst cs S.\\ k) m) M.empty ks
SemiJoin _ -> pFunDeps p1
AntiJoin _ -> pFunDeps p1
LeftOuterJoin _ -> pFunDeps p1
DisjUnion _ -> emptyFDSet
Difference _ -> pFunDeps p1
| ulricha/dsh-sql | src/Database/DSH/Backend/Sql/Opt/Properties/FD.hs | bsd-3-clause | 5,179 | 0 | 16 | 1,598 | 1,330 | 689 | 641 | 82 | 11 |
{- |
Module : SAWScript.Prover.MRSolver
Description : The SAW monadic-recursive solver (Mr. Solver)
Copyright : Galois, Inc. 2022
License : BSD3
Maintainer : westbrook@galois.com
Stability : experimental
Portability : non-portable (language extensions)
-}
module SAWScript.Prover.MRSolver
(askMRSolver, MRFailure(..), showMRFailure, isCompFunType,
MREnv(..), emptyMREnv) where
import SAWScript.Prover.MRSolver.Term
import SAWScript.Prover.MRSolver.Monad
import SAWScript.Prover.MRSolver.Solver
| GaloisInc/saw-script | src/SAWScript/Prover/MRSolver.hs | bsd-3-clause | 515 | 0 | 5 | 69 | 57 | 40 | 17 | 6 | 0 |
{-# OPTIONS -Wall #-}
module Language.Pck.Cpu.Instruction (
-- * the instruction set type
Inst(..)
, GReg(..)
, FCond(..)
) where
import Data.Array (Ix)
import Control.DeepSeq (NFData, rnf)
----------------------------------------
-- instruction set
----------------------------------------
-- | the instruction definition.
--
-- You can create instructions as you like :-)
--
-- Operand order is Intel, ARM, MIPS, PowerPC,... order.
-- (opcode dst src1 src2)
data Inst = NOP -- ^ no operation
| HALT -- ^ halt (stop the processor)
| MOVI GReg Int -- ^ GReg <- Int
| MOV GReg GReg -- ^ GReg <- GReg
| MOVPC GReg -- ^ GReg <- PC
| ADD GReg GReg GReg -- ^ GReg <- GReg + GReg
| SUB GReg GReg GReg -- ^ GReg <- GReg - GReg
| CMP GReg GReg -- ^ Flag <- compare(GReg, GReg)
| ABS GReg GReg -- ^ GReg <- abs(GReg)
| ASH GReg GReg GReg -- ^ GReg <- GReg << GReg // arithmetic shift
| MUL GReg GReg GReg -- ^ GReg <- GReg * GReg
| DIV GReg GReg GReg -- ^ GReg <- GReg / GReg
| AND GReg GReg GReg -- ^ GReg <- GReg & GReg
| OR GReg GReg GReg -- ^ GReg <- GReg | GReg
| NOT GReg GReg -- ^ GReg <- ~GReg
| XOR GReg GReg GReg -- ^ GReg <- GReg ^ GReg
| LSH GReg GReg GReg -- ^ GReg <- GReg << GReg // logical shift
| BRI FCond Int -- ^ if (FCond(Flag)) goto (PC + Int)
-- // pc relative addressing
| JRI Int -- ^ goto (PC + Int)
-- // pc relative addressing
| J GReg -- ^ goto GReg
-- // absolute addressing
| CALL GReg -- ^ goto GReg; R0 <- PC
-- // absolute addressing
| RET -- ^ goto R0
| LD GReg GReg -- ^ GReg <- memory(GReg)
| ST GReg GReg -- ^ memory(GReg) <- GReg
| UNDEF -- ^ undefined
deriving (Show, Eq)
-- to use deepseq for the assembler
instance NFData Inst where rnf x = seq x ()
-- | the general purpose registers.
--
-- You can create registers as you like :-)
data GReg = R0 | R1 | R2 | R3 | R4 | R5 | R6 | R7
deriving (Show, Eq, Ord, Ix, Enum, Bounded)
-- | the Flag conditions
data FCond = FCEQ -- ^ equal
| FCNE -- ^ not equal
| FCLT -- ^ little than
| FCLE -- ^ little equal
| FCGT -- ^ greater than
| FCGE -- ^ greater equal
deriving (Show, Eq)
| takenobu-hs/processor-creative-kit | Language/Pck/Cpu/Instruction.hs | bsd-3-clause | 2,855 | 0 | 7 | 1,236 | 400 | 255 | 145 | 43 | 0 |
{-# LANGUAGE NoImplicitPrelude #-}
-- | JSON schema validation.
module Data.Aeson.Validation
( -- * Schema validation
Schema
, validate
-- * Boolean schemas
, bool
, true
, false
-- * Number schemas
, number
, theNumber
, someNumber
, integer
, theInteger
, someInteger
-- * String schemas
, string
, theString
, someString
, regex
, datetime
-- * Object schemas
, Field
, object
, object'
, (.:)
, (.:?)
-- * Array schemas (homogenous lists)
, array
, sizedArray
, -- * Set schemas (homogenous, unique lists)
set
, sizedSet
-- * Tuple schemas (heterogeneous lists)
, tuple
-- * Miscellaneous schemas
, anything
, nullable
) where
import Data.Aeson.Validation.Internal.Field (Field)
import Data.Aeson.Validation.Internal.Schema
| mitchellwrosen/json-validation | src/Data/Aeson/Validation.hs | bsd-3-clause | 825 | 0 | 5 | 214 | 129 | 92 | 37 | 33 | 0 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Main where
import Control.Applicative
import Control.Exception
import Control.Monad
import Control.Monad.Reader
import Data.Aeson
import qualified Data.HashMap.Strict as HM
import Data.List (nub)
import Data.List.NonEmpty (NonEmpty (..))
import qualified Data.List.NonEmpty as NE
import qualified Data.Map.Strict as M
import Data.Text (Text)
import qualified Data.Text as T
import Data.Time.Calendar (Day (..))
import Data.Time.Clock (UTCTime (..),
secondsToDiffTime)
import qualified Data.Vector as V
import Database.Bloodhound
import GHC.Generics (Generic)
import Network.HTTP.Client
import qualified Network.HTTP.Types.Status as NHTS
import Prelude hiding (filter)
import Test.Hspec
import Test.QuickCheck.Property.Monoid (prop_Monoid, eq, T(..))
import Test.Hspec.QuickCheck (prop)
import Test.QuickCheck
testServer :: Server
testServer = Server "http://localhost:9200"
testIndex :: IndexName
testIndex = IndexName "bloodhound-tests-twitter-1"
testMapping :: MappingName
testMapping = MappingName "tweet"
withTestEnv :: BH IO a -> IO a
withTestEnv = withBH defaultManagerSettings testServer
validateStatus :: Response body -> Int -> Expectation
validateStatus resp expected =
(NHTS.statusCode $ responseStatus resp)
`shouldBe` (expected :: Int)
createExampleIndex :: BH IO Reply
createExampleIndex = createIndex defaultIndexSettings testIndex
deleteExampleIndex :: BH IO Reply
deleteExampleIndex = deleteIndex testIndex
data ServerVersion = ServerVersion Int Int Int deriving (Show, Eq, Ord)
es14 :: ServerVersion
es14 = ServerVersion 1 4 0
es13 :: ServerVersion
es13 = ServerVersion 1 3 0
es12 :: ServerVersion
es12 = ServerVersion 1 2 0
es11 :: ServerVersion
es11 = ServerVersion 1 1 0
es10 :: ServerVersion
es10 = ServerVersion 1 0 0
serverBranch :: ServerVersion -> ServerVersion
serverBranch (ServerVersion majorVer minorVer patchVer) =
ServerVersion majorVer minorVer patchVer
mkServerVersion :: [Int] -> Maybe ServerVersion
mkServerVersion [majorVer, minorVer, patchVer] =
Just (ServerVersion majorVer minorVer patchVer)
mkServerVersion _ = Nothing
getServerVersion :: IO (Maybe ServerVersion)
getServerVersion = liftM extractVersion (withTestEnv getStatus)
where
version' = T.splitOn "." . number . version
toInt = read . T.unpack
parseVersion v = map toInt (version' v)
extractVersion = join . liftM (mkServerVersion . parseVersion)
testServerBranch :: IO (Maybe ServerVersion)
testServerBranch = getServerVersion >>= \v -> return $ liftM serverBranch v
atleast :: ServerVersion -> IO Bool
atleast v = testServerBranch >>= \x -> return $ x >= Just (serverBranch v)
atmost :: ServerVersion -> IO Bool
atmost v = testServerBranch >>= \x -> return $ x <= Just (serverBranch v)
is :: ServerVersion -> IO Bool
is v = testServerBranch >>= \x -> return $ x == Just (serverBranch v)
when' :: Monad m => m Bool -> m () -> m ()
when' b f = b >>= \x -> when x f
data Location = Location { lat :: Double
, lon :: Double } deriving (Eq, Generic, Show)
data Tweet = Tweet { user :: Text
, postDate :: UTCTime
, message :: Text
, age :: Int
, location :: Location }
deriving (Eq, Generic, Show)
instance ToJSON Tweet
instance FromJSON Tweet
instance ToJSON Location
instance FromJSON Location
data TweetMapping = TweetMapping deriving (Eq, Show)
instance ToJSON TweetMapping where
toJSON TweetMapping =
object ["tweet" .=
object ["properties" .=
object [ "user" .= object ["type" .= ("string" :: Text)]
-- Serializing the date as a date is breaking other tests, mysteriously.
-- , "postDate" .= object [ "type" .= ("date" :: Text)
-- , "format" .= ("YYYY-MM-dd`T`HH:mm:ss.SSSZZ" :: Text)]
, "message" .= object ["type" .= ("string" :: Text)]
, "age" .= object ["type" .= ("integer" :: Text)]
, "location" .= object ["type" .= ("geo_point" :: Text)]
]]]
exampleTweet :: Tweet
exampleTweet = Tweet { user = "bitemyapp"
, postDate = UTCTime
(ModifiedJulianDay 55000)
(secondsToDiffTime 10)
, message = "Use haskell!"
, age = 10000
, location = Location 40.12 (-71.34) }
otherTweet :: Tweet
otherTweet = Tweet { user = "notmyapp"
, postDate = UTCTime
(ModifiedJulianDay 55000)
(secondsToDiffTime 11)
, message = "Use haskell!"
, age = 1000
, location = Location 40.12 (-71.34) }
resetIndex :: BH IO ()
resetIndex = do
_ <- deleteExampleIndex
_ <- createExampleIndex
_ <- putMapping testIndex testMapping TweetMapping
return ()
insertData :: BH IO Reply
insertData = do
resetIndex
insertData' defaultIndexDocumentSettings
insertData' :: IndexDocumentSettings -> BH IO Reply
insertData' ids = do
r <- indexDocument testIndex testMapping ids exampleTweet (DocId "1")
_ <- refreshIndex testIndex
return r
insertOther :: BH IO ()
insertOther = do
_ <- indexDocument testIndex testMapping defaultIndexDocumentSettings otherTweet (DocId "2")
_ <- refreshIndex testIndex
return ()
searchTweet :: Search -> BH IO (Either String Tweet)
searchTweet search = do
reply <- searchByIndex testIndex search
let result = eitherDecode (responseBody reply) :: Either String (SearchResult Tweet)
let myTweet = fmap (hitSource . head . hits . searchHits) result
return myTweet
searchExpectNoResults :: Search -> BH IO ()
searchExpectNoResults search = do
reply <- searchByIndex testIndex search
let result = eitherDecode (responseBody reply) :: Either String (SearchResult Tweet)
let emptyHits = fmap (hits . searchHits) result
liftIO $
emptyHits `shouldBe` Right []
searchExpectAggs :: Search -> BH IO ()
searchExpectAggs search = do
reply <- searchAll search
let isEmpty x = return (M.null x)
let result = decode (responseBody reply) :: Maybe (SearchResult Tweet)
liftIO $
(result >>= aggregations >>= isEmpty) `shouldBe` Just False
searchValidBucketAgg :: (BucketAggregation a, FromJSON a, Show a) =>
Search -> Text -> (Text -> AggregationResults -> Maybe (Bucket a)) -> BH IO ()
searchValidBucketAgg search aggKey extractor = do
reply <- searchAll search
let bucketDocs = docCount . head . buckets
let result = decode (responseBody reply) :: Maybe (SearchResult Tweet)
let count = result >>= aggregations >>= extractor aggKey >>= \x -> return (bucketDocs x)
liftIO $
count `shouldBe` Just 1
searchTermsAggHint :: [ExecutionHint] -> BH IO ()
searchTermsAggHint hints = do
let terms hint = TermsAgg $ (mkTermsAggregation "user") { termExecutionHint = Just hint }
let search hint = mkAggregateSearch Nothing $ mkAggregations "users" $ terms hint
forM_ hints $ searchExpectAggs . search
forM_ hints (\x -> searchValidBucketAgg (search x) "users" toTerms)
searchTweetHighlight :: Search -> BH IO (Either String (Maybe HitHighlight))
searchTweetHighlight search = do
reply <- searchByIndex testIndex search
let result = eitherDecode (responseBody reply) :: Either String (SearchResult Tweet)
let myHighlight = fmap (hitHighlight . head . hits . searchHits) result
return myHighlight
data BulkTest = BulkTest { name :: Text } deriving (Eq, Generic, Show)
instance FromJSON BulkTest
instance ToJSON BulkTest
noDuplicates :: Eq a => [a] -> Bool
noDuplicates xs = nub xs == xs
instance Arbitrary RegexpFlags where
arbitrary = oneof [ pure AllRegexpFlags
, pure NoRegexpFlags
, SomeRegexpFlags <$> arbitrary
]
instance Arbitrary a => Arbitrary (NonEmpty a) where
arbitrary = liftA2 (:|) arbitrary arbitrary
instance Arbitrary RegexpFlag where
arbitrary = oneof [ pure AnyString
, pure Automaton
, pure Complement
, pure Empty
, pure Intersection
, pure Interval
]
arbitraryScore :: Gen Score
arbitraryScore = fmap getPositive <$> arbitrary
instance Arbitrary Text where
arbitrary = T.pack <$> arbitrary
instance (Arbitrary k, Arbitrary v, Ord k) => Arbitrary (M.Map k v) where
arbitrary = M.fromList <$> arbitrary
instance Arbitrary IndexName where
arbitrary = IndexName <$> arbitrary
instance Arbitrary MappingName where
arbitrary = MappingName <$> arbitrary
instance Arbitrary DocId where
arbitrary = DocId <$> arbitrary
instance Arbitrary a => Arbitrary (Hit a) where
arbitrary = Hit <$> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitraryScore
<*> arbitrary
<*> arbitrary
instance Arbitrary a => Arbitrary (SearchHits a) where
arbitrary = sized $ \n -> resize (n `div` 2) $ do
tot <- getPositive <$> arbitrary
score <- arbitraryScore
hs <- arbitrary
return $ SearchHits tot score hs
main :: IO ()
main = hspec $ do
describe "index create/delete API" $ do
it "creates and then deletes the requested index" $ withTestEnv $ do
-- priming state.
_ <- deleteExampleIndex
resp <- createExampleIndex
deleteResp <- deleteExampleIndex
liftIO $ do
validateStatus resp 200
validateStatus deleteResp 200
describe "document API" $ do
it "indexes, gets, and then deletes the generated document" $ withTestEnv $ do
_ <- insertData
docInserted <- getDocument testIndex testMapping (DocId "1")
let newTweet = eitherDecode
(responseBody docInserted) :: Either String (EsResult Tweet)
liftIO $ (fmap _source newTweet `shouldBe` Right exampleTweet)
it "can use optimistic concurrency control" $ withTestEnv $ do
let ev = ExternalDocVersion minBound
let cfg = defaultIndexDocumentSettings { idsVersionControl = ExternalGT ev }
resetIndex
res <- insertData' cfg
liftIO $ isCreated res `shouldBe` True
res' <- insertData' cfg
liftIO $ isVersionConflict res' `shouldBe` True
describe "template API" $ do
it "can create a template" $ withTestEnv $ do
let idxTpl = IndexTemplate (TemplatePattern "tweet-*") (Just (IndexSettings (ShardCount 1) (ReplicaCount 1))) [toJSON TweetMapping]
resp <- putTemplate idxTpl (TemplateName "tweet-tpl")
liftIO $ validateStatus resp 200
it "can detect if a template exists" $ withTestEnv $ do
exists <- templateExists (TemplateName "tweet-tpl")
liftIO $ exists `shouldBe` True
it "can delete a template" $ withTestEnv $ do
resp <- deleteTemplate (TemplateName "tweet-tpl")
liftIO $ validateStatus resp 200
it "can detect if a template doesn't exist" $ withTestEnv $ do
exists <- templateExists (TemplateName "tweet-tpl")
liftIO $ exists `shouldBe` False
describe "bulk API" $ do
it "inserts all documents we request" $ withTestEnv $ do
_ <- insertData
let firstTest = BulkTest "blah"
let secondTest = BulkTest "bloo"
let firstDoc = BulkIndex testIndex
testMapping (DocId "2") (toJSON firstTest)
let secondDoc = BulkCreate testIndex
testMapping (DocId "3") (toJSON secondTest)
let stream = V.fromList [firstDoc, secondDoc]
_ <- bulk stream
_ <- refreshIndex testIndex
fDoc <- getDocument testIndex testMapping (DocId "2")
sDoc <- getDocument testIndex testMapping (DocId "3")
let maybeFirst = eitherDecode $ responseBody fDoc :: Either String (EsResult BulkTest)
let maybeSecond = eitherDecode $ responseBody sDoc :: Either String (EsResult BulkTest)
liftIO $ do
fmap _source maybeFirst `shouldBe` Right firstTest
fmap _source maybeSecond `shouldBe` Right secondTest
describe "query API" $ do
it "returns document for term query and identity filter" $ withTestEnv $ do
_ <- insertData
let query = TermQuery (Term "user" "bitemyapp") Nothing
let filter = IdentityFilter <&&> IdentityFilter
let search = mkSearch (Just query) (Just filter)
myTweet <- searchTweet search
liftIO $
myTweet `shouldBe` Right exampleTweet
it "returns document for terms query and identity filter" $ withTestEnv $ do
_ <- insertData
let query = TermsQuery (NE.fromList [(Term "user" "bitemyapp")])
let filter = IdentityFilter <&&> IdentityFilter
let search = mkSearch (Just query) (Just filter)
myTweet <- searchTweet search
liftIO $
myTweet `shouldBe` Right exampleTweet
it "returns document for match query" $ withTestEnv $ do
_ <- insertData
let query = QueryMatchQuery $ mkMatchQuery (FieldName "user") (QueryString "bitemyapp")
let search = mkSearch (Just query) Nothing
myTweet <- searchTweet search
liftIO $
myTweet `shouldBe` Right exampleTweet
it "returns document for multi-match query" $ withTestEnv $ do
_ <- insertData
let fields = [FieldName "user", FieldName "message"]
let query = QueryMultiMatchQuery $ mkMultiMatchQuery fields (QueryString "bitemyapp")
let search = mkSearch (Just query) Nothing
myTweet <- searchTweet search
liftIO $
myTweet `shouldBe` Right exampleTweet
it "returns document for bool query" $ withTestEnv $ do
_ <- insertData
let innerQuery = QueryMatchQuery $
mkMatchQuery (FieldName "user") (QueryString "bitemyapp")
let query = QueryBoolQuery $
mkBoolQuery [innerQuery] [] []
let search = mkSearch (Just query) Nothing
myTweet <- searchTweet search
liftIO $
myTweet `shouldBe` Right exampleTweet
it "returns document for boosting query" $ withTestEnv $ do
_ <- insertData
let posQuery = QueryMatchQuery $ mkMatchQuery (FieldName "user") (QueryString "bitemyapp")
let negQuery = QueryMatchQuery $ mkMatchQuery (FieldName "user") (QueryString "notmyapp")
let query = QueryBoostingQuery $ BoostingQuery posQuery negQuery (Boost 0.2)
let search = mkSearch (Just query) Nothing
myTweet <- searchTweet search
liftIO $
myTweet `shouldBe` Right exampleTweet
it "returns document for common terms query" $ withTestEnv $ do
_ <- insertData
let query = QueryCommonTermsQuery $
CommonTermsQuery (FieldName "user")
(QueryString "bitemyapp")
(CutoffFrequency 0.0001)
Or Or Nothing Nothing Nothing Nothing
let search = mkSearch (Just query) Nothing
myTweet <- searchTweet search
liftIO $
myTweet `shouldBe` Right exampleTweet
describe "sorting" $ do
it "returns documents in the right order" $ withTestEnv $ do
_ <- insertData
_ <- insertOther
let sortSpec = DefaultSortSpec $ mkSort (FieldName "age") Ascending
let search = Search Nothing
(Just IdentityFilter) (Just [sortSpec]) Nothing Nothing
False (From 0) (Size 10)
reply <- searchByIndex testIndex search
let result = eitherDecode (responseBody reply) :: Either String (SearchResult Tweet)
let myTweet = fmap (hitSource . head . hits . searchHits) result
liftIO $
myTweet `shouldBe` Right otherTweet
describe "filtering API" $ do
it "returns document for composed boolmatch and identity" $ withTestEnv $ do
_ <- insertData
let queryFilter = BoolFilter (MustMatch (Term "user" "bitemyapp") False)
<&&> IdentityFilter
let search = mkSearch Nothing (Just queryFilter)
myTweet <- searchTweet search
liftIO $
myTweet `shouldBe` Right exampleTweet
it "returns document for term filter" $ withTestEnv $ do
_ <- insertData
let termFilter = TermFilter (Term "user" "bitemyapp") False
let search = mkSearch Nothing (Just termFilter)
myTweet <- searchTweet search
liftIO $
myTweet `shouldBe` Right exampleTweet
it "returns document for existential filter" $ withTestEnv $ do
_ <- insertData
let search = mkSearch Nothing (Just (ExistsFilter (FieldName "user")))
myTweet <- searchTweet search
liftIO $
myTweet `shouldBe` Right exampleTweet
it "returns document for geo boundingbox filter" $ withTestEnv $ do
_ <- insertData
let box = GeoBoundingBox (LatLon 40.73 (-74.1)) (LatLon 40.10 (-71.12))
let bbConstraint = GeoBoundingBoxConstraint (FieldName "tweet.location") box False GeoFilterMemory
let geoFilter = GeoBoundingBoxFilter bbConstraint
let search = mkSearch Nothing (Just geoFilter)
myTweet <- searchTweet search
liftIO $
myTweet `shouldBe` Right exampleTweet
it "doesn't return document for nonsensical boundingbox filter" $ withTestEnv $ do
_ <- insertData
let box = GeoBoundingBox (LatLon 0.73 (-4.1)) (LatLon 0.10 (-1.12))
let bbConstraint = GeoBoundingBoxConstraint (FieldName "tweet.location") box False GeoFilterMemory
let geoFilter = GeoBoundingBoxFilter bbConstraint
let search = mkSearch Nothing (Just geoFilter)
searchExpectNoResults search
it "returns document for geo distance filter" $ withTestEnv $ do
_ <- insertData
let geoPoint = GeoPoint (FieldName "tweet.location") (LatLon 40.12 (-71.34))
let distance = Distance 10.0 Miles
let optimizeBbox = OptimizeGeoFilterType GeoFilterMemory
let geoFilter = GeoDistanceFilter geoPoint distance SloppyArc optimizeBbox False
let search = mkSearch Nothing (Just geoFilter)
myTweet <- searchTweet search
liftIO $
myTweet `shouldBe` Right exampleTweet
it "returns document for geo distance range filter" $ withTestEnv $ do
_ <- insertData
let geoPoint = GeoPoint (FieldName "tweet.location") (LatLon 40.12 (-71.34))
let distanceRange = DistanceRange (Distance 0.0 Miles) (Distance 10.0 Miles)
let geoFilter = GeoDistanceRangeFilter geoPoint distanceRange
let search = mkSearch Nothing (Just geoFilter)
myTweet <- searchTweet search
liftIO $
myTweet `shouldBe` Right exampleTweet
it "doesn't return document for wild geo distance range filter" $ withTestEnv $ do
_ <- insertData
let geoPoint = GeoPoint (FieldName "tweet.location") (LatLon 40.12 (-71.34))
let distanceRange = DistanceRange (Distance 100.0 Miles) (Distance 1000.0 Miles)
let geoFilter = GeoDistanceRangeFilter geoPoint distanceRange
let search = mkSearch Nothing (Just geoFilter)
searchExpectNoResults search
it "returns document for geo polygon filter" $ withTestEnv $ do
_ <- insertData
let points = [LatLon 40.0 (-70.00),
LatLon 40.0 (-72.00),
LatLon 41.0 (-70.00),
LatLon 41.0 (-72.00)]
let geoFilter = GeoPolygonFilter (FieldName "tweet.location") points
let search = mkSearch Nothing (Just geoFilter)
myTweet <- searchTweet search
liftIO $
myTweet `shouldBe` Right exampleTweet
it "doesn't return document for bad geo polygon filter" $ withTestEnv $ do
_ <- insertData
let points = [LatLon 40.0 (-70.00),
LatLon 40.0 (-71.00),
LatLon 41.0 (-70.00),
LatLon 41.0 (-71.00)]
let geoFilter = GeoPolygonFilter (FieldName "tweet.location") points
let search = mkSearch Nothing (Just geoFilter)
searchExpectNoResults search
it "returns document for ids filter" $ withTestEnv $ do
_ <- insertData
let filter = IdsFilter (MappingName "tweet") [DocId "1"]
let search = mkSearch Nothing (Just filter)
myTweet <- searchTweet search
liftIO $
myTweet `shouldBe` Right exampleTweet
it "returns document for Double range filter" $ withTestEnv $ do
_ <- insertData
let filter = RangeFilter (FieldName "age")
(RangeDoubleGtLt (GreaterThan 1000.0) (LessThan 100000.0))
RangeExecutionIndex False
let search = mkSearch Nothing (Just filter)
myTweet <- searchTweet search
liftIO $
myTweet `shouldBe` Right exampleTweet
it "returns document for UTCTime date filter" $ withTestEnv $ do
_ <- insertData
let filter = RangeFilter (FieldName "postDate")
(RangeDateGtLt
(GreaterThanD (UTCTime
(ModifiedJulianDay 54000)
(secondsToDiffTime 0)))
(LessThanD (UTCTime
(ModifiedJulianDay 55000)
(secondsToDiffTime 11))))
RangeExecutionIndex False
let search = mkSearch Nothing (Just filter)
myTweet <- searchTweet search
liftIO $
myTweet `shouldBe` Right exampleTweet
it "returns document for regexp filter" $ withTestEnv $ do
_ <- insertData
let filter = RegexpFilter (FieldName "user") (Regexp "bite.*app")
AllRegexpFlags (CacheName "test") False (CacheKey "key")
let search = mkSearch Nothing (Just filter)
myTweet <- searchTweet search
liftIO $
myTweet `shouldBe` Right exampleTweet
it "doesn't return document for non-matching regexp filter" $ withTestEnv $ do
_ <- insertData
let filter = RegexpFilter (FieldName "user")
(Regexp "boy") AllRegexpFlags
(CacheName "test") False (CacheKey "key")
let search = mkSearch Nothing (Just filter)
searchExpectNoResults search
it "returns document for query filter, uncached" $ withTestEnv $ do
_ <- insertData
let filter = QueryFilter (TermQuery (Term "user" "bitemyapp") Nothing) True
search = mkSearch Nothing (Just filter)
myTweet <- searchTweet search
liftIO $ myTweet `shouldBe` Right exampleTweet
it "returns document for query filter, cached" $ withTestEnv $ do
_ <- insertData
let filter = QueryFilter (TermQuery (Term "user" "bitemyapp") Nothing) False
search = mkSearch Nothing (Just filter)
myTweet <- searchTweet search
liftIO $ myTweet `shouldBe` Right exampleTweet
describe "Aggregation API" $ do
it "returns term aggregation results" $ withTestEnv $ do
_ <- insertData
let terms = TermsAgg $ mkTermsAggregation "user"
let search = mkAggregateSearch Nothing $ mkAggregations "users" terms
searchExpectAggs search
searchValidBucketAgg search "users" toTerms
it "can give collection hint parameters to term aggregations" $ when' (atleast es13) $ withTestEnv $ do
_ <- insertData
let terms = TermsAgg $ (mkTermsAggregation "user") { termCollectMode = Just BreadthFirst }
let search = mkAggregateSearch Nothing $ mkAggregations "users" terms
searchExpectAggs search
searchValidBucketAgg search "users" toTerms
it "can give execution hint parameters to term aggregations" $ when' (atmost es11) $ withTestEnv $ do
_ <- insertData
searchTermsAggHint [Map, Ordinals]
it "can give execution hint parameters to term aggregations" $ when' (is es12) $ withTestEnv $ do
_ <- insertData
searchTermsAggHint [GlobalOrdinals, GlobalOrdinalsHash, GlobalOrdinalsLowCardinality, Map, Ordinals]
it "can give execution hint parameters to term aggregations" $ when' (atleast es12) $ withTestEnv $ do
_ <- insertData
searchTermsAggHint [GlobalOrdinals, GlobalOrdinalsHash, GlobalOrdinalsLowCardinality, Map]
-- Interaction of date serialization and date histogram aggregation is broken.
-- it "returns date histogram aggregation results" $ withTestEnv $ do
-- _ <- insertData
-- let histogram = DateHistogramAgg $ mkDateHistogram (FieldName "postDate") Minute
-- let search = mkAggregateSearch Nothing (mkAggregations "byDate" histogram)
-- searchExpectAggs search
-- searchValidBucketAgg search "byDate" toDateHistogram
-- it "returns date histogram using fractional date" $ withTestEnv $ do
-- _ <- insertData
-- let periods = [Year, Quarter, Month, Week, Day, Hour, Minute, Second]
-- let fractionals = map (FractionalInterval 1.5) [Weeks, Days, Hours, Minutes, Seconds]
-- let intervals = periods ++ fractionals
-- let histogram = mkDateHistogram (FieldName "postDate")
-- let search interval = mkAggregateSearch Nothing $ mkAggregations "byDate" $ DateHistogramAgg (histogram interval)
-- let expect interval = searchExpectAggs (search interval)
-- let valid interval = searchValidBucketAgg (search interval) "byDate" toDateHistogram
-- forM_ intervals expect
-- forM_ intervals valid
describe "Highlights API" $ do
it "returns highlight from query when there should be one" $ withTestEnv $ do
_ <- insertData
_ <- insertOther
let query = QueryMatchQuery $ mkMatchQuery (FieldName "_all") (QueryString "haskell")
let testHighlight = Highlights Nothing [FieldHighlight (FieldName "message") Nothing]
let search = mkHighlightSearch (Just query) testHighlight
myHighlight <- searchTweetHighlight search
liftIO $
myHighlight `shouldBe` Right (Just (M.fromList [("message",["Use <em>haskell</em>!"])]))
it "doesn't return highlight from a query when it shouldn't" $ withTestEnv $ do
_ <- insertData
_ <- insertOther
let query = QueryMatchQuery $ mkMatchQuery (FieldName "_all") (QueryString "haskell")
let testHighlight = Highlights Nothing [FieldHighlight (FieldName "user") Nothing]
let search = mkHighlightSearch (Just query) testHighlight
myHighlight <- searchTweetHighlight search
liftIO $
myHighlight `shouldBe` Right Nothing
describe "ToJSON RegexpFlags" $ do
it "generates the correct JSON for AllRegexpFlags" $
toJSON AllRegexpFlags `shouldBe` String "ALL"
it "generates the correct JSON for NoRegexpFlags" $
toJSON NoRegexpFlags `shouldBe` String "NONE"
it "generates the correct JSON for SomeRegexpFlags" $
let flags = AnyString :| [ Automaton
, Complement
, Empty
, Intersection
, Interval ]
in toJSON (SomeRegexpFlags flags) `shouldBe` String "ANYSTRING|AUTOMATON|COMPLEMENT|EMPTY|INTERSECTION|INTERVAL"
prop "removes duplicates from flags" $ \(flags :: RegexpFlags) ->
let String str = toJSON flags
flagStrs = T.splitOn "|" str
in noDuplicates flagStrs
describe "omitNulls" $ do
it "checks that omitNulls drops list elements when it should" $
let dropped = omitNulls $ [ "test1" .= (toJSON ([] :: [Int]))
, "test2" .= (toJSON ("some value" :: Text))]
in dropped `shouldBe` Object (HM.fromList [("test2", String "some value")])
it "checks that omitNulls doesn't drop list elements when it shouldn't" $
let notDropped = omitNulls $ [ "test1" .= (toJSON ([1] :: [Int]))
, "test2" .= (toJSON ("some value" :: Text))]
in notDropped `shouldBe` Object (HM.fromList [ ("test1", Array (V.fromList [Number 1.0]))
, ("test2", String "some value")])
it "checks that omitNulls drops non list elements when it should" $
let dropped = omitNulls $ [ "test1" .= (toJSON Null)
, "test2" .= (toJSON ("some value" :: Text))]
in dropped `shouldBe` Object (HM.fromList [("test2", String "some value")])
it "checks that omitNulls doesn't drop non list elements when it shouldn't" $
let notDropped = omitNulls $ [ "test1" .= (toJSON (1 :: Int))
, "test2" .= (toJSON ("some value" :: Text))]
in notDropped `shouldBe` Object (HM.fromList [ ("test1", Number 1.0)
, ("test2", String "some value")])
describe "Monoid (SearchHits a)" $ do
prop "abides the monoid laws" $ eq $
prop_Monoid (T :: T (SearchHits ()))
describe "mkDocVersion" $ do
prop "can never construct an out of range docVersion" $ \i ->
let res = mkDocVersion i
in case res of
Nothing -> property True
Just dv -> (dv >= minBound) .&&.
(dv <= maxBound) .&&.
docVersionNumber dv === i
describe "Enum DocVersion" $ do
it "follows the laws of Enum, Bounded" $ do
evaluate (succ maxBound :: DocVersion) `shouldThrow` anyErrorCall
evaluate (pred minBound :: DocVersion) `shouldThrow` anyErrorCall
evaluate (toEnum 0 :: DocVersion) `shouldThrow` anyErrorCall
evaluate (toEnum 9200000000000000001 :: DocVersion) `shouldThrow` anyErrorCall
enumFrom (pred maxBound :: DocVersion) `shouldBe` [pred maxBound, maxBound]
enumFrom (pred maxBound :: DocVersion) `shouldBe` [pred maxBound, maxBound]
enumFromThen minBound (pred maxBound :: DocVersion) `shouldBe` [minBound, pred maxBound]
| cies/bloodhound | tests/tests.hs | bsd-3-clause | 30,357 | 0 | 25 | 8,436 | 8,188 | 3,972 | 4,216 | 592 | 2 |
module Win32Bitmap where
import StdDIS
import Win32Types
import GDITypes
----------------------------------------------------------------
-- Resources
----------------------------------------------------------------
-- Yoiks - name clash
-- %dis bitmap x = addr ({LPTSTR} x)
--
-- type Bitmap = LPCTSTR
--
-- intToBitmap :: Int -> Bitmap
-- intToBitmap i = makeIntResource (toWord i)
--
-- %fun LoadBitmap :: MbHINSTANCE -> Bitmap -> IO HBITMAP
-- %fail { res1 == 0 } { ErrorString("LoadBitmap") }
--
-- %const Bitmap
-- % [ OBM_CLOSE = { MAKEINTRESOURCE(OBM_CLOSE) }
-- % , OBM_UPARROW = { MAKEINTRESOURCE(OBM_UPARROW) }
-- % , OBM_DNARROW = { MAKEINTRESOURCE(OBM_DNARROW) }
-- % , OBM_RGARROW = { MAKEINTRESOURCE(OBM_RGARROW) }
-- % , OBM_LFARROW = { MAKEINTRESOURCE(OBM_LFARROW) }
-- % , OBM_REDUCE = { MAKEINTRESOURCE(OBM_REDUCE) }
-- % , OBM_ZOOM = { MAKEINTRESOURCE(OBM_ZOOM) }
-- % , OBM_RESTORE = { MAKEINTRESOURCE(OBM_RESTORE) }
-- % , OBM_REDUCED = { MAKEINTRESOURCE(OBM_REDUCED) }
-- % , OBM_ZOOMD = { MAKEINTRESOURCE(OBM_ZOOMD) }
-- % , OBM_RESTORED = { MAKEINTRESOURCE(OBM_RESTORED) }
-- % , OBM_UPARROWD = { MAKEINTRESOURCE(OBM_UPARROWD) }
-- % , OBM_DNARROWD = { MAKEINTRESOURCE(OBM_DNARROWD) }
-- % , OBM_RGARROWD = { MAKEINTRESOURCE(OBM_RGARROWD) }
-- % , OBM_LFARROWD = { MAKEINTRESOURCE(OBM_LFARROWD) }
-- % , OBM_MNARROW = { MAKEINTRESOURCE(OBM_MNARROW) }
-- % , OBM_COMBO = { MAKEINTRESOURCE(OBM_COMBO) }
-- % , OBM_UPARROWI = { MAKEINTRESOURCE(OBM_UPARROWI) }
-- % , OBM_DNARROWI = { MAKEINTRESOURCE(OBM_DNARROWI) }
-- % , OBM_RGARROWI = { MAKEINTRESOURCE(OBM_RGARROWI) }
-- % , OBM_LFARROWI = { MAKEINTRESOURCE(OBM_LFARROWI) }
-- % , OBM_OLD_CLOSE = { MAKEINTRESOURCE(OBM_OLD_CLOSE) }
-- % , OBM_SIZE = { MAKEINTRESOURCE(OBM_SIZE) }
-- % , OBM_OLD_UPARROW = { MAKEINTRESOURCE(OBM_OLD_UPARROW) }
-- % , OBM_OLD_DNARROW = { MAKEINTRESOURCE(OBM_OLD_DNARROW) }
-- % , OBM_OLD_RGARROW = { MAKEINTRESOURCE(OBM_OLD_RGARROW) }
-- % , OBM_OLD_LFARROW = { MAKEINTRESOURCE(OBM_OLD_LFARROW) }
-- % , OBM_BTSIZE = { MAKEINTRESOURCE(OBM_BTSIZE) }
-- % , OBM_CHECK = { MAKEINTRESOURCE(OBM_CHECK) }
-- % , OBM_CHECKBOXES = { MAKEINTRESOURCE(OBM_CHECKBOXES) }
-- % , OBM_BTNCORNERS = { MAKEINTRESOURCE(OBM_BTNCORNERS) }
-- % , OBM_OLD_REDUCE = { MAKEINTRESOURCE(OBM_OLD_REDUCE) }
-- % , OBM_OLD_ZOOM = { MAKEINTRESOURCE(OBM_OLD_ZOOM) }
-- % , OBM_OLD_RESTORE = { MAKEINTRESOURCE(OBM_OLD_RESTORE) }
-- % ]
----------------------------------------------------------------
-- Raster Ops
----------------------------------------------------------------
type RasterOp3 = Word32
type RasterOp4 = Word32
sRCCOPY :: RasterOp3
sRCCOPY =
unsafePerformIO(
prim_Win32Bitmap_cpp_sRCCOPY >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Bitmap_cpp_sRCCOPY :: IO (Word32)
sRCPAINT :: RasterOp3
sRCPAINT =
unsafePerformIO(
prim_Win32Bitmap_cpp_sRCPAINT >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Bitmap_cpp_sRCPAINT :: IO (Word32)
sRCAND :: RasterOp3
sRCAND =
unsafePerformIO(
prim_Win32Bitmap_cpp_sRCAND >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Bitmap_cpp_sRCAND :: IO (Word32)
sRCINVERT :: RasterOp3
sRCINVERT =
unsafePerformIO(
prim_Win32Bitmap_cpp_sRCINVERT >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Bitmap_cpp_sRCINVERT :: IO (Word32)
sRCERASE :: RasterOp3
sRCERASE =
unsafePerformIO(
prim_Win32Bitmap_cpp_sRCERASE >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Bitmap_cpp_sRCERASE :: IO (Word32)
nOTSRCCOPY :: RasterOp3
nOTSRCCOPY =
unsafePerformIO(
prim_Win32Bitmap_cpp_nOTSRCCOPY >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Bitmap_cpp_nOTSRCCOPY :: IO (Word32)
nOTSRCERASE :: RasterOp3
nOTSRCERASE =
unsafePerformIO(
prim_Win32Bitmap_cpp_nOTSRCERASE >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Bitmap_cpp_nOTSRCERASE :: IO (Word32)
mERGECOPY :: RasterOp3
mERGECOPY =
unsafePerformIO(
prim_Win32Bitmap_cpp_mERGECOPY >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Bitmap_cpp_mERGECOPY :: IO (Word32)
mERGEPAINT :: RasterOp3
mERGEPAINT =
unsafePerformIO(
prim_Win32Bitmap_cpp_mERGEPAINT >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Bitmap_cpp_mERGEPAINT :: IO (Word32)
pATCOPY :: RasterOp3
pATCOPY =
unsafePerformIO(
prim_Win32Bitmap_cpp_pATCOPY >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Bitmap_cpp_pATCOPY :: IO (Word32)
pATPAINT :: RasterOp3
pATPAINT =
unsafePerformIO(
prim_Win32Bitmap_cpp_pATPAINT >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Bitmap_cpp_pATPAINT :: IO (Word32)
pATINVERT :: RasterOp3
pATINVERT =
unsafePerformIO(
prim_Win32Bitmap_cpp_pATINVERT >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Bitmap_cpp_pATINVERT :: IO (Word32)
dSTINVERT :: RasterOp3
dSTINVERT =
unsafePerformIO(
prim_Win32Bitmap_cpp_dSTINVERT >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Bitmap_cpp_dSTINVERT :: IO (Word32)
bLACKNESS :: RasterOp3
bLACKNESS =
unsafePerformIO(
prim_Win32Bitmap_cpp_bLACKNESS >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Bitmap_cpp_bLACKNESS :: IO (Word32)
wHITENESS :: RasterOp3
wHITENESS =
unsafePerformIO(
prim_Win32Bitmap_cpp_wHITENESS >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Bitmap_cpp_wHITENESS :: IO (Word32)
mAKEROP4 :: RasterOp3 -> RasterOp3 -> RasterOp4
mAKEROP4 arg1 arg2 =
unsafePerformIO(
prim_Win32Bitmap_cpp_mAKEROP4 arg1 arg2 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Bitmap_cpp_mAKEROP4 :: Word32 -> Word32 -> IO (Word32)
----------------------------------------------------------------
-- BITMAP
----------------------------------------------------------------
type BITMAP =
( LONG -- bmType
, LONG -- bmWidth
, LONG -- bmHeight
, LONG -- bmWidthBytes
, WORD -- bmPlanes
, WORD -- bmBitsPixel
, LPVOID -- bmBits
)
type LPBITMAP = Addr
setBITMAP :: LPBITMAP -> BITMAP -> IO ()
setBITMAP arg1 gc_arg1 =
case gc_arg1 of { (gc_arg2,gc_arg4,gc_arg6,gc_arg8,gc_arg10,gc_arg12,gc_arg14) ->
case ( fromIntegral gc_arg2) of { gc_arg3 ->
case ( fromIntegral gc_arg4) of { gc_arg5 ->
case ( fromIntegral gc_arg6) of { gc_arg7 ->
case ( fromIntegral gc_arg8) of { gc_arg9 ->
case ( fromIntegral gc_arg10) of { gc_arg11 ->
case ( fromIntegral gc_arg12) of { gc_arg13 ->
prim_Win32Bitmap_cpp_setBITMAP arg1 gc_arg3 gc_arg5 gc_arg7 gc_arg9 gc_arg11 gc_arg13 gc_arg14}}}}}}}
primitive prim_Win32Bitmap_cpp_setBITMAP :: Addr -> Int -> Int -> Int -> Int -> Word32 -> Word32 -> Addr -> IO ()
marshall_bITMAP_ :: BITMAP -> IO LPBITMAP
marshall_bITMAP_ bmp = do
lpbmp <- malloc sizeofBITMAP
setBITMAP lpbmp bmp
return lpbmp
----------------------------------------------------------------
-- Misc
----------------------------------------------------------------
deleteBitmap :: HBITMAP -> IO ()
deleteBitmap arg1 =
prim_Win32Bitmap_cpp_deleteBitmap arg1 >>= \ (gc_failed,gc_failstring) ->
if ( gc_failed /= (0::Int))
then unmarshall_string_ gc_failstring >>= ioError . userError
else (return (()))
primitive prim_Win32Bitmap_cpp_deleteBitmap :: Addr -> IO (Int,Addr)
createCompatibleBitmap :: HDC -> Int32 -> Int32 -> IO HBITMAP
createCompatibleBitmap arg1 gc_arg1 gc_arg2 =
case ( fromIntegral gc_arg1) of { arg2 ->
case ( fromIntegral gc_arg2) of { arg3 ->
prim_Win32Bitmap_cpp_createCompatibleBitmap arg1 arg2 arg3 >>= \ (res1,gc_failed,gc_failstring) ->
if ( gc_failed /= (0::Int))
then unmarshall_string_ gc_failstring >>= ioError . userError
else (return (res1))}}
primitive prim_Win32Bitmap_cpp_createCompatibleBitmap :: Addr -> Int -> Int -> IO (Addr,Int,Addr)
createBitmap :: INT -> INT -> UINT -> UINT -> MbLPVOID -> IO HBITMAP
createBitmap gc_arg1 gc_arg2 arg3 arg4 arg5 =
case ( fromIntegral gc_arg1) of { arg1 ->
case ( fromIntegral gc_arg2) of { arg2 ->
(case arg5 of {
Nothing -> (return (nullAddr));
(Just arg5) -> (return ((arg5)))
}) >>= \ (arg5) ->
prim_Win32Bitmap_cpp_createBitmap arg1 arg2 arg3 arg4 arg5 >>= \ (res1,gc_failed,gc_failstring) ->
if ( gc_failed /= (0::Int))
then unmarshall_string_ gc_failstring >>= ioError . userError
else (return (res1))}}
primitive prim_Win32Bitmap_cpp_createBitmap :: Int -> Int -> Word32 -> Word32 -> Addr -> IO (Addr,Int,Addr)
createBitmapIndirect :: LPBITMAP -> IO HBITMAP
createBitmapIndirect arg1 =
prim_Win32Bitmap_cpp_createBitmapIndirect arg1 >>= \ (res1,gc_failed,gc_failstring) ->
if ( gc_failed /= (0::Int))
then unmarshall_string_ gc_failstring >>= ioError . userError
else (return (res1))
primitive prim_Win32Bitmap_cpp_createBitmapIndirect :: Addr -> IO (Addr,Int,Addr)
createDIBPatternBrushPt :: LPVOID -> ColorFormat -> IO HBRUSH
createDIBPatternBrushPt arg1 arg2 =
prim_Win32Bitmap_cpp_createDIBPatternBrushPt arg1 arg2 >>= \ (res1,gc_failed,gc_failstring) ->
if ( gc_failed /= (0::Int))
then unmarshall_string_ gc_failstring >>= ioError . userError
else (return (res1))
primitive prim_Win32Bitmap_cpp_createDIBPatternBrushPt :: Addr -> Word32 -> IO (Addr,Int,Addr)
----------------------------------------------------------------
-- Querying
----------------------------------------------------------------
getBitmapDimensionEx :: HBITMAP -> IO SIZE
getBitmapDimensionEx h =
prim_Win32Bitmap_cpp_getBitmapDimensionEx h >>= \ (gc_res2,gc_res4,gc_failed,gc_failstring) ->
if ( gc_failed /= (0::Int))
then unmarshall_string_ gc_failstring >>= ioError . userError
else let gc_res1 = ( fromIntegral (gc_res2)) in
let gc_res3 = ( fromIntegral (gc_res4)) in
(return ((gc_res1,gc_res3)))
primitive prim_Win32Bitmap_cpp_getBitmapDimensionEx :: Addr -> IO (Int,Int,Int,Addr)
setBitmapDimensionEx :: HBITMAP -> SIZE -> IO SIZE
setBitmapDimensionEx h gc_arg1 =
case gc_arg1 of { (gc_arg2,gc_arg4) ->
case ( fromIntegral gc_arg2) of { gc_arg3 ->
case ( fromIntegral gc_arg4) of { gc_arg5 ->
prim_Win32Bitmap_cpp_setBitmapDimensionEx h gc_arg3 gc_arg5 >>= \ (gc_res2,gc_res4,gc_failed,gc_failstring) ->
if ( gc_failed /= (0::Int))
then unmarshall_string_ gc_failstring >>= ioError . userError
else let gc_res1 = ( fromIntegral (gc_res2)) in
let gc_res3 = ( fromIntegral (gc_res4)) in
(return ((gc_res1,gc_res3)))}}}
primitive prim_Win32Bitmap_cpp_setBitmapDimensionEx :: Addr -> Int -> Int -> IO (Int,Int,Int,Addr)
getBitmapInfo :: HBITMAP -> IO BITMAP
getBitmapInfo x =
prim_Win32Bitmap_cpp_getBitmapInfo x >>= \ (gc_res2,gc_res4,gc_res6,gc_res8,gc_res10,gc_res12,gc_res13,gc_failed,gc_failstring) ->
if ( gc_failed /= (0::Int))
then unmarshall_string_ gc_failstring >>= ioError . userError
else let gc_res1 = ( fromIntegral (gc_res2)) in
let gc_res3 = ( fromIntegral (gc_res4)) in
let gc_res5 = ( fromIntegral (gc_res6)) in
let gc_res7 = ( fromIntegral (gc_res8)) in
let gc_res9 = ( fromIntegral (gc_res10)) in
let gc_res11 = ( fromIntegral (gc_res12)) in
(return ((gc_res1,gc_res3,gc_res5,gc_res7,gc_res9,gc_res11,gc_res13)))
primitive prim_Win32Bitmap_cpp_getBitmapInfo :: Addr -> IO (Int,Int,Int,Int,Word32,Word32,Addr,Int,Addr)
----------------------------------------------------------------
--
----------------------------------------------------------------
type BitmapCompression = WORD
bI_RGB :: BitmapCompression
bI_RGB =
unsafePerformIO(
prim_Win32Bitmap_cpp_bI_RGB >>= \ (res1) ->
let gc_res1 = ( fromIntegral (res1)) in
(return (gc_res1)))
primitive prim_Win32Bitmap_cpp_bI_RGB :: IO (Word32)
bI_RLE8 :: BitmapCompression
bI_RLE8 =
unsafePerformIO(
prim_Win32Bitmap_cpp_bI_RLE8 >>= \ (res1) ->
let gc_res1 = ( fromIntegral (res1)) in
(return (gc_res1)))
primitive prim_Win32Bitmap_cpp_bI_RLE8 :: IO (Word32)
bI_RLE4 :: BitmapCompression
bI_RLE4 =
unsafePerformIO(
prim_Win32Bitmap_cpp_bI_RLE4 >>= \ (res1) ->
let gc_res1 = ( fromIntegral (res1)) in
(return (gc_res1)))
primitive prim_Win32Bitmap_cpp_bI_RLE4 :: IO (Word32)
bI_BITFIELDS :: BitmapCompression
bI_BITFIELDS =
unsafePerformIO(
prim_Win32Bitmap_cpp_bI_BITFIELDS >>= \ (res1) ->
let gc_res1 = ( fromIntegral (res1)) in
(return (gc_res1)))
primitive prim_Win32Bitmap_cpp_bI_BITFIELDS :: IO (Word32)
type ColorFormat = DWORD
dIB_PAL_COLORS :: ColorFormat
dIB_PAL_COLORS =
unsafePerformIO(
prim_Win32Bitmap_cpp_dIB_PAL_COLORS >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Bitmap_cpp_dIB_PAL_COLORS :: IO (Word32)
dIB_RGB_COLORS :: ColorFormat
dIB_RGB_COLORS =
unsafePerformIO(
prim_Win32Bitmap_cpp_dIB_RGB_COLORS >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Bitmap_cpp_dIB_RGB_COLORS :: IO (Word32)
----------------------------------------------------------------
-- BITMAPINFO
----------------------------------------------------------------
type LPBITMAPINFO = Addr
----------------------------------------------------------------
-- BITMAPINFOHEADER
----------------------------------------------------------------
type BITMAPINFOHEADER =
( DWORD -- biSize -- sizeof(BITMAPINFOHEADER)
, LONG -- biWidth
, LONG -- biHeight
, WORD -- biPlanes
, WORD -- biBitCount -- 1, 4, 8, 16, 24 or 32
, BitmapCompression -- biCompression
, DWORD -- biSizeImage
, LONG -- biXPelsPerMeter
, LONG -- biYPelsPerMeter
, Maybe DWORD -- biClrUsed
, Maybe DWORD -- biClrImportant
)
type LPBITMAPINFOHEADER = Addr
getBITMAPINFOHEADER_ :: LPBITMAPINFOHEADER -> IO BITMAPINFOHEADER
getBITMAPINFOHEADER_ arg1 =
prim_Win32Bitmap_cpp_getBITMAPINFOHEADER_ arg1 >>= \ (gc_res1,gc_res3,gc_res5,gc_res7,gc_res9,gc_res11,gc_res12,gc_res14,gc_res16,gc_res18,gc_res20) ->
let gc_res2 = ( fromIntegral (gc_res3)) in
let gc_res4 = ( fromIntegral (gc_res5)) in
let gc_res6 = ( fromIntegral (gc_res7)) in
let gc_res8 = ( fromIntegral (gc_res9)) in
let gc_res10 = ( fromIntegral (gc_res11)) in
let gc_res13 = ( fromIntegral (gc_res14)) in
let gc_res15 = ( fromIntegral (gc_res16)) in
(if 0 == (gc_res18)
then return Nothing
else (return ((Just gc_res18)))) >>= \ gc_res17 ->
(if 0 == (gc_res20)
then return Nothing
else (return ((Just gc_res20)))) >>= \ gc_res19 ->
(return ((gc_res1,gc_res2,gc_res4,gc_res6,gc_res8,gc_res10,gc_res12,gc_res13,gc_res15,gc_res17,gc_res19)))
primitive prim_Win32Bitmap_cpp_getBITMAPINFOHEADER_ :: Addr -> IO (Word32,Int,Int,Word32,Word32,Word32,Word32,Int,Int,Word32,Word32)
----------------------------------------------------------------
-- BITMAPFILEHEADER
----------------------------------------------------------------
type BITMAPFILEHEADER =
( WORD -- bfType -- "BM" == 0x4d42
, DWORD -- bfSize -- number of bytes in file
, WORD -- bfReserved1 -- == 0
, WORD -- bfReserved2 -- == 0
, DWORD -- bfOffBits -- == (char*) bits - (char*) filehdr
)
type LPBITMAPFILEHEADER = Addr
getBITMAPFILEHEADER :: LPBITMAPFILEHEADER -> IO BITMAPFILEHEADER
getBITMAPFILEHEADER arg1 =
prim_Win32Bitmap_cpp_getBITMAPFILEHEADER arg1 >>= \ (gc_res2,gc_res3,gc_res5,gc_res7,gc_res8) ->
let gc_res1 = ( fromIntegral (gc_res2)) in
let gc_res4 = ( fromIntegral (gc_res5)) in
let gc_res6 = ( fromIntegral (gc_res7)) in
(return ((gc_res1,gc_res3,gc_res4,gc_res6,gc_res8)))
primitive prim_Win32Bitmap_cpp_getBITMAPFILEHEADER :: Addr -> IO (Word32,Word32,Word32,Word32,Word32)
sizeofBITMAP :: Word32
sizeofBITMAP =
unsafePerformIO(
prim_Win32Bitmap_cpp_sizeofBITMAP >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Bitmap_cpp_sizeofBITMAP :: IO (Word32)
sizeofBITMAPINFO :: Word32
sizeofBITMAPINFO =
unsafePerformIO(
prim_Win32Bitmap_cpp_sizeofBITMAPINFO >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Bitmap_cpp_sizeofBITMAPINFO :: IO (Word32)
sizeofBITMAPINFOHEADER :: Word32
sizeofBITMAPINFOHEADER =
unsafePerformIO(
prim_Win32Bitmap_cpp_sizeofBITMAPINFOHEADER >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Bitmap_cpp_sizeofBITMAPINFOHEADER :: IO (Word32)
sizeofBITMAPFILEHEADER :: Word32
sizeofBITMAPFILEHEADER =
unsafePerformIO(
prim_Win32Bitmap_cpp_sizeofBITMAPFILEHEADER >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Bitmap_cpp_sizeofBITMAPFILEHEADER :: IO (Word32)
sizeofLPBITMAPFILEHEADER :: Word32
sizeofLPBITMAPFILEHEADER =
unsafePerformIO(
prim_Win32Bitmap_cpp_sizeofLPBITMAPFILEHEADER >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Bitmap_cpp_sizeofLPBITMAPFILEHEADER :: IO (Word32)
----------------------------------------------------------------
-- CreateBMPFile
----------------------------------------------------------------
-- A (large) helper function - courtesy of Microsoft
-- Includes "dumpBMP.c" for non-ghc backends.
createBMPFile :: String -> HBITMAP -> HDC -> IO ()
createBMPFile gc_arg1 arg2 arg3 =
(marshall_string_ gc_arg1) >>= \ (arg1) ->
prim_Win32Bitmap_cpp_createBMPFile arg1 arg2 arg3
primitive prim_Win32Bitmap_cpp_createBMPFile :: Addr -> Addr -> Addr -> IO ()
----------------------------------------------------------------
-- Device Independent Bitmaps
----------------------------------------------------------------
cBM_INIT :: DWORD
cBM_INIT =
unsafePerformIO(
prim_Win32Bitmap_cpp_cBM_INIT >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Bitmap_cpp_cBM_INIT :: IO (Word32)
getDIBits :: HDC -> HBITMAP -> INT -> INT -> MbLPVOID -> LPBITMAPINFO -> ColorFormat -> IO INT
getDIBits arg1 arg2 gc_arg1 gc_arg2 arg5 arg6 arg7 =
case ( fromIntegral gc_arg1) of { arg3 ->
case ( fromIntegral gc_arg2) of { arg4 ->
(case arg5 of {
Nothing -> (return (nullAddr));
(Just arg5) -> (return ((arg5)))
}) >>= \ (arg5) ->
prim_Win32Bitmap_cpp_getDIBits arg1 arg2 arg3 arg4 arg5 arg6 arg7 >>= \ (res1,gc_failed,gc_failstring) ->
if ( gc_failed /= (0::Int))
then unmarshall_string_ gc_failstring >>= ioError . userError
else let gc_res1 = ( fromIntegral (res1)) in
(return (gc_res1))}}
primitive prim_Win32Bitmap_cpp_getDIBits :: Addr -> Addr -> Int -> Int -> Addr -> Addr -> Word32 -> IO (Int,Int,Addr)
setDIBits :: HDC -> HBITMAP -> INT -> INT -> LPVOID -> LPBITMAPINFO -> ColorFormat -> IO INT
setDIBits arg1 arg2 gc_arg1 gc_arg2 arg5 arg6 arg7 =
case ( fromIntegral gc_arg1) of { arg3 ->
case ( fromIntegral gc_arg2) of { arg4 ->
prim_Win32Bitmap_cpp_setDIBits arg1 arg2 arg3 arg4 arg5 arg6 arg7 >>= \ (res1,gc_failed,gc_failstring) ->
if ( gc_failed /= (0::Int))
then unmarshall_string_ gc_failstring >>= ioError . userError
else let gc_res1 = ( fromIntegral (res1)) in
(return (gc_res1))}}
primitive prim_Win32Bitmap_cpp_setDIBits :: Addr -> Addr -> Int -> Int -> Addr -> Addr -> Word32 -> IO (Int,Int,Addr)
createDIBitmap :: HDC -> LPBITMAPINFOHEADER -> DWORD -> LPVOID -> LPBITMAPINFO -> ColorFormat -> IO HBITMAP
createDIBitmap arg1 arg2 arg3 arg4 arg5 arg6 =
prim_Win32Bitmap_cpp_createDIBitmap arg1 arg2 arg3 arg4 arg5 arg6 >>= \ (res1,gc_failed,gc_failstring) ->
if ( gc_failed /= (0::Int))
then unmarshall_string_ gc_failstring >>= ioError . userError
else (return (res1))
primitive prim_Win32Bitmap_cpp_createDIBitmap :: Addr -> Addr -> Word32 -> Addr -> Addr -> Word32 -> IO (Addr,Int,Addr)
----------------------------------------------------------------
-- End
----------------------------------------------------------------
needPrims_hugs 2
| OS2World/DEV-UTIL-HUGS | libraries/win32/Win32Bitmap.hs | bsd-3-clause | 19,802 | 174 | 31 | 3,400 | 4,833 | 2,679 | 2,154 | -1 | -1 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Duration.DE.Corpus
( corpus
) where
import Prelude
import Data.String
import Duckling.Duration.Types
import Duckling.Locale
import Duckling.Resolve
import Duckling.Testing.Types
import Duckling.TimeGrain.Types (Grain(..))
corpus :: Corpus
corpus = (testContext {locale = makeLocale DE Nothing}, testOptions, allExamples)
allExamples :: [Example]
allExamples = concat
[ examples (DurationData 1 Second)
[ "ein sekunde"
, "zirka eine sekunde"
]
, examples (DurationData 30 Minute)
[ "1/2 stunde"
, "1/2stunde"
, "eine halbe stunde"
, "einer halben stunde"
, "halbe stunde"
, "halben stunde"
, "ungefahr einer halben stunde"
]
, examples (DurationData 15 Minute)
[ "einer Viertelstunde"
, "eine viertelstunde"
, "ViErTelStUnDe"
, "genau viertelstunde"
]
, examples (DurationData 45 Minute)
[ "3/4 stunde"
, "3/4stunde"
, "eine dreiviertel stunde"
, "einer dreiviertel stunde"
, "dreiviertel stunde"
, "drei viertelstunden"
]
, examples (DurationData 92 Minute)
[ "92 minuten"
, "zweiundneunzig minuten"
, "eine Stunde und zweiunddreißig Minuten"
, "ein stunde und zweiunddreissig minuten"
]
, examples (DurationData 30 Day)
[ "30 tage"
, "dreißig tage"
, "dreissig tage"
]
, examples (DurationData 7 Week)
[ "7 Wochen"
, "sieben wochen"
]
, examples (DurationData 90 Minute)
[ "1,5 stunden"
, "1,5 stunde"
, "90 min"
, "90min"
]
, examples (DurationData 75 Minute)
[ "1,25 stunden"
]
, examples (DurationData 31719604 Second)
[ "1 Jahr, 2 Tage, 3 Stunden und 4 Sekunden"
, "1 Jahr 2 Tage 3 Stunden und 4 Sekunden"
]
, examples (DurationData 330 Second)
[ "5 und eine halbe Minuten"
, "5,5 min"
]
, examples (DurationData 330 Minute)
[ "5 und eine halbe stunden"
, "5,5 stunde"
, "exakt 5,5 stunden"
]
, examples (DurationData 930 Second)
[ "15,5 minuten"
, "15,5 minute"
, "15,5 min"
]
]
| facebookincubator/duckling | Duckling/Duration/DE/Corpus.hs | bsd-3-clause | 2,814 | 0 | 9 | 1,088 | 449 | 262 | 187 | 70 | 1 |
module MyCloud
( module MyCloud.Types
--, module MyCloud.Files
, runMyCloud
, postgresConf
-- * DB queries
, recentEvents
) where
import Control.Concurrent.MState
import Control.Monad.Reader
--import Database.HDBC.PostgreSQL
import Network
import qualified Data.Map as M
import MyCloud.DB
import MyCloud.Internal.Types
import MyCloud.Types
--import MyCloud.Files
postgresConf :: Config
postgresConf = Config
{ runOn = PortNumber 7767
, encryption = ForceAES "aes.key"
, postgresqlConnection = "user=mycloud dbname=mycloud password=test"
}
initialState :: CloudState
initialState = CloudState
{ connectedClients = M.empty
}
runMyCloud :: Config -> MyCloud a -> IO a
runMyCloud cfg (MyCloud go) =
runReaderT (evalMState True go initialState) cfg
| mcmaniac/mycloud | src/MyCloud.hs | bsd-3-clause | 805 | 0 | 7 | 156 | 170 | 101 | 69 | 23 | 1 |
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.NV.DepthClamp
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.NV.DepthClamp (
-- * Extension Support
glGetNVDepthClamp,
gl_NV_depth_clamp,
-- * Enums
pattern GL_DEPTH_CLAMP_NV
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
| haskell-opengl/OpenGLRaw | src/Graphics/GL/NV/DepthClamp.hs | bsd-3-clause | 632 | 0 | 5 | 91 | 47 | 36 | 11 | 7 | 0 |
{-# OPTIONS_GHC -fno-warn-orphans -fno-warn-incomplete-patterns #-}
module Test.Distribution.Version (properties) where
import Distribution.Version
import Test.QuickCheck
import Test.QuickCheck.Utils
import qualified Test.Laws as Laws
import Control.Monad (liftM, liftM2)
import Data.Maybe (isJust, fromJust)
import Data.List (sort, sortBy, nub)
import Data.Ord (comparing)
properties :: [Property]
properties =
-- properties to validate the test framework
[ property prop_nonNull
, property prop_gen_intervals1
, property prop_gen_intervals2
, property prop_equivalentVersionRange
, property prop_intermediateVersion
-- the basic syntactic version range functions
, property prop_anyVersion
, property prop_noVersion
, property prop_thisVersion
, property prop_notThisVersion
, property prop_laterVersion
, property prop_orLaterVersion
, property prop_earlierVersion
, property prop_orEarlierVersion
, property prop_unionVersionRanges
, property prop_intersectVersionRanges
, property prop_withinVersion
, property prop_foldVersionRange
-- the semantic query functions
, property prop_isAnyVersion1
, property prop_isAnyVersion2
, property prop_isNoVersion
, property prop_isSpecificVersion1
, property prop_isSpecificVersion2
, property prop_simplifyVersionRange1
, property prop_simplifyVersionRange1'
, property prop_simplifyVersionRange2
, property prop_simplifyVersionRange2'
, property prop_simplifyVersionRange2'' --FIXME
-- converting between version ranges and version intervals
, property prop_to_intervals
, property prop_to_intervals_canonical
, property prop_to_intervals_canonical'
, property prop_from_intervals
, property prop_to_from_intervals
, property prop_from_to_intervals
, property prop_from_to_intervals'
-- union and intersection of version intervals
, property prop_unionVersionIntervals
, property prop_unionVersionIntervals_idempotent
, property prop_unionVersionIntervals_commutative
, property prop_unionVersionIntervals_associative
, property prop_intersectVersionIntervals
, property prop_intersectVersionIntervals_idempotent
, property prop_intersectVersionIntervals_commutative
, property prop_intersectVersionIntervals_associative
, property prop_union_intersect_distributive
, property prop_intersect_union_distributive
]
instance Arbitrary Version where
arbitrary = do
branch <- smallListOf1 $
frequency [(3, return 0)
,(3, return 1)
,(2, return 2)
,(1, return 3)]
return (Version branch []) -- deliberate []
where
smallListOf1 = adjustSize (\n -> min 5 (n `div` 3)) . listOf1
shrink (Version branch []) =
[ Version branch' [] | branch' <- shrink branch, not (null branch') ]
shrink (Version branch _tags) =
[ Version branch [] ]
instance Arbitrary VersionRange where
arbitrary = sized verRangeExp
where
verRangeExp n = frequency $
[ (2, return anyVersion)
, (1, liftM thisVersion arbitrary)
, (1, liftM laterVersion arbitrary)
, (1, liftM orLaterVersion arbitrary)
, (1, liftM earlierVersion arbitrary)
, (1, liftM orEarlierVersion arbitrary)
, (1, liftM withinVersion arbitrary)
] ++ if n == 0 then [] else
[ (2, liftM2 unionVersionRanges verRangeExp2 verRangeExp2)
, (2, liftM2 intersectVersionRanges verRangeExp2 verRangeExp2)
]
where
verRangeExp2 = verRangeExp (n `div` 2)
---------------------------
-- VersionRange properties
--
prop_nonNull :: Version -> Bool
prop_nonNull = not . null . versionBranch
prop_anyVersion :: Version -> Bool
prop_anyVersion v' =
withinRange v' anyVersion == True
prop_noVersion :: Version -> Bool
prop_noVersion v' =
withinRange v' noVersion == False
prop_thisVersion :: Version -> Version -> Bool
prop_thisVersion v v' =
withinRange v' (thisVersion v)
== (v' == v)
prop_notThisVersion :: Version -> Version -> Bool
prop_notThisVersion v v' =
withinRange v' (notThisVersion v)
== (v' /= v)
prop_laterVersion :: Version -> Version -> Bool
prop_laterVersion v v' =
withinRange v' (laterVersion v)
== (v' > v)
prop_orLaterVersion :: Version -> Version -> Bool
prop_orLaterVersion v v' =
withinRange v' (orLaterVersion v)
== (v' >= v)
prop_earlierVersion :: Version -> Version -> Bool
prop_earlierVersion v v' =
withinRange v' (earlierVersion v)
== (v' < v)
prop_orEarlierVersion :: Version -> Version -> Bool
prop_orEarlierVersion v v' =
withinRange v' (orEarlierVersion v)
== (v' <= v)
prop_unionVersionRanges :: VersionRange -> VersionRange -> Version -> Bool
prop_unionVersionRanges vr1 vr2 v' =
withinRange v' (unionVersionRanges vr1 vr2)
== (withinRange v' vr1 || withinRange v' vr2)
prop_intersectVersionRanges :: VersionRange -> VersionRange -> Version -> Bool
prop_intersectVersionRanges vr1 vr2 v' =
withinRange v' (intersectVersionRanges vr1 vr2)
== (withinRange v' vr1 && withinRange v' vr2)
prop_withinVersion :: Version -> Version -> Bool
prop_withinVersion v v' =
withinRange v' (withinVersion v)
== (v' >= v && v' < upper v)
where
upper (Version lower t) = Version (init lower ++ [last lower + 1]) t
prop_foldVersionRange :: VersionRange -> Bool
prop_foldVersionRange range =
range
== foldVersionRange anyVersion thisVersion
laterVersion earlierVersion
(\v _ -> withinVersion v)
unionVersionRanges intersectVersionRanges
range
prop_isAnyVersion1 :: VersionRange -> Version -> Property
prop_isAnyVersion1 range version =
isAnyVersion range ==> withinRange version range
prop_isAnyVersion2 :: VersionRange -> Property
prop_isAnyVersion2 range =
isAnyVersion range ==>
foldVersionRange True (\_ -> False) (\_ -> False) (\_ -> False)
(\_ _ -> False) (\_ _ -> False) (\_ _ -> False)
(simplifyVersionRange range)
prop_isNoVersion :: VersionRange -> Version -> Property
prop_isNoVersion range version =
isNoVersion range ==> not (withinRange version range)
prop_isSpecificVersion1 :: VersionRange -> NonEmptyList Version -> Property
prop_isSpecificVersion1 range (NonEmpty versions) =
isJust version && not (null versions') ==>
allEqual (fromJust version : versions')
where
version = isSpecificVersion range
versions' = filter (`withinRange` range) versions
allEqual xs = and (zipWith (==) xs (tail xs))
prop_isSpecificVersion2 :: VersionRange -> Property
prop_isSpecificVersion2 range =
isJust version ==>
foldVersionRange Nothing Just (\_ -> Nothing) (\_ -> Nothing)
(\_ _ -> Nothing) (\_ _ -> Nothing) (\_ _ -> Nothing)
(simplifyVersionRange range)
== version
where
version = isSpecificVersion range
-- | 'simplifyVersionRange' is a semantic identity on 'VersionRange'.
--
prop_simplifyVersionRange1 :: VersionRange -> Version -> Bool
prop_simplifyVersionRange1 range version =
withinRange version range == withinRange version (simplifyVersionRange range)
prop_simplifyVersionRange1' :: VersionRange -> Bool
prop_simplifyVersionRange1' range =
range `equivalentVersionRange` (simplifyVersionRange range)
-- | 'simplifyVersionRange' produces a canonical form for ranges with
-- equivalent semantics.
--
prop_simplifyVersionRange2 :: VersionRange -> VersionRange -> Version -> Property
prop_simplifyVersionRange2 r r' v =
r /= r' && simplifyVersionRange r == simplifyVersionRange r' ==>
withinRange v r == withinRange v r'
prop_simplifyVersionRange2' :: VersionRange -> VersionRange -> Property
prop_simplifyVersionRange2' r r' =
r /= r' && simplifyVersionRange r == simplifyVersionRange r' ==>
r `equivalentVersionRange` r'
prop_simplifyVersionRange2'' :: VersionRange -> VersionRange -> Property
prop_simplifyVersionRange2'' r r' =
r /= r' && r `equivalentVersionRange` r' ==>
simplifyVersionRange r == simplifyVersionRange r'
--------------------
-- VersionIntervals
--
-- | Generating VersionIntervals
--
-- This is a tad tricky as VersionIntervals is an abstract type, so we first
-- make a local type for generating the internal representation. Then we check
-- that this lets us construct valid 'VersionIntervals'.
--
newtype VersionIntervals' = VersionIntervals' [VersionInterval]
deriving (Eq, Show)
instance Arbitrary VersionIntervals' where
arbitrary = do
ubound <- arbitrary
bounds <- arbitrary
let intervals = mergeTouching
. map fixEmpty
. replaceUpper ubound
. pairs
. sortBy (comparing fst)
$ bounds
return (VersionIntervals' intervals)
where
pairs ((l, lb):(u, ub):bs) = (LowerBound l lb, UpperBound u ub)
: pairs bs
pairs _ = []
replaceUpper NoUpperBound [(l,_)] = [(l, NoUpperBound)]
replaceUpper NoUpperBound (i:is) = i : replaceUpper NoUpperBound is
replaceUpper _ is = is
-- merge adjacent intervals that touch
mergeTouching (i1@(l,u):i2@(l',u'):is)
| doesNotTouch u l' = i1 : mergeTouching (i2:is)
| otherwise = mergeTouching ((l,u'):is)
mergeTouching is = is
doesNotTouch :: UpperBound -> LowerBound -> Bool
doesNotTouch NoUpperBound _ = False
doesNotTouch (UpperBound u ub) (LowerBound l lb) =
u < l
|| (u == l && ub == ExclusiveBound && lb == ExclusiveBound)
fixEmpty (LowerBound l _, UpperBound u _)
| l == u = (LowerBound l InclusiveBound, UpperBound u InclusiveBound)
fixEmpty i = i
shrink (VersionIntervals' intervals) =
[ VersionIntervals' intervals' | intervals' <- shrink intervals ]
instance Arbitrary Bound where
arbitrary = elements [ExclusiveBound, InclusiveBound]
instance Arbitrary LowerBound where
arbitrary = liftM2 LowerBound arbitrary arbitrary
instance Arbitrary UpperBound where
arbitrary = oneof [return NoUpperBound
,liftM2 UpperBound arbitrary arbitrary]
-- | Check that our VersionIntervals' arbitrary instance generates intervals
-- that satisfies the invariant.
--
prop_gen_intervals1 :: VersionIntervals' -> Bool
prop_gen_intervals1 (VersionIntervals' intervals) =
isJust (mkVersionIntervals intervals)
instance Arbitrary VersionIntervals where
arbitrary = do
VersionIntervals' intervals <- arbitrary
case mkVersionIntervals intervals of
Just xs -> return xs
-- | Check that constructing our intervals type and converting it to a
-- 'VersionRange' and then into the true intervals type gives us back
-- the exact same sequence of intervals. This tells us that our arbitrary
-- instance for 'VersionIntervals'' is ok.
--
prop_gen_intervals2 :: VersionIntervals' -> Bool
prop_gen_intervals2 (VersionIntervals' intervals') =
asVersionIntervals (fromVersionIntervals intervals) == intervals'
where
Just intervals = mkVersionIntervals intervals'
-- | Check that 'VersionIntervals' models 'VersionRange' via
-- 'toVersionIntervals'.
--
prop_to_intervals :: VersionRange -> Version -> Bool
prop_to_intervals range version =
withinRange version range == withinIntervals version intervals
where
intervals = toVersionIntervals range
-- | Check that semantic equality on 'VersionRange's is the same as converting
-- to 'VersionIntervals' and doing syntactic equality.
--
prop_to_intervals_canonical :: VersionRange -> VersionRange -> Property
prop_to_intervals_canonical r r' =
r /= r' && r `equivalentVersionRange` r' ==>
toVersionIntervals r == toVersionIntervals r'
prop_to_intervals_canonical' :: VersionRange -> VersionRange -> Property
prop_to_intervals_canonical' r r' =
r /= r' && toVersionIntervals r == toVersionIntervals r' ==>
r `equivalentVersionRange` r'
-- | Check that 'VersionIntervals' models 'VersionRange' via
-- 'fromVersionIntervals'.
--
prop_from_intervals :: VersionIntervals -> Version -> Bool
prop_from_intervals intervals version =
withinRange version range == withinIntervals version intervals
where
range = fromVersionIntervals intervals
-- | @'toVersionIntervals' . 'fromVersionIntervals'@ is an exact identity on
-- 'VersionIntervals'.
--
prop_to_from_intervals :: VersionIntervals -> Bool
prop_to_from_intervals intervals =
toVersionIntervals (fromVersionIntervals intervals) == intervals
-- | @'fromVersionIntervals' . 'toVersionIntervals'@ is a semantic identity on
-- 'VersionRange', though not necessarily a syntactic identity.
--
prop_from_to_intervals :: VersionRange -> Bool
prop_from_to_intervals range =
range' `equivalentVersionRange` range
where
range' = fromVersionIntervals (toVersionIntervals range)
-- | Equivalent of 'prop_from_to_intervals'
--
prop_from_to_intervals' :: VersionRange -> Version -> Bool
prop_from_to_intervals' range version =
withinRange version range' == withinRange version range
where
range' = fromVersionIntervals (toVersionIntervals range)
-- | The semantics of 'unionVersionIntervals' is (||).
--
prop_unionVersionIntervals :: VersionIntervals -> VersionIntervals
-> Version -> Bool
prop_unionVersionIntervals is1 is2 v =
withinIntervals v (unionVersionIntervals is1 is2)
== (withinIntervals v is1 || withinIntervals v is2)
-- | 'unionVersionIntervals' is idempotent
--
prop_unionVersionIntervals_idempotent :: VersionIntervals -> Bool
prop_unionVersionIntervals_idempotent =
Laws.idempotent_binary unionVersionIntervals
-- | 'unionVersionIntervals' is commutative
--
prop_unionVersionIntervals_commutative :: VersionIntervals
-> VersionIntervals -> Bool
prop_unionVersionIntervals_commutative =
Laws.commutative unionVersionIntervals
-- | 'unionVersionIntervals' is associative
--
prop_unionVersionIntervals_associative :: VersionIntervals
-> VersionIntervals
-> VersionIntervals -> Bool
prop_unionVersionIntervals_associative =
Laws.associative unionVersionIntervals
-- | The semantics of 'intersectVersionIntervals' is (&&).
--
prop_intersectVersionIntervals :: VersionIntervals -> VersionIntervals
-> Version -> Bool
prop_intersectVersionIntervals is1 is2 v =
withinIntervals v (intersectVersionIntervals is1 is2)
== (withinIntervals v is1 && withinIntervals v is2)
-- | 'intersectVersionIntervals' is idempotent
--
prop_intersectVersionIntervals_idempotent :: VersionIntervals -> Bool
prop_intersectVersionIntervals_idempotent =
Laws.idempotent_binary intersectVersionIntervals
-- | 'intersectVersionIntervals' is commutative
--
prop_intersectVersionIntervals_commutative :: VersionIntervals
-> VersionIntervals -> Bool
prop_intersectVersionIntervals_commutative =
Laws.commutative intersectVersionIntervals
-- | 'intersectVersionIntervals' is associative
--
prop_intersectVersionIntervals_associative :: VersionIntervals
-> VersionIntervals
-> VersionIntervals -> Bool
prop_intersectVersionIntervals_associative =
Laws.associative intersectVersionIntervals
-- | 'unionVersionIntervals' distributes over 'intersectVersionIntervals'
--
prop_union_intersect_distributive :: Property
prop_union_intersect_distributive =
Laws.distributive_left unionVersionIntervals intersectVersionIntervals
.&. Laws.distributive_right unionVersionIntervals intersectVersionIntervals
-- | 'intersectVersionIntervals' distributes over 'unionVersionIntervals'
--
prop_intersect_union_distributive :: Property
prop_intersect_union_distributive =
Laws.distributive_left intersectVersionIntervals unionVersionIntervals
.&. Laws.distributive_right intersectVersionIntervals unionVersionIntervals
--------------------------------
-- equivalentVersionRange helper
prop_equivalentVersionRange :: VersionRange -> VersionRange
-> Version -> Property
prop_equivalentVersionRange range range' version =
equivalentVersionRange range range' && range /= range' ==>
withinRange version range == withinRange version range'
equivalentVersionRange :: VersionRange -> VersionRange -> Bool
equivalentVersionRange vr1 vr2 =
let allVersionsUsed = nub (sort (versionsUsed vr1 ++ versionsUsed vr2))
minPoint = Version [0] []
maxPoint | null allVersionsUsed = minPoint
| otherwise = case maximum allVersionsUsed of
Version vs _ -> Version (vs ++ [1]) []
probeVersions = minPoint : maxPoint
: intermediateVersions allVersionsUsed
in all (\v -> withinRange v vr1 == withinRange v vr2) probeVersions
where
versionsUsed = foldVersionRange [] (\x->[x]) (\x->[x]) (\x->[x])
(\x y -> [x,y]) (++) (++)
intermediateVersions (v1:v2:vs) = v1 : intermediateVersion v1 v2
: intermediateVersions (v2:vs)
intermediateVersions vs = vs
intermediateVersion :: Version -> Version -> Version
intermediateVersion v1 v2 | v1 >= v2 = error "intermediateVersion: v1 >= v2"
intermediateVersion (Version v1 _) (Version v2 _) =
Version (intermediateList v1 v2) []
where
intermediateList :: [Int] -> [Int] -> [Int]
intermediateList [] (_:_) = [0]
intermediateList (x:xs) (y:ys)
| x < y = x : xs ++ [0]
| otherwise = x : intermediateList xs ys
prop_intermediateVersion :: Version -> Version -> Property
prop_intermediateVersion v1 v2 =
(v1 /= v2) && not (adjacentVersions v1 v2) ==>
if v1 < v2
then let v = intermediateVersion v1 v2
in (v1 < v && v < v2)
else let v = intermediateVersion v2 v1
in v1 > v && v > v2
adjacentVersions :: Version -> Version -> Bool
adjacentVersions (Version v1 _) (Version v2 _) = v1 ++ [0] == v2
|| v2 ++ [0] == v1
| dcreager/cabal | tests/Test/Distribution/Version.hs | bsd-3-clause | 18,209 | 0 | 16 | 3,848 | 4,169 | 2,176 | 1,993 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
-- | Semantics of abilities in terms of actions and the AI procedure
-- for picking the best action for an actor.
module Game.LambdaHack.Client.AI.HandleAbilityClient
( actionStrategy
) where
import Prelude ()
import Prelude.Compat
import Control.Arrow (second)
import Control.Exception.Assert.Sugar
import Control.Monad (mzero, msum)
import qualified Data.EnumMap.Strict as EM
import qualified Data.EnumSet as ES
import Data.Function
import Data.List (groupBy, sortBy, intersect, foldl')
import qualified Data.Map.Strict as M
import Data.Maybe
import Data.Ord
import Data.Ratio
import Data.Text (Text)
import Game.LambdaHack.Client.AI.ConditionClient
import Game.LambdaHack.Client.AI.Preferences
import Game.LambdaHack.Client.AI.Strategy
import Game.LambdaHack.Client.BfsClient
import Game.LambdaHack.Client.CommonClient
import Game.LambdaHack.Client.MonadClient
import Game.LambdaHack.Client.State
import Game.LambdaHack.Common.Ability
import Game.LambdaHack.Common.Actor
import Game.LambdaHack.Common.ActorState
import Game.LambdaHack.Common.Faction
import Game.LambdaHack.Common.Frequency
import Game.LambdaHack.Common.Item
import Game.LambdaHack.Common.ItemStrongest
import qualified Game.LambdaHack.Common.Kind as Kind
import Game.LambdaHack.Common.Level
import Game.LambdaHack.Common.Misc
import Game.LambdaHack.Common.MonadStateRead
import Game.LambdaHack.Common.Perception
import Game.LambdaHack.Common.Point
import Game.LambdaHack.Common.Request
import Game.LambdaHack.Common.State
import qualified Game.LambdaHack.Common.Tile as Tile
import Game.LambdaHack.Common.Time
import Game.LambdaHack.Common.Vector
import qualified Game.LambdaHack.Content.ItemKind as IK
import Game.LambdaHack.Content.ModeKind
import qualified Game.LambdaHack.Content.TileKind as TK
type ToAny a = Strategy (RequestTimed a) -> Strategy RequestAnyAbility
toAny :: ToAny a
toAny strat = RequestAnyAbility <$> strat
-- | AI strategy based on actor's sight, smell, etc.
-- Never empty.
actionStrategy :: forall m. MonadClient m
=> ActorId -> m (Strategy RequestAnyAbility)
actionStrategy aid = do
body <- getsState $ getActorBody aid
activeItems <- activeItemsClient aid
fact <- getsState $ (EM.! bfid body) . sfactionD
condTgtEnemyPresent <- condTgtEnemyPresentM aid
condTgtEnemyRemembered <- condTgtEnemyRememberedM aid
condTgtEnemyAdjFriend <- condTgtEnemyAdjFriendM aid
condAnyFoeAdj <- condAnyFoeAdjM aid
threatDistL <- threatDistList aid
condHpTooLow <- condHpTooLowM aid
condOnTriggerable <- condOnTriggerableM aid
condBlocksFriends <- condBlocksFriendsM aid
condNoEqpWeapon <- condNoEqpWeaponM aid
let condNoUsableWeapon = all (not . isMelee) activeItems
condEnoughGear <- condEnoughGearM aid
condFloorWeapon <- condFloorWeaponM aid
condCanProject <- condCanProjectM False aid
condNotCalmEnough <- condNotCalmEnoughM aid
condDesirableFloorItem <- condDesirableFloorItemM aid
condMeleeBad <- condMeleeBadM aid
condTgtNonmoving <- condTgtNonmovingM aid
aInAmbient <- getsState $ actorInAmbient body
explored <- getsClient sexplored
(fleeL, badVic) <- fleeList aid
let lidExplored = ES.member (blid body) explored
panicFleeL = fleeL ++ badVic
actorShines = sumSlotNoFilter IK.EqpSlotAddLight activeItems > 0
condThreatAdj = not $ null $ takeWhile ((== 1) . fst) threatDistL
condThreatAtHand = not $ null $ takeWhile ((<= 2) . fst) threatDistL
condThreatNearby = not $ null $ takeWhile ((<= 9) . fst) threatDistL
speed1_5 = speedScale (3%2) (bspeed body activeItems)
condFastThreatAdj = any (\(_, (_, b)) -> bspeed b activeItems > speed1_5)
$ takeWhile ((== 1) . fst) threatDistL
heavilyDistressed = -- actor hit by a proj or similarly distressed
deltaSerious (bcalmDelta body)
let actorMaxSk = sumSkills activeItems
abInMaxSkill ab = EM.findWithDefault 0 ab actorMaxSk > 0
stratToFreq :: MonadStateRead m
=> Int -> m (Strategy RequestAnyAbility)
-> m (Frequency RequestAnyAbility)
stratToFreq scale mstrat = do
st <- mstrat
return $! if scale == 0
then mzero
else scaleFreq scale $ bestVariant st -- TODO: flatten instead?
-- Order matters within the list, because it's summed with .| after
-- filtering. Also, the results of prefix, distant and suffix
-- are summed with .| at the end.
prefix, suffix :: [([Ability], m (Strategy RequestAnyAbility), Bool)]
prefix =
[ ( [AbApply], (toAny :: ToAny 'AbApply)
<$> applyItem aid ApplyFirstAid
, condHpTooLow && not condAnyFoeAdj
&& not condOnTriggerable ) -- don't block stairs, perhaps ascend
, ( [AbTrigger], (toAny :: ToAny 'AbTrigger)
<$> trigger aid True
-- flee via stairs, even if to wrong level
-- may return via different stairs
, condOnTriggerable
&& ((condNotCalmEnough || condHpTooLow)
&& condThreatNearby && not condTgtEnemyPresent
|| condMeleeBad && condThreatAdj) )
, ( [AbDisplace]
, displaceFoe aid -- only swap with an enemy to expose him
, condBlocksFriends && condAnyFoeAdj
&& not condOnTriggerable && not condDesirableFloorItem )
, ( [AbMoveItem], (toAny :: ToAny 'AbMoveItem)
<$> pickup aid True
, condNoEqpWeapon && condFloorWeapon && not condHpTooLow
&& abInMaxSkill AbMelee )
, ( [AbMelee], (toAny :: ToAny 'AbMelee)
<$> meleeBlocker aid -- only melee target or blocker
, condAnyFoeAdj
|| not (abInMaxSkill AbDisplace) -- melee friends, not displace
&& fleaderMode (gplayer fact) == LeaderNull -- not restrained
&& condTgtEnemyPresent ) -- excited
, ( [AbTrigger], (toAny :: ToAny 'AbTrigger)
<$> trigger aid False
, condOnTriggerable && not condDesirableFloorItem
&& (lidExplored || condEnoughGear)
&& not condTgtEnemyPresent )
, ( [AbMove]
, flee aid fleeL
, condMeleeBad && not condFastThreatAdj
-- Don't keep fleeing if was just hit, unless can't melee at all.
&& not (heavilyDistressed
&& abInMaxSkill AbMelee
&& not condNoUsableWeapon)
&& condThreatAtHand )
, ( [AbDisplace] -- prevents some looping movement
, displaceBlocker aid -- fires up only when path blocked
, not condDesirableFloorItem )
, ( [AbMoveItem], (toAny :: ToAny 'AbMoveItem)
<$> equipItems aid -- doesn't take long, very useful if safe
-- only if calm enough, so high priority
, not (condAnyFoeAdj
|| condDesirableFloorItem
|| condNotCalmEnough) )
]
-- Order doesn't matter, scaling does.
distant :: [([Ability], m (Frequency RequestAnyAbility), Bool)]
distant =
[ ( [AbMoveItem]
, stratToFreq 20000 $ (toAny :: ToAny 'AbMoveItem)
<$> yieldUnneeded aid -- 20000 to unequip ASAP, unless is thrown
, True )
, ( [AbProject] -- for high-value target, shoot even in melee
, stratToFreq 2 $ (toAny :: ToAny 'AbProject)
<$> projectItem aid
, condTgtEnemyPresent && condCanProject && not condOnTriggerable )
, ( [AbApply]
, stratToFreq 2 $ (toAny :: ToAny 'AbApply)
<$> applyItem aid ApplyAll -- use any potion or scroll
, (condTgtEnemyPresent || condThreatNearby) -- can affect enemies
&& not condOnTriggerable )
, ( [AbMove]
, stratToFreq (if not condTgtEnemyPresent
then 3 -- if enemy only remembered, investigate anyway
else if condTgtNonmoving
then 0
else if condTgtEnemyAdjFriend
then 1000 -- friends probably pummeled, go to help
else 100)
$ chase aid True (condMeleeBad && condThreatNearby
&& not aInAmbient && not actorShines)
, (condTgtEnemyPresent || condTgtEnemyRemembered)
&& not (condDesirableFloorItem && not condThreatAtHand)
&& abInMaxSkill AbMelee
&& not condNoUsableWeapon )
]
-- Order matters again.
suffix =
[ ( [AbMelee], (toAny :: ToAny 'AbMelee)
<$> meleeAny aid -- avoid getting damaged for naught
, condAnyFoeAdj )
, ( [AbMove]
, flee aid panicFleeL -- ultimate panic mode, displaces foes
, condAnyFoeAdj )
, ( [AbMoveItem], (toAny :: ToAny 'AbMoveItem)
<$> pickup aid False
, not condThreatAtHand ) -- e.g., to give to other party members
, ( [AbMoveItem], (toAny :: ToAny 'AbMoveItem)
<$> unEquipItems aid -- late, because these items not bad
, True )
, ( [AbMove]
, chase aid True (condTgtEnemyPresent
-- Don't keep hiding in darkness if hit right now,
-- unless can't melee at all.
&& not (heavilyDistressed
&& abInMaxSkill AbMelee
&& not condNoUsableWeapon)
&& condMeleeBad && condThreatNearby
&& not aInAmbient && not actorShines)
, not (condTgtNonmoving && condThreatAtHand) )
-- TODO: unless tgt can't melee
]
fallback =
[ ( [AbWait], (toAny :: ToAny 'AbWait)
<$> waitBlockNow
-- Wait until friends sidestep; ensures strategy is never empty.
-- TODO: try to switch leader away before that (we already
-- switch him afterwards)
, True )
]
-- TODO: don't msum not to evaluate until needed
-- Check current, not maximal skills, since this can be a non-leader action.
actorSk <- actorSkillsClient aid
let abInSkill ab = EM.findWithDefault 0 ab actorSk > 0
checkAction :: ([Ability], m a, Bool) -> Bool
checkAction (abts, _, cond) = all abInSkill abts && cond
sumS abAction = do
let as = filter checkAction abAction
strats <- mapM (\(_, m, _) -> m) as
return $! msum strats
sumF abFreq = do
let as = filter checkAction abFreq
strats <- mapM (\(_, m, _) -> m) as
return $! msum strats
combineDistant as = liftFrequency <$> sumF as
sumPrefix <- sumS prefix
comDistant <- combineDistant distant
sumSuffix <- sumS suffix
sumFallback <- sumS fallback
return $! sumPrefix .| comDistant .| sumSuffix .| sumFallback
-- | A strategy to always just wait.
waitBlockNow :: MonadClient m => m (Strategy (RequestTimed 'AbWait))
waitBlockNow = return $! returN "wait" ReqWait
pickup :: MonadClient m
=> ActorId -> Bool -> m (Strategy (RequestTimed 'AbMoveItem))
pickup aid onlyWeapon = do
benItemL <- benGroundItems aid
b <- getsState $ getActorBody aid
activeItems <- activeItemsClient aid
-- This calmE is outdated when one of the items increases max Calm
-- (e.g., in pickup, which handles many items at once), but this is OK,
-- the server accepts item movement based on calm at the start, not end
-- or in the middle.
-- The calmE is inaccurate also if an item not IDed, but that's intended
-- and the server will ignore and warn (and content may avoid that,
-- e.g., making all rings identified)
let calmE = calmEnough b activeItems
isWeapon (_, (_, itemFull)) = isMeleeEqp itemFull
filterWeapon | onlyWeapon = filter isWeapon
| otherwise = id
prepareOne (oldN, l4) ((_, (k, _)), (iid, itemFull)) =
let n = oldN + k
(newN, toCStore)
| calmE && goesIntoSha itemFull = (oldN, CSha)
| goesIntoEqp itemFull && eqpOverfull b n =
(oldN, if calmE then CSha else CInv)
| goesIntoEqp itemFull = (n, CEqp)
| otherwise = (oldN, CInv)
in (newN, (iid, k, CGround, toCStore) : l4)
(_, prepared) = foldl' prepareOne (0, []) $ filterWeapon benItemL
return $! if null prepared
then reject
else returN "pickup" $ ReqMoveItems prepared
equipItems :: MonadClient m
=> ActorId -> m (Strategy (RequestTimed 'AbMoveItem))
equipItems aid = do
cops <- getsState scops
body <- getsState $ getActorBody aid
activeItems <- activeItemsClient aid
let calmE = calmEnough body activeItems
fact <- getsState $ (EM.! bfid body) . sfactionD
eqpAssocs <- fullAssocsClient aid [CEqp]
invAssocs <- fullAssocsClient aid [CInv]
shaAssocs <- fullAssocsClient aid [CSha]
condAnyFoeAdj <- condAnyFoeAdjM aid
condLightBetrays <- condLightBetraysM aid
condTgtEnemyPresent <- condTgtEnemyPresentM aid
let improve :: CStore
-> (Int, [(ItemId, Int, CStore, CStore)])
-> ( IK.EqpSlot
, ( [(Int, (ItemId, ItemFull))]
, [(Int, (ItemId, ItemFull))] ) )
-> (Int, [(ItemId, Int, CStore, CStore)])
improve fromCStore (oldN, l4) (slot, (bestInv, bestEqp)) =
let n = 1 + oldN
in case (bestInv, bestEqp) of
((_, (iidInv, _)) : _, []) | not (eqpOverfull body n) ->
(n, (iidInv, 1, fromCStore, CEqp) : l4)
((vInv, (iidInv, _)) : _, (vEqp, _) : _)
| not (eqpOverfull body n)
&& (vInv > vEqp || not (toShare slot)) ->
(n, (iidInv, 1, fromCStore, CEqp) : l4)
_ -> (oldN, l4)
-- We filter out unneeded items. In particular, we ignore them in eqp
-- when comparing to items we may want to equip. Anyway, the unneeded
-- items should be removed in yieldUnneeded earlier or soon after.
filterNeeded (_, itemFull) =
not $ unneeded cops condAnyFoeAdj condLightBetrays
condTgtEnemyPresent (not calmE)
body activeItems fact itemFull
bestThree = bestByEqpSlot (filter filterNeeded eqpAssocs)
(filter filterNeeded invAssocs)
(filter filterNeeded shaAssocs)
bEqpInv = foldl' (improve CInv) (0, [])
$ map (\((slot, _), (eqp, inv, _)) ->
(slot, (inv, eqp))) bestThree
bEqpBoth | calmE =
foldl' (improve CSha) bEqpInv
$ map (\((slot, _), (eqp, _, sha)) ->
(slot, (sha, eqp))) bestThree
| otherwise = bEqpInv
(_, prepared) = bEqpBoth
return $! if null prepared
then reject
else returN "equipItems" $ ReqMoveItems prepared
toShare :: IK.EqpSlot -> Bool
toShare IK.EqpSlotPeriodic = False
toShare _ = True
yieldUnneeded :: MonadClient m
=> ActorId -> m (Strategy (RequestTimed 'AbMoveItem))
yieldUnneeded aid = do
cops <- getsState scops
body <- getsState $ getActorBody aid
activeItems <- activeItemsClient aid
let calmE = calmEnough body activeItems
fact <- getsState $ (EM.! bfid body) . sfactionD
eqpAssocs <- fullAssocsClient aid [CEqp]
condAnyFoeAdj <- condAnyFoeAdjM aid
condLightBetrays <- condLightBetraysM aid
condTgtEnemyPresent <- condTgtEnemyPresentM aid
-- Here AI hides from the human player the Ring of Speed And Bleeding,
-- which is a bit harsh, but fair. However any subsequent such
-- rings will not be picked up at all, so the human player
-- doesn't lose much fun. Additionally, if AI learns alchemy later on,
-- they can repair the ring, wield it, drop at death and it's
-- in play again.
let yieldSingleUnneeded (iidEqp, itemEqp) =
let csha = if calmE then CSha else CInv
in if harmful cops body activeItems fact itemEqp
then [(iidEqp, itemK itemEqp, CEqp, CInv)]
else if hinders condAnyFoeAdj condLightBetrays
condTgtEnemyPresent (not calmE)
body activeItems itemEqp
then [(iidEqp, itemK itemEqp, CEqp, csha)]
else []
yieldAllUnneeded = concatMap yieldSingleUnneeded eqpAssocs
return $! if null yieldAllUnneeded
then reject
else returN "yieldUnneeded" $ ReqMoveItems yieldAllUnneeded
unEquipItems :: MonadClient m
=> ActorId -> m (Strategy (RequestTimed 'AbMoveItem))
unEquipItems aid = do
cops <- getsState scops
body <- getsState $ getActorBody aid
activeItems <- activeItemsClient aid
let calmE = calmEnough body activeItems
fact <- getsState $ (EM.! bfid body) . sfactionD
eqpAssocs <- fullAssocsClient aid [CEqp]
invAssocs <- fullAssocsClient aid [CInv]
shaAssocs <- fullAssocsClient aid [CSha]
condAnyFoeAdj <- condAnyFoeAdjM aid
condLightBetrays <- condLightBetraysM aid
condTgtEnemyPresent <- condTgtEnemyPresentM aid
-- Here AI hides from the human player the Ring of Speed And Bleeding,
-- which is a bit harsh, but fair. However any subsequent such
-- rings will not be picked up at all, so the human player
-- doesn't lose much fun. Additionally, if AI learns alchemy later on,
-- they can repair the ring, wield it, drop at death and it's
-- in play again.
let improve :: CStore -> ( IK.EqpSlot
, ( [(Int, (ItemId, ItemFull))]
, [(Int, (ItemId, ItemFull))] ) )
-> [(ItemId, Int, CStore, CStore)]
improve fromCStore (slot, (bestSha, bestEOrI)) =
case (bestSha, bestEOrI) of
_ | not (toShare slot)
&& fromCStore == CEqp
&& not (eqpOverfull body 1) -> -- keep periodic items up to M-1
[]
(_, (vEOrI, (iidEOrI, _)) : _) | (toShare slot || fromCStore == CInv)
&& getK bestEOrI > 1
&& betterThanSha vEOrI bestSha ->
-- To share the best items with others, if they care.
[(iidEOrI, getK bestEOrI - 1, fromCStore, CSha)]
(_, _ : (vEOrI, (iidEOrI, _)) : _) | (toShare slot
|| fromCStore == CInv)
&& betterThanSha vEOrI bestSha ->
-- To share the second best items with others, if they care.
[(iidEOrI, getK bestEOrI, fromCStore, CSha)]
(_, (vEOrI, (_, _)) : _) | fromCStore == CEqp
&& eqpOverfull body 1
&& worseThanSha vEOrI bestSha ->
-- To make place in eqp for an item better than any ours.
[(fst $ snd $ last bestEOrI, 1, fromCStore, CSha)]
_ -> []
getK [] = 0
getK ((_, (_, itemFull)) : _) = itemK itemFull
betterThanSha _ [] = True
betterThanSha vEOrI ((vSha, _) : _) = vEOrI > vSha
worseThanSha _ [] = False
worseThanSha vEOrI ((vSha, _) : _) = vEOrI < vSha
filterNeeded (_, itemFull) =
not $ unneeded cops condAnyFoeAdj condLightBetrays
condTgtEnemyPresent (not calmE)
body activeItems fact itemFull
bestThree =
bestByEqpSlot eqpAssocs invAssocs (filter filterNeeded shaAssocs)
bInvSha = concatMap
(improve CInv . (\((slot, _), (_, inv, sha)) ->
(slot, (sha, inv)))) bestThree
bEqpSha = concatMap
(improve CEqp . (\((slot, _), (eqp, _, sha)) ->
(slot, (sha, eqp)))) bestThree
prepared = if calmE then bInvSha ++ bEqpSha else []
return $! if null prepared
then reject
else returN "unEquipItems" $ ReqMoveItems prepared
groupByEqpSlot :: [(ItemId, ItemFull)]
-> M.Map (IK.EqpSlot, Text) [(ItemId, ItemFull)]
groupByEqpSlot is =
let f (iid, itemFull) = case strengthEqpSlot $ itemBase itemFull of
Nothing -> Nothing
Just es -> Just (es, [(iid, itemFull)])
withES = mapMaybe f is
in M.fromListWith (++) withES
bestByEqpSlot :: [(ItemId, ItemFull)]
-> [(ItemId, ItemFull)]
-> [(ItemId, ItemFull)]
-> [((IK.EqpSlot, Text)
, ( [(Int, (ItemId, ItemFull))]
, [(Int, (ItemId, ItemFull))]
, [(Int, (ItemId, ItemFull))] ) )]
bestByEqpSlot eqpAssocs invAssocs shaAssocs =
let eqpMap = M.map (\g -> (g, [], [])) $ groupByEqpSlot eqpAssocs
invMap = M.map (\g -> ([], g, [])) $ groupByEqpSlot invAssocs
shaMap = M.map (\g -> ([], [], g)) $ groupByEqpSlot shaAssocs
appendThree (g1, g2, g3) (h1, h2, h3) = (g1 ++ h1, g2 ++ h2, g3 ++ h3)
eqpInvShaMap = M.unionsWith appendThree [eqpMap, invMap, shaMap]
bestSingle = strongestSlot
bestThree (eqpSlot, _) (g1, g2, g3) = (bestSingle eqpSlot g1,
bestSingle eqpSlot g2,
bestSingle eqpSlot g3)
in M.assocs $ M.mapWithKey bestThree eqpInvShaMap
harmful :: Kind.COps -> Actor -> [ItemFull] -> Faction -> ItemFull -> Bool
harmful cops body activeItems fact itemFull =
-- Items that are known and their effects are not stricly beneficial
-- should not be equipped (either they are harmful or they waste eqp space).
maybe False (\(u, _) -> u <= 0)
(totalUsefulness cops body activeItems fact itemFull)
unneeded :: Kind.COps -> Bool -> Bool -> Bool -> Bool
-> Actor -> [ItemFull] -> Faction -> ItemFull
-> Bool
unneeded cops condAnyFoeAdj condLightBetrays
condTgtEnemyPresent condNotCalmEnough
body activeItems fact itemFull =
harmful cops body activeItems fact itemFull
|| hinders condAnyFoeAdj condLightBetrays
condTgtEnemyPresent condNotCalmEnough
body activeItems itemFull
|| let calm10 = calmEnough10 body activeItems -- unneeded risk
itemLit = isJust $ strengthFromEqpSlot IK.EqpSlotAddLight itemFull
in itemLit && not calm10
-- Everybody melees in a pinch, even though some prefer ranged attacks.
meleeBlocker :: MonadClient m => ActorId -> m (Strategy (RequestTimed 'AbMelee))
meleeBlocker aid = do
b <- getsState $ getActorBody aid
fact <- getsState $ (EM.! bfid b) . sfactionD
actorSk <- actorSkillsClient aid
mtgtMPath <- getsClient $ EM.lookup aid . stargetD
case mtgtMPath of
Just (_, Just (_ : q : _, (goal, _))) -> do
-- We prefer the goal (e.g., when no accessible, but adjacent),
-- but accept @q@ even if it's only a blocking enemy position.
let maim | adjacent (bpos b) goal = Just goal
| adjacent (bpos b) q = Just q
| otherwise = Nothing -- MeleeDistant
lBlocker <- case maim of
Nothing -> return []
Just aim -> getsState $ posToActors aim (blid b)
case lBlocker of
(aid2, _) : _ -> do
-- No problem if there are many projectiles at the spot. We just
-- attack the first one.
body2 <- getsState $ getActorBody aid2
if not (actorDying body2) -- already dying
&& (not (bproj body2) -- displacing saves a move
&& isAtWar fact (bfid body2) -- they at war with us
|| EM.findWithDefault 0 AbDisplace actorSk <= 0 -- not disp.
&& fleaderMode (gplayer fact) == LeaderNull -- no restrain
&& EM.findWithDefault 0 AbMove actorSk > 0 -- blocked move
&& bhp body2 < bhp b) -- respect power
then do
mel <- maybeToList <$> pickWeaponClient aid aid2
return $! liftFrequency $ uniformFreq "melee in the way" mel
else return reject
[] -> return reject
_ -> return reject -- probably no path to the enemy, if any
-- Everybody melees in a pinch, skills and weapons allowing,
-- even though some prefer ranged attacks.
meleeAny :: MonadClient m => ActorId -> m (Strategy (RequestTimed 'AbMelee))
meleeAny aid = do
b <- getsState $ getActorBody aid
fact <- getsState $ (EM.! bfid b) . sfactionD
allFoes <- getsState $ actorRegularAssocs (isAtWar fact) (blid b)
let adjFoes = filter (adjacent (bpos b) . bpos . snd) allFoes
mels <- mapM (pickWeaponClient aid . fst) adjFoes
-- TODO: prioritize somehow
let freq = uniformFreq "melee adjacent" $ catMaybes mels
return $! liftFrequency freq
-- TODO: take charging status into account
-- TODO: make sure the stairs are specifically targetted and not
-- an item on them, etc., so that we don't leave level if items visible.
-- When invalidating target, make sure the stairs should really be taken.
-- | The level the actor is on is either explored or the actor already
-- has a weapon equipped, so no need to explore further, he tries to find
-- enemies on other levels.
-- We don't verify the stairs are targeted by the actor, but at least
-- the actor doesn't target a visible enemy at this point.
trigger :: MonadClient m
=> ActorId -> Bool -> m (Strategy (RequestTimed 'AbTrigger))
trigger aid fleeViaStairs = do
cops@Kind.COps{cotile=Kind.Ops{okind}} <- getsState scops
dungeon <- getsState sdungeon
explored <- getsClient sexplored
b <- getsState $ getActorBody aid
activeItems <- activeItemsClient aid
fact <- getsState $ (EM.! bfid b) . sfactionD
let lid = blid b
lvl <- getLevel lid
unexploredD <- unexploredDepth
s <- getState
let lidExplored = ES.member lid explored
allExplored = ES.size explored == EM.size dungeon
t = lvl `at` bpos b
feats = TK.tfeature $ okind t
ben feat = case feat of
TK.Cause (IK.Ascend k) -> do -- change levels sensibly, in teams
(lid2, pos2) <- getsState $ whereTo lid (bpos b) k . sdungeon
per <- getPerFid lid2
let canSee = ES.member (bpos b) (totalVisible per)
aimless = ftactic (gplayer fact) `elem` [TRoam, TPatrol]
easier = signum k /= signum (fromEnum lid)
unexpForth = unexploredD (signum k) lid
unexpBack = unexploredD (- signum k) lid
expBenefit
| aimless = 100 -- faction is not exploring, so switch at will
| unexpForth =
if easier -- alway try as easy level as possible
|| not unexpBack
&& lidExplored -- no other choice for exploration
then 1000
else 0
| not lidExplored = 0 -- fully explore current
| unexpBack = 0 -- wait for stairs in the opposite direciton
| not $ null $ lescape lvl = 0
-- all explored, stay on the escape level
| otherwise = 2 -- no escape, switch levels occasionally
actorsThere = posToActors pos2 lid2 s
return $!
if boldpos b == Just (bpos b) -- probably used stairs last turn
&& boldlid b == lid2 -- in the opposite direction
then 0 -- avoid trivial loops (pushing, being pushed, etc.)
else let eben = case actorsThere of
[] | canSee -> expBenefit
_ -> min 1 expBenefit -- risk pushing
in if fleeViaStairs
then 1000 * eben + 1 -- strongly prefer correct direction
else eben
TK.Cause ef@IK.Escape{} -> return $ -- flee via this way, too
-- Only some factions try to escape but they first explore all
-- for high score.
if not (fcanEscape $ gplayer fact) || not allExplored
then 0
else effectToBenefit cops b activeItems fact ef
TK.Cause ef | not fleeViaStairs ->
return $! effectToBenefit cops b activeItems fact ef
_ -> return 0
benFeats <- mapM ben feats
let benFeat = zip benFeats feats
return $! liftFrequency $ toFreq "trigger"
[ (benefit, ReqTrigger (Just feat))
| (benefit, feat) <- benFeat
, benefit > 0 ]
projectItem :: MonadClient m => ActorId -> m (Strategy (RequestTimed 'AbProject))
projectItem aid = do
btarget <- getsClient $ getTarget aid
b <- getsState $ getActorBody aid
mfpos <- aidTgtToPos aid (blid b) btarget
seps <- getsClient seps
case (btarget, mfpos) of
(_, Just fpos) | chessDist (bpos b) fpos == 1 -> return reject
(Just TEnemy{}, Just fpos) -> do
mnewEps <- makeLine False b fpos seps
case mnewEps of
Just newEps -> do
actorSk <- actorSkillsClient aid
let skill = EM.findWithDefault 0 AbProject actorSk
-- ProjectAimOnself, ProjectBlockActor, ProjectBlockTerrain
-- and no actors or obstracles along the path.
let q _ itemFull b2 activeItems =
either (const False) id
$ permittedProject " " False skill itemFull b2 activeItems
activeItems <- activeItemsClient aid
let calmE = calmEnough b activeItems
stores = [CEqp, CInv, CGround] ++ [CSha | calmE]
benList <- benAvailableItems aid q stores
localTime <- getsState $ getLocalTime (blid b)
let coeff CGround = 2
coeff COrgan = 3 -- can't give to others
coeff CEqp = 100000 -- must hinder currently
coeff CInv = 1
coeff CSha = 1
fRanged ( (mben, (_, cstore))
, (iid, itemFull@ItemFull{itemBase}) ) =
-- We assume if the item has a timeout, most effects are under
-- Recharging, so no point projecting if not recharged.
-- This is not an obvious assumption, so recharging is not
-- included in permittedProject and can be tweaked here easily.
let recharged = hasCharge localTime itemFull
trange = totalRange itemBase
bestRange =
chessDist (bpos b) fpos + 2 -- margin for fleeing
rangeMult = -- penalize wasted or unsafely low range
10 + max 0 (10 - abs (trange - bestRange))
durable = IK.Durable `elem` jfeature itemBase
durableBonus = if durable
then 2 -- we or foes keep it after the throw
else 1
benR = durableBonus
* coeff cstore
* case mben of
Nothing -> -1 -- experiment if no options
Just (_, ben) -> ben
* (if recharged then 1 else 0)
in if -- Durable weapon is usually too useful for melee.
not (isMeleeEqp itemFull)
&& benR < 0
&& trange >= chessDist (bpos b) fpos
then Just ( -benR * rangeMult `div` 10
, ReqProject fpos newEps iid cstore )
else Nothing
benRanged = mapMaybe fRanged benList
return $! liftFrequency $ toFreq "projectItem" benRanged
_ -> return reject
_ -> return reject
data ApplyItemGroup = ApplyAll | ApplyFirstAid
deriving Eq
applyItem :: MonadClient m
=> ActorId -> ApplyItemGroup -> m (Strategy (RequestTimed 'AbApply))
applyItem aid applyGroup = do
actorSk <- actorSkillsClient aid
b <- getsState $ getActorBody aid
localTime <- getsState $ getLocalTime (blid b)
let skill = EM.findWithDefault 0 AbApply actorSk
q _ itemFull _ activeItems =
-- TODO: terrible hack to prevent the use of identified healing gems
let freq = case itemDisco itemFull of
Nothing -> []
Just ItemDisco{itemKind} -> IK.ifreq itemKind
in maybe True (<= 0) (lookup "gem" freq)
&& either (const False) id
(permittedApply " " localTime skill itemFull b activeItems)
activeItems <- activeItemsClient aid
let calmE = calmEnough b activeItems
stores = [CEqp, CInv, CGround] ++ [CSha | calmE]
benList <- benAvailableItems aid q stores
organs <- mapM (getsState . getItemBody) $ EM.keys $ borgan b
let itemLegal itemFull = case applyGroup of
ApplyFirstAid ->
let getP (IK.RefillHP p) _ | p > 0 = True
getP (IK.OverfillHP p) _ | p > 0 = True
getP _ acc = acc
in case itemDisco itemFull of
Just ItemDisco{itemAE=Just ItemAspectEffect{jeffects}} ->
foldr getP False jeffects
_ -> False
ApplyAll -> True
coeff CGround = 2
coeff COrgan = 3 -- can't give to others
coeff CEqp = 100000 -- must hinder currently
coeff CInv = 1
coeff CSha = 1
fTool ((mben, (_, cstore)), (iid, itemFull@ItemFull{itemBase})) =
let durableBonus = if IK.Durable `elem` jfeature itemBase
then 5 -- we keep it after use
else 1
oldGrps = map (toGroupName . jname) organs
createOrganAgain =
-- This assumes the organ creation is beneficial. If it's
-- a drawback of an otherwise good item, we should reverse
-- the condition.
let newGrps = strengthCreateOrgan itemFull
in not $ null $ intersect newGrps oldGrps
dropOrganVoid =
-- This assumes the organ dropping is beneficial. If it's
-- a drawback of an otherwise good item, or a marginal
-- advantage only, we should reverse or ignore the condition.
-- We ignore a very general @grp@ being used for a very
-- common and easy to drop organ, etc.
let newGrps = strengthDropOrgan itemFull
hasDropOrgan = not $ null newGrps
in hasDropOrgan && null (newGrps `intersect` oldGrps)
benR = case mben of
Nothing -> 0
-- experimenting is fun, but it's better to risk
-- foes' skin than ours -- TODO: when {applied}
-- is implemented, enable this for items too heavy,
-- etc. for throwing
Just (_, ben) -> ben
* (if not createOrganAgain then 1 else 0)
* (if not dropOrganVoid then 1 else 0)
* durableBonus
* coeff cstore
in if itemLegal itemFull && benR > 0
then Just (benR, ReqApply iid cstore)
else Nothing
benTool = mapMaybe fTool benList
return $! liftFrequency $ toFreq "applyItem" benTool
-- If low on health or alone, flee in panic, close to the path to target
-- and as far from the attackers, as possible. Usually fleeing from
-- foes will lead towards friends, but we don't insist on that.
-- We use chess distances, not pathfinding, because melee can happen
-- at path distance 2.
flee :: MonadClient m
=> ActorId -> [(Int, Point)] -> m (Strategy RequestAnyAbility)
flee aid fleeL = do
b <- getsState $ getActorBody aid
let vVic = map (second (`vectorToFrom` bpos b)) fleeL
str = liftFrequency $ toFreq "flee" vVic
mapStrategyM (moveOrRunAid True aid) str
displaceFoe :: MonadClient m => ActorId -> m (Strategy RequestAnyAbility)
displaceFoe aid = do
cops <- getsState scops
b <- getsState $ getActorBody aid
lvl <- getLevel $ blid b
fact <- getsState $ (EM.! bfid b) . sfactionD
let friendlyFid fid = fid == bfid b || isAllied fact fid
friends <- getsState $ actorRegularList friendlyFid (blid b)
allFoes <- getsState $ actorRegularAssocs (isAtWar fact) (blid b)
let accessibleHere = accessible cops lvl $ bpos b
displaceable body = -- DisplaceAccess
adjacent (bpos body) (bpos b) && accessibleHere (bpos body)
nFriends body = length $ filter (adjacent (bpos body) . bpos) friends
nFrHere = nFriends b + 1
qualifyActor (aid2, body2) = do
activeItems <- activeItemsClient aid2
dEnemy <- getsState $ dispEnemy aid aid2 activeItems
-- DisplaceDying, DisplaceBraced, DisplaceImmobile, DisplaceSupported
let nFr = nFriends body2
return $! if displaceable body2 && dEnemy && nFr < nFrHere
then Just (nFr * nFr, bpos body2 `vectorToFrom` bpos b)
else Nothing
vFoes <- mapM qualifyActor allFoes
let str = liftFrequency $ toFreq "displaceFoe" $ catMaybes vFoes
mapStrategyM (moveOrRunAid True aid) str
displaceBlocker :: MonadClient m => ActorId -> m (Strategy RequestAnyAbility)
displaceBlocker aid = do
mtgtMPath <- getsClient $ EM.lookup aid . stargetD
str <- case mtgtMPath of
Just (_, Just (p : q : _, _)) -> displaceTowards aid p q
_ -> return reject -- goal reached
mapStrategyM (moveOrRunAid True aid) str
-- TODO: perhaps modify target when actually moving, not when
-- producing the strategy, even if it's a unique choice in this case.
displaceTowards :: MonadClient m
=> ActorId -> Point -> Point -> m (Strategy Vector)
displaceTowards aid source target = do
cops <- getsState scops
b <- getsState $ getActorBody aid
let !_A = assert (source == bpos b && adjacent source target) ()
lvl <- getLevel $ blid b
if boldpos b /= Just target -- avoid trivial loops
&& accessible cops lvl source target then do -- DisplaceAccess
mleader <- getsClient _sleader
mBlocker <- getsState $ posToActors target (blid b)
case mBlocker of
[] -> return reject
[(aid2, b2)] | Just aid2 /= mleader -> do
mtgtMPath <- getsClient $ EM.lookup aid2 . stargetD
case mtgtMPath of
Just (tgt, Just (p : q : rest, (goal, len)))
| q == source && p == target
|| waitedLastTurn b2 -> do
let newTgt = if q == source && p == target
then Just (tgt, Just (q : rest, (goal, len - 1)))
else Nothing
modifyClient $ \cli ->
cli {stargetD = EM.alter (const newTgt) aid (stargetD cli)}
return $! returN "displace friend" $ target `vectorToFrom` source
Just _ -> return reject
Nothing -> do
tfact <- getsState $ (EM.! bfid b2) . sfactionD
activeItems <- activeItemsClient aid2
dEnemy <- getsState $ dispEnemy aid aid2 activeItems
if not (isAtWar tfact (bfid b)) || dEnemy then
return $! returN "displace other" $ target `vectorToFrom` source
else return reject -- DisplaceDying, etc.
_ -> return reject -- DisplaceProjectiles or trying to displace leader
else return reject
chase :: MonadClient m
=> ActorId -> Bool -> Bool -> m (Strategy RequestAnyAbility)
chase aid doDisplace avoidAmbient = do
Kind.COps{cotile} <- getsState scops
body <- getsState $ getActorBody aid
fact <- getsState $ (EM.! bfid body) . sfactionD
mtgtMPath <- getsClient $ EM.lookup aid . stargetD
lvl <- getLevel $ blid body
let isAmbient pos = Tile.isLit cotile (lvl `at` pos)
str <- case mtgtMPath of
Just (_, Just (p : q : _, (goal, _))) | not $ avoidAmbient && isAmbient q ->
-- With no leader, the goal is vague, so permit arbitrary detours.
moveTowards aid p q goal (fleaderMode (gplayer fact) == LeaderNull)
_ -> return reject -- goal reached
-- If @doDisplace@: don't pick fights, assuming the target is more important.
-- We'd normally melee the target earlier on via @AbMelee@, but for
-- actors that don't have this ability (and so melee only when forced to),
-- this is meaningul.
mapStrategyM (moveOrRunAid doDisplace aid) str
-- TODO: rename source here and elsewhere, it's always an ActorId in the code
moveTowards :: MonadClient m
=> ActorId -> Point -> Point -> Point -> Bool -> m (Strategy Vector)
moveTowards aid source target goal relaxed = do
cops@Kind.COps{cotile} <- getsState scops
b <- getsState $ getActorBody aid
actorSk <- actorSkillsClient aid
let alterSkill = EM.findWithDefault 0 AbAlter actorSk
!_A = assert (source == bpos b
`blame` (source, bpos b, aid, b, goal)) ()
!_B = assert (adjacent source target
`blame` (source, target, aid, b, goal)) ()
lvl <- getLevel $ blid b
fact <- getsState $ (EM.! bfid b) . sfactionD
friends <- getsState $ actorList (not . isAtWar fact) $ blid b
let noFriends = unoccupied friends
accessibleHere = accessible cops lvl source
-- Only actors with AbAlter can search for hidden doors, etc.
bumpableHere p =
let t = lvl `at` p
in alterSkill >= 1
&& (Tile.isOpenable cotile t
|| Tile.isSuspect cotile t
|| Tile.isChangeable cotile t)
enterableHere p = accessibleHere p || bumpableHere p
if noFriends target && enterableHere target then
return $! returN "moveTowards adjacent" $ target `vectorToFrom` source
else do
let goesBack v = maybe False (\oldpos -> v == oldpos `vectorToFrom` source)
(boldpos b)
nonincreasing p = chessDist source goal >= chessDist p goal
isSensible p = (relaxed || nonincreasing p)
&& noFriends p
&& enterableHere p
sensible = [ ((goesBack v, chessDist p goal), v)
| v <- moves, let p = source `shift` v, isSensible p ]
sorted = sortBy (comparing fst) sensible
groups = map (map snd) $ groupBy ((==) `on` fst) sorted
freqs = map (liftFrequency . uniformFreq "moveTowards") groups
return $! foldr (.|) reject freqs
-- | Actor moves or searches or alters or attacks. Displaces if @run@.
-- This function is very general, even though it's often used in contexts
-- when only one or two of the many cases can possibly occur.
moveOrRunAid :: MonadClient m
=> Bool -> ActorId -> Vector -> m (Maybe RequestAnyAbility)
moveOrRunAid run source dir = do
cops@Kind.COps{cotile} <- getsState scops
sb <- getsState $ getActorBody source
actorSk <- actorSkillsClient source
let lid = blid sb
lvl <- getLevel lid
let skill = EM.findWithDefault 0 AbAlter actorSk
spos = bpos sb -- source position
tpos = spos `shift` dir -- target position
t = lvl `at` tpos
-- We start by checking actors at the the target position,
-- which gives a partial information (actors can be invisible),
-- as opposed to accessibility (and items) which are always accurate
-- (tiles can't be invisible).
tgts <- getsState $ posToActors tpos lid
case tgts of
[(target, b2)] | run -> do
-- @target@ can be a foe, as well as a friend.
tfact <- getsState $ (EM.! bfid b2) . sfactionD
activeItems <- activeItemsClient target
dEnemy <- getsState $ dispEnemy source target activeItems
if boldpos sb == Just tpos && not (waitedLastTurn sb)
-- avoid Displace loops
|| not (accessible cops lvl spos tpos) -- DisplaceAccess
then return Nothing
else if isAtWar tfact (bfid sb) && not dEnemy -- DisplaceDying, etc.
then do
wps <- pickWeaponClient source target
case wps of
Nothing -> return Nothing
Just wp -> return $! Just $ RequestAnyAbility wp
else return $! Just $ RequestAnyAbility $ ReqDisplace target
(target, _) : _ -> do -- can be a foe, as well as friend (e.g., proj.)
-- No problem if there are many projectiles at the spot. We just
-- attack the first one.
-- Attacking does not require full access, adjacency is enough.
wps <- pickWeaponClient source target
case wps of
Nothing -> return Nothing
Just wp -> return $! Just $ RequestAnyAbility wp
[] -- move or search or alter
| accessible cops lvl spos tpos ->
-- Movement requires full access.
return $! Just $ RequestAnyAbility $ ReqMove dir
-- The potential invisible actor is hit.
| skill < 1 ->
assert `failure` "AI causes AlterUnskilled" `twith` (run, source, dir)
| EM.member tpos $ lfloor lvl ->
-- This could be, e.g., inaccessible open door with an item in it,
-- but for this case to happen, it would also need to be unwalkable.
assert `failure` "AI causes AlterBlockItem" `twith` (run, source, dir)
| not (Tile.isWalkable cotile t) -- not implied
&& (Tile.isSuspect cotile t
|| Tile.isOpenable cotile t
|| Tile.isClosable cotile t
|| Tile.isChangeable cotile t) ->
-- No access, so search and/or alter the tile.
return $! Just $ RequestAnyAbility $ ReqAlter tpos Nothing
| otherwise ->
-- Boring tile, no point bumping into it, do WaitSer if really idle.
assert `failure` "AI causes MoveNothing or AlterNothing"
`twith` (run, source, dir)
| beni55/LambdaHack | Game/LambdaHack/Client/AI/HandleAbilityClient.hs | bsd-3-clause | 45,456 | 22 | 34 | 14,101 | 11,698 | 6,042 | 5,656 | -1 | -1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
-- | This module implements an optimisation that moves in-place
-- updates into/before loops where possible, with the end goal of
-- minimising memory copies. As an example, consider this program:
--
-- @
-- loop (r = r0) = for i < n do
-- let a = r[i] in
-- let r[i] = a * i in
-- r
-- in
-- ...
-- let x = y with [k] <- r in
-- ...
-- @
--
-- We want to turn this into the following:
--
-- @
-- let x0 = y with [k] <- r0
-- loop (x = x0) = for i < n do
-- let a = a[k,i] in
-- let x[k,i] = a * i in
-- x
-- in
-- let r = x[y] in
-- ...
-- @
--
-- The intent is that we are also going to optimise the new data
-- movement (in the @x0@-binding), possibly by changing how @r0@ is
-- defined. For the above transformation to be valid, a number of
-- conditions must be fulfilled:
--
-- (1) @r@ must not be consumed after the original in-place update.
--
-- (2) @k@ and @y@ must be available at the beginning of the loop.
--
-- (3) @x@ must be visible whenever @r@ is visible. (This means
-- that both @x@ and @r@ must be bound in the same 'Body'.)
--
-- (4) If @x@ is consumed at a point after the loop, @r@ must not
-- be used after that point.
--
-- (5) The size of @r@ is invariant inside the loop.
--
-- (6) The value @r@ must come from something that we can actually
-- optimise (e.g. not a function parameter).
--
-- (7) @y@ (or its aliases) may not be used inside the body of the
-- loop.
--
-- FIXME: the implementation is not finished yet. Specifically, the
-- above conditions are not really checked.
module Futhark.Optimise.InPlaceLowering
(
inPlaceLowering
) where
import Control.Applicative
import Control.Monad.RWS hiding (mapM_)
import qualified Data.HashMap.Lazy as HM
import qualified Data.HashSet as HS
import Data.Foldable
import Data.Maybe
import Futhark.Analysis.Alias
import Futhark.Representation.Aliases
import Futhark.Representation.Kernels (Kernels)
import Futhark.Optimise.InPlaceLowering.LowerIntoBinding
import Futhark.MonadFreshNames
import Futhark.Binder
import Futhark.Pass
import Futhark.Tools (intraproceduralTransformation)
import Prelude hiding (any, mapM_, elem, all)
-- | Apply the in-place lowering optimisation to the given program.
inPlaceLowering :: Pass Kernels Kernels
inPlaceLowering = simplePass
"In-place lowering"
"Lower in-place updates into loops" $
fmap removeProgAliases .
intraproceduralTransformation optimiseFunDef .
aliasAnalysis
optimiseFunDef :: MonadFreshNames m => FunDef (Aliases Kernels) -> m (FunDef (Aliases Kernels))
optimiseFunDef fundec =
modifyNameSource $ runForwardingM $
bindingFParams (funDefParams fundec) $ do
body <- optimiseBody $ funDefBody fundec
return $ fundec { funDefBody = body }
optimiseBody :: Body (Aliases Kernels) -> ForwardingM (Body (Aliases Kernels))
optimiseBody (Body als bnds res) = do
bnds' <- deepen $ optimiseBindings bnds $
mapM_ seen res
return $ Body als bnds' res
where seen Constant{} = return ()
seen (Var v) = seenVar v
optimiseBindings :: [Binding (Aliases Kernels)]
-> ForwardingM ()
-> ForwardingM [Binding (Aliases Kernels)]
optimiseBindings [] m = m >> return []
optimiseBindings (bnd:bnds) m = do
(bnds', bup) <- tapBottomUp $ bindingBinding bnd $ optimiseBindings bnds m
bnd' <- optimiseInBinding bnd
case filter ((`elem` boundHere) . updateValue) $
forwardThese bup of
[] -> checkIfForwardableUpdate bnd' bnds'
updates -> do
let updateBindings = map updateBinding updates
-- Condition (5) and (7) are assumed to be checked by
-- lowerUpdate.
case lowerUpdate bnd' updates of
Just lowering -> do new_bnds <- lowering
new_bnds' <- optimiseBindings new_bnds $
tell bup { forwardThese = [] }
return $ new_bnds' ++ bnds'
Nothing -> checkIfForwardableUpdate bnd' $
updateBindings ++ bnds'
where boundHere = patternNames $ bindingPattern bnd
checkIfForwardableUpdate bnd'@(Let pat _ e) bnds'
| [PatElem v (BindInPlace cs src [i]) attr] <- patternElements pat,
PrimOp (SubExp (Var ve)) <- e = do
forwarded <- maybeForward ve v attr cs src i
return $ if forwarded
then bnds'
else bnd' : bnds'
checkIfForwardableUpdate bnd' bnds' =
return $ bnd' : bnds'
optimiseInBinding :: Binding (Aliases Kernels)
-> ForwardingM (Binding (Aliases Kernels))
optimiseInBinding (Let pat attr e) = do
e' <- optimiseExp e
return $ Let pat attr e'
optimiseExp :: Exp (Aliases Kernels) -> ForwardingM (Exp (Aliases Kernels))
optimiseExp (DoLoop ctx val form body) =
bindingIndices (boundInForm form) $
bindingFParams (map fst $ ctx ++ val) $ do
body' <- optimiseBody body
return $ DoLoop ctx val form body'
where boundInForm (ForLoop i _) = [i]
boundInForm (WhileLoop _) = []
-- TODO: handle Kernel here.
optimiseExp e = mapExpM optimise e
where optimise = identityMapper { mapOnBody = optimiseBody
}
data Entry = Entry { entryNumber :: Int
, entryAliases :: Names
, entryDepth :: Int
, entryOptimisable :: Bool
, entryType :: NameInfo (Aliases Kernels)
}
type VTable = HM.HashMap VName Entry
data TopDown = TopDown { topDownCounter :: Int
, topDownTable :: VTable
, topDownDepth :: Int
}
data BottomUp = BottomUp { bottomUpSeen :: Names
, forwardThese :: [DesiredUpdate (LetAttr (Aliases Kernels))]
}
instance Monoid BottomUp where
BottomUp seen1 forward1 `mappend` BottomUp seen2 forward2 =
BottomUp (seen1 `mappend` seen2) (forward1 `mappend` forward2)
mempty = BottomUp mempty mempty
updateBinding :: DesiredUpdate (LetAttr (Aliases Kernels)) -> Binding (Aliases Kernels)
updateBinding fwd =
mkLet [] [(Ident (updateName fwd) $ typeOf $ updateType fwd,
BindInPlace
(updateCertificates fwd)
(updateSource fwd)
(updateIndices fwd))] $
PrimOp $ SubExp $ Var $ updateValue fwd
newtype ForwardingM a = ForwardingM (RWS TopDown BottomUp VNameSource a)
deriving (Monad, Applicative, Functor,
MonadReader TopDown,
MonadWriter BottomUp,
MonadState VNameSource)
instance MonadFreshNames ForwardingM where
getNameSource = get
putNameSource = put
instance HasScope (Aliases Kernels) ForwardingM where
askScope = HM.map entryType <$> asks topDownTable
runForwardingM :: ForwardingM a -> VNameSource -> (a, VNameSource)
runForwardingM (ForwardingM m) src = let (x, src', _) = runRWS m emptyTopDown src
in (x, src')
where emptyTopDown = TopDown { topDownCounter = 0
, topDownTable = HM.empty
, topDownDepth = 0
}
bindingParams :: (attr -> NameInfo (Aliases Kernels))
-> [Param attr]
-> ForwardingM a
-> ForwardingM a
bindingParams f params = local $ \(TopDown n vtable d) ->
let entry fparam =
(paramName fparam,
Entry n mempty d False $ f $ paramAttr fparam)
entries = HM.fromList $ map entry params
in TopDown (n+1) (HM.union entries vtable) d
bindingFParams :: [FParam (Aliases Kernels)]
-> ForwardingM a
-> ForwardingM a
bindingFParams = bindingParams FParamInfo
bindingBinding :: Binding (Aliases Kernels)
-> ForwardingM a
-> ForwardingM a
bindingBinding (Let pat _ _) = local $ \(TopDown n vtable d) ->
let entries = HM.fromList $ map entry $ patternElements pat
entry patElem =
let (aliases, _) = patElemAttr patElem
in (patElemName patElem,
Entry n (unNames aliases) d True $ LetInfo $ patElemAttr patElem)
in TopDown (n+1) (HM.union entries vtable) d
bindingIndices :: [VName]
-> ForwardingM a
-> ForwardingM a
bindingIndices is = local $ \(TopDown n vtable d) ->
let entries = HM.fromList $ map entry is
entry v =
(v,
Entry n mempty d False IndexInfo)
in TopDown (n+1) (HM.union entries vtable) d
bindingNumber :: VName -> ForwardingM Int
bindingNumber name = do
res <- asks $ fmap entryNumber . HM.lookup name . topDownTable
case res of Just n -> return n
Nothing -> fail $ "bindingNumber: variable " ++
pretty name ++ " not found."
deepen :: ForwardingM a -> ForwardingM a
deepen = local $ \env -> env { topDownDepth = topDownDepth env + 1 }
areAvailableBefore :: [SubExp] -> VName -> ForwardingM Bool
areAvailableBefore ses point = do
pointN <- bindingNumber point
nameNs <- mapM bindingNumber $ subExpVars ses
return $ all (< pointN) nameNs
isInCurrentBody :: VName -> ForwardingM Bool
isInCurrentBody name = do
current <- asks topDownDepth
res <- asks $ fmap entryDepth . HM.lookup name . topDownTable
case res of Just d -> return $ d == current
Nothing -> fail $ "isInCurrentBody: variable " ++
pretty name ++ " not found."
isOptimisable :: VName -> ForwardingM Bool
isOptimisable name = do
res <- asks $ fmap entryOptimisable . HM.lookup name . topDownTable
case res of Just b -> return b
Nothing -> fail $ "isOptimisable: variable " ++
pretty name ++ " not found."
seenVar :: VName -> ForwardingM ()
seenVar name = do
aliases <- asks $
maybe mempty entryAliases .
HM.lookup name . topDownTable
tell $ mempty { bottomUpSeen = HS.insert name aliases }
tapBottomUp :: ForwardingM a -> ForwardingM (a, BottomUp)
tapBottomUp m = do (x,bup) <- listen m
return (x, bup)
maybeForward :: VName
-> VName -> LetAttr (Aliases Kernels) -> Certificates -> VName -> SubExp
-> ForwardingM Bool
maybeForward v dest_nm dest_attr cs src i = do
-- Checks condition (2)
available <- [i,Var src] `areAvailableBefore` v
-- ...subcondition, the certificates must also.
certs_available <- map Var cs `areAvailableBefore` v
-- Check condition (3)
samebody <- isInCurrentBody v
-- Check condition (6)
optimisable <- isOptimisable v
not_prim <- not . primType <$> lookupType v
if available && certs_available && samebody && optimisable && not_prim then do
let fwd = DesiredUpdate dest_nm dest_attr cs src [i] v
tell mempty { forwardThese = [fwd] }
return True
else return False
| mrakgr/futhark | src/Futhark/Optimise/InPlaceLowering.hs | bsd-3-clause | 11,234 | 0 | 22 | 3,249 | 2,880 | 1,473 | 1,407 | 208 | 5 |
module Data.Geo.GPX.Lens.AgeofdgpsdataL where
import Data.Lens.Common
class AgeofdgpsdataL a where
ageofdgpsdataL :: Lens a (Maybe Double)
| tonymorris/geo-gpx | src/Data/Geo/GPX/Lens/AgeofdgpsdataL.hs | bsd-3-clause | 144 | 0 | 9 | 20 | 40 | 23 | 17 | 4 | 0 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Main (main) where
import ACME
import Control.Monad.Catch
import Control.Monad.IO.Class
import Control.Monad.State as State
import Crypto.Hash
import Crypto.PubKey.RSA hiding (Error)
import Data.ASN1.BinaryEncoding
import Data.ASN1.Encoding
import Data.ASN1.Types
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as Char
import qualified Data.ByteString.Lazy as L
import Data.Hourglass
import Data.List (foldl')
import Data.PEM
import qualified Data.Text as T
import Data.X509
import Data.X509.File
import Data.X509.PKCS10 as CSR hiding (subject)
import PKCS1
import System.Directory (doesFileExist)
import System.Environment (getArgs, getProgName)
import System.Exit (die)
import System.Hourglass
import System.IO (hPutStrLn, stderr)
import Text.Printf
import Utils
decodeDER :: Char.ByteString -> Either String [ASN1]
decodeDER = either (Left . show) Right . decodeASN1' DER
keyFromDER :: Char.ByteString -> Either String PrivateKey
keyFromDER bs = getPrivateKey . fst <$> (decodeDER bs >>= fromASN1)
keyFromPEM :: PEM -> Either String PrivateKey
keyFromPEM pem =
if pemName pem == "RSA PRIVATE KEY"
then keyFromDER . pemContent $ pem
else Left "PEM: unknown format"
newtype PKCSException = PKCSError String deriving (Show, Typeable)
instance Exception PKCSException where
displayException (PKCSError e) = "PKCS Error: " ++ e
keyFromFile :: (MonadIO m, MonadThrow m) => FilePath -> m PrivateKey
keyFromFile file = do
bytes <- liftIO $ B.readFile file
pems <- PKCSError `throwIfError` pemParseBS bytes
pem <- PKCSError ("pem container '" ++ file ++ "' is corrupted or empty") `throwIfNothing` headMay pems
PKCSError `throwIfError` keyFromPEM pem
certChainToPEM :: CertificateChain -> L.ByteString
certChainToPEM chain =
let CertificateChainRaw encoded = encodeCertificateChain chain in
L.concat $ certToPEM <$> encoded
where
certToPEM bytes = pemWriteLBS $ PEM "CERTIFICATE" [] bytes
makeCSR :: PrivateKey -> [String] -> AcmeM CertificationRequest
makeCSR domainPriv domains = do
csr <- liftIO $ generateCSR subject extAttrs keyPair SHA256
(PKCSError . show) `throwIfError` csr
where
keyPair = KeyPairRSA (private_pub domainPriv) domainPriv
subject = X520Attributes []
altNames = AltNameDNS <$> domains
extAttrs = PKCS9Attributes [PKCS9Attribute $ ExtSubjectAltName altNames]
logStrLn :: (MonadIO m, MonadState Int m, PrintfArg r) => String -> r -> m ()
logStrLn format args = do
step <- State.get
liftIO $ hPrintf stderr ("[%v] " ++ format ++ "\n") step args
State.put $ succ step
retrieveCert :: ChainFetchOptions -> PrivateKey -> String -> [String] -> AcmeM L.ByteString
retrieveCert fetchOpts domainKey webroot domains =
flip evalStateT 1 $ do
regUrl <- lift acmeNewReg
logStrLn "Registered account with url '%v'" regUrl
_ <- lift $ acmeAgreeTOS regUrl
logStrLn "%s" "Agreed to TOS"
forM_ domains $ \domain -> do
logStrLn "Performing HTTP validation for domain '%v'..." domain
_ <- lift $ acmeNewHttp01Authz webroot $ T.pack domain
logStrLn "Completed challenge for domain '%v'" domain
chain <- lift (acmeNewCert fetchOpts =<< makeCSR domainKey domains)
logStrLn "Obtained certificate chain of length %v" (chainLength chain)
return $ certChainToPEM chain
where
chainLength (CertificateChain c) = length c
data Options = Options { optDirectoryUrl :: String
, optWebroot :: String
, optAccoutKey :: String
, optDomainKey :: String
, optDomains :: [String]
, optRenewCert :: Maybe FilePath
, optRenewDuration :: Duration
, optFetchChain :: ChainFetchOptions
}
defaultStagingDirectory :: String
defaultStagingDirectory = "https://acme-staging.api.letsencrypt.org/directory"
defaultDirectory :: String
defaultDirectory = "https://acme-v01.api.letsencrypt.org/directory"
defaultOptions :: Options
defaultOptions = Options defaultStagingDirectory mzero mzero mzero mzero mzero oneWeek ChainFull
where
oneWeek = mempty { durationHours = 24 * 7 }
options :: [OptDescrEx (Options -> Options)]
options =
[ OptOption $ Option ['D'] ["directory-url"]
(OptArg
(\o opts -> opts { optDirectoryUrl = fromMaybe defaultDirectory o })
"URL"
) "The ACME directory URL.\n\
\If this option is specified without URL, the Let's Encrypt directory is\n\
\used. For testing purposes this option can be omitted, in which case the\n\
\Let's Encrypt staging directory is used. Note that certificates issued by\n\
\the staging environment are not trusted.\n\n"
, ReqOption $ Option ['w'] ["webroot"]
(ReqArg
(\o opts -> opts { optWebroot = o })
"DIR"
) "Path to the webroot for responding to http challenges.\n\n"
, ReqOption $ Option ['a'] ["account-key"]
(ReqArg
(\o opts -> opts { optAccoutKey = o })
"FILE"
) "The ACME account key.\n\n"
, ReqOption $ Option ['d'] ["domain-key"]
(ReqArg
(\o opts -> opts { optDomainKey = o })
"FILE"
) "Key for issuing the certificate.\n\n"
, OptOption $ Option ['r'] ["renew"]
(ReqArg
(\o opts -> opts { optRenewCert = Just o })
"FILE"
) "An optional certificate that is checked for impending expiration.\n\
\If renewal is required the certificate is replaced by a newly issued one.\n\
\Otherwise, no action is performed.\n\n"
, OptOption $ Option ['h'] ["head"]
(NoArg
(\opts -> opts { optFetchChain = ChainHead })
) "Fetch only the leaf certificate and not the full certificate chain."
]
parseOptions :: [String] -> IO Options
parseOptions args =
case getOptReq options args of
(True, opts, domains, []) -> processOptions opts domains
(False, _, _, _) -> getProgName >>= dieWithUsage []
(_, _, _, errs) -> getProgName >>= dieWithUsage (errs ++ ["\n"])
where
header :: String -> String
header prog = "Usage: " ++ prog ++ " [OPTION...] domains...\n"
dieWithUsage errs prog = die $ concat errs ++ usageInfo (header prog) (getOptDescr <$> options)
processOptions opts domains =
if null domains then
getProgName >>= dieWithUsage []
else
return $ (foldl' (flip id) defaultOptions opts) { optDomains = domains }
renewRequired :: Options -> IO Bool
renewRequired opts =
case optRenewCert opts of
Nothing -> pure True
Just certPath -> doesFileExist certPath >>= \exists ->
if not exists then pure True else do
certs :: [SignedCertificate] <- readSignedObject certPath
time <- dateCurrent
pure $ any (isExpired time . getCertificate) certs
where
isExpired time cert = (validityEnd cert `timeDiff` renewStart time) < 0
validityEnd = snd . certValidity
renewStart time = time `timeAdd` optRenewDuration opts
main :: IO ()
main = do
opts @ Options {..} <- parseOptions =<< getArgs
flip catchAll (die . displayException) $ do
renew <- renewRequired opts
if not renew then
hPutStrLn stderr $ "Certificate '" <> fromMaybe "" optRenewCert <> "' does not require renewal."
else do
accountKey <- keyFromFile optAccoutKey
domainKey <- keyFromFile optDomainKey
cert <- runAcmeM accountKey optDirectoryUrl $ retrieveCert optFetchChain domainKey optWebroot optDomains
case optRenewCert of
Nothing -> L.putStr cert
Just certPath -> L.writeFile certPath cert
| sam142/hasencrypt | src/Main.hs | bsd-3-clause | 8,065 | 1 | 17 | 2,080 | 2,041 | 1,071 | 970 | 167 | 4 |
module PIC.Simulator
( simulate
) where
import Data.Bits
import Data.IntMap as Map hiding ( null, filter )
import PIC.Assemble
import PIC.Configuration
import Utils
-- | Execution violations.
data Violation
= NoMoreInstructions
| InvalidGOTO
| InvalidSkip
deriving Show
-- | The state of the machine.
data State = State
{ completedCycles :: Int
, prevInstrs
, nextInstrs :: [Instruction]
, regFile :: Map.IntMap Int
, regW :: Int
, remainingAssertions :: [(String,[Instruction])]
, assertionViolations :: Bool
}
instance Show State where
show state = show (head (nextInstrs state)) ++
" W=" ++ show (regW state) ++
" Z=" ++ (if testBit (regFile state ! status) zero then "1" else "0") ++
" C=" ++ (if testBit (regFile state ! status) carry then "1" else "0") ++
" " ++ show (regFile state) ++ "\n"
simulate :: String -> Maybe Int -> ProgramAbs -> IO Bool
simulate name cycles program = do
result <- run name config cycles (initState dMD program)
case result of
Left NoMoreInstructions -> do
putStrLn "ERROR: Program ran out of instructions to execute."
return False
Left InvalidGOTO -> do
putStrLn $ "ERROR: Program encountered an invalid GOTO address."
return False
Left InvalidSkip -> do
putStrLn $ "ERROR: Program encountered an invalid skip instruction."
return False
Right state ->
case (completedCycles state, assertionViolations state, remainingAssertions state) of
(_,False,[]) -> return True
(_,True,[]) -> do
putStrLn $ "ERROR: Simulation " ++ name ++ " failed with assertion violations."
return False
(_,False,remaining) -> do
putStrLn $ "ERROR: Simulation " ++ name ++ " failed to check the following assertions:"
mapM_ (\ (n,_) -> putStrLn $ " " ++ n) remaining
return False
(_,True,remaining) -> do
putStrLn $ "ERROR: Simulation " ++ name ++ " failed with assertion violations and failed to check the following assertions:"
mapM_ (\ (n,_) -> putStrLn $ " " ++ n) remaining
return False
where
dMD = dataMemoryDepth config
config = basicConfig
initState :: Int -> ProgramAbs -> State
initState regFileDepth program = State
{ completedCycles = 0
, prevInstrs = []
, nextInstrs = instrs
, regFile = initRegFile regFileDepth
, regW = 0
, remainingAssertions = assertions instrs
, assertionViolations = False
}
where
ProgramRel instrs = relative program
assertions :: [Instruction] -> [(String,[Instruction])]
assertions [] = []
assertions i@(ASSERT name _ : is) = (name,i) : assertions is
assertions (_:is) = assertions is
initRegFile :: Int -> Map.IntMap Int
initRegFile depth = foldl (\ m i -> Map.insert i 0 m) Map.empty [0 .. depth - 1]
run :: String -> Configuration -> Maybe Int -> State -> IO (Either Violation State)
run _ _ (Just cycles) state | cycles <= 0 = return $ Right state
run n config (Just cycles) state = do stepResult <- step n config state
case stepResult of
Left violation -> return (Left violation)
Right s -> run n config (Just $ cycles - 1) s
run _ _ Nothing state | null (remainingAssertions state) = return $ Right state
run n config Nothing state = do stepResult <- step n config state
case stepResult of
Left violation -> return (Left violation)
Right s -> run n config Nothing s
step :: String -> Configuration -> State -> IO (Either Violation State)
step _ _ (State { nextInstrs = [] }) = return $ Left NoMoreInstructions
step name config state' = newState
where
state = state'
newState = case current of
ADDLW k -> carryLW (w + k)
ADDWF f d -> carryWF f d (w +)
ANDLW k -> basicLW (w .&. k)
ANDWF f d -> basicWF f d (w .&.)
ASSERT n f -> if testBit (regFileMap ! f) 0
then do
putStrLn $ "Assertion Passed : " ++ name ++ "." ++ n
return $ Right $ nextState'
else do
putStrLn $ "ERROR: Assertion Failed : " ++ name ++ "." ++ n
return $ Right $ nextState' { assertionViolations = True }
where
nextState' = nextState { remainingAssertions = remAsserts }
remAsserts = filter isNotAssert (remainingAssertions state)
isNotAssert (_,i) = i /= (current : next)
BSF f b -> return $ Right $ nextState { regFile = adjust (\ v -> setBit v b) f regFileMap }
BTFSC f b -> if not bitSet && null next then return $ Left $ InvalidSkip else return $ Right $ nextState'
where
bitSet = testBit (regFileMap ! f) b
nextState' = if bitSet then nextState else nextStateSkip
BTFSS f b -> if bitSet && null next then return $ Left $ InvalidSkip else return $ Right $ nextState'
where
bitSet = testBit (regFileMap ! f) b
nextState' = if bitSet then nextStateSkip else nextState
CLRF f -> basicWF f F (\ _ -> 0)
COMF f d -> basicWF f d complement
GOTO k | k == 0 -> return $ Right $ nextState { prevInstrs = prev, nextInstrs = current : next }
GOTO k | k < 0 && abs k > length prev -> return $ Left InvalidGOTO
GOTO k | k > 0 && k - 1 > length next -> return $ Left InvalidGOTO
GOTO k | k < 0 -> return $ Right $ nextState { prevInstrs = drop (abs k) prev, nextInstrs = reverse (take (abs k) prev) ++ current : next }
GOTO k -> return $ Right $ nextState { prevInstrs = reverse (take (k - 1) next) ++ current : prev, nextInstrs = drop (k - 1) next }
INCFSZ f d ->
if v == 0 && null next then return $ Left $ InvalidSkip else return $ Right $ nextState2
where
v = mask ((regFileMap ! f) + 1)
nextState1 = if v == 0 then nextStateSkip else nextState
nextState2 = case d of
W -> nextState1 { regW = v }
F -> nextState2 { regFile = insert f v regFileMap }
IORWF f d -> basicWF f d (w .|.)
MOVLW k -> return $ Right $ nextState { regW = k }
MOVF f d -> basicWF f d id
MOVWF f -> return $ Right $ nextState { regFile = insert f w regFileMap }
NOP -> return $ Right $ nextState
SUBWF f d -> carryWF f d (\ r -> r - w)
XORWF f d -> basicWF f d (xor w)
prev = prevInstrs state
(current : next) = nextInstrs state
w = regW state
regFileMap = regFile state
nextState = state
{ completedCycles = completedCycles state + 1
, prevInstrs = current : prev
, nextInstrs = next
}
nextStateSkip = nextState { prevInstrs = head next : current : prev, nextInstrs = tail next }
dW = dataWidth config
mask i = i .&. (power 2 dW - 1)
zeroStatus :: Int -> (Int,IntMap Int)
zeroStatus v = (v',insert status ((if v' == 0 then setBit else clearBit) (regFileMap ! status) zero) regFileMap)
where
v' = mask v
zeroCarryStatus :: Int -> (Int,IntMap Int)
zeroCarryStatus v = (v', regFileMap'')
where
(v',regFileMap') = zeroStatus v
regFileMap'' = insert status ((if testBit v dW then setBit else clearBit) (regFileMap' ! status) carry) regFileMap
basicLW :: Int -> IO (Either Violation State)
basicLW v = return $ Right $ nextState { regW = v', regFile = regFileMap' }
where
(v',regFileMap') = zeroStatus v
basicWF :: Int -> D -> (Int -> Int) -> IO (Either Violation State)
basicWF reg W f = return $ Right $ nextState { regW = v', regFile = regFileMap' }
where
(v',regFileMap') = zeroStatus (f (regFileMap ! reg))
basicWF reg F f = return $ Right $ nextState { regFile = regFileMap'' }
where
(v',regFileMap') = zeroStatus (f (regFileMap ! reg))
regFileMap'' = insert reg v' regFileMap'
carryLW :: Int -> IO (Either Violation State)
carryLW v = return $ Right $ nextState { regW = v', regFile = regFileMap' }
where
(v',regFileMap') = zeroCarryStatus v
carryWF :: Int -> D -> (Int -> Int) -> IO (Either Violation State)
carryWF reg W f = return $ Right $ nextState { regW = v', regFile = regFileMap' }
where
(v',regFileMap') = zeroCarryStatus (f (regFileMap ! reg))
carryWF reg F f = return $ Right $ nextState { regFile = regFileMap'' }
where
(v',regFileMap') = zeroCarryStatus (f (regFileMap ! reg))
regFileMap'' = insert reg v' regFileMap'
status = 3
carry = 0
zero = 2
| tomahawkins/trs | attic/PIC/Simulator.hs | bsd-3-clause | 8,900 | 0 | 20 | 2,830 | 3,073 | 1,585 | 1,488 | 168 | 35 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
-- | Will Jones' style.
module HIndent.Styles.WillJones where
import HIndent.Pretty
import HIndent.Styles.WillJones.Data
import HIndent.Styles.WillJones.Modules
import HIndent.Styles.WillJones.Types
import HIndent.Types
import Control.Monad.State
import Language.Haskell.Exts.Annotated.Syntax
--------------------------------------------------------------------------------
-- Style configuration
data State =
State
willJones :: Style
willJones =
Style {styleName = "will-jones"
,styleAuthor = "Will Jones"
,styleDescription = "Will Jones' personal style."
,styleInitialState = State
,styleExtenders =
[Extender prettyModule
,Extender prettyModuleHead
,Extender prettyDecl]
,styleDefConfig =
defaultConfig {configMaxColumns = 80
,configIndentSpaces = 2
}
,styleCommentPreprocessor = return}
--------------------------------------------------------------------------------
-- Extenders
-- | Pretty print a declaration
prettyDecl :: Decl NodeInfo -> Printer s ()
prettyDecl (TypeDecl _ declHead ty) =
prettyTySynDecl declHead ty
prettyDecl (TypeFamDecl _ declHead mkind) =
prettyTyFamDecl declHead mkind
prettyDecl (DataDecl _ dataOrNewtype mctx declHead cons mderiv) =
case dataOrNewtype of
DataType _ ->
prettyDataDecl mctx declHead cons mderiv
NewType _ ->
case cons of
[con] ->
prettyNewtypeDecl mctx declHead con mderiv
_ ->
fail "Data types declared using 'newtype' must have exactly one constructor"
prettyDecl (TypeSig _ names ty) =
prettyTySig names ty
prettyDecl (PatSynSig loc name mtyVars mctx1 mctx2 ty) =
prettyPatSynSig loc name mtyVars mctx1 mctx2 ty
prettyDecl e = prettyNoExt e
-- | Pretty print a type synonym like
--
-- type Foo a
-- = forall m n.
-- (Monad m,
-- Monad n)
-- => m (n a)
-- -> n (m a)
--
prettyTySynDecl :: (MonadState (PrintState s) m)
=> DeclHead NodeInfo
-> Type NodeInfo
-> m ()
prettyTySynDecl declHead ty =
do write "type "
pretty declHead
newline
depend (write " = ")
(prettyTy ty)
-- | Pretty print a type family declaration like
--
-- type family Foo (a :: *) (m :: * -> *)
-- :: *
-- -> *
prettyTyFamDecl :: (MonadState (PrintState s) m)
=> DeclHead NodeInfo
-> Maybe (Kind NodeInfo)
-> m ()
prettyTyFamDecl declHead mkind =
do write "type family "
pretty declHead
case mkind of
Nothing -> return ()
Just kind ->
do newline
depend (write " :: ")
(prettyKind kind)
-- | Pretty print a type signature like
--
-- fooBar
-- :: (Applicative f,
-- Monad m)
-- => (a -> f b)
-- -> m a
-- -> f (m b)
--
prettyTySig :: (MonadState (PrintState s) m)
=> [Name NodeInfo]
-> Type NodeInfo
-> m ()
prettyTySig names ty =
do depend (do inter (write ", ")
(map pretty names)
newline
write " :: ")
(prettyTy ty)
-- | Pretty print a pattern synonym type signature like
--
-- Foo
-- :: (Applicative f,
-- Applicative g)
-- => (Monad m,
-- Monad n)
-- => f (g a)
-- -> T (m (n a))
--
prettyPatSynSig :: (MonadState (PrintState s) m)
=> NodeInfo
-> Name NodeInfo
-> Maybe [TyVarBind NodeInfo]
-> Maybe (Context NodeInfo)
-> Maybe (Context NodeInfo)
-> Type NodeInfo
-> m ()
prettyPatSynSig loc name mtyVars mctx1 mctx2 ty =
do write "pattern "
pretty name
newline
depend (write " :: ")
(prettyTy (TyForall loc mtyVars mctx1
(TyForall loc Nothing mctx2 ty)))
| lunaris/hindent | src/HIndent/Styles/WillJones.hs | bsd-3-clause | 3,975 | 0 | 14 | 1,227 | 876 | 456 | 420 | 94 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.