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
module Main where import MigratePersonStatementsPersonId main = moveToNewTable
tippenein/scrape_the_truth
migrations/Main.hs
mit
81
0
4
10
12
8
4
3
1
{-# LANGUAGE QuasiQuotes, TemplateHaskell, TypeFamilies, RecordWildCards, OverloadedStrings, DeriveGeneric, GeneralizedNewtypeDeriving #-} module Tach.Periodic where import Prelude hiding (foldl) import Tach.Periodic.Internal import System.Random import Control.Applicative import GHC.Generics import Data.Maybe import qualified Data.Sequence as S import qualified Data.Foldable as F newtype PeriodicData a = PeriodicData { unPeriodicData :: S.Seq a } deriving (Eq, Show, Generic) newtype APeriodicData a = APeriodicData { unAPeriodicData :: S.Seq a } deriving (Eq, Show, Generic) data TVData a = TVPeriodic (PeriodicData a) | TVAPeriodic (APeriodicData a) deriving (Eq, Show, Generic) data PeriodicFolding a = PeriodicFolding { firstPeriodic :: Int ,periodicCount :: Int ,timeValueData :: [TVData a] } tvDataToEither :: TVData a -> Either (APeriodicData a) (PeriodicData a) tvDataToEither (TVPeriodic x) = Right x tvDataToEither (TVAPeriodic x) = Left x --testData :: IO [TVData Double] --testData = do -- rData <- genRandomData (0,10000) (10,100) -- return $ combineAperiodic $ classifyPeriodic 10 10 rData testList :: [Double] testList = aperiodicTimeData 515.0 1000.0 100 seqToList :: S.Seq a -> [a] seqToList = (F.foldr' (\item list -> item:list) []) combineAperiodic :: S.Seq (TVData a) -> S.Seq (TVData a) combineAperiodic = F.foldl' combineAperiodicFold S.empty classifyData :: (Num a, Ord a) => a -> a -> Int -> (b -> a) -> [b] -> ([TVData b]) classifyData period delta minPeriodicSize toNumFunc list = seqToList . combineAperiodic . (removePeriodicBelow minPeriodicSize) $ classifyPeriodic period delta toNumFunc (S.fromList list) removePeriodicBelow :: Int -> S.Seq (TVData a) -> S.Seq (TVData a) removePeriodicBelow minSize list = (setAperiodicBelow minSize) <$> list setAperiodicBelow :: Int -> (TVData a) -> (TVData a) setAperiodicBelow minSize val@(TVPeriodic (PeriodicData periodic)) = if ((S.length periodic) < minSize) then TVAPeriodic $ APeriodicData periodic else val setAperiodicBelow _ b = b -- Appends the TVData to the last element of the TVData list if both are aperiodic combineAperiodicFold :: S.Seq (TVData a) -> TVData a -> S.Seq (TVData a) combineAperiodicFold list item = let end = lastMaySeq list in case end of Nothing -> S.singleton item (Just (TVAPeriodic (APeriodicData periodicList))) -> case item of (TVAPeriodic (APeriodicData aSeq)) -> (initSeq list) S.|> (TVAPeriodic $ APeriodicData (periodicList S.>< aSeq)) _ -> list S.|> item (Just (TVPeriodic (PeriodicData _))) -> list S.|> item classifyPeriodic :: (Num a, Ord a) => a -> a -> (b -> a) -> S.Seq b -> S.Seq (TVData b) classifyPeriodic period delta toNumFunc list = F.foldl' (takePeriodic period delta toNumFunc) S.empty list -- | The function that folds over a list and looks for any matches in a period takePeriodic :: (Num a, Ord a) => a -> a -> (b -> a) -> S.Seq (TVData b) -> b -> S.Seq (TVData b) takePeriodic period delta toNumFunc old current = let maxPeriod = period + delta minPeriod = period - delta mLast = lastMaySeq old in case mLast of Nothing -> S.singleton $ TVAPeriodic $ APeriodicData (S.singleton current) (Just (TVPeriodic (PeriodicData periodData))) -> let firstVal = lastSeq periodData difference = abs $ (toNumFunc current) - (toNumFunc firstVal) in if ((difference <= maxPeriod) && (difference >= minPeriod)) then ((initSeq old) S.|> (TVPeriodic . PeriodicData $ periodData S.|> current)) else ((old) S.|> (TVAPeriodic $ APeriodicData (S.singleton current))) (Just (TVAPeriodic (APeriodicData aperiodicData))) -> let lastVal = lastSeq aperiodicData difference = abs $ (toNumFunc current) - (toNumFunc lastVal) in if ((difference <= maxPeriod) && (difference >= minPeriod)) then ((initSeq old) S.|> (TVPeriodic . PeriodicData $ aperiodicData S.|> current)) else (old S.|> (TVAPeriodic $ APeriodicData (S.singleton current))) headSeq :: S.Seq a -> a headSeq = fromJust . headMaySeq headMaySeq :: S.Seq a -> Maybe a headMaySeq aSeq = if (len >= 1) then Just $ S.index aSeq (len - 1) else Nothing where len = S.length aSeq initSeq :: S.Seq a -> S.Seq a initSeq aSeq = if (len >= 1) then if (len == 1) then S.empty else S.take (len - 1) aSeq else S.empty where len = S.length aSeq lastSeq :: S.Seq a -> a lastSeq = fromJust . lastMaySeq lastMaySeq :: S.Seq a -> Maybe a lastMaySeq aSeq = if (len >= 1) then Just $ S.index aSeq (len - 1) else Nothing where len = S.length aSeq periodStart :: Double -> Int -> Int -> [Int] periodStart start count period = take count [(round start) + (x*period) | x <- [0..]] --classifiy :: [(Double, Double)] -> V.Vector --classify xs = foldl' addPeriodic [] --addPeriodic :: linSpace :: Double -> Double -> Int -> [Double] linSpace start end n | n-1 <= 0 = [] | otherwise = map (\x -> (x * mult) + start) (take (n - 1) [0..]) where mult = (end - start) / (fromIntegral l) l = n-1 :: Int aperiodicTimeData :: Double -> Double -> Int -> [Double] aperiodicTimeData start end n = [x+(sin x) | x <- (linSpace start end n)] randomChunks :: Double -> Double -> Double -> Double -> IO [(Double,Double)] randomChunks start end minStep maxStep | (end - start) < minStep = return [(start,end+minStep)] | otherwise = do step <- randomRIO (minStep,maxStep) let newEnd = start+step case newEnd > end of True -> return [(start,end)] False -> do xs <- randomChunks (newEnd + 16) end minStep maxStep return $ (start,newEnd):xs getRandomList :: Int -> (Int,Int) -> IO [Int] getRandomList size range = mapM (\_ -> randomRIO range) [1..size] randomData :: (Double,Double) -> IO (TVData Double) randomData (start,end) = do randomChoice <- randomRIO (0,10) :: IO Int case randomChoice of _ | randomChoice <= 5 -> do --Get a period with 15 second intervals let xs = linSpace start end (round ((end - start)/15)) return . TVPeriodic . PeriodicData . S.fromList $ xs | otherwise -> do randomCount <- randomRIO ((end - start)/15, (end - start)/200) let xs = aperiodicTimeData start end (round randomCount) return . TVAPeriodic . APeriodicData . S.fromList $ xs genRandomData :: (Double,Double) -> (Double, Double) -> IO [(TVData Double)] genRandomData (start,end) (minStep,maxStep) = do chunks <- randomChunks start end minStep maxStep chunkedData <- mapM randomData chunks return . removeEmptyRandoms $ chunkedData removeTVData :: (Num a, Ord a) => [TVData a] -> [a] removeTVData list = F.foldl' removeTVDataFold [] list removeTVDataFold :: (Num a, Ord a) => [a] -> TVData a -> [a] removeTVDataFold list item =list ++ (seqToList . unTVData $ item) unTVData :: (Num a, Ord a) => TVData a -> S.Seq a unTVData (TVPeriodic (PeriodicData c)) = c unTVData (TVAPeriodic (APeriodicData b)) = b removeEmptyRandoms :: [TVData Double] -> [TVData Double] removeEmptyRandoms xs = F.foldl' remEmpty [] xs remEmpty :: [TVData Double] -> TVData Double -> [TVData Double] remEmpty ys xs@(TVPeriodic (PeriodicData x)) = if (S.null x) then ys else (ys ++ [xs]) remEmpty ys xs@(TVAPeriodic (APeriodicData x)) = if (S.null x) then ys else (ys ++ [xs])
smurphy8/tach
core-libs/tach-periodic/src/Tach/Periodic.hs
mit
7,433
0
22
1,574
2,858
1,491
1,367
148
5
fact :: Double -> Double fact 0 = 1 fact n = n * fact(n-1) solve :: Double -> Double solve x = sum $ map (\y -> x ** y / fact y) [0,1..9] main :: IO () main = getContents >>= mapM_ print. map solve. map (read::String->Double). tail. words
jerryzh168/hackerrank
FunctionalProgramming/Introduction/EvaluatingEX.hs
mit
240
0
10
52
147
75
72
7
1
-- Dieses Modul definiert einen Algebraischen Datentyp der im Codegenerator zur Generierung des Zielcodes benötigt. Er enthält die % TODO : Referenz -- Komponenten ID, sowie benannte Ein- und Ausgangspins. module System.ArrowVHDL.Circuit.PinTransit where -- Benötigt werden Modul-Definitionen aus \hsSource{Circuit}. import System.ArrowVHDL.Circuit.Descriptor -- \subsection{Datenstruktur} -- Zunächst werden Typaliasse angelegt, welche die verwendeten Datentypen nach ihrer Aufgabe benennen. type NamedPin = (PinID, String) type InNames = [NamedPin] type OutNames = [NamedPin] type NamedComp = (CompID, (InNames, OutNames)) -- \subsection{Funktionen} -- Um die interne Datenstruktur des Algebraischen Datentypes bedienen zu können, werden folgende Funktionen definiert -- generateNamedComps % \\ Eine Funktion die aus einem CircuitDescriptor die Benamte Komponentenliste erstellt -- getInPinNames % \\ Eine Funktion die eine In-PinID / Namen's Liste aus der NamedComp Liste erzeugt -- getOutPinNames % \\ Eine Funktion die eine Out-PinID / Namen's Liste aus der NamedComp Liste erzeugt -- getInPinName % \\ Eien weitere Funktion die ein InPinID/Namens Paar aus der NamedComp Liste und aus einer PinID erstellt -- getOutPinName % \\ Eien weitere Funktion die ein OutPinID/Namens Paar aus der NamedComp Liste und aus einer PinID erstellt -- Die Funktion \hsSource{generateNamedComps} erzeugt die benannten Komponenten Liste. Hier werden nur die Pins benannt. Ein Pin kann immer von -- zwei Seiten aus gesehen werden. Es gibt \begriff{externe} Pins, also Pins, die an die von außen ein Draht angeschlossen werden kann. Diese -- werden unter dem namen \hsSource{generateSuperNames} zusammengefasst. Daneben existieren auch \begriff{interne} Pins, die man hinter dem -- Namen \hsSource{generateSubNames} findet. Diese Unterscheidung muss getroffen werden, da externe Pins mit den Präfixen \hsSource{nameExI} -- und \hsSource{nameExO} versehen werden. Interne Pins werden mit \hsSource{nameInI} sowie \hsSource{NameInO} benamt. -- \hsSource{generateSuperNames} wird auf den übergebenen \hsSource{CircuitDescriptor} angewandt, die Funktion \hsSource{generateSubNames} -- hingegen auf alle dem \hsSource{CircuitDescriptor} untergeordneten \hsSource{CircuitDescriptor}en. generateNamedComps :: CircuitDescriptor -> [NamedComp] generateNamedComps g = generateSuperNames g : (map generateSubNames $ nodes g) where generateSuperNames g = ( (nodeId.nodeDesc) g , ( namePins (sinks.nodeDesc) nameExI g , namePins (sources.nodeDesc) nameExO g ) ) generateSubNames g = ( (nodeId.nodeDesc) g , ( namePins (sinks.nodeDesc) nameInI g , namePins (sources.nodeDesc) nameInO g ) ) -- Die beiden Funktionen \hsSource{getNamedInPins} sowie \hsSource{getInPinNames} holen jeweils aus einer Liste von \hsSource{NamedComp} und -- einer \hsSource{CompID} den passenden Datensatz heraus. Hierbei unterscheiden sie sich lediglich im Rückgabetyp voneinander. So liefert -- \hsSource{getNamedInPins} die \hsSource{InNames}, also eine Liste benannter Pins, zurück. \hsSource{getInPinNames} liefert nur eine Liste -- der Namen. -- TODO: is fst the right function to get the in-names ??? getNamedInPins :: [NamedComp] -> CompID -> InNames getNamedInPins = getPinNames fst getInPinNames :: [NamedComp] -> CompID -> [String] getInPinNames cname cid = map snd $ getNamedInPins cname cid -- Die beiden nächsten Funktionen, \hsSource{getNamedOutPins} sowie \hsSource{getOutPinNames} verhalten sich analog zu den beiden -- \begriff{InPin} varianten, mit dem Unterschied, dass diese beiden Funktionen sich auf die Ausgabepins beziehen. -- TODO: is snd the right function to get the out-names ??? getNamedOutPins :: [NamedComp] -> CompID -> OutNames getNamedOutPins = getPinNames snd getOutPinNames :: [NamedComp] -> CompID -> [String] getOutPinNames cname cid = map snd $ getNamedOutPins cname cid -- Mit der Funktion \hsSource{getPinNames} wird die eigentliche Logik beschrieben, die für das herausfiltern der Pin-Namen notwendig ist. Aus -- der übergebenen Liste der benannten Komponenten werden all die Komponenten heraus gefiltert, die der ebenfalls übergebenen Komponenten ID -- entsprechen. Im nächsten Schritt (\hsSource{map snd}) wird die Komponenten ID verworfen. Die übergeben Funktion \hsSource{f} definiert nun, -- ob das Ergebnis eingehende oder ausgehende Pins sind. Der letzte Schritt entfernt überflüssige Listen-Verschachtelungen. getPinNames :: (([NamedPin], [NamedPin]) -> [NamedPin]) -> [NamedComp] -> CompID -> [(PinID, String)] getPinNames f cname cid = concat $ map f $ map snd $ filter (\(x, _) -> x == cid) $ cname -- Die folgenden fünf Funktionen arbeiten analog zu den vorhergehenden fünf. Sie unterscheiden sich darin, dass sie einen weiteren Parameter -- erwarten, ein \hsSource{PinID}. Dieser Parameter schränkt die Ergebnismenge auf exakt ein Ergebnis ein, sie liefern also einen benannten -- Pin. getNamedInPin :: [NamedComp] -> CompID -> PinID -> NamedPin getNamedInPin = getPinName getNamedInPins getNamedOutPin :: [NamedComp] -> CompID -> PinID -> NamedPin getNamedOutPin = getPinName getNamedOutPins getInPinName :: [NamedComp] -> CompID -> PinID -> String getInPinName cname cid pid = snd $ getNamedInPin cname cid pid getOutPinName :: [NamedComp] -> CompID -> PinID -> String getOutPinName cname cid pid = snd $ getNamedOutPin cname cid pid getPinName :: ([NamedComp] -> CompID -> [NamedPin]) -> [NamedComp] -> CompID -> PinID -> NamedPin getPinName f cname cid pid = head $ filter (\(x, _) -> x == pid) $ f cname cid -- Die letzte Funktion in diesem Modul erzeugt aus einem \hsSource{CircuitDescriptor} und einem Präfix eine Liste benannter Pins. Diese -- Funktion wird in \hsSource{generateNamedComps} verwendet, um interne und externe Pins mit Namen zu versehen. Je nach übergebenen -- \hsSource{f} produziert \hsSource{namePins} benannte interne oder benannte externe Pinlisten. namePins :: (CircuitDescriptor -> Pins) -> String -> CircuitDescriptor -> [NamedPin] namePins f pre g = map (\x -> (x, pre ++ (show x))) $ f g
frosch03/arrowVHDL
src/System/ArrowVHDL/Circuit/PinTransit.hs
cc0-1.0
6,501
0
12
1,277
786
445
341
45
1
module Main where import Primes ( primeFactors, mergeFactorLists, multiplyFactorList) import Util (runLength) main :: IO () main = let numbers = [1..20] factorLists = map (runLength.primeFactors) numbers merged = foldl mergeFactorLists [] factorLists result = multiplyFactorList merged in print result
liefswanson/projectEuler
app/p1/q5/Main.hs
gpl-2.0
363
0
11
101
97
53
44
14
1
module Requests ( registerRequest, cookieRequest ) where -- sandbox imports import Network.Http.Client (http, Method(GET), setAuthorizationBasic, RequestBuilder, setHeader ) -- local imports import Types registerRequest :: Cookie -> RequestBuilder() registerRequest (Cookie token _ _ _) = http GET "/FIT/st/course-sl.php?xml=f3c30eb7c65a9a46d9fb2a20ad73bf15fe49084c,1423595852&id=568612&log_51900=xml">> setAuthorizationBasic "xkidon00" "vujurhum6o" >> setHeader "User-Agent" "wis register tool" >> setHeader "Accept" "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" >> setHeader "Referer" "https://wis.fit.vutbr.cz/FIT/st/course-sl.php?id=568612&item=51899" >> setHeader "Accept-Encoding" "gzip, deflate" >> setHeader "DNT" "1" >> setHeader "Connection" "keep-alive" >> setHeader "Referer" "https://wis.fit.vutbr.cz/FIT/st/course-sl.php?id=568612" >> setHeader "X-Requested-With" "XMLHttpRequest" cookieRequest :: RequestBuilder () cookieRequest = http GET "https://wis.fit.vutbr.cz/FIT/st/course-sl.php?id=568612&item=51899" >> setAuthorizationBasic "xkidon00" "vujurhum6o" >> setHeader "User-Agent" "wis register tool" >> setHeader "Accept" "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" >> setHeader "Referer" "https://wis.fit.vutbr.cz/FIT/st/" >> setHeader "Accept-Encoding" "gzip, deflate" >> setHeader "DNT" "1" >> setHeader "Connection" "keep-alive" >> setHeader "Referer" "https://wis.fit.vutbr.cz/FIT/st/course-sl.php?id=568612" >> setHeader "X-Requested-With" "XMLHttpRequest"
Tr1p0d/WisRegister
src/Requests.hs
gpl-3.0
1,571
0
14
171
265
131
134
30
1
module QHaskell.TraversalGenerator where import Prelude import Language.Haskell.TH.Syntax hiding (unQ) import Language.Haskell.TH hiding (match) import QHaskell.Expression.Utils.TemplateHaskell import Data.Char import Control.Applicative lowerFirst :: String -> String lowerFirst [] = [] lowerFirst (x : xs) = toLower x : xs getNameCount :: Con -> (Name, [Type]) getNameCount (NormalC n ts) = (n , map snd ts) getNameCount (ForallC _ _ c) = getNameCount c getNameCount (InfixC tl n tr) = getNameCount (NormalC n [tl,tr]) getNameCount _ = error "not supported" nameConsT :: Name nameConsT = (Name (OccName ":") (NameG DataName (PkgName "ghc-prim") (ModName "GHC.Types"))) matchQ :: Type -> Q Type -> Bool matchQ t t' = match t (unQ t') match :: Type -> Type -> Bool match (SigT a _) a' = match a a' match _ (VarT _) = True match (ConT n) (PromotedT n') = n == n' match (PromotedT n) (ConT n') = n == n' match (ConT n) (ConT n') = n == n' match (AppT a b) (AppT a' b') = match a a' && match b b' match PromotedConsT PromotedConsT = True match (PromotedT n) PromotedConsT | n == nameConsT = True match PromotedConsT (PromotedT n) | n == nameConsT = True match PromotedNilT PromotedNilT = True match ArrowT ArrowT = True match ListT ListT = True match (TupleT n) (TupleT n') = n == n' match (PromotedT n) (PromotedT n') = n == n' match _ _ = False {- gen :: Name -> Name -> [Name] -> Q Exp -> Q Exp gen ee n ns e = recAppQ ee n (return . ConE) ns (\ _ -> id) (const e) -} genOverloaded :: Name -> Name -> [Name] -> (Type -> Q Exp) -> Q Exp genOverloaded e t ns f = recAppMQ e t (return . ConE) ns [| id |] [| ($) |] [| ($) |] (const id) f genOverloadedW :: Name -> Name -> [Name] -> (Name -> Q Exp -> Q Exp) -> (Type -> Q Exp) -> Q Exp genOverloadedW e t ns wf f = recAppMQ e t (return . ConE) ns [| id |] [| ($) |] [| ($) |] wf f genOverloadedM :: Name -> Name -> [Name] -> (Type -> Q Exp) -> Q Exp genOverloadedM e t ns f = recAppMQ e t (return . ConE) ns [| pure |] [| (<$>) |] [| (<*>) |] (const id) f genOverloadedMW :: Name -> Name -> [Name] -> (Name -> Q Exp -> Q Exp) -> (Type -> Q Exp) -> Q Exp genOverloadedMW e t ns wf f = recAppMQ e t (return . ConE) ns [| pure |] [| (<$>) |] [| (<*>) |] wf f biGenOverloaded :: Name -> Name -> String -> [Name] -> (Type -> Q Exp) -> Q Exp biGenOverloaded e t g ns f = recAppMQ e t (\ n -> conE (mkName (g ++ "." ++ ( (nameBase n))))) ns [| id |] [| ($) |] [| ($) |] (const id) f biGenOverloadedW :: Name -> Name -> String -> [Name] -> (Name -> Q Exp -> Q Exp) -> (Type -> Q Exp) -> Q Exp biGenOverloadedW e t g ns wf f = recAppMQ e t (\ n -> conE (mkName (g ++ "." ++ ( (nameBase n))))) ns [| id |] [| ($) |] [| ($) |] wf f biGenOverloadedM :: Name -> Name -> String -> [Name] -> (Type -> Q Exp) -> Q Exp biGenOverloadedM e t g ns f = recAppMQ e t (\ n -> conE (mkName (g ++ "." ++ ( (nameBase n))))) ns [| pure |] [| (<$>) |] [| (<*>) |] (const id) f biGenOverloadedMW :: Name -> Name -> String -> [Name] -> (Name -> Q Exp -> Q Exp) -> (Type -> Q Exp) -> Q Exp biGenOverloadedMW e t g ns wf f = recAppMQ e t (\ n -> conE (mkName (g ++ "." ++ ( (nameBase n))))) ns [| pure |] [| (<$>) |] [| (<*>) |] wf f biGenOverloadedL :: Name -> Name -> String -> [Name] -> (Type -> Q Exp) -> Q Exp biGenOverloadedL e t g ns f = recAppMQ e t (\ n -> varE (mkName (g ++ "." ++ (lowerFirst(nameBase n))))) ns [| id |] [| ($) |] [| ($) |] (const id) f biGenOverloadedWL :: Name -> Name -> String -> [Name] -> (Name -> Q Exp -> Q Exp) -> (Type -> Q Exp) -> Q Exp biGenOverloadedWL e t g ns wf f = recAppMQ e t (\ n -> varE (mkName (g ++ "." ++ (lowerFirst(nameBase n))))) ns [| id |] [| ($) |] [| ($) |] wf f biGenOverloadedML :: Name -> Name -> String -> [Name] -> (Type -> Q Exp) -> Q Exp biGenOverloadedML e t g ns f = recAppMQ e t (\ n -> varE (mkName (g ++ "." ++ (lowerFirst(nameBase n))))) ns [| pure |] [| (<$>) |] [| (<*>) |] (const id) f biGenOverloadedMWL :: Name -> Name -> String -> [Name] -> (Name -> Q Exp -> Q Exp) -> (Type -> Q Exp) -> Q Exp biGenOverloadedMWL e t g ns wf f = recAppMQ e t (\ n -> varE (mkName (g ++ "." ++ (lowerFirst(nameBase n))))) ns [| pure |] [| (<$>) |] [| (<*>) |] wf f {- biRecAppMQS :: Name -> Name -> String -> [Name] -> (Name -> Q Exp -> Q Exp) -> Q Exp biRecAppMQS e dn g ns wf = recAppMQ e dn (\ n -> varE (mkName (g ++ "." ++ (lowerFirst (nameBase n))))) ns [| pure |] (varE $ stripNameSpace $ mkName "<$@>") (varE $ stripNameSpace $ mkName "<*@>") wf (const [| id |]) --biRecAppMQ :: Name -> Name -> String -> Q Exp -- biRecAppMQ e dn g = biRecAppMQW e dn g [] (const id) biRecAppQW :: Name -> Name -> String -> [Name] -> (Name -> Q Exp -> Q Exp) -> Q Exp biRecAppQW e dn g ns wf = recAppMQ e dn (\ n -> conE (mkName (g ++ "." ++ nameBase n))) ns [| pure |] (varE $ stripNameSpace $ mkName "<$@>") (varE $ stripNameSpace $ mkName "<*@>") wf (const [| id |]) -} {- biRecAppMQW :: Name -> Name -> String -> [Name] -> (Name -> Q Exp -> Q Exp) -> Q Exp biRecAppMQW e dn g ns wf = recAppMQ e dn (\ n -> conE (mkName (g ++ "." ++ nameBase n))) ns [| id |] [| ($) |] [| ($) |] wf (const [| id |]) biOverloadedW :: Name -> Name -> String -> [Name] -> (Name -> Q Exp -> Q Exp) -> (Type -> Q Exp) -> Q Exp biOverloadedW e dn g = recAppQ e dn (\ n -> conE (mkName (g ++ "." ++ nameBase n))) recAppQ :: Name -> Name -> (Name -> Q Exp) -> [Name] -> (Name -> Q Exp -> Q Exp) -> (Type -> Q Exp) -> Q Exp recAppQ e dn g ns wf fn = recApp e dn (unQ . g) ns (\ n -> unQ . wf n . return) (unQ . fn) recApp :: Name -> Name -> (Name -> Exp) -> [Name] -> (Name -> Exp -> Exp) -> (Type -> Exp) -> Q Exp recApp e dn g ns = recAppM e dn g ns (unQ [| id |]) (unQ [| ($) |]) (unQ [| ($) |]) -} recAppMQ :: Name -> Name -> (Name -> Q Exp) -> [Name] -> Q Exp -> Q Exp -> Q Exp -> (Name -> Q Exp -> Q Exp) -> (Type -> Q Exp) -> Q Exp recAppMQ e dn g ns o0 o1 o2 wf fn = recAppM e dn (unQ . g) ns (unQ o0) (unQ o1) (unQ o2) (\ n -> unQ . wf n . return) (unQ . fn) recAppM :: Name -> Name -> (Name -> Exp) -> [Name] -> Exp -> Exp -> Exp -> (Name -> Exp -> Exp) -> (Type -> Exp) -> Q Exp recAppM e dn g ns o0 o1 o2 wf fn = do TyConI (DataD _ _ _ ds _) <- reify dn return $ CaseE (VarE e) [Match (ConP n [VarP (mkName ("_x" ++ show i)) | i <- [0.. length tl-1]]) (NormalB (case length tl of 0 -> wf n (AppE o0 (g n)) 1 -> wf n (InfixE (Just (g n)) o1 (Just $ AppE (fn (tl!!0)) (VarE (mkName "_x0")))) m -> wf n (foldl (\ es i -> InfixE (Just es) o2 (Just $ AppE (fn (tl!!i)) (VarE (mkName ("_x" ++ show i))))) (InfixE (Just (g n)) o1 (Just$ AppE (fn (tl!!0)) (VarE (mkName "_x0")))) [1 .. m-1]) ) ) [] | d <- ds, let (n , tl) = getNameCount d , not (n `elem` ns)]
shayan-najd/QHaskell
QHaskell/TraversalGenerator.hs
gpl-3.0
11,119
0
32
5,988
2,827
1,488
1,339
-1
-1
module Amoeba.GameStorage.GameStorage where import Amoeba.GameLogic.Facade as GL import Amoeba.GameLogic.GameLogicAccessor as GL import qualified Control.Concurrent.STM.TVar as STM -- Seems wrong. initGameStorage :: GL.Game -> IO GameLogicAccessor initGameStorage = createGameLogicAccessor
graninas/The-Amoeba-World
src/Amoeba/GameStorage/GameStorage.hs
gpl-3.0
294
0
6
32
53
36
17
6
1
-- Perform one of several analyses of apache log files -- -- Neil Mayhew - 2013-10-08 -- -- Adapted from: https://variadic.me/posts/2012-02-25-adventures-in-parsec-attoparsec.html {-# LANGUAGE OverloadedStrings, DeriveGeneric, CPP #-} {-# OPTIONS_GHC -Wno-name-shadowing -Wno-orphans #-} module Main where import Parse import Color import Text.Blaze.Html4.Strict (docTypeHtml, toMarkup, (!)) import Text.Blaze.Html.Renderer.Pretty import qualified Text.Blaze.Html4.Strict as H import qualified Text.Blaze.Html4.Strict.Attributes as A import qualified Data.ByteString.Char8 as BS import qualified Data.HashMap.Strict as M import Data.Either import Data.Functor ((<$>)) import Data.Function import Data.Hashable import Data.IP (IP(..), toHostAddress, toHostAddress6) import Data.List import Data.Maybe import Data.String (fromString) import Data.Time (UTCTime(..), diffUTCTime) import Data.Tuple import Debian.Version (DebianVersion, prettyDebianVersion) import GHC.Generics (Generic) import Text.Printf import Network.URI (unEscapeString) import Control.Arrow (first, second, (&&&)) import Control.Monad import System.Environment import System.FilePath #if !MIN_VERSION_debian(3,89,0) parseDebianVersion' = parseDebianVersion #else import Debian.Version (parseDebianVersion') #endif main :: IO () main = do [cmd, path] <- getArgs dispatch cmd path type Command = String type Action = [LogLine] -> IO () -- Looks up command in the list of actions, calls corresponding action. dispatch :: Command -> FilePath -> IO () dispatch cmd path = action =<< parseFile path where action = fromMaybe err (lookup cmd actions) err _ = putStrLn $ "Error: " ++ cmd ++ " is not a valid command." -- Associative list of commands and actions. actions :: [(Command, Action)] actions = [ ("ips", topList 20 . countItems . map (BS.unpack . llIP)) , ("urls", topList 20 . countItems . filter notSvn . rights . map llPath) , ("debs", putDebs) , ("users", putArchUsers . archUsers) , ("arches", putArchCounts . archCounts) , ("bad", badReqs) , ("successful", putSuccessfulIPs . successfulIPs) ] topList :: Int -> [(String, Int)] -> IO () topList n = putList . take n . sortList -- Helper that turns a map into a top list, based on the second value. putList :: [(String, Int)] -> IO () putList = mapM_ putStrLn . tabulate [AlignRight, AlignLeft] . zipWith mkRow [1::Int ..] where mkRow i (s, n) = [show i, s, show n] sortList :: [(a, Int)] -> [(a, Int)] sortList = sortBy (flip compare `on` snd) -- Helper for tabulating output data Alignment = AlignLeft | AlignRight align :: (Alignment, Int, String) -> String align (a, n, s) = case a of AlignLeft -> s ++ padding AlignRight -> padding ++ s where padding = replicate m ' ' m = max 0 (n - length s) tabulate :: [Alignment] -> [[String]] -> [String] tabulate alignments rows = map formatRow rows where alignments' = alignments ++ repeat AlignRight formatRow = intercalate " " . map align . zip3 alignments' widths widths = map maximum . transpose . map (map length) $ rows groupFirsts :: (Ord a, Ord b) => [(a, b)] -> [(a, [b])] groupFirsts = map combine . groupBy ((==) `on` fst) . sort where combine = fst . head &&& map snd -- Calculate a list of items and their counts countItems :: (Eq a, Hashable a) => [a] -> [(a, Int)] countItems = M.toList . foldl' count M.empty where count acc x = M.insertWith (+) x 1 acc type Arch = String type Addr = String data Deb = Deb { debName :: String , debVersion :: DebianVersion , debArch :: Arch } deriving (Eq, Ord, Show, Generic) instance Hashable DebianVersion where hashWithSalt n = hashWithSalt n . show . prettyDebianVersion instance Hashable Deb parseDeb :: FilePath -> Maybe Deb parseDeb = toDeb . split '_' . dropExtension . unEscapeString . takeFileName where toDeb [n, v, a] = Just $ Deb n (parseDebianVersion' v) a toDeb _ = Nothing -- Count deb downloads extractDebs :: [LogLine] -> [Deb] extractDebs = mapMaybe parseDeb . filter isDeb . rights . map llPath . filter isDownload -- Count architectures archCounts :: [LogLine] -> [(Arch, Int)] archCounts = map (second length) . archUsers -- Unique users of architectures archUsers :: [LogLine] -> [(String, [Addr])] archUsers = groupFirsts . nub . arches . indices where arches :: [(Addr, FilePath)] -> [(Arch, Addr)] arches = map (swap . second arch) arch :: FilePath -> Arch arch = fromMaybe "?" . stripPrefix "binary-" . takeFileName . takeDirectory indices :: [LogLine] -> [(Addr, FilePath)] indices = filter (isIndex . snd) . rights . map ipAndPath . filter isDownload ipAndPath l = (,) (BS.unpack $ llIP l) <$> llPath l -- Log line filtering predicates isDownload :: LogLine -> Bool isDownload = (=='2') . BS.head . llStatus notSvn :: [Char] -> Bool notSvn = not . ("/svn/" `isPrefixOf`) isDeb :: FilePath -> Bool isDeb = (==".deb") . takeExtension isIndex :: FilePath -> Bool isIndex = (=="Packages") . takeBaseName -- List package downloads putDebs :: [LogLine] -> IO () putDebs entries = putStr . renderHtml . docTypeHtml $ do let (start, end) = (head &&& last) . map llTime $ entries timespan = show (utctDay start) ++ " – " ++ show (utctDay end) debs = extractDebs entries arches = sort . countItems . map debArch $ debs groups = groupFirsts . map swap . countItems . map debName $ debs pkgs = groupFirsts . map (debName . fst &&& id) . countItems $ debs H.head $ do H.title $ toMarkup $ "DebianAnalytics: " ++ timespan H.meta ! A.httpEquiv "Content-Type" ! A.content "text/html; charset=UTF-8" H.style ! A.type_ "text/css" $ mapM_ toMarkup [ "body {" , " font-family: \"Lucida Grande\", Verdana, Tahoma, sans-serif;" , " font-size: 90%;" , " background-color: "++hsv(210,15,60)++";" , " color: "++hsv(210,25,45)++";" , " margin: 0;" , "}" , ":link, :visited {" , " color: "++hsv(210,80,45)++";" , "}" , "table {" , " border-collapse: collapse;" , " margin: auto;" , "}" , "td, th {" , " border: 1pt solid "++hsv(210,25,45)++";" , " padding: 0.25em;" , " vertical-align: top;" , "}" , "th {" , " background-color: "++hsv(210,25,45)++";" , " color: "++hsv(60,50,100)++";" , " font-weight: normal;" , " font-size: 115%;" , "}" , "td {" , " background-color: "++hsv(210,8,100)++";" , "}" , ".title th {" , " font-size: 175%;" , " }" , ".title td {" , " text-align: center;" , " }" , ".arches td.count {" , " width: 6.5em;" , "}" , ".packages td.count {" , " width: 4em;" , "}" , ".count { text-align: right; }" , ".name { text-align: left; }" , ".filler { border: none; background-color: inherit; }" ] H.body $ do let total = sum $ map snd arches H.table ! A.class_ "title" $ do H.tr $ do H.th ! A.class_ "filler" $ "\xa0" H.tr $ do H.th ! A.class_ "name" $ toMarkup timespan H.tr $ do H.td ! A.class_ "name" $ fromString . printf "%.1f downloads/day" $ (fromIntegral total / realToFrac (end `diffUTCTime` start) * (60*60*24) :: Double) H.table ! A.class_ "arches" $ do H.tr $ do H.th ! A.class_ "filler" $ "\xa0" H.tr $ do H.th ! A.class_ "name" $ "Arch" H.th ! A.class_ "count" $ "Downloads" H.th ! A.class_ "count" $ "Proportion" forM_ arches $ \(a, n) -> do H.tr $ do H.td ! A.class_ "name" $ do toMarkup a H.td ! A.class_ "count" $ do toMarkup n H.td ! A.class_ "count" $ do fromString $ printf "%.0f%%" (fromIntegral n / fromIntegral total * 100 :: Double) H.tr $ do H.td ! A.class_ "name" $ do "Total" H.td ! A.class_ "count" $ do toMarkup total H.td ! A.class_ "count" $ do "100%" H.table ! A.class_ "groups" $ do H.tr $ do H.th ! A.class_ "filler" $ "\xa0" H.tr $ do H.th ! A.class_ "count" $ "Downloads" H.th ! A.class_ "name" $ "Packages" forM_ (reverse groups) $ \(n, ps) -> do H.tr $ do H.td ! A.class_ "count" $ do toMarkup n H.td ! A.class_ "name" $ do let pkgref p = H.a ! A.href (fromString $ '#':p) $ toMarkup p sequence_ . intersperse H.br . map pkgref $ ps H.table ! A.class_ "packages" $ do forM_ pkgs $ \(name, dcs) -> do let arches = sort . nub . map (debArch . fst) $ dcs versions = groupBy ((==) `on` debVersion . fst) dcs H.tr $ do H.th ! A.class_ "filler" ! A.id (fromString name) $ "\xa0" H.tr $ do H.th ! A.class_ "name" $ toMarkup name forM_ arches $ \a -> do H.th ! A.class_ "count" $ toMarkup a forM_ versions $ \dcs -> do let archdebs = map (first debArch) dcs H.tr $ do H.td ! A.class_ "name" $ do toMarkup . show . prettyDebianVersion . debVersion . fst . head $ dcs forM_ arches $ \a -> do H.td ! A.class_ "count" $ do toMarkup . fromMaybe 0 $ lookup a archdebs H.tr $ do H.th ! A.class_ "filler" $ "\xa0" -- List architecture users putArchUsers :: [(String, [Addr])] -> IO () putArchUsers arches = do let width = maximum . map (length . fst) $ arches forM_ arches $ \(a, ips) -> putStrLn $ printf "%*s %s" width a (intercalate "," ips) -- List architectures putArchCounts :: [(String, Int)] -> IO () putArchCounts arches = do let width = length . show . maximum . map snd $ arches forM_ arches $ \(a, n) -> putStrLn $ printf "%*d %s" width n a -- Show just the bad requests badReqs :: [LogLine] -> IO () badReqs = mapM_ putStrLn . lefts . map llRequest -- Show the IPs of the successful requests putSuccessfulIPs :: [BS.ByteString] -> IO () putSuccessfulIPs = mapM_ putStrLn . tabulate [AlignLeft] . map toRow . sort . map (first toIP) . countItems where toRow (a, c) = [show a, show c] toIP = read . BS.unpack :: BS.ByteString -> IP successfulIPs :: [LogLine] -> [BS.ByteString] successfulIPs = map llIP . filter (leSuccessful . mkEntry) leSuccessful :: LogEntry -> Bool leSuccessful = (<400) . leStatus instance Hashable IP where hashWithSalt n (IPv4 a) = hashWithSalt n $ toHostAddress a hashWithSalt n (IPv6 a) = hashWithSalt n $ toHostAddress6 a -- Split a string on a character split :: Eq a => a -> [a] -> [[a]] split _ [] = [] split c s = front : split c rest where (front, rest') = span (/= c) s rest = drop 1 rest'
neilmayhew/DebianAnalytics
Analyze.hs
gpl-3.0
11,750
0
34
3,711
3,859
2,031
1,828
-1
-1
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} module Class.DateTime where import Data.Time.Clock(UTCTime(..)) import Data.Time.Calendar(fromGregorian,toGregorian) class DateTimeClass a where toYMD :: a -> (Integer, (Word, Word)) toHMS :: a -> (Word , (Word, Word)) year :: a -> Integer mon,month,day,hour,min,minute,sec,second :: a -> Word year = fst . toYMD month = fst . snd . toYMD mon = month day = snd . snd . toYMD hour = fst . toHMS minute = fst . snd . toHMS min = minute second = snd . snd . toHMS sec = second instance DateTimeClass UTCTime where toYMD = toYMD' . toGregorian . utctDay where toYMD' (y,m,d) = (y, (fromIntegral m, fromIntegral d)) toHMS t = (h',(m',s')) where hsec' = fromIntegral 3600 msec' = fromIntegral 60 hmin' = fromIntegral 60 sec' = floor $ toRational $ utctDayTime t h' = fromIntegral $ floor $ (fromIntegral sec') / hsec' m' = fromIntegral $ (floor $ ((fromIntegral sec') / msec')) `mod` hmin' s' = fromIntegral $ (fromIntegral sec') `mod` (fromIntegral 60)
shinjiro-itagaki/shinjirecs
shinjirecs-api/src/Class/DateTime.hs
gpl-3.0
1,130
0
15
275
410
238
172
30
0
module Paste.Tests where import Data.Functor import qualified Data.Text as T import qualified Test.QuickCheck.Monadic as QCM import Test.Tasty import Test.Tasty.HUnit import qualified Test.Tasty.QuickCheck as QC import Test.Tasty.QuickCheck (testProperty) import Paste tests :: TestTree tests = testGroup "Paste.Tests" [ testProperty "dummy" prop_dummy , testProperty "create" prop_create , testCase "dummy unit" test_dummy ] prop_dummy :: String -> Bool prop_dummy a = reverse (reverse a) == a prop_create = QCM.monadicIO $ do email <- T.pack <$> QCM.pick QC.arbitrary password <- T.pack <$> QCM.pick QC.arbitrary user <- QCM.run $ createUser email password QCM.assert $ (checkUserPassword password user) == True test_dummy = True @?= False
nantes-fp/workshop-haskell-minipaste
test/Paste/Tests.hs
gpl-3.0
844
0
11
201
230
125
105
22
1
module Ampersand.Input ( module Ampersand.Input.ADL1.CtxError , module Ampersand.Input.Parsing ) where import Ampersand.Input.ADL1.CtxError (CtxError,Warning,Guarded(..),showErr,showWarning,showWarnings) import Ampersand.Input.Parsing (parseADL,parseMeta,parseSystemContext,parseRule,runParser)
AmpersandTarski/ampersand
src/Ampersand/Input.hs
gpl-3.0
313
0
6
34
77
52
25
5
0
{-# LANGUAGE CPP #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE RecordWildCards #-} module NS3473Column.System where -- import Data.Maybe (fromJust) import Control.Monad.Writer (Writer,runWriter,tell) import Text.Printf (printf) import qualified NS3473.Concrete as M import qualified NS3473.Rebars as R import qualified NS3473.Columns as C import qualified NS3473.Buckling as X import qualified NS3473Column.ColumnSystem as CS import qualified NS3473Column.CmdLine as CMD type WriterSB = Writer String Double createRebarCollection :: Int -- ^ Rebar diam -> Int -- ^ Rebar amount along h2 -> R.RebarCollection createRebarCollection rdiam rmnt = R.ColumnRebars rebar (fromIntegral rmnt) 25 where rebar = R.Rebar (fromIntegral rdiam) createColumn :: Int -- ^ Shortest column side [mm] -> Int -- ^ Longest column side [mm] -> Int -- ^ Column lenght -> String -- ^ Effective length factor -> M.Concrete -> R.RebarCollection -> C.Column createColumn h1 h2 cln lkf conc rebar = C.Column (fromIntegral h1) (fromIntegral h2) (fromIntegral cln) (read lkf :: Double) conc rebar -- | Moment based on creep, excentricity, etc calcMf :: C.Column -> Double -> Double -> WriterSB calcMf co nf mo = let e1 = X.e1 co nf mo ae = X.ae co nf creep = X.creep co nf mo in tell (printf "e1: %.2f mm\nae: %.2f mm\ncreep: %.2f mm\n" e1 ae creep) >> return (nf*(ae+e1+creep)/1000.0) runSystem' :: C.Column -> Double -- ^ Normal Force [kN] -> Double -- ^ Moment [kNm] -> IO () runSystem' co nf mo = let factn = X.nf co nf mf = runWriter (calcMf co nf mo) factm = X.factM co (fst mf) in putStrLn (snd mf) >> putStrLn (printf "mf: %.6f" factm) >> putStrLn (printf "nf: %.6f" factn) >> return () runSystem :: CMD.CmdLine -> IO () runSystem cs = let col = (CS.column cs) m = (CS.moment cs) nf = (CS.normalForce cs) in runSystem' col nf m calcAs :: CMD.CmdLine -> IO () calcAs cs = undefined --printf "As en side: %.2f mm2\n" result -- where wt' = (read (wt opts)) :: Double -- result = (wt' * (X.ac column) * (X.fcd column) / fsd)
baalbek/ns3473column
src/NS3473Column/System.hs
gpl-3.0
2,581
0
14
913
620
332
288
56
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.DFAReporting.Campaigns.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 an existing campaign. This method supports patch semantics. -- -- /See:/ <https://developers.google.com/doubleclick-advertisers/ DCM/DFA Reporting And Trafficking API Reference> for @dfareporting.campaigns.patch@. module Network.Google.Resource.DFAReporting.Campaigns.Patch ( -- * REST Resource CampaignsPatchResource -- * Creating a Request , campaignsPatch , CampaignsPatch -- * Request Lenses , cpProFileId , cpPayload , cpId ) where import Network.Google.DFAReporting.Types import Network.Google.Prelude -- | A resource alias for @dfareporting.campaigns.patch@ method which the -- 'CampaignsPatch' request conforms to. type CampaignsPatchResource = "dfareporting" :> "v2.7" :> "userprofiles" :> Capture "profileId" (Textual Int64) :> "campaigns" :> QueryParam "id" (Textual Int64) :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Campaign :> Patch '[JSON] Campaign -- | Updates an existing campaign. This method supports patch semantics. -- -- /See:/ 'campaignsPatch' smart constructor. data CampaignsPatch = CampaignsPatch' { _cpProFileId :: !(Textual Int64) , _cpPayload :: !Campaign , _cpId :: !(Textual Int64) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'CampaignsPatch' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cpProFileId' -- -- * 'cpPayload' -- -- * 'cpId' campaignsPatch :: Int64 -- ^ 'cpProFileId' -> Campaign -- ^ 'cpPayload' -> Int64 -- ^ 'cpId' -> CampaignsPatch campaignsPatch pCpProFileId_ pCpPayload_ pCpId_ = CampaignsPatch' { _cpProFileId = _Coerce # pCpProFileId_ , _cpPayload = pCpPayload_ , _cpId = _Coerce # pCpId_ } -- | User profile ID associated with this request. cpProFileId :: Lens' CampaignsPatch Int64 cpProFileId = lens _cpProFileId (\ s a -> s{_cpProFileId = a}) . _Coerce -- | Multipart request metadata. cpPayload :: Lens' CampaignsPatch Campaign cpPayload = lens _cpPayload (\ s a -> s{_cpPayload = a}) -- | Campaign ID. cpId :: Lens' CampaignsPatch Int64 cpId = lens _cpId (\ s a -> s{_cpId = a}) . _Coerce instance GoogleRequest CampaignsPatch where type Rs CampaignsPatch = Campaign type Scopes CampaignsPatch = '["https://www.googleapis.com/auth/dfatrafficking"] requestClient CampaignsPatch'{..} = go _cpProFileId (Just _cpId) (Just AltJSON) _cpPayload dFAReportingService where go = buildClient (Proxy :: Proxy CampaignsPatchResource) mempty
rueshyna/gogol
gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/Campaigns/Patch.hs
mpl-2.0
3,553
0
15
836
507
298
209
72
1
-- | -- Module : Numbers.Map -- Copyright : (c) 2012 Brendan Hay <brendan@soundcloud.com> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <brendan@soundcloud.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- module Numbers.Map ( -- * Exported Types Policy(..) -- * Opaque , Map , empty -- * Functions , toList , keys , lookup , update ) where import Prelude hiding (lookup) import Control.Monad import Control.Monad.IO.Class import Control.Concurrent import Control.Concurrent.Async hiding (wait) import Numbers.Types hiding (P) import qualified Numbers.Map.Internal as I type Handler k v = k -> v -> Time -> IO () data Policy k v = Reset Int (Handler k v) | Continue Int (Handler k v) | NoPolicy data Map k v = Map { _policy :: Policy k v , _imap :: I.Map k v } empty :: MonadIO m => Policy k v -> m (Map k v) empty p = Map p `liftM` I.empty toList :: MonadIO m => Map k v -> m [(k, v)] toList = I.toList . _imap keys :: MonadIO m => Map k v -> m [k] keys = I.keys . _imap lookup :: (MonadIO m, Ord k) => k -> Map k v -> m (Maybe v) lookup key = I.lookup key . _imap update :: (MonadIO m, Ord k) => k -> (Maybe v -> v) -> Map k v -> m () update key f Map{..} = do u <- I.update key f _imap case u of I.New -> scheduleSweep key _policy _imap I.Existing -> return () scheduleSweep :: (MonadIO m, Ord k) => k -> Policy k v -> I.Map k v -> m () scheduleSweep _ NoPolicy _ = return () scheduleSweep key (Reset d h) imap = sweep d h I.modify key imap scheduleSweep key (Continue d h) imap = sweep d h I.create key imap sweep :: (MonadIO m, Ord k) => Int -> Handler k v -> (I.Entry v -> Time) -> k -> I.Map k v -> m () sweep delay handle lastTime key imap = do liftIO $ async waitAndCheck >>= link where waitAndCheck = do _ <- liftIO . threadDelay $ delay * 1000000 now <- liftIO currentTime me <- I.deleteIf (\e -> lastTime e + fromIntegral delay <= now) key imap maybe waitAndCheck (\e -> handle key (I.value e) now) me
brendanhay/numbersd
src/Numbers/Map.hs
mpl-2.0
2,375
0
15
662
855
448
407
-1
-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.Compute.TargetSSLProxies.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) -- -- Returns the specified TargetSslProxy resource. Get a list of available -- target SSL proxies by making a list() request. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.targetSslProxies.get@. module Network.Google.Resource.Compute.TargetSSLProxies.Get ( -- * REST Resource TargetSSLProxiesGetResource -- * Creating a Request , targetSSLProxiesGet , TargetSSLProxiesGet -- * Request Lenses , tspgProject , tspgTargetSSLProxy ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.targetSslProxies.get@ method which the -- 'TargetSSLProxiesGet' request conforms to. type TargetSSLProxiesGetResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "global" :> "targetSslProxies" :> Capture "targetSslProxy" Text :> QueryParam "alt" AltJSON :> Get '[JSON] TargetSSLProxy -- | Returns the specified TargetSslProxy resource. Get a list of available -- target SSL proxies by making a list() request. -- -- /See:/ 'targetSSLProxiesGet' smart constructor. data TargetSSLProxiesGet = TargetSSLProxiesGet' { _tspgProject :: !Text , _tspgTargetSSLProxy :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'TargetSSLProxiesGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tspgProject' -- -- * 'tspgTargetSSLProxy' targetSSLProxiesGet :: Text -- ^ 'tspgProject' -> Text -- ^ 'tspgTargetSSLProxy' -> TargetSSLProxiesGet targetSSLProxiesGet pTspgProject_ pTspgTargetSSLProxy_ = TargetSSLProxiesGet' { _tspgProject = pTspgProject_ , _tspgTargetSSLProxy = pTspgTargetSSLProxy_ } -- | Project ID for this request. tspgProject :: Lens' TargetSSLProxiesGet Text tspgProject = lens _tspgProject (\ s a -> s{_tspgProject = a}) -- | Name of the TargetSslProxy resource to return. tspgTargetSSLProxy :: Lens' TargetSSLProxiesGet Text tspgTargetSSLProxy = lens _tspgTargetSSLProxy (\ s a -> s{_tspgTargetSSLProxy = a}) instance GoogleRequest TargetSSLProxiesGet where type Rs TargetSSLProxiesGet = TargetSSLProxy type Scopes TargetSSLProxiesGet = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/compute.readonly"] requestClient TargetSSLProxiesGet'{..} = go _tspgProject _tspgTargetSSLProxy (Just AltJSON) computeService where go = buildClient (Proxy :: Proxy TargetSSLProxiesGetResource) mempty
rueshyna/gogol
gogol-compute/gen/Network/Google/Resource/Compute/TargetSSLProxies/Get.hs
mpl-2.0
3,688
0
15
842
393
237
156
67
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.Vault.Matters.Holds.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) -- -- Gets the specified hold. -- -- /See:/ <https://developers.google.com/vault G Suite Vault API Reference> for @vault.matters.holds.get@. module Network.Google.Resource.Vault.Matters.Holds.Get ( -- * REST Resource MattersHoldsGetResource -- * Creating a Request , mattersHoldsGet , MattersHoldsGet -- * Request Lenses , mhgXgafv , mhgUploadProtocol , mhgHoldId , mhgAccessToken , mhgUploadType , mhgMatterId , mhgView , mhgCallback ) where import Network.Google.Prelude import Network.Google.Vault.Types -- | A resource alias for @vault.matters.holds.get@ method which the -- 'MattersHoldsGet' request conforms to. type MattersHoldsGetResource = "v1" :> "matters" :> Capture "matterId" Text :> "holds" :> Capture "holdId" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "view" MattersHoldsGetView :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] Hold -- | Gets the specified hold. -- -- /See:/ 'mattersHoldsGet' smart constructor. data MattersHoldsGet = MattersHoldsGet' { _mhgXgafv :: !(Maybe Xgafv) , _mhgUploadProtocol :: !(Maybe Text) , _mhgHoldId :: !Text , _mhgAccessToken :: !(Maybe Text) , _mhgUploadType :: !(Maybe Text) , _mhgMatterId :: !Text , _mhgView :: !(Maybe MattersHoldsGetView) , _mhgCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'MattersHoldsGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mhgXgafv' -- -- * 'mhgUploadProtocol' -- -- * 'mhgHoldId' -- -- * 'mhgAccessToken' -- -- * 'mhgUploadType' -- -- * 'mhgMatterId' -- -- * 'mhgView' -- -- * 'mhgCallback' mattersHoldsGet :: Text -- ^ 'mhgHoldId' -> Text -- ^ 'mhgMatterId' -> MattersHoldsGet mattersHoldsGet pMhgHoldId_ pMhgMatterId_ = MattersHoldsGet' { _mhgXgafv = Nothing , _mhgUploadProtocol = Nothing , _mhgHoldId = pMhgHoldId_ , _mhgAccessToken = Nothing , _mhgUploadType = Nothing , _mhgMatterId = pMhgMatterId_ , _mhgView = Nothing , _mhgCallback = Nothing } -- | V1 error format. mhgXgafv :: Lens' MattersHoldsGet (Maybe Xgafv) mhgXgafv = lens _mhgXgafv (\ s a -> s{_mhgXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). mhgUploadProtocol :: Lens' MattersHoldsGet (Maybe Text) mhgUploadProtocol = lens _mhgUploadProtocol (\ s a -> s{_mhgUploadProtocol = a}) -- | The hold ID. mhgHoldId :: Lens' MattersHoldsGet Text mhgHoldId = lens _mhgHoldId (\ s a -> s{_mhgHoldId = a}) -- | OAuth access token. mhgAccessToken :: Lens' MattersHoldsGet (Maybe Text) mhgAccessToken = lens _mhgAccessToken (\ s a -> s{_mhgAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). mhgUploadType :: Lens' MattersHoldsGet (Maybe Text) mhgUploadType = lens _mhgUploadType (\ s a -> s{_mhgUploadType = a}) -- | The matter ID. mhgMatterId :: Lens' MattersHoldsGet Text mhgMatterId = lens _mhgMatterId (\ s a -> s{_mhgMatterId = a}) -- | The amount of detail to return for a hold. mhgView :: Lens' MattersHoldsGet (Maybe MattersHoldsGetView) mhgView = lens _mhgView (\ s a -> s{_mhgView = a}) -- | JSONP mhgCallback :: Lens' MattersHoldsGet (Maybe Text) mhgCallback = lens _mhgCallback (\ s a -> s{_mhgCallback = a}) instance GoogleRequest MattersHoldsGet where type Rs MattersHoldsGet = Hold type Scopes MattersHoldsGet = '["https://www.googleapis.com/auth/ediscovery", "https://www.googleapis.com/auth/ediscovery.readonly"] requestClient MattersHoldsGet'{..} = go _mhgMatterId _mhgHoldId _mhgXgafv _mhgUploadProtocol _mhgAccessToken _mhgUploadType _mhgView _mhgCallback (Just AltJSON) vaultService where go = buildClient (Proxy :: Proxy MattersHoldsGetResource) mempty
brendanhay/gogol
gogol-vault/gen/Network/Google/Resource/Vault/Matters/Holds/Get.hs
mpl-2.0
5,150
0
19
1,290
861
500
361
124
1
module Handler.Notification where import Import hiding (delete) import Model.Notification import Model.Project import Model.User import View.Time import qualified Data.Foldable as F import Data.List (sort) import qualified Data.Text as T -- Merge two notification types together. This should only be used -- for rendering. data Notification = UNotification UserNotificationId UserNotification | PNotification ProjectNotificationId ProjectNotification deriving Eq instance Ord Notification where -- The arguments of 'compare' are intentionally swapped, so the -- newest notifications are listed first. compare (UNotification _ un1) (UNotification _ un2) = compare (userNotificationCreatedTs un2) (userNotificationCreatedTs un1) compare (UNotification _ un) (PNotification _ pn) = compare (projectNotificationCreatedTs pn) (userNotificationCreatedTs un) compare (PNotification _ pn) (UNotification _ un) = compare (userNotificationCreatedTs un) (projectNotificationCreatedTs pn) compare (PNotification _ pn1) (PNotification _ pn2) = compare (projectNotificationCreatedTs pn2) (projectNotificationCreatedTs pn1) buildNotificationsList :: [Entity UserNotification] -> [Entity ProjectNotification] -> [Notification] buildNotificationsList uns pns = sort $ ((\(Entity un_id un) -> UNotification un_id un) <$> uns) <> ((\(Entity pn_id pn) -> PNotification pn_id pn) <$> pns) getNotificationsR :: Handler Html getNotificationsR = do user_id <- requireAuthId notifs <- runDB $ do userReadNotificationsDB user_id user_notifs <- fetchUserNotificationsDB user_id project_notifs <- fetchProjectNotificationsDB user_id return $ buildNotificationsList user_notifs project_notifs defaultLayout $ do snowdriftTitle "Notifications" $(widgetFile "notifications") whenNotifId :: (PersistEntity r, DBConstraint m) => Text -> (Key r -> m ()) -> m () whenNotifId value action = F.forM_ (readMaybe $ T.unpack value :: Maybe Int) $ \notif_id -> action $ key $ toPersistValue notif_id whenUserNotifId :: DBConstraint m => Text -> (UserNotificationId -> m ()) -> m () whenUserNotifId = whenNotifId whenProjectNotifId :: DBConstraint m => Text -> (ProjectNotificationId -> m ()) -> m () whenProjectNotifId = whenNotifId proxyNotifications :: RedirectUrl App route => Text -> Text -> (UserId -> DB ()) -> (UserId -> DB ()) -> (UserNotificationId -> DB ()) -> (UserNotificationId -> DB ()) -> (ProjectNotificationId -> DB ()) -> (ProjectNotificationId -> DB ()) -> route -> Handler Html proxyNotifications value1 value2 action_all1 action_all2 action_user_notif1 action_user_notif2 action_project_notif1 action_project_notif2 route = do user_id <- requireAuthId req <- getRequest let params = reqGetParams req names = fst `map` params handleAction :: DB () -> DB () -> DB () handleAction action1 action2 = if | value1 `elem` names -> action1 | value2 `elem` names -> action2 | otherwise -> return () forM_ params $ \(name, value) -> case name of "all" -> runDB $ handleAction (action_all1 user_id) (action_all2 user_id) "user_notification" -> whenUserNotifId value $ \notif_id -> runDB $ handleAction (action_user_notif1 notif_id) (action_user_notif2 notif_id) "project_notification" -> whenProjectNotifId value $ \notif_id -> runDB $ handleAction (action_project_notif1 notif_id) (action_project_notif2 notif_id) _ -> return () redirect route getNotificationsProxyR :: Handler Html getNotificationsProxyR = proxyNotifications "archive" "delete" archiveNotificationsDB deleteNotificationsDB archiveUserNotificationDB deleteUserNotificationDB archiveProjectNotificationDB deleteProjectNotificationDB NotificationsR getArchivedNotificationsR :: Handler Html getArchivedNotificationsR = do user_id <- requireAuthId notifs <- runDB $ buildNotificationsList <$> fetchArchivedUserNotificationsDB user_id <*> fetchArchivedProjectNotificationsDB user_id defaultLayout $ do snowdriftTitle "Archived Notifications" $(widgetFile "archived_notifications") getArchivedNotificationsProxyR :: Handler Html getArchivedNotificationsProxyR = proxyNotifications "unarchive" "delete" unarchiveNotificationsDB deleteArchivedNotificationsDB unarchiveUserNotificationDB deleteUserNotificationDB unarchiveProjectNotificationDB deleteProjectNotificationDB ArchivedNotificationsR
akegalj/snowdrift
Handler/Notification.hs
agpl-3.0
5,120
0
17
1,382
1,192
594
598
-1
-1
{-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE DeriveGeneric #-} import Generics.MultiRec hiding ( (&), show ) import Generics.MultiRec.Base -- import Generics.MultiRec.Fold import Generics.MultiRec.HFix import Generics.MultiRec.HFunctor -- import qualified Generics.MultiRec.Fold as F import Generics.MultiRec.FoldAlg as FA import qualified GHC.Generics as G import qualified Generics.Deriving.Base as GD import Control.Monad.Identity import Control.Monad.State.Strict import Data.Maybe import Data.List.Ordered import Annotations.Bounds import Annotations.BoundsParser as BP import Annotations.Except import Annotations.ExploreHints import Annotations.MultiRec.Annotated import Annotations.MultiRec.Any import Annotations.MultiRec.ParserCombinators import Annotations.MultiRec.Yield import Annotations.MultiRec.Zipper import Annotations.MultiRec.ZipperFix import Annotations.MultiRec.ShowFam import Control.Applicative hiding (many) import Text.Parsec.Combinator hiding (chainl1,chainl) import qualified Text.Parsec.Prim as P import Text.Parsec.Char hiding (satisfy) import Text.Parsec.Error import Text.Parsec.String import Text.Parsec.Pos main = putStrLn "hello" -- --------------------------------------------------------------------- -- chapter 6 p 50 data Expr = EAdd Expr Expr | EMul Expr Expr | ETup Expr Expr | EIntLit Int | ETyped Expr Type deriving (Eq, Show) data Type = TyInt | TyTup Type Type deriving (Eq, Show) -- Sums of products representation type PFExpr = I Expr :*: I Expr :*: U -- EAdd :+: I Expr :*: I Expr :*: U -- EMul :+: I Expr :*: I Expr :*: U -- ETup :+: K Int :*: U -- EIntLit :+: I Expr :*: I Type :*:U -- ETyped type PFType = U -- TyInt :+: I Type :*: I Type :*:U -- TyTup -- The pattern family type PFTuples = PFExpr :>: Expr :+: PFType :>: Type -- --------------------------------------------------------------------- deriving instance G.Generic Expr deriving instance G.Generic Type e1 = EIntLit 1 {- G.from e1 (G.D1 Main.D1Expr ((G.C1 Main.C1_0Expr (G.S1 G.NoSelector (G.Rec0 Expr) G.:*: G.S1 G.NoSelector (G.Rec0 Expr)) G.:+: G.C1 Main.C1_1Expr (G.S1 G.NoSelector (G.Rec0 Expr) G.:*: G.S1 G.NoSelector (G.Rec0 Expr))) G.:+: (G.C1 Main.C1_2Expr (G.S1 G.NoSelector (G.Rec0 Expr) G.:*: G.S1 G.NoSelector (G.Rec0 Expr)) G.:+: (G.C1 Main.C1_3Expr (G.S1 G.NoSelector (G.Rec0 Int)) G.:+: G.C1 Main.C1_4Expr (G.S1 G.NoSelector (G.Rec0 Expr) G.:*: G.S1 G.NoSelector (G.Rec0 Type))))) x0)) -} e2 = EAdd (EIntLit 1) (EIntLit 2) {- G.from e2 (G.D1 Main.D1Expr ((G.C1 Main.C1_0Expr (G.S1 G.NoSelector (G.Rec0 Expr) G.:*: G.S1 G.NoSelector (G.Rec0 Expr)) G.:+: G.C1 Main.C1_1Expr (G.S1 G.NoSelector (G.Rec0 Expr) G.:*: G.S1 G.NoSelector (G.Rec0 Expr))) G.:+: (G.C1 Main.C1_2Expr (G.S1 G.NoSelector (G.Rec0 Expr) G.:*: G.S1 G.NoSelector (G.Rec0 Expr)) G.:+: (G.C1 Main.C1_3Expr (G.S1 G.NoSelector (G.Rec0 Int)) G.:+: G.C1 Main.C1_4Expr (G.S1 G.NoSelector (G.Rec0 Expr) G.:*: G.S1 G.NoSelector (G.Rec0 Type))))) x0)) -} showPF x = r where v = G.from x r = go v -- go (G.D1 x) = show x go = undefined -- Using aeson approach -- | Class of generic representation types ('Rep') that can be converted to a PF. class GToPF f where -- | This method (applied to 'defaultOptions') is used as the -- default generic implementation of 'toPF'. gToPF :: f -> Int class GToPF1 f where gToPF1 :: f a -> Int -- We need index type, PF, Fam and El instances, coming from GHC.Generics t1 = TyInt t1r = U {- So we must convert (G.D1 Main.D1Type (G.C1 Main.C1_0Type G.U1 G.:+: G.C1 Main.C1_1Type (G.S1 G.NoSelector (G.Rec0 Type) G.:*: G.S1 G.NoSelector (G.Rec0 Type))) x0)) To -} -- --------------------------------------------------------------------- -- Attempting a generic derivation of Fam, based on example for Functor {- class (PF phi a b) => GFam' phi where gfrom' :: phi ix -> ix -> PF phi I0 ix gto' :: phi ix -> PF phi I0 ix -> ix instance GFam' G.U1 where -- gfrom' _ G.U1 = U -- gto' G.U1 _ = G.U1 -} -- --------------------------------------------------------------------- -- Index type phi data Tuples :: * -> * where Expr :: Tuples Expr Type :: Tuples Type -- In this declaration phi stands for Tuples -- type family PF phi :: (* -> *) -> * -> * -- | Type family describing the pattern functor of a family. -- type family PF (phi :: * -> *) :: (* -> *) -> * -> * type instance PF Tuples = PFTuples ------------------------------------------------------------------------ instance Fam Tuples where from Expr ex = L . Tag $ case ex of EAdd x y -> L $ I (I0 x) :*: I (I0 y) :*: U EMul x y -> R . L $ I (I0 x) :*: I (I0 y) :*: U ETup x y -> R . R . L $ I (I0 x) :*: I (I0 y) :*: U EIntLit n -> R . R . R . L $ K n :*: U ETyped e t -> R . R . R . R $ I (I0 e) :*: I (I0 t) :*: U from Type ty = R . Tag $ case ty of TyInt -> L $ U TyTup x y -> R $ I (I0 x) :*: I (I0 y) :*: U to Expr (L (Tag ex)) = case ex of L (I (I0 x) :*: I (I0 y) :*: U) -> EAdd x y R (L (I (I0 x) :*: I (I0 y) :*: U)) -> EMul x y R (R (L (I (I0 x) :*: I (I0 y) :*: U))) -> ETup x y R (R (R (L (K n :*: U)))) -> EIntLit n R (R (R (R (I (I0 x) :*: I (I0 y) :*: U)))) -> ETyped x y to Type (R (Tag ty)) = case ty of L U -> TyInt R (I (I0 x) :*: I (I0 y) :*: U) -> TyTup x y instance El Tuples Expr where proof = Expr instance El Tuples Type where proof = Type -- --------------------------------------------------------------------- instance ShowFam Tuples where showFam Expr (EAdd e1 e2) = "(EAdd " ++ (showFam Expr e1) ++ " " ++ (showFam Expr e2) ++ ")" showFam Expr (EMul e1 e2) = "(EMul " ++ (showFam Expr e1) ++ " " ++ (showFam Expr e2) ++ ")" showFam Expr (ETup e1 e2) = "(ETup " ++ (showFam Expr e1) ++ " " ++ (showFam Expr e2) ++ ")" showFam Expr (EIntLit e1) = "(EIntlit " ++ (show e1) ++ ")" showFam Expr (ETyped e1 t1) = "(ETyped " ++ (showFam Expr e1) ++ " " ++ (showFam Type t1) ++ ")" showFam Type TyInt = "TyInt" showFam Type (TyTup t1 t2) = "(ETyTup " ++ (showFam Type t1) ++ " " ++ (showFam Type t2) ++ ")" -- --------------------------------------------------------------------- -- p 55 -- Note: K x is the annotation -- type AnnFix x φ = HFix (K x :*: PF φ) -- type AnnFix1 x φ = (PF φ) (AnnFix x φ) -- p57 type ErrorAlgPF f e a = forall ix.f (K0 a) ix -> Either e a errorCata :: (HFunctor φ f ) => ErrorAlgPF f e r -> φ ix -> HFix (K x :*: f ) ix -> Except [(e, x)] r errorCata alg pf (HIn (K k :*: f )) = case hmapA (\pg g -> K0 <$> errorCata alg pg g) pf f of Failed xs -> Failed xs OK expr' -> case alg expr' of Left x' -> Failed [(x', k)] Right v -> OK v type family ErrorAlg (f :: (* -> *) -> * -> *) -- pattern functor (e :: *) -- error type (a :: *) -- result type :: * -- resulting algebra type type instance ErrorAlg U e a = Either e a type instance ErrorAlg (K b :*: f ) e a = b -> ErrorAlg f e a type instance ErrorAlg (I xi :*: f ) e a = a -> ErrorAlg f e a type instance ErrorAlg (f :+: g) e a = (ErrorAlg f e a, ErrorAlg g e a) type instance ErrorAlg (f :>: xi) e a = ErrorAlg f e a -- --------------------------------------------------------------------- type ExprErrorAlg e a = (a -> a -> Either e a) -- EAdd :&: (a -> a -> Either e a) -- EMul :&: (a -> a -> Either e a) -- ETup :&: (Int -> Either e a) -- EIntLit :&: (a -> a -> Either e a) -- ETyped type TypeErrorAlg e a = (Either e a) -- TyInt :&: (a -> a -> Either e a) -- TyTup infixr 5 :&: -- Note: This is a type synonym, so normal tuple processing stuff will -- still work type (:&:) = (,) class MkErrorAlg f where mkErrorAlg :: ErrorAlg f e a -> ErrorAlgPF f e a instance MkErrorAlg U where mkErrorAlg x U = x instance MkErrorAlg f => MkErrorAlg (K a :*: f ) where mkErrorAlg alg (K x :*: f ) = mkErrorAlg (alg x) f instance MkErrorAlg f => MkErrorAlg (I xi :*: f ) where mkErrorAlg alg (I (K0 x) :*: f ) = mkErrorAlg (alg x) f instance MkErrorAlg f => MkErrorAlg (f :>: xi) where mkErrorAlg alg (Tag f ) = mkErrorAlg alg f instance (MkErrorAlg f, MkErrorAlg g) => MkErrorAlg (f :+: g) where mkErrorAlg (algf, _) (L x) = mkErrorAlg algf x mkErrorAlg (_, algg) (R y) = mkErrorAlg algg y -- -------------------------- inferType :: ExprErrorAlg String Type :&: TypeErrorAlg String Type inferType = ( equal "+" -- EAdd & equal "*" -- EMul & tup -- ETup & const (Right TyInt) -- EIntLit & equal "::") -- ETyped & (Right TyInt -- TyInt & tup) -- TyTup where equal op ty1 ty2 | ty1 == ty2 = Right ty1 | otherwise = Left ("lhs and rhs of "++ op ++ " must have equal types") tup ty1 ty2 = Right (TyTup ty1 ty2) {- When we have implemented readExpr... -- p 59 >let expr1 = readExpr "(1, (2, 3))" >errorCata (mkErrorAlg inferType) Expr expr1 OK (TyTup TyInt (TyTup TyInt TyInt)) -} ------------------------------------------------------------------------ -- section 6.6 constructing recursively annotated trees p 60 mkAnnFix :: x -> AnnFix1 x s ix -> AnnFix x s ix mkAnnFix x = HIn . (K x :*:) {- Parsing "2+3" First push EIntLit 2, then EIntLit 3 and finally EAdd (EIntLit 2) (EIntLit 3). -} {- class Monad m => MonadYield m where type ΦYield m :: * -> * type AnnType m:: * yield :: ΦYield m ix -> AnnType m -> ix -> m ix -- Value to be pushed on the parse stack -- data AnyF φ f where -- AnyF :: φ ix -> f ix -> AnyF φ f -- type AnyAnnFix x φ = AnyF φ (AnnFix x φ) newtype YieldT x φ m a = YieldT (StateT [AnyAnnFix x φ] m a) deriving (Functor,Monad) instance MonadTrans (YieldT x φ) where lift = YieldT . lift instance (Monad m, HFunctor φ (PF φ), EqS φ,Fam φ) => MonadYield (YieldT x φ m) where type ΦYield (YieldT x φ m) = φ type AnnType (YieldT x φ m) = x yield = doYield doYield :: (Monad m, HFunctor φ (PF φ), EqS φ,Fam φ) => φ ix -> x -> ix -> YieldT x φ m ix doYield p bounds x = YieldT $ do let pfx = from p x let n = length (children p pfx) stack <- get if length stack < n then error $ "structure mismatch: required "++ show n ++ " accumulated children but found only "++ show (length stack) else do let (cs, cs') = splitAt n stack let newChild = evalState (hmapM distribute p pfx) (reverse cs) put (AnyF p (HIn (K bounds :*: newChild)) : cs') return x distribute :: EqS φ => φ ix -> I0 ix -> State [AnyAnnFix x φ] (AnnFix x φ ix) distribute p1 _ = do xs <- get case xs of [] -> error "structure mismatch: too few children" AnyF p2 x : xs' -> case eqS p1 p2 of Nothing -> error "structure mismatch: incompatible child type" Just Refl -> do put xs'; return x -} -- ---------------------------------------------------- -- section 6.7 parsing p 64 -- Note: this Monad stack make use of Parsec 'try' dangerous as it may -- yield values before discarding the parse leg -- type YP s φ m = P s (YieldT Bounds φ m) instance EqS Tuples where eqS Expr Expr = Just Refl eqS Type Type = Just Refl eqS _ _ = Nothing data ExprToken = TIntLit Int | TPlus | TMinus | TStar | TSlash | TLParen | TRParen | TSpace String | TComma | TDoubleColon | TInt deriving (Show,Eq) instance Symbol ExprToken where unparse (TIntLit v) = show v unparse TPlus = "+" unparse TMinus = "-" unparse TStar = "*" unparse TSlash = "/" unparse TLParen = "(" unparse TRParen = ")" unparse (TSpace s) = s unparse TComma = "," unparse TDoubleColon = "::" unparse TInt = "Int" isIntLit (TIntLit _) = True isIntLit _ = False isSpace (TSpace _) = True isSpace _ = False -- --------------------------------------------------------------------- -- Lexical analysis tIntLit :: Parser ExprToken tIntLit = do { ds <- many1 digit; return (TIntLit (read ds)) } P.<?> "number" tPlus :: Parser ExprToken tPlus = do { char '+'; return TPlus } tMinus :: Parser ExprToken tMinus = do { char '-'; return TMinus } tStar :: Parser ExprToken tStar = do { char '*'; return TStar } tSlash :: Parser ExprToken tSlash = do { char '/'; return TSlash } tLParen :: Parser ExprToken tLParen = do { char '('; return TLParen } tRParen :: Parser ExprToken tRParen = do { char ')'; return TRParen } tSpace :: Parser ExprToken tSpace = do { ss <- many1 space; return (TSpace ss) } tComma :: Parser ExprToken tComma = do { char ','; return TComma } tDoubleColon :: Parser ExprToken tDoubleColon = do { string "::"; return TDoubleColon } tInt :: Parser ExprToken tInt = do { string "Int"; return TInt } pOneTok :: Parser ExprToken pOneTok = tIntLit P.<|> tPlus P.<|> tMinus P.<|> tStar P.<|> tSlash P.<|> tLParen P.<|> tRParen P.<|> tSpace P.<|> tComma P.<|> tDoubleColon P.<|> tInt pManyToks :: Parser [ExprToken] pManyToks = P.many pOneTok pM = undefined tFoo :: P (String,Bounds) Identity ExprToken tFoo = do -- string "::" return TDoubleColon {- pO :: P ExprToken Identity (ExprToken,Bounds) pO = do _ <- tFoo satisfy (\_ -> True) -} -- parseTokens :: String -> Either ParseError [ExprToken] -- parseTokens :: String -> BP.P ExprToken Identity [(ExprToken,Bounds)] -- parseTokens :: String -> BP.P ExprToken Identity a parseTokens str = case P.parse pManyToks "string" str of Left _ -> [] Right toks -> toks {- parseTokens str = do let pr = runParser pManyToks [] "src" str case pr of Left err -> undefined -- Right toks -> return $ collapse isSpace toks -- Right toks -> toks Right toks -> undefined -} pp = parseTokens "1 + 2" ppp :: [(ExprToken, Bounds)] ppp = collapse isSpace pp {- ppp = do v <- runParsecT [] pp show v -} -- --------------------------------------------------------------------- type ExprParser = YP ExprToken Tuples Identity pExpr :: ExprParser Expr pExpr = do left <- getPos ex <- pAdd option ex $ do pToken TDoubleColon ty <- pType mkBounded Expr left (ETyped ex ty) pAdd :: ExprParser Expr pAdd = chainl Expr pMul (EAdd <$ pToken TPlus) pMul :: ExprParser Expr pMul = chainl Expr pFactor (EAdd <$ pToken TStar) pFactor :: ExprParser Expr pFactor = pIntLit P.<|> pTupleVal pIntLit :: ExprParser Expr pIntLit = unit Expr $ (\(TIntLit n) -> EIntLit n) <$> satisfy isIntLit pTupleVal :: ExprParser Expr pTupleVal = pTuple Expr pExpr ETup pType :: ExprParser Type pType = pTyInt P.<|> pTyTuple pTyInt :: ExprParser Type pTyInt = unit Type $ TyInt <$ pToken TInt pTyTuple :: ExprParser Type pTyTuple = pTuple Type pType TyTup pTuple :: Tuples ix -> ExprParser ix -> (ix -> ix -> ix) -> ExprParser ix pTuple w pEl f = do left <- getPos pToken TLParen lhs <- pEl ty <- option lhs $ do pToken TComma rhs <- pEl mkBounded w left (f lhs rhs) pToken TRParen return ty -- ----------- -- pn -- pn = runYieldT Tuples -- type ExprParser = YP ExprToken Tuples Identity -- type YP s fam m = P s (YieldT Bounds fam m) -- so YP ExprToken Tuples Identity = P ExprToken (YieldT Bounds Tuples Identity) -- type P s -- = ParsecT [(s, Bounds)] Range -- so P ExprToken (YieldT Bounds Tuples Identity) -- = ParsecT [(ExprToken, Bounds)] Range (YieldT Bounds Tuples Identity) -- newtype ParsecT s u m a -- So s = [(ExprToken, Bounds)] -- u = Range -- m = (YieldT Bounds Tuples Identity) -- a = Expr -- runYieldT :: fam a -> YieldT x fam m a -> m (Maybe (AnnFix x fam a) -- Tuples a -> YieldT Bounds Tuples Identity a -> Identity (Maybe (AnnFix Bounds Tuples a) -- We need a = Expr -- Tuples Expr -> YieldT Bounds Tuples Identity Expr -> Identity (Maybe (AnnFix Bounds Tuples Expr) -- pExpr :: ExprParser Expr g :: Tuples Expr g = Expr ff = runYield g -- newtype YieldT x fam m a -- = Annotations.MultiRec.Yield.YieldT (StateT [AnyAnnFix x fam] m a) xx :: YieldT Bounds Tuples Identity Expr xx = undefined gg :: Maybe (AnnFix Bounds Tuples Expr) gg = runIdentity $ runYieldT g xx ggg :: Identity (Maybe (AnnFix Bounds Tuples Expr)) ggg = runYieldT g xx initState :: [(ExprToken, Bounds)] -> P.State [(ExprToken, Bounds)] Range -- initState = undefined initState toks = P.State { P.stateInput = toks , P.statePos = initialPos "src" , P.stateUser = (0,0) } hh :: -- P.State [(ExprToken, Bounds)] Range -- -> YieldT Bounds -- annotation Tuples -- fam Identity -- m (P.Consumed (YieldT Bounds Tuples Identity (P.Reply [(ExprToken, Bounds)] Range Expr))) hh = P.runParsecT pExpr (initState []) -- ii = runIdentity $ runYieldT g hh -- jj = (runParsecT (runYieldT g pExpr) initState) -- jj :: -- YieldT -- Bounds -- Tuples -- Identity -- (YieldT -- Bounds Tuples Identity (Reply [(ExprToken, Bounds)] Range Expr)) jj = do x <- P.runParsecT pExpr (initState []) let x' = case x of P.Consumed a -> a P.Empty a -> a --let y = case runYieldT g x' of -- yy -> yy -- Ok a b c -> (a,b,c) -- Error e -> error "parse error" -- y <- runIdentity $ runYieldT g x' -- y <- runIdentity $ runYieldT g x' -- y <- runIdentity $ runYieldT x' return x' -- readExpr :: String -> AnnFix Bounds Tuples Expr -- readExpr str = parse pExpr "src" -- readExpr :: String -> YieldT Bounds Tuples Identity Expr readExpr' :: String -> YieldT Bounds Tuples Identity Expr readExpr' str = do -- let toks = [] let toks = parseTokens str let toks' = collapse isSpace toks x <- P.runParsecT pExpr (initState toks') x' <- case x of P.Consumed a -> a P.Empty a -> a (p',q',r') <- case x' of P.Ok p q r -> return (p,q,r) P.Error e -> error $ "parse error:" ++ show e -- x''' <- x'' -- x''' <- runYieldT g x'' return p' readExpr :: String -> AnnFix Bounds Tuples Expr readExpr str = case runIdentity $ runYieldT g (readExpr' str) of Nothing -> error "parse failed" Just r -> r {- >let expr1 = readExpr "(1, (2, 3))" >errorCata (mkErrorAlg inferType) Expr expr1 OK (TyTup TyInt (TyTup TyInt TyInt)) -} expr1 :: AnnFix Bounds Tuples Expr expr1 = readExpr "(1, (2, 3))" ee = errorCata (mkErrorAlg inferType) Expr expr1 {- >let expr2 = readExpr "(1 :: (Int, Int), 2 + (3, 4))" >errorCata (mkErrorAlg inferType) Expr expr2 Failed [("lhs and rhs of :: must have equal types", Bounds {leftMargin = (1, 1), rightMargin = (16, 16)}) , ("lhs and rhs of + must have equal types" -} expr2 = readExpr "(1 :: (Int, Int), 2 + (3, 4))" ee2 = errorCata (mkErrorAlg inferType) Expr expr2 -- --------------------------------------------------------------------- -- Playing with Algebra's. data RV = RVE Expr | RVT Type deriving Show -- Just return the tree, without an annotation stripAnnot :: ExprErrorAlg String RV :&: TypeErrorAlg String RV stripAnnot = ( eadd -- EAdd & emul -- EMul & etup -- ETup & eint -- EIntLit & etyped) -- ETyped & ( etyint -- TyInt & etytup) -- TyTup where eadd (RVE r1) (RVE r2) = Right (RVE $ EAdd r1 r2) emul (RVE r1) (RVE r2) = Right (RVE $ EMul r1 r2) eint r1 = Right (RVE $ EIntLit r1) etup (RVE ty1) (RVE ty2) = Right (RVE $ ETup ty1 ty2) -- etyped r1 r2 = Right (ETyped r1 r2) etyped (RVE r1) (RVT r2) = Right (RVE $ ETyped r1 r2) etyint = Right (RVT TyInt) etytup (RVT r1) (RVT r2) = Right (RVT $ TyTup r1 r2) es = errorCata (mkErrorAlg stripAnnot) Expr expr1 -- --------------------------------------------------------------------- -- Zippers ch 6.8 p 67 -- type AnnZipper φ x = FixZipper φ (K x :*: PF φ) -- focusAnn :: AnnZipper φ x ix -> x -- focusAnn = on (\ (HIn (K x :*: _)) -> x) -- instance (Zipper Tuples f) where myenter :: Zipper phi f => phi ix -> r ix -> Loc phi f r ix myenter = undefined zenter :: Zipper φ f => φ ix -> HFix f ix -> FixZipper φ f ix zenter = enter z1 :: FixZipper Tuples (K Bounds :*: PFTuples) Expr z1 = zenter Expr expr1 f1 = focusAnn z1 -- explore :: Zipper φ (PF φ)⇒ φ ix→(x→ExploreHints)→(AnnFix x φ) ix→[AnnZipper φ x ix] explore p hints = explore? hints ◦ enter p selectByRange :: Zipper φ (PF φ) => φ ix -> Range -> AnnFix Bounds φ ix -> Maybe (AnnZipper φ Bounds ix) selectByRange p range@(left, _) = listToMaybe . reverse . explore p hints where hints bounds@(Bounds _ (ir, _)) = ExploreHints { matchHere = range `rangeInBounds` bounds , exploreDown = range `rangeInRange` outerRange bounds , exploreRight = left >= ir } selectByPos :: (Zipper φ (PF φ)) => φ ix -> Int -> AnnFix Bounds φ ix -> Maybe (AnnZipper φ Bounds ix) selectByPos p pos = findLeftmostDeepest p (posInRange pos . innerRange) repairBy :: (Ord dist, HFunctor φ (PF φ)) => φ ix -> (Range -> Range -> dist) -> AnnFix Bounds φ ix -> Range -> Bounds repairBy p cost tree range = head (sortOn (cost range . innerRange) (allAnnotations p tree)) repair :: HFunctor φ (PF φ) => φ ix -> AnnFix Bounds φ ix -> Range -> Bounds repair p = repairBy p distRange moveSelection :: Zipper φ (PF φ) => φ ix -> AnnFix Bounds φ ix -> Nav -> Range -> Maybe Bounds moveSelection p tree nav range = focusAnn <$> (selectByRange p range tree >>= nav)
alanz/annotations-play
src/ch6-generics.hs
unlicense
22,716
0
21
6,028
5,575
2,903
2,672
381
3
module SquareCube where mySqr = [x^2 | x <- [1..5]] myCube = [x^3 | x <- [1..5]] tuples = [(x, y) | x <- mySqr, y <- myCube, x < 50, y < 50] numTupes = length tuples -- alternative: allLessThan :: Integer -> [Integer] -> [Integer] allLessThan x xs = takeWhile (< x) xs allLessThan50 :: [Integer] -> [Integer] allLessThan50 xs = allLessThan 50 xs tuples' :: [(Integer, Integer)] tuples' = [(x, y) | x <- allLessThan50 mySqr, y <- allLessThan50 myCube]
thewoolleyman/haskellbook
09/06/maor/squarecube.hs
unlicense
461
0
8
93
225
125
100
11
1
module Braxton.A284434Spec (main, spec) where import Test.Hspec import Braxton.A284434 (a284434) main :: IO () main = hspec spec spec :: Spec spec = describe "A284434" $ it "correctly computes the first 5 elements" $ take 5 (map a284434 [1..]) `shouldBe` expectedValue where expectedValue = [1,2,1,6,2]
peterokagey/haskellOEIS
test/Braxton/A284434pec.hs
apache-2.0
317
0
10
59
115
65
50
10
1
-- Empty module to serve as the default current module. module Hugs where import Control.Concurrent import Data.List import IO import System.Environment main = do threadDelay 3000 putStrLine "Was it worth the wait?" main3 = do prog <- getProgName args <- getArgs putStrLn $ unwords (prog : args) main2 = do name <- getLine if name == "Paul" then putStrLn "Programmer" else if name == "Sophie" then putStrLn "Student" else putStrLn "Not sure" main1 = do list <- getList putStrLn ("list is " ++ show list) putStrLn ("sum is " ++ show (foldr (+) 0 list)) putStrLn ("product is " ++ show (foldr (*) 1 list)) showFactorials list getList = do line <- getLine if read line == 0 then return [] else do rest <- getList return ((read line :: Int) : rest) showFactorials [] = return () showFactorials (x:xs) = do putStrLn (show x ++ "! = " ++ show (foldr (*) 1 [2..x])) showFactorials xs x = 5 y = (6, "Hello") z = x * fst y square x = x * x signum x | x > 0 = 1 | x == 0 = 0 | x < 0 = -1 fib 1 = 1 fib 2 = 1 fib n = fib (n - 2) + fib (n - 1) my_mult 0 _ = 0 my_mult _ 0 = 0 my_mult a b = a + my_mult a (b - 1) my_map :: (a -> b) -> [a] -> [b] my_map _ [] = [] my_map f (x:xs) = f x : my_map f xs data Triple a b c = Triple a b c tripleFst (Triple x _ _) = x tripleSnd (Triple _ x _) = x tripleThd (Triple _ _ x) = x data List a = Nil | Cons a (List a) listHead (Cons x xs) = x listTail (Cons x xs) = xs listFoldr f n Nil = n listFoldr f n (Cons x xs) = listFoldr f (f n x) xs data BinaryTree a = Leaf a | Branch (BinaryTree a) a (BinaryTree a) elements (Leaf v) = [v] elements (Branch lhs v rhs) = (elements lhs) ++ (v : elements rhs)
pdbartlett/misc-stuff
unfuddle/PdbMisc/Haskell/Tutorial/Hugs.hs
apache-2.0
1,861
0
14
600
859
433
426
66
3
module Utils where import Data.Maybe import Data.Char import Data.List cross f g (a, b) = (f a, g b) showlist sh sep [] = "" showlist sh sep (t1:ts) = sh t1 ++ concat [sep ++ sh t | t <- ts] separate sep [] = [] separate sep (t1:ts) = t1 : concat [[sep, t] | t <- ts] breaks2' p [] = [] breaks2' p (x:xs) | p x = (x, ys) : ws where (ys, zs) = break p xs ws = breaks2' p zs breaks2 p xs = (ys, breaks2' p zs) where (ys, zs) = break p xs
Kelketek/proto-import
Utils.hs
bsd-2-clause
466
0
9
133
284
148
136
17
1
{-# LANGUAGE OverloadedStrings, RankNTypes #-} module Model.Tarball where import Import import Control.Monad import Data.Conduit import Data.Conduit.Binary import qualified Data.Conduit.List as CL import Data.Conduit.Zlib import Database.Persist.GenericSql.Raw import qualified Data.Text as S import Data.Text.Encoding (encodeUtf8) import Data.Time import Data.Time.Lens import Text.Printf createFile :: forall master sub. (YesodPersist master, YesodPersistBackend master ~ SqlPersist) => GHandler sub master () createFile = do (qC, vC) <- runDB $ do a <- count [QuoteApproved ==. True] b <- selectFirst [] [ Desc TarballTimestamp] return (a,maybe 0 (tarballNumquotes.entityVal) b) when (qC>vC+32) $ do time <- liftIO $ getCurrentTime let y = getL year time m = getL month time d = getL day time s = printf "%04d%02d%02d" y m d f = "fortune-mod-gentoo-ru-"++s++".gz" t = Tarball { tarballFilename = S.pack f , tarballNumquotes = qC , tarballTimestamp = time } _ <- runDB $ insert t writeFortunes f writeFortunes "fortune-mod-gentoo-ru-99999999.ebuild" writeFortunes :: forall master sub. (YesodPersist master, YesodPersistBackend master ~ SqlPersist) => [Char] -> GHandler sub master () writeFortunes f = do runDB $ do runResourceT $ selectSource [QuoteApproved ==. True] [] $= CL.map toText $$ CL.map encodeUtf8 =$ gzip =$ sinkFile ("static/files/"++f) toText :: Entity Quote -> Text toText (Entity _ quote) = S.concat [ (unTextarea $ quoteText quote) , "\n" , " -- " , (maybe "" id $ quoteAuthor quote) , " " , (S.pack $ show $ quoteSource quote) , "\n%\n" ]
qnikst/ygruq
Model/Tarball.hs
bsd-2-clause
2,075
0
17
744
569
300
269
57
1
{-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-| Tests for the lock data structure -} {- Copyright (C) 2014 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Test.Ganeti.Locking.Locks (testLocking_Locks) where import Control.Applicative ((<$>), (<*>), liftA2) import Control.Monad (liftM) import System.Posix.Types (CPid) import Test.QuickCheck import Text.JSON import Test.Ganeti.TestHelper import Test.Ganeti.TestCommon import Test.Ganeti.Types () import Ganeti.Locking.Locks import Ganeti.Locking.Types instance Arbitrary GanetiLocks where arbitrary = oneof [ return BGL , return ClusterLockSet , return InstanceLockSet , Instance <$> genFQDN , return NodeGroupLockSet , NodeGroup <$> genUUID , return NAL , return NodeAllocLockSet , return NodeResLockSet , NodeRes <$> genUUID , return NodeLockSet , Node <$> genUUID , return NetworkLockSet , Network <$> genUUID ] -- | Verify that readJSON . showJSON = Ok prop_ReadShow :: Property prop_ReadShow = forAll (arbitrary :: Gen GanetiLocks) $ \a -> readJSON (showJSON a) ==? Ok a -- | Verify the implied locks are earlier in the lock order. prop_ImpliedOrder :: Property prop_ImpliedOrder = forAll ((arbitrary :: Gen GanetiLocks) `suchThat` (not . null . lockImplications)) $ \b -> printTestCase "Implied locks must be earlier in the lock order" . flip all (lockImplications b) $ \a -> a < b -- | Verify the intervall property of the locks. prop_ImpliedIntervall :: Property prop_ImpliedIntervall = forAll ((arbitrary :: Gen GanetiLocks) `suchThat` (not . null . lockImplications)) $ \b -> forAll (elements $ lockImplications b) $ \a -> forAll (arbitrary `suchThat` liftA2 (&&) (a <) (<= b)) $ \x -> printTestCase ("Locks between a group and a member of the group" ++ " must also belong to the group") $ a `elem` lockImplications x instance Arbitrary LockLevel where arbitrary = elements [LevelCluster ..] -- | Verify that readJSON . showJSON = Ok for lock levels prop_ReadShowLevel :: Property prop_ReadShowLevel = forAll (arbitrary :: Gen LockLevel) $ \a -> readJSON (showJSON a) ==? Ok a instance Arbitrary ClientType where arbitrary = oneof [ ClientOther <$> arbitrary , ClientJob <$> arbitrary ] -- | Verify that readJSON . showJSON = Ok for ClientType prop_ReadShow_ClientType :: Property prop_ReadShow_ClientType = forAll (arbitrary :: Gen ClientType) $ \a -> readJSON (showJSON a) ==? Ok a instance Arbitrary CPid where arbitrary = liftM fromIntegral (arbitrary :: Gen Integer) instance Arbitrary ClientId where arbitrary = ClientId <$> arbitrary <*> arbitrary <*> arbitrary -- | Verify that readJSON . showJSON = Ok for ClientId prop_ReadShow_ClientId :: Property prop_ReadShow_ClientId = forAll (arbitrary :: Gen ClientId) $ \a -> readJSON (showJSON a) ==? Ok a testSuite "Locking/Locks" [ 'prop_ReadShow , 'prop_ImpliedOrder , 'prop_ImpliedIntervall , 'prop_ReadShowLevel , 'prop_ReadShow_ClientType , 'prop_ReadShow_ClientId ]
ganeti-github-testing/ganeti-test-1
test/hs/Test/Ganeti/Locking/Locks.hs
bsd-2-clause
4,567
0
15
1,030
750
419
331
72
1
{-# LANGUAGE CPP #-} ------------------------------------------------------------------------------- -- -- | Dynamic flags -- -- Most flags are dynamic flags, which means they can change from compilation -- to compilation using @OPTIONS_GHC@ pragmas, and in a multi-session GHC each -- session can be using different dynamic flags. Dynamic flags can also be set -- at the prompt in GHCi. -- -- (c) The University of Glasgow 2005 -- ------------------------------------------------------------------------------- {-# OPTIONS_GHC -fno-cse #-} -- -fno-cse is needed for GLOBAL_VAR's to behave properly module DynFlags ( -- * Dynamic flags and associated configuration types DumpFlag(..), GeneralFlag(..), WarningFlag(..), ExtensionFlag(..), Language(..), PlatformConstants(..), FatalMessager, LogAction, FlushOut(..), FlushErr(..), ProfAuto(..), glasgowExtsFlags, dopt, dopt_set, dopt_unset, gopt, gopt_set, gopt_unset, wopt, wopt_set, wopt_unset, xopt, xopt_set, xopt_unset, lang_set, useUnicodeSyntax, whenGeneratingDynamicToo, ifGeneratingDynamicToo, whenCannotGenerateDynamicToo, dynamicTooMkDynamicDynFlags, DynFlags(..), FlagSpec(..), HasDynFlags(..), ContainsDynFlags(..), RtsOptsEnabled(..), HscTarget(..), isObjectTarget, defaultObjectTarget, targetRetainsAllBindings, GhcMode(..), isOneShot, GhcLink(..), isNoLink, PackageFlag(..), PackageArg(..), ModRenaming(..), PkgConfRef(..), Option(..), showOpt, DynLibLoader(..), fFlags, fWarningFlags, fLangFlags, xFlags, dynFlagDependencies, tablesNextToCode, mkTablesNextToCode, SigOf(..), getSigOf, Way(..), mkBuildTag, wayRTSOnly, addWay', updateWays, wayGeneralFlags, wayUnsetGeneralFlags, -- ** Safe Haskell SafeHaskellMode(..), safeHaskellOn, safeImportsOn, safeLanguageOn, safeInferOn, packageTrustOn, safeDirectImpsReq, safeImplicitImpsReq, unsafeFlags, unsafeFlagsForInfer, -- ** System tool settings and locations Settings(..), targetPlatform, programName, projectVersion, ghcUsagePath, ghciUsagePath, topDir, tmpDir, rawSettings, versionedAppDir, extraGccViaCFlags, systemPackageConfig, pgm_L, pgm_P, pgm_F, pgm_c, pgm_s, pgm_a, pgm_l, pgm_dll, pgm_T, pgm_sysman, pgm_windres, pgm_libtool, pgm_lo, pgm_lc, opt_L, opt_P, opt_F, opt_c, opt_a, opt_l, opt_windres, opt_lo, opt_lc, -- ** Manipulating DynFlags defaultDynFlags, -- Settings -> DynFlags defaultWays, interpWays, initDynFlags, -- DynFlags -> IO DynFlags defaultFatalMessager, defaultLogAction, defaultLogActionHPrintDoc, defaultLogActionHPutStrDoc, defaultFlushOut, defaultFlushErr, getOpts, -- DynFlags -> (DynFlags -> [a]) -> [a] getVerbFlags, updOptLevel, setTmpDir, setPackageKey, interpretPackageEnv, -- ** Parsing DynFlags parseDynamicFlagsCmdLine, parseDynamicFilePragma, parseDynamicFlagsFull, -- ** Available DynFlags allFlags, flagsAll, flagsDynamic, flagsPackage, flagsForCompletion, supportedLanguagesAndExtensions, languageExtensions, -- ** DynFlags C compiler options picCCOpts, picPOpts, -- * Configuration of the stg-to-stg passes StgToDo(..), getStgToDo, -- * Compiler configuration suitable for display to the user compilerInfo, #ifdef GHCI rtsIsProfiled, #endif dynamicGhc, #include "../includes/dist-derivedconstants/header/GHCConstantsHaskellExports.hs" bLOCK_SIZE_W, wORD_SIZE_IN_BITS, tAG_MASK, mAX_PTR_TAG, tARGET_MIN_INT, tARGET_MAX_INT, tARGET_MAX_WORD, unsafeGlobalDynFlags, setUnsafeGlobalDynFlags, -- * SSE and AVX isSseEnabled, isSse2Enabled, isSse4_2Enabled, isAvxEnabled, isAvx2Enabled, isAvx512cdEnabled, isAvx512erEnabled, isAvx512fEnabled, isAvx512pfEnabled, -- * Linker/compiler information LinkerInfo(..), CompilerInfo(..), ) where #include "HsVersions.h" import Platform import PlatformConstants import Module import PackageConfig import {-# SOURCE #-} Hooks import {-# SOURCE #-} PrelNames ( mAIN ) import {-# SOURCE #-} Packages (PackageState) import DriverPhases ( Phase(..), phaseInputExt ) import Config import CmdLineParser import Constants import Panic import Util import Maybes import MonadUtils import qualified Pretty import SrcLoc import FastString import Outputable #ifdef GHCI import Foreign.C ( CInt(..) ) import System.IO.Unsafe ( unsafeDupablePerformIO ) #endif import {-# SOURCE #-} ErrUtils ( Severity(..), MsgDoc, mkLocMessage ) import System.IO.Unsafe ( unsafePerformIO ) import Data.IORef import Control.Arrow ((&&&)) import Control.Monad import Control.Exception (throwIO) import Data.Bits import Data.Char import Data.Int import Data.List import Data.Map (Map) import qualified Data.Map as Map import Data.Set (Set) import qualified Data.Set as Set import Data.Word import System.FilePath import System.Directory import System.Environment (getEnv) import System.IO import System.IO.Error import Text.ParserCombinators.ReadP hiding (char) import Text.ParserCombinators.ReadP as R import Data.IntSet (IntSet) import qualified Data.IntSet as IntSet import GHC.Foreign (withCString, peekCString) -- Note [Updating flag description in the User's Guide] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- If you modify anything in this file please make sure that your changes are -- described in the User's Guide. Usually at least two sections need to be -- updated: -- -- * Flag Reference section in docs/users-guide/flags.xml lists all available -- flags together with a short description -- -- * Flag description in docs/users_guide/using.xml provides a detailed -- explanation of flags' usage. -- Note [Supporting CLI completion] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- The command line interface completion (in for example bash) is an easy way -- for the developer to learn what flags are available from GHC. -- GHC helps by separating which flags are available when compiling with GHC, -- and which flags are available when using GHCi. -- A flag is assumed to either work in both these modes, or only in one of them. -- When adding or changing a flag, please consider for which mode the flag will -- have effect, and annotate it accordingly. For Flags use defFlag, defGhcFlag, -- defGhciFlag, and for FlagSpec use flagSpec or flagGhciSpec. -- ----------------------------------------------------------------------------- -- DynFlags data DumpFlag -- See Note [Updating flag description in the User's Guide] -- debugging flags = Opt_D_dump_cmm | Opt_D_dump_cmm_raw -- All of the cmm subflags (there are a lot!) Automatically -- enabled if you run -ddump-cmm | Opt_D_dump_cmm_cfg | Opt_D_dump_cmm_cbe | Opt_D_dump_cmm_proc | Opt_D_dump_cmm_sink | Opt_D_dump_cmm_sp | Opt_D_dump_cmm_procmap | Opt_D_dump_cmm_split | Opt_D_dump_cmm_info | Opt_D_dump_cmm_cps -- end cmm subflags | Opt_D_dump_asm | Opt_D_dump_asm_native | Opt_D_dump_asm_liveness | Opt_D_dump_asm_regalloc | Opt_D_dump_asm_regalloc_stages | Opt_D_dump_asm_conflicts | Opt_D_dump_asm_stats | Opt_D_dump_asm_expanded | Opt_D_dump_llvm | Opt_D_dump_core_stats | Opt_D_dump_deriv | Opt_D_dump_ds | Opt_D_dump_foreign | Opt_D_dump_inlinings | Opt_D_dump_rule_firings | Opt_D_dump_rule_rewrites | Opt_D_dump_simpl_trace | Opt_D_dump_occur_anal | Opt_D_dump_parsed | Opt_D_dump_rn | Opt_D_dump_simpl | Opt_D_dump_simpl_iterations | Opt_D_dump_spec | Opt_D_dump_prep | Opt_D_dump_stg | Opt_D_dump_call_arity | Opt_D_dump_stranal | Opt_D_dump_strsigs | Opt_D_dump_tc | Opt_D_dump_types | Opt_D_dump_rules | Opt_D_dump_cse | Opt_D_dump_worker_wrapper | Opt_D_dump_rn_trace | Opt_D_dump_rn_stats | Opt_D_dump_opt_cmm | Opt_D_dump_simpl_stats | Opt_D_dump_cs_trace -- Constraint solver in type checker | Opt_D_dump_tc_trace | Opt_D_dump_if_trace | Opt_D_dump_vt_trace | Opt_D_dump_splices | Opt_D_th_dec_file | Opt_D_dump_BCOs | Opt_D_dump_vect | Opt_D_dump_ticked | Opt_D_dump_rtti | Opt_D_source_stats | Opt_D_verbose_stg2stg | Opt_D_dump_hi | Opt_D_dump_hi_diffs | Opt_D_dump_mod_cycles | Opt_D_dump_mod_map | Opt_D_dump_view_pattern_commoning | Opt_D_verbose_core2core | Opt_D_dump_debug deriving (Eq, Show, Enum) -- | Enumerates the simple on-or-off dynamic flags data GeneralFlag -- See Note [Updating flag description in the User's Guide] = Opt_DumpToFile -- ^ Append dump output to files instead of stdout. | Opt_D_faststring_stats | Opt_D_dump_minimal_imports | Opt_DoCoreLinting | Opt_DoStgLinting | Opt_DoCmmLinting | Opt_DoAsmLinting | Opt_DoAnnotationLinting | Opt_NoLlvmMangler -- hidden flag | Opt_WarnIsError -- -Werror; makes warnings fatal | Opt_PrintExplicitForalls | Opt_PrintExplicitKinds -- optimisation opts | Opt_CallArity | Opt_Strictness | Opt_LateDmdAnal | Opt_KillAbsence | Opt_KillOneShot | Opt_FullLaziness | Opt_FloatIn | Opt_Specialise | Opt_SpecialiseAggressively | Opt_StaticArgumentTransformation | Opt_CSE | Opt_LiberateCase | Opt_SpecConstr | Opt_DoLambdaEtaExpansion | Opt_IgnoreAsserts | Opt_DoEtaReduction | Opt_CaseMerge | Opt_UnboxStrictFields | Opt_UnboxSmallStrictFields | Opt_DictsCheap | Opt_EnableRewriteRules -- Apply rewrite rules during simplification | Opt_Vectorise | Opt_VectorisationAvoidance | Opt_RegsGraph -- do graph coloring register allocation | Opt_RegsIterative -- do iterative coalescing graph coloring register allocation | Opt_PedanticBottoms -- Be picky about how we treat bottom | Opt_LlvmTBAA -- Use LLVM TBAA infastructure for improving AA (hidden flag) | Opt_LlvmPassVectorsInRegisters -- Pass SIMD vectors in registers (requires a patched LLVM) (hidden flag) | Opt_IrrefutableTuples | Opt_CmmSink | Opt_CmmElimCommonBlocks | Opt_OmitYields | Opt_SimpleListLiterals | Opt_FunToThunk -- allow WwLib.mkWorkerArgs to remove all value lambdas | Opt_DictsStrict -- be strict in argument dictionaries | Opt_DmdTxDictSel -- use a special demand transformer for dictionary selectors | Opt_Loopification -- See Note [Self-recursive tail calls] -- Interface files | Opt_IgnoreInterfacePragmas | Opt_OmitInterfacePragmas | Opt_ExposeAllUnfoldings | Opt_WriteInterface -- forces .hi files to be written even with -fno-code -- profiling opts | Opt_AutoSccsOnIndividualCafs | Opt_ProfCountEntries -- misc opts | Opt_Pp | Opt_ForceRecomp | Opt_ExcessPrecision | Opt_EagerBlackHoling | Opt_NoHsMain | Opt_SplitObjs | Opt_StgStats | Opt_HideAllPackages | Opt_PrintBindResult | Opt_Haddock | Opt_HaddockOptions | Opt_BreakOnException | Opt_BreakOnError | Opt_PrintEvldWithShow | Opt_PrintBindContents | Opt_GenManifest | Opt_EmbedManifest | Opt_SharedImplib | Opt_BuildingCabalPackage | Opt_IgnoreDotGhci | Opt_GhciSandbox | Opt_GhciHistory | Opt_HelpfulErrors | Opt_DeferTypeErrors | Opt_DeferTypedHoles | Opt_Parallel | Opt_PIC | Opt_SccProfilingOn | Opt_Ticky | Opt_Ticky_Allocd | Opt_Ticky_LNE | Opt_Ticky_Dyn_Thunk | Opt_Static | Opt_RPath | Opt_RelativeDynlibPaths | Opt_Hpc | Opt_FlatCache -- PreInlining is on by default. The option is there just to see how -- bad things get if you turn it off! | Opt_SimplPreInlining -- output style opts | Opt_ErrorSpans -- Include full span info in error messages, -- instead of just the start position. | Opt_PprCaseAsLet | Opt_PprShowTicks -- Suppress all coercions, them replacing with '...' | Opt_SuppressCoercions | Opt_SuppressVarKinds -- Suppress module id prefixes on variables. | Opt_SuppressModulePrefixes -- Suppress type applications. | Opt_SuppressTypeApplications -- Suppress info such as arity and unfoldings on identifiers. | Opt_SuppressIdInfo -- Suppress separate type signatures in core, but leave types on -- lambda bound vars | Opt_SuppressTypeSignatures -- Suppress unique ids on variables. -- Except for uniques, as some simplifier phases introduce new -- variables that have otherwise identical names. | Opt_SuppressUniques -- temporary flags | Opt_AutoLinkPackages | Opt_ImplicitImportQualified -- keeping stuff | Opt_KeepHiDiffs | Opt_KeepHcFiles | Opt_KeepSFiles | Opt_KeepTmpFiles | Opt_KeepRawTokenStream | Opt_KeepLlvmFiles | Opt_BuildDynamicToo -- safe haskell flags | Opt_DistrustAllPackages | Opt_PackageTrust -- debugging flags | Opt_Debug deriving (Eq, Show, Enum) data WarningFlag = -- See Note [Updating flag description in the User's Guide] Opt_WarnDuplicateExports | Opt_WarnDuplicateConstraints | Opt_WarnRedundantConstraints | Opt_WarnHiShadows | Opt_WarnImplicitPrelude | Opt_WarnIncompletePatterns | Opt_WarnIncompleteUniPatterns | Opt_WarnIncompletePatternsRecUpd | Opt_WarnOverflowedLiterals | Opt_WarnEmptyEnumerations | Opt_WarnMissingFields | Opt_WarnMissingImportList | Opt_WarnMissingMethods | Opt_WarnMissingSigs | Opt_WarnMissingLocalSigs | Opt_WarnNameShadowing | Opt_WarnOverlappingPatterns | Opt_WarnTypeDefaults | Opt_WarnMonomorphism | Opt_WarnUnusedTopBinds | Opt_WarnUnusedLocalBinds | Opt_WarnUnusedPatternBinds | Opt_WarnUnusedImports | Opt_WarnUnusedMatches | Opt_WarnContextQuantification | Opt_WarnWarningsDeprecations | Opt_WarnDeprecatedFlags | Opt_WarnAMP | Opt_WarnDodgyExports | Opt_WarnDodgyImports | Opt_WarnOrphans | Opt_WarnAutoOrphans | Opt_WarnIdentities | Opt_WarnTabs | Opt_WarnUnrecognisedPragmas | Opt_WarnDodgyForeignImports | Opt_WarnUnusedDoBind | Opt_WarnWrongDoBind | Opt_WarnAlternativeLayoutRuleTransitional | Opt_WarnUnsafe | Opt_WarnSafe | Opt_WarnTrustworthySafe | Opt_WarnPointlessPragmas | Opt_WarnUnsupportedCallingConventions | Opt_WarnUnsupportedLlvmVersion | Opt_WarnInlineRuleShadowing | Opt_WarnTypedHoles | Opt_WarnPartialTypeSignatures | Opt_WarnMissingExportedSigs | Opt_WarnUntickedPromotedConstructors | Opt_WarnDerivingTypeable deriving (Eq, Show, Enum) data Language = Haskell98 | Haskell2010 deriving Enum -- | The various Safe Haskell modes data SafeHaskellMode = Sf_None | Sf_Unsafe | Sf_Trustworthy | Sf_Safe deriving (Eq) instance Show SafeHaskellMode where show Sf_None = "None" show Sf_Unsafe = "Unsafe" show Sf_Trustworthy = "Trustworthy" show Sf_Safe = "Safe" instance Outputable SafeHaskellMode where ppr = text . show data ExtensionFlag -- See Note [Updating flag description in the User's Guide] = Opt_Cpp | Opt_OverlappingInstances | Opt_UndecidableInstances | Opt_IncoherentInstances | Opt_MonomorphismRestriction | Opt_MonoPatBinds | Opt_MonoLocalBinds | Opt_RelaxedPolyRec -- Deprecated | Opt_ExtendedDefaultRules -- Use GHC's extended rules for defaulting | Opt_ForeignFunctionInterface | Opt_UnliftedFFITypes | Opt_InterruptibleFFI | Opt_CApiFFI | Opt_GHCForeignImportPrim | Opt_JavaScriptFFI | Opt_ParallelArrays -- Syntactic support for parallel arrays | Opt_Arrows -- Arrow-notation syntax | Opt_TemplateHaskell | Opt_QuasiQuotes | Opt_ImplicitParams | Opt_ImplicitPrelude | Opt_ScopedTypeVariables | Opt_AllowAmbiguousTypes | Opt_UnboxedTuples | Opt_BangPatterns | Opt_TypeFamilies | Opt_OverloadedStrings | Opt_OverloadedLists | Opt_NumDecimals | Opt_DisambiguateRecordFields | Opt_RecordWildCards | Opt_RecordPuns | Opt_ViewPatterns | Opt_GADTs | Opt_GADTSyntax | Opt_NPlusKPatterns | Opt_DoAndIfThenElse | Opt_RebindableSyntax | Opt_ConstraintKinds | Opt_PolyKinds -- Kind polymorphism | Opt_DataKinds -- Datatype promotion | Opt_InstanceSigs | Opt_StandaloneDeriving | Opt_DeriveDataTypeable | Opt_AutoDeriveTypeable -- Automatic derivation of Typeable | Opt_DeriveFunctor | Opt_DeriveTraversable | Opt_DeriveFoldable | Opt_DeriveGeneric -- Allow deriving Generic/1 | Opt_DefaultSignatures -- Allow extra signatures for defmeths | Opt_DeriveAnyClass -- Allow deriving any class | Opt_TypeSynonymInstances | Opt_FlexibleContexts | Opt_FlexibleInstances | Opt_ConstrainedClassMethods | Opt_MultiParamTypeClasses | Opt_NullaryTypeClasses | Opt_FunctionalDependencies | Opt_UnicodeSyntax | Opt_ExistentialQuantification | Opt_MagicHash | Opt_EmptyDataDecls | Opt_KindSignatures | Opt_RoleAnnotations | Opt_ParallelListComp | Opt_TransformListComp | Opt_MonadComprehensions | Opt_GeneralizedNewtypeDeriving | Opt_RecursiveDo | Opt_PostfixOperators | Opt_TupleSections | Opt_PatternGuards | Opt_LiberalTypeSynonyms | Opt_RankNTypes | Opt_ImpredicativeTypes | Opt_TypeOperators | Opt_ExplicitNamespaces | Opt_PackageImports | Opt_ExplicitForAll | Opt_AlternativeLayoutRule | Opt_AlternativeLayoutRuleTransitional | Opt_DatatypeContexts | Opt_NondecreasingIndentation | Opt_RelaxedLayout | Opt_TraditionalRecordSyntax | Opt_LambdaCase | Opt_MultiWayIf | Opt_BinaryLiterals | Opt_NegativeLiterals | Opt_EmptyCase | Opt_PatternSynonyms | Opt_PartialTypeSignatures | Opt_NamedWildCards | Opt_StaticPointers deriving (Eq, Enum, Show) data SigOf = NotSigOf | SigOf Module | SigOfMap (Map ModuleName Module) getSigOf :: DynFlags -> ModuleName -> Maybe Module getSigOf dflags n = case sigOf dflags of NotSigOf -> Nothing SigOf m -> Just m SigOfMap m -> Map.lookup n m -- | Contains not only a collection of 'GeneralFlag's but also a plethora of -- information relating to the compilation of a single file or GHC session data DynFlags = DynFlags { ghcMode :: GhcMode, ghcLink :: GhcLink, hscTarget :: HscTarget, settings :: Settings, -- See Note [Signature parameters in TcGblEnv and DynFlags] sigOf :: SigOf, -- ^ Compiling an hs-boot against impl. verbosity :: Int, -- ^ Verbosity level: see Note [Verbosity levels] optLevel :: Int, -- ^ Optimisation level simplPhases :: Int, -- ^ Number of simplifier phases maxSimplIterations :: Int, -- ^ Max simplifier iterations ruleCheck :: Maybe String, strictnessBefore :: [Int], -- ^ Additional demand analysis parMakeCount :: Maybe Int, -- ^ The number of modules to compile in parallel -- in --make mode, where Nothing ==> compile as -- many in parallel as there are CPUs. enableTimeStats :: Bool, -- ^ Enable RTS timing statistics? ghcHeapSize :: Maybe Int, -- ^ The heap size to set. maxRelevantBinds :: Maybe Int, -- ^ Maximum number of bindings from the type envt -- to show in type error messages simplTickFactor :: Int, -- ^ Multiplier for simplifier ticks specConstrThreshold :: Maybe Int, -- ^ Threshold for SpecConstr specConstrCount :: Maybe Int, -- ^ Max number of specialisations for any one function specConstrRecursive :: Int, -- ^ Max number of specialisations for recursive types -- Not optional; otherwise ForceSpecConstr can diverge. liberateCaseThreshold :: Maybe Int, -- ^ Threshold for LiberateCase floatLamArgs :: Maybe Int, -- ^ Arg count for lambda floating -- See CoreMonad.FloatOutSwitches historySize :: Int, cmdlineHcIncludes :: [String], -- ^ @\-\#includes@ importPaths :: [FilePath], mainModIs :: Module, mainFunIs :: Maybe String, ctxtStkDepth :: Int, -- ^ Typechecker context stack depth tyFunStkDepth :: Int, -- ^ Typechecker type function stack depth thisPackage :: PackageKey, -- ^ name of package currently being compiled -- ways ways :: [Way], -- ^ Way flags from the command line buildTag :: String, -- ^ The global \"way\" (e.g. \"p\" for prof) rtsBuildTag :: String, -- ^ The RTS \"way\" -- For object splitting splitInfo :: Maybe (String,Int), -- paths etc. objectDir :: Maybe String, dylibInstallName :: Maybe String, hiDir :: Maybe String, stubDir :: Maybe String, dumpDir :: Maybe String, objectSuf :: String, hcSuf :: String, hiSuf :: String, canGenerateDynamicToo :: IORef Bool, dynObjectSuf :: String, dynHiSuf :: String, -- Packages.isDllName needs to know whether a call is within a -- single DLL or not. Normally it does this by seeing if the call -- is to the same package, but for the ghc package, we split the -- package between 2 DLLs. The dllSplit tells us which sets of -- modules are in which package. dllSplitFile :: Maybe FilePath, dllSplit :: Maybe [Set String], outputFile :: Maybe String, dynOutputFile :: Maybe String, outputHi :: Maybe String, dynLibLoader :: DynLibLoader, -- | This is set by 'DriverPipeline.runPipeline' based on where -- its output is going. dumpPrefix :: Maybe FilePath, -- | Override the 'dumpPrefix' set by 'DriverPipeline.runPipeline'. -- Set by @-ddump-file-prefix@ dumpPrefixForce :: Maybe FilePath, ldInputs :: [Option], includePaths :: [String], libraryPaths :: [String], frameworkPaths :: [String], -- used on darwin only cmdlineFrameworks :: [String], -- ditto rtsOpts :: Maybe String, rtsOptsEnabled :: RtsOptsEnabled, hpcDir :: String, -- ^ Path to store the .mix files -- Plugins pluginModNames :: [ModuleName], pluginModNameOpts :: [(ModuleName,String)], -- GHC API hooks hooks :: Hooks, -- For ghc -M depMakefile :: FilePath, depIncludePkgDeps :: Bool, depExcludeMods :: [ModuleName], depSuffixes :: [String], -- Package flags extraPkgConfs :: [PkgConfRef] -> [PkgConfRef], -- ^ The @-package-db@ flags given on the command line, in the order -- they appeared. packageFlags :: [PackageFlag], -- ^ The @-package@ and @-hide-package@ flags from the command-line packageEnv :: Maybe FilePath, -- ^ Filepath to the package environment file (if overriding default) -- Package state -- NB. do not modify this field, it is calculated by -- Packages.initPackages pkgDatabase :: Maybe [PackageConfig], pkgState :: PackageState, -- Temporary files -- These have to be IORefs, because the defaultCleanupHandler needs to -- know what to clean when an exception happens filesToClean :: IORef [FilePath], dirsToClean :: IORef (Map FilePath FilePath), filesToNotIntermediateClean :: IORef [FilePath], -- The next available suffix to uniquely name a temp file, updated atomically nextTempSuffix :: IORef Int, -- Names of files which were generated from -ddump-to-file; used to -- track which ones we need to truncate because it's our first run -- through generatedDumps :: IORef (Set FilePath), -- hsc dynamic flags dumpFlags :: IntSet, generalFlags :: IntSet, warningFlags :: IntSet, -- Don't change this without updating extensionFlags: language :: Maybe Language, -- | Safe Haskell mode safeHaskell :: SafeHaskellMode, safeInfer :: Bool, safeInferred :: Bool, -- We store the location of where some extension and flags were turned on so -- we can produce accurate error messages when Safe Haskell fails due to -- them. thOnLoc :: SrcSpan, newDerivOnLoc :: SrcSpan, overlapInstLoc :: SrcSpan, incoherentOnLoc :: SrcSpan, pkgTrustOnLoc :: SrcSpan, warnSafeOnLoc :: SrcSpan, warnUnsafeOnLoc :: SrcSpan, trustworthyOnLoc :: SrcSpan, -- Don't change this without updating extensionFlags: extensions :: [OnOff ExtensionFlag], -- extensionFlags should always be equal to -- flattenExtensionFlags language extensions extensionFlags :: IntSet, -- Unfolding control -- See Note [Discounts and thresholds] in CoreUnfold ufCreationThreshold :: Int, ufUseThreshold :: Int, ufFunAppDiscount :: Int, ufDictDiscount :: Int, ufKeenessFactor :: Float, ufDearOp :: Int, maxWorkerArgs :: Int, ghciHistSize :: Int, -- | MsgDoc output action: use "ErrUtils" instead of this if you can log_action :: LogAction, flushOut :: FlushOut, flushErr :: FlushErr, haddockOptions :: Maybe String, ghciScripts :: [String], -- Output style options pprUserLength :: Int, pprCols :: Int, traceLevel :: Int, -- Standard level is 1. Less verbose is 0. useUnicode :: Bool, -- | what kind of {-# SCC #-} to add automatically profAuto :: ProfAuto, interactivePrint :: Maybe String, llvmVersion :: IORef Int, nextWrapperNum :: IORef (ModuleEnv Int), -- | Machine dependant flags (-m<blah> stuff) sseVersion :: Maybe SseVersion, avx :: Bool, avx2 :: Bool, avx512cd :: Bool, -- Enable AVX-512 Conflict Detection Instructions. avx512er :: Bool, -- Enable AVX-512 Exponential and Reciprocal Instructions. avx512f :: Bool, -- Enable AVX-512 instructions. avx512pf :: Bool, -- Enable AVX-512 PreFetch Instructions. -- | Run-time linker information (what options we need, etc.) rtldInfo :: IORef (Maybe LinkerInfo), -- | Run-time compiler information rtccInfo :: IORef (Maybe CompilerInfo), -- Constants used to control the amount of optimization done. -- | Max size, in bytes, of inline array allocations. maxInlineAllocSize :: Int, -- | Only inline memcpy if it generates no more than this many -- pseudo (roughly: Cmm) instructions. maxInlineMemcpyInsns :: Int, -- | Only inline memset if it generates no more than this many -- pseudo (roughly: Cmm) instructions. maxInlineMemsetInsns :: Int } class HasDynFlags m where getDynFlags :: m DynFlags class ContainsDynFlags t where extractDynFlags :: t -> DynFlags replaceDynFlags :: t -> DynFlags -> t data ProfAuto = NoProfAuto -- ^ no SCC annotations added | ProfAutoAll -- ^ top-level and nested functions are annotated | ProfAutoTop -- ^ top-level functions annotated only | ProfAutoExports -- ^ exported functions annotated only | ProfAutoCalls -- ^ annotate call-sites deriving (Eq,Enum) data Settings = Settings { sTargetPlatform :: Platform, -- Filled in by SysTools sGhcUsagePath :: FilePath, -- Filled in by SysTools sGhciUsagePath :: FilePath, -- ditto sTopDir :: FilePath, sTmpDir :: String, -- no trailing '/' sProgramName :: String, sProjectVersion :: String, -- You shouldn't need to look things up in rawSettings directly. -- They should have their own fields instead. sRawSettings :: [(String, String)], sExtraGccViaCFlags :: [String], sSystemPackageConfig :: FilePath, sLdSupportsCompactUnwind :: Bool, sLdSupportsBuildId :: Bool, sLdSupportsFilelist :: Bool, sLdIsGnuLd :: Bool, -- commands for particular phases sPgm_L :: String, sPgm_P :: (String,[Option]), sPgm_F :: String, sPgm_c :: (String,[Option]), sPgm_s :: (String,[Option]), sPgm_a :: (String,[Option]), sPgm_l :: (String,[Option]), sPgm_dll :: (String,[Option]), sPgm_T :: String, sPgm_sysman :: String, sPgm_windres :: String, sPgm_libtool :: String, sPgm_lo :: (String,[Option]), -- LLVM: opt llvm optimiser sPgm_lc :: (String,[Option]), -- LLVM: llc static compiler -- options for particular phases sOpt_L :: [String], sOpt_P :: [String], sOpt_F :: [String], sOpt_c :: [String], sOpt_a :: [String], sOpt_l :: [String], sOpt_windres :: [String], sOpt_lo :: [String], -- LLVM: llvm optimiser sOpt_lc :: [String], -- LLVM: llc static compiler sPlatformConstants :: PlatformConstants } targetPlatform :: DynFlags -> Platform targetPlatform dflags = sTargetPlatform (settings dflags) programName :: DynFlags -> String programName dflags = sProgramName (settings dflags) projectVersion :: DynFlags -> String projectVersion dflags = sProjectVersion (settings dflags) ghcUsagePath :: DynFlags -> FilePath ghcUsagePath dflags = sGhcUsagePath (settings dflags) ghciUsagePath :: DynFlags -> FilePath ghciUsagePath dflags = sGhciUsagePath (settings dflags) topDir :: DynFlags -> FilePath topDir dflags = sTopDir (settings dflags) tmpDir :: DynFlags -> String tmpDir dflags = sTmpDir (settings dflags) rawSettings :: DynFlags -> [(String, String)] rawSettings dflags = sRawSettings (settings dflags) extraGccViaCFlags :: DynFlags -> [String] extraGccViaCFlags dflags = sExtraGccViaCFlags (settings dflags) systemPackageConfig :: DynFlags -> FilePath systemPackageConfig dflags = sSystemPackageConfig (settings dflags) pgm_L :: DynFlags -> String pgm_L dflags = sPgm_L (settings dflags) pgm_P :: DynFlags -> (String,[Option]) pgm_P dflags = sPgm_P (settings dflags) pgm_F :: DynFlags -> String pgm_F dflags = sPgm_F (settings dflags) pgm_c :: DynFlags -> (String,[Option]) pgm_c dflags = sPgm_c (settings dflags) pgm_s :: DynFlags -> (String,[Option]) pgm_s dflags = sPgm_s (settings dflags) pgm_a :: DynFlags -> (String,[Option]) pgm_a dflags = sPgm_a (settings dflags) pgm_l :: DynFlags -> (String,[Option]) pgm_l dflags = sPgm_l (settings dflags) pgm_dll :: DynFlags -> (String,[Option]) pgm_dll dflags = sPgm_dll (settings dflags) pgm_T :: DynFlags -> String pgm_T dflags = sPgm_T (settings dflags) pgm_sysman :: DynFlags -> String pgm_sysman dflags = sPgm_sysman (settings dflags) pgm_windres :: DynFlags -> String pgm_windres dflags = sPgm_windres (settings dflags) pgm_libtool :: DynFlags -> String pgm_libtool dflags = sPgm_libtool (settings dflags) pgm_lo :: DynFlags -> (String,[Option]) pgm_lo dflags = sPgm_lo (settings dflags) pgm_lc :: DynFlags -> (String,[Option]) pgm_lc dflags = sPgm_lc (settings dflags) opt_L :: DynFlags -> [String] opt_L dflags = sOpt_L (settings dflags) opt_P :: DynFlags -> [String] opt_P dflags = concatMap (wayOptP (targetPlatform dflags)) (ways dflags) ++ sOpt_P (settings dflags) opt_F :: DynFlags -> [String] opt_F dflags = sOpt_F (settings dflags) opt_c :: DynFlags -> [String] opt_c dflags = concatMap (wayOptc (targetPlatform dflags)) (ways dflags) ++ sOpt_c (settings dflags) opt_a :: DynFlags -> [String] opt_a dflags = sOpt_a (settings dflags) opt_l :: DynFlags -> [String] opt_l dflags = concatMap (wayOptl (targetPlatform dflags)) (ways dflags) ++ sOpt_l (settings dflags) opt_windres :: DynFlags -> [String] opt_windres dflags = sOpt_windres (settings dflags) opt_lo :: DynFlags -> [String] opt_lo dflags = sOpt_lo (settings dflags) opt_lc :: DynFlags -> [String] opt_lc dflags = sOpt_lc (settings dflags) -- | The directory for this version of ghc in the user's app directory -- (typically something like @~/.ghc/x86_64-linux-7.6.3@) -- versionedAppDir :: DynFlags -> IO FilePath versionedAppDir dflags = do appdir <- getAppUserDataDirectory (programName dflags) return $ appdir </> (TARGET_ARCH ++ '-':TARGET_OS ++ '-':cProjectVersion) -- | The target code type of the compilation (if any). -- -- Whenever you change the target, also make sure to set 'ghcLink' to -- something sensible. -- -- 'HscNothing' can be used to avoid generating any output, however, note -- that: -- -- * If a program uses Template Haskell the typechecker may try to run code -- from an imported module. This will fail if no code has been generated -- for this module. You can use 'GHC.needsTemplateHaskell' to detect -- whether this might be the case and choose to either switch to a -- different target or avoid typechecking such modules. (The latter may be -- preferable for security reasons.) -- data HscTarget = HscC -- ^ Generate C code. | HscAsm -- ^ Generate assembly using the native code generator. | HscLlvm -- ^ Generate assembly using the llvm code generator. | HscInterpreted -- ^ Generate bytecode. (Requires 'LinkInMemory') | HscNothing -- ^ Don't generate any code. See notes above. deriving (Eq, Show) -- | Will this target result in an object file on the disk? isObjectTarget :: HscTarget -> Bool isObjectTarget HscC = True isObjectTarget HscAsm = True isObjectTarget HscLlvm = True isObjectTarget _ = False -- | Does this target retain *all* top-level bindings for a module, -- rather than just the exported bindings, in the TypeEnv and compiled -- code (if any)? In interpreted mode we do this, so that GHCi can -- call functions inside a module. In HscNothing mode we also do it, -- so that Haddock can get access to the GlobalRdrEnv for a module -- after typechecking it. targetRetainsAllBindings :: HscTarget -> Bool targetRetainsAllBindings HscInterpreted = True targetRetainsAllBindings HscNothing = True targetRetainsAllBindings _ = False -- | The 'GhcMode' tells us whether we're doing multi-module -- compilation (controlled via the "GHC" API) or one-shot -- (single-module) compilation. This makes a difference primarily to -- the "Finder": in one-shot mode we look for interface files for -- imported modules, but in multi-module mode we look for source files -- in order to check whether they need to be recompiled. data GhcMode = CompManager -- ^ @\-\-make@, GHCi, etc. | OneShot -- ^ @ghc -c Foo.hs@ | MkDepend -- ^ @ghc -M@, see "Finder" for why we need this deriving Eq instance Outputable GhcMode where ppr CompManager = ptext (sLit "CompManager") ppr OneShot = ptext (sLit "OneShot") ppr MkDepend = ptext (sLit "MkDepend") isOneShot :: GhcMode -> Bool isOneShot OneShot = True isOneShot _other = False -- | What to do in the link step, if there is one. data GhcLink = NoLink -- ^ Don't link at all | LinkBinary -- ^ Link object code into a binary | LinkInMemory -- ^ Use the in-memory dynamic linker (works for both -- bytecode and object code). | LinkDynLib -- ^ Link objects into a dynamic lib (DLL on Windows, DSO on ELF platforms) | LinkStaticLib -- ^ Link objects into a static lib deriving (Eq, Show) isNoLink :: GhcLink -> Bool isNoLink NoLink = True isNoLink _ = False -- | We accept flags which make packages visible, but how they select -- the package varies; this data type reflects what selection criterion -- is used. data PackageArg = PackageArg String -- ^ @-package@, by 'PackageName' | PackageIdArg String -- ^ @-package-id@, by 'SourcePackageId' | PackageKeyArg String -- ^ @-package-key@, by 'InstalledPackageId' deriving (Eq, Show) -- | Represents the renaming that may be associated with an exposed -- package, e.g. the @rns@ part of @-package "foo (rns)"@. -- -- Here are some example parsings of the package flags (where -- a string literal is punned to be a 'ModuleName': -- -- * @-package foo@ is @ModRenaming True []@ -- * @-package foo ()@ is @ModRenaming False []@ -- * @-package foo (A)@ is @ModRenaming False [("A", "A")]@ -- * @-package foo (A as B)@ is @ModRenaming False [("A", "B")]@ -- * @-package foo with (A as B)@ is @ModRenaming True [("A", "B")]@ data ModRenaming = ModRenaming { modRenamingWithImplicit :: Bool, -- ^ Bring all exposed modules into scope? modRenamings :: [(ModuleName, ModuleName)] -- ^ Bring module @m@ into scope -- under name @n@. } deriving (Eq) -- | Flags for manipulating packages. data PackageFlag = ExposePackage PackageArg ModRenaming -- ^ @-package@, @-package-id@ -- and @-package-key@ | HidePackage String -- ^ @-hide-package@ | IgnorePackage String -- ^ @-ignore-package@ | TrustPackage String -- ^ @-trust-package@ | DistrustPackage String -- ^ @-distrust-package@ deriving (Eq) defaultHscTarget :: Platform -> HscTarget defaultHscTarget = defaultObjectTarget -- | The 'HscTarget' value corresponding to the default way to create -- object files on the current platform. defaultObjectTarget :: Platform -> HscTarget defaultObjectTarget platform | platformUnregisterised platform = HscC | cGhcWithNativeCodeGen == "YES" = HscAsm | otherwise = HscLlvm tablesNextToCode :: DynFlags -> Bool tablesNextToCode dflags = mkTablesNextToCode (platformUnregisterised (targetPlatform dflags)) -- Determines whether we will be compiling -- info tables that reside just before the entry code, or with an -- indirection to the entry code. See TABLES_NEXT_TO_CODE in -- includes/rts/storage/InfoTables.h. mkTablesNextToCode :: Bool -> Bool mkTablesNextToCode unregisterised = not unregisterised && cGhcEnableTablesNextToCode == "YES" data DynLibLoader = Deployable | SystemDependent deriving Eq data RtsOptsEnabled = RtsOptsNone | RtsOptsSafeOnly | RtsOptsAll deriving (Show) ----------------------------------------------------------------------------- -- Ways -- The central concept of a "way" is that all objects in a given -- program must be compiled in the same "way". Certain options change -- parameters of the virtual machine, eg. profiling adds an extra word -- to the object header, so profiling objects cannot be linked with -- non-profiling objects. -- After parsing the command-line options, we determine which "way" we -- are building - this might be a combination way, eg. profiling+threaded. -- We then find the "build-tag" associated with this way, and this -- becomes the suffix used to find .hi files and libraries used in -- this compilation. data Way = WayCustom String -- for GHC API clients building custom variants | WayThreaded | WayDebug | WayProf | WayEventLog | WayPar | WayNDP | WayDyn deriving (Eq, Ord, Show) allowed_combination :: [Way] -> Bool allowed_combination way = and [ x `allowedWith` y | x <- way, y <- way, x < y ] where -- Note ordering in these tests: the left argument is -- <= the right argument, according to the Ord instance -- on Way above. -- dyn is allowed with everything _ `allowedWith` WayDyn = True WayDyn `allowedWith` _ = True -- debug is allowed with everything _ `allowedWith` WayDebug = True WayDebug `allowedWith` _ = True (WayCustom {}) `allowedWith` _ = True WayProf `allowedWith` WayNDP = True WayThreaded `allowedWith` WayProf = True WayThreaded `allowedWith` WayEventLog = True _ `allowedWith` _ = False mkBuildTag :: [Way] -> String mkBuildTag ways = concat (intersperse "_" (map wayTag ways)) wayTag :: Way -> String wayTag (WayCustom xs) = xs wayTag WayThreaded = "thr" wayTag WayDebug = "debug" wayTag WayDyn = "dyn" wayTag WayProf = "p" wayTag WayEventLog = "l" wayTag WayPar = "mp" wayTag WayNDP = "ndp" wayRTSOnly :: Way -> Bool wayRTSOnly (WayCustom {}) = False wayRTSOnly WayThreaded = True wayRTSOnly WayDebug = True wayRTSOnly WayDyn = False wayRTSOnly WayProf = False wayRTSOnly WayEventLog = True wayRTSOnly WayPar = False wayRTSOnly WayNDP = False wayDesc :: Way -> String wayDesc (WayCustom xs) = xs wayDesc WayThreaded = "Threaded" wayDesc WayDebug = "Debug" wayDesc WayDyn = "Dynamic" wayDesc WayProf = "Profiling" wayDesc WayEventLog = "RTS Event Logging" wayDesc WayPar = "Parallel" wayDesc WayNDP = "Nested data parallelism" -- Turn these flags on when enabling this way wayGeneralFlags :: Platform -> Way -> [GeneralFlag] wayGeneralFlags _ (WayCustom {}) = [] wayGeneralFlags _ WayThreaded = [] wayGeneralFlags _ WayDebug = [] wayGeneralFlags _ WayDyn = [Opt_PIC] -- We could get away without adding -fPIC when compiling the -- modules of a program that is to be linked with -dynamic; the -- program itself does not need to be position-independent, only -- the libraries need to be. HOWEVER, GHCi links objects into a -- .so before loading the .so using the system linker. Since only -- PIC objects can be linked into a .so, we have to compile even -- modules of the main program with -fPIC when using -dynamic. wayGeneralFlags _ WayProf = [Opt_SccProfilingOn] wayGeneralFlags _ WayEventLog = [] wayGeneralFlags _ WayPar = [Opt_Parallel] wayGeneralFlags _ WayNDP = [] -- Turn these flags off when enabling this way wayUnsetGeneralFlags :: Platform -> Way -> [GeneralFlag] wayUnsetGeneralFlags _ (WayCustom {}) = [] wayUnsetGeneralFlags _ WayThreaded = [] wayUnsetGeneralFlags _ WayDebug = [] wayUnsetGeneralFlags _ WayDyn = [-- There's no point splitting objects -- when we're going to be dynamically -- linking. Plus it breaks compilation -- on OSX x86. Opt_SplitObjs] wayUnsetGeneralFlags _ WayProf = [] wayUnsetGeneralFlags _ WayEventLog = [] wayUnsetGeneralFlags _ WayPar = [] wayUnsetGeneralFlags _ WayNDP = [] wayExtras :: Platform -> Way -> DynFlags -> DynFlags wayExtras _ (WayCustom {}) dflags = dflags wayExtras _ WayThreaded dflags = dflags wayExtras _ WayDebug dflags = dflags wayExtras _ WayDyn dflags = dflags wayExtras _ WayProf dflags = dflags wayExtras _ WayEventLog dflags = dflags wayExtras _ WayPar dflags = exposePackage' "concurrent" dflags wayExtras _ WayNDP dflags = setExtensionFlag' Opt_ParallelArrays $ setGeneralFlag' Opt_Vectorise dflags wayOptc :: Platform -> Way -> [String] wayOptc _ (WayCustom {}) = [] wayOptc platform WayThreaded = case platformOS platform of OSOpenBSD -> ["-pthread"] OSNetBSD -> ["-pthread"] _ -> [] wayOptc _ WayDebug = [] wayOptc _ WayDyn = [] wayOptc _ WayProf = ["-DPROFILING"] wayOptc _ WayEventLog = ["-DTRACING"] wayOptc _ WayPar = ["-DPAR", "-w"] wayOptc _ WayNDP = [] wayOptl :: Platform -> Way -> [String] wayOptl _ (WayCustom {}) = [] wayOptl platform WayThreaded = case platformOS platform of -- FreeBSD's default threading library is the KSE-based M:N libpthread, -- which GHC has some problems with. It's currently not clear whether -- the problems are our fault or theirs, but it seems that using the -- alternative 1:1 threading library libthr works around it: OSFreeBSD -> ["-lthr"] OSOpenBSD -> ["-pthread"] OSNetBSD -> ["-pthread"] _ -> [] wayOptl _ WayDebug = [] wayOptl _ WayDyn = [] wayOptl _ WayProf = [] wayOptl _ WayEventLog = [] wayOptl _ WayPar = ["-L${PVM_ROOT}/lib/${PVM_ARCH}", "-lpvm3", "-lgpvm3"] wayOptl _ WayNDP = [] wayOptP :: Platform -> Way -> [String] wayOptP _ (WayCustom {}) = [] wayOptP _ WayThreaded = [] wayOptP _ WayDebug = [] wayOptP _ WayDyn = [] wayOptP _ WayProf = ["-DPROFILING"] wayOptP _ WayEventLog = ["-DTRACING"] wayOptP _ WayPar = ["-D__PARALLEL_HASKELL__"] wayOptP _ WayNDP = [] whenGeneratingDynamicToo :: MonadIO m => DynFlags -> m () -> m () whenGeneratingDynamicToo dflags f = ifGeneratingDynamicToo dflags f (return ()) ifGeneratingDynamicToo :: MonadIO m => DynFlags -> m a -> m a -> m a ifGeneratingDynamicToo dflags f g = generateDynamicTooConditional dflags f g g whenCannotGenerateDynamicToo :: MonadIO m => DynFlags -> m () -> m () whenCannotGenerateDynamicToo dflags f = ifCannotGenerateDynamicToo dflags f (return ()) ifCannotGenerateDynamicToo :: MonadIO m => DynFlags -> m a -> m a -> m a ifCannotGenerateDynamicToo dflags f g = generateDynamicTooConditional dflags g f g generateDynamicTooConditional :: MonadIO m => DynFlags -> m a -> m a -> m a -> m a generateDynamicTooConditional dflags canGen cannotGen notTryingToGen = if gopt Opt_BuildDynamicToo dflags then do let ref = canGenerateDynamicToo dflags b <- liftIO $ readIORef ref if b then canGen else cannotGen else notTryingToGen dynamicTooMkDynamicDynFlags :: DynFlags -> DynFlags dynamicTooMkDynamicDynFlags dflags0 = let dflags1 = addWay' WayDyn dflags0 dflags2 = dflags1 { outputFile = dynOutputFile dflags1, hiSuf = dynHiSuf dflags1, objectSuf = dynObjectSuf dflags1 } dflags3 = updateWays dflags2 dflags4 = gopt_unset dflags3 Opt_BuildDynamicToo in dflags4 ----------------------------------------------------------------------------- -- | Used by 'GHC.runGhc' to partially initialize a new 'DynFlags' value initDynFlags :: DynFlags -> IO DynFlags initDynFlags dflags = do let -- We can't build with dynamic-too on Windows, as labels before -- the fork point are different depending on whether we are -- building dynamically or not. platformCanGenerateDynamicToo = platformOS (targetPlatform dflags) /= OSMinGW32 refCanGenerateDynamicToo <- newIORef platformCanGenerateDynamicToo refNextTempSuffix <- newIORef 0 refFilesToClean <- newIORef [] refDirsToClean <- newIORef Map.empty refFilesToNotIntermediateClean <- newIORef [] refGeneratedDumps <- newIORef Set.empty refLlvmVersion <- newIORef 28 refRtldInfo <- newIORef Nothing refRtccInfo <- newIORef Nothing wrapperNum <- newIORef emptyModuleEnv canUseUnicode <- do let enc = localeEncoding str = "‘’" (withCString enc str $ \cstr -> do str' <- peekCString enc cstr return (str == str')) `catchIOError` \_ -> return False return dflags{ canGenerateDynamicToo = refCanGenerateDynamicToo, nextTempSuffix = refNextTempSuffix, filesToClean = refFilesToClean, dirsToClean = refDirsToClean, filesToNotIntermediateClean = refFilesToNotIntermediateClean, generatedDumps = refGeneratedDumps, llvmVersion = refLlvmVersion, nextWrapperNum = wrapperNum, useUnicode = canUseUnicode, rtldInfo = refRtldInfo, rtccInfo = refRtccInfo } -- | The normal 'DynFlags'. Note that they are not suitable for use in this form -- and must be fully initialized by 'GHC.runGhc' first. defaultDynFlags :: Settings -> DynFlags defaultDynFlags mySettings = -- See Note [Updating flag description in the User's Guide] DynFlags { ghcMode = CompManager, ghcLink = LinkBinary, hscTarget = defaultHscTarget (sTargetPlatform mySettings), sigOf = NotSigOf, verbosity = 0, optLevel = 0, simplPhases = 2, maxSimplIterations = 4, ruleCheck = Nothing, maxRelevantBinds = Just 6, simplTickFactor = 100, specConstrThreshold = Just 2000, specConstrCount = Just 3, specConstrRecursive = 3, liberateCaseThreshold = Just 2000, floatLamArgs = Just 0, -- Default: float only if no fvs historySize = 20, strictnessBefore = [], parMakeCount = Just 1, enableTimeStats = False, ghcHeapSize = Nothing, cmdlineHcIncludes = [], importPaths = ["."], mainModIs = mAIN, mainFunIs = Nothing, ctxtStkDepth = mAX_CONTEXT_REDUCTION_DEPTH, tyFunStkDepth = mAX_TYPE_FUNCTION_REDUCTION_DEPTH, thisPackage = mainPackageKey, objectDir = Nothing, dylibInstallName = Nothing, hiDir = Nothing, stubDir = Nothing, dumpDir = Nothing, objectSuf = phaseInputExt StopLn, hcSuf = phaseInputExt HCc, hiSuf = "hi", canGenerateDynamicToo = panic "defaultDynFlags: No canGenerateDynamicToo", dynObjectSuf = "dyn_" ++ phaseInputExt StopLn, dynHiSuf = "dyn_hi", dllSplitFile = Nothing, dllSplit = Nothing, pluginModNames = [], pluginModNameOpts = [], hooks = emptyHooks, outputFile = Nothing, dynOutputFile = Nothing, outputHi = Nothing, dynLibLoader = SystemDependent, dumpPrefix = Nothing, dumpPrefixForce = Nothing, ldInputs = [], includePaths = [], libraryPaths = [], frameworkPaths = [], cmdlineFrameworks = [], rtsOpts = Nothing, rtsOptsEnabled = RtsOptsSafeOnly, hpcDir = ".hpc", extraPkgConfs = id, packageFlags = [], packageEnv = Nothing, pkgDatabase = Nothing, pkgState = panic "no package state yet: call GHC.setSessionDynFlags", ways = defaultWays mySettings, buildTag = mkBuildTag (defaultWays mySettings), rtsBuildTag = mkBuildTag (defaultWays mySettings), splitInfo = Nothing, settings = mySettings, -- ghc -M values depMakefile = "Makefile", depIncludePkgDeps = False, depExcludeMods = [], depSuffixes = [], -- end of ghc -M values nextTempSuffix = panic "defaultDynFlags: No nextTempSuffix", filesToClean = panic "defaultDynFlags: No filesToClean", dirsToClean = panic "defaultDynFlags: No dirsToClean", filesToNotIntermediateClean = panic "defaultDynFlags: No filesToNotIntermediateClean", generatedDumps = panic "defaultDynFlags: No generatedDumps", haddockOptions = Nothing, dumpFlags = IntSet.empty, generalFlags = IntSet.fromList (map fromEnum (defaultFlags mySettings)), warningFlags = IntSet.fromList (map fromEnum standardWarnings), ghciScripts = [], language = Nothing, safeHaskell = Sf_None, safeInfer = True, safeInferred = True, thOnLoc = noSrcSpan, newDerivOnLoc = noSrcSpan, overlapInstLoc = noSrcSpan, incoherentOnLoc = noSrcSpan, pkgTrustOnLoc = noSrcSpan, warnSafeOnLoc = noSrcSpan, warnUnsafeOnLoc = noSrcSpan, trustworthyOnLoc = noSrcSpan, extensions = [], extensionFlags = flattenExtensionFlags Nothing [], -- The ufCreationThreshold threshold must be reasonably high to -- take account of possible discounts. -- E.g. 450 is not enough in 'fulsom' for Interval.sqr to inline -- into Csg.calc (The unfolding for sqr never makes it into the -- interface file.) ufCreationThreshold = 750, ufUseThreshold = 60, ufFunAppDiscount = 60, -- Be fairly keen to inline a fuction if that means -- we'll be able to pick the right method from a dictionary ufDictDiscount = 30, ufKeenessFactor = 1.5, ufDearOp = 40, maxWorkerArgs = 10, ghciHistSize = 50, -- keep a log of length 50 by default log_action = defaultLogAction, flushOut = defaultFlushOut, flushErr = defaultFlushErr, pprUserLength = 5, pprCols = 100, useUnicode = False, traceLevel = 1, profAuto = NoProfAuto, llvmVersion = panic "defaultDynFlags: No llvmVersion", interactivePrint = Nothing, nextWrapperNum = panic "defaultDynFlags: No nextWrapperNum", sseVersion = Nothing, avx = False, avx2 = False, avx512cd = False, avx512er = False, avx512f = False, avx512pf = False, rtldInfo = panic "defaultDynFlags: no rtldInfo", rtccInfo = panic "defaultDynFlags: no rtccInfo", maxInlineAllocSize = 128, maxInlineMemcpyInsns = 32, maxInlineMemsetInsns = 32 } defaultWays :: Settings -> [Way] defaultWays settings = if pc_DYNAMIC_BY_DEFAULT (sPlatformConstants settings) then [WayDyn] else [] interpWays :: [Way] interpWays = if dynamicGhc then [WayDyn] else [] -------------------------------------------------------------------------- type FatalMessager = String -> IO () type LogAction = DynFlags -> Severity -> SrcSpan -> PprStyle -> MsgDoc -> IO () defaultFatalMessager :: FatalMessager defaultFatalMessager = hPutStrLn stderr defaultLogAction :: LogAction defaultLogAction dflags severity srcSpan style msg = case severity of SevOutput -> printSDoc msg style SevDump -> printSDoc (msg $$ blankLine) style SevInteractive -> putStrSDoc msg style SevInfo -> printErrs msg style SevFatal -> printErrs msg style _ -> do hPutChar stderr '\n' printErrs (mkLocMessage severity srcSpan msg) style -- careful (#2302): printErrs prints in UTF-8, -- whereas converting to string first and using -- hPutStr would just emit the low 8 bits of -- each unicode char. where printSDoc = defaultLogActionHPrintDoc dflags stdout printErrs = defaultLogActionHPrintDoc dflags stderr putStrSDoc = defaultLogActionHPutStrDoc dflags stdout defaultLogActionHPrintDoc :: DynFlags -> Handle -> SDoc -> PprStyle -> IO () defaultLogActionHPrintDoc dflags h d sty = defaultLogActionHPutStrDoc dflags h (d $$ text "") sty -- Adds a newline defaultLogActionHPutStrDoc :: DynFlags -> Handle -> SDoc -> PprStyle -> IO () defaultLogActionHPutStrDoc dflags h d sty = Pretty.printDoc_ Pretty.PageMode (pprCols dflags) h doc where -- Don't add a newline at the end, so that successive -- calls to this log-action can output all on the same line doc = runSDoc d (initSDocContext dflags sty) newtype FlushOut = FlushOut (IO ()) defaultFlushOut :: FlushOut defaultFlushOut = FlushOut $ hFlush stdout newtype FlushErr = FlushErr (IO ()) defaultFlushErr :: FlushErr defaultFlushErr = FlushErr $ hFlush stderr {- Note [Verbosity levels] ~~~~~~~~~~~~~~~~~~~~~~~ 0 | print errors & warnings only 1 | minimal verbosity: print "compiling M ... done." for each module. 2 | equivalent to -dshow-passes 3 | equivalent to existing "ghc -v" 4 | "ghc -v -ddump-most" 5 | "ghc -v -ddump-all" -} data OnOff a = On a | Off a -- OnOffs accumulate in reverse order, so we use foldr in order to -- process them in the right order flattenExtensionFlags :: Maybe Language -> [OnOff ExtensionFlag] -> IntSet flattenExtensionFlags ml = foldr f defaultExtensionFlags where f (On f) flags = IntSet.insert (fromEnum f) flags f (Off f) flags = IntSet.delete (fromEnum f) flags defaultExtensionFlags = IntSet.fromList (map fromEnum (languageExtensions ml)) languageExtensions :: Maybe Language -> [ExtensionFlag] languageExtensions Nothing -- Nothing => the default case = Opt_NondecreasingIndentation -- This has been on by default for some time : delete Opt_DatatypeContexts -- The Haskell' committee decided to -- remove datatype contexts from the -- language: -- http://www.haskell.org/pipermail/haskell-prime/2011-January/003335.html (languageExtensions (Just Haskell2010)) -- NB: MonoPatBinds is no longer the default languageExtensions (Just Haskell98) = [Opt_ImplicitPrelude, Opt_MonomorphismRestriction, Opt_NPlusKPatterns, Opt_DatatypeContexts, Opt_TraditionalRecordSyntax, Opt_NondecreasingIndentation -- strictly speaking non-standard, but we always had this -- on implicitly before the option was added in 7.1, and -- turning it off breaks code, so we're keeping it on for -- backwards compatibility. Cabal uses -XHaskell98 by -- default unless you specify another language. ] languageExtensions (Just Haskell2010) = [Opt_ImplicitPrelude, Opt_MonomorphismRestriction, Opt_DatatypeContexts, Opt_TraditionalRecordSyntax, Opt_EmptyDataDecls, Opt_ForeignFunctionInterface, Opt_PatternGuards, Opt_DoAndIfThenElse, Opt_RelaxedPolyRec] -- | Test whether a 'DumpFlag' is set dopt :: DumpFlag -> DynFlags -> Bool dopt f dflags = (fromEnum f `IntSet.member` dumpFlags dflags) || (verbosity dflags >= 4 && enableIfVerbose f) where enableIfVerbose Opt_D_dump_tc_trace = False enableIfVerbose Opt_D_dump_rn_trace = False enableIfVerbose Opt_D_dump_cs_trace = False enableIfVerbose Opt_D_dump_if_trace = False enableIfVerbose Opt_D_dump_vt_trace = False enableIfVerbose Opt_D_dump_tc = False enableIfVerbose Opt_D_dump_rn = False enableIfVerbose Opt_D_dump_rn_stats = False enableIfVerbose Opt_D_dump_hi_diffs = False enableIfVerbose Opt_D_verbose_core2core = False enableIfVerbose Opt_D_verbose_stg2stg = False enableIfVerbose Opt_D_dump_splices = False enableIfVerbose Opt_D_th_dec_file = False enableIfVerbose Opt_D_dump_rule_firings = False enableIfVerbose Opt_D_dump_rule_rewrites = False enableIfVerbose Opt_D_dump_simpl_trace = False enableIfVerbose Opt_D_dump_rtti = False enableIfVerbose Opt_D_dump_inlinings = False enableIfVerbose Opt_D_dump_core_stats = False enableIfVerbose Opt_D_dump_asm_stats = False enableIfVerbose Opt_D_dump_types = False enableIfVerbose Opt_D_dump_simpl_iterations = False enableIfVerbose Opt_D_dump_ticked = False enableIfVerbose Opt_D_dump_view_pattern_commoning = False enableIfVerbose Opt_D_dump_mod_cycles = False enableIfVerbose Opt_D_dump_mod_map = False enableIfVerbose _ = True -- | Set a 'DumpFlag' dopt_set :: DynFlags -> DumpFlag -> DynFlags dopt_set dfs f = dfs{ dumpFlags = IntSet.insert (fromEnum f) (dumpFlags dfs) } -- | Unset a 'DumpFlag' dopt_unset :: DynFlags -> DumpFlag -> DynFlags dopt_unset dfs f = dfs{ dumpFlags = IntSet.delete (fromEnum f) (dumpFlags dfs) } -- | Test whether a 'GeneralFlag' is set gopt :: GeneralFlag -> DynFlags -> Bool gopt f dflags = fromEnum f `IntSet.member` generalFlags dflags -- | Set a 'GeneralFlag' gopt_set :: DynFlags -> GeneralFlag -> DynFlags gopt_set dfs f = dfs{ generalFlags = IntSet.insert (fromEnum f) (generalFlags dfs) } -- | Unset a 'GeneralFlag' gopt_unset :: DynFlags -> GeneralFlag -> DynFlags gopt_unset dfs f = dfs{ generalFlags = IntSet.delete (fromEnum f) (generalFlags dfs) } -- | Test whether a 'WarningFlag' is set wopt :: WarningFlag -> DynFlags -> Bool wopt f dflags = fromEnum f `IntSet.member` warningFlags dflags -- | Set a 'WarningFlag' wopt_set :: DynFlags -> WarningFlag -> DynFlags wopt_set dfs f = dfs{ warningFlags = IntSet.insert (fromEnum f) (warningFlags dfs) } -- | Unset a 'WarningFlag' wopt_unset :: DynFlags -> WarningFlag -> DynFlags wopt_unset dfs f = dfs{ warningFlags = IntSet.delete (fromEnum f) (warningFlags dfs) } -- | Test whether a 'ExtensionFlag' is set xopt :: ExtensionFlag -> DynFlags -> Bool xopt f dflags = fromEnum f `IntSet.member` extensionFlags dflags -- | Set a 'ExtensionFlag' xopt_set :: DynFlags -> ExtensionFlag -> DynFlags xopt_set dfs f = let onoffs = On f : extensions dfs in dfs { extensions = onoffs, extensionFlags = flattenExtensionFlags (language dfs) onoffs } -- | Unset a 'ExtensionFlag' xopt_unset :: DynFlags -> ExtensionFlag -> DynFlags xopt_unset dfs f = let onoffs = Off f : extensions dfs in dfs { extensions = onoffs, extensionFlags = flattenExtensionFlags (language dfs) onoffs } lang_set :: DynFlags -> Maybe Language -> DynFlags lang_set dflags lang = dflags { language = lang, extensionFlags = flattenExtensionFlags lang (extensions dflags) } useUnicodeSyntax :: DynFlags -> Bool useUnicodeSyntax = xopt Opt_UnicodeSyntax -- | Set the Haskell language standard to use setLanguage :: Language -> DynP () setLanguage l = upd (`lang_set` Just l) -- | Some modules have dependencies on others through the DynFlags rather than textual imports dynFlagDependencies :: DynFlags -> [ModuleName] dynFlagDependencies = pluginModNames -- | Is the -fpackage-trust mode on packageTrustOn :: DynFlags -> Bool packageTrustOn = gopt Opt_PackageTrust -- | Is Safe Haskell on in some way (including inference mode) safeHaskellOn :: DynFlags -> Bool safeHaskellOn dflags = safeHaskell dflags /= Sf_None || safeInferOn dflags -- | Is the Safe Haskell safe language in use safeLanguageOn :: DynFlags -> Bool safeLanguageOn dflags = safeHaskell dflags == Sf_Safe -- | Is the Safe Haskell safe inference mode active safeInferOn :: DynFlags -> Bool safeInferOn = safeInfer -- | Test if Safe Imports are on in some form safeImportsOn :: DynFlags -> Bool safeImportsOn dflags = safeHaskell dflags == Sf_Unsafe || safeHaskell dflags == Sf_Trustworthy || safeHaskell dflags == Sf_Safe -- | Set a 'Safe Haskell' flag setSafeHaskell :: SafeHaskellMode -> DynP () setSafeHaskell s = updM f where f dfs = do let sf = safeHaskell dfs safeM <- combineSafeFlags sf s case s of Sf_Safe -> return $ dfs { safeHaskell = safeM, safeInfer = False } -- leave safe inferrence on in Trustworthy mode so we can warn -- if it could have been inferred safe. Sf_Trustworthy -> do l <- getCurLoc return $ dfs { safeHaskell = safeM, trustworthyOnLoc = l } -- leave safe inference on in Unsafe mode as well. _ -> return $ dfs { safeHaskell = safeM } -- | Are all direct imports required to be safe for this Safe Haskell mode? -- Direct imports are when the code explicitly imports a module safeDirectImpsReq :: DynFlags -> Bool safeDirectImpsReq d = safeLanguageOn d -- | Are all implicit imports required to be safe for this Safe Haskell mode? -- Implicit imports are things in the prelude. e.g System.IO when print is used. safeImplicitImpsReq :: DynFlags -> Bool safeImplicitImpsReq d = safeLanguageOn d -- | Combine two Safe Haskell modes correctly. Used for dealing with multiple flags. -- This makes Safe Haskell very much a monoid but for now I prefer this as I don't -- want to export this functionality from the module but do want to export the -- type constructors. combineSafeFlags :: SafeHaskellMode -> SafeHaskellMode -> DynP SafeHaskellMode combineSafeFlags a b | a == Sf_None = return b | b == Sf_None = return a | a == b = return a | otherwise = addErr errm >> return (panic errm) where errm = "Incompatible Safe Haskell flags! (" ++ show a ++ ", " ++ show b ++ ")" -- | A list of unsafe flags under Safe Haskell. Tuple elements are: -- * name of the flag -- * function to get srcspan that enabled the flag -- * function to test if the flag is on -- * function to turn the flag off unsafeFlags, unsafeFlagsForInfer :: [(String, DynFlags -> SrcSpan, DynFlags -> Bool, DynFlags -> DynFlags)] unsafeFlags = [ ("-XGeneralizedNewtypeDeriving", newDerivOnLoc, xopt Opt_GeneralizedNewtypeDeriving, flip xopt_unset Opt_GeneralizedNewtypeDeriving) , ("-XTemplateHaskell", thOnLoc, xopt Opt_TemplateHaskell, flip xopt_unset Opt_TemplateHaskell) ] unsafeFlagsForInfer = unsafeFlags ++ -- TODO: Can we do better than this for inference? [ ("-XOverlappingInstances", overlapInstLoc, xopt Opt_OverlappingInstances, flip xopt_unset Opt_OverlappingInstances) , ("-XIncoherentInstances", incoherentOnLoc, xopt Opt_IncoherentInstances, flip xopt_unset Opt_IncoherentInstances) ] -- | Retrieve the options corresponding to a particular @opt_*@ field in the correct order getOpts :: DynFlags -- ^ 'DynFlags' to retrieve the options from -> (DynFlags -> [a]) -- ^ Relevant record accessor: one of the @opt_*@ accessors -> [a] -- ^ Correctly ordered extracted options getOpts dflags opts = reverse (opts dflags) -- We add to the options from the front, so we need to reverse the list -- | Gets the verbosity flag for the current verbosity level. This is fed to -- other tools, so GHC-specific verbosity flags like @-ddump-most@ are not included getVerbFlags :: DynFlags -> [String] getVerbFlags dflags | verbosity dflags >= 4 = ["-v"] | otherwise = [] setObjectDir, setHiDir, setStubDir, setDumpDir, setOutputDir, setDynObjectSuf, setDynHiSuf, setDylibInstallName, setObjectSuf, setHiSuf, setHcSuf, parseDynLibLoaderMode, setPgmP, addOptl, addOptc, addOptP, addCmdlineFramework, addHaddockOpts, addGhciScript, setInteractivePrint :: String -> DynFlags -> DynFlags setOutputFile, setDynOutputFile, setOutputHi, setDumpPrefixForce :: Maybe String -> DynFlags -> DynFlags setObjectDir f d = d{ objectDir = Just f} setHiDir f d = d{ hiDir = Just f} setStubDir f d = d{ stubDir = Just f, includePaths = f : includePaths d } -- -stubdir D adds an implicit -I D, so that gcc can find the _stub.h file -- \#included from the .hc file when compiling via C (i.e. unregisterised -- builds). setDumpDir f d = d{ dumpDir = Just f} setOutputDir f = setObjectDir f . setHiDir f . setStubDir f . setDumpDir f setDylibInstallName f d = d{ dylibInstallName = Just f} setObjectSuf f d = d{ objectSuf = f} setDynObjectSuf f d = d{ dynObjectSuf = f} setHiSuf f d = d{ hiSuf = f} setDynHiSuf f d = d{ dynHiSuf = f} setHcSuf f d = d{ hcSuf = f} setOutputFile f d = d{ outputFile = f} setDynOutputFile f d = d{ dynOutputFile = f} setOutputHi f d = d{ outputHi = f} parseSigOf :: String -> SigOf parseSigOf str = case filter ((=="").snd) (readP_to_S parse str) of [(r, "")] -> r _ -> throwGhcException $ CmdLineError ("Can't parse -sig-of: " ++ str) where parse = parseOne +++ parseMany parseOne = SigOf `fmap` parseModule parseMany = SigOfMap . Map.fromList <$> sepBy parseEntry (R.char ',') parseEntry = do n <- tok $ parseModuleName -- ToDo: deprecate this 'is' syntax? tok $ ((string "is" >> return ()) +++ (R.char '=' >> return ())) m <- tok $ parseModule return (n, m) parseModule = do pk <- munch1 (\c -> isAlphaNum c || c `elem` "-_") _ <- R.char ':' m <- parseModuleName return (mkModule (stringToPackageKey pk) m) tok m = skipSpaces >> m setSigOf :: String -> DynFlags -> DynFlags setSigOf s d = d { sigOf = parseSigOf s } addPluginModuleName :: String -> DynFlags -> DynFlags addPluginModuleName name d = d { pluginModNames = (mkModuleName name) : (pluginModNames d) } addPluginModuleNameOption :: String -> DynFlags -> DynFlags addPluginModuleNameOption optflag d = d { pluginModNameOpts = (mkModuleName m, option) : (pluginModNameOpts d) } where (m, rest) = break (== ':') optflag option = case rest of [] -> "" -- should probably signal an error (_:plug_opt) -> plug_opt -- ignore the ':' from break parseDynLibLoaderMode f d = case splitAt 8 f of ("deploy", "") -> d{ dynLibLoader = Deployable } ("sysdep", "") -> d{ dynLibLoader = SystemDependent } _ -> throwGhcException (CmdLineError ("Unknown dynlib loader: " ++ f)) setDumpPrefixForce f d = d { dumpPrefixForce = f} -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"] -- Config.hs should really use Option. setPgmP f = let (pgm:args) = words f in alterSettings (\s -> s { sPgm_P = (pgm, map Option args)}) addOptl f = alterSettings (\s -> s { sOpt_l = f : sOpt_l s}) addOptc f = alterSettings (\s -> s { sOpt_c = f : sOpt_c s}) addOptP f = alterSettings (\s -> s { sOpt_P = f : sOpt_P s}) setDepMakefile :: FilePath -> DynFlags -> DynFlags setDepMakefile f d = d { depMakefile = f } setDepIncludePkgDeps :: Bool -> DynFlags -> DynFlags setDepIncludePkgDeps b d = d { depIncludePkgDeps = b } addDepExcludeMod :: String -> DynFlags -> DynFlags addDepExcludeMod m d = d { depExcludeMods = mkModuleName m : depExcludeMods d } addDepSuffix :: FilePath -> DynFlags -> DynFlags addDepSuffix s d = d { depSuffixes = s : depSuffixes d } addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d} addHaddockOpts f d = d{ haddockOptions = Just f} addGhciScript f d = d{ ghciScripts = f : ghciScripts d} setInteractivePrint f d = d{ interactivePrint = Just f} -- ----------------------------------------------------------------------------- -- Command-line options -- | When invoking external tools as part of the compilation pipeline, we -- pass these a sequence of options on the command-line. Rather than -- just using a list of Strings, we use a type that allows us to distinguish -- between filepaths and 'other stuff'. The reason for this is that -- this type gives us a handle on transforming filenames, and filenames only, -- to whatever format they're expected to be on a particular platform. data Option = FileOption -- an entry that _contains_ filename(s) / filepaths. String -- a non-filepath prefix that shouldn't be -- transformed (e.g., "/out=") String -- the filepath/filename portion | Option String deriving ( Eq ) showOpt :: Option -> String showOpt (FileOption pre f) = pre ++ f showOpt (Option s) = s ----------------------------------------------------------------------------- -- Setting the optimisation level updOptLevel :: Int -> DynFlags -> DynFlags -- ^ Sets the 'DynFlags' to be appropriate to the optimisation level updOptLevel n dfs = dfs2{ optLevel = final_n } where final_n = max 0 (min 2 n) -- Clamp to 0 <= n <= 2 dfs1 = foldr (flip gopt_unset) dfs remove_gopts dfs2 = foldr (flip gopt_set) dfs1 extra_gopts extra_gopts = [ f | (ns,f) <- optLevelFlags, final_n `elem` ns ] remove_gopts = [ f | (ns,f) <- optLevelFlags, final_n `notElem` ns ] -- ----------------------------------------------------------------------------- -- StgToDo: abstraction of stg-to-stg passes to run. data StgToDo = StgDoMassageForProfiling -- should be (next to) last -- There's also setStgVarInfo, but its absolute "lastness" -- is so critical that it is hardwired in (no flag). | D_stg_stats getStgToDo :: DynFlags -> [StgToDo] getStgToDo dflags = todo2 where stg_stats = gopt Opt_StgStats dflags todo1 = if stg_stats then [D_stg_stats] else [] todo2 | WayProf `elem` ways dflags = StgDoMassageForProfiling : todo1 | otherwise = todo1 {- ********************************************************************** %* * DynFlags parser %* * %********************************************************************* -} -- ----------------------------------------------------------------------------- -- Parsing the dynamic flags. -- | Parse dynamic flags from a list of command line arguments. Returns the -- the parsed 'DynFlags', the left-over arguments, and a list of warnings. -- Throws a 'UsageError' if errors occurred during parsing (such as unknown -- flags or missing arguments). parseDynamicFlagsCmdLine :: MonadIO m => DynFlags -> [Located String] -> m (DynFlags, [Located String], [Located String]) -- ^ Updated 'DynFlags', left-over arguments, and -- list of warnings. parseDynamicFlagsCmdLine = parseDynamicFlagsFull flagsAll True -- | Like 'parseDynamicFlagsCmdLine' but does not allow the package flags -- (-package, -hide-package, -ignore-package, -hide-all-packages, -package-db). -- Used to parse flags set in a modules pragma. parseDynamicFilePragma :: MonadIO m => DynFlags -> [Located String] -> m (DynFlags, [Located String], [Located String]) -- ^ Updated 'DynFlags', left-over arguments, and -- list of warnings. parseDynamicFilePragma = parseDynamicFlagsFull flagsDynamic False -- | Parses the dynamically set flags for GHC. This is the most general form of -- the dynamic flag parser that the other methods simply wrap. It allows -- saying which flags are valid flags and indicating if we are parsing -- arguments from the command line or from a file pragma. parseDynamicFlagsFull :: MonadIO m => [Flag (CmdLineP DynFlags)] -- ^ valid flags to match against -> Bool -- ^ are the arguments from the command line? -> DynFlags -- ^ current dynamic flags -> [Located String] -- ^ arguments to parse -> m (DynFlags, [Located String], [Located String]) parseDynamicFlagsFull activeFlags cmdline dflags0 args = do let ((leftover, errs, warns), dflags1) = runCmdLine (processArgs activeFlags args) dflags0 -- See Note [Handling errors when parsing commandline flags] unless (null errs) $ liftIO $ throwGhcExceptionIO $ errorsToGhcException . map (showPpr dflags0 . getLoc &&& unLoc) $ errs -- check for disabled flags in safe haskell let (dflags2, sh_warns) = safeFlagCheck cmdline dflags1 dflags3 = updateWays dflags2 theWays = ways dflags3 unless (allowed_combination theWays) $ liftIO $ throwGhcExceptionIO (CmdLineError ("combination not supported: " ++ intercalate "/" (map wayDesc theWays))) let chooseOutput | isJust (outputFile dflags3) -- Only iff user specified -o ... , not (isJust (dynOutputFile dflags3)) -- but not -dyno = return $ dflags3 { dynOutputFile = Just $ dynOut (fromJust $ outputFile dflags3) } | otherwise = return dflags3 where dynOut = flip addExtension (dynObjectSuf dflags3) . dropExtension dflags4 <- ifGeneratingDynamicToo dflags3 chooseOutput (return dflags3) let (dflags5, consistency_warnings) = makeDynFlagsConsistent dflags4 dflags6 <- case dllSplitFile dflags5 of Nothing -> return (dflags5 { dllSplit = Nothing }) Just f -> case dllSplit dflags5 of Just _ -> -- If dllSplit is out of date then it would have -- been set to Nothing. As it's a Just, it must be -- up-to-date. return dflags5 Nothing -> do xs <- liftIO $ readFile f let ss = map (Set.fromList . words) (lines xs) return $ dflags5 { dllSplit = Just ss } -- Set timer stats & heap size when (enableTimeStats dflags6) $ liftIO enableTimingStats case (ghcHeapSize dflags6) of Just x -> liftIO (setHeapSize x) _ -> return () liftIO $ setUnsafeGlobalDynFlags dflags6 return (dflags6, leftover, consistency_warnings ++ sh_warns ++ warns) updateWays :: DynFlags -> DynFlags updateWays dflags = let theWays = sort $ nub $ ways dflags f = if WayDyn `elem` theWays then unSetGeneralFlag' else setGeneralFlag' in f Opt_Static $ dflags { ways = theWays, buildTag = mkBuildTag (filter (not . wayRTSOnly) theWays), rtsBuildTag = mkBuildTag theWays } -- | Check (and potentially disable) any extensions that aren't allowed -- in safe mode. -- -- The bool is to indicate if we are parsing command line flags (false means -- file pragma). This allows us to generate better warnings. safeFlagCheck :: Bool -> DynFlags -> (DynFlags, [Located String]) safeFlagCheck _ dflags | safeLanguageOn dflags = (dflagsUnset, warns) where -- Handle illegal flags under safe language. (dflagsUnset, warns) = foldl check_method (dflags, []) unsafeFlags check_method (df, warns) (str,loc,test,fix) | test df = (fix df, warns ++ safeFailure (loc df) str) | otherwise = (df, warns) safeFailure loc str = [L loc $ str ++ " is not allowed in Safe Haskell; ignoring " ++ str] safeFlagCheck cmdl dflags = case (safeInferOn dflags) of True | safeFlags -> (dflags', warn) True -> (dflags' { safeInferred = False }, warn) False -> (dflags', warn) where -- dynflags and warn for when -fpackage-trust by itself with no safe -- haskell flag (dflags', warn) | safeHaskell dflags == Sf_None && not cmdl && packageTrustOn dflags = (gopt_unset dflags Opt_PackageTrust, pkgWarnMsg) | otherwise = (dflags, []) pkgWarnMsg = [L (pkgTrustOnLoc dflags') $ "-fpackage-trust ignored;" ++ " must be specified with a Safe Haskell flag"] safeFlags = all (\(_,_,t,_) -> not $ t dflags) unsafeFlagsForInfer -- Have we inferred Unsafe? -- See Note [HscMain . Safe Haskell Inference] {- ********************************************************************** %* * DynFlags specifications %* * %********************************************************************* -} -- | All dynamic flags option strings. These are the user facing strings for -- enabling and disabling options. allFlags :: [String] allFlags = [ '-':flagName flag | flag <- flagsAll , ok (flagOptKind flag) ] where ok (PrefixPred _ _) = False ok _ = True {- - Below we export user facing symbols for GHC dynamic flags for use with the - GHC API. -} -- All dynamic flags present in GHC. flagsAll :: [Flag (CmdLineP DynFlags)] flagsAll = package_flags ++ dynamic_flags -- All dynamic flags, minus package flags, present in GHC. flagsDynamic :: [Flag (CmdLineP DynFlags)] flagsDynamic = dynamic_flags -- ALl package flags present in GHC. flagsPackage :: [Flag (CmdLineP DynFlags)] flagsPackage = package_flags --------------- The main flags themselves ------------------ -- See Note [Updating flag description in the User's Guide] -- See Note [Supporting CLI completion] dynamic_flags :: [Flag (CmdLineP DynFlags)] dynamic_flags = [ defFlag "n" (NoArg (addWarn "The -n flag is deprecated and no longer has any effect")) , defFlag "cpp" (NoArg (setExtensionFlag Opt_Cpp)) , defFlag "F" (NoArg (setGeneralFlag Opt_Pp)) , defFlag "#include" (HasArg (\s -> do addCmdlineHCInclude s addWarn ("-#include and INCLUDE pragmas are " ++ "deprecated: They no longer have any effect"))) , defFlag "v" (OptIntSuffix setVerbosity) , defGhcFlag "j" (OptIntSuffix (\n -> upd (\d -> d {parMakeCount = n}))) , defFlag "sig-of" (sepArg setSigOf) -- RTS options ------------------------------------------------------------- , defFlag "H" (HasArg (\s -> upd (\d -> d { ghcHeapSize = Just $ fromIntegral (decodeSize s)}))) , defFlag "Rghc-timing" (NoArg (upd (\d -> d { enableTimeStats = True }))) ------- ways --------------------------------------------------------------- , defGhcFlag "prof" (NoArg (addWay WayProf)) , defGhcFlag "eventlog" (NoArg (addWay WayEventLog)) , defGhcFlag "parallel" (NoArg (addWay WayPar)) , defGhcFlag "smp" (NoArg (addWay WayThreaded >> deprecate "Use -threaded instead")) , defGhcFlag "debug" (NoArg (addWay WayDebug)) , defGhcFlag "ndp" (NoArg (addWay WayNDP)) , defGhcFlag "threaded" (NoArg (addWay WayThreaded)) , defGhcFlag "ticky" (NoArg (setGeneralFlag Opt_Ticky >> addWay WayDebug)) -- -ticky enables ticky-ticky code generation, and also implies -debug which -- is required to get the RTS ticky support. ----- Linker -------------------------------------------------------- , defGhcFlag "static" (NoArg removeWayDyn) , defGhcFlag "dynamic" (NoArg (addWay WayDyn)) , defGhcFlag "rdynamic" $ noArg $ #ifdef linux_HOST_OS addOptl "-rdynamic" #elif defined (mingw32_HOST_OS) addOptl "-export-all-symbols" #else -- ignored for compat w/ gcc: id #endif , defGhcFlag "relative-dynlib-paths" (NoArg (setGeneralFlag Opt_RelativeDynlibPaths)) ------- Specific phases -------------------------------------------- -- need to appear before -pgmL to be parsed as LLVM flags. , defFlag "pgmlo" (hasArg (\f -> alterSettings (\s -> s { sPgm_lo = (f,[])}))) , defFlag "pgmlc" (hasArg (\f -> alterSettings (\s -> s { sPgm_lc = (f,[])}))) , defFlag "pgmL" (hasArg (\f -> alterSettings (\s -> s { sPgm_L = f}))) , defFlag "pgmP" (hasArg setPgmP) , defFlag "pgmF" (hasArg (\f -> alterSettings (\s -> s { sPgm_F = f}))) , defFlag "pgmc" (hasArg (\f -> alterSettings (\s -> s { sPgm_c = (f,[])}))) , defFlag "pgms" (hasArg (\f -> alterSettings (\s -> s { sPgm_s = (f,[])}))) , defFlag "pgma" (hasArg (\f -> alterSettings (\s -> s { sPgm_a = (f,[])}))) , defFlag "pgml" (hasArg (\f -> alterSettings (\s -> s { sPgm_l = (f,[])}))) , defFlag "pgmdll" (hasArg (\f -> alterSettings (\s -> s { sPgm_dll = (f,[])}))) , defFlag "pgmwindres" (hasArg (\f -> alterSettings (\s -> s { sPgm_windres = f}))) , defFlag "pgmlibtool" (hasArg (\f -> alterSettings (\s -> s { sPgm_libtool = f}))) -- need to appear before -optl/-opta to be parsed as LLVM flags. , defFlag "optlo" (hasArg (\f -> alterSettings (\s -> s { sOpt_lo = f : sOpt_lo s}))) , defFlag "optlc" (hasArg (\f -> alterSettings (\s -> s { sOpt_lc = f : sOpt_lc s}))) , defFlag "optL" (hasArg (\f -> alterSettings (\s -> s { sOpt_L = f : sOpt_L s}))) , defFlag "optP" (hasArg addOptP) , defFlag "optF" (hasArg (\f -> alterSettings (\s -> s { sOpt_F = f : sOpt_F s}))) , defFlag "optc" (hasArg addOptc) , defFlag "opta" (hasArg (\f -> alterSettings (\s -> s { sOpt_a = f : sOpt_a s}))) , defFlag "optl" (hasArg addOptl) , defFlag "optwindres" (hasArg (\f -> alterSettings (\s -> s { sOpt_windres = f : sOpt_windres s}))) , defGhcFlag "split-objs" (NoArg (if can_split then setGeneralFlag Opt_SplitObjs else addWarn "ignoring -fsplit-objs")) -------- ghc -M ----------------------------------------------------- , defGhcFlag "dep-suffix" (hasArg addDepSuffix) , defGhcFlag "dep-makefile" (hasArg setDepMakefile) , defGhcFlag "include-pkg-deps" (noArg (setDepIncludePkgDeps True)) , defGhcFlag "exclude-module" (hasArg addDepExcludeMod) -------- Linking ---------------------------------------------------- , defGhcFlag "no-link" (noArg (\d -> d{ ghcLink=NoLink })) , defGhcFlag "shared" (noArg (\d -> d{ ghcLink=LinkDynLib })) , defGhcFlag "staticlib" (noArg (\d -> d{ ghcLink=LinkStaticLib })) , defGhcFlag "dynload" (hasArg parseDynLibLoaderMode) , defGhcFlag "dylib-install-name" (hasArg setDylibInstallName) -- -dll-split is an internal flag, used only during the GHC build , defHiddenFlag "dll-split" (hasArg (\f d -> d{ dllSplitFile = Just f, dllSplit = Nothing })) ------- Libraries --------------------------------------------------- , defFlag "L" (Prefix addLibraryPath) , defFlag "l" (hasArg (addLdInputs . Option . ("-l" ++))) ------- Frameworks -------------------------------------------------- -- -framework-path should really be -F ... , defFlag "framework-path" (HasArg addFrameworkPath) , defFlag "framework" (hasArg addCmdlineFramework) ------- Output Redirection ------------------------------------------ , defGhcFlag "odir" (hasArg setObjectDir) , defGhcFlag "o" (sepArg (setOutputFile . Just)) , defGhcFlag "dyno" (sepArg (setDynOutputFile . Just)) , defGhcFlag "ohi" (hasArg (setOutputHi . Just )) , defGhcFlag "osuf" (hasArg setObjectSuf) , defGhcFlag "dynosuf" (hasArg setDynObjectSuf) , defGhcFlag "hcsuf" (hasArg setHcSuf) , defGhcFlag "hisuf" (hasArg setHiSuf) , defGhcFlag "dynhisuf" (hasArg setDynHiSuf) , defGhcFlag "hidir" (hasArg setHiDir) , defGhcFlag "tmpdir" (hasArg setTmpDir) , defGhcFlag "stubdir" (hasArg setStubDir) , defGhcFlag "dumpdir" (hasArg setDumpDir) , defGhcFlag "outputdir" (hasArg setOutputDir) , defGhcFlag "ddump-file-prefix" (hasArg (setDumpPrefixForce . Just)) , defGhcFlag "dynamic-too" (NoArg (setGeneralFlag Opt_BuildDynamicToo)) ------- Keeping temporary files ------------------------------------- -- These can be singular (think ghc -c) or plural (think ghc --make) , defGhcFlag "keep-hc-file" (NoArg (setGeneralFlag Opt_KeepHcFiles)) , defGhcFlag "keep-hc-files" (NoArg (setGeneralFlag Opt_KeepHcFiles)) , defGhcFlag "keep-s-file" (NoArg (setGeneralFlag Opt_KeepSFiles)) , defGhcFlag "keep-s-files" (NoArg (setGeneralFlag Opt_KeepSFiles)) , defGhcFlag "keep-llvm-file" (NoArg (do setObjTarget HscLlvm setGeneralFlag Opt_KeepLlvmFiles)) , defGhcFlag "keep-llvm-files" (NoArg (do setObjTarget HscLlvm setGeneralFlag Opt_KeepLlvmFiles)) -- This only makes sense as plural , defGhcFlag "keep-tmp-files" (NoArg (setGeneralFlag Opt_KeepTmpFiles)) ------- Miscellaneous ---------------------------------------------- , defGhcFlag "no-auto-link-packages" (NoArg (unSetGeneralFlag Opt_AutoLinkPackages)) , defGhcFlag "no-hs-main" (NoArg (setGeneralFlag Opt_NoHsMain)) , defGhcFlag "with-rtsopts" (HasArg setRtsOpts) , defGhcFlag "rtsopts" (NoArg (setRtsOptsEnabled RtsOptsAll)) , defGhcFlag "rtsopts=all" (NoArg (setRtsOptsEnabled RtsOptsAll)) , defGhcFlag "rtsopts=some" (NoArg (setRtsOptsEnabled RtsOptsSafeOnly)) , defGhcFlag "rtsopts=none" (NoArg (setRtsOptsEnabled RtsOptsNone)) , defGhcFlag "no-rtsopts" (NoArg (setRtsOptsEnabled RtsOptsNone)) , defGhcFlag "main-is" (SepArg setMainIs) , defGhcFlag "haddock" (NoArg (setGeneralFlag Opt_Haddock)) , defGhcFlag "haddock-opts" (hasArg addHaddockOpts) , defGhcFlag "hpcdir" (SepArg setOptHpcDir) , defGhciFlag "ghci-script" (hasArg addGhciScript) , defGhciFlag "interactive-print" (hasArg setInteractivePrint) , defGhcFlag "ticky-allocd" (NoArg (setGeneralFlag Opt_Ticky_Allocd)) , defGhcFlag "ticky-LNE" (NoArg (setGeneralFlag Opt_Ticky_LNE)) , defGhcFlag "ticky-dyn-thunk" (NoArg (setGeneralFlag Opt_Ticky_Dyn_Thunk)) ------- recompilation checker -------------------------------------- , defGhcFlag "recomp" (NoArg (do unSetGeneralFlag Opt_ForceRecomp deprecate "Use -fno-force-recomp instead")) , defGhcFlag "no-recomp" (NoArg (do setGeneralFlag Opt_ForceRecomp deprecate "Use -fforce-recomp instead")) ------ HsCpp opts --------------------------------------------------- , defFlag "D" (AnySuffix (upd . addOptP)) , defFlag "U" (AnySuffix (upd . addOptP)) ------- Include/Import Paths ---------------------------------------- , defFlag "I" (Prefix addIncludePath) , defFlag "i" (OptPrefix addImportPath) ------ Output style options ----------------------------------------- , defFlag "dppr-user-length" (intSuffix (\n d -> d{ pprUserLength = n })) , defFlag "dppr-cols" (intSuffix (\n d -> d{ pprCols = n })) , defGhcFlag "dtrace-level" (intSuffix (\n d -> d{ traceLevel = n })) -- Suppress all that is suppressable in core dumps. -- Except for uniques, as some simplifier phases introduce new varibles that -- have otherwise identical names. , defGhcFlag "dsuppress-all" (NoArg $ do setGeneralFlag Opt_SuppressCoercions setGeneralFlag Opt_SuppressVarKinds setGeneralFlag Opt_SuppressModulePrefixes setGeneralFlag Opt_SuppressTypeApplications setGeneralFlag Opt_SuppressIdInfo setGeneralFlag Opt_SuppressTypeSignatures) ------ Debugging ---------------------------------------------------- , defGhcFlag "dstg-stats" (NoArg (setGeneralFlag Opt_StgStats)) , defGhcFlag "ddump-cmm" (setDumpFlag Opt_D_dump_cmm) , defGhcFlag "ddump-cmm-raw" (setDumpFlag Opt_D_dump_cmm_raw) , defGhcFlag "ddump-cmm-cfg" (setDumpFlag Opt_D_dump_cmm_cfg) , defGhcFlag "ddump-cmm-cbe" (setDumpFlag Opt_D_dump_cmm_cbe) , defGhcFlag "ddump-cmm-proc" (setDumpFlag Opt_D_dump_cmm_proc) , defGhcFlag "ddump-cmm-sink" (setDumpFlag Opt_D_dump_cmm_sink) , defGhcFlag "ddump-cmm-sp" (setDumpFlag Opt_D_dump_cmm_sp) , defGhcFlag "ddump-cmm-procmap" (setDumpFlag Opt_D_dump_cmm_procmap) , defGhcFlag "ddump-cmm-split" (setDumpFlag Opt_D_dump_cmm_split) , defGhcFlag "ddump-cmm-info" (setDumpFlag Opt_D_dump_cmm_info) , defGhcFlag "ddump-cmm-cps" (setDumpFlag Opt_D_dump_cmm_cps) , defGhcFlag "ddump-core-stats" (setDumpFlag Opt_D_dump_core_stats) , defGhcFlag "ddump-asm" (setDumpFlag Opt_D_dump_asm) , defGhcFlag "ddump-asm-native" (setDumpFlag Opt_D_dump_asm_native) , defGhcFlag "ddump-asm-liveness" (setDumpFlag Opt_D_dump_asm_liveness) , defGhcFlag "ddump-asm-regalloc" (setDumpFlag Opt_D_dump_asm_regalloc) , defGhcFlag "ddump-asm-conflicts" (setDumpFlag Opt_D_dump_asm_conflicts) , defGhcFlag "ddump-asm-regalloc-stages" (setDumpFlag Opt_D_dump_asm_regalloc_stages) , defGhcFlag "ddump-asm-stats" (setDumpFlag Opt_D_dump_asm_stats) , defGhcFlag "ddump-asm-expanded" (setDumpFlag Opt_D_dump_asm_expanded) , defGhcFlag "ddump-llvm" (NoArg (do setObjTarget HscLlvm setDumpFlag' Opt_D_dump_llvm)) , defGhcFlag "ddump-deriv" (setDumpFlag Opt_D_dump_deriv) , defGhcFlag "ddump-ds" (setDumpFlag Opt_D_dump_ds) , defGhcFlag "ddump-foreign" (setDumpFlag Opt_D_dump_foreign) , defGhcFlag "ddump-inlinings" (setDumpFlag Opt_D_dump_inlinings) , defGhcFlag "ddump-rule-firings" (setDumpFlag Opt_D_dump_rule_firings) , defGhcFlag "ddump-rule-rewrites" (setDumpFlag Opt_D_dump_rule_rewrites) , defGhcFlag "ddump-simpl-trace" (setDumpFlag Opt_D_dump_simpl_trace) , defGhcFlag "ddump-occur-anal" (setDumpFlag Opt_D_dump_occur_anal) , defGhcFlag "ddump-parsed" (setDumpFlag Opt_D_dump_parsed) , defGhcFlag "ddump-rn" (setDumpFlag Opt_D_dump_rn) , defGhcFlag "ddump-simpl" (setDumpFlag Opt_D_dump_simpl) , defGhcFlag "ddump-simpl-iterations" (setDumpFlag Opt_D_dump_simpl_iterations) , defGhcFlag "ddump-spec" (setDumpFlag Opt_D_dump_spec) , defGhcFlag "ddump-prep" (setDumpFlag Opt_D_dump_prep) , defGhcFlag "ddump-stg" (setDumpFlag Opt_D_dump_stg) , defGhcFlag "ddump-call-arity" (setDumpFlag Opt_D_dump_call_arity) , defGhcFlag "ddump-stranal" (setDumpFlag Opt_D_dump_stranal) , defGhcFlag "ddump-strsigs" (setDumpFlag Opt_D_dump_strsigs) , defGhcFlag "ddump-tc" (setDumpFlag Opt_D_dump_tc) , defGhcFlag "ddump-types" (setDumpFlag Opt_D_dump_types) , defGhcFlag "ddump-rules" (setDumpFlag Opt_D_dump_rules) , defGhcFlag "ddump-cse" (setDumpFlag Opt_D_dump_cse) , defGhcFlag "ddump-worker-wrapper" (setDumpFlag Opt_D_dump_worker_wrapper) , defGhcFlag "ddump-rn-trace" (setDumpFlag Opt_D_dump_rn_trace) , defGhcFlag "ddump-if-trace" (setDumpFlag Opt_D_dump_if_trace) , defGhcFlag "ddump-cs-trace" (setDumpFlag Opt_D_dump_cs_trace) , defGhcFlag "ddump-tc-trace" (NoArg (do setDumpFlag' Opt_D_dump_tc_trace setDumpFlag' Opt_D_dump_cs_trace)) , defGhcFlag "ddump-vt-trace" (setDumpFlag Opt_D_dump_vt_trace) , defGhcFlag "ddump-splices" (setDumpFlag Opt_D_dump_splices) , defGhcFlag "dth-dec-file" (setDumpFlag Opt_D_th_dec_file) , defGhcFlag "ddump-rn-stats" (setDumpFlag Opt_D_dump_rn_stats) , defGhcFlag "ddump-opt-cmm" (setDumpFlag Opt_D_dump_opt_cmm) , defGhcFlag "ddump-simpl-stats" (setDumpFlag Opt_D_dump_simpl_stats) , defGhcFlag "ddump-bcos" (setDumpFlag Opt_D_dump_BCOs) , defGhcFlag "dsource-stats" (setDumpFlag Opt_D_source_stats) , defGhcFlag "dverbose-core2core" (NoArg (do setVerbosity (Just 2) setVerboseCore2Core)) , defGhcFlag "dverbose-stg2stg" (setDumpFlag Opt_D_verbose_stg2stg) , defGhcFlag "ddump-hi" (setDumpFlag Opt_D_dump_hi) , defGhcFlag "ddump-minimal-imports" (NoArg (setGeneralFlag Opt_D_dump_minimal_imports)) , defGhcFlag "ddump-vect" (setDumpFlag Opt_D_dump_vect) , defGhcFlag "ddump-hpc" (setDumpFlag Opt_D_dump_ticked) -- back compat , defGhcFlag "ddump-ticked" (setDumpFlag Opt_D_dump_ticked) , defGhcFlag "ddump-mod-cycles" (setDumpFlag Opt_D_dump_mod_cycles) , defGhcFlag "ddump-mod-map" (setDumpFlag Opt_D_dump_mod_map) , defGhcFlag "ddump-view-pattern-commoning" (setDumpFlag Opt_D_dump_view_pattern_commoning) , defGhcFlag "ddump-to-file" (NoArg (setGeneralFlag Opt_DumpToFile)) , defGhcFlag "ddump-hi-diffs" (setDumpFlag Opt_D_dump_hi_diffs) , defGhcFlag "ddump-rtti" (setDumpFlag Opt_D_dump_rtti) , defGhcFlag "dcore-lint" (NoArg (setGeneralFlag Opt_DoCoreLinting)) , defGhcFlag "dstg-lint" (NoArg (setGeneralFlag Opt_DoStgLinting)) , defGhcFlag "dcmm-lint" (NoArg (setGeneralFlag Opt_DoCmmLinting)) , defGhcFlag "dasm-lint" (NoArg (setGeneralFlag Opt_DoAsmLinting)) , defGhcFlag "dannot-lint" (NoArg (setGeneralFlag Opt_DoAnnotationLinting)) , defGhcFlag "dshow-passes" (NoArg (do forceRecompile setVerbosity $ Just 2)) , defGhcFlag "dfaststring-stats" (NoArg (setGeneralFlag Opt_D_faststring_stats)) , defGhcFlag "dno-llvm-mangler" (NoArg (setGeneralFlag Opt_NoLlvmMangler)) -- hidden flag , defGhcFlag "ddump-debug" (setDumpFlag Opt_D_dump_debug) ------ Machine dependant (-m<blah>) stuff --------------------------- , defGhcFlag "msse" (noArg (\d -> d{ sseVersion = Just SSE1 })) , defGhcFlag "msse2" (noArg (\d -> d{ sseVersion = Just SSE2 })) , defGhcFlag "msse3" (noArg (\d -> d{ sseVersion = Just SSE3 })) , defGhcFlag "msse4" (noArg (\d -> d{ sseVersion = Just SSE4 })) , defGhcFlag "msse4.2" (noArg (\d -> d{ sseVersion = Just SSE42 })) , defGhcFlag "mavx" (noArg (\d -> d{ avx = True })) , defGhcFlag "mavx2" (noArg (\d -> d{ avx2 = True })) , defGhcFlag "mavx512cd" (noArg (\d -> d{ avx512cd = True })) , defGhcFlag "mavx512er" (noArg (\d -> d{ avx512er = True })) , defGhcFlag "mavx512f" (noArg (\d -> d{ avx512f = True })) , defGhcFlag "mavx512pf" (noArg (\d -> d{ avx512pf = True })) ------ Warning opts ------------------------------------------------- , defFlag "W" (NoArg (mapM_ setWarningFlag minusWOpts)) , defFlag "Werror" (NoArg (setGeneralFlag Opt_WarnIsError)) , defFlag "Wwarn" (NoArg (unSetGeneralFlag Opt_WarnIsError)) , defFlag "Wall" (NoArg (mapM_ setWarningFlag minusWallOpts)) , defFlag "Wnot" (NoArg (do upd (\dfs -> dfs {warningFlags = IntSet.empty}) deprecate "Use -w instead")) , defFlag "w" (NoArg (upd (\dfs -> dfs {warningFlags = IntSet.empty}))) ------ Plugin flags ------------------------------------------------ , defGhcFlag "fplugin-opt" (hasArg addPluginModuleNameOption) , defGhcFlag "fplugin" (hasArg addPluginModuleName) ------ Optimisation flags ------------------------------------------ , defGhcFlag "O" (noArgM (setOptLevel 1)) , defGhcFlag "Onot" (noArgM (\dflags -> do deprecate "Use -O0 instead" setOptLevel 0 dflags)) , defGhcFlag "Odph" (noArgM setDPHOpt) , defGhcFlag "O" (optIntSuffixM (\mb_n -> setOptLevel (mb_n `orElse` 1))) -- If the number is missing, use 1 , defFlag "fmax-relevant-binds" (intSuffix (\n d -> d{ maxRelevantBinds = Just n })) , defFlag "fno-max-relevant-binds" (noArg (\d -> d{ maxRelevantBinds = Nothing })) , defFlag "fsimplifier-phases" (intSuffix (\n d -> d{ simplPhases = n })) , defFlag "fmax-simplifier-iterations" (intSuffix (\n d -> d{ maxSimplIterations = n })) , defFlag "fsimpl-tick-factor" (intSuffix (\n d -> d{ simplTickFactor = n })) , defFlag "fspec-constr-threshold" (intSuffix (\n d -> d{ specConstrThreshold = Just n })) , defFlag "fno-spec-constr-threshold" (noArg (\d -> d{ specConstrThreshold = Nothing })) , defFlag "fspec-constr-count" (intSuffix (\n d -> d{ specConstrCount = Just n })) , defFlag "fno-spec-constr-count" (noArg (\d -> d{ specConstrCount = Nothing })) , defFlag "fspec-constr-recursive" (intSuffix (\n d -> d{ specConstrRecursive = n })) , defFlag "fliberate-case-threshold" (intSuffix (\n d -> d{ liberateCaseThreshold = Just n })) , defFlag "fno-liberate-case-threshold" (noArg (\d -> d{ liberateCaseThreshold = Nothing })) , defFlag "frule-check" (sepArg (\s d -> d{ ruleCheck = Just s })) , defFlag "fcontext-stack" (intSuffix (\n d -> d{ ctxtStkDepth = n })) , defFlag "ftype-function-depth" (intSuffix (\n d -> d{ tyFunStkDepth = n })) , defFlag "fstrictness-before" (intSuffix (\n d -> d{ strictnessBefore = n : strictnessBefore d })) , defFlag "ffloat-lam-args" (intSuffix (\n d -> d{ floatLamArgs = Just n })) , defFlag "ffloat-all-lams" (noArg (\d -> d{ floatLamArgs = Nothing })) , defFlag "fhistory-size" (intSuffix (\n d -> d{ historySize = n })) , defFlag "funfolding-creation-threshold" (intSuffix (\n d -> d {ufCreationThreshold = n})) , defFlag "funfolding-use-threshold" (intSuffix (\n d -> d {ufUseThreshold = n})) , defFlag "funfolding-fun-discount" (intSuffix (\n d -> d {ufFunAppDiscount = n})) , defFlag "funfolding-dict-discount" (intSuffix (\n d -> d {ufDictDiscount = n})) , defFlag "funfolding-keeness-factor" (floatSuffix (\n d -> d {ufKeenessFactor = n})) , defFlag "fmax-worker-args" (intSuffix (\n d -> d {maxWorkerArgs = n})) , defGhciFlag "fghci-hist-size" (intSuffix (\n d -> d {ghciHistSize = n})) , defGhcFlag "fmax-inline-alloc-size" (intSuffix (\n d -> d{ maxInlineAllocSize = n })) , defGhcFlag "fmax-inline-memcpy-insns" (intSuffix (\n d -> d{ maxInlineMemcpyInsns = n })) , defGhcFlag "fmax-inline-memset-insns" (intSuffix (\n d -> d{ maxInlineMemsetInsns = n })) ------ Profiling ---------------------------------------------------- -- OLD profiling flags , defGhcFlag "auto-all" (noArg (\d -> d { profAuto = ProfAutoAll } )) , defGhcFlag "no-auto-all" (noArg (\d -> d { profAuto = NoProfAuto } )) , defGhcFlag "auto" (noArg (\d -> d { profAuto = ProfAutoExports } )) , defGhcFlag "no-auto" (noArg (\d -> d { profAuto = NoProfAuto } )) , defGhcFlag "caf-all" (NoArg (setGeneralFlag Opt_AutoSccsOnIndividualCafs)) , defGhcFlag "no-caf-all" (NoArg (unSetGeneralFlag Opt_AutoSccsOnIndividualCafs)) -- NEW profiling flags , defGhcFlag "fprof-auto" (noArg (\d -> d { profAuto = ProfAutoAll } )) , defGhcFlag "fprof-auto-top" (noArg (\d -> d { profAuto = ProfAutoTop } )) , defGhcFlag "fprof-auto-exported" (noArg (\d -> d { profAuto = ProfAutoExports } )) , defGhcFlag "fprof-auto-calls" (noArg (\d -> d { profAuto = ProfAutoCalls } )) , defGhcFlag "fno-prof-auto" (noArg (\d -> d { profAuto = NoProfAuto } )) ------ Compiler flags ----------------------------------------------- , defGhcFlag "fasm" (NoArg (setObjTarget HscAsm)) , defGhcFlag "fvia-c" (NoArg (addWarn $ "The -fvia-c flag does nothing; " ++ "it will be removed in a future GHC release")) , defGhcFlag "fvia-C" (NoArg (addWarn $ "The -fvia-C flag does nothing; " ++ "it will be removed in a future GHC release")) , defGhcFlag "fllvm" (NoArg (setObjTarget HscLlvm)) , defFlag "fno-code" (NoArg (do upd $ \d -> d{ ghcLink=NoLink } setTarget HscNothing)) , defFlag "fbyte-code" (NoArg (setTarget HscInterpreted)) , defFlag "fobject-code" (NoArg (setTargetWithPlatform defaultHscTarget)) , defFlag "fglasgow-exts" (NoArg (do enableGlasgowExts deprecate "Use individual extensions instead")) , defFlag "fno-glasgow-exts" (NoArg (do disableGlasgowExts deprecate "Use individual extensions instead")) , defFlag "fwarn-unused-binds" (NoArg enableUnusedBinds) , defFlag "fno-warn-unused-binds" (NoArg disableUnusedBinds) ------ Safe Haskell flags ------------------------------------------- , defFlag "fpackage-trust" (NoArg setPackageTrust) , defFlag "fno-safe-infer" (noArg (\d -> d { safeInfer = False } )) , defGhcFlag "fPIC" (NoArg (setGeneralFlag Opt_PIC)) , defGhcFlag "fno-PIC" (NoArg (unSetGeneralFlag Opt_PIC)) ------ Debugging flags ---------------------------------------------- , defGhcFlag "g" (NoArg (setGeneralFlag Opt_Debug)) ] ++ map (mkFlag turnOn "" setGeneralFlag ) negatableFlags ++ map (mkFlag turnOff "no-" unSetGeneralFlag) negatableFlags ++ map (mkFlag turnOn "d" setGeneralFlag ) dFlags ++ map (mkFlag turnOff "dno-" unSetGeneralFlag) dFlags ++ map (mkFlag turnOn "f" setGeneralFlag ) fFlags ++ map (mkFlag turnOff "fno-" unSetGeneralFlag) fFlags ++ map (mkFlag turnOn "f" setWarningFlag ) fWarningFlags ++ map (mkFlag turnOff "fno-" unSetWarningFlag) fWarningFlags ++ map (mkFlag turnOn "f" setExtensionFlag ) fLangFlags ++ map (mkFlag turnOff "fno-" unSetExtensionFlag) fLangFlags ++ map (mkFlag turnOn "X" setExtensionFlag ) xFlags ++ map (mkFlag turnOff "XNo" unSetExtensionFlag) xFlags ++ map (mkFlag turnOn "X" setLanguage) languageFlags ++ map (mkFlag turnOn "X" setSafeHaskell) safeHaskellFlags ++ [ defFlag "XGenerics" (NoArg (deprecate $ "it does nothing; look into -XDefaultSignatures " ++ "and -XDeriveGeneric for generic programming support.")) , defFlag "XNoGenerics" (NoArg (deprecate $ "it does nothing; look into -XDefaultSignatures and " ++ "-XDeriveGeneric for generic programming support.")) ] -- See Note [Supporting CLI completion] package_flags :: [Flag (CmdLineP DynFlags)] package_flags = [ ------- Packages ---------------------------------------------------- defFlag "package-db" (HasArg (addPkgConfRef . PkgConfFile)) , defFlag "clear-package-db" (NoArg clearPkgConf) , defFlag "no-global-package-db" (NoArg removeGlobalPkgConf) , defFlag "no-user-package-db" (NoArg removeUserPkgConf) , defFlag "global-package-db" (NoArg (addPkgConfRef GlobalPkgConf)) , defFlag "user-package-db" (NoArg (addPkgConfRef UserPkgConf)) -- backwards compat with GHC<=7.4 : , defFlag "package-conf" (HasArg $ \path -> do addPkgConfRef (PkgConfFile path) deprecate "Use -package-db instead") , defFlag "no-user-package-conf" (NoArg $ do removeUserPkgConf deprecate "Use -no-user-package-db instead") , defGhcFlag "package-name" (HasArg $ \name -> do upd (setPackageKey name) deprecate "Use -this-package-key instead") , defGhcFlag "this-package-key" (hasArg setPackageKey) , defFlag "package-id" (HasArg exposePackageId) , defFlag "package" (HasArg exposePackage) , defFlag "package-key" (HasArg exposePackageKey) , defFlag "hide-package" (HasArg hidePackage) , defFlag "hide-all-packages" (NoArg (setGeneralFlag Opt_HideAllPackages)) , defFlag "package-env" (HasArg setPackageEnv) , defFlag "ignore-package" (HasArg ignorePackage) , defFlag "syslib" (HasArg (\s -> do exposePackage s deprecate "Use -package instead")) , defFlag "distrust-all-packages" (NoArg (setGeneralFlag Opt_DistrustAllPackages)) , defFlag "trust" (HasArg trustPackage) , defFlag "distrust" (HasArg distrustPackage) ] where setPackageEnv env = upd $ \s -> s { packageEnv = Just env } -- | Make a list of flags for shell completion. -- Filter all available flags into two groups, for interactive GHC vs all other. flagsForCompletion :: Bool -> [String] flagsForCompletion isInteractive = [ '-':flagName flag | flag <- flagsAll , modeFilter (flagGhcMode flag) ] where modeFilter AllModes = True modeFilter OnlyGhci = isInteractive modeFilter OnlyGhc = not isInteractive modeFilter HiddenFlag = False type TurnOnFlag = Bool -- True <=> we are turning the flag on -- False <=> we are turning the flag off turnOn :: TurnOnFlag; turnOn = True turnOff :: TurnOnFlag; turnOff = False data FlagSpec flag = FlagSpec { flagSpecName :: String -- ^ Flag in string form , flagSpecFlag :: flag -- ^ Flag in internal form , flagSpecAction :: (TurnOnFlag -> DynP ()) -- ^ Extra action to run when the flag is found -- Typically, emit a warning or error , flagSpecGhcMode :: GhcFlagMode -- ^ In which ghc mode the flag has effect } -- | Define a new flag. flagSpec :: String -> flag -> FlagSpec flag flagSpec name flag = flagSpec' name flag nop -- | Define a new flag with an effect. flagSpec' :: String -> flag -> (TurnOnFlag -> DynP ()) -> FlagSpec flag flagSpec' name flag act = FlagSpec name flag act AllModes -- | Define a new flag for GHCi. flagGhciSpec :: String -> flag -> FlagSpec flag flagGhciSpec name flag = flagGhciSpec' name flag nop -- | Define a new flag for GHCi with an effect. flagGhciSpec' :: String -> flag -> (TurnOnFlag -> DynP ()) -> FlagSpec flag flagGhciSpec' name flag act = FlagSpec name flag act OnlyGhci -- | Define a new flag invisible to CLI completion. flagHiddenSpec :: String -> flag -> FlagSpec flag flagHiddenSpec name flag = flagHiddenSpec' name flag nop -- | Define a new flag invisible to CLI completion with an effect. flagHiddenSpec' :: String -> flag -> (TurnOnFlag -> DynP ()) -> FlagSpec flag flagHiddenSpec' name flag act = FlagSpec name flag act HiddenFlag mkFlag :: TurnOnFlag -- ^ True <=> it should be turned on -> String -- ^ The flag prefix -> (flag -> DynP ()) -- ^ What to do when the flag is found -> FlagSpec flag -- ^ Specification of this particular flag -> Flag (CmdLineP DynFlags) mkFlag turn_on flagPrefix f (FlagSpec name flag extra_action mode) = Flag (flagPrefix ++ name) (NoArg (f flag >> extra_action turn_on)) mode deprecatedForExtension :: String -> TurnOnFlag -> DynP () deprecatedForExtension lang turn_on = deprecate ("use -X" ++ flag ++ " or pragma {-# LANGUAGE " ++ flag ++ " #-} instead") where flag | turn_on = lang | otherwise = "No"++lang useInstead :: String -> TurnOnFlag -> DynP () useInstead flag turn_on = deprecate ("Use -f" ++ no ++ flag ++ " instead") where no = if turn_on then "" else "no-" nop :: TurnOnFlag -> DynP () nop _ = return () -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@ fWarningFlags :: [FlagSpec WarningFlag] fWarningFlags = [ -- See Note [Updating flag description in the User's Guide] -- See Note [Supporting CLI completion] -- Please keep the list of flags below sorted alphabetically flagSpec "warn-alternative-layout-rule-transitional" Opt_WarnAlternativeLayoutRuleTransitional, flagSpec' "warn-amp" Opt_WarnAMP (\_ -> deprecate "it has no effect, and will be removed in GHC 7.12"), flagSpec "warn-auto-orphans" Opt_WarnAutoOrphans, flagSpec "warn-deprecations" Opt_WarnWarningsDeprecations, flagSpec "warn-deprecated-flags" Opt_WarnDeprecatedFlags, flagSpec "warn-deriving-typeable" Opt_WarnDerivingTypeable, flagSpec "warn-dodgy-exports" Opt_WarnDodgyExports, flagSpec "warn-dodgy-foreign-imports" Opt_WarnDodgyForeignImports, flagSpec "warn-dodgy-imports" Opt_WarnDodgyImports, flagSpec "warn-empty-enumerations" Opt_WarnEmptyEnumerations, flagSpec "warn-context-quantification" Opt_WarnContextQuantification, flagSpec' "warn-duplicate-constraints" Opt_WarnDuplicateConstraints (\_ -> deprecate "it is subsumed by -fwarn-redundant-constraints"), flagSpec "warn-redundant-constraints" Opt_WarnRedundantConstraints, flagSpec "warn-duplicate-exports" Opt_WarnDuplicateExports, flagSpec "warn-hi-shadowing" Opt_WarnHiShadows, flagSpec "warn-implicit-prelude" Opt_WarnImplicitPrelude, flagSpec "warn-incomplete-patterns" Opt_WarnIncompletePatterns, flagSpec "warn-incomplete-record-updates" Opt_WarnIncompletePatternsRecUpd, flagSpec "warn-incomplete-uni-patterns" Opt_WarnIncompleteUniPatterns, flagSpec "warn-inline-rule-shadowing" Opt_WarnInlineRuleShadowing, flagSpec "warn-identities" Opt_WarnIdentities, flagSpec "warn-missing-fields" Opt_WarnMissingFields, flagSpec "warn-missing-import-lists" Opt_WarnMissingImportList, flagSpec "warn-missing-local-sigs" Opt_WarnMissingLocalSigs, flagSpec "warn-missing-methods" Opt_WarnMissingMethods, flagSpec "warn-missing-signatures" Opt_WarnMissingSigs, flagSpec "warn-missing-exported-sigs" Opt_WarnMissingExportedSigs, flagSpec "warn-monomorphism-restriction" Opt_WarnMonomorphism, flagSpec "warn-name-shadowing" Opt_WarnNameShadowing, flagSpec "warn-orphans" Opt_WarnOrphans, flagSpec "warn-overflowed-literals" Opt_WarnOverflowedLiterals, flagSpec "warn-overlapping-patterns" Opt_WarnOverlappingPatterns, flagSpec "warn-pointless-pragmas" Opt_WarnPointlessPragmas, flagSpec' "warn-safe" Opt_WarnSafe setWarnSafe, flagSpec "warn-trustworthy-safe" Opt_WarnTrustworthySafe, flagSpec "warn-tabs" Opt_WarnTabs, flagSpec "warn-type-defaults" Opt_WarnTypeDefaults, flagSpec "warn-typed-holes" Opt_WarnTypedHoles, flagSpec "warn-partial-type-signatures" Opt_WarnPartialTypeSignatures, flagSpec "warn-unrecognised-pragmas" Opt_WarnUnrecognisedPragmas, flagSpec' "warn-unsafe" Opt_WarnUnsafe setWarnUnsafe, flagSpec "warn-unsupported-calling-conventions" Opt_WarnUnsupportedCallingConventions, flagSpec "warn-unsupported-llvm-version" Opt_WarnUnsupportedLlvmVersion, flagSpec "warn-unticked-promoted-constructors" Opt_WarnUntickedPromotedConstructors, flagSpec "warn-unused-do-bind" Opt_WarnUnusedDoBind, flagSpec "warn-unused-imports" Opt_WarnUnusedImports, flagSpec "warn-unused-local-binds" Opt_WarnUnusedLocalBinds, flagSpec "warn-unused-matches" Opt_WarnUnusedMatches, flagSpec "warn-unused-pattern-binds" Opt_WarnUnusedPatternBinds, flagSpec "warn-unused-top-binds" Opt_WarnUnusedTopBinds, flagSpec "warn-warnings-deprecations" Opt_WarnWarningsDeprecations, flagSpec "warn-wrong-do-bind" Opt_WarnWrongDoBind] -- | These @-\<blah\>@ flags can all be reversed with @-no-\<blah\>@ negatableFlags :: [FlagSpec GeneralFlag] negatableFlags = [ flagGhciSpec "ignore-dot-ghci" Opt_IgnoreDotGhci ] -- | These @-d\<blah\>@ flags can all be reversed with @-dno-\<blah\>@ dFlags :: [FlagSpec GeneralFlag] dFlags = [ -- See Note [Updating flag description in the User's Guide] -- See Note [Supporting CLI completion] -- Please keep the list of flags below sorted alphabetically flagSpec "ppr-case-as-let" Opt_PprCaseAsLet, flagSpec "ppr-ticks" Opt_PprShowTicks, flagSpec "suppress-coercions" Opt_SuppressCoercions, flagSpec "suppress-idinfo" Opt_SuppressIdInfo, flagSpec "suppress-module-prefixes" Opt_SuppressModulePrefixes, flagSpec "suppress-type-applications" Opt_SuppressTypeApplications, flagSpec "suppress-type-signatures" Opt_SuppressTypeSignatures, flagSpec "suppress-uniques" Opt_SuppressUniques, flagSpec "suppress-var-kinds" Opt_SuppressVarKinds] -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@ fFlags :: [FlagSpec GeneralFlag] fFlags = [ -- See Note [Updating flag description in the User's Guide] -- See Note [Supporting CLI completion] -- Please keep the list of flags below sorted alphabetically flagGhciSpec "break-on-error" Opt_BreakOnError, flagGhciSpec "break-on-exception" Opt_BreakOnException, flagSpec "building-cabal-package" Opt_BuildingCabalPackage, flagSpec "call-arity" Opt_CallArity, flagSpec "case-merge" Opt_CaseMerge, flagSpec "cmm-elim-common-blocks" Opt_CmmElimCommonBlocks, flagSpec "cmm-sink" Opt_CmmSink, flagSpec "cse" Opt_CSE, flagSpec "defer-type-errors" Opt_DeferTypeErrors, flagSpec "defer-typed-holes" Opt_DeferTypedHoles, flagSpec "dicts-cheap" Opt_DictsCheap, flagSpec "dicts-strict" Opt_DictsStrict, flagSpec "dmd-tx-dict-sel" Opt_DmdTxDictSel, flagSpec "do-eta-reduction" Opt_DoEtaReduction, flagSpec "do-lambda-eta-expansion" Opt_DoLambdaEtaExpansion, flagSpec "eager-blackholing" Opt_EagerBlackHoling, flagSpec "embed-manifest" Opt_EmbedManifest, flagSpec "enable-rewrite-rules" Opt_EnableRewriteRules, flagSpec "error-spans" Opt_ErrorSpans, flagSpec "excess-precision" Opt_ExcessPrecision, flagSpec "expose-all-unfoldings" Opt_ExposeAllUnfoldings, flagSpec "flat-cache" Opt_FlatCache, flagSpec "float-in" Opt_FloatIn, flagSpec "force-recomp" Opt_ForceRecomp, flagSpec "full-laziness" Opt_FullLaziness, flagSpec "fun-to-thunk" Opt_FunToThunk, flagSpec "gen-manifest" Opt_GenManifest, flagSpec "ghci-history" Opt_GhciHistory, flagSpec "ghci-sandbox" Opt_GhciSandbox, flagSpec "helpful-errors" Opt_HelpfulErrors, flagSpec "hpc" Opt_Hpc, flagSpec "ignore-asserts" Opt_IgnoreAsserts, flagSpec "ignore-interface-pragmas" Opt_IgnoreInterfacePragmas, flagGhciSpec "implicit-import-qualified" Opt_ImplicitImportQualified, flagSpec "irrefutable-tuples" Opt_IrrefutableTuples, flagSpec "kill-absence" Opt_KillAbsence, flagSpec "kill-one-shot" Opt_KillOneShot, flagSpec "late-dmd-anal" Opt_LateDmdAnal, flagSpec "liberate-case" Opt_LiberateCase, flagHiddenSpec "llvm-pass-vectors-in-regs" Opt_LlvmPassVectorsInRegisters, flagHiddenSpec "llvm-tbaa" Opt_LlvmTBAA, flagSpec "loopification" Opt_Loopification, flagSpec "omit-interface-pragmas" Opt_OmitInterfacePragmas, flagSpec "omit-yields" Opt_OmitYields, flagSpec "pedantic-bottoms" Opt_PedanticBottoms, flagSpec "pre-inlining" Opt_SimplPreInlining, flagGhciSpec "print-bind-contents" Opt_PrintBindContents, flagGhciSpec "print-bind-result" Opt_PrintBindResult, flagGhciSpec "print-evld-with-show" Opt_PrintEvldWithShow, flagSpec "print-explicit-foralls" Opt_PrintExplicitForalls, flagSpec "print-explicit-kinds" Opt_PrintExplicitKinds, flagSpec "prof-cafs" Opt_AutoSccsOnIndividualCafs, flagSpec "prof-count-entries" Opt_ProfCountEntries, flagSpec "regs-graph" Opt_RegsGraph, flagSpec "regs-iterative" Opt_RegsIterative, flagSpec' "rewrite-rules" Opt_EnableRewriteRules (useInstead "enable-rewrite-rules"), flagSpec "shared-implib" Opt_SharedImplib, flagSpec "simple-list-literals" Opt_SimpleListLiterals, flagSpec "spec-constr" Opt_SpecConstr, flagSpec "specialise" Opt_Specialise, flagSpec "specialise-aggressively" Opt_SpecialiseAggressively, flagSpec "static-argument-transformation" Opt_StaticArgumentTransformation, flagSpec "strictness" Opt_Strictness, flagSpec "use-rpaths" Opt_RPath, flagSpec "write-interface" Opt_WriteInterface, flagSpec "unbox-small-strict-fields" Opt_UnboxSmallStrictFields, flagSpec "unbox-strict-fields" Opt_UnboxStrictFields, flagSpec "vectorisation-avoidance" Opt_VectorisationAvoidance, flagSpec "vectorise" Opt_Vectorise ] -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@ fLangFlags :: [FlagSpec ExtensionFlag] fLangFlags = [ -- See Note [Updating flag description in the User's Guide] -- See Note [Supporting CLI completion] flagSpec' "th" Opt_TemplateHaskell (\on -> deprecatedForExtension "TemplateHaskell" on >> checkTemplateHaskellOk on), flagSpec' "fi" Opt_ForeignFunctionInterface (deprecatedForExtension "ForeignFunctionInterface"), flagSpec' "ffi" Opt_ForeignFunctionInterface (deprecatedForExtension "ForeignFunctionInterface"), flagSpec' "arrows" Opt_Arrows (deprecatedForExtension "Arrows"), flagSpec' "implicit-prelude" Opt_ImplicitPrelude (deprecatedForExtension "ImplicitPrelude"), flagSpec' "bang-patterns" Opt_BangPatterns (deprecatedForExtension "BangPatterns"), flagSpec' "monomorphism-restriction" Opt_MonomorphismRestriction (deprecatedForExtension "MonomorphismRestriction"), flagSpec' "mono-pat-binds" Opt_MonoPatBinds (deprecatedForExtension "MonoPatBinds"), flagSpec' "extended-default-rules" Opt_ExtendedDefaultRules (deprecatedForExtension "ExtendedDefaultRules"), flagSpec' "implicit-params" Opt_ImplicitParams (deprecatedForExtension "ImplicitParams"), flagSpec' "scoped-type-variables" Opt_ScopedTypeVariables (deprecatedForExtension "ScopedTypeVariables"), flagSpec' "parr" Opt_ParallelArrays (deprecatedForExtension "ParallelArrays"), flagSpec' "PArr" Opt_ParallelArrays (deprecatedForExtension "ParallelArrays"), flagSpec' "allow-overlapping-instances" Opt_OverlappingInstances (deprecatedForExtension "OverlappingInstances"), flagSpec' "allow-undecidable-instances" Opt_UndecidableInstances (deprecatedForExtension "UndecidableInstances"), flagSpec' "allow-incoherent-instances" Opt_IncoherentInstances (deprecatedForExtension "IncoherentInstances") ] supportedLanguages :: [String] supportedLanguages = map flagSpecName languageFlags supportedLanguageOverlays :: [String] supportedLanguageOverlays = map flagSpecName safeHaskellFlags supportedExtensions :: [String] supportedExtensions = concatMap (\name -> [name, "No" ++ name]) (map flagSpecName xFlags) supportedLanguagesAndExtensions :: [String] supportedLanguagesAndExtensions = supportedLanguages ++ supportedLanguageOverlays ++ supportedExtensions -- | These -X<blah> flags cannot be reversed with -XNo<blah> languageFlags :: [FlagSpec Language] languageFlags = [ flagSpec "Haskell98" Haskell98, flagSpec "Haskell2010" Haskell2010 ] -- | These -X<blah> flags cannot be reversed with -XNo<blah> -- They are used to place hard requirements on what GHC Haskell language -- features can be used. safeHaskellFlags :: [FlagSpec SafeHaskellMode] safeHaskellFlags = [mkF Sf_Unsafe, mkF Sf_Trustworthy, mkF Sf_Safe] where mkF flag = flagSpec (show flag) flag -- | These -X<blah> flags can all be reversed with -XNo<blah> xFlags :: [FlagSpec ExtensionFlag] xFlags = [ -- See Note [Updating flag description in the User's Guide] -- See Note [Supporting CLI completion] -- Please keep the list of flags below sorted alphabetically flagSpec "AllowAmbiguousTypes" Opt_AllowAmbiguousTypes, flagSpec "AlternativeLayoutRule" Opt_AlternativeLayoutRule, flagSpec "AlternativeLayoutRuleTransitional" Opt_AlternativeLayoutRuleTransitional, flagSpec "Arrows" Opt_Arrows, flagSpec "AutoDeriveTypeable" Opt_AutoDeriveTypeable, flagSpec "BangPatterns" Opt_BangPatterns, flagSpec "BinaryLiterals" Opt_BinaryLiterals, flagSpec "CApiFFI" Opt_CApiFFI, flagSpec "CPP" Opt_Cpp, flagSpec "ConstrainedClassMethods" Opt_ConstrainedClassMethods, flagSpec "ConstraintKinds" Opt_ConstraintKinds, flagSpec "DataKinds" Opt_DataKinds, flagSpec' "DatatypeContexts" Opt_DatatypeContexts (\ turn_on -> when turn_on $ deprecate $ "It was widely considered a misfeature, " ++ "and has been removed from the Haskell language."), flagSpec "DefaultSignatures" Opt_DefaultSignatures, flagSpec "DeriveAnyClass" Opt_DeriveAnyClass, flagSpec "DeriveDataTypeable" Opt_DeriveDataTypeable, flagSpec "DeriveFoldable" Opt_DeriveFoldable, flagSpec "DeriveFunctor" Opt_DeriveFunctor, flagSpec "DeriveGeneric" Opt_DeriveGeneric, flagSpec "DeriveTraversable" Opt_DeriveTraversable, flagSpec "DisambiguateRecordFields" Opt_DisambiguateRecordFields, flagSpec "DoAndIfThenElse" Opt_DoAndIfThenElse, flagSpec' "DoRec" Opt_RecursiveDo (deprecatedForExtension "RecursiveDo"), flagSpec "EmptyCase" Opt_EmptyCase, flagSpec "EmptyDataDecls" Opt_EmptyDataDecls, flagSpec "ExistentialQuantification" Opt_ExistentialQuantification, flagSpec "ExplicitForAll" Opt_ExplicitForAll, flagSpec "ExplicitNamespaces" Opt_ExplicitNamespaces, flagSpec "ExtendedDefaultRules" Opt_ExtendedDefaultRules, flagSpec "FlexibleContexts" Opt_FlexibleContexts, flagSpec "FlexibleInstances" Opt_FlexibleInstances, flagSpec "ForeignFunctionInterface" Opt_ForeignFunctionInterface, flagSpec "FunctionalDependencies" Opt_FunctionalDependencies, flagSpec "GADTSyntax" Opt_GADTSyntax, flagSpec "GADTs" Opt_GADTs, flagSpec "GHCForeignImportPrim" Opt_GHCForeignImportPrim, flagSpec' "GeneralizedNewtypeDeriving" Opt_GeneralizedNewtypeDeriving setGenDeriving, flagSpec "ImplicitParams" Opt_ImplicitParams, flagSpec "ImplicitPrelude" Opt_ImplicitPrelude, flagSpec "ImpredicativeTypes" Opt_ImpredicativeTypes, flagSpec' "IncoherentInstances" Opt_IncoherentInstances setIncoherentInsts, flagSpec "InstanceSigs" Opt_InstanceSigs, flagSpec "InterruptibleFFI" Opt_InterruptibleFFI, flagSpec "JavaScriptFFI" Opt_JavaScriptFFI, flagSpec "KindSignatures" Opt_KindSignatures, flagSpec "LambdaCase" Opt_LambdaCase, flagSpec "LiberalTypeSynonyms" Opt_LiberalTypeSynonyms, flagSpec "MagicHash" Opt_MagicHash, flagSpec "MonadComprehensions" Opt_MonadComprehensions, flagSpec "MonoLocalBinds" Opt_MonoLocalBinds, flagSpec' "MonoPatBinds" Opt_MonoPatBinds (\ turn_on -> when turn_on $ deprecate "Experimental feature now removed; has no effect"), flagSpec "MonomorphismRestriction" Opt_MonomorphismRestriction, flagSpec "MultiParamTypeClasses" Opt_MultiParamTypeClasses, flagSpec "MultiWayIf" Opt_MultiWayIf, flagSpec "NPlusKPatterns" Opt_NPlusKPatterns, flagSpec "NamedFieldPuns" Opt_RecordPuns, flagSpec "NamedWildCards" Opt_NamedWildCards, flagSpec "NegativeLiterals" Opt_NegativeLiterals, flagSpec "NondecreasingIndentation" Opt_NondecreasingIndentation, flagSpec' "NullaryTypeClasses" Opt_NullaryTypeClasses (deprecatedForExtension "MultiParamTypeClasses"), flagSpec "NumDecimals" Opt_NumDecimals, flagSpec' "OverlappingInstances" Opt_OverlappingInstances setOverlappingInsts, flagSpec "OverloadedLists" Opt_OverloadedLists, flagSpec "OverloadedStrings" Opt_OverloadedStrings, flagSpec "PackageImports" Opt_PackageImports, flagSpec "ParallelArrays" Opt_ParallelArrays, flagSpec "ParallelListComp" Opt_ParallelListComp, flagSpec "PartialTypeSignatures" Opt_PartialTypeSignatures, flagSpec "PatternGuards" Opt_PatternGuards, flagSpec' "PatternSignatures" Opt_ScopedTypeVariables (deprecatedForExtension "ScopedTypeVariables"), flagSpec "PatternSynonyms" Opt_PatternSynonyms, flagSpec "PolyKinds" Opt_PolyKinds, flagSpec "PolymorphicComponents" Opt_RankNTypes, flagSpec "PostfixOperators" Opt_PostfixOperators, flagSpec "QuasiQuotes" Opt_QuasiQuotes, flagSpec "Rank2Types" Opt_RankNTypes, flagSpec "RankNTypes" Opt_RankNTypes, flagSpec "RebindableSyntax" Opt_RebindableSyntax, flagSpec' "RecordPuns" Opt_RecordPuns (deprecatedForExtension "NamedFieldPuns"), flagSpec "RecordWildCards" Opt_RecordWildCards, flagSpec "RecursiveDo" Opt_RecursiveDo, flagSpec "RelaxedLayout" Opt_RelaxedLayout, flagSpec' "RelaxedPolyRec" Opt_RelaxedPolyRec (\ turn_on -> unless turn_on $ deprecate "You can't turn off RelaxedPolyRec any more"), flagSpec "RoleAnnotations" Opt_RoleAnnotations, flagSpec "ScopedTypeVariables" Opt_ScopedTypeVariables, flagSpec "StandaloneDeriving" Opt_StandaloneDeriving, flagSpec "StaticPointers" Opt_StaticPointers, flagSpec' "TemplateHaskell" Opt_TemplateHaskell checkTemplateHaskellOk, flagSpec "TraditionalRecordSyntax" Opt_TraditionalRecordSyntax, flagSpec "TransformListComp" Opt_TransformListComp, flagSpec "TupleSections" Opt_TupleSections, flagSpec "TypeFamilies" Opt_TypeFamilies, flagSpec "TypeOperators" Opt_TypeOperators, flagSpec "TypeSynonymInstances" Opt_TypeSynonymInstances, flagSpec "UnboxedTuples" Opt_UnboxedTuples, flagSpec "UndecidableInstances" Opt_UndecidableInstances, flagSpec "UnicodeSyntax" Opt_UnicodeSyntax, flagSpec "UnliftedFFITypes" Opt_UnliftedFFITypes, flagSpec "ViewPatterns" Opt_ViewPatterns ] defaultFlags :: Settings -> [GeneralFlag] defaultFlags settings -- See Note [Updating flag description in the User's Guide] = [ Opt_AutoLinkPackages, Opt_EmbedManifest, Opt_FlatCache, Opt_GenManifest, Opt_GhciHistory, Opt_GhciSandbox, Opt_HelpfulErrors, Opt_OmitYields, Opt_PrintBindContents, Opt_ProfCountEntries, Opt_RPath, Opt_SharedImplib, Opt_SimplPreInlining ] ++ [f | (ns,f) <- optLevelFlags, 0 `elem` ns] -- The default -O0 options ++ default_PIC platform ++ (if pc_DYNAMIC_BY_DEFAULT (sPlatformConstants settings) then wayGeneralFlags platform WayDyn else []) where platform = sTargetPlatform settings default_PIC :: Platform -> [GeneralFlag] default_PIC platform = case (platformOS platform, platformArch platform) of (OSDarwin, ArchX86_64) -> [Opt_PIC] _ -> [] impliedGFlags :: [(GeneralFlag, TurnOnFlag, GeneralFlag)] impliedGFlags = [(Opt_DeferTypeErrors, turnOn, Opt_DeferTypedHoles)] impliedXFlags :: [(ExtensionFlag, TurnOnFlag, ExtensionFlag)] impliedXFlags -- See Note [Updating flag description in the User's Guide] = [ (Opt_RankNTypes, turnOn, Opt_ExplicitForAll) , (Opt_ScopedTypeVariables, turnOn, Opt_ExplicitForAll) , (Opt_LiberalTypeSynonyms, turnOn, Opt_ExplicitForAll) , (Opt_ExistentialQuantification, turnOn, Opt_ExplicitForAll) , (Opt_FlexibleInstances, turnOn, Opt_TypeSynonymInstances) , (Opt_FunctionalDependencies, turnOn, Opt_MultiParamTypeClasses) , (Opt_MultiParamTypeClasses, turnOn, Opt_ConstrainedClassMethods) -- c.f. Trac #7854 , (Opt_RebindableSyntax, turnOff, Opt_ImplicitPrelude) -- NB: turn off! , (Opt_GADTs, turnOn, Opt_GADTSyntax) , (Opt_GADTs, turnOn, Opt_MonoLocalBinds) , (Opt_TypeFamilies, turnOn, Opt_MonoLocalBinds) , (Opt_TypeFamilies, turnOn, Opt_KindSignatures) -- Type families use kind signatures , (Opt_PolyKinds, turnOn, Opt_KindSignatures) -- Ditto polymorphic kinds -- AutoDeriveTypeable is not very useful without DeriveDataTypeable , (Opt_AutoDeriveTypeable, turnOn, Opt_DeriveDataTypeable) -- We turn this on so that we can export associated type -- type synonyms in subordinates (e.g. MyClass(type AssocType)) , (Opt_TypeFamilies, turnOn, Opt_ExplicitNamespaces) , (Opt_TypeOperators, turnOn, Opt_ExplicitNamespaces) , (Opt_ImpredicativeTypes, turnOn, Opt_RankNTypes) -- Record wild-cards implies field disambiguation -- Otherwise if you write (C {..}) you may well get -- stuff like " 'a' not in scope ", which is a bit silly -- if the compiler has just filled in field 'a' of constructor 'C' , (Opt_RecordWildCards, turnOn, Opt_DisambiguateRecordFields) , (Opt_ParallelArrays, turnOn, Opt_ParallelListComp) -- An implicit parameter constraint, `?x::Int`, is desugared into -- `IP "x" Int`, which requires a flexible context/instance. , (Opt_ImplicitParams, turnOn, Opt_FlexibleContexts) , (Opt_ImplicitParams, turnOn, Opt_FlexibleInstances) , (Opt_JavaScriptFFI, turnOn, Opt_InterruptibleFFI) , (Opt_DeriveTraversable, turnOn, Opt_DeriveFunctor) , (Opt_DeriveTraversable, turnOn, Opt_DeriveFoldable) ] -- Note [Documenting optimisation flags] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- If you change the list of flags enabled for particular optimisation levels -- please remember to update the User's Guide. The relevant files are: -- -- * docs/users_guide/flags.xml -- * docs/users_guide/using.xml -- -- The first contains the Flag Refrence section, which breifly lists all -- available flags. The second contains a detailed description of the -- flags. Both places should contain information whether a flag is implied by -- -O0, -O or -O2. optLevelFlags :: [([Int], GeneralFlag)] optLevelFlags -- see Note [Documenting optimisation flags] = [ ([0,1,2], Opt_DoLambdaEtaExpansion) , ([0,1,2], Opt_DmdTxDictSel) , ([0,1,2], Opt_LlvmTBAA) , ([0,1,2], Opt_VectorisationAvoidance) -- This one is important for a tiresome reason: -- we want to make sure that the bindings for data -- constructors are eta-expanded. This is probably -- a good thing anyway, but it seems fragile. , ([0], Opt_IgnoreInterfacePragmas) , ([0], Opt_OmitInterfacePragmas) , ([1,2], Opt_CallArity) , ([1,2], Opt_CaseMerge) , ([1,2], Opt_CmmElimCommonBlocks) , ([1,2], Opt_CmmSink) , ([1,2], Opt_CSE) , ([1,2], Opt_DoEtaReduction) , ([1,2], Opt_EnableRewriteRules) -- Off for -O0; see Note [Scoping for Builtin rules] -- in PrelRules , ([1,2], Opt_FloatIn) , ([1,2], Opt_FullLaziness) , ([1,2], Opt_IgnoreAsserts) , ([1,2], Opt_Loopification) , ([1,2], Opt_Specialise) , ([1,2], Opt_Strictness) , ([1,2], Opt_UnboxSmallStrictFields) , ([2], Opt_LiberateCase) , ([2], Opt_SpecConstr) -- , ([2], Opt_RegsGraph) -- RegsGraph suffers performance regression. See #7679 -- , ([2], Opt_StaticArgumentTransformation) -- Static Argument Transformation needs investigation. See #9374 ] -- ----------------------------------------------------------------------------- -- Standard sets of warning options -- Note [Documenting warning flags] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- If you change the list of warning enabled by default -- please remember to update the User's Guide. The relevant file is: -- -- * docs/users_guide/using.xml standardWarnings :: [WarningFlag] standardWarnings -- see Note [Documenting warning flags] = [ Opt_WarnOverlappingPatterns, Opt_WarnWarningsDeprecations, Opt_WarnDeprecatedFlags, Opt_WarnTypedHoles, Opt_WarnPartialTypeSignatures, Opt_WarnUnrecognisedPragmas, Opt_WarnPointlessPragmas, Opt_WarnRedundantConstraints, Opt_WarnDuplicateExports, Opt_WarnOverflowedLiterals, Opt_WarnEmptyEnumerations, Opt_WarnMissingFields, Opt_WarnMissingMethods, Opt_WarnWrongDoBind, Opt_WarnUnsupportedCallingConventions, Opt_WarnDodgyForeignImports, Opt_WarnInlineRuleShadowing, Opt_WarnAlternativeLayoutRuleTransitional, Opt_WarnUnsupportedLlvmVersion, Opt_WarnContextQuantification, Opt_WarnTabs ] minusWOpts :: [WarningFlag] -- Things you get with -W minusWOpts = standardWarnings ++ [ Opt_WarnUnusedTopBinds, Opt_WarnUnusedLocalBinds, Opt_WarnUnusedPatternBinds, Opt_WarnUnusedMatches, Opt_WarnUnusedImports, Opt_WarnIncompletePatterns, Opt_WarnDodgyExports, Opt_WarnDodgyImports ] minusWallOpts :: [WarningFlag] -- Things you get with -Wall minusWallOpts = minusWOpts ++ [ Opt_WarnTypeDefaults, Opt_WarnNameShadowing, Opt_WarnMissingSigs, Opt_WarnHiShadows, Opt_WarnOrphans, Opt_WarnUnusedDoBind, Opt_WarnTrustworthySafe, Opt_WarnUntickedPromotedConstructors ] enableUnusedBinds :: DynP () enableUnusedBinds = mapM_ setWarningFlag unusedBindsFlags disableUnusedBinds :: DynP () disableUnusedBinds = mapM_ unSetWarningFlag unusedBindsFlags -- Things you get with -fwarn-unused-binds unusedBindsFlags :: [WarningFlag] unusedBindsFlags = [ Opt_WarnUnusedTopBinds , Opt_WarnUnusedLocalBinds , Opt_WarnUnusedPatternBinds ] enableGlasgowExts :: DynP () enableGlasgowExts = do setGeneralFlag Opt_PrintExplicitForalls mapM_ setExtensionFlag glasgowExtsFlags disableGlasgowExts :: DynP () disableGlasgowExts = do unSetGeneralFlag Opt_PrintExplicitForalls mapM_ unSetExtensionFlag glasgowExtsFlags glasgowExtsFlags :: [ExtensionFlag] glasgowExtsFlags = [ Opt_ConstrainedClassMethods , Opt_DeriveDataTypeable , Opt_DeriveFoldable , Opt_DeriveFunctor , Opt_DeriveGeneric , Opt_DeriveTraversable , Opt_EmptyDataDecls , Opt_ExistentialQuantification , Opt_ExplicitNamespaces , Opt_FlexibleContexts , Opt_FlexibleInstances , Opt_ForeignFunctionInterface , Opt_FunctionalDependencies , Opt_GeneralizedNewtypeDeriving , Opt_ImplicitParams , Opt_KindSignatures , Opt_LiberalTypeSynonyms , Opt_MagicHash , Opt_MultiParamTypeClasses , Opt_ParallelListComp , Opt_PatternGuards , Opt_PostfixOperators , Opt_RankNTypes , Opt_RecursiveDo , Opt_ScopedTypeVariables , Opt_StandaloneDeriving , Opt_TypeOperators , Opt_TypeSynonymInstances , Opt_UnboxedTuples , Opt_UnicodeSyntax , Opt_UnliftedFFITypes ] #ifdef GHCI -- Consult the RTS to find whether GHC itself has been built profiled -- If so, you can't use Template Haskell foreign import ccall unsafe "rts_isProfiled" rtsIsProfiledIO :: IO CInt rtsIsProfiled :: Bool rtsIsProfiled = unsafeDupablePerformIO rtsIsProfiledIO /= 0 #endif #ifdef GHCI -- Consult the RTS to find whether GHC itself has been built with -- dynamic linking. This can't be statically known at compile-time, -- because we build both the static and dynamic versions together with -- -dynamic-too. foreign import ccall unsafe "rts_isDynamic" rtsIsDynamicIO :: IO CInt dynamicGhc :: Bool dynamicGhc = unsafeDupablePerformIO rtsIsDynamicIO /= 0 #else dynamicGhc :: Bool dynamicGhc = False #endif setWarnSafe :: Bool -> DynP () setWarnSafe True = getCurLoc >>= \l -> upd (\d -> d { warnSafeOnLoc = l }) setWarnSafe False = return () setWarnUnsafe :: Bool -> DynP () setWarnUnsafe True = getCurLoc >>= \l -> upd (\d -> d { warnUnsafeOnLoc = l }) setWarnUnsafe False = return () setPackageTrust :: DynP () setPackageTrust = do setGeneralFlag Opt_PackageTrust l <- getCurLoc upd $ \d -> d { pkgTrustOnLoc = l } setGenDeriving :: TurnOnFlag -> DynP () setGenDeriving True = getCurLoc >>= \l -> upd (\d -> d { newDerivOnLoc = l }) setGenDeriving False = return () setOverlappingInsts :: TurnOnFlag -> DynP () setOverlappingInsts False = return () setOverlappingInsts True = do l <- getCurLoc upd (\d -> d { overlapInstLoc = l }) deprecate "instead use per-instance pragmas OVERLAPPING/OVERLAPPABLE/OVERLAPS" setIncoherentInsts :: TurnOnFlag -> DynP () setIncoherentInsts False = return () setIncoherentInsts True = do l <- getCurLoc upd (\d -> d { incoherentOnLoc = l }) checkTemplateHaskellOk :: TurnOnFlag -> DynP () #ifdef GHCI checkTemplateHaskellOk turn_on | turn_on && rtsIsProfiled = addErr "You can't use Template Haskell with a profiled compiler" | otherwise = getCurLoc >>= \l -> upd (\d -> d { thOnLoc = l }) #else -- In stage 1, Template Haskell is simply illegal, except with -M -- We don't bleat with -M because there's no problem with TH there, -- and in fact GHC's build system does ghc -M of the DPH libraries -- with a stage1 compiler checkTemplateHaskellOk turn_on | turn_on = do dfs <- liftEwM getCmdLineState case ghcMode dfs of MkDepend -> return () _ -> addErr msg | otherwise = return () where msg = "Template Haskell requires GHC with interpreter support\n " ++ "Perhaps you are using a stage-1 compiler?" #endif {- ********************************************************************** %* * DynFlags constructors %* * %********************************************************************* -} type DynP = EwM (CmdLineP DynFlags) upd :: (DynFlags -> DynFlags) -> DynP () upd f = liftEwM (do dflags <- getCmdLineState putCmdLineState $! f dflags) updM :: (DynFlags -> DynP DynFlags) -> DynP () updM f = do dflags <- liftEwM getCmdLineState dflags' <- f dflags liftEwM $ putCmdLineState $! dflags' --------------- Constructor functions for OptKind ----------------- noArg :: (DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags) noArg fn = NoArg (upd fn) noArgM :: (DynFlags -> DynP DynFlags) -> OptKind (CmdLineP DynFlags) noArgM fn = NoArg (updM fn) hasArg :: (String -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags) hasArg fn = HasArg (upd . fn) sepArg :: (String -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags) sepArg fn = SepArg (upd . fn) intSuffix :: (Int -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags) intSuffix fn = IntSuffix (\n -> upd (fn n)) floatSuffix :: (Float -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags) floatSuffix fn = FloatSuffix (\n -> upd (fn n)) optIntSuffixM :: (Maybe Int -> DynFlags -> DynP DynFlags) -> OptKind (CmdLineP DynFlags) optIntSuffixM fn = OptIntSuffix (\mi -> updM (fn mi)) setDumpFlag :: DumpFlag -> OptKind (CmdLineP DynFlags) setDumpFlag dump_flag = NoArg (setDumpFlag' dump_flag) -------------------------- addWay :: Way -> DynP () addWay w = upd (addWay' w) addWay' :: Way -> DynFlags -> DynFlags addWay' w dflags0 = let platform = targetPlatform dflags0 dflags1 = dflags0 { ways = w : ways dflags0 } dflags2 = wayExtras platform w dflags1 dflags3 = foldr setGeneralFlag' dflags2 (wayGeneralFlags platform w) dflags4 = foldr unSetGeneralFlag' dflags3 (wayUnsetGeneralFlags platform w) in dflags4 removeWayDyn :: DynP () removeWayDyn = upd (\dfs -> dfs { ways = filter (WayDyn /=) (ways dfs) }) -------------------------- setGeneralFlag, unSetGeneralFlag :: GeneralFlag -> DynP () setGeneralFlag f = upd (setGeneralFlag' f) unSetGeneralFlag f = upd (unSetGeneralFlag' f) setGeneralFlag' :: GeneralFlag -> DynFlags -> DynFlags setGeneralFlag' f dflags = foldr ($) (gopt_set dflags f) deps where deps = [ if turn_on then setGeneralFlag' d else unSetGeneralFlag' d | (f', turn_on, d) <- impliedGFlags, f' == f ] -- When you set f, set the ones it implies -- NB: use setGeneralFlag recursively, in case the implied flags -- implies further flags unSetGeneralFlag' :: GeneralFlag -> DynFlags -> DynFlags unSetGeneralFlag' f dflags = gopt_unset dflags f -- When you un-set f, however, we don't un-set the things it implies -------------------------- setWarningFlag, unSetWarningFlag :: WarningFlag -> DynP () setWarningFlag f = upd (\dfs -> wopt_set dfs f) unSetWarningFlag f = upd (\dfs -> wopt_unset dfs f) -------------------------- setExtensionFlag, unSetExtensionFlag :: ExtensionFlag -> DynP () setExtensionFlag f = upd (setExtensionFlag' f) unSetExtensionFlag f = upd (unSetExtensionFlag' f) setExtensionFlag', unSetExtensionFlag' :: ExtensionFlag -> DynFlags -> DynFlags setExtensionFlag' f dflags = foldr ($) (xopt_set dflags f) deps where deps = [ if turn_on then setExtensionFlag' d else unSetExtensionFlag' d | (f', turn_on, d) <- impliedXFlags, f' == f ] -- When you set f, set the ones it implies -- NB: use setExtensionFlag recursively, in case the implied flags -- implies further flags unSetExtensionFlag' f dflags = xopt_unset dflags f -- When you un-set f, however, we don't un-set the things it implies -- (except for -fno-glasgow-exts, which is treated specially) -------------------------- alterSettings :: (Settings -> Settings) -> DynFlags -> DynFlags alterSettings f dflags = dflags { settings = f (settings dflags) } -------------------------- setDumpFlag' :: DumpFlag -> DynP () setDumpFlag' dump_flag = do upd (\dfs -> dopt_set dfs dump_flag) when want_recomp forceRecompile where -- Certain dumpy-things are really interested in what's going -- on during recompilation checking, so in those cases we -- don't want to turn it off. want_recomp = dump_flag `notElem` [Opt_D_dump_if_trace, Opt_D_dump_hi_diffs] forceRecompile :: DynP () -- Whenver we -ddump, force recompilation (by switching off the -- recompilation checker), else you don't see the dump! However, -- don't switch it off in --make mode, else *everything* gets -- recompiled which probably isn't what you want forceRecompile = do dfs <- liftEwM getCmdLineState when (force_recomp dfs) (setGeneralFlag Opt_ForceRecomp) where force_recomp dfs = isOneShot (ghcMode dfs) setVerboseCore2Core :: DynP () setVerboseCore2Core = setDumpFlag' Opt_D_verbose_core2core setVerbosity :: Maybe Int -> DynP () setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 }) addCmdlineHCInclude :: String -> DynP () addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes = a : cmdlineHcIncludes s}) data PkgConfRef = GlobalPkgConf | UserPkgConf | PkgConfFile FilePath addPkgConfRef :: PkgConfRef -> DynP () addPkgConfRef p = upd $ \s -> s { extraPkgConfs = (p:) . extraPkgConfs s } removeUserPkgConf :: DynP () removeUserPkgConf = upd $ \s -> s { extraPkgConfs = filter isNotUser . extraPkgConfs s } where isNotUser UserPkgConf = False isNotUser _ = True removeGlobalPkgConf :: DynP () removeGlobalPkgConf = upd $ \s -> s { extraPkgConfs = filter isNotGlobal . extraPkgConfs s } where isNotGlobal GlobalPkgConf = False isNotGlobal _ = True clearPkgConf :: DynP () clearPkgConf = upd $ \s -> s { extraPkgConfs = const [] } parseModuleName :: ReadP ModuleName parseModuleName = fmap mkModuleName $ munch1 (\c -> isAlphaNum c || c `elem` ".") parsePackageFlag :: (String -> PackageArg) -- type of argument -> String -- string to parse -> PackageFlag parsePackageFlag constr str = case filter ((=="").snd) (readP_to_S parse str) of [(r, "")] -> r _ -> throwGhcException $ CmdLineError ("Can't parse package flag: " ++ str) where parse = do pkg <- tok $ munch1 (\c -> isAlphaNum c || c `elem` ":-_.") ( do _ <- tok $ string "with" fmap (ExposePackage (constr pkg) . ModRenaming True) parseRns <++ fmap (ExposePackage (constr pkg) . ModRenaming False) parseRns <++ return (ExposePackage (constr pkg) (ModRenaming True []))) parseRns = do _ <- tok $ R.char '(' rns <- tok $ sepBy parseItem (tok $ R.char ',') _ <- tok $ R.char ')' return rns parseItem = do orig <- tok $ parseModuleName (do _ <- tok $ string "as" new <- tok $ parseModuleName return (orig, new) +++ return (orig, orig)) tok m = m >>= \x -> skipSpaces >> return x exposePackage, exposePackageId, exposePackageKey, hidePackage, ignorePackage, trustPackage, distrustPackage :: String -> DynP () exposePackage p = upd (exposePackage' p) exposePackageId p = upd (\s -> s{ packageFlags = parsePackageFlag PackageIdArg p : packageFlags s }) exposePackageKey p = upd (\s -> s{ packageFlags = parsePackageFlag PackageKeyArg p : packageFlags s }) hidePackage p = upd (\s -> s{ packageFlags = HidePackage p : packageFlags s }) ignorePackage p = upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s }) trustPackage p = exposePackage p >> -- both trust and distrust also expose a package upd (\s -> s{ packageFlags = TrustPackage p : packageFlags s }) distrustPackage p = exposePackage p >> upd (\s -> s{ packageFlags = DistrustPackage p : packageFlags s }) exposePackage' :: String -> DynFlags -> DynFlags exposePackage' p dflags = dflags { packageFlags = parsePackageFlag PackageArg p : packageFlags dflags } setPackageKey :: String -> DynFlags -> DynFlags setPackageKey p s = s{ thisPackage = stringToPackageKey p } -- ----------------------------------------------------------------------------- -- | Find the package environment (if one exists) -- -- We interpret the package environment as a set of package flags; to be -- specific, if we find a package environment -- -- > id1 -- > id2 -- > .. -- > idn -- -- we interpret this as -- -- > [ -hide-all-packages -- > , -package-id id1 -- > , -package-id id2 -- > , .. -- > , -package-id idn -- > ] interpretPackageEnv :: DynFlags -> IO DynFlags interpretPackageEnv dflags = do mPkgEnv <- runMaybeT $ msum $ [ getCmdLineArg >>= \env -> msum [ loadEnvFile env , loadEnvName env , cmdLineError env ] , getEnvVar >>= \env -> msum [ loadEnvFile env , loadEnvName env , envError env ] , loadEnvFile localEnvFile , loadEnvName defaultEnvName ] case mPkgEnv of Nothing -> -- No environment found. Leave DynFlags unchanged. return dflags Just ids -> do let setFlags :: DynP () setFlags = do setGeneralFlag Opt_HideAllPackages mapM_ exposePackageId (lines ids) (_, dflags') = runCmdLine (runEwM setFlags) dflags return dflags' where -- Loading environments (by name or by location) namedEnvPath :: String -> MaybeT IO FilePath namedEnvPath name = do appdir <- liftMaybeT $ versionedAppDir dflags return $ appdir </> "environments" </> name loadEnvName :: String -> MaybeT IO String loadEnvName name = loadEnvFile =<< namedEnvPath name loadEnvFile :: String -> MaybeT IO String loadEnvFile path = do guard =<< liftMaybeT (doesFileExist path) liftMaybeT $ readFile path -- Various ways to define which environment to use getCmdLineArg :: MaybeT IO String getCmdLineArg = MaybeT $ return $ packageEnv dflags getEnvVar :: MaybeT IO String getEnvVar = do mvar <- liftMaybeT $ try $ getEnv "GHC_ENVIRONMENT" case mvar of Right var -> return var Left err -> if isDoesNotExistError err then mzero else liftMaybeT $ throwIO err defaultEnvName :: String defaultEnvName = "default" localEnvFile :: FilePath localEnvFile = "./.ghc.environment" -- Error reporting cmdLineError :: String -> MaybeT IO a cmdLineError env = liftMaybeT . throwGhcExceptionIO . CmdLineError $ "Package environment " ++ show env ++ " not found" envError :: String -> MaybeT IO a envError env = liftMaybeT . throwGhcExceptionIO . CmdLineError $ "Package environment " ++ show env ++ " (specified in GHC_ENVIRIONMENT) not found" -- If we're linking a binary, then only targets that produce object -- code are allowed (requests for other target types are ignored). setTarget :: HscTarget -> DynP () setTarget l = setTargetWithPlatform (const l) setTargetWithPlatform :: (Platform -> HscTarget) -> DynP () setTargetWithPlatform f = upd set where set dfs = let l = f (targetPlatform dfs) in if ghcLink dfs /= LinkBinary || isObjectTarget l then dfs{ hscTarget = l } else dfs -- Changes the target only if we're compiling object code. This is -- used by -fasm and -fllvm, which switch from one to the other, but -- not from bytecode to object-code. The idea is that -fasm/-fllvm -- can be safely used in an OPTIONS_GHC pragma. setObjTarget :: HscTarget -> DynP () setObjTarget l = updM set where set dflags | isObjectTarget (hscTarget dflags) = return $ dflags { hscTarget = l } | otherwise = return dflags setOptLevel :: Int -> DynFlags -> DynP DynFlags setOptLevel n dflags | hscTarget dflags == HscInterpreted && n > 0 = do addWarn "-O conflicts with --interactive; -O ignored." return dflags | otherwise = return (updOptLevel n dflags) -- -Odph is equivalent to -- -- -O2 optimise as much as possible -- -fmax-simplifier-iterations20 this is necessary sometimes -- -fsimplifier-phases=3 we use an additional simplifier phase for fusion -- setDPHOpt :: DynFlags -> DynP DynFlags setDPHOpt dflags = setOptLevel 2 (dflags { maxSimplIterations = 20 , simplPhases = 3 }) setMainIs :: String -> DynP () setMainIs arg | not (null main_fn) && isLower (head main_fn) -- The arg looked like "Foo.Bar.baz" = upd $ \d -> d{ mainFunIs = Just main_fn, mainModIs = mkModule mainPackageKey (mkModuleName main_mod) } | isUpper (head arg) -- The arg looked like "Foo" or "Foo.Bar" = upd $ \d -> d{ mainModIs = mkModule mainPackageKey (mkModuleName arg) } | otherwise -- The arg looked like "baz" = upd $ \d -> d{ mainFunIs = Just arg } where (main_mod, main_fn) = splitLongestPrefix arg (== '.') addLdInputs :: Option -> DynFlags -> DynFlags addLdInputs p dflags = dflags{ldInputs = ldInputs dflags ++ [p]} ----------------------------------------------------------------------------- -- Paths & Libraries addImportPath, addLibraryPath, addIncludePath, addFrameworkPath :: FilePath -> DynP () -- -i on its own deletes the import paths addImportPath "" = upd (\s -> s{importPaths = []}) addImportPath p = upd (\s -> s{importPaths = importPaths s ++ splitPathList p}) addLibraryPath p = upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p}) addIncludePath p = upd (\s -> s{includePaths = includePaths s ++ splitPathList p}) addFrameworkPath p = upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p}) #ifndef mingw32_TARGET_OS split_marker :: Char split_marker = ':' -- not configurable (ToDo) #endif splitPathList :: String -> [String] splitPathList s = filter notNull (splitUp s) -- empty paths are ignored: there might be a trailing -- ':' in the initial list, for example. Empty paths can -- cause confusion when they are translated into -I options -- for passing to gcc. where #ifndef mingw32_TARGET_OS splitUp xs = split split_marker xs #else -- Windows: 'hybrid' support for DOS-style paths in directory lists. -- -- That is, if "foo:bar:baz" is used, this interpreted as -- consisting of three entries, 'foo', 'bar', 'baz'. -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar" -- -- Notice that no attempt is made to fully replace the 'standard' -- split marker ':' with the Windows / DOS one, ';'. The reason being -- that this will cause too much breakage for users & ':' will -- work fine even with DOS paths, if you're not insisting on being silly. -- So, use either. splitUp [] = [] splitUp (x:':':div:xs) | div `elem` dir_markers = ((x:':':div:p): splitUp rs) where (p,rs) = findNextPath xs -- we used to check for existence of the path here, but that -- required the IO monad to be threaded through the command-line -- parser which is quite inconvenient. The splitUp xs = cons p (splitUp rs) where (p,rs) = findNextPath xs cons "" xs = xs cons x xs = x:xs -- will be called either when we've consumed nought or the -- "<Drive>:/" part of a DOS path, so splitting is just a Q of -- finding the next split marker. findNextPath xs = case break (`elem` split_markers) xs of (p, _:ds) -> (p, ds) (p, xs) -> (p, xs) split_markers :: [Char] split_markers = [':', ';'] dir_markers :: [Char] dir_markers = ['/', '\\'] #endif -- ----------------------------------------------------------------------------- -- tmpDir, where we store temporary files. setTmpDir :: FilePath -> DynFlags -> DynFlags setTmpDir dir = alterSettings (\s -> s { sTmpDir = normalise dir }) -- we used to fix /cygdrive/c/.. on Windows, but this doesn't -- seem necessary now --SDM 7/2/2008 ----------------------------------------------------------------------------- -- RTS opts setRtsOpts :: String -> DynP () setRtsOpts arg = upd $ \ d -> d {rtsOpts = Just arg} setRtsOptsEnabled :: RtsOptsEnabled -> DynP () setRtsOptsEnabled arg = upd $ \ d -> d {rtsOptsEnabled = arg} ----------------------------------------------------------------------------- -- Hpc stuff setOptHpcDir :: String -> DynP () setOptHpcDir arg = upd $ \ d -> d{hpcDir = arg} ----------------------------------------------------------------------------- -- Via-C compilation stuff -- There are some options that we need to pass to gcc when compiling -- Haskell code via C, but are only supported by recent versions of -- gcc. The configure script decides which of these options we need, -- and puts them in the "settings" file in $topdir. The advantage of -- having these in a separate file is that the file can be created at -- install-time depending on the available gcc version, and even -- re-generated later if gcc is upgraded. -- -- The options below are not dependent on the version of gcc, only the -- platform. picCCOpts :: DynFlags -> [String] picCCOpts dflags = case platformOS (targetPlatform dflags) of OSDarwin -- Apple prefers to do things the other way round. -- PIC is on by default. -- -mdynamic-no-pic: -- Turn off PIC code generation. -- -fno-common: -- Don't generate "common" symbols - these are unwanted -- in dynamic libraries. | gopt Opt_PIC dflags -> ["-fno-common", "-U__PIC__", "-D__PIC__"] | otherwise -> ["-mdynamic-no-pic"] OSMinGW32 -- no -fPIC for Windows | gopt Opt_PIC dflags -> ["-U__PIC__", "-D__PIC__"] | otherwise -> [] _ -- we need -fPIC for C files when we are compiling with -dynamic, -- otherwise things like stub.c files don't get compiled -- correctly. They need to reference data in the Haskell -- objects, but can't without -fPIC. See -- http://ghc.haskell.org/trac/ghc/wiki/Commentary/PositionIndependentCode | gopt Opt_PIC dflags || not (gopt Opt_Static dflags) -> ["-fPIC", "-U__PIC__", "-D__PIC__"] | otherwise -> [] picPOpts :: DynFlags -> [String] picPOpts dflags | gopt Opt_PIC dflags = ["-U__PIC__", "-D__PIC__"] | otherwise = [] -- ----------------------------------------------------------------------------- -- Splitting can_split :: Bool can_split = cSupportsSplitObjs == "YES" -- ----------------------------------------------------------------------------- -- Compiler Info compilerInfo :: DynFlags -> [(String, String)] compilerInfo dflags = -- We always make "Project name" be first to keep parsing in -- other languages simple, i.e. when looking for other fields, -- you don't have to worry whether there is a leading '[' or not ("Project name", cProjectName) -- Next come the settings, so anything else can be overridden -- in the settings file (as "lookup" uses the first match for the -- key) : rawSettings dflags ++ [("Project version", projectVersion dflags), ("Project Git commit id", cProjectGitCommitId), ("Booter version", cBooterVersion), ("Stage", cStage), ("Build platform", cBuildPlatformString), ("Host platform", cHostPlatformString), ("Target platform", cTargetPlatformString), ("Have interpreter", cGhcWithInterpreter), ("Object splitting supported", cSupportsSplitObjs), ("Have native code generator", cGhcWithNativeCodeGen), ("Support SMP", cGhcWithSMP), ("Tables next to code", cGhcEnableTablesNextToCode), ("RTS ways", cGhcRTSWays), ("Support dynamic-too", if isWindows then "NO" else "YES"), ("Support parallel --make", "YES"), ("Support reexported-modules", "YES"), ("Support thinning and renaming package flags", "YES"), ("Uses package keys", "YES"), ("Dynamic by default", if dYNAMIC_BY_DEFAULT dflags then "YES" else "NO"), ("GHC Dynamic", if dynamicGhc then "YES" else "NO"), ("Leading underscore", cLeadingUnderscore), ("Debug on", show debugIsOn), ("LibDir", topDir dflags), ("Global Package DB", systemPackageConfig dflags) ] where isWindows = platformOS (targetPlatform dflags) == OSMinGW32 #include "../includes/dist-derivedconstants/header/GHCConstantsHaskellWrappers.hs" bLOCK_SIZE_W :: DynFlags -> Int bLOCK_SIZE_W dflags = bLOCK_SIZE dflags `quot` wORD_SIZE dflags wORD_SIZE_IN_BITS :: DynFlags -> Int wORD_SIZE_IN_BITS dflags = wORD_SIZE dflags * 8 tAG_MASK :: DynFlags -> Int tAG_MASK dflags = (1 `shiftL` tAG_BITS dflags) - 1 mAX_PTR_TAG :: DynFlags -> Int mAX_PTR_TAG = tAG_MASK -- Might be worth caching these in targetPlatform? tARGET_MIN_INT, tARGET_MAX_INT, tARGET_MAX_WORD :: DynFlags -> Integer tARGET_MIN_INT dflags = case platformWordSize (targetPlatform dflags) of 4 -> toInteger (minBound :: Int32) 8 -> toInteger (minBound :: Int64) w -> panic ("tARGET_MIN_INT: Unknown platformWordSize: " ++ show w) tARGET_MAX_INT dflags = case platformWordSize (targetPlatform dflags) of 4 -> toInteger (maxBound :: Int32) 8 -> toInteger (maxBound :: Int64) w -> panic ("tARGET_MAX_INT: Unknown platformWordSize: " ++ show w) tARGET_MAX_WORD dflags = case platformWordSize (targetPlatform dflags) of 4 -> toInteger (maxBound :: Word32) 8 -> toInteger (maxBound :: Word64) w -> panic ("tARGET_MAX_WORD: Unknown platformWordSize: " ++ show w) -- Whenever makeDynFlagsConsistent does anything, it starts over, to -- ensure that a later change doesn't invalidate an earlier check. -- Be careful not to introduce potential loops! makeDynFlagsConsistent :: DynFlags -> (DynFlags, [Located String]) makeDynFlagsConsistent dflags -- Disable -dynamic-too on Windows (#8228, #7134, #5987) | os == OSMinGW32 && gopt Opt_BuildDynamicToo dflags = let dflags' = gopt_unset dflags Opt_BuildDynamicToo warn = "-dynamic-too is not supported on Windows" in loop dflags' warn | hscTarget dflags == HscC && not (platformUnregisterised (targetPlatform dflags)) = if cGhcWithNativeCodeGen == "YES" then let dflags' = dflags { hscTarget = HscAsm } warn = "Compiler not unregisterised, so using native code generator rather than compiling via C" in loop dflags' warn else let dflags' = dflags { hscTarget = HscLlvm } warn = "Compiler not unregisterised, so using LLVM rather than compiling via C" in loop dflags' warn | hscTarget dflags == HscAsm && platformUnregisterised (targetPlatform dflags) = loop (dflags { hscTarget = HscC }) "Compiler unregisterised, so compiling via C" | hscTarget dflags == HscAsm && cGhcWithNativeCodeGen /= "YES" = let dflags' = dflags { hscTarget = HscLlvm } warn = "No native code generator, so using LLVM" in loop dflags' warn | hscTarget dflags == HscLlvm && not ((arch == ArchX86_64) && (os == OSLinux || os == OSDarwin || os == OSFreeBSD)) && not ((isARM arch) && (os == OSLinux)) && (not (gopt Opt_Static dflags) || gopt Opt_PIC dflags) = if cGhcWithNativeCodeGen == "YES" then let dflags' = dflags { hscTarget = HscAsm } warn = "Using native code generator rather than LLVM, as LLVM is incompatible with -fPIC and -dynamic on this platform" in loop dflags' warn else throwGhcException $ CmdLineError "Can't use -fPIC or -dynamic on this platform" | os == OSDarwin && arch == ArchX86_64 && not (gopt Opt_PIC dflags) = loop (gopt_set dflags Opt_PIC) "Enabling -fPIC as it is always on for this platform" | otherwise = (dflags, []) where loc = mkGeneralSrcSpan (fsLit "when making flags consistent") loop updated_dflags warning = case makeDynFlagsConsistent updated_dflags of (dflags', ws) -> (dflags', L loc warning : ws) platform = targetPlatform dflags arch = platformArch platform os = platformOS platform -------------------------------------------------------------------------- -- Do not use unsafeGlobalDynFlags! -- -- unsafeGlobalDynFlags is a hack, necessary because we need to be able -- to show SDocs when tracing, but we don't always have DynFlags -- available. -- -- Do not use it if you can help it. You may get the wrong value, or this -- panic! GLOBAL_VAR(v_unsafeGlobalDynFlags, panic "v_unsafeGlobalDynFlags: not initialised", DynFlags) unsafeGlobalDynFlags :: DynFlags unsafeGlobalDynFlags = unsafePerformIO $ readIORef v_unsafeGlobalDynFlags setUnsafeGlobalDynFlags :: DynFlags -> IO () setUnsafeGlobalDynFlags = writeIORef v_unsafeGlobalDynFlags -- ----------------------------------------------------------------------------- -- SSE and AVX -- TODO: Instead of using a separate predicate (i.e. isSse2Enabled) to -- check if SSE is enabled, we might have x86-64 imply the -msse2 -- flag. data SseVersion = SSE1 | SSE2 | SSE3 | SSE4 | SSE42 deriving (Eq, Ord) isSseEnabled :: DynFlags -> Bool isSseEnabled dflags = case platformArch (targetPlatform dflags) of ArchX86_64 -> True ArchX86 -> sseVersion dflags >= Just SSE1 _ -> False isSse2Enabled :: DynFlags -> Bool isSse2Enabled dflags = case platformArch (targetPlatform dflags) of ArchX86_64 -> -- SSE2 is fixed on for x86_64. It would be -- possible to make it optional, but we'd need to -- fix at least the foreign call code where the -- calling convention specifies the use of xmm regs, -- and possibly other places. True ArchX86 -> sseVersion dflags >= Just SSE2 _ -> False isSse4_2Enabled :: DynFlags -> Bool isSse4_2Enabled dflags = sseVersion dflags >= Just SSE42 isAvxEnabled :: DynFlags -> Bool isAvxEnabled dflags = avx dflags || avx2 dflags || avx512f dflags isAvx2Enabled :: DynFlags -> Bool isAvx2Enabled dflags = avx2 dflags || avx512f dflags isAvx512cdEnabled :: DynFlags -> Bool isAvx512cdEnabled dflags = avx512cd dflags isAvx512erEnabled :: DynFlags -> Bool isAvx512erEnabled dflags = avx512er dflags isAvx512fEnabled :: DynFlags -> Bool isAvx512fEnabled dflags = avx512f dflags isAvx512pfEnabled :: DynFlags -> Bool isAvx512pfEnabled dflags = avx512pf dflags -- ----------------------------------------------------------------------------- -- Linker/compiler information -- LinkerInfo contains any extra options needed by the system linker. data LinkerInfo = GnuLD [Option] | GnuGold [Option] | DarwinLD [Option] | SolarisLD [Option] | UnknownLD deriving Eq -- CompilerInfo tells us which C compiler we're using data CompilerInfo = GCC | Clang | AppleClang | AppleClang51 | UnknownCC deriving Eq -- ----------------------------------------------------------------------------- -- RTS hooks -- Convert sizes like "3.5M" into integers decodeSize :: String -> Integer decodeSize str | c == "" = truncate n | c == "K" || c == "k" = truncate (n * 1000) | c == "M" || c == "m" = truncate (n * 1000 * 1000) | c == "G" || c == "g" = truncate (n * 1000 * 1000 * 1000) | otherwise = throwGhcException (CmdLineError ("can't decode size: " ++ str)) where (m, c) = span pred str n = readRational m pred c = isDigit c || c == '.' foreign import ccall unsafe "setHeapSize" setHeapSize :: Int -> IO () foreign import ccall unsafe "enableTimingStats" enableTimingStats :: IO ()
gcampax/ghc
compiler/main/DynFlags.hs
bsd-3-clause
176,930
0
34
47,780
32,462
17,839
14,623
-1
-1
module Network.EmailSend(MailBackend(..), SendingReceipt) where import Data.ByteString (ByteString) type SendingReceipt = Maybe String class MailBackend a where sendMessage :: a -> String -> String -> ByteString -> IO SendingReceipt
weissi/haskell-email
Network/EmailSend.hs
bsd-3-clause
240
0
11
35
70
39
31
5
0
{-# OPTIONS -fno-warn-type-defaults -fno-warn-unused-binds -fno-warn-orphans #-} {-# LANGUAGE FlexibleInstances, ExistentialQuantification #-} module Test.TestParseTime where import Control.Monad import Data.Char import Data.Ratio import Data.Time import Data.Time.Calendar.OrdinalDate import Data.Time.Calendar.WeekDate import Data.Time.Clock.POSIX import Test.QuickCheck hiding (Result,reason) import Test.QuickCheck.Property hiding (result) import Test.TestUtil hiding (Result) ntest :: Int ntest = 1000 type NamedProperty = (String, Property) testParseTime :: Test testParseTime = testGroup "testParseTime" [ readOtherTypesTest, readTests, simpleFormatTests, extests, particularParseTests, badParseTests, defaultTimeZoneTests, militaryTimeZoneTests, testGroup "properties" (fmap (\(n,prop) -> testProperty n prop) properties) ] yearDays :: Integer -> [Day] yearDays y = [(fromGregorian y 1 1) .. (fromGregorian y 12 31)] makeExhaustiveTest :: String -> [t] -> (t -> Test) -> Test makeExhaustiveTest name cases f = testGroup name (fmap f cases) extests :: Test extests = testGroup "exhaustive" ([ makeExhaustiveTest "parse %y" [0..99] parseYY, makeExhaustiveTest "parse %-C %y 1900s" [0,1,50,99] (parseCYY 19), makeExhaustiveTest "parse %-C %y 2000s" [0,1,50,99] (parseCYY 20), makeExhaustiveTest "parse %-C %y 1400s" [0,1,50,99] (parseCYY 14), makeExhaustiveTest "parse %C %y 0700s" [0,1,50,99] (parseCYY2 7), makeExhaustiveTest "parse %-C %y 700s" [0,1,50,99] (parseCYY 7), makeExhaustiveTest "parse %-C %y 10000s" [0,1,50,99] (parseCYY 100), makeExhaustiveTest "parse %-C centuries" [20..100] (parseCentury " "), makeExhaustiveTest "parse %-C century X" [1,10,20,100] (parseCentury "X"), makeExhaustiveTest "parse %-C century 2sp" [1,10,20,100] (parseCentury " "), makeExhaustiveTest "parse %-C century 5sp" [1,10,20,100] (parseCentury " ") ] ++ (concat $ fmap (\y -> [ (makeExhaustiveTest "parse %Y%m%d" (yearDays y) parseYMD), (makeExhaustiveTest "parse %Y %m %d" (yearDays y) parseYearDayD), (makeExhaustiveTest "parse %Y %-m %e" (yearDays y) parseYearDayE) ]) [1,4,20,753,2000,2011,10001])) readTest :: (Eq a,Show a,Read a) => [(a,String)] -> String -> Test readTest expected target = let found = reads target result = diff expected found name = show target in pureTest name result readTestsParensSpaces :: forall a. (Eq a,Show a,Read a) => a -> String -> Test readTestsParensSpaces expected target = testGroup target [ readTest [(expected,"")] $ target, readTest [(expected,"")] $ "("++target++")", readTest [(expected,"")] $ " ("++target++")", readTest [(expected," ")] $ " ( "++target++" ) ", readTest [(expected," ")] $ " (( "++target++" )) ", readTest ([] :: [(a,String)]) $ "("++target, readTest [(expected,")")] $ ""++target++")", readTest [(expected,"")] $ "(("++target++"))", readTest [(expected," ")] $ " ( ( "++target++" ) ) " ] where readOtherTypesTest :: Test readOtherTypesTest = testGroup "read other types" [ readTestsParensSpaces 3 "3", readTestsParensSpaces "a" "\"a\"" ] readTests :: Test readTests = testGroup "read times" [ readTestsParensSpaces testDay "1912-07-08", --readTestsParensSpaces testDay "1912-7-8", readTestsParensSpaces testTimeOfDay "08:04:02" --,readTestsParensSpaces testTimeOfDay "8:4:2" ] where testDay = fromGregorian 1912 7 8 testTimeOfDay = TimeOfDay 8 4 2 epoch :: LocalTime epoch = LocalTime (fromGregorian 1970 0 0) midnight simpleFormatTests :: Test simpleFormatTests = testGroup "simple" [ readsTest [(epoch,"")] "" "", readsTest [(epoch," ")] "" " ", readsTest [(epoch,"")] " " " ", readsTest [(epoch,"")] " " " ", readsTest [(epoch,"")] "%k" "0", readsTest [(epoch,"")] "%k" " 0", readsTest [(epoch,"")] "%m" "01", readsTest [(epoch," ")] "%m" "01 ", readsTest [(epoch," ")] " %m" " 01 ", readsTest [(epoch,"")] " %m" " 01", -- https://ghc.haskell.org/trac/ghc/ticket/9150 readsTest [(epoch,"")] " %M" " 00", readsTest [(epoch,"")] "%M " "00 ", readsTest [(epoch,"")] "%Q" "", readsTest [(epoch," ")] "%Q" " ", readsTest [(epoch,"X")] "%Q" "X", readsTest [(epoch," X")] "%Q" " X", readsTest [(epoch,"")] "%Q " " ", readsTest [(epoch,"")] "%Q X" " X", readsTest [(epoch,"")] "%QX" "X" ] where readsTest :: (Show a, Eq a, ParseTime a) => [(a,String)] -> String -> String -> Test readsTest expected formatStr target = let found = readSTime False defaultTimeLocale formatStr target result = diff expected found name = (show formatStr) ++ " of " ++ (show target) in pureTest name result spacingTests :: (Show t, Eq t, ParseTime t) => t -> String -> String -> Test spacingTests expected formatStr target = testGroup "particular" [ parseTest False (Just expected) formatStr target, parseTest True (Just expected) formatStr target, parseTest False (Just expected) (formatStr ++ " ") (target ++ " "), parseTest True (Just expected) (formatStr ++ " ") (target ++ " "), parseTest False (Just expected) (" " ++ formatStr) (" " ++ target), parseTest True (Just expected) (" " ++ formatStr) (" " ++ target), parseTest True (Just expected) ("" ++ formatStr) (" " ++ target), parseTest True (Just expected) (" " ++ formatStr) (" " ++ target) ] particularParseTests :: Test particularParseTests = testGroup "particular" [ spacingTests epoch "%Q" "", spacingTests epoch "%Q" ".0", spacingTests epoch "%k" " 0", spacingTests epoch "%M" "00", spacingTests epoch "%m" "01", spacingTests (TimeZone 120 False "") "%z" "+0200", spacingTests (TimeZone 120 False "") "%Z" "+0200", spacingTests (TimeZone (-480) False "PST") "%Z" "PST" ] badParseTests :: Test badParseTests = testGroup "bad" [ parseTest False (Nothing :: Maybe Day) "%Y" "" ] parseYMD :: Day -> Test parseYMD day = case toGregorian day of (y,m,d) -> parseTest False (Just day) "%Y%m%d" ((show y) ++ (show2 m) ++ (show2 d)) parseYearDayD :: Day -> Test parseYearDayD day = case toGregorian day of (y,m,d) -> parseTest False (Just day) "%Y %m %d" ((show y) ++ " " ++ (show2 m) ++ " " ++ (show2 d)) parseYearDayE :: Day -> Test parseYearDayE day = case toGregorian day of (y,m,d) -> parseTest False (Just day) "%Y %-m %e" ((show y) ++ " " ++ (show m) ++ " " ++ (show d)) -- | 1969 - 2068 expectedYear :: Integer -> Integer expectedYear i | i >= 69 = 1900 + i expectedYear i = 2000 + i show2 :: (Show n,Integral n) => n -> String show2 i = (show (div i 10)) ++ (show (mod i 10)) parseYY :: Integer -> Test parseYY i = parseTest False (Just (fromGregorian (expectedYear i) 1 1)) "%y" (show2 i) parseCYY :: Integer -> Integer -> Test parseCYY c i = parseTest False (Just (fromGregorian ((c * 100) + i) 1 1)) "%-C %y" ((show c) ++ " " ++ (show2 i)) parseCYY2 :: Integer -> Integer -> Test parseCYY2 c i = parseTest False (Just (fromGregorian ((c * 100) + i) 1 1)) "%C %y" ((show2 c) ++ " " ++ (show2 i)) parseCentury :: String -> Integer -> Test parseCentury int c = parseTest False (Just (fromGregorian (c * 100) 1 1)) ("%-C" ++ int ++ "%y") ((show c) ++ int ++ "00") parseTest :: (Show t, Eq t, ParseTime t) => Bool -> Maybe t -> String -> String -> Test parseTest sp expected formatStr target = let found = parse sp formatStr target result = diff expected found name = (show formatStr) ++ " of " ++ (show target) ++ (if sp then " allowing spaces" else "") in pureTest name result {- readsTest :: forall t. (Show t, Eq t, ParseTime t) => Maybe t -> String -> String -> Test readsTest (Just e) = readsTest' [(e,"")] readsTest Nothing = readsTest' ([] :: [(t,String)]) -} enumAdd :: (Enum a) => Int -> a -> a enumAdd i a = toEnum (i + fromEnum a) getMilZoneLetter :: Int -> Char getMilZoneLetter 0 = 'Z' getMilZoneLetter h | h < 0 = enumAdd (negate h) 'M' getMilZoneLetter h | h < 10 = enumAdd (h - 1) 'A' getMilZoneLetter h = enumAdd (h - 10) 'K' getMilZone :: Int -> TimeZone getMilZone hour = TimeZone (hour * 60) False [getMilZoneLetter hour] testParseTimeZone :: TimeZone -> Test testParseTimeZone tz = parseTest False (Just tz) "%Z" (timeZoneName tz) defaultTimeZoneTests :: Test defaultTimeZoneTests = testGroup "default time zones" (fmap testParseTimeZone (knownTimeZones defaultTimeLocale)) militaryTimeZoneTests :: Test militaryTimeZoneTests = testGroup "military time zones" (fmap (testParseTimeZone . getMilZone) [-12 .. 12]) parse :: ParseTime t => Bool -> String -> String -> Maybe t parse sp f t = parseTimeM sp defaultTimeLocale f t format :: (FormatTime t) => String -> t -> String format f t = formatTime defaultTimeLocale f t instance Arbitrary Day where arbitrary = liftM ModifiedJulianDay $ choose (-313698, 2973483) -- 1000-01-1 to 9999-12-31 instance CoArbitrary Day where coarbitrary (ModifiedJulianDay d) = coarbitrary d instance Arbitrary DiffTime where arbitrary = oneof [intSecs, fracSecs] -- up to 1 leap second where intSecs = liftM secondsToDiffTime' $ choose (0, 86400) fracSecs = liftM picosecondsToDiffTime' $ choose (0, 86400 * 10^12) secondsToDiffTime' :: Integer -> DiffTime secondsToDiffTime' = fromInteger picosecondsToDiffTime' :: Integer -> DiffTime picosecondsToDiffTime' x = fromRational (x % 10^12) instance CoArbitrary DiffTime where coarbitrary t = coarbitrary (fromEnum t) instance Arbitrary TimeOfDay where arbitrary = liftM timeToTimeOfDay arbitrary instance CoArbitrary TimeOfDay where coarbitrary t = coarbitrary (timeOfDayToTime t) instance Arbitrary LocalTime where arbitrary = liftM2 LocalTime arbitrary arbitrary instance CoArbitrary LocalTime where coarbitrary t = coarbitrary (truncate (utcTimeToPOSIXSeconds (localTimeToUTC utc t)) :: Integer) instance Arbitrary TimeZone where arbitrary = liftM minutesToTimeZone $ choose (-720,720) instance CoArbitrary TimeZone where coarbitrary tz = coarbitrary (timeZoneMinutes tz) instance Arbitrary ZonedTime where arbitrary = liftM2 ZonedTime arbitrary arbitrary instance CoArbitrary ZonedTime where coarbitrary t = coarbitrary (truncate (utcTimeToPOSIXSeconds (zonedTimeToUTC t)) :: Integer) instance Arbitrary UTCTime where arbitrary = liftM2 UTCTime arbitrary arbitrary instance CoArbitrary UTCTime where coarbitrary t = coarbitrary (truncate (utcTimeToPOSIXSeconds t) :: Integer) instance Arbitrary UniversalTime where arbitrary = liftM (\n -> ModJulianDate $ n % k) $ choose (-313698 * k, 2973483 * k) where -- 1000-01-1 to 9999-12-31 k = 86400 instance CoArbitrary UniversalTime where coarbitrary (ModJulianDate d) = coarbitrary d -- missing from the time package instance Eq ZonedTime where ZonedTime t1 tz1 == ZonedTime t2 tz2 = t1 == t2 && tz1 == tz2 compareResult' :: (Eq a,Show a) => String -> a -> a -> Result compareResult' extra expected found | expected == found = succeeded | otherwise = failed {reason = "expected " ++ (show expected) ++ ", found " ++ (show found) ++ extra} compareResult :: (Eq a,Show a) => a -> a -> Result compareResult = compareResult' "" compareParse :: forall a. (Eq a,Show a,ParseTime a) => a -> String -> String -> Result compareParse expected fmt text = compareResult' (", parsing " ++ (show text)) (Just expected) (parse False fmt text) -- -- * tests for dbugging failing cases -- test_parse_format :: (FormatTime t,ParseTime t,Show t) => String -> t -> (String,String,Maybe t) test_parse_format f t = let s = format f t in (show t, s, parse False f s `asTypeOf` Just t) -- -- * show and read -- prop_read_show :: (Read a, Show a, Eq a) => a -> Result prop_read_show t = compareResult [(t,"")] (reads (show t)) prop_read_show' :: (Read a, Show a, Eq a) => a -> Result prop_read_show' t = compareResult t (read (show t)) -- -- * special show functions -- prop_parse_showWeekDate :: Day -> Result prop_parse_showWeekDate d = compareParse d "%G-W%V-%u" (showWeekDate d) prop_parse_showGregorian :: Day -> Result prop_parse_showGregorian d = compareParse d "%Y-%m-%d" (showGregorian d) prop_parse_showOrdinalDate :: Day -> Result prop_parse_showOrdinalDate d = compareParse d "%Y-%j" (showOrdinalDate d) -- -- * fromMondayStartWeek and fromSundayStartWeek -- prop_fromMondayStartWeek :: Day -> Result prop_fromMondayStartWeek d = let (w,wd) = mondayStartWeek d (y,_,_) = toGregorian d in compareResult d (fromMondayStartWeek y w wd) prop_fromSundayStartWeek :: Day -> Result prop_fromSundayStartWeek d = let (w,wd) = sundayStartWeek d (y,_,_) = toGregorian d in compareResult d (fromSundayStartWeek y w wd) -- -- * format and parse -- -- | Helper for defining named properties. prop_named :: (Arbitrary t, Show t, Testable a) => String -> (FormatString s -> t -> a) -> String -> FormatString s -> NamedProperty prop_named n prop typeName f = (n ++ " " ++ typeName ++ " " ++ show f, property (prop f)) prop_parse_format :: (Eq t, FormatTime t, ParseTime t, Show t) => FormatString t -> t -> Result prop_parse_format (FormatString f) t = compareParse t f (format f t) prop_parse_format_named :: (Arbitrary t, Eq t, Show t, FormatTime t, ParseTime t) => String -> FormatString t -> NamedProperty prop_parse_format_named = prop_named "prop_parse_format" prop_parse_format -- Verify case-insensitivity with upper case. prop_parse_format_upper :: (Eq t, FormatTime t, ParseTime t, Show t) => FormatString t -> t -> Result prop_parse_format_upper (FormatString f) t = compareParse t f (map toUpper $ format f t) prop_parse_format_upper_named :: (Arbitrary t, Eq t, Show t, FormatTime t, ParseTime t) => String -> FormatString t -> NamedProperty prop_parse_format_upper_named = prop_named "prop_parse_format_upper" prop_parse_format_upper -- Verify case-insensitivity with lower case. prop_parse_format_lower :: (Eq t, FormatTime t, ParseTime t, Show t) => FormatString t -> t -> Result prop_parse_format_lower (FormatString f) t = compareParse t f (map toLower $ format f t) prop_parse_format_lower_named :: (Arbitrary t, Eq t, Show t, FormatTime t, ParseTime t) => String -> FormatString t -> NamedProperty prop_parse_format_lower_named = prop_named "prop_parse_format_lower" prop_parse_format_lower prop_format_parse_format :: (FormatTime t, ParseTime t, Show t) => FormatString t -> t -> Result prop_format_parse_format (FormatString f) t = compareResult (Just (format f t)) (fmap (format f) (parse False f (format f t) `asTypeOf` Just t)) prop_format_parse_format_named :: (Arbitrary t, Show t, FormatTime t, ParseTime t) => String -> FormatString t -> NamedProperty prop_format_parse_format_named = prop_named "prop_format_parse_format" prop_format_parse_format -- -- * crashes in parse -- newtype Input = Input String instance Show Input where show (Input s) = s instance Arbitrary Input where arbitrary = liftM Input $ list cs where cs = elements (['0'..'9'] ++ ['-',' ','/'] ++ ['a'..'z'] ++ ['A' .. 'Z']) list g = sized (\n -> choose (0,n) >>= \l -> replicateM l g) instance CoArbitrary Input where coarbitrary (Input s) = coarbitrary (sum (map ord s)) prop_no_crash_bad_input :: (Eq t, ParseTime t) => FormatString t -> Input -> Property prop_no_crash_bad_input fs@(FormatString f) (Input s) = property $ case parse False f s of Nothing -> True Just t -> t == t `asTypeOf` formatType fs where prop_no_crash_bad_input_named :: (Eq t, ParseTime t) => String -> FormatString t -> NamedProperty prop_no_crash_bad_input_named = prop_named "prop_no_crash_bad_input" prop_no_crash_bad_input -- -- -- newtype FormatString a = FormatString String formatType :: FormatString t -> t formatType _ = undefined castFormatString :: FormatString a -> FormatString b castFormatString (FormatString f) = FormatString f instance Show (FormatString a) where show (FormatString f) = show f properties :: [NamedProperty] properties = [("prop_fromMondayStartWeek", property prop_fromMondayStartWeek), ("prop_fromSundayStartWeek", property prop_fromSundayStartWeek)] ++ [("prop_read_show Day", property (prop_read_show :: Day -> Result)), ("prop_read_show TimeOfDay", property (prop_read_show :: TimeOfDay -> Result)), ("prop_read_show LocalTime", property (prop_read_show :: LocalTime -> Result)), ("prop_read_show TimeZone", property (prop_read_show :: TimeZone -> Result)), ("prop_read_show ZonedTime", property (prop_read_show :: ZonedTime -> Result)), ("prop_read_show UTCTime", property (prop_read_show :: UTCTime -> Result)), ("prop_read_show UniversalTime", property (prop_read_show :: UniversalTime -> Result))] ++ [("prop_parse_showWeekDate", property prop_parse_showWeekDate), ("prop_parse_showGregorian", property prop_parse_showGregorian), ("prop_parse_showOrdinalDate", property prop_parse_showOrdinalDate)] ++ map (prop_parse_format_named "Day") dayFormats ++ map (prop_parse_format_named "TimeOfDay") timeOfDayFormats ++ map (prop_parse_format_named "LocalTime") localTimeFormats ++ map (prop_parse_format_named "TimeZone") timeZoneFormats ++ map (prop_parse_format_named "ZonedTime") zonedTimeFormats ++ map (prop_parse_format_named "UTCTime") utcTimeFormats ++ map (prop_parse_format_named "UniversalTime") universalTimeFormats ++ map (prop_parse_format_upper_named "Day") dayFormats ++ map (prop_parse_format_upper_named "TimeOfDay") timeOfDayFormats ++ map (prop_parse_format_upper_named "LocalTime") localTimeFormats ++ map (prop_parse_format_upper_named "TimeZone") timeZoneFormats ++ map (prop_parse_format_upper_named "ZonedTime") zonedTimeFormats ++ map (prop_parse_format_upper_named "UTCTime") utcTimeFormats ++ map (prop_parse_format_upper_named "UniversalTime") universalTimeFormats ++ map (prop_parse_format_lower_named "Day") dayFormats ++ map (prop_parse_format_lower_named "TimeOfDay") timeOfDayFormats ++ map (prop_parse_format_lower_named "LocalTime") localTimeFormats ++ map (prop_parse_format_lower_named "TimeZone") timeZoneFormats ++ map (prop_parse_format_lower_named "ZonedTime") zonedTimeFormats ++ map (prop_parse_format_lower_named "UTCTime") utcTimeFormats ++ map (prop_parse_format_lower_named "UniversalTime") universalTimeFormats ++ map (prop_format_parse_format_named "Day") partialDayFormats ++ map (prop_format_parse_format_named "TimeOfDay") partialTimeOfDayFormats ++ map (prop_format_parse_format_named "LocalTime") partialLocalTimeFormats ++ map (prop_format_parse_format_named "ZonedTime") partialZonedTimeFormats ++ map (prop_format_parse_format_named "UTCTime") partialUTCTimeFormats ++ map (prop_format_parse_format_named "UniversalTime") partialUniversalTimeFormats ++ map (prop_no_crash_bad_input_named "Day") (dayFormats ++ partialDayFormats ++ failingPartialDayFormats) ++ map (prop_no_crash_bad_input_named "TimeOfDay") (timeOfDayFormats ++ partialTimeOfDayFormats) ++ map (prop_no_crash_bad_input_named "LocalTime") (localTimeFormats ++ partialLocalTimeFormats) ++ map (prop_no_crash_bad_input_named "TimeZone") (timeZoneFormats) ++ map (prop_no_crash_bad_input_named "ZonedTime") (zonedTimeFormats ++ partialZonedTimeFormats) ++ map (prop_no_crash_bad_input_named "UTCTime") (utcTimeFormats ++ partialUTCTimeFormats) ++ map (prop_no_crash_bad_input_named "UniversalTime") (universalTimeFormats ++ partialUniversalTimeFormats) dayFormats :: [FormatString Day] dayFormats = map FormatString [ -- numeric year, month, day "%Y-%m-%d","%Y%m%d","%C%y%m%d","%Y %m %e","%m/%d/%Y","%d/%m/%Y","%Y/%d/%m","%D %C","%F", -- month names "%Y-%B-%d","%Y-%b-%d","%Y-%h-%d", -- ordinal dates "%Y-%j", -- ISO week dates "%G-%V-%u","%G-%V-%a","%G-%V-%A","%G-%V-%w", "%A week %V, %G", "day %V, week %A, %G", "%G-W%V-%u", "%f%g-%V-%u","%f%g-%V-%a","%f%g-%V-%A","%f%g-%V-%w", "%A week %V, %f%g", "day %V, week %A, %f%g", "%f%g-W%V-%u", -- monday and sunday week dates "%Y-w%U-%A", "%Y-w%W-%A", "%Y-%A-w%U", "%Y-%A-w%W", "%A week %U, %Y", "%A week %W, %Y" ] timeOfDayFormats :: [FormatString TimeOfDay] timeOfDayFormats = map FormatString [ -- 24 h formats "%H:%M:%S.%q","%k:%M:%S.%q","%H%M%S.%q","%T.%q","%X.%q","%R:%S.%q", "%H:%M:%S%Q","%k:%M:%S%Q","%H%M%S%Q","%T%Q","%X%Q","%R:%S%Q", -- 12 h formats "%I:%M:%S.%q %p","%I:%M:%S.%q %P","%l:%M:%S.%q %p","%r %q", "%I:%M:%S%Q %p","%I:%M:%S%Q %P","%l:%M:%S%Q %p","%r %Q" ] localTimeFormats' :: [FormatString LocalTime] localTimeFormats' = map FormatString $ concat [ [df ++ " " ++ tf, tf ++ " " ++ df] | FormatString df <- dayFormats, FormatString tf <- timeOfDayFormats] localTimeFormats :: [FormatString LocalTime] localTimeFormats = map FormatString [{-"%Q","%Q ","%QX"-}] timeZoneFormats :: [FormatString TimeZone] timeZoneFormats = map FormatString ["%z","%z%Z","%Z%z","%Z"] zonedTimeFormats :: [FormatString ZonedTime] zonedTimeFormats = map FormatString ["%a, %d %b %Y %H:%M:%S.%q %z", "%a, %d %b %Y %H:%M:%S%Q %z", "%s.%q %z", "%s%Q %z", "%a, %d %b %Y %H:%M:%S.%q %Z", "%a, %d %b %Y %H:%M:%S%Q %Z", "%s.%q %Z", "%s%Q %Z"] utcTimeFormats :: [FormatString UTCTime] utcTimeFormats = map FormatString ["%s.%q","%s%Q"] universalTimeFormats :: [FormatString UniversalTime] universalTimeFormats = map FormatString [] -- -- * Formats that do not include all the information -- partialDayFormats :: [FormatString Day] partialDayFormats = map FormatString [ ] partialTimeOfDayFormats :: [FormatString TimeOfDay] partialTimeOfDayFormats = map FormatString [ ] partialLocalTimeFormats :: [FormatString LocalTime] partialLocalTimeFormats = map FormatString [ ] partialZonedTimeFormats :: [FormatString ZonedTime] partialZonedTimeFormats = map FormatString [ -- %s does not include second decimals "%s %z", -- %S does not include second decimals "%c", "%a, %d %b %Y %H:%M:%S %Z" ] partialUTCTimeFormats :: [FormatString UTCTime] partialUTCTimeFormats = map FormatString [ -- %s does not include second decimals "%s", -- %c does not include second decimals "%c" ] partialUniversalTimeFormats :: [FormatString UniversalTime] partialUniversalTimeFormats = map FormatString [ ] -- -- * Known failures -- knownFailures :: [NamedProperty] knownFailures = map (prop_format_parse_format_named "Day") failingPartialDayFormats failingPartialDayFormats :: [FormatString Day] failingPartialDayFormats = map FormatString [ -- ISO week dates with two digit year. -- This can fail in the beginning or the end of a year where -- the ISO week date year does not match the gregorian year. "%g-%V-%u","%g-%V-%a","%g-%V-%A","%g-%V-%w", "%A week %V, %g", "day %V, week %A, %g", "%g-W%V-%u" ]
bergmark/time
test/Test/TestParseTime.hs
bsd-3-clause
23,340
0
45
4,413
7,183
3,814
3,369
419
2
module Main where import Control.DeepSeq (NFData(rnf)) import Common import qualified Data.List import qualified TS.B01 import qualified Data.Table as T main :: IO () main = do return $! rnf elements return $! rnf test test :: TS.B01.TS test = fromList elements elements :: [C01] elements = map (\x -> C01 x (x `div` s) [x .. x + s]) [0 .. 40000] where s = 5 fromList :: [C01] -> TS.B01.TS fromList = Data.List.foldl' (\acc x -> insert x $! acc) TS.B01.empty insert :: C01 -> TS.B01.TS -> TS.B01.TS insert t x = snd $! T.insert' t x
Palmik/data-store
benchmarks/src/TSSO.hs
bsd-3-clause
551
0
10
116
245
139
106
19
1
module Module4.Task23 where data Tree a = Leaf a | Node (Tree a) (Tree a) height :: Tree a -> Int height (Leaf _) = 0 height (Node l r) = 1 + max (height l) (height r) size :: Tree a -> Int size (Leaf _) = 1 size (Node l r) = 1 + size l + size r
dstarcev/stepic-haskell
src/Module4/Task23.hs
bsd-3-clause
260
0
8
75
154
78
76
8
1
module Ifrit.Client.DummySpec where import Ifrit.Client.Dummy import Ifrit.Framework import Test.Hspec spec = do describe "A dummy client" $ do it "can send a simple message" $ do let message = TitledMessage "awesome title" "amazing content!" response <- send Dummy message response `shouldBe` True it "can receive a message (this terminology should be changed...)" $ do message <- receive Dummy message `shouldBe` (TitledMessage "noop" "noop")
frio/ifrit
test/hs/Ifrit/Client/DummySpec.hs
bsd-3-clause
487
0
16
105
120
59
61
13
1
-- -- Copyright © 2014-2015 Anchor Systems, Pty Ltd and Others -- -- The code in this file, and the program it is a part of, is -- made available to you by its authors as open source software: -- you can redistribute it and/or modify it under the terms of -- the 3-clause BSD licence. -- {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} -- | Description: Unique identifiers for internal an external use. module Synchronise.Identifier ( -- * Configuration names EntityName(..), SourceName(..), -- * Unique identifiers InternalID, ForeignID, ForeignKey(..), InternalKey(..), -- * Checking compatibility Synchronisable(..), compatibleEntity, compatibleSource, ) where import Data.Aeson.TH import Data.String import Data.Text (Text) import qualified Data.Text as T import Database.PostgreSQL.Simple.ToField import Database.PostgreSQL.Simple.ToRow -- | Unique name for an entity. newtype EntityName = EntityName { ename :: Text } deriving (Eq, Ord) instance IsString EntityName where fromString = EntityName . T.pack instance Show EntityName where show = T.unpack . ename instance Read EntityName where readsPrec _ s = [(EntityName (T.pack s), "")] -- | Unique name for a data source. newtype SourceName = SourceName { sname :: Text } deriving (Eq, Ord) instance Show SourceName where show = T.unpack . sname instance IsString SourceName where fromString = SourceName . T.pack instance Read SourceName where readsPrec _ s = [(SourceName (T.pack s), "")] -- | Types which participate, in one way or another, in the synchronisation -- process. class Synchronisable a where -- | Get the 'EntityName' for which the value is valid. getEntityName :: a -> EntityName -- | Get the 'SourceName' for which the value is valid. getSourceName :: a -> SourceName -------------------------------------------------------------------------------- type InternalID = Int type ForeignID = Text -- | Uniquely identify a 'Document' shared across one or more 'DataSource's. -- -- Each 'InternalKey' value can be mapped to the 'ForeignKey's for the -- 'DataSource's which store copies of the associated 'Document'. data InternalKey = InternalKey { ikEntity :: EntityName , ikID :: InternalID } deriving (Eq, Ord, Show) instance Synchronisable InternalKey where getEntityName = ikEntity getSourceName _ = SourceName "" -- | Uniquely identify a 'Document' stored in 'DataSource'. data ForeignKey = ForeignKey { fkEntity :: EntityName , fkSource :: SourceName , fkID :: ForeignID } deriving (Eq, Ord, Show) instance Synchronisable ForeignKey where getEntityName = fkEntity getSourceName = fkSource -- json $(deriveJSON defaultOptions ''EntityName) $(deriveJSON defaultOptions ''SourceName) $(deriveJSON defaultOptions ''ForeignKey) -- postgres instance ToField EntityName where toField (EntityName n) = toField n instance ToField SourceName where toField (SourceName n) = toField n instance ToRow ForeignKey where toRow (ForeignKey a b c) = toRow (a,b,c) instance ToRow InternalKey where toRow (InternalKey a b) = toRow (a,b) -------------------------------------------------------------------------------- -- | Check that two synchronisable values have the same entity. compatibleEntity :: (Synchronisable a, Synchronisable b) => a -> b -> Bool compatibleEntity a b = getEntityName a == getEntityName b -- | Check that two synchronisable values have the same data source. compatibleSource :: (Synchronisable a, Synchronisable b) => a -> b -> Bool compatibleSource a b = compatibleEntity a b && getSourceName a == getSourceName b
anchor/synchronise
lib/Synchronise/Identifier.hs
bsd-3-clause
3,734
0
11
721
757
430
327
76
1
module Graphics.Gnuplot.Private.ColorSpecification where import Graphics.Gnuplot.Utility (quote, ) import Data.List.HT (padLeft, ) import Data.Word (Word8, ) import Numeric (showHex, ) data T = Name String | RGB8 {red, green, blue :: Word8} | PaletteFrac Double toString :: T -> String toString c = case c of Name name -> "rgbcolor " ++ quote name RGB8 r g b -> "rgbcolor " ++ quote ("#" ++ concatMap (padLeft '0' 2 . flip showHex "") [r,g,b]) PaletteFrac frac -> "palette frac " ++ show frac
kubkon/gnuplot
src/Graphics/Gnuplot/Private/ColorSpecification.hs
bsd-3-clause
548
0
15
137
192
108
84
17
3
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Types ( GhcSource(..) , Options(..) , HsenvState(..) , DirStructure(..) , HsenvException(..) , Verbosity(..) ) where import Control.Monad.Error (Error) data GhcSource = System -- Use System's copy of GHC | Tarball FilePath -- Use GHC from tarball | Url String -- Use GHC downloadable at URL | Release String -- Infer a URL and use GHC from there data Verbosity = Quiet | Verbose | VeryVerbose deriving (Eq, Ord) data Options = Options { verbosity :: Verbosity , skipSanityCheck :: Bool , hsEnvName :: Maybe String -- Virtual Haskell Environment name , ghcSource :: GhcSource , makeCmd :: String -- make substitute used for 'make install' of external GHC , noSharing :: Bool -- don't share ~/.cabal/packages , noPS1 :: Bool -- Don't modify shell prompt } data HsenvState = HsenvState { logDepth :: Integer -- used for indentation of logging messages } newtype HsenvException = HsenvException { getExceptionMessage :: String } deriving Error -- Only absolute paths! data DirStructure = DirStructure { hsEnv :: FilePath -- dir containing .hsenv_ENVNAME dir -- (usually dir with cabal project) , hsEnvDir :: FilePath -- .hsenv_ENVNAME dir , ghcPackagePath :: FilePath -- file (<ghc-6.12) or dir (>=ghc-6.12) containing private GHC pkg db , cabalDir :: FilePath -- directory with private cabal dir , cabalBinDir :: FilePath -- cabal's bin/ dir (used in $PATH) , hsEnvBinDir :: FilePath -- dir with haskell tools wrappers and activate script , ghcDir :: FilePath -- directory with private copy of external GHC (only used when using GHC from tarball) , ghcBinDir :: FilePath -- ghc's bin/ dir (with ghc[i|-pkg]) (only used when using GHC from tarball) }
tmhedberg/hsenv
src/Types.hs
bsd-3-clause
2,479
0
9
1,055
267
179
88
34
0
{-# LANGUAGE NamedFieldPuns, OverloadedStrings #-} module MusicPad.Core.Scene where import MusicPad.Env import Prelude () import qualified Prelude as P import MusicPad.Model.Sample import MusicPad.Toolkit.Console import MusicPad.Model import Rika.Engine.Render.GL.Helper (camera_view_space_hit_test, camera_view_m) import qualified Rika.Type as Rika import Control.Arrow ((&&&)) import MusicPad.Env.Constant excape_to_exit :: IOAction State excape_to_exit g x = do _env <- read - g.env when (_env.input.keys.map key_code .has ('\27')) - g.global_state $= GameEnded play_sound_action :: IOAction State play_sound_action g x = do game_object <- read x when (game_object.tag.is (Just - Tag "speaker")) - do with_state g - \_state -> do let current_verse = _state.song.verses.at (_state.song.current_verse_index) _env <- read - g.env let t = _env.game_time.current_script_time t0 = _state.loop_start_time delta_time = current_verse.tempo.tempo_to_interval elapsed_time = t + (-t0) _beats = current_verse.beats current_beat = floor - elapsed_time / delta_time -- log - "t0: " ++ show t0 -- log - "t: " ++ show t -- log - show elapsed_time -- log - show current_beat with_state g - \_state -> do let current_track = current_verse.tracks.at (current_verse.current_track_index) let { active_tracks = if _state.song.solo then [current_track] else current_verse.tracks } when ( _state.last_beat P.< current_beat) - do g.state $~ set __last_beat current_beat let beat = current_beat `P.mod` _beats notes_on_beat track = track.notes.select note_enabled .select (note_y > is beat) active_tracks.mapM_ (\active_track -> do active_track.notes_on_beat.mapM_ (play_note g active_track) ) current_track.notes_on_beat .highlight_notes g delta_time highlight_notes :: Game State -> Double -> [TrackNote] -> IO () highlight_notes g delta_time notes = do let ids = notes.map (note_x &&& note_y) _scene <- read - g.scene _scene.objects.filterT (tag > is (Just - Tag "note")) >>= mapM_ (\o -> do _attributes <- note_data o _attributes.want - \_attr -> do when ( (_attr.note_index_x, _attr.note_index_y ).belongs_to ids ) - do highlight_note g delta_time o ) play_note :: Game State -> Track -> TrackNote -> IO () play_note g track note = do with_state g - \_state -> do let _sample_db = _state.sample_db _sample_db.find (sample_id > is (track.track_sample_id)) .want - \sample -> do let ind = note.note_x scale_loop i xs = [0,12 ..].concat_map (\i -> xs.map (+i)) .take i max_scale = _state.app_env.pad_width + 1 offset = track.scale .scale_loop max_scale .at ind note_abs_pitch = track.key.absPitch + offset let sorted_notes = sample.samples.sortBy (compare_by (sample_pitch > absPitch > (P.- note_abs_pitch) > abs )) let closest_note = sorted_notes.first path = closest_note.sample_path play_audio path logf g - show note is_in_square_of :: (Real a) => a -> (a, a) -> (a, a) -> Bool is_in_square_of radius (origin_x, origin_y) (point_x, point_y) = ( abs( origin_x + (-point_x) ) <= radius ) && ( abs( origin_y + (-point_y) ) <= radius ) touch_note_action :: IOAction State touch_note_action g x = do _env <- read - g.env let _touches = _env.input.touches.select (touch_type > is TouchUp) when (_touches.null.not) - do _scene <- read - g.scene let _touch = _touches.first _pos = _touch.touch_pos _screen_pos = Vector2 (_pos.x2) (_env.window_height.from_i + (-_pos.y2)) main_camera _scene.wantM - \_camera -> do let { _hit_ray = camera_view_space_hit_test (_env.window_width.from_i, _env.window_height.from_i) (_screen_pos.x2) (_screen_pos.y2) _camera } _camera_object <- main_camera_object _scene let inv_view_matrix = _camera_object.fromMaybe def .camera_view_m .invert_matrix Vector4 touch_pos_x touch_pos_y _ _ = inv_view_matrix `mul` _hit_ray.fst _scene.objects.filterT (tag > is (Just - Tag "note")) >>= mapM_ (\o -> do _game_object <- read o let pos_x = _game_object.transform.position.x3 pos_y = _game_object.transform.position.y3 hit = is_in_square_of c_square_radius (pos_x, pos_y) (touch_pos_x, touch_pos_y) when hit - do _attributes <- note_data o _attributes.want - \_attr -> do logf g - "found note: " ++ show _attributes touch_note_on_object g o (_attr.note_index_x) (_attr.note_index_y) logf g - "origin: " ++ show (pos_x, pos_y) logf g - "point: " ++ show (touch_pos_x, touch_pos_y) ) touch_track_action :: IOAction State touch_track_action g x = do _env <- read - g.env let _touches = _env.input.touches.select (touch_type > is TouchUp) when (_touches.null.not) - do _scene <- read - g.scene let _touch = _touches.first _pos = _touch.touch_pos _screen_pos = Vector2 (_pos.x2) (_env.window_height.from_i + (-_pos.y2)) main_camera _scene.wantM - \_camera -> do let { _hit_ray = camera_view_space_hit_test (_env.window_width.from_i, _env.window_height.from_i) (_screen_pos.x2) (_screen_pos.y2) _camera } _camera_object <- main_camera_object _scene let inv_view_matrix = _camera_object.fromMaybe def .camera_view_m .invert_matrix Vector4 touch_pos_x touch_pos_y _ _ = inv_view_matrix `mul` _hit_ray.fst _scene.objects.filterT (tag > is (Just - Tag "track")) >>= mapM_ (\o -> do _game_object <- read o let pos_x = _game_object.transform.position.x3 pos_y = _game_object.transform.position.y3 hit = is_in_square_of c_square_radius (pos_x, pos_y) (touch_pos_x, touch_pos_y) when hit - do _attributes <- track_data o _attributes.want - \_attr -> do logf g - "found note: " ++ show _attributes set_active_track_on_object g o (_attr.track_no) update_all_note_color g ) touch_verse_action :: IOAction State touch_verse_action g x = do _env <- read - g.env let _touches = _env.input.touches.select (touch_type > is TouchUp) when (_touches.null.not) - do _scene <- read - g.scene let _touch = _touches.first _pos = _touch.touch_pos _screen_pos = Vector2 (_pos.x2) (_env.window_height.from_i + (-_pos.y2)) main_camera _scene.wantM - \_camera -> do let { _hit_ray = camera_view_space_hit_test (_env.window_width.from_i, _env.window_height.from_i) (_screen_pos.x2) (_screen_pos.y2) _camera } _camera_object <- main_camera_object _scene let inv_view_matrix = _camera_object.fromMaybe def .camera_view_m .invert_matrix Vector4 touch_pos_x touch_pos_y _ _ = inv_view_matrix `mul` _hit_ray.fst _scene.objects.filterT (tag > is (Just - Tag "verse")) >>= mapM_ (\o -> do _game_object <- read o let pos_x = _game_object.transform.position.x3 pos_y = _game_object.transform.position.y3 hit = is_in_square_of c_square_radius (pos_x, pos_y) (touch_pos_x, touch_pos_y) when hit - do _attributes <- verse_data o _attributes.want - \_attr -> do logf g - "found verse: " ++ show _attributes set_active_verse_on_object g o (_attr.verse_no) update_all_track_color g update_all_note_color g ) touch_home_action :: IOAction State touch_home_action g x = do _env <- read - g.env let _touches = _env.input.touches.select (touch_type > is TouchUp) when (_touches.null.not) - do _scene <- read - g.scene let _touch = _touches.first _pos = _touch.touch_pos _screen_pos = Vector2 (_pos.x2) (_env.window_height.from_i + (-_pos.y2)) main_camera _scene.wantM - \_camera -> do let { _hit_ray = camera_view_space_hit_test (_env.window_width.from_i, _env.window_height.from_i) (_screen_pos.x2) (_screen_pos.y2) _camera } _camera_object <- main_camera_object _scene let inv_view_matrix = _camera_object.fromMaybe def .camera_view_m .invert_matrix Vector4 touch_pos_x touch_pos_y _ _ = inv_view_matrix `mul` _hit_ray.fst _scene.objects.filterT (tag > is (Just - Tag "home")) >>= mapM_ (\o -> do _game_object <- read o let pos_x = _game_object.transform.position.x3 pos_y = _game_object.transform.position.y3 hit = is_in_square_of c_square_radius (pos_x, pos_y) (touch_pos_x, touch_pos_y) when hit - do g.global_state $= GameEnded ) tempo_to_interval :: Double -> Double tempo_to_interval = (15 /) debug_script :: IOAction State debug_script g x = do -- e <- read - g.env -- let fps_str = e.game_time.fps .printf "%2.0f" -- logf g - fps_str return () show_touch :: IOAction State show_touch g x = don't - do _env <- read - g.env let _touches = _env.input.touches.select (touch_type > is TouchUp) when (_touches.null.not) - do let _touch = _touches.first _pos = _touch.touch_pos _screen_pos = Vector2 (_pos.x2) (_env.window_height.from_i + (-_pos.y2)) _scene <- read - g.scene main_camera _scene.wantM - \_camera -> do let { _hit_ray = camera_view_space_hit_test (_env.window_width.from_i, _env.window_height.from_i) (_screen_pos.x2) (_screen_pos.y2) _camera } _scene.objects.mapM_ (\game_object -> do _game_object <- read game_object logf g - show _hit_ray logf g - show - _game_object.transform.position ) note_position_from_index :: (Int, Int) -> (RikaPrim, RikaPrim) note_position_from_index (idx_x, idx_y) = (( idx_x.from_i + (-5) ) * 2, (-idx_y.from_i + 8) * 2 ) init_pad_scene :: Game State -> (Scene State) -> IO (Scene State) init_pad_scene g _scene = do logf g - "init pad scene" _state <- read - g.state let _app_env = _state.app_env from_prefab :: GameObject a -> GameObject a -> GameObject a from_prefab prefab o = o {mesh = prefab.mesh, renderer = prefab.renderer} button_note_prefab <- _scene.objects.find_or_fail_with_message_T "Button.Note.Prefab" (name > unpack > is "Button.Note.Prefab") _button_note_prefab <- read button_note_prefab button_note_objects <- mapM newTVarIO - do index_x <- [ 0 .. _app_env.pad_width ] index_y <- [ 0 .. _app_env.pad_height ] let attributes = Just - def {note_index_x = index_x, note_index_y = index_y} .encodeJSON position_2d = note_position_from_index (index_x, index_y) position = Vector3 (position_2d.fst) (position_2d.snd) 1.0 _transform = _button_note_prefab.transform.set __position position tag = Just - Tag "note" return - def { tag, attributes, transform = _transform, renderer = _button_note_prefab.renderer, prefab = Just button_note_prefab } button_track_prefab <- _scene.objects.find_or_fail_with_message_T "Button.Track.Prefab" (name > unpack > is "Button.Track.Prefab") _button_track_prefab <- read button_track_prefab button_track_objects <- mapM newTVarIO - do index_x <- [ 0 .. _app_env.pad_width ] let position_from_index idx_x = (( idx_x.from_i + (-5) ) * 2, -17) attributes = Just - def {track_no = index_x} .encodeJSON position_2d = position_from_index index_x position = Vector3 (position_2d.fst) (position_2d.snd) 1.0 _transform = _button_track_prefab.transform.set __position position tag = Just - Tag "track" r = _button_track_prefab.renderer _renderer = if index_x.is 0 then r.fmap (set __materials [ Linked "TrackEnabled" ] ) else r return - def { tag, attributes, transform = _transform, prefab = Just button_track_prefab, renderer = _renderer} button_verse_prefab <- _scene.objects.find_or_fail_with_message_T "Button.Verse.Prefab" (name > unpack > is "Button.Verse.Prefab") _button_verse_prefab <- read button_verse_prefab button_verse_objects <- mapM newTVarIO - do index_y <- [ 0 .. _app_env.pad_height ] let position_from_index idx_y = (11, (-idx_y.from_i + 8) * 2 ) attributes = Just - def {verse_no = index_y} .encodeJSON position_2d = position_from_index index_y position = Vector3 (position_2d.fst) (position_2d.snd) 1.0 _transform = _button_verse_prefab.transform.set __position position tag = Just - Tag "verse" r = _button_verse_prefab.renderer _renderer = if index_y.is 0 then r.fmap (set __materials [ Linked "VerseEnabled" ] ) else r return - def { tag, attributes, transform = _transform, prefab = Just button_verse_prefab , renderer = _renderer} button_verse_prefab <- _scene.objects.find_or_fail_with_message_T "Button.Home.Prefab" (name > unpack > is "Button.Home.Prefab") _button_verse_prefab <- read button_verse_prefab button_home_objects <- mapM newTVarIO - do let position_2d = (11, -17) position = Vector3 (position_2d.fst) (position_2d.snd) 1.0 tag = Just - Tag "home" _transform = _button_verse_prefab.transform.set __position position return - def { tag, transform = _transform, prefab = Just button_verse_prefab } let button_objects = button_note_objects ++ button_track_objects ++ button_verse_objects ++ button_home_objects speaker_object <- newTVarIO def let _objects = speaker_object : button_objects speaker_object $~ set __tag (Just - Tag "speaker") _scene <- read - g.scene let { scene = _scene .mod __objects (++ _objects) .set __background_color (Vector4 0.88 0.88 0.88 0) .set ( __renderer_config > __with_normal_buffer ) False .set ( __renderer_config > __with_depth_buffer ) False .set ( __renderer_config > __with_color_buffer ) False .set ( __scene_config > __output_fps_to_console ) True } speaker_object.attach_io_action play_sound_action scene.objects .filterT (name > is "Camera") >>= mapM_ (\o -> do -- Game State o.attach_io_action excape_to_exit -- Debug -- o.attach_io_action debug_script -- o.attach_input_action show_touch -- Game Logic o.attach_input_action touch_note_action o.attach_input_action touch_track_action o.attach_input_action touch_verse_action o.attach_input_action touch_home_action ) scene.update_all_object_matrix_cache return scene init_hook :: Game State -> (Scene State) -> IO (Scene State) init_hook g s = do _scene <- init_pad_scene g s logf g "before hook done" -- less CPU intensive to prevent crash >< -- g.env $~ set __script_update_interval 1.0 -- g.env $~ set __display_update_interval 1.0 return _scene before_hook :: Game State -> (Scene State) -> IO (Scene State) before_hook g s = do init_pad g return s after_hook :: Game State -> (Scene State) -> IO (Scene State) after_hook g s = do logf g - "saving scrap pad" save_scrap_pad g return s default_state :: State default_state = init_state c_pad_width c_pad_height default_sample_id :: SampleID default_sample_id = def { sample_name = "Wide Marimba" , sample_author = "mp" } init_song :: Int -> Int -> Song init_song pad_width pad_height = let notes = [def {note_x, note_y} | note_x <- [ 0 .. pad_width ], note_y <- [ 0 .. pad_height ] ] track_sample_id = default_sample_id scale = [0, 2, 4, 7, 9] key = (D, 4) track = def {notes, track_sample_id, scale, key} track_number = pad_width tracks = (track_number + 1).times track tempo = 120 beats = pad_height + 1 verse = def {tracks, tempo, beats} verse_number = pad_height verses = (verse_number + 1).times verse song = def {verses, song_version = _song_version} in song init_state :: Int -> Int -> State init_state pad_width pad_height = let song = init_song pad_width pad_height app_env = def { pad_width, pad_height } in def {song, app_env, state_version = _state_version} scene_hook :: Hook State (Scene State) IO scene_hook = def { initialize = Just init_hook , before = Just before_hook , after = Just after_hook , dealloc = Nothing }
nfjinjing/level5
src/MusicPad/Core/Scene.hs
bsd-3-clause
17,397
25
29
4,773
5,077
2,566
2,511
-1
-1
module Prose.CharSet ((∩),(∪),(⊙),(∖),(¬), module Data.CharSet) where import Data.CharSet hiding (map,filter) (⊙) :: [Char] -> CharSet (⊙) = fromList (∩) = intersection (∪) = union infixl 7 ∩ infixl 6 ∪ (∖) = difference infixl 6 ∖ (¬) = complement infixl 7 ¬
llelf/prose
Prose/CharSet.hs
bsd-3-clause
319
0
6
75
122
84
38
13
1
{-# LANGUAGE UnicodeSyntax #-} import Prelude.Unicode
m00nlight/99-problems
haskell/p-91.hs
bsd-3-clause
56
0
4
8
7
4
3
2
0
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} module Main ( main ) where import Control.Monad.IO.Class (liftIO) import Data.Aeson (FromJSON (..), defaultOptions, genericParseJSON, genericToJSON, object, (.=)) import Data.List.NonEmpty (NonEmpty (..)) import Data.Text (Text) 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 (defaultManagerSettings) data TweetMapping = TweetMapping deriving (Eq, Show) instance ToJSON TweetMapping where toJSON TweetMapping = object [ "properties" .= object ["location" .= object ["type" .= ("geo_point" :: Text)]] ] data Tweet = Tweet { user :: Text , postDate :: UTCTime , message :: Text , age :: Int , location :: LatLon } deriving (Eq, Generic, Show) exampleTweet :: Tweet exampleTweet = Tweet { user = "bitemyapp" , postDate = UTCTime (ModifiedJulianDay 55000) (secondsToDiffTime 10) , message = "Use haskell!" , age = 10000 , location = loc } where loc = LatLon {lat = 40.12, lon = -71.3} instance ToJSON Tweet where toJSON = genericToJSON defaultOptions instance FromJSON Tweet where parseJSON = genericParseJSON defaultOptions main :: IO () main = runBH' $ do -- set up index _ <- createIndex indexSettings testIndex True <- indexExists testIndex _ <- putMapping testIndex TweetMapping -- create a tweet resp <- indexDocument testIndex defaultIndexDocumentSettings exampleTweet (DocId "1") liftIO (print resp) -- Response {responseStatus = Status {statusCode = 201, statusMessage = "Created"}, responseVersion = HTTP/1.1, responseHeaders = [("Content-Type","application/json; charset=UTF-8"),("Content-Length","74")], responseBody = "{\"_index\":\"twitter\",\"_type\":\"tweet\",\"_id\":\"1\",\"_version\":1,\"created\":true}", responseCookieJar = CJ {expose = []}, responseClose' = ResponseClose} -- bulk load let stream = V.fromList [BulkIndex testIndex (DocId "2") (toJSON exampleTweet)] _ <- bulk stream -- Bulk loads require an index refresh before new data is loaded. _ <- refreshIndex testIndex -- set up some aliases let aliasName = IndexName "twitter-alias" let iAlias = IndexAlias testIndex (IndexAliasName aliasName) let aliasRouting = Nothing let aliasFiltering = Nothing let aliasCreate = IndexAliasCreate aliasRouting aliasFiltering _ <- updateIndexAliases (AddAlias iAlias aliasCreate :| []) True <- indexExists aliasName -- create a template so that if we just write into an index named tweet-2017-01-02, for instance, the index will be automatically created with the given mapping. This is a great idea for any ongoing indices because it makes them much easier to manage and rotate. let idxTpl = IndexTemplate [IndexPattern "tweet-*"] (Just (IndexSettings (ShardCount 1) (ReplicaCount 1))) (toJSON TweetMapping) let templateName = TemplateName "tweet-tpl" tplResp <- putTemplate idxTpl templateName liftIO (print tplResp) True <- templateExists templateName -- do a search let boost = Nothing let query = TermQuery (Term "user" "bitemyapp") boost let search = mkSearch (Just query) boost tweetResp <- searchByIndex testIndex search liftIO (print tweetResp) -- clean up _ <- deleteTemplate templateName _ <- deleteIndex testIndex False <- indexExists testIndex return () where testServer = Server "http://localhost:9200" runBH' = withBH defaultManagerSettings testServer testIndex = IndexName "twitter" indexSettings = IndexSettings (ShardCount 1) (ReplicaCount 0)
bitemyapp/bloodhound
examples/Tweet.hs
bsd-3-clause
3,937
0
17
896
897
466
431
77
1
{- (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 \section[ConFold]{Constant Folder} Conceptually, constant folding should be parameterized with the kind of target machine to get identical behaviour during compilation time and runtime. We cheat a little bit here... ToDo: check boundaries before folding, e.g. we can fold the Float addition (i1 + i2) only if it results in a valid Float. -} {-# LANGUAGE CPP, RankNTypes #-} {-# OPTIONS_GHC -optc-DNON_POSIX_SOURCE #-} module PrelRules ( primOpRules, builtinRules ) where #include "HsVersions.h" #include "../includes/MachDeps.h" import {-# SOURCE #-} MkId ( mkPrimOpId, magicDictId ) import CoreSyn import MkCore import Id import Literal import CoreSubst ( exprIsLiteral_maybe ) import PrimOp ( PrimOp(..), tagToEnumKey ) import TysWiredIn import TysPrim import TyCon ( tyConDataCons_maybe, isEnumerationTyCon, isNewTyCon, unwrapNewTyCon_maybe ) import DataCon ( dataConTag, dataConTyCon, dataConWorkId ) import CoreUtils ( cheapEqExpr, exprIsHNF ) import CoreUnfold ( exprIsConApp_maybe ) import Type import TypeRep import OccName ( occNameFS ) import PrelNames import Maybes ( orElse ) import Name ( Name, nameOccName ) import Outputable import FastString import BasicTypes import DynFlags import Platform import Util import Coercion (mkUnbranchedAxInstCo,mkSymCo,Role(..)) #if __GLASGOW_HASKELL__ >= 709 import Control.Applicative ( Alternative(..) ) #else import Control.Applicative ( Applicative(..), Alternative(..) ) #endif import Control.Monad import Data.Bits as Bits import qualified Data.ByteString as BS import Data.Int import Data.Ratio import Data.Word {- Note [Constant folding] ~~~~~~~~~~~~~~~~~~~~~~~ primOpRules generates a rewrite rule for each primop These rules do what is often called "constant folding" E.g. the rules for +# might say 4 +# 5 = 9 Well, of course you'd need a lot of rules if you did it like that, so we use a BuiltinRule instead, so that we can match in any two literal values. So the rule is really more like (Lit x) +# (Lit y) = Lit (x+#y) where the (+#) on the rhs is done at compile time That is why these rules are built in here. -} primOpRules :: Name -> PrimOp -> Maybe CoreRule -- ToDo: something for integer-shift ops? -- NotOp primOpRules nm TagToEnumOp = mkPrimOpRule nm 2 [ tagToEnumRule ] primOpRules nm DataToTagOp = mkPrimOpRule nm 2 [ dataToTagRule ] -- Int operations primOpRules nm IntAddOp = mkPrimOpRule nm 2 [ binaryLit (intOp2 (+)) , identityDynFlags zeroi ] primOpRules nm IntSubOp = mkPrimOpRule nm 2 [ binaryLit (intOp2 (-)) , rightIdentityDynFlags zeroi , equalArgs >> retLit zeroi ] primOpRules nm IntMulOp = mkPrimOpRule nm 2 [ binaryLit (intOp2 (*)) , zeroElem zeroi , identityDynFlags onei ] primOpRules nm IntQuotOp = mkPrimOpRule nm 2 [ nonZeroLit 1 >> binaryLit (intOp2 quot) , leftZero zeroi , rightIdentityDynFlags onei , equalArgs >> retLit onei ] primOpRules nm IntRemOp = mkPrimOpRule nm 2 [ nonZeroLit 1 >> binaryLit (intOp2 rem) , leftZero zeroi , do l <- getLiteral 1 dflags <- getDynFlags guard (l == onei dflags) retLit zeroi , equalArgs >> retLit zeroi , equalArgs >> retLit zeroi ] primOpRules nm AndIOp = mkPrimOpRule nm 2 [ binaryLit (intOp2 (.&.)) , idempotent , zeroElem zeroi ] primOpRules nm OrIOp = mkPrimOpRule nm 2 [ binaryLit (intOp2 (.|.)) , idempotent , identityDynFlags zeroi ] primOpRules nm XorIOp = mkPrimOpRule nm 2 [ binaryLit (intOp2 xor) , identityDynFlags zeroi , equalArgs >> retLit zeroi ] primOpRules nm NotIOp = mkPrimOpRule nm 1 [ unaryLit complementOp , inversePrimOp NotIOp ] primOpRules nm IntNegOp = mkPrimOpRule nm 1 [ unaryLit negOp , inversePrimOp IntNegOp ] primOpRules nm ISllOp = mkPrimOpRule nm 2 [ binaryLit (intOp2 Bits.shiftL) , rightIdentityDynFlags zeroi ] primOpRules nm ISraOp = mkPrimOpRule nm 2 [ binaryLit (intOp2 Bits.shiftR) , rightIdentityDynFlags zeroi ] primOpRules nm ISrlOp = mkPrimOpRule nm 2 [ binaryLit (intOp2' shiftRightLogical) , rightIdentityDynFlags zeroi ] -- Word operations primOpRules nm WordAddOp = mkPrimOpRule nm 2 [ binaryLit (wordOp2 (+)) , identityDynFlags zerow ] primOpRules nm WordSubOp = mkPrimOpRule nm 2 [ binaryLit (wordOp2 (-)) , rightIdentityDynFlags zerow , equalArgs >> retLit zerow ] primOpRules nm WordMulOp = mkPrimOpRule nm 2 [ binaryLit (wordOp2 (*)) , identityDynFlags onew ] primOpRules nm WordQuotOp = mkPrimOpRule nm 2 [ nonZeroLit 1 >> binaryLit (wordOp2 quot) , rightIdentityDynFlags onew ] primOpRules nm WordRemOp = mkPrimOpRule nm 2 [ nonZeroLit 1 >> binaryLit (wordOp2 rem) , rightIdentityDynFlags onew ] primOpRules nm AndOp = mkPrimOpRule nm 2 [ binaryLit (wordOp2 (.&.)) , idempotent , zeroElem zerow ] primOpRules nm OrOp = mkPrimOpRule nm 2 [ binaryLit (wordOp2 (.|.)) , idempotent , identityDynFlags zerow ] primOpRules nm XorOp = mkPrimOpRule nm 2 [ binaryLit (wordOp2 xor) , identityDynFlags zerow , equalArgs >> retLit zerow ] primOpRules nm NotOp = mkPrimOpRule nm 1 [ unaryLit complementOp , inversePrimOp NotOp ] primOpRules nm SllOp = mkPrimOpRule nm 2 [ wordShiftRule (const Bits.shiftL) ] primOpRules nm SrlOp = mkPrimOpRule nm 2 [ wordShiftRule shiftRightLogical ] -- coercions primOpRules nm Word2IntOp = mkPrimOpRule nm 1 [ liftLitDynFlags word2IntLit , inversePrimOp Int2WordOp ] primOpRules nm Int2WordOp = mkPrimOpRule nm 1 [ liftLitDynFlags int2WordLit , inversePrimOp Word2IntOp ] primOpRules nm Narrow8IntOp = mkPrimOpRule nm 1 [ liftLit narrow8IntLit , subsumedByPrimOp Narrow8IntOp , Narrow8IntOp `subsumesPrimOp` Narrow16IntOp , Narrow8IntOp `subsumesPrimOp` Narrow32IntOp ] primOpRules nm Narrow16IntOp = mkPrimOpRule nm 1 [ liftLit narrow16IntLit , subsumedByPrimOp Narrow8IntOp , subsumedByPrimOp Narrow16IntOp , Narrow16IntOp `subsumesPrimOp` Narrow32IntOp ] primOpRules nm Narrow32IntOp = mkPrimOpRule nm 1 [ liftLit narrow32IntLit , subsumedByPrimOp Narrow8IntOp , subsumedByPrimOp Narrow16IntOp , subsumedByPrimOp Narrow32IntOp , removeOp32 ] primOpRules nm Narrow8WordOp = mkPrimOpRule nm 1 [ liftLit narrow8WordLit , subsumedByPrimOp Narrow8WordOp , Narrow8WordOp `subsumesPrimOp` Narrow16WordOp , Narrow8WordOp `subsumesPrimOp` Narrow32WordOp ] primOpRules nm Narrow16WordOp = mkPrimOpRule nm 1 [ liftLit narrow16WordLit , subsumedByPrimOp Narrow8WordOp , subsumedByPrimOp Narrow16WordOp , Narrow16WordOp `subsumesPrimOp` Narrow32WordOp ] primOpRules nm Narrow32WordOp = mkPrimOpRule nm 1 [ liftLit narrow32WordLit , subsumedByPrimOp Narrow8WordOp , subsumedByPrimOp Narrow16WordOp , subsumedByPrimOp Narrow32WordOp , removeOp32 ] primOpRules nm OrdOp = mkPrimOpRule nm 1 [ liftLit char2IntLit , inversePrimOp ChrOp ] primOpRules nm ChrOp = mkPrimOpRule nm 1 [ do [Lit lit] <- getArgs guard (litFitsInChar lit) liftLit int2CharLit , inversePrimOp OrdOp ] primOpRules nm Float2IntOp = mkPrimOpRule nm 1 [ liftLit float2IntLit ] primOpRules nm Int2FloatOp = mkPrimOpRule nm 1 [ liftLit int2FloatLit ] primOpRules nm Double2IntOp = mkPrimOpRule nm 1 [ liftLit double2IntLit ] primOpRules nm Int2DoubleOp = mkPrimOpRule nm 1 [ liftLit int2DoubleLit ] -- SUP: Not sure what the standard says about precision in the following 2 cases primOpRules nm Float2DoubleOp = mkPrimOpRule nm 1 [ liftLit float2DoubleLit ] primOpRules nm Double2FloatOp = mkPrimOpRule nm 1 [ liftLit double2FloatLit ] -- Float primOpRules nm FloatAddOp = mkPrimOpRule nm 2 [ binaryLit (floatOp2 (+)) , identity zerof ] primOpRules nm FloatSubOp = mkPrimOpRule nm 2 [ binaryLit (floatOp2 (-)) , rightIdentity zerof ] primOpRules nm FloatMulOp = mkPrimOpRule nm 2 [ binaryLit (floatOp2 (*)) , identity onef , strengthReduction twof FloatAddOp ] -- zeroElem zerof doesn't hold because of NaN primOpRules nm FloatDivOp = mkPrimOpRule nm 2 [ guardFloatDiv >> binaryLit (floatOp2 (/)) , rightIdentity onef ] primOpRules nm FloatNegOp = mkPrimOpRule nm 1 [ unaryLit negOp , inversePrimOp FloatNegOp ] -- Double primOpRules nm DoubleAddOp = mkPrimOpRule nm 2 [ binaryLit (doubleOp2 (+)) , identity zerod ] primOpRules nm DoubleSubOp = mkPrimOpRule nm 2 [ binaryLit (doubleOp2 (-)) , rightIdentity zerod ] primOpRules nm DoubleMulOp = mkPrimOpRule nm 2 [ binaryLit (doubleOp2 (*)) , identity oned , strengthReduction twod DoubleAddOp ] -- zeroElem zerod doesn't hold because of NaN primOpRules nm DoubleDivOp = mkPrimOpRule nm 2 [ guardDoubleDiv >> binaryLit (doubleOp2 (/)) , rightIdentity oned ] primOpRules nm DoubleNegOp = mkPrimOpRule nm 1 [ unaryLit negOp , inversePrimOp DoubleNegOp ] -- Relational operators primOpRules nm IntEqOp = mkRelOpRule nm (==) [ litEq True ] primOpRules nm IntNeOp = mkRelOpRule nm (/=) [ litEq False ] primOpRules nm CharEqOp = mkRelOpRule nm (==) [ litEq True ] primOpRules nm CharNeOp = mkRelOpRule nm (/=) [ litEq False ] primOpRules nm IntGtOp = mkRelOpRule nm (>) [ boundsCmp Gt ] primOpRules nm IntGeOp = mkRelOpRule nm (>=) [ boundsCmp Ge ] primOpRules nm IntLeOp = mkRelOpRule nm (<=) [ boundsCmp Le ] primOpRules nm IntLtOp = mkRelOpRule nm (<) [ boundsCmp Lt ] primOpRules nm CharGtOp = mkRelOpRule nm (>) [ boundsCmp Gt ] primOpRules nm CharGeOp = mkRelOpRule nm (>=) [ boundsCmp Ge ] primOpRules nm CharLeOp = mkRelOpRule nm (<=) [ boundsCmp Le ] primOpRules nm CharLtOp = mkRelOpRule nm (<) [ boundsCmp Lt ] primOpRules nm FloatGtOp = mkFloatingRelOpRule nm (>) primOpRules nm FloatGeOp = mkFloatingRelOpRule nm (>=) primOpRules nm FloatLeOp = mkFloatingRelOpRule nm (<=) primOpRules nm FloatLtOp = mkFloatingRelOpRule nm (<) primOpRules nm FloatEqOp = mkFloatingRelOpRule nm (==) primOpRules nm FloatNeOp = mkFloatingRelOpRule nm (/=) primOpRules nm DoubleGtOp = mkFloatingRelOpRule nm (>) primOpRules nm DoubleGeOp = mkFloatingRelOpRule nm (>=) primOpRules nm DoubleLeOp = mkFloatingRelOpRule nm (<=) primOpRules nm DoubleLtOp = mkFloatingRelOpRule nm (<) primOpRules nm DoubleEqOp = mkFloatingRelOpRule nm (==) primOpRules nm DoubleNeOp = mkFloatingRelOpRule nm (/=) primOpRules nm WordGtOp = mkRelOpRule nm (>) [ boundsCmp Gt ] primOpRules nm WordGeOp = mkRelOpRule nm (>=) [ boundsCmp Ge ] primOpRules nm WordLeOp = mkRelOpRule nm (<=) [ boundsCmp Le ] primOpRules nm WordLtOp = mkRelOpRule nm (<) [ boundsCmp Lt ] primOpRules nm WordEqOp = mkRelOpRule nm (==) [ litEq True ] primOpRules nm WordNeOp = mkRelOpRule nm (/=) [ litEq False ] primOpRules nm AddrAddOp = mkPrimOpRule nm 2 [ rightIdentityDynFlags zeroi ] primOpRules nm SeqOp = mkPrimOpRule nm 4 [ seqRule ] primOpRules nm SparkOp = mkPrimOpRule nm 4 [ sparkRule ] primOpRules _ _ = Nothing {- ************************************************************************ * * \subsection{Doing the business} * * ************************************************************************ -} -- useful shorthands mkPrimOpRule :: Name -> Int -> [RuleM CoreExpr] -> Maybe CoreRule mkPrimOpRule nm arity rules = Just $ mkBasicRule nm arity (msum rules) mkRelOpRule :: Name -> (forall a . Ord a => a -> a -> Bool) -> [RuleM CoreExpr] -> Maybe CoreRule mkRelOpRule nm cmp extra = mkPrimOpRule nm 2 $ binaryCmpLit cmp : equal_rule : extra where -- x `cmp` x does not depend on x, so -- compute it for the arbitrary value 'True' -- and use that result equal_rule = do { equalArgs ; dflags <- getDynFlags ; return (if cmp True True then trueValInt dflags else falseValInt dflags) } {- Note [Rules for floating-point comparisons] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We need different rules for floating-point values because for floats it is not true that x = x (for NaNs); so we do not want the equal_rule rule that mkRelOpRule uses. Note also that, in the case of equality/inequality, we do /not/ want to switch to a case-expression. For example, we do not want to convert case (eqFloat# x 3.8#) of True -> this False -> that to case x of 3.8#::Float# -> this _ -> that See Trac #9238. Reason: comparing floating-point values for equality delicate, and we don't want to implement that delicacy in the code for case expressions. So we make it an invariant of Core that a case expression never scrutinises a Float# or Double#. This transformation is what the litEq rule does; see Note [The litEq rule: converting equality to case]. So we /refrain/ from using litEq for mkFloatingRelOpRule. -} mkFloatingRelOpRule :: Name -> (forall a . Ord a => a -> a -> Bool) -> Maybe CoreRule -- See Note [Rules for floating-point comparisons] mkFloatingRelOpRule nm cmp = mkPrimOpRule nm 2 [binaryCmpLit cmp] -- common constants zeroi, onei, zerow, onew :: DynFlags -> Literal zeroi dflags = mkMachInt dflags 0 onei dflags = mkMachInt dflags 1 zerow dflags = mkMachWord dflags 0 onew dflags = mkMachWord dflags 1 zerof, onef, twof, zerod, oned, twod :: Literal zerof = mkMachFloat 0.0 onef = mkMachFloat 1.0 twof = mkMachFloat 2.0 zerod = mkMachDouble 0.0 oned = mkMachDouble 1.0 twod = mkMachDouble 2.0 cmpOp :: DynFlags -> (forall a . Ord a => a -> a -> Bool) -> Literal -> Literal -> Maybe CoreExpr cmpOp dflags cmp = go where done True = Just $ trueValInt dflags done False = Just $ falseValInt dflags -- These compares are at different types go (MachChar i1) (MachChar i2) = done (i1 `cmp` i2) go (MachInt i1) (MachInt i2) = done (i1 `cmp` i2) go (MachInt64 i1) (MachInt64 i2) = done (i1 `cmp` i2) go (MachWord i1) (MachWord i2) = done (i1 `cmp` i2) go (MachWord64 i1) (MachWord64 i2) = done (i1 `cmp` i2) go (MachFloat i1) (MachFloat i2) = done (i1 `cmp` i2) go (MachDouble i1) (MachDouble i2) = done (i1 `cmp` i2) go _ _ = Nothing -------------------------- negOp :: DynFlags -> Literal -> Maybe CoreExpr -- Negate negOp _ (MachFloat 0.0) = Nothing -- can't represent -0.0 as a Rational negOp dflags (MachFloat f) = Just (mkFloatVal dflags (-f)) negOp _ (MachDouble 0.0) = Nothing negOp dflags (MachDouble d) = Just (mkDoubleVal dflags (-d)) negOp dflags (MachInt i) = intResult dflags (-i) negOp _ _ = Nothing complementOp :: DynFlags -> Literal -> Maybe CoreExpr -- Binary complement complementOp dflags (MachWord i) = wordResult dflags (complement i) complementOp dflags (MachInt i) = intResult dflags (complement i) complementOp _ _ = Nothing -------------------------- intOp2 :: (Integral a, Integral b) => (a -> b -> Integer) -> DynFlags -> Literal -> Literal -> Maybe CoreExpr intOp2 = intOp2' . const intOp2' :: (Integral a, Integral b) => (DynFlags -> a -> b -> Integer) -> DynFlags -> Literal -> Literal -> Maybe CoreExpr intOp2' op dflags (MachInt i1) (MachInt i2) = let o = op dflags in intResult dflags (fromInteger i1 `o` fromInteger i2) intOp2' _ _ _ _ = Nothing -- Could find LitLit shiftRightLogical :: DynFlags -> Integer -> Int -> Integer -- Shift right, putting zeros in rather than sign-propagating as Bits.shiftR would do -- Do this by converting to Word and back. Obviously this won't work for big -- values, but its ok as we use it here shiftRightLogical dflags x n | wordSizeInBits dflags == 32 = fromIntegral (fromInteger x `shiftR` n :: Word32) | wordSizeInBits dflags == 64 = fromIntegral (fromInteger x `shiftR` n :: Word64) | otherwise = panic "shiftRightLogical: unsupported word size" -------------------------- retLit :: (DynFlags -> Literal) -> RuleM CoreExpr retLit l = do dflags <- getDynFlags return $ Lit $ l dflags wordOp2 :: (Integral a, Integral b) => (a -> b -> Integer) -> DynFlags -> Literal -> Literal -> Maybe CoreExpr wordOp2 op dflags (MachWord w1) (MachWord w2) = wordResult dflags (fromInteger w1 `op` fromInteger w2) wordOp2 _ _ _ _ = Nothing -- Could find LitLit wordShiftRule :: (DynFlags -> Integer -> Int -> Integer) -> RuleM CoreExpr -- Shifts take an Int; hence third arg of op is Int -- See Note [Guarding against silly shifts] wordShiftRule shift_op = do { dflags <- getDynFlags ; [e1, Lit (MachInt shift_len)] <- getArgs ; case e1 of _ | shift_len == 0 -> return e1 | shift_len < 0 || wordSizeInBits dflags < shift_len -> return (mkRuntimeErrorApp rUNTIME_ERROR_ID wordPrimTy ("Bad shift length" ++ show shift_len)) Lit (MachWord x) -> let op = shift_op dflags in liftMaybe $ wordResult dflags (x `op` fromInteger shift_len) -- Do the shift at type Integer, but shift length is Int _ -> mzero } wordSizeInBits :: DynFlags -> Integer wordSizeInBits dflags = toInteger (platformWordSize (targetPlatform dflags) `shiftL` 3) -------------------------- floatOp2 :: (Rational -> Rational -> Rational) -> DynFlags -> Literal -> Literal -> Maybe (Expr CoreBndr) floatOp2 op dflags (MachFloat f1) (MachFloat f2) = Just (mkFloatVal dflags (f1 `op` f2)) floatOp2 _ _ _ _ = Nothing -------------------------- doubleOp2 :: (Rational -> Rational -> Rational) -> DynFlags -> Literal -> Literal -> Maybe (Expr CoreBndr) doubleOp2 op dflags (MachDouble f1) (MachDouble f2) = Just (mkDoubleVal dflags (f1 `op` f2)) doubleOp2 _ _ _ _ = Nothing -------------------------- {- Note [The litEq rule: converting equality to case] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This stuff turns n ==# 3# into case n of 3# -> True m -> False This is a Good Thing, because it allows case-of case things to happen, and case-default absorption to happen. For example: if (n ==# 3#) || (n ==# 4#) then e1 else e2 will transform to case n of 3# -> e1 4# -> e1 m -> e2 (modulo the usual precautions to avoid duplicating e1) -} litEq :: Bool -- True <=> equality, False <=> inequality -> RuleM CoreExpr litEq is_eq = msum [ do [Lit lit, expr] <- getArgs dflags <- getDynFlags do_lit_eq dflags lit expr , do [expr, Lit lit] <- getArgs dflags <- getDynFlags do_lit_eq dflags lit expr ] where do_lit_eq dflags lit expr = do guard (not (litIsLifted lit)) return (mkWildCase expr (literalType lit) intPrimTy [(DEFAULT, [], val_if_neq), (LitAlt lit, [], val_if_eq)]) where val_if_eq | is_eq = trueValInt dflags | otherwise = falseValInt dflags val_if_neq | is_eq = falseValInt dflags | otherwise = trueValInt dflags -- | Check if there is comparison with minBound or maxBound, that is -- always true or false. For instance, an Int cannot be smaller than its -- minBound, so we can replace such comparison with False. boundsCmp :: Comparison -> RuleM CoreExpr boundsCmp op = do dflags <- getDynFlags [a, b] <- getArgs liftMaybe $ mkRuleFn dflags op a b data Comparison = Gt | Ge | Lt | Le mkRuleFn :: DynFlags -> Comparison -> CoreExpr -> CoreExpr -> Maybe CoreExpr mkRuleFn dflags Gt (Lit lit) _ | isMinBound dflags lit = Just $ falseValInt dflags mkRuleFn dflags Le (Lit lit) _ | isMinBound dflags lit = Just $ trueValInt dflags mkRuleFn dflags Ge _ (Lit lit) | isMinBound dflags lit = Just $ trueValInt dflags mkRuleFn dflags Lt _ (Lit lit) | isMinBound dflags lit = Just $ falseValInt dflags mkRuleFn dflags Ge (Lit lit) _ | isMaxBound dflags lit = Just $ trueValInt dflags mkRuleFn dflags Lt (Lit lit) _ | isMaxBound dflags lit = Just $ falseValInt dflags mkRuleFn dflags Gt _ (Lit lit) | isMaxBound dflags lit = Just $ falseValInt dflags mkRuleFn dflags Le _ (Lit lit) | isMaxBound dflags lit = Just $ trueValInt dflags mkRuleFn _ _ _ _ = Nothing isMinBound :: DynFlags -> Literal -> Bool isMinBound _ (MachChar c) = c == minBound isMinBound dflags (MachInt i) = i == tARGET_MIN_INT dflags isMinBound _ (MachInt64 i) = i == toInteger (minBound :: Int64) isMinBound _ (MachWord i) = i == 0 isMinBound _ (MachWord64 i) = i == 0 isMinBound _ _ = False isMaxBound :: DynFlags -> Literal -> Bool isMaxBound _ (MachChar c) = c == maxBound isMaxBound dflags (MachInt i) = i == tARGET_MAX_INT dflags isMaxBound _ (MachInt64 i) = i == toInteger (maxBound :: Int64) isMaxBound dflags (MachWord i) = i == tARGET_MAX_WORD dflags isMaxBound _ (MachWord64 i) = i == toInteger (maxBound :: Word64) isMaxBound _ _ = False -- Note that we *don't* warn the user about overflow. It's not done at -- runtime either, and compilation of completely harmless things like -- ((124076834 :: Word32) + (2147483647 :: Word32)) -- would yield a warning. Instead we simply squash the value into the -- *target* Int/Word range. intResult :: DynFlags -> Integer -> Maybe CoreExpr intResult dflags result = Just (mkIntVal dflags result') where result' = case platformWordSize (targetPlatform dflags) of 4 -> toInteger (fromInteger result :: Int32) 8 -> toInteger (fromInteger result :: Int64) w -> panic ("intResult: Unknown platformWordSize: " ++ show w) wordResult :: DynFlags -> Integer -> Maybe CoreExpr wordResult dflags result = Just (mkWordVal dflags result') where result' = case platformWordSize (targetPlatform dflags) of 4 -> toInteger (fromInteger result :: Word32) 8 -> toInteger (fromInteger result :: Word64) w -> panic ("wordResult: Unknown platformWordSize: " ++ show w) inversePrimOp :: PrimOp -> RuleM CoreExpr inversePrimOp primop = do [Var primop_id `App` e] <- getArgs matchPrimOpId primop primop_id return e subsumesPrimOp :: PrimOp -> PrimOp -> RuleM CoreExpr this `subsumesPrimOp` that = do [Var primop_id `App` e] <- getArgs matchPrimOpId that primop_id return (Var (mkPrimOpId this) `App` e) subsumedByPrimOp :: PrimOp -> RuleM CoreExpr subsumedByPrimOp primop = do [e@(Var primop_id `App` _)] <- getArgs matchPrimOpId primop primop_id return e idempotent :: RuleM CoreExpr idempotent = do [e1, e2] <- getArgs guard $ cheapEqExpr e1 e2 return e1 {- Note [Guarding against silly shifts] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this code: import Data.Bits( (.|.), shiftL ) chunkToBitmap :: [Bool] -> Word32 chunkToBitmap chunk = foldr (.|.) 0 [ 1 `shiftL` n | (True,n) <- zip chunk [0..] ] This optimises to: Shift.$wgo = \ (w_sCS :: GHC.Prim.Int#) (w1_sCT :: [GHC.Types.Bool]) -> case w1_sCT of _ { [] -> 0##; : x_aAW xs_aAX -> case x_aAW of _ { GHC.Types.False -> case w_sCS of wild2_Xh { __DEFAULT -> Shift.$wgo (GHC.Prim.+# wild2_Xh 1) xs_aAX; 9223372036854775807 -> 0## }; GHC.Types.True -> case GHC.Prim.>=# w_sCS 64 of _ { GHC.Types.False -> case w_sCS of wild3_Xh { __DEFAULT -> case Shift.$wgo (GHC.Prim.+# wild3_Xh 1) xs_aAX of ww_sCW { __DEFAULT -> GHC.Prim.or# (GHC.Prim.narrow32Word# (GHC.Prim.uncheckedShiftL# 1## wild3_Xh)) ww_sCW }; 9223372036854775807 -> GHC.Prim.narrow32Word# !!!!--> (GHC.Prim.uncheckedShiftL# 1## 9223372036854775807) }; GHC.Types.True -> case w_sCS of wild3_Xh { __DEFAULT -> Shift.$wgo (GHC.Prim.+# wild3_Xh 1) xs_aAX; 9223372036854775807 -> 0## } } } } Note the massive shift on line "!!!!". It can't happen, because we've checked that w < 64, but the optimiser didn't spot that. We DO NO want to constant-fold this! Moreover, if the programmer writes (n `uncheckedShiftL` 9223372036854775807), we can't constant fold it, but if it gets to the assember we get Error: operand type mismatch for `shl' So the best thing to do is to rewrite the shift with a call to error, when the second arg is stupid. ************************************************************************ * * \subsection{Vaguely generic functions} * * ************************************************************************ -} mkBasicRule :: Name -> Int -> RuleM CoreExpr -> CoreRule -- Gives the Rule the same name as the primop itself mkBasicRule op_name n_args rm = BuiltinRule { ru_name = occNameFS (nameOccName op_name), ru_fn = op_name, ru_nargs = n_args, ru_try = \ dflags in_scope _ -> runRuleM rm dflags in_scope } newtype RuleM r = RuleM { runRuleM :: DynFlags -> InScopeEnv -> [CoreExpr] -> Maybe r } instance Functor RuleM where fmap = liftM instance Applicative RuleM where pure = return (<*>) = ap instance Monad RuleM where return x = RuleM $ \_ _ _ -> Just x RuleM f >>= g = RuleM $ \dflags iu e -> case f dflags iu e of Nothing -> Nothing Just r -> runRuleM (g r) dflags iu e fail _ = mzero instance Alternative RuleM where empty = mzero (<|>) = mplus instance MonadPlus RuleM where mzero = RuleM $ \_ _ _ -> Nothing mplus (RuleM f1) (RuleM f2) = RuleM $ \dflags iu args -> f1 dflags iu args `mplus` f2 dflags iu args instance HasDynFlags RuleM where getDynFlags = RuleM $ \dflags _ _ -> Just dflags liftMaybe :: Maybe a -> RuleM a liftMaybe Nothing = mzero liftMaybe (Just x) = return x liftLit :: (Literal -> Literal) -> RuleM CoreExpr liftLit f = liftLitDynFlags (const f) liftLitDynFlags :: (DynFlags -> Literal -> Literal) -> RuleM CoreExpr liftLitDynFlags f = do dflags <- getDynFlags [Lit lit] <- getArgs return $ Lit (f dflags lit) removeOp32 :: RuleM CoreExpr removeOp32 = do dflags <- getDynFlags if wordSizeInBits dflags == 32 then do [e] <- getArgs return e else mzero getArgs :: RuleM [CoreExpr] getArgs = RuleM $ \_ _ args -> Just args getInScopeEnv :: RuleM InScopeEnv getInScopeEnv = RuleM $ \_ iu _ -> Just iu -- return the n-th argument of this rule, if it is a literal -- argument indices start from 0 getLiteral :: Int -> RuleM Literal getLiteral n = RuleM $ \_ _ exprs -> case drop n exprs of (Lit l:_) -> Just l _ -> Nothing unaryLit :: (DynFlags -> Literal -> Maybe CoreExpr) -> RuleM CoreExpr unaryLit op = do dflags <- getDynFlags [Lit l] <- getArgs liftMaybe $ op dflags (convFloating dflags l) binaryLit :: (DynFlags -> Literal -> Literal -> Maybe CoreExpr) -> RuleM CoreExpr binaryLit op = do dflags <- getDynFlags [Lit l1, Lit l2] <- getArgs liftMaybe $ op dflags (convFloating dflags l1) (convFloating dflags l2) binaryCmpLit :: (forall a . Ord a => a -> a -> Bool) -> RuleM CoreExpr binaryCmpLit op = do dflags <- getDynFlags binaryLit (\_ -> cmpOp dflags op) leftIdentity :: Literal -> RuleM CoreExpr leftIdentity id_lit = leftIdentityDynFlags (const id_lit) rightIdentity :: Literal -> RuleM CoreExpr rightIdentity id_lit = rightIdentityDynFlags (const id_lit) identity :: Literal -> RuleM CoreExpr identity lit = leftIdentity lit `mplus` rightIdentity lit leftIdentityDynFlags :: (DynFlags -> Literal) -> RuleM CoreExpr leftIdentityDynFlags id_lit = do dflags <- getDynFlags [Lit l1, e2] <- getArgs guard $ l1 == id_lit dflags return e2 rightIdentityDynFlags :: (DynFlags -> Literal) -> RuleM CoreExpr rightIdentityDynFlags id_lit = do dflags <- getDynFlags [e1, Lit l2] <- getArgs guard $ l2 == id_lit dflags return e1 identityDynFlags :: (DynFlags -> Literal) -> RuleM CoreExpr identityDynFlags lit = leftIdentityDynFlags lit `mplus` rightIdentityDynFlags lit leftZero :: (DynFlags -> Literal) -> RuleM CoreExpr leftZero zero = do dflags <- getDynFlags [Lit l1, _] <- getArgs guard $ l1 == zero dflags return $ Lit l1 rightZero :: (DynFlags -> Literal) -> RuleM CoreExpr rightZero zero = do dflags <- getDynFlags [_, Lit l2] <- getArgs guard $ l2 == zero dflags return $ Lit l2 zeroElem :: (DynFlags -> Literal) -> RuleM CoreExpr zeroElem lit = leftZero lit `mplus` rightZero lit equalArgs :: RuleM () equalArgs = do [e1, e2] <- getArgs guard $ e1 `cheapEqExpr` e2 nonZeroLit :: Int -> RuleM () nonZeroLit n = getLiteral n >>= guard . not . isZeroLit -- When excess precision is not requested, cut down the precision of the -- Rational value to that of Float/Double. We confuse host architecture -- and target architecture here, but it's convenient (and wrong :-). convFloating :: DynFlags -> Literal -> Literal convFloating dflags (MachFloat f) | not (gopt Opt_ExcessPrecision dflags) = MachFloat (toRational (fromRational f :: Float )) convFloating dflags (MachDouble d) | not (gopt Opt_ExcessPrecision dflags) = MachDouble (toRational (fromRational d :: Double)) convFloating _ l = l guardFloatDiv :: RuleM () guardFloatDiv = do [Lit (MachFloat f1), Lit (MachFloat f2)] <- getArgs guard $ (f1 /=0 || f2 > 0) -- see Note [negative zero] && f2 /= 0 -- avoid NaN and Infinity/-Infinity guardDoubleDiv :: RuleM () guardDoubleDiv = do [Lit (MachDouble d1), Lit (MachDouble d2)] <- getArgs guard $ (d1 /=0 || d2 > 0) -- see Note [negative zero] && d2 /= 0 -- avoid NaN and Infinity/-Infinity -- Note [negative zero] Avoid (0 / -d), otherwise 0/(-1) reduces to -- zero, but we might want to preserve the negative zero here which -- is representable in Float/Double but not in (normalised) -- Rational. (#3676) Perhaps we should generate (0 :% (-1)) instead? strengthReduction :: Literal -> PrimOp -> RuleM CoreExpr strengthReduction two_lit add_op = do -- Note [Strength reduction] arg <- msum [ do [arg, Lit mult_lit] <- getArgs guard (mult_lit == two_lit) return arg , do [Lit mult_lit, arg] <- getArgs guard (mult_lit == two_lit) return arg ] return $ Var (mkPrimOpId add_op) `App` arg `App` arg -- Note [Strength reduction] -- ~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- This rule turns floating point multiplications of the form 2.0 * x and -- x * 2.0 into x + x addition, because addition costs less than multiplication. -- See #7116 -- Note [What's true and false] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- trueValInt and falseValInt represent true and false values returned by -- comparison primops for Char, Int, Word, Integer, Double, Float and Addr. -- True is represented as an unboxed 1# literal, while false is represented -- as 0# literal. -- We still need Bool data constructors (True and False) to use in a rule -- for constant folding of equal Strings trueValInt, falseValInt :: DynFlags -> Expr CoreBndr trueValInt dflags = Lit $ onei dflags -- see Note [What's true and false] falseValInt dflags = Lit $ zeroi dflags trueValBool, falseValBool :: Expr CoreBndr trueValBool = Var trueDataConId -- see Note [What's true and false] falseValBool = Var falseDataConId ltVal, eqVal, gtVal :: Expr CoreBndr ltVal = Var ltDataConId eqVal = Var eqDataConId gtVal = Var gtDataConId mkIntVal :: DynFlags -> Integer -> Expr CoreBndr mkIntVal dflags i = Lit (mkMachInt dflags i) mkWordVal :: DynFlags -> Integer -> Expr CoreBndr mkWordVal dflags w = Lit (mkMachWord dflags w) mkFloatVal :: DynFlags -> Rational -> Expr CoreBndr mkFloatVal dflags f = Lit (convFloating dflags (MachFloat f)) mkDoubleVal :: DynFlags -> Rational -> Expr CoreBndr mkDoubleVal dflags d = Lit (convFloating dflags (MachDouble d)) matchPrimOpId :: PrimOp -> Id -> RuleM () matchPrimOpId op id = do op' <- liftMaybe $ isPrimOpId_maybe id guard $ op == op' {- ************************************************************************ * * \subsection{Special rules for seq, tagToEnum, dataToTag} * * ************************************************************************ Note [tagToEnum#] ~~~~~~~~~~~~~~~~~ Nasty check to ensure that tagToEnum# is applied to a type that is an enumeration TyCon. Unification may refine the type later, but this check won't see that, alas. It's crude but it works. Here's are two cases that should fail f :: forall a. a f = tagToEnum# 0 -- Can't do tagToEnum# at a type variable g :: Int g = tagToEnum# 0 -- Int is not an enumeration We used to make this check in the type inference engine, but it's quite ugly to do so, because the delayed constraint solving means that we don't really know what's going on until the end. It's very much a corner case because we don't expect the user to call tagToEnum# at all; we merely generate calls in derived instances of Enum. So we compromise: a rewrite rule rewrites a bad instance of tagToEnum# to an error call, and emits a warning. -} tagToEnumRule :: RuleM CoreExpr -- If data T a = A | B | C -- then tag2Enum# (T ty) 2# --> B ty tagToEnumRule = do [Type ty, Lit (MachInt i)] <- getArgs case splitTyConApp_maybe ty of Just (tycon, tc_args) | isEnumerationTyCon tycon -> do let tag = fromInteger i correct_tag dc = (dataConTag dc - fIRST_TAG) == tag (dc:rest) <- return $ filter correct_tag (tyConDataCons_maybe tycon `orElse` []) ASSERT(null rest) return () return $ mkTyApps (Var (dataConWorkId dc)) tc_args -- See Note [tagToEnum#] _ -> WARN( True, ptext (sLit "tagToEnum# on non-enumeration type") <+> ppr ty ) return $ mkRuntimeErrorApp rUNTIME_ERROR_ID ty "tagToEnum# on non-enumeration type" {- For dataToTag#, we can reduce if either (a) the argument is a constructor (b) the argument is a variable whose unfolding is a known constructor -} dataToTagRule :: RuleM CoreExpr dataToTagRule = a `mplus` b where a = do [Type ty1, Var tag_to_enum `App` Type ty2 `App` tag] <- getArgs guard $ tag_to_enum `hasKey` tagToEnumKey guard $ ty1 `eqType` ty2 return tag -- dataToTag (tagToEnum x) ==> x b = do dflags <- getDynFlags [_, val_arg] <- getArgs in_scope <- getInScopeEnv (dc,_,_) <- liftMaybe $ exprIsConApp_maybe in_scope val_arg ASSERT( not (isNewTyCon (dataConTyCon dc)) ) return () return $ mkIntVal dflags (toInteger (dataConTag dc - fIRST_TAG)) {- ************************************************************************ * * \subsection{Rules for seq# and spark#} * * ************************************************************************ -} -- seq# :: forall a s . a -> State# s -> (# State# s, a #) seqRule :: RuleM CoreExpr seqRule = do [ty_a, Type ty_s, a, s] <- getArgs guard $ exprIsHNF a return $ mkConApp (tupleDataCon Unboxed 2) [Type (mkStatePrimTy ty_s), ty_a, s, a] -- spark# :: forall a s . a -> State# s -> (# State# s, a #) sparkRule :: RuleM CoreExpr sparkRule = seqRule -- reduce on HNF, just the same -- XXX perhaps we shouldn't do this, because a spark eliminated by -- this rule won't be counted as a dud at runtime? {- ************************************************************************ * * \subsection{Built in rules} * * ************************************************************************ Note [Scoping for Builtin rules] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When compiling a (base-package) module that defines one of the functions mentioned in the RHS of a built-in rule, there's a danger that we'll see f = ...(eq String x).... ....and lower down... eqString = ... Then a rewrite would give f = ...(eqString x)... ....and lower down... eqString = ... and lo, eqString is not in scope. This only really matters when we get to code generation. With -O we do a GlomBinds step that does a new SCC analysis on the whole set of bindings, which sorts out the dependency. Without -O we don't do any rule rewriting so again we are fine. (This whole thing doesn't show up for non-built-in rules because their dependencies are explicit.) -} builtinRules :: [CoreRule] -- Rules for non-primops that can't be expressed using a RULE pragma builtinRules = [BuiltinRule { ru_name = fsLit "AppendLitString", ru_fn = unpackCStringFoldrName, ru_nargs = 4, ru_try = \_ _ _ -> match_append_lit }, BuiltinRule { ru_name = fsLit "EqString", ru_fn = eqStringName, ru_nargs = 2, ru_try = \dflags _ _ -> match_eq_string dflags }, BuiltinRule { ru_name = fsLit "Inline", ru_fn = inlineIdName, ru_nargs = 2, ru_try = \_ _ _ -> match_inline }, BuiltinRule { ru_name = fsLit "MagicDict", ru_fn = idName magicDictId, ru_nargs = 4, ru_try = \_ _ _ -> match_magicDict } ] ++ builtinIntegerRules builtinIntegerRules :: [CoreRule] builtinIntegerRules = [rule_IntToInteger "smallInteger" smallIntegerName, rule_WordToInteger "wordToInteger" wordToIntegerName, rule_Int64ToInteger "int64ToInteger" int64ToIntegerName, rule_Word64ToInteger "word64ToInteger" word64ToIntegerName, rule_convert "integerToWord" integerToWordName mkWordLitWord, rule_convert "integerToInt" integerToIntName mkIntLitInt, rule_convert "integerToWord64" integerToWord64Name (\_ -> mkWord64LitWord64), rule_convert "integerToInt64" integerToInt64Name (\_ -> mkInt64LitInt64), rule_binop "plusInteger" plusIntegerName (+), rule_binop "minusInteger" minusIntegerName (-), rule_binop "timesInteger" timesIntegerName (*), rule_unop "negateInteger" negateIntegerName negate, rule_binop_Prim "eqInteger#" eqIntegerPrimName (==), rule_binop_Prim "neqInteger#" neqIntegerPrimName (/=), rule_unop "absInteger" absIntegerName abs, rule_unop "signumInteger" signumIntegerName signum, rule_binop_Prim "leInteger#" leIntegerPrimName (<=), rule_binop_Prim "gtInteger#" gtIntegerPrimName (>), rule_binop_Prim "ltInteger#" ltIntegerPrimName (<), rule_binop_Prim "geInteger#" geIntegerPrimName (>=), rule_binop_Ordering "compareInteger" compareIntegerName compare, rule_encodeFloat "encodeFloatInteger" encodeFloatIntegerName mkFloatLitFloat, rule_convert "floatFromInteger" floatFromIntegerName (\_ -> mkFloatLitFloat), rule_encodeFloat "encodeDoubleInteger" encodeDoubleIntegerName mkDoubleLitDouble, rule_decodeDouble "decodeDoubleInteger" decodeDoubleIntegerName, rule_convert "doubleFromInteger" doubleFromIntegerName (\_ -> mkDoubleLitDouble), rule_rationalTo "rationalToFloat" rationalToFloatName mkFloatExpr, rule_rationalTo "rationalToDouble" rationalToDoubleName mkDoubleExpr, rule_binop "gcdInteger" gcdIntegerName gcd, rule_binop "lcmInteger" lcmIntegerName lcm, rule_binop "andInteger" andIntegerName (.&.), rule_binop "orInteger" orIntegerName (.|.), rule_binop "xorInteger" xorIntegerName xor, rule_unop "complementInteger" complementIntegerName complement, rule_Int_binop "shiftLInteger" shiftLIntegerName shiftL, rule_Int_binop "shiftRInteger" shiftRIntegerName shiftR, rule_bitInteger "bitInteger" bitIntegerName, -- See Note [Integer division constant folding] in libraries/base/GHC/Real.hs rule_divop_one "quotInteger" quotIntegerName quot, rule_divop_one "remInteger" remIntegerName rem, rule_divop_one "divInteger" divIntegerName div, rule_divop_one "modInteger" modIntegerName mod, rule_divop_both "divModInteger" divModIntegerName divMod, rule_divop_both "quotRemInteger" quotRemIntegerName quotRem, -- These rules below don't actually have to be built in, but if we -- put them in the Haskell source then we'd have to duplicate them -- between all Integer implementations rule_XToIntegerToX "smallIntegerToInt" integerToIntName smallIntegerName, rule_XToIntegerToX "wordToIntegerToWord" integerToWordName wordToIntegerName, rule_XToIntegerToX "int64ToIntegerToInt64" integerToInt64Name int64ToIntegerName, rule_XToIntegerToX "word64ToIntegerToWord64" integerToWord64Name word64ToIntegerName, rule_smallIntegerTo "smallIntegerToWord" integerToWordName Int2WordOp, rule_smallIntegerTo "smallIntegerToFloat" floatFromIntegerName Int2FloatOp, rule_smallIntegerTo "smallIntegerToDouble" doubleFromIntegerName Int2DoubleOp ] where rule_convert str name convert = BuiltinRule { ru_name = fsLit str, ru_fn = name, ru_nargs = 1, ru_try = match_Integer_convert convert } rule_IntToInteger str name = BuiltinRule { ru_name = fsLit str, ru_fn = name, ru_nargs = 1, ru_try = match_IntToInteger } rule_WordToInteger str name = BuiltinRule { ru_name = fsLit str, ru_fn = name, ru_nargs = 1, ru_try = match_WordToInteger } rule_Int64ToInteger str name = BuiltinRule { ru_name = fsLit str, ru_fn = name, ru_nargs = 1, ru_try = match_Int64ToInteger } rule_Word64ToInteger str name = BuiltinRule { ru_name = fsLit str, ru_fn = name, ru_nargs = 1, ru_try = match_Word64ToInteger } rule_unop str name op = BuiltinRule { ru_name = fsLit str, ru_fn = name, ru_nargs = 1, ru_try = match_Integer_unop op } rule_bitInteger str name = BuiltinRule { ru_name = fsLit str, ru_fn = name, ru_nargs = 1, ru_try = match_IntToInteger_unop (bit . fromIntegral) } rule_binop str name op = BuiltinRule { ru_name = fsLit str, ru_fn = name, ru_nargs = 2, ru_try = match_Integer_binop op } rule_divop_both str name op = BuiltinRule { ru_name = fsLit str, ru_fn = name, ru_nargs = 2, ru_try = match_Integer_divop_both op } rule_divop_one str name op = BuiltinRule { ru_name = fsLit str, ru_fn = name, ru_nargs = 2, ru_try = match_Integer_divop_one op } rule_Int_binop str name op = BuiltinRule { ru_name = fsLit str, ru_fn = name, ru_nargs = 2, ru_try = match_Integer_Int_binop op } rule_binop_Prim str name op = BuiltinRule { ru_name = fsLit str, ru_fn = name, ru_nargs = 2, ru_try = match_Integer_binop_Prim op } rule_binop_Ordering str name op = BuiltinRule { ru_name = fsLit str, ru_fn = name, ru_nargs = 2, ru_try = match_Integer_binop_Ordering op } rule_encodeFloat str name op = BuiltinRule { ru_name = fsLit str, ru_fn = name, ru_nargs = 2, ru_try = match_Integer_Int_encodeFloat op } rule_decodeDouble str name = BuiltinRule { ru_name = fsLit str, ru_fn = name, ru_nargs = 1, ru_try = match_decodeDouble } rule_XToIntegerToX str name toIntegerName = BuiltinRule { ru_name = fsLit str, ru_fn = name, ru_nargs = 1, ru_try = match_XToIntegerToX toIntegerName } rule_smallIntegerTo str name primOp = BuiltinRule { ru_name = fsLit str, ru_fn = name, ru_nargs = 1, ru_try = match_smallIntegerTo primOp } rule_rationalTo str name mkLit = BuiltinRule { ru_name = fsLit str, ru_fn = name, ru_nargs = 2, ru_try = match_rationalTo mkLit } --------------------------------------------------- -- The rule is this: -- unpackFoldrCString# "foo" c (unpackFoldrCString# "baz" c n) -- = unpackFoldrCString# "foobaz" c n match_append_lit :: [Expr CoreBndr] -> Maybe (Expr CoreBndr) match_append_lit [Type ty1, Lit (MachStr s1), c1, Var unpk `App` Type ty2 `App` Lit (MachStr s2) `App` c2 `App` n ] | unpk `hasKey` unpackCStringFoldrIdKey && c1 `cheapEqExpr` c2 = ASSERT( ty1 `eqType` ty2 ) Just (Var unpk `App` Type ty1 `App` Lit (MachStr (s1 `BS.append` s2)) `App` c1 `App` n) match_append_lit _ = Nothing --------------------------------------------------- -- The rule is this: -- eqString (unpackCString# (Lit s1)) (unpackCString# (Lit s2) = s1==s2 match_eq_string :: DynFlags -> [Expr CoreBndr] -> Maybe (Expr CoreBndr) match_eq_string _ [Var unpk1 `App` Lit (MachStr s1), Var unpk2 `App` Lit (MachStr s2)] | unpk1 `hasKey` unpackCStringIdKey, unpk2 `hasKey` unpackCStringIdKey = Just (if s1 == s2 then trueValBool else falseValBool) match_eq_string _ _ = Nothing --------------------------------------------------- -- The rule is this: -- inline f_ty (f a b c) = <f's unfolding> a b c -- (if f has an unfolding, EVEN if it's a loop breaker) -- -- It's important to allow the argument to 'inline' to have args itself -- (a) because its more forgiving to allow the programmer to write -- inline f a b c -- or inline (f a b c) -- (b) because a polymorphic f wll get a type argument that the -- programmer can't avoid -- -- Also, don't forget about 'inline's type argument! match_inline :: [Expr CoreBndr] -> Maybe (Expr CoreBndr) match_inline (Type _ : e : _) | (Var f, args1) <- collectArgs e, Just unf <- maybeUnfoldingTemplate (realIdUnfolding f) -- Ignore the IdUnfoldingFun here! = Just (mkApps unf args1) match_inline _ = Nothing -- See Note [magicDictId magic] in `basicTypes/MkId.hs` -- for a description of what is going on here. match_magicDict :: [Expr CoreBndr] -> Maybe (Expr CoreBndr) match_magicDict [Type _, Var wrap `App` Type a `App` Type _ `App` f, x, y ] | Just (fieldTy, _) <- splitFunTy_maybe $ dropForAlls $ idType wrap , Just (dictTy, _) <- splitFunTy_maybe fieldTy , Just dictTc <- tyConAppTyCon_maybe dictTy , Just (_,_,co) <- unwrapNewTyCon_maybe dictTc = Just $ f `App` Cast x (mkSymCo (mkUnbranchedAxInstCo Representational co [a])) `App` y match_magicDict _ = Nothing ------------------------------------------------- -- Integer rules -- smallInteger (79::Int#) = 79::Integer -- wordToInteger (79::Word#) = 79::Integer -- Similarly Int64, Word64 match_IntToInteger :: RuleFun match_IntToInteger = match_IntToInteger_unop id match_WordToInteger :: RuleFun match_WordToInteger _ id_unf id [xl] | Just (MachWord x) <- exprIsLiteral_maybe id_unf xl = case idType id of FunTy _ integerTy -> Just (Lit (LitInteger x integerTy)) _ -> panic "match_WordToInteger: Id has the wrong type" match_WordToInteger _ _ _ _ = Nothing match_Int64ToInteger :: RuleFun match_Int64ToInteger _ id_unf id [xl] | Just (MachInt64 x) <- exprIsLiteral_maybe id_unf xl = case idType id of FunTy _ integerTy -> Just (Lit (LitInteger x integerTy)) _ -> panic "match_Int64ToInteger: Id has the wrong type" match_Int64ToInteger _ _ _ _ = Nothing match_Word64ToInteger :: RuleFun match_Word64ToInteger _ id_unf id [xl] | Just (MachWord64 x) <- exprIsLiteral_maybe id_unf xl = case idType id of FunTy _ integerTy -> Just (Lit (LitInteger x integerTy)) _ -> panic "match_Word64ToInteger: Id has the wrong type" match_Word64ToInteger _ _ _ _ = Nothing ------------------------------------------------- match_Integer_convert :: Num a => (DynFlags -> a -> Expr CoreBndr) -> RuleFun match_Integer_convert convert dflags id_unf _ [xl] | Just (LitInteger x _) <- exprIsLiteral_maybe id_unf xl = Just (convert dflags (fromInteger x)) match_Integer_convert _ _ _ _ _ = Nothing match_Integer_unop :: (Integer -> Integer) -> RuleFun match_Integer_unop unop _ id_unf _ [xl] | Just (LitInteger x i) <- exprIsLiteral_maybe id_unf xl = Just (Lit (LitInteger (unop x) i)) match_Integer_unop _ _ _ _ _ = Nothing {- Note [Rewriting bitInteger] For most types the bitInteger operation can be implemented in terms of shifts. The integer-gmp package, however, can do substantially better than this if allowed to provide its own implementation. However, in so doing it previously lost constant-folding (see Trac #8832). The bitInteger rule above provides constant folding specifically for this function. There is, however, a bit of trickiness here when it comes to ranges. While the AST encodes all integers (even MachInts) as Integers, `bit` expects the bit index to be given as an Int. Hence we coerce to an Int in the rule definition. This will behave a bit funny for constants larger than the word size, but the user should expect some funniness given that they will have at very least ignored a warning in this case. -} match_IntToInteger_unop :: (Integer -> Integer) -> RuleFun match_IntToInteger_unop unop _ id_unf fn [xl] | Just (MachInt x) <- exprIsLiteral_maybe id_unf xl = case idType fn of FunTy _ integerTy -> Just (Lit (LitInteger (unop x) integerTy)) _ -> panic "match_IntToInteger_unop: Id has the wrong type" match_IntToInteger_unop _ _ _ _ _ = Nothing match_Integer_binop :: (Integer -> Integer -> Integer) -> RuleFun match_Integer_binop binop _ id_unf _ [xl,yl] | Just (LitInteger x i) <- exprIsLiteral_maybe id_unf xl , Just (LitInteger y _) <- exprIsLiteral_maybe id_unf yl = Just (Lit (LitInteger (x `binop` y) i)) match_Integer_binop _ _ _ _ _ = Nothing -- This helper is used for the quotRem and divMod functions match_Integer_divop_both :: (Integer -> Integer -> (Integer, Integer)) -> RuleFun match_Integer_divop_both divop _ id_unf _ [xl,yl] | Just (LitInteger x t) <- exprIsLiteral_maybe id_unf xl , Just (LitInteger y _) <- exprIsLiteral_maybe id_unf yl , y /= 0 , (r,s) <- x `divop` y = Just $ mkConApp (tupleDataCon Unboxed 2) [Type t, Type t, Lit (LitInteger r t), Lit (LitInteger s t)] match_Integer_divop_both _ _ _ _ _ = Nothing -- This helper is used for the quot and rem functions match_Integer_divop_one :: (Integer -> Integer -> Integer) -> RuleFun match_Integer_divop_one divop _ id_unf _ [xl,yl] | Just (LitInteger x i) <- exprIsLiteral_maybe id_unf xl , Just (LitInteger y _) <- exprIsLiteral_maybe id_unf yl , y /= 0 = Just (Lit (LitInteger (x `divop` y) i)) match_Integer_divop_one _ _ _ _ _ = Nothing match_Integer_Int_binop :: (Integer -> Int -> Integer) -> RuleFun match_Integer_Int_binop binop _ id_unf _ [xl,yl] | Just (LitInteger x i) <- exprIsLiteral_maybe id_unf xl , Just (MachInt y) <- exprIsLiteral_maybe id_unf yl = Just (Lit (LitInteger (x `binop` fromIntegral y) i)) match_Integer_Int_binop _ _ _ _ _ = Nothing match_Integer_binop_Prim :: (Integer -> Integer -> Bool) -> RuleFun match_Integer_binop_Prim binop dflags id_unf _ [xl, yl] | Just (LitInteger x _) <- exprIsLiteral_maybe id_unf xl , Just (LitInteger y _) <- exprIsLiteral_maybe id_unf yl = Just (if x `binop` y then trueValInt dflags else falseValInt dflags) match_Integer_binop_Prim _ _ _ _ _ = Nothing match_Integer_binop_Ordering :: (Integer -> Integer -> Ordering) -> RuleFun match_Integer_binop_Ordering binop _ id_unf _ [xl, yl] | Just (LitInteger x _) <- exprIsLiteral_maybe id_unf xl , Just (LitInteger y _) <- exprIsLiteral_maybe id_unf yl = Just $ case x `binop` y of LT -> ltVal EQ -> eqVal GT -> gtVal match_Integer_binop_Ordering _ _ _ _ _ = Nothing match_Integer_Int_encodeFloat :: RealFloat a => (a -> Expr CoreBndr) -> RuleFun match_Integer_Int_encodeFloat mkLit _ id_unf _ [xl,yl] | Just (LitInteger x _) <- exprIsLiteral_maybe id_unf xl , Just (MachInt y) <- exprIsLiteral_maybe id_unf yl = Just (mkLit $ encodeFloat x (fromInteger y)) match_Integer_Int_encodeFloat _ _ _ _ _ = Nothing --------------------------------------------------- -- constant folding for Float/Double -- -- This turns -- rationalToFloat n d -- into a literal Float, and similarly for Doubles. -- -- it's important to not match d == 0, because that may represent a -- literal "0/0" or similar, and we can't produce a literal value for -- NaN or +-Inf match_rationalTo :: RealFloat a => (a -> Expr CoreBndr) -> RuleFun match_rationalTo mkLit _ id_unf _ [xl, yl] | Just (LitInteger x _) <- exprIsLiteral_maybe id_unf xl , Just (LitInteger y _) <- exprIsLiteral_maybe id_unf yl , y /= 0 = Just (mkLit (fromRational (x % y))) match_rationalTo _ _ _ _ _ = Nothing match_decodeDouble :: RuleFun match_decodeDouble _ id_unf fn [xl] | Just (MachDouble x) <- exprIsLiteral_maybe id_unf xl = case idType fn of FunTy _ (TyConApp _ [integerTy, intHashTy]) -> case decodeFloat (fromRational x :: Double) of (y, z) -> Just $ mkConApp (tupleDataCon Unboxed 2) [Type integerTy, Type intHashTy, Lit (LitInteger y integerTy), Lit (MachInt (toInteger z))] _ -> panic "match_decodeDouble: Id has the wrong type" match_decodeDouble _ _ _ _ = Nothing match_XToIntegerToX :: Name -> RuleFun match_XToIntegerToX n _ _ _ [App (Var x) y] | idName x == n = Just y match_XToIntegerToX _ _ _ _ _ = Nothing match_smallIntegerTo :: PrimOp -> RuleFun match_smallIntegerTo primOp _ _ _ [App (Var x) y] | idName x == smallIntegerName = Just $ App (Var (mkPrimOpId primOp)) y match_smallIntegerTo _ _ _ _ _ = Nothing
ml9951/ghc
compiler/prelude/PrelRules.hs
bsd-3-clause
59,291
825
14
17,696
11,894
6,457
5,437
869
9
module B1.Data.Price.Google ( getGooglePrices , parseGoogleCsv ) where import Control.Exception import Data.Either import Data.Maybe import Data.Time import Network.HTTP hiding (close) import Network.Stream hiding (close) import System.IO import System.Locale import B1.Data.Price import B1.Data.String.Utils -- | Get price information using Google Finance. -- Returns a tuple of Nothing and a list of error messages if tthere was a -- network problem or parsing issue. getGooglePrices :: LocalTime -> LocalTime -> String -> IO (Either [Price] String) getGooglePrices startDate endDate symbol = pricesOrError where formatDate = formatTime Data.Time.defaultTimeLocale "%m/%d/%y" formattedStartDate = formatDate startDate formattedEndDate = formatDate endDate url = "http://www.google.com/finance/historical?q=NASDAQ:" ++ symbol ++ "&startdate=" ++ formattedStartDate ++ "&enddate=" ++ formattedEndDate ++ "&output=csv" pricesOrError = do putStrLn url exceptionOrResult <- try $ simpleHTTP (getRequest url) return $ either handleGetException handleGetResult exceptionOrResult handleGetException :: SomeException -> Either [Price] String handleGetException exception = Right $ show exception handleGetResult :: Either ConnError (Response String) -> Either [Price] String handleGetResult = either handleConError handleResponse handleConError :: ConnError -> Either [Price] String handleConError connError = Right $ show connError handleResponse :: Response String -> Either [Price] String handleResponse response = case rspCode response of (2, 0, 0) -> parseGoogleCsv (rspBody response) (x, y, z) -> Right $ "Response error code: " ++ show x ++ show y ++ show z -- | Parses the CSV response from Google Finance. -- Exposed only for testing purposes. parseGoogleCsv :: String -> Either [Price] String parseGoogleCsv = maybe (Right "Invalid CSV format 1") pricesOrError . maybe Nothing (Just . parsePriceLines) . dropHeader . split '\n' dropHeader :: [String] -> Maybe [String] dropHeader (_:rest) = Just rest dropHeader _ = Nothing parsePriceLines :: [String] -> [Maybe Price] parsePriceLines = map (parsePriceTokens . split ',') parsePriceTokens :: [String] -> Maybe Price parsePriceTokens (date:open:high:low:close:volume:_) = maybePrice where maybeStartTime = parseDateString date maybeEndTime = parseDateString date maybeOpen = parseValue open::Maybe Float maybeHigh = parseValue high::Maybe Float maybeLow = parseValue low::Maybe Float maybeClose = parseValue close::Maybe Float maybeVolume = parseValue volume::Maybe Int maybePrice = if all isJust [maybeStartTime, maybeEndTime] && all isJust [maybeOpen, maybeHigh, maybeLow, maybeClose] && all isJust [maybeVolume] then Just Price { startTime = fromJust maybeStartTime , endTime = fromJust maybeEndTime , open = fromJust maybeOpen , high = fromJust maybeHigh , low = fromJust maybeLow , close = fromJust maybeClose , volume = fromJust maybeVolume } else Nothing parsePriceTokens _ = Nothing parseDateString :: String -> Maybe LocalTime parseDateString time = parseTimeM True Data.Time.defaultTimeLocale "%e-%b-%y-%C" (time ++ "-20") parseValue :: (Read a) => String -> Maybe a parseValue string = case reads string of [(value, "")] -> Just value _ -> Nothing pricesOrError :: [Maybe Price] -> Either [Price] String pricesOrError maybePrices = Left $ catMaybes maybePrices
madjestic/b1
src/B1/Data/Price/Google.hs
bsd-3-clause
3,613
0
13
732
983
516
467
81
2
module GLogger.Server ( initLogger, cleanLog, logDebug, logInfo, logNotice, logWarning, logError, logCritical, logAlert, logEmergency ) where import qualified System.Log.Logger as SL import System.Log.Handler.Simple (fileHandler) import System.Log.Handler (setFormatter) import System.Log.Formatter (tfLogFormatter) import System.IO (withFile, IOMode(..)) import Control.Monad (when) logFileName :: String logFileName = "server.log" loggerName :: String loggerName = "serverLogger" enableLogging :: Bool enableLogging = True initLogger :: IO () initLogger = when enableLogging $ do h <- fileHandler logFileName SL.DEBUG >>= \lh -> return $ setFormatter lh (tfLogFormatter "%T:%q" "[$time: $loggername : $prio] $msg") SL.updateGlobalLogger loggerName (SL.setLevel SL.DEBUG) SL.updateGlobalLogger loggerName (SL.addHandler h) cleanLog :: IO () cleanLog = when enableLogging $ do withFile logFileName WriteMode (\_ -> return ()) logDebug :: String -> IO () logDebug string = when enableLogging $ do SL.debugM loggerName string logInfo :: String -> IO () logInfo string = when enableLogging $ do SL.infoM loggerName string logNotice :: String -> IO () logNotice string = when enableLogging $ do SL.noticeM loggerName string logWarning :: String -> IO () logWarning string = when enableLogging $ do SL.warningM loggerName string logError :: String -> IO () logError string = when enableLogging $ do SL.errorM loggerName string logCritical :: String -> IO () logCritical string = when enableLogging $ do SL.criticalM loggerName string logAlert :: String -> IO () logAlert string = when enableLogging $ do SL.alertM loggerName string logEmergency :: String -> IO () logEmergency string = when enableLogging $ do SL.emergencyM loggerName string
cernat-catalin/haskellGame
src/GLogger/Server.hs
bsd-3-clause
1,815
0
14
314
595
302
293
56
1
{-# OPTIONS_GHC -O2 -fllvm -funbox-strict-fields -mavx -mavx2 -mavx512f #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE UnboxedTuples #-} {-# LANGUAGE FlexibleContexts #-} import Control.DeepSeq import Control.Monad import Control.Monad.Random import Control.Monad.ST import Criterion.Config import Criterion.Main import Data.Params import Data.Primitive.ByteArray import qualified Data.Vector as V import qualified Data.Vector.Generic as VG import qualified Data.Vector.Unboxed as VU import qualified Data.Vector.Storable as VS import GHC.Float import GHC.Int import GHC.Base (Int (..)) import GHC.Prim import Data.SIMD ------------------------------------------------------------------------------- -- config veclen = 16000 critConfig = defaultConfig { cfgPerformGC = ljust True , cfgSamples = ljust 1000 , cfgSummaryFile = ljust $ "summary"++show veclen++".csv" , cfgReport = ljust $ "report"++show veclen++".html" } ------------------------------------------------------------------------------- -- main main = do ----------------------------------- -- initialize single vectors putStrLn "constructing vectors" let lf1 :: [Float] = evalRand (replicateM veclen $ getRandomR (-10000,10000)) (mkStdGen $ 1) lf2 :: [Float] = evalRand (replicateM veclen $ getRandomR (-10000,10000)) (mkStdGen $ 2) ld1 :: [Double] = evalRand (replicateM veclen $ getRandomR (-10000,10000)) (mkStdGen $ 1) ld2 :: [Double] = evalRand (replicateM veclen $ getRandomR (-10000,10000)) (mkStdGen $ 2) let vuf1 = VU.fromList lf1 :: VU.Vector Float vuf2 = VU.fromList lf2 :: VU.Vector Float deepseq vuf1 $ deepseq vuf2 $ return () let vud1 = VU.fromList ld2 :: VU.Vector Double vud2 = VU.fromList ld2 :: VU.Vector Double deepseq vud1 $ deepseq vud2 $ return () let vsf1 = VS.fromList lf1 :: VS.Vector Float vsf2 = VS.fromList lf2 :: VS.Vector Float deepseq vsf1 $ deepseq vsf2 $ return () let vsd1 = VS.fromList ld2 :: VS.Vector Double vsd2 = VS.fromList ld2 :: VS.Vector Double deepseq vsd1 $ deepseq vsd2 $ return () ----------------------------------- -- tests putStrLn "starting criterion" defaultMainWith critConfig (return ()) [ bgroup "VU" [ bgroup "Float" [ bench "diff1" $ nf (distance_diff1 vuf1) vuf2 , bench "diff4" $ nf (distance_diff4 vuf1) vuf2 , bench "simd4" $ nf (distance_unbox_simd4 vuf1) vuf2 , bench "simd8" $ nf (distance_unbox_simd8 vuf1) vuf2 , bench "simd16" $ nf (distance_unbox_simd16 vuf1) vuf2 , bench "hof" $ nf (distance_hof vuf1) vuf2 , bench "hof_simd4" $ nf (distance_unbox_hof_simd4 vuf1) vuf2 , bench "hof_simd8" $ nf (distance_unbox_hof_simd8 vuf1) vuf2 , bench "hof_simd16" $ nf (distance_unbox_hof_simd16 vuf1) vuf2 ] , bgroup "Double" [ bench "diff1" $ nf (distance_diff1 vud1) vud2 , bench "diff4" $ nf (distance_diff4 vud1) vud2 , bench "simd4" $ nf (distance_unbox_simd4 vud1) vud2 , bench "simd8" $ nf (distance_unbox_simd8 vud1) vud2 , bench "hof" $ nf (distance_hof vud1) vud2 , bench "hof_simd4" $ nf (distance_unbox_hof_simd4 vud1) vud2 , bench "hof_simd8" $ nf (distance_unbox_hof_simd8 vud1) vud2 ] ] , bgroup "VS" [ bgroup "Float" [ bench "diff1" $ nf (distance_diff1 vsf1) vsf2 , bench "diff4" $ nf (distance_diff4 vsf1) vsf2 , bench "simd4" $ nf (distance_storable_simd4 vsf1) vsf2 , bench "simd8" $ nf (distance_storable_simd8 vsf1) vsf2 , bench "simd16" $ nf (distance_storable_simd16 vsf1) vsf2 , bench "hof" $ nf (distance_hof vsf1) vsf2 , bench "hof_simd4" $ nf (distance_storable_hof_simd4 vsf1) vsf2 , bench "hof_simd8" $ nf (distance_storable_hof_simd8 vsf1) vsf2 , bench "hof_simd16" $ nf (distance_storable_hof_simd16 vsf1) vsf2 ] , bgroup "Double" [ bench "diff1" $ nf (distance_diff1 vsd1) vsd2 , bench "diff4" $ nf (distance_diff4 vsd1) vsd2 , bench "simd4" $ nf (distance_storable_simd4 vsd1) vsd2 , bench "simd8" $ nf (distance_storable_simd8 vsd1) vsd2 , bench "hof" $ nf (distance_hof vsd1) vsd2 , bench "hof_simd4" $ nf (distance_storable_hof_simd4 vsd1) vsd2 , bench "hof_simd8" $ nf (distance_storable_hof_simd8 vsd1) vsd2 ] ] ] ------------------------------------------------------------------------------- -- distance functions distance_diff1 :: (VG.Vector v f, Floating f) => v f -> v f -> f distance_diff1 !v1 !v2 = sqrt $ go 0 (VG.length v1-1) where go tot (-1) = tot go tot i = go tot' (i-1) where tot' = tot+diff1*diff1 diff1 = v1 `VG.unsafeIndex` i-v2 `VG.unsafeIndex` i distance_diff4 :: (VG.Vector v f, Floating f) => v f -> v f -> f distance_diff4 !v1 !v2 = sqrt $ go 0 (VG.length v1-1) where go tot (-1) = tot go tot i = go tot' (i-4) where tot' = tot+diff1*diff1 +diff2*diff2 +diff3*diff3 +diff4*diff4 diff1 = v1 `VG.unsafeIndex` i-v2 `VG.unsafeIndex` i diff2 = v1 `VG.unsafeIndex` (i-1)-v2 `VG.unsafeIndex` (i-1) diff3 = v1 `VG.unsafeIndex` (i-2)-v2 `VG.unsafeIndex` (i-2) diff4 = v1 `VG.unsafeIndex` (i-3)-v2 `VG.unsafeIndex` (i-3) distance_unbox_simd4 :: ( SIMD4 f , Floating f , VU.Unbox f , VU.Unbox (X4 f) ) => VU.Vector f -> VU.Vector f -> f distance_unbox_simd4 v1 v2 = sqrt $ plusHorizontalX4 $ go 0 (VG.length v1'-1) where v1' = unsafeVectorizeUnboxedX4 v1 v2' = unsafeVectorizeUnboxedX4 v2 go tot (-1) = tot go tot i = go tot' (i-1) where tot' = tot+diff*diff diff = v1' `VG.unsafeIndex` i - v2' `VG.unsafeIndex` i distance_unbox_simd8 :: ( SIMD8 f , Floating f , VU.Unbox f , VU.Unbox (X8 f) ) => VU.Vector f -> VU.Vector f -> f distance_unbox_simd8 v1 v2 = sqrt $ plusHorizontalX8 $ go 0 (VG.length v1'-1) where v1' = unsafeVectorizeUnboxedX8 v1 v2' = unsafeVectorizeUnboxedX8 v2 go tot (-1) = tot go tot i = go tot' (i-1) where tot' = tot+diff*diff diff = v1' `VG.unsafeIndex` i - v2' `VG.unsafeIndex` i distance_unbox_simd16 :: ( SIMD16 f , Floating f , VU.Unbox f , VU.Unbox (X16 f) ) => VU.Vector f -> VU.Vector f -> f distance_unbox_simd16 v1 v2 = sqrt $ plusHorizontalX16 $ go 0 (VG.length v1'-1) where v1' = unsafeVectorizeUnboxedX16 v1 v2' = unsafeVectorizeUnboxedX16 v2 go tot (-1) = tot go tot i = go tot' (i-1) where tot' = tot+diff*diff diff = v1' `VG.unsafeIndex` i - v2' `VG.unsafeIndex` i distance_storable_simd4 :: ( SIMD4 f , Floating f , VS.Storable f , VS.Storable (X4 f) ) => VS.Vector f -> VS.Vector f -> f distance_storable_simd4 v1 v2 = sqrt $ plusHorizontalX4 $ go 0 (VG.length v1'-1) where v1' = vectorizeStorableX4 v1 v2' = vectorizeStorableX4 v2 go tot (-1) = tot go tot i = go tot' (i-1) where tot' = tot+diff*diff diff = v1' `VG.unsafeIndex` i - v2' `VG.unsafeIndex` i distance_storable_simd8 :: ( SIMD8 f , Floating f , VS.Storable f , VS.Storable (X8 f) ) => VS.Vector f -> VS.Vector f -> f distance_storable_simd8 v1 v2 = sqrt $ plusHorizontalX8 $ go 0 (VG.length v1'-1) where v1' = vectorizeStorableX8 v1 v2' = vectorizeStorableX8 v2 go tot (-1) = tot go tot i = go tot' (i-1) where tot' = tot+diff*diff diff = v1' `VG.unsafeIndex` i - v2' `VG.unsafeIndex` i distance_storable_simd16 :: ( SIMD16 f , Floating f , VS.Storable f , VS.Storable (X16 f) ) => VS.Vector f -> VS.Vector f -> f distance_storable_simd16 v1 v2 = sqrt $ plusHorizontalX16 $ go 0 (VG.length v1'-1) where v1' = vectorizeStorableX16 v1 v2' = vectorizeStorableX16 v2 go tot (-1) = tot go tot i = go tot' (i-1) where tot' = tot+diff*diff diff = v1' `VG.unsafeIndex` i - v2' `VG.unsafeIndex` i distance_hof :: (VG.Vector v f, Floating f) => v f -> v f -> f distance_hof v1 v2 = sqrt $ VG.foldl1' (+) $ VG.zipWith (\a1 a2 -> (a1-a2)*(a1-a2)) v1 v2 distance_unbox_hof_simd4 :: ( SIMD4 f , Floating f , VU.Unbox f , VU.Unbox (X4 f) ) => VU.Vector f -> VU.Vector f -> f distance_unbox_hof_simd4 v1 v2 = sqrt $ plusHorizontalX4 $ VG.foldl1' (+) $ (VG.zipWith (\a1 a2 -> (a1-a2)*(a1-a2)) (unsafeVectorizeUnboxedX4 v1) (unsafeVectorizeUnboxedX4 v2)) distance_unbox_hof_simd8 :: ( SIMD8 f , Floating f , VU.Unbox f , VU.Unbox (X8 f) ) => VU.Vector f -> VU.Vector f -> f distance_unbox_hof_simd8 v1 v2 = sqrt $ plusHorizontalX8 $ VG.foldl1' (+) $ (VG.zipWith (\a1 a2 -> (a1-a2)*(a1-a2)) (unsafeVectorizeUnboxedX8 v1) (unsafeVectorizeUnboxedX8 v2)) distance_unbox_hof_simd16 :: ( SIMD16 f , Floating f , VU.Unbox f , VU.Unbox (X16 f) ) => VU.Vector f -> VU.Vector f -> f distance_unbox_hof_simd16 v1 v2 = sqrt $ plusHorizontalX16 $ VG.foldl1' (+) $ (VG.zipWith (\a1 a2 -> (a1-a2)*(a1-a2)) (unsafeVectorizeUnboxedX16 v1) (unsafeVectorizeUnboxedX16 v2)) distance_storable_hof_simd4 :: ( SIMD4 f , Floating f , VS.Storable f , VS.Storable (X4 f) ) => VS.Vector f -> VS.Vector f -> f distance_storable_hof_simd4 v1 v2 = sqrt $ plusHorizontalX4 $ VG.foldl1' (+) $ (VG.zipWith (\a1 a2 -> (a1-a2)*(a1-a2)) (vectorizeStorableX4 v1) (vectorizeStorableX4 v2)) distance_storable_hof_simd8 :: ( SIMD8 f , Floating f , VS.Storable f , VS.Storable (X8 f) ) => VS.Vector f -> VS.Vector f -> f distance_storable_hof_simd8 v1 v2 = sqrt $ plusHorizontalX8 $ VG.foldl1' (+) $ (VG.zipWith (\a1 a2 -> (a1-a2)*(a1-a2)) (vectorizeStorableX8 v1) (vectorizeStorableX8 v2)) distance_storable_hof_simd16 :: ( SIMD16 f , Floating f , VS.Storable f , VS.Storable (X16 f) ) => VS.Vector f -> VS.Vector f -> f distance_storable_hof_simd16 v1 v2 = sqrt $ plusHorizontalX16 $ VG.foldl1' (+) $ (VG.zipWith (\a1 a2 -> (a1-a2)*(a1-a2)) (vectorizeStorableX16 v1) (vectorizeStorableX16 v2))
mikeizbicki/simd
examples/criterion-distance.hs
bsd-3-clause
12,055
0
16
4,254
3,920
2,012
1,908
252
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module GasModelSpec (spec) where import Test.Hspec import Test.Hspec.Golden as G import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy as BL import qualified Data.Set as S import qualified Data.Text as T import qualified Data.HashMap.Strict as HM import qualified Data.Map as Map import qualified Data.Yaml as Y import Control.Lens hiding ((.=)) import Control.Exception (bracket, throwIO) import Control.Monad (when) import Data.Aeson import Data.Int (Int64) import Data.List (foldl') import Test.QuickCheck import Test.QuickCheck.Gen (Gen(..)) import Test.QuickCheck.Random (mkQCGen) import System.Directory import GoldenSpec (cleanupActual) import Pact.Types.Exp import Pact.Types.SizeOf import Pact.Types.PactValue import Pact.Types.Runtime import Pact.GasModel.GasModel import Pact.GasModel.Types import Pact.GasModel.Utils import Pact.GasModel.GasTests import Pact.Gas.Table import Pact.Native spec :: Spec spec = describe "gas model tests" $ do describe "untestedNativesCheck" untestedNativesCheck describe "allGasTestsAndGoldenShouldPass" allGasTestsAndGoldenShouldPass describe "allNativesInGasTable" allNativesInGasTable describe "goldenSizeOfPactValues" goldenSizeOfPactValues untestedNativesCheck :: Spec untestedNativesCheck = do it "only deprecated or constant natives should be missing gas model tests" $ S.fromList (map asString untestedNatives) `shouldBe` (S.fromList [ "CHARSET_ASCII" , "CHARSET_LATIN1" , "verify-spv" , "public-chain-data" , "list" ]) allGasTestsAndGoldenShouldPass :: Spec allGasTestsAndGoldenShouldPass = after_ (cleanupActual "gas-model" []) $ allGasTestsAndGoldenShouldPass' -- | Calling directly is useful as it doesn't clean up, so you can use the actual -- as a new golden on expected changes. allGasTestsAndGoldenShouldPass' :: Spec allGasTestsAndGoldenShouldPass' = do res <- runIO gasTestResults -- fails if one of the gas tests throws a pact error let allActualOutputsGolden = map toGoldenOutput res it "gas model tests should not return a PactError, but should pass golden" $ do (golden "gas-model" allActualOutputsGolden) golden :: (FromJSON a,ToJSON a) => String -> a -> Golden a golden name obj = Golden { G.output = obj , G.encodePretty = B.unpack . Y.encode , G.writeToFile = Y.encodeFile , G.readFromFile = Y.decodeFileThrow , G.testName = name , G.directory = "golden" , G.failFirstTime = False } goldenSizeOfPactValues :: Spec goldenSizeOfPactValues = do mapM_ (someGoldenSizeOfPactValue . fst) pactValuesDescAndGen allNativesInGasTable :: Spec allNativesInGasTable = do it "all native functions should be in gas table" $ do let justNatives = map (asString . fst) (concatMap snd natives) absent li name = case (Map.lookup name defaultGasTable) of Nothing -> name : li Just _ -> li absentNatives = foldl' absent [] justNatives (S.fromList absentNatives) `shouldBe` (S.fromList ["CHARSET_ASCII", "CHARSET_LATIN1", "public-chain-data", "list"]) gasTestResults :: IO [GasTestResult ([Term Name], EvalState)] gasTestResults = concat <$> mapM (runTest . snd) (HM.toList unitTests) -- | Use this to run a single named test. _runNative :: NativeDefName -> IO (Maybe [(T.Text,Gas)]) _runNative = traverse (fmap (map toGoldenOutput) . runTest) . unitTestFromDef runTest :: GasUnitTests -> IO [GasTestResult ([Term Name], EvalState)] runTest t = mapOverGasUnitTests t run run where run expr dbSetup = do (res, st) <- bracket (setupEnv' dbSetup) (gasSetupCleanup dbSetup) (mockRun expr) res' <- eitherDie (getDescription expr dbSetup) res return (res', st) setupEnv' dbs = do (r, s) <- setupEnv dbs let r' = set eeExecutionConfig (mkExecutionConfig [FlagDisableInlineMemCheck]) r pure (r', s) toGoldenOutput :: GasTestResult ([Term Name], EvalState) -> (T.Text, Gas) toGoldenOutput r = (_gasTestResultDesciption r, gasCost r) where gasCost = _evalGas . snd . _gasTestResultSqliteDb -- Utils -- -- | Pseudo golden test of the Gas Model's sizeOf function. -- Enforces that the sizeOf function remains the same for some pre-generated, -- psuedo-random pact value. someGoldenSizeOfPactValue :: String -> Spec someGoldenSizeOfPactValue desc = do it ("passes sizeOf golden test with pseudo-random " <> desc <> " pact value") $ do (goldenSize, goldenPactValue) <- jsonDecode (goldenPactValueFilePath desc) let actualSize = sizeOf goldenPactValue actualSize `shouldBe` goldenSize where jsonDecode :: FilePath -> IO (Int64, PactValue) jsonDecode fp = do isGoldenFilePresent <- doesFileExist fp when (not isGoldenFilePresent) $ throwIO $ userError $ "Golden pact value file does not exist: " ++ show fp r <- eitherDecode <$> BL.readFile fp case r of Left e -> throwIO $ userError $ "golden decode failed: " ++ show e Right v -> return v -- | Genearates golden files expected in `someGoldenSizeOfPactValue` -- Creates a golden file in the format of (sizeOf <somePactValue>, <somePactValue>) _generateGoldenPactValues :: IO () _generateGoldenPactValues = mapM_ f pactValuesDescAndGen where f (desc, genPv) = do let fp = goldenPactValueFilePath desc _ <- createDirectoryIfMissing False (goldenPactValueDirectory desc) isGoldenFilePresent <- doesFileExist fp when (not isGoldenFilePresent) (createGolden fp genPv) createGolden fp genPv = do -- TODO add quickcheck propeties for json roundtrips pv <- generate $ suchThat genPv satisfiesRoundtripJSON jsonEncode fp (sizeOf pv, pv) jsonEncode :: FilePath -> (Int64, PactValue) -> IO () jsonEncode fp = BL.writeFile fp . encode -- | List of pact value pseudo-random generators and their descriptions pactValuesDescAndGen :: [(String, Gen PactValue)] pactValuesDescAndGen = genSomeLiteralPactValues seed <> genSomeGuardPactValues seed <> [ ("list", genSomeListPactValue seed) , ("object-map", genSomeObjectPactValue seed) ] goldenPactValueDirectory :: String -> FilePath goldenPactValueDirectory desc = goldenDirectory <> "/" <> testPrefix <> desc where goldenDirectory = "golden" testPrefix = "size-of-pactvalue-" goldenPactValueFilePath :: String -> FilePath goldenPactValueFilePath desc = (goldenPactValueDirectory desc) <> "/golden" -- To run a generator in the repl: -- `import Pact.Types.Pretty` -- `import Data.Aeson (toJSON)` -- `fmap (pretty . toJSON) (generate $ genSomeLiteralPactValue seed)` -- | Generator of some psuedo-random Literal pact values genSomeLiteralPactValues :: Int -> [(String, Gen PactValue)] genSomeLiteralPactValues s = [ ("literal-string", f genLiteralString) , ("literal-integer", f genLiteralInteger) , ("literal-decimal", f genLiteralDecimal) , ("literal-bool", f genLiteralBool) , ("literal-time", f genLiteralTime) ] where f g = PLiteral <$> genWithSeed s g -- | Generator of some psuedo-random List pact value genSomeListPactValue :: Int -> Gen PactValue genSomeListPactValue s = genWithSeed s $ PList <$> genPactValueList RecurseTwice -- | Generator of some psuedo-random ObjectMap pact value genSomeObjectPactValue :: Int -> Gen PactValue genSomeObjectPactValue s = genWithSeed s $ PObject <$> genPactValueObjectMap RecurseTwice -- | Generator of some psuedo-random Guard pact values genSomeGuardPactValues :: Int -> [(String, Gen PactValue)] genSomeGuardPactValues s = [ ("guard-pact", f $ GPact <$> arbitrary) , ("guard-keySet", f $ GKeySet <$> arbitrary) , ("guard-keySetRef", f $ GKeySetRef <$> arbitrary) , ("guard-module", f $ GModule <$> arbitrary) , ("guard-user", f $ genUserGuard RecurseTwice) ] where f g = PGuard <$> genWithSeed s g -- | Generate arbitrary value with the provided "random" seed. -- Allows for replicating arbitrary values. genWithSeed :: Int -> Gen a -> Gen a genWithSeed i (MkGen g) = MkGen (\_ n -> g (mkQCGen i) n) -- | Random seed used to generate the pact values in the sizeOf golden tests seed :: Int seed = 10000000000 _diffGoldens :: FilePath -> FilePath -> IO () _diffGoldens g1 g2 = do (y1 :: Map.Map T.Text [Int]) <- fmap pure . Map.fromList <$> Y.decodeFileThrow g1 (y2 :: Map.Map T.Text [Int]) <- fmap pure . Map.fromList <$> Y.decodeFileThrow g2 let merge [c1] [c2] = [c1,c2,c2-c1] merge _ _ = [] Y.encodeFile "diff.yaml" $ Map.unionWith merge y1 y2
kadena-io/pact
tests/GasModelSpec.hs
bsd-3-clause
8,571
0
17
1,555
2,188
1,167
1,021
169
2
{-# LANGUAGE FlexibleContexts #-} {- | Module : Data.Random.Extras Copyright : 2010 Aristid Breitkreuz License : BSD3 Stability : experimental Portability : portable Additional monadic random functions, based on random-fu. -} module Data.Random.Extras ( -- * Random functions -- ** Shuffling shuffle , shuffleSeq -- ** Sampling , sample , sampleSeq -- ** Choice , choiceExtract , choiceExtractSeq , choice , safeChoice , iterativeChoice , choiceSeq , safeChoiceSeq , choiceArray -- ** Choices , choices , safeChoices , choicesArray ) where import Control.Monad import Data.Random.RVar import Data.Random.Distribution import Data.Random.Distribution.Uniform import Data.List import Data.Maybe import qualified Data.Sequence as Seq import Data.Sequence ((><), ViewL((:<))) import qualified Data.Array.IArray as Arr import qualified Data.Array import Data.Array.IArray ((!)) moduleError :: String -> String -> a moduleError n s = error $ "Data.Random.Extras." ++ n ++ ": " ++ s (.:) :: (c -> c') -> (a -> b -> c) -> (a -> b -> c') (.:) = (.).(.) extract :: [a] -> Int -> Maybe ([a], a) extract s i | null r = Nothing | otherwise = Just (a ++ c, b) where (a, r) = splitAt i s (b : c) = r extractSeq :: Seq.Seq a -> Int -> Maybe (Seq.Seq a, a) extractSeq s i | Seq.null r = Nothing | otherwise = Just (a >< c, b) where (a, r) = Seq.splitAt i s (b :< c) = Seq.viewl r backsaw :: Int -> [Int] backsaw n = [n - 1, n - 2 .. 0] -- Shuffling -- | Shuffle a list randomly. The method is based on Oleg Kiselyov's -- /perfect shuffle/ <http://okmij.org/ftp/Haskell/perfect-shuffle.txt>, -- but much simpler because it uses existing data structures. The efficiency -- of both methods should be comparable. -- -- /Complexity:/ O(n * log n), where /n/ is the length of the input list. shuffle :: [a] -> RVar [a] shuffle = shuffleSeq . Seq.fromList -- | Shuffle a sequence randomly. This is being used by 'shuffle', -- so it logically uses the same method. -- -- /Complexity:/ O(n * log n), where /n/ is the length of the input sequence. shuffleSeq :: Seq.Seq a -> RVar [a] shuffleSeq s = do samples <- mapM (uniform 0) . backsaw $ Seq.length s return (shuffleSeq' s samples) shuffleSeq' :: Seq.Seq a -> [Int] -> [a] shuffleSeq' = snd .: mapAccumL (fromJust .: extractSeq) -- Sampling -- | Take a random sample from a list. -- -- /Complexity:/ O(n + m * log n), where /n/ is the length of the input list -- and /m/ is the sample size. sample :: Int -> [a] -> RVar [a] sample m = sampleSeq m . Seq.fromList -- | Take a random sample from a sequence. -- -- /Complexity:/ O(m * log n), where /n/ is the length of the input sequence -- and /m/ is the sample size. sampleSeq :: Int -> Seq.Seq a -> RVar [a] sampleSeq m s = do samples <- mapM (uniform 0) . take m . backsaw $ Seq.length s return (shuffleSeq' s samples) -- Choice -- | Randomly choose and extract an element from a list. -- -- /Complexity:/ O(n), where /n/ is the length of the input list. choiceExtract :: [a] -> Maybe (RVar ([a], a)) choiceExtract [] = Nothing choiceExtract xs = Just $ (fromJust . extract xs) `liftM` uniform 0 (length xs - 1) -- | Randomly choose and extract an element from a sequence. -- -- /Complexity:/ O(log n), where /n/ is the length of the input sequence. choiceExtractSeq :: Seq.Seq a -> Maybe (RVar (Seq.Seq a, a)) choiceExtractSeq s | Seq.null s = Nothing | otherwise = Just $ (fromJust . extractSeq s) `liftM` uniform 0 (Seq.length s - 1) -- | Select a random element from a list. -- -- /Partial function:/ This function is only defined on non-empty lists. -- -- /Complexity:/ O(n), where /n/ is the length of the input list. choice :: [a] -> RVar a choice [] = moduleError "choice" "empty list" choice xs = (xs !!) `liftM` uniform 0 (length xs - 1) -- | Safely select a random element from a list. -- -- /Complexity:/ O(n), where /n/ is the length of the input list. safeChoice :: [a] -> Maybe (RVar a) safeChoice [] = Nothing safeChoice xs = Just $ choice xs -- | Select a random element from a list, traversing the list only once. -- -- /Partial function:/ This function is only defined on non-empty lists -- with a length below ('maxBound' + 1 :: Int). -- -- /Complexity:/ O(n), where /n/ is the length of the input list. iterativeChoice :: [a] -> RVar a iterativeChoice xs = fst `liftM` foldl' stepM (return start) xs where stepM x y = x >>= step y step offered (old, n) = do i <- uniform 0 n let new | i == 0 = offered | otherwise = old return $! new `seq` (new, n + 1) start = (err, 0 :: Int) err = moduleError "iterativeChoice" "empty list" -- | Select a random element from a sequence. -- -- /Partial function:/ This function is only defined on non-empty sequences. -- -- /Complexity:/ O(log n), where /n/ is the length of the input sequence. choiceSeq :: Seq.Seq a -> RVar a choiceSeq s | Seq.null s = moduleError "choiceSeq" "empty sequence" | otherwise = Seq.index s `liftM` uniform 0 (Seq.length s - 1) -- | Safely select a random element from a sequence. -- -- /Complexity:/ O(log n), where /n/ is the length of the input sequence. safeChoiceSeq :: Seq.Seq a -> Maybe (RVar a) safeChoiceSeq s | Seq.null s = Nothing | otherwise = Just $ choiceSeq s -- | Select a random element from an array. -- -- /Complexity:/ O(1). choiceArray :: (Arr.IArray arr a, Arr.Ix i, Distribution Uniform i) => arr i a -> RVar a choiceArray v = (v !) `liftM` uncurry uniform (Arr.bounds v) -- Choices -- | A stream of random elements from a list. -- -- /Partial function:/ This function is only defined on non-empty lists. -- -- /Complexity:/ O(n) base and O(1) per element. choices :: Int -> [a] -> RVar [a] choices _ [] = moduleError "choices" "empty list" choices n xs = choicesArray n $ Data.Array.listArray (1, length xs) xs -- | Safely get a stream of random elements from a list. -- -- /Complexity:/ O(n) base and O(1) per element, where /n/ is the length of -- the input list. safeChoices :: Int -> [a] -> Maybe (RVar [a]) safeChoices _ [] = Nothing safeChoices n xs = Just $ choices n xs -- | A stream of random elements from an array. -- -- /Complexity:/ O(1) per element. choicesArray :: (Arr.IArray arr a, Arr.Ix i, Distribution Uniform i) => Int -> arr i a -> RVar [a] choicesArray n v = map (v !) `liftM` replicateM n (uncurry uniform (Arr.bounds v))
aristidb/random-extras
Data/Random/Extras.hs
bsd-3-clause
6,599
1
15
1,512
1,730
938
792
97
1
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} {-| Module : Numeric.AERN.RealArithmetic.Basis.MPFR.MixedFieldOps Description : rounded basic arithmetic operations mixing MPFR and another type Copyright : (c) Michal Konecny License : BSD3 Maintainer : mikkonecny@gmail.com Stability : experimental Portability : portable Rounded basic arithmetical operations mixing MPFR and another type. This module is hidden and reexported via its parent MPFR. -} module Numeric.AERN.RealArithmetic.Basis.MPFR.MixedFieldOps where import Numeric.AERN.RealArithmetic.Basis.MPFR.Basics import Numeric.AERN.RealArithmetic.Basis.MPFR.Conversion import Numeric.AERN.RealArithmetic.Basis.MPFR.NumericOrder import Numeric.AERN.RealArithmetic.Basis.MPFR.FieldOps import Numeric.AERN.RealArithmetic.Basis.MPFR.Utilities import Numeric.AERN.RealArithmetic.NumericOrderRounding instance RoundedMixedAddEffort MPFR Int where type MixedAddEffortIndicator MPFR Int = () mixedAddDefaultEffort _ _ = () -- TODO: will need to extend rounded to link to MPFR addi etc ... instance RoundedMixedAdd MPFR Int where mixedAddUpEff _ d i = mixedAddUpEffByConversion ((), ()) d i mixedAddDnEff _ d i = mixedAddDnEffByConversion ((), ()) d i -- mixedAddUpEff _ d n = M.addi M.Up (getPrecision d) d n -- mixedAddDnEff _ d n = M.addi M.Down (getPrecision d) d n instance RoundedMixedMultiplyEffort MPFR Int where type MixedMultEffortIndicator MPFR Int = () mixedMultDefaultEffort _ _ = () instance RoundedMixedMultiply MPFR Int where mixedMultUpEff _ d i = mixedMultUpEffByConversion ((), (), ()) d i mixedMultDnEff _ d i = mixedMultDnEffByConversion ((), (), ()) d i -- mixedMultUpEff _ d i = -- -- infty * 0 is NaN -- detectNaNUp ("mixed multiplication " ++ show d ++ " *^| " ++ show i ) $ -- M.muli M.Up (getPrecision d) d i -- mixedMultDnEff _ d i = -- detectNaNDn ("mixed multiplication " ++ show d ++ " *.| " ++ show i ) $ -- M.muli M.Down (getPrecision d) d i instance RoundedMixedDivideEffort MPFR Int where type MixedDivEffortIndicator MPFR Int = () mixedDivDefaultEffort _ _ = () instance RoundedMixedDivide MPFR Int where mixedDivUpEff _ d i = mixedDivUpEffByConversion ((), (), ((),())) d i mixedDivDnEff _ d i = mixedDivDnEffByConversion ((), (), ((),())) d i -- mixedDivUpEff _ d i = -- -- 0 / 0 is NaN -- detectNaNUp ("mixed division " ++ show d ++ " /^| " ++ show i ) $ -- M.divi M.Up (getPrecision d) d i -- mixedDivDnEff _ d i = -- detectNaNDn ("mixed division " ++ show d ++ " /.| " ++ show i ) $ -- M.divi M.Down (getPrecision d) d i instance RoundedMixedRingEffort MPFR Int where type MixedRingOpsEffortIndicator MPFR Int = () mixedRingOpsDefaultEffort _ _ = () mxringEffortAdd _ _ _ = () mxringEffortMult _ _ _ = () instance RoundedMixedRing MPFR Int instance RoundedMixedFieldEffort MPFR Int where type MixedFieldOpsEffortIndicator MPFR Int = () mixedFieldOpsDefaultEffort _ _ = () mxfldEffortAdd _ _ _ = () mxfldEffortMult _ _ _ = () mxfldEffortDiv _ _ _ = () instance RoundedMixedField MPFR Int instance RoundedMixedAddEffort MPFR Integer where type MixedAddEffortIndicator MPFR Integer = () mixedAddDefaultEffort _ _ = () instance RoundedMixedAdd MPFR Integer where mixedAddUpEff _ d i = mixedAddUpEffByConversion ((), ()) d i mixedAddDnEff _ d i = mixedAddDnEffByConversion ((), ()) d i instance RoundedMixedMultiplyEffort MPFR Integer where type MixedMultEffortIndicator MPFR Integer = () mixedMultDefaultEffort _ _ = () instance RoundedMixedMultiply MPFR Integer where mixedMultUpEff _ d i = mixedMultUpEffByConversion ((), (), ()) d i mixedMultDnEff _ d i = mixedMultDnEffByConversion ((), (), ()) d i instance RoundedMixedDivideEffort MPFR Integer where type MixedDivEffortIndicator MPFR Integer = () mixedDivDefaultEffort _ _ = () instance RoundedMixedDivide MPFR Integer where mixedDivUpEff _ d i = mixedDivUpEffByConversion ((), (), ((),())) d i mixedDivDnEff _ d i = mixedDivDnEffByConversion ((), (), ((),())) d i instance RoundedMixedRingEffort MPFR Integer where type MixedRingOpsEffortIndicator MPFR Integer = () mixedRingOpsDefaultEffort _ _ = () mxringEffortAdd _ _ eff = () mxringEffortMult _ _ eff = () instance RoundedMixedRing MPFR Integer instance RoundedMixedFieldEffort MPFR Integer where type MixedFieldOpsEffortIndicator MPFR Integer = () mixedFieldOpsDefaultEffort _ _ = () mxfldEffortAdd _ _ eff = () mxfldEffortMult _ _ eff = () mxfldEffortDiv _ _ eff = () instance RoundedMixedField MPFR Integer instance RoundedMixedAddEffort MPFR Rational where type MixedAddEffortIndicator MPFR Rational = () mixedAddDefaultEffort _ _ = () instance RoundedMixedAdd MPFR Rational where mixedAddUpEff _ d r = mixedAddUpEffByConversion ((), ()) d r mixedAddDnEff _ d r = mixedAddDnEffByConversion ((), ()) d r instance RoundedMixedMultiplyEffort MPFR Rational where type MixedMultEffortIndicator MPFR Rational = () mixedMultDefaultEffort _ _ = () instance RoundedMixedMultiply MPFR Rational where mixedMultUpEff _ d r = mixedMultUpEffByConversion ((), (), ()) d r mixedMultDnEff _ d r = mixedMultDnEffByConversion ((), (), ()) d r instance RoundedMixedDivideEffort MPFR Rational where type MixedDivEffortIndicator MPFR Rational = () mixedDivDefaultEffort _ _ = () instance RoundedMixedDivide MPFR Rational where mixedDivUpEff _ d r = mixedDivUpEffByConversion ((), (), ((),())) d r mixedDivDnEff _ d r = mixedDivDnEffByConversion ((), (), ((),())) d r instance RoundedMixedRingEffort MPFR Rational where type MixedRingOpsEffortIndicator MPFR Rational = () mixedRingOpsDefaultEffort _ _ = () mxringEffortAdd sample _ eff = () mxringEffortMult sample _ eff = () instance RoundedMixedRing MPFR Rational instance RoundedMixedFieldEffort MPFR Rational where type MixedFieldOpsEffortIndicator MPFR Rational = () mixedFieldOpsDefaultEffort _ _ = () mxfldEffortAdd sample _ eff = () mxfldEffortMult sample _ eff = () mxfldEffortDiv sample _ eff = () instance RoundedMixedField MPFR Rational instance RoundedMixedAddEffort MPFR Double where type MixedAddEffortIndicator MPFR Double = () mixedAddDefaultEffort _ _ = () instance RoundedMixedAdd MPFR Double where mixedAddUpEff _ d r = mixedAddUpEffByConversion ((), ()) d r mixedAddDnEff _ d r = mixedAddDnEffByConversion ((), ()) d r -- mixedAddUpEff _ d i = -- -- infty - infty is NaN -- detectNaNUp ("mixed addition " ++ show d ++ " +^| " ++ show i ) $ -- M.addd M.Up (getPrecision d) d i -- mixedAddDnEff _ d i = -- detectNaNUp ("mixed addition " ++ show d ++ " +.| " ++ show i ) $ -- M.addd M.Down (getPrecision d) d i instance RoundedMixedMultiplyEffort MPFR Double where type MixedMultEffortIndicator MPFR Double = () mixedMultDefaultEffort _ _ = () instance RoundedMixedMultiply MPFR Double where mixedMultUpEff _ d r = mixedMultUpEffByConversion ((), (), ()) d r mixedMultDnEff _ d r = mixedMultDnEffByConversion ((), (), ()) d r -- mixedMultUpEff _ d i = -- -- infty * 0 is NaN -- detectNaNUp ("mixed multiplication " ++ show d ++ " *^| " ++ show i ) $ -- M.muld M.Up (getPrecision d) d i -- mixedMultDnEff _ d i = -- detectNaNDn ("mixed multiplication " ++ show d ++ " *.| " ++ show i ) $ -- M.muld M.Down (getPrecision d) d i instance RoundedMixedDivideEffort MPFR Double where type MixedDivEffortIndicator MPFR Double = () mixedDivDefaultEffort _ _ = () instance RoundedMixedDivide MPFR Double where mixedDivUpEff _ d i = mixedDivUpEffByConversion ((), (), ((),())) d i mixedDivDnEff _ d i = mixedDivDnEffByConversion ((), (), ((),())) d i -- mixedDivUpEff _ d i = -- -- 0 / 0 is NaN -- detectNaNUp ("mixed division " ++ show d ++ " /^| " ++ show i ) $ -- M.divd M.Up (getPrecision d) d i -- mixedDivDnEff _ d i = -- detectNaNDn ("mixed division " ++ show d ++ " /.| " ++ show i ) $ -- M.divd M.Down (getPrecision d) d i instance RoundedMixedRingEffort MPFR Double where type MixedRingOpsEffortIndicator MPFR Double = () mixedRingOpsDefaultEffort _ _ = () mxringEffortAdd _ _ _ = () mxringEffortMult _ _ _ = () instance RoundedMixedRing MPFR Double instance RoundedMixedFieldEffort MPFR Double where type MixedFieldOpsEffortIndicator MPFR Double = () mixedFieldOpsDefaultEffort _ _ = () mxfldEffortAdd _ _ _ = () mxfldEffortMult _ _ _ = () mxfldEffortDiv _ _ _ = () instance RoundedMixedField MPFR Double instance RoundedMixedAddEffort MPFR MPFR where type MixedAddEffortIndicator MPFR MPFR = () mixedAddDefaultEffort _ _ = () instance RoundedMixedAdd MPFR MPFR where mixedAddUpEff = addUpEff mixedAddDnEff = addDnEff instance RoundedMixedMultiplyEffort MPFR MPFR where type MixedMultEffortIndicator MPFR MPFR = () mixedMultDefaultEffort _ _ = () instance RoundedMixedMultiply MPFR MPFR where mixedMultUpEff = multUpEff mixedMultDnEff = multDnEff instance RoundedMixedDivideEffort MPFR MPFR where type MixedDivEffortIndicator MPFR MPFR = () mixedDivDefaultEffort _ _ = () instance RoundedMixedDivide MPFR MPFR where mixedDivUpEff = divUpEff mixedDivDnEff = divDnEff instance RoundedMixedRingEffort MPFR MPFR where type MixedRingOpsEffortIndicator MPFR MPFR = () mixedRingOpsDefaultEffort _ _ = () mxringEffortAdd _ _ _ = () mxringEffortMult _ _ _ = () instance RoundedMixedRing MPFR MPFR instance RoundedMixedFieldEffort MPFR MPFR where type MixedFieldOpsEffortIndicator MPFR MPFR = () mixedFieldOpsDefaultEffort _ _ = () mxfldEffortAdd _ _ _ = () mxfldEffortMult _ _ _ = () mxfldEffortDiv _ _ _ = () instance RoundedMixedField MPFR MPFR
michalkonecny/aern
aern-mpfr-rounded/src/Numeric/AERN/RealArithmetic/Basis/MPFR/MixedFieldOps.hs
bsd-3-clause
10,427
0
9
2,411
2,441
1,298
1,143
167
0
#include "Prelude.hs" root = () tests = [ (0 == 1, False), (1 == 1, True), (0 /= 1, True), (1 /= 1, False), (1 + 2, 3), (3 - 2, 1), (3 * 2, 6), (3 `div` 2, 1), (4 `div` 2, 2), (1 <= 2, True), (2 <= 2, True), (1 < 2, True), (2 < 2, False), (2 >= 2, True), (1 >= 2, False), (3 > 2, True), (2 > 2, False), (negate (negate 3), 3), (negate 3 /= 3, True), (signum 4, 1), (signum 0, 0), (signum (negate 2), negate 1), (abs 3, 3), (abs (negate 3), 3), (3 `mod` 2, 1), (2 `mod` 4, 2), (show 1, "1"), (show (10 + 9), "19"), (id 3, 3), ((Left . Right) 1, Left (Right 1)), (Left $ 1, Left 1), (not True, False), (not False, True), (False && False, False), (True && False, False), (False && True, False), (True && True, True), (False && undefined, False), (False || False, False), (True || False, True), (False || True, True), (True || True, True), (True || undefined, True), (head (1 : 2 : []), 1), (tail (1 : 2 : []), 2 : []), (length [1, 2, 3], 3), (map Left [1, 2, 3], [Left 1, Left 2, Left 3]), (concatMap (\x -> [x, x]) [1, 2, 3], [1, 1, 2, 2, 3, 3]), (foldr (+) 0 [1, 2, 3], 6), (take 0 [1, 2, 3], []), (take 2 [1, 2, 3], [1, 2]), ([1, 2] ++ [3, 4], [1, 2, 3, 4]), (concat [[1, 2], [3, 4]], [1, 2, 3, 4]), (enumFromTo 1 4, [1, 2, 3, 4]) ]
batterseapower/supercompilation-by-evaluation
examples/PreludeTest.hs
bsd-3-clause
1,335
0
10
374
978
591
387
33
1
module Voting.Ranked.Types where newtype Ballot a = Ballot [a]
nuttycom/haskell-voting
src/Voting/Ranked/Types.hs
bsd-3-clause
64
0
6
10
19
13
6
2
0
module Main where import Tree import Graphics.UI.FLTK.LowLevel.FLTKHS import qualified Graphics.UI.FLTK.LowLevel.FL as FL import Graphics.UI.FLTK.LowLevel.Fl_Types import Graphics.UI.FLTK.LowLevel.Fl_Enumerations main :: IO () main = do win <- make_window showWidget win _ <- FL.run return ()
deech/fltkhs-fluid-examples
src/fluid-tree.hs
mit
302
0
8
42
87
52
35
12
1
module Utils (mparam, defparam, toKey, generatePasscode) where import Control.Monad.IO.Class (liftIO) import Data.Text.Lazy (Text) import System.Random (randomRs, newStdGen) import Database.Persist.Sql (ToBackendKey, SqlBackend, Key, toSqlKey) import Web.Scotty (ActionM, Parsable, param, rescue) mparam :: (Parsable a) => Text -> ActionM (Maybe a) mparam key = fmap Just (param key) `rescue` (\_ -> return Nothing) defparam :: (Parsable a) => Text -> a -> ActionM a defparam key def = param key `rescue` (\_ -> return def) toKey :: ToBackendKey SqlBackend a => Integer -> Key a toKey key = toSqlKey $ fromIntegral (key :: Integer) -------------------------------------------------------------------------------- -- | Generates a random passcode of the given length generatePasscode :: Int -> IO (String) generatePasscode len = do gen <- newStdGen return $ take len $ randomRs ('a', 'z') gen
vyorkin/assignment
api/src/Utils.hs
mit
907
0
9
140
310
172
138
-1
-1
-- -- -- ----------------- -- Exercise 7.34. ----------------- -- -- -- module E'7'34 where import Data.List ( isPrefixOf , drop ) subst :: String -> String -> String -> String subst "" _ string = string subst _ _ "" = "" subst oldSubstring newSubstring string@( stringCharacter : remainingStringCharacters ) | isPrefixOf oldSubstring string = newSubstring ++ (drop (length oldSubstring) string) | otherwise = stringCharacter : subst oldSubstring newSubstring remainingStringCharacters {- GHCi> subst "much " "tall " "How much is that?" -} -- "How tall is that?"
pascal-knodel/haskell-craft
_/links/E'7'34.hs
mit
606
0
10
130
140
77
63
8
1
{-# LANGUAGE DeriveDataTypeable #-} {- | Module : $Header$ Description : CSMOF signature and sentences Copyright : (c) Daniel Calegari Universidad de la Republica, Uruguay 2013 License : GPLv2 or higher, see LICENSE.txt Maintainer : dcalegar@fing.edu.uy Stability : provisional Portability : portable -} module CSMOF.Sign where import CSMOF.As () import qualified Common.Lib.Rel as Rel import Common.Doc import Common.DocUtils import Common.Id import Data.Data import qualified Data.Map as Map import qualified Data.Set as Set data TypeKind = DataTypeKind | ClassKind deriving (Show, Eq, Ord, Typeable, Data) instance Pretty TypeKind where pretty DataTypeKind = text "datatype" pretty ClassKind = text "class" data TypeClass = TypeClass { name :: String, kind :: TypeKind } deriving (Show, Eq, Ord, Typeable, Data) instance Pretty TypeClass where pretty (TypeClass nam _) = text nam type Role = String data PropertyT = PropertyT { sourceRole :: Role , sourceType :: TypeClass , targetRole :: Role , targetType :: TypeClass } deriving (Show, Eq, Ord, Typeable, Data) instance Pretty PropertyT where pretty (PropertyT souR souT tarR tarT) = text "property" <> lparen <> text souR <+> colon <+> pretty souT <+> comma <+> text tarR <+> colon <+> pretty tarT <> rparen data LinkT = LinkT { sourceVar :: Role , targetVar :: Role , property :: PropertyT } deriving (Show, Eq, Ord, Typeable, Data) instance Pretty LinkT where pretty (LinkT souV tarV pro) = text "link" <> lparen <> text souV <+> colon <+> text (sourceRole pro) <+> colon <+> pretty (sourceType pro) <+> comma <+> text tarV <+> colon <+> text (targetRole pro) <+> colon <+> pretty (targetType pro) <+> rparen data Sign = Sign { types :: Set.Set TypeClass , typeRel :: Rel.Rel TypeClass , abstractClasses :: Set.Set TypeClass , roles :: Set.Set Role , properties :: Set.Set PropertyT , instances :: Map.Map String TypeClass , links :: Set.Set LinkT } deriving (Show, Eq, Ord, Typeable, Data) instance GetRange Sign where getRange _ = nullRange rangeSpan _ = [] instance Pretty Sign where pretty (Sign typ tyR abst rol pro ins lin) = Set.fold (($+$) . toType abst) empty typ $++$ foldr (($+$) . toSubRel) empty (Rel.toList tyR) $++$ Set.fold (($+$) . text . ("role " ++)) empty rol $++$ Set.fold (($+$) . pretty) empty pro $++$ foldr (($+$) . toInstance) empty (Map.toList ins) $++$ Set.fold (($+$) . pretty) empty lin toType :: Set.Set TypeClass -> TypeClass -> Doc toType setTC (TypeClass nam ki) = if Set.member (TypeClass nam ki) setTC then text "abstract" <+> pretty ki <+> text nam else pretty ki <+> text nam toSubRel :: (TypeClass, TypeClass) -> Doc toSubRel (a, b) = pretty a <+> text "<" <+> pretty b toInstance :: (String, TypeClass) -> Doc toInstance (a, b) = text "object" <+> text a <+> colon <+> pretty b emptySign :: Sign emptySign = Sign { types = Set.empty , typeRel = Rel.empty , abstractClasses = Set.empty , roles = Set.empty , properties = Set.empty , instances = Map.empty , links = Set.empty } {- signUnion :: Sign -> Sign -> Result Sign signUnion s1 s2 = return s1 { rels = Map.unionWith Set.union (rels s1) (rels s2) , isas = Rel.union (isas s1) (isas s2) } -} data MultConstr = MultConstr { getType :: TypeClass , getRole :: Role } deriving (Show, Eq, Ord, Typeable, Data) instance Pretty MultConstr where pretty (MultConstr tc ro) = pretty tc <> text "." <> text ro data ConstraintType = EQUAL | LEQ | GEQ deriving (Show, Eq, Ord, Typeable, Data) instance Pretty ConstraintType where pretty EQUAL = equals pretty LEQ = text "<=" pretty GEQ = text ">=" data Sen = Sen { constraint :: MultConstr , cardinality :: Integer , constraintType :: ConstraintType } deriving (Show, Eq, Ord, Typeable, Data) instance GetRange Sen where getRange _ = nullRange rangeSpan _ = [] instance Pretty Sen where pretty (Sen con car cty) = pretty con <+> pretty cty <+> pretty car
mariefarrell/Hets
CSMOF/Sign.hs
gpl-2.0
4,660
0
19
1,465
1,360
723
637
100
2
-- | -- Copyright: © 2018 Herbert Valerio Riedel -- SPDX-License-Identifier: GPL-3.0-or-later -- module WorkerApi.Client where import Prelude.Local import Control.Monad.Except (ExceptT (..)) import Servant.API import Servant.HttpStreams import PkgId import WorkerApi runClientM' :: NFData a => BaseUrl -> ClientM a -> ExceptT ClientError IO a runClientM' baseurl act = ExceptT $ withClientEnvIO baseurl (runClientM act) getWorkerInfo :: ClientM WorkerInfo getJobsInfo :: ClientM [JobId] createJob :: CreateJobReq -> ClientM CreateJobRes getJobSolveInfo :: JobId -> ClientM JobSolve getJobBuildDepsInfo :: JobId -> ClientM JobBuildDeps getJobBuildInfo :: JobId -> ClientM JobBuild destroyJob :: JobId -> ClientM NoContent listCompilers :: ClientM [CompilerID] listPkgDbGlobal :: CompilerID -> ClientM [GPkgInfo] listPkgDbStore :: CompilerID -> ClientM [SPkgInfo] destroyPkgDbStore :: CompilerID -> ClientM NoContent getWorkerInfo :<|> getJobsInfo :<|> createJob :<|> getJobSolveInfo :<|> getJobBuildDepsInfo :<|> getJobBuildInfo :<|> destroyJob :<|> listCompilers :<|> listPkgDbGlobal :<|> listPkgDbStore :<|> destroyPkgDbStore = client workerApi workerApi :: Proxy (WorkerApi ()) workerApi = Proxy
Rizary/hackage-matrix-builder
src-lib/WorkerApi/Client.hs
gpl-3.0
1,501
0
14
448
303
160
143
34
1
{-# LANGUAGE CPP #-} -- | -- Module : Statistics.Resampling.Bootstrap -- Copyright : (c) 2009, 2011 Bryan O'Sullivan -- License : BSD3 -- -- Maintainer : bos@serpentine.com -- Stability : experimental -- Portability : portable -- -- The bootstrap method for statistical inference. module Statistics.Resampling.Bootstrap ( bootstrapBCA , basicBootstrap -- * References -- $references ) where import Data.Vector.Generic ((!)) import qualified Data.Vector.Unboxed as U import qualified Data.Vector.Generic as G import Statistics.Distribution (cumulative, quantile) import Statistics.Distribution.Normal import Statistics.Resampling (Bootstrap(..), jackknife) import Statistics.Sample (mean) import Statistics.Types (Sample, CL, Estimate, ConfInt, estimateFromInterval, estimateFromErr, CL, significanceLevel) import Statistics.Function (gsort) import qualified Statistics.Resampling as R #if !defined(__GHCJS__) import Control.Monad.Par (parMap, runPar) #endif data T = {-# UNPACK #-} !Double :< {-# UNPACK #-} !Double infixl 2 :< -- | Bias-corrected accelerated (BCA) bootstrap. This adjusts for both -- bias and skewness in the resampled distribution. -- -- BCA algorithm is described in ch. 5 of Davison, Hinkley "Confidence -- intervals" in section 5.3 "Percentile method" bootstrapBCA :: CL Double -- ^ Confidence level -> Sample -- ^ Full data sample -> [(R.Estimator, Bootstrap U.Vector Double)] -- ^ Estimates obtained from resampled data and estimator used for -- this. -> [Estimate ConfInt Double] bootstrapBCA confidenceLevel sample resampledData #if defined(__GHCJS__) -- monad-par causes seems to cause "thread blocked indefinitely on MVar" -- on GHCJS still -- -- I (phadej) would change the interface to return IO, and use mapConcurrently from async = map e resampledData #else = runPar $ parMap e resampledData #endif where e (est, Bootstrap pt resample) | U.length sample == 1 || isInfinite bias = estimateFromErr pt (0,0) confidenceLevel | otherwise = estimateFromInterval pt (resample ! lo, resample ! hi) confidenceLevel where -- Quantile estimates for given CL lo = min (max (cumn a1) 0) (ni - 1) where a1 = bias + b1 / (1 - accel * b1) b1 = bias + z1 hi = max (min (cumn a2) (ni - 1)) 0 where a2 = bias + b2 / (1 - accel * b2) b2 = bias - z1 -- Number of resamples ni = U.length resample n = fromIntegral ni -- Corrections z1 = quantile standard (significanceLevel confidenceLevel / 2) cumn = round . (*n) . cumulative standard bias = quantile standard (probN / n) where probN = fromIntegral . U.length . U.filter (<pt) $ resample accel = sumCubes / (6 * (sumSquares ** 1.5)) where (sumSquares :< sumCubes) = U.foldl' f (0 :< 0) jack f (s :< c) j = s + d2 :< c + d2 * d where d = jackMean - j d2 = d * d jackMean = mean jack jack = jackknife est sample -- | Basic bootstrap. This method simply uses empirical quantiles for -- confidence interval. basicBootstrap :: (G.Vector v a, Ord a, Num a) => CL Double -- ^ Confidence vector -> Bootstrap v a -- ^ Estimate from full sample and vector of -- estimates obtained from resamples -> Estimate ConfInt a {-# INLINE basicBootstrap #-} basicBootstrap cl (Bootstrap e ests) = estimateFromInterval e (sorted ! lo, sorted ! hi) cl where sorted = gsort ests n = fromIntegral $ G.length ests c = n * (significanceLevel cl / 2) -- FIXME: can we have better estimates of quantiles in case when p -- is not multiple of 1/N -- -- FIXME: we could have undercoverage here lo = round c hi = truncate (n - c) -- $references -- -- * Davison, A.C; Hinkley, D.V. (1997) Bootstrap methods and their -- application. <http://statwww.epfl.ch/davison/BMA/>
bos/statistics
Statistics/Resampling/Bootstrap.hs
bsd-2-clause
4,131
0
14
1,116
892
507
385
62
1
module Main where import Options.Applicative import qualified Data.Yaml as Y import Data.Yaml.Pretty import qualified Data.ByteString.Char8 as B data Options = Options { --variables :: String dashes :: Bool ,files :: [String]} cfg :: Parser Options cfg = Options <$> -- strOption (short 'V' <> long "variable" <> metavar "VAR-DEF" <> -- help "Set variables of the yaml-file \ switch (short 'd' <> long "dashes" <> help "Whether to print dashes at beginning and end" ) <*> some (argument str (metavar "YAML-FILES")) union :: Options -> IO () union (Options{files = fs, dashes = dsh}) = do s <- mapM Y.decodeFileEither fs let yaml = case s of Left s -> error $ "Yaml-File parsing failed " ++ s Right x -> x let ymlStr = encodePretty defConfig yaml let str = if dsh then B.unlines [ B.pack "---", ymlStr, B.pack "..."] else ymlStr B.putStrLn str main :: IO () main = execParser opts >>= union where opts = info (helper <*> cfg ) ( fullDesc <> header "Program to concatenate yaml-files" <> progDesc "Concatenate and filter yaml-files" )
michelk/yaml-overrides.hs
bin/yaml-concat.hs
bsd-3-clause
1,213
0
14
358
334
175
159
32
3
{-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTSyntax #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UnboxedTuples #-} {-# LANGUAGE UnliftedNewtypes #-} module UnliftedNewtypesUnassociatedFamily where import GHC.Int (Int(I#)) import GHC.Exts (Int#,Word#,RuntimeRep(IntRep)) import GHC.Exts (TYPE) type KindOf (a :: TYPE k) = k data family D (a :: TYPE r) :: TYPE r newtype instance D a = MkWordD Word# newtype instance D a :: TYPE (KindOf a) where MkIntD :: forall (a :: TYPE 'IntRep). Int# -> D a
sdiehl/ghc
testsuite/tests/typecheck/should_compile/UnliftedNewtypesUnifySig.hs
bsd-3-clause
582
4
9
94
154
94
60
-1
-1
{-# LANGUAGE CPP #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE RecordWildCards #-} ----------------------------------------------------------------------------- -- | -- Module : Database.PostgreSQL.Simple.Notification -- Copyright : (c) 2011-2015 Leon P Smith -- (c) 2012 Joey Adams -- License : BSD3 -- -- Maintainer : leon@melding-monads.com -- Stability : experimental -- -- Support for receiving asynchronous notifications via PostgreSQL's -- Listen/Notify mechanism. See -- <https://www.postgresql.org/docs/9.5/static/sql-notify.html> for more -- information. -- -- Note that on Windows, @getNotification@ currently uses a polling loop -- of 1 second to check for more notifications, due to some inadequacies -- in GHC's IO implementation and interface on that platform. See GHC -- issue #7353 for more information. While this workaround is less than -- ideal, notifications are still better than polling the database directly. -- Notifications do not create any extra work for the backend, and are -- likely cheaper on the client side as well. -- -- <https://hackage.haskell.org/trac/ghc/ticket/7353> -- ----------------------------------------------------------------------------- module Database.PostgreSQL.Simple.Notification ( Notification(..) , getNotification , getNotificationNonBlocking , getBackendPID ) where import Control.Monad ( join, void ) import Control.Exception ( throwIO, catch ) import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as B8 import Database.PostgreSQL.Simple.Internal import qualified Database.PostgreSQL.LibPQ as PQ import System.Posix.Types ( CPid ) import GHC.IO.Exception ( ioe_location ) #if defined(mingw32_HOST_OS) import Control.Concurrent ( threadDelay ) #elif !MIN_VERSION_base(4,7,0) import Control.Concurrent ( threadWaitRead ) #else import GHC.Conc ( atomically ) import Control.Concurrent ( threadWaitReadSTM ) #endif data Notification = Notification { notificationPid :: {-# UNPACK #-} !CPid , notificationChannel :: {-# UNPACK #-} !B.ByteString , notificationData :: {-# UNPACK #-} !B.ByteString } deriving (Show, Eq) convertNotice :: PQ.Notify -> Notification convertNotice PQ.Notify{..} = Notification { notificationPid = notifyBePid , notificationChannel = notifyRelname , notificationData = notifyExtra } -- | Returns a single notification. If no notifications are available, -- 'getNotification' blocks until one arrives. -- -- It is safe to call 'getNotification' on a connection that is concurrently -- being used for other purposes, note however that PostgreSQL does not -- deliver notifications while a connection is inside a transaction. getNotification :: Connection -> IO Notification getNotification conn = join $ withConnection conn fetch where funcName = "Database.PostgreSQL.Simple.Notification.getNotification" fetch c = do mmsg <- PQ.notifies c case mmsg of Just msg -> return (return $! convertNotice msg) Nothing -> do mfd <- PQ.socket c case mfd of Nothing -> return (throwIO $! fdError funcName) #if defined(mingw32_HOST_OS) -- threadWaitRead doesn't work for sockets on Windows, so just -- poll for input every second (PQconsumeInput is non-blocking). -- -- We could call select(), but FFI calls can't be interrupted -- with async exceptions, whereas threadDelay can. Just _fd -> do return (threadDelay 1000000 >> loop) #elif !MIN_VERSION_base(4,7,0) -- Technically there's a race condition that is usually benign. -- If the connection is closed or reset after we drop the -- lock, and then the fd index is reallocated to a new -- descriptor before we call threadWaitRead, then -- we could end up waiting on the wrong descriptor. -- -- Now, if the descriptor becomes readable promptly, then -- it's no big deal as we'll wake up and notice the change -- on the next iteration of the loop. But if are very -- unlucky, then we could end up waiting a long time. Just fd -> do return $ do threadWaitRead fd `catch` (throwIO . setIOErrorLocation) loop #else -- This case fixes the race condition above. By registering -- our interest in the descriptor before we drop the lock, -- there is no opportunity for the descriptor index to be -- reallocated on us. -- -- (That is, assuming there isn't concurrently executing -- code that manipulates the descriptor without holding -- the lock... but such a major bug is likely to exhibit -- itself in an at least somewhat more dramatic fashion.) Just fd -> do (waitRead, _) <- threadWaitReadSTM fd return $ do atomically waitRead `catch` (throwIO . setIOErrorLocation) loop #endif loop = join $ withConnection conn $ \c -> do void $ PQ.consumeInput c fetch c setIOErrorLocation :: IOError -> IOError setIOErrorLocation err = err { ioe_location = B8.unpack funcName } -- | Non-blocking variant of 'getNotification'. Returns a single notification, -- if available. If no notifications are available, returns 'Nothing'. getNotificationNonBlocking :: Connection -> IO (Maybe Notification) getNotificationNonBlocking conn = withConnection conn $ \c -> do mmsg <- PQ.notifies c case mmsg of Just msg -> return $! Just $! convertNotice msg Nothing -> do _ <- PQ.consumeInput c mmsg' <- PQ.notifies c case mmsg' of Just msg -> return $! Just $! convertNotice msg Nothing -> return Nothing -- | Returns the process 'CPid' of the backend server process -- handling this connection. -- -- The backend PID is useful for debugging purposes and for comparison -- to NOTIFY messages (which include the PID of the notifying backend -- process). Note that the PID belongs to a process executing on the -- database server host, not the local host! getBackendPID :: Connection -> IO CPid getBackendPID conn = withConnection conn PQ.backendPID
tomjaguarpaw/postgresql-simple
src/Database/PostgreSQL/Simple/Notification.hs
bsd-3-clause
6,773
0
22
1,935
660
372
288
61
3
----------------------------------------------------------------------------- -- | -- Module : Data.Either.Combinators -- Copyright : (c) 2010-2014 Gregory Crosswhite, Chris Done, Edward Kmett -- License : BSD-style -- -- Maintainer : ekmett@gmail.com -- Stability : provisional -- Portability : portable -- -- Functions for probing and unwrapping values inside of 'Either'. -- -- Most of these combinators are provided for pedagogical purposes and exist -- in more general forms in other libraries. To that end alternative definitions -- are supplied below. -- ----------------------------------------------------------------------------- module Data.Either.Combinators ( isLeft , isRight , fromLeft , fromRight , fromLeft' , fromRight' , mapBoth , mapLeft , mapRight , whenLeft , whenRight , unlessLeft , unlessRight , leftToMaybe , rightToMaybe , eitherToError , swapEither ) where import Control.Applicative import Control.Monad.Error.Class ( MonadError(throwError) ) -- --------------------------------------------------------------------------- -- Functions over Either -- |The 'isLeft' function returns 'True' iff its argument is of the form @'Left' _@. -- -- Using @Control.Lens@: -- -- @ -- 'isLeft' ≡ has _Left -- @ -- -- >>> isLeft (Left 12) -- True -- -- >>> isLeft (Right 12) -- False isLeft :: Either a b -> Bool isLeft (Left _) = True isLeft _ = False -- |The 'isRight' function returns 'True' iff its argument is of the form @'Right' _@. -- -- Using @Control.Lens@: -- -- @ -- 'isRight' ≡ has _Right -- @ -- -- >>> isRight (Left 12) -- False -- -- >>> isRight (Right 12) -- True isRight :: Either a b -> Bool isRight (Right _) = True isRight _ = False -- | Extracts the element out of a 'Left' and -- throws an error if its argument take the form @'Right' _@. -- -- Using @Control.Lens@: -- -- @ -- 'fromLeft'' x ≡ x^?!_Left -- @ -- -- >>> fromLeft' (Left 12) -- 12 fromLeft' :: Either a b -> a fromLeft' (Right _) = error "Data.Either.Combinators.fromLeft: Argument takes form 'Right _'" -- yuck fromLeft' (Left x) = x -- | Extracts the element out of a 'Right' and -- throws an error if its argument take the form @'Left' _@. -- -- Using @Control.Lens@: -- -- @ -- 'fromRight'' x ≡ x^?!_Right -- @ -- -- >>> fromRight' (Right 12) -- 12 fromRight' :: Either a b -> b fromRight' (Left _) = error "Data.Either.Combinators.fromRight: Argument takes form 'Left _'" -- yuck fromRight' (Right x) = x -- | The 'mapBoth' function takes two functions and applies the first if iff the value -- takes the form @'Left' _@ and the second if the value takes the form @'Right' _@. -- -- Using @Data.Bifunctor@: -- -- @ -- 'mapBoth' = bimap -- @ -- -- Using @Control.Arrow@: -- -- @ -- 'mapBoth' = ('Control.Arrow.+++') -- @ -- -- >>> mapBoth (*2) (*3) (Left 4) -- Left 8 -- -- >>> mapBoth (*2) (*3) (Right 4) -- Right 12 mapBoth :: (a -> c) -> (b -> d) -> Either a b -> Either c d mapBoth f _ (Left x) = Left (f x) mapBoth _ f (Right x) = Right (f x) -- | The 'mapLeft' function takes a function and applies it to an Either value -- iff the value takes the form @'Left' _@. -- -- Using @Data.Bifunctor@: -- -- @ -- 'mapLeft' = first -- @ -- -- Using @Control.Arrow@: -- -- @ -- 'mapLeft' = ('Control.Arrow.left') -- @ -- -- Using @Control.Lens@: -- -- @ -- 'mapLeft' = over _Left -- @ -- -- >>> mapLeft (*2) (Left 4) -- Left 8 -- -- >>> mapLeft (*2) (Right "hello") -- Right "hello" mapLeft :: (a -> c) -> Either a b -> Either c b mapLeft f = mapBoth f id -- | The 'mapRight' function takes a function and applies it to an Either value -- iff the value takes the form @'Right' _@. -- -- Using @Data.Bifunctor@: -- -- @ -- 'mapRight' = second -- @ -- -- Using @Control.Arrow@: -- -- @ -- 'mapRight' = ('Control.Arrow.right') -- @ -- -- Using @Control.Lens@: -- -- @ -- 'mapRight' = over _Right -- @ -- -- >>> mapRight (*2) (Left "hello") -- Left "hello" -- -- >>> mapRight (*2) (Right 4) -- Right 8 mapRight :: (b -> c) -> Either a b -> Either a c mapRight = mapBoth id -- | The 'whenLeft' function takes an 'Either' value and a function which returns a monad. -- The monad is only executed when the given argument takes the form @'Left' _@, otherwise -- it does nothing. -- -- Using @Control.Lens@: -- -- @ -- 'whenLeft' ≡ forOf_ _Left -- @ -- -- >>> whenLeft (Left 12) print -- 12 whenLeft :: Applicative m => Either a b -> (a -> m ()) -> m () whenLeft (Left x) f = f x whenLeft _ _ = pure () -- | The 'whenRight' function takes an 'Either' value and a function which returns a monad. -- The monad is only executed when the given argument takes the form @'Right' _@, otherwise -- it does nothing. -- -- Using @Data.Foldable@: -- -- @ -- 'whenRight' ≡ 'forM_' -- @ -- -- Using @Control.Lens@: -- -- @ -- 'whenRight' ≡ forOf_ _Right -- @ -- -- >>> whenRight (Right 12) print -- 12 whenRight :: Applicative m => Either a b -> (b -> m ()) -> m () whenRight (Right x) f = f x whenRight _ _ = pure () -- | A synonym of 'whenRight'. unlessLeft :: Applicative m => Either a b -> (b -> m ()) -> m () unlessLeft = whenRight -- | A synonym of 'whenLeft'. unlessRight :: Applicative m => Either a b -> (a -> m ()) -> m () unlessRight = whenLeft -- | Extract the left value or a default. -- -- @ -- 'fromLeft' ≡ 'either' 'id' -- @ -- -- >>> fromLeft "hello" (Right 42) -- "hello" -- -- >>> fromLeft "hello" (Left "world") -- "world" fromLeft :: a -> Either a b -> a fromLeft _ (Left x) = x fromLeft x _ = x -- | Extract the right value or a default. -- -- @ -- 'fromRight' b ≡ 'either' b 'id' -- @ -- -- >>> fromRight "hello" (Right "world") -- "world" -- -- >>> fromRight "hello" (Left 42) -- "hello" fromRight :: b -> Either a b -> b fromRight _ (Right x) = x fromRight x _ = x -- | Maybe get the 'Left' side of an 'Either'. -- -- @ -- 'leftToMaybe' ≡ 'either' 'Just' ('const' 'Nothing') -- @ -- -- Using @Control.Lens@: -- -- @ -- 'leftToMaybe' ≡ preview _Left -- 'leftToMaybe' x ≡ x^?_Left -- @ -- -- >>> leftToMaybe (Left 12) -- Just 12 -- -- >>> leftToMaybe (Right 12) -- Nothing leftToMaybe :: Either a b -> Maybe a leftToMaybe = either Just (const Nothing) -- | Maybe get the 'Right' side of an 'Either'. -- -- @ -- 'rightToMaybe' ≡ 'either' ('const' 'Nothing') 'Just' -- @ -- -- Using @Control.Lens@: -- -- @ -- 'rightToMaybe' ≡ preview _Right -- 'rightToMaybe' x ≡ x^?_Right -- @ -- -- >>> rightToMaybe (Left 12) -- Nothing -- -- >>> rightToMaybe (Right 12) -- Just 12 rightToMaybe :: Either a b -> Maybe b rightToMaybe = either (const Nothing) Just -- | Generalize @Either e@ as @MonadError e m@. -- -- If the argument has form @Left e@, an error is produced in the monad via -- 'throwError'. Otherwise, the @Right a@ part is forwarded. eitherToError :: (MonadError e m) => Either e a -> m a eitherToError = either throwError return -- | Swap the 'Left' and 'Right' sides of an 'Either'. -- -- @ -- >>> swapEither (Right 3) -- Left 3 -- -- >>> swapEither (Left "error") -- Right "error" -- @ swapEither :: Either e a -> Either a e swapEither = either Right Left {-# INLINE swapEither #-}
anand-singh/either
src/Data/Either/Combinators.hs
bsd-3-clause
7,130
0
11
1,422
1,131
693
438
64
1
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE TemplateHaskell #-} module Network.Wai.Ghcjs ( mkDevelopmentApp, BuildConfig(..), Exec(..), mkProductionApp, serveGhcjs, ) where import Control.Monad import Language.Haskell.TH import Network.Wai.Ghcjs.Development import Network.Wai.Ghcjs.Internal import Network.Wai.Ghcjs.Production -- * serveGhcjs -- | -- 'serveGhcjs' combines 'mkDevelopmentApp' and 'mkProductionApp'. It will -- read the file @ghcjs-compilation-mode@ with @TemplateHaskell@. If that file -- contains the word @"development"@ 'mkDevelopmentApp' is used. If it contains -- @"production"@ 'mkProductionApp' is used. -- -- The produced splice has the type: -- -- @'IO' 'Network.Wai.Application'@ -- -- >>> :set -XTemplateHaskell -- >>> :type $(serveGhcjs (BuildConfig "Main.hs" Nothing [] "test/test-project/client" Vanilla "test-builds")) -- ... -- =====> building client code with ghcjs -- ... -- =====> done -- $(serveGhcjs (BuildConfig "Main.hs" Nothing [] "test/test-project/client" Vanilla "test-builds")) -- :: IO Network.Wai.Application serveGhcjs :: BuildConfig -> Q Exp serveGhcjs config = do join $ runCM $ ifDevel [|mkDevelopmentApp config|] (mkProductionApp config)
soenkehahn/wai-shake
src/Network/Wai/Ghcjs.hs
bsd-3-clause
1,299
0
10
225
132
90
42
19
1
module Utils ( parseFromFile , parseString , shouldAccept , shouldReject ) where import Control.Applicative ((<*)) import Test.Hspec import Text.Parsec (eof) import Uroboro.Parser (parse, Parser) -- |Exceptions instead of Either. parseIO :: Parser a -> String -> String -> IO a parseIO parser fname input = case parse parser fname input of Left _ -> ioError $ userError "" Right v -> return v parseFromFile :: Parser a -> FilePath -> IO a parseFromFile parser fname = do input <- readFile fname parseIO parser fname input parseString :: Parser a -> String -> IO a parseString parser input = parseIO parser "" input shouldAccept :: Parser a -> String -> Expectation shouldAccept p s = case parse (p <* eof) "<testcase>" s of Left e -> expectationFailure (show e) Right _ -> return () shouldReject :: Show a => Parser a -> String -> Expectation shouldReject p s = case parse (p <* eof) "<testcase>" s of Left _ -> return () Right x -> expectationFailure $ "Parsing \"" ++ s ++ "\" succeded with result " ++ show x ++ "."
tewe/uroboro
test/Utils.hs
mit
1,093
0
12
255
391
193
198
29
2
module Compiler.OptimiseLp(optimiseLp) where import Compiler.Lp import Compiler.Util optimiseLp :: Program -> Program optimiseLp = collapsePrimArgs . deadCode . specialise --------------------------------------------------------------------- -- Remove adjacent strings for primitive calls collapsePrimArgs :: Program -> Program collapsePrimArgs = transformBi f where f (Prim name args) = Prim name (g args) f x = x g (Lit x:Lit y:xs) = g $ Lit (x++y) : xs g (x:xs) = x : g xs g [] = [] --------------------------------------------------------------------- -- Remove rules that are unreachable from root deadCode :: Program -> Program deadCode xs = filter (flip elem needed . ruleName) xs where needed = follow [] ["root"] follow done (t:odo) | t `elem` done = follow done odo follow done (t:odo) = follow (t:done) (odo++new) where new = [x | Call x _ <- universeBi $ getRule xs t] follow done [] = done --------------------------------------------------------------------- -- Given parameter invokations of local rules, specialise them type Template = (String, [Maybe String]) specialise :: Program -> Program specialise x = useTemplate ts $ x ++ map (genTemplate x) ts where ts = zipWith (\i x -> (x, fst x ++ show i)) [1..] $ nub $ mapMaybe getTemplate $ childrenBi x getTemplate :: Exp -> Maybe Template getTemplate (Call name xs) | any isJust ys = Just (name,ys) where ys = map asLit xs getTemplate _ = Nothing useTemplate :: [(Template, String)] -> Program -> Program useTemplate ts = transformBi f where f x@(Call _ args) = case getTemplate x of Just y -> Call (fromJust $ lookup y ts) (filter (isNothing . asLit) args) _ -> x f x = x genTemplate :: [Rule] -> (Template,String) -> Rule genTemplate xs ((name,args),name2) = Rule name2 args2 bod2 where Rule _ as bod = getRule xs name args2 = concat $ zipWith (\i s -> [s | isNothing i]) args as rep = concat $ zipWith (\i s -> [(s,Lit $ fromJust i) | isJust i]) args as bod2 = transformBi f bod f (Var x) = fromMaybe (Var x) $ lookup x rep f x = x
silkapp/tagsoup
dead/parser/Compiler/OptimiseLp.hs
bsd-3-clause
2,257
0
15
594
851
439
412
42
4
module Dotnet.System.UriPartial where import Dotnet import qualified Dotnet.System.Enum data UriPartial_ a type UriPartial a = Dotnet.System.Enum.Enum (UriPartial_ a)
alekar/hugs
dotnet/lib/Dotnet/System/UriPartial.hs
bsd-3-clause
171
0
7
22
41
27
14
-1
-1
module Data.RDF.PatriciaTreeGraph_Test (triplesOf',uniqTriplesOf',empty',mkRdf') where import Data.RDF.Types import Data.RDF.PatriciaTreeGraph (PatriciaTreeGraph) import Data.RDF.GraphTestUtils import qualified Data.Map as Map import Control.Monad import Test.QuickCheck instance Arbitrary PatriciaTreeGraph where arbitrary = liftM3 mkRdf arbitraryTs (return Nothing) (return $ PrefixMappings Map.empty) --coarbitrary = undefined empty' :: PatriciaTreeGraph empty' = empty mkRdf' :: Triples -> Maybe BaseUrl -> PrefixMappings -> PatriciaTreeGraph mkRdf' = mkRdf triplesOf' :: PatriciaTreeGraph -> Triples triplesOf' = triplesOf uniqTriplesOf' :: PatriciaTreeGraph -> Triples uniqTriplesOf' = uniqTriplesOf
LeifW/rdf4h
testsuite/tests/Data/RDF/PatriciaTreeGraph_Test.hs
bsd-3-clause
717
0
10
84
166
97
69
17
1
{-# LANGUAGE RecordWildCards #-} -- | DSL for testing the modular solver module UnitTests.Distribution.Solver.Modular.DSL ( ExampleDependency(..) , Dependencies(..) , ExTest(..) , ExPreference(..) , ExampleDb , ExampleVersionRange , ExamplePkgVersion , ExamplePkgName , ExampleAvailable(..) , ExampleInstalled(..) , exAv , exInst , exFlag , exResolve , extractInstallPlan , withSetupDeps , withTest , withTests ) where -- base import Data.Either (partitionEithers) import Data.Maybe (catMaybes) import Data.List (nub) import Data.Monoid import Data.Version import qualified Data.Map as Map -- Cabal import qualified Distribution.Compiler as C import qualified Distribution.InstalledPackageInfo as C import qualified Distribution.Package as C hiding (HasUnitId(..)) import qualified Distribution.PackageDescription as C import qualified Distribution.Simple.PackageIndex as C.PackageIndex import qualified Distribution.System as C import qualified Distribution.Version as C import Language.Haskell.Extension (Extension(..), Language) -- cabal-install import Distribution.Client.Dependency import Distribution.Client.Dependency.Types import Distribution.Client.Types import qualified Distribution.Client.InstallPlan as CI.InstallPlan import Distribution.Solver.Types.ComponentDeps (ComponentDeps) import qualified Distribution.Solver.Types.ComponentDeps as CD import Distribution.Solver.Types.ConstraintSource import Distribution.Solver.Types.LabeledPackageConstraint import Distribution.Solver.Types.OptionalStanza import qualified Distribution.Solver.Types.PackageIndex as CI.PackageIndex import qualified Distribution.Solver.Types.PkgConfigDb as PC import Distribution.Solver.Types.Settings import Distribution.Solver.Types.SolverPackage import Distribution.Solver.Types.SourcePackage {------------------------------------------------------------------------------- Example package database DSL In order to be able to set simple examples up quickly, we define a very simple version of the package database here explicitly designed for use in tests. The design of `ExampleDb` takes the perspective of the solver, not the perspective of the package DB. This makes it easier to set up tests for various parts of the solver, but makes the mapping somewhat awkward, because it means we first map from "solver perspective" `ExampleDb` to the package database format, and then the modular solver internally in `IndexConversion` maps this back to the solver specific data structures. IMPLEMENTATION NOTES -------------------- TODO: Perhaps these should be made comments of the corresponding data type definitions. For now these are just my own conclusions and may be wrong. * The difference between `GenericPackageDescription` and `PackageDescription` is that `PackageDescription` describes a particular _configuration_ of a package (for instance, see documentation for `checkPackage`). A `GenericPackageDescription` can be turned into a `PackageDescription` in two ways: a. `finalizePackageDescription` does the proper translation, by taking into account the platform, available dependencies, etc. and picks a flag assignment (or gives an error if no flag assignment can be found) b. `flattenPackageDescription` ignores flag assignment and just joins all components together. The slightly odd thing is that a `GenericPackageDescription` contains a `PackageDescription` as a field; both of the above functions do the same thing: they take the embedded `PackageDescription` as a basis for the result value, but override `library`, `executables`, `testSuites`, `benchmarks` and `buildDepends`. * The `condTreeComponents` fields of a `CondTree` is a list of triples `(condition, then-branch, else-branch)`, where the `else-branch` is optional. -------------------------------------------------------------------------------} type ExamplePkgName = String type ExamplePkgVersion = Int type ExamplePkgHash = String -- for example "installed" packages type ExampleFlagName = String type ExampleTestName = String type ExampleVersionRange = C.VersionRange data Dependencies = NotBuildable | Buildable [ExampleDependency] deriving Show data ExampleDependency = -- | Simple dependency on any version ExAny ExamplePkgName -- | Simple dependency on a fixed version | ExFix ExamplePkgName ExamplePkgVersion -- | Dependencies indexed by a flag | ExFlag ExampleFlagName Dependencies Dependencies -- | Dependency on a language extension | ExExt Extension -- | Dependency on a language version | ExLang Language -- | Dependency on a pkg-config package | ExPkg (ExamplePkgName, ExamplePkgVersion) deriving Show data ExTest = ExTest ExampleTestName [ExampleDependency] exFlag :: ExampleFlagName -> [ExampleDependency] -> [ExampleDependency] -> ExampleDependency exFlag n t e = ExFlag n (Buildable t) (Buildable e) data ExPreference = ExPref String ExampleVersionRange data ExampleAvailable = ExAv { exAvName :: ExamplePkgName , exAvVersion :: ExamplePkgVersion , exAvDeps :: ComponentDeps [ExampleDependency] } deriving Show -- | Constructs an 'ExampleAvailable' package for the 'ExampleDb', -- given: -- -- 1. The name 'ExamplePkgName' of the available package, -- 2. The version 'ExamplePkgVersion' available -- 3. The list of dependency constraints 'ExampleDependency' -- that this package has. 'ExampleDependency' provides -- a number of pre-canned dependency types to look at. -- exAv :: ExamplePkgName -> ExamplePkgVersion -> [ExampleDependency] -> ExampleAvailable exAv n v ds = ExAv { exAvName = n, exAvVersion = v , exAvDeps = CD.fromLibraryDeps n ds } withSetupDeps :: ExampleAvailable -> [ExampleDependency] -> ExampleAvailable withSetupDeps ex setupDeps = ex { exAvDeps = exAvDeps ex <> CD.fromSetupDeps setupDeps } withTest :: ExampleAvailable -> ExTest -> ExampleAvailable withTest ex test = withTests ex [test] withTests :: ExampleAvailable -> [ExTest] -> ExampleAvailable withTests ex tests = let testCDs = CD.fromList [(CD.ComponentTest name, deps) | ExTest name deps <- tests] in ex { exAvDeps = exAvDeps ex <> testCDs } -- | An installed package in 'ExampleDb'; construct me with 'exInst'. data ExampleInstalled = ExInst { exInstName :: ExamplePkgName , exInstVersion :: ExamplePkgVersion , exInstHash :: ExamplePkgHash , exInstBuildAgainst :: [ExamplePkgHash] } deriving Show -- | Constructs an example installed package given: -- -- 1. The name of the package 'ExamplePkgName', i.e., 'String' -- 2. The version of the package 'ExamplePkgVersion', i.e., 'Int' -- 3. The IPID for the package 'ExamplePkgHash', i.e., 'String' -- (just some unique identifier for the package.) -- 4. The 'ExampleInstalled' packages which this package was -- compiled against.) -- exInst :: ExamplePkgName -> ExamplePkgVersion -> ExamplePkgHash -> [ExampleInstalled] -> ExampleInstalled exInst pn v hash deps = ExInst pn v hash (map exInstHash deps) -- | An example package database is a list of installed packages -- 'ExampleInstalled' and available packages 'ExampleAvailable'. -- Generally, you want to use 'exInst' and 'exAv' to construct -- these packages. type ExampleDb = [Either ExampleInstalled ExampleAvailable] type DependencyTree a = C.CondTree C.ConfVar [C.Dependency] a exDbPkgs :: ExampleDb -> [ExamplePkgName] exDbPkgs = map (either exInstName exAvName) exAvSrcPkg :: ExampleAvailable -> UnresolvedSourcePackage exAvSrcPkg ex = let (libraryDeps, exts, mlang, pcpkgs) = splitTopLevel (CD.libraryDeps (exAvDeps ex)) testSuites = [(name, deps) | (CD.ComponentTest name, deps) <- CD.toList (exAvDeps ex)] in SourcePackage { packageInfoId = exAvPkgId ex , packageSource = LocalTarballPackage "<<path>>" , packageDescrOverride = Nothing , packageDescription = C.GenericPackageDescription { C.packageDescription = C.emptyPackageDescription { C.package = exAvPkgId ex , C.libraries = error "not yet configured: library" , C.executables = error "not yet configured: executables" , C.testSuites = error "not yet configured: testSuites" , C.benchmarks = error "not yet configured: benchmarks" , C.buildDepends = error "not yet configured: buildDepends" , C.setupBuildInfo = Just C.SetupBuildInfo { C.setupDepends = mkSetupDeps (CD.setupDeps (exAvDeps ex)), C.defaultSetupDepends = False } } , C.genPackageFlags = nub $ concatMap extractFlags $ CD.libraryDeps (exAvDeps ex) ++ concatMap snd testSuites , C.condLibraries = [(exAvName ex, mkCondTree (extsLib exts <> langLib mlang <> pcpkgLib pcpkgs) disableLib (Buildable libraryDeps))] , C.condExecutables = [] , C.condTestSuites = let mkTree = mkCondTree mempty disableTest . Buildable in map (\(t, deps) -> (t, mkTree deps)) testSuites , C.condBenchmarks = [] } } where -- Split the set of dependencies into the set of dependencies of the library, -- the dependencies of the test suites and extensions. splitTopLevel :: [ExampleDependency] -> ( [ExampleDependency] , [Extension] , Maybe Language , [(ExamplePkgName, ExamplePkgVersion)] -- pkg-config ) splitTopLevel [] = ([], [], Nothing, []) splitTopLevel (ExExt ext:deps) = let (other, exts, lang, pcpkgs) = splitTopLevel deps in (other, ext:exts, lang, pcpkgs) splitTopLevel (ExLang lang:deps) = case splitTopLevel deps of (other, exts, Nothing, pcpkgs) -> (other, exts, Just lang, pcpkgs) _ -> error "Only 1 Language dependency is supported" splitTopLevel (ExPkg pkg:deps) = let (other, exts, lang, pcpkgs) = splitTopLevel deps in (other, exts, lang, pkg:pcpkgs) splitTopLevel (dep:deps) = let (other, exts, lang, pcpkgs) = splitTopLevel deps in (dep:other, exts, lang, pcpkgs) -- Extract the total set of flags used extractFlags :: ExampleDependency -> [C.Flag] extractFlags (ExAny _) = [] extractFlags (ExFix _ _) = [] extractFlags (ExFlag f a b) = C.MkFlag { C.flagName = C.FlagName f , C.flagDescription = "" , C.flagDefault = True , C.flagManual = False } : concatMap extractFlags (deps a ++ deps b) where deps :: Dependencies -> [ExampleDependency] deps NotBuildable = [] deps (Buildable ds) = ds extractFlags (ExExt _) = [] extractFlags (ExLang _) = [] extractFlags (ExPkg _) = [] mkCondTree :: Monoid a => a -> (a -> a) -> Dependencies -> DependencyTree a mkCondTree x dontBuild NotBuildable = C.CondNode { C.condTreeData = dontBuild x , C.condTreeConstraints = [] , C.condTreeComponents = [] } mkCondTree x dontBuild (Buildable deps) = let (directDeps, flaggedDeps) = splitDeps deps in C.CondNode { C.condTreeData = x -- Necessary for language extensions , C.condTreeConstraints = map mkDirect directDeps , C.condTreeComponents = map (mkFlagged dontBuild) flaggedDeps } mkDirect :: (ExamplePkgName, Maybe ExamplePkgVersion) -> C.Dependency mkDirect (dep, Nothing) = C.Dependency (C.PackageName dep) C.anyVersion mkDirect (dep, Just n) = C.Dependency (C.PackageName dep) (C.thisVersion v) where v = Version [n, 0, 0] [] mkFlagged :: Monoid a => (a -> a) -> (ExampleFlagName, Dependencies, Dependencies) -> (C.Condition C.ConfVar , DependencyTree a, Maybe (DependencyTree a)) mkFlagged dontBuild (f, a, b) = ( C.Var (C.Flag (C.FlagName f)) , mkCondTree mempty dontBuild a , Just (mkCondTree mempty dontBuild b) ) -- Split a set of dependencies into direct dependencies and flagged -- dependencies. A direct dependency is a tuple of the name of package and -- maybe its version (no version means any version) meant to be converted -- to a 'C.Dependency' with 'mkDirect' for example. A flagged dependency is -- the set of dependencies guarded by a flag. -- -- TODO: Take care of flagged language extensions and language flavours. splitDeps :: [ExampleDependency] -> ( [(ExamplePkgName, Maybe Int)] , [(ExampleFlagName, Dependencies, Dependencies)] ) splitDeps [] = ([], []) splitDeps (ExAny p:deps) = let (directDeps, flaggedDeps) = splitDeps deps in ((p, Nothing):directDeps, flaggedDeps) splitDeps (ExFix p v:deps) = let (directDeps, flaggedDeps) = splitDeps deps in ((p, Just v):directDeps, flaggedDeps) splitDeps (ExFlag f a b:deps) = let (directDeps, flaggedDeps) = splitDeps deps in (directDeps, (f, a, b):flaggedDeps) splitDeps (_:deps) = splitDeps deps -- Currently we only support simple setup dependencies mkSetupDeps :: [ExampleDependency] -> [C.Dependency] mkSetupDeps deps = let (directDeps, []) = splitDeps deps in map mkDirect directDeps -- A 'C.Library' with just the given extensions in its 'BuildInfo' extsLib :: [Extension] -> C.Library extsLib es = mempty { C.libBuildInfo = mempty { C.otherExtensions = es } } -- A 'C.Library' with just the given extensions in its 'BuildInfo' langLib :: Maybe Language -> C.Library langLib (Just lang) = mempty { C.libBuildInfo = mempty { C.defaultLanguage = Just lang } } langLib _ = mempty disableLib :: C.Library -> C.Library disableLib lib = lib { C.libBuildInfo = (C.libBuildInfo lib) { C.buildable = False }} disableTest :: C.TestSuite -> C.TestSuite disableTest test = test { C.testBuildInfo = (C.testBuildInfo test) { C.buildable = False }} -- A 'C.Library' with just the given pkgconfig-depends in its 'BuildInfo' pcpkgLib :: [(ExamplePkgName, ExamplePkgVersion)] -> C.Library pcpkgLib ds = mempty { C.libBuildInfo = mempty { C.pkgconfigDepends = [mkDirect (n, (Just v)) | (n,v) <- ds] } } exAvPkgId :: ExampleAvailable -> C.PackageIdentifier exAvPkgId ex = C.PackageIdentifier { pkgName = C.PackageName (exAvName ex) , pkgVersion = Version [exAvVersion ex, 0, 0] [] } exInstInfo :: ExampleInstalled -> C.InstalledPackageInfo exInstInfo ex = C.emptyInstalledPackageInfo { C.installedUnitId = C.mkUnitId (exInstHash ex) , C.sourcePackageId = exInstPkgId ex , C.depends = map C.mkUnitId (exInstBuildAgainst ex) } exInstPkgId :: ExampleInstalled -> C.PackageIdentifier exInstPkgId ex = C.PackageIdentifier { pkgName = C.PackageName (exInstName ex) , pkgVersion = Version [exInstVersion ex, 0, 0] [] } exAvIdx :: [ExampleAvailable] -> CI.PackageIndex.PackageIndex UnresolvedSourcePackage exAvIdx = CI.PackageIndex.fromList . map exAvSrcPkg exInstIdx :: [ExampleInstalled] -> C.PackageIndex.InstalledPackageIndex exInstIdx = C.PackageIndex.fromList . map exInstInfo exResolve :: ExampleDb -- List of extensions supported by the compiler, or Nothing if unknown. -> Maybe [Extension] -- List of languages supported by the compiler, or Nothing if unknown. -> Maybe [Language] -> PC.PkgConfigDb -> [ExamplePkgName] -> Solver -> Maybe Int -> IndependentGoals -> ReorderGoals -> EnableBackjumping -> [ExPreference] -> ([String], Either String CI.InstallPlan.SolverInstallPlan) exResolve db exts langs pkgConfigDb targets solver mbj indepGoals reorder enableBj prefs = runProgress $ resolveDependencies C.buildPlatform compiler pkgConfigDb solver params where defaultCompiler = C.unknownCompilerInfo C.buildCompilerId C.NoAbiTag compiler = defaultCompiler { C.compilerInfoExtensions = exts , C.compilerInfoLanguages = langs } (inst, avai) = partitionEithers db instIdx = exInstIdx inst avaiIdx = SourcePackageDb { packageIndex = exAvIdx avai , packagePreferences = Map.empty } enableTests = fmap (\p -> PackageConstraintStanzas (C.PackageName p) [TestStanzas]) (exDbPkgs db) targets' = fmap (\p -> NamedPackage (C.PackageName p) []) targets params = addPreferences (fmap toPref prefs) $ addConstraints (fmap toLpc enableTests) $ setIndependentGoals indepGoals $ setReorderGoals reorder $ setMaxBackjumps mbj $ setEnableBackjumping enableBj $ standardInstallPolicy instIdx avaiIdx targets' toLpc pc = LabeledPackageConstraint pc ConstraintSourceUnknown toPref (ExPref n v) = PackageVersionPreference (C.PackageName n) v extractInstallPlan :: CI.InstallPlan.SolverInstallPlan -> [(ExamplePkgName, ExamplePkgVersion)] extractInstallPlan = catMaybes . map confPkg . CI.InstallPlan.toList where confPkg :: CI.InstallPlan.SolverPlanPackage -> Maybe (String, Int) confPkg (CI.InstallPlan.Configured pkg) = Just $ srcPkg pkg confPkg _ = Nothing srcPkg :: SolverPackage UnresolvedPkgLoc -> (String, Int) srcPkg cpkg = let C.PackageIdentifier (C.PackageName p) (Version (n:_) _) = packageInfoId (solverPkgSource cpkg) in (p, n) {------------------------------------------------------------------------------- Auxiliary -------------------------------------------------------------------------------} -- | Run Progress computation -- -- Like `runLog`, but for the more general `Progress` type. runProgress :: Progress step e a -> ([step], Either e a) runProgress = go where go (Step s p) = let (ss, result) = go p in (s:ss, result) go (Fail e) = ([], Left e) go (Done a) = ([], Right a)
headprogrammingczar/cabal
cabal-install/tests/UnitTests/Distribution/Solver/Modular/DSL.hs
bsd-3-clause
19,362
0
20
5,211
3,949
2,205
1,744
293
19
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} module WWRec where class Rule f a where get :: Decorator f => f a class Monad f => Decorator f where foo :: Rule f a => f a data A1 = MkA1 A2 data A2 = MkA2 A3 data A3 = MkA3 A4 data A4 = MkA4 A5 data A5 = MkA5 A6 data A6 = MkA6 A7 data A7 = MkA7 A8 data A8 = MkA8 A9 data A9 = MkA9 A10 data A10 = MkA10 A11 data A11 = MkA11 A12 data A12 = MkA12 A13 data A13 = MkA13 A14 data A14 = MkA14 A15 data A15 = MkA15 A16 data A16 = MkA16 A17 data A17 = MkA17 A18 data A18 = MkA18 A19 data A19 = MkA19 A20 data A20 = MkA20 A21 data A21 = MkA21 A22 data A22 = MkA22 A23 data A23 = MkA23 A24 data A24 = MkA24 A25 data A25 = MkA25 A26 data A26 = MkA26 A27 data A27 = MkA27 A28 data A28 = MkA28 A29 data A29 = MkA29 A30 data A30 = MkA30 A1 instance Rule f A2 => Rule f A1 where get = MkA1 <$> foo instance Rule f A3 => Rule f A2 where get = MkA2 <$> foo instance Rule f A4 => Rule f A3 where get = MkA3 <$> foo instance Rule f A5 => Rule f A4 where get = MkA4 <$> foo instance Rule f A6 => Rule f A5 where get = MkA5 <$> foo instance Rule f A7 => Rule f A6 where get = MkA6 <$> foo instance Rule f A8 => Rule f A7 where get = MkA7 <$> foo instance Rule f A9 => Rule f A8 where get = MkA8 <$> foo instance Rule f A10 => Rule f A9 where get = MkA9 <$> foo instance Rule f A11 => Rule f A10 where get = MkA10 <$> foo instance Rule f A12 => Rule f A11 where get = MkA11 <$> foo instance Rule f A13 => Rule f A12 where get = MkA12 <$> foo instance Rule f A14 => Rule f A13 where get = MkA13 <$> foo instance Rule f A15 => Rule f A14 where get = MkA14 <$> foo instance Rule f A16 => Rule f A15 where get = MkA15 <$> foo instance Rule f A17 => Rule f A16 where get = MkA16 <$> foo instance Rule f A18 => Rule f A17 where get = MkA17 <$> foo instance Rule f A19 => Rule f A18 where get = MkA18 <$> foo instance Rule f A20 => Rule f A19 where get = MkA19 <$> foo instance Rule f A21 => Rule f A20 where get = MkA20 <$> foo instance Rule f A22 => Rule f A21 where get = MkA21 <$> foo instance Rule f A23 => Rule f A22 where get = MkA22 <$> foo instance Rule f A24 => Rule f A23 where get = MkA23 <$> foo instance Rule f A25 => Rule f A24 where get = MkA24 <$> foo instance Rule f A26 => Rule f A25 where get = MkA25 <$> foo instance Rule f A27 => Rule f A26 where get = MkA26 <$> foo instance Rule f A28 => Rule f A27 where get = MkA27 <$> foo instance Rule f A29 => Rule f A28 where get = MkA28 <$> foo instance Rule f A30 => Rule f A29 where get = MkA29 <$> foo instance Rule f A1 => Rule f A30 where get = MkA30 <$> foo
sdiehl/ghc
testsuite/tests/perf/compiler/WWRec.hs
bsd-3-clause
2,654
0
8
624
1,177
604
573
69
0
module Main(main) where import Control.Monad import Control.Exception import Control.Monad.Trans.Cont import GHC.Exts type RAW a = ContT () IO a -- See https://gitlab.haskell.org/ghc/ghc/issues/11555 catchSafe1, catchSafe2 :: IO a -> (SomeException -> IO a) -> IO a catchSafe1 a b = lazy a `catch` b catchSafe2 a b = join (evaluate a) `catch` b -- | Run and then call a continuation. runRAW1, runRAW2 :: RAW a -> (Either SomeException a -> IO ()) -> IO () runRAW1 m k = m `runContT` (k . Right) `catchSafe1` \e -> k $ Left e runRAW2 m k = m `runContT` (k . Right) `catchSafe2` \e -> k $ Left e {-# NOINLINE run1 #-} run1 :: RAW ()-> IO () run1 rs = do runRAW1 rs $ \x -> case x of Left e -> putStrLn "CAUGHT" Right x -> return x {-# NOINLINE run2 #-} run2 :: RAW ()-> IO () run2 rs = do runRAW2 rs $ \x -> case x of Left e -> putStrLn "CAUGHT" Right x -> return x main :: IO () main = do run1 $ error "MISSED" run2 $ error "MISSED"
sdiehl/ghc
testsuite/tests/stranal/should_run/T11555a.hs
bsd-3-clause
988
0
12
242
423
218
205
28
2
{-# LANGUAGE CPP #-} module Distribution.Client.Dependency.Modular.Preference where -- Reordering or pruning the tree in order to prefer or make certain choices. import qualified Data.List as L import qualified Data.Map as M #if !MIN_VERSION_base(4,8,0) import Data.Monoid #endif import Data.Ord import Distribution.Client.Dependency.Types ( PackageConstraint(..), PackagePreferences(..), InstalledPreference(..) ) import Distribution.Client.Types ( OptionalStanza(..) ) import Distribution.Client.Dependency.Modular.Dependency import Distribution.Client.Dependency.Modular.Flag import Distribution.Client.Dependency.Modular.Package import Distribution.Client.Dependency.Modular.PSQ as P import Distribution.Client.Dependency.Modular.Tree import Distribution.Client.Dependency.Modular.Version -- | Generic abstraction for strategies that just rearrange the package order. -- Only packages that match the given predicate are reordered. packageOrderFor :: (PN -> Bool) -> (PN -> I -> I -> Ordering) -> Tree a -> Tree a packageOrderFor p cmp = trav go where go (PChoiceF v@(Q _ pn) r cs) | p pn = PChoiceF v r (P.sortByKeys (flip (cmp pn)) cs) | otherwise = PChoiceF v r cs go x = x -- | Ordering that treats preferred versions as greater than non-preferred -- versions. preferredVersionsOrdering :: VR -> Ver -> Ver -> Ordering preferredVersionsOrdering vr v1 v2 = compare (checkVR vr v1) (checkVR vr v2) -- | Traversal that tries to establish package preferences (not constraints). -- Works by reordering choice nodes. preferPackagePreferences :: (PN -> PackagePreferences) -> Tree a -> Tree a preferPackagePreferences pcs = packageOrderFor (const True) preference where preference pn i1@(I v1 _) i2@(I v2 _) = let PackagePreferences vr ipref = pcs pn in preferredVersionsOrdering vr v1 v2 `mappend` -- combines lexically locationsOrdering ipref i1 i2 -- Note that we always rank installed before uninstalled, and later -- versions before earlier, but we can change the priority of the -- two orderings. locationsOrdering PreferInstalled v1 v2 = preferInstalledOrdering v1 v2 `mappend` preferLatestOrdering v1 v2 locationsOrdering PreferLatest v1 v2 = preferLatestOrdering v1 v2 `mappend` preferInstalledOrdering v1 v2 -- | Ordering that treats installed instances as greater than uninstalled ones. preferInstalledOrdering :: I -> I -> Ordering preferInstalledOrdering (I _ (Inst _)) (I _ (Inst _)) = EQ preferInstalledOrdering (I _ (Inst _)) _ = GT preferInstalledOrdering _ (I _ (Inst _)) = LT preferInstalledOrdering _ _ = EQ -- | Compare instances by their version numbers. preferLatestOrdering :: I -> I -> Ordering preferLatestOrdering (I v1 _) (I v2 _) = compare v1 v2 -- | Helper function that tries to enforce a single package constraint on a -- given instance for a P-node. Translates the constraint into a -- tree-transformer that either leaves the subtree untouched, or replaces it -- with an appropriate failure node. processPackageConstraintP :: ConflictSet QPN -> I -> PackageConstraint -> Tree a -> Tree a processPackageConstraintP c (I v _) (PackageConstraintVersion _ vr) r | checkVR vr v = r | otherwise = Fail c (GlobalConstraintVersion vr) processPackageConstraintP c i (PackageConstraintInstalled _) r | instI i = r | otherwise = Fail c GlobalConstraintInstalled processPackageConstraintP c i (PackageConstraintSource _) r | not (instI i) = r | otherwise = Fail c GlobalConstraintSource processPackageConstraintP _ _ _ r = r -- | Helper function that tries to enforce a single package constraint on a -- given flag setting for an F-node. Translates the constraint into a -- tree-transformer that either leaves the subtree untouched, or replaces it -- with an appropriate failure node. processPackageConstraintF :: Flag -> ConflictSet QPN -> Bool -> PackageConstraint -> Tree a -> Tree a processPackageConstraintF f c b' (PackageConstraintFlags _ fa) r = case L.lookup f fa of Nothing -> r Just b | b == b' -> r | otherwise -> Fail c GlobalConstraintFlag processPackageConstraintF _ _ _ _ r = r -- | Helper function that tries to enforce a single package constraint on a -- given flag setting for an F-node. Translates the constraint into a -- tree-transformer that either leaves the subtree untouched, or replaces it -- with an appropriate failure node. processPackageConstraintS :: OptionalStanza -> ConflictSet QPN -> Bool -> PackageConstraint -> Tree a -> Tree a processPackageConstraintS s c b' (PackageConstraintStanzas _ ss) r = if not b' && s `elem` ss then Fail c GlobalConstraintFlag else r processPackageConstraintS _ _ _ _ r = r -- | Traversal that tries to establish various kinds of user constraints. Works -- by selectively disabling choices that have been ruled out by global user -- constraints. enforcePackageConstraints :: M.Map PN [PackageConstraint] -> Tree QGoalReasonChain -> Tree QGoalReasonChain enforcePackageConstraints pcs = trav go where go (PChoiceF qpn@(Q _ pn) gr ts) = let c = toConflictSet (Goal (P qpn) gr) -- compose the transformation functions for each of the relevant constraint g = \ i -> foldl (\ h pc -> h . processPackageConstraintP c i pc) id (M.findWithDefault [] pn pcs) in PChoiceF qpn gr (P.mapWithKey g ts) go (FChoiceF qfn@(FN (PI (Q _ pn) _) f) gr tr m ts) = let c = toConflictSet (Goal (F qfn) gr) -- compose the transformation functions for each of the relevant constraint g = \ b -> foldl (\ h pc -> h . processPackageConstraintF f c b pc) id (M.findWithDefault [] pn pcs) in FChoiceF qfn gr tr m (P.mapWithKey g ts) go (SChoiceF qsn@(SN (PI (Q _ pn) _) f) gr tr ts) = let c = toConflictSet (Goal (S qsn) gr) -- compose the transformation functions for each of the relevant constraint g = \ b -> foldl (\ h pc -> h . processPackageConstraintS f c b pc) id (M.findWithDefault [] pn pcs) in SChoiceF qsn gr tr (P.mapWithKey g ts) go x = x -- | Transformation that tries to enforce manual flags. Manual flags -- can only be re-set explicitly by the user. This transformation should -- be run after user preferences have been enforced. For manual flags, -- it checks if a user choice has been made. If not, it disables all but -- the first choice. enforceManualFlags :: Tree QGoalReasonChain -> Tree QGoalReasonChain enforceManualFlags = trav go where go (FChoiceF qfn gr tr True ts) = FChoiceF qfn gr tr True $ let c = toConflictSet (Goal (F qfn) gr) in case span isDisabled (P.toList ts) of ([], y : ys) -> P.fromList (y : L.map (\ (b, _) -> (b, Fail c ManualFlag)) ys) _ -> ts -- something has been manually selected, leave things alone where isDisabled (_, Fail _ GlobalConstraintFlag) = True isDisabled _ = False go x = x -- | Prefer installed packages over non-installed packages, generally. -- All installed packages or non-installed packages are treated as -- equivalent. preferInstalled :: Tree a -> Tree a preferInstalled = packageOrderFor (const True) (const preferInstalledOrdering) -- | Prefer packages with higher version numbers over packages with -- lower version numbers, for certain packages. preferLatestFor :: (PN -> Bool) -> Tree a -> Tree a preferLatestFor p = packageOrderFor p (const preferLatestOrdering) -- | Prefer packages with higher version numbers over packages with -- lower version numbers, for all packages. preferLatest :: Tree a -> Tree a preferLatest = preferLatestFor (const True) -- | Require installed packages. requireInstalled :: (PN -> Bool) -> Tree (QGoalReasonChain, a) -> Tree (QGoalReasonChain, a) requireInstalled p = trav go where go (PChoiceF v@(Q _ pn) i@(gr, _) cs) | p pn = PChoiceF v i (P.mapWithKey installed cs) | otherwise = PChoiceF v i cs where installed (I _ (Inst _)) x = x installed _ _ = Fail (toConflictSet (Goal (P v) gr)) CannotInstall go x = x -- | Avoid reinstalls. -- -- This is a tricky strategy. If a package version is installed already and the -- same version is available from a repo, the repo version will never be chosen. -- This would result in a reinstall (either destructively, or potentially, -- shadowing). The old instance won't be visible or even present anymore, but -- other packages might have depended on it. -- -- TODO: It would be better to actually check the reverse dependencies of installed -- packages. If they're not depended on, then reinstalling should be fine. Even if -- they are, perhaps this should just result in trying to reinstall those other -- packages as well. However, doing this all neatly in one pass would require to -- change the builder, or at least to change the goal set after building. avoidReinstalls :: (PN -> Bool) -> Tree (QGoalReasonChain, a) -> Tree (QGoalReasonChain, a) avoidReinstalls p = trav go where go (PChoiceF qpn@(Q _ pn) i@(gr, _) cs) | p pn = PChoiceF qpn i disableReinstalls | otherwise = PChoiceF qpn i cs where disableReinstalls = let installed = [ v | (I v (Inst _), _) <- toList cs ] in P.mapWithKey (notReinstall installed) cs notReinstall vs (I v InRepo) _ | v `elem` vs = Fail (toConflictSet (Goal (P qpn) gr)) CannotReinstall notReinstall _ _ x = x go x = x -- | Always choose the first goal in the list next, abandoning all -- other choices. -- -- This is unnecessary for the default search strategy, because -- it descends only into the first goal choice anyway, -- but may still make sense to just reduce the tree size a bit. firstGoal :: Tree a -> Tree a firstGoal = trav go where go (GoalChoiceF xs) = -- casePSQ xs (GoalChoiceF xs) (\ _ t _ -> out t) -- more space efficient, but removes valuable debug info casePSQ xs (GoalChoiceF (fromList [])) (\ g t _ -> GoalChoiceF (fromList [(g, t)])) go x = x -- Note that we keep empty choice nodes, because they mean success. -- | Transformation that tries to make a decision on base as early as -- possible. In nearly all cases, there's a single choice for the base -- package. Also, fixing base early should lead to better error messages. preferBaseGoalChoice :: Tree a -> Tree a preferBaseGoalChoice = trav go where go (GoalChoiceF xs) = GoalChoiceF (P.sortByKeys preferBase xs) go x = x preferBase :: OpenGoal -> OpenGoal -> Ordering preferBase (OpenGoal (Simple (Dep (Q [] pn) _)) _) _ | unPN pn == "base" = LT preferBase _ (OpenGoal (Simple (Dep (Q [] pn) _)) _) | unPN pn == "base" = GT preferBase _ _ = EQ -- | Transformation that sorts choice nodes so that -- child nodes with a small branching degree are preferred. As a -- special case, choices with 0 branches will be preferred (as they -- are immediately considered inconsistent), and choices with 1 -- branch will also be preferred (as they don't involve choice). preferEasyGoalChoices :: Tree a -> Tree a preferEasyGoalChoices = trav go where go (GoalChoiceF xs) = GoalChoiceF (P.sortBy (comparing choices) xs) go x = x -- | Transformation that tries to avoid making weak flag choices early. -- Weak flags are trivial flags (not influencing dependencies) or such -- flags that are explicitly declared to be weak in the index. deferWeakFlagChoices :: Tree a -> Tree a deferWeakFlagChoices = trav go where go (GoalChoiceF xs) = GoalChoiceF (P.sortBy defer xs) go x = x defer :: Tree a -> Tree a -> Ordering defer (FChoice _ _ True _ _) _ = GT defer _ (FChoice _ _ True _ _) = LT defer _ _ = EQ -- | Variant of 'preferEasyGoalChoices'. -- -- Only approximates the number of choices in the branches. Less accurate, -- more efficient. lpreferEasyGoalChoices :: Tree a -> Tree a lpreferEasyGoalChoices = trav go where go (GoalChoiceF xs) = GoalChoiceF (P.sortBy (comparing lchoices) xs) go x = x -- | Variant of 'preferEasyGoalChoices'. -- -- I first thought that using a paramorphism might be faster here, -- but it doesn't seem to make any difference. preferEasyGoalChoices' :: Tree a -> Tree a preferEasyGoalChoices' = para (inn . go) where go (GoalChoiceF xs) = GoalChoiceF (P.map fst (P.sortBy (comparing (choices . snd)) xs)) go x = fmap fst x
DavidAlphaFox/ghc
libraries/Cabal/cabal-install/Distribution/Client/Dependency/Modular/Preference.hs
bsd-3-clause
13,140
0
20
3,327
3,082
1,590
1,492
152
4
module USCC(decls) where import UFree import UAbstract(Decls,Def,defaNames,Var(..),decl') import TiSCC import FreeNames import DefinedNames import HsIdent(HsIdentI(..)) decls = map decl' . sccD :: [Def] -> Decls instance FreeNames Var Def where freeNames = map (flip (,) ValueNames . HsVar) . free instance DefinedNames Var Def where definedNames = map (flip (,) Value . HsVar) . defaNames
forste/haReFork
tools/hs2alfa/USCC.hs
bsd-3-clause
397
0
11
62
153
88
65
-1
-1
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-} {-# LANGUAGE TypeFamilies, EmptyCase, LambdaCase #-} -- Check interaction between Newtypes and Type Families module EmptyCase007 where import Data.Kind (Type) type family FA a :: Type -- just an open type family type instance FA Int = (Char, Bool) type instance FA Char = Char type instance FA [a] = [FA a] type instance FA (a,b,b) = Void1 newtype Foo2 a = Foo2 (FA a) data Void1 -- Non-exhaustive. Missing: (_ :: Foo2 a) (no info about a) f05 :: Foo2 a -> () f05 = \case -- Non-exhaustive. Missing: (_ :: Foo2 (a, a)) (does not reduce) f06 :: Foo2 (a, a) -> () f06 = \case -- Exhaustive (reduces to Void) f07 :: Foo2 (Int, Char, Char) -> () f07 = \case -- Non-exhaustive. Missing: Foo2 (_, _) f08 :: Foo2 Int -> () f08 = \case -- Non-exhaustive. Missing: Foo2 _ f09 :: Foo2 Char -> () f09 = \case -- Non-exhaustive. Missing: (_ :: Char) -- This is a more general trick: If the warning gives you a constructor form -- and you don't know what the type of the underscore is, just match against -- the constructor form, and the warning you'll get will fill the type in. f09' :: Foo2 Char -> () f09' (Foo2 x) = case x of {} -- Non-exhaustive. Missing: Foo2 [], Foo2 (_:_) f10 :: Foo2 [Int] -> () f10 = \case
sdiehl/ghc
testsuite/tests/pmcheck/should_compile/EmptyCase007.hs
bsd-3-clause
1,274
0
7
260
291
175
116
-1
-1
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE TypeFamilies #-} module T14048b where import Data.Kind data family Foo :: Constraint
sdiehl/ghc
testsuite/tests/typecheck/should_fail/T14048b.hs
bsd-3-clause
133
0
4
20
18
13
5
5
0
module Main where import Parser import Codegen import Emit import Control.Monad.Trans import System.IO import System.Environment import System.Console.Haskeline import qualified LLVM.General.AST as AST initModule :: AST.Module initModule = emptyModule "my cool jit" process :: AST.Module -> String -> IO (Maybe AST.Module) process modo source = do let res = parseToplevel source case res of Left err -> print err >> return Nothing Right ex -> do ast <- codegen modo ex compileResult <- runJIT ast case compileResult of Left err -> print err >> return Nothing Right ast' -> return $ Just ast' processFile :: String -> IO (Maybe AST.Module) processFile fname = readFile fname >>= process initModule repl :: IO () repl = runInputT defaultSettings (loop initModule) where loop mod = do minput <- getInputLine "ready> " case minput of Nothing -> outputStrLn "Goodbye." Just input -> do modn <- liftIO $ process mod input case modn of Just modn -> loop modn Nothing -> loop mod main :: IO () main = do args <- getArgs case args of [] -> repl [fname] -> processFile fname >> return ()
yigitozkavci/glow
src/Main.hs
mit
1,210
0
17
312
417
201
216
41
3
module Text.Ponder.Char ( Parser , parse , run , item , satisfy , char , string , oneOf ) where import Control.Monad import Control.Monad.State import Control.Monad.Error import Control.Monad.Identity import Control.Applicative import Text.Ponder.Prim type Parser a = ParserT String String Identity a parse :: Parser a -> String -> Either String ((a, String), Pos) parse p s = runIdentity $ evalStateT (runErrorT $ runStateT (runStateT p s) 1) [] run :: Parser a -> String -> Pos -> Memo -> Either String ((a, String), Pos) run p s pos memo = runIdentity $ evalStateT (runErrorT $ runStateT (runStateT p s) pos) memo item :: Parser Char item = StateT $ \s -> case s of c:cs -> do p <- get put (p+1) return (c, cs) otherwise -> throwError "end of input" satisfy :: (Char -> Bool) -> Parser Char satisfy f = do c <- item if f c then StateT $ \s -> return (c,s) else StateT $ \s -> do p <- get put (p-1) throwError "not match" char :: Char -> Parser Char char c = satisfy (c==) string :: String -> Parser String string [] = return [] string (c:cs) = (:) <$> (char c) <*> (string cs) oneOf :: String -> Parser Char oneOf cs = satisfy (\c -> elem c cs)
matt76k/ponder
Text/Ponder/Char.hs
mit
1,407
0
14
476
546
287
259
38
2
module Graphics.D3D11Binding.Interface.D3DBlob where import Data.Word import Foreign.Ptr import Graphics.D3D11Binding.Interface.Unknown data ID3DBlob = ID3DBlob foreign import stdcall "GetBufferPointer" c_getBufferPointer :: Ptr ID3DBlob -> IO (Ptr ()) foreign import stdcall "GetBufferSize" c_getBufferSize :: Ptr ID3DBlob -> IO Word32 class (UnknownInterface interface) => D3DBlobInterface interface where getBufferPointer :: Ptr interface -> IO (Ptr ()) getBufferPointer ptr = c_getBufferPointer (castPtr ptr) getBufferSize :: Ptr interface -> IO Word32 getBufferSize ptr = c_getBufferSize (castPtr ptr) instance UnknownInterface ID3DBlob instance D3DBlobInterface ID3DBlob
jwvg0425/d3d11binding
src/Graphics/D3D11Binding/Interface/D3DBlob.hs
mit
696
0
11
95
188
96
92
16
0
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} module Main where import Common import Config import TL import Control.Applicative ((<$>)) import Control.Monad (when) import Control.Monad.Logger import Control.Monad.Trans import Control.Monad.Trans.Resource import qualified Data.Aeson as AE import qualified Data.Aeson.Encode as AEE import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy.Char8 as BL import qualified Data.Conduit as C import qualified Data.Conduit.List as CL import Data.Default import qualified Data.List as L import Data.Maybe (fromJust, isJust, isNothing) import qualified Data.Text as T import qualified Data.Text.Encoding as TE import Network.HTTP.Conduit (withManager) import Web.Authenticate.OAuth (Credential(..)) import Web.Twitter.Conduit import Web.Twitter.Types (StreamingAPI(..)) isLogging :: Configuration -> Bool isLogging = isJust . logFile logAndShow :: (StreamingAPI, AE.Value) -> IO () logAndShow (s, v) = do Just cfg <- loadConfig when (isLogging cfg) $ do let file = "./" ++ (T.unpack . fromJust $ logFile cfg) BL.appendFile file $ AEE.encode v BL.appendFile file "\n" if isColor cfg then showTLwithColor s else showTL s loadCfg :: IO Configuration loadCfg = do mcfg <- loadConfig case mcfg of Just c -> return c Nothing -> error "Configuration file is not found!" withCredential :: Credential -> Configuration -> TW (ResourceT (NoLoggingT IO)) a -> NoLoggingT IO a withCredential cred cfg task = do pr <- liftIO getProxyEnv let tokens = getTokens (B.pack $ consumerToken cfg) (B.pack $ consumerSecret cfg) let env = (setCredential tokens cred def) { twProxy = pr } runTW env task ($=+) :: MonadIO m => C.ResumableSource m a -> C.Conduit a m o -> m (C.ResumableSource m o) ($=+) = (return .) . (C.$=+) sinkFromJSONWithRaw :: (AE.FromJSON a, MonadThrow m, MonadLogger m) => C.Consumer B.ByteString m (a, AE.Value) sinkFromJSONWithRaw = do v <- sinkJSON case AE.fromJSON v of AE.Error err -> monadThrow $ FromJSONError err AE.Success r -> return (r, v) streamWithRaw :: (TwitterBaseM m, AE.FromJSON value) => APIRequest apiName responseType -> TW m (C.ResumableSource (TW m) (value, AE.Value)) streamWithRaw req = do rsrc <- getResponse =<< makeRequest req responseBody rsrc $=+ CL.sequence sinkFromJSONWithRaw getOAuthToken :: Configuration -> IO Configuration getOAuthToken cfg = do let oauth = getTokens (B.pack $ consumerToken cfg) (B.pack $ consumerSecret cfg) pr <- getProxyEnv cred <- withManager $ authorize pr oauth return $ cfg { oauthToken = TE.decodeUtf8 <$> L.lookup "oauth_token" (unCredential cred), oauthTokenSecret = TE.decodeUtf8 <$> L.lookup "oauth_token_secret" (unCredential cred)} main :: IO () main = do cfg <- loadCfg when (isNothing $ oauthToken cfg) $ do cfg' <- getOAuthToken cfg saveConfig cfg' cfg' <- loadCfg let cred = makeCred cfg' runNoLoggingT $ withCredential cred cfg' $ do src <- streamWithRaw userstream src C.$$+- CL.mapM_ (liftIO . logAndShow)
chiro/tchhh
src/Main.hs
mit
3,198
0
17
623
1,081
566
515
87
2
{-# language NoImplicitPrelude, DoAndIfThenElse, OverloadedStrings, ExtendedDefaultRules #-}{-# LANGUAGE CPP #-} module IHaskellPrelude ( module IHaskellPrelude, module X, -- Select reexports Data.Typeable.Typeable, Data.Typeable.cast, #if MIN_VERSION_ghc(7,8,0) Data.Typeable.Proxy, GHC.Exts.IsString, GHC.Exts.IsList, #endif System.IO.hPutStrLn, System.IO.hPutStr, System.IO.hPutChar, System.IO.hPrint, System.IO.stdout, System.IO.stderr, System.IO.stdin, System.IO.getChar, System.IO.getLine, System.IO.writeFile, System.IO.Handle, System.IO.Strict.readFile, System.IO.Strict.getContents, System.IO.Strict.hGetContents, Control.Exception.catch, Control.Exception.SomeException, Control.Applicative.Applicative(..), Control.Applicative.ZipList(..), (Control.Applicative.<$>), Control.Concurrent.MVar.MVar, Control.Concurrent.MVar.newMVar, Control.Concurrent.MVar.newEmptyMVar, Control.Concurrent.MVar.isEmptyMVar, Control.Concurrent.MVar.readMVar, Control.Concurrent.MVar.takeMVar, Control.Concurrent.MVar.putMVar, Control.Concurrent.MVar.modifyMVar, Control.Concurrent.MVar.modifyMVar_, Data.IORef.IORef, Data.IORef.readIORef, Data.IORef.writeIORef, Data.IORef.modifyIORef', Data.IORef.newIORef, -- Miscellaneous names Data.Map.Map, GHC.IO.FilePath, Data.Text.Text, Data.ByteString.ByteString, Text.Printf.printf, Data.Function.on, ) where import Prelude import Data.Monoid as X import Data.Tuple as X import Control.Monad as X import Data.Maybe as X import Data.Either as X import Control.Monad.IO.Class as X import Data.Ord as X import GHC.Show as X import GHC.Enum as X import GHC.Num as X import GHC.Real as X import GHC.Err as X hiding (absentErr) #if MIN_VERSION_ghc(8,0,0) import GHC.Base as X hiding (Any, mapM, foldr, sequence, many, (<|>), Module(..)) #elif MIN_VERSION_ghc(7,10,0) import GHC.Base as X hiding (Any, mapM, foldr, sequence, many, (<|>)) #else import GHC.Base as X hiding (Any) #endif import Data.List as X hiding (head, last, tail, init, transpose, subsequences, permutations, foldl, foldl1, maximum, minimum, scanl, scanl1, scanr, scanr1, span, break, mapAccumL, mapAccumR, dropWhileEnd, (!!), elemIndices, elemIndex, findIndex, findIndices, zip5, zip6, zip7, zipWith5, zipWith6, zipWith7, unzip5, unzip6, unzip6, delete, union, lookup, intersect, insert, deleteBy, deleteFirstBy, unionBy, intersectBy, group, groupBy, insertBy, maximumBy, minimumBy, genericLength, genericDrop, genericTake, genericSplitAt, genericIndex, genericReplicate, inits, tails) import qualified Control.Applicative import qualified Data.Typeable import qualified Data.IORef import qualified Data.Map import qualified Data.Text import qualified Data.Text.Lazy import qualified Data.ByteString import qualified Data.ByteString.Lazy import qualified Data.Function import qualified GHC.Exts import qualified System.IO import qualified System.IO.Strict import qualified GHC.IO import qualified Text.Printf import qualified Control.Exception import qualified Control.Concurrent.MVar import qualified Data.List import qualified Prelude as P type LByteString = Data.ByteString.Lazy.ByteString type LText = Data.Text.Lazy.Text (headMay, tailMay, lastMay, initMay, maximumMay, minimumMay) = (wrapEmpty head, wrapEmpty tail, wrapEmpty last, wrapEmpty init, wrapEmpty maximum, wrapEmpty minimum) where wrapEmpty :: ([a] -> b) -> [a] -> Maybe b wrapEmpty _ [] = Nothing wrapEmpty f xs = Just (f xs) maximumByMay :: (a -> a -> Ordering) -> [a] -> Maybe a maximumByMay _ [] = Nothing maximumByMay f xs = Just (Data.List.maximumBy f xs) minimumByMay :: (a -> a -> Ordering) -> [a] -> Maybe a minimumByMay _ [] = Nothing minimumByMay f xs = Just (Data.List.minimumBy f xs) readMay :: Read a => String -> Maybe a readMay = fmap fst . headMay . reads putStrLn :: (MonadIO m) => String -> m () putStrLn = liftIO . P.putStrLn putStr :: (MonadIO m) => String -> m () putStr = liftIO . P.putStr putChar :: MonadIO m => Char -> m () putChar = liftIO . P.putChar print :: (MonadIO m, Show a) => a -> m () print = liftIO . P.print
sumitsahrawat/IHaskell
main/IHaskellPrelude.hs
mit
4,841
0
10
1,282
1,183
745
438
110
2
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} -- | Chell is a simple and intuitive library for automated testing. It natively -- supports assertion-based testing, and can use companion libraries -- such as @chell-quickcheck@ to support more complex testing strategies. -- -- An example test suite, which verifies the behavior of artithmetic operators. -- -- @ --{-\# LANGUAGE TemplateHaskell \#-} -- --import Test.Chell -- --suite_Math :: Suite --suite_Math = 'suite' \"math\" -- [ test_Addition -- , test_Subtraction -- ] -- --test_Addition :: Test --test_Addition = 'assertions' \"addition\" $ do -- $'expect' ('equal' (2 + 1) 3) -- $'expect' ('equal' (1 + 2) 3) -- --test_Subtraction :: Test --test_Subtraction = 'assertions' \"subtraction\" $ do -- $'expect' ('equal' (2 - 1) 1) -- $'expect' ('equal' (1 - 2) (-1)) -- --main :: IO () --main = 'defaultMain' [suite_Math] -- @ -- -- >$ ghc --make chell-example.hs -- >$ ./chell-example -- >PASS: 2 tests run, 2 tests passed module Test.Chell ( -- * Main defaultMain -- * Test suites , Suite , suite , suiteName , suiteTests -- ** Skipping some tests , SuiteOrTest , skipIf , skipWhen -- * Basic testing library , Assertions , assertions , IsAssertion , Assertion , assertionPassed , assertionFailed , assert , expect , die , trace , note , afterTest , requireLeft , requireRight -- ** Built-in assertions , equal , notEqual , equalWithin , just , nothing , left , right , throws , throwsEq , greater , greaterEqual , lesser , lesserEqual , sameItems , equalItems , IsText , equalLines , equalLinesWith -- * Custom test types , Test , test , testName , runTest -- ** Test results , TestResult (..) -- *** Failures , Failure , failure , failureLocation , failureMessage -- *** Failure locations , Location , location , locationFile , locationModule , locationLine -- ** Test options , TestOptions , defaultTestOptions , testOptionSeed , testOptionTimeout ) where import qualified Control.Applicative import qualified Control.Exception import Control.Exception (Exception) import Control.Monad (ap, liftM) import Control.Monad.IO.Class (MonadIO, liftIO) import qualified Data.Algorithm.Patience as Patience import qualified Data.ByteString.Char8 import qualified Data.ByteString.Lazy.Char8 import Data.Foldable (Foldable, foldMap) import Data.List (foldl', intercalate, sort) import Data.Maybe (isJust, isNothing) import Data.IORef (IORef, newIORef, readIORef, modifyIORef) import qualified Data.Text import Data.Text (Text) import qualified Data.Text.Lazy import qualified Language.Haskell.TH as TH import Test.Chell.Main (defaultMain) import Test.Chell.Types -- | A single pass/fail assertion. Failed assertions include an explanatory -- message. data Assertion = AssertionPassed | AssertionFailed String deriving (Eq, Show) -- | See 'Assertion'. assertionPassed :: Assertion assertionPassed = AssertionPassed -- | See 'Assertion'. assertionFailed :: String -> Assertion assertionFailed = AssertionFailed -- | See 'assert' and 'expect'. class IsAssertion a where runAssertion :: a -> IO Assertion instance IsAssertion Assertion where runAssertion = return instance IsAssertion Bool where runAssertion x = return $ if x then assertionPassed else assertionFailed "boolean assertion failed" instance IsAssertion a => IsAssertion (IO a) where runAssertion x = x >>= runAssertion type TestState = (IORef [(String, String)], IORef [IO ()], [Failure]) -- | See 'assertions'. newtype Assertions a = Assertions { unAssertions :: TestState -> IO (Maybe a, TestState) } instance Functor Assertions where fmap = liftM instance Control.Applicative.Applicative Assertions where pure = return (<*>) = ap instance Monad Assertions where return x = Assertions (\s -> return (Just x, s)) m >>= f = Assertions (\s -> do (maybe_a, s') <- unAssertions m s case maybe_a of Nothing -> return (Nothing, s') Just a -> unAssertions (f a) s') instance MonadIO Assertions where liftIO io = Assertions (\s -> do x <- io return (Just x, s)) -- | Convert a sequence of pass/fail assertions into a runnable test. -- -- @ -- test_Equality :: Test -- test_Equality = assertions \"equality\" $ do -- $assert (1 == 1) -- $assert (equal 1 1) -- @ assertions :: String -> Assertions a -> Test assertions name testm = test name $ \opts -> do noteRef <- newIORef [] afterTestRef <- newIORef [] let getNotes = fmap reverse (readIORef noteRef) let getResult = do res <- unAssertions testm (noteRef, afterTestRef, []) case res of (_, (_, _, [])) -> do notes <- getNotes return (TestPassed notes) (_, (_, _, fs)) -> do notes <- getNotes return (TestFailed notes (reverse fs)) Control.Exception.finally (handleJankyIO opts getResult getNotes) (runAfterTest afterTestRef) runAfterTest :: IORef [IO ()] -> IO () runAfterTest ref = readIORef ref >>= loop where loop [] = return () loop (io:ios) = Control.Exception.finally (loop ios) io addFailure :: Maybe TH.Loc -> String -> Assertions () addFailure maybe_loc msg = Assertions $ \(notes, afterTestRef, fs) -> do let loc = do th_loc <- maybe_loc return $ location { locationFile = TH.loc_filename th_loc , locationModule = TH.loc_module th_loc , locationLine = Just (toInteger (fst (TH.loc_start th_loc))) } let f = failure { failureLocation = loc , failureMessage = msg } return (Just (), (notes, afterTestRef, f : fs)) -- | Cause a test to immediately fail, with a message. -- -- 'die' is a Template Haskell macro, to retain the source-file location from -- which it was used. Its effective type is: -- -- @ -- $die :: 'String' -> 'Assertions' a -- @ die :: TH.Q TH.Exp die = do loc <- TH.location let qloc = liftLoc loc [| \msg -> dieAt $qloc ("die: " ++ msg) |] dieAt :: TH.Loc -> String -> Assertions a dieAt loc msg = do addFailure (Just loc) msg Assertions (\s -> return (Nothing, s)) -- | Print a message from within a test. This is just a helper for debugging, -- so you don't have to import @Debug.Trace@. Messages will be prefixed with -- the filename and line number where @$trace@ was called. -- -- 'trace' is a Template Haskell macro, to retain the source-file location -- from which it was used. Its effective type is: -- -- @ -- $trace :: 'String' -> 'Assertions' () -- @ trace :: TH.Q TH.Exp trace = do loc <- TH.location let qloc = liftLoc loc [| traceAt $qloc |] traceAt :: TH.Loc -> String -> Assertions () traceAt loc msg = liftIO $ do let file = TH.loc_filename loc let line = fst (TH.loc_start loc) putStr ("[" ++ file ++ ":" ++ show line ++ "] ") putStrLn msg -- | Attach a note to a test run. Notes will be printed to stdout and -- included in reports, even if the test fails or aborts. Notes are useful for -- debugging failing tests. note :: String -> String -> Assertions () note key value = Assertions (\(notes, afterTestRef, fs) -> do modifyIORef notes ((key, value) :) return (Just (), (notes, afterTestRef, fs))) -- | Register an IO action to be run after the test completes. This action -- will run even if the test failed or aborted. afterTest :: IO () -> Assertions () afterTest io = Assertions (\(notes, ref, fs) -> do modifyIORef ref (io :) return (Just (), (notes, ref, fs))) -- | Require an 'Either' value to be 'Left', and return its contents. If -- the value is 'Right', fail the test. -- -- 'requireLeft' is a Template Haskell macro, to retain the source-file -- location from which it was used. Its effective type is: -- -- @ -- $requireLeft :: 'Show' b => 'Either' a b -> 'Assertions' a -- @ requireLeft :: TH.Q TH.Exp requireLeft = do loc <- TH.location let qloc = liftLoc loc [| requireLeftAt $qloc |] requireLeftAt :: Show b => TH.Loc -> Either a b -> Assertions a requireLeftAt loc val = case val of Left a -> return a Right b -> do let dummy = Right b `asTypeOf` Left () dieAt loc ("requireLeft: received " ++ showsPrec 11 dummy "") -- | Require an 'Either' value to be 'Right', and return its contents. If -- the value is 'Left', fail the test. -- -- 'requireRight' is a Template Haskell macro, to retain the source-file -- location from which it was used. Its effective type is: -- -- @ -- $requireRight :: 'Show' a => 'Either' a b -> 'Assertions' b -- @ requireRight :: TH.Q TH.Exp requireRight = do loc <- TH.location let qloc = liftLoc loc [| requireRightAt $qloc |] requireRightAt :: Show a => TH.Loc -> Either a b -> Assertions b requireRightAt loc val = case val of Left a -> do let dummy = Left a `asTypeOf` Right () dieAt loc ("requireRight: received " ++ showsPrec 11 dummy "") Right b -> return b liftLoc :: TH.Loc -> TH.Q TH.Exp liftLoc loc = [| TH.Loc filename package module_ start end |] where filename = TH.loc_filename loc package = TH.loc_package loc module_ = TH.loc_module loc start = TH.loc_start loc end = TH.loc_end loc assertAt :: IsAssertion assertion => TH.Loc -> Bool -> assertion -> Assertions () assertAt loc fatal assertion = do result <- liftIO (runAssertion assertion) case result of AssertionPassed -> return () AssertionFailed err -> if fatal then dieAt loc err else addFailure (Just loc) err -- | Check an assertion. If the assertion fails, the test will immediately -- fail. -- -- The assertion to check can be a boolean value, an 'Assertion', or an IO -- action returning one of the above. -- -- 'assert' is a Template Haskell macro, to retain the source-file location -- from which it was used. Its effective type is: -- -- @ -- $assert :: 'IsAssertion' assertion => assertion -> 'Assertions' () -- @ assert :: TH.Q TH.Exp assert = do loc <- TH.location let qloc = liftLoc loc [| assertAt $qloc True |] -- | Check an assertion. If the assertion fails, the test will continue to -- run until it finishes, a call to 'assert' fails, or the test runs 'die'. -- -- The assertion to check can be a boolean value, an 'Assertion', or an IO -- action returning one of the above. -- -- 'expect' is a Template Haskell macro, to retain the source-file location -- from which it was used. Its effective type is: -- -- @ -- $expect :: 'IsAssertion' assertion => assertion -> 'Assertions' () -- @ expect :: TH.Q TH.Exp expect = do loc <- TH.location let qloc = liftLoc loc [| assertAt $qloc False |] pure :: Bool -> String -> Assertion pure True _ = assertionPassed pure False err = AssertionFailed err -- | Assert that two values are equal. equal :: (Show a, Eq a) => a -> a -> Assertion equal x y = pure (x == y) ("equal: " ++ show x ++ " is not equal to " ++ show y) -- | Assert that two values are not equal. notEqual :: (Eq a, Show a) => a -> a -> Assertion notEqual x y = pure (x /= y) ("notEqual: " ++ show x ++ " is equal to " ++ show y) -- | Assert that two values are within some delta of each other. equalWithin :: (Real a, Show a) => a -> a -> a -- ^ delta -> Assertion equalWithin x y delta = pure ((x - delta <= y) && (x + delta >= y)) ("equalWithin: " ++ show x ++ " is not within " ++ show delta ++ " of " ++ show y) -- | Assert that some value is @Just@. just :: Maybe a -> Assertion just x = pure (isJust x) ("just: received Nothing") -- | Assert that some value is @Nothing@. nothing :: Show a => Maybe a -> Assertion nothing x = pure (isNothing x) ("nothing: received " ++ showsPrec 11 x "") -- | Assert that some value is @Left@. left :: Show b => Either a b -> Assertion left (Left _) = assertionPassed left (Right b) = assertionFailed ("left: received " ++ showsPrec 11 dummy "") where dummy = Right b `asTypeOf` Left () -- | Assert that some value is @Right@. right :: Show a => Either a b -> Assertion right (Right _) = assertionPassed right (Left a) = assertionFailed ("right: received " ++ showsPrec 11 dummy "") where dummy = Left a `asTypeOf` Right () -- | Assert that some computation throws an exception matching the provided -- predicate. This is mostly useful for exception types which do not have an -- instance for @Eq@, such as @'Control.Exception.ErrorCall'@. throws :: Exception err => (err -> Bool) -> IO a -> IO Assertion throws p io = do either_exc <- Control.Exception.try io return $ case either_exc of Left exc -> if p exc then assertionPassed else assertionFailed ("throws: exception " ++ show exc ++ " did not match predicate") Right _ -> assertionFailed "throws: no exception thrown" -- | Assert that some computation throws an exception equal to the given -- exception. This is better than just checking that the correct type was -- thrown, because the test can also verify the exception contains the correct -- information. throwsEq :: (Eq err, Exception err, Show err) => err -> IO a -> IO Assertion throwsEq expected io = do either_exc <- Control.Exception.try io return $ case either_exc of Left exc -> if exc == expected then assertionPassed else assertionFailed ("throwsEq: exception " ++ show exc ++ " is not equal to " ++ show expected) Right _ -> assertionFailed "throwsEq: no exception thrown" -- | Assert a value is greater than another. greater :: (Ord a, Show a) => a -> a -> Assertion greater x y = pure (x > y) ("greater: " ++ show x ++ " is not greater than " ++ show y) -- | Assert a value is greater than or equal to another. greaterEqual :: (Ord a, Show a) => a -> a -> Assertion greaterEqual x y = pure (x >= y) ("greaterEqual: " ++ show x ++ " is not greater than or equal to " ++ show y) -- | Assert a value is less than another. lesser :: (Ord a, Show a) => a -> a -> Assertion lesser x y = pure (x < y) ("lesser: " ++ show x ++ " is not less than " ++ show y) -- | Assert a value is less than or equal to another. lesserEqual :: (Ord a, Show a) => a -> a -> Assertion lesserEqual x y = pure (x <= y) ("lesserEqual: " ++ show x ++ " is not less than or equal to " ++ show y) -- | Assert that two containers have the same items, in any order. sameItems :: (Foldable container, Show item, Ord item) => container item -> container item -> Assertion sameItems x y = equalDiff' "sameItems" sort x y -- | Assert that two containers have the same items, in the same order. equalItems :: (Foldable container, Show item, Ord item) => container item -> container item -> Assertion equalItems x y = equalDiff' "equalItems" id x y equalDiff' :: (Foldable container, Show item, Ord item) => String -> ([item] -> [item]) -> container item -> container item -> Assertion equalDiff' label norm x y = checkDiff (items x) (items y) where items = norm . foldMap (:[]) checkDiff xs ys = case checkItems (Patience.diff xs ys) of (same, diff) -> pure same diff checkItems diffItems = case foldl' checkItem (True, []) diffItems of (same, diff) -> (same, errorMsg (intercalate "\n" (reverse diff))) checkItem (same, acc) item = case item of Patience.Old t -> (False, ("\t- " ++ show t) : acc) Patience.New t -> (False, ("\t+ " ++ show t) : acc) Patience.Both t _-> (same, ("\t " ++ show t) : acc) errorMsg diff = label ++ ": items differ\n" ++ diff -- | Class for types which can be treated as text; see 'equalLines'. class IsText a where toLines :: a -> [a] unpack :: a -> String instance IsText String where toLines = lines unpack = id instance IsText Text where toLines = Data.Text.lines unpack = Data.Text.unpack instance IsText Data.Text.Lazy.Text where toLines = Data.Text.Lazy.lines unpack = Data.Text.Lazy.unpack -- | Uses @Data.ByteString.Char8@ instance IsText Data.ByteString.Char8.ByteString where toLines = Data.ByteString.Char8.lines unpack = Data.ByteString.Char8.unpack -- | Uses @Data.ByteString.Lazy.Char8@ instance IsText Data.ByteString.Lazy.Char8.ByteString where toLines = Data.ByteString.Lazy.Char8.lines unpack = Data.ByteString.Lazy.Char8.unpack -- | Assert that two pieces of text are equal. This uses a diff algorithm -- to check line-by-line, so the error message will be easier to read on -- large inputs. equalLines :: (Ord a, IsText a) => a -> a -> Assertion equalLines x y = checkLinesDiff "equalLines" (toLines x) (toLines y) -- | Variant of 'equalLines' which allows a user-specified line-splitting -- predicate. equalLinesWith :: Ord a => (a -> [String]) -> a -> a -> Assertion equalLinesWith toStringLines x y = checkLinesDiff "equalLinesWith" (toStringLines x) (toStringLines y) checkLinesDiff :: (Ord a, IsText a) => String -> [a] -> [a] -> Assertion checkLinesDiff label = go where go xs ys = case checkItems (Patience.diff xs ys) of (same, diff) -> pure same diff checkItems diffItems = case foldl' checkItem (True, []) diffItems of (same, diff) -> (same, errorMsg (intercalate "\n" (reverse diff))) checkItem (same, acc) item = case item of Patience.Old t -> (False, ("\t- " ++ unpack t) : acc) Patience.New t -> (False, ("\t+ " ++ unpack t) : acc) Patience.Both t _-> (same, ("\t " ++ unpack t) : acc) errorMsg diff = label ++ ": lines differ\n" ++ diff
shlevy/chell
lib/Test/Chell.hs
mit
17,183
69
26
3,534
4,655
2,502
2,153
329
3
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.UIEvent (js_initUIEvent, initUIEvent, js_getView, getView, js_getDetail, getDetail, js_getKeyCode, getKeyCode, js_getCharCode, getCharCode, js_getLayerX, getLayerX, js_getLayerY, getLayerY, js_getPageX, getPageX, js_getPageY, getPageY, js_getWhich, getWhich, UIEvent, castToUIEvent, gTypeUIEvent, IsUIEvent, toUIEvent) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSRef(..), JSString, castRef) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSRef(..), FromJSRef(..)) import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.Enums foreign import javascript unsafe "$1[\"initUIEvent\"]($2, $3, $4,\n$5, $6)" js_initUIEvent :: JSRef UIEvent -> JSString -> Bool -> Bool -> JSRef Window -> Int -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/UIEvent.initUIEvent Mozilla UIEvent.initUIEvent documentation> initUIEvent :: (MonadIO m, IsUIEvent self, ToJSString type') => self -> type' -> Bool -> Bool -> Maybe Window -> Int -> m () initUIEvent self type' canBubble cancelable view detail = liftIO (js_initUIEvent (unUIEvent (toUIEvent self)) (toJSString type') canBubble cancelable (maybe jsNull pToJSRef view) detail) foreign import javascript unsafe "$1[\"view\"]" js_getView :: JSRef UIEvent -> IO (JSRef Window) -- | <https://developer.mozilla.org/en-US/docs/Web/API/UIEvent.view Mozilla UIEvent.view documentation> getView :: (MonadIO m, IsUIEvent self) => self -> m (Maybe Window) getView self = liftIO ((js_getView (unUIEvent (toUIEvent self))) >>= fromJSRef) foreign import javascript unsafe "$1[\"detail\"]" js_getDetail :: JSRef UIEvent -> IO Int -- | <https://developer.mozilla.org/en-US/docs/Web/API/UIEvent.detail Mozilla UIEvent.detail documentation> getDetail :: (MonadIO m, IsUIEvent self) => self -> m Int getDetail self = liftIO (js_getDetail (unUIEvent (toUIEvent self))) foreign import javascript unsafe "$1[\"keyCode\"]" js_getKeyCode :: JSRef UIEvent -> IO Int -- | <https://developer.mozilla.org/en-US/docs/Web/API/UIEvent.keyCode Mozilla UIEvent.keyCode documentation> getKeyCode :: (MonadIO m, IsUIEvent self) => self -> m Int getKeyCode self = liftIO (js_getKeyCode (unUIEvent (toUIEvent self))) foreign import javascript unsafe "$1[\"charCode\"]" js_getCharCode :: JSRef UIEvent -> IO Int -- | <https://developer.mozilla.org/en-US/docs/Web/API/UIEvent.charCode Mozilla UIEvent.charCode documentation> getCharCode :: (MonadIO m, IsUIEvent self) => self -> m Int getCharCode self = liftIO (js_getCharCode (unUIEvent (toUIEvent self))) foreign import javascript unsafe "$1[\"layerX\"]" js_getLayerX :: JSRef UIEvent -> IO Int -- | <https://developer.mozilla.org/en-US/docs/Web/API/UIEvent.layerX Mozilla UIEvent.layerX documentation> getLayerX :: (MonadIO m, IsUIEvent self) => self -> m Int getLayerX self = liftIO (js_getLayerX (unUIEvent (toUIEvent self))) foreign import javascript unsafe "$1[\"layerY\"]" js_getLayerY :: JSRef UIEvent -> IO Int -- | <https://developer.mozilla.org/en-US/docs/Web/API/UIEvent.layerY Mozilla UIEvent.layerY documentation> getLayerY :: (MonadIO m, IsUIEvent self) => self -> m Int getLayerY self = liftIO (js_getLayerY (unUIEvent (toUIEvent self))) foreign import javascript unsafe "$1[\"pageX\"]" js_getPageX :: JSRef UIEvent -> IO Int -- | <https://developer.mozilla.org/en-US/docs/Web/API/UIEvent.pageX Mozilla UIEvent.pageX documentation> getPageX :: (MonadIO m, IsUIEvent self) => self -> m Int getPageX self = liftIO (js_getPageX (unUIEvent (toUIEvent self))) foreign import javascript unsafe "$1[\"pageY\"]" js_getPageY :: JSRef UIEvent -> IO Int -- | <https://developer.mozilla.org/en-US/docs/Web/API/UIEvent.pageY Mozilla UIEvent.pageY documentation> getPageY :: (MonadIO m, IsUIEvent self) => self -> m Int getPageY self = liftIO (js_getPageY (unUIEvent (toUIEvent self))) foreign import javascript unsafe "$1[\"which\"]" js_getWhich :: JSRef UIEvent -> IO Int -- | <https://developer.mozilla.org/en-US/docs/Web/API/UIEvent.which Mozilla UIEvent.which documentation> getWhich :: (MonadIO m, IsUIEvent self) => self -> m Int getWhich self = liftIO (js_getWhich (unUIEvent (toUIEvent self)))
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/UIEvent.hs
mit
4,904
70
13
773
1,254
689
565
73
1
{-# LANGUAGE GADTs #-} {-# LANGUAGE Arrows #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE UndecidableInstances #-} module Control.FRP.Wire(Wire, runWire, stepWire) where import Prelude hiding (id, (.)) import Control.Category import Control.Arrow import Control.Arrow.Transformer import Control.Arrow.Operations data Wire a b c where WLift :: a b c -> Wire a b c WState :: a (b, s) (c, s) -> s -> Wire a b c runWire :: (Arrow a) => Wire a () () -> a () () runWire (WLift a) = ioLoop where ioLoop = a >>> ioLoop runWire (WState f s) = const ((), s) ^>> ioLoop >>^ const () where ioLoop = f >>> ioLoop stepWire :: (Arrow a) => Wire a b c -> a b (c, Wire a b c) stepWire w@(WLift a) = a >>^ (\x -> (x, w)) stepWire (WState f s) = (\x -> (x, s)) ^>> f >>^ (\(x, s') -> (x, WState f s')) instance (Arrow a) => Category (Wire a) where id = WLift id WLift f . WLift g = WLift (f . g) WLift f . WState g isg = WState (first f . g) isg WState f isf . WLift g = WState (f . first g) isf WState f isf . WState g isg = WState h (isf, isg) where h = proc ~(x, (sf, sg)) -> do ~(y, sg') <- g -< (x, sg) ~(z, sf') <- f -< (y, sf) id -< (z, (sf', sg')) instance (Arrow a) => Arrow (Wire a) where arr = WLift . arr first (WLift f) = WLift (first f) first (WState f s) = WState (exchange ^>> first f >>^ exchange) s where exchange ~((x, y), z) = ((x, z), y) instance (ArrowChoice a) => ArrowChoice (Wire a) where left (WLift f) = WLift (left f) left (WState f s) = WState (exchange ^>> left f >>^ unexchange) s where exchange (Left x, y) = Left (x, y) exchange (Right x, y) = Right (x, y) unexchange (Left (x, y)) = (Left x, y) unexchange (Right (x, y)) = (Right x, y) instance (ArrowLoop a) => ArrowLoop (Wire a) where loop (WLift f) = WLift (loop f) loop (WState f s) = WState (loop $ exchange ^>> f >>^ exchange) s where exchange ~((a, b), c) = ((a, c), b) instance (Arrow a) => ArrowTransformer Wire a where lift = WLift instance (ArrowLoop a) => ArrowCircuit (Wire a) where delay = WState (arr swp) where swp ~(x, y) = (y, x) instance (ArrowZero a) => ArrowZero (Wire a) where zeroArrow = WLift zeroArrow instance (ArrowReader r a) => ArrowReader r (Wire a) where readState = WLift readState newReader (WLift x) = WLift (newReader x) newReader (WState f s) = WState f' s where f' = exchange ^>> newReader f exchange ~((x, y), z) = ((x, z), y) instance (ArrowWriter w a) => ArrowWriter w (Wire a) where write = WLift write newWriter (WLift x) = WLift (newWriter x) newWriter (WState f s) = WState (newWriter f >>^ exchange) s where exchange ~((x, y), z) = ((x, z), y) instance (ArrowState s a) => ArrowState s (Wire a) where fetch = WLift fetch store = WLift store instance (ArrowChoice a, ArrowError ex a) => ArrowError ex (Wire a) where raise = WLift raise newError (WLift a) = WLift (newError a) newError (WState f a) = WState f' a where f' = proc ~(x, s) -> do y <- newError f -< (x, s) case y of Left ex -> id -< (Left ex, s) Right (z, s') -> id -< (Right z, s') tryInUnless = tryInUnlessDefault
prophile/state-wire
Control/FRP/Wire.hs
mit
3,371
2
17
941
1,664
878
786
77
1
{-# LANGUAGE RecordWildCards , ForeignFunctionInterface , TemplateHaskell , BangPatterns , FlexibleContexts #-} module RustNBodyExperiment ( RustNBodyExperiment ) where import Control.Monad.IO.Class import Control.Lens import Control.Monad import Control.Monad.State.Class import Foreign.C.Types import Foreign.Ptr import Data.Word import Data.Maybe import Text.Printf import qualified Data.Vector.Storable.Mutable as VSM import qualified Graphics.UI.GLFW as GLFW import Experiment import FrameBuffer import Timing import qualified BoundedSequence as BS import Median import GLFWHelpers -- N-Body Simulation data RustNBodyExperiment = RustNBodyExperiment { _rnbNumSteps :: !Int , _rnbTimes :: !(BS.BoundedSequence Double) , _rnbTimeStep :: !Double , _rnbTheta :: !Double , _rnbNumThreads :: !Int } makeLenses ''RustNBodyExperiment instance Experiment RustNBodyExperiment where withExperiment f = do liftIO $ nbStableOrbits 10000 0.5 30.0 f $ RustNBodyExperiment { _rnbNumSteps = 0 , _rnbTimes = BS.empty 30 , _rnbTimeStep = 0.01 , _rnbTheta = 0.85 , _rnbNumThreads = 1 } experimentName _ = "RustNBody" experimentDraw fb _tick = do dt <- use rnbTimeStep theta <- use rnbTheta nthreads <- use rnbNumThreads -- Simulate first time <- fst <$> liftIO (timeIt $ nbStepBarnesHut (realToFrac theta) (realToFrac dt) (fromIntegral nthreads)) void . liftIO . fillFrameBuffer fb $ \w h vec -> VSM.unsafeWith vec $ \pvec -> nbDraw (fromIntegral w) (fromIntegral h) pvec rnbNumSteps += 1 rnbTimes %= BS.push_ time experimentStatusString = do RustNBodyExperiment { .. } <- get let avgtime = fromMaybe 1 . median . BS.toList $ _rnbTimes np <- liftIO (fromIntegral <$> nbNumParticles :: IO Int) return $ printf ( "%i Steps, %.1fSPS/%.2fms | %s Bodies\n" ++ "[QWE] Scene | Time Step [X][x]: %.4f | Theta [A][a]: %.2f | " ++ "Threads [P][p]: %i" ) _rnbNumSteps (1 / avgtime) (avgtime * 1000) ( if np > 999 then show (np `div` 1000) ++ "K" else show np ) _rnbTimeStep _rnbTheta _rnbNumThreads experimentGLFWEvent ev = do case ev of GLFWEventKey _win k _sc ks mk | ks == GLFW.KeyState'Pressed -> case k of GLFW.Key'Q -> liftIO $ nbStableOrbits 10000 0.5 30.0 GLFW.Key'W -> liftIO $ nbRandomDisk 10000 GLFW.Key'E -> liftIO $ nbStableOrbits 5 5.0 40.0 GLFW.Key'X | GLFW.modifierKeysShift mk -> rnbTimeStep //= 2 | otherwise -> rnbTimeStep *= 2 GLFW.Key'A | GLFW.modifierKeysShift mk -> rnbTheta %= max 0.0 . min 0.95 . (\x -> x - 0.05) | otherwise -> rnbTheta %= max 0.0 . min 0.95 . (\x -> x + 0.05) GLFW.Key'P | GLFW.modifierKeysShift mk -> rnbNumThreads %= max 1 . min 16 . pred | otherwise -> rnbNumThreads %= max 1 . min 16 . succ _ -> return () _ -> return () foreign import ccall "nb_draw" nbDraw :: CInt -> CInt -> Ptr Word32 -> IO () foreign import ccall "nb_step_brute_force" _nbStepBruteForce :: CFloat -> IO () foreign import ccall "nb_step_barnes_hut" nbStepBarnesHut :: CFloat -> CFloat -> CInt -> IO () foreign import ccall "nb_random_disk" nbRandomDisk :: CInt -> IO () foreign import ccall "nb_stable_orbits" nbStableOrbits :: CInt -> CFloat -> CFloat -> IO () foreign import ccall "nb_num_particles" nbNumParticles :: IO CInt
blitzcode/rust-exp
hs-src/RustNBodyExperiment.hs
mit
4,666
0
19
2,023
1,017
518
499
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-subnetgroup.html module Stratosphere.Resources.ElastiCacheSubnetGroup where import Stratosphere.ResourceImports -- | Full data type definition for ElastiCacheSubnetGroup. See -- 'elastiCacheSubnetGroup' for a more convenient constructor. data ElastiCacheSubnetGroup = ElastiCacheSubnetGroup { _elastiCacheSubnetGroupCacheSubnetGroupName :: Maybe (Val Text) , _elastiCacheSubnetGroupDescription :: Val Text , _elastiCacheSubnetGroupSubnetIds :: ValList Text } deriving (Show, Eq) instance ToResourceProperties ElastiCacheSubnetGroup where toResourceProperties ElastiCacheSubnetGroup{..} = ResourceProperties { resourcePropertiesType = "AWS::ElastiCache::SubnetGroup" , resourcePropertiesProperties = hashMapFromList $ catMaybes [ fmap (("CacheSubnetGroupName",) . toJSON) _elastiCacheSubnetGroupCacheSubnetGroupName , (Just . ("Description",) . toJSON) _elastiCacheSubnetGroupDescription , (Just . ("SubnetIds",) . toJSON) _elastiCacheSubnetGroupSubnetIds ] } -- | Constructor for 'ElastiCacheSubnetGroup' containing required fields as -- arguments. elastiCacheSubnetGroup :: Val Text -- ^ 'ecsugDescription' -> ValList Text -- ^ 'ecsugSubnetIds' -> ElastiCacheSubnetGroup elastiCacheSubnetGroup descriptionarg subnetIdsarg = ElastiCacheSubnetGroup { _elastiCacheSubnetGroupCacheSubnetGroupName = Nothing , _elastiCacheSubnetGroupDescription = descriptionarg , _elastiCacheSubnetGroupSubnetIds = subnetIdsarg } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-subnetgroup.html#cfn-elasticache-subnetgroup-cachesubnetgroupname ecsugCacheSubnetGroupName :: Lens' ElastiCacheSubnetGroup (Maybe (Val Text)) ecsugCacheSubnetGroupName = lens _elastiCacheSubnetGroupCacheSubnetGroupName (\s a -> s { _elastiCacheSubnetGroupCacheSubnetGroupName = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-subnetgroup.html#cfn-elasticache-subnetgroup-description ecsugDescription :: Lens' ElastiCacheSubnetGroup (Val Text) ecsugDescription = lens _elastiCacheSubnetGroupDescription (\s a -> s { _elastiCacheSubnetGroupDescription = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-subnetgroup.html#cfn-elasticache-subnetgroup-subnetids ecsugSubnetIds :: Lens' ElastiCacheSubnetGroup (ValList Text) ecsugSubnetIds = lens _elastiCacheSubnetGroupSubnetIds (\s a -> s { _elastiCacheSubnetGroupSubnetIds = a })
frontrowed/stratosphere
library-gen/Stratosphere/Resources/ElastiCacheSubnetGroup.hs
mit
2,747
0
15
309
370
211
159
36
1
{- | Module : $Header$ Description : Helper functions for dealing with terms (mainly for pretty printing which is directly adapted from hollight) Copyright : (c) Jonathan von Schroeder, DFKI GmbH 2010 License : GPLv2 or higher, see LICENSE.txt Maintainer : jonathan.von_schroeder@dfki.de Stability : experimental Portability : portable -} module HolLight.Helper where import Data.Maybe (fromJust, isJust, catMaybes) import HolLight.Term import Data.List (union, (\\), find) import Common.Doc import Data.Char as Char names :: [String] names = let nextName [] = "a" nextName (x : xs) = if Char.ord x >= 122 then 'a' : nextName xs else Char.chr (Char.ord x + 1) : xs in iterate (reverse . nextName . reverse) "a" freeName :: [String] -> String freeName ns = head (filter (\ x -> case find (== x) ns of Nothing -> True _ -> False) names) fromRight :: Either t t1 -> t1 fromRight e = case e of Right t -> t Left _ -> error "fromRight" isPrefix :: Term -> Bool isPrefix tm = case tm of Var _ _ (HolTermInfo (Prefix, _)) -> True Const _ _ (HolTermInfo (Prefix, _)) -> True _ -> False ppPrintType :: HolType -> Doc ppPrintType = sot 0 soc :: String -> Bool -> [Doc] -> Doc soc sep' flag ss = if null ss then empty else let s = foldr1 (\ s1 s2 -> hcat [s1, text sep', s2]) ss in if flag then parens s else s sot :: Int -> HolType -> Doc sot pr ty = case (destVartype ty, destType ty) of -- exactly one of these is not Nothing (Just vtype, _) -> text vtype (_, Just t) -> case t of (con, []) -> text con ("fun", [ty1, ty2]) -> soc "->" (pr > 0) [sot 1 ty1, sot 0 ty2] ("sum", [ty1, ty2]) -> soc "+" (pr > 2) [sot 3 ty1, sot 2 ty2] ("prod", [ty1, ty2]) -> soc "#" (pr > 4) [sot 5 ty1, sot 4 ty2] ("cart", [ty1, ty2]) -> soc "^" (pr > 6) [sot 6 ty1, sot 7 ty2] (con, args) -> hcat [soc "," True (map (sot 0) args), text con] _ -> empty -- doesn't happen -- lib.ml revAssocd :: Eq t1 => t1 -> [(t, t1)] -> t -> t revAssocd a l d = case l of [] -> d (x, y) : t -> if y == a then x else revAssocd a t d -- fusion.ml destVar :: Term -> Maybe (String, HolType) destVar v = case v of Var s ty _ -> Just (s, ty) _ -> Nothing isVar :: Term -> Bool isVar v = isJust (destVar v) frees :: Term -> [Term] frees tm = case tm of Var _ _ _ -> [tm] Const _ _ _ -> [] Abs bv bod -> frees bod \\ [bv] Comb s t -> frees s `union` frees t vfreeIn :: Term -> Term -> Bool vfreeIn v tm = case tm of Abs bv bod -> v /= bv && vfreeIn v bod Comb s t -> vfreeIn v s || vfreeIn v t _ -> tm == v variant :: [Term] -> Term -> Maybe Term variant avoid v = if not (any (vfreeIn v) avoid) then Just v else case v of Var s ty p -> variant avoid (Var (s ++ "'") ty p) _ -> Nothing vsubst :: [(Term, Term)] -> Term -> Maybe Term vsubst = let vsubst' ilist tm = case tm of Var _ _ _ -> Just $ revAssocd tm ilist tm Const _ _ _ -> Just tm Comb s t -> case (vsubst' ilist s, vsubst ilist t) of (Just s', Just t') -> if s' == s && t' == t then Just tm else Just (Comb s' t') _ -> Nothing Abs v s -> let ilist' = filter (\ (_, x) -> x /= v) ilist in if ilist' == [] then Just tm else case vsubst ilist' s of Just s' | s' == s -> Just tm | any (\ (t, x) -> vfreeIn v t && vfreeIn x s) ilist' -> case variant [s'] v of Just v' -> case vsubst ((v', v) : ilist') s of Just t' -> Just (Abs v' t') _ -> Nothing _ -> Nothing | otherwise -> Just (Abs v s') _ -> Nothing in \ theta -> if theta == [] then Just else if all (\ (t, x) -> case (typeOf t, destVar x) of (Just t', Just (_, x')) -> t' == x' _ -> False) theta then vsubst' theta else (\ _ -> Nothing) destComb :: Term -> Maybe (Term, Term) destComb c = case c of Comb f x -> Just (f, x) _ -> Nothing isComb :: Term -> Bool isComb c = isJust (destComb c) destConst :: Term -> Maybe (String, HolType) destConst c = case c of Const s ty _ -> Just (s, ty) _ -> Nothing isConst :: Term -> Bool isConst c = isJust (destConst c) destAbs :: Term -> Maybe (Term, Term) destAbs a = case a of Abs v b -> Just (v, b) _ -> Nothing isAbs :: Term -> Bool isAbs a = isJust (destAbs a) rator :: Term -> Maybe Term rator tm = maybe Nothing (Just . fst) (destComb tm) rand :: Term -> Maybe Term rand tm = maybe Nothing (Just . snd) (destComb tm) splitlist :: (t -> Maybe (a, t)) -> t -> ([a], t) splitlist dest x = case dest x of Just (l, r) -> let (ls, res) = splitlist dest r in (l : ls, res) _ -> ([], x) revSplitlist :: (t -> Maybe (t, t1)) -> t -> (t, [t1]) revSplitlist dest x = let rsplist ls x' = case dest x' of Just (l, r) -> rsplist (r : ls) l _ -> (x', ls) in rsplist [] x typeOf :: Term -> Maybe HolType typeOf tm = case tm of Var _ ty _ -> Just ty Const _ ty _ -> Just ty Comb s _ -> case typeOf s of Just t -> case destType t of Just (_, _ : x1 : _) -> Just x1 _ -> Nothing _ -> Nothing Abs (Var _ ty _) t -> case typeOf t of Just t' -> Just (TyApp "fun" [ty, t']) _ -> Nothing _ -> Nothing destType :: HolType -> Maybe (String, [HolType]) destType a = case a of TyApp s ty -> Just (s, ty) _ -> Nothing destVartype :: HolType -> Maybe String destVartype t = case t of TyVar s -> Just s _ -> Nothing typeSubst :: [(HolType, HolType)] -> HolType -> HolType typeSubst i ty = case ty of TyApp tycon args -> let args' = map (typeSubst i) args in if args' == args then ty else TyApp tycon args' _ -> revAssocd ty i ty mkEq :: (Term, Term) -> Maybe Term mkEq (l, r) = case (typeOf l, mkConst ("=", [])) of (Just ty, Just eq) -> case inst [(ty, TyVar "A")] eq of Right eq_tm -> case mkComb (eq_tm, l) of Just m1 -> mkComb (m1, r) _ -> Nothing _ -> Nothing _ -> Nothing inst :: [(HolType, HolType)] -> Term -> Either Term Term inst = let inst' env tyin tm = case tm of Var n ty at -> let ty' = typeSubst tyin ty in let tm' = if ty' == ty then tm else Var n ty' at in if revAssocd tm' env tm == tm then Right tm' else Left tm' Const c ty at -> let ty' = typeSubst tyin ty in if ty' == ty then Right tm else Right (Const c ty' at) Comb f x -> case (inst' env tyin f, inst' env tyin x) of (Right f', Right x') -> if f' == f && x' == x then Right tm else Right (Comb f' x') (Left c, _) -> Left c (_, Left c) -> Left c Abs y t -> case inst' [] tyin y of Right y' -> let env' = (y, y') : env in case inst' env' tyin t of Right t' -> if y' == y && t' == t then Right tm else Right (Abs y' t') Left w' -> if w' /= y' then Left w' else let ifrees = map (fromRight . inst' [] tyin) (frees t) in case variant ifrees y' of Just y'' -> case (destVar y'', destVar y) of (Just (v1, _), Just (_, v2)) -> let z = (Var v1 v2 (HolTermInfo (Normal, Nothing))) in case vsubst [(z, y)] t of Just s -> inst' env tyin (Abs z s) _ -> Left w' _ -> Left w' _ -> Left w' _ -> Left tm in (\ tyin -> if tyin == [] then Right else inst' [] tyin) mkComb :: (Term, Term) -> Maybe Term mkComb (f, a) = case typeOf f of Just (TyApp "fun" [ty, _]) -> case typeOf a of Just t -> if ty == t then Just (Comb f a) else Nothing _ -> Nothing _ -> Nothing eqType :: HolType eqType = TyApp "fun" [ TyVar "A", TyApp "fun" [ TyVar "A", TyApp "bool" [] ]] mkConst :: (String, [(HolType, HolType)]) -> Maybe Term mkConst (name, theta) = if name == "=" then Just (Const name (typeSubst theta eqType) (HolTermInfo (InfixR 12, Nothing))) else Nothing -- basics.ml destBinder :: String -> Term -> Maybe (Term, Term) destBinder s tm = case tm of Comb (Const s' _ _) (Abs x t) -> if s' == s then Just (x, t) else Nothing _ -> Nothing destExists :: Term -> Maybe (Term, Term) destExists = destBinder "?" stripExists :: Term -> ([Term], Term) stripExists = splitlist destExists destForall :: Term -> Maybe (Term, Term) destForall = destBinder "!" stripForall :: Term -> ([Term], Term) stripForall = splitlist destForall stripComb :: Term -> (Term, [Term]) stripComb = revSplitlist destComb body :: Term -> Maybe Term body tm = case destAbs tm of Just (_, ret) -> Just ret _ -> Nothing destNumeral :: Term -> Maybe Integer destNumeral tm' = let dest_num tm = case destConst tm of Just ("_0", _) -> Just (toInteger (0 :: Int)) _ -> case destComb tm of Just (l, r) -> case dest_num r of Just i -> let n = toInteger (2 :: Int) * i in case destConst l of Just ("BIT0", _) -> Just n Just ("BIT1", _) -> Just (n + toInteger (1 :: Int)) _ -> Nothing _ -> Nothing _ -> Nothing in case destComb tm' of Just (l, r) -> case destConst l of Just ("NUMERAL", _) -> dest_num r _ -> Nothing _ -> Nothing destBinary' :: String -> Term -> Maybe (Term, Term) destBinary' s tm = case tm of Comb (Comb (Const s' _ _) l) r -> if s' == s then Just (l, r) else Nothing _ -> Nothing destCons :: Term -> Maybe (Term, Term) destCons = destBinary' "CONS" destList :: Term -> Maybe [Term] destList tm = let (tms, nil) = splitlist destCons tm in case destConst nil of Just ("NIL", _) -> Just tms _ -> Nothing destGabs :: Term -> Maybe (Term, Term) destGabs tm = let dest_geq = destBinary' "GEQ" in if isAbs tm then destAbs tm else case destComb tm of Just (l, r) -> case destConst l of Just ("GABS", _) -> case body r of Just b -> case dest_geq (snd (stripForall b)) of Just (ltm, rtm) -> case rand ltm of Just r' -> Just (r', rtm) _ -> Nothing _ -> Nothing _ -> Nothing _ -> Nothing _ -> Nothing isGabs :: Term -> Bool isGabs tm = isJust (destGabs tm) stripGabs :: Term -> ([Term], Term) stripGabs = splitlist destGabs destFunTy :: HolType -> Maybe (HolType, HolType) destFunTy ty = case ty of TyApp "fun" [ty1, ty2] -> Just (ty1, ty2) _ -> Nothing destLet :: Term -> Maybe ([(Term, Term)], Term) destLet tm = let (l, aargs) = stripComb tm in case (aargs, destConst l) of (a : as, Just ("LET", _)) -> let (vars, lebod) = stripGabs a in let eqs = zip vars as in case destComb lebod of Just (le, bod) -> case destConst le of Just ("LET_END", _) -> Just (eqs, bod) _ -> Nothing _ -> Nothing _ -> Nothing -- printer.ml nameOf :: Term -> String nameOf tm = case tm of Var x _ _ -> x Const x _ _ -> x _ -> "" -- printer.ml - pp_print_term reverseInterface :: (String, Term) -> (String, Maybe HolParseType) reverseInterface (s, tm) = case tm of Var _ _ ti -> case ti of HolTermInfo (_, Just (s'', pt)) -> (s'', Just pt) _ -> (s, Nothing) Const _ _ ti -> case ti of HolTermInfo (_, Just (s'', pt)) -> (s'', Just pt) _ -> (s, Nothing) _ -> (s, Nothing) destBinary :: Term -> Term -> Maybe (Term, Term) destBinary c tm = case destComb tm of -- original name: DEST_BINARY Just (il, r) -> case destComb il of Just (i, l) -> if (i == c) || (isConst i && isConst c && (fst (reverseInterface (fst (fromJust (destConst i)), i)) == fst (reverseInterface (fst (fromJust (destConst c)), i)))) then Just (l, r) else Nothing _ -> Nothing _ -> Nothing powerof10 :: Integer -> Bool powerof10 n = (10 * div n 10) == n boolOfTerm :: Term -> Maybe Bool boolOfTerm t = case t of Const "T" _ _ -> Just True Const "F" _ _ -> Just False _ -> Nothing codeOfTerm :: Num b => Term -> Maybe b codeOfTerm t = let (f, tms) = stripComb t in if not (isConst f && fst (fromJust (destConst f)) == "ASCII") || length tms /= 8 then Nothing else let bools = map boolOfTerm (reverse tms) in if not (any (Nothing ==) bools) then Just (foldr (\ b f' -> if b then 1 + 2 * f' else 2 * f') 0 (catMaybes bools)) else Nothing randRator :: Term -> Maybe Term randRator v = case rator v of Just v1 -> rand v1 _ -> Nothing destClause :: Term -> Maybe [Term] destClause tm = case maybe Nothing (Just . stripExists) (maybe Nothing body (body tm)) of Just (_, pbod) -> let (s, args) = stripComb pbod in case (nameOf s, length args) of ("_UNGUARDED_PATTERN", 2) -> case (randRator (head args), randRator (args !! 1)) of (Just _1, Just _2) -> Just [_1, _2] _ -> Nothing ("_GUARDED_PATTERN", 3) -> case (randRator (head args), randRator (args !! 2)) of (Just _1, Just _3) -> Just [_1, args !! 1, _3] _ -> Nothing _ -> Nothing _ -> Nothing destClauses :: Term -> Maybe [[Term]] destClauses tm = let (s, args) = stripComb tm in if nameOf s == "_SEQPATTERN" && length args == 2 then case destClauses (args !! 1) of Just cs -> case destClause (head args) of Just c -> Just (c : cs) _ -> Nothing _ -> Nothing else case destClause tm of Just c -> Just [c] _ -> Nothing aright :: Term -> Bool aright tm = case tm of Var _ _ (HolTermInfo (InfixR _, _)) -> True Const _ _ (HolTermInfo (InfixR _, _)) -> True _ -> False getPrec :: Term -> Int getPrec tm = case tm of Var _ _ (HolTermInfo (InfixR i, _)) -> i Const _ _ (HolTermInfo (InfixR i, _)) -> i _ -> 0 parsesAsBinder :: Term -> Bool parsesAsBinder tm = case tm of Var _ _ (HolTermInfo (Binder, _)) -> True Const _ _ (HolTermInfo (Binder, _)) -> True _ -> False canGetInfixStatus :: Term -> Bool canGetInfixStatus tm = case tm of Var _ _ (HolTermInfo (InfixR _, _)) -> True Var _ _ (HolTermInfo (InfixL _, _)) -> True Const _ _ (HolTermInfo (InfixR _, _)) -> True Const _ _ (HolTermInfo (InfixL _, _)) -> True _ -> False
nevrenato/Hets_Fork
HolLight/Helper.hs
gpl-2.0
18,314
332
22
8,398
6,419
3,419
3,000
420
18
module GraphTheory.Main where import Notes import Sets.Basics.Terms import GraphTheory.Macro import GraphTheory.Terms graphTheory :: Note graphTheory = chapter "Graph Theory" $ do graphDefinition graphDefinition :: Note graphDefinition = de $ do lab graphDefinitionLabel s ["A", graph', "is a tuple of two", sets, m grph_] itemize $ do item $ s [the, elements, "of", m vrt_, "are called", vertices'] item $ s [the, elements, "of", m edg_, "are called", edges']
NorfairKing/the-notes
src/GraphTheory/Main.hs
gpl-2.0
538
0
14
145
158
86
72
15
1
{-# LANGUAGE FlexibleContexts #-} module Fresh.InferMonad where import Control.Monad (when, foldM, forM) import Data.Map (Map) import qualified Data.Set as Set import Data.STRef import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.State (StateT(..)) import Control.Monad.State.Class (MonadState(..), modify) import Control.Monad.Trans.Either (EitherT(..)) import Control.Monad.Error.Class (MonadError(..)) import qualified Data.List as List import Control.Monad.ST (ST) import Data.Maybe (catMaybes, fromMaybe) import qualified Fresh.OrderedSet as OrderedSet import Fresh.Pretty (Pretty(..)) import Fresh.Types import Fresh.Expr import Fresh.Kind data InferState s = InferState { isContext :: Map EVarName (TypeVar (STRef s) (SType s)) , isGenFresh :: Int , isLevel :: Level } deriving Show type Infer s a = StateT (InferState s) (EitherT TypeError (ST s)) a getCurrentLevel :: Infer s Level getCurrentLevel = isLevel <$> get enterLevel :: Infer s () enterLevel = modify (\is -> is { isLevel = levelInc $ isLevel is }) leaveLevel :: Infer s () leaveLevel = modify (\is -> is { isLevel = levelDec $ isLevel is }) inLevel :: Infer s a -> Infer s a inLevel act = do enterLevel res <- act leaveLevel return res listUnion :: Ord a => [a] -> [a] -> [a] [] `listUnion` y = y x `listUnion` [] = x x `listUnion` y = OrderedSet.toList $ OrderedSet.fromList x `OrderedSet.concatUnion` OrderedSet.fromList y freshName :: Infer s Int freshName = do is <- get let genId = isGenFresh is put $ is { isGenFresh = genId + 1 } return genId -- TODO should return a set getUnbound :: Maybe Level -> SType s -> Infer s [TypeVar (STRef s) (SType s)] getUnbound mCurLevel (SType (TyVar tv)) = do v <- readVar tv case v of Unbound _ l -> case mCurLevel of Just curLevel | curLevel >= l -> pure [] _ -> pure [tv] Link t' -> getUnbound mCurLevel t' getUnbound mCurLevel (SType (TyAST t)) = concat <$> traverse (getUnbound mCurLevel) t mkGen :: [GenVar Level] -> [Pred (SType s)] -> SType s -> Infer s (SType s) mkGen gvs ps (SType (TyAST (TyGen gvs' (QualType ps2 t)))) = mkGen (gvs++gvs') (ps++ps2) t -- mkGen gvs ps touter@(SType (TyAST (TyAp t1@(SType (TyAST (TyAp (SType (TyAST (TyCon f))) arg))) (SType (TyAST (TyGen gvs' (QualType ps' t))))))) -- = do gvsArg <- liftST $ freeGenVars arg -- if (f == conFunc) && (OrderedSet.null $ gvsArg `OrderedSet.intersection` (OrderedSet.fromList gvs')) -- then mkGen (gvs++gvs') (ps++ps') (SType . TyAST $ TyAp t1 t) -- else return touter --mkGen gvs ps (SType (TyAST (TyAp t1 (SType (TyAST (TyGen gvs' (QualType ps2 t))))))) = mkGen (gvs++gvs') (ps++ps2) (SType (TyAST (TyAp t1 t))) mkGen [] [] t = return t mkGen gvs ps t = do freeGVs <-liftST $ freeGenVars (QualType ps t) when (not $ Set.fromList gvs `Set.isSubsetOf` OrderedSet.toSet freeGVs) $ throwError $ AssertionError $ "Non-existing GenVars appears in TyGen?! " ++ show gvs ++ " in type " ++ show t ++ ", freeGVs: " ++ show freeGVs return $ SType (TyAST (TyGen (OrderedSet.toList freeGVs) (QualType ps t))) mkGenQ :: [GenVar Level] -> [Pred (SType s)] -> SType s -> Infer s (QualType (SType s)) mkGenQ gvs ps t = do let gvsSet = OrderedSet.fromList gvs (psNotInT, psInT) <- partitionM (\p -> do gvsInP <- liftST (freeGenVars p) return $ OrderedSet.null $ gvsInP `OrderedSet.intersection` gvsSet) ps QualType psNotInT <$> mkGen gvs psInT t generalizeAtLevel :: [Pred (SType s)] -> SType s -> Maybe Level -> Infer s (QualType (SType s)) generalizeAtLevel ps t mCurLevel = do unboundTVarsT <- getUnbound mCurLevel t unboundTVarsPS <- concatMap fromPred <$> mapM (traverse $ getUnbound mCurLevel) ps let unboundTVars = unboundTVarsT ++ unboundTVarsPS let wrapGen tv@(TypeVar _ k) = do res <- readVar tv case res of Link (SType (TyAST (TyGenVar _))) -> return Nothing -- already overwritten Link _ -> error "Assertion failed" Unbound{} -> do gv <- GenVar <$> freshName <*> pure k <*> pure (fromMaybe LevelAny mCurLevel) writeVar tv (Link $ SType $ TyAST $ TyGenVar gv) return $ Just gv gvs <- catMaybes <$> mapM wrapGen unboundTVars mkGenQ gvs ps t generalize :: [Pred (SType s)] -> SType s -> Infer s (QualType (SType s)) generalize ps t = callFrame "generalize" $ getCurrentLevel >>= (generalizeAtLevel ps t . Just) instantiate :: SType s -> Infer s (QualType (SType s)) instantiate (SType (TyAST (TyGen gvs (QualType ps tGen)))) = callFrame "instantiate" $ do newGVs <- mapM (\(GenVar n k l) -> SType . TyVar <$> freshTVarK k) gvs let s = substGens gvs newGVs QualType <$> (mapM (traverse s) ps) <*> s tGen instantiate t@(SType (TyAST _)) = return $ QualType [] t instantiate t@(SType (TyVar tvar)) = do t' <- readVar tvar case t' of Unbound{} -> return $ QualType [] t -- TODO: Keep predicates on metavars? Link tLink -> instantiate tLink substGen :: GenVar Level -> SType s -> SType s -> Infer s (SType s) substGen gv tv t@(SType (TyVar tv')) = do t' <- readVar tv' case t' of Unbound{} -> return t Link tLink -> substGen gv tv tLink substGen gv tv t@(SType (TyAST tast)) = case tast of TyGenVar g -> return $ if g == gv then tv else t TyAp tf tx -> SType . TyAST <$> (TyAp <$> substGen gv tv tf <*> substGen gv tv tx) TyCon c -> return . SType . TyAST $ TyCon c TyGen gvs (QualType ps tGen') -> do let (shadowedGVs, rest) = List.partition (\sgv -> genVarId sgv == genVarId gv) gvs (newGVs, newTypes) <- unzip <$> forM shadowedGVs (\sgv -> do name <- freshName let sgv' = sgv { genVarId = name } return (sgv', SType . TyAST . TyGenVar $ sgv')) stGen' <- substGens shadowedGVs newTypes tGen' ps' <- mapM (traverse $ substGens shadowedGVs newTypes) ps mkGen (newGVs ++ rest) ps' stGen' TyComp c -> SType . TyAST . TyComp <$> traverse (substGen gv tv) c substGens :: [GenVar Level] -> [SType s] -> SType s -> Infer s (SType s) substGens vs ts t = foldM (\t' (v,s) -> substGen v s t') t $ zip vs ts fresh :: Infer s (STRef s (TVarLink t)) fresh = do curLevel <- getCurrentLevel name <- freshName lift . lift $ newSTRef $ Unbound name curLevel freshTVarK :: Kind -> Infer s (TypeVar (STRef s) a) freshTVarK k = do ref <- fresh return $ TypeVar ref k freshTVar :: Infer s (TypeVar (STRef s) a) freshTVar = freshTVarK Star freshRVar :: Infer s (TypeVar (STRef s) a) freshRVar = freshTVarK Composite liftST :: ST s a -> Infer s a liftST = lift . lift readVar :: TypeVar (STRef s) t -> Infer s (TVarLink t) readVar (TypeVar ref _) = liftST $ readSTRef ref writeVar :: TypeVar (STRef s) t -> TVarLink t -> Infer s () writeVar (TypeVar ref _) link = liftST $ writeSTRef ref link purifyVar :: TypeVar (STRef s) (SType s) -> Infer s PType purifyVar tvar@(TypeVar _ k) = do link <- readVar tvar case link of Unbound name l -> return . PType . TyVar $ TypeVar (PCell $ Unbound name l) k Link t -> purify t purify :: SType s -> Infer s PType purify (SType (TyVar tvar)) = purifyVar tvar purify (SType (TyAST t)) = PType . TyAST <$> traverse purify t resolve :: SType s -> Infer s (Maybe Type) resolve t@(SType (TyVar tvar)) = callFrame "resolve" $ do link <- readVar tvar case link of Unbound _name l -> do pt <- purify t throwError $ EscapedSkolemError $ "resolve " ++ show (pretty pt) ++ ", level: " ++ show l Link t' -> resolve t' resolve (SType (TyAST t)) = do mt <- traverse resolve t return $ fmap Fix $ sequenceA $ bimapTypeAST (const ()) id mt checkKind :: Maybe Kind -> Infer s Kind checkKind Nothing = throwError InvalidKind checkKind (Just k) = return k getKind :: HasKind t => t -> Infer s Kind getKind = checkKind . kind callFrame :: MonadError TypeError m => String -> m a -> m a callFrame s act = act `catchError` (\e -> throwError $ WrappedError (CallFrame s) e)
sinelaw/fresh
src/Fresh/InferMonad.hs
gpl-2.0
8,454
0
21
2,232
3,281
1,622
1,659
174
7
module PulseLambda.Error ( throwParsingError ) where import PulseLambda.Location throwParsingError :: Location -> String -> a throwParsingError loc str = error $! show loc ++ ": " ++ str
brunoczim/PulseLambda
PulseLambda/Error.hs
gpl-3.0
187
0
8
28
54
29
25
5
1
{- Copyright (c) 2014 Genome Research Ltd. Author: Nicholas A. Clarke <nicholas.clarke@sanger.ac.uk> 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 (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, see <http://www.gnu.org/licenses/>. -} {-# LANGUAGE DeriveGeneric #-} -- | Types and functions dealing with environment variables. module Tabula.Record.Environment (Env, EnvChange, diff, indifferentMerge) where import Control.Arrow ((***)) import Control.Monad (join) import Data.Aeson (FromJSON, ToJSON) import Data.List (foldl') import qualified Data.Map.Strict as Map import GHC.Generics (Generic) type Key = String type Value = String type Env = [(Key, Value)] data Delta = Insert Key Value | Delete Key | Modify Key Value Value deriving (Eq, Show, Generic) instance FromJSON Delta instance ToJSON Delta type EnvChange = [Delta] diff :: Env -> Env -> EnvChange diff from to = let map2 = join (***) (f,t) = map2 Map.fromList (from, to) insertions = map (uncurry Insert) . Map.assocs $ Map.difference t f deletions = map Delete . Map.keys $ Map.difference f t modifications = filter (\(Modify _ a b) -> a /= b) . Map.elems $ Map.intersectionWithKey Modify f t in insertions ++ deletions ++ modifications {- | Merge in changes to an environment to produce a new environment. Note that this version of merge is indifferent to whether the changes are actually appropriate to the environment they are being applied to: - A modify will work even if the old value is different from the one present, or there is no value present. - An insert will act as a modify if a value is already there. - A delete will not care if the value it's deleting does not exist. -} indifferentMerge :: EnvChange -> Env -> Env indifferentMerge changes old = Map.toList $ foldl' appDelta (Map.fromList old) changes where appDelta env (Insert key value) = Map.insert key value env appDelta env (Modify key _ value) = Map.insert key value env appDelta env (Delete key) = Map.delete key env
nc6/tabula
Tabula/Record/Environment.hs
gpl-3.0
2,641
0
15
602
481
262
219
33
3
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} module Api.Queue (resource) where import Control.Monad.Except import Data.String import Rest import qualified Rest.Resource as R import Api.Package (validatePackage) import Api.Root (Root) import Api.Types (PackageName, WithPackage) import Api.Utils import Queue (Create (..), Priority (..), QueueItem (..)) import qualified Queue as Q resource :: Resource Root WithPackage PackageName () Void resource = mkResourceReader { R.name = "queue" , R.schema = withListing () $ named [("name", singleBy fromString)] , R.list = const list , R.get = Just get , R.create = Just create , R.update = Just update , R.remove = Just remove } get :: Handler WithPackage get = mkIdHandler jsonO $ const handler where handler :: PackageName -> ExceptT Reason_ WithPackage QueueItem handler pkgName = (`orThrow` NotFound) . liftIO $ Q.get pkgName list :: ListHandler Root list = mkListing jsonO handler where handler :: Range -> ExceptT Reason_ Root [QueueItem] handler r = listRange r <$> liftIO Q.list create :: Handler Root create = mkInputHandler jsonI handler where handler :: Create -> ExceptT Reason_ Root () handler c = do secure validatePackage (cPackageName c) liftIO $ Q.add (cPackageName c) (cPriority c) update :: Handler WithPackage update = mkIdHandler (jsonO . jsonI) handler where handler :: Priority -> PackageName -> ExceptT Reason_ WithPackage QueueItem handler prio pkgName = do secure validatePackage pkgName (`orThrow` NotFound) . liftIO $ Q.update pkgName prio remove :: Handler WithPackage remove = mkIdHandler id $ const handler where handler :: PackageName -> ExceptT Reason_ WithPackage () handler pkgName = do secure void $ liftIO (Q.get pkgName) `orThrow` NotFound void $ liftIO $ Q.remove pkgName
imalsogreg/hackage-matrix-builder
src/Api/Queue.hs
gpl-3.0
2,102
0
14
591
623
330
293
52
1
module Lamdu.Sugar.Internal ( BodyU, ExpressionU , replaceWith ) where import Data.UUID.Types (UUID) import qualified Data.Store.Property as Property import Data.Store.Transaction (Transaction) import qualified Lamdu.Expr.IRef as ExprIRef import qualified Lamdu.Sugar.Internal.EntityId as EntityId import Lamdu.Sugar.Types type T = Transaction type BodyU m a = Body UUID m (ExpressionU m a) type ExpressionU m a = Expression UUID m a replaceWith :: Monad m => ExprIRef.ValIProperty m -> ExprIRef.ValIProperty m -> T m EntityId replaceWith parentP replacerP = do Property.set parentP replacerI return $ EntityId.ofValI replacerI where replacerI = Property.value replacerP
da-x/lamdu
Lamdu/Sugar/Internal.hs
gpl-3.0
757
0
9
173
197
114
83
20
1
module Main (main) where import Control.Concurrent (threadDelay) import Control.Exception import Control.Monad (replicateM, forever) import Data.Aeson import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy.Char8 as LB import Data.Default (Default(..)) import Data.List (find) import Data.Text (Text) import Data.Text.Encoding (encodeUtf8) import Data.Text.Format (left) import Data.Text.Format.Types (Hex(..)) import Data.Text.IO (getLine) import Data.Text.Lazy (toStrict) import Data.Text.Lazy.Builder (toLazyText) import Data.Time.LocalTime (getZonedTime) import Data.Typeable (Typeable) import Data.Word (Word8) import GHC.Generics (Generic) import Network.HTTP.Client import Network.HTTP.Client.TLS (tlsManagerSettings) import Network.Info import System.Directory (createDirectoryIfMissing) import System.Environment.XDG.BaseDir (getUserConfigFile) import System.FilePath (takeDirectory) import System.Random (Random(..)) main :: IO () main = do man <- newManager tlsManagerSettings cfg <- try readConfig cfg' <- case cfg of Left (ex :: IOException) -> do putStrLn ("Couldn't read config: " ++ show ex) setupNewConfig Right Nothing -> do putStrLn "Couldn't parse config." setupNewConfig Right (Just cfg'') -> return cfg'' case cfg' of Config {clientId, user, pass} -> forever $ do let exHandlers = [ Handler (\(ex :: HttpException) -> putStrLn $ "HTTP call failed: " ++ show ex), Handler (\(_ :: PIAForwardException) -> putStrLn "Couldn't get VPN IP address.")] flip catches exHandlers $ do mbVpnIP <- find ((== "tun0") . name) <$> getNetworkInterfaces vpnIP <- case mbVpnIP of Nothing -> throwIO CouldntGetIP Just vpnIP' -> return $ ipv4 vpnIP' let params = [ ("user", Just $ encodeUtf8 user), ("pass", Just $ encodeUtf8 pass), ("client_id", Just $ encodeUtf8 clientId), ("local_ip", Just (B.pack $ show vpnIP))] body = B.drop 1 $ queryString $ setQueryString params def let req = "https://www.privateinternetaccess.com/vpninfo/port_forward_assignment" {method = "POST", requestBody = RequestBodyBS body} time <- getZonedTime putStrLn $ "sending " ++ show body ++ " at " ++ show time resp <- httpLbs req man LB.putStrLn $ responseBody resp threadDelay $ 30*60*1000000 data PIAForwardException = CouldntGetIP deriving (Show, Typeable) instance Exception PIAForwardException setupNewConfig :: IO Config setupNewConfig = do bytes :: [Word8] <- replicateM 16 randomIO let clientId = toStrict $ toLazyText $ mconcat $ map (left 2 '0' . Hex) bytes putStrLn "Enter PIA username:" user <- Data.Text.IO.getLine putStrLn "Enter PIA password:" pass <- Data.Text.IO.getLine let cfg = Config {clientId, user, pass} writeConfig cfg return cfg data Config = Config {clientId :: Text, user :: Text, pass :: Text} deriving (Show, Generic) instance FromJSON Config instance ToJSON Config getConfigPath :: IO FilePath getConfigPath = getUserConfigFile "pia-forward" "config" writeConfig :: Config -> IO () writeConfig cfg = do configPath <- getConfigPath createDirectoryIfMissing True $ takeDirectory configPath LB.writeFile configPath (encode cfg) readConfig :: IO (Maybe Config) readConfig = decode <$> (getConfigPath >>= LB.readFile)
enolan/pia-forward
src/Main.hs
gpl-3.0
3,756
0
24
1,014
1,083
572
511
-1
-1
instance (Monoid w) => Monad (Writer w) where (Writer (a, w)) >>= k = let (a', w') = runWriter (k a) in Writer (a', w `mappend` w') return a = Writer (a, mempty)
hmemcpy/milewski-ctfp-pdf
src/content/3.5/code/haskell/snippet15.hs
gpl-3.0
197
0
12
68
106
55
51
4
0
{-# LANGUAGE TypeOperators #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE StandaloneDeriving #-} -- | This module defines a GADT `STTerm` that is the very core of this library -- -- Session typed programs are constructed by composing the constructors of `STTerm`. -- -- Each constructor is annotated with a specific session type (except for `Ret` and `Lift`). -- -- By passing a constructor to another constructor as an argument their session types are joined -- to form a larger session type. -- -- We do not recommend explicitly composing the `STTerm` constructors. Instead make use of the functions defined in the "Control.SessionTypes.MonadSession" module. -- -- Of course a `STTerm` program in itself is not very useful as it is devoid of any semantics. -- However, an interpreter function can give meaning to a `STTerm` program. -- -- We define a couple in this library: "Control.SessionTypes.Debug", "Control.SessionTypes.Interactive", "Control.SessionTypes.Normalize" and "Control.SessionTypes.Visualize". module Control.SessionTypes.STTerm ( STTerm (..), inferIdentity ) where import Control.SessionTypes.MonadSession import Control.SessionTypes.Types import qualified Control.SessionTypes.Indexed as I import Control.Monad.IO.Class import Data.Functor.Identity (Identity) import Data.Kind import Data.Typeable -- | The STTerm GADT -- -- Although we say that a `STTerm` is annotated with a session type, it is actually annotated with a capability (`Cap`). -- -- The capability contains a context that is necessary for recursion and the session type. -- -- The constructors can be split in four different categories: -- -- * Communication: `Send` and `Recv` for basic communication -- * Branching: `Sel1`, `Sel2`, `OffZ` and `OffS` -- * Recursion: `Rec`, `Weaken` and `Var` -- * Unsession typed: `Ret` and `Lift` data STTerm :: (Type -> Type) -> Cap a -> Cap a -> Type -> Type where -- | The constructor for sending messages. It is annotated with the send session type (`:!>`). -- -- It takes as an argument, the message to send, of type equal to the first argument of `:!>` and the continuing `STTerm` that is session typed with the second argument of `:!>`. Send :: a -> STTerm m ('Cap ctx r) r' b -> STTerm m ('Cap ctx (a :!> r)) r' b -- | The constructor for receiving messages. It is annotated with the receive session type (`:?>`) -- -- It takes a continuation that promises to deliver a value that may be used in the rest of the program. Recv :: (a -> STTerm m ('Cap ctx r) r' b) -> STTerm m ('Cap ctx (a :?> r)) r' b -- | Selects the first branch in a selection session type. -- -- By selecting a branch, that selected session type must then be implemented. Sel1 :: STTerm m ('Cap ctx s) r a -> STTerm m ('Cap ctx (Sel (s ': xs))) r a -- | Skips a branch in a selection session type. -- -- If the first branch in the selection session type is not the one we want to implement -- then we may use `Sel2` to skip this. Sel2 :: STTerm m ('Cap ctx (Sel (t ': xs))) r a -> STTerm m ('Cap ctx (Sel (s ': t ': xs))) r a -- | Dually to selection there is also offering branches. -- -- Unlike selection, where we may only implement one branch, an offering asks you to implement all branches. Which is chosen depends -- on how an interpreter synchronizes selection with offering. -- -- This constructor denotes the very last branch that may be offered. OffZ :: STTerm m ('Cap ctx s) r a -> STTerm m ('Cap ctx (Off '[s])) r a -- | offers a branch and promises at least one more branch to be offered. OffS :: STTerm m ('Cap ctx s) r a -> STTerm m ('Cap ctx (Off (t ': xs))) r a -> STTerm m ('Cap ctx (Off (s ': t ': xs))) r a -- | Constructor for delimiting the scope of recursion -- -- The recursion constructors also modify or at least make use of the context in the capability. -- -- The `Rec` constructor inserts the session type argument to `R` into the context of the capability of its `STTerm` argument. -- -- This is necessary such that we remember the session type of the body of code that we may want to recurse over and thus avoiding -- infinite type occurrence errors. Rec :: STTerm m ('Cap (s ': ctx) s) r a -> STTerm m ('Cap ctx (R s)) r a -- | Constructor for weakening (expanding) the scope of recusion -- -- This constructor does the opposite of `R` by popping a session type from the context. -- -- Use this constructor to essentially exit a recursion Weaken :: STTerm m ('Cap ctx t) r a -> STTerm m ('Cap (s ': ctx) (Wk t)) r a -- | Constructor that denotes the recursion variable -- -- It assumes the context to be non-empty and uses the session type at the top of the context to determine what should be implemented after `Var`. Var :: STTerm m ('Cap (s ': ctx) s) t a -> STTerm m ('Cap (s ': ctx) V) t a -- | Constructor that makes `STTerm` a (indexed) monad Ret :: (a :: Type) -> STTerm m s s a -- | Constructor that makes `STTerm` a (indexed) monad transformer Lift :: m (STTerm m s r a) -> STTerm m s r a deriving instance Typeable (STTerm m s r a) instance Functor (STTerm m s s) where fmap f (Ret a) = Ret $ f a instance Applicative (STTerm m s s) where pure x = Ret x (Ret f) <*> (Ret a) = Ret $ f a instance Monad (STTerm m s s) where return x = Ret x (Ret x) >>= f = f x instance Monad m => I.IxFunctor (STTerm m) where fmap f st = st I.>>= \a -> I.return $ f a instance Monad m => I.IxApplicative (STTerm m) where pure x = Ret x (<*>) = I.ap instance Monad m => I.IxMonad (STTerm m) where return x = Ret x (Send a r) >>= f = Send a (r I.>>= f) (Recv x) >>= f = Recv $ \c -> x c I.>>= f (Sel1 s) >>= f = Sel1 $ s I.>>= f (Sel2 xs) >>= f = Sel2 $ xs I.>>= f (OffZ s) >>= f = OffZ (s I.>>= f) (OffS s xs) >>= f = OffS (s I.>>= f) (xs I.>>= f) (Rec s) >>= f = Rec $ s I.>>= f (Var s) >>= f = Var $ s I.>>= f (Weaken s) >>= f = Weaken $ s I.>>= f (Lift m) >>= f = Lift $ do st <- m return $ st I.>>= f (Ret x) >>= f = f x instance Monad m => I.IxMonadT (STTerm) m where lift m = Lift $ m >>= return . Ret instance MonadIO m => I.IxMonadIO (STTerm m) where liftIO m = I.lift $ liftIO m instance Monad m => MonadSession (STTerm m) where send a = Send a (Ret ()) recv = Recv Ret sel1 = Sel1 $ Ret () sel2 = Sel2 $ Ret () offZ = OffZ offS = OffS recurse = Rec weaken = Weaken var = Var eps = Ret -- | This function can be used if we do not use `lift` in a program -- but we must still disambiguate `m`. inferIdentity :: STTerm Identity s r a -> STTerm Identity s r a inferIdentity = id
Ferdinand-vW/sessiontypes
src/Control/SessionTypes/STTerm.hs
gpl-3.0
6,850
0
15
1,584
1,708
896
812
75
1
module Game.Toliman.Graphical.UI ( module State, module Events, module Widgets, module Types ) where import Game.Toliman.Graphical.UI.State as State import Game.Toliman.Graphical.UI.Events as Events import Game.Toliman.Graphical.UI.Widgets as Widgets import Game.Toliman.Graphical.UI.Types as Types
duncanburke/toliman-graphical
src-lib/Game/Toliman/Graphical/UI.hs
mpl-2.0
312
0
4
42
66
51
15
9
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.DFAReporting.Placements.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) -- -- Gets one placement by ID. -- -- /See:/ <https://developers.google.com/doubleclick-advertisers/ Campaign Manager 360 API Reference> for @dfareporting.placements.get@. module Network.Google.Resource.DFAReporting.Placements.Get ( -- * REST Resource PlacementsGetResource -- * Creating a Request , placementsGet , PlacementsGet -- * Request Lenses , pgXgafv , pgUploadProtocol , pgAccessToken , pgUploadType , pgProFileId , pgId , pgCallback ) where import Network.Google.DFAReporting.Types import Network.Google.Prelude -- | A resource alias for @dfareporting.placements.get@ method which the -- 'PlacementsGet' request conforms to. type PlacementsGetResource = "dfareporting" :> "v3.5" :> "userprofiles" :> Capture "profileId" (Textual Int64) :> "placements" :> Capture "id" (Textual Int64) :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] Placement -- | Gets one placement by ID. -- -- /See:/ 'placementsGet' smart constructor. data PlacementsGet = PlacementsGet' { _pgXgafv :: !(Maybe Xgafv) , _pgUploadProtocol :: !(Maybe Text) , _pgAccessToken :: !(Maybe Text) , _pgUploadType :: !(Maybe Text) , _pgProFileId :: !(Textual Int64) , _pgId :: !(Textual Int64) , _pgCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PlacementsGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pgXgafv' -- -- * 'pgUploadProtocol' -- -- * 'pgAccessToken' -- -- * 'pgUploadType' -- -- * 'pgProFileId' -- -- * 'pgId' -- -- * 'pgCallback' placementsGet :: Int64 -- ^ 'pgProFileId' -> Int64 -- ^ 'pgId' -> PlacementsGet placementsGet pPgProFileId_ pPgId_ = PlacementsGet' { _pgXgafv = Nothing , _pgUploadProtocol = Nothing , _pgAccessToken = Nothing , _pgUploadType = Nothing , _pgProFileId = _Coerce # pPgProFileId_ , _pgId = _Coerce # pPgId_ , _pgCallback = Nothing } -- | V1 error format. pgXgafv :: Lens' PlacementsGet (Maybe Xgafv) pgXgafv = lens _pgXgafv (\ s a -> s{_pgXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pgUploadProtocol :: Lens' PlacementsGet (Maybe Text) pgUploadProtocol = lens _pgUploadProtocol (\ s a -> s{_pgUploadProtocol = a}) -- | OAuth access token. pgAccessToken :: Lens' PlacementsGet (Maybe Text) pgAccessToken = lens _pgAccessToken (\ s a -> s{_pgAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pgUploadType :: Lens' PlacementsGet (Maybe Text) pgUploadType = lens _pgUploadType (\ s a -> s{_pgUploadType = a}) -- | User profile ID associated with this request. pgProFileId :: Lens' PlacementsGet Int64 pgProFileId = lens _pgProFileId (\ s a -> s{_pgProFileId = a}) . _Coerce -- | Placement ID. pgId :: Lens' PlacementsGet Int64 pgId = lens _pgId (\ s a -> s{_pgId = a}) . _Coerce -- | JSONP pgCallback :: Lens' PlacementsGet (Maybe Text) pgCallback = lens _pgCallback (\ s a -> s{_pgCallback = a}) instance GoogleRequest PlacementsGet where type Rs PlacementsGet = Placement type Scopes PlacementsGet = '["https://www.googleapis.com/auth/dfatrafficking"] requestClient PlacementsGet'{..} = go _pgProFileId _pgId _pgXgafv _pgUploadProtocol _pgAccessToken _pgUploadType _pgCallback (Just AltJSON) dFAReportingService where go = buildClient (Proxy :: Proxy PlacementsGetResource) mempty
brendanhay/gogol
gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/Placements/Get.hs
mpl-2.0
4,777
0
19
1,180
821
474
347
112
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE RecordWildCards #-} module Commands.Reddit ( startrek, wcgw, meme, randomReddit, wallpaper ) where import Servant.API import Servant.Client import Control.Monad.IO.Class import Control.Monad.Random import Data.ByteString.Char8 (ByteString, pack) import Data.Proxy import Data.Maybe import Data.Monoid import Data.Response import Data.List (isPrefixOf) import Network.IRC import Network.HTTP.Client (Manager) import Data.Aeson import qualified Data.Vector as V newtype SubReddit = SubReddit String deriving (Eq, Show, Ord, ToHttpApiData) type RedditRandom = "r" :> Capture "subreddit" SubReddit :> Header "User-Agent" String :> "random" :> Get '[JSON] Reddit query :: Client RedditRandom query = client (Proxy :: Proxy RedditRandom) baseUrl :: BaseUrl baseUrl = BaseUrl Http "api.reddit.com" 80 "" data Reddit = Reddit { nsfw :: Bool, url :: String, title :: String } deriving (Show, Eq, Ord) instance FromJSON Reddit where parseJSON (Array v) = do let Object o0 = v V.! 0 Object o1 <- o0 .: "data" Array o2 <- o1 .: "children" let Object o3 = o2 V.! 0 Object o4 <- o3 .: "data" url <- o4 .: "url" nsfw <- o4 .: "over_18" title <- o4 .: "title" return Reddit{..} parseJSON o@(Object _) = parseJSON (Array (V.fromList [o])) parseJSON _ = fail "Error parsing Reddit data!" randomReddit :: MonadIO m => Bool -> Manager -> m SubReddit -> ByteString -> m (Response m) randomReddit showTitle man sub cmd = return $ simpleCmd' cmd go where go _ chan = do let uagent = Just "linux:tsahyt/lmrbot:v0.1.0 (by /u/tsahyt)" env = ClientEnv man baseUrl sub' <- sub res <- liftIO $ flip runClientM env $ query sub' uagent case res of Left _ -> return Nothing Right Reddit{..} -> let ret = if nsfw then "(NSFW!) " else mempty <> pack url <> if showTitle then " : " <> pack title else mempty in if forbidden url then go Nothing chan else return . Just $ privmsg (fromMaybe "" chan) ret forbidden url = "https://i.reddituploads.com" `isPrefixOf` url startrek :: MonadIO m => Manager -> m (Response m) startrek m = randomReddit True m (pure $ SubReddit "startrekgifs") ":startrek" wcgw :: MonadIO m => Manager -> m (Response m) wcgw m = randomReddit True m (pure $ SubReddit "whatcouldgowrong") ":wcgw" meme :: (MonadRandom m, MonadIO m) => Manager -> m (Response m) meme m = let subs = [ SubReddit "linuxmemes", SubReddit "windowsmemes" ] bound = pred $ V.length subs in randomReddit True m ((subs V.!) <$> getRandomR (0, bound)) ":meme" wallpaper :: (MonadRandom m, MonadIO m) => Manager -> m (Response m) wallpaper m = let subs = [ SubReddit "wallpapers", SubReddit "unixwallpapers" , SubReddit "widescreenwallpaper" ] bound = pred $ V.length subs in randomReddit False m ((subs V.!) <$> getRandomR (0, bound)) ":wallpaper"
tsahyt/lmrbot
src/Commands/Reddit.hs
agpl-3.0
3,499
1
20
1,035
1,065
545
520
87
5
module Gameboy.Assembler ( parseInstructions, encodeInstructions, assemble ) where import Prelude hiding (and, or) import Data.Maybe import Data.Char import Data.Word import Control.Monad import Text.Parsec import qualified Data.Vector.Unboxed as VU import Gameboy.Instructions data Register16 = AFRegister16 | BCRegister16 | DERegister16 | HLRegister16 | SPRegister16 deriving (Show) data Address = AtHL | AtC | AtBC | AtDE | AtNN Word16 | AtN Word8 deriving (Show) data Argument = RegisterArg Register | Register16Arg Register16 | AddressArg Address | I8Arg Word8 | I16Arg Word16 deriving (Show) hexToInt :: String -> Integer hexToInt = foldl (\a i -> a * 16 + fromIntegral (digitToInt i)) 0 spaces1 :: Parsec String st String spaces1 = many1 space immediate8 :: Parsec String st Word8 immediate8 = do _ <- char '$' digits <- count 2 hexDigit return $ fromIntegral $ hexToInt digits immediate16 :: Parsec String st Word16 immediate16 = do _ <- char '$' digits <- count 4 hexDigit return $ fromIntegral $ hexToInt digits registerArg :: Parsec String st Argument registerArg = a <|> b <|> c <|> d <|> e <|> h <|> l where a = char 'A' >> return (RegisterArg ARegister) b = char 'B' >> return (RegisterArg BRegister) c = char 'C' >> return (RegisterArg CRegister) d = char 'D' >> return (RegisterArg DRegister) e = char 'E' >> return (RegisterArg ERegister) h = char 'H' >> return (RegisterArg HRegister) l = char 'L' >> return (RegisterArg LRegister) register16Arg :: Parsec String st Argument register16Arg = af <|> bc <|> de <|> hl <|> sp where af = string "AF" >> return (Register16Arg AFRegister16) bc = string "BC" >> return (Register16Arg BCRegister16) de = string "DE" >> return (Register16Arg DERegister16) hl = string "HL" >> return (Register16Arg HLRegister16) sp = string "SP" >> return (Register16Arg SPRegister16) addressArg :: Parsec String st Argument addressArg = do _ <- char '(' r <- hl <|> c <|> bc <|> de <|> try nn <|> n _ <- char ')' return r where hl = string "HL" >> return (AddressArg AtHL) c = string "C" >> return (AddressArg AtC) bc = string "BC" >> return (AddressArg AtBC) de = string "DE" >> return (AddressArg AtDE) nn = AddressArg . AtNN <$> immediate16 n = AddressArg . AtN <$> immediate8 regularArg :: Parsec String st Argument regularArg = try addressArg <|> try (I16Arg <$> immediate16) <|> try (I8Arg <$> immediate8) <|> try register16Arg <|> registerArg bitArg :: Parsec String st Bit bitArg = b0 <|> b1 <|> b2 <|> b3 <|> b4 <|> b5 <|> b6 <|> b7 where b0 = char '0' >> return Bit0 b1 = char '1' >> return Bit1 b2 = char '2' >> return Bit2 b3 = char '3' >> return Bit3 b4 = char '4' >> return Bit4 b5 = char '5' >> return Bit5 b6 = char '6' >> return Bit6 b7 = char '7' >> return Bit7 condArg :: Parsec String st Cond condArg = z <|> c <|> try nz <|> nc where z = char 'Z' >> return Zero c = char 'C' >> return Carry nz = string "NZ" >> return NZero nc = string "NC" >> return NCarry instruction1Arg :: String -> Parsec String st a1 -> Parsec String st a1 instruction1Arg inst arg1 = do _ <- string inst >> spaces1 arg1 instruction2Arg :: String -> Parsec String st a1 -> Parsec String st a2 -> Parsec String st (a1, a2) instruction2Arg inst arg1 arg2 = do _ <- string inst >> spaces1 a1 <- arg1 _ <- spaces >> char ',' >> spaces a2 <- arg2 return (a1, a2) load8 :: Parsec String st Instruction load8 = do (t, s) <- instruction2Arg "LD" regularArg regularArg encode t s where encode (RegisterArg t) (RegisterArg s) = return $ LD_R_R t s encode (RegisterArg t) (AddressArg AtHL) = return $ LD_R_ATHL t encode (RegisterArg t) (I8Arg n) = return $ LD_R_N t n encode (AddressArg AtHL) (RegisterArg s) = return $ LD_ATHL_R s encode (AddressArg AtHL) (I8Arg n) = return $ LD_ATHL_N n encode (RegisterArg ARegister) (AddressArg AtC) = return LD_A_ATC encode (RegisterArg ARegister) (AddressArg AtBC) = return LD_A_ATBC encode (RegisterArg ARegister) (AddressArg AtDE) = return LD_A_ATDE encode (RegisterArg ARegister) (AddressArg (AtNN nn)) = return $ LD_A_ATNN nn encode (AddressArg AtC) (RegisterArg ARegister) = return LD_ATC_A encode (AddressArg AtBC) (RegisterArg ARegister) = return LD_ATBC_A encode (AddressArg AtDE) (RegisterArg ARegister) = return LD_ATDE_A encode (AddressArg (AtNN nn)) (RegisterArg ARegister) = return $ LD_ATNN_A nn encode _ _ = fail "Invalid LD instruction" load8dec :: Parsec String st Instruction load8dec = do (t, s) <- instruction2Arg "LDD" regularArg regularArg encode t s where encode (RegisterArg ARegister) (AddressArg AtHL) = return LDD_A_ATHL encode (AddressArg AtHL) (RegisterArg ARegister) = return LDD_ATHL_A encode _ _ = fail "Invalid LDD instruction" load8inc :: Parsec String st Instruction load8inc = do (t, s) <- instruction2Arg "LDI" regularArg regularArg encode t s where encode (RegisterArg ARegister) (AddressArg AtHL) = return LDI_A_ATHL encode (AddressArg AtHL) (RegisterArg ARegister) = return LDI_ATHL_A encode _ _ = fail "Invalid LDI instruction" loadh :: Parsec String st Instruction loadh = do (t, s) <- instruction2Arg "LDH" regularArg regularArg encode t s where encode (RegisterArg ARegister) (AddressArg (AtN n)) = return $ LDH_A_ATN n encode (AddressArg (AtN n)) (RegisterArg ARegister) = return $ LDH_ATN_A n encode _ _ = fail "Invalid LDH instruction" load16 :: Parsec String st Instruction load16 = do (t, s) <- instruction2Arg "LD" regularArg regularArg encode t s where encode (Register16Arg BCRegister16) (I16Arg nn) = return $ LD_BC_NN nn encode (Register16Arg DERegister16) (I16Arg nn) = return $ LD_DE_NN nn encode (Register16Arg HLRegister16) (I16Arg nn) = return $ LD_HL_NN nn encode (Register16Arg SPRegister16) (I16Arg nn) = return $ LD_SP_NN nn encode (Register16Arg SPRegister16) (Register16Arg HLRegister16) = return LD_SP_HL encode (AddressArg (AtNN nn)) (Register16Arg SPRegister16) = return $ LD_ATNN_SP nn encode _ _ = fail "Invalid LD instruction" loadhl :: Parsec String st Instruction loadhl = do (t, s) <- instruction2Arg "LDHL" regularArg regularArg encode t s where encode (Register16Arg SPRegister16) (I8Arg n) = return $ LDHL_SP_N (fromIntegral n) encode _ _ = fail "Invalid LDHL instruction" push :: Parsec String st Instruction push = instruction1Arg "PUSH" regularArg >>= encode where encode (Register16Arg AFRegister16) = return PUSH_AF encode (Register16Arg BCRegister16) = return PUSH_BC encode (Register16Arg DERegister16) = return PUSH_DE encode (Register16Arg HLRegister16) = return PUSH_HL encode _ = fail "Invalid PUSH instruction" pop :: Parsec String st Instruction pop = instruction1Arg "POP" regularArg >>= encode where encode (Register16Arg AFRegister16) = return POP_AF encode (Register16Arg BCRegister16) = return POP_BC encode (Register16Arg DERegister16) = return POP_DE encode (Register16Arg HLRegister16) = return POP_HL encode _ = fail "Invalid POP instruction" add :: Parsec String st Instruction add = do (t, s) <- instruction2Arg "ADD" regularArg regularArg encode t s where encode (RegisterArg ARegister) (RegisterArg r) = return $ ADD_A_R r encode (RegisterArg ARegister) (I8Arg n) = return $ ADD_A_N n encode (RegisterArg ARegister) (AddressArg AtHL) = return ADD_A_ATHL encode (Register16Arg HLRegister16) (Register16Arg BCRegister16) = return ADD_HL_BC encode (Register16Arg HLRegister16) (Register16Arg DERegister16) = return ADD_HL_DE encode (Register16Arg HLRegister16) (Register16Arg HLRegister16) = return ADD_HL_HL encode (Register16Arg HLRegister16) (Register16Arg SPRegister16) = return ADD_HL_SP encode (Register16Arg SPRegister16) (I8Arg n) = return $ ADD_SP_N (fromIntegral n) encode _ _ = fail "Invalid ADD instruction" adc :: Parsec String st Instruction adc = do (t, s) <- instruction2Arg "ADC" regularArg regularArg encode t s where encode (RegisterArg ARegister) (RegisterArg r) = return $ ADC_A_R r encode (RegisterArg ARegister) (I8Arg n) = return $ ADC_A_N n encode (RegisterArg ARegister) (AddressArg AtHL) = return ADC_A_ATHL encode _ _ = fail "Invalid ADC instruction" sub :: Parsec String st Instruction sub = instruction1Arg "SUB" regularArg >>= encode where encode (RegisterArg r) = return $ SUB_R r encode (I8Arg n) = return $ SUB_N n encode (AddressArg AtHL) = return SUB_ATHL encode _ = fail "Invalid SUB instruction" sbc :: Parsec String st Instruction sbc = do (t, s) <- instruction2Arg "SBC" regularArg regularArg encode t s where encode (RegisterArg ARegister) (RegisterArg r) = return $ SBC_A_R r encode (RegisterArg ARegister) (I8Arg n) = return $ SBC_A_N n encode (RegisterArg ARegister) (AddressArg AtHL) = return SBC_A_ATHL encode _ _ = fail "Invalid SBC instruction" and :: Parsec String st Instruction and = instruction1Arg "AND" regularArg >>= encode where encode (RegisterArg r) = return $ AND_R r encode (I8Arg n) = return $ AND_N n encode (AddressArg AtHL) = return AND_ATHL encode _ = fail "Invalid AND instruction" or :: Parsec String st Instruction or = instruction1Arg "OR" regularArg >>= encode where encode (RegisterArg r) = return $ OR_R r encode (I8Arg n) = return $ OR_N n encode (AddressArg AtHL) = return OR_ATHL encode _ = fail "Invalid OR instruction" xor :: Parsec String st Instruction xor = instruction1Arg "XOR" regularArg >>= encode where encode (RegisterArg r) = return $ XOR_R r encode (I8Arg n) = return $ XOR_N n encode (AddressArg AtHL) = return XOR_ATHL encode _ = fail "Invalid XOR instruction" cp :: Parsec String st Instruction cp = instruction1Arg "CP" regularArg >>= encode where encode (RegisterArg r) = return $ CP_R r encode (I8Arg n) = return $ CP_N n encode (AddressArg AtHL) = return CP_ATHL encode _ = fail "Invalid CP instruction" inc :: Parsec String st Instruction inc = instruction1Arg "INC" regularArg >>= encode where encode (RegisterArg r) = return $ INC_R r encode (AddressArg AtHL) = return INC_ATHL encode (Register16Arg BCRegister16) = return INC_BC encode (Register16Arg DERegister16) = return INC_DE encode (Register16Arg HLRegister16) = return INC_HL encode (Register16Arg SPRegister16) = return INC_SP encode _ = fail "Invalid INC instruction" dec :: Parsec String st Instruction dec = instruction1Arg "DEC" regularArg >>= encode where encode (RegisterArg r) = return $ DEC_R r encode (AddressArg AtHL) = return DEC_ATHL encode (Register16Arg BCRegister16) = return DEC_BC encode (Register16Arg DERegister16) = return DEC_DE encode (Register16Arg HLRegister16) = return DEC_HL encode (Register16Arg SPRegister16) = return DEC_SP encode _ = fail "Invalid DEC instruction" swap :: Parsec String st Instruction swap = instruction1Arg "SWAP" regularArg >>= encode where encode (RegisterArg r) = return $ SWAP_R r encode (AddressArg AtHL) = return SWAP_ATHL encode _ = fail "Invalid SWAP instruction" daa :: Parsec String st Instruction daa = string "DAA" >> return DAA cpl :: Parsec String st Instruction cpl = string "CPL" >> return CPL ccf :: Parsec String st Instruction ccf = string "CCF" >> return CCF scf :: Parsec String st Instruction scf = string "SCF" >> return SCF nop :: Parsec String st Instruction nop = string "NOP" >> return NOP halt :: Parsec String st Instruction halt = string "HALT" >> return HALT stop :: Parsec String st Instruction stop = string "STOP" >> return STOP di :: Parsec String st Instruction di = string "DI" >> return DI ei :: Parsec String st Instruction ei = string "EI" >> return EI rlca :: Parsec String st Instruction rlca = string "RLCA" >> return RLCA rla :: Parsec String st Instruction rla = string "RLA" >> return RLA rrca :: Parsec String st Instruction rrca = string "RRCA" >> return RRCA rra :: Parsec String st Instruction rra = string "RRA" >> return RRA rlc :: Parsec String st Instruction rlc = instruction1Arg "RLC" regularArg >>= encode where encode (RegisterArg r) = return $ RLC_R r encode (AddressArg AtHL) = return RLC_ATHL encode _ = fail "Invalid RLC instruction" rl :: Parsec String st Instruction rl = instruction1Arg "RL" regularArg >>= encode where encode (RegisterArg r) = return $ RL_R r encode (AddressArg AtHL) = return RL_ATHL encode _ = fail "Invalid RL instruction" rrc :: Parsec String st Instruction rrc = instruction1Arg "RRC" regularArg >>= encode where encode (RegisterArg r) = return $ RRC_R r encode (AddressArg AtHL) = return RRC_ATHL encode _ = fail "Invalid RRC instruction" rr :: Parsec String st Instruction rr = instruction1Arg "RR" regularArg >>= encode where encode (RegisterArg r) = return $ RR_R r encode (AddressArg AtHL) = return RR_ATHL encode _ = fail "Invalid RR instruction" sla :: Parsec String st Instruction sla = instruction1Arg "SLA" regularArg >>= encode where encode (RegisterArg r) = return $ SLA_R r encode (AddressArg AtHL) = return SLA_ATHL encode _ = fail "Invalid SLA instruction" sra :: Parsec String st Instruction sra = instruction1Arg "SRA" regularArg >>= encode where encode (RegisterArg r) = return $ SRA_R r encode (AddressArg AtHL) = return SRA_ATHL encode _ = fail "Invalid SRA instruction" srl :: Parsec String st Instruction srl = instruction1Arg "SRL" regularArg >>= encode where encode (RegisterArg r) = return $ SRL_R r encode (AddressArg AtHL) = return SRL_ATHL encode _ = fail "Invalid SRL instruction" bit :: Parsec String st Instruction bit = do (b, t) <- instruction2Arg "BIT" bitArg regularArg encode b t where encode b (RegisterArg r) = return $ BIT_B_R b r encode b (AddressArg AtHL) = return $ BIT_B_ATHL b encode _ _ = fail "Invalid BIT instruction" set :: Parsec String st Instruction set = do (b, t) <- instruction2Arg "SET" bitArg regularArg encode b t where encode b (RegisterArg r) = return $ SET_B_R b r encode b (AddressArg AtHL) = return $ SET_B_ATHL b encode _ _ = fail "Invalid SET instruction" res :: Parsec String st Instruction res = do (b, t) <- instruction2Arg "RES" bitArg regularArg encode b t where encode b (RegisterArg r) = return $ RES_B_R b r encode b (AddressArg AtHL) = return $ RES_B_ATHL b encode _ _ = fail "Invalid RES instruction" jp :: Parsec String st Instruction jp = try jp2 <|> jp1 where jp2 = do (c, a) <- instruction2Arg "JP" condArg regularArg enc2 c a jp1 = instruction1Arg "JP" regularArg >>= enc1 enc1 (I16Arg nn) = return $ JP_NN nn enc1 (AddressArg AtHL) = return JP_ATHL enc1 _ = fail "Invalid JP instruction" enc2 c (I16Arg nn) = return $ JP_C_NN c nn enc2 _ _ = fail "Invalid JP instruction" jr :: Parsec String st Instruction jr = try jr2 <|> jr1 where jr2 = do (c, a) <- instruction2Arg "JR" condArg regularArg enc2 c a jr1 = instruction1Arg "JR" regularArg >>= enc1 enc1 (I8Arg n) = return $ JR_N (fromIntegral n) enc1 _ = fail "Invalid JR instruction" enc2 c (I8Arg n) = return $ JR_C_N c (fromIntegral n) enc2 _ _ = fail "Invalid JR instruction" call :: Parsec String st Instruction call = try call2 <|> call1 where call2 = do (c, a) <- instruction2Arg "CALL" condArg immediate16 return $ CALL_C_NN c a call1 = CALL_NN <$> instruction1Arg "CALL" immediate16 rst :: Parsec String st Instruction rst = instruction1Arg "RST" immediate8 >>= encode where encode 0x00 = return $ RST_RA Reset00 encode 0x08 = return $ RST_RA Reset08 encode 0x10 = return $ RST_RA Reset10 encode 0x18 = return $ RST_RA Reset18 encode 0x20 = return $ RST_RA Reset20 encode 0x28 = return $ RST_RA Reset28 encode 0x30 = return $ RST_RA Reset30 encode 0x38 = return $ RST_RA Reset38 encode _ = fail "Invalid RST address" ret :: Parsec String st Instruction ret = try ret1 <|> ret0 where ret1 = RET_C <$> instruction1Arg "RET" condArg ret0 = string "RET" >> return RET reti :: Parsec String st Instruction reti = string "RETI" >> return RETI instruction :: Parsec String st Instruction instruction = try load8 <|> try load8dec <|> try load8inc <|> try loadhl <|> try load16 <|> try loadh <|> try push <|> try pop <|> try add <|> try adc <|> try sub <|> try sbc <|> try and <|> try or <|> try xor <|> try cp <|> try inc <|> try dec <|> try swap <|> try daa <|> try cpl <|> try ccf <|> try scf <|> try nop <|> try halt <|> try stop <|> try di <|> try ei <|> try rlca <|> try rla <|> try rrca <|> try rra <|> try rlc <|> try rl <|> try rrc <|> try rr <|> try sla <|> try sra <|> try srl <|> try bit <|> try set <|> try res <|> try jp <|> try jr <|> try call <|> try rst <|> try reti <|> ret comment :: Parsec String st () comment = do _ <- char ';' _ <- many (noneOf "\r\n") return () instructionLine :: Parsec String st (Maybe Instruction) instructionLine = do skipMany (oneOf " \t") mi <- optionMaybe instruction skipMany (oneOf " \t") optional comment return mi instructions :: Parsec String st [Instruction] instructions = do r <- liftM catMaybes $ instructionLine `sepBy1` endOfLine optional endOfLine eof return r parseInstructions :: String -> Either String [Instruction] parseInstructions input = case parse instructions "" input of Left err -> Left (show err) Right result -> Right result encodeInstructions :: [Instruction] -> VU.Vector Word8 encodeInstructions insts = VU.fromList <$> concat $ map encodeInstruction insts assemble :: String -> Either String (VU.Vector Word8) assemble text = do inst <- parseInstructions text return $ encodeInstructions inst
kyren/hsgb
lib/Gameboy/Assembler.hs
unlicense
18,206
0
52
4,053
6,609
3,177
3,432
466
14
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {- Copyright 2017 The CodeWorld Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} module Collaboration ( -- routes for simultaneous editing and adding user for collaboration into the project collabRoutes, ) where import Control.Monad.Trans import Data.Aeson import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as BC import qualified Data.Text as T import qualified Data.Text.Encoding as T import Snap.Core import System.FilePath import CollaborationUtil import DataUtil import Model import SnapUtil collabRoutes :: ClientId -> [(B.ByteString, Snap ())] collabRoutes clientId = [ ("addToCollaborate", addToCollaborateHandler clientId) , ("collabShare", collabShareHandler clientId) , ("listCurrentOwners", listCurrentOwnersHandler clientId) ] data ParamsGetType = GetFromHash | NotInCommentables deriving (Eq) getFrequentParams :: ParamsGetType -> ClientId -> Snap (User, BuildMode, FilePath) getFrequentParams getType clientId = do user <- getUser clientId mode <- getBuildMode case getType of NotInCommentables -> do Just path' <- fmap (splitDirectories . BC.unpack) <$> getParam "path" Just name <- getParam "name" let projectId = nameToProjectId $ T.decodeUtf8 name finalDir = joinPath $ map (dirBase . nameToDirId . T.pack) path' file = userProjectDir mode (userId user) </> finalDir </> projectFile projectId case (length path', path' !! 0) of (0, _) -> return (user, mode, file) (_, x) | x /= "commentables" -> return (user, mode, file) GetFromHash -> do Just collabHash <- fmap (CollabId . T.decodeUtf8) <$> getParam "collabHash" let collabHashPath = collabHashRootDir mode </> collabHashLink collabHash <.> "cw" return (user, mode, collabHashPath) addToCollaborateHandler :: ClientId -> Snap () addToCollaborateHandler clientId = do (user, mode, collabHashPath) <- getFrequentParams GetFromHash clientId Just path' <- fmap (splitDirectories . BC.unpack) <$> getParam "path" case length path' of x | x /= 0 && path' !! 0 == "commentables" -> do modifyResponse $ setContentType "text/plain" modifyResponse $ setResponseCode 404 writeBS . BC.pack $ "Cannot add a project to collaborate with in `commentables` directory." | otherwise -> do Just userIdent' <- fmap T.decodeUtf8 <$> getParam "userIdent" Just name <- getParam "name" let pathDir = joinPath $ map (dirBase . nameToDirId . T.pack) path' projectId = nameToProjectId . T.decodeUtf8 $ name filePath = userProjectDir mode (userId user) </> pathDir </> projectFile projectId res <- liftIO $ addForCollaboration mode (userId user) userIdent' name filePath collabHashPath case res of Left err -> do modifyResponse $ setContentType "text/plain" modifyResponse $ setResponseCode 404 writeBS . BC.pack $ err Right _ -> return () collabShareHandler :: ClientId -> Snap () collabShareHandler clientId = do (_, _, filePath) <- getFrequentParams NotInCommentables clientId collabHashFile <- liftIO $ takeFileName . BC.unpack <$> B.readFile filePath modifyResponse $ setContentType "text/plain" writeBS . BC.pack . take (length collabHashFile - 3) $ collabHashFile listCurrentOwnersHandler :: ClientId -> Snap () listCurrentOwnersHandler clientId = do (_, _, filePath) <- getFrequentParams NotInCommentables clientId collabHashPath <- liftIO $ BC.unpack <$> B.readFile filePath Just (currentUsers :: [UserDump]) <- liftIO $ decodeStrict <$> B.readFile (collabHashPath <.> "users") let currentOwners = map (T.unpack . uuserIdent) $ filter (\u -> utype u == "owner") currentUsers modifyResponse $ setContentType "application/json" writeLBS . encode $ currentOwners
parvmor/codeworld
codeworld-server/src/Collaboration.hs
apache-2.0
4,696
0
20
1,145
1,130
564
566
77
3
module Palindromes.A248122Spec (main, spec) where import Test.Hspec import Palindromes.A248122 (a248122) main :: IO () main = hspec spec spec :: Spec spec = describe "A248122" $ it "correctly computes the first 10 elements" $ take 10 (map a248122 [0..]) `shouldBe` expectedValue where expectedValue = [0,0,3,15,51,165,507,1551,4683,14127]
peterokagey/haskellOEIS
test/Palindromes/A248122Spec.hs
apache-2.0
353
0
10
59
130
75
55
10
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeOperators #-} -- | Implementation of the ethereum-analyzer API. module Ethereum.Analyzer.Web.Server.Handlers ( server ) where import Protolude import Control.Monad.Except (ExceptT(..)) import Control.Monad.Log (Severity, logInfo) import Ethereum.Analyzer.EVM import Ethereum.Analyzer.Web.API (API, DotCfgResp(..), RootPage(..), User(..), Users(..)) import qualified Ethereum.Analyzer.Web.Server.Logging as Log import Servant ((:<|>)(..), (:>), (:~>)(..), Raw, ServantErr, Server, enter) import Servant.Utils.StaticFiles (serveDirectory) import Text.PrettyPrint.Leijen.Text (Doc, Pretty, text) -- | ethereum-analyzer API implementation. server :: Severity -> Server (API :<|> "web" :> Raw) server logLevel = enter (toHandler logLevel) handlers :<|> serveDirectory "web" where handlers = pure RootPage :<|> users :<|> dotcfg :<|> dotcfg2 -- | Our custom handler type. type Handler msg = ExceptT ServantErr (Log.LogM msg IO) -- | Translate our custom monad into a Servant handler. -- -- See http://haskell-servant.readthedocs.io/en/stable/tutorial/Server.html#using-another-monad-for-your-handlers -- for the details. toHandler :: Pretty msg => Severity -> (Handler msg :~> ExceptT ServantErr IO) toHandler logLevel = Nat toHandler' where toHandler' :: Pretty msg => Handler msg a -> ExceptT ServantErr IO a toHandler' = ExceptT . Log.withLogging logLevel . runExceptT -- | Example endpoint. users :: Handler Doc Users users = do logInfo (text "Example of logging") pure (Users [User 1 "Isaac" "Newton", User 2 "Albert" "Einstein"]) dotcfg :: Maybe Text -> Handler Doc DotCfgResp dotcfg (Just t) = pure (DotCfgResp (disasmToDotText $ EvmHexString t) "") dotcfg _ = pure (DotCfgResp "" "") dotcfg2 :: Maybe Text -> Handler Doc DotCfgResp dotcfg2 (Just t) = pure (uncurry DotCfgResp $ disasmToDotText2 $ EvmHexString t) dotcfg2 _ = pure (DotCfgResp "" "")
zchn/ethereum-analyzer
ethereum-analyzer-webui/src/Ethereum/Analyzer/Web/Server/Handlers.hs
apache-2.0
1,992
0
11
317
566
316
250
38
1
module Braxton.A274701 (a274701) where import Braxton.A259280 (a259280) import Helpers.ListHelpers (firstDifferences) a274701 :: Int -> Integer a274701 n = a274701_list !! (n - 1) a274701_list :: [Integer] a274701_list = firstDifferences $ map a259280 [1..]
peterokagey/haskellOEIS
src/Braxton/A274701.hs
apache-2.0
260
0
7
35
84
48
36
7
1
module Arbitrary.Model where import Model.Types import Test.QuickCheck instance Arbitrary Side where arbitrary = elements [SLeft, SRight] instance Arbitrary PlayMode where arbitrary = do side <- arbitrary elements [ BeforeKickOff , PlayOn , TimeOver , KickOff side , KickIn side , FreeKick side , CornerKick side , GoalKick side , Goal side , DropBall , Offside side ]
klangner/splayer
test-src/Arbitrary/Model.hs
bsd-2-clause
584
0
10
272
118
63
55
19
0
-- -*- Mode: Haskell; -*- -- -- QuickCheck tests for Megaparsec's lexer. -- -- Copyright © 2015 Megaparsec contributors -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are -- met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- -- * 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 "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 holders 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 Lexer (tests) where import Control.Applicative (empty) import Control.Monad (void) import Data.Bool (bool) import Data.Char ( readLitChar , showLitChar , isDigit , isAlphaNum , isSpace , toLower ) import Data.List (findIndices, isInfixOf, find) import Data.Maybe (listToMaybe, maybeToList, isNothing, fromJust) import Numeric (showInt, showHex, showOct, showSigned) import Test.Framework import Test.Framework.Providers.QuickCheck2 (testProperty) import Test.QuickCheck import Text.Megaparsec.Error import Text.Megaparsec.Lexer import Text.Megaparsec.Pos import Text.Megaparsec.Prim import Text.Megaparsec.String import qualified Text.Megaparsec.Char as C import Util tests :: Test tests = testGroup "Lexer" [ testProperty "space combinator" prop_space , testProperty "symbol combinator" prop_symbol , testProperty "symbol' combinator" prop_symbol' , testProperty "indentGuard combinator" prop_indentGuard , testProperty "charLiteral" prop_charLiteral , testProperty "integer" prop_integer , testProperty "decimal" prop_decimal , testProperty "hexadecimal" prop_hexadecimal , testProperty "octal" prop_octal , testProperty "float 0" prop_float_0 , testProperty "float 1" prop_float_1 , testProperty "number" prop_number , testProperty "signed" prop_signed ] newtype WhiteSpace = WhiteSpace { getWhiteSpace :: String } deriving (Show, Eq) instance Arbitrary WhiteSpace where arbitrary = WhiteSpace . concat <$> listOf whiteUnit newtype Symbol = Symbol { getSymbol :: String } deriving (Show, Eq) instance Arbitrary Symbol where arbitrary = Symbol <$> ((++) <$> symbolName <*> whiteChars) whiteUnit :: Gen String whiteUnit = oneof [whiteChars, whiteLine, whiteBlock] whiteChars :: Gen String whiteChars = listOf $ elements "\t\n " whiteLine :: Gen String whiteLine = commentOut <$> arbitrary `suchThat` goodEnough where commentOut x = "//" ++ x ++ "\n" goodEnough x = '\n' `notElem` x whiteBlock :: Gen String whiteBlock = commentOut <$> arbitrary `suchThat` goodEnough where commentOut x = "/*" ++ x ++ "*/" goodEnough x = not $ "*/" `isInfixOf` x symbolName :: Gen String symbolName = listOf $ arbitrary `suchThat` isAlphaNum sc :: Parser () sc = space (void C.spaceChar) l b where l = skipLineComment "//" b = skipBlockComment "/*" "*/" sc' :: Parser () sc' = space (void $ C.oneOf " \t") empty empty prop_space :: WhiteSpace -> Property prop_space w = checkParser p r s where p = sc r = Right () s = getWhiteSpace w prop_symbol :: Symbol -> Maybe Char -> Property prop_symbol = parseSymbol (symbol sc) id prop_symbol' :: Symbol -> Maybe Char -> Property prop_symbol' = parseSymbol (symbol' sc) (fmap toLower) parseSymbol :: (String -> Parser String) -> (String -> String) -> Symbol -> Maybe Char -> Property parseSymbol p' f s' t = checkParser p r s where p = p' (f g) r | g == s || isSpace (last s) = Right g | otherwise = posErr (length s - 1) s [uneCh (last s), exEof] g = takeWhile (not . isSpace) s s = getSymbol s' ++ maybeToList t newtype IndLine = IndLine { getIndLine :: String } deriving (Show, Eq) instance Arbitrary IndLine where arbitrary = IndLine . concat <$> sequence [spc, sym, spc, eol] where spc = listOf (elements " \t") sym = return "xxx" eol = return "\n" prop_indentGuard :: IndLine -> IndLine -> IndLine -> Property prop_indentGuard l0 l1 l2 = checkParser p r s where p = ip (> 1) >>= \x -> sp >> ip (== x) >> sp >> ip (> x) >> sp ip = indentGuard sc' sp = void $ symbol sc' "xxx" <* C.eol r | f' l0 <= 1 = posErr 0 s msg' | f' l1 /= f' l0 = posErr (f l1 + g [l0]) s msg' | f' l2 <= f' l0 = posErr (f l2 + g [l0, l1]) s msg' | otherwise = Right () msg' = [msg "incorrect indentation"] f = length . takeWhile isSpace . getIndLine f' x = sourceColumn $ updatePosString defaultTabWidth (initialPos "") $ take (f x) (getIndLine x) g xs = sum $ length . getIndLine <$> xs s = concat $ getIndLine <$> [l0, l1, l2] prop_charLiteral :: String -> Bool -> Property prop_charLiteral t i = checkParser charLiteral r s where b = listToMaybe $ readLitChar s (h, g) = fromJust b r | isNothing b = posErr 0 s $ exSpec "literal character" : [ if null s then uneEof else uneCh (head s) ] | null g = Right h | otherwise = posErr l s [uneCh (head g), exEof] l = length s - length g s = if null t || i then t else showLitChar (head t) (tail t) prop_integer :: NonNegative Integer -> Int -> Property prop_integer n' i = checkParser integer r s where (r, s) = quasiCorrupted n' i showInt "integer" prop_decimal :: NonNegative Integer -> Int -> Property prop_decimal n' i = checkParser decimal r s where (r, s) = quasiCorrupted n' i showInt "decimal integer" prop_hexadecimal :: NonNegative Integer -> Int -> Property prop_hexadecimal n' i = checkParser hexadecimal r s where (r, s) = quasiCorrupted n' i showHex "hexadecimal integer" prop_octal :: NonNegative Integer -> Int -> Property prop_octal n' i = checkParser octal r s where (r, s) = quasiCorrupted n' i showOct "octal integer" prop_float_0 :: NonNegative Double -> Property prop_float_0 n' = checkParser float r s where n = getNonNegative n' r = Right n s = show n prop_float_1 :: Maybe (NonNegative Integer) -> Property prop_float_1 n' = checkParser float r s where r | isNothing n' = posErr 0 s [uneEof, exSpec "float"] | otherwise = posErr (length s) s [ uneEof, exCh '.', exCh 'E' , exCh 'e', exSpec "digit" ] s = maybe "" (show . getNonNegative) n' prop_number :: Either (NonNegative Integer) (NonNegative Double) -> Integer -> Property prop_number n' i = checkParser number r s where r | null s = posErr 0 s [uneEof, exSpec "number"] | otherwise = Right $ case n' of Left x -> Left $ getNonNegative x Right x -> Right $ getNonNegative x s = if i < 5 then "" else either (show . getNonNegative) (show . getNonNegative) n' prop_signed :: Integer -> Int -> Bool -> Property prop_signed n i plus = checkParser p r s where p = signed (hidden C.space) integer r | i > length z = Right n | otherwise = posErr i s $ uneCh '?' : (if i <= 0 then [exCh '+', exCh '-'] else []) ++ [exSpec $ bool "rest of integer" "integer" $ isNothing . find isDigit $ take i s] ++ [exEof | i > head (findIndices isDigit s)] z = let bar = showSigned showInt 0 n "" in if n < 0 || plus then bar else '+' : bar s = if i <= length z then take i z ++ "?" ++ drop i z else z quasiCorrupted :: NonNegative Integer -> Int -> (Integer -> String -> String) -> String -> (Either ParseError Integer, String) quasiCorrupted n' i shower l = (r, s) where n = getNonNegative n' r | i > length z = Right n | otherwise = posErr i s $ uneCh '?' : [ exEof | i > 0 ] ++ [if i <= 0 || null l then exSpec l else exSpec $ "rest of " ++ l] z = shower n "" s = if i <= length z then take i z ++ "?" ++ drop i z else z
neongreen/megaparsec
tests/Lexer.hs
bsd-2-clause
9,267
0
15
2,645
2,724
1,411
1,313
178
4
{-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- | -- Module : Web.Pagure.HookReceiver.Post -- Copyright : (C) 2015 Ricky Elrod -- License : BSD2 (see LICENSE file) -- Maintainer : Ricky Elrod <relrod@redhat.com> -- Stability : experimental -- Portability : ghc -- -- The POST hook receiver for Pagure projects. ---------------------------------------------------------------------------- module Web.Pagure.HookReceiver.Post where import Control.Monad.IO.Class import qualified Data.Map as M import qualified Data.Text as T import Shelly (rm_rf, fromText, shelly) import Web.Scotty runPagureListener :: Int -> M.Map String [String -> IO ()] -> IO () runPagureListener port projectMapping = scotty port $ post "/:projectname" $ do name <- param "projectname" case M.lookup name projectMapping of Nothing -> text "Project not found." Just hooks -> do let hooks' = fmap (\f -> f name) hooks liftIO (sequence_ hooks') shelly $ rm_rf (fromText (T.pack ("clones/" ++ name))) text "OK."
fedora-infra/pagure-hook-receiver
src/Web/Pagure/HookReceiver/Post.hs
bsd-2-clause
1,117
0
20
206
239
128
111
19
2