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
{- lat - tool to track alerts from LWN. - Copyright (C) 2010 Magnus Therning - - 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, version 3 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see <http://www.gnu.org/licenses/>. -} module Types where import Data.Maybe import Data.Time.Calendar --import Data.Time.Clock import Text.PrettyPrint.ANSI.Leijen data Distro = Distro { distroId :: Maybe Int -- ^ DB ID, automatically populated by the DB , distroName :: String , distroUrl :: Maybe String -- ^ URL to use for lookup, if it's 'Nothing' then @distroName@ will be used to construct the URL } deriving (Show, Eq) data Alert = Alert { alertId :: Maybe Int -- ^ DB ID, automatically populated by the DB , alertUrl :: [String] , alertIdentity :: String -- ^ identity as reported by LWN , alertPackage :: String , alertDate :: Day , alertProcessed :: Bool -- ^ record of whether the alert has been processed by lat before , alertDistro :: Distro } deriving (Show, Eq) distro = Distro Nothing alert = Alert Nothing getAlertDistroName :: Alert -> String getAlertDistroName = distroName . alertDistro -- | Class for pretty output of different levels of verbosity. class PrettyLevels a where prettyTerse :: a -> Doc prettyTerse = prettyNormal prettyNormal :: a -> Doc prettyVerbose :: a -> Doc prettyVerbose = prettyNormal instance PrettyLevels Distro where prettyNormal d = let name = pretty $ distroName d url = parens $ text $ fromMaybe "-" (distroUrl d) in name <> space <> url instance PrettyLevels Alert where prettyTerse a = let urls = foldl (<+>) empty . map text $ alertUrl a identity = text $ alertIdentity a package = text $ alertPackage a in identity <+> colon <+> package <+> colon <+> urls prettyNormal a = let urls = foldl (<+>) empty . map text $ alertUrl a identity = text $ alertIdentity a package = text $ alertPackage a date = pretty $ alertDate a processed = pretty $ alertProcessed a distro = prettyNormal $ alertDistro a in package <+> colon <+> identity <$> indent 2 (date <+> distro <+> processed <+> urls) instance Pretty Day where pretty = text . show
magthe/lat
src/Types.hs
gpl-3.0
2,806
0
13
737
525
282
243
50
1
module Data.Range where -- | VHDL Range type data RangeT = RangeT { rbegin :: Int , rend :: Int } | UnconstrT | NullRangeT deriving(Show) inner_of NullRangeT _ = True inner_of _ UnconstrT = True inner_of UnconstrT _ = False inner_of _ NullRangeT = False inner_of (RangeT b1 e1) (RangeT b2 e2) = (b1 >= b2) && (e1 <= e2) inrage :: Int -> RangeT -> Bool inrage x (RangeT l r) = x >= l && x <= r inrage x (UnconstrT) = True inrage x (NullRangeT) = False toList UnconstrT = error "toList: unable to make list out of unconstained range" toList (RangeT l u) = [l..u] toList (NullRangeT) = [] left (RangeT l _) = l left x = error $ "left: undefined for " ++ (show x) right (RangeT _ r) = r right x = error $ "right: undefined for " ++ (show x)
grwlf/vsim
src_r/Data/Range.hs
gpl-3.0
795
0
8
208
315
166
149
23
1
{-Key/Value pairs -} module KV where import Data.List (intercalate) import Data.List.Split (splitOn) type Pair = (String, String) data KVMap = KVMap [Pair] toJSON :: KVMap -> String toJSON (KVMap ps) = "{" ++ (intercalate "," (map (\(k,v) -> k ++ ": '" ++ v ++"'") ps)) ++"}" toCookie :: KVMap -> String toCookie (KVMap ps) = intercalate "&" [k ++ "=" ++ v | (k,v) <- ps] instance Show KVMap where show pairs = toJSON pairs newMap :: KVMap newMap = KVMap [] addPair :: KVMap -> Pair -> KVMap addPair (KVMap ps) p = KVMap (p:ps) ps = addPair (addPair newMap ("One", "First")) ("Two", "Second") parseCookie :: String -> KVMap parseCookie s = KVMap $ map firstTwo [splitOn "=" ps | ps <- splitOn "&" s] firstTwo :: [String] -> Pair firstTwo [] = ("","") firstTwo (x:[]) = (x, "") firstTwo (x:y:_) = (x,y) cookie = "foo=bar&baz=quux&zap=zazzle&snee"
CharlesRandles/cryptoChallenge
kv.hs
gpl-3.0
900
0
15
202
407
222
185
24
1
module Lecture5' (solveAndShow', genProblem', blockConstrnt) where import Data.List import System.Random import Lecture5NRC (blocksNRC) -- | Refactored code type Position = (Row,Column) type Constrnt = [[Position]] rowConstrnt, columnConstrnt, blockConstrnt, nrcConstrnt, allConstrnt :: Constrnt rowConstrnt = [[(r,c)| c <- values ] | r <- values ] columnConstrnt = [[(r,c)| r <- values ] | c <- values ] blockConstrnt = [[(r,c)| r <- b1, c <- b2 ] | b1 <- blocks, b2 <- blocks ] -- | Very easy to add some more constraints :) nrcConstrnt = [[(r,c)| r <- b1, c <- b2 ] | b1 <- blocksNRC, b2 <- blocksNRC ] allConstrnt = rowConstrnt ++ columnConstrnt ++ blockConstrnt ++ nrcConstrnt freeAtPos :: Sudoku -> Position -> Constrnt -> [Value] freeAtPos s (r,c) xs = let ys = filter (elem (r,c)) xs in foldl1 intersect (map ((values \\) . map s) ys) constraints :: Sudoku -> [Constraint] constraints s = sortBy length3rd [(r,c, freeAtPos s (r,c) allConstrnt) | (r,c) <- openPositions s ] consistent :: Sudoku -> Bool consistent s = all (constrntInjective s) allConstrnt -- | Check if a constraint is injective instead of a function per row, column, grid etc constrntInjective :: Sudoku -> [(Row,Column)] -> Bool constrntInjective s xs = injective xs prune :: (Row,Column,Value) -> [Constraint] -> [Constraint] prune _ [] = [] prune (r,c,v) ((x,y,zs):rest) | sameConstrnt (r,c) (x,y) = (x,y,zs\\[v]) : prune (r,c,v) rest | otherwise = (x,y,zs) : prune (r,c,v) rest -- | Use sameConstrnt instead of sameblock -- First filter the constraints to find the right constraint for the position. -- Next check if constraint matches sameConstrnt :: (Row,Column) -> (Row,Column) -> Bool sameConstrnt (r,c) (x,y) = any (elem (x,y)) $ filter (elem (r,c)) allConstrnt solveAndShow' :: Grid -> IO[()] solveAndShow' gr = solveShowNs (initNode gr) genProblem' :: Node -> IO Node genProblem' n = do ys <- randomize xs return (minimalize n ys) where xs = filledPositions (fst n) -- | Existing code from Lecture5.hs type Row = Int type Column = Int type Value = Int type Grid = [[Value]] positions, values :: [Int] positions = [1..9] values = [1..9] blocks :: [[Int]] blocks = [[1..3],[4..6],[7..9]] showVal :: Value -> String showVal 0 = " " showVal d = show d showRow :: [Value] -> IO() showRow [a1,a2,a3,a4,a5,a6,a7,a8,a9] = do putChar '|' ; putChar ' ' putStr (showVal a1) ; putChar ' ' putStr (showVal a2) ; putChar ' ' putStr (showVal a3) ; putChar ' ' putChar '|' ; putChar ' ' putStr (showVal a4) ; putChar ' ' putStr (showVal a5) ; putChar ' ' putStr (showVal a6) ; putChar ' ' putChar '|' ; putChar ' ' putStr (showVal a7) ; putChar ' ' putStr (showVal a8) ; putChar ' ' putStr (showVal a9) ; putChar ' ' putChar '|' ; putChar '\n' showGrid :: Grid -> IO() showGrid [as,bs,cs,ds,es,fs,gs,hs,is] = do putStrLn ("+-------+-------+-------+") showRow as; showRow bs; showRow cs putStrLn ("+-------+-------+-------+") showRow ds; showRow es; showRow fs putStrLn ("+-------+-------+-------+") showRow gs; showRow hs; showRow is putStrLn ("+-------+-------+-------+") type Sudoku = (Row,Column) -> Value sud2grid :: Sudoku -> Grid sud2grid s = [ [ s (r,c) | c <- [1..9] ] | r <- [1..9] ] grid2sud :: Grid -> Sudoku grid2sud gr = \ (r,c) -> pos gr (r,c) where pos :: [[a]] -> (Row,Column) -> a pos gr (r,c) = (gr !! (r-1)) !! (c-1) showSudoku :: Sudoku -> IO() showSudoku = showGrid . sud2grid bl :: Int -> [Int] bl x = concat $ filter (elem x) blocks subGrid :: Sudoku -> (Row,Column) -> [Value] subGrid s (r,c) = [ s (r',c') | r' <- bl r, c' <- bl c ] freeInSeq :: [Value] -> [Value] freeInSeq seq = values \\ seq freeInRow :: Sudoku -> Row -> [Value] freeInRow s r = freeInSeq [ s (r,i) | i <- positions ] freeInColumn :: Sudoku -> Column -> [Value] freeInColumn s c = freeInSeq [ s (i,c) | i <- positions ] freeInSubgrid :: Sudoku -> (Row,Column) -> [Value] freeInSubgrid s (r,c) = freeInSeq (subGrid s (r,c)) injective :: Eq a => [a] -> Bool injective xs = nub xs == xs rowInjective :: Sudoku -> Row -> Bool rowInjective s r = injective vs where vs = filter (/= 0) [ s (r,i) | i <- positions ] colInjective :: Sudoku -> Column -> Bool colInjective s c = injective vs where vs = filter (/= 0) [ s (i,c) | i <- positions ] subgridInjective :: Sudoku -> (Row,Column) -> Bool subgridInjective s (r,c) = injective vs where vs = filter (/= 0) (subGrid s (r,c)) extend :: Sudoku -> ((Row,Column),Value) -> Sudoku extend = update update :: Eq a => (a -> b) -> (a,b) -> a -> b update f (y,z) x = if x == y then z else f x type Constraint = (Row,Column,[Value]) type Node = (Sudoku,[Constraint]) showNode :: Node -> IO() showNode = showSudoku . fst solved :: Node -> Bool solved = null . snd extendNode :: Node -> Constraint -> [Node] extendNode (s,constraints) (r,c,vs) = [(extend s ((r,c),v), sortBy length3rd $ prune (r,c,v) constraints) | v <- vs ] initNode :: Grid -> [Node] initNode gr = let s = grid2sud gr in if (not . consistent) s then [] else [(s, constraints s)] openPositions :: Sudoku -> [(Row,Column)] openPositions s = [ (r,c) | r <- positions, c <- positions, s (r,c) == 0 ] length3rd :: (a,b,[c]) -> (a,b,[c]) -> Ordering length3rd (_,_,zs) (_,_,zs') = compare (length zs) (length zs') data Tree a = T a [Tree a] deriving (Eq,Ord,Show) exmple1 = T 1 [T 2 [], T 3 []] exmple2 = T 0 [exmple1,exmple1,exmple1] grow :: (node -> [node]) -> node -> Tree node grow step seed = T seed (map (grow step) (step seed)) count :: Tree a -> Int count (T _ ts) = 1 + sum (map count ts) takeT :: Int -> Tree a -> Tree a takeT 0 (T x _) = T x [] takeT n (T x ts) = T x $ map (takeT (n-1)) ts search :: (node -> [node]) -> (node -> Bool) -> [node] -> [node] search children goal [] = [] search children goal (x:xs) | goal x = x : search children goal xs | otherwise = search children goal ((children x) ++ xs) solveNs :: [Node] -> [Node] solveNs = search succNode solved succNode :: Node -> [Node] succNode (s,[]) = [] succNode (s,p:ps) = extendNode (s,ps) p solveShowNs :: [Node] -> IO[()] solveShowNs = sequence . fmap showNode . solveNs example1 :: Grid example1 = [[5,3,0,0,7,0,0,0,0], [6,0,0,1,9,5,0,0,0], [0,9,8,0,0,0,0,6,0], [8,0,0,0,6,0,0,0,3], [4,0,0,8,0,3,0,0,1], [7,0,0,0,2,0,0,0,6], [0,6,0,0,0,0,2,8,0], [0,0,0,4,1,9,0,0,5], [0,0,0,0,8,0,0,7,9]] example2 :: Grid example2 = [[0,3,0,0,7,0,0,0,0], [6,0,0,1,9,5,0,0,0], [0,9,8,0,0,0,0,6,0], [8,0,0,0,6,0,0,0,3], [4,0,0,8,0,3,0,0,1], [7,0,0,0,2,0,0,0,6], [0,6,0,0,0,0,2,8,0], [0,0,0,4,1,9,0,0,5], [0,0,0,0,8,0,0,7,9]] example3 :: Grid example3 = [[1,0,0,0,3,0,5,0,4], [0,0,0,0,0,0,0,0,3], [0,0,2,0,0,5,0,9,8], [0,0,9,0,0,0,0,3,0], [2,0,0,0,0,0,0,0,7], [8,0,3,0,9,1,0,6,0], [0,5,1,4,7,0,0,0,0], [0,0,0,3,0,0,0,0,0], [0,4,0,0,0,9,7,0,0]] example4 :: Grid example4 = [[1,2,3,4,5,6,7,8,9], [2,0,0,0,0,0,0,0,0], [3,0,0,0,0,0,0,0,0], [4,0,0,0,0,0,0,0,0], [5,0,0,0,0,0,0,0,0], [6,0,0,0,0,0,0,0,0], [7,0,0,0,0,0,0,0,0], [8,0,0,0,0,0,0,0,0], [9,0,0,0,0,0,0,0,0]] example5 :: Grid example5 = [[1,0,0,0,0,0,0,0,0], [0,2,0,0,0,0,0,0,0], [0,0,3,0,0,0,0,0,0], [0,0,0,4,0,0,0,0,0], [0,0,0,0,5,0,0,0,0], [0,0,0,0,0,6,0,0,0], [0,0,0,0,0,0,7,0,0], [0,0,0,0,0,0,0,8,0], [0,0,0,0,0,0,0,0,9]] emptyN :: Node emptyN = (\ _ -> 0,constraints (\ _ -> 0)) getRandomInt :: Int -> IO Int getRandomInt n = getStdRandom (randomR (0,n)) getRandomItem :: [a] -> IO [a] getRandomItem [] = return [] getRandomItem xs = do n <- getRandomInt maxi return [xs !! n] where maxi = length xs - 1 randomize :: Eq a => [a] -> IO [a] randomize xs = do y <- getRandomItem xs if null y then return [] else do ys <- randomize (xs\\y) return (head y:ys) sameLen :: Constraint -> Constraint -> Bool sameLen (_,_,xs) (_,_,ys) = length xs == length ys getRandomCnstr :: [Constraint] -> IO [Constraint] getRandomCnstr cs = getRandomItem (f cs) where f [] = [] f (x:xs) = takeWhile (sameLen x) (x:xs) rsuccNode :: Node -> IO [Node] rsuccNode (s,cs) = do xs <- getRandomCnstr cs if null xs then return [] else return (extendNode (s,cs\\xs) (head xs)) rsolveNs :: [Node] -> IO [Node] rsolveNs ns = rsearch rsuccNode solved (return ns) rsearch :: (node -> IO [node]) -> (node -> Bool) -> IO [node] -> IO [node] rsearch succ goal ionodes = do xs <- ionodes if null xs then return [] else if goal (head xs) then return [head xs] else do ys <- rsearch succ goal (succ (head xs)) if (not . null) ys then return [head ys] else if null (tail xs) then return [] else rsearch succ goal (return $ tail xs) genRandomSudoku :: IO Node genRandomSudoku = do [r] <- rsolveNs [emptyN] return r randomS = genRandomSudoku >>= showNode uniqueSol :: Node -> Bool uniqueSol node = singleton (solveNs [node]) where singleton [] = False singleton [x] = True singleton (x:y:zs) = False eraseS :: Sudoku -> (Row,Column) -> Sudoku eraseS s (r,c) (x,y) | (r,c) == (x,y) = 0 | otherwise = s (x,y) eraseN :: Node -> (Row,Column) -> Node eraseN n (r,c) = (s, constraints s) where s = eraseS (fst n) (r,c) minimalize :: Node -> [(Row,Column)] -> Node minimalize n [] = n minimalize n ((r,c):rcs) | uniqueSol n' = minimalize n' rcs | otherwise = minimalize n rcs where n' = eraseN n (r,c) filledPositions :: Sudoku -> [(Row,Column)] filledPositions s = [ (r,c) | r <- positions, c <- positions, s (r,c) /= 0 ] -- main :: IO () -- main = do [r] <- rsolveNs [emptyN] -- showNode r -- s <- genProblem r -- showNode s
vdweegen/UvA-Software_Testing
Lab5/Final/Lecture5'.hs
gpl-3.0
10,707
0
16
3,025
5,643
3,193
2,450
272
5
module Hython.BuiltinTypes.Dict where import qualified Data.IntMap as IntMap import Hython.Ref import Hython.Types dictNew :: MonadInterpreter m => m Object dictNew = do r <- newRef IntMap.empty return $ Dict r dictClear :: MonadInterpreter m => DictRef -> m Object dictClear ref = do writeRef ref IntMap.empty return None dictContains :: MonadInterpreter m => DictRef -> Object -> m Object dictContains ref obj = do dict <- readRef ref key <- hash obj newBool $ key `IntMap.member` dict dictDel :: MonadInterpreter m => DictRef -> Object -> m Object dictDel ref obj = do key <- hash obj modifyRef ref $ \m -> IntMap.delete key m return None dictGet :: MonadInterpreter m => DictRef -> Object -> m Object dictGet ref obj = do dict <- readRef ref key <- hash obj case IntMap.lookup key dict of Just (_, v) -> return v Nothing -> do raise "KeyError" "key not found" return None dictItems :: MonadInterpreter m => DictRef -> m Object dictItems ref = do dict <- readRef ref items <- mapM unwrap (IntMap.elems dict) newList items where unwrap (key, value) = newTuple [key, value] dictLength :: MonadInterpreter m => DictRef -> m Object dictLength ref = newInt . fromIntegral . IntMap.size =<< readRef ref dictSet :: MonadInterpreter m => DictRef -> Object -> Object -> m Object dictSet ref key value = do hashed <- hash key modifyRef ref $ \m -> IntMap.insert hashed (key, value) m return None
mattgreen/hython
src/Hython/BuiltinTypes/Dict.hs
gpl-3.0
1,554
0
12
405
571
269
302
44
2
-- -*-haskell-*- -- Vision (for the Voice): an XMMS2 client. -- -- Author: Oleg Belozeorov -- Created: 12 Jul. 2010 -- -- Copyright (C) 2010, 2011 Oleg Belozeorov -- -- 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. -- {-# LANGUAGE TupleSections, DeriveDataTypeable, Rank2Types #-} {-# OPTIONS_GHC -fno-warn-incomplete-patterns #-} module Properties.Impex ( initImpex , showPropertyExport , showPropertyImport ) where import Prelude hiding (catch) import Control.Exception import System.IO.Error (ioeGetErrorString) import Control.Applicative import Control.Monad import Control.Monad.Fix import Control.Monad.Trans import Control.Concurrent.MVar import Data.Char import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe import Data.List import Data.Typeable import Data.Env import Codec.Binary.UTF8.String import System.FilePath import System.IO.Unsafe import Text.JSON import Graphics.UI.Gtk import XMMS2.Client hiding (Property) import qualified XMMS2.Client as X import UI import Registry import Medialib import Utils import XMMS data Ix = Ix deriving (Typeable) data Impex = Impex { _export :: WithUI => [MediaId] -> IO () , _import :: WithUI => IO () } deriving (Typeable) showPropertyImport :: (WithRegistry, WithUI) => IO () showPropertyImport = do Just (Env impex) <- getEnv (Extract :: Extract Ix Impex) _import impex showPropertyExport :: (WithRegistry, WithUI) => [MediaId] -> IO () showPropertyExport ids = do Just (Env impex) <- getEnv (Extract :: Extract Ix Impex) _export impex ids initImpex :: (WithMedialib, WithXMMS, WithRegistry) => IO () initImpex = do impex <- mkImpex addEnv Ix impex mkImpex :: (WithMedialib, WithXMMS) => IO Impex mkImpex = do exportDlg <- unsafeInterleaveIO makeExportDlg importDlg <- unsafeInterleaveIO makeImportDlg return Impex { _export = \ids -> runChooser exportDlg (exportProps ids) , _import = runChooser importDlg importProps } makeExportDlg :: IO Chooser makeExportDlg = makeChooser "Export properties" FileChooserActionSave stockSave exportProps :: (WithMedialib, WithUI) => [MediaId] -> String -> IO (IO ()) exportProps ids file = retrieveProperties ids $ either (const $ return ()) $ \list -> do let base = dropFileName $ decodeString file text = encodeStrict $ showJSON $ map (exConv base . snd) list writeFile file text `catch` \e -> informUser MessageError $ "Property export failed: " ++ (decodeString file) ++ ": " ++ ioeGetErrorString e exConv :: String -> Map String X.Property -> ((String, String), Map String X.Property) exConv base info = ((url', args), Map.difference info readOnlyProps) where url' = stripBase $ decodeURL path (path, args) = break (== '?') url X.PropString url = fromJust $ Map.lookup "url" info stripBase url | Just path <- stripPrefix "file://" url , Just tail <- stripPrefix base path = tail | otherwise = url readOnlyProps :: Map String X.Property readOnlyProps = Map.fromList $ map (, undefined) [ "added", "bitrate", "chain", "channels", "duration" , "id", "laststarted", "lmod", "mime", "sample_format" , "samplerate", "size", "status", "timesplayed", "url" , "startms", "stopms", "isdir", "intsort" ] makeImportDlg :: IO Chooser makeImportDlg = makeChooser "Import properties" FileChooserActionOpen stockOpen importProps :: (WithXMMS, WithUI) => String -> IO () importProps name = importAll `catch` (erep . ioeGetErrorString) where importAll = do text <- readFile name case decodeStrict text of Ok recs -> mapM_ (importOne base) recs Error _ -> erep "invalid file format" base = dropFileName decn decn = decodeString name erep = informUser MessageError . (("Property import failed: " ++ decn ++ ": ") ++) importOne :: WithXMMS => FilePath -> ((String, String), Map String X.Property) -> IO () importOne base ((url, args), props) = medialibAddEntryEncoded xmms enc >>* do liftIO $ medialibGetIdEncoded xmms enc >>* do id <- result unless (id == 0) $ liftIO $ setProps id props where enc = (encodeURL url') ++ args url' | isInfixOf "://" url = url | otherwise = "file://" ++ joinPath [base, url] setProps :: WithXMMS => MediaId -> Map String X.Property -> IO () setProps id props = mapM_ set $ Map.toList props where set (k, v) = medialibEntryPropertySet xmms id src k v src = Just "client/generic/override/vision" data Chooser = Chooser { cLock :: MVar () , cChooser :: FileChooserDialog } makeChooser :: String -> FileChooserAction -> String -> IO Chooser makeChooser title action stockId = do lock <- newMVar () chooser <- fileChooserDialogNew (Just title) Nothing action [ (stockCancel, ResponseCancel) , (stockId, ResponseAccept) ] hideOnDeleteEvent chooser filter <- fileFilterNew fileFilterSetName filter "Vision property files" fileFilterAddCustom filter [FileFilterFilename] $ \name _ _ _ -> return $ maybe False ((==) ".vpf" . map toLower . takeExtension) name fileChooserAddFilter chooser filter filter <- fileFilterNew fileFilterSetName filter "All files" fileFilterAddCustom filter [] $ \_ _ _ _ -> return True fileChooserAddFilter chooser filter return Chooser { cLock = lock , cChooser = chooser } runChooser :: WithUI => Chooser -> (FilePath -> IO b) -> IO () runChooser Chooser { cLock = lock, cChooser = chooser } onAccept = do locked <- isJust <$> tryTakeMVar lock when locked $ do windowSetTransientFor chooser window void $ mfix $ \cid -> chooser `onResponse` \resp -> do signalDisconnect cid case resp of ResponseAccept -> do name <- fileChooserGetFilename chooser withJust name onAccept _ -> return () widgetHide chooser putMVar lock () windowPresent chooser instance JSON X.Property where showJSON (X.PropInt32 i) = showJSON i showJSON (X.PropString s) = showJSON s readJSON (JSRational _ i) = return $ X.PropInt32 $ truncate i readJSON (JSString s) = return $ X.PropString $ fromJSString s
upwawet/vision
src/Properties/Impex.hs
gpl-3.0
6,871
0
22
1,623
1,975
1,018
957
-1
-1
{-# LANGUAGE UnicodeSyntax #-} {-# LANGUAGE OverloadedStrings #-} module Game.Osu.OszLoader.OsuParser.EditorSpec (spec) where import Data.Attoparsec.Text import Data.Text import Game.Osu.OszLoader.OsuParser.Editor import Game.Osu.OszLoader.Types import Test.Hspec import Test.QuickCheck editorSample ∷ Text editorSample = Data.Text.concat [ "[Editor]\n" , "Bookmarks: 18297,29658,23365,24758,25289,25696,25925\n" , "DistanceSpacing: 1\n" , "BeatDivisor: 4\n" , "GridSize: 8\n" ] numProp ∷ (Show a, Eq a) ⇒ Parser a → Text → Positive a → Expectation numProp p t (Positive x) = parseOnly p tx `shouldBe` Right x where tx = t `append` pack (show x) spec ∷ Spec spec = do describe "Editor section" $ do it "can parse the provided sample" $ do parseOnly editorSection editorSample `shouldBe` Right (Editor { _bookmarks = [18297,29658,23365,24758,25289,25696,25925] , _distanceSpacing = 1.0 , _beatDivisor = 4 , _gridSize = 8 , _timelineZoom = Nothing}) context "subparsers" $ do it "bookmarksP" . property $ \xs → let ns = Prelude.map getPositive xs ys = Prelude.map (pack . show) ns zs = intercalate "," ys in parseOnly bookmarksP ("Bookmarks: " `append` zs) `shouldBe` Right ns it "distanceSpacingP" . property $ numProp distanceSpacingP "DistanceSpacing: " it "beatDivisorP" . property $ numProp beatDivisorP "BeatDivisor: " it "gridSizeP" . property $ numProp gridSizeP "GridSize: " it "timelineZoomP" . property $ numProp timelineZoomP "TimelineZoom: "
Fuuzetsu/osz-loader
test/Game/Osu/OszLoader/OsuParser/EditorSpec.hs
gpl-3.0
1,701
0
21
433
453
242
211
42
1
{-# LANGUAGE FlexibleInstances #-} -- The purpose of ShowADL is to print things in Ampersand source format. -- Rule: The semantics of each fSpec produced by the compiler is identical to the semantics of (parse (showADL fSpec)). -- Rule: The standard show is used only for simple error messages during testing. -- Question (SJC): If STRING is the code produced by showADL, would STRING == showADL (parse STRING) (context (parse STRING)) be true? -- Answer (SJ): No, not for every STRING. Yet, for every fSpec we want semantics fSpec == semantics (parse (showADL fSpec)). -- Note that 'parse' and 'semantics' do not exist in this shape, so the actual expression is slightly more complicated. -- -- Every Expression should be disambiguated before printing to ensure unambiguity. module Database.Design.Ampersand.FSpec.ShowADL ( ShowADL(..), LanguageDependent(..), showPAclause, showREL) where import Database.Design.Ampersand.Core.ParseTree import Database.Design.Ampersand.Core.AbstractSyntaxTree import Database.Design.Ampersand.Basics (fatalMsg,Collection(..),Named(..)) import Database.Design.Ampersand.Classes import Database.Design.Ampersand.ADL1 (insParentheses) import Database.Design.Ampersand.FSpec.FSpec import Data.List import Prelude --import Data.Time.Calendar fatal :: Int -> String -> a fatal = fatalMsg "FSpec.ShowADL" class ShowADL a where showADL :: a -> String -- there are data types yielding language dependent data like an Expression -- the LanguageDependent class provides function(s) to map language dependent functions on those data if any. -- for example to print all expressions in a data structure with a practical amount of type directives -- (instances have been created when needed) -- -- LanguageDependent is part of ShowAdl because the only application at time of writing is to disambiguate expressions for the purpose of printing -- SJ 31-12-2012: Since 'disambiguate' has become obsolete, do we still need this? class LanguageDependent a where mapexprs :: (Language l, ConceptStructure l, Named l) => (l -> Expression -> Expression) -> l -> a -> a mapexprs _ _ = id instance LanguageDependent a => LanguageDependent (Maybe a) where mapexprs _ _ Nothing = Nothing mapexprs f l (Just x) = Just $ mapexprs f l x instance LanguageDependent (a, Expression) where mapexprs f l (x,e) = (x, f l e) instance LanguageDependent Rule where mapexprs f l rul = rul{rrexp = f l (rrexp rul)} instance LanguageDependent Interface where mapexprs f l ifc = ifc{ifcObj = mapexprs f l (ifcObj ifc)} instance LanguageDependent ObjectDef where mapexprs f l obj = obj{objctx = f l (objctx obj), objmsub = mapexprs f l $ objmsub obj} instance LanguageDependent SubInterface where mapexprs _ _ iref@(InterfaceRef _ _) = iref mapexprs f l (Box o cl objs) = Box o cl $ map (mapexprs f l) objs instance LanguageDependent Declaration where mapexprs _ _ = id instance LanguageDependent ECArule where mapexprs _ _ = id instance LanguageDependent Event where mapexprs _ _ = id -------------------------------------------------------------- instance ShowADL (P_SubIfc a) where showADL (P_Box{}) = "BOX" showADL (P_InterfaceRef _ isLink nm) = (if isLink then " LINKTO" else "")++" INTERFACE "++showstr nm instance ShowADL ObjectDef where -- WHY (HJ)? In deze instance van ShowADL worden diverse zaken gebruikt die ik hier niet zou verwachten. -- Het vertroebelt de code ook een beetje, want nu moeten er dingen als 'source' en -- 'target' hier al bekend zijn. -- Dat lijkt me hier nog niet op z'n plaats, als je alleen maar wat wilt kunnen 'prettyprinten'. -- BECAUSE (SJ): Dit blijft nog even zo, omdat showADL gebruikt wordt in het genereren van interfaces. -- Zolang we dat nog niet onder de knie hebben blijft de code wat troebel. showADL obj = " : "++showADL (objctx obj)++ recur "\n " (objmsub obj) where recur :: String -> Maybe SubInterface -> String recur _ Nothing = "" recur ind (Just (InterfaceRef isLink nm)) = ind++(if isLink then " LINKTO" else "")++" INTERFACE "++showstr nm recur ind (Just (Box _ cl objs)) = ind++" BOX" ++ showClass cl ++ " [ "++ intercalate (ind++" , ") [ showstr (name o)++ (if null (objstrs o) then "" else " {"++intercalate ", " [showstr (unwords ss) | ss<-objstrs o]++"}")++ " : "++showADL (objctx o)++ recur (ind++" ") (objmsub o) | o<-objs ]++ ind++" ]" showClass Nothing = "" showClass (Just cl) = "<" ++ cl ++ ">" -- TODO: parser cannot handle these class annotations yet instance ShowADL Meta where showADL (Meta _ metaObj nm val) = "META "++(if null $ showADL metaObj then "" else showADL metaObj++" ") ++show nm++" "++show val instance ShowADL MetaObj where showADL ContextMeta = "" instance ShowADL Purpose where showADL expl = "PURPOSE "++showADL (explObj expl) ++" "++showADL (amLang (explMarkup expl)) ++(if null (explRefIds expl) then "" else " REF "++intercalate ";" (explRefIds expl)) ++ "{+"++aMarkup2String ReST (explMarkup expl)++"-}" instance ShowADL PandocFormat where showADL LaTeX = "LATEX " showADL HTML = "HTML " showADL ReST = "REST " showADL Markdown = "MARKDOWN " instance ShowADL A_Markup where showADL m = showADL (amLang m) ++ "{+"++aMarkup2String ReST m++"-}" instance ShowADL Lang where showADL Dutch = "IN DUTCH" showADL English = "IN ENGLISH" instance ShowADL ExplObj where showADL e = case e of ExplConceptDef cd -> "CONCEPT "++cdcpt cd ExplDeclaration d -> "RELATION "++show (name d) ExplRule str -> "RULE "++showstr str ExplIdentityDef str-> "IDENT "++showstr str ExplViewDef str -> "VIEW "++showstr str ExplPattern str -> "PATTERN "++ showstr str ExplInterface str -> "INTERFACE "++showstr str ExplContext str -> "CONTEXT "++showstr str showstr :: String -> String showstr str = "\""++str++"\"" -- TODO: making these tuples instance of ShowADL is very hacky instance ShowADL (String,Rule) where showADL (role,rul) = "ROLE "++role++" MAINTAINS "++show (name rul) instance ShowADL (String,Declaration) where showADL (role,rel) = "ROLE "++role++" EDITS "++showADL rel instance ShowADL (String,Interface) where showADL (role,ifc) = "ROLE "++role++" USES "++show (name ifc) instance ShowADL Pattern where -- TODO: This function is VERY outdated showADL pat = "PATTERN " ++ showstr (name pat) ++ "\n" ++ (if null (ptrls pat) then "" else "\n " ++intercalate "\n " (map showADL (ptrls pat)) ++ "\n") ++ (if null (ptgns pat) then "" else "\n " ++intercalate "\n " (map showADL (ptgns pat)) ++ "\n") ++ (if null (ptdcs pat) then "" else "\n " ++intercalate "\n " (map showADL (ptdcs pat)) ++ "\n") -- concept definitions are not printed, because we have no way of telling where they come from.... ++ (if null (ptids pat) then "" else "\n " ++intercalate "\n " (map showADL (ptids pat)) ++ "\n") ++ "ENDPATTERN" instance ShowADL (PairViewSegment Expression) where showADL (PairViewText _ str) = "TXT " ++ show str showADL (PairViewExp _ srcOrTgt e) = showADL srcOrTgt ++ " " ++ showADL e instance ShowADL SrcOrTgt where showADL Src = "SRC" showADL Tgt = "TGT" instance ShowADL Rule where showADL r = "RULE \""++rrnm r++"\" : "++showADL (rrexp r) ++ concat ["\n MEANING "++showADL mng | mng <- ameaMrk $ rrmean r ] ++ concat ["\n MESSAGE "++showADL msg | msg <- rrmsg r] ++ case rrviol r of Nothing -> "" Just (PairView pvSegs) -> "\n VIOLATION ("++intercalate ", " (map showADL pvSegs)++")" instance ShowADL A_Gen where showADL g = case g of Isa{} -> "CLASSIFY "++showADL (genspc g)++" ISA "++showADL (gengen g) IsE{} -> "CLASSIFY "++showADL (genspc g)++" IS "++intercalate " /\\ " (map showADL (genrhs g)) instance ShowADL A_RoleRelation where showADL r = "ROLE "++intercalate ", " (map show (rrRoles r))++" EDITS "++intercalate ", " (map showADL (rrRels r)) instance ShowADL P_RoleRule where showADL r = "ROLE "++intercalate ", " (map show (mRoles r))++" MAINTAINS "++intercalate ", " (map show (mRules r)) instance ShowADL Interface where showADL ifc = "INTERFACE "++showstr(name ifc) ++ maybe "" ((" CLASS "++) . showstr) (ifcClass ifc) ++(if null (ifcParams ifc) then "" else "("++intercalate ", " [showADL r | r<-ifcParams ifc]++")") ++(if null (ifcArgs ifc) then "" else "{"++intercalate ", " [showstr(unwords strs) | strs<-ifcArgs ifc]++"}") ++(if null (ifcRoles ifc) then "" else " FOR "++intercalate ", " (map name (ifcRoles ifc))) ++showADL (ifcObj ifc) instance ShowADL IdentityDef where showADL identity = "IDENT "++idLbl identity ++ ": " ++name (idCpt identity) ++ "(" ++intercalate ", " (map showADL $ identityAts identity) ++ ")" instance ShowADL IdentitySegment where showADL (IdentityExp objDef) = (if null (name objDef) then "" else "\""++name objDef++"\":") ++ showADL (objctx objDef) instance ShowADL ViewDef where showADL vd = "VIEW "++vdlbl vd ++ ": " ++name (vdcpt vd) ++ "(" ++intercalate ", " (map showADL $ vdats vd) ++ ")" instance ShowADL ViewSegment where showADL (ViewExp _ objDef) = (if null (name objDef) then "" else "\""++name objDef++"\":") ++ showADL (objctx objDef) showADL (ViewText _ str) = "TXT " ++ show str showADL (ViewHtml _ str) = "PRIMHTML " ++ show str -- showADL Relation only prints complete signatures to ensure unambiguity. -- therefore, when printing expressions, do not apply this function to print relations, but apply one that prints names only --instance ShowADL Relation where -- showADL rel = show rel instance ShowADL Expression where showADL = showExpr (" = ", " |- ", " /\\ ", " \\/ ", " - ", " / ", " \\ ", " <> ", ";", "!", "*", "*", "+", "~", ("-"++), "(", ")", "[", "*", "]") -- NOTE: retain space after \\, because of unexpected side effects if it is used just before an 'r' or 'n'.... where showExpr :: (String,String,String,String,String,String,String,String,String,String,String,String,String,String,String -> String,String,String,String,String,String) -> Expression -> String showExpr (equi, impl, inter, union',diff, lresi, rresi, rDia, rMul , rAdd , rPrd ,closK0,closK1,flp', compl, lpar, rpar, lbr, star, rbr) expr = showchar (insParentheses expr) where showchar (EEqu (l,r)) = showchar l++equi++showchar r showchar (EImp (l,r)) = showchar l++impl++showchar r showchar (EIsc (l,r)) = showchar l++inter++showchar r showchar (EUni (l,r)) = showchar l++union'++showchar r showchar (EDif (l,r)) = showchar l++diff ++showchar r showchar (ELrs (l,r)) = showchar l++lresi++showchar r showchar (ERrs (l,r)) = showchar l++rresi++showchar r showchar (EDia (l,r)) = showchar l++rDia++showchar r showchar (ECps (l,r)) = showchar l++rMul++showchar r showchar (ERad (l,r)) = showchar l++rAdd++showchar r showchar (EPrd (l,r)) = showchar l++rPrd++showchar r showchar (EKl0 e) = showchar e++closK0 showchar (EKl1 e) = showchar e++closK1 showchar (EFlp e) = showchar e++flp' showchar (ECpl e) = compl (showchar e) showchar (EBrk e) = lpar++showchar e++rpar showchar (EDcD dcl) = name dcl showchar (EDcI c) = "I"++lbr++name c++rbr showchar (EEps i _) = "I{-Eps-}"++lbr++name i++rbr showchar (EDcV sgn) = "V"++lbr++name (source sgn)++star++name (target sgn)++rbr showchar (EMp1 val c) = "'"++showWithoutDoubleQuotes val++"'"++lbr++name c++rbr showWithoutDoubleQuotes str = case showADL str of [] -> [] [c] -> [c] cs -> if head cs == '\"' && last cs == '\"' then reverse . tail . reverse .tail $ cs else cs instance ShowADL DnfClause where showADL dnfClause = showADL (dnf2expr dnfClause) instance ShowADL Declaration where showADL decl = case decl of Sgn{} -> name decl++" :: "++name (source decl)++(if null ([Uni,Tot]>-multiplicities decl) then " -> " else " * ")++name (target decl)++ (let mults=if null ([Uni,Tot]>-multiplicities decl) then multiplicities decl>-[Uni,Tot] else multiplicities decl in if null mults then "" else "["++intercalate "," (map showADL mults)++"]")++ (if null(decprL decl++decprM decl++decprR decl) then "" else " PRAGMA "++unwords (map show [decprL decl,decprM decl,decprR decl])) ++ concatMap meaning (ameaMrk (decMean decl)) Isn{} -> "I["++show (detyp decl)++"]" -- Isn{} is of type Declaration and it is implicitly defined Vs{} -> "V"++show (decsgn decl) -- Vs{} is of type Declaration and it is implicitly defined where meaning :: A_Markup -> String meaning pmkup = " MEANING "++showADL pmkup showREL :: Declaration-> String showREL decl = show decl {- case decl of Sgn{} -> name decl++showSign (sign decl) Isn{} -> "I["++show (detyp decl)++"]" -- Isn{} is of type Declaration and it is implicitly defined Vs{} -> "V"++show (decsgn decl) -} instance ShowADL P_Markup where showADL (P_Markup lng fmt str) = case lng of Nothing -> "" Just l -> "IN "++show l++" " ++ case fmt of Nothing -> "" Just f -> " "++show f++" " ++ "{+"++str++"-} " instance ShowADL Prop where showADL = show instance ShowADL A_Concept where showADL c = show (name c) instance ShowADL ConceptDef where showADL cd = "\n CONCEPT "++show (cdcpt cd)++" "++show (cddef cd)++" "++(if null (cdref cd) then "" else show (cdref cd)) instance ShowADL A_Context where showADL context = "CONTEXT " ++name context ++ " " ++ (showADL (ctxlang context)) ++ (if null (ctxmetas context) then "" else "\n" ++intercalate "\n\n" (map showADL (ctxmetas context))++ "\n") ++ (if null (ctxifcs context) then "" else "\n" ++intercalate "\n\n" (map showADL (ctxifcs context)) ++ "\n") ++ (if null (ctxpats context) then "" else "\n" ++intercalate "\n\n" (map showADL (ctxpats context)) ++ "\n") ++ (if null (ctxrs context) then "" else "\n" ++intercalate "\n" (map showADL (ctxrs context)) ++ "\n") ++ (if null (ctxds context) then "" else "\n" ++intercalate "\n" (map showADL (ctxds context)) ++ "\n") ++ (if null (ctxks context) then "" else "\n" ++intercalate "\n" (map showADL (ctxks context)) ++ "\n") ++ (if null (ctxgs context) then "" else "\n" ++intercalate "\n" (map showADL (ctxgs context)) ++ "\n") ++ (if null (ctxcds context) then "" else "\n" ++intercalate "\n" (map showADL (ctxcds context)) ++ "\n") ++ (if null (ctxpopus context) then "" else "\n" ++intercalate "\n" (map showADL (ctxpopus context))++ "\n") ++ (if null (ctxsql context) then "" else "\n" ++intercalate "\n\n" (map showADL (ctxsql context)) ++ "\n") ++ (if null (ctxphp context) then "" else "\n" ++intercalate "\n\n" (map showADL (ctxphp context)) ++ "\n") ++ "\n\nENDCONTEXT" instance ShowADL (Maybe String) where showADL _ = "" instance ShowADL ECArule where showADL eca = "ECA #"++show (ecaNum eca) instance ShowADL Event where showADL ev = " On " ++show (eSrt ev)++" "++showREL (eDcl ev) instance (ShowADL a, ShowADL b) => ShowADL (a,b) where showADL (a,b) = "(" ++ showADL a ++ ", " ++ showADL b ++ ")" instance ShowADL P_Population where showADL pop = "POPULATION "++name pop ++ case pop of P_RelPopu{p_nmdr = PNamedRel _ _ (Just sgn)} -> "["++(name.pSrc) sgn++"*"++(name.pTgt) sgn++"]" _ -> "" ++ " CONTAINS\n" ++ if (case pop of P_RelPopu{} -> null (p_popps pop) P_CptPopu{} -> null (p_popas pop) ) then "" else indent++"[ "++intercalate ("\n"++indent++", ") showContent++indent++"]" where indent = " " showContent = case pop of P_RelPopu{} -> map showADL (p_popps pop) P_CptPopu{} -> map showADL (p_popas pop) instance ShowADL PAtomPair where showADL p = "("++showADL (ppLeft p)++","++ showADL (ppRight p)++")" instance ShowADL AAtomPair where showADL p = "("++showADL (apLeft p)++","++ showADL (apRight p)++")" instance ShowADL Population where showADL pop = "POPULATION " ++ case pop of ARelPopu{} -> (name.popdcl) pop++(show.sign.popdcl) pop ACptPopu{} -> (name.popcpt) pop ++ " CONTAINS\n" ++ if (case pop of ARelPopu{} -> null (popps pop) ACptPopu{} -> null (popas pop) ) then "" else indent++"[ "++intercalate ("\n"++indent++", ") showContent++indent++"]" where indent = " " showContent = case pop of ARelPopu{} -> map showADL (popps pop) ACptPopu{} -> map showADL (popas pop) -- showADL (ARelPopu r pairs) -- = "POPULATION "++showADL r++" CONTAINS\n"++ -- indent++"[ "++intercalate ("\n"++indent++", ") (map (\(x,y)-> showatom x++" * "++ showatom y) pairs)++indent++"]" -- where indent = " " instance ShowADL PAtomValue where showADL at = case at of PSingleton _ s _ -> show s ScriptString _ s -> show s XlsxString _ s -> show s ScriptInt _ s -> show s ScriptFloat _ x -> show x XlsxDouble _ d -> show d ComnBool _ b -> show b ScriptDate _ x -> show x ScriptDateTime _ x -> show x instance ShowADL AAtomValue where showADL at = case at of AAVString _ str -> show str AAVInteger _ i -> show i AAVFloat _ f -> show f AAVBoolean _ b -> show b AAVDate _ day -> show day AAVDateTime _ dt -> show dt AtomValueOfONE -> "1" instance ShowADL TermPrim where showADL (PI _) = "I" showADL (Pid _ c) = "I["++showADL c++"]" showADL (Patm _ val mSign) = showSingleton where showSingleton = "'"++ (case val of PSingleton _ x _ -> x ScriptString _ x -> x XlsxString _ x -> concatMap escapeSingleQuote x where escapeSingleQuote c= case c of '\'' -> ['\\','\''] _ -> [c] ScriptInt _ x -> show x ScriptFloat _ x -> show x XlsxDouble _ x -> show x ComnBool _ x -> show x ScriptDate _ x -> show x ScriptDateTime _ x -> show x ) ++ "'" ++ (case mSign of Nothing -> "" Just c -> "["++show c++"]" ) showADL (PVee _) = "V" showADL (Pfull _ s t) = "V["++show s++"*"++show t++"]" showADL (PNamedR rel) = showADL rel instance ShowADL P_NamedRel where showADL (PNamedRel _ rel mSgn) = rel++maybe "" showsign mSgn where showsign (P_Sign src trg) = "["++showADL src++"*"++showADL trg++"]" --used to compose error messages at p2a time instance (ShowADL a, Traced a) => ShowADL (Term a) where showADL = showPExpr (" = ", " |- ", " /\\ ", " \\/ ", " - ", " / ", " \\ ", "<>", ";", "!", "*", "*", "+", "~", "(", ")") where showPExpr (equi,impl,inter,union',diff,lresi,rresi,rDia,rMul,rAdd,rPrd,closK0,closK1,flp',lpar,rpar) expr = showchar (insP_Parentheses expr) where showchar (Prim a) = showADL a showchar (PEqu _ l r) = showchar l++equi++showchar r showchar (PImp _ l r) = showchar l++impl++showchar r showchar (PIsc _ l r) = showchar l++inter++showchar r showchar (PUni _ l r) = showchar l++union'++showchar r showchar (PDif _ l r) = showchar l++diff ++showchar r showchar (PLrs _ l r) = showchar l++lresi++showchar r showchar (PRrs _ l r) = showchar l++rresi++showchar r showchar (PDia _ l r) = showchar l++rDia++showchar r showchar (PCps _ l r) = showchar l++rMul++showchar r showchar (PRad _ l r) = showchar l++rAdd++showchar r showchar (PPrd _ l r) = showchar l++rPrd++showchar r showchar (PKl0 _ e) = showchar e++closK0 showchar (PKl1 _ e) = showchar e++closK1 showchar (PFlp _ e) = showchar e++flp' showchar (PCpl _ e) = '-':showchar e showchar (PBrk _ e) = lpar++showchar e++rpar insP_Parentheses :: (Traced a) => Term a -> Term a insP_Parentheses = insPar 0 where wrap :: (Traced a) => Integer -> Integer -> Term a -> Term a wrap i j e' = if i<=j then e' else PBrk (origin e') e' insPar :: (Traced a) => Integer -> Term a -> Term a insPar i (PEqu o l r) = wrap i 0 (PEqu o (insPar 1 l) (insPar 1 r)) insPar i (PImp o l r) = wrap i 0 (PImp o (insPar 1 l) (insPar 1 r)) insPar i (PIsc o l r) = wrap (i+1) 2 (PIsc o (insPar 2 l) (insPar 2 r)) insPar i (PUni o l r) = wrap (i+1) 2 (PUni o (insPar 2 l) (insPar 2 r)) insPar i (PDif o l r) = wrap i 4 (PDif o (insPar 5 l) (insPar 5 r)) insPar i (PLrs o l r) = wrap i 6 (PLrs o (insPar 7 l) (insPar 7 r)) insPar i (PRrs o l r) = wrap i 6 (PRrs o (insPar 7 l) (insPar 7 r)) insPar i (PDia o l r) = wrap i 6 (PDia o (insPar 7 l) (insPar 7 r)) insPar i (PCps o l r) = wrap (i+1) 8 (PCps o (insPar 8 l) (insPar 8 r)) insPar i (PRad o l r) = wrap (i+1) 8 (PRad o (insPar 8 l) (insPar 8 r)) insPar i (PPrd o l r) = wrap (i+1) 8 (PPrd o (insPar 8 l) (insPar 8 r)) insPar _ (PKl0 o e) = PKl0 o (insPar 10 e) insPar _ (PKl1 o e) = PKl1 o (insPar 10 e) insPar _ (PFlp o e) = PFlp o (insPar 10 e) insPar _ (PCpl o e) = PCpl o (insPar 10 e) insPar i (PBrk _ e) = insPar i e insPar _ x = x --used to compose error messages at p2a time instance ShowADL P_Concept where showADL = name instance ShowADL PAclause where showADL = showPAclause "\n " showPAclause :: String -> PAclause -> String showPAclause indent pa@Do{} = ( case paSrt pa of Ins -> "INSERT INTO " Del -> "DELETE FROM ")++ showREL (paTo pa) ++ indent++" SELECTFROM "++ showADL (paDelta pa)++ indent++motivate indent "TO MAINTAIN " (paMotiv pa) showPAclause indent (New c clause cj_ruls) = "NEW x:"++show c++";"++indent'++showPAclause indent' (clause (makePSingleton "x"))++motivate indent "MAINTAINING" cj_ruls where indent' = indent++" " showPAclause indent (Rmv c clause cj_ruls) = "REMOVE x:"++show c++";"++indent'++showPAclause indent' (clause (makePSingleton "x"))++motivate indent "MAINTAINING" cj_ruls where indent' = indent++" " showPAclause indent (CHC ds cj_ruls) = "ONE OF "++intercalate indent' [showPAclause indent' d | d<-ds]++motivate indent "MAINTAINING" cj_ruls where indent' = indent++" " showPAclause indent (GCH ds cj_ruls) = "ONE NONEMPTY ALTERNATIVE OF "++intercalate indent' ["PICK a,b FROM "++showADL links++indent'++"THEN "++showPAclause (indent'++" ") p| (_,links,p)<-ds]++ motivate indent "MAINTAINING" cj_ruls where indent' = indent++" " showPAclause indent (ALL ds cj_ruls) = "ALL of "++intercalate indent' [showPAclause indent' d | d<-ds]++motivate indent "MAINTAINING" cj_ruls where indent' = indent++" " showPAclause indent (Nop cj_ruls) = "DO NOTHING"++motivate indent "TO MAINTAIN" cj_ruls showPAclause indent (Blk cj_ruls) = "BLOCK"++motivate indent "CANNOT CHANGE" cj_ruls showPAclause _ (Let _ _ _) = fatal 55 "showPAclause is missing for `Let`. Contact your dealer!" showPAclause _ (Ref _) = fatal 56 "showPAclause is missing for `Ref`. Contact your dealer!" motivate :: [Char] -> [Char] -> [(Expression, [Rule])] -> [Char] motivate indent motive motives = concat [ indent++showConj cj_rul | cj_rul<-motives ] where showConj (conj,rs) = "("++motive++" "++showADL conj++" FROM "++intercalate ", " (map name rs) ++")"
guoy34/ampersand
src/Database/Design/Ampersand/FSpec/ShowADL.hs
gpl-3.0
25,493
1
26
7,385
8,881
4,466
4,415
417
18
{-# 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.ServiceManagement.Services.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Lists managed services. If called without any authentication, it returns -- only the public services. If called with authentication, it returns all -- services that the caller has \"servicemanagement.services.get\" -- permission for. **BETA:** If the caller specifies the \`consumer_id\`, -- it returns only the services enabled on the consumer. The -- \`consumer_id\` must have the format of \"project:{PROJECT-ID}\". -- -- /See:/ <https://cloud.google.com/service-management/ Google Service Management API Reference> for @servicemanagement.services.list@. module Network.Google.Resource.ServiceManagement.Services.List ( -- * REST Resource ServicesListResource -- * Creating a Request , servicesList , ServicesList -- * Request Lenses , slXgafv , slUploadProtocol , slPp , slAccessToken , slUploadType , slBearerToken , slPageToken , slProducerProjectId , slConsumerId , slPageSize , slCallback ) where import Network.Google.Prelude import Network.Google.ServiceManagement.Types -- | A resource alias for @servicemanagement.services.list@ method which the -- 'ServicesList' request conforms to. type ServicesListResource = "v1" :> "services" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "pp" Bool :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "bearer_token" Text :> QueryParam "pageToken" Text :> QueryParam "producerProjectId" Text :> QueryParam "consumerId" Text :> QueryParam "pageSize" (Textual Int32) :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] ListServicesResponse -- | Lists managed services. If called without any authentication, it returns -- only the public services. If called with authentication, it returns all -- services that the caller has \"servicemanagement.services.get\" -- permission for. **BETA:** If the caller specifies the \`consumer_id\`, -- it returns only the services enabled on the consumer. The -- \`consumer_id\` must have the format of \"project:{PROJECT-ID}\". -- -- /See:/ 'servicesList' smart constructor. data ServicesList = ServicesList' { _slXgafv :: !(Maybe Xgafv) , _slUploadProtocol :: !(Maybe Text) , _slPp :: !Bool , _slAccessToken :: !(Maybe Text) , _slUploadType :: !(Maybe Text) , _slBearerToken :: !(Maybe Text) , _slPageToken :: !(Maybe Text) , _slProducerProjectId :: !(Maybe Text) , _slConsumerId :: !(Maybe Text) , _slPageSize :: !(Maybe (Textual Int32)) , _slCallback :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ServicesList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'slXgafv' -- -- * 'slUploadProtocol' -- -- * 'slPp' -- -- * 'slAccessToken' -- -- * 'slUploadType' -- -- * 'slBearerToken' -- -- * 'slPageToken' -- -- * 'slProducerProjectId' -- -- * 'slConsumerId' -- -- * 'slPageSize' -- -- * 'slCallback' servicesList :: ServicesList servicesList = ServicesList' { _slXgafv = Nothing , _slUploadProtocol = Nothing , _slPp = True , _slAccessToken = Nothing , _slUploadType = Nothing , _slBearerToken = Nothing , _slPageToken = Nothing , _slProducerProjectId = Nothing , _slConsumerId = Nothing , _slPageSize = Nothing , _slCallback = Nothing } -- | V1 error format. slXgafv :: Lens' ServicesList (Maybe Xgafv) slXgafv = lens _slXgafv (\ s a -> s{_slXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). slUploadProtocol :: Lens' ServicesList (Maybe Text) slUploadProtocol = lens _slUploadProtocol (\ s a -> s{_slUploadProtocol = a}) -- | Pretty-print response. slPp :: Lens' ServicesList Bool slPp = lens _slPp (\ s a -> s{_slPp = a}) -- | OAuth access token. slAccessToken :: Lens' ServicesList (Maybe Text) slAccessToken = lens _slAccessToken (\ s a -> s{_slAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). slUploadType :: Lens' ServicesList (Maybe Text) slUploadType = lens _slUploadType (\ s a -> s{_slUploadType = a}) -- | OAuth bearer token. slBearerToken :: Lens' ServicesList (Maybe Text) slBearerToken = lens _slBearerToken (\ s a -> s{_slBearerToken = a}) -- | Token identifying which result to start with; returned by a previous -- list call. slPageToken :: Lens' ServicesList (Maybe Text) slPageToken = lens _slPageToken (\ s a -> s{_slPageToken = a}) -- | Include services produced by the specified project. slProducerProjectId :: Lens' ServicesList (Maybe Text) slProducerProjectId = lens _slProducerProjectId (\ s a -> s{_slProducerProjectId = a}) -- | Include services consumed by the specified consumer. The Google Service -- Management implementation accepts the following forms: - project: slConsumerId :: Lens' ServicesList (Maybe Text) slConsumerId = lens _slConsumerId (\ s a -> s{_slConsumerId = a}) -- | Requested size of the next page of data. slPageSize :: Lens' ServicesList (Maybe Int32) slPageSize = lens _slPageSize (\ s a -> s{_slPageSize = a}) . mapping _Coerce -- | JSONP slCallback :: Lens' ServicesList (Maybe Text) slCallback = lens _slCallback (\ s a -> s{_slCallback = a}) instance GoogleRequest ServicesList where type Rs ServicesList = ListServicesResponse type Scopes ServicesList = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/cloud-platform.read-only", "https://www.googleapis.com/auth/service.management", "https://www.googleapis.com/auth/service.management.readonly"] requestClient ServicesList'{..} = go _slXgafv _slUploadProtocol (Just _slPp) _slAccessToken _slUploadType _slBearerToken _slPageToken _slProducerProjectId _slConsumerId _slPageSize _slCallback (Just AltJSON) serviceManagementService where go = buildClient (Proxy :: Proxy ServicesListResource) mempty
rueshyna/gogol
gogol-servicemanagement/gen/Network/Google/Resource/ServiceManagement/Services/List.hs
mpl-2.0
7,399
0
21
1,835
1,136
658
478
154
1
{-# LANGUAGE OverloadedStrings, DoAndIfThenElse #-} module Codec.Chunky.Internal ( Chunk (..) , readChunks , putChunks , expectStr , expectStrLn , putStr , putStrLn , readStr , readStrLn , putStrPadded , putStrLnPadded , readStrPadded , readStrLnPadded ) where import Prelude hiding (putStr, putStrLn) import Data.Binary.Get import Data.Binary.Put import qualified Data.ByteString.Lazy as B import Data.Text as T import Data.Text.Encoding import Control.Applicative import Data.Int import Control.Monad -- Title can be up to 30 characters. data Chunk = Binary { title :: T.Text , bContent :: B.ByteString } | Textual { title :: T.Text , tContent :: T.Text } deriving (Show, Read, Eq, Ord) readChunks :: Int -> Get [Chunk] readChunks n = replicateM n parseChunk parseChunk :: Get Chunk parseChunk = do expectStrLn sep expectStr "Title: " title <- readStrLnPadded 30 expectStr "Type: " ty' <- readStr 3 expectStr " Length: " len <- fromInteger . read . T.unpack <$> readStrLn 20 expectStrLn sep bd <- getLazyByteString len expectStr "\n" expectStrLn sep return $ case ty' of "TXT" -> Textual title (decodeUtf8 $ B.toStrict bd) "BIN" -> Binary title bd putChunks :: [Chunk] -> Put putChunks cs = mapM printChunk cs >> return () printChunk :: Chunk -> Put printChunk chnk = do putStrLn sep putStr $ "Title: " putStrLnPadded 30 (title chnk) putStr "Type: " body <- case chnk of (Textual _ bd) -> do putStr "TXT " return $ B.fromStrict $ encodeUtf8 bd (Binary _ bd) -> do putStr "BIN " return bd let len = B.length body putStrLn $ "Length: " `T.append` (padLeft "0" 20 $ T.pack $ show len) putStrLn sep putLazyByteString body putStr "\n" putStrLn sep -- TODO actually call this... validate :: Chunk -> () validate chnk = -- title must not start/end with whitespace case True of _ | T.strip (title chnk) /= title chnk -> error "Title must not start/end with whitespaces." _ | T.length (title chnk) > 20 -> error "Title must not be longer than 20 characters." _ -> () expectStrLn :: T.Text -> Get T.Text expectStrLn t = T.init <$> expectStr (t `T.append` "\n") expectStr :: T.Text -> Get T.Text expectStr t = do let tAsBytes = B.fromStrict $ encodeUtf8 t act <- getLazyByteString (B.length tAsBytes) if act == tAsBytes then return t else error $ "Malformed input!" readStrLn :: Int64 -> Get T.Text readStrLn n = readStr n <* expectStr "\n" readStr :: Int64 -> Get T.Text readStr n = decodeUtf8 . B.toStrict <$> getLazyByteString n putStrLn :: T.Text -> Put putStrLn s = putStr (s `T.append` "\n") putStr :: T.Text -> Put putStr = putLazyByteString . B.fromStrict . encodeUtf8 putStrPadded :: Int -> T.Text -> Put putStrPadded n t = case (T.stripEnd t == t, T.length t <= n) of (True, True) -> putStr (padRight " " n t) (False, _) -> error "Padded strings must not end with whitespaces." (_, False) -> error "Padded strings must not be longer than the allocated space." putStrLnPadded :: Int -> T.Text -> Put putStrLnPadded n t = putStrPadded n t >> putStr "\n" readStrPadded :: Int64 -> Get T.Text readStrPadded n = T.stripEnd <$> readStr n readStrLnPadded :: Int64 -> Get T.Text readStrLnPadded n = do r <- readStrPadded n expectStr "\n" return r padRight :: T.Text -> Int -> T.Text -> T.Text padRight s n t = t `T.append` (T.replicate (n - T.length t) s) padLeft :: T.Text -> Int -> T.Text -> T.Text padLeft s n t = (T.replicate (n - T.length t) s) `T.append` t sep :: T.Text sep = T.replicate 20 "="
phile314/chunky
src/lib/Codec/Chunky/Internal.hs
lgpl-3.0
3,679
0
15
867
1,310
655
655
116
3
{-# LANGUAGE OverloadedStrings #-} module Network.Haskoin.Crypto.Mnemonic.Units (tests) where import Data.ByteString (ByteString) import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as C import Data.Either (fromRight) import Data.List (isPrefixOf) import Data.Maybe (fromJust) import Data.String.Conversions (cs) import Network.Haskoin.Crypto import Network.Haskoin.Util import Test.Framework (Test, testGroup) import Test.Framework.Providers.HUnit (testCase) import Test.HUnit (assertBool, assertEqual) tests :: [Test] tests = [ testGroup "Entropy to mnemonic sentence" toMnemonicTest , testGroup "Mnemonic sentence to entropy" fromMnemonicTest , testGroup "Mnemonic sentence to seed" mnemonicToSeedTest , testGroup "Mnemonic sentence with invalid checksum" fromMnemonicInvalidTest , testGroup "Empty mnemonic sentence is invalid" [emptyMnemonicTest] ] toMnemonicTest :: [Test] toMnemonicTest = zipWith f ents mss where f e m = g (cs e) . assertEqual "" m . h $ e g = testCase h = fromRight (error "Could not decode mnemonic sentence") . toMnemonic . fromJust . decodeHex fromMnemonicTest :: [Test] fromMnemonicTest = zipWith f ents mss where f e = g (cs e) . assertEqual "" e . h g = testCase h = encodeHex . fromRight (error "Could not decode mnemonic sentence") . fromMnemonic mnemonicToSeedTest :: [Test] mnemonicToSeedTest = zipWith f mss seeds where f m s = g s . assertEqual "" s . h $ m g = testCase . (++ "...") . cs . BS.take 50 h = encodeHex . fromRight (error "Could not decode mnemonic seed") . mnemonicToSeed "TREZOR" fromMnemonicInvalidTest :: [Test] fromMnemonicInvalidTest = map f invalidMss where f m = g m . assertBool "" . h $ m g m = let ms = length (C.words m) msg = concat [ "[MS: ", show ms, "]" , cs (BS.take 50 m), "..." ] in testCase msg h m = case fromMnemonic m of Right _ -> False Left err -> "fromMnemonic: checksum failed:" `isPrefixOf` err emptyMnemonicTest :: Test emptyMnemonicTest = testCase "mnemonic sentence can not be empty" $ assertBool "" $ case fromMnemonic "" of Right _ -> False Left err -> "fromMnemonic: empty mnemonic" `isPrefixOf` err ents :: [ByteString] ents = [ "00000000000000000000000000000000" , "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f" , "80808080808080808080808080808080" , "ffffffffffffffffffffffffffffffff" , "000000000000000000000000000000000000000000000000" , "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f" , "808080808080808080808080808080808080808080808080" , "ffffffffffffffffffffffffffffffffffffffffffffffff" , "0000000000000000000000000000000000000000000000000000000000000000" , "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f" , "8080808080808080808080808080808080808080808080808080808080808080" , "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" , "77c2b00716cec7213839159e404db50d" , "b63a9c59a6e641f288ebc103017f1da9f8290b3da6bdef7b" , "3e141609b97933b66a060dcddc71fad1d91677db872031e85f4c015c5e7e8982" , "0460ef47585604c5660618db2e6a7e7f" , "72f60ebac5dd8add8d2a25a797102c3ce21bc029c200076f" , "2c85efc7f24ee4573d2b81a6ec66cee209b2dcbd09d8eddc51e0215b0b68e416" , "eaebabb2383351fd31d703840b32e9e2" , "7ac45cfe7722ee6c7ba84fbc2d5bd61b45cb2fe5eb65aa78" , "4fa1a8bc3e6d80ee1316050e862c1812031493212b7ec3f3bb1b08f168cabeef" , "18ab19a9f54a9274f03e5209a2ac8a91" , "18a2e1d81b8ecfb2a333adcb0c17a5b9eb76cc5d05db91a4" , "15da872c95a13dd738fbf50e427583ad61f18fd99f628c417a61cf8343c90419" ] mss :: [Mnemonic] mss = [ "abandon abandon abandon abandon abandon abandon abandon abandon abandon\ \ abandon abandon about" , "legal winner thank year wave sausage worth useful legal winner thank\ \ yellow" , "letter advice cage absurd amount doctor acoustic avoid letter advice\ \ cage above" , "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong" , "abandon abandon abandon abandon abandon abandon abandon abandon abandon\ \ abandon abandon abandon abandon abandon abandon abandon abandon agent" , "legal winner thank year wave sausage worth useful legal winner thank\ \ year wave sausage worth useful legal will" , "letter advice cage absurd amount doctor acoustic avoid letter advice\ \ cage absurd amount doctor acoustic avoid letter always" , "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo\ \ when" , "abandon abandon abandon abandon abandon abandon abandon abandon abandon\ \ abandon abandon abandon abandon abandon abandon abandon abandon abandon\ \ abandon abandon abandon abandon abandon art" , "legal winner thank year wave sausage worth useful legal winner thank\ \ year wave sausage worth useful legal winner thank year wave sausage\ \ worth title" , "letter advice cage absurd amount doctor acoustic avoid letter advice\ \ cage absurd amount doctor acoustic avoid letter advice cage absurd\ \ amount doctor acoustic bless" , "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo\ \ zoo zoo zoo zoo zoo vote" , "jelly better achieve collect unaware mountain thought cargo oxygen act\ \ hood bridge" , "renew stay biology evidence goat welcome casual join adapt armor shuffle\ \ fault little machine walk stumble urge swap" , "dignity pass list indicate nasty swamp pool script soccer toe leaf photo\ \ multiply desk host tomato cradle drill spread actor shine dismiss\ \ champion exotic" , "afford alter spike radar gate glance object seek swamp infant panel\ \ yellow" , "indicate race push merry suffer human cruise dwarf pole review arch keep\ \ canvas theme poem divorce alter left" , "clutch control vehicle tonight unusual clog visa ice plunge glimpse\ \ recipe series open hour vintage deposit universe tip job dress radar\ \ refuse motion taste" , "turtle front uncle idea crush write shrug there lottery flower risk\ \ shell" , "kiss carry display unusual confirm curtain upgrade antique rotate hello\ \ void custom frequent obey nut hole price segment" , "exile ask congress lamp submit jacket era scheme attend cousin alcohol\ \ catch course end lucky hurt sentence oven short ball bird grab wing top" , "board flee heavy tunnel powder denial science ski answer betray cargo\ \ cat" , "board blade invite damage undo sun mimic interest slam gaze truly\ \ inherit resist great inject rocket museum chief" , "beyond stage sleep clip because twist token leaf atom beauty genius food\ \ business side grid unable middle armed observe pair crouch tonight away\ \ coconut" ] seeds :: [ByteString] seeds = [ "c55257c360c07c72029aebc1b53c05ed0362ada38ead3e3e9efa3708e53495531f09a69\ \87599d18264c1e1c92f2cf141630c7a3c4ab7c81b2f001698e7463b04" , "2e8905819b8723fe2c1d161860e5ee1830318dbf49a83bd451cfb8440c28bd6fa457fe1\ \296106559a3c80937a1c1069be3a3a5bd381ee6260e8d9739fce1f607" , "d71de856f81a8acc65e6fc851a38d4d7ec216fd0796d0a6827a3ad6ed5511a30fa280f1\ \2eb2e47ed2ac03b5c462a0358d18d69fe4f985ec81778c1b370b652a8" , "ac27495480225222079d7be181583751e86f571027b0497b5b5d11218e0a8a133325729\ \17f0f8e5a589620c6f15b11c61dee327651a14c34e18231052e48c069" , "035895f2f481b1b0f01fcf8c289c794660b289981a78f8106447707fdd9666ca06da5a9\ \a565181599b79f53b844d8a71dd9f439c52a3d7b3e8a79c906ac845fa" , "f2b94508732bcbacbcc020faefecfc89feafa6649a5491b8c952cede496c214a0c7b3c3\ \92d168748f2d4a612bada0753b52a1c7ac53c1e93abd5c6320b9e95dd" , "107d7c02a5aa6f38c58083ff74f04c607c2d2c0ecc55501dadd72d025b751bc27fe913f\ \fb796f841c49b1d33b610cf0e91d3aa239027f5e99fe4ce9e5088cd65" , "0cd6e5d827bb62eb8fc1e262254223817fd068a74b5b449cc2f667c3f1f985a76379b43\ \348d952e2265b4cd129090758b3e3c2c49103b5051aac2eaeb890a528" , "bda85446c68413707090a52022edd26a1c9462295029f2e60cd7c4f2bbd3097170af7a4\ \d73245cafa9c3cca8d561a7c3de6f5d4a10be8ed2a5e608d68f92fcc8" , "bc09fca1804f7e69da93c2f2028eb238c227f2e9dda30cd63699232578480a4021b146a\ \d717fbb7e451ce9eb835f43620bf5c514db0f8add49f5d121449d3e87" , "c0c519bd0e91a2ed54357d9d1ebef6f5af218a153624cf4f2da911a0ed8f7a09e2ef61a\ \f0aca007096df430022f7a2b6fb91661a9589097069720d015e4e982f" , "dd48c104698c30cfe2b6142103248622fb7bb0ff692eebb00089b32d22484e1613912f0\ \a5b694407be899ffd31ed3992c456cdf60f5d4564b8ba3f05a69890ad" , "b5b6d0127db1a9d2226af0c3346031d77af31e918dba64287a1b44b8ebf63cdd52676f6\ \72a290aae502472cf2d602c051f3e6f18055e84e4c43897fc4e51a6ff" , "9248d83e06f4cd98debf5b6f010542760df925ce46cf38a1bdb4e4de7d21f5c39366941\ \c69e1bdbf2966e0f6e6dbece898a0e2f0a4c2b3e640953dfe8b7bbdc5" , "ff7f3184df8696d8bef94b6c03114dbee0ef89ff938712301d27ed8336ca89ef9635da2\ \0af07d4175f2bf5f3de130f39c9d9e8dd0472489c19b1a020a940da67" , "65f93a9f36b6c85cbe634ffc1f99f2b82cbb10b31edc7f087b4f6cb9e976e9faf76ff41\ \f8f27c99afdf38f7a303ba1136ee48a4c1e7fcd3dba7aa876113a36e4" , "3bbf9daa0dfad8229786ace5ddb4e00fa98a044ae4c4975ffd5e094dba9e0bb289349db\ \e2091761f30f382d4e35c4a670ee8ab50758d2c55881be69e327117ba" , "fe908f96f46668b2d5b37d82f558c77ed0d69dd0e7e043a5b0511c48c2f1064694a956f\ \86360c93dd04052a8899497ce9e985ebe0c8c52b955e6ae86d4ff4449" , "bdfb76a0759f301b0b899a1e3985227e53b3f51e67e3f2a65363caedf3e32fde42a66c4\ \04f18d7b05818c95ef3ca1e5146646856c461c073169467511680876c" , "ed56ff6c833c07982eb7119a8f48fd363c4a9b1601cd2de736b01045c5eb8ab4f57b079\ \403485d1c4924f0790dc10a971763337cb9f9c62226f64fff26397c79" , "095ee6f817b4c2cb30a5a797360a81a40ab0f9a4e25ecd672a3f58a0b5ba0687c096a6b\ \14d2c0deb3bdefce4f61d01ae07417d502429352e27695163f7447a8c" , "6eff1bb21562918509c73cb990260db07c0ce34ff0e3cc4a8cb3276129fbcb300bddfe0\ \05831350efd633909f476c45c88253276d9fd0df6ef48609e8bb7dca8" , "f84521c777a13b61564234bf8f8b62b3afce27fc4062b51bb5e62bdfecb23864ee6ecf0\ \7c1d5a97c0834307c5c852d8ceb88e7c97923c0a3b496bedd4e5f88a9" , "b15509eaa2d09d3efd3e006ef42151b30367dc6e3aa5e44caba3fe4d3e352e65101fbdb\ \86a96776b91946ff06f8eac594dc6ee1d3e82a42dfe1b40fef6bcc3fd" ] invalidMss :: [Mnemonic] invalidMss = [ "abandon abandon abandon abandon abandon abandon abandon abandon abandon\ \ abandon abandon abandon" , "legal winner thank year wave sausage worth useful legal winner thank\ \ thank" , "letter advice cage absurd amount doctor acoustic avoid letter advice\ \ cage sausage" , "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo" , "abandon abandon abandon abandon abandon abandon abandon abandon abandon\ \ abandon abandon abandon abandon abandon abandon abandon abandon abandon" , "legal winner thank year wave sausage worth useful legal winner thank\ \ year wave sausage worth useful legal letter" , "letter advice cage absurd amount doctor acoustic avoid letter advice\ \ cage absurd amount doctor acoustic avoid letter abandon" , "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo\ \ zoo" , "abandon abandon abandon abandon abandon abandon abandon abandon abandon\ \ abandon abandon abandon abandon abandon abandon abandon abandon abandon\ \ abandon abandon abandon abandon abandon abandon" , "legal winner thank year wave sausage worth useful legal winner thank\ \ year wave sausage worth useful legal winner thank year wave sausage\ \ worth letter" , "letter advice cage absurd amount doctor acoustic avoid letter advice\ \ cage absurd amount doctor acoustic avoid letter advice cage absurd\ \ amount doctor acoustic letter" , "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo\ \ zoo zoo zoo zoo zoo zoo" , "jelly better achieve collect unaware mountain thought cargo oxygen act\ \ hood zoo" , "renew stay biology evidence goat welcome casual join adapt armor shuffle\ \ fault little machine walk stumble urge zoo" , "dignity pass list indicate nasty swamp pool script soccer toe leaf photo\ \ multiply desk host tomato cradle drill spread actor shine dismiss\ \ champion zoo" , "afford alter spike radar gate glance object seek swamp infant panel\ \ zoo" , "indicate race push merry suffer human cruise dwarf pole review arch keep\ \ canvas theme poem divorce alter zoo" , "clutch control vehicle tonight unusual clog visa ice plunge glimpse\ \ recipe series open hour vintage deposit universe tip job dress radar\ \ refuse motion zoo" , "turtle front uncle idea crush write shrug there lottery flower risk\ \ zoo" , "kiss carry display unusual confirm curtain upgrade antique rotate hello\ \ void custom frequent obey nut hole price zoo" , "exile ask congress lamp submit jacket era scheme attend cousin alcohol\ \ catch course end lucky hurt sentence oven short ball bird grab wing zoo" , "board flee heavy tunnel powder denial science ski answer betray cargo\ \ zoo" , "board blade invite damage undo sun mimic interest slam gaze truly\ \ inherit resist great inject rocket museum zoo" , "beyond stage sleep clip because twist token leaf atom beauty genius food\ \ business side grid unable middle armed observe pair crouch tonight away\ \ zoo" ]
xenog/haskoin
test/bitcoin/Network/Haskoin/Crypto/Mnemonic/Units.hs
unlicense
13,955
0
16
2,814
1,012
583
429
162
2
module Coins.A265415Spec (main, spec) where import Test.Hspec import Coins.A265415 (a265415) main :: IO () main = hspec spec spec :: Spec spec = describe "A265415" $ it "correctly computes the first 10 elements" $ take 10 (map a265415 [1..]) `shouldBe` expectedValue where expectedValue = [1,10,21,31,37,101,119,157,197,273]
peterokagey/haskellOEIS
test/Coins/A265415Spec.hs
apache-2.0
339
0
10
59
130
75
55
10
1
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE TemplateHaskell #-} module Worker where import Control.Concurrent (threadDelay) import Control.Applicative import Control.Monad import Control.Monad.Trans.Except import Control.Distributed.Process import Control.Distributed.Process.Closure import Control.Distributed.Process.Serializable (Serializable) import Text.Printf import GHC.Generics (Generic) import Types ---------------------------------------------------------------- -- Dot product ---------------------------------------------------------------- -- | Worker for dot product dotProductWorker :: (MasterProtocol, BoundedProtocol Double) -> Process () dotProductWorker (master,upstream) = workerLoop master $ \(i::Int,j::Int) -> do me <- getSelfPid logMsg master $ printf "[%s]: Fold received work %s" (show me) (show (i,j)) liftIO $ threadDelay (1000*1000) sendBoundedStream upstream (1 :: Double) workerLoop :: (Serializable a) => MasterProtocol -> (a -> Process ()) -> Process () workerLoop master action = loop where loop = do idle master msg <- expect case msg of Nothing -> return () Just a -> action a >> loop ---------------------------------------------------------------- -- Fold ---------------------------------------------------------------- -- | Worker for summing partial results foldWorker :: (MasterProtocol,ResultProtocol Double) -> Process () foldWorker (master,result) = loop Nothing 0 0 where loop :: Maybe Int -> Int -> Double -> Process () loop (Just tot) !n !x | n >= tot = sendResult result x loop tot n x = do msg <- receiveWait [ match $ return . Val . (\(BoundedV x) -> x) , match $ return . Total . (\(Count x) -> x) ] me <- getSelfPid logMsg master $ printf "[%s] fold received: %s" (show me) (show msg) case msg of Val y -> loop tot (n+1) (x+y) Total k | n >= k -> sendResult result x | otherwise -> loop (Just k) n x data FoldTypes = Val Double | Total Int deriving Show remotable [ 'dotProductWorker , 'foldWorker ]
SKA-ScienceDataProcessor/RC
MS1/distributed-dot-product/Worker.hs
apache-2.0
2,242
0
16
526
660
342
318
51
3
{-# LANGUAGE TemplateHaskell, QuasiQuotes, OverloadedStrings #-} {-# LANGUAGE NoMonomorphismRestriction #-} module Handler.Root where import Model.Accessor import Foundation import Control.Applicative import Data.Text (Text, pack, unpack) import Text.Blaze import qualified Data.Text as T -- This is a handler function for the GET request method on the HomeR -- resource pattern. All of your resource patterns are defined in -- config/routes -- -- The majority of the code you will write in Yesod lives in these handler -- functions. You can spread them across multiple files if you are so -- inclined, or create a single monolithic file. getHomeR :: Handler RepHtml getHomeR = getPageR "home" -- read getPageR :: Text -> Handler RepHtml getPageR pageName = do page <- runDB $ getPage pageName case page of Nothing -> do redirect RedirectTemporary $ EditR pageName Just (id,page) -> do render <- getUrlRender let body = page `toWidgetWith` render sidebarLayout [whamlet|^{toolbar pageName}^{body}|] -- create & update data YikiPageEdit = YikiPageEdit { peBody :: Textarea } toPageEdit :: YikiPage -> YikiPageEdit toPageEdit yp = YikiPageEdit $ Textarea $ yikiPageBody yp yikiPageEditForm :: Maybe YikiPageEdit -> Html -> Form Yiki Yiki (FormResult YikiPageEdit, Widget) yikiPageEditForm ype = renderDivs $ YikiPageEdit <$> areq textareaField "" (peBody <$> ype) getEditR :: Text -> Handler RepHtml getEditR pageName = do -- result :: Maybe (YikiPageId, YikiPage) result <- runDB $ getPage pageName let edit = case result of Nothing -> YikiPageEdit $ Textarea "" Just (_,page) -> toPageEdit page ((_, widget), enctype) <- generateFormPost $ yikiPageEditForm $ Just edit sidebarLayout [whamlet| <h1>#{unpack pageName} <form method=post action=@{EditR pageName} enctype=#{enctype}> ^{widget} <input type=submit> <a href=@{PageR pageName}>cancel <p> |] postEditR :: Text -> Handler RepHtml postEditR pageName = do ((result, widget), enctype) <- runFormPost $ yikiPageEditForm Nothing case result of FormSuccess ype -> do let body = T.filter (`notElem` "\r") $ unTextarea $ peBody ype runDB $ createOrUpdatePageBody pageName body redirect RedirectTemporary $ PageR pageName _ -> sidebarLayout [whamlet| <p>Invalid input, let's try again. <form method=post action=@{EditR pageName} enctype=#{enctype}> ^{widget} <input type=submit> |] -- delete postDeleteR :: Text -> Handler RepHtml postDeleteR = undefined -- display all articles getIndexR :: Handler RepHtml getIndexR = do pages <- runDB $ getAllPages sidebarLayout [whamlet| <h1>Index <h2> All articles $if null pages No Articles $else <ul> $forall page <- pages <li><a href=@{PageR $ yikiPageName page}>#{yikiPageName page}</a> #{show $ yikiPageCreated page} |] ------------------------------------------------------------ -- Helpers ------------------------------------------------------------ toolbar name = [whamlet| <div .toolbar> <a href=@{EditR name}>edit</a> <a href=@{IndexR}>index</a> |] yikiPageNameField = checkBool validateYikiPageName errorMessage textField where errorMessage :: Text errorMessage = pack $ "Unacceptable page name!" ++ " Available page name must be composed of" ++ " only alphabet and digit." toWidgetWith :: YikiPage -> (YikiRoute -> Text) -> Widget page `toWidgetWith` routeRender = either failure success rendered where body = yikiPageBody page name = yikiPageName page rendered :: Either String String rendered = markdownToHtml routeRender $ unpack body success :: String -> Widget success html = [whamlet|<p>#{preEscapedString html}|] failure :: String -> Widget failure err = [whamlet|<p>#{err}</p><pre>#{body}</pre>|] ------------------------------------------------------------ -- Design ------------------------------------------------------------ sidebarLayout :: Widget -> Handler RepHtml sidebarLayout content = do yikiSidebar <- runDB $ getPage "sidebar" urlRender <- getUrlRender let sidebar = toSidebarWith (snd <$> yikiSidebar) urlRender titleId <- newIdent mainId <- newIdent sidebarId <- newIdent contentId <- newIdent defaultLayout' $ do addCassius [cassius| html height: 100%; body height: 100%; background-color: #EBE1AD; margin: 0; color: #423B0B; header background-color: #666149; color: #FFF; ##{titleId} width: 900px; height: 80px; position: relative; margin: 0 auto; padding-top: 25px; color: #fff; ##{mainId} width: 900px; position: relative; margin: 0 auto; ##{sidebarId} width: 240px; float: right; padding-bottom: 40px; ##{contentId} width: 500px; float: left; text-shadow: 0 1px 0 #fff; padding-bottom: 40px; footer width: 900px; position: relative; margin: 0 auto; clear: both; padding: 30px 0; footer p font-size: 11px; line-height: 18px; text-shadow: 0 1px 0 #fff; h1, h2, h3 color: #221F66; textarea resize: none; font-size: medium; width: 125%; height: 500px; border: 3px solid #cccccc; padding: 5px; font-family: Tahoma, sans-serif; background-position: bottom right; background-repeat: no-repeat; |] addWidget [whamlet| <header> <h1 ##{titleId}>Yiki: a simple wiki <div ##{mainId}> <div ##{contentId}> ^{content} <div ##{sidebarId}> ^{sidebar} |] toSidebarWith :: Maybe YikiPage -> (YikiRoute -> Text) -> Widget page `toSidebarWith` routeRender = maybe redirectWidget (`toWidgetWith` routeRender) page where redirectWidget = [whamlet| hoge |] defaultLayout' :: Widget -> Handler RepHtml defaultLayout' w = do p <- widgetToPageContent w mmsg <- getMessage hamletToRepHtml [hamlet| !!! <html> <head> <title>#{pageTitle p} ^{pageHead p} <body> $maybe msg <- mmsg <p .message>#{msg} ^{pageBody p} <footer> <p> powerd by <a href=http://www.github.com/masaedw/Yiki/>Yiki</a><br/> powerd by <a href=http://www.yesodweb.com/>yesod</a> |]
masaedw/Yiki
Handler/Root.hs
bsd-2-clause
6,292
0
18
1,383
993
525
468
87
2
module P011 where import Arrays run :: IO () run = print . maximum . map product $ groups where groups = concatMap (($ grid) . ($ 4)) [verticalWindow, horizontalWindow, forwardDiagWindow, backwardDiagWindow] grid :: [[Integer]] grid = [[08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91, 08] ,[49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 04, 56, 62, 00] ,[81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 03, 49, 13, 36, 65] ,[52, 70, 95, 23, 04, 60, 11, 42, 69, 24, 68, 56, 01, 32, 56, 71, 37, 02, 36, 91] ,[22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80] ,[24, 47, 32, 60, 99, 03, 45, 02, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50] ,[32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70] ,[67, 26, 20, 68, 02, 62, 12, 20, 95, 63, 94, 39, 63, 08, 40, 91, 66, 49, 94, 21] ,[24, 55, 58, 05, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72] ,[21, 36, 23, 09, 75, 00, 76, 44, 20, 45, 35, 14, 00, 61, 33, 97, 34, 31, 33, 95] ,[78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 03, 80, 04, 62, 16, 14, 09, 53, 56, 92] ,[16, 39, 05, 42, 96, 35, 31, 47, 55, 58, 88, 24, 00, 17, 54, 24, 36, 29, 85, 57] ,[86, 56, 00, 48, 35, 71, 89, 07, 05, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58] ,[19, 80, 81, 68, 05, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 04, 89, 55, 40] ,[04, 52, 08, 83, 97, 35, 99, 16, 07, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66] ,[88, 36, 68, 87, 57, 62, 20, 72, 03, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69] ,[04, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 08, 46, 29, 32, 40, 62, 76, 36] ,[20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 04, 36, 16] ,[20, 73, 35, 29, 78, 31, 90, 01, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 05, 54] ,[01, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 01, 89, 19, 67, 48]]
tyehle/euler-haskell
src/P011.hs
bsd-3-clause
2,018
0
10
579
1,352
894
458
26
1
module GameData.Animation where import qualified Data.List as L import Gamgine.Math.Vect as V data Animation = Animation { currentPosition :: V.Vect, currentVelocity :: V.Vect, velocity :: Double, path :: [V.Vect], bidirectional :: Bool, movingToPathIdx :: Int, finished :: Bool } deriving Show newAnimation :: Double -> [V.Vect] -> Bool -> Animation newAnimation velocity path@(currPos : nextPos : _) bidirectional = Animation currPos currVelo velocity path bidirectional 1 False where currVelo = (V.normalize $ nextPos - currPos) * V.v3 velocity velocity velocity basePosition :: Animation -> V.Vect basePosition = L.head . path setBasePosition :: Animation -> V.Vect -> Animation setBasePosition ani newBase = let (basePt : otherPts) = path ani diffPath = L.map ((-) basePt) otherPts otherPts' = L.map (newBase `plus`) diffPath in newAnimation (velocity ani) (newBase : otherPts') (bidirectional ani) where plus = (+) update :: Animation -> Animation update ani@Animation {finished = True} = ani update ani@Animation {currentPosition = currPos, currentVelocity = currVelo, velocity = velo, path = path, movingToPathIdx = idx} = let nextPos | idx >= L.length path = currPos | otherwise = path !! idx currPos' = currPos + currVelo nextPosReached = V.len (currPos' - nextPos) < 0.1 in if nextPosReached then incrementIdx ani {currentPosition = nextPos} else ani {currentPosition = currPos'} where incrementIdx ani@Animation {currentPosition = currPos, movingToPathIdx = idx, path = path, bidirectional = bidir} = let nextIdx = idx + 1 atEnd = nextIdx >= L.length path in if atEnd then if bidir then newAnimation velo (L.reverse path) bidir else ani {finished = True} else ani {movingToPathIdx = nextIdx, currentVelocity = (V.normalize $ (path !! nextIdx) - currPos) * V.v3 velo velo velo}
dan-t/layers
src/GameData/Animation.hs
bsd-3-clause
2,114
0
17
594
647
360
287
42
4
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-missing-fields #-} {-# OPTIONS_GHC -fno-warn-missing-signatures #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} ----------------------------------------------------------------- -- Autogenerated by Thrift Compiler (0.9.2) -- -- -- -- DO NOT EDIT UNLESS YOU ARE SURE YOU KNOW WHAT YOU ARE DOING -- ----------------------------------------------------------------- module AuroraSchedulerManager_Client(createJob,scheduleCronJob,descheduleCronJob,startCronJob,restartShards,killTasks,addInstances,acquireLock,releaseLock,replaceCronTemplate,startJobUpdate,pauseJobUpdate,resumeJobUpdate,abortJobUpdate,pulseJobUpdate) where import ReadOnlyScheduler_Client import qualified Data.IORef as R import Prelude (($), (.), (>>=), (==), (++)) import qualified Prelude as P import qualified Control.Exception as X import qualified Control.Monad as M ( liftM, ap, when ) import Data.Functor ( (<$>) ) import qualified Data.ByteString.Lazy as LBS import qualified Data.Hashable as H import qualified Data.Int as I import qualified Data.Maybe as M (catMaybes) import qualified Data.Text.Lazy.Encoding as E ( decodeUtf8, encodeUtf8 ) import qualified Data.Text.Lazy as LT import qualified Data.Typeable as TY ( Typeable ) import qualified Data.HashMap.Strict as Map import qualified Data.HashSet as Set import qualified Data.Vector as Vector import qualified Test.QuickCheck.Arbitrary as QC ( Arbitrary(..) ) import qualified Test.QuickCheck as QC ( elements ) import qualified Thrift as T import qualified Thrift.Types as T import qualified Thrift.Arbitraries as T import Api_Types import AuroraSchedulerManager seqid = R.newIORef 0 createJob (ip,op) arg_description arg_lock arg_session = do send_createJob op arg_description arg_lock arg_session recv_createJob ip send_createJob op arg_description arg_lock arg_session = do seq <- seqid seqn <- R.readIORef seq T.writeMessageBegin op ("createJob", T.M_CALL, seqn) write_CreateJob_args op (CreateJob_args{createJob_args_description=arg_description,createJob_args_lock=arg_lock,createJob_args_session=arg_session}) T.writeMessageEnd op T.tFlush (T.getTransport op) recv_createJob ip = do (fname, mtype, rseqid) <- T.readMessageBegin ip M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn } res <- read_CreateJob_result ip T.readMessageEnd ip P.return $ createJob_result_success res scheduleCronJob (ip,op) arg_description arg_lock arg_session = do send_scheduleCronJob op arg_description arg_lock arg_session recv_scheduleCronJob ip send_scheduleCronJob op arg_description arg_lock arg_session = do seq <- seqid seqn <- R.readIORef seq T.writeMessageBegin op ("scheduleCronJob", T.M_CALL, seqn) write_ScheduleCronJob_args op (ScheduleCronJob_args{scheduleCronJob_args_description=arg_description,scheduleCronJob_args_lock=arg_lock,scheduleCronJob_args_session=arg_session}) T.writeMessageEnd op T.tFlush (T.getTransport op) recv_scheduleCronJob ip = do (fname, mtype, rseqid) <- T.readMessageBegin ip M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn } res <- read_ScheduleCronJob_result ip T.readMessageEnd ip P.return $ scheduleCronJob_result_success res descheduleCronJob (ip,op) arg_job arg_lock arg_session = do send_descheduleCronJob op arg_job arg_lock arg_session recv_descheduleCronJob ip send_descheduleCronJob op arg_job arg_lock arg_session = do seq <- seqid seqn <- R.readIORef seq T.writeMessageBegin op ("descheduleCronJob", T.M_CALL, seqn) write_DescheduleCronJob_args op (DescheduleCronJob_args{descheduleCronJob_args_job=arg_job,descheduleCronJob_args_lock=arg_lock,descheduleCronJob_args_session=arg_session}) T.writeMessageEnd op T.tFlush (T.getTransport op) recv_descheduleCronJob ip = do (fname, mtype, rseqid) <- T.readMessageBegin ip M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn } res <- read_DescheduleCronJob_result ip T.readMessageEnd ip P.return $ descheduleCronJob_result_success res startCronJob (ip,op) arg_job arg_session = do send_startCronJob op arg_job arg_session recv_startCronJob ip send_startCronJob op arg_job arg_session = do seq <- seqid seqn <- R.readIORef seq T.writeMessageBegin op ("startCronJob", T.M_CALL, seqn) write_StartCronJob_args op (StartCronJob_args{startCronJob_args_job=arg_job,startCronJob_args_session=arg_session}) T.writeMessageEnd op T.tFlush (T.getTransport op) recv_startCronJob ip = do (fname, mtype, rseqid) <- T.readMessageBegin ip M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn } res <- read_StartCronJob_result ip T.readMessageEnd ip P.return $ startCronJob_result_success res restartShards (ip,op) arg_job arg_shardIds arg_lock arg_session = do send_restartShards op arg_job arg_shardIds arg_lock arg_session recv_restartShards ip send_restartShards op arg_job arg_shardIds arg_lock arg_session = do seq <- seqid seqn <- R.readIORef seq T.writeMessageBegin op ("restartShards", T.M_CALL, seqn) write_RestartShards_args op (RestartShards_args{restartShards_args_job=arg_job,restartShards_args_shardIds=arg_shardIds,restartShards_args_lock=arg_lock,restartShards_args_session=arg_session}) T.writeMessageEnd op T.tFlush (T.getTransport op) recv_restartShards ip = do (fname, mtype, rseqid) <- T.readMessageBegin ip M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn } res <- read_RestartShards_result ip T.readMessageEnd ip P.return $ restartShards_result_success res killTasks (ip,op) arg_query arg_lock arg_session = do send_killTasks op arg_query arg_lock arg_session recv_killTasks ip send_killTasks op arg_query arg_lock arg_session = do seq <- seqid seqn <- R.readIORef seq T.writeMessageBegin op ("killTasks", T.M_CALL, seqn) write_KillTasks_args op (KillTasks_args{killTasks_args_query=arg_query,killTasks_args_lock=arg_lock,killTasks_args_session=arg_session}) T.writeMessageEnd op T.tFlush (T.getTransport op) recv_killTasks ip = do (fname, mtype, rseqid) <- T.readMessageBegin ip M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn } res <- read_KillTasks_result ip T.readMessageEnd ip P.return $ killTasks_result_success res addInstances (ip,op) arg_config arg_lock arg_session = do send_addInstances op arg_config arg_lock arg_session recv_addInstances ip send_addInstances op arg_config arg_lock arg_session = do seq <- seqid seqn <- R.readIORef seq T.writeMessageBegin op ("addInstances", T.M_CALL, seqn) write_AddInstances_args op (AddInstances_args{addInstances_args_config=arg_config,addInstances_args_lock=arg_lock,addInstances_args_session=arg_session}) T.writeMessageEnd op T.tFlush (T.getTransport op) recv_addInstances ip = do (fname, mtype, rseqid) <- T.readMessageBegin ip M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn } res <- read_AddInstances_result ip T.readMessageEnd ip P.return $ addInstances_result_success res acquireLock (ip,op) arg_lockKey arg_session = do send_acquireLock op arg_lockKey arg_session recv_acquireLock ip send_acquireLock op arg_lockKey arg_session = do seq <- seqid seqn <- R.readIORef seq T.writeMessageBegin op ("acquireLock", T.M_CALL, seqn) write_AcquireLock_args op (AcquireLock_args{acquireLock_args_lockKey=arg_lockKey,acquireLock_args_session=arg_session}) T.writeMessageEnd op T.tFlush (T.getTransport op) recv_acquireLock ip = do (fname, mtype, rseqid) <- T.readMessageBegin ip M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn } res <- read_AcquireLock_result ip T.readMessageEnd ip P.return $ acquireLock_result_success res releaseLock (ip,op) arg_lock arg_validation arg_session = do send_releaseLock op arg_lock arg_validation arg_session recv_releaseLock ip send_releaseLock op arg_lock arg_validation arg_session = do seq <- seqid seqn <- R.readIORef seq T.writeMessageBegin op ("releaseLock", T.M_CALL, seqn) write_ReleaseLock_args op (ReleaseLock_args{releaseLock_args_lock=arg_lock,releaseLock_args_validation=arg_validation,releaseLock_args_session=arg_session}) T.writeMessageEnd op T.tFlush (T.getTransport op) recv_releaseLock ip = do (fname, mtype, rseqid) <- T.readMessageBegin ip M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn } res <- read_ReleaseLock_result ip T.readMessageEnd ip P.return $ releaseLock_result_success res replaceCronTemplate (ip,op) arg_config arg_lock arg_session = do send_replaceCronTemplate op arg_config arg_lock arg_session recv_replaceCronTemplate ip send_replaceCronTemplate op arg_config arg_lock arg_session = do seq <- seqid seqn <- R.readIORef seq T.writeMessageBegin op ("replaceCronTemplate", T.M_CALL, seqn) write_ReplaceCronTemplate_args op (ReplaceCronTemplate_args{replaceCronTemplate_args_config=arg_config,replaceCronTemplate_args_lock=arg_lock,replaceCronTemplate_args_session=arg_session}) T.writeMessageEnd op T.tFlush (T.getTransport op) recv_replaceCronTemplate ip = do (fname, mtype, rseqid) <- T.readMessageBegin ip M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn } res <- read_ReplaceCronTemplate_result ip T.readMessageEnd ip P.return $ replaceCronTemplate_result_success res startJobUpdate (ip,op) arg_request arg_session = do send_startJobUpdate op arg_request arg_session recv_startJobUpdate ip send_startJobUpdate op arg_request arg_session = do seq <- seqid seqn <- R.readIORef seq T.writeMessageBegin op ("startJobUpdate", T.M_CALL, seqn) write_StartJobUpdate_args op (StartJobUpdate_args{startJobUpdate_args_request=arg_request,startJobUpdate_args_session=arg_session}) T.writeMessageEnd op T.tFlush (T.getTransport op) recv_startJobUpdate ip = do (fname, mtype, rseqid) <- T.readMessageBegin ip M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn } res <- read_StartJobUpdate_result ip T.readMessageEnd ip P.return $ startJobUpdate_result_success res pauseJobUpdate (ip,op) arg_jobKey arg_session = do send_pauseJobUpdate op arg_jobKey arg_session recv_pauseJobUpdate ip send_pauseJobUpdate op arg_jobKey arg_session = do seq <- seqid seqn <- R.readIORef seq T.writeMessageBegin op ("pauseJobUpdate", T.M_CALL, seqn) write_PauseJobUpdate_args op (PauseJobUpdate_args{pauseJobUpdate_args_jobKey=arg_jobKey,pauseJobUpdate_args_session=arg_session}) T.writeMessageEnd op T.tFlush (T.getTransport op) recv_pauseJobUpdate ip = do (fname, mtype, rseqid) <- T.readMessageBegin ip M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn } res <- read_PauseJobUpdate_result ip T.readMessageEnd ip P.return $ pauseJobUpdate_result_success res resumeJobUpdate (ip,op) arg_jobKey arg_session = do send_resumeJobUpdate op arg_jobKey arg_session recv_resumeJobUpdate ip send_resumeJobUpdate op arg_jobKey arg_session = do seq <- seqid seqn <- R.readIORef seq T.writeMessageBegin op ("resumeJobUpdate", T.M_CALL, seqn) write_ResumeJobUpdate_args op (ResumeJobUpdate_args{resumeJobUpdate_args_jobKey=arg_jobKey,resumeJobUpdate_args_session=arg_session}) T.writeMessageEnd op T.tFlush (T.getTransport op) recv_resumeJobUpdate ip = do (fname, mtype, rseqid) <- T.readMessageBegin ip M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn } res <- read_ResumeJobUpdate_result ip T.readMessageEnd ip P.return $ resumeJobUpdate_result_success res abortJobUpdate (ip,op) arg_jobKey arg_session = do send_abortJobUpdate op arg_jobKey arg_session recv_abortJobUpdate ip send_abortJobUpdate op arg_jobKey arg_session = do seq <- seqid seqn <- R.readIORef seq T.writeMessageBegin op ("abortJobUpdate", T.M_CALL, seqn) write_AbortJobUpdate_args op (AbortJobUpdate_args{abortJobUpdate_args_jobKey=arg_jobKey,abortJobUpdate_args_session=arg_session}) T.writeMessageEnd op T.tFlush (T.getTransport op) recv_abortJobUpdate ip = do (fname, mtype, rseqid) <- T.readMessageBegin ip M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn } res <- read_AbortJobUpdate_result ip T.readMessageEnd ip P.return $ abortJobUpdate_result_success res pulseJobUpdate (ip,op) arg_updateId arg_session = do send_pulseJobUpdate op arg_updateId arg_session recv_pulseJobUpdate ip send_pulseJobUpdate op arg_updateId arg_session = do seq <- seqid seqn <- R.readIORef seq T.writeMessageBegin op ("pulseJobUpdate", T.M_CALL, seqn) write_PulseJobUpdate_args op (PulseJobUpdate_args{pulseJobUpdate_args_updateId=arg_updateId,pulseJobUpdate_args_session=arg_session}) T.writeMessageEnd op T.tFlush (T.getTransport op) recv_pulseJobUpdate ip = do (fname, mtype, rseqid) <- T.readMessageBegin ip M.when (mtype == T.M_EXCEPTION) $ do { exn <- T.readAppExn ip ; T.readMessageEnd ip ; X.throw exn } res <- read_PulseJobUpdate_result ip T.readMessageEnd ip P.return $ pulseJobUpdate_result_success res
futufeld/eclogues
eclogues-impl/gen-hs/AuroraSchedulerManager_Client.hs
bsd-3-clause
13,610
0
12
1,836
4,134
2,051
2,083
273
1
module Main where import Lib main :: IO () main = tokenizerMain
NogikuchiKBYS/hsit-sandbox
app/Tokenizer.hs
bsd-3-clause
67
0
6
15
22
13
9
4
1
{-# LANGUAGE TypeOperators, ScopedTypeVariables #-} -- | -- Module : Data.Array.Accelerate.Prelude -- Copyright : [2010..2011] Manuel M T Chakravarty, Gabriele Keller, Ben Lever -- [2009..2012] Manuel M T Chakravarty, Gabriele Keller, Trevor L. McDonell -- License : BSD3 -- -- Maintainer : Manuel M T Chakravarty <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Standard functions that are not part of the core set (directly represented in the AST), but are -- instead implemented in terms of the core set. -- module Data.Array.Accelerate.Prelude ( -- * Zipping zipWith3, zipWith4, zip, zip3, zip4, -- * Unzipping unzip, unzip3, unzip4, -- * Reductions foldAll, fold1All, -- ** Specialised folds all, any, and, or, sum, product, minimum, maximum, -- * Scans prescanl, postscanl, prescanr, postscanr, -- ** Segmented scans scanlSeg, scanl'Seg, scanl1Seg, prescanlSeg, postscanlSeg, scanrSeg, scanr'Seg, scanr1Seg, prescanrSeg, postscanrSeg, -- * Shape manipulation flatten, -- * Enumeration and filling fill, enumFromN, enumFromStepN, -- * Working with predicates -- ** Filtering filter, -- ** Scatter / Gather scatter, scatterIf, gather, gatherIf, -- * Permutations reverse, transpose, -- * Extracting sub-vectors init, tail, take, drop, slit ) where -- avoid clashes with Prelude functions -- import Data.Bits import Data.Bool import Prelude ((.), ($), (+), (-), (*), const, subtract, id) import qualified Prelude as P -- friends import Data.Array.Accelerate.Array.Sugar hiding ((!), ignore, shape, size) import Data.Array.Accelerate.Language import Data.Array.Accelerate.Smart import Data.Array.Accelerate.Type -- Map-like composites -- ------------------- -- | Zip three arrays with the given function -- zipWith3 :: (Shape sh, Elt a, Elt b, Elt c, Elt d) => (Exp a -> Exp b -> Exp c -> Exp d) -> Acc (Array sh a) -> Acc (Array sh b) -> Acc (Array sh c) -> Acc (Array sh d) zipWith3 f as bs cs = map (\x -> let (a,b,c) = unlift x in f a b c) $ zip3 as bs cs -- | Zip four arrays with the given function -- zipWith4 :: (Shape sh, Elt a, Elt b, Elt c, Elt d, Elt e) => (Exp a -> Exp b -> Exp c -> Exp d -> Exp e) -> Acc (Array sh a) -> Acc (Array sh b) -> Acc (Array sh c) -> Acc (Array sh d) -> Acc (Array sh e) zipWith4 f as bs cs ds = map (\x -> let (a,b,c,d) = unlift x in f a b c d) $ zip4 as bs cs ds -- | Combine the elements of two arrays pairwise. The shape of the result is -- the intersection of the two argument shapes. -- zip :: (Shape sh, Elt a, Elt b) => Acc (Array sh a) -> Acc (Array sh b) -> Acc (Array sh (a, b)) zip = zipWith (curry lift) -- | Take three arrays and return an array of triples, analogous to zip. -- zip3 :: forall sh. forall a. forall b. forall c. (Shape sh, Elt a, Elt b, Elt c) => Acc (Array sh a) -> Acc (Array sh b) -> Acc (Array sh c) -> Acc (Array sh (a, b, c)) zip3 as bs cs = zipWith (\a bc -> let (b, c) = unlift bc :: (Exp b, Exp c) in lift (a, b, c)) as $ zip bs cs -- | Take four arrays and return an array of quadruples, analogous to zip. -- zip4 :: forall sh. forall a. forall b. forall c. forall d. (Shape sh, Elt a, Elt b, Elt c, Elt d) => Acc (Array sh a) -> Acc (Array sh b) -> Acc (Array sh c) -> Acc (Array sh d) -> Acc (Array sh (a, b, c, d)) zip4 as bs cs ds = zipWith (\a bcd -> let (b, c, d) = unlift bcd :: (Exp b, Exp c, Exp d) in lift (a, b, c, d)) as $ zip3 bs cs ds -- | The converse of 'zip', but the shape of the two results is identical to the -- shape of the argument. -- unzip :: (Shape sh, Elt a, Elt b) => Acc (Array sh (a, b)) -> (Acc (Array sh a), Acc (Array sh b)) unzip arr = (map fst arr, map snd arr) -- | Take an array of triples and return three arrays, analogous to unzip. -- unzip3 :: (Shape sh, Elt a, Elt b, Elt c) => Acc (Array sh (a, b, c)) -> (Acc (Array sh a), Acc (Array sh b), Acc (Array sh c)) unzip3 xs = (map get1 xs, map get2 xs, map get3 xs) where get1 :: forall a b c. (Elt a, Elt b, Elt c) => Exp (a,b,c) -> Exp a get1 x = let (a, _ :: Exp b, _ :: Exp c) = unlift x in a get2 :: forall a b c. (Elt a, Elt b, Elt c) => Exp (a,b,c) -> Exp b get2 x = let (_ :: Exp a, b, _ :: Exp c) = unlift x in b get3 :: forall a b c. (Elt a, Elt b, Elt c) => Exp (a,b,c) -> Exp c get3 x = let (_ :: Exp a, _ :: Exp b, c) = unlift x in c -- | Take an array of quadruples and return four arrays, analogous to unzip. -- unzip4 :: (Shape sh, Elt a, Elt b, Elt c, Elt d) => Acc (Array sh (a, b, c, d)) -> (Acc (Array sh a), Acc (Array sh b), Acc (Array sh c), Acc (Array sh d)) unzip4 xs = (map get1 xs, map get2 xs, map get3 xs, map get4 xs) where get1 :: forall a b c d. (Elt a, Elt b, Elt c, Elt d) => Exp (a,b,c,d) -> Exp a get1 x = let (a, _ :: Exp b, _ :: Exp c, _ :: Exp d) = unlift x in a get2 :: forall a b c d. (Elt a, Elt b, Elt c, Elt d) => Exp (a,b,c,d) -> Exp b get2 x = let (_ :: Exp a, b, _ :: Exp c, _ :: Exp d) = unlift x in b get3 :: forall a b c d. (Elt a, Elt b, Elt c, Elt d) => Exp (a,b,c,d) -> Exp c get3 x = let (_ :: Exp a, _ :: Exp b, c, _ :: Exp d) = unlift x in c get4 :: forall a b c d. (Elt a, Elt b, Elt c, Elt d) => Exp (a,b,c,d) -> Exp d get4 x = let (_ :: Exp a, _ :: Exp b, _ :: Exp c, d) = unlift x in d -- Reductions -- ---------- -- | Reduction of an array of arbitrary rank to a single scalar value. -- foldAll :: (Shape sh, Elt a) => (Exp a -> Exp a -> Exp a) -> Exp a -> Acc (Array sh a) -> Acc (Scalar a) foldAll f e arr = fold f e (flatten arr) -- | Variant of 'foldAll' that requires the reduced array to be non-empty and -- doesn't need an default value. -- fold1All :: (Shape sh, Elt a) => (Exp a -> Exp a -> Exp a) -> Acc (Array sh a) -> Acc (Scalar a) fold1All f arr = fold1 f (flatten arr) -- Specialised reductions -- ---------------------- -- -- Leave the results of these as scalar arrays to make it clear that these are -- array computations, and thus can not be nested. -- | Check if all elements satisfy a predicate -- all :: (Shape sh, Elt e) => (Exp e -> Exp Bool) -> Acc (Array sh e) -> Acc (Scalar Bool) all f = and . map f -- | Check if any element satisfies the predicate -- any :: (Shape sh, Elt e) => (Exp e -> Exp Bool) -> Acc (Array sh e) -> Acc (Scalar Bool) any f = or . map f -- | Check if all elements are 'True' -- and :: Shape sh => Acc (Array sh Bool) -> Acc (Scalar Bool) and = foldAll (&&*) (constant True) -- | Check if any element is 'True' -- or :: Shape sh => Acc (Array sh Bool) -> Acc (Scalar Bool) or = foldAll (||*) (constant False) -- | Compute the sum of elements -- sum :: (Shape sh, Elt e, IsNum e) => Acc (Array sh e) -> Acc (Scalar e) sum = foldAll (+) 0 -- | Compute the product of the elements -- product :: (Shape sh, Elt e, IsNum e) => Acc (Array sh e) -> Acc (Scalar e) product = foldAll (*) 1 -- | Yield the minimum element of an array. The array must not be empty. -- minimum :: (Shape sh, Elt e, IsScalar e) => Acc (Array sh e) -> Acc (Scalar e) minimum = fold1All min -- | Yield the maximum element of an array. The array must not be empty. -- maximum :: (Shape sh, Elt e, IsScalar e) => Acc (Array sh e) -> Acc (Scalar e) maximum = fold1All max -- Composite scans -- --------------- -- |Left-to-right prescan (aka exclusive scan). As for 'scan', the first argument must be an -- /associative/ function. Denotationally, we have -- -- > prescanl f e = Prelude.fst . scanl' f e -- prescanl :: Elt a => (Exp a -> Exp a -> Exp a) -> Exp a -> Acc (Vector a) -> Acc (Vector a) prescanl f e = P.fst . scanl' f e -- |Left-to-right postscan, a variant of 'scanl1' with an initial value. Denotationally, we have -- -- > postscanl f e = map (e `f`) . scanl1 f -- postscanl :: Elt a => (Exp a -> Exp a -> Exp a) -> Exp a -> Acc (Vector a) -> Acc (Vector a) postscanl f e = map (e `f`) . scanl1 f -- |Right-to-left prescan (aka exclusive scan). As for 'scan', the first argument must be an -- /associative/ function. Denotationally, we have -- -- > prescanr f e = Prelude.fst . scanr' f e -- prescanr :: Elt a => (Exp a -> Exp a -> Exp a) -> Exp a -> Acc (Vector a) -> Acc (Vector a) prescanr f e = P.fst . scanr' f e -- |Right-to-left postscan, a variant of 'scanr1' with an initial value. Denotationally, we have -- -- > postscanr f e = map (e `f`) . scanr1 f -- postscanr :: Elt a => (Exp a -> Exp a -> Exp a) -> Exp a -> Acc (Vector a) -> Acc (Vector a) postscanr f e = map (`f` e) . scanr1 f -- Segmented scans -- --------------- -- |Segmented version of 'scanl' -- scanlSeg :: (Elt a, Elt i, IsIntegral i) => (Exp a -> Exp a -> Exp a) -> Exp a -> Acc (Vector a) -> Acc (Segments i) -> Acc (Vector a) scanlSeg f z vec seg = scanl1Seg f vec' seg' where -- Segmented exclusive scan is implemented by first injecting the seed -- element at the head of each segment, and then performing a segmented -- inclusive scan. -- -- This is done by creating a creating a vector entirely of the seed -- element, and overlaying the input data in all places other than at the -- start of a segment. -- seg' = map (+1) seg vec' = permute const (fill (index1 $ size vec + size seg) z) (\ix -> index1' $ unindex1' ix + inc ! ix) vec -- Each element in the segments must be shifted to the right one additional -- place for each successive segment, to make room for the seed element. -- Here, we make use of the fact that the vector returned by 'mkHeadFlags' -- contains non-unit entries, which indicate zero length segments. -- flags = mkHeadFlags seg inc = scanl1 (+) flags -- |Segmented version of 'scanl'' -- -- The first element of the resulting tuple is a vector of scanned values. The -- second element is a vector of segment scan totals and has the same size as -- the segment vector. -- scanl'Seg :: forall a i. (Elt a, Elt i, IsIntegral i) => (Exp a -> Exp a -> Exp a) -> Exp a -> Acc (Vector a) -> Acc (Segments i) -> Acc (Vector a, Vector a) scanl'Seg f z vec seg = result where -- Returned the result combined, so that the sub-calculations are shared -- should the user require both results. -- result = lift (body, sums) -- Segmented scan' is implemented by deconstructing a segmented exclusive -- scan, to separate the final value and scan body. -- -- TLM: Segmented scans, and this version in particular, expend a lot of -- effort scanning flag arrays. On inspection it appears that several -- of these operations are duplicated, but this will not be picked up -- by sharing _observation_. Perhaps a global CSE-style pass would be -- beneficial. -- vec' = scanlSeg f z vec seg -- Extract the final reduction value for each segment, which is at the last -- index of each segment. -- seg' = map (+1) seg tails = zipWith (+) seg . P.fst $ scanl' (+) 0 seg' sums = backpermute (shape seg) (\ix -> index1' $ tails ! ix) vec' -- Slice out the body of each segment. -- -- Build a head-flags representation based on the original segment -- descriptor. This contains the target length of each of the body segments, -- which is one fewer element than the actual bodies stored in vec'. Thus, -- the flags align with the last element of each body section, and when -- scanned, this element will be incremented over. -- offset = scanl1 (+) seg inc = scanl1 (+) $ permute (+) (fill (index1 $ size vec + 1) 0) (\ix -> index1' $ offset ! ix) (fill (shape seg) (1 :: Exp i)) body = backpermute (shape vec) (\ix -> index1' $ unindex1' ix + inc ! ix) vec' -- |Segmented version of 'scanl1'. -- scanl1Seg :: (Elt a, Elt i, IsIntegral i) => (Exp a -> Exp a -> Exp a) -> Acc (Vector a) -> Acc (Segments i) -> Acc (Vector a) scanl1Seg f vec seg = P.snd . unzip . scanl1 (segmented f) $ zip (mkHeadFlags seg) vec -- |Segmented version of 'prescanl'. -- prescanlSeg :: (Elt a, Elt i, IsIntegral i) => (Exp a -> Exp a -> Exp a) -> Exp a -> Acc (Vector a) -> Acc (Segments i) -> Acc (Vector a) prescanlSeg f e vec seg = P.fst . unatup2 $ scanl'Seg f e vec seg -- |Segmented version of 'postscanl'. -- postscanlSeg :: (Elt a, Elt i, IsIntegral i) => (Exp a -> Exp a -> Exp a) -> Exp a -> Acc (Vector a) -> Acc (Segments i) -> Acc (Vector a) postscanlSeg f e vec seg = map (f e) $ scanl1Seg f vec seg -- |Segmented version of 'scanr'. -- scanrSeg :: (Elt a, Elt i, IsIntegral i) => (Exp a -> Exp a -> Exp a) -> Exp a -> Acc (Vector a) -> Acc (Segments i) -> Acc (Vector a) scanrSeg f z vec seg = scanr1Seg f vec' seg' where -- Using technique described for 'scanlSeg', where we intersperse the array -- with the seed element at the start of each segment, and then perform an -- inclusive segmented scan. -- inc = scanl1 (+) (mkHeadFlags seg) seg' = map (+1) seg vec' = permute const (fill (index1 $ size vec + size seg) z) (\ix -> index1' $ unindex1' ix + inc ! ix - 1) vec -- | Segmented version of 'scanr''. -- scanr'Seg :: forall a i. (Elt a, Elt i, IsIntegral i) => (Exp a -> Exp a -> Exp a) -> Exp a -> Acc (Vector a) -> Acc (Segments i) -> Acc (Vector a, Vector a) scanr'Seg f z vec seg = result where -- Using technique described for scanl'Seg -- result = lift (body, sums) vec' = scanrSeg f z vec seg -- reduction values seg' = map (+1) seg heads = P.fst $ scanl' (+) 0 seg' sums = backpermute (shape seg) (\ix -> index1' $ heads ! ix) vec' -- body segments inc = scanl1 (+) $ mkHeadFlags seg body = backpermute (shape vec) (\ix -> index1' $ unindex1' ix + inc ! ix) vec' -- |Segmented version of 'scanr1'. -- scanr1Seg :: (Elt a, Elt i, IsIntegral i) => (Exp a -> Exp a -> Exp a) -> Acc (Vector a) -> Acc (Segments i) -> Acc (Vector a) scanr1Seg f vec seg = P.snd . unzip . scanr1 (segmented f) $ zip (mkTailFlags seg) vec -- |Segmented version of 'prescanr'. -- prescanrSeg :: (Elt a, Elt i, IsIntegral i) => (Exp a -> Exp a -> Exp a) -> Exp a -> Acc (Vector a) -> Acc (Segments i) -> Acc (Vector a) prescanrSeg f e vec seg = P.fst . unatup2 $ scanr'Seg f e vec seg -- |Segmented version of 'postscanr'. -- postscanrSeg :: (Elt a, Elt i, IsIntegral i) => (Exp a -> Exp a -> Exp a) -> Exp a -> Acc (Vector a) -> Acc (Segments i) -> Acc (Vector a) postscanrSeg f e vec seg = map (f e) $ scanr1Seg f vec seg -- Segmented scan helpers -- ---------------------- -- |Compute head flags vector from segment vector for left-scans. -- -- The vector will be full of zeros in the body of a segment, and non-zero -- otherwise. The "flag" value, if greater than one, indicates that several -- empty segments are represented by this single flag entry. This is additional -- data is used by exclusive segmented scan. -- mkHeadFlags :: (Elt i, IsIntegral i) => Acc (Segments i) -> Acc (Segments i) mkHeadFlags seg = init $ permute (+) zeros (\ix -> index1' (offset ! ix)) ones where (offset, len) = scanl' (+) 0 seg zeros = fill (index1' $ the len + 1) 0 ones = fill (index1 $ size offset) 1 -- |Compute tail flags vector from segment vector for right-scans. That is, the -- flag is placed at the last place in each segment. -- mkTailFlags :: (Elt i, IsIntegral i) => Acc (Segments i) -> Acc (Segments i) mkTailFlags seg = init $ permute (+) zeros (\ix -> index1' (the len - 1 - offset ! ix)) ones where (offset, len) = scanr' (+) 0 seg zeros = fill (index1' $ the len + 1) 0 ones = fill (index1 $ size offset) 1 -- |Construct a segmented version of a function from a non-segmented version. -- The segmented apply operates on a head-flag value tuple, and follows the -- procedure of Sengupta et. al. -- segmented :: (Elt e, Elt i, IsIntegral i) => (Exp e -> Exp e -> Exp e) -> Exp (i, e) -> Exp (i, e) -> Exp (i, e) segmented f a b = let (aF, aV) = unlift a (bF, bV) = unlift b in lift (aF .|. bF, bF /=* 0 ? (bV, f aV bV)) -- |Index construction and destruction generalised to integral types. -- -- We generalise the segment descriptor to integral types because some -- architectures, such as GPUs, have poor performance for 64-bit types. So, -- there is a tension between performance and requiring 64-bit indices for some -- applications, and we would not like to restrict ourselves to either one. -- -- As we don't yet support non-Int dimensions in shapes, we will need to convert -- back to concrete Int. However, don't put these generalised forms into the -- base library, because it results in too many ambiguity errors. -- index1' :: (Elt i, IsIntegral i) => Exp i -> Exp DIM1 index1' i = lift (Z :. fromIntegral i) unindex1' :: (Elt i, IsIntegral i) => Exp DIM1 -> Exp i unindex1' ix = let Z :. i = unlift ix in fromIntegral i -- Reshaping of arrays -- ------------------- -- | Flattens a given array of arbitrary dimension. -- flatten :: (Shape ix, Elt a) => Acc (Array ix a) -> Acc (Vector a) flatten a = reshape (index1 $ size a) a -- Enumeration and filling -- ----------------------- -- | Create an array where all elements are the same value. -- fill :: (Shape sh, Elt e) => Exp sh -> Exp e -> Acc (Array sh e) fill sh c = generate sh (const c) -- | Create an array of the given shape containing the values x, x+1, etc (in -- row-major order). -- enumFromN :: (Shape sh, Elt e, IsNum e) => Exp sh -> Exp e -> Acc (Array sh e) enumFromN sh x = enumFromStepN sh x 1 -- | Create an array of the given shape containing the values @x@, @x+y@, -- @x+y+y@ etc. (in row-major order). -- enumFromStepN :: (Shape sh, Elt e, IsNum e) => Exp sh -> Exp e -- ^ x: start -> Exp e -- ^ y: step -> Acc (Array sh e) enumFromStepN sh x y = reshape sh $ generate (index1 $ shapeSize sh) (\ix -> (fromIntegral (unindex1 ix :: Exp Int) * y) + x) -- Filtering -- --------- -- | Drop elements that do not satisfy the predicate -- filter :: Elt a => (Exp a -> Exp Bool) -> Acc (Vector a) -> Acc (Vector a) filter p arr = let flags = map (boolToInt . p) arr (targetIdx, len) = scanl' (+) 0 flags arr' = backpermute (index1 $ the len) id arr in permute const arr' (\ix -> flags!ix ==* 0 ? (ignore, index1 $ targetIdx!ix)) arr -- FIXME: This is abusing 'permute' in that the first two arguments are -- only justified because we know the permutation function will -- write to each location in the target exactly once. -- Instead, we should have a primitive that directly encodes the -- compaction pattern of the permutation function. {-# RULES "ACC filter/filter" forall f g arr. filter f (filter g arr) = filter (\x -> g x &&* f x) arr #-} -- Gather operations -- ----------------- -- | Copy elements from source array to destination array according to a map. This -- is a backpermute operation where a 'map' vector encodes the ouput to input -- index mapping. -- -- For example: -- -- > input = [1, 9, 6, 4, 4, 2, 0, 1, 2] -- > map = [1, 3, 7, 2, 5, 3] -- > -- > output = [9, 4, 1, 6, 2, 4] -- gather :: (Elt e) => Acc (Vector Int) -- ^map -> Acc (Vector e) -- ^input -> Acc (Vector e) -- ^output gather mapV inputV = backpermute (shape mapV) bpF inputV where bpF ix = lift (Z :. (mapV ! ix)) -- | Conditionally copy elements from source array to destination array according -- to a map. This is a backpermute opereation where a 'map' vector encdes the -- output to input index mapping. In addition, there is a 'mask' vector, and an -- associated predication function, that specifies whether an element will be -- copied. If not copied, the output array assumes the default vector's value. -- -- For example: -- -- > default = [6, 6, 6, 6, 6, 6] -- > map = [1, 3, 7, 2, 5, 3] -- > mask = [3, 4, 9, 2, 7, 5] -- > pred = (> 4) -- > input = [1, 9, 6, 4, 4, 2, 0, 1, 2] -- > -- > output = [6, 6, 1, 6, 2, 4] -- gatherIf :: (Elt e, Elt e') => Acc (Vector Int) -- ^map -> Acc (Vector e) -- ^mask -> (Exp e -> Exp Bool) -- ^predicate -> Acc (Vector e') -- ^default -> Acc (Vector e') -- ^input -> Acc (Vector e') -- ^output gatherIf mapV maskV pred defaultV inputV = zipWith zwF predV gatheredV where zwF p g = p ? (unlift g) gatheredV = zip (gather mapV inputV) defaultV predV = map pred maskV -- Scatter operations -- ------------------ -- | Copy elements from source array to destination array according to a map. This -- is a forward-permute operation where a 'map' vector encodes an input to output -- index mapping. Output elements for indices that are not mapped assume the -- default vector's value. -- -- For example: -- -- > default = [0, 0, 0, 0, 0, 0, 0, 0, 0] -- > map = [1, 3, 7, 2, 5, 8] -- > input = [1, 9, 6, 4, 4, 2, 5] -- > -- > output = [0, 1, 4, 9, 0, 4, 0, 6, 2] -- -- Note if the same index appears in the map more than once, the result is -- undefined. The map vector cannot be larger than the input vector. -- scatter :: (Elt e) => Acc (Vector Int) -- ^map -> Acc (Vector e) -- ^default -> Acc (Vector e) -- ^input -> Acc (Vector e) -- ^output scatter mapV defaultV inputV = permute (const) defaultV pF inputV where pF ix = lift (Z :. (mapV ! ix)) -- | Conditionally copy elements from source array to destination array according -- to a map. This is a forward-permute operation where a 'map' vector encodes an -- input to output index mapping. In addition, there is a 'mask' vector, and an -- associated predicate function, that specifies whether an elements will be -- copied. If not copied, the output array assumes the default vector's value. -- -- For example: -- -- > default = [0, 0, 0, 0, 0, 0, 0, 0, 0] -- > map = [1, 3, 7, 2, 5, 8] -- > mask = [3, 4, 9, 2, 7, 5] -- > pred = (> 4) -- > input = [1, 9, 6, 4, 4, 2] -- > -- > output = [0, 0, 0, 0, 0, 4, 0, 6, 2] -- -- Note if the same index appears in the map more than once, the result is -- undefined. The map and input vector must be of the same length. -- scatterIf :: (Elt e, Elt e') => Acc (Vector Int) -- ^map -> Acc (Vector e) -- ^mask -> (Exp e -> Exp Bool) -- ^predicate -> Acc (Vector e') -- ^default -> Acc (Vector e') -- ^input -> Acc (Vector e') -- ^output scatterIf mapV maskV pred defaultV inputV = permute const defaultV pF inputV where pF ix = (pred (maskV ! ix)) ? (lift (Z :. (mapV ! ix)), ignore) -- Permutations -- ------------ -- | Reverse the elements of a vector. -- reverse :: Elt e => Acc (Vector e) -> Acc (Vector e) reverse xs = let len = unindex1 (shape xs) pf i = len - i - 1 in backpermute (shape xs) (ilift1 pf) xs -- | Transpose the rows and columns of a matrix. -- transpose :: Elt e => Acc (Array DIM2 e) -> Acc (Array DIM2 e) transpose mat = let swap = lift1 $ \(Z:.x:.y) -> Z:.y:.x :: Z:.Exp Int:.Exp Int in backpermute (swap $ shape mat) swap mat -- Extracting sub-vectors -- ---------------------- -- | Yield the first @n@ elements of the input vector. The vector must contain -- no more than @n@ elements. -- take :: Elt e => Exp Int -> Acc (Vector e) -> Acc (Vector e) take n = backpermute (index1 n) id -- | Yield all but the first @n@ elements of the input vector. The vector must -- contain no more than @n@ elements. -- drop :: Elt e => Exp Int -> Acc (Vector e) -> Acc (Vector e) drop n arr = let n' = unit n in backpermute (ilift1 (subtract n) (shape arr)) (ilift1 (+ the n')) arr -- | Yield all but the last element of the input vector. The vector must not be -- empty. -- init :: Elt e => Acc (Vector e) -> Acc (Vector e) init arr = take ((unindex1 $ shape arr) - 1) arr -- | Yield all but the first element of the input vector. The vector must not be -- empty. -- tail :: Elt e => Acc (Vector e) -> Acc (Vector e) tail arr = backpermute (ilift1 (subtract 1) (shape arr)) (ilift1 (+1)) arr -- | Yield a slit (slice) from the vector. The vector must contain at least -- @i + n@ elements. Denotationally, we have: -- -- > slit i n = take n . drop i -- slit :: Elt e => Exp Int -> Exp Int -> Acc (Vector e) -> Acc (Vector e) slit i n = let i' = unit i in backpermute (index1 n) (ilift1 (+ the i'))
robeverest/accelerate
Data/Array/Accelerate/Prelude.hs
bsd-3-clause
26,223
2
18
7,739
7,832
4,125
3,707
390
1
module Onedrive.Session (Session, newSessionWithToken, newSessionWithRenewableToken, getAccessToken, tryRenewToken) where import Control.Concurrent.STM (atomically) import Control.Concurrent.STM.TVar (TVar, newTVar, readTVar, writeTVar) import Data.Text (Text) data Session = SessionWithToken Text | SessionWithRenewableToken (TVar Text) (IO Text) newSessionWithToken :: Text -> IO Session newSessionWithToken accessToken = return $ SessionWithToken accessToken newSessionWithRenewableToken :: Text -> IO Text -> IO Session newSessionWithRenewableToken accessToken renewAccessToken = do tokenStore <- atomically $ newTVar accessToken return $ SessionWithRenewableToken tokenStore renewAccessToken getAccessToken :: Session -> IO Text getAccessToken (SessionWithToken accessToken) = return accessToken getAccessToken (SessionWithRenewableToken accessToken _) = atomically $ readTVar accessToken tryRenewToken :: Session -> IO (Maybe Text) tryRenewToken (SessionWithToken _) = return Nothing tryRenewToken (SessionWithRenewableToken accessToken renewAccessToken) = do newAccessToken <- renewAccessToken atomically $ writeTVar accessToken newAccessToken return $ Just newAccessToken
asvyazin/hs-onedrive
src/Onedrive/Session.hs
bsd-3-clause
1,214
0
9
155
307
157
150
26
1
-- Enter your code here. Read input from STDIN. Print output to STDOUT is_function :: [(Int, Int)] -> Bool is_function pairs = no_dups (map fst pairs) no_dups :: Eq a => [a] -> Bool no_dups [] = True no_dups (x:xs) = (not (x `elem` xs)) && (no_dups xs) swap f = \y -> \x -> f x y for = swap map list2pair :: [a] -> (a, a) list2pair [] = undefined list2pair (x : xs) = (x, head xs) main :: IO [()] main = do num_tests <- readLn sequence $ take num_tests $ repeat $ do num_pairs <- readLn pairs <- sequence $ take num_pairs $ repeat $ (list2pair . map read . words) `fmap` getLine if is_function pairs then (putStrLn "YES") else (putStrLn "NO")
capn-freako/Haskell_Misc
HackerRank/function_test.hs
bsd-3-clause
715
1
16
199
312
161
151
19
2
{-# LANGUAGE OverloadedStrings #-} module Seeds (users) where import Data.Time import UserService.Types user1 = User "burt" "bobby" email theirAddress "218-222-5555" theirDob where email = "[email protected]" theirDob = fromGregorian 2012 1 1 theirAddress = Address "Sttreet" "LA" "CA" "#1" "90210" user2 = User "basdf" "sdfawef" email theirAddress "218-222-5555" theirDob where email = "[email protected]" theirDob = fromGregorian 2000 1 1 theirAddress = Address "St ave goo" "Pelican Rapids" "MN" "#1" "56572" users = [user1, user2]
tippenein/user_clone
src/Seeds.hs
bsd-3-clause
565
0
7
105
137
74
63
13
1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP, NoImplicitPrelude, CApiFFI #-} ----------------------------------------------------------------------------- -- | -- Module : System.IO -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Stability : stable -- Portability : portable -- -- The standard IO library. -- ----------------------------------------------------------------------------- module System.IO ( -- * The IO monad IO, fixIO, -- * Files and handles FilePath, Handle, -- abstract, instance of: Eq, Show. -- | GHC note: a 'Handle' will be automatically closed when the garbage -- collector detects that it has become unreferenced by the program. -- However, relying on this behaviour is not generally recommended: -- the garbage collector is unpredictable. If possible, use -- an explicit 'hClose' to close 'Handle's when they are no longer -- required. GHC does not currently attempt to free up file -- descriptors when they have run out, it is your responsibility to -- ensure that this doesn't happen. -- ** Standard handles -- | Three handles are allocated during program initialisation, -- and are initially open. stdin, stdout, stderr, -- * Opening and closing files -- ** Opening files withFile, openFile, IOMode(ReadMode,WriteMode,AppendMode,ReadWriteMode), -- ** Closing files hClose, -- ** Special cases -- | These functions are also exported by the "Prelude". readFile, writeFile, appendFile, -- ** File locking -- $locking -- * Operations on handles -- ** Determining and changing the size of a file hFileSize, hSetFileSize, -- ** Detecting the end of input hIsEOF, isEOF, -- ** Buffering operations BufferMode(NoBuffering,LineBuffering,BlockBuffering), hSetBuffering, hGetBuffering, hFlush, -- ** Repositioning handles hGetPosn, hSetPosn, HandlePosn, -- abstract, instance of: Eq, Show. hSeek, SeekMode(AbsoluteSeek,RelativeSeek,SeekFromEnd), hTell, -- ** Handle properties hIsOpen, hIsClosed, hIsReadable, hIsWritable, hIsSeekable, -- ** Terminal operations (not portable: GHC only) hIsTerminalDevice, hSetEcho, hGetEcho, -- ** Showing handle state (not portable: GHC only) hShow, -- * Text input and output -- ** Text input hWaitForInput, hReady, hGetChar, hGetLine, hLookAhead, hGetContents, -- ** Text output hPutChar, hPutStr, hPutStrLn, hPrint, -- ** Special cases for standard input and output -- | These functions are also exported by the "Prelude". interact, putChar, putStr, putStrLn, print, getChar, getLine, getContents, readIO, readLn, -- * Binary input and output withBinaryFile, openBinaryFile, hSetBinaryMode, hPutBuf, hGetBuf, hGetBufSome, hPutBufNonBlocking, hGetBufNonBlocking, -- * Temporary files openTempFile, openBinaryTempFile, openTempFileWithDefaultPermissions, openBinaryTempFileWithDefaultPermissions, -- * Unicode encoding\/decoding -- | A text-mode 'Handle' has an associated 'TextEncoding', which -- is used to decode bytes into Unicode characters when reading, -- and encode Unicode characters into bytes when writing. -- -- The default 'TextEncoding' is the same as the default encoding -- on your system, which is also available as 'localeEncoding'. -- (GHC note: on Windows, we currently do not support double-byte -- encodings; if the console\'s code page is unsupported, then -- 'localeEncoding' will be 'latin1'.) -- -- Encoding and decoding errors are always detected and reported, -- except during lazy I/O ('hGetContents', 'getContents', and -- 'readFile'), where a decoding error merely results in -- termination of the character stream, as with other I/O errors. hSetEncoding, hGetEncoding, -- ** Unicode encodings TextEncoding, latin1, utf8, utf8_bom, utf16, utf16le, utf16be, utf32, utf32le, utf32be, localeEncoding, char8, mkTextEncoding, -- * Newline conversion -- | In Haskell, a newline is always represented by the character -- @\'\\n\'@. However, in files and external character streams, a -- newline may be represented by another character sequence, such -- as @\'\\r\\n\'@. -- -- A text-mode 'Handle' has an associated 'NewlineMode' that -- specifies how to translate newline characters. The -- 'NewlineMode' specifies the input and output translation -- separately, so that for instance you can translate @\'\\r\\n\'@ -- to @\'\\n\'@ on input, but leave newlines as @\'\\n\'@ on output. -- -- The default 'NewlineMode' for a 'Handle' is -- 'nativeNewlineMode', which does no translation on Unix systems, -- but translates @\'\\r\\n\'@ to @\'\\n\'@ and back on Windows. -- -- Binary-mode 'Handle's do no newline translation at all. -- hSetNewlineMode, Newline(..), nativeNewline, NewlineMode(..), noNewlineTranslation, universalNewlineMode, nativeNewlineMode, ) where import Control.Exception.Base import Data.Bits import Data.Maybe import Foreign.C.Error #if defined(mingw32_HOST_OS) import Foreign.C.String import Foreign.Ptr import Foreign.Marshal.Alloc import Foreign.Storable #endif import Foreign.C.Types import System.Posix.Internals import System.Posix.Types import GHC.Base import GHC.List #if !defined(mingw32_HOST_OS) import GHC.IORef #endif import GHC.Num import GHC.IO hiding ( bracket, onException ) import GHC.IO.IOMode import GHC.IO.Handle.FD import qualified GHC.IO.FD as FD import GHC.IO.Handle import GHC.IO.Handle.Text ( hGetBufSome, hPutStrLn ) import GHC.IO.Exception ( userError ) import GHC.IO.Encoding import Text.Read import GHC.Show import GHC.MVar -- ----------------------------------------------------------------------------- -- Standard IO -- | Write a character to the standard output device -- (same as 'hPutChar' 'stdout'). putChar :: Char -> IO () putChar c = hPutChar stdout c -- | Write a string to the standard output device -- (same as 'hPutStr' 'stdout'). putStr :: String -> IO () putStr s = hPutStr stdout s -- | The same as 'putStr', but adds a newline character. putStrLn :: String -> IO () putStrLn s = hPutStrLn stdout s -- | The 'print' function outputs a value of any printable type to the -- standard output device. -- Printable types are those that are instances of class 'Show'; 'print' -- converts values to strings for output using the 'show' operation and -- adds a newline. -- -- For example, a program to print the first 20 integers and their -- powers of 2 could be written as: -- -- > main = print ([(n, 2^n) | n <- [0..19]]) print :: Show a => a -> IO () print x = putStrLn (show x) -- | Read a character from the standard input device -- (same as 'hGetChar' 'stdin'). getChar :: IO Char getChar = hGetChar stdin -- | Read a line from the standard input device -- (same as 'hGetLine' 'stdin'). getLine :: IO String getLine = hGetLine stdin -- | The 'getContents' operation returns all user input as a single string, -- which is read lazily as it is needed -- (same as 'hGetContents' 'stdin'). getContents :: IO String getContents = hGetContents stdin -- | The 'interact' function takes a function of type @String->String@ -- as its argument. The entire input from the standard input device is -- passed to this function as its argument, and the resulting string is -- output on the standard output device. interact :: (String -> String) -> IO () interact f = do s <- getContents putStr (f s) -- | The 'readFile' function reads a file and -- returns the contents of the file as a string. -- The file is read lazily, on demand, as with 'getContents'. readFile :: FilePath -> IO String readFile name = openFile name ReadMode >>= hGetContents -- | The computation 'writeFile' @file str@ function writes the string @str@, -- to the file @file@. writeFile :: FilePath -> String -> IO () writeFile f txt = withFile f WriteMode (\ hdl -> hPutStr hdl txt) -- | The computation 'appendFile' @file str@ function appends the string @str@, -- to the file @file@. -- -- Note that 'writeFile' and 'appendFile' write a literal string -- to a file. To write a value of any printable type, as with 'print', -- use the 'show' function to convert the value to a string first. -- -- > main = appendFile "squares" (show [(x,x*x) | x <- [0,0.1..2]]) appendFile :: FilePath -> String -> IO () appendFile f txt = withFile f AppendMode (\ hdl -> hPutStr hdl txt) -- | The 'readLn' function combines 'getLine' and 'readIO'. readLn :: Read a => IO a readLn = do l <- getLine r <- readIO l return r -- | The 'readIO' function is similar to 'read' except that it signals -- parse failure to the 'IO' monad instead of terminating the program. readIO :: Read a => String -> IO a readIO s = case (do { (x,t) <- reads s ; ("","") <- lex t ; return x }) of [x] -> return x [] -> ioError (userError "Prelude.readIO: no parse") _ -> ioError (userError "Prelude.readIO: ambiguous parse") -- | The Unicode encoding of the current locale -- -- This is the initial locale encoding: if it has been subsequently changed by -- 'GHC.IO.Encoding.setLocaleEncoding' this value will not reflect that change. localeEncoding :: TextEncoding localeEncoding = initLocaleEncoding -- | Computation 'hReady' @hdl@ indicates whether at least one item is -- available for input from handle @hdl@. -- -- This operation may fail with: -- -- * 'System.IO.Error.isEOFError' if the end of file has been reached. hReady :: Handle -> IO Bool hReady h = hWaitForInput h 0 -- | Computation 'hPrint' @hdl t@ writes the string representation of @t@ -- given by the 'shows' function to the file or channel managed by @hdl@ -- and appends a newline. -- -- This operation may fail with: -- -- * 'System.IO.Error.isFullError' if the device is full; or -- -- * 'System.IO.Error.isPermissionError' if another system resource limit -- would be exceeded. hPrint :: Show a => Handle -> a -> IO () hPrint hdl = hPutStrLn hdl . show -- | @'withFile' name mode act@ opens a file using 'openFile' and passes -- the resulting handle to the computation @act@. The handle will be -- closed on exit from 'withFile', whether by normal termination or by -- raising an exception. If closing the handle raises an exception, then -- this exception will be raised by 'withFile' rather than any exception -- raised by @act@. withFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r withFile name mode = bracket (openFile name mode) hClose -- | @'withBinaryFile' name mode act@ opens a file using 'openBinaryFile' -- and passes the resulting handle to the computation @act@. The handle -- will be closed on exit from 'withBinaryFile', whether by normal -- termination or by raising an exception. withBinaryFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r withBinaryFile name mode = bracket (openBinaryFile name mode) hClose -- --------------------------------------------------------------------------- -- fixIO -- | The implementation of 'Control.Monad.Fix.mfix' for 'IO'. If the function -- passed to 'fixIO' inspects its argument, the resulting action will throw -- 'FixIOException'. fixIO :: (a -> IO a) -> IO a fixIO k = do m <- newEmptyMVar ans <- unsafeDupableInterleaveIO (readMVar m `catch` \BlockedIndefinitelyOnMVar -> throwIO FixIOException) result <- k ans putMVar m result return result -- NOTE: we do our own explicit black holing here, because GHC's lazy -- blackholing isn't enough. In an infinite loop, GHC may run the IO -- computation a few times before it notices the loop, which is wrong. -- -- NOTE2: the explicit black-holing with an IORef ran into trouble -- with multiple threads (see #5421), so now we use an MVar. We used -- to use takeMVar with unsafeInterleaveIO. This, however, uses noDuplicate#, -- which is not particularly cheap. Better to use readMVar, which can be -- performed in multiple threads safely, and to use unsafeDupableInterleaveIO -- to avoid the noDuplicate cost. -- -- What we'd ideally want is probably an IVar, but we don't quite have those. -- STM TVars look like an option at first, but I don't think they are: -- we'd need to be able to write to the variable in an IO context, which can -- only be done using 'atomically', and 'atomically' is not allowed within -- unsafePerformIO. We can't know if someone will try to use the result -- of fixIO with unsafePerformIO! -- -- See also System.IO.Unsafe.unsafeFixIO. -- -- | The function creates a temporary file in ReadWrite mode. -- The created file isn\'t deleted automatically, so you need to delete it manually. -- -- The file is created with permissions such that only the current -- user can read\/write it. -- -- With some exceptions (see below), the file will be created securely -- in the sense that an attacker should not be able to cause -- openTempFile to overwrite another file on the filesystem using your -- credentials, by putting symbolic links (on Unix) in the place where -- the temporary file is to be created. On Unix the @O_CREAT@ and -- @O_EXCL@ flags are used to prevent this attack, but note that -- @O_EXCL@ is sometimes not supported on NFS filesystems, so if you -- rely on this behaviour it is best to use local filesystems only. -- openTempFile :: FilePath -- ^ Directory in which to create the file -> String -- ^ File name template. If the template is \"foo.ext\" then -- the created file will be \"fooXXX.ext\" where XXX is some -- random number. Note that this should not contain any path -- separator characters. -> IO (FilePath, Handle) openTempFile tmp_dir template = openTempFile' "openTempFile" tmp_dir template False 0o600 -- | Like 'openTempFile', but opens the file in binary mode. See 'openBinaryFile' for more comments. openBinaryTempFile :: FilePath -> String -> IO (FilePath, Handle) openBinaryTempFile tmp_dir template = openTempFile' "openBinaryTempFile" tmp_dir template True 0o600 -- | Like 'openTempFile', but uses the default file permissions openTempFileWithDefaultPermissions :: FilePath -> String -> IO (FilePath, Handle) openTempFileWithDefaultPermissions tmp_dir template = openTempFile' "openTempFileWithDefaultPermissions" tmp_dir template False 0o666 -- | Like 'openBinaryTempFile', but uses the default file permissions openBinaryTempFileWithDefaultPermissions :: FilePath -> String -> IO (FilePath, Handle) openBinaryTempFileWithDefaultPermissions tmp_dir template = openTempFile' "openBinaryTempFileWithDefaultPermissions" tmp_dir template True 0o666 openTempFile' :: String -> FilePath -> String -> Bool -> CMode -> IO (FilePath, Handle) openTempFile' loc tmp_dir template binary mode | pathSeparator template = failIO $ "openTempFile': Template string must not contain path separator characters: "++template | otherwise = findTempName where -- We split off the last extension, so we can use .foo.ext files -- for temporary files (hidden on Unix OSes). Unfortunately we're -- below filepath in the hierarchy here. (prefix, suffix) = case break (== '.') $ reverse template of -- First case: template contains no '.'s. Just re-reverse it. (rev_suffix, "") -> (reverse rev_suffix, "") -- Second case: template contains at least one '.'. Strip the -- dot from the prefix and prepend it to the suffix (if we don't -- do this, the unique number will get added after the '.' and -- thus be part of the extension, which is wrong.) (rev_suffix, '.':rest) -> (reverse rest, '.':reverse rev_suffix) -- Otherwise, something is wrong, because (break (== '.')) should -- always return a pair with either the empty string or a string -- beginning with '.' as the second component. _ -> errorWithoutStackTrace "bug in System.IO.openTempFile" #if defined(mingw32_HOST_OS) findTempName = do let label = if null prefix then "ghc" else prefix withCWString tmp_dir $ \c_tmp_dir -> withCWString label $ \c_template -> withCWString suffix $ \c_suffix -> -- NOTE: revisit this when new I/O manager in place and use a UUID -- based one when we are no longer MAX_PATH bound. allocaBytes (sizeOf (undefined :: CWchar) * 260) $ \c_str -> do res <- c_getTempFileNameErrorNo c_tmp_dir c_template c_suffix 0 c_str if not res then do errno <- getErrno ioError (errnoToIOError loc errno Nothing (Just tmp_dir)) else do filename <- peekCWString c_str handleResults filename handleResults filename = do let oflags1 = rw_flags .|. o_EXCL binary_flags | binary = o_BINARY | otherwise = 0 oflags = oflags1 .|. binary_flags fd <- withFilePath filename $ \ f -> c_open f oflags mode case fd < 0 of True -> do errno <- getErrno ioError (errnoToIOError loc errno Nothing (Just tmp_dir)) False -> do (fD,fd_type) <- FD.mkFD fd ReadWriteMode Nothing{-no stat-} False{-is_socket-} True{-is_nonblock-} enc <- getLocaleEncoding h <- mkHandleFromFD fD fd_type filename ReadWriteMode False{-set non-block-} (Just enc) return (filename, h) foreign import ccall "getTempFileNameErrorNo" c_getTempFileNameErrorNo :: CWString -> CWString -> CWString -> CUInt -> Ptr CWchar -> IO Bool pathSeparator :: String -> Bool pathSeparator template = any (\x-> x == '/' || x == '\\') template output_flags = std_flags #else /* else mingw32_HOST_OS */ findTempName = do rs <- rand_string let filename = prefix ++ rs ++ suffix filepath = tmp_dir `combine` filename r <- openNewFile filepath binary mode case r of FileExists -> findTempName OpenNewError errno -> ioError (errnoToIOError loc errno Nothing (Just tmp_dir)) NewFileCreated fd -> do (fD,fd_type) <- FD.mkFD fd ReadWriteMode Nothing{-no stat-} False{-is_socket-} True{-is_nonblock-} enc <- getLocaleEncoding h <- mkHandleFromFD fD fd_type filepath ReadWriteMode False{-set non-block-} (Just enc) return (filepath, h) where -- XXX bits copied from System.FilePath, since that's not available here combine a b | null b = a | null a = b | pathSeparator [last a] = a ++ b | otherwise = a ++ [pathSeparatorChar] ++ b tempCounter :: IORef Int tempCounter = unsafePerformIO $ newIORef 0 {-# NOINLINE tempCounter #-} -- build large digit-alike number rand_string :: IO String rand_string = do r1 <- c_getpid (r2, _) <- atomicModifyIORef'_ tempCounter (+1) return $ show r1 ++ "-" ++ show r2 data OpenNewFileResult = NewFileCreated CInt | FileExists | OpenNewError Errno openNewFile :: FilePath -> Bool -> CMode -> IO OpenNewFileResult openNewFile filepath binary mode = do let oflags1 = rw_flags .|. o_EXCL binary_flags | binary = o_BINARY | otherwise = 0 oflags = oflags1 .|. binary_flags fd <- withFilePath filepath $ \ f -> c_open f oflags mode if fd < 0 then do errno <- getErrno case errno of _ | errno == eEXIST -> return FileExists _ -> return (OpenNewError errno) else return (NewFileCreated fd) -- XXX Should use filepath library pathSeparatorChar :: Char pathSeparatorChar = '/' pathSeparator :: String -> Bool pathSeparator template = pathSeparatorChar `elem` template output_flags = std_flags .|. o_CREAT #endif /* mingw32_HOST_OS */ -- XXX Copied from GHC.Handle std_flags, output_flags, rw_flags :: CInt std_flags = o_NONBLOCK .|. o_NOCTTY rw_flags = output_flags .|. o_RDWR -- $locking -- Implementations should enforce as far as possible, at least locally to the -- Haskell process, multiple-reader single-writer locking on files. -- That is, /there may either be many handles on the same file which manage input, or just one handle on the file which manages output/. If any -- open or semi-closed handle is managing a file for output, no new -- handle can be allocated for that file. If any open or semi-closed -- handle is managing a file for input, new handles can only be allocated -- if they do not manage output. Whether two files are the same is -- implementation-dependent, but they should normally be the same if they -- have the same absolute path name and neither has been renamed, for -- example. -- -- /Warning/: the 'readFile' operation holds a semi-closed handle on -- the file until the entire contents of the file have been consumed. -- It follows that an attempt to write to a file (using 'writeFile', for -- example) that was earlier opened by 'readFile' will usually result in -- failure with 'System.IO.Error.isAlreadyInUseError'.
sdiehl/ghc
libraries/base/System/IO.hs
bsd-3-clause
22,275
0
26
5,582
2,338
1,367
971
247
5
-- A little benchmark adapted from attoparsec module Main where import Control.Monad -- import qualified Data.ByteString.Lazy as L import System.Environment import Data.IterIO import Data.IterIO.Parse iterio :: IO () iterio = do args <- getArgs forM_ args $ \arg -> do result <- enumFile' arg |$ p print (length result) where fast = many (while1I isLetter <|> while1I isDigit) isDigit c = c >= eord '0' && c <= eord '9' isLetter c = (c >= eord 'a' && c <= eord 'z') || (c >= eord 'A' && c <= eord 'Z') p = fast main :: IO () main = iterio
scslab/iterIO
tests/bench.hs
bsd-3-clause
595
0
13
158
213
107
106
18
1
----------------------------------------------------------------------------- -- TIMain: Type Inference Algorithm -- -- Part of `Typing Haskell in Haskell', version of November 23, 2000 -- Copyright (c) Mark P Jones and the Oregon Graduate Institute -- of Science and Technology, 1999-2000 -- -- This program is distributed as Free Software under the terms -- in the file "License" that is included in the distribution -- of this software, copies of which may be obtained from: -- http://www.cse.ogi.edu/~mpj/thih/ -- ----------------------------------------------------------------------------- module Thih.TI.TIMain where import Data.List( (\\), intersect, union, partition ) import Thih.TI.Id import Thih.TI.Kind import Thih.TI.Type import Thih.TI.Subst import Thih.TI.Pred import Thih.TI.Scheme import Thih.TI.Assump import Thih.TI.TIMonad import Thih.TI.Infer import Thih.TI.Lit import Thih.TI.Pat import Thih.Static.Prelude ----------------------------------------------------------------------------- data Expr = Var Id | Lit Literal | Const Assump | Ap Expr Expr | Let BindGroup Expr | Lam Alt | If Expr Expr Expr | Case Expr [(Pat,Expr)] ----------------------------------------------------------------------------- -- The following helper functions are used to construct sample programs; if we -- change the representation of Expr above, then we need only change the -- definitions of the following combinators to match, and do not need to -- rewrite all the test code. ap = foldl1 Ap evar v = (Var v) elit l = (Lit l) econst c = (Const c) elet e f = foldr Let f (map toBg e) toBg :: [(Id, Maybe Scheme, [Alt])] -> BindGroup toBg g = ([(v, t, alts) | (v, Just t, alts) <- g ], filter (not . null) [[(v,alts) | (v,Nothing,alts) <- g]]) pNil = PCon nilCfun [] pCons x y = PCon consCfun [x,y] eNil = econst nilCfun eCons x y = ap [ econst consCfun, x, y ] {- ecase = Case elambda = Lam eif = If -} ecase d as = elet [[ ("_case", Nothing, [([p],e) | (p,e) <- as]) ]] (ap [evar "_case", d]) eif c t f = ecase c [(PCon trueCfun [], t),(PCon falseCfun [], f)] elambda alt = elet [[ ("_lambda", Nothing, [alt]) ]] (evar "_lambda") eguarded l = foldr (\(c,t) e -> eif c t e) efail l efail = Const ("FAIL" :>: Forall [Star] ([] :=> TGen 0)) esign e t = elet [[ ("_val", Just t, [([],e)]) ]] (evar "_val") eCompFrom p e c = ap [ econst mbindMfun, e, elambda ([p],c) ] eCompGuard e c = eif e c eNil eCompLet bgs c = elet bgs c eListRet e = eCons e eNil ----------------------------------------------------------------------------- tiExpr :: Infer Expr Type tiExpr ce as (Var i) = do sc <- find i as (ps :=> t) <- freshInst sc return (ps, t) tiExpr ce as (Const (i:>:sc)) = do (ps :=> t) <- freshInst sc return (ps, t) tiExpr ce as (Lit l) = do (ps,t) <- tiLit l return (ps, t) tiExpr ce as (Ap e f) = do (ps,te) <- tiExpr ce as e (qs,tf) <- tiExpr ce as f t <- newTVar Star unify (tf `fn` t) te return (ps++qs, t) tiExpr ce as (Let bg e) = do (ps, as') <- tiBindGroup ce as bg (qs, t) <- tiExpr ce (as' ++ as) e return (ps ++ qs, t) tiExpr ce as (Lam alt) = tiAlt ce as alt tiExpr ce as (If e e1 e2) = do (ps,t) <- tiExpr ce as e unify t tBool (ps1,t1) <- tiExpr ce as e1 (ps2,t2) <- tiExpr ce as e2 unify t1 t2 return (ps++ps1++ps2, t1) tiExpr ce as (Case e branches) = do (ps, t) <- tiExpr ce as e v <- newTVar Star let tiBr (pat, f) = do (ps, as',t') <- tiPat pat unify t t' (qs, t'') <- tiExpr ce (as'++as) f unify v t'' return (ps++qs) pss <- mapM tiBr branches return (ps++concat pss, v) ----------------------------------------------------------------------------- type Alt = ([Pat], Expr) tiAlt :: Infer Alt Type tiAlt ce as (pats, e) = do (ps, as', ts) <- tiPats pats (qs,t) <- tiExpr ce (as'++as) e return (ps++qs, foldr fn t ts) tiAlts :: ClassEnv -> [Assump] -> [Alt] -> Type -> TI [Pred] tiAlts ce as alts t = do psts <- mapM (tiAlt ce as) alts mapM (unify t) (map snd psts) return (concat (map fst psts)) ----------------------------------------------------------------------------- split :: Monad m => ClassEnv -> [Tyvar] -> [Tyvar] -> [Pred] -> m ([Pred], [Pred]) split ce fs gs ps = do ps' <- reduce ce ps let (ds, rs) = partition (all (`elem` fs) . tv) ps' rs' <- defaultedPreds ce (fs++gs) rs return (ds, rs \\ rs') type Ambiguity = (Tyvar, [Pred]) ambiguities :: ClassEnv -> [Tyvar] -> [Pred] -> [Ambiguity] ambiguities ce vs ps = [ (v, filter (elem v . tv) ps) | v <- tv ps \\ vs ] numClasses :: [Id] numClasses = ["Num", "Integral", "Floating", "Fractional", "Real", "RealFloat", "RealFrac"] stdClasses :: [Id] stdClasses = ["Eq", "Ord", "Show", "Read", "Bounded", "Enum", "Ix", "Functor", "Monad", "MonadPlus"] ++ numClasses candidates :: ClassEnv -> Ambiguity -> [Type] candidates ce (v, qs) = [ t' | let is = [ i | IsIn i t <- qs ] ts = [ t | IsIn i t <- qs ], all ((TVar v)==) ts, any (`elem` numClasses) is, all (`elem` stdClasses) is, t' <- defaults ce, all (entail ce []) [ IsIn i t' | i <- is ] ] withDefaults :: Monad m => ([Ambiguity] -> [Type] -> a) -> ClassEnv -> [Tyvar] -> [Pred] -> m a withDefaults f ce vs ps | any null tss = fail "cannot resolve ambiguity" | otherwise = return (f vps (map head tss)) where vps = ambiguities ce vs ps tss = map (candidates ce) vps defaultedPreds :: Monad m => ClassEnv -> [Tyvar] -> [Pred] -> m [Pred] defaultedPreds = withDefaults (\vps ts -> concat (map snd vps)) defaultSubst :: Monad m => ClassEnv -> [Tyvar] -> [Pred] -> m Subst defaultSubst = withDefaults (\vps ts -> zip (map fst vps) ts) ----------------------------------------------------------------------------- type Expl = (Id, Scheme, [Alt]) tiExpl :: ClassEnv -> [Assump] -> Expl -> TI [Pred] tiExpl ce as (i, sc, alts) = do (qs :=> t) <- freshInst sc ps <- tiAlts ce as alts t s <- getSubst let qs' = apply s qs t' = apply s t fs = tv (apply s as) gs = tv t' \\ fs sc' = quantify gs (qs':=>t') ps' = filter (not . entail ce qs') (apply s ps) (ds,rs) <- split ce fs gs ps' if sc /= sc' then fail "signature too general" else if not (null rs) then fail "context too weak" else return ds ----------------------------------------------------------------------------- type Impl = (Id, [Alt]) restricted :: [Impl] -> Bool restricted bs = any simple bs where simple (i,alts) = any (null . fst) alts tiImpls :: Infer [Impl] [Assump] tiImpls ce as bs = do ts <- mapM (\_ -> newTVar Star) bs let is = map fst bs scs = map toScheme ts as' = zipWith (:>:) is scs ++ as altss = map snd bs pss <- sequence (zipWith (tiAlts ce as') altss ts) s <- getSubst let ps' = apply s (concat pss) ts' = apply s ts fs = tv (apply s as) vss = map tv ts' gs = foldr1 union vss \\ fs (ds,rs) <- split ce fs (foldr1 intersect vss) ps' if restricted bs then let gs' = gs \\ tv rs scs' = map (quantify gs' . ([]:=>)) ts' in return (ds++rs, zipWith (:>:) is scs') else let scs' = map (quantify gs . (rs:=>)) ts' in return (ds, zipWith (:>:) is scs') ----------------------------------------------------------------------------- type BindGroup = ([Expl], [[Impl]]) tiBindGroup :: Infer BindGroup [Assump] tiBindGroup ce as (es,iss) = do let as' = [ v:>:sc | (v,sc,alts) <- es ] (ps, as'') <- tiSeq tiImpls ce (as'++as) iss qss <- mapM (tiExpl ce (as''++as'++as)) es return (ps++concat qss, as''++as') tiSeq :: Infer bg [Assump] -> Infer [bg] [Assump] tiSeq ti ce as [] = return ([],[]) tiSeq ti ce as (bs:bss) = do (ps,as') <- ti ce as bs (qs,as'') <- tiSeq ti ce (as'++as) bss return (ps++qs, as''++as') -----------------------------------------------------------------------------
yu-i9/thih
src/Thih/TI/TIMain.hs
bsd-3-clause
9,988
0
16
3,836
3,489
1,841
1,648
183
3
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleContexts #-} module Diff2Html where import Data.Foldable import Data.Monoid import qualified Data.Text as T import qualified Data.Algorithm.Patience as P import Lucid import Chunk import Diff import Utils (breakWith) chunksToTable :: [Chunk] -> Html () chunksToTable chunks = table_ [class_ "diff"]$ foldMap chunkToRows chunks chunkToRows :: Chunk -> Html () chunkToRows (Chunk files pos body) = do tr_ [class_ "header"] $ mapM_ (td_ . span_ [class_ "filename"] . toHtml . fileName) files tr_ $ mapM_ showTd pos mapM_ chunkBodyToRows body where showTd :: Show a => a -> Html () showTd = cell [] . show chunkBodyToRows :: ChunkBody -> Html () chunkBodyToRows (CContext lines) = mapM_ go lines where go :: T.Text -> Html () go l = tr_ [class_ "diff"] $ cell [] l <> cell [] l chunkBodyToRows (CDiff (Diff dels adds)) = mapM_ row' (fillIn dels adds) where row, row' :: (T.Text, T.Text) -> Html () row' (del, add) = tr_ [class_ "diff"] $ fold (td_ <$> Diff delAttrs addAttrs <*> diffLines del add) row (del, add) = tr_ [class_ "diff"] $ do cell delAttrs del cell addAttrs add addAttrs = [class_ "add"] delAttrs = [class_ "del"] fillIn :: [T.Text] -> [T.Text] -> [(T.Text, T.Text)] fillIn [] [] = [] fillIn (x:xs) (y:ys) = (x, y) : fillIn xs ys fillIn (x:xs) [] = (x, T.empty) : fillIn xs [] fillIn [] (y:ys) = (T.empty, y) : fillIn [] ys cell :: ToHtml a => [Attribute] -> a -> Html () cell attrs d = td_ attrs $ pre_ (toHtml d) data Pair a b = Pair !a !b diffLines :: T.Text -> T.Text -> Diff (Html ()) diffLines a b = foldl' go (Diff mempty mempty) $ groupItems $ P.diff (T.unpack a) (T.unpack b) where go :: Diff (Html ()) -> P.Item String -> Diff (Html ()) go (Diff l r) (P.Both l' r') = Diff (l <> span_ [] (toHtml l')) (r <> span_ [] (toHtml r')) go (Diff l r) (P.Old l') = Diff (l <> span_ new (toHtml l')) r go (Diff l r) (P.New r') = Diff l (r <> span_ new (toHtml r')) new = [class_ "change"] groupItems :: [P.Item a] -> [P.Item [a]] groupItems [] = [] groupItems (P.Old a : rest) = P.Old (a:xs) : groupItems rest' where (xs, rest') = breakWith go rest go (P.Old x) = Just x go _ = Nothing groupItems (P.New a : rest) = P.New (a:xs) : groupItems rest' where (xs, rest') = breakWith go rest go (P.New x) = Just x go _ = Nothing groupItems (P.Both l r : rest) = P.Both (l:ls) (r:rs) : groupItems rest' where (ls, rs) = unzip xs (xs, rest') = breakWith go rest go (P.Both a b) = Just (a, b) go _ = Nothing
bgamari/diff-utils
src/Diff2Html.hs
bsd-3-clause
2,790
0
15
791
1,367
692
675
67
9
module GalFld.GalFld ( module X , factorP , extendFFBy ) where import GalFld.Core as X import GalFld.Algorithmen as X -- |Nimmt einen Grad `d` und ein Element `e` eines Endlichen Körpers und bildet -- über den Endlichen Körper, dass das Element enthält eine Erweiterun von Grad -- `d`. -- Das übergebene Element muss "genug" Information enthalten. extendFFBy :: (Show a, Num a, Fractional a, FiniteField a) => Int -> a -> FFElem a extendFFBy d e = FFElem (pTupUnsave [(0,onefy)]) $ findIrred $ getAllMonicPs (elems e) [d] where onefy | e == 1 = e | otherwise = e / e -- |Nimmt ein Polynom f und faktorisiert dieses komplett mittels SFF und -- Berlekamp factorP :: (Show a, Num a, Fractional a, FiniteField a) => Polynom a -> [(Int,Polynom a)] factorP = aggFact . appBerlekamp . appSff . obviousFactor
maximilianhuber/softwareProjekt
src/GalFld/GalFld.hs
bsd-3-clause
838
0
11
172
229
126
103
12
1
-- | -- Module : $Header$ -- Copyright : (c) 2013-2014 Galois, Inc. -- License : BSD3 -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable {-# LANGUAGE Safe #-} {-# LANGUAGE PatternGuards #-} module Cryptol.Eval ( moduleEnv , EvalEnv() , emptyEnv , evalExpr , EvalError(..) , WithBase(..) ) where import Cryptol.Eval.Error import Cryptol.Eval.Env import Cryptol.Eval.Type import Cryptol.Eval.Value import Cryptol.TypeCheck.AST import Cryptol.Utils.Panic (panic) import Cryptol.Utils.PP import Cryptol.Prims.Eval import Data.List (transpose) import Data.Monoid (Monoid(..),mconcat) import qualified Data.Map as Map -- Expression Evaluation ------------------------------------------------------- moduleEnv :: Module -> EvalEnv -> EvalEnv moduleEnv m env = evalDecls (mDecls m) (evalNewtypes (mNewtypes m) env) evalExpr :: EvalEnv -> Expr -> Value evalExpr env expr = case expr of ECon con -> evalECon con EList es ty -> evalList env es (evalType env ty) ETuple es -> VTuple (length es) (map eval es) ERec fields -> VRecord [ (f,eval e) | (f,e) <- fields ] ESel e sel -> evalSel env e sel EIf c t f | fromVBit (eval c) -> eval t | otherwise -> eval f EComp l h gs -> evalComp env (evalType env l) h gs EVar n -> case lookupVar n env of Just val -> val Nothing -> panic "[Eval] evalExpr" ["var `" ++ show (pp n) ++ "` is not defined" , pretty (WithBase defaultPPOpts env) ] ETAbs tv b -> VPoly $ \ty -> evalExpr (bindType (tpVar tv) ty env) b ETApp e ty -> case eval e of VPoly f -> f (evalType env ty) val -> panic "[Eval] evalExpr" ["expected a polymorphic value" , show (ppV val), show e, show ty ] EApp f x -> case eval f of VFun f' -> f' (eval x) it -> panic "[Eval] evalExpr" ["not a function", show (ppV it) ] EAbs n _ty b -> VFun (\ val -> evalExpr (bindVar n val env) b ) -- XXX these will likely change once there is an evidence value EProofAbs _ e -> evalExpr env e EProofApp e -> evalExpr env e ECast e _ty -> evalExpr env e EWhere e ds -> evalExpr (evalDecls ds env) e where eval = evalExpr env ppV = ppValue defaultPPOpts -- Newtypes -------------------------------------------------------------------- evalNewtypes :: Map.Map QName Newtype -> EvalEnv -> EvalEnv evalNewtypes nts env = Map.foldl (flip evalNewtype) env nts -- | Introduce the constructor function for a newtype. evalNewtype :: Newtype -> EvalEnv -> EvalEnv evalNewtype nt = bindVar (ntName nt) (foldr tabs con (ntParams nt)) where tabs _tp body = tlam (\ _ -> body) con = VFun id -- Declarations ---------------------------------------------------------------- evalDecls :: [DeclGroup] -> EvalEnv -> EvalEnv evalDecls dgs env = foldl (flip evalDeclGroup) env dgs evalDeclGroup :: DeclGroup -> EvalEnv -> EvalEnv evalDeclGroup dg env = env' where -- the final environment is passed in for each declaration, to permit -- recursive values. env' = case dg of Recursive ds -> foldr (evalDecl env') env ds NonRecursive d -> evalDecl env d env evalDecl :: ReadEnv -> Decl -> EvalEnv -> EvalEnv evalDecl renv d = bindVar (dName d) (evalExpr renv (dDefinition d)) -- Selectors ------------------------------------------------------------------- evalSel :: ReadEnv -> Expr -> Selector -> Value evalSel env e sel = case sel of TupleSel n _ -> tupleSel n val RecordSel n _ -> recordSel n val ListSel ix _ -> fromSeq val !! ix where val = evalExpr env e tupleSel n v = case v of VTuple _ vs -> vs !! (n - 1) VSeq False vs -> VSeq False [ tupleSel n v1 | v1 <- vs ] VStream vs -> VStream [ tupleSel n v1 | v1 <- vs ] VFun f -> VFun (\x -> tupleSel n (f x)) _ -> evalPanic "Cryptol.Eval.evalSel" [ "Unexpected value in tuple selection" , show (ppValue defaultPPOpts v) ] recordSel n v = case v of VRecord {} -> lookupRecord n v VSeq False vs -> VSeq False [ recordSel n v1 | v1 <- vs ] VStream vs -> VStream [recordSel n v1 | v1 <- vs ] VFun f -> VFun (\x -> recordSel n (f x)) _ -> evalPanic "Cryptol.Eval.evalSel" [ "Unexpected value in record selection" , show (ppValue defaultPPOpts v) ] -- List Comprehensions --------------------------------------------------------- -- | Evaluate a comprehension. evalComp :: ReadEnv -> TValue -> Expr -> [[Match]] -> Value evalComp env seqty body ms | Just (len,el) <- isTSeq seqty = toSeq len el [ evalExpr e body | e <- envs ] | otherwise = evalPanic "Cryptol.Eval" [ "evalComp given a non sequence" , show seqty ] -- XXX we could potentially print this as a number if the type was available. where -- generate a new environment for each iteration of each parallel branch benvs = map (branchEnvs env) ms -- take parallel slices of each environment. when the length of the list -- drops below the number of branches, one branch has terminated. allBranches es = length es == length ms slices = takeWhile allBranches (transpose benvs) -- join environments to produce environments at each step through the process. envs = map mconcat slices -- | Turn a list of matches into the final environments for each iteration of -- the branch. branchEnvs :: ReadEnv -> [Match] -> [EvalEnv] branchEnvs env matches = case matches of m:ms -> do env' <- evalMatch env m branchEnvs env' ms [] -> return env -- | Turn a match into the list of environments it represents. evalMatch :: EvalEnv -> Match -> [EvalEnv] evalMatch env m = case m of -- many envs From n _ty expr -> do e <- fromSeq (evalExpr env expr) return (bindVar n e env) -- XXX we don't currently evaluate these as though they could be recursive, as -- they are typechecked that way; the read environment to evalDecl is the same -- as the environment to bind a new name in. Let d -> [evalDecl env d env] -- Lists ----------------------------------------------------------------------- -- | Evaluate a list literal, optionally packing them into a word. evalList :: EvalEnv -> [Expr] -> TValue -> Value evalList env es ty = toPackedSeq w ty (map (evalExpr env) es) where w = TValue $ tNum $ length es
dylanmc/cryptol
src/Cryptol/Eval.hs
bsd-3-clause
6,625
0
17
1,769
1,903
958
945
119
19
module Reporting.Annotation where import Prelude hiding (map) import qualified Reporting.Region as R import qualified Data.String as String -- ANNOTATION data Located a = A R.Region a deriving (Eq) instance (Show a) => Show (Located a) where showsPrec p (A r a) = showParen (p > 10) $ showString $ String.unwords [ "at" , show (R.line $ R.start r) , show (R.column $ R.start r) , show (R.line $ R.end r) , show (R.column $ R.end r) , showsPrec 99 a "" ] -- CREATE at :: R.Position -> R.Position -> a -> Located a at start end value = A (R.Region start end) value merge :: Located a -> Located b -> value -> Located value merge (A region1 _) (A region2 _) value = A (R.merge region1 region2) value sameAs :: Located a -> b -> Located b sameAs (A annotation _) value = A annotation value -- MANIPULATE map :: (a -> b) -> Located a -> Located b map f (A annotation value) = A annotation (f value) drop :: Located a -> a drop (A _ value) = value class Strippable a where stripRegion :: a -> a instance Strippable (Located a) where stripRegion (A _ value) = A (R.Region (R.Position 0 0) (R.Position 0 0)) value
rgrempel/frelm.org
vendor/elm-format/parser/src/Reporting/Annotation.hs
mit
1,260
0
13
365
540
276
264
36
1
{-# LANGUAGE StandaloneDeriving #-} module TreeDB( DirList, dlEmpty, dlByExt, dlByExts, dlAdd, dlAddByExt, TreeDB, tdbEmpty, tdbByDir, tdbAdd, tdbAddDir, tdbBuild, tdbMerge, tdbByDirExt, tdbByDirExts ) where import qualified Data.ByteString.Char8 as C import Data.List import Data.Trie(Trie) import qualified Data.Trie as T import Data.Typeable import System.FilePath -- -- The files in a directory, partitioned by extension. -- type DirList = [(String, [String])] dlEmpty :: DirList dlEmpty = [] -- Linear search for files by extension, in a single directory. dlByExt :: String -> DirList -> [String] dlByExt _ [] = [] dlByExt ext ((ext', names) : dirlist) | ext' == ext = [n <.> ext' | n <- names] | otherwise = dlByExt ext dirlist -- Search for multiple extensions at once. 'exts' must be sorted, with no -- duplicates. dlByExts :: [String] -> DirList -> [String] dlByExts _ [] = [] dlByExts [] _ = [] dlByExts (ext:exts) ((ext', names):dirlist) = case compare ext ext' of -- 'ext' isn't in the list. LT -> dlByExts exts ((ext', names):dirlist) -- 'ext' is right here. EQ -> [n <.> ext' | n <- names] ++ dlByExts exts dirlist -- 'ext' may be in the remainder. Nothing else can match here. GT -> dlByExts (ext:exts) dirlist -- Insert a file, given its extension. Again linear. dlAdd :: FilePath -> DirList -> DirList dlAdd file dirList = dlAddByExt (takeExtension file) (dropExtension file) dirList -- Keeps the list sorted by extension dlAddByExt :: String -> String -> DirList -> DirList dlAddByExt ext name [] = [(ext, [name])] dlAddByExt ext name ((ext', names):dirlist) = case compare ext ext' of LT -> (ext, [name]):(ext', names):dirlist EQ -> (ext', name:names):dirlist GT -> (ext', names):(dlAddByExt ext name dirlist) -- -- A map from directory to contents, excluding subdirectories. -- type TreeDB = Trie DirList deriving instance Typeable Trie tdbEmpty :: TreeDB tdbEmpty = T.empty -- Get directory contents by directory path tdbByDir :: FilePath -> TreeDB -> Maybe DirList tdbByDir path treeDB = T.lookup (C.pack path) treeDB -- Add a file tdbAdd :: FilePath -> TreeDB -> TreeDB tdbAdd path treeDB | T.member dirS treeDB = T.adjust (\dirList -> dlAdd file dirList) dirS treeDB | otherwise = T.insert dirS (dlAdd file dlEmpty) treeDB where dir = takeDirectory path file = takeFileName path dirS = C.pack dir -- Add a directory, complete with (relative) contents tdbAddDir :: FilePath -> [FilePath] -> TreeDB -> TreeDB tdbAddDir dir files treeDB | T.member dirS treeDB = T.adjust (\dirList -> foldr dlAdd dirList files) dirS treeDB | otherwise = T.insert dirS (foldr dlAdd dlEmpty files) treeDB where dirS = C.pack dir tdbBuild :: [FilePath] -> TreeDB tdbBuild files = foldr tdbAdd tdbEmpty files tdbMerge :: TreeDB -> TreeDB -> TreeDB tdbMerge = T.unionL -- -- Combined queries -- -- Find files by directory and extension tdbByDirExt :: FilePath -> String -> TreeDB -> Maybe [FilePath] tdbByDirExt path ext treeDB = do dirList <- tdbByDir path treeDB let filenames = dlByExt ext dirList return [ path </> file | file <- filenames ] -- Look for multiple extensions. 'exts' need not be sorted. tdbByDirExts :: FilePath -> [String] -> TreeDB -> Maybe [FilePath] tdbByDirExts path exts treeDB = do dirList <- tdbByDir path treeDB let filenames = dlByExts (sort exts) dirList return [ path </> file | file <- filenames ]
kishoredbn/barrelfish
hake/TreeDB.hs
mit
3,589
0
12
802
1,101
590
511
76
3
{- | Module : ./SoftFOL/tests/PrintTests.hs Copyright : (c) C. Maeder, DFKI GmbH 2010 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : experimental Portability : portable -} module Main where import Test.HUnit import SoftFOL.Sign import SoftFOL.Print import Common.AS_Annotation import Common.DocUtils import Common.Id toTestFormula :: SPTerm -> SPFormula toTestFormula = makeNamed "testformula" printProblemTest = TestList [ TestLabel "problem" (TestCase (assertEqual "" expected actual)) ] where expected = "begin_problem(testproblem).\n\n" ++ descr_expected ++ "\n\n" ++ logical_part_expected ++ "\n\nend_problem." descr_expected = "list_of_descriptions.\nname({* testdesc *}).\n" ++ "author({* testauthor *}).\nstatus(unknown).\n" ++ "description({* Just a test. *}).\nend_of_list." logical_part_expected = "list_of_symbols.\nfunctions[(foo, 1), bar].\n" ++ "end_of_list.\n\nlist_of_declarations.\n" ++ "subsort(a, b).\nsort a generated by [genA].\n" ++ "end_of_list.\n\nlist_of_formulae(axioms).\n" ++ "formula(equal(a, a), testformula).\n" ++ "end_of_list.\nlist_of_formulae(conjectures).\n" ++ "formula(equal(a, a), testformula).\n" ++ "formula(equal(a, a), testformula).\nend_of_list." actual = showDoc SPProblem {identifier = "testproblem", description = descr, logicalPart = logical_part, settings = []} "" descr = SPDescription {name = "testdesc", author = "testauthor", version = Nothing, logic = Nothing, status = SPStateUnknown, desc = "Just a test.", date = Nothing} logical_part = emptySPLogicalPart {symbolList = Just SPSymbolList {functions = syms, predicates = [], sorts = []}, declarationList = Just [ SPSubsortDecl {sortSymA = mkSimpleId "a", sortSymB = mkSimpleId "b"}, SPGenDecl {sortSym = mkSimpleId "a", freelyGenerated = False, funcList = [mkSimpleId "genA"]}], formulaLists = [SPFormulaList {originType = SPOriginAxioms, formulae = [toTestFormula SPComplexTerm {symbol = SPEqual, arguments = [ simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "a")]}]}, SPFormulaList {originType = SPOriginConjectures, formulae = [toTestFormula SPComplexTerm {symbol = SPEqual, arguments = [simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "a")]}, toTestFormula SPComplexTerm {symbol = SPEqual, arguments = [simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "a")]}]}]} syms = [SPSignSym {sym = mkSimpleId "foo", arity = 1} , SPSimpleSignSym $ mkSimpleId "bar"] printLogicalPartTest = TestList [ TestLabel "logical_part" (TestCase (assertEqual "" expected actual)) ] where expected = "list_of_symbols.\nfunctions[(foo, 1), bar].\nend_of_list.\n" ++ "\nlist_of_declarations.\nsubsort(a, b).\n" ++ "sort a generated by [genA].\nend_of_list.\n" ++ "\nlist_of_formulae(axioms).\n" ++ "formula(equal(a, a), testformula).\nend_of_list.\n" ++ "list_of_formulae(conjectures).\n" ++ "formula(equal(a, a), testformula).\n" ++ "formula(equal(a, a), testformula).\nend_of_list." actual = showDoc (emptySPLogicalPart {symbolList = Just SPSymbolList {functions = syms, predicates = [], sorts = []}, declarationList = Just [SPSubsortDecl {sortSymA = mkSimpleId "a", sortSymB = mkSimpleId "b"}, SPGenDecl {sortSym = mkSimpleId "a", freelyGenerated = False, funcList = [mkSimpleId "genA"]}], formulaLists = [SPFormulaList {originType = SPOriginAxioms, formulae = [toTestFormula SPComplexTerm {symbol = SPEqual, arguments = [simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "a")]}]}, SPFormulaList {originType = SPOriginConjectures, formulae = [toTestFormula SPComplexTerm {symbol = SPEqual, arguments = [simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "a")]}, toTestFormula SPComplexTerm {symbol = SPEqual, arguments = [simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "a")]}]}]}) "" syms = [SPSignSym {sym = mkSimpleId "foo", arity = 1} , SPSimpleSignSym $ mkSimpleId "bar"] printSymbolListTest = TestList [ TestLabel "sym_list_functions" (TestCase (assertEqual "" ("list_of_symbols.\nfunctions[(foo, 1), bar].\n" ++ "end_of_list.") (showDoc SPSymbolList {functions = syms, predicates = [], sorts = []} ""))), TestLabel "sym_list_predicates" (TestCase (assertEqual "" ("list_of_symbols.\npredicates[(foo, 1), bar].\n" ++ "end_of_list.") (showDoc SPSymbolList {functions = [], predicates = syms, sorts = []} ""))), TestLabel "sym_list_sorts" (TestCase (assertEqual "" ("list_of_symbols.\nsorts[(foo, 1), bar].\n" ++ "end_of_list.") (showDoc SPSymbolList {functions = [], predicates = [], sorts = syms} ""))) ] where syms = [SPSignSym {sym = mkSimpleId "foo", arity = 1} , SPSimpleSignSym $ mkSimpleId "bar"] printSignSymTest = TestList [ TestLabel "sign_sym" (TestCase (assertEqual "" "(a, 1)" (showDoc SPSignSym {sym = mkSimpleId "a", arity = 1} ""))), TestLabel "simple_sign_sym" (TestCase (assertEqual "" "b" (showDoc (SPSimpleSignSym $ mkSimpleId "b") ""))) ] printDeclarationTest = TestList [ TestLabel "subsort_decl" (TestCase (assertEqual "" "subsort(a, b)." (showDoc SPSubsortDecl {sortSymA = mkSimpleId "a", sortSymB = mkSimpleId "b"} ""))), TestLabel "term_decl" (TestCase ( assertEqual "" "forall([a, b], implies(a, b))." (showDoc SPTermDecl {termDeclTermList = [simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "b")], termDeclTerm = SPComplexTerm {symbol = SPImplies, arguments = [simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "b")]}} ""))), TestLabel "simple_term_decl" (TestCase (assertEqual "" "asimpletestterm." (showDoc (SPSimpleTermDecl (simpTerm (mkSPCustomSymbol "asimpletestterm"))) ""))), TestLabel "pred_decl1" (TestCase (assertEqual "" "predicate(a, b)." (showDoc SPPredDecl {predSym = mkSimpleId "a", sortSyms = [mkSimpleId "b"]} ""))), TestLabel "pred_decl2" (TestCase (assertEqual "" "predicate(a, b, c)." (showDoc SPPredDecl {predSym = mkSimpleId "a", sortSyms = map mkSimpleId ["b", "c"]} ""))), TestLabel "gen_decl1" (TestCase (assertEqual "" "sort a generated by [genA]." (showDoc SPGenDecl {sortSym = mkSimpleId "a", freelyGenerated = False, funcList = [mkSimpleId "genA"]} ""))), TestLabel "gen_decl2" (TestCase (assertEqual "" "sort a generated by [genA, genA2]." (showDoc SPGenDecl {sortSym = mkSimpleId "a", freelyGenerated = False, funcList = map mkSimpleId ["genA", "genA2"]} ""))), TestLabel "gen_decl3" (TestCase (assertEqual "" "sort a freely generated by [genA]." (showDoc SPGenDecl {sortSym = mkSimpleId "a", freelyGenerated = True, funcList = [mkSimpleId "genA"]} ""))), TestLabel "gen_decl4" (TestCase (assertEqual "" "sort a freely generated by [genA, genA2]." (showDoc SPGenDecl {sortSym = mkSimpleId "a", freelyGenerated = True, funcList = map mkSimpleId ["genA", "genA2"]} ""))), TestLabel "gen_decl5" (TestCase (assertEqual "" "sort a freely generated by [genA, genA2, genA3]." (showDoc SPGenDecl {sortSym = mkSimpleId "a", freelyGenerated = True, funcList = map mkSimpleId ["genA", "genA2", "genA3"]} ""))) ] printFormulaListTest = TestList [ TestLabel "formula_list0" (TestList [ TestCase (assertEqual "" "list_of_formulae(axioms).\nend_of_list." (showDoc SPFormulaList {originType = SPOriginAxioms, formulae = []} "")), TestCase (assertEqual "" "list_of_formulae(conjectures).\nend_of_list." (showDoc SPFormulaList {originType = SPOriginConjectures, formulae = []} ""))]), TestLabel "formula_list1" (TestList [ TestCase (assertEqual "" ("list_of_formulae(axioms).\n" ++ "formula(equal(a, a), testformula).\nend_of_list.") (showDoc SPFormulaList {originType = SPOriginAxioms, formulae = [toTestFormula SPComplexTerm {symbol = SPEqual, arguments = [simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "a")]}]} "")), TestCase (assertEqual "" ("list_of_formulae(conjectures).\n" ++ "formula(equal(a, a), testformula).\nend_of_list.") (showDoc SPFormulaList {originType = SPOriginConjectures, formulae = [toTestFormula SPComplexTerm {symbol = SPEqual, arguments = [simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "a")]}]} ""))]), TestLabel "formula_list2" (TestList [ TestCase (assertEqual "" ("list_of_formulae(axioms).\n" ++ "formula(equal(a, a), testformula).\n" ++ "formula(equal(a, a), testformula).\nend_of_list.") (showDoc SPFormulaList {originType = SPOriginAxioms, formulae = [toTestFormula SPComplexTerm {symbol = SPEqual, arguments = [simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "a")]}, toTestFormula SPComplexTerm {symbol = SPEqual, arguments = [simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "a")]}]} "")), TestCase (assertEqual "" ("list_of_formulae(conjectures).\n" ++ "formula(equal(a, a), testformula).\n" ++ "formula(equal(a, a), testformula).\nend_of_list.") (showDoc SPFormulaList {originType = SPOriginConjectures, formulae = [(toTestFormula SPComplexTerm {symbol = SPEqual, arguments = [simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "a")]}) {senAttr = "testformula"}, toTestFormula SPComplexTerm {symbol = SPEqual, arguments = [simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "a")]}]} ""))]) ] printFormulaTest = TestList [ TestLabel "formula" (TestCase (assertEqual "" "formula(equal(a, a), testformula)." (show (printFormula (toTestFormula SPComplexTerm {symbol = SPEqual, arguments = [simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "a")]}))))) ] printTermTest = TestList [ -- empty term list not allowed! TestLabel "quant_term1" (TestCase (assertEqual "" "forall([a], equal(a, a))" (showDoc SPQuantTerm {quantSym = SPForall, variableList = [simpTerm (mkSPCustomSymbol "a")], qFormula = SPComplexTerm {symbol = SPEqual, arguments = [simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "a")]}} ""))), TestLabel "quant_term2" (TestCase (assertEqual "" "forall([a, a], equal(a, a))" (showDoc SPQuantTerm {quantSym = SPForall, variableList = [simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "a")], qFormula = SPComplexTerm {symbol = SPEqual, arguments = [simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "a")]}} ""))), TestLabel "simple_term" (TestCase (assertEqual "" "testsymbol" (showDoc (simpTerm (mkSPCustomSymbol "testsymbol")) ""))), -- empty arguments list not allowed! TestLabel "complex_term1" (TestCase (assertEqual "" "test(a)" (showDoc SPComplexTerm {symbol = mkSPCustomSymbol "test", arguments = [simpTerm (mkSPCustomSymbol "a")]} ""))), TestLabel "complex_term2" (TestCase (assertEqual "" "implies(a, b)" (showDoc SPComplexTerm {symbol = SPImplies, arguments = [simpTerm (mkSPCustomSymbol "a"), simpTerm (mkSPCustomSymbol "b")]} "")))] printQuantSymTest = TestList [ TestLabel "forall_sym" (TestCase (assertEqual "" "forall" (showDoc SPForall ""))), TestLabel "exists_sym" (TestCase (assertEqual "" "exists" (showDoc SPExists ""))), TestLabel "custom_sym" (TestCase (assertEqual "" "custom" (showDoc (SPCustomQuantSym $ mkSimpleId "custom") "")))] printSymTest = TestList [ TestLabel "equal_sym" (TestCase (assertEqual "" "equal" (showDoc SPEqual ""))), TestLabel "true_sym" (TestCase (assertEqual "" "true" (showDoc SPTrue ""))), TestLabel "false_sym" (TestCase (assertEqual "" "false" (showDoc SPFalse ""))), TestLabel "or_sym" (TestCase (assertEqual "" "or" (showDoc SPOr ""))), TestLabel "and_sym" (TestCase (assertEqual "" "and" (showDoc SPAnd ""))), TestLabel "not_sym" (TestCase (assertEqual "" "not" (showDoc SPNot ""))), TestLabel "implies_sym" (TestCase (assertEqual "" "implies" (showDoc SPImplies ""))), TestLabel "implied_sym" (TestCase (assertEqual "" "implied" (showDoc SPImplied ""))), TestLabel "equiv_sym" (TestCase (assertEqual "" "equiv" (showDoc SPEquiv ""))), TestLabel "custom_sym" (TestCase (assertEqual "" "custom" (showDoc (mkSPCustomSymbol "custom") "")))] printDescriptionTest = TestList [ TestLabel "description1" (TestCase (assertEqual "" ("list_of_descriptions.\nname({* testdesc *}).\n" ++ "author({* testauthor *}).\nstatus(unknown).\n" ++ "description({* Just a test. *}).\nend_of_list.") (showDoc SPDescription {name = "testdesc", author = "testauthor", version = Nothing, logic = Nothing, status = SPStateUnknown, desc = "Just a test.", date = Nothing} ""))), TestLabel "description2" (TestCase (assertEqual "" ("list_of_descriptions.\nname({* testdesc *}).\n" ++ "author({* testauthor *}).\nversion({* 0.1 *}).\n" ++ "logic({* logic description *}).\nstatus(unknown).\n" ++ "description({* Just a test. *}).\ndate({* today *}).\n" ++ "end_of_list.") (showDoc SPDescription {name = "testdesc", author = "testauthor", version = Just "0.1", logic = Just "logic description", status = SPStateUnknown, desc = "Just a test.", date = Just "today"} ""))) ] printLogStateTest = TestList [ TestLabel "state_satisfiable" (TestCase (assertEqual "" "satisfiable" (showDoc SPStateSatisfiable ""))), TestLabel "state_unsatisfiable" (TestCase (assertEqual "" "unsatisfiable" (showDoc SPStateUnsatisfiable ""))), TestLabel "state_unkwown" (TestCase (assertEqual "" "unknown" (showDoc SPStateUnknown "")))] tests = TestList [ printProblemTest, printLogicalPartTest, printSymbolListTest, printSignSymTest, printDeclarationTest, printFormulaListTest, printFormulaTest, printTermTest, printQuantSymTest, printSymTest, printDescriptionTest, printLogStateTest] main :: IO () main = do c <- runTestTT tests return ()
spechub/Hets
SoftFOL/tests/PrintTests.hs
gpl-2.0
16,893
0
27
5,184
3,836
2,083
1,753
277
1
-- | This module provide a totally partial and incomplete maping -- of Exif values. Used for Tiff parsing and reused for Exif extraction. module Codec.Picture.Metadata.Exif ( ExifTag( .. ) , ExifData( .. ) , tagOfWord16 , word16OfTag ) where import Control.DeepSeq( NFData( .. ) ) import Data.Int( Int32 ) import Data.Word( Word16, Word32 ) import qualified Data.Vector as V import qualified Data.ByteString as B -- | Tag values used for exif fields. Completly incomplete data ExifTag = TagPhotometricInterpretation | TagCompression -- ^ Short type | TagImageWidth -- ^ Short or long type | TagImageLength -- ^ Short or long type | TagXResolution -- ^ Rational type | TagYResolution -- ^ Rational type | TagResolutionUnit -- ^ Short type | TagRowPerStrip -- ^ Short or long type | TagStripByteCounts -- ^ Short or long | TagStripOffsets -- ^ Short or long | TagBitsPerSample -- ^ Short | TagColorMap -- ^ Short | TagTileWidth | TagTileLength | TagTileOffset | TagTileByteCount | TagSamplesPerPixel -- ^ Short | TagArtist | TagDocumentName | TagSoftware | TagPlanarConfiguration -- ^ Short | TagOrientation | TagSampleFormat -- ^ Short | TagInkSet | TagSubfileType | TagFillOrder | TagYCbCrCoeff | TagYCbCrSubsampling | TagYCbCrPositioning | TagReferenceBlackWhite | TagXPosition | TagYPosition | TagExtraSample | TagImageDescription | TagPredictor | TagCopyright | TagMake | TagModel | TagDateTime | TagGPSInfo | TagJpegProc | TagJPEGInterchangeFormat | TagJPEGInterchangeFormatLength | TagJPEGRestartInterval | TagJPEGLosslessPredictors | TagJPEGPointTransforms | TagJPEGQTables | TagJPEGDCTables | TagJPEGACTables | TagExifOffset | TagUnknown !Word16 deriving (Eq, Ord, Show) -- | Convert a value to it's corresponding Exif tag. -- Will often be written as 'TagUnknown' tagOfWord16 :: Word16 -> ExifTag tagOfWord16 v = case v of 255 -> TagSubfileType 256 -> TagImageWidth 257 -> TagImageLength 258 -> TagBitsPerSample 259 -> TagCompression 262 -> TagPhotometricInterpretation 266 -> TagFillOrder 269 -> TagDocumentName 270 -> TagImageDescription 271 -> TagMake 272 -> TagModel 273 -> TagStripOffsets 274 -> TagOrientation 277 -> TagSamplesPerPixel 278 -> TagRowPerStrip 279 -> TagStripByteCounts 282 -> TagXResolution 283 -> TagYResolution 284 -> TagPlanarConfiguration 286 -> TagXPosition 287 -> TagYPosition 296 -> TagResolutionUnit 305 -> TagSoftware 306 -> TagDateTime 315 -> TagArtist 317 -> TagPredictor 320 -> TagColorMap 322 -> TagTileWidth 323 -> TagTileLength 324 -> TagTileOffset 325 -> TagTileByteCount 332 -> TagInkSet 338 -> TagExtraSample 339 -> TagSampleFormat 529 -> TagYCbCrCoeff 512 -> TagJpegProc 513 -> TagJPEGInterchangeFormat 514 -> TagJPEGInterchangeFormatLength 515 -> TagJPEGRestartInterval 517 -> TagJPEGLosslessPredictors 518 -> TagJPEGPointTransforms 519 -> TagJPEGQTables 520 -> TagJPEGDCTables 521 -> TagJPEGACTables 530 -> TagYCbCrSubsampling 531 -> TagYCbCrPositioning 532 -> TagReferenceBlackWhite 33432 -> TagCopyright 34665 -> TagExifOffset 34853 -> TagGPSInfo vv -> TagUnknown vv -- | Convert a tag to it's corresponding value. word16OfTag :: ExifTag -> Word16 word16OfTag t = case t of TagSubfileType -> 255 TagImageWidth -> 256 TagImageLength -> 257 TagBitsPerSample -> 258 TagCompression -> 259 TagPhotometricInterpretation -> 262 TagFillOrder -> 266 TagDocumentName -> 269 TagImageDescription -> 270 TagMake -> 271 TagModel -> 272 TagStripOffsets -> 273 TagOrientation -> 274 TagSamplesPerPixel -> 277 TagRowPerStrip -> 278 TagStripByteCounts -> 279 TagXResolution -> 282 TagYResolution -> 283 TagPlanarConfiguration -> 284 TagXPosition -> 286 TagYPosition -> 287 TagResolutionUnit -> 296 TagSoftware -> 305 TagDateTime -> 306 TagArtist -> 315 TagPredictor -> 317 TagColorMap -> 320 TagTileWidth -> 322 TagTileLength -> 323 TagTileOffset -> 324 TagTileByteCount -> 325 TagInkSet -> 332 TagExtraSample -> 338 TagSampleFormat -> 339 TagYCbCrCoeff -> 529 TagJpegProc -> 512 TagJPEGInterchangeFormat -> 513 TagJPEGInterchangeFormatLength -> 514 TagJPEGRestartInterval -> 515 TagJPEGLosslessPredictors -> 517 TagJPEGPointTransforms -> 518 TagJPEGQTables -> 519 TagJPEGDCTables -> 520 TagJPEGACTables -> 521 TagYCbCrSubsampling -> 530 TagYCbCrPositioning -> 531 TagReferenceBlackWhite -> 532 TagCopyright -> 33432 TagExifOffset -> 34665 TagGPSInfo -> 34853 (TagUnknown v) -> v -- | Possible data held by an Exif tag data ExifData = ExifNone | ExifLong !Word32 | ExifShort !Word16 | ExifString !B.ByteString | ExifUndefined !B.ByteString | ExifShorts !(V.Vector Word16) | ExifLongs !(V.Vector Word32) | ExifRational !Word32 !Word32 | ExifSignedRational !Int32 !Int32 | ExifIFD ![(ExifTag, ExifData)] deriving Show instance NFData ExifTag where rnf a = a `seq` () instance NFData ExifData where rnf (ExifIFD ifds) = rnf ifds `seq` () rnf (ExifLongs l) = rnf l `seq` () rnf (ExifShorts l) = rnf l `seq` () rnf a = a `seq` ()
clinty/Juicy.Pixels
src/Codec/Picture/Metadata/Exif.hs
bsd-3-clause
5,379
0
10
1,210
1,164
638
526
211
51
module CmmMachOp ( MachOp(..) , pprMachOp, isCommutableMachOp, isAssociativeMachOp , isComparisonMachOp, machOpResultType , machOpArgReps, maybeInvertComparison -- MachOp builders , mo_wordAdd, mo_wordSub, mo_wordEq, mo_wordNe,mo_wordMul, mo_wordSQuot , mo_wordSRem, mo_wordSNeg, mo_wordUQuot, mo_wordURem , mo_wordSGe, mo_wordSLe, mo_wordSGt, mo_wordSLt, mo_wordUGe , mo_wordULe, mo_wordUGt, mo_wordULt , mo_wordAnd, mo_wordOr, mo_wordXor, mo_wordNot, mo_wordShl, mo_wordSShr, mo_wordUShr , mo_u_8To32, mo_s_8To32, mo_u_16To32, mo_s_16To32 , mo_u_8ToWord, mo_s_8ToWord, mo_u_16ToWord, mo_s_16ToWord, mo_u_32ToWord, mo_s_32ToWord , mo_32To8, mo_32To16, mo_WordTo8, mo_WordTo16, mo_WordTo32 -- CallishMachOp , CallishMachOp(..) , pprCallishMachOp ) where #include "HsVersions.h" import CmmType import Outputable ----------------------------------------------------------------------------- -- MachOp ----------------------------------------------------------------------------- {- | Machine-level primops; ones which we can reasonably delegate to the native code generators to handle. Most operations are parameterised by the 'Width' that they operate on. Some operations have separate signed and unsigned versions, and float and integer versions. -} data MachOp -- Integer operations (insensitive to signed/unsigned) = MO_Add Width | MO_Sub Width | MO_Eq Width | MO_Ne Width | MO_Mul Width -- low word of multiply -- Signed multiply/divide | MO_S_MulMayOflo Width -- nonzero if signed multiply overflows | MO_S_Quot Width -- signed / (same semantics as IntQuotOp) | MO_S_Rem Width -- signed % (same semantics as IntRemOp) | MO_S_Neg Width -- unary - -- Unsigned multiply/divide | MO_U_MulMayOflo Width -- nonzero if unsigned multiply overflows | MO_U_Quot Width -- unsigned / (same semantics as WordQuotOp) | MO_U_Rem Width -- unsigned % (same semantics as WordRemOp) -- Signed comparisons | MO_S_Ge Width | MO_S_Le Width | MO_S_Gt Width | MO_S_Lt Width -- Unsigned comparisons | MO_U_Ge Width | MO_U_Le Width | MO_U_Gt Width | MO_U_Lt Width -- Floating point arithmetic | MO_F_Add Width | MO_F_Sub Width | MO_F_Neg Width -- unary - | MO_F_Mul Width | MO_F_Quot Width -- Floating point comparison | MO_F_Eq Width | MO_F_Ne Width | MO_F_Ge Width | MO_F_Le Width | MO_F_Gt Width | MO_F_Lt Width -- Bitwise operations. Not all of these may be supported -- at all sizes, and only integral Widths are valid. | MO_And Width | MO_Or Width | MO_Xor Width | MO_Not Width | MO_Shl Width | MO_U_Shr Width -- unsigned shift right | MO_S_Shr Width -- signed shift right -- Conversions. Some of these will be NOPs. -- Floating-point conversions use the signed variant. | MO_SF_Conv Width Width -- Signed int -> Float | MO_FS_Conv Width Width -- Float -> Signed int | MO_SS_Conv Width Width -- Signed int -> Signed int | MO_UU_Conv Width Width -- unsigned int -> unsigned int | MO_FF_Conv Width Width -- Float -> Float deriving (Eq, Show) pprMachOp :: MachOp -> SDoc pprMachOp mo = text (show mo) -- ----------------------------------------------------------------------------- -- Some common MachReps -- A 'wordRep' is a machine word on the target architecture -- Specifically, it is the size of an Int#, Word#, Addr# -- and the unit of allocation on the stack and the heap -- Any pointer is also guaranteed to be a wordRep. mo_wordAdd, mo_wordSub, mo_wordEq, mo_wordNe,mo_wordMul, mo_wordSQuot , mo_wordSRem, mo_wordSNeg, mo_wordUQuot, mo_wordURem , mo_wordSGe, mo_wordSLe, mo_wordSGt, mo_wordSLt, mo_wordUGe , mo_wordULe, mo_wordUGt, mo_wordULt , mo_wordAnd, mo_wordOr, mo_wordXor, mo_wordNot, mo_wordShl, mo_wordSShr, mo_wordUShr , mo_u_8To32, mo_s_8To32, mo_u_16To32, mo_s_16To32 , mo_u_8ToWord, mo_s_8ToWord, mo_u_16ToWord, mo_s_16ToWord, mo_u_32ToWord, mo_s_32ToWord , mo_32To8, mo_32To16, mo_WordTo8, mo_WordTo16, mo_WordTo32 :: MachOp mo_wordAdd = MO_Add wordWidth mo_wordSub = MO_Sub wordWidth mo_wordEq = MO_Eq wordWidth mo_wordNe = MO_Ne wordWidth mo_wordMul = MO_Mul wordWidth mo_wordSQuot = MO_S_Quot wordWidth mo_wordSRem = MO_S_Rem wordWidth mo_wordSNeg = MO_S_Neg wordWidth mo_wordUQuot = MO_U_Quot wordWidth mo_wordURem = MO_U_Rem wordWidth mo_wordSGe = MO_S_Ge wordWidth mo_wordSLe = MO_S_Le wordWidth mo_wordSGt = MO_S_Gt wordWidth mo_wordSLt = MO_S_Lt wordWidth mo_wordUGe = MO_U_Ge wordWidth mo_wordULe = MO_U_Le wordWidth mo_wordUGt = MO_U_Gt wordWidth mo_wordULt = MO_U_Lt wordWidth mo_wordAnd = MO_And wordWidth mo_wordOr = MO_Or wordWidth mo_wordXor = MO_Xor wordWidth mo_wordNot = MO_Not wordWidth mo_wordShl = MO_Shl wordWidth mo_wordSShr = MO_S_Shr wordWidth mo_wordUShr = MO_U_Shr wordWidth mo_u_8To32 = MO_UU_Conv W8 W32 mo_s_8To32 = MO_SS_Conv W8 W32 mo_u_16To32 = MO_UU_Conv W16 W32 mo_s_16To32 = MO_SS_Conv W16 W32 mo_u_8ToWord = MO_UU_Conv W8 wordWidth mo_s_8ToWord = MO_SS_Conv W8 wordWidth mo_u_16ToWord = MO_UU_Conv W16 wordWidth mo_s_16ToWord = MO_SS_Conv W16 wordWidth mo_s_32ToWord = MO_SS_Conv W32 wordWidth mo_u_32ToWord = MO_UU_Conv W32 wordWidth mo_WordTo8 = MO_UU_Conv wordWidth W8 mo_WordTo16 = MO_UU_Conv wordWidth W16 mo_WordTo32 = MO_UU_Conv wordWidth W32 mo_32To8 = MO_UU_Conv W32 W8 mo_32To16 = MO_UU_Conv W32 W16 -- ---------------------------------------------------------------------------- -- isCommutableMachOp {- | Returns 'True' if the MachOp has commutable arguments. This is used in the platform-independent Cmm optimisations. If in doubt, return 'False'. This generates worse code on the native routes, but is otherwise harmless. -} isCommutableMachOp :: MachOp -> Bool isCommutableMachOp mop = case mop of MO_Add _ -> True MO_Eq _ -> True MO_Ne _ -> True MO_Mul _ -> True MO_S_MulMayOflo _ -> True MO_U_MulMayOflo _ -> True MO_And _ -> True MO_Or _ -> True MO_Xor _ -> True _other -> False -- ---------------------------------------------------------------------------- -- isAssociativeMachOp {- | Returns 'True' if the MachOp is associative (i.e. @(x+y)+z == x+(y+z)@) This is used in the platform-independent Cmm optimisations. If in doubt, return 'False'. This generates worse code on the native routes, but is otherwise harmless. -} isAssociativeMachOp :: MachOp -> Bool isAssociativeMachOp mop = case mop of MO_Add {} -> True -- NB: does not include MO_Mul {} -> True -- floatint point! MO_And {} -> True MO_Or {} -> True MO_Xor {} -> True _other -> False -- ---------------------------------------------------------------------------- -- isComparisonMachOp {- | Returns 'True' if the MachOp is a comparison. If in doubt, return False. This generates worse code on the native routes, but is otherwise harmless. -} isComparisonMachOp :: MachOp -> Bool isComparisonMachOp mop = case mop of MO_Eq _ -> True MO_Ne _ -> True MO_S_Ge _ -> True MO_S_Le _ -> True MO_S_Gt _ -> True MO_S_Lt _ -> True MO_U_Ge _ -> True MO_U_Le _ -> True MO_U_Gt _ -> True MO_U_Lt _ -> True MO_F_Eq {} -> True MO_F_Ne {} -> True MO_F_Ge {} -> True MO_F_Le {} -> True MO_F_Gt {} -> True MO_F_Lt {} -> True _other -> False -- ----------------------------------------------------------------------------- -- Inverting conditions -- Sometimes it's useful to be able to invert the sense of a -- condition. Not all conditional tests are invertible: in -- particular, floating point conditionals cannot be inverted, because -- there exist floating-point values which return False for both senses -- of a condition (eg. !(NaN > NaN) && !(NaN /<= NaN)). maybeInvertComparison :: MachOp -> Maybe MachOp maybeInvertComparison op = case op of -- None of these Just cases include floating point MO_Eq r -> Just (MO_Ne r) MO_Ne r -> Just (MO_Eq r) MO_U_Lt r -> Just (MO_U_Ge r) MO_U_Gt r -> Just (MO_U_Le r) MO_U_Le r -> Just (MO_U_Gt r) MO_U_Ge r -> Just (MO_U_Lt r) MO_S_Lt r -> Just (MO_S_Ge r) MO_S_Gt r -> Just (MO_S_Le r) MO_S_Le r -> Just (MO_S_Gt r) MO_S_Ge r -> Just (MO_S_Lt r) MO_F_Eq r -> Just (MO_F_Ne r) MO_F_Ne r -> Just (MO_F_Eq r) MO_F_Ge r -> Just (MO_F_Le r) MO_F_Le r -> Just (MO_F_Ge r) MO_F_Gt r -> Just (MO_F_Lt r) MO_F_Lt r -> Just (MO_F_Gt r) _other -> Nothing -- ---------------------------------------------------------------------------- -- machOpResultType {- | Returns the MachRep of the result of a MachOp. -} machOpResultType :: MachOp -> [CmmType] -> CmmType machOpResultType mop tys = case mop of MO_Add {} -> ty1 -- Preserve GC-ptr-hood MO_Sub {} -> ty1 -- of first arg MO_Mul r -> cmmBits r MO_S_MulMayOflo r -> cmmBits r MO_S_Quot r -> cmmBits r MO_S_Rem r -> cmmBits r MO_S_Neg r -> cmmBits r MO_U_MulMayOflo r -> cmmBits r MO_U_Quot r -> cmmBits r MO_U_Rem r -> cmmBits r MO_Eq {} -> comparisonResultRep MO_Ne {} -> comparisonResultRep MO_S_Ge {} -> comparisonResultRep MO_S_Le {} -> comparisonResultRep MO_S_Gt {} -> comparisonResultRep MO_S_Lt {} -> comparisonResultRep MO_U_Ge {} -> comparisonResultRep MO_U_Le {} -> comparisonResultRep MO_U_Gt {} -> comparisonResultRep MO_U_Lt {} -> comparisonResultRep MO_F_Add r -> cmmFloat r MO_F_Sub r -> cmmFloat r MO_F_Mul r -> cmmFloat r MO_F_Quot r -> cmmFloat r MO_F_Neg r -> cmmFloat r MO_F_Eq {} -> comparisonResultRep MO_F_Ne {} -> comparisonResultRep MO_F_Ge {} -> comparisonResultRep MO_F_Le {} -> comparisonResultRep MO_F_Gt {} -> comparisonResultRep MO_F_Lt {} -> comparisonResultRep MO_And {} -> ty1 -- Used for pointer masking MO_Or {} -> ty1 MO_Xor {} -> ty1 MO_Not r -> cmmBits r MO_Shl r -> cmmBits r MO_U_Shr r -> cmmBits r MO_S_Shr r -> cmmBits r MO_SS_Conv _ to -> cmmBits to MO_UU_Conv _ to -> cmmBits to MO_FS_Conv _ to -> cmmBits to MO_SF_Conv _ to -> cmmFloat to MO_FF_Conv _ to -> cmmFloat to where (ty1:_) = tys comparisonResultRep :: CmmType comparisonResultRep = bWord -- is it? -- ----------------------------------------------------------------------------- -- machOpArgReps -- | This function is used for debugging only: we can check whether an -- application of a MachOp is "type-correct" by checking that the MachReps of -- its arguments are the same as the MachOp expects. This is used when -- linting a CmmExpr. machOpArgReps :: MachOp -> [Width] machOpArgReps op = case op of MO_Add r -> [r,r] MO_Sub r -> [r,r] MO_Eq r -> [r,r] MO_Ne r -> [r,r] MO_Mul r -> [r,r] MO_S_MulMayOflo r -> [r,r] MO_S_Quot r -> [r,r] MO_S_Rem r -> [r,r] MO_S_Neg r -> [r] MO_U_MulMayOflo r -> [r,r] MO_U_Quot r -> [r,r] MO_U_Rem r -> [r,r] MO_S_Ge r -> [r,r] MO_S_Le r -> [r,r] MO_S_Gt r -> [r,r] MO_S_Lt r -> [r,r] MO_U_Ge r -> [r,r] MO_U_Le r -> [r,r] MO_U_Gt r -> [r,r] MO_U_Lt r -> [r,r] MO_F_Add r -> [r,r] MO_F_Sub r -> [r,r] MO_F_Mul r -> [r,r] MO_F_Quot r -> [r,r] MO_F_Neg r -> [r] MO_F_Eq r -> [r,r] MO_F_Ne r -> [r,r] MO_F_Ge r -> [r,r] MO_F_Le r -> [r,r] MO_F_Gt r -> [r,r] MO_F_Lt r -> [r,r] MO_And r -> [r,r] MO_Or r -> [r,r] MO_Xor r -> [r,r] MO_Not r -> [r] MO_Shl r -> [r,wordWidth] MO_U_Shr r -> [r,wordWidth] MO_S_Shr r -> [r,wordWidth] MO_SS_Conv from _ -> [from] MO_UU_Conv from _ -> [from] MO_SF_Conv from _ -> [from] MO_FS_Conv from _ -> [from] MO_FF_Conv from _ -> [from] ----------------------------------------------------------------------------- -- CallishMachOp ----------------------------------------------------------------------------- -- CallishMachOps tend to be implemented by foreign calls in some backends, -- so we separate them out. In Cmm, these can only occur in a -- statement position, in contrast to an ordinary MachOp which can occur -- anywhere in an expression. data CallishMachOp = MO_F64_Pwr | MO_F64_Sin | MO_F64_Cos | MO_F64_Tan | MO_F64_Sinh | MO_F64_Cosh | MO_F64_Tanh | MO_F64_Asin | MO_F64_Acos | MO_F64_Atan | MO_F64_Log | MO_F64_Exp | MO_F64_Sqrt | MO_F32_Pwr | MO_F32_Sin | MO_F32_Cos | MO_F32_Tan | MO_F32_Sinh | MO_F32_Cosh | MO_F32_Tanh | MO_F32_Asin | MO_F32_Acos | MO_F32_Atan | MO_F32_Log | MO_F32_Exp | MO_F32_Sqrt | MO_WriteBarrier | MO_Touch -- Keep variables live (when using interior pointers) -- Note that these three MachOps all take 1 extra parameter than the -- standard C lib versions. The extra (last) parameter contains -- alignment of the pointers. Used for optimisation in backends. | MO_Memcpy | MO_Memset | MO_Memmove | MO_PopCnt Width deriving (Eq, Show) pprCallishMachOp :: CallishMachOp -> SDoc pprCallishMachOp mo = text (show mo)
mcmaniac/ghc
compiler/cmm/CmmMachOp.hs
bsd-3-clause
14,455
0
10
4,149
2,965
1,606
1,359
306
43
{-# LANGUAGE OverloadedStrings #-} -- | -- Module: Trace.Hpc.Coveralls -- Copyright: (c) 2014-2015 Guillaume Nargeot -- License: BSD3 -- Maintainer: Guillaume Nargeot <[email protected]> -- Stability: experimental -- -- Functions for converting and sending hpc output to coveralls.io. module Trace.Hpc.Coveralls ( generateCoverallsFromTix ) where import Control.Applicative import Data.Aeson import Data.Aeson.Types () import qualified Data.ByteString.Lazy.Char8 as LBS import Data.Digest.Pure.MD5 import Data.Function import Data.List import qualified Data.Map.Strict as M import System.Exit (exitFailure) import Trace.Hpc.Coveralls.Config import Trace.Hpc.Coveralls.GitInfo (GitInfo) import Trace.Hpc.Coveralls.Lix import Trace.Hpc.Coveralls.Paths import Trace.Hpc.Coveralls.Types import Trace.Hpc.Coveralls.Util import Trace.Hpc.Mix import Trace.Hpc.Tix import Trace.Hpc.Util type ModuleCoverageData = ( String, -- file source code Mix, -- module index data [Integer]) -- tixs recorded by hpc type TestSuiteCoverageData = M.Map FilePath ModuleCoverageData -- single file coverage data in the format defined by coveralls.io type SimpleCoverage = [CoverageValue] -- Is there a way to restrict this to only Number and Null? type CoverageValue = Value type LixConverter = Lix -> SimpleCoverage strictConverter :: LixConverter strictConverter = map $ \lix -> case lix of Full -> Number 1 Partial -> Number 0 None -> Number 0 Irrelevant -> Null looseConverter :: LixConverter looseConverter = map $ \lix -> case lix of Full -> Number 2 Partial -> Number 1 None -> Number 0 Irrelevant -> Null toSimpleCoverage :: LixConverter -> Int -> [CoverageEntry] -> SimpleCoverage toSimpleCoverage convert lineCount = convert . toLix lineCount getExprSource :: [String] -> MixEntry -> [String] getExprSource source (hpcPos, _) = subSubSeq startCol endCol subLines where subLines = subSeq startLine endLine source startLine = startLine' - 1 startCol = startCol' - 1 (startLine', startCol', endLine, endCol) = fromHpcPos hpcPos groupMixEntryTixs :: [(MixEntry, Integer, [String])] -> [CoverageEntry] groupMixEntryTixs = map mergeOnLst3 . groupBy ((==) `on` fst . fst3) where mergeOnLst3 xxs@(x : _) = (map fst3 xxs, map snd3 xxs, trd3 x) mergeOnLst3 [] = error "mergeOnLst3 appliedTo empty list" coverageToJson :: LixConverter -> FilePath -> ModuleCoverageData -> Value coverageToJson converter filePath (source, mix, tixs) = object [ "name" .= filePath, "source_digest" .= (show . md5 . LBS.pack) source, "coverage" .= coverage] where coverage = toSimpleCoverage converter lineCount mixEntriesTixs lineCount = length $ lines source mixEntriesTixs = groupMixEntryTixs mixEntryTixs mixEntryTixs = zip3 mixEntries tixs (map getExprSource' mixEntries) Mix _ _ _ _ mixEntries = mix getExprSource' = getExprSource $ lines source toCoverallsJson :: String -> String -> Maybe String -> GitInfo -> LixConverter -> TestSuiteCoverageData -> Value toCoverallsJson serviceName jobId repoTokenM gitInfo converter testSuiteCoverageData = object $ if serviceName == "travis-ci" then withRepoToken else withGitInfo where base = [ "service_job_id" .= jobId, "service_name" .= serviceName, "source_files" .= toJsonCoverageList testSuiteCoverageData] toJsonCoverageList = map (uncurry $ coverageToJson converter) . M.toList withRepoToken = mcons (("repo_token" .=) <$> repoTokenM) base withGitInfo = ("git" .= gitInfo) : withRepoToken mergeModuleCoverageData :: ModuleCoverageData -> ModuleCoverageData -> ModuleCoverageData mergeModuleCoverageData (source, mix, tixs1) (_, _, tixs2) = (source, mix, zipWith (+) tixs1 tixs2) mergeCoverageData :: [TestSuiteCoverageData] -> TestSuiteCoverageData mergeCoverageData = foldr1 (M.unionWith mergeModuleCoverageData) readMix' :: Maybe String -> String -> String -> TixModule -> IO Mix readMix' mPkgNameVer hpcDir name tix = readMix dirs (Right tix) where dirs = nub $ (\x -> getMixPath x hpcDir name tix) <$> [Nothing, mPkgNameVer] -- | Create a list of coverage data from the tix input readCoverageData :: Maybe String -- ^ Package name-version -> String -- ^ hpc data directory -> [String] -- ^ excluded source folders -> String -- ^ test suite name -> IO TestSuiteCoverageData -- ^ coverage data list readCoverageData mPkgNameVer hpcDir excludeDirPatterns testSuiteName = do let tixPath = getTixPath hpcDir testSuiteName mTix <- readTix tixPath case mTix of Nothing -> putStrLn ("Couldn't find the file " ++ tixPath) >> dumpDirectoryTree hpcDir >> ioFailure Just (Tix tixs) -> do mixs <- mapM (readMix' mPkgNameVer hpcDir testSuiteName) tixs let files = map filePath mixs sources <- mapM readFile files let coverageDataList = zip4 files sources mixs (map tixModuleTixs tixs) let filteredCoverageDataList = filter sourceDirFilter coverageDataList return $ M.fromList $ map toFirstAndRest filteredCoverageDataList where filePath (Mix fp _ _ _ _) = fp sourceDirFilter = not . matchAny excludeDirPatterns . fst4 -- | Generate coveralls json formatted code coverage from hpc coverage data generateCoverallsFromTix :: String -- ^ CI name -> String -- ^ CI Job ID -> GitInfo -- ^ Git repo information -> Config -- ^ hpc-coveralls configuration -> Maybe String -- ^ Package name-version -> IO Value -- ^ code coverage result in json format generateCoverallsFromTix serviceName jobId gitInfo config mPkgNameVer = do mHpcDir <- firstExistingDirectory hpcDirs case mHpcDir of Nothing -> putStrLn "Couldn't find the hpc data directory" >> dumpDirectory distDir >> ioFailure Just hpcDir -> do testSuitesCoverages <- mapM (readCoverageData mPkgNameVer hpcDir excludedDirPatterns) testSuiteNames let coverageData = mergeCoverageData testSuitesCoverages return $ toCoverallsJson serviceName jobId repoTokenM gitInfo converter coverageData where excludedDirPatterns = excludedDirs config testSuiteNames = testSuites config repoTokenM = repoToken config converter = case coverageMode config of StrictlyFullLines -> strictConverter AllowPartialLines -> looseConverter ioFailure :: IO a ioFailure = putStrLn ("You can get support at " ++ gitterUrl) >> exitFailure where gitterUrl = "https://gitter.im/guillaume-nargeot/hpc-coveralls" :: String
jdnavarro/hpc-coveralls
src/Trace/Hpc/Coveralls.hs
bsd-3-clause
7,216
0
17
1,894
1,574
845
729
-1
-1
main = putStrLn "hello" foo x = y + 3 y = 7
ankhers/haskell-ide-engine
test/testdata/HaReDemote.hs
bsd-3-clause
47
1
5
16
29
13
16
3
1
{-# LANGUAGE TypeFamilies, EmptyDataDecls, GADTs #-} module T4484 where import Data.Kind (Type) type family F f :: Type data Id c = Id type instance F (Id c) = c data C :: Type -> Type where C :: f -> C (W (F f)) data W :: Type -> Type fails :: C a -> C a fails (C _) = -- We know (W (F f) ~ a) C Id -- We need (a ~ W (F (Id beta))) -- ie (a ~ W beta) -- Use the equality; we need -- (W (F f) ~ W beta) -- ie (F f ~ beta) -- Solve with beta := f works :: C (W a) -> C (W a) works (C _) = -- We know (W (F f) ~ W a) C Id -- We need (W a ~ W (F (Id beta))) -- ie (W a ~ W beta) -- Solve with beta := a
sdiehl/ghc
testsuite/tests/indexed-types/should_compile/T4484.hs
bsd-3-clause
714
0
11
273
180
102
78
-1
-1
-- | Comment on the first declaration main = return ()
sdiehl/ghc
testsuite/tests/haddock/should_compile_flag_haddock/T17561.hs
bsd-3-clause
55
0
6
11
12
6
6
1
1
{-# LANGUAGE UnicodeSyntax #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module T5886a where import Language.Haskell.TH class C α where type AT α ∷ ★ bang ∷ DecsQ bang = return [InstanceD Nothing [] (AppT (ConT ''C) (ConT ''Int)) [TySynInstD ''AT (TySynEqn [ConT ''Int] (ConT ''Int))]]
olsner/ghc
testsuite/tests/th/T5886a.hs
bsd-3-clause
337
0
14
69
114
62
52
10
1
import qualified Barcode main :: IO () main = Barcode.main
pauldoo/scratch
RealWorldHaskell/ch12/Main.hs
isc
61
0
6
12
22
12
10
3
1
module Main where import CommandLine import Control.Monad import Data.Char import Expense import Parser import PetParser import System.Environment import System.Exit import System.IO main :: IO () main = do opts <- getArgs >>= parseCmdLine logF opts LogInfo "Parsed command-line arguments" contents <- input opts logF opts LogInfo "Read file contents" exps <- execParser opts contents _ <- execIOCmds exps $ cmds opts return () where execIOCmds = foldM (\a f -> f a) execParser :: Options -> String -> IO [Expense] execParser opts cts = case runParser parseManyExpenses cts (1, 1) of Left (m, (l, c)) -> let msg = failedParse "Parse error" l c (Just m) cts in hPutStrLn stderr msg >> exitFailure Right (e, r, (l, c)) -> if not $ null r then let msg = failedParse "Incomplete parse" l c Nothing cts in hPutStrLn stderr msg >> exitFailure else logF opts LogInfo (successfulParse $ length e) >> return e where successfulParse l = "Successful parse: " ++ show l ++ " expenses" pointerLine :: Int -> String pointerLine c = replicate (c - 1) '-' ++ "^" actualLine :: Int -> String -> String actualLine l i = let linesList = lines i in if length linesList <= l - 1 then "" else linesList !! (l - 1) failedParse :: String -> Int -> Int -> Maybe String -> String -> String failedParse title l c msg cts = fullBadLine `seq` concat [ title, " at line ", show l, ", column ", show c, maybe "" (" -> " ++) msg, fullBadLine ] where badLine = dropWhile isSpace $ actualLine l cts fullBadLine = if null badLine then "" else "\n " ++ badLine ++ "\n--" ++ pointerLine c
fredmorcos/attic
projects/pet/archive/pet_haskell_petparser/Main.hs
isc
1,853
0
14
585
617
313
304
43
3
{-# LANGUAGE OverloadedStrings #-} import Data.Time.LocalTime import Data.Time.Clock import Data.Maybe import Control.Monad import System.Environment import qualified Data.Configurator as CFG import Data.Configurator.Types import Format import System.Console.Terminfo.PrettyPrint import Data.Time.Calendar import Data.Time.Clock import System.Console.GetOpt import Text.Read getHomoList :: Config -> Name -> IO (Maybe [String]) getHomoList cfg str = do r <- CFG.lookup cfg str case r of (Just (List v)) -> return $ helper v _ -> return $ Nothing where helper values = let vs = map convert values :: [Maybe String] homo = foldr (\x y -> y && isJust x) True vs in if homo then Just $ map fromJust vs else Nothing addDaysTime :: Integer -> UTCTime -> UTCTime addDaysTime i (UTCTime day t) = let dday = addDays i day in UTCTime dday t -- can't we do this better, also missing colors str2color :: String -> TermDoc -> TermDoc str2color str | str == "white" = white | str == "red" = red | str == "magenta" = magenta getColors :: Config -> Name -> IO (Coloring, Coloring, Coloring, Coloring) getColors cfg name = do s <- CFG.lookup cfg name case s of Nothing -> return (white, red, magenta, white) (Just (a,b,c,d)) -> return (str2color a, str2color b, str2color c, str2color d) getConfig :: [Worth FilePath] -> IO XmlTvPP getConfig paths = do cfg <- CFG.load paths url <- liftM (fromMaybe "") $ CFG.lookup cfg "url" chans <- liftM (fromMaybe []) $ getHomoList cfg "channels" minWidth <- liftM (fromMaybe 20) $ CFG.lookup cfg "min-width" colors <- getColors cfg "colors" yester <- liftM (fromMaybe False) $ CFG.lookup cfg "show-trailing" sort <- liftM (fromMaybe True) $ CFG.lookup cfg "sort-channels" showAired <- liftM (fromMaybe True) $ CFG.lookup cfg "show-aired" width <- getCols tz <- getCurrentTimeZone current <- getCurrentTime return $ XmlTvPP url chans tz current width minWidth colors yester sort showAired True readpos :: String -> Int readpos str = let i = read str in if i >= 0 then i else error "negative number" parseChannels :: String -> [String] parseChannels str = case readMaybe str of (Just c) -> c Nothing -> [str] options :: [OptDescr (XmlTvPP -> XmlTvPP)] options = [ Option ['t'] ["time"] (ReqArg (\d cfg -> cfg { currentTime = addDaysTime (read d) (currentTime cfg) , today = (read d) == 0}) "relative day") "relative day, -1,2,+1" , Option ['c'] ["channel"] (ReqArg (\c cfg -> cfg { channels = parseChannels c}) "channels") "channels you want to display" , Option ['w'] ["width"] (ReqArg (\w cfg -> cfg { minWidth = readpos w }) "width") "Min width of channel" , Option ['u'] ["url"] (ReqArg (\u cfg -> cfg { url = u }) "xmltv url") "url to the xmltv" ] parseArgs :: XmlTvPP -> [String] -> IO (XmlTvPP, [String]) parseArgs cfg args = case getOpt Permute options args of (o,n,[]) -> return (foldl (flip id) cfg o, n) (_,_,errs) -> ioError (userError (concat errs ++ usageInfo header options)) where header = "Usage: tv [OPTION...]" main :: IO () main = do args <- getArgs cfg <- getConfig ["$(HOME)/.config/tv/tv.cfg"] (parsed, _) <- parseArgs cfg args showTvDay parsed
dagle/hs-xmltv
src/Tv.hs
mit
3,493
0
15
915
1,277
654
623
91
3
module Data.Vector.Generic.Lifted ( unsafeFreeze , read , write , new , freeze , replicate , mapM , thaw , forM ) where import Prelude hiding (mapM, read, replicate) import Control.Monad.Trans (MonadTrans, lift) import Data.Vector.Generic (Mutable, Vector) import qualified Data.Vector.Generic as V import Data.Vector.Generic.Mutable (MVector) import qualified Data.Vector.Generic.Mutable as MV import Control.Monad.Primitive (PrimMonad, PrimState) unsafeFreeze :: (Vector v a, PrimMonad m, MonadTrans t) => Mutable v (PrimState m) a -> t m (v a) unsafeFreeze = lift . V.unsafeFreeze {-# INLINE unsafeFreeze #-} read :: (MVector v a, PrimMonad m, MonadTrans t) => v (PrimState m) a -> Int -> t m a read v i = lift (MV.read v i) {-# INLINE read #-} write :: (MVector v a, PrimMonad m, MonadTrans t) => v (PrimState m) a -> Int -> a -> t m () write v i a = lift (MV.write v i a) {-# INLINE write #-} new :: (MVector v a, PrimMonad m, MonadTrans t) => Int -> t m (v (PrimState m) a) new = lift . MV.new {-# INLINE new #-} freeze :: (Vector v a, PrimMonad m, MonadTrans t) => Mutable v (PrimState m) a -> t m (v a) freeze = lift . V.freeze {-# INLINE freeze #-} replicate :: (MVector v a, PrimMonad m, MonadTrans t) => Int -> a -> t m (v (PrimState m) a) replicate i a = lift (MV.replicate i a) mapM :: (Vector v a, Vector v b, Monad m, MonadTrans t) => (a -> m b) -> v a -> t m (v b) mapM f v = lift $ V.mapM f v {-# INLINE mapM #-} thaw :: (Vector v a, PrimMonad m, MonadTrans t) => v a -> t m (Mutable v (PrimState m) a) thaw = lift . V.thaw {-# INLINE thaw #-} forM :: (Vector v a, Vector v b, Monad m, MonadTrans t) => v a -> (a -> m b) -> t m (v b) forM = flip mapM {-# INLINE forM #-}
NicolasT/reedsolomon
src/Data/Vector/Generic/Lifted.hs
mit
1,742
0
12
388
799
427
372
43
1
-- | -- Module: Math.NumberTheory.ArithmeticFunctions.NFreedom -- Copyright: (c) 2018 Alexandre Rodrigues Baldé -- Licence: MIT -- Maintainer: Alexandre Rodrigues Baldé <[email protected]> -- -- N-free number generation. -- {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} module Math.NumberTheory.ArithmeticFunctions.NFreedom ( nFrees , nFreesBlock , sieveBlockNFree ) where import Control.Monad (forM_) import Control.Monad.ST (runST) import Data.Bits (Bits) import Data.List (scanl') import qualified Data.Vector.Unboxed as U import qualified Data.Vector.Unboxed.Mutable as MU import Math.NumberTheory.Roots import Math.NumberTheory.Primes import Math.NumberTheory.Utils.FromIntegral -- | Evaluate the `Math.NumberTheory.ArithmeticFunctions.isNFree` function over a block. -- Value at @0@, if zero falls into block, is undefined. -- -- This function should __**not**__ be used with a negative lower bound. -- If it is, the result is undefined. -- Furthermore, do not: -- -- * use a block length greater than @maxBound :: Int@. -- * use a power that is either of @0, 1@. -- -- None of these preconditions are checked, and if any occurs, the result is -- undefined, __if__ the function terminates. -- -- >>> sieveBlockNFree 2 1 10 -- [True,True,True,False,True,True,True,False,False,True] sieveBlockNFree :: forall a. (Integral a, Enum (Prime a), Bits a, UniqueFactorisation a) => Word -- ^ Power whose @n@-freedom will be checked. -> a -- ^ Lower index of the block. -> Word -- ^ Length of the block. -> U.Vector Bool -- ^ Vector of flags, where @True@ at index @i@ means the @i@-th element of -- the block is @n@-free. sieveBlockNFree _ _ 0 = U.empty sieveBlockNFree n lowIndex len' = runST $ do as <- MU.replicate (wordToInt len') True forM_ ps $ \p -> do let pPow :: a pPow = p ^ n offset :: a offset = negate lowIndex `mod` pPow -- The second argument in @Data.Vector.Unboxed.Mutable.write@ is an -- @Int@, so to avoid segmentation faults or out-of-bounds errors, -- the enumeration's higher bound must always be less than -- @maxBound :: Int@. -- As mentioned above, this is not checked when using this function -- by itself, but is carefully managed when this function is called -- by @nFrees@, see the comments in it. indices :: [a] indices = [offset, offset + pPow .. len - 1] forM_ indices $ \ix -> MU.write as (fromIntegral ix) False U.freeze as where len :: a len = fromIntegral len' highIndex :: a highIndex = lowIndex + len - 1 ps :: [a] ps = if highIndex < 4 then [] else map unPrime [nextPrime 2 .. precPrime (integerSquareRoot highIndex)] -- | For a given nonnegative integer power @n@, generate all @n@-free -- numbers in ascending order, starting at @1@. -- -- When @n@ is @0@ or @1@, the resulting list is @[1]@. nFrees :: forall a. (Integral a, Bits a, UniqueFactorisation a, Enum (Prime a)) => Word -- ^ Power @n@ to be used to generate @n@-free numbers. -> [a] -- ^ Generated infinite list of @n@-free numbers. nFrees 0 = [1] nFrees 1 = [1] nFrees n = concatMap (uncurry (nFreesBlock n)) $ zip bounds strides where -- The 56th element of @iterate (2 *) 256@ is @2^64 :: Word == 0@, so to -- avoid overflow only the first 55 elements of this list are used. -- After those, since @maxBound :: Int@ is the largest a vector can be, -- this value is just repeated. This means after a few dozen iterations, -- the sieve will stop increasing in size. strides :: [Word] strides = take 55 (iterate (2 *) 256) ++ repeat (intToWord (maxBound :: Int)) -- Infinite list of lower bounds at which @sieveBlockNFree@ will be -- applied. This has type @Integral a => a@ instead of @Word@ because -- unlike the sizes of the sieve that eventually stop increasing (see -- above comment), the lower bound at which @sieveBlockNFree@ is called does not. bounds :: [a] bounds = scanl' (+) 1 $ map fromIntegral strides -- | Generate @n@-free numbers in a block starting at a certain value. -- The length of the list is determined by the value passed in as the third -- argument. It will be lesser than or equal to this value. -- -- This function should not be used with a negative lower bound. If it is, -- the result is undefined. -- -- The block length cannot exceed @maxBound :: Int@, this precondition is not -- checked. -- -- As with @nFrees@, passing @n = 0, 1@ results in an empty list. nFreesBlock :: forall a . (Integral a, Bits a, UniqueFactorisation a, Enum (Prime a)) => Word -- ^ Power @n@ to be used to generate @n@-free numbers. -> a -- ^ Starting number in the block. -> Word -- ^ Maximum length of the block to be generated. -> [a] -- ^ Generated list of @n@-free numbers. nFreesBlock 0 lo _ = help lo nFreesBlock 1 lo _ = help lo nFreesBlock n lowIndex len = let -- When indexing the array of flags @bs@, the index has to be an -- @Int@. As such, it's necessary to cast @strd@ twice. -- * Once, immediately below, to create the range of values whose -- @n@-freedom will be tested. Since @nFrees@ has return type -- @[a]@, this cannot be avoided as @strides@ has type @[Word]@. len' :: Int len' = wordToInt len -- * Twice, immediately below, to create the range of indices with -- which to query @bs@. len'' :: a len'' = fromIntegral len bs = sieveBlockNFree n lowIndex len in map snd . filter ((bs U.!) . fst) . zip [0 .. len' - 1] $ [lowIndex .. lowIndex + len''] {-# INLINE nFreesBlock #-} help :: Integral a => a -> [a] help 1 = [1] help _ = [] {-# INLINE help #-}
Bodigrim/arithmoi
Math/NumberTheory/ArithmeticFunctions/NFreedom.hs
mit
5,954
0
16
1,486
909
525
384
75
2
{-# LANGUAGE OverloadedStrings #-} module Database.Selda.SQL.Print.Config (PPConfig (..), defPPConfig) where import Data.Text (Text) import qualified Data.Text as T import Database.Selda.SqlType import Database.Selda.Table -- | Backend-specific configuration for the SQL pretty-printer. data PPConfig = PPConfig { -- | The SQL type name of the given type. -- -- This function should be used everywhere a type is needed to be printed but in primary -- keys position. This is due to the fact that some backends might have a special -- representation of primary keys (using sequences are such). If you have such a need, -- please use the 'ppTypePK' record instead. ppType :: SqlTypeRep -> Text -- | Hook that allows you to modify 'ppType' output. , ppTypeHook :: SqlTypeRep -> [ColAttr] -> (SqlTypeRep -> Text) -> Text -- | The SQL type name of the given type for primary keys uses. , ppTypePK :: SqlTypeRep -> Text -- | Parameter placeholder for the @n@th parameter. , ppPlaceholder :: Int -> Text -- | List of column attributes. , ppColAttrs :: [ColAttr] -> Text -- | Hook that allows you to modify 'ppColAttrs' output. , ppColAttrsHook :: SqlTypeRep -> [ColAttr] -> ([ColAttr] -> Text) -> Text -- | The value used for the next value for an auto-incrementing column. -- For instance, @DEFAULT@ for PostgreSQL, and @NULL@ for SQLite. , ppAutoIncInsert :: Text -- | Insert queries may have at most this many parameters; if an insertion -- has more parameters than this, it will be chunked. -- -- Note that only insertions of multiple rows are chunked. If your table -- has more than this many columns, you should really rethink -- your database design. , ppMaxInsertParams :: Maybe Int -- | @CREATE INDEX@ suffix to indicate that the index should use the given -- index method. , ppIndexMethodHook :: IndexMethod -> Text } -- | Default settings for pretty-printing. -- Geared towards SQLite. -- -- The default definition of 'ppTypePK' is 'defType, so that you don’t have to do anything -- special if you don’t use special types for primary keys. defPPConfig :: PPConfig defPPConfig = PPConfig { ppType = defType , ppTypeHook = \ty _ _ -> defType ty , ppTypePK = defType , ppPlaceholder = T.cons '$' . T.pack . show , ppColAttrs = T.unwords . map defColAttr , ppColAttrsHook = \_ ats _ -> T.unwords $ map defColAttr ats , ppAutoIncInsert = "NULL" , ppMaxInsertParams = Nothing , ppIndexMethodHook = const "" } -- | Default compilation for SQL types. -- By default, anything we don't know is just a blob. defType :: SqlTypeRep -> Text defType TText = "TEXT" defType TRowID = "INTEGER" defType TInt32 = "INT" defType TInt64 = "BIGINT" defType TFloat = "DOUBLE PRECISION" defType TBool = "BOOLEAN" defType TDateTime = "DATETIME" defType TDate = "DATE" defType TTime = "TIME" defType TBlob = "BLOB" defType TUUID = "BLOB" defType TJSON = "BLOB" -- | Default compilation for a column attribute. defColAttr :: ColAttr -> Text defColAttr Primary = "" defColAttr (AutoPrimary Strong) = "PRIMARY KEY AUTOINCREMENT" defColAttr (AutoPrimary Weak) = "PRIMARY KEY" defColAttr Required = "NOT NULL" defColAttr Optional = "NULL" defColAttr Unique = "UNIQUE" defColAttr (Indexed _) = ""
valderman/selda
selda/src/Database/Selda/SQL/Print/Config.hs
mit
3,457
0
14
814
531
312
219
48
1
module Main where import Control.Monad import Data.IORef import Data.Tuple.HT import FRP.Yampa import Graphics import Graphics.Rendering.OpenGL import Graphics.UI.GLUT import System.Exit import Types import Simulation -- Entry point. main :: IO () main = do newInput <- newIORef NoEvent oldTime <- newIORef (0 :: Int) rh <- reactInit (initGL >> return NoEvent) (\_ _ b -> b >> return False) simulate -- We allow control over the position of the ball, though the rate of spin is -- determined as a constant. keyboardMouseCallback $= Just (keyMouse newInput) displayCallback $= return () idleCallback $= Just (idle newInput oldTime rh) mainLoop where keyMouse _keyEv (Char '\27') Down _ _ = exitSuccess keyMouse keyEv (Char ' ') Down _ _ = writeIORef keyEv $ Event () keyMouse _keyEv _ _ _ _ = return () -- Update angle of the ball when idle. -- angle the angle should idle :: IORef (Event ()) -> IORef Int -> ReactHandle (Event ()) (IO ()) -> IO () idle newInput oldTime rh = do newInput' <- readIORef newInput if isEvent newInput' then print "Spacebar pressed!" else return () newTime' <- get elapsedTime oldTime' <- readIORef oldTime let dt = let dt' = (fromIntegral $ newTime' - oldTime')/100 in if dt' < 0.8 then dt' else 0.8 -- clamping of time react rh (dt,Just newInput') writeIORef newInput NoEvent writeIORef oldTime newTime' return ()
fatuhoku/haskell-yampa-bouncing-ball
src/Main.hs
mit
1,480
0
17
360
480
236
244
38
3
import System.Random main = do gen <- getStdGen putStr $ take 20 (randomRs ('a', 'z') gen)
UoBCS/haskell-diary
monads/random/random_string.hs
mit
102
0
11
27
44
22
22
4
1
module Feature.User.PG where import ClassyPrelude import Feature.User.Types import Feature.Auth.Types import Platform.PG import Database.PostgreSQL.Simple -- * UserRepo findUserByAuth :: PG r m => Auth -> m (Maybe (UserId, User)) findUserByAuth (Auth email pass) = do results <- withConn $ \conn -> query conn qry (email, pass) case results of [(uId, name, bio, image)] -> return $ Just (uId, User email "tempToken" name bio image) _ -> return Nothing where qry = "select id, cast (name as text), bio, image \ \from users where email = ? AND pass = crypt(?, pass) \ \limit 1" findUserById :: PG r m => UserId -> m (Maybe User) findUserById uId = do results <- withConn $ \conn -> query conn qry (Only uId) case results of [(name, email, bio, image)] -> return $ Just $ User email "tempToken" name bio image _ -> return Nothing where qry = "select cast (name as text), cast (email as text), bio, image \ \from users where id = ? limit 1" addUser :: (PG r m) => Register -> Text -> m (Either UserError ()) addUser (Register name email pass) defaultImgUrl = do result <- withConn $ try . action return $ bimap (translateSqlUserError email name) (const ()) result where action conn = execute conn qry (name, email, pass, defaultImgUrl) qry = "insert into users (name, email, pass, bio, image) \ \values (?, ?, crypt(?, gen_salt('bf')), '', ?)" updateUserById :: (PG r m) => UserId -> UpdateUser -> m (Either UserError ()) updateUserById uId (UpdateUser email uname pass img bio) = do result <- withConn $ try . action return $ bimap (translateSqlUserError (fromMaybe "" email) (fromMaybe "" uname)) (const ()) result where action conn = execute conn qry (email, uname, pass, img, bio, uId) qry = "update users set \ \email = coalesce(?, email), \ \name = coalesce(?, name), \ \pass = coalesce(crypt(?, gen_salt('bf')), pass), \ \image = coalesce(?, image), \ \bio = coalesce(?, bio) \ \where id = ?" translateSqlUserError :: Email -> Username -> SqlError -> UserError translateSqlUserError email username sqlError | isUniqueConstraintsViolation sqlError "users_email_key" = UserErrorEmailTaken email | isUniqueConstraintsViolation sqlError "users_name_key" = UserErrorNameTaken username | otherwise = error $ "Unknown SQL error: " <> show sqlError isUniqueConstraintsViolation :: SqlError -> ByteString -> Bool isUniqueConstraintsViolation SqlError{sqlState = state, sqlErrorMsg = msg} constraintName = state == "23505" && constraintName `isInfixOf` msg -- * ProfileRepo findProfile :: PG r m => Maybe UserId -> Username -> m (Maybe Profile) findProfile mayUserId username = do results <- withConn $ \conn -> query conn qry (mayUserId, username) return $ case results of [a] -> Just a _ -> Nothing where qry = "select cast (name as text), bio, image, exists(select 1 from followings where user_id = id and followed_by = ?) as following \ \from users where name = ? limit 1" followUserByUsername :: (PG r m) => UserId -> Username -> m (Either UserError ()) followUserByUsername uId username = do result <- withConn $ \conn -> try $ execute conn qry (uId, username) return $ case result of Left SqlError{sqlState="23503"} -> Left $ UserErrorNotFound username Left err -> error $ "Unhandled PG error: " <> show err Right _ -> Right () where qry = "insert into followings (followed_by, user_id) \ \(select ?, id from users where name = ? limit 1) on conflict do nothing" unfollowUserByUsername :: PG r m => UserId -> Username -> m () unfollowUserByUsername uId username = void . withConn $ \conn -> execute conn qry (uId, username) where qry = "delete from followings where \ \followed_by = ? and user_id in (select id from users where name = ? limit 1)"
eckyputrady/haskell-scotty-realworld-example-app
src/Feature/User/PG.hs
mit
3,969
0
14
922
1,074
548
526
69
3
{-# LANGUAGE OverloadedStrings #-} module Main (main) where import qualified Control.Foldl as Fold import Data.List (genericLength) import Data.Maybe (catMaybes) import Data.Text (unpack) import System.Exit (exitFailure, exitSuccess) import Text.Regex (matchRegex, mkRegex) import Turtle (inprocWithErr, fold) average :: (Fractional a, Real b) => [b] -> a average xs = realToFrac (sum xs) / genericLength xs expected :: Fractional a => a expected = 90 main :: IO () main = do text <- fold (fmap (\(Left o) -> o) (inprocWithErr "stack" ["haddock"] "")) Fold.list let output = map unpack text avg = average $ match output putStrLn $ "\nAverage documentation coverage: " ++ show avg if avg >= expected then exitSuccess else exitFailure match :: [String] -> [Int] match = fmap read . concat . catMaybes . fmap (matchRegex p) where p = mkRegex "^ *([0-9]*)% "
tylerjl/adventofcode
test/Haddock.hs
mit
1,020
0
14
300
326
176
150
27
2
{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-} {-# LANGUAGE UnicodeSyntax #-} -- From: Herbert P. Sander. A logic of functional programs with an -- application to concurrency. PhD thesis, Chalmers University of -- Technology and University of Gothenburg, Department of Computer -- Sciences, 1992. pp. 12-13. module Berry where import Data.Peano ( PeanoNat(S,Z) ) loop ∷ a loop = loop -- Warning: Pattern match(es) are non-exhaustive -- In an equation for `f': -- Patterns not matched: -- Z (S (S _)) _ -- Z Z Z -- Z Z (S (S _)) -- (S (S _)) (S _) _ -- ... f ∷ PeanoNat → PeanoNat → PeanoNat → PeanoNat f Z (S Z) _ = S Z f (S Z) _ Z = S (S Z) f _ Z (S Z) = S (S (S Z)) -- Tests: -- f Z (S Z) loop = 1 -- f (S Z) loop Z = 2 -- f loop Z (S Z) = *** Non-terminating ***
asr/fotc
notes/Berry/Berry.hs
mit
905
0
9
288
146
86
60
10
1
{-# LANGUAGE BangPatterns , FlexibleContexts , TypeFamilies , MultiParamTypeClasses , FunctionalDependencies , TypeSynonymInstances , FlexibleInstances #-} module RobotVision.ImageRep.Utility ( fromChannels , toChannels , getNotBoundaryPoints , getImagePoints , onBoundary ) where import Data.Array.Repa import qualified Data.Array.Repa.Repr.Unboxed as U import Data.Array.Repa.Repr.ForeignPtr as F import Data.Word import Prelude as P import Data.Convertible test = id toChannels :: (Source r e) => Array r DIM3 e -> (Array D DIM2 e, Array D DIM2 e, Array D DIM2 e) toChannels img = (r,g,b) where r = fromFunction (Z :. height :. width) rf g = fromFunction (Z :. height :. width) gf b = fromFunction (Z :. height :. width) bf (Z :. height :. width :. _) = extent img rf (Z :. y :. x) = img ! (Z :. y :. x :. 0) gf (Z :. y :. x) = img ! (Z :. y :. x :. 1) bf (Z :. y :. x) = img ! (Z :. y :. x :. 2) {-# INLINE toChannels #-} fromChannels :: (Source r e) => (Array r DIM2 e, Array r DIM2 e, Array r DIM2 e) -> Array D DIM3 e fromChannels (r,g,b) = let (Z :. width :. height) = extent r in fromFunction (Z :. width :. height :. 3) f where f (Z :. y :. x :. z) = case z of 0 -> r ! (Z :. y :. x) 1 -> g ! (Z :. y :. x) 2 -> b ! (Z :. y :. x) {-# INLINE fromChannels #-} getImagePoints :: (Source r e) => Array r DIM2 e -> [DIM2] getImagePoints img = let (Z :. y :. x) = extent img in P.map tupleToPoint $ permuteList [0 .. (y-1)] [0 .. (x-1)] tupleList :: [a] -> b -> [(a,b)] tupleList [] _ = [] tupleList (x:xs) y = (x,y) : (tupleList xs y) permuteList :: [a] -> [b] -> [(a,b)] permuteList _ [] = [] permuteList xs (y:ys) = tupleList xs y P.++ permuteList xs ys tupleToPoint :: (Int, Int) -> DIM2 tupleToPoint (x,y) = Z :. x :. y getNotBoundaryPoints :: (Source r e) => Array r DIM2 e -> [DIM2] getNotBoundaryPoints img = notBoundaryPoints img $ getImagePoints img notBoundaryPoints :: (Source r e) => Array r DIM2 e -> [DIM2] -> [DIM2] notBoundaryPoints img pts = let (Z :. w :. h) = extent img in filter (not . (onBoundary w h)) pts onTop :: Int -> DIM2 -> Bool onTop height (Z :. y :. _) = y == (height - 1) onBot :: DIM2 -> Bool onBot (Z :. y :. _) = y == 0 onLeft :: DIM2 -> Bool onLeft (Z :. _ :. x) = x == 0 onRight :: Int -> DIM2 -> Bool onRight width (Z :. _ :. x) = x == (width - 1) onBoundary :: Int -> Int -> DIM2 -> Bool onBoundary height width pt = (onTop height pt) || (onBot pt) || (onLeft pt) || (onRight width pt)
eklinkhammer/haskell-vision
RobotVision/ImageRep/Utility.hs
mit
2,685
0
13
757
1,217
651
566
66
3
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module Models where import Data.Aeson import Data.Text import Data.Time (UTCTime) import Database.Persist.Sql import Database.Persist.TH import Elm import GHC.Generics -- DB Models share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| Account firstName Text lastName Text email Text UniqueEmail email deriving Show Generic Gig date UTCTime venue Text -- venueId VenueId deriving Show Generic -- Venue json -- name Text -- locationId LocationId -- deriving Show -- Location json -- -- Consider adding for Maps or something. -- -- Maybe needs it's own model like Location -- street Text -- city Text -- state Text -- zip Integer -- deriving Show |] instance ElmType Account instance ToJSON Account instance FromJSON Account instance ElmType Gig instance ToJSON Gig instance FromJSON Gig
erlandsona/caldwell-api
library/Models.hs
mit
1,186
0
7
237
120
69
51
24
0
{-# LANGUAGE OverloadedStrings #-} module ParseCommand ( parseCommand ) where import Data.ByteString (ByteString) import qualified Data.ByteString as B import qualified Data.ByteString.UTF8 as UTF8 import Data.List import Text.Parsec import Text.Parsec.ByteString import Types parseCommand :: [CommandDef] -> ByteString -> Either ParseError Command parseCommand cl input = parse (playerCommand cl) "" input playerCommand :: [CommandDef] -> Parser Command playerCommand cl = do cmdName <- word <?> "command" case lookupCommand cmdName cl of Just cmdDef -> commandArgs cmdDef Nothing -> return $ BadCommand $ "You don't know how to \"" `B.append` UTF8.fromString cmdName `B.append` "\"." commandArgs :: CommandDef -> Parser Command commandArgs (CommandDef name [] _) = return $ BadCommand $ "That's not how you " `B.append` UTF8.fromString name `B.append` "." commandArgs (CommandDef name (CmdTypeNone:_) f) = return $ Command name CmdArgsNone f commandArgs (CommandDef name (CmdTypeString:rest) f) = do whitespace <?> "whitespace" str <- anyString <?> "arg string" return $ Command name (CmdArgsString (UTF8.fromString str)) f <|> ( commandArgs (CommandDef name rest f) ) word :: Parser String word = (many1 $ oneOf ['a'..'z']) <?> "word" anyString :: Parser String anyString = (many1 $ noneOf "\r\n") <?> "anystring" whitespace :: Parser () whitespace = skipMany1 space <?> "space" lookupCommand :: String -> [CommandDef] -> Maybe CommandDef lookupCommand str = find helper where helper (CommandDef name _ _) = isPrefixOf str name
sproctor/dirtywater
src/ParseCommand.hs
gpl-2.0
1,581
0
14
268
517
269
248
38
2
{-| Algorithm Options for HTools This module describes the parameters that influence the balancing algorithm in htools. -} {- Copyright (C) 2014 Google Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -} module Ganeti.HTools.AlgorithmParams ( AlgorithmOptions(..) , defaultOptions , fromCLIOptions ) where import qualified Ganeti.HTools.CLI as CLI data AlgorithmOptions = AlgorithmOptions { algDiskMoves :: Bool -- ^ Whether disk moves are allowed , algInstanceMoves :: Bool -- ^ Whether instance moves are allowed , algRestrictedMigration :: Bool -- ^ Whether migration is restricted , algIgnoreSoftErrors :: Bool -- ^ Whether to always ignore soft errors , algEvacMode :: Bool -- ^ Consider only eavacation moves , algMinGain :: Double -- ^ Minimal gain per balancing step , algMinGainLimit :: Double -- ^ Limit below which minimal gain is used } -- | Obtain the relevant algorithmic option from the commandline options fromCLIOptions :: CLI.Options -> AlgorithmOptions fromCLIOptions opts = AlgorithmOptions { algDiskMoves = CLI.optDiskMoves opts , algInstanceMoves = CLI.optInstMoves opts , algRestrictedMigration = CLI.optRestrictedMigrate opts , algIgnoreSoftErrors = CLI.optIgnoreSoftErrors opts , algEvacMode = CLI.optEvacMode opts , algMinGain = CLI.optMinGain opts , algMinGainLimit = CLI.optMinGainLim opts } -- | Default options for the balancing algorithm defaultOptions :: AlgorithmOptions defaultOptions = fromCLIOptions CLI.defaultOptions
ribag/ganeti-experiments
src/Ganeti/HTools/AlgorithmParams.hs
gpl-2.0
2,195
0
8
413
206
127
79
24
1
import Data.Maybe (fromJust) import Network.Circus handleEvent :: EventFunction handleEvent _ ev = case eType ev of Privmsg -> putStrLn $ fromJust (eNick ev) ++ " said in " ++ fromJust (eChannel ev) ++ ": " ++ head (eArgs ev) _ -> print ev main :: IO Session main = connect server where server = (defaultParams "irc.freenode.net" handleEvent) { pNick = "circus-hs", pChannels = ["#circus-hs"] }
DasAsozialeNetzwerk/circus
example.hs
gpl-3.0
472
0
15
142
148
76
72
9
2
module Problem39 where import Problem31(isPrime) primesR :: Int -> Int -> [Int] primesR x y = filter isPrime [x..y]
wando-hs/H-99
src/Problem39.hs
gpl-3.0
117
0
7
20
48
27
21
4
1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Risk where import Control.Monad import Control.Monad.Random import Data.List ------------------------------------------------------------ -- Die values newtype DieValue = DV { unDV :: Int } deriving (Eq, Ord, Show, Num) first :: (a -> b) -> (a, c) -> (b, c) first f (a, c) = (f a, c) instance Random DieValue where random = first DV . randomR (1,6) randomR (low,hi) = first DV . randomR (max 1 (unDV low), min 6 (unDV hi)) die :: Rand StdGen DieValue die = getRandom ------------------------------------------------------------ -- Risk type Army = Int data Battlefield = Battlefield { attackers :: Army, defenders :: Army } battle :: Battlefield -> Rand StdGen Battlefield battle (Battlefield att def) = let a = min (att - 1) 2 d = min def 2 battles = min a d in do aDies <- randList a dDies <- randList d let aWins = attWins aDies dDies return $ Battlefield (att - battles + aWins) (def - aWins) where attWins xs ys = length . filter id $ zipWith (>) (reverse . Data.List.sort $ xs) (reverse . Data.List.sort $ ys) randList n = liftM (map unDV) . replicateM n $ die invade :: Battlefield -> Rand StdGen Battlefield invade b@(Battlefield att def) = if def <= 0 || att < 2 then do return b else battle b >>= invade successProb :: Battlefield -> Rand StdGen Double successProb b = do bResult <- replicateM n (attWin b) return $ (/(fromIntegral n)) . fromIntegral . length . filter id $ bResult where attWin b = do Battlefield att def <- invade b return (att > def) n = 1000 print m n = do x <- evalRandIO (successProb (Battlefield m n)) putStrLn (show x)
lifengsun/haskell-exercise
upenn-cis-194/12/Risk.hs
gpl-3.0
2,053
0
14
734
693
357
336
45
2
module Main where import qualified Web.BitTorrent.Tracker.Tracker as Tracker main = Tracker.main
greatest-ape/hs-bt-tracker
app/Main.hs
gpl-3.0
98
0
5
12
21
15
6
3
1
module Color ( colorString , Color(..) ) where data Color = -- Bold Colors BoldBlack | BoldRed | BoldGreen | BoldYellow | BoldBlue | BoldMagenta | BoldCyan | BoldWhite | Black -- Normal Colors | Red | Green | Yellow | Blue | Magenta | Cyan | White -- This just makes the current color bold... | Bold -- This resets the colors... | Reset getColorCode :: Color -> String getColorCode color = colorCodeStarter ++ getColor color ++ colorCodeEnder where colorCodeStarter :: String colorCodeStarter = "\x1b[" colorCodeEnder :: String colorCodeEnder = "m" getColor :: Color -> String getColor BoldBlack = "30;1" getColor BoldRed = "31;1" getColor BoldGreen = "32;1" getColor BoldYellow = "33;1" getColor BoldBlue = "34;1" getColor BoldMagenta = "35;1" getColor BoldCyan = "36;1" getColor BoldWhite = "37;1" getColor Black = "30" getColor Red = "31" getColor Green = "32" getColor Yellow = "33" getColor Blue = "34" getColor Magenta = "35" getColor Cyan = "36" getColor White = "37" getColor Bold = "1" getColor Reset = "0" colorString :: Color -> String -> String colorString color string = getColorCode color ++ string ++ getColorCode Reset
cdepillabout/haskell-git-too-many-cherry-picks
Color.hs
gpl-3.0
1,496
0
7
548
318
175
143
49
18
{-# LANGUAGE FlexibleContexts #-} module Application.KMeans.Conduit where import Control.Monad.IO.Class import Control.Monad.Trans.Resource import Data.Array.Repa as R import Data.Binary import Data.Conduit import Data.Conduit.List as CL import Data.List as L import Data.Vector.Unboxed as VU import PetaVision.Data.KMeans as KMP import PetaVision.Utility.Array import PetaVision.Utility.Parallel kmeansArrSinkP :: (R.Source s Double) => ParallelParams -> FilePath -> Int -> Int -> Int -> Int -> Sink (Array s DIM3 Double) (ResourceT IO) () kmeansArrSinkP parallelParams filePath k numTrain downsampleFactor stride = do xs <- CL.take numTrain let ys = L.concatMap (extractFeaturePoint . downsample [downsampleFactor,downsampleFactor,1]) xs (Z :. _r :. _c :. ch) = extent . L.head $ xs model <- liftIO $ KMP.kmeans parallelParams k (KMP.Shape 1 1 ch stride) ys liftIO $ encodeFile filePath model kmeansVecSinkP :: ParallelParams -> FilePath -> Int -> Int -> KMP.Shape -> Sink [Vector Double] (ResourceT IO) () kmeansVecSinkP parallelParams filePath k numTrain sh = do xs <- CL.take numTrain let ys = L.concat xs model <- liftIO $ kmeans parallelParams k sh ys liftIO $ encodeFile filePath model
XinhuaZhang/PetaVisionHaskell
Application/KMeans/Conduit.hs
gpl-3.0
1,556
0
14
529
416
220
196
49
1
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE PackageImports #-} {-# LANGUAGE OverloadedStrings #-} import System.FilePath import System.Directory import qualified Data.ByteString.Lazy as BS import System.FilePath.Glob (namesMatching) import Text.Read import Data.Either (partitionEithers) import Data.List (sortBy) import Data.Ord (comparing) import Data.Monoid ((<>)) import Data.Foldable (for_) import Options.Generic import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as A import Text.Blaze.Html.Renderer.Utf8 -- Generic html stuff -- | Returns a link to a licence file indexed by an Int linkI :: H.Html -> Int -> H.Html linkI caption i = link caption (H.toValue i <> ".html") -- | Returns a link link :: H.Html -> H.AttributeValue -> H.Html link caption ref = H.a H.! A.href ref $ caption -- | html preambule, with title and body html :: H.Html -> H.Html -> H.Html html title body = H.docTypeHtml $ do H.head $ do H.title title H.body body -- Utils -- | partition either argument is in the form `XXX.ext` or not, with XXX an int. partitionInvalidNames :: FilePath -> Either FilePath (FilePath, Int) partitionInvalidNames s = case readMaybe (takeBaseName s) of Nothing -> Left s Just i -> Right (s, i) -- The real work generatePage :: FilePath -> Int -> ((FilePath, Int), Maybe Int, Maybe Int) -> IO () generatePage outDir lastI ((path, currentI), prevI, nextI) = do content <- BS.readFile path let output = generatePage' lastI (prevI, currentI, nextI) content BS.writeFile (outDir </> show currentI <.> "html") $ renderHtml $ output generatePage' :: Int -> (Maybe Int, Int, Maybe Int) -> BS.ByteString -> H.Html generatePage' lastI (prevI, currentI, nextI) content = do html ("GPL Version " <> H.toHtml currentI) $ do link "Home" "index.html" maybe mempty (linkI "Previous") prevI maybe mempty (linkI "Next") nextI linkI "Last" lastI H.pre $ H.unsafeLazyByteString content -- | generate an index linking all pages i.html generateIndex :: [Int] -> H.Html generateIndex iS = html "Index" $ do H.ul $ do for_ iS $ \i -> do H.li $ do link (H.toHtml i) (H.toValue i <> ".html") data Options = Options { inputDirectory :: FilePath, outputDirectory :: FilePath } deriving (Generic, Show, ParseRecord) main :: IO () main = do Options{..} <- getRecord "Generate HTML from text files" names <- namesMatching (inputDirectory </> "*" <.> "txt") -- only keep name looking like 'XXXX.txt', where XXXX is an int let (invalid, valid) = partitionEithers (map partitionInvalidNames names) putStr "Ignored invalid files: " print invalid let files = sortBy (comparing snd) valid idsJust = map (Just . snd) files -- previous and next button are generated only if the file exists prev_indices = Nothing : idsJust next_indices = drop 1 idsJust ++ [Nothing] lastI = snd (last files) filesWithPreviousAndNext = zip3 files prev_indices next_indices createDirectoryIfMissing False outputDirectory mapM_ (generatePage outputDirectory lastI) filesWithPreviousAndNext -- index let index = generateIndex (map snd files) BS.writeFile (outputDirectory </> "index.html") (renderHtml index)
deber/GPL_Torture
backend/language/haskell/src/app/Torture2.hs
gpl-3.0
3,315
0
22
630
1,005
521
484
74
2
{- | This module contains a purely Haskell implementation of dyadic rationals, suitable for interval arithmetic. A faster implementation of dyadic rationals would use a fast arbitrary-precision floating-point library, such as MPFR and the related hmpfr Haskell bindings for it. A dyadic number is a rational whose denominator is a power of 2. We also include positive and negative infinity, these are useful for representing infinite intervals. The special value 'NaN' (not a number) is included as well in order to follow more closely the usual floating-point format, but is not used in the interval computations because there we use [-inf, +inf] to represent the completely undefined value. -} module Dyadic ( ApproximateField(..), Dyadic(..), ) where import Data.Bits import Data.Ratio import Staged {- | An approximate field is a structure in which we can perform approximate arithmetical operations. The typical example is the ring of dyadic rational numbers: division of dyadic rationals is only approximate, and even though the other operations (+, -, *) can be peformed exactly, it is too expensive and unecessary to do so in an interval computation. Therefore, we want approximate versions of all operations. The approximate operations take a 'Stage' argument which tells whether the result of the operation should be rounded up or down, in the sense of the linear ordering of the structure, and how precise the result should be. (Missing explanation of what exactly an approximate field is supposed to be.) -} class (Show q, Ord q) => ApproximateField q where normalize :: Stage -> q -> q size :: q -> Int -- ^ the size of the number (memory usage) log2 :: q -> Int -- ^ @log2 q@ is a number @k@ such that @2^k <= abs q <= 2^(k+1)@. midpoint :: q -> q -> q -- ^ exact midpoint zero :: q positive_inf :: q negative_inf :: q toFloat :: q -> Double toRational' :: q -> Rational -- approximate operations app_add :: Stage -> q -> q -> q app_sub :: Stage -> q -> q -> q app_mul :: Stage -> q -> q -> q app_inv :: Stage -> q -> q app_div :: Stage -> q -> q -> q app_negate :: Stage -> q -> q app_abs :: Stage -> q -> q app_signum :: Stage -> q -> q app_fromInteger :: Stage -> Integer -> q app_fromInteger_ws :: Integer -> q app_shift :: Stage -> q -> Int -> q -- ^ shift by a power of 2 app_fromRational :: Stage -> Rational -> q app_fromRational s r = app_div s (app_fromInteger_ws (numerator r)) (app_fromInteger_ws (denominator r)) -- | A dyadic number is of the form @m * 2^e@ where @m@ is the /mantissa/ and @e@ is the /exponent/. data Dyadic = Dyadic { mant :: Integer, expo :: Int } | PositiveInfinity | NegativeInfinity | NaN -- ^ not a number, result of undefined arithmetical operation -- | This should be improved so that dyadics are shown in the usual -- decimal notation. The trouble is: how many digits should we show? -- MPFR does something reasonable, maybe we can do the same thing -- here. instance Show Dyadic where show PositiveInfinity = "+inf" show NegativeInfinity = "-inf" show NaN = "NaN" show Dyadic {mant=m, expo=e} = show m ++ "*2^" ++ show e -- | Suppose @g@ is a map of two dyadic arguments which is invariant -- under multiplication by a power of two, i.e., @g x y = g (x * 2^e) -- (y * 2^e)@. Then @g@ is already determined by its action on -- integers. The map 'shifted2' takes such a @g@ restricted to the -- integers and extends it to dyadics. shifted2 :: (Integer -> Integer -> a) -> Dyadic -> Dyadic -> a shifted2 f (Dyadic {mant=m1, expo=e1}) (Dyadic {mant=m2, expo=e2}) = case compare e1 e2 of LT -> f m1 (shiftL m2 (e2-e1)) EQ -> f m1 m2 GT -> f (shiftL m1 (e1-e2)) m2 -- | zeroCmp q returns the same thing as compare 0 q zeroCmp :: Dyadic -> Ordering zeroCmp NegativeInfinity = GT zeroCmp PositiveInfinity = LT zeroCmp Dyadic {mant=m, expo=e} = compare 0 m instance Eq Dyadic where PositiveInfinity == PositiveInfinity = True NegativeInfinity == NegativeInfinity = True a@(Dyadic _ _) == b@(Dyadic _ _) = shifted2 (==) a b _ == _ = False PositiveInfinity /= PositiveInfinity = False NegativeInfinity /= NegativeInfinity = False a@(Dyadic _ _) /= b@(Dyadic _ _) = shifted2 (/=) a b _ /= _ = True instance Ord Dyadic where compare NegativeInfinity NegativeInfinity = EQ compare NegativeInfinity _ = LT compare _ NegativeInfinity = GT compare PositiveInfinity PositiveInfinity = EQ compare PositiveInfinity _ = GT compare _ PositiveInfinity = LT compare a@(Dyadic _ _) b@(Dyadic _ _) = shifted2 compare a b instance Num Dyadic where -- addition NaN + _ = NaN _ + NaN = NaN NegativeInfinity + PositiveInfinity = NaN PositiveInfinity + NegativeInfinity = NaN NegativeInfinity + _ = NegativeInfinity _ + NegativeInfinity = NegativeInfinity PositiveInfinity + _ = PositiveInfinity _ + PositiveInfinity = PositiveInfinity Dyadic {mant=m1, expo=e1} + Dyadic {mant=m2, expo=e2} = Dyadic {mant = m3, expo = e3} where m3 = if e1 < e2 then m1 + shiftL m2 (e2 - e1) else shiftL m1 (e1 - e2) + m2 e3 = min e1 e2 -- subtraction NaN - _ = NaN _ - NaN = NaN NegativeInfinity - NegativeInfinity = NaN PositiveInfinity - PositiveInfinity = NaN NegativeInfinity - _ = NegativeInfinity _ - NegativeInfinity = PositiveInfinity PositiveInfinity - _ = PositiveInfinity _ - PositiveInfinity = NegativeInfinity Dyadic {mant=m1, expo=e1} - Dyadic {mant=m2, expo=e2} = Dyadic {mant = m3, expo = e3} where m3 = if e1 < e2 then m1 - shiftL m2 (e2 - e1) else shiftL m1 (e1 - e2) - m2 e3 = min e1 e2 -- multiplication NaN * _ = NaN _ * NaN = NaN NegativeInfinity * q = case zeroCmp q of LT -> NegativeInfinity -- 0 < q EQ -> fromInteger 0 -- 0 == q GT -> PositiveInfinity -- q < 0 PositiveInfinity * q = case zeroCmp q of LT -> PositiveInfinity -- 0 < q EQ -> fromInteger 0 -- 0 == q GT -> NegativeInfinity -- q < 0 q@(Dyadic _ _) * NegativeInfinity = NegativeInfinity * q q@(Dyadic _ _) * PositiveInfinity = PositiveInfinity * q Dyadic {mant=m1, expo=e1} * Dyadic {mant=m2, expo=e2} = Dyadic {mant = m1 * m2, expo = e1 + e2} -- absolute value abs NaN = NaN abs PositiveInfinity = PositiveInfinity abs NegativeInfinity = NegativeInfinity abs Dyadic {mant=m, expo=e} = Dyadic {mant = abs m, expo = e} -- signum signum NaN = NaN signum PositiveInfinity = fromInteger 1 signum NegativeInfinity = fromInteger (-1) signum Dyadic {mant=m, expo=e} = fromInteger (signum m) -- fromInteger fromInteger i = Dyadic {mant = i, expo = 0} -- | This was taken from -- | <http://www.haskell.org/pipermail/haskell-cafe/2008-February/039640.html> -- | and it computes the integral logarithm in given base. ilogb :: Integer -> Integer -> Int ilogb b n | n < 0 = ilogb b (- n) | n < b = 0 | otherwise = (up b n 1) - 1 where up b n a = if n < (b ^ a) then bin b (quot a 2) a else up b n (2*a) bin b lo hi = if (hi - lo) <= 1 then hi else let av = quot (lo + hi) 2 in if n < (b ^ av) then bin b lo av else bin b av hi {- | Dyadics with normalization and rounding form an "approximate" field in which operations can be performed up to a given precision. We take the easy route: first we perform an exact operation then we normalize the result. A better implementation would directly compute the approximation, but it's probably not worth doing this with Dyadics. If you want speed, use hmpfr, see <http://hackage.haskell.org/package/hmpfr>. -} instance ApproximateField Dyadic where normalize s NaN = case rounding s of RoundDown -> NegativeInfinity RoundUp -> PositiveInfinity normalize s PositiveInfinity = PositiveInfinity normalize s NegativeInfinity = NegativeInfinity normalize s a@(Dyadic {mant=m, expo=e}) = let j = ilogb 2 m k = precision s r = rounding s in if j <= k then a else Dyadic {mant = shift_with_round r (j-k) m, expo = e + (j-k) } where shift_with_round r k x = let y = shiftR x k in case r of RoundDown -> y RoundUp -> succ y size NaN = 0 size PositiveInfinity = 0 size NegativeInfinity = 0 size Dyadic{mant=m, expo=e} = ilogb 2 m log2 NaN = error "log2 of NaN" log2 PositiveInfinity = error "log2 of +inf" log2 NegativeInfinity = error "log2 of -inf" log2 Dyadic{mant=m, expo=e} = e + ilogb 2 m zero = Dyadic {mant=0, expo=1} positive_inf = PositiveInfinity negative_inf = NegativeInfinity toFloat NaN = 0.0 / 0.0 toFloat PositiveInfinity = 1.0 / 0.0 toFloat NegativeInfinity = - 1.0 / 0.0 toFloat Dyadic{mant=m, expo=e} = encodeFloat m e midpoint NaN _ = NaN midpoint _ NaN = NaN midpoint NegativeInfinity NegativeInfinity = NegativeInfinity midpoint NegativeInfinity PositiveInfinity = zero midpoint NegativeInfinity Dyadic{mant=m, expo=e} = Dyadic {mant = -1 - abs m, expo= 2 * max 1 e} midpoint PositiveInfinity NegativeInfinity = zero midpoint PositiveInfinity PositiveInfinity = PositiveInfinity midpoint PositiveInfinity Dyadic{mant=m, expo=e} = Dyadic {mant = 1 + abs m, expo= 2 * max 1 e} midpoint Dyadic{mant=m,expo=e} NegativeInfinity = Dyadic {mant = -1 - abs m, expo= 2 * max 1 e} midpoint Dyadic{mant=m,expo=e} PositiveInfinity = Dyadic {mant = 1 + abs m, expo= 2 * max 1 e} midpoint Dyadic{mant=m1,expo=e1} Dyadic{mant=m2,expo=e2} = Dyadic {mant = m3, expo = e3 - 1} where m3 = if e1 < e2 then m1 + shiftL m2 (e2 - e1) else shiftL m1 (e1 - e2) + m2 e3 = min e1 e2 app_add s a b = normalize s (a + b) app_sub s a b = normalize s (a - b) app_mul s a b = normalize s (a * b) app_negate s a = negate a app_abs s a = normalize s (abs a) app_signum s a = normalize s (signum a) app_fromInteger s i = normalize s (fromInteger i) app_fromInteger_ws i = (fromInteger i) app_inv s NaN = normalize s NaN app_inv s PositiveInfinity = zero app_inv s NegativeInfinity = zero app_inv s Dyadic{mant=m, expo=e} = let d = precision s b = ilogb 2 m r = case rounding s of RoundDown -> 0 RoundUp -> 1 in if signum m == 0 then normalize s NaN else Dyadic {mant = r + (shiftL 1 (d + b)) `div` m, expo = -(b + d + e)} app_div s Dyadic{mant=m1,expo=e1} Dyadic{mant=m2,expo=e2} = let e = precision s r = case rounding s of RoundDown -> 0 RoundUp -> 1 in if signum m2 == 0 then normalize s NaN else Dyadic {mant = r + (shiftL 1 e * m1) `div` m2, expo = e1 - e2 - e} app_div s _ _ = normalize s NaN -- can we do better than this in other cases? app_shift s NaN k = normalize s NaN app_shift s PositiveInfinity k = PositiveInfinity app_shift s NegativeInfinity k = NegativeInfinity app_shift s Dyadic {mant=m, expo=e} k = normalize s (Dyadic {mant = m, expo = e + k}) toRational' NaN = error"It's not a rational number" toRational' PositiveInfinity = error"It's not a rational number" toRational' NegativeInfinity = error"It's not a rational number" toRational' Dyadic {mant=m, expo=e} = if signum e == -1 then (toRational m)/2^(-e) else (toRational m)*2^e
aljosaVodopija/eksaktnaRealna
Dyadic.hs
gpl-3.0
11,910
0
16
3,287
3,499
1,839
1,660
205
4
{-# LANGUAGE QuasiQuotes, RecordWildCards, NoCPP #-} {-| The @cashflow@ command prints a simplified cashflow statement. It just shows the change in all "cash" accounts for the period (without the traditional segmentation into operating, investing, and financing cash flows.) -} module Hledger.Cli.Commands.Cashflow ( cashflowmode ,cashflow ,tests_Hledger_Cli_Commands_Cashflow ) where import Data.String.Here import System.Console.CmdArgs.Explicit import Test.HUnit import Hledger import Hledger.Cli.CliOptions import Hledger.Cli.CompoundBalanceCommand cashflowSpec = CompoundBalanceCommandSpec { cbcname = "cashflow", cbcaliases = ["cf"], cbchelp = [here| This command displays a simple cashflow statement, showing changes in "cash" accounts. It assumes that these accounts are under a top-level `asset` account (case insensitive, plural forms also allowed) and do not contain `receivable` or `A/R` in their name. |], cbctitle = "Cashflow Statement", cbcqueries = [("Cash flows", journalCashAccountQuery, Just NormalPositive)], cbctype = PeriodChange } cashflowmode :: Mode RawOpts cashflowmode = compoundBalanceCommandMode cashflowSpec cashflow :: CliOpts -> Journal -> IO () cashflow = compoundBalanceCommand cashflowSpec tests_Hledger_Cli_Commands_Cashflow :: Test tests_Hledger_Cli_Commands_Cashflow = TestList [ ]
ony/hledger
hledger/Hledger/Cli/Commands/Cashflow.hs
gpl-3.0
1,370
0
9
205
176
109
67
25
1
{-| Module : Devel.Compile Description : For building and running your WAI application. Copyright : (c) License : GPL-3 Maintainer : [email protected] Stability : experimental Portability : POSIX -} {-# LANGUAGE RecordWildCards #-} module Devel.Build (build) where import IdeSession hiding (getEnv) import qualified Data.ByteString.Char8 as S8 import Control.Concurrent (forkIO, killThread, ThreadId) import Control.Concurrent.STM.TVar import Network.Socket import Control.Concurrent (threadDelay) import Data.Text (unpack) import Devel.Paths import Devel.Watch import Devel.Compile (compile) import Devel.ReverseProxy -- | Compiles and runs your WAI application. build :: FilePath -> String -> Bool -> SessionConfig -> (Int, Int) -> IO () build buildFile runFunction reverseProxy' config (srcPort, destPort) = do -- Either an ideBackend session or a list of errors from `build`. eitherSession <- compile buildFile config sock <- createSocket srcPort case eitherSession of Left errorList -> do -- Start the warp server if the TVar is True. _ <- forkIO $ runServer errorList sock destPort putStrLn $ "Errors at http://localhost:"++(show srcPort) -- Listen for changes in the current working directory. isDirty <- newTVarIO False _ <- forkIO $ watchErrored isDirty checkForChange isDirty -- close the socket so that we may create another in the new build. close sock -- Restart the whole process. restart buildFile runFunction reverseProxy' config (srcPort, destPort) Right session -> do -- Run the WAI application in a separate thread. (runActionsRunResult, threadId) <- run buildFile runFunction session sock (srcPort, destPort) reverseProxy' -- For watching for file changes in current working directory. isDirty <- newTVarIO False -- List of paths to watch pathsToWatch <- getFilesToWatch session -- Watch for changes in the current working directory. _ <- forkIO $ watch isDirty pathsToWatch -- Block until change is made then carry on with program execution. checkForChange isDirty stopApp runActionsRunResult threadId sock restart buildFile runFunction reverseProxy' config (srcPort, destPort) -- | Invoked when we are ready to run the compiled code. run :: FilePath -> String -> IdeSession -> Socket -> (Int, Int) -> Bool -> IO (RunActions RunResult, ThreadId) run buildFile runFunction session sock (srcPort, destPort) reverseProxy' = do case reverseProxy' of False -> close sock True -> return () mapFunction <- getFileMap session buildModule <- case mapFunction buildFile of Nothing -> fail "The file's module name couldn't be found" Just moduleId -> return $ unpack $ moduleName moduleId -- Run the given ide-backend session. runActionsRunResult <- runStmt session buildModule runFunction threadId <- forkIO $ loop runActionsRunResult _ <- threadDelay 1000 case reverseProxy' of False -> putStrLn $ "Starting development server without reverse proxing http://localhost:"++(show srcPort) True -> do putStrLn $ "Starting development server at http://localhost:"++(show srcPort) _ <- forkIO $ runServer [] sock destPort return () return (runActionsRunResult, threadId) -- | Restart the whole process. -- Like calling main in Main but first notifies that -- it's about to restart. restart :: FilePath -> String -> Bool -> SessionConfig -> (Int, Int) -> IO () restart buildFile runFunction reverseProxy' config portPair = do putStrLn "\nRestarting...\n" build buildFile runFunction reverseProxy' config portPair -- | Stop the currently running WAI application. stopApp :: RunActions RunResult -> ThreadId -> Socket -> IO () stopApp runResult threadId sock = do interrupt runResult killThread threadId close sock -- | Run for as long as we need to. loop :: RunActions RunResult -> IO () loop res = do runAction <- runWait res case runAction of Left bs -> S8.putStr bs >> loop res Right result -> putStrLn $ "Run result: " ++ show result
bitemyapp/wai-devel
src/Devel/Build.hs
gpl-3.0
4,199
0
15
920
911
451
460
68
4
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} import qualified Network.WebSockets as WS import qualified Data.Text as T import qualified Data.Text.IO as T import Control.Monad (forever) import Control.Concurrent (forkIO) import Network import System.IO import Text.Printf import System.Environment (lookupEnv) server = "irc.freenode.org" port = 6667 chan = "#haskell" nick = "tutbot-413" type Username = String type Password = String type AppState = (Username, Password, Handle) main :: IO () main = do hIrc <- connectTo server (PortNumber (fromIntegral port)) maybePw <- lookupEnv "PW" let pw = case maybePw of Just x -> x Nothing -> "guest" write hIrc "NICK" nick write hIrc "USER" (nick++" 0 * :tutorial bot") write hIrc "JOIN" chan hSetBuffering hIrc NoBuffering putStrLn "Running on port 9160" WS.runServer "0.0.0.0" 9160 $ application (nick, pw, hIrc) application (nick, pw, hIrc) pending = do conn <- WS.acceptRequest pending passwd :: T.Text <- WS.receiveData conn if passwd == T.pack pw then talkloop conn hIrc else WS.sendTextData conn ("Bad pass" :: T.Text) talkloop conn hIrc = do forkIO $ getwsmsg conn hIrc getircmsg conn hIrc getwsmsg conn hIrc = forever $ do msg :: T.Text <- WS.receiveData conn WS.sendTextData conn msg getircmsg conn hIrc = forever $ do s <- hGetLine hIrc WS.sendTextData conn $ T.pack s write :: Handle -> String -> String -> IO () write h s t = do hPrintf h "%s %s\r\n" s t
r24y/wsirc
src/Main.hs
gpl-3.0
1,822
0
13
612
520
263
257
42
2
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.CloudKMS.Types -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.Google.CloudKMS.Types ( -- * Service Configuration cloudKMSService -- * OAuth Scopes , cloudPlatformScope , cloudKMSScope -- * AsymmetricDecryptResponse , AsymmetricDecryptResponse , asymmetricDecryptResponse , adrPlaintextCrc32c , adrPlaintext , adrProtectionLevel , adrVerifiedCiphertextCrc32c -- * EncryptResponse , EncryptResponse , encryptResponse , erVerifiedAdditionalAuthenticatedDataCrc32c , erVerifiedPlaintextCrc32c , erName , erProtectionLevel , erCiphertext , erCiphertextCrc32c -- * LocationSchema , LocationSchema , locationSchema , lsAddtional -- * AuditConfig , AuditConfig , auditConfig , acService , acAuditLogConfigs -- * Expr , Expr , expr , eLocation , eExpression , eTitle , eDescription -- * ListLocationsResponse , ListLocationsResponse , listLocationsResponse , llrNextPageToken , llrLocations -- * ListKeyRingsResponse , ListKeyRingsResponse , listKeyRingsResponse , lkrrNextPageToken , lkrrTotalSize , lkrrKeyRings -- * ImportJobProtectionLevel , ImportJobProtectionLevel (..) -- * AsymmetricSignResponse , AsymmetricSignResponse , asymmetricSignResponse , asrSignature , asrSignatureCrc32c , asrName , asrProtectionLevel , asrVerifiedDigestCrc32c -- * CryptoKeyPurpose , CryptoKeyPurpose (..) -- * WrAppingPublicKey , WrAppingPublicKey , wrAppingPublicKey , wapkPem -- * KeyRing , KeyRing , keyRing , krName , krCreateTime -- * ImportCryptoKeyVersionRequestAlgorithm , ImportCryptoKeyVersionRequestAlgorithm (..) -- * DestroyCryptoKeyVersionRequest , DestroyCryptoKeyVersionRequest , destroyCryptoKeyVersionRequest -- * Location , Location , location , lName , lMetadata , lDisplayName , lLabels , lLocationId -- * AsymmetricSignRequest , AsymmetricSignRequest , asymmetricSignRequest , asrDigest , asrDigestCrc32c -- * ListImportJobsResponse , ListImportJobsResponse , listImportJobsResponse , lijrNextPageToken , lijrImportJobs , lijrTotalSize -- * PublicKeyProtectionLevel , PublicKeyProtectionLevel (..) -- * DecryptResponseProtectionLevel , DecryptResponseProtectionLevel (..) -- * CryptoKeyVersionTemplateProtectionLevel , CryptoKeyVersionTemplateProtectionLevel (..) -- * CertificateChains , CertificateChains , certificateChains , ccGooglePartitionCerts , ccGoogleCardCerts , ccCaviumCerts -- * PublicKey , PublicKey , publicKey , pkPem , pkPemCrc32c , pkName , pkAlgorithm , pkProtectionLevel -- * DecryptResponse , DecryptResponse , decryptResponse , drUsedPrimary , drPlaintextCrc32c , drPlaintext , drProtectionLevel -- * CryptoKeyVersionTemplate , CryptoKeyVersionTemplate , cryptoKeyVersionTemplate , ckvtAlgorithm , ckvtProtectionLevel -- * SetIAMPolicyRequest , SetIAMPolicyRequest , setIAMPolicyRequest , siprUpdateMask , siprPolicy -- * CryptoKeyLabels , CryptoKeyLabels , cryptoKeyLabels , cklAddtional -- * CryptoKeyVersionTemplateAlgorithm , CryptoKeyVersionTemplateAlgorithm (..) -- * PublicKeyAlgorithm , PublicKeyAlgorithm (..) -- * CryptoKeyVersionState , CryptoKeyVersionState (..) -- * CryptoKey , CryptoKey , cryptoKey , ckVersionTemplate , ckPurpose , ckRotationPeriod , ckPrimary , ckName , ckLabels , ckNextRotationTime , ckCreateTime -- * DecryptRequest , DecryptRequest , decryptRequest , drAdditionalAuthenticatedData , drAdditionalAuthenticatedDataCrc32c , drCiphertext , drCiphertextCrc32c -- * KeyOperationAttestation , KeyOperationAttestation , keyOperationAttestation , koaFormat , koaContent , koaCertChains -- * ProjectsLocationsKeyRingsCryptoKeysListVersionView , ProjectsLocationsKeyRingsCryptoKeysListVersionView (..) -- * ListCryptoKeyVersionsResponse , ListCryptoKeyVersionsResponse , listCryptoKeyVersionsResponse , lckvrNextPageToken , lckvrTotalSize , lckvrCryptoKeyVersions -- * AsymmetricSignResponseProtectionLevel , AsymmetricSignResponseProtectionLevel (..) -- * KeyOperationAttestationFormat , KeyOperationAttestationFormat (..) -- * RestoreCryptoKeyVersionRequest , RestoreCryptoKeyVersionRequest , restoreCryptoKeyVersionRequest -- * AuditLogConfigLogType , AuditLogConfigLogType (..) -- * UpdateCryptoKeyPrimaryVersionRequest , UpdateCryptoKeyPrimaryVersionRequest , updateCryptoKeyPrimaryVersionRequest , uckpvrCryptoKeyVersionId -- * Xgafv , Xgafv (..) -- * ImportJob , ImportJob , importJob , ijState , ijImportMethod , ijAttestation , ijPublicKey , ijGenerateTime , ijName , ijExpireEventTime , ijProtectionLevel , ijExpireTime , ijCreateTime -- * ImportCryptoKeyVersionRequest , ImportCryptoKeyVersionRequest , importCryptoKeyVersionRequest , ickvrRsaAESWrAppedKey , ickvrAlgorithm , ickvrImportJob -- * TestIAMPermissionsRequest , TestIAMPermissionsRequest , testIAMPermissionsRequest , tiprPermissions -- * ImportJobState , ImportJobState (..) -- * ExternalProtectionLevelOptions , ExternalProtectionLevelOptions , externalProtectionLevelOptions , eploExternalKeyURI -- * TestIAMPermissionsResponse , TestIAMPermissionsResponse , testIAMPermissionsResponse , tiamprPermissions -- * Digest , Digest , digest , dSha512 , dSha384 , dSha256 -- * ImportJobImportMethod , ImportJobImportMethod (..) -- * Policy , Policy , policy , pAuditConfigs , pEtag , pVersion , pBindings -- * LocationLabels , LocationLabels , locationLabels , llAddtional -- * LocationMetadata , LocationMetadata , locationMetadata , lmHSMAvailable , lmEkmAvailable -- * AuditLogConfig , AuditLogConfig , auditLogConfig , alcLogType , alcExemptedMembers -- * CryptoKeyVersionProtectionLevel , CryptoKeyVersionProtectionLevel (..) -- * ProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsListView , ProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsListView (..) -- * ListCryptoKeysResponse , ListCryptoKeysResponse , listCryptoKeysResponse , lckrCryptoKeys , lckrNextPageToken , lckrTotalSize -- * AsymmetricDecryptRequest , AsymmetricDecryptRequest , asymmetricDecryptRequest , adrCiphertext , adrCiphertextCrc32c -- * CryptoKeyVersion , CryptoKeyVersion , cryptoKeyVersion , ckvState , ckvAttestation , ckvGenerateTime , ckvImportFailureReason , ckvName , ckvAlgorithm , ckvDestroyTime , ckvImportJob , ckvProtectionLevel , ckvImportTime , ckvExternalProtectionLevelOptions , ckvDestroyEventTime , ckvCreateTime -- * EncryptRequest , EncryptRequest , encryptRequest , erAdditionalAuthenticatedData , erAdditionalAuthenticatedDataCrc32c , erPlaintextCrc32c , erPlaintext -- * AsymmetricDecryptResponseProtectionLevel , AsymmetricDecryptResponseProtectionLevel (..) -- * CryptoKeyVersionAlgorithm , CryptoKeyVersionAlgorithm (..) -- * EncryptResponseProtectionLevel , EncryptResponseProtectionLevel (..) -- * Binding , Binding , binding , bMembers , bRole , bCondition ) where import Network.Google.CloudKMS.Types.Product import Network.Google.CloudKMS.Types.Sum import Network.Google.Prelude -- | Default request referring to version 'v1' of the Cloud Key Management Service (KMS) API. This contains the host and root path used as a starting point for constructing service requests. cloudKMSService :: ServiceConfig cloudKMSService = defaultService (ServiceId "cloudkms:v1") "cloudkms.googleapis.com" -- | See, edit, configure, and delete your Google Cloud Platform data cloudPlatformScope :: Proxy '["https://www.googleapis.com/auth/cloud-platform"] cloudPlatformScope = Proxy -- | View and manage your keys and secrets stored in Cloud Key Management -- Service cloudKMSScope :: Proxy '["https://www.googleapis.com/auth/cloudkms"] cloudKMSScope = Proxy
brendanhay/gogol
gogol-cloudkms/gen/Network/Google/CloudKMS/Types.hs
mpl-2.0
9,121
0
7
2,153
960
669
291
254
1
module Widgets.Time where -- TODO make this prettier import Import import Data.Time import System.Locale import Data.List renderTime :: UTCTime -> Widget renderTime time = do now <- liftIO getCurrentTime let render (UTCTime (ModifiedJulianDay 0) 0) = preEscapedToMarkup ("(soon)" :: Text); render t = preEscapedToMarkup . intercalate "&nbsp;" . words . formatTime defaultTimeLocale "%c" $ t toWidget [hamlet| <span title="#{render time}"> #{showDiffTime now time}&nbsp;ago |]
Happy0/snowdrift
Widgets/Time.hs
agpl-3.0
528
0
14
116
130
68
62
-1
-1
{-# language ScopedTypeVariables, OverloadedStrings #-} module Base.Renderable.Header (header, headerHeight) where import Data.Abelian import Graphics.Qt import Utils import Base.Types import Base.Constants import Base.Prose import Base.Font import Base.Pixmap import Base.Renderable.HBox import Base.Renderable.Centered headerHeight :: Double = 44 -- | implements menu headers header :: Application -> Prose -> RenderableInstance header app = colorizeProse headerFontColor >>> capitalizeProse >>> proseToGlyphs (standardFont app) >>> fmap glyphToHeaderCube >>> addStartAndEndCube >>> hBox >>> renderable data HeaderCube = StartCube | StandardCube Glyph | SpaceCube | EndCube deriving Show -- | converts a glyph into a renderable cube for headers glyphToHeaderCube :: Glyph -> HeaderCube glyphToHeaderCube glyph = if equalsSpace glyph then SpaceCube else StandardCube glyph equalsSpace :: Glyph -> Bool equalsSpace (Glyph c _) = " " == c equalsSpace ErrorGlyph{} = False -- | Adds one cube before and one cube after the header. addStartAndEndCube :: [HeaderCube] -> [HeaderCube] addStartAndEndCube inner = StartCube : inner ++ EndCube : [] instance Renderable HeaderCube where label = const "HeaderCube" render ptr app config size cube = case pixmapCube cube of Left getter -> render ptr app config size $ getter pixmaps Right glyph -> do (childSize, background) <- render ptr app config size $ standardCube pixmaps return $ tuple childSize $ do recoverMatrix ptr background snd =<< render ptr app config (childSize -~ Size (fromUber 1) 0) (centered [glyph]) where pixmaps = headerCubePixmaps $ applicationPixmaps app -- | Returns (Left getter) if the cube should be rendered by just one pixmap, -- (Right glyph) otherwise. pixmapCube :: HeaderCube -> Either (HeaderCubePixmaps -> Pixmap) Glyph pixmapCube cube = case cube of StartCube -> Left startCube SpaceCube -> Left spaceCube EndCube -> Left endCube StandardCube x -> Right x
nikki-and-the-robots/nikki
src/Base/Renderable/Header.hs
lgpl-3.0
2,152
0
20
498
526
271
255
57
4
#!/usr/bin/env runhaskell import Data.List (foldl', group) import System.Environment (getArgs) digits :: Integer -> [Int] digits 0 = [0] digits n = reverse (extract n) where extract 0 = [] extract x = (fromIntegral x `mod` 10) : extract (fromIntegral x `div` 10) fromDigits :: [Int] -> Integer fromDigits d = foldl' (\a b -> a*10 + b) 0 (map toInteger d) looknsay :: [Int] -> [Int] looknsay d = concatMap (\x -> [length x, head x]) (group d) main :: IO () main = do args <- getArgs putStr ( case args of [seed] -> unlines (run seed Nothing) [seed, "-last"] -> last (run seed Nothing) [seed, steps] -> unlines (run seed (Just steps)) [seed, steps, "-last"] -> last (run seed (Just steps)) _ -> "usage: seed [steps=20] [-last]" ) where run seedStr Nothing = run seedStr (Just "20") run seedStr (Just stepsStr) = simulate seed steps where seed = read seedStr :: Integer steps = read stepsStr :: Int simulate seed steps | seed > 0 && seed < 10 = map (show . fromDigits) (take steps (iterate looknsay (digits seed))) | otherwise = error "seed should be a non-zero digit (1,2,...,9)"
jajakobyly/looknsay
haskell/looknsay.hs
unlicense
1,275
0
16
390
510
263
247
28
6
module HelperSequences.A112798 (a112798, a112798_row) where import HelperSequences.A027746 (a027746_row) import Data.Maybe (fromJust) import Data.List (elemIndex) import HelperSequences.A000040 (a000040_list) a112798 :: Int -> Int a112798 n = a112798_tabl !! (n - 2) a112798_tabl :: [Int] a112798_tabl = concatMap a112798_row [1..] a112798_row :: Integer -> [Int] a112798_row 1 = [] a112798_row n = map f $ a027746_row n where f p = (1+) $ fromJust $ elemIndex p a000040_list
peterokagey/haskellOEIS
src/HelperSequences/A112798.hs
apache-2.0
482
0
9
72
170
94
76
13
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeFamilies #-} -- | Data types for the K3 effect system module Language.K3.Analysis.SEffects.Core where import Control.DeepSeq import GHC.Generics (Generic) import Data.Binary import Data.Serialize import Data.List import Data.Tree import Data.Typeable import Language.K3.Core.Annotation import Language.K3.Core.Common import Language.K3.Utils.Pretty import Data.Text ( Text ) import qualified Data.Text as T import qualified Language.K3.Utils.PrettyText as PT import Language.K3.Analysis.Provenance.Core type FPtr = Int data FMatVar = FMatVar {fmvn :: !Identifier, fmvloc :: !UID, fmvptr :: !FPtr} deriving (Eq, Ord, Read, Show, Typeable, Generic) data Effect = FFVar !Identifier | FBVar !FMatVar | FRead !(K3 Provenance) | FWrite !(K3 Provenance) | FIO | FData !(Maybe [Identifier]) -- An effect container, to support structural matching for lambda effects. | FScope ![FMatVar] -- Materialization point for the given FMatVars. This has four children: -- initialization execution effects (i.e., pre-body effects), body execution effects -- post-body execution effects, and result effect structure. | FLambda !Identifier -- Lambda effects have three effect children: closure construction effects, -- deferred execution effects and deferred effect structure. | FApply !(Maybe FMatVar) -- Application effect nodes have either two, three or five children: -- i. 5-child variant: -- lambda effect structure, arg effect structure, -- initializer execution effects, result execution effects, -- and a result effect structure. -- ii. 2-child variant: -- lambda effect structure, and arg effect structure. -- iii. 1-child variant: result effect structure -- -- Note after simplification, we introduce a 3-child variant as a -- simplified form of the 5-child version: -- iv. initializer execution effects, result execution effects, -- and a result effect structure. | FSet -- Set of effects, all of which are possible. | FSeq | FLoop -- A repetitive effect. Can only happen in a foreign function | FNone -- Null effect deriving (Eq, Ord, Read, Show, Typeable, Generic) data instance Annotation Effect = FDeclared !(K3 Effect) deriving (Eq, Ord, Read, Show, Generic) {- SEffect instances -} instance NFData FMatVar instance NFData Effect instance NFData (Annotation Effect) instance Binary FMatVar instance Binary Effect instance Binary (Annotation Effect) instance Serialize FMatVar instance Serialize Effect instance Serialize (Annotation Effect) {- Annotation extractors -} isFDeclared :: Annotation Effect -> Bool isFDeclared (FDeclared _) = True instance Pretty (K3 Effect) where prettyLines (Node (FRead p :@: as) _) = let (aStr, chAStr) = drawFAnnotations as in ["FRead " ++ aStr] %+ prettyLines p ++ shift "`- " " " chAStr prettyLines (Node (FWrite p :@: as) _) = let (aStr, chAStr) = drawFAnnotations as in ["FWrite " ++ aStr] %+ prettyLines p ++ shift "`- " " " chAStr prettyLines (Node (tg :@: as) ch) = let (aStr, chAStr) = drawFAnnotations as in [show tg ++ aStr] ++ (let (p,l) = if null ch then ("`- ", " ") else ("+- ", "| ") in shift p l chAStr) ++ drawSubTrees ch drawFAnnotations :: [Annotation Effect] -> (String, [String]) drawFAnnotations as = let (fdeclAnns, anns) = partition isFDeclared as prettyEffAnns = concatMap drawFDeclAnnotation fdeclAnns in (drawAnnotations anns, prettyEffAnns) where drawFDeclAnnotation (FDeclared f) = ["FDeclared "] %+ prettyLines f instance PT.Pretty (K3 Effect) where prettyLines (Node (FRead p :@: as) _) = let (aTxt, chATxt) = drawFAnnotationsT as in [T.append (T.pack "FRead ") aTxt] PT.%+ PT.prettyLines p ++ (PT.shift (T.pack "`- ") (T.pack " ") chATxt) prettyLines (Node (FWrite p :@: as) _) = let (aTxt, chATxt) = drawFAnnotationsT as in [T.append (T.pack "FWrite ") aTxt] PT.%+ PT.prettyLines p ++ (PT.shift (T.pack "`- ") (T.pack " ") chATxt) prettyLines (Node (tg :@: as) ch) = let (aTxt, chATxt) = drawFAnnotationsT as in [T.append (T.pack $ show tg) aTxt] ++ (let (p,l) = if null ch then (T.pack "`- ", T.pack " ") else (T.pack "+- ", T.pack "| ") in PT.shift p l chATxt) ++ PT.drawSubTrees ch drawFAnnotationsT :: [Annotation Effect] -> (Text, [Text]) drawFAnnotationsT as = let (fdeclAnns, anns) = partition isFDeclared as prettyEffAnns = concatMap drawFDeclAnnotation fdeclAnns in (PT.drawAnnotations anns, prettyEffAnns) where drawFDeclAnnotation (FDeclared f) = [T.pack "FDeclared "] PT.%+ PT.prettyLines f
DaMSL/K3
src/Language/K3/Analysis/SEffects/Core.hs
apache-2.0
5,420
0
18
1,600
1,342
709
633
115
1
-- parse nested parens into a tree structure -- Exercise 1 from chapter 8 of Basics of Haskell -- https://www.schoolofhaskell.com/school/starting-with-haskell/basics-of-haskell/8_Parser data Token = TokLParen | TokRParen | TokEnd deriving (Show, Eq) lookAhead :: String -> Token lookAhead [] = TokEnd lookAhead (c:cs)| c == '(' = TokLParen | c == ')' = TokRParen | otherwise = error $ "Bad input: " ++ (c:cs) accept :: String -> String accept [] = error "Nothing to accept" accept (c:cs) = cs data Tree = Node Tree Tree | Leaf deriving Show root, expr, par :: String -> (Tree, String) root = par expr s = let (p, s') = par s (p', s'') = par s' in (Node p p', s'') par s = case lookAhead s of TokLParen -> case lookAhead (accept s) of TokRParen -> (Leaf, accept (accept s)) _ -> let (e, s') = expr (accept s) in if lookAhead s' == TokRParen then (e, accept s') else error $ "Missing closing paren in: " ++ show s' _ -> error $ "Bad expression: " ++ show s parse str = let (tree, str') = root str in if null str' then tree else error $ "Unconsumed string " ++ str' main = print $ parse "(()(()(()())))"
cbare/Etudes
haskell/parse_parens.hs
apache-2.0
1,526
0
17
633
442
229
213
31
4
import Control.Parallel.Strategies power5 x = x * x * x * x * x digitSumPower5 n = sum $ map power5 $ map (\x -> read [x] :: Int) $ show n isSameAsDigitSumPower5 n = (n == digitSumPower5 n) main = do let base = [2..10000000] let filtered = filter isSameAsDigitSumPower5 base let cs = filtered `using` parList rdeepseq print $ sum $ cs
ulikoehler/ProjectEuler
Euler30.hs
apache-2.0
355
0
11
84
157
78
79
9
1
{-# LANGUAGE TemplateHaskell #-} module DBusTests.TH where import DBus.Generation import DBusTests.Generation generateClient defaultGenerationParams testIntrospectionInterface generateSignalsFromInterface defaultGenerationParams testIntrospectionInterface
rblaze/haskell-dbus
tests/DBusTests/TH.hs
apache-2.0
259
0
5
20
33
17
16
6
0
-- | Specific configuration for Joey Hess's sites. Probably not useful to -- others except as an example. {-# LANGUAGE FlexibleContexts, TypeFamilies #-} module Propellor.Property.SiteSpecific.JoeySites where import Propellor.Base import qualified Propellor.Property.Apt as Apt import qualified Propellor.Property.File as File import qualified Propellor.Property.ConfFile as ConfFile import qualified Propellor.Property.Gpg as Gpg import qualified Propellor.Property.Ssh as Ssh import qualified Propellor.Property.Git as Git import qualified Propellor.Property.Cron as Cron import qualified Propellor.Property.Service as Service import qualified Propellor.Property.User as User import qualified Propellor.Property.Obnam as Obnam import qualified Propellor.Property.Apache as Apache import qualified Propellor.Property.Postfix as Postfix import qualified Propellor.Property.Systemd as Systemd import qualified Propellor.Property.Fail2Ban as Fail2Ban import qualified Propellor.Property.LetsEncrypt as LetsEncrypt import Utility.FileMode import Data.List import System.Posix.Files import Data.String.Utils scrollBox :: Property (HasInfo + DebianLike) scrollBox = propertyList "scroll server" $ props & User.accountFor (User "scroll") & Git.cloned (User "scroll") "git://git.kitenet.net/scroll" (d </> "scroll") Nothing & Apt.installed ["ghc", "make", "cabal-install", "libghc-vector-dev", "libghc-bytestring-dev", "libghc-mtl-dev", "libghc-ncurses-dev", "libghc-random-dev", "libghc-monad-loops-dev", "libghc-text-dev", "libghc-ifelse-dev", "libghc-case-insensitive-dev", "libghc-data-default-dev", "libghc-optparse-applicative-dev"] & userScriptProperty (User "scroll") [ "cd " ++ d </> "scroll" , "git pull" , "cabal configure" , "make" ] `assume` MadeChange & s `File.hasContent` [ "#!/bin/sh" , "set -e" , "echo Preparing to run scroll!" , "cd " ++ d , "mkdir -p tmp" , "TMPDIR= t=$(tempfile -d tmp)" , "export t" , "rm -f \"$t\"" , "mkdir \"$t\"" , "cd \"$t\"" , "echo" , "echo Note that games on this server are time-limited to 2 hours" , "echo 'Need more time? Run scroll locally instead!'" , "echo" , "echo Press Enter to start the game." , "read me" , "SHELL=/bin/sh script --timing=timing -c " ++ g ] `onChange` (s `File.mode` (combineModes (ownerWriteMode:readModes ++ executeModes))) & g `File.hasContent` [ "#!/bin/sh" , "if ! timeout --kill-after 1m --foreground 2h ../../scroll/scroll; then" , "echo Scroll seems to have ended unexpectedly. Possibly a bug.." , "else" , "echo Thanks for playing scroll! https://joeyh.name/code/scroll/" , "fi" , "echo Your game was recorded, as ID:$(basename \"$t\")" , "echo if you would like to talk about how it went, email [email protected]" , "read line" ] `onChange` (g `File.mode` (combineModes (ownerWriteMode:readModes ++ executeModes))) -- prevent port forwarding etc by not letting scroll log in via ssh & Ssh.sshdConfig `File.containsLine` ("DenyUsers scroll") `onChange` Ssh.restarted & User.shellSetTo (User "scroll") s & User.hasPassword (User "scroll") -- telnetd attracted password crackers, so disabled & Apt.removed ["telnetd"] & Apt.installed ["shellinabox"] & File.hasContent "/etc/default/shellinabox" [ "# Deployed by propellor" , "SHELLINABOX_DAEMON_START=1" , "SHELLINABOX_PORT=4242" , "SHELLINABOX_ARGS=\"--disable-ssl --no-beep --service=:scroll:scroll:" ++ d ++ ":" ++ s ++ "\"" ] `onChange` Service.restarted "shellinabox" & Service.running "shellinabox" where d = "/home/scroll" s = d </> "login.sh" g = d </> "game.sh" oldUseNetServer :: [Host] -> Property (HasInfo + DebianLike) oldUseNetServer hosts = propertyList "olduse.net server" $ props & Apt.installed ["leafnode"] & oldUseNetInstalled "oldusenet-server" & oldUseNetBackup & spoolsymlink & "/etc/news/leafnode/config" `File.hasContent` [ "# olduse.net configuration (deployed by propellor)" , "expire = 1000000" -- no expiry via texpire , "server = " -- no upstream server , "debugmode = 1" , "allowSTRANGERS = 42" -- lets anyone connect , "nopost = 1" -- no new posting (just gather them) ] & "/etc/hosts.deny" `File.lacksLine` "leafnode: ALL" & Apt.serviceInstalledRunning "openbsd-inetd" & File.notPresent "/etc/cron.daily/leafnode" & File.notPresent "/etc/cron.d/leafnode" & Cron.niceJob "oldusenet-expire" (Cron.Times "11 1 * * *") (User "news") newsspool expirecommand & Cron.niceJob "oldusenet-uucp" (Cron.Times "*/5 * * * *") (User "news") "/" uucpcommand & Apache.siteEnabled "nntp.olduse.net" nntpcfg where newsspool = "/var/spool/news" datadir = "/var/spool/oldusenet" expirecommand = intercalate ";" [ "find \\( -path ./out.going -or -path ./interesting.groups -or -path './*/.overview' \\) -prune -or -type f -ctime +60 -print | xargs --no-run-if-empty rm" , "find -type d -empty | xargs --no-run-if-empty rmdir" ] uucpcommand = "/usr/bin/uucp " ++ datadir nntpcfg = apachecfg "nntp.olduse.net" [ " DocumentRoot " ++ datadir ++ "/" , " <Directory " ++ datadir ++ "/>" , " Options Indexes FollowSymlinks" , " AllowOverride None" , Apache.allowAll , " </Directory>" ] spoolsymlink :: Property UnixLike spoolsymlink = check (not . isSymbolicLink <$> getSymbolicLinkStatus newsspool) (property "olduse.net spool in place" $ makeChange $ do removeDirectoryRecursive newsspool createSymbolicLink (datadir </> "news") newsspool ) oldUseNetBackup :: Property (HasInfo + DebianLike) oldUseNetBackup = Obnam.backup datadir (Cron.Times "33 4 * * *") [ "--repository=sftp://[email protected]/~/olduse.net" , "--client-name=spool" , "--ssh-key=" ++ keyfile , Obnam.keepParam [Obnam.KeepDays 30] ] Obnam.OnlyClient `requires` Ssh.userKeyAt (Just keyfile) (User "root") (Context "olduse.net") (SshRsa, "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD0F6L76SChMCIGmeyGhlFMUTgZ3BoTbATiOSs0A7KXQoI1LTE5ZtDzzUkrQRJVpJ640pfMR7cQZyBm8tv+kYIPp0238GrX43c1vgm0L78agDnBU7r2iNMyWIwhssK8O3ZAhp8Q4KCz1r8hP2nIiD0y1D1VWW8h4KWOS7I1XCEAjOTvFvEjTh6a9MyHrcIkv7teUUzTBRjNrsyijCFRk1+pEET54RueoOmEjQcWd/sK1tYRiMZjegRLBOus2wUWsUOvznJ2iniLONUTGAWRnEV+O7hLN6CD44osJ+wkZk8bPAumTS0zcSLckX1jpdHJicmAyeniWSd4FCqm1YE6/xDD") `requires` Ssh.knownHost hosts "usw-s002.rsync.net" (User "root") keyfile = "/root/.ssh/olduse.net.key" oldUseNetShellBox :: Property DebianLike oldUseNetShellBox = propertyList "olduse.net shellbox" $ props & oldUseNetInstalled "oldusenet" & Service.running "shellinabox" oldUseNetInstalled :: Apt.Package -> Property DebianLike oldUseNetInstalled pkg = check (not <$> Apt.isInstalled pkg) $ propertyList ("olduse.net " ++ pkg) $ props & Apt.installed (words "build-essential devscripts debhelper git libncursesw5-dev libpcre3-dev pkg-config bison libicu-dev libidn11-dev libcanlock2-dev libuu-dev ghc libghc-strptime-dev libghc-hamlet-dev libghc-ifelse-dev libghc-hxt-dev libghc-utf8-string-dev libghc-missingh-dev libghc-sha-dev") `describe` "olduse.net build deps" & scriptProperty [ "rm -rf /root/tmp/oldusenet" -- idenpotency , "git clone git://olduse.net/ /root/tmp/oldusenet/source" , "cd /root/tmp/oldusenet/source/" , "dpkg-buildpackage -us -uc" , "dpkg -i ../" ++ pkg ++ "_*.deb || true" , "apt-get -fy install" -- dependencies , "rm -rf /root/tmp/oldusenet" ] `assume` MadeChange `describe` "olduse.net built" kgbServer :: Property (HasInfo + Debian) kgbServer = propertyList desc $ props & installed & File.hasPrivContent "/etc/kgb-bot/kgb.conf" anyContext `onChange` Service.restarted "kgb-bot" where desc = "kgb.kitenet.net setup" installed :: Property Debian installed = withOS desc $ \w o -> case o of (Just (System (Debian _ Unstable) _)) -> ensureProperty w $ propertyList desc $ props & Apt.serviceInstalledRunning "kgb-bot" & "/etc/default/kgb-bot" `File.containsLine` "BOT_ENABLED=1" `describe` "kgb bot enabled" `onChange` Service.running "kgb-bot" _ -> error "kgb server needs Debian unstable (for kgb-bot 1.31+)" mumbleServer :: [Host] -> Property (HasInfo + DebianLike) mumbleServer hosts = combineProperties hn $ props & Apt.serviceInstalledRunning "mumble-server" & Obnam.backup "/var/lib/mumble-server" (Cron.Times "55 5 * * *") [ "--repository=sftp://[email protected]/~/" ++ hn ++ ".obnam" , "--ssh-key=" ++ sshkey , "--client-name=mumble" , Obnam.keepParam [Obnam.KeepDays 30] ] Obnam.OnlyClient `requires` Ssh.userKeyAt (Just sshkey) (User "root") (Context hn) (SshRsa, "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDSXXSM3mM8SNu+qel9R/LkDIkjpV3bfpUtRtYv2PTNqicHP+DdoThrr0ColFCtLH+k2vQJvR2n8uMzHn53Dq2IO3TtD27+7rJSsJwAZ8oftNzuTir8IjAwX5g6JYJs+L0Ny4RB0ausd+An0k/CPMRl79zKxpZd2MBMDNXt8hyqu0vS0v1ohq5VBEVhBBvRvmNQvWOCj7PdrKQXpUBHruZOeVVEdUUXZkVc1H0t7LVfJnE+nGKyWbw2jM+7r3Rn5Semc4R1DxsfaF8lKkZyE88/5uZQ/ddomv8ptz6YZ5b+Bg6wfooWPC3RWAALjxnHaC2yN1VONAvHmT0uNn1o6v0b") `requires` Ssh.knownHost hosts "usw-s002.rsync.net" (User "root") & cmdProperty "chown" ["-R", "mumble-server:mumble-server", "/var/lib/mumble-server"] `assume` NoChange where hn = "mumble.debian.net" sshkey = "/root/.ssh/mumble.debian.net.key" -- git.kitenet.net and git.joeyh.name gitServer :: [Host] -> Property (HasInfo + DebianLike) gitServer hosts = propertyList "git.kitenet.net setup" $ props & Obnam.backupEncrypted "/srv/git" (Cron.Times "33 3 * * *") [ "--repository=sftp://[email protected]/~/git.kitenet.net" , "--ssh-key=" ++ sshkey , "--client-name=wren" -- historical , Obnam.keepParam [Obnam.KeepDays 30] ] Obnam.OnlyClient (Gpg.GpgKeyId "1B169BE1") `requires` Ssh.userKeyAt (Just sshkey) (User "root") (Context "git.kitenet.net") (SshRsa, "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD0F6L76SChMCIGmeyGhlFMUTgZ3BoTbATiOSs0A7KXQoI1LTE5ZtDzzUkrQRJVpJ640pfMR7cQZyBm8tv+kYIPp0238GrX43c1vgm0L78agDnBU7r2iNMyWIwhssK8O3ZAhp8Q4KCz1r8hP2nIiD0y1D1VWW8h4KWOS7I1XCEAjOTvFvEjTh6a9MyHrcIkv7teUUzTBRjNrsyijCFRk1+pEET54RueoOmEjQcWd/sK1tYRiMZjegRLBOus2wUWsUOvznJ2iniLONUTGAWRnEV+O7hLN6CD44osJ+wkZk8bPAumTS0zcSLckX1jpdHJicmAyeniWSd4FCqm1YE6/xDD") `requires` Ssh.knownHost hosts "usw-s002.rsync.net" (User "root") `requires` Ssh.authorizedKeys (User "family") (Context "git.kitenet.net") `requires` User.accountFor (User "family") & Apt.installed ["git", "rsync", "cgit"] & Apt.installed ["git-annex"] & Apt.installed ["kgb-client"] & File.hasPrivContentExposed "/etc/kgb-bot/kgb-client.conf" anyContext `requires` File.dirExists "/etc/kgb-bot/" & Git.daemonRunning "/srv/git" & "/etc/cgitrc" `File.hasContent` [ "clone-url=https://git.joeyh.name/git/$CGIT_REPO_URL git://git.joeyh.name/$CGIT_REPO_URL" , "css=/cgit-css/cgit.css" , "logo=/cgit-css/cgit.png" , "enable-http-clone=1" , "root-title=Joey's git repositories" , "root-desc=" , "enable-index-owner=0" , "snapshots=tar.gz" , "enable-git-config=1" , "scan-path=/srv/git" ] `describe` "cgit configured" -- I keep the website used for git.kitenet.net/git.joeyh.name checked into git.. & Git.cloned (User "root") "/srv/git/joey/git.kitenet.net.git" "/srv/web/git.kitenet.net" Nothing -- Don't need global apache configuration for cgit. ! Apache.confEnabled "cgit" & website "git.kitenet.net" & website "git.joeyh.name" & Apache.modEnabled "cgi" where sshkey = "/root/.ssh/git.kitenet.net.key" website hn = Apache.httpsVirtualHost' hn "/srv/web/git.kitenet.net/" letos [ Apache.iconDir , " <Directory /srv/web/git.kitenet.net/>" , " Options Indexes ExecCGI FollowSymlinks" , " AllowOverride None" , " AddHandler cgi-script .cgi" , " DirectoryIndex index.cgi" , Apache.allowAll , " </Directory>" , "" , " ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/" , " <Directory /usr/lib/cgi-bin>" , " SetHandler cgi-script" , " Options ExecCGI" , " </Directory>" ] type AnnexUUID = String -- | A website, with files coming from a git-annex repository. annexWebSite :: Git.RepoUrl -> HostName -> AnnexUUID -> [(String, Git.RepoUrl)] -> Property (HasInfo + DebianLike) annexWebSite origin hn uuid remotes = propertyList (hn ++" website using git-annex") $ props & Git.cloned (User "joey") origin dir Nothing `onChange` setup & alias hn & postupdatehook `File.hasContent` [ "#!/bin/sh" , "exec git update-server-info" ] `onChange` (postupdatehook `File.mode` (combineModes (ownerWriteMode:readModes ++ executeModes))) & setupapache where dir = "/srv/web/" ++ hn postupdatehook = dir </> ".git/hooks/post-update" setup = userScriptProperty (User "joey") setupscript `assume` MadeChange setupscript = [ "cd " ++ shellEscape dir , "git annex reinit " ++ shellEscape uuid ] ++ map addremote remotes ++ [ "git annex get" , "git update-server-info" ] addremote (name, url) = "git remote add " ++ shellEscape name ++ " " ++ shellEscape url setupapache = Apache.httpsVirtualHost' hn dir letos [ " ServerAlias www."++hn , Apache.iconDir , " <Directory "++dir++">" , " Options Indexes FollowSymLinks ExecCGI" , " AllowOverride None" , " AddHandler cgi-script .cgi" , " DirectoryIndex index.html index.cgi" , Apache.allowAll , " </Directory>" ] letos :: LetsEncrypt.AgreeTOS letos = LetsEncrypt.AgreeTOS (Just "[email protected]") apacheSite :: HostName -> Apache.ConfigFile -> RevertableProperty DebianLike DebianLike apacheSite hn middle = Apache.siteEnabled hn $ apachecfg hn middle apachecfg :: HostName -> Apache.ConfigFile -> Apache.ConfigFile apachecfg hn middle = [ "<VirtualHost *:" ++ val port ++ ">" , " ServerAdmin [email protected]" , " ServerName "++hn++":" ++ val port ] ++ middle ++ [ "" , " ErrorLog /var/log/apache2/error.log" , " LogLevel warn" , " CustomLog /var/log/apache2/access.log combined" , " ServerSignature On" , " " , Apache.iconDir , "</VirtualHost>" ] where port = Port 80 gitAnnexDistributor :: Property (HasInfo + DebianLike) gitAnnexDistributor = combineProperties "git-annex distributor, including rsync server and signer" $ props & Apt.installed ["rsync"] & File.hasPrivContent "/etc/rsyncd.conf" (Context "git-annex distributor") `onChange` Service.restarted "rsync" & File.hasPrivContent "/etc/rsyncd.secrets" (Context "git-annex distributor") `onChange` Service.restarted "rsync" & "/etc/default/rsync" `File.containsLine` "RSYNC_ENABLE=true" `onChange` Service.running "rsync" & Systemd.enabled "rsync" & endpoint "/srv/web/downloads.kitenet.net/git-annex/autobuild" & endpoint "/srv/web/downloads.kitenet.net/git-annex/autobuild/x86_64-apple-yosemite" & endpoint "/srv/web/downloads.kitenet.net/git-annex/autobuild/windows" -- git-annex distribution signing key & Gpg.keyImported (Gpg.GpgKeyId "89C809CB") (User "joey") where endpoint d = combineProperties ("endpoint " ++ d) $ props & File.dirExists d & File.ownerGroup d (User "joey") (Group "joey") downloads :: [Host] -> Property (HasInfo + DebianLike) downloads hosts = annexWebSite "/srv/git/downloads.git" "downloads.kitenet.net" "840760dc-08f0-11e2-8c61-576b7e66acfd" [("eubackup", "ssh://eubackup.kitenet.net/~/lib/downloads/")] `requires` Ssh.knownHost hosts "eubackup.kitenet.net" (User "joey") tmp :: Property (HasInfo + DebianLike) tmp = propertyList "tmp.joeyh.name" $ props & annexWebSite "/srv/git/joey/tmp.git" "tmp.joeyh.name" "26fd6e38-1226-11e2-a75f-ff007033bdba" [] & pumpRss -- Work around for expired ssl cert. -- (Obsolete; need to revert this.) pumpRss :: Property DebianLike pumpRss = Cron.job "pump rss" (Cron.Times "15 * * * *") (User "joey") "/srv/web/tmp.joeyh.name/" "wget https://pump2rss.com/feed/[email protected] -O pump.atom.new --no-check-certificate 2>/dev/null; sed 's/ & / /g' pump.atom.new > pump.atom" ircBouncer :: Property (HasInfo + DebianLike) ircBouncer = propertyList "IRC bouncer" $ props & Apt.installed ["znc"] & User.accountFor (User "znc") & File.dirExists (takeDirectory conf) & File.hasPrivContent conf anyContext & File.ownerGroup conf (User "znc") (Group "znc") & Cron.job "znconboot" (Cron.Times "@reboot") (User "znc") "~" "znc" -- ensure running if it was not already & userScriptProperty (User "znc") ["znc || true"] `assume` NoChange `describe` "znc running" where conf = "/home/znc/.znc/configs/znc.conf" kiteShellBox :: Property DebianLike kiteShellBox = propertyList "kitenet.net shellinabox" $ props & Apt.installed ["openssl", "shellinabox", "openssh-client"] & File.hasContent "/etc/default/shellinabox" [ "# Deployed by propellor" , "SHELLINABOX_DAEMON_START=1" , "SHELLINABOX_PORT=443" , "SHELLINABOX_ARGS=\"--no-beep --service=/:SSH:kitenet.net\"" ] `onChange` Service.restarted "shellinabox" & Service.running "shellinabox" githubBackup :: Property (HasInfo + DebianLike) githubBackup = propertyList "github-backup box" $ props & Apt.installed ["github-backup", "moreutils"] & githubKeys & Cron.niceJob "github-backup run" (Cron.Times "30 4 * * *") (User "joey") "/home/joey/lib/backup" backupcmd where backupcmd = intercalate "&&" $ [ "mkdir -p github" , "cd github" , ". $HOME/.github-keys" , "github-backup joeyh" ] githubKeys :: Property (HasInfo + UnixLike) githubKeys = let f = "/home/joey/.github-keys" in File.hasPrivContent f anyContext `onChange` File.ownerGroup f (User "joey") (Group "joey") rsyncNetBackup :: [Host] -> Property DebianLike rsyncNetBackup hosts = Cron.niceJob "rsync.net copied in daily" (Cron.Times "30 5 * * *") (User "joey") "/home/joey/lib/backup" "mkdir -p rsync.net && rsync --delete -az [email protected]: rsync.net" `requires` Ssh.knownHost hosts "usw-s002.rsync.net" (User "joey") backupsBackedupFrom :: [Host] -> HostName -> FilePath -> Property DebianLike backupsBackedupFrom hosts srchost destdir = Cron.niceJob desc (Cron.Times "@reboot") (User "joey") "/" cmd `requires` Ssh.knownHost hosts srchost (User "joey") where desc = "backups copied from " ++ srchost ++ " on boot" cmd = "sleep 30m && rsync -az --bwlimit=300K --partial --delete " ++ srchost ++ ":lib/backup/ " ++ destdir </> srchost obnamRepos :: [String] -> Property UnixLike obnamRepos rs = propertyList ("obnam repos for " ++ unwords rs) $ toProps (mkbase : map mkrepo rs) where mkbase = mkdir "/home/joey/lib/backup" `requires` mkdir "/home/joey/lib" mkrepo r = mkdir ("/home/joey/lib/backup/" ++ r ++ ".obnam") mkdir d = File.dirExists d `before` File.ownerGroup d (User "joey") (Group "joey") podcatcher :: Property DebianLike podcatcher = Cron.niceJob "podcatcher run hourly" (Cron.Times "55 * * * *") (User "joey") "/home/joey/lib/sound/podcasts" "xargs git-annex importfeed -c annex.genmetadata=true < feeds; mr --quiet update" `requires` Apt.installed ["git-annex", "myrepos"] kiteMailServer :: Property (HasInfo + DebianLike) kiteMailServer = propertyList "kitenet.net mail server" $ props & Postfix.installed & Apt.installed ["postfix-pcre"] & Apt.serviceInstalledRunning "postgrey" & Apt.serviceInstalledRunning "spamassassin" & "/etc/default/spamassassin" `File.containsLines` [ "# Propellor deployed" , "ENABLED=1" , "OPTIONS=\"--create-prefs --max-children 5 --helper-home-dir\"" , "CRON=1" , "NICE=\"--nicelevel 15\"" ] `onChange` Service.restarted "spamassassin" `describe` "spamd enabled" `requires` Apt.serviceInstalledRunning "cron" & Apt.serviceInstalledRunning "spamass-milter" -- Add -m to prevent modifying messages Subject or body. & "/etc/default/spamass-milter" `File.containsLine` "OPTIONS=\"-m -u spamass-milter -i 127.0.0.1\"" `onChange` Service.restarted "spamass-milter" `describe` "spamass-milter configured" & Apt.serviceInstalledRunning "amavisd-milter" & "/etc/default/amavisd-milter" `File.containsLines` [ "# Propellor deployed" , "MILTERSOCKET=/var/spool/postfix/amavis/amavis.sock" , "MILTERSOCKETOWNER=\"postfix:postfix\"" , "MILTERSOCKETMODE=\"0660\"" ] `onChange` Service.restarted "amavisd-milter" `describe` "amavisd-milter configured for postfix" & Apt.serviceInstalledRunning "clamav-freshclam" -- Workaround https://bugs.debian.org/569150 & Cron.niceJob "amavis-expire" Cron.Daily (User "root") "/" "find /var/lib/amavis/virusmails/ -type f -ctime +7 -delete" & dkimInstalled & Postfix.saslAuthdInstalled & Fail2Ban.installed & Fail2Ban.jailEnabled "postfix-sasl" & "/etc/default/saslauthd" `File.containsLine` "MECHANISMS=sasldb" & Postfix.saslPasswdSet "kitenet.net" (User "errol") & Postfix.saslPasswdSet "kitenet.net" (User "joey") & Apt.installed ["maildrop"] & "/etc/maildroprc" `File.hasContent` [ "# Global maildrop filter file (deployed with propellor)" , "DEFAULT=\"$HOME/Maildir\"" , "MAILBOX=\"$DEFAULT/.\"" , "# Filter spam to a spam folder, unless .keepspam exists" , "if (/^X-Spam-Status: Yes/)" , "{" , " `test -e \"$HOME/.keepspam\"`" , " if ( $RETURNCODE != 0 )" , " to ${MAILBOX}spam" , "}" ] `describe` "maildrop configured" & "/etc/aliases" `File.hasPrivContentExposed` ctx `onChange` Postfix.newaliases & hasPostfixCert ctx & "/etc/postfix/mydomain" `File.containsLines` [ "/.*\\.kitenet\\.net/\tOK" , "/ikiwiki\\.info/\tOK" , "/joeyh\\.name/\tOK" ] `onChange` Postfix.reloaded `describe` "postfix mydomain file configured" & "/etc/postfix/obscure_client_relay.pcre" `File.hasContent` -- Remove received lines for mails relayed from trusted -- clients. These can be a privacy violation, or trigger -- spam filters. [ "/^Received: from ([^.]+)\\.kitenet\\.net.*using TLS.*by kitenet\\.net \\(([^)]+)\\) with (E?SMTPS?A?) id ([A-F[:digit:]]+)(.*)/ IGNORE" -- Munge local Received line for postfix running on a -- trusted client that relays through. These can trigger -- spam filters. , "/^Received: by ([^.]+)\\.kitenet\\.net.*/ REPLACE X-Question: 42" ] `onChange` Postfix.reloaded `describe` "postfix obscure_client_relay file configured" & Postfix.mappedFile "/etc/postfix/virtual" (flip File.containsLines [ "# *@joeyh.name to joey" , "@joeyh.name\tjoey" ] ) `describe` "postfix virtual file configured" `onChange` Postfix.reloaded & Postfix.mappedFile "/etc/postfix/relay_clientcerts" (flip File.hasPrivContentExposed ctx) & Postfix.mainCfFile `File.containsLines` [ "myhostname = kitenet.net" , "mydomain = $myhostname" , "append_dot_mydomain = no" , "myorigin = kitenet.net" , "mydestination = $myhostname, localhost.$mydomain, $mydomain, kite.$mydomain., localhost, regexp:$config_directory/mydomain" , "mailbox_command = maildrop" , "virtual_alias_maps = hash:/etc/postfix/virtual" , "# Allow clients with trusted certs to relay mail through." , "relay_clientcerts = hash:/etc/postfix/relay_clientcerts" , "smtpd_relay_restrictions = permit_mynetworks,permit_tls_clientcerts,permit_sasl_authenticated,reject_unauth_destination" , "# Filter out client relay lines from headers." , "header_checks = pcre:$config_directory/obscure_client_relay.pcre" , "# Password auth for relaying" , "smtpd_sasl_auth_enable = yes" , "smtpd_sasl_security_options = noanonymous" , "smtpd_sasl_local_domain = kitenet.net" , "# Enable postgrey." , "smtpd_recipient_restrictions = permit_tls_clientcerts,permit_sasl_authenticated,,permit_mynetworks,reject_unauth_destination,check_policy_service inet:127.0.0.1:10023" , "# Enable spamass-milter, amavis-milter (opendkim is not enabled because it causes mails forwarded from eg gmail to be rejected)" , "smtpd_milters = unix:/spamass/spamass.sock unix:amavis/amavis.sock" , "# opendkim is used for outgoing mail" , "non_smtpd_milters = inet:localhost:8891" , "milter_connect_macros = j {daemon_name} v {if_name} _" , "# If a milter is broken, fall back to just accepting mail." , "milter_default_action = accept" , "# TLS setup -- server" , "smtpd_tls_CAfile = /etc/ssl/certs/joeyca.pem" , "smtpd_tls_cert_file = /etc/ssl/certs/postfix.pem" , "smtpd_tls_key_file = /etc/ssl/private/postfix.pem" , "smtpd_tls_loglevel = 1" , "smtpd_tls_received_header = yes" , "smtpd_use_tls = yes" , "smtpd_tls_ask_ccert = yes" , "smtpd_tls_session_cache_database = sdbm:/etc/postfix/smtpd_scache" , "# TLS setup -- client" , "smtp_tls_CAfile = /etc/ssl/certs/joeyca.pem" , "smtp_tls_cert_file = /etc/ssl/certs/postfix.pem" , "smtp_tls_key_file = /etc/ssl/private/postfix.pem" , "smtp_tls_loglevel = 1" , "smtp_use_tls = yes" , "smtp_tls_session_cache_database = sdbm:/etc/postfix/smtp_scache" ] `onChange` Postfix.dedupMainCf `onChange` Postfix.reloaded `describe` "postfix configured" & Apt.serviceInstalledRunning "dovecot-imapd" & Apt.serviceInstalledRunning "dovecot-pop3d" & "/etc/dovecot/conf.d/10-mail.conf" `File.containsLine` "mail_location = maildir:~/Maildir" `onChange` Service.reloaded "dovecot" `describe` "dovecot mail.conf" & "/etc/dovecot/conf.d/10-auth.conf" `File.containsLine` "!include auth-passwdfile.conf.ext" `onChange` Service.restarted "dovecot" `describe` "dovecot auth.conf" & File.hasPrivContent dovecotusers ctx `onChange` (dovecotusers `File.mode` combineModes [ownerReadMode, groupReadMode]) & File.ownerGroup dovecotusers (User "root") (Group "dovecot") & Apt.installed ["mutt", "bsd-mailx", "alpine"] & pinescript `File.hasContent` [ "#!/bin/sh" , "# deployed with propellor" , "set -e" , "pass=$HOME/.pine-password" , "if [ ! -e $pass ]; then" , "\ttouch $pass" , "fi" , "chmod 600 $pass" , "exec alpine -passfile $pass \"$@\"" ] `onChange` (pinescript `File.mode` combineModes (readModes ++ executeModes)) `describe` "pine wrapper script" & "/etc/pine.conf" `File.hasContent` [ "# deployed with propellor" , "inbox-path={localhost/novalidate-cert/NoRsh}inbox" ] `describe` "pine configured to use local imap server" & Apt.serviceInstalledRunning "mailman" -- Override the default http url. (Only affects new lists.) & "/etc/mailman/mm_cfg.py" `File.containsLine` "DEFAULT_URL_PATTERN = 'https://%s/cgi-bin/mailman/'" & Postfix.service ssmtp & Apt.installed ["fetchmail"] where ctx = Context "kitenet.net" pinescript = "/usr/local/bin/pine" dovecotusers = "/etc/dovecot/users" ssmtp = Postfix.Service (Postfix.InetService Nothing "ssmtp") "smtpd" Postfix.defServiceOpts -- Configures postfix to have the dkim milter, and no other milters. dkimMilter :: Property (HasInfo + DebianLike) dkimMilter = Postfix.mainCfFile `File.containsLines` [ "smtpd_milters = inet:localhost:8891" , "non_smtpd_milters = inet:localhost:8891" , "milter_default_action = accept" ] `describe` "postfix dkim milter" `onChange` Postfix.dedupMainCf `onChange` Postfix.reloaded `requires` dkimInstalled -- This does not configure postfix to use the dkim milter, -- nor does it set up domainkey DNS. dkimInstalled :: Property (HasInfo + DebianLike) dkimInstalled = go `onChange` Service.restarted "opendkim" where go = propertyList "opendkim installed" $ props & Apt.serviceInstalledRunning "opendkim" & File.dirExists "/etc/mail" & File.hasPrivContent "/etc/mail/dkim.key" (Context "kitenet.net") & File.ownerGroup "/etc/mail/dkim.key" (User "opendkim") (Group "opendkim") & "/etc/default/opendkim" `File.containsLine` "SOCKET=\"inet:8891@localhost\"" & "/etc/opendkim.conf" `File.containsLines` [ "KeyFile /etc/mail/dkim.key" , "SubDomains yes" , "Domain *" , "Selector mail" ] -- This is the dkim public key, corresponding with /etc/mail/dkim.key -- This value can be included in a domain's additional records to make -- it use this domainkey. domainKey :: (BindDomain, Record) domainKey = (RelDomain "mail._domainkey", TXT "v=DKIM1; k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCc+/rfzNdt5DseBBmfB3C6sVM7FgVvf4h1FeCfyfwPpVcmPdW6M2I+NtJsbRkNbEICxiP6QY2UM0uoo9TmPqLgiCCG2vtuiG6XMsS0Y/gGwqKM7ntg/7vT1Go9vcquOFFuLa5PnzpVf8hB9+PMFdS4NPTvWL2c5xxshl/RJzICnQIDAQAB") hasJoeyCAChain :: Property (HasInfo + UnixLike) hasJoeyCAChain = "/etc/ssl/certs/joeyca.pem" `File.hasPrivContentExposed` Context "joeyca.pem" hasPostfixCert :: Context -> Property (HasInfo + UnixLike) hasPostfixCert ctx = combineProperties "postfix tls cert installed" $ props & "/etc/ssl/certs/postfix.pem" `File.hasPrivContentExposed` ctx & "/etc/ssl/private/postfix.pem" `File.hasPrivContent` ctx -- Legacy static web sites and redirections from kitenet.net to newer -- sites. legacyWebSites :: Property (HasInfo + DebianLike) legacyWebSites = propertyList "legacy web sites" $ props & Apt.serviceInstalledRunning "apache2" & Apache.modEnabled "rewrite" & Apache.modEnabled "cgi" & Apache.modEnabled "speling" & userDirHtml & Apache.httpsVirtualHost' "kitenet.net" "/var/www" letos kitenetcfg & alias "anna.kitenet.net" & apacheSite "anna.kitenet.net" [ "DocumentRoot /home/anna/html" , "<Directory /home/anna/html/>" , " Options Indexes ExecCGI" , " AllowOverride None" , Apache.allowAll , "</Directory>" ] & alias "sows-ear.kitenet.net" & alias "www.sows-ear.kitenet.net" & apacheSite "sows-ear.kitenet.net" [ "ServerAlias www.sows-ear.kitenet.net" , "DocumentRoot /srv/web/sows-ear.kitenet.net" , "<Directory /srv/web/sows-ear.kitenet.net>" , " Options FollowSymLinks" , " AllowOverride None" , Apache.allowAll , "</Directory>" , "RewriteEngine On" , "RewriteRule .* http://www.sowsearpoetry.org/ [L]" ] & alias "wortroot.kitenet.net" & alias "www.wortroot.kitenet.net" & apacheSite "wortroot.kitenet.net" [ "ServerAlias www.wortroot.kitenet.net" , "DocumentRoot /srv/web/wortroot.kitenet.net" , "<Directory /srv/web/wortroot.kitenet.net>" , " Options FollowSymLinks" , " AllowOverride None" , Apache.allowAll , "</Directory>" ] & alias "creeksidepress.com" & apacheSite "creeksidepress.com" [ "ServerAlias www.creeksidepress.com" , "DocumentRoot /srv/web/www.creeksidepress.com" , "<Directory /srv/web/www.creeksidepress.com>" , " Options FollowSymLinks" , " AllowOverride None" , Apache.allowAll , "</Directory>" ] & alias "joey.kitenet.net" & apacheSite "joey.kitenet.net" [ "DocumentRoot /var/www" , "<Directory /var/www/>" , " Options Indexes ExecCGI" , " AllowOverride None" , Apache.allowAll , "</Directory>" , "RewriteEngine On" , "# Old ikiwiki filenames for joey's wiki." , "rewritecond $1 !.*/index$" , "rewriterule (.+).html$ http://joeyh.name/$1/ [l]" , "rewritecond $1 !.*/index$" , "rewriterule (.+).rss$ http://joeyh.name/$1/index.rss [l]" , "# Redirect all to joeyh.name." , "rewriterule (.*) http://joeyh.name$1 [r]" ] where kitenetcfg = -- /var/www is empty [ "DocumentRoot /var/www" , "<Directory /var/www>" , " Options Indexes FollowSymLinks MultiViews ExecCGI Includes" , " AllowOverride None" , Apache.allowAll , "</Directory>" , "ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/" -- for mailman cgi scripts , "<Directory /usr/lib/cgi-bin>" , " AllowOverride None" , " Options ExecCGI" , Apache.allowAll , "</Directory>" , "Alias /pipermail/ /var/lib/mailman/archives/public/" , "<Directory /var/lib/mailman/archives/public/>" , " Options Indexes MultiViews FollowSymlinks" , " AllowOverride None" , Apache.allowAll , "</Directory>" , "Alias /images/ /usr/share/images/" , "<Directory /usr/share/images/>" , " Options Indexes MultiViews" , " AllowOverride None" , Apache.allowAll , "</Directory>" , "RewriteEngine On" , "# Force hostname to kitenet.net" , "RewriteCond %{HTTP_HOST} !^kitenet\\.net [NC]" , "RewriteCond %{HTTP_HOST} !^$" , "RewriteRule ^/(.*) http://kitenet\\.net/$1 [L,R]" , "# Moved pages" , "RewriteRule /programs/debhelper http://joeyh.name/code/debhelper/ [L]" , "RewriteRule /programs/satutils http://joeyh.name/code/satutils/ [L]" , "RewriteRule /programs/filters http://joeyh.name/code/filters/ [L]" , "RewriteRule /programs/ticker http://joeyh.name/code/ticker/ [L]" , "RewriteRule /programs/pdmenu http://joeyh.name/code/pdmenu/ [L]" , "RewriteRule /programs/sleepd http://joeyh.name/code/sleepd/ [L]" , "RewriteRule /programs/Lingua::EN::Words2Nums http://joeyh.name/code/Words2Nums/ [L]" , "RewriteRule /programs/wmbattery http://joeyh.name/code/wmbattery/ [L]" , "RewriteRule /programs/dpkg-repack http://joeyh.name/code/dpkg-repack/ [L]" , "RewriteRule /programs/debconf http://joeyh.name/code/debconf/ [L]" , "RewriteRule /programs/perlmoo http://joeyh.name/code/perlmoo/ [L]" , "RewriteRule /programs/alien http://joeyh.name/code/alien/ [L]" , "RewriteRule /~joey/blog/entry/(.+)-[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]-[0-9][0-9]-[0-9][0-9].html http://joeyh.name/blog/entry/$1/ [L]" , "RewriteRule /~anna/.* http://waldeneffect\\.org/ [R]" , "RewriteRule /~anna/.* http://waldeneffect\\.org/ [R]" , "RewriteRule /~anna http://waldeneffect\\.org/ [R]" , "RewriteRule /simpleid/ http://openid.kitenet.net:8081/simpleid/" , "# Even the kite home page is not here any more!" , "RewriteRule ^/$ http://www.kitenet.net/ [R]" , "RewriteRule ^/index.html http://www.kitenet.net/ [R]" , "RewriteRule ^/joey http://www.kitenet.net/joey/ [R]" , "RewriteRule ^/joey/index.html http://www.kitenet.net/joey/ [R]" , "RewriteRule ^/wifi http://www.kitenet.net/wifi/ [R]" , "RewriteRule ^/wifi/index.html http://www.kitenet.net/wifi/ [R]" , "# Old ikiwiki filenames for kitenet.net wiki." , "rewritecond $1 !^/~" , "rewritecond $1 !^/doc/" , "rewritecond $1 !^/pipermail/" , "rewritecond $1 !^/cgi-bin/" , "rewritecond $1 !.*/index$" , "rewriterule (.+).html$ $1/ [r]" , "# Old ikiwiki filenames for joey's wiki." , "rewritecond $1 ^/~joey/" , "rewritecond $1 !.*/index$" , "rewriterule (.+).html$ http://kitenet.net/$1/ [L,R]" , "# ~joey to joeyh.name" , "rewriterule /~joey/(.*) http://joeyh.name/$1 [L]" , "# Old familywiki location." , "rewriterule /~family/(.*).html http://family.kitenet.net/$1 [L]" , "rewriterule /~family/(.*).rss http://family.kitenet.net/$1/index.rss [L]" , "rewriterule /~family(.*) http://family.kitenet.net$1 [L]" , "rewriterule /~kyle/bywayofscience(.*) http://bywayofscience.branchable.com$1 [L]" , "rewriterule /~kyle/family/wiki/(.*).html http://macleawiki.branchable.com/$1 [L]" , "rewriterule /~kyle/family/wiki/(.*).rss http://macleawiki.branchable.com/$1/index.rss [L]" , "rewriterule /~kyle/family/wiki(.*) http://macleawiki.branchable.com$1 [L]" ] userDirHtml :: Property DebianLike userDirHtml = File.fileProperty "apache userdir is html" (map munge) conf `onChange` Apache.reloaded `requires` Apache.modEnabled "userdir" where munge = replace "public_html" "html" conf = "/etc/apache2/mods-available/userdir.conf" -- Alarm clock: see -- <http://joeyh.name/blog/entry/a_programmable_alarm_clock_using_systemd/> -- -- oncalendar example value: "*-*-* 7:30" alarmClock :: String -> User -> String -> Property Linux alarmClock oncalendar (User user) command = combineProperties "goodmorning timer installed" $ props & "/etc/systemd/system/goodmorning.timer" `File.hasContent` [ "[Unit]" , "Description=good morning" , "" , "[Timer]" , "Unit=goodmorning.service" , "OnCalendar=" ++ oncalendar , "WakeSystem=true" , "Persistent=false" , "" , "[Install]" , "WantedBy=multi-user.target" ] `onChange` (Systemd.daemonReloaded `before` Systemd.restarted "goodmorning.timer") & "/etc/systemd/system/goodmorning.service" `File.hasContent` [ "[Unit]" , "Description=good morning" , "RefuseManualStart=true" , "RefuseManualStop=true" , "ConditionACPower=true" , "StopWhenUnneeded=yes" , "" , "[Service]" , "Type=oneshot" , "ExecStart=/bin/systemd-inhibit --what=handle-lid-switch --why=goodmorning /bin/su " ++ user ++ " -c \"" ++ command ++ "\"" ] `onChange` Systemd.daemonReloaded & Systemd.enabled "goodmorning.timer" & Systemd.started "goodmorning.timer" & "/etc/systemd/logind.conf" `ConfFile.containsIniSetting` ("Login", "LidSwitchIgnoreInhibited", "no")
ArchiveTeam/glowing-computing-machine
src/Propellor/Property/SiteSpecific/JoeySites.hs
bsd-2-clause
36,052
388
86
5,154
6,496
3,576
2,920
-1
-1
module BookCalendar where import Data.Time import Data.Time.Calendar.WeekDate currentWordCount :: Integer currentWordCount = 14700 wordsPerDay :: Integer wordsPerDay = 333 isWeekend :: Day -> Bool isWeekend d = let (_,_,dow) = toWeekDate d in dow > 5 addToDay :: UTCTime -> Integer -> Day addToDay today days = addDays days . utctDay $ today printDay :: FormatTime t => t -> String printDay d = formatTime defaultTimeLocale " %a - %b %e %Y" d futureCounts :: [Integer] futureCounts = map (\n -> currentWordCount + (n * wordsPerDay)) [1..] buildDate :: UTCTime -> Integer -> String buildDate today daysFuture = let dayNumber = addToDay today daysFuture in printDay dayNumber dailyCounts :: t -> UTCTime -> [String] dailyCounts goal today = let days = filter (\n -> not $ isWeekend $ addToDay today n) [1..35] dayStrings = map (buildDate today) days in map (\(n, d) -> (show n) ++ d) $ zip futureCounts dayStrings main :: IO [()] main = do today <- getCurrentTime sequence $ map (putStrLn . show) $ dailyCounts wordsPerDay today
steveshogren/haskell-katas
src/BookCalendar.hs
bsd-3-clause
1,058
0
13
202
399
208
191
30
1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 The @TyCon@ datatype -} {-# LANGUAGE CPP, FlexibleInstances #-} module TyCon( -- * Main TyCon data types TyCon, AlgTyConRhs(..), visibleDataCons, AlgTyConFlav(..), isNoParent, FamTyConFlav(..), Role(..), Injectivity(..), RuntimeRepInfo(..), -- * TyConBinder TyConBinder, TyConBndrVis(..), mkNamedTyConBinder, mkNamedTyConBinders, mkAnonTyConBinder, mkAnonTyConBinders, tyConBinderArgFlag, isNamedTyConBinder, isVisibleTyConBinder, isInvisibleTyConBinder, -- ** Field labels tyConFieldLabels, tyConFieldLabelEnv, -- ** Constructing TyCons mkAlgTyCon, mkClassTyCon, mkFunTyCon, mkPrimTyCon, mkKindTyCon, mkLiftedPrimTyCon, mkTupleTyCon, mkSynonymTyCon, mkFamilyTyCon, mkPromotedDataCon, mkTcTyCon, -- ** Predicates on TyCons isAlgTyCon, isVanillaAlgTyCon, isClassTyCon, isFamInstTyCon, isFunTyCon, isPrimTyCon, isTupleTyCon, isUnboxedTupleTyCon, isBoxedTupleTyCon, isTypeSynonymTyCon, mightBeUnsaturatedTyCon, isPromotedDataCon, isPromotedDataCon_maybe, isKindTyCon, isLiftedTypeKindTyConName, isDataTyCon, isProductTyCon, isDataProductTyCon_maybe, isEnumerationTyCon, isNewTyCon, isAbstractTyCon, isFamilyTyCon, isOpenFamilyTyCon, isTypeFamilyTyCon, isDataFamilyTyCon, isOpenTypeFamilyTyCon, isClosedSynFamilyTyConWithAxiom_maybe, familyTyConInjectivityInfo, isBuiltInSynFamTyCon_maybe, isUnliftedTyCon, isGadtSyntaxTyCon, isInjectiveTyCon, isGenerativeTyCon, isGenInjAlgRhs, isTyConAssoc, tyConAssoc_maybe, isImplicitTyCon, isTyConWithSrcDataCons, isTcTyCon, -- ** Extracting information out of TyCons tyConName, tyConKind, tyConUnique, tyConTyVars, tyConCType, tyConCType_maybe, tyConDataCons, tyConDataCons_maybe, tyConSingleDataCon_maybe, tyConSingleDataCon, tyConSingleAlgDataCon_maybe, tyConFamilySize, tyConStupidTheta, tyConArity, tyConRoles, tyConFlavour, tyConTuple_maybe, tyConClass_maybe, tyConATs, tyConFamInst_maybe, tyConFamInstSig_maybe, tyConFamilyCoercion_maybe, tyConFamilyResVar_maybe, synTyConDefn_maybe, synTyConRhs_maybe, famTyConFlav_maybe, famTcResVar, algTyConRhs, newTyConRhs, newTyConEtadArity, newTyConEtadRhs, unwrapNewTyCon_maybe, unwrapNewTyConEtad_maybe, newTyConDataCon_maybe, algTcFields, tyConRuntimeRepInfo, tyConBinders, tyConResKind, tcTyConScopedTyVars, -- ** Manipulating TyCons expandSynTyCon_maybe, makeTyConAbstract, newTyConCo, newTyConCo_maybe, pprPromotionQuote, mkTyConKind, -- * Runtime type representation TyConRepName, tyConRepName_maybe, mkPrelTyConRepName, tyConRepModOcc, -- * Primitive representations of Types PrimRep(..), PrimElemRep(..), isVoidRep, isGcPtrRep, primRepSizeW, primElemRepSizeB, primRepIsFloat, -- * Recursion breaking RecTcChecker, initRecTc, checkRecTc ) where #include "HsVersions.h" import {-# SOURCE #-} TyCoRep ( Kind, Type, PredType, pprType ) import {-# SOURCE #-} TysWiredIn ( runtimeRepTyCon, constraintKind , vecCountTyCon, vecElemTyCon, liftedTypeKind , mkFunKind, mkForAllKind ) import {-# SOURCE #-} DataCon ( DataCon, dataConExTyVars, dataConFieldLabels ) import Binary import Var import Class import BasicTypes import DynFlags import ForeignCall import Name import NameEnv import CoAxiom import PrelNames import Maybes import Outputable import FastStringEnv import FieldLabel import Constants import Util import Unique( tyConRepNameUnique, dataConRepNameUnique ) import UniqSet import Module import qualified Data.Data as Data {- ----------------------------------------------- Notes about type families ----------------------------------------------- Note [Type synonym families] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Type synonym families, also known as "type functions", map directly onto the type functions in FC: type family F a :: * type instance F Int = Bool ..etc... * Reply "yes" to isTypeFamilyTyCon, and isFamilyTyCon * From the user's point of view (F Int) and Bool are simply equivalent types. * A Haskell 98 type synonym is a degenerate form of a type synonym family. * Type functions can't appear in the LHS of a type function: type instance F (F Int) = ... -- BAD! * Translation of type family decl: type family F a :: * translates to a FamilyTyCon 'F', whose FamTyConFlav is OpenSynFamilyTyCon type family G a :: * where G Int = Bool G Bool = Char G a = () translates to a FamilyTyCon 'G', whose FamTyConFlav is ClosedSynFamilyTyCon, with the appropriate CoAxiom representing the equations We also support injective type families -- see Note [Injective type families] Note [Data type families] ~~~~~~~~~~~~~~~~~~~~~~~~~ See also Note [Wrappers for data instance tycons] in MkId.hs * Data type families are declared thus data family T a :: * data instance T Int = T1 | T2 Bool Here T is the "family TyCon". * Reply "yes" to isDataFamilyTyCon, and isFamilyTyCon * The user does not see any "equivalent types" as he did with type synonym families. He just sees constructors with types T1 :: T Int T2 :: Bool -> T Int * Here's the FC version of the above declarations: data T a data R:TInt = T1 | T2 Bool axiom ax_ti : T Int ~R R:TInt Note that this is a *representational* coercion The R:TInt is the "representation TyCons". It has an AlgTyConFlav of DataFamInstTyCon T [Int] ax_ti * The axiom ax_ti may be eta-reduced; see Note [Eta reduction for data family axioms] in TcInstDcls * The data constructor T2 has a wrapper (which is what the source-level "T2" invokes): $WT2 :: Bool -> T Int $WT2 b = T2 b `cast` sym ax_ti * A data instance can declare a fully-fledged GADT: data instance T (a,b) where X1 :: T (Int,Bool) X2 :: a -> b -> T (a,b) Here's the FC version of the above declaration: data R:TPair a where X1 :: R:TPair Int Bool X2 :: a -> b -> R:TPair a b axiom ax_pr :: T (a,b) ~R R:TPair a b $WX1 :: forall a b. a -> b -> T (a,b) $WX1 a b (x::a) (y::b) = X2 a b x y `cast` sym (ax_pr a b) The R:TPair are the "representation TyCons". We have a bit of work to do, to unpick the result types of the data instance declaration for T (a,b), to get the result type in the representation; e.g. T (a,b) --> R:TPair a b The representation TyCon R:TList, has an AlgTyConFlav of DataFamInstTyCon T [(a,b)] ax_pr * Notice that T is NOT translated to a FC type function; it just becomes a "data type" with no constructors, which can be coerced inot into R:TInt, R:TPair by the axioms. These axioms axioms come into play when (and *only* when) you - use a data constructor - do pattern matching Rather like newtype, in fact As a result - T behaves just like a data type so far as decomposition is concerned - (T Int) is not implicitly converted to R:TInt during type inference. Indeed the latter type is unknown to the programmer. - There *is* an instance for (T Int) in the type-family instance environment, but it is only used for overlap checking - It's fine to have T in the LHS of a type function: type instance F (T a) = [a] It was this last point that confused me! The big thing is that you should not think of a data family T as a *type function* at all, not even an injective one! We can't allow even injective type functions on the LHS of a type function: type family injective G a :: * type instance F (G Int) = Bool is no good, even if G is injective, because consider type instance G Int = Bool type instance F Bool = Char So a data type family is not an injective type function. It's just a data type with some axioms that connect it to other data types. * The tyConTyVars of the representation tycon are the tyvars that the user wrote in the patterns. This is important in TcDeriv, where we bring these tyvars into scope before type-checking the deriving clause. This fact is arranged for in TcInstDecls.tcDataFamInstDecl. Note [Associated families and their parent class] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *Associated* families are just like *non-associated* families, except that they have a famTcParent field of (Just cls), which identifies the parent class. However there is an important sharing relationship between * the tyConTyVars of the parent Class * the tyConTyvars of the associated TyCon class C a b where data T p a type F a q b Here the 'a' and 'b' are shared with the 'Class'; that is, they have the same Unique. This is important. In an instance declaration we expect * all the shared variables to be instantiated the same way * the non-shared variables of the associated type should not be instantiated at all instance C [x] (Tree y) where data T p [x] = T1 x | T2 p type F [x] q (Tree y) = (x,y,q) Note [TyCon Role signatures] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Every tycon has a role signature, assigning a role to each of the tyConTyVars (or of equal length to the tyConArity, if there are no tyConTyVars). An example demonstrates these best: say we have a tycon T, with parameters a at nominal, b at representational, and c at phantom. Then, to prove representational equality between T a1 b1 c1 and T a2 b2 c2, we need to have nominal equality between a1 and a2, representational equality between b1 and b2, and nothing in particular (i.e., phantom equality) between c1 and c2. This might happen, say, with the following declaration: data T a b c where MkT :: b -> T Int b c Data and class tycons have their roles inferred (see inferRoles in TcTyDecls), as do vanilla synonym tycons. Family tycons have all parameters at role N, though it is conceivable that we could relax this restriction. (->)'s and tuples' parameters are at role R. Each primitive tycon declares its roles; it's worth noting that (~#)'s parameters are at role N. Promoted data constructors' type arguments are at role R. All kind arguments are at role N. Note [Unboxed tuple RuntimeRep vars] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The contents of an unboxed tuple may have any representation. Accordingly, the kind of the unboxed tuple constructor is runtime-representation polymorphic. For example, (#,#) :: forall (q :: RuntimeRep) (r :: RuntimeRep). TYPE q -> TYPE r -> # These extra tyvars (v and w) cause some delicate processing around tuples, where we used to be able to assume that the tycon arity and the datacon arity were the same. Note [Injective type families] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We allow injectivity annotations for type families (both open and closed): type family F (a :: k) (b :: k) = r | r -> a type family G a b = res | res -> a b where ... Injectivity information is stored in the `famTcInj` field of `FamilyTyCon`. `famTcInj` maybe stores a list of Bools, where each entry corresponds to a single element of `tyConTyVars` (both lists should have identical length). If no injectivity annotation was provided `famTcInj` is Nothing. From this follows an invariant that if `famTcInj` is a Just then at least one element in the list must be True. See also: * [Injectivity annotation] in HsDecls * [Renaming injectivity annotation] in RnSource * [Verifying injectivity annotation] in FamInstEnv * [Type inference for type families with injectivity] in TcInteract ************************************************************************ * * TyConBinder * * ************************************************************************ -} type TyConBinder = TyVarBndr TyVar TyConBndrVis data TyConBndrVis = NamedTCB ArgFlag | AnonTCB mkAnonTyConBinder :: TyVar -> TyConBinder mkAnonTyConBinder tv = TvBndr tv AnonTCB mkAnonTyConBinders :: [TyVar] -> [TyConBinder] mkAnonTyConBinders tvs = map mkAnonTyConBinder tvs mkNamedTyConBinder :: ArgFlag -> TyVar -> TyConBinder -- The odd argument order supports currying mkNamedTyConBinder vis tv = TvBndr tv (NamedTCB vis) mkNamedTyConBinders :: ArgFlag -> [TyVar] -> [TyConBinder] -- The odd argument order supports currying mkNamedTyConBinders vis tvs = map (mkNamedTyConBinder vis) tvs tyConBinderArgFlag :: TyConBinder -> ArgFlag tyConBinderArgFlag (TvBndr _ (NamedTCB vis)) = vis tyConBinderArgFlag (TvBndr _ AnonTCB) = Required isNamedTyConBinder :: TyConBinder -> Bool isNamedTyConBinder (TvBndr _ (NamedTCB {})) = True isNamedTyConBinder _ = False isVisibleTyConBinder :: TyVarBndr tv TyConBndrVis -> Bool -- Works for IfaceTyConBinder too isVisibleTyConBinder (TvBndr _ (NamedTCB vis)) = isVisibleArgFlag vis isVisibleTyConBinder (TvBndr _ AnonTCB) = True isInvisibleTyConBinder :: TyVarBndr tv TyConBndrVis -> Bool -- Works for IfaceTyConBinder too isInvisibleTyConBinder tcb = not (isVisibleTyConBinder tcb) mkTyConKind :: [TyConBinder] -> Kind -> Kind mkTyConKind bndrs res_kind = foldr mk res_kind bndrs where mk :: TyConBinder -> Kind -> Kind mk (TvBndr tv AnonTCB) k = mkFunKind (tyVarKind tv) k mk (TvBndr tv (NamedTCB vis)) k = mkForAllKind tv vis k {- Note [The binders/kind/arity fields of a TyCon] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All TyCons have this group of fields tyConBinders :: [TyConBinder] tyConResKind :: Kind tyConTyVars :: [TyVra] -- Cached = binderVars tyConBinders tyConKind :: Kind -- Cached = mkTyConKind tyConBinders tyConResKind tyConArity :: Arity -- Cached = length tyConBinders They fit together like so: * tyConBinders gives the telescope of type variables on the LHS of the type declaration. For example: type App a (b :: k) = a b tyConBinders = [ TvBndr (k::*) (NamedTCB Inferred) , TvBndr (a:k->*) AnonTCB , TvBndr (b:k) AnonTCB ] Note that that are three binders here, including the kind variable k. See Note [TyBinders and ArgFlags] in TyCoRep for what the visibility flag means. * Each TyConBinder tyConBinders has a TyVar, and that TyVar may scope over some other part of the TyCon's definition. Eg type T a = a->a we have tyConBinders = [ TvBndr (a:*) AnonTCB ] synTcRhs = a->a So the 'a' scopes over the synTcRhs * From the tyConBinders and tyConResKind we can get the tyConKind E.g for our App example: App :: forall k. (k->*) -> k -> * We get a 'forall' in the kind for each NamedTCB, and an arrow for each AnonTCB tyConKind is the full kind of the TyCon, not just the result kind * tyConArity is the arguments this TyCon must be applied to, to be considered saturated. Here we mean "applied to in the actual Type", not surface syntax; i.e. including implicit kind variables. So it's just (length tyConBinders) -} instance Outputable tv => Outputable (TyVarBndr tv TyConBndrVis) where ppr (TvBndr v AnonTCB) = ppr v ppr (TvBndr v (NamedTCB Required)) = ppr v ppr (TvBndr v (NamedTCB Specified)) = char '@' <> ppr v ppr (TvBndr v (NamedTCB Inferred)) = braces (ppr v) instance Binary TyConBndrVis where put_ bh AnonTCB = putByte bh 0 put_ bh (NamedTCB vis) = do { putByte bh 1; put_ bh vis } get bh = do { h <- getByte bh ; case h of 0 -> return AnonTCB _ -> do { vis <- get bh; return (NamedTCB vis) } } {- ********************************************************************* * * The TyCon type * * ************************************************************************ -} -- | TyCons represent type constructors. Type constructors are introduced by -- things such as: -- -- 1) Data declarations: @data Foo = ...@ creates the @Foo@ type constructor of -- kind @*@ -- -- 2) Type synonyms: @type Foo = ...@ creates the @Foo@ type constructor -- -- 3) Newtypes: @newtype Foo a = MkFoo ...@ creates the @Foo@ type constructor -- of kind @* -> *@ -- -- 4) Class declarations: @class Foo where@ creates the @Foo@ type constructor -- of kind @*@ -- -- This data type also encodes a number of primitive, built in type constructors -- such as those for function and tuple types. -- If you edit this type, you may need to update the GHC formalism -- See Note [GHC Formalism] in coreSyn/CoreLint.hs data TyCon = -- | The function type constructor, @(->)@ FunTyCon { tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant: -- identical to Unique of Name stored in -- tyConName field. tyConName :: Name, -- ^ Name of the constructor -- See Note [The binders/kind/arity fields of a TyCon] tyConBinders :: [TyConBinder], -- ^ Full binders tyConResKind :: Kind, -- ^ Result kind tyConKind :: Kind, -- ^ Kind of this TyCon tyConArity :: Arity, -- ^ Arity tcRepName :: TyConRepName } -- | Algebraic data types, from -- - @data@ declararations -- - @newtype@ declarations -- - data instance declarations -- - type instance declarations -- - the TyCon generated by a class declaration -- - boxed tuples -- - unboxed tuples -- - constraint tuples -- All these constructors are lifted and boxed except unboxed tuples -- which should have an 'UnboxedAlgTyCon' parent. -- Data/newtype/type /families/ are handled by 'FamilyTyCon'. -- See 'AlgTyConRhs' for more information. | AlgTyCon { tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant: -- identical to Unique of Name stored in -- tyConName field. tyConName :: Name, -- ^ Name of the constructor -- See Note [The binders/kind/arity fields of a TyCon] tyConBinders :: [TyConBinder], -- ^ Full binders tyConTyVars :: [TyVar], -- ^ TyVar binders tyConResKind :: Kind, -- ^ Result kind tyConKind :: Kind, -- ^ Kind of this TyCon tyConArity :: Arity, -- ^ Arity -- The tyConTyVars scope over: -- -- 1. The 'algTcStupidTheta' -- 2. The cached types in algTyConRhs.NewTyCon -- 3. The family instance types if present -- -- Note that it does /not/ scope over the data -- constructors. tcRoles :: [Role], -- ^ The role for each type variable -- This list has length = tyConArity -- See also Note [TyCon Role signatures] tyConCType :: Maybe CType,-- ^ The C type that should be used -- for this type when using the FFI -- and CAPI algTcGadtSyntax :: Bool, -- ^ Was the data type declared with GADT -- syntax? If so, that doesn't mean it's a -- true GADT; only that the "where" form -- was used. This field is used only to -- guide pretty-printing algTcStupidTheta :: [PredType], -- ^ The \"stupid theta\" for the data -- type (always empty for GADTs). A -- \"stupid theta\" is the context to -- the left of an algebraic type -- declaration, e.g. @Eq a@ in the -- declaration @data Eq a => T a ...@. algTcRhs :: AlgTyConRhs, -- ^ Contains information about the -- data constructors of the algebraic type algTcFields :: FieldLabelEnv, -- ^ Maps a label to information -- about the field algTcParent :: AlgTyConFlav -- ^ Gives the class or family declaration -- 'TyCon' for derived 'TyCon's representing -- class or family instances, respectively. } -- | Represents type synonyms | SynonymTyCon { tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant: -- identical to Unique of Name stored in -- tyConName field. tyConName :: Name, -- ^ Name of the constructor -- See Note [The binders/kind/arity fields of a TyCon] tyConBinders :: [TyConBinder], -- ^ Full binders tyConTyVars :: [TyVar], -- ^ TyVar binders tyConResKind :: Kind, -- ^ Result kind tyConKind :: Kind, -- ^ Kind of this TyCon tyConArity :: Arity, -- ^ Arity -- tyConTyVars scope over: synTcRhs tcRoles :: [Role], -- ^ The role for each type variable -- This list has length = tyConArity -- See also Note [TyCon Role signatures] synTcRhs :: Type -- ^ Contains information about the expansion -- of the synonym } -- | Represents families (both type and data) -- Argument roles are all Nominal | FamilyTyCon { tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant: -- identical to Unique of Name stored in -- tyConName field. tyConName :: Name, -- ^ Name of the constructor -- See Note [The binders/kind/arity fields of a TyCon] tyConBinders :: [TyConBinder], -- ^ Full binders tyConTyVars :: [TyVar], -- ^ TyVar binders tyConResKind :: Kind, -- ^ Result kind tyConKind :: Kind, -- ^ Kind of this TyCon tyConArity :: Arity, -- ^ Arity -- tyConTyVars connect an associated family TyCon -- with its parent class; see TcValidity.checkConsistentFamInst famTcResVar :: Maybe Name, -- ^ Name of result type variable, used -- for pretty-printing with --show-iface -- and for reifying TyCon in Template -- Haskell famTcFlav :: FamTyConFlav, -- ^ Type family flavour: open, closed, -- abstract, built-in. See comments for -- FamTyConFlav famTcParent :: Maybe Class, -- ^ For *associated* type/data families -- The class in whose declaration the family is declared -- See Note [Associated families and their parent class] famTcInj :: Injectivity -- ^ is this a type family injective in -- its type variables? Nothing if no -- injectivity annotation was given } -- | Primitive types; cannot be defined in Haskell. This includes -- the usual suspects (such as @Int#@) as well as foreign-imported -- types and kinds (@*@, @#@, and @?@) | PrimTyCon { tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant: -- identical to Unique of Name stored in -- tyConName field. tyConName :: Name, -- ^ Name of the constructor -- See Note [The binders/kind/arity fields of a TyCon] tyConBinders :: [TyConBinder], -- ^ Full binders tyConResKind :: Kind, -- ^ Result kind tyConKind :: Kind, -- ^ Kind of this TyCon tyConArity :: Arity, -- ^ Arity tcRoles :: [Role], -- ^ The role for each type variable -- This list has length = tyConArity -- See also Note [TyCon Role signatures] isUnlifted :: Bool, -- ^ Most primitive tycons are unlifted (may -- not contain bottom) but other are lifted, -- e.g. @RealWorld@ -- Only relevant if tyConKind = * primRepName :: Maybe TyConRepName -- Only relevant for kind TyCons -- i.e, *, #, ? } -- | Represents promoted data constructor. | PromotedDataCon { -- See Note [Promoted data constructors] tyConUnique :: Unique, -- ^ Same Unique as the data constructor tyConName :: Name, -- ^ Same Name as the data constructor -- See Note [The binders/kind/arity fields of a TyCon] tyConBinders :: [TyConBinder], -- ^ Full binders tyConResKind :: Kind, -- ^ Result kind tyConKind :: Kind, -- ^ Kind of this TyCon tyConArity :: Arity, -- ^ Arity tcRoles :: [Role], -- ^ Roles: N for kind vars, R for type vars dataCon :: DataCon, -- ^ Corresponding data constructor tcRepName :: TyConRepName, promDcRepInfo :: RuntimeRepInfo -- ^ See comments with 'RuntimeRepInfo' } -- | These exist only during a recursive type/class type-checking knot. | TcTyCon { tyConUnique :: Unique, tyConName :: Name, tyConUnsat :: Bool, -- ^ can this tycon be unsaturated? -- See Note [The binders/kind/arity fields of a TyCon] tyConBinders :: [TyConBinder], -- ^ Full binders tyConTyVars :: [TyVar], -- ^ TyVar binders tyConResKind :: Kind, -- ^ Result kind tyConKind :: Kind, -- ^ Kind of this TyCon tyConArity :: Arity, -- ^ Arity tcTyConScopedTyVars :: [TyVar] -- ^ Scoped tyvars over the -- tycon's body. See Note [TcTyCon] } -- | Represents right-hand-sides of 'TyCon's for algebraic types data AlgTyConRhs -- | Says that we know nothing about this data type, except that -- it's represented by a pointer. Used when we export a data type -- abstractly into an .hi file. = AbstractTyCon Bool -- True <=> It's definitely a distinct data type, -- equal only to itself; ie not a newtype -- False <=> Not sure -- | Information about those 'TyCon's derived from a @data@ -- declaration. This includes data types with no constructors at -- all. | DataTyCon { data_cons :: [DataCon], -- ^ The data type constructors; can be empty if the -- user declares the type to have no constructors -- -- INVARIANT: Kept in order of increasing 'DataCon' -- tag (see the tag assignment in DataCon.mkDataCon) is_enum :: Bool -- ^ Cached value: is this an enumeration type? -- See Note [Enumeration types] } | TupleTyCon { -- A boxed, unboxed, or constraint tuple data_con :: DataCon, -- NB: it can be an *unboxed* tuple tup_sort :: TupleSort -- ^ Is this a boxed, unboxed or constraint -- tuple? } -- | Information about those 'TyCon's derived from a @newtype@ declaration | NewTyCon { data_con :: DataCon, -- ^ The unique constructor for the @newtype@. -- It has no existentials nt_rhs :: Type, -- ^ Cached value: the argument type of the -- constructor, which is just the representation -- type of the 'TyCon' (remember that @newtype@s -- do not exist at runtime so need a different -- representation type). -- -- The free 'TyVar's of this type are the -- 'tyConTyVars' from the corresponding 'TyCon' nt_etad_rhs :: ([TyVar], Type), -- ^ Same as the 'nt_rhs', but this time eta-reduced. -- Hence the list of 'TyVar's in this field may be -- shorter than the declared arity of the 'TyCon'. -- See Note [Newtype eta] nt_co :: CoAxiom Unbranched -- The axiom coercion that creates the @newtype@ -- from the representation 'Type'. -- See Note [Newtype coercions] -- Invariant: arity = #tvs in nt_etad_rhs; -- See Note [Newtype eta] -- Watch out! If any newtypes become transparent -- again check Trac #1072. } -- | Some promoted datacons signify extra info relevant to GHC. For example, -- the @IntRep@ constructor of @RuntimeRep@ corresponds to the 'IntRep' -- constructor of 'PrimRep'. This data structure allows us to store this -- information right in the 'TyCon'. The other approach would be to look -- up things like @RuntimeRep@'s @PrimRep@ by known-key every time. data RuntimeRepInfo = NoRRI -- ^ an ordinary promoted data con | RuntimeRep ([Type] -> PrimRep) -- ^ A constructor of @RuntimeRep@. The argument to the function should -- be the list of arguments to the promoted datacon. | VecCount Int -- ^ A constructor of @VecCount@ | VecElem PrimElemRep -- ^ A constructor of @VecElem@ -- | Extract those 'DataCon's that we are able to learn about. Note -- that visibility in this sense does not correspond to visibility in -- the context of any particular user program! visibleDataCons :: AlgTyConRhs -> [DataCon] visibleDataCons (AbstractTyCon {}) = [] visibleDataCons (DataTyCon{ data_cons = cs }) = cs visibleDataCons (NewTyCon{ data_con = c }) = [c] visibleDataCons (TupleTyCon{ data_con = c }) = [c] -- ^ Both type classes as well as family instances imply implicit -- type constructors. These implicit type constructors refer to their parent -- structure (ie, the class or family from which they derive) using a type of -- the following form. data AlgTyConFlav = -- | An ordinary type constructor has no parent. VanillaAlgTyCon TyConRepName -- | An unboxed type constructor. Note that this carries no TyConRepName -- as it is not representable. | UnboxedAlgTyCon -- | Type constructors representing a class dictionary. -- See Note [ATyCon for classes] in TyCoRep | ClassTyCon Class -- INVARIANT: the classTyCon of this Class is the -- current tycon TyConRepName -- | Type constructors representing an *instance* of a *data* family. -- Parameters: -- -- 1) The type family in question -- -- 2) Instance types; free variables are the 'tyConTyVars' -- of the current 'TyCon' (not the family one). INVARIANT: -- the number of types matches the arity of the family 'TyCon' -- -- 3) A 'CoTyCon' identifying the representation -- type with the type instance family | DataFamInstTyCon -- See Note [Data type families] (CoAxiom Unbranched) -- The coercion axiom. -- A *Representational* coercion, -- of kind T ty1 ty2 ~R R:T a b c -- where T is the family TyCon, -- and R:T is the representation TyCon (ie this one) -- and a,b,c are the tyConTyVars of this TyCon -- -- BUT may be eta-reduced; see TcInstDcls -- Note [Eta reduction for data family axioms] -- Cached fields of the CoAxiom, but adjusted to -- use the tyConTyVars of this TyCon TyCon -- The family TyCon [Type] -- Argument types (mentions the tyConTyVars of this TyCon) -- Match in length the tyConTyVars of the family TyCon -- E.g. data intance T [a] = ... -- gives a representation tycon: -- data R:TList a = ... -- axiom co a :: T [a] ~ R:TList a -- with R:TList's algTcParent = DataFamInstTyCon T [a] co instance Outputable AlgTyConFlav where ppr (VanillaAlgTyCon {}) = text "Vanilla ADT" ppr (UnboxedAlgTyCon {}) = text "Unboxed ADT" ppr (ClassTyCon cls _) = text "Class parent" <+> ppr cls ppr (DataFamInstTyCon _ tc tys) = text "Family parent (family instance)" <+> ppr tc <+> sep (map pprType tys) -- | Checks the invariants of a 'AlgTyConFlav' given the appropriate type class -- name, if any okParent :: Name -> AlgTyConFlav -> Bool okParent _ (VanillaAlgTyCon {}) = True okParent _ (UnboxedAlgTyCon) = True okParent tc_name (ClassTyCon cls _) = tc_name == tyConName (classTyCon cls) okParent _ (DataFamInstTyCon _ fam_tc tys) = tyConArity fam_tc == length tys isNoParent :: AlgTyConFlav -> Bool isNoParent (VanillaAlgTyCon {}) = True isNoParent _ = False -------------------- data Injectivity = NotInjective | Injective [Bool] -- 1-1 with tyConTyVars (incl kind vars) deriving( Eq ) -- | Information pertaining to the expansion of a type synonym (@type@) data FamTyConFlav = -- | Represents an open type family without a fixed right hand -- side. Additional instances can appear at any time. -- -- These are introduced by either a top level declaration: -- -- > data family T a :: * -- -- Or an associated data type declaration, within a class declaration: -- -- > class C a b where -- > data T b :: * DataFamilyTyCon TyConRepName -- | An open type synonym family e.g. @type family F x y :: * -> *@ | OpenSynFamilyTyCon -- | A closed type synonym family e.g. -- @type family F x where { F Int = Bool }@ | ClosedSynFamilyTyCon (Maybe (CoAxiom Branched)) -- See Note [Closed type families] -- | A closed type synonym family declared in an hs-boot file with -- type family F a where .. | AbstractClosedSynFamilyTyCon -- | Built-in type family used by the TypeNats solver | BuiltInSynFamTyCon BuiltInSynFamily {- Note [Closed type families] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * In an open type family you can add new instances later. This is the usual case. * In a closed type family you can only put equations where the family is defined. A non-empty closed type family has a single axiom with multiple branches, stored in the 'ClosedSynFamilyTyCon' constructor. A closed type family with no equations does not have an axiom, because there is nothing for the axiom to prove! Note [Promoted data constructors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All data constructors can be promoted to become a type constructor, via the PromotedDataCon alternative in TyCon. * The TyCon promoted from a DataCon has the *same* Name and Unique as the DataCon. Eg. If the data constructor Data.Maybe.Just(unique 78, say) is promoted to a TyCon whose name is Data.Maybe.Just(unique 78) * Small note: We promote the *user* type of the DataCon. Eg data T = MkT {-# UNPACK #-} !(Bool, Bool) The promoted kind is MkT :: (Bool,Bool) -> T *not* MkT :: Bool -> Bool -> T Note [Enumeration types] ~~~~~~~~~~~~~~~~~~~~~~~~ We define datatypes with no constructors to *not* be enumerations; this fixes trac #2578, Otherwise we end up generating an empty table for <mod>_<type>_closure_tbl which is used by tagToEnum# to map Int# to constructors in an enumeration. The empty table apparently upset the linker. Moreover, all the data constructor must be enumerations, meaning they have type (forall abc. T a b c). GADTs are not enumerations. For example consider data T a where T1 :: T Int T2 :: T Bool T3 :: T a What would [T1 ..] be? [T1,T3] :: T Int? Easiest thing is to exclude them. See Trac #4528. Note [Newtype coercions] ~~~~~~~~~~~~~~~~~~~~~~~~ The NewTyCon field nt_co is a CoAxiom which is used for coercing from the representation type of the newtype, to the newtype itself. For example, newtype T a = MkT (a -> a) the NewTyCon for T will contain nt_co = CoT where CoT t : T t ~ t -> t. In the case that the right hand side is a type application ending with the same type variables as the left hand side, we "eta-contract" the coercion. So if we had newtype S a = MkT [a] then we would generate the arity 0 axiom CoS : S ~ []. The primary reason we do this is to make newtype deriving cleaner. In the paper we'd write axiom CoT : (forall t. T t) ~ (forall t. [t]) and then when we used CoT at a particular type, s, we'd say CoT @ s which encodes as (TyConApp instCoercionTyCon [TyConApp CoT [], s]) Note [Newtype eta] ~~~~~~~~~~~~~~~~~~ Consider newtype Parser a = MkParser (IO a) deriving Monad Are these two types equal (to Core)? Monad Parser Monad IO which we need to make the derived instance for Monad Parser. Well, yes. But to see that easily we eta-reduce the RHS type of Parser, in this case to ([], Froogle), so that even unsaturated applications of Parser will work right. This eta reduction is done when the type constructor is built, and cached in NewTyCon. Here's an example that I think showed up in practice Source code: newtype T a = MkT [a] newtype Foo m = MkFoo (forall a. m a -> Int) w1 :: Foo [] w1 = ... w2 :: Foo T w2 = MkFoo (\(MkT x) -> case w1 of MkFoo f -> f x) After desugaring, and discarding the data constructors for the newtypes, we get: w2 = w1 `cast` Foo CoT so the coercion tycon CoT must have kind: T ~ [] and arity: 0 Note [TcTyCon] ~~~~~~~~~~~~~~ When checking a type/class declaration (in module TcTyClsDecls), we come upon knowledge of the eventual tycon in bits and pieces. First, we use getInitialKinds to look over the user-provided kind signature of a tycon (including, for example, the number of parameters written to the tycon) to get an initial shape of the tycon's kind. Then, using these initial kinds, we kind-check the body of the tycon (class methods, data constructors, etc.), filling in the metavariables in the tycon's initial kind. We then generalize to get the tycon's final, fixed kind. Finally, once this has happened for all tycons in a mutually recursive group, we can desugar the lot. For convenience, we store partially-known tycons in TcTyCons, which might store meta-variables. These TcTyCons are stored in the local environment in TcTyClsDecls, until the real full TyCons can be created during desugaring. A desugared program should never have a TcTyCon. A challenging piece in all of this is that we end up taking three separate passes over every declaration: one in getInitialKind (this pass look only at the head, not the body), one in kcTyClDecls (to kind-check the body), and a final one in tcTyClDecls (to desugar). In the latter two passes, we need to connect the user-written type variables in an LHsQTyVars with the variables in the tycon's inferred kind. Because the tycon might not have a CUSK, this matching up is, in general, quite hard to do. (Look through the git history between Dec 2015 and Apr 2016 for TcHsType.splitTelescopeTvs!) Instead of trying, we just store the list of type variables to bring into scope in the later passes when we create a TcTyCon in getInitialKinds. Much easier this way! These tyvars are brought into scope in kcTyClTyVars and tcTyClTyVars, both in TcHsType. It is important that the scoped type variables not be zonked, as some scoped type variables come into existence as SigTvs. If we zonk, the Unique will change and the user-written occurrences won't match up with what we expect. In a TcTyCon, everything is zonked (except the scoped vars) after the kind-checking pass. ************************************************************************ * * TyConRepName * * ********************************************************************* -} type TyConRepName = Name -- The Name of the top-level declaration -- $tcMaybe :: Data.Typeable.Internal.TyCon -- $tcMaybe = TyCon { tyConName = "Maybe", ... } tyConRepName_maybe :: TyCon -> Maybe TyConRepName tyConRepName_maybe (FunTyCon { tcRepName = rep_nm }) = Just rep_nm tyConRepName_maybe (PrimTyCon { primRepName = mb_rep_nm }) = mb_rep_nm tyConRepName_maybe (AlgTyCon { algTcParent = parent }) | VanillaAlgTyCon rep_nm <- parent = Just rep_nm | ClassTyCon _ rep_nm <- parent = Just rep_nm tyConRepName_maybe (FamilyTyCon { famTcFlav = DataFamilyTyCon rep_nm }) = Just rep_nm tyConRepName_maybe (PromotedDataCon { tcRepName = rep_nm }) = Just rep_nm tyConRepName_maybe _ = Nothing -- | Make a 'Name' for the 'Typeable' representation of the given wired-in type mkPrelTyConRepName :: Name -> TyConRepName -- See Note [Grand plan for Typeable] in 'TcTypeable' in TcTypeable. mkPrelTyConRepName tc_name -- Prelude tc_name is always External, -- so nameModule will work = mkExternalName rep_uniq rep_mod rep_occ (nameSrcSpan tc_name) where name_occ = nameOccName tc_name name_mod = nameModule tc_name name_uniq = nameUnique tc_name rep_uniq | isTcOcc name_occ = tyConRepNameUnique name_uniq | otherwise = dataConRepNameUnique name_uniq (rep_mod, rep_occ) = tyConRepModOcc name_mod name_occ -- | The name (and defining module) for the Typeable representation (TyCon) of a -- type constructor. -- -- See Note [Grand plan for Typeable] in 'TcTypeable' in TcTypeable. tyConRepModOcc :: Module -> OccName -> (Module, OccName) tyConRepModOcc tc_module tc_occ = (rep_module, mkTyConRepOcc tc_occ) where rep_module | tc_module == gHC_PRIM = gHC_TYPES | otherwise = tc_module {- ********************************************************************* * * PrimRep * * ************************************************************************ Note [rep swamp] GHC has a rich selection of types that represent "primitive types" of one kind or another. Each of them makes a different set of distinctions, and mostly the differences are for good reasons, although it's probably true that we could merge some of these. Roughly in order of "includes more information": - A Width (cmm/CmmType) is simply a binary value with the specified number of bits. It may represent a signed or unsigned integer, a floating-point value, or an address. data Width = W8 | W16 | W32 | W64 | W80 | W128 - Size, which is used in the native code generator, is Width + floating point information. data Size = II8 | II16 | II32 | II64 | FF32 | FF64 | FF80 it is necessary because e.g. the instruction to move a 64-bit float on x86 (movsd) is different from the instruction to move a 64-bit integer (movq), so the mov instruction is parameterised by Size. - CmmType wraps Width with more information: GC ptr, float, or other value. data CmmType = CmmType CmmCat Width data CmmCat -- "Category" (not exported) = GcPtrCat -- GC pointer | BitsCat -- Non-pointer | FloatCat -- Float It is important to have GcPtr information in Cmm, since we generate info tables containing pointerhood for the GC from this. As for why we have float (and not signed/unsigned) here, see Note [Signed vs unsigned]. - ArgRep makes only the distinctions necessary for the call and return conventions of the STG machine. It is essentially CmmType + void. - PrimRep makes a few more distinctions than ArgRep: it divides non-GC-pointers into signed/unsigned and addresses, information that is necessary for passing these values to foreign functions. There's another tension here: whether the type encodes its size in bytes, or whether its size depends on the machine word size. Width and CmmType have the size built-in, whereas ArgRep and PrimRep do not. This means to turn an ArgRep/PrimRep into a CmmType requires DynFlags. On the other hand, CmmType includes some "nonsense" values, such as CmmType GcPtrCat W32 on a 64-bit machine. -} -- | A 'PrimRep' is an abstraction of a type. It contains information that -- the code generator needs in order to pass arguments, return results, -- and store values of this type. data PrimRep = VoidRep | PtrRep | IntRep -- ^ Signed, word-sized value | WordRep -- ^ Unsigned, word-sized value | Int64Rep -- ^ Signed, 64 bit value (with 32-bit words only) | Word64Rep -- ^ Unsigned, 64 bit value (with 32-bit words only) | AddrRep -- ^ A pointer, but /not/ to a Haskell value (use 'PtrRep') | FloatRep | DoubleRep | VecRep Int PrimElemRep -- ^ A vector deriving( Eq, Show ) data PrimElemRep = Int8ElemRep | Int16ElemRep | Int32ElemRep | Int64ElemRep | Word8ElemRep | Word16ElemRep | Word32ElemRep | Word64ElemRep | FloatElemRep | DoubleElemRep deriving( Eq, Show ) instance Outputable PrimRep where ppr r = text (show r) instance Outputable PrimElemRep where ppr r = text (show r) isVoidRep :: PrimRep -> Bool isVoidRep VoidRep = True isVoidRep _other = False isGcPtrRep :: PrimRep -> Bool isGcPtrRep PtrRep = True isGcPtrRep _ = False -- | Find the size of a 'PrimRep', in words primRepSizeW :: DynFlags -> PrimRep -> Int primRepSizeW _ IntRep = 1 primRepSizeW _ WordRep = 1 primRepSizeW dflags Int64Rep = wORD64_SIZE `quot` wORD_SIZE dflags primRepSizeW dflags Word64Rep = wORD64_SIZE `quot` wORD_SIZE dflags primRepSizeW _ FloatRep = 1 -- NB. might not take a full word primRepSizeW dflags DoubleRep = dOUBLE_SIZE dflags `quot` wORD_SIZE dflags primRepSizeW _ AddrRep = 1 primRepSizeW _ PtrRep = 1 primRepSizeW _ VoidRep = 0 primRepSizeW dflags (VecRep len rep) = len * primElemRepSizeB rep `quot` wORD_SIZE dflags primElemRepSizeB :: PrimElemRep -> Int primElemRepSizeB Int8ElemRep = 1 primElemRepSizeB Int16ElemRep = 2 primElemRepSizeB Int32ElemRep = 4 primElemRepSizeB Int64ElemRep = 8 primElemRepSizeB Word8ElemRep = 1 primElemRepSizeB Word16ElemRep = 2 primElemRepSizeB Word32ElemRep = 4 primElemRepSizeB Word64ElemRep = 8 primElemRepSizeB FloatElemRep = 4 primElemRepSizeB DoubleElemRep = 8 -- | Return if Rep stands for floating type, -- returns Nothing for vector types. primRepIsFloat :: PrimRep -> Maybe Bool primRepIsFloat FloatRep = Just True primRepIsFloat DoubleRep = Just True primRepIsFloat (VecRep _ _) = Nothing primRepIsFloat _ = Just False {- ************************************************************************ * * Field labels * * ************************************************************************ -} -- | The labels for the fields of this particular 'TyCon' tyConFieldLabels :: TyCon -> [FieldLabel] tyConFieldLabels tc = dFsEnvElts $ tyConFieldLabelEnv tc -- | The labels for the fields of this particular 'TyCon' tyConFieldLabelEnv :: TyCon -> FieldLabelEnv tyConFieldLabelEnv tc | isAlgTyCon tc = algTcFields tc | otherwise = emptyDFsEnv -- | Make a map from strings to FieldLabels from all the data -- constructors of this algebraic tycon fieldsOfAlgTcRhs :: AlgTyConRhs -> FieldLabelEnv fieldsOfAlgTcRhs rhs = mkDFsEnv [ (flLabel fl, fl) | fl <- dataConsFields (visibleDataCons rhs) ] where -- Duplicates in this list will be removed by 'mkFsEnv' dataConsFields dcs = concatMap dataConFieldLabels dcs {- ************************************************************************ * * \subsection{TyCon Construction} * * ************************************************************************ Note: the TyCon constructors all take a Kind as one argument, even though they could, in principle, work out their Kind from their other arguments. But to do so they need functions from Types, and that makes a nasty module mutual-recursion. And they aren't called from many places. So we compromise, and move their Kind calculation to the call site. -} -- | Given the name of the function type constructor and it's kind, create the -- corresponding 'TyCon'. It is reccomended to use 'TyCoRep.funTyCon' if you want -- this functionality mkFunTyCon :: Name -> [TyConBinder] -> Name -> TyCon mkFunTyCon name binders rep_nm = FunTyCon { tyConUnique = nameUnique name, tyConName = name, tyConBinders = binders, tyConResKind = liftedTypeKind, tyConKind = mkTyConKind binders liftedTypeKind, tyConArity = 2, tcRepName = rep_nm } -- | This is the making of an algebraic 'TyCon'. Notably, you have to -- pass in the generic (in the -XGenerics sense) information about the -- type constructor - you can get hold of it easily (see Generics -- module) mkAlgTyCon :: Name -> [TyConBinder] -- ^ Binders of the 'TyCon' -> Kind -- ^ Result kind -> [Role] -- ^ The roles for each TyVar -> Maybe CType -- ^ The C type this type corresponds to -- when using the CAPI FFI -> [PredType] -- ^ Stupid theta: see 'algTcStupidTheta' -> AlgTyConRhs -- ^ Information about data constructors -> AlgTyConFlav -- ^ What flavour is it? -- (e.g. vanilla, type family) -> Bool -- ^ Was the 'TyCon' declared with GADT syntax? -> TyCon mkAlgTyCon name binders res_kind roles cType stupid rhs parent gadt_syn = AlgTyCon { tyConName = name, tyConUnique = nameUnique name, tyConBinders = binders, tyConResKind = res_kind, tyConKind = mkTyConKind binders res_kind, tyConArity = length binders, tyConTyVars = binderVars binders, tcRoles = roles, tyConCType = cType, algTcStupidTheta = stupid, algTcRhs = rhs, algTcFields = fieldsOfAlgTcRhs rhs, algTcParent = ASSERT2( okParent name parent, ppr name $$ ppr parent ) parent, algTcGadtSyntax = gadt_syn } -- | Simpler specialization of 'mkAlgTyCon' for classes mkClassTyCon :: Name -> [TyConBinder] -> [Role] -> AlgTyConRhs -> Class -> Name -> TyCon mkClassTyCon name binders roles rhs clas tc_rep_name = mkAlgTyCon name binders constraintKind roles Nothing [] rhs (ClassTyCon clas tc_rep_name) False mkTupleTyCon :: Name -> [TyConBinder] -> Kind -- ^ Result kind of the 'TyCon' -> Arity -- ^ Arity of the tuple -> DataCon -> TupleSort -- ^ Whether the tuple is boxed or unboxed -> AlgTyConFlav -> TyCon mkTupleTyCon name binders res_kind arity con sort parent = AlgTyCon { tyConName = name, tyConUnique = nameUnique name, tyConBinders = binders, tyConResKind = res_kind, tyConKind = mkTyConKind binders res_kind, tyConArity = arity, tyConTyVars = binderVars binders, tcRoles = replicate arity Representational, tyConCType = Nothing, algTcStupidTheta = [], algTcRhs = TupleTyCon { data_con = con, tup_sort = sort }, algTcFields = emptyDFsEnv, algTcParent = parent, algTcGadtSyntax = False } -- | Makes a tycon suitable for use during type-checking. -- The only real need for this is for printing error messages during -- a recursive type/class type-checking knot. It has a kind because -- TcErrors sometimes calls typeKind. -- See also Note [Kind checking recursive type and class declarations] -- in TcTyClsDecls. mkTcTyCon :: Name -> [TyConBinder] -> Kind -- ^ /result/ kind only -> Bool -- ^ Can this be unsaturated? -> [TyVar] -- ^ Scoped type variables, see Note [TcTyCon] -> TyCon mkTcTyCon name binders res_kind unsat scoped_tvs = TcTyCon { tyConUnique = getUnique name , tyConName = name , tyConTyVars = binderVars binders , tyConBinders = binders , tyConResKind = res_kind , tyConKind = mkTyConKind binders res_kind , tyConUnsat = unsat , tyConArity = length binders , tcTyConScopedTyVars = scoped_tvs } -- | Create an unlifted primitive 'TyCon', such as @Int#@ mkPrimTyCon :: Name -> [TyConBinder] -> Kind -- ^ /result/ kind -> [Role] -> TyCon mkPrimTyCon name binders res_kind roles = mkPrimTyCon' name binders res_kind roles True (Just $ mkPrelTyConRepName name) -- | Kind constructors mkKindTyCon :: Name -> [TyConBinder] -> Kind -- ^ /result/ kind -> [Role] -> Name -> TyCon mkKindTyCon name binders res_kind roles rep_nm = tc where tc = mkPrimTyCon' name binders res_kind roles False (Just rep_nm) -- | Create a lifted primitive 'TyCon' such as @RealWorld@ mkLiftedPrimTyCon :: Name -> [TyConBinder] -> Kind -- ^ /result/ kind -> [Role] -> TyCon mkLiftedPrimTyCon name binders res_kind roles = mkPrimTyCon' name binders res_kind roles False (Just rep_nm) where rep_nm = mkPrelTyConRepName name mkPrimTyCon' :: Name -> [TyConBinder] -> Kind -- ^ /result/ kind -> [Role] -> Bool -> Maybe TyConRepName -> TyCon mkPrimTyCon' name binders res_kind roles is_unlifted rep_nm = PrimTyCon { tyConName = name, tyConUnique = nameUnique name, tyConBinders = binders, tyConResKind = res_kind, tyConKind = mkTyConKind binders res_kind, tyConArity = length roles, tcRoles = roles, isUnlifted = is_unlifted, primRepName = rep_nm } -- | Create a type synonym 'TyCon' mkSynonymTyCon :: Name -> [TyConBinder] -> Kind -- ^ /result/ kind -> [Role] -> Type -> TyCon mkSynonymTyCon name binders res_kind roles rhs = SynonymTyCon { tyConName = name, tyConUnique = nameUnique name, tyConBinders = binders, tyConResKind = res_kind, tyConKind = mkTyConKind binders res_kind, tyConArity = length binders, tyConTyVars = binderVars binders, tcRoles = roles, synTcRhs = rhs } -- | Create a type family 'TyCon' mkFamilyTyCon :: Name -> [TyConBinder] -> Kind -- ^ /result/ kind -> Maybe Name -> FamTyConFlav -> Maybe Class -> Injectivity -> TyCon mkFamilyTyCon name binders res_kind resVar flav parent inj = FamilyTyCon { tyConUnique = nameUnique name , tyConName = name , tyConBinders = binders , tyConResKind = res_kind , tyConKind = mkTyConKind binders res_kind , tyConArity = length binders , tyConTyVars = binderVars binders , famTcResVar = resVar , famTcFlav = flav , famTcParent = parent , famTcInj = inj } -- | Create a promoted data constructor 'TyCon' -- Somewhat dodgily, we give it the same Name -- as the data constructor itself; when we pretty-print -- the TyCon we add a quote; see the Outputable TyCon instance mkPromotedDataCon :: DataCon -> Name -> TyConRepName -> [TyConBinder] -> Kind -> [Role] -> RuntimeRepInfo -> TyCon mkPromotedDataCon con name rep_name binders res_kind roles rep_info = PromotedDataCon { tyConUnique = nameUnique name, tyConName = name, tyConArity = length roles, tcRoles = roles, tyConBinders = binders, tyConResKind = res_kind, tyConKind = mkTyConKind binders res_kind, dataCon = con, tcRepName = rep_name, promDcRepInfo = rep_info } isFunTyCon :: TyCon -> Bool isFunTyCon (FunTyCon {}) = True isFunTyCon _ = False -- | Test if the 'TyCon' is algebraic but abstract (invisible data constructors) isAbstractTyCon :: TyCon -> Bool isAbstractTyCon (AlgTyCon { algTcRhs = AbstractTyCon {} }) = True isAbstractTyCon _ = False -- | Make an fake, abstract 'TyCon' from an existing one. -- Used when recovering from errors makeTyConAbstract :: TyCon -> TyCon makeTyConAbstract tc = mkTcTyCon (tyConName tc) (tyConBinders tc) (tyConResKind tc) (mightBeUnsaturatedTyCon tc) [{- no scoped vars -}] -- | Does this 'TyCon' represent something that cannot be defined in Haskell? isPrimTyCon :: TyCon -> Bool isPrimTyCon (PrimTyCon {}) = True isPrimTyCon _ = False -- | Is this 'TyCon' unlifted (i.e. cannot contain bottom)? Note that this can -- only be true for primitive and unboxed-tuple 'TyCon's isUnliftedTyCon :: TyCon -> Bool isUnliftedTyCon (PrimTyCon {isUnlifted = is_unlifted}) = is_unlifted isUnliftedTyCon (AlgTyCon { algTcRhs = rhs } ) | TupleTyCon { tup_sort = sort } <- rhs = not (isBoxed (tupleSortBoxity sort)) isUnliftedTyCon _ = False -- | Returns @True@ if the supplied 'TyCon' resulted from either a -- @data@ or @newtype@ declaration isAlgTyCon :: TyCon -> Bool isAlgTyCon (AlgTyCon {}) = True isAlgTyCon _ = False -- | Returns @True@ for vanilla AlgTyCons -- that is, those created -- with a @data@ or @newtype@ declaration. isVanillaAlgTyCon :: TyCon -> Bool isVanillaAlgTyCon (AlgTyCon { algTcParent = VanillaAlgTyCon _ }) = True isVanillaAlgTyCon _ = False isDataTyCon :: TyCon -> Bool -- ^ Returns @True@ for data types that are /definitely/ represented by -- heap-allocated constructors. These are scrutinised by Core-level -- @case@ expressions, and they get info tables allocated for them. -- -- Generally, the function will be true for all @data@ types and false -- for @newtype@s, unboxed tuples and type family 'TyCon's. But it is -- not guaranteed to return @True@ in all cases that it could. -- -- NB: for a data type family, only the /instance/ 'TyCon's -- get an info table. The family declaration 'TyCon' does not isDataTyCon (AlgTyCon {algTcRhs = rhs}) = case rhs of TupleTyCon { tup_sort = sort } -> isBoxed (tupleSortBoxity sort) DataTyCon {} -> True NewTyCon {} -> False AbstractTyCon {} -> False -- We don't know, so return False isDataTyCon _ = False -- | 'isInjectiveTyCon' is true of 'TyCon's for which this property holds -- (where X is the role passed in): -- If (T a1 b1 c1) ~X (T a2 b2 c2), then (a1 ~X1 a2), (b1 ~X2 b2), and (c1 ~X3 c2) -- (where X1, X2, and X3, are the roles given by tyConRolesX tc X) -- See also Note [Decomposing equality] in TcCanonical isInjectiveTyCon :: TyCon -> Role -> Bool isInjectiveTyCon _ Phantom = False isInjectiveTyCon (FunTyCon {}) _ = True isInjectiveTyCon (AlgTyCon {}) Nominal = True isInjectiveTyCon (AlgTyCon {algTcRhs = rhs}) Representational = isGenInjAlgRhs rhs isInjectiveTyCon (SynonymTyCon {}) _ = False isInjectiveTyCon (FamilyTyCon { famTcFlav = DataFamilyTyCon _ }) Nominal = True isInjectiveTyCon (FamilyTyCon { famTcInj = Injective inj }) _ = and inj isInjectiveTyCon (FamilyTyCon {}) _ = False isInjectiveTyCon (PrimTyCon {}) _ = True isInjectiveTyCon (PromotedDataCon {}) _ = True isInjectiveTyCon tc@(TcTyCon {}) _ = pprPanic "isInjectiveTyCon sees a TcTyCon" (ppr tc) -- | 'isGenerativeTyCon' is true of 'TyCon's for which this property holds -- (where X is the role passed in): -- If (T tys ~X t), then (t's head ~X T). -- See also Note [Decomposing equality] in TcCanonical isGenerativeTyCon :: TyCon -> Role -> Bool isGenerativeTyCon (FamilyTyCon { famTcFlav = DataFamilyTyCon _ }) Nominal = True isGenerativeTyCon (FamilyTyCon {}) _ = False -- in all other cases, injectivity implies generativitiy isGenerativeTyCon tc r = isInjectiveTyCon tc r -- | Is this an 'AlgTyConRhs' of a 'TyCon' that is generative and injective -- with respect to representational equality? isGenInjAlgRhs :: AlgTyConRhs -> Bool isGenInjAlgRhs (TupleTyCon {}) = True isGenInjAlgRhs (DataTyCon {}) = True isGenInjAlgRhs (AbstractTyCon distinct) = distinct isGenInjAlgRhs (NewTyCon {}) = False -- | Is this 'TyCon' that for a @newtype@ isNewTyCon :: TyCon -> Bool isNewTyCon (AlgTyCon {algTcRhs = NewTyCon {}}) = True isNewTyCon _ = False -- | Take a 'TyCon' apart into the 'TyVar's it scopes over, the 'Type' it expands -- into, and (possibly) a coercion from the representation type to the @newtype@. -- Returns @Nothing@ if this is not possible. unwrapNewTyCon_maybe :: TyCon -> Maybe ([TyVar], Type, CoAxiom Unbranched) unwrapNewTyCon_maybe (AlgTyCon { tyConTyVars = tvs, algTcRhs = NewTyCon { nt_co = co, nt_rhs = rhs }}) = Just (tvs, rhs, co) unwrapNewTyCon_maybe _ = Nothing unwrapNewTyConEtad_maybe :: TyCon -> Maybe ([TyVar], Type, CoAxiom Unbranched) unwrapNewTyConEtad_maybe (AlgTyCon { algTcRhs = NewTyCon { nt_co = co, nt_etad_rhs = (tvs,rhs) }}) = Just (tvs, rhs, co) unwrapNewTyConEtad_maybe _ = Nothing isProductTyCon :: TyCon -> Bool -- True of datatypes or newtypes that have -- one, non-existential, data constructor -- See Note [Product types] isProductTyCon tc@(AlgTyCon {}) = case algTcRhs tc of TupleTyCon {} -> True DataTyCon{ data_cons = [data_con] } -> null (dataConExTyVars data_con) NewTyCon {} -> True _ -> False isProductTyCon _ = False isDataProductTyCon_maybe :: TyCon -> Maybe DataCon -- True of datatypes (not newtypes) with -- one, vanilla, data constructor -- See Note [Product types] isDataProductTyCon_maybe (AlgTyCon { algTcRhs = rhs }) = case rhs of DataTyCon { data_cons = [con] } | null (dataConExTyVars con) -- non-existential -> Just con TupleTyCon { data_con = con } -> Just con _ -> Nothing isDataProductTyCon_maybe _ = Nothing {- Note [Product types] ~~~~~~~~~~~~~~~~~~~~~~~ A product type is * A data type (not a newtype) * With one, boxed data constructor * That binds no existential type variables The main point is that product types are amenable to unboxing for * Strict function calls; we can transform f (D a b) = e to fw a b = e via the worker/wrapper transformation. (Question: couldn't this work for existentials too?) * CPR for function results; we can transform f x y = let ... in D a b to fw x y = let ... in (# a, b #) Note that the data constructor /can/ have evidence arguments: equality constraints, type classes etc. So it can be GADT. These evidence arguments are simply value arguments, and should not get in the way. -} -- | Is this a 'TyCon' representing a regular H98 type synonym (@type@)? isTypeSynonymTyCon :: TyCon -> Bool isTypeSynonymTyCon (SynonymTyCon {}) = True isTypeSynonymTyCon _ = False -- As for newtypes, it is in some contexts important to distinguish between -- closed synonyms and synonym families, as synonym families have no unique -- right hand side to which a synonym family application can expand. -- -- | True iff we can decompose (T a b c) into ((T a b) c) -- I.e. is it injective and generative w.r.t nominal equality? -- That is, if (T a b) ~N d e f, is it always the case that -- (T ~N d), (a ~N e) and (b ~N f)? -- Specifically NOT true of synonyms (open and otherwise) -- -- It'd be unusual to call mightBeUnsaturatedTyCon on a regular H98 -- type synonym, because you should probably have expanded it first -- But regardless, it's not decomposable mightBeUnsaturatedTyCon :: TyCon -> Bool mightBeUnsaturatedTyCon (SynonymTyCon {}) = False mightBeUnsaturatedTyCon (FamilyTyCon { famTcFlav = flav}) = isDataFamFlav flav mightBeUnsaturatedTyCon (TcTyCon { tyConUnsat = unsat }) = unsat mightBeUnsaturatedTyCon _other = True -- | Is this an algebraic 'TyCon' declared with the GADT syntax? isGadtSyntaxTyCon :: TyCon -> Bool isGadtSyntaxTyCon (AlgTyCon { algTcGadtSyntax = res }) = res isGadtSyntaxTyCon _ = False -- | Is this an algebraic 'TyCon' which is just an enumeration of values? isEnumerationTyCon :: TyCon -> Bool -- See Note [Enumeration types] in TyCon isEnumerationTyCon (AlgTyCon { tyConArity = arity, algTcRhs = rhs }) = case rhs of DataTyCon { is_enum = res } -> res TupleTyCon {} -> arity == 0 _ -> False isEnumerationTyCon _ = False -- | Is this a 'TyCon', synonym or otherwise, that defines a family? isFamilyTyCon :: TyCon -> Bool isFamilyTyCon (FamilyTyCon {}) = True isFamilyTyCon _ = False -- | Is this a 'TyCon', synonym or otherwise, that defines a family with -- instances? isOpenFamilyTyCon :: TyCon -> Bool isOpenFamilyTyCon (FamilyTyCon {famTcFlav = flav }) | OpenSynFamilyTyCon <- flav = True | DataFamilyTyCon {} <- flav = True isOpenFamilyTyCon _ = False -- | Is this a synonym 'TyCon' that can have may have further instances appear? isTypeFamilyTyCon :: TyCon -> Bool isTypeFamilyTyCon (FamilyTyCon { famTcFlav = flav }) = not (isDataFamFlav flav) isTypeFamilyTyCon _ = False -- | Is this a synonym 'TyCon' that can have may have further instances appear? isDataFamilyTyCon :: TyCon -> Bool isDataFamilyTyCon (FamilyTyCon { famTcFlav = flav }) = isDataFamFlav flav isDataFamilyTyCon _ = False -- | Is this an open type family TyCon? isOpenTypeFamilyTyCon :: TyCon -> Bool isOpenTypeFamilyTyCon (FamilyTyCon {famTcFlav = OpenSynFamilyTyCon }) = True isOpenTypeFamilyTyCon _ = False -- | Is this a non-empty closed type family? Returns 'Nothing' for -- abstract or empty closed families. isClosedSynFamilyTyConWithAxiom_maybe :: TyCon -> Maybe (CoAxiom Branched) isClosedSynFamilyTyConWithAxiom_maybe (FamilyTyCon {famTcFlav = ClosedSynFamilyTyCon mb}) = mb isClosedSynFamilyTyConWithAxiom_maybe _ = Nothing -- | Try to read the injectivity information from a FamilyTyCon. -- For every other TyCon this function panics. familyTyConInjectivityInfo :: TyCon -> Injectivity familyTyConInjectivityInfo (FamilyTyCon { famTcInj = inj }) = inj familyTyConInjectivityInfo _ = panic "familyTyConInjectivityInfo" isBuiltInSynFamTyCon_maybe :: TyCon -> Maybe BuiltInSynFamily isBuiltInSynFamTyCon_maybe (FamilyTyCon {famTcFlav = BuiltInSynFamTyCon ops }) = Just ops isBuiltInSynFamTyCon_maybe _ = Nothing isDataFamFlav :: FamTyConFlav -> Bool isDataFamFlav (DataFamilyTyCon {}) = True -- Data family isDataFamFlav _ = False -- Type synonym family -- | Are we able to extract information 'TyVar' to class argument list -- mapping from a given 'TyCon'? isTyConAssoc :: TyCon -> Bool isTyConAssoc tc = isJust (tyConAssoc_maybe tc) tyConAssoc_maybe :: TyCon -> Maybe Class tyConAssoc_maybe (FamilyTyCon { famTcParent = mb_cls }) = mb_cls tyConAssoc_maybe _ = Nothing -- The unit tycon didn't used to be classed as a tuple tycon -- but I thought that was silly so I've undone it -- If it can't be for some reason, it should be a AlgTyCon isTupleTyCon :: TyCon -> Bool -- ^ Does this 'TyCon' represent a tuple? -- -- NB: when compiling @Data.Tuple@, the tycons won't reply @True@ to -- 'isTupleTyCon', because they are built as 'AlgTyCons'. However they -- get spat into the interface file as tuple tycons, so I don't think -- it matters. isTupleTyCon (AlgTyCon { algTcRhs = TupleTyCon {} }) = True isTupleTyCon _ = False tyConTuple_maybe :: TyCon -> Maybe TupleSort tyConTuple_maybe (AlgTyCon { algTcRhs = rhs }) | TupleTyCon { tup_sort = sort} <- rhs = Just sort tyConTuple_maybe _ = Nothing -- | Is this the 'TyCon' for an unboxed tuple? isUnboxedTupleTyCon :: TyCon -> Bool isUnboxedTupleTyCon (AlgTyCon { algTcRhs = rhs }) | TupleTyCon { tup_sort = sort } <- rhs = not (isBoxed (tupleSortBoxity sort)) isUnboxedTupleTyCon _ = False -- | Is this the 'TyCon' for a boxed tuple? isBoxedTupleTyCon :: TyCon -> Bool isBoxedTupleTyCon (AlgTyCon { algTcRhs = rhs }) | TupleTyCon { tup_sort = sort } <- rhs = isBoxed (tupleSortBoxity sort) isBoxedTupleTyCon _ = False -- | Is this a PromotedDataCon? isPromotedDataCon :: TyCon -> Bool isPromotedDataCon (PromotedDataCon {}) = True isPromotedDataCon _ = False -- | Retrieves the promoted DataCon if this is a PromotedDataCon; isPromotedDataCon_maybe :: TyCon -> Maybe DataCon isPromotedDataCon_maybe (PromotedDataCon { dataCon = dc }) = Just dc isPromotedDataCon_maybe _ = Nothing -- | Is this tycon really meant for use at the kind level? That is, -- should it be permitted without -XDataKinds? isKindTyCon :: TyCon -> Bool isKindTyCon tc = getUnique tc `elementOfUniqSet` kindTyConKeys -- | These TyCons should be allowed at the kind level, even without -- -XDataKinds. kindTyConKeys :: UniqSet Unique kindTyConKeys = unionManyUniqSets ( mkUniqSet [ liftedTypeKindTyConKey, starKindTyConKey, unicodeStarKindTyConKey , constraintKindTyConKey, tYPETyConKey ] : map (mkUniqSet . tycon_with_datacons) [ runtimeRepTyCon , vecCountTyCon, vecElemTyCon ] ) where tycon_with_datacons tc = getUnique tc : map getUnique (tyConDataCons tc) isLiftedTypeKindTyConName :: Name -> Bool isLiftedTypeKindTyConName = (`hasKey` liftedTypeKindTyConKey) <||> (`hasKey` starKindTyConKey) <||> (`hasKey` unicodeStarKindTyConKey) -- | Identifies implicit tycons that, in particular, do not go into interface -- files (because they are implicitly reconstructed when the interface is -- read). -- -- Note that: -- -- * Associated families are implicit, as they are re-constructed from -- the class declaration in which they reside, and -- -- * Family instances are /not/ implicit as they represent the instance body -- (similar to a @dfun@ does that for a class instance). -- -- * Tuples are implicit iff they have a wired-in name -- (namely: boxed and unboxed tupeles are wired-in and implicit, -- but constraint tuples are not) isImplicitTyCon :: TyCon -> Bool isImplicitTyCon (FunTyCon {}) = True isImplicitTyCon (PrimTyCon {}) = True isImplicitTyCon (PromotedDataCon {}) = True isImplicitTyCon (AlgTyCon { algTcRhs = rhs, tyConName = name }) | TupleTyCon {} <- rhs = isWiredInName name | otherwise = False isImplicitTyCon (FamilyTyCon { famTcParent = parent }) = isJust parent isImplicitTyCon (SynonymTyCon {}) = False isImplicitTyCon tc@(TcTyCon {}) = pprPanic "isImplicitTyCon sees a TcTyCon" (ppr tc) tyConCType_maybe :: TyCon -> Maybe CType tyConCType_maybe tc@(AlgTyCon {}) = tyConCType tc tyConCType_maybe _ = Nothing -- | Is this a TcTyCon? (That is, one only used during type-checking?) isTcTyCon :: TyCon -> Bool isTcTyCon (TcTyCon {}) = True isTcTyCon _ = False {- ----------------------------------------------- -- Expand type-constructor applications ----------------------------------------------- -} expandSynTyCon_maybe :: TyCon -> [tyco] -- ^ Arguments to 'TyCon' -> Maybe ([(TyVar,tyco)], Type, [tyco]) -- ^ Returns a 'TyVar' substitution, the body -- type of the synonym (not yet substituted) -- and any arguments remaining from the -- application -- ^ Expand a type synonym application, if any expandSynTyCon_maybe tc tys | SynonymTyCon { tyConTyVars = tvs, synTcRhs = rhs, tyConArity = arity } <- tc = case arity `compare` length tys of LT -> Just (tvs `zip` tys, rhs, drop arity tys) EQ -> Just (tvs `zip` tys, rhs, []) GT -> Nothing | otherwise = Nothing ---------------- -- | Check if the tycon actually refers to a proper `data` or `newtype` -- with user defined constructors rather than one from a class or other -- construction. isTyConWithSrcDataCons :: TyCon -> Bool isTyConWithSrcDataCons (AlgTyCon { algTcRhs = rhs, algTcParent = parent }) = case rhs of DataTyCon {} -> isSrcParent NewTyCon {} -> isSrcParent TupleTyCon {} -> isSrcParent _ -> False where isSrcParent = isNoParent parent isTyConWithSrcDataCons _ = False -- | As 'tyConDataCons_maybe', but returns the empty list of constructors if no -- constructors could be found tyConDataCons :: TyCon -> [DataCon] -- It's convenient for tyConDataCons to return the -- empty list for type synonyms etc tyConDataCons tycon = tyConDataCons_maybe tycon `orElse` [] -- | Determine the 'DataCon's originating from the given 'TyCon', if the 'TyCon' -- is the sort that can have any constructors (note: this does not include -- abstract algebraic types) tyConDataCons_maybe :: TyCon -> Maybe [DataCon] tyConDataCons_maybe (AlgTyCon {algTcRhs = rhs}) = case rhs of DataTyCon { data_cons = cons } -> Just cons NewTyCon { data_con = con } -> Just [con] TupleTyCon { data_con = con } -> Just [con] _ -> Nothing tyConDataCons_maybe _ = Nothing -- | If the given 'TyCon' has a /single/ data constructor, i.e. it is a @data@ -- type with one alternative, a tuple type or a @newtype@ then that constructor -- is returned. If the 'TyCon' has more than one constructor, or represents a -- primitive or function type constructor then @Nothing@ is returned. In any -- other case, the function panics tyConSingleDataCon_maybe :: TyCon -> Maybe DataCon tyConSingleDataCon_maybe (AlgTyCon { algTcRhs = rhs }) = case rhs of DataTyCon { data_cons = [c] } -> Just c TupleTyCon { data_con = c } -> Just c NewTyCon { data_con = c } -> Just c _ -> Nothing tyConSingleDataCon_maybe _ = Nothing tyConSingleDataCon :: TyCon -> DataCon tyConSingleDataCon tc = case tyConSingleDataCon_maybe tc of Just c -> c Nothing -> pprPanic "tyConDataCon" (ppr tc) tyConSingleAlgDataCon_maybe :: TyCon -> Maybe DataCon -- Returns (Just con) for single-constructor -- *algebraic* data types *not* newtypes tyConSingleAlgDataCon_maybe (AlgTyCon { algTcRhs = rhs }) = case rhs of DataTyCon { data_cons = [c] } -> Just c TupleTyCon { data_con = c } -> Just c _ -> Nothing tyConSingleAlgDataCon_maybe _ = Nothing -- | Determine the number of value constructors a 'TyCon' has. Panics if the -- 'TyCon' is not algebraic or a tuple tyConFamilySize :: TyCon -> Int tyConFamilySize tc@(AlgTyCon { algTcRhs = rhs }) = case rhs of DataTyCon { data_cons = cons } -> length cons NewTyCon {} -> 1 TupleTyCon {} -> 1 _ -> pprPanic "tyConFamilySize 1" (ppr tc) tyConFamilySize tc = pprPanic "tyConFamilySize 2" (ppr tc) -- | Extract an 'AlgTyConRhs' with information about data constructors from an -- algebraic or tuple 'TyCon'. Panics for any other sort of 'TyCon' algTyConRhs :: TyCon -> AlgTyConRhs algTyConRhs (AlgTyCon {algTcRhs = rhs}) = rhs algTyConRhs other = pprPanic "algTyConRhs" (ppr other) -- | Extract type variable naming the result of injective type family tyConFamilyResVar_maybe :: TyCon -> Maybe Name tyConFamilyResVar_maybe (FamilyTyCon {famTcResVar = res}) = res tyConFamilyResVar_maybe _ = Nothing -- | Get the list of roles for the type parameters of a TyCon tyConRoles :: TyCon -> [Role] -- See also Note [TyCon Role signatures] tyConRoles tc = case tc of { FunTyCon {} -> const_role Representational ; AlgTyCon { tcRoles = roles } -> roles ; SynonymTyCon { tcRoles = roles } -> roles ; FamilyTyCon {} -> const_role Nominal ; PrimTyCon { tcRoles = roles } -> roles ; PromotedDataCon { tcRoles = roles } -> roles ; TcTyCon {} -> pprPanic "tyConRoles sees a TcTyCon" (ppr tc) } where const_role r = replicate (tyConArity tc) r -- | Extract the bound type variables and type expansion of a type synonym -- 'TyCon'. Panics if the 'TyCon' is not a synonym newTyConRhs :: TyCon -> ([TyVar], Type) newTyConRhs (AlgTyCon {tyConTyVars = tvs, algTcRhs = NewTyCon { nt_rhs = rhs }}) = (tvs, rhs) newTyConRhs tycon = pprPanic "newTyConRhs" (ppr tycon) -- | The number of type parameters that need to be passed to a newtype to -- resolve it. May be less than in the definition if it can be eta-contracted. newTyConEtadArity :: TyCon -> Int newTyConEtadArity (AlgTyCon {algTcRhs = NewTyCon { nt_etad_rhs = tvs_rhs }}) = length (fst tvs_rhs) newTyConEtadArity tycon = pprPanic "newTyConEtadArity" (ppr tycon) -- | Extract the bound type variables and type expansion of an eta-contracted -- type synonym 'TyCon'. Panics if the 'TyCon' is not a synonym newTyConEtadRhs :: TyCon -> ([TyVar], Type) newTyConEtadRhs (AlgTyCon {algTcRhs = NewTyCon { nt_etad_rhs = tvs_rhs }}) = tvs_rhs newTyConEtadRhs tycon = pprPanic "newTyConEtadRhs" (ppr tycon) -- | Extracts the @newtype@ coercion from such a 'TyCon', which can be used to -- construct something with the @newtype@s type from its representation type -- (right hand side). If the supplied 'TyCon' is not a @newtype@, returns -- @Nothing@ newTyConCo_maybe :: TyCon -> Maybe (CoAxiom Unbranched) newTyConCo_maybe (AlgTyCon {algTcRhs = NewTyCon { nt_co = co }}) = Just co newTyConCo_maybe _ = Nothing newTyConCo :: TyCon -> CoAxiom Unbranched newTyConCo tc = case newTyConCo_maybe tc of Just co -> co Nothing -> pprPanic "newTyConCo" (ppr tc) newTyConDataCon_maybe :: TyCon -> Maybe DataCon newTyConDataCon_maybe (AlgTyCon {algTcRhs = NewTyCon { data_con = con }}) = Just con newTyConDataCon_maybe _ = Nothing -- | Find the \"stupid theta\" of the 'TyCon'. A \"stupid theta\" is the context -- to the left of an algebraic type declaration, e.g. @Eq a@ in the declaration -- @data Eq a => T a ...@ tyConStupidTheta :: TyCon -> [PredType] tyConStupidTheta (AlgTyCon {algTcStupidTheta = stupid}) = stupid tyConStupidTheta tycon = pprPanic "tyConStupidTheta" (ppr tycon) -- | Extract the 'TyVar's bound by a vanilla type synonym -- and the corresponding (unsubstituted) right hand side. synTyConDefn_maybe :: TyCon -> Maybe ([TyVar], Type) synTyConDefn_maybe (SynonymTyCon {tyConTyVars = tyvars, synTcRhs = ty}) = Just (tyvars, ty) synTyConDefn_maybe _ = Nothing -- | Extract the information pertaining to the right hand side of a type synonym -- (@type@) declaration. synTyConRhs_maybe :: TyCon -> Maybe Type synTyConRhs_maybe (SynonymTyCon {synTcRhs = rhs}) = Just rhs synTyConRhs_maybe _ = Nothing -- | Extract the flavour of a type family (with all the extra information that -- it carries) famTyConFlav_maybe :: TyCon -> Maybe FamTyConFlav famTyConFlav_maybe (FamilyTyCon {famTcFlav = flav}) = Just flav famTyConFlav_maybe _ = Nothing -- | Is this 'TyCon' that for a class instance? isClassTyCon :: TyCon -> Bool isClassTyCon (AlgTyCon {algTcParent = ClassTyCon {}}) = True isClassTyCon _ = False -- | If this 'TyCon' is that for a class instance, return the class it is for. -- Otherwise returns @Nothing@ tyConClass_maybe :: TyCon -> Maybe Class tyConClass_maybe (AlgTyCon {algTcParent = ClassTyCon clas _}) = Just clas tyConClass_maybe _ = Nothing -- | Return the associated types of the 'TyCon', if any tyConATs :: TyCon -> [TyCon] tyConATs (AlgTyCon {algTcParent = ClassTyCon clas _}) = classATs clas tyConATs _ = [] ---------------------------------------------------------------------------- -- | Is this 'TyCon' that for a data family instance? isFamInstTyCon :: TyCon -> Bool isFamInstTyCon (AlgTyCon {algTcParent = DataFamInstTyCon {} }) = True isFamInstTyCon _ = False tyConFamInstSig_maybe :: TyCon -> Maybe (TyCon, [Type], CoAxiom Unbranched) tyConFamInstSig_maybe (AlgTyCon {algTcParent = DataFamInstTyCon ax f ts }) = Just (f, ts, ax) tyConFamInstSig_maybe _ = Nothing -- | If this 'TyCon' is that of a data family instance, return the family in question -- and the instance types. Otherwise, return @Nothing@ tyConFamInst_maybe :: TyCon -> Maybe (TyCon, [Type]) tyConFamInst_maybe (AlgTyCon {algTcParent = DataFamInstTyCon _ f ts }) = Just (f, ts) tyConFamInst_maybe _ = Nothing -- | If this 'TyCon' is that of a data family instance, return a 'TyCon' which -- represents a coercion identifying the representation type with the type -- instance family. Otherwise, return @Nothing@ tyConFamilyCoercion_maybe :: TyCon -> Maybe (CoAxiom Unbranched) tyConFamilyCoercion_maybe (AlgTyCon {algTcParent = DataFamInstTyCon ax _ _ }) = Just ax tyConFamilyCoercion_maybe _ = Nothing -- | Extract any 'RuntimeRepInfo' from this TyCon tyConRuntimeRepInfo :: TyCon -> RuntimeRepInfo tyConRuntimeRepInfo (PromotedDataCon { promDcRepInfo = rri }) = rri tyConRuntimeRepInfo _ = NoRRI -- could panic in that second case. But Douglas Adams told me not to. {- ************************************************************************ * * \subsection[TyCon-instances]{Instance declarations for @TyCon@} * * ************************************************************************ @TyCon@s are compared by comparing their @Unique@s. -} instance Eq TyCon where a == b = getUnique a == getUnique b a /= b = getUnique a /= getUnique b instance Uniquable TyCon where getUnique tc = tyConUnique tc instance Outputable TyCon where -- At the moment a promoted TyCon has the same Name as its -- corresponding TyCon, so we add the quote to distinguish it here ppr tc = pprPromotionQuote tc <> ppr (tyConName tc) tyConFlavour :: TyCon -> String tyConFlavour (AlgTyCon { algTcParent = parent, algTcRhs = rhs }) | ClassTyCon _ _ <- parent = "class" | otherwise = case rhs of TupleTyCon { tup_sort = sort } | isBoxed (tupleSortBoxity sort) -> "tuple" | otherwise -> "unboxed tuple" DataTyCon {} -> "data type" NewTyCon {} -> "newtype" AbstractTyCon {} -> "abstract type" tyConFlavour (FamilyTyCon { famTcFlav = flav }) | isDataFamFlav flav = "data family" | otherwise = "type family" tyConFlavour (SynonymTyCon {}) = "type synonym" tyConFlavour (FunTyCon {}) = "built-in type" tyConFlavour (PrimTyCon {}) = "built-in type" tyConFlavour (PromotedDataCon {}) = "promoted data constructor" tyConFlavour tc@(TcTyCon {}) = pprPanic "tyConFlavour sees a TcTyCon" (ppr tc) pprPromotionQuote :: TyCon -> SDoc -- Promoted data constructors already have a tick in their OccName pprPromotionQuote tc = case tc of PromotedDataCon {} -> char '\'' -- Always quote promoted DataCons in types _ -> empty instance NamedThing TyCon where getName = tyConName instance Data.Data TyCon where -- don't traverse? toConstr _ = abstractConstr "TyCon" gunfold _ _ = error "gunfold" dataTypeOf _ = mkNoRepType "TyCon" instance Binary Injectivity where put_ bh NotInjective = putByte bh 0 put_ bh (Injective xs) = putByte bh 1 >> put_ bh xs get bh = do { h <- getByte bh ; case h of 0 -> return NotInjective _ -> do { xs <- get bh ; return (Injective xs) } } {- ************************************************************************ * * Walking over recursive TyCons * * ************************************************************************ Note [Expanding newtypes and products] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When expanding a type to expose a data-type constructor, we need to be careful about newtypes, lest we fall into an infinite loop. Here are the key examples: newtype Id x = MkId x newtype Fix f = MkFix (f (Fix f)) newtype T = MkT (T -> T) Type Expansion -------------------------- T T -> T Fix Maybe Maybe (Fix Maybe) Id (Id Int) Int Fix Id NO NO NO Notice that * We can expand T, even though it's recursive. * We can expand Id (Id Int), even though the Id shows up twice at the outer level, because Id is non-recursive So, when expanding, we keep track of when we've seen a recursive newtype at outermost level; and bale out if we see it again. We sometimes want to do the same for product types, so that the strictness analyser doesn't unbox infinitely deeply. More precisely, we keep a *count* of how many times we've seen it. This is to account for data instance T (a,b) = MkT (T a) (T b) Then (Trac #10482) if we have a type like T (Int,(Int,(Int,(Int,Int)))) we can still unbox deeply enough during strictness analysis. We have to treat T as potentially recursive, but it's still good to be able to unwrap multiple layers. The function that manages all this is checkRecTc. -} data RecTcChecker = RC !Int (NameEnv Int) -- The upper bound, and the number of times -- we have encountered each TyCon initRecTc :: RecTcChecker -- Intialise with a fixed max bound of 100 -- We should probably have a flag for this initRecTc = RC 100 emptyNameEnv checkRecTc :: RecTcChecker -> TyCon -> Maybe RecTcChecker -- Nothing => Recursion detected -- Just rec_tcs => Keep going checkRecTc (RC bound rec_nts) tc = case lookupNameEnv rec_nts tc_name of Just n | n >= bound -> Nothing | otherwise -> Just (RC bound (extendNameEnv rec_nts tc_name (n+1))) Nothing -> Just (RC bound (extendNameEnv rec_nts tc_name 1)) where tc_name = tyConName tc
vTurbine/ghc
compiler/types/TyCon.hs
bsd-3-clause
89,529
2
16
25,435
10,609
5,995
4,614
943
7
{-# LANGUAGE TypeOperators #-} module Main where import Control.Applicative ((<*>)) import Data.OI hiding (openFile) import System.IO (IOMode (..), Handle) import qualified System.IO as IO import Prelude hiding (readFile, writeFile) main :: IO () main = runInteraction pmain pmain :: (([String],Either ((Handle, String), [(Handle, String)]) [(Handle, String)]), (Handle, ())) :-> () pmain = args |/| ((choiceOI (lines . readFile "files2" |/| zipWithOI readFile) . zipWithOI readFile) <*> null) |/| writeFile "output2.txt" . concatMap textproc textproc :: String -> String textproc = id readFile :: FilePath -> (Handle, String) :-> String readFile f = openFile f ReadMode |/| hGetContents writeFile :: FilePath -> String -> (Handle, ()) :-> () writeFile f cs = openFile f WriteMode |/| flip hPutStr cs openFile :: FilePath -> IOMode -> Handle :-> Handle openFile = (iooi .) . IO.openFile hGetContents :: Handle -> String :-> String hGetContents = iooi . IO.hGetContents hPutStr :: Handle -> String -> () :-> () hPutStr = (iooi .) . IO.hPutStr
nobsun/oi
sample/cats2.hs
bsd-3-clause
1,078
0
16
196
405
229
176
-1
-1
{-# LANGUAGE CPP #-} {-# OPTIONS_GHC -fno-warn-orphans -fno-warn-incomplete-patterns -fno-warn-deprecations -fno-warn-unused-binds #-} --FIXME module UnitTests.Distribution.Version (versionTests) where import Distribution.Version import Distribution.Text import Text.PrettyPrint as Disp (text, render, parens, hcat ,punctuate, int, char, (<>), (<+>)) import Test.Tasty import Test.Tasty.QuickCheck import qualified Test.Laws as Laws #if !MIN_VERSION_QuickCheck(2,9,0) import Test.QuickCheck.Utils #endif import Control.Monad (liftM, liftM2) import Data.Maybe (isJust, fromJust) import Data.List (sort, sortBy, nub) import Data.Ord (comparing) versionTests :: [TestTree] versionTests = zipWith (\n p -> testProperty ("Range Property " ++ show n) p) [1::Int ..] -- properties to validate the test framework [ property prop_nonNull , property prop_gen_intervals1 , property prop_gen_intervals2 --, property prop_equivalentVersionRange --FIXME: runs out of test cases , property prop_intermediateVersion -- the basic syntactic version range functions , property prop_anyVersion , property prop_noVersion , property prop_thisVersion , property prop_notThisVersion , property prop_laterVersion , property prop_orLaterVersion , property prop_earlierVersion , property prop_orEarlierVersion , property prop_unionVersionRanges , property prop_intersectVersionRanges , property prop_differenceVersionRanges , property prop_invertVersionRange , property prop_withinVersion , property prop_foldVersionRange , property prop_foldVersionRange' -- the semantic query functions --, property prop_isAnyVersion1 --FIXME: runs out of test cases --, property prop_isAnyVersion2 --FIXME: runs out of test cases --, property prop_isNoVersion --FIXME: runs out of test cases --, property prop_isSpecificVersion1 --FIXME: runs out of test cases --, property prop_isSpecificVersion2 --FIXME: runs out of test cases , property prop_simplifyVersionRange1 , property prop_simplifyVersionRange1' --, property prop_simplifyVersionRange2 --FIXME: runs out of test cases --, property prop_simplifyVersionRange2' --FIXME: runs out of test cases --, property prop_simplifyVersionRange2'' --FIXME: actually wrong -- converting between version ranges and version intervals , property prop_to_intervals --, property prop_to_intervals_canonical --FIXME: runs out of test cases --, property prop_to_intervals_canonical' --FIXME: runs out of test cases , property prop_from_intervals , property prop_to_from_intervals , property prop_from_to_intervals , property prop_from_to_intervals' -- union and intersection of version intervals , property prop_unionVersionIntervals , property prop_unionVersionIntervals_idempotent , property prop_unionVersionIntervals_commutative , property prop_unionVersionIntervals_associative , property prop_intersectVersionIntervals , property prop_intersectVersionIntervals_idempotent , property prop_intersectVersionIntervals_commutative , property prop_intersectVersionIntervals_associative , property prop_union_intersect_distributive , property prop_intersect_union_distributive -- inversion of version intervals , property prop_invertVersionIntervals , property prop_invertVersionIntervalsTwice ] -- parseTests :: [TestTree] -- parseTests = -- zipWith (\n p -> testProperty ("Parse Property " ++ show n) p) [1::Int ..] -- -- parsing and pretty printing -- [ -- property prop_parse_disp1 --FIXME: actually wrong -- -- These are also wrong, see -- -- https://github.com/haskell/cabal/issues/3037#issuecomment-177671011 -- -- property prop_parse_disp2 -- -- , property prop_parse_disp3 -- -- , property prop_parse_disp4 -- -- , property prop_parse_disp5 -- ] #if !MIN_VERSION_QuickCheck(2,9,0) instance Arbitrary Version where arbitrary = do branch <- smallListOf1 $ frequency [(3, return 0) ,(3, return 1) ,(2, return 2) ,(1, return 3)] return (Version branch []) -- deliberate [] where smallListOf1 = adjustSize (\n -> min 5 (n `div` 3)) . listOf1 shrink (Version branch []) = [ Version branch' [] | branch' <- shrink branch, not (null branch') ] shrink (Version branch _tags) = [ Version branch [] ] #endif instance Arbitrary VersionRange where arbitrary = sized verRangeExp where verRangeExp n = frequency $ [ (2, return anyVersion) , (1, liftM thisVersion arbitrary) , (1, liftM laterVersion arbitrary) , (1, liftM orLaterVersion arbitrary) , (1, liftM orLaterVersion' arbitrary) , (1, liftM earlierVersion arbitrary) , (1, liftM orEarlierVersion arbitrary) , (1, liftM orEarlierVersion' arbitrary) , (1, liftM withinVersion arbitrary) , (2, liftM VersionRangeParens arbitrary) ] ++ if n == 0 then [] else [ (2, liftM2 unionVersionRanges verRangeExp2 verRangeExp2) , (2, liftM2 intersectVersionRanges verRangeExp2 verRangeExp2) ] where verRangeExp2 = verRangeExp (n `div` 2) orLaterVersion' v = unionVersionRanges (LaterVersion v) (ThisVersion v) orEarlierVersion' v = unionVersionRanges (EarlierVersion v) (ThisVersion v) --------------------------- -- VersionRange properties -- prop_nonNull :: Version -> Bool prop_nonNull = not . null . versionBranch prop_anyVersion :: Version -> Bool prop_anyVersion v' = withinRange v' anyVersion == True prop_noVersion :: Version -> Bool prop_noVersion v' = withinRange v' noVersion == False prop_thisVersion :: Version -> Version -> Bool prop_thisVersion v v' = withinRange v' (thisVersion v) == (v' == v) prop_notThisVersion :: Version -> Version -> Bool prop_notThisVersion v v' = withinRange v' (notThisVersion v) == (v' /= v) prop_laterVersion :: Version -> Version -> Bool prop_laterVersion v v' = withinRange v' (laterVersion v) == (v' > v) prop_orLaterVersion :: Version -> Version -> Bool prop_orLaterVersion v v' = withinRange v' (orLaterVersion v) == (v' >= v) prop_earlierVersion :: Version -> Version -> Bool prop_earlierVersion v v' = withinRange v' (earlierVersion v) == (v' < v) prop_orEarlierVersion :: Version -> Version -> Bool prop_orEarlierVersion v v' = withinRange v' (orEarlierVersion v) == (v' <= v) prop_unionVersionRanges :: VersionRange -> VersionRange -> Version -> Bool prop_unionVersionRanges vr1 vr2 v' = withinRange v' (unionVersionRanges vr1 vr2) == (withinRange v' vr1 || withinRange v' vr2) prop_intersectVersionRanges :: VersionRange -> VersionRange -> Version -> Bool prop_intersectVersionRanges vr1 vr2 v' = withinRange v' (intersectVersionRanges vr1 vr2) == (withinRange v' vr1 && withinRange v' vr2) prop_differenceVersionRanges :: VersionRange -> VersionRange -> Version -> Bool prop_differenceVersionRanges vr1 vr2 v' = withinRange v' (differenceVersionRanges vr1 vr2) == (withinRange v' vr1 && not (withinRange v' vr2)) prop_invertVersionRange :: VersionRange -> Version -> Bool prop_invertVersionRange vr v' = withinRange v' (invertVersionRange vr) == not (withinRange v' vr) prop_withinVersion :: Version -> Version -> Bool prop_withinVersion v v' = withinRange v' (withinVersion v) == (v' >= v && v' < upper v) where upper (Version lower t) = Version (init lower ++ [last lower + 1]) t prop_foldVersionRange :: VersionRange -> Bool prop_foldVersionRange range = expandWildcard range == foldVersionRange anyVersion thisVersion laterVersion earlierVersion unionVersionRanges intersectVersionRanges range where expandWildcard (WildcardVersion v) = intersectVersionRanges (orLaterVersion v) (earlierVersion (upper v)) where upper (Version lower t) = Version (init lower ++ [last lower + 1]) t expandWildcard (UnionVersionRanges v1 v2) = UnionVersionRanges (expandWildcard v1) (expandWildcard v2) expandWildcard (IntersectVersionRanges v1 v2) = IntersectVersionRanges (expandWildcard v1) (expandWildcard v2) expandWildcard (VersionRangeParens v) = expandWildcard v expandWildcard v = v prop_foldVersionRange' :: VersionRange -> Bool prop_foldVersionRange' range = canonicalise range == foldVersionRange' anyVersion thisVersion laterVersion earlierVersion orLaterVersion orEarlierVersion (\v _ -> withinVersion v) (\v _ -> majorBoundVersion v) unionVersionRanges intersectVersionRanges id range where canonicalise (UnionVersionRanges (LaterVersion v) (ThisVersion v')) | v == v' = UnionVersionRanges (ThisVersion v') (LaterVersion v) canonicalise (UnionVersionRanges (EarlierVersion v) (ThisVersion v')) | v == v' = UnionVersionRanges (ThisVersion v') (EarlierVersion v) canonicalise (UnionVersionRanges v1 v2) = UnionVersionRanges (canonicalise v1) (canonicalise v2) canonicalise (IntersectVersionRanges v1 v2) = IntersectVersionRanges (canonicalise v1) (canonicalise v2) canonicalise (VersionRangeParens v) = canonicalise v canonicalise v = v prop_isAnyVersion1 :: VersionRange -> Version -> Property prop_isAnyVersion1 range version = isAnyVersion range ==> withinRange version range prop_isAnyVersion2 :: VersionRange -> Property prop_isAnyVersion2 range = isAnyVersion range ==> foldVersionRange True (\_ -> False) (\_ -> False) (\_ -> False) (\_ _ -> False) (\_ _ -> False) (simplifyVersionRange range) prop_isNoVersion :: VersionRange -> Version -> Property prop_isNoVersion range version = isNoVersion range ==> not (withinRange version range) prop_isSpecificVersion1 :: VersionRange -> NonEmptyList Version -> Property prop_isSpecificVersion1 range (NonEmpty versions) = isJust version && not (null versions') ==> allEqual (fromJust version : versions') where version = isSpecificVersion range versions' = filter (`withinRange` range) versions allEqual xs = and (zipWith (==) xs (tail xs)) prop_isSpecificVersion2 :: VersionRange -> Property prop_isSpecificVersion2 range = isJust version ==> foldVersionRange Nothing Just (\_ -> Nothing) (\_ -> Nothing) (\_ _ -> Nothing) (\_ _ -> Nothing) (simplifyVersionRange range) == version where version = isSpecificVersion range -- | 'simplifyVersionRange' is a semantic identity on 'VersionRange'. -- prop_simplifyVersionRange1 :: VersionRange -> Version -> Bool prop_simplifyVersionRange1 range version = withinRange version range == withinRange version (simplifyVersionRange range) prop_simplifyVersionRange1' :: VersionRange -> Bool prop_simplifyVersionRange1' range = range `equivalentVersionRange` (simplifyVersionRange range) -- | 'simplifyVersionRange' produces a canonical form for ranges with -- equivalent semantics. -- prop_simplifyVersionRange2 :: VersionRange -> VersionRange -> Version -> Property prop_simplifyVersionRange2 r r' v = r /= r' && simplifyVersionRange r == simplifyVersionRange r' ==> withinRange v r == withinRange v r' prop_simplifyVersionRange2' :: VersionRange -> VersionRange -> Property prop_simplifyVersionRange2' r r' = r /= r' && simplifyVersionRange r == simplifyVersionRange r' ==> r `equivalentVersionRange` r' --FIXME: see equivalentVersionRange for details prop_simplifyVersionRange2'' :: VersionRange -> VersionRange -> Property prop_simplifyVersionRange2'' r r' = r /= r' && r `equivalentVersionRange` r' ==> simplifyVersionRange r == simplifyVersionRange r' || isNoVersion r || isNoVersion r' -------------------- -- VersionIntervals -- -- | Generating VersionIntervals -- -- This is a tad tricky as VersionIntervals is an abstract type, so we first -- make a local type for generating the internal representation. Then we check -- that this lets us construct valid 'VersionIntervals'. -- newtype VersionIntervals' = VersionIntervals' [VersionInterval] deriving (Eq, Show) instance Arbitrary VersionIntervals' where arbitrary = do ubound <- arbitrary bounds <- arbitrary let intervals = mergeTouching . map fixEmpty . replaceUpper ubound . pairs . sortBy (comparing fst) $ bounds return (VersionIntervals' intervals) where pairs ((l, lb):(u, ub):bs) = (LowerBound l lb, UpperBound u ub) : pairs bs pairs _ = [] replaceUpper NoUpperBound [(l,_)] = [(l, NoUpperBound)] replaceUpper NoUpperBound (i:is) = i : replaceUpper NoUpperBound is replaceUpper _ is = is -- merge adjacent intervals that touch mergeTouching (i1@(l,u):i2@(l',u'):is) | doesNotTouch u l' = i1 : mergeTouching (i2:is) | otherwise = mergeTouching ((l,u'):is) mergeTouching is = is doesNotTouch :: UpperBound -> LowerBound -> Bool doesNotTouch NoUpperBound _ = False doesNotTouch (UpperBound u ub) (LowerBound l lb) = u < l || (u == l && ub == ExclusiveBound && lb == ExclusiveBound) fixEmpty (LowerBound l _, UpperBound u _) | l == u = (LowerBound l InclusiveBound, UpperBound u InclusiveBound) fixEmpty i = i shrink (VersionIntervals' intervals) = [ VersionIntervals' intervals' | intervals' <- shrink intervals ] instance Arbitrary Bound where arbitrary = elements [ExclusiveBound, InclusiveBound] instance Arbitrary LowerBound where arbitrary = liftM2 LowerBound arbitrary arbitrary instance Arbitrary UpperBound where arbitrary = oneof [return NoUpperBound ,liftM2 UpperBound arbitrary arbitrary] -- | Check that our VersionIntervals' arbitrary instance generates intervals -- that satisfies the invariant. -- prop_gen_intervals1 :: VersionIntervals' -> Bool prop_gen_intervals1 (VersionIntervals' intervals) = isJust (mkVersionIntervals intervals) instance Arbitrary VersionIntervals where arbitrary = do VersionIntervals' intervals <- arbitrary case mkVersionIntervals intervals of Just xs -> return xs -- | Check that constructing our intervals type and converting it to a -- 'VersionRange' and then into the true intervals type gives us back -- the exact same sequence of intervals. This tells us that our arbitrary -- instance for 'VersionIntervals'' is ok. -- prop_gen_intervals2 :: VersionIntervals' -> Bool prop_gen_intervals2 (VersionIntervals' intervals') = asVersionIntervals (fromVersionIntervals intervals) == intervals' where Just intervals = mkVersionIntervals intervals' -- | Check that 'VersionIntervals' models 'VersionRange' via -- 'toVersionIntervals'. -- prop_to_intervals :: VersionRange -> Version -> Bool prop_to_intervals range version = withinRange version range == withinIntervals version intervals where intervals = toVersionIntervals range -- | Check that semantic equality on 'VersionRange's is the same as converting -- to 'VersionIntervals' and doing syntactic equality. -- prop_to_intervals_canonical :: VersionRange -> VersionRange -> Property prop_to_intervals_canonical r r' = r /= r' && r `equivalentVersionRange` r' ==> toVersionIntervals r == toVersionIntervals r' prop_to_intervals_canonical' :: VersionRange -> VersionRange -> Property prop_to_intervals_canonical' r r' = r /= r' && toVersionIntervals r == toVersionIntervals r' ==> r `equivalentVersionRange` r' -- | Check that 'VersionIntervals' models 'VersionRange' via -- 'fromVersionIntervals'. -- prop_from_intervals :: VersionIntervals -> Version -> Bool prop_from_intervals intervals version = withinRange version range == withinIntervals version intervals where range = fromVersionIntervals intervals -- | @'toVersionIntervals' . 'fromVersionIntervals'@ is an exact identity on -- 'VersionIntervals'. -- prop_to_from_intervals :: VersionIntervals -> Bool prop_to_from_intervals intervals = toVersionIntervals (fromVersionIntervals intervals) == intervals -- | @'fromVersionIntervals' . 'toVersionIntervals'@ is a semantic identity on -- 'VersionRange', though not necessarily a syntactic identity. -- prop_from_to_intervals :: VersionRange -> Bool prop_from_to_intervals range = range' `equivalentVersionRange` range where range' = fromVersionIntervals (toVersionIntervals range) -- | Equivalent of 'prop_from_to_intervals' -- prop_from_to_intervals' :: VersionRange -> Version -> Bool prop_from_to_intervals' range version = withinRange version range' == withinRange version range where range' = fromVersionIntervals (toVersionIntervals range) -- | The semantics of 'unionVersionIntervals' is (||). -- prop_unionVersionIntervals :: VersionIntervals -> VersionIntervals -> Version -> Bool prop_unionVersionIntervals is1 is2 v = withinIntervals v (unionVersionIntervals is1 is2) == (withinIntervals v is1 || withinIntervals v is2) -- | 'unionVersionIntervals' is idempotent -- prop_unionVersionIntervals_idempotent :: VersionIntervals -> Bool prop_unionVersionIntervals_idempotent = Laws.idempotent_binary unionVersionIntervals -- | 'unionVersionIntervals' is commutative -- prop_unionVersionIntervals_commutative :: VersionIntervals -> VersionIntervals -> Bool prop_unionVersionIntervals_commutative = Laws.commutative unionVersionIntervals -- | 'unionVersionIntervals' is associative -- prop_unionVersionIntervals_associative :: VersionIntervals -> VersionIntervals -> VersionIntervals -> Bool prop_unionVersionIntervals_associative = Laws.associative unionVersionIntervals -- | The semantics of 'intersectVersionIntervals' is (&&). -- prop_intersectVersionIntervals :: VersionIntervals -> VersionIntervals -> Version -> Bool prop_intersectVersionIntervals is1 is2 v = withinIntervals v (intersectVersionIntervals is1 is2) == (withinIntervals v is1 && withinIntervals v is2) -- | 'intersectVersionIntervals' is idempotent -- prop_intersectVersionIntervals_idempotent :: VersionIntervals -> Bool prop_intersectVersionIntervals_idempotent = Laws.idempotent_binary intersectVersionIntervals -- | 'intersectVersionIntervals' is commutative -- prop_intersectVersionIntervals_commutative :: VersionIntervals -> VersionIntervals -> Bool prop_intersectVersionIntervals_commutative = Laws.commutative intersectVersionIntervals -- | 'intersectVersionIntervals' is associative -- prop_intersectVersionIntervals_associative :: VersionIntervals -> VersionIntervals -> VersionIntervals -> Bool prop_intersectVersionIntervals_associative = Laws.associative intersectVersionIntervals -- | 'unionVersionIntervals' distributes over 'intersectVersionIntervals' -- prop_union_intersect_distributive :: Property prop_union_intersect_distributive = Laws.distributive_left unionVersionIntervals intersectVersionIntervals .&. Laws.distributive_right unionVersionIntervals intersectVersionIntervals -- | 'intersectVersionIntervals' distributes over 'unionVersionIntervals' -- prop_intersect_union_distributive :: Property prop_intersect_union_distributive = Laws.distributive_left intersectVersionIntervals unionVersionIntervals .&. Laws.distributive_right intersectVersionIntervals unionVersionIntervals -- | The semantics of 'invertVersionIntervals' is 'not'. -- prop_invertVersionIntervals :: VersionIntervals -> Version -> Bool prop_invertVersionIntervals vi v = withinIntervals v (invertVersionIntervals vi) == not (withinIntervals v vi) -- | Double application of 'invertVersionIntervals' is the identity function prop_invertVersionIntervalsTwice :: VersionIntervals -> Bool prop_invertVersionIntervalsTwice vi = invertVersionIntervals (invertVersionIntervals vi) == vi -------------------------------- -- equivalentVersionRange helper prop_equivalentVersionRange :: VersionRange -> VersionRange -> Version -> Property prop_equivalentVersionRange range range' version = equivalentVersionRange range range' && range /= range' ==> withinRange version range == withinRange version range' --FIXME: this is wrong. consider version ranges "<=1" and "<1.0" -- this algorithm cannot distinguish them because there is no version -- that is included by one that is excluded by the other. -- Alternatively we must reconsider the semantics of '<' and '<=' -- in version ranges / version intervals. Perhaps the canonical -- representation should use just < v and interpret "<= v" as "< v.0". equivalentVersionRange :: VersionRange -> VersionRange -> Bool equivalentVersionRange vr1 vr2 = let allVersionsUsed = nub (sort (versionsUsed vr1 ++ versionsUsed vr2)) minPoint = Version [0] [] maxPoint | null allVersionsUsed = minPoint | otherwise = case maximum allVersionsUsed of Version vs _ -> Version (vs ++ [1]) [] probeVersions = minPoint : maxPoint : intermediateVersions allVersionsUsed in all (\v -> withinRange v vr1 == withinRange v vr2) probeVersions where versionsUsed = foldVersionRange [] (\x->[x]) (\x->[x]) (\x->[x]) (++) (++) intermediateVersions (v1:v2:vs) = v1 : intermediateVersion v1 v2 : intermediateVersions (v2:vs) intermediateVersions vs = vs intermediateVersion :: Version -> Version -> Version intermediateVersion v1 v2 | v1 >= v2 = error "intermediateVersion: v1 >= v2" intermediateVersion (Version v1 _) (Version v2 _) = Version (intermediateList v1 v2) [] where intermediateList :: [Int] -> [Int] -> [Int] intermediateList [] (_:_) = [0] intermediateList (x:xs) (y:ys) | x < y = x : xs ++ [0] | otherwise = x : intermediateList xs ys prop_intermediateVersion :: Version -> Version -> Property prop_intermediateVersion v1 v2 = (v1 /= v2) && not (adjacentVersions v1 v2) ==> if v1 < v2 then let v = intermediateVersion v1 v2 in (v1 < v && v < v2) else let v = intermediateVersion v2 v1 in v1 > v && v > v2 adjacentVersions :: Version -> Version -> Bool adjacentVersions (Version v1 _) (Version v2 _) = v1 ++ [0] == v2 || v2 ++ [0] == v1 -------------------------------- -- Parsing and pretty printing -- prop_parse_disp1 :: VersionRange -> Bool prop_parse_disp1 vr = fmap stripParens (simpleParse (display vr)) == Just (canonicalise vr) where canonicalise = swizzle . swap swizzle (UnionVersionRanges (UnionVersionRanges v1 v2) v3) | not (isOrLaterVersion v1 v2) && not (isOrEarlierVersion v1 v2) = swizzle (UnionVersionRanges v1 (UnionVersionRanges v2 v3)) swizzle (IntersectVersionRanges (IntersectVersionRanges v1 v2) v3) = swizzle (IntersectVersionRanges v1 (IntersectVersionRanges v2 v3)) swizzle (UnionVersionRanges v1 v2) = UnionVersionRanges (swizzle v1) (swizzle v2) swizzle (IntersectVersionRanges v1 v2) = IntersectVersionRanges (swizzle v1) (swizzle v2) swizzle (VersionRangeParens v) = swizzle v swizzle v = v isOrLaterVersion (ThisVersion v) (LaterVersion v') = v == v' isOrLaterVersion _ _ = False isOrEarlierVersion (ThisVersion v) (EarlierVersion v') = v == v' isOrEarlierVersion _ _ = False swap = foldVersionRange' anyVersion thisVersion laterVersion earlierVersion orLaterVersion orEarlierVersion (\v _ -> withinVersion v) (\v _ -> MajorBoundVersion v) unionVersionRanges intersectVersionRanges id stripParens :: VersionRange -> VersionRange stripParens (VersionRangeParens v) = stripParens v stripParens (UnionVersionRanges v1 v2) = UnionVersionRanges (stripParens v1) (stripParens v2) stripParens (IntersectVersionRanges v1 v2) = IntersectVersionRanges (stripParens v1) (stripParens v2) stripParens v = v prop_parse_disp2 :: VersionRange -> Property prop_parse_disp2 vr = let b = fmap (display :: VersionRange -> String) (simpleParse (display vr)) a = Just (display vr) in counterexample ("Expected: " ++ show a) $ counterexample ("But got: " ++ show b) $ b == a prop_parse_disp3 :: VersionRange -> Property prop_parse_disp3 vr = let a = Just (display vr) b = fmap displayRaw (simpleParse (display vr)) in counterexample ("Expected: " ++ show a) $ counterexample ("But got: " ++ show b) $ b == a prop_parse_disp4 :: VersionRange -> Property prop_parse_disp4 vr = let a = Just vr b = (simpleParse (display vr)) in counterexample ("Expected: " ++ show a) $ counterexample ("But got: " ++ show b) $ b == a prop_parse_disp5 :: VersionRange -> Property prop_parse_disp5 vr = let a = Just vr b = simpleParse (displayRaw vr) in counterexample ("Expected: " ++ show a) $ counterexample ("But got: " ++ show b) $ b == a displayRaw :: VersionRange -> String displayRaw = Disp.render . foldVersionRange' -- precedence: -- All the same as the usual pretty printer, except for the parens ( Disp.text "-any") (\v -> Disp.text "==" <> disp v) (\v -> Disp.char '>' <> disp v) (\v -> Disp.char '<' <> disp v) (\v -> Disp.text ">=" <> disp v) (\v -> Disp.text "<=" <> disp v) (\v _ -> Disp.text "==" <> dispWild v) (\v _ -> Disp.text "^>=" <> disp v) (\r1 r2 -> r1 <+> Disp.text "||" <+> r2) (\r1 r2 -> r1 <+> Disp.text "&&" <+> r2) (\r -> Disp.parens r) -- parens where dispWild (Version b _) = Disp.hcat (Disp.punctuate (Disp.char '.') (map Disp.int b)) <> Disp.text ".*"
sopvop/cabal
Cabal/tests/UnitTests/Distribution/Version.hs
bsd-3-clause
26,798
0
16
6,085
6,148
3,179
2,969
-1
-1
{-# LANGUAGE QuasiQuotes #-} -- | Simple C runtime representation. module Futhark.CodeGen.Backends.SimpleRepresentation ( sameRepresentation , tupleField , tupleFieldExp , funName , defaultMemBlockType , builtInFunctionDefs , intTypeToCType , floatTypeToCType , primTypeToCType -- * Primitive value operations , cIntOps , cFloat32Ops , cFloat64Ops , cFloatConvOps -- * Specific builtin functions , c_log32, c_sqrt32, c_exp32, c_sin32, c_cos32, c_atan2_32, c_isnan32, c_isinf32 , c_log64, c_sqrt64, c_exp64, c_sin64, c_cos64, c_atan2_64, c_isnan64, c_isinf64 ) where import qualified Language.C.Syntax as C import qualified Language.C.Quote.C as C import Futhark.CodeGen.ImpCode import Futhark.Util.Pretty (pretty) intTypeToCType :: IntType -> C.Type intTypeToCType Int8 = [C.cty|typename int8_t|] intTypeToCType Int16 = [C.cty|typename int16_t|] intTypeToCType Int32 = [C.cty|typename int32_t|] intTypeToCType Int64 = [C.cty|typename int64_t|] uintTypeToCType :: IntType -> C.Type uintTypeToCType Int8 = [C.cty|typename uint8_t|] uintTypeToCType Int16 = [C.cty|typename uint16_t|] uintTypeToCType Int32 = [C.cty|typename uint32_t|] uintTypeToCType Int64 = [C.cty|typename uint64_t|] floatTypeToCType :: FloatType -> C.Type floatTypeToCType Float32 = [C.cty|float|] floatTypeToCType Float64 = [C.cty|double|] primTypeToCType :: PrimType -> C.Type primTypeToCType (IntType t) = intTypeToCType t primTypeToCType (FloatType t) = floatTypeToCType t primTypeToCType Bool = [C.cty|char|] primTypeToCType Cert = [C.cty|char|] -- | True if both types map to the same runtime representation. This -- is the case if they are identical modulo uniqueness. sameRepresentation :: [Type] -> [Type] -> Bool sameRepresentation ets1 ets2 | length ets1 == length ets2 = and $ zipWith sameRepresentation' ets1 ets2 | otherwise = False sameRepresentation' :: Type -> Type -> Bool sameRepresentation' (Scalar t1) (Scalar t2) = t1 == t2 sameRepresentation' (Mem _ space1) (Mem _ space2) = space1 == space2 sameRepresentation' _ _ = False -- | @tupleField i@ is the name of field number @i@ in a tuple. tupleField :: Int -> String tupleField i = "elem_" ++ show i -- | @tupleFieldExp e i@ is the expression for accesing field @i@ of -- tuple @e@. If @e@ is an lvalue, so will the resulting expression -- be. tupleFieldExp :: C.Exp -> Int -> C.Exp tupleFieldExp e i = [C.cexp|$exp:e.$id:(tupleField i)|] -- | @funName f@ is the name of the C function corresponding to -- the Futhark function @f@. funName :: Name -> String funName = ("futhark_"++) . nameToString funName' :: String -> String funName' = funName . nameFromString -- | The type of memory blocks in the default memory space. defaultMemBlockType :: C.Type defaultMemBlockType = [C.cty|unsigned char*|] cIntOps :: [C.Definition] cIntOps = concatMap (`map` [minBound..maxBound]) ops where ops = [mkAdd, mkSub, mkMul, mkUDiv, mkUMod, mkSDiv, mkSMod, mkSQuot, mkSRem, mkShl, mkLShr, mkAShr, mkAnd, mkOr, mkXor, mkUlt, mkUle, mkSlt, mkSle, mkPow ] ++ map mkSExt [minBound..maxBound] ++ map mkZExt [minBound..maxBound] taggedI s Int8 = s ++ "8" taggedI s Int16 = s ++ "16" taggedI s Int32 = s ++ "32" taggedI s Int64 = s ++ "64" mkAdd = simpleIntOp "add" [C.cexp|x + y|] mkSub = simpleIntOp "sub" [C.cexp|x - y|] mkMul = simpleIntOp "mul" [C.cexp|x * y|] mkUDiv = simpleUintOp "udiv" [C.cexp|x / y|] mkUMod = simpleUintOp "umod" [C.cexp|x % y|] mkSDiv t = let ct = intTypeToCType t in [C.cedecl|static inline $ty:ct $id:(taggedI "sdiv" t)($ty:ct x, $ty:ct y) { $ty:ct q = x / y; $ty:ct r = x % y; return q - (((r != 0) && ((r < 0) != (y < 0))) ? 1 : 0); }|] mkSMod t = let ct = intTypeToCType t in [C.cedecl|static inline $ty:ct $id:(taggedI "smod" t)($ty:ct x, $ty:ct y) { $ty:ct r = x % y; return r + ((r == 0 || (x > 0 && y > 0) || (x < 0 && y < 0)) ? 0 : y); }|] mkSQuot = simpleIntOp "squot" [C.cexp|x / y|] mkSRem = simpleIntOp "srem" [C.cexp|x % y|] mkShl = simpleUintOp "shl" [C.cexp|x << y|] mkLShr = simpleUintOp "lshr" [C.cexp|x >> y|] mkAShr = simpleIntOp "ashr" [C.cexp|x >> y|] mkAnd = simpleUintOp "and" [C.cexp|x & y|] mkOr = simpleUintOp "or" [C.cexp|x | y|] mkXor = simpleUintOp "xor" [C.cexp|x ^ y|] mkUlt = uintCmpOp "ult" [C.cexp|x < y|] mkUle = uintCmpOp "ule" [C.cexp|x <= y|] mkSlt = intCmpOp "slt" [C.cexp|x < y|] mkSle = intCmpOp "sle" [C.cexp|x <= y|] mkPow t = let ct = intTypeToCType t in [C.cedecl|static inline $ty:ct $id:(taggedI "pow" t)($ty:ct x, $ty:ct y) { $ty:ct res = 1, rem = y; while (rem != 0) { if (rem & 1) { res *= x; } rem >>= 1; x *= x; } return res; }|] mkSExt from_t to_t = [C.cedecl|static inline $ty:to_ct $id:name($ty:from_ct x) { return x;} |] where name = "sext_"++pretty from_t++"_"++pretty to_t from_ct = intTypeToCType from_t to_ct = intTypeToCType to_t mkZExt from_t to_t = [C.cedecl|static inline $ty:to_ct $id:name($ty:from_ct x) { return x;} |] where name = "zext_"++pretty from_t++"_"++pretty to_t from_ct = uintTypeToCType from_t to_ct = uintTypeToCType to_t simpleUintOp s e t = [C.cedecl|static inline $ty:ct $id:(taggedI s t)($ty:ct x, $ty:ct y) { return $exp:e; }|] where ct = uintTypeToCType t simpleIntOp s e t = [C.cedecl|static inline $ty:ct $id:(taggedI s t)($ty:ct x, $ty:ct y) { return $exp:e; }|] where ct = intTypeToCType t intCmpOp s e t = [C.cedecl|static inline char $id:(taggedI s t)($ty:ct x, $ty:ct y) { return $exp:e; }|] where ct = intTypeToCType t uintCmpOp s e t = [C.cedecl|static inline char $id:(taggedI s t)($ty:ct x, $ty:ct y) { return $exp:e; }|] where ct = uintTypeToCType t cFloat32Ops :: [C.Definition] cFloat64Ops :: [C.Definition] cFloatConvOps :: [C.Definition] (cFloat32Ops, cFloat64Ops, cFloatConvOps) = ( map ($Float32) mkOps , map ($Float64) mkOps , [ mkFPConvFF "fpconv" from to | from <- [minBound..maxBound], to <- [minBound..maxBound] ]) where taggedF s Float32 = s ++ "32" taggedF s Float64 = s ++ "64" convOp s from to = s ++ "_" ++ pretty from ++ "_" ++ pretty to mkOps = [mkFDiv, mkFAdd, mkFSub, mkFMul, mkPow, mkCmpLt, mkCmpLe] ++ map (mkFPConvIF "sitofp") [minBound..maxBound] ++ map (mkFPConvUF "uitofp") [minBound..maxBound] ++ map (flip $ mkFPConvFI "fptosi") [minBound..maxBound] ++ map (flip $ mkFPConvFU "fptoui") [minBound..maxBound] mkFDiv = simpleFloatOp "fdiv" [C.cexp|x / y|] mkFAdd = simpleFloatOp "fadd" [C.cexp|x + y|] mkFSub = simpleFloatOp "fsub" [C.cexp|x - y|] mkFMul = simpleFloatOp "fmul" [C.cexp|x * y|] mkCmpLt = floatCmpOp "cmplt" [C.cexp|x < y|] mkCmpLe = floatCmpOp "cmple" [C.cexp|x <= y|] mkPow Float32 = [C.cedecl|static inline float fpow32(float x, float y) { return pow(x, y); }|] mkPow Float64 = [C.cedecl|static inline double fpow64(double x, double y) { return pow(x, y); }|] mkFPConv from_f to_f s from_t to_t = [C.cedecl|static inline $ty:to_ct $id:(convOp s from_t to_t)($ty:from_ct x) { return x;} |] where from_ct = from_f from_t to_ct = to_f to_t mkFPConvFF = mkFPConv floatTypeToCType floatTypeToCType mkFPConvFI = mkFPConv floatTypeToCType intTypeToCType mkFPConvIF = mkFPConv intTypeToCType floatTypeToCType mkFPConvFU = mkFPConv floatTypeToCType uintTypeToCType mkFPConvUF = mkFPConv uintTypeToCType floatTypeToCType simpleFloatOp s e t = [C.cedecl|static inline $ty:ct $id:(taggedF s t)($ty:ct x, $ty:ct y) { return $exp:e; }|] where ct = floatTypeToCType t floatCmpOp s e t = [C.cedecl|static inline char $id:(taggedF s t)($ty:ct x, $ty:ct y) { return $exp:e; }|] where ct = floatTypeToCType t c_log32 :: C.Func c_log32 = [C.cfun| static inline float $id:(funName' "log32")(float x) { return log(x); } |] c_sqrt32 :: C.Func c_sqrt32 = [C.cfun| static inline float $id:(funName' "sqrt32")(float x) { return sqrt(x); } |] c_exp32 ::C.Func c_exp32 = [C.cfun| static inline float $id:(funName' "exp32")(float x) { return exp(x); } |] c_cos32 ::C.Func c_cos32 = [C.cfun| static inline float $id:(funName' "cos32")(float x) { return cos(x); } |] c_sin32 ::C.Func c_sin32 = [C.cfun| static inline float $id:(funName' "sin32")(float x) { return sin(x); } |] c_atan2_32 ::C.Func c_atan2_32 = [C.cfun| static inline double $id:(funName' "atan2_32")(double x, double y) { return atan2(x,y); } |] c_isnan32 ::C.Func c_isnan32 = [C.cfun| static inline char $id:(funName' "isnan32")(float x) { return isnan(x); } |] c_isinf32 ::C.Func c_isinf32 = [C.cfun| static inline char $id:(funName' "isinf32")(float x) { return isinf(x); } |] c_log64 :: C.Func c_log64 = [C.cfun| static inline double $id:(funName' "log64")(double x) { return log(x); } |] c_sqrt64 :: C.Func c_sqrt64 = [C.cfun| static inline double $id:(funName' "sqrt64")(double x) { return sqrt(x); } |] c_exp64 ::C.Func c_exp64 = [C.cfun| static inline double $id:(funName' "exp64")(double x) { return exp(x); } |] c_cos64 ::C.Func c_cos64 = [C.cfun| static inline double $id:(funName' "cos64")(double x) { return cos(x); } |] c_sin64 ::C.Func c_sin64 = [C.cfun| static inline double $id:(funName' "sin64")(double x) { return sin(x); } |] c_atan2_64 ::C.Func c_atan2_64 = [C.cfun| static inline double $id:(funName' "atan2_64")(double x, double y) { return atan2(x,y); } |] c_isnan64 ::C.Func c_isnan64 = [C.cfun| static inline char $id:(funName' "isnan64")(double x) { return isnan(x); } |] c_isinf64 ::C.Func c_isinf64 = [C.cfun| static inline char $id:(funName' "isinf64")(double x) { return isinf(x); } |] -- | C definitions of the Futhark "standard library". builtInFunctionDefs :: [C.Func] builtInFunctionDefs = [c_log32, c_sqrt32, c_exp32, c_cos32, c_sin32, c_atan2_32, c_isnan32, c_isinf32, c_log64, c_sqrt64, c_exp64, c_cos64, c_sin64, c_atan2_64, c_isnan64, c_isinf64]
CulpaBS/wbBach
src/Futhark/CodeGen/Backends/SimpleRepresentation.hs
bsd-3-clause
11,377
0
13
3,293
2,323
1,378
945
202
4
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} module Geometry where import GHC.Generics import Data.Aeson data Point = Point1D {xp :: Double} | Point2D {xp :: Double, yp :: Double} | Point3D {xp :: Double, yp :: Double, zp :: Double} deriving (Eq, Ord, Show, Generic) instance ToJSON Point instance FromJSON Point data Node = Node { nodeNumber :: Int , nodePoint :: Point} deriving (Eq, Ord, Show, Generic) instance ToJSON Node instance FromJSON Node -- | The `x` coordinate of the `Node`. xn :: Node -> Double xn (Node _ p) = xp p -- | The `y` coordinate of the given `Node`. An exception is thrown in the case of a dimension mismatch. yn :: Node -> Double yn (Node _ p) = yp p -- | The `z` coordinate of the given `Node`. An exception is thrown in the case of a dimension mismatch. zn :: Node -> Double zn (Node _ p) = zp p
adrienhaxaire/funfem
Geometry.hs
bsd-3-clause
925
0
8
238
245
136
109
22
1
import Test.Framework (defaultMain) import qualified Database.Sqroll.Pure.Tests import qualified Database.Sqroll.Sqlite3.Tests import qualified Database.Sqroll.Table.Naming.Tests import qualified Database.Sqroll.TH.Tests import qualified Database.Sqroll.Json.Tests import qualified Database.Sqroll.Tests import qualified Database.Sqroll.Flexible.Tests main :: IO () main = defaultMain [ Database.Sqroll.Pure.Tests.tests , Database.Sqroll.Sqlite3.Tests.tests , Database.Sqroll.Table.Naming.Tests.tests , Database.Sqroll.TH.Tests.tests , Database.Sqroll.Tests.tests , Database.Sqroll.Flexible.Tests.tests , Database.Sqroll.Json.Tests.tests ]
pacak/sqroll
tests/TestSuite.hs
bsd-3-clause
674
0
7
80
141
99
42
17
1
{-# LANGUAGE OverloadedStrings #-} -- | RequestTests runs as a standalone executable so that developers can change -- TestConfig to whatever settings they want. module Main where import Blaze.ByteString.Builder import Control.Applicative import Control.Monad import Control.Monad.IO.Class import qualified Data.ByteString.Lazy.Char8 as BSL8 import Data.Char import Data.Either.Utils import Data.Map import Data.Maybe import Data.OpenSRS import Data.OpenSRS.Types import Data.Time import Data.Tuple.Sequence import Data.UUID import Data.UUID.V5 import System.Environment import System.Locale (defaultTimeLocale) import Test.Hspec import Test.Hspec.Expectations import Text.XmlHtml import TestConfig -- To run a full suite, you must define the following environment variables: -- * SRS Configuration -- * SRS_HOST -- * SRS_USER -- * SRS_KEY -- * SRS_IP -- * Domain availability tests -- * SRSTEST_DOMAINLOOKUP_FREE -- * SRSTEST_DOMAINLOOKUP_TAKEN -- * SRSTEST_DOMAINGET_OURS -- * SRSTEST_DOMAINGET_NOTOURS -- * Domain registration and renewal tests -- * SRSTEST_DOMAINREGISTER_NAME -- * SRSTEST_DOMAINREGISTER_NAME2 -- * SRSTEST_DOMAINRENEW_NAME -- * SRSTEST_DOMAINRENEW_AFFID -- * SRSTEST_DOMAINRENEW_EXPYEAR -- * Cookie tests -- * SRSTEST_COOKIE_DOMAINGET_DOMAIN -- * SRSTEST_COOKIE_DOMAINGET_USER -- * SRSTEST_COOKIE_DOMAINGET_PASS -- * Domain password tests -- * SRSTEST_DOMAINPASSWORD_SEND -- * Domain update tests -- * SRSTEST_DOMAINMODIFY_WHOISPRIV_DOMAIN -- * SRSTEST_DOMAINMODIFY_WHOISPRIV_ENABLE (True || False) makeDomain :: String -> IO Domain makeDomain dname = do t <- getCurrentTime let t' = addUTCTime ((86400 * 365) :: NominalDiffTime) t return $ Domain dname True testContacts (Just t) True (Just t) (Just "5534") True (Just t') testNameservers suite :: Spec suite = do describe "Domain List" . it "can list domains with expiry in a given period" $ let run cfg = do t <- getCurrentTime let sd = addUTCTime ((-86400 * 365 * 20) :: NominalDiffTime) t let ed = addUTCTime ((86400 * 365 * 20) :: NominalDiffTime) t res <- doRequest $ ListDomainsByExpiry cfg sd ed 0 5000 case res of Right (DomainListResult (DomainList count items _)) -> length items `shouldBe` count Left e -> error e _ -> error "This should never happen." in withSRSConfig run describe "Domain Lookup/Get" $ do it "looks up a valid free domain" $ let run cfg d = do res <- doRequest $ LookupDomain cfg d res `shouldBe` (Right . DomainAvailabilityResult $ Available d) in withSRSConfigArgs (lookupEnv "SRSTEST_DOMAINLOOKUP_FREE") run it "looks up a valid taken domain" $ let run cfg d = do res <- doRequest $ LookupDomain cfg d res `shouldBe` (Right . DomainAvailabilityResult $ Unavailable d) in withSRSConfigArgs (lookupEnv "SRSTEST_DOMAINLOOKUP_TAKEN") run it "gets a valid existing domain" $ let run cfg d = do res <- doRequest $ GetDomain cfg d case res of Right (DomainResult dr) -> domainName dr `shouldBe` d Left e -> error e _ -> error "This should never happen." in withSRSConfigArgs (lookupEnv "SRSTEST_DOMAINGET_OURS") run it "gets a valid existing domain that we don't own" $ withSRSConfigArgs (lookupEnv "SRSTEST_DOMAINGET_NOTOURS") (\cfg d -> do res <- doRequest $ GetDomain cfg d fromLeft res `shouldContain` "415: Authentication Error.") describe "Domain Registration" . it "registers a domain" $ let run cfg d = do domain <- makeDomain d res <- doRequest $ RegisterDomain cfg domain True Nothing Nothing False False False True 2 un pwd NewRegistration Nothing case res of Right DomainRegistrationResult{} -> pass Left e -> error e _ -> error "This should never happen." un = fromJust $ makeUsername "webmaster" pwd = fromJust $ makePassword "aTestingPassWord123" in withSRSConfigArgs (lookupEnv "SRSTEST_DOMAINREGISTER_NAME") run describe "Domain Registration/Renewal" $ do it "registers and renews a new domain" $ let run cfg d = do domain <- makeDomain d let changeContact = False let comments = Nothing let encoding = Nothing let lock = False let park = False let whois = False let handleNow = True let regPeriod = 1 let username = fromJust $ makeUsername "webmaster" let password = fromJust $ makePassword "testPassword123" let regType = NewRegistration let tldData = Nothing -- Stage 1: Register domain let req = RegisterDomain cfg domain changeContact comments encoding lock park whois handleNow regPeriod username password regType tldData res <- doRequest req case res of Right DomainRegistrationResult{} -> do -- Stage 2: Get domain let req = GetDomain cfg (domainName domain) res <- doRequest req case res of Right (DomainResult d2) -> do -- Stage 3: Renew domain let expyear = read . formatTime defaultTimeLocale "%Y" . fromJust $ domainExpireDate d2 let req = RenewDomain cfg (domainName d2) (domainAutoRenew d2) (fromJust $ domainAffiliateID d2) expyear True 1 res <- doRequest req case res of Right (DomainRenewalResult drr) -> do print drr pass Left e -> error e _ -> error "This should never happen." Left e -> error e _ -> error "This should never happen." Left e -> error e _ -> error "This should never happen." in withSRSConfigArgs (lookupEnv "SRSTEST_DOMAINREGISTER_NAME2") run it "renews a domain" $ let run cfg (d,a,y) = do res <- doRequest $ RenewDomain cfg d False a y True 1 case res of Right (DomainRenewalResult dr) -> do print dr pass Left e -> error e _ -> error "This should never happen." getSettings = do d <- lookupEnv "SRSTEST_DOMAINRENEW_NAME" a <- lookupEnv "SRSTEST_DOMAINRENEW_AFFID" y <- lookupEnv "SRSTEST_DOMAINRENEW_EXPYEAR" return $ sequenceT (d, a, fmap toInt y) toInt x = read x :: Int in withSRSConfigArgs getSettings run describe "Passwords" $ do it "can change to a valid password" $ let run cfg d = do let un = fromJust $ makeUsername "webmaster" let pwd = fromJust $ makePassword validPassword unPassword pwd `shouldBe` validPassword res <- doRequest $ ChangeDomainOwnership cfg d un pwd case res of Right (GenericSuccess _) -> pass Left e -> error e _ -> error "This should never happen." in withSRSConfigArgs (lookupEnv "SRSTEST_DOMAINPASSWORD_SEND") run it "cannot use an invalid password" $ do let pwd = makePassword invalidPassword pwd `shouldBe` Nothing it "can send passwords to a domain contact" $ let run cfg d = do res <- doRequest $ SendDomainPassword cfg d "owner" False case res of Right (GenericSuccess _) -> pass Left e -> error e _ -> error "This should never happen." in withSRSConfigArgs (lookupEnv "SRSTEST_DOMAINPASSWORD_SEND") run describe "Cookies" $ do it "can get a cookie for a valid domain logon" $ let run cfg (d,u,p) = do res <- doRequest $ SetCookie cfg d u p case res of Right (CookieResult _) -> pass Left e -> error e _ -> error "This should never happen." in withSRSConfigArgs getCookieSettings run it "gets a domain using a cookie" $ let run cfg (d,u,p) = do res <- doRequest $ SetCookie cfg d u p case res of Right (CookieResult jar) -> do res2 <- doRequest (GetDomainWithCookie cfg d $ cookieStr jar) case res2 of Right (DomainResult d') -> domainName d' `shouldBe` d Left e -> error e _ -> error "This should never happen." Left e -> error e _ -> error "This should never happen." in withSRSConfigArgs getCookieSettings run describe "Domain Updates" . it "can set whois privacy" $ let run cfg (d,s) = do let s' = if s then "enable" else "disable" let req = ModifyDomain cfg d False (fromList [("data", "whois_privacy_state"), ("state", s')]) Nothing res <- doRequest req if s then res `shouldBe` (Right $ GenericSuccess "Whois Privacy successfully enabled") else res `shouldBe` (Right $ GenericSuccess "Whois Privacy successfully disabled") getSettings = do d <- liftIO $ lookupEnv "SRSTEST_DOMAINMODIFY_WHOISPRIV_DOMAIN" e <- liftIO $ lookupEnv "SRSTEST_DOMAINMODIFY_WHOISPRIV_ENABLE" return $ sequenceT (d, (== "True") <$> e) in withSRSConfigArgs getSettings run -- | Get configuration getSRSConfig :: IO (Maybe SRSConfig) getSRSConfig = do host <- lookupEnv "SRS_HOST" user <- lookupEnv "SRS_USER" key <- lookupEnv "SRS_KEY" ip <- lookupEnv "SRS_IP" return $ case sequenceT (host,user,key,ip) of Just (h,u,k,i) -> Just (SRSConfig h u k i False) _ -> Nothing -- | Wrap an expectation in a check for config. -- If we don't have config, we pass (defer) the expectation. withSRSConfig :: (SRSConfig -> Expectation) -> Expectation withSRSConfig fn = do cfg <- liftIO getSRSConfig case cfg of Just c -> fn c _ -> do liftIO $ putStrLn "WARNING: No OpenSRS configuration in use." pass -- | Wrap an expectation in a check for config and arguments. -- If we don't have config or arguments, we pass (defer) the expectation. withSRSConfigArgs :: IO (Maybe a) -> (SRSConfig -> a -> Expectation) -> Expectation withSRSConfigArgs getArgs fn = do cfg <- liftIO getSRSConfig args <- liftIO getArgs case sequenceT (cfg, args) of Just (c, a) -> fn c a _ -> do liftIO $ putStrLn "WARNING: Cannot get OpenSRS configuration and/or test arguments." pass getCookieSettings :: IO (Maybe (String, SRSUsername, Password)) getCookieSettings = do d <- liftIO $ lookupEnv "SRSTEST_COOKIE_DOMAINGET_DOMAIN" u <- liftIO $ lookupEnv "SRSTEST_COOKIE_DOMAINGET_USER" p <- liftIO $ lookupEnv "SRSTEST_COOKIE_DOMAINGET_PASS" return $ sequenceT (d, join $ fmap makeUsername u, join $ fmap makePassword p) -- | Explicitly pass a test. pass :: Expectation pass = return () main :: IO () main = do res <- hspec suite return ()
anchor/haskell-opensrs
tests/RequestTests.hs
bsd-3-clause
13,098
0
33
5,272
2,889
1,380
1,509
237
27
{-# LANGUAGE ExtendedDefaultRules #-} {-# LANGUAGE ScopedTypeVariables #-} {-# OPTIONS_GHC -fno-warn-type-defaults #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module ChartSpec where import Test.Hspec import Graphics.HSD3.Chart import Graphics.HSD3.Theme import Utils spec :: Spec spec = describe "Chart" $ do describe "Bar Graph, with records" $ do sample "a simple graph, with a record" [Bar 1.0 "red", Bar 0.2 "green", Bar 0.3 "blue"] (ThemeChart def coloredBarGraph) sample "a more complicated record graph, with a record" (zipWith Bar (map ((+ 10) . (*10) . sin . (/5)) (take 15 [0..])) (concat $ repeat ["red", "red", "red", "green", "green", "green", "blue", "blue", "blue"])) (ThemeChart def coloredBarGraph) describe "Bar Graphs" $ do sample "a simple graph" [1.0, 0.2, 0.3] (ThemeChart def barGraph) sample "a large, but still simple bar graph" (take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8]) (ThemeChart def barGraph) sample "a bar graph with arbitrary data size" (map ((+ 10) . (*10) . sin . (/5)) (take 75 [0..])) (ThemeChart def barGraph) describe "Stacked Bar Graphs" $ do sample "a trivial stacked bar graph" [ take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8] ] (ThemeChart def stackedBarGraph) sample "a simple stacked bar graph" [ take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8] ] (ThemeChart def stackedBarGraph) sample "a normal stacked bar graph" [ take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8] ] (ThemeChart def stackedBarGraph) sample "a complex stacked bar graph" [ take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8] ] (ThemeChart def stackedBarGraph) sample "a complex stacked bar graph with different number of elements" [ take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 40 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 20 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 2 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 14 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8] ] (ThemeChart def stackedBarGraph) sample "a stacked bar graph with arbitrary data size" (replicate 10 (map ((+ 10) . (*10) . sin . (/5)) (take 75 [0..]))) (ThemeChart def stackedBarGraph) describe "Grid layouts" $ do sample "a trivial grid layout" (replicate 5 [ take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8] ]) (ThemeChart def gridBarGraph) sample "a non symmetrical grid layout" (fmap (uncurry take) . zip [5, 4, 4, 2, 5] . replicate 5 $ [ take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 40 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 30 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 10 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8], take 50 . concat . repeat $ [1.0, 0.5, 0.25, 0.7, 0.9, 0.76, 0.2, 0.3, 0.1, 1.0, 0.6, 0.4, 0.8] ]) (ThemeChart def gridBarGraph) sample "a grid bar graph with arbitrary data size" (replicate 6 (replicate 6 (map ((+ 10) . (*10) . sin . (/5)) (take 75 [0..])))) (ThemeChart def gridBarGraph)
Soostone/hs-d3
test/suite/ChartSpec.hs
bsd-3-clause
5,451
0
22
1,849
2,103
1,226
877
84
1
module PrefStringUtil where import Data.List import Data.List.Split import Data.Char (isSpace) import Data.Maybe -- | This is a quick and dirty "Trim whitespace from both sides" function", that is taken straight outta -- <http://stackoverflow.com/questions/6270324/in-haskell-how-do-you-trim-whitespace-from-the-beginning-and-end-of-a-string Stack Overflow>. trim :: String -> String trim = f . f where f = reverse . dropWhile isSpace -- | This takes a string of form "Value1 delim Value2 delim ... Valuen", with a character representing -- a delimiter. It returns the sequence [Value1, Value2, ... Valuen]. All whitespace is trimmed -- from all the values. stripandtrim :: String -> Char -> [String] stripandtrim stringval charval = [trim x | x <- splitOn [charval] stringval] -- | This method takes a string, and attempts to parse it into a number. convertstringtoint :: String -> Maybe Int convertstringtoint stringval | null conversion = Nothing | otherwise = Just (fst (head conversion)) where conversion = reads stringval -- | This method takes a string of the form "a, b, c, ..." where a, b, c -- and so on are integer; it attempts to create a sequence of integers -- from them. convertstringtoseq :: String -> Maybe [Int] convertstringtoseq stringval | null result = Nothing | elem Nothing result = Nothing | otherwise = Just [fromJust d | d <- result] where result = [convertstringtoint c | c <- stripandtrim stringval ','] -- This is for test code. This is a constant for a selection of space characters spacerange = " \t\n\r\f\v\160" -- | This is used for the existence of whitespace in a string. This is used for testing. iswhitespacewithin :: String -> Bool iswhitespacewithin stringval | isNothing (find isSpace stringval) = False | otherwise = True
peterkmurphy/preference
src/PrefStringUtil.hs
bsd-3-clause
1,809
0
10
325
330
170
160
26
1
{-| Module : Database.Relational.Update Description : Definition of UPDATE and friends. Copyright : (c) Alexander Vieth, 2015 Licence : BSD3 Maintainer : [email protected] Stability : experimental Portability : non-portable (GHC only) -} {-# LANGUAGE AutoDeriveTypeable #-} module Database.Relational.Update ( UPDATE(..) ) where data UPDATE table projection rows = UPDATE table projection rows
avieth/Relational
Database/Relational/Update.hs
bsd-3-clause
423
0
6
81
34
23
11
4
0
module Language.TNT.Token ( Token (..) ) where import Prelude hiding (Bool (..)) data Token = Name String | Operator String | Number Double | String String | Char Char | Import | As | Var | Fun | If | Else | For | In | While | Return | Throw | Null | True | False | Or | And | LT | LE | GT | GE | Plus | Minus | Multiply | Div | Mod | Not | Period | Comma | OpenParen | CloseParen | OpenBrace | CloseBrace | OpenBracket | CloseBracket | Equal | PlusEqual | Colon | Semi | EOF deriving (Eq, Show)
sonyandy/tnt
Language/TNT/Token.hs
bsd-3-clause
984
0
6
598
186
121
65
47
0
{-# OPTIONS_GHC -fno-warn-orphans #-} {-| Module : Game.GoreAndAsh.Resources.Module Description : Monad transformer and instance for core module Copyright : (c) Anton Gushcha, 2016 License : BSD3 Maintainer : [email protected] Stability : experimental Portability : POSIX -} module Game.GoreAndAsh.Resources.Module( ResourcesT(..) ) where import Control.Monad.Catch import Control.Monad.Fix import Control.Monad.State.Strict import Game.GoreAndAsh import Game.GoreAndAsh.Resources.State -- | Monad transformer of the core module. -- -- [@s@] - State of next core module in modules chain; -- -- [@m@] - Next monad in modules monad stack; -- -- [@a@] - Type of result value; -- -- How to embed module: -- -- @ -- type AppStack = ModuleStack [ResourcesT, ... other modules ... ] IO -- -- newtype AppMonad a = AppMonad (AppStack a) -- deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadThrow, MonadCatch, MonadResources) -- @ -- -- The module is pure within first phase (see 'ModuleStack' docs), therefore 'Identity' can be used as end monad. newtype ResourcesT s m a = ResourcesT { runResourcesT :: StateT (ResourcesState s) m a } deriving (Functor, Applicative, Monad, MonadState (ResourcesState s), MonadFix, MonadTrans, MonadIO, MonadThrow, MonadCatch, MonadMask) instance GameModule m s => GameModule (ResourcesT s m) (ResourcesState s) where type ModuleState (ResourcesT s m) = ResourcesState s runModule (ResourcesT m) s = do ((a, s'), nextState) <- runModule (runStateT m s) (resourcesNextState s) return (a, s' { resourcesNextState = nextState }) newModuleState = emptyResourcesState <$> newModuleState withModule _ = id cleanupModule _ = return ()
Teaspot-Studio/gore-and-ash-resources
src/Game/GoreAndAsh/Resources/Module.hs
bsd-3-clause
1,734
0
11
305
305
177
128
-1
-1
{-# LANGUAGE CPP #-} {-# LANGUAGE ViewPatterns #-} ----------------------------------------------------------------------------- -- | -- This module rexposes wrapped parsers from the GHC API. Along with -- returning the parse result, the corresponding annotations are also -- returned such that it is then easy to modify the annotations and print -- the result. -- ---------------------------------------------------------------------------- module Language.Haskell.GHC.ExactPrint.Parsers ( -- * Utility Parser , withDynFlags , CppOptions(..) , defaultCppOptions -- * Module Parsers , parseModule , parseModuleFromString , parseModuleWithOptions , parseModuleWithCpp -- * Basic Parsers , parseExpr , parseImport , parseType , parseDecl , parsePattern , parseStmt , parseWith -- * Internal , parseModuleApiAnnsWithCpp ) where import Language.Haskell.GHC.ExactPrint.Annotate import Language.Haskell.GHC.ExactPrint.Delta import Language.Haskell.GHC.ExactPrint.Preprocess import Language.Haskell.GHC.ExactPrint.Types import Control.Monad.RWS import GHC.Paths (libdir) import qualified ApiAnnotation as GHC import qualified DynFlags as GHC import qualified FastString as GHC import qualified GHC as GHC hiding (parseModule) import qualified HeaderInfo as GHC import qualified Lexer as GHC import qualified MonadUtils as GHC import qualified Outputable as GHC import qualified Parser as GHC import qualified SrcLoc as GHC import qualified StringBuffer as GHC #if __GLASGOW_HASKELL__ <= 710 import qualified OrdList as OL #else import qualified GHC.LanguageExtensions as LangExt #endif import qualified Data.Map as Map -- --------------------------------------------------------------------- -- | Wrapper function which returns Annotations along with the parsed -- element. parseWith :: Annotate w => GHC.DynFlags -> FilePath -> GHC.P (GHC.Located w) -> String -> Either (GHC.SrcSpan, String) (Anns, GHC.Located w) parseWith dflags fileName parser s = case runParser parser dflags fileName s of GHC.PFailed ss m -> Left (ss, GHC.showSDoc dflags m) GHC.POk (mkApiAnns -> apianns) pmod -> Right (as, pmod) where as = relativiseApiAnns pmod apianns -- --------------------------------------------------------------------- runParser :: GHC.P a -> GHC.DynFlags -> FilePath -> String -> GHC.ParseResult a runParser parser flags filename str = GHC.unP parser parseState where location = GHC.mkRealSrcLoc (GHC.mkFastString filename) 1 1 buffer = GHC.stringToStringBuffer str parseState = GHC.mkPState flags buffer location -- --------------------------------------------------------------------- -- | Provides a safe way to consume a properly initialised set of -- 'DynFlags'. -- -- @ -- myParser fname expr = withDynFlags (\\d -> parseExpr d fname expr) -- @ withDynFlags :: (GHC.DynFlags -> a) -> IO a withDynFlags action = GHC.defaultErrorHandler GHC.defaultFatalMessager GHC.defaultFlushOut $ GHC.runGhc (Just libdir) $ do dflags <- GHC.getSessionDynFlags void $ GHC.setSessionDynFlags dflags return (action dflags) -- --------------------------------------------------------------------- parseFile :: GHC.DynFlags -> FilePath -> String -> GHC.ParseResult (GHC.Located (GHC.HsModule GHC.RdrName)) parseFile = runParser GHC.parseModule -- --------------------------------------------------------------------- type Parser a = GHC.DynFlags -> FilePath -> String -> Either (GHC.SrcSpan, String) (Anns, a) parseExpr :: Parser (GHC.LHsExpr GHC.RdrName) parseExpr df fp = parseWith df fp GHC.parseExpression parseImport :: Parser (GHC.LImportDecl GHC.RdrName) parseImport df fp = parseWith df fp GHC.parseImport parseType :: Parser (GHC.LHsType GHC.RdrName) parseType df fp = parseWith df fp GHC.parseType -- safe, see D1007 parseDecl :: Parser (GHC.LHsDecl GHC.RdrName) #if __GLASGOW_HASKELL__ <= 710 parseDecl df fp = parseWith df fp (head . OL.fromOL <$> GHC.parseDeclaration) #else parseDecl df fp = parseWith df fp GHC.parseDeclaration #endif parseStmt :: Parser (GHC.ExprLStmt GHC.RdrName) parseStmt df fp = parseWith df fp GHC.parseStatement parsePattern :: Parser (GHC.LPat GHC.RdrName) parsePattern df fp = parseWith df fp GHC.parsePattern -- --------------------------------------------------------------------- -- -- | This entry point will also work out which language extensions are -- required and perform CPP processing if necessary. -- -- @ -- parseModule = parseModuleWithCpp defaultCppOptions -- @ -- -- Note: 'GHC.ParsedSource' is a synonym for 'GHC.Located' ('GHC.HsModule' 'GHC.RdrName') parseModule :: FilePath -> IO (Either (GHC.SrcSpan, String) (Anns, GHC.ParsedSource)) parseModule = parseModuleWithCpp defaultCppOptions normalLayout -- | This entry point will work out which language extensions are -- required but will _not_ perform CPP processing. -- In contrast to `parseModoule` the input source is read from the provided -- string; the `FilePath` parameter solely exists to provide a name -- in source location annotations. parseModuleFromString :: FilePath -> String -> IO (Either (GHC.SrcSpan, String) (Anns, GHC.ParsedSource)) parseModuleFromString fp s = do GHC.defaultErrorHandler GHC.defaultFatalMessager GHC.defaultFlushOut $ GHC.runGhc (Just libdir) $ do dflags <- initDynFlagsPure fp s return $ parseWith dflags fp GHC.parseModule s parseModuleWithOptions :: DeltaOptions -> FilePath -> IO (Either (GHC.SrcSpan, String) (Anns, GHC.ParsedSource)) parseModuleWithOptions opts fp = parseModuleWithCpp defaultCppOptions opts fp -- | Parse a module with specific instructions for the C pre-processor. parseModuleWithCpp :: CppOptions -> DeltaOptions -> FilePath -> IO (Either (GHC.SrcSpan, String) (Anns, GHC.ParsedSource)) parseModuleWithCpp cpp opts fp = do res <- parseModuleApiAnnsWithCpp cpp fp return (either Left mkAnns res) where mkAnns (apianns, cs, _, m) = Right (relativiseApiAnnsWithOptions opts cs m apianns, m) -- | Low level function which is used in the internal tests. -- It is advised to use 'parseModule' or 'parseModuleWithCpp' instead of -- this function. parseModuleApiAnnsWithCpp :: CppOptions -> FilePath -> IO (Either (GHC.SrcSpan, String) (GHC.ApiAnns, [Comment], GHC.DynFlags, GHC.ParsedSource)) parseModuleApiAnnsWithCpp cppOptions file = GHC.defaultErrorHandler GHC.defaultFatalMessager GHC.defaultFlushOut $ GHC.runGhc (Just libdir) $ do dflags <- initDynFlags file #if __GLASGOW_HASKELL__ <= 710 let useCpp = GHC.xopt GHC.Opt_Cpp dflags #else let useCpp = GHC.xopt LangExt.Cpp dflags #endif (fileContents, injectedComments, dflags') <- if useCpp then do (contents,dflags1) <- getPreprocessedSrcDirect cppOptions file cppComments <- getCppTokensAsComments cppOptions file return (contents,cppComments,dflags1) else do txt <- GHC.liftIO $ readFileGhc file let (contents1,lp) = stripLinePragmas txt return (contents1,lp,dflags) return $ case parseFile dflags' file fileContents of GHC.PFailed ss m -> Left $ (ss, (GHC.showSDoc dflags m)) GHC.POk (mkApiAnns -> apianns) pmod -> Right $ (apianns, injectedComments, dflags', pmod) -- --------------------------------------------------------------------- initDynFlags :: GHC.GhcMonad m => FilePath -> m GHC.DynFlags initDynFlags file = do dflags0 <- GHC.getSessionDynFlags src_opts <- GHC.liftIO $ GHC.getOptionsFromFile dflags0 file (dflags1, _, _) <- GHC.parseDynamicFilePragma dflags0 src_opts -- Turn this on last to avoid T10942 let dflags2 = dflags1 `GHC.gopt_set` GHC.Opt_KeepRawTokenStream void $ GHC.setSessionDynFlags dflags2 return dflags2 -- | Requires GhcMonad constraint because there is -- no pure variant of `parseDynamicFilePragma`. Yet, in constrast to -- `initDynFlags`, it does not (try to) read the file at filepath, but -- solely depends on the module source in the input string. initDynFlagsPure :: GHC.GhcMonad m => FilePath -> String -> m GHC.DynFlags initDynFlagsPure fp s = do -- I was told we could get away with using the unsafeGlobalDynFlags. -- as long as `parseDynamicFilePragma` is impure there seems to be -- no reason to use it. dflags0 <- GHC.getSessionDynFlags let pragmaInfo = GHC.getOptions dflags0 (GHC.stringToStringBuffer $ s) fp (dflags1, _, _) <- GHC.parseDynamicFilePragma dflags0 pragmaInfo -- Turn this on last to avoid T10942 let dflags2 = dflags1 `GHC.gopt_set` GHC.Opt_KeepRawTokenStream void $ GHC.setSessionDynFlags dflags2 return dflags2 -- --------------------------------------------------------------------- mkApiAnns :: GHC.PState -> GHC.ApiAnns mkApiAnns pstate = ( Map.fromListWith (++) . GHC.annotations $ pstate , Map.fromList ((GHC.noSrcSpan, GHC.comment_q pstate) : (GHC.annotations_comments pstate)))
mpickering/ghc-exactprint
src/Language/Haskell/GHC/ExactPrint/Parsers.hs
bsd-3-clause
9,633
0
16
2,150
1,946
1,055
891
155
3
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-| Module : Network.Linode License : BSD3 Stability : experimental This package contains some helpers to create and configure <https://www.linode.com/ Linode> instances. They all require an API key, which can be created on the Linode website. Usage example. We want to create one Linode instance in Atlanta with 1GB of RAM: > import Network.Linode > import Data.List (find) > import qualified System.Process as P > import Data.Foldable (traverse_) > import Data.Monoid ((<>)) > > main :: IO() > main = do > apiKey <- fmap (head . words) (readFile "apiKey") > sshPublicKey <- readFile "id_rsa.pub" > let options = defaultLinodeCreationOptions { > datacenterChoice = "atlanta", > planChoice = "Linode 1024", > sshKey = Just sshPublicKey > } > c <- createLinode apiKey True options > case c of > Left err -> print err > Right linode -> do > traverse_ (\a -> waitForSSH a >> setup a) (publicAddress linode) > print linode > > setup address = P.callCommand $ "scp yourfile root@" <> ip address <> ":/root" You should see something like this: > Creating empty linode (Linode 1024 at atlanta) > Creating disk (24448 MB) > .............. > Creating swap (128 MB) > ........ > Creating config > Booting > ...................................... > Booted linode 1481198 And get something like that: > Linode { > linodeId = LinodeId {unLinodeId = 1481198}, > linodeConfigId = ConfigId {unConfigId = 2251152}, > linodeDatacenterName = "atlanta", > linodePassword = "We4kP4ssw0rd", > linodeAddresses = [Address {ip = "45.79.194.121", rdnsName = "li1293-121.members.linode.com"}]} -} module Network.Linode ( -- * Most common operations createLinode , createCluster , defaultLinodeCreationOptions , waitForSSH , deleteInstance , deleteCluster -- * Lower level API calls , getAccountInfo , getDatacenters , getDistributions , getInstances , getKernels , getPlans , getIpList , createConfig , createDiskFromDistribution , createDisklessLinode , createSwapDisk , createDisk , boot , jobList -- * Helpers , waitUntilCompletion , select , publicAddress -- * Examples , exampleCreateOneLinode , exampleCreateTwoLinodes , module Network.Linode.Types ) where import Control.Concurrent (threadDelay) import qualified Control.Concurrent.Async as A import Control.Error hiding (err) import Control.Lens import Control.Monad (when) import Control.Monad.IO.Class (liftIO) import qualified Control.Retry as R import Data.Foldable (traverse_) import Data.List (find, sortBy) import Data.Monoid ((<>)) import Data.Ord (comparing) import qualified Data.Text as T import qualified Network.Wreq as W import Prelude hiding (log) import qualified System.Process as P import Network.Linode.Internal import Network.Linode.Types {-| Create a Linode instance and boot it. -} createLinode :: ApiKey -> Bool -> LinodeCreationOptions -> IO (Either LinodeError Linode) createLinode apiKey log options = do i <- runExceptT create case i of Left e -> return $ Left e Right (linId, selected) -> do r <- runExceptT $ configure linId selected case r of Left e -> deleteInstance apiKey linId >> return (Left e) Right l -> return $ Right l where create :: ExceptT LinodeError IO (LinodeId, (Datacenter, Distribution, Plan, Kernel)) = do (datacenter, distribution, plan, kernel) <- select apiKey options printLog $ "Creating empty linode (" <> T.unpack (planName plan) <> " at " <> T.unpack (datacenterName datacenter) <> ")" CreatedLinode linId <- createDisklessLinode apiKey (datacenterId datacenter) (planId plan) (paymentChoice options) return (linId, (datacenter, distribution, plan, kernel)) configure linId (datacenter, distribution, plan, kernel) = do let swapSize = swapAmount options let rootDiskSize = (1024 * disk plan) - swapSize let wait = liftIO (waitUntilCompletion apiKey linId log) (CreatedDisk diskId _) <- createDiskFromDistribution apiKey linId (distributionId distribution) (diskLabel options) rootDiskSize (password options) (sshKey options) printLog ("Creating disk (" ++ show rootDiskSize ++ " MB)") >> wait (CreatedDisk swapId _) <- createSwapDisk apiKey linId "swap" swapSize printLog ("Creating swap (" ++ show swapSize ++ " MB)") >> wait (CreatedConfig configId) <- maybeOr (CreatedConfig <$> config options) (createConfig apiKey linId (kernelId kernel) "profile" [diskId, swapId]) printLog "Creating config" (BootedInstance _) <- boot apiKey linId configId printLog "Booting" >> wait addresses <- getIpList apiKey linId printLog $ "Booted linode " ++ show (unLinodeId linId) return $ Linode linId configId (datacenterName datacenter) (password options) addresses printLog l = when log (liftIO $ putStrLn l) {-| Create a Linode cluster. -} createCluster :: ApiKey -> LinodeCreationOptions -> Int -> Bool -> IO (Either [LinodeError] [Linode]) createCluster apiKey options number log = do let optionsList = take number $ map (\(o,i) -> o {diskLabel = diskLabel o <> "-" <> show i}) (zip (repeat options) ([0..] :: [Int])) r <- partitionEithers <$> A.mapConcurrently (createLinode apiKey log) optionsList case r of ([], linodes) -> return (Right linodes) (errors, linodes) -> do _ <- deleteCluster apiKey (map linodeId linodes) return (Left errors) {-| Default options to create an instance. Please customize the security options. -} defaultLinodeCreationOptions :: LinodeCreationOptions defaultLinodeCreationOptions = LinodeCreationOptions { datacenterChoice = "london", planChoice = "Linode 1024", kernelSelect = find (("Latest 64 bit" `T.isPrefixOf`) . kernelName), -- Most recent 64 bits kernel distributionSelect = lastMay . sortBy (comparing distributionName) . filter ((T.pack "Debian" `T.isPrefixOf`) . distributionName), -- Most recent Debian paymentChoice = OneMonth, swapAmount = 128, password = "We4kP4ssw0rd", sshKey = Nothing, diskLabel = "mainDisk", config = Nothing } -- TODO: only works in linux and macos {-| Wait until an ssh connexion is possible, then add the Linode's ip in known_hosts. A newly created Linode is unreachable during a few seconds. -} waitForSSH :: Address -> IO () waitForSSH address = R.recoverAll retryPolicy command where retryPolicy = R.constantDelay oneSecond <> R.limitRetries 100 oneSecond = 1000 * 1000 command _ = P.callCommand $ "ssh -q -o StrictHostKeyChecking=no root@" <> ip address <> " exit" {-| Delete a Linode instance. -} deleteInstance :: ApiKey -> LinodeId -> IO (Either LinodeError DeletedLinode) deleteInstance apiKey (LinodeId i) = runExceptT $ getWith $ W.defaults & W.param "api_key" .~ [T.pack apiKey] & W.param "api_action" .~ [T.pack "linode.delete"] & W.param "LinodeID" .~ [T.pack $ show i] & W.param "skipChecks" .~ ["true"] {-| Delete a list of Linode instances. -} deleteCluster :: ApiKey -> [LinodeId] -> IO ([LinodeError],[DeletedLinode]) deleteCluster apiKey linodes = partitionEithers <$> mapM (deleteInstance apiKey) linodes {-| Read your global account information: network usage, billing state and billing method. -} getAccountInfo :: ApiKey -> ExceptT LinodeError IO AccountInfo getAccountInfo = simpleGetter "account.info" {-| Read all Linode datacenters: dallas, fremont, atlanta, newark, london, tokyo, singapore, frankfurt -} getDatacenters :: ApiKey -> ExceptT LinodeError IO [Datacenter] getDatacenters = simpleGetter "avail.datacenters" {-| Read all available Linux distributions. For example, Debian 8.1 has id 140. -} getDistributions :: ApiKey -> ExceptT LinodeError IO [Distribution] getDistributions = simpleGetter "avail.distributions" {-| Read detailed information about all your instances. -} getInstances :: ApiKey -> ExceptT LinodeError IO [Instance] getInstances = simpleGetter "linode.list" {-| Read all available Linux kernels. -} getKernels :: ApiKey -> ExceptT LinodeError IO [Kernel] getKernels = simpleGetter "avail.kernels" {-| Read all plans offered by Linode. A plan specifies the available CPU, RAM, network usage and pricing of an instance. The smallest plan is Linode 1024. -} getPlans :: ApiKey -> ExceptT LinodeError IO [Plan] getPlans = simpleGetter "avail.linodeplans" {-| Read all IP addresses of an instance. -} getIpList :: ApiKey -> LinodeId -> ExceptT LinodeError IO [Address] getIpList apiKey (LinodeId i) = getWith $ W.defaults & W.param "api_key" .~ [T.pack apiKey] & W.param "api_action" .~ [T.pack "linode.ip.list"] & W.param "LinodeID" .~ [T.pack $ show i] {-| Create a Linode Config (a bag of instance options). -} createConfig :: ApiKey -> LinodeId -> KernelId -> String -> [DiskId] -> ExceptT LinodeError IO CreatedConfig createConfig apiKey (LinodeId i) (KernelId k) label disksIds = do let disksList = T.intercalate "," $ take 9 $ map (T.pack . show . unDisk) disksIds ++ repeat "" let opts = W.defaults & W.param "api_key" .~ [T.pack apiKey] & W.param "api_action" .~ [T.pack "linode.config.create"] & W.param "LinodeID" .~ [T.pack $ show i] & W.param "KernelID" .~ [T.pack $ show k] & W.param "Label" .~ [T.pack label] & W.param "DiskList" .~ [disksList] & W.param "helper_distro" .~ ["true"] & W.param "helper_network" .~ ["true"] getWith opts {-| Create a disk from a supported Linux distribution. Size in MB. -} createDiskFromDistribution :: ApiKey -> LinodeId -> DistributionId -> String -> Int -> String -> Maybe String -> ExceptT LinodeError IO CreatedDisk createDiskFromDistribution apiKey (LinodeId i) (DistributionId d) label size pass sshPublicKey = getWith $ W.defaults & W.param "api_key" .~ [T.pack apiKey] & W.param "api_action" .~ [T.pack "linode.disk.createfromdistribution"] & W.param "LinodeID" .~ [T.pack $ show i] & W.param "DistributionID" .~ [T.pack $ show d] & W.param "Label" .~ [T.pack label] & W.param "Size" .~ [T.pack $ show size] & W.param "rootPass" .~ [T.pack pass] & case T.pack <$> sshPublicKey of Nothing -> id Just k -> W.param "rootSSHKey" .~ [k] {-| Create a Linode instance with no disk and no configuration. You probably want createLinode instead. -} createDisklessLinode :: ApiKey -> DatacenterId -> PlanId -> PaymentTerm -> ExceptT LinodeError IO CreatedLinode createDisklessLinode apiKey (DatacenterId d) (PlanId p) paymentTerm = getWith $ W.defaults & W.param "api_key" .~ [T.pack apiKey] & W.param "api_action" .~ [T.pack "linode.create"] & W.param "DatacenterID" .~ [T.pack $ show d] & W.param "PlanID" .~ [T.pack $ show p] & W.param "PaymentTerm" .~ [T.pack $ show (paymentTermToInt paymentTerm)] {-| Create a swap partition. -} createSwapDisk :: ApiKey -> LinodeId -> String -> Int -> ExceptT LinodeError IO CreatedDisk createSwapDisk apiKey linId label = createDisk apiKey linId label Swap {-| Create a partition. -} createDisk :: ApiKey -> LinodeId -> String -> DiskType -> Int -> ExceptT LinodeError IO CreatedDisk createDisk apiKey (LinodeId i) label diskType size = getWith $ W.defaults & W.param "api_key" .~ [T.pack apiKey] & W.param "api_action" .~ [T.pack "linode.disk.create"] & W.param "LinodeID" .~ [T.pack $ show i] & W.param "Label" .~ [T.pack label] & W.param "Type" .~ [T.pack (diskTypeToString diskType)] & W.param "size" .~ [T.pack $ show size] {-| Boot a Linode instance. -} boot :: ApiKey-> LinodeId -> ConfigId -> ExceptT LinodeError IO BootedInstance boot apiKey (LinodeId i) (ConfigId c) = getWith $ W.defaults & W.param "api_key" .~ [T.pack apiKey] & W.param "api_action" .~ [T.pack "linode.boot"] & W.param "LinodeID" .~ [T.pack $ show i] & W.param "ConfigID" .~ [T.pack $ show c] {-| List of pending jobs for this Linode instance. -} jobList :: ApiKey -> LinodeId -> ExceptT LinodeError IO [WaitingJob] jobList apiKey (LinodeId i) = getWith $ W.defaults & W.param "api_key" .~ [T.pack apiKey] & W.param "api_action" .~ [T.pack "linode.job.list"] & W.param "LinodeID" .~ [T.pack $ show i] & W.param "pendingOnly" .~ ["true"] {-| Wait until all operations on one instance are done. -} waitUntilCompletion :: ApiKey -> LinodeId -> Bool -> IO() waitUntilCompletion apiKey linId log = do waitingJobs <- runExceptT $ jobList apiKey linId case all waitingJobSuccess <$> waitingJobs of Left e -> putStrLn $ "Error during wait:" ++ show e Right True -> when log (putStrLn "") Right False -> do when log (putStr ".") threadDelay (100*1000) waitUntilCompletion apiKey linId log {-| Select a Datacenter, a Plan, a Linux distribution and kernel from all Linode offering. -} select :: ApiKey -> LinodeCreationOptions -> ExceptT LinodeError IO (Datacenter, Distribution, Plan, Kernel) select apiKey options = (,,,) <$> fetchAndSelect (runExceptT $ getDatacenters apiKey) (find ((== T.pack (datacenterChoice options)) . datacenterName)) "datacenter" <*> fetchAndSelect (runExceptT $ getDistributions apiKey) (distributionSelect options) "distribution" <*> fetchAndSelect (runExceptT $ getPlans apiKey) (find ((== T.pack (planChoice options)) . planName)) "plan" <*> fetchAndSelect (runExceptT $ getKernels apiKey) (kernelSelect options) "kernel" {-| Pick one public address of the Linode Instance -} publicAddress :: Linode -> Maybe Address publicAddress = headMay . sortBy (comparing ip) . filter isPublic . linodeAddresses {-| Example of Linode creation. It expects the apiKey and id_rsa.pub files in the current directory. -} exampleCreateOneLinode :: IO (Maybe Linode) exampleCreateOneLinode = do apiKey <- fmap (head . words) (readFile "apiKey") sshPublicKey <- readFile "id_rsa.pub" let options = defaultLinodeCreationOptions { datacenterChoice = "atlanta", planChoice = "Linode 1024", sshKey = Just sshPublicKey } c <- createLinode apiKey True options case c of Left err -> do print err return Nothing Right linode -> do traverse_ (\a -> waitForSSH a >> setup a) (publicAddress linode) return (Just linode) where setup address = P.callCommand $ "scp TODO root@" <> ip address <> ":/root" {-| Example of Linodes creation. It expects the apiKey and id_rsa.pub files in the current directory. -} exampleCreateTwoLinodes :: IO (Maybe [Linode]) exampleCreateTwoLinodes = do sshPublicKey <- readFile "id_rsa.pub" apiKey <- fmap (head . words) (readFile "apiKey") let options = defaultLinodeCreationOptions { datacenterChoice = "atlanta", planChoice = "Linode 1024", sshKey = Just sshPublicKey } c <- createCluster apiKey options 2 True case c of Left errors -> do print ("error(s) in cluster creation" ++ show errors) return Nothing Right linodes -> do mapM_ (traverse_ (\a -> waitForSSH a >> setup a) . publicAddress) linodes return (Just linodes) where setup address = P.callCommand $ "scp TODO root@" <> ip address <> ":/root"
Helkafen/haskell-linode
src/Network/Linode.hs
bsd-3-clause
15,875
0
27
3,599
3,993
2,022
1,971
234
3
-- | Special retrieval queries to build 'ClockTable's using 'HeadingFilter's. -- -- 'ClockTable' is not a type saved directly in the database, it's a combination -- type used for presenting org-mode data. -- Should work similarly to -- <http://orgmode.org/manual/The-clock-table.html The clock table in emacs>. -- -- = Usage -- -- To retrieve a 'ClockTable' you only need to use the 'getTable' function and -- understand how 'HeadingFilter' (see docs for type for usage) works. -- -- For example if you want to retrieve a 'ClockTable' with from all 'Heading's -- that have clocks in all 'Document's: -- -- > import Data.Default -- > import qualified Database.OrgMode.Query.ClockTable as ClockTable -- > -- > ctable <- ClockTable.getTable def -- -- If you want to retrieve a 'ClockTable' with all 'Heading's from a specific -- document you use: -- -- > ctable <- ClockTable.getTable def { headingFilterDocumentIds = [yourDocId] } module Database.OrgMode.Export.ClockTable where import Control.Monad (unless) import Data.Int (Int64) import Database.Esqueleto import qualified Data.HashMap.Strict as HM import Data.HashMap.Strict (HashMap) import Database.OrgMode.Internal.Import import Database.OrgMode.Internal.Types import Database.OrgMode.Types ------------------------------------------------------------------------------- -- * Retrieval {-| Retrives a clocktable using the given 'HeadingFilter' for all items. See the docs of 'HeadingFilter' for more information about how the filter works. NB: Does not check that the given date range is valid. -} getTable :: (MonadIO m) => HeadingFilter -> ReaderT SqlBackend m ClockTable getTable hedFilter = do rows <- getRows hedFilter return $ ClockTable rows hedFilter {-| Retrieves all 'ClockRow's from the database using the given 'HeadingFilter' for all items. -} getRows :: (MonadIO m) => HeadingFilter -> ReaderT SqlBackend m [ClockRow] getRows hedFilter = shortsToRows `liftM` getShorts hedFilter {-| Retrieves a list of 'HeadingShort' using the given 'HeadingFilter'. The list of 'HeadingShort's have the right hierarchy, and is not just a flat list. The hierarchy is built using the 'mkShortsHierarchy' function. NB: 'Heading's without clocks are ignored. -} getShorts :: (MonadIO m) => HeadingFilter -> ReaderT SqlBackend m [HeadingShort] getShorts hedFilter = (mkShortsHierarchy . map unWrap) `liftM` select q where (HeadingFilter startM endM docIds) = hedFilter q = from $ \(doc, heading, clock) -> do let docId = doc ^. DocumentId hedId = heading ^. HeadingId hedDurM = sum_ (clock ^. ClockDuration) where_ $ heading ^. HeadingDocument ==. docId where_ $ clock ^. ClockHeading ==. hedId whenJust startM $ \startT -> where_ (clock ^. ClockStart >=. val startT) whenJust endM $ \endT -> where_ (clock ^. ClockEnd <=. just (val endT)) unless (null docIds) $ where_ (in_ docId (valList docIds)) groupBy hedId return $ (heading, docId, hedDurM) unWrap :: (Entity Heading, Value (Key Document), Value (Maybe Int)) -> HeadingShort unWrap ((Entity headingId Heading{..}), docId, hedDurM) = let docKey = fromSqlKey (unValue docId) hedKey = fromSqlKey headingId hedParKey = fromSqlKey <$> headingParent dur = maybe 0 id (unValue hedDurM) in HeadingShort docKey hedKey hedParKey headingTitle dur [] ------------------------------------------------------------------------------- -- * Helpers {-| Helper for running a Monadic function on the given value when it is 'Just'. Instead of writing: > case valM of > Just val -> myFunc val > Nothing -> return () You can write: > whenJust valM myFunc And get the same result with less code. -} whenJust :: (Monad m) => Maybe a -- ^ Value to use -> (a -> m ()) -- ^ Function to apply on pure value -> m () whenJust (Just v) f = f v whenJust Nothing _ = return () {-| Takes a flat list of 'HeadingShort's and creates a 'HeadingShort' hierarchy. NB: This function is really naive and inefficient. It probably has time complexity of O(n^∞) and you need a quantum computer to run it. -} mkShortsHierarchy :: [HeadingShort] -> [HeadingShort] mkShortsHierarchy inp = map findChildren $ filter isRoot inp where isRoot :: HeadingShort -> Bool isRoot HeadingShort{..} = case headingShortParId of Nothing -> True _ -> False isChild :: Int64 -> HeadingShort -> Bool isChild currParent HeadingShort{..} = maybe False (currParent ==) headingShortParId findChildren curr@HeadingShort{..} = let subs = map findChildren $ filter (isChild headingShortId) inp in curr{ headingShortSubs = subs } {-| Creates a list of 'ClockRow's from a list of 'HeadingShort'. 'ClockRow's are matched and created from each 'HeadingShort's document ID. NB: This function needs to be run _after_ the 'HeadingShort' hierarchy is created. It should not be run on a flat list. -} shortsToRows :: [HeadingShort] -> [ClockRow] shortsToRows = go emptyMap where emptyMap :: HashMap Int64 [HeadingShort] emptyMap = HM.empty go m [] = map (\(k, v) -> ClockRow k 0 v) (HM.toList m) go m (h:hs) = let newM = HM.insertWith (++) (headingShortDocId h) [h] m in go newM hs
rzetterberg/orgmode-sql
lib/Database/OrgMode/Export/ClockTable.hs
bsd-3-clause
5,556
0
18
1,304
1,029
551
478
-1
-1
{-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE RankNTypes #-} #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702 {-# LANGUAGE Trustworthy #-} {-# LANGUAGE DeriveGeneric #-} #endif {-# LANGUAGE DeriveDataTypeable #-} #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 708 {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE ScopedTypeVariables #-} #endif ----------------------------------------------------------------------------- -- | -- License : BSD-style (see the file LICENSE) -- Maintainer : Edward Kmett <[email protected]> -- Stability : provisional -- Portability : portable -- -- Operations on affine spaces. ----------------------------------------------------------------------------- module Linear.Affine where import Control.Applicative import Control.DeepSeq import Control.Monad (liftM) import Control.Lens import Data.Binary as Binary import Data.Bytes.Serial import Data.Complex (Complex) import Data.Data import Data.Distributive import Data.Foldable as Foldable import Data.Functor.Bind import Data.Functor.Classes import Data.Functor.Rep as Rep import Data.HashMap.Lazy (HashMap) import Data.Hashable import Data.IntMap (IntMap) import Data.Ix import Data.Map (Map) import Data.Serialize as Cereal import Data.Vector (Vector) import Foreign.Storable #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702 import GHC.Generics (Generic) #endif #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 706 import GHC.Generics (Generic1) #endif import Linear.Epsilon import Linear.Metric import Linear.Plucker import Linear.Quaternion import Linear.V import Linear.V0 import Linear.V1 import Linear.V2 import Linear.V3 import Linear.V4 import Linear.Vector #ifdef HLINT {-# ANN module "HLint: ignore Unused LANGUAGE pragma" #-} #endif -- | An affine space is roughly a vector space in which we have -- forgotten or at least pretend to have forgotten the origin. -- -- > a .+^ (b .-. a) = b@ -- > (a .+^ u) .+^ v = a .+^ (u ^+^ v)@ -- > (a .-. b) ^+^ v = (a .+^ v) .-. q@ class Additive (Diff p) => Affine p where type Diff p :: * -> * infixl 6 .-. -- | Get the difference between two points as a vector offset. (.-.) :: Num a => p a -> p a -> Diff p a infixl 6 .+^ -- | Add a vector offset to a point. (.+^) :: Num a => p a -> Diff p a -> p a infixl 6 .-^ -- | Subtract a vector offset from a point. (.-^) :: Num a => p a -> Diff p a -> p a p .-^ v = p .+^ negated v {-# INLINE (.-^) #-} -- | Compute the quadrance of the difference (the square of the distance) qdA :: (Affine p, Foldable (Diff p), Num a) => p a -> p a -> a qdA a b = Foldable.sum (fmap (join (*)) (a .-. b)) {-# INLINE qdA #-} -- | Distance between two points in an affine space distanceA :: (Floating a, Foldable (Diff p), Affine p) => p a -> p a -> a distanceA a b = sqrt (qdA a b) {-# INLINE distanceA #-} #define ADDITIVEC(CTX,T) instance CTX => Affine T where type Diff T = T ; \ (.-.) = (^-^) ; {-# INLINE (.-.) #-} ; (.+^) = (^+^) ; {-# INLINE (.+^) #-} ; \ (.-^) = (^-^) ; {-# INLINE (.-^) #-} #define ADDITIVE(T) ADDITIVEC((), T) ADDITIVE([]) ADDITIVE(Complex) ADDITIVE(ZipList) ADDITIVE(Maybe) ADDITIVE(IntMap) ADDITIVE(Identity) ADDITIVE(Vector) ADDITIVE(V0) ADDITIVE(V1) ADDITIVE(V2) ADDITIVE(V3) ADDITIVE(V4) ADDITIVE(Plucker) ADDITIVE(Quaternion) ADDITIVE(((->) b)) ADDITIVEC(Ord k, (Map k)) ADDITIVEC((Eq k, Hashable k), (HashMap k)) ADDITIVEC(Dim n, (V n)) -- | A handy wrapper to help distinguish points from vectors at the -- type level newtype Point f a = P (f a) deriving ( Eq, Ord, Show, Read, Monad, Functor, Applicative, Foldable , Eq1, Ord1, Show1, Read1 , Traversable, Apply, Additive, Metric , Fractional , Num, Ix, Storable, Epsilon , Hashable #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702 , Generic #endif #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 706 , Generic1 #endif #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 708 , Typeable, Data #endif ) instance NFData (f a) => NFData (Point f a) where rnf (P x) = rnf x instance Serial1 f => Serial1 (Point f) where serializeWith f (P p) = serializeWith f p deserializeWith m = P `liftM` deserializeWith m instance Serial (f a) => Serial (Point f a) where serialize (P p) = serialize p deserialize = P `liftM` deserialize instance Binary (f a) => Binary (Point f a) where put (P p) = Binary.put p get = P `liftM` Binary.get instance Serialize (f a) => Serialize (Point f a) where put (P p) = Cereal.put p get = P `liftM` Cereal.get #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 708 instance forall f. Typeable1 f => Typeable1 (Point f) where typeOf1 _ = mkTyConApp (mkTyCon3 "linear" "Linear.Affine" "Point") [] `mkAppTy` typeOf1 (undefined :: f a) deriving instance (Data (f a), Typeable1 f, Typeable a) => Data (Point f a) #endif lensP :: Lens' (Point g a) (g a) lensP afb (P a) = P <$> afb a {-# INLINE lensP #-} _Point :: Iso' (Point f a) (f a) _Point = iso (\(P a) -> a) P {-# INLINE _Point #-} instance (t ~ Point g b) => Rewrapped (Point f a) t instance Wrapped (Point f a) where type Unwrapped (Point f a) = f a _Wrapped' = _Point {-# INLINE _Wrapped' #-} instance Bind f => Bind (Point f) where join (P m) = P $ join $ fmap (\(P m')->m') m instance Distributive f => Distributive (Point f) where distribute = P . collect (\(P p) -> p) instance Representable f => Representable (Point f) where type Rep (Point f) = Rep f tabulate f = P (tabulate f) {-# INLINE tabulate #-} index (P xs) = Rep.index xs {-# INLINE index #-} type instance Index (Point f a) = Index (f a) type instance IxValue (Point f a) = IxValue (f a) instance Ixed (f a) => Ixed (Point f a) where ix l = lensP . ix l {-# INLINE ix #-} instance Traversable f => Each (Point f a) (Point f b) a b where each = traverse {-# INLINE each #-} instance R1 f => R1 (Point f) where _x = lensP . _x {-# INLINE _x #-} instance R2 f => R2 (Point f) where _y = lensP . _y {-# INLINE _y #-} _xy = lensP . _xy {-# INLINE _xy #-} instance R3 f => R3 (Point f) where _z = lensP . _z {-# INLINE _z #-} _xyz = lensP . _xyz {-# INLINE _xyz #-} instance R4 f => R4 (Point f) where _w = lensP . _w {-# INLINE _w #-} _xyzw = lensP . _xyzw {-# INLINE _xyzw #-} instance Additive f => Affine (Point f) where type Diff (Point f) = f P x .-. P y = x ^-^ y {-# INLINE (.-.) #-} P x .+^ v = P (x ^+^ v) {-# INLINE (.+^) #-} P x .-^ v = P (x ^-^ v) {-# INLINE (.-^) #-} -- | Vector spaces have origins. origin :: (Additive f, Num a) => Point f a origin = P zero -- | An isomorphism between points and vectors, given a reference -- point. relative :: (Additive f, Num a) => Point f a -> Iso' (Point f a) (f a) relative p0 = iso (.-. p0) (p0 .+^) {-# INLINE relative #-}
phaazon/linear
src/Linear/Affine.hs
bsd-3-clause
7,173
2
12
1,468
2,186
1,169
1,017
-1
-1
module Physics.Falling.Collision.Detection.GJK ( distanceToOrigin , distance , algorithmGJK , closestPoints , initialSimplexResult , SimplexResult ) where import Physics.Falling.Math.Error import Physics.Falling.Math.Transform hiding(distance) import Physics.Falling.Math.AnnotatedVector import Physics.Falling.Shape.ImplicitShape import Physics.Falling.Shape.CSO import Physics.Falling.Collision.Detection.Simplex hiding(dimension) import qualified Physics.Falling.Collision.Detection.Simplex as S (dimension) type SimplexResult v = Either (v, [ Double ], Simplex v, Simplex v) -- need more iterations (v, [ Double ], Simplex v) -- success {-# INLINABLE initialSimplexResult #-} initialSimplexResult :: (Dimension v, Vector v, DotProd v) => v -> SimplexResult v initialSimplexResult initialPoint = let initSimplex = addPoint initialPoint emptySimplex in Left (initialPoint, [1.0], initSimplex, initSimplex) {-# INLINABLE distance #-} distance :: (Dimension v , ImplicitShape g1 v , ImplicitShape g2 v , UnitVector v n , Eq v , Fractional v) => g1 -> g2 -> Double distance g1 g2 = distanceToOrigin cso (neg notZeroDirection) where cso = mkCSO g1 g2 -- initialDirection = -- translation t1 &- translation t2 notZeroDirection = 1.0 -- if lensqr initialDirection /= 0.0 then initialDirection -- else 1.0 {-# INLINABLE closestPoints #-} closestPoints :: (Dimension v , ImplicitShape g1 v , ImplicitShape g2 v , UnitVector v n , Eq v , Fractional v) => g1 -> g2 -> Maybe (v, v) closestPoints g1 g2 = case algorithmGJK cso $ initialSimplexResult initialPoint of Nothing -> Nothing Just (_, b, s) -> Just $ _pointsFromAnnotatedSimplex b s where cso = mkAnnotatedCSO g1 g2 -- initialDirection = 1.0 -- translation t1 &- translation t2 notZeroDirection = 1.0 -- if lensqr initialDirection /= 0.0 then initialDirection -- else 1.0 initialPoint = supportPoint cso (AnnotatedVector notZeroDirection undefined) {-# INLINABLE distanceToOrigin #-} distanceToOrigin :: (Dimension v, ImplicitShape g v, Eq v, DotProd v, Fractional v) => g -> v -> Double distanceToOrigin s initialDirection = case algorithmGJK s $ initialSimplexResult initialPoint of Nothing -> 0.0 Just (projection, _, _) -> len projection where initialPoint = supportPoint s initialDirection {-# INLINABLE algorithmGJK #-} algorithmGJK :: (Dimension v, ImplicitShape g v, Eq v, DotProd v) => g -> SimplexResult v -> Maybe (v, [ Double ], Simplex v) algorithmGJK s (Left (projection, barCoords, lastSimplex, newSimplex)) | (sDim == dimension || lensqr projection <= epsTol * maxLen newSimplex) = Nothing | otherwise = algorithmGJK s $ _stepGJK s lastSimplex newSimplex projection barCoords where sDim = S.dimension newSimplex dimension = dim projection algorithmGJK _ (Right (projection, barCoords, simplex)) = Just (projection, barCoords, simplex) {-# INLINABLE _stepGJK #-} _stepGJK :: (ImplicitShape g v, Eq v, DotProd v) => g -> Simplex v -> Simplex v -> v -> [ Double ] -> SimplexResult v _stepGJK s lastSimplex newSimplex v barCoords = if contains csoPoint lastSimplex || sqlenv - v &. csoPoint <= sqEpsRel * sqlenv || lensqr proj > sqlenv then -- we test for inconsistancies: if the new lower bound -- is greater than the old one something went wrong. -- This should actually nether happen and might be an -- implementation bug… Right $ (v, barCoords, newSimplex) -- terminate the algorithm: distance has acceptable precision else Left (proj, projCoords, newSimplex', projSimplex) where sqlenv = lensqr v csoPoint = supportPoint s $ neg v newSimplex' = addPoint csoPoint newSimplex (proj, projCoords, projSimplex) = projectOrigin newSimplex' {-# INLINABLE _pointsFromAnnotatedSimplex #-} _pointsFromAnnotatedSimplex :: (Vector v, DotProd v) => [ Double ] -> Simplex (AnnotatedVector v (v, v)) -> (v, v) _pointsFromAnnotatedSimplex coords simplex = let (pa, pb) = foldr1 (\(a, b) (a', b') -> (a &+ a', b &+ b')) $ zipWith (\coord (a, b) -> (coord *& a, coord *& b)) coords $ map annotation $ points simplex in (pa, neg pb) {-# INLINABLE _pointFromBarycentricCoordinates #-} _pointFromBarycentricCoordinates :: Vector v => [ Double ] -> [ v ] -> v _pointFromBarycentricCoordinates coords pts = foldr1 (&+) $ zipWith (\coord pt -> pt &* coord) coords pts
sebcrozet/falling
Physics/Falling/Collision/Detection/GJK.hs
bsd-3-clause
5,672
0
16
2,080
1,266
690
576
81
2
import Test.QuickCheck main :: IO () main = putStrLn "Test suite not yet implemented"
nozaq/programming-in-haskell
test/Spec.hs
mit
87
0
6
15
24
12
12
3
1
-- | Modular wrapper around Posix signal handlers -- -- This module is only included in the .cabal file when we are not on Windows. module Pos.Infra.Util.SigHandler ( Signal(..) , installHandler , uninstallAllHandlers ) where import Universum import Control.Concurrent (modifyMVar_, withMVar) import qualified Data.Map.Strict as Map import System.IO.Unsafe (unsafePerformIO) import qualified System.Posix.Signals as Posix {------------------------------------------------------------------------------- Enumeratate signals (The unix package doesn't use an enumeration but just uses numbers.) We don't list all supported signals because these are not available on all platforms; instead, we just introduce them when we need them. -------------------------------------------------------------------------------} -- | POSIX signal data Signal = SigHUP deriving (Show, Eq, Ord) toPosixSignal :: Signal -> Posix.Signal toPosixSignal SigHUP = Posix.sigHUP {------------------------------------------------------------------------------- Internal but global state -------------------------------------------------------------------------------} -- | The old Posix handlers (before we installed our own) regOldHandlers :: MVar (Map Signal Posix.Handler) {-# NOINLINE regOldHandlers #-} regOldHandlers = unsafePerformIO $ newMVar Map.empty -- | All globally installed handlers (the ones we call from our Posix handler) regAllHandlers :: MVar (Map Signal [IO ()]) {-# NOINLINE regAllHandlers #-} regAllHandlers = unsafePerformIO $ newMVar Map.empty -- | The actual Posix handler that gets installed and calls all other handlers delegationHandler :: Signal -> IO () delegationHandler signal = sequence_ =<< Map.findWithDefault [] signal <$> readMVar regAllHandlers {------------------------------------------------------------------------------- Public API -------------------------------------------------------------------------------} -- | Install handler for given signal -- -- When multiple handlers are registered they will be called in order of -- invocation. installHandler :: Signal -> IO () -> IO () installHandler signal handler = do -- Install Posix handler if we need to modifyMVar_ regOldHandlers $ \oldHandlers -> if Map.member signal oldHandlers then -- already installed, nothing to do return oldHandlers else do oldHandler <- Posix.installHandler (toPosixSignal signal) (Posix.Catch $ delegationHandler signal) Nothing return $ Map.insert signal oldHandler oldHandlers -- Register the new handler modifyMVar_ regAllHandlers $ return . Map.alter aux signal where aux :: Maybe [IO ()] -> Maybe [IO ()] aux Nothing = Just [handler] aux (Just handlers) = Just (handlers ++ [handler]) -- | Restore all the old Posix handlers -- -- Any registered handlers will simply not be called anymore uninstallAllHandlers :: IO () uninstallAllHandlers = withMVar regOldHandlers $ \oldHandlers -> forM_ (Map.toList oldHandlers) $ \(signal, oldHandler) -> void $ Posix.installHandler (toPosixSignal signal) oldHandler Nothing
input-output-hk/pos-haskell-prototype
infra/src/Pos/Infra/Util/SigHandler.hs
mit
3,250
0
16
609
528
285
243
42
3
{-# LANGUAGE DeriveDataTypeable #-} {- | Module : $Header$ Copyright : (c) Dominik Luecke, Felix Gabriel Mance License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : portable Complexity analysis of OWL2 -} module OWL2.Sublogic where import OWL2.AS import OWL2.MS import OWL2.Sign import OWL2.Morphism import Data.List import Data.Maybe import Data.Data import qualified Data.Set as Set data NumberRestrictions = None | Unqualified | Qualified deriving (Show, Eq, Ord, Typeable, Data) owlDatatypes :: Set.Set Datatype owlDatatypes = predefIRIs data OWLSub = OWLSub { numberRestrictions :: NumberRestrictions , nominals :: Bool , inverseRoles :: Bool , roleTransitivity :: Bool , roleHierarchy :: Bool , complexRoleInclusions :: Bool , addFeatures :: Bool , datatype :: Set.Set Datatype } deriving (Show, Eq, Ord, Typeable, Data) allSublogics :: [[OWLSub]] allSublogics = let t = True b = slBottom in [ [ b { numberRestrictions = Unqualified } , b { numberRestrictions = Qualified } ] , [b { nominals = t } ] , [b { inverseRoles = t } ] , [b { roleTransitivity = t } ] , [b { roleHierarchy = t } ] , [b { complexRoleInclusions = t } ] , [b { addFeatures = t } ] , map (\ d -> b { datatype = Set.singleton d }) $ Set.toList owlDatatypes ] -- | sROIQ(D) slTop :: OWLSub slTop = OWLSub { numberRestrictions = Qualified , nominals = True , inverseRoles = True , roleTransitivity = True , roleHierarchy = True , complexRoleInclusions = True , addFeatures = True , datatype = owlDatatypes } -- | ALC slBottom :: OWLSub slBottom = OWLSub { numberRestrictions = None , nominals = False , inverseRoles = False , roleTransitivity = False , roleHierarchy = False , complexRoleInclusions = False , addFeatures = False , datatype = Set.empty } slMax :: OWLSub -> OWLSub -> OWLSub slMax sl1 sl2 = OWLSub { numberRestrictions = max (numberRestrictions sl1) (numberRestrictions sl2) , nominals = max (nominals sl1) (nominals sl2) , inverseRoles = max (inverseRoles sl1) (inverseRoles sl2) , roleTransitivity = max (roleTransitivity sl1) (roleTransitivity sl2) , roleHierarchy = max (roleHierarchy sl1) (roleHierarchy sl2) , complexRoleInclusions = max (complexRoleInclusions sl1) (complexRoleInclusions sl2) , addFeatures = max (addFeatures sl1) (addFeatures sl2) , datatype = Set.union (datatype sl1) (datatype sl2) } -- | Naming for Description Logics slName :: OWLSub -> String slName sl = (if complexRoleInclusions sl || addFeatures sl then (if addFeatures sl then "s" else "") ++ "R" else (if roleTransitivity sl then "S" else "ALC") ++ if roleHierarchy sl then "H" else "") ++ (if nominals sl then "O" else "") ++ (if inverseRoles sl then "I" else "") ++ (case numberRestrictions sl of Qualified -> "Q" Unqualified -> "N" None -> "") ++ let ds = datatype sl in if Set.null ds then "" else "-D|" ++ (if ds == owlDatatypes then "-|" else intercalate "|" (map printDatatype $ Set.toList ds) ++ "|") requireQualNumberRestrictions :: OWLSub -> OWLSub requireQualNumberRestrictions sl = sl {numberRestrictions = Qualified} requireNumberRestrictions :: OWLSub -> OWLSub requireNumberRestrictions sl = let nr = numberRestrictions sl in sl {numberRestrictions = if nr /= Qualified then Unqualified else nr} requireRoleTransitivity :: OWLSub -> OWLSub requireRoleTransitivity sl = sl {roleTransitivity = True} requireRoleHierarchy :: OWLSub -> OWLSub requireRoleHierarchy sl = sl {roleHierarchy = True} requireComplexRoleInclusions :: OWLSub -> OWLSub requireComplexRoleInclusions sl = (requireRoleHierarchy $ requireRoleTransitivity sl) {complexRoleInclusions = True} requireAddFeatures :: OWLSub -> OWLSub requireAddFeatures sl = (requireComplexRoleInclusions sl) {addFeatures = True} requireNominals :: OWLSub -> OWLSub requireNominals sl = sl {nominals = True} requireInverseRoles :: OWLSub -> OWLSub requireInverseRoles sl = sl {inverseRoles = True} slDatatype :: Datatype -> OWLSub slDatatype dt = slBottom {datatype = if isDatatypeKey dt then Set.singleton $ setDatatypePrefix dt else Set.empty} slObjProp :: ObjectPropertyExpression -> OWLSub slObjProp o = case o of ObjectProp _ -> slBottom ObjectInverseOf _ -> requireInverseRoles slBottom slEntity :: Entity -> OWLSub slEntity (Entity _ et iri) = case et of Datatype -> slDatatype iri _ -> slBottom slDataRange :: DataRange -> OWLSub slDataRange rn = case rn of DataType ur _ -> slDatatype ur DataComplementOf c -> slDataRange c DataOneOf _ -> requireNominals slBottom DataJunction _ drl -> foldl slMax slBottom $ map slDataRange drl slClassExpression :: ClassExpression -> OWLSub slClassExpression des = case des of ObjectJunction _ dec -> foldl slMax slBottom $ map slClassExpression dec ObjectComplementOf dec -> slClassExpression dec ObjectOneOf _ -> requireNominals slBottom ObjectValuesFrom _ o d -> slMax (slObjProp o) (slClassExpression d) ObjectHasSelf o -> requireAddFeatures $ slObjProp o ObjectHasValue o _ -> slObjProp o ObjectCardinality c -> slObjCard c DataValuesFrom _ _ dr -> slDataRange dr DataCardinality c -> slDataCard c _ -> slBottom slDataCard :: Cardinality DataPropertyExpression DataRange -> OWLSub slDataCard (Cardinality _ _ _ x) = requireNumberRestrictions $ case x of Nothing -> slBottom Just y -> slDataRange y slObjCard :: Cardinality ObjectPropertyExpression ClassExpression -> OWLSub slObjCard (Cardinality _ _ op x) = requireNumberRestrictions $ case x of Nothing -> slObjProp op Just y -> slMax (slObjProp op) (slClassExpression y) slLFB :: Maybe Relation -> ListFrameBit -> OWLSub slLFB mr lfb = case lfb of ExpressionBit anl -> foldl slMax slBottom $ map (slClassExpression . snd) anl ObjectBit anl -> slMax (case fromMaybe (error "relation needed") mr of EDRelation Disjoint -> requireAddFeatures slBottom _ -> slBottom) $ foldl slMax slBottom $ map (slObjProp . snd) anl DataBit _ -> case fromMaybe (error "relation needed") mr of EDRelation Disjoint -> requireAddFeatures slBottom _ -> slBottom IndividualSameOrDifferent _ -> requireNominals slBottom ObjectCharacteristics anl -> foldl slMax slBottom $ map ((\ c -> case c of Transitive -> requireRoleTransitivity slBottom Reflexive -> requireAddFeatures slBottom Irreflexive -> requireAddFeatures slBottom Asymmetric -> requireAddFeatures slBottom _ -> slBottom) . snd) anl DataPropRange anl -> foldl slMax slBottom $ map (slDataRange . snd) anl _ -> slBottom slAFB :: AnnFrameBit -> OWLSub slAFB afb = case afb of DatatypeBit dr -> slDataRange dr ClassDisjointUnion cel -> foldl slMax slBottom $ map slClassExpression cel ClassHasKey opl _ -> foldl slMax slBottom $ map slObjProp opl ObjectSubPropertyChain opl -> requireComplexRoleInclusions $ requireRoleHierarchy $ foldl slMax slBottom $ map slObjProp opl _ -> slBottom slFB :: FrameBit -> OWLSub slFB fb = case fb of AnnFrameBit _ afb -> slAFB afb ListFrameBit mr lfb -> slMax (slLFB mr lfb) $ case mr of Nothing -> slBottom Just r -> case r of SubPropertyOf -> requireRoleHierarchy slBottom InverseOf -> requireInverseRoles slBottom _ -> slBottom -- maybe addFeatures ?? slAxiom :: Axiom -> OWLSub slAxiom (PlainAxiom ext fb) = case ext of Misc _ -> slFB fb ClassEntity ce -> slMax (slFB fb) (slClassExpression ce) ObjectEntity o -> slMax (slFB fb) (slObjProp o) SimpleEntity e -> slMax (slEntity e) (slFB fb) slFrame :: Frame -> OWLSub slFrame = foldl slMax slBottom . map slAxiom . getAxioms slODoc :: OntologyDocument -> OWLSub slODoc = foldl slMax slBottom . map slFrame . ontFrames . ontology slSig :: Sign -> OWLSub slSig sig = let dts = Set.toList $ datatypes sig in if Set.size (dataProperties sig) == 0 && null dts then slBottom else foldl slMax slBottom $ map slDatatype dts slMor :: OWLMorphism -> OWLSub slMor mor = slMax (slSig $ osource mor) $ slSig $ otarget mor -- projections along sublogics prMor :: OWLSub -> OWLMorphism -> OWLMorphism prMor s a = a { osource = prSig s $ osource a , otarget = prSig s $ otarget a } prSig :: OWLSub -> Sign -> Sign prSig s a = if datatype s == Set.empty then a {datatypes = Set.empty, dataProperties = Set.empty} else a prODoc :: OWLSub -> OntologyDocument -> OntologyDocument prODoc s a = let o = (ontology a) {ontFrames = filter ((s >=) . slFrame) $ ontFrames $ ontology a } in a {ontology = o}
keithodulaigh/Hets
OWL2/Sublogic.hs
gpl-2.0
8,944
0
17
2,028
2,737
1,416
1,321
204
13
{-# LANGUAGE StrictData #-} {-# LANGUAGE Trustworthy #-} module Network.Tox.NodeInfo.NodeInfoSpec where import Test.Hspec import qualified Data.Binary as Binary (get) import qualified Data.Binary.Get as Binary (Get) import Data.Proxy (Proxy (..)) import Network.Tox.EncodingSpec import Network.Tox.NodeInfo.NodeInfo (NodeInfo) spec :: Spec spec = do rpcSpec (Proxy :: Proxy NodeInfo) binarySpec (Proxy :: Proxy NodeInfo) readShowSpec (Proxy :: Proxy NodeInfo) it "should handle invalid packets as failures" $ do expectDecoderFailure [0x20] "Invalid address family: 32" expectDecoderFailure [0xa0] "Invalid address family: 32" expectDecoderFailure [0x00] "Invalid address family: 0" expectDecoderFailure [0x01] "Invalid address family: 1" where expectDecoderFailure = expectDecoderFail (Binary.get :: Binary.Get NodeInfo)
iphydf/hs-toxcore
test/Network/Tox/NodeInfo/NodeInfoSpec.hs
gpl-3.0
955
0
11
230
206
114
92
21
1
-- | -- Module : Criterion.Main -- Copyright : (c) 2009-2014 Bryan O'Sullivan -- -- License : BSD-style -- Maintainer : [email protected] -- Stability : experimental -- Portability : GHC -- -- Wrappers for compiling and running benchmarks quickly and easily. -- See 'defaultMain' below for an example. module Criterion.Main ( -- * How to write benchmarks -- $bench -- ** Benchmarking IO actions -- $io -- ** Benchmarking pure code -- $pure -- ** Fully evaluating a result -- $rnf -- * Types Benchmarkable , Benchmark -- * Creating a benchmark suite , env , bench , bgroup -- ** Running a benchmark , nf , whnf , nfIO , whnfIO -- * Turning a suite of benchmarks into a program , defaultMain , defaultMainWith , defaultConfig -- * Other useful code , makeMatcher ) where import Control.Monad (unless) import Control.Monad.Trans (liftIO) import Criterion.IO.Printf (printError, writeCsv) import Criterion.Internal (runAndAnalyse, runFixedIters) import Criterion.Main.Options (MatchType(..), Mode(..), defaultConfig, describe, versionInfo) import Criterion.Measurement (initializeTime, initializeRAPL, finishRAPL) import Criterion.Monad (withConfig) import Criterion.Types import Data.List (isPrefixOf, sort, stripPrefix) import Data.Maybe (fromMaybe) import Options.Applicative (execParser) import System.Environment (getProgName) import System.Exit (ExitCode(..), exitWith) import System.FilePath.Glob -- | An entry point that can be used as a @main@ function. -- -- > import Criterion.Main -- > -- > fib :: Int -> Int -- > fib 0 = 0 -- > fib 1 = 1 -- > fib n = fib (n-1) + fib (n-2) -- > -- > main = defaultMain [ -- > bgroup "fib" [ bench "10" $ whnf fib 10 -- > , bench "35" $ whnf fib 35 -- > , bench "37" $ whnf fib 37 -- > ] -- > ] defaultMain :: [Benchmark] -> IO () defaultMain = defaultMainWith defaultConfig -- | Create a function that can tell if a name given on the command -- line matches a benchmark. makeMatcher :: MatchType -> [String] -- ^ Command line arguments. -> Either String (String -> Bool) makeMatcher matchKind args = case matchKind of Prefix -> Right $ \b -> null args || any (`isPrefixOf` b) args Glob -> let compOptions = compDefault { errorRecovery = False } in case mapM (tryCompileWith compOptions) args of Left errMsg -> Left . fromMaybe errMsg . stripPrefix "compile :: " $ errMsg Right ps -> Right $ \b -> null ps || any (`match` b) ps selectBenches :: MatchType -> [String] -> Benchmark -> IO (String -> Bool) selectBenches matchType benches bsgroup = do toRun <- either parseError return . makeMatcher matchType $ benches unless (null benches || any toRun (benchNames bsgroup)) $ parseError "none of the specified names matches a benchmark" return toRun -- | An entry point that can be used as a @main@ function, with -- configurable defaults. -- -- Example: -- -- > import Criterion.Main.Options -- > import Criterion.Main -- > -- > myConfig = defaultConfig { -- > -- Do not GC between runs. -- > forceGC = False -- > } -- > -- > main = defaultMainWith myConfig [ -- > bench "fib 30" $ whnf fib 30 -- > ] -- -- If you save the above example as @\"Fib.hs\"@, you should be able -- to compile it as follows: -- -- > ghc -O --make Fib -- -- Run @\"Fib --help\"@ on the command line to get a list of command -- line options. defaultMainWith :: Config -> [Benchmark] -> IO () defaultMainWith defCfg bs = do wat <- execParser (describe defCfg) let bsgroup = BenchGroup "" bs case wat of List -> mapM_ putStrLn . sort . concatMap benchNames $ bs Version -> putStrLn versionInfo OnlyRun iters matchType benches -> do shouldRun <- selectBenches matchType benches bsgroup withConfig defaultConfig $ runFixedIters iters shouldRun bsgroup Run cfg matchType benches -> do shouldRun <- selectBenches matchType benches bsgroup withConfig cfg $ do writeCsv ("Name","Mean","MeanLB","MeanUB","Stddev","StddevLB", "StddevUB") liftIO initializeTime liftIO initializeRAPL runAndAnalyse shouldRun bsgroup liftIO finishRAPL -- | Display an error message from a command line parsing failure, and -- exit. parseError :: String -> IO a parseError msg = do _ <- printError "Error: %s\n" msg _ <- printError "Run \"%s --help\" for usage information\n" =<< getProgName exitWith (ExitFailure 64) -- $bench -- -- The 'Benchmarkable' type is a container for code that can be -- benchmarked. The value inside must run a benchmark the given -- number of times. We are most interested in benchmarking two -- things: -- -- * 'IO' actions. Any 'IO' action can be benchmarked directly. -- -- * Pure functions. GHC optimises aggressively when compiling with -- @-O@, so it is easy to write innocent-looking benchmark code that -- doesn't measure the performance of a pure function at all. We -- work around this by benchmarking both a function and its final -- argument together. -- $io -- -- Any 'IO' action can be benchmarked easily if its type resembles -- this: -- -- @ -- 'IO' a -- @ -- $pure -- -- Because GHC optimises aggressively when compiling with @-O@, it is -- potentially easy to write innocent-looking benchmark code that will -- only be evaluated once, for which all but the first iteration of -- the timing loop will be timing the cost of doing nothing. -- -- To work around this, we provide two functions for benchmarking pure -- code. -- -- The first will cause results to be fully evaluated to normal form -- (NF): -- -- @ -- 'nf' :: 'NFData' b => (a -> b) -> a -> 'Benchmarkable' -- @ -- -- The second will cause results to be evaluated to weak head normal -- form (the Haskell default): -- -- @ -- 'whnf' :: (a -> b) -> a -> 'Benchmarkable' -- @ -- -- As both of these types suggest, when you want to benchmark a -- function, you must supply two values: -- -- * The first element is the function, saturated with all but its -- last argument. -- -- * The second element is the last argument to the function. -- -- Here is an example that makes the use of these functions clearer. -- Suppose we want to benchmark the following function: -- -- @ -- firstN :: Int -> [Int] -- firstN k = take k [(0::Int)..] -- @ -- -- So in the easy case, we construct a benchmark as follows: -- -- @ -- 'nf' firstN 1000 -- @ -- $rnf -- -- The 'whnf' harness for evaluating a pure function only evaluates -- the result to weak head normal form (WHNF). If you need the result -- evaluated all the way to normal form, use the 'nf' function to -- force its complete evaluation. -- -- Using the @firstN@ example from earlier, to naive eyes it might -- /appear/ that the following code ought to benchmark the production -- of the first 1000 list elements: -- -- @ -- 'whnf' firstN 1000 -- @ -- -- Since we are using 'whnf', in this case the result will only be -- forced until it reaches WHNF, so what this would /actually/ -- benchmark is merely how long it takes to produce the first list -- element!
paulolieuthier/criterion
Criterion/Main.hs
bsd-2-clause
7,392
0
17
1,787
981
584
397
77
4
------------------------------------------------------------------------------- -- -- Module : Yesod.Feed -- Copyright : Patrick Brisbin -- License : as-is -- -- Maintainer : Patrick Brisbin <[email protected]> -- Stability : Stable -- Portability : Portable -- -- Generic Feed and Feed Entry data types that can be used as either an -- Rss feed or an Atom feed (or both, or other). -- -- Atom spec: <http://en.wikipedia.org/wiki/Atom_(standard)> -- Rss spec: <http://www.rssboard.org/rss-specification> -- ------------------------------------------------------------------------------- module Yesod.Feed ( newsFeed , RepAtomRss (..) , module Yesod.FeedTypes ) where import Yesod.FeedTypes import Yesod.AtomFeed import Yesod.RssFeed import Yesod.Content (HasReps (chooseRep), typeAtom, typeRss) import Yesod.Core (Route, GHandler) data RepAtomRss = RepAtomRss RepAtom RepRss instance HasReps RepAtomRss where chooseRep (RepAtomRss (RepAtom a) (RepRss r)) = chooseRep [ (typeAtom, a) , (typeRss, r) ] newsFeed :: Feed (Route master) -> GHandler sub master RepAtomRss newsFeed f = do a <- atomFeed f r <- rssFeed f return $ RepAtomRss a r
chreekat/yesod
yesod-newsfeed/Yesod/Feed.hs
bsd-2-clause
1,220
0
10
233
222
129
93
19
1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1998 \section[PatSyn]{@PatSyn@: Pattern synonyms} -} {-# LANGUAGE CPP #-} module PatSyn ( -- * Main data types PatSyn, mkPatSyn, -- ** Type deconstruction patSynName, patSynArity, patSynIsInfix, patSynArgs, patSynMatcher, patSynBuilder, patSynUnivTyVarBinders, patSynExTyVars, patSynExTyVarBinders, patSynSig, patSynInstArgTys, patSynInstResTy, patSynFieldLabels, patSynFieldType, tidyPatSynIds, pprPatSynType ) where #include "HsVersions.h" import GhcPrelude import Type import Name import Outputable import Unique import Util import BasicTypes import Var import FieldLabel import qualified Data.Data as Data import Data.Function import Data.List {- ************************************************************************ * * \subsection{Pattern synonyms} * * ************************************************************************ -} -- | Pattern Synonym -- -- See Note [Pattern synonym representation] -- See Note [Pattern synonym signature contexts] data PatSyn = MkPatSyn { psName :: Name, psUnique :: Unique, -- Cached from Name psArgs :: [Type], psArity :: Arity, -- == length psArgs psInfix :: Bool, -- True <=> declared infix psFieldLabels :: [FieldLabel], -- List of fields for a -- record pattern synonym -- INVARIANT: either empty if no -- record pat syn or same length as -- psArgs -- Universally-quantified type variables psUnivTyVars :: [TyVarBinder], -- Required dictionaries (may mention psUnivTyVars) psReqTheta :: ThetaType, -- Existentially-quantified type vars psExTyVars :: [TyVarBinder], -- Provided dictionaries (may mention psUnivTyVars or psExTyVars) psProvTheta :: ThetaType, -- Result type psResultTy :: Type, -- Mentions only psUnivTyVars -- See Note [Pattern synonym result type] -- See Note [Matchers and builders for pattern synonyms] psMatcher :: (Id, Bool), -- Matcher function. -- If Bool is True then prov_theta and arg_tys are empty -- and type is -- forall (p :: RuntimeRep) (r :: TYPE p) univ_tvs. -- req_theta -- => res_ty -- -> (forall ex_tvs. Void# -> r) -- -> (Void# -> r) -- -> r -- -- Otherwise type is -- forall (p :: RuntimeRep) (r :: TYPE r) univ_tvs. -- req_theta -- => res_ty -- -> (forall ex_tvs. prov_theta => arg_tys -> r) -- -> (Void# -> r) -- -> r psBuilder :: Maybe (Id, Bool) -- Nothing => uni-directional pattern synonym -- Just (builder, is_unlifted) => bi-directional -- Builder function, of type -- forall univ_tvs, ex_tvs. (req_theta, prov_theta) -- => arg_tys -> res_ty -- See Note [Builder for pattern synonyms with unboxed type] } {- Note [Pattern synonym signature contexts] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In a pattern synonym signature we write pattern P :: req => prov => t1 -> ... tn -> res_ty Note that the "required" context comes first, then the "provided" context. Moreover, the "required" context must not mention existentially-bound type variables; that is, ones not mentioned in res_ty. See lots of discussion in Trac #10928. If there is no "provided" context, you can omit it; but you can't omit the "required" part (unless you omit both). Example 1: pattern P1 :: (Num a, Eq a) => b -> Maybe (a,b) pattern P1 x = Just (3,x) We require (Num a, Eq a) to match the 3; there is no provided context. Example 2: data T2 where MkT2 :: (Num a, Eq a) => a -> a -> T2 pattern P2 :: () => (Num a, Eq a) => a -> T2 pattern P2 x = MkT2 3 x When we match against P2 we get a Num dictionary provided. We can use that to check the match against 3. Example 3: pattern P3 :: Eq a => a -> b -> T3 b This signature is illegal because the (Eq a) is a required constraint, but it mentions the existentially-bound variable 'a'. You can see it's existential because it doesn't appear in the result type (T3 b). Note [Pattern synonym result type] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider data T a b = MkT b a pattern P :: a -> T [a] Bool pattern P x = MkT True [x] P's psResultTy is (T a Bool), and it really only matches values of type (T [a] Bool). For example, this is ill-typed f :: T p q -> String f (P x) = "urk" This is differnet to the situation with GADTs: data S a where MkS :: Int -> S Bool Now MkS (and pattern synonyms coming from MkS) can match a value of type (S a), not just (S Bool); we get type refinement. That in turn means that if you have a pattern P x :: T [ty] Bool it's not entirely straightforward to work out the instantiation of P's universal tyvars. You have to /match/ the type of the pattern, (T [ty] Bool) against the psResultTy for the pattern synonym, T [a] Bool to get the instantiation a := ty. This is very unlike DataCons, where univ tyvars match 1-1 the arguments of the TyCon. Note [Pattern synonym representation] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider the following pattern synonym declaration pattern P x = MkT [x] (Just 42) where data T a where MkT :: (Show a, Ord b) => [b] -> a -> T a so pattern P has type b -> T (Maybe t) with the following typeclass constraints: requires: (Eq t, Num t) provides: (Show (Maybe t), Ord b) In this case, the fields of MkPatSyn will be set as follows: psArgs = [b] psArity = 1 psInfix = False psUnivTyVars = [t] psExTyVars = [b] psProvTheta = (Show (Maybe t), Ord b) psReqTheta = (Eq t, Num t) psResultTy = T (Maybe t) Note [Matchers and builders for pattern synonyms] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For each pattern synonym P, we generate * a "matcher" function, used to desugar uses of P in patterns, which implements pattern matching * A "builder" function (for bidirectional pattern synonyms only), used to desugar uses of P in expressions, which constructs P-values. For the above example, the matcher function has type: $mP :: forall (r :: ?) t. (Eq t, Num t) => T (Maybe t) -> (forall b. (Show (Maybe t), Ord b) => b -> r) -> (Void# -> r) -> r with the following implementation: $mP @r @t $dEq $dNum scrut cont fail = case scrut of MkT @b $dShow $dOrd [x] (Just 42) -> cont @b $dShow $dOrd x _ -> fail Void# Notice that the return type 'r' has an open kind, so that it can be instantiated by an unboxed type; for example where we see f (P x) = 3# The extra Void# argument for the failure continuation is needed so that it is lazy even when the result type is unboxed. For the same reason, if the pattern has no arguments, an extra Void# argument is added to the success continuation as well. For *bidirectional* pattern synonyms, we also generate a "builder" function which implements the pattern synonym in an expression context. For our running example, it will be: $bP :: forall t b. (Eq t, Num t, Show (Maybe t), Ord b) => b -> T (Maybe t) $bP x = MkT [x] (Just 42) NB: the existential/universal and required/provided split does not apply to the builder since you are only putting stuff in, not getting stuff out. Injectivity of bidirectional pattern synonyms is checked in tcPatToExpr which walks the pattern and returns its corresponding expression when available. Note [Builder for pattern synonyms with unboxed type] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For bidirectional pattern synonyms that have no arguments and have an unboxed type, we add an extra Void# argument to the builder, else it would be a top-level declaration with an unboxed type. pattern P = 0# $bP :: Void# -> Int# $bP _ = 0# This means that when typechecking an occurrence of P in an expression, we must remember that the builder has this void argument. This is done by TcPatSyn.patSynBuilderOcc. Note [Pattern synonyms and the data type Type] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The type of a pattern synonym is of the form (See Note [Pattern synonym signatures] in TcSigs): forall univ_tvs. req => forall ex_tvs. prov => ... We cannot in general represent this by a value of type Type: - if ex_tvs is empty, then req and prov cannot be distinguished from each other - if req is empty, then univ_tvs and ex_tvs cannot be distinguished from each other, and moreover, prov is seen as the "required" context (as it is the only context) ************************************************************************ * * \subsection{Instances} * * ************************************************************************ -} instance Eq PatSyn where (==) = (==) `on` getUnique (/=) = (/=) `on` getUnique instance Uniquable PatSyn where getUnique = psUnique instance NamedThing PatSyn where getName = patSynName instance Outputable PatSyn where ppr = ppr . getName instance OutputableBndr PatSyn where pprInfixOcc = pprInfixName . getName pprPrefixOcc = pprPrefixName . getName instance Data.Data PatSyn where -- don't traverse? toConstr _ = abstractConstr "PatSyn" gunfold _ _ = error "gunfold" dataTypeOf _ = mkNoRepType "PatSyn" {- ************************************************************************ * * \subsection{Construction} * * ************************************************************************ -} -- | Build a new pattern synonym mkPatSyn :: Name -> Bool -- ^ Is the pattern synonym declared infix? -> ([TyVarBinder], ThetaType) -- ^ Universially-quantified type variables -- and required dicts -> ([TyVarBinder], ThetaType) -- ^ Existentially-quantified type variables -- and provided dicts -> [Type] -- ^ Original arguments -> Type -- ^ Original result type -> (Id, Bool) -- ^ Name of matcher -> Maybe (Id, Bool) -- ^ Name of builder -> [FieldLabel] -- ^ Names of fields for -- a record pattern synonym -> PatSyn -- NB: The univ and ex vars are both in TyBinder form and TyVar form for -- convenience. All the TyBinders should be Named! mkPatSyn name declared_infix (univ_tvs, req_theta) (ex_tvs, prov_theta) orig_args orig_res_ty matcher builder field_labels = MkPatSyn {psName = name, psUnique = getUnique name, psUnivTyVars = univ_tvs, psExTyVars = ex_tvs, psProvTheta = prov_theta, psReqTheta = req_theta, psInfix = declared_infix, psArgs = orig_args, psArity = length orig_args, psResultTy = orig_res_ty, psMatcher = matcher, psBuilder = builder, psFieldLabels = field_labels } -- | The 'Name' of the 'PatSyn', giving it a unique, rooted identification patSynName :: PatSyn -> Name patSynName = psName -- | Should the 'PatSyn' be presented infix? patSynIsInfix :: PatSyn -> Bool patSynIsInfix = psInfix -- | Arity of the pattern synonym patSynArity :: PatSyn -> Arity patSynArity = psArity patSynArgs :: PatSyn -> [Type] patSynArgs = psArgs patSynFieldLabels :: PatSyn -> [FieldLabel] patSynFieldLabels = psFieldLabels -- | Extract the type for any given labelled field of the 'DataCon' patSynFieldType :: PatSyn -> FieldLabelString -> Type patSynFieldType ps label = case find ((== label) . flLabel . fst) (psFieldLabels ps `zip` psArgs ps) of Just (_, ty) -> ty Nothing -> pprPanic "dataConFieldType" (ppr ps <+> ppr label) patSynUnivTyVarBinders :: PatSyn -> [TyVarBinder] patSynUnivTyVarBinders = psUnivTyVars patSynExTyVars :: PatSyn -> [TyVar] patSynExTyVars ps = binderVars (psExTyVars ps) patSynExTyVarBinders :: PatSyn -> [TyVarBinder] patSynExTyVarBinders = psExTyVars patSynSig :: PatSyn -> ([TyVar], ThetaType, [TyVar], ThetaType, [Type], Type) patSynSig (MkPatSyn { psUnivTyVars = univ_tvs, psExTyVars = ex_tvs , psProvTheta = prov, psReqTheta = req , psArgs = arg_tys, psResultTy = res_ty }) = (binderVars univ_tvs, req, binderVars ex_tvs, prov, arg_tys, res_ty) patSynMatcher :: PatSyn -> (Id,Bool) patSynMatcher = psMatcher patSynBuilder :: PatSyn -> Maybe (Id, Bool) patSynBuilder = psBuilder tidyPatSynIds :: (Id -> Id) -> PatSyn -> PatSyn tidyPatSynIds tidy_fn ps@(MkPatSyn { psMatcher = matcher, psBuilder = builder }) = ps { psMatcher = tidy_pr matcher, psBuilder = fmap tidy_pr builder } where tidy_pr (id, dummy) = (tidy_fn id, dummy) patSynInstArgTys :: PatSyn -> [Type] -> [Type] -- Return the types of the argument patterns -- e.g. data D a = forall b. MkD a b (b->a) -- pattern P f x y = MkD (x,True) y f -- D :: forall a. forall b. a -> b -> (b->a) -> D a -- P :: forall c. forall b. (b->(c,Bool)) -> c -> b -> P c -- patSynInstArgTys P [Int,bb] = [bb->(Int,Bool), Int, bb] -- NB: the inst_tys should be both universal and existential patSynInstArgTys (MkPatSyn { psName = name, psUnivTyVars = univ_tvs , psExTyVars = ex_tvs, psArgs = arg_tys }) inst_tys = ASSERT2( tyvars `equalLength` inst_tys , text "patSynInstArgTys" <+> ppr name $$ ppr tyvars $$ ppr inst_tys ) map (substTyWith tyvars inst_tys) arg_tys where tyvars = binderVars (univ_tvs ++ ex_tvs) patSynInstResTy :: PatSyn -> [Type] -> Type -- Return the type of whole pattern -- E.g. pattern P x y = Just (x,x,y) -- P :: a -> b -> Just (a,a,b) -- (patSynInstResTy P [Int,Bool] = Maybe (Int,Int,Bool) -- NB: unlike patSynInstArgTys, the inst_tys should be just the *universal* tyvars patSynInstResTy (MkPatSyn { psName = name, psUnivTyVars = univ_tvs , psResultTy = res_ty }) inst_tys = ASSERT2( univ_tvs `equalLength` inst_tys , text "patSynInstResTy" <+> ppr name $$ ppr univ_tvs $$ ppr inst_tys ) substTyWith (binderVars univ_tvs) inst_tys res_ty -- | Print the type of a pattern synonym. The foralls are printed explicitly pprPatSynType :: PatSyn -> SDoc pprPatSynType (MkPatSyn { psUnivTyVars = univ_tvs, psReqTheta = req_theta , psExTyVars = ex_tvs, psProvTheta = prov_theta , psArgs = orig_args, psResultTy = orig_res_ty }) = sep [ pprForAll univ_tvs , pprThetaArrowTy req_theta , ppWhen insert_empty_ctxt $ parens empty <+> darrow , pprType sigma_ty ] where sigma_ty = mkForAllTys ex_tvs $ mkFunTys prov_theta $ mkFunTys orig_args orig_res_ty insert_empty_ctxt = null req_theta && not (null prov_theta && null ex_tvs)
shlevy/ghc
compiler/basicTypes/PatSyn.hs
bsd-3-clause
16,364
0
14
5,031
1,530
915
615
141
2
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE ConstraintKinds #-} module Stack.Types.Package where import Stack.Prelude import qualified RIO.Text as T import Data.Aeson (ToJSON (..), FromJSON (..), (.=), (.:), object, withObject) import qualified Data.Map as M import qualified Data.Set as Set import Distribution.Parsec (PError (..), PWarning (..), showPos) import qualified Distribution.SPDX.License as SPDX import Distribution.License (License) import Distribution.ModuleName (ModuleName) import Distribution.PackageDescription (TestSuiteInterface, BuildType) import Distribution.System (Platform (..)) import Stack.Types.Compiler import Stack.Types.Config import Stack.Types.GhcPkgId import Stack.Types.NamedComponent import Stack.Types.SourceMap import Stack.Types.Version -- | All exceptions thrown by the library. data PackageException = PackageInvalidCabalFile !(Either PackageIdentifierRevision (Path Abs File)) !(Maybe Version) ![PError] ![PWarning] | MismatchedCabalIdentifier !PackageIdentifierRevision !PackageIdentifier deriving Typeable instance Exception PackageException instance Show PackageException where show (PackageInvalidCabalFile loc _mversion errs warnings) = concat [ "Unable to parse cabal file " , case loc of Left pir -> "for " ++ T.unpack (utf8BuilderToText (display pir)) Right fp -> toFilePath fp {- Not actually needed, the errors will indicate if a newer version exists. Also, it seems that this is set to Just the version even if we support it. , case mversion of Nothing -> "" Just version -> "\nRequires newer Cabal file parser version: " ++ versionString version -} , "\n\n" , unlines $ map (\(PError pos msg) -> concat [ "- " , showPos pos , ": " , msg ]) errs , unlines $ map (\(PWarning _ pos msg) -> concat [ "- " , showPos pos , ": " , msg ]) warnings ] show (MismatchedCabalIdentifier pir ident) = concat [ "Mismatched package identifier." , "\nFound: " , packageIdentifierString ident , "\nExpected: " , T.unpack $ utf8BuilderToText $ display pir ] -- | Libraries in a package. Since Cabal 2.0, internal libraries are a -- thing. data PackageLibraries = NoLibraries | HasLibraries !(Set Text) -- ^ the foreign library names, sub libraries get built automatically without explicit component name passing deriving (Show,Typeable) -- | Name of an executable. newtype ExeName = ExeName { unExeName :: Text } deriving (Show, Eq, Ord, Hashable, IsString, Generic, NFData, Data, Typeable) -- | Some package info. data Package = Package {packageName :: !PackageName -- ^ Name of the package. ,packageVersion :: !Version -- ^ Version of the package ,packageLicense :: !(Either SPDX.License License) -- ^ The license the package was released under. ,packageFiles :: !GetPackageFiles -- ^ Get all files of the package. ,packageDeps :: !(Map PackageName DepValue) -- ^ Packages that the package depends on, both as libraries and build tools. ,packageUnknownTools :: !(Set ExeName) -- ^ Build tools specified in the legacy manner (build-tools:) that failed the hard-coded lookup. ,packageAllDeps :: !(Set PackageName) -- ^ Original dependencies (not sieved). ,packageGhcOptions :: ![Text] -- ^ Ghc options used on package. ,packageCabalConfigOpts :: ![Text] -- ^ Additional options passed to ./Setup.hs configure ,packageFlags :: !(Map FlagName Bool) -- ^ Flags used on package. ,packageDefaultFlags :: !(Map FlagName Bool) -- ^ Defaults for unspecified flags. ,packageLibraries :: !PackageLibraries -- ^ does the package have a buildable library stanza? ,packageInternalLibraries :: !(Set Text) -- ^ names of internal libraries ,packageTests :: !(Map Text TestSuiteInterface) -- ^ names and interfaces of test suites ,packageBenchmarks :: !(Set Text) -- ^ names of benchmarks ,packageExes :: !(Set Text) -- ^ names of executables ,packageOpts :: !GetPackageOpts -- ^ Args to pass to GHC. ,packageHasExposedModules :: !Bool -- ^ Does the package have exposed modules? ,packageBuildType :: !BuildType -- ^ Package build-type. ,packageSetupDeps :: !(Maybe (Map PackageName VersionRange)) -- ^ If present: custom-setup dependencies ,packageCabalSpec :: !VersionRange -- ^ Cabal spec range } deriving (Show,Typeable) packageIdent :: Package -> PackageIdentifier packageIdent p = PackageIdentifier (packageName p) (packageVersion p) -- | The value for a map from dependency name. This contains both the -- version range and the type of dependency, and provides a semigroup -- instance. data DepValue = DepValue { dvVersionRange :: !VersionRange , dvType :: !DepType } deriving (Show,Typeable) instance Semigroup DepValue where DepValue a x <> DepValue b y = DepValue (intersectVersionRanges a b) (x <> y) -- | Is this package being used as a library, or just as a build tool? -- If the former, we need to ensure that a library actually -- exists. See -- <https://github.com/commercialhaskell/stack/issues/2195> data DepType = AsLibrary | AsBuildTool deriving (Show, Eq) instance Semigroup DepType where AsLibrary <> _ = AsLibrary AsBuildTool <> x = x packageIdentifier :: Package -> PackageIdentifier packageIdentifier pkg = PackageIdentifier (packageName pkg) (packageVersion pkg) packageDefinedFlags :: Package -> Set FlagName packageDefinedFlags = M.keysSet . packageDefaultFlags type InstallMap = Map PackageName (InstallLocation, Version) -- | Files that the package depends on, relative to package directory. -- Argument is the location of the .cabal file newtype GetPackageOpts = GetPackageOpts { getPackageOpts :: forall env. HasEnvConfig env => InstallMap -> InstalledMap -> [PackageName] -> [PackageName] -> Path Abs File -> RIO env (Map NamedComponent (Map ModuleName (Path Abs File)) ,Map NamedComponent [DotCabalPath] ,Map NamedComponent BuildInfoOpts) } instance Show GetPackageOpts where show _ = "<GetPackageOpts>" -- | GHC options based on cabal information and ghc-options. data BuildInfoOpts = BuildInfoOpts { bioOpts :: [String] , bioOneWordOpts :: [String] , bioPackageFlags :: [String] -- ^ These options can safely have 'nubOrd' applied to them, as -- there are no multi-word options (see -- https://github.com/commercialhaskell/stack/issues/1255) , bioCabalMacros :: Path Abs File } deriving Show -- | Files to get for a cabal package. data CabalFileType = AllFiles | Modules -- | Files that the package depends on, relative to package directory. -- Argument is the location of the .cabal file newtype GetPackageFiles = GetPackageFiles { getPackageFiles :: forall env. HasEnvConfig env => Path Abs File -> RIO env (Map NamedComponent (Map ModuleName (Path Abs File)) ,Map NamedComponent [DotCabalPath] ,Set (Path Abs File) ,[PackageWarning]) } instance Show GetPackageFiles where show _ = "<GetPackageFiles>" -- | Warning generated when reading a package data PackageWarning = UnlistedModulesWarning NamedComponent [ModuleName] -- ^ Modules found that are not listed in cabal file -- TODO: bring this back - see -- https://github.com/commercialhaskell/stack/issues/2649 {- | MissingModulesWarning (Path Abs File) (Maybe String) [ModuleName] -- ^ Modules not found in file system, which are listed in cabal file -} -- | Package build configuration data PackageConfig = PackageConfig {packageConfigEnableTests :: !Bool -- ^ Are tests enabled? ,packageConfigEnableBenchmarks :: !Bool -- ^ Are benchmarks enabled? ,packageConfigFlags :: !(Map FlagName Bool) -- ^ Configured flags. ,packageConfigGhcOptions :: ![Text] -- ^ Configured ghc options. ,packageConfigCabalConfigOpts :: ![Text] -- ^ ./Setup.hs configure options ,packageConfigCompilerVersion :: ActualCompiler -- ^ GHC version ,packageConfigPlatform :: !Platform -- ^ host platform } deriving (Show,Typeable) -- | Compares the package name. instance Ord Package where compare = on compare packageName -- | Compares the package name. instance Eq Package where (==) = on (==) packageName -- | Where the package's source is located: local directory or package index data PackageSource = PSFilePath LocalPackage -- ^ Package which exist on the filesystem | PSRemote PackageLocationImmutable Version FromSnapshot CommonPackage -- ^ Package which is downloaded remotely. instance Show PackageSource where show (PSFilePath lp) = concat ["PSFilePath (", show lp, ")"] show (PSRemote pli v fromSnapshot _) = concat [ "PSRemote" , "(", show pli, ")" , "(", show v, ")" , show fromSnapshot , "<CommonPackage>" ] psVersion :: PackageSource -> Version psVersion (PSFilePath lp) = packageVersion $ lpPackage lp psVersion (PSRemote _ v _ _) = v -- | Information on a locally available package of source code data LocalPackage = LocalPackage { lpPackage :: !Package -- ^ The @Package@ info itself, after resolution with package flags, -- with tests and benchmarks disabled , lpComponents :: !(Set NamedComponent) -- ^ Components to build, not including the library component. , lpUnbuildable :: !(Set NamedComponent) -- ^ Components explicitly requested for build, that are marked -- "buildable: false". , lpWanted :: !Bool -- FIXME Should completely drop this "wanted" terminology, it's unclear -- ^ Whether this package is wanted as a target. , lpTestDeps :: !(Map PackageName VersionRange) -- ^ Used for determining if we can use --enable-tests in a normal build. , lpBenchDeps :: !(Map PackageName VersionRange) -- ^ Used for determining if we can use --enable-benchmarks in a normal -- build. , lpTestBench :: !(Maybe Package) -- ^ This stores the 'Package' with tests and benchmarks enabled, if -- either is asked for by the user. , lpCabalFile :: !(Path Abs File) -- ^ The .cabal file , lpBuildHaddocks :: !Bool , lpForceDirty :: !Bool , lpDirtyFiles :: !(MemoizedWith EnvConfig (Maybe (Set FilePath))) -- ^ Nothing == not dirty, Just == dirty. Note that the Set may be empty if -- we forced the build to treat packages as dirty. Also, the Set may not -- include all modified files. , lpNewBuildCaches :: !(MemoizedWith EnvConfig (Map NamedComponent (Map FilePath FileCacheInfo))) -- ^ current state of the files , lpComponentFiles :: !(MemoizedWith EnvConfig (Map NamedComponent (Set (Path Abs File)))) -- ^ all files used by this package } deriving Show newtype MemoizedWith env a = MemoizedWith { unMemoizedWith :: RIO env a } deriving (Functor, Applicative, Monad) memoizeRefWith :: MonadIO m => RIO env a -> m (MemoizedWith env a) memoizeRefWith action = do ref <- newIORef Nothing pure $ MemoizedWith $ do mres <- readIORef ref res <- case mres of Just res -> pure res Nothing -> do res <- tryAny action writeIORef ref $ Just res pure res either throwIO pure res runMemoizedWith :: (HasEnvConfig env, MonadReader env m, MonadIO m) => MemoizedWith EnvConfig a -> m a runMemoizedWith (MemoizedWith action) = do envConfig <- view envConfigL runRIO envConfig action instance Show (MemoizedWith env a) where show _ = "<<MemoizedWith>>" lpFiles :: HasEnvConfig env => LocalPackage -> RIO env (Set.Set (Path Abs File)) lpFiles = runMemoizedWith . fmap (Set.unions . M.elems) . lpComponentFiles lpFilesForComponents :: HasEnvConfig env => Set NamedComponent -> LocalPackage -> RIO env (Set.Set (Path Abs File)) lpFilesForComponents components lp = runMemoizedWith $ do componentFiles <- lpComponentFiles lp pure $ mconcat (M.elems (M.restrictKeys componentFiles components)) -- | A location to install a package into, either snapshot or local data InstallLocation = Snap | Local deriving (Show, Eq) instance Semigroup InstallLocation where Local <> _ = Local _ <> Local = Local Snap <> Snap = Snap instance Monoid InstallLocation where mempty = Snap mappend = (<>) data InstalledPackageLocation = InstalledTo InstallLocation | ExtraGlobal deriving (Show, Eq) newtype FileCacheInfo = FileCacheInfo { fciHash :: SHA256 } deriving (Generic, Show, Eq, Typeable) instance NFData FileCacheInfo -- Provided for storing the BuildCache values in a file. But maybe -- JSON/YAML isn't the right choice here, worth considering. instance ToJSON FileCacheInfo where toJSON (FileCacheInfo hash') = object [ "hash" .= hash' ] instance FromJSON FileCacheInfo where parseJSON = withObject "FileCacheInfo" $ \o -> FileCacheInfo <$> o .: "hash" -- | A descriptor from a .cabal file indicating one of the following: -- -- exposed-modules: Foo -- other-modules: Foo -- or -- main-is: Foo.hs -- data DotCabalDescriptor = DotCabalModule !ModuleName | DotCabalMain !FilePath | DotCabalFile !FilePath | DotCabalCFile !FilePath deriving (Eq,Ord,Show) -- | Maybe get the module name from the .cabal descriptor. dotCabalModule :: DotCabalDescriptor -> Maybe ModuleName dotCabalModule (DotCabalModule m) = Just m dotCabalModule _ = Nothing -- | Maybe get the main name from the .cabal descriptor. dotCabalMain :: DotCabalDescriptor -> Maybe FilePath dotCabalMain (DotCabalMain m) = Just m dotCabalMain _ = Nothing -- | A path resolved from the .cabal file, which is either main-is or -- an exposed/internal/referenced module. data DotCabalPath = DotCabalModulePath !(Path Abs File) | DotCabalMainPath !(Path Abs File) | DotCabalFilePath !(Path Abs File) | DotCabalCFilePath !(Path Abs File) deriving (Eq,Ord,Show) -- | Get the module path. dotCabalModulePath :: DotCabalPath -> Maybe (Path Abs File) dotCabalModulePath (DotCabalModulePath fp) = Just fp dotCabalModulePath _ = Nothing -- | Get the main path. dotCabalMainPath :: DotCabalPath -> Maybe (Path Abs File) dotCabalMainPath (DotCabalMainPath fp) = Just fp dotCabalMainPath _ = Nothing -- | Get the c file path. dotCabalCFilePath :: DotCabalPath -> Maybe (Path Abs File) dotCabalCFilePath (DotCabalCFilePath fp) = Just fp dotCabalCFilePath _ = Nothing -- | Get the path. dotCabalGetPath :: DotCabalPath -> Path Abs File dotCabalGetPath dcp = case dcp of DotCabalModulePath fp -> fp DotCabalMainPath fp -> fp DotCabalFilePath fp -> fp DotCabalCFilePath fp -> fp type InstalledMap = Map PackageName (InstallLocation, Installed) data Installed = Library PackageIdentifier GhcPkgId (Maybe (Either SPDX.License License)) | Executable PackageIdentifier deriving (Show, Eq) installedPackageIdentifier :: Installed -> PackageIdentifier installedPackageIdentifier (Library pid _ _) = pid installedPackageIdentifier (Executable pid) = pid -- | Get the installed Version. installedVersion :: Installed -> Version installedVersion i = let PackageIdentifier _ version = installedPackageIdentifier i in version
juhp/stack
src/Stack/Types/Package.hs
bsd-3-clause
16,867
0
20
4,482
3,157
1,717
1,440
403
4