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
-- Joe Jevnik -- 21.9.2013 -- Experiment with threading to do checks. -- Poor performance unfortunatly. import Control.Monad (mapM_) import Control.Concurrent (runInBoundThread) main :: IO () main = mapM_ (runInBoundThread . fizz_buzz) [1..100] where fizz_buzz :: Int -> IO () fizz_buzz n | n `rem` 15 == 0 = putStrLn "fizzbuzz" | n `rem` 3 == 0 = putStrLn "fizz" | n `rem` 5 == 0 = putStrLn "buzz" | otherwise = putStrLn $ show n
llllllllll/fizzbuzz
haskell/forkingfizz.hs
gpl-2.0
521
0
11
166
160
83
77
10
1
module Main where import System.Environment import PlayingWindow import LevelBuilder import LevelParser main = do args <- getArgs case args of {-[width, height] -> showWindow createRandom (read width) (read height)-} [fileName] -> do objects <- createFromFile fileName showWindow objects _ -> showWindow createRandom
NemoNessuno/Haskmose
HaskMose.hs
gpl-2.0
428
0
13
153
72
37
35
12
2
{-# OPTIONS_GHC -Wall -fwarn-tabs -Werror #-} ------------------------------------------------------------------------------- -- | -- Module : App -- Copyright : Copyright (c) 2014 Michael R. Shannon -- License : GPLv2 or Later -- Maintainer : [email protected] -- Stability : unstable -- Portability : portable -- -- Main application module. ------------------------------------------------------------------------------- module App ( App(..) , RefApp(..) , pullRef , putRef , makeRef ) where import Data.IORef import App.Types -- Pull the data out of the references and place them in an App structure. pullRef :: RefApp -> IO App pullRef refApp = do kb <- readIORef . keyboardRef $ refApp m <- readIORef . mouseRef $ refApp win <- readIORef . windowRef $ refApp v <- readIORef . viewRef $ refApp t <- readIORef . timeRef $ refApp s <- readIORef . settingsRef $ refApp w <- readIORef . worldRef $ refApp inf <- readIORef . initFunRef $ refApp uf <- readIORef . updateFunRef $ refApp df <- readIORef . drawFunRef $ refApp return App { keyboard = kb , mouse = m , window = win , view = v , time = t , settings = s , world = w , initFun = inf , updateFun = uf , drawFun = df } -- Put App data into references. putRef :: App -> RefApp -> IO () putRef app refApp = do writeIORef ( keyboardRef refApp ) ( keyboard app ) writeIORef ( mouseRef refApp ) ( mouse app ) writeIORef ( windowRef refApp ) ( window app ) writeIORef ( viewRef refApp ) ( view app ) writeIORef ( timeRef refApp ) ( time app ) writeIORef ( settingsRef refApp ) ( settings app ) writeIORef ( worldRef refApp ) ( world app ) writeIORef ( initFunRef refApp ) ( initFun app ) writeIORef ( updateFunRef refApp ) ( updateFun app ) writeIORef ( drawFunRef refApp ) ( drawFun app ) makeRef :: App -> IO RefApp makeRef app = do kbRef <- newIORef $ keyboard app mRef <- newIORef $ mouse app winRef <- newIORef $ window app vRef <- newIORef $ view app tRef <- newIORef $ time app sRef <- newIORef $ settings app wRef <- newIORef $ world app infRef <- newIORef $ initFun app ufRef <- newIORef $ updateFun app dfRef <- newIORef $ drawFun app return RefApp { keyboardRef = kbRef , mouseRef = mRef , windowRef = winRef , viewRef = vRef , timeRef = tRef , settingsRef = sRef , worldRef = wRef , initFunRef = infRef , updateFunRef = ufRef , drawFunRef = dfRef }
mrshannon/trees
src/App.hs
gpl-2.0
2,856
0
9
957
747
380
367
67
1
{- as3tohaxe - An Actionscript 3 to haXe source file translator Copyright (C) 2008 Don-Duong Quach This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. -} -- Parse a file import ActionhaXe.Lexer import ActionhaXe.Prim import ActionhaXe.Parser import System.Environment (getArgs) main = do args <- getArgs let filename = args!!0 contents <- readFile filename let tokens = runLexer "" contents case parseTokens filename tokens of Right ast -> print ast Left err -> print err
geekrelief/as3tohaxe
Parseit.hs
gpl-3.0
1,154
0
10
290
113
54
59
11
2
module Data.XDR.PrettyPrintJava ( ppJava ) where import Control.Monad import Data.Char import Data.List import Data.Map (Map) import qualified Data.Map as M import Data.Maybe import Data.XDR.AST import Data.XDR.PPKeywords import Data.XDR.PPUtils import Text.PrettyPrint.Leijen as PP hiding (braces, indent) -- | Bird. pair :: (a -> b, a -> c) -> a -> (b, c) pair (f, g) x = (f x, g x) -- | Bird. cross :: (a -> b, c -> d) -> (a, c) -> (b, d) cross (f, g) = pair (f . fst, g . snd) indent :: Int indent = 4 lrparen :: Doc lrparen = lparen <> rparen braces :: Doc -> Doc braces d = nest indent (lbrace <$> d) <$> rbrace maybePush :: Maybe a -> [a] -> [a] maybePush = maybe id (:) camelCase :: String -> String camelCase [] = [] camelCase ('_':x:xs) = toUpper x : camelCase xs camelCase (x:xs) = x : camelCase xs typeName :: String -> String typeName [] = [] typeName (x:xs) = toUpper x : camelCase xs topName :: Module -> String topName (Module elems) = last elems upperName :: String -> String upperName = map toUpper -- | DeclPair is Decl without DeclVoid. data DeclPair = DeclPair { declName :: String , declInternal :: DeclInternal } declToPair :: Decl -> Maybe DeclPair declToPair (Decl n di) = Just $ DeclPair n di declToPair DeclVoid = Nothing declsToPairs :: [Decl] -> [DeclPair] -> [DeclPair] declsToPairs = flip (foldr f) where f (Decl n di) = (DeclPair n di :) f _ = id defsToPairs :: [Definition] -> [DeclPair] -> [DeclPair] defsToPairs = flip (foldr f) where f (DefTypedef (Typedef k v)) = (DeclPair k (typedefToDecl v) :) f _ = id type DeclMap = Map String DeclPair specToDeclMap :: Specification -> DeclMap -> DeclMap specToDeclMap (Specification _ imports defs) m = defsToDeclMap defs m' where m' = foldr specToDeclMap m (M.elems imports) defsToDeclMap :: [Definition] -> DeclMap -> DeclMap defsToDeclMap = flip (foldr f) where f (DefTypedef (Typedef k v)) = M.insert k $ DeclPair k (typedefToDecl v) f _ = id typedefToDecl :: TypedefInternal -> DeclInternal typedefToDecl (DefSimple di) = di typedefToDecl (DefEnum ed) = DeclSimple (TEnum ed) typedefToDecl (DefStruct sd) = DeclSimple (TStruct sd) typedefToDecl (DefUnion ud) = DeclSimple (TUnion ud) -- JType data JType = JType { jType :: Doc , jUnbox :: Doc , jConstExpr :: ConstExpr -> Doc } lookupPair :: DeclMap -> DeclPair -> JType lookupPair m (DeclPair n (DeclSimple t)) = lookupType m n t lookupPair m (DeclPair n (DeclArray t _)) = JType td td ppConstExpr where td = text "Array" <> langle <> jType jt <> rangle jt = lookupType m n t lookupPair m (DeclPair n (DeclVarArray t mc)) = JType td td ppConstExpr where td = text "Array" <> langle <> jType jt <> rangle jt = lookupType m n t lookupPair m (DeclPair n (DeclOpaque c)) = JType td td ppConstExpr where td = text "Opaque" lookupPair m (DeclPair n (DeclVarOpaque mc)) = JType td td ppConstExpr where td = text "Opaque" lookupPair m (DeclPair n (DeclString mc)) = JType td td ppConstExpr where td = text "String" lookupPair m (DeclPair n (DeclPointer t)) = lookupType m n t lookupType :: DeclMap -> String -> Type -> JType lookupType _ _ TInt = JType (text "Integer") kInt ppConstExpr lookupType _ _ TUInt = JType (text "Integer") kInt ppConstExpr lookupType _ _ THyper = JType (text "Long") kLong ppConstExpr lookupType _ _ TUHyper = JType (text "Long") kLong ppConstExpr lookupType _ _ TFloat = JType (text "Float") kFloat ppConstExpr lookupType _ _ TDouble = JType (text "Double") kDouble ppConstExpr lookupType _ _ TQuadruple = error "not supported" lookupType _ _ TBool = JType (text "Boolean") kBoolean f where f = (text "0 !=" <+>) . ppConstExpr lookupType _ _ (TEnum _) = JType (text "Integer") kInt ppConstExpr lookupType _ n (TStruct _) = JType td td ppConstExpr where td = text $ typeName n lookupType m n (TUnion (UnionDetail sel _ _)) = JType td td ppConstExpr where td = text "Union" <> langle <> maybe (text "Integer") jType jt <> rangle jt = lookupPair m `fmap` declToPair sel lookupType m _ (TTypedef n) = JType td ud cp where td = maybe td' jType jt ud = maybe td' jUnbox jt cp = maybe ppConstExpr jConstExpr jt td' = text $ typeName n jt = lookupPair m `fmap` M.lookup n m kByteBuffer = text "java.nio.ByteBuffer" kCharacterCodingException = text "java.nio.charset.CharacterCodingException" ppCodecPair :: DeclMap -> DeclPair -> Doc ppCodecPair m (DeclPair n (DeclSimple t)) = ppCodecType m n t ppCodecPair m (DeclPair n (DeclArray t c)) = text "XdrArray.newCodec" <> tupled [ppCodecType m n t, ppConstExpr c] ppCodecPair m (DeclPair n (DeclVarArray t mc)) = text "XdrArray.newVarCodec" <> tupled [ppCodecType m n t, maybe (text "Integer.MAX_VALUE") ppConstExpr mc] ppCodecPair m (DeclPair n (DeclOpaque c)) = text "XdrOpaque.newCodec" <> tupled [ppConstExpr c] ppCodecPair m (DeclPair n (DeclVarOpaque mc)) = text "XdrOpaque." <> maybe (text "VAR_CODEC") ppVarCodec mc ppCodecPair m (DeclPair n (DeclString mc)) = text "XdrString." <> maybe (text "VAR_CODEC") ppVarCodec mc ppCodecPair m (DeclPair n (DeclPointer t)) = text "XdrOptional.newCodec" <> tupled [ppCodecType m n t] ppCodecType :: DeclMap -> String -> Type -> Doc ppCodecType _ _ TInt = text "XdrInt.CODEC" ppCodecType _ _ TUInt = text "XdrUInt.CODEC" ppCodecType _ _ THyper = text "XdrHyper.CODEC" ppCodecType _ _ TUHyper = text "XdrUHyper.CODEC" ppCodecType _ _ TFloat = text "XdrFloat.CODEC" ppCodecType _ _ TDouble = text "XdrDouble.CODEC" ppCodecType _ _ TQuadruple = error "not supported" ppCodecType _ _ TBool = text "XdrBool.CODEC" ppCodecType _ _ (TEnum _) = text "XdrInt.CODEC" ppCodecType _ n (TStruct _) = text ("Xdr" ++ typeName n ++ ".CODEC") ppCodecType m _ (TUnion (UnionDetail sel _ mDef)) = text "XdrUnion.newCodec" <> tupled ((fromMaybe (text "XdrInt.CODEC") sd) : text "CASES" : maybeToList dd) where sd = ppCodecPair m `fmap` declToPair sel dd = ppCodecPair m `fmap` dp dp = declToPair =<< mDef ppCodecType _ _ (TTypedef n) = text ("Xdr" ++ typeName n ++ ".CODEC") ppVarCodec :: ConstExpr -> Doc ppVarCodec c = text "newVarCodec" <> tupled [ppConstExpr c] -- Java ppMaybePackage :: Module -> Maybe Doc ppMaybePackage (Module elems) = if null ps then Nothing else Just $ kPackage <+> f ps <> semi where f = text . concat . intersperse "." ps = init elems ppImports :: [Module] -> Doc ppImports = (kImport <+> text "org.openxdr.*" <> semi <$>) . vcat . map ppImport ppImport :: Module -> Doc ppImport m@(Module elems) = kImport <+> kStatic <+> f elems <> text ".*" <> semi where f = text . concat . intersperse "." ppClass :: String -> [Doc] -> Doc ppClass n = (head <+>) . braces . vcat . (ppPrivateCons n :) where head = kClass <+> text n ppPrivateCons :: String -> Doc ppPrivateCons n = kPrivate <+> text n <> lrparen <+> lbrace <$> rbrace ppConstantDef n d = kPublic <+> kStatic <+> kFinal <+> kInt <+> text n' <+> equals <+> nest indent d <> semi where n' = upperName n ppSimpleCodec :: DeclMap -> DeclPair -> Doc ppSimpleCodec m p@(DeclPair n d) = kPublic <+> kStatic <+> kFinal <+> ppClass ("Xdr" ++ typeName n) [ppPublicCodec td cd] where td = jType $ lookupPair m p cd = ppCodecPair m p ppPublicCodec :: Doc -> Doc -> Doc ppPublicCodec t = (kPublic <+>) . ppStaticCodec "CODEC" t ppPrivateCodec :: String -> Doc -> Doc -> Doc ppPrivateCodec n t = (kPrivate <+>) . ppStaticCodec un t where un = upperName n ++ "_CODEC" ppStaticCodec :: String -> Doc -> Doc -> Doc ppStaticCodec n t d = nest indent (decl <+> equals </> d) <> semi where decl = kStatic <+> kFinal <+> text "Codec" <> langle <> t <> rangle <+> text n ppIface :: String -> [(String, JType)] -> Doc ppIface n = (head <+>) . braces . vcat . map ppGetterDecl where head = kInterface <+> text n ppGetterName :: String -> Doc ppGetterName n = text ("get" ++ typeName n) ppGetterDecl :: (String, JType) -> Doc ppGetterDecl (n, jt) = jUnbox jt <+> ppGetterName n <> lrparen <> semi ppFactory :: String -> [(String, JType)] -> Doc ppFactory n jts = (head <+>) . braces $ ppInstance n jts where head = kStatic <+> kFinal <+> text n <+> text ("new" ++ n) <> tupled (ppFactoryParams jts) ppInstance :: String -> [(String, JType)] -> Doc ppInstance n = (<> semi) . (head <+>) . braces . vcat . ppGetterImpls where head = kReturn <+> kNew <+> text n <> lrparen ppGetterImpls :: [(String, JType)] -> [Doc] ppGetterImpls = map ppGetterImpl ppGetterImpl :: (String, JType) -> Doc ppGetterImpl (n, jt) = kPublic <+> kFinal <+> jUnbox jt <+> ppGetterName n <> lrparen <+> braces body where body = kReturn <+> text (cn ++ "_") <> semi cn = camelCase n ppFactoryParams :: [(String, JType)] -> [Doc] ppFactoryParams = map ppFactoryParam ppFactoryParam :: (String, JType) -> Doc ppFactoryParam (n, jt) = kFinal <+> jUnbox jt <+> text (cn ++ "_") where cn = camelCase n ppFactoryCall :: String -> [(String, JType)] -> Doc ppFactoryCall n = (head <>) . (<> semi) . tupled . ppFactoryArgs where head = kReturn <+> text ("new" ++ tn) tn = typeName n ppFactoryArgs :: [(String, JType)] -> [Doc] ppFactoryArgs = map ppFactoryArg ppFactoryArg :: (String, JType) -> Doc ppFactoryArg (n, _) = text (cn ++ "_") where cn = camelCase n ppAnonCodec :: String -> [(String, JType)] -> Doc ppAnonCodec n jts = nest indent (head <+> braces body) <> semi where head = kPublic <+> kStatic <+> kFinal <+> ct <+> text "CODEC" <+> equals </> kNew <+> ct <> lrparen body = ppEncode n jts <$> ppDecode n jts <$> ppSize n jts ct = text "Codec" <> langle <> text tn <> rangle tn = typeName n ppEncode :: String -> [(String, JType)] -> Doc ppEncode n = (nest indent head <+>) . braces . ppEncodeBody where head = kPublic <+> kFinal <+> kVoid <+> text "encode" <> tupled [kByteBuffer <+> text "buf", text (tn ++ " val")] </> kThrows <+> kCharacterCodingException tn = typeName n ppEncodeBody :: [(String, JType)] -> Doc ppEncodeBody = vcat . ppEncodeVars ppEncodeVars :: [(String, JType)] -> [Doc] ppEncodeVars = map ppEncodeVar ppEncodeVar :: (String, JType) -> Doc ppEncodeVar (n, jt) = text un <> text "_CODEC.encode" <> tupled [text "buf", text ("val.get" ++ tn) <> lrparen] <> semi where tn = typeName n un = upperName n ppDecode :: String -> [(String, JType)] -> Doc ppDecode n = (nest indent head <+>) . braces . ppDecodeBody n where head = kPublic <+> kFinal <+> text tn <+> text "decode" <> tupled [kByteBuffer <+> text "buf"] </> kThrows <+> kCharacterCodingException tn = typeName n ppDecodeBody :: String -> [(String, JType)] -> Doc ppDecodeBody n jts = (vcat $ ppDecodeVars jts) <$> ppFactoryCall n jts ppDecodeVars :: [(String, JType)] -> [Doc] ppDecodeVars = map ppDecodeVar ppDecodeVar :: (String, JType) -> Doc ppDecodeVar (n, jt) = kFinal <+> jUnbox jt <+> text (cn ++ "_") <+> equals <+> text un <> text "_CODEC.decode" <> tupled [text "buf"] <> semi where cn = camelCase n un = upperName n ppSize :: String -> [(String, JType)] -> Doc ppSize n = (nest indent head <+>) . braces . ppSizeBody where head = kPublic <+> kFinal <+> kInt <+> text "size" <> tupled [text (tn ++ " val")] tn = typeName n ppSizeBody :: [(String, JType)] -> Doc ppSizeBody jts = kInt <+> text "n" <+> equals <+> text "0" <> semi <$> (vcat $ ppSizeVars jts) <$> kReturn <+> text "n" <> semi ppSizeVars :: [(String, JType)] -> [Doc] ppSizeVars = map ppSizeVar ppSizeVar :: (String, JType) -> Doc ppSizeVar (n, jt) = text "n +=" <+> text un <> text "_CODEC.size" <> tupled [text ("val.get" ++ tn) <> lrparen] <> semi where tn = typeName n un = upperName n ppCodecDecls :: DeclMap -> [DeclPair] -> [Doc] ppCodecDecls m = map (ppCodecDecl m) ppCodecDecl :: DeclMap -> DeclPair -> Doc ppCodecDecl m p@(DeclPair n d) = ppPrivateCodec n td (ppCodecPair m p) where td = jType $ lookupPair m p ppJava :: Specification -> String ppJava spec = show . vcat $ maybePush (ppMaybePackage m) [ppImports . M.keys $ imports spec, body] where body = kPublic <+> kFinal <+> ppClass tn (ppSpec spec) tn = topName m m = moduleName spec ppSpec (Specification _ _ defs) = f defs where f = punctuate linebreak . map (ppDef m) m = specToDeclMap spec $ M.empty ppDef m (DefConstant (ConstantDef n c)) = ppConstantDef n $ ppConstExpr c ppDef m (DefTypedef (Typedef n ti)) = ppDecl m n $ typedefToDecl ti ppDecl m n d@(DeclSimple (TEnum ed)) = ppEnumDetail n ed <$> (ppSimpleCodec m (DeclPair n d)) ppDecl m n d@(DeclSimple (TStruct sd)) = ppStructDetail m n sd ppDecl m n d@(DeclSimple (TUnion ud)) = kPublic <+> kStatic <+> kFinal <+> ppClass ("Xdr" ++ typeName n) [ppUnionCases m ud, ppPublicCodec td cd] where td = jType $ lookupPair m dp cd = ppCodecPair m dp dp = DeclPair n d ppDecl m n d = ppSimpleCodec m $ DeclPair n d -- | Enumerated values must be visible in the top-level namespace, so they -- are not enclosed in a separate class or interface. ppEnumDetail n (EnumDetail pairs) = vcat $ map f pairs where f (ConstantDef n c) = ppConstantDef n $ ppConstExpr c ppStructDetail m n (StructDetail decls) = kPublic <+> ppIface tn jts <$> kPublic <+> ppFactory tn jts <$> kPublic <+> kStatic <+> kFinal <+> ppClass ("Xdr" ++ tn) (anc : ppCodecDecls m dps) where anc = ppAnonCodec n jts jts = map (pair (declName, lookupPair m)) dps dps = declsToPairs decls [] tn = typeName n ppUnionCases m (UnionDetail sel cases mDef) = nest indent head <> semi where head = kPrivate <+> kStatic <+> kFinal <+> text "java.util.Map" <> langle <> (maybe (text "Integer") jType jt) <> char ',' <+> text "Codec" <> langle <> char '?' <> rangle <> rangle <+> text "CASES" <+> equals </> text "XdrUnion.newCases" <> tupled (ppUnionPairs m (maybe ppConstExpr jConstExpr jt) cases) jt = lookupPair m `fmap` sp sp = declToPair sel ppUnionPairs m f = foldr (g . ppUnionPair m f) [] where g (c, d) = (c :) . (d :) ppUnionPair m f (c, d) = (f c, fromMaybe (text "XdrVoid.CODEC") cd) where cd = (ppCodecPair m) `fmap` declToPair d
jthornber/xdrgen
Data/XDR/PrettyPrintJava.hs
gpl-3.0
15,212
0
23
4,001
5,814
2,981
2,833
386
5
module Main where import Data.List -- задача 1 quickSort [] = [] quickSort (x:xs) = quickSort lesser ++ [x] ++ quickSort greater where lesser = filter (<=x) xs greater = filter (>x) xs multisetSum a b = quickSort (a ++ b) count elem lst = length (filter (==elem) lst) concat_ ll = foldr (++) [] ll multisetIntersect a b = concat_ [replicate (min (count x a) (count x b)) x | x <- nub(a++b)] multisetUnion a b = concat_ [replicate (max (count x a) (count x b)) x | x <- nub(a++b)] lstA = [1,2,2,3,3,4,5] lstB = [2,3,3,3,5,6] -- задача 2 -- трябва да съставим собствен comparator който да използваме в quickSort histogram lst = [(x, count x lst) | x <- nub lst] lst2 = ["moo", "bee", "eve", "abracadabra", "abcdefg", "mama", "z"] -- maximumBy? hlsort [] = [] hlsort (x:xs) = hlsort lesser ++ [x] ++ hlsort greater where lesser = filter (<=x) xs greater = filter (>x) xs -- задача 3 type Quote = (String, Double) companyCount :: String -> [Quote] -> Integer companyCount company quotes = fromIntegral $ length [name | (name, _) <- quotes, name == company] companyAverage :: String -> [Quote] -> Double companyAverage company quotes = total / (fromInteger cnt) where total = sum [value | (name, value) <- quotes, name == company] cnt = companyCount company quotes companyMax :: String -> [Quote] -> Double companyMax company quotes = maximum [value | (name, value) <- quotes, name == company] companyMin :: String -> [Quote] -> Double companyMin company quotes = minimum [value | (name, value) <- quotes, name == company] bestCompany :: [Quote] -> (String, Double, Double) bestCompany quotes = (bestName, companyMin bestName quotes, companyMax bestName quotes) where (_, bestName) = maximum $ map (\name -> (companyAverage name quotes, name)) (nub $ map fst quotes) quotes = [("Acme", 2.56), ("Buy'n'Large", 12.5), ("Acme", 42), ("Smiths", 9.8), ("Buy'n'Large", 13.37), ("Acme", 10.4), ("Smiths", 10.6)] main = do print(multisetUnion lstA lstB) print(multisetIntersect lstA lstB) print(multisetSum lstA lstB) print(histogram lst2) print (bestCompany quotes)
antonpetkoff/learning
haskell/fmi-fp/61793_exam2.hs
gpl-3.0
2,218
0
12
438
960
522
438
41
1
{-# LANGUAGE FlexibleContexts, NoMonomorphismRestriction #-} module Main where import Control.Monad import Control.Monad.Identity import Control.Monad.State import Data.Char import Data.List ((\\)) {- Let us look at parsing a few simple formal languages. Our goal is to first recognize them and then, if possible, extract useful information out of them. Some of them are specified formally in eBNf while others are just given an informal description. Those in eBNf share the following common productions. space = " " | "\t" | "\n" | "\v" | "\f" | "\r" ; digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ; uppercase = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" | "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" | "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z" ; We shall be working with Megaparsec, a descendant of Parsec. It is a convenient parser combinator library built on top of the basic applicative, monadic and alternative type classes. A simple example of parsing natural numbers follows. -} {- Our first case study is the regular language of Canadian postal codes. postalCode = forwardSortationArea , [ space ] , localDeliveryUnit ; forwardSortationArea = postalDistrict , region , section ; localDeliveryUnit = digit , trailingLetter , digit ; postalDistrict = initialLetter ; region = rural | urban ; section = trailingLetter ; rural = "0" ; urban = digit - rural ; trailingLetter = uppercase - ( "D" | "F" | "I" | "O" | "Q" | "U" ) ; initialLetter = trailingLetter - "W" | "Z" ; We would like to convert them into Haskell data structures. type PostalCode = ((Char, Int, Char), (Int, Char, Int)) -} {- Since we are dealing with parser combinators, we can also parametrize parsers in terms of other parsers. Let us do just that by implementing the following context-free language of keyed recursive listings and extracting the items appropriately. listing p = entry p | group p ; group p = "[" , listing p , "]" ; entry p = identifier , ":" , p ; identifier = digit , { digit } ; -} {- Consider a small variation of the listing grammar that may also contain references to previously identified items. Such a change makes the language context-sensitive. -} {- We now have the tools and knowledge to parse all decidable languages that admit a left-recursive parser. However our journey does not end here. Practical languages are usually regular or context-free. Even those categories have two popular subcategories that deserve special attention. Flags like options given as arguments to programs or file permission lists form a permutation language. xw -} {- Hierarchies like trees or simple algebraic expressions form a nested word language. -1+2*3-4+5*(-6)+(-7) -} {- It might seem that we can parse all but the most pathological of languages. Unfortunately some of them are rather tricky to work with. Try the context-free language of palindromes for example. palindrome = "A" | ... | "A" , { palindrome } , "A" | ... ; -} main :: IO () main = return ()
Tuplanolla/ties341-parsing
ParsenatorComments.hs
gpl-3.0
3,144
0
6
693
66
43
23
9
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.EC2.GetPasswordData -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Retrieves the encrypted administrator password for an instance running -- Windows. -- -- The Windows password is generated at boot if the 'EC2Config' service plugin, 'Ec2SetPassword', is enabled. This usually only happens the first time an AMI is launched, -- and then 'Ec2SetPassword' is automatically disabled. The password is not -- generated for rebundled AMIs unless 'Ec2SetPassword' is enabled before bundling. -- -- The password is encrypted using the key pair that you specified when you -- launched the instance. You must provide the corresponding key pair file. -- -- Password generation and encryption takes a few moments. We recommend that -- you wait up to 15 minutes after launching an instance before trying to -- retrieve the generated password. -- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-GetPasswordData.html> module Network.AWS.EC2.GetPasswordData ( -- * Request GetPasswordData -- ** Request constructor , getPasswordData -- ** Request lenses , gpdDryRun , gpdInstanceId -- * Response , GetPasswordDataResponse -- ** Response constructor , getPasswordDataResponse -- ** Response lenses , gpdrInstanceId , gpdrPasswordData , gpdrTimestamp ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.EC2.Types import qualified GHC.Exts data GetPasswordData = GetPasswordData { _gpdDryRun :: Maybe Bool , _gpdInstanceId :: Text } deriving (Eq, Ord, Read, Show) -- | 'GetPasswordData' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'gpdDryRun' @::@ 'Maybe' 'Bool' -- -- * 'gpdInstanceId' @::@ 'Text' -- getPasswordData :: Text -- ^ 'gpdInstanceId' -> GetPasswordData getPasswordData p1 = GetPasswordData { _gpdInstanceId = p1 , _gpdDryRun = Nothing } gpdDryRun :: Lens' GetPasswordData (Maybe Bool) gpdDryRun = lens _gpdDryRun (\s a -> s { _gpdDryRun = a }) -- | The ID of the Windows instance. gpdInstanceId :: Lens' GetPasswordData Text gpdInstanceId = lens _gpdInstanceId (\s a -> s { _gpdInstanceId = a }) data GetPasswordDataResponse = GetPasswordDataResponse { _gpdrInstanceId :: Text , _gpdrPasswordData :: Text , _gpdrTimestamp :: ISO8601 } deriving (Eq, Ord, Read, Show) -- | 'GetPasswordDataResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'gpdrInstanceId' @::@ 'Text' -- -- * 'gpdrPasswordData' @::@ 'Text' -- -- * 'gpdrTimestamp' @::@ 'UTCTime' -- getPasswordDataResponse :: Text -- ^ 'gpdrInstanceId' -> UTCTime -- ^ 'gpdrTimestamp' -> Text -- ^ 'gpdrPasswordData' -> GetPasswordDataResponse getPasswordDataResponse p1 p2 p3 = GetPasswordDataResponse { _gpdrInstanceId = p1 , _gpdrTimestamp = withIso _Time (const id) p2 , _gpdrPasswordData = p3 } -- | The ID of the Windows instance. gpdrInstanceId :: Lens' GetPasswordDataResponse Text gpdrInstanceId = lens _gpdrInstanceId (\s a -> s { _gpdrInstanceId = a }) -- | The password of the instance. gpdrPasswordData :: Lens' GetPasswordDataResponse Text gpdrPasswordData = lens _gpdrPasswordData (\s a -> s { _gpdrPasswordData = a }) -- | The time the data was last updated. gpdrTimestamp :: Lens' GetPasswordDataResponse UTCTime gpdrTimestamp = lens _gpdrTimestamp (\s a -> s { _gpdrTimestamp = a }) . _Time instance ToPath GetPasswordData where toPath = const "/" instance ToQuery GetPasswordData where toQuery GetPasswordData{..} = mconcat [ "DryRun" =? _gpdDryRun , "InstanceId" =? _gpdInstanceId ] instance ToHeaders GetPasswordData instance AWSRequest GetPasswordData where type Sv GetPasswordData = EC2 type Rs GetPasswordData = GetPasswordDataResponse request = post "GetPasswordData" response = xmlResponse instance FromXML GetPasswordDataResponse where parseXML x = GetPasswordDataResponse <$> x .@ "instanceId" <*> x .@ "passwordData" <*> x .@ "timestamp"
kim/amazonka
amazonka-ec2/gen/Network/AWS/EC2/GetPasswordData.hs
mpl-2.0
5,157
0
11
1,153
654
396
258
74
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Healthcare.Projects.Locations.DataSets.ConsentStores.Consents.Patch -- 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) -- -- Updates the latest revision of the specified Consent by committing a new -- revision with the changes. A FAILED_PRECONDITION error occurs if the -- latest revision of the specified Consent is in the \`REJECTED\` or -- \`REVOKED\` state. -- -- /See:/ <https://cloud.google.com/healthcare Cloud Healthcare API Reference> for @healthcare.projects.locations.datasets.consentStores.consents.patch@. module Network.Google.Resource.Healthcare.Projects.Locations.DataSets.ConsentStores.Consents.Patch ( -- * REST Resource ProjectsLocationsDataSetsConsentStoresConsentsPatchResource -- * Creating a Request , projectsLocationsDataSetsConsentStoresConsentsPatch , ProjectsLocationsDataSetsConsentStoresConsentsPatch -- * Request Lenses , pldscscpXgafv , pldscscpUploadProtocol , pldscscpUpdateMask , pldscscpAccessToken , pldscscpUploadType , pldscscpPayload , pldscscpName , pldscscpCallback ) where import Network.Google.Healthcare.Types import Network.Google.Prelude -- | A resource alias for @healthcare.projects.locations.datasets.consentStores.consents.patch@ method which the -- 'ProjectsLocationsDataSetsConsentStoresConsentsPatch' request conforms to. type ProjectsLocationsDataSetsConsentStoresConsentsPatchResource = "v1" :> Capture "name" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "updateMask" GFieldMask :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Consent :> Patch '[JSON] Consent -- | Updates the latest revision of the specified Consent by committing a new -- revision with the changes. A FAILED_PRECONDITION error occurs if the -- latest revision of the specified Consent is in the \`REJECTED\` or -- \`REVOKED\` state. -- -- /See:/ 'projectsLocationsDataSetsConsentStoresConsentsPatch' smart constructor. data ProjectsLocationsDataSetsConsentStoresConsentsPatch = ProjectsLocationsDataSetsConsentStoresConsentsPatch' { _pldscscpXgafv :: !(Maybe Xgafv) , _pldscscpUploadProtocol :: !(Maybe Text) , _pldscscpUpdateMask :: !(Maybe GFieldMask) , _pldscscpAccessToken :: !(Maybe Text) , _pldscscpUploadType :: !(Maybe Text) , _pldscscpPayload :: !Consent , _pldscscpName :: !Text , _pldscscpCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsLocationsDataSetsConsentStoresConsentsPatch' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pldscscpXgafv' -- -- * 'pldscscpUploadProtocol' -- -- * 'pldscscpUpdateMask' -- -- * 'pldscscpAccessToken' -- -- * 'pldscscpUploadType' -- -- * 'pldscscpPayload' -- -- * 'pldscscpName' -- -- * 'pldscscpCallback' projectsLocationsDataSetsConsentStoresConsentsPatch :: Consent -- ^ 'pldscscpPayload' -> Text -- ^ 'pldscscpName' -> ProjectsLocationsDataSetsConsentStoresConsentsPatch projectsLocationsDataSetsConsentStoresConsentsPatch pPldscscpPayload_ pPldscscpName_ = ProjectsLocationsDataSetsConsentStoresConsentsPatch' { _pldscscpXgafv = Nothing , _pldscscpUploadProtocol = Nothing , _pldscscpUpdateMask = Nothing , _pldscscpAccessToken = Nothing , _pldscscpUploadType = Nothing , _pldscscpPayload = pPldscscpPayload_ , _pldscscpName = pPldscscpName_ , _pldscscpCallback = Nothing } -- | V1 error format. pldscscpXgafv :: Lens' ProjectsLocationsDataSetsConsentStoresConsentsPatch (Maybe Xgafv) pldscscpXgafv = lens _pldscscpXgafv (\ s a -> s{_pldscscpXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pldscscpUploadProtocol :: Lens' ProjectsLocationsDataSetsConsentStoresConsentsPatch (Maybe Text) pldscscpUploadProtocol = lens _pldscscpUploadProtocol (\ s a -> s{_pldscscpUploadProtocol = a}) -- | Required. The update mask to apply to the resource. For the -- \`FieldMask\` definition, see -- https:\/\/developers.google.com\/protocol-buffers\/docs\/reference\/google.protobuf#fieldmask. -- Only the \`user_id\`, \`policies\`, \`consent_artifact\`, and -- \`metadata\` fields can be updated. pldscscpUpdateMask :: Lens' ProjectsLocationsDataSetsConsentStoresConsentsPatch (Maybe GFieldMask) pldscscpUpdateMask = lens _pldscscpUpdateMask (\ s a -> s{_pldscscpUpdateMask = a}) -- | OAuth access token. pldscscpAccessToken :: Lens' ProjectsLocationsDataSetsConsentStoresConsentsPatch (Maybe Text) pldscscpAccessToken = lens _pldscscpAccessToken (\ s a -> s{_pldscscpAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pldscscpUploadType :: Lens' ProjectsLocationsDataSetsConsentStoresConsentsPatch (Maybe Text) pldscscpUploadType = lens _pldscscpUploadType (\ s a -> s{_pldscscpUploadType = a}) -- | Multipart request metadata. pldscscpPayload :: Lens' ProjectsLocationsDataSetsConsentStoresConsentsPatch Consent pldscscpPayload = lens _pldscscpPayload (\ s a -> s{_pldscscpPayload = a}) -- | Resource name of the Consent, of the form -- \`projects\/{project_id}\/locations\/{location_id}\/datasets\/{dataset_id}\/consentStores\/{consent_store_id}\/consents\/{consent_id}\`. -- Cannot be changed after creation. pldscscpName :: Lens' ProjectsLocationsDataSetsConsentStoresConsentsPatch Text pldscscpName = lens _pldscscpName (\ s a -> s{_pldscscpName = a}) -- | JSONP pldscscpCallback :: Lens' ProjectsLocationsDataSetsConsentStoresConsentsPatch (Maybe Text) pldscscpCallback = lens _pldscscpCallback (\ s a -> s{_pldscscpCallback = a}) instance GoogleRequest ProjectsLocationsDataSetsConsentStoresConsentsPatch where type Rs ProjectsLocationsDataSetsConsentStoresConsentsPatch = Consent type Scopes ProjectsLocationsDataSetsConsentStoresConsentsPatch = '["https://www.googleapis.com/auth/cloud-platform"] requestClient ProjectsLocationsDataSetsConsentStoresConsentsPatch'{..} = go _pldscscpName _pldscscpXgafv _pldscscpUploadProtocol _pldscscpUpdateMask _pldscscpAccessToken _pldscscpUploadType _pldscscpCallback (Just AltJSON) _pldscscpPayload healthcareService where go = buildClient (Proxy :: Proxy ProjectsLocationsDataSetsConsentStoresConsentsPatchResource) mempty
brendanhay/gogol
gogol-healthcare/gen/Network/Google/Resource/Healthcare/Projects/Locations/DataSets/ConsentStores/Consents/Patch.hs
mpl-2.0
7,602
0
17
1,491
870
512
358
135
1
module Main where import Prelude hiding ((++)) import Control.Monad import Control.Exception import System.IO import System.IO.Error import qualified Data.Text.Encoding as T import System.Posix.ByteString import System.Exit hiding (die) import System.Console.CmdArgs.Explicit import ByteString (ByteString) import qualified ByteString as B import qualified Pack import RawFilePath import Parser import Format import GitHub import Unsafe import Platform (++) :: Monoid m => m -> m -> m (++) = mappend data Cmd = CmdHelp | CmdBuild | CmdBump | CmdGithub arguments :: Mode Cmd arguments = modes "wild" CmdHelp "Release Haskell projects" [ m "build" CmdBuild "build project and strip executables\ \ to prepare for release" , m "bump" CmdBump "read the change log, change the version string\ \ in files and commit those changes" , m "github" CmdGithub "create a new release draft in GitHub\ \ and upload executables as its assets" ] where m :: Name -> Cmd -> Help -> Mode Cmd m name cmd help = mode name cmd help (flagArg (\_ c -> Right c) "") [] main :: IO () main = do arg <- processArgs arguments case arg of CmdHelp -> print $ helpText [] HelpFormatDefault arguments CmdBuild -> runBuild CmdBump -> runBump CmdGithub -> runGithub runBuild :: IO () runBuild = do Cabal{..} <- getCabal run "stack" ["install"] forM_ cabalExecs $ \ bin -> do stripCommand bin run "upx" ["-9", "--lzma", bin] runBump :: IO () runBump = do versions <- parseChangeLog <$> readCatch "CHANGELOG.md" case versions of [] -> die ["version not found in change log"] [_] -> return () (newver : oldver : _) -> do cabalPath <- getCabalPath Cabal{..} <- getCabal when (cabalVersion /= newver) $ do B.writeFile cabalPath $ mconcat [cabalPrefix, head versions, cabalSuffix] run "git" ["add", cabalPath] readCatch "README.md" >>= \ b -> case parseReadMe oldver b of Left e -> die ["README.md: ", e] Right ReadMe{..} -> do B.writeFile "README.md" $ mconcat [readMePrefix, newver, readMeSuffix] run "git" ["add", "README.md"] run "git" ["add", "CHANGELOG.md"] bracket (mkstemp "/tmp/wild-") (\ (path, _) -> removeLink path) $ \ (path, h) -> do B.hPutStr h $ mconcat ["Version: ", head versions] hClose h void $ run "git" ["commit", "-v", "--allow-empty-message", "-t", path] runGithub :: IO () runGithub = do versions <- parseChangeLog <$> readCatch "CHANGELOG.md" homePath <- getHomePath Cabal{..} <- getCabal Conf{..} <- fmap (either error id . dec) $ catchIOError (B.readFile "wild.json") $ const $ do B.writeFile "wild.json" $ enc initConf B.putStrLn "Created wild.json with default configuration." exitFailure token <- fmap (fst . B.breakEnd (/= '\n')) $ readCatch $ let path = T.encodeUtf8 tokenPath in if B.head path == '~' then homePath ++ B.tail path else path B.putStr "Uploading to GitHub releases.." uploadResult <- uploadRelease token (T.encodeUtf8 owner) (T.encodeUtf8 repo) ("v" ++ head versions) cabalExecs case uploadResult of Left x -> error (show x) Right _ -> return () getHomePath :: IO RawFilePath getHomePath = getRef homePathRef $ getEnv "HOME" >>= \ m -> case m of Nothing -> die ["No $HOME?!"] Just p -> return p getCabalPath :: IO RawFilePath getCabalPath = getRef cabalPathRef $ getDirectoryContentsSuffix "." ".cabal" >>= \ s -> case s of [] -> error "no cabal file found in the current directory" (x : _) -> return x getCabal :: IO Cabal getCabal = getRef cabalRef $ do homePath <- getHomePath cabalPath <- getCabalPath let binPath = map (homePath ++ "/.local/bin/" ++) parseCabal <$> readCatch cabalPath >>= \ m -> case m of Left e -> die [e] Right c -> return c { cabalExecs = binPath (cabalExecs c) } runFail :: RawFilePath -> [ByteString] -> IO ByteString runFail cmd args = do x <- runRead cmd args case x of Left c -> do B.putStrLn $ mconcat ["command fail: ", cmd, " (", Pack.int c, ")"] exitFailure Right output -> return output die :: [ByteString] -> IO a die e = B.putStrLn (mconcat e) *> exitFailure readCatch :: RawFilePath -> IO ByteString readCatch path = catchIOError (B.readFile path) $ const $ B.putStrLn ("Failed reading " ++ path) *> exitFailure
kinoru/wild
src/Main.hs
agpl-3.0
4,793
0
21
1,396
1,523
762
761
-1
-1
{- - This file is part of Bilder. - - Bilder is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - Bilder is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with Bilder. If not, see <http://www.gnu.org/licenses/>. - - Copyright © 2012-2013 Filip Lundborg - Copyright © 2012-2013 Ingemar Ådahl - -} {-# LANGUAGE UnicodeSyntax #-} module Compiler.Utils where import Control.Applicative import Control.Monad.Identity import Control.Monad.State import Control.Monad.Writer import CompilerError import FrontEnd.AbsGrammar import TypeChecker.Utils (cIdentToString, cIdentToPos, paramToString) import qualified TypeChecker.Types as T import Data.List (nub) liftCError ∷ CError a → StateT b CError a liftCError m = StateT (\s → case m of { Fail f → Fail f; Pass a → return (a,s) }) -- | Creates a Variable from a FilePath and a Param paramToVar ∷ FilePath → Param → T.Variable paramToVar f (ParamDec qs cid) = T.Variable (cIdentToString cid) (f, cIdentToPos cid) (qualsToType qs) Nothing paramToVar f (ParamDefault qs cid _ e) = T.Variable (cIdentToString cid) (f, cIdentToPos cid) (qualsToType qs) (Just e) varTypeToParam ∷ String → Type → Param varTypeToParam n t = ParamDec [QType t] name where name = CIdent ((-1,-1),n) -- | Extracts a declared variables name. declToName ∷ Decl → [String] declToName (Dec _ dp) = declPostToName dp declToName (Struct {}) = [] declToName (StructDecl _ _ _ cid) = [cIdentToString cid] declToTypeAndName ∷ Decl → [(Type, String)] declToTypeAndName (Dec qs dp) = zip (repeat $ qualsToType qs) (declPostToName dp) -- TODO: Structs. --declToTypeAndName (Struct {}) = undefined --declToTypeAndName (StructDecl {}) = undefined -- | Qualifiers to type (typechecked so it should always be OK) qualsToType ∷ [Qualifier] → Type --qualsToType [] = undefined -- Should never happen (typechecked) qualsToType (QType t:_) = t qualsToType (_:qs) = qualsToType qs declPostToName ∷ DeclPost → [String] declPostToName (Vars cids) = map cIdentToString cids declPostToName (DecAss cids _ _) = map cIdentToString cids -- DecFun is replaced with SFunDecl in the typechecker. --declPostToName (DecFun {}) = [] -- Exp and Stm folding and mapping {{{ foldExpM ∷ Monad m => (a → Exp → m a) → a → Exp → m a foldExpM f p e@(EAss el _ er) = foldM (foldExpM f) p [el,er] >>= flip f e foldExpM f p e@(EAssAdd el _ er) = foldM (foldExpM f) p [el,er] >>= flip f e foldExpM f p e@(EAssSub el _ er) = foldM (foldExpM f) p [el,er] >>= flip f e foldExpM f p e@(EAssMul el _ er) = foldM (foldExpM f) p [el,er] >>= flip f e foldExpM f p e@(EAssDiv el _ er) = foldM (foldExpM f) p [el,er] >>= flip f e foldExpM f p e@(EAssMod el _ er) = foldM (foldExpM f) p [el,er] >>= flip f e foldExpM f p e@(EAssBWAnd el _ er) = foldM (foldExpM f) p [el,er] >>= flip f e foldExpM f p e@(EAssBWXOR el _ er) = foldM (foldExpM f) p [el,er] >>= flip f e foldExpM f p e@(EAssBWOR el _ er) = foldM (foldExpM f) p [el,er] >>= flip f e foldExpM f p e@(ECond econd _ etrue _ efalse) = foldM (foldExpM f) p [econd,etrue,efalse] >>= flip f e foldExpM f p e@(EOR el _ er) = foldM (foldExpM f) p [el,er] >>= flip f e foldExpM f p e@(EXOR el _ er) = foldM (foldExpM f) p [el,er] >>= flip f e foldExpM f p e@(EAnd el _ er) = foldM (foldExpM f) p [el,er] >>= flip f e foldExpM f p e@(EBWOR el _ er) = foldM (foldExpM f) p [el,er] >>= flip f e foldExpM f p e@(EBWXOR el _ er) = foldM (foldExpM f) p [el,er] >>= flip f e foldExpM f p e@(EBWAnd el _ er) = foldM (foldExpM f) p [el,er] >>= flip f e foldExpM f p e@(EEqual el _ er) = foldM (foldExpM f) p [el,er] >>= flip f e foldExpM f p e@(ENEqual el _ er) = foldM (foldExpM f) p [el,er] >>= flip f e foldExpM f p e@(ELt el _ er) = foldM (foldExpM f) p [el,er] >>= flip f e foldExpM f p e@(EGt el _ er) = foldM (foldExpM f) p [el,er] >>= flip f e foldExpM f p e@(ELEt el _ er) = foldM (foldExpM f) p [el,er] >>= flip f e foldExpM f p e@(EGEt el _ er) = foldM (foldExpM f) p [el,er] >>= flip f e foldExpM f p e@(EBWShiftLeft el _ er) = foldM (foldExpM f) p [el,er] >>= flip f e foldExpM f p e@(EBWShiftRight el _ er) = foldM (foldExpM f) p [el,er] >>= flip f e foldExpM f p e@(EAdd el _ er) = foldM (foldExpM f) p [el,er] >>= flip f e foldExpM f p e@(ESub el _ er) = foldM (foldExpM f) p [el,er] >>= flip f e foldExpM f p e@(EMul el _ er) = foldM (foldExpM f) p [el,er] >>= flip f e foldExpM f p e@(EDiv el _ er) = foldM (foldExpM f) p [el,er] >>= flip f e foldExpM f p e@(EMod el _ er) = foldM (foldExpM f) p [el,er] >>= flip f e foldExpM f p e@(ENeg _ ei) = foldExpM f p ei >>= flip f e foldExpM f p e@(ENegSign _ ei) = foldExpM f p ei >>= flip f e foldExpM f p e@(EComplement _ ei) = foldExpM f p ei >>= flip f e foldExpM f p e@(EPos _ ei) = foldExpM f p ei >>= flip f e foldExpM f p e@(EPreInc _ ei) = foldExpM f p ei >>= flip f e foldExpM f p e@(EPreDec _ ei) = foldExpM f p ei >>= flip f e foldExpM f p e@(EPostInc ei _) = foldExpM f p ei >>= flip f e foldExpM f p e@(EPostDec ei _) = foldExpM f p ei >>= flip f e foldExpM f p e@(EMember ei _) = foldExpM f p ei >>= flip f e foldExpM f p e@(EMemberCall ei _ es) = foldM (foldExpM f) p (ei:es) >>= flip f e foldExpM f p e@(ECall _ es) = foldM (foldExpM f) p es >>= flip f e foldExpM f p e@(EPartCall _ es _) = foldM (foldExpM f) p es >>= flip f e foldExpM f p e@(ECurryCall _ ei _) = foldExpM f p ei >>= flip f e foldExpM f p e@(ETypeCall _ es) = foldM (foldExpM f) p es >>= flip f e foldExpM f p e@(EVar {}) = f p e foldExpM f p e@(EVarType {}) = f p e foldExpM f p e@(EIndex _ ei) = foldExpM f p ei >>= flip f e foldExpM f p e@(EIndexDouble _ e1 e2) = foldM (foldExpM f) p [e1, e2] >>= flip f e foldExpM f p e@(EFloat {}) = f p e foldExpM f p e@(EInt {}) = f p e foldExpM f p e@ETrue = f p e foldExpM f p e@EFalse = f p e foldExp ∷ (a → Exp → a) → a → Exp → a foldExp f p e = runIdentity (foldExpM (liftIdentity f) p e) foldStmM ∷ Monad m => (a → Stm → m a) → a → Stm → m a foldStmM f p s@(SDecl {}) = f p s foldStmM f p s@(SExp {}) = f p s foldStmM f p s@(SBlock iss) = foldM (foldStmM f) p iss >>= flip f s foldStmM f p s@(SWhile _ _ is) = foldStmM f p is >>= flip f s foldStmM f p s@(SDoWhile _ is _ _) = foldStmM f p is >>= flip f s foldStmM f p s@(SFor _ _ _ _ is) = foldStmM f p is >>= flip f s foldStmM f p s@(SReturn {}) = f p s foldStmM f p s@(SVoidReturn {}) = f p s foldStmM f p s@(SIf _ _ is) = foldStmM f p is >>= flip f s foldStmM f p s@(SIfElse _ _ istrue _ isfalse) = foldM (foldStmM f) p [istrue,isfalse] >>= flip f s foldStmM f p s@(SBreak {}) = f p s foldStmM f p s@(SContinue {}) = f p s foldStmM f p s@(SDiscard {}) = f p s foldStmM f p s@(SType _ is) = foldStmM f p is >>= flip f s foldStmM f p s@(SFunDecl _ _ _ _ iss) = foldM (foldStmM f) p iss >>= flip f s foldStm ∷ (a → Stm → a) → a → Stm → a foldStm f p s = runIdentity (foldStmM (liftIdentity f) p s) liftIdentity ∷ (a → b → a) → a → b → Identity a liftIdentity f' p' s' = Identity (f' p' s') mapExpM ∷ (Monad m, Applicative m) => (Exp → m Exp) → Exp → m Exp mapExpM f (EAss el tk er) = EAss <$> f el <*> pure tk <*> f er mapExpM f (EAssAdd el tk er) = EAssAdd <$> f el <*> pure tk <*> f er mapExpM f (EAssSub el tk er) = EAssSub <$> f el <*> pure tk <*> f er mapExpM f (EAssMul el tk er) = EAssMul <$> f el <*> pure tk <*> f er mapExpM f (EAssDiv el tk er) = EAssDiv <$> f el <*> pure tk <*> f er mapExpM f (EAssMod el tk er) = EAssMod <$> f el <*> pure tk <*> f er mapExpM f (EAssBWAnd el tk er) = EAssBWAnd <$> f el <*> pure tk <*> f er mapExpM f (EAssBWXOR el tk er) = EAssBWXOR <$> f el <*> pure tk <*> f er mapExpM f (EAssBWOR el tk er) = EAssBWOR <$> f el <*> pure tk <*> f er mapExpM f (EOR el tk er) = EOR <$> f el <*> pure tk <*> f er mapExpM f (EXOR el tk er) = EXOR <$> f el <*> pure tk <*> f er mapExpM f (EAnd el tk er) = EAnd <$> f el <*> pure tk <*> f er mapExpM f (EBWOR el tk er) = EBWOR <$> f el <*> pure tk <*> f er mapExpM f (EBWXOR el tk er) = EBWXOR <$> f el <*> pure tk <*> f er mapExpM f (EBWAnd el tk er) = EBWAnd <$> f el <*> pure tk <*> f er mapExpM f (EEqual el tk er) = EEqual <$> f el <*> pure tk <*> f er mapExpM f (ENEqual el tk er) = ENEqual <$> f el <*> pure tk <*> f er mapExpM f (ELt el tk er) = ELt <$> f el <*> pure tk <*> f er mapExpM f (EGt el tk er) = EGt <$> f el <*> pure tk <*> f er mapExpM f (ELEt el tk er) = ELEt <$> f el <*> pure tk <*> f er mapExpM f (EGEt el tk er) = EGEt <$> f el <*> pure tk <*> f er mapExpM f (EBWShiftLeft el tk er) = EBWShiftLeft <$> f el <*> pure tk <*> f er mapExpM f (EBWShiftRight el tk er) = EBWShiftRight <$> f el <*> pure tk <*> f er mapExpM f (EAdd el tk er) = EAdd <$> f el <*> pure tk <*> f er mapExpM f (ESub el tk er) = ESub <$> f el <*> pure tk <*> f er mapExpM f (EMul el tk er) = EMul <$> f el <*> pure tk <*> f er mapExpM f (EDiv el tk er) = EDiv <$> f el <*> pure tk <*> f er mapExpM f (EMod el tk er) = EMod <$> f el <*> pure tk <*> f er mapExpM f (ECond eq tkl el tkr er) = ECond <$> f eq <*> pure tkl <*> f el <*> pure tkr <*> f er mapExpM f (ENeg tk e) = ENeg tk <$> f e mapExpM f (ENegSign tk e) = ENegSign tk <$> f e mapExpM f (EComplement tk e) = EComplement tk <$> f e mapExpM f (EPos tk e) = EPos tk <$> f e mapExpM f (EPreInc tk e) = EPreInc tk <$> f e mapExpM f (EPreDec tk e) = EPreDec tk <$> f e mapExpM f (EPostInc e tk) = EPostInc <$> f e <*> pure tk mapExpM f (EPostDec e tk) = EPostDec <$> f e <*> pure tk mapExpM f (EMember e cid) = EMember <$> f e <*> pure cid mapExpM f (EMemberCall el cid es) = EMemberCall <$> f el <*> pure cid <*> mapM f es mapExpM f (ECall cid es) = ECall cid <$> mapM f es mapExpM f (EPartCall cid es ts) = EPartCall cid <$> mapM f es <*> pure ts mapExpM f (ECurryCall cid e t) = ECurryCall cid <$> f e <*> pure t mapExpM f (ETypeCall t es) = ETypeCall t <$> mapM f es mapExpM f (EIndex cid e) = EIndex cid <$> f e mapExpM f (EIndexDouble cid e1 e2) = EIndexDouble cid <$> f e1 <*> f e2 mapExpM _ e@(EVar {}) = pure e mapExpM _ e@(EFloat {}) = pure e mapExpM _ e@(EInt {}) = pure e mapExpM _ e@ETrue = pure e mapExpM _ e@EFalse = pure e mapExpM _ e@(EVarType {}) = pure e mapExp ∷ (Exp → Exp) → Exp → Exp mapExp f ex = runIdentity $ mapExpM f' ex where f' ∷ Exp → Identity Exp f' e = return $ f e mapStmM ∷ (Monad m, Applicative m) => (Stm → m Stm) → Stm → m Stm mapStmM _ s@(SDecl {}) = pure s mapStmM _ s@(SExp {}) = pure s mapStmM f (SBlock ss) = SBlock <$> mapM f ss mapStmM f (SWhile tk e s) = SWhile tk e <$> f s mapStmM f (SDoWhile tkl s tkr e) = SDoWhile tkl <$> f s <*> pure tkr <*> pure e mapStmM f (SFor tk dec el er s) = SFor tk dec el er <$> f s mapStmM _ s@(SReturn {}) = pure s mapStmM _ s@(SVoidReturn {}) = pure s mapStmM f (SIf tk e s) = SIf tk e <$> f s mapStmM f (SIfElse tk e st tke se) = SIfElse tk e <$> f st <*> pure tke <*> f se mapStmM _ s@(SBreak {}) = pure s mapStmM _ s@(SContinue {}) = pure s mapStmM _ s@(SDiscard {}) = pure s mapStmM f (SType t s) = SType t <$> f s mapStmM f (SFunDecl cid t px ps ss) = SFunDecl cid t px ps <$> mapM f ss mapStm ∷ (Stm → Stm) → Stm → Stm mapStm f s = runIdentity $ mapStmM f' s where f' ∷ Stm → Identity Stm f' stm = return $ f stm -- | Mapping over all Exp in Stm. mapStmExpM ∷ (Monad m, Applicative m) => (Exp → m Exp) → Stm → m Stm mapStmExpM f (SDecl (Dec qs (DecAss cids tk e))) = SDecl <$> Dec qs <$> DecAss cids tk <$> f e mapStmExpM f (SExp e) = SExp <$> f e mapStmExpM f (SDoWhile tkd s tkw e) = SDoWhile tkd <$> mapStmExpM f s <*> pure tkw <*> f e mapStmExpM f (SWhile tk e s) = SWhile tk <$> f e <*> mapStmExpM f s mapStmExpM f (SFor tk fds ecs els s) = SFor tk <$> mapM (mapForDeclExpM f) fds <*> mapM f ecs <*> mapM f els <*> mapStmExpM f s mapStmExpM f (SReturn tk e) = SReturn tk <$> f e mapStmExpM f (SIf tk e s) = SIf tk <$> f e <*> mapStmExpM f s mapStmExpM f (SIfElse tki e st tke stf) = SIfElse tki <$> f e <*> mapStmExpM f st <*> pure tke <*> mapStmExpM f stf mapStmExpM f s = mapStmM (mapStmExpM f) s mapForDeclExpM ∷ (Monad m, Applicative m) => (Exp → m Exp) → ForDecl → m ForDecl mapForDeclExpM f (FDecl (Dec qs (DecAss cids tk e))) = liftM (FDecl . Dec qs . DecAss cids tk) (f e) -- TODO: Structs! mapForDeclExpM _ d@(FDecl _) = return d mapForDeclExpM f (FExp e) = FExp <$> f e mapStmExp ∷ (Exp → Exp) → Stm → Stm mapStmExp f s = runIdentity $ mapStmExpM f' s where f' ∷ Exp → Identity Exp f' e = return $ f e -- Expands statements, useful for rewriting code expandStmM ∷ (Monad m, Applicative m) => ([Stm] → m [Stm]) → [Stm] → m [Stm] expandStmM f (SBlock stms:ss) = (:) <$> (SBlock <$> f stms) <*> f ss expandStmM f (SWhile tkw e s:ss) = do s' ← liftM makeBlock $ f [s] ss' ← f ss return $ SWhile tkw e s':ss' expandStmM f (SDoWhile tkd s tkw e:ss) = do s' ← liftM makeBlock $ f [s] ss' ← f ss return $ SDoWhile tkd s' tkw e:ss' expandStmM f (SFor tkf fdec es es' s:ss) = (:) <$> (SFor tkf fdec es es' <$> liftM makeBlock (f [s])) <*> f ss expandStmM f (SIf tkif e s:ss) = (:) <$> (SIf tkif e <$> liftM makeBlock (f [s])) <*> f ss expandStmM f (SIfElse tkif e st tke sf:ss) = do st' ← liftM makeBlock (f [st]) sf' ← liftM makeBlock (f [sf]) ss' ← f ss return $ SIfElse tkif e st' tke sf':ss' expandStmM f (SType t s:ss) = (++) <$> liftM (map (SType t)) (f [s]) <*> f ss expandStmM f (s:ss) = (:) <$> pure s <*> expandStmM f ss expandStmM _ [] = return [] makeBlock ∷ [Stm] → Stm makeBlock ss = if length ss == 1 then head ss else SBlock ss expandStm ∷ ([Stm] → [Stm]) → [Stm] → [Stm] expandStm f s = runIdentity $ expandStmM f' s where f' ∷ [Stm] → Identity [Stm] f' s' = return $ f s' -- }}} -- Free Variables {{{ -- TODO: Move this to Compiler/Types.hs type AbsFun = (String, [Param], [Stm]) -- | Find all free variables in a function. freeFunctionVars ∷ [String] → AbsFun → [String] freeFunctionVars global (_, ps, stms) = nub . snd $ foldl stmVars (bound, []) stms where bound = global ++ map paramToString ps -- | Calculates a statements bound and free variables -- (given already known bound and free variables) stmVars ∷ ([String], [String]) → Stm → ([String], [String]) stmVars (b, f) s@(SDecl d) = (declToName d ++ b, f ++ filterBound b (usedVars' [s])) stmVars (b, f) (SExp e) = (b, f ++ filterBound b (expVars e)) stmVars vs (SBlock stms) = foldl stmVars vs stms stmVars vs (SFor _ fd el er s) = (b' ++ b, filterBound (b' ++ b) (f'' ++ f' ++ f)) where b' = concatMap declToName [ d | FDecl d ← fd ] f'' = concatMap expVars [ e | FExp e ← fd ] f' = concatMap expVars (el ++ er) (b, f) = stmVars vs s stmVars vs (SWhile _ e s) = (b, f ++ filterBound b (expVars e)) where (b, f) = stmVars vs s -- Order does not matter because of unique names stmVars (b, f) (SReturn _ e) = (b, f ++ filterBound b (expVars e)) stmVars vs (SVoidReturn _) = vs stmVars (b, f) (SIf _ e stm) = (b'', f ++ f' ++ filterBound b'' (expVars e)) where (b', f') = stmVars (b, f) stm b'' = b ++ b' stmVars (b, f) (SIfElse _ econd strue _ sfalse) = (b', f ++ ftrue ++ ffalse ++ filterBound b' (expVars econd)) where (btrue, ftrue) = stmVars (b, f) strue (bfalse, ffalse) = stmVars (b, f) sfalse b' = b ++ btrue ++ bfalse -- This is OK because of unique names. stmVars vs (SType _ stm) = stmVars vs stm stmVars vs (SFunDecl {}) = vs stmVars _ stm = error $ "UNHANDLED " ++ show stm -- | Known bound variables → Variables → Free variables filterBound ∷ [String] → [String] → [String] filterBound bound = filter (not . (`elem` bound)) -- | Find all referenced variables in an expression. expVars ∷ Exp → [String] expVars = foldExp expVar [] where expVar ∷ [String] → Exp → [String] expVar p (ECall cid es) = concatMap expVars es ++ cIdentToString cid : p expVar p (EVar cid) = cIdentToString cid : p expVar p (ECurryCall cid e _) = expVars e ++ cIdentToString cid : p expVar p (EIndex cid e) = expVars e ++ cIdentToString cid : p expVar p (EIndexDouble cid e1 e2) = expVars e1 ++ expVars e2 ++ cIdentToString cid : p expVar p _ = p gather' ∷ Monoid a => (Exp → Writer a Exp) → [Stm] → a gather' f ss = execWriter (mapM_ (mapStmExpM f) ss) -- Get a list of all variables references usedVars' ∷ [Stm] → [String] usedVars' = nub . gather' collect where collect ∷ Exp → Writer [String] Exp collect e@(EVar cid) = tell [cIdentToString cid] >> return e collect e@(ECall cid es) = tell [cIdentToString cid] >> mapM_ collect es >> return e collect e@(ECurryCall cid ei _) = tell [cIdentToString cid] >> collect ei >> return e collect e@(EIndex cid es) = tell [cIdentToString cid] >> collect es >> return e collect e@(EIndexDouble cid e1 e2) = tell [cIdentToString cid] >> collect e1 >> collect e2 >> return e collect e = mapExpM collect e -- }}} -- vi:fdm=marker
ingemaradahl/bilder
src/Compiler/Utils.hs
lgpl-3.0
17,332
0
12
3,856
9,020
4,497
4,523
288
6
{-# LANGUAGE BangPatterns, OverloadedStrings #-} -- -- Copyright : (c) T.Mishima 2014 -- License : Apache-2.0 -- module Hinecraft.Rendering.WithBasicShader ( BasicShaderProg , makeBasicShdrVAO , orthoProjMatrix , setLightMode , setColorBlendMode , setModelMatrix , setMVPMatrix , setTMatrix , setShadowSW , setGlobalLightParam ) where -- OpenGL import Graphics.Rendering.OpenGL as GL import Graphics.GLUtil as GU import qualified Graphics.GLUtil.Camera3D as GU3 --import Control.Exception ( bracket ) import Linear.V4 import Linear import Hinecraft.Rendering.Types data BasicShaderProg = BasicShaderProg { shprg :: ShaderProgram , inVertTag :: String , inVertClrTag :: String , inTexTag :: String , inVertNormTag :: String , outFragTag :: String , uniMMatTag :: String , uniMVPMTag :: String , uniTMatTag :: String , uniTexEnFTag :: String , uniClrBlndTag :: String , uniLightMdTag :: String , uniShadwMdTag :: String , uniGLhtVecTag :: String } instance WithShader BasicShaderProg where initShaderProgram home = do sp <- simpleShaderProgramWith vertFn fragFn $ \ p -> do attribLocation p inVertTag' $= AttribLocation 0 attribLocation p inVertClrTag' $= AttribLocation 1 attribLocation p inVertNormTag' $= AttribLocation 2 attribLocation p inTexTag' $= AttribLocation 3 bindFragDataLocation p outFragTag' $= 0 -- set Defualt param to uniform currentProgram $= Just (program sp) asUniform eMat $ getUniform sp uniMMatrixTag' asUniform eMat $ getUniform sp uniMvpMatrixTag' asUniform eMat $ getUniform sp uniTMatrixTag' asUniform (0 :: GLint) $ getUniform sp uniTexEnFTag' asUniform (0::GLint) $ getUniform sp "TexUnit" asUniform (1::GLint) $ getUniform sp "ShadowMap" asUniform (V3 0.0 1.0 (0.0:: GLfloat)) $ getUniform sp uniGLhtVecTag' currentProgram $= Nothing return BasicShaderProg { shprg = sp , inVertTag = inVertTag' , inVertClrTag = inVertClrTag' , inTexTag = inTexTag' , inVertNormTag = inVertNormTag' , outFragTag = outFragTag' , uniMMatTag = uniMMatrixTag' , uniMVPMTag = uniMvpMatrixTag' , uniTMatTag = uniTMatrixTag' , uniTexEnFTag = uniTexEnFTag' , uniClrBlndTag = "ColorBlandType" , uniLightMdTag = "LightMode" , uniShadwMdTag = "ShadowSW" , uniGLhtVecTag = uniGLhtVecTag' } where !vertFn = home ++ "/.Hinecraft/shader/basic.vert" !fragFn = home ++ "/.Hinecraft/shader/basic.frag" !inVertTag' = "VertexPosition" !inVertClrTag' = "VertexColor" !inTexTag' = "VertexTexture" !inVertNormTag' = "VertexNormal" !outFragTag' = "FragColor" !uniMMatrixTag' = "mMatrix" !uniMvpMatrixTag' = "mvpMatrix" !uniTMatrixTag' = "tMatrix" !uniTexEnFTag' = "TexEnbFlg" !uniGLhtVecTag' = "GlobalLightVec" !eMat = V4 (V4 1.0 0.0 0.0 0.0) (V4 0.0 1.0 0.0 0.0) (V4 0.0 0.0 1.0 0.0) (V4 0.0 0.0 0.0 1.0) :: M44 GLfloat useShader shd fn = do op <- get currentProgram currentProgram $= Just (program sp) fn shd currentProgram $= op where sp = shprg shd enableTexture shd flg = uniformScalar (getUniform s $ uniTexEnFTag shd) $= if flg then 1 else (0 :: GLint) where !s = shprg shd getShaderProgram = shprg setModelMatrix :: BasicShaderProg -> M44 GLfloat -> IO () setModelMatrix shd mMat = asUniform mMat mMUnifLoc where !mMUnifLoc = getUniform s (uniMMatTag shd) !s = shprg shd setMVPMatrix :: BasicShaderProg -> M44 GLfloat -> IO () setMVPMatrix shd mvpMat = asUniform mvpMat mvpMUnifLoc where !mvpMUnifLoc = GU.getUniform sp (uniMVPMTag shd) !sp = shprg shd setTMatrix :: BasicShaderProg -> M44 GLfloat -> IO () setTMatrix shd tMat = asUniform tMat tMUnifLoc where !tMUnifLoc = GU.getUniform sp (uniTMatTag shd) !sp = shprg shd orthoProjMatrix :: GLfloat -> GLfloat -> M44 GLfloat orthoProjMatrix w h = V4 (V4 (2/w) 0 0 (-1)) (V4 0 (2/h) 0 (-1)) (V4 0 0 0 0) (V4 0 0 0 1) setLightMode :: BasicShaderProg -> Int -> IO () setLightMode sh md = uniformScalar (getUniform sp $ uniLightMdTag sh) $= (fromIntegral md::GLint) where sp = shprg sh setGlobalLightParam :: BasicShaderProg -> GLfloat -> IO () setGlobalLightParam sh deg = asUniform vec $ getUniform sp tag where vec = V3 (0.0:: GLfloat) y z z = cos $ GU3.deg2rad deg y = sin $ GU3.deg2rad deg tag = uniGLhtVecTag sh sp = shprg sh setShadowSW :: BasicShaderProg -> Int -> IO () setShadowSW sh md = uniformScalar (getUniform sp $ uniShadwMdTag sh) $= (fromIntegral md::GLint) where sp = shprg sh setColorBlendMode :: BasicShaderProg -> Int -> IO () setColorBlendMode sh md = uniformScalar (getUniform sp $ uniClrBlndTag sh) $= (fromIntegral md::GLint) where sp = shprg sh makeBasicShdrVAO :: BasicShaderProg -> [GLfloat] -> [GLfloat] -> [GLfloat] -> [GLfloat] -> IO VAO makeBasicShdrVAO simpShdr vertLst vertClrLst vertNrmLst texCdLst = do op <- get currentProgram currentProgram $= Just (program sp) vb <- makeBuffer ArrayBuffer vertLst cb <- makeBuffer ArrayBuffer vertClrLst nb <- makeBuffer ArrayBuffer vertNrmLst tb <- makeBuffer ArrayBuffer texCdLst vao <- makeVAO $ do bindBuffer ArrayBuffer $= Just vb enableAttrib sp (inVertTag simpShdr) setAttrib sp (inVertTag simpShdr) ToFloat (VertexArrayDescriptor 3 Float 0 offset0) bindBuffer ArrayBuffer $= Just cb enableAttrib sp (inVertClrTag simpShdr) setAttrib sp (inVertClrTag simpShdr) ToFloat (VertexArrayDescriptor 4 Float 0 offset0) bindBuffer ArrayBuffer $= Just nb enableAttrib sp (inVertNormTag simpShdr) setAttrib sp (inVertNormTag simpShdr) ToFloat (VertexArrayDescriptor 3 Float 0 offset0) bindBuffer ArrayBuffer $= Just tb enableAttrib sp (inTexTag simpShdr) setAttrib sp (inTexTag simpShdr) ToFloat (VertexArrayDescriptor 2 Float 0 offset0) deleteObjectNames [vb,cb,nb,tb] GL.currentProgram $= op return vao where sp = shprg simpShdr
tmishima/Hinecraft
Hinecraft/Rendering/WithBasicShader.hs
apache-2.0
6,358
0
14
1,610
1,851
918
933
154
1
module RayCaster ( Camera(..) , Config(..) , Light(..) , Material(..) , Object(..) , Scene(..) , Shape(..) , Vector(..) ) where import RayCaster.Camera (Camera (..)) import RayCaster.DataTypes (Config (..), Light (..), Material (..), Object (..), Scene (..)) import RayCaster.Shapes (Shape (..)) import RayCaster.Vector (Vector (..))
bkach/HaskellRaycaster
src/RayCaster.hs
apache-2.0
440
0
6
150
146
100
46
14
0
module PrettyJSON where import SimpleJSON import PrettyStub renderJSON :: JValue -> Doc renderJSON (JBool True) = text "true"
EricYT/Haskell
src/real_haskell/chapter-5/PrettyJSON.hs
apache-2.0
129
0
7
21
36
20
16
5
1
-- |Environment test cases. The .js files in the environment directory are -- parsed as: -- -- tests ::= test ; -- | ; -- | test ; tests -- -- test ::= ( identifier * ) function-expression -- -- function-expression is defined in TypedJavaScript.Parser. Each test -- lists the the local variables of the associated function. The test -- succeeds if all local variables are accounted for. If the function -- body repeats a declaration for a variable, the identifier must -- be duplicated in the identifier list. -- -- -- Note that there is a trailing ';' at the end of a list of tests. -- JavaScript-style comments are permitted in .test files. -- -- The funcEnv function will signal an error only if it is supplied with -- an expression that is not a FuncExpr. Since this is trivial, we don't -- test for errors. module Environment where import Text.ParserCombinators.Parsec import Test.HUnit import qualified Data.List as L import TypedJavaScript.Syntax (Expression,Id(..)) import TypedJavaScript.Lexer (semi,identifier,parens) import TypedJavaScript.Parser (parseFuncExpr) import TypedJavaScript.Environment (funcEnv) import TypedJavaScript.Test import TypedJavaScript.PrettyPrint assertEnv :: [String] -> Expression SourcePos -> Assertion assertEnv expectedIds expr = do let env = funcEnv expr let envIds = map (\((Id _ s),_,_) -> s) env assertEqual "environment mismatch" (L.sort expectedIds) (L.sort envIds) parseTestCase :: CharParser st Test parseTestCase = do let testEmpty = return $ TestCase (return ()) let testEnv = do ids <- parens (many identifier) expr <- parseFuncExpr return (TestCase $ assertEnv ids expr) testEnv <|> testEmpty readTestFile :: FilePath -> IO Test readTestFile path = do result <- parseFromFile (parseTestCase `endBy` semi) path case result of -- Reporting the parse error is deferred until the test is run. Left err -> return $ TestCase (assertFailure (show err)) Right tests -> return $ TestList tests main = do testPaths <- getPathsWithExtension ".js" "environment" testCases <- mapM readTestFile testPaths return (TestList testCases)
brownplt/strobe-old
tests/Environment.hs
bsd-2-clause
2,164
0
15
405
444
237
207
33
2
-- | This module provides transition semantics for the SIMPLE language module Language.SIMPLE.TransitionSemantics ( isRedex ,reduceExpr ,reduceSequenceOfExpr ,runExprMachine ,isReducible ,reduceStm ,reduceSequenceOfStm ,runMachine ) where import Control.Applicative import Text.PrettyPrint import Language.SIMPLE.AbstractSyntax import Language.SIMPLE.Environment import Language.SIMPLE.PrettyPrint -- $setup -- >>> type Name = String -- >>> let exp0 = Add (Multiply (Number 1) (Number 2)) (Multiply (Number 3) (Number 4)) :: Expr Name -- >>> let env0 = emptyEnv isNumber :: Expr a -> Bool isNumber expr = case expr of Number _ -> True _ -> False isBoolean :: Expr a -> Bool isBoolean expr = case expr of Boolean _ -> True _ -> False isNormalForm :: Expr a -> Bool isNormalForm = (||) . isNumber <*> isBoolean -- | -- Predicate if the specified expression is redex or not. -- -- >>> isRedex (Number 1 :: Expr Name) -- False -- >>> isRedex (Boolean undefined :: Expr Name) -- False -- >>> isRedex (Variable undefined :: Expr Name) -- True -- >>> isRedex (Add undefined undefined :: Expr Name) -- True -- >>> isRedex (Multiply undefined undefined :: Expr Name) -- True -- >>> isRedex (And undefined undefined :: Expr Name) -- True -- >>> isRedex (Or undefined undefined :: Expr Name) -- True -- >>> isRedex (LessThan undefined undefined :: Expr Name) -- True -- >>> isRedex (Not undefined :: Expr Name) -- True isRedex :: Expr a -> Bool isRedex = not . isNormalForm isδredex :: Expr a -> Bool isδredex (Add e1 e2) = isNormalForm e1 && isNormalForm e2 isδredex (Multiply e1 e2) = isNormalForm e1 && isNormalForm e2 isδredex (And e1 e2) = isNormalForm e1 && isNormalForm e2 isδredex (Or e1 e2) = isNormalForm e1 && isNormalForm e2 isδredex (LessThan e1 e2) = isNormalForm e1 && isNormalForm e2 isδredex (Not e) = isNormalForm e isδredex _ = False δreduce :: Expr a -> Expr a δreduce (Add (Number m) (Number n)) = Number (m+n) δreduce (Multiply (Number m) (Number n)) = Number (m*n) δreduce (LessThan (Number m) (Number n)) = Boolean (m<n) δreduce (And (Boolean b) (Boolean c)) = Boolean (b&&c) δreduce (Or (Boolean b) (Boolean c)) = Boolean (b||c) δreduce (Not (Boolean b)) = Boolean (not b) δreduce _ = error "Type error" -- | -- make a small-step reducing of the specified expression in the specified environment. -- -- >>> isRedex exp0 -- True -- >>> let exp1 = reduceExpr emptyEnv exp0 -- >>> exp1 -- Add (Number 2) (Multiply (Number 3) (Number 4)) -- >>> isRedex exp1 -- True -- >>> let exp2 = reduceExpr emptyEnv exp1 -- >>> exp2 -- Add (Number 2) (Number 12) -- >>> isRedex exp2 -- True -- >>> let exp3 = reduceExpr emptyEnv exp2 -- >>> exp3 -- Number 14 -- >>> isRedex exp3 -- False reduceExpr :: (Ord a, Show a) => Env Expr a -> Expr a -> Expr a reduceExpr σ expr | isNormalForm expr = expr | isδredex expr = δreduce expr | otherwise = case expr of Variable x -> lookupEnv x σ Add e1 e2 | isRedex e1 -> Add (reduceExpr σ e1 ) e2 | otherwise -> Add e1 (reduceExpr σ e2) Multiply e1 e2 | isRedex e1 -> Multiply (reduceExpr σ e1) e2 | otherwise -> Multiply e1 (reduceExpr σ e2) LessThan e1 e2 | isRedex e1 -> LessThan (reduceExpr σ e1) e2 | otherwise -> LessThan e1 (reduceExpr σ e2) And e1 e2 | isRedex e1 -> And (reduceExpr σ e1) e2 | otherwise -> And e1 (reduceExpr σ e2) Or e1 e2 | isRedex e1 -> Or (reduceExpr σ e1) e2 | otherwise -> Or e1 (reduceExpr σ e2) Not e -> Not (reduceExpr σ e) _ -> error "Unknown expression" -- | -- makes expression reduce sequence. reduceSequenceOfExpr :: (Ord a, Show a) => Env Expr a -> Expr a -> [Expr a] reduceSequenceOfExpr = (till isNormalForm .) . iterate . reduceExpr till :: (a -> Bool) -> [a] -> [a] till p xs = case break p xs of (ys,[]) -> ys (ys,z:_) -> ys ++ [z] -- | -- displays expression reduce sequence. -- -- >>> runExprMachine env0 exp0 -- (1 × 2) + (3 × 4) -- 2 + (3 × 4) -- 2 + 12 -- 14 -- >>> let exp4 = LessThan (Number 5) (Add (Number 2) (Number 2)) -- >>> runExprMachine env0 exp4 -- 5 < (2 + 2) -- 5 < 4 -- False -- >>> let exp5 = Add (Variable "x") (Variable "y") -- >>> let env5 = fromListEnv [("x",Number 3),("y",Number 4)] -- >>> runExprMachine env5 exp5 -- x + y -- 3 + y -- 3 + 4 -- 7 runExprMachine :: (Ord a, Show a) => Env Expr a -> Expr a -> IO () runExprMachine = (mapM_ (putStrLn . render . pprExpr) .) . reduceSequenceOfExpr -- | -- Predicate whether the specified statement is reducible. isReducible :: Stm a -> Bool isReducible DoNothing = False isReducible _ = True -- | -- make a small-step reducing of the specified statement in the specified environment. -- -- >>> let stm1 = Assign "x" (Add (Variable "x") (Number 1)) -- >>> putStr $ render $ pprStm stm1 -- x := x + 1 -- >>> let env1 = fromListEnv [("x", Number 2)] -- >>> putStr $ render $ pprEnv env1 -- {x <- 2} -- >>> isReducible stm1 -- True -- >>> let step2@(env2,stm2) = reduceStm env1 stm1 -- >>> putStr $ render $ pprStepStm step2 -- x := 2 + 1 {x <- 2} -- >>> let step3@(env3,stm3) = reduceStm env2 stm2 -- >>> putStr $ render $ pprStepStm step3 -- x := 3 {x <- 2} -- >>> let step4@(env4,stm4) = reduceStm env3 stm3 -- >>> putStr $ render $ pprStepStm step4 -- φ {x <- 3} -- >>> isReducible stm4 -- False reduceStm :: (Ord a, Show a) => Env Expr a -> Stm a -> (Env Expr a, Stm a) reduceStm σ stm | not . isReducible $ stm = (σ,stm) | otherwise = case stm of Assign x e | isNormalForm e -> (insertEnv x e σ, DoNothing) | otherwise -> (σ, Assign x (reduceExpr σ e)) If e t f | isNormalForm e -> case e of Boolean c -> (σ, if c then t else f) _ -> error "Type error" | otherwise -> (σ, If (reduceExpr σ e) t f) While e s -> (σ,If e (Sequence s stm) DoNothing) Sequence DoNothing s2 -> reduceStm σ s2 Sequence s1 s2 -> case reduceStm σ s1 of (σ',s1') -> (σ' ,Sequence s1' s2) _ -> error (render (pprStm stm)) -- | -- makes statement reduce sequence. reduceSequenceOfStm :: (Ord a, Show a) => Env Expr a -> Stm a -> [(Env Expr a, Stm a)] reduceSequenceOfStm σ stm = till (not . isReducible . snd) $ iterate (uncurry reduceStm) (σ,stm) -- | -- displays statement reduce sequence. -- -- >>> let stm1 = Assign "x" (Add (Variable "x") (Number 1)) -- >>> let env1 = fromListEnv [("x", Number 2)] -- >>> runMachine env1 stm1 -- x := x + 1 {x <- 2} -- x := 2 + 1 {x <- 2} -- x := 3 {x <- 2} -- φ {x <- 3} -- >>> let stm2 = If (Variable "x") (Assign "y" (Number 1)) (Assign "y" (Number 2)) -- >>> let env2 = fromListEnv [("x",Boolean True)] -- >>> runMachine env2 stm2 -- if (x) y := 1 else y := 2 {x <- True} -- if (True) y := 1 else y := 2 {x <- True} -- y := 1 {x <- True} -- φ {x <- True; y <- 1} -- >>> let stm3 = If (Variable "x") (Assign "y" (Number 1)) DoNothing -- >>> let env3 = fromListEnv [("x",Boolean False)] -- >>> runMachine env3 stm3 -- if (x) y := 1 else φ {x <- False} -- if (False) y := 1 else φ {x <- False} -- φ {x <- False} -- >>> let stm4 = Sequence (Assign "x" (Add (Number 1) (Number 1))) (Assign "y" (Add (Variable "x") (Number 3))) -- >>> runMachine env0 stm4 -- x := 1 + 1; y := x + 3 {} -- x := 2; y := x + 3 {} -- y := x + 3 {x <- 2} -- y := 2 + 3 {x <- 2} -- y := 5 {x <- 2} -- φ {x <- 2; y <- 5} -- >>> let stm5 = While (LessThan (Variable "x") (Number 5)) (Assign "x" (Multiply (Variable "x") (Number 3))) :: Stm Name -- >>> let env5 = fromListEnv [("x",Number 1)] :: Env Expr Name -- >>> runMachine env5 stm5 -- while (x < 5) x := x × 3 {x <- 1} -- if (x < 5) {x := x × 3; while (x < 5) x := x × 3} else φ {x <- 1} -- if (1 < 5) {x := x × 3; while (x < 5) x := x × 3} else φ {x <- 1} -- if (True) {x := x × 3; while (x < 5) x := x × 3} else φ {x <- 1} -- x := x × 3; while (x < 5) x := x × 3 {x <- 1} -- x := 1 × 3; while (x < 5) x := x × 3 {x <- 1} -- x := 3; while (x < 5) x := x × 3 {x <- 1} -- while (x < 5) x := x × 3 {x <- 3} -- if (x < 5) {x := x × 3; while (x < 5) x := x × 3} else φ {x <- 3} -- if (3 < 5) {x := x × 3; while (x < 5) x := x × 3} else φ {x <- 3} -- if (True) {x := x × 3; while (x < 5) x := x × 3} else φ {x <- 3} -- x := x × 3; while (x < 5) x := x × 3 {x <- 3} -- x := 3 × 3; while (x < 5) x := x × 3 {x <- 3} -- x := 9; while (x < 5) x := x × 3 {x <- 3} -- while (x < 5) x := x × 3 {x <- 9} -- if (x < 5) {x := x × 3; while (x < 5) x := x × 3} else φ {x <- 9} -- if (9 < 5) {x := x × 3; while (x < 5) x := x × 3} else φ {x <- 9} -- if (False) {x := x × 3; while (x < 5) x := x × 3} else φ {x <- 9} -- φ {x <- 9} runMachine :: (Ord a, Show a) => Env Expr a -> Stm a -> IO () runMachine = (mapM_ (putStrLn . render . pprStepStm) .) . reduceSequenceOfStm
nobsun/hs-uc
src/Language/SIMPLE/TransitionSemantics.hs
bsd-3-clause
9,218
2
14
2,423
1,928
1,021
907
92
8
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE DataKinds #-} module Hardware.KansasLava.Boards.Papilio.LogicStart ( Model(..) -- * Class for the methods of the Spartan3e , LogicStart(..) -- * Initialization, and global settings. , clockRate , board_init , toUCF -- * Data structures , Active(..) , SevenSegment(..) , Buttons(..) , VGA(..) -- -- * Utilities for Board and Simulation use , switchesP -- , buttonsP -- TODO , ledsP ) where import Language.KansasLava as KL import Hardware.KansasLava.Boards.Papilio import qualified Hardware.KansasLava.Boards.Papilio.UCF as Papilio import Hardware.KansasLava.SevenSegment import Hardware.KansasLava.VGA import Data.Sized.Ix hiding (all) import Data.Sized.Matrix hiding (all) import Control.Applicative import Control.Monad (ap, liftM) data Buttons clk = Buttons{ buttonUp, buttonDown , buttonLeft, buttonRight , buttonCenter :: Signal clk Bool } ------------------------------------------------------------ -- The LogicStart class ------------------------------------------------------------ class Papilio fabric => LogicStart fabric where ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- switches :: fabric (Matrix X8 (Signal CLK Bool)) buttons :: fabric (Buttons CLK) leds :: Matrix X8 (Signal CLK Bool) -> fabric () sseg :: SevenSegment CLK ActiveLow X4 -> fabric () vga :: RawVGA CLK X3 X3 X2 -> fabric () ------------------------------------------------------------ -- initialization ------------------------------------------------------------ toUCF :: Model -> KLEG -> IO String toUCF model = Papilio.toUCF fileName (Just "CLK_32MHZ") where fileName = "LogicStart-" ++ designator ++ ".ucf" designator = case model of PapilioOne -> "One" PapilioPro -> "Pro" ------------------------------------------------------------ -- instance ------------------------------------------------------------ instance LogicStart Fabric where ------------------------------------------------------------ -- RAW APIs ------------------------------------------------------------ switches = do inp <- inStdLogicVector "SWITCH" :: Fabric (Seq (Matrix X8 Bool)) return (unpack inp) buttons = Buttons `liftM` inStdLogic "BTN_UP" `ap` inStdLogic "BTN_DOWN" `ap` inStdLogic "BTN_LEFT" `ap` inStdLogic "BTN_RIGHT" `ap` inStdLogic "BTN_CENTER" leds inp = outStdLogicVector "LED" (pack inp :: Seq (Matrix X8 Bool)) sseg SevenSegment{..} = do outStdLogicVector "SS_ANODES" (pack ssAnodes :: Seq (Matrix X4 Bool)) outStdLogicVector "SS_SEGS" (pack ssSegments :: Seq (Matrix X7 Bool)) outStdLogic "SS_DP" ssDecimalPoint vga RawVGA{..} = do outStdLogicVector "VGA_R" (pack vgaRawR :: Seq (Matrix X3 Bool)) outStdLogicVector "VGA_G" (pack vgaRawG :: Seq (Matrix X3 Bool)) outStdLogicVector "VGA_B" (pack vgaRawB :: Seq (Matrix X2 Bool)) outStdLogic "VGA_VSYNC" vgaRawVSync outStdLogic "VGA_HSYNC" vgaRawHSync ------------------------------------------------------------- -- Utilites that can be shared ------------------------------------------------------------- -- | 'switchesP' gives a patch-level API for the toggle switches. switchesP :: (LogicStart fabric) => fabric (Patch () (Matrix X8 (Seq Bool)) () (Matrix X8 ())) switchesP = do sws <- switches return $ outputP sws $$ backwardP (\ _mat -> ()) $$ matrixStackP (pure emptyP) {- -- | 'buttonsP' gives a patch-level API for the toggle switches. buttonsP :: (LogicStart fabric) => fabric (Patch () Buttons () (Matrix X5 ())) buttonsP = do btns <- buttons return $ outputP btns $$ backwardP (\ _mat -> ()) $$ matrixStackP (pure emptyP) -} -- | 'ledP' gives a patch-level API for the leds. ledsP :: (LogicStart fabric) => Patch (Matrix X8 (Seq Bool)) (fabric ()) (Matrix X8 ()) () ledsP = backwardP (\ () -> pure ()) $$ forwardP leds
gergoerdi/kansas-lava-papilio
src/Hardware/KansasLava/Boards/Papilio/LogicStart.hs
bsd-3-clause
4,322
0
13
978
927
502
425
72
2
{-# LANGUAGE UnicodeSyntax #-} module Stat.Base ( dirStat , getFileSystemStats , contentsFileStat , fileStat ) where import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as B import System.Fuse import System.Posix.Files -- for file modes import System.Posix.Types (FileOffset) import Debug (dbg) -- ^ What should these be? getFileSystemStats :: String -> IO (Either Errno FileSystemStats) getFileSystemStats _ = return $ Right FileSystemStats { fsStatBlockSize = 512 , fsStatBlockCount = 1 , fsStatBlocksFree = 1 , fsStatBlocksAvailable = 1 , fsStatFileCount = 5 , fsStatFilesFree = 10 , fsStatMaxNameLength = 255 } dirStat ∷ FuseContext → FileStat dirStat ctx = FileStat { statEntryType = Directory , statFileMode = dirFileMode , statLinkCount = 2 -- ?? -- Owners -- record members for FuseContext , statFileOwner = fuseCtxUserID ctx , statFileGroup = fuseCtxGroupID ctx -- ?? , statSpecialDeviceID = 0 , statFileSize = 4096 , statBlocks = 1 -- times: Access, Modification, and StatusChange , statAccessTime = 0 , statModificationTime = 0 , statStatusChangeTime = 0 } ---------------------- contentsFileStat ∷ FuseContext → ByteString → FileStat contentsFileStat ctx contents = (fileStat ctx) { statFileSize = byteLen contents } where byteLen ∷ ByteString → FileOffset byteLen = fromInteger . toInteger . B.length fileStat ∷ FuseContext → FileStat fileStat ctx = FileStat { statEntryType = RegularFile , statFileMode = fileFileMode , statLinkCount = 1 , statFileOwner = fuseCtxUserID ctx , statFileGroup = fuseCtxGroupID ctx , statSpecialDeviceID = 0 , statFileSize = 0 , statBlocks = 1 -- times: Access, Modification, and StatusChange , statAccessTime = 0 , statModificationTime = 0 , statStatusChangeTime = 0 } {- | unionFileModes ∷ FileMode → FileMode → FileMode Combines the 2 file modes into 1 that contains modes that appear in either. `FileMode`s are in System.Posix.Files -} dirFileMode = foldr1 unionFileModes [ ownerReadMode, ownerExecuteMode, ownerWriteMode , groupReadMode, groupExecuteMode , otherReadMode, otherExecuteMode ] fileFileMode = foldr1 unionFileModes [ ownerReadMode, ownerWriteMode , groupReadMode , otherReadMode ]
marklar/TagFS
src/Stat/Base.hs
bsd-3-clause
3,336
0
8
1,458
460
281
179
58
1
{- Copyright 2013-2019 Mario Blazevic License: BSD3 (see BSD3-LICENSE.txt file) -} -- | This module defines the monoid transformer data type 'Measured'. -- {-# LANGUAGE Haskell2010 #-} module Data.Monoid.Instances.Measured ( Measured, measure, extract ) where import Data.Functor -- ((<$>)) import qualified Data.List as List import Data.String (IsString(..)) import Data.Semigroup (Semigroup(..)) import Data.Monoid (Monoid(..)) import Data.Semigroup.Cancellative (LeftReductive(..), RightReductive(..)) import Data.Semigroup.Factorial (Factorial(..), StableFactorial) import Data.Monoid.GCD (LeftGCDMonoid(..), RightGCDMonoid(..)) import Data.Monoid.Null (MonoidNull(null), PositiveMonoid) import Data.Monoid.Factorial (FactorialMonoid(..)) import Data.Monoid.Textual (TextualMonoid(..)) import qualified Data.Monoid.Factorial as Factorial import qualified Data.Monoid.Textual as Textual import Prelude hiding (all, any, break, filter, foldl, foldl1, foldr, foldr1, map, concatMap, length, null, reverse, scanl, scanr, scanl1, scanr1, span, splitAt) -- | @'Measured' a@ is a wrapper around the 'FactorialMonoid' @a@ that memoizes the monoid's 'length' so it becomes a -- constant-time operation. The parameter is restricted to the 'StableFactorial' class, which guarantees that -- @'length' (a <> b) == 'length' a + 'length' b@. data Measured a = Measured{_measuredLength :: Int, extract :: a} deriving (Eq, Show) -- | Create a new 'Measured' value. measure :: Factorial a => a -> Measured a measure x = Measured (length x) x instance Ord a => Ord (Measured a) where compare (Measured _ x) (Measured _ y) = compare x y instance StableFactorial a => Semigroup (Measured a) where Measured m a <> Measured n b = Measured (m + n) (a <> b) instance (StableFactorial a, Monoid a) => Monoid (Measured a) where mempty = Measured 0 mempty mappend = (<>) instance (StableFactorial a, Monoid a) => MonoidNull (Measured a) where null (Measured n _) = n == 0 instance (StableFactorial a, Monoid a) => PositiveMonoid (Measured a) instance (LeftReductive a, StableFactorial a) => LeftReductive (Measured a) where stripPrefix (Measured m x) (Measured n y) = fmap (Measured (n - m)) (stripPrefix x y) instance (RightReductive a, StableFactorial a) => RightReductive (Measured a) where stripSuffix (Measured m x) (Measured n y) = fmap (Measured (n - m)) (stripSuffix x y) instance (LeftGCDMonoid a, StableFactorial a) => LeftGCDMonoid (Measured a) where commonPrefix (Measured _ x) (Measured _ y) = measure (commonPrefix x y) instance (RightGCDMonoid a, StableFactorial a) => RightGCDMonoid (Measured a) where commonSuffix (Measured _ x) (Measured _ y) = measure (commonSuffix x y) instance (StableFactorial a, MonoidNull a) => Factorial (Measured a) where factors (Measured _ x) = List.map (Measured 1) (factors x) primePrefix m@(Measured _ x) = if null x then m else Measured 1 (primePrefix x) primeSuffix m@(Measured _ x) = if null x then m else Measured 1 (primeSuffix x) foldl f a0 (Measured _ x) = Factorial.foldl g a0 x where g a = f a . Measured 1 foldl' f a0 (Measured _ x) = Factorial.foldl' g a0 x where g a = f a . Measured 1 foldr f a0 (Measured _ x) = Factorial.foldr g a0 x where g = f . Measured 1 foldMap f (Measured _ x) = Factorial.foldMap (f . Measured 1) x length (Measured n _) = n reverse (Measured n x) = Measured n (reverse x) instance (StableFactorial a, FactorialMonoid a) => FactorialMonoid (Measured a) where splitPrimePrefix (Measured n x) = case splitPrimePrefix x of Nothing -> Nothing Just (p, s) -> Just (Measured 1 p, Measured (n - 1) s) splitPrimeSuffix (Measured n x) = case splitPrimeSuffix x of Nothing -> Nothing Just (p, s) -> Just (Measured (n - 1) p, Measured 1 s) span p (Measured n x) = (xp', xs') where (xp, xs) = Factorial.span (p . Measured 1) x xp' = measure xp xs' = Measured (n - length xp') xs split p (Measured _ x) = measure <$> Factorial.split (p . Measured 1) x splitAt m (Measured n x) | m <= 0 = (mempty, Measured n x) | m >= n = (Measured n x, mempty) | otherwise = (Measured m xp, Measured (n - m) xs) where (xp, xs) = splitAt m x instance (StableFactorial a, MonoidNull a) => StableFactorial (Measured a) instance (FactorialMonoid a, IsString a) => IsString (Measured a) where fromString = measure . fromString instance (Eq a, StableFactorial a, TextualMonoid a) => TextualMonoid (Measured a) where fromText = measure . fromText singleton = Measured 1 . singleton splitCharacterPrefix (Measured n x) = (Measured (n - 1) <$>) <$> splitCharacterPrefix x characterPrefix (Measured _ x) = characterPrefix x map f (Measured n x) = Measured n (map f x) any p (Measured _ x) = any p x all p (Measured _ x) = all p x foldl ft fc a0 (Measured _ x) = Textual.foldl (\a-> ft a . Measured 1) fc a0 x foldl' ft fc a0 (Measured _ x) = Textual.foldl' (\a-> ft a . Measured 1) fc a0 x foldr ft fc a0 (Measured _ x) = Textual.foldr (ft . Measured 1) fc a0 x toString ft (Measured _ x) = toString (ft . Measured 1) x toText ft (Measured _ x) = toText (ft . Measured 1) x span pt pc (Measured n x) = (xp', xs') where (xp, xs) = Textual.span (pt . Measured 1) pc x xp' = measure xp xs' = Measured (n - length xp') xs break pt pc = Textual.span (not . pt) (not . pc) find p (Measured _ x) = find p x
blamario/monoid-subclasses
src/Data/Monoid/Instances/Measured.hs
bsd-3-clause
5,700
0
13
1,351
2,252
1,178
1,074
90
1
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses #-} module NginxUpdater where import Data.Maybe import Debug.Trace import Data.List import System.Directory import System.IO import System.Process import Text.Regex type AppName = String data DeployInfo = DeployInfo { identifier :: Int, hostname :: String, portnum :: Int } deriving Show class Monad m => Table d m where addEntry :: d -> AppName -> DeployInfo -> m () removeEntry :: d -> AppName -> DeployInfo -> m () lookup :: d -> AppName -> m (Maybe DeployInfo) instance Table FilePath IO where addEntry filepath appname deployinfo = do trace "===nginx: addEntry===" $ return () oldh <- openFile filepath ReadWriteMode -- handle to current config file trace "addEntry: opened current file" $ return () let tmppath = filepath ++ ".new" -- temporary; will be copied back to filepath at the end newh <- openFile tmppath ReadWriteMode -- handle to modified config file trace "addEntry: opened tmp file" $ return () let starttag = "# START: " ++ appname ++ (show $ identifier deployinfo) endtag = "# END: " ++ appname ++ (show $ identifier deployinfo) let code = starttag ++ "\n" ++ -- new code to add to the config file " server { \n\ \ listen 8080; \n\ \ server_name " ++ appname ++ ".lvh.me; \n " ++ " location / { \n\ \ proxy_pass http://localhost:1234; \n\ \ } \n\ \ } \n" ++ endtag insertAt "http {" code oldh newh hClose newh hClose oldh renameFile filepath (filepath ++ ".backup") renameFile tmppath filepath restartNginx where insertAt tag newtext oldh newh = do eof <- hIsEOF oldh if eof then do hPutStrLn newh "http {" hPutStrLn newh newtext hPutStrLn newh "}" return () else do line <- hGetLine oldh hPutStrLn newh line if (isInfixOf tag line) then do -- if the http tag is part of the line hPutStrLn newh newtext copyRemainder oldh newh -- copy the rest of the old file into the new file else insertAt tag newtext oldh newh copyRemainder oldh newh = do -- copy the remainder of oldh's file into newh's file eof <- hIsEOF oldh if eof then return () else do line <- hGetLine oldh hPutStrLn newh line copyRemainder oldh newh removeEntry filepath appname deployinfo = do let starttag = "# START: " ++ appname ++ (show $ identifier deployinfo) endtag = "# END: " ++ appname ++ (show $ identifier deployinfo) let backuppath = filepath ++ ".backup" renameFile filepath backuppath oldh <- openFile backuppath ReadWriteMode newh <- openFile filepath ReadWriteMode processFile oldh newh starttag endtag True hClose oldh hClose newh restartNginx where processFile oldh newh starttag endtag copymode = do eof <- hIsEOF oldh if eof then return () else do line <- hGetLine oldh --trace ("line: " ++ line) $ return () --trace ("copymode: " ++ show copymode) $ return () if (isInfixOf starttag line || isInfixOf endtag line) then processFile oldh newh starttag endtag $ not copymode else do if copymode then hPutStrLn newh line else return () processFile oldh newh starttag endtag copymode lookup filepath appname = do -- todo: decide whether to add the app identifier as a parameter (there could be multiple instances of an app running) handle <- openFile filepath ReadWriteMode lookuphelper appname handle where lookuphelper app h = do -- this looks for the start tag. if found, it calls getDeployInfo to get the deploy info; if not, return Nothing because the app is not running. eof <- hIsEOF h if eof then return Nothing else do line <- hGetLine h let starttag = "# START: " ++ appname if (isInfixOf starttag line) then do let matches = matchRegex (mkRegex (appname ++ "([0-9]+)")) line appidentifier = read $ head $ fromJust matches getDeployInfo h appidentifier Nothing -- found start tag; now get deploy info else lookuphelper app h getDeployInfo h identifier mhostname = do -- parse an app's config info to get its deploy info line <- hGetLine h case mhostname of Just hostname -> -- found the hostname; now find the port number if (isInfixOf "proxy_pass" line) then let matches = fromJust $ matchRegex (mkRegex "http://[a-zA-Z0-9]+:([0-9]+);") line -- matches = ["1234"] or whatever the portnum is in return $ Just $ DeployInfo identifier hostname $ read $ head matches else getDeployInfo h identifier mhostname Nothing -> -- hostname is still unknown; find the hostname if (isInfixOf "server_name" line) then let pattern = mkRegex "server_name[[:space:]]+([a-z[:punct:]]+);" hostname = head $ fromJust $ matchRegex pattern line in getDeployInfo h identifier $ Just hostname else getDeployInfo h identifier Nothing restartNginx :: IO () restartNginx = do let createProc = shell "nginx -s reload" (_, _, _, _) <- createProcess createProc -- the last underscore is a handle return ()
scslab/appdeploy
src/NginxUpdater.hs
bsd-3-clause
5,876
0
23
1,987
1,283
611
672
114
1
{-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE ForeignFunctionInterface #-} -- | -- Module : Crypto.Encrypt.SecretBox -- Copyright : (c) Austin Seipp 2011-2013 -- License : BSD3 -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- Authenticated secret-key encryption. -- -- The selected underlying primitive used is -- @crypto_secretbox_xsalsa20poly1305@, a particular combination of -- XSalsa20 and Poly1305. See the specification, \"Cryptography in -- NaCl\": <http://cr.yp.to/highspeed/naclcrypto-20090310.pdf> -- -- This module is intended to be imported @qualified@ to avoid name -- clashes with other cryptographic primitives, e.g. -- -- > import qualified Crypto.Encrypt.SecretBox as SecretBox -- module Crypto.Encrypt.SecretBox ( -- * Security model -- $securitymodel -- * Types SecretBox -- :: * -- * Key creation , randomKey -- :: IO (SecretKey SecretBox) -- * Encrypting messages -- ** Example usage -- $example , encrypt -- :: Nonce SecretBox -> ByteString -> SecretKey SecretBox -> ByteString , decrypt -- :: Nonce SecretBox -> ByteString -> SecretKey SecretBox -> Maybe ByteString ) where import Data.Word import Foreign.C.Types import Foreign.ForeignPtr (withForeignPtr) import Foreign.Ptr import System.IO.Unsafe (unsafePerformIO) import Data.ByteString as S import Data.ByteString.Internal as SI import Data.ByteString.Unsafe as SU import Crypto.Key import Crypto.Nonce import System.Crypto.Random -- $securitymodel -- -- The @'encrypt'@ function is designed to meet the standard notions -- of privacy and authenticity for a secret-key -- authenticated-encryption scheme using nonces. For formal -- definitions see, e.g., Bellare and Namprempre, \"Authenticated -- encryption: relations among notions and analysis of the generic -- composition paradigm,\" Lecture Notes in Computer Science 1976 -- (2000), 531–545, <http://www-cse.ucsd.edu/~mihir/papers/oem.html>. -- -- Note that the length is not hidden. Note also that it is the -- caller's responsibility to ensure the uniqueness of nonces—for -- example, by using nonce 1 for the first message, nonce 2 for the -- second message, etc. Nonces are long enough that randomly generated -- nonces have negligible risk of collision. -- $setup -- >>> :set -XOverloadedStrings -- | A phantom type for representing types related to authenticated, -- secret-key encryption. data SecretBox instance Nonces SecretBox where nonceSize _ = nonceBYTES -- | Generate a random key for performing encryption. -- -- Example usage: -- -- >>> key <- randomKey randomKey :: IO (SecretKey SecretBox) randomKey = SecretKey `fmap` randombytes keyBYTES -- | The @'encrypt'@ function encrypts and authenticates a message @m@ -- using a secret @'SecretKey'@ @k@, and a @'Nonce'@ @n@. encrypt :: Nonce SecretBox -- ^ Nonce -> ByteString -- ^ Input -> SecretKey SecretBox -- ^ Shared @'SecretKey'@ -> ByteString -- ^ Ciphertext encrypt (Nonce n) msg (SecretKey k) = unsafePerformIO $ do -- inputs to crypto_box must be padded let m = S.replicate zeroBYTES 0x0 `S.append` msg mlen = S.length m c <- SI.mallocByteString mlen -- as you can tell, this is unsafe _ <- withForeignPtr c $ \pc -> SU.unsafeUseAsCString m $ \pm -> SU.unsafeUseAsCString n $ \pn -> SU.unsafeUseAsCString k $ \pk -> c_crypto_secretbox pc pm (fromIntegral mlen) pn pk return $! SI.fromForeignPtr c boxZEROBYTES (mlen - boxZEROBYTES) {-# INLINE encrypt #-} -- | The @'decrypt'@ function verifies and decrypts a ciphertext @c@ -- using a secret @'Key'@ @k@, and a @'Nonce'@ @n@. decrypt :: Nonce SecretBox -- ^ Nonce -> ByteString -- ^ Input -> SecretKey SecretBox -- ^ Shared @'SecretKey'@ -> Maybe ByteString -- ^ Ciphertext decrypt (Nonce n) cipher (SecretKey k) = unsafePerformIO $ do let c = S.replicate boxZEROBYTES 0x0 `S.append` cipher clen = S.length c m <- SI.mallocByteString clen -- as you can tell, this is unsafe r <- withForeignPtr m $ \pm -> SU.unsafeUseAsCString c $ \pc -> SU.unsafeUseAsCString n $ \pn -> SU.unsafeUseAsCString k $ \pk -> c_crypto_secretbox_open pm pc (fromIntegral clen) pn pk return $! if r /= 0 then Nothing else Just $ SI.fromForeignPtr m zeroBYTES (clen - zeroBYTES) -- $example -- >>> key <- randomKey -- >>> nonce <- randomNonce :: IO (Nonce SecretBox) -- >>> let cipherText = encrypt nonce "Hello" key -- >>> let recoveredText = decrypt nonce cipherText key -- >>> recoveredText == Just "Hello" -- True keyBYTES :: Int keyBYTES = 32 nonceBYTES :: Int nonceBYTES = 24 zeroBYTES :: Int zeroBYTES = 32 boxZEROBYTES :: Int boxZEROBYTES = 16 foreign import ccall unsafe "xsalsa20poly1305_secretbox" c_crypto_secretbox :: Ptr Word8 -> Ptr CChar -> CULLong -> Ptr CChar -> Ptr CChar -> IO Int foreign import ccall unsafe "xsalsa20poly1305_secretbox_open" c_crypto_secretbox_open :: Ptr Word8 -> Ptr CChar -> CULLong -> Ptr CChar -> Ptr CChar -> IO Int
thoughtpolice/hs-nacl
src/Crypto/Encrypt/SecretBox.hs
bsd-3-clause
5,406
0
19
1,298
778
442
336
-1
-1
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE LambdaCase, OverloadedStrings #-} module Model ( Step(..) , MaybeStep(..) , MatchAlgo(..) , nextStep , undo , context , suggest , setCurrentComment , getCurrentComment , setTransactionComment , getTransactionComment -- * Helpers exported for easier testing , accountsByFrequency , isDuplicateTransaction ) where import Data.Function import Data.List import qualified Data.HashMap.Lazy as HM import Data.Maybe import Data.Monoid import Data.Ord (Down(..)) import Data.Text (Text) import qualified Data.Text as T import Data.Time.Ext hiding (parseTime) import qualified Hledger as HL import Data.Foldable import Control.Applicative import AmountParser import DateParser type Comment = Text type Duplicate = Bool data Step = DateQuestion Comment | DescriptionQuestion Day Comment | AccountQuestion HL.Transaction Comment | AmountQuestion HL.AccountName HL.Transaction Comment | FinalQuestion HL.Transaction Duplicate deriving (Eq, Show) data MaybeStep = Finished HL.Transaction | Step Step deriving (Eq, Show) data MatchAlgo = Fuzzy | Substrings deriving (Eq, Show) nextStep :: HL.Journal -> DateFormat -> Either Text Text -> Step -> IO (Either Text MaybeStep) nextStep journal dateFormat entryText current = case current of DateQuestion comment -> fmap (Step . flip DescriptionQuestion comment) <$> either (parseDateWithToday dateFormat) parseHLDateWithToday entryText DescriptionQuestion day comment -> return $ Right $ Step $ AccountQuestion HL.nulltransaction { HL.tdate = day , HL.tdescription = (fromEither entryText) , HL.tcomment = comment } "" -- empty comment AccountQuestion trans comment | T.null (fromEither entryText) && transactionBalanced trans -> return $ Right $ Step $ FinalQuestion trans (isDuplicateTransaction journal trans) | T.null (fromEither entryText) -- unbalanced -> return $ Left $ "Transaction not balanced! Please balance your transaction before adding it to the journal." | otherwise -> return $ Right $ Step $ AmountQuestion (fromEither entryText) trans comment AmountQuestion name trans comment -> case parseAmount journal (fromEither entryText) of Left err -> return $ Left (T.pack err) Right amount -> return $ Right $ Step $ let newPosting = post' name amount comment in AccountQuestion (addPosting newPosting trans) "" FinalQuestion trans _ | fromEither entryText == "y" -> return $ Right $ Finished trans | otherwise -> return $ Right $ Step $ AccountQuestion trans "" -- | Reverses the last step. -- -- Returns (Left errorMessage), if the step can't be reversed undo :: Step -> Either Text Step undo current = case current of DateQuestion _ -> Left "Already at oldest step in current transaction" DescriptionQuestion _ comment -> return (DateQuestion comment) AccountQuestion trans _ -> return $ case HL.tpostings trans of [] -> DescriptionQuestion (HL.tdate trans) (HL.tcomment trans) ps -> AmountQuestion (HL.paccount (last ps)) trans { HL.tpostings = init ps } (HL.pcomment (last ps)) AmountQuestion _ trans comment -> Right $ AccountQuestion trans comment FinalQuestion trans _ -> undo (AccountQuestion trans "") context :: HL.Journal -> MatchAlgo -> DateFormat -> Text -> Step -> IO [Text] context _ _ dateFormat entryText (DateQuestion _) = parseDateWithToday dateFormat entryText >>= \case Left _ -> return [] Right date -> return [T.pack $ HL.showDate date] context j matchAlgo _ entryText (DescriptionQuestion _ _) = return $ let descs = HL.journalDescriptions j in sortBy (descUses j) $ filter (matches matchAlgo entryText) descs context j matchAlgo _ entryText (AccountQuestion _ _) = return $ let names = accountsByFrequency j in filter (matches matchAlgo entryText) names context journal _ _ entryText (AmountQuestion _ _ _) = return $ maybeToList $ T.pack . HL.showMixedAmount <$> trySumAmount journal entryText context _ _ _ _ (FinalQuestion _ _) = return [] -- | Suggest the initial text of the entry box for each step -- -- For example, it suggests today for the date prompt suggest :: HL.Journal -> DateFormat -> Step -> IO (Maybe Text) suggest _ dateFormat (DateQuestion _) = Just . printDate dateFormat <$> getLocalDay suggest _ _ (DescriptionQuestion _ _) = return Nothing suggest journal _ (AccountQuestion trans _) = return $ if numPostings trans /= 0 && transactionBalanced trans then Nothing else HL.paccount <$> (suggestAccountPosting journal trans) suggest journal _ (AmountQuestion account trans _) = return $ fmap (T.pack . HL.showMixedAmount) $ do case findLastSimilar journal trans of Nothing | null (HL.tpostings trans) -> Nothing -- Don't suggest an amount for first account | otherwise -> Just $ negativeAmountSum trans Just last | transactionBalanced trans || (trans `isSubsetTransaction` last) -> HL.pamount <$> (findPostingByAcc account last) | otherwise -> Just $ negativeAmountSum trans suggest _ _ (FinalQuestion _ _) = return $ Just "y" getCurrentComment :: Step -> Comment getCurrentComment step = case step of DateQuestion c -> c DescriptionQuestion _ c -> c AccountQuestion _ c -> c AmountQuestion _ _ c -> c FinalQuestion trans _ -> HL.tcomment trans setCurrentComment :: Comment -> Step -> Step setCurrentComment comment step = case step of DateQuestion _ -> DateQuestion comment DescriptionQuestion date _ -> DescriptionQuestion date comment AccountQuestion trans _ -> AccountQuestion trans comment AmountQuestion trans name _ -> AmountQuestion trans name comment FinalQuestion trans duplicate -> FinalQuestion trans { HL.tcomment = comment } duplicate getTransactionComment :: Step -> Comment getTransactionComment step = case step of DateQuestion c -> c DescriptionQuestion _ c -> c AccountQuestion trans _ -> HL.tcomment trans AmountQuestion _ trans _ -> HL.tcomment trans FinalQuestion trans _ -> HL.tcomment trans setTransactionComment :: Comment -> Step -> Step setTransactionComment comment step = case step of DateQuestion _ -> DateQuestion comment DescriptionQuestion date _ -> DescriptionQuestion date comment AccountQuestion trans comment' -> AccountQuestion (trans { HL.tcomment = comment }) comment' AmountQuestion name trans comment' -> AmountQuestion name (trans { HL.tcomment = comment }) comment' FinalQuestion trans duplicate -> FinalQuestion trans { HL.tcomment = comment } duplicate -- | Returns true if the pattern is not empty and all of its words occur in the string -- -- If the pattern is empty, we don't want any entries in the list, so nothing is -- selected if the users enters an empty string. Empty inputs are special cased, -- so this is important. matches :: MatchAlgo -> Text -> Text -> Bool matches algo a b | T.null a = False | otherwise = matches' (T.toCaseFold a) (T.toCaseFold b) where matches' a' b' | algo == Fuzzy && T.any (== ':') b' = all (`fuzzyMatch` (T.splitOn ":" b')) (T.words a') | otherwise = all (`T.isInfixOf` b') (T.words a') fuzzyMatch :: Text -> [Text] -> Bool fuzzyMatch _ [] = False fuzzyMatch query (part : partsRest) = case (T.uncons query) of Nothing -> True Just (c, queryRest) | c == ':' -> fuzzyMatch queryRest partsRest | otherwise -> fuzzyMatch query partsRest || case (T.uncons part) of Nothing -> False Just (c2, partRest) | c == c2 -> fuzzyMatch queryRest (partRest : partsRest) | otherwise -> False post' :: HL.AccountName -> HL.MixedAmount -> Comment -> HL.Posting post' account amount comment = HL.nullposting { HL.paccount = account , HL.pamount = amount , HL.pcomment = comment } addPosting :: HL.Posting -> HL.Transaction -> HL.Transaction addPosting p t = t { HL.tpostings = (HL.tpostings t) ++ [p] } trySumAmount :: HL.Journal -> Text -> Maybe HL.MixedAmount trySumAmount ctx = either (const Nothing) Just . parseAmount ctx -- | Given a previous similar transaction, suggest the next posting to enter -- -- This next posting is the one the user likely wants to type in next. suggestNextPosting :: HL.Transaction -> HL.Transaction -> Maybe HL.Posting suggestNextPosting current reference = -- Postings that aren't already used in the new posting let unusedPostings = filter (`notContainedIn` curPostings) refPostings in listToMaybe unusedPostings where [refPostings, curPostings] = map HL.tpostings [reference, current] notContainedIn p = not . any (((==) `on` HL.paccount) p) -- | Given the last transaction entered, suggest the likely most comparable posting -- -- Since the transaction isn't necessarily the same type, we can't rely on matching the data -- so we must use the order. This way if the user typically uses a certain order -- like expense category and then payment method. Useful if entering many similar postings -- in a row. For example, when entering transactions from a credit card statement -- where the first account is usually food, and the second posting is always the credit card. suggestCorrespondingPosting :: HL.Transaction -> HL.Transaction -> Maybe HL.Posting suggestCorrespondingPosting current reference = let postingsEntered = length curPostings in if postingsEntered < (length refPostings) then Just (refPostings !! postingsEntered) else suggestNextPosting current reference where [refPostings, curPostings] = map HL.tpostings [reference, current] findLastSimilar :: HL.Journal -> HL.Transaction -> Maybe HL.Transaction findLastSimilar journal desc = maximumBy (compare `on` HL.tdate) <$> listToMaybe' (filter (((==) `on` HL.tdescription) desc) $ HL.jtxns journal) suggestAccountPosting :: HL.Journal -> HL.Transaction -> Maybe HL.Posting suggestAccountPosting journal trans = case findLastSimilar journal trans of Just t -> suggestNextPosting trans t Nothing -> (last <$> listToMaybe' (HL.jtxns journal)) >>= (suggestCorrespondingPosting trans) -- | Return the first Posting that matches the given account name in the transaction findPostingByAcc :: HL.AccountName -> HL.Transaction -> Maybe HL.Posting findPostingByAcc account = find ((==account) . HL.paccount) . HL.tpostings -- | Returns True if the first transaction is a subset of the second one. -- -- That means, all postings from the first transaction are present in the -- second one. isSubsetTransaction :: HL.Transaction -> HL.Transaction -> Bool isSubsetTransaction current origin = let origPostings = HL.tpostings origin currPostings = HL.tpostings current in null (deleteFirstsBy cmpPosting currPostings origPostings) where cmpPosting a b = HL.paccount a == HL.paccount b && HL.pamount a == HL.pamount b listToMaybe' :: [a] -> Maybe [a] listToMaybe' [] = Nothing listToMaybe' ls = Just ls numPostings :: HL.Transaction -> Int numPostings = length . HL.tpostings -- | Returns True if all postings balance and the transaction is not empty transactionBalanced :: HL.Transaction -> Bool transactionBalanced trans = HL.isTransactionBalanced Nothing trans -- | Computes the sum of all postings in the transaction and inverts it negativeAmountSum :: HL.Transaction -> HL.MixedAmount negativeAmountSum trans = let (rsum, _, _) = HL.transactionPostingBalances trans in HL.divideMixedAmount (-1) rsum -- | Compare two transaction descriptions based on their number of occurences in -- the given journal. descUses :: HL.Journal -> Text -> Text -> Ordering descUses journal = compare `on` (Down . flip HM.lookup usesMap) where usesMap = foldr (count . HL.tdescription) HM.empty $ HL.jtxns journal -- Add one to the current count of this element count :: Text -> HM.HashMap Text (Sum Int) -> HM.HashMap Text (Sum Int) count = HM.alter (<> Just 1) -- | All accounts occuring in the journal sorted in descending order of -- appearance. accountsByFrequency :: HL.Journal -> [HL.AccountName] accountsByFrequency journal = let usedAccounts = map HL.paccount (HL.journalPostings journal) frequencyMap :: HM.HashMap HL.AccountName Int = foldr insertOrPlusOne HM.empty usedAccounts mapWithSubaccounts = foldr insertIfNotPresent frequencyMap (subaccounts frequencyMap) declaredAccounts = HL.expandAccountNames (HL.journalAccountNamesDeclared journal) mapWithDeclared = foldr insertIfNotPresent mapWithSubaccounts declaredAccounts in map fst (sortBy (compare `on` (Down . snd)) (HM.toList mapWithDeclared)) where insertOrPlusOne = HM.alter (Just . maybe 1 (+1)) insertIfNotPresent account = HM.insertWith (flip const) account 0 subaccounts m = HL.expandAccountNames (HM.keys m) -- | Deterimine if a given transaction already occurs in the journal -- -- This function ignores certain attributes of transactions, postings and -- amounts that are either artifacts of knot-tying or are purely for -- presentation. -- -- See the various ...attributes functions in the where clause for details. isDuplicateTransaction :: HL.Journal -> HL.Transaction -> Bool isDuplicateTransaction journal trans = any ((==EQ) . cmpTransaction trans) (HL.jtxns journal) where -- | Transaction attributes that are compared to determine duplicates transactionAttributes = [ cmp HL.tdate, cmp HL.tdate2, cmp HL.tdescription, cmp HL.tstatus , cmp HL.tcode, cmpPostings `on` HL.tpostings ] -- | Posting attributes that are compared to determine duplicates postingAttributes = [ cmp HL.pdate, cmp HL.pdate2, cmp HL.pstatus, cmp HL.paccount , cmpMixedAmount `on` HL.pamount, cmpPType `on` HL.ptype , (fmap fold . liftA2 cmpBalanceAssertion) `on` HL.pbalanceassertion ] -- | Ammount attributes that are compared to determine duplicates amountAttributes = [ cmp HL.acommodity, cmp HL.aprice, cmp HL.aquantity ] -- | Compare two transactions but ignore unimportant details cmpTransaction :: HL.Transaction -> HL.Transaction -> Ordering cmpTransaction = lexical transactionAttributes -- | Compare two posting lists of postings by sorting them deterministically -- and then compare correspondings list elements cmpPostings :: [HL.Posting] -> [HL.Posting] -> Ordering cmpPostings ps1 ps2 = mconcat (zipWith (lexical postingAttributes) (sortPostings ps1) (sortPostings ps2)) -- | Compare two posting styles (this should really be an Eq instance) cmpPType :: HL.PostingType -> HL.PostingType -> Ordering cmpPType = compare `on` pTypeToInt where pTypeToInt :: HL.PostingType -> Int pTypeToInt HL.RegularPosting = 0 pTypeToInt HL.VirtualPosting = 1 pTypeToInt HL.BalancedVirtualPosting = 2 -- | Compare two amounts ignoring unimportant details cmpAmount :: HL.Amount -> HL.Amount -> Ordering cmpAmount = lexical amountAttributes -- | Compare two mixed amounts by first sorting the individual amounts -- deterministically and then comparing them one-by-one. cmpMixedAmount :: HL.MixedAmount -> HL.MixedAmount -> Ordering cmpMixedAmount (HL.Mixed as1) (HL.Mixed as2) = let sortedAs1 = sortBy cmpAmount as1 sortedAs2 = sortBy cmpAmount as2 in mconcat $ compare (length as1) (length as2) : zipWith cmpAmount sortedAs1 sortedAs2 cmpBalanceAssertion :: HL.BalanceAssertion -> HL.BalanceAssertion -> Ordering cmpBalanceAssertion = lexical [cmp HL.baamount, cmp HL.batotal] sortPostings :: [HL.Posting] -> [HL.Posting] sortPostings = sortBy (lexical postingAttributes) -- | Shortcut for 'compare `on`' cmp :: Ord b => (a -> b) -> a -> a -> Ordering cmp f = compare `on` f -- | Apply two things with multiple predicats and combine the results lexicographically lexical :: [a -> b -> Ordering] -> a -> b -> Ordering lexical = fold -- hehe fromEither :: Either a a -> a fromEither = either id id
rootzlevel/hledger-add
src/Model.hs
bsd-3-clause
16,417
0
17
3,490
4,320
2,210
2,110
270
6
----------------------------------------------------------------------------- -- -- Module : Main -- Copyright : Copyright (c) 2015 Artem Tsushko -- License : BSD3 -- -- Maintainer : Artem Tsushko <[email protected]> -- Stability : provisional -- -- | -- ----------------------------------------------------------------------------- module Main ( main ) where import Test.DocTest main :: IO () main = doctest ["-isrc", "src/Main.hs"]
artemtsushko/matching-files-copier
test/Main.hs
bsd-3-clause
467
0
6
79
50
34
16
5
1
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE OverloadedStrings #-} module Duckling.AmountOfMoney.HR.Corpus ( corpus ) where import Data.String import Prelude import Duckling.AmountOfMoney.Types import Duckling.Locale import Duckling.Resolve import Duckling.Testing.Types corpus :: Corpus corpus = (testContext {locale = makeLocale HR Nothing}, testOptions, allExamples) allExamples :: [Example] allExamples = concat [ examples (simple Dollar 1) [ "$1" , "jedan dolar" ] , examples (simple Dollar 10) [ "$10" , "10$" , "deset dolara" ] , examples (simple Cent 1) [ "jedan cent" ] , examples (simple Cent 10) [ "deset centa" ] , examples (simple Dollar 10000) [ "$10.000" , "10K$" , "$10k" ] , examples (simple USD 1.23) [ "USD1,23" ] , examples (simple Dollar 2.23) [ "2 dolara i 23 centa" , "dva dolara 23 centa" , "2 dolara 23" , "dva dolara i 23" ] , examples (simple HRK 1) [ "jedna kuna" ] , examples (simple HRK 2.23) [ "2 kune i 23 lipe" , "dvije kune 23 lipe" , "2 kune 23" , "dvije kune i 23" ] , examples (simple HRK 100) [ "100 kuna" , "sto kuna" ] , examples (simple HRK 200) [ "200 kuna" , "dvije stotine kuna" , "dvjesto kuna" , "dvjesta kuna" ] , examples (simple EUR 1) [ "jedan euro" ] , examples (simple EUR 20) [ "20€" , "20 euros" , "20 Euro" , "20 Euros" , "EUR 20" ] , examples (simple EUR 29.99) [ "EUR29,99" ] , examples (simple INR 20) [ "Rs. 20" , "Rs 20" , "20 Rupija" , "20Rs" , "Rs20" ] , examples (simple INR 20.43) [ "20 Rupija 43" , "dvadeset rupija 43" ] , examples (simple INR 33) [ "INR33" ] , examples (simple Pound 9) [ "£9" , "devet funti" ] , examples (simple GBP 3.01) [ "GBP3,01" , "GBP 3,01" ] , examples (between Dollar (100, 200)) [ "od 100 do 200 dolara" , "od 100 dolara do 200 dolara" , "otprilike 100 do 200 dolara" , "otprilike 100 dolara do 200 dolara" , "100 dolara - 200 dolara" , "100-200 dolara" , "oko 100-200 dolara" , "u blizini 100-200 dolara" , "skoro 100-200 dolara" , "približno 100 do 200 dolara" , "izmedju 100 i 200 dolara" , "izmedju 100 dolara i 200 dolara" ] , examples (under EUR 7) [ "manje od EUR 7" , "ispod EUR 7" ] , examples (above Dollar 1.42) [ "više od jednog dolara i četrdeset dva centa" , "najmanje 1,42 dolara" , "preko 1,42 dolara" , "iznad 1,42 dolara" ] ]
facebookincubator/duckling
Duckling/AmountOfMoney/HR/Corpus.hs
bsd-3-clause
3,564
0
10
1,593
644
368
276
98
1
{-# LANGUAGE CPP, RecordWildCards, BangPatterns #-} {-# OPTIONS_HADDOCK not-home #-} #ifdef __GLASGOW_HASKELL__ {-# LANGUAGE Trustworthy #-} {-# LANGUAGE InterruptibleFFI #-} #endif ----------------------------------------------------------------------------- -- | -- Module : System.Process.Internals -- Copyright : (c) The University of Glasgow 2004 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- __Note:__ This module exports internal implementation details that may -- change anytime. If you want a more stable API, use "System.Process" -- instead. -- ----------------------------------------------------------------------------- module System.Process.Internals ( ProcessHandle(..), ProcessHandle__(..), PHANDLE, closePHANDLE, mkProcessHandle, modifyProcessHandle, withProcessHandle, #ifdef __GLASGOW_HASKELL__ CreateProcess(..), CmdSpec(..), StdStream(..), createProcess_, runGenProcess_, --deprecated #endif startDelegateControlC, endDelegateControlC, stopDelegateControlC, #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__) pPrPr_disableITimers, c_execvpe, ignoreSignal, defaultSignal, #endif withFilePathException, withCEnvironment, translate, fdToHandle, ) where import Control.Concurrent import Control.Exception import Data.Bits import Data.String import Foreign.C import Foreign.Marshal import Foreign.Ptr import Foreign.Storable import System.IO.Unsafe #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__) import Control.Monad import Data.Char import System.IO import System.Posix.Process.Internals ( pPrPr_disableITimers, c_execvpe ) import System.Posix.Types #endif #ifdef __GLASGOW_HASKELL__ import System.Posix.Internals import GHC.IO.Exception import GHC.IO.Encoding import qualified GHC.IO.FD as FD import GHC.IO.Device import GHC.IO.Handle.FD import GHC.IO.Handle.Internals import GHC.IO.Handle.Types hiding (ClosedHandle) import System.IO.Error import Data.Typeable # if defined(mingw32_HOST_OS) import GHC.IO.IOMode import System.Win32.DebugApi (PHANDLE) # else import System.Posix.Signals as Sig # endif #endif #if defined(mingw32_HOST_OS) import System.Directory ( doesFileExist ) import System.Environment ( getEnv ) import System.FilePath #endif #include "HsProcessConfig.h" #include "processFlags.h" #ifdef mingw32_HOST_OS # if defined(i386_HOST_ARCH) # define WINDOWS_CCONV stdcall # elif defined(x86_64_HOST_ARCH) # define WINDOWS_CCONV ccall # else # error Unknown mingw32 arch # endif #endif -- ---------------------------------------------------------------------------- -- ProcessHandle type {- | A handle to a process, which can be used to wait for termination of the process using 'System.Process.waitForProcess'. None of the process-creation functions in this library wait for termination: they all return a 'ProcessHandle' which may be used to wait for the process later. -} data ProcessHandle__ = OpenHandle PHANDLE | ClosedHandle ExitCode data ProcessHandle = ProcessHandle !(MVar ProcessHandle__) !Bool modifyProcessHandle :: ProcessHandle -> (ProcessHandle__ -> IO (ProcessHandle__, a)) -> IO a modifyProcessHandle (ProcessHandle m _) io = modifyMVar m io withProcessHandle :: ProcessHandle -> (ProcessHandle__ -> IO a) -> IO a withProcessHandle (ProcessHandle m _) io = withMVar m io #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__) type PHANDLE = CPid mkProcessHandle :: PHANDLE -> Bool -> IO ProcessHandle mkProcessHandle p mb_delegate_ctlc = do m <- newMVar (OpenHandle p) return (ProcessHandle m mb_delegate_ctlc) closePHANDLE :: PHANDLE -> IO () closePHANDLE _ = return () #else throwErrnoIfBadPHandle :: String -> IO PHANDLE -> IO PHANDLE throwErrnoIfBadPHandle = throwErrnoIfNull -- On Windows, we have to close this HANDLE when it is no longer required, -- hence we add a finalizer to it mkProcessHandle :: PHANDLE -> IO ProcessHandle mkProcessHandle h = do m <- newMVar (OpenHandle h) _ <- mkWeakMVar m (processHandleFinaliser m) return (ProcessHandle m False) processHandleFinaliser :: MVar ProcessHandle__ -> IO () processHandleFinaliser m = modifyMVar_ m $ \p_ -> do case p_ of OpenHandle ph -> closePHANDLE ph _ -> return () return (error "closed process handle") closePHANDLE :: PHANDLE -> IO () closePHANDLE ph = c_CloseHandle ph foreign import WINDOWS_CCONV unsafe "CloseHandle" c_CloseHandle :: PHANDLE -> IO () #endif -- ---------------------------------------------------------------------------- data CreateProcess = CreateProcess{ cmdspec :: CmdSpec, -- ^ Executable & arguments, or shell command cwd :: Maybe FilePath, -- ^ Optional path to the working directory for the new process env :: Maybe [(String,String)], -- ^ Optional environment (otherwise inherit from the current process) std_in :: StdStream, -- ^ How to determine stdin std_out :: StdStream, -- ^ How to determine stdout std_err :: StdStream, -- ^ How to determine stderr close_fds :: Bool, -- ^ Close all file descriptors except stdin, stdout and stderr in the new process (on Windows, only works if std_in, std_out, and std_err are all Inherit) create_group :: Bool, -- ^ Create a new process group delegate_ctlc:: Bool -- ^ Delegate control-C handling. Use this for interactive console processes to let them handle control-C themselves (see below for details). -- -- On Windows this has no effect. -- -- /Since: 1.2.0.0/ } data CmdSpec = ShellCommand String -- ^ A command line to execute using the shell | RawCommand FilePath [String] -- ^ The name of an executable with a list of arguments -- -- The 'FilePath' argument names the executable, and is interpreted -- according to the platform's standard policy for searching for -- executables. Specifically: -- -- * on Unix systems the -- <http://pubs.opengroup.org/onlinepubs/9699919799/functions/execvp.html execvp(3)> -- semantics is used, where if the executable filename does not -- contain a slash (@/@) then the @PATH@ environment variable is -- searched for the executable. -- -- * on Windows systems the Win32 @CreateProcess@ semantics is used. -- Briefly: if the filename does not contain a path, then the -- directory containing the parent executable is searched, followed -- by the current directory, then some standard locations, and -- finally the current @PATH@. An @.exe@ extension is added if the -- filename does not already have an extension. For full details -- see the -- <http://msdn.microsoft.com/en-us/library/windows/desktop/aa365527%28v=vs.85%29.aspx documentation> -- for the Windows @SearchPath@ API. -- | construct a `ShellCommand` from a string literal -- -- /Since: 1.2.1.0/ instance IsString CmdSpec where fromString = ShellCommand data StdStream = Inherit -- ^ Inherit Handle from parent | UseHandle Handle -- ^ Use the supplied Handle | CreatePipe -- ^ Create a new pipe. The returned -- @Handle@ will use the default encoding -- and newline translation mode (just -- like @Handle@s created by @openFile@). -- | This function is almost identical to -- 'System.Process.createProcess'. The only differences are: -- -- * 'Handle's provided via 'UseHandle' are not closed automatically. -- -- * This function takes an extra @String@ argument to be used in creating -- error messages. -- -- This function has been available from the "System.Process.Internals" module -- for some time, and is part of the "System.Process" module since version -- 1.2.1.0. -- -- /Since: 1.2.1.0/ createProcess_ :: String -- ^ function name (for error messages) -> CreateProcess -> IO (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle) #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__) #ifdef __GLASGOW_HASKELL__ -- ----------------------------------------------------------------------------- -- POSIX runProcess with signal handling in the child createProcess_ fun CreateProcess{ cmdspec = cmdsp, cwd = mb_cwd, env = mb_env, std_in = mb_stdin, std_out = mb_stdout, std_err = mb_stderr, close_fds = mb_close_fds, create_group = mb_create_group, delegate_ctlc = mb_delegate_ctlc } = do let (cmd,args) = commandToProcess cmdsp withFilePathException cmd $ alloca $ \ pfdStdInput -> alloca $ \ pfdStdOutput -> alloca $ \ pfdStdError -> alloca $ \ pFailedDoing -> maybeWith withCEnvironment mb_env $ \pEnv -> maybeWith withFilePath mb_cwd $ \pWorkDir -> withMany withFilePath (cmd:args) $ \cstrs -> withArray0 nullPtr cstrs $ \pargs -> do fdin <- mbFd fun fd_stdin mb_stdin fdout <- mbFd fun fd_stdout mb_stdout fderr <- mbFd fun fd_stderr mb_stderr when mb_delegate_ctlc startDelegateControlC -- runInteractiveProcess() blocks signals around the fork(). -- Since blocking/unblocking of signals is a global state -- operation, we better ensure mutual exclusion of calls to -- runInteractiveProcess(). proc_handle <- withMVar runInteractiveProcess_lock $ \_ -> c_runInteractiveProcess pargs pWorkDir pEnv fdin fdout fderr pfdStdInput pfdStdOutput pfdStdError (if mb_delegate_ctlc then 1 else 0) ((if mb_close_fds then RUN_PROCESS_IN_CLOSE_FDS else 0) .|.(if mb_create_group then RUN_PROCESS_IN_NEW_GROUP else 0)) pFailedDoing when (proc_handle == -1) $ do cFailedDoing <- peek pFailedDoing failedDoing <- peekCString cFailedDoing when mb_delegate_ctlc stopDelegateControlC throwErrno (fun ++ ": " ++ failedDoing) hndStdInput <- mbPipe mb_stdin pfdStdInput WriteMode hndStdOutput <- mbPipe mb_stdout pfdStdOutput ReadMode hndStdError <- mbPipe mb_stderr pfdStdError ReadMode ph <- mkProcessHandle proc_handle mb_delegate_ctlc return (hndStdInput, hndStdOutput, hndStdError, ph) {-# NOINLINE runInteractiveProcess_lock #-} runInteractiveProcess_lock :: MVar () runInteractiveProcess_lock = unsafePerformIO $ newMVar () -- ---------------------------------------------------------------------------- -- Delegated control-C handling on Unix -- See ticket https://ghc.haskell.org/trac/ghc/ticket/2301 -- and http://www.cons.org/cracauer/sigint.html -- -- While running an interactive console process like ghci or a shell, we want -- to let that process handle Ctl-C keyboard interrupts how it sees fit. -- So that means we need to ignore the SIGINT/SIGQUIT Unix signals while we're -- running such programs. And then if/when they do terminate, we need to check -- if they terminated due to SIGINT/SIGQUIT and if so then we behave as if we -- got the Ctl-C then, by throwing the UserInterrupt exception. -- -- If we run multiple programs like this concurrently then we have to be -- careful to avoid messing up the signal handlers. We keep a count and only -- restore when the last one has finished. {-# NOINLINE runInteractiveProcess_delegate_ctlc #-} runInteractiveProcess_delegate_ctlc :: MVar (Maybe (Int, Sig.Handler, Sig.Handler)) runInteractiveProcess_delegate_ctlc = unsafePerformIO $ newMVar Nothing startDelegateControlC :: IO () startDelegateControlC = modifyMVar_ runInteractiveProcess_delegate_ctlc $ \delegating -> do case delegating of Nothing -> do -- We're going to ignore ^C in the parent while there are any -- processes using ^C delegation. -- -- If another thread runs another process without using -- delegation while we're doing this then it will inherit the -- ignore ^C status. old_int <- installHandler sigINT Ignore Nothing old_quit <- installHandler sigQUIT Ignore Nothing return (Just (1, old_int, old_quit)) Just (count, old_int, old_quit) -> do -- If we're already doing it, just increment the count let !count' = count + 1 return (Just (count', old_int, old_quit)) stopDelegateControlC :: IO () stopDelegateControlC = modifyMVar_ runInteractiveProcess_delegate_ctlc $ \delegating -> do case delegating of Just (1, old_int, old_quit) -> do -- Last process, so restore the old signal handlers _ <- installHandler sigINT old_int Nothing _ <- installHandler sigQUIT old_quit Nothing return Nothing Just (count, old_int, old_quit) -> do -- Not the last, just decrement the count let !count' = count - 1 return (Just (count', old_int, old_quit)) Nothing -> return Nothing -- should be impossible endDelegateControlC :: ExitCode -> IO () endDelegateControlC exitCode = do stopDelegateControlC -- And if the process did die due to SIGINT or SIGQUIT then -- we throw our equivalent exception here (synchronously). -- -- An alternative design would be to throw to the main thread, as the -- normal signal handler does. But since we can be sync here, we do so. -- It allows the code locally to catch it and do something. case exitCode of ExitFailure n | isSigIntQuit n -> throwIO UserInterrupt _ -> return () where isSigIntQuit n = sig == sigINT || sig == sigQUIT where sig = fromIntegral (-n) foreign import ccall unsafe "runInteractiveProcess" c_runInteractiveProcess :: Ptr CString -> CString -> Ptr CString -> FD -> FD -> FD -> Ptr FD -> Ptr FD -> Ptr FD -> CInt -- reset child's SIGINT & SIGQUIT handlers -> CInt -- flags -> Ptr CString -> IO PHANDLE #endif /* __GLASGOW_HASKELL__ */ ignoreSignal, defaultSignal :: CLong ignoreSignal = CONST_SIG_IGN defaultSignal = CONST_SIG_DFL #else #ifdef __GLASGOW_HASKELL__ createProcess_ fun CreateProcess{ cmdspec = cmdsp, cwd = mb_cwd, env = mb_env, std_in = mb_stdin, std_out = mb_stdout, std_err = mb_stderr, close_fds = mb_close_fds, create_group = mb_create_group, delegate_ctlc = _ignored } = do (cmd, cmdline) <- commandToProcess cmdsp withFilePathException cmd $ alloca $ \ pfdStdInput -> alloca $ \ pfdStdOutput -> alloca $ \ pfdStdError -> maybeWith withCEnvironment mb_env $ \pEnv -> maybeWith withCWString mb_cwd $ \pWorkDir -> do withCWString cmdline $ \pcmdline -> do fdin <- mbFd fun fd_stdin mb_stdin fdout <- mbFd fun fd_stdout mb_stdout fderr <- mbFd fun fd_stderr mb_stderr -- #2650: we must ensure mutual exclusion of c_runInteractiveProcess, -- because otherwise there is a race condition whereby one thread -- has created some pipes, and another thread spawns a process which -- accidentally inherits some of the pipe handles that the first -- thread has created. -- -- An MVar in Haskell is the best way to do this, because there -- is no way to do one-time thread-safe initialisation of a mutex -- the C code. Also the MVar will be cheaper when not running -- the threaded RTS. proc_handle <- withMVar runInteractiveProcess_lock $ \_ -> throwErrnoIfBadPHandle fun $ c_runInteractiveProcess pcmdline pWorkDir pEnv fdin fdout fderr pfdStdInput pfdStdOutput pfdStdError ((if mb_close_fds then RUN_PROCESS_IN_CLOSE_FDS else 0) .|.(if mb_create_group then RUN_PROCESS_IN_NEW_GROUP else 0)) hndStdInput <- mbPipe mb_stdin pfdStdInput WriteMode hndStdOutput <- mbPipe mb_stdout pfdStdOutput ReadMode hndStdError <- mbPipe mb_stderr pfdStdError ReadMode ph <- mkProcessHandle proc_handle return (hndStdInput, hndStdOutput, hndStdError, ph) {-# NOINLINE runInteractiveProcess_lock #-} runInteractiveProcess_lock :: MVar () runInteractiveProcess_lock = unsafePerformIO $ newMVar () -- The following functions are always present in the export list. For -- compatibility with the non-Windows code, we provide the same functions with -- matching type signatures, but implemented as no-ops. For details, see: -- <https://github.com/haskell/process/pull/21> startDelegateControlC :: IO () startDelegateControlC = return () endDelegateControlC :: ExitCode -> IO () endDelegateControlC _ = return () stopDelegateControlC :: IO () stopDelegateControlC = return () -- End no-op functions foreign import ccall unsafe "runInteractiveProcess" c_runInteractiveProcess :: CWString -> CWString -> Ptr CWString -> FD -> FD -> FD -> Ptr FD -> Ptr FD -> Ptr FD -> CInt -- flags -> IO PHANDLE #endif #endif /* __GLASGOW_HASKELL__ */ fd_stdin, fd_stdout, fd_stderr :: FD fd_stdin = 0 fd_stdout = 1 fd_stderr = 2 mbFd :: String -> FD -> StdStream -> IO FD mbFd _ _std CreatePipe = return (-1) mbFd _fun std Inherit = return std mbFd fun _std (UseHandle hdl) = withHandle fun hdl $ \Handle__{haDevice=dev,..} -> case cast dev of Just fd -> do -- clear the O_NONBLOCK flag on this FD, if it is set, since -- we're exposing it externally (see #3316) fd' <- FD.setNonBlockingMode fd False return (Handle__{haDevice=fd',..}, FD.fdFD fd') Nothing -> ioError (mkIOError illegalOperationErrorType "createProcess" (Just hdl) Nothing `ioeSetErrorString` "handle is not a file descriptor") mbPipe :: StdStream -> Ptr FD -> IOMode -> IO (Maybe Handle) mbPipe CreatePipe pfd mode = fmap Just (pfdToHandle pfd mode) mbPipe _std _pfd _mode = return Nothing pfdToHandle :: Ptr FD -> IOMode -> IO Handle pfdToHandle pfd mode = do fd <- peek pfd let filepath = "fd:" ++ show fd (fD,fd_type) <- FD.mkFD (fromIntegral fd) mode (Just (Stream,0,0)) -- avoid calling fstat() False {-is_socket-} False {-non-blocking-} fD' <- FD.setNonBlockingMode fD True -- see #3316 #if __GLASGOW_HASKELL__ >= 704 enc <- getLocaleEncoding #else let enc = localeEncoding #endif mkHandleFromFD fD' fd_type filepath mode False {-is_socket-} (Just enc) -- ---------------------------------------------------------------------------- -- commandToProcess {- | Turns a shell command into a raw command. Usually this involves wrapping it in an invocation of the shell. There's a difference in the signature of commandToProcess between the Windows and Unix versions. On Unix, exec takes a list of strings, and we want to pass our command to /bin/sh as a single argument. On Windows, CreateProcess takes a single string for the command, which is later decomposed by cmd.exe. In this case, we just want to prepend @\"c:\WINDOWS\CMD.EXE \/c\"@ to our command line. The command-line translation that we normally do for arguments on Windows isn't required (or desirable) here. -} #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__) commandToProcess :: CmdSpec -> (FilePath, [String]) commandToProcess (ShellCommand string) = ("/bin/sh", ["-c", string]) commandToProcess (RawCommand cmd args) = (cmd, args) #else commandToProcess :: CmdSpec -> IO (FilePath, String) commandToProcess (ShellCommand string) = do cmd <- findCommandInterpreter return (cmd, translate cmd ++ " /c " ++ string) -- We don't want to put the cmd into a single -- argument, because cmd.exe will not try to split it up. Instead, -- we just tack the command on the end of the cmd.exe command line, -- which partly works. There seem to be some quoting issues, but -- I don't have the energy to find+fix them right now (ToDo). --SDM -- (later) Now I don't know what the above comment means. sigh. commandToProcess (RawCommand cmd args) = do return (cmd, translate cmd ++ concatMap ((' ':) . translate) args) -- Find CMD.EXE (or COMMAND.COM on Win98). We use the same algorithm as -- system() in the VC++ CRT (Vc7/crt/src/system.c in a VC++ installation). findCommandInterpreter :: IO FilePath findCommandInterpreter = do -- try COMSPEC first catchJust (\e -> if isDoesNotExistError e then Just e else Nothing) (getEnv "COMSPEC") $ \_ -> do -- try to find CMD.EXE or COMMAND.COM {- XXX We used to look at _osver (using cbits) and pick which shell to use with let filename | osver .&. 0x8000 /= 0 = "command.com" | otherwise = "cmd.exe" We ought to use GetVersionEx instead, but for now we just look for either filename -} path <- getEnv "PATH" let -- use our own version of System.Directory.findExecutable, because -- that assumes the .exe suffix. search :: [FilePath] -> IO (Maybe FilePath) search [] = return Nothing search (d:ds) = do let path1 = d </> "cmd.exe" path2 = d </> "command.com" b1 <- doesFileExist path1 b2 <- doesFileExist path2 if b1 then return (Just path1) else if b2 then return (Just path2) else search ds -- mb_path <- search (splitSearchPath path) case mb_path of Nothing -> ioError (mkIOError doesNotExistErrorType "findCommandInterpreter" Nothing Nothing) Just cmd -> return cmd #endif -- ------------------------------------------------------------------------ -- Escaping commands for shells {- On Windows we also use this for running commands. We use CreateProcess, passing a single command-line string (lpCommandLine) as its argument. (CreateProcess is well documented on http://msdn.microsoft.com.) - It parses the beginning of the string to find the command. If the file name has embedded spaces, it must be quoted, using double quotes thus "foo\this that\cmd" arg1 arg2 - The invoked command can in turn access the entire lpCommandLine string, and the C runtime does indeed do so, parsing it to generate the traditional argument vector argv[0], argv[1], etc. It does this using a complex and arcane set of rules which are described here: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccelng/htm/progs_12.asp (if this URL stops working, you might be able to find it by searching for "Parsing C Command-Line Arguments" on MSDN. Also, the code in the Microsoft C runtime that does this translation is shipped with VC++). Our goal in runProcess is to take a command filename and list of arguments, and construct a string which inverts the translatsions described above, such that the program at the other end sees exactly the same arguments in its argv[] that we passed to rawSystem. This inverse translation is implemented by 'translate' below. Here are some pages that give informations on Windows-related limitations and deviations from Unix conventions: http://support.microsoft.com/default.aspx?scid=kb;en-us;830473 Command lines and environment variables effectively limited to 8191 characters on Win XP, 2047 on NT/2000 (probably even less on Win 9x): http://www.microsoft.com/windowsxp/home/using/productdoc/en/default.asp?url=/WINDOWSXP/home/using/productdoc/en/percent.asp Command-line substitution under Windows XP. IIRC these facilities (or at least a large subset of them) are available on Win NT and 2000. Some might be available on Win 9x. http://www.microsoft.com/windowsxp/home/using/productdoc/en/default.asp?url=/WINDOWSXP/home/using/productdoc/en/Cmd.asp How CMD.EXE processes command lines. Note: CreateProcess does have a separate argument (lpApplicationName) with which you can specify the command, but we have to slap the command into lpCommandLine anyway, so that argv[0] is what a C program expects (namely the application name). So it seems simpler to just use lpCommandLine alone, which CreateProcess supports. -} translate :: String -> String #if mingw32_HOST_OS translate xs = '"' : snd (foldr escape (True,"\"") xs) where escape '"' (_, str) = (True, '\\' : '"' : str) escape '\\' (True, str) = (True, '\\' : '\\' : str) escape '\\' (False, str) = (False, '\\' : str) escape c (_, str) = (False, c : str) -- See long comment above for what this function is trying to do. -- -- The Bool passed back along the string is True iff the -- rest of the string is a sequence of backslashes followed by -- a double quote. #else translate "" = "''" translate str -- goodChar is a pessimistic predicate, such that if an argument is -- non-empty and only contains goodChars, then there is no need to -- do any quoting or escaping | all goodChar str = str | otherwise = '\'' : foldr escape "'" str where escape '\'' = showString "'\\''" escape c = showChar c goodChar c = isAlphaNum c || c `elem` "-_.,/" #endif -- ---------------------------------------------------------------------------- -- Utils withFilePathException :: FilePath -> IO a -> IO a withFilePathException fpath act = handle mapEx act where mapEx ex = ioError (ioeSetFileName ex fpath) #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__) withCEnvironment :: [(String,String)] -> (Ptr CString -> IO a) -> IO a withCEnvironment envir act = let env' = map (\(name, val) -> name ++ ('=':val)) envir in withMany withCString env' (\pEnv -> withArray0 nullPtr pEnv act) #else withCEnvironment :: [(String,String)] -> (Ptr CWString -> IO a) -> IO a withCEnvironment envir act = let env' = foldr (\(name, val) env -> name ++ ('=':val)++'\0':env) "\0" envir in withCWString env' (act . castPtr) #endif -- ---------------------------------------------------------------------------- -- Deprecated / compat #ifdef __GLASGOW_HASKELL__ {-# DEPRECATED runGenProcess_ "Please do not use this anymore, use the ordinary 'System.Process.createProcess'. If you need the SIGINT handling, use delegate_ctlc = True (runGenProcess_ is now just an imperfectly emulated stub that probably duplicates or overrides your own signal handling)." #-} runGenProcess_ :: String -- ^ function name (for error messages) -> CreateProcess -> Maybe CLong -- ^ handler for SIGINT -> Maybe CLong -- ^ handler for SIGQUIT -> IO (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle) #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__) runGenProcess_ fun c (Just sig) (Just sig') | sig == defaultSignal && sig == sig' = createProcess_ fun c { delegate_ctlc = True } runGenProcess_ fun c _ _ = createProcess_ fun c #else runGenProcess_ fun c _ _ = createProcess_ fun c #endif #endif
DavidAlphaFox/ghc
libraries/process/System/Process/Internals.hs
bsd-3-clause
28,555
0
32
7,388
2,853
1,598
1,255
126
2
module Data.Connection where import qualified Data.ByteString as B import qualified Data.ByteString.Lazy.Internal as L import qualified System.IO.Streams as S -- | A simple connection abstraction. -- -- 'Connection' s from this package are supposed to have following properties: -- -- * 'S.InputStream' is choosen to simplify streaming processing. -- You can easily push back some data with 'S.unRead', -- reading 'S.InputStream' will block until GHC IO manager find data is ready, for example: -- @'S.readExactly' 1024@ will block until at least 1024 bytes are available. -- -- * The type @'L.ByteString' -> 'IO' ()@ is choosen because it worked well with haskell's builder infrastructure. -- <http://hackage.haskell.org/package/network-2.6.2.1/docs/Network-Socket-ByteString.html#g:2 vector-IO> -- is used automatically when there's more than one chunk to send to save system call. -- -- * 'connExtraInfo' field store extra data about the connection, 'N.SockAddr' for example. -- You can also use this field as a type tag to distinguish different type of connection. -- -- * 'close' should close connection resource, thus the 'Connection' shouldn't be used anymore -- after 'close' is called. -- -- * You should make sure there's no pending recv/send before you 'close' a 'Connection'. -- That means either you call 'close' in the same thread you recv/send, or use async exception -- to terminate recv/send thread before call 'close' in other thread(such as a reaper thread). -- Otherwise you may run into -- <https://mail.haskell.org/pipermail/haskell-cafe/2014-September/115823.html race-connections>. -- -- * Exception or closed by other peer during recv/send will NOT close underline socket, -- you should always use 'close' with 'E.bracket' to ensure safety. -- -- @since 1.0 -- data Connection a = Connection { source :: {-# UNPACK #-} !(S.InputStream B.ByteString) -- ^ receive data as 'S.InputStream' , send :: L.ByteString -> IO () -- ^ send data with connection , close :: IO () -- ^ close connection , connExtraInfo :: a -- ^ extra info }
didi-FP/tcp-streams
Data/Connection.hs
bsd-3-clause
2,248
0
12
508
129
94
35
9
0
{-# LANGUAGE FlexibleInstances #-} import Music.Prelude import qualified Data.Interval as I import qualified TypeUnary.Nat class Display a where display :: a -> IO () display = open . displayS displayS :: a -> Score StandardNote displayS = error "Not implemnented: displayS" instance Display Pitch where displayS = displayS . (pure :: a -> Score a) instance Display Interval where displayS = (<> c) . fmap (fromPitch'.pure) . (pure :: a -> Score a) . (c .+^) instance Display [Pitch] where displayS = fmap (fromPitch'.pure) . compress 4 . scat . map (pure :: a -> Score a) instance Display (Ambitus Pitch) where displayS = displayS . ambitusShowPitches instance TypeUnary.Nat.IsNat a => Display (Equal a) where displayS = displayS . equalToPitch instance TypeUnary.Nat.IsNat a => Display [Equal a] where displayS = displayS . fmap equalToPitch instance Display (Score Pitch) where displayS = fmap (fromPitch'.pure) -- TOOD hide dynamics etc instance Display Dynamics where displayS x = level x c instance Display Part where displayS x = set parts' x c instance Display Instrument where displayS = displayS . tutti instance Display String where displayS x = text x c -- TODO move -- | Pitches to show when drawing an interval. -- Always return a list of 1 or 2 elements. ambitusShowPitches :: Num a => Ambitus a -> [a] ambitusShowPitches x = case (I.lowerBound x, I.upperBound x) of (I.Finite x, I.Finite y) -> [x,y] (_, I.Finite y) -> [y] (I.Finite x, _) -> [x] ambitus :: Iso' (Pitch, Pitch) (Ambitus Pitch) ambitus = iso f g where f (x,y) = I.interval (I.Finite x, True) (I.Finite y, True) g = undefined -- TODO move instance TypeUnary.Nat.IsNat a => Enum (Equal a) where toEnum = toEqual fromEnum = fromEqual instance TypeUnary.Nat.IsNat a => Real (Equal a) where toRational = toRational . fromEqual instance TypeUnary.Nat.IsNat a => Integral (Equal a) where toInteger = toInteger . fromEqual quotRem x y = (fromIntegral q, fromIntegral r) where (q, r) = quotRem (fromIntegral x) (fromIntegral y) -- TODO reexport IsNat equalToPitch :: TypeUnary.Nat.IsNat a => Equal a -> Pitch equalToPitch = equal12ToPitch . toEqual12 toEqual12 :: TypeUnary.Nat.IsNat a => Equal a -> Equal12 toEqual12 = cast equal12ToPitch :: Equal12 -> Pitch equal12ToPitch = (c .+^) . spell modally . (fromIntegral :: Equal12 -> Semitones)
music-suite/music-preludes
sketch/display.hs
bsd-3-clause
2,404
0
11
467
869
458
411
55
3
{-# LANGUAGE Trustworthy, TypeOperators, ScopedTypeVariables, BangPatterns, PolyKinds, DataKinds, ConstraintKinds, RankNTypes, TypeFamilies, MultiParamTypeClasses, FunctionalDependencies, FlexibleContexts, FlexibleInstances, UndecidableInstances #-} module Type.BST.BST ( -- * BST, Record and Union -- ** Data Types BST(Leaf, Node), Record(None, Triple), Union(Top, GoL, GoR) -- ** Conversion , Fromlistable(Fromlist, fromlist) , Fromsumable(fromsum) , Foldable(virtual), tolist, tosum, Tolist -- ** Accessible , Accessible(At), at, proj, inj, (!) , AccessibleF(), smap, supdate, adjust, update, (<$*>) , Contains, ContainedBy -- ** Searchable , Searchable(Smap, atX, projX, injX), (!?), SearchableF(smapX), supdateX, adjustX, updateX, (<$*?>) -- ** Unioncasable , Unioncasable, unioncase, UnioncasableX(unioncaseX) -- ** Inclusion , Includes, IncludedBy, shrink, expand -- ** Balancing , Balanceable(Balance, balance) -- ** Metamorphosis , Metamorphosable(metamorphose) -- ** Merging , Mergeable(Merge, merge, MergeE, mergeE) -- ** Insertion , Insertable(Insert, insert) -- ** Deletion , Deletable(Delete, delete) -- ** Min and Max , Minnable(Findmin, splitmin), findmin, deletemin , Maxable(Findmax, splitmax), findmax, deletemax ) where import Data.Maybe import GHC.TypeLits import Type.BST.Proxy import Type.BST.Item import Type.BST.Compare import Type.BST.List import Type.BST.Sum {- Data Types -} -- | Type-level binary search tree used as an \"ordered map\". -- -- @a@ is supposed to be a proper type @'Item' key val@ of the kind @*@, -- where @key@ is a key type of an arbitrary kind -- @val@ is a value type of the kind @*@. -- All 'Item's in a 'BST' should have different keys. -- -- Type inference works very well with 'BST's, and value types can naturally be /polymorphic/. -- -- If you want to build a new 'BST', use 'Fromlist', whose result is guaranteed to be balanced. data BST a = Leaf | Node (BST a) a (BST a) -- | Dependently-typed record, or an /extensible/ record. -- If you want to build a new 'Record', use 'fromlist'. data family Record (s :: BST *) data instance Record Leaf = None data instance Record (Node l a r) = Triple (Record l) a (Record r) instance (Foldable s, Show (List (Tolist s))) => Show (Record s) where showsPrec p rc = showParen (p > 10) $ showString "<Record> " . showsPrec 11 (tolist rc) -- | Dependently-typed union, or an /extensible/ union. -- If you want to build a new 'Union', use 'inj' or 'fromsum'. data family Union (s :: BST *) data instance Union Leaf data instance Union (Node l a r) = Top a | GoL (Union l) | GoR (Union r) instance Show (Union Leaf) where show !_ = undefined instance (Show a, Show (Union l), Show (Union r)) => Show (Union (Node l a r)) where showsPrec p (Top x) = showParen (p > 10) $ showString "<Union> " . showsPrec 11 x showsPrec p (GoL l) = showsPrec p l showsPrec p (GoR r) = showsPrec p r {- Conversion -} class Fromlistable (as :: [*]) where -- | /O(n log n)/. Convert from a type-level list to a 'BST'. -- If @as@ has two or more 'Item's that have the same key, only the first one will be added to the result. -- -- If @as@ and @bs@ have the same items (just in different orders), @Fromlist as == Fromlist bs@. -- -- Example: -- -- >>> type T = Fromlist [0 |> Bool, 4 |> String, 2 |> Int, 3 |> Double, 1 |> Char] -- >>> :kind! T -- T :: BST * -- = 'Node -- ('Node 'Leaf (Item 0 Bool) ('Node 'Leaf (Item 1 Char) 'Leaf)) -- (Item 2 Int) -- ('Node ('Node 'Leaf (Item 3 Double) 'Leaf) (Item 4 [Char]) 'Leaf) -- >>> :kind! Tolist T -- Tolist T :: [*] -- = '[Item 0 Bool, Item 1 Char, Item 2 Int, Item 3 Double, -- Item 4 [Char]] type Fromlist as :: BST * -- | /O(n log n)/. Convert from a 'List' to a 'Record'. -- -- If @rc@ and @rc'@ have the same items (just in different orders), @fromlist rc == fromlist rc'@. -- -- Example (where @T@ is a type defined in the previous example): -- -- >>> let rct = fromlist $ p3 |> 3 .:. p0 |> True .:. p2 |> 10 .:. p4 |> "wow" .:. p1 |> 'a' .:. Nil -- >>> rct -- <Record> [<0> True,<1> 'a',<2> 10,<3> 3,<4> "wow"] -- >>> :type rct -- rct -- :: (Num a1, Num a) => -- Record -- ('Node -- ('Node 'Leaf (Item 0 Bool) ('Node 'Leaf (Item 1 Char) 'Leaf)) -- (Item 2 a1) -- ('Node ('Node 'Leaf (Item 3 a) 'Leaf) (Item 4 [Char]) 'Leaf)) -- >>> :type rct :: Record T -- rct :: Record T :: Record T fromlist :: List as -> Record (Fromlist as) instance (Sortable as, Fromslistable (Sort as)) => Fromlistable as where type Fromlist as = Fromslist (Sort as) fromlist xs = fromslist (sort xs) {-# INLINE fromlist #-} type Fromslist as = Fromslist' True (Length as) 0 as '[] type Fromslistable as = Fromslistable' True (Length as) 0 as '[] fromslist :: Fromslistable as => List as -> Record (Fromslist as) fromslist (xs :: List as) = fromslist' (Proxy :: Proxy True) (Proxy :: Proxy (Length as)) (Proxy :: Proxy 0) xs Nil {-# INLINE fromslist #-} type FromslistR as = Fromslist' False (Length as) 0 as '[] type FromslistableR as = Fromslistable' False (Length as) 0 as '[] fromslistR :: FromslistableR as => List as -> Record (FromslistR as) fromslistR (xs :: List as) = fromslist' (Proxy :: Proxy False) (Proxy :: Proxy (Length as)) (Proxy :: Proxy 0) xs Nil {-# INLINE fromslistR #-} class Fromslistable' (fw :: Bool) (m :: Nat) (n :: Nat) (as :: [*]) (bs :: [*]) where type Fromslist' fw m n as bs :: BST * fromslist' :: Proxy fw -> Proxy m -> Proxy n -> List as -> List bs -> Record (Fromslist' fw m n as bs) instance Fromslistable' fw 0 0 '[] '[] where type Fromslist' fw 0 0 '[] '[] = Leaf fromslist' _ _ _ _ _ = None {-# INLINE fromslist' #-} instance Fromslistable' fw 0 1 '[] '[b] where type Fromslist' fw 0 1 '[] '[b] = Node Leaf b Leaf fromslist' _ _ _ _ (Cons y _) = Triple None y None {-# INLINE fromslist' #-} instance Fromslistable'' (m <=? n + 1) fw m n (a ': as) bs => Fromslistable' fw m n (a ': as) bs where type Fromslist' fw m n (a ': as) bs = Fromslist'' (m <=? n + 1) fw m n (a ': as) bs fromslist' = fromslist'' (Proxy :: Proxy (m <=? n + 1)) {-# INLINE fromslist' #-} class Fromslistable'' (b :: Bool) (fw :: Bool) (m :: Nat) (n :: Nat) (as :: [*]) (bs :: [*]) where type Fromslist'' b fw m n as bs :: BST * fromslist'' :: Proxy b -> Proxy fw -> Proxy m -> Proxy n -> List as -> List bs -> Record (Fromslist'' b fw m n as bs) instance (Fromslistable as, FromslistableR bs) => Fromslistable'' True True m n (a ': as) bs where type Fromslist'' True True m n (a ': as) bs = Node (FromslistR bs) a (Fromslist as) fromslist'' _ _ _ _ (Cons x xs) ys = Triple (fromslistR ys) x (fromslist xs) {-# INLINABLE fromslist'' #-} instance (FromslistableR as, Fromslistable bs) => Fromslistable'' True False m n (a ': as) bs where type Fromslist'' True False m n (a ': as) bs = Node (FromslistR as) a (Fromslist bs) fromslist'' _ _ _ _ (Cons x xs) ys = Triple (fromslistR xs) x (fromslist ys) {-# INLINABLE fromslist'' #-} instance Fromslistable' fw (m - 1) (n + 1) as (a ': bs) => Fromslistable'' False fw m n (a ': as) bs where type Fromslist'' False fw m n (a ': as) bs = Fromslist' fw (m - 1) (n + 1) as (a ': bs) fromslist'' _ _ _ _ (Cons x xs) ys = fromslist' (Proxy :: Proxy fw) (Proxy :: Proxy (m - 1)) (Proxy :: Proxy (n + 1)) xs (x .:. ys) {-# INLINABLE fromslist'' #-} class Fromsumable (as :: [*]) where -- | /O(n)/. Convert from a 'Sum' to a 'Union'. fromsum :: Sum as -> Union (Fromlist as) instance Fromsumable' as (Fromlist as) => Fromsumable as where fromsum = fromsum' {-# INLINE fromsum #-} class Fromsumable' (as :: [*]) (t :: BST *) where fromsum' :: Sum as -> Union t instance Fromsumable' '[] t where fromsum' !_ = undefined {-# INLINE fromsum' #-} instance (Contains t key a, Fromsumable' as t) => Fromsumable' (key |> a ': as) t where fromsum' (Head (Item x)) = inj (Proxy :: Proxy key) x fromsum' (Tail s) = fromsum' s {-# INLINABLE fromsum' #-} class Foldable (t :: BST *) where type Tolist' t (as :: [*]) :: [*] tolist' :: Record t -> List as -> List (Tolist' t as) tosum' :: Either (Sum as) (Union t) -> Sum (Tolist' t as) -- | Build a 'Record' with empty 'Item's. virtual :: Record t -- | /O(n)/. Convert from a 'BST' to a type-level sorted list. type family Tolist (t :: BST *) :: [*] type instance Tolist t = Tolist' t '[] -- | /O(n)/. Convert from a 'Record' to a 'List'. tolist :: Foldable t => Record t -> List (Tolist t) tolist rc = tolist' rc Nil {-# INLINE tolist #-} -- | /O(n)/. Convert from a 'Union' to a 'Sum'. tosum :: Foldable t => Union t -> Sum (Tolist t) tosum (u :: Union t) = tosum' (Right u :: Either (Sum '[]) (Union t)) {-# INLINE tosum #-} instance Foldable Leaf where type Tolist' Leaf as = as tolist' _ xs = xs {-# INLINE tolist' #-} tosum' (Right !_) = undefined tosum' (Left s) = s {-# INLINE tosum' #-} virtual = None {-# INLINE virtual #-} instance (Foldable l, Foldable r) => Foldable (Node l a r) where type Tolist' (Node l a r) as = Tolist' l (a ': Tolist' r as) tolist' (Triple l x r) xs = tolist' l (x .:. tolist' r xs) {-# INLINABLE tolist' #-} tosum' (Right (Top x) :: Either (Sum as) (Union (Node l a r))) = tosum' (Left $ Head x :: Either (Sum (a ': Tolist' r as)) (Union l)) tosum' (Right (GoL u) :: Either (Sum as) (Union (Node l a r))) = tosum' (Right u :: Either (Sum (a ': Tolist' r as)) (Union l)) tosum' (Right (GoR u) :: Either (Sum as) (Union (Node l a r))) = tosum' (Left $ Tail $ tosum' (Right u :: Either (Sum as) (Union r)) :: Either (Sum (a ': Tolist' r as)) (Union l)) tosum' (Left s :: Either (Sum as) (Union (Node l a r))) = tosum' (Left $ Tail $ tosum' (Left s :: Either (Sum as) (Union r)) :: Either (Sum (a ': Tolist' r as)) (Union l)) {-# INLINABLE tosum' #-} virtual = Triple (virtual :: Record l) (error "Type.BST.BST.virtual: an empty item") (virtual :: Record r) {-# INLINABLE virtual #-} {- Accessible -} -- | @t@ has an 'Item' with @key@. class Searchable t key (At t key) => Accessible (t :: BST *) (key :: k) where -- | /O(log n)/. Find the type at @key@. type At t key :: * instance Accessible' (Compare key key') (Node l (key' |> a) r) key => Accessible (Node l (key' |> a) r) key where type At (Node l (key' |> a) r) key = At' (Compare key key') (Node l (key' |> a) r) key class Searchable' o t key (At' o t key) => Accessible' (o :: Ordering) (t :: BST *) (key :: k) where type At' o t key :: * instance Accessible' EQ (Node _' (key |> a) _'') key where type At' EQ (Node _' (key |> a) _'') key = a instance Accessible l key => Accessible' LT (Node l _' _'') key where type At' LT (Node l _' _'') key = At l key instance Accessible r key => Accessible' GT (Node _' _'' r) key where type At' GT (Node _' _'' r) key = At r key -- | /O(log n)/. Get the value at @key@ in a 'Record'. -- -- A special version of 'atX' with a tighter context and without 'Maybe'. at :: Accessible t key => Record t -> proxy key -> At t key at rc p = fromJust $ atX rc p {-# INLINE at #-} -- | /O(log n)/. Get the value at @key@ in a 'Union'. -- -- A special version of 'projX' with a tighter context. proj :: Accessible t key => Union t -> proxy key -> Maybe (At t key) proj = projX {-# INLINE proj #-} -- | /O(log n)/. Injection to a dependently-typed union. One way to build a 'Union'. -- -- A special version of 'injX' with a tighter context and without 'Maybe'. -- -- >Just (inj p x) == injX p x inj :: Accessible t key => proxy key -> At t key -> Union t inj p x = fromJust $ injX p x {-# INLINE inj #-} -- | Infix synonym for 'at'. (!) :: Accessible t key => Record t -> proxy key -> At t key (!) = at {-# INLINE (!) #-} infixl 9 ! -- | When f is either 'Record' or 'Union', -- -- >AccessibleF f t key == Accessible t key class (Accessible t key, SearchableF f t key (At t key)) => AccessibleF (f :: BST * -> *) (t :: BST *) (key :: k) instance Accessible t key => AccessibleF Record t key instance Accessible t key => AccessibleF Union t key -- | /O(log n)/. 'smap' stands for \"super-map\". -- Change the value of the 'Item' at @key@ in @f t@ by applying the function @At t key -> b@. -- A special version of 'smapX' with a tighter context. smap :: AccessibleF f t key => proxy key -> (At t key -> b) -> f t -> f (Smap t key (At t key) b) smap = smapX {-# INLINE smap #-} -- | /O(log n)/. 'supdate' stands for \"super-update\". -- A special version of 'supdateX' with a tighter context. -- -- >supdate p x == smap p (const x) supdate :: AccessibleF f t key => proxy key -> b -> f t -> f (Smap t key (At t key) b) supdate = supdateX {-# INLINE supdate #-} -- | /O(log n)/. A special version of 'smap' that does not change the value type. -- A special version of 'adjustX' with a tighter context. adjust :: AccessibleF f t key => proxy key -> (At t key -> At t key) -> f t -> f t adjust = adjustX {-# INLINE adjust #-} -- | /O(log n)/. A special version of 'supdate' that does not change the value type. -- A special version of 'updateX' with a tighter context. -- -- >update p x == adjust p (const x) update :: AccessibleF f t key => proxy key -> At t key -> f t -> f t update p x = adjust p (const x) {-# INLINE update #-} -- | Infix operator that works almost like 'smap'. -- -- > (p |> f) <$*> c = smap p f c (<$*>) :: AccessibleF f t key => key |> (At t key -> b) -> f t -> f (Smap t key (At t key) b) (<$*>) (Item f :: key |> (At t key -> b)) (c :: f t) = smap (Proxy :: Proxy key) f c {-# INLINE (<$*>) #-} infixl 4 <$*> -- >Contains t key k == (Accessible t key, a ~ At t key) class (Accessible t key, a ~ At t key) => Contains (t :: BST *) (key :: k) (a :: *) | t key -> a instance (Accessible t key, a ~ At t key) => Contains t key a -- >ContainedBy key a t == (Accessible t key, a ~ At t key) class Contains t key a => ContainedBy (key :: k) (a :: *) (t :: BST *) | t key -> a instance Contains t key a => ContainedBy key a t {- Searchable -} -- | @t@ /may/ have an 'Item' with a key type @key@ and a value type @a@. -- -- When @'Accessible' t key@, @a@ should be @'At' t key@, -- but when not, @a@ can be any type. class Smap t key a a ~ t => Searchable (t :: BST *) (key :: k) (a :: *) where -- | /O(log n)/. 'at' with a looser context and 'Maybe'. atX :: Record t -> proxy key -> Maybe a -- | /O(log n)/. 'proj' with a looser context. projX :: Union t -> proxy key -> Maybe a -- | /O(log n)/. 'inj' with a looser context and 'Maybe'. injX :: proxy key -> a -> Maybe (Union t) -- | /O(log n)/. Change the value type of an 'Item' at 'key' from 'a' to 'b'. type Smap t key a (b :: *) :: BST * smapXR :: proxy key -> (a -> b) -> Record t -> Record (Smap t key a b) smapXU :: proxy key -> (a -> b) -> Union t -> Union (Smap t key a b) -- | Infix synonym for 'atX'. (!?) :: Searchable t key a => Record t -> proxy key -> Maybe a (!?) = atX {-# INLINE (!?) #-} instance Searchable Leaf _' _'' where atX _ _ = Nothing {-# INLINE atX #-} projX _ _ = Nothing {-# INLINE projX #-} injX _ _ = Nothing {-# INLINE injX #-} type Smap Leaf key a b = Leaf smapXR _ _ _ = None {-# INLINE smapXR #-} smapXU _ _ u = u {-# INLINE smapXU #-} instance Searchable' (Compare key key') (Node l (key' |> c) r) key a => Searchable (Node l (key' |> c) r) key a where atX rc _ = atX' (Proxy :: Proxy '(Compare key key', key)) rc {-# INLINE atX #-} projX u _ = projX' (Proxy :: Proxy '(Compare key key', key)) u {-# INLINE projX #-} injX _ x = injX' (Proxy :: Proxy '(Compare key key', key)) x {-# INLINE injX #-} type Smap (Node l (key' |> c) r) key a b = Smap' (Compare key key') (Node l (key' |> c) r) key a b smapXR _ = smapXR' (Proxy :: Proxy '(Compare key key', key)) {-# INLINE smapXR #-} smapXU _ = smapXU' (Proxy :: Proxy '(Compare key key', key)) {-# INLINE smapXU #-} class Smap' o t key a a ~ t => Searchable' (o :: Ordering) (t :: BST *) (key :: k) (a :: *) where atX' :: Proxy '(o, key) -> Record t -> Maybe a projX' :: Proxy '(o, key) -> Union t -> Maybe a injX' :: Proxy '(o, key) -> a -> Maybe (Union t) type Smap' o t key a (b :: *) :: BST * smapXR' :: Proxy '(o, key) -> (a -> b) -> Record t -> Record (Smap' o t key a b) smapXU' :: Proxy '(o, key) -> (a -> b) -> Union t -> Union (Smap' o t key a b) instance Searchable' EQ (Node _' (key |> a) _'') key a where atX' _ (Triple _ (Item x) _) = Just x {-# INLINE atX' #-} projX' _ (Top (Item x)) = Just x projX' _ _ = Nothing {-# INLINE projX' #-} injX' _ x = Just $ Top $ (Item :: With key) x {-# INLINE injX' #-} type Smap' EQ (Node l (key |> a) r) key a b = Node l (key |> b) r smapXR' _ f (Triple l (Item x) r) = Triple l (Item $ f x) r {-# INLINE smapXR' #-} smapXU' _ f (Top (Item x)) = Top $ Item $ f x smapXU' _ _ (GoL l) = GoL l smapXU' _ _ (GoR r) = GoR r {-# INLINE smapXU' #-} instance Searchable l key a => Searchable' LT (Node l _' _'') key a where atX' _ (Triple l _ _) = atX l (Proxy :: Proxy key) {-# INLINABLE atX' #-} projX' _ (GoL u) = projX u (Proxy :: Proxy key) projX' _ _ = Nothing {-# INLINABLE projX' #-} injX' _ x = fmap GoL $ injX (Proxy :: Proxy key) x {-# INLINABLE injX' #-} type Smap' LT (Node l c r) key a b = Node (Smap l key a b) c r smapXR' _ f (Triple l x r) = Triple (smapXR (Proxy :: Proxy key) f l) x r {-# INLINABLE smapXR' #-} smapXU' _ f (GoL l) = GoL $ smapXU (Proxy :: Proxy key) f l smapXU' _ _ (GoR r) = GoR r smapXU' _ _ (Top x) = Top x {-# INLINABLE smapXU' #-} instance Searchable r key a => Searchable' GT (Node _' _'' r) key a where atX' _ (Triple _ _ r) = atX r (Proxy :: Proxy key) {-# INLINABLE atX' #-} projX' _ (GoR u) = projX u (Proxy :: Proxy key) projX' _ _ = Nothing {-# INLINABLE projX' #-} injX' _ x = fmap GoR $ injX (Proxy :: Proxy key) x {-# INLINABLE injX' #-} type Smap' GT (Node l c r) key a b = Node l c (Smap r key a b) smapXR' _ f (Triple l x r) = Triple l x (smapXR (Proxy :: Proxy key) f r) {-# INLINABLE smapXR' #-} smapXU' _ f (GoR r) = GoR $ smapXU (Proxy :: Proxy key) f r smapXU' _ _ (GoL l) = GoL l smapXU' _ _ (Top x) = Top x {-# INLINABLE smapXU' #-} -- | When f is either 'Record' or 'Union', -- -- >SearchableF f t key == Searchable t key class Searchable t key a => SearchableF (f :: BST * -> *) (t :: BST *) (key :: k) (a :: *) where -- | /O(log n)/. 'smap' with a looser context. smapX :: proxy key -> (a -> b) -> f t -> f (Smap t key a b) -- | /O(log n)/. 'supdate' with a looser context. supdateX :: SearchableF f t key (At t key) => proxy key -> b -> f t -> f (Smap t key (At t key) b) supdateX (p :: proxy key) (x :: b) (c :: f t) = smapX p (const x :: At t key -> b) c {-# INLINE supdateX #-} -- | /O(log n)/. 'adjust' with a looser context. adjustX :: SearchableF f t key a => proxy key -> (a -> a) -> f t -> f t adjustX = smapX {-# INLINE adjustX #-} -- | /O(log n)/. 'update' with a looser context. updateX :: SearchableF f t key a => proxy key -> a -> f t -> f t updateX p x = adjustX p (const x) {-# INLINE updateX #-} -- | Infix operator that works almost like 'smapX'. -- -- > (p |> f) <$*?> c = smapX p f cz (<$*?>) :: SearchableF f t key a => key |> (a -> b) -> f t -> f (Smap t key a b) (<$*?>) (Item f :: key |> (a -> b)) = smapX (Proxy :: Proxy key) f {-# INLINE (<$*?>) #-} infixl 4 <$*?> instance Searchable t key a => SearchableF Record t key a where smapX = smapXR {-# INLINE smapX #-} instance Searchable t key a => SearchableF Union t key a where smapX = smapXU {-# INLINE smapX #-} {- Unioncasable -} class UnioncasableX t t' res => Unioncasable (t :: BST *) (t' :: BST *) (res :: *) instance Unioncasable Leaf t' res instance (Contains t' key (a -> res), Unioncasable l t' res, Unioncasable r t' res) => Unioncasable (Node l (Item key a) r) t' res -- | /O(log n + log n')/. Pattern matching on @'Union' t@, -- where @'Record' t'@ contains functions that return @res@ for /all/ items in @t@. -- -- A special version of 'unioncaseX' with a tighter context. unioncase :: Unioncasable t t' res => Union t -> Record t' -> res unioncase = unioncaseX class UnioncasableX (t :: BST *) (t' :: BST *) (res :: *) where -- | /O(log n + log n')/. Pattern matching on @'Union' t@, -- where @'Record' t'@ contains functions that return @res@ for /some/ items in @t@. -- -- 'unioncase' with a looser context. unioncaseX :: Union t -> Record t' -> res instance UnioncasableX Leaf t' res where unioncaseX !_ _ = undefined {-# INLINE unioncaseX #-} instance (Searchable t' key (a -> res), UnioncasableX l t' res, UnioncasableX r t' res) => UnioncasableX (Node l (Item key a) r) t' res where unioncaseX (Top (Item x)) rc = case rc !? (Proxy :: Proxy key) of Just f -> f x Nothing -> error "Type.BST.BST.unioncaseX: corresponding function not found" unioncaseX (GoL l) rc = unioncaseX l rc unioncaseX (GoR r) rc = unioncaseX r rc {-# INLINABLE unioncaseX #-} {- Inclusion -} -- | @t@ includes @t'@; in other words, @t@ contains all items in @t'@. class Includes (t :: BST *) (t' :: BST *) instance Includes t Leaf instance (Contains t key a, Includes t l, Includes t r) => Includes t (Node l (key |> a) r) -- | @t@ is included by @t'@; in other words, @t'@ contains all items in @t@. -- -- >IncludedBy t t' == Includes t' t class Includes t' t => IncludedBy (t :: BST *) (t' :: BST *) instance Includes t' t => IncludedBy t t' -- | /O(n log n')/. A special version of 'metamorphose' with a tighter context guaranteeing the safety of the conversion. shrink :: (Metamorphosable Record t t', Includes t t') => Record t -> Record t' shrink = metamorphose -- | /O(log n + log n')/. A special version of 'metamorphose' with a tighter context guaranteeing the safety of the conversion. expand :: (Metamorphosable Union t t', IncludedBy t t') => Union t -> Union t' expand = metamorphose {- Balancing -} class (Foldable t, Fromlistable (Tolist t)) => Balanceable (t :: BST *) where -- | /O(n log n)/ (no matter how unbalanced @t@ is). Balance an unbalanced 'BST'. -- -- Doing a lot of insertions and deletions may cause an unbalanced BST. -- -- If @t@ and @t'@ have the same items (just in different orders), @Balance t == Balance t'@, -- -- Moreover, if @t@ and @as@ have the same items (just in different orders), @Balance t = Fromlist as@. type Balance t :: BST * -- | /O(n log n)/ (no matter how unbalanced @t@ is). Balance an unbalanced 'Record'. -- -- If @rc@ and @rc'@ have the same items (just in different orders), @balance rc == balance rc'@, -- -- Moreover, if @rc@ and @l@ have the same items (just in different orders), @balance rc = fromlist l@. balance :: Record t -> Record (Balance t) instance (Foldable t, Fromlistable (Tolist t)) => Balanceable t where type Balance t = Fromlist (Tolist t) balance = fromlist . tolist {-# INLINE balance #-} {- Metamorphosis -} class Metamorphosable (f :: BST * -> *) (t :: BST *) (t' :: BST *) where -- | /O(n log n')/ when @f@ is 'Record' and /O(log n + log n')/ when @f@ is 'Union'. -- -- Possibly unsafe conversion from @f t@ to @f t'@. metamorphose :: f t -> f t' instance MetamorphosableR t t' => Metamorphosable Record t t' where metamorphose = metamorphoseR {-# INLINE metamorphose #-} instance MetamorphosableU t t' => Metamorphosable Union t t' where metamorphose = metamorphoseU {-# INLINE metamorphose #-} class MetamorphosableR t t' where metamorphoseR :: Record t -> Record t' instance (Foldable t', MetamorphosableR' t t') => MetamorphosableR t t' where metamorphoseR = metamorphoseR' virtual {-# INLINE metamorphoseR #-} class MetamorphosableR' (t :: BST *) (t' :: BST *) where metamorphoseR' :: Record t' -> Record t -> Record t' instance MetamorphosableR' Leaf t where metamorphoseR' rc _ = rc {-# INLINE metamorphoseR' #-} instance (Searchable t key a, MetamorphosableR' l t, MetamorphosableR' r t) => MetamorphosableR' (Node l (key |> a) r) t where metamorphoseR' rc (Triple l (Item x) r) = metamorphoseR' ((updateX (Proxy :: Proxy key) x) $ metamorphoseR' rc r) l {-# INLINABLE metamorphoseR' #-} class MetamorphosableU (t :: BST *) (t' :: BST *) where metamorphoseU :: Union t -> Union t' instance MetamorphosableU Leaf t where metamorphoseU _ = error "Type.BST.BST.metamorphoseU: bad luck!" {-# INLINE metamorphoseU #-} instance (Searchable t key a, MetamorphosableU l t, MetamorphosableU r t) => MetamorphosableU (Node l (key |> a) r) t where metamorphoseU (Top (Item x)) = case injX (Proxy :: Proxy key) x of Nothing -> error "Type.BST.BST.metamorphoseU: bad luck!" Just u -> u metamorphoseU (GoL l) = metamorphoseU l metamorphoseU (GoR r) = metamorphoseU r {-# INLINABLE metamorphoseU #-} {- Merging -} class Mergeable (t :: BST *) (t' :: BST *) where -- | /O(n log n + n' log n')/. Merge two 'BST's. -- If @t@ and @t'@ has an @Item@ with the same key, -- only the one in @t@ will be added to the result. type Merge t t' :: BST * -- | /O(n log n + n' log n')/. Merge two 'Record's. merge :: Record t -> Record t' -> Record (Merge t t') -- | /O(n log n + n' log n')/. Merge two 'BST's in a more equal manner. -- If @t@ has @'Item' key a@ and @t'@ has @'Item' key b@, -- @'Item' key (a, b)@ will be added to the result. type MergeE t t' :: BST * -- | /O(n log n + n' log n')/. Merge two 'Record's in a more equal manner. mergeE :: Record t -> Record t' -> Record (MergeE t t') instance (Foldable t, Foldable t', MergeableL (Tolist t) (Tolist t'), Fromlistable (MergeL (Tolist t) (Tolist t')), Fromlistable (MergeEL (Tolist t) (Tolist t'))) => Mergeable t t' where type Merge t t' = Fromlist (MergeL (Tolist t) (Tolist t')) merge rc rc' = fromlist $ mergeL (tolist rc) (tolist rc') {-# INLINE merge #-} type MergeE t t' = Fromlist (MergeEL (Tolist t) (Tolist t')) mergeE rc rc' = fromlist $ mergeEL (tolist rc) (tolist rc') {-# INLINE mergeE #-} {- Insertion -} class Insertable (t :: BST *) (key :: k) where -- | /O(log n)/. Insert @'Item' key a@ into the 'BST'. -- If @t@ already has an 'Item' with @key@, the 'Item' will be overwritten. -- The result may be unbalanced. type Insert t key (a :: *) :: BST * -- | /O(log n)/. Insert @a@ at @key@ into the 'Record'. -- The result may be unbalanced. insert :: proxy key -> a -> Record t -> Record (Insert t key a) instance Insertable Leaf key where type Insert Leaf key a = Node Leaf (key |> a) Leaf insert _ x _ = Triple None ((Item :: With key) x) None {-# INLINE insert #-} instance Insertable' (Compare key key') (Node l (key' |> b) r) key => Insertable (Node l (key' |> b) r) key where type Insert (Node l (key' |> b) r) key a = Insert' (Compare key key') (Node l (key' |> b) r) key a insert _ = insert' (Proxy :: Proxy '(Compare key key', key)) {-# INLINE insert #-} class Insertable' (o :: Ordering) (t :: BST *) (key :: k) where type Insert' o t key (a :: *) :: BST * insert' :: Proxy '(o, key) -> a -> Record t -> Record (Insert' o t key a) instance Insertable' EQ (Node l (key |> _') r) key where type Insert' EQ (Node l (key |> _') r) key a = Node l (key |> a) r insert' _ x (Triple l _ r) = Triple l ((Item :: With key) x) r {-# INLINE insert' #-} instance Insertable l key => Insertable' LT (Node l b r) key where type Insert' LT (Node l b r) key a = Node (Insert l key a) b r insert' _ x (Triple l y r) = Triple (insert (Proxy :: Proxy key) x l) y r {-# INLINABLE insert' #-} instance Insertable r key => Insertable' GT (Node l b r) key where type Insert' GT (Node l b r) key a = Node l b (Insert r key a) insert' _ x (Triple l y r) = Triple l y (insert (Proxy :: Proxy key) x r) {-# INLINABLE insert' #-} {- Deletion -} class Deletable (t :: BST *) (key :: k) where -- | /O(log n)/. Delete an 'Item' at @key@ from the 'BST'. -- If the BST does not have any item at @key@, the original BST will be returned. -- The result may be unbalanced. type Delete t key :: BST * -- | /O(log n)/. Delete an 'Item' at @key@ from the 'Record'. delete :: proxy key -> Record t -> Record (Delete t key) instance Deletable Leaf key where type Delete Leaf key = Leaf delete _ rc = rc {-# INLINE delete #-} instance Deletable' (Compare key key') (Node l (key' |> a) r) key => Deletable (Node l (key' |> a) r) key where type Delete (Node l (key' |> a) r) key = Delete' (Compare key key') (Node l (key' |> a) r) key delete _ = delete' (Proxy :: Proxy '(Compare key key', key)) {-# INLINE delete #-} class Deletable' (o :: Ordering) (t :: BST *) (key :: k) where type Delete' o t key :: BST * delete' :: Proxy '(o, key) -> Record t -> Record (Delete' o t key) instance Deletable' EQ (Node Leaf (key |> _') r) key where type Delete' EQ (Node Leaf (key |> _') r) key = r delete' _ (Triple _ _ r) = r {-# INLINE delete' #-} instance Deletable' EQ (Node (Node l a r) (key |> _') Leaf) key where type Delete' EQ (Node (Node l a r) (key |> _') Leaf) key = Node l a r delete' _ (Triple l _ _) = l {-# INLINE delete' #-} instance Maxable (Node l a r) => Deletable' EQ (Node (Node l a r) (key |> _') (Node l' b r')) key where type Delete' EQ (Node (Node l a r) (key |> _') (Node l' b r')) key = Node (Deletemax (Node l a r)) (Findmax (Node l a r)) (Node l' b r') delete' _ (Triple l _ r) = let (y, rc) = splitmax l in Triple rc y r {-# INLINE delete' #-} instance Deletable l key => Deletable' LT (Node l a r) key where type Delete' LT (Node l a r) key = Node (Delete l key) a r delete' _ (Triple l x r) = Triple (delete (Proxy :: Proxy key) l) x r {-# INLINE delete' #-} instance Deletable r key => Deletable' GT (Node l a r) key where type Delete' GT (Node l a r) key = Node l a (Delete r key) delete' _ (Triple l x r) = Triple l x (delete (Proxy :: Proxy key) r) {-# INLINE delete' #-} {- Min and Max -} class Minnable (t :: BST *) where -- | /O(log n)/. Delete the 'Item' at the minimum key from the 'BST'. -- The result may be unbalanced. type Deletemin t :: BST * -- | /O(log n)/. Get the value type of the 'Item' at the minimum key in the 'BST'. type Findmin t :: * -- | /O(log n)/. Split the 'Record' into (the value of) the 'Item' at the minimum key and the rest. splitmin :: Record t -> (Findmin t, Record (Deletemin t)) -- | /O(log n)/. Get the value of the 'Item' at the minimum key in the 'Record'. -- -- >findmin = fst . splitmin findmin :: Minnable t => Record t -> Findmin t findmin = fst . splitmin {-# INLINE findmin #-} -- | /O(log n)/. Delete the 'Item' at the minimum key from the 'Record'. -- -- >deletemin = snd . splitmin deletemin :: Minnable t => Record t ->Record (Deletemin t) deletemin = snd . splitmin {-# INLINE deletemin #-} instance Minnable (Node Leaf a r) where type Deletemin (Node Leaf a r) = r type Findmin (Node Leaf a r) = a splitmin (Triple _ x r) = (x, r) {-# INLINE splitmin #-} instance Minnable (Node l' b r') => Minnable (Node (Node l' b r') a r) where type Deletemin (Node (Node l' b r') a r) = Node (Deletemin (Node l' b r')) a r type Findmin (Node (Node l' b r') a r) = Findmin (Node l' b r') splitmin (Triple l x r) = let (y, rc) = splitmin l in (y, Triple rc x r) {-# INLINABLE splitmin #-} class Maxable (t :: BST *) where -- | /O(log n)/. Delete the 'Item' at the maximum key from the 'BST'. -- The result may be unbalanced. type Deletemax t :: BST * type Findmax t :: * -- | /O(log n)/. Get the value type of the 'Item' at the maximum key in the 'BST'. splitmax :: Record t -> (Findmax t, Record (Deletemax t)) -- | /O(log n)/. Get the value of the 'Item' at the maximum key in the 'Record'. -- -- >findmin = fst . splitmin findmax :: Maxable t => Record t -> Findmax t findmax = fst . splitmax {-# INLINE findmax #-} -- | /O(log n)/. Delete the 'Item' at the maximum key from the 'Record'. -- -- >deletemin = snd . splitmin deletemax :: Maxable t => Record t ->Record (Deletemax t) deletemax = snd . splitmax {-# INLINE deletemax #-} instance Maxable (Node l a Leaf) where type Deletemax (Node l a Leaf) = l type Findmax (Node l a Leaf) = a splitmax (Triple l x _) = (x, l) {-# INLINE splitmax #-} instance Maxable (Node l' b r') => Maxable (Node l a (Node l' b r')) where type Deletemax (Node l a (Node l' b r')) = Node l a (Deletemax (Node l' b r')) type Findmax (Node l a (Node l' b r')) = Findmax (Node l' b r') splitmax (Triple l x r) = let (y, rc) = splitmax r in (y, Triple l x rc) {-# INLINABLE splitmax #-}
Kinokkory/type-level-bst
src/Type/BST/BST.hs
bsd-3-clause
33,231
0
15
8,085
11,504
6,047
5,457
-1
-1
{-# LANGUAGE TypeSynonymInstances, PatternGuards #-} {-| This module is for working with HTML/XML. It deals with both well-formed XML and malformed HTML from the web. It features: * A lazy parser, based on the HTML 5 specification - see 'parseTags'. * A renderer that can write out HTML/XML - see 'renderTags'. * Utilities for extracting information from a document - see '~==', 'sections' and 'partitions'. The standard practice is to parse a 'String' to @[@'Tag' 'String'@]@ using 'parseTags', then operate upon it to extract the necessary information. -} module Text.HTML.TagSoup( -- * Data structures and parsing Tag(..), Row, Column, Attribute, module Text.HTML.TagSoup.Parser, module Text.HTML.TagSoup.Render, canonicalizeTags, -- * Tag identification isTagOpen, isTagClose, isTagText, isTagWarning, isTagPosition, isTagOpenName, isTagCloseName, -- * Extraction fromTagText, fromAttrib, maybeTagText, maybeTagWarning, innerText, -- * Utility sections, partitions, -- * Combinators TagRep, (~==),(~/=) ) where import Text.HTML.TagSoup.Type import Text.HTML.TagSoup.Parser import Text.HTML.TagSoup.Render import Data.Char import Data.List import Text.StringLike -- | Turns all tag names and attributes to lower case and -- converts DOCTYPE to upper case. canonicalizeTags :: StringLike str => [Tag str] -> [Tag str] canonicalizeTags = map f where f (TagOpen tag attrs) | Just ('!',name) <- uncons tag = TagOpen ('!' `cons` ucase name) attrs f (TagOpen name attrs) = TagOpen (lcase name) [(lcase k, v) | (k,v) <- attrs] f (TagClose name) = TagClose (lcase name) f a = a ucase = fromString . map toUpper . toString lcase = fromString . map toLower . toString -- | Define a class to allow String's or Tag str's to be used as matches class TagRep a where toTagRep :: StringLike str => a -> Tag str instance StringLike str => TagRep (Tag str) where toTagRep = fmap castString instance TagRep String where toTagRep x = case parseTags x of [a] -> toTagRep a _ -> error $ "When using a TagRep it must be exactly one tag, you gave: " ++ x -- | Performs an inexact match, the first item should be the thing to match. -- If the second item is a blank string, that is considered to match anything. -- For example: -- -- > (TagText "test" ~== TagText "" ) == True -- > (TagText "test" ~== TagText "test") == True -- > (TagText "test" ~== TagText "soup") == False -- -- For 'TagOpen' missing attributes on the right are allowed. (~==) :: (StringLike str, TagRep t) => Tag str -> t -> Bool (~==) a b = f a (toTagRep b) where f (TagText y) (TagText x) = strNull x || x == y f (TagClose y) (TagClose x) = strNull x || x == y f (TagOpen y ys) (TagOpen x xs) = (strNull x || x == y) && all g xs where g (name,val) | strNull name = val `elem` map snd ys | strNull val = name `elem` map fst ys g nameval = nameval `elem` ys f _ _ = False -- | Negation of '~==' (~/=) :: (StringLike str, TagRep t) => Tag str -> t -> Bool (~/=) a b = not (a ~== b) -- | This function takes a list, and returns all suffixes whose -- first item matches the predicate. sections :: (a -> Bool) -> [a] -> [[a]] sections p = filter (p . head) . init . tails -- | This function is similar to 'sections', but splits the list -- so no element appears in any two partitions. partitions :: (a -> Bool) -> [a] -> [[a]] partitions p = let notp = not . p in groupBy (const notp) . dropWhile notp
nfjinjing/yuuko
src/Text/HTML/TagSoup.hs
bsd-3-clause
3,702
0
12
949
908
497
411
51
5
{-# LANGUAGE TemplateHaskell, EmptyDataDecls, FlexibleContexts, OverlappingInstances #-} {-# LANGUAGE FlexibleInstances ,TypeSynonymInstances, TypeFamilies, TypeOperators #-} module Main where import Generics.Instant import Language.Haskell.TH import Generics.Instant.Derive data Expr = N Int | V String | P Expr Expr deriving (Show, Eq, Ord) derive ''Expr deriveWith ''(,,) [Just "Triple_Con"] deriveWith ''() [Just "Unit_Unit"] class Count a where count :: a -> Int count _ = 1 instance Count Int instance Count Char instance Count Bool instance Count String instance Count U instance Count (C con U) instance Count a => Count (Var a) where count (Var a) = count a instance (Count a, Count b) => Count (a :*: b) where count (a :*: b) = count a + count b instance (Count a) => Count (Rec a) where count (Rec a) = count a instance Count a => Count (C con a) where count (C a) = 1 + count a instance (Count a, Count b) => Count (a :+: b) where count (L a) = count a count (R b) = count b dft_count :: (Representable a, Count (Rep a)) => a -> Int dft_count = count . from instance Count () where count = dft_count instance Count a => Count (Maybe a) where count = dft_count instance Count a => Count [a] where count = dft_count instance (Count a, Count b) => Count (a, b) where count = dft_count instance (Count a, Count b, Count c) => Count (a, b, c) where count = dft_count instance Count Expr where count = dft_count
konn/derive-IG
example/count.hs
bsd-3-clause
1,493
0
8
326
615
315
300
41
1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TemplateHaskell #-} -------------------------------------------------------------------------------- -- | -- Module: HipChat.Types -- Description: Common types used in both the HipChat REST API and Add-on API. -- -------------------------------------------------------------------------------- module HipChat.Types ( Room(..) , RoomId , URL , (/) , parseURL , toBaseUrl , Vendor(..) , name , url , Key(..) , OAuth2Provider(..) , authorizationUrl , tokenUrl ) where import HipChat.Types.Key import HipChat.Types.URL import HipChat.Util (ToFromJSON) import Control.Lens.TH import Data.Text (Text) import GHC.Generics import Prelude hiding ((/)) import Web.HttpApiData -------------------------------------------------------------------------------- -- Room and RoomId -------------------------------------------------------------------------------- -- | The id or url-encoded name of the room -- Valid length range: 1 - 100. data Room = RoomNum RoomId | RoomName Text deriving (Eq, Show) instance ToHttpApiData Room where toUrlPiece (RoomNum i) = toUrlPiece i toUrlPiece (RoomName t) = t type RoomId = Int -------------------------------------------------------------------------------- -- Vendor -------------------------------------------------------------------------------- data Vendor = Vendor { vendorUrl :: URL -- ^ The vendor's home page URL , vendorName :: Text -- ^ The vendor display name } deriving (Show, Eq, Generic) instance ToFromJSON Vendor makeLensesWith camelCaseFields ''Vendor -------------------------------------------------------------------------------- -- OAuth2Provider -------------------------------------------------------------------------------- data OAuth2Provider = OAuth2Provider { oAuth2ProviderAuthorizationUrl :: Maybe URL , oAuth2ProviderTokenUrl :: Maybe URL } deriving (Show, Eq, Generic) instance ToFromJSON OAuth2Provider makeLensesWith camelCaseFields ''OAuth2Provider
mjhopkins/hipchat
src/HipChat/Types.hs
bsd-3-clause
2,267
0
9
412
330
202
128
45
0
{-# LANGUAGE OverloadedStrings #-} module Trombone.Dispatch.NodeJs ( dispatchNodeJs ) where import Control.Applicative import Control.Monad import Control.Monad.IO.Class ( liftIO ) import Data.Aeson import Data.ByteString ( ByteString ) import Data.Text ( Text, unpack ) import System.Process import Trombone.Dispatch.Core import Trombone.Response import qualified Data.ByteString.Lazy.Char8 as L8 data NodeResponse = NodeResponse { nodeStatus :: Int , nodeBody :: Value } instance FromJSON NodeResponse where parseJSON (Object v) = NodeResponse <$> v .: "statusCode" <*> v .: "body" parseJSON _ = mzero dispatchNodeJs :: Text -> ByteString -> Dispatch IO RouteResponse dispatchNodeJs path body = do r <- liftIO $ readProcess "node" [unpack path] $ transl body return $ case decode $ L8.pack r of Just nr -> (RouteResponse [] <$> nodeStatus <*> nodeBody) nr Nothing -> errorResponse ErrorServerGeneric "Invalid response from node.js application script." where transl :: ByteString -> String transl = L8.unpack . L8.fromStrict
johanneshilden/trombone
Trombone/Dispatch/NodeJs.hs
bsd-3-clause
1,253
0
16
368
296
161
135
30
2
{-# LANGUAGE DeriveDataTypeable #-} {-# OPTIONS_HADDOCK show-extensions #-} -- | -- Module : Language.Logo.Exception -- Copyright : (c) 2013-2016, the HLogo team -- License : BSD3 -- Maintainer : Nikolaos Bezirgiannis <[email protected]> -- Stability : experimental -- -- The exception handling of the framework. Uses the built-in exception mechanism of Haskell, -- so the EDSL is defined as a very shallow embedding. Alternative way with deeper embedding is to use the ErrorT transformer. module Language.Logo.Exception (throw, catch, catchIO, evaluate, -- * The type class Exception, assert, -- * Built-in exceptions imported from Haskell base SomeException, IOException , ArithException (..) , AssertionFailed (..), AsyncException (..), NestedAtomically (..) , BlockedIndefinitelyOnSTM (..) , Deadlock (..), ErrorCall (..), -- * Exceptions specific to HLogo TypeException (..), StopException (..), DevException (..) ) where import Language.Logo.Base import Control.Exception hiding (catch) import qualified Control.Exception as E (catch) import Control.Concurrent.STM import Data.Typeable import Control.Monad.Trans.Reader (liftCatch) {-# INLINE catch #-} -- | Catches an Exception in STM monad catch :: Exception e => C _s _s' STM a -> (e -> C _s _s' STM a) -> C _s _s' STM a catch = liftCatch catchSTM {-# INLINE catchIO #-} -- | Catches an Exception in IO monad catchIO :: Exception e => C _s _s' IO a -> (e -> C _s _s' IO a) -> C _s _s' IO a catchIO = liftCatch E.catch -- | Thrown when a primitive procedure expected a different *this* context (i.e. the callee inside the context monad transformer). -- -- Used as ContextException ExpectedCalleeAsString GotInsteadAgentRef -- | A type error thrown when a procedure expected a different type of agent argument. -- Normally we use the static typing of Haskell, except for 'AgentRef's, which are checked dynamically on run-time -- -- Used as TypeException ExpectedTypeAsString GotInsteadAgentRef -- | A type error thrown when a procedure expected a different type of agent argument. -- Normally we use the static typing of Haskell, except for 'AgentRef's, which are checked dynamically on run-time -- -- Used as TypeException ExpectedTypeAsString GotInsteadAgentRef data TypeException = TypeException String deriving (Eq, Typeable) -- | The error thrown by the 'Language.Logo.Prim.stop' primitive. It is a trick and should be catched in an upper caller primitive. data StopException = StopException deriving (Eq, Typeable) data DevException = DevException deriving (Eq, Typeable) instance Exception StopException instance Exception DevException instance Exception TypeException instance Show TypeException where show (TypeException expected) = "TypeException " ++ expected instance Show StopException where show StopException = "Stop called and has not be catched. This should not normally happen" instance Show DevException where show DevException = "error: this should not happen, contact the developers"
bezirg/hlogo
src/Language/Logo/Exception.hs
bsd-3-clause
3,145
0
10
620
447
267
180
37
1
module Lib ( mainWindowTitle ) where mainWindowTitle :: String mainWindowTitle = "Horbits"
chwthewke/horbits2
src/Lib.hs
bsd-3-clause
100
0
4
21
19
12
7
4
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} module Language.Fixpoint.Types.PrettyPrint where import Debug.Trace (trace) import Text.Parsec import Text.PrettyPrint.HughesPJ import qualified Text.PrettyPrint.Boxes as B import qualified Data.HashMap.Strict as M import qualified Data.HashSet as S import Language.Fixpoint.Misc import Data.Hashable import qualified Data.Text as T traceFix :: (Fixpoint a) => String -> a -> a traceFix s x = trace ("\nTrace: [" ++ s ++ "] : " ++ showFix x) x ------------------------------------------------------------------ class Fixpoint a where toFix :: a -> Doc simplify :: a -> a simplify = id showFix :: (Fixpoint a) => a -> String showFix = render . toFix instance (Eq a, Hashable a, Fixpoint a) => Fixpoint (S.HashSet a) where toFix xs = brackets $ sep $ punctuate (text ";") (toFix <$> S.toList xs) simplify = S.fromList . map simplify . S.toList instance Fixpoint () where toFix _ = text "()" instance Fixpoint a => Fixpoint (Maybe a) where toFix = maybe (text "Nothing") ((text "Just" <+>) . toFix) simplify = fmap simplify instance Fixpoint a => Fixpoint [a] where toFix xs = brackets $ sep $ punctuate (text ";") (fmap toFix xs) simplify = map simplify instance (Fixpoint a, Fixpoint b) => Fixpoint (a,b) where toFix (x,y) = toFix x <+> text ":" <+> toFix y simplify (x,y) = (simplify x, simplify y) instance (Fixpoint a, Fixpoint b, Fixpoint c) => Fixpoint (a,b,c) where toFix (x,y,z) = toFix x <+> text ":" <+> toFix y <+> text ":" <+> toFix z simplify (x,y,z) = (simplify x, simplify y,simplify z) instance Fixpoint Bool where toFix True = text "True" toFix False = text "False" simplify z = z instance Fixpoint Int where toFix = tshow instance Fixpoint Integer where toFix = integer instance Fixpoint Double where toFix = double ------------------------------------------------------------------ data Tidy = Lossy | Full deriving (Eq, Ord) class PPrint a where pprint :: a -> Doc pprint = pprintPrec 0 -- | Pretty-print something with a specific precedence. pprintPrec :: Int -> a -> Doc pprintPrec _ = pprint pprintTidy :: Tidy -> a -> Doc pprintTidy _ = pprint showpp :: (PPrint a) => a -> String showpp = render . pprint tracepp :: (PPrint a) => String -> a -> a tracepp s x = trace ("\nTrace: [" ++ s ++ "] : " ++ showpp x) x instance PPrint Doc where pprint = id instance PPrint a => PPrint (Maybe a) where pprint = maybe (text "Nothing") ((text "Just" <+>) . pprint) instance PPrint a => PPrint [a] where pprint = brackets . intersperse comma . map pprint instance PPrint a => PPrint (S.HashSet a) where pprint = pprint . S.toList instance (PPrint a, PPrint b) => PPrint (M.HashMap a b) where pprint = pprintKVs . M.toList pprintKVs :: (PPrint k, PPrint v) => [(k, v)] -> Doc pprintKVs = vcat . punctuate (text "\n") . map pp1 -- . M.toList where pp1 (x,y) = pprint x <+> text ":=" <+> pprint y instance (PPrint a, PPrint b, PPrint c) => PPrint (a, b, c) where pprint (x, y, z) = parens $ pprint x <> text "," <> pprint y <> text "," <> pprint z instance (PPrint a, PPrint b) => PPrint (a,b) where pprint (x, y) = pprint x <+> text ":" <+> pprint y instance PPrint Bool where pprint = text . show instance PPrint Float where pprint = text . show instance PPrint () where pprint = text . show instance PPrint String where pprint = text instance PPrint Int where pprint = tshow instance PPrint Integer where pprint = integer instance PPrint T.Text where pprint = text . T.unpack newtype DocTable = DocTable [(Doc, Doc)] instance Monoid DocTable where mempty = DocTable [] mappend (DocTable t1) (DocTable t2) = DocTable (t1 ++ t2) class PTable a where ptable :: a -> DocTable instance PPrint DocTable where pprint (DocTable kvs) = boxDoc $ B.hsep 1 B.left [ks', cs', vs'] where (ks, vs) = unzip kvs n = length kvs ks' = B.vcat B.left $ docBox <$> ks vs' = B.vcat B.right $ docBox <$> vs cs' = B.vcat B.left $ replicate n $ B.text ":" boxHSep :: Doc -> Doc -> Doc boxHSep d1 d2 = boxDoc $ B.hcat B.top [docBox d1, docBox d2] boxDoc :: B.Box -> Doc boxDoc = text . B.render docBox :: Doc -> B.Box docBox = B.text . render
gridaphobe/liquid-fixpoint
src/Language/Fixpoint/Types/PrettyPrint.hs
bsd-3-clause
4,468
0
11
1,099
1,735
911
824
109
1
{-# LANGUAGE MultiParamTypeClasses , FunctionalDependencies , FlexibleInstances, EmptyDataDecls , DataKinds , KindSignatures, TypeFamilies #-} module Data.Shapely.Bool where -- Probably keep private for now, as with Data.Shapely.Category -- Again, these borrowed from Oleg's HList work type family And (a :: Bool) (b :: Bool) :: Bool type instance And True b = b type instance And b True = b type instance And False b = False -- N.B. coincident overlap type instance And b False = False -- N.B. coincident overlap type family Or (a :: Bool) (b :: Bool) :: Bool type instance Or False b = b type instance Or b False = b type instance Or True b = True -- N.B. coincident overlap type instance Or b True = True -- N.B. coincident overlap type family Not (a :: Bool) :: Bool type instance Not True = False type instance Not False = True
jberryman/shapely-data
src/Data/Shapely/Bool.hs
bsd-3-clause
846
0
6
161
189
120
69
15
0
{- arch-tag: log4j XMLLayout log handler Copyright (C) 2007-2008 John Goerzen <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -} {- | Module : System.Log.Handler.Log4jXML Copyright : Copyright (C) 2007-2008 John Goerzen License : GNU LGPL, version 2.1 or above Maintainer : [email protected] Stability : experimental Portability: GHC only? log4j[1] XMLLayout log handlers. Written by Bjorn Buckwalter, bjorn.buckwalter\@gmail.com -} module System.Log.Handler.Log4jXML ( -- * Introduction {- | This module provides handlers for hslogger that are compatible with log4j's XMLLayout. In particular log messages created by the handlers can be published directly to the GUI-based log viewer Chainsaw v2[2]. The set of log levels in hslogger is richer than the basic set of log4j levels. Two sets of handlers are provided with hslogger4j, one which produces logs with hslogger's levels and one which \"demotes\" them to the basic log4j levels. If full hslogger levels are used some Java installation (see below) is necessary to make Chainsaw aware of them. Usage of the handlers in hslogger4j is analoguous to usage of the 'System.Log.Handler.Simple.StreamHandler' and 'System.Log.Handler.Simple.FileHandler' in "System.Log.Handler.Simple". The following handlers are provided: -} -- ** Handlers with hslogger levels log4jStreamHandler, log4jFileHandler, -- ** Handlers with log4j levels log4jStreamHandler', log4jFileHandler' -- * Java install process {- | This is only necessary if you want to use the hslogger levels. Add @hslogger4j.jar@ from @contrib\/java@ to your classpath. To use you will also need to have the jars @log4j-1.3alpha-7.jar@ and @log4j-xml-1.3alpha-7.jar@ that are distributed with Chainsaw on your classpath. (On Mac OS X I added all three jars to @~\/Library\/Java\/Extensions@. It seems that it is not sufficient that Chainsaw already includes its jars in the classpath when launching - perhaps the plugin classloader does not inherit Chainsaw's classpath. Adding the jars to @~\/.chainsaw\/plugins@ wouldn't work either.) If for whatever reason you have to rebuild the hslogger4j jar just run @ant@[3] in the @contrib\/java@ directory. The new jar will be created in the @contrib\/java\/dist@ directory. The Java source code is copyright The Apache Software Foundation and licensed under the Apache Licence version 2.0. -} -- * Chainsaw setup {- | If you are only using the basic log4j levels just use Chainsaw's regular facilities to browse logs or listen for log messages (e.g. @XMLSocketReceiver@). If you want to use the hslogger levels the easiest way to set up Chainsaw is to load the plugins in @hslogger4j-plugins.xml@ in @contrib\/java@ when launching Chainsaw. Two receivers will be defined, one that listens for logmessages and one for reading log files. Edit the properties of those receivers as needed (e.g. @port@, @fileURL@) and restart them. You will also want to modify Chainsaw's formatting preferences to display levels as text instead of icons. -} -- * Example usage {- | In the IO monad: > lh2 <- log4jFileHandler "log.xml" DEBUG > updateGlobalLogger rootLoggerName (addHandler lh2) > h <- connectTo "localhost" (PortNumber 4448) > lh <- log4jStreamHandler h NOTICE > updateGlobalLogger rootLoggerName (addHandler lh) -} -- * References {- | (1) <http://logging.apache.org/log4j/> (2) <http://logging.apache.org/chainsaw/> (3) <http://ant.apache.org/> -} ) where import Control.Concurrent (ThreadId, myThreadId) -- myThreadId is GHC only! import Control.Concurrent.MVar import Data.List (isPrefixOf) import System.IO import System.Locale (defaultTimeLocale) import Data.Time import System.Log import System.Log.Handler.Simple (GenericHandler (..)) -- Handler that logs to a handle rendering message priorities according -- to the supplied function. log4jHandler :: (Priority -> String) -> Handle -> Priority -> IO (GenericHandler Handle) log4jHandler showPrio h pri = do lock <- newMVar () let mywritefunc hdl (prio, msg) loggername = withMVar lock (\_ -> do time <- getCurrentTime thread <- myThreadId hPutStrLn hdl (show $ createMessage loggername time prio thread msg) hFlush hdl ) return (GenericHandler { priority = pri, privData = h, writeFunc = mywritefunc, closeFunc = \x -> return () }) where -- Creates an XML element representing a log4j event/message. createMessage :: String -> UTCTime -> Priority -> ThreadId -> String -> XML createMessage logger time prio thread msg = Elem "log4j:event" [ ("logger" , logger ) , ("timestamp", millis time ) , ("level" , showPrio prio) , ("thread" , show thread ) ] (Just $ Elem "log4j:message" [] (Just $ CDATA msg)) where -- This is an ugly hack to get a unix epoch with milliseconds. -- The use of "take 3" causes the milliseconds to always be -- rounded downwards, which I suppose may be the expected -- behaviour for time. millis t = formatTime defaultTimeLocale "%s" t ++ (take 3 $ formatTime defaultTimeLocale "%q" t) -- | Create a stream log handler that uses hslogger priorities. log4jStreamHandler :: Handle -> Priority -> IO (GenericHandler Handle) log4jStreamHandler = log4jHandler show {- | Create a stream log handler that uses log4j levels (priorities). The priorities of messages are shoehorned into log4j levels as follows: @ DEBUG -> DEBUG INFO, NOTICE -> INFO WARNING -> WARN ERROR, CRITICAL, ALERT -> ERROR EMERGENCY -> FATAL @ This is useful when the log will only be consumed by log4j tools and you don't want to go out of your way transforming the log or configuring the tools. -} log4jStreamHandler' :: Handle -> Priority -> IO (GenericHandler Handle) log4jStreamHandler' = log4jHandler show' where show' :: Priority -> String show' NOTICE = "INFO" show' WARNING = "WARN" show' CRITICAL = "ERROR" show' ALERT = "ERROR" show' EMERGENCY = "FATAL" show' p = show p -- Identical for DEBUG, INFO, ERROR. -- | Create a file log handler that uses hslogger priorities. log4jFileHandler :: FilePath -> Priority -> IO (GenericHandler Handle) log4jFileHandler fp pri = do h <- openFile fp AppendMode sh <- log4jStreamHandler h pri return (sh{closeFunc = hClose}) {- | Create a file log handler that uses log4j levels (see 'log4jStreamHandler'' for mappings). -} log4jFileHandler' :: FilePath -> Priority -> IO (GenericHandler Handle) log4jFileHandler' fp pri = do h <- openFile fp AppendMode sh <- log4jStreamHandler' h pri return (sh{closeFunc = hClose}) -- A type for building and showing XML elements. Could use a fancy XML -- library but am reluctant to introduce dependencies. data XML = Elem String [(String, String)] (Maybe XML) | CDATA String instance Show XML where show (CDATA s) = "<![CDATA[" ++ escapeCDATA s ++ "]]>" where escapeCDATA = replace "]]>" "]]&lt;" -- The best we can do, I guess. show (Elem name attrs child) = "<" ++ name ++ showAttrs attrs ++ showChild child where showAttrs [] = "" showAttrs ((k,v):as) = " " ++ k ++ "=\"" ++ escapeAttr v ++ "\"" ++ showAttrs as where escapeAttr = replace "\"" "&quot;" . replace "<" "&lt;" . replace "&" "&amp;" showChild Nothing = "/>" showChild (Just c) = ">" ++ show c ++ "</" ++ name ++ ">" -- Replaces instances of first list by second list in third list. -- Definition blatantly stoled from jethr0's comment at -- http://bluebones.net/2007/01/replace-in-haskell/. Can be swapped -- with definition (or import) from MissingH. replace :: Eq a => [a] -> [a] -> [a] -> [a] replace _ _ [ ] = [] replace from to xs@(a:as) = if isPrefixOf from xs then to ++ drop (length from) xs else a : replace from to as
abuiles/turbinado-blog
tmp/dependencies/hslogger-1.0.6/src/System/Log/Handler/Log4jXML.hs
bsd-3-clause
9,350
0
18
2,474
1,093
580
513
-1
-1
module Database.Persist.Sql.Raw where import Control.Exception (throwIO) import Control.Monad (liftM, when) import Control.Monad.IO.Class (MonadIO, liftIO) import Control.Monad.Logger (logDebugNS, runLoggingT) import Control.Monad.Reader (MonadReader, ReaderT, ask) import Control.Monad.Trans.Resource (MonadResource, release) import Data.Acquire (Acquire, allocateAcquire, mkAcquire, with) import Data.Conduit import Data.IORef (newIORef, readIORef, writeIORef) import Data.Int (Int64) import Data.Text (Text, pack) import qualified Data.Text as T import Database.Persist import Database.Persist.Sql.Class import Database.Persist.Sql.Types import Database.Persist.Sql.Types.Internal import Database.Persist.SqlBackend.Internal.StatementCache rawQuery :: (MonadResource m, MonadReader env m, BackendCompatible SqlBackend env) => Text -> [PersistValue] -> ConduitM () [PersistValue] m () rawQuery sql vals = do srcRes <- liftPersist $ rawQueryRes sql vals (releaseKey, src) <- allocateAcquire srcRes src release releaseKey rawQueryRes :: (MonadIO m1, MonadIO m2, BackendCompatible SqlBackend env) => Text -> [PersistValue] -> ReaderT env m1 (Acquire (ConduitM () [PersistValue] m2 ())) rawQueryRes sql vals = do conn <- projectBackend `liftM` ask let make = do runLoggingT (logDebugNS (pack "SQL") $ T.append sql $ pack $ "; " ++ show vals) (connLogFunc conn) getStmtConn conn sql return $ do stmt <- mkAcquire make stmtReset stmtQuery stmt vals -- | Execute a raw SQL statement rawExecute :: (MonadIO m, BackendCompatible SqlBackend backend) => Text -- ^ SQL statement, possibly with placeholders. -> [PersistValue] -- ^ Values to fill the placeholders. -> ReaderT backend m () rawExecute x y = liftM (const ()) $ rawExecuteCount x y -- | Execute a raw SQL statement and return the number of -- rows it has modified. rawExecuteCount :: (MonadIO m, BackendCompatible SqlBackend backend) => Text -- ^ SQL statement, possibly with placeholders. -> [PersistValue] -- ^ Values to fill the placeholders. -> ReaderT backend m Int64 rawExecuteCount sql vals = do conn <- projectBackend `liftM` ask runLoggingT (logDebugNS (pack "SQL") $ T.append sql $ pack $ "; " ++ show vals) (connLogFunc conn) stmt <- getStmt sql res <- liftIO $ stmtExecute stmt vals liftIO $ stmtReset stmt return res getStmt :: (MonadIO m, MonadReader backend m, BackendCompatible SqlBackend backend) => Text -> m Statement getStmt sql = do conn <- projectBackend `liftM` ask liftIO $ getStmtConn conn sql getStmtConn :: SqlBackend -> Text -> IO Statement getStmtConn conn sql = do let cacheK = mkCacheKeyFromQuery sql mstmt <- statementCacheLookup (connStmtMap conn) cacheK stmt <- case mstmt of Just stmt -> pure stmt Nothing -> do stmt' <- liftIO $ connPrepare conn sql iactive <- liftIO $ newIORef True let stmt = Statement { stmtFinalize = do active <- readIORef iactive when active $ do stmtFinalize stmt' writeIORef iactive False , stmtReset = do active <- readIORef iactive when active $ stmtReset stmt' , stmtExecute = \x -> do active <- readIORef iactive if active then stmtExecute stmt' x else throwIO $ StatementAlreadyFinalized sql , stmtQuery = \x -> do active <- liftIO $ readIORef iactive if active then stmtQuery stmt' x else liftIO $ throwIO $ StatementAlreadyFinalized sql } liftIO $ statementCacheInsert (connStmtMap conn) cacheK stmt pure stmt (hookGetStatement $ connHooks conn) conn sql stmt -- | Execute a raw SQL statement and return its results as a -- list. If you do not expect a return value, use of -- `rawExecute` is recommended. -- -- If you're using 'Entity'@s@ (which is quite likely), then you -- /must/ use entity selection placeholders (double question -- mark, @??@). These @??@ placeholders are then replaced for -- the names of the columns that we need for your entities. -- You'll receive an error if you don't use the placeholders. -- Please see the 'Entity'@s@ documentation for more details. -- -- You may put value placeholders (question marks, @?@) in your -- SQL query. These placeholders are then replaced by the values -- you pass on the second parameter, already correctly escaped. -- You may want to use 'toPersistValue' to help you constructing -- the placeholder values. -- -- Since you're giving a raw SQL statement, you don't get any -- guarantees regarding safety. If 'rawSql' is not able to parse -- the results of your query back, then an exception is raised. -- However, most common problems are mitigated by using the -- entity selection placeholder @??@, and you shouldn't see any -- error at all if you're not using 'Single'. -- -- Some example of 'rawSql' based on this schema: -- -- @ -- share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| -- Person -- name String -- age Int Maybe -- deriving Show -- BlogPost -- title String -- authorId PersonId -- deriving Show -- |] -- @ -- -- Examples based on the above schema: -- -- @ -- getPerson :: MonadIO m => ReaderT SqlBackend m [Entity Person] -- getPerson = rawSql "select ?? from person where name=?" [PersistText "john"] -- -- getAge :: MonadIO m => ReaderT SqlBackend m [Single Int] -- getAge = rawSql "select person.age from person where name=?" [PersistText "john"] -- -- getAgeName :: MonadIO m => ReaderT SqlBackend m [(Single Int, Single Text)] -- getAgeName = rawSql "select person.age, person.name from person where name=?" [PersistText "john"] -- -- getPersonBlog :: MonadIO m => ReaderT SqlBackend m [(Entity Person, Entity BlogPost)] -- getPersonBlog = rawSql "select ??,?? from person,blog_post where person.id = blog_post.author_id" [] -- @ -- -- Minimal working program for PostgreSQL backend based on the above concepts: -- -- > {-# LANGUAGE EmptyDataDecls #-} -- > {-# LANGUAGE FlexibleContexts #-} -- > {-# LANGUAGE GADTs #-} -- > {-# LANGUAGE GeneralizedNewtypeDeriving #-} -- > {-# LANGUAGE MultiParamTypeClasses #-} -- > {-# LANGUAGE OverloadedStrings #-} -- > {-# LANGUAGE QuasiQuotes #-} -- > {-# LANGUAGE TemplateHaskell #-} -- > {-# LANGUAGE TypeFamilies #-} -- > -- > import Control.Monad.IO.Class (liftIO) -- > import Control.Monad.Logger (runStderrLoggingT) -- > import Database.Persist -- > import Control.Monad.Reader -- > import Data.Text -- > import Database.Persist.Sql -- > import Database.Persist.Postgresql -- > import Database.Persist.TH -- > -- > share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| -- > Person -- > name String -- > age Int Maybe -- > deriving Show -- > |] -- > -- > conn = "host=localhost dbname=new_db user=postgres password=postgres port=5432" -- > -- > getPerson :: MonadIO m => ReaderT SqlBackend m [Entity Person] -- > getPerson = rawSql "select ?? from person where name=?" [PersistText "sibi"] -- > -- > liftSqlPersistMPool y x = liftIO (runSqlPersistMPool y x) -- > -- > main :: IO () -- > main = runStderrLoggingT $ withPostgresqlPool conn 10 $ liftSqlPersistMPool $ do -- > runMigration migrateAll -- > xs <- getPerson -- > liftIO (print xs) -- > rawSql :: (RawSql a, MonadIO m, BackendCompatible SqlBackend backend) => Text -- ^ SQL statement, possibly with placeholders. -> [PersistValue] -- ^ Values to fill the placeholders. -> ReaderT backend m [a] rawSql stmt = run where getType :: (x -> m [a]) -> a getType = error "rawSql.getType" x = getType run process = rawSqlProcessRow withStmt' colSubsts params sink = do srcRes <- rawQueryRes sql params liftIO $ with srcRes (\src -> runConduit $ src .| sink) where sql = T.concat $ makeSubsts colSubsts $ T.splitOn placeholder stmt placeholder = "??" makeSubsts (s:ss) (t:ts) = t : s : makeSubsts ss ts makeSubsts [] [] = [] makeSubsts [] ts = [T.intercalate placeholder ts] makeSubsts ss [] = error (concat err) where err = [ "rawsql: there are still ", show (length ss) , "'??' placeholder substitutions to be made " , "but all '??' placeholders have already been " , "consumed. Please read 'rawSql's documentation " , "on how '??' placeholders work." ] run params = do conn <- projectBackend `liftM` ask let (colCount, colSubsts) = rawSqlCols (connEscapeRawName conn) x withStmt' colSubsts params $ firstRow colCount firstRow colCount = do mrow <- await case mrow of Nothing -> return [] Just row | colCount == length row -> getter mrow | otherwise -> fail $ concat [ "rawSql: wrong number of columns, got " , show (length row), " but expected ", show colCount , " (", rawSqlColCountReason x, ")." ] getter = go id where go acc Nothing = return (acc []) go acc (Just row) = case process row of Left err -> fail (T.unpack err) Right r -> await >>= go (acc . (r:))
paul-rouse/persistent
persistent/Database/Persist/Sql/Raw.hs
mit
10,187
54
20
3,033
1,775
972
803
-1
-1
{-# LANGUAGE TypeFamilies, MultiParamTypeClasses, FlexibleContexts, FlexibleInstances, RankNTypes, ScopedTypeVariables, StandaloneDeriving #-} {-| Module : Control.Monad.Module.IdealCoproduct Copyright : (c) 2015 Maciej Piróg License : MIT Maintainer : [email protected] Stability : experimental Haskell implementation of the coproduct of two ideal monads. For abstract nonsense, consult N. Ghani, T. Uustalu /Coproducts of ideal monads/ <http://www.cs.ioc.ee/~tarmo/papers/fics03-tia.pdf>. -} module Control.Monad.Module.IdealCoproduct ( -- * The @Turns@ datatype Turns(..), foldTurns, interpTurns, hoistTurns, turnsToFree, turnsToFreeC, -- * The @IdealCoproduct@ datatype IdealCoproduct(..), AmbiTurns(..), sym, liftl, liftr, foldIdealCoproduct, interpIdealCoproduct, hoistIdealCoproduct, idealCoproductToFree, idealCoproductToFreeC ) where import Control.Applicative (Applicative(..), (<$>)) import Control.Monad (ap) import Control.Monad.Free (Free(..)) import Data.Foldable (Foldable(..)) import Data.Traversable (Traversable(..)) import Data.Functor.Coproduct (Coproduct(..), left, right) import Data.Functor.Apply (Apply(..)) import Data.Functor.Bind (Bind(..)) import Control.Monad.Module -- | Values of @Turns h t a@ can be seen as interleaved layers of -- the functors @h@ and @t@ (they /take turns/) with variables of -- the type @a@ possible on every level (except for the outermost -- layer, which is always given by @h@). newtype Turns h t a = Turns { unTurns :: h (Either a (Turns t h a)) } instance (Functor h, Functor t) => Functor (Turns h t) where fmap f (Turns h) = Turns $ fmap aux h where aux (Left x) = Left $ f x aux (Right y) = Right $ fmap f y instance (Functor t, Functor h, Foldable t, Foldable h) => Foldable (Turns h t) where foldMap f (Turns h) = foldMap id $ fmap (either f (foldMap f)) h instance (Traversable t, Traversable h) => Traversable (Turns t h) where traverse f (Turns h) = fmap Turns $ traverse aux h where aux (Left a) = Left <$> f a aux (Right t) = Right <$> traverse f t -- | Fold the structure of a 'Turns' using an @h@-algebra and a -- @t@-algebra. foldTurns :: (Functor h, Functor t) => (h a -> a) -> (t a -> a) -> Turns h t a -> a foldTurns f g (Turns t) = f $ fmap aux t where aux (Left a) = a aux (Right i) = foldTurns g f i -- | Fold the structure of a 'Turns' by interpreting each level as -- a computation in a monad @k@ and then @'join'@-ing them to -- obtain one computation in @k@. interpTurns :: (Monad k) => (forall a. h a -> k a) -> (forall a. t a -> k a) -> Turns h t a -> k a interpTurns f g (Turns h) = f h >>= aux where aux (Left a) = return a aux (Right i) = interpTurns g f i -- | Use two natural transformations to \"rename\" the nodes. hoistTurns :: (Functor h, Functor t, Functor h', Functor t') => (forall a. h a -> h' a) -> (forall a. t a -> t' a) -> Turns h t a -> Turns h' t' a hoistTurns f g (Turns h) = Turns $ f $ fmap aux h where aux (Left a) = Left a aux (Right t) = Right $ hoistTurns g f t -- | Convert @'Turns'@ to @'Free'@. turnsToFree :: (Functor h, Functor t, Functor z) => (forall a. h a -> z a) -> (forall a. t a -> z a) -> Turns h t a -> Free z a turnsToFree f g (Turns h) = Free $ f $ fmap aux h where aux (Left a) = Pure a aux (Right t) = turnsToFree g f t -- | Convert @'Turns'@ to @'Free'@ generated by the coproduct of -- functors. turnsToFreeC :: (Functor h, Functor t) => Turns h t a -> Free (Coproduct h t) a turnsToFreeC = turnsToFree left right -- | The coproduct (a disjoint sum in the category of ideal monads) -- of ideal monads @m@ and @n@. Each value consists of alternating -- layers of the ideals of @m@ and @n@ with variables of the type -- @a@. data IdealCoproduct m n a = ICVar a | ICLeft (Turns (Ideal m) (Ideal n) a) | ICRight (Turns (Ideal n) (Ideal m) a) toM :: (MonadIdeal m, MonadIdeal n) => IdealCoproduct m n a -> m (Either a (Turns (Ideal n) (Ideal m) a)) toM (ICVar a) = return $ Left a toM (ICLeft i) = embed $ unTurns i toM (ICRight i) = return $ Right i (|>-) :: (MonadIdeal m, MonadIdeal n) => Turns (Ideal m) (Ideal n) a -> (a -> IdealCoproduct m n b) -> Turns (Ideal m) (Ideal n) b Turns x |>- f = Turns $ x |>>= aux where aux (Left a) = toM (f a) aux (Right i) = return $ Right $ i |>- (sym . f) instance (Functor (Ideal m), Functor (Ideal n)) => Functor (IdealCoproduct m n) where fmap f (ICVar a) = ICVar $ f a fmap f (ICLeft i) = ICLeft $ fmap f i fmap f (ICRight i) = ICRight $ fmap f i instance (MonadIdeal m, MonadIdeal n) => Monad (IdealCoproduct m n) where return = ICVar ICVar a >>= f = f a ICLeft i >>= f = ICLeft $ i |>- f ICRight i >>= f = ICRight $ i |>- (sym . f) instance (MonadIdeal m, MonadIdeal n) => Bind (IdealCoproduct m n) where (>>-) = (>>=) instance (MonadIdeal m, MonadIdeal n) => Applicative (IdealCoproduct m n) where pure = return (<*>) = ap instance (MonadIdeal m, MonadIdeal n) => Apply (IdealCoproduct m n) where (<.>) = (<*>) instance (MonadIdeal m, MonadIdeal n, Foldable (Ideal m), Foldable (Ideal n)) => Foldable (IdealCoproduct m n) where foldMap f (ICVar a) = f a foldMap f (ICLeft i) = foldMap f i foldMap f (ICRight i) = foldMap f i instance (MonadIdeal m, MonadIdeal n, Traversable (Ideal m), Traversable (Ideal n)) => Traversable (IdealCoproduct m n) where traverse f (ICVar a) = ICVar <$> f a traverse f (ICLeft i) = ICLeft <$> traverse f i traverse f (ICRight i) = ICRight <$> traverse f i -- | The ideal of 'IdealCoproduct'. (See also -- <https://www.youtube.com/watch?v=8hJ1HDcMowk>) newtype AmbiTurns m n a = AmbiTurns { unAmbiTurns :: (Either (Turns (Ideal m) (Ideal n) a) (Turns (Ideal n) (Ideal m) a)) } instance (MonadIdeal m, MonadIdeal n) => Functor (AmbiTurns m n) where fmap f (AmbiTurns (Left i)) = AmbiTurns $ Left $ fmap f i fmap f (AmbiTurns (Right i)) = AmbiTurns $ Right $ fmap f i instance (MonadIdeal m, MonadIdeal n, Foldable (Ideal m), Foldable (Ideal n)) => Foldable (AmbiTurns m n) where foldMap f = foldMap f . (embed :: AmbiTurns m n a -> IdealCoproduct m n a) -- ^ This is where scoped type variables come in handy! instance (MonadIdeal m, MonadIdeal n, Traversable (Ideal m), Traversable (Ideal n)) => Traversable (AmbiTurns m n) where traverse f (AmbiTurns (Left i)) = (AmbiTurns . Left) <$> traverse f i traverse f (AmbiTurns (Right i)) = (AmbiTurns . Right) <$> traverse f i instance (MonadIdeal m, MonadIdeal n) => Apply (AmbiTurns m n) where AmbiTurns (Left t) <.> u = AmbiTurns $ Left $ t |>- (\f -> (embed :: AmbiTurns m n a -> IdealCoproduct m n a) u >>= return . f) AmbiTurns (Right t) <.> u = AmbiTurns $ Right $ t |>- (\f -> sym ((embed :: AmbiTurns m n a -> IdealCoproduct m n a) u) >>= return . f) instance (MonadIdeal m, MonadIdeal n) => Bind (AmbiTurns m n) where AmbiTurns (Left t) >>- f = AmbiTurns $ Left $ t |>- ((embed :: AmbiTurns m n a -> IdealCoproduct m n a) . f) AmbiTurns (Right t) >>- f = AmbiTurns $ Right $ t |>- (sym . (embed :: AmbiTurns m n a -> IdealCoproduct m n a) . f) instance (MonadIdeal m, MonadIdeal n) => RModule (IdealCoproduct m n) (AmbiTurns m n) where AmbiTurns (Left i) |>>= f = AmbiTurns $ Left $ i |>- f AmbiTurns (Right i) |>>= f = AmbiTurns $ Right $ i |>- (sym . f) instance (MonadIdeal m, MonadIdeal n) => Idealised (IdealCoproduct m n) (AmbiTurns m n) where embed (AmbiTurns (Left i)) = ICLeft i embed (AmbiTurns (Right i)) = ICRight i instance (MonadIdeal m, MonadIdeal n) => MonadIdeal (IdealCoproduct m n) where type Ideal (IdealCoproduct m n) = AmbiTurns m n split (ICVar a) = Left a split (ICLeft i) = Right $ AmbiTurns $ Left i split (ICRight i) = Right $ AmbiTurns $ Right i -- | Swap the 'ICLeft' and 'ICRight' constructors. The function 'sym' is an involution, that is, @sym . sym = id@. sym :: IdealCoproduct m n a -> IdealCoproduct n m a sym (ICVar a) = ICVar a sym (ICLeft a) = ICRight a sym (ICRight a) = ICLeft a -- | Lift an ideal monad @m@ to @IdealCoproduct m n@. The function -- 'inl' respects the equations of the 'MonadTrans' class, that is: -- -- * @'liftl' . 'return' = 'return'@ -- -- * @'liftl' m '>>=' 'liftl' . f = 'liftl' (m '>>=' f)@ liftl :: (MonadIdeal m, MonadIdeal n) => m a -> IdealCoproduct m n a liftl m = case split m of Left a -> ICVar a Right m' -> ICLeft $ Turns $ fmap Left m' -- | Symmetric version of 'liftl'. liftr :: (MonadIdeal m, MonadIdeal n) => n a -> IdealCoproduct m n a liftr = sym . liftl -- | Fold the structure of an 'IdealCoproduct' using an @m@-algebra -- and an @n@-algebra. foldIdealCoproduct :: (MonadIdeal m, MonadIdeal n) => (m a -> a) -> (n a -> a) -> IdealCoproduct m n a -> a foldIdealCoproduct f g (ICVar a) = a foldIdealCoproduct f g (ICLeft i) = foldTurns (f . embed) (g . embed) i foldIdealCoproduct f g (ICRight i) = foldTurns (g . embed) (f . embed) i -- | Fold the structure of an 'IdealCoproduct' by interpreting each -- level as a computation in a monad @k@ and then @'join'@-ing them -- to obtain one computation in @k@. -- From the category-theoretic point of view, if the first two -- arguments are ideal monad morphisms, @'interpIdealCoproduct'@ is -- the coproduct mediator. interpIdealCoproduct :: (MonadIdeal m, MonadIdeal n, Monad k) => (forall a. m a -> k a) -> (forall a. n a -> k a) -> IdealCoproduct m n a -> k a interpIdealCoproduct f g (ICVar a) = return a interpIdealCoproduct f g (ICLeft i) = interpTurns (f . embed) (g . embed) i interpIdealCoproduct f g (ICRight i) = interpTurns (g . embed) (f . embed) i -- | Use two ideal monad morphisms to \"rename\" the nodes. hoistIdealCoproduct :: (MonadIdeal m, MonadIdeal n, MonadIdeal m', MonadIdeal n') => (forall a. m a -> m' a) -> (forall a. n a -> n' a) -> IdealCoproduct m n a -> IdealCoproduct m' n' a hoistIdealCoproduct _ _ (ICVar a) = ICVar a hoistIdealCoproduct f g (ICLeft t) = ICLeft $ hoistTurns (restriction f) (restriction g) t hoistIdealCoproduct f g (ICRight t) = ICRight $ hoistTurns (restriction g) (restriction f) t -- | Convert @'IdealCoproduct'@ to @'Free'@. idealCoproductToFree :: (MonadIdeal m, MonadIdeal n, Functor z) => (forall a. Ideal m a -> z a) -> (forall a. Ideal n a -> z a) -> IdealCoproduct m n a -> Free z a idealCoproductToFree _ _ (ICVar a) = Pure a idealCoproductToFree f g (ICLeft t) = turnsToFree f g t idealCoproductToFree f g (ICRight t) = turnsToFree g f t -- | Convert @'IdealCoproduct'@ to @'Free'@ generated by the -- ideals. idealCoproductToFreeC :: (MonadIdeal m, MonadIdeal n) => IdealCoproduct m n a -> Free (Coproduct (Ideal m) (Ideal n)) a idealCoproductToFreeC = idealCoproductToFree left right
maciejpirog/modules-over-monads
src/Control/Monad/Module/IdealCoproduct.hs
mit
10,943
43
19
2,441
4,206
2,144
2,062
168
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.OpsWorks.DeleteInstance -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Deletes a specified instance, which terminates the associated Amazon EC2 -- instance. You must stop an instance before you can delete it. -- -- For more information, see <http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-delete.html Deleting Instances>. -- -- Required Permissions: To use this action, an IAM user must have a Manage -- permissions level for the stack, or an attached policy that explicitly grants -- permissions. For more information on user permissions, see <http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html Managing UserPermissions>. -- -- <http://docs.aws.amazon.com/opsworks/latest/APIReference/API_DeleteInstance.html> module Network.AWS.OpsWorks.DeleteInstance ( -- * Request DeleteInstance -- ** Request constructor , deleteInstance -- ** Request lenses , diDeleteElasticIp , diDeleteVolumes , diInstanceId -- * Response , DeleteInstanceResponse -- ** Response constructor , deleteInstanceResponse ) where import Network.AWS.Data (Object) import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.OpsWorks.Types import qualified GHC.Exts data DeleteInstance = DeleteInstance { _diDeleteElasticIp :: Maybe Bool , _diDeleteVolumes :: Maybe Bool , _diInstanceId :: Text } deriving (Eq, Ord, Read, Show) -- | 'DeleteInstance' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'diDeleteElasticIp' @::@ 'Maybe' 'Bool' -- -- * 'diDeleteVolumes' @::@ 'Maybe' 'Bool' -- -- * 'diInstanceId' @::@ 'Text' -- deleteInstance :: Text -- ^ 'diInstanceId' -> DeleteInstance deleteInstance p1 = DeleteInstance { _diInstanceId = p1 , _diDeleteElasticIp = Nothing , _diDeleteVolumes = Nothing } -- | Whether to delete the instance Elastic IP address. diDeleteElasticIp :: Lens' DeleteInstance (Maybe Bool) diDeleteElasticIp = lens _diDeleteElasticIp (\s a -> s { _diDeleteElasticIp = a }) -- | Whether to delete the instance's Amazon EBS volumes. diDeleteVolumes :: Lens' DeleteInstance (Maybe Bool) diDeleteVolumes = lens _diDeleteVolumes (\s a -> s { _diDeleteVolumes = a }) -- | The instance ID. diInstanceId :: Lens' DeleteInstance Text diInstanceId = lens _diInstanceId (\s a -> s { _diInstanceId = a }) data DeleteInstanceResponse = DeleteInstanceResponse deriving (Eq, Ord, Read, Show, Generic) -- | 'DeleteInstanceResponse' constructor. deleteInstanceResponse :: DeleteInstanceResponse deleteInstanceResponse = DeleteInstanceResponse instance ToPath DeleteInstance where toPath = const "/" instance ToQuery DeleteInstance where toQuery = const mempty instance ToHeaders DeleteInstance instance ToJSON DeleteInstance where toJSON DeleteInstance{..} = object [ "InstanceId" .= _diInstanceId , "DeleteElasticIp" .= _diDeleteElasticIp , "DeleteVolumes" .= _diDeleteVolumes ] instance AWSRequest DeleteInstance where type Sv DeleteInstance = OpsWorks type Rs DeleteInstance = DeleteInstanceResponse request = post "DeleteInstance" response = nullResponse DeleteInstanceResponse
kim/amazonka
amazonka-opsworks/gen/Network/AWS/OpsWorks/DeleteInstance.hs
mpl-2.0
4,242
0
9
866
501
304
197
61
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} module Stack.PackageDump ( Line , eachSection , eachPair , DumpPackage (..) , conduitDumpPackage , ghcPkgDump , ghcPkgDescribe , InstalledCache , InstalledCacheEntry (..) , newInstalledCache , loadInstalledCache , saveInstalledCache , addProfiling , addHaddock , sinkMatching , pruneDeps ) where import Control.Applicative import Control.Arrow ((&&&)) import Control.Exception.Enclosed (tryIO) import Control.Monad (liftM) import Control.Monad.Catch import Control.Monad.IO.Class import Control.Monad.Logger (MonadLogger) import Control.Monad.Trans.Control import Data.Attoparsec.Args import Data.Attoparsec.Text as P import Data.Binary.VersionTagged import Data.Conduit import qualified Data.Conduit.List as CL import qualified Data.Conduit.Text as CT import Data.Either (partitionEithers) import Data.IORef import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (catMaybes, listToMaybe) import Data.Maybe.Extra (mapMaybeM) import qualified Data.Set as Set import qualified Data.Text as T import Data.Text (Text) import Data.Typeable (Typeable) import GHC.Generics (Generic) import Path import Path.IO (createTree) import Path.Extra (toFilePathNoTrailingSep) import Prelude -- Fix AMP warning import Stack.GhcPkg import Stack.Types import System.Directory (getDirectoryContents, doesFileExist) import System.Process.Read -- | Cached information on whether package have profiling libraries and haddocks. newtype InstalledCache = InstalledCache (IORef InstalledCacheInner) newtype InstalledCacheInner = InstalledCacheInner (Map GhcPkgId InstalledCacheEntry) deriving (Binary, NFData, Generic) instance HasStructuralInfo InstalledCacheInner instance HasSemanticVersion InstalledCacheInner -- | Cached information on whether a package has profiling libraries and haddocks. data InstalledCacheEntry = InstalledCacheEntry { installedCacheProfiling :: !Bool , installedCacheHaddock :: !Bool , installedCacheIdent :: !PackageIdentifier } deriving (Eq, Generic) instance Binary InstalledCacheEntry instance HasStructuralInfo InstalledCacheEntry instance NFData InstalledCacheEntry -- | Call ghc-pkg dump with appropriate flags and stream to the given @Sink@, for a single database ghcPkgDump :: (MonadIO m, MonadLogger m, MonadBaseControl IO m, MonadCatch m, MonadThrow m) => EnvOverride -> WhichCompiler -> [Path Abs Dir] -- ^ if empty, use global -> Sink Text IO a -> m a ghcPkgDump = ghcPkgCmdArgs ["dump"] -- | Call ghc-pkg describe with appropriate flags and stream to the given @Sink@, for a single database ghcPkgDescribe :: (MonadIO m, MonadLogger m, MonadBaseControl IO m, MonadCatch m, MonadThrow m) => PackageName -> EnvOverride -> WhichCompiler -> [Path Abs Dir] -- ^ if empty, use global -> Sink Text IO a -> m a ghcPkgDescribe pkgName = ghcPkgCmdArgs ["describe", "--simple-output", packageNameString pkgName] -- | Call ghc-pkg and stream to the given @Sink@, for a single database ghcPkgCmdArgs :: (MonadIO m, MonadLogger m, MonadBaseControl IO m, MonadCatch m, MonadThrow m) => [String] -> EnvOverride -> WhichCompiler -> [Path Abs Dir] -- ^ if empty, use global -> Sink Text IO a -> m a ghcPkgCmdArgs cmd menv wc mpkgDbs sink = do case reverse mpkgDbs of (pkgDb:_) -> createDatabase menv wc pkgDb -- TODO maybe use some retry logic instead? _ -> return () sinkProcessStdout Nothing menv (ghcPkgExeName wc) args sink' where args = concat [ case mpkgDbs of [] -> ["--global", "--no-user-package-db"] _ -> ["--user", "--no-user-package-db"] ++ concatMap (\pkgDb -> ["--package-db", toFilePathNoTrailingSep pkgDb]) mpkgDbs , cmd , ["--expand-pkgroot"] ] sink' = CT.decodeUtf8 =$= sink -- | Create a new, empty @InstalledCache@ newInstalledCache :: MonadIO m => m InstalledCache newInstalledCache = liftIO $ InstalledCache <$> newIORef (InstalledCacheInner Map.empty) -- | Load a @InstalledCache@ from disk, swallowing any errors and returning an -- empty cache. loadInstalledCache :: (MonadLogger m, MonadIO m) => Path Abs File -> m InstalledCache loadInstalledCache path = do m <- taggedDecodeOrLoad path (return $ InstalledCacheInner Map.empty) liftIO $ InstalledCache <$> newIORef m -- | Save a @InstalledCache@ to disk saveInstalledCache :: MonadIO m => Path Abs File -> InstalledCache -> m () saveInstalledCache path (InstalledCache ref) = liftIO $ do createTree (parent path) readIORef ref >>= taggedEncodeFile path -- | Prune a list of possible packages down to those whose dependencies are met. -- -- * id uniquely identifies an item -- -- * There can be multiple items per name pruneDeps :: (Ord name, Ord id) => (id -> name) -- ^ extract the name from an id -> (item -> id) -- ^ the id of an item -> (item -> [id]) -- ^ get the dependencies of an item -> (item -> item -> item) -- ^ choose the desired of two possible items -> [item] -- ^ input items -> Map name item pruneDeps getName getId getDepends chooseBest = Map.fromList . fmap (getName . getId &&& id) . loop Set.empty Set.empty [] where loop foundIds usedNames foundItems dps = case partitionEithers $ map depsMet dps of ([], _) -> foundItems (s', dps') -> let foundIds' = Map.fromListWith chooseBest s' foundIds'' = Set.fromList $ map getId $ Map.elems foundIds' usedNames' = Map.keysSet foundIds' foundItems' = Map.elems foundIds' in loop (Set.union foundIds foundIds'') (Set.union usedNames usedNames') (foundItems ++ foundItems') (catMaybes dps') where depsMet dp | name `Set.member` usedNames = Right Nothing | all (`Set.member` foundIds) (getDepends dp) = Left (name, dp) | otherwise = Right $ Just dp where id' = getId dp name = getName id' -- | Find the package IDs matching the given constraints with all dependencies installed. -- Packages not mentioned in the provided @Map@ are allowed to be present too. sinkMatching :: Monad m => Bool -- ^ require profiling? -> Bool -- ^ require haddock? -> Map PackageName Version -- ^ allowed versions -> Consumer (DumpPackage Bool Bool) m (Map PackageName (DumpPackage Bool Bool)) sinkMatching reqProfiling reqHaddock allowed = do dps <- CL.filter (\dp -> isAllowed (dpPackageIdent dp) && (not reqProfiling || dpProfiling dp) && (not reqHaddock || dpHaddock dp)) =$= CL.consume return $ Map.fromList $ map (packageIdentifierName . dpPackageIdent &&& id) $ Map.elems $ pruneDeps id dpGhcPkgId dpDepends const -- Could consider a better comparison in the future dps where isAllowed (PackageIdentifier name version) = case Map.lookup name allowed of Just version' | version /= version' -> False _ -> True -- | Add profiling information to the stream of @DumpPackage@s addProfiling :: MonadIO m => InstalledCache -> Conduit (DumpPackage a b) m (DumpPackage Bool b) addProfiling (InstalledCache ref) = CL.mapM go where go dp = liftIO $ do InstalledCacheInner m <- readIORef ref let gid = dpGhcPkgId dp p <- case Map.lookup gid m of Just installed -> return (installedCacheProfiling installed) Nothing | null (dpLibraries dp) -> return True Nothing -> do let loop [] = return False loop (dir:dirs) = do econtents <- tryIO $ getDirectoryContents dir let contents = either (const []) id econtents if or [isProfiling content lib | content <- contents , lib <- dpLibraries dp ] && not (null contents) then return True else loop dirs loop $ dpLibDirs dp return dp { dpProfiling = p } isProfiling :: FilePath -- ^ entry in directory -> Text -- ^ name of library -> Bool isProfiling content lib = prefix `T.isPrefixOf` T.pack content where prefix = T.concat ["lib", lib, "_p"] -- | Add haddock information to the stream of @DumpPackage@s addHaddock :: MonadIO m => InstalledCache -> Conduit (DumpPackage a b) m (DumpPackage a Bool) addHaddock (InstalledCache ref) = CL.mapM go where go dp = liftIO $ do InstalledCacheInner m <- readIORef ref let gid = dpGhcPkgId dp h <- case Map.lookup gid m of Just installed -> return (installedCacheHaddock installed) Nothing | not (dpHasExposedModules dp) -> return True Nothing -> do let loop [] = return False loop (ifc:ifcs) = do exists <- doesFileExist ifc if exists then return True else loop ifcs loop $ dpHaddockInterfaces dp return dp { dpHaddock = h } -- | Dump information for a single package data DumpPackage profiling haddock = DumpPackage { dpGhcPkgId :: !GhcPkgId , dpPackageIdent :: !PackageIdentifier , dpLibDirs :: ![FilePath] , dpLibraries :: ![Text] , dpHasExposedModules :: !Bool , dpDepends :: ![GhcPkgId] , dpHaddockInterfaces :: ![FilePath] , dpHaddockHtml :: !(Maybe FilePath) , dpProfiling :: !profiling , dpHaddock :: !haddock , dpIsExposed :: !Bool } deriving (Show, Eq, Ord) data PackageDumpException = MissingSingleField Text (Map Text [Line]) | Couldn'tParseField Text [Line] deriving Typeable instance Exception PackageDumpException instance Show PackageDumpException where show (MissingSingleField name values) = unlines $ concat [ return $ concat [ "Expected single value for field name " , show name , " when parsing ghc-pkg dump output:" ] , map (\(k, v) -> " " ++ show (k, v)) (Map.toList values) ] show (Couldn'tParseField name ls) = "Couldn't parse the field " ++ show name ++ " from lines: " ++ show ls -- | Convert a stream of bytes into a stream of @DumpPackage@s conduitDumpPackage :: MonadThrow m => Conduit Text m (DumpPackage () ()) conduitDumpPackage = (=$= CL.catMaybes) $ eachSection $ do pairs <- eachPair (\k -> (k, ) <$> CL.consume) =$= CL.consume let m = Map.fromList pairs let parseS k = case Map.lookup k m of Just [v] -> return v _ -> throwM $ MissingSingleField k m -- Can't fail: if not found, same as an empty list. See: -- https://github.com/fpco/stack/issues/182 parseM k = Map.findWithDefault [] k m parseDepend :: MonadThrow m => Text -> m (Maybe GhcPkgId) parseDepend "builtin_rts" = return Nothing parseDepend bs = liftM Just $ parseGhcPkgId bs' where (bs', _builtinRts) = case stripSuffixText " builtin_rts" bs of Nothing -> case stripPrefixText "builtin_rts " bs of Nothing -> (bs, False) Just x -> (x, True) Just x -> (x, True) case Map.lookup "id" m of Just ["builtin_rts"] -> return Nothing _ -> do name <- parseS "name" >>= parsePackageName version <- parseS "version" >>= parseVersion ghcPkgId <- parseS "id" >>= parseGhcPkgId -- if a package has no modules, these won't exist let libDirKey = "library-dirs" libraries = parseM "hs-libraries" exposedModules = parseM "exposed-modules" exposed = parseM "exposed" depends <- mapMaybeM parseDepend $ concatMap T.words $ parseM "depends" let parseQuoted key = case mapM (P.parseOnly (argsParser NoEscaping)) val of Left{} -> throwM (Couldn'tParseField key val) Right dirs -> return (concat dirs) where val = parseM key libDirPaths <- parseQuoted libDirKey haddockInterfaces <- parseQuoted "haddock-interfaces" haddockHtml <- parseQuoted "haddock-html" return $ Just DumpPackage { dpGhcPkgId = ghcPkgId , dpPackageIdent = PackageIdentifier name version , dpLibDirs = libDirPaths , dpLibraries = T.words $ T.unwords libraries , dpHasExposedModules = not (null libraries || null exposedModules) , dpDepends = depends , dpHaddockInterfaces = haddockInterfaces , dpHaddockHtml = listToMaybe haddockHtml , dpProfiling = () , dpHaddock = () , dpIsExposed = exposed == ["True"] } stripPrefixText :: Text -> Text -> Maybe Text stripPrefixText x y | x `T.isPrefixOf` y = Just $ T.drop (T.length x) y | otherwise = Nothing stripSuffixText :: Text -> Text -> Maybe Text stripSuffixText x y | x `T.isSuffixOf` y = Just $ T.take (T.length y - T.length x) y | otherwise = Nothing -- | A single line of input, not including line endings type Line = Text -- | Apply the given Sink to each section of output, broken by a single line containing --- eachSection :: Monad m => Sink Line m a -> Conduit Text m a eachSection inner = CL.map (T.filter (/= '\r')) =$= CT.lines =$= start where peekText = await >>= maybe (return Nothing) (\bs -> if T.null bs then peekText else leftover bs >> return (Just bs)) start = peekText >>= maybe (return ()) (const go) go = do x <- toConsumer $ takeWhileC (/= "---") =$= inner yield x CL.drop 1 start -- | Grab each key/value pair eachPair :: Monad m => (Text -> Sink Line m a) -> Conduit Line m a eachPair inner = start where start = await >>= maybe (return ()) start' start' bs1 = toConsumer (valSrc =$= inner key) >>= yield >> start where (key, bs2) = T.break (== ':') bs1 (spaces, bs3) = T.span (== ' ') $ T.drop 1 bs2 indent = T.length key + 1 + T.length spaces valSrc | T.null bs3 = noIndent | otherwise = yield bs3 >> loopIndent indent noIndent = do mx <- await case mx of Nothing -> return () Just bs -> do let (spaces, val) = T.span (== ' ') bs if T.length spaces == 0 then leftover val else do yield val loopIndent (T.length spaces) loopIndent i = loop where loop = await >>= maybe (return ()) go go bs | T.length spaces == i && T.all (== ' ') spaces = yield val >> loop | otherwise = leftover bs where (spaces, val) = T.splitAt i bs -- | General purpose utility takeWhileC :: Monad m => (a -> Bool) -> Conduit a m a takeWhileC f = loop where loop = await >>= maybe (return ()) go go x | f x = yield x >> loop | otherwise = leftover x
rubik/stack
src/Stack/PackageDump.hs
bsd-3-clause
16,527
1
27
5,401
4,229
2,162
2,067
-1
-1
----------------------------------------------------------------------------- -- | -- Module : System.Mem -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- Memory-related system things. -- ----------------------------------------------------------------------------- module System.Mem ( performGC -- :: IO () ) where import Prelude #ifdef __HUGS__ import Hugs.IOExts #endif #ifdef __GLASGOW_HASKELL__ -- | Triggers an immediate garbage collection foreign import ccall {-safe-} "performMajorGC" performGC :: IO () #endif #ifdef __NHC__ import NHC.IOExtras (performGC) #endif
FranklinChen/hugs98-plus-Sep2006
packages/base/System/Mem.hs
bsd-3-clause
766
2
7
117
70
50
20
3
0
{-# LANGUAGE TransformListComp #-} ----------------------------------------------------------------------------- -- | -- Module : Haddock.Backends.Html.Decl -- Copyright : (c) Simon Marlow 2003-2006, -- David Waern 2006-2009, -- Mark Lentczner 2010 -- License : BSD-like -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable ----------------------------------------------------------------------------- module Haddock.Backends.Xhtml.Decl ( ppDecl, ppTyName, ppTyFamHeader, ppTypeApp, tyvarNames ) where import Haddock.Backends.Xhtml.DocMarkup import Haddock.Backends.Xhtml.Layout import Haddock.Backends.Xhtml.Names import Haddock.Backends.Xhtml.Types import Haddock.Backends.Xhtml.Utils import Haddock.GhcUtils import Haddock.Types import Haddock.Doc (combineDocumentation) import Control.Applicative import Data.List ( intersperse, sort ) import qualified Data.Map as Map import Data.Maybe import Text.XHtml hiding ( name, title, p, quote ) import GHC import GHC.Exts import Name import BooleanFormula ppDecl :: Bool -> LinksInfo -> LHsDecl DocName -> DocForDecl DocName -> [DocInstance DocName] -> [(DocName, Fixity)] -> [(DocName, DocForDecl DocName)] -> Splice -> Unicode -> Qualification -> Html ppDecl summ links (L loc decl) (mbDoc, fnArgsDoc) instances fixities subdocs splice unicode qual = case decl of TyClD (FamDecl d) -> ppTyFam summ False links instances fixities loc mbDoc d splice unicode qual TyClD d@(DataDecl {}) -> ppDataDecl summ links instances fixities subdocs loc mbDoc d splice unicode qual TyClD d@(SynDecl {}) -> ppTySyn summ links fixities loc (mbDoc, fnArgsDoc) d splice unicode qual TyClD d@(ClassDecl {}) -> ppClassDecl summ links instances fixities loc mbDoc subdocs d splice unicode qual SigD (TypeSig lnames lty _) -> ppLFunSig summ links loc (mbDoc, fnArgsDoc) lnames lty fixities splice unicode qual SigD (PatSynSig lname qtvs prov req ty) -> ppLPatSig summ links loc (mbDoc, fnArgsDoc) lname qtvs prov req ty fixities splice unicode qual ForD d -> ppFor summ links loc (mbDoc, fnArgsDoc) d fixities splice unicode qual InstD _ -> noHtml _ -> error "declaration not supported by ppDecl" ppLFunSig :: Bool -> LinksInfo -> SrcSpan -> DocForDecl DocName -> [Located DocName] -> LHsType DocName -> [(DocName, Fixity)] -> Splice -> Unicode -> Qualification -> Html ppLFunSig summary links loc doc lnames lty fixities splice unicode qual = ppFunSig summary links loc doc (map unLoc lnames) (unLoc lty) fixities splice unicode qual ppFunSig :: Bool -> LinksInfo -> SrcSpan -> DocForDecl DocName -> [DocName] -> HsType DocName -> [(DocName, Fixity)] -> Splice -> Unicode -> Qualification -> Html ppFunSig summary links loc doc docnames typ fixities splice unicode qual = ppSigLike summary links loc mempty doc docnames fixities (typ, pp_typ) splice unicode qual where pp_typ = ppType unicode qual typ ppLPatSig :: Bool -> LinksInfo -> SrcSpan -> DocForDecl DocName -> Located DocName -> (HsExplicitFlag, LHsTyVarBndrs DocName) -> LHsContext DocName -> LHsContext DocName -> LHsType DocName -> [(DocName, Fixity)] -> Splice -> Unicode -> Qualification -> Html ppLPatSig summary links loc (doc, _argDocs) (L _ name) (expl, qtvs) lprov lreq typ fixities splice unicode qual | summary = pref1 | otherwise = topDeclElem links loc splice [name] (pref1 <+> ppFixities fixities qual) +++ docSection Nothing qual doc where pref1 = hsep [ keyword "pattern" , ppBinder summary occname , dcolon unicode , ppLTyVarBndrs expl qtvs unicode qual , cxt , ppLType unicode qual typ ] cxt = case (ppLContextMaybe lprov unicode qual, ppLContextMaybe lreq unicode qual) of (Nothing, Nothing) -> noHtml (Nothing, Just req) -> parens noHtml <+> darr <+> req <+> darr (Just prov, Nothing) -> prov <+> darr (Just prov, Just req) -> prov <+> darr <+> req <+> darr darr = darrow unicode occname = nameOccName . getName $ name ppSigLike :: Bool -> LinksInfo -> SrcSpan -> Html -> DocForDecl DocName -> [DocName] -> [(DocName, Fixity)] -> (HsType DocName, Html) -> Splice -> Unicode -> Qualification -> Html ppSigLike summary links loc leader doc docnames fixities (typ, pp_typ) splice unicode qual = ppTypeOrFunSig summary links loc docnames typ doc ( addFixities $ leader <+> ppTypeSig summary occnames pp_typ unicode , addFixities . concatHtml . punctuate comma $ map (ppBinder False) occnames , dcolon unicode ) splice unicode qual where occnames = map (nameOccName . getName) docnames addFixities html | summary = html | otherwise = html <+> ppFixities fixities qual ppTypeOrFunSig :: Bool -> LinksInfo -> SrcSpan -> [DocName] -> HsType DocName -> DocForDecl DocName -> (Html, Html, Html) -> Splice -> Unicode -> Qualification -> Html ppTypeOrFunSig summary links loc docnames typ (doc, argDocs) (pref1, pref2, sep) splice unicode qual | summary = pref1 | Map.null argDocs = topDeclElem links loc splice docnames pref1 +++ docSection curName qual doc | otherwise = topDeclElem links loc splice docnames pref2 +++ subArguments qual (do_args 0 sep typ) +++ docSection curName qual doc where curName = getName <$> listToMaybe docnames argDoc n = Map.lookup n argDocs do_largs n leader (L _ t) = do_args n leader t do_args :: Int -> Html -> HsType DocName -> [SubDecl] do_args n leader (HsForAllTy _ _ tvs lctxt ltype) = case unLoc lctxt of [] -> do_largs n leader' ltype _ -> (leader' <+> ppLContextNoArrow lctxt unicode qual, Nothing, []) : do_largs n (darrow unicode) ltype where leader' = leader <+> ppForAll tvs unicode qual do_args n leader (HsFunTy lt r) = (leader <+> ppLFunLhType unicode qual lt, argDoc n, []) : do_largs (n+1) (arrow unicode) r do_args n leader t = [(leader <+> ppType unicode qual t, argDoc n, [])] ppForAll :: LHsTyVarBndrs DocName -> Unicode -> Qualification -> Html ppForAll tvs unicode qual = case [ppKTv n k | L _ (KindedTyVar (L _ n) k) <- hsQTvBndrs tvs] of [] -> noHtml ts -> forallSymbol unicode <+> hsep ts +++ dot where ppKTv n k = parens $ ppTyName (getName n) <+> dcolon unicode <+> ppLKind unicode qual k ppFixities :: [(DocName, Fixity)] -> Qualification -> Html ppFixities [] _ = noHtml ppFixities fs qual = foldr1 (+++) (map ppFix uniq_fs) +++ rightEdge where ppFix (ns, p, d) = thespan ! [theclass "fixity"] << (toHtml d <+> toHtml (show p) <+> ppNames ns) ppDir InfixR = "infixr" ppDir InfixL = "infixl" ppDir InfixN = "infix" ppNames = case fs of _:[] -> const noHtml -- Don't display names for fixities on single names _ -> concatHtml . intersperse (stringToHtml ", ") . map (ppDocName qual Infix False) uniq_fs = [ (n, the p, the d') | (n, Fixity p d) <- fs , let d' = ppDir d , then group by Down (p,d') using groupWith ] rightEdge = thespan ! [theclass "rightedge"] << noHtml ppTyVars :: LHsTyVarBndrs DocName -> [Html] ppTyVars tvs = map ppTyName (tyvarNames tvs) tyvarNames :: LHsTyVarBndrs DocName -> [Name] tyvarNames = map getName . hsLTyVarNames ppFor :: Bool -> LinksInfo -> SrcSpan -> DocForDecl DocName -> ForeignDecl DocName -> [(DocName, Fixity)] -> Splice -> Unicode -> Qualification -> Html ppFor summary links loc doc (ForeignImport (L _ name) (L _ typ) _ _) fixities splice unicode qual = ppFunSig summary links loc doc [name] typ fixities splice unicode qual ppFor _ _ _ _ _ _ _ _ _ = error "ppFor" -- we skip type patterns for now ppTySyn :: Bool -> LinksInfo -> [(DocName, Fixity)] -> SrcSpan -> DocForDecl DocName -> TyClDecl DocName -> Splice -> Unicode -> Qualification -> Html ppTySyn summary links fixities loc doc (SynDecl { tcdLName = L _ name, tcdTyVars = ltyvars , tcdRhs = ltype }) splice unicode qual = ppTypeOrFunSig summary links loc [name] (unLoc ltype) doc (full <+> fixs, hdr <+> fixs, spaceHtml +++ equals) splice unicode qual where hdr = hsep ([keyword "type", ppBinder summary occ] ++ ppTyVars ltyvars) full = hdr <+> equals <+> ppLType unicode qual ltype occ = nameOccName . getName $ name fixs | summary = noHtml | otherwise = ppFixities fixities qual ppTySyn _ _ _ _ _ _ _ _ _ = error "declaration not supported by ppTySyn" ppTypeSig :: Bool -> [OccName] -> Html -> Bool -> Html ppTypeSig summary nms pp_ty unicode = concatHtml htmlNames <+> dcolon unicode <+> pp_ty where htmlNames = intersperse (stringToHtml ", ") $ map (ppBinder summary) nms ppTyName :: Name -> Html ppTyName = ppName Prefix -------------------------------------------------------------------------------- -- * Type families -------------------------------------------------------------------------------- ppTyFamHeader :: Bool -> Bool -> FamilyDecl DocName -> Unicode -> Qualification -> Html ppTyFamHeader summary associated d@(FamilyDecl { fdInfo = info , fdKindSig = mkind }) unicode qual = (case info of OpenTypeFamily | associated -> keyword "type" | otherwise -> keyword "type family" DataFamily | associated -> keyword "data" | otherwise -> keyword "data family" ClosedTypeFamily _ -> keyword "type family" ) <+> ppFamDeclBinderWithVars summary d <+> (case mkind of Just kind -> dcolon unicode <+> ppLKind unicode qual kind Nothing -> noHtml ) ppTyFam :: Bool -> Bool -> LinksInfo -> [DocInstance DocName] -> [(DocName, Fixity)] -> SrcSpan -> Documentation DocName -> FamilyDecl DocName -> Splice -> Unicode -> Qualification -> Html ppTyFam summary associated links instances fixities loc doc decl splice unicode qual | summary = ppTyFamHeader True associated decl unicode qual | otherwise = header_ +++ docSection Nothing qual doc +++ instancesBit where docname = unLoc $ fdLName decl header_ = topDeclElem links loc splice [docname] $ ppTyFamHeader summary associated decl unicode qual <+> ppFixities fixities qual instancesBit | FamilyDecl { fdInfo = ClosedTypeFamily eqns } <- decl , not summary = subEquations qual $ map (ppTyFamEqn . unLoc) eqns | otherwise = ppInstances links instances docname unicode qual -- Individual equation of a closed type family ppTyFamEqn TyFamEqn { tfe_tycon = n, tfe_rhs = rhs , tfe_pats = HsWB { hswb_cts = ts }} = ( ppAppNameTypes (unLoc n) [] (map unLoc ts) unicode qual <+> equals <+> ppType unicode qual (unLoc rhs) , Nothing, [] ) -------------------------------------------------------------------------------- -- * Associated Types -------------------------------------------------------------------------------- ppAssocType :: Bool -> LinksInfo -> DocForDecl DocName -> LFamilyDecl DocName -> [(DocName, Fixity)] -> Splice -> Unicode -> Qualification -> Html ppAssocType summ links doc (L loc decl) fixities splice unicode qual = ppTyFam summ True links [] fixities loc (fst doc) decl splice unicode qual -------------------------------------------------------------------------------- -- * TyClDecl helpers -------------------------------------------------------------------------------- -- | Print a type family and its variables ppFamDeclBinderWithVars :: Bool -> FamilyDecl DocName -> Html ppFamDeclBinderWithVars summ (FamilyDecl { fdLName = lname, fdTyVars = tvs }) = ppAppDocNameNames summ (unLoc lname) (tyvarNames tvs) -- | Print a newtype / data binder and its variables ppDataBinderWithVars :: Bool -> TyClDecl DocName -> Html ppDataBinderWithVars summ decl = ppAppDocNameNames summ (tcdName decl) (tyvarNames $ tcdTyVars decl) -------------------------------------------------------------------------------- -- * Type applications -------------------------------------------------------------------------------- -- | Print an application of a DocName and two lists of HsTypes (kinds, types) ppAppNameTypes :: DocName -> [HsType DocName] -> [HsType DocName] -> Unicode -> Qualification -> Html ppAppNameTypes n ks ts unicode qual = ppTypeApp n ks ts (\p -> ppDocName qual p True) (ppParendType unicode qual) -- | Print an application of a DocName and a list of Names ppAppDocNameNames :: Bool -> DocName -> [Name] -> Html ppAppDocNameNames summ n ns = ppTypeApp n [] ns ppDN ppTyName where ppDN notation = ppBinderFixity notation summ . nameOccName . getName ppBinderFixity Infix = ppBinderInfix ppBinderFixity _ = ppBinder -- | General printing of type applications ppTypeApp :: DocName -> [a] -> [a] -> (Notation -> DocName -> Html) -> (a -> Html) -> Html ppTypeApp n [] (t1:t2:rest) ppDN ppT | operator, not . null $ rest = parens opApp <+> hsep (map ppT rest) | operator = opApp where operator = isNameSym . getName $ n opApp = ppT t1 <+> ppDN Infix n <+> ppT t2 ppTypeApp n ks ts ppDN ppT = ppDN Prefix n <+> hsep (map ppT $ ks ++ ts) ------------------------------------------------------------------------------- -- * Contexts ------------------------------------------------------------------------------- ppLContext, ppLContextNoArrow :: Located (HsContext DocName) -> Unicode -> Qualification -> Html ppLContext = ppContext . unLoc ppLContextNoArrow = ppContextNoArrow . unLoc ppLContextMaybe :: Located (HsContext DocName) -> Unicode -> Qualification -> Maybe Html ppLContextMaybe = ppContextNoLocsMaybe . map unLoc . unLoc ppContextNoArrow :: HsContext DocName -> Unicode -> Qualification -> Html ppContextNoArrow cxt unicode qual = fromMaybe noHtml $ ppContextNoLocsMaybe (map unLoc cxt) unicode qual ppContextNoLocs :: [HsType DocName] -> Unicode -> Qualification -> Html ppContextNoLocs cxt unicode qual = maybe noHtml (<+> darrow unicode) $ ppContextNoLocsMaybe cxt unicode qual ppContextNoLocsMaybe :: [HsType DocName] -> Unicode -> Qualification -> Maybe Html ppContextNoLocsMaybe [] _ _ = Nothing ppContextNoLocsMaybe cxt unicode qual = Just $ ppHsContext cxt unicode qual ppContext :: HsContext DocName -> Unicode -> Qualification -> Html ppContext cxt unicode qual = ppContextNoLocs (map unLoc cxt) unicode qual ppHsContext :: [HsType DocName] -> Unicode -> Qualification-> Html ppHsContext [] _ _ = noHtml ppHsContext [p] unicode qual = ppCtxType unicode qual p ppHsContext cxt unicode qual = parenList (map (ppType unicode qual) cxt) ------------------------------------------------------------------------------- -- * Class declarations ------------------------------------------------------------------------------- ppClassHdr :: Bool -> Located [LHsType DocName] -> DocName -> LHsTyVarBndrs DocName -> [Located ([Located DocName], [Located DocName])] -> Unicode -> Qualification -> Html ppClassHdr summ lctxt n tvs fds unicode qual = keyword "class" <+> (if not . null . unLoc $ lctxt then ppLContext lctxt unicode qual else noHtml) <+> ppAppDocNameNames summ n (tyvarNames tvs) <+> ppFds fds unicode qual ppFds :: [Located ([Located DocName], [Located DocName])] -> Unicode -> Qualification -> Html ppFds fds unicode qual = if null fds then noHtml else char '|' <+> hsep (punctuate comma (map (fundep . unLoc) fds)) where fundep (vars1,vars2) = ppVars vars1 <+> arrow unicode <+> ppVars vars2 ppVars = hsep . map ((ppDocName qual Prefix True) . unLoc) ppShortClassDecl :: Bool -> LinksInfo -> TyClDecl DocName -> SrcSpan -> [(DocName, DocForDecl DocName)] -> Splice -> Unicode -> Qualification -> Html ppShortClassDecl summary links (ClassDecl { tcdCtxt = lctxt, tcdLName = lname, tcdTyVars = tvs , tcdFDs = fds, tcdSigs = sigs, tcdATs = ats }) loc subdocs splice unicode qual = if not (any isVanillaLSig sigs) && null ats then (if summary then id else topDeclElem links loc splice [nm]) hdr else (if summary then id else topDeclElem links loc splice [nm]) (hdr <+> keyword "where") +++ shortSubDecls False ( [ ppAssocType summary links doc at [] splice unicode qual | at <- ats , let doc = lookupAnySubdoc (unL $ fdLName $ unL at) subdocs ] ++ -- ToDo: add associated type defaults [ ppFunSig summary links loc doc names typ [] splice unicode qual | L _ (TypeSig lnames (L _ typ) _) <- sigs , let doc = lookupAnySubdoc (head names) subdocs names = map unLoc lnames ] -- FIXME: is taking just the first name ok? Is it possible that -- there are different subdocs for different names in a single -- type signature? ) where hdr = ppClassHdr summary lctxt (unLoc lname) tvs fds unicode qual nm = unLoc lname ppShortClassDecl _ _ _ _ _ _ _ _ = error "declaration type not supported by ppShortClassDecl" ppClassDecl :: Bool -> LinksInfo -> [DocInstance DocName] -> [(DocName, Fixity)] -> SrcSpan -> Documentation DocName -> [(DocName, DocForDecl DocName)] -> TyClDecl DocName -> Splice -> Unicode -> Qualification -> Html ppClassDecl summary links instances fixities loc d subdocs decl@(ClassDecl { tcdCtxt = lctxt, tcdLName = lname, tcdTyVars = ltyvars , tcdFDs = lfds, tcdSigs = lsigs, tcdATs = ats }) splice unicode qual | summary = ppShortClassDecl summary links decl loc subdocs splice unicode qual | otherwise = classheader +++ docSection Nothing qual d +++ minimalBit +++ atBit +++ methodBit +++ instancesBit where classheader | any isVanillaLSig lsigs = topDeclElem links loc splice [nm] (hdr unicode qual <+> keyword "where" <+> fixs) | otherwise = topDeclElem links loc splice [nm] (hdr unicode qual <+> fixs) -- Only the fixity relevant to the class header fixs = ppFixities [ f | f@(n,_) <- fixities, n == unLoc lname ] qual nm = tcdName decl hdr = ppClassHdr summary lctxt (unLoc lname) ltyvars lfds -- ToDo: add assocatied typ defaults atBit = subAssociatedTypes [ ppAssocType summary links doc at subfixs splice unicode qual | at <- ats , let n = unL . fdLName $ unL at doc = lookupAnySubdoc (unL $ fdLName $ unL at) subdocs subfixs = [ f | f@(n',_) <- fixities, n == n' ] ] methodBit = subMethods [ ppFunSig summary links loc doc names typ subfixs splice unicode qual | L _ (TypeSig lnames (L _ typ) _) <- lsigs , let doc = lookupAnySubdoc (head names) subdocs subfixs = [ f | n <- names , f@(n',_) <- fixities , n == n' ] names = map unLoc lnames ] -- FIXME: is taking just the first name ok? Is it possible that -- there are different subdocs for different names in a single -- type signature? minimalBit = case [ s | L _ (MinimalSig _ s) <- lsigs ] of -- Miminal complete definition = every shown method And xs : _ | sort [getName n | Var (L _ n) <- xs] == sort [getName n | L _ (TypeSig ns _ _) <- lsigs, L _ n <- ns] -> noHtml -- Minimal complete definition = the only shown method Var (L _ n) : _ | [getName n] == [getName n' | L _ (TypeSig ns _ _) <- lsigs, L _ n' <- ns] -> noHtml -- Minimal complete definition = nothing And [] : _ -> subMinimal $ toHtml "Nothing" m : _ -> subMinimal $ ppMinimal False m _ -> noHtml ppMinimal _ (Var (L _ n)) = ppDocName qual Prefix True n ppMinimal _ (And fs) = foldr1 (\a b -> a+++", "+++b) $ map (ppMinimal True) fs ppMinimal p (Or fs) = wrap $ foldr1 (\a b -> a+++" | "+++b) $ map (ppMinimal False) fs where wrap | p = parens | otherwise = id instancesBit = ppInstances links instances nm unicode qual ppClassDecl _ _ _ _ _ _ _ _ _ _ _ = error "declaration type not supported by ppShortClassDecl" ppInstances :: LinksInfo -> [DocInstance DocName] -> DocName -> Unicode -> Qualification -> Html ppInstances links instances baseName unicode qual = subInstances qual instName links True baseName (map instDecl instances) -- force Splice = True to use line URLs where instName = getOccString $ getName baseName instDecl :: DocInstance DocName -> (SubDecl,SrcSpan) instDecl (L l inst, maybeDoc) = ((instHead inst, maybeDoc, []),l) instHead (n, ks, ts, ClassInst cs) = ppContextNoLocs cs unicode qual <+> ppAppNameTypes n ks ts unicode qual instHead (n, ks, ts, TypeInst rhs) = keyword "type" <+> ppAppNameTypes n ks ts unicode qual <+> maybe noHtml (\t -> equals <+> ppType unicode qual t) rhs instHead (n, ks, ts, DataInst dd) = keyword "data" <+> ppAppNameTypes n ks ts unicode qual <+> ppShortDataDecl False True dd unicode qual lookupAnySubdoc :: Eq id1 => id1 -> [(id1, DocForDecl id2)] -> DocForDecl id2 lookupAnySubdoc n = fromMaybe noDocForDecl . lookup n ------------------------------------------------------------------------------- -- * Data & newtype declarations ------------------------------------------------------------------------------- -- TODO: print contexts ppShortDataDecl :: Bool -> Bool -> TyClDecl DocName -> Unicode -> Qualification -> Html ppShortDataDecl summary dataInst dataDecl unicode qual | [] <- cons = dataHeader | [lcon] <- cons, ResTyH98 <- resTy, (cHead,cBody,cFoot) <- ppShortConstrParts summary dataInst (unLoc lcon) unicode qual = (dataHeader <+> equals <+> cHead) +++ cBody +++ cFoot | ResTyH98 <- resTy = dataHeader +++ shortSubDecls dataInst (zipWith doConstr ('=':repeat '|') cons) | otherwise = (dataHeader <+> keyword "where") +++ shortSubDecls dataInst (map doGADTConstr cons) where dataHeader | dataInst = noHtml | otherwise = ppDataHeader summary dataDecl unicode qual doConstr c con = toHtml [c] <+> ppShortConstr summary (unLoc con) unicode qual doGADTConstr con = ppShortConstr summary (unLoc con) unicode qual cons = dd_cons (tcdDataDefn dataDecl) resTy = (con_res . unLoc . head) cons ppDataDecl :: Bool -> LinksInfo -> [DocInstance DocName] -> [(DocName, Fixity)] -> [(DocName, DocForDecl DocName)] -> SrcSpan -> Documentation DocName -> TyClDecl DocName -> Splice -> Unicode -> Qualification -> Html ppDataDecl summary links instances fixities subdocs loc doc dataDecl splice unicode qual | summary = ppShortDataDecl summary False dataDecl unicode qual | otherwise = header_ +++ docSection Nothing qual doc +++ constrBit +++ instancesBit where docname = tcdName dataDecl cons = dd_cons (tcdDataDefn dataDecl) resTy = (con_res . unLoc . head) cons header_ = topDeclElem links loc splice [docname] $ ppDataHeader summary dataDecl unicode qual <+> whereBit <+> fix fix = ppFixities (filter (\(n,_) -> n == docname) fixities) qual whereBit | null cons = noHtml | otherwise = case resTy of ResTyGADT _ _ -> keyword "where" _ -> noHtml constrBit = subConstructors qual [ ppSideBySideConstr subdocs subfixs unicode qual c | c <- cons , let subfixs = filter (\(n,_) -> any (\cn -> cn == n) (map unLoc (con_names (unLoc c)))) fixities ] instancesBit = ppInstances links instances docname unicode qual ppShortConstr :: Bool -> ConDecl DocName -> Unicode -> Qualification -> Html ppShortConstr summary con unicode qual = cHead <+> cBody <+> cFoot where (cHead,cBody,cFoot) = ppShortConstrParts summary False con unicode qual -- returns three pieces: header, body, footer so that header & footer can be -- incorporated into the declaration ppShortConstrParts :: Bool -> Bool -> ConDecl DocName -> Unicode -> Qualification -> (Html, Html, Html) ppShortConstrParts summary dataInst con unicode qual = case con_res con of ResTyH98 -> case con_details con of PrefixCon args -> (header_ unicode qual +++ hsep (ppOcc : map (ppLParendType unicode qual) args), noHtml, noHtml) RecCon (L _ fields) -> (header_ unicode qual +++ ppOcc <+> char '{', doRecordFields fields, char '}') InfixCon arg1 arg2 -> (header_ unicode qual +++ hsep [ppLParendType unicode qual arg1, ppOccInfix, ppLParendType unicode qual arg2], noHtml, noHtml) ResTyGADT _ resTy -> case con_details con of -- prefix & infix could use hsConDeclArgTys if it seemed to -- simplify the code. PrefixCon args -> (doGADTCon args resTy, noHtml, noHtml) -- display GADT records with the new syntax, -- Constr :: (Context) => { field :: a, field2 :: b } -> Ty (a, b) -- (except each field gets its own line in docs, to match -- non-GADT records) RecCon (L _ fields) -> (ppOcc <+> dcolon unicode <+> ppForAllCon forall_ ltvs lcontext unicode qual <+> char '{', doRecordFields fields, char '}' <+> arrow unicode <+> ppLType unicode qual resTy) InfixCon arg1 arg2 -> (doGADTCon [arg1, arg2] resTy, noHtml, noHtml) where doRecordFields fields = shortSubDecls dataInst (map (ppShortField summary unicode qual) (map unLoc fields)) doGADTCon args resTy = ppOcc <+> dcolon unicode <+> hsep [ ppForAllCon forall_ ltvs lcontext unicode qual, ppLType unicode qual (foldr mkFunTy resTy args) ] header_ = ppConstrHdr forall_ tyVars context occ = map (nameOccName . getName . unLoc) $ con_names con ppOcc = case occ of [one] -> ppBinder summary one _ -> hsep (punctuate comma (map (ppBinder summary) occ)) ppOccInfix = case occ of [one] -> ppBinderInfix summary one _ -> hsep (punctuate comma (map (ppBinderInfix summary) occ)) ltvs = con_qvars con tyVars = tyvarNames ltvs lcontext = con_cxt con context = unLoc (con_cxt con) forall_ = con_explicit con mkFunTy a b = noLoc (HsFunTy a b) -- ppConstrHdr is for (non-GADT) existentials constructors' syntax ppConstrHdr :: HsExplicitFlag -> [Name] -> HsContext DocName -> Unicode -> Qualification -> Html ppConstrHdr forall_ tvs ctxt unicode qual = (if null tvs then noHtml else ppForall) +++ (if null ctxt then noHtml else ppContextNoArrow ctxt unicode qual <+> darrow unicode +++ toHtml " ") where ppForall = case forall_ of Explicit -> forallSymbol unicode <+> hsep (map (ppName Prefix) tvs) <+> toHtml ". " Qualified -> noHtml Implicit -> noHtml ppSideBySideConstr :: [(DocName, DocForDecl DocName)] -> [(DocName, Fixity)] -> Unicode -> Qualification -> LConDecl DocName -> SubDecl ppSideBySideConstr subdocs fixities unicode qual (L _ con) = (decl, mbDoc, fieldPart) where decl = case con_res con of ResTyH98 -> case con_details con of PrefixCon args -> hsep ((header_ +++ ppOcc) : map (ppLParendType unicode qual) args) <+> fixity RecCon _ -> header_ +++ ppOcc <+> fixity InfixCon arg1 arg2 -> hsep [header_ +++ ppLParendType unicode qual arg1, ppOccInfix, ppLParendType unicode qual arg2] <+> fixity ResTyGADT _ resTy -> case con_details con of -- prefix & infix could also use hsConDeclArgTys if it seemed to -- simplify the code. PrefixCon args -> doGADTCon args resTy cd@(RecCon _) -> doGADTCon (hsConDeclArgTys cd) resTy InfixCon arg1 arg2 -> doGADTCon [arg1, arg2] resTy fieldPart = case con_details con of RecCon (L _ fields) -> [doRecordFields fields] _ -> [] doRecordFields fields = subFields qual (map (ppSideBySideField subdocs unicode qual) (map unLoc fields)) doGADTCon :: [LHsType DocName] -> Located (HsType DocName) -> Html doGADTCon args resTy = ppOcc <+> dcolon unicode <+> hsep [ppForAllCon forall_ ltvs (con_cxt con) unicode qual, ppLType unicode qual (foldr mkFunTy resTy args) ] <+> fixity fixity = ppFixities fixities qual header_ = ppConstrHdr forall_ tyVars context unicode qual occ = map (nameOccName . getName . unLoc) $ con_names con ppOcc = case occ of [one] -> ppBinder False one _ -> hsep (punctuate comma (map (ppBinder False) occ)) ppOccInfix = case occ of [one] -> ppBinderInfix False one _ -> hsep (punctuate comma (map (ppBinderInfix False) occ)) ltvs = con_qvars con tyVars = tyvarNames (con_qvars con) context = unLoc (con_cxt con) forall_ = con_explicit con -- don't use "con_doc con", in case it's reconstructed from a .hi file, -- or also because we want Haddock to do the doc-parsing, not GHC. mbDoc = lookup (unLoc $ head $ con_names con) subdocs >>= combineDocumentation . fst mkFunTy a b = noLoc (HsFunTy a b) ppSideBySideField :: [(DocName, DocForDecl DocName)] -> Unicode -> Qualification -> ConDeclField DocName -> SubDecl ppSideBySideField subdocs unicode qual (ConDeclField names ltype _) = (hsep (punctuate comma (map ((ppBinder False) . nameOccName . getName . unL) names)) <+> dcolon unicode <+> ppLType unicode qual ltype, mbDoc, []) where -- don't use cd_fld_doc for same reason we don't use con_doc above -- Where there is more than one name, they all have the same documentation mbDoc = lookup (unL $ head names) subdocs >>= combineDocumentation . fst ppShortField :: Bool -> Unicode -> Qualification -> ConDeclField DocName -> Html ppShortField summary unicode qual (ConDeclField names ltype _) = hsep (punctuate comma (map ((ppBinder summary) . nameOccName . getName . unL) names)) <+> dcolon unicode <+> ppLType unicode qual ltype -- | Print the LHS of a data\/newtype declaration. -- Currently doesn't handle 'data instance' decls or kind signatures ppDataHeader :: Bool -> TyClDecl DocName -> Unicode -> Qualification -> Html ppDataHeader summary decl@(DataDecl { tcdDataDefn = HsDataDefn { dd_ND = nd , dd_ctxt = ctxt , dd_kindSig = ks } }) unicode qual = -- newtype or data (case nd of { NewType -> keyword "newtype"; DataType -> keyword "data" }) <+> -- context ppLContext ctxt unicode qual <+> -- T a b c ..., or a :+: b ppDataBinderWithVars summary decl <+> case ks of Nothing -> mempty Just (L _ x) -> dcolon unicode <+> ppKind unicode qual x ppDataHeader _ _ _ _ = error "ppDataHeader: illegal argument" -------------------------------------------------------------------------------- -- * Types and contexts -------------------------------------------------------------------------------- ppBang :: HsBang -> Html ppBang HsNoBang = noHtml ppBang _ = toHtml "!" -- Unpacked args is an implementation detail, -- so we just show the strictness annotation tupleParens :: HsTupleSort -> [Html] -> Html tupleParens HsUnboxedTuple = ubxParenList tupleParens _ = parenList -------------------------------------------------------------------------------- -- * Rendering of HsType -------------------------------------------------------------------------------- pREC_TOP, pREC_CTX, pREC_FUN, pREC_OP, pREC_CON :: Int pREC_TOP = 0 :: Int -- type in ParseIface.y in GHC pREC_CTX = 1 :: Int -- Used for single contexts, eg. ctx => type -- (as opposed to (ctx1, ctx2) => type) pREC_FUN = 2 :: Int -- btype in ParseIface.y in GHC -- Used for LH arg of (->) pREC_OP = 3 :: Int -- Used for arg of any infix operator -- (we don't keep their fixities around) pREC_CON = 4 :: Int -- Used for arg of type applicn: -- always parenthesise unless atomic maybeParen :: Int -- Precedence of context -> Int -- Precedence of top-level operator -> Html -> Html -- Wrap in parens if (ctxt >= op) maybeParen ctxt_prec op_prec p | ctxt_prec >= op_prec = parens p | otherwise = p ppLType, ppLParendType, ppLFunLhType :: Unicode -> Qualification -> Located (HsType DocName) -> Html ppLType unicode qual y = ppType unicode qual (unLoc y) ppLParendType unicode qual y = ppParendType unicode qual (unLoc y) ppLFunLhType unicode qual y = ppFunLhType unicode qual (unLoc y) ppType, ppCtxType, ppParendType, ppFunLhType :: Unicode -> Qualification -> HsType DocName -> Html ppType unicode qual ty = ppr_mono_ty pREC_TOP ty unicode qual ppCtxType unicode qual ty = ppr_mono_ty pREC_CTX ty unicode qual ppParendType unicode qual ty = ppr_mono_ty pREC_CON ty unicode qual ppFunLhType unicode qual ty = ppr_mono_ty pREC_FUN ty unicode qual ppLKind :: Unicode -> Qualification -> LHsKind DocName -> Html ppLKind unicode qual y = ppKind unicode qual (unLoc y) ppKind :: Unicode -> Qualification -> HsKind DocName -> Html ppKind unicode qual ki = ppr_mono_ty pREC_TOP ki unicode qual -- Drop top-level for-all type variables in user style -- since they are implicit in Haskell ppForAllCon :: HsExplicitFlag -> LHsTyVarBndrs DocName -> Located (HsContext DocName) -> Unicode -> Qualification -> Html ppForAllCon expl tvs cxt unicode qual = forall_part <+> ppLContext cxt unicode qual where forall_part = ppLTyVarBndrs expl tvs unicode qual ppLTyVarBndrs :: HsExplicitFlag -> LHsTyVarBndrs DocName -> Unicode -> Qualification -> Html ppLTyVarBndrs expl tvs unicode _qual | show_forall = hsep (forallSymbol unicode : ppTyVars tvs) +++ dot | otherwise = noHtml where show_forall = not (null (hsQTvBndrs tvs)) && is_explicit is_explicit = case expl of {Explicit -> True; Implicit -> False; Qualified -> False} ppr_mono_lty :: Int -> LHsType DocName -> Unicode -> Qualification -> Html ppr_mono_lty ctxt_prec ty = ppr_mono_ty ctxt_prec (unLoc ty) ppr_mono_ty :: Int -> HsType DocName -> Unicode -> Qualification -> Html ppr_mono_ty ctxt_prec (HsForAllTy expl extra tvs ctxt ty) unicode qual = maybeParen ctxt_prec pREC_FUN $ ppForAllCon expl tvs ctxt' unicode qual <+> ppr_mono_lty pREC_TOP ty unicode qual where ctxt' = case extra of Just loc -> (++ [L loc HsWildcardTy]) `fmap` ctxt Nothing -> ctxt -- UnicodeSyntax alternatives ppr_mono_ty _ (HsTyVar name) True _ | getOccString (getName name) == "*" = toHtml "★" | getOccString (getName name) == "(->)" = toHtml "(→)" ppr_mono_ty _ (HsBangTy b ty) u q = ppBang b +++ ppLParendType u q ty ppr_mono_ty _ (HsTyVar name) _ q = ppDocName q Prefix True name ppr_mono_ty ctxt_prec (HsFunTy ty1 ty2) u q = ppr_fun_ty ctxt_prec ty1 ty2 u q ppr_mono_ty _ (HsTupleTy con tys) u q = tupleParens con (map (ppLType u q) tys) ppr_mono_ty _ (HsKindSig ty kind) u q = parens (ppr_mono_lty pREC_TOP ty u q <+> dcolon u <+> ppLKind u q kind) ppr_mono_ty _ (HsListTy ty) u q = brackets (ppr_mono_lty pREC_TOP ty u q) ppr_mono_ty _ (HsPArrTy ty) u q = pabrackets (ppr_mono_lty pREC_TOP ty u q) ppr_mono_ty ctxt_prec (HsIParamTy n ty) u q = maybeParen ctxt_prec pREC_CTX $ ppIPName n <+> dcolon u <+> ppr_mono_lty pREC_TOP ty u q ppr_mono_ty _ (HsSpliceTy {}) _ _ = error "ppr_mono_ty HsSpliceTy" ppr_mono_ty _ (HsQuasiQuoteTy {}) _ _ = error "ppr_mono_ty HsQuasiQuoteTy" ppr_mono_ty _ (HsRecTy {}) _ _ = error "ppr_mono_ty HsRecTy" ppr_mono_ty _ (HsCoreTy {}) _ _ = error "ppr_mono_ty HsCoreTy" ppr_mono_ty _ (HsExplicitListTy _ tys) u q = quote $ brackets $ hsep $ punctuate comma $ map (ppLType u q) tys ppr_mono_ty _ (HsExplicitTupleTy _ tys) u q = quote $ parenList $ map (ppLType u q) tys ppr_mono_ty _ (HsWrapTy {}) _ _ = error "ppr_mono_ty HsWrapTy" ppr_mono_ty ctxt_prec (HsEqTy ty1 ty2) unicode qual = maybeParen ctxt_prec pREC_CTX $ ppr_mono_lty pREC_OP ty1 unicode qual <+> char '~' <+> ppr_mono_lty pREC_OP ty2 unicode qual ppr_mono_ty ctxt_prec (HsAppTy fun_ty arg_ty) unicode qual = maybeParen ctxt_prec pREC_CON $ hsep [ppr_mono_lty pREC_FUN fun_ty unicode qual, ppr_mono_lty pREC_CON arg_ty unicode qual] ppr_mono_ty ctxt_prec (HsOpTy ty1 (_, op) ty2) unicode qual = maybeParen ctxt_prec pREC_FUN $ ppr_mono_lty pREC_OP ty1 unicode qual <+> ppr_op <+> ppr_mono_lty pREC_OP ty2 unicode qual where ppr_op = ppLDocName qual Infix op ppr_mono_ty ctxt_prec (HsParTy ty) unicode qual -- = parens (ppr_mono_lty pREC_TOP ty) = ppr_mono_lty ctxt_prec ty unicode qual ppr_mono_ty ctxt_prec (HsDocTy ty _) unicode qual = ppr_mono_lty ctxt_prec ty unicode qual ppr_mono_ty _ HsWildcardTy _ _ = char '_' ppr_mono_ty _ (HsNamedWildcardTy name) _ q = ppDocName q Prefix True name ppr_mono_ty _ (HsTyLit n) _ _ = ppr_tylit n ppr_tylit :: HsTyLit -> Html ppr_tylit (HsNumTy _ n) = toHtml (show n) ppr_tylit (HsStrTy _ s) = toHtml (show s) ppr_fun_ty :: Int -> LHsType DocName -> LHsType DocName -> Unicode -> Qualification -> Html ppr_fun_ty ctxt_prec ty1 ty2 unicode qual = let p1 = ppr_mono_lty pREC_FUN ty1 unicode qual p2 = ppr_mono_lty pREC_TOP ty2 unicode qual in maybeParen ctxt_prec pREC_FUN $ hsep [p1, arrow unicode <+> p2]
DavidAlphaFox/ghc
utils/haddock/haddock-api/src/Haddock/Backends/Xhtml/Decl.hs
bsd-3-clause
39,215
0
22
10,327
11,664
5,910
5,754
613
9
{-# LANGUAGE BangPatterns, CPP, MagicHash #-} #if __GLASGOW_HASKELL__ >= 701 {-# LANGUAGE Trustworthy #-} #endif ----------------------------------------------------------------------------- -- | -- Module : Data.Binary.Builder.Base -- Copyright : Lennart Kolmodin, Ross Paterson -- License : BSD3-style (see LICENSE) -- -- Maintainer : Lennart Kolmodin <[email protected]> -- Stability : experimental -- Portability : portable to Hugs and GHC -- -- A module exporting types and functions that are shared by -- 'Data.Binary.Builder' and 'Data.Binary.Builder.Internal'. -- ----------------------------------------------------------------------------- #if defined(__GLASGOW_HASKELL__) && !defined(__HADDOCK__) #include "MachDeps.h" #endif module Data.Binary.Builder.Base ( -- * The Builder type Builder , toLazyByteString -- * Constructing Builders , empty , singleton , append , fromByteString -- :: S.ByteString -> Builder , fromLazyByteString -- :: L.ByteString -> Builder -- * Flushing the buffer state , flush -- * Derived Builders -- ** Big-endian writes , putWord16be -- :: Word16 -> Builder , putWord32be -- :: Word32 -> Builder , putWord64be -- :: Word64 -> Builder -- ** Little-endian writes , putWord16le -- :: Word16 -> Builder , putWord32le -- :: Word32 -> Builder , putWord64le -- :: Word64 -> Builder -- ** Host-endian, unaligned writes , putWordhost -- :: Word -> Builder , putWord16host -- :: Word16 -> Builder , putWord32host -- :: Word32 -> Builder , putWord64host -- :: Word64 -> Builder -- ** Unicode , putCharUtf8 -- * Low-level construction of Builders , writeN , writeAtMost ) where import qualified Data.ByteString as S import qualified Data.ByteString.Lazy as L import Data.Monoid import Data.Word import Foreign import System.IO.Unsafe as IO ( unsafePerformIO ) #ifdef BYTESTRING_IN_BASE import Data.ByteString.Base (inlinePerformIO) import qualified Data.ByteString.Base as S import qualified Data.ByteString.Lazy.Base as L #else import Data.ByteString.Internal (inlinePerformIO) import qualified Data.ByteString.Internal as S import qualified Data.ByteString.Lazy.Internal as L #endif #if defined(__GLASGOW_HASKELL__) && !defined(__HADDOCK__) import GHC.Base (ord,Int(..),uncheckedShiftRL#) import GHC.Word (Word32(..),Word16(..),Word64(..)) # if WORD_SIZE_IN_BITS < 64 import GHC.Word (uncheckedShiftRL64#) # endif #endif ------------------------------------------------------------------------ -- | A 'Builder' is an efficient way to build lazy 'L.ByteString's. -- There are several functions for constructing 'Builder's, but only one -- to inspect them: to extract any data, you have to turn them into lazy -- 'L.ByteString's using 'toLazyByteString'. -- -- Internally, a 'Builder' constructs a lazy 'L.Bytestring' by filling byte -- arrays piece by piece. As each buffer is filled, it is \'popped\' -- off, to become a new chunk of the resulting lazy 'L.ByteString'. -- All this is hidden from the user of the 'Builder'. newtype Builder = Builder { runBuilder :: (Buffer -> IO L.ByteString) -> Buffer -> IO L.ByteString } instance Monoid Builder where mempty = empty {-# INLINE mempty #-} mappend = append {-# INLINE mappend #-} mconcat = foldr mappend mempty {-# INLINE mconcat #-} ------------------------------------------------------------------------ -- | /O(1)./ The empty Builder, satisfying -- -- * @'toLazyByteString' 'empty' = 'L.empty'@ -- empty :: Builder empty = Builder (\ k b -> k b) {-# INLINE empty #-} -- | /O(1)./ A Builder taking a single byte, satisfying -- -- * @'toLazyByteString' ('singleton' b) = 'L.singleton' b@ -- singleton :: Word8 -> Builder singleton = writeN 1 . flip poke {-# INLINE singleton #-} ------------------------------------------------------------------------ -- | /O(1)./ The concatenation of two Builders, an associative operation -- with identity 'empty', satisfying -- -- * @'toLazyByteString' ('append' x y) = 'L.append' ('toLazyByteString' x) ('toLazyByteString' y)@ -- append :: Builder -> Builder -> Builder append (Builder f) (Builder g) = Builder (f . g) {-# INLINE [0] append #-} -- | /O(1)./ A Builder taking a 'S.ByteString', satisfying -- -- * @'toLazyByteString' ('fromByteString' bs) = 'L.fromChunks' [bs]@ -- fromByteString :: S.ByteString -> Builder fromByteString bs | S.null bs = empty | otherwise = flush `append` mapBuilder (L.Chunk bs) {-# INLINE fromByteString #-} -- | /O(1)./ A Builder taking a lazy 'L.ByteString', satisfying -- -- * @'toLazyByteString' ('fromLazyByteString' bs) = bs@ -- fromLazyByteString :: L.ByteString -> Builder fromLazyByteString bss = flush `append` mapBuilder (bss `L.append`) {-# INLINE fromLazyByteString #-} ------------------------------------------------------------------------ -- Our internal buffer type data Buffer = Buffer {-# UNPACK #-} !(ForeignPtr Word8) {-# UNPACK #-} !Int -- offset {-# UNPACK #-} !Int -- used bytes {-# UNPACK #-} !Int -- length left ------------------------------------------------------------------------ -- | /O(n)./ Extract a lazy 'L.ByteString' from a 'Builder'. -- The construction work takes place if and when the relevant part of -- the lazy 'L.ByteString' is demanded. -- toLazyByteString :: Builder -> L.ByteString toLazyByteString m = IO.unsafePerformIO $ do buf <- newBuffer defaultSize runBuilder (m `append` flush) (const (return L.Empty)) buf {-# INLINE toLazyByteString #-} -- | /O(1)./ Pop the 'S.ByteString' we have constructed so far, if any, -- yielding a new chunk in the result lazy 'L.ByteString'. flush :: Builder flush = Builder $ \ k buf@(Buffer p o u l) -> if u == 0 -- Invariant (from Data.ByteString.Lazy) then k buf else let !b = Buffer p (o+u) 0 l !bs = S.PS p o u in return $! L.Chunk bs (inlinePerformIO (k b)) ------------------------------------------------------------------------ -- -- copied from Data.ByteString.Lazy -- defaultSize :: Int defaultSize = 32 * k - overhead where k = 1024 overhead = 2 * sizeOf (undefined :: Int) ------------------------------------------------------------------------ -- | Sequence an IO operation on the buffer withBuffer :: (Buffer -> IO Buffer) -> Builder withBuffer f = Builder $ \ k buf -> f buf >>= k {-# INLINE withBuffer #-} -- | Get the size of the buffer withSize :: (Int -> Builder) -> Builder withSize f = Builder $ \ k buf@(Buffer _ _ _ l) -> runBuilder (f l) k buf -- | Map the resulting list of bytestrings. mapBuilder :: (L.ByteString -> L.ByteString) -> Builder mapBuilder f = Builder (fmap f .) ------------------------------------------------------------------------ -- | Ensure that there are at least @n@ many bytes available. ensureFree :: Int -> Builder ensureFree n = n `seq` withSize $ \ l -> if n <= l then empty else flush `append` withBuffer (const (newBuffer (max n defaultSize))) {-# INLINE [0] ensureFree #-} -- | Ensure that @n@ bytes are available, and then use @f@ to write at -- most @n@ bytes into memory. @f@ must return the actual number of -- bytes written. writeAtMost :: Int -> (Ptr Word8 -> IO Int) -> Builder writeAtMost n f = ensureFree n `append` withBuffer (writeBuffer f) {-# INLINE [0] writeAtMost #-} -- | Ensure that @n@ bytes are available, and then use @f@ to write -- exactly @n@ bytes into memory. writeN :: Int -> (Ptr Word8 -> IO ()) -> Builder writeN n f = writeAtMost n (\ p -> f p >> return n) {-# INLINE writeN #-} writeBuffer :: (Ptr Word8 -> IO Int) -> Buffer -> IO Buffer writeBuffer f (Buffer fp o u l) = do n <- withForeignPtr fp (\p -> f (p `plusPtr` (o+u))) return $! Buffer fp o (u+n) (l-n) {-# INLINE writeBuffer #-} newBuffer :: Int -> IO Buffer newBuffer size = do fp <- S.mallocByteString size return $! Buffer fp 0 0 size {-# INLINE newBuffer #-} ------------------------------------------------------------------------ -- -- We rely on the fromIntegral to do the right masking for us. -- The inlining here is critical, and can be worth 4x performance -- -- | Write a Word16 in big endian format putWord16be :: Word16 -> Builder putWord16be w = writeN 2 $ \p -> do poke p (fromIntegral (shiftr_w16 w 8) :: Word8) poke (p `plusPtr` 1) (fromIntegral (w) :: Word8) {-# INLINE putWord16be #-} -- | Write a Word16 in little endian format putWord16le :: Word16 -> Builder putWord16le w = writeN 2 $ \p -> do poke p (fromIntegral (w) :: Word8) poke (p `plusPtr` 1) (fromIntegral (shiftr_w16 w 8) :: Word8) {-# INLINE putWord16le #-} -- putWord16le w16 = writeN 2 (\p -> poke (castPtr p) w16) -- | Write a Word32 in big endian format putWord32be :: Word32 -> Builder putWord32be w = writeN 4 $ \p -> do poke p (fromIntegral (shiftr_w32 w 24) :: Word8) poke (p `plusPtr` 1) (fromIntegral (shiftr_w32 w 16) :: Word8) poke (p `plusPtr` 2) (fromIntegral (shiftr_w32 w 8) :: Word8) poke (p `plusPtr` 3) (fromIntegral (w) :: Word8) {-# INLINE putWord32be #-} -- -- a data type to tag Put/Check. writes construct these which are then -- inlined and flattened. matching Checks will be more robust with rules. -- -- | Write a Word32 in little endian format putWord32le :: Word32 -> Builder putWord32le w = writeN 4 $ \p -> do poke p (fromIntegral (w) :: Word8) poke (p `plusPtr` 1) (fromIntegral (shiftr_w32 w 8) :: Word8) poke (p `plusPtr` 2) (fromIntegral (shiftr_w32 w 16) :: Word8) poke (p `plusPtr` 3) (fromIntegral (shiftr_w32 w 24) :: Word8) {-# INLINE putWord32le #-} -- on a little endian machine: -- putWord32le w32 = writeN 4 (\p -> poke (castPtr p) w32) -- | Write a Word64 in big endian format putWord64be :: Word64 -> Builder #if WORD_SIZE_IN_BITS < 64 -- -- To avoid expensive 64 bit shifts on 32 bit machines, we cast to -- Word32, and write that -- putWord64be w = let a = fromIntegral (shiftr_w64 w 32) :: Word32 b = fromIntegral w :: Word32 in writeN 8 $ \p -> do poke p (fromIntegral (shiftr_w32 a 24) :: Word8) poke (p `plusPtr` 1) (fromIntegral (shiftr_w32 a 16) :: Word8) poke (p `plusPtr` 2) (fromIntegral (shiftr_w32 a 8) :: Word8) poke (p `plusPtr` 3) (fromIntegral (a) :: Word8) poke (p `plusPtr` 4) (fromIntegral (shiftr_w32 b 24) :: Word8) poke (p `plusPtr` 5) (fromIntegral (shiftr_w32 b 16) :: Word8) poke (p `plusPtr` 6) (fromIntegral (shiftr_w32 b 8) :: Word8) poke (p `plusPtr` 7) (fromIntegral (b) :: Word8) #else putWord64be w = writeN 8 $ \p -> do poke p (fromIntegral (shiftr_w64 w 56) :: Word8) poke (p `plusPtr` 1) (fromIntegral (shiftr_w64 w 48) :: Word8) poke (p `plusPtr` 2) (fromIntegral (shiftr_w64 w 40) :: Word8) poke (p `plusPtr` 3) (fromIntegral (shiftr_w64 w 32) :: Word8) poke (p `plusPtr` 4) (fromIntegral (shiftr_w64 w 24) :: Word8) poke (p `plusPtr` 5) (fromIntegral (shiftr_w64 w 16) :: Word8) poke (p `plusPtr` 6) (fromIntegral (shiftr_w64 w 8) :: Word8) poke (p `plusPtr` 7) (fromIntegral (w) :: Word8) #endif {-# INLINE putWord64be #-} -- | Write a Word64 in little endian format putWord64le :: Word64 -> Builder #if WORD_SIZE_IN_BITS < 64 putWord64le w = let b = fromIntegral (shiftr_w64 w 32) :: Word32 a = fromIntegral w :: Word32 in writeN 8 $ \p -> do poke (p) (fromIntegral (a) :: Word8) poke (p `plusPtr` 1) (fromIntegral (shiftr_w32 a 8) :: Word8) poke (p `plusPtr` 2) (fromIntegral (shiftr_w32 a 16) :: Word8) poke (p `plusPtr` 3) (fromIntegral (shiftr_w32 a 24) :: Word8) poke (p `plusPtr` 4) (fromIntegral (b) :: Word8) poke (p `plusPtr` 5) (fromIntegral (shiftr_w32 b 8) :: Word8) poke (p `plusPtr` 6) (fromIntegral (shiftr_w32 b 16) :: Word8) poke (p `plusPtr` 7) (fromIntegral (shiftr_w32 b 24) :: Word8) #else putWord64le w = writeN 8 $ \p -> do poke p (fromIntegral (w) :: Word8) poke (p `plusPtr` 1) (fromIntegral (shiftr_w64 w 8) :: Word8) poke (p `plusPtr` 2) (fromIntegral (shiftr_w64 w 16) :: Word8) poke (p `plusPtr` 3) (fromIntegral (shiftr_w64 w 24) :: Word8) poke (p `plusPtr` 4) (fromIntegral (shiftr_w64 w 32) :: Word8) poke (p `plusPtr` 5) (fromIntegral (shiftr_w64 w 40) :: Word8) poke (p `plusPtr` 6) (fromIntegral (shiftr_w64 w 48) :: Word8) poke (p `plusPtr` 7) (fromIntegral (shiftr_w64 w 56) :: Word8) #endif {-# INLINE putWord64le #-} -- on a little endian machine: -- putWord64le w64 = writeN 8 (\p -> poke (castPtr p) w64) ------------------------------------------------------------------------ -- Unaligned, word size ops -- | /O(1)./ A Builder taking a single native machine word. The word is -- written in host order, host endian form, for the machine you're on. -- On a 64 bit machine the Word is an 8 byte value, on a 32 bit machine, -- 4 bytes. Values written this way are not portable to -- different endian or word sized machines, without conversion. -- putWordhost :: Word -> Builder putWordhost w = writeN (sizeOf (undefined :: Word)) (\p -> poke (castPtr p) w) {-# INLINE putWordhost #-} -- | Write a Word16 in native host order and host endianness. -- 2 bytes will be written, unaligned. putWord16host :: Word16 -> Builder putWord16host w16 = writeN (sizeOf (undefined :: Word16)) (\p -> poke (castPtr p) w16) {-# INLINE putWord16host #-} -- | Write a Word32 in native host order and host endianness. -- 4 bytes will be written, unaligned. putWord32host :: Word32 -> Builder putWord32host w32 = writeN (sizeOf (undefined :: Word32)) (\p -> poke (castPtr p) w32) {-# INLINE putWord32host #-} -- | Write a Word64 in native host order. -- On a 32 bit machine we write two host order Word32s, in big endian form. -- 8 bytes will be written, unaligned. putWord64host :: Word64 -> Builder putWord64host w = writeN (sizeOf (undefined :: Word64)) (\p -> poke (castPtr p) w) {-# INLINE putWord64host #-} ------------------------------------------------------------------------ -- Unicode -- Code lifted from the text package by Bryan O'Sullivan. -- | Write a character using UTF-8 encoding. putCharUtf8 :: Char -> Builder putCharUtf8 x = writeAtMost 4 $ \ p -> case undefined of _ | n <= 0x7F -> poke p c >> return 1 | n <= 0x07FF -> do poke p a2 poke (p `plusPtr` 1) b2 return 2 | n <= 0xFFFF -> do poke p a3 poke (p `plusPtr` 1) b3 poke (p `plusPtr` 2) c3 return 3 | otherwise -> do poke p a4 poke (p `plusPtr` 1) b4 poke (p `plusPtr` 2) c4 poke (p `plusPtr` 3) d4 return 4 where n = ord x c = fromIntegral n (a2,b2) = ord2 x (a3,b3,c3) = ord3 x (a4,b4,c4,d4) = ord4 x ord2 :: Char -> (Word8,Word8) ord2 c = (x1,x2) where n = ord c x1 = fromIntegral $ (n `shiftR` 6) + 0xC0 x2 = fromIntegral $ (n .&. 0x3F) + 0x80 ord3 :: Char -> (Word8,Word8,Word8) ord3 c = (x1,x2,x3) where n = ord c x1 = fromIntegral $ (n `shiftR` 12) + 0xE0 x2 = fromIntegral $ ((n `shiftR` 6) .&. 0x3F) + 0x80 x3 = fromIntegral $ (n .&. 0x3F) + 0x80 ord4 :: Char -> (Word8,Word8,Word8,Word8) ord4 c = (x1,x2,x3,x4) where n = ord c x1 = fromIntegral $ (n `shiftR` 18) + 0xF0 x2 = fromIntegral $ ((n `shiftR` 12) .&. 0x3F) + 0x80 x3 = fromIntegral $ ((n `shiftR` 6) .&. 0x3F) + 0x80 x4 = fromIntegral $ (n .&. 0x3F) + 0x80 ------------------------------------------------------------------------ -- Unchecked shifts {-# INLINE shiftr_w16 #-} shiftr_w16 :: Word16 -> Int -> Word16 {-# INLINE shiftr_w32 #-} shiftr_w32 :: Word32 -> Int -> Word32 {-# INLINE shiftr_w64 #-} shiftr_w64 :: Word64 -> Int -> Word64 #if defined(__GLASGOW_HASKELL__) && !defined(__HADDOCK__) shiftr_w16 (W16# w) (I# i) = W16# (w `uncheckedShiftRL#` i) shiftr_w32 (W32# w) (I# i) = W32# (w `uncheckedShiftRL#` i) # if WORD_SIZE_IN_BITS < 64 shiftr_w64 (W64# w) (I# i) = W64# (w `uncheckedShiftRL64#` i) # else shiftr_w64 (W64# w) (I# i) = W64# (w `uncheckedShiftRL#` i) # endif #else shiftr_w16 = shiftR shiftr_w32 = shiftR shiftr_w64 = shiftR #endif ------------------------------------------------------------------------ -- Some nice rules for Builder #if __GLASGOW_HASKELL__ >= 700 -- In versions of GHC prior to 7.0 these rules would make GHC believe -- that 'writeN' and 'ensureFree' are recursive and the rules wouldn't -- fire. {-# RULES "append/writeAtMost" forall a b (f::Ptr Word8 -> IO Int) (g::Ptr Word8 -> IO Int) ws. append (writeAtMost a f) (append (writeAtMost b g) ws) = append (writeAtMost (a+b) (\p -> f p >>= \n -> g (p `plusPtr` n) >>= \m -> let s = n+m in s `seq` return s)) ws "writeAtMost/writeAtMost" forall a b (f::Ptr Word8 -> IO Int) (g::Ptr Word8 -> IO Int). append (writeAtMost a f) (writeAtMost b g) = writeAtMost (a+b) (\p -> f p >>= \n -> g (p `plusPtr` n) >>= \m -> let s = n+m in s `seq` return s) "ensureFree/ensureFree" forall a b . append (ensureFree a) (ensureFree b) = ensureFree (max a b) "flush/flush" append flush flush = flush #-} #endif
fpco/binary
src/Data/Binary/Builder/Base.hs
bsd-3-clause
17,914
0
15
4,249
3,575
2,002
1,573
227
2
import Test.HUnit (Assertion, (@=?), runTestTT, Test(..), Counts(..)) import System.Exit (ExitCode(..), exitWith) import Series (digits, slices, largestProduct) exitProperly :: IO Counts -> IO () exitProperly m = do counts <- m exitWith $ if failures counts /= 0 || errors counts /= 0 then ExitFailure 1 else ExitSuccess testCase :: String -> Assertion -> Test testCase label assertion = TestLabel label (TestCase assertion) main :: IO () main = exitProperly $ runTestTT $ TestList [ TestList seriesTests ] -- Allow implementations that work with Integral to compile without warning ints :: [Int] -> [Int] ints = id int :: Int -> Int int = id seriesTests :: [Test] seriesTests = map TestCase [ ints [0..9] @=? digits ['0'..'9'] , ints [9,8..0] @=? digits ['9','8'..'0'] , ints [8,7..4] @=? digits ['8','7'..'4'] , ints [9, 3, 6, 9, 2, 3, 4, 6, 8] @=? digits "936923468" , map ints [[9, 8], [8, 2], [2, 7], [7, 3], [3, 4], [4, 6], [6, 3]] @=? slices 2 "98273463" , map ints [[9, 8, 2], [8, 2, 3], [2, 3, 4], [3, 4, 7]] @=? slices 3 "982347" , int 72 @=? largestProduct 2 "0123456789" , int 2 @=? largestProduct 2 "12" , int 9 @=? largestProduct 2 "19" , int 48 @=? largestProduct 2 "576802143" , int 504 @=? largestProduct 3 ['0'..'9'] , int 270 @=? largestProduct 3 "1027839564" , int 15120 @=? largestProduct 5 ['0'..'9'] , int 23520 @=? largestProduct 6 "73167176531330624919225119674426574742355349194934" , int 28350 @=? largestProduct 6 "52677741234314237566414902593461595376319419139427" , int 1 @=? largestProduct 0 "" -- unlike the Ruby implementation, no error is expected for too small input , int 1 @=? largestProduct 4 "123" -- edge case :) , int 0 @=? largestProduct 2 "00" ]
pminten/xhaskell
largest-series-product/largest-series-product_test.hs
mit
1,764
0
12
359
709
388
321
40
2
{-# LANGUAGE CPP #-} module TypeUtilsSpec (main, spec) where import Test.Hspec import TestUtils import qualified GHC.SYB.Utils as SYB import qualified GHC as GHC import qualified GhcMonad as GHC import qualified Name as GHC import qualified RdrName as GHC import qualified Module as GHC import Data.Maybe import Language.Haskell.GHC.ExactPrint import Language.Haskell.GHC.ExactPrint.Parsers import Language.Haskell.GHC.ExactPrint.Types import Language.Haskell.GHC.ExactPrint.Utils import Language.Haskell.Refact.Utils.GhcVersionSpecific import Language.Haskell.Refact.Utils.LocUtils import Language.Haskell.Refact.Utils.Monad import Language.Haskell.Refact.Utils.MonadFunctions import Language.Haskell.Refact.Utils.TypeUtils import Language.Haskell.Refact.Utils.Types import Language.Haskell.Refact.Utils.Utils import Language.Haskell.Refact.Utils.Variables import Data.List main :: IO () main = do hspec spec spec :: Spec spec = do -- ------------------------------------------------------------------- {- describe "findAllNameOccurences" $ do it "finds all occurrences of the given name in a syntax phrase" $ do t <- ct $ parsedFileGhc "./TypeUtils/S.hs" let renamed = tmRenamedSource t let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (4,5) parsed (showGhcQual n) `shouldBe` "x" let res = findAllNameOccurences n renamed (showGhcQual res) `shouldBe` "[x, x]" -- NOTE: does not get the x's in line 8 (showGhcQual $ map startEndLocGhc res) `shouldBe` "[((4, 5), (4, 6)), ((4, 17), (4, 18))]" -} -- ------------------------------------------------------------------- describe "locToName" $ do it "returns a GHC.Name for a given source location, if it falls anywhere in an identifier #1" $ do t <- ct $ parsedFileGhc "./TypeUtils/B.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just (res'@(GHC.L l _)) = locToRdrName (7,3) parsed n = rdrName2NamePure nm res' res = GHC.L l n showGhcQual l `shouldBe` "TypeUtils/B.hs:7:1-3" getLocatedStart res `shouldBe` (7,1) showGhcQual n `shouldBe` "TypeUtils.B.foo" -- --------------------------------- it "returns a GHC.Name for a given source location, if it falls anywhere in an identifier #2" $ do t <- ct $ parsedFileGhc "./TypeUtils/B.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just (res'@(GHC.L l _)) = locToRdrName (25,8) parsed n = rdrName2NamePure nm res' res = GHC.L l n showGhcQual n `shouldBe` "TypeUtils.B.bob" showGhcQual l `shouldBe` "TypeUtils/B.hs:25:7-9" getLocatedStart res `shouldBe` (25,7) -- --------------------------------- it "returns Nothing for a given source location, if it does not fall in an identifier" $ do t <- ct $ parsedFileGhc "TypeUtils/B.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let res = locToNameRdrPure nm (7,7) parsed (showGhcQual res) `shouldBe` "Nothing" -- --------------------------------- it "gets a short name too" $ do t <- ct $ parsedFileGhc "./Demote/WhereIn2.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just (res'@(GHC.L l _)) = locToRdrName (14,1) parsed n = rdrName2NamePure nm res' res = GHC.L l n showGhcQual n `shouldBe` "Demote.WhereIn2.sq" showGhcQual l `shouldBe` "Demote/WhereIn2.hs:14:1-2" getLocatedStart res `shouldBe` (14,1) -- --------------------------------- it "gets a type variable name" $ do t <- ct $ parsedFileGhc "./Renaming/ConstructorIn3.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just (res'@(GHC.L l _)) = locToRdrName (9,12) parsed n = rdrName2NamePure nm res' res = GHC.L l n showGhcQual n `shouldBe` "a" -- Note: loc does not line up due to multiple matches in FunBind showGhcQual l `shouldBe` "Renaming/ConstructorIn3.hs:9:12" getLocatedStart res `shouldBe` (9,12) -- --------------------------------- it "gets an instance class name" $ do t <- ct $ parsedFileGhc "./Renaming/ClassIn3.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just (res'@(GHC.L l _)) = locToRdrName (16,10) parsed n = rdrName2NamePure nm res' res = GHC.L l n showGhcQual n `shouldBe` "GHC.Classes.Eq" showGhcQual l `shouldBe` "Renaming/ClassIn3.hs:16:10-11" getLocatedStart res `shouldBe` (16,10) -- ------------------------------------------------------------------- describe "locToRdrName" $ do it "returns a GHC.RdrName for a given source location, if it falls anywhere in an identifier" $ do t <- ct $ parsedFileGhc "./Renaming/D5.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t let Just (res@(GHC.L l n)) = locToRdrName (20,1) parsed (show $ ss2span l) `shouldBe` "((20,1),(20,11))" getLocatedStart res `shouldBe` (20,1) showGhcQual n `shouldBe` "sumSquares" it "returns a GHC.RdrName for a source location, in a MatchGroup" $ do t <- ct $ parsedFileGhc "./LocToName.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t let Just (res@(GHC.L l n)) = locToRdrName (24,2) parsed showGhcQual n `shouldBe` "sumSquares" getLocatedStart res `shouldBe` (24,1) showGhcQual l `shouldBe` "LocToName.hs:24:1-10" -- ------------------------------------------------------------------- describe "getName" $ do it "gets a qualified Name at the top level" $ do t <- ct $ parsedFileGhc "./TypeUtils/B.hs" let renamed = tmRenamedSource t let Just n = getName "TypeUtils.B.foo'" renamed (showGhcQual n) `shouldBe` "TypeUtils.B.foo'" (showGhcQual $ GHC.getSrcSpan n) `shouldBe` "TypeUtils/B.hs:14:1-4" it "gets any instance of an unqualified Name" $ do t <- ct $ parsedFileGhc "./TypeUtils/B.hs" let renamed = tmRenamedSource t let Just n = getName "foo" renamed (showGhcQual n) `shouldBe` "foo" (showGhcQual $ GHC.getSrcSpan n) `shouldBe` "TypeUtils/B.hs:9:15-17" it "returns Nothing if the Name is not found" $ do t <- ct $ parsedFileGhc "./TypeUtils/B.hs" let renamed = tmRenamedSource t let res = getName "baz" renamed (showGhcQual res) `shouldBe` "Nothing" -- ------------------------------------------------------------------- describe "definingDeclsRdrNames" $ do it "returns [] if not found" $ do t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t let nm = initRdrNameMap t let Just n = locToNameRdrPure nm (16,6) parsed let decls = GHC.hsmodDecls $ GHC.unLoc parsed let res = definingDeclsRdrNames nm [n] decls False False showGhcQual res `shouldBe` "[]" -- --------------------------------- it "finds declarations at the top level" $ do t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t let nm = initRdrNameMap t let Just n = locToNameRdrPure nm (3,3) parsed let decls = GHC.hsmodDecls $ GHC.unLoc parsed let res = definingDeclsRdrNames nm [n] decls False False showGhcQual res `shouldBe` "[toplevel x = c * x]" -- --------------------------------- it "finds declarations not at the top level 1" $ do t <- ct $ parsedFileGhc "./LiftToToplevel/WhereIn6.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t let nm = initRdrNameMap t let Just n = locToNameRdrPure nm (13,29) parsed let decls = GHC.hsmodDecls $ GHC.unLoc parsed let res = definingDeclsRdrNames nm [n] decls False True showGhcQual n `shouldBe` "pow" showGhcQual res `shouldBe` "[pow = 2]" -- --------------------------------- it "finds declarations not at the top level 2" $ do t <- ct $ parsedFileGhc "./LiftToToplevel/LetIn1.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t let nm = initRdrNameMap t let Just n = locToNameRdrPure nm (11,22) parsed let decls = GHC.hsmodDecls $ GHC.unLoc parsed let res = definingDeclsRdrNames nm [n] decls False True showGhcQual n `shouldBe` "sq" showGhcQual res `shouldBe` "[sq 0 = 0\n sq z = z ^ pow]" -- --------------------------------- it "finds in a patbind" $ do t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t let nm = initRdrNameMap t let Just n = locToNameRdrPure nm (14,1) parsed let decls = GHC.hsmodDecls $ GHC.unLoc parsed let res = definingDeclsRdrNames nm [n] decls False False showGhcQual res `shouldBe` "[tup@(h, t)\n = head $ zip [1 .. 10] [3 .. ff]\n where\n ff :: Int\n ff = 15]" -- --------------------------------- it "finds recursively in sub-binds" $ do {- modInfo@((_, _, mod@(GHC.L l (GHC.HsModule name exps imps ds _ _))), toks) <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let res = definingDecls [(PN (mkRdrName "zz"))] ds False True showGhcQual res `shouldBe` "[zz n = n + 1]" -- TODO: Currently fails, will come back to it -} pending -- "Currently fails, will come back to it" -- --------------------------------- it "only finds recursively in sub-binds if asked" $ do {- modInfo@((_, _, mod@(GHC.L l (GHC.HsModule name exps imps ds _ _))), toks) <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let res = definingDecls [(PN (mkRdrName "zz"))] ds False False showGhcQual res `shouldBe` "[]" -} pending -- "Convert to definingDeclsNames" -- --------------------------------- it "finds a name declared in a RecCon data declaration" $ do t <- ct $ parsedFileGhc "./Renaming/Field1.hs" let comp = do parsed <- getRefactParsed decls <- liftT $ hsDecls parsed nm <- getRefactNameMap let Just n = locToNameRdrPure nm (5,18) parsed let rg = definingDeclsRdrNames nm [n] decls False False return (n,rg) -- ((bb,resg),_s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions ((nn,resg),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual nn) `shouldBe` "Field1.pointx" (showGhcQual resg) `shouldBe` "[data Point\n = Pt {pointx, pointy :: Float}\n deriving (Show)]" -- --------------------------------------- -- ------------------------------------------------------------------- {- describe "definingDeclsNames" $ do it "returns [] if not found" $ do t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let renamed = tmRenamedSource t let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (16,6) parsed let res = definingDeclsNames [n] (hsBinds renamed) False False showGhcQual res `shouldBe` "[]" it "finds declarations at the top level" $ do t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let renamed = tmRenamedSource t let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (3,3) parsed let res = definingDeclsNames [n] (hsBinds renamed) False False showGhcQual res `shouldBe` "[DupDef.Dd1.toplevel x = DupDef.Dd1.c GHC.Num.* x]" it "finds in a patbind" $ do t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let renamed = tmRenamedSource t let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (14,1) parsed let res = definingDeclsNames [n] (hsBinds renamed) False False showGhcQual res `shouldBe` "[DupDef.Dd1.tup@(DupDef.Dd1.h, DupDef.Dd1.t)\n = GHC.List.head GHC.Base.$ GHC.List.zip [1 .. 10] [3 .. ff]\n where\n ff :: GHC.Types.Int\n ff = 15]" it "finds recursively in sub-binds" $ do {- modInfo@((_, _, mod@(GHC.L l (GHC.HsModule name exps imps ds _ _))), toks) <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let res = definingDecls [(PN (mkRdrName "zz"))] ds False True showGhcQual res `shouldBe` "[zz n = n + 1]" -- TODO: Currently fails, will come back to it -} pending -- "Currently fails, will come back to it" it "only finds recursively in sub-binds if asked" $ do {- modInfo@((_, _, mod@(GHC.L l (GHC.HsModule name exps imps ds _ _))), toks) <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let res = definingDecls [(PN (mkRdrName "zz"))] ds False False showGhcQual res `shouldBe` "[]" -} pending -- "Convert to definingDeclsNames" -} -- ------------------------------------------------------------------- describe "definingSigsRdrNames" $ do it "returns [] if not found" $ do t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t let nm = initRdrNameMap t let Just n = locToNameRdrPure nm (21,1) parsed showGhcQual n `shouldBe` "DupDef.Dd1.ff" let res = definingSigsRdrNames nm [n] parsed showGhcQual res `shouldBe` "[]" -- --------------------------------- it "finds signatures at the top level" $ do t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t let nm = initRdrNameMap t let Just n = locToNameRdrPure nm (4,1) parsed showGhcQual n `shouldBe` "DupDef.Dd1.toplevel" let res = definingSigsRdrNames nm [n] parsed showGhcQual res `shouldBe` "[toplevel :: Integer -> Integer]" -- --------------------------------- it "returns only the single signature where there are others too" $ do t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t let nm = initRdrNameMap t let Just n = locToNameRdrPure nm (7,1) parsed showGhcQual n `shouldBe` "DupDef.Dd1.c" let res = definingSigsRdrNames nm [n] parsed showGhcQual res `shouldBe` "[c :: Integer]" -- --------------------------------- it "finds signatures at lower levels" $ do t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t let nm = initRdrNameMap t let Just n = locToNameRdrPure nm (16,5) parsed showGhcQual n `shouldBe` "ff" let res = definingSigsRdrNames nm [n] parsed showGhcQual res `shouldBe` "[ff :: Int]" -- --------------------------------- it "finds multiple signatures 1" $ do t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t let nm = initRdrNameMap t let Just n1 = locToNameRdrPure nm (21,1) parsed showGhcQual n1 `shouldBe` "DupDef.Dd1.ff" let Just n2 = locToNameRdrPure nm (16,5) parsed showGhcQual n2 `shouldBe` "ff" let Just n3 = locToNameRdrPure nm (4,1) parsed showGhcQual n3 `shouldBe` "DupDef.Dd1.toplevel" let res = definingSigsRdrNames nm [n1,n2,n3] parsed showGhcQual res `shouldBe` "[toplevel :: Integer -> Integer, ff :: Int]" -- --------------------------------- it "finds multiple signatures 2" $ do t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t let nm = initRdrNameMap t let Just n1 = locToNameRdrPure nm (14,1) parsed showGhcQual n1 `shouldBe` "DupDef.Dd1.tup" let Just n2 = locToNameRdrPure nm (14,6) parsed showGhcQual n2 `shouldBe` "DupDef.Dd1.h" let Just n3 = locToNameRdrPure nm (14,8) parsed showGhcQual n3 `shouldBe` "DupDef.Dd1.t" let res = definingSigsRdrNames nm [n1,n2,n3] parsed showGhcQual res `shouldBe` "[tup :: (Int, Int), h :: Int, t :: Int]" -- ------------------------------------------------------------------- describe "definingTyClDeclsNames" $ do it "returns [] if not found" $ do t <- ct $ parsedFileGhc "./TypeUtils/TyClDecls.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (10,29) parsed let res = definingTyClDeclsNames nm [n] parsed showGhcQual res `shouldBe` "[]" -- --------------------------------- it "finds foreign type declarations" $ do pending -- --------------------------------- it "finds family declarations" $ do t <- ct $ parsedFileGhc "./TypeUtils/TyClDecls.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t -- putStrLn $ "parsed:" ++ SYB.showData SYB.Parser 0 parsed let Just n = locToNameRdrPure nm (7,14) parsed let res = definingTyClDeclsNames nm [n] parsed showGhcQual res `shouldBe` "[data family XList a]" -- --------------------------------- it "finds data declarations" $ do t <- ct $ parsedFileGhc "./TypeUtils/TyClDecls.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (12,6) parsed let res = definingTyClDeclsNames nm [n] parsed (unspace $ showGhcQual res) `shouldBe` "[data Foo = Foo Int]" -- --------------------------------- it "finds field names in data declarations" $ do t <- ct $ parsedFileGhc "./Renaming/Field4.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (5,23) parsed let res = definingTyClDeclsNames nm [n] parsed (unspace $ showGhcQual res) `shouldBe` "[data Vtree a\n = Vleaf {value1 :: a} |\n Vnode {value2 :: a, left, right :: Vtree a}]" -- --------------------------------- it "finds type declarations" $ do t <- ct $ parsedFileGhc "./TypeUtils/TyClDecls.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (14,6) parsed let res = definingTyClDeclsNames nm [n] parsed showGhcQual res `shouldBe` "[type Foo2 = String]" -- --------------------------------- it "finds class declarations" $ do t <- ct $ parsedFileGhc "./TypeUtils/TyClDecls.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (16,7) parsed let res = definingTyClDeclsNames nm [n] parsed showGhcQual res `shouldBe` "[class Bar a where\n bar :: a -> Bool]" -- --------------------------------- it "finds multiple declarations" $ do t <- ct $ parsedFileGhc "./TypeUtils/TyClDecls.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n1 = locToNameRdrPure nm (14,6) parsed let Just n2 = locToNameRdrPure nm (16,7) parsed let res = definingTyClDeclsNames nm [n1,n2] parsed showGhcQual res `shouldBe` "[type Foo2 = String,\n class Bar a where\n bar :: a -> Bool]" -- ------------------------------------------------------------------- describe "isFunBindR" $ do it "Returns False if not a function definition" $ do t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let renamed = tmRenamedSource t let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let decls = getHsDecls parsed let Just tup = getName "DupDef.Dd1.tup" renamed let [GHC.L l (GHC.ValD decl)] = definingDeclsRdrNames nm [tup] decls False False isFunBindR (GHC.L l decl) `shouldBe` False it "Returns True if a function definition" $ do t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let (GHC.L _l (GHC.HsModule _name _exps _imps _ds _ _)) = GHC.pm_parsed_source $ tmParsedModule t let renamed = tmRenamedSource t let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just toplevel = getName "DupDef.Dd1.toplevel" renamed let [GHC.L l (GHC.ValD decl)] = definingDeclsRdrNames nm [toplevel] (getHsDecls parsed) False False isFunBindR (GHC.L l decl) `shouldBe` True -- ------------------------------------------------------------------- describe "isFunOrPatName" $ do it "return True if a PName is a function/pattern name defined in t" $ do t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let renamed = tmRenamedSource t let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t -- putStrLn $ "parsed:\n" ++ SYB.showData SYB.Parser 0 parsed let Just tup = getName "DupDef.Dd1.tup" renamed (showGhcQual tup) `shouldBe` "DupDef.Dd1.tup" isFunOrPatName nm tup parsed `shouldBe` True -- --------------------------------- it "return False if a PName is a function/pattern name defined in t" $ do t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" t2 <- ct $ parsedFileGhc "./DupDef/Dd2.hs" let renamed = tmRenamedSource t let parsed2 = GHC.pm_parsed_source $ tmParsedModule t2 nm2 = initRdrNameMap t2 let Just tup = getName "DupDef.Dd1.tup" renamed isFunOrPatName nm2 tup parsed2 `shouldBe` False -- ------------------------------------------------------------------- describe "hsFreeAndDeclaredXXXX" $ do it "finds declared in type class definitions" $ do t <- ct $ parsedFileGhc "./FreeAndDeclared/DeclareTypes.hs" let comp = do parsed <- getRefactParsed decls <- liftT $ hsDecls parsed tdss <- mapM getDeclaredTypesRdr decls let tds = nub $ concat tdss return (tds) ((res),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- ((res),_s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual $ map (\n -> (n, getGhcLoc $ GHC.nameSrcSpan n)) (res)) `shouldBe` "[(FreeAndDeclared.DeclareTypes.XList, (8, 1)),\n"++ " (FreeAndDeclared.DeclareTypes.X, (19, 1)),\n"++ " (FreeAndDeclared.DeclareTypes.Y, (19, 10)),\n"++ " (FreeAndDeclared.DeclareTypes.Z, (19, 22)),\n"++ " (FreeAndDeclared.DeclareTypes.W, (19, 26)),\n"++ " (FreeAndDeclared.DeclareTypes.Foo, (21, 1)),\n"++ " (FreeAndDeclared.DeclareTypes.Bar, (23, 1)),\n"++ " (FreeAndDeclared.DeclareTypes.doBar, (27, 3)),\n"++ " (FreeAndDeclared.DeclareTypes.BarVar, (24, 3)),\n"++ " (FreeAndDeclared.DeclareTypes.BarData, (25, 3))]" -- --------------------------------- it "finds free and declared variables" $ do t <- ct $ parsedFileGhc "./FreeAndDeclared/Declare.hs" let comp = do parsed <- getRefactParsed nm <- getRefactNameMap logDataWithAnns "parsed:" parsed let rr = hsFreeAndDeclaredRdr nm parsed return rr -- ((FN fr,DN dr),_s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions ((FN fr,DN dr),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- --------------------- -- Free Vars - parsed (showGhcQual $ map (\n -> (n, getGhcLoc $ GHC.nameSrcSpan n)) fr) `shouldBe` "[(GHC.Integer.Type.Integer, (-1, -1)), "++ "(GHC.Num.*, (-1, -1)),\n "++ "(GHC.Types.Int, (-1, -1)), "++ "(GHC.Base.$, (-1, -1)),\n "++ "(GHC.List.head, (-1, -1)), "++ "(GHC.List.zip, (-1, -1)),\n "++ "(GHC.Base.String, (-1, -1)), "++ "(System.IO.getChar, (-1, -1)),\n "++ "(System.IO.putStrLn, (-1, -1)),\n "++ "(Data.Generics.Text.gshow, (-1, -1))]" -- Declared Vars - parsed (showGhcQual $ map (\n -> (n, getGhcLoc $ GHC.nameSrcSpan n)) dr) `shouldBe` "[(FreeAndDeclared.Declare.toplevel, (6, 1)),\n "++ "(FreeAndDeclared.Declare.c, (9, 1)),\n "++ "(FreeAndDeclared.Declare.d, (10, 1)),\n "++ "(FreeAndDeclared.Declare.tup, (16, 1)),\n "++ "(FreeAndDeclared.Declare.h, (16, 6)),\n "++ "(FreeAndDeclared.Declare.t, (16, 8)),\n "++ "(FreeAndDeclared.Declare.D, (18, 1)),\n "++ "(FreeAndDeclared.Declare.A, (18, 10)),\n "++ "(FreeAndDeclared.Declare.B, (18, 14)),\n "++ "(FreeAndDeclared.Declare.C, (18, 25)),\n "++ "(FreeAndDeclared.Declare.unD, (21, 1)),\n "++ "(FreeAndDeclared.Declare.F, (25, 1)),\n "++ "(FreeAndDeclared.Declare.G, (25, 10)),\n "++ "(FreeAndDeclared.Declare.:|, (25, 14)),\n "++ "(FreeAndDeclared.Declare.unF, (27, 1)),\n "++ "(FreeAndDeclared.Declare.main, (30, 1)),\n "++ "(FreeAndDeclared.Declare.mkT, (34, 1)),\n "++ "(FreeAndDeclared.Declare.ff, (36, 1))]" -- --------------------------------- it "finds free and declared in a single bind PrefixCon" $ do t <- ct $ parsedFileGhc "./FreeAndDeclared/Declare.hs" -- (SYB.showData SYB.Renamer 0 renamed) `shouldBe` "" let comp = do parsed <- getRefactParsed decls <- liftT $ hsDecls parsed let b = head $ drop 10 $ decls rg <- hsFreeAndDeclaredPNs [b] return (b,rg) ((bb,resg),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual bb) `shouldBe` "unD (B y) = y" -- (SYB.showData SYB.Renamer 0 bb) `shouldBe` "" -- Free Vars (showGhcQual $ map (\n -> (n, getGhcLoc $ GHC.nameSrcSpan n)) (fst resg)) `shouldBe` "[(FreeAndDeclared.Declare.B, (18, 14))]" -- Declared Vars (showGhcQual $ map (\n -> (n, getGhcLoc $ GHC.nameSrcSpan n)) (snd resg)) `shouldBe` "[(FreeAndDeclared.Declare.unD, (21, 1))]" -- --------------------------------- it "finds free and declared in a single bind InfixCon" $ do t <- ct $ parsedFileGhc "./FreeAndDeclared/Declare.hs" let comp = do parsed <- getRefactParsed decls <- liftT $ hsDecls parsed let b = head $ drop 12 $ decls rg <- hsFreeAndDeclaredPNs [b] return (b,rg) ((bb,resg),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual bb) `shouldBe` "unF (a :| b) = (a, b)" -- (SYB.showData SYB.Renamer 0 bb) `shouldBe` "" -- Free Vars (showGhcQual $ map (\n -> (n, getGhcLoc $ GHC.nameSrcSpan n)) (fst resg)) `shouldBe` "[(FreeAndDeclared.Declare.:|, (25, 14))]" -- Declared Vars (showGhcQual $ map (\n -> (n, getGhcLoc $ GHC.nameSrcSpan n)) (snd resg)) `shouldBe` "[(FreeAndDeclared.Declare.unF, (27, 1))]" -- --------------------------------- it "finds free and declared in a single bind RecCon" $ do t <- ct $ parsedFileGhc "./FreeAndDeclared/DeclareRec.hs" let comp = do parsed <- getRefactParsed decls <- liftT $ hsDecls parsed let b = head $ drop 2 decls rg <- hsFreeAndDeclaredPNs [b] return (b,rg) ((bb,resg),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual bb) `shouldBe` "unR2 (RCon {r1 = a}) = a" -- (SYB.showData SYB.Renamer 0 bb) `shouldBe` "" -- Free Vars (showGhcQual $ map (\n -> (n, getGhcLoc $ GHC.nameSrcSpan n)) (fst resg)) `shouldBe` "[(FreeAndDeclared.DeclareRec.RCon, (3, 10))]" -- Declared Vars (showGhcQual $ map (\n -> (n, getGhcLoc $ GHC.nameSrcSpan n)) (snd resg)) `shouldBe` "[(FreeAndDeclared.DeclareRec.unR2, (7, 1))]" -- --------------------------------- it "finds free and declared in a RecCon data declaration" $ do t <- ct $ parsedFileGhc "./Renaming/Field1.hs" let comp = do parsed <- getRefactParsed decls <- liftT $ hsDecls parsed let b = head $ drop 0 decls rg <- hsFreeAndDeclaredPNs b return (b,rg) -- ((bb,resg),_s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions ((bb,resg),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual bb) `shouldBe` "data Point\n = Pt {pointx, pointy :: Float}\n deriving (Show)" -- (SYB.showData SYB.Renamer 0 bb) `shouldBe` "" -- Free Vars (showGhcQual $ map (\n -> (n, getGhcLoc $ GHC.nameSrcSpan n)) (fst resg)) `shouldBe` "[(GHC.Types.Float, (-1, -1)), "++ "(GHC.Show.Show, (-1, -1))]" -- Declared Vars (showGhcQual $ map (\n -> (n, getGhcLoc $ GHC.nameSrcSpan n)) (snd resg)) `shouldBe` "[(Field1.Point, (5, 1)), "++ "(Field1.Pt, (5, 14)),\n "++ "(Field1.pointx, (5, 18)), "++ "(Field1.pointy, (5, 26))]" -- --------------------------------- it "finds free and declared in a data declaration, ignoring tyvars 1" $ do t <- ct $ parsedFileGhc "./Renaming/D1.hs" let comp = do parsed <- getRefactParsed decls <- liftT $ hsDecls parsed let b = head $ drop 0 decls rg <- hsFreeAndDeclaredPNs b return (b,rg) -- ((bb,resg),_s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions ((bb,resg),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual bb) `shouldBe` "data Tree a = Leaf a | Branch (Tree a) (Tree a)" -- (SYB.showData SYB.Renamer 0 bb) `shouldBe` "" -- Free Vars (showGhcQual $ map (\n -> (n, getGhcLoc $ GHC.nameSrcSpan n)) (fst resg)) `shouldBe` "[]" -- Declared Vars (showGhcQual $ map (\n -> (n, getGhcLoc $ GHC.nameSrcSpan n)) (snd resg)) `shouldBe` "[(Renaming.D1.Tree, (6, 1)), "++ "(Renaming.D1.Leaf, (6, 15)),\n "++ "(Renaming.D1.Branch, (6, 24))]" -- --------------------------------- it "finds free and declared in a data declaration, ignoring tyvars 2" $ do t <- ct $ parsedFileGhc "./Renaming/D1.hs" let comp = do parsed <- getRefactParsed decls <- liftT $ hsDecls parsed let b = head $ drop 3 decls rg <- hsFreeAndDeclaredPNs b return (b,rg) -- ((bb,resg),_s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions ((bb,resg),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual bb) `shouldBe` "class SameOrNot c where\n isSame :: c -> c -> Bool\n isNotSame :: c -> c -> Bool" -- (SYB.showData SYB.Renamer 0 bb) `shouldBe` "" -- Free Vars (showGhcQual $ map (\n -> (n, getGhcLoc $ GHC.nameSrcSpan n)) (fst resg)) `shouldBe` "[(GHC.Types.Bool, (-1, -1))]" -- Declared Vars (showGhcQual $ map (\n -> (n, getGhcLoc $ GHC.nameSrcSpan n)) (snd resg)) `shouldBe` "[(Renaming.D1.SameOrNot, (12, 1)), "++ "(Renaming.D1.isSame, (13, 4)),\n "++ "(Renaming.D1.isNotSame, (14, 4))]" -- ----------------------------------------------------------------- it "hsFreeAndDeclaredPNs simplest" $ do t <- ct $ parsedFileGhc "./FreeAndDeclared/DeclareS.hs" let comp = do parsed <- getRefactParsed r <- hsFreeAndDeclaredPNs parsed return r ((res),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- Free Vars (showGhcQual $ map (\n -> (n, getGhcLoc $ GHC.nameSrcSpan n)) (fst res)) `shouldBe` "[]" -- Declared Vars (showGhcQual $ map (\n -> (n, getGhcLoc $ GHC.nameSrcSpan n)) (snd res)) `shouldBe` "[(FreeAndDeclared.DeclareS.c, (6, 1))]" -- ----------------------------------------------------------------- it "finds free and declared in a single bind #2" $ do t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let renamed = tmRenamedSource t let Just tup = getName "DupDef.Dd1.ff" renamed let comp = do parsed <- getRefactParsed nm <- getRefactNameMap decls <- liftT $ hsDecls parsed let [decl] = definingDeclsRdrNames nm [tup] decls False False r <- hsFreeAndDeclaredPNs [decl] return (r,decl) ((res,d),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual d) `shouldBe` "ff y\n = y + zz\n where\n zz = 1" -- (SYB.showData SYB.Renamer 0 d) `shouldBe` "" -- Free Vars (showGhcQual $ map (\n -> (n, getGhcLoc $ GHC.nameSrcSpan n)) (fst res)) `shouldBe` "[(GHC.Num.+, (-1, -1))]" -- Declared Vars (showGhcQual $ map (\n -> (n, getGhcLoc $ GHC.nameSrcSpan n)) (snd res)) `shouldBe` "[(DupDef.Dd1.ff, (21, 1))]" -- ----------------------------------------------------------------- it "finds free and declared at the top level 1" $ do t <- ct $ parsedFileGhc "./LiftToToplevel/WhereIn1.hs" let comp = do parsed <- getRefactParsed r <- hsFreeAndDeclaredPNs parsed return r ((res),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- Declared Vars (showGhcQual $ map (\n -> (n, getGhcLoc $ GHC.nameSrcSpan n)) (snd res)) `shouldBe` "[(LiftToToplevel.WhereIn1.sumSquares, (9, 1)),\n "++ "(LiftToToplevel.WhereIn1.anotherFun, (15, 1))]" -- Free Vars (showGhcQual $ map (\n -> (n, getGhcLoc $ GHC.nameSrcSpan n)) (fst res)) `shouldBe` "[(GHC.Num.+, (-1, -1)), (GHC.Real.^, (-1, -1))]" -- ----------------------------------------------------------------- it "finds free and declared at the top level 2" $ do t <- ct $ parsedFileGhc "./Renaming/IdIn3.hs" let comp = do parsed <- getRefactParsed r <- hsFreeAndDeclaredPNs parsed return r ((res),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- Declared Vars (showGhcQual $ map (\n -> (n, getGhcLoc $ GHC.nameSrcSpan n)) (snd res)) `shouldBe` "[(IdIn3.x, (10, 1)), "++ "(IdIn3.foo, (12, 1)), "++ "(IdIn3.bar, (14, 1)),\n "++ "(IdIn3.main, (18, 1))]" -- Free Vars (showGhcQual $ map (\n -> (n, getGhcLoc $ GHC.nameSrcSpan n)) (fst res)) `shouldBe` "[(GHC.Num.+, (-1, -1))]" -- ----------------------------------------------------------------- it "finds free and declared in a GRHSs" $ do t <- ct $ parsedFileGhc "./LiftOneLevel/LetIn2.hs" let renamed = tmRenamedSource t let Just tup = getName "LiftOneLevel.LetIn2.sumSquares" renamed let comp = do nm <- getRefactNameMap parsed <- getRefactParsed decls <- liftT $ hsDecls parsed let [decl] = definingDeclsRdrNames nm [tup] decls False False #if __GLASGOW_HASKELL__ <= 710 let (GHC.L _ (GHC.ValD (GHC.FunBind _ _ (GHC.MG [match] _ _ _) _ _ _))) = decl #else let (GHC.L _ (GHC.ValD (GHC.FunBind _ (GHC.MG (GHC.L _ [match]) _ _ _) _ _ _))) = decl #endif let (GHC.L _ (GHC.Match _ _pat _ grhss)) = match r <- hsFreeAndDeclaredPNs grhss return r ((res),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- Declared Vars (showGhcQual $ map (\n -> (n, getGhcLoc $ GHC.nameSrcSpan n)) (snd res)) `shouldBe` "[]" -- Free Vars (showGhcQual $ map (\n -> (n, getGhcLoc $ GHC.nameSrcSpan n)) (fst res)) `shouldBe` "[(GHC.Real.^, (-1, -1)), (GHC.Num.+, (-1, -1)), (x, (10, 12)),\n (y, (10, 14))]" -- ----------------------------------------------------------------- it "finds free and declared in a single bind" $ do pending -- "fix the prior test" -- --------------------------------------------------------------------- describe "hsFDsFromInsideRdr" $ do it "does something useful" $ do pendingWith "need to convert to using Parsed source" -- "Complete this" describe "hsFDsFromInside" $ do it "does something useful" $ do pending -- "Complete this" describe "hsFDNamesFromInside" $ do it "does something useful" $ do pending -- "Complete this" -- --------------------------------------------------------------------- describe "hsVisibleNames" $ do it "does something useful" $ do pending -- "Complete this" -- --------------------------------------------------------------------- describe "hsVisibleDsRdr" $ do -- --------------------------------- it "returns [] if e does not occur in t" $ do t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let renamed = tmRenamedSource t let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just tl1 = locToExp (4,13) (4,40) parsed :: (Maybe (GHC.Located (GHC.HsExpr GHC.RdrName))) let Just tup = getName "DupDef.Dd1.tup" renamed let comp = do DN r <- hsVisibleDsRdr nm tup tl1 return r ((res),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (null res) `shouldBe` True -- ----------------------------------------------------------------- it "returns visible vars if e does occur in t #1" $ do pendingWith "no longer relevant?" {- t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let renamed = tmRenamedSource t let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just tl1 = locToExp (28,4) (28,12) parsed :: (Maybe (GHC.LHsExpr GHC.RdrName)) (showGhcQual tl1) `shouldBe` "ll + z" let Just tup = getName "DupDef.Dd1.l" renamed let comp = do decls <- liftT $ hsDecls parsed let [decl] = definingDeclsRdrNames nm [tup] decls False False r <- hsVisibleDsRdr nm (rdrName2NamePure nm tl1) decl return (r,decl) ((res,d),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual d) `shouldBe` "l z = let ll = 34 in ll + z" (showGhcQual res ) `shouldBe` "[z, ll]" -- (showGhcQual res2 ) `shouldBe` "[z, ll]" -} -- ----------------------------------------------------------------- it "returns visible vars if e does occur in t #2" $ do pendingWith "no longer relevant?" {- t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just tl1 = locToExp (28,4) (28,12) parsed :: (Maybe (GHC.LHsExpr GHC.RdrName)) (showGhcQual tl1) `shouldBe` "ll + z" let Just rhs = locToExp (26,1) (28,12) parsed :: (Maybe (GHC.LHsExpr GHC.RdrName)) (showGhcQual rhs) `shouldBe` "let ll = 34 in ll + z" let comp = do r <- hsVisibleDsRdr nm (rdrName2NamePure nm tl1) rhs return r ((res),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual res) `shouldBe` "[ll]" -} -- --------------------------------- it "Rdr:finds function arguments visible in RHS 1" $ do pendingWith "no longer relevant?" {- t <- ct $ parsedFileGhc "./Visible/Simple.hs" let renamed = tmRenamedSource t let parsed = GHC.pm_parsed_source $ tmParsedModule t let Just e = locToExp (5,11) (5,19) parsed :: (Maybe (GHC.LHsExpr GHC.RdrName)) (showGhcQual e) `shouldBe` "a + b" let Just n = getName "Visible.Simple.params" renamed let comp = do nm <- getRefactNameMap declsp <- liftT $ hsDecls parsed let [decl] = definingDeclsRdrNames nm [n] declsp False False fds' <- hsVisibleDsRdr nm (rdrName2NamePure nm e) decl return (fds') -- ((fds),_s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions ((fds),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (show fds) `shouldBe` "DN [a, b, GHC.Num.+]" -} -- ----------------------------------- it "finds function arguments visible in RHS 2" $ do pendingWith "no longer relevant?" {- t <- ct $ parsedFileGhc "./Visible/Simple.hs" let renamed = tmRenamedSource t let parsed = GHC.pm_parsed_source $ tmParsedModule t -- (SYB.showData SYB.Renamer 0 renamed) `shouldBe` "" let Just e = locToExp (9,15) (9,17) parsed :: (Maybe (GHC.LHsExpr GHC.RdrName)) (showGhcQual e) `shouldBe` "x" let Just n = getName "Visible.Simple.param2" renamed let comp = do nm <- getRefactNameMap declsp <- liftT $ hsDecls parsed let [decl] = definingDeclsRdrNames nm [n] declsp False False fds' <- hsVisibleDsRdr nm (rdrName2NamePure nm e) decl return (fds') -- ((fds),_s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions ((fds),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (show fds) `shouldBe` "DN [x]" -} -- ----------------------------------- it "finds visible vars inside a function" $ do t <- ct $ parsedFileGhc "./Renaming/IdIn5.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t let Just rhs = locToExp (17,6) (18,14) parsed :: (Maybe (GHC.LHsExpr GHC.RdrName)) (showGhcQual rhs) `shouldBe` "x + y + z" -- let Just er = getName "IdIn5.x" renamed let Just e = locToRdrName (17,7) parsed (showGhcQual e) `shouldBe` "x" (SYB.showData SYB.Parser 0 e) `shouldBe` "\n(L {Renaming/IdIn5.hs:17:7} \n (Unqual {OccName: x}))" let comp = do nm <- getRefactNameMap fds' <- hsVisibleDsRdr nm (rdrName2NamePure nm e) rhs let ffds = hsFreeAndDeclaredRdr nm rhs return (fds',ffds) -- ((fds,_fds),_s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions ((fds,_fds),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (show _fds) `shouldBe` "(FN [GHC.Num.+, IdIn5.x, y, z],DN [])" (show fds) `shouldBe` "DN [GHC.Num.+, IdIn5.x, y, z]" -- ----------------------------------- it "finds visible vars inside a data declaration" $ do t <- ct $ parsedFileGhc "./Renaming/D1.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t let Just ln = locToRdrName (6, 6) parsed (showGhcQual ln) `shouldBe` "Tree" (SYB.showData SYB.Parser 0 ln) `shouldBe` "\n(L {Renaming/D1.hs:6:6-9} \n (Unqual {OccName: Tree}))" let comp = do -- logDataWithAnns "parsed" parsed nm <- getRefactNameMap fds' <- hsVisibleDsRdr nm (rdrName2NamePure nm ln) parsed let ffds = hsFreeAndDeclaredRdr nm parsed return (fds',ffds) ((fds,_fds),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- ((fds,_fds),_s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (show _fds) `shouldBe` "(FN [GHC.Base.++, "++ "GHC.Types.Bool, "++ "GHC.Types.Int, "++ "GHC.Classes.==,\n "++ "GHC.Classes./=, "++ ":, "++ "GHC.Num.+, "++ "GHC.Real.^, "++ "[]],"++ "DN [Renaming.D1.Tree, "++ "Renaming.D1.Leaf, "++ "Renaming.D1.Branch,\n "++ "Renaming.D1.fringe, "++ "Renaming.D1.SameOrNot, "++ "Renaming.D1.isSame,\n "++ "Renaming.D1.isNotSame, "++ "Renaming.D1.sumSquares])" (show fds) `shouldBe` "DN [Renaming.D1.Tree, Renaming.D1.Leaf, Renaming.D1.Branch]" -- ----------------------------------- it "finds visible vars inIdIn5" $ do t <- ct $ parsedFileGhc "./Renaming/IdIn5.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t let Just ln = locToRdrName (13, 1) parsed (showGhcQual ln) `shouldBe` "x" (SYB.showData SYB.Parser 0 ln) `shouldBe` "\n(L {Renaming/IdIn5.hs:13:1} \n (Unqual {OccName: x}))" let comp = do logDataWithAnns "parsed" parsed nm <- getRefactNameMap fds' <- hsVisibleDsRdr nm (rdrName2NamePure nm ln) parsed let ffds = hsFreeAndDeclaredRdr nm parsed return (fds',ffds) ((fds,_fds),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- ((fds,_fds),_s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (show _fds) `shouldBe` "(FN [GHC.Base.String, GHC.Num.+],"++ "DN [IdIn5.x, IdIn5.foo, IdIn5.bar, IdIn5.main])" (show fds) `shouldBe` "DN [GHC.Num.+, IdIn5.x, z, y, IdIn5.foo, IdIn5.bar]" -- --------------------------------------------------------------------- describe "hsFreeAndDeclaredRdr" $ do it "finds function arguments visible in RHS fd" $ do t <- ct $ parsedFileGhc "./Visible/Simple.hs" let renamed = tmRenamedSource t let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just e = locToExp (5,11) (5,19) parsed :: (Maybe (GHC.Located (GHC.HsExpr GHC.RdrName))) (showGhcQual e) `shouldBe` "a + b" let Just n = getName "Visible.Simple.params" renamed let comp = do decls <- liftT $ hsDecls parsed let [decl] = definingDeclsRdrNames nm [n] decls False False let fds' = hsFreeAndDeclaredRdr nm decl return (fds') -- ((fds),_s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions ((fds),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (show fds) `shouldBe` "(FN [GHC.Num.+],DN [Visible.Simple.params])" -- ----------------------------------- it "finds function arguments and free vars visible in RHS" $ do t <- ct $ parsedFileGhc "./Visible/Simple.hs" let renamed = tmRenamedSource t let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just e = locToExp (9,15) (9,17) parsed :: Maybe (GHC.LHsExpr GHC.RdrName) (showGhcQual e) `shouldBe` "x" let Just n = getName "Visible.Simple.param2" renamed let comp = do decls <- liftT $ hsDecls parsed let [decl] = definingDeclsRdrNames nm [n] decls False False #if __GLASGOW_HASKELL__ <= 710 let (GHC.L _ (GHC.ValD (GHC.FunBind _ _ (GHC.MG matches _ _ _) _ _ _))) = decl #else let (GHC.L _ (GHC.ValD (GHC.FunBind _ (GHC.MG (GHC.L _ matches) _ _ _) _ _ _))) = decl #endif let [(GHC.L _ (GHC.Match _ pats _ _))] = matches let lpat = head pats logDataWithAnns "lpat" lpat let fds' = hsFreeAndDeclaredRdr nm lpat return (fds') -- ((fds),_s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions ((fds),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (show fds) `shouldBe` "(FN [Visible.Simple.B],DN [x])" -- ----------------------------------- it "finds imported functions used in the rhs" $ do t <- ct $ parsedFileGhc "./FreeAndDeclared/Declare.hs" let renamed = tmRenamedSource t let parsed = GHC.pm_parsed_source $ tmParsedModule t let Just n = getName "FreeAndDeclared.Declare.tup" renamed let comp = do nm <- getRefactNameMap decls <- liftT $ hsDecls parsed let [decl] = definingDeclsRdrNames nm [n] decls False False let fds' = hsFreeAndDeclaredRdr nm decl return (fds') ((fds),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (show fds) `shouldBe` "(FN [GHC.Base.$, GHC.List.head, GHC.List.zip],"++ "DN [FreeAndDeclared.Declare.tup, FreeAndDeclared.Declare.h,\n "++ "FreeAndDeclared.Declare.t])" -- ----------------------------------- it "finds free vars in HsWithBndrs" $ do t <- ct $ parsedFileGhc "./FreeAndDeclared/Binders.hs" let renamed = tmRenamedSource t let Just n = getName "FreeAndDeclared.Binders.findNewPName" renamed let comp = do nm <- getRefactNameMap parsed <- getRefactParsed -- logDataWithAnns "parsed" parsed decls <- liftT $ hsDecls parsed let [decl] = definingDeclsRdrNames nm [n] decls False False #if __GLASGOW_HASKELL__ <= 710 let (GHC.L _ (GHC.ValD (GHC.FunBind _ _ (GHC.MG [match] _ _ _) _ _ _))) = decl #else let (GHC.L _ (GHC.ValD (GHC.FunBind _ (GHC.MG (GHC.L _ [match]) _ _ _) _ _ _))) = decl #endif let (GHC.L _ (GHC.Match _ _pats _rhs binds)) = match logDataWithAnns "binds" binds let fds' = hsFreeAndDeclaredRdr nm binds return (fds') -- ((fds),_s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions ((fds),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (show fds) `shouldBe` "(FN [FreeAndDeclared.Binders.gfromJust,\n "++ "FreeAndDeclared.Binders.somethingStaged,\n "++ "FreeAndDeclared.Binders.Renamer, "++ "GHC.Base.Nothing, "++ "renamed,\n "++ "FreeAndDeclared.Binders.Name, "++ "GHC.Classes.==, "++ "GHC.Base.$,\n "++ "FreeAndDeclared.Binders.occNameString,\n "++ "FreeAndDeclared.Binders.getOccName, "++ "name, "++ "GHC.Base.Just],"++ "DN [res, worker])" -- ----------------------------------- it "finds free vars in TH files" $ do t <- ct $ parsedFileGhc "./TH/Main.hs" let comp = do parseSourceFileGhc "./TH/Main.hs" parsed <- getRefactParsed nm <- getRefactNameMap let fds' = hsFreeAndDeclaredRdr nm parsed return (fds') ((fds),_s) <- ct $ runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (show fds) `shouldBe` "(FN [System.IO.putStrLn, pr],"++ "DN [TH.Main.main, TH.Main.baz, TH.Main.sillyString])" -- --------------------------------------------- describe "isLocalPN" $ do it "returns True if the name is local to the module" $ do t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (17, 5) parsed (showGhcQual n) `shouldBe` "ff" isLocalPN n `shouldBe` True it "returns False if the name is not local to the module" $ do t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (21, 1) parsed (showGhcQual n) `shouldBe` "DupDef.Dd1.ff" isLocalPN n `shouldBe` False -- --------------------------------------------- describe "isTopLevelPN" $ do it "returns False if the name is not defined at the top level of the module" $ do t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let comp = do parsed <- getRefactParsed nm <- getRefactNameMap let Just n = locToNameRdrPure nm (17, 5) parsed topLevel <- isTopLevelPN n return (n,topLevel) ((nf,tl),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual nf) `shouldBe` "ff" tl `shouldBe` False it "returns True if the name is defined at the top level of the module" $ do t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let comp = do parsed <- getRefactParsed nm <- getRefactNameMap let Just n = locToNameRdrPure nm (21, 1) parsed topLevel <- isTopLevelPN n return (n,topLevel) ((nf,tl),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual nf) `shouldBe` "DupDef.Dd1.ff" tl `shouldBe` True -- --------------------------------------------- describe "definedPNsRdr" $ do it "gets the PNs defined in a declaration" $ do t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just pn = locToNameRdrPure nm (3, 1) parsed (showGhcQual pn) `shouldBe` "DupDef.Dd1.toplevel" let origDecls = getHsDecls parsed let demotedDecls'= definingDeclsRdrNames nm [pn] origDecls True False let declaredPns = nub $ concatMap definedPNsRdr demotedDecls' (showGhcQual declaredPns) `shouldBe` "[toplevel]" -- --------------------------------- it "gets the PNs defined in an as-match" $ do t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just pn = locToNameRdrPure nm (14, 1) parsed (showGhcQual pn) `shouldBe` "DupDef.Dd1.tup" let origDecls = getHsDecls parsed let demotedDecls'= definingDeclsRdrNames nm [pn] origDecls True False let declaredPns = nub $ concatMap definedPNsRdr demotedDecls' (showGhcQual declaredPns) `shouldBe` "[tup, h, t]" -- --------------------------------------------- describe "inScopeInfo" $ do it "returns 4 element tuples for in scope names" $ do pending -- "is this still needed?" {- ((inscopes, _renamed, _parsed), _toks) <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let info = inScopeInfo inscopes (show $ head info) `shouldBe` "foo" -- (show $ info) `shouldBe` "foo" -} -- --------------------------------------------- describe "isInScopeAndUnqualified" $ do it "True if the identifier is in scope and unqualified" $ do pending -- "needed?" {- ((inscopes, _renamed, _parsed), _toks) <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let info = inScopeInfo inscopes (show $ head info) `shouldBe` "foo" -} -- inScopeInfo for c is -- (\"DupDef.Dd1.c\",VarName,DupDef.Dd1,Nothing) -- --------------------------------------------- describe "isInScopeAndUnqualifiedGhc" $ do it "True if the identifier is in scope and unqualified" $ do let comp = do parseSourceFileGhc "./DupDef/Dd1.hs" ctx <- GHC.getContext res1 <- isInScopeAndUnqualifiedGhc "c" Nothing res2 <- isInScopeAndUnqualifiedGhc "DupDef.Dd1.c" Nothing res3 <- isInScopeAndUnqualifiedGhc "nonexistent" Nothing return (res1,res2,res3,ctx) ((r1,r2,r3,_c),_s) <- ct $ runRefactGhc comp (initialState { rsModule = Nothing }) testOptions r1 `shouldBe` True r2 `shouldBe` True r3 `shouldBe` False -- --------------------------------- it "requires qualification on name clash with an import" $ do t <- ct $ parsedFileGhc "./ScopeAndQual.hs" let comp = do parseSourceFileGhc "./ScopeAndQual.hs" -- putParsedModule t renamed <- getRefactRenamed parsed <- getRefactParsed nm <- getRefactNameMap logm $ "renamed=" ++ (SYB.showData SYB.Renamer 0 renamed) -- ++AZ++ ctx <- GHC.getContext let Just sumSquares = locToNameRdrPure nm (13,15) parsed ssUnqual <- isQualifiedPN sumSquares names <- GHC.parseName "sum" names2 <- GHC.parseName "mySumSq" res1 <- isInScopeAndUnqualifiedGhc "sum" Nothing res2 <- isInScopeAndUnqualifiedGhc "L.sum" Nothing return (res1,res2,names,names2,sumSquares,ssUnqual,ctx) ((r1,r2,ns,ns2,ss,ssu,_c),_s) <- ct $ runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (prettyprint ss) `shouldBe` "sumSquares" (showGhcQual ss) `shouldBe` "ScopeAndQual.sumSquares" (show $ ssu) `shouldBe` "False" (showGhcQual ns) `shouldBe` "[ScopeAndQual.sum]" (showGhcQual ns2) `shouldBe` "[ScopeAndQual.mySumSq]" "1" ++ (show r1) `shouldBe` "1True" "2" ++ (show r2) `shouldBe` "2True" -- --------------------------------------------- describe "mkNewGhcName" $ do it "Creates a new GHC.Name" $ do t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let comp = do parsed <- getRefactParsed nm <- getRefactNameMap let Just topLevel = locToNameRdrPure nm (3,1) parsed name1 <- mkNewGhcName Nothing "foo" name2 <- mkNewGhcName Nothing "bar" name3 <- mkNewGhcName (Just (GHC.nameModule topLevel)) "baz" return (name1,name2,name3) ((n1,n2,n3),_s) <- ct $ runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions GHC.getOccString n1 `shouldBe` "foo" showGhcQual n1 `shouldBe` "foo" GHC.getOccString n2 `shouldBe` "bar" showGhcQual n2 `shouldBe` "bar" (showGhcQual $ GHC.nameModule n3) `shouldBe` "main@main:DupDef.Dd1" (SYB.showData SYB.Renamer 0 n3) `shouldBe` "{Name: baz}" GHC.getOccString n3 `shouldBe` "baz" showGhcQual n3 `shouldBe` "DupDef.Dd1.baz" (showGhcQual $ GHC.nameUnique n1) `shouldBe` "H2" (showGhcQual $ GHC.nameUnique n2) `shouldBe` "H3" (showGhcQual $ GHC.nameUnique n3) `shouldBe` "H4" -- --------------------------------------------- describe "prettyprint" $ do it "Prints a GHC.Name ready for parsing into tokens" $ do -- (_t, _toks, _tgt) <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let comp = do name1 <- mkNewGhcName Nothing "foo" name2 <- mkNewGhcName Nothing "bar" return (name1,name2) ((n1,n2),_s) <- ct $ runRefactGhcState comp GHC.getOccString n1 `shouldBe` "foo" showGhcQual n1 `shouldBe` "foo" GHC.getOccString n2 `shouldBe` "bar" showGhcQual n2 `shouldBe` "bar" showGhcQual n1 `shouldBe` "foo" -- --------------------------------------------- describe "duplicateDecl" $ do it "duplicates a bind only" $ do t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (3, 1) parsed let comp = do -- parsed <- getRefactParsed declsp <- liftT $ hsDecls parsed newName2 <- mkNewGhcName Nothing "bar2" newBindings <- duplicateDecl declsp n newName2 parsed' <- liftT $ replaceDecls parsed newBindings putRefactParsed parsed' emptyAnns return newBindings (_nb,s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "DupDef.Dd1.toplevel" (sourceFromState s) `shouldBe` "module DupDef.Dd1 where\n\ntoplevel :: Integer -> Integer\ntoplevel x = c * x\n\nbar2 :: Integer -> Integer\nbar2 x = c * x\n\nc,d :: Integer\nc = 7\nd = 9\n\n-- Pattern bind\ntup :: (Int, Int)\nh :: Int\nt :: Int\ntup@(h,t) = head $ zip [1..10] [3..ff]\n where\n ff :: Int\n ff = 15\n\ndata D = A | B String | C\n\nff y = y + zz\n where\n zz = 1\n\nl z =\n let\n ll = 34\n in ll + z\n\ndd q = do\n let ss = 5\n return (ss + q)\n\n" -- --------------------------------------------- it "duplicates a bind with a signature, and an offset" $ do t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just np = locToNameRdrPure nm (14, 1) parsed (showGhcQual np) `shouldBe` "DupDef.Dd1.tup" let Just ln'@(GHC.L l _) = locToRdrName (17, 6) parsed n = rdrName2NamePure nm ln' ln = GHC.L l n (showGhcQual n) `shouldBe` "ff" let comp = do newName2 <- mkNewGhcName Nothing "gg" -- parsed <- getRefactParsed decls <- liftT $ hsDecls parsed (front,[parent],back) <- divideDecls decls ln (parent',Just (funBinding,declsToDup,declsp')) <- modifyValD (GHC.getLoc parent) parent $ \_m declsp -> do let declsToDup = definingDeclsRdrNames nm [n] declsp False True funBinding = filter isFunOrPatBindP declsToDup --get the fun binding. declsp' <- duplicateDecl declsp n newName2 return (declsp',Just (funBinding,declsToDup,declsp')) parsed' <- liftT $ replaceDecls parsed (front ++ [parent'] ++ back) putRefactParsed parsed' emptyAnns return (funBinding,declsToDup,declsp') ((fb,dd,newb),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- ((fb,dd,newb),s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "ff" (showGhcQual dd) `shouldBe` "[ff = 15]" (showGhcQual fb) `shouldBe` "[ff = 15]" (show $ getStartEndLoc fb) `shouldBe` "((17,5),(17,12))" (sourceFromState s) `shouldBe` "module DupDef.Dd1 where\n\ntoplevel :: Integer -> Integer\ntoplevel x = c * x\n\nc,d :: Integer\nc = 7\nd = 9\n\n-- Pattern bind\ntup :: (Int, Int)\nh :: Int\nt :: Int\ntup@(h,t) = head $ zip [1..10] [3..ff]\n where\n ff :: Int\n ff = 15\n\n gg :: Int\n gg = 15\n\ndata D = A | B String | C\n\nff y = y + zz\n where\n zz = 1\n\nl z =\n let\n ll = 34\n in ll + z\n\ndd q = do\n let ss = 5\n return (ss + q)\n\n" (showGhcQual newb) `shouldBe` "[ff :: Int, ff = 15, gg :: Int, gg = 15]" (showGhcQual fb) `shouldBe` "[ff = 15]" -- --------------------------------------------- describe "addParamsToDecl" $ do it "adds parameters to a declaration" $ do t <- ct $ parsedFileGhc "./MoveDef/Md1.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (3, 1) parsed let comp = do declsp <- liftT $ hsDecls parsed let newName2 = mkRdrName "bar2" declsp' <- addParamsToDecls declsp n [newName2] parsed' <- liftT $ replaceDecls parsed declsp' putRefactParsed parsed' emptyAnns return declsp' (nb,s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "MoveDef.Md1.toplevel" (sourceFromState s) `shouldBe` "module MoveDef.Md1 where\n\ntoplevel :: Integer -> Integer\ntoplevel bar2 x = c * x\n\nc,d :: Integer\nc = 7\nd = 9\n\n-- Pattern bind\ntup :: (Int, Int)\nh :: Int\nt :: Int\ntup@(h,t) = head $ zip [1..10] [3..ff]\n where\n ff :: Int\n ff = 15\n\ndata D = A | B String | C\n\nff :: Int -> Int\nff y = y + zz\n where\n zz = 1\n\nl z =\n let\n ll = 34\n in ll + z\n\ndd q = do\n let ss = 5\n return (ss + q)\n\nzz1 a = 1 + toplevel a\n\n-- General Comment\n-- |haddock comment\ntlFunc :: Integer -> Integer\ntlFunc x = c * x\n-- Comment at end\n\n\n" (showGhcQual $ head $ tail nb) `shouldBe` "toplevel bar2 x = c * x" -- --------------------------------- it "adds parameters to a declaration with multiple matches" $ do t <- ct $ parsedFileGhc "./AddParams1.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (3, 1) parsed let comp = do declsp <- liftT $ hsDecls parsed let newName = mkRdrName "pow" declsp' <- addParamsToDecls declsp n [newName] parsed' <- liftT $ replaceDecls parsed declsp' putRefactParsed parsed' emptyAnns return declsp' (_nb,s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- (_nb,s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "AddParams1.sq" (sourceFromState s) `shouldBe` "module AddParams1 where\n\nsq pow 0 = 0\nsq pow z = z^2\n\nfoo = 3\n\n" -- --------------------------------- it "adds parameters to a declaration with no existing ones" $ do t <- ct $ parsedFileGhc "./AddParams1.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (6, 1) parsed let comp = do declsp <- liftT $ hsDecls parsed let newName1 = mkRdrName "baz" let newName2 = mkRdrName "bar" declsp' <- addParamsToDecls declsp n [newName1,newName2] parsed' <- liftT $ replaceDecls parsed declsp' putRefactParsed parsed' emptyAnns return declsp' (_nb,s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "AddParams1.foo" (sourceFromState s) `shouldBe` "module AddParams1 where\n\nsq 0 = 0\nsq z = z^2\n\nfoo baz bar = 3\n\n" -- --------------------------------------------- describe "addActualParamsToRhs" $ do it "adds a parameter to the rhs of a declaration" $ do t <- ct $ parsedFileGhc "./LiftToToplevel/D1.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (6, 21) parsed let comp = do -- parsed <- getRefactParsed declsp <- liftT $ hsDecls parsed let decl = head declsp let newName2 = mkRdrName "bar2" newBinding <- addActualParamsToRhs n [newName2] decl return (newBinding,decl) ((nb,decl'),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- ((nb,decl'),s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions -- putStrLn $ "nb[]\n" ++ showAnnDataItemFromState s nb ++ "\n]" (showGhcQual decl') `shouldBe` "sumSquares (x : xs)\n = sq x + sumSquares xs\n where\n sq x = x ^ pow\n pow = 2\nsumSquares [] = 0" (showGhcQual n) `shouldBe` "sq" (showGhcQual nb) `shouldBe` "sumSquares (x : xs)\n = (sq bar2) x + sumSquares xs\n where\n sq x = x ^ pow\n pow = 2\nsumSquares [] = 0" (exactPrintFromState s nb) `shouldBe` "\n\n{-lift 'sq' to top level. This refactoring\n affects module 'D1' and 'C1' -}\n\nsumSquares (x:xs) = (sq bar2) x + sumSquares xs\n where\n sq x = x ^ pow\n pow =2\n\nsumSquares [] = 0" -- -------------------- it "adds parameters to a complex rhs of a declaration" $ do t <- ct $ parsedFileGhc "./LiftToToplevel/WhereIn7.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (10, 17) parsed let comp = do -- parsed <- getRefactParsed declsp <- liftT $ hsDecls parsed let decl = head declsp let newName1 = mkRdrName "x1" let newName2 = mkRdrName "y1" let newName3 = mkRdrName "z1" newBinding <- addActualParamsToRhs n [newName1,newName2,newName3] decl return (newBinding,decl) ((nb,decl'),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual decl') `shouldBe` "fun x y z\n = inc addthree\n where\n inc a = a + 1\n addthree = x + y + z" (showGhcQual n) `shouldBe` "addthree" (showGhcQual nb) `shouldBe` "fun x y z\n = inc (addthree x1 y1 z1)\n where\n inc a = a + 1\n addthree = x + y + z" (exactPrintFromState s nb) `shouldBe` "\n\n--A definition can be lifted from a where or let to the top level binding group.\n--Lifting a definition widens the scope of the definition.\n\n--In this example, lift 'addthree' defined in 'fun'.\n--This example aims to test adding parenthese.\n\n\nfun x y z =inc (addthree x1 y1 z1)\n where inc a =a +1\n addthree=x+y+z" -- --------------------------------- it "adds parameters to a declaration in a tuple" $ do t <- ct $ parsedFileGhc "./AddParams2.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (5, 36) parsed let Just e = locToExp (5,23) (5,47) parsed :: Maybe (GHC.Located (GHC.HsExpr GHC.RdrName)) let comp = do let newName1 = mkRdrName "baz" let newName2 = mkRdrName "bar" e' <- addActualParamsToRhs n [newName1,newName2] e return e' (nb,s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "rightOuter" (showGhcQual e) `shouldBe` "(rightInner, rightOuter)" (exactPrintFromState s nb) `shouldBe` " (rightInner, (rightOuter baz bar))" -- putStrLn (showAnnDataItemFromState s e) -- putStrLn (showAnnDataItemFromState s nb) -- --------------------------------------------- describe "rmDecl" $ do it "removes a top level declaration, leaving type signature 1" $ do t <- ct $ parsedFileGhc "./MoveDef/Md1a.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (6, 1) parsed let comp = do (parsed',_removedDecl,_removedSig) <- rmDecl n False parsed putRefactParsed parsed' emptyAnns return parsed' -- (_nb,s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (_nb,s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "MoveDef.Md1a.ff" (sourceFromState s) `shouldBe` "module MoveDef.Md1a where\n\ndata D = A | B String | C\n\nff :: Int -> Int\n\nl = 1\n\n" -- --------------------------------- it "removes a top level declaration, leaving type signature 2b" $ do t <- ct $ parsedFileGhc "./MoveDef/Md1b.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (6, 1) parsed let comp = do (parsed',_removedDecl,_removedSig) <- rmDecl n False parsed putRefactParsed parsed' emptyAnns return parsed' -- (_nb,s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (_nb,s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "MoveDef.Md1b.ff" (sourceFromState s) `shouldBe` "module MoveDef.Md1b where\n\ndata D = A | C\n\nff :: Int -> Int\n\nl z =\n let\n ll = 34\n in ll + z\n\n" -- --------------------------------- it "removes a top level declaration, leaving type signature 2" $ do t <- ct $ parsedFileGhc "./MoveDef/Md1.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (22, 1) parsed let comp = do (parsed',_removedDecl,_removedSig) <- rmDecl n False parsed putRefactParsed parsed' emptyAnns logDataWithAnns "parsed'" parsed' return parsed' -- (_nb,s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (_nb,s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "MoveDef.Md1.ff" (sourceFromState s) `shouldBe` "module MoveDef.Md1 where\n\ntoplevel :: Integer -> Integer\ntoplevel x = c * x\n\nc,d :: Integer\nc = 7\nd = 9\n\n-- Pattern bind\ntup :: (Int, Int)\nh :: Int\nt :: Int\ntup@(h,t) = head $ zip [1..10] [3..ff]\n where\n ff :: Int\n ff = 15\n\ndata D = A | B String | C\n\nff :: Int -> Int\n\nl z =\n let\n ll = 34\n in ll + z\n\ndd q = do\n let ss = 5\n return (ss + q)\n\nzz1 a = 1 + toplevel a\n\n-- General Comment\n-- |haddock comment\ntlFunc :: Integer -> Integer\ntlFunc x = c * x\n-- Comment at end\n\n\n" -- --------------------------------- it "removes a top level declaration, and type signature" $ do t <- ct $ parsedFileGhc "./MoveDef/Md1.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (22, 1) parsed let comp = do (newDecls,_removedDecl,_removedSig) <- rmDecl n True parsed putRefactParsed newDecls emptyAnns return newDecls -- (_nb,s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (_nb,s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "MoveDef.Md1.ff" (sourceFromState s) `shouldBe` "module MoveDef.Md1 where\n\ntoplevel :: Integer -> Integer\ntoplevel x = c * x\n\nc,d :: Integer\nc = 7\nd = 9\n\n-- Pattern bind\ntup :: (Int, Int)\nh :: Int\nt :: Int\ntup@(h,t) = head $ zip [1..10] [3..ff]\n where\n ff :: Int\n ff = 15\n\ndata D = A | B String | C\n\nl z =\n let\n ll = 34\n in ll + z\n\ndd q = do\n let ss = 5\n return (ss + q)\n\nzz1 a = 1 + toplevel a\n\n-- General Comment\n-- |haddock comment\ntlFunc :: Integer -> Integer\ntlFunc x = c * x\n-- Comment at end\n\n\n" -- ----------------------------------- it "removes the last local decl in a let/in clause" $ do t <- ct $ parsedFileGhc "./LiftToToplevel/LetIn1.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (11, 22) parsed let comp = do -- parsed <- getRefactParsed (parsed',_removedDecl,_removedSig) <- rmDecl n True parsed putRefactParsed parsed' emptyAnns return parsed' (_nb,s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- (_nb,s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "sq" -- (showToks $ take 20 $ toksFromState s) `shouldBe` "" (sourceFromState s) `shouldBe` "module LiftToToplevel.LetIn1 where\n\n--A definition can be lifted from a where or let to the top level binding group.\n--Lifting a definition widens the scope of the definition.\n\n--In this example, lift 'sq' in 'sumSquares'\n--This example aims to test lifting a definition from a let clause to top level,\n--and the elimination of the keywords 'let' and 'in'\n\nsumSquares x y = sq x + sq y\n where pow=2\n\nanotherFun 0 y = sq y\n where sq x = x^2\n" -- ----------------------------------- it "removes the last local decl in a where clause" $ do t <- ct $ parsedFileGhc "./RmDecl3.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (6, 5) parsed let comp = do (parsed',_removedDecl,_removedSig) <- rmDecl n True parsed putRefactParsed parsed' emptyAnns return parsed' (_nb,s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- (_nb,s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "zz" (sourceFromState s) `shouldBe` "module RmDecl3 where\n\n-- Remove last declaration from a where clause, where should disappear too\nff y = y + zz\n\n-- EOF\n" -- ----------------------------------- it "removes the first local decl in a where clause" $ do t <- ct $ parsedFileGhc "./RmDecl4.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t -- (SYB.showData SYB.Renamer 0 renamed) `shouldBe` "" let Just n = locToNameRdrPure nm (7, 5) parsed let comp = do (parsed',_removedDecl,_removedSig) <- rmDecl n True parsed putRefactParsed parsed' emptyAnns return parsed' (_nb,s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- (_nb,s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "zz" (sourceFromState s) `shouldBe` "{-# LANGUAGE FlexibleContexts #-}\nmodule RmDecl4 where\n\n-- Remove first declaration from a where clause, rest should still be indented\nff y = y + zz ++ xx\n where\n xx = 2\n\n-- EOF\n" -- ----------------------------------- it "removes the non last local decl in a let/in clause 1" $ do t <- ct $ parsedFileGhc "./Demote/LetIn1.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t -- (SYB.showData SYB.Renamer 0 renamed) `shouldBe` "" let Just n = locToNameRdrPure nm (12, 22) parsed let comp = do (parsed',_removedDecl,_removedSig) <- rmDecl n False parsed putRefactParsed parsed' emptyAnns return parsed' (_nb,s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- (_nb,s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "pow" (sourceFromState s) `shouldBe` "module Demote.LetIn1 where\n\n--A definition can be demoted to the local 'where' binding of a friend declaration,\n--if it is only used by this friend declaration.\n\n--Demoting a definition narrows down the scope of the definition.\n--In this example, demote the local 'pow' to 'sq'\n--This example also aims to test the demoting a local declaration in 'let'.\n\nsumSquares x y = let sq 0=0\n sq z=z^pow\n in sq x + sq y\n\n\nanotherFun 0 y = sq y\n where sq x = x^2\n" -- ----------------------------------- it "removes the non last local decl in a let/in clause 2" $ do t <- ct $ parsedFileGhc "./Demote/LetIn2.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (10, 22) parsed let comp = do (parsed',_removedDecl,_removedSig) <- rmDecl n False parsed putRefactParsed parsed' emptyAnns return parsed' (_nb,s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- (_nb,s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "sq" (sourceFromState s) `shouldBe` "module Demote.LetIn2 where\n\n--A definition can be demoted to the local 'where' binding of a friend declaration,\n--if it is only used by this friend declaration.\n\n--Demoting a definition narrows down the scope of the definition.\n--In this example, demote the local 'pow' will fail.\n\nsumSquares x y = let pow=2\n in sq x + sq y +pow\n\n\nanotherFun 0 y = sq y\n where sq x = x^2\n\n " -- ----------------------------------------------------------------- it "removes a decl with a trailing comment" $ do t <- ct $ parsedFileGhc "./Demote/WhereIn3.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (14, 1) parsed let comp = do (parsed',_removedDecl,_removedSig1) <- rmDecl n False parsed putRefactParsed parsed' emptyAnns return parsed' (_nb,s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- (_nb,s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "Demote.WhereIn3.sq" (sourceFromState s) `shouldBe` "module Demote.WhereIn3 where\n\n--A definition can be demoted to the local 'where' binding of a friend declaration,\n--if it is only used by this friend declaration.\n\n--Demoting a definition narrows down the scope of the definition.\n--In this example, demote the top level 'sq' to 'sumSquares'\n--In this case (there are multi matches), the parameters are not folded after demoting.\n\nsumSquares x y = sq p x + sq p y\n where p=2 {-There is a comment-}\n\nsq :: Int -> Int -> Int\n\n{- foo bar -}\nanotherFun 0 y = sq y\n where sq x = x^2\n" -- ----------------------------------------------------------------- it "removes a sub decl liftOneLevel D1" $ do t <- ct $ parsedFileGhc "./LiftOneLevel/D1.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (8, 6) parsed let comp = do (parsed',_removedDecl,_removedSig1) <- rmDecl n False parsed putRefactParsed parsed' emptyAnns return parsed' (_nb,s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- (_nb,s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "sq" (sourceFromState s) `shouldBe` "module LiftOneLevel.D1 where\n\n{-lift 'sq' to top level. This refactoring\naffects module 'D1' and 'C1' -}\n\nsumSquares (x:xs) = sq x + sumSquares xs\n where\n pow =2\n\nsumSquares [] = 0\n\nmain = sumSquares [1..4]\n" -- --------------------------------------------- describe "rmTypeSig" $ do it "removes a type signature from the top level 1" $ do t <- ct $ parsedFileGhc "./MoveDef/Md1.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (22, 1) parsed let comp = do (renamed',sigRemoved) <- rmTypeSig n parsed putRefactParsed renamed' emptyAnns return (renamed',sigRemoved) ((_nb,os),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- ((_nb,os),s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "MoveDef.Md1.ff" (sourceFromState s) `shouldBe` "module MoveDef.Md1 where\n\ntoplevel :: Integer -> Integer\ntoplevel x = c * x\n\nc,d :: Integer\nc = 7\nd = 9\n\n-- Pattern bind\ntup :: (Int, Int)\nh :: Int\nt :: Int\ntup@(h,t) = head $ zip [1..10] [3..ff]\n where\n ff :: Int\n ff = 15\n\ndata D = A | B String | C\n\nff y = y + zz\n where\n zz = 1\n\nl z =\n let\n ll = 34\n in ll + z\n\ndd q = do\n let ss = 5\n return (ss + q)\n\nzz1 a = 1 + toplevel a\n\n-- General Comment\n-- |haddock comment\ntlFunc :: Integer -> Integer\ntlFunc x = c * x\n-- Comment at end\n\n\n" (showGhcQual os) `shouldBe` "Just ff :: Int -> Int" -- ----------------------------------------------------------------- it "removes a type signature from the top level, after decl removed" $ do t <- ct $ parsedFileGhc "./Demote/WhereIn3.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (14, 1) parsed let comp = do (parsed',_removedDecl,_removedSig1) <- rmDecl n False parsed (parsed2,_removedSig2) <- rmTypeSig n parsed' putRefactParsed parsed2 emptyAnns return parsed2 (_nb,s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- (_nb,s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "Demote.WhereIn3.sq" (sourceFromState s) `shouldBe` "module Demote.WhereIn3 where\n\n--A definition can be demoted to the local 'where' binding of a friend declaration,\n--if it is only used by this friend declaration.\n\n--Demoting a definition narrows down the scope of the definition.\n--In this example, demote the top level 'sq' to 'sumSquares'\n--In this case (there are multi matches), the parameters are not folded after demoting.\n\nsumSquares x y = sq p x + sq p y\n where p=2 {-There is a comment-}\n\n{- foo bar -}\nanotherFun 0 y = sq y\n where sq x = x^2\n" -- ----------------------------------------------------------------- it "removes a type signature from non-top level" $ do t <- ct $ parsedFileGhc "./MoveDef/Md1.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (16, 5) parsed let comp = do (renamed',_removedSig) <- rmTypeSig n parsed putRefactParsed renamed' emptyAnns return renamed' -- (_nb,s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (_nb,s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "ff" -- (showToks $ take 20 $ toksFromState s) `shouldBe` "" (sourceFromState s) `shouldBe` "module MoveDef.Md1 where\n\ntoplevel :: Integer -> Integer\ntoplevel x = c * x\n\nc,d :: Integer\nc = 7\nd = 9\n\n-- Pattern bind\ntup :: (Int, Int)\nh :: Int\nt :: Int\ntup@(h,t) = head $ zip [1..10] [3..ff]\n where\n ff = 15\n\ndata D = A | B String | C\n\nff :: Int -> Int\nff y = y + zz\n where\n zz = 1\n\nl z =\n let\n ll = 34\n in ll + z\n\ndd q = do\n let ss = 5\n return (ss + q)\n\nzz1 a = 1 + toplevel a\n\n-- General Comment\n-- |haddock comment\ntlFunc :: Integer -> Integer\ntlFunc x = c * x\n-- Comment at end\n\n\n" -- ----------------------------------------------------------------- it "removes a type signature within multi signatures 1" $ do t <- ct $ parsedFileGhc "./TypeUtils/TypeSigs.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just b = locToNameRdrPure nm (12, 1) parsed let comp = do (renamed',removedSig) <- rmTypeSig b parsed putRefactParsed renamed' emptyAnns return (renamed',removedSig) ((_nb,os),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (exactPrintFromState s (fromJust os)) `shouldBe` "\n\nb::Int->Integer->Char" (showGhcQual b) `shouldBe` "TypeSigs.b" (sourceFromState s) `shouldBe` "module TypeSigs where\n\nsq,anotherFun :: Int -> Int\nsq 0 = 0\nsq z = z^2\n\nanotherFun x = x^2\n\na,c::Int->Integer->Char\n\na x y = undefined\nb x y = undefined\nc x y = undefined\n\n" -- ----------------------------------------------------------------- it "removes a type signature within multi signatures 2" $ do t <- ct $ parsedFileGhc "./TypeUtils/TypeSigs.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (4, 1) parsed let comp = do (renamed',removedSig) <- rmTypeSig n parsed putRefactParsed renamed' emptyAnns return (renamed',removedSig) -- ((_nb,os),s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions ((_nb,os),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- putStrLn $ "anntree\n" ++ showAnnDataFromState s (exactPrintFromState s (fromJust os)) `shouldBe` "\n\nsq :: Int -> Int" (showGhcQual n) `shouldBe` "TypeSigs.sq" (sourceFromState s) `shouldBe` "module TypeSigs where\n\nanotherFun :: Int -> Int\nsq 0 = 0\nsq z = z^2\n\nanotherFun x = x^2\n\na,b,c::Int->Integer->Char\n\na x y = undefined\nb x y = undefined\nc x y = undefined\n\n" (showGhcQual os) `shouldBe` "Just sq :: Int -> Int" -- ----------------------------------------------------------------- it "removes a type signature within multi signatures 3" $ do t <- ct $ parsedFileGhc "./Demote/WhereIn7.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (12, 1) parsed let comp = do (parsed',removedSig) <- rmTypeSig n parsed putRefactParsed parsed' emptyAnns return (parsed',removedSig) -- ((_nb,os),s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions ((_nb,os),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "WhereIn7.sq" (exactPrintFromState s (fromJust os)) `shouldBe` "\n\nsq :: Int -> Int" (sourceFromState s) `shouldBe` "module WhereIn7 where\n\n--A definition can be demoted to the local 'where' binding of a friend declaration,\n--if it is only used by this friend declaration.\n\n--Demoting a definition narrows down the scope of the definition.\n--In this example, demote the top level 'sq' to 'sumSquares'\n--This example also aims to test the split of type signature.\n\nsumSquares x y = sq x + sq y\n\nanotherFun :: Int -> Int\nsq 0 = 0\nsq z = z^pow\n where pow=2\n\nanotherFun x = x^2\n" (showGhcQual os) `shouldBe` "Just sq :: Int -> Int" -- ----------------------------------------------------------------- {- it "removes a type signature for a pattern in a bind" $ do t <- ct $ parsedFileGhc "./LiftToToplevel/PatBindIn1.hs" let renamed = tmRenamedSource t let Just (GHC.L _ n) = locToName (GHC.mkFastString "./test/testdata/LiftToToplevel/PatBindIn1.hs") (18, 7) renamed let comp = do (renamed',removedSig) <- rmTypeSig n renamed let (Just (GHC.L ss _)) = removedSig oldSigToks <- getToksForSpan ss return (renamed',removedSig,oldSigToks) -- ((nb,os,ot),s) <- runRefactGhc comp $ initialState { rsModule = initRefactModule [] t } ((nb,os,ot),s) <- runRefactGhc comp $ initialLogOnState { rsModule = initRefactModule [] t } (showGhcQual n) `shouldBe` "tup" -- (showToks $ take 20 $ toksFromState s) `shouldBe` "" (sourceFromState s) `shouldBe` "module LiftToToplevel.PatBindIn1 where\n\n --A definition can be lifted from a where or let into the surrounding binding group.\n --Lifting a definition widens the scope of the definition.\n\n --In this example, lift 'tup' defined in 'foo'\n --This example aims to test renaming and the lifting of type signatures.\n\n main :: Int\n main = foo 3\n\n foo :: Int -> Int\n foo x = h + t + (snd tup)\n where\n \n \n\n tup@(h,t) = head $ zip [1..10] [3..15]\n " (showGhcQual nb) `shouldBe` "" (showGhcQual os) `shouldBe` "" (GHC.showRichTokenStream ot) `shouldBe` "" -} -- --------------------------------------------- describe "addDecl" $ do it "adds a top level declaration without a type signature, in default pos" $ do t <- ct $ parsedFileGhc "./MoveDef/Md1.hs" let comp = do parsed <- getRefactParsed (decl,declAnns) <- GHC.liftIO $ withDynFlags (\df -> parseDeclToAnnotated df "a" "nn = n2") -- let declAnns' = setPrecedingLines declAnns newDecl 2 parsed' <- addDecl parsed Nothing ([decl],Just declAnns) putRefactParsed parsed' emptyAnns return parsed' (nb,s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- (nb,s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (sourceFromState s) `shouldBe` "module MoveDef.Md1 where\n\nnn = n2\n\ntoplevel :: Integer -> Integer\ntoplevel x = c * x\n\nc,d :: Integer\nc = 7\nd = 9\n\n-- Pattern bind\ntup :: (Int, Int)\nh :: Int\nt :: Int\ntup@(h,t) = head $ zip [1..10] [3..ff]\n where\n ff :: Int\n ff = 15\n\ndata D = A | B String | C\n\nff :: Int -> Int\nff y = y + zz\n where\n zz = 1\n\nl z =\n let\n ll = 34\n in ll + z\n\ndd q = do\n let ss = 5\n return (ss + q)\n\nzz1 a = 1 + toplevel a\n\n-- General Comment\n-- |haddock comment\ntlFunc :: Integer -> Integer\ntlFunc x = c * x\n-- Comment at end\n\n\n" (unspace $ showGhcQual nb) `shouldBe` unspace "module MoveDef.Md1 where\nnn = n2\ntoplevel :: Integer -> Integer\ntoplevel x = c * x\nc, d :: Integer\nc = 7\nd = 9\ntup :: (Int, Int)\nh :: Int\nt :: Int\ntup@(h, t)\n = head $ zip [1 .. 10] [3 .. ff]\n where\n ff :: Int\n ff = 15\ndata D = A | B String | C\nff :: Int -> Int\nff y\n = y + zz\n where\n zz = 1\nl z = let ll = 34 in ll + z\ndd q\n = do { let ss = 5;\n return (ss + q) }\nzz1 a = 1 + toplevel a\ntlFunc :: Integer -> Integer\ntlFunc x = c * x" -- ------------------------------------------- it "adds a top level declaration with a type signature 1" $ do t <- ct $ parsedFileGhc "./MoveDef/Md1.hs" let comp = do parsed <- getRefactParsed (decl,declAnns) <- GHC.liftIO $ withDynFlags (\df -> parseDeclToAnnotated df "decl" "nn = 2") (sig, sigAnns) <- GHC.liftIO $ withDynFlags (\df -> parseDeclToAnnotated df "sig" "nn :: Int") parsed' <- addDecl parsed Nothing ([sig,decl],Just $ mergeAnns sigAnns declAnns) putRefactParsed parsed' emptyAnns return (sig,parsed') ((_hs,nb),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (sourceFromState s) `shouldBe` "module MoveDef.Md1 where\n\nnn :: Int\nnn = 2\n\ntoplevel :: Integer -> Integer\ntoplevel x = c * x\n\nc,d :: Integer\nc = 7\nd = 9\n\n-- Pattern bind\ntup :: (Int, Int)\nh :: Int\nt :: Int\ntup@(h,t) = head $ zip [1..10] [3..ff]\n where\n ff :: Int\n ff = 15\n\ndata D = A | B String | C\n\nff :: Int -> Int\nff y = y + zz\n where\n zz = 1\n\nl z =\n let\n ll = 34\n in ll + z\n\ndd q = do\n let ss = 5\n return (ss + q)\n\nzz1 a = 1 + toplevel a\n\n-- General Comment\n-- |haddock comment\ntlFunc :: Integer -> Integer\ntlFunc x = c * x\n-- Comment at end\n\n\n" (unspace $ showGhcQual nb) `shouldBe` unspace "module MoveDef.Md1 where\nnn :: Int\nnn = 2\ntoplevel :: Integer -> Integer\ntoplevel x = c * x\nc, d :: Integer\nc = 7\nd = 9\ntup :: (Int, Int)\nh :: Int\nt :: Int\ntup@(h, t)\n = head $ zip [1 .. 10] [3 .. ff]\n where\n ff :: Int\n ff = 15\ndata D = A | B String | C\nff :: Int -> Int\nff y\n = y + zz\n where\n zz = 1\nl z = let ll = 34 in ll + z\ndd q\n = do { let ss = 5;\n return (ss + q) }\nzz1 a = 1 + toplevel a\ntlFunc :: Integer -> Integer\ntlFunc x = c * x" -- ------------------------------------------- it "adds a top level declaration after a specified one 1" $ do t <- ct $ parsedFileGhc "./MoveDef/Md1.hs" let comp = do parsed <- getRefactParsed (decl,declAnns) <- GHC.liftIO $ withDynFlags (\df -> parseDeclToAnnotated df "a" "nn = nn2") nm <- getRefactNameMap let Just n = locToNameRdrPure nm (21, 1) parsed parsed' <- addDecl parsed (Just n) ([decl],Just declAnns) putRefactParsed parsed' emptyAnns return (n,parsed') ((n,nb),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- ((n,nb),s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "MoveDef.Md1.ff" (sourceFromState s) `shouldBe` "module MoveDef.Md1 where\n\ntoplevel :: Integer -> Integer\ntoplevel x = c * x\n\nc,d :: Integer\nc = 7\nd = 9\n\n-- Pattern bind\ntup :: (Int, Int)\nh :: Int\nt :: Int\ntup@(h,t) = head $ zip [1..10] [3..ff]\n where\n ff :: Int\n ff = 15\n\ndata D = A | B String | C\n\nff :: Int -> Int\nff y = y + zz\n where\n zz = 1\n\nnn = nn2\n\nl z =\n let\n ll = 34\n in ll + z\n\ndd q = do\n let ss = 5\n return (ss + q)\n\nzz1 a = 1 + toplevel a\n\n-- General Comment\n-- |haddock comment\ntlFunc :: Integer -> Integer\ntlFunc x = c * x\n-- Comment at end\n\n\n" (unspace $ showGhcQual nb) `shouldBe` unspace "module MoveDef.Md1 where\ntoplevel :: Integer -> Integer\ntoplevel x = c * x\nc, d :: Integer\nc = 7\nd = 9\ntup :: (Int, Int)\nh :: Int\nt :: Int\ntup@(h, t)\n = head $ zip [1 .. 10] [3 .. ff]\n where\n ff :: Int\n ff = 15\ndata D = A | B String | C\nff :: Int -> Int\nff y\n = y + zz\n where\n zz = 1\nnn = nn2\nl z = let ll = 34 in ll + z\ndd q\n = do { let ss = 5;\n return (ss + q) }\nzz1 a = 1 + toplevel a\ntlFunc :: Integer -> Integer\ntlFunc x = c * x" -- ------------------------------------------- it "adds a top level declaration after a specified one 2" $ do t <- ct $ parsedFileGhc "./AddOneParameter/FunIn1.hs" let comp = do parsed <- getRefactParsed (decl,declAnns) <- GHC.liftIO $ withDynFlags (\df -> parseDeclToAnnotated df "a" "nn = nn2") nm <- getRefactNameMap let Just n = locToNameRdrPure nm (7, 1) parsed parsed' <- addDecl parsed (Just n) ([decl],Just declAnns) putRefactParsed parsed' emptyAnns return (n,parsed') ((n,nb),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- ((n,nb),s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "FunIn1.foo" -- putStrLn (sourceFromState s) (sourceFromState s) `shouldBe` "module FunIn1 where\n\n--Default parameters can be added to definition of functions and simple constants.\n\n--In this example: add parameter 'y' to 'foo'\nfoo :: Int -> Int\nfoo x= h + t where (h,t) = head $ zip [1..x] [3..15] {-There\nis a comment-}\n\nnn = nn2\n\nmain :: Int\nmain = foo 4\n" (unspace $ showGhcQual nb) `shouldBe` unspace "module FunIn1 where\nfoo :: Int -> Int\nfoo x\n = h + t\n where\n (h, t) = head $ zip [1 .. x] [3 .. 15]\nnn = nn2\nmain :: Int\nmain = foo 4" -- ------------------------------------------- it "adds a top level declaration with a type signature after a specified one" $ do t <- ct $ parsedFileGhc "./MoveDef/Md1.hs" let comp = do parsed <- getRefactParsed nm <- getRefactNameMap let Just n = locToNameRdrPure nm (21, 1) parsed (decl,declAnns) <- GHC.liftIO $ withDynFlags (\df -> parseDeclToAnnotated df "decl" "nn = nn2") (sig, sigAnns) <- GHC.liftIO $ withDynFlags (\df -> parseDeclToAnnotated df "sig" "nn :: Int") parsed' <- addDecl parsed (Just n) ([sig,decl],Just $ mergeAnns sigAnns declAnns) putRefactParsed parsed' emptyAnns return (n,parsed') ((nn,nb),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual nn) `shouldBe` "MoveDef.Md1.ff" (sourceFromState s) `shouldBe`"module MoveDef.Md1 where\n\ntoplevel :: Integer -> Integer\ntoplevel x = c * x\n\nc,d :: Integer\nc = 7\nd = 9\n\n-- Pattern bind\ntup :: (Int, Int)\nh :: Int\nt :: Int\ntup@(h,t) = head $ zip [1..10] [3..ff]\n where\n ff :: Int\n ff = 15\n\ndata D = A | B String | C\n\nff :: Int -> Int\nff y = y + zz\n where\n zz = 1\n\nnn :: Int\nnn = nn2\n\nl z =\n let\n ll = 34\n in ll + z\n\ndd q = do\n let ss = 5\n return (ss + q)\n\nzz1 a = 1 + toplevel a\n\n-- General Comment\n-- |haddock comment\ntlFunc :: Integer -> Integer\ntlFunc x = c * x\n-- Comment at end\n\n\n" (unspace $ showGhcQual nb) `shouldBe` unspace "module MoveDef.Md1 where\ntoplevel :: Integer -> Integer\ntoplevel x = c * x\nc, d :: Integer\nc = 7\nd = 9\ntup :: (Int, Int)\nh :: Int\nt :: Int\ntup@(h, t)\n = head $ zip [1 .. 10] [3 .. ff]\n where\n ff :: Int\n ff = 15\ndata D = A | B String | C\nff :: Int -> Int\nff y\n = y + zz\n where\n zz = 1\nnn :: Int\nnn = nn2\nl z = let ll = 34 in ll + z\ndd q\n = do { let ss = 5;\n return (ss + q) }\nzz1 a = 1 + toplevel a\ntlFunc :: Integer -> Integer\ntlFunc x = c * x" -- ------------------------------------------- it "adds a local declaration without a type signature 1" $ do t <- ct $ parsedFileGhc "./MoveDef/Md1.hs" let comp = do parsed <- getRefactParsed nm <- getRefactNameMap let Just tl = locToNameRdrPure nm (4, 1) parsed decls <- liftT (hsDecls parsed) let [tlDecl] = definingDeclsRdrNames nm [tl] decls False False (decl,declAnns) <- GHC.liftIO $ withDynFlags (\df -> parseDeclToAnnotated df "decl" "nn = nn2") newDecl <- addDecl tlDecl Nothing ([decl],Just declAnns) logm $ "test:addDecl done" return (tlDecl,newDecl) -- ((tl,nb),s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions ((tl,nb),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual tl) `shouldBe` "toplevel x = c * x" (exactPrintFromState s nb) `shouldBe` "\ntoplevel x = c * x\n where\n nn = nn2" (showGhcQual nb) `shouldBe` "toplevel x\n = c * x\n where\n nn = nn2" -- ------------------------------------------- it "adds a local declaration with a type signature 1" $ do t <- ct $ parsedFileGhc "./MoveDef/Md1.hs" let comp = do parsed <- getRefactParsed nm <- getRefactNameMap let Just tl = locToNameRdrPure nm (4, 1) parsed decls <- liftT (hsDecls parsed) let [tlDecl] = definingDeclsRdrNames nm [tl] decls False False (decl,declAnns) <- GHC.liftIO $ withDynFlags (\df -> parseDeclToAnnotated df "decl" "nn = nn2") (sig, sigAnns) <- GHC.liftIO $ withDynFlags (\df -> parseDeclToAnnotated df "sig" "nn :: Int") newDecl <- addDecl tlDecl Nothing ([sig,decl],Just $ mergeAnns sigAnns declAnns) return (tlDecl,newDecl) ((tl,nb),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- ((tl,nb),s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual tl) `shouldBe` "toplevel x = c * x" -- putStrLn (showAnnDataItemFromState s nb) (exactPrintFromState s nb) `shouldBe` "\ntoplevel x = c * x\n where\n nn :: Int\n nn = nn2" (showGhcQual nb) `shouldBe` "toplevel x\n = c * x\n where\n nn = nn2\n nn :: Int" -- ------------------------------------------- it "adds a local declaration with a where clause" $ do t <- ct $ parsedFileGhc "./MoveDef/Demote.hs" let comp = do parsed <- getRefactParsed nm <- getRefactNameMap let Just tl = locToNameRdrPure nm (4, 1) parsed decls <- liftT (hsDecls parsed) let [tlDecl] = definingDeclsRdrNames nm [tl] decls False False (decl,declAnns) <- GHC.liftIO $ withDynFlags (\df -> parseDeclToAnnotated df "decl" "nn = nn2") newDecl <- addDecl tlDecl Nothing ([decl],Just declAnns) return (tlDecl,newDecl) ((tl,nb),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual tl) `shouldBe` "toplevel x = c * x" (exactPrintFromState s nb) `shouldBe` "\ntoplevel x = c * x\n where\n nn = nn2" (showGhcQual nb) `shouldBe` "toplevel x\n = c * x\n where\n nn = nn2" -- ------------------------------------------- it "adds a local declaration to an existing one" $ do t <- ct $ parsedFileGhc "./MoveDef/Md2.hs" let comp = do parsed <- getRefactParsed nm <- getRefactNameMap let Just tl = locToNameRdrPure nm (4, 1) parsed decls <- liftT (hsDecls parsed) let [tlDecl] = definingDeclsRdrNames nm [tl] decls False False (decl,declAnns) <- GHC.liftIO $ withDynFlags (\df -> parseDeclToAnnotated df "decl" "nn = nn2") newDecl <- addDecl tlDecl Nothing ([decl],Just declAnns) return (tlDecl,newDecl) ((tl,nb),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- ((tl,nb),s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual tl) `shouldBe` "toplevel x\n = c * x * b\n where\n b = 3" (exactPrintFromState s nb) `shouldBe` "\ntoplevel x = c * x * b\n where\n nn = nn2\n\n b = 3" (showGhcQual nb) `shouldBe` "toplevel x\n = c * x * b\n where\n b = 3\n nn = nn2" -- ------------------------------------------- it "adds a local declaration with a type signature to an existing one" $ do t <- ct $ parsedFileGhc "./MoveDef/Md2.hs" let comp = do parsed <- getRefactParsed nm <- getRefactNameMap let Just tl = locToNameRdrPure nm (4, 1) parsed decls <- liftT (hsDecls parsed) let [tlDecl] = definingDeclsRdrNames nm [tl] decls False False (decl,declAnns) <- GHC.liftIO $ withDynFlags (\df -> parseDeclToAnnotated df "decl" "nn = nn2") (sig, sigAnns) <- GHC.liftIO $ withDynFlags (\df -> parseDeclToAnnotated df "sig" "nn :: Int") newDecl <- addDecl tlDecl Nothing ([sig,decl],Just $ mergeAnns sigAnns declAnns) return (tlDecl,newDecl) ((tl,nb),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual tl) `shouldBe` "toplevel x\n = c * x * b\n where\n b = 3" (exactPrintFromState s nb) `shouldBe` "\ntoplevel x = c * x * b\n where\n nn :: Int\n nn = nn2\n\n b = 3" (showGhcQual nb) `shouldBe` "toplevel x\n = c * x * b\n where\n b = 3\n nn = nn2\n nn :: Int" -- ------------------------------------------- it "adds a local decl with type signature to an existing one, with a comment" $ do t <- ct $ parsedFileGhc "./Demote/WhereIn3.hs" let comp = do parsed <- getRefactParsed nm <- getRefactNameMap let Just tl = locToNameRdrPure nm (10, 1) parsed decls <- liftT (hsDecls parsed) let [tlDecl] = definingDeclsRdrNames nm [tl] decls True False let Just sq = locToNameRdrPure nm (14, 1) parsed let Just af = locToNameRdrPure nm (18, 1) parsed let [sqSig] = definingSigsRdrNames nm [sq] parsed [sqDecl] = definingDeclsRdrNames nm [sq] decls False False [afDecl] = definingDeclsRdrNames nm [af] decls False False let sqSigDecl = wrapSig sqSig liftT (balanceComments tlDecl sqSigDecl) liftT (balanceComments sqDecl afDecl) newDecl <- addDecl tlDecl Nothing ([sqSigDecl,sqDecl],Nothing) return (sqSig,sqDecl,tlDecl,afDecl,newDecl) -- ((sigs,_sd,tl,aa,nb),s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions ((sigs,_sd,tl,aa,nb),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual sigs) `shouldBe` "sq :: Int -> Int -> Int" (showGhcQual tl) `shouldBe` "sumSquares x y\n = sq p x + sq p y\n where\n p = 2" (showGhcQual aa) `shouldBe` "anotherFun 0 y\n = sq y\n where\n sq x = x ^ 2" (exactPrintFromState s nb) `shouldBe` "\n\n--A definition can be demoted to the local 'where' binding of a friend declaration,\n--if it is only used by this friend declaration.\n\n--Demoting a definition narrows down the scope of the definition.\n--In this example, demote the top level 'sq' to 'sumSquares'\n--In this case (there are multi matches), the parameters are not folded after demoting.\n\nsumSquares x y = sq p x + sq p y\n where sq :: Int -> Int -> Int\n sq pow 0 = 0\n sq pow z = z^pow --there is a comment\n\n p=2 {-There is a comment-}" (showGhcQual nb) `shouldBe` "sumSquares x y\n = sq p x + sq p y\n where\n p = 2\n sq :: Int -> Int -> Int\n sq pow 0 = 0\n sq pow z = z ^ pow" -- ------------------------------------------- it "does not add a local decl to a FunBind with multiple matches" $ do t <- ct $ parsedFileGhc "./MoveDef/MultiFunBind1.hs" let comp = do parsed <- getRefactParsed nm <- getRefactNameMap let Just tl = locToNameRdrPure nm (3, 1) parsed decls <- liftT (hsDecls parsed) let -- decls = hsBinds parsed [tlDecl] = definingDeclsRdrNames nm [tl] decls True False let Just y = locToNameRdrPure nm (6, 1) parsed let [yDecl] = definingDeclsRdrNames nm [y] decls False False newDecl <- addDecl tlDecl Nothing ([yDecl],Nothing) return (yDecl,tlDecl,newDecl) Just r <- catchException $ runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (isPrefixOf "addDecl:Cannot add a local decl to a FunBind with multiple matches" r) `shouldBe` True -- ------------------------------------------- it "adds a local declaration to a PatBind" $ do t <- ct $ parsedFileGhc "./MoveDef/PatBind1.hs" let comp = do parsed <- getRefactParsed nm <- getRefactNameMap let Just tl = locToNameRdrPure nm (3, 1) parsed decls <- liftT (hsDecls parsed) let [tlDecl] = definingDeclsRdrNames nm [tl] decls True False (decl,declAnns) <- GHC.liftIO $ withDynFlags (\df -> parseDeclToAnnotated df "decl" "nn = nn2") newDecl <- addDecl tlDecl Nothing ([decl],Just declAnns) return (tlDecl,newDecl) ((tl,nb),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- ((tl,nb),s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual tl) `shouldBe` "tup@(h, t) = (x, 1)" (exactPrintFromState s nb) `shouldBe` "\n\ntup@(h,t) = (x,1)\n where\n nn = nn2" (showGhcQual nb) `shouldBe` "tup@(h, t)\n = (x, 1)\n where\n nn = nn2" -- --------------------------------------------- describe "renamePN" $ do it "replaces a Name with another 1" $ do t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let comp = do parsed <- getRefactParsed nm <- getRefactNameMap let Just n' = locToNameRdrPure nm (3, 1) parsed newName <- mkNewGhcName Nothing "bar2" new <- renamePN n' newName PreserveQualify parsed putRefactParsed new emptyAnns return (new,newName,n') let ((nb,nn,n),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual (n,nn)) `shouldBe` "(DupDef.Dd1.toplevel, bar2)" (sourceFromState s) `shouldBe` "module DupDef.Dd1 where\n\nbar2 :: Integer -> Integer\nbar2 x = c * x\n\nc,d :: Integer\nc = 7\nd = 9\n\n-- Pattern bind\ntup :: (Int, Int)\nh :: Int\nt :: Int\ntup@(h,t) = head $ zip [1..10] [3..ff]\n where\n ff :: Int\n ff = 15\n\ndata D = A | B String | C\n\nff y = y + zz\n where\n zz = 1\n\nl z =\n let\n ll = 34\n in ll + z\n\ndd q = do\n let ss = 5\n return (ss + q)\n\n" (showGhcQual nb) `shouldBe` "module DupDef.Dd1 where\nbar2 :: Integer -> Integer\nbar2 x = c * x\nc, d :: Integer\nc = 7\nd = 9\ntup :: (Int, Int)\nh :: Int\nt :: Int\ntup@(h, t)\n = head $ zip [1 .. 10] [3 .. ff]\n where\n ff :: Int\n ff = 15\ndata D = A | B String | C\nff y\n = y + zz\n where\n zz = 1\nl z = let ll = 34 in ll + z\ndd q\n = do { let ss = 5;\n return (ss + q) }" -- ----------------------------------------------------------------- it "replaces a Name with another 2" $ do t <- ct $ parsedFileGhc "./Demote/WhereIn4.hs" let comp = do parsed <- getRefactParsed nm <- getRefactNameMap declsr <- liftT $ hsDecls parsed let decl = head $ drop 0 declsr let Just n' = locToNameRdrPure nm (11, 21) parsed newName <- mkNewGhcName Nothing "p_1" new <- renamePN n' newName PreserveQualify decl parsed' <- liftT $ replaceDecls parsed (new:tail declsr) putRefactParsed parsed' emptyAnns return (new,newName,decl,n') let ((nb,nn,d,n),s) <- ct $ runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual d) `shouldBe` "sumSquares x y\n = sq p x + sq p y\n where\n p = 2" (showGhcQual (n,nn)) `shouldBe` "(p, p_1)" (sourceFromState s) `shouldBe` "module Demote.WhereIn4 where\n\n--A definition can be demoted to the local 'where' binding of a friend declaration,\n--if it is only used by this friend declaration.\n\n--Demoting a definition narrows down the scope of the definition.\n--In this example, demote the top level 'sq' to 'sumSquares'\n--In this case (there is single matches), if possible,\n--the parameters will be folded after demoting and type sigature will be removed.\n\nsumSquares x y = sq p_1 x + sq p_1 y\n where p_1=2 {-There is a comment-}\n\nsq::Int->Int->Int\nsq pow z = z^pow --there is a comment\n\nanotherFun 0 y = sq y\n where sq x = x^2\n\n" (showGhcQual nb) `shouldBe` "sumSquares x y\n = sq p_1 x + sq p_1 y\n where\n p_1 = 2" -- --------------------------------- it "replaces a Name with another in limited scope 1" $ do t <- ct $ parsedFileGhc "./TokenTest.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (19, 1) parsed (showGhcQual n) `shouldBe` "TokenTest.foo" let comp = do -- parsed <- getRefactParsed decls <- liftT $ hsDecls parsed newName <- mkNewGhcName Nothing "bar2" new <- renamePN n newName PreserveQualify (head $ drop 3 decls) parsed' <- liftT $ replaceDecls parsed (take 3 decls ++ [new] ++ drop 4 decls) putRefactParsed parsed' emptyAnns return (new,newName) let ((nb,nn),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- ((nb,nn),s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual (n,nn)) `shouldBe` "(TokenTest.foo, bar2)" (sourceFromState s) `shouldBe` "module TokenTest where\n\n-- Test new style token manager\n\nbob a b = x\n where x = 3\n\nbib a b = x\n where\n x = 3\n\n\nbab a b =\n let bar = 3\n in b + bar -- ^trailing comment\n\n\n-- leading comment\nbar2 x y =\n do c <- getChar\n return c\n\n\n\n\n" (showGhcQual nb) `shouldBe` "bar2 x y\n = do { c <- getChar;\n return c }" -- (showToks $ take 20 $ toksFromState s) `shouldBe` "" -- --------------------------------- it "replace a Name with another in limited scope 2" $ do t <- ct $ parsedFileGhc "./TokenTest.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (19, 1) parsed (showGhcQual n) `shouldBe` "TokenTest.foo" let comp = do -- parsed <- getRefactParsed decls <- liftT $ hsDecls parsed let decl = head $ drop 3 decls newName <- mkNewGhcName Nothing "bar2" new <- renamePN n newName PreserveQualify decl parsed' <- liftT $ replaceDecls parsed (take 3 decls ++ [new] ++ drop 4 decls) putRefactParsed parsed' emptyAnns return (new,newName) ((nb,_nn),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "TokenTest.foo" (sourceFromState s) `shouldBe` "module TokenTest where\n\n-- Test new style token manager\n\nbob a b = x\n where x = 3\n\nbib a b = x\n where\n x = 3\n\n\nbab a b =\n let bar = 3\n in b + bar -- ^trailing comment\n\n\n-- leading comment\nbar2 x y =\n do c <- getChar\n return c\n\n\n\n\n" (showGhcQual nb) `shouldBe` "bar2 x y\n = do { c <- getChar;\n return c }" -- (showToks $ take 20 $ toksFromState s) `shouldBe` "" ------------------------------------ it "replaces a name in a data declaration too" $ do t <- ct $ parsedFileGhc "./Renaming/Field1.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (5, 19) parsed let comp = do logParsedSource "parsed" logm $ "nm:" ++ showNameMap nm logm $ "n:nameUnique:" ++ show (GHC.nameUnique n) newName <- mkNewGhcName Nothing "pointx1" new <- renamePN n newName PreserveQualify parsed putRefactParsed new emptyAnns logParsedSource "parsed:after" return (new,newName) let ((nb,_nn),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- ((nb,_nn),s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "Field1.pointx" (sourceFromState s) `shouldBe` "module Field1 where\n\n--Rename field name 'pointx' to 'pointx1'\n\ndata Point = Pt {pointx1, pointy :: Float} deriving Show\n\nabsPoint :: Point -> Float\nabsPoint p = sqrt (pointx1 p * pointx1 p +\n pointy p * pointy p)\n\n" (unspace $ showGhcQual nb) `shouldBe` "module Field1 where\ndata Point\n = Pt {pointx1, pointy :: Float}\n deriving (Show)\nabsPoint :: Point -> Float\nabsPoint p = sqrt (pointx1 p * pointx1 p + pointy p * pointy p)" ------------------------------------ it "replaces a name in a type signature too" $ do t <- ct $ parsedFileGhc "./Renaming/Field1.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (5, 6) parsed let comp = do logParsedSource "parsed" newName <- mkNewGhcName Nothing "NewPoint" new <- renamePN n newName PreserveQualify parsed putRefactParsed new emptyAnns logParsedSource "parsed:after" return (new,newName) let ((nb,_nn),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- ((nb,nn),s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "Field1.Point" (sourceFromState s) `shouldBe` "module Field1 where\n\n--Rename field name 'pointx' to 'pointx1'\n\ndata NewPoint = Pt {pointx, pointy :: Float} deriving Show\n\nabsPoint :: NewPoint -> Float\nabsPoint p = sqrt (pointx p * pointx p +\n pointy p * pointy p)\n\n" (unspace $ showGhcQual nb) `shouldBe` "module Field1 where\ndata NewPoint\n = Pt {pointx, pointy :: Float}\n deriving (Show)\nabsPoint :: NewPoint -> Float\nabsPoint p = sqrt (pointx p * pointx p + pointy p * pointy p)" ------------------------------------ it "replace a name in a FunBind with multiple patterns" $ do t <- ct $ parsedFileGhc "./LocToName.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (20, 1) parsed let comp = do newName <- mkNewGhcName Nothing "newPoint" new <- renamePN n newName PreserveQualify parsed putRefactParsed new emptyAnns return (new,newName) let ((nb,_nn),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "LocToName.sumSquares" (sourceFromState s) `shouldBe` "module LocToName where\n\n{-\n\n\n\n\n\n\n\n\n-}\n\n\n\n\n\n\n\nnewPoint (x:xs) = x ^2 + newPoint xs\n -- where sq x = x ^pow \n -- pow = 2\n\nnewPoint [] = 0\n" (unspace $ showGhcQual nb) `shouldBe` "module LocToName where\nnewPoint (x : xs) = x ^ 2 + newPoint xs\nnewPoint [] = 0" ------------------------------------ it "replaces a qualified name in a FunBind with multiple patterns" $ do t <- ct $ parsedFileGhc "./LocToName.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t #if __GLASGOW_HASKELL__ <= 710 let modu = GHC.mkModule (GHC.stringToPackageKey "mypackage-1.0") (GHC.mkModuleName "LocToName") #else let modu = GHC.mkModule (GHC.stringToUnitId "mypackage-1.0") (GHC.mkModuleName "LocToName") #endif let Just n = locToNameRdrPure nm (20, 1) parsed let comp = do -- logm $ "renamed:" ++ (SYB.showData SYB.Renamer 0 renamed) logDataWithAnns "parsed" parsed newName <- mkNewGhcName (Just modu) "newPoint" new <- renamePN n newName Qualify parsed putRefactParsed new emptyAnns -- logParsedSource "parsed:after" return (new,newName) ((nb,_nn),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- ((nb,_nn),s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "LocToName.sumSquares" (unspace $ showGhcQual nb) `shouldBe` "module LocToName where\nLocToName.newPoint (x : xs) = x ^ 2 + LocToName.newPoint xs\nLocToName.newPoint [] = 0" (sourceFromState s) `shouldBe` "module LocToName where\n\n{-\n\n\n\n\n\n\n\n\n-}\n\n\n\n\n\n\n\nnewPoint (x:xs) = x ^2 + LocToName.newPoint xs\n -- where sq x = x ^pow \n -- pow = 2\n\nnewPoint [] = 0\n" ------------------------------------ it "replaces a parameter name in a FunBind" $ do t <- ct $ parsedFileGhc "./Renaming/LayoutIn2.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (8, 7) parsed let comp = do logParsedSource "parsed" newName <- mkNewGhcName Nothing "ls" new <- renamePN n newName PreserveQualify parsed putRefactParsed new emptyAnns logParsedSource "parsed:after" return (new,newName) ((nb,_nn),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- ((nb,_nn),s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (sourceFromState s) `shouldBe` "module LayoutIn2 where\n\n--Layout rule applies after 'where','let','do' and 'of'\n\n--In this Example: rename 'list' to 'ls'.\n\nsilly :: [Int] -> Int\nsilly ls = case ls of (1:xs) -> 1\n--There is a comment\n (2:xs)\n | x < 10 -> 4 where x = last xs\n otherwise -> 12\n" (unspace $ showGhcQual nb) `shouldBe` "module LayoutIn2 where\nsilly :: [Int] -> Int\nsilly ls\n = case ls of {\n (1 : xs) -> 1\n (2 : xs)\n | x < 10 -> 4\n where\n x = last xs\n otherwise -> 12 }" ------------------------------------ it "does not qualify a name in an import hiding clause" $ do t <- ct $ parsedFileGhc "./ScopeAndQual.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t #if __GLASGOW_HASKELL__ <= 710 let modu = GHC.mkModule (GHC.stringToPackageKey "mypackage-1.0") (GHC.mkModuleName "LocToName") #else let modu = GHC.mkModule (GHC.stringToUnitId "mypackage-1.0") (GHC.mkModuleName "LocToName") #endif let Just n = locToNameRdrPure nm (4, 24) parsed let comp = do logParsedSource "parsed" newName <- mkNewGhcName (Just modu) "mySum" new <- renamePN n newName Qualify parsed putRefactParsed new emptyAnns return (new,newName) ((nb,_nn),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- ((nb,_nn),s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "Data.Foldable.sum" (sourceFromState s) `shouldBe` "module ScopeAndQual where\n\nimport qualified Data.List as L\nimport Prelude hiding (mySum)\n\nmain :: IO ()\nmain = putStrLn (show $ L.mySum [1,2,3])\n\nsum a b = a + b\n\nsumSquares xs = L.mySum $ map (\\x -> x*x) xs\n\nmySumSq = sumSquares\n" (unspace $ showGhcQual nb) `shouldBe` "module ScopeAndQual where\nimport qualified Data.List as L\nimport Prelude hiding ( mySum )\nmain :: IO ()\nmain = putStrLn (show $ L.mySum [1, 2, 3])\nsum a b = a + b\nsumSquares xs = L.mySum $ map (\\ x -> x * x) xs\nmySumSq = sumSquares" ------------------------------------ it "does not qualify the subject of a type signature" $ do t <- ct $ parsedFileGhc "./Renaming/C7.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t #if __GLASGOW_HASKELL__ <= 710 let modu = GHC.mkModule (GHC.stringToPackageKey "mypackage-1.0") (GHC.mkModuleName "LocToName") #else let modu = GHC.mkModule (GHC.stringToUnitId "mypackage-1.0") (GHC.mkModuleName "LocToName") #endif let Just n = locToNameRdrPure nm (5, 1) parsed let comp = do logParsedSource "parsed" newName <- mkNewGhcName (Just modu) "myNewFringe" new <- renamePN n newName Qualify parsed putRefactParsed new emptyAnns return (new,newName) ((nb,_nn),s) <- ct $ runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- ((nb,_nn),s) <- ct $ runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "Renaming.C7.myFringe" (sourceFromState s) `shouldBe` "module Renaming.C7(LocToName.myNewFringe) where\n\nimport Renaming.D7\n\nmyNewFringe:: Tree a -> [a]\nmyNewFringe (Leaf x ) = [x]\nmyNewFringe (Branch left right) = LocToName.myNewFringe left ++ fringe right\n\n\n\n\n" (unspace $ showGhcQual nb) `shouldBe` "module Renaming.C7 (\n LocToName.myNewFringe\n ) where\nimport Renaming.D7\nmyNewFringe :: Tree a -> [a]\nLocToName.myNewFringe (Leaf x) = [x]\nLocToName.myNewFringe (Branch left right)\n = LocToName.myNewFringe left ++ fringe right" ------------------------------------ it "realigns in a case for a shorter name" $ do t <- ct $ parsedFileGhc "./Renaming/LayoutIn2.hs" let renamed = tmRenamedSource t let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (8, 7) parsed let comp = do logm $ "renamed:" ++ (SYB.showData SYB.Renamer 0 renamed) newName <- mkNewGhcName Nothing "ls" new <- renamePN n newName PreserveQualify parsed putRefactParsed new emptyAnns return (new,newName) ((nb,_nn),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "list" (sourceFromState s) `shouldBe` "module LayoutIn2 where\n\n--Layout rule applies after 'where','let','do' and 'of'\n\n--In this Example: rename 'list' to 'ls'.\n\nsilly :: [Int] -> Int\nsilly ls = case ls of (1:xs) -> 1\n--There is a comment\n (2:xs)\n | x < 10 -> 4 where x = last xs\n otherwise -> 12\n" (unspace $ showGhcQual nb) `shouldBe` "module LayoutIn2 where\nsilly :: [Int] -> Int\nsilly ls\n = case ls of {\n (1 : xs) -> 1\n (2 : xs)\n | x < 10 -> 4\n where\n x = last xs\n otherwise -> 12 }" ------------------------------------ it "realigns in a case for a longer name" $ do t <- ct $ parsedFileGhc "./Renaming/LayoutIn2.hs" let renamed = tmRenamedSource t let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (8, 7) parsed let comp = do logm $ "renamed:" ++ (SYB.showData SYB.Renamer 0 renamed) newName <- mkNewGhcName Nothing "listlonger" new <- renamePN n newName PreserveQualify parsed putRefactParsed new emptyAnns return (new,newName) ((nb,_nn),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "list" (sourceFromState s) `shouldBe` "module LayoutIn2 where\n\n--Layout rule applies after 'where','let','do' and 'of'\n\n--In this Example: rename 'list' to 'ls'.\n\nsilly :: [Int] -> Int\nsilly listlonger = case listlonger of (1:xs) -> 1\n --There is a comment\n (2:xs)\n | x < 10 -> 4 where x = last xs\n otherwise -> 12\n" (unspace $ showGhcQual nb) `shouldBe` "module LayoutIn2 where\nsilly :: [Int] -> Int\nsilly listlonger\n = case listlonger of {\n (1 : xs) -> 1\n (2 : xs)\n | x < 10 -> 4\n where\n x = last xs\n otherwise -> 12 }" ------------------------------------ it "realigns in a do for a shorter name" $ do t <- ct $ parsedFileGhc "./Renaming/LayoutIn4.hs" let renamed = tmRenamedSource t let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (7, 8) parsed let comp = do logm $ "renamed:" ++ (SYB.showData SYB.Renamer 0 renamed) newName <- mkNewGhcName Nothing "io" new <- renamePN n newName PreserveQualify parsed putRefactParsed new emptyAnns return (new,newName) ((nb,_nn),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "ioFun" (sourceFromState s) `shouldBe` "module LayoutIn4 where\n\n--Layout rule applies after 'where','let','do' and 'of'\n\n--In this Example: rename 'ioFun' to 'io'\n\nmain = io \"hello\" where io s= do let k = reverse s\n--There is a comment\n s <- getLine\n let q = (k ++ s)\n putStr q\n putStr \"foo\"\n\n" (unspace $ showGhcQual nb) `shouldBe` "module LayoutIn4 where\nmain\n = io \"hello\"\n where\n io s\n = do { let k = reverse s;\n s <- getLine;\n let q = (k ++ s);\n putStr q;\n putStr \"foo\" }" ------------------------------------ it "realigns in a do for a longer name" $ do t <- ct $ parsedFileGhc "./Renaming/LayoutIn4.hs" let renamed = tmRenamedSource t let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (7, 8) parsed let comp = do logm $ "renamed:" ++ (SYB.showData SYB.Renamer 0 renamed) newName <- mkNewGhcName Nothing "ioFunLong" new <- renamePN n newName PreserveQualify parsed putRefactParsed new emptyAnns return (new,newName) ((nb,_nn),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "ioFun" (sourceFromState s) `shouldBe` "module LayoutIn4 where\n\n--Layout rule applies after 'where','let','do' and 'of'\n\n--In this Example: rename 'ioFun' to 'io'\n\nmain = ioFunLong \"hello\" where ioFunLong s= do let k = reverse s\n --There is a comment\n s <- getLine\n let q = (k ++ s)\n putStr q\n putStr \"foo\"\n\n" (unspace $ showGhcQual nb) `shouldBe` "module LayoutIn4 where\nmain\n = ioFunLong \"hello\"\n where\n ioFunLong s\n = do { let k = reverse s;\n s <- getLine;\n let q = (k ++ s);\n putStr q;\n putStr \"foo\" }" ------------------------------------ it "realigns in a where for a shorter name" $ do t <- ct $ parsedFileGhc "./Renaming/LayoutIn1.hs" let renamed = tmRenamedSource t let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (7, 17) parsed let comp = do logm $ "renamed:" ++ (SYB.showData SYB.Renamer 0 renamed) newName <- mkNewGhcName Nothing "q" new <- renamePN n newName PreserveQualify parsed putRefactParsed new emptyAnns return (new,newName) ((nb,_nn),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "sq" (sourceFromState s) `shouldBe` "module LayoutIn1 where\n\n--Layout rule applies after 'where','let','do' and 'of'\n\n--In this Example: rename 'sq' to 'square'.\n\nsumSquares x y= q x + q y where q x= x^pow\n--There is a comment.\n pow=2\n" (unspace $ showGhcQual nb) `shouldBe` "module LayoutIn1 where\nsumSquares x y\n = q x + q y\n where\n q x = x ^ pow\n pow = 2" ------------------------------------ it "realigns in a where for a longer name" $ do t <- ct $ parsedFileGhc "./Renaming/LayoutIn1.hs" -- let renamed = tmRenamedSource t let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (7, 17) parsed let comp = do -- logm $ "renamed:" ++ (SYB.showData SYB.Renamer 0 renamed) logParsedSource "parsed" newName <- mkNewGhcName Nothing "square" new <- renamePN n newName PreserveQualify parsed putRefactParsed new emptyAnns return (new,newName) ((nb,_nn),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- ((nb,_nn),s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "sq" (sourceFromState s) `shouldBe` "module LayoutIn1 where\n\n--Layout rule applies after 'where','let','do' and 'of'\n\n--In this Example: rename 'sq' to 'square'.\n\nsumSquares x y= square x + square y where square x= x^pow\n --There is a comment.\n pow=2\n" (unspace $ showGhcQual nb) `shouldBe` "module LayoutIn1 where\nsumSquares x y\n = square x + square y\n where\n square x = x ^ pow\n pow = 2" ------------------------------------ it "realigns in a let/in for a shorter name" $ do t <- ct $ parsedFileGhc "./TypeUtils/LayoutLet1.hs" let renamed = tmRenamedSource t let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (6, 6) parsed let comp = do logm $ "renamed:" ++ (SYB.showData SYB.Renamer 0 renamed) newName <- mkNewGhcName Nothing "x" new <- renamePN n newName PreserveQualify parsed putRefactParsed new emptyAnns return (new,newName) ((nb,_nn),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "xxx" (sourceFromState s) `shouldBe` "module LayoutLet1 where\n\n-- Simple let expression, rename xxx to something longer or shorter\n-- and the let/in layout should adjust accordingly\n\nfoo x = let a = 1\n b = 2\n in x + a + b\n\n" (unspace $ showGhcQual nb) `shouldBe` "module LayoutLet1 where\nfoo x\n = let\n a = 1\n b = 2\n in x + a + b" ------------------------------------ it "realigns in a let/in for a longer name 1" $ do t <- ct $ parsedFileGhc "./TypeUtils/LayoutLet1.hs" let renamed = tmRenamedSource t let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (6, 6) parsed let comp = do logm $ "renamed:" ++ (SYB.showData SYB.Renamer 0 renamed) newName <- mkNewGhcName Nothing "xxxlong" -- new <- renamePN n newName False renamed new <- renamePN n newName PreserveQualify parsed putRefactParsed new emptyAnns return (new,newName) ((nb,_nn),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- ((nb,nn),s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "xxx" (sourceFromState s) `shouldBe` "module LayoutLet1 where\n\n-- Simple let expression, rename xxx to something longer or shorter\n-- and the let/in layout should adjust accordingly\n\nfoo xxxlong = let a = 1\n b = 2\n in xxxlong + a + b\n\n" (unspace $ showGhcQual nb) `shouldBe` "module LayoutLet1 where\nfoo xxxlong\n = let\n a = 1\n b = 2\n in xxxlong + a + b" ------------------------------------ it "realigns in a let/in for a longer name 2" $ do t <- ct $ parsedFileGhc "./TypeUtils/LayoutLet2.hs" let renamed = tmRenamedSource t let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (7, 6) parsed let comp = do logm $ "renamed:" ++ (SYB.showData SYB.Renamer 0 renamed) newName <- mkNewGhcName Nothing "xxxlong" new <- renamePN n newName PreserveQualify parsed putRefactParsed new emptyAnns return (new,newName) ((nb,nn),s) <- ct $ runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- ((nb,nn),s) <- ct $ runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual (n,nn)) `shouldBe` "(xxx, xxxlong)" (sourceFromState s) `shouldBe` "module LayoutLet2 where\n\n-- Simple let expression, rename xxx to something longer or shorter\n-- and the let/in layout should adjust accordingly\n-- In this case the tokens for xxx + a + b should also shift out\n\nfoo xxxlong = let a = 1\n b = 2 in xxxlong + a + b\n\n" (unspace $ showGhcQual nb) `shouldBe` "module LayoutLet2 where\nfoo xxxlong\n = let\n a = 1\n b = 2\n in xxxlong + a + b" ------------------------------------ it "renames an exported data type" $ do t <- ct $ parsedFileGhc "./Renaming/RenameInExportedType2.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (6, 24) parsed let comp = do logm $ "parsed:" ++ (SYB.showData SYB.Parser 0 parsed) newName <- mkNewGhcName Nothing "NewType" new <- renamePN n newName PreserveQualify parsed putRefactParsed new emptyAnns logm $ "parsed:after" ++ (SYB.showData SYB.Parser 0 new) return (new,newName) ((_nb,nn),s) <- ct $ runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- ((_nb,nn),s) <- ct $ runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual (n,nn)) `shouldBe` "(Renaming.RenameInExportedType.NT, NewType)" (sourceFromState s) `shouldBe` "module Renaming.RenameInExportedType\n (\n MyType (NewType)\n ) where\n\ndata MyType = MT Int | NewType\n\n\n" ------------------------------------ it "renames a qualified usage of a name" $ do t <- ct $ parsedFileGhc "./Renaming/QualClient.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (10, 10) parsed let comp = do logm $ "parsed:" ++ (SYB.showData SYB.Parser 0 parsed) newName <- mkNewGhcName Nothing "foo1" new <- renamePN n newName PreserveQualify parsed putRefactParsed new emptyAnns logm $ "parsed:after" ++ (SYB.showData SYB.Parser 0 new) return (new,newName) ((_nb,nn),s) <- ct $ runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- ((_nb,nn),s) <- ct $ runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual (n,nn)) `shouldBe` "(Renaming.QualServer.foo, foo1)" (sourceFromState s) `shouldBe` "module Renaming.QualClient where\n\n{- foo is imported qualified as in QualClient. Renaming should\n preserve the qualification there\n-}\n\nimport qualified Renaming.QualServer as QS\n\nbaz :: String\nbaz = QS.foo1 : \"hello\"\n" ------------------------------------ it "renames a class op signature" $ do t <- ct $ parsedFileGhc "./Renaming/D4.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (13, 5) parsed let comp = do logm $ "parsed:" ++ (SYB.showData SYB.Parser 0 parsed) newName <- mkNewGhcName Nothing "isSameOrNot" new <- renamePN n newName PreserveQualify parsed putRefactParsed new emptyAnns logm $ "parsed:after" ++ (SYB.showData SYB.Parser 0 new) return (new,newName) ((_nb,nn),s) <- ct $ runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- ((_nb,nn),s) <- ct $ runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual (n,nn)) `shouldBe` "(Renaming.D4.isSame, isSameOrNot)" (sourceFromState s) `shouldBe` "module Renaming.D4 where\n\n{-Rename instance name 'isSame'' to 'sameOrNot'.\n This refactoring affects module `D4', 'B4' and 'C4' -}\n\ndata Tree a = Leaf a | Branch (Tree a) (Tree a)\n\nfringe :: Tree a -> [a]\nfringe (Leaf x ) = [x]\nfringe (Branch left right) = fringe left ++ fringe right\n\nclass SameOrNot a where\n isSameOrNot :: a -> a -> Bool\n isNotSame :: a -> a -> Bool\n\ninstance SameOrNot Int where\n isSameOrNot a b = a == b\n isNotSame a b = a /= b\n\nsumSquares (x:xs) = sq x + sumSquares xs\n where sq x = x ^pow\n pow = 2\n\nsumSquares [] = 0\n" ------------------------------------ it "renames a data decl parameter" $ do t <- ct $ parsedFileGhc "./Renaming/ConstructorIn3.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (9, 13) parsed let comp = do logParsedSource "parsed" newName <- mkNewGhcName Nothing "b" new <- renamePN n newName PreserveQualify parsed putRefactParsed new emptyAnns logParsedSource "parsed:after" return (new,newName) ((_nb,nn),s) <- ct $ runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- ((_nb,nn),s) <- ct $ runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual (n,nn)) `shouldBe` "(a, b)" (sourceFromState s) `shouldBe` "module ConstructorIn3 where\n\n\n--Any type/data constructor name declared in this module can be renamed.\n--Any type variable can be renamed.\n\n--Rename tyoe variable 'a' in BTree to 'b'\n\ndata BTree b = Empty | T b (BTree b) (BTree b)\n deriving Show\n\nbuildtree :: Ord a => [a] -> BTree a\nbuildtree [] = Empty\nbuildtree (x:xs) = insert x (buildtree xs)\n\ninsert :: Ord a => a -> BTree a -> BTree a\ninsert val Empty = T val Empty Empty\ninsert val tree@(T tval left right)\n | val > tval = T tval left (insert val right)\n | otherwise = T tval (insert val left) right\n\nmain :: BTree Int\nmain = buildtree [3,1,2]\n" -- --------------------------------------------- describe "qualifyToplevelName" $ do it "qualifies a name at the top level" $ do t <- ct $ parsedFileGhc "./Renaming/C7.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t nm = initRdrNameMap t let Just n = locToNameRdrPure nm (7, 1) parsed let comp = do qualifyToplevelName n return () let (_,s) <- ct $ runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- (_,s) <- ct $ runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n) `shouldBe` "Renaming.C7.myFringe" (sourceFromState s) `shouldBe` "module Renaming.C7(Renaming.C7.myFringe) where\n\nimport Renaming.D7\n\nmyFringe:: Tree a -> [a]\nmyFringe (Leaf x ) = [x]\nmyFringe (Branch left right) = Renaming.C7.myFringe left ++ fringe right\n\n\n\n\n" -- --------------------------------------------- describe "findEntity" $ do it "returns true if a (Located) Name is part of a HsBind 1" $ do pendingWith "this may go away" {- t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let comp = do parentr <- getRefactRenamed parsed <- getRefactParsed nm <- getRefactNameMap let (Just ln'@(GHC.L l _)) = locToRdrName (4,1) parsed let n = rdrName2NamePure nm ln' ln = GHC.L l n let declsr = hsBinds parentr duplicatedDecls = definingDeclsNames [n] declsr True False res = findEntity ln duplicatedDecls res2 = findEntity n duplicatedDecls -- res = findEntity' ln duplicatedDecls return (res,res2,duplicatedDecls,ln) ((r,r2,d,_l),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual d) `shouldBe` "[DupDef.Dd1.toplevel x = DupDef.Dd1.c GHC.Num.* x]" (showGhcQual _l) `shouldBe` "DupDef.Dd1.toplevel" ("1" ++ show r) `shouldBe` "1True" ("2" ++ show r2) `shouldBe` "2True" -} -- --------------------------------- it "returns true if a (Located) Name is part of a HsBind 2" $ do pendingWith "this may go away" {- t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let comp = do parentr <- getRefactRenamed parsed <- getRefactParsed nm <- getRefactNameMap let (Just ln'@(GHC.L l _)) = locToRdrName (31,7) parsed let n = rdrName2NamePure nm ln' ln = GHC.L l n let (Just nd) = locToNameRdrPure nm (30,1) parsed let declsr = hsBinds parentr duplicatedDecls = definingDeclsNames [nd] declsr True False res = findEntity ln duplicatedDecls res2 = findEntity n duplicatedDecls return (res,res2,duplicatedDecls,ln) ((r,r2,d,_l),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual d) `shouldBe` "[DupDef.Dd1.dd q\n = do { let ss = 5;\n"++ " GHC.Base.return (ss GHC.Num.+ q) }]" (showGhcQual _l) `shouldBe` "ss" ("1" ++ show r) `shouldBe` "1True" ("2" ++ show r2) `shouldBe` "2True" -} -- ----------------------------------------------------------------- it "returns false if a syntax phrase is not part of another" $ do pendingWith "this may go away" {- t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let comp = do parentr <- getRefactRenamed parsed <- getRefactParsed nm <- getRefactNameMap let (Just n) = locToNameRdrPure nm (4,1) parsed let (Just tup) = locToNameRdrPure nm (11,1) parsed let declsr = hsBinds parentr duplicatedDecls = definingDeclsNames [n] declsr True False res = findEntity tup duplicatedDecls -- res = findEntity' ln duplicatedDecls return (res,duplicatedDecls) ((r,d),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual d) `shouldBe` "[DupDef.Dd1.toplevel x = DupDef.Dd1.c GHC.Num.* x]" ("1" ++ show r) `shouldBe` "1False" -} -- ----------------------------------------------------------------- it "Finds an entity in [HsBind Name]" $ do pending -- "write this test" -- ----------------------------------------------------------------- it "Finds an entity in (MatchGroup matches _)" $ do pending -- "write this test" -- ----------------------------------------------------------------- it "Finds an entity in (HsLet decls _)" $ do pending -- "write this test" -- ----------------------------------------------------------------- it "Finds an entity in (HsLet _ e1)" $ do pending -- "write this test" -- ----------------------------------------------------------------- it "Finds an entity in (HsLet decls _)" $ do pending -- "write this test" -- ----------------------------------------------------------------- it "Finds an entity in (PatBind pat rhs _ _ _)" $ do pending -- "write this test" -- ----------------------------------------------------------------- it "Finds an entity in (Match _ _ rhs)" $ do pending -- "write this test" -- ----------------------------------------------------------------- it "Finds an entity in (LetStmt binds)" $ do pending -- "write this test" -- ----------------------------------------------------------------- it "Finds an entity in (BindStmt _ rhs _ _)" $ do pending -- "write this test" -- --------------------------------------------- describe "modIsExported" $ do it "Returns True if the module is explicitly exported" $ do t <- ct $ parsedFileGhc "./FreeAndDeclared/Declare.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t let renamed = tmRenamedSource t let (Just (modName,_)) = getModuleName parsed (modIsExported modName renamed) `shouldBe` True it "Returns True if the module is exported by default" $ do t <- ct $ parsedFileGhc "./FreeAndDeclared/Declare1.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t let renamed = tmRenamedSource t let (Just (modName,_)) = getModuleName parsed (modIsExported modName renamed) `shouldBe` True it "Returns False if the module is explicitly not exported" $ do t <- ct $ parsedFileGhc "./FreeAndDeclared/Declare2.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t let renamed = tmRenamedSource t let (Just (modName,_)) = getModuleName parsed (modIsExported modName renamed) `shouldBe` False -- --------------------------------------------- describe "isExported" $ do it "returns True if a GHC.Name is exported" $ do t <- ct $ parsedFileGhc "./Renaming/B1.hs" let comp = do parsed <- getRefactParsed nm <- getRefactNameMap let (Just myFringe) = locToNameRdrPure nm (11,1) parsed let (Just sumSquares) = locToNameRdrPure nm (15,1) parsed exMyFring <- isExported myFringe exSumSquares <- isExported sumSquares return (myFringe,exMyFring,sumSquares,exSumSquares) ((mf,emf,ss,ess),_s) <- ct $ runRefactGhc comp (initialState { rsModule = initRefactModule [] t}) testOptions (showGhcQual mf) `shouldBe` "Renaming.B1.myFringe" emf `shouldBe` True (showGhcQual ss) `shouldBe` "Renaming.B1.sumSquares" ess `shouldBe` False -- --------------------------------------------- describe "addHiding" $ do it "add a hiding entry to the imports with no existing hiding" $ do t1 <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let comp = do clearParsedModule t2 <- parseSourceFileTest "./DupDef/Dd2.hs" let renamed2 = tmRenamedSource t2 let parsed1 = GHC.pm_parsed_source $ tmParsedModule t1 let parsed2 = GHC.pm_parsed_source $ tmParsedModule t2 let Just (modName,_) = getModuleName parsed1 let n1 = mkRdrName "n1" n2 = mkRdrName "n2" res <- addHiding modName parsed2 [n1,n2] putRefactParsed res emptyAnns return (res,renamed2) ((_r,_r2),s) <- ct $ runRefactGhc comp (initialState { rsModule = initRefactModule [] t1}) testOptions -- ((_r,_r2),s) <- ct $ runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t1}) testOptions -- putStrLn $ showAnnDataFromState s (sourceFromState s) `shouldBe` "module DupDef.Dd2 where\n\nimport DupDef.Dd1 hiding (n1,n2)\n\n\nf2 x = ff (x+1)\n\nmm = 5\n\n\n" ------------------------------------ it "adds a hiding entry to the imports with an existing hiding" $ do t1 <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let comp = do clearParsedModule t2 <- parseSourceFileTest "./DupDef/Dd3.hs" let renamed2 = tmRenamedSource t2 let parsed1 = GHC.pm_parsed_source $ tmParsedModule t1 let parsed2 = GHC.pm_parsed_source $ tmParsedModule t2 -- let mn = locToName (4,1) renamed1 -- let (Just (GHC.L _ _n)) = mn let Just (modName,_) = getModuleName parsed1 let n1 = mkRdrName "n1" n2 = mkRdrName "n2" res <- addHiding modName parsed2 [n1,n2] return (res,renamed2) ((_r,_r2),s) <- ct $ runRefactGhc comp (initialState { rsModule = initRefactModule [] t1}) testOptions (sourceFromState s) `shouldBe` "module DupDef.Dd3 where\n\nimport DupDef.Dd1 hiding (dd,n1,n2)\n\n\nf2 x = ff (x+1)\n\nmm = 5\n\n\n" -- --------------------------------------------- describe "equivalentNameInNewMod" $ do it "finds equivalent name for normal import" $ do let ctc = cdAndDo "./test/testdata/cabal/foo" let comp = do parseSourceFileGhc "./src/Foo/Bar.hs" parsed <- getRefactParsed nm <- getRefactNameMap let Just old = locToNameRdrPure nm (3,1) parsed parseSourceFileGhc "./src/Main.hs" [equiv] <- equivalentNameInNewMod old return (old,equiv) ((o,e),_s) <- ctc $ runRefactGhc comp initialState testOptions -- ((o,e),_s) <- ctc $ runRefactGhc comp initialLogOnState testOptions (showGhcQual (o,e)) `shouldBe` "(Foo.Bar.bar, Foo.Bar.bar)" -- putStrLn( "(GHC.nameUnique o,GHC.nameUnique e)" ++ (showGhcQual (GHC.nameUnique o,GHC.nameUnique e))) -- (GHC.nameUnique o == GHC.nameUnique e) `shouldBe` True -- seems to reuse the already loaded names? -- --------------------------------- it "finds equivalent name for qualified import" $ do let ctc = cdAndDo "./test/testdata/cabal/cabal4" let comp = do parseSourceFileGhc "./src/Foo/Bar.hs" parsed <- getRefactParsed nm <- getRefactNameMap let Just old = locToNameRdrPure nm (3,1) parsed parseSourceFileGhc "./src/main4.hs" parsed' <- getRefactParsed [equiv] <- equivalentNameInNewMod old let Just ((GHC.L _l new)) = locToRdrName (11,12) parsed' return (old,equiv,new) ((o,e,n),_s) <- ctc $ runRefactGhc comp initialState testOptions (showGhcQual (o,e,n)) `shouldBe` "(Foo.Bar.baz, Foo.Bar.baz, B.baz)" -- (showGhcQual (GHC.nameUnique o,GHC.nameUnique e)) `shouldBe` "" -- (GHC.nameUnique o == GHC.nameUnique e) `shouldBe` True -- seems to reuse the already loaded names? -- --------------------------------------------- describe "usedWithoutQualR" $ do it "returns True if the identifier is used unqualified Dd1" $ do t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let comp = do parsed <- getRefactParsed nm <- getRefactNameMap let Just n@name = locToNameRdrPure nm (14,21) parsed let res = usedWithoutQualR name parsed return (res,n,name) ((r,n1,n2),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (GHC.getOccString n2) `shouldBe` "zip" (showGhcQual n1) `shouldBe` "GHC.List.zip" r `shouldBe` True -- --------------------------------- it "returns True if the identifier is used unqualified Dd3" $ do t <- ct $ parsedFileGhc "./DupDef/Dd3.hs" let comp = do parsed <- getRefactParsed nm <- getRefactNameMap let Just n@name = locToNameRdrPure nm (8,1) parsed let res = usedWithoutQualR name parsed return (res,n,name) ((r,n1,n2),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (GHC.getOccString n2) `shouldBe` "mm" (showGhcQual n1) `shouldBe` "DupDef.Dd3.mm" r `shouldBe` True -- --------------------------------- it "returns False if the identifier is used qualified" $ do t <- ct $ parsedFileGhc "./FreeAndDeclared/Declare.hs" let comp = do parsed <- getRefactParsed nm <- getRefactNameMap let Just n@name = locToNameRdrPure nm (36,12) parsed let Just (GHC.L _ namep) = locToRdrName (36,12) parsed let res = usedWithoutQualR name parsed return (res,namep,name,n) ((r,np,n1,n2),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (myShow np) `shouldBe` "Qual:G:gshow" (myShow $ GHC.getRdrName n1) `shouldBe` "Exact:Data.Generics.Text.gshow" (showGhcQual $ GHC.getRdrName n1) `shouldBe` "Data.Generics.Text.gshow" (showGhcQual n2) `shouldBe` "Data.Generics.Text.gshow" r `shouldBe` False -- --------------------------------------------- describe "isExplicitlyExported" $ do it "Returns True if the identifier is explicitly exported" $ do pending -- "write this " it "Returns False if the identifier is not explicitly exported" $ do pending -- "write this " -- --------------------------------------------- describe "causeNameClashInExports" $ do it "Returns True if there is a clash" $ do t <- ct $ parsedFileGhc "./Renaming/ConflictExport.hs" let nm = initRdrNameMap t let parsed = GHC.pm_parsed_source $ tmParsedModule t let modu = GHC.ms_mod $ GHC.pm_mod_summary $ tmParsedModule t -- Is this the right module? let Just (modName,_) = getModuleName parsed let Just myFringe = locToNameRdrPure nm (9,1) parsed (showGhcQual myFringe) `shouldBe` "Renaming.ConflictExport.myFringe" -- old name is myFringe -- new name is "Renaming.ConflictExport.fringe" let newName = mkTestGhcName 1 (Just modu) "fringe" -- (showGhcQual modu) `shouldBe` "main@main:Renaming.ConflictExport" (showGhc modu) `shouldBe` "Renaming.ConflictExport" (showGhcQual newName) `shouldBe` "Renaming.ConflictExport.fringe" (showGhcQual $ GHC.localiseName newName) `shouldBe` "fringe" let res = causeNameClashInExports nm myFringe newName modName parsed res `shouldBe` True it "Returns False if there is no clash" $ do t <- ct $ parsedFileGhc "./Renaming/ConflictExport.hs" let nm = initRdrNameMap t let parsed = GHC.pm_parsed_source $ tmParsedModule t let modu = GHC.ms_mod $ GHC.pm_mod_summary $ tmParsedModule t -- Is this the right module? let Just (modName,_) = getModuleName parsed let Just myFringe = locToNameRdrPure nm (9,1) parsed (showGhcQual myFringe) `shouldBe` "Renaming.ConflictExport.myFringe" -- old name is myFringe -- new name is "Renaming.ConflictExport.fringe" let newName = mkTestGhcName 1 (Just modu) "fringeOk" -- (showGhcQual modu) `shouldBe` "main@main:Renaming.ConflictExport" (showGhc modu) `shouldBe` "Renaming.ConflictExport" (showGhcQual newName) `shouldBe` "Renaming.ConflictExport.fringeOk" (showGhcQual $ GHC.localiseName newName) `shouldBe` "fringeOk" let res = causeNameClashInExports nm myFringe newName modName parsed res `shouldBe` False -- --------------------------------------- describe "rmQualifier" $ do it "removes the qualifiers from a list of identifiers in a given syntax phrase" $ do let comp = do parseSourceFileGhc "./TypeUtils/Qualified.hs" parsed <- getRefactParsed decls <- liftT $ hsDecls parsed nm <- getRefactNameMap let Just foo = locToNameRdrPure nm (5, 1) parsed let Just baz = locToNameRdrPure nm (5, 27) parsed let [fooDecl] = definingDeclsRdrNames nm [foo] decls False False res <- rmQualifier [baz] fooDecl return (res,fooDecl,baz) ((r,d,n1),_s) <- ct $ runRefactGhc comp initialState testOptions (showGhcQual n1) `shouldBe` "TypeUtils.C.baz" (showGhcQual d) `shouldBe` "main = return TypeUtils.C.baz" (showGhcQual r) `shouldBe` "main = return baz" it "Removes the qualifiers and updates the tokens" $ do pending -- "Is this needed?" -- --------------------------------------- describe "usedByRhs" $ do it "returns True if a given identifier is used in the RHS of a syntax element" $ do t <- ct $ parsedFileGhc "./MoveDef/Demote.hs" let comp = do parsed <- getRefactParsed declsp <- liftT $ hsDecls parsed nm <- getRefactNameMap let Just tl = locToNameRdrPure nm (4,1) parsed let Just name = locToNameRdrPure nm (7,1) parsed let decls = definingDeclsRdrNames nm [tl] declsp False False decls' <- rmQualifier [name] decls let res = usedByRhsRdr nm decls' [name] return (res,decls,tl,name) ((r,d,n1,n2),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n1) `shouldBe` "MoveDef.Demote.toplevel" (showGhcQual n2) `shouldBe` "MoveDef.Demote.c" (showGhcQual d) `shouldBe` "[toplevel x = c * x]" r `shouldBe` True -- --------------------------------------- describe "autoRenameLocalVar" $ do it "renames an identifier if it is used and updates tokens" $ do t <- ct $ parsedFileGhc "./Demote/WhereIn4.hs" let comp = do parsed <- getRefactParsed nm <- getRefactNameMap tlDecls <- liftT $ hsDecls parsed let Just tl = locToNameRdrPure nm (11,1) parsed let Just name = locToNameRdrPure nm (11,21) parsed let [decls] = definingDeclsRdrNames nm [tl] tlDecls False True decls' <- autoRenameLocalVar name decls return (decls',decls,tl,name) ((r,d,n1,n2),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- ((r,d,n1,n2),s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual n1) `shouldBe` "Demote.WhereIn4.sumSquares" (showGhcQual n2) `shouldBe` "p" (showGhcQual d) `shouldBe` "sumSquares x y\n = sq p x + sq p y\n where\n p = 2" (showGhcQual r) `shouldBe` "sumSquares x y\n = sq p_1 x + sq p_1 y\n where\n p_1 = 2" (exactPrintFromState s r) `shouldBe` "\n\n--A definition can be demoted to the local 'where' binding of a friend declaration,\n--if it is only used by this friend declaration.\n\n--Demoting a definition narrows down the scope of the definition.\n--In this example, demote the top level 'sq' to 'sumSquares'\n--In this case (there is single matches), if possible,\n--the parameters will be folded after demoting and type sigature will be removed.\n\nsumSquares x y = sq p_1 x + sq p_1 y\n where p_1=2" -- --------------------------------------- describe "mkNewName" $ do it "Makes a new name that does not clash with existing ones" $ do (mkNewName "f" ["f"] 0) `shouldBe` "f_1" (mkNewName "f" ["g"] 0) `shouldBe` "f" (mkNewName "f" ["g","f_1","f"] 0) `shouldBe` "f_2" -- --------------------------------------- describe "addImportDecl" $ do it "adds an import entry to a module with already existing, non conflicting imports and other declarations" $ do t <- ct $ parsedFileGhc "./DupDef/Dd1.hs" let comp = do clearParsedModule parseSourceFileGhc "./DupDef/Dd2.hs" renamed2 <- getRefactRenamed parsed2 <- getRefactParsed let listModName = GHC.mkModuleName "Data.List" res <- addImportDecl parsed2 listModName Nothing False False False Nothing False [] putRefactParsed res emptyAnns return (res,renamed2) ((_r,_r2),s) <- ct $ runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (sourceFromState s) `shouldBe` "module DupDef.Dd2 where\n\nimport DupDef.Dd1\nimport Data.List\n\n\nf2 x = ff (x+1)\n\nmm = 5\n\n\n" -- --------------------------------- it "adds an import entry to a module with some declaration, but no explicit imports." $ do t <- ct $ parsedFileGhc "./TypeUtils/Simplest.hs" let comp = do let renamed1 = tmRenamedSource t parsed <- getRefactParsed let listModName = GHC.mkModuleName "Data.List" res <- addImportDecl parsed listModName Nothing False False False Nothing False [] putRefactParsed res emptyAnns return (res,renamed1) ((_r,_r2),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (sourceFromState s) `shouldBe` "module Simplest where\nimport Data.List\n\n\nsimple x = x\n" -- --------------------------------- it "adds an import entry to a module with explicit imports, but no declarations." $ do t <- ct $ parsedFileGhc "./TypeUtils/JustImports.hs" let comp = do let renamed1 = tmRenamedSource t parsed <- getRefactParsed let listModName = GHC.mkModuleName "Data.List" res <- addImportDecl parsed listModName Nothing False False False Nothing False [] putRefactParsed res emptyAnns return (res,renamed1) ((_r,_r2),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (sourceFromState s) `shouldBe` "module JustImports where\n\nimport Data.Maybe\nimport Data.List\n" -- --------------------------------- it "adds an import entry to a module with no declarations and no explicit imports" $ do t <- ct $ parsedFileGhc "./TypeUtils/Empty.hs" let comp = do renamed1 <- getRefactRenamed parsed <- getRefactParsed let listModName = GHC.mkModuleName "Data.List" res <- addImportDecl parsed listModName Nothing False False False Nothing False [] putRefactParsed res emptyAnns return (res,renamed1) ((_r,_r2),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (sourceFromState s) `shouldBe` "module Empty where\nimport Data.List\n\n" -- --------------------------------------- it "adds an import entry that only imports a single name" $ do t <- ct $ parsedFileGhc "./TypeUtils/Empty.hs" let comp = do renamed1 <- getRefactRenamed parsed <- getRefactParsed let listModName = GHC.mkModuleName "Data.List" rdr = mkRdrName "head" res <- addImportDecl parsed listModName Nothing False False False Nothing False [rdr] putRefactParsed res emptyAnns return (res,renamed1) ((_r,_r2),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (sourceFromState s) `shouldBe` "module Empty where\nimport Data.List (head)\n\n" -- --------------------------------------- it "adds a qualified import" $ do t <- ct $ parsedFileGhc "./TypeUtils/Empty.hs" let comp = do renamed1 <- getRefactRenamed parsed <- getRefactParsed let listModName = GHC.mkModuleName "Data.List" qual = Just "List" res <- addImportDecl parsed listModName Nothing False False True qual False [] putRefactParsed res emptyAnns return (res,renamed1) ((_r,_r2),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (sourceFromState s) `shouldBe` "module Empty where\nimport qualified Data.List as List\n\n" -- --------------------------------------- describe "addItemsToImport" $ do it "adds an item to an import entry with no items" $ do t <- ct $ parsedFileGhc "./TypeUtils/JustImports.hs" let comp = do parsed <- getRefactParsed let modName = GHC.mkModuleName "Data.Maybe" -- itemName <- mkNewGhcName Nothing "fromJust" let itemName = mkRdrName "fromJust" res <- addItemsToImport modName Nothing (Left [itemName]) parsed putRefactParsed res emptyAnns return (res) ((_r),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- This is the correct behavior. If the import doesn't have an import list, creating -- one for an item effectively reduces the imported interface. (sourceFromState s) `shouldBe` "module JustImports where\n\nimport Data.Maybe\n" -- Not sure if this should be a test {- it "Try adding more than one item to an existing import entry with no items, using separate calls." $ do let comp = do (t1,_toks1) <- parseSourceFileTest "./TypeUtils/JustImports.hs" -- clearParsedModule let renamed1 = tmRenamedSource t1 let modName = GHC.mkModuleName "Data.Maybe" itemName <- mkNewGhcName Nothing "fromJust" res <- addItemsToImport modName renamed1 [itemName] --listModName Nothing False False False Nothing False [] itemName2 <- mkNewGhcName Nothing "isJust" res2 <- addItemsToImport modName res [itemName2] toks <- fetchToks return (res2,toks,renamed,_toks1) ((_r,t,r2,tk2),s) <- ct $ runRefactGhcState comp (GHC.showRichTokenStream t) `shouldBe` "module JustImports where\n\n import Data.Maybe (fromJust,isJust)\n " -} -- --------------------------------- it "adds an item to an import entry with existing items" $ do t <- ct $ parsedFileGhc "./TypeUtils/SelectivelyImports.hs" let comp = do parsed <-getRefactParsed let modName = GHC.mkModuleName "Data.Maybe" let itemName = mkRdrName "isJust" res <- addItemsToImport modName Nothing (Left [itemName]) parsed putRefactParsed res emptyAnns return (res) ((_r),s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions (sourceFromState s) `shouldBe` "module SelectivelyImports where\n\nimport Data.Maybe (fromJust,isJust)\n\n__ = id\n" {- -- test after properly inserting conditional identifier it "Add an item to an import entry with existing items, passing existing conditional identifier." $ do let comp = do (t1,_toks1) <- parseSourceFileTest "./TypeUtils/SelectivelyImports.hs" -- clearParsedModule let renamed1 = tmRenamedSource t1 let modName = GHC.mkModuleName "Data.Maybe" itemName <- mkNewGhcName Nothing "isJust" conditionalId <- mkNewGhcName Nothing "fromJust" res <- addItemsToImport modName renamed1 [itemName] (Just conditionalId) toks <- fetchToks return (res,toks,renamed1,_toks1) ((_r,t,r2,tk2),s) <- ct $ runRefactGhcState comp (GHC.showRichTokenStream t) `shouldBe` "module SelectivelyImports where\n\n import Data.Maybe (fromJust,isJust)\n\n __ = id\n " it "Add an item to an import entry with existing items, passing missing conditional identifier" $ do let comp = do (t1,_toks1) <- parseSourceFileTest "./TypeUtils/SelectivelyImports.hs" -- clearParsedModule let renamed1 = tmRenamedSource t1 let modName = GHC.mkModuleName "Data.Maybe" itemName <- mkNewGhcName Nothing "isJust" res <- addItemsToImport modName renamed1 [itemName] (Just itemName) toks <- fetchToks return (res,toks,renamed1,_toks1) ((_r,t,r2,tk2),s) <- ct $ runRefactGhcState comp (GHC.showRichTokenStream t) `shouldBe` "module SelectivelyImports where\n\n import Data.Maybe (fromJust)\n\n __ = id\n " -} -- --------------------------------------- describe "addItemsToExport" $ do it "adds an item to an export entry with no items" $ do pendingWith "write these tests" -- --------------------------------------- describe "unspace" $ do it "Reduces all sequences of more than one space to a single one" $ do (unspace []) `shouldBe` [] (unspace "a") `shouldBe` "a" (unspace "a bc") `shouldBe` "a bc" (unspace "a bc") `shouldBe` "a bc" (unspace "ab c") `shouldBe` "ab c" (unspace " ab c") `shouldBe` " ab c" (unspace "abc ") `shouldBe` "abc " -- --------------------------------------- describe "isFieldName" $ do it "returns True if a Name is a field name" $ do t <- ct $ parsedFileGhc "./Renaming/Field3.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t let nm = initRdrNameMap t let Just nf = locToNameRdrPure nm (10,21) parsed let Just n = locToNameRdrPure nm (10,1) parsed (showGhcQual n) `shouldBe` "Field3.absPoint" (showGhcQual nf) `shouldBe` "Field3.pointx" -- --------------------------------------- describe "name predicates" $ do it "classifies names" $ do t <- ct $ parsedFileGhc "./Cons.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t let nm = initRdrNameMap t let Just n1 = locToNameRdrPure nm (3,6) parsed let Just n2 = locToNameRdrPure nm (3,12) parsed let Just n3 = locToNameRdrPure nm (3,16) parsed let Just n4 = locToNameRdrPure nm (5,1) parsed let Just n5 = locToNameRdrPure nm (8,5) parsed (showGhcQual n1) `shouldBe` "Main.Foo" "11" ++ (show $ GHC.isTyVarName n1) `shouldBe` "11False" "12" ++ (show $ GHC.isTyConName n1) `shouldBe` "12True" "13" ++ (show $ GHC.isDataConName n1) `shouldBe` "13False" "14" ++ (show $ GHC.isValName n1) `shouldBe` "14False" "15" ++ (show $ GHC.isVarName n1) `shouldBe` "15False" (showGhcQual n2) `shouldBe` "Main.Ff" "21" ++ (show $ GHC.isTyVarName n2) `shouldBe` "21False" "22" ++ (show $ GHC.isTyConName n2) `shouldBe` "22False" "23" ++ (show $ GHC.isDataConName n2) `shouldBe` "23True" "24" ++ (show $ GHC.isValName n2) `shouldBe` "24True" "25" ++ (show $ GHC.isVarName n2) `shouldBe` "25False" (showGhcQual n3) `shouldBe` "Main.fooA" -- field name "31" ++ (show $ GHC.isTyVarName n3) `shouldBe` "31False" "32" ++ (show $ GHC.isTyConName n3) `shouldBe` "32False" "33" ++ (show $ GHC.isDataConName n3) `shouldBe` "33False" "34" ++ (show $ GHC.isValName n3) `shouldBe` "34True" "35" ++ (show $ GHC.isVarName n3) `shouldBe` "35True" (showGhcQual n4) `shouldBe` "Main.xx" "41" ++ (show $ GHC.isTyVarName n4) `shouldBe` "41False" "42" ++ (show $ GHC.isTyConName n4) `shouldBe` "42False" "43" ++ (show $ GHC.isDataConName n4) `shouldBe` "43False" "44" ++ (show $ GHC.isValName n4) `shouldBe` "44True" "45" ++ (show $ GHC.isVarName n4) `shouldBe` "45True" (showGhcQual n5) `shouldBe` "GHC.Classes.==" "51" ++ (show $ GHC.isTyVarName n5) `shouldBe` "51False" "52" ++ (show $ GHC.isTyConName n5) `shouldBe` "52False" "53" ++ (show $ GHC.isDataConName n5) `shouldBe` "53False" "54" ++ (show $ GHC.isValName n5) `shouldBe` "54True" "55" ++ (show $ GHC.isVarName n5) `shouldBe` "55True" -- --------------------------------------------------------------------- describe "rdrName2Name" $ do it "finds a Name for a top-level RdrName" $ do t <- ct $ parsedFileGhc "./TokenTest.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t let comp = do let (Just rdr) = locToRdrName (5,1) parsed -- (Just name) = locToName (5,1) renamed nname <- rdrName2Name rdr return (rdr,nname) ((r,n),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- ((r,n),_s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual (r,n)) `shouldBe` "(bob, TokenTest.bob)" -- --------------------------------- it "finds a Name for a local RdrName" $ do t <- ct $ parsedFileGhc "./TokenTest.hs" let parsed = GHC.pm_parsed_source $ tmParsedModule t let comp = do let (Just rdr) = locToRdrName (14,7) parsed nname <- rdrName2Name rdr return (rdr,nname) ((r,n),_s) <- runRefactGhc comp (initialState { rsModule = initRefactModule [] t }) testOptions -- ((r,n),_s) <- runRefactGhc comp (initialLogOnState { rsModule = initRefactModule [] t }) testOptions (showGhcQual (r,n)) `shouldBe` "(bar, bar)" -- --------------------------------------------------------------------- myShow :: GHC.RdrName -> String myShow n = case n of GHC.Unqual on -> ("Unqual:" ++ (showGhcQual on)) GHC.Qual ms on -> ("Qual:" ++ (showGhcQual ms) ++ ":" ++ (showGhcQual on)) GHC.Orig ms on -> ("Orig:" ++ (showGhcQual ms) ++ ":" ++ (showGhcQual on)) GHC.Exact en -> ("Exact:" ++ (showGhcQual en)) -- --------------------------------------------------------------------- -- EOF
RefactoringTools/HaRe
test/TypeUtilsSpec.hs
bsd-3-clause
179,467
548
41
46,279
34,856
17,455
17,401
-1
-1
module ListProp where import List assert ElemProp = {-#cert:Alfa_ElemProp#-} All y . All xs . All ys . True {y `elem` ys} ==> True {y `elem` (xs++ys)} property Reflexive = {| op | All x . True {op x x} |} assert NubByProp = {-#cert:Alfa_NubByProp#-} All eq . Reflexive {eq} ==> All x . {nubBy eq [x,x]} === {[x]} sameEq x y = (==) (y `asTypeOf` x) assert NubProp = {-#cert:Alfa_NubProp#-} All x . Reflexive {sameEq x} ==> {nub [x,x]} === {[x]} assert NubPropDoesn'tWork = All x . Reflexive {(==)} ==> {nub [x,x]} === {[x]}
forste/haReFork
tools/hs2alfa/tests/ListProp.hs
bsd-3-clause
537
16
12
109
263
153
110
-1
-1
{-# LANGUAGE PatternSynonyms #-} module T15517 where data Nat = Z | S Nat pattern Zpat = Z sfrom :: Nat -> () -> Bool sfrom Zpat = \_ -> False sfrom (S Z) = \_ -> False
sdiehl/ghc
testsuite/tests/simplCore/should_compile/T15517.hs
bsd-3-clause
173
0
7
42
72
40
32
7
1
import Test.Cabal.Prelude -- NB: cabal-install doesn't understand --dependency main = setupTest $ do skipUnless =<< ghcVersionIs (>= mkVersion [8,1]) withPackageDb $ do withDirectory "sigs" $ setup_install_with_docs ["--cid", "sigs-0.1.0.0", "lib:sigs"] withDirectory "indef" $ setup_install_with_docs ["--cid", "indef-0.1.0.0", "--dependency=sigs=sigs-0.1.0.0", "lib:indef"]
themoritz/cabal
cabal-testsuite/PackageTests/Backpack/Includes3/setup-external-explicit.test.hs
bsd-3-clause
396
0
13
57
94
49
45
6
1
{-# LANGUAGE OverloadedStrings #-} module Main (main) where import Data.ByteString.Char8 import ServantBench import Hasql.Connection (settings) import System.Environment (getArgs) main :: IO () main = do [host] <- getArgs run 7041 $ dbSettings (pack host) dbSettings :: ByteString -> ByteString dbSettings host = settings host 5432 "benchmarkdbuser" "benchmarkdbpass" "hello_world"
ashawnbandy-te-tfb/FrameworkBenchmarks
frameworks/Haskell/servant/driver/Main.hs
bsd-3-clause
391
0
10
57
111
60
51
13
1
module Spear.Math.Collision ( CollisionType(..) -- * 2D Collision , Collisionable2(..) , Collisioner2(..) -- ** Construction , aabb2Collisioner , circleCollisioner , mkCols -- ** Collision test , collide -- ** Manipulation , move -- ** Helpers , buildAABB2 , aabb2FromCircle , circleFromAABB2 -- * 3D Collision , Collisionable3(..) -- ** Helpers , aabb3FromSphere ) where import Spear.Assets.Model import Spear.Math.AABB import Spear.Math.Circle import qualified Spear.Math.Matrix4 as M4 import Spear.Math.Plane import Spear.Math.Sphere import Spear.Math.Vector import Data.List (foldl') data CollisionType = NoCollision | Collision | FullyContains | FullyContainedBy deriving (Eq, Show) -- 2D collision class Collisionable2 a where -- | Collide the object with an AABB. collideAABB2 :: AABB2 -> a -> CollisionType -- | Collide the object with a circle. collideCircle :: Circle -> a -> CollisionType instance Collisionable2 AABB2 where collideAABB2 box1@(AABB2 min1 max1) box2@(AABB2 min2 max2) | (x max1) < (x min2) = NoCollision | (x min1) > (x max2) = NoCollision | (y max1) < (y min2) = NoCollision | (y min1) > (y max2) = NoCollision | box1 `aabb2pt` min2 && box1 `aabb2pt` max2 = FullyContains | box2 `aabb2pt` min1 && box2 `aabb2pt` max1 = FullyContainedBy | otherwise = Collision collideCircle circle@(Circle c r) aabb@(AABB2 min max) | test == FullyContains || test == FullyContainedBy = test | normSq (c - boxC) > (l + r)^2 = NoCollision | otherwise = Collision where test = collideAABB2 aabb $ aabb2FromCircle circle boxC = min + (max-min)/2 l = norm $ min + (vec2 (x boxC) (y min)) - min instance Collisionable2 Circle where collideAABB2 box circle = case collideCircle circle box of FullyContains -> FullyContainedBy FullyContainedBy -> FullyContains x -> x collideCircle s1@(Circle c1 r1) s2@(Circle c2 r2) | distance_centers <= sub_radii = if (r1 > r2) then FullyContains else FullyContainedBy | distance_centers <= sum_radii = Collision | otherwise = NoCollision where distance_centers = normSq $ c1 - c2 sum_radii = (r1 + r2)^2 sub_radii = (r1 - r2)^2 instance Collisionable2 Collisioner2 where collideAABB2 box (AABB2Col self) = collideAABB2 box self collideAABB2 box (CircleCol self) = collideAABB2 box self collideCircle circle (AABB2Col self) = collideCircle circle self collideCircle circle (CircleCol self) = collideCircle circle self aabbPoints :: AABB2 -> [Vector2] aabbPoints (AABB2 min max) = [p1,p2,p3,p4,p5,p6,p7,p8] where p1 = vec2 (x min) (y min) p2 = vec2 (x min) (y min) p3 = vec2 (x min) (y max) p4 = vec2 (x min) (y max) p5 = vec2 (x max) (y min) p6 = vec2 (x max) (y min) p7 = vec2 (x max) (y max) p8 = vec2 (x max) (y max) -- | A collisioner component. data Collisioner2 -- | An axis-aligned bounding box. = AABB2Col {-# UNPACK #-} !AABB2 -- | A bounding circle. | CircleCol {-# UNPACK #-} !Circle -- | Create a collisioner from the specified box. aabb2Collisioner :: AABB2 -> Collisioner2 aabb2Collisioner = AABB2Col -- | Create a collisioner from the specified circle. circleCollisioner :: Circle -> Collisioner2 circleCollisioner = CircleCol -- | Compute AABB collisioners in view space from the given AABB. mkCols :: M4.Matrix4 -- ^ Modelview matrix -> Box -> [Collisioner2] mkCols modelview (Box (Vec3 xmin ymin zmin) (Vec3 xmax ymax zmax)) = let toVec2 v = vec2 (x v) (y v) p1 = toVec2 $ modelview `M4.mulp` vec3 xmin ymin zmax p2 = toVec2 $ modelview `M4.mulp` vec3 xmax ymin zmin p3 = toVec2 $ modelview `M4.mulp` vec3 xmax ymax zmin col1 = AABB2Col $ AABB2 p1 p2 col2 = AABB2Col $ AABB2 p1 p3 in [col1, col2] -- | Create the minimal AABB fully containing the specified collisioners. buildAABB2 :: [Collisioner2] -> AABB2 buildAABB2 cols = aabb2 $ generatePoints cols -- | Create the minimal box fully containing the specified circle. aabb2FromCircle :: Circle -> AABB2 aabb2FromCircle (Circle c r) = AABB2 bot top where bot = c - (vec2 r r) top = c + (vec2 r r) -- | Create the minimal circle fully containing the specified box. circleFromAABB2 :: AABB2 -> Circle circleFromAABB2 (AABB2 min max) = Circle c r where c = scale 0.5 (min + max) r = norm . scale 0.5 $ max - min generatePoints :: [Collisioner2] -> [Vector2] generatePoints = foldl' generate [] where generate acc (AABB2Col (AABB2 pmin pmax)) = p1:p2:p3:p4:p5:p6:p7:p8:acc where p1 = vec2 (x pmin) (y pmin) p2 = vec2 (x pmin) (y pmin) p3 = vec2 (x pmin) (y pmax) p4 = vec2 (x pmin) (y pmax) p5 = vec2 (x pmax) (y pmin) p6 = vec2 (x pmax) (y pmin) p7 = vec2 (x pmax) (y pmax) p8 = vec2 (x pmax) (y pmax) generate acc (CircleCol (Circle c r)) = p1:p2:p3:p4:acc where p1 = c + unitx2 * (vec2 r r) p2 = c - unitx2 * (vec2 r r) p3 = c + unity2 * (vec2 r r) p4 = c - unity2 * (vec2 r r) -- | Collide the given collisioners. collide :: Collisioner2 -> Collisioner2 -> CollisionType collide (AABB2Col box1) (AABB2Col box2) = collideAABB2 box1 box2 collide (AABB2Col box) (CircleCol circle) = collideAABB2 box circle collide (CircleCol s1) (CircleCol s2) = collideCircle s1 s2 collide (CircleCol circle) (AABB2Col box) = collideCircle circle box -- | Move the collisioner. move :: Vector2 -> Collisioner2 -> Collisioner2 move v (AABB2Col (AABB2 min max)) = AABB2Col (AABB2 (min+v) (max+v)) move v (CircleCol (Circle c r)) = CircleCol (Circle (c+v) r) -- 3D collision class Collisionable3 a where -- | Collide the object with an AABB. collideAABB3 :: AABB3 -> a -> CollisionType -- | Collide the object with a sphere. collideSphere :: Sphere -> a -> CollisionType instance Collisionable3 AABB3 where collideAABB3 box1@(AABB3 min1 max1) box2@(AABB3 min2 max2) | (x max1) < (x min2) = NoCollision | (x min1) > (x max2) = NoCollision | (y max1) < (y min2) = NoCollision | (y min1) > (y max2) = NoCollision | box1 `aabb3pt` min2 && box1 `aabb3pt` max2 = FullyContains | box2 `aabb3pt` min1 && box2 `aabb3pt` max1 = FullyContainedBy | otherwise = Collision collideSphere sphere@(Sphere c r) aabb@(AABB3 min max) | test == FullyContains || test == FullyContainedBy = test | normSq (c - boxC) > (l + r)^2 = NoCollision | otherwise = Collision where test = collideAABB3 aabb $ aabb3FromSphere sphere boxC = min + v l = norm v v = (max-min)/2 instance Collisionable3 Sphere where collideAABB3 box sphere = case collideSphere sphere box of FullyContains -> FullyContainedBy FullyContainedBy -> FullyContains x -> x collideSphere s1@(Sphere c1 r1) s2@(Sphere c2 r2) | distance_centers <= sub_radii = if (r1 > r2) then FullyContains else FullyContainedBy | distance_centers <= sum_radii = Collision | otherwise = NoCollision where distance_centers = normSq $ c1 - c2 sum_radii = (r1 + r2)^2 sub_radii = (r1 - r2)^2 -- | Create the minimal box fully containing the specified sphere. aabb3FromSphere :: Sphere -> AABB3 aabb3FromSphere (Sphere c r) = AABB3 bot top where bot = c - (vec3 r r r) top = c + (vec3 r r r)
jeannekamikaze/Spear
Spear/Math/Collision.hs
mit
8,614
6
15
2,968
2,673
1,402
1,271
161
2
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings, FlexibleInstances #-} -- | If you are interested in the IHaskell library for the purpose of augmenting the IHaskell -- notebook or writing your own display mechanisms and widgets, this module contains all functions -- you need. -- -- In order to create a display mechanism for a particular data type, write a module named (for -- example) @IHaskell.Display.YourThing@ in a package named @ihaskell-yourThing@. (Note the -- capitalization - it's important!) Then, in that module, add an instance of @IHaskellDisplay@ for -- your data type. Similarly, to create a widget, add an instance of @IHaskellWidget@. -- -- An example of creating a display is provided in the -- <http://gibiansky.github.io/IHaskell/demo.html demo notebook>. -- module IHaskell.Display ( -- * Rich display and interactive display typeclasses and types IHaskellDisplay(..), Display(..), DisplayData(..), IHaskellWidget(..), -- ** Interactive use functions printDisplay, -- * Constructors for displays plain, html, bmp, png, jpg, gif, svg, latex, markdown, javascript, json, vega, vegalite, vdom, widgetdisplay, custom, many, -- ** Image and data encoding functions Width, Height, Base64, encode64, base64, -- ** Utilities switchToTmpDir, -- * Internal only use displayFromChanEncoded, serializeDisplay, Widget(..), ) where import IHaskellPrelude import qualified Data.Text as T import qualified Data.ByteString.Char8 as CBS import qualified Data.ByteString.Lazy as LBS import Data.Binary as Binary import qualified Data.ByteString.Base64 as Base64 import System.Directory (getTemporaryDirectory, setCurrentDirectory) import Control.Concurrent.STM (atomically) import Control.Exception (try) import Control.Concurrent.STM.TChan import System.IO.Unsafe (unsafePerformIO) import qualified Data.Text.Encoding as E import IHaskell.Types import IHaskell.Eval.Util (unfoldM) import StringUtils (rstrip) type Base64 = Text -- | Encode many displays into a single one. All will be output. many :: [Display] -> Display many = ManyDisplay -- | Generate a plain text display. plain :: String -> DisplayData plain = DisplayData PlainText . T.pack . rstrip -- | Generate an HTML display. html :: String -> DisplayData html = DisplayData MimeHtml . T.pack -- | Generate an SVG display. svg :: String -> DisplayData svg = DisplayData MimeSvg . T.pack -- | Generate a LaTeX display. latex :: String -> DisplayData latex = DisplayData MimeLatex . T.pack -- | Generate a Javascript display. javascript :: String -> DisplayData javascript = DisplayData MimeJavascript . T.pack -- | Generate a Json display. json :: String -> DisplayData json = DisplayData MimeJson . T.pack -- | Generate a Vega display. vega :: String -> DisplayData vega = DisplayData MimeVega . T.pack -- | Generate a Vegalite display. vegalite :: String -> DisplayData vegalite = DisplayData MimeVegalite . T.pack -- | Generate a Vdom display. vdom :: String -> DisplayData vdom = DisplayData MimeVdom . T.pack -- | Generate a custom display. The first argument is the mimetype and the second argument is the -- payload. custom :: T.Text -> String -> DisplayData custom mimetype = DisplayData (MimeCustom mimetype) . T.pack -- | Generate a Markdown display. markdown :: String -> DisplayData markdown = DisplayData MimeMarkdown . T.pack -- | Generate a GIF display of the given width and height. Data must be provided in a Base64 encoded -- manner, suitable for embedding into HTML. The @base64@ function may be used to encode data into -- this format. gif :: Width -> Height -> Base64 -> DisplayData gif width height = DisplayData (MimeGif width height) -- | Generate a BMP display of the given width and height. Data must be provided in a Base64 encoded -- manner, suitable for embedding into HTML. The @base64@ function may be used to encode data into -- this format. bmp :: Width -> Height -> Base64 -> DisplayData bmp width height = DisplayData (MimeBmp width height) -- | Generate a PNG display of the given width and height. Data must be provided in a Base64 encoded -- manner, suitable for embedding into HTML. The @base64@ function may be used to encode data into -- this format. png :: Width -> Height -> Base64 -> DisplayData png width height = DisplayData (MimePng width height) -- | Generate a JPG display of the given width and height. Data must be provided in a Base64 encoded -- manner, suitable for embedding into HTML. The @base64@ function may be used to encode data into -- this format. jpg :: Width -> Height -> Base64 -> DisplayData jpg width height = DisplayData (MimeJpg width height) -- | Generate a Widget display given the uuid and the view version widgetdisplay :: String -> DisplayData widgetdisplay = DisplayData MimeWidget .T.pack -- | Convert from a string into base 64 encoded data. encode64 :: String -> Base64 encode64 str = base64 $ CBS.pack str -- | Convert from a ByteString into base 64 encoded data. base64 :: ByteString -> Base64 base64 = E.decodeUtf8 . Base64.encode -- | For internal use within IHaskell. Serialize displays to a ByteString. serializeDisplay :: Display -> LBS.ByteString serializeDisplay = Binary.encode -- | Items written to this chan will be included in the output sent to the frontend (ultimately the -- browser), the next time IHaskell has an item to display. {-# NOINLINE displayChan #-} displayChan :: TChan Display displayChan = unsafePerformIO newTChanIO -- | Take everything that was put into the 'displayChan' at that point out, and make a 'Display' out -- of it. displayFromChanEncoded :: IO LBS.ByteString displayFromChanEncoded = Binary.encode <$> Just . many <$> unfoldM (atomically $ tryReadTChan displayChan) -- | Write to the display channel. The contents will be displayed in the notebook once the current -- execution call ends. printDisplay :: IHaskellDisplay a => a -> IO () printDisplay disp = display disp >>= atomically . writeTChan displayChan -- | Convenience function for client libraries. Switch to a temporary directory so that any files we -- create aren't visible. On Unix, this is usually /tmp. switchToTmpDir :: IO () switchToTmpDir = void (try switchDir :: IO (Either SomeException ())) where switchDir = getTemporaryDirectory >>= setCurrentDirectory
gibiansky/IHaskell
src/IHaskell/Display.hs
mit
6,523
1
10
1,266
997
582
415
102
1
------------------------------------------------------------------------------- -- | -- Module : System.Hardware.Arduino.SamplePrograms.Counter -- Copyright : (c) Levent Erkok -- License : BSD3 -- Maintainer : [email protected] -- Stability : experimental -- -- Demonstrates using two push-buttons to count up and down. ------------------------------------------------------------------------------- module System.Hardware.Arduino.SamplePrograms.Counter where import Control.Monad.Trans (liftIO) import System.Hardware.Arduino -- | Two push-button switches, controlling a counter value. We will increment -- the counter if the first one ('bUp') is pressed, and decrement the value if the -- second one ('bDown') is pressed. We also have a led connected to pin 13 (either use -- the internal or connect an external one), that we light up when the counter value -- is 0. -- -- Wiring is very simple: Up-button connected to pin 4, Down-button connected -- to pin 2, and a led on pin 13. -- -- <<http://github.com/LeventErkok/hArduino/raw/master/System/Hardware/Arduino/SamplePrograms/Schematics/Counter.png>> counter :: IO () counter = withArduino False "/dev/cu.usbmodemfd131" $ do setPinMode led OUTPUT setPinMode bUp INPUT setPinMode bDown INPUT update (0::Int) where bUp = digital 4 bDown = digital 2 led = digital 13 update curVal = do liftIO $ print curVal digitalWrite led (curVal == 0) [up, down] <- waitAnyHigh [bUp, bDown] let newVal = case (up, down) of (True, True) -> curVal -- simultaneous press (True, False) -> curVal+1 (False, True) -> curVal-1 (False, False) -> curVal -- can't happen update newVal
aufheben/lambda-arduino
packages/hArduino-0.9/System/Hardware/Arduino/SamplePrograms/Counter.hs
mit
1,929
0
15
536
270
151
119
22
4
{-# LANGUAGE BangPatterns, DataKinds, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module Hadoop.Protos.DataTransferProtos.Status (Status(..)) where import Prelude ((+), (/), (.)) import qualified Prelude as Prelude' import qualified Data.Typeable as Prelude' import qualified Data.Data as Prelude' import qualified Text.ProtocolBuffers.Header as P' data Status = SUCCESS | ERROR | ERROR_CHECKSUM | ERROR_INVALID | ERROR_EXISTS | ERROR_ACCESS_TOKEN | CHECKSUM_OK | ERROR_UNSUPPORTED | OOB_RESTART | OOB_RESERVED1 | OOB_RESERVED2 | OOB_RESERVED3 | IN_PROGRESS deriving (Prelude'.Read, Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data) instance P'.Mergeable Status instance Prelude'.Bounded Status where minBound = SUCCESS maxBound = IN_PROGRESS instance P'.Default Status where defaultValue = SUCCESS toMaybe'Enum :: Prelude'.Int -> P'.Maybe Status toMaybe'Enum 0 = Prelude'.Just SUCCESS toMaybe'Enum 1 = Prelude'.Just ERROR toMaybe'Enum 2 = Prelude'.Just ERROR_CHECKSUM toMaybe'Enum 3 = Prelude'.Just ERROR_INVALID toMaybe'Enum 4 = Prelude'.Just ERROR_EXISTS toMaybe'Enum 5 = Prelude'.Just ERROR_ACCESS_TOKEN toMaybe'Enum 6 = Prelude'.Just CHECKSUM_OK toMaybe'Enum 7 = Prelude'.Just ERROR_UNSUPPORTED toMaybe'Enum 8 = Prelude'.Just OOB_RESTART toMaybe'Enum 9 = Prelude'.Just OOB_RESERVED1 toMaybe'Enum 10 = Prelude'.Just OOB_RESERVED2 toMaybe'Enum 11 = Prelude'.Just OOB_RESERVED3 toMaybe'Enum 12 = Prelude'.Just IN_PROGRESS toMaybe'Enum _ = Prelude'.Nothing instance Prelude'.Enum Status where fromEnum SUCCESS = 0 fromEnum ERROR = 1 fromEnum ERROR_CHECKSUM = 2 fromEnum ERROR_INVALID = 3 fromEnum ERROR_EXISTS = 4 fromEnum ERROR_ACCESS_TOKEN = 5 fromEnum CHECKSUM_OK = 6 fromEnum ERROR_UNSUPPORTED = 7 fromEnum OOB_RESTART = 8 fromEnum OOB_RESERVED1 = 9 fromEnum OOB_RESERVED2 = 10 fromEnum OOB_RESERVED3 = 11 fromEnum IN_PROGRESS = 12 toEnum = P'.fromMaybe (Prelude'.error "hprotoc generated code: toEnum failure for type Hadoop.Protos.DataTransferProtos.Status") . toMaybe'Enum succ SUCCESS = ERROR succ ERROR = ERROR_CHECKSUM succ ERROR_CHECKSUM = ERROR_INVALID succ ERROR_INVALID = ERROR_EXISTS succ ERROR_EXISTS = ERROR_ACCESS_TOKEN succ ERROR_ACCESS_TOKEN = CHECKSUM_OK succ CHECKSUM_OK = ERROR_UNSUPPORTED succ ERROR_UNSUPPORTED = OOB_RESTART succ OOB_RESTART = OOB_RESERVED1 succ OOB_RESERVED1 = OOB_RESERVED2 succ OOB_RESERVED2 = OOB_RESERVED3 succ OOB_RESERVED3 = IN_PROGRESS succ _ = Prelude'.error "hprotoc generated code: succ failure for type Hadoop.Protos.DataTransferProtos.Status" pred ERROR = SUCCESS pred ERROR_CHECKSUM = ERROR pred ERROR_INVALID = ERROR_CHECKSUM pred ERROR_EXISTS = ERROR_INVALID pred ERROR_ACCESS_TOKEN = ERROR_EXISTS pred CHECKSUM_OK = ERROR_ACCESS_TOKEN pred ERROR_UNSUPPORTED = CHECKSUM_OK pred OOB_RESTART = ERROR_UNSUPPORTED pred OOB_RESERVED1 = OOB_RESTART pred OOB_RESERVED2 = OOB_RESERVED1 pred OOB_RESERVED3 = OOB_RESERVED2 pred IN_PROGRESS = OOB_RESERVED3 pred _ = Prelude'.error "hprotoc generated code: pred failure for type Hadoop.Protos.DataTransferProtos.Status" instance P'.Wire Status where wireSize ft' enum = P'.wireSize ft' (Prelude'.fromEnum enum) wirePut ft' enum = P'.wirePut ft' (Prelude'.fromEnum enum) wireGet 14 = P'.wireGetEnum toMaybe'Enum wireGet ft' = P'.wireGetErr ft' wireGetPacked 14 = P'.wireGetPackedEnum toMaybe'Enum wireGetPacked ft' = P'.wireGetErr ft' instance P'.GPB Status instance P'.MessageAPI msg' (msg' -> Status) Status where getVal m' f' = f' m' instance P'.ReflectEnum Status where reflectEnum = [(0, "SUCCESS", SUCCESS), (1, "ERROR", ERROR), (2, "ERROR_CHECKSUM", ERROR_CHECKSUM), (3, "ERROR_INVALID", ERROR_INVALID), (4, "ERROR_EXISTS", ERROR_EXISTS), (5, "ERROR_ACCESS_TOKEN", ERROR_ACCESS_TOKEN), (6, "CHECKSUM_OK", CHECKSUM_OK), (7, "ERROR_UNSUPPORTED", ERROR_UNSUPPORTED), (8, "OOB_RESTART", OOB_RESTART), (9, "OOB_RESERVED1", OOB_RESERVED1), (10, "OOB_RESERVED2", OOB_RESERVED2), (11, "OOB_RESERVED3", OOB_RESERVED3), (12, "IN_PROGRESS", IN_PROGRESS)] reflectEnumInfo _ = P'.EnumInfo (P'.makePNF (P'.pack ".hadoop.hdfs.Status") ["Hadoop", "Protos"] ["DataTransferProtos"] "Status") ["Hadoop", "Protos", "DataTransferProtos", "Status.hs"] [(0, "SUCCESS"), (1, "ERROR"), (2, "ERROR_CHECKSUM"), (3, "ERROR_INVALID"), (4, "ERROR_EXISTS"), (5, "ERROR_ACCESS_TOKEN"), (6, "CHECKSUM_OK"), (7, "ERROR_UNSUPPORTED"), (8, "OOB_RESTART"), (9, "OOB_RESERVED1"), (10, "OOB_RESERVED2"), (11, "OOB_RESERVED3"), (12, "IN_PROGRESS")] instance P'.TextType Status where tellT = P'.tellShow getT = P'.getRead
alexbiehl/hoop
hadoop-protos/src/Hadoop/Protos/DataTransferProtos/Status.hs
mit
4,920
0
11
858
1,272
701
571
111
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-servicediscovery-service-dnsconfig.html module Stratosphere.ResourceProperties.ServiceDiscoveryServiceDnsConfig where import Stratosphere.ResourceImports import Stratosphere.ResourceProperties.ServiceDiscoveryServiceDnsRecord -- | Full data type definition for ServiceDiscoveryServiceDnsConfig. See -- 'serviceDiscoveryServiceDnsConfig' for a more convenient constructor. data ServiceDiscoveryServiceDnsConfig = ServiceDiscoveryServiceDnsConfig { _serviceDiscoveryServiceDnsConfigDnsRecords :: [ServiceDiscoveryServiceDnsRecord] , _serviceDiscoveryServiceDnsConfigNamespaceId :: Maybe (Val Text) , _serviceDiscoveryServiceDnsConfigRoutingPolicy :: Maybe (Val Text) } deriving (Show, Eq) instance ToJSON ServiceDiscoveryServiceDnsConfig where toJSON ServiceDiscoveryServiceDnsConfig{..} = object $ catMaybes [ (Just . ("DnsRecords",) . toJSON) _serviceDiscoveryServiceDnsConfigDnsRecords , fmap (("NamespaceId",) . toJSON) _serviceDiscoveryServiceDnsConfigNamespaceId , fmap (("RoutingPolicy",) . toJSON) _serviceDiscoveryServiceDnsConfigRoutingPolicy ] -- | Constructor for 'ServiceDiscoveryServiceDnsConfig' containing required -- fields as arguments. serviceDiscoveryServiceDnsConfig :: [ServiceDiscoveryServiceDnsRecord] -- ^ 'sdsdcDnsRecords' -> ServiceDiscoveryServiceDnsConfig serviceDiscoveryServiceDnsConfig dnsRecordsarg = ServiceDiscoveryServiceDnsConfig { _serviceDiscoveryServiceDnsConfigDnsRecords = dnsRecordsarg , _serviceDiscoveryServiceDnsConfigNamespaceId = Nothing , _serviceDiscoveryServiceDnsConfigRoutingPolicy = Nothing } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-servicediscovery-service-dnsconfig.html#cfn-servicediscovery-service-dnsconfig-dnsrecords sdsdcDnsRecords :: Lens' ServiceDiscoveryServiceDnsConfig [ServiceDiscoveryServiceDnsRecord] sdsdcDnsRecords = lens _serviceDiscoveryServiceDnsConfigDnsRecords (\s a -> s { _serviceDiscoveryServiceDnsConfigDnsRecords = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-servicediscovery-service-dnsconfig.html#cfn-servicediscovery-service-dnsconfig-namespaceid sdsdcNamespaceId :: Lens' ServiceDiscoveryServiceDnsConfig (Maybe (Val Text)) sdsdcNamespaceId = lens _serviceDiscoveryServiceDnsConfigNamespaceId (\s a -> s { _serviceDiscoveryServiceDnsConfigNamespaceId = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-servicediscovery-service-dnsconfig.html#cfn-servicediscovery-service-dnsconfig-routingpolicy sdsdcRoutingPolicy :: Lens' ServiceDiscoveryServiceDnsConfig (Maybe (Val Text)) sdsdcRoutingPolicy = lens _serviceDiscoveryServiceDnsConfigRoutingPolicy (\s a -> s { _serviceDiscoveryServiceDnsConfigRoutingPolicy = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/ServiceDiscoveryServiceDnsConfig.hs
mit
2,989
0
13
258
359
207
152
34
1
:set prompt "" :module Sound.Tidal.Context let newStream = stream "127.0.0.1" 7771 dirt d1 <- newStream d2 <- newStream d3 <- newStream d4 <- newStream d5 <- newStream d6 <- newStream d7 <- newStream d8 <- newStream d9 <- newStream (cps, getNow) <- bpsUtils let bps x = cps (x/2) let hush = mapM_ ($ silence) [d1,d2,d3,d4,d5,d6,d7,d8,d9] let solo = (>>) hush :set prompt "tidal> "
santolucito/atom-hasklive
lib/BootTidal.hs
mit
387
16
7
71
181
98
83
-1
-1
{-# LANGUAGE LambdaCase #-} module Main ( main ) where import Control.Concurrent import Control.Concurrent.Async import Control.Exception import Control.Monad import System.IO import System.Random {- for some not-yet-explained reason, restarting a looping thread outside of errHandler doesn't seem to be reliably working when it comes to interaction with twitter-conduit (could be http-client), the following example simulates a frequently crashing thread with restart mechanism intentionally placed outside of errHandler to see if we can reproduce the situation. for now it all seems to work just fine... -} errHandler :: SomeException -> IO (Maybe a) errHandler _e = pure Nothing threadLoop :: StdGen -> IO () threadLoop s = catch (Just <$> step s) errHandler >>= \case Nothing -> threadLoop s Just s' -> threadLoop s' where step :: StdGen -> IO StdGen step sg = do let (v, sg') = next sg when (v `mod` 16 < 5) $ error "crash" threadDelay $ 1000 * 20 pure sg' main :: IO () main = do hSetBuffering stdout LineBuffering sg <- newStdGen t0 <- async (threadLoop sg) t1 <- async (forever (threadDelay (1000 * 1000 * 10)) >> pure ()) {- since t1 takes literally forever to run, waitEither should block indefinitely, we'll quit whenever t0 crashes, which isn't supposed to happen due to the fact that the "catch'em all" protection is set up. -} waitEither t0 t1 >>= print
Javran/misc
thread-exception-tests/src/Main.hs
mit
1,495
0
16
353
320
158
162
29
2
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE RecordWildCards #-} module Crypto.Sodium.Hash.Internal where import Crypto.Sodium.Internal (constantTimeEq, mkHelper) import Control.Monad (void) import Data.ByteString (ByteString) import qualified Data.ByteString.Internal as B import qualified Data.ByteString.Unsafe as B import Data.Function (on) import Data.Hashable (Hashable) import Data.Word (Word8) import Foreign.C.Types (CChar, CInt (..), CULLong (..)) import Foreign.Ptr (Ptr) type HashFn = Ptr Word8 -> Ptr CChar -> CULLong -> IO CInt newtype Digest h = Digest { _unDigest :: ByteString } deriving (Show, Ord, Hashable) instance Eq (Digest h) where (==) = constantTimeEq `on` _unDigest data Hash h = Hash { digestBytes :: Int , mkDigest :: ByteString -> Maybe (Digest h) , unDigest :: Digest h -> ByteString , hash :: ByteString -> Digest h } mkHash :: CInt -> HashFn -> Hash h mkHash c_digestBytes c_hash = Hash {..} where digestBytes = fromIntegral c_digestBytes mkDigest = mkHelper digestBytes Digest unDigest = _unDigest hash m = Digest $ B.unsafeCreate digestBytes $ \pd -> B.unsafeUseAsCStringLen m $ \(pm, mLen) -> void $ c_hash pd pm (fromIntegral mLen)
dnaq/crypto-sodium
src/Crypto/Sodium/Hash/Internal.hs
mit
1,543
0
14
531
390
226
164
32
1
{-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TypeFamilies #-} module Data.Monoid.Colorful.Nested ( Style(..) , Color(..) , Term(..) , Colored(..) , hGetTerm , getTerm , hPrintColored , printColored , hPrintColoredIO , printColoredIO , hPrintColoredS , printColoredS , showColored , showColoredM , showColoredS ) where import System.IO (Handle) import Data.Monoid.Colorful.Term import Data.Monoid.Colorful.Color import Data.Monoid.Colorful.SGR import Data.Monoid.Colorful.Trustworthy import Data.String (IsString(..)) import qualified Data.Semigroup as Sem import GHC.Generics (Generic, Generic1) import qualified Data.Monoid.Colorful.Flat as Flat import Control.Monad (ap) -- | Colored Monoid data Colored a = Nil | Value a | Style !Style (Colored a) | Unstyle !Style (Colored a) | Fg !Color (Colored a) | Bg !Color (Colored a) | Pair (Colored a) (Colored a) deriving (Eq, Ord, Show, Read, Functor, Foldable, Traversable, Generic, Generic1) -- | Free monad! instance Applicative Colored where pure = Value (<*>) = ap -- | Free monad! instance Monad Colored where Nil >>= _ = Nil Value x >>= f = f x Style a x >>= f = Style a (x >>= f) Unstyle a x >>= f = Unstyle a (x >>= f) Fg a x >>= f = Fg a (x >>= f) Bg a x >>= f = Bg a (x >>= f) Pair x y >>= f = Pair (x >>= f) (y >>= f) instance Sem.Semigroup (Colored a) where (<>) = Pair instance Monoid (Colored a) where mempty = Nil mappend = (Sem.<>) instance IsString a => IsString (Colored a) where fromString = Value . fromString instance IsList (Colored a) where type Item (Colored a) = Colored a fromList = foldr Pair Nil toList = (:[]) -- TODO, invalid -- | Flatten the Monoid @Colored a@ and return @[Flat.Colored a]@ -- -- This function is used internally for rendering the Colored monoids. flatten :: Colored a -> [Flat.Colored a] flatten s = go s [] where go (Value a) = (Flat.Value a:) go (Style a b) = (Flat.Push:) . (Flat.Style a:) . go b . (Flat.Pop:) go (Unstyle a b) = (Flat.Push:) . (Flat.Unstyle a:) . go b . (Flat.Pop:) go (Fg a b) = (Flat.Push:) . (Flat.Fg a:) . go b . (Flat.Pop:) go (Bg a b) = (Flat.Push:) . (Flat.Bg a:) . go b . (Flat.Pop:) go Nil = id go (Pair a b) = go a . go b hPrintColoredIO :: Handle -> Term -> Colored (IO ()) -> IO () hPrintColoredIO h t = Flat.hPrintColoredIO h t . flatten printColoredIO :: Term -> Colored (IO ()) -> IO () printColoredIO t = Flat.printColoredIO t . flatten hPrintColored :: (Handle -> a -> IO ()) -> Handle -> Term -> Colored a -> IO () hPrintColored f h t = Flat.hPrintColored f h t . flatten printColored :: (a -> IO ()) -> Term -> Colored a -> IO () printColored f t = Flat.printColored f t . flatten hPrintColoredS :: Handle -> Term -> Colored String -> IO () hPrintColoredS h t = Flat.hPrintColoredS h t . flatten printColoredS :: Term -> Colored String -> IO () printColoredS t = Flat.printColoredS t . flatten showColoredM :: (Monad f, Monoid o) => (a -> f o) -> (SGRCode -> f o) -> Term -> Colored a -> f o showColoredM f g t = Flat.showColoredM f g t . flatten showColored :: Monoid o => (a -> o) -> (SGRCode -> o) -> Term -> Colored a -> o showColored f g t = Flat.showColored f g t . flatten showColoredS :: Term -> Colored String -> ShowS showColoredS t = Flat.showColoredS t . flatten
minad/colorful-monoids
src/Data/Monoid/Colorful/Nested.hs
mit
3,579
0
12
868
1,444
761
683
97
7
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Betfair.StreamingAPI.Types.RequestStatus ( RequestStatus(..) ) where import Data.Aeson.TH (Options (omitNothingFields), defaultOptions, deriveJSON) import Protolude import Text.PrettyPrint.GenericPretty data RequestStatus = SUCCESS | FAILURE deriving (Eq, Show, Generic, Pretty, Read) $(deriveJSON defaultOptions {omitNothingFields = True} ''RequestStatus)
joe9/streaming-betfair-api
src/Betfair/StreamingAPI/Types/RequestStatus.hs
mit
650
0
9
142
108
67
41
17
0
module SyntaxTreeDetails ( SyntaxTreeWithEOF , syntaxTreeWithoutEOF , simplifySyntaxTree ) where import GrammarDetails ( TerminalsAndEOF(..), ProductionNamesAndStart(..) ) import Grammar import SyntaxTree import Error import Token import Helpers ( maybeToEither ) import Control.Applicative ( (<$>) ) import Control.Monad ( mapM ) import qualified Data.Map as Map type SyntaxTreeWithEOF alphabet productionNames tokenNames = SyntaxTree alphabet (ProductionNamesAndStart productionNames) (TerminalsAndEOF tokenNames) syntaxTreeWithoutEOF :: SyntaxTreeWithEOF alphabet productionNames tokenNames -> Result alphabet (SyntaxTree alphabet productionNames tokenNames) -- Shouldn't be called with EOFTerminal Leaf, no way to remove that syntaxTreeWithoutEOF (Leaf (Token EOFTerminal _ _)) = Left $ AssertionError "syntaxTreeWithoutEOF called on an invalid syntax tree with an EOF leaf" -- Normal leaf syntaxTreeWithoutEOF (Leaf token@(Token (NormalTerminal tokenName) _ _)) = Right $ Leaf $ token { tName = tokenName } -- Start production syntaxTreeWithoutEOF (Node StartProductionName [child, Leaf (Token EOFTerminal _ _)]) = syntaxTreeWithoutEOF child syntaxTreeWithoutEOF (Node StartProductionName [child]) = syntaxTreeWithoutEOF child -- Start production should only have one child since the terminal EOF following it is discardable. syntaxTreeWithoutEOF (Node StartProductionName _) = Left $ AssertionError "syntaxTreeWithoutEOF called on an invalid syntax tree with a StartProduction node with an invalid number of children" -- Normal production syntaxTreeWithoutEOF (Node (NormalProductionName productionName) children) = Node productionName <$> mapM syntaxTreeWithoutEOF children -- Discards what's discardable. Side-effect of verifying the tree matches the productions. simplifySyntaxTree :: (Ord productionNames, Eq tokenNames, Eq symbols) -- Grammar which defines discardable productions and terminals => Grammar tokenNames productionNames symbols -- Tree to simplify -> SyntaxTree alphabet productionNames tokenNames -- Simplified tree -> Result alphabet (SyntaxTree alphabet productionNames tokenNames) simplifySyntaxTree _ (Leaf _) = Left $ AssertionError "simplifySyntaxTree: Called on leaf, which is no valid syntax tree!" simplifySyntaxTree grammar node = do list <- simplifySyntaxTree' grammar (startSymbol grammar) True node if null list then Left $ AssertionError "simplifySyntaxTree' returned [] for root node, it shouldn't do that!" else return $ head list -- returns [] if the current node is completely discardable (e.g. a comment) -- except for the root node (isRoot) -- otherwise returns [simplified node] simplifySyntaxTree' :: (Ord productionNames, Eq tokenNames, Eq symbols) -- Grammar which defines discardable productions and terminals => Grammar tokenNames productionNames symbols -- Symbol the current node must match -> symbols -- Whether this is the root node -> Bool -- Tree to simplify -> SyntaxTree alphabet productionNames tokenNames -- Simplified tree -> Result alphabet [SyntaxTree alphabet productionNames tokenNames] simplifySyntaxTree' _ _ _ (Leaf _) = Left $ AssertionError "simplifySyntaxTree' called on Leaf!" simplifySyntaxTree' grammar symbol isRoot (Node productionName children) = do production <- lookupProduction productionName grammar if productionSymbol production /= symbol then Left $ AssertionError "simplifySyntaxTree: Tree does not match grammar, node production does not match parents' requirements" else do simplifiedChildren <- simplifyNodeForest grammar productionName production children -- can only discard if we have a parent or there is exactly one child let numChildren = length simplifiedChildren if productionDiscardable production && numChildren <= 1 && (not isRoot || numChildren == 1) then if numChildren == 0 -- implies not isRoot then return [] else -- length simplifiedChildren == 1 return simplifiedChildren else -- not discardable return [Node productionName simplifiedChildren] lookupProduction :: (Ord productionNames) => productionNames -> Grammar tokenNames productionNames symbols -> Result alphabet (Production tokenNames symbols) lookupProduction productionName grammar = maybeToEither (AssertionError "simplifySyntaxTree: syntax tree contains production name that's not in the grammar") $ Map.lookup productionName (productions grammar) simplifyNodeForest :: (Ord productionNames, Eq tokenNames, Eq symbols) => Grammar tokenNames productionNames symbols -- Which production's forest is this? -> productionName -> Production tokenNames symbols -- What to simplify? -> [SyntaxTree alphabet productionNames tokenNames] -> Result alphabet [SyntaxTree alphabet productionNames tokenNames] simplifyNodeForest grammar prodName production forest = do children <- sequence $ simplifyNodeForest' grammar (productionString production) forest return children simplifyNodeForest' :: (Ord productionNames, Eq tokenNames, Eq symbols) => Grammar tokenNames productionNames symbols -- Production string this should match -> [ProductionElement tokenNames symbols] -> [SyntaxTree alphabet productionNames tokenNames] -> [Result alphabet (SyntaxTree alphabet productionNames tokenNames)] simplifyNodeForest' _ [] [] = [] simplifyNodeForest' _ _ [] = [Left $ AssertionError "Syntax Tree does not match production; Node with too few children"] simplifyNodeForest' _ [] _ = [Left $ AssertionError "Syntax Tree does not match production; Node with too many children"] simplifyNodeForest' grammar (productionElement:productionElements) (tree:trees) = simplifyNodeTree grammar productionElement tree ++ simplifyNodeForest' grammar productionElements trees expectedTerminalError :: Result a b expectedTerminalError = Left $ AssertionError "Syntax Tree does not match production; Expected Terminal, got Symbol" expectedSymbolError :: Result a b expectedSymbolError = Left $ AssertionError "Syntax Tree does not match production; Expected Symbol, got Terminal" differingTerminalError :: Result a b differingTerminalError = Left $ AssertionError "Syntax Tree does not match production; Differing Terminals" differingSymbolError :: Result a b differingSymbolError = Left $ AssertionError "Syntax Tree does not match production; Differing Symbols" simplifyNodeTree :: (Ord productionNames, Eq tokenNames, Eq symbols) => Grammar tokenNames productionNames symbols -> ProductionElement tokenNames symbols -> SyntaxTree alphabet productionNames tokenNames -> [Result alphabet (SyntaxTree alphabet productionNames tokenNames)] simplifyNodeTree grammar (Terminal _) (Node _ _) = [expectedTerminalError] simplifyNodeTree grammar (DiscardableTerminal _) (Node _ _) = [expectedTerminalError] simplifyNodeTree grammar (Symbol _) (Leaf _) = [expectedSymbolError] simplifyNodeTree grammar (Terminal t) (Leaf l) | t == tName l = [return $ Leaf l] | otherwise = [differingTerminalError] simplifyNodeTree grammar (DiscardableTerminal t) (Leaf l) | t == tName l = [] -- discard | otherwise = [differingTerminalError] simplifyNodeTree grammar (Symbol symbol) tree = case simplifySyntaxTree' grammar symbol False tree of Left error -> [Left error] Right list -> map Right list
mrwonko/wonkococo
wcc/SyntaxTreeDetails.hs
mit
7,619
0
15
1,406
1,577
801
776
116
4
{-# LANGUAGE OverloadedStrings #-} module Internal.Colors where -- import Data.Word (Word8(..)) import Linear.V4 (V4 (..)) -- clrWhite, clrBlack :: V4 Word8 clrLGray, clrGray :: V4 Word8 clrRed, clrOrange :: V4 Word8 clrYellow, clrGreen :: V4 Word8 clrBlue, clrIndigo :: V4 Word8 clrPurple, clrPink :: V4 Word8 -- clrWhite = V4 0 0 0 255 clrBlack = V4 255 255 255 255 clrLGray = V4 192 192 192 255 clrGray = V4 128 128 128 255 -- clrPink = V4 255 105 180 255 clrRed = V4 255 0 0 255 clrOrange = V4 255 153 0 255 clrYellow = V4 255 255 0 255 clrGreen = V4 0 255 0 255 clrBlue = V4 0 0 255 255 clrIndigo = V4 75 0 130 255 clrPurple = V4 143 0 255 255 --
Pixelgebra/tilepin
src/Internal/Colors.hs
mit
699
0
6
180
268
148
120
22
1
fib 0 = 1 fib 1 = 1 fib n = fib (n-1) + fib (n-2) main = do putStrLn "N = " line <- getLine let n = read line putStrLn $ show (fib n)
folivetti/PI-UFABC
AULA_03/Haskell/Fibonacci.hs
mit
163
0
10
65
97
44
53
8
1
import Data.List import Data.Digits import Data.Numbers.Primes import qualified Data.Map as Map import qualified Data.Set as Set below _ [] = [] below max (x:xs) = if (x < max) then [x] ++ (below max xs) else (below max xs) -- get content of list below max and stop (when list is growing) belowStop :: Integral a => a -> [a] -> [a] belowStop _ [] = [] belowStop max (x:xs) = if (x < max) then [x] ++ (belowStop max xs) else [] -- rotate a list rotate :: Int -> [a] -> [a] rotate _ [] = [] rotate n xs = zipWith const (drop n (cycle xs)) xs -- rotations of a list rotations :: [a] -> [[a]] rotations list = map (\i -> rotate i list) [0 .. length(list)-1] isEven x = (x `mod` 2) == 0 isOdd x = not $ isEven x allOdd x = all isOdd (digits 10 x) primesList = belowStop 1000000 (2:(filter allOdd primes)) primesSet = Set.fromList primesList -- rotations of an integer nrotations x = map (\i -> unDigits 10 i) (rotations (digits 10 x)) isPrimeEfficient x = Set.member x primesSet -- generate all circular primes in a set isCircular x = all isPrimeEfficient (nrotations x) circulars = filter isCircular primesList answer = length circulars main = print answer
gumgl/project-euler
35/35.hs
mit
1,166
0
9
231
512
274
238
26
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-kernelcapabilities.html module Stratosphere.ResourceProperties.ECSTaskDefinitionKernelCapabilities where import Stratosphere.ResourceImports -- | Full data type definition for ECSTaskDefinitionKernelCapabilities. See -- 'ecsTaskDefinitionKernelCapabilities' for a more convenient constructor. data ECSTaskDefinitionKernelCapabilities = ECSTaskDefinitionKernelCapabilities { _eCSTaskDefinitionKernelCapabilitiesAdd :: Maybe (ValList Text) , _eCSTaskDefinitionKernelCapabilitiesDrop :: Maybe (ValList Text) } deriving (Show, Eq) instance ToJSON ECSTaskDefinitionKernelCapabilities where toJSON ECSTaskDefinitionKernelCapabilities{..} = object $ catMaybes [ fmap (("Add",) . toJSON) _eCSTaskDefinitionKernelCapabilitiesAdd , fmap (("Drop",) . toJSON) _eCSTaskDefinitionKernelCapabilitiesDrop ] -- | Constructor for 'ECSTaskDefinitionKernelCapabilities' containing required -- fields as arguments. ecsTaskDefinitionKernelCapabilities :: ECSTaskDefinitionKernelCapabilities ecsTaskDefinitionKernelCapabilities = ECSTaskDefinitionKernelCapabilities { _eCSTaskDefinitionKernelCapabilitiesAdd = Nothing , _eCSTaskDefinitionKernelCapabilitiesDrop = Nothing } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-kernelcapabilities.html#cfn-ecs-taskdefinition-kernelcapabilities-add ecstdkcAdd :: Lens' ECSTaskDefinitionKernelCapabilities (Maybe (ValList Text)) ecstdkcAdd = lens _eCSTaskDefinitionKernelCapabilitiesAdd (\s a -> s { _eCSTaskDefinitionKernelCapabilitiesAdd = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-kernelcapabilities.html#cfn-ecs-taskdefinition-kernelcapabilities-drop ecstdkcDrop :: Lens' ECSTaskDefinitionKernelCapabilities (Maybe (ValList Text)) ecstdkcDrop = lens _eCSTaskDefinitionKernelCapabilitiesDrop (\s a -> s { _eCSTaskDefinitionKernelCapabilitiesDrop = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/ECSTaskDefinitionKernelCapabilities.hs
mit
2,169
0
12
205
264
151
113
27
1
import Distribution.MacOSX import Distribution.Simple main :: IO () main = defaultMainWithHooks $ simpleUserHooks { postBuild = appBundleBuildHook guiApps -- no-op if not MacOS X } guiApps :: [MacApp] guiApps = [MacApp "jsaddle-hello-wkwebview" Nothing (Just "macos/Info.plist") [] -- No other resources. [] -- No other binaries. DoNotChase -- Try changing to ChaseWithDefaults ]
ghcjs/jsaddle-hello
Setup.hs
mit
498
0
8
170
84
47
37
12
1
module JVM.State where -- $Id$ import JVM.Type import JVM.Memory import Machine.History import Autolib.ToDoc import Autolib.FiniteMap import Data.Array import Data.Typeable data State = State { schritt :: Int , code :: Array Int Statement , pc :: Int , stack :: [ Integer ] , memory :: Memory , past :: [State] -- vorige zustände } deriving ( Eq, Ord, Typeable ) instance ToDoc State where toDoc st = text "State" <+> dutch_record [ text "schritt" <+> equals <+> toDoc ( schritt st ) , text "memory" <+> equals <+> toDoc ( memory st ) , text "stack" <+> equals <+> toDoc ( stack st ) , text "pc" <+> equals <+> toDoc ( pc st ) , text "code [pc]" <+> equals <+> if inRange (bounds $ code st) ( pc st ) then toDoc ( code st ! pc st ) else text "<<outside>>" ] instance History State where history = past
florianpilz/autotool
src/JVM/State.hs
gpl-2.0
923
12
14
273
319
169
150
28
0
module ListManipulation where -- foldl :: (a -> b -> a) -> a -> [b] -> a -- foldl :: ([[a]] -> b -> [[a]]) -> [[a]] -> [b] -> [[a]] pack :: Eq a => [a] -> [[a]] pack list = foldl (\ l e -> case l of [[]] -> [[e]] (x:xs):ys -> if x == e then (e:x:xs):ys else [e]:(x:xs):ys) [[]] $ reverse list -- *ListManipulation> pack [1,1,1,2,2,3] -- [[1,1,1],[2,2],[3]]
ardumont/haskell-lab
src/ListManipulation.hs
gpl-2.0
421
0
16
137
151
85
66
6
3
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Supply (Supply , next , runSupply, getSupply) where import Control.Monad.State newtype Supply s a = S (State [s] a) deriving(Monad) next = S $ do st <- get case st of [] -> return Nothing (x:xs) -> do put xs return (Just x) runSupply (S m) xs = runState m xs getSupply (S m) xs = return (runSupply (S m) xs)
dservgun/haskell_test_code
src/Supply.hs
gpl-2.0
493
0
15
200
172
90
82
15
2
-- file doctests.hs -- Main for doctests. Run it as a normal haskell code. import Test.DocTest main = doctest ["-isrc", "PassGen.hs"]
salmonix/Haskell_smallities
PassGen/DocTest.hs
gpl-3.0
146
0
6
33
22
13
9
2
1
module Snail (snail) where type Matrix = [[Integer]] goRight :: Matrix -> [Integer] goRight = head goDown :: Matrix -> [Integer] goDown = tail . map last rotate :: Matrix -> Matrix rotate = reverse . map reverse submatrix :: Matrix -> Matrix submatrix = tail . map init snail :: Matrix -> [Integer] snail [] = [] snail (x:[]) = x snail ((x:[]):xs) = x : map head xs snail x = goRight x ++ goDown x ++ snail ( rotate $ submatrix x )
luinix/haskell_snail
Snail.hs
gpl-3.0
438
0
10
92
213
114
99
15
1
{- ============================================================================ | Copyright 2010 Matthew D. Steele <[email protected]> | | | | This file is part of Pylos. | | | | Pylos 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. | | | | Pylos 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 Pylos. If not, see <http://www.gnu.org/licenses/>. | ============================================================================ -} module Pylos.State where import Control.Concurrent (MVar, ThreadId, newEmptyMVar) import Pylos.Data.TotalMap (TotalMap, makeTotalMap) import Pylos.Game ------------------------------------------------------------------------------- data GameState = GameState { gsRuleset :: Ruleset, gsBoard :: Board, gsTurn :: Team, gsPhase :: Phase, gsPlayers :: TotalMap Team Player, gsCpuThreadId :: Maybe ThreadId, gsCpuMove :: MVar Move } data NewGameSpec = NewGameSpec { ngRuleset :: Ruleset, ngBoardSize :: Int, ngWhitePlayer :: Player, ngBlackPlayer :: Player } newGameState :: NewGameSpec -> IO GameState newGameState spec = do cpuMove <- newEmptyMVar return GameState { gsRuleset = ngRuleset spec, gsBoard = emptyBoard (ngBoardSize spec), gsTurn = WhiteTeam, gsPhase = case ngWhitePlayer spec of HumanPlayer -> BeginPhase CpuPlayer -> CpuTurnPhase, gsPlayers = makeTotalMap $ \team -> case team of WhiteTeam -> ngWhitePlayer spec BlackTeam -> ngBlackPlayer spec, gsCpuThreadId = Nothing, gsCpuMove = cpuMove } ------------------------------------------------------------------------------- data Player = CpuPlayer | HumanPlayer deriving Eq ------------------------------------------------------------------------------- data Phase = CpuTurnPhase -- start of computer turn | CpuRunningPhase -- during computer turn | BeginPhase -- human turn: place or jump piece | LandPhase Coords -- human turn: land a jumped piece | RemovePhase Move -- human turn: remove a piece | AnimatePhase Animation -- animation in progress | EndPhase -- turn is now finished | VictoryPhase -- current player has won data Animation = Animation { animKind :: AnimKind, animCurrent :: Double, animMaximum :: Double, animNextBoard :: Board, animNextPhase :: Phase } data AnimKind = AnimPlace Coords | AnimJump Coords Coords | AnimRemove Coords -------------------------------------------------------------------------------
mdsteele/pylos
src/Pylos/State.hs
gpl-3.0
3,646
0
15
1,241
395
236
159
51
3
{-# LANGUAGE TemplateHaskell #-} module Tic.Location where import ClassyPrelude import Control.Lens (makeLenses) import Tic.GeoCoord data Location a = Location { _locName :: Text , _locCoord :: GeoCoord a } deriving(Show) $(makeLenses ''Location)
pmiddend/tic
lib/Tic/Location.hs
gpl-3.0
291
0
9
76
69
40
29
10
0
{-# LANGUAGE DeriveGeneric #-} module Game ( Pos (..) , Dir (..) , Color (..) , Snake (..) , Bounds (..) , GameState (..) , inverse , go , canGo , move , canMove , snakeToBodyPositions -- demo , start , advanceRandom ) where import GHC.Generics import Prelude hiding (Left, Right) import System.Random (randomRIO) data Pos = Pos { posX :: Int , posY :: Int } deriving (Generic, Eq, Show) data Dir = Up | Down | Left | Right deriving (Generic, Eq, Show, Enum) data Color = Color Float Float Float Float deriving (Generic, Eq, Show) -- R G B Alpha [0.0, 1.0] type Moves = [Dir] data Snake = Snake { snakeHead :: Pos , snakeMoves :: Moves , snakeColor :: Color } deriving (Generic, Eq, Show) data GameState = GameState { gsSnakes :: [Snake] } deriving (Generic, Eq, Show) data Bounds = Bounds { lowerBounds :: Pos , upperBounds :: Pos } deriving (Eq, Show) inverse :: Dir -> Dir inverse Up = Down inverse Down = Up inverse Left = Right inverse Right = Left go :: Pos -> Dir -> Pos go pos Up = pos { posY = posY pos - 1 } go pos Down = pos { posY = posY pos + 1 } go pos Left = pos { posX = posX pos - 1 } go pos Right = pos { posX = posX pos + 1 } canGo :: Bounds -> Pos -> Dir -> Bool canGo bounds pos Up = posY pos > (posY . lowerBounds) bounds canGo bounds pos Down = posY pos < (posY . upperBounds) bounds canGo bounds pos Left = posX pos > (posX . lowerBounds) bounds canGo bounds pos Right = posX pos < (posX . upperBounds) bounds move :: Snake -> Dir -> Snake move snake dir = snake { snakeHead = go (snakeHead snake) dir , snakeMoves = dir : init (snakeMoves snake) } canMove :: Bounds -> Snake -> Dir -> Bool canMove bounds snake dir = canGo bounds (snakeHead snake) dir -- && not (collided (snakeHead snake) (tail $ snakeToBodyPositions snake)) collided :: Pos -> [Pos] -> Bool collided pos poss = pos `elem` poss snakeToBodyPositions :: Snake -> [Pos] snakeToBodyPositions snake = init $ scanl (\pos mov -> go pos $ inverse mov) (snakeHead snake) (snakeMoves snake) -- demo start :: GameState start = GameState { gsSnakes = [ Snake { snakeHead = Pos { posX = 20, posY = 20 }, snakeMoves = replicate 6 Left, snakeColor = Color 1.0 0.0 1.0 1.0 } ] } advanceRandom :: GameState -> IO GameState advanceRandom gs = do moved <- traverse moveRandom (gsSnakes gs) return $ gs { gsSnakes = moved } randomDir :: IO Dir randomDir = do n <- randomRIO (0, 3) return $ [Up, Down, Left, Right] !! n moveRandom :: Snake -> IO Snake moveRandom snake = do dir <- randomDir if canMove gameBounds snake dir then return $ move snake dir else moveRandom snake gameBounds :: Bounds gameBounds = Bounds { lowerBounds = Pos { posX = 0, posY = 0 } , upperBounds = Pos { posX = 39, posY = 39 } }
nettok/culebra-hs
src/Game.hs
gpl-3.0
2,813
0
11
668
1,089
601
488
85
2
{-# LANGUAGE TypeFamilies, FlexibleContexts, GADTs #-} {-# LANGUAGE OverloadedStrings, FlexibleInstances #-} {-# LANGUAGE TypeSynonymInstances, NoMonomorphismRestriction #-} module Teatros.Default (prepararDb) where import Teatros.Persistent import Database.Persist (insertUnique) import Control.Monad (forM_) import Data.Text (Text) xsFormatoAfiches :: [Text] xsFormatoAfiches = ["Oficio (22x33)", "Tabloide (29x41)" ,"Medio Pliego (50x70)", "Pliego (100x70)" ,"Gran Formato (mayor a 100x70)", "Otro"] xsFormatoFotos :: [Text] xsFormatoFotos = ["Documento (5x4)", "Medio Oficio (22x16,5)" ,"Oficio (22x33)", "Medio Pliego (70x50)" ,"Otro"] xsTecnologiasFotos :: [Text] xsTecnologiasFotos = ["Análoga - BN", "Análoga - Color", "Digital - BN" ,"Digital - Color", "Diapositiva - BN" ,"Diapositiva-Color", "Sin definir"] xsTecnologiasAudiovisuales :: [Text] xsTecnologiasAudiovisuales = ["BETACAM", "BETA", "VHS", "DVD", "CD" ,"Cassette", "Carrete Abierto", "Disco" ,"Material Fílmico", "Otra"] xsSedes :: [Text] xsSedes = ["Casa Teatro Nacional", "Teatro La Castellana" ,"Teatro Fanny Mikey Calle 71", "Proyecto Pedagógico"] xsTiposDeDocumentos :: [Text] xsTiposDeDocumentos = ["Revista", "Libro", "Guión"] xsEncabezamientos :: [Text] xsEncabezamientos = ["Historia teatro", "Crítica teatral", "Festivales" ,"Entrevistas", "Correspondencia" ,"Programación cultural", "Fanny mikey", "Actores" ,"Directores", "Dramaturgos" ,"Proyecto pedagógico", "Trayectoria"] importar t xs = forM_ xs (insertUnique . t) prepararDb = do importar Sede xsSedes importar Encabezamiento xsEncabezamientos importar FormatoAfiche xsFormatoAfiches importar TecnologiaFotografia xsTecnologiasFotos importar FormatoFotografia xsFormatoFotos importar TipoDocumento xsTiposDeDocumentos importar TecnologiaAudiovisual xsTecnologiasAudiovisuales
arpunk/jfdb
src/Teatros/Default.hs
gpl-3.0
2,195
0
7
561
364
216
148
44
1
{-# LANGUAGE TemplateHaskell #-} -- Copyright (C) 2010-2012 John Millikin <[email protected]> -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. module DBusTests.BusName (test_BusName) where import Test.Chell import Test.Chell.QuickCheck import Test.QuickCheck hiding (property) import Data.List (intercalate) import DBus import DBusTests.Util test_BusName :: Suite test_BusName = suite "BusName" [ test_Parse , test_ParseInvalid , test_IsVariant ] test_Parse :: Test test_Parse = property "parse" prop where prop = forAll gen_BusName check check x = case parseBusName x of Nothing -> False Just parsed -> formatBusName parsed == x test_ParseInvalid :: Test test_ParseInvalid = assertions "parse-invalid" $ do -- empty $expect (nothing (parseBusName "")) -- well-known starting with a digit $expect (nothing (parseBusName "foo.0bar")) -- well-known with one element $expect (nothing (parseBusName "foo")) -- unique with one element $expect (nothing (parseBusName ":foo")) -- trailing characters $expect (nothing (parseBusName "foo.bar!")) -- at most 255 characters $expect (just (parseBusName (":0." ++ replicate 251 'y'))) $expect (just (parseBusName (":0." ++ replicate 252 'y'))) $expect (nothing (parseBusName (":0." ++ replicate 253 'y'))) test_IsVariant :: Test test_IsVariant = assertions "IsVariant" $ do assertVariant TypeString (busName_ "foo.bar") gen_BusName :: Gen String gen_BusName = oneof [unique, wellKnown] where alpha = ['a'..'z'] ++ ['A'..'Z'] ++ "_-" alphanum = alpha ++ ['0'..'9'] unique = trim $ do x <- chunks alphanum return (":" ++ x) wellKnown = trim (chunks alpha) trim gen = do x <- gen if length x > 255 then return (dropWhileEnd (== '.') (take 255 x)) else return x chunks start = do x <- chunk start xs <- listOf1 (chunk start) return (intercalate "." (x:xs)) chunk start = do x <- elements start xs <- listOf (elements alphanum) return (x:xs) instance Arbitrary BusName where arbitrary = fmap busName_ gen_BusName
jotrk/haskell-dbus
tests/DBusTests/BusName.hs
gpl-3.0
2,680
17
15
529
699
354
345
55
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.PlayMoviesPartner.Accounts.Orders.Get -- 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) -- -- Get an Order given its id. See _Authentication and Authorization rules_ -- and _Get methods rules_ for more information about this method. -- -- /See:/ <https://developers.google.com/playmoviespartner/ Google Play Movies Partner API Reference> for @playmoviespartner.accounts.orders.get@. module Network.Google.Resource.PlayMoviesPartner.Accounts.Orders.Get ( -- * REST Resource AccountsOrdersGetResource -- * Creating a Request , accountsOrdersGet , AccountsOrdersGet -- * Request Lenses , aogXgafv , aogUploadProtocol , aogPp , aogAccessToken , aogUploadType , aogAccountId , aogBearerToken , aogOrderId , aogCallback ) where import Network.Google.PlayMoviesPartner.Types import Network.Google.Prelude -- | A resource alias for @playmoviespartner.accounts.orders.get@ method which the -- 'AccountsOrdersGet' request conforms to. type AccountsOrdersGetResource = "v1" :> "accounts" :> Capture "accountId" Text :> "orders" :> Capture "orderId" Text :> QueryParam "$.xgafv" Text :> QueryParam "upload_protocol" Text :> QueryParam "pp" Bool :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "bearer_token" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] Order -- | Get an Order given its id. See _Authentication and Authorization rules_ -- and _Get methods rules_ for more information about this method. -- -- /See:/ 'accountsOrdersGet' smart constructor. data AccountsOrdersGet = AccountsOrdersGet' { _aogXgafv :: !(Maybe Text) , _aogUploadProtocol :: !(Maybe Text) , _aogPp :: !Bool , _aogAccessToken :: !(Maybe Text) , _aogUploadType :: !(Maybe Text) , _aogAccountId :: !Text , _aogBearerToken :: !(Maybe Text) , _aogOrderId :: !Text , _aogCallback :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountsOrdersGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aogXgafv' -- -- * 'aogUploadProtocol' -- -- * 'aogPp' -- -- * 'aogAccessToken' -- -- * 'aogUploadType' -- -- * 'aogAccountId' -- -- * 'aogBearerToken' -- -- * 'aogOrderId' -- -- * 'aogCallback' accountsOrdersGet :: Text -- ^ 'aogAccountId' -> Text -- ^ 'aogOrderId' -> AccountsOrdersGet accountsOrdersGet pAogAccountId_ pAogOrderId_ = AccountsOrdersGet' { _aogXgafv = Nothing , _aogUploadProtocol = Nothing , _aogPp = True , _aogAccessToken = Nothing , _aogUploadType = Nothing , _aogAccountId = pAogAccountId_ , _aogBearerToken = Nothing , _aogOrderId = pAogOrderId_ , _aogCallback = Nothing } -- | V1 error format. aogXgafv :: Lens' AccountsOrdersGet (Maybe Text) aogXgafv = lens _aogXgafv (\ s a -> s{_aogXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). aogUploadProtocol :: Lens' AccountsOrdersGet (Maybe Text) aogUploadProtocol = lens _aogUploadProtocol (\ s a -> s{_aogUploadProtocol = a}) -- | Pretty-print response. aogPp :: Lens' AccountsOrdersGet Bool aogPp = lens _aogPp (\ s a -> s{_aogPp = a}) -- | OAuth access token. aogAccessToken :: Lens' AccountsOrdersGet (Maybe Text) aogAccessToken = lens _aogAccessToken (\ s a -> s{_aogAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). aogUploadType :: Lens' AccountsOrdersGet (Maybe Text) aogUploadType = lens _aogUploadType (\ s a -> s{_aogUploadType = a}) -- | REQUIRED. See _General rules_ for more information about this field. aogAccountId :: Lens' AccountsOrdersGet Text aogAccountId = lens _aogAccountId (\ s a -> s{_aogAccountId = a}) -- | OAuth bearer token. aogBearerToken :: Lens' AccountsOrdersGet (Maybe Text) aogBearerToken = lens _aogBearerToken (\ s a -> s{_aogBearerToken = a}) -- | REQUIRED. Order ID. aogOrderId :: Lens' AccountsOrdersGet Text aogOrderId = lens _aogOrderId (\ s a -> s{_aogOrderId = a}) -- | JSONP aogCallback :: Lens' AccountsOrdersGet (Maybe Text) aogCallback = lens _aogCallback (\ s a -> s{_aogCallback = a}) instance GoogleRequest AccountsOrdersGet where type Rs AccountsOrdersGet = Order type Scopes AccountsOrdersGet = '["https://www.googleapis.com/auth/playmovies_partner.readonly"] requestClient AccountsOrdersGet'{..} = go _aogAccountId _aogOrderId _aogXgafv _aogUploadProtocol (Just _aogPp) _aogAccessToken _aogUploadType _aogBearerToken _aogCallback (Just AltJSON) playMoviesPartnerService where go = buildClient (Proxy :: Proxy AccountsOrdersGetResource) mempty
rueshyna/gogol
gogol-play-moviespartner/gen/Network/Google/Resource/PlayMoviesPartner/Accounts/Orders/Get.hs
mpl-2.0
5,906
0
20
1,477
934
542
392
133
1
module Main where import Kawaii main :: IO () main = runApp $ defaultApp { appTitle = "Lonesome Space" , appMode = Windowed 1024 768 , appStages = [Stage updateGame renderGame] , appGrabInput = True } updateMainMenu :: Event -> Updating () updateMainMenu _ = return Skip renderMainMenu :: Rendering () renderMainMenu = return () updateGame :: Event -> Updating () updateGame (EventKeyPressed ScancodeEscape _) = return Terminate updateGame (EventKeyPressed ScancodeSpace _) = return Success updateGame _ = return Skip renderGame :: Rendering () renderGame = drawTile "tileset" 1 2 0 0 0 0 -- Say hi little astronaut! {- import Relational import Debug.Trace main :: IO () main = runRelational (viaDisk "test") $ do foo <- createRelation ([1,2,3] :: [Int]) updateRelation foo [69,42,18] updateRelation foo [5,5,5] result <- readRelation foo traceShow result $ return () -}
nitrix/lspace
lspace/Main.hs
unlicense
930
0
9
196
205
107
98
18
1
module WordNumber where import Data.List (intersperse) digitToWord :: Int -> String digitToWord 1 = "one" digitToWord 2 = "two" digitToWord 3 = "three" digitToWord 4 = "four" digitToWord 5 = "five" digitToWord 6 = "six" digitToWord 7 = "seven" digitToWord 8 = "eight" digitToWord 9 = "nine" digits :: Int -> [Int] digits n = go [] n where go acc n | div n 10 == 0 = n:acc | otherwise = go ((mod n 10):acc) (div n 10) wordNumber :: Int -> String wordNumber = concat . intersperse "-" . map digitToWord . digits
aniketd/learn.haskell
haskellbook/wordNumber.hs
unlicense
546
0
12
132
222
112
110
19
1
{-# LANGUAGE LambdaCase #-} {- | Module : Neovim.Debug Description : Utilities to debug Neovim and nvim-hs functionality Copyright : (c) Sebastian Witte License : Apache-2.0 Maintainer : [email protected] Stability : experimental Portability : GHC -} module Neovim.Debug ( debug, debug', develMain, quitDevelMain, restartDevelMain, runNeovim, runNeovim', module Neovim, ) where import Neovim import Neovim.Context (runNeovim) import qualified Neovim.Context.Internal as Internal import Neovim.Log (disableLogger) import Neovim.Main (CommandLineOptions (..), runPluginProvider) import Neovim.RPC.Common (RPCConfig) import Control.Concurrent import Control.Monad import Foreign.Store import Prelude -- | Run a 'Neovim' function. -- -- This function connects to the socket pointed to by the environment variable -- @$NVIM_LISTEN_ADDRESS@ and executes the command. It does not register itself -- as a real plugin provider, you can simply call neovim-functions from the -- module "Neovim.API.String" this way. -- -- Tip: If you run a terminal inside a neovim instance, then this variable is -- automatically set. debug :: r -> st -> Internal.Neovim r st a -> IO (Either String (a, st)) debug r st a = disableLogger $ do runPluginProvider def { env = True } Nothing transitionHandler Nothing where transitionHandler tids cfg = takeMVar (Internal.transitionTo cfg) >>= \case Internal.Failure e -> return $ Left e Internal.InitSuccess -> do res <- Internal.runNeovim (cfg { Internal.customConfig = r, Internal.pluginSettings = Nothing }) st a mapM_ killThread tids return res _ -> return $ Left "Unexpected transition state." -- | Run a 'Neovim'' function. -- -- @ -- debug' a = fmap fst <$> debug () () a -- @ -- -- See documentation for 'debug'. debug' :: Internal.Neovim' a -> IO (Either String a) debug' a = fmap fst <$> debug () () a -- | This function is intended to be run _once_ in a ghci session that to -- give a REPL based workflow when developing a plugin. -- -- Note that the dyre-based reload mechanisms, i.e. the -- "Neovim.Plugin.ConfigHelper" plugin, is not started this way. -- -- To use this in ghci, you simply bind the results to some variables. After -- each reload of ghci, you have to rebind those variables. -- -- Example: -- -- @ -- λ 'Right' (tids, cfg) <- 'develMain' 'Nothing' -- -- λ 'runNeovim'' cfg \$ vim_call_function \"getqflist\" [] -- 'Right' ('Right' ('ObjectArray' [])) -- -- λ :r -- -- λ 'Right' (tids, cfg) <- 'develMain' 'Nothing' -- @ -- develMain :: Maybe NeovimConfig -> IO (Either String ([ThreadId], Internal.Config RPCConfig ())) develMain mcfg = lookupStore 0 >>= \case Nothing -> do x <- disableLogger $ runPluginProvider def { env = True } mcfg transitionHandler Nothing void $ newStore x return x Just x -> readStore x where transitionHandler tids cfg = takeMVar (Internal.transitionTo cfg) >>= \case Internal.Failure e -> return $ Left e Internal.InitSuccess -> do transitionHandlerThread <- forkIO $ do myTid <- myThreadId void $ transitionHandler (myTid:tids) cfg return $ Right (transitionHandlerThread:tids, cfg) Internal.Quit -> do lookupStore 0 >>= \case Nothing -> return () Just x -> deleteStore x mapM_ killThread tids return $ Left "Quit develMain" _ -> return $ Left "Unexpected transition state for develMain." -- | Quit a previously started plugin provider. quitDevelMain :: Internal.Config r st -> IO () quitDevelMain cfg = putMVar (Internal.transitionTo cfg) Internal.Quit -- | Restart the development plugin provider. restartDevelMain :: Internal.Config RPCConfig () -> Maybe NeovimConfig -> IO (Either String ([ThreadId], Internal.Config RPCConfig ())) restartDevelMain cfg mcfg = do quitDevelMain cfg develMain mcfg -- | Convenience function to run a stateless 'Neovim' function. runNeovim' :: Internal.Config r st -> Neovim' a -> IO (Either String a) runNeovim' cfg = fmap (fmap fst) . runNeovim (Internal.retypeConfig () () cfg) ()
gibiansky/nvim-hs
library/Neovim/Debug.hs
apache-2.0
4,618
0
20
1,314
908
473
435
79
6
module Primitives( Render(render), Renderable(Renderable), cylinder, sphere ) where import Vector import Material import Graphics.Rendering.OpenGL import Graphics.UI.GLUT -- Like show, but it actually shows it! class Render a where render :: a -> IO () -- Interesting non-standard way making heterogenius objects of arbitrary -- instances of a typeclass. -- -- Of course, all information about the objects is lost, apart from the fact -- that they are renderable. I'm not sure why there didn't seem to be a -- standard way to do this in haskell, heterogenius collections seems like -- a fairly common problem. data Renderable = forall a . Render a => Renderable a instance Render Renderable where render (Renderable x) = render x instance Render a => Render [a] where render xs = do mapM render xs return () instance Render () where render x = return () -- material, the normal to the quad, then its 4 verticies. -- (? What is the normal used for? Determining which side is in/outside?) data Quad = Quad Material (Normal3 GLfloat) (Vertex3 GLfloat) (Vertex3 GLfloat) (Vertex3 GLfloat) (Vertex3 GLfloat) deriving (Show) instance Render Quad where render (Quad m n v1 v2 v3 v4) = renderPrimitive Quads $ do material m normal n vertex v1 vertex v2 vertex v3 vertex v4 -- material, start point, end point, radius, sides -- -- I later saw that GLUT had a method to render cylinders built in, but I'd -- already written this and it would have required figuring out how to rotate -- them as they were always drawn along the z-axis. cylinder :: Material -> Vector GLfloat -> Vector GLfloat -> GLfloat -> Int -> Renderable cylinder m s e r' n = Renderable $ [Quad m (toNorm (norm i)) (toVertex (r i /+ s)) (toVertex (r i /+ e)) (toVertex (r (i + 1) /+ e)) (toVertex (r (i + 1) /+ s)) | i <- [0..n - 1]] where d = e /- s r 0 = orth /* (r' / len orth) r i = rot d (2 * pi * (fromIntegral i) / n') (r 0) norm i = rot d (2 * pi * ((fromIntegral i) + 0.5) / n') (r 0) orth = orthogonal d n' = fromIntegral n -- material -> position -> radius -> fineness (however that this implemented) data GLUTObject = GLUTObject Material (Vector3 GLfloat) Object deriving (Show) instance Render GLUTObject where render (GLUTObject m pos obj) = preservingMatrix (do translate pos material m renderObject Solid obj) sphere :: Material -> Vector GLfloat -> GLfloat -> Int -> Renderable sphere m v r n = Renderable $ GLUTObject m (toGLVector v) $ Sphere' (realToFrac r) (fromIntegral n) (fromIntegral n)
tkerber/-abandoned-3dlsystem-
Primitives.hs
apache-2.0
2,624
0
14
599
799
406
393
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} module Network.HTTP.Neon.ProgType where import System.Console.CmdArgs data Hneon = Test deriving (Show,Data,Typeable) test :: Hneon test = Test mode = modes [test]
wavewave/hneon
lib/Network/HTTP/Neon/ProgType.hs
bsd-2-clause
223
0
6
48
58
35
23
8
1
{-# LANGUAGE MagicHash #-} {-# LANGUAGE UnboxedTuples #-} {-# LANGUAGE UnliftedFFITypes #-} {-# LANGUAGE GHCForeignImportPrim #-} {-# LANGUAGE ForeignFunctionInterface #-} module Concurrent.Primitive.MVar ( localTakeMVar ) where import GHC.IO import GHC.MVar import GHC.Prim foreign import prim "localTakeMVarzh" localTakeMVar# :: MVar# d a -> State# d -> (# State# d, a #) localTakeMVar :: MVar a -> IO a localTakeMVar (MVar m) = IO $ \s -> localTakeMVar# m s
ekmett/concurrent
src/Concurrent/Primitive/MVar.hs
bsd-2-clause
468
0
9
75
111
61
50
-1
-1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QGraphicsSceneHelpEvent.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:21 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QGraphicsSceneHelpEvent ( qGraphicsSceneHelpEvent_delete ) where import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Enums.Core.QEvent import Qtc.Classes.Base import Qtc.Classes.Qccs import Qtc.Classes.Core import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui import Qtc.ClassTypes.Gui instance QscenePos (QGraphicsSceneHelpEvent a) (()) where scenePos x0 () = withPointFResult $ \cpointf_ret_x cpointf_ret_y -> withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsSceneHelpEvent_scenePos_qth cobj_x0 cpointf_ret_x cpointf_ret_y foreign import ccall "qtc_QGraphicsSceneHelpEvent_scenePos_qth" qtc_QGraphicsSceneHelpEvent_scenePos_qth :: Ptr (TQGraphicsSceneHelpEvent a) -> Ptr CDouble -> Ptr CDouble -> IO () instance QqscenePos (QGraphicsSceneHelpEvent a) (()) where qscenePos x0 () = withQPointFResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsSceneHelpEvent_scenePos cobj_x0 foreign import ccall "qtc_QGraphicsSceneHelpEvent_scenePos" qtc_QGraphicsSceneHelpEvent_scenePos :: Ptr (TQGraphicsSceneHelpEvent a) -> IO (Ptr (TQPointF ())) instance QscreenPos (QGraphicsSceneHelpEvent a) (()) where screenPos x0 () = withPointResult $ \cpoint_ret_x cpoint_ret_y -> withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsSceneHelpEvent_screenPos_qth cobj_x0 cpoint_ret_x cpoint_ret_y foreign import ccall "qtc_QGraphicsSceneHelpEvent_screenPos_qth" qtc_QGraphicsSceneHelpEvent_screenPos_qth :: Ptr (TQGraphicsSceneHelpEvent a) -> Ptr CInt -> Ptr CInt -> IO () instance QqscreenPos (QGraphicsSceneHelpEvent a) (()) where qscreenPos x0 () = withQPointResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsSceneHelpEvent_screenPos cobj_x0 foreign import ccall "qtc_QGraphicsSceneHelpEvent_screenPos" qtc_QGraphicsSceneHelpEvent_screenPos :: Ptr (TQGraphicsSceneHelpEvent a) -> IO (Ptr (TQPoint ())) instance QsetScenePos (QGraphicsSceneHelpEvent a) ((PointF)) where setScenePos x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCPointF x1 $ \cpointf_x1_x cpointf_x1_y -> qtc_QGraphicsSceneHelpEvent_setScenePos_qth cobj_x0 cpointf_x1_x cpointf_x1_y foreign import ccall "qtc_QGraphicsSceneHelpEvent_setScenePos_qth" qtc_QGraphicsSceneHelpEvent_setScenePos_qth :: Ptr (TQGraphicsSceneHelpEvent a) -> CDouble -> CDouble -> IO () instance QqsetScenePos (QGraphicsSceneHelpEvent a) ((QPointF t1)) where qsetScenePos x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsSceneHelpEvent_setScenePos cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsSceneHelpEvent_setScenePos" qtc_QGraphicsSceneHelpEvent_setScenePos :: Ptr (TQGraphicsSceneHelpEvent a) -> Ptr (TQPointF t1) -> IO () instance QsetScreenPos (QGraphicsSceneHelpEvent a) ((Point)) where setScreenPos x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> qtc_QGraphicsSceneHelpEvent_setScreenPos_qth cobj_x0 cpoint_x1_x cpoint_x1_y foreign import ccall "qtc_QGraphicsSceneHelpEvent_setScreenPos_qth" qtc_QGraphicsSceneHelpEvent_setScreenPos_qth :: Ptr (TQGraphicsSceneHelpEvent a) -> CInt -> CInt -> IO () instance QqsetScreenPos (QGraphicsSceneHelpEvent a) ((QPoint t1)) where qsetScreenPos x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsSceneHelpEvent_setScreenPos cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsSceneHelpEvent_setScreenPos" qtc_QGraphicsSceneHelpEvent_setScreenPos :: Ptr (TQGraphicsSceneHelpEvent a) -> Ptr (TQPoint t1) -> IO () qGraphicsSceneHelpEvent_delete :: QGraphicsSceneHelpEvent a -> IO () qGraphicsSceneHelpEvent_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsSceneHelpEvent_delete cobj_x0 foreign import ccall "qtc_QGraphicsSceneHelpEvent_delete" qtc_QGraphicsSceneHelpEvent_delete :: Ptr (TQGraphicsSceneHelpEvent a) -> IO ()
uduki/hsQt
Qtc/Gui/QGraphicsSceneHelpEvent.hs
bsd-2-clause
4,296
0
12
566
981
505
476
-1
-1
{-# LANGUAGE OverloadedStrings #-} module BSPLoader where import Control.Applicative import Control.Monad import Data.Bits import Data.Int import Data.Word import Data.Binary as B import Data.Binary.Get as B import Data.Binary.IEEE754 import Data.Vect hiding (Vector) import Data.Vector (Vector) import qualified Data.ByteString as SB8 import qualified Data.ByteString.Char8 as SB import qualified Data.ByteString.Lazy as LB import qualified Data.Vector as V {- Information: http://graphics.stanford.edu/~kekoa/q3/ Data types Quake 3 BSP files contains only four basic data types. They are: Type Description ubyte unsigned byte int 4-byte integer, little-endian float 4-byte IEEE float, little-endian string[n] string of n ASCII bytes, not necessarily null-terminated All data in a BSP file is organized into records composed of these four data types. -} -- http://www.mralligator.com/q3/ lumpEntities = 0 :: Int -- ^ Game-related object descriptions lumpShaders = 1 :: Int -- ^ Stores texture information lumpPlanes = 2 :: Int -- ^ Stores the splitting planes lumpNodes = 3 :: Int -- ^ Stores the BSP nodes lumpLeaves = 4 :: Int -- ^ Stores the leafs of the nodes lumpLeafSurfaces = 5 :: Int -- ^ Stores the leaf's indices into the faces lumpLeafBrushes = 6 :: Int -- ^ Stores the leaf's indices into the brushes lumpModels = 7 :: Int -- ^ Descriptions of rigid world geometry in map lumpBrushes = 8 :: Int -- ^ Stores the brushes info (for collision) lumpBrushSides = 9 :: Int -- ^ Stores the brush surfaces lumpDrawVertices = 10 :: Int -- ^ Stores the level vertices lumpDrawIndices = 11 :: Int -- ^ Stores the level indices lumpFogs = 12 :: Int -- ^ List of special map effects lumpSurfaces = 13 :: Int -- ^ Stores the faces for the level lumpLightmaps = 14 :: Int -- ^ Stores the lightmaps for the level lumpLightGrid = 15 :: Int -- ^ Local illumination data lumpVisibility = 16 :: Int -- ^ Stores PVS and cluster info (visibility) data Model = Model { mdMins :: Vec3 , mdMaxs :: Vec3 , mdFirstSurface :: Int , mdNumSurfaces :: Int , mdFirstBrush :: Int , mdNumBrushes :: Int } data Shader = Shader { shName :: SB.ByteString , shSurfaceFlags :: Int , shContentFlags :: Int } data Plane = Plane { plNormal :: Vec3 , plDist :: Float } data Node = Node { ndPlaneNum :: Int , ndChildren :: (Int,Int) , ndMins :: Vec3 , ndMaxs :: Vec3 } data Leaf = Leaf { lfCluster :: Int , lfArea :: Int , lfMins :: Vec3 , lfMaxs :: Vec3 , lfFirstLeafSurface :: Int , lfNumLeafSurfaces :: Int , lfFirstLeafBrush :: Int , lfNumLeafBrushes :: Int } data BrushSide = BrushSide { bsPlaneNum :: Int , bsShaderNum :: Int } data Brush = Brush { brFirstSide :: Int , brNumSides :: Int , brShaderNum :: Int } data Fog = Fog { fgName :: SB.ByteString , fgBrushNum :: Int , fgVisibleSide :: Int } data DrawVertex = DrawVertex { dvPosition :: Vec3 , dvDiffuseUV :: Vec2 , dvLightmaptUV :: Vec2 , dvNormal :: Vec3 , dvColor :: Vec4 } data SurfaceType = Planar | Patch | TriangleSoup | Flare data Surface = Surface { srShaderNum :: Int , srFogNum :: Int , srSurfaceType :: SurfaceType , srFirstVertex :: Int , srNumVertices :: Int , srFirstIndex :: Int , srNumIndices :: Int , srLightmapNum :: Int , srLightmapPos :: Vec2 , srLightmapSize :: Vec2 , srLightmapOrigin :: Vec3 , srLightmapVec1 :: Vec3 , srLightmapVec2 :: Vec3 , srLightmapVec3 :: Vec3 , srPatchSize :: (Int,Int) } data Lightmap = Lightmap { lmMap :: SB.ByteString } data LightGrid = LightGrid data Visibility = Visibility { vsNumVecs :: Int , vsSizeVecs :: Int , vsVecs :: Vector Word8 } data BSPLevel = BSPLevel { blEntities :: SB.ByteString , blShaders :: Vector Shader , blPlanes :: Vector Plane , blNodes :: Vector Node , blLeaves :: Vector Leaf , blLeafSurfaces :: Vector Int , blLeafBrushes :: Vector Int , blModels :: Vector Model , blBrushes :: Vector Brush , blBrushSides :: Vector BrushSide , blDrawVertices :: Vector DrawVertex , blDrawIndices :: Vector Int , blFogs :: Vector Fog , blSurfaces :: Vector Surface , blLightmaps :: Vector Lightmap , blLightgrid :: Vector LightGrid , blVisibility :: Visibility } getString = fmap (SB.takeWhile (/= '\0')) . getByteString getWord = getWord32le getUByte = B.get :: Get Word8 getUByte2 = B.get :: Get (Word8,Word8) getUByte3 = B.get :: Get (Word8,Word8,Word8) getFloat = getFloat32le getVec2 = Vec2 <$> getFloat <*> getFloat getVec3 = (\x y z -> Vec3 x z (-y)) <$> getFloat <*> getFloat <*> getFloat getVec2i = (\x y -> Vec2 (fromIntegral x) (fromIntegral y)) <$> getInt <*> getInt getVec3i = (\x y z -> Vec3 (fromIntegral x) (fromIntegral z) (fromIntegral (-y))) <$> getInt <*> getInt <*> getInt getVec4RGBA = (\r g b a -> Vec4 (f r) (f g) (f b) (f a)) <$> getUByte <*> getUByte <*> getUByte <*> getUByte where f v = fromIntegral v / 255 getInt = fromIntegral <$> getInt' :: Get Int where getInt' = fromIntegral <$> getWord32le :: Get Int32 getInt2 = (,) <$> getInt <*> getInt getItems s act l = V.fromList <$> replicateM (l `div` s) act getHeader = do magic <- getString 4 case magic == "IBSP" of True -> return () _ -> error "Invalid format." version <- getWord el <- replicateM 17 getInt2 return (magic,version,el) getBSPLevel el = BSPLevel <$> getLump getEntities lumpEntities <*> getLump getShaders lumpShaders <*> getLump getPlanes lumpPlanes <*> getLump getNodes lumpNodes <*> getLump getLeaves lumpLeaves <*> getLump getLeafSurfaces lumpLeafSurfaces <*> getLump getLeafBrushes lumpLeafBrushes <*> getLump getModels lumpModels <*> getLump getBrushes lumpBrushes <*> getLump getBrushSides lumpBrushSides <*> getLump getDrawVertices lumpDrawVertices <*> getLump getDrawIndices lumpDrawIndices <*> getLump getFogs lumpFogs <*> getLump getSurfaces lumpSurfaces <*> getLump getLightmaps lumpLightmaps <*> getLump getLightGrid lumpLightGrid <*> getLump getVisibility lumpVisibility where getLump g i = lookAhead $ do let (o,l) = el !! i skip o g l getSurfaceType = getInt >>= \i -> return $ case i of 1 -> Planar 2 -> Patch 3 -> TriangleSoup 4 -> Flare _ -> error "Invalid surface type" getEntities l = getString l getShaders = getItems 72 $ Shader <$> getString 64 <*> getInt <*> getInt getPlanes = getItems 16 $ Plane <$> getVec3 <*> getFloat getNodes = getItems 36 $ Node <$> getInt <*> getInt2 <*> getVec3i <*> getVec3i getLeaves = getItems 48 $ Leaf <$> getInt <*> getInt <*> getVec3i <*> getVec3i <*> getInt <*> getInt <*> getInt <*> getInt getLeafSurfaces = getItems 4 getInt getLeafBrushes = getItems 4 getInt getModels = getItems 40 $ Model <$> getVec3 <*> getVec3 <*> getInt <*> getInt <*> getInt <*> getInt getBrushes = getItems 12 $ Brush <$> getInt <*> getInt <*> getInt getBrushSides = getItems 8 $ BrushSide <$> getInt <*> getInt getDrawVertices = getItems 44 $ DrawVertex <$> getVec3 <*> getVec2 <*> getVec2 <*> getVec3 <*> getVec4RGBA getDrawIndices = getItems 4 getInt getFogs = getItems 72 $ Fog <$> getString 64 <*> getInt <*> getInt getSurfaces = getItems 104 $ Surface <$> getInt <*> getInt <*> getSurfaceType <*> getInt <*> getInt <*> getInt <*> getInt <*> getInt <*> getVec2i <*> getVec2i <*> getVec3 <*> getVec3 <*> getVec3 <*> getVec3 <*> getInt2 getLightmaps = getItems (128*128*3) (Lightmap <$> (getByteString $ 128*128*3)) getLightGrid = getItems 8 $ do ambient <- getUByte3 directional <- getUByte3 dir <- getUByte2 return LightGrid getVisibility l = do nvecs <- getInt szvecs <- getInt vecs <- getByteString $ nvecs * szvecs return $ Visibility nvecs szvecs $ V.fromList $ SB8.unpack vecs loadBSP :: String -> IO BSPLevel loadBSP n = readBSP <$> LB.readFile n readBSP dat = do let (magic,version,el) = runGet getHeader dat runGet (getBSPLevel el) dat
csabahruska/GFXDemo
BSPLoader.hs
bsd-3-clause
8,889
0
22
2,585
2,243
1,237
1,006
221
5
{-# LANGUAGE BangPatterns, TypeOperators, CPP, MultiParamTypeClasses, UnboxedTuples, MagicHash, NamedFieldPuns, FlexibleInstances #-} module Data.TrieMap.WordMap.Searchable () where import Control.Monad.Unpack import Control.Monad.Option import Data.TrieMap.TrieKey import Data.Word import Data.TrieMap.WordMap.Base import Data.TrieMap.WordMap.Zippable () import Prelude hiding (lookup) import GHC.Exts #define BIN(args) SNode{node = (Bin args)} #define TIP(args) SNode{node = (Tip args)} #define NIL SNode{node = Nil} instance Searchable (TrieMap Word) Word where search k (WordMap m) = mapHole Hole (search k m) singleZip = Hole . singleZip singleton = WordMap .: singleton lookup k (WordMap m) = lookup k m insertWith f k a (WordMap m) = WordMap (insertWith f k a m) instance Searchable SNode Word where {-# INLINE search #-} search k t notfound found = searchC k t (unpack notfound) (unpack . found) singleZip k = WHole k Root singleton = single {-# INLINE lookup #-} lookup !k !t = option $ \ no yes -> let look BIN(_ m l r) = if zeroN k m then look l else look r look TIP(kx x) | k == kx = yes x look _ = no in look t {-# INLINE insertWith #-} insertWith f k a m = insertWithC f k (getSize a) a m searchC :: Key -> SNode a -> (Zipper SNode a :~> r) -> (a -> Zipper SNode a :~> r) -> r searchC !k t notfound found = seek Root t where seek path t@BIN(p m l r) | nomatch k p m = notfound $~ WHole k (branchHole k p path t) | mask0 k m = seek (LeftBin p m path r) l | otherwise = seek (RightBin p m l path) r seek path t@TIP(ky y) | k == ky = found y $~ WHole k path | otherwise = notfound $~ WHole k (branchHole k ky path t) seek path NIL = notfound $~ WHole k path insertWithC :: Sized a => (a -> a) -> Key -> Int -> a -> SNode a -> SNode a insertWithC f !k !szA a !t = ins' t where {-# INLINE tip #-} tip = SNode {sz = szA, node = Tip k a} {-# INLINE out #-} out SNode{sz = I# sz#, node} = (# sz#, node #) {-# INLINE ins' #-} ins' t = case ins t of (# sz#, node #) -> SNode{sz = I# sz#, node} ins !t = case t of BIN(p m l r) | nomatch k p m -> out $ join k tip p t | mask0 k m -> out $ bin' p m (ins' l) r | otherwise -> out $ bin' p m l (ins' r) TIP(kx x) | k == kx -> out $ singleton kx (f x) | otherwise -> out $ join k tip kx t NIL -> out tip
lowasser/TrieMap
Data/TrieMap/WordMap/Searchable.hs
bsd-3-clause
2,415
28
16
624
1,056
520
536
-1
-1
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module GHC.Hs.Instances where -- This module defines the Data instances for the hsSyn AST. -- It happens here to avoid massive constraint types on the AST with concomitant -- slow GHC bootstrap times. -- UndecidableInstances ? import Data.Data hiding ( Fixity ) import GhcPrelude import GHC.Hs.Extension import GHC.Hs.Binds import GHC.Hs.Decls import GHC.Hs.Expr import GHC.Hs.Lit import GHC.Hs.Types import GHC.Hs.Pat import GHC.Hs.ImpExp -- --------------------------------------------------------------------- -- Data derivations from GHC.Hs----------------------------------------- -- --------------------------------------------------------------------- -- Data derivations from GHC.Hs.Binds ---------------------------------- -- deriving instance (DataIdLR pL pR) => Data (HsLocalBindsLR pL pR) deriving instance Data (HsLocalBindsLR GhcPs GhcPs) deriving instance Data (HsLocalBindsLR GhcPs GhcRn) deriving instance Data (HsLocalBindsLR GhcRn GhcRn) deriving instance Data (HsLocalBindsLR GhcTc GhcTc) -- deriving instance (DataIdLR pL pR) => Data (HsValBindsLR pL pR) deriving instance Data (HsValBindsLR GhcPs GhcPs) deriving instance Data (HsValBindsLR GhcPs GhcRn) deriving instance Data (HsValBindsLR GhcRn GhcRn) deriving instance Data (HsValBindsLR GhcTc GhcTc) -- deriving instance (DataIdLR pL pL) => Data (NHsValBindsLR pL) deriving instance Data (NHsValBindsLR GhcPs) deriving instance Data (NHsValBindsLR GhcRn) deriving instance Data (NHsValBindsLR GhcTc) -- deriving instance (DataIdLR pL pR) => Data (HsBindLR pL pR) deriving instance Data (HsBindLR GhcPs GhcPs) deriving instance Data (HsBindLR GhcPs GhcRn) deriving instance Data (HsBindLR GhcRn GhcRn) deriving instance Data (HsBindLR GhcTc GhcTc) -- deriving instance (DataId p) => Data (ABExport p) deriving instance Data (ABExport GhcPs) deriving instance Data (ABExport GhcRn) deriving instance Data (ABExport GhcTc) -- deriving instance (DataIdLR pL pR) => Data (PatSynBind pL pR) deriving instance Data (PatSynBind GhcPs GhcPs) deriving instance Data (PatSynBind GhcPs GhcRn) deriving instance Data (PatSynBind GhcRn GhcRn) deriving instance Data (PatSynBind GhcTc GhcTc) -- deriving instance (DataIdLR p p) => Data (HsIPBinds p) deriving instance Data (HsIPBinds GhcPs) deriving instance Data (HsIPBinds GhcRn) deriving instance Data (HsIPBinds GhcTc) -- deriving instance (DataIdLR p p) => Data (IPBind p) deriving instance Data (IPBind GhcPs) deriving instance Data (IPBind GhcRn) deriving instance Data (IPBind GhcTc) -- deriving instance (DataIdLR p p) => Data (Sig p) deriving instance Data (Sig GhcPs) deriving instance Data (Sig GhcRn) deriving instance Data (Sig GhcTc) -- deriving instance (DataId p) => Data (FixitySig p) deriving instance Data (FixitySig GhcPs) deriving instance Data (FixitySig GhcRn) deriving instance Data (FixitySig GhcTc) -- deriving instance (DataId p) => Data (StandaloneKindSig p) deriving instance Data (StandaloneKindSig GhcPs) deriving instance Data (StandaloneKindSig GhcRn) deriving instance Data (StandaloneKindSig GhcTc) -- deriving instance (DataIdLR p p) => Data (HsPatSynDir p) deriving instance Data (HsPatSynDir GhcPs) deriving instance Data (HsPatSynDir GhcRn) deriving instance Data (HsPatSynDir GhcTc) -- --------------------------------------------------------------------- -- Data derivations from GHC.Hs.Decls ---------------------------------- -- deriving instance (DataIdLR p p) => Data (HsDecl p) deriving instance Data (HsDecl GhcPs) deriving instance Data (HsDecl GhcRn) deriving instance Data (HsDecl GhcTc) -- deriving instance (DataIdLR p p) => Data (HsGroup p) deriving instance Data (HsGroup GhcPs) deriving instance Data (HsGroup GhcRn) deriving instance Data (HsGroup GhcTc) -- deriving instance (DataIdLR p p) => Data (SpliceDecl p) deriving instance Data (SpliceDecl GhcPs) deriving instance Data (SpliceDecl GhcRn) deriving instance Data (SpliceDecl GhcTc) -- deriving instance (DataIdLR p p) => Data (TyClDecl p) deriving instance Data (TyClDecl GhcPs) deriving instance Data (TyClDecl GhcRn) deriving instance Data (TyClDecl GhcTc) -- deriving instance (DataIdLR p p) => Data (TyClGroup p) deriving instance Data (TyClGroup GhcPs) deriving instance Data (TyClGroup GhcRn) deriving instance Data (TyClGroup GhcTc) -- deriving instance (DataIdLR p p) => Data (FamilyResultSig p) deriving instance Data (FamilyResultSig GhcPs) deriving instance Data (FamilyResultSig GhcRn) deriving instance Data (FamilyResultSig GhcTc) -- deriving instance (DataIdLR p p) => Data (FamilyDecl p) deriving instance Data (FamilyDecl GhcPs) deriving instance Data (FamilyDecl GhcRn) deriving instance Data (FamilyDecl GhcTc) -- deriving instance (DataIdLR p p) => Data (InjectivityAnn p) deriving instance Data (InjectivityAnn GhcPs) deriving instance Data (InjectivityAnn GhcRn) deriving instance Data (InjectivityAnn GhcTc) -- deriving instance (DataIdLR p p) => Data (FamilyInfo p) deriving instance Data (FamilyInfo GhcPs) deriving instance Data (FamilyInfo GhcRn) deriving instance Data (FamilyInfo GhcTc) -- deriving instance (DataIdLR p p) => Data (HsDataDefn p) deriving instance Data (HsDataDefn GhcPs) deriving instance Data (HsDataDefn GhcRn) deriving instance Data (HsDataDefn GhcTc) -- deriving instance (DataIdLR p p) => Data (HsDerivingClause p) deriving instance Data (HsDerivingClause GhcPs) deriving instance Data (HsDerivingClause GhcRn) deriving instance Data (HsDerivingClause GhcTc) -- deriving instance (DataIdLR p p) => Data (ConDecl p) deriving instance Data (ConDecl GhcPs) deriving instance Data (ConDecl GhcRn) deriving instance Data (ConDecl GhcTc) -- deriving instance DataIdLR p p => Data (TyFamInstDecl p) deriving instance Data (TyFamInstDecl GhcPs) deriving instance Data (TyFamInstDecl GhcRn) deriving instance Data (TyFamInstDecl GhcTc) -- deriving instance DataIdLR p p => Data (DataFamInstDecl p) deriving instance Data (DataFamInstDecl GhcPs) deriving instance Data (DataFamInstDecl GhcRn) deriving instance Data (DataFamInstDecl GhcTc) -- deriving instance (DataIdLR p p,Data rhs)=>Data (FamEqn p rhs) deriving instance Data rhs => Data (FamEqn GhcPs rhs) deriving instance Data rhs => Data (FamEqn GhcRn rhs) deriving instance Data rhs => Data (FamEqn GhcTc rhs) -- deriving instance (DataIdLR p p) => Data (ClsInstDecl p) deriving instance Data (ClsInstDecl GhcPs) deriving instance Data (ClsInstDecl GhcRn) deriving instance Data (ClsInstDecl GhcTc) -- deriving instance (DataIdLR p p) => Data (InstDecl p) deriving instance Data (InstDecl GhcPs) deriving instance Data (InstDecl GhcRn) deriving instance Data (InstDecl GhcTc) -- deriving instance (DataIdLR p p) => Data (DerivDecl p) deriving instance Data (DerivDecl GhcPs) deriving instance Data (DerivDecl GhcRn) deriving instance Data (DerivDecl GhcTc) -- deriving instance (DataIdLR p p) => Data (DerivStrategy p) deriving instance Data (DerivStrategy GhcPs) deriving instance Data (DerivStrategy GhcRn) deriving instance Data (DerivStrategy GhcTc) -- deriving instance (DataIdLR p p) => Data (DefaultDecl p) deriving instance Data (DefaultDecl GhcPs) deriving instance Data (DefaultDecl GhcRn) deriving instance Data (DefaultDecl GhcTc) -- deriving instance (DataIdLR p p) => Data (ForeignDecl p) deriving instance Data (ForeignDecl GhcPs) deriving instance Data (ForeignDecl GhcRn) deriving instance Data (ForeignDecl GhcTc) -- deriving instance (DataIdLR p p) => Data (RuleDecls p) deriving instance Data (RuleDecls GhcPs) deriving instance Data (RuleDecls GhcRn) deriving instance Data (RuleDecls GhcTc) -- deriving instance (DataIdLR p p) => Data (RuleDecl p) deriving instance Data (RuleDecl GhcPs) deriving instance Data (RuleDecl GhcRn) deriving instance Data (RuleDecl GhcTc) -- deriving instance (DataIdLR p p) => Data (RuleBndr p) deriving instance Data (RuleBndr GhcPs) deriving instance Data (RuleBndr GhcRn) deriving instance Data (RuleBndr GhcTc) -- deriving instance (DataId p) => Data (WarnDecls p) deriving instance Data (WarnDecls GhcPs) deriving instance Data (WarnDecls GhcRn) deriving instance Data (WarnDecls GhcTc) -- deriving instance (DataId p) => Data (WarnDecl p) deriving instance Data (WarnDecl GhcPs) deriving instance Data (WarnDecl GhcRn) deriving instance Data (WarnDecl GhcTc) -- deriving instance (DataIdLR p p) => Data (AnnDecl p) deriving instance Data (AnnDecl GhcPs) deriving instance Data (AnnDecl GhcRn) deriving instance Data (AnnDecl GhcTc) -- deriving instance (DataId p) => Data (RoleAnnotDecl p) deriving instance Data (RoleAnnotDecl GhcPs) deriving instance Data (RoleAnnotDecl GhcRn) deriving instance Data (RoleAnnotDecl GhcTc) -- --------------------------------------------------------------------- -- Data derivations from GHC.Hs.Expr ----------------------------------- -- deriving instance (DataIdLR p p) => Data (SyntaxExpr p) deriving instance Data (SyntaxExpr GhcPs) deriving instance Data (SyntaxExpr GhcRn) deriving instance Data (SyntaxExpr GhcTc) -- deriving instance (DataIdLR p p) => Data (HsPragE p) deriving instance Data (HsPragE GhcPs) deriving instance Data (HsPragE GhcRn) deriving instance Data (HsPragE GhcTc) -- deriving instance (DataIdLR p p) => Data (HsExpr p) deriving instance Data (HsExpr GhcPs) deriving instance Data (HsExpr GhcRn) deriving instance Data (HsExpr GhcTc) -- deriving instance (DataIdLR p p) => Data (HsTupArg p) deriving instance Data (HsTupArg GhcPs) deriving instance Data (HsTupArg GhcRn) deriving instance Data (HsTupArg GhcTc) -- deriving instance (DataIdLR p p) => Data (HsCmd p) deriving instance Data (HsCmd GhcPs) deriving instance Data (HsCmd GhcRn) deriving instance Data (HsCmd GhcTc) -- deriving instance (DataIdLR p p) => Data (HsCmdTop p) deriving instance Data (HsCmdTop GhcPs) deriving instance Data (HsCmdTop GhcRn) deriving instance Data (HsCmdTop GhcTc) -- deriving instance (DataIdLR p p,Data body) => Data (MatchGroup p body) deriving instance (Data body) => Data (MatchGroup GhcPs body) deriving instance (Data body) => Data (MatchGroup GhcRn body) deriving instance (Data body) => Data (MatchGroup GhcTc body) -- deriving instance (DataIdLR p p,Data body) => Data (Match p body) deriving instance (Data body) => Data (Match GhcPs body) deriving instance (Data body) => Data (Match GhcRn body) deriving instance (Data body) => Data (Match GhcTc body) -- deriving instance (DataIdLR p p,Data body) => Data (GRHSs p body) deriving instance (Data body) => Data (GRHSs GhcPs body) deriving instance (Data body) => Data (GRHSs GhcRn body) deriving instance (Data body) => Data (GRHSs GhcTc body) -- deriving instance (DataIdLR p p,Data body) => Data (GRHS p body) deriving instance (Data body) => Data (GRHS GhcPs body) deriving instance (Data body) => Data (GRHS GhcRn body) deriving instance (Data body) => Data (GRHS GhcTc body) -- deriving instance (DataIdLR p p,Data body) => Data (StmtLR p p body) deriving instance (Data body) => Data (StmtLR GhcPs GhcPs body) deriving instance (Data body) => Data (StmtLR GhcPs GhcRn body) deriving instance (Data body) => Data (StmtLR GhcRn GhcRn body) deriving instance (Data body) => Data (StmtLR GhcTc GhcTc body) deriving instance Data RecStmtTc -- deriving instance (DataIdLR p p) => Data (ParStmtBlock p p) deriving instance Data (ParStmtBlock GhcPs GhcPs) deriving instance Data (ParStmtBlock GhcPs GhcRn) deriving instance Data (ParStmtBlock GhcRn GhcRn) deriving instance Data (ParStmtBlock GhcTc GhcTc) -- deriving instance (DataIdLR p p) => Data (ApplicativeArg p) deriving instance Data (ApplicativeArg GhcPs) deriving instance Data (ApplicativeArg GhcRn) deriving instance Data (ApplicativeArg GhcTc) -- deriving instance (DataIdLR p p) => Data (HsSplice p) deriving instance Data (HsSplice GhcPs) deriving instance Data (HsSplice GhcRn) deriving instance Data (HsSplice GhcTc) -- deriving instance (DataIdLR p p) => Data (HsSplicedThing p) deriving instance Data (HsSplicedThing GhcPs) deriving instance Data (HsSplicedThing GhcRn) deriving instance Data (HsSplicedThing GhcTc) -- deriving instance (DataIdLR p p) => Data (HsBracket p) deriving instance Data (HsBracket GhcPs) deriving instance Data (HsBracket GhcRn) deriving instance Data (HsBracket GhcTc) -- deriving instance (DataIdLR p p) => Data (ArithSeqInfo p) deriving instance Data (ArithSeqInfo GhcPs) deriving instance Data (ArithSeqInfo GhcRn) deriving instance Data (ArithSeqInfo GhcTc) deriving instance Data RecordConTc deriving instance Data CmdTopTc deriving instance Data PendingRnSplice deriving instance Data PendingTcSplice -- --------------------------------------------------------------------- -- Data derivations from GHC.Hs.Lit ------------------------------------ -- deriving instance (DataId p) => Data (HsLit p) deriving instance Data (HsLit GhcPs) deriving instance Data (HsLit GhcRn) deriving instance Data (HsLit GhcTc) -- deriving instance (DataIdLR p p) => Data (HsOverLit p) deriving instance Data (HsOverLit GhcPs) deriving instance Data (HsOverLit GhcRn) deriving instance Data (HsOverLit GhcTc) -- --------------------------------------------------------------------- -- Data derivations from GHC.Hs.Pat ------------------------------------ -- deriving instance (DataIdLR p p) => Data (Pat p) deriving instance Data (Pat GhcPs) deriving instance Data (Pat GhcRn) deriving instance Data (Pat GhcTc) deriving instance Data ListPatTc -- deriving instance (DataIdLR p p, Data body) => Data (HsRecFields p body) deriving instance (Data body) => Data (HsRecFields GhcPs body) deriving instance (Data body) => Data (HsRecFields GhcRn body) deriving instance (Data body) => Data (HsRecFields GhcTc body) -- --------------------------------------------------------------------- -- Data derivations from GHC.Hs.Types ---------------------------------- -- deriving instance (DataIdLR p p) => Data (LHsQTyVars p) deriving instance Data (LHsQTyVars GhcPs) deriving instance Data (LHsQTyVars GhcRn) deriving instance Data (LHsQTyVars GhcTc) -- deriving instance (DataIdLR p p, Data thing) =>Data (HsImplicitBndrs p thing) deriving instance (Data thing) => Data (HsImplicitBndrs GhcPs thing) deriving instance (Data thing) => Data (HsImplicitBndrs GhcRn thing) deriving instance (Data thing) => Data (HsImplicitBndrs GhcTc thing) -- deriving instance (DataIdLR p p, Data thing) =>Data (HsWildCardBndrs p thing) deriving instance (Data thing) => Data (HsWildCardBndrs GhcPs thing) deriving instance (Data thing) => Data (HsWildCardBndrs GhcRn thing) deriving instance (Data thing) => Data (HsWildCardBndrs GhcTc thing) -- deriving instance (DataIdLR p p) => Data (HsTyVarBndr p) deriving instance Data (HsTyVarBndr GhcPs) deriving instance Data (HsTyVarBndr GhcRn) deriving instance Data (HsTyVarBndr GhcTc) -- deriving instance (DataIdLR p p) => Data (HsType p) deriving instance Data (HsType GhcPs) deriving instance Data (HsType GhcRn) deriving instance Data (HsType GhcTc) deriving instance Data (LHsTypeArg GhcPs) deriving instance Data (LHsTypeArg GhcRn) deriving instance Data (LHsTypeArg GhcTc) -- deriving instance (DataIdLR p p) => Data (ConDeclField p) deriving instance Data (ConDeclField GhcPs) deriving instance Data (ConDeclField GhcRn) deriving instance Data (ConDeclField GhcTc) -- deriving instance (DataId p) => Data (FieldOcc p) deriving instance Data (FieldOcc GhcPs) deriving instance Data (FieldOcc GhcRn) deriving instance Data (FieldOcc GhcTc) -- deriving instance DataId p => Data (AmbiguousFieldOcc p) deriving instance Data (AmbiguousFieldOcc GhcPs) deriving instance Data (AmbiguousFieldOcc GhcRn) deriving instance Data (AmbiguousFieldOcc GhcTc) -- deriving instance (DataId name) => Data (ImportDecl name) deriving instance Data (ImportDecl GhcPs) deriving instance Data (ImportDecl GhcRn) deriving instance Data (ImportDecl GhcTc) -- deriving instance (DataId name) => Data (IE name) deriving instance Data (IE GhcPs) deriving instance Data (IE GhcRn) deriving instance Data (IE GhcTc) -- deriving instance (Eq name, Eq (IdP name)) => Eq (IE name) deriving instance Eq (IE GhcPs) deriving instance Eq (IE GhcRn) deriving instance Eq (IE GhcTc) -- ---------------------------------------------------------------------
sdiehl/ghc
compiler/GHC/Hs/Instances.hs
bsd-3-clause
16,662
0
7
2,455
3,715
1,929
1,786
249
0
main :: Stream -> Stream main stdin = toStream "Hello, world!\n"
tromp/hs2blc
examples/hello.hs
bsd-3-clause
65
0
5
11
21
10
11
2
1
module Evaluation where import Syntax import Data.Maybe import Prelude hiding (lookup) -- a frequently used pattern match x1 x2 f1 f2 = if x1 == x2 then f1 else f2 -- see slide 546 type Environment = [(Identifier, Location)] type Store = [(Location, Int)] type Location = Int -- see slide 553 type PEnvironment = [(Procedure, Store -> Store)] -- see slide 547 lookup :: Environment -> Store -> Identifier -> Maybe Int lookup env sto = store2value sto . env2loc env env2loc :: Environment -> Identifier -> Maybe Location env2loc [] x = Nothing env2loc ((x1,l):xls) x2 = match x1 x2 (Just l) (env2loc xls x2) store2value :: Store -> Maybe Location -> Maybe Int store2value _ Nothing = Nothing store2value [] (Just l) = Nothing store2value ((l1,v):lvs) (Just l2) = match l1 l2 (Just v) (store2value lvs (Just l2)) -- same old thing, with State replaced by Environment and Store, as slide 546 suggested evala :: AExpression -> Environment -> Store -> Int evala (Number n) _ _ = n evala (Identifier x) env sto = Data.Maybe.fromMaybe (error "Undefined variable") (lookup env sto x) evala (Add a1 a2) env sto = evala a1 env sto + evala a2 env sto evala (Sub a1 a2) env sto = evala a1 env sto - evala a2 env sto evala (Mul a1 a2) env sto = evala a1 env sto * evala a2 env sto evalb :: BExpression -> Environment -> Store -> Bool evalb BTrue _ _ = True evalb BFalse _ _ = False evalb (Equals a1 a2) env sto = evala a1 env sto == evala a2 env sto evalb (LessThanOrEqual a1 a2) env sto = evala a1 env sto <= evala a2 env sto evalb (Not b) env sto = not (evalb b env sto) evalb (And b1 b2) env sto = evalb b1 env sto && evalb b2 env sto
grammarware/slps
topics/semantics/while/extended/Evaluation.hs
bsd-3-clause
1,641
6
9
330
709
365
344
34
2
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} module Stack.Solver ( checkResolverSpec , cabalPackagesCheck , findCabalFiles , getResolverConstraints , mergeConstraints , solveExtraDeps , solveResolverSpec -- * Internal - for tests , parseCabalOutputLine ) where import Prelude () import Prelude.Compat import Control.Applicative import Control.Exception (assert) import Control.Exception.Enclosed (tryIO) import Control.Monad (when,void,join,liftM,unless,zipWithM_) import Control.Monad.Catch import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Reader (MonadReader, asks) import Control.Monad.Trans.Control import Data.Aeson.Extended ( WithJSONWarnings(..), object, (.=), toJSON , logJSONWarnings) import qualified Data.ByteString as S import Data.Char (isSpace) import Data.Either import Data.Function (on) import qualified Data.HashMap.Strict as HashMap import Data.List ( (\\), isSuffixOf, intercalate , minimumBy, isPrefixOf) import Data.List.Extra (groupSortOn) import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (catMaybes, isNothing, mapMaybe) import Data.Monoid import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (decodeUtf8, encodeUtf8) import Data.Text.Encoding.Error (lenientDecode) import qualified Data.Text.Lazy as LT import Data.Text.Lazy.Encoding (decodeUtf8With) import Data.Tuple (swap) import qualified Data.Yaml as Yaml import qualified Distribution.Package as C import qualified Distribution.PackageDescription as C import qualified Distribution.Text as C import Network.HTTP.Client.Conduit (HasHttpManager) import Text.Regex.Applicative.Text (match, sym, psym, anySym, few) import Path import Path.Find (findFiles) import Path.IO hiding (findExecutable, findFiles) import Stack.BuildPlan import Stack.Constants (stackDotYaml) import Stack.Package (printCabalFileWarning , hpack , readPackageUnresolved) import Stack.Setup import Stack.Setup.Installed import Stack.Types import Stack.Types.Internal ( HasTerminal , HasReExec , HasLogLevel) import qualified System.Directory as D import qualified System.FilePath as FP import System.Process.Read data ConstraintType = Constraint | Preference deriving (Eq) type ConstraintSpec = Map PackageName (Version, Map FlagName Bool) cabalSolver :: (MonadIO m, MonadLogger m, MonadMask m, MonadBaseControl IO m, MonadReader env m, HasConfig env) => EnvOverride -> [Path Abs Dir] -- ^ cabal files -> ConstraintType -> ConstraintSpec -- ^ src constraints -> ConstraintSpec -- ^ dep constraints -> [String] -- ^ additional arguments -> m (Either [PackageName] ConstraintSpec) cabalSolver menv cabalfps constraintType srcConstraints depConstraints cabalArgs = withSystemTempDir "cabal-solver" $ \dir' -> do let versionConstraints = fmap fst depConstraints dir = toFilePath dir' configLines <- getCabalConfig dir constraintType versionConstraints let configFile = dir FP.</> "cabal.config" liftIO $ S.writeFile configFile $ encodeUtf8 $ T.unlines configLines -- Run from a temporary directory to avoid cabal getting confused by any -- sandbox files, see: -- https://github.com/commercialhaskell/stack/issues/356 -- -- In theory we could use --ignore-sandbox, but not all versions of cabal -- support it. tmpdir <- getTempDir let args = ("--config-file=" ++ configFile) : "install" : "--enable-tests" : "--enable-benchmarks" : "--dry-run" : "--reorder-goals" : "--max-backjumps=-1" : "--package-db=clear" : "--package-db=global" : cabalArgs ++ toConstraintArgs (flagConstraints constraintType) ++ fmap toFilePath cabalfps catch (liftM Right (readProcessStdout (Just tmpdir) menv "cabal" args)) (\ex -> case ex of ReadProcessException _ _ _ err -> return $ Left err _ -> throwM ex) >>= either parseCabalErrors parseCabalOutput where errCheck = T.isInfixOf "Could not resolve dependencies" cabalBuildErrMsg e = ">>>> Cabal errors begin\n" <> e <> "<<<< Cabal errors end\n" parseCabalErrors err = do let errExit e = error $ "Could not parse cabal-install errors:\n\n" ++ cabalBuildErrMsg (T.unpack e) msg = LT.toStrict $ decodeUtf8With lenientDecode err if errCheck msg then do $logInfo "Attempt failed.\n" $logInfo $ cabalBuildErrMsg msg let pkgs = parseConflictingPkgs msg mPkgNames = map (C.simpleParse . T.unpack) pkgs pkgNames = map (fromCabalPackageName . C.pkgName) (catMaybes mPkgNames) when (any isNothing mPkgNames) $ do $logInfo $ "*** Only some package names could be parsed: " <> (T.pack (intercalate ", " (map show pkgNames))) error $ T.unpack $ "*** User packages involved in cabal failure: " <> (T.intercalate ", " $ parseConflictingPkgs msg) if pkgNames /= [] then do return $ Left pkgNames else errExit msg else errExit msg parseConflictingPkgs msg = let ls = dropWhile (not . errCheck) $ T.lines msg select s = ((T.isPrefixOf "trying:" s) || (T.isPrefixOf "next goal:" s)) && (T.isSuffixOf "(user goal)" s) pkgName = (take 1) . T.words . (T.drop 1) . (T.dropWhile (/= ':')) in concat $ map pkgName (filter select ls) parseCabalOutput bs = do let ls = drop 1 $ dropWhile (not . T.isPrefixOf "In order, ") $ T.lines $ decodeUtf8 bs (errs, pairs) = partitionEithers $ map parseCabalOutputLine ls if null errs then return $ Right (Map.fromList pairs) else error $ "The following lines from cabal-install output could \ \not be parsed: \n" ++ (T.unpack (T.intercalate "\n" errs)) toConstraintArgs userFlagMap = [formatFlagConstraint package flag enabled | (package, fs) <- Map.toList userFlagMap , (flag, enabled) <- Map.toList fs] formatFlagConstraint package flag enabled = let sign = if enabled then '+' else '-' in "--constraint=" ++ unwords [packageNameString package, sign : flagNameString flag] -- Note the order of the Map union is important -- We override a package in snapshot by a src package flagConstraints Constraint = fmap snd (Map.union srcConstraints depConstraints) -- Even when using preferences we want to -- keep the src package flags unchanged -- TODO - this should be done only for manual flags. flagConstraints Preference = fmap snd srcConstraints -- An ugly parser to extract module id and flags parseCabalOutputLine :: Text -> Either Text (PackageName, (Version, Map FlagName Bool)) parseCabalOutputLine t0 = maybe (Left t0) Right . join . match re $ t0 -- Sample outputs to parse: -- text-1.2.1.1 (latest: 1.2.2.0) -integer-simple (via: parsec-3.1.9) (new package)) -- hspec-snap-1.0.0.0 *test (via: servant-snap-0.5) (new package) -- time-locale-compat-0.1.1.1 -old-locale (via: http-api-data-0.2.2) (new package)) -- flowdock-rest-0.2.0.0 -aeson-compat *test (via: haxl-fxtra-0.0.0.0) (new package) where re = mk <$> some (psym $ not . isSpace) <*> many (lexeme reMaybeFlag) reMaybeFlag = (\s -> Just (True, s)) <$ sym '+' <*> some (psym $ not . isSpace) <|> (\s -> Just (False, s)) <$ sym '-' <*> some (psym $ not . isSpace) <|> Nothing <$ sym '*' <* some (psym $ not . isSpace) <|> Nothing <$ sym '(' <* few anySym <* sym ')' mk :: String -> [Maybe (Bool, String)] -> Maybe (PackageName, (Version, Map FlagName Bool)) mk ident fl = do PackageIdentifier name version <- parsePackageIdentifierFromString ident fl' <- (traverse . traverse) parseFlagNameFromString $ catMaybes fl return (name, (version, Map.fromList $ map swap fl')) lexeme r = some (psym isSpace) *> r getCabalConfig :: (MonadLogger m, MonadReader env m, HasConfig env, MonadIO m, MonadThrow m) => FilePath -- ^ temp dir -> ConstraintType -> Map PackageName Version -- ^ constraints -> m [Text] getCabalConfig dir constraintType constraints = do indices <- asks $ configPackageIndices . getConfig remotes <- mapM goIndex indices let cache = T.pack $ "remote-repo-cache: " ++ dir return $ cache : remotes ++ map goConstraint (Map.toList constraints) where goIndex index = do src <- configPackageIndex $ indexName index let dstdir = dir FP.</> T.unpack (indexNameText $ indexName index) dst = dstdir FP.</> "00-index.tar" liftIO $ void $ tryIO $ do D.createDirectoryIfMissing True dstdir D.copyFile (toFilePath src) dst return $ T.concat [ "remote-repo: " , indexNameText $ indexName index , ":http://0.0.0.0/fake-url" ] goConstraint (name, version) = assert (not . null . versionString $ version) $ T.concat [ (if constraintType == Constraint then "constraint: " else "preference: ") , T.pack $ packageNameString name , "==" , T.pack $ versionString version ] setupCompiler :: ( MonadBaseControl IO m, MonadIO m, MonadLogger m, MonadMask m , MonadReader env m, HasConfig env , HasGHCVariant env , HasHttpManager env , HasLogLevel env , HasReExec env , HasTerminal env) => CompilerVersion -> m (Maybe ExtraDirs) setupCompiler compiler = do let msg = Just $ T.concat [ "Compiler version (" <> compilerVersionText compiler <> ") " , "required by your resolver specification cannot be found.\n\n" , "Please use '--install-ghc' command line switch to automatically " , "install the compiler or '--system-ghc' to use a suitable " , "compiler available on your PATH." ] config <- asks getConfig mpaths <- ensureCompiler SetupOpts { soptsInstallIfMissing = configInstallGHC config , soptsUseSystem = configSystemGHC config , soptsWantedCompiler = compiler , soptsCompilerCheck = configCompilerCheck config , soptsStackYaml = Nothing , soptsForceReinstall = False , soptsSanityCheck = False , soptsSkipGhcCheck = False , soptsSkipMsys = configSkipMsys config , soptsUpgradeCabal = False , soptsResolveMissingGHC = msg , soptsStackSetupYaml = defaultStackSetupYaml , soptsGHCBindistURL = Nothing } return mpaths setupCabalEnv :: ( MonadBaseControl IO m, MonadIO m, MonadLogger m, MonadMask m , MonadReader env m, HasConfig env , HasGHCVariant env , HasHttpManager env , HasLogLevel env , HasReExec env , HasTerminal env) => CompilerVersion -> m EnvOverride setupCabalEnv compiler = do mpaths <- setupCompiler compiler menv0 <- getMinimalEnvOverride envMap <- removeHaskellEnvVars <$> augmentPathMap (maybe [] edBins mpaths) (unEnvOverride menv0) platform <- asks getPlatform menv <- mkEnvOverride platform envMap mcabal <- findExecutable menv "cabal" case mcabal of Nothing -> throwM SolverMissingCabalInstall Just _ -> return () mver <- getSystemCompiler menv (whichCompiler compiler) case mver of Just (version, _) -> $logInfo $ "Using compiler: " <> compilerVersionText version Nothing -> error "Failed to determine compiler version. \ \This is most likely a bug." return menv -- | Merge two separate maps, one defining constraints on package versions and -- the other defining package flagmap, into a single map of version and flagmap -- tuples. mergeConstraints :: Map PackageName v -> Map PackageName (Map p f) -> Map PackageName (v, Map p f) mergeConstraints = Map.mergeWithKey -- combine entry in both maps (\_ v f -> Just (v, f)) -- convert entry in first map only (fmap (flip (,) Map.empty)) -- convert entry in second map only (\m -> if Map.null m then Map.empty else error "Bug: An entry in flag map must have a corresponding \ \entry in the version map") -- | Given a resolver, user package constraints (versions and flags) and extra -- dependency constraints determine what extra dependencies are required -- outside the resolver snapshot and the specified extra dependencies. -- -- First it tries by using the snapshot and the input extra dependencies -- as hard constraints, if no solution is arrived at by using hard -- constraints it then tries using them as soft constraints or preferences. -- -- It returns either conflicting packages when no solution is arrived at -- or the solution in terms of src package flag settings and extra -- dependencies. solveResolverSpec :: ( MonadBaseControl IO m, MonadIO m, MonadLogger m, MonadMask m , MonadReader env m, HasConfig env , HasGHCVariant env , HasHttpManager env , HasLogLevel env , HasReExec env , HasTerminal env) => Path Abs File -- ^ stack.yaml file location -> [Path Abs Dir] -- ^ package dirs containing cabal files -> ( Resolver , ConstraintSpec , ConstraintSpec) -- ^ ( resolver -- , src package constraints -- , extra dependency constraints ) -> m (Either [PackageName] (ConstraintSpec , ConstraintSpec)) -- ^ (Conflicting packages -- (resulting src package specs, external dependency specs)) solveResolverSpec stackYaml cabalDirs (resolver, srcConstraints, extraConstraints) = do $logInfo $ "Using resolver: " <> resolverName resolver (compilerVer, snapConstraints) <- getResolverConstraints stackYaml resolver menv <- setupCabalEnv compilerVer let -- Note - The order in Map.union below is important. -- We want to override snapshot with extra deps depConstraints = Map.union extraConstraints snapConstraints -- Make sure to remove any user packages from the dep constraints -- There are two reasons for this: -- 1. We do not want snapshot versions to override the sources -- 2. Sources may have blank versions leading to bad cabal constraints depOnlyConstraints = Map.difference depConstraints srcConstraints solver t = cabalSolver menv cabalDirs t srcConstraints depOnlyConstraints $ ["-v"] -- TODO make it conditional on debug ++ ["--ghcjs" | (whichCompiler compilerVer) == Ghcjs] let srcNames = (T.intercalate " and ") $ ["packages from " <> resolverName resolver | not (Map.null snapConstraints)] ++ [T.pack ((show $ Map.size extraConstraints) <> " external packages") | not (Map.null extraConstraints)] $logInfo "Asking cabal to calculate a build plan..." unless (Map.null depOnlyConstraints) ($logInfo $ "Trying with " <> srcNames <> " as hard constraints...") eresult <- solver Constraint eresult' <- case eresult of Left _ | not (Map.null depOnlyConstraints) -> do $logInfo $ "Retrying with " <> srcNames <> " as preferences..." solver Preference _ -> return eresult case eresult' of Right deps -> do let -- All src package constraints returned by cabal. -- Flags may have changed. srcs = Map.intersection deps srcConstraints inSnap = Map.intersection deps snapConstraints -- All packages which are in the snapshot but cabal solver -- returned versions or flags different from the snapshot. inSnapChanged = Map.differenceWith diffConstraints inSnap snapConstraints -- Packages neither in snapshot, nor srcs extra = Map.difference deps (Map.union srcConstraints snapConstraints) external = Map.union inSnapChanged extra -- Just in case. -- If cabal output contains versions of user packages, those -- versions better be the same as those in our cabal file i.e. -- cabal should not be solving using versions from external -- indices. let outVers = fmap fst srcs inVers = fmap fst srcConstraints bothVers = Map.intersectionWith (\v1 v2 -> (v1, v2)) inVers outVers when (not $ outVers `Map.isSubmapOf` inVers) $ do let msg = "Error: user package versions returned by cabal \ \solver are not the same as the versions in the \ \cabal files:\n" -- TODO We can do better in formatting the message error $ T.unpack $ msg <> (showItems $ map show (Map.toList bothVers)) $logInfo $ "Successfully determined a build plan with " <> T.pack (show $ Map.size external) <> " external dependencies." return $ Right (srcs, external) Left x -> do $logInfo $ "*** Failed to arrive at a workable build plan." return $ Left x where -- Think of the first map as the deps reported in cabal output and -- the second as the snapshot packages -- Note: For flags we only require that the flags in cabal output be a -- subset of the snapshot flags. This is to avoid a false difference -- reporting due to any spurious flags in the build plan which will -- always be absent in the cabal output. diffConstraints :: (Eq v, Eq a, Ord k) => (v, Map k a) -> (v, Map k a) -> Maybe (v, Map k a) diffConstraints (v, f) (v', f') | (v == v') && (f `Map.isSubmapOf` f') = Nothing | otherwise = Just (v, f) -- | Given a resolver (snpashot, compiler or custom resolver) -- return the compiler version, package versions and packages flags -- for that resolver. getResolverConstraints :: ( MonadBaseControl IO m, MonadIO m, MonadLogger m, MonadMask m , MonadReader env m, HasConfig env , HasGHCVariant env , HasHttpManager env , HasLogLevel env , HasReExec env , HasTerminal env) => Path Abs File -> Resolver -> m (CompilerVersion, Map PackageName (Version, Map FlagName Bool)) getResolverConstraints stackYaml resolver = do (mbp, _loadedResolver) <- loadResolver (Just stackYaml) resolver return (mbpCompilerVersion mbp, mbpConstraints mbp) where mpiConstraints mpi = (mpiVersion mpi, mpiFlags mpi) mbpConstraints mbp = fmap mpiConstraints (mbpPackages mbp) -- | Given a bundle of user packages, flag constraints on those packages and a -- resolver, determine if the resolver fully, partially or fails to satisfy the -- dependencies of the user packages. -- -- If the package flags are passed as 'Nothing' then flags are chosen -- automatically. checkResolverSpec :: ( MonadIO m, MonadMask m, MonadLogger m, MonadReader env m , HasHttpManager env, HasConfig env, HasGHCVariant env , MonadBaseControl IO m) => [C.GenericPackageDescription] -> Maybe (Map PackageName (Map FlagName Bool)) -> Resolver -> m BuildPlanCheck checkResolverSpec gpds flags resolver = do case resolver of ResolverSnapshot name -> checkSnapBuildPlan gpds flags name ResolverCompiler {} -> return $ BuildPlanCheckPartial Map.empty Map.empty -- TODO support custom resolver for stack init ResolverCustom {} -> return $ BuildPlanCheckPartial Map.empty Map.empty -- | Finds all files with a .cabal extension under a given directory. If -- a `hpack` `package.yaml` file exists, this will be used to generate a cabal -- file. -- Subdirectories can be included depending on the @recurse@ parameter. findCabalFiles :: MonadIO m => Bool -> Path Abs Dir -> m [Path Abs File] findCabalFiles recurse dir = liftIO $ do findFiles dir isHpack subdirFilter >>= mapM_ (hpack . parent) findFiles dir isCabal subdirFilter where subdirFilter subdir = recurse && not (isIgnored subdir) isHpack = (== "package.yaml") . toFilePath . filename isCabal = (".cabal" `isSuffixOf`) . toFilePath isIgnored path = "." `isPrefixOf` dirName || dirName `Set.member` ignoredDirs where dirName = FP.dropTrailingPathSeparator (toFilePath (dirname path)) -- | Special directories that we don't want to traverse for .cabal files ignoredDirs :: Set FilePath ignoredDirs = Set.fromList [ "dist" ] -- | Perform some basic checks on a list of cabal files to be used for creating -- stack config. It checks for duplicate package names, package name and -- cabal file name mismatch and reports any issues related to those. -- -- If no error occurs it returns filepath and @GenericPackageDescription@s -- pairs as well as any filenames for duplicate packages not included in the -- pairs. cabalPackagesCheck :: ( MonadBaseControl IO m, MonadIO m, MonadLogger m, MonadMask m , MonadReader env m, HasConfig env , HasGHCVariant env , HasHttpManager env , HasLogLevel env , HasReExec env , HasTerminal env) => [Path Abs File] -> String -> Maybe String -> m ( Map PackageName (Path Abs File, C.GenericPackageDescription) , [Path Abs File]) cabalPackagesCheck cabalfps noPkgMsg dupErrMsg = do when (null cabalfps) $ error noPkgMsg relpaths <- mapM prettyPath cabalfps $logInfo $ "Using cabal packages:" $logInfo $ T.pack (formatGroup relpaths) (warnings, gpds) <- fmap unzip (mapM readPackageUnresolved cabalfps) zipWithM_ (mapM_ . printCabalFileWarning) cabalfps warnings -- package name cannot be empty or missing otherwise -- it will result in cabal solver failure. -- stack requires packages name to match the cabal file name -- Just the latter check is enough to cover both the cases let packages = zip cabalfps gpds getNameMismatchPkg (fp, gpd) | (show . gpdPackageName) gpd /= (FP.takeBaseName . toFilePath) fp = Just fp | otherwise = Nothing nameMismatchPkgs = mapMaybe getNameMismatchPkg packages when (nameMismatchPkgs /= []) $ do rels <- mapM prettyPath nameMismatchPkgs error $ "Package name as defined in the .cabal file must match the \ \.cabal file name.\n\ \Please fix the following packages and try again:\n" <> (formatGroup rels) let dupGroups = filter ((> 1) . length) . groupSortOn (gpdPackageName . snd) dupAll = concat $ dupGroups packages -- Among duplicates prefer to include the ones in upper level dirs pathlen = length . FP.splitPath . toFilePath . fst getmin = minimumBy (compare `on` pathlen) dupSelected = map getmin (dupGroups packages) dupIgnored = dupAll \\ dupSelected unique = packages \\ dupIgnored when (dupIgnored /= []) $ do dups <- mapM (mapM (prettyPath. fst)) (dupGroups packages) $logWarn $ T.pack $ "Following packages have duplicate package names:\n" <> intercalate "\n" (map formatGroup dups) case dupErrMsg of Nothing -> $logWarn $ T.pack $ "Packages with duplicate names will be ignored.\n" <> "Packages in upper level directories will be preferred.\n" Just msg -> error msg return (Map.fromList $ map (\(file, gpd) -> (gpdPackageName gpd,(file, gpd))) unique , map fst dupIgnored) formatGroup :: [String] -> String formatGroup = concatMap (\path -> "- " <> path <> "\n") reportMissingCabalFiles :: (MonadIO m, MonadThrow m, MonadLogger m) => [Path Abs File] -- ^ Directories to scan -> Bool -- ^ Whether to scan sub-directories -> m () reportMissingCabalFiles cabalfps includeSubdirs = do allCabalfps <- findCabalFiles includeSubdirs =<< getCurrentDir relpaths <- mapM prettyPath (allCabalfps \\ cabalfps) unless (null relpaths) $ do $logWarn $ "The following packages are missing from the config:" $logWarn $ T.pack (formatGroup relpaths) -- TODO Currently solver uses a stack.yaml in the parent chain when there is -- no stack.yaml in the current directory. It should instead look for a -- stack yaml only in the current directory and suggest init if there is -- none available. That will make the behavior consistent with init and provide -- a correct meaning to a --ignore-subdirs option if implemented. -- | Verify the combination of resolver, package flags and extra -- dependencies in an existing stack.yaml and suggest changes in flags or -- extra dependencies so that the specified packages can be compiled. solveExtraDeps :: ( MonadBaseControl IO m, MonadIO m, MonadLogger m, MonadMask m , MonadReader env m, HasConfig env , HasEnvConfig env, HasGHCVariant env , HasHttpManager env , HasLogLevel env , HasReExec env , HasTerminal env) => Bool -- ^ modify stack.yaml? -> m () solveExtraDeps modStackYaml = do econfig <- asks getEnvConfig bconfig <- asks getBuildConfig let stackYaml = bcStackYaml bconfig relStackYaml <- toFilePath <$> makeRelativeToCurrentDir stackYaml $logInfo $ "Using configuration file: " <> T.pack relStackYaml let cabalDirs = Map.keys $ envConfigPackages econfig noPkgMsg = "No cabal packages found in " <> relStackYaml <> ". Please add at least one directory containing a .cabal \ \file. You can also use 'stack init' to automatically \ \generate the config file." dupPkgFooter = "Please remove the directories containing duplicate \ \entries from '" <> relStackYaml <> "'." cabalfps <- liftM concat (mapM (findCabalFiles False) cabalDirs) -- TODO when solver supports --ignore-subdirs option pass that as the -- second argument here. reportMissingCabalFiles cabalfps True (bundle, _) <- cabalPackagesCheck cabalfps noPkgMsg (Just dupPkgFooter) let gpds = Map.elems $ fmap snd bundle oldFlags = unPackageFlags (bcFlags bconfig) oldExtraVersions = bcExtraDeps bconfig resolver = bcResolver bconfig oldSrcs = gpdPackages gpds oldSrcFlags = Map.intersection oldFlags oldSrcs oldExtraFlags = Map.intersection oldFlags oldExtraVersions srcConstraints = mergeConstraints oldSrcs oldSrcFlags extraConstraints = mergeConstraints oldExtraVersions oldExtraFlags let resolver' = toResolverNotLoaded resolver resolverResult <- checkResolverSpec gpds (Just oldSrcFlags) resolver' resultSpecs <- case resolverResult of BuildPlanCheckOk flags -> return $ Just ((mergeConstraints oldSrcs flags), Map.empty) BuildPlanCheckPartial {} -> do eres <- solveResolverSpec stackYaml cabalDirs (resolver', srcConstraints, extraConstraints) -- TODO Solver should also use the init code to ignore incompatible -- packages return $ either (const Nothing) Just eres BuildPlanCheckFail {} -> throwM $ ResolverMismatch resolver (show resolverResult) (srcs, edeps) <- case resultSpecs of Nothing -> throwM (SolverGiveUp giveUpMsg) Just x -> return x let flags = removeSrcPkgDefaultFlags gpds (fmap snd (Map.union srcs edeps)) versions = fmap fst edeps vDiff v v' = if v == v' then Nothing else Just v versionsDiff = Map.differenceWith vDiff newVersions = versionsDiff versions oldExtraVersions goneVersions = versionsDiff oldExtraVersions versions fDiff f f' = if f == f' then Nothing else Just f flagsDiff = Map.differenceWith fDiff newFlags = flagsDiff flags oldFlags goneFlags = flagsDiff oldFlags flags changed = any (not . Map.null) [newVersions, goneVersions] || any (not . Map.null) [newFlags, goneFlags] if changed then do $logInfo "" $logInfo $ "The following changes will be made to " <> T.pack relStackYaml <> ":" -- TODO print whether resolver changed from previous $logInfo $ "* Resolver is " <> resolverName resolver printFlags newFlags "* Flags to be added" printDeps newVersions "* Dependencies to be added" printFlags goneFlags "* Flags to be deleted" printDeps goneVersions "* Dependencies to be deleted" -- TODO backup the old config file if modStackYaml then do writeStackYaml stackYaml resolver versions flags $logInfo $ "Updated " <> T.pack relStackYaml else do $logInfo $ "To automatically update " <> T.pack relStackYaml <> ", rerun with '--update-config'" else $logInfo $ "No changes needed to " <> T.pack relStackYaml where indent t = T.unlines $ fmap (" " <>) (T.lines t) printFlags fl msg = do when ((not . Map.null) fl) $ do $logInfo $ T.pack msg $logInfo $ indent $ decodeUtf8 $ Yaml.encode $ object ["flags" .= fl] printDeps deps msg = do when ((not . Map.null) deps) $ do $logInfo $ T.pack msg $logInfo $ indent $ decodeUtf8 $ Yaml.encode $ object $ [("extra-deps" .= map fromTuple (Map.toList deps))] writeStackYaml path res deps fl = do let fp = toFilePath path obj <- liftIO (Yaml.decodeFileEither fp) >>= either throwM return WithJSONWarnings (ProjectAndConfigMonoid _ _) warnings <- liftIO (Yaml.decodeFileEither fp) >>= either throwM return logJSONWarnings fp warnings let obj' = HashMap.insert "extra-deps" (toJSON $ map fromTuple $ Map.toList deps) $ HashMap.insert ("flags" :: Text) (toJSON fl) $ HashMap.insert ("resolver" :: Text) (toJSON (resolverName res)) obj liftIO $ Yaml.encodeFile fp obj' giveUpMsg = concat [ " - Update external packages with 'stack update' and try again.\n" , " - Tweak " <> toFilePath stackDotYaml <> " and try again\n" , " - Remove any unnecessary packages.\n" , " - Add any missing remote packages.\n" , " - Add extra dependencies to guide solver.\n" ] prettyPath :: forall r t m. (MonadIO m, RelPath (Path r t) ~ Path Rel t, AnyPath (Path r t)) => Path r t -> m String prettyPath path = do eres <- liftIO $ try $ makeRelativeToCurrentDir path return $ case eres of Left (_ :: PathParseException) -> toFilePath path Right res -> toFilePath (res :: Path Rel t)
phadej/stack
src/Stack/Solver.hs
bsd-3-clause
33,609
486
29
10,547
6,541
3,549
2,992
551
8
{-# LANGUAGE Arrows #-} module NPNTool.XMLReader where import Control.Arrow import Text.XML.HXT.Core import NPNTool.PetriNet import NPNTool.NPNet import NPNTool.NPNConstr import NPNTool.PTConstr (PTConstrM) import qualified NPNTool.PTConstr as PTC import Control.Monad import qualified Data.IntMap as IM type Label = Int type Variable = String idToPlace :: String -> PTPlace idToPlace = read . tail idToTrans :: String -> Trans idToTrans = Trans . tail idToElemNet :: String -> ElemNetId idToElemNet = ElemNetId . read . tail getPlace :: IOSArrow XmlTree (PTConstrM Label ()) getPlace = hasName "places" >>> getAttrValue "id" >>> arr (PTC.insPlace . read) getTrans :: IOSArrow XmlTree (PTConstrM Label ()) getTrans = hasName "transitions" >>> hasAttr "synchronization" >>> listA (proc t -> do sync <- getAttrValue "synchronization" -< t tid <- getAttrValue "id" -< t returnA -< PTC.label (Trans tid) (read (tail sync))) >>> arr sequence_ getInscr :: ArrowXml a => a XmlTree (Expr Variable Int) getInscr = hasName "inscription" >>> proc inscr -> do ms <- hasName "monoms" <<< getChildren -< inscr var <- getAttrValue "variable" -< ms -- power <- arr read <<< getAttrValue "power" -< ms -- returnA -< exprMult (Var var) power returnA -< Var var getArcPT :: IOSArrow XmlTree (NPNConstrM Label Variable ()) getArcPT = hasName "arcsPT" >>> (proc a -> do p <- getAttrValue "inPlace" -< a t <- getAttrValue "outTransition" -< a inscr <- getInscr <<< hasName "inscription" <<< getChildren -< a returnA -< inT (idToPlace p) inscr (idToTrans t)) >. sequence_ getArcPTPTC :: IOSArrow XmlTree (PTConstrM Label ()) getArcPTPTC = hasName "arcsPT" >>> (proc a -> do p <- getAttrValue "inPlace" -< a t <- getAttrValue "outTransition" -< a returnA -< PTC.inT (idToPlace p) (idToTrans t)) >. sequence_ getArcTP :: ArrowXml a => a XmlTree (NPNConstrM Label Variable ()) getArcTP = hasName "arcsTP" >>> (proc a -> do t <- getAttrValue "inTransition" -< a p <- getAttrValue "outPlace" -< a inscr <- getInscr <<< hasName "inscription" <<< getChildren -< a returnA -< outT (idToTrans t) inscr (idToPlace p)) >. sequence_ getArcTPPTC :: IOSArrow XmlTree (PTConstrM Label ()) getArcTPPTC = hasName "arcsTP" >>> (proc a -> do t <- getAttrValue "inTransition" -< a p <- getAttrValue "outPlace" -< a returnA -< PTC.outT (idToTrans t) (idToPlace p)) >. sequence_ sysNet :: IOSArrow XmlTree (NPNConstrM Label Variable ()) sysNet = hasName "netSystem" >>> listA (getChildren >>> getPlaceNPN <+> getTransNPN <+> getArcPT <+> getArcTP) >>> arr sequence_ where getPlaceNPN = arr liftPTC <<< getPlace getTransNPN = arr liftPTC <<< getTrans sysNetMarking :: IOSArrow XmlTree (NPNConstrM Label Variable ()) sysNetMarking = getChildren >>> hasName "marking" >>> (getChildren >>> hasName "map" >>> proc m -> do pl <- getAttrValue "place" -< m marking <- getChildren <<< hasName "marking" <<< getChildren -< m t <- getAttrValue "token" <<< hasName "weight" -< marking w <- getAttrValue "weight" <<< hasName "weight" -< marking returnA -< replicateM_ (read w) (mark (idToPlace pl) (Right (idToElemNet t)))) >. sequence_ elemMarking :: IOSArrow XmlTree (PTConstrM Label ()) elemMarking = hasName "marking" >>> (getChildren >>> hasName "map" >>> proc m -> do place <- getAttrValue "place" -< m weight <- getAttrValue "weight" <<< deep (hasName "weight") -< m -- traceValue 1 show -< weight returnA -< replicateM_ (read weight) (PTC.mark (idToPlace place))) >. sequence_ elemToken :: IOSArrow XmlTree Int elemToken = arr read <<< -- traceValue 1 id <<< getAttrValue "id" <<< hasName "tokenNets" elemNetPTC :: IOSArrow XmlTree (PTConstrM Label ()) elemNetPTC = hasName "net" >>> listA (getChildren >>> getPlace <+> getTrans <+> getArcPTPTC <+> getArcTPPTC) >>> arr sequence_ elemNet :: IOSArrow XmlTree (NPNConstrM Label Variable ()) elemNet = hasName "typeElementNet" >>> proc en -> do enPTC <- getChildren >>> elemNetPTC -< en enMark <- getChildren >>> deep elemMarking -< en t <- getChildren >>> elemToken -< en returnA -< insElemNet t (enPTC >> enMark) getNetConstr :: FilePath -> IO [NPNConstrM Label Variable ()] getNetConstr doc = runX $ configSysVars [withTrace 1] >>> readDocument [] doc -- >>> listA (deep elemNet) -- >>> arr sequence_ >>> (deep elemNet <+> deep sysNet <+> deep sysNetMarking) runConstr :: FilePath -> IO (NPNet Label Variable Int) runConstr doc = do constr <- getNetConstr doc let (_,sn) = run (sequence constr) new return sn
co-dan/NPNTool
src/NPNTool/XMLReader.hs
bsd-3-clause
5,464
9
17
1,737
1,610
780
830
122
1
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.ARB.ProgramInterfaceQuery -- Copyright : (c) Sven Panne 2015 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -- The <https://www.opengl.org/registry/specs/ARB/program_interface_query.txt ARB_program_interface_query> extension. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.ARB.ProgramInterfaceQuery ( -- * Enums gl_ACTIVE_RESOURCES, gl_ACTIVE_VARIABLES, gl_ARRAY_SIZE, gl_ARRAY_STRIDE, gl_ATOMIC_COUNTER_BUFFER, gl_ATOMIC_COUNTER_BUFFER_INDEX, gl_BLOCK_INDEX, gl_BUFFER_BINDING, gl_BUFFER_DATA_SIZE, gl_BUFFER_VARIABLE, gl_COMPATIBLE_SUBROUTINES, gl_COMPUTE_SUBROUTINE, gl_COMPUTE_SUBROUTINE_UNIFORM, gl_FRAGMENT_SUBROUTINE, gl_FRAGMENT_SUBROUTINE_UNIFORM, gl_GEOMETRY_SUBROUTINE, gl_GEOMETRY_SUBROUTINE_UNIFORM, gl_IS_PER_PATCH, gl_IS_ROW_MAJOR, gl_LOCATION, gl_LOCATION_INDEX, gl_MATRIX_STRIDE, gl_MAX_NAME_LENGTH, gl_MAX_NUM_ACTIVE_VARIABLES, gl_MAX_NUM_COMPATIBLE_SUBROUTINES, gl_NAME_LENGTH, gl_NUM_ACTIVE_VARIABLES, gl_NUM_COMPATIBLE_SUBROUTINES, gl_OFFSET, gl_PROGRAM_INPUT, gl_PROGRAM_OUTPUT, gl_REFERENCED_BY_COMPUTE_SHADER, gl_REFERENCED_BY_FRAGMENT_SHADER, gl_REFERENCED_BY_GEOMETRY_SHADER, gl_REFERENCED_BY_TESS_CONTROL_SHADER, gl_REFERENCED_BY_TESS_EVALUATION_SHADER, gl_REFERENCED_BY_VERTEX_SHADER, gl_SHADER_STORAGE_BLOCK, gl_TESS_CONTROL_SUBROUTINE, gl_TESS_CONTROL_SUBROUTINE_UNIFORM, gl_TESS_EVALUATION_SUBROUTINE, gl_TESS_EVALUATION_SUBROUTINE_UNIFORM, gl_TOP_LEVEL_ARRAY_SIZE, gl_TOP_LEVEL_ARRAY_STRIDE, gl_TRANSFORM_FEEDBACK_VARYING, gl_TYPE, gl_UNIFORM, gl_UNIFORM_BLOCK, gl_VERTEX_SUBROUTINE, gl_VERTEX_SUBROUTINE_UNIFORM, -- * Functions glGetProgramInterfaceiv, glGetProgramResourceIndex, glGetProgramResourceLocation, glGetProgramResourceLocationIndex, glGetProgramResourceName, glGetProgramResourceiv ) where import Graphics.Rendering.OpenGL.Raw.Tokens import Graphics.Rendering.OpenGL.Raw.Functions
phaazon/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/ARB/ProgramInterfaceQuery.hs
bsd-3-clause
2,240
0
4
250
211
148
63
59
0
{-# LANGUAGE DeriveDataTypeable #-} module Types where import Data.Typeable import Data.Time data Paste = Paste { paste_id :: Int , paste_timestamp :: !(Maybe UTCTime) , paste_content :: String , paste_title :: String , paste_author :: String -- ..md5 sum of email address.. , paste_hostname :: Maybe String , paste_ipaddress :: String , paste_expireon :: Maybe Int , paste_language :: String , paste_channel :: String , paste_parentid :: Maybe Int } deriving (Typeable, Show) data User = User { user_id :: Int , user_name :: String , user_password :: String , user_ircmask :: Maybe String , user_admin :: Bool } deriving (Typeable, Show) type SessionId = Int
glguy/hpaste
src/Types.hs
bsd-3-clause
827
0
11
273
177
108
69
27
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE TemplateHaskell #-} module Numeric.QuaterFloatTest (runTests) where import Numeric.Arbitraries import Numeric.Basics import Numeric.Quaternion import Numeric.Vector import Test.QuickCheck type T = Float -- | Some non-linear function are very unstable; -- it would be a downting task to determine the uncertainty precisely. -- Instead, I just make sure the tolerance is small enough to find at least -- the most obvious bugs. -- This function increases the tolerance by the span of magnitudes in q. qSpan :: Quater T -> T qSpan (Quater a b c d) = asSpan . foldl mm (1,1) $ map (\x -> x*x) [a, b, c, d] where mm :: (T,T) -> T -> (T,T) mm (mi, ma) x | x > M_EPS = (min mi x, max ma x) | otherwise = (mi, ma) asSpan :: (T,T) -> T asSpan (mi, ma) = ma / mi prop_Eq :: Quater T -> Bool prop_Eq q = and [ q == q , Quater (takei q) (takej q) (takek q) (taker q) == q , fromVecNum (imVec q) (taker q) == q , im q + re q == q , fromVec4 (toVec4 q) == q ] prop_DoubleConjugate :: Quater T -> Property prop_DoubleConjugate q = property $ conjugate (conjugate q) == q prop_Square :: Quater T -> Property prop_Square q = q * conjugate q =~= realToFrac (square q) prop_RotScale :: Quater T -> Vector T 3 -> Property prop_RotScale q v = fromVecNum (rotScale q v) 0 =~= q * fromVecNum v 0 * conjugate q prop_GetRotScale :: Vector T 3 -> Vector T 3 -> Property prop_GetRotScale a b = normL2 a * ab > M_EPS * normL2 b ==> approxEq (recip ab) b (rotScale q a) where q = getRotScale a b -- when a and b are almost opposite, precision of getRotScale suffers a lot -- compensate it by increasing tolerance: ab = min 1 $ 1 + normalized a `dot` normalized b prop_InverseRotScale :: Quater T -> Vector T 3 -> Property prop_InverseRotScale q v = min (recip s) s > M_EPS ==> v =~= rotScale (1/q) (rotScale q v) where s = square q prop_NegateToMatrix33 :: Quater T -> Bool prop_NegateToMatrix33 q = toMatrix33 q == toMatrix33 (negate q) prop_NegateToMatrix44 :: Quater T -> Bool prop_NegateToMatrix44 q = toMatrix44 q == toMatrix44 (negate q) prop_FromToMatrix33 :: Quater T -> Property prop_FromToMatrix33 q = q /= 0 ==> fromMatrix33 (toMatrix33 q) =~= q .||. fromMatrix33 (toMatrix33 q) =~= negate q prop_FromToMatrix44 :: Quater T -> Property prop_FromToMatrix44 q = q /= 0 ==> fromMatrix44 (toMatrix44 q) =~= q .||. fromMatrix44 (toMatrix44 q) =~= negate q prop_RotationArg :: Quater T -> Property prop_RotationArg q | q == 0 = axisRotation (imVec q) (qArg q) =~= 1 | otherwise = axisRotation (imVec q) (qArg q) =~= signum q prop_UnitQ :: Quater T -> Property prop_UnitQ q = square q > M_EPS ==> square (q / q) =~= 1 prop_ExpLog :: Quater T -> Property prop_ExpLog q | square q < M_EPS = approxEq (qSpan q) q $ log (exp q) | otherwise = approxEq (qSpan q) q $ exp (log q) prop_SinAsin :: Quater T -> Property prop_SinAsin q = approxEq (qSpan q `max` qSpan q') q $ sin q' where q' = asin q prop_CosAcos :: Quater T -> Property prop_CosAcos q = approxEq (qSpan q `max` qSpan q') q $ cos q' where q' = acos q prop_TanAtan :: Quater T -> Property prop_TanAtan q = approxEq (qSpan q `max` qSpan q') q $ tan q' where q' = atan q prop_SinhAsinh :: Quater T -> Property prop_SinhAsinh q = approxEq (qSpan q `max` qSpan q') q $ sinh q' where q' = asinh q prop_CoshAcosh :: Quater T -> Property prop_CoshAcosh q = approxEq (qSpan q `max` qSpan q') q $ cosh q' where q' = acosh q prop_TanhAtanh :: Quater T -> Property prop_TanhAtanh q = approxEq (qSpan q `max` qSpan q') q $ tanh q' where q' = atanh q prop_SqrtSqr :: Quater T -> Property prop_SqrtSqr q = approxEq (qSpan q) q $ sqrt q * sqrt q prop_SinCos :: Quater T -> Property prop_SinCos q' = approxEq (qSpan s `max` qSpan c) 1 $ c * c + s * s where q = signum q' -- avoid exploding exponents s = sin q c = cos q prop_SinhCosh :: Quater T -> Property prop_SinhCosh q' = approxEq (qSpan s `max` qSpan c) 1 $ c * c - s * s where q = signum q' -- avoid exploding exponents s = sinh q c = cosh q prop_ReadShow :: Quater T -> Bool prop_ReadShow q = q == read (show q) return [] runTests :: Int -> IO Bool runTests n = $forAllProperties $ quickCheckWithResult stdArgs { maxSuccess = n }
achirkin/easytensor
easytensor/test/Numeric/QuaterFloatTest.hs
bsd-3-clause
4,487
0
12
1,148
1,759
873
886
97
1
{-# LANGUAGE OverloadedStrings #-} {-# LAnGUAGE ExtendedDefaultRules #-} module Lucid.Foundation.Navigation.TopBar where import Lucid.Base import Lucid.Html5 import qualified Data.Text as T import Data.Monoid fixed_ :: Term arg result => arg -> result fixed_ = termWith "div" [class_ "fixed"] contain_to_grid_ :: Term arg result => arg -> result contain_to_grid_ = termWith "div" [class_ "contain-to-grid"] data_topbar_ :: Attribute data_topbar_ = data_ "topbar" "" top_bar_ :: T.Text top_bar_ = " top-bar " sticky_ :: T.Text sticky_ = " sticky " sticky_on_ :: T.Text -> Attribute sticky_on_ size = data_ "options" ("sticky_on: " <> size) clickable_ :: Attribute clickable_ = data_ "options" "is_hover: false" divider_ :: Monad m => HtmlT m () divider_ = li_ [class_ "divider"] mempty title_area_ :: Term arg result => arg -> result title_area_ = termWith "ul" [class_ "title-area"]
athanclark/lucid-foundation
src/Lucid/Foundation/Navigation/TopBar.hs
bsd-3-clause
911
0
7
156
255
137
118
31
1
module Homoiconic.Constrained.TH where import Prelude import Control.Monad import Data.Foldable import Data.List import Data.Maybe import Data.Typeable import Data.Proxy import Data.Kind import GHC.Exts hiding (IsList(..)) import Homoiconic.Common.TH import Language.Haskell.TH hiding (Type) import qualified Language.Haskell.TH as TH import Debug.Trace import Unsafe.Coerce -------------------------------------------------------------------------------- -- | Generates an instance of the form -- -- > atName (Free (Sig alg) t a) = Free (Sig alg) (tagName : t) a tagFreeInstance :: Name -> Dec tagFreeInstance atName = TySynInstD atName ( TySynEqn [ AppT ( AppT ( AppT ( ConT $ mkName "Free" ) ( AppT ( ConT $ mkName "Sig" ) ( VarT $ mkName "alg" ) ) ) ( VarT $ mkName "t" ) ) ( VarT $ mkName "a" ) ] ( AppT ( AppT ( AppT ( ConT $ mkName "Free" ) ( AppT ( ConT $ mkName "Sig" ) ( VarT $ mkName "alg" ) ) ) ( AppT ( AppT ( ConT $ mkName "ConsTag" ) ( ConT $ mkName $ "T"++renameClassMethod atName ) ) ( VarT $ mkName "t" ) ) ) ( VarT $ mkName "a" ) ) ) -- | Constructs the needed declarations for a type family assuming no constraints on the type family mkTag :: Name -> Q [Dec] mkTag atName = do ret <- mkTagFromCxt atName [] return $ tagFreeInstance atName:ret -- | This functions is designed to be called on non-associated type families only. -- The second argument lists the constraints that the family must obey. -- For example: -- -- > mkTagFromCnst ''Scalar [t| forall a. Scalar (Scalar a) ~ Scalar a |] mkTagFromCnst :: Name -> Q Pred -> Q [Dec] mkTagFromCnst atName qpred = do pred <- qpred ret <- case pred of ForallT _ _ t -> mkTagFromCnst atName $ return t (AppT (AppT EqualityT t1) t2) -> mkTagFromCnst atName $ return (AppT (AppT (ConT (mkName "Data.Type.Equality.~")) t1) t2) t -> mkTagFromCxt atName [t] return $ tagFreeInstance atName:ret -- | Constructs the declarations for a type family that is constrainted by some context. -- Currently, the only supported constraints are idempocency constraints. mkTagFromCxt :: Name -> Cxt -> Q [Dec] mkTagFromCxt atName cxt = do -- validate input qinfo <- reify atName case qinfo of FamilyI (OpenTypeFamilyD (TypeFamilyHead _ [_] _ _)) _ -> return () _ -> error $ "mkAt called on " ++show atName ++", which is not an open type family of kind `Type -> Type`" -- common names let tagName = mkName $ "T"++renameClassMethod atName -------------------- -- all tags need these declarations -- construct the data Tag let decT = DataD [] tagName [] Nothing [NormalC tagName []] [] -- construct the AppTags instance let instApp = TySynInstD ( mkName "AppTag" ) ( TySynEqn [ ConT tagName, VarT $ mkName "a" ] ( AppT ( ConT atName ) ( VarT $ mkName "a" ) ) ) -- generate an overlappable MkFree instance that always behave like Free1 let instMkFreeOverlap = InstanceD ( Just Overlappable ) [ AppT ( AppT ( ConT $ mkName "FreeConstraints" ) ( VarT $ mkName "t" ) ) ( VarT $ mkName "a" ) , AppT ( AppT EqualityT ( AppT ( AppT ( ConT $ mkName "ConsTag" ) ( ConT $ tagName ) ) ( VarT $ mkName "t" ) ) ) ( AppT ( AppT PromotedConsT ( ConT $ tagName ) ) ( VarT $ mkName "t" ) ) ] ( AppT ( AppT ( AppT ( ConT $ mkName "MkFree" ) ( ConT $ tagName ) ) ( VarT $ mkName "t" ) ) ( VarT $ mkName "a" ) ) [ FunD ( mkName "mkFree" ) [ Clause [ VarP $ mkName "p" ] ( NormalB $ ConE $ mkName "Free1" ) [] ] ] -------------------- -- these declarations depend on the tag's cxt cxt' <- subTypeFamilies cxt cnsts <- return $ case filter isEqualityCnst cxt' of -- there's no constraints [] -> -- ConsTag is the same as PromotedConsT [ TySynInstD ( mkName "ConsTag" ) ( TySynEqn [ ConT tagName , VarT $ mkName "ts" ] ( AppT ( AppT PromotedConsT ( ConT tagName ) ) ( VarT $ mkName "ts" ) ) ) ] -- there's exactly one idempotency constraint -- FIXME: -- the check that the constraint is an idempotency is not restrictive enough cnst@[(AppT (AppT _ t1) t2)] -> if maxDepth/=minDepth+1 then error $ "mkTagFromCxt constraint too complex: "++show cnst else -- ConsTag needs to call out to the ConsTag_algName closed family [ TySynInstD ( mkName "ConsTag" ) ( TySynEqn [ ConT tagName , VarT $ mkName "ts" ] ( AppT ( ConT $ mkName $ "ConsTag_"++renameClassMethod tagName ) ( VarT $ mkName "ts" ) ) ) -- create the ConsTag_algName closed family , ClosedTypeFamilyD ( TypeFamilyHead ( mkName $ "ConsTag_"++renameClassMethod tagName ) [ PlainTV $ mkName "ts" ] NoSig Nothing ) [ let t = foldl' ( \b _ -> AppT ( AppT PromotedConsT ( ConT tagName ) ) b ) ( VarT $ mkName "ts" ) ( replicate minDepth () ) in TySynEqn [t] (t) , TySynEqn [ VarT $ mkName "ts" ] ( AppT ( AppT PromotedConsT ( ConT tagName ) ) ( VarT $ mkName "ts" ) ) ] ] ++ -- create MkFree instances [ let tagsType = ( foldl' ( \b _ -> AppT ( AppT PromotedConsT ( ConT tagName ) ) b ) ( if i==minDepth then VarT $ mkName "t" else PromotedNilT ) ( replicate i () ) ) in InstanceD Nothing [ AppT ( AppT ( ConT $ mkName "FreeConstraints" ) tagsType ) ( VarT $ mkName "a" ) ] ( AppT ( AppT ( AppT ( ConT $ mkName "MkFree" ) ( ConT $ tagName ) ) tagsType ) ( VarT $ mkName "a" ) ) [ FunD ( mkName "mkFree" ) [ Clause [ VarP $ mkName "p" ] ( NormalB $ ConE $ if i==minDepth then mkName "Free0" else mkName "Free1" ) [] ] ] | i <- [0..minDepth] ] where maxDepth = max (depthSameAppT t1) (depthSameAppT t2) minDepth = min (depthSameAppT t1) (depthSameAppT t2) return $ cnsts ++ [instMkFreeOverlap, decT, instApp] -- | Generates the FAlgebra instance for the specified name and all of its dependencies recursively mkFAlgebra :: Name -> Q [Dec] mkFAlgebra algName = do -- validate input and extract the class functions qinfo <- reify algName (cxt,rawdecs) <- case qinfo of ClassI (ClassD cxt _ [_] _ decs) _ -> return (cxt,decs) _ -> error $ "mkFAlgebra called on " ++show algName ++", which is not a class of kind `Type -> Constraint`" -- common variables we'll need later allcxt <- superPredicates $ AppT (ConT algName) (VarT $ mkName "t") -- For all the superclasses without FAlgebras, generate them prereqs <- fmap (nub . concat) $ sequence [ do qinfo <- reify (mkName "FAlgebra") case qinfo of (ClassI _ insts) -> do if (ConT predClass) `elem` map (\(InstanceD _ _ (AppT _ t) _) -> t) insts then return [] else mkFAlgebraNoRec predClass | PredInfo (AppT (ConT predClass) _) _ _ <- allcxt ] return prereqs -- | Generates the FAlgebra instance for the specified name without recusively generating dependencies mkFAlgebraNoRec :: Name -> Q [Dec] mkFAlgebraNoRec algName = do -- validate input and extract the class functions qinfo <- reify algName (rawcxt,rawdecs) <- case qinfo of ClassI (ClassD cxt _ [_] _ decs) _ -> return (cxt,decs) _ -> error $ "mkFAlgebraNoRec called on " ++show algName ++", which is not a class of kind `Type -> Constraint`" -- remove functions from decsraw that we can't handle let decs = filter isHeterogeneousFunction rawdecs cxt <- subTypeFamilies rawcxt -- common variables we'll need later let varName = mkName "a" tagName = mkName "t" thisPred = AppT (ConT algName) (VarT tagName) allcxt <- superPredicates thisPred -- construct associated types -- FIXME: -- Should this construct non-associated types that happen to be used as well? -- If so, should we prevent duplicate instances from being created? ats <- fmap concat $ sequence [ mkTagFromCxt atName cxt | OpenTypeFamilyD (TypeFamilyHead atName _ _ _) <- decs ] -- create a constructor for each member function let consFunc = nub $ [ GadtC [ mkName $ "Sig_" ++ renameClassMethod sigName ] ( map ( Bang NoSourceUnpackedness NoSourceStrictness,) ( getArgs $ subForall varName sigType) ) ( AppT ( AppT ( AppT ( ConT $ mkName "Sig" ) ( ConT $ algName ) ) ( pred2tag PromotedNilT $ getReturnType $ subForall varName sigType ) ) ( VarT varName ) ) | SigD sigName sigType <- decs ] -- create a constructor for each predicate class to hold their signatures let consPred = nub $ [ GadtC [ mkName $ "Sig_"++renameClassMethod algName ++"_"++renameClassMethod predClass ++"_"++predType2str predType ] [ ( Bang NoSourceUnpackedness SourceStrict , AppT ( AppT ( AppT ( ConT $ mkName "Sig" ) ( ConT predClass ) ) ( VarT tagName ) ) ( VarT varName ) ) ] ( AppT ( AppT ( AppT ( ConT $ mkName "Sig" ) ( ConT $ algName ) ) ( case predType of (VarT _) -> VarT tagName _ -> AppT ( AppT ( ConT $ mkName "Snoc" ) ( VarT tagName ) ) ( pred2tagSingleton predType ) ) ) ( VarT varName ) ) | AppT (ConT predClass) predType <- cxt ] -- construct the FAlgebra instance let instFAlgebra = InstanceD Nothing [] ( AppT ( ConT $ mkName "FAlgebra" ) ( ConT $ algName) ) [ DataInstD [] ( mkName "Sig" ) [ ConT algName, VarT tagName, VarT varName ] Nothing ( consFunc++consPred ) [] , FunD ( mkName "mapRun" ) ( -- for each function constructor ( [ Clause [ VarP $ mkName "f" , ConP ( mkName $ "Sig_" ++ renameClassMethod sigName ) ( map VarP $ genericArgs sigType ) ] ( NormalB $ foldl AppE ( ConE $ mkName $ "Sig_"++renameClassMethod sigName ) -- FIXME: -- The code below handles lists specially, -- but it should work for any functor. [ if isList argType then AppE ( AppE ( VarE $ mkName "map" ) ( VarE $ mkName "f" ) ) ( VarE $ argName ) else if not $ isConcrete argType then AppE ( VarE $ mkName "f" ) ( VarE $ argName ) else VarE argName | (argName,argType) <- zip (genericArgs sigType) (getArgs sigType) ] ) [] | SigD sigName sigType <- decs ] )++ -- for each predicate constructor [ Clause [ VarP $ mkName "f" , ConP ( mkName $ "Sig_"++renameClassMethod algName ++"_"++renameClassMethod predClass ++"_"++predType2str predType ) [ VarP $ mkName "s" ] ] ( NormalB ( AppE ( ConE $ mkName $ "Sig_"++renameClassMethod algName ++"_"++renameClassMethod predClass ++"_"++predType2str predType ) ( AppE ( AppE ( VarE $ mkName "mapRun" ) ( VarE $ mkName "f" ) ) ( VarE $ mkName "s" ) ) ) ) [] | AppT (ConT predClass) predType <- cxt ] ++ -- catch all error message [ Clause [ VarP $ mkName "f", VarP $ mkName "s" ] ( NormalB $ AppE ( VarE $ mkName "error" ) ( LitE $ StringL $ "mapRun ("++renameClassMethod algName++"): this should never happen" ) ) [] ] ) , FunD ( mkName "runSig1" ) ( -- evaluate functions ( catMaybes [ case getReturnType sigType of (VarT _) -> Nothing _ -> Just $ Clause [ SigP ( VarP $ mkName "p" ) ( AppT ( VarT $ mkName "proxy" ) ( VarT $ mkName "r" ) ) , ConP ( mkName $ "Sig_" ++ renameClassMethod sigName ) ( map VarP ( genericArgs sigType ) ) ] ( NormalB $ foldl AppE (VarE sigName) $ map VarE $ genericArgs sigType ) [] | SigD sigName sigType <- decs ] ) ++ -- evaluate nested constructors [ Clause [ SigP ( VarP $ mkName "p" ) ( AppT ( VarT $ mkName "proxy" ) ( VarT varName ) ) , SigP ( ConP ( mkName $ "Sig_"++renameClassMethod algName ++"_"++renameClassMethod predClass ++"_"++predType2str predType ) [ VarP $ mkName $ "s" ] ) ( AppT ( AppT ( AppT ( ConT $ mkName "Sig" ) ( ConT $ algName ) ) ( AppT ( AppT PromotedConsT ( VarT $ mkName "s" ) ) ( VarT $ mkName "t" ) ) ) ( AppT ( AppT ( ConT $ mkName "AppTags" ) ( VarT $ mkName "t" ) ) ( VarT $ mkName "a" ) ) ) ] ( NormalB $ case predType of (VarT _) -> AppE ( AppE ( VarE $ mkName "runSig1" ) ( VarE $ mkName "p" ) ) ( VarE $ mkName "s" ) _ -> AppE ( AppE ( AppE ( AppE ( AppE ( VarE $ mkName "runSig1Snoc" ) ( mkProxyE $ pred2tagSingleton predType ) ) ( mkProxyE $ VarT $ mkName "s" ) ) ( mkProxyE $ VarT $ mkName "t" ) ) ( mkProxyE $ VarT $ mkName "a" ) ) ( VarE $ mkName "s" ) ) [] | AppT (ConT predClass) predType <- cxt ] ++ -- catch all error message [ Clause [ VarP $ mkName "p", VarP $ mkName "s" ] ( NormalB $ AppE ( VarE $ mkName "error" ) ( LitE $ StringL $ "runSig1 ("++renameClassMethod algName++"): this should never happen" ) ) [] ] ) , FunD ( mkName "runSig0" ) ( -- evaluate functions ( catMaybes [ case getReturnType sigType of (VarT _) -> Just $ Clause [ SigP ( VarP $ mkName "p" ) ( AppT ( VarT $ mkName "proxy" ) ( VarT $ mkName "r" ) ) , ConP ( mkName $ "Sig_" ++ renameClassMethod sigName ) ( map VarP ( genericArgs sigType ) ) ] ( NormalB $ foldl AppE (VarE sigName) $ map VarE $ genericArgs sigType ) [] _ -> Nothing | SigD sigName sigType <- decs ] ) ++ -- evaluate nested constructors [ Clause [ SigP ( VarP $ mkName "p" ) ( AppT ( VarT $ mkName "proxy" ) ( VarT varName ) ) , ConP ( mkName $ "Sig_"++renameClassMethod algName ++"_"++renameClassMethod predClass ++"_"++predType2str predType ) [ VarP $ mkName $ "s" ] ] ( NormalB $ case predType of (VarT _) -> AppE ( AppE ( VarE $ mkName "runSig0" ) ( VarE $ mkName "p" ) ) ( VarE $ mkName "s" ) _ -> AppE ( AppE ( AppE ( VarE $ mkName "runSig0Snoc" ) ( SigE ( ConE $ mkName "Proxy" ) ( AppT ( ConT $ mkName "Proxy" ) ( pred2tagSingleton predType ) ) ) ) ( SigE ( ConE $ mkName "Proxy" ) ( AppT ( ConT $ mkName "Proxy" ) ( VarT $ mkName "a" ) ) ) ) ( VarE $ mkName "s" ) ) [] | AppT (ConT predClass) predType <- cxt ] ++ -- catch all error message [ Clause [ VarP $ mkName "p", VarP $ mkName "s" ] ( NormalB $ AppE ( VarE $ mkName "error" ) ( LitE $ StringL $ "runSig0 ("++renameClassMethod algName++"): this should never happen" ) ) [] ] ) ] -- construct pattern synonyms -- -- FIXME: -- The pattern synonyns for the tagged and untagged versions are currently split into two separate cases. -- There's a lot of overlap in them though, and so the code would probably be nicer to merge the two cases. #if __GHC__GLASGOW__ < 801 let patSyns = [] #else let patSyns = concat $ [ if isVarT $ getReturnType sigType then [ PatSynSigD ( mkName $ "AST_" ++ renameClassMethod sigName ) ( ForallT [ PlainTV $ mkName "alg" , PlainTV tagName , PlainTV varName ] [ AppT ( AppT ( AppT ( AppT ( ConT $ mkName "View" ) ( ConT $ algName ) ) PromotedNilT ) ( VarT $ mkName "alg" ) ) ( VarT tagName ) , AppT ( AppT ( ConT $ mkName "FreeConstraints" ) ( VarT tagName ) ) ( VarT varName ) ] ( foldr (\a b -> AppT ( AppT ArrowT ( if isConcrete a then a else AppT ( AppT ( AppT ( ConT $ mkName "Free" ) ( AppT ( ConT $ mkName "Sig" ) ( VarT $ mkName "alg" ) ) ) ( if isVarT a then VarT tagName else pred2tag (VarT tagName) a ) ) ( VarT varName ) ) ) b ) ( AppT ( AppT ( AppT ( ConT $ mkName "Free" ) ( AppT ( ConT $ mkName "Sig" ) ( VarT $ mkName "alg" ) ) ) ( VarT tagName ) ) ( VarT varName ) ) ( getArgs sigType ) ) ) , PatSynD ( mkName $ "AST_" ++ renameClassMethod sigName ) ( PrefixPatSyn $ genericArgs sigType ) ( ExplBidir [ Clause ( map VarP $ genericArgs sigType ) ( NormalB $ AppE ( ConE $ mkName "Free0" ) ( AppE ( VarE $ mkName "embedSig" ) ( foldl AppE ( ConE $ mkName $ "Sig_" ++ renameClassMethod sigName ) ( map VarE $ genericArgs sigType ) ) ) ) [] ] ) ( ConP ( mkName "Free0" ) [ ViewP ( VarE $ mkName "unsafeExtractSigTag0" ) ( ConP ( mkName $ "Sig_" ++ renameClassMethod sigName ) ( map VarP $ genericArgs sigType ) ) ] ) ] else [ PatSynSigD ( mkName $ "AST_" ++ renameClassMethod sigName ) ( ForallT [ PlainTV $ mkName "alg" , PlainTV tagName , PlainTV varName ] [ AppT ( AppT ( AppT ( AppT ( ConT $ mkName "View" ) ( ConT $ algName ) ) ( pred2tag PromotedNilT $ getReturnType sigType ) ) ( VarT $ mkName "alg" ) ) ( pred2tag (VarT tagName) $ getReturnType sigType ) , AppT ( AppT ( ConT $ mkName "FreeConstraints" ) ( VarT tagName ) ) ( VarT varName ) ] ( foldr (\a b -> AppT ( AppT ArrowT ( AppT ( AppT ( AppT ( ConT $ mkName "Free" ) ( AppT ( ConT $ mkName "Sig" ) ( VarT $ mkName "alg" ) ) ) ( if isVarT a then VarT tagName else pred2tag (VarT tagName) a ) ) ( VarT varName ) ) ) b ) ( AppT ( AppT ( AppT ( ConT $ mkName "Free" ) ( AppT ( ConT $ mkName "Sig" ) ( VarT $ mkName "alg" ) ) ) ( if isVarT $ getReturnType sigType then VarT tagName else pred2tag (VarT tagName) $ getReturnType sigType ) ) ( VarT varName ) ) ( getArgs sigType ) ) ) , PatSynD ( mkName $ "AST_" ++ renameClassMethod sigName ) ( PrefixPatSyn $ genericArgs sigType ) ( ExplBidir [ Clause ( map VarP $ genericArgs sigType ) ( NormalB $ AppE ( ConE $ mkName "Free1" ) ( AppE ( VarE $ mkName "embedSigTag" ) ( foldl AppE ( ConE $ mkName $ "Sig_" ++ renameClassMethod sigName ) ( map VarE $ genericArgs sigType ) ) ) ) [] ] ) ( ConP ( mkName "Free1" ) [ ViewP ( VarE $ mkName "unsafeExtractSigTag" ) ( ConP ( mkName $ "Sig_" ++ renameClassMethod sigName ) ( map VarP $ genericArgs sigType ) ) ] ) ] | SigD sigName sigType <- decs ] #endif -- construct the overlapping Show instance let instShowOverlap = InstanceD ( Just Overlapping ) [] ( AppT ( ConT $ mkName "Show" ) ( AppT ( AppT ( AppT ( ConT $ mkName "Sig" ) ( ConT algName ) ) ( foldr (\a b -> AppT ( AppT PromotedConsT ( VarT $ mkName $ "t"++show a ) ) b ) PromotedNilT [1..4] ) ) ( VarT $ varName ) ) ) [ FunD ( mkName "show" ) [ Clause [ VarP $ mkName "s" ] ( NormalB $ LitE $ StringL "<<overflow>>" ) [] ] ] -- construct the `Show a => Show (Sig98 alg a)` instance let instShow = InstanceD ( Just Overlappable ) ( (nub $ concat $ concat $ concat $ [ [ [ case t of ( ConT _ ) -> [] _ -> [ AppT ( ConT $ mkName "Show" ) ( subAllVars (VarT varName) t ) ] | t <- getReturnType sigType:getArgs sigType ] | SigD sigName sigType <- filter isHeterogeneousFunction decs ] | PredInfo (AppT (ConT predClass) predType) (ClassI (ClassD _ _ _ _ decs) _) _ <- allcxt ]) -- nub $ -- ( concat $ concat $ -- [ [ case t of -- ( ConT _ ) -> [] -- _ -> [ AppT -- ( ConT $ mkName "Show" ) -- ( subAllVars (VarT varName) t ) -- ] -- | t <- getReturnType sigType:getArgs sigType -- ] -- | SigD sigName sigType <- decs -- ] -- ) -- ++ -- [ AppT -- ( ConT $ mkName "Show" ) -- ( AppT -- ( AppT -- ( AppT -- ( ConT $ mkName "Sig" ) -- ( ConT predClass ) -- ) -- ( case predType of -- (VarT _) -> VarT tagName -- _ -> AppT -- ( AppT -- ( ConT $ mkName "Snoc" ) -- ( VarT tagName ) -- ) -- ( pred2tagSingleton predType ) -- ) -- -- ( VarT $ mkName "t" ) -- ) -- ( VarT $ mkName "a" ) -- ) -- | AppT (ConT predClass) predType <- cxt -- ] ) ( AppT ( ConT $ mkName "Show" ) ( AppT ( AppT ( AppT ( ConT $ mkName "Sig" ) ( ConT algName ) ) ( VarT $ tagName ) ) ( VarT $ varName ) ) ) [ FunD ( mkName "show" ) ( -- show all the class's predicates [ Clause [ ConP ( mkName $ "Sig_"++renameClassMethod algName ++"_"++renameClassMethod predClass ++"_"++predType2str predType ) [ VarP $ mkName "s" ] ] ( NormalB $ AppE ( VarE $ mkName "show" ) ( VarE $ mkName "s" ) ) [] | AppT (ConT predClass) predType <- cxt ] ++ -- show all the class's functions [ Clause [ ConP ( mkName $ "Sig_" ++ renameClassMethod sigName ) ( map VarP $ genericArgs sigType ) ] ( if isOperator (renameClassMethod sigName) -- if we're an operator, then there's exactly two arguments named a0, a1; -- display the operator infix then NormalB $ AppE ( AppE ( VarE $ mkName "++" ) ( AppE ( AppE ( VarE $ mkName "++" ) ( AppE ( VarE $ mkName "show" ) ( VarE $ mkName "a0" ) ) ) ( LitE $ StringL $ renameClassMethod sigName ) ) ) ( AppE ( VarE $ mkName "show" ) ( VarE $ mkName "a1" ) ) -- not an operator means we display the function prefix, -- there may be anynumber 0 or more arguments that we have to fold over else NormalB $ foldl ( \b a -> AppE ( AppE ( VarE $ mkName "++" ) ( AppE ( AppE ( VarE $ mkName "++" ) b ) ( LitE $ StringL " " ) ) ) ( AppE ( VarE $ mkName "show" ) a ) ) ( LitE $ StringL $ renameClassMethod sigName ) ( map VarE $ genericArgs sigType ) ) [] | SigD sigName sigType <- decs ] ++ -- catch all error message [ Clause [ VarP $ mkName "s" ] ( NormalB $ AppE ( VarE $ mkName "error" ) ( LitE $ StringL $ "show ("++renameClassMethod algName++"): this should never happen" ) ) [] ] ) ] -- construct the `View alg '[] alg' t => alg (Free (Sig alg') t a)` instance let instFree = InstanceD Nothing ( nub $ -- the `FreeConstraints` instance ( [ AppT ( AppT ( ConT $ mkName "FreeConstraints" ) ( type2tag predType ) ) ( VarT $ mkName "a" ) | PredInfo (AppT (ConT predClass) predType) _ _ <- allcxt ] ++ [ AppT ( AppT ( ConT $ mkName "FreeConstraints" ) ( VarT $ mkName "t" ) ) ( VarT $ mkName "a" ) ] ) ++ -- the `View ...` constraints ( concat $ [ [ AppT ( AppT ( AppT ( AppT ( ConT $ mkName "View" ) ( ConT predClass ) ) ( cons2consTag $ pred2tag PromotedNilT $ getReturnType sigType ) ) ( VarT $ mkName "alg'" ) ) ( cons2consTag $ pred2tag ( pred2tag (VarT tagName) predType ) ( getReturnType sigType ) ) | SigD _ sigType <- filter isHeterogeneousFunction decs ] | PredInfo (AppT (ConT predClass) predType) (ClassI (ClassD _ _ _ _ decs) _) _ <- allcxt ] ) ++ -- the ConsTagCnst constraints -- FIXME: ensure that `c` is set correctly ( concat $ [ [ AppT ( AppT EqualityT ( type2tag $ subAllVars predType t1 ) ) ( type2tag $ subAllVars predType t2 ) | (AppT (AppT c t1) t2) <- cxt ] | PredInfo (AppT (ConT predClass) predType) (ClassI (ClassD cxt _ _ _ _) _) _ <- allcxt ] ) ++ -- MkFree instances -- FIXME: ensure that `c` is set correctly [ AppT ( AppT ( AppT ( ConT $ mkName "MkFree" ) ( ConT $ mkName t ) ) ( foldl' ( \b a -> AppT ( AppT ( ConT $ mkName "ConsTag" ) ( ConT $ mkName a ) ) b ) ( VarT $ mkName "t" ) ts ) ) ( VarT $ mkName "a" ) | (t,ts) <- nub $ concat $ concat $ [ [ case t1 of (AppT (ConT n) _) -> [ ( "T"++renameClassMethod n , (case pred2strList predType of [] -> [] (s:_) -> if renameClassMethod n==s then [] else [s] )++(replicate i $ "T"++renameClassMethod n ) ) | i <- [0..min (depthSameAppT t1) (depthSameAppT t2)] ] _ -> [] | (AppT (AppT c t1) t2) <- cxt ] | PredInfo (AppT (ConT predClass) predType) (ClassI (ClassD cxt _ _ _ _) _) _ <- allcxt ] -- the section above genrates lists of the form -- [("TLogic",[]) -- ,("TLogic",["TLogic"]) -- ,("TLogic",["TLogic","TLogic"]) -- ] ] ) ( AppT ( ConT algName ) ( AppT ( AppT ( AppT ( ConT $ mkName "Free" ) ( AppT ( ConT $ mkName "Sig" ) ( VarT $ mkName "alg'" ) ) ) ( VarT $ tagName ) ) ( VarT varName ) ) ) ( -- create associated types [ TySynInstD atName $ TySynEqn [ AppT ( AppT ( AppT ( ConT $ mkName "Free" ) ( AppT ( ConT $ mkName "Sig" ) ( VarT $ mkName "alg'" ) ) ) ( VarT $ tagName ) ) ( VarT varName ) ] ( AppT ( AppT ( AppT ( ConT $ mkName "Free" ) ( AppT ( ConT $ mkName "Sig" ) ( VarT $ mkName "alg'" ) ) ) ( AppT ( AppT ( ConT $ mkName "ConsTag" ) ( ConT $ mkName $ "T"++renameClassMethod atName ) ) ( VarT $ tagName ) ) ) ( VarT varName ) ) | OpenTypeFamilyD (TypeFamilyHead atName _ _ _) <- decs ] ++ -- create associated functions [ FunD sigName [ Clause ( map VarP $ genericArgs sigType ) ( NormalB $ case getReturnType sigType of (VarT _) -> AppE ( ConE $ mkName "Free0" ) ( AppE ( VarE $ mkName "embedSig" ) ( foldl AppE (ConE $ mkName $ "Sig_"++renameClassMethod sigName) $ map VarE $ genericArgs sigType ) ) (AppT (ConT n) _) -> AppE ( AppE ( VarE $ mkName "mkFree" ) ( SigE ( ConE $ mkName "Proxy" ) ( AppT ( ConT $ mkName "Proxy" ) ( ConT $ mkName $ "T"++renameClassMethod n ) ) ) ) ( AppE ( VarE $ mkName "embedSig" ) ( foldl AppE (ConE $ mkName $ "Sig_"++renameClassMethod sigName) $ map VarE $ genericArgs sigType ) ) _ -> AppE ( VarE $ mkName "error" ) ( LitE $ StringL $ renameClassMethod sigName++" called on AST, but return type unsupported; this should never happen" ) ) [] ] | SigD sigName sigType <- decs ] ) -- construct the `View alg alg'` instances let instViews = nubBy (\ (InstanceD _ _ i1 _) (InstanceD _ _ i2 _) -> i1==i2) $ concat $ [ [ InstanceD Nothing [] ( AppT ( AppT ( AppT ( AppT ( ConT $ mkName "View" ) ( ConT predClass ) ) ( pred2tag PromotedNilT ( getReturnType sigType ) ) ) ( ConT algName ) ) ( pred2tag ( pred2tag PromotedNilT predType ) ( getReturnType sigType ) ) ) [ if parent==thisPred -- parent predicates are stored directly in Sig -- there is no need to call embedSig recusively then FunD ( mkName "embedSig" ) [ Clause [] ( NormalB $ ConE $ mkName $ "Sig_"++renameClassMethod algName ++"_"++renameClassMethod predClass ++"_"++predType2str predType ) [] ] -- non-parent predicates must be embedded in the Sig -- with a recusive call to embedSig else FunD ( mkName "embedSig" ) [ Clause [ SigP ( VarP $ mkName "s" ) ( AppT ( AppT ( AppT ( ConT $ mkName "Sig" ) ( ConT predClass ) ) ( pred2tag PromotedNilT ( getReturnType sigType ) ) ) ( VarT varName ) ) ] ( NormalB $ AppE ( ConE $ mkName $ "Sig_"++renameClassMethod algName ++"_"++renameClassMethod parentClass ++"_"++predType2str parentType ) ( SigE ( AppE ( VarE $ mkName "embedSig" ) ( VarE $ mkName "s" ) ) ( AppT ( AppT ( AppT ( ConT $ mkName "Sig" ) ( ConT parentClass ) ) ( case parentType of (VarT _) -> pred2tag ( pred2tag PromotedNilT predType ) ( getReturnType sigType ) _ -> typeListInit $ pred2tag ( pred2tag PromotedNilT predType ) ( getReturnType sigType ) ) ) ( VarT varName ) ) ) ) [] ] , if parent==thisPred -- parent predicates are stored directly in Sig -- there is no need to call unsafeExtractSig then FunD ( mkName "unsafeExtractSig" ) [ Clause [ ConP ( mkName $ "Sig_"++renameClassMethod algName ++"_"++renameClassMethod predClass ++"_"++predType2str predType ) [ VarP $ mkName "s" ] ] ( NormalB $ AppE ( AppE ( VarE $ mkName "unsafeCoerceSigTag" ) ( SigE ( ConE $ mkName "Proxy" ) ( AppT ( ConT $ mkName "Proxy" ) ( pred2tag PromotedNilT $ getReturnType sigType ) ) ) ) ( VarE $ mkName "s" ) ) [] ] -- non-parent predicates must be embedded in the Sig -- with a recusive call to unsafeExtractSig else FunD ( mkName "unsafeExtractSig" ) [ Clause [ ConP ( mkName $ "Sig_"++renameClassMethod algName ++"_"++renameClassMethod parentClass ++"_"++predType2str parentType ) [ VarP $ mkName "s" ] ] ( NormalB $ AppE ( VarE $ mkName "unsafeExtractSig" ) ( AppE ( AppE ( VarE $ mkName "unsafeCoerceSigTag" ) ( SigE ( ConE $ mkName "Proxy" ) ( AppT ( ConT $ mkName "Proxy" ) ( case parentType of (VarT _) -> pred2tag ( pred2tag PromotedNilT predType ) ( getReturnType sigType ) _ -> typeListInit $ pred2tag ( pred2tag PromotedNilT predType ) ( getReturnType sigType ) ) ) ) ) ( VarE $ mkName "s" ) ) ) [] ] ] | SigD _ sigType <- filter isHeterogeneousFunction $ SigD undefined (VarT varName):decs ] | PredInfo (AppT (ConT predClass) predType) (ClassI (ClassD _ _ _ _ decs) _) (Just parent@(AppT (ConT parentClass) parentType)) <- allcxt ] if nameBase algName=="Constructible" then return $ nub $ ats ++ instViews ++ patSyns ++ [instFAlgebra,instShow,instShowOverlap,instFree] else return $ nub $ ats ++ instViews ++ patSyns ++ [instFAlgebra,instShow,instShowOverlap,instFree] predType2str :: Pred -> String predType2str (ConT t) = renameClassMethod t predType2str (AppT a1 a2) = predType2str a1 ++ "_" ++ predType2str a2 predType2str _ = "" pred2strList :: Pred -> [String] pred2strList (AppT (ConT n) t) = ("T"++renameClassMethod n):pred2strList t pred2strList _ = [] pred2tag :: Pred -> Pred -> TH.Type pred2tag s t = foldr (\a b -> AppT (AppT PromotedConsT a) b) s $ go t where go (AppT a1 a2) = go a1 ++ go a2 go (ConT t) = [ConT $ mkName $ "T"++renameClassMethod t] go _ = [] cons2consTag :: TH.Type -> TH.Type cons2consTag PromotedConsT = ConT $ mkName "ConsTag" cons2consTag (AppT t1 t2) = AppT (cons2consTag t1) (cons2consTag t2) cons2consTag t = t pred2tagSingleton :: Pred -> TH.Type pred2tagSingleton t = case pred2tag PromotedNilT t of (AppT (AppT PromotedConsT t) PromotedNilT) -> t typeListTail :: TH.Type -> TH.Type typeListTail (AppT (AppT PromotedConsT _) t) = t typeListInit :: TH.Type -> TH.Type typeListInit (AppT (AppT PromotedConsT t ) PromotedNilT) = PromotedNilT typeListInit (AppT (AppT PromotedConsT t1) t2 ) = AppT (AppT PromotedConsT t1) $ typeListInit t2 typeListHead :: TH.Type -> TH.Type typeListHead (AppT (AppT PromotedConsT t) _) = t subAllVars :: TH.Type -> TH.Type -> TH.Type subAllVars e = go where go (VarT _) = e go (AppT t1 t2) = AppT (go t1) (go t2) go t = t renameVars :: TH.Type -> TH.Type renameVars = go where go (VarT n) = VarT $ mkName $ renameClassMethod n go (AppT t1 t2) = AppT (go t1) (go t2) go t = t mkProxyE :: TH.Type -> Exp mkProxyE t = SigE ( ConE $ mkName "Proxy" ) ( AppT (ConT $ mkName "Proxy") t) -- | Converts a type of the form -- -- > Scalar (Scalar (Scalar a))) -- -- into -- -- > TScalar ': TScalar ': TScalar ': t type2tag :: TH.Type -> TH.Type type2tag (AppT (ConT n) t) = AppT ( AppT ( ConT $ mkName "ConsTag" ) ( ConT $ mkName $ "T"++renameClassMethod n ) ) ( type2tag t ) type2tag _ = VarT $ mkName "t" -- | Stores all the information we'll need about a predicate data PredInfo = PredInfo { predSig :: Pred , predReify :: Info , predHost :: Maybe Pred } deriving (Eq,Show) depthSameAppT :: TH.Type -> Int depthSameAppT (AppT t1 t2) = go 1 t2 where go i (AppT t1' t2') = if t1==t1' then go (i+1) t2' else i go i _ = i depthSameAppT _ = 0 -- FIXME: -- This is poor approximation of the true definition isHeterogeneousFunction :: Dec -> Bool isHeterogeneousFunction x = case x of SigD _ sigType -> if isConcrete $ getReturnType sigType then False else case getReturnType sigType of (AppT (VarT _) _) -> False _ -> True _ -> True isEqualityCnst :: TH.Type -> Bool isEqualityCnst (AppT (AppT (ConT n) _) _) = show n == "Data.Type.Equality.~" isEqualityCnst (AppT (AppT EqualityT _) _) = True isEqualityCnst _ = False subTypeFamilies :: Cxt -> Q Cxt subTypeFamilies cxt = do cxt1 <- go cxt cxt2 <- go cxt1 if cxt1==cxt2 then return cxt1 else go cxt2 where go [] = return [] go ((x@(AppT (ConT n) t)):xs) = do qinfo <- reify n case qinfo of TyConI (TySynD _ _ t') -> do xs' <- go xs return $ map (subAllVars t) (tuple2list t') ++ xs' _ -> do xs' <- go xs return $ x:xs' go (x:xs) = do xs' <- go xs return $ x:xs' tuple2list :: Pred -> Cxt tuple2list t@(AppT t1 t2) = if go t1 then t2:tuple2list t1 else [t] where go (TupleT _) = True go (AppT t _) = go t go _ = False tuple2list (TupleT _) = [] tuple2list t = [t] -- | Given a predicate that represents a class/tag combination, -- recursively list all super predicates superPredicates :: Pred -> Q [PredInfo] superPredicates (ForallT _ _ t) = superPredicates t superPredicates rootPred@(AppT (ConT predClass) _) = do qinfo <- reify predClass go [] $ PredInfo rootPred qinfo Nothing where go :: Cxt -- a list containing all of the equality constraints in effect -> PredInfo -- the predicate that we're recursively finding superpredicates of -> Q [PredInfo] go eqcxt predInfo@(PredInfo (AppT (ConT predClass) predType) _ _) = do if stopRecursion eqcxt (predSig predInfo) then return [] else do qinfo <- reify predClass case qinfo of ClassI (ClassD cxt a b@[_] c d) e -> do cxt' <- subTypeFamilies cxt newCxt <- mapM (go $ eqcxt ++ filter isEqualityCnst cxt') $ map (\sig -> PredInfo sig undefined $ if predHost predInfo==Nothing || predHost predInfo==Just rootPred then Just $ predSig predInfo else predHost predInfo ) $ map (subPred predType) cxt' let newEqcxt = map (\t -> PredInfo t qinfo $ predHost predInfo ) $ filter isEqualityCnst cxt' return $ nub $ predInfo { predReify=ClassI (ClassD cxt' a b c d) e }:concat newCxt++newEqcxt _ -> error $ "superPredicates called on " ++show predClass ++", which is not a class of kind `Type -> Constraint`" go _ _ = return [] -- stop looking for superpredicates when they are being generated by an idempotent type family -- this lets us handle the UndecidableSuperClasses language extension stopRecursion :: Cxt -- a list containing all of the equality constraints in effect -> TH.Type -- the type signature to simplify based on equality constraints -> Bool stopRecursion eqcxt (AppT _ t) = or [ depthSameAppT t > max (depthSameAppT t1) (depthSameAppT t2) | AppT (AppT _ t1) t2 <- eqcxt ] stopRecursion _ _ = False -- When the go function recurses, -- we need to remember what layer of tags we've already seen. -- This function substitutes those tags into the predicate. subPred :: Pred -> Pred -> Pred subPred predType' (AppT (ConT predClass) predType) = AppT (ConT predClass) $ go predType where go (AppT t1 t2) = AppT t1 $ go t2 go (VarT t) = predType' go t = t subPred p t = t -- FIXME?
mikeizbicki/homoiconic
src/Homoiconic/Constrained/TH.hs
bsd-3-clause
70,464
11
37
45,223
10,686
5,393
5,293
-1
-1
-------------------------------------------------------------------------------- module Hakyll.Core.Provider.MetadataCache ( resourceMetadata , resourceBody , resourceInvalidateMetadataCache ) where -------------------------------------------------------------------------------- import qualified Data.Map as M -------------------------------------------------------------------------------- import Hakyll.Core.Identifier import Hakyll.Core.Metadata import Hakyll.Core.Provider.Internal import Hakyll.Core.Provider.Metadata import qualified Hakyll.Core.Store as Store -------------------------------------------------------------------------------- resourceMetadata :: Provider -> Identifier -> IO Metadata resourceMetadata p r | not (resourceExists p r) = return M.empty | otherwise = do -- TODO keep time in md cache load p r Store.Found md <- Store.get (providerStore p) [name, toFilePath r, "metadata"] return md -------------------------------------------------------------------------------- resourceBody :: Provider -> Identifier -> IO String resourceBody p r = do load p r Store.Found bd <- Store.get (providerStore p) [name, toFilePath r, "body"] maybe (resourceString p r) return bd -------------------------------------------------------------------------------- resourceInvalidateMetadataCache :: Provider -> Identifier -> IO () resourceInvalidateMetadataCache p r = do Store.delete (providerStore p) [name, toFilePath r, "metadata"] Store.delete (providerStore p) [name, toFilePath r, "body"] -------------------------------------------------------------------------------- load :: Provider -> Identifier -> IO () load p r = do mmd <- Store.get store mdk :: IO (Store.Result Metadata) case mmd of -- Already loaded Store.Found _ -> return () -- Not yet loaded _ -> do (md, body) <- loadMetadata p r Store.set store mdk md Store.set store bk body where store = providerStore p mdk = [name, toFilePath r, "metadata"] bk = [name, toFilePath r, "body"] -------------------------------------------------------------------------------- name :: String name = "Hakyll.Core.Resource.Provider.MetadataCache"
bergmark/hakyll
src/Hakyll/Core/Provider/MetadataCache.hs
bsd-3-clause
2,406
0
13
512
535
278
257
42
2
{-# LANGUAGE GeneralizedNewtypeDeriving, StandaloneDeriving, FlexibleContexts, FlexibleInstances, NamedFieldPuns #-} module Distribution.Server.Framework.Resource ( -- | Paths DynamicPath, BranchComponent(..), BranchPath, trunkAt, -- | Resources Resource(..), ResourceFormat(..), BranchFormat(..), BranchEnd(..), Content, resourceAt, extendResource, extendResourcePath, serveResource, resourceMethods, -- | URI generation renderURI, renderResource, renderResource', -- | ServerTree ServerTree(..), serverTreeEmpty, addServerNode, renderServerTree, drawServerTree, -- | Error page serving serveErrorResponse, ServerErrorResponse, ) where import Distribution.Server.Prelude import Happstack.Server import Distribution.Server.Framework.HappstackUtils (remainingPathString, uriEscape) import Distribution.Server.Util.ContentType (parseContentAccept) import Distribution.Server.Framework.Error import Data.List (isSuffixOf) import Data.Map (Map) import qualified Data.Map as Map import Data.Function (on) import Data.List (intercalate, unionBy, findIndices, find) import qualified Text.ParserCombinators.Parsec as Parse import System.FilePath.Posix ((</>), (<.>)) import qualified Data.Tree as Tree (Tree(..), drawTree) import qualified Data.ByteString.Char8 as BS -- Used for accept header only type Content = String type DynamicPath = [(String, String)] type ServerResponse = DynamicPath -> ServerPartE Response type ServerErrorResponse = ErrorResponse -> ServerPartE Response -- | A resource is an object that handles requests at a given URI. Best practice -- is to construct it by calling resourceAt and then setting the method fields -- using record update syntax. You can also extend an existing resource with -- extendResource, which can be mappended to the original to combine their -- functionality, or with extendResourcePath. data Resource = Resource { -- | The location in a form which can be added to a ServerTree. resourceLocation :: BranchPath, -- | Handlers for GET requests for different content-types resourceGet :: [(Content, ServerResponse)], -- | Handlers for PUT requests resourcePut :: [(Content, ServerResponse)], -- | Handlers for POST requests resourcePost :: [(Content, ServerResponse)], -- | Handlers for DELETE requests resourceDelete :: [(Content, ServerResponse)], -- | The format conventions held by the resource. resourceFormat :: ResourceFormat, -- | The trailing slash conventions held by the resource. resourcePathEnd :: BranchEnd, -- | Human readable description of the resource resourceDesc :: [(Method, String)] } -- favors first instance Monoid Resource where mempty = Resource [] [] [] [] [] noFormat NoSlash [] mappend = (<>) instance Semigroup Resource where (Resource bpath rget rput rpost rdelete rformat rend desc) <> (Resource bpath' rget' rput' rpost' rdelete' rformat' rend' desc') = Resource (simpleCombine bpath bpath') (ccombine rget rget') (ccombine rput rput') (ccombine rpost rpost') (ccombine rdelete rdelete') (simpleCombine rformat rformat') (simpleCombine rend rend') (desc ++ desc') where ccombine = unionBy ((==) `on` fst) simpleCombine xs ys = if null bpath then ys else xs -- | A path element of a URI. -- -- * StaticBranch dirName - \/dirName -- * DynamicBranch dynamicName - \/anyName (mapping created dynamicName -> anyName) -- * TrailingBranch - doesn't consume any path; it's here to prevent e.g. conflict between \/.:format and \/... -- -- trunkAt yields a simple list of BranchComponents. -- resourceAt yields the same, and some complex metadata for processing formats and the like. data BranchComponent = StaticBranch String | DynamicBranch String | TrailingBranch deriving (Show, Eq, Ord) type BranchPath = [BranchComponent] -- | This type dictates the preprocessing we must do on extensions (foo.json) when serving Resources -- For BranchFormat, we need to do: -- 1. for NoFormat - don't do any preprocessing. The second field is ignored here. -- 1. for StaticFormat - look for a specific format, and guard against that -- 2. for DynamicFormat - strip off any extension (starting from the right end, so no periods allowed) -- Under either of the above cases, the component might need to be preprocessed as well. -- 1. for Nothing - this means a standalone format, like \/.json (as in \/distro\/arch\/.json) -- either accept \/distro\/arch\/ or read \/distro\/arch\/.format and pass it along -- 2. for Just (StaticBranch sdir) - strip off the pre-format part and make sure it equals sdir -- 3. for Just (DynamicBranch sdir) - strip off the pre-format part and pass it with the DynamicPath as sdir -- DynamicFormat also has the property that it is optional, and defaulting is allowed. data ResourceFormat = ResourceFormat BranchFormat (Maybe BranchComponent) deriving (Show, Eq, Ord) noFormat :: ResourceFormat noFormat = ResourceFormat NoFormat Nothing data BranchFormat = NoFormat | DynamicFormat | StaticFormat String deriving (Show, Eq, Ord) data BranchEnd = Slash | NoSlash | Trailing deriving (Show, Eq, Ord) -- | Creates an empty resource from a string specifying its location and format conventions. -- -- (Explain path literal syntax.) resourceAt :: String -> Resource resourceAt arg = mempty { resourceLocation = reverse loc , resourceFormat = format , resourcePathEnd = slash } where branch = either trunkError id $ Parse.parse parseFormatTrunkAt "Distribution.Server.Resource.parseFormatTrunkAt" arg trunkError pe = error $ "Distribution.Server.Resource.resourceAt: Could not parse trunk literal " ++ show arg ++ ". Parsec error: " ++ show pe (loc, slash, format) = trunkToResource branch -- | Creates a new resource at the same location, but without any of the request -- handlers of the original. When mappend'd to the original, its methods and content-types -- will be combined. This can be useful for extending an existing resource with new representations and new -- functionality. extendResource :: Resource -> Resource extendResource resource = resource { resourceDesc = [] , resourceGet = [] , resourcePut = [] , resourcePost = [] , resourceDelete = [] } -- | Creates a new resource that is at a subdirectory of an existing resource. This function takes care of formats -- as best as it can. -- -- extendResourcePath "\/bar\/.:format" (resourceAt "\/data\/:foo.:format") == resourceAt "\/data\/:foo\/bar\/:.format" -- -- Extending static formats with this method is not recommended. (extending "\/:tarball.tar.gz" -- with "\/data" will give "\/:tarball\/data", with the format stripped, and extending -- "\/help\/.json" with "\/tree" will give "\/help\/.json\/tree") extendResourcePath :: String -> Resource -> Resource extendResourcePath arg resource = let endLoc = case resourceFormat resource of ResourceFormat (StaticFormat _) Nothing -> case loc of (DynamicBranch "format":rest) -> rest _ -> funcError "Static ending format must have dynamic 'format' branch" ResourceFormat (StaticFormat _) (Just (StaticBranch sdir)) -> case loc of (DynamicBranch sdir':rest) | sdir == sdir' -> rest _ -> funcError "Static branch and format must match stated location" ResourceFormat (StaticFormat _) (Just (DynamicBranch sdir)) -> case loc of (DynamicBranch sdir':_) | sdir == sdir' -> loc _ -> funcError "Dynamic branch with static format must match stated location" ResourceFormat DynamicFormat Nothing -> loc ResourceFormat DynamicFormat (Just (StaticBranch sdir)) -> case loc of (DynamicBranch sdir':rest) | sdir == sdir' -> StaticBranch sdir:rest _ -> funcError "Dynamic format with static branch must match stated location" ResourceFormat DynamicFormat (Just (DynamicBranch sdir)) -> case loc of (DynamicBranch sdir':_) | sdir == sdir' -> loc _ -> funcError "Dynamic branch and format must match stated location" -- For a URI like /resource/.format: since it is encoded as NoFormat in trunkToResource, -- this branch will incorrectly be taken. this isn't too big a handicap though ResourceFormat NoFormat Nothing -> case loc of (TrailingBranch:rest) -> rest _ -> loc _ -> funcError $ "invalid resource format in argument 2" in extendResource resource { resourceLocation = reverse loc' ++ endLoc, resourceFormat = format', resourcePathEnd = slash' } where branch = either trunkError id $ Parse.parse parseFormatTrunkAt "Distribution.Server.Resource.parseFormatTrunkAt" arg trunkError pe = funcError $ "Could not parse trunk literal " ++ show arg ++ ". Parsec error: " ++ show pe funcError reason = error $ "Distribution.Server.Resource.extendResourcePath :" ++ reason loc = resourceLocation resource (loc', slash', format') = trunkToResource branch -- Allows the formation of a URI from a URI specification (BranchPath). -- URIs may obey additional constraints and have special rules (e.g., formats). -- To accomodate these, insteaduse renderResource to get a URI. -- -- ".." is a special argument that fills in a TrailingBranch. Make sure it's -- properly escaped (see Happstack.Server.SURI) -- -- renderURI (trunkAt "/home/:user/..") -- [("user", "mgruen"), ("..", "docs/todo.txt")] -- == "/home/mgruen/docs/todo.txt" renderURI :: BranchPath -> DynamicPath -> String renderURI bpath dpath = renderGenURI bpath (flip lookup dpath) -- Render a URI generally using a function of one's choosing (usually flip lookup dpath) -- Stops when a requested field is not found, yielding an incomplete URI. I think -- this is better than having a function that doesn't return *some* result. renderGenURI :: BranchPath -> (String -> Maybe String) -> String renderGenURI bpath pathFunc = "/" </> go (reverse bpath) where go (StaticBranch sdir:rest) = uriEscape sdir </> go rest go (DynamicBranch sdir:rest) | (ddir, sformat@('.':_)) <- break (=='.') sdir = case pathFunc ddir of Nothing -> "" Just str -> uriEscape str <.> uriEscape sformat </> go rest go (DynamicBranch sdir:rest) = case pathFunc sdir of Nothing -> "" Just str -> uriEscape str </> go rest go (TrailingBranch:_) = fromMaybe "" $ pathFunc ".." go [] = "" -- Doesn't use a DynamicPath - rather, munches path components from a list -- it stops if there aren't enough, and returns the extras if there's more than enough. -- -- Trailing branches currently are assumed to be complete escaped URI paths. renderListURI :: BranchPath -> [String] -> (String, [String]) renderListURI bpath list = let (res, extra) = go (reverse bpath) list in ("/" </> res, extra) where go (StaticBranch sdir:rest) xs = let (res, extra) = go rest xs in (uriEscape sdir </> res, extra) go (DynamicBranch _:rest) (x:xs) = let (res, extra) = go rest xs in (uriEscape x </> res, extra) go (TrailingBranch:_) xs = case xs of [] -> ("", []); (x:rest) -> (x, rest) go _ rest = ("", rest) -- Given a Resource, construct a URI generator. If the Resource uses a dynamic format, it can -- be passed in the DynamicPath as "format". Trailing slash conventions are obeyed. -- -- See documentation for the Resource to see the conventions in interpreting the DynamicPath. -- As in renderURI, ".." is interpreted as the trailing branch. It should be the case that -- -- > fix $ \r -> (resourceAt uri) { resourceGet = [("txt", ok . toResponse . renderResource' r)] } -- -- will print the URI that was used to request the page. -- -- renderURI (resourceAt "/home/:user/docs/:doc.:format") -- [("user", "mgruen"), ("doc", "todo"), ("format", "txt")] -- == "/home/mgruen/docs/todo.txt" renderResource' :: Resource -> DynamicPath -> String renderResource' resource dpath = renderResourceFormat resource (lookup "format" dpath) $ renderGenURI (normalizeResourceLocation resource) (flip lookup dpath) -- A more convenient form of renderResource'. Used when you know the path structure. -- The first argument unused in the path, if any, will be used as a dynamic format, -- if any. -- -- renderResource (resourceAt "/home/:user/docs/:doc.:format") -- ["mgruen", "todo", "txt"] -- == "/home/mgruen/docs/todo.txt" renderResource :: Resource -> [String] -> String renderResource resource list = case renderListURI (normalizeResourceLocation resource) list of (str, format:_) -> renderResourceFormat resource (Just format) str (str, []) -> renderResourceFormat resource Nothing str -- in some cases, DynamicBranches are used to accomodate formats for StaticBranches. -- this returns them to their pre-format state so renderGenURI can handle them normalizeResourceLocation :: Resource -> BranchPath normalizeResourceLocation resource = case (resourceFormat resource, resourceLocation resource) of (ResourceFormat _ (Just (StaticBranch sdir)), DynamicBranch sdir':xs) | sdir == sdir' -> StaticBranch sdir:xs (_, loc) -> loc renderResourceFormat :: Resource -> Maybe String -> String -> String renderResourceFormat resource dformat str = case (resourcePathEnd resource, resourceFormat resource) of (NoSlash, ResourceFormat NoFormat _) -> str (Slash, ResourceFormat NoFormat _) -> case str of "/" -> "/"; _ -> str ++ "/" (NoSlash, ResourceFormat (StaticFormat format) branch) -> case branch of Just {} -> str ++ "." ++ format Nothing -> str ++ "/." ++ format (Slash, ResourceFormat DynamicFormat Nothing) -> case dformat of Just format@(_:_) -> str ++ "/." ++ format _ -> str ++ "/" (NoSlash, ResourceFormat DynamicFormat _) -> case dformat of Just format@(_:_) -> str ++ "." ++ format _ -> str -- This case might be taken by TrailingBranch _ -> str ----------------------- -- Converts the output of parseTrunkFormatAt to something consumable by a Resource -- It forbids many things that parse correctly, most notably using formats in the middle of a path. -- It's possible in theory to allow such things, but complicated. -- Directories are really format-less things. -- -- trunkToResource is a top-level call to weed out cases that don't make sense recursively in trunkToResource' trunkToResource :: [(BranchComponent, BranchFormat)] -> ([BranchComponent], BranchEnd, ResourceFormat) trunkToResource [] = ([], Slash, noFormat) -- "" trunkToResource [(StaticBranch "", format)] = ([], Slash, ResourceFormat format Nothing) -- "/" or "/.format" trunkToResource anythingElse = trunkToResource' anythingElse trunkToResource' :: [(BranchComponent, BranchFormat)] -> ([BranchComponent], BranchEnd, ResourceFormat) trunkToResource' [] = ([], NoSlash, noFormat) -- /... trunkToResource' ((TrailingBranch, _):xs) | null xs = ([TrailingBranch], Trailing, noFormat) | otherwise = error "Trailing path only allowed at very end" -- /foo/, /foo/.format, or /foo/.:format trunkToResource' [(branch, NoFormat), (StaticBranch "", format)] = pathFormatSep format where pathFormatSep (StaticFormat form) = ([branch, StaticBranch ("." ++ form)], NoSlash, noFormat) -- /foo/.json, format is not optional here! pathFormatSep DynamicFormat = ([branch], Slash, ResourceFormat DynamicFormat Nothing) -- /foo/.format pathFormatSep NoFormat = ([branch], Slash, noFormat) -- /foo/ -- /foo.format/[...] (rewrite into next case) trunkToResource' ((StaticBranch sdir, StaticFormat format):xs) = trunkToResource' ((StaticBranch (sdir ++ "." ++ format), NoFormat):xs) trunkToResource' ((DynamicBranch ddir, StaticFormat format):xs) = trunkToResource' ((DynamicBranch (ddir ++ "." ++ format), NoFormat):xs) -- /foo/[...] trunkToResource' ((branch, NoFormat):xs) = case trunkToResource' xs of (xs', slash, res) -> (branch:xs', slash, res) -- /foo.format trunkToResource' [(branch, format)] = pathFormat branch format where pathFormat (StaticBranch sdir) (StaticFormat form) = ([StaticBranch (sdir ++ "." ++ form)], NoSlash, noFormat) -- foo.json pathFormat (StaticBranch sdir) DynamicFormat = ([DynamicBranch sdir], NoSlash, ResourceFormat DynamicFormat (Just branch)) -- foo.:json pathFormat (DynamicBranch {}) (StaticFormat {}) = ([branch], NoSlash, ResourceFormat format (Just branch)) -- :foo.json pathFormat (DynamicBranch {}) DynamicFormat = ([branch], NoSlash, ResourceFormat DynamicFormat (Just branch)) -- :foo.:json pathFormat _ NoFormat = ([branch], NoSlash, noFormat) -- foo or :foo pathFormat _ _ = error "Trailing path can't have a format" -- /foo.format/[...] trunkToResource' _ = error "Format only allowed at end of path" trunkAt :: String -> BranchPath trunkAt arg = either trunkError reverse $ Parse.parse parseTrunkAt "Distribution.Server.Resource.parseTrunkAt" arg where trunkError pe = error $ "Distribution.Server.Resource.trunkAt: Could not parse trunk literal " ++ show arg ++ ". Parsec error: " ++ show pe parseTrunkAt :: Parse.Parser [BranchComponent] parseTrunkAt = do components <- Parse.many (Parse.try parseComponent) Parse.optional (Parse.char '/') Parse.eof return components where parseComponent = do void $ Parse.char '/' fmap DynamicBranch (Parse.char ':' >> Parse.many1 (Parse.noneOf "/")) Parse.<|> fmap StaticBranch (Parse.many1 (Parse.noneOf "/")) parseFormatTrunkAt :: Parse.Parser [(BranchComponent, BranchFormat)] parseFormatTrunkAt = do components <- Parse.many (Parse.try parseComponent) rest <- Parse.option [] (Parse.char '/' >> return [(StaticBranch "", NoFormat)]) Parse.eof return (components ++ rest) where parseComponent :: Parse.Parser (BranchComponent, BranchFormat) parseComponent = do void $ Parse.char '/' Parse.choice $ map Parse.try [ Parse.char '.' >> Parse.many1 (Parse.char '.') >> ((Parse.lookAhead (Parse.char '/') >> return ()) Parse.<|> Parse.eof) >> return (TrailingBranch, NoFormat) , Parse.char ':' >> parseMaybeFormat DynamicBranch , do Parse.lookAhead (void $ Parse.satisfy (/=':')) Parse.choice $ map Parse.try [ parseMaybeFormat StaticBranch , fmap ((,) (StaticBranch "")) parseFormat , fmap (flip (,) NoFormat . StaticBranch) untilNext ] ] parseMaybeFormat :: (String -> BranchComponent) -> Parse.Parser (BranchComponent, BranchFormat) parseMaybeFormat control = do sdir <- Parse.many1 (Parse.noneOf "/.") format <- Parse.option NoFormat parseFormat return (control sdir, format) parseFormat :: Parse.Parser BranchFormat parseFormat = Parse.char '.' >> Parse.choice [ Parse.char ':' >> untilNext >> return DynamicFormat , fmap StaticFormat untilNext ] untilNext :: Parse.Parser String untilNext = Parse.many1 (Parse.noneOf "/") -- serveResource does all the path format and HTTP method preprocessing for a Resource -- -- For a small curl-based testing mini-suite of [Resource]: -- [res "/foo" ["json"], res "/foo/:bar.:format" ["html", "json"], res "/baz/test/.:format" ["html", "text", "json"], res "/package/:package/:tarball.tar.gz" ["tarball"], res "/a/:a/:b/" ["html", "json"], res "/mon/..." [""], res "/wiki/path.:format" [], res "/hi.:format" ["yaml", "blah"]] -- where res field formats = (resourceAt field) { resourceGet = map (\format -> (format, \_ -> return . toResponse . (++"\n") . ((show format++" - ")++) . show)) formats } serveResource :: [(Content, ServerErrorResponse)] -> Resource -> ServerResponse serveResource errRes (Resource _ rget rput rpost rdelete rformat rend _) = \dpath -> msum $ map (\func -> func dpath) $ methodPart ++ [optionPart] where optionPart = makeOptions $ concat [ met | ((_:_), met) <- zip methods methodsList] methodPart = [ serveResources met res | (res@(_:_), met) <- zip methods methodsList] methods = [rget, rput, rpost, rdelete] methodsList = [[GET, HEAD], [PUT], [POST], [DELETE]] makeOptions :: [Method] -> ServerResponse makeOptions methodList = \_ -> method OPTIONS >> nullDir >> do setHeaderM "Allow" (intercalate ", " . map show $ methodList) return $ toResponse () -- some of the dpath lookup calls can be replaced by pattern matching the head/replacing -- at the moment, duplicate entries tend to be inserted in dpath, because old ones are not replaced -- Procedure: -- > Guard against method -- > Extract format/whatnot -- > Potentially redirect to canonical slash form -- > Go from format/content-type to ServerResponse to serve-} serveResources :: [Method] -> [(Content, ServerResponse)] -> ServerResponse serveResources met res dpath = case rend of Trailing -> method met >> (remainingPathString >>= \str -> serveContent res (("..", str):dpath)) _ -> serveFormat res met dpath serveFormat :: [(Content, ServerResponse)] -> [Method] -> ServerResponse serveFormat res met = case rformat of ResourceFormat NoFormat Nothing -> \dpath -> method met >> nullDir >> serveContent res dpath ResourceFormat (StaticFormat format) Nothing -> \dpath -> path $ \format' -> method met >> nullDir >> do -- this branch shouldn't happen - /foo/.json would instead be stored as two static dirs guard (format' == ('.':format)) serveContent res dpath ResourceFormat (StaticFormat format) (Just (StaticBranch sdir)) -> \dpath -> method met >> nullDir >> -- likewise, foo.json should be stored as a single static dir if lookup sdir dpath == Just (sdir ++ "." ++ format) then mzero else serveContent res dpath ResourceFormat (StaticFormat format) (Just (DynamicBranch sdir)) -> \dpath -> method met >> nullDir >> case matchExt format =<< lookup sdir dpath of Just pname -> serveContent res ((sdir, pname):dpath) Nothing -> mzero ResourceFormat DynamicFormat Nothing -> \dpath -> msum [ method met >> nullDir >> serveContent res dpath , path $ \pname -> case pname of ('.':format) -> method met >> nullDir >> serveContent res (("format", format):dpath) _ -> mzero ] ResourceFormat DynamicFormat (Just (StaticBranch sdir)) -> \dpath -> method met >> nullDir >> case fmap extractExt (lookup sdir dpath) of Just (pname, format) | pname == sdir -> serveContent res (("format", format):dpath) _ -> mzero ResourceFormat DynamicFormat (Just (DynamicBranch sdir)) -> \dpath -> method met >> nullDir >> -- this is somewhat complicated. consider /pkg-0.1 and /pkg-0.1.html. If the format is optional, where to split? -- the solution is to manually check the available formats to see if something matches -- if this situation comes up in practice, try to require a trailing slash, e.g. /pkg-0.1/.html case fmap (\sd -> (,) sd $ extractExt sd) (lookup sdir dpath) of Just (full, (pname, format)) -> do let splitOption = serveContent res (("format", format):(sdir, pname):dpath) fullOption = serveContent res ((sdir, full):dpath) case guard (not $ null format) >> lookup format res of Nothing -> fullOption Just {} -> splitOption _ -> mzero -- some invalid combination _ -> \dpath -> method met >> nullDir >> serveContent res dpath serveContent :: [(Content, ServerResponse)] -> ServerResponse serveContent res dpath = do -- there should be no remaining path segments at this point, now check page redirection met <- fmap rqMethod askRq -- we don't check if the page exists before redirecting! -- just send them to the canonical place the document may or may not be (if met == HEAD || met == GET then redirCanonicalSlash dpath else id) $ do -- "Find " ++ show (lookup "format" dpath) ++ " in " ++ show (map fst res) case lookup "format" dpath of Just format@(_:_) -> case lookup format res of -- return a specific format if it is found Just answer -> handleErrors (Just format) $ answer dpath Nothing -> mzero -- return 404 if the specific format is not found -- return default response when format is empty or non-existent _ -> do (format,answer) <- negotiateContent (head res) res handleErrors (Just format) $ answer dpath handleErrors format = handleErrorResponse (serveErrorResponse errRes format) redirCanonicalSlash :: DynamicPath -> ServerPartE Response -> ServerPartE Response redirCanonicalSlash dpath trueRes = case rformat of ResourceFormat format Nothing | format /= NoFormat -> case lookup "format" dpath of Just {} -> requireNoSlash `mplus` trueRes Nothing -> requireSlash `mplus` trueRes _ -> case rend of Slash -> requireSlash `mplus` trueRes NoSlash -> requireNoSlash `mplus` trueRes Trailing -> mplus (nullDir >> requireSlash) trueRes requireSlash = do theUri <- fmap rqUri askRq guard $ last theUri /= '/' movedPermanently (theUri ++ "/") (toResponse ()) requireNoSlash = do theUri <- fmap rqUri askRq guard $ last theUri == '/' movedPermanently (reverse . dropWhile (=='/') . reverse $ theUri) (toResponse ()) -- matchExt and extractExt could also use manual string-chomping recursion if wanted matchExt format pname = let fsize = length format (pname', format') = splitAt (length pname - fsize - 1) pname in if '.':format == format' then Just pname' else Nothing extractExt pname = case findIndices (=='.') pname of [] -> (pname, "") xs -> case splitAt (last xs) pname of (pname', _:format) -> (pname', format) _ -> (pname, "") -- this shouldn't happen resourceMethods :: Resource -> [Method] resourceMethods (Resource _ rget rput rpost rdelete _ _ _) = [ met | ((_:_), met) <- zip methods methodsList] where methods = [rget, rput, rpost, rdelete] methodsList = [GET, PUT, POST, DELETE] serveErrorResponse :: [(Content, ServerErrorResponse)] -> Maybe Content -> ServerErrorResponse serveErrorResponse errRes mformat err = do -- So our strategy is to give priority to a content type requested by -- the client, then secondly any format implied by the requested url -- e.g. requesting a .html file, or html being default for the resource -- and finally just fall through to using text/plain (_, errHandler) <- negotiateContent ("", defHandler) errRes errHandler err where defHandler = fromMaybe throwError $ do format <- mformat lookup format errRes negotiateContent :: (FilterMonad Response m, ServerMonad m) => (Content, a) -> [(Content, a)] -> m (Content, a) negotiateContent def available = do when (length available > 1) $ setHeaderM "Vary" "Accept" maccept <- getHeaderM "Accept" case maccept of Nothing -> return def Just accept -> return $ fromMaybe def $ listToMaybe $ catMaybes [ simpleContentTypeMapping ct >>= \f -> find (\x -> fst x == f) available | let acceptable = parseContentAccept (BS.unpack accept) , ct <- acceptable ] where -- This is rather a non-extensible hack simpleContentTypeMapping ContentType {ctType, ctSubtype, ctParameters = []} = case (ctType, ctSubtype) of ("text", "html") -> Just "html" ("text", "plain") -> Just "txt" ("application", "json") -> Just "json" _ -> Nothing simpleContentTypeMapping _ = Nothing ---------------------------------------------------------------------------- data ServerTree a = ServerTree { nodeResponse :: Maybe a, nodeForest :: Map BranchComponent (ServerTree a) } deriving (Show) instance Functor ServerTree where fmap func (ServerTree value forest) = ServerTree (fmap func value) (Map.map (fmap func) forest) drawServerTree :: ServerTree a -> Maybe (a -> String) -> String drawServerTree tree func = Tree.drawTree (transformTree tree Nothing) where transformTree (ServerTree res for) mlink = Tree.Node (drawLink mlink res) (map transformForest $ Map.toList for) drawLink mlink res = maybe "" ((++": ") . show) mlink ++ maybe "(nothing)" (fromMaybe (const "node") func) res transformForest (link, tree') = transformTree tree' (Just link) serverTreeEmpty :: ServerTree a serverTreeEmpty = ServerTree Nothing Map.empty -- essentially a ReaderT DynamicPath ServerPart Response -- this always renders parent URIs, but usually we guard against remaining path segments, so it's fine renderServerTree :: DynamicPath -> ServerTree ServerResponse -> ServerPartE Response renderServerTree dpath (ServerTree func forest) = msum $ maybeToList (fmap (\fun -> fun dpath) func) ++ map (uncurry renderBranch) (Map.toList forest) where renderBranch :: BranchComponent -> ServerTree ServerResponse -> ServerPartE Response renderBranch (StaticBranch sdir) tree = dir sdir $ renderServerTree dpath tree renderBranch (DynamicBranch sdir) tree | (ddir, sformat@('.':_)) <- break (=='.') sdir = path $ \pname -> do guard (sformat `isSuffixOf` pname) let pname' = take (length pname - length sformat) pname renderServerTree ((ddir, pname'):dpath) tree | otherwise = path $ \pname -> renderServerTree ((sdir, pname):dpath) tree renderBranch TrailingBranch tree = renderServerTree dpath tree reinsert :: Monoid a => BranchComponent -> ServerTree a -> Map BranchComponent (ServerTree a) -> Map BranchComponent (ServerTree a) -- combine will only be called if branchMap already contains the key reinsert key newTree branchMap = Map.insertWith combine key newTree branchMap combine :: Monoid a => ServerTree a -> ServerTree a -> ServerTree a combine (ServerTree newResponse newForest) (ServerTree oldResponse oldForest) = -- replace old resource with new resource, combine old and new responses ServerTree (mappend newResponse oldResponse) (Map.foldrWithKey reinsert oldForest newForest) addServerNode :: Monoid a => BranchPath -> a -> ServerTree a -> ServerTree a addServerNode trunk response tree = treeFold trunk (ServerTree (Just response) Map.empty) tree --this function takes a list whose head is the resource and traverses leftwards in the URI --this is due to the original design of specifying URI branches: if the resources are --themselves encoded in the branch, then subresources should share the same parent --resource, sharing list tails. -- --This version is greatly simplified compared to what was previously here. treeFold :: Monoid a => BranchPath -> ServerTree a -> ServerTree a -> ServerTree a treeFold [] newChild topLevel = combine newChild topLevel treeFold (sdir:otherTree) newChild topLevel = treeFold otherTree (ServerTree Nothing $ Map.singleton sdir newChild) topLevel
edsko/hackage-server
Distribution/Server/Framework/Resource.hs
bsd-3-clause
32,081
0
24
7,258
7,417
3,928
3,489
382
25
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 -} {-# LANGUAGE CPP, DeriveDataTypeable #-} -- | -- #name_types# -- GHC uses several kinds of name internally: -- -- * 'OccName.OccName': see "OccName#name_types" -- -- * 'RdrName.RdrName' is the type of names that come directly from the parser. They -- have not yet had their scoping and binding resolved by the renamer and can be -- thought of to a first approximation as an 'OccName.OccName' with an optional module -- qualifier -- -- * 'Name.Name': see "Name#name_types" -- -- * 'Id.Id': see "Id#name_types" -- -- * 'Var.Var': see "Var#name_types" module RdrName ( -- * The main type RdrName(..), -- Constructors exported only to BinIface -- ** Construction mkRdrUnqual, mkRdrQual, mkUnqual, mkVarUnqual, mkQual, mkOrig, nameRdrName, getRdrName, -- ** Destruction rdrNameOcc, rdrNameSpace, demoteRdrName, isRdrDataCon, isRdrTyVar, isRdrTc, isQual, isQual_maybe, isUnqual, isOrig, isOrig_maybe, isExact, isExact_maybe, isSrcRdrName, -- * Local mapping of 'RdrName' to 'Name.Name' LocalRdrEnv, emptyLocalRdrEnv, extendLocalRdrEnv, extendLocalRdrEnvList, lookupLocalRdrEnv, lookupLocalRdrOcc, elemLocalRdrEnv, inLocalRdrEnvScope, localRdrEnvElts, delLocalRdrEnvList, -- * Global mapping of 'RdrName' to 'GlobalRdrElt's GlobalRdrEnv, emptyGlobalRdrEnv, mkGlobalRdrEnv, plusGlobalRdrEnv, lookupGlobalRdrEnv, extendGlobalRdrEnv, greOccName, shadowNames, pprGlobalRdrEnv, globalRdrEnvElts, lookupGRE_RdrName, lookupGRE_Name, lookupGRE_Field_Name, getGRE_NameQualifier_maybes, transformGREs, pickGREs, -- * GlobalRdrElts gresFromAvails, gresFromAvail, localGREsFromAvail, availFromGRE, greUsedRdrName, greRdrNames, greSrcSpan, greQualModName, -- ** Global 'RdrName' mapping elements: 'GlobalRdrElt', 'Provenance', 'ImportSpec' GlobalRdrElt(..), isLocalGRE, isRecFldGRE, greLabel, unQualOK, qualSpecOK, unQualSpecOK, pprNameProvenance, Parent(..), ImportSpec(..), ImpDeclSpec(..), ImpItemSpec(..), importSpecLoc, importSpecModule, isExplicitItem ) where #include "HsVersions.h" import Module import Name import Avail import NameSet import Maybes import SrcLoc import FastString import FieldLabel import Outputable import Unique import Util import StaticFlags( opt_PprStyle_Debug ) import Data.Data {- ************************************************************************ * * \subsection{The main data type} * * ************************************************************************ -} -- | Do not use the data constructors of RdrName directly: prefer the family -- of functions that creates them, such as 'mkRdrUnqual' -- -- - Note: A Located RdrName will only have API Annotations if it is a -- compound one, -- e.g. -- -- > `bar` -- > ( ~ ) -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnType', -- 'ApiAnnotation.AnnOpen' @'('@ or @'['@ or @'[:'@, -- 'ApiAnnotation.AnnClose' @')'@ or @']'@ or @':]'@,, -- 'ApiAnnotation.AnnBackquote' @'`'@, -- 'ApiAnnotation.AnnVal','ApiAnnotation.AnnTildehsh', -- 'ApiAnnotation.AnnTilde', -- For details on above see note [Api annotations] in ApiAnnotation data RdrName = Unqual OccName -- ^ Used for ordinary, unqualified occurrences, e.g. @x@, @y@ or @Foo@. -- Create such a 'RdrName' with 'mkRdrUnqual' | Qual ModuleName OccName -- ^ A qualified name written by the user in -- /source/ code. The module isn't necessarily -- the module where the thing is defined; -- just the one from which it is imported. -- Examples are @Bar.x@, @Bar.y@ or @Bar.Foo@. -- Create such a 'RdrName' with 'mkRdrQual' | Orig Module OccName -- ^ An original name; the module is the /defining/ module. -- This is used when GHC generates code that will be fed -- into the renamer (e.g. from deriving clauses), but where -- we want to say \"Use Prelude.map dammit\". One of these -- can be created with 'mkOrig' | Exact Name -- ^ We know exactly the 'Name'. This is used: -- -- (1) When the parser parses built-in syntax like @[]@ -- and @(,)@, but wants a 'RdrName' from it -- -- (2) By Template Haskell, when TH has generated a unique name -- -- Such a 'RdrName' can be created by using 'getRdrName' on a 'Name' deriving (Data, Typeable) {- ************************************************************************ * * \subsection{Simple functions} * * ************************************************************************ -} instance HasOccName RdrName where occName = rdrNameOcc rdrNameOcc :: RdrName -> OccName rdrNameOcc (Qual _ occ) = occ rdrNameOcc (Unqual occ) = occ rdrNameOcc (Orig _ occ) = occ rdrNameOcc (Exact name) = nameOccName name rdrNameSpace :: RdrName -> NameSpace rdrNameSpace = occNameSpace . rdrNameOcc -- demoteRdrName lowers the NameSpace of RdrName. -- see Note [Demotion] in OccName demoteRdrName :: RdrName -> Maybe RdrName demoteRdrName (Unqual occ) = fmap Unqual (demoteOccName occ) demoteRdrName (Qual m occ) = fmap (Qual m) (demoteOccName occ) demoteRdrName (Orig _ _) = panic "demoteRdrName" demoteRdrName (Exact _) = panic "demoteRdrName" -- These two are the basic constructors mkRdrUnqual :: OccName -> RdrName mkRdrUnqual occ = Unqual occ mkRdrQual :: ModuleName -> OccName -> RdrName mkRdrQual mod occ = Qual mod occ mkOrig :: Module -> OccName -> RdrName mkOrig mod occ = Orig mod occ --------------- -- These two are used when parsing source files -- They do encode the module and occurrence names mkUnqual :: NameSpace -> FastString -> RdrName mkUnqual sp n = Unqual (mkOccNameFS sp n) mkVarUnqual :: FastString -> RdrName mkVarUnqual n = Unqual (mkVarOccFS n) -- | Make a qualified 'RdrName' in the given namespace and where the 'ModuleName' and -- the 'OccName' are taken from the first and second elements of the tuple respectively mkQual :: NameSpace -> (FastString, FastString) -> RdrName mkQual sp (m, n) = Qual (mkModuleNameFS m) (mkOccNameFS sp n) getRdrName :: NamedThing thing => thing -> RdrName getRdrName name = nameRdrName (getName name) nameRdrName :: Name -> RdrName nameRdrName name = Exact name -- Keep the Name even for Internal names, so that the -- unique is still there for debug printing, particularly -- of Types (which are converted to IfaceTypes before printing) nukeExact :: Name -> RdrName nukeExact n | isExternalName n = Orig (nameModule n) (nameOccName n) | otherwise = Unqual (nameOccName n) isRdrDataCon :: RdrName -> Bool isRdrTyVar :: RdrName -> Bool isRdrTc :: RdrName -> Bool isRdrDataCon rn = isDataOcc (rdrNameOcc rn) isRdrTyVar rn = isTvOcc (rdrNameOcc rn) isRdrTc rn = isTcOcc (rdrNameOcc rn) isSrcRdrName :: RdrName -> Bool isSrcRdrName (Unqual _) = True isSrcRdrName (Qual _ _) = True isSrcRdrName _ = False isUnqual :: RdrName -> Bool isUnqual (Unqual _) = True isUnqual _ = False isQual :: RdrName -> Bool isQual (Qual _ _) = True isQual _ = False isQual_maybe :: RdrName -> Maybe (ModuleName, OccName) isQual_maybe (Qual m n) = Just (m,n) isQual_maybe _ = Nothing isOrig :: RdrName -> Bool isOrig (Orig _ _) = True isOrig _ = False isOrig_maybe :: RdrName -> Maybe (Module, OccName) isOrig_maybe (Orig m n) = Just (m,n) isOrig_maybe _ = Nothing isExact :: RdrName -> Bool isExact (Exact _) = True isExact _ = False isExact_maybe :: RdrName -> Maybe Name isExact_maybe (Exact n) = Just n isExact_maybe _ = Nothing {- ************************************************************************ * * \subsection{Instances} * * ************************************************************************ -} instance Outputable RdrName where ppr (Exact name) = ppr name ppr (Unqual occ) = ppr occ ppr (Qual mod occ) = ppr mod <> dot <> ppr occ ppr (Orig mod occ) = getPprStyle (\sty -> pprModulePrefix sty mod occ <> ppr occ) instance OutputableBndr RdrName where pprBndr _ n | isTvOcc (rdrNameOcc n) = char '@' <+> ppr n | otherwise = ppr n pprInfixOcc rdr = pprInfixVar (isSymOcc (rdrNameOcc rdr)) (ppr rdr) pprPrefixOcc rdr | Just name <- isExact_maybe rdr = pprPrefixName name -- pprPrefixName has some special cases, so -- we delegate to them rather than reproduce them | otherwise = pprPrefixVar (isSymOcc (rdrNameOcc rdr)) (ppr rdr) instance Eq RdrName where (Exact n1) == (Exact n2) = n1==n2 -- Convert exact to orig (Exact n1) == r2@(Orig _ _) = nukeExact n1 == r2 r1@(Orig _ _) == (Exact n2) = r1 == nukeExact n2 (Orig m1 o1) == (Orig m2 o2) = m1==m2 && o1==o2 (Qual m1 o1) == (Qual m2 o2) = m1==m2 && o1==o2 (Unqual o1) == (Unqual o2) = o1==o2 _ == _ = False instance Ord RdrName where a <= b = case (a `compare` b) of { LT -> True; EQ -> True; GT -> False } a < b = case (a `compare` b) of { LT -> True; EQ -> False; GT -> False } a >= b = case (a `compare` b) of { LT -> False; EQ -> True; GT -> True } a > b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True } -- Exact < Unqual < Qual < Orig -- [Note: Apr 2004] We used to use nukeExact to convert Exact to Orig -- before comparing so that Prelude.map == the exact Prelude.map, but -- that meant that we reported duplicates when renaming bindings -- generated by Template Haskell; e.g -- do { n1 <- newName "foo"; n2 <- newName "foo"; -- <decl involving n1,n2> } -- I think we can do without this conversion compare (Exact n1) (Exact n2) = n1 `compare` n2 compare (Exact _) _ = LT compare (Unqual _) (Exact _) = GT compare (Unqual o1) (Unqual o2) = o1 `compare` o2 compare (Unqual _) _ = LT compare (Qual _ _) (Exact _) = GT compare (Qual _ _) (Unqual _) = GT compare (Qual m1 o1) (Qual m2 o2) = (o1 `compare` o2) `thenCmp` (m1 `compare` m2) compare (Qual _ _) (Orig _ _) = LT compare (Orig m1 o1) (Orig m2 o2) = (o1 `compare` o2) `thenCmp` (m1 `compare` m2) compare (Orig _ _) _ = GT {- ************************************************************************ * * LocalRdrEnv * * ************************************************************************ -} -- | This environment is used to store local bindings (@let@, @where@, lambda, @case@). -- It is keyed by OccName, because we never use it for qualified names -- We keep the current mapping, *and* the set of all Names in scope -- Reason: see Note [Splicing Exact Names] in RnEnv data LocalRdrEnv = LRE { lre_env :: OccEnv Name , lre_in_scope :: NameSet } instance Outputable LocalRdrEnv where ppr (LRE {lre_env = env, lre_in_scope = ns}) = hang (ptext (sLit "LocalRdrEnv {")) 2 (vcat [ ptext (sLit "env =") <+> pprOccEnv ppr_elt env , ptext (sLit "in_scope =") <+> braces (pprWithCommas ppr (nameSetElems ns)) ] <+> char '}') where ppr_elt name = parens (ppr (getUnique (nameOccName name))) <+> ppr name -- So we can see if the keys line up correctly emptyLocalRdrEnv :: LocalRdrEnv emptyLocalRdrEnv = LRE { lre_env = emptyOccEnv, lre_in_scope = emptyNameSet } extendLocalRdrEnv :: LocalRdrEnv -> Name -> LocalRdrEnv -- The Name should be a non-top-level thing extendLocalRdrEnv (LRE { lre_env = env, lre_in_scope = ns }) name = WARN( isExternalName name, ppr name ) LRE { lre_env = extendOccEnv env (nameOccName name) name , lre_in_scope = extendNameSet ns name } extendLocalRdrEnvList :: LocalRdrEnv -> [Name] -> LocalRdrEnv extendLocalRdrEnvList (LRE { lre_env = env, lre_in_scope = ns }) names = WARN( any isExternalName names, ppr names ) LRE { lre_env = extendOccEnvList env [(nameOccName n, n) | n <- names] , lre_in_scope = extendNameSetList ns names } lookupLocalRdrEnv :: LocalRdrEnv -> RdrName -> Maybe Name lookupLocalRdrEnv (LRE { lre_env = env }) (Unqual occ) = lookupOccEnv env occ lookupLocalRdrEnv _ _ = Nothing lookupLocalRdrOcc :: LocalRdrEnv -> OccName -> Maybe Name lookupLocalRdrOcc (LRE { lre_env = env }) occ = lookupOccEnv env occ elemLocalRdrEnv :: RdrName -> LocalRdrEnv -> Bool elemLocalRdrEnv rdr_name (LRE { lre_env = env, lre_in_scope = ns }) = case rdr_name of Unqual occ -> occ `elemOccEnv` env Exact name -> name `elemNameSet` ns -- See Note [Local bindings with Exact Names] Qual {} -> False Orig {} -> False localRdrEnvElts :: LocalRdrEnv -> [Name] localRdrEnvElts (LRE { lre_env = env }) = occEnvElts env inLocalRdrEnvScope :: Name -> LocalRdrEnv -> Bool -- This is the point of the NameSet inLocalRdrEnvScope name (LRE { lre_in_scope = ns }) = name `elemNameSet` ns delLocalRdrEnvList :: LocalRdrEnv -> [OccName] -> LocalRdrEnv delLocalRdrEnvList (LRE { lre_env = env, lre_in_scope = ns }) occs = LRE { lre_env = delListFromOccEnv env occs , lre_in_scope = ns } {- Note [Local bindings with Exact Names] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ With Template Haskell we can make local bindings that have Exact Names. Computing shadowing etc may use elemLocalRdrEnv (at least it certainly does so in RnTpes.bindHsTyVars), so for an Exact Name we must consult the in-scope-name-set. ************************************************************************ * * GlobalRdrEnv * * ************************************************************************ -} type GlobalRdrEnv = OccEnv [GlobalRdrElt] -- ^ Keyed by 'OccName'; when looking up a qualified name -- we look up the 'OccName' part, and then check the 'Provenance' -- to see if the appropriate qualification is valid. This -- saves routinely doubling the size of the env by adding both -- qualified and unqualified names to the domain. -- -- The list in the codomain is required because there may be name clashes -- These only get reported on lookup, not on construction -- -- INVARIANT 1: All the members of the list have distinct -- 'gre_name' fields; that is, no duplicate Names -- -- INVARIANT 2: Imported provenance => Name is an ExternalName -- However LocalDefs can have an InternalName. This -- happens only when type-checking a [d| ... |] Template -- Haskell quotation; see this note in RnNames -- Note [Top-level Names in Template Haskell decl quotes] -- | An element of the 'GlobalRdrEnv' data GlobalRdrElt = GRE { gre_name :: Name , gre_par :: Parent , gre_lcl :: Bool -- ^ True <=> the thing was defined locally , gre_imp :: [ImportSpec] -- ^ In scope through these imports } -- INVARIANT: either gre_lcl = True or gre_imp is non-empty -- See Note [GlobalRdrElt provenance] -- | The children of a Name are the things that are abbreviated by the ".." -- notation in export lists. See Note [Parents] data Parent = NoParent | ParentIs { par_is :: Name } | FldParent { par_is :: Name, par_lbl :: Maybe FieldLabelString } -- ^ See Note [Parents for record fields] deriving (Eq) instance Outputable Parent where ppr NoParent = empty ppr (ParentIs n) = ptext (sLit "parent:") <> ppr n ppr (FldParent n f) = ptext (sLit "fldparent:") <> ppr n <> colon <> ppr f plusParent :: Parent -> Parent -> Parent -- See Note [Combining parents] plusParent p1@(ParentIs _) p2 = hasParent p1 p2 plusParent p1@(FldParent _ _) p2 = hasParent p1 p2 plusParent p1 p2@(ParentIs _) = hasParent p2 p1 plusParent p1 p2@(FldParent _ _) = hasParent p2 p1 plusParent NoParent NoParent = NoParent hasParent :: Parent -> Parent -> Parent #ifdef DEBUG hasParent p NoParent = p hasParent p p' | p /= p' = pprPanic "hasParent" (ppr p <+> ppr p') -- Parents should agree #endif hasParent p _ = p {- Note [GlobalRdrElt provenance] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The gre_lcl and gre_imp fields of a GlobalRdrElt describe its "provenance", i.e. how the Name came to be in scope. It can be in scope two ways: - gre_lcl = True: it is bound in this module - gre_imp: a list of all the imports that brought it into scope It's an INVARIANT that you have one or the other; that is, either gre_lcl is True, or gre_imp is non-empty. It is just possible to have *both* if there is a module loop: a Name is defined locally in A, and also brought into scope by importing a module that SOURCE-imported A. Exapmle (Trac #7672): A.hs-boot module A where data T B.hs module B(Decl.T) where import {-# SOURCE #-} qualified A as Decl A.hs module A where import qualified B data T = Z | S B.T In A.hs, 'T' is locally bound, *and* imported as B.T. Note [Parents] ~~~~~~~~~~~~~~~~~ Parent Children ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ data T Data constructors Record-field ids data family T Data constructors and record-field ids of all visible data instances of T class C Class operations Associated type constructors Note [Parents for record fields] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For record fields, in addition to the Name of the type constructor (stored in par_is), we use FldParent to store the field label. This extra information is used for identifying overloaded record fields during renaming. In a definition arising from a normal module (without -XDuplicateRecordFields), par_lbl will be Nothing, meaning that the field's label is the same as the OccName of the selector's Name. The GlobalRdrEnv will contain an entry like this: "x" |-> GRE x (FldParent T Nothing) LocalDef When -XDuplicateRecordFields is enabled for the module that contains T, the selector's Name will be mangled (see comments in FieldLabel). Thus we store the actual field label in par_lbl, and the GlobalRdrEnv entry looks like this: "x" |-> GRE $sel:x:MkT (FldParent T (Just "x")) LocalDef Note that the OccName used when adding a GRE to the environment (greOccName) now depends on the parent field: for FldParent it is the field label, if present, rather than the selector name. Note [Combining parents] ~~~~~~~~~~~~~~~~~~~~~~~~ With an associated type we might have module M where class C a where data T a op :: T a -> a instance C Int where data T Int = TInt instance C Bool where data T Bool = TBool Then: C is the parent of T T is the parent of TInt and TBool So: in an export list C(..) is short for C( op, T ) T(..) is short for T( TInt, TBool ) Module M exports everything, so its exports will be AvailTC C [C,T,op] AvailTC T [T,TInt,TBool] On import we convert to GlobalRdrElt and then combine those. For T that will mean we have one GRE with Parent C one GRE with NoParent That's why plusParent picks the "best" case. -} -- | make a 'GlobalRdrEnv' where all the elements point to the same -- Provenance (useful for "hiding" imports, or imports with no details). gresFromAvails :: Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt] -- prov = Nothing => locally bound -- Just spec => imported as described by spec gresFromAvails prov avails = concatMap (gresFromAvail (const prov)) avails localGREsFromAvail :: AvailInfo -> [GlobalRdrElt] -- Turn an Avail into a list of LocalDef GlobalRdrElts localGREsFromAvail = gresFromAvail (const Nothing) gresFromAvail :: (Name -> Maybe ImportSpec) -> AvailInfo -> [GlobalRdrElt] gresFromAvail prov_fn avail = map mk_gre (availNonFldNames avail) ++ map mk_fld_gre (availFlds avail) where mk_gre n = case prov_fn n of -- Nothing => bound locally -- Just is => imported from 'is' Nothing -> GRE { gre_name = n, gre_par = mkParent n avail , gre_lcl = True, gre_imp = [] } Just is -> GRE { gre_name = n, gre_par = mkParent n avail , gre_lcl = False, gre_imp = [is] } mk_fld_gre (FieldLabel lbl is_overloaded n) = case prov_fn n of -- Nothing => bound locally -- Just is => imported from 'is' Nothing -> GRE { gre_name = n, gre_par = FldParent (availName avail) mb_lbl , gre_lcl = True, gre_imp = [] } Just is -> GRE { gre_name = n, gre_par = FldParent (availName avail) mb_lbl , gre_lcl = False, gre_imp = [is] } where mb_lbl | is_overloaded = Just lbl | otherwise = Nothing greQualModName :: GlobalRdrElt -> ModuleName -- Get a suitable module qualifier for the GRE -- (used in mkPrintUnqualified) -- Prerecondition: the gre_name is always External greQualModName gre@(GRE { gre_name = name, gre_lcl = lcl, gre_imp = iss }) | lcl, Just mod <- nameModule_maybe name = moduleName mod | (is:_) <- iss = is_as (is_decl is) | otherwise = pprPanic "greQualModName" (ppr gre) greUsedRdrName :: GlobalRdrElt -> RdrName -- For imported things, return a RdrName to add to the -- used-RdrName set, which is used to generate -- unused-import-decl warnings -- Return an Unqual if possible, otherwise any Qual greUsedRdrName gre@GRE{ gre_name = name, gre_lcl = lcl, gre_imp = iss } | lcl = Unqual occ | not (all (is_qual . is_decl) iss) = Unqual occ | (is:_) <- iss = Qual (is_as (is_decl is)) occ | otherwise = pprPanic "greRdrName" (ppr name) where occ = greOccName gre greRdrNames :: GlobalRdrElt -> [RdrName] greRdrNames GRE{ gre_name = name, gre_lcl = lcl, gre_imp = iss } = (if lcl then [unqual] else []) ++ concatMap do_spec (map is_decl iss) where occ = nameOccName name unqual = Unqual occ do_spec decl_spec | is_qual decl_spec = [qual] | otherwise = [unqual,qual] where qual = Qual (is_as decl_spec) occ -- the SrcSpan that pprNameProvenance prints out depends on whether -- the Name is defined locally or not: for a local definition the -- definition site is used, otherwise the location of the import -- declaration. We want to sort the export locations in -- exportClashErr by this SrcSpan, we need to extract it: greSrcSpan :: GlobalRdrElt -> SrcSpan greSrcSpan gre@(GRE { gre_name = name, gre_lcl = lcl, gre_imp = iss } ) | lcl = nameSrcSpan name | (is:_) <- iss = is_dloc (is_decl is) | otherwise = pprPanic "greSrcSpan" (ppr gre) mkParent :: Name -> AvailInfo -> Parent mkParent _ (Avail _) = NoParent mkParent n (AvailTC m _ _) | n == m = NoParent | otherwise = ParentIs m availFromGRE :: GlobalRdrElt -> AvailInfo availFromGRE gre = case gre_par gre of ParentIs p -> AvailTC p [me] [] NoParent | isTyConName me -> AvailTC me [me] [] | otherwise -> Avail me FldParent p Nothing -> AvailTC p [] [FieldLabel (occNameFS $ nameOccName me) False me] FldParent p (Just lbl) -> AvailTC p [] [FieldLabel lbl True me] where me = gre_name gre emptyGlobalRdrEnv :: GlobalRdrEnv emptyGlobalRdrEnv = emptyOccEnv globalRdrEnvElts :: GlobalRdrEnv -> [GlobalRdrElt] globalRdrEnvElts env = foldOccEnv (++) [] env instance Outputable GlobalRdrElt where ppr gre = hang (ppr (gre_name gre) <+> ppr (gre_par gre)) 2 (pprNameProvenance gre) pprGlobalRdrEnv :: Bool -> GlobalRdrEnv -> SDoc pprGlobalRdrEnv locals_only env = vcat [ ptext (sLit "GlobalRdrEnv") <+> ppWhen locals_only (ptext (sLit "(locals only)")) <+> lbrace , nest 2 (vcat [ pp (remove_locals gre_list) | gre_list <- occEnvElts env ] <+> rbrace) ] where remove_locals gres | locals_only = filter isLocalGRE gres | otherwise = gres pp [] = empty pp gres = hang (ppr occ <+> parens (ptext (sLit "unique") <+> ppr (getUnique occ)) <> colon) 2 (vcat (map ppr gres)) where occ = nameOccName (gre_name (head gres)) lookupGlobalRdrEnv :: GlobalRdrEnv -> OccName -> [GlobalRdrElt] lookupGlobalRdrEnv env occ_name = case lookupOccEnv env occ_name of Nothing -> [] Just gres -> gres greOccName :: GlobalRdrElt -> OccName greOccName (GRE{gre_par = FldParent{par_lbl = Just lbl}}) = mkVarOccFS lbl greOccName gre = nameOccName (gre_name gre) lookupGRE_RdrName :: RdrName -> GlobalRdrEnv -> [GlobalRdrElt] lookupGRE_RdrName rdr_name env = case lookupOccEnv env (rdrNameOcc rdr_name) of Nothing -> [] Just gres -> pickGREs rdr_name gres lookupGRE_Name :: GlobalRdrEnv -> Name -> [GlobalRdrElt] lookupGRE_Name env name = [ gre | gre <- lookupGlobalRdrEnv env (nameOccName name), gre_name gre == name ] lookupGRE_Field_Name :: GlobalRdrEnv -> Name -> FastString -> [GlobalRdrElt] -- Used when looking up record fields, where the selector name and -- field label are different: the GlobalRdrEnv is keyed on the label lookupGRE_Field_Name env sel_name lbl = [ gre | gre <- lookupGlobalRdrEnv env (mkVarOccFS lbl), gre_name gre == sel_name ] getGRE_NameQualifier_maybes :: GlobalRdrEnv -> Name -> [Maybe [ModuleName]] -- Returns all the qualifiers by which 'x' is in scope -- Nothing means "the unqualified version is in scope" -- [] means the thing is not in scope at all getGRE_NameQualifier_maybes env = map (qualifier_maybe) . lookupGRE_Name env where qualifier_maybe (GRE { gre_lcl = lcl, gre_imp = iss }) | lcl = Nothing | otherwise = Just $ map (is_as . is_decl) iss isLocalGRE :: GlobalRdrElt -> Bool isLocalGRE (GRE {gre_lcl = lcl }) = lcl isRecFldGRE :: GlobalRdrElt -> Bool isRecFldGRE (GRE {gre_par = FldParent{}}) = True isRecFldGRE _ = False -- Returns the field label of this GRE, if it has one greLabel :: GlobalRdrElt -> Maybe FieldLabelString greLabel (GRE{gre_par = FldParent{par_lbl = Just lbl}}) = Just lbl greLabel (GRE{gre_name = n, gre_par = FldParent{}}) = Just (occNameFS (nameOccName n)) greLabel _ = Nothing unQualOK :: GlobalRdrElt -> Bool -- ^ Test if an unqualifed version of this thing would be in scope unQualOK (GRE {gre_lcl = lcl, gre_imp = iss }) | lcl = True | otherwise = any unQualSpecOK iss pickGREs :: RdrName -> [GlobalRdrElt] -> [GlobalRdrElt] -- ^ Take a list of GREs which have the right OccName -- Pick those GREs that are suitable for this RdrName -- And for those, keep only only the Provenances that are suitable -- Only used for Qual and Unqual, not Orig or Exact -- -- Consider: -- -- @ -- module A ( f ) where -- import qualified Foo( f ) -- import Baz( f ) -- f = undefined -- @ -- -- Let's suppose that @Foo.f@ and @Baz.f@ are the same entity really. -- The export of @f@ is ambiguous because it's in scope from the local def -- and the import. The lookup of @Unqual f@ should return a GRE for -- the locally-defined @f@, and a GRE for the imported @f@, with a /single/ -- provenance, namely the one for @Baz(f)@, so that the "ambiguous occurrence" -- message mentions the correct candidates pickGREs rdr_name gres = ASSERT2( isSrcRdrName rdr_name, ppr rdr_name ) mapMaybe pick gres where rdr_is_unqual = isUnqual rdr_name rdr_is_qual = isQual_maybe rdr_name pick :: GlobalRdrElt -> Maybe GlobalRdrElt pick gre@(GRE { gre_name = n, gre_lcl = lcl, gre_imp = iss }) | not lcl' && null iss' = Nothing | otherwise = Just (gre { gre_lcl = lcl', gre_imp = iss' }) where lcl' | not lcl = False | rdr_is_unqual = True | Just (mod,_) <- rdr_is_qual -- Qualified name , Just n_mod <- nameModule_maybe n -- Binder is External = mod == moduleName n_mod | otherwise = False iss' | rdr_is_unqual = filter (not . is_qual . is_decl) iss | Just (mod,_) <- rdr_is_qual = filter ((== mod) . is_as . is_decl) iss | otherwise = [] -- Building GlobalRdrEnvs plusGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrEnv -> GlobalRdrEnv plusGlobalRdrEnv env1 env2 = plusOccEnv_C (foldr insertGRE) env1 env2 mkGlobalRdrEnv :: [GlobalRdrElt] -> GlobalRdrEnv mkGlobalRdrEnv gres = foldr add emptyGlobalRdrEnv gres where add gre env = extendOccEnv_Acc insertGRE singleton env (greOccName gre) gre insertGRE :: GlobalRdrElt -> [GlobalRdrElt] -> [GlobalRdrElt] insertGRE new_g [] = [new_g] insertGRE new_g (old_g : old_gs) | gre_name new_g == gre_name old_g = new_g `plusGRE` old_g : old_gs | otherwise = old_g : insertGRE new_g old_gs plusGRE :: GlobalRdrElt -> GlobalRdrElt -> GlobalRdrElt -- Used when the gre_name fields match plusGRE g1 g2 = GRE { gre_name = gre_name g1 , gre_lcl = gre_lcl g1 || gre_lcl g2 , gre_imp = gre_imp g1 ++ gre_imp g2 , gre_par = gre_par g1 `plusParent` gre_par g2 } transformGREs :: (GlobalRdrElt -> GlobalRdrElt) -> [OccName] -> GlobalRdrEnv -> GlobalRdrEnv -- ^ Apply a transformation function to the GREs for these OccNames transformGREs trans_gre occs rdr_env = foldr trans rdr_env occs where trans occ env = case lookupOccEnv env occ of Just gres -> extendOccEnv env occ (map trans_gre gres) Nothing -> env extendGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrElt -> GlobalRdrEnv extendGlobalRdrEnv env gre = extendOccEnv_Acc insertGRE singleton env (greOccName gre) gre shadowNames :: GlobalRdrEnv -> [Name] -> GlobalRdrEnv shadowNames = foldl shadowName {- Note [GlobalRdrEnv shadowing] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Before adding new names to the GlobalRdrEnv we nuke some existing entries; this is "shadowing". The actual work is done by RdrEnv.shadowNames. There are two reasons for shadowing: * The GHCi REPL - Ids bought into scope on the command line (eg let x = True) have External Names, like Ghci4.x. We want a new binding for 'x' (say) to override the existing binding for 'x'. See Note [Interactively-bound Ids in GHCi] in HscTypes - Data types also have Extenal Names, like Ghci4.T; but we still want 'T' to mean the newly-declared 'T', not an old one. * Nested Template Haskell declaration brackets See Note [Top-level Names in Template Haskell decl quotes] in RnNames Consider a TH decl quote: module M where f x = h [d| f = 3 |] We must shadow the outer declaration of 'f', else we'll get a complaint when extending the GlobalRdrEnv, saying that there are two bindings for 'f'. There are several tricky points: - This shadowing applies even if the binding for 'f' is in a where-clause, and hence is in the *local* RdrEnv not the *global* RdrEnv. This is done in lcl_env_TH in extendGlobalRdrEnvRn. - The External Name M.f from the enclosing module must certainly still be available. So we don't nuke it entirely; we just make it seem like qualified import. - We only shadow *External* names (which come from the main module), or from earlier GHCi commands. Do not shadow *Internal* names because in the bracket [d| class C a where f :: a f = 4 |] rnSrcDecls will first call extendGlobalRdrEnvRn with C[f] from the class decl, and *separately* extend the envt with the value binding. At that stage, the class op 'f' will have an Internal name. -} shadowName :: GlobalRdrEnv -> Name -> GlobalRdrEnv -- Remove certain old GREs that share the same OccName as this new Name. -- See Note [GlobalRdrEnv shadowing] for details shadowName env name = alterOccEnv (fmap alter_fn) env (nameOccName name) where alter_fn :: [GlobalRdrElt] -> [GlobalRdrElt] alter_fn gres = mapMaybe (shadow_with name) gres shadow_with :: Name -> GlobalRdrElt -> Maybe GlobalRdrElt shadow_with new_name old_gre@(GRE { gre_name = old_name, gre_lcl = lcl, gre_imp = iss }) = case nameModule_maybe old_name of Nothing -> Just old_gre -- Old name is Internal; do not shadow Just old_mod | Just new_mod <- nameModule_maybe new_name , new_mod == old_mod -- Old name same as new name; shadow completely -> Nothing | null iss' -- Nothing remains -> Nothing | otherwise -> Just (old_gre { gre_lcl = False, gre_imp = iss' }) where iss' = lcl_imp ++ mapMaybe (shadow_is new_name) iss lcl_imp | lcl = [mk_fake_imp_spec old_name old_mod] | otherwise = [] mk_fake_imp_spec old_name old_mod -- Urgh! = ImpSpec id_spec ImpAll where old_mod_name = moduleName old_mod id_spec = ImpDeclSpec { is_mod = old_mod_name , is_as = old_mod_name , is_qual = True , is_dloc = nameSrcSpan old_name } shadow_is :: Name -> ImportSpec -> Maybe ImportSpec shadow_is new_name is@(ImpSpec { is_decl = id_spec }) | Just new_mod <- nameModule_maybe new_name , is_as id_spec == moduleName new_mod = Nothing -- Shadow both qualified and unqualified | otherwise -- Shadow unqualified only = Just (is { is_decl = id_spec { is_qual = True } }) {- ************************************************************************ * * Provenance * * ************************************************************************ -} -- | The 'ImportSpec' of something says how it came to be imported -- It's quite elaborate so that we can give accurate unused-name warnings. data ImportSpec = ImpSpec { is_decl :: ImpDeclSpec, is_item :: ImpItemSpec } deriving( Eq, Ord ) -- | Describes a particular import declaration and is -- shared among all the 'Provenance's for that decl data ImpDeclSpec = ImpDeclSpec { is_mod :: ModuleName, -- ^ Module imported, e.g. @import Muggle@ -- Note the @Muggle@ may well not be -- the defining module for this thing! -- TODO: either should be Module, or there -- should be a Maybe UnitId here too. is_as :: ModuleName, -- ^ Import alias, e.g. from @as M@ (or @Muggle@ if there is no @as@ clause) is_qual :: Bool, -- ^ Was this import qualified? is_dloc :: SrcSpan -- ^ The location of the entire import declaration } -- | Describes import info a particular Name data ImpItemSpec = ImpAll -- ^ The import had no import list, -- or had a hiding list | ImpSome { is_explicit :: Bool, is_iloc :: SrcSpan -- Location of the import item } -- ^ The import had an import list. -- The 'is_explicit' field is @True@ iff the thing was named -- /explicitly/ in the import specs rather -- than being imported as part of a "..." group. Consider: -- -- > import C( T(..) ) -- -- Here the constructors of @T@ are not named explicitly; -- only @T@ is named explicitly. instance Eq ImpDeclSpec where p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False instance Ord ImpDeclSpec where compare is1 is2 = (is_mod is1 `compare` is_mod is2) `thenCmp` (is_dloc is1 `compare` is_dloc is2) instance Eq ImpItemSpec where p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False instance Ord ImpItemSpec where compare is1 is2 = is_iloc is1 `compare` is_iloc is2 unQualSpecOK :: ImportSpec -> Bool -- ^ Is in scope unqualified? unQualSpecOK is = not (is_qual (is_decl is)) qualSpecOK :: ModuleName -> ImportSpec -> Bool -- ^ Is in scope qualified with the given module? qualSpecOK mod is = mod == is_as (is_decl is) importSpecLoc :: ImportSpec -> SrcSpan importSpecLoc (ImpSpec decl ImpAll) = is_dloc decl importSpecLoc (ImpSpec _ item) = is_iloc item importSpecModule :: ImportSpec -> ModuleName importSpecModule is = is_mod (is_decl is) isExplicitItem :: ImpItemSpec -> Bool isExplicitItem ImpAll = False isExplicitItem (ImpSome {is_explicit = exp}) = exp {- -- Note [Comparing provenance] -- Comparison of provenance is just used for grouping -- error messages (in RnEnv.warnUnusedBinds) instance Eq Provenance where p1 == p2 = case p1 `compare` p2 of EQ -> True; _ -> False instance Ord Provenance where compare (Prov l1 i1) (Prov l2 i2) = (l1 `compare` l2) `thenCmp` (i1 `cmp_is` i2) where -- See Note [Comparing provenance] [] `cmp_is` [] = EQ [] `cmp_is` _ = LT (_:_) `cmp_is` [] = GT (i1:_) `cmp_is` (i2:_) = i1 `compare` i2 -} pprNameProvenance :: GlobalRdrElt -> SDoc -- ^ Print out one place where the name was define/imported -- (With -dppr-debug, print them all) pprNameProvenance (GRE { gre_name = name, gre_lcl = lcl, gre_imp = iss }) | opt_PprStyle_Debug = vcat pp_provs | otherwise = head pp_provs where pp_provs = pp_lcl ++ map pp_is iss pp_lcl = if lcl then [ptext (sLit "defined at") <+> ppr (nameSrcLoc name)] else [] pp_is is = sep [ppr is, ppr_defn_site is name] -- If we know the exact definition point (which we may do with GHCi) -- then show that too. But not if it's just "imported from X". ppr_defn_site :: ImportSpec -> Name -> SDoc ppr_defn_site imp_spec name | same_module && not (isGoodSrcSpan loc) = empty -- Nothing interesting to say | otherwise = parens $ hang (ptext (sLit "and originally defined") <+> pp_mod) 2 (pprLoc loc) where loc = nameSrcSpan name defining_mod = nameModule name same_module = importSpecModule imp_spec == moduleName defining_mod pp_mod | same_module = empty | otherwise = ptext (sLit "in") <+> quotes (ppr defining_mod) instance Outputable ImportSpec where ppr imp_spec = ptext (sLit "imported") <+> qual <+> ptext (sLit "from") <+> quotes (ppr (importSpecModule imp_spec)) <+> pprLoc (importSpecLoc imp_spec) where qual | is_qual (is_decl imp_spec) = ptext (sLit "qualified") | otherwise = empty pprLoc :: SrcSpan -> SDoc pprLoc (RealSrcSpan s) = ptext (sLit "at") <+> ppr s pprLoc (UnhelpfulSpan {}) = empty
siddhanathan/ghc
compiler/basicTypes/RdrName.hs
bsd-3-clause
40,547
0
16
11,342
7,728
4,105
3,623
493
4
{-# LANGUAGE NoMonomorphismRestriction #-} module Network.DGS.Atto ( module Control.Applicative , module Data.Attoparsec , module Network.DGS.Atto , ByteString ) where import Control.Applicative import Data.Attoparsec hiding (Parser) import Data.Attoparsec as A import Data.ByteString (ByteString) import Data.Int import Data.Ix import Data.SGF.Types (Color(..), RuleSetGo(..)) import Data.Time import System.Locale import qualified Data.ByteString.Char8 as C import qualified Data.ByteString as W enum = toEnum . fromEnum comma = word8 (enum ',') s --> v = string (C.pack s) >> return v field = quotedField <|> A.takeWhile (not . special) where special x = x `elem` map enum "'\\ ," quotedField = do word8 (enum '\'') chunks <- many (chunk <|> escape) word8 (enum '\'') return (W.concat chunks) where chunk = takeWhile1 (not . special) escape = word8 (enum '\\') >> pack <$> satisfy special special x = x == enum '\'' || x == enum '\\' pack x = W.pack [x] integral = liftA2 (*) sign natural where sign = (word8 (enum '-') >> return (-1)) <|> return 1 natural = digits2Integer <$> takeWhile1 isDigit where isDigit x = x >= zero && x <= nine digits2Integer = W.foldl' (\n d -> n * 10 + fromIntegral (d - zero)) 0 zero = enum '0' nine = enum '9' column = comma >> attoparse bracketed s e p = do word8 (enum s) v <- p word8 (enum e) return v parenthesized = bracketed '(' ')' quoted = bracketed '\'' '\'' class Atto a where attoparse :: A.Parser a instance Atto Integer where attoparse = integral instance Atto Int16 where attoparse = attoparse >>= \n -> if inRange (-32768,32767) n then return (fromInteger n) else fail $ "number out of range for an Int16: " ++ show n instance Atto UTCTime where attoparse = do contents <- quotedField case parseTime defaultTimeLocale "%F %T" (C.unpack contents) of Just t -> return t Nothing -> fail $ "couldn't parse date " ++ C.unpack contents instance Atto Bool where attoparse = "0" --> False <|> "1" --> True instance Atto Color where attoparse = "B" --> Black <|> "W" --> White instance Atto RuleSetGo where attoparse = "CHINESE" --> Chinese <|> "JAPANESE" --> Japanese
dmwit/dgs
Network/DGS/Atto.hs
bsd-3-clause
2,228
4
13
473
829
431
398
60
1