code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-#LANGUAGE OverloadedStrings#-} {-| Module : ETA.Utils.JAR Description : Small utility functions for creating Jars from class files. Copyright : (c) Christopher Wells 2016 (c) Rahul Muttineni 2016-2017 License : MIT This module provides utility functions for creating Jar archives from JVM class files. The general process used for creating a Jar archive is to first create an empty Jar in the desired location using `createEmptyJar`. After the Jar has been created, files can be added to it using the `addByteStringToJar` and `addMultiByteStringsToJar` functions. When adding multiple files to a Jar, be sure to use the `addMultiByteStringsToJar` function, as it writes all of the file changes in one action, while mapping over a list of files with `addByteStringToJar` would perform the file write actions all seperately. Here is a quick exampe of how to create a Jar and add a file into it. @ -- Create the empty jar let jarLocation = "build/Hello.jar" createEmptyJar jarLocation -- Add a single file to the jar import Data.ByteString.Internal (packChars) let fileLocation = "hellopackage/Main.class" let fileContents = packChars "Hello, World!" addByteStringToJar fileLocation fileContents jarLocation @ -} module ETA.Utils.JAR ( addMultiByteStringsToJar' , createEmptyJar , getEntriesFromJar , mergeClassesAndJars , CompressionMethod , deflate , normal , bzip2 , mkPath ) where import Data.Coerce(coerce) import Codec.Archive.Zip import Control.Monad (forM_, forM, when) import Control.Monad.IO.Class (MonadIO(..)) import Control.Monad.Catch (MonadCatch(..), MonadThrow) import Data.ByteString.Internal (ByteString) import Path import Path.IO (copyFile) import Data.Map.Lazy (keys) import Data.Map.Strict (filterWithKey) import Data.List (sortBy) import System.Directory hiding (copyFile) import Data.Text (Text) import qualified Data.Text as T type FileAndContents = (RelativeFile, ByteString) type AbsoluteFile = Path Abs File type RelativeFile = Path Rel File deflate, normal, bzip2 :: CompressionMethod deflate = Deflate normal = Store bzip2 = BZip2 -- | Creates an empty jar archive at the given relative filepath location. -- The name of the archive and its file ending should be included in the -- filepath. -- -- __Throws__: 'PathParseException' -- -- See 'createArchive' and 'parseRelFile' for more information. -- -- For example, passing in "src\/Main.jar" would create an empty jar archive -- named "Main.jar" in the "src" sub-directory of the current directory. -- -- @ -- createEmptyJar "src/Main.jar" -- @ -- -- __Before__ -- -- @ -- . -- └── src -- @ -- -- __After__ -- -- @ -- . -- └── src -- └── Main.jar -- @ createEmptyJar :: (MonadIO m, MonadCatch m) => FilePath -> m () createEmptyJar location = do isRelative <- catch (parseRelFile location >> return True) handler if isRelative then do p <- parseRelFile location createArchive p (return ()) else do p <- parseAbsFile location createArchive p (return ()) where handler :: (MonadIO m, MonadCatch m) => PathParseException -> m Bool handler _ = return False -- | Adds the given ByteString as a file at the given location within the given -- jar archive. -- -- __Throws__: 'PathParseException', 'EntrySelectorException', -- isAlreadyInUseError, isDoesNotExistError, isPermissionError, 'ParsingFailed' -- -- See 'withArchive', 'mkEntrySelector', and 'parseRelFile' for more information. -- -- For example, running the following would create a file named "Hello.class" -- containing the string "Hello, World!" within the "src" directory in the jar -- archive located at "build\/libs\/HelloWorld.jar". -- -- @ -- let fileLocation = "src\/Hello.class" -- let contents = packChars "Hello, World!" -- let jarLocation = "build\/libs\/HelloWorld.jar" -- addByteStringToJar fileLocation contents jarLocation -- @ -- -- __Before__ -- -- @ -- . -- └── build -- └── libs -- └── HelloWorld.jar -- @ -- -- __After__ -- -- @ -- . -- └── build -- └── libs -- └── HelloWorld.jar -- └── src -- └── Hello.class -- @ addByteStringToJar :: (MonadThrow m, MonadIO m) => FilePath -- ^ Location of the new file within the jar -> CompressionMethod -- ^ Compression Method -> ByteString -- ^ Contents of the new file to add -> FilePath -- ^ Location of the jar to add the new file into -> m () addByteStringToJar fileLocation compress contents jarLocation = zipAction where zipAction = jarPath >>= flip withArchive zipChange zipChange = entrySel >>= addEntry compress contents entrySel = filePath >>= mkEntrySelector jarPath = parseRelFile jarLocation filePath = parseRelFile fileLocation -- | Adds the given files into the given jar. Each file is represented by a -- tuple containing the location where the file will be added inside the jar, -- and the contents of the file as a ByteString. -- -- __Throws__: 'PathParseException', 'EntrySelectorException', -- isAlreadyInUseError, isDoesNotExistError, isPermissionError, 'ParsingFailed' -- -- See 'withArchive', 'mkEntrySelector', and 'parseRelFile' for more information. -- -- For example, running the following would create two files within the jar -- archive located at "build\/libs\/HelloWorld.jar". The first file would be -- named "Hello.class" containing the string "Hello, World!" within the -- "helloworld" directory in the jar archive. The second file would be named -- \"MANIFEST.MF" containing the string "Manifest-Version: 1.0" within the -- \"META-INF" directory in the jar archive. -- -- @ -- let file1Location = "helloworld\/Hello.class" -- let file1Contents = "Hello, World!" -- let file1 = (file1Location, file1Contents) -- -- let file2Location = "META-INF\/MANIFEST.MF" -- let file2Contents = "Manifest-Version: 1.0" -- let file2 = (file2Location, file2Contents) -- -- let files = [file1, file2] -- let jarLocation = "build\/libs\/HelloWorld.jar" -- addMultiByteStringsToJar files jarLocation -- @ -- -- __Before__ -- -- @ -- . -- └── build -- └── libs -- └── HelloWorld.jar -- @ -- -- __After__ -- -- @ -- . -- └── build -- └── libs -- └── HelloWorld.jar -- β”œβ”€β”€ helloworld -- β”‚ └── Hello.class -- └── META-INF -- └── MANIFEST.MF -- @ -- addMultiByteStringsToJar -- :: (MonadThrow m, MonadIO m) -- => [(FilePath, ByteString)] -- ^ Filepaths and contents of files to add into the jar -- -> FilePath -- ^ Location of the jar to add the new files into -- -> m () -- addMultiByteStringsToJar files jarLocation = do -- jarPath <- parseRelFile jarLocation -- withArchive jarPath $ -- forM_ files $ \(path, contents) -> do -- filePath <- parseRelFile path -- entrySel <- mkEntrySelector filePath -- addEntry Deflate contents entrySel addMultiByteStringsToJar' :: (MonadThrow m, MonadIO m, MonadCatch m) => FilePath -- ^ Location of the jar to add the new files into -> CompressionMethod -- ^ Compression Method -> [(Path Rel File, ByteString)] -- ^ Filepaths and contents of files to add into the jar -> m () addMultiByteStringsToJar' jarLocation compress files = do isRelative <- catch (parseRelFile jarLocation >> return True) handler if isRelative then do p <- parseRelFile jarLocation createArchive p action else do p <- parseAbsFile jarLocation createArchive p action where action = forM_ files $ \(path, contents) -> do entrySel <- mkEntrySelector path addEntry compress contents entrySel handler :: (MonadThrow m, MonadCatch m, MonadIO m) => PathParseException -> m Bool handler _ = return False -- getFilesFromJar -- :: (MonadThrow m, MonadCatch m, MonadIO m) -- => FilePath -- -> m [(Path Rel File, ByteString)] -- getFilesFromJar jarLocation = -- withUnsafePath jarLocation (flip withArchive action) (flip withArchive action) -- where action = do -- entrySelectors <- keys <$> getEntries -- forM entrySelectors $ \es -> do -- contents <- getEntry es -- return (unEntrySelector es, contents) mkPath :: (MonadThrow m, MonadIO m) => FilePath -> m (Path Rel File) mkPath = parseRelFile makeAbsoluteFilePath :: (MonadIO m, MonadThrow m) => FilePath -> m (Path Abs File) makeAbsoluteFilePath fp = do absPath <- liftIO $ canonicalizePath fp parseAbsFile absPath getEntriesFromJar :: (MonadThrow m, MonadCatch m, MonadIO m) => FilePath -> m (AbsoluteFile, [EntrySelector]) getEntriesFromJar jarLocation = do p <- makeAbsoluteFilePath jarLocation fmap (p,) $ withArchive p $ keys <$> getEntries mergeClassesAndJars :: (MonadIO m, MonadCatch m, MonadThrow m) => FilePath -> CompressionMethod -- ^ Compression Method -> [FileAndContents] -> [(AbsoluteFile, [EntrySelector])] -> m () mergeClassesAndJars jarLocation compress fileAndContents jarSelectors = do let ((copy, _):selectors) = sortBy (\(_, e1) (_, e2) -> compare (length e2) (length e1)) jarSelectors exists <- liftIO $ doesFileExist jarLocation when (not exists) $ liftIO $ writeFile jarLocation "" p <- makeAbsoluteFilePath jarLocation copyFile copy p withArchive p $ do existingEntries <- getEntries let invalidEntries = filterWithKey (\k _ -> invalidEntrySelector k) existingEntries mapM_ deleteEntry (keys invalidEntries) forM_ selectors $ \(absFile, entries) -> do forM_ entries $ \entry -> do when (invalidEntrySelector entry /= True) $ copyEntry absFile entry entry forM_ fileAndContents $ \(relFile, contents) -> do entrySel <- mkEntrySelector relFile addEntry compress contents entrySel where invalidEntrySelector :: EntrySelector -> Bool invalidEntrySelector fname = any (endsWith (getEntryName fname)) filterFileExts filterFileExts = [".SF", ".DSA", ".RSA"] endsWith :: Text -> Text -> Bool endsWith txt pred = T.toUpper (T.takeEnd (T.length pred) txt) == (T.toUpper pred)
alexander-at-github/eta
compiler/ETA/Utils/JAR.hs
bsd-3-clause
10,355
0
22
2,176
1,559
879
680
-1
-1
{- Codec for de/encoding form data shipped in URL query strings or in POST request bodies. (application/x-www-form-urlencoded) (cf. RFC 3986.) -} module Web.Codec.URLEncoder ( encodeString , decodeString , isUTF8Encoded , utf8Encode ) where import qualified Codec.Binary.UTF8.String as UTF8 ( encodeString ) import Web.Codec.Percent ( getEncodedChar, getDecodedChar ) -- for isUTF8Encoded import Data.Bits import Data.Word ( Word32 ) utf8Encode :: String -> String utf8Encode str | isUTF8Encoded str = str | otherwise = UTF8.encodeString str encodeString :: String -> String encodeString str = go (utf8Encode str) where go "" = "" go (' ':xs) = '+':go xs go ('\r':'\n':xs) = '%':'0':'D':'%':'0':'A':go xs go ('\r':xs) = go ('\r':'\n':xs) go ('\n':xs) = go ('\r':'\n':xs) go (x:xs) = case getEncodedChar x of Nothing -> x : go xs Just ss -> ss ++ go xs decodeString :: String -> String decodeString "" = "" decodeString ('+':xs) = ' ':decodeString xs decodeString ls@(x:xs) = case getDecodedChar ls of Nothing -> x : decodeString xs Just (ch,xs1) -> ch : decodeString xs1 -- | @isUTF8Encoded str@ tries to recognize input string as being in UTF-8 form. -- Will soon migrate to @utf8-string@. isUTF8Encoded :: String -> Bool isUTF8Encoded [] = True isUTF8Encoded (x:xs) = case ox of _ | ox < 0x80 -> isUTF8Encoded xs | ox > 0xff -> False | ox < 0xc0 -> False | ox < 0xe0 -> check1 | ox < 0xf0 -> check_byte 2 0xf 0 | ox < 0xf8 -> check_byte 3 0x7 0x10000 | ox < 0xfc -> check_byte 4 0x3 0x200000 | ox < 0xfe -> check_byte 5 0x1 0x4000000 | otherwise -> False where ox = toW32 x toW32 :: Char -> Word32 toW32 ch = fromIntegral (fromEnum ch) check1 = case xs of [] -> False c1 : ds | oc .&. 0xc0 /= 0x80 || d < 0x000080 -> False | otherwise -> isUTF8Encoded ds where oc = toW32 c1 d = ((ox .&. 0x1f) `shiftL` 6) .|. (oc .&. 0x3f) check_byte :: Int -> Word32 -> Word32 -> Bool check_byte i mask overlong = aux i xs (ox .&. mask) where aux 0 rs acc | overlong <= acc && acc <= 0x10ffff && (acc < 0xd800 || 0xdfff < acc) && (acc < 0xfffe || 0xffff < acc) = isUTF8Encoded rs | otherwise = False aux n (r:rs) acc | toW32 r .&. 0xc0 == 0x80 = aux (n-1) rs (acc `shiftL` 6 .|. (toW32 r .&. 0x3f)) aux _ _ _ = False
sof/twitter
Web/Codec/URLEncoder.hs
bsd-3-clause
2,544
4
17
752
947
479
468
67
7
module Printer ( nl , join , style , bold , inYellow , inGreen , inRed , line , line80 , dline , dline80 , padLeft , padRight , padLeftS , padRightS , toRow , toRowF , toPanel ) where import Data.List (intercalate) nl :: String -> String nl str = str ++ "\n" join :: [String] -> String join = intercalate "\n" style :: Int -> String -> String style code text = "\ESC[" ++ (show code) ++ "m" ++ text ++ "\ESC[0m" bold = style 1 inYellow = style 93 inGreen = style 92 inRed = style 91 line :: Int -> String line = toLine "-" dline :: Int -> String dline = toLine "=" line80 = line 80 dline80 = dline 80 padLeft :: String -> Int -> String -> String padLeft padder width str = (toLine padder rest) ++ str where rest = width - length str padRight :: String -> Int -> String -> String padRight padder width str = str ++ (toLine padder rest) where rest = width - length str padLeftS = padLeft " " padRightS = padRight " " toLine :: String -> Int -> String toLine c w = concatMap (\ _ -> c) [0..(w - 1)] toRow :: [Int] -> [String] -> String toRow x y = concatMap spaceOut tuple where spaceOut (w, c) = padRight " " w c tuple = zip x y toRowF :: [String -> String] -> [String] -> String toRowF fs r = concat $ toRowFRaw fs r toRowFRaw :: [String -> String] -> [String] -> [String] toRowFRaw x y = map apply $ zip x y where apply (f, i) = f i toPanel :: [Int] -> [[String]] -> [String] toPanel dim (header:rows) = concat [intro, outro] where intro = [toPanelHeader dim header, line (sum dim)] outro = map (toPanelRow dim) rows toPanelHeader :: [Int] -> [String] -> String toPanelHeader dim header = concat . firstBold $ toPanelRowRaw dim header where firstBold (x:xs) = bold x:xs toPanelRow :: [Int] -> [String] -> String toPanelRow d r = concat $ toPanelRowRaw d r toPanelRowRaw :: [Int] -> [String] -> [String] toPanelRowRaw dim row = toRowFRaw (applyDim dim fs) row where fs = getPanelRowFormatter . length $ row getPanelRowFormatter :: Int -> [Int -> String -> String] getPanelRowFormatter i = padRightS:map (\_ -> padLeftS) [0..(i - 1)] applyDim :: [a] -> [a -> b -> b] -> [b -> b] applyDim a b = map apply $ zip b a where apply (f, d) = f d
LFDM/hstats
src/lib/Printer.hs
bsd-3-clause
2,196
0
10
481
978
522
456
72
1
module Main (main) where import Data.Binary.Get import Data.Binary.Put import qualified Data.ByteString.Lazy as BL import Codec.Tracker.IT main :: IO () main = do file <- BL.getContents let it0 = runGet getModule file it1 = runGet getModule $ runPut $ putModule it0 if it0 == it1 then putStrLn "it0 and it1 are identical" else putStrLn "it0 and it1 differ"
riottracker/modfile
examples/testIT.hs
bsd-3-clause
426
0
12
126
114
62
52
13
2
{-# LANGUAGE DeriveGeneric, FlexibleInstances, OverloadedStrings, ScopedTypeVariables #-} module Main where import qualified Language.Lua.Annotated as A import qualified Language.Lua.Annotated.Lexer as L import qualified Language.Lua.Annotated.Simplify as S import qualified Language.Lua.Parser as P import Language.Lua.PrettyPrinter (pprint) import Language.Lua.StringLiteral import Language.Lua.Syntax import qualified Language.Lua.Token as T import qualified Text.Parsec as P import Test.QuickCheck hiding (Args) import Test.Tasty import Test.Tasty.HUnit import Test.Tasty.QuickCheck import Control.Applicative import Control.DeepSeq (deepseq, force) import Control.Monad (forM_) import qualified Data.ByteString.Lazy as B import Data.Char (isSpace) import GHC.Generics import Prelude hiding (Ordering (..), exp) import System.Directory (getDirectoryContents) import System.FilePath main :: IO () main = defaultMain tests tests :: TestTree tests = testGroup "Tests" [unitTests, propertyTests] unitTests :: TestTree unitTests = testGroup "Unit tests" [stringTests, numberTests, regressions, lua531Tests, literalDecodingTests] where lua531Tests = parseFilesTest "Parsing Lua files from Lua 5.3.1 test suite" "lua-5.3.1-tests" propertyTests :: TestTree propertyTests = testGroup "Property tests" [{-genPrintParse-}] parseExps :: String -> String -> Either P.ParseError [A.Exp P.SourcePos] parseExps file contents = case L.llex contents of Left (msg,pos) -> P.runParser (reportLexError msg pos) () file [] Right xs -> P.runParser (many A.exp) () file xs reportLexError :: Monad m => String -> L.AlexPosn -> P.ParsecT s u m a reportLexError msg (L.AlexPn _ line column) = do pos <- P.getPosition P.setPosition (pos `P.setSourceLine` line `P.setSourceColumn` column) fail ("lexical error: " ++ msg) literalDecodingTests :: TestTree literalDecodingTests = testGroup "Literal codec tests" [ testCase "decoding" (do assertEqual "C escapes wrong" (Just "\a\b\f\n\r\t\v\\\"'") $ interpretStringLiteral "\"\\a\\b\\f\\n\\r\\t\\v\\\\\\\"'\"" assertEqual "C escapes wrong" (Just "\a \b \f \n \r \t \v \\ \" '") $ interpretStringLiteral "\"\\a \\b \\f \\n \\r \\t \\v \\\\ \\\" '\"" assertEqual "ASCII characters wrong" (Just "the quick brown fox jumps over the lazy dog") $ interpretStringLiteral "'the quick brown fox jumps over the lazy dog'" assertEqual "Test decimal escapes" (Just "\0\1\2\3\4\60\127\255") $ interpretStringLiteral "'\\0\\1\\2\\3\\4\\60\\127\\255'" assertEqual "Test hexadecimal escapes" (Just "\0\1\2\3\4\127\255") $ interpretStringLiteral "\"\\x00\\x01\\x02\\x03\\x04\\x7f\\xff\"" assertEqual "Test UTF-8 encoding" (Just "\230\177\137\229\173\151") $ interpretStringLiteral "'汉字'" assertEqual "Test unicode escape" (Just "\0 \16 \230\177\137\229\173\151") $ interpretStringLiteral "'\\u{0} \\u{10} \\u{6c49}\\u{5b57}'" assertEqual "Test continued line" (Just "hello\nworld") $ interpretStringLiteral "\"hello\\\nworld\"" assertEqual "Test skipped whitespace" (Just "helloworld") $ interpretStringLiteral "'hello\\z \n \f \t \r \v world'" assertEqual "Long-quote leading newline" (Just "line1\nline2\n") $ interpretStringLiteral "[===[\nline1\nline2\n]===]" assertEqual "Long-quote without leading newline" (Just "line1\nline2\n") $ interpretStringLiteral "[===[line1\nline2\n]===]" assertEqual "Long-quote no escapes" (Just "\\0\\x00\\u{000}") $ interpretStringLiteral "[===[\\0\\x00\\u{000}]===]" assertEqual "Empty single quoted" (Just "") $ interpretStringLiteral "''" assertEqual "Empty double quoted" (Just "") $ interpretStringLiteral "\"\"" assertEqual "Empty long quoted" (Just "") $ interpretStringLiteral "[[]]" ) , testCase "encoding" (do assertEqual "Empty string" "\"\"" $ constructStringLiteral "" assertEqual "Normal escapes" "\"\\a\\b\\f\\n\\r\\t\\v\\\\\\\"\"" $ constructStringLiteral "\a\b\f\n\r\t\v\\\"" assertEqual "Exhaustive test" "\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\a\ \\\b\\t\\n\\v\\f\\r\\x0e\\x0f\ \\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\ \\\x18\\x19\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f\ \ !\\\"#$%&'()*+,-./0123456789:;<=>?@\ \ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`\ \abcdefghijklmnopqrstuvwxyz{|}~\\x7f\ \\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\ \\\x88\\x89\\x8a\\x8b\\x8c\\x8d\\x8e\\x8f\ \\\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97\ \\\x98\\x99\\x9a\\x9b\\x9c\\x9d\\x9e\\x9f\ \\\xa0\\xa1\\xa2\\xa3\\xa4\\xa5\\xa6\\xa7\ \\\xa8\\xa9\\xaa\\xab\\xac\\xad\\xae\\xaf\ \\\xb0\\xb1\\xb2\\xb3\\xb4\\xb5\\xb6\\xb7\ \\\xb8\\xb9\\xba\\xbb\\xbc\\xbd\\xbe\\xbf\ \\\xc0\\xc1\\xc2\\xc3\\xc4\\xc5\\xc6\\xc7\ \\\xc8\\xc9\\xca\\xcb\\xcc\\xcd\\xce\\xcf\ \\\xd0\\xd1\\xd2\\xd3\\xd4\\xd5\\xd6\\xd7\ \\\xd8\\xd9\\xda\\xdb\\xdc\\xdd\\xde\\xdf\ \\\xe0\\xe1\\xe2\\xe3\\xe4\\xe5\\xe6\\xe7\ \\\xe8\\xe9\\xea\\xeb\\xec\\xed\\xee\\xef\ \\\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\ \\\xf8\\xf9\\xfa\\xfb\\xfc\\xfd\\xfe\\xff\"" (constructStringLiteral (B.pack [0..255])) ) ] stringTests :: TestTree stringTests = testGroup "String tests" [ testCase "Equal strings from 5.3.1 reference manual" (do let file = "tests/strings" contents <- readFile file case parseExps file contents of Left parseErr -> assertFailure (show parseErr) Right exps -> do assertBool "Wrong number of strings parsed" (length exps == 5) case asStrings exps of Nothing -> assertFailure "Not all strings were strings" Just strs -> forM_ strs $ \str -> assertEqual "String not same" expected $ interpretStringLiteral str) , testCase "Round-trip through the pretty-printer" (do let file = "tests/string-literal-roundtrip.lua" contents <- readFile file case P.parseText P.chunk contents of Left parseErr -> assertFailure (show parseErr) Right x -> assertEqual "pretty printer didn't preserve" contents (show (pprint x) ++ "\n")) -- text file lines always end in a newline -- but the pretty printer doesn't know this ] where expected = Just "alo\n123\"" asString (String s) = Just s asString _ = Nothing asStrings = mapM (asString . S.sExp) numberTests :: TestTree numberTests = testGroup "Number tests" [ testCase "Numbers from 5.3.1 reference manual" (do let file = "tests/numbers" contents <- readFile file case parseExps file contents of Left parseErr -> assertFailure (show parseErr) Right exps -> do assertBool "Wrong number of numbers parsed" (length exps == 9) forM_ exps (assertNumber . S.sExp)) ] where assertNumber :: Exp -> Assertion assertNumber Number{} = return () assertNumber nan = assertFailure ("Not a number: " ++ show nan) regressions :: TestTree regressions = testGroup "Regression tests" [ testCase "Lexing comment with text \"EOF\" in it" $ assertEqual "Lexing is wrong" (Right [(T.LTokEof, L.AlexPn (-1) (-1) (-1))]) (L.llex "--EOF") , testCase "Binary/unary operator parsing/printing" $ do pp "2^3^2 == 2^(3^2)" pp "2^3*4 == (2^3)*4" pp "2^-2 == 1/4 and -2^- -2 == - - -4" pp "not nil and 2 and not(2>3 or 3<2)" pp "-3-1-5 == 0+0-9" pp "-2^2 == -4 and (-2)^2 == 4 and 2*2-3-1 == 0" pp "2*1+3/3 == 3 and 1+2 .. 3*1 == \"33\"" pp "not(2+1 > 3*1) and \"a\"..\"b\" > \"a\"" pp "not ((true or false) and nil)" pp "true or false and nil" pp "(((1 or false) and true) or false) == true" pp "(((nil and true) or false) and true) == false" , testCase "Lexing unnecessarily escaped quotes" $ do show (L.llex "'\\\"'") `deepseq` return () show (L.llex "\"\\\'\"") `deepseq` return () , testCase "Lexing Lua string: '\\\\\"'" $ do assertEqual "String lexed wrong" (Right [T.LTokSLit "'\\\\\"'", T.LTokEof]) (fmap (map fst) $ L.llex "'\\\\\"'") , testCase "Lexing long literal `[====[ ... ]====]`" $ show (L.llex "[=[]]=]") `deepseq` return () , testCase "Handling \\z" $ show (L.llex "\"\\z\n \"") `deepseq` return () , testCase "varlist parser shouldn't accept empty list of variables in local declarations" $ assertParseFailure (P.parseText P.stat "local = test") , testCase "explist parser shouldn't accept empty list of expressions in local declarations" $ assertParseFailure (P.parseText P.stat "local x =") , testCase "empty varlist and explist in single assignment, should be rejected" $ assertParseFailure (P.parseText P.stat "local =") , testCase "varlist parser shouldn't accept empty list of expressions in global declarations" $ assertParseFailure (P.parseText P.stat "= test") , testCase "explist parsers shouldn't accept empty list of expressions in global declarations" $ assertParseFailure (P.parseText P.stat "x =") , testCase "empty list of return values should be accpeted" $ assertEqual "Parsed wrong" (Right $ Block [] (Just [])) (P.parseText P.chunk "return") , testCase "Long comments should start immediately after --" $ do assertEqual "Parsed wrong" (Right $ Block [] Nothing) (P.parseText P.chunk "--[[ line1\nline2 ]]") assertParseFailure (P.parseText P.chunk "-- [[ line1\nline2 ]]") , testCase "Print EmptyStat for disambiguation" $ ppChunk "f();(f)()" , testCase "printing negation chains" $ let exp = Unop Neg (Unop Neg (Unop Neg (Number "120"))) in assertEqual "Parsed and/or printed wrong" (Right exp) (P.parseText P.exp (show (pprint exp))) ] where pp :: String -> Assertion pp = ppTest (P.parseText P.exp) (show . pprint) ppChunk :: String -> Assertion ppChunk = ppTest (P.parseText P.chunk) (show . pprint) ppTest :: Show err => (String -> Either err ret) -> (ret -> String) -> String -> Assertion ppTest parser printer str = case parser str of Left err -> assertFailure $ "Parsing failed: " ++ show err Right expr' -> assertEqual "Printed string is not equal to original one modulo whitespace" (filter (not . isSpace) str) (filter (not . isSpace) (printer expr')) assertParseFailure (Left _parseError) = return () assertParseFailure (Right ret) = assertFailure $ "Unexpected parse: " ++ show ret parseFilesTest :: String -> FilePath -> TestTree parseFilesTest msg root = testCase msg $ do luaFiles <- map (root </>) . filter ((==) ".lua" . takeExtension) <$> getDirectoryContents root putStrLn $ "Trying to parse " ++ show (length luaFiles) ++ " Lua files." forM_ luaFiles $ \luaFile -> do putStrLn $ "Parsing file: " ++ luaFile ret <- P.parseFile luaFile case ret of Left err -> assertFailure ("Parser error in " ++ luaFile ++ ": " ++ show err) Right st -> -- force st `seq` return () let printed = show (pprint st) in case P.parseText P.chunk printed of Left err -> assertFailure ("Parser error while parsing printed version of " ++ luaFile ++ ": " ++ show err ++ "\nPrinted file:\n" ++ printed) Right st' -> force st' `seq` return () genPrintParse :: TestTree genPrintParse = localOption (QuickCheckTests 10) . localOption (mkTimeout 100000) . localOption (QuickCheckMaxSize 2) $ testGroup "Generate-Print-Parse" [ testProperty "forall l, (parse . pprint) l = l" prop ] where prop :: Property prop = forAll arbitrary printAndParseEq printAndParseEq :: Block -> Property printAndParseEq b = Right b === (P.parseText P.chunk . show . pprint) b -- * Arbitrary instances newtype LuaString = LuaString { unwrapLuaString :: String } deriving (Generic) -- FIXME: either fix this or implement separate lexer tests instance Arbitrary LuaString where arbitrary = LuaString <$> listOf1 (elements ['a'..'z']) shrink = recursivelyShrink arbitraryLuaStringList :: Gen [String] arbitraryLuaStringList = liftA unwrapLuaString <$> listOf1 arbitrary arbitraryLuaString :: Gen String arbitraryLuaString = unwrapLuaString <$> arbitrary instance Arbitrary Stat where arbitrary = oneof [ Assign <$> arbitrary <*> arbitrary , FunCall <$> arbitrary , Label <$> arbitrary , return Break , Goto <$> arbitrary , Do <$> arbitrary , While <$> arbitrary <*> arbitrary , Repeat <$> arbitrary <*> arbitrary , If <$> listOf1 arbitrary <*> arbitrary , ForRange <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary , ForIn <$> listOf1 arbitrary <*> arbitrary <*> arbitrary , FunAssign <$> arbitrary <*> arbitrary , LocalFunAssign <$> arbitrary <*> arbitrary , LocalAssign <$> listOf1 arbitrary <*> arbitrary -- Don't generate EmptyState - it's not printed by pretty-printer , return EmptyStat ] shrink = recursivelyShrink instance Arbitrary Exp where arbitrary = oneof [ return Nil , Bool <$> arbitrary , Number <$> listOf1 (elements ['0'..'9']) -- TODO: implement number lexer tests , String <$> arbitraryLuaString , return Vararg , EFunDef <$> arbitrary , PrefixExp <$> arbitrary , TableConst <$> arbitrary , Binop <$> arbitrary <*> arbitrary <*> arbitrary , Unop <$> arbitrary <*> expNotUnop ] shrink = recursivelyShrink -- | Any expression except Unop. (see #2) expNotUnop :: Gen Exp expNotUnop = suchThat arbitrary notUnop where notUnop :: Exp -> Bool notUnop Unop{} = False notUnop _ = True instance Arbitrary Var where arbitrary = oneof [ VarName <$> arbitrary , Select <$> arbitrary <*> arbitrary , SelectName <$> arbitrary <*> arbitrary ] shrink = recursivelyShrink instance Arbitrary Binop where arbitrary = oneof $ map return [Add, Sub, Mul, Div, Exp, Mod, Concat, LT, LTE, GT, GTE, EQ, NEQ, And, Or] shrink = recursivelyShrink instance Arbitrary Unop where arbitrary = oneof [ return Neg , return Not , return Len ] shrink = recursivelyShrink instance Arbitrary PrefixExp where arbitrary = oneof [ PEVar <$> arbitrary , PEFunCall <$> arbitrary , Paren <$> arbitrary ] shrink = recursivelyShrink instance Arbitrary TableField where arbitrary = oneof [ ExpField <$> arbitrary <*> arbitrary , NamedField <$> arbitrary <*> arbitrary , Field <$> arbitrary ] shrink = recursivelyShrink instance Arbitrary Block where arbitrary = Block <$> arbitrary <*> suchThat arbitrary (maybe True (not . null)) shrink = recursivelyShrink instance Arbitrary FunName where arbitrary = FunName <$> arbitrary <*> listOf arbitrary <*> arbitrary shrink = recursivelyShrink instance Arbitrary FunBody where arbitrary = FunBody <$> listOf1 arbitrary <*> arbitrary <*> arbitrary shrink = recursivelyShrink instance Arbitrary FunCall where arbitrary = oneof [ NormalFunCall <$> arbitrary <*> arbitrary , MethodCall <$> arbitrary <*> arbitrary <*> arbitrary ] shrink = recursivelyShrink instance Arbitrary FunArg where arbitrary = oneof [ Args <$> arbitrary , TableArg <$> arbitrary , StringArg <$> arbitrary ] shrink = recursivelyShrink
osa1/language-lua
tests/Main.hs
bsd-3-clause
16,916
0
26
4,758
3,638
1,830
1,808
330
5
{-# LANGUAGE OverloadedStrings #-} module Crypto.Pkcs12.BmpStringSpec where import Crypto.Pkcs12.BmpString ( BmpString(..), encode, decode ) import qualified Data.ByteString as B import qualified Data.ByteString.Base16 as H import Data.Either.Compat import Test.Hspec import Test.QuickCheck spec = describe "BmpString" $ do describe "encode" $ do it "encodes a String" $ do -- Example from https://tools.ietf.org/html/rfc7292#appendix-B. hexBmpString "Beavis" `shouldBe` Just "0042006500610076006900730000" -- Some characters from the "Letterlike Symbols Unicode block". hexBmpString "\x2115 - Double-struck N" `shouldBe` Just "21150020002d00200044006f00750062006c0065002d00730074007200750063006b0020004e0000" -- any character outside the BMP should trigger an error. hexBmpString "\x0001f000 East wind (Mahjong)" `shouldBe` Nothing it "has (n + 1) * 2 bytes length" $ property $ \s -> let Just (BmpString bs) = encode s in B.length bs `shouldBe` (length s + 1) * 2 it "has 2 zeros at last" $ property $ \s -> let Just (BmpString bs) = encode s in B.drop (B.length bs - 2) bs `shouldBe` B.pack [0, 0] describe "decode" $ do it "decodes an encoded BmpString" $ property $ \s -> let Just bmp = encode s in decode bmp `shouldBe` Right s it "returns Left when length is odd" $ isLeft $ decode (BmpString "\0\x42\0") it "doesn't strip when not null terminated" $ decode (BmpString "\0\x42\0\x65") `shouldBe` (Right "Be") hexBmpString :: String -> Maybe B.ByteString hexBmpString s = fmap (H.encode . unBmpString) (encode s)
tkawachi/pkcs12-hs
test/Crypto/Pkcs12/BmpStringSpec.hs
bsd-3-clause
1,759
0
20
457
441
222
219
38
1
module PartII (partII) where import Euterpea import Changes import Elements -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Part II -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- fMinorScale :: [PitchClass] fMinorScale = [F, G, Af, Bf, C, Df, Ef, F] b1pitches, b2pitches, b3pitches, b4pitches :: [Pitch] b1pitches = [(E, 3), (Df, 3), (Bf, 2), (G, 2)] b2pitches = [(Bf, 3), (Af, 3), (F, 3), (C, 3)] b3pitches = [(Df, 4), (Bf, 3), (Af, 3), (E, 3)] b4pitches = [(F, 4), (Ef, 4), (C, 4), (G, 3)] r4phraseDur :: Dur r4phraseDur = 9*qn ostinado :: Music Pitch ostinado = bassMF $ (onBassEString $ riff 0 0 0 b1pitches) :=: (onBassAString $ riff 4 0 (-2) b2pitches) :=: (onBassDString $ riff 8 0 (-1) b3pitches) :=: (onBassGString $ riff 10 4 (-3) b4pitches) where riff a b c ps = delayM (a*r4phraseDur + b*qn + c*sn) $ ringNotes qn ps coil :: Music Pitch coil = onCoilShort $ riff 2 [(Af, 5), (F, 5), (C, 5)] :=: riff 3 [(C, 6), (Af, 5), (E, 5)] :=: riff 7 [(Ef, 6), (C, 6), (G, 5)] where riff a ps = delayM (a*r4phraseDur) $ ringNotes (sn/2) ps coilAccentB3 :: Music Pitch coilAccentB3 = onCoilShort $ delayM (8*r4phraseDur) $ chord (map acc [4, 6, 7, 10, 11, 12]) where acc n = delayM (fromIntegral n*r4phraseDur) $ chord $ zipWith accLine [0..] $ take 8 $ drop (n * 8) b3line accLine m (p,o) = delayM (m*qn) $ ringNotes (sn) [(p,o+2)] b3line = concat $ ringOf b3pitches ++ [b3pitches] percA :: Music Pitch percA = onDrums $ vol FF slowPerc :+: timesM 3 (vol MP slowPerc) where slowPerc = ringCymbal qn 2 ringCymbal :: Dur -> Int -> Music Pitch ringCymbal d n = ringPerc d $ replicate n RideCymbal2 vol :: StdLoudness -> Music a -> Music a vol d = phrase [Dyn $ StdLoudness d] percB :: Music Pitch percB = onDrums $ delayM (4*r4phraseDur - qn) $ vol MP (ringCymbal sn 4) :+: rest (11*sn) :+: phrase [Dyn (Diminuendo 0.5)] (vol MP $ ringCymbal sn 4) percB3 :: Music Pitch percB3 = onDrums $ vol MP $ chord [riff 4 5, riff 10 4] where riff d n = delayM ((8+d)*r4phraseDur + dhn) $ timesM n ride ride = ringPerc sn [AcousticSnare, RideCymbal2, RideCymbal2] percC :: Music Pitch percC = onDrums $ delayM (810*sn) rollAndCrash rollAndCrash :: Music Pitch rollAndCrash = holdLast $ phrase [Tmp $ Accelerando 0.20, Dyn $ Crescendo 2, Dyn $ StdLoudness PPP] (timesM 32 (perc RideCymbal2 (sn/2) )) :+: perc RideCymbal2 dqn p2tempo :: Music a -> Music a p2tempo m = tempo (startTempo / 120) mAll where startTempo = 70 endTempo = 80 accl = (endTempo - startTempo) / endTempo firstDur = 6 * r4phraseDur mFirst = removeZeros $ takeM firstDur m mRest = removeZeros $ dropM firstDur m mAll = mFirst :+: phrase [Tmp $ Accelerando accl] mRest partII :: Music Pitch partII = p2tempo $ percA :=: delayM (5*qn) (ostinado :=: coil :=: coilAccentB3 :=: percB :=: percB3 :=: percC)
mzero/PlainChanges2
src/PartII.hs
bsd-3-clause
3,026
0
14
745
1,384
753
631
69
1
{-# LINE 1 "System.Console.GetOpt.hs" #-} {-# LANGUAGE Safe #-} ----------------------------------------------------------------------------- -- | -- Module : System.Console.GetOpt -- Copyright : (c) Sven Panne 2002-2005 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- This library provides facilities for parsing the command-line options -- in a standalone program. It is essentially a Haskell port of the GNU -- @getopt@ library. -- ----------------------------------------------------------------------------- {- Sven Panne <[email protected]> Oct. 1996 (small changes Dec. 1997) Two rather obscure features are missing: The Bash 2.0 non-option hack (if you don't already know it, you probably don't want to hear about it...) and the recognition of long options with a single dash (e.g. '-help' is recognised as '--help', as long as there is no short option 'h'). Other differences between GNU's getopt and this implementation: * To enforce a coherent description of options and arguments, there are explanation fields in the option/argument descriptor. * Error messages are now more informative, but no longer POSIX compliant... :-( And a final Haskell advertisement: The GNU C implementation uses well over 1100 lines, we need only 195 here, including a 46 line example! :-) -} module System.Console.GetOpt ( -- * GetOpt getOpt, getOpt', usageInfo, ArgOrder(..), OptDescr(..), ArgDescr(..), -- * Examples -- |To hopefully illuminate the role of the different data structures, -- here are the command-line options for a (very simple) compiler, -- done in two different ways. -- The difference arises because the type of 'getOpt' is -- parameterized by the type of values derived from flags. -- ** Interpreting flags as concrete values -- $example1 -- ** Interpreting flags as transformations of an options record -- $example2 ) where import Data.List ( isPrefixOf, find ) -- |What to do with options following non-options data ArgOrder a = RequireOrder -- ^ no option processing after first non-option | Permute -- ^ freely intersperse options and non-options | ReturnInOrder (String -> a) -- ^ wrap non-options into options {-| Each 'OptDescr' describes a single option. The arguments to 'Option' are: * list of short option characters * list of long option strings (without \"--\") * argument descriptor * explanation of option for user -} data OptDescr a = -- description of a single options: Option [Char] -- list of short option characters [String] -- list of long option strings (without "--") (ArgDescr a) -- argument descriptor String -- explanation of option for user -- |Describes whether an option takes an argument or not, and if so -- how the argument is injected into a value of type @a@. data ArgDescr a = NoArg a -- ^ no argument expected | ReqArg (String -> a) String -- ^ option requires argument | OptArg (Maybe String -> a) String -- ^ optional argument instance Functor ArgOrder where fmap _ RequireOrder = RequireOrder fmap _ Permute = Permute fmap f (ReturnInOrder g) = ReturnInOrder (f . g) instance Functor OptDescr where fmap f (Option a b argDescr c) = Option a b (fmap f argDescr) c instance Functor ArgDescr where fmap f (NoArg a) = NoArg (f a) fmap f (ReqArg g s) = ReqArg (f . g) s fmap f (OptArg g s) = OptArg (f . g) s data OptKind a -- kind of cmd line arg (internal use only): = Opt a -- an option | UnreqOpt String -- an un-recognized option | NonOpt String -- a non-option | EndOfOpts -- end-of-options marker (i.e. "--") | OptErr String -- something went wrong... -- | Return a string describing the usage of a command, derived from -- the header (first argument) and the options described by the -- second argument. usageInfo :: String -- header -> [OptDescr a] -- option descriptors -> String -- nicely formatted decription of options usageInfo header optDescr = unlines (header:table) where (ss,ls,ds) = (unzip3 . concatMap fmtOpt) optDescr table = zipWith3 paste (sameLen ss) (sameLen ls) ds paste x y z = " " ++ x ++ " " ++ y ++ " " ++ z sameLen xs = flushLeft ((maximum . map length) xs) xs flushLeft n xs = [ take n (x ++ repeat ' ') | x <- xs ] fmtOpt :: OptDescr a -> [(String,String,String)] fmtOpt (Option sos los ad descr) = case lines descr of [] -> [(sosFmt,losFmt,"")] (d:ds) -> (sosFmt,losFmt,d) : [ ("","",d') | d' <- ds ] where sepBy _ [] = "" sepBy _ [x] = x sepBy ch (x:xs) = x ++ ch:' ':sepBy ch xs sosFmt = sepBy ',' (map (fmtShort ad) sos) losFmt = sepBy ',' (map (fmtLong ad) los) fmtShort :: ArgDescr a -> Char -> String fmtShort (NoArg _ ) so = "-" ++ [so] fmtShort (ReqArg _ ad) so = "-" ++ [so] ++ " " ++ ad fmtShort (OptArg _ ad) so = "-" ++ [so] ++ "[" ++ ad ++ "]" fmtLong :: ArgDescr a -> String -> String fmtLong (NoArg _ ) lo = "--" ++ lo fmtLong (ReqArg _ ad) lo = "--" ++ lo ++ "=" ++ ad fmtLong (OptArg _ ad) lo = "--" ++ lo ++ "[=" ++ ad ++ "]" {-| Process the command-line, and return the list of values that matched (and those that didn\'t). The arguments are: * The order requirements (see 'ArgOrder') * The option descriptions (see 'OptDescr') * The actual command line arguments (presumably got from 'System.Environment.getArgs'). 'getOpt' returns a triple consisting of the option arguments, a list of non-options, and a list of error messages. -} getOpt :: ArgOrder a -- non-option handling -> [OptDescr a] -- option descriptors -> [String] -- the command-line arguments -> ([a],[String],[String]) -- (options,non-options,error messages) getOpt ordering optDescr args = (os,xs,es ++ map errUnrec us) where (os,xs,us,es) = getOpt' ordering optDescr args {-| This is almost the same as 'getOpt', but returns a quadruple consisting of the option arguments, a list of non-options, a list of unrecognized options, and a list of error messages. -} getOpt' :: ArgOrder a -- non-option handling -> [OptDescr a] -- option descriptors -> [String] -- the command-line arguments -> ([a],[String], [String] ,[String]) -- (options,non-options,unrecognized,error messages) getOpt' _ _ [] = ([],[],[],[]) getOpt' ordering optDescr (arg:args) = procNextOpt opt ordering where procNextOpt (Opt o) _ = (o:os,xs,us,es) procNextOpt (UnreqOpt u) _ = (os,xs,u:us,es) procNextOpt (NonOpt x) RequireOrder = ([],x:rest,[],[]) procNextOpt (NonOpt x) Permute = (os,x:xs,us,es) procNextOpt (NonOpt x) (ReturnInOrder f) = (f x :os, xs,us,es) procNextOpt EndOfOpts RequireOrder = ([],rest,[],[]) procNextOpt EndOfOpts Permute = ([],rest,[],[]) procNextOpt EndOfOpts (ReturnInOrder f) = (map f rest,[],[],[]) procNextOpt (OptErr e) _ = (os,xs,us,e:es) (opt,rest) = getNext arg args optDescr (os,xs,us,es) = getOpt' ordering optDescr rest -- take a look at the next cmd line arg and decide what to do with it getNext :: String -> [String] -> [OptDescr a] -> (OptKind a,[String]) getNext ('-':'-':[]) rest _ = (EndOfOpts,rest) getNext ('-':'-':xs) rest optDescr = longOpt xs rest optDescr getNext ('-': x :xs) rest optDescr = shortOpt x xs rest optDescr getNext a rest _ = (NonOpt a,rest) -- handle long option longOpt :: String -> [String] -> [OptDescr a] -> (OptKind a,[String]) longOpt ls rs optDescr = long ads arg rs where (opt,arg) = break (=='=') ls getWith p = [ o | o@(Option _ xs _ _) <- optDescr , find (p opt) xs /= Nothing ] exact = getWith (==) options = if null exact then getWith isPrefixOf else exact ads = [ ad | Option _ _ ad _ <- options ] optStr = ("--"++opt) long (_:_:_) _ rest = (errAmbig options optStr,rest) long [NoArg a ] [] rest = (Opt a,rest) long [NoArg _ ] ('=':_) rest = (errNoArg optStr,rest) long [ReqArg _ d] [] [] = (errReq d optStr,[]) long [ReqArg f _] [] (r:rest) = (Opt (f r),rest) long [ReqArg f _] ('=':xs) rest = (Opt (f xs),rest) long [OptArg f _] [] rest = (Opt (f Nothing),rest) long [OptArg f _] ('=':xs) rest = (Opt (f (Just xs)),rest) long _ _ rest = (UnreqOpt ("--"++ls),rest) -- handle short option shortOpt :: Char -> String -> [String] -> [OptDescr a] -> (OptKind a,[String]) shortOpt y ys rs optDescr = short ads ys rs where options = [ o | o@(Option ss _ _ _) <- optDescr, s <- ss, y == s ] ads = [ ad | Option _ _ ad _ <- options ] optStr = '-':[y] short (_:_:_) _ rest = (errAmbig options optStr,rest) short (NoArg a :_) [] rest = (Opt a,rest) short (NoArg a :_) xs rest = (Opt a,('-':xs):rest) short (ReqArg _ d:_) [] [] = (errReq d optStr,[]) short (ReqArg f _:_) [] (r:rest) = (Opt (f r),rest) short (ReqArg f _:_) xs rest = (Opt (f xs),rest) short (OptArg f _:_) [] rest = (Opt (f Nothing),rest) short (OptArg f _:_) xs rest = (Opt (f (Just xs)),rest) short [] [] rest = (UnreqOpt optStr,rest) short [] xs rest = (UnreqOpt optStr,('-':xs):rest) -- miscellaneous error formatting errAmbig :: [OptDescr a] -> String -> OptKind a errAmbig ods optStr = OptErr (usageInfo header ods) where header = "option `" ++ optStr ++ "' is ambiguous; could be one of:" errReq :: String -> String -> OptKind a errReq d optStr = OptErr ("option `" ++ optStr ++ "' requires an argument " ++ d ++ "\n") errUnrec :: String -> String errUnrec optStr = "unrecognized option `" ++ optStr ++ "'\n" errNoArg :: String -> OptKind a errNoArg optStr = OptErr ("option `" ++ optStr ++ "' doesn't allow an argument\n") {- ----------------------------------------------------------------------------------------- -- and here a small and hopefully enlightening example: data Flag = Verbose | Version | Name String | Output String | Arg String deriving Show options :: [OptDescr Flag] options = [Option ['v'] ["verbose"] (NoArg Verbose) "verbosely list files", Option ['V','?'] ["version","release"] (NoArg Version) "show version info", Option ['o'] ["output"] (OptArg out "FILE") "use FILE for dump", Option ['n'] ["name"] (ReqArg Name "USER") "only dump USER's files"] out :: Maybe String -> Flag out Nothing = Output "stdout" out (Just o) = Output o test :: ArgOrder Flag -> [String] -> String test order cmdline = case getOpt order options cmdline of (o,n,[] ) -> "options=" ++ show o ++ " args=" ++ show n ++ "\n" (_,_,errs) -> concat errs ++ usageInfo header options where header = "Usage: foobar [OPTION...] files..." -- example runs: -- putStr (test RequireOrder ["foo","-v"]) -- ==> options=[] args=["foo", "-v"] -- putStr (test Permute ["foo","-v"]) -- ==> options=[Verbose] args=["foo"] -- putStr (test (ReturnInOrder Arg) ["foo","-v"]) -- ==> options=[Arg "foo", Verbose] args=[] -- putStr (test Permute ["foo","--","-v"]) -- ==> options=[] args=["foo", "-v"] -- putStr (test Permute ["-?o","--name","bar","--na=baz"]) -- ==> options=[Version, Output "stdout", Name "bar", Name "baz"] args=[] -- putStr (test Permute ["--ver","foo"]) -- ==> option `--ver' is ambiguous; could be one of: -- -v --verbose verbosely list files -- -V, -? --version, --release show version info -- Usage: foobar [OPTION...] files... -- -v --verbose verbosely list files -- -V, -? --version, --release show version info -- -o[FILE] --output[=FILE] use FILE for dump -- -n USER --name=USER only dump USER's files ----------------------------------------------------------------------------------------- -} {- $example1 A simple choice for the type associated with flags is to define a type @Flag@ as an algebraic type representing the possible flags and their arguments: > module Opts1 where > > import System.Console.GetOpt > import Data.Maybe ( fromMaybe ) > > data Flag > = Verbose | Version > | Input String | Output String | LibDir String > deriving Show > > options :: [OptDescr Flag] > options = > [ Option ['v'] ["verbose"] (NoArg Verbose) "chatty output on stderr" > , Option ['V','?'] ["version"] (NoArg Version) "show version number" > , Option ['o'] ["output"] (OptArg outp "FILE") "output FILE" > , Option ['c'] [] (OptArg inp "FILE") "input FILE" > , Option ['L'] ["libdir"] (ReqArg LibDir "DIR") "library directory" > ] > > inp,outp :: Maybe String -> Flag > outp = Output . fromMaybe "stdout" > inp = Input . fromMaybe "stdin" > > compilerOpts :: [String] -> IO ([Flag], [String]) > compilerOpts argv = > case getOpt Permute options argv of > (o,n,[] ) -> return (o,n) > (_,_,errs) -> ioError (userError (concat errs ++ usageInfo header options)) > where header = "Usage: ic [OPTION...] files..." Then the rest of the program will use the constructed list of flags to determine it\'s behaviour. -} {- $example2 A different approach is to group the option values in a record of type @Options@, and have each flag yield a function of type @Options -> Options@ transforming this record. > module Opts2 where > > import System.Console.GetOpt > import Data.Maybe ( fromMaybe ) > > data Options = Options > { optVerbose :: Bool > , optShowVersion :: Bool > , optOutput :: Maybe FilePath > , optInput :: Maybe FilePath > , optLibDirs :: [FilePath] > } deriving Show > > defaultOptions = Options > { optVerbose = False > , optShowVersion = False > , optOutput = Nothing > , optInput = Nothing > , optLibDirs = [] > } > > options :: [OptDescr (Options -> Options)] > options = > [ Option ['v'] ["verbose"] > (NoArg (\ opts -> opts { optVerbose = True })) > "chatty output on stderr" > , Option ['V','?'] ["version"] > (NoArg (\ opts -> opts { optShowVersion = True })) > "show version number" > , Option ['o'] ["output"] > (OptArg ((\ f opts -> opts { optOutput = Just f }) . fromMaybe "output") > "FILE") > "output FILE" > , Option ['c'] [] > (OptArg ((\ f opts -> opts { optInput = Just f }) . fromMaybe "input") > "FILE") > "input FILE" > , Option ['L'] ["libdir"] > (ReqArg (\ d opts -> opts { optLibDirs = optLibDirs opts ++ [d] }) "DIR") > "library directory" > ] > > compilerOpts :: [String] -> IO (Options, [String]) > compilerOpts argv = > case getOpt Permute options argv of > (o,n,[] ) -> return (foldl (flip id) defaultOptions o, n) > (_,_,errs) -> ioError (userError (concat errs ++ usageInfo header options)) > where header = "Usage: ic [OPTION...] files..." Similarly, each flag could yield a monadic function transforming a record, of type @Options -> IO Options@ (or any other monad), allowing option processing to perform actions of the chosen monad, e.g. printing help or version messages, checking that file arguments exist, etc. -}
phischu/fragnix
builtins/base/System.Console.GetOpt.hs
bsd-3-clause
16,494
0
12
4,725
3,010
1,632
1,378
134
10
module Cases.IfaceWriterTest where import Data.List import qualified Data.Map as Map import Language.Haskell.Exts hiding (name) import Tc.Assumption import Tc.Class import Tc.Kc.KcEnv import Iface.IfaceWriter import Utils.Id import qualified Utils.Env as Env testifacewriter1 = do writeInterface name1 m (toId (Ident "Teste1")) [syn1, syn2] (Map.fromList [lbl]) kcenv classes insts varenv name1 = "/home/rodrigo/Dropbox/projects/haskell/mptc/src/Tests/Data/Full/" m = ModuleName "Teste1" kcenv = insertTypeKind (toId (Ident "MyList")) (KindFn KindStar KindStar) (insertClassKind myeqid myeqkind emptyEnv) varenv = [nilassump, consassump, eqassump] classes = [myeqconstr] insts = [myeqinstconstr, insteqmylist, instordmylist] -- definition for data type MyList tcmylist = TyApp (TyCon (UnQual (Ident "MyList"))) tva idnil = toId (Ident "Nil") idcons = toId (Ident "Cons") nilassump = idnil :>: (TyForall Nothing [] tcmylist) consassump = idcons :>: (TyForall Nothing [] (tva +-> tcmylist +-> tcmylist)) ideq = toId (Ident "Eq") idord = toId (Ident "Ord") insteqmylist = Inst ideq [tcmylist] [] instordmylist = Inst idord [tcmylist] [] -- definition of some synonyms syn1 = (TyCon (UnQual (Ident "String")), TyList (TyCon (UnQual (Ident ("Char"))))) syn2 = (TyApp (TyCon (UnQual (Ident "Vec"))) tva, TyList (TyCon (UnQual (Ident "Int")))) -- definition of a label nid = toId (Ident "name") tn = TyForall Nothing [] tbool +-> tva lbl = (toId (Ident "R"), [(nid, tn)]) -- definitions for class myeq myeqid = toId (Ident "MyEq") myeqkind = KindFn KindStar KindStar myeqconstr = Class myeqid [tva, tvb] [] [eqassump] [] tva = TyVar (Ident "a") tvb = TyVar (Ident "b") eqsym = Symbol "=:=" cme = ClassA (UnQual (Ident "MyEq")) [tva, tvb] eqassump = (toId eqsym) :>: TyForall Nothing [cme] (tva +-> (tvb +-> tbool)) tbool = TyCon (UnQual (Ident "Bool")) -- definitions for instance MyEq Int Float myeqinstconstr = Inst myeqid [tint, tfloat] [] tint = TyCon (UnQual (Ident "Int")) tfloat = TyCon (UnQual (Ident "Float")) x +-> y = TyFun x y
rodrigogribeiro/mptc
test/Cases/IfaceWriterTest.hs
bsd-3-clause
2,181
0
13
446
806
433
373
47
1
{- Dev: representation of a device Part of Mackerel: a strawman device definition DSL for Barrelfish Copyright (c) 2007, 2008, ETH Zurich. All rights reserved. This file is distributed under the terms in the attached LICENSE file. If you do not find this file, copies can be found by writing to: ETH Zurich D-INFK, Universitaetstrasse 6, CH-8092 Zurich. Attn: Systems Group. -} module Dev where import MackerelParser import qualified TypeTable as TT import qualified RegisterTable as RT import qualified Space {-------------------------------------------------------------------- --------------------------------------------------------------------} data Rec = Rec { name :: String, desc :: String, args :: [ AST ], types ::[ TT.Rec ], all_types ::[ TT.Rec ], registers ::[ RT.Rec ], spaces :: [ Space.Rec ], imports :: [ String ] } -- Create a device record from a list of DeviceFile ASTs from the Parser. The first is the actual device file, while the rest are imports make_dev :: DeviceFile -> [DeviceFile] -> Rec make_dev df@(DeviceFile (Device n bitorder al d decls) imps) dfl = let ttbl = TT.make_rtypetable df stbl = Space.builtins ++ [ rec | (SpaceDecl rec) <- decls ] rtbl = RT.make_table ttbl decls n bitorder stbl in Rec { name = n, desc = d, args = al, types = ttbl, all_types = ttbl ++ ( concat $ map TT.make_rtypetable dfl ), registers = rtbl, spaces = stbl, imports = imps } shdws :: Rec -> [ RT.Shadow ] shdws dev = RT.get_shadows (registers dev)
kishoredbn/barrelfish
tools/mackerel/Dev.hs
mit
1,761
0
14
537
323
191
132
28
1
module Beta where import Data.List sum' [] = 0 sum' (x:xs) = x + sum' xs add 0 a = a add a b = add (pred a) (succ b) add' a 0 = a add' a b | b > 0 = add' (succ a) (pred b) | otherwise = add' (pred a) (succ b) drop' _ [] = [] drop' 0 xs = xs drop' n (x:xs) = drop' (pred n) xs drop2 _ [] = [] drop2 0 xs = xs drop2 n (a:b:xs) = drop2 (pred n) xs --drop2 2 [1,2,3,4,5,6,] = drop2 1 [3,4,5,6] -- d 0 [1,2,3] = [1,2,3] -- d n [] = [] -- d 1 [1,2,3] = d (pred n) () -- 1:[2,3]= [1,2,3] -- nDiv 8 2 = -- add 0 3 = 3 -- add 3 5 = add (pred 3) (succ 5) -- add 0 8 = 8 sub a 0 = a sub a b = sub (pred a) (pred b) mul a 0 = 0 mul a 1 = a mul a b = add a (mul a (sub b 1)) -- mul 3 5 = add 3 (mul 3 (4)) -- MUL 3 6 = + 3 (* 3 (5)) sol1 0 = 0 sol1 n = n + (sol1 $ pred n) mutlak x | x >= 0 = x | otherwise = (-x) sol2 lim = iter 1 0 where iter i res | i > lim = res | 0 /= rem i 2 = iter (succ i) (res + (mutlak $ i + 50)) | otherwise = iter (succ i) (res + (mutlak $ 50 - i)) basis6 n | n < 6 = [n] | otherwise = (rem n 6) : (basis6 $ div n 6) sol3 i = rev $ basis6 i where rev [] = 0 rev (x:xs) = x + 10* (rev xs) numcol n | n < 10 = [n] | otherwise = (numcol $ div n 10) ++ [(rem n 10)] prod [] = 1 prod (x:xs) = x * prod xs fact 0 = 1 fact i = prod [1..i] map' f [] = [] map' f (x:xs) = f x : map' f xs fakDig i = sum' $ map' fact $ numcol i sol4 lim = sum' $ map' fakDig [1..lim] last' (x: []) = x last' (x:xs) = last' xs delete' e [] = [] delete' e (x:xs) | e == x = delete' e xs | otherwise = x : delete' e xs distinct [] = [] distinct (x:xs) = x : distinct (delete' x xs) scanl1' f [] = [] scanl1' f (x:xs) = iter x xs where iter res [] = res : [] iter res (k:ks) = res : iter (f res k) ks -- primitives : Num, String, Bool => + - * ^ div rem -- collections : list & tuples ++ : -- global & local scope -- definings functions -> if/guards/pattern matching -- TOTAL cuma 10 hal => 1 jam
squest/Zenx-trainer-training
haskell/beta.hs
epl-1.0
2,023
0
13
648
1,086
541
545
60
2
{- Copyright (C) 2006-2010 John MacFarlane <[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 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} {- | Module : Text.Pandoc.Parsing Copyright : Copyright (C) 2006-2010 John MacFarlane License : GNU GPL, version 2 or above Maintainer : John MacFarlane <[email protected]> Stability : alpha Portability : portable A utility library with parsers used in pandoc readers. -} module Text.Pandoc.Parsing ( (>>~), anyLine, many1Till, notFollowedBy', oneOfStrings, spaceChar, nonspaceChar, skipSpaces, blankline, blanklines, enclosed, stringAnyCase, parseFromString, lineClump, charsInBalanced, romanNumeral, emailAddress, uri, withHorizDisplacement, nullBlock, failIfStrict, failUnlessLHS, escaped, anyOrderedListMarker, orderedListMarker, charRef, tableWith, gridTableWith, readWith, testStringWith, ParserState (..), defaultParserState, HeaderType (..), ParserContext (..), QuoteContext (..), NoteTable, KeyTable, Key, toKey, fromKey, lookupKeySrc, smartPunctuation, macro, applyMacros' ) where import Text.Pandoc.Definition import Text.Pandoc.Generic import qualified Text.Pandoc.UTF8 as UTF8 (putStrLn) import Text.ParserCombinators.Parsec import Text.Pandoc.CharacterReferences ( characterReference ) import Data.Char ( toLower, toUpper, ord, isAscii, isAlphaNum, isDigit, isPunctuation ) import Data.List ( intercalate, transpose ) import Network.URI ( parseURI, URI (..), isAllowedInURI ) import Control.Monad ( join, liftM, guard ) import Text.Pandoc.Shared import qualified Data.Map as M import Text.TeXMath.Macros (applyMacros, Macro, parseMacroDefinitions) -- | Like >>, but returns the operation on the left. -- (Suggested by Tillmann Rendel on Haskell-cafe list.) (>>~) :: (Monad m) => m a -> m b -> m a a >>~ b = a >>= \x -> b >> return x -- | Parse any line of text anyLine :: GenParser Char st [Char] anyLine = manyTill anyChar newline -- | Like @manyTill@, but reads at least one item. many1Till :: GenParser tok st a -> GenParser tok st end -> GenParser tok st [a] many1Till p end = do first <- p rest <- manyTill p end return (first:rest) -- | A more general form of @notFollowedBy@. This one allows any -- type of parser to be specified, and succeeds only if that parser fails. -- It does not consume any input. notFollowedBy' :: Show b => GenParser a st b -> GenParser a st () notFollowedBy' p = try $ join $ do a <- try p return (unexpected (show a)) <|> return (return ()) -- (This version due to Andrew Pimlott on the Haskell mailing list.) -- | Parses one of a list of strings (tried in order). oneOfStrings :: [String] -> GenParser Char st String oneOfStrings listOfStrings = choice $ map (try . string) listOfStrings -- | Parses a space or tab. spaceChar :: CharParser st Char spaceChar = satisfy $ \c -> c == ' ' || c == '\t' -- | Parses a nonspace, nonnewline character. nonspaceChar :: CharParser st Char nonspaceChar = satisfy $ \x -> x /= '\t' && x /= '\n' && x /= ' ' && x /= '\r' -- | Skips zero or more spaces or tabs. skipSpaces :: GenParser Char st () skipSpaces = skipMany spaceChar -- | Skips zero or more spaces or tabs, then reads a newline. blankline :: GenParser Char st Char blankline = try $ skipSpaces >> newline -- | Parses one or more blank lines and returns a string of newlines. blanklines :: GenParser Char st [Char] blanklines = many1 blankline -- | Parses material enclosed between start and end parsers. enclosed :: GenParser Char st t -- ^ start parser -> GenParser Char st end -- ^ end parser -> GenParser Char st a -- ^ content parser (to be used repeatedly) -> GenParser Char st [a] enclosed start end parser = try $ start >> notFollowedBy space >> many1Till parser end -- | Parse string, case insensitive. stringAnyCase :: [Char] -> CharParser st String stringAnyCase [] = string "" stringAnyCase (x:xs) = do firstChar <- char (toUpper x) <|> char (toLower x) rest <- stringAnyCase xs return (firstChar:rest) -- | Parse contents of 'str' using 'parser' and return result. parseFromString :: GenParser tok st a -> [tok] -> GenParser tok st a parseFromString parser str = do oldPos <- getPosition oldInput <- getInput setInput str result <- parser setInput oldInput setPosition oldPos return result -- | Parse raw line block up to and including blank lines. lineClump :: GenParser Char st String lineClump = blanklines <|> (many1 (notFollowedBy blankline >> anyLine) >>= return . unlines) -- | Parse a string of characters between an open character -- and a close character, including text between balanced -- pairs of open and close, which must be different. For example, -- @charsInBalanced '(' ')' anyChar@ will parse "(hello (there))" -- and return "hello (there)". charsInBalanced :: Char -> Char -> GenParser Char st Char -> GenParser Char st String charsInBalanced open close parser = try $ do char open let isDelim c = c == open || c == close raw <- many $ many1 (notFollowedBy (satisfy isDelim) >> parser) <|> (do res <- charsInBalanced open close parser return $ [open] ++ res ++ [close]) char close return $ concat raw -- old charsInBalanced would be: -- charsInBalanced open close (noneOf "\n" <|> char '\n' >> notFollowedBy blankline) -- old charsInBalanced' would be: -- charsInBalanced open close anyChar -- Auxiliary functions for romanNumeral: lowercaseRomanDigits :: [Char] lowercaseRomanDigits = ['i','v','x','l','c','d','m'] uppercaseRomanDigits :: [Char] uppercaseRomanDigits = map toUpper lowercaseRomanDigits -- | Parses a roman numeral (uppercase or lowercase), returns number. romanNumeral :: Bool -- ^ Uppercase if true -> GenParser Char st Int romanNumeral upperCase = do let romanDigits = if upperCase then uppercaseRomanDigits else lowercaseRomanDigits lookAhead $ oneOf romanDigits let [one, five, ten, fifty, hundred, fivehundred, thousand] = map char romanDigits thousands <- many thousand >>= (return . (1000 *) . length) ninehundreds <- option 0 $ try $ hundred >> thousand >> return 900 fivehundreds <- many fivehundred >>= (return . (500 *) . length) fourhundreds <- option 0 $ try $ hundred >> fivehundred >> return 400 hundreds <- many hundred >>= (return . (100 *) . length) nineties <- option 0 $ try $ ten >> hundred >> return 90 fifties <- many fifty >>= (return . (50 *) . length) forties <- option 0 $ try $ ten >> fifty >> return 40 tens <- many ten >>= (return . (10 *) . length) nines <- option 0 $ try $ one >> ten >> return 9 fives <- many five >>= (return . (5 *) . length) fours <- option 0 $ try $ one >> five >> return 4 ones <- many one >>= (return . length) let total = thousands + ninehundreds + fivehundreds + fourhundreds + hundreds + nineties + fifties + forties + tens + nines + fives + fours + ones if total == 0 then fail "not a roman numeral" else return total -- Parsers for email addresses and URIs emailChar :: GenParser Char st Char emailChar = alphaNum <|> satisfy (\c -> c == '-' || c == '+' || c == '_' || c == '.') domainChar :: GenParser Char st Char domainChar = alphaNum <|> char '-' domain :: GenParser Char st [Char] domain = do first <- many1 domainChar dom <- many1 $ try (char '.' >> many1 domainChar ) return $ intercalate "." (first:dom) -- | Parses an email address; returns original and corresponding -- escaped mailto: URI. emailAddress :: GenParser Char st (String, String) emailAddress = try $ do firstLetter <- alphaNum restAddr <- many emailChar let addr = firstLetter:restAddr char '@' dom <- domain let full = addr ++ '@':dom return (full, escapeURI $ "mailto:" ++ full) -- | Parses a URI. Returns pair of original and URI-escaped version. uri :: GenParser Char st (String, String) uri = try $ do let protocols = [ "http:", "https:", "ftp:", "file:", "mailto:", "news:", "telnet:" ] lookAhead $ oneOfStrings protocols -- Scan non-ascii characters and ascii characters allowed in a URI. -- We allow punctuation except when followed by a space, since -- we don't want the trailing '.' in 'http://google.com.' let innerPunct = try $ satisfy isPunctuation >>~ notFollowedBy (newline <|> spaceChar) let uriChar = innerPunct <|> satisfy (\c -> not (isPunctuation c) && (not (isAscii c) || isAllowedInURI c)) -- We want to allow -- http://en.wikipedia.org/wiki/State_of_emergency_(disambiguation) -- as a URL, while NOT picking up the closing paren in -- (http://wikipedia.org) -- So we include balanced parens in the URL. let inParens = try $ do char '(' res <- many uriChar char ')' return $ '(' : res ++ ")" str <- liftM concat $ many1 $ inParens <|> count 1 (innerPunct <|> uriChar) -- now see if they amount to an absolute URI case parseURI (escapeURI str) of Just uri' -> if uriScheme uri' `elem` protocols then return (str, show uri') else fail "not a URI" Nothing -> fail "not a URI" -- | Applies a parser, returns tuple of its results and its horizontal -- displacement (the difference between the source column at the end -- and the source column at the beginning). Vertical displacement -- (source row) is ignored. withHorizDisplacement :: GenParser Char st a -- ^ Parser to apply -> GenParser Char st (a, Int) -- ^ (result, displacement) withHorizDisplacement parser = do pos1 <- getPosition result <- parser pos2 <- getPosition return (result, sourceColumn pos2 - sourceColumn pos1) -- | Parses a character and returns 'Null' (so that the parser can move on -- if it gets stuck). nullBlock :: GenParser Char st Block nullBlock = anyChar >> return Null -- | Fail if reader is in strict markdown syntax mode. failIfStrict :: GenParser a ParserState () failIfStrict = do state <- getState if stateStrict state then fail "strict mode" else return () -- | Fail unless we're in literate haskell mode. failUnlessLHS :: GenParser tok ParserState () failUnlessLHS = do state <- getState if stateLiterateHaskell state then return () else fail "Literate haskell feature" -- | Parses backslash, then applies character parser. escaped :: GenParser Char st Char -- ^ Parser for character to escape -> GenParser Char st Char escaped parser = try $ char '\\' >> parser -- | Parses an uppercase roman numeral and returns (UpperRoman, number). upperRoman :: GenParser Char st (ListNumberStyle, Int) upperRoman = do num <- romanNumeral True return (UpperRoman, num) -- | Parses a lowercase roman numeral and returns (LowerRoman, number). lowerRoman :: GenParser Char st (ListNumberStyle, Int) lowerRoman = do num <- romanNumeral False return (LowerRoman, num) -- | Parses a decimal numeral and returns (Decimal, number). decimal :: GenParser Char st (ListNumberStyle, Int) decimal = do num <- many1 digit return (Decimal, read num) -- | Parses a '@' and optional label and -- returns (DefaultStyle, [next example number]). The next -- example number is incremented in parser state, and the label -- (if present) is added to the label table. exampleNum :: GenParser Char ParserState (ListNumberStyle, Int) exampleNum = do char '@' lab <- many (alphaNum <|> satisfy (\c -> c == '_' || c == '-')) st <- getState let num = stateNextExample st let newlabels = if null lab then stateExamples st else M.insert lab num $ stateExamples st updateState $ \s -> s{ stateNextExample = num + 1 , stateExamples = newlabels } return (Example, num) -- | Parses a '#' returns (DefaultStyle, 1). defaultNum :: GenParser Char st (ListNumberStyle, Int) defaultNum = do char '#' return (DefaultStyle, 1) -- | Parses a lowercase letter and returns (LowerAlpha, number). lowerAlpha :: GenParser Char st (ListNumberStyle, Int) lowerAlpha = do ch <- oneOf ['a'..'z'] return (LowerAlpha, ord ch - ord 'a' + 1) -- | Parses an uppercase letter and returns (UpperAlpha, number). upperAlpha :: GenParser Char st (ListNumberStyle, Int) upperAlpha = do ch <- oneOf ['A'..'Z'] return (UpperAlpha, ord ch - ord 'A' + 1) -- | Parses a roman numeral i or I romanOne :: GenParser Char st (ListNumberStyle, Int) romanOne = (char 'i' >> return (LowerRoman, 1)) <|> (char 'I' >> return (UpperRoman, 1)) -- | Parses an ordered list marker and returns list attributes. anyOrderedListMarker :: GenParser Char ParserState ListAttributes anyOrderedListMarker = choice $ [delimParser numParser | delimParser <- [inPeriod, inOneParen, inTwoParens], numParser <- [decimal, exampleNum, defaultNum, romanOne, lowerAlpha, lowerRoman, upperAlpha, upperRoman]] -- | Parses a list number (num) followed by a period, returns list attributes. inPeriod :: GenParser Char st (ListNumberStyle, Int) -> GenParser Char st ListAttributes inPeriod num = try $ do (style, start) <- num char '.' let delim = if style == DefaultStyle then DefaultDelim else Period return (start, style, delim) -- | Parses a list number (num) followed by a paren, returns list attributes. inOneParen :: GenParser Char st (ListNumberStyle, Int) -> GenParser Char st ListAttributes inOneParen num = try $ do (style, start) <- num char ')' return (start, style, OneParen) -- | Parses a list number (num) enclosed in parens, returns list attributes. inTwoParens :: GenParser Char st (ListNumberStyle, Int) -> GenParser Char st ListAttributes inTwoParens num = try $ do char '(' (style, start) <- num char ')' return (start, style, TwoParens) -- | Parses an ordered list marker with a given style and delimiter, -- returns number. orderedListMarker :: ListNumberStyle -> ListNumberDelim -> GenParser Char ParserState Int orderedListMarker style delim = do let num = defaultNum <|> -- # can continue any kind of list case style of DefaultStyle -> decimal Example -> exampleNum Decimal -> decimal UpperRoman -> upperRoman LowerRoman -> lowerRoman UpperAlpha -> upperAlpha LowerAlpha -> lowerAlpha let context = case delim of DefaultDelim -> inPeriod Period -> inPeriod OneParen -> inOneParen TwoParens -> inTwoParens (start, _, _) <- context num return start -- | Parses a character reference and returns a Str element. charRef :: GenParser Char st Inline charRef = do c <- characterReference return $ Str [c] -- | Parse a table using 'headerParser', 'rowParser', -- 'lineParser', and 'footerParser'. tableWith :: GenParser Char ParserState ([[Block]], [Alignment], [Int]) -> ([Int] -> GenParser Char ParserState [[Block]]) -> GenParser Char ParserState sep -> GenParser Char ParserState end -> GenParser Char ParserState [Inline] -> GenParser Char ParserState Block tableWith headerParser rowParser lineParser footerParser captionParser = try $ do caption' <- option [] captionParser (heads, aligns, indices) <- headerParser lines' <- rowParser indices `sepEndBy` lineParser footerParser caption <- if null caption' then option [] captionParser else return caption' state <- getState let numColumns = stateColumns state let widths = widthsFromIndices numColumns indices return $ Table caption aligns widths heads lines' -- Calculate relative widths of table columns, based on indices widthsFromIndices :: Int -- Number of columns on terminal -> [Int] -- Indices -> [Double] -- Fractional relative sizes of columns widthsFromIndices _ [] = [] widthsFromIndices numColumns' indices = let numColumns = max numColumns' (if null indices then 0 else last indices) lengths' = zipWith (-) indices (0:indices) lengths = reverse $ case reverse lengths' of [] -> [] [x] -> [x] -- compensate for the fact that intercolumn -- spaces are counted in widths of all columns -- but the last... (x:y:zs) -> if x < y && y - x <= 2 then y:y:zs else x:y:zs totLength = sum lengths quotient = if totLength > numColumns then fromIntegral totLength else fromIntegral numColumns fracs = map (\l -> (fromIntegral l) / quotient) lengths in tail fracs -- Parse a grid table: starts with row of '-' on top, then header -- (which may be grid), then the rows, -- which may be grid, separated by blank lines, and -- ending with a footer (dashed line followed by blank line). gridTableWith :: GenParser Char ParserState Block -- ^ Block parser -> GenParser Char ParserState [Inline] -- ^ Caption parser -> Bool -- ^ Headerless table -> GenParser Char ParserState Block gridTableWith block tableCaption headless = tableWith (gridTableHeader headless block) (gridTableRow block) (gridTableSep '-') gridTableFooter tableCaption gridTableSplitLine :: [Int] -> String -> [String] gridTableSplitLine indices line = map removeFinalBar $ tail $ splitStringByIndices (init indices) $ removeTrailingSpace line gridPart :: Char -> GenParser Char st (Int, Int) gridPart ch = do dashes <- many1 (char ch) char '+' return (length dashes, length dashes + 1) gridDashedLines :: Char -> GenParser Char st [(Int,Int)] gridDashedLines ch = try $ char '+' >> many1 (gridPart ch) >>~ blankline removeFinalBar :: String -> String removeFinalBar = reverse . dropWhile (`elem` " \t") . dropWhile (=='|') . reverse -- | Separator between rows of grid table. gridTableSep :: Char -> GenParser Char ParserState Char gridTableSep ch = try $ gridDashedLines ch >> return '\n' -- | Parse header for a grid table. gridTableHeader :: Bool -- ^ Headerless table -> GenParser Char ParserState Block -> GenParser Char ParserState ([[Block]], [Alignment], [Int]) gridTableHeader headless block = try $ do optional blanklines dashes <- gridDashedLines '-' rawContent <- if headless then return $ repeat "" else many1 (notFollowedBy (gridTableSep '=') >> char '|' >> many1Till anyChar newline) if headless then return () else gridTableSep '=' >> return () let lines' = map snd dashes let indices = scanl (+) 0 lines' let aligns = replicate (length lines') AlignDefault -- RST does not have a notion of alignments let rawHeads = if headless then replicate (length dashes) "" else map (intercalate " ") $ transpose $ map (gridTableSplitLine indices) rawContent heads <- mapM (parseFromString $ many block) $ map removeLeadingTrailingSpace rawHeads return (heads, aligns, indices) gridTableRawLine :: [Int] -> GenParser Char ParserState [String] gridTableRawLine indices = do char '|' line <- many1Till anyChar newline return (gridTableSplitLine indices line) -- | Parse row of grid table. gridTableRow :: GenParser Char ParserState Block -> [Int] -> GenParser Char ParserState [[Block]] gridTableRow block indices = do colLines <- many1 (gridTableRawLine indices) let cols = map ((++ "\n") . unlines . removeOneLeadingSpace) $ transpose colLines mapM (liftM compactifyCell . parseFromString (many block)) cols removeOneLeadingSpace :: [String] -> [String] removeOneLeadingSpace xs = if all startsWithSpace xs then map (drop 1) xs else xs where startsWithSpace "" = True startsWithSpace (y:_) = y == ' ' compactifyCell :: [Block] -> [Block] compactifyCell bs = head $ compactify [bs] -- | Parse footer for a grid table. gridTableFooter :: GenParser Char ParserState [Char] gridTableFooter = blanklines --- -- | Parse a string with a given parser and state. readWith :: GenParser t ParserState a -- ^ parser -> ParserState -- ^ initial state -> [t] -- ^ input -> a readWith parser state input = case runParser parser state "source" input of Left err -> error $ "\nError:\n" ++ show err Right result -> result -- | Parse a string with @parser@ (for testing). testStringWith :: (Show a) => GenParser Char ParserState a -> String -> IO () testStringWith parser str = UTF8.putStrLn $ show $ readWith parser defaultParserState str -- | Parsing options. data ParserState = ParserState { stateParseRaw :: Bool, -- ^ Parse raw HTML and LaTeX? stateParserContext :: ParserContext, -- ^ Inside list? stateQuoteContext :: QuoteContext, -- ^ Inside quoted environment? stateLastStrPos :: Maybe SourcePos, -- ^ Position after last str parsed stateKeys :: KeyTable, -- ^ List of reference keys stateCitations :: [String], -- ^ List of available citations stateNotes :: NoteTable, -- ^ List of notes stateTabStop :: Int, -- ^ Tab stop stateStandalone :: Bool, -- ^ Parse bibliographic info? stateTitle :: [Inline], -- ^ Title of document stateAuthors :: [[Inline]], -- ^ Authors of document stateDate :: [Inline], -- ^ Date of document stateStrict :: Bool, -- ^ Use strict markdown syntax? stateSmart :: Bool, -- ^ Use smart typography? stateOldDashes :: Bool, -- ^ Use pandoc <= 1.8.2.1 behavior -- in parsing dashes; -- is em-dash; -- before numeral is en-dash stateLiterateHaskell :: Bool, -- ^ Treat input as literate haskell stateColumns :: Int, -- ^ Number of columns in terminal stateHeaderTable :: [HeaderType], -- ^ Ordered list of header types used stateIndentedCodeClasses :: [String], -- ^ Classes to use for indented code blocks stateNextExample :: Int, -- ^ Number of next example stateExamples :: M.Map String Int, -- ^ Map from example labels to numbers stateHasChapters :: Bool, -- ^ True if \chapter encountered stateApplyMacros :: Bool, -- ^ Apply LaTeX macros? stateMacros :: [Macro] -- ^ List of macros defined so far } deriving Show defaultParserState :: ParserState defaultParserState = ParserState { stateParseRaw = False, stateParserContext = NullState, stateQuoteContext = NoQuote, stateLastStrPos = Nothing, stateKeys = M.empty, stateCitations = [], stateNotes = [], stateTabStop = 4, stateStandalone = False, stateTitle = [], stateAuthors = [], stateDate = [], stateStrict = False, stateSmart = False, stateOldDashes = False, stateLiterateHaskell = False, stateColumns = 80, stateHeaderTable = [], stateIndentedCodeClasses = [], stateNextExample = 1, stateExamples = M.empty, stateHasChapters = False, stateApplyMacros = True, stateMacros = []} data HeaderType = SingleHeader Char -- ^ Single line of characters underneath | DoubleHeader Char -- ^ Lines of characters above and below deriving (Eq, Show) data ParserContext = ListItemState -- ^ Used when running parser on list item contents | NullState -- ^ Default state deriving (Eq, Show) data QuoteContext = InSingleQuote -- ^ Used when parsing inside single quotes | InDoubleQuote -- ^ Used when parsing inside double quotes | NoQuote -- ^ Used when not parsing inside quotes deriving (Eq, Show) type NoteTable = [(String, String)] newtype Key = Key [Inline] deriving (Show, Read, Eq, Ord) toKey :: [Inline] -> Key toKey = Key . bottomUp lowercase where lowercase :: Inline -> Inline lowercase (Str xs) = Str (map toLower xs) lowercase (Math t xs) = Math t (map toLower xs) lowercase (Code attr xs) = Code attr (map toLower xs) lowercase (RawInline f xs) = RawInline f (map toLower xs) lowercase LineBreak = Space lowercase x = x fromKey :: Key -> [Inline] fromKey (Key xs) = xs type KeyTable = M.Map Key Target -- | Look up key in key table and return target object. lookupKeySrc :: KeyTable -- ^ Key table -> Key -- ^ Key -> Maybe Target lookupKeySrc table key = case M.lookup key table of Nothing -> Nothing Just src -> Just src -- | Fail unless we're in "smart typography" mode. failUnlessSmart :: GenParser tok ParserState () failUnlessSmart = getState >>= guard . stateSmart smartPunctuation :: GenParser Char ParserState Inline -> GenParser Char ParserState Inline smartPunctuation inlineParser = do failUnlessSmart choice [ quoted inlineParser, apostrophe, dash, ellipses ] apostrophe :: GenParser Char ParserState Inline apostrophe = (char '\'' <|> char '\8217') >> return (Str "\x2019") quoted :: GenParser Char ParserState Inline -> GenParser Char ParserState Inline quoted inlineParser = doubleQuoted inlineParser <|> singleQuoted inlineParser withQuoteContext :: QuoteContext -> (GenParser Char ParserState Inline) -> GenParser Char ParserState Inline withQuoteContext context parser = do oldState <- getState let oldQuoteContext = stateQuoteContext oldState setState oldState { stateQuoteContext = context } result <- parser newState <- getState setState newState { stateQuoteContext = oldQuoteContext } return result singleQuoted :: GenParser Char ParserState Inline -> GenParser Char ParserState Inline singleQuoted inlineParser = try $ do singleQuoteStart withQuoteContext InSingleQuote $ many1Till inlineParser singleQuoteEnd >>= return . Quoted SingleQuote . normalizeSpaces doubleQuoted :: GenParser Char ParserState Inline -> GenParser Char ParserState Inline doubleQuoted inlineParser = try $ do doubleQuoteStart withQuoteContext InDoubleQuote $ do contents <- manyTill inlineParser doubleQuoteEnd return . Quoted DoubleQuote . normalizeSpaces $ contents failIfInQuoteContext :: QuoteContext -> GenParser tok ParserState () failIfInQuoteContext context = do st <- getState if stateQuoteContext st == context then fail "already inside quotes" else return () charOrRef :: [Char] -> GenParser Char st Char charOrRef cs = oneOf cs <|> try (do c <- characterReference guard (c `elem` cs) return c) singleQuoteStart :: GenParser Char ParserState () singleQuoteStart = do failIfInQuoteContext InSingleQuote pos <- getPosition st <- getState -- single quote start can't be right after str guard $ stateLastStrPos st /= Just pos try $ do charOrRef "'\8216\145" notFollowedBy (oneOf ")!],;:-? \t\n") notFollowedBy (char '.') <|> lookAhead (string "..." >> return ()) notFollowedBy (try (oneOfStrings ["s","t","m","ve","ll","re"] >> satisfy (not . isAlphaNum))) -- possess/contraction return () singleQuoteEnd :: GenParser Char st () singleQuoteEnd = try $ do charOrRef "'\8217\146" notFollowedBy alphaNum doubleQuoteStart :: GenParser Char ParserState () doubleQuoteStart = do failIfInQuoteContext InDoubleQuote try $ do charOrRef "\"\8220\147" notFollowedBy (satisfy (\c -> c == ' ' || c == '\t' || c == '\n')) doubleQuoteEnd :: GenParser Char st () doubleQuoteEnd = do charOrRef "\"\8221\148" return () ellipses :: GenParser Char st Inline ellipses = do try (charOrRef "\8230\133") <|> try (string "..." >> return '…') return (Str "\8230") dash :: GenParser Char ParserState Inline dash = do oldDashes <- stateOldDashes `fmap` getState if oldDashes then emDashOld <|> enDashOld else Str `fmap` (hyphenDash <|> emDash <|> enDash) -- Two hyphens = en-dash, three = em-dash hyphenDash :: GenParser Char st String hyphenDash = do try $ string "--" option "\8211" (char '-' >> return "\8212") emDash :: GenParser Char st String emDash = do try (charOrRef "\8212\151") return "\8212" enDash :: GenParser Char st String enDash = do try (charOrRef "\8212\151") return "\8211" enDashOld :: GenParser Char st Inline enDashOld = do try (charOrRef "\8211\150") <|> try (char '-' >> lookAhead (satisfy isDigit) >> return '–') return (Str "\8211") emDashOld :: GenParser Char st Inline emDashOld = do try (charOrRef "\8212\151") <|> (try $ string "--" >> optional (char '-') >> return '-') return (Str "\8212") -- -- Macros -- -- | Parse a \newcommand or \renewcommand macro definition. macro :: GenParser Char ParserState Block macro = do getState >>= guard . stateApplyMacros inp <- getInput case parseMacroDefinitions inp of ([], _) -> pzero (ms, rest) -> do count (length inp - length rest) anyChar updateState $ \st -> st { stateMacros = ms ++ stateMacros st } return Null -- | Apply current macros to string. applyMacros' :: String -> GenParser Char ParserState String applyMacros' target = do apply <- liftM stateApplyMacros getState if apply then do macros <- liftM stateMacros getState return $ applyMacros macros target else return target
sol/pandoc
src/Text/Pandoc/Parsing.hs
gpl-2.0
33,058
0
21
9,993
7,663
3,957
3,706
624
10
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.CloudWatch.Types.Product -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.AWS.CloudWatch.Types.Product where import Network.AWS.CloudWatch.Types.Sum import Network.AWS.Prelude -- | The 'AlarmHistoryItem' data type contains descriptive information about -- the history of a specific alarm. If you call DescribeAlarmHistory, -- Amazon CloudWatch returns this data type as part of the -- DescribeAlarmHistoryResult data type. -- -- /See:/ 'alarmHistoryItem' smart constructor. data AlarmHistoryItem = AlarmHistoryItem' { _ahiAlarmName :: !(Maybe Text) , _ahiHistoryItemType :: !(Maybe HistoryItemType) , _ahiHistoryData :: !(Maybe Text) , _ahiHistorySummary :: !(Maybe Text) , _ahiTimestamp :: !(Maybe ISO8601) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'AlarmHistoryItem' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ahiAlarmName' -- -- * 'ahiHistoryItemType' -- -- * 'ahiHistoryData' -- -- * 'ahiHistorySummary' -- -- * 'ahiTimestamp' alarmHistoryItem :: AlarmHistoryItem alarmHistoryItem = AlarmHistoryItem' { _ahiAlarmName = Nothing , _ahiHistoryItemType = Nothing , _ahiHistoryData = Nothing , _ahiHistorySummary = Nothing , _ahiTimestamp = Nothing } -- | The descriptive name for the alarm. ahiAlarmName :: Lens' AlarmHistoryItem (Maybe Text) ahiAlarmName = lens _ahiAlarmName (\ s a -> s{_ahiAlarmName = a}); -- | The type of alarm history item. ahiHistoryItemType :: Lens' AlarmHistoryItem (Maybe HistoryItemType) ahiHistoryItemType = lens _ahiHistoryItemType (\ s a -> s{_ahiHistoryItemType = a}); -- | Machine-readable data about the alarm in JSON format. ahiHistoryData :: Lens' AlarmHistoryItem (Maybe Text) ahiHistoryData = lens _ahiHistoryData (\ s a -> s{_ahiHistoryData = a}); -- | A human-readable summary of the alarm history. ahiHistorySummary :: Lens' AlarmHistoryItem (Maybe Text) ahiHistorySummary = lens _ahiHistorySummary (\ s a -> s{_ahiHistorySummary = a}); -- | The time stamp for the alarm history item. Amazon CloudWatch uses -- Coordinated Universal Time (UTC) when returning time stamps, which do -- not accommodate seasonal adjustments such as daylight savings time. For -- more information, see -- <http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/cloudwatch_concepts.html#about_timestamp Time stamps> -- in the /Amazon CloudWatch Developer Guide/. ahiTimestamp :: Lens' AlarmHistoryItem (Maybe UTCTime) ahiTimestamp = lens _ahiTimestamp (\ s a -> s{_ahiTimestamp = a}) . mapping _Time; instance FromXML AlarmHistoryItem where parseXML x = AlarmHistoryItem' <$> (x .@? "AlarmName") <*> (x .@? "HistoryItemType") <*> (x .@? "HistoryData") <*> (x .@? "HistorySummary") <*> (x .@? "Timestamp") -- | The 'Datapoint' data type encapsulates the statistical data that Amazon -- CloudWatch computes from metric data. -- -- /See:/ 'datapoint' smart constructor. data Datapoint = Datapoint' { _dSampleCount :: !(Maybe Double) , _dMaximum :: !(Maybe Double) , _dAverage :: !(Maybe Double) , _dMinimum :: !(Maybe Double) , _dSum :: !(Maybe Double) , _dUnit :: !(Maybe StandardUnit) , _dTimestamp :: !(Maybe ISO8601) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'Datapoint' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dSampleCount' -- -- * 'dMaximum' -- -- * 'dAverage' -- -- * 'dMinimum' -- -- * 'dSum' -- -- * 'dUnit' -- -- * 'dTimestamp' datapoint :: Datapoint datapoint = Datapoint' { _dSampleCount = Nothing , _dMaximum = Nothing , _dAverage = Nothing , _dMinimum = Nothing , _dSum = Nothing , _dUnit = Nothing , _dTimestamp = Nothing } -- | The number of metric values that contributed to the aggregate value of -- this datapoint. dSampleCount :: Lens' Datapoint (Maybe Double) dSampleCount = lens _dSampleCount (\ s a -> s{_dSampleCount = a}); -- | The maximum of the metric value used for the datapoint. dMaximum :: Lens' Datapoint (Maybe Double) dMaximum = lens _dMaximum (\ s a -> s{_dMaximum = a}); -- | The average of metric values that correspond to the datapoint. dAverage :: Lens' Datapoint (Maybe Double) dAverage = lens _dAverage (\ s a -> s{_dAverage = a}); -- | The minimum metric value used for the datapoint. dMinimum :: Lens' Datapoint (Maybe Double) dMinimum = lens _dMinimum (\ s a -> s{_dMinimum = a}); -- | The sum of metric values used for the datapoint. dSum :: Lens' Datapoint (Maybe Double) dSum = lens _dSum (\ s a -> s{_dSum = a}); -- | The standard unit used for the datapoint. dUnit :: Lens' Datapoint (Maybe StandardUnit) dUnit = lens _dUnit (\ s a -> s{_dUnit = a}); -- | The time stamp used for the datapoint. Amazon CloudWatch uses -- Coordinated Universal Time (UTC) when returning time stamps, which do -- not accommodate seasonal adjustments such as daylight savings time. For -- more information, see -- <http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/cloudwatch_concepts.html#about_timestamp Time stamps> -- in the /Amazon CloudWatch Developer Guide/. dTimestamp :: Lens' Datapoint (Maybe UTCTime) dTimestamp = lens _dTimestamp (\ s a -> s{_dTimestamp = a}) . mapping _Time; instance FromXML Datapoint where parseXML x = Datapoint' <$> (x .@? "SampleCount") <*> (x .@? "Maximum") <*> (x .@? "Average") <*> (x .@? "Minimum") <*> (x .@? "Sum") <*> (x .@? "Unit") <*> (x .@? "Timestamp") -- | The 'Dimension' data type further expands on the identity of a metric -- using a Name, Value pair. -- -- For examples that use one or more dimensions, see PutMetricData. -- -- /See:/ 'dimension' smart constructor. data Dimension = Dimension' { _dName :: !Text , _dValue :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'Dimension' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dName' -- -- * 'dValue' dimension :: Text -- ^ 'dName' -> Text -- ^ 'dValue' -> Dimension dimension pName_ pValue_ = Dimension' { _dName = pName_ , _dValue = pValue_ } -- | The name of the dimension. dName :: Lens' Dimension Text dName = lens _dName (\ s a -> s{_dName = a}); -- | The value representing the dimension measurement dValue :: Lens' Dimension Text dValue = lens _dValue (\ s a -> s{_dValue = a}); instance FromXML Dimension where parseXML x = Dimension' <$> (x .@ "Name") <*> (x .@ "Value") instance ToQuery Dimension where toQuery Dimension'{..} = mconcat ["Name" =: _dName, "Value" =: _dValue] -- | The 'DimensionFilter' data type is used to filter ListMetrics results. -- -- /See:/ 'dimensionFilter' smart constructor. data DimensionFilter = DimensionFilter' { _dfValue :: !(Maybe Text) , _dfName :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DimensionFilter' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dfValue' -- -- * 'dfName' dimensionFilter :: Text -- ^ 'dfName' -> DimensionFilter dimensionFilter pName_ = DimensionFilter' { _dfValue = Nothing , _dfName = pName_ } -- | The value of the dimension to be matched. dfValue :: Lens' DimensionFilter (Maybe Text) dfValue = lens _dfValue (\ s a -> s{_dfValue = a}); -- | The dimension name to be matched. dfName :: Lens' DimensionFilter Text dfName = lens _dfName (\ s a -> s{_dfName = a}); instance ToQuery DimensionFilter where toQuery DimensionFilter'{..} = mconcat ["Value" =: _dfValue, "Name" =: _dfName] -- | The 'Metric' data type contains information about a specific metric. If -- you call ListMetrics, Amazon CloudWatch returns information contained by -- this data type. -- -- The example in the Examples section publishes two metrics named buffers -- and latency. Both metrics are in the examples namespace. Both metrics -- have two dimensions, InstanceID and InstanceType. -- -- /See:/ 'metric' smart constructor. data Metric = Metric' { _mMetricName :: !(Maybe Text) , _mNamespace :: !(Maybe Text) , _mDimensions :: !(Maybe [Dimension]) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'Metric' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mMetricName' -- -- * 'mNamespace' -- -- * 'mDimensions' metric :: Metric metric = Metric' { _mMetricName = Nothing , _mNamespace = Nothing , _mDimensions = Nothing } -- | The name of the metric. mMetricName :: Lens' Metric (Maybe Text) mMetricName = lens _mMetricName (\ s a -> s{_mMetricName = a}); -- | The namespace of the metric. mNamespace :: Lens' Metric (Maybe Text) mNamespace = lens _mNamespace (\ s a -> s{_mNamespace = a}); -- | A list of dimensions associated with the metric. mDimensions :: Lens' Metric [Dimension] mDimensions = lens _mDimensions (\ s a -> s{_mDimensions = a}) . _Default . _Coerce; instance FromXML Metric where parseXML x = Metric' <$> (x .@? "MetricName") <*> (x .@? "Namespace") <*> (x .@? "Dimensions" .!@ mempty >>= may (parseXMLList "member")) -- | The MetricAlarm data type represents an alarm. You can use -- PutMetricAlarm to create or update an alarm. -- -- /See:/ 'metricAlarm' smart constructor. data MetricAlarm = MetricAlarm' { _maAlarmName :: !(Maybe Text) , _maStateUpdatedTimestamp :: !(Maybe ISO8601) , _maPeriod :: !(Maybe Nat) , _maAlarmDescription :: !(Maybe Text) , _maEvaluationPeriods :: !(Maybe Nat) , _maMetricName :: !(Maybe Text) , _maNamespace :: !(Maybe Text) , _maComparisonOperator :: !(Maybe ComparisonOperator) , _maOKActions :: !(Maybe [Text]) , _maStateValue :: !(Maybe StateValue) , _maThreshold :: !(Maybe Double) , _maAlarmConfigurationUpdatedTimestamp :: !(Maybe ISO8601) , _maActionsEnabled :: !(Maybe Bool) , _maInsufficientDataActions :: !(Maybe [Text]) , _maStateReason :: !(Maybe Text) , _maStateReasonData :: !(Maybe Text) , _maDimensions :: !(Maybe [Dimension]) , _maAlarmARN :: !(Maybe Text) , _maAlarmActions :: !(Maybe [Text]) , _maUnit :: !(Maybe StandardUnit) , _maStatistic :: !(Maybe Statistic) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'MetricAlarm' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'maAlarmName' -- -- * 'maStateUpdatedTimestamp' -- -- * 'maPeriod' -- -- * 'maAlarmDescription' -- -- * 'maEvaluationPeriods' -- -- * 'maMetricName' -- -- * 'maNamespace' -- -- * 'maComparisonOperator' -- -- * 'maOKActions' -- -- * 'maStateValue' -- -- * 'maThreshold' -- -- * 'maAlarmConfigurationUpdatedTimestamp' -- -- * 'maActionsEnabled' -- -- * 'maInsufficientDataActions' -- -- * 'maStateReason' -- -- * 'maStateReasonData' -- -- * 'maDimensions' -- -- * 'maAlarmARN' -- -- * 'maAlarmActions' -- -- * 'maUnit' -- -- * 'maStatistic' metricAlarm :: MetricAlarm metricAlarm = MetricAlarm' { _maAlarmName = Nothing , _maStateUpdatedTimestamp = Nothing , _maPeriod = Nothing , _maAlarmDescription = Nothing , _maEvaluationPeriods = Nothing , _maMetricName = Nothing , _maNamespace = Nothing , _maComparisonOperator = Nothing , _maOKActions = Nothing , _maStateValue = Nothing , _maThreshold = Nothing , _maAlarmConfigurationUpdatedTimestamp = Nothing , _maActionsEnabled = Nothing , _maInsufficientDataActions = Nothing , _maStateReason = Nothing , _maStateReasonData = Nothing , _maDimensions = Nothing , _maAlarmARN = Nothing , _maAlarmActions = Nothing , _maUnit = Nothing , _maStatistic = Nothing } -- | The name of the alarm. maAlarmName :: Lens' MetricAlarm (Maybe Text) maAlarmName = lens _maAlarmName (\ s a -> s{_maAlarmName = a}); -- | The time stamp of the last update to the alarm\'s state. Amazon -- CloudWatch uses Coordinated Universal Time (UTC) when returning time -- stamps, which do not accommodate seasonal adjustments such as daylight -- savings time. For more information, see -- <http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/cloudwatch_concepts.html#about_timestamp Time stamps> -- in the /Amazon CloudWatch Developer Guide/. maStateUpdatedTimestamp :: Lens' MetricAlarm (Maybe UTCTime) maStateUpdatedTimestamp = lens _maStateUpdatedTimestamp (\ s a -> s{_maStateUpdatedTimestamp = a}) . mapping _Time; -- | The period in seconds over which the statistic is applied. maPeriod :: Lens' MetricAlarm (Maybe Natural) maPeriod = lens _maPeriod (\ s a -> s{_maPeriod = a}) . mapping _Nat; -- | The description for the alarm. maAlarmDescription :: Lens' MetricAlarm (Maybe Text) maAlarmDescription = lens _maAlarmDescription (\ s a -> s{_maAlarmDescription = a}); -- | The number of periods over which data is compared to the specified -- threshold. maEvaluationPeriods :: Lens' MetricAlarm (Maybe Natural) maEvaluationPeriods = lens _maEvaluationPeriods (\ s a -> s{_maEvaluationPeriods = a}) . mapping _Nat; -- | The name of the alarm\'s metric. maMetricName :: Lens' MetricAlarm (Maybe Text) maMetricName = lens _maMetricName (\ s a -> s{_maMetricName = a}); -- | The namespace of alarm\'s associated metric. maNamespace :: Lens' MetricAlarm (Maybe Text) maNamespace = lens _maNamespace (\ s a -> s{_maNamespace = a}); -- | The arithmetic operation to use when comparing the specified 'Statistic' -- and 'Threshold'. The specified 'Statistic' value is used as the first -- operand. maComparisonOperator :: Lens' MetricAlarm (Maybe ComparisonOperator) maComparisonOperator = lens _maComparisonOperator (\ s a -> s{_maComparisonOperator = a}); -- | The list of actions to execute when this alarm transitions into an 'OK' -- state from any other state. Each action is specified as an Amazon -- Resource Number (ARN). Currently the only actions supported are -- publishing to an Amazon SNS topic and triggering an Auto Scaling policy. maOKActions :: Lens' MetricAlarm [Text] maOKActions = lens _maOKActions (\ s a -> s{_maOKActions = a}) . _Default . _Coerce; -- | The state value for the alarm. maStateValue :: Lens' MetricAlarm (Maybe StateValue) maStateValue = lens _maStateValue (\ s a -> s{_maStateValue = a}); -- | The value against which the specified statistic is compared. maThreshold :: Lens' MetricAlarm (Maybe Double) maThreshold = lens _maThreshold (\ s a -> s{_maThreshold = a}); -- | The time stamp of the last update to the alarm configuration. Amazon -- CloudWatch uses Coordinated Universal Time (UTC) when returning time -- stamps, which do not accommodate seasonal adjustments such as daylight -- savings time. For more information, see -- <http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/cloudwatch_concepts.html#about_timestamp Time stamps> -- in the /Amazon CloudWatch Developer Guide/. maAlarmConfigurationUpdatedTimestamp :: Lens' MetricAlarm (Maybe UTCTime) maAlarmConfigurationUpdatedTimestamp = lens _maAlarmConfigurationUpdatedTimestamp (\ s a -> s{_maAlarmConfigurationUpdatedTimestamp = a}) . mapping _Time; -- | Indicates whether actions should be executed during any changes to the -- alarm\'s state. maActionsEnabled :: Lens' MetricAlarm (Maybe Bool) maActionsEnabled = lens _maActionsEnabled (\ s a -> s{_maActionsEnabled = a}); -- | The list of actions to execute when this alarm transitions into an -- 'INSUFFICIENT_DATA' state from any other state. Each action is specified -- as an Amazon Resource Number (ARN). Currently the only actions supported -- are publishing to an Amazon SNS topic or triggering an Auto Scaling -- policy. -- -- The current WSDL lists this attribute as 'UnknownActions'. maInsufficientDataActions :: Lens' MetricAlarm [Text] maInsufficientDataActions = lens _maInsufficientDataActions (\ s a -> s{_maInsufficientDataActions = a}) . _Default . _Coerce; -- | A human-readable explanation for the alarm\'s state. maStateReason :: Lens' MetricAlarm (Maybe Text) maStateReason = lens _maStateReason (\ s a -> s{_maStateReason = a}); -- | An explanation for the alarm\'s state in machine-readable JSON format maStateReasonData :: Lens' MetricAlarm (Maybe Text) maStateReasonData = lens _maStateReasonData (\ s a -> s{_maStateReasonData = a}); -- | The list of dimensions associated with the alarm\'s associated metric. maDimensions :: Lens' MetricAlarm [Dimension] maDimensions = lens _maDimensions (\ s a -> s{_maDimensions = a}) . _Default . _Coerce; -- | The Amazon Resource Name (ARN) of the alarm. maAlarmARN :: Lens' MetricAlarm (Maybe Text) maAlarmARN = lens _maAlarmARN (\ s a -> s{_maAlarmARN = a}); -- | The list of actions to execute when this alarm transitions into an -- 'ALARM' state from any other state. Each action is specified as an -- Amazon Resource Number (ARN). Currently the only actions supported are -- publishing to an Amazon SNS topic and triggering an Auto Scaling policy. maAlarmActions :: Lens' MetricAlarm [Text] maAlarmActions = lens _maAlarmActions (\ s a -> s{_maAlarmActions = a}) . _Default . _Coerce; -- | The unit of the alarm\'s associated metric. maUnit :: Lens' MetricAlarm (Maybe StandardUnit) maUnit = lens _maUnit (\ s a -> s{_maUnit = a}); -- | The statistic to apply to the alarm\'s associated metric. maStatistic :: Lens' MetricAlarm (Maybe Statistic) maStatistic = lens _maStatistic (\ s a -> s{_maStatistic = a}); instance FromXML MetricAlarm where parseXML x = MetricAlarm' <$> (x .@? "AlarmName") <*> (x .@? "StateUpdatedTimestamp") <*> (x .@? "Period") <*> (x .@? "AlarmDescription") <*> (x .@? "EvaluationPeriods") <*> (x .@? "MetricName") <*> (x .@? "Namespace") <*> (x .@? "ComparisonOperator") <*> (x .@? "OKActions" .!@ mempty >>= may (parseXMLList "member")) <*> (x .@? "StateValue") <*> (x .@? "Threshold") <*> (x .@? "AlarmConfigurationUpdatedTimestamp") <*> (x .@? "ActionsEnabled") <*> (x .@? "InsufficientDataActions" .!@ mempty >>= may (parseXMLList "member")) <*> (x .@? "StateReason") <*> (x .@? "StateReasonData") <*> (x .@? "Dimensions" .!@ mempty >>= may (parseXMLList "member")) <*> (x .@? "AlarmArn") <*> (x .@? "AlarmActions" .!@ mempty >>= may (parseXMLList "member")) <*> (x .@? "Unit") <*> (x .@? "Statistic") -- | The 'MetricDatum' data type encapsulates the information sent with -- PutMetricData to either create a new metric or add new values to be -- aggregated into an existing metric. -- -- /See:/ 'metricDatum' smart constructor. data MetricDatum = MetricDatum' { _mdValue :: !(Maybe Double) , _mdDimensions :: !(Maybe [Dimension]) , _mdUnit :: !(Maybe StandardUnit) , _mdTimestamp :: !(Maybe ISO8601) , _mdStatisticValues :: !(Maybe StatisticSet) , _mdMetricName :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'MetricDatum' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mdValue' -- -- * 'mdDimensions' -- -- * 'mdUnit' -- -- * 'mdTimestamp' -- -- * 'mdStatisticValues' -- -- * 'mdMetricName' metricDatum :: Text -- ^ 'mdMetricName' -> MetricDatum metricDatum pMetricName_ = MetricDatum' { _mdValue = Nothing , _mdDimensions = Nothing , _mdUnit = Nothing , _mdTimestamp = Nothing , _mdStatisticValues = Nothing , _mdMetricName = pMetricName_ } -- | The value for the metric. -- -- Although the 'Value' parameter accepts numbers of type 'Double', Amazon -- CloudWatch truncates values with very large exponents. Values with -- base-10 exponents greater than 126 (1 x 10^126) are truncated. Likewise, -- values with base-10 exponents less than -130 (1 x 10^-130) are also -- truncated. mdValue :: Lens' MetricDatum (Maybe Double) mdValue = lens _mdValue (\ s a -> s{_mdValue = a}); -- | A list of dimensions associated with the metric. Note, when using the -- Dimensions value in a query, you need to append .member.N to it (e.g., -- Dimensions.member.N). mdDimensions :: Lens' MetricDatum [Dimension] mdDimensions = lens _mdDimensions (\ s a -> s{_mdDimensions = a}) . _Default . _Coerce; -- | The unit of the metric. mdUnit :: Lens' MetricDatum (Maybe StandardUnit) mdUnit = lens _mdUnit (\ s a -> s{_mdUnit = a}); -- | The time stamp used for the metric. If not specified, the default value -- is set to the time the metric data was received. Amazon CloudWatch uses -- Coordinated Universal Time (UTC) when returning time stamps, which do -- not accommodate seasonal adjustments such as daylight savings time. For -- more information, see -- <http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/cloudwatch_concepts.html#about_timestamp Time stamps> -- in the /Amazon CloudWatch Developer Guide/. mdTimestamp :: Lens' MetricDatum (Maybe UTCTime) mdTimestamp = lens _mdTimestamp (\ s a -> s{_mdTimestamp = a}) . mapping _Time; -- | A set of statistical values describing the metric. mdStatisticValues :: Lens' MetricDatum (Maybe StatisticSet) mdStatisticValues = lens _mdStatisticValues (\ s a -> s{_mdStatisticValues = a}); -- | The name of the metric. mdMetricName :: Lens' MetricDatum Text mdMetricName = lens _mdMetricName (\ s a -> s{_mdMetricName = a}); instance ToQuery MetricDatum where toQuery MetricDatum'{..} = mconcat ["Value" =: _mdValue, "Dimensions" =: toQuery (toQueryList "member" <$> _mdDimensions), "Unit" =: _mdUnit, "Timestamp" =: _mdTimestamp, "StatisticValues" =: _mdStatisticValues, "MetricName" =: _mdMetricName] -- | The 'StatisticSet' data type describes the 'StatisticValues' component -- of MetricDatum, and represents a set of statistics that describes a -- specific metric. -- -- /See:/ 'statisticSet' smart constructor. data StatisticSet = StatisticSet' { _ssSampleCount :: !Double , _ssSum :: !Double , _ssMinimum :: !Double , _ssMaximum :: !Double } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'StatisticSet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ssSampleCount' -- -- * 'ssSum' -- -- * 'ssMinimum' -- -- * 'ssMaximum' statisticSet :: Double -- ^ 'ssSampleCount' -> Double -- ^ 'ssSum' -> Double -- ^ 'ssMinimum' -> Double -- ^ 'ssMaximum' -> StatisticSet statisticSet pSampleCount_ pSum_ pMinimum_ pMaximum_ = StatisticSet' { _ssSampleCount = pSampleCount_ , _ssSum = pSum_ , _ssMinimum = pMinimum_ , _ssMaximum = pMaximum_ } -- | The number of samples used for the statistic set. ssSampleCount :: Lens' StatisticSet Double ssSampleCount = lens _ssSampleCount (\ s a -> s{_ssSampleCount = a}); -- | The sum of values for the sample set. ssSum :: Lens' StatisticSet Double ssSum = lens _ssSum (\ s a -> s{_ssSum = a}); -- | The minimum value of the sample set. ssMinimum :: Lens' StatisticSet Double ssMinimum = lens _ssMinimum (\ s a -> s{_ssMinimum = a}); -- | The maximum value of the sample set. ssMaximum :: Lens' StatisticSet Double ssMaximum = lens _ssMaximum (\ s a -> s{_ssMaximum = a}); instance ToQuery StatisticSet where toQuery StatisticSet'{..} = mconcat ["SampleCount" =: _ssSampleCount, "Sum" =: _ssSum, "Minimum" =: _ssMinimum, "Maximum" =: _ssMaximum]
fmapfmapfmap/amazonka
amazonka-cloudwatch/gen/Network/AWS/CloudWatch/Types/Product.hs
mpl-2.0
25,482
0
28
5,693
4,743
2,759
1,984
441
1
-------------------------------------------------------------------- -- | -- Module : Text.RSS.Export -- Copyright : (c) Galois, Inc. 2008 -- License : BSD3 -- -- Maintainer: Sigbjorn Finne <[email protected]> -- Stability : provisional -- Description: Convert from RSS to XML -- -------------------------------------------------------------------- module Text.RSS.Export where import Text.XML.Light as XML import Text.RSS.Syntax import Data.List import Data.Maybe qualNode :: String -> [XML.Content] -> XML.Element qualNode n cs = blank_element { elName = qualName n , elContent = cs } qualName :: String -> QName qualName n = QName{qName=n,qURI=Nothing,qPrefix=Nothing} --- xmlRSS :: RSS -> XML.Element xmlRSS r = (qualNode "rss" $ map Elem $ ( [ xmlChannel (rssChannel r) ] ++ rssOther r)) { elAttribs = (Attr (qualName "version") (rssVersion r)):rssAttrs r } xmlChannel :: RSSChannel -> XML.Element xmlChannel ch = (qualNode "channel" $ map Elem $ ( [ xmlLeaf "title" (rssTitle ch) , xmlLeaf "link" (rssLink ch) , xmlLeaf "description" (rssDescription ch) ] ++ map xmlItem (rssItems ch) ++ mb (xmlLeaf "language") (rssLanguage ch) ++ mb (xmlLeaf "copyright") (rssCopyright ch) ++ mb (xmlLeaf "managingEditor") (rssEditor ch) ++ mb (xmlLeaf "webMaster") (rssWebMaster ch) ++ mb (xmlLeaf "pubDate") (rssPubDate ch) ++ mb (xmlLeaf "lastBuildDate") (rssLastUpdate ch) ++ map xmlCategory (rssCategories ch) ++ mb (xmlLeaf "generator") (rssGenerator ch) ++ mb (xmlLeaf "docs") (rssDocs ch) ++ mb xmlCloud (rssCloud ch) ++ mb ((xmlLeaf "ttl") . show) (rssTTL ch) ++ mb xmlImage (rssImage ch) ++ mb (xmlLeaf "rating") (rssRating ch) ++ mb xmlTextInput (rssTextInput ch) ++ mb xmlSkipHours (rssSkipHours ch) ++ mb xmlSkipDays (rssSkipDays ch) ++ rssChannelOther ch)) xmlItem :: RSSItem -> XML.Element xmlItem it = (qualNode "item" $ map Elem $ ( mb (xmlLeaf "title") (rssItemTitle it) ++ mb (xmlLeaf "link") (rssItemLink it) ++ mb (xmlLeaf "description") (rssItemDescription it) ++ mb (xmlLeaf "author") (rssItemAuthor it) ++ map xmlCategory (rssItemCategories it) ++ mb (xmlLeaf "comments") (rssItemComments it) ++ mb xmlEnclosure (rssItemEnclosure it) ++ mb xmlGuid (rssItemGuid it) ++ mb (xmlLeaf "pubDate") (rssItemPubDate it) ++ mb xmlSource (rssItemSource it) ++ rssItemOther it)) { elAttribs = rssItemAttrs it } xmlSource :: RSSSource -> XML.Element xmlSource s = (xmlLeaf "source" (rssSourceTitle s)) { elAttribs = (Attr (qualName "url") (rssSourceURL s)) : rssSourceAttrs s } xmlEnclosure :: RSSEnclosure -> XML.Element xmlEnclosure e = (xmlLeaf "enclosure" "") { elAttribs = (Attr (qualName "url") (rssEnclosureURL e)) : (Attr (qualName "length") (show $ rssEnclosureLength e)) : (Attr (qualName "type") (rssEnclosureType e)) : rssEnclosureAttrs e } xmlCategory :: RSSCategory -> XML.Element xmlCategory c = (xmlLeaf "category" (rssCategoryValue c)) { elAttribs = (fromMaybe id (fmap (\ n -> ((Attr (qualName "domain") n):)) (rssCategoryDomain c))) $ (rssCategoryAttrs c) } xmlGuid :: RSSGuid -> XML.Element xmlGuid g = (xmlLeaf "guid" (rssGuidValue g)) { elAttribs = (fromMaybe id (fmap (\ n -> ((Attr (qualName "isPermaLink") (toBool n)):)) (rssGuidPermanentURL g))) $ (rssGuidAttrs g) } where toBool False = "false" toBool _ = "true" xmlImage :: RSSImage -> XML.Element xmlImage im = (qualNode "image" $ map Elem $ ( [ xmlLeaf "url" (rssImageURL im) , xmlLeaf "title" (rssImageTitle im) , xmlLeaf "link" (rssImageLink im) ] ++ mb ((xmlLeaf "width") . show) (rssImageWidth im) ++ mb ((xmlLeaf "height") . show) (rssImageHeight im) ++ mb (xmlLeaf "description") (rssImageDesc im) ++ rssImageOther im)) xmlCloud :: RSSCloud -> XML.Element xmlCloud cl = (xmlLeaf "cloud" "") { elAttribs = ( mb (Attr (qualName "domain")) (rssCloudDomain cl) ++ mb (Attr (qualName "port")) (rssCloudPort cl) ++ mb (Attr (qualName "path")) (rssCloudPath cl) ++ mb (Attr (qualName "register")) (rssCloudRegister cl) ++ mb (Attr (qualName "protocol")) (rssCloudProtocol cl) ++ rssCloudAttrs cl) } xmlTextInput :: RSSTextInput -> XML.Element xmlTextInput ti = (qualNode "textInput" $ map Elem $ ( [ xmlLeaf "title" (rssTextInputTitle ti) , xmlLeaf "description" (rssTextInputDesc ti) , xmlLeaf "name" (rssTextInputName ti) , xmlLeaf "link" (rssTextInputLink ti) ] ++ rssTextInputOther ti)) { elAttribs = rssTextInputAttrs ti } xmlSkipHours :: [Integer] -> XML.Element xmlSkipHours hs = (qualNode "skipHours" $ map Elem $ (map (\ n -> xmlLeaf "hour" (show n)) hs)) xmlSkipDays :: [String] -> XML.Element xmlSkipDays hs = (qualNode "skipDayss" $ map Elem $ (map (\ n -> xmlLeaf "day" n) hs)) -- xmlAttr :: String -> String -> XML.Attr xmlAttr k v = Attr (qualName k) v xmlLeaf :: String -> String -> XML.Element xmlLeaf tg txt = blank_element{ elName = qualName tg , elContent = [ Text blank_cdata { cdData = txt } ] } --- mb :: (a -> b) -> Maybe a -> [b] mb _ Nothing = [] mb f (Just x) = [f x]
GaloisInc/feed
Text/RSS/Export.hs
bsd-3-clause
5,501
12
29
1,353
2,019
1,030
989
132
2
{-# LANGUAGE DeriveDataTypeable, MultiParamTypeClasses, FlexibleInstances, TypeSynonymInstances #-} ----------------------------------------------------------------------------- -- | -- Module : XMonad.Layout.Fullscreen -- Copyright : (c) 2010 Audun Skaugen -- License : BSD-style (see xmonad/LICENSE) -- -- Maintainer : [email protected] -- Stability : unstable -- Portability : unportable -- -- Hooks for sending messages about fullscreen windows to layouts, and -- a few example layout modifier that implement fullscreen windows. ----------------------------------------------------------------------------- module XMonad.Layout.Fullscreen ( -- * Usage: -- $usage fullscreenFull ,fullscreenFocus ,fullscreenFullRect ,fullscreenFocusRect ,fullscreenFloat ,fullscreenFloatRect ,fullscreenEventHook ,fullscreenManageHook ,fullscreenManageHookWith ,FullscreenMessage(..) -- * Types for reference ,FullscreenFloat, FullscreenFocus, FullscreenFull ) where import XMonad import XMonad.Layout.LayoutModifier import XMonad.Util.WindowProperties import XMonad.Hooks.ManageHelpers (isFullscreen) import qualified XMonad.StackSet as W import Data.List import Data.Maybe import Data.Monoid import qualified Data.Map as M import Control.Monad import Control.Arrow (second) -- $usage -- Provides a ManageHook and an EventHook that sends layout messages -- with information about fullscreening windows. This allows layouts -- to make their own decisions about what they should to with a -- window that requests fullscreen. -- -- The module also includes a few layout modifiers as an illustration -- of how such layouts should behave. -- -- To use this module, add 'fullscreenEventHook' and 'fullscreenManageHook' -- to your config, i.e. -- -- > xmonad def { handleEventHook = fullscreenEventHook, -- > manageHook = fullscreenManageHook, -- > layoutHook = myLayouts } -- -- Now you can use layouts that respect fullscreen, for example the -- provided 'fullscreenFull': -- -- > myLayouts = fullscreenFull someLayout -- -- | Messages that control the fullscreen state of the window. -- AddFullscreen and RemoveFullscreen are sent to all layouts -- when a window wants or no longer wants to be fullscreen. -- FullscreenChanged is sent to the current layout after one -- of the above have been sent. data FullscreenMessage = AddFullscreen Window | RemoveFullscreen Window | FullscreenChanged deriving (Typeable) instance Message FullscreenMessage data FullscreenFull a = FullscreenFull W.RationalRect [a] deriving (Read, Show) data FullscreenFocus a = FullscreenFocus W.RationalRect [a] deriving (Read, Show) data FullscreenFloat a = FullscreenFloat W.RationalRect (M.Map a (W.RationalRect, Bool)) deriving (Read, Show) instance LayoutModifier FullscreenFull Window where pureMess ff@(FullscreenFull frect fulls) m = case fromMessage m of Just (AddFullscreen win) -> Just $ FullscreenFull frect $ nub $ win:fulls Just (RemoveFullscreen win) -> Just $ FullscreenFull frect $ delete win $ fulls Just FullscreenChanged -> Just ff _ -> Nothing pureModifier (FullscreenFull frect fulls) rect _ list = (map (flip (,) rect') visfulls ++ rest, Nothing) where visfulls = intersect fulls $ map fst list rest = filter (flip notElem visfulls . fst) list rect' = scaleRationalRect rect frect instance LayoutModifier FullscreenFocus Window where pureMess ff@(FullscreenFocus frect fulls) m = case fromMessage m of Just (AddFullscreen win) -> Just $ FullscreenFocus frect $ nub $ win:fulls Just (RemoveFullscreen win) -> Just $ FullscreenFocus frect $ delete win $ fulls Just FullscreenChanged -> Just ff _ -> Nothing pureModifier (FullscreenFocus frect fulls) rect (Just (W.Stack {W.focus = f})) list | f `elem` fulls = ((f, rect') : rest, Nothing) | otherwise = (list, Nothing) where rest = filter ((/= f) . fst) list rect' = scaleRationalRect rect frect pureModifier _ _ Nothing list = (list, Nothing) instance LayoutModifier FullscreenFloat Window where handleMess (FullscreenFloat frect fulls) m = case fromMessage m of Just (AddFullscreen win) -> do mrect <- (M.lookup win . W.floating) `fmap` gets windowset return $ case mrect of Just rect -> Just $ FullscreenFloat frect $ M.insert win (rect,True) fulls Nothing -> Nothing Just (RemoveFullscreen win) -> return $ Just $ FullscreenFloat frect $ M.adjust (second $ const False) win fulls -- Modify the floating member of the stack set directly; this is the hackish part. Just FullscreenChanged -> do st <- get let ws = windowset st flt = W.floating ws flt' = M.intersectionWith doFull fulls flt put st {windowset = ws {W.floating = M.union flt' flt}} return $ Just $ FullscreenFloat frect $ M.filter snd fulls where doFull (_, True) _ = frect doFull (rect, False) _ = rect Nothing -> return Nothing -- | Layout modifier that makes fullscreened window fill the -- entire screen. fullscreenFull :: LayoutClass l a => l a -> ModifiedLayout FullscreenFull l a fullscreenFull = fullscreenFullRect $ W.RationalRect 0 0 1 1 -- | As above, but the fullscreened window will fill the -- specified rectangle instead of the entire screen. fullscreenFullRect :: LayoutClass l a => W.RationalRect -> l a -> ModifiedLayout FullscreenFull l a fullscreenFullRect r = ModifiedLayout $ FullscreenFull r [] -- | Layout modifier that makes the fullscreened window fill -- the entire screen only if it is currently focused. fullscreenFocus :: LayoutClass l a => l a -> ModifiedLayout FullscreenFocus l a fullscreenFocus = fullscreenFocusRect $ W.RationalRect 0 0 1 1 -- | As above, but the fullscreened window will fill the -- specified rectangle instead of the entire screen. fullscreenFocusRect :: LayoutClass l a => W.RationalRect -> l a -> ModifiedLayout FullscreenFocus l a fullscreenFocusRect r = ModifiedLayout $ FullscreenFocus r [] -- | Hackish layout modifier that makes floating fullscreened -- windows fill the entire screen. fullscreenFloat :: LayoutClass l a => l a -> ModifiedLayout FullscreenFloat l a fullscreenFloat = fullscreenFloatRect $ W.RationalRect 0 0 1 1 -- | As above, but the fullscreened window will fill the -- specified rectangle instead of the entire screen. fullscreenFloatRect :: LayoutClass l a => W.RationalRect -> l a -> ModifiedLayout FullscreenFloat l a fullscreenFloatRect r = ModifiedLayout $ FullscreenFloat r M.empty -- | The event hook required for the layout modifiers to work fullscreenEventHook :: Event -> X All fullscreenEventHook (ClientMessageEvent _ _ _ dpy win typ (action:dats)) = do wmstate <- getAtom "_NET_WM_STATE" fullsc <- getAtom "_NET_WM_STATE_FULLSCREEN" wstate <- fromMaybe [] `fmap` getProp32 wmstate win let fi :: (Integral i, Num n) => i -> n fi = fromIntegral isFull = fi fullsc `elem` wstate remove = 0 add = 1 toggle = 2 ptype = 4 chWState f = io $ changeProperty32 dpy win wmstate ptype propModeReplace (f wstate) when (typ == wmstate && fi fullsc `elem` dats) $ do when (action == add || (action == toggle && not isFull)) $ do chWState (fi fullsc:) broadcastMessage $ AddFullscreen win sendMessage FullscreenChanged when (action == remove || (action == toggle && isFull)) $ do chWState $ delete (fi fullsc) broadcastMessage $ RemoveFullscreen win sendMessage FullscreenChanged return $ All True fullscreenEventHook (DestroyWindowEvent {ev_window = w}) = do -- When a window is destroyed, the layouts should remove that window -- from their states. broadcastMessage $ RemoveFullscreen w cw <- (W.workspace . W.current) `fmap` gets windowset sendMessageWithNoRefresh FullscreenChanged cw return $ All True fullscreenEventHook _ = return $ All True -- | Manage hook that sets the fullscreen property for -- windows that are initially fullscreen fullscreenManageHook :: ManageHook fullscreenManageHook = fullscreenManageHook' isFullscreen -- | A version of fullscreenManageHook that lets you specify -- your own query to decide whether a window should be fullscreen. fullscreenManageHookWith :: Query Bool -> ManageHook fullscreenManageHookWith h = fullscreenManageHook' $ isFullscreen <||> h fullscreenManageHook' :: Query Bool -> ManageHook fullscreenManageHook' isFull = isFull --> do w <- ask liftX $ do broadcastMessage $ AddFullscreen w cw <- (W.workspace . W.current) `fmap` gets windowset sendMessageWithNoRefresh FullscreenChanged cw idHook
eb-gh-cr/XMonadContrib1
XMonad/Layout/Fullscreen.hs
bsd-3-clause
8,783
0
17
1,751
2,008
1,040
968
137
1
{-# LANGUAGE FlexibleInstances #-} -- | -- This module contains the Json Parser. module Data.Katydid.Parser.Json ( decodeJSON , JsonTree ) where import Text.JSON ( decode , Result(..) , JSValue(..) , fromJSString , fromJSObject ) import Data.Ratio ( denominator ) import Data.Text ( pack ) import qualified Data.Tree as DataTree import Data.Katydid.Parser.Parser instance Tree JsonTree where getLabel (DataTree.Node l _) = l getChildren (DataTree.Node _ cs) = cs -- | -- JsonTree is a tree that can be validated by Relapse. type JsonTree = DataTree.Tree Label -- | -- decodeJSON returns a JsonTree, given an input string. decodeJSON :: String -> Either String [JsonTree] decodeJSON s = case decode s of (Error e) -> Left e (Ok v) -> Right (uValue v) uValue :: JSValue -> [JsonTree] uValue JSNull = [] uValue (JSBool b ) = [DataTree.Node (Bool b) []] uValue (JSRational _ r) = if denominator r /= 1 then [DataTree.Node (Double (fromRational r :: Double)) []] else [DataTree.Node (Int $ truncate r) []] uValue (JSString s ) = [DataTree.Node (String $ pack $ fromJSString s) []] uValue (JSArray vs) = uArray 0 vs uValue (JSObject o ) = uObject $ fromJSObject o uArray :: Int -> [JSValue] -> [JsonTree] uArray _ [] = [] uArray index (v : vs) = DataTree.Node (Int index) (uValue v) : uArray (index + 1) vs uObject :: [(String, JSValue)] -> [JsonTree] uObject = map uKeyValue uKeyValue :: (String, JSValue) -> JsonTree uKeyValue (name, value) = DataTree.Node (String $ pack name) (uValue value)
katydid/haslapse
src/Data/Katydid/Parser/Json.hs
bsd-3-clause
1,905
0
11
665
591
319
272
38
2
{-# language ScopedTypeVariables #-} -- | module to continue the physics simulation of the scene in a background thread. module Game.BackgroundScene where import Data.Initial import Data.IORef import Control.Monad.State.Strict import Control.Concurrent import Clocked import Utils import Base import Game.Scene -- | Advances the scene until a key that is validated by the given predicate is pressed, -- or the given timelimit is reached waitForPressedButtonBackgroundScene :: forall a . Application -> IORef GameState -> SceneMVar -> (Button -> Bool) -> Maybe POSIXTime -> M (Maybe Button) waitForPressedButtonBackgroundScene app gameStateRef sceneMVar buttonPred mTimeLimit = do startTime <- io $ getTime gameState <- io $ readIORef gameStateRef (button, gameState') <- runStateT (withTimer $ loopSuperStep startTime) gameState io $ writeIORef gameStateRef gameState' return button where -- | loops to perform supersteps loopSuperStep :: POSIXTime -> Timer -> GameMonad (Maybe Button) loopSuperStep startTime timer = do performSubSteps timer subStepsPerSuperStep mEvent <- lift $ nextAppEvent app let continue = do io $ waitTimer timer (realToFrac (superStepQuantum / timeFactor)) loopSuperStep startTime timer state <- get case mEvent of Just (Press b) | buttonPred b -> return $ Just b _ -> do exceeds <- io $ exceedsTimeLimit startTime if exceeds then return Nothing else continue -- If waitForPressedButtonBackgroundScene exceeded the given time limit. exceedsTimeLimit :: POSIXTime -> IO Bool exceedsTimeLimit startTime = case mTimeLimit of Nothing -> return False Just timeLimit -> do now <- getTime return (now - startTime >= timeLimit) -- | performs n substeps. Aborts in case of level end. Returns (Just AppState) in -- that case. Nothing means, the game should continue. performSubSteps :: Timer -> Int -> GameMonad () performSubSteps timer 0 = return () performSubSteps timer n = do io $ resetDebugging -- stepping of the scene (includes rendering) space <- gets cmSpace sc <- gets scene configuration <- lift get sc' <- io $ stepScene app configuration space initial sc puts setScene sc' swapSceneMVar =<< io getDebugging performSubSteps timer (pred n) swapSceneMVar :: DebuggingCommand -> GameMonad () swapSceneMVar debugging = do s <- gets scene immutableCopyOfScene <- io $ sceneImmutableCopy s io $ modifyMVar_ sceneMVar (const $ return (immutableCopyOfScene, debugging)) return ()
geocurnoff/nikki
src/Game/BackgroundScene.hs
lgpl-3.0
2,806
0
19
758
649
310
339
56
5
{-| Discovery of incidents by the maintenance daemon. This module implements the querying of all monitoring daemons for the value of the node-status data collector. Any new incident gets registered. -} {- Copyright (C) 2015 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.MaintD.CollectIncidents ( collectIncidents ) where import Control.Applicative (liftA2) import Control.Monad (unless) import Control.Monad.IO.Class (liftIO) import qualified Data.ByteString.UTF8 as UTF8 import Data.IORef (IORef) import Network.Curl import System.Time (getClockTime) import qualified Text.JSON as J import Ganeti.BasicTypes (ResultT) import qualified Ganeti.Constants as C import qualified Ganeti.DataCollectors.Diagnose as D import Ganeti.DataCollectors.Types (getCategoryName) import qualified Ganeti.HTools.Container as Container import qualified Ganeti.HTools.Node as Node import Ganeti.Logging.Lifted import Ganeti.MaintD.MemoryState (MemoryState, getIncidents, updateIncident) import Ganeti.Objects.Maintenance import Ganeti.Utils (newUUID) -- | Query a node, unless it is offline, and return -- the paylod of the report, if available. For offline -- nodes return nothing. queryStatus :: Node.Node -> IO (Maybe J.JSValue) queryStatus node = do let name = Node.name node let url = name ++ ":" ++ show C.defaultMondPort ++ "/1/report/" ++ maybe "default" getCategoryName D.dcCategory ++ "/" ++ D.dcName if Node.offline node then do logDebug $ "Not asking " ++ name ++ "; it is offline" return Nothing else do (code, body) <- liftIO $ curlGetString url [] case code of CurlOK -> case J.decode body of J.Ok r -> return $ Just r _ -> return Nothing _ -> do logWarning $ "Failed to contact " ++ name return Nothing -- | Update the status of one node. updateNode :: IORef MemoryState -> Node.Node -> ResultT String IO () updateNode memstate node = do let name = Node.name node logDebug $ "Inspecting " ++ name report <- liftIO $ queryStatus node case report of Just (J.JSObject obj) | Just orig@(J.JSObject origobj) <- lookup "data" $ J.fromJSObject obj, Just s <- lookup "status" $ J.fromJSObject origobj, J.Ok state <- J.readJSON s, state /= RANoop -> do let origs = J.encode orig logDebug $ "Relevant event on " ++ name ++ ": " ++ origs incidents <- getIncidents memstate unless (any (liftA2 (&&) ((==) name . incidentNode) ((==) orig . incidentOriginal)) incidents) $ do logInfo $ "Registering new incident on " ++ name ++ ": " ++ origs uuid <- liftIO newUUID now <- liftIO getClockTime let tag = C.maintdSuccessTagPrefix ++ uuid incident = Incident { incidentOriginal = orig , incidentAction = state , incidentRepairStatus = RSNoted , incidentJobs = [] , incidentNode = name , incidentTag = tag , incidentUuid = UTF8.fromString uuid , incidentCtime = now , incidentMtime = now , incidentSerial = 1 } liftIO $ updateIncident memstate incident _ -> return () -- | Query all MonDs for updates on the node-status. collectIncidents :: IORef MemoryState -> Node.List -> ResultT String IO () collectIncidents memstate nl = do _ <- getIncidents memstate -- always update the memory state, -- even if we do not observe anything logDebug "Querying all nodes for incidents" mapM_ (updateNode memstate) $ Container.elems nl
leshchevds/ganeti
src/Ganeti/MaintD/CollectIncidents.hs
bsd-2-clause
5,195
0
22
1,427
923
481
442
78
4
module Curry where f :: Int -> Int -> Int f x y = x + y g :: (Int, Int) -> Int g (x,y) = x + y main = do print $ curry g 3 4 print $ uncurry f (3,4)
beni55/fay
tests/curry.hs
bsd-3-clause
156
0
9
50
101
54
47
8
1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Distribution.Solver.Types.Settings ( ReorderGoals(..) , IndependentGoals(..) , AvoidReinstalls(..) , ShadowPkgs(..) , StrongFlags(..) , EnableBackjumping(..) , CountConflicts(..) ) where import Distribution.Simple.Setup ( BooleanFlag(..) ) import Distribution.Compat.Binary (Binary(..)) import GHC.Generics (Generic) newtype ReorderGoals = ReorderGoals Bool deriving (BooleanFlag, Eq, Generic, Show) newtype CountConflicts = CountConflicts Bool deriving (BooleanFlag, Eq, Generic, Show) newtype IndependentGoals = IndependentGoals Bool deriving (BooleanFlag, Eq, Generic, Show) newtype AvoidReinstalls = AvoidReinstalls Bool deriving (BooleanFlag, Eq, Generic, Show) newtype ShadowPkgs = ShadowPkgs Bool deriving (BooleanFlag, Eq, Generic, Show) newtype StrongFlags = StrongFlags Bool deriving (BooleanFlag, Eq, Generic, Show) newtype EnableBackjumping = EnableBackjumping Bool deriving (BooleanFlag, Eq, Generic, Show) instance Binary ReorderGoals instance Binary CountConflicts instance Binary IndependentGoals instance Binary AvoidReinstalls instance Binary ShadowPkgs instance Binary StrongFlags
thomie/cabal
cabal-install/Distribution/Solver/Types/Settings.hs
bsd-3-clause
1,237
0
6
180
332
193
139
33
0
{-# LANGUAGE ScopedTypeVariables #-} module CV.DFT where import CV.Bindings.Types import CV.Bindings.Core import CV.Bindings.ImgProc import CV.Image import CV.ImageMath as IM import CV.ImageMathOp import System.IO.Unsafe import Foreign.Ptr dft :: Image GrayScale d -> Image Complex D32 dft i = unsafePerformIO $ do n::(Image GrayScale D32) <- create (w', h') n <- copyMakeBorder i 0 (h'-h) 0 (w'-w) BorderConstant 0 c::(Image Complex D32) <- create (w', h') withGenImage n $ \nimg -> withGenImage c $ \cimg -> do c'cvMerge nimg nullPtr nullPtr nullPtr cimg c'cvDFT cimg cimg c'CV_DXT_FORWARD 0 return c where (w,h) = getSize i w' = fromIntegral $ c'cvGetOptimalDFTSize (fromIntegral w) h' = fromIntegral $ c'cvGetOptimalDFTSize (fromIntegral h) idft :: Image Complex D32 -> Image GrayScale D32 idft c = unsafePerformIO $ do n::(Image GrayScale D32) <- create s withGenImage c $ \c_ptr -> withGenImage n $ \n_ptr -> do c'cvDFT c_ptr c_ptr c'CV_DXT_INVERSE 0 c'cvSplit c_ptr n_ptr nullPtr nullPtr nullPtr return n where s = getSize c complexSplit :: Image Complex D32 -> (Image GrayScale D32, Image GrayScale D32) complexSplit c = unsafePerformIO $ do re::(Image GrayScale D32) <- create (w, h) im::(Image GrayScale D32) <- create (w, h) withGenImage c $ \c_ptr -> withGenImage re $ \re_ptr -> withGenImage im $ \im_ptr -> do c'cvSplit c_ptr re_ptr im_ptr nullPtr nullPtr return (re,im) where (w,h) = getSize c complexToMagnitude :: Image Complex D32 -> Image GrayScale D32 complexToMagnitude c = unsafePerformIO $ do mag::(Image GrayScale D32) <- create (w, h) withGenImage re $ \re_ptr -> withGenImage im $ \im_ptr -> withGenImage mag $ \mag_ptr -> do c'cvCartToPolar re_ptr im_ptr mag_ptr nullPtr (fromIntegral 0) return $ IM.log $ 1 |+ mag where (re,im) = complexSplit c (w,h) = getSize c
BeautifulDestinations/CV
CV/DFT.hs
bsd-3-clause
1,950
0
19
438
757
376
381
52
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} -- --------------------------------------------------------------------------- -- | -- Module : Data.Vector.Algorithms.Common -- Copyright : (c) 2008-2011 Dan Doel -- Maintainer : Dan Doel -- Stability : Experimental -- Portability : Portable -- -- Common operations and utility functions for all sorts module Data.Vector.Algorithms.Common where import Language.Haskell.Liquid.Prelude (liquidAssert) import Prelude hiding (read, length) import Control.Monad.Primitive import Data.Vector.Generic.Mutable import qualified Data.Vector.Primitive.Mutable as PV import qualified Data.Vector.Primitive.Mutable ---------------------------------------------------------------------------- -- LIQUID Specifications --------------------------------------------------- ---------------------------------------------------------------------------- -- | Vector Size Measure {-@ measure vsize :: (v m e) -> Int @-} -- | Vector Type Aliases {-@ type NeVec v m e = {v: (v (PrimState m) e) | 0 < (vsize v)} @-} {-@ type OkIdx X = {v:Nat | (OkRng v X 0)} @-} {-@ type AOkIdx X = {v:Nat | v <= (vsize X)} @-} {-@ type Pos = {v:Int | v > 0 } @-} {-@ type LtIdxOff Off Vec = {v:Nat | v+Off < (vsize Vec)} @-} {-@ type LeIdxOff Off Vec = {v:Nat | v+Off <= (vsize Vec)} @-} -- | Only mention of ordering {-@ predicate InRngL V L U = (L < V && V <= U) @-} {-@ predicate InRng V L U = (L <= V && V <= U) @-} {-@ predicate EqSiz X Y = (vsize X) = (vsize Y) @-} -- | Abstractly defined using @InRng@ {-@ predicate OkOff X B O = (InRng (B + O) 0 (vsize X)) @-} {-@ predicate OkRng V X N = (InRng V 0 ((vsize X) - (N + 1))) @-} -- | Assumed Types for Vector {-@ Data.Vector.Generic.Mutable.length :: (Data.Vector.Generic.Mutable.MVector v a) => x:(v s a) -> {v:Nat | v = (vsize x)} @-} {-@ Data.Vector.Generic.Mutable.unsafeRead :: (PrimMonad m, Data.Vector.Generic.Mutable.MVector v a) => x:(v (PrimState m) a) -> (OkIdx x) -> m a @-} {-@ Data.Vector.Generic.Mutable.unsafeWrite :: (PrimMonad m, Data.Vector.Generic.Mutable.MVector v a) => x:(v (PrimState m) a) -> (OkIdx x) -> a -> m () @-} {-@ Data.Vector.Generic.Mutable.unsafeSwap :: (PrimMonad m, Data.Vector.Generic.Mutable.MVector v a) => x:(v (PrimState m) a) -> (OkIdx x) -> (OkIdx x) -> m () @-} {-@ Data.Vector.Generic.Mutable.unsafeSlice :: Data.Vector.Generic.Mutable.MVector v a => i:Nat -> n:Nat -> {v:(v s a) | (OkOff v i n)} -> {v:(v s a) | (vsize v) = n} @-} {-@ Data.Vector.Generic.Mutable.unsafeCopy :: (PrimMonad m, Data.Vector.Generic.Mutable.MVector v a) => src:(v (PrimState m) a) -> {dst:(v (PrimState m) a) | (EqSiz src dst)} -> m () @-} {-@ Data.Vector.Generic.Mutable.new :: (PrimMonad m, Data.Vector.Generic.Mutable.MVector v a) => nINTENDO:Nat -> m {v: (v (PrimState m) a) | (vsize v) = nINTENDO} @-} {-@ Data.Vector.Primitive.Mutable.new :: (PrimMonad m, Data.Vector.Primitive.Mutable.Prim a) => nONKEY:Nat -> m {v: (Data.Vector.Primitive.Mutable.MVector (PrimState m) a) | (vsize v) = nONKEY} @-} {-@ qualif Termination(v:Int, l:Int, twit:Int): v = l + twit @-} {-@ qualif NonEmpty(v:a): 0 < (vsize v) @-} {-@ qualif Cmp(v:int, x:int): v < x @-} {-@ qualif OkIdx(v:int, x:a): v <= (vsize x) @-} {-@ qualif OkIdx(v:int, x:b): v < (vsize x) @-} {-@ qualif EqSiz(x:a, y:int): (vsize x) = y @-} {-@ qualif EqSiz(x:int, y:b): x = (vsize y) @-} {-@ qualif EqSiz(x:a, y:b): (vsize x) = (vsize y) @-} {-@ qualif Plus(v:Int, x:Int, y:Int): v + x = y @-} -- TODO: push this type into the signature for `shiftR`. Issue: math on non-num types. -- TODO: support unchecked `assume`. Currently writing `undefined` to suppress warning -- {- assume shiftRI :: x:Nat -> {v:Int | v = 1} -> {v:Nat | (x <= 2*v + 1 && 2*v <= x)} @-} {-@ assume shiftRI :: x:Nat -> s:Nat -> {v:Nat | ( (s=1 => (2*v <= x && x <= 2*v + 1)) && (s=2 => (4*v <= x && x <= 4*v + 3))) } @-} shiftRI :: Int -> Int -> Int shiftRI = undefined -- shiftR {-@ assume shiftLI :: x:Nat -> s:Nat -> {v:Nat | ( (s = 1 => v = 2 * x) && (s = 2 => v = 4 * x)) } @-} shiftLI :: Int -> Int -> Int shiftLI = undefined -- shiftL ---------------------------------------------------------------------------- -- | A type of comparisons between two values of a given type. type Comparison e = e -> e -> Ordering {-@ copyOffset :: (PrimMonad m, MVector v e) => from : (v (PrimState m) e) -> to : (v (PrimState m) e) -> iFrom : Nat -> iTo : Nat -> {len : Nat | ((OkOff from iFrom len) && (OkOff to iTo len))} -> m () @-} copyOffset :: (PrimMonad m, MVector v e) => v (PrimState m) e -> v (PrimState m) e -> Int -> Int -> Int -> m () copyOffset from to iFrom iTo len = unsafeCopy (unsafeSlice iTo len to) (unsafeSlice iFrom len from) {-# INLINE copyOffset #-} {-@ inc :: (PrimMonad m, MVector v Int) => x:(v (PrimState m) Int) -> (OkIdx x) -> m Int @-} inc :: (PrimMonad m, MVector v Int) => v (PrimState m) Int -> Int -> m Int inc arr i = unsafeRead arr i >>= \e -> unsafeWrite arr i (e+1) >> return e {-# INLINE inc #-} -- LIQUID: flipping order to allow dependency. -- shared bucket sorting stuff {-@ countLoop :: (PrimMonad m, MVector v e) => (v (PrimState m) e) -> count:(PV.MVector (PrimState m) Int) -> (e -> (OkIdx count)) -> m () @-} countLoop :: (PrimMonad m, MVector v e) => (v (PrimState m) e) -> (PV.MVector (PrimState m) Int) -> (e -> Int) -> m () countLoop src count rdx = set count 0 >> go len 0 where len = length src go (m :: Int) i | i < len = let lenSrc = length src in ({- liquidAssert (i < lenSrc) $ -} unsafeRead src i) >>= inc count . rdx >> go (m-1) (i+1) | otherwise = return () {-# INLINE countLoop #-}
abakst/liquidhaskell
benchmarks/vector-algorithms-0.5.4.2/Data/Vector/Algorithms/Common.hs
bsd-3-clause
6,421
0
14
1,813
588
340
248
32
1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP, NoImplicitPrelude, BangPatterns, MagicHash #-} {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.Enum -- Copyright : (c) The University of Glasgow, 1992-2002 -- License : see libraries/base/LICENSE -- -- Maintainer : [email protected] -- Stability : internal -- Portability : non-portable (GHC extensions) -- -- The 'Enum' and 'Bounded' classes. -- ----------------------------------------------------------------------------- module GHC.Enum( Bounded(..), Enum(..), boundedEnumFrom, boundedEnumFromThen, toEnumError, fromEnumError, succError, predError, -- Instances for Bounded and Enum: (), Char, Int ) where import GHC.Base hiding ( many ) import GHC.Char import GHC.Integer import GHC.Num import GHC.Show default () -- Double isn't available yet -- | The 'Bounded' class is used to name the upper and lower limits of a -- type. 'Ord' is not a superclass of 'Bounded' since types that are not -- totally ordered may also have upper and lower bounds. -- -- The 'Bounded' class may be derived for any enumeration type; -- 'minBound' is the first constructor listed in the @data@ declaration -- and 'maxBound' is the last. -- 'Bounded' may also be derived for single-constructor datatypes whose -- constituent types are in 'Bounded'. class Bounded a where minBound, maxBound :: a -- | Class 'Enum' defines operations on sequentially ordered types. -- -- The @enumFrom@... methods are used in Haskell's translation of -- arithmetic sequences. -- -- Instances of 'Enum' may be derived for any enumeration type (types -- whose constructors have no fields). The nullary constructors are -- assumed to be numbered left-to-right by 'fromEnum' from @0@ through @n-1@. -- See Chapter 10 of the /Haskell Report/ for more details. -- -- For any type that is an instance of class 'Bounded' as well as 'Enum', -- the following should hold: -- -- * The calls @'succ' 'maxBound'@ and @'pred' 'minBound'@ should result in -- a runtime error. -- -- * 'fromEnum' and 'toEnum' should give a runtime error if the -- result value is not representable in the result type. -- For example, @'toEnum' 7 :: 'Bool'@ is an error. -- -- * 'enumFrom' and 'enumFromThen' should be defined with an implicit bound, -- thus: -- -- > enumFrom x = enumFromTo x maxBound -- > enumFromThen x y = enumFromThenTo x y bound -- > where -- > bound | fromEnum y >= fromEnum x = maxBound -- > | otherwise = minBound -- class Enum a where -- | the successor of a value. For numeric types, 'succ' adds 1. succ :: a -> a -- | the predecessor of a value. For numeric types, 'pred' subtracts 1. pred :: a -> a -- | Convert from an 'Int'. toEnum :: Int -> a -- | Convert to an 'Int'. -- It is implementation-dependent what 'fromEnum' returns when -- applied to a value that is too large to fit in an 'Int'. fromEnum :: a -> Int -- | Used in Haskell's translation of @[n..]@. enumFrom :: a -> [a] -- | Used in Haskell's translation of @[n,n'..]@. enumFromThen :: a -> a -> [a] -- | Used in Haskell's translation of @[n..m]@. enumFromTo :: a -> a -> [a] -- | Used in Haskell's translation of @[n,n'..m]@. enumFromThenTo :: a -> a -> a -> [a] succ = toEnum . (+ 1) . fromEnum pred = toEnum . (subtract 1) . fromEnum enumFrom x = map toEnum [fromEnum x ..] enumFromThen x y = map toEnum [fromEnum x, fromEnum y ..] enumFromTo x y = map toEnum [fromEnum x .. fromEnum y] enumFromThenTo x1 x2 y = map toEnum [fromEnum x1, fromEnum x2 .. fromEnum y] -- Default methods for bounded enumerations boundedEnumFrom :: (Enum a, Bounded a) => a -> [a] boundedEnumFrom n = map toEnum [fromEnum n .. fromEnum (maxBound `asTypeOf` n)] boundedEnumFromThen :: (Enum a, Bounded a) => a -> a -> [a] boundedEnumFromThen n1 n2 | i_n2 >= i_n1 = map toEnum [i_n1, i_n2 .. fromEnum (maxBound `asTypeOf` n1)] | otherwise = map toEnum [i_n1, i_n2 .. fromEnum (minBound `asTypeOf` n1)] where i_n1 = fromEnum n1 i_n2 = fromEnum n2 ------------------------------------------------------------------------ -- Helper functions ------------------------------------------------------------------------ {-# NOINLINE toEnumError #-} toEnumError :: (Show a) => String -> Int -> (a,a) -> b toEnumError inst_ty i bnds = error $ "Enum.toEnum{" ++ inst_ty ++ "}: tag (" ++ show i ++ ") is outside of bounds " ++ show bnds {-# NOINLINE fromEnumError #-} fromEnumError :: (Show a) => String -> a -> b fromEnumError inst_ty x = error $ "Enum.fromEnum{" ++ inst_ty ++ "}: value (" ++ show x ++ ") is outside of Int's bounds " ++ show (minBound::Int, maxBound::Int) {-# NOINLINE succError #-} succError :: String -> a succError inst_ty = error $ "Enum.succ{" ++ inst_ty ++ "}: tried to take `succ' of maxBound" {-# NOINLINE predError #-} predError :: String -> a predError inst_ty = error $ "Enum.pred{" ++ inst_ty ++ "}: tried to take `pred' of minBound" ------------------------------------------------------------------------ -- Tuples ------------------------------------------------------------------------ instance Bounded () where minBound = () maxBound = () instance Enum () where succ _ = error "Prelude.Enum.().succ: bad argument" pred _ = error "Prelude.Enum.().pred: bad argument" toEnum x | x == 0 = () | otherwise = error "Prelude.Enum.().toEnum: bad argument" fromEnum () = 0 enumFrom () = [()] enumFromThen () () = let many = ():many in many enumFromTo () () = [()] enumFromThenTo () () () = let many = ():many in many -- Report requires instances up to 15 instance (Bounded a, Bounded b) => Bounded (a,b) where minBound = (minBound, minBound) maxBound = (maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c) => Bounded (a,b,c) where minBound = (minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d) => Bounded (a,b,c,d) where minBound = (minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e) => Bounded (a,b,c,d,e) where minBound = (minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f) => Bounded (a,b,c,d,e,f) where minBound = (minBound, minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g) => Bounded (a,b,c,d,e,f,g) where minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g, Bounded h) => Bounded (a,b,c,d,e,f,g,h) where minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g, Bounded h, Bounded i) => Bounded (a,b,c,d,e,f,g,h,i) where minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g, Bounded h, Bounded i, Bounded j) => Bounded (a,b,c,d,e,f,g,h,i,j) where minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g, Bounded h, Bounded i, Bounded j, Bounded k) => Bounded (a,b,c,d,e,f,g,h,i,j,k) where minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g, Bounded h, Bounded i, Bounded j, Bounded k, Bounded l) => Bounded (a,b,c,d,e,f,g,h,i,j,k,l) where minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g, Bounded h, Bounded i, Bounded j, Bounded k, Bounded l, Bounded m) => Bounded (a,b,c,d,e,f,g,h,i,j,k,l,m) where minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g, Bounded h, Bounded i, Bounded j, Bounded k, Bounded l, Bounded m, Bounded n) => Bounded (a,b,c,d,e,f,g,h,i,j,k,l,m,n) where minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g, Bounded h, Bounded i, Bounded j, Bounded k, Bounded l, Bounded m, Bounded n, Bounded o) => Bounded (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o) where minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound) ------------------------------------------------------------------------ -- Bool ------------------------------------------------------------------------ instance Bounded Bool where minBound = False maxBound = True instance Enum Bool where succ False = True succ True = error "Prelude.Enum.Bool.succ: bad argument" pred True = False pred False = error "Prelude.Enum.Bool.pred: bad argument" toEnum n | n == 0 = False | n == 1 = True | otherwise = error "Prelude.Enum.Bool.toEnum: bad argument" fromEnum False = 0 fromEnum True = 1 -- Use defaults for the rest enumFrom = boundedEnumFrom enumFromThen = boundedEnumFromThen ------------------------------------------------------------------------ -- Ordering ------------------------------------------------------------------------ instance Bounded Ordering where minBound = LT maxBound = GT instance Enum Ordering where succ LT = EQ succ EQ = GT succ GT = error "Prelude.Enum.Ordering.succ: bad argument" pred GT = EQ pred EQ = LT pred LT = error "Prelude.Enum.Ordering.pred: bad argument" toEnum n | n == 0 = LT | n == 1 = EQ | n == 2 = GT toEnum _ = error "Prelude.Enum.Ordering.toEnum: bad argument" fromEnum LT = 0 fromEnum EQ = 1 fromEnum GT = 2 -- Use defaults for the rest enumFrom = boundedEnumFrom enumFromThen = boundedEnumFromThen ------------------------------------------------------------------------ -- Char ------------------------------------------------------------------------ instance Bounded Char where minBound = '\0' maxBound = '\x10FFFF' instance Enum Char where succ (C# c#) | isTrue# (ord# c# /=# 0x10FFFF#) = C# (chr# (ord# c# +# 1#)) | otherwise = error ("Prelude.Enum.Char.succ: bad argument") pred (C# c#) | isTrue# (ord# c# /=# 0#) = C# (chr# (ord# c# -# 1#)) | otherwise = error ("Prelude.Enum.Char.pred: bad argument") toEnum = chr fromEnum = ord {-# INLINE enumFrom #-} enumFrom (C# x) = eftChar (ord# x) 0x10FFFF# -- Blarg: technically I guess enumFrom isn't strict! {-# INLINE enumFromTo #-} enumFromTo (C# x) (C# y) = eftChar (ord# x) (ord# y) {-# INLINE enumFromThen #-} enumFromThen (C# x1) (C# x2) = efdChar (ord# x1) (ord# x2) {-# INLINE enumFromThenTo #-} enumFromThenTo (C# x1) (C# x2) (C# y) = efdtChar (ord# x1) (ord# x2) (ord# y) {-# RULES "eftChar" [~1] forall x y. eftChar x y = build (\c n -> eftCharFB c n x y) "efdChar" [~1] forall x1 x2. efdChar x1 x2 = build (\ c n -> efdCharFB c n x1 x2) "efdtChar" [~1] forall x1 x2 l. efdtChar x1 x2 l = build (\ c n -> efdtCharFB c n x1 x2 l) "eftCharList" [1] eftCharFB (:) [] = eftChar "efdCharList" [1] efdCharFB (:) [] = efdChar "efdtCharList" [1] efdtCharFB (:) [] = efdtChar #-} -- We can do better than for Ints because we don't -- have hassles about arithmetic overflow at maxBound {-# INLINE [0] eftCharFB #-} eftCharFB :: (Char -> a -> a) -> a -> Int# -> Int# -> a eftCharFB c n x0 y = go x0 where go x | isTrue# (x ># y) = n | otherwise = C# (chr# x) `c` go (x +# 1#) {-# NOINLINE [1] eftChar #-} eftChar :: Int# -> Int# -> String eftChar x y | isTrue# (x ># y ) = [] | otherwise = C# (chr# x) : eftChar (x +# 1#) y -- For enumFromThenTo we give up on inlining {-# NOINLINE [0] efdCharFB #-} efdCharFB :: (Char -> a -> a) -> a -> Int# -> Int# -> a efdCharFB c n x1 x2 | isTrue# (delta >=# 0#) = go_up_char_fb c n x1 delta 0x10FFFF# | otherwise = go_dn_char_fb c n x1 delta 0# where !delta = x2 -# x1 {-# NOINLINE [1] efdChar #-} efdChar :: Int# -> Int# -> String efdChar x1 x2 | isTrue# (delta >=# 0#) = go_up_char_list x1 delta 0x10FFFF# | otherwise = go_dn_char_list x1 delta 0# where !delta = x2 -# x1 {-# NOINLINE [0] efdtCharFB #-} efdtCharFB :: (Char -> a -> a) -> a -> Int# -> Int# -> Int# -> a efdtCharFB c n x1 x2 lim | isTrue# (delta >=# 0#) = go_up_char_fb c n x1 delta lim | otherwise = go_dn_char_fb c n x1 delta lim where !delta = x2 -# x1 {-# NOINLINE [1] efdtChar #-} efdtChar :: Int# -> Int# -> Int# -> String efdtChar x1 x2 lim | isTrue# (delta >=# 0#) = go_up_char_list x1 delta lim | otherwise = go_dn_char_list x1 delta lim where !delta = x2 -# x1 go_up_char_fb :: (Char -> a -> a) -> a -> Int# -> Int# -> Int# -> a go_up_char_fb c n x0 delta lim = go_up x0 where go_up x | isTrue# (x ># lim) = n | otherwise = C# (chr# x) `c` go_up (x +# delta) go_dn_char_fb :: (Char -> a -> a) -> a -> Int# -> Int# -> Int# -> a go_dn_char_fb c n x0 delta lim = go_dn x0 where go_dn x | isTrue# (x <# lim) = n | otherwise = C# (chr# x) `c` go_dn (x +# delta) go_up_char_list :: Int# -> Int# -> Int# -> String go_up_char_list x0 delta lim = go_up x0 where go_up x | isTrue# (x ># lim) = [] | otherwise = C# (chr# x) : go_up (x +# delta) go_dn_char_list :: Int# -> Int# -> Int# -> String go_dn_char_list x0 delta lim = go_dn x0 where go_dn x | isTrue# (x <# lim) = [] | otherwise = C# (chr# x) : go_dn (x +# delta) ------------------------------------------------------------------------ -- Int ------------------------------------------------------------------------ {- Be careful about these instances. (a) remember that you have to count down as well as up e.g. [13,12..0] (b) be careful of Int overflow (c) remember that Int is bounded, so [1..] terminates at maxInt -} instance Bounded Int where minBound = minInt maxBound = maxInt instance Enum Int where succ x | x == maxBound = error "Prelude.Enum.succ{Int}: tried to take `succ' of maxBound" | otherwise = x + 1 pred x | x == minBound = error "Prelude.Enum.pred{Int}: tried to take `pred' of minBound" | otherwise = x - 1 toEnum x = x fromEnum x = x {-# INLINE enumFrom #-} enumFrom (I# x) = eftInt x maxInt# where !(I# maxInt#) = maxInt -- Blarg: technically I guess enumFrom isn't strict! {-# INLINE enumFromTo #-} enumFromTo (I# x) (I# y) = eftInt x y {-# INLINE enumFromThen #-} enumFromThen (I# x1) (I# x2) = efdInt x1 x2 {-# INLINE enumFromThenTo #-} enumFromThenTo (I# x1) (I# x2) (I# y) = efdtInt x1 x2 y ----------------------------------------------------- -- eftInt and eftIntFB deal with [a..b], which is the -- most common form, so we take a lot of care -- In particular, we have rules for deforestation {-# RULES "eftInt" [~1] forall x y. eftInt x y = build (\ c n -> eftIntFB c n x y) "eftIntList" [1] eftIntFB (:) [] = eftInt #-} {-# NOINLINE [1] eftInt #-} eftInt :: Int# -> Int# -> [Int] -- [x1..x2] eftInt x0 y | isTrue# (x0 ># y) = [] | otherwise = go x0 where go x = I# x : if isTrue# (x ==# y) then [] else go (x +# 1#) {-# INLINE [0] eftIntFB #-} eftIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> r eftIntFB c n x0 y | isTrue# (x0 ># y) = n | otherwise = go x0 where go x = I# x `c` if isTrue# (x ==# y) then n else go (x +# 1#) -- Watch out for y=maxBound; hence ==, not > -- Be very careful not to have more than one "c" -- so that when eftInfFB is inlined we can inline -- whatever is bound to "c" ----------------------------------------------------- -- efdInt and efdtInt deal with [a,b..] and [a,b..c]. -- The code is more complicated because of worries about Int overflow. {-# RULES "efdtInt" [~1] forall x1 x2 y. efdtInt x1 x2 y = build (\ c n -> efdtIntFB c n x1 x2 y) "efdtIntUpList" [1] efdtIntFB (:) [] = efdtInt #-} efdInt :: Int# -> Int# -> [Int] -- [x1,x2..maxInt] efdInt x1 x2 | isTrue# (x2 >=# x1) = case maxInt of I# y -> efdtIntUp x1 x2 y | otherwise = case minInt of I# y -> efdtIntDn x1 x2 y {-# NOINLINE [1] efdtInt #-} efdtInt :: Int# -> Int# -> Int# -> [Int] -- [x1,x2..y] efdtInt x1 x2 y | isTrue# (x2 >=# x1) = efdtIntUp x1 x2 y | otherwise = efdtIntDn x1 x2 y {-# INLINE [0] efdtIntFB #-} efdtIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> Int# -> r efdtIntFB c n x1 x2 y | isTrue# (x2 >=# x1) = efdtIntUpFB c n x1 x2 y | otherwise = efdtIntDnFB c n x1 x2 y -- Requires x2 >= x1 efdtIntUp :: Int# -> Int# -> Int# -> [Int] efdtIntUp x1 x2 y -- Be careful about overflow! | isTrue# (y <# x2) = if isTrue# (y <# x1) then [] else [I# x1] | otherwise = -- Common case: x1 <= x2 <= y let !delta = x2 -# x1 -- >= 0 !y' = y -# delta -- x1 <= y' <= y; hence y' is representable -- Invariant: x <= y -- Note that: z <= y' => z + delta won't overflow -- so we are guaranteed not to overflow if/when we recurse go_up x | isTrue# (x ># y') = [I# x] | otherwise = I# x : go_up (x +# delta) in I# x1 : go_up x2 -- Requires x2 >= x1 efdtIntUpFB :: (Int -> r -> r) -> r -> Int# -> Int# -> Int# -> r efdtIntUpFB c n x1 x2 y -- Be careful about overflow! | isTrue# (y <# x2) = if isTrue# (y <# x1) then n else I# x1 `c` n | otherwise = -- Common case: x1 <= x2 <= y let !delta = x2 -# x1 -- >= 0 !y' = y -# delta -- x1 <= y' <= y; hence y' is representable -- Invariant: x <= y -- Note that: z <= y' => z + delta won't overflow -- so we are guaranteed not to overflow if/when we recurse go_up x | isTrue# (x ># y') = I# x `c` n | otherwise = I# x `c` go_up (x +# delta) in I# x1 `c` go_up x2 -- Requires x2 <= x1 efdtIntDn :: Int# -> Int# -> Int# -> [Int] efdtIntDn x1 x2 y -- Be careful about underflow! | isTrue# (y ># x2) = if isTrue# (y ># x1) then [] else [I# x1] | otherwise = -- Common case: x1 >= x2 >= y let !delta = x2 -# x1 -- <= 0 !y' = y -# delta -- y <= y' <= x1; hence y' is representable -- Invariant: x >= y -- Note that: z >= y' => z + delta won't underflow -- so we are guaranteed not to underflow if/when we recurse go_dn x | isTrue# (x <# y') = [I# x] | otherwise = I# x : go_dn (x +# delta) in I# x1 : go_dn x2 -- Requires x2 <= x1 efdtIntDnFB :: (Int -> r -> r) -> r -> Int# -> Int# -> Int# -> r efdtIntDnFB c n x1 x2 y -- Be careful about underflow! | isTrue# (y ># x2) = if isTrue# (y ># x1) then n else I# x1 `c` n | otherwise = -- Common case: x1 >= x2 >= y let !delta = x2 -# x1 -- <= 0 !y' = y -# delta -- y <= y' <= x1; hence y' is representable -- Invariant: x >= y -- Note that: z >= y' => z + delta won't underflow -- so we are guaranteed not to underflow if/when we recurse go_dn x | isTrue# (x <# y') = I# x `c` n | otherwise = I# x `c` go_dn (x +# delta) in I# x1 `c` go_dn x2 ------------------------------------------------------------------------ -- Word ------------------------------------------------------------------------ instance Bounded Word where minBound = 0 -- use unboxed literals for maxBound, because GHC doesn't optimise -- (fromInteger 0xffffffff :: Word). maxBound = W# (int2Word# 0xFFFFFFFF#) instance Enum Word where succ x | x /= maxBound = x + 1 | otherwise = succError "Word" pred x | x /= minBound = x - 1 | otherwise = predError "Word" toEnum i@(I# i#) | i >= 0 = W# (int2Word# i#) | otherwise = toEnumError "Word" i (minBound::Word, maxBound::Word) fromEnum x@(W# x#) | x <= maxIntWord = I# (word2Int# x#) | otherwise = fromEnumError "Word" x enumFrom n = map integerToWordX [wordToIntegerX n .. wordToIntegerX (maxBound :: Word)] enumFromTo n1 n2 = map integerToWordX [wordToIntegerX n1 .. wordToIntegerX n2] enumFromThenTo n1 n2 m = map integerToWordX [wordToIntegerX n1, wordToIntegerX n2 .. wordToIntegerX m] enumFromThen n1 n2 = map integerToWordX [wordToIntegerX n1, wordToIntegerX n2 .. wordToIntegerX limit] where limit :: Word limit | n2 >= n1 = maxBound | otherwise = minBound maxIntWord :: Word -- The biggest word representable as an Int maxIntWord = W# (case maxInt of I# i -> int2Word# i) -- For some reason integerToWord and wordToInteger (GHC.Integer.Type) -- work over Word# integerToWordX :: Integer -> Word integerToWordX i = W# (integerToWord i) wordToIntegerX :: Word -> Integer wordToIntegerX (W# x#) = wordToInteger x# ------------------------------------------------------------------------ -- Integer ------------------------------------------------------------------------ instance Enum Integer where succ x = x + 1 pred x = x - 1 toEnum (I# n) = smallInteger n fromEnum n = I# (integerToInt n) {-# INLINE enumFrom #-} {-# INLINE enumFromThen #-} {-# INLINE enumFromTo #-} {-# INLINE enumFromThenTo #-} enumFrom x = enumDeltaInteger x 1 enumFromThen x y = enumDeltaInteger x (y-x) enumFromTo x lim = enumDeltaToInteger x 1 lim enumFromThenTo x y lim = enumDeltaToInteger x (y-x) lim {-# RULES "enumDeltaInteger" [~1] forall x y. enumDeltaInteger x y = build (\c _ -> enumDeltaIntegerFB c x y) "efdtInteger" [~1] forall x y l.enumDeltaToInteger x y l = build (\c n -> enumDeltaToIntegerFB c n x y l) "enumDeltaInteger" [1] enumDeltaIntegerFB (:) = enumDeltaInteger "enumDeltaToInteger" [1] enumDeltaToIntegerFB (:) [] = enumDeltaToInteger #-} {-# NOINLINE [0] enumDeltaIntegerFB #-} enumDeltaIntegerFB :: (Integer -> b -> b) -> Integer -> Integer -> b enumDeltaIntegerFB c x d = x `seq` (x `c` enumDeltaIntegerFB c (x+d) d) {-# NOINLINE [1] enumDeltaInteger #-} enumDeltaInteger :: Integer -> Integer -> [Integer] enumDeltaInteger x d = x `seq` (x : enumDeltaInteger (x+d) d) -- strict accumulator, so -- head (drop 1000000 [1 .. ] -- works {-# NOINLINE [0] enumDeltaToIntegerFB #-} -- Don't inline this until RULE "enumDeltaToInteger" has had a chance to fire enumDeltaToIntegerFB :: (Integer -> a -> a) -> a -> Integer -> Integer -> Integer -> a enumDeltaToIntegerFB c n x delta lim | delta >= 0 = up_fb c n x delta lim | otherwise = dn_fb c n x delta lim {-# RULES "enumDeltaToInteger1" [0] forall c n x . enumDeltaToIntegerFB c n x 1 = up_fb c n x 1 #-} -- This rule ensures that in the common case (delta = 1), we do not do the check here, -- and also that we have the chance to inline up_fb, which would allow the constructor to be -- inlined and good things to happen. -- We do not do it for Int this way because hand-tuned code already exists, and -- the special case varies more from the general case, due to the issue of overflows. {-# NOINLINE [1] enumDeltaToInteger #-} enumDeltaToInteger :: Integer -> Integer -> Integer -> [Integer] enumDeltaToInteger x delta lim | delta >= 0 = up_list x delta lim | otherwise = dn_list x delta lim up_fb :: (Integer -> a -> a) -> a -> Integer -> Integer -> Integer -> a up_fb c n x0 delta lim = go (x0 :: Integer) where go x | x > lim = n | otherwise = x `c` go (x+delta) dn_fb :: (Integer -> a -> a) -> a -> Integer -> Integer -> Integer -> a dn_fb c n x0 delta lim = go (x0 :: Integer) where go x | x < lim = n | otherwise = x `c` go (x+delta) up_list :: Integer -> Integer -> Integer -> [Integer] up_list x0 delta lim = go (x0 :: Integer) where go x | x > lim = [] | otherwise = x : go (x+delta) dn_list :: Integer -> Integer -> Integer -> [Integer] dn_list x0 delta lim = go (x0 :: Integer) where go x | x < lim = [] | otherwise = x : go (x+delta)
alexander-at-github/eta
libraries/base/GHC/Enum.hs
bsd-3-clause
28,127
0
15
7,845
7,566
4,057
3,509
435
2
module Binary (tests) where import Control.Applicative import Data.Binary.Put import Data.Binary.Get import Linear import qualified Data.ByteString.Lazy as BS import Test.HUnit originalVecs :: (V3 Float, V2 Char) originalVecs = (V3 1 2 3, V2 'a' 'b') bytes :: BS.ByteString bytes = runPut $ do putLinear $ fst originalVecs putLinear $ snd originalVecs tests :: Test tests = test [ "Serialized length" ~: BS.length bytes ~?= 3*13+2 , "Deserialization" ~: deserialized ~?= originalVecs ] where deserialized = runGet ((,) <$> getLinear <*> getLinear) bytes
isomorphism/linear
tests/Binary.hs
bsd-3-clause
592
0
12
119
193
106
87
16
1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="id-ID"> <title>Mulai Cepat | Eksistensi ZAP</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Indeks</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Telusuri</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorit</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/quickstart/src/main/javahelp/org/zaproxy/zap/extension/quickstart/resources/help_id_ID/helpset_id_ID.hs
apache-2.0
974
78
66
159
413
209
204
-1
-1
{-# OPTIONS -fno-warn-orphans #-} {-# LANGUAGE TemplateHaskell, DeriveDataTypeable, RankNTypes, NoMonomorphismRestriction #-} module Lamdu.Data.Expression.Utils ( makeApply , makePi, makeLambda, makeLam , pureApply , pureHole , pureSet , pureRecord , pureLam , pureGetField , pureLiteralInteger , pureIntegerType , pureExpression , randomizeExpr , randomizeParamIds , randomizeParamIdsG , randomizeExprAndParams , NameGen(..), onNgMakeName , randomNameGen, debugNameGen , matchBody, matchExpression, matchExpressionG , subExpressions, subExpressionsWithout , isDependentPi, exprHasGetVar , curriedFuncArguments , ApplyFormAnnotation(..), applyForms , recordValForm, structureForType , alphaEq, couldEq , subst, substGetPar , showBodyExpr, showsPrecBodyExpr , isTypeConstructorType , addExpressionContexts , addBodyContexts , PiWrappers(..), piWrappersDepParams, piWrappersMIndepParam, piWrappersResultType , getPiWrappers ) where import Prelude hiding (pi) import Lamdu.Data.Expression import Control.Applicative (Applicative(..), liftA2, (<$>), (<$)) import Control.Arrow ((***)) import Control.Lens (Context(..)) import Control.Lens.Operators import Control.Lens.Utils (addListContexts, addTuple2Contexts) import Control.Monad (guard) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Reader (runReaderT) import Control.Monad.Trans.State (evalState, state) import Data.Map (Map) import Data.Maybe (isJust, fromMaybe) import Data.Monoid (Any) import Data.Store.Guid (Guid) import Data.Traversable (Traversable(..), sequenceA) import System.Random (Random, RandomGen, random) import qualified Control.Lens as Lens import qualified Control.Monad.Trans.Reader as Reader import qualified Data.Foldable as Foldable import qualified Data.List as List import qualified Data.List.Utils as ListUtils import qualified Data.Map as Map import qualified Data.Store.Guid as Guid import qualified Lamdu.Data.Expression.Lens as ExprLens import qualified System.Random as Random data PiWrappers def a = PiWrappers { _piWrappersDepParams :: [(Guid, Expression def a)] , _piWrappersMIndepParam :: Maybe (Guid, Expression def a) , _piWrappersResultType :: Expression def a } Lens.makeLenses ''PiWrappers data NameGen pl = NameGen { ngSplit :: (NameGen pl, NameGen pl) , ngMakeName :: Guid -> pl -> (Guid, NameGen pl) } onNgMakeName :: (NameGen b -> (Guid -> a -> (Guid, NameGen b)) -> Guid -> b -> (Guid, NameGen b)) -> NameGen a -> NameGen b onNgMakeName onMakeName = go where go nameGen = result where result = nameGen { ngMakeName = ngMakeName nameGen & Lens.mapped . Lens.mapped . Lens._2 %~ go & onMakeName result , ngSplit = ngSplit nameGen & Lens.both %~ go } getPiWrappers :: Expression def a -> PiWrappers def a getPiWrappers expr = case expr ^? ExprLens.exprLam of Just (Lam KType param paramType resultType) | isDependentPi expr -> getPiWrappers resultType & piWrappersDepParams %~ (p :) | otherwise -> PiWrappers { _piWrappersDepParams = [] , _piWrappersMIndepParam = Just p , _piWrappersResultType = resultType } where p = (param, paramType) _ -> PiWrappers [] Nothing expr couldEq :: Eq def => Expression def a -> Expression def a -> Bool couldEq x y = isJust $ matchExpression (const . Just) onMismatch x y where onMismatch (Expression (BodyLeaf Hole) _) e = Just e onMismatch e (Expression (BodyLeaf Hole) _) = Just e onMismatch _ _ = Nothing alphaEq :: Eq def => Expression def a -> Expression def a -> Bool alphaEq x y = isJust $ matchExpression ((const . const . Just) ()) ((const . const) Nothing) x y -- Useful functions: substGetPar :: Guid -> Expression def a -> Expression def a -> Expression def a substGetPar from = subst (ExprLens.exprParameterRef . Lens.filtered (== from)) subst :: Lens.Getting Any (Expression def a) b -> Expression def a -> Expression def a -> Expression def a subst lens to expr | Lens.has lens expr = to | otherwise = expr & eBody . traverse %~ subst lens to data ApplyFormAnnotation = Untouched | DependentParamAdded | IndependentParamAdded deriving Eq -- Transform expression to expression applied with holes, -- with all different sensible levels of currying. applyForms :: Expression def () -> Expression def () -> [Expression def ApplyFormAnnotation] applyForms exprType rawExpr | Lens.has (ExprLens.exprLam . lamKind . _KVal) expr = [expr] | otherwise = reverse withAllAppliesAdded where expr = Untouched <$ rawExpr withDepAppliesAdded = foldl (addApply DependentParamAdded) expr depParamTypes withAllAppliesAdded = scanl (addApply IndependentParamAdded) withDepAppliesAdded $ indepParamTypes ++ assumeHoleIsPi depParamTypes = snd <$> depParams indepParamTypes = mNonDepParam ^.. Lens._Just . Lens._2 assumeHoleIsPi | Lens.has ExprLens.exprHole resultType = [pureHole] | otherwise = [] PiWrappers { _piWrappersDepParams = depParams , _piWrappersMIndepParam = mNonDepParam , _piWrappersResultType = resultType } = getPiWrappers exprType addApply ann func paramType = Expression (makeApply func arg) ann where arg = ann <$ fromMaybe pureHole (recordValForm paramType) recordValForm :: Expression def () -> Maybe (Expression def ()) recordValForm paramType = replaceFieldTypesWithHoles <$> (paramType ^? ExprLens.exprKindedRecordFields KType) where replaceFieldTypesWithHoles fields = ExprLens.pureExpr . _BodyRecord . ExprLens.kindedRecordFields KVal # (fields & Lens.traversed . Lens._2 .~ pureHole) structureForType :: Expression def () -> Expression def () structureForType = (eBody %~) $ const (ExprLens.bodyHole # ()) & Lens.outside (ExprLens.bodyKindedRecordFields KType) .~ (ExprLens.bodyKindedRecordFields KVal # ) . (traverse . Lens._2 %~ structureForType) & Lens.outside (ExprLens.bodyKindedLam KType) .~ (ExprLens.bodyKindedLam KVal # ) . (Lens._3 %~ structureForType) randomizeExprAndParams :: (RandomGen gen, Random r) => gen -> Expression def (r -> a) -> Expression def a randomizeExprAndParams gen = randomizeParamIds paramGen . randomizeExpr exprGen where (exprGen, paramGen) = Random.split gen randomizeExpr :: (RandomGen gen, Random r) => gen -> Expression def (r -> a) -> Expression def a randomizeExpr gen (Expression body pl) = (`evalState` gen) $ do r <- state random newBody <- body & traverse %%~ randomizeSubexpr return . Expression newBody $ pl r where randomizeSubexpr subExpr = do localGen <- state Random.split return $ randomizeExpr localGen subExpr randomNameGen :: RandomGen g => g -> NameGen dummy randomNameGen g = NameGen { ngSplit = Random.split g & Lens.both %~ randomNameGen , ngMakeName = const . const $ random g & Lens._2 %~ randomNameGen } debugNameGen :: NameGen dummy debugNameGen = ng names "" where names = (:[]) <$> ['a'..'z'] ng [] _ = error "TODO: Infinite list of names" ng st@(l:ls) suffix = NameGen { ngSplit = (ng st "_0", ng st "_1") , ngMakeName = const . const $ (Guid.fromString (l++suffix), ng ls suffix) } randomizeParamIds :: RandomGen g => g -> Expression def a -> Expression def a randomizeParamIds gen = randomizeParamIdsG id (randomNameGen gen) Map.empty $ \_ _ a -> a randomizeParamIdsG :: (a -> n) -> NameGen n -> Map Guid Guid -> (NameGen n -> Map Guid Guid -> a -> b) -> Expression def a -> Expression def b randomizeParamIdsG preNG gen initMap convertPL = (`evalState` gen) . (`runReaderT` initMap) . go where go (Expression v s) = do guidMap <- Reader.ask newGen <- lift $ state ngSplit (`Expression` convertPL newGen guidMap s) <$> case v of BodyLam (Lam k oldParamId paramType body) -> do newParamId <- lift . state $ makeName oldParamId s fmap BodyLam $ liftA2 (Lam k newParamId) (go paramType) . Reader.local (Map.insert oldParamId newParamId) $ go body BodyLeaf (GetVariable (ParameterRef guid)) -> pure $ ExprLens.bodyParameterRef # fromMaybe guid (Map.lookup guid guidMap) x@BodyLeaf {} -> traverse go x x@BodyApply {} -> traverse go x x@BodyGetField {} -> traverse go x x@BodyRecord {} -> traverse go x makeName oldParamId s nameGen = ngMakeName nameGen oldParamId $ preNG s -- Left-biased on parameter guids {-# INLINE matchBody #-} matchBody :: Eq def => (Guid -> Guid -> a -> b -> c) -> -- ^ Lam/Pi result match (a -> b -> c) -> -- ^ Ordinary structural match (Apply components, param type) (Guid -> Guid -> Bool) -> -- ^ Match ParameterRef's Body def a -> Body def b -> Maybe (Body def c) matchBody matchLamResult matchOther matchGetPar body0 body1 = case body0 of BodyLam (Lam k0 p0 pt0 r0) -> do Lam k1 p1 pt1 r1 <- body1 ^? _BodyLam guard $ k0 == k1 return . BodyLam $ Lam k0 p0 (matchOther pt0 pt1) $ matchLamResult p0 p1 r0 r1 BodyApply (Apply f0 a0) -> do Apply f1 a1 <- body1 ^? _BodyApply return . BodyApply $ Apply (matchOther f0 f1) (matchOther a0 a1) BodyRecord (Record k0 fs0) -> do Record k1 fs1 <- body1 ^? _BodyRecord guard $ k0 == k1 BodyRecord . Record k0 <$> ListUtils.match matchPair fs0 fs1 BodyGetField (GetField r0 f0) -> do GetField r1 f1 <- body1 ^? _BodyGetField return . BodyGetField $ GetField (matchOther r0 r1) (matchOther f0 f1) BodyLeaf (GetVariable (ParameterRef p0)) -> do p1 <- body1 ^? ExprLens.bodyParameterRef guard $ matchGetPar p0 p1 return $ ExprLens.bodyParameterRef # p0 BodyLeaf x -> do y <- body1 ^? _BodyLeaf guard $ x == y return $ BodyLeaf x where matchPair (k0, v0) (k1, v1) = (matchOther k0 k1, matchOther v0 v1) -- The returned expression gets the same guids as the left -- expression {-# INLINE matchExpression #-} matchExpression :: (Eq def, Applicative f) => (a -> b -> f c) -> (Expression def a -> Expression def b -> f (Expression def c)) -> Expression def a -> Expression def b -> f (Expression def c) matchExpression = matchExpressionG . const . const $ pure () {-# INLINE matchExpressionG #-} matchExpressionG :: (Eq def, Applicative f) => (Guid -> Guid -> f ()) -> -- ^ Left expr guid overrides right expr guid (a -> b -> f c) -> (Expression def a -> Expression def b -> f (Expression def c)) -> Expression def a -> Expression def b -> f (Expression def c) matchExpressionG overrideGuids onMatch onMismatch = go Map.empty where go scope e0@(Expression body0 pl0) e1@(Expression body1 pl1) = case matchBody matchLamResult matchOther matchGetPar body0 body1 of Nothing -> onMismatch e0 $ (ExprLens.exprLeaves . ExprLens.parameterRef %~ lookupGuid) e1 Just bodyMatched -> Expression <$> sequenceA bodyMatched <*> onMatch pl0 pl1 where matchGetPar p0 p1 = p0 == lookupGuid p1 matchLamResult p0 p1 r0 r1 = overrideGuids p0 p1 *> go (Map.insert p1 p0 scope) r0 r1 matchOther = go scope lookupGuid guid = fromMaybe guid $ Map.lookup guid scope subExpressions :: Expression def a -> [Expression def a] subExpressions x = x : Foldable.concatMap subExpressions (x ^. eBody) subExpressionsWithout :: Lens.Traversal' (Expression def (Bool, a)) (Expression def (Bool, a)) -> Expression def a -> [Expression def a] subExpressionsWithout group = map (fmap snd) . filter (fst . (^. ePayload)) . subExpressions . (group . ePayload . Lens._1 .~ False) . fmap ((,) True) isDependentPi :: Expression def a -> Bool isDependentPi = Lens.has (ExprLens.exprKindedLam KType . Lens.filtered f) where f (g, _, resultType) = exprHasGetVar g resultType parameterRefs :: Lens.Fold (Expression def a) Guid parameterRefs = Lens.folding subExpressions . ExprLens.exprParameterRef exprHasGetVar :: Guid -> Expression def a -> Bool exprHasGetVar g = Lens.anyOf parameterRefs (== g) curriedFuncArguments :: Expression def a -> [Expression def a] curriedFuncArguments = (^.. ExprLens.exprLam . ExprLens.kindedLam KVal . Lens.folding f) where f (_, paramType, body) = paramType : curriedFuncArguments body pureIntegerType :: Expression def () pureIntegerType = ExprLens.pureExpr . ExprLens.bodyIntegerType # () pureLiteralInteger :: Integer -> Expression def () pureLiteralInteger = (ExprLens.pureExpr . ExprLens.bodyLiteralInteger # ) pureApply :: Expression def () -> Expression def () -> Expression def () pureApply f x = ExprLens.pureExpr . _BodyApply # Apply f x pureHole :: Expression def () pureHole = ExprLens.pureExpr . ExprLens.bodyHole # () pureSet :: Expression def () pureSet = ExprLens.pureExpr . ExprLens.bodyType # () pureRecord :: Kind -> [(Expression def (), Expression def ())] -> Expression def () pureRecord k fields = ExprLens.pureExpr . ExprLens.bodyKindedRecordFields k # fields pureLam :: Kind -> Guid -> Expression def () -> Expression def () -> Expression def () pureLam k paramGuid paramType result = ExprLens.pureExpr . ExprLens.bodyKindedLam k # (paramGuid, paramType, result) pureGetField :: Expression def () -> Expression def () -> Expression def () pureGetField record field = ExprLens.pureExpr . _BodyGetField # GetField record field -- TODO: Deprecate below here: pureExpression :: Body def (Expression def ()) -> Expression def () pureExpression = (ExprLens.pureExpr # ) makeApply :: expr -> expr -> Body def expr makeApply func arg = BodyApply $ Apply func arg makeLam :: Kind -> Guid -> expr -> expr -> Body def expr makeLam k argId argType resultType = BodyLam $ Lam k argId argType resultType -- TODO: Remove the kind-passing wrappers makePi :: Guid -> expr -> expr -> Body def expr makePi = makeLam KType makeLambda :: Guid -> expr -> expr -> Body def expr makeLambda = makeLam KVal isTypeConstructorType :: Expression def a -> Bool isTypeConstructorType expr = case expr ^. eBody of BodyLeaf Type -> True BodyLam (Lam KType _ _ res) -> isTypeConstructorType res _ -> False -- Show isntances: showsPrecBody :: (Show def, Show expr) => (Guid -> expr -> Bool) -> Int -> Body def expr -> ShowS showsPrecBody mayDepend prec body = case body of BodyLam (Lam KVal paramId paramType result) -> paren 0 $ showChar '\\' . shows paramId . showChar ':' . showsPrec 11 paramType . showString "==>" . shows result BodyLam (Lam KType paramId paramType resultType) -> paren 0 $ paramStr . showString "->" . shows resultType where paramStr | dependent = showString "(" . shows paramId . showString ":" . showsPrec 11 paramType . showString ")" | otherwise = showsPrec 1 paramType dependent = mayDepend paramId resultType BodyApply (Apply func arg) -> paren 10 $ showsPrec 10 func . showChar ' ' . showsPrec 11 arg BodyRecord (Record k fields) -> paren 11 $ showString recStr where recStr = concat ["Rec", recType k, "{", List.intercalate ", " (map showField fields), "}"] showField (field, typ) = unwords [show field, sep k, show typ] sep KVal = "=" sep KType = ":" recType KVal = "V" recType KType = "T" BodyGetField (GetField r tag) -> paren 8 $ showsPrec 8 r . showChar '.' . showsPrec 9 tag BodyLeaf leaf -> showsPrec prec leaf where paren innerPrec = showParen (prec > innerPrec) showsPrecBodyExpr :: (Show def, Show a) => Int -> BodyExpr def a -> ShowS showsPrecBodyExpr = showsPrecBody exprHasGetVar showBodyExpr :: BodyExpr String String -> String showBodyExpr = flip (showsPrecBodyExpr 0) "" instance (Show def, Show expr) => Show (Body def expr) where showsPrec = showsPrecBody mayDepend where -- We are polymorphic on any expr, so we cannot tell... mayDepend _ _ = True instance (Show def, Show a) => Show (Expression def a) where showsPrec prec (Expression body payload) = showsPrecBodyExpr bodyPrec body . showString showPayload where (bodyPrec, showPayload) = case show payload of "" -> (prec, "") "()" -> (prec, "") str -> (11, "{" ++ str ++ "}") addBodyContexts :: (a -> b) -> Context (Body def a) (Body def b) container -> Body def (Context a b container) addBodyContexts tob (Context intoContainer body) = afterSetter %~ intoContainer $ case body of BodyLam (Lam k paramId func arg) -> Lam k paramId (Context (flip (Lam k paramId) (tob arg)) func) (Context (Lam k paramId (tob func)) arg) & BodyLam & afterSetter %~ BodyLam BodyApply (Apply func arg) -> Apply (Context (`Apply` tob arg) func) (Context (tob func `Apply`) arg) & BodyApply & afterSetter %~ BodyApply BodyRecord (Record k fields) -> (Record k . map (addTuple2Contexts tob) . addListContexts (tob *** tob)) (Context (Record k) fields) & BodyRecord & afterSetter %~ BodyRecord BodyGetField (GetField record tag) -> GetField (Context (`GetField` tob tag) record) (Context (tob record `GetField`) tag) & BodyGetField & afterSetter %~ BodyGetField BodyLeaf leaf -> BodyLeaf leaf where afterSetter = Lens.mapped . Lens.mapped addExpressionContexts :: (a -> b) -> Context (Expression def a) (Expression def b) container -> Expression def (Context a (Expression def b) container) addExpressionContexts atob (Context intoContainer (Expression body a)) = Expression newBody (Context intoContainer a) where newBody = addExpressionContexts atob <$> addBodyContexts (fmap atob) bodyPtr bodyPtr = Context (intoContainer . (`Expression` atob a)) body
schell/lamdu
Lamdu/Data/Expression/Utils.hs
gpl-3.0
17,945
0
20
3,963
6,113
3,125
2,988
-1
-1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE PolyKinds #-} {-# OPTIONS_GHC -Werror=typed-holes #-} main :: IO () main = undefined data Proxy k = Proxy test1 = _ :: Proxy '[ 'True ] test2 = _ :: Proxy '[ '[ 1 ] ] test3 = _ :: Proxy '[ '( "Symbol", 1 ) ]
sdiehl/ghc
testsuite/tests/printer/T14343.hs
bsd-3-clause
251
0
9
56
90
52
38
9
1
-- | Use persistent-mongodb the same way you would use other persistent -- libraries and refer to the general persistent documentation. -- There are some new MongoDB specific filters under the filters section. -- These help extend your query into a nested document. -- -- However, at some point you will find the normal Persistent APIs lacking. -- and want lower level-level MongoDB access. -- There are functions available to make working with the raw driver -- easier: they are under the Entity conversion section. -- You should still use the same connection pool that you are using for Persistent. -- -- MongoDB is a schema-less database. -- The MongoDB Persistent backend does not help perform migrations. -- Unlike SQL backends, uniqueness constraints cannot be created for you. -- You must place a unique index on unique fields. {-# LANGUAGE CPP, PackageImports, OverloadedStrings, ScopedTypeVariables #-} {-# LANGUAGE DeriveDataTypeable, GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances, FlexibleContexts #-} {-# LANGUAGE RankNTypes, TypeFamilies #-} {-# LANGUAGE EmptyDataDecls #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE GADTs #-} module Database.Persist.MongoDB ( -- * Entity conversion collectionName , docToEntityEither , docToEntityThrow , entityToDocument , recordToDocument , documentFromEntity , toInsertDoc , entityToInsertDoc , updatesToDoc , filtersToDoc , toUniquesDoc -- * MongoDB specific queries -- $nested , (->.), (~>.), (?&->.), (?&~>.), (&->.), (&~>.) -- ** Filters -- $filters , nestEq, nestNe, nestGe, nestLe, nestIn, nestNotIn , anyEq, nestAnyEq, nestBsonEq, anyBsonEq, multiBsonEq , inList, ninList , (=~.) -- non-operator forms of filters , NestedField(..) , MongoRegexSearchable , MongoRegex -- ** Updates -- $updates , nestSet, nestInc, nestDec, nestMul, push, pull, pullAll, addToSet, eachOp -- * Key conversion helpers , BackendKey(..) , keyToOid , oidToKey , recordTypeFromKey , readMayObjectId , readMayMongoKey , keyToText -- * PersistField conversion , fieldName -- * using connections , withConnection , withMongoPool , withMongoDBConn , withMongoDBPool , createMongoDBPool , runMongoDBPool , runMongoDBPoolDef , ConnectionPool , Connection , MongoAuth (..) -- * Connection configuration , MongoConf (..) , defaultMongoConf , defaultHost , defaultAccessMode , defaultPoolStripes , defaultConnectionIdleTime , defaultStripeConnections , applyDockerEnv -- ** using raw MongoDB pipes , PipePool , createMongoDBPipePool , runMongoDBPipePool -- * network type , HostName , PortID -- * MongoDB driver types , Database , DB.Action , DB.AccessMode(..) , DB.master , DB.slaveOk , (DB.=:) , DB.ObjectId , DB.MongoContext -- * Database.Persist , module Database.Persist ) where import Database.Persist import qualified Database.Persist.Sql as Sql import qualified Control.Monad.IO.Class as Trans import Control.Exception (throw, throwIO) import Data.Acquire (mkAcquire) import qualified Data.Traversable as Traversable import Data.Bson (ObjectId(..)) import qualified Database.MongoDB as DB import Database.MongoDB.Query (Database) import Control.Applicative as A (Applicative, (<$>)) import Network (PortID (PortNumber)) import Network.Socket (HostName) import Data.Maybe (mapMaybe, fromJust) import qualified Data.Text as T import Data.Text (Text) import qualified Data.ByteString as BS import qualified Data.Text.Encoding as E import qualified Data.Serialize as Serialize import Web.PathPieces (PathPiece(..)) import Web.HttpApiData (ToHttpApiData(..), FromHttpApiData(..), parseUrlPieceMaybe, parseUrlPieceWithPrefix, readTextData) import Data.Conduit import Control.Monad.IO.Class (liftIO) import Data.Aeson (Value (Number), (.:), (.:?), (.!=), FromJSON(..), ToJSON(..), withText, withObject) import Data.Aeson.Types (modifyFailure) import Control.Monad (liftM, (>=>), forM_, unless) import qualified Data.Pool as Pool import Data.Time (NominalDiffTime) #ifdef HIGH_PRECISION_DATE import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds) #endif import Data.Time.Calendar (Day(..)) #if MIN_VERSION_aeson(0, 7, 0) #else import Data.Attoparsec.Number #endif import Data.Bits (shiftR) import Data.Word (Word16) import Data.Monoid (mappend) import Control.Monad.Trans.Reader (ask, runReaderT) import Control.Monad.Trans.Control (MonadBaseControl) import Numeric (readHex) import Unsafe.Coerce (unsafeCoerce) #if MIN_VERSION_base(4,6,0) import System.Environment (lookupEnv) #else import System.Environment (getEnvironment) #endif #ifdef DEBUG import FileLocation (debug) #endif #if !MIN_VERSION_base(4,6,0) lookupEnv :: String -> IO (Maybe String) lookupEnv key = do env <- getEnvironment return $ lookup key env #endif instance HasPersistBackend DB.MongoContext where type BaseBackend DB.MongoContext = DB.MongoContext persistBackend = id recordTypeFromKey :: Key record -> record recordTypeFromKey _ = error "recordTypeFromKey" newtype NoOrphanNominalDiffTime = NoOrphanNominalDiffTime NominalDiffTime deriving (Show, Eq, Num) instance FromJSON NoOrphanNominalDiffTime where #if MIN_VERSION_aeson(0, 7, 0) parseJSON (Number x) = (return . NoOrphanNominalDiffTime . fromRational . toRational) x #else parseJSON (Number (I x)) = (return . NoOrphanNominalDiffTime . fromInteger) x parseJSON (Number (D x)) = (return . NoOrphanNominalDiffTime . fromRational . toRational) x #endif parseJSON _ = fail "couldn't parse diff time" newtype NoOrphanPortID = NoOrphanPortID PortID deriving (Show, Eq) instance FromJSON NoOrphanPortID where #if MIN_VERSION_aeson(0, 7, 0) parseJSON (Number x) = (return . NoOrphanPortID . PortNumber . fromIntegral ) cnvX where cnvX :: Word16 cnvX = round x #else parseJSON (Number (I x)) = (return . NoOrphanPortID . PortNumber . fromInteger) x #endif parseJSON _ = fail "couldn't parse port number" data Connection = Connection DB.Pipe DB.Database type ConnectionPool = Pool.Pool Connection instance ToHttpApiData (BackendKey DB.MongoContext) where toUrlPiece = keyToText instance FromHttpApiData (BackendKey DB.MongoContext) where parseUrlPiece input = do s <- parseUrlPieceWithPrefix "o" input <!> return input MongoKey A.<$> readTextData s where infixl 3 <!> Left _ <!> y = y x <!> _ = x -- | ToPathPiece is used to convert a key to/from text instance PathPiece (BackendKey DB.MongoContext) where toPathPiece = toUrlPiece fromPathPiece = parseUrlPieceMaybe keyToText :: BackendKey DB.MongoContext -> Text keyToText = T.pack . show . unMongoKey -- | Convert a Text to a Key readMayMongoKey :: Text -> Maybe (BackendKey DB.MongoContext) readMayMongoKey = fmap MongoKey . readMayObjectId readMayObjectId :: Text -> Maybe DB.ObjectId readMayObjectId str = case filter (null . snd) $ reads $ T.unpack str :: [(DB.ObjectId,String)] of (parsed,_):[] -> Just parsed _ -> Nothing instance PersistField DB.ObjectId where toPersistValue = oidToPersistValue fromPersistValue oid@(PersistObjectId _) = Right $ persistObjectIdToDbOid oid fromPersistValue (PersistByteString bs) = fromPersistValue (PersistObjectId bs) fromPersistValue _ = Left $ T.pack "expected PersistObjectId" instance Sql.PersistFieldSql DB.ObjectId where sqlType _ = Sql.SqlOther "doesn't make much sense for MongoDB" instance Sql.PersistFieldSql (BackendKey DB.MongoContext) where sqlType _ = Sql.SqlOther "doesn't make much sense for MongoDB" withConnection :: (Trans.MonadIO m, A.Applicative m) => MongoConf -> (ConnectionPool -> m b) -> m b withConnection mc = withMongoDBPool (mgDatabase mc) (T.unpack $ mgHost mc) (mgPort mc) (mgAuth mc) (mgPoolStripes mc) (mgStripeConnections mc) (mgConnectionIdleTime mc) withMongoDBConn :: (Trans.MonadIO m, Applicative m) => Database -> HostName -> PortID -> Maybe MongoAuth -> NominalDiffTime -> (ConnectionPool -> m b) -> m b withMongoDBConn dbname hostname port mauth connectionIdleTime = withMongoDBPool dbname hostname port mauth 1 1 connectionIdleTime createPipe :: HostName -> PortID -> IO DB.Pipe createPipe hostname port = DB.connect (DB.Host hostname port) createReplicatSet :: (DB.ReplicaSetName, [DB.Host]) -> Database -> Maybe MongoAuth -> IO Connection createReplicatSet rsSeed dbname mAuth = do pipe <- DB.openReplicaSet rsSeed >>= DB.primary testAccess pipe dbname mAuth return $ Connection pipe dbname createRsPool :: (Trans.MonadIO m, Applicative m) => Database -> ReplicaSetConfig -> Maybe MongoAuth -> Int -- ^ pool size (number of stripes) -> Int -- ^ stripe size (number of connections per stripe) -> NominalDiffTime -- ^ time a connection is left idle before closing -> m ConnectionPool createRsPool dbname (ReplicaSetConfig rsName rsHosts) mAuth connectionPoolSize stripeSize connectionIdleTime = do Trans.liftIO $ Pool.createPool (createReplicatSet (rsName, rsHosts) dbname mAuth) (\(Connection pipe _) -> DB.close pipe) connectionPoolSize connectionIdleTime stripeSize testAccess :: DB.Pipe -> Database -> Maybe MongoAuth -> IO () testAccess pipe dbname mAuth = do _ <- case mAuth of Just (MongoAuth user pass) -> DB.access pipe DB.UnconfirmedWrites dbname (DB.auth user pass) Nothing -> return undefined return () createConnection :: Database -> HostName -> PortID -> Maybe MongoAuth -> IO Connection createConnection dbname hostname port mAuth = do pipe <- createPipe hostname port testAccess pipe dbname mAuth return $ Connection pipe dbname createMongoDBPool :: (Trans.MonadIO m, Applicative m) => Database -> HostName -> PortID -> Maybe MongoAuth -> Int -- ^ pool size (number of stripes) -> Int -- ^ stripe size (number of connections per stripe) -> NominalDiffTime -- ^ time a connection is left idle before closing -> m ConnectionPool createMongoDBPool dbname hostname port mAuth connectionPoolSize stripeSize connectionIdleTime = do Trans.liftIO $ Pool.createPool (createConnection dbname hostname port mAuth) (\(Connection pipe _) -> DB.close pipe) connectionPoolSize connectionIdleTime stripeSize createMongoPool :: (Trans.MonadIO m, Applicative m) => MongoConf -> m ConnectionPool createMongoPool c@MongoConf{mgReplicaSetConfig = Just (ReplicaSetConfig rsName hosts)} = createRsPool (mgDatabase c) (ReplicaSetConfig rsName ((DB.Host (T.unpack $ mgHost c) (mgPort c)):hosts)) (mgAuth c) (mgPoolStripes c) (mgStripeConnections c) (mgConnectionIdleTime c) createMongoPool c@MongoConf{mgReplicaSetConfig = Nothing} = createMongoDBPool (mgDatabase c) (T.unpack (mgHost c)) (mgPort c) (mgAuth c) (mgPoolStripes c) (mgStripeConnections c) (mgConnectionIdleTime c) type PipePool = Pool.Pool DB.Pipe -- | A pool of plain MongoDB pipes. -- The database parameter has not yet been applied yet. -- This is useful for switching between databases (on the same host and port) -- Unlike the normal pool, no authentication is available createMongoDBPipePool :: (Trans.MonadIO m, Applicative m) => HostName -> PortID -> Int -- ^ pool size (number of stripes) -> Int -- ^ stripe size (number of connections per stripe) -> NominalDiffTime -- ^ time a connection is left idle before closing -> m PipePool createMongoDBPipePool hostname port connectionPoolSize stripeSize connectionIdleTime = Trans.liftIO $ Pool.createPool (createPipe hostname port) DB.close connectionPoolSize connectionIdleTime stripeSize withMongoPool :: (Trans.MonadIO m, Applicative m) => MongoConf -> (ConnectionPool -> m b) -> m b withMongoPool conf connectionReader = createMongoPool conf >>= connectionReader withMongoDBPool :: (Trans.MonadIO m, Applicative m) => Database -> HostName -> PortID -> Maybe MongoAuth -> Int -> Int -> NominalDiffTime -> (ConnectionPool -> m b) -> m b withMongoDBPool dbname hostname port mauth poolStripes stripeConnections connectionIdleTime connectionReader = do pool <- createMongoDBPool dbname hostname port mauth poolStripes stripeConnections connectionIdleTime connectionReader pool -- | run a pool created with 'createMongoDBPipePool' runMongoDBPipePool :: (Trans.MonadIO m, MonadBaseControl IO m) => DB.AccessMode -> Database -> DB.Action m a -> PipePool -> m a runMongoDBPipePool accessMode db action pool = Pool.withResource pool $ \pipe -> DB.access pipe accessMode db action runMongoDBPool :: (Trans.MonadIO m, MonadBaseControl IO m) => DB.AccessMode -> DB.Action m a -> ConnectionPool -> m a runMongoDBPool accessMode action pool = Pool.withResource pool $ \(Connection pipe db) -> DB.access pipe accessMode db action -- | use default 'AccessMode' runMongoDBPoolDef :: (Trans.MonadIO m, MonadBaseControl IO m) => DB.Action m a -> ConnectionPool -> m a runMongoDBPoolDef = runMongoDBPool defaultAccessMode queryByKey :: (PersistEntity record, PersistEntityBackend record ~ DB.MongoContext) => Key record -> DB.Query queryByKey k = (DB.select (keyToMongoDoc k) (collectionNameFromKey k)) {DB.project = projectionFromKey k} selectByKey :: (PersistEntity record, PersistEntityBackend record ~ DB.MongoContext) => Key record -> DB.Selection selectByKey k = DB.select (keyToMongoDoc k) (collectionNameFromKey k) updatesToDoc :: (PersistEntity record, PersistEntityBackend record ~ DB.MongoContext) => [Update record] -> DB.Document updatesToDoc upds = map updateToMongoField upds updateToBson :: Text -> PersistValue -> Either PersistUpdate MongoUpdateOperation -> DB.Field updateToBson fname v up = #ifdef DEBUG debug ( #endif opName DB.:= DB.Doc [fname DB.:= opValue] #ifdef DEBUG ) #endif where inc = "$inc" mul = "$mul" (opName, opValue) = case up of Left pup -> case (pup, v) of (Assign, PersistNull) -> ("$unset", DB.Int64 1) (Assign,a) -> ("$set", DB.val a) (Add, a) -> (inc, DB.val a) (Subtract, PersistInt64 i) -> (inc, DB.Int64 (-i)) (Multiply, PersistInt64 i) -> (mul, DB.Int64 i) (Multiply, PersistDouble d) -> (mul, DB.Float d) (Subtract, _) -> error "expected PersistInt64 for a subtraction" (Multiply, _) -> error "expected PersistInt64 or PersistDouble for a subtraction" -- Obviously this could be supported for floats by multiplying with 1/x (Divide, _) -> throw $ PersistMongoDBUnsupported "divide not supported" (BackendSpecificUpdate bsup, _) -> throw $ PersistMongoDBError $ T.pack $ "did not expect BackendSpecificUpdate " ++ T.unpack bsup Right mup -> case mup of MongoEach op -> case op of MongoPull -> ("$pullAll", DB.val v) _ -> (opToText op, DB.Doc ["$each" DB.:= DB.val v]) MongoSimple x -> (opToText x, DB.val v) updateToMongoField :: (PersistEntity record, PersistEntityBackend record ~ DB.MongoContext) => Update record -> DB.Field updateToMongoField (Update field v up) = updateToBson (fieldName field) (toPersistValue v) (Left up) updateToMongoField (BackendUpdate up) = mongoUpdateToDoc up -- | convert a unique key into a MongoDB document toUniquesDoc :: forall record. (PersistEntity record) => Unique record -> [DB.Field] toUniquesDoc uniq = zipWith (DB.:=) (map (unDBName . snd) $ persistUniqueToFieldNames uniq) (map DB.val (persistUniqueToValues uniq)) -- | convert a PersistEntity into document fields. -- for inserts only: nulls are ignored so they will be unset in the document. -- 'entityToDocument' includes nulls toInsertDoc :: forall record. (PersistEntity record, PersistEntityBackend record ~ DB.MongoContext) => record -> DB.Document toInsertDoc record = zipFilter (embeddedFields $ toEmbedEntityDef entDef) (map toPersistValue $ toPersistFields record) where entDef = entityDef $ Just record zipFilter :: [EmbedFieldDef] -> [PersistValue] -> DB.Document zipFilter [] _ = [] zipFilter _ [] = [] zipFilter (fd:efields) (pv:pvs) = if isNull pv then recur else (fieldToLabel fd DB.:= embeddedVal (emFieldEmbed fd) pv):recur where recur = zipFilter efields pvs isNull PersistNull = True isNull (PersistMap m) = null m isNull (PersistList l) = null l isNull _ = False -- make sure to removed nulls from embedded entities also embeddedVal :: Maybe EmbedEntityDef -> PersistValue -> DB.Value embeddedVal (Just emDef) (PersistMap m) = DB.Doc $ zipFilter (embeddedFields emDef) $ map snd m embeddedVal je@(Just _) (PersistList l) = DB.Array $ map (embeddedVal je) l embeddedVal _ pv = DB.val pv entityToInsertDoc :: forall record. (PersistEntity record, PersistEntityBackend record ~ DB.MongoContext) => Entity record -> DB.Document entityToInsertDoc (Entity key record) = keyToMongoDoc key ++ toInsertDoc record collectionName :: (PersistEntity record, PersistEntityBackend record ~ DB.MongoContext) => record -> Text collectionName = unDBName . entityDB . entityDef . Just -- | convert a PersistEntity into document fields. -- unlike 'toInsertDoc', nulls are included. recordToDocument :: (PersistEntity record, PersistEntityBackend record ~ DB.MongoContext) => record -> DB.Document recordToDocument record = zipToDoc (map fieldDB $ entityFields entity) (toPersistFields record) where entity = entityDef $ Just record entityToDocument :: (PersistEntity record, PersistEntityBackend record ~ DB.MongoContext) => record -> DB.Document entityToDocument = recordToDocument {-# DEPRECATED entityToDocument "use recordToDocument" #-} documentFromEntity :: (PersistEntity record, PersistEntityBackend record ~ DB.MongoContext) => Entity record -> DB.Document documentFromEntity (Entity key record) = keyToMongoDoc key ++ entityToDocument record zipToDoc :: PersistField a => [DBName] -> [a] -> [DB.Field] zipToDoc [] _ = [] zipToDoc _ [] = [] zipToDoc (e:efields) (p:pfields) = let pv = toPersistValue p in (unDBName e DB.:= DB.val pv):zipToDoc efields pfields fieldToLabel :: EmbedFieldDef -> Text fieldToLabel = unDBName . emFieldDB keyFrom_idEx :: (Trans.MonadIO m, PersistEntity record) => DB.Value -> m (Key record) keyFrom_idEx idVal = case keyFrom_id idVal of Right k -> return k Left err -> liftIO $ throwIO $ PersistMongoDBError $ "could not convert key: " `Data.Monoid.mappend` T.pack (show idVal) `mappend` err keyFrom_id :: (PersistEntity record) => DB.Value -> Either Text (Key record) keyFrom_id idVal = case cast idVal of (PersistMap m) -> keyFromValues $ map snd m pv -> keyFromValues [pv] -- | It would make sense to define the instance for ObjectId -- and then use newtype deriving -- however, that would create an orphan instance instance ToJSON (BackendKey DB.MongoContext) where toJSON (MongoKey (Oid x y)) = toJSON $ DB.showHexLen 8 x $ DB.showHexLen 16 y "" instance FromJSON (BackendKey DB.MongoContext) where parseJSON = withText "MongoKey" $ \t -> maybe (fail "Invalid base64") (return . MongoKey . persistObjectIdToDbOid . PersistObjectId) $ fmap (i2bs (8 * 12) . fst) $ headMay $ readHex $ T.unpack t where -- should these be exported from Types/Base.hs ? headMay [] = Nothing headMay (x:_) = Just x -- taken from crypto-api -- |@i2bs bitLen i@ converts @i@ to a 'ByteString' of @bitLen@ bits (must be a multiple of 8). i2bs :: Int -> Integer -> BS.ByteString i2bs l i = BS.unfoldr (\l' -> if l' < 0 then Nothing else Just (fromIntegral (i `shiftR` l'), l' - 8)) (l-8) {-# INLINE i2bs #-} -- | older versions versions of haddock (like that on hackage) do not show that this defines -- @BackendKey DB.MongoContext = MongoKey { unMongoKey :: DB.ObjectId }@ instance PersistCore DB.MongoContext where newtype BackendKey DB.MongoContext = MongoKey { unMongoKey :: DB.ObjectId } deriving (Show, Read, Eq, Ord, PersistField) instance PersistStoreWrite DB.MongoContext where insert record = DB.insert (collectionName record) (toInsertDoc record) >>= keyFrom_idEx insertMany [] = return [] insertMany records@(r:_) = mapM keyFrom_idEx =<< DB.insertMany (collectionName r) (map toInsertDoc records) insertEntityMany [] = return () insertEntityMany ents@(Entity _ r : _) = DB.insertMany_ (collectionName r) (map entityToInsertDoc ents) insertKey k record = DB.insert_ (collectionName record) $ entityToInsertDoc (Entity k record) repsert k record = DB.save (collectionName record) $ documentFromEntity (Entity k record) replace k record = do DB.replace (selectByKey k) (recordToDocument record) return () delete k = DB.deleteOne DB.Select { DB.coll = collectionNameFromKey k , DB.selector = keyToMongoDoc k } update _ [] = return () update key upds = DB.modify (DB.Select (keyToMongoDoc key) (collectionNameFromKey key)) $ updatesToDoc upds updateGet key upds = do result <- DB.findAndModify (queryByKey key) (updatesToDoc upds) either err instantiate result where instantiate doc = do Entity _ rec <- fromPersistValuesThrow t doc return rec err msg = Trans.liftIO $ throwIO $ KeyNotFound $ show key ++ msg t = entityDefFromKey key instance PersistStoreRead DB.MongoContext where get k = do d <- DB.findOne (queryByKey k) case d of Nothing -> return Nothing Just doc -> do Entity _ ent <- fromPersistValuesThrow t doc return $ Just ent where t = entityDefFromKey k instance PersistUniqueRead DB.MongoContext where getBy uniq = do mdoc <- DB.findOne $ (DB.select (toUniquesDoc uniq) (collectionName rec)) {DB.project = projectionFromRecord rec} case mdoc of Nothing -> return Nothing Just doc -> liftM Just $ fromPersistValuesThrow t doc where t = entityDef $ Just rec rec = dummyFromUnique uniq instance PersistUniqueWrite DB.MongoContext where deleteBy uniq = DB.delete DB.Select { DB.coll = collectionName $ dummyFromUnique uniq , DB.selector = toUniquesDoc uniq } upsert newRecord upds = do uniq <- onlyUnique newRecord upsertBy uniq newRecord upds -- - let uniqKeys = map DB.label uniqueDoc -- - let insDoc = DB.exclude uniqKeys $ toInsertDoc newRecord -- let selection = DB.select uniqueDoc $ collectionName newRecord -- - if null upds -- - then DB.upsert selection ["$set" DB.=: insDoc] -- - else do -- - DB.upsert selection ["$setOnInsert" DB.=: insDoc] -- - DB.modify selection $ updatesToDoc upds -- - -- because findAndModify $setOnInsert is broken we do a separate get now upsertBy uniq newRecord upds = do let uniqueDoc = toUniquesDoc uniq :: [DB.Field] let uniqKeys = map DB.label uniqueDoc :: [DB.Label] let insDoc = DB.exclude uniqKeys $ toInsertDoc newRecord :: DB.Document let selection = DB.select uniqueDoc $ collectionName newRecord :: DB.Selection mdoc <- getBy uniq case mdoc of Nothing -> unless (null upds) (DB.upsert selection ["$setOnInsert" DB.=: insDoc]) Just _ -> unless (null upds) (DB.modify selection $ DB.exclude uniqKeys $ updatesToDoc upds) newMdoc <- getBy uniq case newMdoc of Nothing -> err "possible race condition: getBy found Nothing" Just doc -> return doc where err = Trans.liftIO . throwIO . UpsertError {- -- cannot use findAndModify -- because $setOnInsert is crippled -- https://jira.mongodb.org/browse/SERVER-2643 result <- DB.findAndModifyOpts selection (DB.defFamUpdateOpts ("$setOnInsert" DB.=: insDoc : ["$set" DB.=: insDoc])) { DB.famUpsert = True } either err instantiate result where -- this is only possible when new is False instantiate Nothing = error "upsert: impossible null" instantiate (Just doc) = fromPersistValuesThrow (entityDef $ Just newRecord) doc -} -- | It would make more sense to call this _id, but GHC treats leading underscore in special ways id_ :: T.Text id_ = "_id" -- _id is always the primary key in MongoDB -- but _id can contain any unique value keyToMongoDoc :: (PersistEntity record, PersistEntityBackend record ~ DB.MongoContext) => Key record -> DB.Document keyToMongoDoc k = case entityPrimary $ entityDefFromKey k of Nothing -> zipToDoc [DBName id_] values Just pdef -> [id_ DB.=: zipToDoc (primaryNames pdef) values] where primaryNames = map fieldDB . compositeFields values = keyToValues k entityDefFromKey :: PersistEntity record => Key record -> EntityDef entityDefFromKey = entityDef . Just . recordTypeFromKey collectionNameFromKey :: (PersistEntity record, PersistEntityBackend record ~ DB.MongoContext) => Key record -> Text collectionNameFromKey = collectionName . recordTypeFromKey projectionFromEntityDef :: EntityDef -> DB.Projector projectionFromEntityDef eDef = map toField (entityFields eDef) where toField :: FieldDef -> DB.Field toField fDef = (unDBName (fieldDB fDef)) DB.=: (1 :: Int) projectionFromKey :: PersistEntity record => Key record -> DB.Projector projectionFromKey = projectionFromEntityDef . entityDefFromKey projectionFromRecord :: PersistEntity record => record -> DB.Projector projectionFromRecord = projectionFromEntityDef . entityDef . Just instance PersistQueryWrite DB.MongoContext where updateWhere _ [] = return () updateWhere filts upds = DB.modify DB.Select { DB.coll = collectionName $ dummyFromFilts filts , DB.selector = filtersToDoc filts } $ updatesToDoc upds deleteWhere filts = do DB.delete DB.Select { DB.coll = collectionName $ dummyFromFilts filts , DB.selector = filtersToDoc filts } instance PersistQueryRead DB.MongoContext where count filts = do i <- DB.count query return $ fromIntegral i where query = DB.select (filtersToDoc filts) $ collectionName $ dummyFromFilts filts -- | uses cursor option NoCursorTimeout -- If there is no sorting, it will turn the $snapshot option on -- and explicitly closes the cursor when done selectSourceRes filts opts = do context <- ask return (pullCursor context `fmap` mkAcquire (open context) (close context)) where close :: DB.MongoContext -> DB.Cursor -> IO () close context cursor = runReaderT (DB.closeCursor cursor) context open :: DB.MongoContext -> IO DB.Cursor open = runReaderT (DB.find (makeQuery filts opts) -- it is an error to apply $snapshot when sorting { DB.snapshot = noSort , DB.options = [DB.NoCursorTimeout] }) pullCursor context cursor = do mdoc <- liftIO $ runReaderT (DB.nextBatch cursor) context case mdoc of [] -> return () docs -> do forM_ docs $ fromPersistValuesThrow t >=> yield pullCursor context cursor t = entityDef $ Just $ dummyFromFilts filts (_, _, orders) = limitOffsetOrder opts noSort = null orders selectFirst filts opts = DB.findOne (makeQuery filts opts) >>= Traversable.mapM (fromPersistValuesThrow t) where t = entityDef $ Just $ dummyFromFilts filts selectKeysRes filts opts = do context <- ask let make = do cursor <- liftIO $ flip runReaderT context $ DB.find $ (makeQuery filts opts) { DB.project = [id_ DB.=: (1 :: Int)] } pullCursor context cursor return $ return make where pullCursor context cursor = do mdoc <- liftIO $ runReaderT (DB.next cursor) context case mdoc of Nothing -> return () Just [_id DB.:= idVal] -> do k <- liftIO $ keyFrom_idEx idVal yield k pullCursor context cursor Just y -> liftIO $ throwIO $ PersistMarshalError $ T.pack $ "Unexpected in selectKeys: " ++ show y orderClause :: PersistEntity val => SelectOpt val -> DB.Field orderClause o = case o of Asc f -> fieldName f DB.=: ( 1 :: Int) Desc f -> fieldName f DB.=: (-1 :: Int) _ -> error "orderClause: expected Asc or Desc" makeQuery :: (PersistEntity record, PersistEntityBackend record ~ DB.MongoContext) => [Filter record] -> [SelectOpt record] -> DB.Query makeQuery filts opts = (DB.select (filtersToDoc filts) (collectionName $ dummyFromFilts filts)) { DB.limit = fromIntegral limit , DB.skip = fromIntegral offset , DB.sort = orders , DB.project = projectionFromRecord (dummyFromFilts filts) } where (limit, offset, orders') = limitOffsetOrder opts orders = map orderClause orders' filtersToDoc :: (PersistEntity record, PersistEntityBackend record ~ DB.MongoContext) => [Filter record] -> DB.Document filtersToDoc filts = #ifdef DEBUG debug $ #endif if null filts then [] else multiFilter AndDollar filts filterToDocument :: (PersistEntity val, PersistEntityBackend val ~ DB.MongoContext) => Filter val -> DB.Document filterToDocument f = case f of Filter field v filt -> [filterToBSON (fieldName field) v filt] BackendFilter mf -> mongoFilterToDoc mf -- The empty filter case should never occur when the user uses ||. -- An empty filter list will throw an exception in multiFilter -- -- The alternative would be to create a query which always returns true -- However, I don't think an end user ever wants that. FilterOr fs -> multiFilter OrDollar fs -- Ignore an empty filter list instead of throwing an exception. -- \$and is necessary in only a few cases, but it makes query construction easier FilterAnd [] -> [] FilterAnd fs -> multiFilter AndDollar fs data MultiFilter = OrDollar | AndDollar deriving Show toMultiOp :: MultiFilter -> Text toMultiOp OrDollar = orDollar toMultiOp AndDollar = andDollar multiFilter :: forall record. (PersistEntity record, PersistEntityBackend record ~ DB.MongoContext) => MultiFilter -> [Filter record] -> [DB.Field] multiFilter _ [] = throw $ PersistMongoDBError "An empty list of filters was given" multiFilter multi filters = case (multi, filter (not . null) (map filterToDocument filters)) of -- a $or must have at least 2 items (OrDollar, []) -> orError (AndDollar, []) -> [] (OrDollar, _:[]) -> orError (AndDollar, doc:[]) -> doc (_, doc) -> [toMultiOp multi DB.:= DB.Array (map DB.Doc doc)] where orError = throw $ PersistMongoDBError $ "An empty list of filters was given to one side of ||." existsDollar, orDollar, andDollar :: Text existsDollar = "$exists" orDollar = "$or" andDollar = "$and" filterToBSON :: forall a. ( PersistField a) => Text -> Either a [a] -> PersistFilter -> DB.Field filterToBSON fname v filt = case filt of Eq -> nullEq Ne -> nullNeq _ -> notEquality where dbv = toValue v notEquality = fname DB.=: [showFilter filt DB.:= dbv] nullEq = case dbv of DB.Null -> orDollar DB.=: [ [fname DB.:= DB.Null] , [fname DB.:= DB.Doc [existsDollar DB.:= DB.Bool False]] ] _ -> fname DB.:= dbv nullNeq = case dbv of DB.Null -> fname DB.:= DB.Doc [ showFilter Ne DB.:= DB.Null , existsDollar DB.:= DB.Bool True ] _ -> notEquality showFilter Ne = "$ne" showFilter Gt = "$gt" showFilter Lt = "$lt" showFilter Ge = "$gte" showFilter Le = "$lte" showFilter In = "$in" showFilter NotIn = "$nin" showFilter Eq = error "EQ filter not expected" showFilter (BackendSpecificFilter bsf) = throw $ PersistMongoDBError $ T.pack $ "did not expect BackendSpecificFilter " ++ T.unpack bsf mongoFilterToBSON :: forall typ. PersistField typ => Text -> MongoFilterOperator typ -> DB.Document mongoFilterToBSON fname filt = case filt of (PersistFilterOperator v op) -> [filterToBSON fname v op] (MongoFilterOperator bval) -> [fname DB.:= bval] mongoUpdateToBson :: forall typ. PersistField typ => Text -> UpdateValueOp typ -> DB.Field mongoUpdateToBson fname upd = case upd of UpdateValueOp (Left v) op -> updateToBson fname (toPersistValue v) op UpdateValueOp (Right v) op -> updateToBson fname (PersistList $ map toPersistValue v) op mongoUpdateToDoc :: PersistEntity record => MongoUpdate record -> DB.Field mongoUpdateToDoc (NestedUpdate field op) = mongoUpdateToBson (nestedFieldName field) op mongoUpdateToDoc (ArrayUpdate field op) = mongoUpdateToBson (fieldName field) op mongoFilterToDoc :: PersistEntity record => MongoFilter record -> DB.Document mongoFilterToDoc (NestedFilter field op) = mongoFilterToBSON (nestedFieldName field) op mongoFilterToDoc (ArrayFilter field op) = mongoFilterToBSON (fieldName field) op mongoFilterToDoc (NestedArrayFilter field op) = mongoFilterToBSON (nestedFieldName field) op mongoFilterToDoc (RegExpFilter fn (reg, opts)) = [ fieldName fn DB.:= DB.RegEx (DB.Regex reg opts)] nestedFieldName :: forall record typ. PersistEntity record => NestedField record typ -> Text nestedFieldName = T.intercalate "." . nesFldName where nesFldName :: forall r1 r2. (PersistEntity r1) => NestedField r1 r2 -> [DB.Label] nesFldName (nf1 `LastEmbFld` nf2) = [fieldName nf1, fieldName nf2] nesFldName ( f1 `MidEmbFld` f2) = fieldName f1 : nesFldName f2 nesFldName ( f1 `MidNestFlds` f2) = fieldName f1 : nesFldName f2 nesFldName ( f1 `MidNestFldsNullable` f2) = fieldName f1 : nesFldName f2 nesFldName (nf1 `LastNestFld` nf2) = [fieldName nf1, fieldName nf2] nesFldName (nf1 `LastNestFldNullable` nf2) = [fieldName nf1, fieldName nf2] toValue :: forall a. PersistField a => Either a [a] -> DB.Value toValue val = case val of Left v -> DB.val $ toPersistValue v Right vs -> DB.val $ map toPersistValue vs fieldName :: forall record typ. (PersistEntity record) => EntityField record typ -> DB.Label fieldName f | fieldHaskell fd == HaskellName "Id" = id_ | otherwise = unDBName $ fieldDB $ fd where fd = persistFieldDef f docToEntityEither :: forall record. (PersistEntity record) => DB.Document -> Either T.Text (Entity record) docToEntityEither doc = entity where entDef = entityDef $ Just (getType entity) entity = eitherFromPersistValues entDef doc getType :: Either err (Entity ent) -> ent getType = error "docToEntityEither/getType: never here" docToEntityThrow :: forall m record. (Trans.MonadIO m, PersistEntity record, PersistEntityBackend record ~ DB.MongoContext) => DB.Document -> m (Entity record) docToEntityThrow doc = case docToEntityEither doc of Left s -> Trans.liftIO . throwIO $ PersistMarshalError $ s Right entity -> return entity fromPersistValuesThrow :: (Trans.MonadIO m, PersistEntity record, PersistEntityBackend record ~ DB.MongoContext) => EntityDef -> [DB.Field] -> m (Entity record) fromPersistValuesThrow entDef doc = case eitherFromPersistValues entDef doc of Left t -> Trans.liftIO . throwIO $ PersistMarshalError $ unHaskellName (entityHaskell entDef) `mappend` ": " `mappend` t Right entity -> return entity mapLeft :: (a -> c) -> Either a b -> Either c b mapLeft _ (Right r) = Right r mapLeft f (Left l) = Left (f l) eitherFromPersistValues :: (PersistEntity record) => EntityDef -> [DB.Field] -> Either T.Text (Entity record) eitherFromPersistValues entDef doc = case mKey of Nothing -> addDetail $ Left $ "could not find _id field: " Just kpv -> do body <- addDetail (fromPersistValues (map snd $ orderPersistValues (toEmbedEntityDef entDef) castDoc)) key <- keyFromValues [kpv] return $ Entity key body where addDetail :: Either Text a -> Either Text a addDetail = mapLeft (\msg -> msg `mappend` " for doc: " `mappend` T.pack (show doc)) castDoc = assocListFromDoc doc -- normally _id is the first field mKey = lookup id_ castDoc -- | unlike many SQL databases, MongoDB makes no guarantee of the ordering -- of the fields returned in the document. -- Ordering might be maintained if persistent were the only user of the db, -- but other tools may be using MongoDB. -- -- Persistent creates a Haskell record from a list of PersistValue -- But most importantly it puts all PersistValues in the proper order orderPersistValues :: EmbedEntityDef -> [(Text, PersistValue)] -> [(Text, PersistValue)] orderPersistValues entDef castDoc = reorder where castColumns = map nameAndEmbed (embeddedFields entDef) nameAndEmbed fdef = (fieldToLabel fdef, emFieldEmbed fdef) -- TODO: the below reasoning should be re-thought now that we are no longer inserting null: searching for a null column will look at every returned field before giving up -- Also, we are now doing the _id lookup at the start. -- -- we have an alist of fields that need to be the same order as entityColumns -- -- this naive lookup is O(n^2) -- reorder = map (fromJust . (flip Prelude.lookup $ castDoc)) castColumns -- -- this is O(n * log(n)) -- reorder = map (\c -> (M.fromList castDoc) M.! c) castColumns -- -- and finally, this is O(n * log(n)) -- * do an alist lookup for each column -- * but once we found an item in the alist use a new alist without that item for future lookups -- * so for the last query there is only one item left -- reorder :: [(Text, PersistValue)] reorder = match castColumns castDoc [] where match :: [(Text, Maybe EmbedEntityDef)] -> [(Text, PersistValue)] -> [(Text, PersistValue)] -> [(Text, PersistValue)] -- when there are no more Persistent castColumns we are done -- -- allow extra mongoDB fields that persistent does not know about -- another application may use fields we don't care about -- our own application may set extra fields with the raw driver match [] _ values = values match (column:columns) fields values = let (found, unused) = matchOne fields [] in match columns unused $ values ++ [(fst column, nestedOrder (snd column) (snd found))] where nestedOrder (Just em) (PersistMap m) = PersistMap $ orderPersistValues em m nestedOrder (Just em) (PersistList l) = PersistList $ map (nestedOrder (Just em)) l -- implied: nestedOrder Nothing found = found nestedOrder _ found = found matchOne (field:fs) tried = if fst column == fst field -- snd drops the name now that it has been used to make the match -- persistent will add the field name later then (field, tried ++ fs) else matchOne fs (field:tried) -- if field is not found, assume it was a Nothing -- -- a Nothing could be stored as null, but that would take up space. -- instead, we want to store no field at all: that takes less space. -- Also, another ORM may be doing the same -- Also, this adding a Maybe field means no migration required matchOne [] tried = ((fst column, PersistNull), tried) assocListFromDoc :: DB.Document -> [(Text, PersistValue)] assocListFromDoc = Prelude.map (\f -> ( (DB.label f), cast (DB.value f) ) ) oidToPersistValue :: DB.ObjectId -> PersistValue oidToPersistValue = PersistObjectId . Serialize.encode oidToKey :: (ToBackendKey DB.MongoContext record) => DB.ObjectId -> Key record oidToKey = fromBackendKey . MongoKey persistObjectIdToDbOid :: PersistValue -> DB.ObjectId persistObjectIdToDbOid (PersistObjectId k) = case Serialize.decode k of Left msg -> throw $ PersistError $ T.pack $ "error decoding " ++ (show k) ++ ": " ++ msg Right o -> o persistObjectIdToDbOid _ = throw $ PersistInvalidField "expected PersistObjectId" keyToOid :: ToBackendKey DB.MongoContext record => Key record -> DB.ObjectId keyToOid = unMongoKey . toBackendKey instance DB.Val PersistValue where val (PersistInt64 x) = DB.Int64 x val (PersistText x) = DB.String x val (PersistDouble x) = DB.Float x val (PersistBool x) = DB.Bool x #ifdef HIGH_PRECISION_DATE val (PersistUTCTime x) = DB.Int64 $ round $ 1000 * 1000 * 1000 * (utcTimeToPOSIXSeconds x) #else -- this is just millisecond precision: https://jira.mongodb.org/browse/SERVER-1460 val (PersistUTCTime x) = DB.UTC x #endif val (PersistDay d) = DB.Int64 $ fromInteger $ toModifiedJulianDay d val (PersistNull) = DB.Null val (PersistList l) = DB.Array $ map DB.val l val (PersistMap m) = DB.Doc $ map (\(k, v)-> (DB.=:) k v) m val (PersistByteString x) = DB.Bin (DB.Binary x) val x@(PersistObjectId _) = DB.ObjId $ persistObjectIdToDbOid x val (PersistTimeOfDay _) = throw $ PersistMongoDBUnsupported "PersistTimeOfDay not implemented for the MongoDB backend. only PersistUTCTime currently implemented" val (PersistRational _) = throw $ PersistMongoDBUnsupported "PersistRational not implemented for the MongoDB backend" val (PersistDbSpecific _) = throw $ PersistMongoDBUnsupported "PersistDbSpecific not implemented for the MongoDB backend" cast' (DB.Float x) = Just (PersistDouble x) cast' (DB.Int32 x) = Just $ PersistInt64 $ fromIntegral x cast' (DB.Int64 x) = Just $ PersistInt64 x cast' (DB.String x) = Just $ PersistText x cast' (DB.Bool x) = Just $ PersistBool x cast' (DB.UTC d) = Just $ PersistUTCTime d cast' DB.Null = Just $ PersistNull cast' (DB.Bin (DB.Binary b)) = Just $ PersistByteString b cast' (DB.Fun (DB.Function f)) = Just $ PersistByteString f cast' (DB.Uuid (DB.UUID uid)) = Just $ PersistByteString uid cast' (DB.Md5 (DB.MD5 md5)) = Just $ PersistByteString md5 cast' (DB.UserDef (DB.UserDefined bs)) = Just $ PersistByteString bs cast' (DB.RegEx (DB.Regex us1 us2)) = Just $ PersistByteString $ E.encodeUtf8 $ T.append us1 us2 cast' (DB.Doc doc) = Just $ PersistMap $ assocListFromDoc doc cast' (DB.Array xs) = Just $ PersistList $ mapMaybe DB.cast' xs cast' (DB.ObjId x) = Just $ oidToPersistValue x cast' (DB.JavaScr _) = throw $ PersistMongoDBUnsupported "cast operation not supported for javascript" cast' (DB.Sym _) = throw $ PersistMongoDBUnsupported "cast operation not supported for sym" cast' (DB.Stamp _) = throw $ PersistMongoDBUnsupported "cast operation not supported for stamp" cast' (DB.MinMax _) = throw $ PersistMongoDBUnsupported "cast operation not supported for minmax" cast :: DB.Value -> PersistValue -- since we have case analysys this won't ever be Nothing -- However, unsupported types do throw an exception in pure code -- probably should re-work this to throw in IO cast = fromJust . DB.cast' instance Serialize.Serialize DB.ObjectId where put (DB.Oid w1 w2) = do Serialize.put w1 Serialize.put w2 get = do w1 <- Serialize.get w2 <- Serialize.get return (DB.Oid w1 w2) dummyFromUnique :: Unique v -> v dummyFromUnique _ = error "dummyFromUnique" dummyFromFilts :: [Filter v] -> v dummyFromFilts _ = error "dummyFromFilts" data MongoAuth = MongoAuth DB.Username DB.Password deriving Show -- | Information required to connect to a mongo database data MongoConf = MongoConf { mgDatabase :: Text , mgHost :: Text , mgPort :: PortID , mgAuth :: Maybe MongoAuth , mgAccessMode :: DB.AccessMode , mgPoolStripes :: Int , mgStripeConnections :: Int , mgConnectionIdleTime :: NominalDiffTime -- | YAML fields for this are @rsName@ and @rsSecondaries@ -- mgHost is assumed to be the primary , mgReplicaSetConfig :: Maybe ReplicaSetConfig } deriving Show defaultHost :: Text defaultHost = "127.0.0.1" defaultAccessMode :: DB.AccessMode defaultAccessMode = DB.ConfirmWrites ["w" DB.:= DB.Int32 1] defaultPoolStripes, defaultStripeConnections :: Int defaultPoolStripes = 1 defaultStripeConnections = 10 defaultConnectionIdleTime :: NominalDiffTime defaultConnectionIdleTime = 20 defaultMongoConf :: Text -> MongoConf defaultMongoConf dbName = MongoConf { mgDatabase = dbName , mgHost = defaultHost , mgPort = DB.defaultPort , mgAuth = Nothing , mgAccessMode = defaultAccessMode , mgPoolStripes = defaultPoolStripes , mgStripeConnections = defaultStripeConnections , mgConnectionIdleTime = defaultConnectionIdleTime , mgReplicaSetConfig = Nothing } data ReplicaSetConfig = ReplicaSetConfig DB.ReplicaSetName [DB.Host] deriving Show instance FromJSON MongoConf where parseJSON v = modifyFailure ("Persistent: error loading MongoDB conf: " ++) $ flip (withObject "MongoConf") v $ \o ->do db <- o .: "database" host <- o .:? "host" .!= defaultHost NoOrphanPortID port <- o .:? "port" .!= NoOrphanPortID DB.defaultPort poolStripes <- o .:? "poolstripes" .!= defaultPoolStripes stripeConnections <- o .:? "connections" .!= defaultStripeConnections NoOrphanNominalDiffTime connectionIdleTime <- o .:? "connectionIdleTime" .!= NoOrphanNominalDiffTime defaultConnectionIdleTime mUser <- o .:? "user" mPass <- o .:? "password" accessString <- o .:? "accessMode" .!= confirmWrites mRsName <- o .:? "rsName" rsSecondaires <- o .:? "rsSecondaries" .!= [] mPoolSize <- o .:? "poolsize" case mPoolSize of Nothing -> return () Just (_::Int) -> fail "specified deprecated poolsize attribute. Please specify a connections. You can also specify a pools attribute which defaults to 1. Total connections opened to the db are connections * pools" accessMode <- case accessString of "ReadStaleOk" -> return DB.ReadStaleOk "UnconfirmedWrites" -> return DB.UnconfirmedWrites "ConfirmWrites" -> return defaultAccessMode badAccess -> fail $ "unknown accessMode: " ++ T.unpack badAccess let rs = case (mRsName, rsSecondaires) of (Nothing, []) -> Nothing (Nothing, _) -> error "found rsSecondaries key. Also expected but did not find a rsName key" (Just rsName, hosts) -> Just $ ReplicaSetConfig rsName $ fmap DB.readHostPort hosts return MongoConf { mgDatabase = db , mgHost = host , mgPort = port , mgAuth = case (mUser, mPass) of (Just user, Just pass) -> Just (MongoAuth user pass) _ -> Nothing , mgPoolStripes = poolStripes , mgStripeConnections = stripeConnections , mgAccessMode = accessMode , mgConnectionIdleTime = connectionIdleTime , mgReplicaSetConfig = rs } where confirmWrites = "ConfirmWrites" instance PersistConfig MongoConf where type PersistConfigBackend MongoConf = DB.Action type PersistConfigPool MongoConf = ConnectionPool createPoolConfig = createMongoPool runPool c = runMongoDBPool (mgAccessMode c) loadConfig = parseJSON -- | docker integration: change the host to the mongodb link applyDockerEnv :: MongoConf -> IO MongoConf applyDockerEnv mconf = do mHost <- lookupEnv "MONGODB_PORT_27017_TCP_ADDR" return $ case mHost of Nothing -> mconf Just h -> mconf { mgHost = T.pack h } -- --------------------------- -- * MongoDB specific Filters -- $filters -- -- You can find example usage for all of Persistent in our test cases: -- <https://github.com/yesodweb/persistent/blob/master/persistent-test/EmbedTest.hs#L144> -- -- These filters create a query that reaches deeper into a document with -- nested fields. type instance BackendSpecificFilter DB.MongoContext record = MongoFilter record type instance BackendSpecificUpdate DB.MongoContext record = MongoUpdate record data NestedField record typ = forall emb. PersistEntity emb => EntityField record [emb] `LastEmbFld` EntityField emb typ | forall emb. PersistEntity emb => EntityField record [emb] `MidEmbFld` NestedField emb typ | forall nest. PersistEntity nest => EntityField record nest `MidNestFlds` NestedField nest typ | forall nest. PersistEntity nest => EntityField record (Maybe nest) `MidNestFldsNullable` NestedField nest typ | forall nest. PersistEntity nest => EntityField record nest `LastNestFld` EntityField nest typ | forall nest. PersistEntity nest => EntityField record (Maybe nest) `LastNestFldNullable` EntityField nest typ -- | A MongoRegex represents a Regular expression. -- It is a tuple of the expression and the options for the regular expression, respectively -- Options are listed here: <http://docs.mongodb.org/manual/reference/operator/query/regex/> -- If you use the same options you may want to define a helper such as @r t = (t, "ims")@ type MongoRegex = (Text, Text) -- | Mark the subset of 'PersistField's that can be searched by a mongoDB regex -- Anything stored as PersistText or an array of PersistText would be valid class PersistField typ => MongoRegexSearchable typ where instance MongoRegexSearchable Text instance MongoRegexSearchable rs => MongoRegexSearchable (Maybe rs) instance MongoRegexSearchable rs => MongoRegexSearchable [rs] -- | Filter using a Regular expression. (=~.) :: forall record searchable. (MongoRegexSearchable searchable, PersistEntity record, PersistEntityBackend record ~ DB.MongoContext) => EntityField record searchable -> MongoRegex -> Filter record fld =~. val = BackendFilter $ RegExpFilter fld val data MongoFilterOperator typ = PersistFilterOperator (Either typ [typ]) PersistFilter | MongoFilterOperator DB.Value data UpdateValueOp typ = UpdateValueOp (Either typ [typ]) (Either PersistUpdate MongoUpdateOperation) deriving Show data MongoUpdateOperation = MongoEach MongoUpdateOperator | MongoSimple MongoUpdateOperator deriving Show data MongoUpdateOperator = MongoPush | MongoPull | MongoAddToSet deriving Show opToText :: MongoUpdateOperator -> Text opToText MongoPush = "$push" opToText MongoPull = "$pull" opToText MongoAddToSet = "$addToSet" data MongoFilter record = forall typ. PersistField typ => NestedFilter (NestedField record typ) (MongoFilterOperator typ) | forall typ. PersistField typ => ArrayFilter (EntityField record [typ]) (MongoFilterOperator typ) | forall typ. PersistField typ => NestedArrayFilter (NestedField record [typ]) (MongoFilterOperator typ) | forall typ. MongoRegexSearchable typ => RegExpFilter (EntityField record typ) MongoRegex data MongoUpdate record = forall typ. PersistField typ => NestedUpdate (NestedField record typ) (UpdateValueOp typ) | forall typ. PersistField typ => ArrayUpdate (EntityField record [typ]) (UpdateValueOp typ) -- | Point to an array field with an embedded object and give a deeper query into the embedded object. -- Use with 'nestEq'. (->.) :: forall record emb typ. PersistEntity emb => EntityField record [emb] -> EntityField emb typ -> NestedField record typ (->.) = LastEmbFld -- | Point to an array field with an embedded object and give a deeper query into the embedded object. -- This level of nesting is not the final level. -- Use '->.' or '&->.' to point to the final level. (~>.) :: forall record typ emb. PersistEntity emb => EntityField record [emb] -> NestedField emb typ -> NestedField record typ (~>.) = MidEmbFld -- | Point to a nested field to query. This field is not an array type. -- Use with 'nestEq'. (&->.) :: forall record typ nest. PersistEntity nest => EntityField record nest -> EntityField nest typ -> NestedField record typ (&->.) = LastNestFld -- | Same as '&->.', but Works against a Maybe type (?&->.) :: forall record typ nest. PersistEntity nest => EntityField record (Maybe nest) -> EntityField nest typ -> NestedField record typ (?&->.) = LastNestFldNullable -- | Point to a nested field to query. This field is not an array type. -- This level of nesting is not the final level. -- Use '->.' or '&>.' to point to the final level. (&~>.) :: forall val nes nes1. PersistEntity nes1 => EntityField val nes1 -> NestedField nes1 nes -> NestedField val nes (&~>.) = MidNestFlds -- | Same as '&~>.', but works against a Maybe type (?&~>.) :: forall val nes nes1. PersistEntity nes1 => EntityField val (Maybe nes1) -> NestedField nes1 nes -> NestedField val nes (?&~>.) = MidNestFldsNullable infixr 4 =~. infixr 5 ~>. infixr 5 &~>. infixr 5 ?&~>. infixr 6 &->. infixr 6 ?&->. infixr 6 ->. infixr 4 `nestEq` infixr 4 `nestNe` infixr 4 `nestGe` infixr 4 `nestLe` infixr 4 `nestIn` infixr 4 `nestNotIn` infixr 4 `anyEq` infixr 4 `nestAnyEq` infixr 4 `nestBsonEq` infixr 4 `multiBsonEq` infixr 4 `anyBsonEq` infixr 4 `nestSet` infixr 4 `push` infixr 4 `pull` infixr 4 `pullAll` infixr 4 `addToSet` -- | The normal Persistent equality test '==.' is not generic enough. -- Instead use this with the drill-down arrow operaters such as '->.' -- -- using this as the only query filter is similar to the following in the mongoDB shell -- -- > db.Collection.find({"object.field": item}) nestEq, nestNe, nestGe, nestLe, nestIn, nestNotIn :: forall record typ. ( PersistField typ , PersistEntityBackend record ~ DB.MongoContext) => NestedField record typ -> typ -> Filter record nestEq = nestedFilterOp Eq nestNe = nestedFilterOp Ne nestGe = nestedFilterOp Ge nestLe = nestedFilterOp Le nestIn = nestedFilterOp In nestNotIn = nestedFilterOp NotIn nestedFilterOp :: forall record typ. ( PersistField typ , PersistEntityBackend record ~ DB.MongoContext ) => PersistFilter -> NestedField record typ -> typ -> Filter record nestedFilterOp op nf v = BackendFilter $ NestedFilter nf $ PersistFilterOperator (Left v) op -- | same as `nestEq`, but give a BSON Value nestBsonEq :: forall record typ. ( PersistField typ , PersistEntityBackend record ~ DB.MongoContext ) => NestedField record typ -> DB.Value -> Filter record nf `nestBsonEq` val = BackendFilter $ NestedFilter nf $ MongoFilterOperator val -- | Like '(==.)' but for an embedded list. -- Checks to see if the list contains an item. -- -- In Haskell we need different equality functions for embedded fields that are lists or non-lists to keep things type-safe. -- -- using this as the only query filter is similar to the following in the mongoDB shell -- -- > db.Collection.find({arrayField: arrayItem}) anyEq :: forall record typ. ( PersistField typ , PersistEntityBackend record ~ DB.MongoContext ) => EntityField record [typ] -> typ -> Filter record fld `anyEq` val = BackendFilter $ ArrayFilter fld $ PersistFilterOperator (Left val) Eq -- | Like nestEq, but for an embedded list. -- Checks to see if the nested list contains an item. nestAnyEq :: forall record typ. ( PersistField typ , PersistEntityBackend record ~ DB.MongoContext ) => NestedField record [typ] -> typ -> Filter record fld `nestAnyEq` val = BackendFilter $ NestedArrayFilter fld $ PersistFilterOperator (Left val) Eq multiBsonEq :: forall record typ. ( PersistField typ , PersistEntityBackend record ~ DB.MongoContext ) => EntityField record [typ] -> DB.Value -> Filter record multiBsonEq = anyBsonEq {-# DEPRECATED multiBsonEq "Please use anyBsonEq instead" #-} -- | same as `anyEq`, but give a BSON Value anyBsonEq :: forall record typ. ( PersistField typ , PersistEntityBackend record ~ DB.MongoContext ) => EntityField record [typ] -> DB.Value -> Filter record fld `anyBsonEq` val = BackendFilter $ ArrayFilter fld $ MongoFilterOperator val nestSet, nestInc, nestDec, nestMul :: forall record typ. ( PersistField typ , PersistEntityBackend record ~ DB.MongoContext) => NestedField record typ -> typ -> Update record nestSet = nestedUpdateOp Assign nestInc = nestedUpdateOp Add nestDec = nestedUpdateOp Subtract nestMul = nestedUpdateOp Multiply push, pull, addToSet :: forall record typ. ( PersistField typ , PersistEntityBackend record ~ DB.MongoContext ) => EntityField record [typ] -> typ -> Update record fld `push` val = backendArrayOperation MongoPush fld val fld `pull` val = backendArrayOperation MongoPull fld val fld `addToSet` val = backendArrayOperation MongoAddToSet fld val backendArrayOperation :: forall record typ. (PersistField typ, BackendSpecificUpdate (PersistEntityBackend record) record ~ MongoUpdate record) => MongoUpdateOperator -> EntityField record [typ] -> typ -> Update record backendArrayOperation op fld val = BackendUpdate $ ArrayUpdate fld $ UpdateValueOp (Left val) (Right $ MongoSimple op) -- | equivalent to $each -- -- > eachOp push field [] -- -- @eachOp pull@ will get translated to @$pullAll@ eachOp :: forall record typ. ( PersistField typ, PersistEntityBackend record ~ DB.MongoContext) => (EntityField record [typ] -> typ -> Update record) -> EntityField record [typ] -> [typ] -> Update record eachOp haskellOp fld val = case haskellOp fld (error "eachOp: undefined") of BackendUpdate (ArrayUpdate _ (UpdateValueOp (Left _) (Right (MongoSimple op)))) -> each op BackendUpdate (ArrayUpdate{}) -> error "eachOp: unexpected ArrayUpdate" BackendUpdate (NestedUpdate{}) -> error "eachOp: did not expect NestedUpdate" Update{} -> error "eachOp: did not expect Update" where each op = BackendUpdate $ ArrayUpdate fld $ UpdateValueOp (Right val) (Right $ MongoEach op) pullAll :: forall record typ. ( PersistField typ , PersistEntityBackend record ~ DB.MongoContext ) => EntityField record [typ] -> [typ] -> Update record fld `pullAll` val = eachOp pull fld val nestedUpdateOp :: forall record typ. ( PersistField typ , PersistEntityBackend record ~ DB.MongoContext ) => PersistUpdate -> NestedField record typ -> typ -> Update record nestedUpdateOp op nf v = BackendUpdate $ NestedUpdate nf $ UpdateValueOp (Left v) (Left op) -- | Intersection of lists: if any value in the field is found in the list. inList :: PersistField typ => EntityField v [typ] -> [typ] -> Filter v f `inList` a = Filter (unsafeCoerce f) (Right a) In infix 4 `inList` -- | No intersection of lists: if no value in the field is found in the list. ninList :: PersistField typ => EntityField v [typ] -> [typ] -> Filter v f `ninList` a = Filter (unsafeCoerce f) (Right a) In infix 4 `ninList`
psibi/persistent
persistent-mongoDB/Database/Persist/MongoDB.hs
mit
61,293
0
21
14,728
15,439
8,055
7,384
-1
-1
-- | -- Module : System.Hapistrano.Commands -- Copyright : Β© 2015-Present Stack Builders -- License : MIT -- -- Maintainer : Cristhian Motoche <[email protected]> -- Stability : experimental -- Portability : portable -- -- Collection of type safe shell commands that can be fed into -- 'System.Hapistrano.Core.runCommand'. {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE CPP #-} module System.Hapistrano.Commands.Internal where import Control.Monad.IO.Class import Data.Char (isSpace) #if MIN_VERSION_base(4,15,0) import Data.Kind (Type) #endif import Data.List (dropWhileEnd) import Data.Maybe (catMaybes, fromJust, mapMaybe) import Data.Proxy import Numeric.Natural import Path import System.Hapistrano.Types (TargetSystem (..)) ---------------------------------------------------------------------------- -- Commands -- | Class for data types that represent shell commands in typed way. class Command a where -- | Type of result. #if MIN_VERSION_base(4,15,0) type Result a :: Type #else type Result a :: * #endif -- | How to render the command before feeding it into shell (possibly via -- SSH). renderCommand :: a -> String -- | How to parse the result from stdout. parseResult :: Proxy a -> String -> Result a -- | Unix @whoami@. data Whoami = Whoami deriving (Show, Eq, Ord) instance Command Whoami where type Result Whoami = String renderCommand Whoami = "whoami" parseResult Proxy = trim -- | Specify directory in which to perform another command. data Cd cmd = Cd (Path Abs Dir) cmd instance Command cmd => Command (Cd cmd) where type Result (Cd cmd) = Result cmd renderCommand (Cd path cmd) = "(cd " ++ quoteCmd (fromAbsDir path) ++ " && " ++ renderCommand cmd ++ ")" parseResult Proxy = parseResult (Proxy :: Proxy cmd) -- | Create a directory. Does not fail if the directory already exists. newtype MkDir = MkDir (Path Abs Dir) instance Command MkDir where type Result MkDir = () renderCommand (MkDir path) = formatCmd "mkdir" [Just "-pv", Just (fromAbsDir path)] parseResult Proxy _ = () -- | Delete file or directory. data Rm where Rm :: Path Abs t -> Rm instance Command Rm where type Result Rm = () renderCommand (Rm path) = formatCmd "rm" [Just "-rf", Just (toFilePath path)] parseResult Proxy _ = () -- | Move or rename files or directories. data Mv t = Mv TargetSystem (Path Abs t) (Path Abs t) instance Command (Mv File) where type Result (Mv File) = () renderCommand (Mv ts old new) = formatCmd "mv" [Just flags, Just (fromAbsFile old), Just (fromAbsFile new)] where flags = if isLinux ts then "-fvT" else "-fv" parseResult Proxy _ = () instance Command (Mv Dir) where type Result (Mv Dir) = () renderCommand (Mv _ old new) = formatCmd "mv" [Just "-fv", Just (fromAbsDir old), Just (fromAbsDir new)] parseResult Proxy _ = () -- | Create symlinks. data Ln where Ln :: TargetSystem -> Path Abs t -> Path Abs File -> Ln instance Command Ln where type Result Ln = () renderCommand (Ln ts target linkName) = formatCmd "ln" [Just flags, Just (toFilePath target), Just (fromAbsFile linkName)] where flags = if isLinux ts then "-svT" else "-sv" parseResult Proxy _ = () -- | Read link. data Readlink t = Readlink TargetSystem (Path Abs File) instance Command (Readlink File) where type Result (Readlink File) = Path Abs File renderCommand (Readlink ts path) = formatCmd "readlink" [flags, Just (toFilePath path)] where flags = if isLinux ts then Just "-f" else Nothing parseResult Proxy = fromJust . parseAbsFile . trim instance Command (Readlink Dir) where type Result (Readlink Dir) = Path Abs Dir renderCommand (Readlink ts path) = formatCmd "readlink" [flags, Just (toFilePath path)] where flags = if isLinux ts then Just "-f" else Nothing parseResult Proxy = fromJust . parseAbsDir . trim -- | @ls@, so far used only to check existence of directories, so it's not -- very functional right now. newtype Ls = Ls (Path Abs Dir) instance Command Ls where type Result Ls = () renderCommand (Ls path) = formatCmd "ls" [Just (fromAbsDir path)] parseResult Proxy _ = () -- | Find (a very limited version). data Find t = Find Natural (Path Abs Dir) instance Command (Find Dir) where type Result (Find Dir) = [Path Abs Dir] renderCommand (Find maxDepth dir) = formatCmd "find" [ Just (fromAbsDir dir) , Just "-maxdepth" , Just (show maxDepth) , Just "-type" , Just "d" ] parseResult Proxy = mapMaybe (parseAbsDir . trim) . lines instance Command (Find File) where type Result (Find File) = [Path Abs File] renderCommand (Find maxDepth dir) = formatCmd "find" [ Just (fromAbsDir dir) , Just "-maxdepth" , Just (show maxDepth) , Just "-type" , Just "f" ] parseResult Proxy = mapMaybe (parseAbsFile . trim) . lines -- | @touch@. newtype Touch = Touch (Path Abs File) instance Command Touch where type Result Touch = () renderCommand (Touch path) = formatCmd "touch" [Just (fromAbsFile path)] parseResult Proxy _ = () -- | Command that checks for the existance of a particular -- file in the host. newtype CheckExists = CheckExists (Path Abs File) -- ^ The absolute path to the file you want to check for existence instance Command CheckExists where type Result CheckExists = Bool renderCommand (CheckExists path) = "([ -r " <> fromAbsFile path <> " ] && echo True) || echo False" parseResult Proxy = read -- | Command used to read the contents of a particular -- file in the host. newtype Cat = Cat (Path Abs File) -- ^ The absolute path to the file you want to read instance Command Cat where type Result Cat = String renderCommand (Cat path) = formatCmd "cat" [Just (fromAbsFile path)] parseResult Proxy = id -- | Basic command that writes to a file some contents. -- It uses the @file > contents@ shell syntax and the @contents@ is -- represented as a 'String', so it shouldn't be used for -- bigger writing operations. Currently used to write @fail@ or @success@ -- to the @.hapistrano_deploy_state@ file. data BasicWrite = BasicWrite (Path Abs File) -- ^ The absolute path to the file to which you want to write String -- ^ The contents that will be written to the file instance Command BasicWrite where type Result BasicWrite = () renderCommand (BasicWrite path contents) = "echo \"" <> contents <> "\"" <> " > " <> fromAbsFile path parseResult Proxy _ = () -- | Git checkout. newtype GitCheckout = GitCheckout String instance Command GitCheckout where type Result GitCheckout = () renderCommand (GitCheckout revision) = formatCmd "git" [Just "checkout", Just revision] parseResult Proxy _ = () -- | Git clone. data GitClone = GitClone Bool (Either String (Path Abs Dir)) (Path Abs Dir) instance Command GitClone where type Result GitClone = () renderCommand (GitClone bare src dest) = formatCmd "git" [ Just "clone" , if bare then Just "--bare" else Nothing , Just (case src of Left repoUrl -> repoUrl Right srcPath -> fromAbsDir srcPath) , Just (fromAbsDir dest) ] parseResult Proxy _ = () -- | Git fetch (simplified). newtype GitFetch = GitFetch String instance Command GitFetch where type Result GitFetch = () renderCommand (GitFetch remote) = formatCmd "git" [Just "fetch", Just remote, Just "+refs/heads/\\*:refs/heads/\\*"] parseResult Proxy _ = () -- | Git reset. newtype GitReset = GitReset String instance Command GitReset where type Result GitReset = () renderCommand (GitReset revision) = formatCmd "git" [Just "reset", Just revision] parseResult Proxy _ = () -- | Weakly-typed generic command, avoid using it directly. newtype GenericCommand = GenericCommand String deriving (Show, Eq, Ord) instance Command GenericCommand where type Result GenericCommand = () renderCommand (GenericCommand cmd) = cmd parseResult Proxy _ = () -- | Smart constructor that allows to create 'GenericCommand's. Just a -- little bit more safety. mkGenericCommand :: String -> Maybe GenericCommand mkGenericCommand str = if '\n' `elem` str' || null str' then Nothing else Just (GenericCommand str') where str' = trim (takeWhile (/= '#') str) -- | Get the raw command back from 'GenericCommand'. unGenericCommand :: GenericCommand -> String unGenericCommand (GenericCommand x) = x -- | Read commands from a file. readScript :: MonadIO m => Path Abs File -> m [GenericCommand] readScript path = liftIO $ mapMaybe mkGenericCommand . lines <$> readFile (fromAbsFile path) ---------------------------------------------------------------------------- -- Helpers -- | Format a command. formatCmd :: String -> [Maybe String] -> String formatCmd cmd args = unwords (quoteCmd <$> (cmd : catMaybes args)) -- | Simple-minded quoter. quoteCmd :: String -> String quoteCmd str = if any isSpace str then "\"" ++ str ++ "\"" else str -- | Trim whitespace from beginning and end. trim :: String -> String trim = dropWhileEnd isSpace . dropWhile isSpace -- | Determines whether or not the target system is a Linux machine. isLinux :: TargetSystem -> Bool isLinux = (== GNULinux)
stackbuilders/hapistrano
src/System/Hapistrano/Commands/Internal.hs
mit
9,754
0
13
2,330
2,522
1,332
1,190
223
2
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Repl ( Repl , get , put , runRepl , liftIO ) where import Control.Applicative (Applicative) import Control.Monad.State (StateT, MonadIO, liftIO, runStateT) import Control.Monad.State.Class (MonadState, get, put) newtype Repl s a = Repl { extractRepl :: StateT s IO a } deriving (Functor, Applicative, Monad, MonadIO, MonadState s) runRepl :: Repl s a -> s -> IO (a, s) runRepl repl = runStateT (extractRepl repl)
kosmoskatten/traffic-analysis
src/Repl.hs
mit
506
0
8
112
161
95
66
15
1
module Util ( sealRandom ) where import Control.Auto import Control.Auto.Effects import Control.Monad.Random import Control.Monad.Trans.State import Data.Serialize import Prelude hiding ((.), id) sealRandom :: (Monad m, RandomGen g, Serialize g) => Auto (RandT g m) a b -> g -> Auto m a b sealRandom = sealState . hoistA (StateT . runRandT)
mstksg/jlebot2
src/Util.hs
mit
393
0
9
103
127
73
54
13
1
{-# LANGUAGE OverloadedStrings #-} module Database.Toxic.Query.Parser where import Database.Toxic.Types as Toxic import Database.Toxic.Query.AST import Control.Applicative ((<$>), (*>), (<*), (<*>)) import Control.Monad import Data.List (nub) import Data.Monoid import qualified Data.Text as T import qualified Data.Vector as V import Text.Parsec import Text.Parsec.Combinator import Text.Parsec.Expr import Text.Parsec.Language import qualified Text.Parsec.Token as P type CharParser a = Parsec String () a reservedOperators = ["<>", "*","+",">",">=","=","<=","<"] reservedOperatorCharacters = nub $ concat reservedOperators sqlLanguageDef = P.LanguageDef { P.commentStart = "", P.commentEnd = "", P.commentLine = "--", P.nestedComments = False, P.identStart = letter <|> char '_', P.identLetter = alphaNum <|> char '_', P.opStart = oneOf $ reservedOperatorCharacters, P.opLetter = oneOf $ reservedOperatorCharacters, P.reservedNames = [], P.reservedOpNames = reservedOperators, P.caseSensitive = False } lexer = P.makeTokenParser sqlLanguageDef integer :: CharParser Literal integer = LInt <$> P.integer lexer identifier :: CharParser T.Text identifier = T.pack <$> P.identifier lexer keyword :: String -> CharParser () keyword text = P.reserved lexer text operator :: String -> CharParser () operator text = P.reservedOp lexer text commaSep = P.commaSep lexer commaSep1 = P.commaSep1 lexer operator_table = let mkUnop name unop = prefix name (EUnop unop) mkBinop name binop = binary name (EBinop binop) AssocLeft in [ [ mkUnop "not" UnopNot ], [ mkBinop "*" BinopTimes, mkBinop "/" BinopDividedBy ], [ mkBinop "+" BinopPlus, mkBinop "-" BinopMinus ], [ mkBinop ">=" BinopGreaterOrEqual, mkBinop ">" BinopGreater, mkBinop "<" BinopLess, mkBinop "<=" BinopLessOrEqual, mkBinop "=" BinopEqual, mkBinop "<>" BinopUnequal ] ] binary name fun assoc = Infix (operator name *> return fun) assoc prefix name fun = Prefix (operator name *> return fun) postfix name fun = Postfix (operator name *> return fun) parens = P.parens lexer union_all :: CharParser () union_all = keyword "union" *> keyword "all" literal :: CharParser Literal literal = let true = keyword "true" *> return (LBool True) false = keyword "false" *> return (LBool False) null = keyword "null" *> return LNull in true <|> false <|> null <|> integer case_condition :: CharParser (Condition, Expression) case_condition = do keyword "when" condition <- expression keyword "then" result <- expression return (condition, result) case_else :: CharParser Expression case_else = keyword "else" *> expression case_when_expression :: CharParser Expression case_when_expression = do keyword "case" conditions <- many $ case_condition else_case <- optionMaybe case_else keyword "end" return $ ECase (V.fromList conditions) else_case not_expression :: CharParser Expression not_expression = do keyword "not" x <- expression return $ EUnop UnopNot x variable :: CharParser Expression variable = EVariable <$> identifier term :: CharParser Expression term = try(ELiteral <$> literal) <|> case_when_expression <|> try function <|> variable <|> parens expression <?> "term" expression :: CharParser Expression expression = buildExpressionParser operator_table term rename_clause :: CharParser T.Text rename_clause = keyword "as" *> identifier select_item :: CharParser Expression select_item = do x <- expression rename <- optionMaybe rename_clause return $ case rename of Just name -> ERename x name Nothing -> x select_clause :: CharParser (ArrayOf Expression) select_clause = do keyword "select" V.fromList <$> commaSep1 select_item group_by_clause :: CharParser (ArrayOf Expression) group_by_clause = do keyword "group" keyword "by" expressions <- V.fromList <$> commaSep1 expression return expressions order_by_clause :: CharParser (ArrayOf (Expression, StreamOrder)) order_by_clause = let order_by_expression :: CharParser (Expression, StreamOrder) order_by_expression = let streamOrder :: CharParser StreamOrder streamOrder = ((keyword "asc" <|> keyword "ascending") *> return Ascending) <|> ((keyword "desc" <|> keyword "descending") *> return Descending) <|> return Ascending in do expression <- expression order <- streamOrder return (expression, order) in do try $ do keyword "order" keyword "by" expressions <- V.fromList <$> commaSep1 order_by_expression return expressions subquery :: CharParser Query subquery = parens query function :: CharParser Expression function = do name <- identifier argument <- parens expression case name of "bool_or" -> return $ EAggregate QAggBoolOr argument "sum" -> return $ EAggregate QAggSum argument _ -> fail $ T.unpack $ "Unknown function " <> name from_clause :: CharParser (Maybe Query) from_clause = let real_from_clause = do try $ keyword "from" product_query in (Just <$> real_from_clause) <|> return Nothing where_clause :: CharParser (Maybe Expression) where_clause = let real_where_clause = do try $ keyword "where" expression in (Just <$> real_where_clause) <|> return Nothing single_query :: CharParser Query single_query = do expressions <- select_clause source <- from_clause whereClause <- where_clause groupBy <- optionMaybe group_by_clause orderBy <- optionMaybe order_by_clause return $ SingleQuery { queryGroupBy = groupBy, queryProject = expressions, querySource = source, queryOrderBy = orderBy, queryWhere = whereClause } composite_query :: CharParser Query composite_query = let one_or_more = V.fromList <$> sepBy1 single_query union_all in do composite <- one_or_more return $ if V.length composite == 1 then V.head composite else SumQuery QuerySumUnionAll composite product_query :: CharParser Query product_query = let one_or_more = V.fromList <$> commaSep1 subquery in do subqueries <- one_or_more return $ if V.length subqueries == 1 then V.head subqueries else ProductQuery { queryFactors = subqueries } query :: CharParser Query query = composite_query <?> "Expected a query or union of queries" select_statement :: CharParser Statement select_statement = do q <- query char ';' return $ SQuery q column_type :: CharParser Type column_type = (keyword "int" *> return TInt) <|> (keyword "bool" *> return TBool) table_spec_column :: CharParser Toxic.Column table_spec_column = do name <- identifier cType <- column_type return Toxic.Column { columnName = name, columnType = cType } table_spec :: CharParser TableSpec table_spec = parens $ TableSpec <$> V.fromList <$> commaSep table_spec_column create_table_statement :: CharParser Statement create_table_statement = do keyword "create" keyword "table" name <- identifier spec <- table_spec char ';' return $ SCreateTable name spec statement :: CharParser Statement statement = select_statement <|> create_table_statement runQueryParser :: T.Text -> Either ParseError Statement runQueryParser text = parse statement "runTokenParser" $ T.unpack text unsafeRunQueryParser :: T.Text -> Statement unsafeRunQueryParser text = case runQueryParser text of Left parseError -> error $ show parseError Right statement -> statement
MichaelBurge/ToxicSludgeDB
src/Database/Toxic/Query/Parser.hs
mit
7,669
0
19
1,616
2,227
1,113
1,114
228
3
module BinaryTree where import Prelude data Tree a = Empty | Node (a) (Tree a) (Tree a) deriving (Show) add :: Ord a => Tree a -> a -> Tree a add tree n = case tree of Empty -> Node n Empty Empty Node node l r | node > n -> Node node (add l n) r | node < n -> Node node l (add r n) | otherwise -> Node node r l create :: Ord a => [a] -> Tree a create l = cr Empty l where cr tree [] = tree cr tree (x:xs) = cr (add tree x) xs traverce :: Show a => Tree a -> [Char] traverce tree = case tree of Empty -> []--"nil " Node n l r -> Prelude.show n ++ " " ++ (traverce l) ++ (traverce r) ++ " " getWay :: (Ord a, Show a) => Tree a -> a -> [a] getWay tree n = case tree of Empty -> error "elem is not exist" Node node l r | node > n -> node : getWay l n | node < n -> node : getWay r n | otherwise -> [n] show :: Show a => Tree a -> [Char] show t = traverce t min :: Eq a => Tree a -> a min Empty = error "min: Tree is undefined." min (Node n Empty _) = n min (Node _ l r) = BinaryTree.min l max :: Eq a => Tree a -> a max Empty = error "max: Tree is undefined." max (Node n Empty _) = n max (Node _ l r) = BinaryTree.max r
NickolayStorm/usatu-learning
Functional programming/lab6/BinaryTree.hs
mit
1,263
112
24
424
687
352
335
33
2
{-# OPTIONS_GHC -fno-warn-unused-do-bind #-} module SFOT.Asm.Parser where import SFOT.Asm.AST import Text.ParserCombinators.Parsec hiding (Parser, token, label, labels) import Prelude hiding (and) import Data.Word import Data.Char (toLower) import Data.List (find) import Control.Monad import Data.Maybe type Parser = GenParser Char [String] decimal :: Parser Int decimal = do cs <- many1 digit return $ read cs hex :: Parser Int hex = do char '$' cs <- many1 hexDigit return $ read $ "0x" ++ cs number :: Parser Int number = hex <|> decimal byteAddr :: Parser ByteAddr byteAddr = do num <- number if num <= 0xff then return $ fromIntegral num else fail "Number too big" wordAddr :: Parser WordAddr wordAddr = do num <- number if num <= 0xffff then return $ fromIntegral num else fail "Only supports 16 bit addresses" comment :: Parser () comment = do char ';' manyTill anyChar (void newline <|> eof) return () whitespace :: Parser () whitespace = skipMany (skipMany1 space <|> comment) token :: String -> Parser () token s = try $ (string s <|> string (map toLower s)) >> notFollowedBy (alphaNum <|> char '_') >> skipMany space startPar :: Parser () startPar = char '(' >> spaces endPar :: Parser () endPar = char ')' >> spaces parens :: Parser a -> Parser a parens = between startPar endPar commaRegister :: Char -> Parser () commaRegister c = do spaces char ',' spaces char c <|> char (toLower c) notFollowedBy (alphaNum <|> char '_') return () immediate :: (ByteAddr -> a) -> Parser a immediate f = do char '#' num <- number if num <= 0xff then return $ f $ fromIntegral num else fail "Number too big" zeroPage :: (ByteAddr -> a) -> Parser a zeroPage f = try $ do num <- byteAddr notFollowedBy (spaces >> char ',') return $ f num zeroPageX :: (ByteAddr -> a) -> Parser a zeroPageX f = try $ do num <- byteAddr commaRegister 'X' return $ f num zeroPageY :: (ByteAddr -> a) -> Parser a zeroPageY f = try $ do num <- byteAddr commaRegister 'Y' return $ f num absolute :: (WordAddr -> a) -> Parser a absolute f = try $ do num <- wordAddr notFollowedBy (spaces >> char ',') return $ f num absoluteX :: (WordAddr -> a) -> Parser a absoluteX f = try $ do num <- wordAddr commaRegister 'X' return $ f num absoluteY :: (WordAddr -> a) -> Parser a absoluteY f = try $ do num <- wordAddr commaRegister 'Y' return $ f num indirect :: (WordAddr -> a) -> Parser a indirect f = try $ parens $ do num <- wordAddr return $ f num indirectX :: (ByteAddr -> a) -> Parser a indirectX f = try $ parens $ do num <- byteAddr commaRegister 'X' return $ f num indirectY :: (ByteAddr -> a) -> Parser a indirectY f = try $ do num <- parens byteAddr commaRegister 'Y' return $ f num adc :: Parser Operation adc = do token "ADC" choice adcParsers where adcParsers = map (liftM ADC) adcParsers' adcParsers' = [immediate AdcI, zeroPage AdcZ, zeroPageX AdcZX, absolute AdcA, absoluteX AdcAX, absoluteY AdcAY, indirectX AdcIX, indirectY AdcIY] and :: Parser Operation and = do token "AND" choice andParsers where andParsers = map (liftM AND) andParsers' andParsers' = [immediate AndI, zeroPage AndZ, zeroPageX AndZX, absolute AndA, absoluteX AndAX, absoluteY AndAY, indirectX AndIX, indirectY AndIY] asl :: Parser Operation asl = do token "ASL" choice aslParsers where aslParsers = map (liftM ASL) aslParsers' aslParsers' = [zeroPage AslZ, zeroPageX AslZX, absolute AslA, absoluteX AslAX, return AslAc] bcc :: Parser Operation bcc = do token "BCC" s <- name return $ BCC (ShortLabel s) bcs :: Parser Operation bcs = do token "BCS" s <- name return $ BCS (ShortLabel s) beq :: Parser Operation beq = do token "BEQ" s <- name return $ BEQ (ShortLabel s) bit :: Parser Operation bit = do token "BIT" choice bitParsers where bitParsers = map (liftM BIT) bitParsers' bitParsers' = [zeroPage BitZ, absolute BitA] bmi :: Parser Operation bmi = do token "BMI" s <- name return $ BMI (ShortLabel s) bne :: Parser Operation bne = do token "BNE" s <- name return $ BNE (ShortLabel s) bpl :: Parser Operation bpl = do token "BPL" s <- name return $ BPL (ShortLabel s) brk :: Parser Operation brk = do token "BRK" return BRK bvc :: Parser Operation bvc = do token "BVC" s <- name return $ BVC (ShortLabel s) bvs :: Parser Operation bvs = do token "BVS" s <- name return $ BVS (ShortLabel s) clc :: Parser Operation clc = do token "CLC" return CLC cld :: Parser Operation cld = do token "CLD" return CLD cli :: Parser Operation cli = do token "CLI" return CLI clv :: Parser Operation clv = do token "CLV" return CLV cmp :: Parser Operation cmp = do token "CMP" choice cmpParsers where cmpParsers = map (liftM CMP) cmpParsers' cmpParsers' = [immediate CmpI, zeroPage CmpZ, zeroPageX CmpZX, absolute CmpA, absoluteX CmpAX, absoluteY CmpAY, indirectX CmpIX, indirectY CmpIY] cpx :: Parser Operation cpx = do token "CPX" choice cpxParsers where cpxParsers = map (liftM CPX) cpxParsers' cpxParsers' = [immediate CpxI, zeroPage CpxZ, absolute CpxA] cpy :: Parser Operation cpy = do token "CPY" choice cpyParsers where cpyParsers = map (liftM CPY) cpyParsers' cpyParsers' = [immediate CpyI, zeroPage CpyZ, absolute CpyA] dec :: Parser Operation dec = do token "DEC" choice decParsers where decParsers = map (liftM DEC) decParsers' decParsers' = [zeroPage DecZ, zeroPageX DecZX, absolute DecA, absoluteX DecAX] dex :: Parser Operation dex = do token "DEX" return DEX dey :: Parser Operation dey = do token "DEY" return DEY eor :: Parser Operation eor = do token "EOR" choice eorParsers where eorParsers = map (liftM EOR) eorParsers' eorParsers' = [immediate EorI, zeroPage EorZ, zeroPageX EorZX, absolute EorA, absoluteX EorAX, absoluteY EorAY, indirectX EorIX, indirectY EorIY] inc :: Parser Operation inc = do token "INC" choice incParsers where incParsers = map (liftM INC) incParsers' incParsers' = [zeroPage IncZ, zeroPageX IncZX, absolute IncA, absoluteX IncAX] inx :: Parser Operation inx = do token "INX" return INX iny :: Parser Operation iny = do token "INY" return INY jmp :: Parser Operation jmp = do token "JMP" choice [jmpInd, jmpAbs] where jmpAbs = do s <- name return $ JMP (JmpA (LongLabel s)) jmpInd = parens $ do s <- name return $ JMP (JmpI (LongLabel s)) jsr :: Parser Operation jsr = do token "JSR" s <- name return $ JSR $ LongLabel s lda :: Parser Operation lda = do token "LDA" choice ldaParsers where ldaParsers = map (liftM LDA) ldaParsers' ldaParsers' = [immediate LdaI, zeroPage LdaZ, zeroPageX LdaZX, absolute LdaA, absoluteX LdaAX, absoluteY LdaAY, indirectX LdaIX, indirectY LdaIY] ldx :: Parser Operation ldx = do token "LDX" choice ldxParsers where ldxParsers = map (liftM LDX) ldxParsers' ldxParsers' = [immediate LdxI, zeroPage LdxZ, zeroPageY LdxZY, absolute LdxA, absoluteY LdxAY] ldy :: Parser Operation ldy = do token "LDY" choice ldyParsers where ldyParsers = map (liftM LDY) ldyParsers' ldyParsers' = [immediate LdyI, zeroPage LdyZ, zeroPageX LdyZX, absolute LdyA, absoluteX LdyAX] lsr :: Parser Operation lsr = do token "LSR" choice lsrParsers where lsrParsers = map (liftM LSR) lsrParsers' lsrParsers' = [zeroPage LsrZ, zeroPageX LsrZX, absolute LsrA, absoluteX LsrAX, return LsrAc] ora :: Parser Operation ora = do token "ORA" choice oraParsers where oraParsers = map (liftM ORA) oraParsers' oraParsers' = [immediate OraI, zeroPage OraZ, zeroPageX OraZX, absolute OraA, absoluteX OraAX, absoluteY OraAY, indirectX OraIX, indirectY OraIY] nop :: Parser Operation nop = do token "NOP" return NOP pha :: Parser Operation pha = do token "PHA" return PHA php :: Parser Operation php = do token "PHP" return PHP pla :: Parser Operation pla = do token "PLA" return PLA plp :: Parser Operation plp = do token "PLP" return PLP rol :: Parser Operation rol = do token "ROL" choice rolParsers where rolParsers = map (liftM ROL) rolParsers' rolParsers' = [zeroPage RolZ, zeroPageX RolZX, absolute RolA, absoluteX RolAX, return RolAc] ror :: Parser Operation ror = do token "ROR" choice rorParsers where rorParsers = map (liftM ROR) rorParsers' rorParsers' = [zeroPage RorZ, zeroPageX RorZX, absolute RorA, absoluteX RorAX, return RorAc] rti :: Parser Operation rti = do token "RTI" return RTI rts :: Parser Operation rts = do token "RTS" return RTS sbc :: Parser Operation sbc = do token "SBC" choice sbcParsers where sbcParsers = map (liftM SBC) sbcParsers' sbcParsers' = [immediate SbcI, zeroPage SbcZ, zeroPageX SbcZX, absolute SbcA, absoluteX SbcAX, absoluteY SbcAY, indirectX SbcIX, indirectY SbcIY] sec :: Parser Operation sec = do token "SEC" return SEC sed :: Parser Operation sed = do token "SED" return SED sei :: Parser Operation sei = do token "SEI" return SEI sta :: Parser Operation sta = do token "STA" choice staParsers where staParsers = map (liftM STA) staParsers' staParsers' = [zeroPage StaZ, zeroPageX StaZX, absolute StaA, absoluteX StaAX, absoluteY StaAY, indirectX StaIX, indirectY StaIY] stx :: Parser Operation stx = do token "STX" choice stxParsers where stxParsers = map (liftM STX) stxParsers' stxParsers' = [zeroPage StxZ, zeroPageY StxZY, absolute StxA] sty :: Parser Operation sty = do token "STY" choice styParsers where styParsers = map (liftM STY) styParsers' styParsers' = [zeroPage StyZ, zeroPageX StyZX, absolute StyA] tax :: Parser Operation tax = do token "TAX" return TAX tay :: Parser Operation tay = do token "TAY" return TAY tsx :: Parser Operation tsx = do token "TSX" return TSX txa :: Parser Operation txa = do token "TXA" return TXA txs :: Parser Operation txs = do token "TXS" return TXS tya :: Parser Operation tya = do token "TYA" return TYA name :: Parser String name = do c <- letter <|> char '_' cs <- many $ alphaNum <|> char '_' return $ c : cs label :: Parser Operation label = try $ do s <- name char ':' return $ Label s lexeme :: Parser a -> Parser a lexeme p = do{ x <- p; spaces; return x } program :: Parser Program program = do many (void space <|> comment) prgm <- choice instructionParsers `endBy` many (void space <|> comment) eof return prgm where instructionParsers = [adc, and, asl, bcc, bcs, beq, bit, bmi, bne, bpl, brk, bvc, bvs, clc, cld, cli, clv, cmp, cpx, cpy, dec, dey, eor, inc, inx, iny, jmp, jsr, label, lda, ldx, ldy, lsr, nop, ora, pha, php, pla, plp, rol, ror, rti, rts, sbc, sec, sed, sei, sta, stx, sty, tax, tsx, txa, txs, dex, tay, tya] resolveLabels :: Int -> [Operation] -> [Operation] resolveLabels programOffset p = zipWith translateLabels p byteOffsets where byteOffsets = scanl (\n op -> n + opsize op) 0 p labelTable = foldl findLabels [] $ zip p byteOffsets -- findLabels labels (ins, i) = case ins of Label s -> case find ((== s) . fst) labels of Nothing -> (s, i) : labels _ -> error $ "Label already exists: " ++ show s _ -> labels -- shortTrans offset s = if (fromIntegral relAddr :: Word8) < (0xff :: Word8) then fromIntegral relAddr else error $ "Branch jump is too big: " ++ show (fromIntegral relAddr :: Word8) where relAddr = labOffset - (offset + 2) labOffset = fromMaybe (error $ "Label not found: " ++ show s) $ lookup s labelTable -- longTrans s = fromIntegral $ fromMaybe (error $ "Label not found: " ++ show s) (lookup s labelTable) + programOffset -- translateLabels (BCC (ShortLabel s)) offset = BCC $ RelAddr $ shortTrans offset s translateLabels (BCS (ShortLabel s)) offset = BCS $ RelAddr $ shortTrans offset s translateLabels (BEQ (ShortLabel s)) offset = BEQ $ RelAddr $ shortTrans offset s translateLabels (BMI (ShortLabel s)) offset = BMI $ RelAddr $ shortTrans offset s translateLabels (BNE (ShortLabel s)) offset = BNE $ RelAddr $ shortTrans offset s translateLabels (BPL (ShortLabel s)) offset = BPL $ RelAddr $ shortTrans offset s translateLabels (BVC (ShortLabel s)) offset = BVC $ RelAddr $ shortTrans offset s translateLabels (BVS (ShortLabel s)) offset = BVS $ RelAddr $ shortTrans offset s translateLabels (JMP (JmpA (LongLabel s))) _ = JMP $ JmpA $ AbsAddr $ longTrans s translateLabels (JMP (JmpI (LongLabel s))) _ = JMP $ JmpI $ AbsAddr $ longTrans s translateLabels (JSR (LongLabel s)) _ = JSR $ AbsAddr $ longTrans s translateLabels inst _ = inst
Munksgaard/SFOT
Asm/Parser.hs
mit
13,754
0
15
3,859
5,078
2,463
2,615
471
15
{-# LANGUAGE NoMonomorphismRestriction #-} module Plugins.Gallery.Gallery.Manual35 where import Diagrams.Prelude spike :: Trail R2 spike = fromOffsets . map r2 $ [(1,3), (1,-3)] burst = mconcat . take 13 . iterate (rotateBy (-1/13)) $ spike example = strokeT burst # fc yellow # lw 0.1 # lc orange
andrey013/pluginstest
Plugins/Gallery/Gallery/Manual35.hs
mit
312
0
12
61
125
67
58
7
1
{-# LANGUAGE ViewPatterns #-} import qualified Data.Sequence as S import Data.Sequence ((<|), (><), Seq) import Data.Sequence (ViewL((:<), EmptyL), viewl) import Data.Foldable (foldl', toList) import Utils (zipMap) import Data.List.Ordered (nub, sort) newtype SeqWithIndex = SWI { getSWI :: (Seq Int, Int, Int, Int) } deriving (Eq, Ord, Show) increment :: Integral a => SeqWithIndex -> [SeqWithIndex] increment (SWI (v,i,s,_)) = inc (S.drop i v) i (if i==0 then 0 else S.index v (i-1)) where inc (viewl -> EmptyL) _ _ = [] inc (viewl -> x :< xs) n prev = if x == prev then inc xs (n+1) x else let (left, right) = S.splitAt n v newSeq = left >< (S.adjust succ 0 right) newProd = prodSeq newSeq in if newProd <= newSum then (SWI (newSeq, n, newSum, newProd)) : (inc xs (n+1) x) else inc xs (n+1) x newSum = succ s --increment :: Integral a => Seq a -> [Seq a] --increment v = inc (mask v) 0 -- where inc (viewl -> b :< bs) n = -- if b -- then let (left, right) = S.splitAt n v -- newSeq = left >< (S.adjust succ 0 right) -- in newSeq : (inc bs (n+1)) -- else inc bs (n+1) -- inc (viewl -> EmptyL) _ = [] --mask :: Eq a => Seq a -> [Bool] --mask l = True : (toList $ S.zipWith (/=) l $ S.drop 1 l) --mask :: Eq a => Seq a -> Seq Bool --mask l = True <| (S.zipWith (/=) l $ S.drop 1 l) -- generates sets of integers with increasing sum sets :: Int -> [SeqWithIndex] sets k = concat $ iterate (concatMap increment) [SWI (S.replicate k 1, 0, k, 1)] --sumSeq :: Num a => Seq a -> a --sumSeq s = foldl' (+) 0 s sumSeq :: Seq Int -> Int sumSeq s = (foldl' (+) 0 left) + (S.length right) where (left, right) = S.spanl (/=1) s --prodSeq :: Num a => Seq a -> a --prodSeq s = foldl' (*) 1 s prodSeq :: (Eq a, Num a) => Seq a -> a prodSeq s = foldl' (*) 1 $ S.takeWhileL (/=1) s solution :: Int -> SeqWithIndex solution k = head $ dropWhile (\(SWI (seq, _, s, p)) -> p /= s) ss where ss = sets k answersUpTo :: Int -> [(Int, Int)] answersUpTo k = map (\(i, SWI (_,_,_,p)) -> (i,p)) $ zipMap solution [2..k] main = do let ans = answersUpTo 1200 mapM_ print ans let tot = sum $ nub $ sort $ map snd ans print tot
arekfu/project_euler
p0088/p0088.hs
mit
2,498
0
15
832
824
461
363
38
5
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} module Game.Halma.TelegramBot.View.I18n ( HalmaLocale (..) , NotYourTurnInfo (..) , CantUndoReason (..) , AIMove (..) , enHalmaLocale , deHalmaLocale , LocaleId (..) , allLocaleIds , localeById ) where import Game.Halma.Board (HalmaDirection) import Game.Halma.Configuration import Game.Halma.TelegramBot.Controller.SlashCmd import Game.Halma.TelegramBot.Model.MoveCmd import Game.Halma.TelegramBot.Model.Types import Game.Halma.TelegramBot.View.Pretty import Data.Char (toUpper) import Data.Foldable (toList) import Data.Monoid ((<>)) import qualified Data.Text as T import qualified Web.Telegram.API.Bot as TG data NotYourTurnInfo = NotYourTurnInfo { you :: TG.User , thePlayerWhoseTurnItIs :: Player } data CantUndoReason = CantUndoNoGame data AIMove = AIMove { aiHomeCorner :: HalmaDirection , aiMoveCmd :: MoveCmd } data HalmaLocale = HalmaLocale { hlNewMatchCmd :: T.Text , hlNewRoundCmd :: T.Text , hlUndoCmd :: T.Text , hlHelpCmd :: T.Text , hlWelcomeMsg :: T.Text , hlHelpMsg :: T.Text , hlCongratulation :: ExtendedPartyResult -> T.Text , hlCantStartNewRoundBecauseNoMatch :: T.Text , hlStartingANewRound :: T.Text , hlYourTurn :: HalmaDirection -> TG.User -> T.Text , hlNotYourTurn :: NotYourTurnInfo -> T.Text , hlCantUndo :: Maybe CantUndoReason -> T.Text , hlAIMove :: AIMove -> T.Text , hlNoMatchMsg :: T.Text , hlNoRoundMsg :: T.Text , hlAmbiguousMoveCmdMsg :: TG.User -> MoveCmd -> T.Text , hlImpossibleMoveCmdMsg :: TG.User -> MoveCmd -> T.Text , hlUnrecognizedCmdMsg :: CmdCall -> T.Text , hlGatheringPlayersMsg :: PlayersSoFar Player -> T.Text , hlMe :: T.Text , hlAnAI :: T.Text , hlYesMe :: T.Text , hlYesAnAI :: T.Text , hlNo :: T.Text } -- | English enHalmaLocale :: HalmaLocale enHalmaLocale = HalmaLocale { hlNewMatchCmd = newMatchCmd , hlNewRoundCmd = newRoundCmd , hlUndoCmd = undoCmd , hlHelpCmd = helpCmd , hlWelcomeMsg = "Greetings from HalmaBot! I am an [open-source](https://github.com/timjb/halma) Telegram bot " <> "written in Haskell by Tim Baumann <[email protected]>." , hlHelpMsg = "You can control me by sending these commands:\n" <> "/" <> newMatchCmd <> " β€” starts a new match between two or three players\n" <> "/" <> newRoundCmd <> " β€” start a new game round\n" <> "/" <> undoCmd <> " β€” reverse your last move\n" <> "/deutsch β€” " <> localeFlag De <> " auf Deutsch umschalten / switch to German\n" <> "/" <> helpCmd <> " β€” display this message\n\n" <> "Here's how move commands are structured:\n" <> "First there comes a letter in the range A-O (the piece you want to " <> " move), then the number of the row you want to move the piece to. " <> "If there are multiple possible target positions on the row, I will " <> "ask you which one you mean.\n" <> "For example: the command 'A11' makes me move your piece labeled 'A' " <> "to row number 11." , hlCongratulation = congrat , hlCantStartNewRoundBecauseNoMatch = "Can't start a new round, because there is no match running. You have to start a /newmatch first." , hlStartingANewRound = "starting a new round!" , hlYourTurn = \homeCorner user -> prettyUser user <> " " <> teamEmoji homeCorner <> " it's your turn!" , hlNotYourTurn = \notYourTurn -> "Hey " <> prettyUser (you notYourTurn) <> ", it's not your turn, it's " <> prettyPlayer (thePlayerWhoseTurnItIs notYourTurn) <> "'s!" , hlCantUndo = \case Nothing -> "can't undo!" Just CantUndoNoGame -> "can't undo: no game running!" , hlAIMove = \aiMove -> "The AI " <> teamEmoji (aiHomeCorner aiMove) <> " makes the following move: " <> showMoveCmd (aiMoveCmd aiMove) , hlNoMatchMsg = "Start a new Halma match with /" <> newMatchCmd , hlNoRoundMsg = "Start a new round with /" <> newRoundCmd , hlAmbiguousMoveCmdMsg = \sender _moveCmd -> prettyUser sender <> ", the move command you sent is ambiguous. " <> "Please send another move command or choose one in the " <> "following list." , hlImpossibleMoveCmdMsg = \_sender moveCmd -> "The selected piece can't be moved to row " <> T.pack (show (unRowNumber (moveTargetRow moveCmd))) <> "!" , hlUnrecognizedCmdMsg = \(CmdCall { cmdCallName = cmd }) -> "Unknown command /" <> cmd <> ". See /" <> helpCmd <> " for a list of all commands." , hlGatheringPlayersMsg = gatheringPlayersMsg , hlMe = "me" , hlAnAI = "an AI" , hlYesMe = "yes, me" , hlYesAnAI = "yes, an AI" , hlNo = "no" } where newMatchCmd, newRoundCmd, undoCmd, helpCmd :: T.Text newMatchCmd = "newmatch" newRoundCmd = "newround" undoCmd = "undo" helpCmd = "help" nominal i = case i of 1 -> "first" 2 -> "second" 3 -> "third" 4 -> "fourth" 5 -> "fifth" 6 -> "sixth" _ -> "(error: unexpected integer)" deficitMsg result = "with a deficit of " <> T.pack (show (eprLag result)) <> " moves" congrat result = let party = prParty $ eprPartyResult result in case (partyPlayer party, eprPlace result) of (AIPlayer, i) -> "The AI " <> teamEmoji (partyHomeCorner party) <> " finishes " <> nominal (i+1) <> (if i == 0 then "" else " " <> deficitMsg result) (TelegramPlayer user, 0) -> prettyUser user <> ", " <> "congratulations on your " <> (if eprPlaceShared result then "shared " else "") <> "first place \127941" -- unicode symbol: sports medal (TelegramPlayer user, i) -> prettyUser user <> ", " <> "you are " <> nominal (i+1) <> " " <> deficitMsg result prettyPlayer :: Player -> T.Text prettyPlayer player = case player of AIPlayer -> "AI" TelegramPlayer user -> prettyUser user prettyList :: [T.Text] -> T.Text prettyList xs = case xs of [] -> "<empty list>" [x] -> x _:_:_ -> T.intercalate ", " (init xs) <> " and " <> last xs gatheringPlayersMsg = \case NoPlayers -> "Starting a new match! Who is the first player?" OnePlayer firstPlayer -> "The first player is " <> prettyPlayer firstPlayer <> ".\n" <> "Who is the second player?" EnoughPlayers config -> let (count, nextOrdinal) = case configurationPlayers config of TwoPlayers {} -> ("two", "third") ThreePlayers {} -> ("three", "fourth") FourPlayers {} -> ("four", "fifth") FivePlayers {} -> ("five", "sixth") SixPlayers {} -> error "unexpected state: gathering players although there are already six!" in "The first " <> count <> " players are " <> prettyList (map prettyPlayer (toList (configurationPlayers config))) <> ".\n" <> "Is there a " <> nextOrdinal <> " player?" -- | German (deutsch) deHalmaLocale :: HalmaLocale deHalmaLocale = HalmaLocale { hlNewMatchCmd = newMatchCmd , hlNewRoundCmd = newRoundCmd , hlUndoCmd = undoCmd , hlHelpCmd = helpCmd , hlWelcomeMsg = "Hallo, ich bin @HalmaBot, ein [quelloffener](https://github.com/timjb/halma) Telegram-Bot " <> " programmiert von Tim Baumann <[email protected]> in Haskell." , hlHelpMsg = "Du kannst mich durch folgende Kommandos steuern:\n" <> "/" <> newMatchCmd <> " β€” startet einen neuen Halma-Wettkampf\n" <> "/" <> newRoundCmd <> " β€” startet eine neue Spielrunde im aktuellen Wettkampf\n" <> "/" <> undoCmd <> " β€” macht den letzten Zug rΓΌckgΓ€ngig\n" <> "/english β€” " <> localeFlag En <> " switch to English / auf Englisch umschalten\n" <> "/" <> helpCmd <> " β€” zeigt diese Hilfe-Nachricht an\n\n" <> "Zuganweisungen sind folgendermaßen aufgebaut:\n" <> "Zuerst kommt ein Buchstabe von A bis O (der Spielstein, den du " <> " bewegen mΓΆchtest), dann kommt die Nummer der Reihe in den du den " <> " Stein bewegen mΓΆchtest. " <> "Wenn es mehrere mΓΆgliche Zielpositionen innerhalb dieser Reihe gibt, " <> "dann frage ich dich, welche du genau meinst.\n" <> "Zum Beispiel: Das Kommando 'A11' bewegt deinen Stein mit der " <> "Aufschrift 'A' in die Zeile Nummer 11." , hlCongratulation = congrat , hlCantStartNewRoundBecauseNoMatch = "Um eine neue Runde zu starten, muss erst ein neues Spiel mit /newmatch gestartet werden." , hlStartingANewRound = "Neue Runde!" , hlYourTurn = \homeCorner user -> prettyUser user <> " " <> teamEmoji homeCorner <> ", du bist dran!" , hlNotYourTurn = \notYourTurn -> "Hey " <> prettyUser (you notYourTurn) <> ", du bist nicht an der Reihe, sondern " <> prettyPlayer (thePlayerWhoseTurnItIs notYourTurn) <> "!" , hlCantUndo = \case Nothing -> "'undo' nicht mΓΆglich!" Just CantUndoNoGame -> "'undo' nicht mΓΆglich: es ist gerade kein Spiel am Laufen!" , hlAIMove = \aiMove -> "Die KI " <> teamEmoji (aiHomeCorner aiMove) <> " macht den folgenden Zug: " <> showMoveCmd (aiMoveCmd aiMove) , hlNoMatchMsg = "Starte einen neuen Halma-Wettkampf mit /" <> newMatchCmd , hlNoRoundMsg = "Starte eine neue Runde mit /" <> newRoundCmd , hlAmbiguousMoveCmdMsg = \sender _moveCmd -> prettyUser sender <> ", deine Zuganweisung ist nicht eindeutig. " <> "Sende bitte eine andere Zuganweisung oder prΓ€zisiere deine Anweisung mit Hilfe " <> "der folgenden Liste." , hlImpossibleMoveCmdMsg = \_sender moveCmd -> "Der Spielstein '" <> showPieceNumber (movePieceNumber moveCmd) <> "' kann nicht in " <> "die Reihe " <> T.pack (show (unRowNumber (moveTargetRow moveCmd))) <> " bewegt werden!" , hlUnrecognizedCmdMsg = \(CmdCall { cmdCallName = cmd }) -> "Unbekanntes Kommando /" <> cmd <> ". Eine Liste aller Kommandos liefert /" <> helpCmd <> "." , hlGatheringPlayersMsg = gatheringPlayersMsg , hlMe = "ich" , hlAnAI = "eine KI" , hlYesMe = "ja, ich" , hlYesAnAI = "ja, eine KI" , hlNo = "nein" } where newMatchCmd, newRoundCmd, undoCmd, helpCmd :: T.Text newMatchCmd = "neuerwettkampf" newRoundCmd = "neuerunde" undoCmd = "zurueck" helpCmd = "hilfe" nominal i = case i of 1 -> "erster" 2 -> "zweiter" 3 -> "dritter" 4 -> "vierter" 5 -> "fΓΌnfter" 6 -> "sechster" _ -> "(Fehler: unerwartete Zahl)" deficitMsg result = "mit einem RΓΌckstand von " <> T.pack (show (eprLag result)) <> " ZΓΌgen" congrat result = let party = prParty $ eprPartyResult result in case (partyPlayer party, eprPlace result) of (AIPlayer, i) -> "Die KI " <> teamEmoji (partyHomeCorner party) <> " wird " <> (if eprPlaceShared result then "ebenfalls " else "") <> capitalize (nominal (i+1)) <> (if i == 0 then "" else " " <> deficitMsg result) (TelegramPlayer user, 0) -> prettyUser user <> ", " <> "GlΓΌckwunsch zum " <> (if eprPlaceShared result then "geteilten " else "") <> "ersten Platz \127941" -- unicode symbol: sports medal (TelegramPlayer user, i) -> prettyUser user <> ", " <> "du bist " <> (if eprPlaceShared result then "auch " else "") <> capitalize (nominal (i+1)) <> " " <> deficitMsg result prettyPlayer :: Player -> T.Text prettyPlayer player = case player of AIPlayer -> "eine KI" TelegramPlayer user -> prettyUser user prettyList :: [T.Text] -> T.Text prettyList xs = case xs of [] -> "<leere Liste>" [x] -> x _:_:_ -> T.intercalate ", " (init xs) <> " und " <> last xs gatheringPlayersMsg = \case NoPlayers -> "Ein neuer Wettkampf! Wer macht mit?" OnePlayer firstPlayer -> prettyPlayer firstPlayer <> " fΓ€ngt also an.\n" <> "Wer macht noch mit?" EnoughPlayers config -> let count = case configurationPlayers config of TwoPlayers {} -> "zwei" ThreePlayers {} -> "drei" FourPlayers {} -> "vier" FivePlayers {} -> "fΓΌnf" SixPlayers {} -> "secht" in "Die ersten " <> count <> " Parteien sind " <> prettyList (map prettyPlayer (toList (configurationPlayers config))) <> ".\n" <> "Macht noch jemand mit?" capitalize :: T.Text -> T.Text capitalize t = if T.null t then t else toUpper (T.head t) `T.cons` T.tail t allLocaleIds :: [LocaleId] allLocaleIds = [En, De] localeById :: LocaleId -> HalmaLocale localeById localeId = case localeId of En -> enHalmaLocale De -> deHalmaLocale
timjb/halma
halma-telegram-bot/src/Game/Halma/TelegramBot/View/I18n.hs
mit
13,187
0
29
3,674
2,858
1,557
1,301
315
23
{-# LANGUAGE RecordWildCards #-} -- | Reading/writing bundles of embedded files and other data from/to -- executables. -- -- A bundle has three parts: the static header, which identifies -- a string of bytes as a bundle using a particular version of the format -- and gives the size of the dynamic header; the dynamic header which -- describes all files and directories contained in the bundle; and the data -- part, where the data for all files is located. -- All words are stored in little endian format. -- -- The static header comprises the last 'bundleHeaderStaticSize' bytes of the -- file, with the dynamic header coming immediately before, and the data -- section coming immediately before the dynamic header. -- -- The dynamic header is stored as a tuple of the number of files in the -- bundle (Word32), and the . -- Each file is stored as a triple of the file's UTF-8 encoded path, -- its offset from the start of the data section, and its size. -- The path is prepended with a Word32 giving its length in bytes; the -- offset is given as a Word32 and the size is given as a Word32. -- -- The layout of the bundle format is given in the following table: -- -- > [file data] -- > -- > [files] * hdrNumFiles -- > pathLen : Word32 -- > path : pathLen * Word8 -- > offset : Word64 -- > size : Word32 -- > -- > [static header] -- > hdrDataOffset : Word64 -- > hdrNumFiles : Word32 -- > hdrDynSize : Word32 -- > hdrVersion : Word8 -- > "BNDLLDNB" : Word64 -- -- The included @embedtool@ program offers a command line interface -- for manipulating and inspecting bundles. module Data.Embed.File ( Bundle, -- * Reading bundles hasBundle, openBundle, withBundle, closeBundle, readBundleFile, readBundle, listBundleFiles, -- * Creating bundles File (..), appendBundle, eraseBundle, replaceBundle ) where import Control.Concurrent import Control.Exception import Control.Monad import qualified Data.ByteString as BS import Data.Hashable import qualified Data.IntMap as M import Data.Serialize import Data.String import System.Directory import System.IO import Data.Embed.Header -- | A file to be included in a bundle. May be either the path to a file on -- disk or an actual (path, data) pair. -- -- If a file path refers to a directory, all non-dotfile files and -- subdirectories of that directory will be included in the bundle. -- File paths also have a strip number: the number of leading directories -- to strip from file names when adding them to a bundle. -- For instance, adding @File 1 "foo/bar"@ to a bundle will add the file -- @foo/bar@, under the name @bar@ within the bundle. -- -- If a file name would "disappear" entirely due to stripping, for instance -- when stripping two directories from @foo/bar@, @bar@ will "disappear" -- entirely and so will be silently ignored. data File = FilePath Int FilePath | FileData FilePath BS.ByteString instance IsString File where fromString = FilePath 0 -- | A handle to a file bundle. Bundle handles are obtained using 'openBundle' -- or 'withBundle' and start out as open. That is, files may be read from -- them. An open bundle contains an open file handle to the bundle's backing -- file, ensuring that the file data will not disappear from under it. -- When a bundle becomes unreachable, its corresponding file handle is -- closed by the bundle's associated finalizer. -- -- However, as finalizers are not guaranteed to run promptly - or even -- at all - bundles may also be closed before becoming unreachable using -- 'closeBundle'. If you expect to perform other operations on a bundle's -- backing file, you should always close the bundle manually first. data Bundle = Bundle { -- | The header of the bundle. bundleHeader :: !BundleHeader, -- | An open handle to the bundle's file, for reading file data. bundleHandle :: !Handle, -- | The offset from the end of the file to the start of the data section. bundleDataOffset :: !Integer, -- | Lock to ensure thread safety of read/close operations. Iff 'True', then -- the bundle is still alive, i.e. the handle is still open. bundleLock :: !(MVar Bool) } -- | Read a bundle static header from the end of a file. readStaticHeader :: Handle -> IO (Either String StaticHeader) readStaticHeader hdl = do hSeek hdl SeekFromEnd (negate bundleHeaderStaticSize) ehdr <- decode <$> BS.hGet hdl (fromInteger bundleHeaderStaticSize) case ehdr of Left e -> pure (Left $ "unable to parse static header: " ++ e) Right hdr | hdrMagicNumber hdr /= bundleMagicNumber -> pure (Left "not a bundle") | hdrVersion hdr > bundleCurrentVersion -> pure (Left "unsupported bundle version") | otherwise -> pure (Right hdr) -- | Open a file bundle. The bundle will keep an open handle to its backing -- file. The handle will be closed when the bundle is garbage collected. -- Use 'closeBundle' to close the handle before the openBundle :: FilePath -> IO (Either String Bundle) openBundle fp = flip catch (\(SomeException e) -> pure (Left $ show e)) $ do -- Read static header hdl <- openBinaryFile fp ReadMode ehdr <- readStaticHeader hdl case ehdr of Left err -> pure (Left err) Right statichdr -> do -- Read dynamic header let dynsize = fromIntegral (hdrDynSize statichdr) dynoffset = bundleHeaderStaticSize + dynsize hSeek hdl SeekFromEnd (negate dynoffset) bytes <- BS.hGet hdl (fromInteger dynsize) -- Parse dynamic header and create bundle case runGet (getHdrFiles (hdrNumFiles statichdr)) bytes of Left e -> fail $ "unable to parse file list: " ++ e Right filehdr -> do let hdr = BundleHeader { hdrFiles = filehdr, hdrStatic = statichdr } lock <- newMVar True let b = Bundle hdr hdl (fromIntegral (hdrDataOffset statichdr)) lock _ <- mkWeakMVar lock (closeBundle b) pure $! Right $! b -- | Close a bundle before it becomes unreachable. After a bundle is closed, -- any read operations performed on it will fail as though the requested -- file could not be found. -- Subsequent close operations on it will have no effect. closeBundle :: Bundle -> IO () closeBundle b = do alive <- takeMVar (bundleLock b) when alive $ hClose (bundleHandle b) putMVar (bundleLock b) False -- | Perform a computation over a bundle, returning an error if either the -- computation failed or the bundle could not be loaded. -- The bundle is always closed before this function returns, regardless of -- whether an error occurred. withBundle :: FilePath -> (Bundle -> IO a) -> IO (Either String a) withBundle fp f = do eb <- openBundle fp case eb of Right b -> fmap Right (f b) `catch` handler <* closeBundle b Left e -> return (Left e) where handler (SomeException e) = pure (Left $ show e) -- | Write a bundle to a file. If the given file already has a bundle, the new -- bundle will be written *after* the old one. The old bundle will thus still -- be present in the file, but only the new one will be recognized by -- 'openBundle' and friends. appendBundle :: FilePath -> [File] -> IO () appendBundle fp fs = withBinaryFile fp AppendMode $ \hdl -> do (datasize, metadata) <- foldM (packFile hdl) (0, M.empty) fs let mdbytes = putHdrFiles metadata mdlen = BS.length mdbytes dataoff = datasize + fromIntegral mdlen + fromIntegral bundleHeaderStaticSize hdr = mkStaticHdr (M.size metadata) mdlen dataoff BS.hPut hdl mdbytes BS.hPut hdl (encode hdr) where isDotFile ('.':_) = True isDotFile _ = False p </> f = p ++ "/" ++ f stripLeading 0 f = f stripLeading n f = stripLeading (n-1) (drop 1 (dropWhile (/= '/') f)) packFile hdl acc (FilePath n p) = do let stripped = stripLeading n p if null stripped then return acc else do isDir <- doesDirectoryExist p if isDir then do files <- filter (not . isDotFile) <$> getDirectoryContents p foldM (packFile hdl) acc (map (FilePath n . (p </>)) files) else BS.readFile p >>= packFile hdl acc . FileData stripped packFile hdl (off, m) (FileData p d) = do BS.hPut hdl d let len = fromIntegral (BS.length d) off' = off + fromIntegral len off' `seq` return (off', (M.alter (ins p off len) (hash p) m)) ins p off len Nothing = Just [(p, (off, len))] ins p off len (Just xs) = Just ((p, (off, len)) : xs) -- | Read a file from a previously opened bundle. Will fail of the given path -- is not found within the bundle, or if the bundle is no longer alive, i.e. -- it has been closed using 'closeBundle'. readBundleFile :: Bundle -> FilePath -> IO (Either String BS.ByteString) readBundleFile (Bundle {..}) fp = flip catch (\(SomeException e) -> pure (Left $ show e)) $ do withMVar bundleLock $ \v -> do when (v == False) $ fail "bundle already closed" case M.lookup (hash fp) (hdrFiles bundleHeader) >>= lookup fp of Nothing -> fail "no such file" Just (off, sz) -> do hSeek bundleHandle SeekFromEnd (fromIntegral off - bundleDataOffset) Right <$> BS.hGet bundleHandle (fromIntegral sz) -- | List all files in the given bundle. Will succeed even on closed bundles. listBundleFiles :: Bundle -> [FilePath] listBundleFiles = map fst . concat . M.elems . hdrFiles . bundleHeader -- | Like 'readBundleFile', but attempts to decode the file's contents into an -- appropriate Haskell value. readBundle :: Serialize a => Bundle -> FilePath -> IO (Either String a) readBundle b fp = do ebytes <- readBundleFile b fp pure (ebytes >>= decode) -- | Does the given file contain a bundle or not? hasBundle :: FilePath -> IO Bool hasBundle fp = do ehdr <- withBinaryFile fp ReadMode readStaticHeader case ehdr of Right _ -> pure True _ -> pure False -- | Remove a bundle from an existing file. Does nothing if the given file -- does not have a bundle. The given file is *not* removed, even if it only -- contains the bundle. eraseBundle :: FilePath -> IO () eraseBundle fp = do withBinaryFile fp ReadWriteMode $ \hdl -> do ehdr <- readStaticHeader hdl case ehdr of Right hdr -> do sz <- hFileSize hdl hSetFileSize hdl (sz - fromIntegral (hdrDataOffset hdr)) _ -> return () -- | Replace the bundle currently attached to the given file. Equivalent to -- 'appendBundle' if the given file does not already have a bundle attached. replaceBundle :: FilePath -> [File] -> IO () replaceBundle fp fs = eraseBundle fp >> appendBundle fp fs
valderman/data-bundle
Data/Embed/File.hs
mit
10,981
0
25
2,716
2,139
1,101
1,038
146
7
-- -*- mode: haskell; -*- module Wiggly ( headMay, takeMay, sortOn, nChooseK, chunkList, comboCount, weird, firstThat , nckValues ) where import Data.Maybe import Data.Ord (comparing) import Data.List (sort, sortBy) import Debug.Trace (trace) nckValuesBelow :: Int -> Int -> Int -> Int -> (Int, Int) nckValuesBelow limit k i v = let nv = comboCount (i+1) k in if nv > limit then (i,v) else nckValuesBelow limit k (i+1) nv -- determine the indices of the elements for n choose k where the limit is the Nth combination required nckValues :: Int -> Int -> [Int] nckValues limit k = let (i,v) = nckValuesBelow limit k 0 0 in if k == 1 then i : [] else i : (nckValues (limit-v) (k-1)) -- runny and ruggy are two things created when trying to break cards into subgroups based on contiguous rank values runny :: (Eq a, Num a, Enum a) => [a] -> [[a]] runny [] = [] runny xs = [indices] where diffs = map (\(x,y) -> y-x ) $ zip xs (drop 1 xs) diffIndices = zip diffs [1..] breakPoints = filter (\x -> fst x /= 1) diffIndices indices = map snd breakPoints ruggy :: Int -> [Int] -> [Int] -> [[Int]] ruggy start breaks [] = [] ruggy start [] xs = [xs] ruggy start breaks xs = (fst taken):(ruggy break (tail breaks) (snd taken)) where break = head breaks takeCount = break - start taken = splitAt takeCount xs firstThat :: (a -> Bool) -> [a] -> a firstThat f (x:xs) | f x == True = x | otherwise = firstThat f xs weird :: (Integral a) => a -> Maybe a weird 3 = (trace "weird ") Nothing weird n = (trace "normal ") Just n takeMay :: Int -> [a] -> Maybe [a] takeMay n xs | length xs >= n = Just $ take n xs | otherwise = Nothing headMay :: [a] -> Maybe a headMay [] = Nothing headMay (x:xs) = Just x -- stolen from new base sortOn :: Ord b => (a -> b) -> [a] -> [a] sortOn f = map snd . sortBy (comparing fst) . map (\x -> let y = f x in y `seq` (y, x)) comboCount :: (Integral a) => a -> a -> a comboCount n 0 = 1 comboCount 0 k = 0 comboCount n k = comboCount (n-1) (k-1) * n `div` k -- n choose k nChooseK :: [a] -> Int -> [[a]] nChooseK xs 1 = map (\x -> [x]) xs nChooseK xs n | (length xs) > n = foo ++ bar | (length xs) == n = [xs] | otherwise = [] where foo = map (\x -> (head xs):x ) (nChooseK (tail xs) (n-1)) bar = (nChooseK (tail xs) n) chunkList :: Int -> [a] -> [[a]] chunkList _ [] = [] chunkList n xs = thisChunk : (chunkList n thisRemainder) where thisChunk = take n xs thisRemainder = drop n xs diffY :: (Num a) => [a] -> [a] diffY [] = [] diffY (x:xs) = reverse $ snd $ foldl go (x,[]) xs where go (last,lst) ce = (ce,(ce-last):lst) discontinuityIndices :: (Num a, Ord a, Integral b) => [a] -> [b] discontinuityIndices xs = map snd $ filter (\x -> fst x > 1) $ zip (diffY $ sort xs) [1..] -- this kind of works but leaves out the final set of numbers that come after the final discontinuity groupByDiscontinuity :: (Num a, Ord a) => [a] -> [[a]] groupByDiscontinuity xs = res where d = discontinuityIndices xs (_,_,res) = foldl go (0,xs,[]) d go (offset,xs,ys) idx = (idx+offset, (snd (splitAt (idx-offset) xs)), (fst (splitAt (idx-offset) xs)):ys )
wiggly/functional-pokering
src/Wiggly.hs
mit
3,444
0
14
1,009
1,594
848
746
84
2
{-# OPTIONS_HADDOCK hide, prune #-} module Handler.Mooc.BrowseProposals ( getBrowseProposalsR , getBrowseProposalsForExpertsR , fetchLastSubmissions , mkSubmissionsWidget , noProposalParams , ProposalParams(..) , ProposalSortParam (..) ) where import Application.Grading (designRatingToVisual) import Database.Persist.Sql (rawSql, Single (..), toSqlKey) import qualified Data.Text as Text import Import import Import.BootstrapUtil import qualified Text.Blaze as Blaze import Text.Read (read) pageSize :: Int pageSize = 80 getBrowseProposalsR :: Int -> Handler Html getBrowseProposalsR = getBrowseProposalsPamsR noProposalParams -- | We are using a separate route to have different sorting defaults. -- i.e. `noProposalParams` differs from `convenientReviewOrder`, -- and it would take more time to implement all these defaults via get parameters -- (and also links would become more weird and less typesafe TM). getBrowseProposalsForExpertsR :: Handler Html getBrowseProposalsForExpertsR = getBrowseProposalsPamsR convenientReviewOrder 1 getBrowseProposalsPamsR :: ProposalParams -> Int -> Handler Html getBrowseProposalsPamsR defParams page = do exercises <- runDB $ selectList [] [] exerciseGet <- lookupGetParam "exercise_id" let params = defParams {onlyByExerciseId = byExerciseDef} where byExerciseDef = orElse (toSqlKey . read . unpack <$> exerciseGet) (onlyByExerciseId defParams) orElse x y = case x of Just _ -> x Nothing -> y ((res, widget), _) <- runFormGet $ proposalsForm params exercises let params' = case res of (FormSuccess ps) -> ps _ -> params submissions <- runDB $ fetchLastSubmissions $ params' { propLimit = Just pageSize , propOffset = (max 0 $ page-1)*pageSize } submissionsWidget <- mkSubmissionsWidget submissions pages <- negate . (`div` pageSize) . negate <$> runDB (countUniqueSubmissions params') let is = [1..pages] fullLayout Nothing "Qua-kit student designs" $ do setTitle "Qua-kit student designs" toWidgetHead $ -- move card-action down. Note, height 210 is 200 for image + 10 for overlapping margin of element above [julius| $(document).ready(function() { $('#proposalsForm').change( function() { this.submit(); }) }); |] toWidgetHead $ [cassius| .form-inline .form-group display: inline-block margin-left: 15px .btn-default margin-left: 15px .pageSelector display:inline background: none !important color: inherit border: none margin: 2px padding: 0 !important font: inherit cursor: pointer color: #ff6f00 &:hover color: #b71c1c @media (min-width: 2000px) .col-xl-3 width: 25% .container max-width: 3000px |] [whamlet| <form .form-inline #proposalsForm action=1 method=GET> <div class="ui-card-wrap"> <div class=row> ^{widget} <div class=row> ^{submissionsWidget} <!-- footer with page numbers --> $if pages == 0 <p>No submissions found with the selected criteria. $else <div class="row"> <div class="col-lg-9 col-md-9 col-sm-9"> <div class="card margin-bottom-no"> <div class="card-main"> <div class="card-inner"> $forall i <- is $if i == page <p style="margin:2px;padding:0;display:inline">#{i} $else <input type=submit class=pageSelector value=#{i} formaction=@{BrowseProposalsR i}> |] mkSubmissionsWidget :: [Submission] -> Handler Widget mkSubmissionsWidget submissions = do role <- muserRole <$> maybeAuth let isExpert = role == UR_EXPERT cOpacity i = 0.5 + fromIntegral i / 198 :: Double return $ do toWidgetHead [cassius| span.card-comment.card-criterion width: 24px padding: 0px margin: 4px display: inline-block color: #ff6f00 text-align: center .containerCard position: relative padding: 0 .criterions padding: 3px 16px 0 16px position: absolute bottom: 0 width: 100% background: white @media (min-width: 500px) .submissionCard height: 200px |] [whamlet| $forall sub <- submissions $with sc <- scenario sub <div class="col-xl-3 col-lg-4 col-md-6 col-xs-12"> <div.card.submissionCard> <aside.card-side.card-side-img.pull-left.card-side-moocimg> <img src=@{ProposalPreviewR $ currentScenarioHistoryScenarioId sc} width="200px" height="200px" style="margin-left: -25px;"> <div.card-main.containerCard> <div.card-inner style="margin: 10px 12px;"> <p style="margin: 6px 0px; color: #b71c1c;"> #{authorName sub} <br> #{show $ utctDay $ currentScenarioLastUpdate sc} <p style="margin: 6px 0px; white-space: pre-line; overflow-y: hidden; color: #555;"> #{shortComment $ currentScenarioDescription sc} <div.card-comment.card-action.criterions> $forall (CriterionData svg cname crating) <- criterions sub $maybe rating <- crating <span.card-comment.card-criterion style="opacity: #{cOpacity rating}" title="#{cname}"> #{svg} <p style="display: inline; margin: 0; padding:0; color: rgb(#{156 + rating}, 111, 0)"> #{rating} $nothing <span.card-comment.card-criterion style="opacity: 0.3" title="Not enough votes to show rating"> #{svg} \ - # $maybe expertgrade <- avgExpertGrade sub <span.card-comment.card-criterion title="Expert Grade"> <span class="icon icon-lg" style="width:24px; height:24px;">star</span> <p style="display: inline; margin: 0; padding:0; color: #b71c1c;)"> #{expertgrade} <div.card-action-btn.pull-right> $with subViewLink <- SubmissionViewerR (currentScenarioTaskId sc) (currentScenarioAuthorId sc) $if isExpert && (isNothing $ currentScenarioGrade sc) <a.btn.btn-flat.btn-brand-accent.waves-attach.waves-effect style="background: red; color: white !important;" href=@{subViewLink} target="_blank"> <span.icon>visibility Review $else <a.btn.btn-flat.btn-brand-accent.waves-attach.waves-effect href=@{subViewLink} target="_blank"> <span.icon>visibility View |] shortLength :: Int shortLength = 140 maxLines :: Int maxLines = 3 data CriterionData = CriterionData { critIcon :: Blaze.Markup , critName :: Text , critRating :: Maybe Int } data Submission = Submission { scenario :: CurrentScenario , authorName :: Text , avgExpertGrade :: Maybe Double , criterions :: [CriterionData] } data ProposalSortParam = Default | Newest | Oldest | GradeDesc | GradeAsc deriving (Eq, Show) data ProposalParams = ProposalParams { onlyNeedsReview :: Maybe () , onlyByAuthorId :: Maybe UserId , onlyByExerciseId :: Maybe ScenarioProblemId , sortOrder :: ProposalSortParam , propLimit :: Maybe Int , propOffset :: Int } noProposalParams :: ProposalParams noProposalParams = ProposalParams { onlyNeedsReview = Nothing , onlyByAuthorId = Nothing , onlyByExerciseId = Nothing , sortOrder = Default , propLimit = Nothing , propOffset = 0 } convenientReviewOrder :: ProposalParams convenientReviewOrder = ProposalParams { onlyNeedsReview = Just () , onlyByAuthorId = Nothing , onlyByExerciseId = Nothing , sortOrder = Oldest , propLimit = Nothing , propOffset = 0 } proposalsForm :: ProposalParams -> [Entity ScenarioProblem] -> Html -> MForm Handler (FormResult ProposalParams, Widget) proposalsForm defParams exercises extra = do maybeMe <- lift maybeAuthId let exerciseList = map (\(Entity spId sp) -> (scenarioProblemDescription sp, Just spId)) exercises (onlyNeedsReviewRes, onlyNeedsReviewView) <- mreq (bootstrapSelectFieldList [ ("All"::Text, Nothing) , ("Needs review", Just ()) ]) "" (Just $ onlyNeedsReview defParams) (onlyByAuthorIdRes, onlyByAuthorView) <- mreq (bootstrapSelectFieldList [ ("All users"::Text, Nothing) , ("Only my submissions", maybeMe) ]) "" (Just $ onlyByAuthorId defParams) (onlyByExerciseIdRes, onlyByExerciseIdView) <- mreq (bootstrapSelectFieldList $ ("All exercises"::Text, Nothing) : exerciseList ) "" (Just $ onlyByExerciseId defParams) (sortOrderRes, sortOrderView) <- mreq (bootstrapSelectFieldList [ ("Default order"::Text, Default) , ("Newest first", Newest) , ("Oldest first", Oldest) , ("Best grade first", GradeDesc) , ("Best grade last", GradeAsc) ]) "" (Just $ sortOrder defParams) let proposalParams = ProposalParams <$> onlyNeedsReviewRes <*> onlyByAuthorIdRes <*> onlyByExerciseIdRes <*> sortOrderRes <*> FormSuccess (propLimit defParams) <*> FormSuccess (propOffset defParams) let widget = do [whamlet| #{extra} ^{fvInput onlyNeedsReviewView} ^{fvInput onlyByAuthorView} ^{fvInput onlyByExerciseIdView} ^{fvInput sortOrderView} <input type=submit value=Filter class="btn btn-default" formaction=@{BrowseProposalsR 1} > |] return (proposalParams, widget) shortComment :: Text -> Text shortComment t = dropInitSpace . remNewLines $ if Text.length t < shortLength then t else remLong t <> "..." where remLong = Text.dropEnd 1 . Text.dropWhileEnd (\c -> c /= ' ' && c /= '\n' && c /= '\t') . Text.take shortLength remNewLines = Text.dropWhileEnd (\c -> c == ' ' || c == '\n' || c == '\r' || c == '\t') . Text.unlines . take maxLines . filter (not . Text.null) . map (Text.dropWhile (\c -> c == ' ' || c == '\r' || c == '\t')) . Text.lines dropInitSpace = Text.dropWhile (\c -> c == ' ' || c == '\n' || c == '\r' || c == '\t') generateJoins :: ProposalParams -> ([PersistValue], Text, Text) generateJoins ps = (whereParams ++ limitParams, joinStr, orderStr) where joinStr = Text.unlines [ " FROM (" , " SELECT s.*, \"user\".name as username" , " FROM current_scenario as s" , " JOIN \"user\"" , " ON \"user\".id = s.author_id" , whereClause , " ORDER BY ", primaryOrder, ", s.id DESC" , limitClause , " ) s" , " JOIN problem_criterion" , " ON s.task_id = problem_criterion.problem_id" , " JOIN criterion" , " ON criterion.id = problem_criterion.criterion_id" , " LEFT OUTER JOIN rating" , " ON s.task_id = rating.problem_id AND" , " s.author_id = rating.author_id AND" , " criterion.id = rating.criterion_id" , " LEFT OUTER JOIN (" , " SELECT scenario_id, AVG(grade) as expertgrade" , " FROM expert_review" , " GROUP BY scenario_id" , " ) eg" , " ON s.history_scenario_id = eg.scenario_id" ] orderStr = Text.unlines [ "ORDER BY ", primaryOrder, ", s.id DESC, criterion.id ASC" ] primaryOrder = case sortOrder ps of Default -> "s.task_id DESC, COALESCE(s.grade, 0) DESC" Newest -> "s.last_update DESC" Oldest -> "s.last_update ASC" GradeDesc -> "COALESCE(s.grade, 0) DESC" GradeAsc -> "COALESCE(s.grade, 0) ASC" pOffset = toPersistValue $ propOffset ps (limitParams, limitClause) = case propLimit ps of Just limit -> ([toPersistValue limit, pOffset], "LIMIT ? OFFSET ?") _ -> ([pOffset], "OFFSET ?") (whereParams, whereClause) = if null wheres then ([], "") else (map fst wheres, "WHERE " ++ intercalate " AND " (map snd wheres)) where wheres = catMaybes [ onlyByAuthorId ps >>= \a -> Just (toPersistValue a, "s.author_id = ?") , onlyNeedsReview ps >>= \_ -> Just (toPersistValue (0::Int), "s.grade IS NULL AND 0 = ?") , onlyByExerciseId ps >>= \e -> Just (toPersistValue e, "s.task_id = ?") ] -- | get user name, scenario, and ratings fetchLastSubmissions :: ProposalParams -> ReaderT SqlBackend Handler [Submission] fetchLastSubmissions params = groupSubs <$> map convertTypes <$> rawSql query preparedParams where (preparedParams, joinStr, orderStr) = generateJoins params groupSubs (sub:subs) = sub' : groupSubs subs' where (sub', subs') = go sub subs go y (x:xs) | currentScenarioHistoryScenarioId (scenario y) == currentScenarioHistoryScenarioId (scenario x) = let crits = criterions y ++ criterions x in go (y {criterions = crits}) xs | otherwise = (y, x:xs) go y [] = (y, []) groupSubs [] = [] currentScenarioCols = [ "s.id" , "s.history_scenario_id" , "s.author_id" , "s.task_id" , "s.description" , "s.grade" , "s.last_update" , "s.edx_grading_id" ] query = Text.unlines [ " SELECT ", intercalate ", " currentScenarioCols , " , username, eg.expertgrade" , " , criterion.icon, criterion.name" , " , COALESCE(rating.current_evidence_w, 0), COALESCE(rating.value, 0)" , joinStr , orderStr ,";" ] countUniqueSubmissions :: ProposalParams -> ReaderT SqlBackend Handler Int countUniqueSubmissions params = getVal <$> rawSql query preparedParams where (preparedParams, joinStr, _) = generateJoins params getVal (Single c:_) = c getVal [] = 0 query = Text.unlines [ "SELECT count(DISTINCT s.author_id)" , joinStr , ";" ] convertTypes :: ( Single CurrentScenarioId --currentScId , ( Single ScenarioId --historyScenarioId , Single UserId --authorId , Single ScenarioProblemId --taskId , Single Text --description , Single (Maybe Double) --grade , Single UTCTime --lastUpdate , Single (Maybe EdxGradingId)--edxGradingId ) , Single Text --authorName , Single (Maybe Double) --avgExpertGrade , ( Single Text --criterionIcon , Single Text --criterionName , Single Double --evidence , Single Double --rating ) ) -> Submission convertTypes ( Single _currentScId , ( Single historyScenarioId , Single authorId , Single taskId , Single description , Single grade , Single lastUpdate , Single edxGradingId ) , Single authorName , Single avgExpertGrade , ( Single criterionIcon , Single criterionName , Single evidence , Single rating ) ) = Submission { scenario = CurrentScenario { currentScenarioHistoryScenarioId = historyScenarioId , currentScenarioAuthorId = authorId , currentScenarioTaskId = taskId , currentScenarioDescription = description , currentScenarioEdxGradingId = edxGradingId , currentScenarioGrade = grade , currentScenarioLastUpdate = lastUpdate } , authorName = authorName , avgExpertGrade = avgExpertGrade , criterions = [ CriterionData { critIcon = Blaze.preEscapedToMarkup (criterionIcon :: Text) , critName = criterionName , critRating = designRatingToVisual evidence rating } ] }
mb21/qua-kit
apps/hs/qua-server/src/Handler/Mooc/BrowseProposals.hs
mit
18,397
0
21
6,951
2,750
1,510
1,240
-1
-1
module RecursiveContents (getRecursiveContents) where import Control.Monad (forM) import System.Directory (doesDirectoryExist, getDirectoryContents) import System.FilePath ((</>), splitFileName, splitPath, joinPath) import Data.List (isInfixOf, foldl', nub) import ListTransformations (dropLastUntil) getRecursiveContents :: FilePath -> IO [FilePath] getRecursiveContents topdir = do names <- getDirectoryContents topdir let properNames = filter (`notElem` [".", ".."]) names paths <- forM properNames $ \name -> do let path = topdir </> name isDirectory <- doesDirectoryExist path if isDirectory then getRecursiveContents path else return [path] return $ concat paths simpleFind :: FilePath -> FilePath -> IO [FilePath] simpleFind fp dir = do names <- getRecursiveContents dir return (filter (\x -> snd (splitFileName x) == fp) names) simpleDirFind :: FilePath -> FilePath -> IO [FilePath] simpleDirFind fp dir = do names <- getRecursiveContents dir return (dropDoubleDirs fp (filter (\x -> fp `isInfixOf` x) names)) dropDoubleDirs :: FilePath -> [FilePath] -> [FilePath] dropDoubleDirs fp dirs = nub (dropAllLast fp '/' dirs) where dropAllLast :: FilePath -> Char -> [FilePath] -> [FilePath] dropAllLast fp sep = foldl' (\x y -> [(dropLastUntil fp sep y)] ++ x ) []
cirquit/Personal-Repository
Haskell/RWH/FileSystem/RecursiveContents.hs
mit
1,574
0
15
479
468
246
222
29
2
import Data.Char type Bit = Int bin2int :: [Bit] -> Int bin2int = foldr (\x y -> x + 2 * y) 0 int2bin :: Int -> [Bit] int2bin 0 = [] int2bin n = n `mod` 2 : int2bin (n `div` 2) make8 :: [Bit] -> [Bit] make8 bits = take 8 (bits ++ repeat 0) -- step 1: add function to include the parity bit parity :: [Bit] -> Bit parity bs = (sum bs) `mod` 2 addParityBit :: [Bit] -> [Bit] addParityBit bits = (parity bits) : bits where parity bs = sum bs `mod` 2 -- step 2: include the parity when encoding encode :: String -> [Bit] encode = concat . map (addParityBit . make8 . int2bin . ord) -- step 3: change chop8 to chop9 to include the parity bit chop9 :: [Bit] -> [[Bit]] chop9 [] = [] chop9 bits = take 9 bits : chop9 (drop 9 bits) -- step 4: add function to check parity bit parityCheck :: [Bit] -> [Bit] parityCheck (b:bs) | parity bs == b = bs | otherwise = error "invalid parity" -- step 5: include parity check when decoding decode :: [Bit] -> String decode = map (chr . bin2int . parityCheck) . chop9 transmit :: String -> String transmit = decode . channel . encode channel :: [Bit] -> [Bit] channel = id faultyChannel :: [Bit] -> [Bit] faultyChannel = tail faultyTransmit :: String -> String faultyTransmit = decode . faultyChannel . encode main = do print $ transmit "higher-order functions are easy" print $ faultyTransmit "higher-order functions are easy"
fabioyamate/programming-in-haskell
ch07/ex08-09.hs
mit
1,402
0
10
308
527
285
242
36
1
main = putStr "Hellow,"
MyXOF/Popush
tmp/1412873118610/test.hs
gpl-2.0
23
0
5
3
9
4
5
1
1
module SimpleRepl (repl) where repl :: (String -> String) -> IO () repl f = interact (eachLine f) eachLine :: (String -> String) -> (String -> String) eachLine f = unlines . map f . lines
robertclancy/tapl
arith/simplerepl.hs
gpl-2.0
190
0
7
38
89
47
42
5
1
-- DivideVenceras.hs -- Divide y vencerΓ‘s. -- JosΓ© A. Alonso JimΓ©nez https://jaalonso.github.com -- ===================================================================== module Tema_23.DivideVenceras (divideVenceras) where -- (divideVenceras ind resuelve divide combina pbInicial) resuelve el -- problema pbInicial mediante la tΓ©cnica de divide y vencerΓ‘s, donde -- + (ind pb) se verifica si el problema pb es indivisible -- + (resuelve pb) es la soluciΓ³n del problema indivisible pb -- + (divide pb) es la lista de subproblemas de pb -- + (combina pb ss) es la combinaciΓ³n de las soluciones ss de los -- subproblemas del problema pb. -- + pbInicial es el problema inicial divideVenceras :: (p -> Bool) -> (p -> s) -> (p -> [p]) -> (p -> [s] -> s) -> p -> s divideVenceras ind resuelve divide combina = dv' where dv' pb | ind pb = resuelve pb | otherwise = combina pb [dv' sp | sp <- divide pb]
jaalonso/I1M-Cod-Temas
src/Tema_23/DivideVenceras.hs
gpl-2.0
1,005
0
12
252
153
84
69
11
1
{-| A module which implements the calculation of apparent rates in a pepa model. -} module Language.Pepa.ApparentRates ( summedPepaRate ) where {- Standard Library Modules Imported -} {- Non-Standard Library Modules Imported -} {- Local Library Modules Imported -} import Language.Pepa.Syntax ( ParsedModel , ParsedComponentId , Transition ( .. ) , ParsedAction , ParsedRate ) import Language.Pepa.Rates ( Rate ( .. ) , sumRateExprs ) import Language.Pepa.PepaUtils ( possibleTransitions ) {- End of Module Imports -} {-| Calculates the summed rate of an action -} summedPepaRate :: ParsedAction -> ParsedComponentId -> ParsedModel -> ParsedRate summedPepaRate act component model | null imms && null tops && null timeds = error "No rates to sum" | not $ null imms = RateImmediate $ sumRateExprs imms | null imms && null tops = RateTimed $ sumRateExprs timeds | null imms && null timeds = RateTop $ sumRateExprs tops | (not $ null timeds) && (not $ null tops) = error "Mixing passive and active" | otherwise = error "Cannot make it here" where trans = filter ((act==) . pepaTransAction) $ possibleTransitions model component rates = map pepaTransRate trans imms = [ i | RateImmediate i <- rates ] tops = [ p | RateTop p <- rates ] timeds = [ t | RateTimed t <- rates ]
allanderek/ipclib
Language/Pepa/ApparentRates.hs
gpl-2.0
1,541
0
11
487
349
181
168
29
1
module Prime where import System.Random import Control.Monad import System.IO.Unsafe -- β”Œ(Β° o Β°)β”˜ DANCE! β””(Β° o Β°)┐ import Math.NumberTheory.Moduli findPrime :: Integer -> Int -> Integer findPrime b k = head (dropWhile (\x -> not (millerRabin x k)) (keyMaker 10000000000000000 b)) millerRabin :: Integer -> Int -> Bool millerRabin _ 0 = False millerRabin 2 _ = True millerRabin n k | k == 0 = False | n == 2 = True | n < 2 = False | otherwise = and $ map (maybePrime n) (witnesses k n) maybePrime :: Integer -> Integer -> Bool maybePrime n a = satisfy (iter a (factor2 (n-1)) n) n factor2 :: Integer -> (Integer, Integer) factor2 n = f2 n 0 where f2 n s | even n = f2 (n `div` 2) (s + 1) | otherwise = (n,s) iter :: Integer -> (Integer, Integer) -> Integer -> [Integer] iter a (k, d) n = map (\x -> powerMod a (k*x) n) [ 2^x | x <- [0, 1 .. d]] -- Given a list from the Miller-Rabin primality test steps -- finds out if the term before 1 squared is congruent to +/- one satisfy :: [Integer] -> Integer -> Bool satisfy [_] n = False satisfy (x:xs) n | head xs == 1 = (((x^2) - (-1)) `mod` n == 0) || (((x^2) - 1) `mod` n == 0) | otherwise = satisfy xs n -- -- -- JUNK -- -- -- ---------------------------------------------------------------------------------------- witnesses :: Int -> Integer -> [Integer] witnesses k n = unsafePerformIO (witnessesNoob k n) keyMaker :: Int -> Integer -> [Integer] keyMaker k n = unsafePerformIO (keyMakerNoob k (n-1)) witnessesNoob :: Int -> Integer -> IO [Integer] witnessesNoob k n = do g <- newStdGen return $ take k (randomRs (2,n-1) g) keyMakerNoob :: Int -> Integer -> IO [Integer] keyMakerNoob k n = do g <- newStdGen return $ take k (randomRs (2^(n-1), 2^(n)-1) g)
h3nnn4n/rsa-haskell
Prime.hs
gpl-3.0
1,852
0
14
456
803
422
381
38
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} module Main (tests, main) where import Prelude hiding (FilePath) import qualified Control.Monad.State as State import Control.Monad.Identity (runIdentity) import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as ByteString import qualified Data.Map as Map import Data.Map (Map) import qualified Data.Text as Text import Data.Text (Text) import Filesystem.Path (FilePath) import qualified Filesystem.Path.Rules as Path import Test.Chell import Anansi import Anansi.Types main :: IO () main = Test.Chell.defaultMain tests tests :: [Suite] tests = [ test_Parse , test_Tangle , test_Weave ] test_Parse :: Suite test_Parse = suite "parse" [ test_ParseFull , test_ParseInclude , test_ParseLoom , test_ParseUnknownCommand , test_ParseInvalidOption , test_ParseUnexpectedTerminator , test_ParseUnterminatedBlock , test_ParseInvalidContent , test_ParseIndentedMacro , test_ParseInvalidMacroName ] test_ParseFull :: Suite test_ParseFull = assertions "full" $ do let bytes = "hello\n\ \:option opt-1=foo\n\ \:option opt-2=bar\n\ \:#a comment\n\ \::blue\n\ \world\n\ \:f test.hs\n\ \foo\n\ \:\n\ \:d macro\n\ \bar\n\ \:\n\ \:f test.hs\n\ \|macro|\n\ \:\n" let blocks = [ BlockText "hello\n" , BlockText ":" , BlockText "blue\n" , BlockText "world\n" , BlockFile "test.hs" [ ContentText (Position "test.in" 8) "foo" ] , BlockDefine "macro" [ ContentText (Position "test.in" 11) "bar" ] , BlockFile "test.hs" [ ContentMacro (Position "test.in" 14) "" "macro" ] ] let options = Map.fromList [("opt-1", "foo"), ("opt-2", "bar")] let res = runParse "test.in" [("test.in", bytes)] $assert (right res) let Right doc = res $expect (equalItems (documentBlocks doc) blocks) $expect (sameItems (documentOptions doc) options) $expect (equal (documentLoomName doc) Nothing) test_ParseInclude :: Suite test_ParseInclude = assertions "include" $ do $expect $ equal (runParse "data/test-1.in" [ ("data/test-1.in", ":i test-2.in\n") , ("./data/test-2.in", ":d macro\nfoo\n:\n") ]) (Right (Document { documentOptions = Map.empty , documentBlocks = [ BlockDefine "macro" [ ContentText (Position "./data/test-2.in" 2) "foo" ] ] , documentLoomName = Nothing })) test_ParseLoom :: Suite test_ParseLoom = assertions "loom" $ do $expect $ equal (runParse "test.in" [("test.in", ":loom anansi.latex\n")]) (Right (Document { documentOptions = Map.empty , documentBlocks = [] , documentLoomName = Just "anansi.latex" })) test_ParseUnknownCommand :: Suite test_ParseUnknownCommand = assertions "unknown-command" $ do $expect $ equal (runParse "test.in" [("test.in", ":bad\n")]) (Left (ParseError (Position "test.in" 1) "unknown command: \":bad\"")) test_ParseInvalidOption :: Suite test_ParseInvalidOption = assertions "invalid-option" $ do $expect $ equal (runParse "test.in" [("test.in", ":option foo bar\nbaz")]) (Left (ParseError (Position "test.in" 1) "Invalid option: \"foo bar\"")) test_ParseUnexpectedTerminator :: Suite test_ParseUnexpectedTerminator = assertions "unexpected-terminator" $ do $expect $ equal (runParse "test.in" [("test.in", ":\n")]) (Left (ParseError (Position "test.in" 1) "Unexpected block terminator")) test_ParseUnterminatedBlock :: Suite test_ParseUnterminatedBlock = assertions "unterminated-block" $ do $expect $ equal (runParse "test.in" [("test.in", ":f foo.hs\n")]) (Left (ParseError (Position "test.in" 1) "Unterminated content block")) $expect $ equal (runParse "test.in" [("test.in", ":d macro\n")]) (Left (ParseError (Position "test.in" 1) "Unterminated content block")) $expect $ equal (runParse "test.in" [("test.in", ":f foo.hs\n:#\n")]) (Left (ParseError (Position "test.in" 1) "Unterminated content block")) test_ParseInvalidContent :: Suite test_ParseInvalidContent = assertions "invalid-content" $ do $expect $ equal (runParse "test.in" [("test.in", ":f foo.hs\n|bad\n")]) (Left (ParseError (Position "test.in" 2) "Invalid content line: \"|bad\"")) $expect $ equal (runParse "test.in" [("test.in", ":f foo.hs\n|bad\n")]) (Left (ParseError (Position "test.in" 2) "Invalid content line: \"|bad\"")) test_ParseIndentedMacro :: Suite test_ParseIndentedMacro = assertions "indented-macro" $ do $expect $ equal (runParse "test.in" [("test.in", ByteString.unlines [ ":d macro-foo" , "foo" , ":" , ":f foo.hs" , " |foo|" , "\t|foo|" , ":" ])]) (Right (Document { documentOptions = Map.empty , documentBlocks = [ BlockDefine "macro-foo" [ ContentText (Position "test.in" 2) "foo" ] ,BlockFile "foo.hs" [ ContentMacro (Position "test.in" 5) " " "foo" , ContentMacro (Position "test.in" 6) "\t" "foo" ] ] , documentLoomName = Nothing })) test_ParseInvalidMacroName :: Suite test_ParseInvalidMacroName = assertions "invalid-macro-name" $ do $expect $ equal (runParse "test.in" [("test.in", ":d foo|bar\n:\n")]) (Left (ParseError (Position "test.in" 1) "Invalid macro name: \"foo|bar\"")) runParse :: FilePath -> [(FilePath, ByteString)] -> Either ParseError Document runParse root files = runIdentity (parse getFile root) where getFile p = return bytes where Just bytes = lookup p files test_Tangle :: Suite test_Tangle = assertions "tangle" $ do let blocks = [ BlockText "foo\n" , BlockFile "file-1.hs" [] , BlockFile "file-2.hs" [ ContentText (Position "test" 0) "foo" ] , BlockFile "file-2.hs" [ ContentText (Position "test" 1) "bar" , ContentText (Position "test" 3) "baz" , ContentMacro (Position "test" 4) " " "macro-a" ] , BlockDefine "macro-a" [ ContentText (Position "test2" 0) "macro-1" ] , BlockDefine "macro-a" [ ContentText (Position "test2" 2) "macro-2" , ContentMacro (Position "test2" 4) " " "macro-b" ] , BlockDefine "macro-b" [ ContentText (Position "test2" 6) "macro-3" ] , BlockFile "file-2.hs" [ ContentText (Position "test" 6) "qux" , ContentMacro (Position "test" 7) " " "macro-b" ] ] $expect $ equalTangle True [] blocks "file-1.hs" "" $expect $ equalTangle True [] blocks "file-2.hs" "#line 0 \"test\"\n\ \foo\n\ \bar\n\ \\n\ \#line 3 \"test\"\n\ \baz\n\ \\n\ \#line 0 \"test2\"\n\ \ macro-1\n\ \\n\ \#line 2 \"test2\"\n\ \ macro-2\n\ \\n\ \#line 4 \"test2\"\n\ \\n\ \#line 6 \"test2\"\n\ \ macro-3\n\ \\n\ \#line 6 \"test\"\n\ \qux\n\ \\n\ \#line 6 \"test2\"\n\ \ macro-3\n" $expect $ equalTangle False [] blocks "file-1.hs" "" $expect $ equalTangle False [] blocks "file-2.hs" "foo\n\ \bar\n\ \\n\ \baz\n\ \\n\ \ macro-1\n\ \\n\ \ macro-2\n\ \\n\ \\n\ \ macro-3\n\ \\n\ \qux\n\ \\n\ \ macro-3\n" -- test custom #line formatting $expect $ equalTangle True [("anansi.line-pragma-hs", "#line ${line}")] blocks "file-2.hs" "#line 0\n\ \foo\n\ \bar\n\ \\n\ \#line 3\n\ \baz\n\ \\n\ \#line 0\n\ \ macro-1\n\ \\n\ \#line 2\n\ \ macro-2\n\ \\n\ \#line 4\n\ \\n\ \#line 6\n\ \ macro-3\n\ \\n\ \#line 6\n\ \qux\n\ \\n\ \#line 6\n\ \ macro-3\n" equalTangle :: Bool -> [(Text, Text)] -> [Block] -> Text -> ByteString -> Assertion equalTangle enableLinePragma opts blocks filename expected = equalLines expected (let doc = Document blocks (Map.fromList opts) Nothing in (case Map.lookup filename (runTangle enableLinePragma doc) of Nothing -> "" Just txt -> txt)) runTangle :: Bool -> Document -> Map Text ByteString runTangle enableLinePragma doc = State.execState st Map.empty where st = tangle putFile enableLinePragma doc putFile path txt = State.modify $ Map.insert (Text.pack (Path.encodeString Path.posix path)) txt test_Weave :: Suite test_Weave = suite "weave" [ test_WeaveDebug , test_WeaveHtml , test_WeaveLatex , test_WeaveMarkdown , test_WeaveNoweb , test_ParseLoomOptions ] test_WeaveDebug :: Suite test_WeaveDebug = assertions "debug" $ do $expect $ equalWeave loomDebug Map.empty [] "\n\ \weaving\n\ \==========================\n" $expect $ equalWeave loomDebug Map.empty [ BlockText "foo" , BlockText "bar" , BlockFile "file-1.hs" [] , BlockFile "file-2.hs" [ ContentText (Position "test" 0) "foo" , ContentMacro (Position "test" 0) " " "bar" ] ] "\n\ \weaving\n\ \==========================\n\ \BlockText \"foo\"\n\ \BlockText \"bar\"\n\ \BlockFile \"file-1.hs\" []\n\ \BlockFile \"file-2.hs\"\ \ [ContentText\ \ (Position {positionFile = FilePath \"test\", positionLine = 0})\ \ \"foo\",\ \ContentMacro\ \ (Position {positionFile = FilePath \"test\", positionLine = 0})\ \ \" \" \"bar\"]\n" test_WeaveHtml :: Suite test_WeaveHtml = assertions "html" $ do $expect $ equalWeave loomHTML Map.empty [] "" $expect $ equalWeave loomHTML Map.empty [ BlockText "foo" , BlockText " < & \" ' > " , BlockText "bar\n" , BlockFile "file-1.hs" [] , BlockDefine "macro < & \" ' > 2" [ ContentText (Position "test" 0) "\tfoo" ] , BlockFile "file-2.hs" [ ContentText (Position "test" 0) "foo < & \" ' > bar" , ContentMacro (Position "test" 0) " " "bar" ] ] "foo < & \" ' > bar\n\ \<pre><b>&#xBB; file-1.hs</b>\n\ \</pre><pre><b>&#xAB;macro &lt; &amp; &quot; &apos; &gt; 2&#xBB;</b>\n\ \ foo\n\ \</pre><pre><b>&#xBB; file-2.hs</b>\n\ \foo &lt; &amp; &quot; &apos; &gt; bar\n\ \ <i>&#xAB;bar&#xBB;</i>\n\ \</pre>\n" test_WeaveLatex :: Suite test_WeaveLatex = assertions "latex" $ do $expect $ equalWeave loomLaTeX Map.empty [] "" $expect $ equalWeave loomLaTeX Map.empty [ BlockText "foo" , BlockText " { \\ _ } " , BlockText "bar\n" , BlockFile "file-1.hs" [] , BlockDefine "macro { \\ _ } 2" [ ContentText (Position "test" 0) "\tfoo" ] , BlockFile "file-2.hs" [ ContentText (Position "test" 0) "foo { \\ _ } bar" , ContentMacro (Position "test" 0) " " "bar" ] ] "foo { \\ _ } bar\n\ \\\begin{alltt}\n\ \{\\bf\\(\\gg\\) file-1.hs}\n\ \\\end{alltt}\n\ \\\begin{alltt}\n\ \{\\bf\\(\\ll\\)macro \\{ \\textbackslash{} \\_ \\} 2\\(\\gg\\)}\n\ \ foo\n\ \\\end{alltt}\n\ \\\begin{alltt}\n\ \{\\bf\\(\\gg\\) file-2.hs}\n\ \foo \\{ \\textbackslash{} \\_ \\} bar\n\ \ |\\emph{bar}|\n\ \\\end{alltt}\n" test_WeaveMarkdown :: Suite test_WeaveMarkdown = assertions "markdown" $ do $expect $ equalWeave loomMarkdown Map.empty [] "" $expect $ equalWeave loomMarkdown Map.empty [ BlockText "foo" , BlockText " _ * \\ & ` []() " , BlockText "bar\n" , BlockFile "file-1.hs" [] , BlockDefine "macro _ * \\ & ` []() 2" [ ContentText (Position "test" 0) "\tfoo" ] , BlockFile "file-2.hs" [ ContentText (Position "test" 0) "foo _ * \\ & ` []() bar" , ContentMacro (Position "test" 0) " " "macro _ * \\ & ` []()" ] ] "foo _ * \\ & ` []() bar\n\ \\n\ \> **\xC2\xBB file-1.hs**\n\ \\n\ \\n\ \\n\ \> **\xC2\xAB\&macro \\_ \\* \\\\ &amp; \\` \\[\\]() 2\xC2\xBB**\n\ \\n\ \> foo\n\ \\n\ \\n\ \> **\xC2\xBB file-2.hs**\n\ \\n\ \> foo _ * \\ & ` []() bar\n\ \> \xC2\xAB\&macro _ * \\ & ` []()\xC2\xBB\n\ \\n" test_WeaveNoweb :: Suite test_WeaveNoweb = assertions "noweb" $ do $expect $ equalWeave loomNoWeb Map.empty [] "" $expect $ equalWeave loomNoWeb Map.empty [ BlockText "foo" , BlockText " { < \t \\ _ $ > } " , BlockText "bar\n" , BlockFile "file-1.hs" [] , BlockDefine "macro { < \t \\ _ $ > } 2" [ ContentText (Position "test" 0) "\tfoo" ] , BlockFile "file-2.hs" [ ContentText (Position "test" 0) "foo { \t \\ _ } bar" , ContentMacro (Position "test" 0) " " "bar" ] ] "foo { < \t \\ _ $ > } bar\n\ \\\nwbegincode{0}\\moddef{file-1.hs}\\endmoddef\\nwstartdeflinemarkup\\nwenddeflinemarkup\n\ \\\nwendcode{}\n\ \\\nwbegincode{0}\ \\\moddef{macro \\{ {$<$} \\\\ \\_ \\$ {$>$} \\} 2}\\endmoddef\ \\\nwstartdeflinemarkup\\nwenddeflinemarkup\n\ \ foo\n\ \\\nwendcode{}\n\ \\\nwbegincode{0}\\moddef{file-2.hs}\\endmoddef\ \\\nwstartdeflinemarkup\\nwenddeflinemarkup\n\ \foo \\{ \\\\ \\_ \\} bar\n\ \ \\LA{}bar\\RA{}\n\ \\\nwendcode{}\n" equalWeave :: Loom -> Map.Map Text Text -> [Block] -> ByteString -> Assertion equalWeave loom opts blocks expected = equalLines expected (weave loom doc) where doc = Document { documentBlocks = blocks , documentOptions = opts , documentLoomName = Nothing } test_ParseLoomOptions :: Suite test_ParseLoomOptions = assertions "parseLoomOptions" $ do $expect $ equal (parseLoomOptions Map.empty) (LoomOptions { loomOptionTabSize = 8 }) $expect $ equal (parseLoomOptions (Map.fromList [("tab-size", "4")])) (LoomOptions { loomOptionTabSize = 4 })
jmillikin/anansi
tests/Tests.hs
gpl-3.0
12,999
278
20
2,669
3,308
1,692
1,616
286
2
module LinkUp where import Control.Monad import Data.List import qualified Data.Vector as V import System.Random type Pattern = Int data Block = Empty | Pattern Pattern type Size = (Int, Int) instance Show Block where show Empty = " " show (Pattern p) = show p type Board = V.Vector (V.Vector Block) printBoard :: Board -> IO () printBoard board = forM_ board $ \row -> do putStrLn $ printBoardRow row where printBoardRow row = intercalate " " $ map show (V.toList row) randomizeBoard :: Size -> IO Board randomizeBoard (rowSize, colSize) = replicateM rowSize randomizeRow >>= return . V.fromList where randomizeRow = replicateM colSize (randomRIO (0, 9) >>= return . numToBlock) >>= return . V.fromList numToBlock 0 = Empty numToBlock p = Pattern p main :: IO () main = do board <- randomizeBoard (8, 10) printBoard board
KenetJervet/mapensee
haskell/problems/LinkUp.hs
gpl-3.0
899
0
14
214
322
168
154
26
2
{-# LANGUAGE NoImplicitPrelude, DeriveFunctor, FlexibleInstances, GeneralizedNewtypeDeriving, MultiParamTypeClasses, BangPatterns, RecordWildCards, TypeFamilies #-} module Lamdu.Infer.Internal.Monad ( Results(..), subst, constraints, emptyResults , Context(..), ctxResults, ctxState, initialContext , InferState(..) , InferCtx(..), inferCtx , Infer , throwError , tell, tellSubst , tellProductConstraint , tellSumConstraint , tellConstraints , listen, listenNoTell , getConstraints, getSubst , listenSubst , getSkolems, addSkolems , narrowTVScope, getSkolemsInScope , CompositeHasVar, VarKind , freshInferredVar, freshInferredVarName ) where import Prelude.Compat import Control.Lens (Lens') import qualified Control.Lens as Lens import Control.Lens.Operators import Control.Lens.Tuple import Control.Monad (liftM) import Control.Monad.Trans.State (StateT(..)) import qualified Control.Monad.Trans.State as State import Data.Map (Map) import qualified Data.Map as Map import Data.Monoid ((<>)) import qualified Data.Set as Set import Data.String (IsString(..)) import Lamdu.Expr.Constraints (Constraints(..), CompositeVarConstraints(..)) import qualified Lamdu.Expr.Constraints as Constraints import Lamdu.Expr.Type (Type) import qualified Lamdu.Expr.Type as T import qualified Lamdu.Expr.TypeVars as TV import Lamdu.Infer.Error (Error) import qualified Lamdu.Infer.Error as Err import qualified Lamdu.Infer.Internal.Constraints as Constraints import Lamdu.Infer.Internal.Scope (SkolemScope) import qualified Lamdu.Infer.Internal.Scope as Scope import Lamdu.Infer.Internal.Subst (Subst) import qualified Lamdu.Infer.Internal.Subst as Subst data SkolemsInScope = SkolemsInScope { _sisTVs :: Map T.TypeVar SkolemScope , _sisRTVs :: Map T.ProductVar SkolemScope , _sisSTVs :: Map T.SumVar SkolemScope } instance Monoid SkolemsInScope where mempty = SkolemsInScope mempty mempty mempty mappend (SkolemsInScope tvs0 rtvs0 stvs0) (SkolemsInScope tvs1 rtvs1 stvs1) = SkolemsInScope (tvs0 <> tvs1) (rtvs0 <> rtvs1) (stvs0 <> stvs1) sisTVs :: Lens' SkolemsInScope (Map T.TypeVar SkolemScope) sisTVs f SkolemsInScope {..} = f _sisTVs <&> \_sisTVs -> SkolemsInScope {..} {-# INLINE sisTVs #-} sisRTVs :: Lens' SkolemsInScope (Map T.ProductVar SkolemScope) sisRTVs f SkolemsInScope {..} = f _sisRTVs <&> \_sisRTVs -> SkolemsInScope {..} {-# INLINE sisRTVs #-} sisSTVs :: Lens' SkolemsInScope (Map T.SumVar SkolemScope) sisSTVs f SkolemsInScope {..} = f _sisSTVs <&> \_sisSTVs -> SkolemsInScope {..} {-# INLINE sisSTVs #-} class Subst.CompositeHasVar p => CompositeHasVar p where compositeSkolemsInScopeMap :: Lens' SkolemsInScope (Map (T.Var (T.Composite p)) SkolemScope) instance CompositeHasVar T.ProductTag where compositeSkolemsInScopeMap = sisRTVs {-# INLINE compositeSkolemsInScopeMap #-} instance CompositeHasVar T.SumTag where compositeSkolemsInScopeMap = sisSTVs {-# INLINE compositeSkolemsInScopeMap #-} class Subst.HasVar t => VarKind t where skolemsInScopeMap :: Lens' SkolemsInScope (Map (T.Var t) SkolemScope) instance VarKind Type where skolemsInScopeMap = sisTVs {-# INLINE skolemsInScopeMap #-} instance CompositeHasVar p => VarKind (T.Composite p) where skolemsInScopeMap = compositeSkolemsInScopeMap {-# INLINE skolemsInScopeMap #-} data InferState = InferState { _inferSupply :: {-# UNPACK #-}!Int , _inferSkolems :: {-# UNPACK #-}!TV.TypeVars , _inferSkolemConstraints :: {-# UNPACK #-}!Constraints , _inferSkolemsInScope :: {-# UNPACK #-}!SkolemsInScope } inferSupply :: Lens' InferState Int inferSupply f InferState {..} = f _inferSupply <&> \_inferSupply -> InferState {..} {-# INLINE inferSupply #-} inferSkolems :: Lens' InferState TV.TypeVars inferSkolems f InferState {..} = f _inferSkolems <&> \_inferSkolems -> InferState {..} {-# INLINE inferSkolems #-} inferSkolemConstraints :: Lens' InferState Constraints inferSkolemConstraints f InferState {..} = f _inferSkolemConstraints <&> \_inferSkolemConstraints -> InferState {..} {-# INLINE inferSkolemConstraints #-} inferSkolemsInScope :: Lens' InferState SkolemsInScope inferSkolemsInScope f InferState {..} = f _inferSkolemsInScope <&> \_inferSkolemsInScope -> InferState {..} {-# INLINE inferSkolemsInScope #-} data Results = Results { _subst :: {-# UNPACK #-} !Subst , _constraints :: !Constraints } subst :: Lens' Results Subst subst f Results {..} = f _subst <&> \_subst -> Results {..} {-# INLINE subst #-} constraints :: Lens' Results Constraints constraints f Results {..} = f _constraints <&> \_constraints -> Results {..} {-# INLINE constraints #-} emptyResults :: Results emptyResults = Results mempty mempty {-# INLINE emptyResults #-} verifySkolemConstraints :: InferState -> Constraints -> Either Error () verifySkolemConstraints state newConstraints | Constraints.null unexpectedConstraints = Right () | otherwise = Left $ Err.UnexpectedSkolemConstraint unexpectedConstraints where unexpectedConstraints = Constraints.intersect (_inferSkolems state) newConstraints `Constraints.difference` _inferSkolemConstraints state {-# INLINE verifySkolemConstraints #-} appendResults :: Context -> Results -> Either Error Results appendResults (Context (Results s0 c0) state) (Results s1 c1) = do (newC, c0') <- Constraints.applySubst s1 c0 -- TODO: c1 is usually empty, but c0' will contain ALL of c0, -- even though we're only interested in the NEW constraints -- that come from applySubst. Change applySubst to return a -- set of NEW constraints separately from the SUBST -- constraints and only verify skolem constraints against the -- new ones. verifySkolemConstraints state (newC <> c1) return $ Results (s0 <> s1) (c0' <> c1) {-# INLINE appendResults #-} data Context = Context { _ctxResults :: {-# UNPACK #-} !Results , _ctxState :: {-# UNPACK #-} !InferState } ctxResults :: Lens' Context Results ctxResults f Context {..} = f _ctxResults <&> \_ctxResults -> Context {..} {-# INLINE ctxResults #-} ctxState :: Lens' Context InferState ctxState f Context {..} = f _ctxState <&> \_ctxState -> Context {..} {-# INLINE ctxState #-} initialContext :: Context initialContext = Context { _ctxResults = emptyResults , _ctxState = InferState { _inferSupply = 0 , _inferSkolems = mempty , _inferSkolemConstraints = mempty , _inferSkolemsInScope = mempty } } -- We use StateT, but it is composed of an actual stateful fresh -- supply and a component used as a writer avoiding the -- associativity/performance issues of WriterT newtype InferCtx m a = Infer { run :: StateT Context m a } deriving (Functor, Applicative, Monad) inferCtx :: Lens.Iso (InferCtx m a) (InferCtx n b) (StateT Context m a) (StateT Context n b) inferCtx = Lens.iso run Infer type Infer = InferCtx (Either Error) throwError :: Error -> Infer a throwError = Infer . StateT . const . Left {-# INLINE throwError #-} getSkolems :: Monad m => InferCtx m TV.TypeVars getSkolems = Infer $ Lens.use (ctxState . inferSkolems) {-# INLINE getSkolems #-} addSkolems :: Monad m => TV.TypeVars -> Constraints -> InferCtx m () addSkolems skolems skolemConstraints = Infer $ Lens.zoom ctxState $ do inferSkolems <>= skolems inferSkolemConstraints <>= skolemConstraints {-# INLINE addSkolems #-} tell :: Results -> Infer () tell w = Infer $ StateT $ \c -> do !newRes <- appendResults c w Right ((), c { _ctxResults = newRes} ) {-# INLINE tell #-} tellSubst :: Subst.HasVar t => T.Var t -> t -> Infer () tellSubst v t = tell $ emptyResults { _subst = Subst.new v t } {-# INLINE tellSubst #-} tellConstraints :: Constraints -> Infer () tellConstraints x = tell $ emptyResults { _constraints = x } {-# INLINE tellConstraints #-} tellProductConstraint :: T.ProductVar -> T.Tag -> Infer () tellProductConstraint v tag = tellConstraints $ mempty { productVarConstraints = CompositeVarConstraints $ Map.singleton v $ Set.singleton tag } {-# INLINE tellProductConstraint #-} tellSumConstraint :: T.SumVar -> T.Tag -> Infer () tellSumConstraint v tag = tellConstraints $ mempty { sumVarConstraints = CompositeVarConstraints $ Map.singleton v $ Set.singleton tag } {-# INLINE tellSumConstraint #-} listen :: Infer a -> Infer (a, Results) listen (Infer (StateT act)) = Infer $ StateT $ \c0 -> do (y, c1) <- act c0 { _ctxResults = emptyResults } !w <- appendResults c0 (_ctxResults c1) Right ((y, _ctxResults c1), c1 { _ctxResults = w} ) {-# INLINE listen #-} -- Duplicate of listen because building one on top of the other has a -- large (~15%) performance penalty. listenNoTell :: Monad m => InferCtx m a -> InferCtx m (a, Results) listenNoTell (Infer (StateT act)) = Infer $ StateT $ \c0 -> do (y, c1) <- act c0 { _ctxResults = emptyResults } return ((y, _ctxResults c1), c1 { _ctxResults = _ctxResults c0} ) {-# INLINE listenNoTell #-} nextInt :: Monad m => StateT Int m Int nextInt = do old <- State.get id += 1 return old {-# INLINE nextInt #-} freshInferredVarName :: (VarKind t, Monad m) => SkolemScope -> String -> InferCtx m (T.Var t) freshInferredVarName skolemScope prefix = do oldSupply <- Lens.zoom inferSupply nextInt let varName = fromString $ prefix ++ show oldSupply inferSkolemsInScope . skolemsInScopeMap . Lens.at varName ?= skolemScope return varName & Lens.zoom ctxState & Infer {-# INLINE freshInferredVarName #-} getSkolemsInScope :: (Monad m, VarKind t) => T.Var t -> InferCtx m SkolemScope getSkolemsInScope varName = Lens.use (ctxState . inferSkolemsInScope . skolemsInScopeMap . Lens.at varName . Lens._Just) & Infer {-# INLINE getSkolemsInScope #-} narrowTVScope :: (Monad m, VarKind t) => SkolemScope -> T.Var t -> InferCtx m () narrowTVScope skolems varName = ctxState . inferSkolemsInScope . skolemsInScopeMap . Lens.at varName . Lens._Just . Scope.skolemScopeVars %= TV.intersection (skolems ^. Scope.skolemScopeVars) & Infer {-# INLINE narrowTVScope #-} freshInferredVar :: Monad m => VarKind t => SkolemScope -> String -> InferCtx m t freshInferredVar skolemScope = liftM TV.lift . freshInferredVarName skolemScope {-# INLINE freshInferredVar #-} listenSubst :: Infer a -> Infer (a, Subst) listenSubst x = listen x <&> _2 %~ _subst {-# INLINE listenSubst #-} getConstraints :: Monad m => InferCtx m Constraints getConstraints = Infer $ State.gets (_constraints . _ctxResults) {-# INLINE getConstraints #-} getSubst :: Monad m => InferCtx m Subst getSubst = Infer $ State.gets (_subst . _ctxResults) {-# INLINE getSubst #-}
da-x/Algorithm-W-Step-By-Step
Lamdu/Infer/Internal/Monad.hs
gpl-3.0
11,112
0
14
2,261
2,890
1,562
1,328
-1
-1
{-| Module : Types Description : Photobooth Core Types Copyright : (c) Chris Tetreault, 2014 License : GPL-3 Stability : experimental -} module DMP.Photobooth.Core.Types where import DMP.Photobooth.Module.Types import Control.Monad.State import Control.Concurrent.STM import Control.Monad.Trans.Maybe {-| An atomic, threadsafe, queue to push log entries into -} type LogQueue = TQueue LogEntry {-| The core stores the module configs and states between module monad invocations. This type is used to store this data -} data ModuleStorage a = ModuleStorage {modState :: Maybe (TVar a), -- ^ The state of a module. Since this is -- a threaded program, the states are protected using STM. modConfig :: Configuration -- ^ The configuration of a module } {-| The state of the Core. Stores all module configs and states -} data CoreState cas ins pes phs prs trs = CoreState {csLogQueue :: LogQueue, csCamera :: ModuleStorage cas, csInterface :: ModuleStorage ins, csPersistence :: ModuleStorage pes, csPhotostrip :: ModuleStorage phs, csPrinter :: ModuleStorage prs, csTrigger :: ModuleStorage trs}
christetreault/dmp-photo-booth-prime
DMP/Photobooth/Core/Types.hs
gpl-3.0
1,186
0
11
256
156
99
57
19
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Language.Documents.AnalyzeSentiment -- 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) -- -- Analyzes the sentiment of the provided text. -- -- /See:/ <https://cloud.google.com/natural-language/ Cloud Natural Language API Reference> for @language.documents.analyzeSentiment@. module Network.Google.Resource.Language.Documents.AnalyzeSentiment ( -- * REST Resource DocumentsAnalyzeSentimentResource -- * Creating a Request , documentsAnalyzeSentiment , DocumentsAnalyzeSentiment -- * Request Lenses , dasXgafv , dasUploadProtocol , dasAccessToken , dasUploadType , dasPayload , dasCallback ) where import Network.Google.Language.Types import Network.Google.Prelude -- | A resource alias for @language.documents.analyzeSentiment@ method which the -- 'DocumentsAnalyzeSentiment' request conforms to. type DocumentsAnalyzeSentimentResource = "v1" :> "documents:analyzeSentiment" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] AnalyzeSentimentRequest :> Post '[JSON] AnalyzeSentimentResponse -- | Analyzes the sentiment of the provided text. -- -- /See:/ 'documentsAnalyzeSentiment' smart constructor. data DocumentsAnalyzeSentiment = DocumentsAnalyzeSentiment' { _dasXgafv :: !(Maybe Xgafv) , _dasUploadProtocol :: !(Maybe Text) , _dasAccessToken :: !(Maybe Text) , _dasUploadType :: !(Maybe Text) , _dasPayload :: !AnalyzeSentimentRequest , _dasCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'DocumentsAnalyzeSentiment' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dasXgafv' -- -- * 'dasUploadProtocol' -- -- * 'dasAccessToken' -- -- * 'dasUploadType' -- -- * 'dasPayload' -- -- * 'dasCallback' documentsAnalyzeSentiment :: AnalyzeSentimentRequest -- ^ 'dasPayload' -> DocumentsAnalyzeSentiment documentsAnalyzeSentiment pDasPayload_ = DocumentsAnalyzeSentiment' { _dasXgafv = Nothing , _dasUploadProtocol = Nothing , _dasAccessToken = Nothing , _dasUploadType = Nothing , _dasPayload = pDasPayload_ , _dasCallback = Nothing } -- | V1 error format. dasXgafv :: Lens' DocumentsAnalyzeSentiment (Maybe Xgafv) dasXgafv = lens _dasXgafv (\ s a -> s{_dasXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). dasUploadProtocol :: Lens' DocumentsAnalyzeSentiment (Maybe Text) dasUploadProtocol = lens _dasUploadProtocol (\ s a -> s{_dasUploadProtocol = a}) -- | OAuth access token. dasAccessToken :: Lens' DocumentsAnalyzeSentiment (Maybe Text) dasAccessToken = lens _dasAccessToken (\ s a -> s{_dasAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). dasUploadType :: Lens' DocumentsAnalyzeSentiment (Maybe Text) dasUploadType = lens _dasUploadType (\ s a -> s{_dasUploadType = a}) -- | Multipart request metadata. dasPayload :: Lens' DocumentsAnalyzeSentiment AnalyzeSentimentRequest dasPayload = lens _dasPayload (\ s a -> s{_dasPayload = a}) -- | JSONP dasCallback :: Lens' DocumentsAnalyzeSentiment (Maybe Text) dasCallback = lens _dasCallback (\ s a -> s{_dasCallback = a}) instance GoogleRequest DocumentsAnalyzeSentiment where type Rs DocumentsAnalyzeSentiment = AnalyzeSentimentResponse type Scopes DocumentsAnalyzeSentiment = '["https://www.googleapis.com/auth/cloud-language", "https://www.googleapis.com/auth/cloud-platform"] requestClient DocumentsAnalyzeSentiment'{..} = go _dasXgafv _dasUploadProtocol _dasAccessToken _dasUploadType _dasCallback (Just AltJSON) _dasPayload languageService where go = buildClient (Proxy :: Proxy DocumentsAnalyzeSentimentResource) mempty
brendanhay/gogol
gogol-language/gen/Network/Google/Resource/Language/Documents/AnalyzeSentiment.hs
mpl-2.0
4,961
0
16
1,110
706
412
294
105
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.DataPipeline.AddTags -- 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. -- | Add or modify tags in an existing pipeline. -- -- <http://docs.aws.amazon.com/datapipeline/latest/APIReference/API_AddTags.html> module Network.AWS.DataPipeline.AddTags ( -- * Request AddTags -- ** Request constructor , addTags -- ** Request lenses , atPipelineId , atTags -- * Response , AddTagsResponse -- ** Response constructor , addTagsResponse ) where import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.DataPipeline.Types import qualified GHC.Exts data AddTags = AddTags { _atPipelineId :: Text , _atTags :: List "tags" Tag } deriving (Eq, Read, Show) -- | 'AddTags' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'atPipelineId' @::@ 'Text' -- -- * 'atTags' @::@ ['Tag'] -- addTags :: Text -- ^ 'atPipelineId' -> AddTags addTags p1 = AddTags { _atPipelineId = p1 , _atTags = mempty } -- | The identifier of the pipeline to which you want to add the tags. atPipelineId :: Lens' AddTags Text atPipelineId = lens _atPipelineId (\s a -> s { _atPipelineId = a }) -- | The tags as key/value pairs to add to the pipeline. atTags :: Lens' AddTags [Tag] atTags = lens _atTags (\s a -> s { _atTags = a }) . _List data AddTagsResponse = AddTagsResponse deriving (Eq, Ord, Read, Show, Generic) -- | 'AddTagsResponse' constructor. addTagsResponse :: AddTagsResponse addTagsResponse = AddTagsResponse instance ToPath AddTags where toPath = const "/" instance ToQuery AddTags where toQuery = const mempty instance ToHeaders AddTags instance ToJSON AddTags where toJSON AddTags{..} = object [ "pipelineId" .= _atPipelineId , "tags" .= _atTags ] instance AWSRequest AddTags where type Sv AddTags = DataPipeline type Rs AddTags = AddTagsResponse request = post "AddTags" response = nullResponse AddTagsResponse
dysinger/amazonka
amazonka-datapipeline/gen/Network/AWS/DataPipeline/AddTags.hs
mpl-2.0
2,975
0
10
726
410
248
162
53
1
module Git.Command.Notes (run) where run :: [String] -> IO () run args = return ()
wereHamster/yag
Git/Command/Notes.hs
unlicense
83
0
7
15
42
23
19
3
1
{-# LANGUAGE CPP #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE TypeOperators #-} module Pos.Util.Jsend ( -- * JSend data types and functions ResponseStatus(..) , HasDiagnostic(..) , noDiagnosticKey -- * Generic parsing and rendering helpers. , jsendErrorGenericToJSON , jsendErrorGenericParseJSON , gconsNames , gconsName ) where import Universum hiding (All, Generic) import Control.Lens ((?~)) import Data.Aeson (GFromJSON, Object, ToJSON, Value (..), Zero, genericParseJSON, object, tagSingleConstructors, withObject, (.:), (.=)) import Data.Aeson.TH import Data.Aeson.Types (Parser) import qualified Data.Char as Char import Data.List ((!!)) import Data.Swagger import qualified Formatting.Buildable import GHC.Generics import Test.QuickCheck (Arbitrary (..), elements) import qualified Data.Aeson as Aeson import qualified Data.HashMap.Lazy as HM import qualified Generics.SOP as SOP class HasDiagnostic a where getDiagnosticKey :: a -> Text -- -- Misc -- -- | Get the ADT constructor's name of the given value gconsName :: forall a. (SOP.Generic a, SOP.HasDatatypeInfo a) => a -> Text gconsName a = gconsNames (Proxy @a) !! SOP.hindex (SOP.from a) -- | Get all constructors names available of an ADT gconsNames :: forall a. (SOP.HasDatatypeInfo a, SOP.SListI (SOP.Code a)) => Proxy a -> [Text] gconsNames = map toText . SOP.hcollapse . SOP.hliftA (SOP.K . SOP.constructorName) . gconsInfos -- -- JSendError Encoding helper -- jsendErrorGenericToJSON :: ( GDiagnosticToJSON (Rep a) , HasDiagnostic a , Generic a , SOP.Generic a , SOP.HasDatatypeInfo a ) => a -> Value jsendErrorGenericToJSON a = object [ "message" .= gconsName a , "status" .= ErrorStatus , "diagnostic" .= gDiagnosticToJSON (getDiagnosticKey a) (from a) ] jsendErrorGenericParseJSON :: ( Generic a , GFromJSON Zero (Rep a) ) => Value -> Parser a jsendErrorGenericParseJSON = withObject "JSEndError" $ \o -> do message <- o .: "message" diagnostic <- o .: "diagnostic" >>= parseDiagnostic genericParseJSON opts $ object [ "tag" .= String message , "contents" .= diagnostic ] where opts :: Aeson.Options opts = Aeson.defaultOptions { tagSingleConstructors = True } parseDiagnostic :: Object -> Parser Value parseDiagnostic hm = case HM.toList hm of [] -> pure (object mempty) [(_, value)] -> pure value _ -> fail "Invalid ToJSON encoding for JSEndError" -- -- INTERNALS -- gconsInfos :: forall a. (SOP.HasDatatypeInfo a) => Proxy a -> SOP.NP SOP.ConstructorInfo (SOP.Code a) gconsInfos pa = case SOP.datatypeInfo pa of SOP.Newtype _ _ conInfo -> conInfo SOP.:* SOP.Nil #if MIN_VERSION_generics_sop(5,0,0) SOP.ADT _ _ consInfo _ -> consInfo #else SOP.ADT _ _ consInfo -> consInfo #endif -- | This class helps us define generically errors JSON instances without -- relying on partial field in records. -- This is used to encode the diagnostic object of an error, as a singleton -- with field 'Text' whenever there's one. -- -- NOTE: We haven't defined instances for everything because we do not want to -- suppport all kind of error structures, but only sums with a unary or -- nullary constructors. class GDiagnosticToJSON (f :: * -> *) where gDiagnosticToJSON :: Text -> f a -> Value instance (GDiagnosticToJSON f) => GDiagnosticToJSON (M1 i c f) where gDiagnosticToJSON k (M1 f) = gDiagnosticToJSON k f instance (GDiagnosticToJSON f, GDiagnosticToJSON g) => GDiagnosticToJSON (f :+: g) where gDiagnosticToJSON k (L1 f) = gDiagnosticToJSON k f gDiagnosticToJSON k (R1 g) = gDiagnosticToJSON k g instance (ToJSON c) => GDiagnosticToJSON (K1 i c) where gDiagnosticToJSON k (K1 c) = object [ k .= c ] instance GDiagnosticToJSON U1 where gDiagnosticToJSON _ _ = object mempty data ResponseStatus = SuccessStatus | ErrorStatus deriving (Show, Eq, Ord, Enum, Bounded) deriveJSON defaultOptions { Data.Aeson.TH.constructorTagModifier = map Char.toLower . reverse . drop 6 . reverse } ''ResponseStatus noDiagnosticKey :: Text noDiagnosticKey = error "Contructor has declared no diagnostic key but apparently requires one! Have a look at HasDiagnostic instances!" instance Arbitrary ResponseStatus where arbitrary = elements [minBound .. maxBound] instance ToSchema ResponseStatus where declareNamedSchema _ = do pure $ NamedSchema (Just "ResponseStatus") $ mempty & type_ ?~ SwaggerString & enum_ .~ Just ["success", "fail", "error"] instance Buildable ResponseStatus where build SuccessStatus = "success" build ErrorStatus = "error"
input-output-hk/cardano-sl
lib/src/Pos/Util/Jsend.hs
apache-2.0
4,941
0
16
1,186
1,240
677
563
-1
-1
-- -- Copyright 2017 Andrew Dawson -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- module Truncate.Test.Truncatable.Convert (suite) where ------------------------------------------------------------------------ import Test.Framework ( Test , testGroup ) import Test.Framework.Providers.QuickCheck2 (testProperty) ------------------------------------------------------------------------ import Data.Word ( Word32 , Word64 ) ------------------------------------------------------------------------ import Truncate ------------------------------------------------------------------------ suite :: Test suite = testGroup "Truncatable convert" [ testProperty "Convert Bin32 -> Dec32" prop_roundTripBin32Dec32 , testProperty "Convert Bin32 -> Hex32" prop_roundTripBin32Hex32 , testProperty "Convert Dec32 -> Bin32" prop_roundTripDec32Bin32 , testProperty "Convert Dec32 -> Hex32" prop_roundTripDec32Hex32 , testProperty "Convert Hex32 -> Bin32" prop_roundTripHex32Bin32 , testProperty "Convert Hex32 -> Dec32" prop_roundTripHex32Dec32 , testProperty "Convert Bin64 -> Dec64" prop_roundTripBin64Dec64 , testProperty "Convert Bin64 -> Hex64" prop_roundTripBin64Hex64 , testProperty "Convert Dec64 -> Bin64" prop_roundTripDec64Bin64 , testProperty "Convert Dec64 -> Hex64" prop_roundTripDec64Hex64 , testProperty "Convert Hex64 -> Bin64" prop_roundTripHex64Bin64 , testProperty "Convert Hex64 -> Dec64" prop_roundTripHex64Dec64 ] ------------------------------------------------------------------------ -- 32-bit tests prop_roundTripBin32Dec32 :: Word32 -> Bool prop_roundTripBin32Dec32 b = (toBin . toDec) bin == bin where bin = fromBits (WordF32 b) :: Binary prop_roundTripBin32Hex32 :: Word32 -> Bool prop_roundTripBin32Hex32 b = (toBin . toHex) bin == bin where bin = fromBits (WordF32 b) :: Binary prop_roundTripDec32Bin32 :: Word32 -> Bool prop_roundTripDec32Bin32 b = case isNaN' dec of True -> isNaN' roundTrip False -> roundTrip == dec where dec = fromBits (WordF32 b) :: Decimal roundTrip = toDec . toBin $ dec prop_roundTripDec32Hex32 :: Word32 -> Bool prop_roundTripDec32Hex32 b = case isNaN' dec of True -> isNaN' roundTrip False -> roundTrip == dec where dec = fromBits (WordF32 b) :: Decimal roundTrip = toDec . toHex $ dec prop_roundTripHex32Bin32 :: Word32 -> Bool prop_roundTripHex32Bin32 b = (toHex . toBin) hex == hex where hex = fromBits (WordF32 b) :: Hexadecimal prop_roundTripHex32Dec32 :: Word32 -> Bool prop_roundTripHex32Dec32 b = (toHex . toDec) hex == hex where hex = fromBits (WordF32 b) :: Hexadecimal ------------------------------------------------------------------------ -- 64-bit tests prop_roundTripBin64Dec64 :: Word64 -> Bool prop_roundTripBin64Dec64 b = (toBin . toDec) bin == bin where bin = fromBits (WordF64 b) :: Binary prop_roundTripBin64Hex64 :: Word64 -> Bool prop_roundTripBin64Hex64 b = (toBin . toHex) bin == bin where bin = fromBits (WordF64 b) :: Binary prop_roundTripDec64Bin64 :: Word64 -> Bool prop_roundTripDec64Bin64 b = case isNaN' dec of True -> isNaN' roundTrip False -> roundTrip == dec where dec = fromBits (WordF64 b) :: Decimal roundTrip = toDec . toBin $ dec prop_roundTripDec64Hex64 :: Word64 -> Bool prop_roundTripDec64Hex64 b = case isNaN' dec of True -> isNaN' roundTrip False -> roundTrip == dec where dec = fromBits (WordF64 b) :: Decimal roundTrip = toDec . toHex $ dec prop_roundTripHex64Bin64 :: Word64 -> Bool prop_roundTripHex64Bin64 b = (toHex . toBin) hex == hex where hex = fromBits (WordF64 b) :: Hexadecimal prop_roundTripHex64Dec64 :: Word64 -> Bool prop_roundTripHex64Dec64 b = (toHex . toDec) hex == hex where hex = fromBits (WordF64 b) :: Hexadecimal ------------------------------------------------------------------------ isNaN' :: Decimal -> Bool isNaN' (Dec32 v) = isNaN v isNaN' (Dec64 v) = isNaN v
aopp-pred/fp-truncate
test/Truncate/Test/Truncatable/Convert.hs
apache-2.0
4,979
0
9
1,253
932
496
436
72
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} module BarthPar.Scrape.Read where import Control.Applicative import Control.Arrow ((&&&)) import Control.Error import Control.Lens hiding ((|>)) import Control.Monad import Data.Bifunctor import Data.Bitraversable import Data.Char import Data.Foldable import qualified Data.List as L import Data.Sequence ((|>)) import qualified Data.Sequence as S import qualified Data.Text as T import Data.Text.Lazy.Builder import Data.Text.Read import Data.Tuple import Prelude hiding (div, span) import Text.Groom import Text.XML import Text.XML.Cursor hiding (forceM) import Text.XML.Lens (_Element) import BarthPar.Scrape.Types import BarthPar.Scrape.Utils import BarthPar.Scrape.XML import BarthPar.Utils hiding (paragraphs) makeChapter :: Title -> Title -> [Cursor] -> PureScript (Chapter ContentBlock) makeChapter vTitle title (h:a:cs) = do cloc <- first ("Error parsing volume ID: " ++) $ parseChapterLoc vTitle title let v = Header (_locVolume cloc) vTitle p' = _locPart cloc c = _locChapter cloc c' = Header c title abst <- pure . flip (ContentBlock v p' c' (Header 0 "Abstract") 0) "" . normalizeWrap . render . foldMap cleanText <$> forceList "Missing abstract" ( a' ^.. traverse . to node . _Element ) paragraphs <- readParagraphs v p' c' cs' return $ Chapter v p' abst c title paragraphs where (a', cs') = if length (h $/ span) == 1 then (a $| abstract, cs) else (h $// excursus, a:cs) makeChapter vTitle cTitle _ = Left $ "Not enough nodes on " ++ T.unpack cTitle ++ show vTitle type RPState = ( Int , Maybe (Int, Paragraph ContentBlock, S.Seq ContentBlock) , S.Seq (Paragraph ContentBlock) ) readParagraphs :: Header -> Int -> Header -> [Cursor] -> PureScript [Paragraph ContentBlock] readParagraphs v p' ch = fmap finis . foldM step (0, Nothing, S.empty) where step :: RPState -> Cursor -> PureScript RPState step (n, Nothing, ps) c | L.null (c $/ spanHead) = do let par = Paragraph v p' ch 0 "" [] return ( succ n , Just (0, par, S.empty) , ps ) | otherwise = do accum <- readParagraph v p' ch c return ( succ n , Just accum , ps ) step (n, Just (n', par, cbs), ps) c | L.null (c $/ spanHead) = do let ph = uncurry Header $ (_paragraphN &&& _paragraphTitle) par cb <- readContent v p' ch ph n' c return ( n , Just (succ n', par, cbs |> cb) , ps ) | otherwise = do accum <- readParagraph v p' ch c return ( succ n , Just accum , ps |> ( par & paragraphContent .~ toList (S.unstableSort cbs) ) ) finis :: RPState -> [Paragraph ContentBlock] finis (_, Nothing, _) = [] finis (_, Just (_, par, cbs), accum) = toList $ accum |> (par & paragraphContent .~ toList cbs) readParagraph :: Header -> Int -> Header -> Cursor -> PureScript (Int, Paragraph ContentBlock, S.Seq ContentBlock) readParagraph v p' ch c = do h <- headErr ( "Unable to find paragraph header: " ++ groom (node c) ) =<< mapM readHeader (c $/ spanHead) cb <- readContent v p' ch h 0 c return ( 1 , Paragraph v p' ch (_headerN h) (_headerTitle h) [] , S.singleton cb ) readContent :: Header -> Int -> Header -> Header -> Int -> Cursor -> PureScript ContentBlock readContent v p' ch ph n c = do let txt = normalizeWrap . render . foldMap cleanText $ (c $/ p ) ^.. traverse . to node . _Element excur = normalizeWrap . render . foldMap cleanExcursus $ (c $/ excursus) ^.. traverse . to node . _Element return $ ContentBlock v p' ch ph n txt excur -- | CD Volume I,1 (Β§Β§ 1-12) parseChapterLoc :: Title -> T.Text -> PureScript ChapterLoc parseChapterLoc vtitle pageName = cloc <$> ( bisequenceA . (fromRomanPS `bimap` (fmap fst . decimal . T.drop 1)) . T.break (== ',') . T.takeWhile (not . isSpace) $ T.drop 10 vtitle ) <*> parsePageName pageName where cloc (v, s) = ChapterLoc v s -- Β§ 1 The Task of Dogmatics. parsePageName :: T.Text -> PureScript Int parsePageName = fmap fst . decimal . T.drop 2 readHeader :: Cursor -> PureScript Header readHeader c = fmap (uncurry Header . swap) . sequenceA . ((normalize . T.drop 2) `bimap` anyNumberPS) . swap $ T.break (=='.') title where title = T.concat $ c $// content cleanText :: Element -> Builder cleanText = cleanWith $ \e -> not $ isCenter e || isNoteLink e cleanExcursus :: Element -> Builder cleanExcursus = cleanWith $ \e -> not $ isCenter e || isNoteLink e || isHiddenNote e cleanWith :: (Element -> Bool) -> Element -> Builder cleanWith f e = foldMap (buildText . NodeElement) (filterEl f e :: Maybe Element)
erochest/barth-scrape
src/BarthPar/Scrape/Read.hs
apache-2.0
5,994
0
18
2,328
1,815
945
870
-1
-1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QTextDocument.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:20 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QTextDocument ( QqTextDocument(..) ,addResource ,blockCount ,QcreateObject(..) ,defaultFont ,defaultStyleSheet ,defaultTextOption ,documentLayout ,qdrawContents ,findBlock ,frameAt ,idealWidth ,markContentsDirty ,maximumBlockCount ,metaInformation ,object ,objectForFormat ,qpageSize ,Qresource(..), Qresource_nf(..) ,rootFrame ,setDefaultFont ,setDefaultStyleSheet ,setDefaultTextOption ,setDocumentLayout ,setMaximumBlockCount ,setMetaInformation ,qsetPageSize ,qTextDocument_delete ,qTextDocument_deleteLater ) where import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Enums.Gui.QTextDocument 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 QuserMethod (QTextDocument ()) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QTextDocument_userMethod cobj_qobj (toCInt evid) foreign import ccall "qtc_QTextDocument_userMethod" qtc_QTextDocument_userMethod :: Ptr (TQTextDocument a) -> CInt -> IO () instance QuserMethod (QTextDocumentSc a) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QTextDocument_userMethod cobj_qobj (toCInt evid) instance QuserMethod (QTextDocument ()) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QTextDocument_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj foreign import ccall "qtc_QTextDocument_userMethodVariant" qtc_QTextDocument_userMethodVariant :: Ptr (TQTextDocument a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) instance QuserMethod (QTextDocumentSc a) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QTextDocument_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj class QqTextDocument x1 where qTextDocument :: x1 -> IO (QTextDocument ()) instance QqTextDocument (()) where qTextDocument () = withQTextDocumentResult $ qtc_QTextDocument foreign import ccall "qtc_QTextDocument" qtc_QTextDocument :: IO (Ptr (TQTextDocument ())) instance QqTextDocument ((String)) where qTextDocument (x1) = withQTextDocumentResult $ withCWString x1 $ \cstr_x1 -> qtc_QTextDocument1 cstr_x1 foreign import ccall "qtc_QTextDocument1" qtc_QTextDocument1 :: CWString -> IO (Ptr (TQTextDocument ())) instance QqTextDocument ((QObject t1)) where qTextDocument (x1) = withQTextDocumentResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QTextDocument2 cobj_x1 foreign import ccall "qtc_QTextDocument2" qtc_QTextDocument2 :: Ptr (TQObject t1) -> IO (Ptr (TQTextDocument ())) instance QqTextDocument ((String, QObject t2)) where qTextDocument (x1, x2) = withQTextDocumentResult $ withCWString x1 $ \cstr_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QTextDocument3 cstr_x1 cobj_x2 foreign import ccall "qtc_QTextDocument3" qtc_QTextDocument3 :: CWString -> Ptr (TQObject t2) -> IO (Ptr (TQTextDocument ())) addResource :: QTextDocument a -> ((Int, QUrl t2, QVariant t3)) -> IO () addResource x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QTextDocument_addResource cobj_x0 (toCInt x1) cobj_x2 cobj_x3 foreign import ccall "qtc_QTextDocument_addResource" qtc_QTextDocument_addResource :: Ptr (TQTextDocument a) -> CInt -> Ptr (TQUrl t2) -> Ptr (TQVariant t3) -> IO () instance QadjustSize (QTextDocument a) (()) where adjustSize x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_adjustSize cobj_x0 foreign import ccall "qtc_QTextDocument_adjustSize" qtc_QTextDocument_adjustSize :: Ptr (TQTextDocument a) -> IO () instance Qbegin (QTextDocument a) (()) (IO (QTextBlock ())) where begin x0 () = withQTextBlockResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_begin cobj_x0 foreign import ccall "qtc_QTextDocument_begin" qtc_QTextDocument_begin :: Ptr (TQTextDocument a) -> IO (Ptr (TQTextBlock ())) blockCount :: QTextDocument a -> (()) -> IO (Int) blockCount x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_blockCount cobj_x0 foreign import ccall "qtc_QTextDocument_blockCount" qtc_QTextDocument_blockCount :: Ptr (TQTextDocument a) -> IO CInt instance Qclear (QTextDocument ()) (()) where clear x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_clear_h cobj_x0 foreign import ccall "qtc_QTextDocument_clear_h" qtc_QTextDocument_clear_h :: Ptr (TQTextDocument a) -> IO () instance Qclear (QTextDocumentSc a) (()) where clear x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_clear_h cobj_x0 instance Qclone (QTextDocument a) (()) (IO (QTextDocument ())) where clone x0 () = withQTextDocumentResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_clone cobj_x0 foreign import ccall "qtc_QTextDocument_clone" qtc_QTextDocument_clone :: Ptr (TQTextDocument a) -> IO (Ptr (TQTextDocument ())) instance Qclone (QTextDocument a) ((QObject t1)) (IO (QTextDocument ())) where clone x0 (x1) = withQTextDocumentResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextDocument_clone1 cobj_x0 cobj_x1 foreign import ccall "qtc_QTextDocument_clone1" qtc_QTextDocument_clone1 :: Ptr (TQTextDocument a) -> Ptr (TQObject t1) -> IO (Ptr (TQTextDocument ())) class QcreateObject x0 x1 where createObject :: x0 -> x1 -> IO (QTextObject ()) instance QcreateObject (QTextDocument ()) ((QTextFormat t1)) where createObject x0 (x1) = withQTextObjectResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextDocument_createObject_h cobj_x0 cobj_x1 foreign import ccall "qtc_QTextDocument_createObject_h" qtc_QTextDocument_createObject_h :: Ptr (TQTextDocument a) -> Ptr (TQTextFormat t1) -> IO (Ptr (TQTextObject ())) instance QcreateObject (QTextDocumentSc a) ((QTextFormat t1)) where createObject x0 (x1) = withQTextObjectResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextDocument_createObject_h cobj_x0 cobj_x1 defaultFont :: QTextDocument a -> (()) -> IO (QFont ()) defaultFont x0 () = withQFontResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_defaultFont cobj_x0 foreign import ccall "qtc_QTextDocument_defaultFont" qtc_QTextDocument_defaultFont :: Ptr (TQTextDocument a) -> IO (Ptr (TQFont ())) defaultStyleSheet :: QTextDocument a -> (()) -> IO (String) defaultStyleSheet x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_defaultStyleSheet cobj_x0 foreign import ccall "qtc_QTextDocument_defaultStyleSheet" qtc_QTextDocument_defaultStyleSheet :: Ptr (TQTextDocument a) -> IO (Ptr (TQString ())) defaultTextOption :: QTextDocument a -> (()) -> IO (QTextOption ()) defaultTextOption x0 () = withQTextOptionResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_defaultTextOption cobj_x0 foreign import ccall "qtc_QTextDocument_defaultTextOption" qtc_QTextDocument_defaultTextOption :: Ptr (TQTextDocument a) -> IO (Ptr (TQTextOption ())) documentLayout :: QTextDocument a -> (()) -> IO (QAbstractTextDocumentLayout ()) documentLayout x0 () = withQAbstractTextDocumentLayoutResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_documentLayout cobj_x0 foreign import ccall "qtc_QTextDocument_documentLayout" qtc_QTextDocument_documentLayout :: Ptr (TQTextDocument a) -> IO (Ptr (TQAbstractTextDocumentLayout ())) instance QdrawContents (QTextDocument a) ((QPainter t1)) where drawContents x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextDocument_drawContents cobj_x0 cobj_x1 foreign import ccall "qtc_QTextDocument_drawContents" qtc_QTextDocument_drawContents :: Ptr (TQTextDocument a) -> Ptr (TQPainter t1) -> IO () qdrawContents :: QTextDocument a -> ((QPainter t1, QRectF t2)) -> IO () qdrawContents x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QTextDocument_drawContents1 cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QTextDocument_drawContents1" qtc_QTextDocument_drawContents1 :: Ptr (TQTextDocument a) -> Ptr (TQPainter t1) -> Ptr (TQRectF t2) -> IO () instance QdrawContents (QTextDocument a) ((QPainter t1, RectF)) where drawContents x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withCRectF x2 $ \crectf_x2_x crectf_x2_y crectf_x2_w crectf_x2_h -> qtc_QTextDocument_drawContents1_qth cobj_x0 cobj_x1 crectf_x2_x crectf_x2_y crectf_x2_w crectf_x2_h foreign import ccall "qtc_QTextDocument_drawContents1_qth" qtc_QTextDocument_drawContents1_qth :: Ptr (TQTextDocument a) -> Ptr (TQPainter t1) -> CDouble -> CDouble -> CDouble -> CDouble -> IO () instance Qend (QTextDocument a) (()) (IO (QTextBlock ())) where end x0 () = withQTextBlockResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_end cobj_x0 foreign import ccall "qtc_QTextDocument_end" qtc_QTextDocument_end :: Ptr (TQTextDocument a) -> IO (Ptr (TQTextBlock ())) instance Qfind (QTextDocument a) ((QRegExp t1)) (IO (QTextCursor ())) where find x0 (x1) = withQTextCursorResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextDocument_find cobj_x0 cobj_x1 foreign import ccall "qtc_QTextDocument_find" qtc_QTextDocument_find :: Ptr (TQTextDocument a) -> Ptr (TQRegExp t1) -> IO (Ptr (TQTextCursor ())) instance Qfind (QTextDocument a) ((QRegExp t1, Int)) (IO (QTextCursor ())) where find x0 (x1, x2) = withQTextCursorResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextDocument_find3 cobj_x0 cobj_x1 (toCInt x2) foreign import ccall "qtc_QTextDocument_find3" qtc_QTextDocument_find3 :: Ptr (TQTextDocument a) -> Ptr (TQRegExp t1) -> CInt -> IO (Ptr (TQTextCursor ())) instance Qfind (QTextDocument a) ((QRegExp t1, Int, FindFlags)) (IO (QTextCursor ())) where find x0 (x1, x2, x3) = withQTextCursorResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextDocument_find8 cobj_x0 cobj_x1 (toCInt x2) (toCLong $ qFlags_toInt x3) foreign import ccall "qtc_QTextDocument_find8" qtc_QTextDocument_find8 :: Ptr (TQTextDocument a) -> Ptr (TQRegExp t1) -> CInt -> CLong -> IO (Ptr (TQTextCursor ())) instance Qfind (QTextDocument a) ((QRegExp t1, QTextCursor t2)) (IO (QTextCursor ())) where find x0 (x1, x2) = withQTextCursorResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QTextDocument_find2 cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QTextDocument_find2" qtc_QTextDocument_find2 :: Ptr (TQTextDocument a) -> Ptr (TQRegExp t1) -> Ptr (TQTextCursor t2) -> IO (Ptr (TQTextCursor ())) instance Qfind (QTextDocument a) ((QRegExp t1, QTextCursor t2, FindFlags)) (IO (QTextCursor ())) where find x0 (x1, x2, x3) = withQTextCursorResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QTextDocument_find9 cobj_x0 cobj_x1 cobj_x2 (toCLong $ qFlags_toInt x3) foreign import ccall "qtc_QTextDocument_find9" qtc_QTextDocument_find9 :: Ptr (TQTextDocument a) -> Ptr (TQRegExp t1) -> Ptr (TQTextCursor t2) -> CLong -> IO (Ptr (TQTextCursor ())) instance Qfind (QTextDocument a) ((String)) (IO (QTextCursor ())) where find x0 (x1) = withQTextCursorResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QTextDocument_find1 cobj_x0 cstr_x1 foreign import ccall "qtc_QTextDocument_find1" qtc_QTextDocument_find1 :: Ptr (TQTextDocument a) -> CWString -> IO (Ptr (TQTextCursor ())) instance Qfind (QTextDocument a) ((String, Int)) (IO (QTextCursor ())) where find x0 (x1, x2) = withQTextCursorResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QTextDocument_find4 cobj_x0 cstr_x1 (toCInt x2) foreign import ccall "qtc_QTextDocument_find4" qtc_QTextDocument_find4 :: Ptr (TQTextDocument a) -> CWString -> CInt -> IO (Ptr (TQTextCursor ())) instance Qfind (QTextDocument a) ((String, Int, FindFlags)) (IO (QTextCursor ())) where find x0 (x1, x2, x3) = withQTextCursorResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QTextDocument_find6 cobj_x0 cstr_x1 (toCInt x2) (toCLong $ qFlags_toInt x3) foreign import ccall "qtc_QTextDocument_find6" qtc_QTextDocument_find6 :: Ptr (TQTextDocument a) -> CWString -> CInt -> CLong -> IO (Ptr (TQTextCursor ())) instance Qfind (QTextDocument a) ((String, QTextCursor t2)) (IO (QTextCursor ())) where find x0 (x1, x2) = withQTextCursorResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QTextDocument_find5 cobj_x0 cstr_x1 cobj_x2 foreign import ccall "qtc_QTextDocument_find5" qtc_QTextDocument_find5 :: Ptr (TQTextDocument a) -> CWString -> Ptr (TQTextCursor t2) -> IO (Ptr (TQTextCursor ())) instance Qfind (QTextDocument a) ((String, QTextCursor t2, FindFlags)) (IO (QTextCursor ())) where find x0 (x1, x2, x3) = withQTextCursorResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QTextDocument_find7 cobj_x0 cstr_x1 cobj_x2 (toCLong $ qFlags_toInt x3) foreign import ccall "qtc_QTextDocument_find7" qtc_QTextDocument_find7 :: Ptr (TQTextDocument a) -> CWString -> Ptr (TQTextCursor t2) -> CLong -> IO (Ptr (TQTextCursor ())) findBlock :: QTextDocument a -> ((Int)) -> IO (QTextBlock ()) findBlock x0 (x1) = withQTextBlockResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_findBlock cobj_x0 (toCInt x1) foreign import ccall "qtc_QTextDocument_findBlock" qtc_QTextDocument_findBlock :: Ptr (TQTextDocument a) -> CInt -> IO (Ptr (TQTextBlock ())) frameAt :: QTextDocument a -> ((Int)) -> IO (QTextFrame ()) frameAt x0 (x1) = withQTextFrameResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_frameAt cobj_x0 (toCInt x1) foreign import ccall "qtc_QTextDocument_frameAt" qtc_QTextDocument_frameAt :: Ptr (TQTextDocument a) -> CInt -> IO (Ptr (TQTextFrame ())) idealWidth :: QTextDocument a -> (()) -> IO (Double) idealWidth x0 () = withDoubleResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_idealWidth cobj_x0 foreign import ccall "qtc_QTextDocument_idealWidth" qtc_QTextDocument_idealWidth :: Ptr (TQTextDocument a) -> IO CDouble instance QqisEmpty (QTextDocument a) (()) where qisEmpty x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_isEmpty cobj_x0 foreign import ccall "qtc_QTextDocument_isEmpty" qtc_QTextDocument_isEmpty :: Ptr (TQTextDocument a) -> IO CBool instance QisModified (QTextDocument a) (()) where isModified x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_isModified cobj_x0 foreign import ccall "qtc_QTextDocument_isModified" qtc_QTextDocument_isModified :: Ptr (TQTextDocument a) -> IO CBool instance QisRedoAvailable (QTextDocument a) (()) where isRedoAvailable x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_isRedoAvailable cobj_x0 foreign import ccall "qtc_QTextDocument_isRedoAvailable" qtc_QTextDocument_isRedoAvailable :: Ptr (TQTextDocument a) -> IO CBool instance QisUndoAvailable (QTextDocument a) (()) where isUndoAvailable x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_isUndoAvailable cobj_x0 foreign import ccall "qtc_QTextDocument_isUndoAvailable" qtc_QTextDocument_isUndoAvailable :: Ptr (TQTextDocument a) -> IO CBool instance QisUndoRedoEnabled (QTextDocument a) (()) where isUndoRedoEnabled x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_isUndoRedoEnabled cobj_x0 foreign import ccall "qtc_QTextDocument_isUndoRedoEnabled" qtc_QTextDocument_isUndoRedoEnabled :: Ptr (TQTextDocument a) -> IO CBool instance QloadResource (QTextDocument ()) ((Int, QUrl t2)) where loadResource x0 (x1, x2) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QTextDocument_loadResource_h cobj_x0 (toCInt x1) cobj_x2 foreign import ccall "qtc_QTextDocument_loadResource_h" qtc_QTextDocument_loadResource_h :: Ptr (TQTextDocument a) -> CInt -> Ptr (TQUrl t2) -> IO (Ptr (TQVariant ())) instance QloadResource (QTextDocumentSc a) ((Int, QUrl t2)) where loadResource x0 (x1, x2) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QTextDocument_loadResource_h cobj_x0 (toCInt x1) cobj_x2 markContentsDirty :: QTextDocument a -> ((Int, Int)) -> IO () markContentsDirty x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_markContentsDirty cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QTextDocument_markContentsDirty" qtc_QTextDocument_markContentsDirty :: Ptr (TQTextDocument a) -> CInt -> CInt -> IO () maximumBlockCount :: QTextDocument a -> (()) -> IO (Int) maximumBlockCount x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_maximumBlockCount cobj_x0 foreign import ccall "qtc_QTextDocument_maximumBlockCount" qtc_QTextDocument_maximumBlockCount :: Ptr (TQTextDocument a) -> IO CInt metaInformation :: QTextDocument a -> ((MetaInformation)) -> IO (String) metaInformation x0 (x1) = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_metaInformation cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QTextDocument_metaInformation" qtc_QTextDocument_metaInformation :: Ptr (TQTextDocument a) -> CLong -> IO (Ptr (TQString ())) object :: QTextDocument a -> ((Int)) -> IO (QTextObject ()) object x0 (x1) = withQTextObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_object cobj_x0 (toCInt x1) foreign import ccall "qtc_QTextDocument_object" qtc_QTextDocument_object :: Ptr (TQTextDocument a) -> CInt -> IO (Ptr (TQTextObject ())) objectForFormat :: QTextDocument a -> ((QTextFormat t1)) -> IO (QTextObject ()) objectForFormat x0 (x1) = withQTextObjectResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextDocument_objectForFormat cobj_x0 cobj_x1 foreign import ccall "qtc_QTextDocument_objectForFormat" qtc_QTextDocument_objectForFormat :: Ptr (TQTextDocument a) -> Ptr (TQTextFormat t1) -> IO (Ptr (TQTextObject ())) instance QpageCount (QTextDocument a) (()) where pageCount x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_pageCount cobj_x0 foreign import ccall "qtc_QTextDocument_pageCount" qtc_QTextDocument_pageCount :: Ptr (TQTextDocument a) -> IO CInt qpageSize :: QTextDocument a -> (()) -> IO (QSizeF ()) qpageSize x0 () = withQSizeFResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_pageSize cobj_x0 foreign import ccall "qtc_QTextDocument_pageSize" qtc_QTextDocument_pageSize :: Ptr (TQTextDocument a) -> IO (Ptr (TQSizeF ())) instance QpageSize (QTextDocument a) (()) (IO (SizeF)) where pageSize x0 () = withSizeFResult $ \csizef_ret_w csizef_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_pageSize_qth cobj_x0 csizef_ret_w csizef_ret_h foreign import ccall "qtc_QTextDocument_pageSize_qth" qtc_QTextDocument_pageSize_qth :: Ptr (TQTextDocument a) -> Ptr CDouble -> Ptr CDouble -> IO () instance Qqprint (QTextDocument a) ((QPrinter t1)) where qprint x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextDocument_print cobj_x0 cobj_x1 foreign import ccall "qtc_QTextDocument_print" qtc_QTextDocument_print :: Ptr (TQTextDocument a) -> Ptr (TQPrinter t1) -> IO () instance Qredo (QTextDocument a) (()) where redo x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_redo cobj_x0 foreign import ccall "qtc_QTextDocument_redo" qtc_QTextDocument_redo :: Ptr (TQTextDocument a) -> IO () instance Qredo (QTextDocument a) ((QTextCursor t1)) where redo x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextDocument_redo1 cobj_x0 cobj_x1 foreign import ccall "qtc_QTextDocument_redo1" qtc_QTextDocument_redo1 :: Ptr (TQTextDocument a) -> Ptr (TQTextCursor t1) -> IO () class Qresource x0 x1 where resource :: x0 -> x1 -> IO (QVariant ()) class Qresource_nf x0 x1 where resource_nf :: x0 -> x1 -> IO (QVariant ()) instance Qresource (QTextDocument ()) ((Int, QUrl t2)) where resource x0 (x1, x2) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QTextDocument_resource cobj_x0 (toCInt x1) cobj_x2 foreign import ccall "qtc_QTextDocument_resource" qtc_QTextDocument_resource :: Ptr (TQTextDocument a) -> CInt -> Ptr (TQUrl t2) -> IO (Ptr (TQVariant ())) instance Qresource (QTextDocumentSc a) ((Int, QUrl t2)) where resource x0 (x1, x2) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QTextDocument_resource cobj_x0 (toCInt x1) cobj_x2 instance Qresource_nf (QTextDocument ()) ((Int, QUrl t2)) where resource_nf x0 (x1, x2) = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QTextDocument_resource cobj_x0 (toCInt x1) cobj_x2 instance Qresource_nf (QTextDocumentSc a) ((Int, QUrl t2)) where resource_nf x0 (x1, x2) = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QTextDocument_resource cobj_x0 (toCInt x1) cobj_x2 rootFrame :: QTextDocument a -> (()) -> IO (QTextFrame ()) rootFrame x0 () = withQTextFrameResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_rootFrame cobj_x0 foreign import ccall "qtc_QTextDocument_rootFrame" qtc_QTextDocument_rootFrame :: Ptr (TQTextDocument a) -> IO (Ptr (TQTextFrame ())) setDefaultFont :: QTextDocument a -> ((QFont t1)) -> IO () setDefaultFont x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextDocument_setDefaultFont cobj_x0 cobj_x1 foreign import ccall "qtc_QTextDocument_setDefaultFont" qtc_QTextDocument_setDefaultFont :: Ptr (TQTextDocument a) -> Ptr (TQFont t1) -> IO () setDefaultStyleSheet :: QTextDocument a -> ((String)) -> IO () setDefaultStyleSheet x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QTextDocument_setDefaultStyleSheet cobj_x0 cstr_x1 foreign import ccall "qtc_QTextDocument_setDefaultStyleSheet" qtc_QTextDocument_setDefaultStyleSheet :: Ptr (TQTextDocument a) -> CWString -> IO () setDefaultTextOption :: QTextDocument a -> ((QTextOption t1)) -> IO () setDefaultTextOption x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextDocument_setDefaultTextOption cobj_x0 cobj_x1 foreign import ccall "qtc_QTextDocument_setDefaultTextOption" qtc_QTextDocument_setDefaultTextOption :: Ptr (TQTextDocument a) -> Ptr (TQTextOption t1) -> IO () setDocumentLayout :: QTextDocument a -> ((QAbstractTextDocumentLayout t1)) -> IO () setDocumentLayout x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextDocument_setDocumentLayout cobj_x0 cobj_x1 foreign import ccall "qtc_QTextDocument_setDocumentLayout" qtc_QTextDocument_setDocumentLayout :: Ptr (TQTextDocument a) -> Ptr (TQAbstractTextDocumentLayout t1) -> IO () instance QsetHtml (QTextDocument a) ((String)) where setHtml x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QTextDocument_setHtml cobj_x0 cstr_x1 foreign import ccall "qtc_QTextDocument_setHtml" qtc_QTextDocument_setHtml :: Ptr (TQTextDocument a) -> CWString -> IO () setMaximumBlockCount :: QTextDocument a -> ((Int)) -> IO () setMaximumBlockCount x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_setMaximumBlockCount cobj_x0 (toCInt x1) foreign import ccall "qtc_QTextDocument_setMaximumBlockCount" qtc_QTextDocument_setMaximumBlockCount :: Ptr (TQTextDocument a) -> CInt -> IO () setMetaInformation :: QTextDocument a -> ((MetaInformation, String)) -> IO () setMetaInformation x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withCWString x2 $ \cstr_x2 -> qtc_QTextDocument_setMetaInformation cobj_x0 (toCLong $ qEnum_toInt x1) cstr_x2 foreign import ccall "qtc_QTextDocument_setMetaInformation" qtc_QTextDocument_setMetaInformation :: Ptr (TQTextDocument a) -> CLong -> CWString -> IO () instance QsetModified (QTextDocument a) (()) where setModified x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_setModified cobj_x0 foreign import ccall "qtc_QTextDocument_setModified" qtc_QTextDocument_setModified :: Ptr (TQTextDocument a) -> IO () instance QsetModified (QTextDocument a) ((Bool)) where setModified x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_setModified1 cobj_x0 (toCBool x1) foreign import ccall "qtc_QTextDocument_setModified1" qtc_QTextDocument_setModified1 :: Ptr (TQTextDocument a) -> CBool -> IO () qsetPageSize :: QTextDocument a -> ((QSizeF t1)) -> IO () qsetPageSize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextDocument_setPageSize cobj_x0 cobj_x1 foreign import ccall "qtc_QTextDocument_setPageSize" qtc_QTextDocument_setPageSize :: Ptr (TQTextDocument a) -> Ptr (TQSizeF t1) -> IO () instance QsetPageSize (QTextDocument a) ((SizeF)) where setPageSize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCSizeF x1 $ \csizef_x1_w csizef_x1_h -> qtc_QTextDocument_setPageSize_qth cobj_x0 csizef_x1_w csizef_x1_h foreign import ccall "qtc_QTextDocument_setPageSize_qth" qtc_QTextDocument_setPageSize_qth :: Ptr (TQTextDocument a) -> CDouble -> CDouble -> IO () instance QsetPlainText (QTextDocument a) ((String)) where setPlainText x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QTextDocument_setPlainText cobj_x0 cstr_x1 foreign import ccall "qtc_QTextDocument_setPlainText" qtc_QTextDocument_setPlainText :: Ptr (TQTextDocument a) -> CWString -> IO () instance QsetTextWidth (QTextDocument a) ((Double)) where setTextWidth x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_setTextWidth cobj_x0 (toCDouble x1) foreign import ccall "qtc_QTextDocument_setTextWidth" qtc_QTextDocument_setTextWidth :: Ptr (TQTextDocument a) -> CDouble -> IO () instance QsetUndoRedoEnabled (QTextDocument a) ((Bool)) where setUndoRedoEnabled x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_setUndoRedoEnabled cobj_x0 (toCBool x1) foreign import ccall "qtc_QTextDocument_setUndoRedoEnabled" qtc_QTextDocument_setUndoRedoEnabled :: Ptr (TQTextDocument a) -> CBool -> IO () instance QsetUseDesignMetrics (QTextDocument a) ((Bool)) where setUseDesignMetrics x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_setUseDesignMetrics cobj_x0 (toCBool x1) foreign import ccall "qtc_QTextDocument_setUseDesignMetrics" qtc_QTextDocument_setUseDesignMetrics :: Ptr (TQTextDocument a) -> CBool -> IO () instance Qqqsize (QTextDocument a) (()) (IO (QSizeF ())) where qqsize x0 () = withQSizeFResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_size cobj_x0 foreign import ccall "qtc_QTextDocument_size" qtc_QTextDocument_size :: Ptr (TQTextDocument a) -> IO (Ptr (TQSizeF ())) instance Qqsize (QTextDocument a) (()) (IO (SizeF)) where qsize x0 () = withSizeFResult $ \csizef_ret_w csizef_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_size_qth cobj_x0 csizef_ret_w csizef_ret_h foreign import ccall "qtc_QTextDocument_size_qth" qtc_QTextDocument_size_qth :: Ptr (TQTextDocument a) -> Ptr CDouble -> Ptr CDouble -> IO () instance QtextWidth (QTextDocument a) (()) where textWidth x0 () = withDoubleResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_textWidth cobj_x0 foreign import ccall "qtc_QTextDocument_textWidth" qtc_QTextDocument_textWidth :: Ptr (TQTextDocument a) -> IO CDouble instance QtoHtml (QTextDocument a) (()) where toHtml x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_toHtml cobj_x0 foreign import ccall "qtc_QTextDocument_toHtml" qtc_QTextDocument_toHtml :: Ptr (TQTextDocument a) -> IO (Ptr (TQString ())) instance QtoHtml (QTextDocument a) ((String)) where toHtml x0 (x1) = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QTextDocument_toHtml1 cobj_x0 cstr_x1 foreign import ccall "qtc_QTextDocument_toHtml1" qtc_QTextDocument_toHtml1 :: Ptr (TQTextDocument a) -> CWString -> IO (Ptr (TQString ())) instance QtoPlainText (QTextDocument a) (()) where toPlainText x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_toPlainText cobj_x0 foreign import ccall "qtc_QTextDocument_toPlainText" qtc_QTextDocument_toPlainText :: Ptr (TQTextDocument a) -> IO (Ptr (TQString ())) instance Qundo (QTextDocument a) (()) where undo x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_undo cobj_x0 foreign import ccall "qtc_QTextDocument_undo" qtc_QTextDocument_undo :: Ptr (TQTextDocument a) -> IO () instance Qundo (QTextDocument a) ((QTextCursor t1)) where undo x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextDocument_undo1 cobj_x0 cobj_x1 foreign import ccall "qtc_QTextDocument_undo1" qtc_QTextDocument_undo1 :: Ptr (TQTextDocument a) -> Ptr (TQTextCursor t1) -> IO () instance QuseDesignMetrics (QTextDocument a) (()) where useDesignMetrics x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_useDesignMetrics cobj_x0 foreign import ccall "qtc_QTextDocument_useDesignMetrics" qtc_QTextDocument_useDesignMetrics :: Ptr (TQTextDocument a) -> IO CBool qTextDocument_delete :: QTextDocument a -> IO () qTextDocument_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_delete cobj_x0 foreign import ccall "qtc_QTextDocument_delete" qtc_QTextDocument_delete :: Ptr (TQTextDocument a) -> IO () qTextDocument_deleteLater :: QTextDocument a -> IO () qTextDocument_deleteLater x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_deleteLater cobj_x0 foreign import ccall "qtc_QTextDocument_deleteLater" qtc_QTextDocument_deleteLater :: Ptr (TQTextDocument a) -> IO () instance QchildEvent (QTextDocument ()) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextDocument_childEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QTextDocument_childEvent" qtc_QTextDocument_childEvent :: Ptr (TQTextDocument a) -> Ptr (TQChildEvent t1) -> IO () instance QchildEvent (QTextDocumentSc a) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextDocument_childEvent cobj_x0 cobj_x1 instance QconnectNotify (QTextDocument ()) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QTextDocument_connectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QTextDocument_connectNotify" qtc_QTextDocument_connectNotify :: Ptr (TQTextDocument a) -> CWString -> IO () instance QconnectNotify (QTextDocumentSc a) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QTextDocument_connectNotify cobj_x0 cstr_x1 instance QcustomEvent (QTextDocument ()) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextDocument_customEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QTextDocument_customEvent" qtc_QTextDocument_customEvent :: Ptr (TQTextDocument a) -> Ptr (TQEvent t1) -> IO () instance QcustomEvent (QTextDocumentSc a) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextDocument_customEvent cobj_x0 cobj_x1 instance QdisconnectNotify (QTextDocument ()) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QTextDocument_disconnectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QTextDocument_disconnectNotify" qtc_QTextDocument_disconnectNotify :: Ptr (TQTextDocument a) -> CWString -> IO () instance QdisconnectNotify (QTextDocumentSc a) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QTextDocument_disconnectNotify cobj_x0 cstr_x1 instance Qevent (QTextDocument ()) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextDocument_event_h cobj_x0 cobj_x1 foreign import ccall "qtc_QTextDocument_event_h" qtc_QTextDocument_event_h :: Ptr (TQTextDocument a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent (QTextDocumentSc a) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextDocument_event_h cobj_x0 cobj_x1 instance QeventFilter (QTextDocument ()) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QTextDocument_eventFilter_h cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QTextDocument_eventFilter_h" qtc_QTextDocument_eventFilter_h :: Ptr (TQTextDocument a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance QeventFilter (QTextDocumentSc a) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QTextDocument_eventFilter_h cobj_x0 cobj_x1 cobj_x2 instance Qreceivers (QTextDocument ()) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QTextDocument_receivers cobj_x0 cstr_x1 foreign import ccall "qtc_QTextDocument_receivers" qtc_QTextDocument_receivers :: Ptr (TQTextDocument a) -> CWString -> IO CInt instance Qreceivers (QTextDocumentSc a) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QTextDocument_receivers cobj_x0 cstr_x1 instance Qsender (QTextDocument ()) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_sender cobj_x0 foreign import ccall "qtc_QTextDocument_sender" qtc_QTextDocument_sender :: Ptr (TQTextDocument a) -> IO (Ptr (TQObject ())) instance Qsender (QTextDocumentSc a) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_sender cobj_x0 instance QtimerEvent (QTextDocument ()) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextDocument_timerEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QTextDocument_timerEvent" qtc_QTextDocument_timerEvent :: Ptr (TQTextDocument a) -> Ptr (TQTimerEvent t1) -> IO () instance QtimerEvent (QTextDocumentSc a) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextDocument_timerEvent cobj_x0 cobj_x1
uduki/hsQt
Qtc/Gui/QTextDocument.hs
bsd-2-clause
36,081
0
15
5,700
11,502
5,824
5,678
-1
-1
{-# LANGUAGE RecordWildCards #-} ----------------------------------------------------------------------------- -- | -- Module : Text.Hoodle.Migrate.FromXournal -- Copyright : (c) 2011-2013 Ian-Woo Kim -- -- License : BSD3 -- Maintainer : Ian-Woo Kim <[email protected]> -- Stability : experimental -- Portability : GHC -- ----------------------------------------------------------------------------- module Text.Hoodle.Migrate.FromXournal ( mkHoodleFromXournal ) where import Control.Applicative import Control.Lens -- import qualified Data.Xournal.Simple as X import qualified Data.Hoodle.Simple as H -- | mkHoodleFromXournal :: X.Xournal -> IO H.Hoodle mkHoodleFromXournal X.Xournal {..} = set H.title xoj_title . set H.pages (map x2h4Page xoj_pages) <$> H.emptyHoodle -- | x2h4Page :: X.Page -> H.Page x2h4Page X.Page {..} = H.Page (x2h4dim page_dim) (x2h4bkg page_bkg) (map x2h4layer page_layers) -- | x2h4dim :: X.Dimension -> H.Dimension x2h4dim X.Dim {..} = H.Dim dim_width dim_height -- | x2h4bkg :: X.Background -> H.Background x2h4bkg X.Background {..} = H.Background bkg_type bkg_color bkg_style x2h4bkg X.BackgroundPdf {..} = H.BackgroundPdf bkg_type bkg_domain bkg_filename bkg_pageno -- | x2h4layer :: X.Layer -> H.Layer x2h4layer X.Layer {..} = H.Layer (map x2h4stroke layer_strokes) -- | x2h4stroke :: X.Stroke -> H.Item -- H.Stroke x2h4stroke X.Stroke {..} = H.ItemStroke (H.Stroke stroke_tool stroke_color stroke_width stroke_data) x2h4stroke X.VWStroke {..} = H.ItemStroke (H.VWStroke stroke_tool stroke_color stroke_vwdata)
wavewave/hoodle-parser
src/Text/Hoodle/Migrate/FromXournal.hs
bsd-2-clause
1,759
0
9
396
407
220
187
28
1
module Append where import qualified Prelude data List a = Nil | Cons a (List a) append :: (List a1) -> (List a1) -> List a1 append xs ys = case xs of { Nil -> ys; Cons h t -> Cons h (append t ys)}
dalaing/bfpg-2013-03
coq/extraction/append.hs
bsd-3-clause
214
0
10
62
104
56
48
10
2
{-# LANGUAGE LambdaCase, RecordWildCards #-} {-# LANGUAGE RankNTypes #-} {-| (re-exports) @ :m +Commands.Mixins.DNS13OSX9 @ -} module Commands.Mixins.DNS13OSX9 ( module Commands.Mixins.DNS13OSX9 , module Commands.Mixins.DNS13OSX9.Types , module Commands.Mixins.DNS13OSX9.Derived , module Commands.Mixins.DNS13OSX9.Frontend , module Commands.Mixins.DNS13OSX9.Parser , module Commands.RHS , module Commands.Command.Types ) where import Commands.Mixins.DNS13OSX9.Types import Commands.Mixins.DNS13OSX9.Derived import Commands.Mixins.DNS13OSX9.Frontend import Commands.Mixins.DNS13OSX9.Parser import Commands.RHS import Commands.Command.Types import Commands.Frontends.Dragon13 (SerializedGrammar,DnsOptimizationSettings,defaultDnsOptimizationSettings,displaySerializedGrammar) import Commands.Parsers.Earley (EarleyParser(..),EarleyEither,fromProd_) import Data.Text.Lazy (Text) import Data.Function ((&)) import Control.Monad.Trans.Reader (ReaderT(..)) -- | see 'unsafeInterpretCommand' data Command' m a = Command' { cGrammar :: SerializedGrammar , cParser :: (forall s r. EarleyParser s r String Text a) , cRun :: a -> m () } -- -- {-| -- -- -} -- isFiniteDNSEarleyGrammar :: RHS n t (DNSEarleyFunc n t) a -> IsFiniteGrammar t -- isFiniteDNSEarleyGrammar = isFiniteGrammar isFiniteDNSEarleyFunc -- -- {-| only uses the dragon grammar (which stores exact tokens), -- as the earley parser's Terminal is a predicate (not a token). -- -- -} -- isFiniteDNSEarleyFunc :: DNSEarleyFunc n t a -> IsFiniteGrammar t -- isFiniteDNSEarleyFunc = \case -- LeafRHS _ g -> isFiniteDNSRHS g -- TreeRHS _ gRHS -> isFiniteDNSEarleyGrammar gRHS test_observeParserAndGrammar :: DNSEarleyRHS a -> (String, String -> EarleyEither String Text a) test_observeParserAndGrammar r = ( displaySerializedGrammar (unsafeDNSGrammar defaultDnsOptimizationSettings r) , fromProd_ (unsafeEarleyProd r) ) {-| interprets an RHS into a grammar and an equivalent parser. -} unsafeInterpretCommand :: DnsOptimizationSettings -> DNSEarleyCommand c (m ()) a -> Command' (ReaderT c m) a unsafeInterpretCommand dnsSettings command = Command' (unsafeDNSGrammar dnsSettings (command&_cRHS)) (EarleyParser (unsafeEarleyProd (command&_cRHS)) (command&_cBest)) (\a -> ReaderT $ \c -> (command&_cDesugar) c a) {- {-| see 'interpretCommand' -} unsafeInterpretCommand :: DnsOptimizationSettings -> DNSEarleyCommand c (m ()) a -> Command' (ReaderT c m) a unsafeInterpretCommand x y = unsafePerformIO $ interpretCommand x y interpretCommand :: DnsOptimizationSettings -> DNSEarleyCommand c (m ()) a -> IO (Command' (ReaderT c m) a) interpretCommand dnsSettings command = do p <- unsafeSTToIO $ de'deriveParserObservedSharing (command&_cRHS) let cParser = EarleyParser p (command&_cBest) let cDesugar a = ReaderT $ \c -> (command&_cDesugar) c a cGrammar <- de'deriveGrammarObservedSharing dnsSettings (command&_cRHS) return $ Command'{..} -}
sboosali/commands-frontend-DragonNaturallySpeaking
sources/Commands/Mixins/DNS13OSX9.hs
bsd-3-clause
2,948
0
12
397
452
278
174
37
1
-- -- BaseTypes.hs -- Copyright (C) 2017 jragonfyre <jragonfyre@jragonfyre> -- -- Distributed under terms of the MIT license. -- module Game.BaseTypes where -- ( -- ) where import qualified Data.HashMap.Lazy as M import qualified Data.Yaml as Y import Data.Yaml (FromJSON (..), (.:), (.!=), (.:?), (.=), ToJSON (..)) import Control.Applicative ((<$>),(<*>),(<|>)) import qualified Data.Maybe as May import qualified Data.List as L import qualified Data.Text as T import Data.Text (Text) import Data.Aeson.Types (typeMismatch) import Data.Vector (toList) import ParseUtilities type Identifier = String data Description = Desc { descriptionContent :: String , properNoun :: Bool } deriving (Show, Read, Eq) instance FromJSON Description where parseJSON (Y.Object v) = Desc <$> v .: "content" <*> v .: "proper-noun" instance ToJSON Description where toJSON desc = Y.object [ "content" .= descriptionContent desc , "proper-noun" .= properNoun desc ] data Visibility = Full | Partial | Dependent Condition deriving (Show, Read, Eq) instance FromJSON Visibility where parseJSON (Y.Bool True) = return Full parseJSON (Y.String "yes") = return Full parseJSON (Y.String "partly") = return Partial parseJSON (Y.Object v) = do mdep <- v .:? "dependent" case mdep of Just cond -> return (Dependent cond) Nothing -> typeMismatch "Visibility" (Y.Object v) parseJSON invalid = typeMismatch "Visibility" invalid instance ToJSON Visibility where toJSON Full = Y.String "yes" toJSON Partial = Y.String "partly" toJSON (Dependent cond) = Y.object ["dependent" .= (toJSON cond)] data Condition = WhenObjectState Identifier | HasObjectState Identifier | WhenAction Identifier | HasRelation Identifier deriving (Show, Read, Eq) instance FromJSON Condition where parseJSON (Y.Object v) = isKVPair v "object-state" WhenObjectState <|> isKVPair v "has-state" HasObjectState <|> isKVPair v "action" WhenAction <|> isKVPair v "relation" HasRelation <|> typeMismatch "Condition" (Y.Object v) parseJSON invalid = typeMismatch "Condition" invalid {- mwobjst <- v .:? "object-state" mhobjst <- v .:? "has-state" maction <- v .:? "action" mhrelation <- v .:? "relation" let ress = May.catMaybes $ map (\(mid, const) -> fmap const mid) [ (mwobjst, WhenObjectState) , (mhobjst, HasObjectState) , (maction, WhenAction) , (mhrelation, HasRelation) ] in case res of [] -> typeMismatch "Condition" (Object v) (a:_) -> return a -} instance ToJSON Condition where toJSON (WhenObjectState id) = Y.object ["object-state" .= (toJSON id)] toJSON (HasObjectState id) = Y.object ["in-state" .= (toJSON id)] toJSON (WhenAction id) = Y.object ["action" .= (toJSON id)] toJSON (HasRelation id) = Y.object ["relation" .= (toJSON id)] -- data type denoting restrictions on content data ContentClass where AllForbidden :: ContentClass Satisfies :: [Condition] -> ContentClass deriving (Show, Read, Eq) instance ToJSON ContentClass where toJSON AllForbidden = Y.String "all-forbidden" toJSON (Satisfies conds) = Y.array $ map toJSON conds instance FromJSON ContentClass where parseJSON (Y.String "all-forbidden") = return AllForbidden parseJSON (Y.Object v) = isKVPair v "satisfies" Satisfies <|> typeMismatch "ContentClass" (Y.Object v) parseJSONList = parseAMAP parseJSON
jragonfyre/TRPG
src/Game/BaseTypes.hs
bsd-3-clause
3,489
0
14
714
948
509
439
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} {-# OPTIONS_GHC -fno-warn-missing-fields -fno-cse #-} module Action.CmdLine(CmdLine(..), getCmdLine) where import System.Console.CmdArgs import System.Directory import System.FilePath import Data.Version import Paths_hoogle(version) data CmdLine = Search {color :: Maybe Bool ,link :: Bool ,info :: Bool ,database :: FilePath ,count :: Int ,query :: [String] } | Generate {hackage :: String ,download :: Maybe Bool ,database :: FilePath ,include :: [String] ,debug :: Bool } | Server {port :: Int ,database :: FilePath ,cdn :: String ,logs :: FilePath } | Replay {logs :: FilePath ,database :: FilePath } | Test {deep :: Bool ,database :: FilePath } deriving (Data,Typeable,Show) getCmdLine :: IO CmdLine getCmdLine = do args <- cmdArgsRun cmdLineMode if database args /= "" then return args else do dir <- getAppUserDataDirectory "hoogle" return $ args{database=dir </> "default-" ++ showVersion version ++ ".hoo"} cmdLineMode = cmdArgsMode $ modes [search_ &= auto,generate,server,replay,test] &= verbosity &= program "hoogle" &= summary ("Hoogle " ++ showVersion version ++ ", http://hoogle.haskell.org/") search_ = Search {color = def &= name "colour" &= help "Use colored output (requires ANSI terminal)" ,link = def &= help "Give URL's for each result" ,info = def &= help "Give extended information about the first result" ,database = def &= typFile &= help "Name of database to use (use .hoo extension)" ,count = 10 &= name "n" &= help "Maximum number of results to return" ,query = def &= args &= typ "QUERY" } &= help "Perform a search" generate = Generate {hackage = "https://hackage.haskell.org/" &= typ "URL" &= help "Hackage instance to target" ,download = def &= help "Download all files from the web" ,include = def &= args &= typ "PACKAGE" ,debug = def &= help "Generate debug information" } &= help "Generate Hoogle databases" server = Server {port = 80 &= typ "INT" &= help "Port number" ,cdn = "" &= typ "URL" &= help "URL prefix to use" ,logs = "" &= opt "log.txt" &= typFile &= help "File to log requests to (defaults to stdout)" } &= help "Start a Hoogle server" replay = Replay {logs = "log.txt" &= args &= typ "FILE" } &= help "Replay a log file" test = Test {deep = False &= help "Run extra long tests" } &= help "Run the test suite"
BartAdv/hoogle
src/Action/CmdLine.hs
bsd-3-clause
2,637
0
15
717
693
380
313
68
2
{- (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, pickGREsModExp, -- * 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, bestImport ) 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 import Data.List( sortBy ) {- ************************************************************************ * * \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 -- The field lre_nwcs is used to keep names of type variables that should -- be replaced with named wildcards. -- See Note [Renaming named wild cards] in RnTypes 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 (text "LocalRdrEnv {") 2 (vcat [ text "env =" <+> pprOccEnv ppr_elt env , text "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 { 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 { 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 { lre_env = env }) occs = lre { lre_env = delListFromOccEnv env occs } {- 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.bindHsQTyVars), 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] | PatternSynonym deriving (Eq) instance Outputable Parent where ppr NoParent = empty ppr (ParentIs n) = text "parent:" <> ppr n ppr (FldParent n f) = text "fldparent:" <> ppr n <> colon <> ppr f ppr (PatternSynonym) = text "pattern synonym" 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 PatternSynonym PatternSynonym = PatternSynonym plusParent _ _ = 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 The `PatternSynonym` constructor is so called as pattern synonyms can be bundled with any type constructor (during renaming). In other words, they can have any parent. ~~~~~~~~~~~~~~~~~~~~~~~~~ Constructor Meaning ~~~~~~~~~~~~~~~~~~~~~~~~ NoParent Can not be bundled with a type constructor. ParentIs n Can be bundled with the type constructor corresponding to n. PatternSynonym Can be bundled with any type constructor. It is so called because only pattern synonyms can be bundled with any type constructor. FldParent See Note [Parents for record fields] 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 a Qual RdrName if poss, so that identifies the most -- specific ImportSpec. See Trac #10890 for some good examples. greUsedRdrName gre@GRE{ gre_name = name, gre_lcl = lcl, gre_imp = iss } | lcl, Just mod <- nameModule_maybe name = Qual (moduleName mod) occ | not (null iss), is <- bestImport iss = Qual (is_as (is_decl is)) occ | otherwise = pprTrace "greUsedRdrName" (ppr gre) (Unqual occ) where occ = greOccName gre greRdrNames :: GlobalRdrElt -> [RdrName] greRdrNames gre@GRE{ gre_lcl = lcl, gre_imp = iss } = (if lcl then [unqual] else []) ++ concatMap do_spec (map is_decl iss) where occ = greOccName gre 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 NotPatSyn _) = NoParent mkParent _ (Avail IsPatSyn _) = PatternSynonym mkParent n (AvailTC m _ _) | n == m = NoParent | otherwise = ParentIs m availFromGRE :: GlobalRdrElt -> AvailInfo availFromGRE (GRE { gre_name = me, gre_par = parent }) = case parent 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] PatternSynonym -> patSynAvail me 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 [ text "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 (text "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 {- Note [GRE filtering] ~~~~~~~~~~~~~~~~~~~~~~~ (pickGREs rdr gres) takes a list of GREs which have the same OccName as 'rdr', say "x". It does two things: (a) filters the GREs to a subset that are in scope * Qualified, as 'M.x' if want_qual is Qual M _ * Unqualified, as 'x' if want_unqual is Unqual _ (b) for that subset, filter the provenance field (gre_lcl and gre_imp) to ones that brought it into scope qualifed or unqualified resp. Example: 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, but the local 'f' is different, so there will be two GREs matching "f": gre1: gre_lcl = True, gre_imp = [] gre2: gre_lcl = False, gre_imp = [ imported from Foo, imported from Bar ] The use of "f" in the export list is ambiguous because it's in scope from the local def and the import Baz(f); but *not* the import qualified Foo. pickGREs returns two GRE gre1: gre_lcl = True, gre_imp = [] gre2: gre_lcl = False, gre_imp = [ imported from Bar ] Now the the "ambiguous occurrence" message can correctly report how the ambiguity arises. -} pickGREs :: RdrName -> [GlobalRdrElt] -> [GlobalRdrElt] -- ^ Takes a list of GREs which have the right OccName 'x' -- Pick those GREs that are are in scope -- * Qualified, as 'M.x' if want_qual is Qual M _ -- * Unqualified, as 'x' if want_unqual is Unqual _ -- -- Return each such GRE, with its ImportSpecs filtered, to reflect -- how it is in scope qualifed or unqualified respectively. -- See Note [GRE filtering] pickGREs (Unqual {}) gres = mapMaybe pickUnqualGRE gres pickGREs (Qual mod _) gres = mapMaybe (pickQualGRE mod) gres pickGREs _ _ = [] -- I don't think this actually happens pickUnqualGRE :: GlobalRdrElt -> Maybe GlobalRdrElt pickUnqualGRE gre@(GRE { gre_lcl = lcl, gre_imp = iss }) | not lcl, null iss' = Nothing | otherwise = Just (gre { gre_imp = iss' }) where iss' = filter unQualSpecOK iss pickQualGRE :: ModuleName -> GlobalRdrElt -> Maybe GlobalRdrElt pickQualGRE mod 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 iss' = filter (qualSpecOK mod) iss lcl' = lcl && name_is_from mod n name_is_from :: ModuleName -> Name -> Bool name_is_from mod name = case nameModule_maybe name of Just n_mod -> moduleName n_mod == mod Nothing -> False pickGREsModExp :: ModuleName -> [GlobalRdrElt] -> [(GlobalRdrElt,GlobalRdrElt)] -- ^ Pick GREs that are in scope *both* qualified *and* unqualified -- Return each GRE that is, as a pair -- (qual_gre, unqual_gre) -- These two GREs are the original GRE with imports filtered to express how -- it is in scope qualified an unqualified respectively -- -- Used only for the 'module M' item in export list; -- see RnNames.exports_from_avail pickGREsModExp mod gres = mapMaybe (pickBothGRE mod) gres pickBothGRE :: ModuleName -> GlobalRdrElt -> Maybe (GlobalRdrElt, GlobalRdrElt) pickBothGRE mod gre@(GRE { gre_name = n }) | isBuiltInSyntax n = Nothing | Just gre1 <- pickQualGRE mod gre , Just gre2 <- pickUnqualGRE gre = Just (gre1, gre2) | otherwise = Nothing where -- isBuiltInSyntax filter out names for built-in syntax They -- just clutter up the environment (esp tuples), and the -- parser will generate Exact RdrNames for them, so the -- cluttered envt is no use. Really, it's only useful for -- GHC.Base and GHC.Tuple. -- 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 } }) {- ************************************************************************ * * ImportSpec * * ************************************************************************ -} -- | 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 bestImport :: [ImportSpec] -> ImportSpec -- Given a non-empty bunch of ImportSpecs, return the one that -- imported the item most specficially (e.g. by name), using -- textually-first as a tie breaker. This is used when reporting -- redundant imports bestImport iss = case sortBy best iss of (is:_) -> is [] -> pprPanic "bestImport" (ppr iss) where best :: ImportSpec -> ImportSpec -> Ordering -- Less means better best (ImpSpec { is_item = item1, is_decl = d1 }) (ImpSpec { is_item = item2, is_decl = d2 }) = best_item item1 item2 `thenCmp` (is_dloc d1 `compare` is_dloc d2) best_item :: ImpItemSpec -> ImpItemSpec -> Ordering best_item ImpAll ImpAll = EQ best_item ImpAll (ImpSome {}) = GT best_item (ImpSome {}) ImpAll = LT best_item (ImpSome { is_explicit = e1 }) (ImpSome { is_explicit = e2 }) = e2 `compare` e1 -- False < True, so if e1 is explicit and e2 is not, we get LT 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 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 [text "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 (text "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 = text "in" <+> quotes (ppr defining_mod) instance Outputable ImportSpec where ppr imp_spec = text "imported" <+> qual <+> text "from" <+> quotes (ppr (importSpecModule imp_spec)) <+> pprLoc (importSpecLoc imp_spec) where qual | is_qual (is_decl imp_spec) = text "qualified" | otherwise = empty pprLoc :: SrcSpan -> SDoc pprLoc (RealSrcSpan s) = text "at" <+> ppr s pprLoc (UnhelpfulSpan {}) = empty
nushio3/ghc
compiler/basicTypes/RdrName.hs
bsd-3-clause
43,942
0
16
12,037
8,173
4,349
3,824
515
5
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE GADTs #-} -- This module is full of orphans, unfortunately module GHCi.TH.Binary () where import Data.Binary import qualified Data.ByteString as B import GHC.Serialized import qualified Language.Haskell.TH as TH import qualified Language.Haskell.TH.Syntax as TH #if !MIN_VERSION_base(4,10,0) import Data.Typeable #endif -- Put these in a separate module because they take ages to compile instance Binary TH.Loc instance Binary TH.Name instance Binary TH.ModName instance Binary TH.NameFlavour instance Binary TH.PkgName instance Binary TH.NameSpace instance Binary TH.Module instance Binary TH.Info instance Binary TH.Type instance Binary TH.TyLit instance Binary TH.TyVarBndr instance Binary TH.Role instance Binary TH.Lit instance Binary TH.Range instance Binary TH.Stmt instance Binary TH.Pat instance Binary TH.Exp instance Binary TH.Dec instance Binary TH.Overlap instance Binary TH.DerivClause instance Binary TH.DerivStrategy instance Binary TH.Guard instance Binary TH.Body instance Binary TH.Match instance Binary TH.Fixity instance Binary TH.TySynEqn instance Binary TH.FunDep instance Binary TH.AnnTarget instance Binary TH.RuleBndr instance Binary TH.Phases instance Binary TH.RuleMatch instance Binary TH.Inline instance Binary TH.Pragma instance Binary TH.Safety instance Binary TH.Callconv instance Binary TH.Foreign instance Binary TH.Bang instance Binary TH.SourceUnpackedness instance Binary TH.SourceStrictness instance Binary TH.DecidedStrictness instance Binary TH.FixityDirection instance Binary TH.OccName instance Binary TH.Con instance Binary TH.AnnLookup instance Binary TH.ModuleInfo instance Binary TH.Clause instance Binary TH.InjectivityAnn instance Binary TH.FamilyResultSig instance Binary TH.TypeFamilyHead instance Binary TH.PatSynDir instance Binary TH.PatSynArgs -- We need Binary TypeRep for serializing annotations instance Binary Serialized where put (Serialized tyrep wds) = put tyrep >> put (B.pack wds) get = Serialized <$> get <*> (B.unpack <$> get) -- Typeable and related instances live in binary since GHC 8.2 #if !MIN_VERSION_base(4,10,0) instance Binary TyCon where put tc = put (tyConPackage tc) >> put (tyConModule tc) >> put (tyConName tc) get = mkTyCon3 <$> get <*> get <*> get instance Binary TypeRep where put type_rep = put (splitTyConApp type_rep) get = do (ty_con, child_type_reps) <- get return (mkTyConApp ty_con child_type_reps) #endif
shlevy/ghc
libraries/ghci/GHCi/TH/Binary.hs
bsd-3-clause
2,621
0
10
374
714
348
366
75
0
----------------------------------------------------------------------------- -- | -- Module : Data.SBV.Core.Symbolic -- Copyright : (c) Levent Erkok -- License : BSD3 -- Maintainer : [email protected] -- Stability : experimental -- -- Symbolic values ----------------------------------------------------------------------------- {-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeSynonymInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Data.SBV.Core.Symbolic ( NodeId(..) , SW(..), swKind, trueSW, falseSW , Op(..), PBOp(..), FPOp(..) , Quantifier(..), needsExistentials , RoundingMode(..) , SBVType(..), newUninterpreted, addAxiom , SVal(..) , svMkSymVar , ArrayContext(..), ArrayInfo , svToSW, svToSymSW, forceSWArg , SBVExpr(..), newExpr, isCodeGenMode , Cached, cache, uncache , ArrayIndex, uncacheAI , NamedSymVar , getSValPathCondition, extendSValPathCondition , getTableIndex , SBVPgm(..), Symbolic, runSymbolic, State(..), withNewIncState, IncState(..), incrementInternalCounter , inSMTMode, SBVRunMode(..), IStage(..), Result(..) , registerKind, registerLabel , addAssertion, addNewSMTOption, imposeConstraint, internalConstraint, internalVariable , SMTLibPgm(..), SMTLibVersion(..), smtLibVersionExtension , SolverCapabilities(..) , extractSymbolicSimulationState , OptimizeStyle(..), Objective(..), Penalty(..), objectiveName, addSValOptGoal , Query(..), QueryState(..) , SMTScript(..), Solver(..), SMTSolver(..), SMTResult(..), SMTModel(..), SMTConfig(..), SMTEngine , outputSVal , SArr(..), readSArr, writeSArr, mergeSArr, newSArr, eqSArr ) where import Control.Arrow (first, second, (***)) import Control.DeepSeq (NFData(..)) import Control.Monad (when, unless) import Control.Monad.Reader (MonadReader, ReaderT, ask, runReaderT) import Control.Monad.State.Lazy (MonadState, StateT(..)) import Control.Monad.Trans (MonadIO, liftIO) import Data.Char (isAlpha, isAlphaNum, toLower) import Data.IORef (IORef, newIORef, readIORef) import Data.List (intercalate, sortBy) import Data.Maybe (isJust, fromJust, fromMaybe) import Data.Time (getCurrentTime, UTCTime) import GHC.Stack import qualified Data.IORef as R (modifyIORef') import qualified Data.Generics as G (Data(..)) import qualified Data.IntMap as IMap (IntMap, empty, size, toAscList, lookup, insert, insertWith) import qualified Data.Map as Map (Map, empty, toList, size, insert, lookup) import qualified Data.Set as Set (Set, empty, toList, insert, member) import qualified Data.Foldable as F (toList) import qualified Data.Sequence as S (Seq, empty, (|>)) import System.Mem.StableName import Data.SBV.Core.Kind import Data.SBV.Core.Concrete import Data.SBV.SMT.SMTLibNames import Data.SBV.Utils.TDiff(Timing) import Data.SBV.Control.Types -- | A symbolic node id newtype NodeId = NodeId Int deriving (Eq, Ord) -- | A symbolic word, tracking it's signedness and size. data SW = SW !Kind !NodeId deriving (Eq, Ord) instance HasKind SW where kindOf (SW k _) = k instance Show SW where show (SW _ (NodeId n)) | n < 0 = "s_" ++ show (abs n) | True = 's' : show n -- | Kind of a symbolic word. swKind :: SW -> Kind swKind (SW k _) = k -- | Forcing an argument; this is a necessary evil to make sure all the arguments -- to an uninterpreted function are evaluated before called; the semantics of uinterpreted -- functions is necessarily strict; deviating from Haskell's forceSWArg :: SW -> IO () forceSWArg (SW k n) = k `seq` n `seq` return () -- | Constant False as an SW. Note that this value always occupies slot -2. falseSW :: SW falseSW = SW KBool $ NodeId (-2) -- | Constant True as an SW. Note that this value always occupies slot -1. trueSW :: SW trueSW = SW KBool $ NodeId (-1) -- | Symbolic operations data Op = Plus | Times | Minus | UNeg | Abs | Quot | Rem | Equal | NotEqual | LessThan | GreaterThan | LessEq | GreaterEq | Ite | And | Or | XOr | Not | Shl | Shr | Rol Int | Ror Int | Extract Int Int -- Extract i j: extract bits i to j. Least significant bit is 0 (big-endian) | Join -- Concat two words to form a bigger one, in the order given | LkUp (Int, Kind, Kind, Int) !SW !SW -- (table-index, arg-type, res-type, length of the table) index out-of-bounds-value | ArrEq Int Int -- Array equality | ArrRead Int | KindCast Kind Kind | Uninterpreted String | Label String -- Essentially no-op; useful for code generation to emit comments. | IEEEFP FPOp -- Floating-point ops, categorized separately | PseudoBoolean PBOp -- Pseudo-boolean ops, categorized separately deriving (Eq, Ord) -- | Floating point operations data FPOp = FP_Cast Kind Kind SW -- From-Kind, To-Kind, RoundingMode. This is "value" conversion | FP_Reinterpret Kind Kind -- From-Kind, To-Kind. This is bit-reinterpretation using IEEE-754 interchange format | FP_Abs | FP_Neg | FP_Add | FP_Sub | FP_Mul | FP_Div | FP_FMA | FP_Sqrt | FP_Rem | FP_RoundToIntegral | FP_Min | FP_Max | FP_ObjEqual | FP_IsNormal | FP_IsSubnormal | FP_IsZero | FP_IsInfinite | FP_IsNaN | FP_IsNegative | FP_IsPositive deriving (Eq, Ord) -- Note that the show instance maps to the SMTLib names. We need to make sure -- this mapping stays correct through SMTLib changes. The only exception -- is FP_Cast; where we handle different source/origins explicitly later on. instance Show FPOp where show (FP_Cast f t r) = "(FP_Cast: " ++ show f ++ " -> " ++ show t ++ ", using RM [" ++ show r ++ "])" show (FP_Reinterpret f t) = case (f, t) of (KBounded False 32, KFloat) -> "(_ to_fp 8 24)" (KBounded False 64, KDouble) -> "(_ to_fp 11 53)" _ -> error $ "SBV.FP_Reinterpret: Unexpected conversion: " ++ show f ++ " to " ++ show t show FP_Abs = "fp.abs" show FP_Neg = "fp.neg" show FP_Add = "fp.add" show FP_Sub = "fp.sub" show FP_Mul = "fp.mul" show FP_Div = "fp.div" show FP_FMA = "fp.fma" show FP_Sqrt = "fp.sqrt" show FP_Rem = "fp.rem" show FP_RoundToIntegral = "fp.roundToIntegral" show FP_Min = "fp.min" show FP_Max = "fp.max" show FP_ObjEqual = "=" show FP_IsNormal = "fp.isNormal" show FP_IsSubnormal = "fp.isSubnormal" show FP_IsZero = "fp.isZero" show FP_IsInfinite = "fp.isInfinite" show FP_IsNaN = "fp.isNaN" show FP_IsNegative = "fp.isNegative" show FP_IsPositive = "fp.isPositive" -- | Pseudo-boolean operations data PBOp = PB_AtMost Int -- ^ At most k | PB_AtLeast Int -- ^ At least k | PB_Exactly Int -- ^ Exactly k | PB_Le [Int] Int -- ^ At most k, with coefficients given. Generalizes PB_AtMost | PB_Ge [Int] Int -- ^ At least k, with coefficients given. Generalizes PB_AtLeast | PB_Eq [Int] Int -- ^ Exactly k, with coefficients given. Generalized PB_Exactly deriving (Eq, Ord, Show) -- Show instance for 'Op'. Note that this is largely for debugging purposes, not used -- for being read by any tool. instance Show Op where show Shl = "<<" show Shr = ">>" show (Rol i) = "<<<" ++ show i show (Ror i) = ">>>" ++ show i show (Extract i j) = "choose [" ++ show i ++ ":" ++ show j ++ "]" show (LkUp (ti, at, rt, l) i e) = "lookup(" ++ tinfo ++ ", " ++ show i ++ ", " ++ show e ++ ")" where tinfo = "table" ++ show ti ++ "(" ++ show at ++ " -> " ++ show rt ++ ", " ++ show l ++ ")" show (ArrEq i j) = "array_" ++ show i ++ " == array_" ++ show j show (ArrRead i) = "select array_" ++ show i show (KindCast fr to) = "cast_" ++ show fr ++ "_" ++ show to show (Uninterpreted i) = "[uninterpreted] " ++ i show (Label s) = "[label] " ++ s show (IEEEFP w) = show w show (PseudoBoolean p) = show p show op | Just s <- op `lookup` syms = s | True = error "impossible happened; can't find op!" where syms = [ (Plus, "+"), (Times, "*"), (Minus, "-"), (UNeg, "-"), (Abs, "abs") , (Quot, "quot") , (Rem, "rem") , (Equal, "=="), (NotEqual, "/=") , (LessThan, "<"), (GreaterThan, ">"), (LessEq, "<="), (GreaterEq, ">=") , (Ite, "if_then_else") , (And, "&"), (Or, "|"), (XOr, "^"), (Not, "~") , (Join, "#") ] -- | Quantifiers: forall or exists. Note that we allow -- arbitrary nestings. data Quantifier = ALL | EX deriving Eq -- | Are there any existential quantifiers? needsExistentials :: [Quantifier] -> Bool needsExistentials = (EX `elem`) -- | A simple type for SBV computations, used mainly for uninterpreted constants. -- We keep track of the signedness/size of the arguments. A non-function will -- have just one entry in the list. newtype SBVType = SBVType [Kind] deriving (Eq, Ord) instance Show SBVType where show (SBVType []) = error "SBV: internal error, empty SBVType" show (SBVType xs) = intercalate " -> " $ map show xs -- | A symbolic expression data SBVExpr = SBVApp !Op ![SW] deriving (Eq, Ord) -- | To improve hash-consing, take advantage of commutative operators by -- reordering their arguments. reorder :: SBVExpr -> SBVExpr reorder s = case s of SBVApp op [a, b] | isCommutative op && a > b -> SBVApp op [b, a] _ -> s where isCommutative :: Op -> Bool isCommutative o = o `elem` [Plus, Times, Equal, NotEqual, And, Or, XOr] -- Show instance for 'SBVExpr'. Again, only for debugging purposes. instance Show SBVExpr where show (SBVApp Ite [t, a, b]) = unwords ["if", show t, "then", show a, "else", show b] show (SBVApp Shl [a, i]) = unwords [show a, "<<", show i] show (SBVApp Shr [a, i]) = unwords [show a, ">>", show i] show (SBVApp (Rol i) [a]) = unwords [show a, "<<<", show i] show (SBVApp (Ror i) [a]) = unwords [show a, ">>>", show i] show (SBVApp (PseudoBoolean pb) args) = unwords (show pb : map show args) show (SBVApp op [a, b]) = unwords [show a, show op, show b] show (SBVApp op args) = unwords (show op : map show args) -- | A program is a sequence of assignments newtype SBVPgm = SBVPgm {pgmAssignments :: S.Seq (SW, SBVExpr)} -- | 'NamedSymVar' pairs symbolic words and user given/automatically generated names type NamedSymVar = (SW, String) -- | Style of optimization. Note that in the pareto case the user is allowed -- to specify a max number of fronts to query the solver for, since there might -- potentially be an infinite number of them and there is no way to know exactly -- how many ahead of time. If 'Nothing' is given, SBV will possibly loop forever -- if the number is really infinite. data OptimizeStyle = Lexicographic -- ^ Objectives are optimized in the order given, earlier objectives have higher priority. This is the default. | Independent -- ^ Each objective is optimized independently. | Pareto (Maybe Int) -- ^ Objectives are optimized according to pareto front: That is, no objective can be made better without making some other worse. deriving (Eq, Show) -- | Penalty for a soft-assertion. The default penalty is @1@, with all soft-assertions belonging -- to the same objective goal. A positive weight and an optional group can be provided by using -- the 'Penalty' constructor. data Penalty = DefaultPenalty -- ^ Default: Penalty of @1@ and no group attached | Penalty Rational (Maybe String) -- ^ Penalty with a weight and an optional group deriving Show -- | Objective of optimization. We can minimize, maximize, or give a soft assertion with a penalty -- for not satisfying it. data Objective a = Minimize String a -- ^ Minimize this metric | Maximize String a -- ^ Maximize this metric | AssertSoft String a Penalty -- ^ A soft assertion, with an associated penalty deriving (Show, Functor) -- | The name of the objective objectiveName :: Objective a -> String objectiveName (Minimize s _) = s objectiveName (Maximize s _) = s objectiveName (AssertSoft s _ _) = s -- | The state we keep track of as we interact with the solver data QueryState = QueryState { queryAsk :: Maybe Int -> String -> IO String , querySend :: Maybe Int -> String -> IO () , queryRetrieveResponse :: Maybe Int -> IO String , queryConfig :: SMTConfig , queryTerminate :: IO () , queryTimeOutValue :: Maybe Int , queryAssertionStackDepth :: Int } -- | A query is a user-guided mechanism to directly communicate and extract results from the solver. newtype Query a = Query (StateT State IO a) deriving (Applicative, Functor, Monad, MonadIO, MonadState State) instance NFData OptimizeStyle where rnf x = x `seq` () instance NFData Penalty where rnf DefaultPenalty = () rnf (Penalty p mbs) = rnf p `seq` rnf mbs `seq` () instance NFData a => NFData (Objective a) where rnf (Minimize s a) = rnf s `seq` rnf a `seq` () rnf (Maximize s a) = rnf s `seq` rnf a `seq` () rnf (AssertSoft s a p) = rnf s `seq` rnf a `seq` rnf p `seq` () -- | Result of running a symbolic computation data Result = Result { reskinds :: Set.Set Kind -- ^ kinds used in the program , resTraces :: [(String, CW)] -- ^ quick-check counter-example information (if any) , resUISegs :: [(String, [String])] -- ^ uninterpeted code segments , resInputs :: ([(Quantifier, NamedSymVar)], [NamedSymVar]) -- ^ inputs (possibly existential) + tracker vars , resConsts :: [(SW, CW)] -- ^ constants , resTables :: [((Int, Kind, Kind), [SW])] -- ^ tables (automatically constructed) (tableno, index-type, result-type) elts , resArrays :: [(Int, ArrayInfo)] -- ^ arrays (user specified) , resUIConsts :: [(String, SBVType)] -- ^ uninterpreted constants , resAxioms :: [(String, [String])] -- ^ axioms , resAsgns :: SBVPgm -- ^ assignments , resConstraints :: [(Maybe String, SW)] -- ^ additional constraints (boolean) , resAssertions :: [(String, Maybe CallStack, SW)] -- ^ assertions , resOutputs :: [SW] -- ^ outputs } -- Show instance for 'Result'. Only for debugging purposes. instance Show Result where -- If there's nothing interesting going on, just print the constant. Note that the -- definiton of interesting here is rather subjective; but essentially if we reduced -- the result to a single constant already, without any reference to anything. show Result{resConsts=cs, resOutputs=[r]} | Just c <- r `lookup` cs = show c show (Result kinds _ cgs is cs ts as uis axs xs cstrs asserts os) = intercalate "\n" $ (if null usorts then [] else "SORTS" : map (" " ++) usorts) ++ ["INPUTS"] ++ map shn (fst is) ++ (if null (snd is) then [] else "TRACKER VARS" : map (shn . (EX,)) (snd is)) ++ ["CONSTANTS"] ++ map shc cs ++ ["TABLES"] ++ map sht ts ++ ["ARRAYS"] ++ map sha as ++ ["UNINTERPRETED CONSTANTS"] ++ map shui uis ++ ["USER GIVEN CODE SEGMENTS"] ++ concatMap shcg cgs ++ ["AXIOMS"] ++ map shax axs ++ ["DEFINE"] ++ map (\(s, e) -> " " ++ shs s ++ " = " ++ show e) (F.toList (pgmAssignments xs)) ++ ["CONSTRAINTS"] ++ map ((" " ++) . shCstr) cstrs ++ ["ASSERTIONS"] ++ map ((" "++) . shAssert) asserts ++ ["OUTPUTS"] ++ sh2 os where sh2 :: Show a => [a] -> [String] sh2 = map ((" "++) . show) usorts = [sh s t | KUserSort s t <- Set.toList kinds] where sh s (Left _) = s sh s (Right es) = s ++ " (" ++ intercalate ", " es ++ ")" shs sw = show sw ++ " :: " ++ show (swKind sw) sht ((i, at, rt), es) = " Table " ++ show i ++ " : " ++ show at ++ "->" ++ show rt ++ " = " ++ show es shc (sw, cw) = " " ++ show sw ++ " = " ++ show cw shcg (s, ss) = ("Variable: " ++ s) : map (" " ++) ss shn (q, (sw, nm)) = " " ++ ni ++ " :: " ++ show (swKind sw) ++ ex ++ alias where ni = show sw ex | q == ALL = "" | True = ", existential" alias | ni == nm = "" | True = ", aliasing " ++ show nm sha (i, (nm, (ai, bi), ctx)) = " " ++ ni ++ " :: " ++ show ai ++ " -> " ++ show bi ++ alias ++ "\n Context: " ++ show ctx where ni = "array_" ++ show i alias | ni == nm = "" | True = ", aliasing " ++ show nm shui (nm, t) = " [uninterpreted] " ++ nm ++ " :: " ++ show t shax (nm, ss) = " -- user defined axiom: " ++ nm ++ "\n " ++ intercalate "\n " ss shCstr (Nothing, c) = show c shCstr (Just nm, c) = nm ++ ": " ++ show c shAssert (nm, stk, p) = " -- assertion: " ++ nm ++ " " ++ maybe "[No location]" #if MIN_VERSION_base(4,9,0) prettyCallStack #else showCallStack #endif stk ++ ": " ++ show p -- | The context of a symbolic array as created data ArrayContext = ArrayFree -- ^ A new array, the contents are uninitialized | ArrayMutate Int SW SW -- ^ An array created by mutating another array at a given cell | ArrayMerge SW Int Int -- ^ An array created by symbolically merging two other arrays instance Show ArrayContext where show ArrayFree = " initialized with random elements" show (ArrayMutate i a b) = " cloned from array_" ++ show i ++ " with " ++ show a ++ " :: " ++ show (swKind a) ++ " |-> " ++ show b ++ " :: " ++ show (swKind b) show (ArrayMerge s i j) = " merged arrays " ++ show i ++ " and " ++ show j ++ " on condition " ++ show s -- | Expression map, used for hash-consing type ExprMap = Map.Map SBVExpr SW -- | Constants are stored in a map, for hash-consing. The bool is needed to tell -0 from +0, sigh type CnstMap = Map.Map (Bool, CW) SW -- | Kinds used in the program; used for determining the final SMT-Lib logic to pick type KindSet = Set.Set Kind -- | Tables generated during a symbolic run type TableMap = Map.Map (Kind, Kind, [SW]) Int -- | Representation for symbolic arrays type ArrayInfo = (String, (Kind, Kind), ArrayContext) -- | Arrays generated during a symbolic run type ArrayMap = IMap.IntMap ArrayInfo -- | Uninterpreted-constants generated during a symbolic run type UIMap = Map.Map String SBVType -- | Code-segments for Uninterpreted-constants, as given by the user type CgMap = Map.Map String [String] -- | Cached values, implementing sharing type Cache a = IMap.IntMap [(StableName (State -> IO a), a)] -- | Stage of an interactive run data IStage = ISetup -- Before we initiate contact | IRun -- After the contact is started -- | Different means of running a symbolic piece of code data SBVRunMode = SMTMode IStage Bool SMTConfig -- ^ In regular mode, with a stage. Bool is True if this is SAT. | CodeGen -- ^ Code generation mode. | Concrete -- ^ Concrete simulation mode. -- Show instance for SBVRunMode; debugging purposes only instance Show SBVRunMode where show (SMTMode ISetup True _) = "Satisfiability setup" show (SMTMode IRun True _) = "Satisfiability" show (SMTMode ISetup False _) = "Proof setup" show (SMTMode IRun False _) = "Proof" show CodeGen = "Code generation" show Concrete = "Concrete evaluation" -- | Is this a CodeGen run? (i.e., generating code) isCodeGenMode :: State -> IO Bool isCodeGenMode State{runMode} = do rm <- readIORef runMode return $ case rm of Concrete{} -> False SMTMode{} -> False CodeGen -> True -- | The state in query mode, i.e., additional context data IncState = IncState { rNewInps :: IORef [NamedSymVar] -- always existential! , rNewKinds :: IORef KindSet , rNewConsts :: IORef CnstMap , rNewArrs :: IORef ArrayMap , rNewTbls :: IORef TableMap , rNewAsgns :: IORef SBVPgm } -- | Get a new IncState newIncState :: IO IncState newIncState = do is <- newIORef [] ks <- newIORef Set.empty nc <- newIORef Map.empty am <- newIORef IMap.empty tm <- newIORef Map.empty pgm <- newIORef (SBVPgm S.empty) return IncState { rNewInps = is , rNewKinds = ks , rNewConsts = nc , rNewArrs = am , rNewTbls = tm , rNewAsgns = pgm } -- | Get a new IncState withNewIncState :: State -> (State -> IO a) -> IO (IncState, a) withNewIncState st cont = do is <- newIncState R.modifyIORef' (rIncState st) (const is) r <- cont st finalIncState <- readIORef (rIncState st) return (finalIncState, r) -- | Return and clean and incState -- | The state of the symbolic interpreter data State = State { pathCond :: SVal -- ^ kind KBool , startTime :: UTCTime , runMode :: IORef SBVRunMode , rIncState :: IORef IncState , rCInfo :: IORef [(String, CW)] , rctr :: IORef Int , rUsedKinds :: IORef KindSet , rUsedLbls :: IORef (Set.Set String) , rinps :: IORef ([(Quantifier, NamedSymVar)], [NamedSymVar]) -- User defined, and internal existential , rConstraints :: IORef [(Maybe String, SW)] , routs :: IORef [SW] , rtblMap :: IORef TableMap , spgm :: IORef SBVPgm , rconstMap :: IORef CnstMap , rexprMap :: IORef ExprMap , rArrayMap :: IORef ArrayMap , rUIMap :: IORef UIMap , rCgMap :: IORef CgMap , raxioms :: IORef [(String, [String])] , rSMTOptions :: IORef [SMTOption] , rOptGoals :: IORef [Objective (SW, SW)] , rAsserts :: IORef [(String, Maybe CallStack, SW)] , rSWCache :: IORef (Cache SW) , rAICache :: IORef (Cache Int) , queryState :: IORef (Maybe QueryState) } -- NFData is a bit of a lie, but it's sufficient, most of the content is iorefs that we don't want to touch instance NFData State where rnf State{} = () -- | Get the current path condition getSValPathCondition :: State -> SVal getSValPathCondition = pathCond -- | Extend the path condition with the given test value. extendSValPathCondition :: State -> (SVal -> SVal) -> State extendSValPathCondition st f = st{pathCond = f (pathCond st)} -- | Are we running in proof mode? inSMTMode :: State -> IO Bool inSMTMode State{runMode} = do rm <- readIORef runMode return $ case rm of CodeGen -> False Concrete{} -> False SMTMode{} -> True -- | The "Symbolic" value. Either a constant (@Left@) or a symbolic -- value (@Right Cached@). Note that caching is essential for making -- sure sharing is preserved. data SVal = SVal !Kind !(Either CW (Cached SW)) instance HasKind SVal where kindOf (SVal k _) = k -- Show instance for 'SVal'. Not particularly "desirable", but will do if needed -- NB. We do not show the type info on constant KBool values, since there's no -- implicit "fromBoolean" applied to Booleans in Haskell; and thus a statement -- of the form "True :: SBool" is just meaningless. (There should be a fromBoolean!) instance Show SVal where show (SVal KBool (Left c)) = showCW False c show (SVal k (Left c)) = showCW False c ++ " :: " ++ show k show (SVal k (Right _)) = "<symbolic> :: " ++ show k -- | Equality constraint on SBV values. Not desirable since we can't really compare two -- symbolic values, but will do. instance Eq SVal where SVal _ (Left a) == SVal _ (Left b) = a == b a == b = error $ "Comparing symbolic bit-vectors; Use (.==) instead. Received: " ++ show (a, b) SVal _ (Left a) /= SVal _ (Left b) = a /= b a /= b = error $ "Comparing symbolic bit-vectors; Use (./=) instead. Received: " ++ show (a, b) -- | Things we do not support in interactive mode, at least for now! noInteractive :: [String] -> a noInteractive ss = error $ unlines $ "" : "*** Data.SBV: Unsupported interactive/query mode feature." : map ("*** " ++) ss ++ ["*** Data.SBV: Please report this as a feature request!"] -- | Modification of the state, but carefully handling the interactive tasks. -- Note that the state is always updated regardless of the mode, but we get -- to also perform extra operation in interactive mode. (Typically error out, but also simply -- ignore if it has no impact.) modifyState :: State -> (State -> IORef a) -> (a -> a) -> IO () -> IO () modifyState st@State{runMode} field update interactiveUpdate = do R.modifyIORef' (field st) update rm <- readIORef runMode case rm of SMTMode IRun _ _ -> interactiveUpdate _ -> return () -- | Modify the incremental state modifyIncState :: State -> (IncState -> IORef a) -> (a -> a) -> IO () modifyIncState State{rIncState} field update = do incState <- readIORef rIncState R.modifyIORef' (field incState) update -- | Increment the variable counter incrementInternalCounter :: State -> IO Int incrementInternalCounter st = do ctr <- readIORef (rctr st) modifyState st rctr (+1) (return ()) return ctr -- | Create a new uninterpreted symbol, possibly with user given code newUninterpreted :: State -> String -> SBVType -> Maybe [String] -> IO () newUninterpreted st nm t mbCode | null nm || not enclosed && (not (isAlpha (head nm)) || not (all validChar (tail nm))) = error $ "Bad uninterpreted constant name: " ++ show nm ++ ". Must be a valid identifier." | True = do uiMap <- readIORef (rUIMap st) case nm `Map.lookup` uiMap of Just t' -> when (t /= t') $ error $ "Uninterpreted constant " ++ show nm ++ " used at incompatible types\n" ++ " Current type : " ++ show t ++ "\n" ++ " Previously used at: " ++ show t' Nothing -> do modifyState st rUIMap (Map.insert nm t) $ noInteractive [ "Uninterpreted function introduction:" , " Named: " ++ nm , " Type : " ++ show t ] when (isJust mbCode) $ modifyState st rCgMap (Map.insert nm (fromJust mbCode)) (return ()) where validChar x = isAlphaNum x || x `elem` "_" enclosed = head nm == '|' && last nm == '|' && length nm > 2 && not (any (`elem` "|\\") (tail (init nm))) -- | Add a new sAssert based constraint addAssertion :: State -> Maybe CallStack -> String -> SW -> IO () addAssertion st cs msg cond = modifyState st rAsserts ((msg, cs, cond):) $ noInteractive [ "Named assertions (sAssert):" , " Tag: " ++ msg , " Loc: " ++ maybe "Unknown" show cs ] -- | Create an internal variable, which acts as an input but isn't visible to the user. -- Such variables are existentially quantified in a SAT context, and universally quantified -- in a proof context. internalVariable :: State -> Kind -> IO SW internalVariable st k = do (sw, nm) <- newSW st k rm <- readIORef (runMode st) let q = case rm of SMTMode _ True _ -> EX SMTMode _ False _ -> ALL CodeGen -> ALL Concrete{} -> ALL modifyState st rinps (first ((:) (q, (sw, "__internal_sbv_" ++ nm)))) $ noInteractive [ "Internal variable creation:" , " Named: " ++ nm ] return sw {-# INLINE internalVariable #-} -- | Create a new SW newSW :: State -> Kind -> IO (SW, String) newSW st k = do ctr <- incrementInternalCounter st let sw = SW k (NodeId ctr) registerKind st k return (sw, 's' : show ctr) {-# INLINE newSW #-} -- | Register a new kind with the system, used for uninterpreted sorts. -- NB: Is it safe to have new kinds in query mode? It could be that -- the new kind might introduce a constraint that effects the logic. For -- instance, if we're seeing 'Double' for the first time and using a BV -- logic, then things would fall apart. But this should be rare, and hopefully -- the 'success' checking mechanism will catch the rare cases where this -- is an issue. In either case, the user can always arrange for the right -- logic by calling 'setLogic' appropriately, so it seems safe to just -- allow for this. registerKind :: State -> Kind -> IO () registerKind st k | KUserSort sortName _ <- k, map toLower sortName `elem` smtLibReservedNames = error $ "SBV: " ++ show sortName ++ " is a reserved sort; please use a different name." | True = do ks <- readIORef (rUsedKinds st) unless (k `Set.member` ks) $ modifyState st rUsedKinds (Set.insert k) $ modifyIncState st rNewKinds (Set.insert k) -- | Register a new label with the system, making sure they are unique and have no '|'s in them registerLabel :: State -> String -> IO () registerLabel st nm | map toLower nm `elem` smtLibReservedNames = error $ "SBV: " ++ show nm ++ " is a reserved string; please use a different name." | '|' `elem` nm = error $ "SBV: " ++ show nm ++ " contains the character `|', which is not allowed!" | '\\' `elem` nm = error $ "SBV: " ++ show nm ++ " contains the character `\', which is not allowed!" | True = do old <- readIORef $ rUsedLbls st if nm `Set.member` old then error $ "SBV: " ++ show nm ++ " is used as a label multiple times. Please do not use duplicate names!" else modifyState st rUsedLbls (Set.insert nm) (return ()) -- | Create a new constant; hash-cons as necessary -- NB. For each constant, we also store weather it's negative-0 or not, -- as otherwise +0 == -0 and thus we'd confuse those entries. That's a -- bummer as we incur an extra boolean for this rare case, but it's simple -- and hopefully we don't generate a ton of constants in general. newConst :: State -> CW -> IO SW newConst st c = do constMap <- readIORef (rconstMap st) let key = (isNeg0 (cwVal c), c) case key `Map.lookup` constMap of Just sw -> return sw Nothing -> do let k = kindOf c (sw, _) <- newSW st k let ins = Map.insert key sw modifyState st rconstMap ins $ modifyIncState st rNewConsts ins return sw where isNeg0 (CWFloat f) = isNegativeZero f isNeg0 (CWDouble d) = isNegativeZero d isNeg0 _ = False {-# INLINE newConst #-} -- | Create a new table; hash-cons as necessary getTableIndex :: State -> Kind -> Kind -> [SW] -> IO Int getTableIndex st at rt elts = do let key = (at, rt, elts) tblMap <- readIORef (rtblMap st) case key `Map.lookup` tblMap of Just i -> return i _ -> do let i = Map.size tblMap upd = Map.insert key i modifyState st rtblMap upd $ modifyIncState st rNewTbls upd return i -- | Create a new expression; hash-cons as necessary newExpr :: State -> Kind -> SBVExpr -> IO SW newExpr st k app = do let e = reorder app exprMap <- readIORef (rexprMap st) case e `Map.lookup` exprMap of Just sw -> return sw Nothing -> do (sw, _) <- newSW st k let append (SBVPgm xs) = SBVPgm (xs S.|> (sw, e)) modifyState st spgm append $ modifyIncState st rNewAsgns append modifyState st rexprMap (Map.insert e sw) (return ()) return sw {-# INLINE newExpr #-} -- | Convert a symbolic value to a symbolic-word svToSW :: State -> SVal -> IO SW svToSW st (SVal _ (Left c)) = newConst st c svToSW st (SVal _ (Right f)) = uncache f st -- | Convert a symbolic value to an SW, inside the Symbolic monad svToSymSW :: SVal -> Symbolic SW svToSymSW sbv = do st <- ask liftIO $ svToSW st sbv ------------------------------------------------------------------------- -- * Symbolic Computations ------------------------------------------------------------------------- -- | A Symbolic computation. Represented by a reader monad carrying the -- state of the computation, layered on top of IO for creating unique -- references to hold onto intermediate results. newtype Symbolic a = Symbolic (ReaderT State IO a) deriving (Applicative, Functor, Monad, MonadIO, MonadReader State) -- | Create a symbolic value, based on the quantifier we have. If an -- explicit quantifier is given, we just use that. If not, then we -- pick the quantifier appropriately based on the run-mode. -- @randomCW@ is used for generating random values for this variable -- when used for 'quickCheck' or 'genTest' purposes. svMkSymVar :: Maybe Quantifier -> Kind -> Maybe String -> State -> IO SVal svMkSymVar = svMkSymVarGen False -- | Create an existentially quantified tracker variable svMkTrackerVar :: Kind -> String -> State -> IO SVal svMkTrackerVar k nm = svMkSymVarGen True (Just EX) k (Just nm) -- | Create a symbolic value, based on the quantifier we have. If an -- explicit quantifier is given, we just use that. If not, then we -- pick the quantifier appropriately based on the run-mode. -- @randomCW@ is used for generating random values for this variable -- when used for 'quickCheck' or 'genTest' purposes. svMkSymVarGen :: Bool -> Maybe Quantifier -> Kind -> Maybe String -> State -> IO SVal svMkSymVarGen isTracker mbQ k mbNm st = do rm <- readIORef (runMode st) let varInfo = case mbNm of Nothing -> ", of type " ++ show k Just nm -> ", while defining " ++ nm ++ " :: " ++ show k disallow what = error $ "Data.SBV: Unsupported: " ++ what ++ varInfo ++ " in mode: " ++ show rm noUI cont | isUninterpreted k = disallow "Uninterpreted sorts" | True = cont mkS q = do (sw, internalName) <- newSW st k let nm = fromMaybe internalName mbNm introduceUserName st isTracker nm k q sw mkC = do cw <- randomCW k do registerKind st k modifyState st rCInfo ((fromMaybe "_" mbNm, cw):) (return ()) return $ SVal k (Left cw) case (mbQ, rm) of (Just q, SMTMode{} ) -> mkS q (Nothing, SMTMode _ isSAT _) -> mkS (if isSAT then EX else ALL) (Just EX, CodeGen{}) -> disallow "Existentially quantified variables" (_ , CodeGen) -> noUI $ mkS ALL -- code generation, pick universal (Just EX, Concrete{}) -> disallow "Existentially quantified variables" (_ , Concrete{}) -> noUI mkC -- | Introduce a new user name. We die if repeated. introduceUserName :: State -> Bool -> String -> Kind -> Quantifier -> SW -> IO SVal introduceUserName st isTracker nm k q sw = do (is, ints) <- readIORef (rinps st) if nm `elem` [n | (_, (_, n)) <- is] ++ [n | (_, n) <- ints] then error $ "SBV: Repeated user given name: " ++ show nm ++ ". Please use unique names." else if isTracker && q == ALL then error $ "SBV: Impossible happened! A universally quantified tracker variable is being introduced: " ++ show nm else do let newInp olds = case q of EX -> (sw, nm) : olds ALL -> noInteractive [ "Adding a new universally quantified variable: " , " Name : " ++ show nm , " Kind : " ++ show k , " Quantifier: Universal" , " Node : " ++ show sw , "Only existential variables are supported in query mode." ] if isTracker then modifyState st rinps (second ((:) (sw, nm))) $ noInteractive ["Adding a new tracker variable in interactive mode: " ++ show nm] else modifyState st rinps (first ((:) (q, (sw, nm)))) $ modifyIncState st rNewInps newInp return $ SVal k $ Right $ cache (const (return sw)) -- | Add a user specified axiom to the generated SMT-Lib file. The first argument is a mere -- string, use for commenting purposes. The second argument is intended to hold the multiple-lines -- of the axiom text as expressed in SMT-Lib notation. Note that we perform no checks on the axiom -- itself, to see whether it's actually well-formed or is sensical by any means. -- A separate formalization of SMT-Lib would be very useful here. addAxiom :: String -> [String] -> Symbolic () addAxiom nm ax = do st <- ask liftIO $ modifyState st raxioms ((nm, ax) :) $ noInteractive [ "Adding a new axiom:" , " Named: " ++ show nm , " Axiom: " ++ unlines ax ] -- | Run a symbolic computation, and return a extra value paired up with the 'Result' runSymbolic :: SBVRunMode -> Symbolic a -> IO (a, Result) runSymbolic currentRunMode (Symbolic c) = do currTime <- getCurrentTime rm <- newIORef currentRunMode ctr <- newIORef (-2) -- start from -2; False and True will always occupy the first two elements cInfo <- newIORef [] pgm <- newIORef (SBVPgm S.empty) emap <- newIORef Map.empty cmap <- newIORef Map.empty inps <- newIORef ([], []) outs <- newIORef [] tables <- newIORef Map.empty arrays <- newIORef IMap.empty uis <- newIORef Map.empty cgs <- newIORef Map.empty axioms <- newIORef [] swCache <- newIORef IMap.empty aiCache <- newIORef IMap.empty usedKinds <- newIORef Set.empty usedLbls <- newIORef Set.empty cstrs <- newIORef [] smtOpts <- newIORef [] optGoals <- newIORef [] asserts <- newIORef [] istate <- newIORef =<< newIncState qstate <- newIORef Nothing let st = State { runMode = rm , startTime = currTime , pathCond = SVal KBool (Left trueCW) , rIncState = istate , rCInfo = cInfo , rctr = ctr , rUsedKinds = usedKinds , rUsedLbls = usedLbls , rinps = inps , routs = outs , rtblMap = tables , spgm = pgm , rconstMap = cmap , rArrayMap = arrays , rexprMap = emap , rUIMap = uis , rCgMap = cgs , raxioms = axioms , rSWCache = swCache , rAICache = aiCache , rConstraints = cstrs , rSMTOptions = smtOpts , rOptGoals = optGoals , rAsserts = asserts , queryState = qstate } _ <- newConst st falseCW -- s(-2) == falseSW _ <- newConst st trueCW -- s(-1) == trueSW r <- runReaderT c st res <- extractSymbolicSimulationState st -- Clean-up after ourselves qs <- readIORef qstate case qs of Nothing -> return () Just QueryState{queryTerminate} -> queryTerminate return (r, res) -- | Grab the program from a running symbolic simulation state. extractSymbolicSimulationState :: State -> IO Result extractSymbolicSimulationState st@State{ spgm=pgm, rinps=inps, routs=outs, rtblMap=tables, rArrayMap=arrays, rUIMap=uis, raxioms=axioms , rAsserts=asserts, rUsedKinds=usedKinds, rCgMap=cgs, rCInfo=cInfo, rConstraints=cstrs } = do SBVPgm rpgm <- readIORef pgm inpsO <- (reverse *** reverse) <$> readIORef inps outsO <- reverse <$> readIORef outs let swap (a, b) = (b, a) swapc ((_, a), b) = (b, a) cmp (a, _) (b, _) = a `compare` b arrange (i, (at, rt, es)) = ((i, at, rt), es) cnsts <- (sortBy cmp . map swapc . Map.toList) <$> readIORef (rconstMap st) tbls <- (map arrange . sortBy cmp . map swap . Map.toList) <$> readIORef tables arrs <- IMap.toAscList <$> readIORef arrays unint <- Map.toList <$> readIORef uis axs <- reverse <$> readIORef axioms knds <- readIORef usedKinds cgMap <- Map.toList <$> readIORef cgs traceVals <- reverse <$> readIORef cInfo extraCstrs <- reverse <$> readIORef cstrs assertions <- reverse <$> readIORef asserts return $ Result knds traceVals cgMap inpsO cnsts tbls arrs unint axs (SBVPgm rpgm) extraCstrs assertions outsO -- | Add a new option addNewSMTOption :: SMTOption -> Symbolic () addNewSMTOption o = do st <- ask liftIO $ modifyState st rSMTOptions (o:) (return ()) -- | Handling constraints imposeConstraint :: Maybe String -> SVal -> Symbolic () imposeConstraint mbNm c = do st <- ask rm <- liftIO $ readIORef (runMode st) case rm of CodeGen -> error "SBV: constraints are not allowed in code-generation" _ -> do () <- case mbNm of Nothing -> return () Just nm -> liftIO $ registerLabel st nm liftIO $ internalConstraint st mbNm c -- | Require a boolean condition to be true in the state. Only used for internal purposes. internalConstraint :: State -> Maybe String -> SVal -> IO () internalConstraint st mbNm b = do v <- svToSW st b modifyState st rConstraints ((mbNm, v):) $ noInteractive [ "Adding an internal constraint:" , " Named: " ++ fromMaybe "<unnamed>" mbNm ] -- | Add an optimization goal addSValOptGoal :: Objective SVal -> Symbolic () addSValOptGoal obj = do st <- ask -- create the tracking variable here for the metric let mkGoal nm orig = liftIO $ do origSW <- svToSW st orig track <- svMkTrackerVar (kindOf orig) nm st trackSW <- svToSW st track return (origSW, trackSW) let walk (Minimize nm v) = Minimize nm <$> mkGoal nm v walk (Maximize nm v) = Maximize nm <$> mkGoal nm v walk (AssertSoft nm v mbP) = flip (AssertSoft nm) mbP <$> mkGoal nm v obj' <- walk obj liftIO $ modifyState st rOptGoals (obj' :) $ noInteractive [ "Adding an optimization objective:" , " Objective: " ++ show obj ] -- | Mark an interim result as an output. Useful when constructing Symbolic programs -- that return multiple values, or when the result is programmatically computed. outputSVal :: SVal -> Symbolic () outputSVal (SVal _ (Left c)) = do st <- ask sw <- liftIO $ newConst st c liftIO $ modifyState st routs (sw:) (return ()) outputSVal (SVal _ (Right f)) = do st <- ask sw <- liftIO $ uncache f st liftIO $ modifyState st routs (sw:) (return ()) --------------------------------------------------------------------------------- -- * Symbolic Arrays --------------------------------------------------------------------------------- -- | Arrays implemented in terms of SMT-arrays: <http://smtlib.cs.uiowa.edu/theories-ArraysEx.shtml> -- -- * Maps directly to SMT-lib arrays -- -- * Reading from an unintialized value is OK and yields an unspecified result -- -- * Can check for equality of these arrays -- -- * Cannot quick-check theorems using @SArr@ values -- -- * Typically slower as it heavily relies on SMT-solving for the array theory -- data SArr = SArr (Kind, Kind) (Cached ArrayIndex) -- | Read the array element at @a@ readSArr :: SArr -> SVal -> SVal readSArr (SArr (_, bk) f) a = SVal bk $ Right $ cache r where r st = do arr <- uncacheAI f st i <- svToSW st a newExpr st bk (SBVApp (ArrRead arr) [i]) -- | Update the element at @a@ to be @b@ writeSArr :: SArr -> SVal -> SVal -> SArr writeSArr (SArr ainfo f) a b = SArr ainfo $ cache g where g st = do arr <- uncacheAI f st addr <- svToSW st a val <- svToSW st b amap <- readIORef (rArrayMap st) let j = IMap.size amap upd = IMap.insert j ("array_" ++ show j, ainfo, ArrayMutate arr addr val) j `seq` modifyState st rArrayMap upd $ modifyIncState st rNewArrs upd return j -- | Merge two given arrays on the symbolic condition -- Intuitively: @mergeArrays cond a b = if cond then a else b@. -- Merging pushes the if-then-else choice down on to elements mergeSArr :: SVal -> SArr -> SArr -> SArr mergeSArr t (SArr ainfo a) (SArr _ b) = SArr ainfo $ cache h where h st = do ai <- uncacheAI a st bi <- uncacheAI b st ts <- svToSW st t amap <- readIORef (rArrayMap st) let k = IMap.size amap upd = IMap.insert k ("array_" ++ show k, ainfo, ArrayMerge ts ai bi) k `seq` modifyState st rArrayMap upd $ modifyIncState st rNewArrs upd return k -- | Create a named new array, with an optional initial value newSArr :: (Kind, Kind) -> (Int -> String) -> Symbolic SArr newSArr ainfo mkNm = do st <- ask amap <- liftIO $ readIORef $ rArrayMap st let i = IMap.size amap nm = mkNm i upd = IMap.insert i (nm, ainfo, ArrayFree) liftIO $ modifyState st rArrayMap upd $ modifyIncState st rNewArrs upd return $ SArr ainfo $ cache $ const $ return i -- | Compare two arrays for equality eqSArr :: SArr -> SArr -> SVal eqSArr (SArr _ a) (SArr _ b) = SVal KBool $ Right $ cache c where c st = do ai <- uncacheAI a st bi <- uncacheAI b st newExpr st KBool (SBVApp (ArrEq ai bi) []) --------------------------------------------------------------------------------- -- * Cached values --------------------------------------------------------------------------------- -- | We implement a peculiar caching mechanism, applicable to the use case in -- implementation of SBV's. Whenever we do a state based computation, we do -- not want to keep on evaluating it in the then-current state. That will -- produce essentially a semantically equivalent value. Thus, we want to run -- it only once, and reuse that result, capturing the sharing at the Haskell -- level. This is similar to the "type-safe observable sharing" work, but also -- takes into the account of how symbolic simulation executes. -- -- See Andy Gill's type-safe obervable sharing trick for the inspiration behind -- this technique: <http://ittc.ku.edu/~andygill/paper.php?label=DSLExtract09> -- -- Note that this is *not* a general memo utility! newtype Cached a = Cached (State -> IO a) -- | Cache a state-based computation cache :: (State -> IO a) -> Cached a cache = Cached -- | Uncache a previously cached computation uncache :: Cached SW -> State -> IO SW uncache = uncacheGen rSWCache -- | An array index is simple an int value type ArrayIndex = Int -- | Uncache, retrieving array indexes uncacheAI :: Cached ArrayIndex -> State -> IO ArrayIndex uncacheAI = uncacheGen rAICache -- | Generic uncaching. Note that this is entirely safe, since we do it in the IO monad. uncacheGen :: (State -> IORef (Cache a)) -> Cached a -> State -> IO a uncacheGen getCache (Cached f) st = do let rCache = getCache st stored <- readIORef rCache sn <- f `seq` makeStableName f let h = hashStableName sn case maybe Nothing (sn `lookup`) (h `IMap.lookup` stored) of Just r -> return r Nothing -> do r <- f st r `seq` R.modifyIORef' rCache (IMap.insertWith (++) h [(sn, r)]) return r -- | Representation of SMTLib Program versions. As of June 2015, we're dropping support -- for SMTLib1, and supporting SMTLib2 only. We keep this data-type around in case -- SMTLib3 comes along and we want to support 2 and 3 simultaneously. data SMTLibVersion = SMTLib2 deriving (Bounded, Enum, Eq, Show) -- | The extension associated with the version smtLibVersionExtension :: SMTLibVersion -> String smtLibVersionExtension SMTLib2 = "smt2" -- | Representation of an SMT-Lib program. In between pre and post goes the refuted models data SMTLibPgm = SMTLibPgm SMTLibVersion [String] instance NFData SMTLibVersion where rnf a = a `seq` () instance NFData SMTLibPgm where rnf (SMTLibPgm v p) = rnf v `seq` rnf p `seq` () instance Show SMTLibPgm where show (SMTLibPgm _ pre) = intercalate "\n" pre -- Other Technicalities.. instance NFData CW where rnf (CW x y) = x `seq` y `seq` () instance NFData GeneralizedCW where rnf (ExtendedCW e) = e `seq` () rnf (RegularCW c) = c `seq` () #if MIN_VERSION_base(4,9,0) #else -- Can't really force this, but not a big deal instance NFData CallStack where rnf _ = () #endif instance NFData Result where rnf (Result kindInfo qcInfo cgs inps consts tbls arrs uis axs pgm cstr asserts outs) = rnf kindInfo `seq` rnf qcInfo `seq` rnf cgs `seq` rnf inps `seq` rnf consts `seq` rnf tbls `seq` rnf arrs `seq` rnf uis `seq` rnf axs `seq` rnf pgm `seq` rnf cstr `seq` rnf asserts `seq` rnf outs instance NFData Kind where rnf a = seq a () instance NFData ArrayContext where rnf a = seq a () instance NFData SW where rnf a = seq a () instance NFData SBVExpr where rnf a = seq a () instance NFData Quantifier where rnf a = seq a () instance NFData SBVType where rnf a = seq a () instance NFData SBVPgm where rnf a = seq a () instance NFData (Cached a) where rnf (Cached f) = f `seq` () instance NFData SVal where rnf (SVal x y) = rnf x `seq` rnf y `seq` () instance NFData SMTResult where rnf Unsatisfiable{} = () rnf (Satisfiable _ xs) = rnf xs `seq` () rnf (SatExtField _ xs) = rnf xs `seq` () rnf (Unknown _ xs) = rnf xs `seq` () rnf (ProofError _ xs) = rnf xs `seq` () instance NFData SMTModel where rnf (SMTModel objs assocs) = rnf objs `seq` rnf assocs `seq` () instance NFData SMTScript where rnf (SMTScript b m) = rnf b `seq` rnf m `seq` () -- | Translation tricks needed for specific capabilities afforded by each solver data SolverCapabilities = SolverCapabilities { supportsQuantifiers :: Bool -- ^ Support for SMT-Lib2 style quantifiers? , supportsUninterpretedSorts :: Bool -- ^ Support for SMT-Lib2 style uninterpreted-sorts , supportsUnboundedInts :: Bool -- ^ Support for unbounded integers? , supportsReals :: Bool -- ^ Support for reals? , supportsApproxReals :: Bool -- ^ Supports printing of approximations of reals? , supportsIEEE754 :: Bool -- ^ Support for floating point numbers? , supportsOptimization :: Bool -- ^ Support for optimization routines? , supportsPseudoBooleans :: Bool -- ^ Support for pseudo-boolean operations? , supportsCustomQueries :: Bool -- ^ Support for interactive queries per SMT-Lib? , supportsGlobalDecls :: Bool -- ^ Support for global decls, needed for push-pop. } -- | Rounding mode to be used for the IEEE floating-point operations. -- Note that Haskell's default is 'RoundNearestTiesToEven'. If you use -- a different rounding mode, then the counter-examples you get may not -- match what you observe in Haskell. data RoundingMode = RoundNearestTiesToEven -- ^ Round to nearest representable floating point value. -- If precisely at half-way, pick the even number. -- (In this context, /even/ means the lowest-order bit is zero.) | RoundNearestTiesToAway -- ^ Round to nearest representable floating point value. -- If precisely at half-way, pick the number further away from 0. -- (That is, for positive values, pick the greater; for negative values, pick the smaller.) | RoundTowardPositive -- ^ Round towards positive infinity. (Also known as rounding-up or ceiling.) | RoundTowardNegative -- ^ Round towards negative infinity. (Also known as rounding-down or floor.) | RoundTowardZero -- ^ Round towards zero. (Also known as truncation.) deriving (Eq, Ord, Show, Read, G.Data, Bounded, Enum) -- | 'RoundingMode' kind instance HasKind RoundingMode -- | Solver configuration. See also 'z3', 'yices', 'cvc4', 'boolector', 'mathSAT', etc. which are instantiations of this type for those solvers, with -- reasonable defaults. In particular, custom configuration can be created by varying those values. (Such as @z3{verbose=True}@.) -- -- Most fields are self explanatory. The notion of precision for printing algebraic reals stems from the fact that such values does -- not necessarily have finite decimal representations, and hence we have to stop printing at some depth. It is important to -- emphasize that such values always have infinite precision internally. The issue is merely with how we print such an infinite -- precision value on the screen. The field 'printRealPrec' controls the printing precision, by specifying the number of digits after -- the decimal point. The default value is 16, but it can be set to any positive integer. -- -- When printing, SBV will add the suffix @...@ at the and of a real-value, if the given bound is not sufficient to represent the real-value -- exactly. Otherwise, the number will be written out in standard decimal notation. Note that SBV will always print the whole value if it -- is precise (i.e., if it fits in a finite number of digits), regardless of the precision limit. The limit only applies if the representation -- of the real value is not finite, i.e., if it is not rational. -- -- The 'printBase' field can be used to print numbers in base 2, 10, or 16. If base 2 or 16 is used, then floating-point values will -- be printed in their internal memory-layout format as well, which can come in handy for bit-precise analysis. data SMTConfig = SMTConfig { verbose :: Bool -- ^ Debug mode , timing :: Timing -- ^ Print timing information on how long different phases took (construction, solving, etc.) , printBase :: Int -- ^ Print integral literals in this base (2, 10, and 16 are supported.) , printRealPrec :: Int -- ^ Print algebraic real values with this precision. (SReal, default: 16) , satCmd :: String -- ^ Usually "(check-sat)". However, users might tweak it based on solver characteristics. , allSatMaxModelCount :: Maybe Int -- ^ In an allSat call, return at most this many models. If nothing, return all. , isNonModelVar :: String -> Bool -- ^ When constructing a model, ignore variables whose name satisfy this predicate. (Default: (const False), i.e., don't ignore anything) , transcript :: Maybe FilePath -- ^ If Just, the entire interaction will be recorded as a playable file (for debugging purposes mostly) , smtLibVersion :: SMTLibVersion -- ^ What version of SMT-lib we use for the tool , solver :: SMTSolver -- ^ The actual SMT solver. , roundingMode :: RoundingMode -- ^ Rounding mode to use for floating-point conversions , solverSetOptions :: [SMTOption] -- ^ Options to set as we start the solver , ignoreExitCode :: Bool -- ^ If true, we shall ignore the exit code upon exit. Otherwise we require ExitSuccess. , redirectVerbose :: Maybe FilePath -- ^ Redirect the verbose output to this file if given. If Nothing, stdout is implied. } -- We're just seq'ing top-level here, it shouldn't really matter. (i.e., no need to go deeper.) instance NFData SMTConfig where rnf SMTConfig{} = () -- | A model, as returned by a solver data SMTModel = SMTModel { modelObjectives :: [(String, GeneralizedCW)] -- ^ Mapping of symbolic values to objective values. , modelAssocs :: [(String, CW)] -- ^ Mapping of symbolic values to constants. } deriving Show -- | The result of an SMT solver call. Each constructor is tagged with -- the 'SMTConfig' that created it so that further tools can inspect it -- and build layers of results, if needed. For ordinary uses of the library, -- this type should not be needed, instead use the accessor functions on -- it. (Custom Show instances and model extractors.) data SMTResult = Unsatisfiable SMTConfig -- ^ Unsatisfiable | Satisfiable SMTConfig SMTModel -- ^ Satisfiable with model | SatExtField SMTConfig SMTModel -- ^ Prover returned a model, but in an extension field containing Infinite/epsilon | Unknown SMTConfig String -- ^ Prover returned unknown, with the given reason | ProofError SMTConfig [String] -- ^ Prover errored out -- | A script, to be passed to the solver. data SMTScript = SMTScript { scriptBody :: String -- ^ Initial feed , scriptModel :: [String] -- ^ Continuation script, to extract results } -- | An SMT engine type SMTEngine = forall res. SMTConfig -- ^ current configuration -> State -- ^ the state in which to run the engine -> String -- ^ program -> (State -> IO res) -- ^ continuation -> IO res -- | Solvers that SBV is aware of data Solver = Z3 | Yices | Boolector | CVC4 | MathSAT | ABC deriving (Show, Enum, Bounded) -- | An SMT solver data SMTSolver = SMTSolver { name :: Solver -- ^ The solver in use , executable :: String -- ^ The path to its executable , options :: SMTConfig -> [String] -- ^ Options to provide to the solver , engine :: SMTEngine -- ^ The solver engine, responsible for interpreting solver output , capabilities :: SolverCapabilities -- ^ Various capabilities of the solver } {-# ANN type FPOp ("HLint: ignore Use camelCase" :: String) #-} {-# ANN type PBOp ("HLint: ignore Use camelCase" :: String) #-}
josefs/sbv
Data/SBV/Core/Symbolic.hs
bsd-3-clause
64,844
0
34
22,141
14,154
7,558
6,596
926
8
{-# LANGUAGE TemplateHaskell, GeneralizedNewtypeDeriving, DeriveDataTypeable, TypeFamilies #-} module Happstack.Auth.Internal.Data.Sessions where import Data.Data import Data.SafeCopy import qualified Data.Map as M import Happstack.Auth.Internal.Data.SessionKey data Sessions a = Sessions { unsession :: M.Map SessionKey a } deriving (Read,Show,Eq,Typeable,Data) deriveSafeCopy 1 'base ''Sessions
mcmaniac/happstack-auth
src/Happstack/Auth/Internal/Data/Sessions.hs
bsd-3-clause
431
0
10
73
95
57
38
10
0
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-} module Compiler.Hoopl.Stream where import Control.Monad import Test.QuickCheck type Stream s a = s -> Maybe (Pair s a) data Pair s a = Pair a (Stream s a) instance Show (s -> Maybe (Pair s a)) where show _ = "<function>" instance (Arbitrary a, Arbitrary s, CoArbitrary s) => Arbitrary (Pair s a) where arbitrary = liftM2 Pair arbitrary arbitrary shrink (Pair a f) = [Pair a' f' | a' <- shrink a, f' <- shrink f] emptyS :: Stream s a emptyS = const Nothing thenS :: Stream s a -> Stream s a -> Stream s a s1 `thenS` s2 = \s -> case s1 s of Nothing -> s2 s Just (Pair a s1') -> Just $ Pair a (s1' `thenS` s2) iterS :: Stream s a -> Stream s a iterS stream = \s -> case stream s of Nothing -> Nothing Just (Pair a s') -> Just $ Pair a (s' `thenS` iterS stream) elems :: s -> Stream s a -> [a] elems s f = case f s of Nothing -> [] Just (Pair a f) -> a : elems s f law1 :: Eq a => Int -> s -> Stream s a -> Bool law1 n sigma stream = iterS stream `eq` (stream `thenS` iterS stream) where s `eq` s' = take n (elems sigma s) == take n (elems sigma s') law2 :: Bool law2 = iterS emptyS `eq` (emptyS :: Stream () Int) where s `eq` s' = elems () s == elems () s' ---------------------------------------------------------------- -- list analogy emptyL :: [a] emptyL = [] thenL :: [a] -> [a] -> [a] thenL = (++) iterL :: [a] -> [a] iterL [] = [] iterL (x:xs) = x : (xs `thenL` iterL (x:xs)) law1' :: Eq a => Int -> [a] -> Bool law1' n l = iterL l `eq` (l `thenL` iterL l) where xs `eq` ys = take n xs == take n ys law2' :: Bool law2' = iterL emptyL == (emptyL :: [Int])
ezyang/hoopl
src/Compiler/Hoopl/Stream.hs
bsd-3-clause
1,765
0
13
492
853
445
408
42
2
module Data.Expression.Inverse where import Prelude (Eq, Show, error, otherwise, show, undefined, ($), (++), (==)) import Domains.Applicable import Domains.Exponentiative import Domains.Field import Domains.Trigonometric import Data.Expression {-# ANN module "HLint: ignore Redundant bracket" #-} {-# ANN module "HLint: ignore Avoid lambda" #-} inv2 :: (Eq a, Field a, Exponentiative a, Trigonometric a, Applicable a) => Fn a -> (Expression a -> Expression a) inv2 f = case (name_ f) of "ln" -> exp "exp" -> ln "sqrt" -> \x -> x ^ two "sin" -> asin "cos" -> acos "tan" -> atan "asin" -> sin "acos" -> cos "atan" -> tan inverse :: (Show a, Eq a, Field a, Exponentiative a, Trigonometric a, Applicable a) => Expression a -> Expression a inverse (Lambda var body) = rec body where rec e = case e of (Const _) -> undefined (Var x) | e == var -> var ~> var | otherwise -> undefined (App f a) -> var ~> apply (rec a) (apply (inverse f) var) (Sum (Const a) b) -> var ~> apply (rec b) (neg (Const a) + var) (Sum a (Const b)) -> var ~> apply (rec a) (var - Const b) (Sum _ _) -> undefined (Neg a) -> var ~> apply (rec a) (neg var) (Prd (Const a) b) -> var ~> apply (rec b) (reciprocal (Const a) * var) (Prd a (Const b)) -> var ~> apply (rec a) (var / Const b) (Prd _ _) -> undefined (Rcp a) -> var ~> apply (rec a) (reciprocal var) (Pow a (Const n)) -> var ~> apply (rec a) (var ^ reciprocal (Const n)) (Pow (Const a) n) -> var ~> apply (rec n) (log (Const a) var) (Pow _ _) -> undefined inverse (Fun f) = let var = Var "x" in var ~> inv2 f var inverse e = error $ "Error: inverse " ++ show e
pmilne/algebra
src/Data/Expression/Inverse.hs
bsd-3-clause
1,919
0
16
647
844
427
417
45
14
{-# LANGUAGE GADTs #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE ImplicitParams #-} {-# LANGUAGE ViewPatterns #-} module SAWScript.HeapsterBuiltins ( heapster_init_env , heapster_init_env_debug , heapster_init_env_from_file , heapster_init_env_from_file_debug , heapster_init_env_for_files , heapster_init_env_for_files_debug , load_sawcore_from_file , heapster_get_cfg , heapster_typecheck_fun , heapster_typecheck_mut_funs , heapster_typecheck_fun_rename , heapster_typecheck_mut_funs_rename -- , heapster_typecheck_fun_rs -- , heapster_typecheck_fun_rename_rs , heapster_define_opaque_perm , heapster_define_recursive_perm , heapster_define_irt_recursive_perm , heapster_define_irt_recursive_shape , heapster_define_reachability_perm , heapster_define_perm , heapster_define_llvmshape , heapster_define_opaque_llvmshape , heapster_define_rust_type , heapster_define_rust_type_qual , heapster_block_entry_hint , heapster_gen_block_perms_hint , heapster_join_point_hint , heapster_find_symbol , heapster_find_symbols , heapster_find_symbol_with_type , heapster_find_symbols_with_type , heapster_find_symbol_commands , heapster_find_trait_method_symbol , heapster_assume_fun , heapster_assume_fun_rename , heapster_assume_fun_rename_prim , heapster_assume_fun_multi , heapster_print_fun_trans , heapster_export_coq , heapster_parse_test , heapster_set_debug_level , heapster_set_translation_checks ) where import Data.Maybe import qualified Data.Map as Map import Data.String import Data.List import Data.List.Extra (splitOn) import Data.IORef import Data.Functor.Product import Control.Lens import Control.Monad import Control.Monad.IO.Class import qualified Control.Monad.Fail as Fail import System.Directory import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString.Lazy.UTF8 as BL import GHC.TypeLits import Data.Text (Text) import Data.Binding.Hobbits hiding (sym) import qualified Data.Type.RList as RL import Data.Parameterized.BoolRepr import qualified Data.Parameterized.Context as Ctx import Data.Parameterized.TraversableF import Data.Parameterized.TraversableFC import Verifier.SAW.Term.Functor import Verifier.SAW.Module as Mod import Verifier.SAW.Prelude import Verifier.SAW.SharedTerm import Verifier.SAW.OpenTerm import Verifier.SAW.Typechecker import Verifier.SAW.SCTypeCheck import qualified Verifier.SAW.UntypedAST as Un import qualified Verifier.SAW.Grammar as Un import Lang.Crucible.Types import Lang.Crucible.FunctionHandle import Lang.Crucible.CFG.Core import Lang.Crucible.LLVM.Extension import Lang.Crucible.LLVM.MemModel import Lang.Crucible.LLVM.Translation -- import Lang.Crucible.LLVM.Translation.Types import Lang.Crucible.LLVM.TypeContext import Lang.Crucible.LLVM.DataLayout import qualified Text.LLVM.AST as L import qualified Text.LLVM.Parser as L import qualified Text.LLVM.PP as L import qualified Text.PrettyPrint.HughesPJ as L (render) import SAWScript.TopLevel import SAWScript.Value import SAWScript.Options import SAWScript.LLVMBuiltins import SAWScript.Builtins import SAWScript.Crucible.LLVM.Builtins import SAWScript.Crucible.LLVM.MethodSpecIR import Verifier.SAW.Heapster.CruUtil import Verifier.SAW.Heapster.Permissions import Verifier.SAW.Heapster.SAWTranslation import Verifier.SAW.Heapster.IRTTranslation import Verifier.SAW.Heapster.PermParser import Verifier.SAW.Heapster.ParsedCtx import Verifier.SAW.Heapster.LLVMGlobalConst import SAWScript.Prover.Exporter import Verifier.SAW.Translation.Coq import Prettyprinter -- | Extract out the contents of the 'Right' of an 'Either', calling 'fail' if -- the 'Either' is a 'Left'. The supplied 'String' describes the action (in -- "ing" form, as in, "parsing") that was performed to create this 'Either'. -- failOnLeft :: (MonadFail m, Show err) => String -> Either err a -> m a -- failOnLeft action (Left err) = Fail.fail ("Error" ++ action ++ ": " ++ show err) -- failOnLeft _ (Right a) = return a -- | Extract out the contents of the 'Just' of a 'Maybe' wrapped in a -- `MonadFail`, calling 'fail' on the given string if the `Maybe` is a -- `Nothing`. failOnNothing :: Fail.MonadFail m => String -> Maybe a -> m a failOnNothing err_str Nothing = Fail.fail err_str failOnNothing _ (Just a) = return a -- | Extract the bit width of an architecture archReprWidth :: ArchRepr arch -> NatRepr (ArchWidth arch) archReprWidth (X86Repr w) = w -- | Get the architecture of an LLVM module llvmModuleArchRepr :: LLVMModule arch -> ArchRepr arch llvmModuleArchRepr lm = llvmArch $ _transContext $ modTrans lm -- | Get the bit width of the architecture of an LLVM module llvmModuleArchReprWidth :: LLVMModule arch -> NatRepr (ArchWidth arch) llvmModuleArchReprWidth = archReprWidth . llvmModuleArchRepr -- | Get the 'TypeContext' of an LLVM module llvmModuleTypeContext :: LLVMModule arch -> TypeContext llvmModuleTypeContext lm = modTrans lm ^. transContext . llvmTypeCtx -- | Look up the 'L.Declare' for an external symbol in an 'LLVMModule' lookupFunctionDecl :: LLVMModule arch -> String -> Maybe L.Declare lookupFunctionDecl lm nm = find ((fromString nm ==) . L.decName) $ L.modDeclares $ modAST lm -- | Look up the Crucible CFG for a defined symbol in an 'LLVMModule' lookupFunctionCFG :: LLVMModule arch -> String -> Maybe (AnyCFG Lang.Crucible.LLVM.Extension.LLVM) lookupFunctionCFG lm nm = snd <$> Map.lookup (fromString nm) (cfgMap $ modTrans lm) -- | Look up the argument and return types of a named function lookupFunctionType :: LLVMModule arch -> String -> TopLevel (Some CtxRepr, Some TypeRepr) lookupFunctionType (lm :: LLVMModule arch) nm = case (lookupFunctionDecl lm nm, lookupFunctionCFG lm nm) of (Just decl, _) -> do let w = llvmModuleArchReprWidth lm leq1_proof <- case decideLeq (knownNat @1) w of Left pf -> return pf Right _ -> fail "LLVM arch width is 0!" leq16_proof <- case decideLeq (knownNat @16) w of Left pf -> return pf Right _ -> fail "LLVM arch width is too small!" let ?ptrWidth = w let ?lc = llvmModuleTypeContext lm withLeqProof leq1_proof $ withLeqProof leq16_proof $ llvmDeclToFunHandleRepr' @(ArchWidth arch) decl $ \args ret -> return (Some args, Some ret) (_, Just (AnyCFG cfg)) -> return (Some (cfgArgTypes cfg), Some (cfgReturnType cfg)) (Nothing, Nothing) -> fail ("Could not find symbol: " ++ nm) -- | Look for the LLVM module in a 'HeapsterEnv' where a symbol is defined lookupModDefiningSym :: HeapsterEnv -> String -> Maybe (Some LLVMModule) lookupModDefiningSym env nm = find (\(Some lm) -> Map.member (fromString nm) (cfgMap $ modTrans lm)) $ heapsterEnvLLVMModules env -- | Look for any LLVM module in a 'HeapsterEnv' containing a symbol lookupModContainingSym :: HeapsterEnv -> String -> Maybe (Some LLVMModule) lookupModContainingSym env nm = find (\(Some lm) -> isJust (lookupFunctionDecl lm nm) || isJust (lookupFunctionCFG lm nm)) $ heapsterEnvLLVMModules env -- | An LLVM module plus a CFG for a specific function in that module data ModuleAndCFG arch = ModuleAndCFG (LLVMModule arch) (AnyCFG Lang.Crucible.LLVM.Extension.LLVM) -- | Look up the LLVM module and associated CFG for a symobl lookupLLVMSymbolModAndCFG :: HeapsterEnv -> String -> Maybe (Some ModuleAndCFG) lookupLLVMSymbolModAndCFG henv nm = case lookupModDefiningSym henv nm of Just (Some lm) -> (Some . ModuleAndCFG lm) <$> lookupFunctionCFG lm nm Nothing -> Nothing heapster_default_env :: PermEnv heapster_default_env = emptyPermEnv -- | Based on the function of the same name in Verifier.SAW.ParserUtils. -- Unlike that function, this calls 'fail' instead of 'error'. readModuleFromFile :: FilePath -> TopLevel (Un.Module, ModuleName) readModuleFromFile path = do base <- liftIO getCurrentDirectory b <- liftIO $ BL.readFile path case Un.parseSAW base path b of Right m@(Un.Module (Un.PosPair _ mnm) _ _) -> pure (m, mnm) Left err -> fail $ "Module parsing failed:\n" ++ show err -- | Parse the second given string as a term, the first given string being -- used as the path for error reporting parseTermFromString :: String -> String -> TopLevel Un.Term parseTermFromString nm term_string = do let base = "" path = "<" ++ nm ++ ">" case Un.parseSAWTerm base path (BL.fromString term_string) of Right term -> pure term Left err -> fail $ "Term parsing failed:\n" ++ show err -- | Find an unused identifier in a 'Module' by starting with a particular -- 'String' and appending a number if necessary findUnusedIdent :: Module -> String -> Ident findUnusedIdent m str = fromJust $ find (isNothing . Mod.resolveName m . identBaseName) $ map (mkSafeIdent (moduleName m)) $ (str : map ((str ++) . show) [(0::Int) ..]) -- | Parse the second given string as a term, check that it has the given type, -- and, if the parsed term is not already an identifier, add it as a definition -- in the current module using the first given string. If that first string is -- already used, find another name for the definition. Return either the -- identifer of the new definition or the identifier that was parsed. parseAndInsDef :: HeapsterEnv -> String -> Term -> String -> TopLevel Ident parseAndInsDef henv nm term_tp term_string = do sc <- getSharedContext un_term <- parseTermFromString nm term_string let mnm = heapsterEnvSAWModule henv typed_term <- liftIO $ scTypeCheckCompleteError sc (Just mnm) un_term liftIO $ scCheckSubtype sc (Just mnm) typed_term term_tp case typedVal typed_term of STApp _ _ (Constant (EC _ (ModuleIdentifier term_ident) _) _) -> return term_ident term -> do m <- liftIO $ scFindModule sc mnm let term_ident = findUnusedIdent m nm liftIO $ scInsertDef sc mnm term_ident term_tp term return term_ident -- | Build a 'HeapsterEnv' associated with the given SAW core module and the -- given 'LLVMModule's. Add any globals in the 'LLVMModule's to the returned -- 'HeapsterEnv'. mkHeapsterEnv :: DebugLevel -> ModuleName -> [Some LLVMModule] -> TopLevel HeapsterEnv mkHeapsterEnv dlevel saw_mod_name llvm_mods@(Some first_mod:_) = do sc <- getSharedContext let w = llvmModuleArchReprWidth first_mod let endianness = llvmDataLayout (modTrans first_mod ^. transContext ^. llvmTypeCtx) ^. intLayout leq_proof <- case decideLeq (knownNat @1) w of Left pf -> return pf Right _ -> fail "LLVM arch width is 0!" let globals = concatMap (\(Some lm) -> L.modGlobals $ modAST lm) llvm_mods env <- liftIO $ withKnownNat w $ withLeqProof leq_proof $ foldM (permEnvAddGlobalConst sc saw_mod_name dlevel endianness w) heapster_default_env globals env_ref <- liftIO $ newIORef env dlevel_ref <- liftIO $ newIORef dlevel checks_ref <- liftIO $ newIORef doChecks return $ HeapsterEnv { heapsterEnvSAWModule = saw_mod_name, heapsterEnvPermEnvRef = env_ref, heapsterEnvLLVMModules = llvm_mods, heapsterEnvDebugLevel = dlevel_ref, heapsterEnvChecksFlag = checks_ref } mkHeapsterEnv _ _ [] = fail "mkHeapsterEnv: empty list of LLVM modules!" heapster_init_env :: BuiltinContext -> Options -> Text -> String -> TopLevel HeapsterEnv heapster_init_env bic opts mod_str llvm_filename = heapster_init_env_gen bic opts noDebugLevel mod_str llvm_filename heapster_init_env_debug :: BuiltinContext -> Options -> Text -> String -> TopLevel HeapsterEnv heapster_init_env_debug bic opts mod_str llvm_filename = heapster_init_env_gen bic opts traceDebugLevel mod_str llvm_filename heapster_init_env_gen :: BuiltinContext -> Options -> DebugLevel -> Text -> String -> TopLevel HeapsterEnv heapster_init_env_gen _bic _opts dlevel mod_str llvm_filename = do llvm_mod <- llvm_load_module llvm_filename sc <- getSharedContext let saw_mod_name = mkModuleName [mod_str] mod_loaded <- liftIO $ scModuleIsLoaded sc saw_mod_name if mod_loaded then fail ("SAW module with name " ++ show mod_str ++ " already defined!") else return () -- import Prelude by default preludeMod <- liftIO $ scFindModule sc preludeModuleName liftIO $ scLoadModule sc (insImport (const True) preludeMod $ emptyModule saw_mod_name) mkHeapsterEnv dlevel saw_mod_name [llvm_mod] load_sawcore_from_file :: BuiltinContext -> Options -> String -> TopLevel () load_sawcore_from_file _ _ mod_filename = do sc <- getSharedContext (saw_mod, _) <- readModuleFromFile mod_filename liftIO $ tcInsertModule sc saw_mod heapster_init_env_from_file :: BuiltinContext -> Options -> String -> String -> TopLevel HeapsterEnv heapster_init_env_from_file bic opts mod_filename llvm_filename = heapster_init_env_from_file_gen bic opts noDebugLevel mod_filename llvm_filename heapster_init_env_from_file_debug :: BuiltinContext -> Options -> String -> String -> TopLevel HeapsterEnv heapster_init_env_from_file_debug bic opts mod_filename llvm_filename = heapster_init_env_from_file_gen bic opts traceDebugLevel mod_filename llvm_filename heapster_init_env_from_file_gen :: BuiltinContext -> Options -> DebugLevel -> String -> String -> TopLevel HeapsterEnv heapster_init_env_from_file_gen _bic _opts dlevel mod_filename llvm_filename = do llvm_mod <- llvm_load_module llvm_filename sc <- getSharedContext (saw_mod, saw_mod_name) <- readModuleFromFile mod_filename liftIO $ tcInsertModule sc saw_mod mkHeapsterEnv dlevel saw_mod_name [llvm_mod] heapster_init_env_for_files_gen :: BuiltinContext -> Options -> DebugLevel -> String -> [String] -> TopLevel HeapsterEnv heapster_init_env_for_files_gen _bic _opts dlevel mod_filename llvm_filenames = do llvm_mods <- mapM llvm_load_module llvm_filenames sc <- getSharedContext (saw_mod, saw_mod_name) <- readModuleFromFile mod_filename liftIO $ tcInsertModule sc saw_mod mkHeapsterEnv dlevel saw_mod_name llvm_mods heapster_init_env_for_files :: BuiltinContext -> Options -> String -> [String] -> TopLevel HeapsterEnv heapster_init_env_for_files _bic _opts mod_filename llvm_filenames = heapster_init_env_for_files_gen _bic _opts noDebugLevel mod_filename llvm_filenames heapster_init_env_for_files_debug :: BuiltinContext -> Options -> String -> [String] -> TopLevel HeapsterEnv heapster_init_env_for_files_debug _bic _opts mod_filename llvm_filenames = heapster_init_env_for_files_gen _bic _opts traceDebugLevel mod_filename llvm_filenames -- | Look up the CFG associated with a symbol name in a Heapster environment heapster_get_cfg :: BuiltinContext -> Options -> HeapsterEnv -> String -> TopLevel SAW_CFG heapster_get_cfg _ _ henv nm = case lookupModDefiningSym henv nm of Just (Some lm) -> llvm_cfg (Some lm) nm Nothing -> fail ("Could not find CFG for symbol: " ++ nm) -- | Define a new opaque named permission with the given name, arguments, and -- type, that translates to the given named SAW core definition heapster_define_opaque_perm :: BuiltinContext -> Options -> HeapsterEnv -> String -> String -> String -> String -> TopLevel () heapster_define_opaque_perm _bic _opts henv nm args_str tp_str term_string = do env <- liftIO $ readIORef $ heapsterEnvPermEnvRef henv Some args <- parseCtxString "argument types" env args_str Some tp_perm <- parseTypeString "permission type" env tp_str sc <- getSharedContext term_tp <- liftIO $ translateCompleteTypeInCtx sc env args (nus (cruCtxProxies args) $ const $ ValuePermRepr tp_perm) term_ident <- parseAndInsDef henv nm term_tp term_string let env' = permEnvAddOpaquePerm env nm args tp_perm term_ident liftIO $ writeIORef (heapsterEnvPermEnvRef henv) env' -- | Define a new recursive named permission with the given name, arguments, -- type, that translates to the given named SAW core definition. heapster_define_recursive_perm :: BuiltinContext -> Options -> HeapsterEnv -> String -> String -> String -> [String] -> String -> String -> String -> TopLevel () heapster_define_recursive_perm _bic _opts henv nm args_str tp_str p_strs trans_str fold_fun_str unfold_fun_str = do env <- liftIO $ readIORef $ heapsterEnvPermEnvRef henv sc <- getSharedContext -- Parse the arguments, the type, and the translation type Some args_ctx <- parseParsedCtxString "argument types" env args_str let args = parsedCtxCtx args_ctx Some tp <- parseTypeString "permission type" env tp_str trans_tp <- liftIO $ translateCompleteTypeInCtx sc env args (nus (cruCtxProxies args) $ const $ ValuePermRepr tp) trans_ident <- parseAndInsDef henv nm trans_tp trans_str -- Use permEnvAddRecPermM to tie the knot of adding a recursive -- permission whose cases and fold/unfold identifiers depend on that -- recursive permission being defined env' <- permEnvAddRecPermM env nm args tp trans_ident NameNonReachConstr (\_ tmp_env -> forM p_strs $ parsePermInCtxString "disjunctive perm" tmp_env args_ctx tp) (\npn cases tmp_env -> do let or_tp = foldr1 (mbMap2 ValPerm_Or) cases nm_tp = nus (cruCtxProxies args) (\ns -> ValPerm_Named npn (namesToExprs ns) NoPermOffset) fold_fun_tp <- liftIO $ translateCompletePureFun sc tmp_env args (singletonValuePerms <$> or_tp) nm_tp unfold_fun_tp <- liftIO $ translateCompletePureFun sc tmp_env args (singletonValuePerms <$> nm_tp) or_tp fold_ident <- parseAndInsDef henv ("fold" ++ nm) fold_fun_tp fold_fun_str unfold_ident <- parseAndInsDef henv ("unfold" ++ nm) unfold_fun_tp unfold_fun_str return (fold_ident, unfold_ident)) (\_ _ -> return NoReachMethods) liftIO $ writeIORef (heapsterEnvPermEnvRef henv) env' -- | Define a new recursive named permission with the given name, arguments, -- and type, auto-generating SAWCore definitions using `IRT` heapster_define_irt_recursive_perm :: BuiltinContext -> Options -> HeapsterEnv -> String -> String -> String -> [String] -> TopLevel () heapster_define_irt_recursive_perm _bic _opts henv nm args_str tp_str p_strs = do env <- liftIO $ readIORef $ heapsterEnvPermEnvRef henv sc <- getSharedContext -- Parse the arguments and type Some args_ctx <- parseParsedCtxString "argument types" env args_str let args = parsedCtxCtx args_ctx Some tp <- parseTypeString "permission type" env tp_str let mnm = heapsterEnvSAWModule henv trans_ident = mkSafeIdent mnm (nm ++ "_IRT") -- Use permEnvAddRecPermM to tie the knot of adding a recursive -- permission whose cases and fold/unfold identifiers depend on that -- recursive permission being defined env' <- permEnvAddRecPermM env nm args tp trans_ident NameNonReachConstr (\_ tmp_env -> forM p_strs $ parsePermInCtxString "disjunctive perm" tmp_env args_ctx tp) (\npn cases tmp_env -> liftIO $ do let or_tp = foldr1 (mbMap2 ValPerm_Or) cases nm_tp = nus (cruCtxProxies args) (\ns -> ValPerm_Named npn (namesToExprs ns) NoPermOffset) -- translate the list of type variables (TypedTerm ls_tm ls_tp, ixs) <- translateCompletePermIRTTyVars sc tmp_env npn args or_tp let ls_ident = mkSafeIdent mnm (nm ++ "_IRTTyVars") scInsertDef sc mnm ls_ident ls_tp ls_tm -- translate the type description (TypedTerm d_tm d_tp) <- translateCompleteIRTDesc sc tmp_env ls_ident args or_tp ixs let d_ident = mkSafeIdent mnm (nm ++ "_IRTDesc") scInsertDef sc mnm d_ident d_tp d_tm -- translate the final definition (TypedTerm tp_tm tp_tp) <- translateCompleteIRTDef sc tmp_env ls_ident d_ident args scInsertDef sc mnm trans_ident tp_tp tp_tm -- translate the fold and unfold functions fold_fun_tp <- translateCompletePureFun sc tmp_env args (singletonValuePerms <$> or_tp) nm_tp unfold_fun_tp <- translateCompletePureFun sc tmp_env args (singletonValuePerms <$> nm_tp) or_tp fold_fun_tm <- translateCompleteIRTFoldFun sc tmp_env ls_ident d_ident trans_ident args unfold_fun_tm <- translateCompleteIRTUnfoldFun sc tmp_env ls_ident d_ident trans_ident args let fold_ident = mkSafeIdent mnm ("fold" ++ nm ++ "_IRT") let unfold_ident = mkSafeIdent mnm ("unfold" ++ nm ++ "_IRT") scInsertDef sc mnm fold_ident fold_fun_tp fold_fun_tm scInsertDef sc mnm unfold_ident unfold_fun_tp unfold_fun_tm return (fold_ident, unfold_ident)) (\_ _ -> return NoReachMethods) liftIO $ writeIORef (heapsterEnvPermEnvRef henv) env' -- | Define a new recursive named shape with the given name, arguments, and -- body, auto-generating SAWCore definitions using `IRT` heapster_define_irt_recursive_shape :: BuiltinContext -> Options -> HeapsterEnv -> String -> Int -> String -> String -> TopLevel () heapster_define_irt_recursive_shape _bic _opts henv nm w_int args_str body_str = do env <- liftIO $ readIORef $ heapsterEnvPermEnvRef henv SomeKnownNatGeq1 w <- failOnNothing "Shape width must be positive" $ someKnownNatGeq1 w_int sc <- getSharedContext -- Parse the arguments Some args_ctx <- parseParsedCtxString "argument types" env args_str let args = parsedCtxCtx args_ctx mnm = heapsterEnvSAWModule henv trans_ident = mkSafeIdent mnm (nm ++ "_IRT") -- Parse the body let tmp_nsh = partialRecShape w nm args Nothing trans_ident tmp_env = permEnvAddNamedShape env tmp_nsh mb_args = nus (cruCtxProxies args) namesToExprs body <- parseExprInCtxString tmp_env (LLVMShapeRepr w) args_ctx body_str abs_body <- failOnNothing "recursive shape applied to different arguments in its body" $ fmap (mbCombine RL.typeCtxProxies) . mbMaybe $ mbMap2 (abstractNS nm args) mb_args body -- Add the named shape to scope using the functions from IRTTranslation.hs env' <- liftIO $ addIRTRecShape sc mnm env nm args abs_body trans_ident liftIO $ writeIORef (heapsterEnvPermEnvRef henv) env' -- | A temporary named recursive shape with `error`s for `fold_ident`, -- `unfold_ident`, and optionally `body`. partialRecShape :: NatRepr w -> String -> CruCtx args -> Maybe (Mb (args :> LLVMShapeType w) (PermExpr (LLVMShapeType w))) -> Ident -> NamedShape 'True args w partialRecShape _ nm args mb_body trans_ident = let body_err = error "Analyzing recursive shape cases before it is defined!" in NamedShape nm args $ RecShapeBody (fromMaybe body_err mb_body) trans_ident Nothing -- | Given a named recursive shape name, arguments, body, and `trans_ident`, -- insert its definition and definitions for its fold and unfold functions -- using the functions in `IRTTranslation.hs`. Returns a modified -- `PermEnv` with the new named shape added. addIRTRecShape :: (1 <= w, KnownNat w) => SharedContext -> ModuleName -> PermEnv -> String -> CruCtx args -> Mb (args :> LLVMShapeType w) (PermExpr (LLVMShapeType w)) -> Ident -> IO PermEnv addIRTRecShape sc mnm env nm args body trans_ident = do let tmp_nsh = partialRecShape knownNat nm args (Just body) trans_ident tmp_env = permEnvAddNamedShape env tmp_nsh nsh_unf = unfoldNamedShape tmp_nsh <$> nus (cruCtxProxies args) namesToExprs nsh_fld = nus (cruCtxProxies args) $ \ns -> PExpr_NamedShape Nothing Nothing tmp_nsh (namesToExprs ns) -- translate the list of type variables (TypedTerm ls_tm ls_tp, ixs) <- translateCompleteShapeIRTTyVars sc tmp_env tmp_nsh let ls_ident = mkSafeIdent mnm (nm ++ "_IRTTyVars") scInsertDef sc mnm ls_ident ls_tp ls_tm -- translate the type description (TypedTerm d_tm d_tp) <- translateCompleteIRTDesc sc tmp_env ls_ident args nsh_unf ixs let d_ident = mkSafeIdent mnm (nm ++ "_IRTDesc") scInsertDef sc mnm d_ident d_tp d_tm -- translate the final definition (TypedTerm tp_tm tp_tp) <- translateCompleteIRTDef sc tmp_env ls_ident d_ident args scInsertDef sc mnm trans_ident tp_tp tp_tm -- translate the fold and unfold functions fold_fun_tp <- translateCompletePureFun sc tmp_env args (singletonValuePerms . ValPerm_LLVMBlockShape <$> nsh_unf) (ValPerm_LLVMBlockShape <$> nsh_fld) unfold_fun_tp <- translateCompletePureFun sc tmp_env args (singletonValuePerms . ValPerm_LLVMBlockShape <$> nsh_fld) (ValPerm_LLVMBlockShape <$> nsh_unf) fold_fun_tm <- translateCompleteIRTFoldFun sc tmp_env ls_ident d_ident trans_ident args unfold_fun_tm <- translateCompleteIRTUnfoldFun sc tmp_env ls_ident d_ident trans_ident args let fold_ident = mkSafeIdent mnm ("fold" ++ nm ++ "_IRT") let unfold_ident = mkSafeIdent mnm ("unfold" ++ nm ++ "_IRT") scInsertDef sc mnm fold_ident fold_fun_tp fold_fun_tm scInsertDef sc mnm unfold_ident unfold_fun_tp unfold_fun_tm let nsh = NamedShape nm args $ RecShapeBody body trans_ident (Just (fold_ident, unfold_ident)) return $ permEnvAddNamedShape env nsh -- | Define a new reachability permission heapster_define_reachability_perm :: BuiltinContext -> Options -> HeapsterEnv -> String -> String -> String -> String -> String -> String -> String -> String -> TopLevel () heapster_define_reachability_perm _bic _opts henv nm args_str tp_str p_str trans_tp_str fold_fun_str unfold_fun_str trans_fun_str = do env <- liftIO $ readIORef $ heapsterEnvPermEnvRef henv sc <- getSharedContext -- Parse the arguments, the type, and the translation type Some (tp :: TypeRepr tp) <- parseTypeString "permission type" env tp_str (Some pre_args_ctx, last_args_ctx :: ParsedCtx (RNil :> tp)) <- do some_args_ctx <- parseParsedCtxString "argument types" env args_str case some_args_ctx of Some args_ctx | CruCtxCons _ tp' <- parsedCtxCtx args_ctx , Just Refl <- testEquality tp tp' -> return (Some (parsedCtxUncons args_ctx), parsedCtxLast args_ctx) _ -> Fail.fail "Incorrect type for last argument of reachability perm" let args_ctx = appendParsedCtx pre_args_ctx last_args_ctx let args = parsedCtxCtx args_ctx trans_tp <- liftIO $ translateCompleteTypeInCtx sc env args $ nus (cruCtxProxies args) $ const $ ValuePermRepr tp trans_tp_ident <- parseAndInsDef henv nm trans_tp trans_tp_str -- Use permEnvAddRecPermM to tie the knot of adding a recursive -- permission whose cases and fold/unfold identifiers depend on that -- recursive permission being defined env' <- permEnvAddRecPermM env nm args tp trans_tp_ident NameReachConstr (\_ tmp_env -> -- Return the disjunctive cases, which for P<args,e> are eq(e) and p do p <- parsePermInCtxString "disjunctive perm" tmp_env args_ctx tp p_str return [nus (cruCtxProxies args) (\(_ :>: n) -> ValPerm_Eq $ PExpr_Var n), p]) (\npn cases tmp_env -> -- Return the Idents for the fold and unfold functions, which -- includes type-checking them, using or_tp = \args. rec perm body, -- where the body = the or of all the cases, and nm_tp = -- \args.P<args> do let or_tp = foldr1 (mbMap2 ValPerm_Or) cases nm_tp = nus (cruCtxProxies args) (\ns -> ValPerm_Named npn (namesToExprs ns) NoPermOffset) -- Typecheck fold against body -o P<args> fold_fun_tp <- liftIO $ translateCompletePureFun sc tmp_env args (singletonValuePerms <$> or_tp) nm_tp -- Typecheck fold against P<args> -o body unfold_fun_tp <- liftIO $ translateCompletePureFun sc tmp_env args (singletonValuePerms <$> nm_tp) or_tp -- Build identifiers foldXXX and unfoldXXX fold_ident <- parseAndInsDef henv ("fold" ++ nm) fold_fun_tp fold_fun_str unfold_ident <- parseAndInsDef henv ("unfold" ++ nm) unfold_fun_tp unfold_fun_str return (fold_ident, unfold_ident)) (\npn tmp_env -> -- Return the ReachMethods structure, which contains trans_ident. -- Typecheck trans_ident with x:P<args,y>, y:P<args,z> -o x:P<args,z> do trans_fun_tp <- liftIO $ translateCompletePureFun sc tmp_env (CruCtxCons args tp) (nus (cruCtxProxies args :>: Proxy) $ \(ns :>: y :>: z) -> MNil :>: ValPerm_Named npn (namesToExprs (ns :>: y)) NoPermOffset :>: ValPerm_Named npn (namesToExprs (ns :>: z)) NoPermOffset) (nus (cruCtxProxies args :>: Proxy) $ \(ns :>: _ :>: z) -> ValPerm_Named npn (namesToExprs (ns :>: z)) NoPermOffset) trans_ident <- parseAndInsDef henv ("trans" ++ nm) trans_fun_tp trans_fun_str return (ReachMethods trans_ident)) liftIO $ writeIORef (heapsterEnvPermEnvRef henv) env' -- | Define a new named permission with the given name, arguments, and type -- that is equivalent to the given permission. heapster_define_perm :: BuiltinContext -> Options -> HeapsterEnv -> String -> String -> String -> String -> TopLevel () heapster_define_perm _bic _opts henv nm args_str tp_str perm_string = do env <- liftIO $ readIORef $ heapsterEnvPermEnvRef henv Some args_ctx <- parseParsedCtxString "argument types" env args_str let args = parsedCtxCtx args_ctx Some tp_perm <- parseTypeString "permission type" env tp_str perm <- parsePermInCtxString "disjunctive perm" env args_ctx tp_perm perm_string let env' = permEnvAddDefinedPerm env nm args tp_perm perm liftIO $ writeIORef (heapsterEnvPermEnvRef henv) env' -- | Define a new named llvm shape with the given name, pointer width, -- arguments, and definition as a shape heapster_define_llvmshape :: BuiltinContext -> Options -> HeapsterEnv -> String -> Int -> String -> String -> TopLevel () heapster_define_llvmshape _bic _opts henv nm w_int args_str sh_str = do env <- liftIO $ readIORef $ heapsterEnvPermEnvRef henv (Some (Pair w LeqProof)) <- failOnNothing "Shape width must be positive" $ someNatGeq1 w_int Some args_ctx <- parseParsedCtxString "argument types" env args_str let args = parsedCtxCtx args_ctx mb_sh <- parseExprInCtxString env (LLVMShapeRepr w) args_ctx sh_str let env' = withKnownNat w $ permEnvAddDefinedShape env nm args mb_sh liftIO $ writeIORef (heapsterEnvPermEnvRef henv) env' -- | Define a new opaque llvm shape with the given name, pointer width, -- arguments, expression for the length in bytes, and SAW core expression for a -- type-level function from the Heapster translations of the argument types to a -- SAW core type heapster_define_opaque_llvmshape :: BuiltinContext -> Options -> HeapsterEnv -> String -> Int -> String -> String -> String -> TopLevel () heapster_define_opaque_llvmshape _bic _opts henv nm w_int args_str len_str tp_str = do env <- liftIO $ readIORef $ heapsterEnvPermEnvRef henv (Some (Pair w LeqProof)) <- failOnNothing "Shape width must be positive" $ someNatGeq1 w_int Some args_ctx <- parseParsedCtxString "argument types" env args_str let args = parsedCtxCtx args_ctx mb_len <- parseExprInCtxString env (BVRepr w) args_ctx len_str sc <- getSharedContext tp_tp <- liftIO $ translateCompleteTypeInCtx sc env args $ nus (cruCtxProxies args) $ const $ ValuePermRepr $ LLVMShapeRepr w tp_id <- parseAndInsDef henv nm tp_tp tp_str let env' = withKnownNat w $ permEnvAddOpaqueShape env nm args mb_len tp_id liftIO $ writeIORef (heapsterEnvPermEnvRef henv) env' -- | Define a new named LLVM shape from a Rust type declaration and an optional -- crate name that qualifies the type name heapster_define_rust_type_qual_opt :: BuiltinContext -> Options -> HeapsterEnv -> Maybe String -> String -> TopLevel () heapster_define_rust_type_qual_opt _bic _opts henv maybe_crate str = -- NOTE: Looking at first LLVM module to determine pointer width. Need to -- think more to determine if this is always a safe thing to do (e.g. are -- there ever circumstances where different modules have different pointer -- widths?) do Some lm <- failOnNothing ("No LLVM modules found") (listToMaybe $ heapsterEnvLLVMModules henv) let w = llvmModuleArchReprWidth lm leq_proof <- case decideLeq (knownNat @1) w of Left pf -> return pf Right _ -> fail "LLVM arch width is 0!" env <- liftIO $ readIORef (heapsterEnvPermEnvRef henv) let crated_nm nm = maybe nm (\crate -> crate ++ "::" ++ nm) maybe_crate withKnownNat w $ withLeqProof leq_proof $ do partialShape <- parseRustTypeString env w str case partialShape of NonRecShape nm ctx sh -> do let nsh = NamedShape { namedShapeName = crated_nm nm , namedShapeArgs = ctx , namedShapeBody = DefinedShapeBody sh } env' = permEnvAddNamedShape env nsh liftIO $ writeIORef (heapsterEnvPermEnvRef henv) env' RecShape nm ctx sh -> do sc <- getSharedContext let mnm = heapsterEnvSAWModule henv nm' = crated_nm nm trans_ident = mkSafeIdent mnm (nm' ++ "_IRT") env' <- liftIO $ addIRTRecShape sc mnm env nm' ctx sh trans_ident liftIO $ writeIORef (heapsterEnvPermEnvRef henv) env' -- | Define a new named LLVM shape from a Rust type declaration heapster_define_rust_type :: BuiltinContext -> Options -> HeapsterEnv -> String -> TopLevel () heapster_define_rust_type bic opts henv str = heapster_define_rust_type_qual_opt bic opts henv Nothing str -- | Define a new named LLVM shape from a Rust type declaration and a crate name -- that qualifies the Rust type by being prefixed to the name of the LLVM shape heapster_define_rust_type_qual :: BuiltinContext -> Options -> HeapsterEnv -> String -> String -> TopLevel () heapster_define_rust_type_qual bic opts henv crate str = heapster_define_rust_type_qual_opt bic opts henv (Just crate) str -- | Add Heapster type-checking hint for some blocks in a function given by -- name. The blocks to receive the hint are those specified in the list, or all -- blocks if the list is empty. heapster_add_block_hints :: HeapsterEnv -> String -> [Int] -> (forall ext blocks init ret args. CFG ext blocks init ret -> BlockID blocks args -> TopLevel (BlockHintSort args)) -> TopLevel () heapster_add_block_hints henv nm blks hintF = do env <- liftIO $ readIORef $ heapsterEnvPermEnvRef henv Some (ModuleAndCFG _ (AnyCFG cfg)) <- failOnNothing ("Could not find symbol definition: " ++ nm) $ lookupLLVMSymbolModAndCFG henv nm let h = cfgHandle cfg blocks = fmapFC blockInputs $ cfgBlockMap cfg block_idxs = fmapFC (blockIDIndex . blockID) $ cfgBlockMap cfg blkIDs <- case blks of -- If an empty list is given, add a hint to every block [] -> pure $ toListFC (Some . BlockID) block_idxs _ -> forM blks $ \blk -> failOnNothing ("Block ID " ++ show blk ++ " not found in function " ++ nm) (fmapF BlockID <$> Ctx.intIndex blk (Ctx.size blocks)) env' <- foldM (\env' (Some blkID) -> permEnvAddHint env' <$> Hint_Block <$> BlockHint h blocks blkID <$> hintF cfg blkID) env blkIDs liftIO $ writeIORef (heapsterEnvPermEnvRef henv) env' -- | Add a hint to the Heapster type-checker that Crucible block number @block@ in -- function @fun@ should have permissions @perms@ on its inputs heapster_block_entry_hint :: BuiltinContext -> Options -> HeapsterEnv -> String -> Int -> String -> String -> String -> TopLevel () heapster_block_entry_hint _bic _opts henv nm blk top_args_str ghosts_str perms_str = do env <- liftIO $ readIORef $ heapsterEnvPermEnvRef henv Some top_args_p <- parseParsedCtxString "top-level argument context" env top_args_str Some ghosts_p <- parseParsedCtxString "ghost argument context" env ghosts_str let top_args = parsedCtxCtx top_args_p ghosts = parsedCtxCtx ghosts_p heapster_add_block_hints henv nm [blk] $ \cfg blkID -> let block_args = mkCruCtx $ blockInputs $ (cfgBlockMap cfg) Ctx.! (blockIDIndex blkID) in BlockEntryHintSort top_args ghosts <$> parsePermsString "block entry permissions" env (appendParsedCtx (appendParsedCtx top_args_p (mkArgsParsedCtx block_args)) ghosts_p) perms_str -- | Add a hint to the Heapster type-checker to *generalize* (recursively -- replace all instances of @eq(const)@ with @exists x. eq(x)@) all permissions -- on the inputs of the given Crucible blocks numbers. If the given list is -- empty, do so for every block in the CFG. heapster_gen_block_perms_hint :: BuiltinContext -> Options -> HeapsterEnv -> String -> [Int] -> TopLevel () heapster_gen_block_perms_hint _bic _opts henv nm blks = heapster_add_block_hints henv nm blks $ \_ _ -> return GenPermsHintSort -- | Add a hint to the Heapster type-checker to make a join point at each of the -- given block numbers, meaning that all entries to the given blocks are merged -- into a single entrypoint, whose permissions are given by the first call to -- the block heapster_join_point_hint :: BuiltinContext -> Options -> HeapsterEnv -> String -> [Int] -> TopLevel () heapster_join_point_hint _bic _opts henv nm blks = heapster_add_block_hints henv nm blks $ \_ _ -> return JoinPointHintSort -- | Search for all symbol names in any LLVM module in a 'HeapsterEnv' that -- contain the supplied string as a substring heapster_find_symbols :: BuiltinContext -> Options -> HeapsterEnv -> String -> TopLevel [String] heapster_find_symbols _bic _opts henv str = return $ concatMap (\(Some lm) -> mapMaybe (\(L.Symbol nm) -> if isInfixOf str nm then Just nm else Nothing) $ map L.decName (L.modDeclares $ modAST lm) ++ map L.defName (L.modDefines $ modAST lm)) $ heapsterEnvLLVMModules henv -- | Search for a symbol name in any LLVM module in a 'HeapsterEnv' that -- contains the supplied string as a substring, failing if there is not exactly -- one such symbol heapster_find_symbol :: BuiltinContext -> Options -> HeapsterEnv -> String -> TopLevel String heapster_find_symbol bic opts henv str = heapster_find_symbols bic opts henv str >>= \syms -> case syms of [sym] -> return sym [] -> fail ("No symbol found matching string: " ++ str) _ -> fail ("Found multiple symbols matching string " ++ str ++ ": " ++ concat (intersperse ", " $ map show syms)) -- | Extract the 'String' name of an LLVM symbol symString :: L.Symbol -> String symString (L.Symbol str) = str -- | Extract the function type of an LLVM definition defFunType :: L.Define -> L.Type defFunType defn = L.FunTy (L.defRetType defn) (map L.typedType (L.defArgs defn)) (L.defVarArgs defn) -- | Extract the function type of an LLVM declaration decFunType :: L.Declare -> L.Type decFunType decl = L.FunTy (L.decRetType decl) (L.decArgs decl) (L.decVarArgs decl) -- | Search for all symbols with the supplied string as a substring that have -- the supplied LLVM type heapster_find_symbols_with_type :: BuiltinContext -> Options -> HeapsterEnv -> String -> String -> TopLevel [String] heapster_find_symbols_with_type _bic _opts henv str tp_str = case L.parseType tp_str of Left err -> fail ("Error parsing LLVM type: " ++ tp_str ++ "\n" ++ show err) Right tp@(L.FunTy _ _ _) -> return $ concatMap (\(Some lm) -> mapMaybe (\decl -> if isInfixOf str (symString $ L.decName decl) && decFunType decl == tp then Just (symString $ L.decName decl) else Nothing) (L.modDeclares $ modAST lm) ++ mapMaybe (\defn -> if isInfixOf str (symString $ L.defName defn) && defFunType defn == tp then Just (symString $ L.defName defn) else Nothing) (L.modDefines $ modAST lm)) $ heapsterEnvLLVMModules henv Right tp -> fail ("Expected an LLVM function type, but found: " ++ show tp) -- | Search for a symbol by name and Crucible type in any LLVM module in a -- 'HeapsterEnv' that contains the supplied string as a substring heapster_find_symbol_with_type :: BuiltinContext -> Options -> HeapsterEnv -> String -> String -> TopLevel String heapster_find_symbol_with_type bic opts henv str tp_str = heapster_find_symbols_with_type bic opts henv str tp_str >>= \syms -> case syms of [sym] -> return sym [] -> fail ("No symbol found matching string: " ++ str ++ " and type: " ++ tp_str) _ -> fail ("Found multiple symbols matching string " ++ str ++ " and type: " ++ tp_str ++ ": " ++ concat (intersperse ", " $ map show syms)) -- | Print a 'String' as a SAW-script string literal, escaping any double quotes -- or newlines print_as_saw_script_string :: String -> String print_as_saw_script_string str = "\"" ++ concatMap (\c -> case c of '\"' -> "\\\"" '\n' -> "\\\n\\" _ -> [c]) str ++ "\""; -- | Map a search string @str@ to a newline-separated sequence of SAW-script -- commands @"heapster_find_symbol_with_type str tp"@, one for each LLVM type -- @tp@ associated with a symbol whose name contains @str@ heapster_find_symbol_commands :: BuiltinContext -> Options -> HeapsterEnv -> String -> TopLevel String heapster_find_symbol_commands _bic _opts henv str = return $ concatMap (\tp -> "heapster_find_symbol_with_type env\n \"" ++ str ++ "\"\n " ++ print_as_saw_script_string (L.render $ L.ppType tp) ++ ";\n") $ concatMap (\(Some lm) -> mapMaybe (\decl -> if isInfixOf str (symString $ L.decName decl) then Just (decFunType decl) else Nothing) (L.modDeclares $ modAST lm) ++ mapMaybe (\defn -> if isInfixOf str (symString $ L.defName defn) then Just (defFunType defn) else Nothing) (L.modDefines $ modAST lm)) $ heapsterEnvLLVMModules henv -- | Search for a symbol name in any LLVM module in a 'HeapsterEnv' that -- corresponds to the supplied string, which should be of the form: -- "trait::method<type>". Fails if there is not exactly one such symbol. heapster_find_trait_method_symbol :: BuiltinContext -> Options -> HeapsterEnv -> String -> TopLevel String heapster_find_trait_method_symbol bic opts henv str = if length instType >= 2 then let unbracketedType = (init . tail) instType queryStr = unbracketedType <> "$u20$as$u20$" <> trait <> "$GT$" <> (show . length) method <> method in heapster_find_symbol bic opts henv queryStr else fail ("Ill-formed query string: " ++ str) where (traitMethod, instType) = span (/= '<') str (colonTrait, method) = let (revMethod, revTrait) = span (/= ':') (reverse traitMethod) in ((reverse . drop 2) revTrait, reverse revMethod) trait = intercalate ".." $ splitOn "::" colonTrait -- | Assume that the given named function has the supplied type and translates -- to a SAW core definition given by the second name heapster_assume_fun_rename :: BuiltinContext -> Options -> HeapsterEnv -> String -> String -> String -> String -> TopLevel () heapster_assume_fun_rename _bic _opts henv nm nm_to perms_string term_string = do Some lm <- failOnNothing ("Could not find symbol: " ++ nm) (lookupModContainingSym henv nm) sc <- getSharedContext let w = llvmModuleArchReprWidth lm leq_proof <- case decideLeq (knownNat @1) w of Left pf -> return pf Right _ -> fail "LLVM arch width is 0!" env <- liftIO $ readIORef $ heapsterEnvPermEnvRef henv (Some cargs, Some ret) <- lookupFunctionType lm nm let args = mkCruCtx cargs withKnownNat w $ withLeqProof leq_proof $ do SomeFunPerm fun_perm <- parseFunPermStringMaybeRust "permissions" w env args ret perms_string env' <- liftIO $ readIORef (heapsterEnvPermEnvRef henv) fun_typ <- liftIO $ translateCompleteFunPerm sc env fun_perm term_ident <- parseAndInsDef henv nm_to fun_typ term_string let env'' = permEnvAddGlobalSymFun env' (GlobalSymbol $ fromString nm) w fun_perm (globalOpenTerm term_ident) liftIO $ writeIORef (heapsterEnvPermEnvRef henv) env'' -- | Create a new SAW core primitive named @nm@ with type @tp@ in the module -- associated with the supplied Heapster environment, and return its identifier insPrimitive :: HeapsterEnv -> String -> Term -> TopLevel Ident insPrimitive henv nm tp = do sc <- getSharedContext let mnm = heapsterEnvSAWModule henv let ident = mkSafeIdent mnm nm i <- liftIO $ scFreshGlobalVar sc liftIO $ scRegisterName sc i (ModuleIdentifier ident) let pn = PrimName i ident tp t <- liftIO $ scFlatTermF sc (Primitive pn) liftIO $ scRegisterGlobal sc ident t liftIO $ scModifyModule sc mnm $ \m -> insDef m $ Def { defIdent = ident, defQualifier = PrimQualifier, defType = tp, defBody = Nothing } return ident -- | Assume that the given named function has the supplied type and translates -- to a SAW core definition given by the second name heapster_assume_fun_rename_prim :: BuiltinContext -> Options -> HeapsterEnv -> String -> String -> String -> TopLevel () heapster_assume_fun_rename_prim _bic _opts henv nm nm_to perms_string = do Some lm <- failOnNothing ("Could not find symbol: " ++ nm) (lookupModContainingSym henv nm) sc <- getSharedContext let w = llvmModuleArchReprWidth lm leq_proof <- case decideLeq (knownNat @1) w of Left pf -> return pf Right _ -> fail "LLVM arch width is 0!" env <- liftIO $ readIORef $ heapsterEnvPermEnvRef henv (Some cargs, Some ret) <- lookupFunctionType lm nm let args = mkCruCtx cargs withKnownNat w $ withLeqProof leq_proof $ do SomeFunPerm fun_perm <- parseFunPermStringMaybeRust "permissions" w env args ret perms_string env' <- liftIO $ readIORef (heapsterEnvPermEnvRef henv) fun_typ <- liftIO $ translateCompleteFunPerm sc env fun_perm term_ident <- insPrimitive henv nm_to fun_typ let env'' = permEnvAddGlobalSymFun env' (GlobalSymbol $ fromString nm) w fun_perm (globalOpenTerm term_ident) liftIO $ writeIORef (heapsterEnvPermEnvRef henv) env'' -- | Assume that the given named function has the supplied type and translates -- to a SAW core definition given by name heapster_assume_fun :: BuiltinContext -> Options -> HeapsterEnv -> String -> String -> String -> TopLevel () heapster_assume_fun _bic _opts henv nm perms_string term_string = heapster_assume_fun_rename _bic _opts henv nm nm perms_string term_string -- | Assume that the given named function has one or more permissions and -- associated translations, each of which is as given in 'heapster_assume_fun' heapster_assume_fun_multi :: BuiltinContext -> Options -> HeapsterEnv -> String -> [(String, String)] -> TopLevel () heapster_assume_fun_multi _bic _opts henv nm perms_terms_strings = do Some lm <- failOnNothing ("Could not find symbol: " ++ nm) (lookupModContainingSym henv nm) sc <- getSharedContext let w = llvmModuleArchReprWidth lm leq_proof <- case decideLeq (knownNat @1) w of Left pf -> return pf Right _ -> fail "LLVM arch width is 0!" (Some (cargs :: CtxRepr cargs), Some (ret :: TypeRepr ret)) <- lookupFunctionType lm nm let args = mkCruCtx cargs env <- liftIO $ readIORef (heapsterEnvPermEnvRef henv) perms_terms :: [(SomeFunPerm (CtxToRList cargs) ret, OpenTerm)] <- forM (zip perms_terms_strings [0::Int ..]) $ \((perms_string, term_string), i) -> withKnownNat w $ withLeqProof leq_proof $ do some_fun_perm <- parseFunPermStringMaybeRust "permissions" w env args ret perms_string fun_typ <- case some_fun_perm of SomeFunPerm fun_perm -> liftIO $ translateCompleteFunPerm sc env fun_perm term_ident <- parseAndInsDef henv (nm ++ "__" ++ show i) fun_typ term_string return (some_fun_perm, globalOpenTerm term_ident) let env' = withKnownNat w $ withLeqProof leq_proof $ permEnvAddGlobalSymFunMulti env (GlobalSymbol $ fromString nm) w perms_terms liftIO $ writeIORef (heapsterEnvPermEnvRef henv) env' heapster_typecheck_mut_funs :: BuiltinContext -> Options -> HeapsterEnv -> [(String, String)] -> TopLevel () heapster_typecheck_mut_funs bic opts henv = heapster_typecheck_mut_funs_rename bic opts henv . map (\(nm, perms_string) -> (nm, nm, perms_string)) heapster_typecheck_mut_funs_rename :: BuiltinContext -> Options -> HeapsterEnv -> [(String, String, String)] -> TopLevel () heapster_typecheck_mut_funs_rename _bic _opts henv fn_names_and_perms = do let (fst_nm, _, _) = head fn_names_and_perms Some lm <- failOnNothing ("Could not find symbol definition: " ++ fst_nm) (lookupModDefiningSym henv fst_nm) let w = llvmModuleArchReprWidth lm let endianness = llvmDataLayout (modTrans lm ^. transContext ^. llvmTypeCtx) ^. intLayout dlevel <- liftIO $ readIORef $ heapsterEnvDebugLevel henv checks <- liftIO $ readIORef $ heapsterEnvChecksFlag henv LeqProof <- case decideLeq (knownNat @16) w of Left pf -> return pf Right _ -> fail "LLVM arch width is < 16!" LeqProof <- case decideLeq (knownNat @1) w of Left pf -> return pf Right _ -> fail "PANIC: 1 > 16!" env <- liftIO $ readIORef $ heapsterEnvPermEnvRef henv some_cfgs_and_perms <- forM fn_names_and_perms $ \(nm, nm_to, perms_string) -> do AnyCFG cfg <- failOnNothing ("Could not find symbol definition: " ++ nm) $ lookupFunctionCFG lm nm let args = mkCruCtx $ handleArgTypes $ cfgHandle cfg let ret = handleReturnType $ cfgHandle cfg SomeFunPerm fun_perm <- -- tracePretty (pretty ("Fun args:" :: String) <+> -- permPretty emptyPPInfo args) $ withKnownNat w $ parseFunPermStringMaybeRust "permissions" w env args ret perms_string return (SomeCFGAndPerm (GlobalSymbol $ fromString nm) nm_to cfg fun_perm) sc <- getSharedContext let saw_modname = heapsterEnvSAWModule henv env' <- liftIO $ let ?ptrWidth = w in tcTranslateAddCFGs sc saw_modname env checks endianness dlevel some_cfgs_and_perms liftIO $ writeIORef (heapsterEnvPermEnvRef henv) env' heapster_typecheck_fun :: BuiltinContext -> Options -> HeapsterEnv -> String -> String -> TopLevel () heapster_typecheck_fun bic opts henv fn_name perms_string = heapster_typecheck_mut_funs bic opts henv [(fn_name, perms_string)] heapster_typecheck_fun_rename :: BuiltinContext -> Options -> HeapsterEnv -> String -> String -> String -> TopLevel () heapster_typecheck_fun_rename bic opts henv fn_name fn_name_to perms_string = heapster_typecheck_mut_funs_rename bic opts henv [(fn_name, fn_name_to, perms_string)] {- heapster_typecheck_fun_rs :: BuiltinContext -> Options -> HeapsterEnv -> String -> String -> TopLevel () heapster_typecheck_fun_rs bic opts henv fn_name perms_string = heapster_typecheck_fun bic opts henv heapster_typecheck_fun_rename_rs :: BuiltinContext -> Options -> HeapsterEnv -> String -> String -> String -> TopLevel () heapster_typecheck_fun_rename_rs bic opts henv fn_name fn_name_to perms_string = heapster_typecheck_mut_funs_rename bic opts henv [(fn_name, fn_name_to, perms_string)] -} heapster_print_fun_trans :: BuiltinContext -> Options -> HeapsterEnv -> String -> TopLevel () heapster_print_fun_trans _bic _opts henv fn_name = do pp_opts <- getTopLevelPPOpts sc <- getSharedContext let saw_modname = heapsterEnvSAWModule henv fun_term <- fmap (fromJust . defBody) $ liftIO $ scRequireDef sc $ mkSafeIdent saw_modname fn_name liftIO $ putStrLn $ scPrettyTerm pp_opts fun_term heapster_export_coq :: BuiltinContext -> Options -> HeapsterEnv -> String -> TopLevel () heapster_export_coq _bic _opts henv filename = do let coq_trans_conf = coqTranslationConfiguration [] [] sc <- getSharedContext saw_mod <- liftIO $ scFindModule sc $ heapsterEnvSAWModule henv let coq_doc = vcat [preamble coq_trans_conf { postPreamble = "From CryptolToCoq Require Import SAWCorePrelude.\n" ++ "From CryptolToCoq Require Import SAWCoreBitvectors." }, translateSAWModule coq_trans_conf saw_mod] liftIO $ writeFile filename (show coq_doc) heapster_set_debug_level :: BuiltinContext -> Options -> HeapsterEnv -> Int -> TopLevel () heapster_set_debug_level _ _ env l = liftIO $ writeIORef (heapsterEnvDebugLevel env) (DebugLevel l) heapster_set_translation_checks :: BuiltinContext -> Options -> HeapsterEnv -> Bool -> TopLevel () heapster_set_translation_checks _ _ env f = liftIO $ writeIORef (heapsterEnvChecksFlag env) (ChecksFlag f) heapster_parse_test :: BuiltinContext -> Options -> Some LLVMModule -> String -> String -> TopLevel () heapster_parse_test _bic _opts _some_lm@(Some lm) fn_name perms_string = do let env = heapster_default_env -- FIXME: env should be an argument let _arch = llvmModuleArchRepr lm AnyCFG cfg <- failOnNothing ("Could not find symbol: " ++ fn_name) $ lookupFunctionCFG lm fn_name let args = mkCruCtx $ handleArgTypes $ cfgHandle cfg let ret = handleReturnType $ cfgHandle cfg SomeFunPerm fun_perm <- parseFunPermString "permissions" env args ret perms_string liftIO $ putStrLn $ permPrettyString emptyPPInfo fun_perm
GaloisInc/saw-script
src/SAWScript/HeapsterBuiltins.hs
bsd-3-clause
59,605
0
25
16,574
12,783
6,309
6,474
-1
-1
{-# LANGUAGE OverloadedStrings, RecordWildCards, MultiParamTypeClasses, FunctionalDependencies, TypeSynonymInstances, FlexibleInstances, TemplateHaskell #-} module Main where -- Generic useful stuff. import Control.Applicative import Control.Monad import Data.Foldable (for_) import Data.Maybe -- Yaml parsing. import Data.Aeson (withObject, withText) import Data.Yaml -- Lenses. import Lens.Micro import Lens.Micro.TH -- IO. import qualified System.FilePath.Find as Find import System.IO -- Text. import qualified Data.Text as T import Text.Printf import Text.Read (readMaybe) import Data.Char -- Lists. import Data.List (intersperse, intercalate, nub, isPrefixOf) import Data.List.Split (chunksOf) -- Harold-specific. import Harold.TextOutput -- | Like 'unwords', but also adds commas. -- -- >>> list ["1", "2", "3"] -- "1, 2, 3" -- list :: [String] -> String list = intercalate ", " -- | Check whether the string is an operator, according to Haskell syntax. isOperator :: String -> Bool isOperator = all isOperatorChar where isOperatorChar c = (isSymbol c || isPunctuation c) && (c `notElem` "_'()[]{}\"") -- | Wrap an operator in parens, leave other names unchanged. -- -- >>> showAsName "+" -- "(+)" -- -- >>> showAsName "f" -- "f" -- showAsName :: String -> String showAsName s | isOperator s = "(" ++ s ++ ")" | otherwise = s -- | Wrap a function in backticks, leave operators unchanged. -- -- >>> showAsOperator "+" -- "+" -- -- >>> showAsOperator "f" -- "`f`" -- showAsOperator :: String -> String showAsOperator s | isOperator s = s | otherwise = "`" ++ s ++ "`" -- | Package version. type Version = String -- | Version ranges in which a function or whatever was available. The 1st -- version is when something was introduces, the 2nd - when it was removed, -- the 3rd - when it was introduced again, etc. type VersionRanges = [Version] -- | Display version ranges in a human-readable way. -- -- >>> showVersionRanges ["4.2"] -- "since v4.2" -- -- >>> showVersionRanges ["0", "4.2"] -- "removed in v4.2" -- -- >>> showVersionRanges ["1.3.3", "4.2"] -- "introduced in v1.3.3, removed in v4.2" -- -- >>> showVersionRanges ["0", "1.3.3", "4.2"] -- "was removed in v1.3.3, reintroduced in v4.2" -- showVersionRanges :: VersionRanges -> String showVersionRanges vs = case vs of [] -> "" ["0"] -> "" [v] -> printf "since v%s" v ["0", u] -> printf "removed in v%s" u [v, u] -> printf "introduced in v%s, removed in v%s" v u ["0", u, v] -> printf "was removed in v%s, reintroduced in v%s" u v vus -> "present in versions " ++ list (map showRange (chunksOf 2 vus)) where showRange [v, u] = v ++ "–" ++ u showRange [v] = v ++ " and onwards" -- | Location of an 'Entry' – package and modules containing it, along with -- versions of the package for which it holds true. data Location = Location { locationPackage :: String , locationModules :: [String] , locationVersions :: VersionRanges } -- | Haskell operator fixity (precedence + associativity). data Fixity = Fixity Int FixityDirection -- | Haskell operator associativity. data FixityDirection = InfixL -- ^ Left-associative. | InfixR -- ^ Right-associative. | InfixN -- ^ Non-associative. -- | An entry in the knowledge base. data Entry = Function { entryName :: String , entryLocation :: [Location] -- | Implementations of the function. , funcImpls :: [FuncImpl] } | Class { entryName :: String , entryLocation :: [Location] -- | Implementations of the class. , classImpls :: [ClassImpl] } | Data { entryName :: String , entryLocation :: [Location] -- | Implementations of the datatype. , dataImpls :: [DataImpl] } -- | Implementation of a function/constructor. data FuncImpl = FuncImpl { -- | Genre (@report@, @naive@, etc.). funcImplGenre :: String -- | Type signature. , funcImplSignature :: String -- | Asymptotic complexity. , funcImplComplexity :: Maybe String -- | Fixity of the function. , funcImplFixity :: Maybe Fixity -- | Source (can be absent for constructors of class methods). , funcImplSource :: Maybe String } -- | Implementation of a class. data ClassImpl = ClassImpl { -- | Genre (@report@, @naive@, etc.). classImplGenre :: String -- | Signature (everything between @class@ and @where@). , classImplSignature :: String -- | Methods. , classImplMethods :: [ClassMethods] } -- | Methods of a class (the reason for having several methods in one object -- is that we'd like to preserve original grouping of methods). data ClassMethods = ClassMethods { -- | Names of the methods. classMethodsNames :: [String] -- | Type signature, common for all methods (without class constraint). , classMethodsSignature :: String } -- | Implementation of a datatype. data DataImpl = DataImpl { -- | Genre (@report@, @naive@, etc.). dataImplGenre :: String -- | A signature (everything between @data@ and @=@). , dataImplSignature :: String -- | List of automatically derived instances. , dataImplDeriving :: [String] -- | Contstructors. , dataImplConstructors :: [Constructor] } -- | A datatype constructor. data Constructor = Constructor { constructorName :: String -- | For 'True' it'd be @[]@. For 'Just', @["a"]@. , constructorParams :: [String] } makeFields ''Location makeFields ''Entry makeFields ''FuncImpl makeFields ''ClassImpl makeFields ''ClassMethods makeFields ''DataImpl makeFields ''Constructor -- | The default package name is "base". The default version range is "always -- been there". instance FromJSON Location where parseJSON = withObject "location" $ \v -> Location <$> v .:? "package" .!= "base" <*> v .: "modules" <*> v .:? "versions" .!= [] instance FromJSON Entry where parseJSON = withObject "entry" $ \v -> -- The order has to be like this because the function parser accepts any -- names, but not other parsers (e.g. parseClass wants the name to start -- with "class"). parseClass v <|> parseData v <|> parseFunction v where parseFunction v = do entryName <- v .: "name" entryLocation <- v .: "location" funcImpls <- v .: "implementations" return Function{..} parseClass v = do entryName <- v .: "name" guard ("class " `isPrefixOf` entryName) entryLocation <- v .: "location" classImpls <- v .: "implementations" return Class{..} parseData v = do entryName <- v .: "name" guard ("data " `isPrefixOf` entryName) entryLocation <- v .: "location" dataImpls <- v .: "implementations" return Data{..} instance FromJSON Fixity where parseJSON = withText "fixity" $ \s -> do let (d, n) = break (== ' ') (T.unpack s) dir <- case d of "infixl" -> return InfixL "infixr" -> return InfixR "infix" -> return InfixN other -> fail ("unknown fixity: '" ++ other ++ "'") prec <- case readMaybe n of Nothing -> fail ("couldn't read '" ++ n ++ "' as a number") Just p -> return p unless (prec >= 0 && prec <= 9) $ fail ("precedence can't be " ++ show prec) return (Fixity prec dir) instance FromJSON FuncImpl where parseJSON = withObject "function implementation" $ \v -> FuncImpl <$> v .: "name" <*> v .: "type" <*> v .:? "complexity" <*> v .:? "fixity" <*> v .:? "code" instance FromJSON ClassImpl where parseJSON = withObject "class implementation" $ \v -> ClassImpl <$> v .: "name" <*> v .: "type" <*> v .: "methods" instance FromJSON ClassMethods where parseJSON = withObject "class methods" $ \v -> ClassMethods <$> nameOrNames v <*> v .: "type" where -- This parses either a single string, or a list of strings. It relies -- on '.:' failing the parse if an object of a different type was -- encountered. nameOrNames v = fmap (:[]) (v .: "name") <|> -- Here '.:' expects a single String. (v .: "name") -- Here '.:' expects [String]. instance FromJSON DataImpl where parseJSON = withObject "datatype implementation" $ \v -> DataImpl <$> v .: "name" <*> v .: "type" <*> v .:? "deriving" .!= [] <*> v .: "constructors" instance FromJSON Constructor where parseJSON = withObject "datatype constructor" $ \v -> Constructor <$> v .: "name" <*> v .:? "params" .!= [] -- | Produces stuff like "base (Prelude, Data.List); since v4.7.0.0". showLocation :: Location -> TextOutput showLocation (Location package modules versions) = do line [package, " (", list modules, ")"] unless (null versions) $ line ["; ", showVersionRanges versions] -- | Produce a textual description of the entry in the knowledge base. showEntry :: Entry -> TextOutput showEntry (Function name locs impls) = do line1 (showAsName name) let signatures = nub (impls ^.. each.signature) indent 2 $ mapM_ (\s -> line [":: ", s]) signatures blank line1 "available from:" indent 2 $ mapM_ showLocation locs blank line1 "implementations:" blank indent 2 $ sequence_ . intersperse blank $ map (showFuncImpl name) impls showEntry (Class name locs impls) = do line1 name blank line1 "available from:" indent 2 $ mapM_ showLocation locs blank line1 "implementations:" blank indent 2 $ sequence_ . intersperse blank $ map showClassImpl impls showEntry (Data name locs impls) = do line1 name blank line1 "available from:" indent 2 $ mapM_ showLocation locs blank line1 "implementations:" blank indent 2 $ sequence_ . intersperse blank $ map showDataImpl impls -- | Show an implementation of a function. showFuncImpl :: String -- ^ Function name. -> FuncImpl -> TextOutput showFuncImpl name (FuncImpl genre signature comp fixity code) = do line [genre, ":"] indent 4 $ do for_ fixity $ \f -> line [showFixity f, " ", showAsOperator name] for_ comp $ \c -> line ["-- complexity: ", c] line [showAsName name, " :: ", signature] mapM_ line1 (maybe [] lines code) showFixityDirection :: FixityDirection -> String showFixityDirection d = case d of InfixL -> "infixl" InfixR -> "infixr" InfixN -> "infix" -- | Produces stuff like "infixl 7". showFixity :: Fixity -> String showFixity (Fixity prec dir) = showFixityDirection dir ++ " " ++ show prec showClassImpl :: ClassImpl -> TextOutput showClassImpl (ClassImpl genre signature methods) = do line [genre, ":"] indent 4 $ do line ["class ", signature, " where"] indent 2 $ mapM_ showClassMethods methods showClassMethods :: ClassMethods -> TextOutput showClassMethods (ClassMethods names signature) = line [list (map showAsName names), " :: ", signature] showDataImpl :: DataImpl -> TextOutput showDataImpl (DataImpl genre signature derivs constrs) = do line [genre, ":"] indent 4 $ do line ["data ", signature] indent 2 $ do case constrs of [] -> return () (c1:cs) -> do line ["= ", showConstructor c1] mapM_ (\c -> line ["| ", showConstructor c]) cs unless (null derivs) $ line ["deriving (", list derivs, ")"] showConstructor :: Constructor -> String showConstructor (Constructor name params) = unwords (name : params) main :: IO () main = do let isRegularFile = (== Find.RegularFile) <$> Find.fileType files <- Find.find (return True) isRegularFile "db" entries <- fmap concat $ forM files $ \f -> do mbRes <- decodeFileEither f case mbRes of Left err -> printf "%s: %s" f (show err) >> return [] Right res -> return res repl entries repl :: [Entry] -> IO () repl entries = do putStr "> " hFlush stdout query <- getLine unless (query == "/quit") $ do let matching = filter ((== query) . view name) entries putStr . getText . sequence_ . intersperse blank . map showEntry $ matching repl entries
aelve/harold
src/Main.hs
bsd-3-clause
12,517
0
23
3,256
3,010
1,562
1,448
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} -- | This module define simple backends using the file-system. The interfaces -- for those backends are defined in `Rescoyl.Types`. module Rescoyl.Simple where import Control.Applicative ((<$>)) import Control.Exception (bracket_) import Control.Monad.Trans (liftIO) import Crypto.PasswordStore (makePassword, verifyPassword) import Data.Aeson (decode, encode) import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy as L import Data.Map (Map) import qualified Data.Map as M import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.IO as T import Snap.Core ( finishWith, getResponse , modifyResponse , setResponseStatus, writeText) import Snap.Snaplet import System.Directory ( createDirectoryIfMissing, doesDirectoryExist, getDirectoryContents , doesFileExist ) import System.FilePath ((</>)) import System.IO (hFlush, hGetEcho, hSetEcho, stdin, stdout) import System.Posix (fileSize, getFileStatus) import Rescoyl.Types import Rescoyl.Utils (saveImageLayerToFile) -- TODO Instead of generating the 404s, or 50Xs here, return a data type -- representing the failure. repositoryPath :: FilePath -> B.ByteString -> B.ByteString -> FilePath repositoryPath static namespace repo = static </> "v1" </> B.unpack namespace </> "repositories" </> B.unpack repo imagePath :: FilePath -> Text -> Text -> FilePath imagePath static namespace image = static </> "v1" </> T.unpack namespace </> "images" </> T.unpack image -- | Check if at least one repository contains a given image. -- Return the first namespace from which the image can be obtained. isImageInRepositories :: FilePath -> Text -> [(Text, Text)] -> IO (Maybe Text) isImageInRepositories _ _ [] = return Nothing isImageInRepositories static image ((namespace, repo):rest) = do info <- readImageIndex' static (T.encodeUtf8 namespace) (T.encodeUtf8 repo) case info of Nothing -> return Nothing Just images -> if T.unpack image `elem` map imageInfoId images then return (Just namespace) else isImageInRepositories static image rest notFound :: Handler App App () notFound = do modifyResponse $ setResponseStatus 404 "Not Found" writeText "404 Not Found" r <- getResponse finishWith r -- | Mapping login / hashed password, and list of public repositories. type Users = (Map Text Text, [(Text, Text)]) initUserBackend :: FilePath -> IO UserBackend initUserBackend static = do us <- readUsers static return UserBackend { isAuthorized = isAuthorized' us , isAllowedToReadImage = isAllowedToReadImage' us static , isAllowedToWriteNamespace = isAllowedToWriteNamespace' } readUsers :: FilePath -> IO Users readUsers static = do let path = static </> "users" e <- liftIO $ doesFileExist path let path' = static </> "public-images" e' <- liftIO $ doesFileExist path' if not e || not e' then return (M.empty, []) else do musers <- decode <$> L.readFile path mimages <- decode <$> L.readFile path' case (musers, mimages) of (Nothing, _) -> error "Can't read users file." (_, Nothing) -> error "Can't read public-images file." (Just users, Just images) -> return (users, images) writeUsers :: FilePath -> Users -> IO () writeUsers static us = do let path = static </> "users" L.writeFile path $ encode us makeUser :: IO (Text, Text) makeUser = do putStr "Login: " >> hFlush stdout login <- getLine putStr "Password: " >> hFlush stdout pw <- withEcho False getLine putChar '\n' pw' <- makePassword (B.pack pw) 16 return (T.pack login, T.decodeUtf8 pw') withEcho :: Bool -> IO a -> IO a withEcho echo action = do old <- hGetEcho stdin bracket_ (hSetEcho stdin echo) (hSetEcho stdin old) action -- | Check a login and password for authorization. isAuthorized' :: Users -> Maybe (Text, Text) -> IO (Maybe Text) isAuthorized' _ Nothing = return Nothing isAuthorized' us (Just (login, password)) = case M.lookup login (fst us) of Just hashedPassword | verifyPassword (T.encodeUtf8 password) (T.encodeUtf8 hashedPassword) -> return $ Just login _ -> return Nothing -- | Check a login and image for access rights. -- Return a namespace from which the image can be obtained. isAllowedToReadImage' :: Users -> FilePath -> Maybe Text -> Text -> IO (Maybe Text) isAllowedToReadImage' us static mlogin image = do -- Login provided; check if image is in the login's repos or in a read-only -- repo. -- No login; check if image is in a read-only repo. repos <- case mlogin of Just login -> map (login,) <$> listRepositories static (T.encodeUtf8 login) Nothing -> return [] mnamespace <- isImageInRepositories static image (repos ++ snd us) case mnamespace of Just namespace | mnamespace == mlogin -> return (Just namespace) Just namespace -> return (Just namespace) Nothing -> return Nothing isAllowedToWriteNamespace' :: Maybe Text -> IO (Maybe Text) isAllowedToWriteNamespace' = error "TODO rescoyl/Rescoyl/Simple.hs::isAllowedToWriteNamespace" initRegistryBackend :: FilePath -> IO RegistryBackend initRegistryBackend static = do return RegistryBackend { loadImage = loadImage' static , saveImageJson = saveImageJson' static , saveImageLayer = saveImageLayer' static , saveImageChecksum = saveImageChecksum' static , saveImageChecksumOld = saveImageChecksumOld' static , saveRepository = saveRepository' static , readTags = readTags' static , saveTag = saveTag' static , readImageIndex = readImageIndex' static , saveImageIndex = saveImageIndex' static } loadImage' :: FilePath -> Text -> Text -> IO GetImage loadImage' static namespace image = do let dir = imagePath static namespace image path = dir </> "json" path' = dir </> "layer" path'' = dir </> "checksum" path''' = dir </> "client_checksum" e <- doesFileExist path a <- doesFileExist $ dir </> "ancestry" if e && a then do mjson <- decode <$> L.readFile path mjson' <- decode <$> L.readFile (dir </> "ancestry") case (mjson, mjson') of (Nothing, _) -> return ImageErrorDecodingJson (_, Nothing) -> return ImageErrorDecodingJson (Just json, Just ancestry) -> do e' <- doesFileExist path' e'' <- doesFileExist path'' if e' && e'' then do size <- getFileStatus path' >>= return . fileSize checksum <- B.readFile path'' e''' <- doesFileExist path''' if e''' then do clientChecksum <- B.readFile path''' return $ Image json ancestry (Layer path' (fromIntegral size) checksum) clientChecksum else return $ ImageLayer json ancestry (Layer path' (fromIntegral size) checksum) else return $ ImageJson json ancestry else return ImageDoesntExist -- TODO `desc` is actually `decode content`. This means that normally -- `content` is redundant. But right now, `decode content` is lossy -- and we really want to store the whole `content`. saveImageJson' :: FilePath -> Text -> Text -> ImageDescription -> L.ByteString -> IO () saveImageJson' static namespace image desc content = do let dir = imagePath static namespace image createDirectoryIfMissing True dir L.writeFile (dir </> "json") content generateAncestry static namespace image $ imageDescriptionParent desc generateAncestry :: String -> Text -> Text -> Maybe String -> IO () generateAncestry static namespace image mparent = do parents <- case mparent of Nothing -> return [] Just parent -> do let dir' = imagePath static namespace $ T.pack parent mparents <- decode <$> (L.readFile $ dir' </> "ancestry") case mparents of Nothing -> error "Corrupted parent ancestry file." Just parents -> return parents let dir = imagePath static namespace image L.writeFile (dir </> "ancestry") $ encode $ image : parents saveImageLayer' :: FilePath -> Text -> Text -> Handler App App () saveImageLayer' static namespace image = do let dir = imagePath static namespace image -- TODO how to bracket open/close with iterHandle in between ? -- TODO Ensure the json is already saved. json <- liftIO $ B.readFile (dir </> "json") (checksum, _) <- saveImageLayerToFile json (dir </> "layer") liftIO $ B.writeFile (dir </> "checksum") $ "sha256:" `B.append` checksum saveImageChecksum' :: FilePath -> Text -> Text -> ByteString -> IO () saveImageChecksum' static namespace image checksum = do let dir = imagePath static namespace image B.writeFile (dir </> "client_checksum") checksum saveImageChecksumOld' :: FilePath -> Text -> Text -> ByteString -> IO () saveImageChecksumOld' static namespace image checksum = do let dir = imagePath static namespace image B.writeFile (dir </> "checksum") checksum B.writeFile (dir </> "client_checksum") checksum saveRepository' :: FilePath -> ByteString -> ByteString -> [ImageInfo] -> IO () saveRepository' static namespace repo images = do let dir = repositoryPath static namespace repo liftIO $ do createDirectoryIfMissing True $ dir </> "tags" L.writeFile (dir </> "images") $ encode images readTags' :: FilePath -> ByteString -> ByteString -> IO [(Text, Text)] readTags' static namespace repo = do let dir = repositoryPath static namespace repo names <- do e <- doesDirectoryExist dir if e then getDirectoryContents $ dir </> "tags" else return [] let names' = filter (not . (`elem` [".", ".."])) names tags <- mapM (T.readFile . (\n -> dir </> "tags" </> n)) names' return $ zipWith (\a b -> (T.pack a, b)) names' tags saveTag' :: FilePath -> ByteString -> ByteString -> ByteString -> L.ByteString -> IO () saveTag' static namespace repo tag value = do let dir = repositoryPath static namespace repo createDirectoryIfMissing True $ dir </> "tags" -- The body is a JSON string, which is an invalid JSON -- payload as per the JSON standard (which only allows -- list and dictionaries at the top level). -- We "decode" it by hand. L.writeFile (dir </> "tags" </> B.unpack tag) value readImageIndex' :: FilePath -> ByteString -> ByteString -> IO (Maybe [ImageInfo]) readImageIndex' static namespace repo = do let dir = repositoryPath static namespace repo path = dir </> "images" e <- doesFileExist path if e then decode <$> L.readFile path else return $ Just [] saveImageIndex' :: FilePath -> ByteString -> ByteString -> [ImageInfo] -> Handler App App () saveImageIndex' static namespace repo new = do let dir = repositoryPath static namespace repo path = dir </> "images" moriginal <- liftIO $ readImageIndex' static namespace repo case moriginal of Nothing -> modifyResponse $ setResponseStatus 500 "Error reading images index." Just original -> do liftIO $ L.writeFile path $ encode $ combineImageInfo original new modifyResponse $ setResponseStatus 204 "No Content" listRepositories :: FilePath -> ByteString -> IO [Text] listRepositories static namespace = do let dir = static </> "v1" </> B.unpack namespace </> "repositories" names <- do e <- doesDirectoryExist dir if e then getDirectoryContents dir else return [] let names' = filter (not . (`elem` [".", ".."])) names return (map T.pack names')
noteed/rescoyl
Rescoyl/Simple.hs
bsd-3-clause
11,588
0
26
2,446
3,417
1,706
1,711
245
6
-------------------------------------------------------------------------------- -- | -- Module : Main -- Note : Hello, World! -- -- A dummy Haskell module, for playing. -- -------------------------------------------------------------------------------- -- main :: IO () main = putStrLn "Hello, World!" listProc :: [a] -> [a] listProc = undefined f :: Char -> Int f x = x + 1 f2 :: [Int] -> Int f2 = foldr (+) 0
capn-freako/Haskell_Misc
hello_world.hs
bsd-3-clause
433
0
7
82
94
52
42
7
1
{-# LANGUAGE DeriveGeneric, DeriveAnyClass #-} module Slack.Response where import GHC.Generics import Data.Aeson import Data.Aeson.Types import Data.Text options = defaultOptions { fieldLabelModifier = camelTo2 '_' , constructorTagModifier = camelTo2 '_' } data ResponseType = Ephemeral | InChannel deriving (Show, Eq, Generic) data Response = Response { responseType :: ResponseType , text :: Text } deriving (Show, Eq, Generic) instance ToJSON ResponseType where toEncoding = genericToEncoding options instance ToJSON Response where toEncoding = genericToEncoding options ephemeral :: Text -> Response ephemeral = Response Ephemeral inChannel :: Text -> Response inChannel = Response InChannel
xldenis/bookclub
src/Slack/Response.hs
bsd-3-clause
759
0
8
154
180
101
79
22
1
{-# LANGUAGE ScopedTypeVariables #-} module Control.Pipe.Binary ( -- ** Handle and File IO fileReader, handleReader, fileWriter, handleWriter, -- ** Chunked Byte Stream Manipulation take, takeWhile, dropWhile, lines, bytes, ) where import Control.Monad import Control.Monad.IO.Class import Control.Monad.Trans.Class import Control.Pipe import Control.Pipe.Exception import Control.Pipe.Combinators (tryAwait, feed) import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as BC import Data.Monoid import Data.Word import System.IO import Prelude hiding (take, takeWhile, dropWhile, lines, catch) -- | Read data from a file. fileReader :: MonadIO m => FilePath -> Pipe () B.ByteString m () fileReader path = bracket (liftIO $ openFile path ReadMode) (liftIO . hClose) handleReader -- | Read data from an open handle. handleReader :: MonadIO m => Handle -> Pipe () B.ByteString m () handleReader h = go where go = do eof <- lift . liftIO $ hIsEOF h unless eof $ do chunk <- lift . liftIO $ B.hGetSome h 4096 yield chunk go -- | Write data to a file. -- -- The file is only opened if some data arrives into the pipe. fileWriter :: MonadIO m => FilePath -> Pipe B.ByteString Void m r fileWriter path = do -- receive some data before opening the handle input <- await -- feed it to the actual worker pipe feed input go where go = bracket (liftIO $ openFile path WriteMode) (liftIO . hClose) handleWriter -- | Write data to a handle. handleWriter:: MonadIO m => Handle -> Pipe B.ByteString Void m r handleWriter h = forever $ do chunk <- await lift . liftIO . B.hPut h $ chunk -- | Act as an identity for the first 'n' bytes, then terminate returning the -- unconsumed portion of the last chunk. take :: Monad m => Int -> Pipe B.ByteString B.ByteString m B.ByteString take size = do chunk <- await let (chunk', leftover) = B.splitAt size chunk yield chunk' if B.null leftover then take $ size - B.length chunk' else return leftover -- | Act as an identity as long as the given predicate holds, then terminate -- returning the unconsumed portion of the last chunk. takeWhile :: Monad m => (Word8 -> Bool) -> Pipe B.ByteString B.ByteString m B.ByteString takeWhile p = go where go = do chunk <- await let (chunk', leftover) = B.span p chunk unless (B.null chunk) $ yield chunk' if B.null leftover then go else return leftover -- | Drop bytes as long as the given predicate holds, then act as an identity. dropWhile :: Monad m => (Word8 -> Bool) -> Pipe B.ByteString B.ByteString m r dropWhile p = do leftover <- takeWhile (not . p) >+> discard yield leftover idP -- | Split the chunked input stream into lines, and yield them individually. lines :: Monad m => Pipe B.ByteString B.ByteString m r lines = go B.empty where go leftover = do mchunk <- tryAwait case mchunk of Nothing | B.null leftover -> idP Nothing -> yield leftover >> idP Just chunk -> split chunk leftover split chunk leftover | B.null chunk = go leftover | B.null rest = go (mappend leftover chunk) | otherwise = yield (mappend leftover line) >> split (B.drop 1 rest) mempty where (line, rest) = B.breakByte 10 chunk -- | Yield individual bytes of the chunked input stream. bytes :: Monad m => Pipe B.ByteString Word8 m r bytes = forever $ await >>= B.foldl (\p c -> p >> yield c) (return ())
pcapriotti/pipes-extra
Control/Pipe/Binary.hs
bsd-3-clause
3,556
0
16
850
1,055
534
521
86
3
{-# LANGUAGE RecursiveDo, FlexibleContexts, RankNTypes, NamedFieldPuns, RecordWildCards #-} module Distribution.Server.Features.Html ( HtmlFeature(..), initHtmlFeature ) where import Distribution.Server.Framework import qualified Distribution.Server.Framework.ResponseContentTypes as Resource import Distribution.Server.Framework.Templating import Distribution.Server.Features.Core import Distribution.Server.Features.Upload import Distribution.Server.Features.BuildReports import Distribution.Server.Features.BuildReports.Render import Distribution.Server.Features.PackageCandidates import Distribution.Server.Features.Users import Distribution.Server.Features.DownloadCount import Distribution.Server.Features.Votes import Distribution.Server.Features.Search import Distribution.Server.Features.Search as Search import Distribution.Server.Features.PreferredVersions -- [reverse index disabled] import Distribution.Server.Features.ReverseDependencies import Distribution.Server.Features.PackageContents (PackageContentsFeature(..)) import Distribution.Server.Features.PackageList import Distribution.Server.Features.Tags import Distribution.Server.Features.Mirror import Distribution.Server.Features.Distro import Distribution.Server.Features.Documentation import Distribution.Server.Features.TarIndexCache import Distribution.Server.Features.UserDetails import Distribution.Server.Features.EditCabalFiles import Distribution.Server.Users.Types import qualified Distribution.Server.Users.Group as Group import Distribution.Server.Packages.Types import Distribution.Server.Packages.Render import qualified Distribution.Server.Users.Users as Users import qualified Distribution.Server.Packages.PackageIndex as PackageIndex import Distribution.Server.Users.Group (UserGroup(..)) import Distribution.Server.Features.Distro.Distributions (DistroPackageInfo(..)) -- [reverse index disabled] import Distribution.Server.Packages.Reverse import qualified Distribution.Server.Pages.Package as Pages import Distribution.Server.Pages.Template import Distribution.Server.Pages.Util import qualified Distribution.Server.Pages.Group as Pages -- [reverse index disabled] import qualified Distribution.Server.Pages.Reverse as Pages import qualified Distribution.Server.Pages.Index as Pages import Distribution.Server.Util.CountingMap (cmFind, cmToList) import Distribution.Server.Util.ServeTarball (loadTarEntry) import Distribution.Package import Distribution.Version import Distribution.Text (display) import Distribution.PackageDescription import Data.List (intercalate, intersperse, insert, sortBy) import Data.Function (on) import qualified Data.Map as Map import Data.Set (Set) import qualified Data.Set as Set import qualified Data.Vector as Vec import Data.Maybe (fromMaybe, isJust) import qualified Data.Text as T import Data.Traversable (traverse) import Control.Applicative (optional) import Data.Array (Array, listArray) import qualified Data.Array as Array import qualified Data.Ix as Ix import Data.Time.Format (formatTime) import Data.Time.Clock (getCurrentTime) import qualified Data.Time.Format.Human as HumanTime import Data.Time.Locale.Compat (defaultTimeLocale) import Text.XHtml.Strict import qualified Text.XHtml.Strict as XHtml import Text.XHtml.Table (simpleTable) import Network.URI (escapeURIString, isUnreserved) -- TODO: move more of the below to Distribution.Server.Pages.*, it's getting -- close to 1K lines, way too much... it's okay to keep data-querying in here, -- but pure HTML generation mostly needlessly clutters up the module. -- Try to make it so no HTML combinators need to be imported. -- -- See the TODO file for more ways to improve the HTML. data HtmlFeature = HtmlFeature { htmlFeatureInterface :: HackageFeature } instance IsHackageFeature HtmlFeature where getFeatureInterface = htmlFeatureInterface -- This feature provides the HTML view to the models of other features -- currently it uses the xhtml package to render HTML (Text.XHtml.Strict) -- -- This means of generating HTML is somewhat temporary, in that a more advanced -- (and better-looking) HTML ajaxy scheme should come about later on. initHtmlFeature :: ServerEnv -> IO (UserFeature -> CoreFeature -> PackageContentsFeature -> UploadFeature -> PackageCandidatesFeature -> VersionsFeature -- [reverse index disabled] -> ReverseFeature -> TagsFeature -> DownloadFeature -> VotesFeature -> ListFeature -> SearchFeature -> MirrorFeature -> DistroFeature -> DocumentationFeature -> DocumentationFeature -> TarIndexCacheFeature -> ReportsFeature -> UserDetailsFeature -> IO HtmlFeature) initHtmlFeature ServerEnv{serverTemplatesDir, serverTemplatesMode, serverCacheDelay, serverVerbosity = verbosity} = do -- Page templates templates <- loadTemplates serverTemplatesMode [serverTemplatesDir, serverTemplatesDir </> "Html"] [ "maintain.html", "maintain-candidate.html" , "reports.html", "report.html" , "maintain-docs.html" , "distro-monitor.html" , "revisions.html" ] return $ \user core@CoreFeature{packageChangeHook} packages upload candidates versions -- [reverse index disabled] reverse tags download rank list@ListFeature{itemUpdate} names mirror distros docsCore docsCandidates tarIndexCache reportsCore usersdetails -> do -- do rec, tie the knot rec let (feature, packageIndex, packagesPage) = htmlFeature user core packages upload candidates versions tags download rank list names mirror distros docsCore docsCandidates tarIndexCache reportsCore usersdetails (htmlUtilities core tags) mainCache namesCache templates -- Index page caches mainCache <- newAsyncCacheNF packageIndex defaultAsyncCachePolicy { asyncCacheName = "packages index page (by category)", asyncCacheUpdateDelay = serverCacheDelay, asyncCacheSyncInit = False, asyncCacheLogVerbosity = verbosity } namesCache <- newAsyncCacheNF packagesPage defaultAsyncCachePolicy { asyncCacheName = "packages index page (by name)", asyncCacheUpdateDelay = serverCacheDelay, asyncCacheLogVerbosity = verbosity } registerHook itemUpdate $ \_ -> prodAsyncCache mainCache >> prodAsyncCache namesCache registerHook packageChangeHook $ \_ -> prodAsyncCache mainCache >> prodAsyncCache namesCache return feature htmlFeature :: UserFeature -> CoreFeature -> PackageContentsFeature -> UploadFeature -> PackageCandidatesFeature -> VersionsFeature -> TagsFeature -> DownloadFeature -> VotesFeature -> ListFeature -> SearchFeature -> MirrorFeature -> DistroFeature -> DocumentationFeature -> DocumentationFeature -> TarIndexCacheFeature -> ReportsFeature -> UserDetailsFeature -> HtmlUtilities -> AsyncCache Response -> AsyncCache Response -> Templates -> (HtmlFeature, IO Response, IO Response) htmlFeature user core@CoreFeature{queryGetPackageIndex} packages upload candidates versions -- [reverse index disabled] ReverseFeature{..} tags download rank list@ListFeature{getAllLists} names mirror distros docsCore docsCandidates tarIndexCache reportsCore usersdetails utilities@HtmlUtilities{..} cachePackagesPage cacheNamesPage templates = (HtmlFeature{..}, packageIndex, packagesPage) where htmlFeatureInterface = (emptyHackageFeature "html") { featureResources = htmlResources , featureState = [] , featureCaches = [ CacheComponent { cacheDesc = "packages page by category", getCacheMemSize = memSize <$> readAsyncCache cachePackagesPage } , CacheComponent { cacheDesc = "packages page by name", getCacheMemSize = memSize <$> readAsyncCache cacheNamesPage } ] , featurePostInit = syncAsyncCache cachePackagesPage , featureReloadFiles = reloadTemplates templates } htmlCore = mkHtmlCore utilities user core versions upload tags docsCore tarIndexCache reportsCore download rank distros packages htmlTags htmlPreferred cachePackagesPage cacheNamesPage templates htmlUsers = mkHtmlUsers user usersdetails htmlUploads = mkHtmlUploads utilities upload htmlDocUploads = mkHtmlDocUploads utilities core docsCore templates htmlDownloads = mkHtmlDownloads utilities download htmlReports = mkHtmlReports utilities core reportsCore templates htmlCandidates = mkHtmlCandidates utilities core versions upload docsCandidates tarIndexCache candidates templates htmlPreferred = mkHtmlPreferred utilities core versions htmlTags = mkHtmlTags utilities core list tags htmlSearch = mkHtmlSearch utilities core list names htmlResources = concat [ htmlCoreResources htmlCore , htmlUsersResources htmlUsers , htmlUploadsResources htmlUploads , htmlDocUploadsResources htmlDocUploads , htmlReportsResources htmlReports , htmlCandidatesResources htmlCandidates , htmlPreferredResources htmlPreferred , htmlDownloadsResources htmlDownloads , htmlTagsResources htmlTags , htmlSearchResources htmlSearch -- and user groups. package maintainers, trustees, admins , htmlGroupResource user (maintainersGroupResource . uploadResource $ upload) , htmlGroupResource user (trusteesGroupResource . uploadResource $ upload) , htmlGroupResource user (uploadersGroupResource . uploadResource $ upload) , htmlGroupResource user (adminResource . userResource $ user) , htmlGroupResource user (mirrorGroupResource . mirrorResource $ mirror) ] -- TODO: write HTML for reports and distros to display the information -- effectively reports {- , (extendResource $ reportsList reports) { resourceGet = [("html", serveReportsList)] } , (extendResource $ reportsPage reports) { resourceGet = [("html", serveReportsPage)] } -} -- distros {- , (extendResource $ distroIndexPage distros) { resourceGet = [("html", serveDistroIndex)] } , (extendResource $ distroAllPage distros) { resourceGet = [("html", serveDistroPackages)] } , (extendResource $ distroPackage distros) { resourceGet = [("html", serveDistroPackage)] } -} -- reverse index (disabled) {- , (extendResource $ reversePackage reverses) { resourceGet = [("html", serveReverse True)] } , (extendResource $ reversePackageOld reverses) { resourceGet = [("html", serveReverse False)] } , (extendResource $ reversePackageAll reverses) { resourceGet = [("html", serveReverseFlat)] } , (extendResource $ reversePackageStats reverses) { resourceGet = [("html", serveReverseStats)] } , (extendResource $ reversePackages reverses) { resourceGet = [("html", serveReverseList)] } -} -- [reverse index disabled] reverses = reverseResource {- [reverse index disabled] -------------------------------------------------------------------------------- -- Reverse serveReverse :: Bool -> DynamicPath -> ServerPart Response serveReverse isRecent dpath = htmlResponse $ withPackageId dpath $ \pkgid -> do let pkgname = packageName pkgid rdisp <- case packageVersion pkgid of Version [] [] -> withPackageAll pkgname $ \_ -> revPackageName pkgname _ -> withPackageVersion pkgid $ \_ -> revPackageId pkgid render <- (if isRecent then renderReverseRecent else renderReverseOld) pkgname rdisp return $ toResponse $ Resource.XHtml $ hackagePage (display pkgname ++ " - Reverse dependencies ") $ Pages.reversePackageRender pkgid (corePackageIdUri "") revr isRecent render serveReverseFlat :: DynamicPath -> ServerPart Response serveReverseFlat dpath = htmlResponse $ withPackageAllPath dpath $ \pkgname _ -> do revCount <- query $ GetReverseCount pkgname pairs <- revPackageFlat pkgname return $ toResponse $ Resource.XHtml $ hackagePage (display pkgname ++ "Flattened reverse dependencies") $ Pages.reverseFlatRender pkgname (corePackageNameUri "") revr revCount pairs serveReverseStats :: DynamicPath -> ServerPart Response serveReverseStats dpath = htmlResponse $ withPackageAllPath dpath $ \pkgname pkgs -> do revCount <- query $ GetReverseCount pkgname return $ toResponse $ Resource.XHtml $ hackagePage (display pkgname ++ "Reverse dependency statistics") $ Pages.reverseStatsRender pkgname (map packageVersion pkgs) (corePackageIdUri "") revr revCount serveReverseList :: DynamicPath -> ServerPart Response serveReverseList _ = do let revr = reverseResource revs triple <- sortedRevSummary revs hackCount <- PackageIndex.indexSize <$> queryGetPackageIndex return $ toResponse $ Resource.XHtml $ hackagePage "Reverse dependencies" $ Pages.reversePackagesRender (corePackageNameUri "") revr hackCount triple -} -------------------------------------------------------------------------------- -- Additional package indices packageIndex :: IO Response packageIndex = do index <- queryGetPackageIndex let htmlIndex = toResponse $ Resource.XHtml $ Pages.packageIndex index return htmlIndex packagesPage :: IO Response packagesPage = do items <- liftIO $ getAllLists let htmlpage = toResponse $ Resource.XHtml $ hackagePage "All packages by name" $ [ h2 << "All packages by name" , ulist ! [theclass "packages"] << map renderItem (Map.elems items) ] return htmlpage {- -- Currently unused, mainly because not all web browsers use eager authentication-sending -- Setting a cookie might work here, albeit one that's stateless for the server, is not -- used for auth and only causes GUI changes, not permission overriding loginWidget :: UserResource -> ServerPart Html loginWidget user = do users <- query State.GetUserDb auth <- Auth.getHackageAuth users return . makeLoginWidget user $ case auth of Left {} -> Nothing Right (_, uinfo) -> Just $ userName uinfo makeLoginWidget :: UserResource -> Maybe UserName -> Html makeLoginWidget user mname = case mname of Nothing -> anchor ! [href $ userLoginUri user Nothing] << "log in" Just uname -> anchor ! [href $ userPageUri user "" uname] << display uname -} {------------------------------------------------------------------------------- Core -------------------------------------------------------------------------------} data HtmlCore = HtmlCore { htmlCoreResources :: [Resource] } mkHtmlCore :: HtmlUtilities -> UserFeature -> CoreFeature -> VersionsFeature -> UploadFeature -> TagsFeature -> DocumentationFeature -> TarIndexCacheFeature -> ReportsFeature -> DownloadFeature -> VotesFeature -> DistroFeature -> PackageContentsFeature -> HtmlTags -> HtmlPreferred -> AsyncCache Response -> AsyncCache Response -> Templates -> HtmlCore mkHtmlCore HtmlUtilities{..} UserFeature{queryGetUserDb} CoreFeature{coreResource} VersionsFeature{ versionsResource , queryGetDeprecatedFor , queryGetPreferredInfo , withPackagePreferred } UploadFeature{guardAuthorisedAsMaintainerOrTrustee} TagsFeature{queryTagsForPackage} documentationFeature@DocumentationFeature{documentationResource, queryDocumentation} TarIndexCacheFeature{cachedTarIndex} reportsFeature DownloadFeature{recentPackageDownloads,totalPackageDownloads} VotesFeature{..} DistroFeature{queryPackageStatus} PackageContentsFeature{packageRender} HtmlTags{..} HtmlPreferred{..} cachePackagesPage cacheNamesPage templates = HtmlCore{..} where cores@CoreResource{packageInPath, lookupPackageName, lookupPackageId} = coreResource versions = versionsResource docs = documentationResource maintainPackage = (resourceAt "/package/:package/maintain") { resourceGet = [("html", serveMaintainPage)] } htmlCoreResources = [ (extendResource $ corePackagePage cores) { resourceDesc = [(GET, "Show detailed package information")] , resourceGet = [("html", servePackagePage)] } , (resourceAt "/package/:package/dependencies") { resourceDesc = [(GET, "Show detailed package dependency information")] , resourceGet = [("html", serveDependenciesPage)] } {- , (extendResource $ coreIndexPage cores) { resourceGet = [("html", serveIndexPage)] }, currently in 'core' feature -} , (resourceAt "/packages/names" ) { resourceGet = [("html", const $ readAsyncCache cacheNamesPage)] } , (extendResource $ corePackagesPage cores) { resourceDesc = [(GET, "Show package index")] , resourceGet = [("html", const $ readAsyncCache cachePackagesPage)] } , maintainPackage , (resourceAt "/package/:package/distro-monitor") { resourceDesc = [(GET, "A handy page for distro package change monitor tools")] , resourceGet = [("html", serveDistroMonitorPage)] } , (resourceAt "/package/:package/revisions/.:format") { resourceGet = [("html", serveCabalRevisionsPage)] } ] -- Currently the main package page is thrown together by querying a bunch -- of features about their attributes for the given package. It'll need -- reorganizing to look aesthetic, as opposed to the sleek and simple current -- design that takes the 1990s school of web design. servePackagePage :: DynamicPath -> ServerPartE Response servePackagePage dpath = do pkgid <- packageInPath dpath withPackagePreferred pkgid $ \pkg pkgs -> do -- get the PackageRender from the PkgInfo render <- liftIO $ packageRender pkg let realpkg = rendPkgId render pkgname = packageName realpkg middleHtml = Pages.renderFields render -- render the build status line buildStatus <- renderBuildStatus documentationFeature reportsFeature realpkg let buildStatusHtml = [("Status", buildStatus)] -- get additional information from other features prefInfo <- queryGetPreferredInfo pkgname let infoUrl = fmap (\_ -> preferredPackageUri versions "" pkgname) $ sumRange prefInfo beforeHtml = [ Pages.renderVersion realpkg (classifyVersions prefInfo $ map packageVersion pkgs) infoUrl , Pages.renderChangelog render , Pages.renderDependencies render] -- and other package indices distributions <- queryPackageStatus pkgname -- [reverse index disabled] revCount <- revPackageSummary realpkg -- We don't currently keep per-version downloads in memory -- (totalDown, versionDown) <- perVersionDownloads pkg totalDown <- cmFind pkgname `liftM` totalPackageDownloads recentDown <- cmFind pkgname `liftM` recentPackageDownloads pkgVotesHtml <- renderVotesHtml pkgname let distHtml = case distributions of [] -> [] _ -> [("Distributions", concatHtml . intersperse (toHtml ", ") $ map showDist distributions)] afterHtml = distHtml ++ [ Pages.renderDownloads totalDown recentDown {- versionDown $ packageVersion realpkg-} , pkgVotesHtml -- [reverse index disabled] ,Pages.reversePackageSummary realpkg revr revCount ] -- bottom sections, currently documentation and readme mdoctarblob <- queryDocumentation realpkg mdocIndex <- maybe (return Nothing) (liftM Just . liftIO . cachedTarIndex) mdoctarblob let docURL = packageDocsContentUri docs realpkg -- "/package" <//> display realpkg <//> "docs" mreadme <- case rendReadme render of Nothing -> return Nothing Just (tarfile, _, offset, _) -> either (\_err -> return Nothing) (return . Just . snd) =<< liftIO (loadTarEntry tarfile offset) -- extra features like tags and downloads tags <- queryTagsForPackage pkgname let tagLinks = toHtml [anchor ! [href "/packages/tags"] << "Tags", toHtml ": ", toHtml (renderTags tags)] deprs <- queryGetDeprecatedFor pkgname let deprHtml = case deprs of Just fors -> paragraph ! [thestyle "color: red"] << [toHtml "Deprecated", case fors of [] -> noHtml _ -> concatHtml . (toHtml " in favor of ":) . intersperse (toHtml ", ") . map (\for -> anchor ! [href $ corePackageNameUri cores "" for] << display for) $ fors] Nothing -> noHtml cacheControlWithoutETag [Public, maxAgeMinutes 5] -- and put it all together return $ toResponse $ Resource.XHtml $ Pages.packagePage render [tagLinks] [deprHtml] (beforeHtml ++ middleHtml ++ afterHtml ++ buildStatusHtml) [] mdocIndex mreadme docURL False where showDist (dname, info) = toHtml (display dname ++ ":") +++ anchor ! [href $ distroUrl info] << toHtml (display $ distroVersion info) serveDependenciesPage :: DynamicPath -> ServerPartE Response serveDependenciesPage dpath = do pkgname <- packageInPath dpath withPackagePreferred pkgname $ \pkg _ -> do render <- liftIO $ packageRender pkg return $ toResponse $ dependenciesPage False render serveMaintainPage :: DynamicPath -> ServerPartE Response serveMaintainPage dpath = do pkgname <- packageInPath dpath pkgs <- lookupPackageName pkgname guardAuthorisedAsMaintainerOrTrustee (pkgname :: PackageName) template <- getTemplate templates "maintain.html" return $ toResponse $ template [ "pkgname" $= pkgname , "versions" $= map packageId pkgs ] serveDistroMonitorPage :: DynamicPath -> ServerPartE Response serveDistroMonitorPage dpath = do pkgname <- packageInPath dpath pkgs <- lookupPackageName pkgname template <- getTemplate templates "distro-monitor.html" return $ toResponse $ template [ "pkgname" $= pkgname , "versions" $= map packageId pkgs ] serveCabalRevisionsPage :: DynamicPath -> ServerPartE Response serveCabalRevisionsPage dpath = do pkginfo <- packageInPath dpath >>= lookupPackageId users <- queryGetUserDb template <- getTemplate templates "revisions.html" let pkgid = packageId pkginfo pkgname = packageName pkginfo revisions = reverse $ Vec.toList (pkgMetadataRevisions pkginfo) numRevisions = pkgNumRevisions pkginfo revchanges = [ case diffCabalRevisions pkgid (cabalFileByteString old) (cabalFileByteString new) of Left _err -> [] Right changes -> changes | ((new, _), (old, _)) <- zip revisions (tail revisions) ] return $ toResponse $ template [ "pkgname" $= pkgname , "pkgid" $= pkgid , "revisions" $= zipWith3 (revisionToTemplate users) (map snd revisions) [numRevisions-1, numRevisions-2..] (revchanges ++ [[]]) ] where revisionToTemplate :: Users.Users -> UploadInfo -> Int -> [Change] -> TemplateVal revisionToTemplate users (utime, uid) revision changes = let uname = Users.userIdToName users uid in templateDict [ templateVal "number" revision , templateVal "user" (display uname) , templateVal "time" (formatTime defaultTimeLocale "%c" utime) , templateVal "changes" changes ] {------------------------------------------------------------------------------- Users -------------------------------------------------------------------------------} data HtmlUsers = HtmlUsers { htmlUsersResources :: [Resource] } mkHtmlUsers :: UserFeature -> UserDetailsFeature -> HtmlUsers mkHtmlUsers UserFeature{..} UserDetailsFeature{..} = HtmlUsers{..} where users = userResource htmlUsersResources = [ -- list of users with user links; if admin, a link to add user page (extendResource $ userList users) { resourceDesc = [ (GET, "list of users") , (POST, "create a new user") ] , resourceGet = [ ("html", serveUserList) ] , resourcePost = [ ("html", \_ -> adminAddUser) ] } -- form to post to /users/ , (resourceAt "/users/register") { resourceDesc = [ (GET, "show \"add user\" form") ] , resourceGet = [ ("html", addUserForm) ] } -- user page with link to password form and list of groups (how to do this?) , (extendResource $ userPage users) { resourceDesc = [ (GET, "show user page") ] , resourceGet = [ ("html", serveUserPage) ] } -- form to PUT password , (extendResource $ passwordResource users) { resourceDesc = [ (GET, "show password change form") , (PUT, "change password") ] , resourceGet = [ ("html", servePasswordForm) ] , resourcePut = [ ("html", servePutPassword) ] } ] serveUserList :: DynamicPath -> ServerPartE Response serveUserList _ = do userlist <- Users.enumerateActiveUsers <$> queryGetUserDb let hlist = unordList [ anchor ! [href $ userPageUri users "" uname] << display uname | (_, uinfo) <- userlist, let uname = userName uinfo ] ok $ toResponse $ Resource.XHtml $ hackagePage "Hackage users" [h2 << "Hackage users", hlist] serveUserPage :: DynamicPath -> ServerPartE Response serveUserPage dpath = do uname <- userNameInPath dpath uid <- lookupUserName uname udetails <- queryUserDetails uid let realname = maybe (display uname) (T.unpack . accountName) udetails uris <- getGroupIndex uid uriPairs <- forM uris $ \uri -> do desc <- getIndexDesc uri return $ Pages.renderGroupName desc (Just uri) return $ toResponse $ Resource.XHtml $ hackagePage realname [ h2 << realname , case uriPairs of [] -> noHtml _ -> toHtml [ toHtml $ display uname ++ " is part of the following groups:" , unordList uriPairs ] ] addUserForm :: DynamicPath -> ServerPartE Response addUserForm _ = return $ toResponse $ Resource.XHtml $ hackagePage "Register account" [ paragraph << "Administrators can register new user accounts here." , form ! [theclass "box", XHtml.method "post", action $ userListUri users ""] << [ simpleTable [] [] [ makeInput [thetype "text"] "username" "User name" , makeInput [thetype "password"] "password" "Password" , makeInput [thetype "password"] "repeat-password" "Confirm password" ] , paragraph << input ! [thetype "submit", value "Create user"] ] ] servePasswordForm :: DynamicPath -> ServerPartE Response servePasswordForm dpath = do uname <- userNameInPath dpath pathUid <- lookupUserName uname uid <- guardAuthenticated -- FIXME: why are we duplicating auth decisions in this feature? canChange <- canChangePassword uid pathUid case canChange of False -> errForbidden "Can't change password" [MText "You're neither this user nor an admin."] True -> return $ toResponse $ Resource.XHtml $ hackagePage "Change password" [ toHtml "Change your password. You'll be prompted for authentication upon submission, if you haven't logged in already." , form ! [theclass "box", XHtml.method "post", action $ userPasswordUri userResource "" uname] << [ simpleTable [] [] [ makeInput [thetype "password"] "password" "Password" , makeInput [thetype "password"] "repeat-password" "Confirm password" ] , paragraph << [ hidden "_method" "PUT" --method override , input ! [thetype "submit", value "Change password"] ] ] ] servePutPassword :: DynamicPath -> ServerPartE Response servePutPassword dpath = do uname <- userNameInPath dpath changePassword uname return $ toResponse $ Resource.XHtml $ hackagePage "Changed password" [toHtml "Changed password for ", anchor ! [href $ userPageUri users "" uname] << display uname] {------------------------------------------------------------------------------- Uploads -------------------------------------------------------------------------------} data HtmlUploads = HtmlUploads { htmlUploadsResources :: [Resource] } mkHtmlUploads :: HtmlUtilities -> UploadFeature -> HtmlUploads mkHtmlUploads HtmlUtilities{..} UploadFeature{..} = HtmlUploads{..} where uploads = uploadResource htmlUploadsResources = [ -- uploads -- serve upload result as HTML (extendResource $ uploadIndexPage uploads) { resourceDesc = [(POST, "Upload package")] , resourcePost = [("html", serveUploadResult)] } -- form for uploading , (resourceAt "/packages/upload") { resourceGet = [("html", serveUploadForm)] } ] serveUploadForm :: DynamicPath -> ServerPartE Response serveUploadForm _ = do return $ toResponse $ Resource.XHtml $ hackagePage "Upload package" [ h2 << "Upload package" , paragraph << [toHtml "See also the ", anchor ! [href "/upload"] << "upload help page", toHtml "."] , form ! [theclass "box", XHtml.method "post", action "/packages/", enctype "multipart/form-data"] << [ input ! [thetype "file", name "package"] , input ! [thetype "submit", value "Upload package"] ] ] serveUploadResult :: DynamicPath -> ServerPartE Response serveUploadResult _ = do res <- uploadPackage let warns = uploadWarnings res pkgid = packageId (uploadDesc res) return $ toResponse $ Resource.XHtml $ hackagePage "Upload successful" $ [ paragraph << [toHtml "Successfully uploaded ", packageLink pkgid, toHtml "!"] ] ++ case warns of [] -> [] _ -> [paragraph << "There were some warnings:", unordList warns] {------------------------------------------------------------------------------- Documentation uploads -------------------------------------------------------------------------------} data HtmlDocUploads = HtmlDocUploads { htmlDocUploadsResources :: [Resource] } mkHtmlDocUploads :: HtmlUtilities -> CoreFeature -> DocumentationFeature -> Templates -> HtmlDocUploads mkHtmlDocUploads HtmlUtilities{..} CoreFeature{coreResource} DocumentationFeature{..} templates = HtmlDocUploads{..} where CoreResource{packageInPath} = coreResource htmlDocUploadsResources = [ (extendResource $ packageDocsWhole documentationResource) { resourcePut = [ ("html", serveUploadDocumentation) ] , resourceDelete = [ ("html", serveDeleteDocumentation) ] } , (resourceAt "/package/:package/maintain/docs") { resourceGet = [("html", serveDocUploadForm)] } ] serveUploadDocumentation :: DynamicPath -> ServerPartE Response serveUploadDocumentation dpath = do pkgid <- packageInPath dpath uploadDocumentation dpath >> ignoreFilters -- Override 204 No Content return $ toResponse $ Resource.XHtml $ hackagePage "Documentation uploaded" $ [ paragraph << [toHtml "Successfully uploaded documentation for ", packageLink pkgid, toHtml "!"] ] serveDeleteDocumentation :: DynamicPath -> ServerPartE Response serveDeleteDocumentation dpath = do pkgid <- packageInPath dpath deleteDocumentation dpath >> ignoreFilters -- Override 204 No Content return $ toResponse $ Resource.XHtml $ hackagePage "Documentation deleted" $ [ paragraph << [toHtml "Successfully deleted documentation for ", packageLink pkgid, toHtml "!"] ] serveDocUploadForm :: DynamicPath -> ServerPartE Response serveDocUploadForm dpath = do pkgid <- packageInPath dpath template <- getTemplate templates "maintain-docs.html" return $ toResponse $ template [ "pkgid" $= (pkgid :: PackageIdentifier) ] {------------------------------------------------------------------------------- Build reports -------------------------------------------------------------------------------} data HtmlReports = HtmlReports { htmlReportsResources :: [Resource] } mkHtmlReports :: HtmlUtilities -> CoreFeature -> ReportsFeature -> Templates -> HtmlReports mkHtmlReports HtmlUtilities{..} CoreFeature{..} ReportsFeature{..} templates = HtmlReports{..} where CoreResource{packageInPath} = coreResource ReportsResource{..} = reportsResource htmlReportsResources = [ (extendResource reportsList) { resourceGet = [ ("html", servePackageReports) ] } , (extendResource reportsPage) { resourceGet = [ ("html", servePackageReport) ] } ] servePackageReports :: DynamicPath -> ServerPartE Response servePackageReports dpath = packageReports dpath $ \reports -> do pkgid <- packageInPath dpath template <- getTemplate templates "reports.html" return $ toResponse $ template [ "pkgid" $= (pkgid :: PackageIdentifier) , "reports" $= reports ] servePackageReport :: DynamicPath -> ServerPartE Response servePackageReport dpath = do (repid, report, mlog) <- packageReport dpath mlog' <- traverse queryBuildLog mlog pkgid <- packageInPath dpath template <- getTemplate templates "report.html" return $ toResponse $ template [ "pkgid" $= (pkgid :: PackageIdentifier) , "report" $= (repid, report) , "log" $= toMessage <$> mlog' ] {------------------------------------------------------------------------------- Candidates -------------------------------------------------------------------------------} data HtmlCandidates = HtmlCandidates { htmlCandidatesResources :: [Resource] } mkHtmlCandidates :: HtmlUtilities -> CoreFeature -> VersionsFeature -> UploadFeature -> DocumentationFeature -> TarIndexCacheFeature -> PackageCandidatesFeature -> Templates -> HtmlCandidates mkHtmlCandidates HtmlUtilities{..} CoreFeature{ coreResource = CoreResource{packageInPath} , queryGetPackageIndex } VersionsFeature{ queryGetPreferredInfo } UploadFeature{ guardAuthorisedAsMaintainer } DocumentationFeature{documentationResource, queryDocumentation} TarIndexCacheFeature{cachedTarIndex} PackageCandidatesFeature{..} templates = HtmlCandidates{..} where candidates = candidatesResource candidatesCore = candidatesCoreResource docs = documentationResource pkgCandUploadForm = (resourceAt "/package/:package/candidate/upload") { resourceGet = [("html", servePackageCandidateUpload)] } candMaintainForm = (resourceAt "/package/:package/candidate/maintain") { resourceGet = [("html", serveCandidateMaintain)] } htmlCandidatesResources = [ -- candidates -- list of all packages which have candidates (extendResource $ corePackagesPage candidatesCore) { resourceDesc = [ (GET, "Show all package candidates") , (POST, "Upload a new candidate") ] , resourceGet = [ ("html", serveCandidatesPage) ] , resourcePost = [ ("html", \_ -> postCandidate) ] } -- TODO: use custom functions, not htmlResponse , (extendResource $ packageCandidatesPage candidates) { resourceDesc = [ (GET, "Show candidate upload form") , (POST, "Upload new package candidate") ] , resourceGet = [ ("html", servePackageCandidates pkgCandUploadForm) ] , resourcePost = [ ("", postPackageCandidate) ] } -- package page for a candidate , (extendResource $ corePackagePage candidatesCore) { resourceDesc = [ (GET, "Show candidate maintenance form") , (PUT, "Upload new package candidate") , (DELETE, "Delete a package candidate") ] , resourceGet = [("html", serveCandidatePage candMaintainForm)] , resourcePut = [("html", putPackageCandidate)] , resourceDelete = [("html", doDeleteCandidate)] } , (resourceAt "/package/:package/candidate/dependencies") { resourceDesc = [(GET, "Show detailed candidate dependency information")] , resourceGet = [("html", serveDependenciesPage)] } -- form for uploading candidate , (resourceAt "/packages/candidates/upload") { resourceDesc = [ (GET, "Show package candidate upload form") ] , resourceGet = [ ("html", serveCandidateUploadForm) ] } -- form for uploading candidate for a specific package version , pkgCandUploadForm -- maintenance for candidate packages , candMaintainForm -- form for publishing package , (extendResource $ publishPage candidates) { resourceDesc = [ (GET, "Show candidate publish form") , (POST, "Publish a package candidate") ] , resourceGet = [ ("html", servePublishForm) ] , resourcePost = [ ("html", servePostPublish) ] } , (extendResource $ deletePage candidates) { resourceDesc = [ (GET, "Show candidate deletion form") , (POST, "Delete a package candidate") ] , resourceGet = [ ("html", serveDeleteForm) ] , resourcePost = [ ("html", doDeleteCandidate) ] } ] serveCandidateUploadForm :: DynamicPath -> ServerPartE Response serveCandidateUploadForm _ = do return $ toResponse $ Resource.XHtml $ hackagePage "Checking and uploading candidates" [ h2 << "Checking and uploading candidates" , paragraph << [toHtml "See also the ", anchor ! [href "/upload"] << "upload help page", toHtml "."] , form ! [theclass "box", XHtml.method "post", action "/packages/candidates/", enctype "multipart/form-data"] << [ input ! [thetype "file", name "package"] , input ! [thetype "submit", value "Upload candidate"] ] ] servePackageCandidateUpload :: DynamicPath -> ServerPartE Response servePackageCandidateUpload _ = do return $ toResponse $ Resource.XHtml $ hackagePage "Checking and uploading candidates" [ form ! [theclass "box", XHtml.method "post", action "/packages/candidates/", enctype "multipart/form-data"] << [ input ! [thetype "file", name "package"] , input ! [thetype "submit", value "Upload candidate"] ] ] serveCandidateMaintain :: DynamicPath -> ServerPartE Response serveCandidateMaintain dpath = do candidate <- packageInPath dpath >>= lookupCandidateId guardAuthorisedAsMaintainer (packageName candidate) template <- getTemplate templates "maintain-candidate.html" return $ toResponse $ template [ "pkgname" $= packageName candidate , "pkgversion" $= packageVersion candidate ] {-some useful URIs here: candidateUri check "" pkgid, packageCandidatesUri check "" pkgid, publishUri check "" pkgid-} serveCandidatePage :: Resource -> DynamicPath -> ServerPartE Response serveCandidatePage maintain dpath = do cand <- packageInPath dpath >>= lookupCandidateId candRender <- liftIO $ candidateRender cand let PackageIdentifier pkgname version = packageId cand render = candPackageRender candRender otherVersions <- map packageVersion . flip PackageIndex.lookupPackageName pkgname <$> queryGetPackageIndex prefInfo <- queryGetPreferredInfo pkgname let sectionHtml = [Pages.renderVersion (packageId cand) (classifyVersions prefInfo $ insert version otherVersions) Nothing, Pages.renderDependencies render] ++ Pages.renderFields render maintainHtml = anchor ! [href $ renderResource maintain [display $ packageId cand]] << "maintain" -- bottom sections, currently documentation and readme mdoctarblob <- queryDocumentation (packageId cand) mdocIndex <- maybe (return Nothing) (liftM Just . liftIO . cachedTarIndex) mdoctarblob let docURL = packageDocsContentUri docs (packageId cand) mreadme <- case rendReadme render of Nothing -> return Nothing Just (tarfile, _, offset, _) -> either (\_err -> return Nothing) (return . Just . snd) =<< liftIO (loadTarEntry tarfile offset) -- also utilize hasIndexedPackage :: Bool let warningBox = case renderWarnings candRender of [] -> [] warn -> [thediv ! [theclass "notification"] << [toHtml "Warnings:", unordList warn]] return $ toResponse $ Resource.XHtml $ Pages.packagePage render [maintainHtml] warningBox sectionHtml [] mdocIndex mreadme docURL True serveDependenciesPage :: DynamicPath -> ServerPartE Response serveDependenciesPage dpath = do candId <- packageInPath dpath candRender <- liftIO . candidateRender =<< lookupCandidateId candId let render = candPackageRender candRender return $ toResponse $ dependenciesPage True render servePublishForm :: DynamicPath -> ServerPartE Response servePublishForm dpath = do candidate <- packageInPath dpath >>= lookupCandidateId guardAuthorisedAsMaintainer (packageName candidate) let pkgid = packageId candidate packages <- queryGetPackageIndex case checkPublish packages candidate of Just err -> throwError err Nothing -> do return $ toResponse $ Resource.XHtml $ hackagePage "Publishing candidates" [form ! [theclass "box", XHtml.method "post", action $ publishUri candidatesResource "" pkgid] << input ! [thetype "submit", value "Publish package"]] serveCandidatesPage :: DynamicPath -> ServerPartE Response serveCandidatesPage _ = do cands <- queryGetCandidateIndex return $ toResponse $ Resource.XHtml $ hackagePage "Package candidates" [ h2 << "Package candidates" , paragraph << [ toHtml "Here follow all the candidate package versions on Hackage. " , thespan ! [thestyle "color: gray"] << [ toHtml "[" , anchor ! [href "/packages/candidates/upload"] << "upload" , toHtml "]" ] ] , unordList $ map showCands $ PackageIndex.allPackagesByName cands ] -- note: each of the lists here should be non-empty, according to PackageIndex where showCands pkgs = let desc = packageDescription . pkgDesc . candPkgInfo $ last pkgs pkgname = packageName desc in [ anchor ! [href $ packageCandidatesUri candidates "" pkgname ] << display pkgname , toHtml ": " , toHtml $ intersperse (toHtml ", ") $ flip map pkgs $ \pkg -> anchor ! [href $ corePackageIdUri candidatesCore "" (packageId pkg)] << display (packageVersion pkg) , toHtml $ ". " ++ description desc ] servePackageCandidates :: Resource -> DynamicPath -> ServerPartE Response servePackageCandidates candPkgUp dpath = do pkgname <- packageInPath dpath pkgs <- lookupCandidateName pkgname return $ toResponse $ Resource.XHtml $ hackagePage "Package candidates" $ [ h3 << ("Candidates for " ++ display pkgname) ] ++ case pkgs of [] -> [ toHtml "No candidates exist for ", packageNameLink pkgname, toHtml ". Upload one for " , anchor ! [href $ renderResource candPkgUp [display pkgname]] << "this" , toHtml " or " , anchor ! [href $ "/packages/candidates/upload"] << "another" , toHtml " package?" ] _ -> [ unordList $ flip map pkgs $ \pkg -> anchor ! [href $ corePackageIdUri candidatesCore "" $ packageId pkg] << display (packageVersion pkg) ] -- TODO: make publishCandidate a member of the PackageCandidates feature, just like -- putDeprecated and putPreferred are for the Versions feature. servePostPublish :: DynamicPath -> ServerPartE Response servePostPublish dpath = do uresult <- publishCandidate dpath False return $ toResponse $ Resource.XHtml $ hackagePage "Publish successful" $ [ paragraph << [toHtml "Successfully published ", packageLink (packageId $ uploadDesc uresult), toHtml "!"] ] ++ case uploadWarnings uresult of [] -> [] warns -> [paragraph << "There were some warnings:", unordList warns] serveDeleteForm :: DynamicPath -> ServerPartE Response serveDeleteForm dpath = do candidate <- packageInPath dpath >>= lookupCandidateId guardAuthorisedAsMaintainer (packageName candidate) let pkgid = packageId candidate return $ toResponse $ Resource.XHtml $ hackagePage "Deleting candidates" [form ! [theclass "box", XHtml.method "post", action $ deleteUri candidatesResource "" pkgid] << input ! [thetype "submit", value "Delete package candidate"]] dependenciesPage :: Bool -> PackageRender -> Resource.XHtml dependenciesPage isCandidate render = Resource.XHtml $ hackagePage (pkg ++ ": dependencies") $ [h2 << heading, Pages.renderDetailedDependencies render] ++ Pages.renderPackageFlags render where pkg = display $ rendPkgId render heading = "Dependencies for " +++ anchor ! [href link] << pkg link = "/package/" ++ pkg ++ if isCandidate then "/candidate" else "" {------------------------------------------------------------------------------- Preferred versions -------------------------------------------------------------------------------} data HtmlPreferred = HtmlPreferred { htmlPreferredResources :: [Resource] , editPreferred :: Resource , editDeprecated :: Resource } mkHtmlPreferred :: HtmlUtilities -> CoreFeature -> VersionsFeature -> HtmlPreferred mkHtmlPreferred HtmlUtilities{..} CoreFeature{ coreResource = CoreResource{ packageInPath , lookupPackageName } } VersionsFeature{..} = HtmlPreferred{..} where versions = versionsResource editDeprecated = (resourceAt "/package/:package/deprecated/edit") { resourceGet = [("html", serveDeprecateForm)] } editPreferred = (resourceAt "/package/:package/preferred/edit") { resourceGet = [("html", servePreferForm)] } htmlPreferredResources = [ -- preferred versions editDeprecated , editPreferred , (extendResource $ preferredResource versions) { resourceGet = [("html", servePreferredSummary)] } , (extendResource $ preferredPackageResource versions) { resourceGet = [("html", servePackagePreferred editPreferred)] , resourcePut = [("html", servePutPreferred)] } , (extendResource $ deprecatedResource versions) { resourceGet = [("html", serveDeprecatedSummary)] } , (extendResource $ deprecatedPackageResource versions) { resourceGet = [("html", servePackageDeprecated editDeprecated)] , resourcePut = [("html", servePutDeprecated )] } ] -- This feature is in great need of a Pages module serveDeprecatedSummary :: DynamicPath -> ServerPartE Response serveDeprecatedSummary _ = doDeprecatedsRender >>= \renders -> do return $ toResponse $ Resource.XHtml $ hackagePage "Deprecated packages" [ h2 << "Deprecated packages" , unordList $ flip map renders $ \(pkg, pkgs) -> [ packageNameLink pkg, toHtml ": ", deprecatedText pkgs ] ] deprecatedText :: [PackageName] -> Html deprecatedText [] = toHtml "deprecated" deprecatedText pkgs = toHtml [ toHtml "deprecated in favor of " , concatHtml $ intersperse (toHtml ", ") (map packageNameLink pkgs) ] servePackageDeprecated :: Resource -> DynamicPath -> ServerPartE Response servePackageDeprecated deprEdit dpath = do pkgname <- packageInPath dpath mpkg <- doDeprecatedRender pkgname return $ toResponse $ Resource.XHtml $ hackagePage "Deprecated status" [ h2 << "Deprecated status" , paragraph << [ toHtml $ case mpkg of Nothing -> [packageNameLink pkgname, toHtml " is not deprecated"] Just pkgs -> [packageNameLink pkgname, toHtml " is ", deprecatedText pkgs] , thespan ! [thestyle "color: gray"] << [ toHtml " [maintainers: " , anchor ! [href $ renderResource deprEdit [display pkgname]] << "edit" , toHtml "]" ] ] ] servePreferredSummary :: DynamicPath -> ServerPartE Response servePreferredSummary _ = doPreferredsRender >>= \renders -> do return $ toResponse $ Resource.XHtml $ hackagePage "Preferred versions" [ h2 << "Preferred versions" , case renders of [] -> paragraph << "There are no global preferred versions." _ -> unordList $ flip map renders $ \(pkgname, pref) -> [ packageNameLink pkgname , unordList [varList "Preferred ranges" (rendRanges pref), varList "Deprecated versions" (map display $ rendVersions pref), toHtml ["Calculated range: ", rendSumRange pref]] ] , paragraph << [ anchor ! [href "/packages/preferred-versions"] << "preferred-versions" , toHtml " is the text file served with every index tarball that contains this information." ] ] where varList summ [] = toHtml $ summ ++ ": none" varList summ xs = toHtml $ summ ++ ": " ++ intercalate ", " xs packagePrefAbout :: Maybe Resource -> PackageName -> [Html] packagePrefAbout maybeEdit pkgname = [ paragraph << [ anchor ! [href $ preferredUri versions ""] << "Preferred and deprecated versions" , toHtml $ " can be used to influence Cabal's decisions about which versions of " , packageNameLink pkgname , toHtml " to install. If a range of versions is preferred, it means that the installer won't install a non-preferred package version unless it is explicitly specified or if it's the only choice the installer has. Deprecating a version adds a range which excludes just that version. All of this information is collected in the " , anchor ! [href "/packages/preferred-versions"] << "preferred-versions" , toHtml " file that's included in the index tarball." , flip (maybe noHtml) maybeEdit $ \prefEdit -> thespan ! [thestyle "color: gray"] << [ toHtml " [maintainers: " , anchor ! [href $ renderResource prefEdit [display pkgname]] << "edit" , toHtml "]" ] ] , paragraph << [ toHtml "If all the available versions of a package are non-preferred or deprecated, cabal-install will treat this the same as if none of them are. This feature doesn't affect whether or not to install a package, only for selecting versions after a given package has decided to be installed. " , anchor ! [href $ deprecatedPackageUri versions "" pkgname] << "Entire-package deprecation" , toHtml " is also available, but it's separate from preferred versions." ] ] servePackagePreferred :: Resource -> DynamicPath -> ServerPartE Response servePackagePreferred prefEdit dpath = do pkgname <- packageInPath dpath pkgs <- lookupPackageName pkgname pref <- doPreferredRender pkgname let dtitle = display pkgname ++ ": preferred and deprecated versions" prefInfo <- queryGetPreferredInfo pkgname return $ toResponse $ Resource.XHtml $ hackagePage dtitle --needs core, preferredVersions, pkgname [ h2 << dtitle , concatHtml $ packagePrefAbout (Just prefEdit) pkgname , h4 << "Stored information" , case rendRanges pref of [] -> paragraph << [display pkgname ++ " has no preferred version ranges."] prefs -> paragraph << ["Preferred versions for " ++ display pkgname ++ ":"] +++ unordList prefs , case rendVersions pref of [] -> paragraph << ["It has no deprecated versions."] deprs -> paragraph << [ "Explicitly deprecated versions for " ++ display pkgname ++ " include: " , intercalate ", " (map display deprs)] , toHtml "The version range given to this package, therefore, is " +++ strong (toHtml $ rendSumRange pref) , h4 << "Versions affected" , paragraph << "Blue versions are normal versions. Green are those out of any preferred version ranges. Gray are deprecated." , paragraph << (snd $ Pages.renderVersion (PackageIdentifier pkgname $ Version [] []) (classifyVersions prefInfo $ map packageVersion pkgs) Nothing) ] servePutPreferred :: DynamicPath -> ServerPartE Response servePutPreferred dpath = do pkgname <- packageInPath dpath putPreferred pkgname return $ toResponse $ Resource.XHtml $ hackagePage "Set preferred versions" [ h2 << "Set preferred versions" , paragraph << [ toHtml "Set the " , anchor ! [href $ preferredPackageUri versionsResource "" pkgname] << "preferred versions" , toHtml " for " , packageNameLink pkgname , toHtml "."] ] servePutDeprecated :: DynamicPath -> ServerPartE Response servePutDeprecated dpath = do pkgname <- packageInPath dpath wasDepr <- putDeprecated pkgname let dtitle = if wasDepr then "Package deprecated" else "Package undeprecated" return $ toResponse $ Resource.XHtml $ hackagePage dtitle [ h2 << dtitle , paragraph << [ toHtml "Set the " , anchor ! [href $ deprecatedPackageUri versionsResource "" pkgname] << "deprecated status" , toHtml " for " , packageNameLink pkgname , toHtml "."] ] -- deprecated: checkbox, by: text field, space-separated list of packagenames serveDeprecateForm :: DynamicPath -> ServerPartE Response serveDeprecateForm dpath = do pkgname <- packageInPath dpath mpkg <- doDeprecatedRender pkgname let (isDepr, mfield) = case mpkg of Just pkgs -> (True, unwords $ map display pkgs) Nothing -> (False, "") return $ toResponse $ Resource.XHtml $ hackagePage "Deprecate package" [paragraph << [toHtml "Configure deprecation for ", packageNameLink pkgname], form . ulist ! [theclass "box", XHtml.method "post", action $ deprecatedPackageUri versionsResource "" pkgname] << [ hidden "_method" "PUT" , li . toHtml $ makeCheckbox isDepr "deprecated" "on" "Deprecate package" , li . toHtml $ makeInput [thetype "text", value mfield] "by" "Superseded by: " ++ [br, toHtml "(Optional; space-separated list of package names)"] , paragraph << input ! [thetype "submit", value "Set status"] ]] -- preferred: text box (one version range per line). deprecated: list of text boxes with same name servePreferForm :: DynamicPath -> ServerPartE Response servePreferForm dpath = do pkgname <- packageInPath dpath pkgs <- lookupPackageName pkgname pref <- doPreferredRender pkgname let allVersions = map packageVersion pkgs rangesList = rendRanges pref deprVersions = rendVersions pref return $ toResponse $ Resource.XHtml $ hackagePage "Adjust preferred versions" [concatHtml $ packagePrefAbout Nothing pkgname, form ! [theclass "box", XHtml.method "post", action $ preferredPackageUri versionsResource "" pkgname] << [ hidden "_method" "PUT" , paragraph << "Preferred version ranges." , paragraph << textarea ! [name "preferred", rows $ show (4::Int), cols $ show (80::Int)] << unlines rangesList , paragraph << "Deprecated versions." , toHtml $ intersperse (toHtml " ") $ map (\v -> toHtml $ makeCheckbox (v `elem` deprVersions) "deprecated" (display v) (display v)) allVersions , paragraph << input ! [thetype "submit", value "Set status"] ]] {------------------------------------------------------------------------------- Downloads -------------------------------------------------------------------------------} data HtmlDownloads = HtmlDownloads { htmlDownloadsResources :: [Resource] } mkHtmlDownloads :: HtmlUtilities -> DownloadFeature -> HtmlDownloads mkHtmlDownloads HtmlUtilities{..} DownloadFeature{..} = HtmlDownloads{..} where downs = downloadResource -- downloads htmlDownloadsResources = [ (extendResource $ topDownloads downs) { resourceGet = [("html", serveDownloadTop)] } ] serveDownloadTop :: DynamicPath -> ServerPartE Response serveDownloadTop _ = do pkgList <- sortedPackages `liftM` recentPackageDownloads return $ toResponse $ Resource.XHtml $ hackagePage "Total downloads" $ [ h2 << "Downloaded packages" , thediv << table << downTableRows pkgList ] where downTableRows pkgList = [ tr << [ th << "Package name", th << "Downloads" ] ] ++ [ tr ! [theclass (if odd n then "odd" else "even")] << [ td << packageNameLink pkgname , td << [ toHtml $ (show count) ] ] | ((pkgname, count), n) <- zip pkgList [(1::Int)..] ] sortedPackages :: RecentDownloads -> [(PackageName, Int)] sortedPackages = sortBy (flip compare `on` snd) . cmToList {------------------------------------------------------------------------------- Tags -------------------------------------------------------------------------------} data HtmlTags = HtmlTags { htmlTagsResources :: [Resource] , tagEdit :: Resource } mkHtmlTags :: HtmlUtilities -> CoreFeature -> ListFeature -> TagsFeature -> HtmlTags mkHtmlTags HtmlUtilities{..} CoreFeature{ coreResource = CoreResource{ packageInPath , lookupPackageName } } ListFeature{makeItemList} TagsFeature{..} = HtmlTags{..} where tags = tagsResource tagEdit = (resourceAt "/package/:package/tags/edit") { resourceGet = [("html", serveTagsForm)] } htmlTagsResources = [ (extendResource $ tagsListing tags) { resourceGet = [("html", serveTagsListing)] } , (extendResource $ tagListing tags) { resourceGet = [("html", serveTagListing)] } , (extendResource $ packageTagsListing tags) { resourcePut = [("html", putPackageTags)], resourceGet = [] } , tagEdit -- (extendResource $ packageTagsEdit tags) { resourceGet = [("html", serveTagsForm)] } ] serveTagsListing :: DynamicPath -> ServerPartE Response serveTagsListing _ = do tagList <- queryGetTagList let withCounts = filter ((>0) . snd) . map (\(tg, pkgs) -> (tg, Set.size pkgs)) $ tagList countSort = sortBy (flip compare `on` snd) withCounts return $ toResponse $ Resource.XHtml $ hackagePage "Hackage tags" $ [ h2 << "Hackage tags" , h4 << "By name" , paragraph ! [theclass "toc"] << (intersperse (toHtml ", ") $ map (tagItem . fst) withCounts) , h4 << "By frequency" , paragraph ! [theclass "toc"] << (intersperse (toHtml ", ") $ map (toHtml . tagCountItem) countSort) ] where tagCountItem (tg, count) = [ tagItem tg , toHtml $ " (" ++ show count ++ ")" ] tagItem tg = anchor ! [href $ tagUri tags "" tg] << display tg serveTagListing :: DynamicPath -> ServerPartE Response serveTagListing dpath = withTagPath dpath $ \tg pkgnames -> do let tagd = "Packages tagged " ++ display tg pkgs = Set.toList pkgnames items <- liftIO $ makeItemList pkgs let (mtag, histogram) = Map.updateLookupWithKey (\_ _ -> Nothing) tg $ tagHistogram items -- make a 'related tags' section, so exclude this tag from the histogram count = fromMaybe 0 mtag return $ toResponse $ Resource.XHtml $ hackagePage tagd $ [ h2 << tagd , case items of [] -> toHtml "No packages have this tag." _ -> toHtml [ paragraph << [if count==1 then "1 package has" else show count ++ " packages have", " this tag."] , paragraph ! [theclass "toc"] << [toHtml "Related tags: ", toHtml $ showHistogram histogram] , ulist ! [theclass "packages"] << map renderItem items ] ] where showHistogram hist = (++takeHtml) . intersperse (toHtml ", ") $ map histogramEntry $ take takeAmount sortHist where hsize = Map.size hist takeAmount = max (div (hsize*2) 3) 12 takeHtml = if takeAmount >= hsize then [] else [toHtml ", ..."] sortHist = sortBy (flip compare `on` snd) $ Map.toList hist histogramEntry (tg', count) = anchor ! [href $ tagUri tags "" tg'] << display tg' +++ (" (" ++ show count ++ ")") putPackageTags :: DynamicPath -> ServerPartE Response putPackageTags dpath = do pkgname <- packageInPath dpath _ <- lookupPackageName pkgname -- TODO: necessary? putTags pkgname return $ toResponse $ Resource.XHtml $ hackagePage "Set tags" [toHtml "Put tags for ", packageNameLink pkgname] -- serve form for editing, to be received by putTags serveTagsForm :: DynamicPath -> ServerPartE Response serveTagsForm dpath = do pkgname <- packageInPath dpath currTags <- queryTagsForPackage pkgname let tagsStr = concat . intersperse ", " . map display . Set.toList $ currTags return $ toResponse $ Resource.XHtml $ hackagePage "Edit package tags" [paragraph << [toHtml "Set tags for ", packageNameLink pkgname], form ! [theclass "box", XHtml.method "post", action $ packageTagsUri tags "" pkgname] << [ hidden "_method" "PUT" , dlist . ddef . toHtml $ makeInput [thetype "text", value tagsStr] "tags" "Set tags to " , paragraph << input ! [thetype "submit", value "Set tags"] ]] {------------------------------------------------------------------------------- Search -------------------------------------------------------------------------------} data HtmlSearch = HtmlSearch { htmlSearchResources :: [Resource] } mkHtmlSearch :: HtmlUtilities -> CoreFeature -> ListFeature -> SearchFeature -> HtmlSearch mkHtmlSearch HtmlUtilities{..} CoreFeature{..} ListFeature{makeItemList} SearchFeature{..} = HtmlSearch{..} where htmlSearchResources = [ (extendResource searchPackagesResource) { resourceGet = [("html", servePackageFind)] } ] servePackageFind :: DynamicPath -> ServerPartE Response servePackageFind _ = do (mtermsStr, offset, limit, mexplain) <- queryString $ (,,,) <$> optional (look "terms") <*> mplus (lookRead "offset") (pure 0) <*> mplus (lookRead "limit") (pure 100) <*> optional (look "explain") let explain = isJust mexplain case mtermsStr of Just termsStr | explain , terms <- words termsStr, not (null terms) -> do params <- queryString getSearchRankParameters results <- searchPackagesExplain params terms return $ toResponse $ Resource.XHtml $ hackagePage "Package search" $ [ toHtml $ paramsForm params termsStr , resetParamsForm termsStr , toHtml $ explainResults results ] Just termsStr | terms <- words termsStr, not (null terms) -> do pkgIndex <- liftIO $ queryGetPackageIndex currentTime <- liftIO $ getCurrentTime pkgnames <- searchPackages terms let (pageResults, moreResults) = splitAt limit (drop offset pkgnames) pkgDetails <- liftIO $ makeItemList pageResults return $ toResponse $ Resource.XHtml $ hackagePage "Package search" $ [ toHtml $ searchForm termsStr False , toHtml $ resultsArea pkgIndex currentTime pkgDetails offset limit moreResults termsStr , alternativeSearch ] _ -> return $ toResponse $ Resource.XHtml $ hackagePage "Text search" $ [ toHtml $ searchForm "" explain , alternativeSearch ] where resultsArea pkgIndex currentTime pkgDetails offset limit moreResults termsStr = [ h2 << "Results" , if offset == 0 then noHtml else paragraph << ("(" ++ show (fst range + 1) ++ " to " ++ show (snd range) ++ ")") , case pkgDetails of [] | offset == 0 -> toHtml "None" | otherwise -> toHtml "No more results" _ -> toHtml [ ulist ! [theclass "searchresults"] << map renderSearchResult pkgDetails , if null moreResults then noHtml else anchor ! [href moreResultsLink] << "More results..." ] ] where renderSearchResult :: PackageItem -> Html renderSearchResult item = li ! classes << [ packageNameLink pkgname , toHtml $ " " ++ ptype (itemHasLibrary item) (itemNumExecutables item) , br , toHtml (itemDesc item) , br , small ! [ theclass "info" ] << [ toHtml (renderTags (itemTags item)) , " Last uploaded " +++ humanTime ] ] where pkgname = itemName item timestamp = maximum $ map pkgOriginalUploadTime $ PackageIndex.lookupPackageName pkgIndex pkgname -- takes current time as argument so it can say how many $X ago something was humanTime = HumanTime.humanReadableTime' currentTime timestamp ptype _ 0 = "library" ptype lib num = (if lib then "library and " else "") ++ (case num of 1 -> "program"; _ -> "programs") classes = case classList of [] -> []; _ -> [theclass $ unwords classList] classList = (case itemDeprecated item of Nothing -> []; _ -> ["deprecated"]) range = (offset, offset + length pkgDetails) moreResultsLink = "/packages/search?" ++ "terms=" ++ escapeURIString isUnreserved termsStr ++ "&offset=" ++ show (offset + limit) ++ "&limit=" ++ show limit searchForm termsStr explain = [ h2 << "Package search" , form ! [XHtml.method "GET", action "/packages/search"] << [ input ! [value termsStr, name "terms", identifier "terms"] , toHtml " " , input ! [thetype "submit", value "Search"] , if explain then input ! [thetype "hidden", name "explain"] else noHtml ] ] alternativeSearch = paragraph << [ toHtml "Alternatively, if you are looking for a particular function then try " , anchor ! [href "http://holumbus.fh-wedel.de/hayoo/hayoo.html"] << "Hayoo" , toHtml " or " , anchor ! [href "http://www.haskell.org/hoogle/"] << "Hoogle" ] explainResults :: [(Search.Explanation PkgDocField PkgDocFeatures T.Text, PackageName)] -> [Html] explainResults results = [ h2 << "Results" , case results of [] -> noHtml ((explanation1, _):_) -> table ! [ border 1 ] << ( ( tr << tableHeader explanation1) : [ tr << tableRow explanation pkgname | (explanation, pkgname) <- results ]) ] where tableHeader Search.Explanation{..} = [ th << "package", th << "overall score" ] ++ [ th << (show term ++ " score") | (term, _score) <- termScores ] ++ [ th << (show term ++ " " ++ show field ++ " score") | (term, fieldScores) <- termFieldScores , (field, _score) <- fieldScores ] ++ [ th << (show feature ++ " score") | (feature, _score) <- nonTermScores ] tableRow Search.Explanation{..} pkgname = [ td << display pkgname, td << show overallScore ] ++ [ td << show score | (_term, score) <- termScores ] ++ [ td << show score | (_term, fieldScores) <- termFieldScores , (_field, score) <- fieldScores ] ++ [ td << show score | (_feature, score) <- nonTermScores ] getSearchRankParameters = do let defaults = defaultSearchRankParameters k1 <- lookRead "k1" `mplus` pure (paramK1 defaults) bs <- sequence [ lookRead ("b" ++ show field) `mplus` pure (paramB defaults field) | field <- Ix.range (minBound, maxBound :: PkgDocField) ] ws <- sequence [ lookRead ("w" ++ show field) `mplus` pure (paramFieldWeights defaults field) | field <- Ix.range (minBound, maxBound :: PkgDocField) ] fs <- sequence [ lookRead ("w" ++ show feature) `mplus` pure (paramFeatureWeights defaults feature) | feature <- Ix.range (minBound, maxBound :: PkgDocFeatures) ] let barr, warr :: Array PkgDocField Float barr = listArray (minBound, maxBound) bs warr = listArray (minBound, maxBound) ws farr = listArray (minBound, maxBound) fs return defaults { paramK1 = k1, paramB = (barr Array.!), paramFieldWeights = (warr Array.!), paramFeatureWeights = (farr Array.!) } paramsForm SearchRankParameters{..} termsStr = [ h2 << "Package search (tuning & explanation)" , form ! [XHtml.method "GET", action "/packages/search"] << [ input ! [value termsStr, name "terms", identifier "terms"] , toHtml " " , input ! [thetype "submit", value "Search"] , input ! [thetype "hidden", name "explain"] , simpleTable [] [] $ makeInput [thetype "text", value (show paramK1)] "k1" "K1 parameter" : [ makeInput [thetype "text", value (show (paramB field))] ("b" ++ fieldname) ("B param for " ++ fieldname) ++ makeInput [thetype "text", value (show (paramFieldWeights field)) ] ("w" ++ fieldname) ("Weight for " ++ fieldname) | field <- Ix.range (minBound, maxBound :: PkgDocField) , let fieldname = show field ] ++ [ makeInput [thetype "text", value (show (paramFeatureWeights feature)) ] ("w" ++ featurename) ("Weight for " ++ featurename) | feature <- Ix.range (minBound, maxBound :: PkgDocFeatures) , let featurename = show feature ] ] ] resetParamsForm termsStr = let SearchRankParameters{..} = defaultSearchRankParameters in form ! [XHtml.method "GET", action "/packages/search"] << (concat $ [ input ! [ thetype "submit", value "Reset parameters" ] , input ! [ thetype "hidden", name "terms", value termsStr ] , input ! [ thetype "hidden", name "explain" ] , input ! [ thetype "hidden", name "k1", value (show paramK1) ] ] : [ [ input ! [ thetype "hidden" , name ("b" ++ fieldname) , value (show (paramB field)) ] , input ! [ thetype "hidden" , name ("w" ++ fieldname) , value (show (paramFieldWeights field)) ] ] | field <- Ix.range (minBound, maxBound :: PkgDocField) , let fieldname = show field ] ++ [ [ input ! [ thetype "hidden" , name ("w" ++ featurename) , value (show (paramFeatureWeights feature)) ] ] | feature <- Ix.range (minBound, maxBound :: PkgDocFeatures) , let featurename = show feature ]) {------------------------------------------------------------------------------- Groups -------------------------------------------------------------------------------} htmlGroupResource :: UserFeature -> GroupResource -> [Resource] htmlGroupResource UserFeature{..} r@(GroupResource groupR userR getGroup) = [ (extendResource groupR) { resourceDesc = [ (GET, "Show list of users") , (POST, "Add a user to the group") ] , resourceGet = [ ("html", getList) ] , resourcePost = [ ("html", postUser) ] } , (extendResource userR) { resourceDesc = [ (DELETE, "Delete a user from the group") ] , resourceDelete = [ ("html", deleteFromGroup) ] } , (extendResourcePath "/edit" groupR) { resourceDesc = [ (GET, "Show edit form for the group") ] , resourceGet = [ ("html", getEditList) ] } ] where getList dpath = do group <- getGroup dpath userDb <- queryGetUserDb usergroup <- liftIO . queryUserGroup $ group let unames = [ Users.userIdToName userDb uid | uid <- Group.toList usergroup ] let baseUri = renderResource' groupR dpath return . toResponse . Resource.XHtml $ Pages.groupPage unames baseUri (False, False) (groupDesc group) getEditList dpath = do group <- getGroup dpath (canAdd, canDelete) <- lookupGroupEditAuth group userDb <- queryGetUserDb usergroup <- liftIO . queryUserGroup $ group let unames = [ Users.userIdToName userDb uid | uid <- Group.toList usergroup ] let baseUri = renderResource' groupR dpath return . toResponse . Resource.XHtml $ Pages.groupPage unames baseUri (canAdd, canDelete) (groupDesc group) postUser dpath = do group <- getGroup dpath groupAddUser group dpath goToList dpath deleteFromGroup dpath = do group <- getGroup dpath groupDeleteUser group dpath goToList dpath goToList dpath = seeOther (renderResource' (groupResource r) dpath) (toResponse ()) {------------------------------------------------------------------------------- Util -------------------------------------------------------------------------------} htmlUtilities :: CoreFeature -> TagsFeature -> HtmlUtilities htmlUtilities CoreFeature{coreResource} TagsFeature{tagsResource} = HtmlUtilities{..} where packageLink :: PackageId -> Html packageLink pkgid = anchor ! [href $ corePackageIdUri cores "" pkgid] << display pkgid packageNameLink :: PackageName -> Html packageNameLink pkgname = anchor ! [href $ corePackageNameUri cores "" pkgname] << display pkgname renderItem :: PackageItem -> Html renderItem item = li ! classes << [ packageNameLink pkgname , toHtml $ " " ++ ptype (itemHasLibrary item) (itemNumExecutables item) ++ ": " ++ itemDesc item , " (" +++ renderTags (itemTags item) +++ ")" ] where pkgname = itemName item ptype _ 0 = "library" ptype lib num = (if lib then "library and " else "") ++ (case num of 1 -> "program"; _ -> "programs") classes = case classList of [] -> []; _ -> [theclass $ unwords classList] classList = (case itemDeprecated item of Nothing -> []; _ -> ["deprecated"]) renderTags :: Set Tag -> [Html] renderTags tags = intersperse (toHtml ", ") (map (\tg -> anchor ! [href $ tagUri tagsResource "" tg] << display tg) $ Set.toList tags) cores = coreResource data HtmlUtilities = HtmlUtilities { packageLink :: PackageId -> Html , packageNameLink :: PackageName -> Html , renderItem :: PackageItem -> Html , renderTags :: Set Tag -> [Html] }
chrisdotcode/hackage-server
Distribution/Server/Features/Html.hs
bsd-3-clause
84,344
0
33
27,223
16,948
8,902
8,046
-1
-1
{-# LANGUAGE OverloadedStrings #-} module Main where import qualified Criterion.Main as C import GHC.Int import Control.DeepSeq import Data.List (foldl') import qualified Y.String as S benchCons :: String -> String -> C.Benchmark benchCons text name = C.bench name $ C.nf go "" where go start = foldr S.cons start text benchSnoc :: String -> String -> C.Benchmark benchSnoc text name = C.bench name $ C.nf go "" where go start = foldl' S.snoc start text benchLength :: S.YiString -> String -> C.Benchmark benchLength text name = C.bench name $ C.nf S.length text benchLines :: S.YiString -> String -> C.Benchmark benchLines text name = C.bench name $ C.nf (S.splitOnNewLines :: S.YiString -> [S.YiString]) text benchDrop :: S.YiString -> String -> C.Benchmark benchDrop text name = C.bench name $ C.nf (\x -> foldr S.drop x (replicate 1000 (1 :: Int64))) text benchTake :: S.YiString -> String -> C.Benchmark benchTake text name = C.bench name $ C.nf (\x -> foldr S.take x [1000, 999 .. 1 :: Int64]) text benchSplitAt text name = C.bench name $ C.nf (\x -> foldr ((fst .) . S.splitAt) x [1000, 999 .. 1 :: Int64]) text main :: IO () main = C.defaultMain [ benchCons longText "cons long" , benchCons wideText "cons wide" , benchSnoc longText "snoc long" , benchSnoc wideText "snoc wide" , benchLines longYiString "lines long" , benchLines wideYiString "lines wide" , benchDrop longYiString "drop long" , benchDrop wideYiString "drop wide" , benchTake longYiString "take long" , benchTake wideYiString "take wide" , benchSplitAt longYiString "splitAt long" , benchSplitAt wideYiString "splitAt wide" ] longText :: String longText = force . unlines $ replicate 1000 "Lorem ipsum dolor sit amet" {-# NOINLINE longText #-} longYiString :: S.YiString longYiString = force (S.fromString longText) {-# NOINLINE longYiString #-} wideText :: String wideText = force . unlines $ replicate 10 . concat $ replicate 100 "Lorem ipsum dolor sit amet " {-# NOINLINE wideText #-} wideYiString :: S.YiString wideYiString = force (S.fromString wideText) {-# NOINLINE wideYiString #-}
ethercrow/y
bench/BenchString.hs
bsd-3-clause
2,214
0
12
476
703
367
336
63
1
{-# LANGUAGE DeriveDataTypeable, DeriveFunctor, FlexibleInstances, GADTs, OverloadedStrings, RankNTypes, RecordWildCards, DefaultSignatures #-} -- | -- Module : Network.Wreq.Internal.Types -- Copyright : (c) 2014 Bryan O'Sullivan -- -- License : BSD-style -- Maintainer : [email protected] -- Stability : experimental -- Portability : GHC -- -- HTTP client types. module Network.Wreq.Internal.Types ( -- * Client configuration Options(..) , Mgr , Auth(..) , AWSAuthVersion(..) , ResponseChecker -- * Request payloads , Payload(..) , Postable(..) , Putable(..) -- ** URL-encoded forms , FormParam(..) , FormValue(..) -- * Headers , ContentType , Link(..) -- * Errors , JSONError(..) -- * Request types , Req(..) , reqURL -- * Sessions , Session(..) , Run , RunHistory , Body(..) -- * Caches , CacheEntry(..) ) where import Control.Exception (Exception) import Data.IORef (IORef) import Data.Monoid ((<>), mconcat) import Data.Text (Text) import Data.Time.Clock (UTCTime) import Data.Typeable (Typeable) import Network.HTTP.Client (CookieJar, Manager, ManagerSettings, Request, RequestBody) import Network.HTTP.Client.Internal (Response, Proxy) import Network.HTTP.Types (Header) import Prelude hiding (head) import qualified Data.ByteString.Char8 as S import qualified Data.ByteString.Lazy as L import qualified Network.HTTP.Client as HTTP -- | A MIME content type, e.g. @\"application/octet-stream\"@. type ContentType = S.ByteString type Mgr = Either ManagerSettings Manager -- | Options for configuring a client. data Options = Options { manager :: Mgr -- ^ Either configuration for a 'Manager', or an actual 'Manager'. -- -- If only 'ManagerSettings' are provided, then by default a new -- 'Manager' will be created for each request. -- -- /Note/: when issuing HTTP requests using 'Options'-based -- functions from the the "Network.Wreq.Session" module -- ('Network.Wreq.Session.getWith', 'Network.Wreq.Session.putWith', -- etc.), this field will be ignored. -- -- An example of using a specific manager: -- -- @ --import "Network.HTTP.Client" ('Network.HTTP.Client.withManager') -- --'Network.HTTP.Client.withManager' $ \\mgr -> do -- let opts = 'Network.Wreq.defaults' { 'manager' = Right mgr } -- 'Network.Wreq.getWith' opts \"http:\/\/httpbin.org\/get\" -- @ -- -- An example of changing settings (this will use a separate -- 'Manager' for every request, so make sense only if you're issuing -- a tiny handful of requets): -- -- @ --import "Network.HTTP.Client" ('Network.HTTP.Client.defaultManagerSettings') -- --let settings = 'Network.HTTP.Client.defaultManagerSettings' { managerConnCount = 5 } -- opts = 'Network.Wreq.defaults' { 'manager' = Left settings } --'Network.Wreq.getWith' opts \"http:\/\/httpbin.org\/get\" -- @ , proxy :: Maybe Proxy -- ^ Host name and port for a proxy to use, if any. , auth :: Maybe Auth -- ^ Authentication information. -- -- Example (note the use of TLS): -- -- @ --let opts = 'Network.Wreq.defaults' { 'auth' = 'Network.Wreq.basicAuth' \"user\" \"pass\" } --'Network.Wreq.getWith' opts \"https:\/\/httpbin.org\/basic-auth\/user\/pass\" -- @ , headers :: [Header] -- ^ Additional headers to send with each request. -- -- @ --let opts = 'Network.Wreq.defaults' { 'headers' = [(\"Accept\", \"*\/*\")] } --'Network.Wreq.getWith' opts \"http:\/\/httpbin.org\/get\" -- @ , params :: [(Text, Text)] -- ^ Key-value pairs to assemble into a query string to add to the -- end of a URL. -- -- For example, given: -- -- @ --let opts = 'Network.Wreq.defaults' { params = [(\"sort\", \"ascending\"), (\"key\", \"name\")] } --'Network.Wreq.getWith' opts \"http:\/\/httpbin.org\/get\" -- @ -- -- This will generate a URL of the form: -- -- >http://httpbin.org/get?sort=ascending&key=name , redirects :: Int -- ^ The maximum number of HTTP redirects to follow before giving up -- and throwing an exception. -- -- In this example, a 'Network.HTTP.Client.HttpException' will be -- thrown with a 'Network.HTTP.Client.TooManyRedirects' constructor, -- because the maximum number of redirects allowed will be exceeded: -- -- @ --let opts = 'Network.Wreq.defaults' { 'redirects' = 3 } --'Network.Wreq.getWith' opts \"http:\/\/httpbin.org\/redirect/5\" -- @ , cookies :: Maybe CookieJar -- ^ Cookies to set when issuing requests. -- -- /Note/: when issuing HTTP requests using 'Options'-based -- functions from the the "Network.Wreq.Session" module -- ('Network.Wreq.Session.getWith', 'Network.Wreq.Session.putWith', -- etc.), this field will be used only for the /first/ HTTP request -- to be issued during a 'Network.Wreq.Session.Session'. Any changes -- changes made for subsequent requests will be ignored. , checkResponse :: Maybe ResponseChecker -- ^ Function that checks the status code and potentially returns an -- exception. -- -- This defaults to 'Nothing', which will just use the default of -- 'Network.HTTP.Client.Request' which throws a 'StatusException' if -- the status is not 2XX. } deriving (Typeable) -- | A function that checks the result of a HTTP request and -- potentially throw an exception. type ResponseChecker = Request -> Response HTTP.BodyReader -> IO () -- | Supported authentication types. -- -- Do not use HTTP authentication unless you are using TLS encryption. -- These authentication tokens can easily be captured and reused by an -- attacker if transmitted in the clear. data Auth = BasicAuth S.ByteString S.ByteString -- ^ Basic authentication. This consists of a plain -- username and password. | OAuth2Bearer S.ByteString -- ^ An OAuth2 bearer token. This is treated by many -- services as the equivalent of a username and password. | OAuth2Token S.ByteString -- ^ A not-quite-standard OAuth2 bearer token (that seems -- to be used only by GitHub). This is treated by whoever -- accepts it as the equivalent of a username and -- password. | AWSAuth AWSAuthVersion S.ByteString S.ByteString (Maybe S.ByteString) -- ^ Amazon Web Services request signing -- AWSAuthVersion key secret (optional: session-token) | AWSFullAuth AWSAuthVersion S.ByteString S.ByteString (Maybe S.ByteString) (Maybe (S.ByteString, S.ByteString)) -- ^ Amazon Web Services request signing -- AWSAuthVersion key secret Maybe (service, region) | OAuth1 S.ByteString S.ByteString S.ByteString S.ByteString -- ^ OAuth1 request signing -- OAuth1 consumerToken consumerSecret token secret deriving (Eq, Show, Typeable) data AWSAuthVersion = AWSv4 -- ^ AWS request signing version 4 deriving (Eq, Show) instance Show Options where show (Options{..}) = concat [ "Options { " , "manager = ", case manager of Left _ -> "Left _" Right _ -> "Right _" , ", proxy = ", show proxy , ", auth = ", show auth , ", headers = ", show headers , ", params = ", show params , ", redirects = ", show redirects , ", cookies = ", show cookies , " }" ] -- | A type that can be converted into a POST request payload. class Postable a where postPayload :: a -> Request -> IO Request default postPayload :: Putable a => a -> Request -> IO Request postPayload = putPayload -- ^ Represent a value in the request body (and perhaps the -- headers) of a POST request. -- | A type that can be converted into a PUT request payload. class Putable a where putPayload :: a -> Request -> IO Request -- ^ Represent a value in the request body (and perhaps the -- headers) of a PUT request. -- | A product type for representing more complex payload types. data Payload where Raw :: ContentType -> RequestBody -> Payload deriving (Typeable) -- | A type that can be rendered as the value portion of a key\/value -- pair for use in an @application\/x-www-form-urlencoded@ POST -- body. Intended for use with the 'FormParam' type. -- -- The instances for 'String', strict 'Data.Text.Text', and lazy -- 'Data.Text.Lazy.Text' are all encoded using UTF-8 before being -- URL-encoded. -- -- The instance for 'Maybe' gives an empty string on 'Nothing', -- and otherwise uses the contained type's instance. class FormValue a where renderFormValue :: a -> S.ByteString -- ^ Render the given value. -- | A key\/value pair for an @application\/x-www-form-urlencoded@ -- POST request body. data FormParam where (:=) :: (FormValue v) => S.ByteString -> v -> FormParam instance Show FormParam where show (a := b) = show a ++ " := " ++ show (renderFormValue b) infixr 3 := -- | The error type used by 'Network.Wreq.asJSON' and -- 'Network.Wreq.asValue' if a failure occurs when parsing a response -- body as JSON. data JSONError = JSONError String deriving (Show, Typeable) instance Exception JSONError -- | An element of a @Link@ header. data Link = Link { linkURL :: S.ByteString , linkParams :: [(S.ByteString, S.ByteString)] } deriving (Eq, Show, Typeable) -- | A request that is ready to be submitted. data Req = Req Mgr Request -- | Return the URL associated with the given 'Req'. -- -- This includes the port number if not standard, and the query string -- if one exists. reqURL :: Req -> S.ByteString reqURL (Req _ req) = mconcat [ if https then "https" else "http" , "://" , HTTP.host req , case (HTTP.port req, https) of (80, False) -> "" (443, True) -> "" (p, _) -> S.pack (show p) , HTTP.path req , case HTTP.queryString req of qs | S.null qs -> "" | otherwise -> "?" <> qs ] where https = HTTP.secure req -- | A function that runs a request and returns the associated -- response. type Run body = Req -> IO (Response body) type RunHistory body = Req -> IO (HTTP.HistoriedResponse body) -- | A session that spans multiple requests. This is responsible for -- cookie management and TCP connection reuse. data Session = Session { seshCookies :: Maybe (IORef CookieJar) , seshManager :: Manager , seshRun :: Session -> Run Body -> Run Body , seshRunHistory :: Session -> RunHistory Body -> RunHistory Body } instance Show Session where show _ = "Session" data CacheEntry body = CacheEntry { entryCreated :: UTCTime , entryExpires :: Maybe UTCTime , entryResponse :: Response body } deriving (Functor) data Body = NoBody | StringBody L.ByteString | ReaderBody HTTP.BodyReader instance Show (CacheEntry body) where show _ = "CacheEntry"
bos/wreq
Network/Wreq/Internal/Types.hs
bsd-3-clause
10,972
1
14
2,500
1,510
927
583
130
4
{-# LANGUAGE OverloadedStrings #-} module Main where import WordVectors.Utils (countWords) main :: IO () main = do counts <- countWords "/projects/programming-collective-intelligence/test/Data/FeedData.xml" putStrLn $ show counts
vprokopchuk256/programming-collective-intelligence
app/Main.hs
bsd-3-clause
281
0
8
76
50
26
24
7
1
{-| Module : Network.Kademlia.Tree Description : Implementation of the Node Storage Tree Network.Kademlia.Tree implements the Node Storage Tree used to store and look up the known nodes. This module is designed to be used as a qualified import. -} module Network.Kademlia.Tree ( NodeTree , create , insert , lookup , delete , handleTimeout , findClosest , extractId , toList , fold ) where import Prelude hiding (lookup) import Network.Kademlia.Types import qualified Data.List as L (find, delete) data NodeTree i = NodeTree ByteStruct (NodeTreeElem i) data NodeTreeElem i = Split (NodeTreeElem i) (NodeTreeElem i) | Bucket ([(Node i, Int)], [Node i]) type NodeTreeFunction i a = Int -> Bool -> ([(Node i, Int)], [Node i]) -> a -- | Modify the position in the tree where the supplied id would be modifyAt :: (Serialize i) => NodeTree i -> i -> NodeTreeFunction i (NodeTreeElem i) -> NodeTree i modifyAt (NodeTree idStruct elem) id f = let targetStruct = toByteStruct id newElems = go idStruct targetStruct 0 True elem in NodeTree idStruct newElems where -- This function is partial, but we know that there will alwasys be a -- bucket at the end. Therefore, we don't have to check for empty -- ByteStructs -- -- Apply the function to the position of the bucket go _ _ depth valid (Bucket b) = f depth valid b -- If the bit is a 0, go left go (i:is) (False:ts) depth valid (Split left right) = let new = go is ts (depth + 1) (valid && not i) left in Split new right -- Otherwise, continue to the right go (i:is) (True:ts) depth valid (Split left right) = let new = go is ts (depth + 1) (valid && i) right in Split left new -- | Modify and apply a function at the position in the tree where the -- supplied id would be bothAt :: (Serialize i) => NodeTree i -> i -> NodeTreeFunction i (NodeTreeElem i, a) -> (NodeTree i, a) bothAt (NodeTree idStruct elem) id f = let targetStruct = toByteStruct id (newElems, val) = go idStruct targetStruct 0 True elem in (NodeTree idStruct newElems, val) where -- This function is partial, but we know that there will alwasys be a -- bucket at the end. Therefore, we don't have to check for empty -- ByteStructs -- -- Apply the function to the position of the bucket go _ _ depth valid (Bucket b) = f depth valid b -- If the bit is a 0, go left go (i:is) (False:ts) depth valid (Split left right) = let (new, val) = go is ts (depth + 1) (valid && not i) left in (Split new right, val) -- Otherwise, continue to the right go (i:is) (True:ts) depth valid (Split left right) = let (new, val) = go is ts (depth + 1) (valid && i) right in (Split left new, val) -- | Apply a function to the bucket the supplied id would be located in applyAt :: (Serialize i) => NodeTree i -> i -> NodeTreeFunction i a -> a applyAt (NodeTree idStruct elem) id f = let targetStruct = toByteStruct id in go idStruct targetStruct 0 True elem where -- This function is partial for the same reason as in modifyAt -- -- Apply the function go _ _ depth valid (Bucket b) = f depth valid b -- If the bit is a 0, go left go (i:is) (False:ts) depth valid (Split left _) = go is ts (depth + 1) (valid && not i) left -- Otherwise, continue to the right go (i:is) (True:ts) depth valid (Split _ right) = go is ts (depth + 1) (valid && i) right -- | Create a NodeTree corresponding to the id create :: (Serialize i) => i -> NodeTree i create id = NodeTree (toByteStruct id) . Bucket $ ([], []) -- | Lookup a node within a NodeTree lookup :: (Serialize i, Eq i) => NodeTree i -> i -> Maybe (Node i) lookup tree id = applyAt tree id f where f _ _ = L.find (idMatches id) . map fst . fst -- | Delete a Node corresponding to a supplied Id from a NodeTree delete :: (Serialize i, Eq i) => NodeTree i -> i -> NodeTree i delete tree id = modifyAt tree id f where f _ _ (nodes, cache) = let deleted = filter (not . idMatches id . fst) $ nodes in Bucket (deleted, cache) -- | Handle a timed out node by incrementing its timeoutCount and deleting it -- if the count exceeds the limit. Also, return wether it's reasonable to ping -- the node again. handleTimeout :: (Serialize i, Eq i) => NodeTree i -> i -> (NodeTree i, Bool) handleTimeout tree id = bothAt tree id f where f _ _ (nodes, cache) = case L.find (idMatches id . fst) nodes of -- Delete a node that exceeded the limit. Don't contact it again -- as it is now considered dead Just x@(_, 4) -> (Bucket (L.delete x $ nodes, cache), False) -- Increment the timeoutCount Just x@(n, timeoutCount) -> (Bucket ((n, timeoutCount + 1) : L.delete x nodes, cache), True) -- Don't contact an unknown node a second time Nothing -> (Bucket (nodes, cache), False) -- | Refresh the node corresponding to a supplied Id by placing it at the first -- index of it's KBucket and reseting its timeoutCount, then return a Bucket -- NodeTreeElem refresh :: (Serialize i, Eq i) => Node i -> ([(Node i, Int)], [Node i]) -> NodeTreeElem i refresh node (nodes, cache) = Bucket (case L.find (idMatches (nodeId node) . fst) nodes of Just x@(n, _) -> (n, 0) : L.delete x nodes _ -> nodes , cache) -- | Insert a node into a NodeTree insert :: (Serialize i, Eq i) => NodeTree i -> Node i -> NodeTree i insert tree node = if applyAt tree (nodeId node) needsSplit -- Split the tree before inserting, when it makes sense then let splitTree = split tree . nodeId $ node in insert splitTree node -- Insert the node else modifyAt tree (nodeId node) doInsert where needsSplit depth valid (nodes, _) = let maxDepth = (length . toByteStruct . nodeId $ node) - 1 in -- A new node will be inserted node `notElem` map fst nodes && -- The bucket is full length nodes >= 7 && -- The bucket may be split (depth < 5 || valid) && depth <= maxDepth doInsert _ _ b@(nodes, cache) -- Refresh an already existing node | node `elem` map fst nodes = refresh node b -- Simply insert the node, if the bucket isn't full | length nodes < 7 = Bucket ((node, 0):nodes, cache) -- Move the node to the first spot, if it's already cached | node `elem` cache = Bucket (nodes, node : L.delete node cache) -- Cache the node and drop older ones, if necessary | otherwise = Bucket (nodes, node : take 4 cache) -- | Split the KBucket the specified id would reside in into two and return a -- Split NodeTreeElem split :: (Serialize i) => NodeTree i -> i -> NodeTree i split tree splitId = modifyAt tree splitId f where f depth _ (nodes, cache) = let (leftNodes, rightNodes) = splitBucket depth fst nodes (leftCache, rightCache) = splitBucket depth id cache in Split (Bucket (leftNodes, leftCache)) (Bucket (rightNodes, rightCache)) -- Recursivly split the nodes into two buckets splitBucket _ _ [] = ([], []) splitBucket i f (n:ns) = let bs = toByteStruct . nodeId . f $ n bit = bs !! i (left, right) = splitBucket i f ns in if bit then (left, n:right) else (n:left, right) -- | Find the k closest Nodes to a given Id findClosest :: (Serialize i) => NodeTree i -> i -> Int -> [Node i] findClosest (NodeTree idStruct elem) id n = let targetStruct = toByteStruct id in go idStruct targetStruct elem n where -- This function is partial for the same reason as in modifyAt -- -- Take the n closest nodes go _ _ (Bucket (nodes, _)) n | length nodes <= n = map fst nodes | otherwise = take n . sortByDistanceTo (map fst nodes) $ id -- Take the closest nodes from the left child first, if those aren't -- enough, take the rest from the right go (i:is) (False:ts) (Split left right) n = let result = go is ts left n in if length result == n then result else result ++ go is ts right n -- Take the closest nodes from the right child first, if those aren't -- enough, take the rest from the left go (i:is) (True:ts) (Split left right) n = let result = go is ts right n in if length result == n then result else result ++ go is ts left n -- Extract original Id from NodeTree extractId :: (Serialize i) => NodeTree i -> i extractId (NodeTree id _) = fromByteStruct id -- | Helper function used for KBucket manipulation idMatches :: (Eq i) => i -> Node i -> Bool idMatches id node = id == nodeId node -- | Turn the NodeTree into a list of nodes toList :: NodeTree i -> [Node i] toList (NodeTree _ elems) = go elems where go (Split left right) = go left ++ go right go (Bucket b) = map fst . fst $ b -- | Fold over the buckets fold :: ([Node i] -> a -> a) -> a -> NodeTree i -> a fold f init (NodeTree _ elems) = go init elems where go a (Split left right) = let a' = go a left in go a' right go a (Bucket b) = f (map fst . fst $ b) a
froozen/kademlia
src/Network/Kademlia/Tree.hs
bsd-3-clause
10,088
0
16
3,339
2,975
1,553
1,422
137
5
{-# LANGUAGE RankNTypes #-} module LiftMe.Database.DB ( DB , connection , withDB ) where import Data.Text (Text) import qualified Data.Text as T import qualified Database.HDBC as HDBC import qualified Database.HDBC.PostgreSQL as PG data DB = DB { m_con :: PG.Connection } -- | Get PostgreSQL connection connection :: DB -> PG.Connection connection = m_con -- | Connect to a PostgreSQL server and automatically disconnect if the -- handler exits normally or throws an exception withDB :: String -- PostgreSQL connection string -> (DB -> IO a) -> IO a withDB conStr action = PG.withPostgreSQL conStr $ \con -> action (DB con) -------------------------------------------------------------------------------- -- Queries
nilscc/weightlifting.cc
src-hs/LiftMe/Database/DB.hs
bsd-3-clause
741
0
9
129
152
92
60
18
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 GADTs #-} {-# LANGUAGE OverloadedStrings #-} module Duckling.Ordinal.NL.Rules ( rules ) where import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HashMap import Data.Text (Text) import qualified Data.Text as Text import Prelude import Data.String import Duckling.Dimensions.Types import Duckling.Numeral.Helpers (parseInt) import Duckling.Ordinal.Helpers import Duckling.Regex.Types import Duckling.Types zeroNineteenMap :: HashMap Text Int zeroNineteenMap = HashMap.fromList [ ("eerste", 1) , ("tweede", 2) , ("derde", 3) , ("vierde", 4) , ("vijfde", 5) , ("zesde", 6) , ("zevende", 7) , ("achste", 8) , ("negende", 9) , ("tiende", 10) , ("elfde", 11) , ("twaalfde", 12) , ("dertiende", 13) , ("veertiende", 14) , ("vijftiende", 15) , ("zestiende", 16) , ("zeventiende", 17) , ("achttiende", 18) , ("negentiende", 19) ] ruleOrdinalsFirstth :: Rule ruleOrdinalsFirstth = Rule { name = "ordinals (first..19th)" , pattern = [ regex "(eerste|tweede|derde|vierde|vijfde|zeste|zevende|achtste|negende|tiende|elfde|twaalfde|veertiende|vijftiende|zestiende|zeventiende|achttiende|negentiende)" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> ordinal <$> HashMap.lookup (Text.toLower match) zeroNineteenMap _ -> Nothing } ruleOrdinalDigits :: Rule ruleOrdinalDigits = Rule { name = "ordinal (digits)" , pattern = [ regex "0*(\\d+)(\\.| ?(ste|de))" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> ordinal <$> parseInt match _ -> Nothing } rules :: [Rule] rules = [ ruleOrdinalDigits , ruleOrdinalsFirstth ]
facebookincubator/duckling
Duckling/Ordinal/NL/Rules.hs
bsd-3-clause
1,942
0
17
366
500
309
191
58
2
module M where data Bool = True | False (&&) :: Bool -> Bool -> Bool class C a where c:: a -> a -> Bool class D a where d:: a -> a -> Bool instance C Bool where c = (&&) instance D Bool where d = (&&) instance (C a, D a) => C [a] where c [] [] = True c (a:x) (b:y) = let cab = c a b cxy = c x y in if d a b then cab && cxy else cab || cxy c _ _ = False --c1 = c [True,True] [True,False] f x = c [[[x]]]
rodrigogribeiro/mptc
test/TesteCarlos.hs
bsd-3-clause
480
0
10
184
245
132
113
18
1
-- -- HTTP client for use with io-streams -- -- Copyright Β© 2012-2013 Operational Dynamics Consulting, Pty Ltd -- -- The code in this file, and the program it is a part of, is made -- available to you by its authors as open source software: you can -- redistribute it and/or modify it under a BSD licence. -- {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS -fno-warn-unused-imports #-} module Snippet where import Control.Applicative import Control.Exception (bracket) import Data.Aeson import Data.Aeson.Encode.Pretty import Data.Aeson.Types (parseEither) import Data.Attoparsec.ByteString import Data.Text hiding (empty) import GHC.Generics import Network.Http.Client import qualified System.IO.Streams.Attoparsec as Streams -- -- Otherwise redundent imports, but useful for testing in GHCi. -- import Blaze.ByteString.Builder (Builder) import qualified Blaze.ByteString.Builder as Builder import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as S import qualified Data.ByteString.Lazy as L import Debug.Trace import System.Exit (exitSuccess) import System.IO.Streams (InputStream, OutputStream, stdout) import qualified System.IO.Streams as Streams main = main0 blob = "{\"name\": \"Kennedy\"}" :: L.ByteString main0 :: IO () main0 = do c <- openConnection "ip.jsontest.com" 80 q <- buildRequest $ do http GET "/" setAccept "application/json" putStr $ show q -- Requests [headers] are terminated by a double newline -- already. We need a better way of emitting debug -- information mid-stream from this library. sendRequest c q emptyBody x <- receiveResponse c jsonHandler :: IO IP L.putStr $ encodePretty x closeConnection c experiment :: IO () experiment = do let (Just result) = decode blob :: Maybe Person putStr $ show result {- let ve = parseOnly json' blob case ve of Left str -> error str Right v -> L.putStr $ encodePretty v -} data Person = Person { name :: Text } deriving (Show) instance FromJSON Person where parseJSON (Object o) = do n <- o .: "name" return Person { name = n } parseJSON _ = empty data IP = IP { ip :: Text } deriving (Show, Generic) instance FromJSON IP instance ToJSON IP
afcowie/pipes-http
tests/JsonSnippet.hs
bsd-3-clause
2,397
0
11
560
478
272
206
53
1
{-# LANGUAGE DuplicateRecordFields #-} module AST.Expression where import AST.V0_16 import qualified AST.Pattern as Pattern import qualified AST.Variable as Var import qualified Reporting.Annotation as A ---- GENERAL AST ---- data UnaryOperator = Negative deriving (Eq, Show) data LetDeclaration = LetDefinition Pattern.Pattern [(Comments, Pattern.Pattern)] Comments Expr | LetAnnotation (Var.Ref, Comments) (Comments, Type) | LetComment Comment deriving (Eq, Show) type Expr = A.Located Expr' type IfClause = (Commented Expr, Commented Expr) data Expr' = Unit Comments | Literal Literal | VarExpr Var.Ref | App Expr [(Comments, Expr)] FunctionApplicationMultiline | Unary UnaryOperator Expr | Binops Expr [(Comments, Var.Ref, Comments, Expr)] Bool | Parens (Commented Expr) | ExplicitList { terms :: Sequence Expr , trailingComments :: Comments , forceMultiline :: ForceMultiline } | Range (Commented Expr) (Commented Expr) Bool | Tuple [Commented Expr] Bool | TupleFunction Int -- will be 2 or greater, indicating the number of elements in the tuple | Record { base :: Maybe (Commented LowercaseIdentifier) , fields :: Sequence (Pair LowercaseIdentifier Expr) , trailingComments :: Comments , forceMultiline :: ForceMultiline } | Access Expr LowercaseIdentifier | AccessFunction LowercaseIdentifier | Lambda [(Comments, Pattern.Pattern)] Comments Expr Bool | If IfClause [(Comments, IfClause)] (Comments, Expr) | Let [LetDeclaration] Comments Expr | Case (Commented Expr, Bool) [(Commented Pattern.Pattern, (Comments, Expr))] -- for type checking and code gen only | GLShader String deriving (Eq, Show) instance A.Strippable Expr' where stripRegion d = case d of App e0 es b -> App (A.stripRegion $ A.map A.stripRegion e0) (map (fmap (A.stripRegion . A.map A.stripRegion)) es) b Tuple es b -> Tuple (map (fmap (A.stripRegion . A.map A.stripRegion)) es) b _ -> d
rgrempel/frelm.org
vendor/elm-format/parser/src/AST/Expression.hs
mit
2,154
0
17
554
612
348
264
59
0
{-# LANGUAGE Safe #-} -- | Read/Write a CNF file only with ghc standard libraries module SAT.Mios.Util.DIMACS ( -- * Input fromFile , clauseListFromFile , fromMinisatOutput , clauseListFromMinisatOutput -- * Output , toFile , toDIMACSString , asDIMACSString , asDIMACSString_ -- * Bool Operation , module SAT.Mios.Util.BoolExp ) where import SAT.Mios.Util.DIMACS.Reader import SAT.Mios.Util.DIMACS.Writer import SAT.Mios.Util.DIMACS.MinisatReader import SAT.Mios.Util.BoolExp -- | String from BoolFrom asDIMACSString :: BoolForm -> String asDIMACSString = toDIMACSString . asList -- | String from BoolFrom asDIMACSString_ :: BoolForm -> String asDIMACSString_ = toDIMACSString . asList_
shnarazk/mios
src/SAT/Mios/Util/DIMACS.hs
gpl-3.0
803
0
5
202
116
79
37
20
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.StorageGateway.DescribeGatewayInformation -- 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. -- | This operation returns metadata about a gateway such as its name, network -- interfaces, configured time zone, and the state (whether the gateway is -- running or not). To specify which gateway to describe, use the Amazon -- Resource Name (ARN) of the gateway in your request. -- -- <http://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DescribeGatewayInformation.html> module Network.AWS.StorageGateway.DescribeGatewayInformation ( -- * Request DescribeGatewayInformation -- ** Request constructor , describeGatewayInformation -- ** Request lenses , dgiGatewayARN -- * Response , DescribeGatewayInformationResponse -- ** Response constructor , describeGatewayInformationResponse -- ** Response lenses , dgirGatewayARN , dgirGatewayId , dgirGatewayNetworkInterfaces , dgirGatewayState , dgirGatewayTimezone , dgirGatewayType , dgirNextUpdateAvailabilityDate ) where import Network.AWS.Data (Object) import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.StorageGateway.Types import qualified GHC.Exts newtype DescribeGatewayInformation = DescribeGatewayInformation { _dgiGatewayARN :: Text } deriving (Eq, Ord, Read, Show, Monoid, IsString) -- | 'DescribeGatewayInformation' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'dgiGatewayARN' @::@ 'Text' -- describeGatewayInformation :: Text -- ^ 'dgiGatewayARN' -> DescribeGatewayInformation describeGatewayInformation p1 = DescribeGatewayInformation { _dgiGatewayARN = p1 } dgiGatewayARN :: Lens' DescribeGatewayInformation Text dgiGatewayARN = lens _dgiGatewayARN (\s a -> s { _dgiGatewayARN = a }) data DescribeGatewayInformationResponse = DescribeGatewayInformationResponse { _dgirGatewayARN :: Maybe Text , _dgirGatewayId :: Maybe Text , _dgirGatewayNetworkInterfaces :: List "GatewayNetworkInterfaces" NetworkInterface , _dgirGatewayState :: Maybe Text , _dgirGatewayTimezone :: Maybe Text , _dgirGatewayType :: Maybe Text , _dgirNextUpdateAvailabilityDate :: Maybe Text } deriving (Eq, Read, Show) -- | 'DescribeGatewayInformationResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'dgirGatewayARN' @::@ 'Maybe' 'Text' -- -- * 'dgirGatewayId' @::@ 'Maybe' 'Text' -- -- * 'dgirGatewayNetworkInterfaces' @::@ ['NetworkInterface'] -- -- * 'dgirGatewayState' @::@ 'Maybe' 'Text' -- -- * 'dgirGatewayTimezone' @::@ 'Maybe' 'Text' -- -- * 'dgirGatewayType' @::@ 'Maybe' 'Text' -- -- * 'dgirNextUpdateAvailabilityDate' @::@ 'Maybe' 'Text' -- describeGatewayInformationResponse :: DescribeGatewayInformationResponse describeGatewayInformationResponse = DescribeGatewayInformationResponse { _dgirGatewayARN = Nothing , _dgirGatewayId = Nothing , _dgirGatewayTimezone = Nothing , _dgirGatewayState = Nothing , _dgirGatewayNetworkInterfaces = mempty , _dgirGatewayType = Nothing , _dgirNextUpdateAvailabilityDate = Nothing } dgirGatewayARN :: Lens' DescribeGatewayInformationResponse (Maybe Text) dgirGatewayARN = lens _dgirGatewayARN (\s a -> s { _dgirGatewayARN = a }) -- | The gateway ID. dgirGatewayId :: Lens' DescribeGatewayInformationResponse (Maybe Text) dgirGatewayId = lens _dgirGatewayId (\s a -> s { _dgirGatewayId = a }) -- | A 'NetworkInterface' array that contains descriptions of the gateway network -- interfaces. dgirGatewayNetworkInterfaces :: Lens' DescribeGatewayInformationResponse [NetworkInterface] dgirGatewayNetworkInterfaces = lens _dgirGatewayNetworkInterfaces (\s a -> s { _dgirGatewayNetworkInterfaces = a }) . _List -- | One of the values that indicates the operating state of the gateway. dgirGatewayState :: Lens' DescribeGatewayInformationResponse (Maybe Text) dgirGatewayState = lens _dgirGatewayState (\s a -> s { _dgirGatewayState = a }) -- | One of the values that indicates the time zone configured for the gateway. dgirGatewayTimezone :: Lens' DescribeGatewayInformationResponse (Maybe Text) dgirGatewayTimezone = lens _dgirGatewayTimezone (\s a -> s { _dgirGatewayTimezone = a }) -- | TBD dgirGatewayType :: Lens' DescribeGatewayInformationResponse (Maybe Text) dgirGatewayType = lens _dgirGatewayType (\s a -> s { _dgirGatewayType = a }) -- | The date at which an update to the gateway is available. This date is in the -- time zone of the gateway. If the gateway is not available for an update this -- field is not returned in the response. dgirNextUpdateAvailabilityDate :: Lens' DescribeGatewayInformationResponse (Maybe Text) dgirNextUpdateAvailabilityDate = lens _dgirNextUpdateAvailabilityDate (\s a -> s { _dgirNextUpdateAvailabilityDate = a }) instance ToPath DescribeGatewayInformation where toPath = const "/" instance ToQuery DescribeGatewayInformation where toQuery = const mempty instance ToHeaders DescribeGatewayInformation instance ToJSON DescribeGatewayInformation where toJSON DescribeGatewayInformation{..} = object [ "GatewayARN" .= _dgiGatewayARN ] instance AWSRequest DescribeGatewayInformation where type Sv DescribeGatewayInformation = StorageGateway type Rs DescribeGatewayInformation = DescribeGatewayInformationResponse request = post "DescribeGatewayInformation" response = jsonResponse instance FromJSON DescribeGatewayInformationResponse where parseJSON = withObject "DescribeGatewayInformationResponse" $ \o -> DescribeGatewayInformationResponse <$> o .:? "GatewayARN" <*> o .:? "GatewayId" <*> o .:? "GatewayNetworkInterfaces" .!= mempty <*> o .:? "GatewayState" <*> o .:? "GatewayTimezone" <*> o .:? "GatewayType" <*> o .:? "NextUpdateAvailabilityDate"
romanb/amazonka
amazonka-storagegateway/gen/Network/AWS/StorageGateway/DescribeGatewayInformation.hs
mpl-2.0
7,048
0
22
1,440
900
533
367
98
1
{-| Definition of the data collectors used by MonD. -} {- Copyright (C) 2014 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.DataCollectors( collectors ) where import Data.Map (findWithDefault) import Data.Monoid (mempty) import qualified Ganeti.DataCollectors.CPUload as CPUload import qualified Ganeti.DataCollectors.Diskstats as Diskstats import qualified Ganeti.DataCollectors.Drbd as Drbd import qualified Ganeti.DataCollectors.InstStatus as InstStatus import qualified Ganeti.DataCollectors.Lv as Lv import Ganeti.DataCollectors.Types (DataCollector(..),ReportBuilder(..)) import Ganeti.JSON (GenericContainer(..)) import Ganeti.Objects import Ganeti.Types -- | The list of available builtin data collectors. collectors :: [DataCollector] collectors = [ cpuLoadCollector , diskStatsCollector , drdbCollector , instStatusCollector , lvCollector ] where f .&&. g = \x y -> f x y && g x y xenHypervisor = flip elem [XenPvm, XenHvm] xenCluster _ cfg = any xenHypervisor . clusterEnabledHypervisors $ configCluster cfg collectorConfig name cfg = let config = fromContainer . clusterDataCollectors $ configCluster cfg in findWithDefault mempty name config updateInterval name cfg = dataCollectorInterval $ collectorConfig name cfg activeConfig name cfg = dataCollectorActive $ collectorConfig name cfg diskStatsCollector = DataCollector Diskstats.dcName Diskstats.dcCategory Diskstats.dcKind (StatelessR Diskstats.dcReport) Nothing activeConfig updateInterval drdbCollector = DataCollector Drbd.dcName Drbd.dcCategory Drbd.dcKind (StatelessR Drbd.dcReport) Nothing activeConfig updateInterval instStatusCollector = DataCollector InstStatus.dcName InstStatus.dcCategory InstStatus.dcKind (StatelessR InstStatus.dcReport) Nothing (xenCluster .&&. activeConfig) updateInterval lvCollector = DataCollector Lv.dcName Lv.dcCategory Lv.dcKind (StatelessR Lv.dcReport) Nothing activeConfig updateInterval cpuLoadCollector = DataCollector CPUload.dcName CPUload.dcCategory CPUload.dcKind (StatefulR CPUload.dcReport) (Just CPUload.dcUpdate) activeConfig updateInterval
apyrgio/ganeti
src/Ganeti/DataCollectors.hs
bsd-2-clause
3,479
0
12
586
489
270
219
46
1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 \section[TcMovectle]{Typechecking a whole module} https://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/TypeChecker -} {-# LANGUAGE CPP #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NondecreasingIndentation #-} module TcRnDriver ( #ifdef GHCI tcRnStmt, tcRnExpr, tcRnType, tcRnImportDecls, tcRnLookupRdrName, getModuleInterface, tcRnDeclsi, isGHCiMonad, runTcInteractive, -- Used by GHC API clients (Trac #8878) #endif tcRnLookupName, tcRnGetInfo, tcRnModule, tcRnModuleTcRnM, tcTopSrcDecls, ) where #ifdef GHCI import {-# SOURCE #-} TcSplice ( finishTH ) import RnSplice ( rnTopSpliceDecls, traceSplice, SpliceInfo(..) ) import IfaceEnv( externaliseName ) import TcHsType import TcMatches import RnTypes import RnExpr import MkId import TidyPgm ( globaliseAndTidyId ) import TysWiredIn ( unitTy, mkListTy ) import DynamicLoading ( loadPlugins ) import Plugins ( tcPlugin ) #endif import DynFlags import StaticFlags import HsSyn import PrelNames import RdrName import TcHsSyn import TcExpr import TcRnMonad import TcEvidence import PprTyThing( pprTyThing ) import Coercion( pprCoAxiom ) import CoreFVs( orphNamesOfFamInst ) import FamInst import InstEnv import FamInstEnv import TcAnnotations import TcBinds import HeaderInfo ( mkPrelImports ) import TcDefaults import TcEnv import TcRules import TcForeign import TcInstDcls import TcIface import TcMType import TcType import MkIface import TcSimplify import TcTyClsDecls import TcTypeable ( mkTypeableBinds ) import LoadIface import TidyPgm ( mkBootModDetailsTc ) import RnNames import RnEnv import RnSource import ErrUtils import Id import IdInfo import VarEnv import Module import UniqFM import Name import NameEnv import NameSet import Avail import TyCon import SrcLoc import HscTypes import ListSetOps import Outputable import ConLike import DataCon import PatSyn import Type import Class import BasicTypes hiding( SuccessFlag(..) ) import CoAxiom import Annotations import Data.List ( sortBy ) import Data.Ord import FastString import Maybes import Util import Bag import Inst (tcGetInsts) import qualified GHC.LanguageExtensions as LangExt import Control.Monad #include "HsVersions.h" {- ************************************************************************ * * Typecheck and rename a module * * ************************************************************************ -} -- | Top level entry point for typechecker and renamer tcRnModule :: HscEnv -> HscSource -> Bool -- True <=> save renamed syntax -> HsParsedModule -> IO (Messages, Maybe TcGblEnv) tcRnModule hsc_env hsc_src save_rn_syntax parsedModule@HsParsedModule {hpm_module=L loc this_module} | RealSrcSpan real_loc <- loc = do { showPass (hsc_dflags hsc_env) "Renamer/typechecker" ; ; initTc hsc_env hsc_src save_rn_syntax this_mod real_loc $ withTcPlugins hsc_env $ tcRnModuleTcRnM hsc_env hsc_src parsedModule pair } | otherwise = return ((emptyBag, unitBag err_msg), Nothing) where err_msg = mkPlainErrMsg (hsc_dflags hsc_env) loc $ text "Module does not have a RealSrcSpan:" <+> ppr this_mod this_pkg = thisPackage (hsc_dflags hsc_env) pair :: (Module, SrcSpan) pair@(this_mod,_) | Just (L mod_loc mod) <- hsmodName this_module = (mkModule this_pkg mod, mod_loc) | otherwise -- 'module M where' is omitted = (mAIN, srcLocSpan (srcSpanStart loc)) -- To be called at the beginning of renaming hsig files. -- If we're processing a signature, load up the RdrEnv -- specified by sig-of so that -- when we process top-level bindings, we pull in the right -- original names. We also need to add in dependencies from -- the implementation (orphans, family instances, packages), -- similar to how rnImportDecl handles things. -- ToDo: Handle SafeHaskell tcRnSignature :: DynFlags -> HscSource -> TcRn TcGblEnv tcRnSignature dflags hsc_src = do { tcg_env <- getGblEnv ; case tcg_sig_of tcg_env of { Just sof | hsc_src /= HsigFile -> do { addErr (text "Illegal -sig-of specified for non hsig") ; return tcg_env } | otherwise -> do { sig_iface <- initIfaceTcRn $ loadSysInterface (text "sig-of") sof ; let { gr = mkGlobalRdrEnv (gresFromAvails Nothing (mi_exports sig_iface)) ; avails = calculateAvails dflags sig_iface False{- safe -} False{- boot -} } ; return (tcg_env { tcg_impl_rdr_env = Just gr , tcg_imports = tcg_imports tcg_env `plusImportAvails` avails }) } ; Nothing | HsigFile <- hsc_src , HscNothing <- hscTarget dflags -> do { return tcg_env } | HsigFile <- hsc_src -> do { addErr (text "Missing -sig-of for hsig") ; failM } | otherwise -> return tcg_env } } checkHsigIface :: HscEnv -> TcGblEnv -> TcRn () checkHsigIface hsc_env tcg_env = case tcg_impl_rdr_env tcg_env of Just gr -> do { sig_details <- liftIO $ mkBootModDetailsTc hsc_env tcg_env ; checkHsigIface' gr sig_details } Nothing -> return () checkHsigIface' :: GlobalRdrEnv -> ModDetails -> TcRn () checkHsigIface' gr ModDetails { md_insts = sig_insts, md_fam_insts = sig_fam_insts, md_types = sig_type_env, md_exports = sig_exports} = do { traceTc "checkHsigIface" $ vcat [ ppr sig_type_env, ppr sig_insts, ppr sig_exports ] ; mapM_ check_export sig_exports ; unless (null sig_fam_insts) $ panic ("TcRnDriver.checkHsigIface: Cannot handle family " ++ "instances in hsig files yet...") ; mapM_ check_inst sig_insts ; failIfErrsM } where check_export sig_avail -- Skip instances, we'll check them later | name `elem` dfun_names = return () | otherwise = do { -- Lookup local environment only (don't want to accidentally pick -- up the backing copy.) We consult tcg_type_env because we want -- to pick up wired in names too (which get dropped by the iface -- creation process); it's OK for a signature file to mention -- a wired in name. env <- getGblEnv ; case lookupNameEnv (tcg_type_env env) name of Nothing -- All this means is no local definition is available: but we -- could have created the export this way: -- -- module ASig(f) where -- import B(f) -- -- In this case, we have to just lookup the identifier in -- the backing implementation and make sure it matches. | [GRE { gre_name = name' }] <- lookupGlobalRdrEnv gr (nameOccName name) , name == name' -> return () -- TODO: Possibly give a different error if the identifier -- is exported, but it's a different original name | otherwise -> addErrAt (nameSrcSpan name) (missingBootThing False name "exported by") Just sig_thing -> do { -- We use tcLookupImported_maybe because we want to EXCLUDE -- tcg_env. ; r <- tcLookupImported_maybe name ; case r of Failed err -> addErr err Succeeded real_thing -> checkBootDeclM False sig_thing real_thing }} where name = availName sig_avail dfun_names = map getName sig_insts -- In general, for hsig files we can't assume that the implementing -- file actually implemented the instances (they may be reexported -- from elsewhere). Where should we look for the instances? We do -- the same as we would otherwise: consult the EPS. This isn't -- perfect (we might conclude the module exports an instance -- when it doesn't, see #9422), but we will never refuse to compile -- something check_inst :: ClsInst -> TcM () check_inst sig_inst = do eps <- getEps when (not (memberInstEnv (eps_inst_env eps) sig_inst)) $ addErrTc (instMisMatch False sig_inst) tcRnModuleTcRnM :: HscEnv -> HscSource -> HsParsedModule -> (Module, SrcSpan) -> TcRn TcGblEnv -- Factored out separately from tcRnModule so that a Core plugin can -- call the type checker directly tcRnModuleTcRnM hsc_env hsc_src (HsParsedModule { hpm_module = (L loc (HsModule maybe_mod export_ies import_decls local_decls mod_deprec maybe_doc_hdr)), hpm_src_files = src_files }) (this_mod, prel_imp_loc) = setSrcSpan loc $ do { let { dflags = hsc_dflags hsc_env ; explicit_mod_hdr = isJust maybe_mod } ; tcg_env <- tcRnSignature dflags hsc_src ; setGblEnv tcg_env $ do { -- Load the hi-boot interface for this module, if any -- We do this now so that the boot_names can be passed -- to tcTyAndClassDecls, because the boot_names are -- automatically considered to be loop breakers -- -- Do this *after* tcRnImports, so that we know whether -- a module that we import imports us; and hence whether to -- look for a hi-boot file boot_info <- tcHiBootIface hsc_src this_mod ; setGblEnv (tcg_env { tcg_self_boot = boot_info }) $ do { -- Deal with imports; first add implicit prelude implicit_prelude <- xoptM LangExt.ImplicitPrelude; let { prel_imports = mkPrelImports (moduleName this_mod) prel_imp_loc implicit_prelude import_decls } ; whenWOptM Opt_WarnImplicitPrelude $ when (notNull prel_imports) $ addWarn (Reason Opt_WarnImplicitPrelude) (implicitPreludeWarn) ; tcg_env <- {-# SCC "tcRnImports" #-} tcRnImports hsc_env (prel_imports ++ import_decls) ; -- If the whole module is warned about or deprecated -- (via mod_deprec) record that in tcg_warns. If we do thereby add -- a WarnAll, it will override any subseqent depracations added to tcg_warns let { tcg_env1 = case mod_deprec of Just (L _ txt) -> tcg_env { tcg_warns = WarnAll txt } Nothing -> tcg_env } ; setGblEnv tcg_env1 $ do { -- Rename and type check the declarations traceRn (text "rn1a") ; tcg_env <- if isHsBootOrSig hsc_src then tcRnHsBootDecls hsc_src local_decls else {-# SCC "tcRnSrcDecls" #-} tcRnSrcDecls explicit_mod_hdr local_decls ; setGblEnv tcg_env $ do { -- Process the export list traceRn (text "rn4a: before exports"); (rn_exports, tcg_env) <- rnExports explicit_mod_hdr export_ies tcg_env ; tcExports rn_exports ; traceRn (text "rn4b: after exports") ; -- Check that main is exported (must be after rnExports) checkMainExported tcg_env ; -- Compare the hi-boot iface (if any) with the real thing -- Must be done after processing the exports tcg_env <- checkHiBootIface tcg_env boot_info ; -- Compare the hsig tcg_env with the real thing checkHsigIface hsc_env tcg_env ; -- Nub out type class instances now that we've checked them, -- if we're compiling an hsig with sig-of. -- See Note [Signature files and type class instances] tcg_env <- (case tcg_sig_of tcg_env of Just _ -> return tcg_env { tcg_inst_env = emptyInstEnv, tcg_fam_inst_env = emptyFamInstEnv, tcg_insts = [], tcg_fam_insts = [] } Nothing -> return tcg_env) ; -- The new type env is already available to stuff slurped from -- interface files, via TcEnv.updateGlobalTypeEnv -- It's important that this includes the stuff in checkHiBootIface, -- because the latter might add new bindings for boot_dfuns, -- which may be mentioned in imported unfoldings -- Don't need to rename the Haddock documentation, -- it's not parsed by GHC anymore. tcg_env <- return (tcg_env { tcg_doc_hdr = maybe_doc_hdr }) ; -- Report unused names reportUnusedNames export_ies tcg_env ; -- add extra source files to tcg_dependent_files addDependentFiles src_files ; -- Dump output and return tcDump tcg_env ; return tcg_env }}}}} implicitPreludeWarn :: SDoc implicitPreludeWarn = text "Module `Prelude' implicitly imported" {- ************************************************************************ * * Import declarations * * ************************************************************************ -} tcRnImports :: HscEnv -> [LImportDecl RdrName] -> TcM TcGblEnv tcRnImports hsc_env import_decls = do { (rn_imports, rdr_env, imports, hpc_info) <- rnImports import_decls ; ; this_mod <- getModule ; let { dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface) ; dep_mods = imp_dep_mods imports -- We want instance declarations from all home-package -- modules below this one, including boot modules, except -- ourselves. The 'except ourselves' is so that we don't -- get the instances from this module's hs-boot file. This -- filtering also ensures that we don't see instances from -- modules batch (@--make@) compiled before this one, but -- which are not below this one. ; want_instances :: ModuleName -> Bool ; want_instances mod = mod `elemUFM` dep_mods && mod /= moduleName this_mod ; (home_insts, home_fam_insts) = hptInstances hsc_env want_instances } ; -- Record boot-file info in the EPS, so that it's -- visible to loadHiBootInterface in tcRnSrcDecls, -- and any other incrementally-performed imports ; updateEps_ (\eps -> eps { eps_is_boot = dep_mods }) ; -- Update the gbl env ; updGblEnv ( \ gbl -> gbl { tcg_rdr_env = tcg_rdr_env gbl `plusGlobalRdrEnv` rdr_env, tcg_imports = tcg_imports gbl `plusImportAvails` imports, tcg_rn_imports = rn_imports, tcg_inst_env = extendInstEnvList (tcg_inst_env gbl) home_insts, tcg_fam_inst_env = extendFamInstEnvList (tcg_fam_inst_env gbl) home_fam_insts, tcg_hpc = hpc_info }) $ do { ; traceRn (text "rn1" <+> ppr (imp_dep_mods imports)) -- Fail if there are any errors so far -- The error printing (if needed) takes advantage -- of the tcg_env we have now set -- ; traceIf (text "rdr_env: " <+> ppr rdr_env) ; failIfErrsM -- Load any orphan-module and family instance-module -- interfaces, so that their rules and instance decls will be -- found. But filter out a self hs-boot: these instances -- will be checked when we define them locally. ; loadModuleInterfaces (text "Loading orphan modules") (filter (/= this_mod) (imp_orphs imports)) -- Check type-family consistency ; traceRn (text "rn1: checking family instance consistency") ; let { dir_imp_mods = moduleEnvKeys . imp_mods $ imports } ; checkFamInstConsistency (imp_finsts imports) dir_imp_mods ; ; getGblEnv } } {- ************************************************************************ * * Type-checking the top level of a module * * ************************************************************************ -} tcRnSrcDecls :: Bool -- False => no 'module M(..) where' header at all -> [LHsDecl RdrName] -- Declarations -> TcM TcGblEnv -- Returns the variables free in the decls -- Reason: solely to report unused imports and bindings tcRnSrcDecls explicit_mod_hdr decls = do { -- Do all the declarations ; ((tcg_env, tcl_env), lie) <- captureConstraints $ do { (tcg_env, tcl_env) <- tc_rn_src_decls decls ; ; tcg_env <- setEnvs (tcg_env, tcl_env) $ checkMain explicit_mod_hdr ; return (tcg_env, tcl_env) } ; setEnvs (tcg_env, tcl_env) $ do { -- Emit Typeable bindings ; tcg_env <- setGblEnv tcg_env mkTypeableBinds ; setGblEnv tcg_env $ do { #ifdef GHCI ; finishTH #endif /* GHCI */ -- wanted constraints from static forms ; stWC <- tcg_static_wc <$> getGblEnv >>= readTcRef -- Finish simplifying class constraints -- -- simplifyTop deals with constant or ambiguous InstIds. -- How could there be ambiguous ones? They can only arise if a -- top-level decl falls under the monomorphism restriction -- and no subsequent decl instantiates its type. -- -- We do this after checkMain, so that we use the type info -- that checkMain adds -- -- We do it with both global and local env in scope: -- * the global env exposes the instances to simplifyTop -- * the local env exposes the local Ids to simplifyTop, -- so that we get better error messages (monomorphism restriction) ; new_ev_binds <- {-# SCC "simplifyTop" #-} simplifyTop (andWC stWC lie) ; traceTc "Tc9" empty ; failIfErrsM -- Don't zonk if there have been errors -- It's a waste of time; and we may get debug warnings -- about strangely-typed TyCons! ; traceTc "Tc10" empty -- Zonk the final code. This must be done last. -- Even simplifyTop may do some unification. -- This pass also warns about missing type signatures ; let { TcGblEnv { tcg_type_env = type_env, tcg_binds = binds, tcg_ev_binds = cur_ev_binds, tcg_imp_specs = imp_specs, tcg_rules = rules, tcg_vects = vects, tcg_fords = fords } = tcg_env ; all_ev_binds = cur_ev_binds `unionBags` new_ev_binds } ; ; (bind_ids, ev_binds', binds', fords', imp_specs', rules', vects') <- {-# SCC "zonkTopDecls" #-} zonkTopDecls all_ev_binds binds rules vects imp_specs fords ; ; traceTc "Tc11" empty ; let { final_type_env = extendTypeEnvWithIds type_env bind_ids ; tcg_env' = tcg_env { tcg_binds = binds', tcg_ev_binds = ev_binds', tcg_imp_specs = imp_specs', tcg_rules = rules', tcg_vects = vects', tcg_fords = fords' } } ; ; setGlobalTypeEnv tcg_env' final_type_env } } } tc_rn_src_decls :: [LHsDecl RdrName] -> TcM (TcGblEnv, TcLclEnv) -- Loops around dealing with each top level inter-splice group -- in turn, until it's dealt with the entire module tc_rn_src_decls ds = {-# SCC "tc_rn_src_decls" #-} do { (first_group, group_tail) <- findSplice ds -- If ds is [] we get ([], Nothing) -- Deal with decls up to, but not including, the first splice ; (tcg_env, rn_decls) <- rnTopSrcDecls first_group -- rnTopSrcDecls fails if there are any errors #ifdef GHCI -- Get TH-generated top-level declarations and make sure they don't -- contain any splices since we don't handle that at the moment ; th_topdecls_var <- fmap tcg_th_topdecls getGblEnv ; th_ds <- readTcRef th_topdecls_var ; writeTcRef th_topdecls_var [] ; (tcg_env, rn_decls) <- if null th_ds then return (tcg_env, rn_decls) else do { (th_group, th_group_tail) <- findSplice th_ds ; case th_group_tail of { Nothing -> return () ; ; Just (SpliceDecl (L loc _) _, _) -> setSrcSpan loc $ addErr (text "Declaration splices are not permitted inside top-level declarations added with addTopDecls") } ; -- Rename TH-generated top-level declarations ; (tcg_env, th_rn_decls) <- setGblEnv tcg_env $ rnTopSrcDecls th_group -- Dump generated top-level declarations ; let msg = "top-level declarations added with addTopDecls" ; traceSplice $ SpliceInfo { spliceDescription = msg , spliceIsDecl = True , spliceSource = Nothing , spliceGenerated = ppr th_rn_decls } ; return (tcg_env, appendGroups rn_decls th_rn_decls) } #endif /* GHCI */ -- Type check all declarations ; (tcg_env, tcl_env) <- setGblEnv tcg_env $ tcTopSrcDecls rn_decls -- If there is no splice, we're nearly done ; setEnvs (tcg_env, tcl_env) $ case group_tail of { Nothing -> return (tcg_env, tcl_env) #ifndef GHCI -- There shouldn't be a splice ; Just (SpliceDecl {}, _) -> failWithTc (text "Can't do a top-level splice; need a bootstrapped compiler") } #else -- If there's a splice, we must carry on ; Just (SpliceDecl (L _ splice) _, rest_ds) -> do { -- Rename the splice expression, and get its supporting decls (spliced_decls, splice_fvs) <- checkNoErrs (rnTopSpliceDecls splice) -- Glue them on the front of the remaining decls and loop ; setGblEnv (tcg_env `addTcgDUs` usesOnly splice_fvs) $ tc_rn_src_decls (spliced_decls ++ rest_ds) } } #endif /* GHCI */ } {- ************************************************************************ * * Compiling hs-boot source files, and comparing the hi-boot interface with the real thing * * ************************************************************************ -} tcRnHsBootDecls :: HscSource -> [LHsDecl RdrName] -> TcM TcGblEnv tcRnHsBootDecls hsc_src decls = do { (first_group, group_tail) <- findSplice decls -- Rename the declarations ; (tcg_env, HsGroup { hs_tyclds = tycl_decls , hs_instds = inst_decls , hs_derivds = deriv_decls , hs_fords = for_decls , hs_defds = def_decls , hs_ruleds = rule_decls , hs_vects = vect_decls , hs_annds = _ , hs_valds = ValBindsOut val_binds val_sigs }) <- rnTopSrcDecls first_group -- The empty list is for extra dependencies coming from .hs-boot files -- See Note [Extra dependencies from .hs-boot files] in RnSource ; (gbl_env, lie) <- captureConstraints $ setGblEnv tcg_env $ do { -- Check for illegal declarations ; case group_tail of Just (SpliceDecl d _, _) -> badBootDecl hsc_src "splice" d Nothing -> return () ; mapM_ (badBootDecl hsc_src "foreign") for_decls ; mapM_ (badBootDecl hsc_src "default") def_decls ; mapM_ (badBootDecl hsc_src "rule") rule_decls ; mapM_ (badBootDecl hsc_src "vect") vect_decls -- Typecheck type/class/instance decls ; traceTc "Tc2 (boot)" empty ; (tcg_env, inst_infos, _deriv_binds) <- tcTyClsInstDecls tycl_decls inst_decls deriv_decls val_binds ; setGblEnv tcg_env $ do { -- Typecheck value declarations ; traceTc "Tc5" empty ; val_ids <- tcHsBootSigs val_binds val_sigs -- Wrap up -- No simplification or zonking to do ; traceTc "Tc7a" empty ; gbl_env <- getGblEnv -- Make the final type-env -- Include the dfun_ids so that their type sigs -- are written into the interface file. ; let { type_env0 = tcg_type_env gbl_env ; type_env1 = extendTypeEnvWithIds type_env0 val_ids -- Don't add the dictionaries for hsig, we don't actually want -- to /define/ the instance ; type_env2 | HsigFile <- hsc_src = type_env1 | otherwise = extendTypeEnvWithIds type_env1 dfun_ids ; dfun_ids = map iDFunId inst_infos } ; setGlobalTypeEnv gbl_env type_env2 }} ; traceTc "boot" (ppr lie); return gbl_env } badBootDecl :: HscSource -> String -> Located decl -> TcM () badBootDecl hsc_src what (L loc _) = addErrAt loc (char 'A' <+> text what <+> text "declaration is not (currently) allowed in a" <+> (case hsc_src of HsBootFile -> text "hs-boot" HsigFile -> text "hsig" _ -> panic "badBootDecl: should be an hsig or hs-boot file") <+> text "file") {- Once we've typechecked the body of the module, we want to compare what we've found (gathered in a TypeEnv) with the hi-boot details (if any). -} checkHiBootIface :: TcGblEnv -> SelfBootInfo -> TcM TcGblEnv -- Compare the hi-boot file for this module (if there is one) -- with the type environment we've just come up with -- In the common case where there is no hi-boot file, the list -- of boot_names is empty. checkHiBootIface tcg_env boot_info | NoSelfBoot <- boot_info -- Common case = return tcg_env | HsBootFile <- tcg_src tcg_env -- Current module is already a hs-boot file! = return tcg_env | SelfBoot { sb_mds = boot_details } <- boot_info , TcGblEnv { tcg_binds = binds , tcg_insts = local_insts , tcg_type_env = local_type_env , tcg_exports = local_exports } <- tcg_env = do { dfun_prs <- checkHiBootIface' local_insts local_type_env local_exports boot_details ; let boot_dfuns = map fst dfun_prs dfun_binds = listToBag [ mkVarBind boot_dfun (nlHsVar dfun) | (boot_dfun, dfun) <- dfun_prs ] type_env' = extendTypeEnvWithIds local_type_env boot_dfuns tcg_env' = tcg_env { tcg_binds = binds `unionBags` dfun_binds } ; setGlobalTypeEnv tcg_env' type_env' } -- Update the global type env *including* the knot-tied one -- so that if the source module reads in an interface unfolding -- mentioning one of the dfuns from the boot module, then it -- can "see" that boot dfun. See Trac #4003 | otherwise = panic "checkHiBootIface: unreachable code" checkHiBootIface' :: [ClsInst] -> TypeEnv -> [AvailInfo] -> ModDetails -> TcM [(Id, Id)] -- Variant which doesn't require a full TcGblEnv; you could get the -- local components from another ModDetails. -- -- We return a list of "impedance-matching" bindings for the dfuns -- defined in the hs-boot file, such as -- $fxEqT = $fEqT -- We need these because the module and hi-boot file might differ in -- the name it chose for the dfun. checkHiBootIface' local_insts local_type_env local_exports (ModDetails { md_insts = boot_insts, md_fam_insts = boot_fam_insts, md_types = boot_type_env, md_exports = boot_exports }) = do { traceTc "checkHiBootIface" $ vcat [ ppr boot_type_env, ppr boot_insts, ppr boot_exports] -- Check the exports of the boot module, one by one ; mapM_ check_export boot_exports -- Check for no family instances ; unless (null boot_fam_insts) $ panic ("TcRnDriver.checkHiBootIface: Cannot handle family " ++ "instances in boot files yet...") -- FIXME: Why? The actual comparison is not hard, but what would -- be the equivalent to the dfun bindings returned for class -- instances? We can't easily equate tycons... -- Check instance declarations -- and generate an impedance-matching binding ; mb_dfun_prs <- mapM check_inst boot_insts ; failIfErrsM ; return (catMaybes mb_dfun_prs) } where check_export boot_avail -- boot_avail is exported by the boot iface | name `elem` dfun_names = return () | isWiredInName name = return () -- No checking for wired-in names. In particular, -- 'error' is handled by a rather gross hack -- (see comments in GHC.Err.hs-boot) -- Check that the actual module exports the same thing | not (null missing_names) = addErrAt (nameSrcSpan (head missing_names)) (missingBootThing True (head missing_names) "exported by") -- If the boot module does not *define* the thing, we are done -- (it simply re-exports it, and names match, so nothing further to do) | isNothing mb_boot_thing = return () -- Check that the actual module also defines the thing, and -- then compare the definitions | Just real_thing <- lookupTypeEnv local_type_env name, Just boot_thing <- mb_boot_thing = checkBootDeclM True boot_thing real_thing | otherwise = addErrTc (missingBootThing True name "defined in") where name = availName boot_avail mb_boot_thing = lookupTypeEnv boot_type_env name missing_names = case lookupNameEnv local_export_env name of Nothing -> [name] Just avail -> availNames boot_avail `minusList` availNames avail dfun_names = map getName boot_insts local_export_env :: NameEnv AvailInfo local_export_env = availsToNameEnv local_exports check_inst :: ClsInst -> TcM (Maybe (Id, Id)) -- Returns a pair of the boot dfun in terms of the equivalent -- real dfun. Delicate (like checkBootDecl) because it depends -- on the types lining up precisely even to the ordering of -- the type variables in the foralls. check_inst boot_inst = case [dfun | inst <- local_insts, let dfun = instanceDFunId inst, idType dfun `eqType` boot_dfun_ty ] of [] -> do { traceTc "check_inst" $ vcat [ text "local_insts" <+> vcat (map (ppr . idType . instanceDFunId) local_insts) , text "boot_inst" <+> ppr boot_inst , text "boot_dfun_ty" <+> ppr boot_dfun_ty ] ; addErrTc (instMisMatch True boot_inst) ; return Nothing } (dfun:_) -> return (Just (local_boot_dfun, dfun)) where local_boot_dfun = Id.mkExportedVanillaId boot_dfun_name (idType dfun) -- Name from the /boot-file/ ClsInst, but type from the dfun -- defined in /this module/. That ensures that the TyCon etc -- inside the type are the ones defined in this module, not -- the ones gotten from the hi-boot file, which may have -- a lot less info (Trac #T8743, comment:10). where boot_dfun = instanceDFunId boot_inst boot_dfun_ty = idType boot_dfun boot_dfun_name = idName boot_dfun -- This has to compare the TyThing from the .hi-boot file to the TyThing -- in the current source file. We must be careful to allow alpha-renaming -- where appropriate, and also the boot declaration is allowed to omit -- constructors and class methods. -- -- See rnfail055 for a good test of this stuff. -- | Compares two things for equivalence between boot-file and normal code, -- reporting an error if they don't match up. checkBootDeclM :: Bool -- ^ True <=> an hs-boot file (could also be a sig) -> TyThing -> TyThing -> TcM () checkBootDeclM is_boot boot_thing real_thing = whenIsJust (checkBootDecl boot_thing real_thing) $ \ err -> addErrAt (nameSrcSpan (getName boot_thing)) (bootMisMatch is_boot err real_thing boot_thing) -- | Compares the two things for equivalence between boot-file and normal -- code. Returns @Nothing@ on success or @Just "some helpful info for user"@ -- failure. If the difference will be apparent to the user, @Just empty@ is -- perfectly suitable. checkBootDecl :: TyThing -> TyThing -> Maybe SDoc checkBootDecl (AnId id1) (AnId id2) = ASSERT(id1 == id2) check (idType id1 `eqType` idType id2) (text "The two types are different") checkBootDecl (ATyCon tc1) (ATyCon tc2) = checkBootTyCon tc1 tc2 checkBootDecl (AConLike (RealDataCon dc1)) (AConLike (RealDataCon _)) = pprPanic "checkBootDecl" (ppr dc1) checkBootDecl _ _ = Just empty -- probably shouldn't happen -- | Combines two potential error messages andThenCheck :: Maybe SDoc -> Maybe SDoc -> Maybe SDoc Nothing `andThenCheck` msg = msg msg `andThenCheck` Nothing = msg Just d1 `andThenCheck` Just d2 = Just (d1 $$ d2) infixr 0 `andThenCheck` -- | If the test in the first parameter is True, succeed with @Nothing@; -- otherwise, return the provided check checkUnless :: Bool -> Maybe SDoc -> Maybe SDoc checkUnless True _ = Nothing checkUnless False k = k -- | Run the check provided for every pair of elements in the lists. -- The provided SDoc should name the element type, in the plural. checkListBy :: (a -> a -> Maybe SDoc) -> [a] -> [a] -> SDoc -> Maybe SDoc checkListBy check_fun as bs whats = go [] as bs where herald = text "The" <+> whats <+> text "do not match" go [] [] [] = Nothing go docs [] [] = Just (hang (herald <> colon) 2 (vcat $ reverse docs)) go docs (x:xs) (y:ys) = case check_fun x y of Just doc -> go (doc:docs) xs ys Nothing -> go docs xs ys go _ _ _ = Just (hang (herald <> colon) 2 (text "There are different numbers of" <+> whats)) -- | If the test in the first parameter is True, succeed with @Nothing@; -- otherwise, fail with the given SDoc. check :: Bool -> SDoc -> Maybe SDoc check True _ = Nothing check False doc = Just doc -- | A more perspicuous name for @Nothing@, for @checkBootDecl@ and friends. checkSuccess :: Maybe SDoc checkSuccess = Nothing ---------------- checkBootTyCon :: TyCon -> TyCon -> Maybe SDoc checkBootTyCon tc1 tc2 | not (eqType (tyConKind tc1) (tyConKind tc2)) = Just $ text "The types have different kinds" -- First off, check the kind | Just c1 <- tyConClass_maybe tc1 , Just c2 <- tyConClass_maybe tc2 , let (clas_tvs1, clas_fds1, sc_theta1, _, ats1, op_stuff1) = classExtraBigSig c1 (clas_tvs2, clas_fds2, sc_theta2, _, ats2, op_stuff2) = classExtraBigSig c2 , Just env <- eqVarBndrs emptyRnEnv2 clas_tvs1 clas_tvs2 = let eqSig (id1, def_meth1) (id2, def_meth2) = check (name1 == name2) (text "The names" <+> pname1 <+> text "and" <+> pname2 <+> text "are different") `andThenCheck` check (eqTypeX env op_ty1 op_ty2) (text "The types of" <+> pname1 <+> text "are different") `andThenCheck` check (eqMaybeBy eqDM def_meth1 def_meth2) (text "The default methods associated with" <+> pname1 <+> text "are different") where name1 = idName id1 name2 = idName id2 pname1 = quotes (ppr name1) pname2 = quotes (ppr name2) (_, rho_ty1) = splitForAllTys (idType id1) op_ty1 = funResultTy rho_ty1 (_, rho_ty2) = splitForAllTys (idType id2) op_ty2 = funResultTy rho_ty2 eqAT (ATI tc1 def_ats1) (ATI tc2 def_ats2) = checkBootTyCon tc1 tc2 `andThenCheck` check (eqATDef def_ats1 def_ats2) (text "The associated type defaults differ") eqDM (_, VanillaDM) (_, VanillaDM) = True eqDM (_, GenericDM t1) (_, GenericDM t2) = eqTypeX env t1 t2 eqDM _ _ = False -- Ignore the location of the defaults eqATDef Nothing Nothing = True eqATDef (Just (ty1, _loc1)) (Just (ty2, _loc2)) = eqTypeX env ty1 ty2 eqATDef _ _ = False eqFD (as1,bs1) (as2,bs2) = eqListBy (eqTypeX env) (mkTyVarTys as1) (mkTyVarTys as2) && eqListBy (eqTypeX env) (mkTyVarTys bs1) (mkTyVarTys bs2) in check (roles1 == roles2) roles_msg `andThenCheck` -- Checks kind of class check (eqListBy eqFD clas_fds1 clas_fds2) (text "The functional dependencies do not match") `andThenCheck` checkUnless (null sc_theta1 && null op_stuff1 && null ats1) $ -- Above tests for an "abstract" class check (eqListBy (eqTypeX env) sc_theta1 sc_theta2) (text "The class constraints do not match") `andThenCheck` checkListBy eqSig op_stuff1 op_stuff2 (text "methods") `andThenCheck` checkListBy eqAT ats1 ats2 (text "associated types") | Just syn_rhs1 <- synTyConRhs_maybe tc1 , Just syn_rhs2 <- synTyConRhs_maybe tc2 , Just env <- eqVarBndrs emptyRnEnv2 (tyConTyVars tc1) (tyConTyVars tc2) = ASSERT(tc1 == tc2) check (roles1 == roles2) roles_msg `andThenCheck` check (eqTypeX env syn_rhs1 syn_rhs2) empty -- nothing interesting to say | Just fam_flav1 <- famTyConFlav_maybe tc1 , Just fam_flav2 <- famTyConFlav_maybe tc2 = ASSERT(tc1 == tc2) let eqFamFlav OpenSynFamilyTyCon OpenSynFamilyTyCon = True eqFamFlav (DataFamilyTyCon {}) (DataFamilyTyCon {}) = True eqFamFlav AbstractClosedSynFamilyTyCon (ClosedSynFamilyTyCon {}) = True eqFamFlav (ClosedSynFamilyTyCon {}) AbstractClosedSynFamilyTyCon = True eqFamFlav (ClosedSynFamilyTyCon ax1) (ClosedSynFamilyTyCon ax2) = eqClosedFamilyAx ax1 ax2 eqFamFlav (BuiltInSynFamTyCon {}) (BuiltInSynFamTyCon {}) = tc1 == tc2 eqFamFlav _ _ = False injInfo1 = familyTyConInjectivityInfo tc1 injInfo2 = familyTyConInjectivityInfo tc2 in -- check equality of roles, family flavours and injectivity annotations check (roles1 == roles2) roles_msg `andThenCheck` check (eqFamFlav fam_flav1 fam_flav2) empty `andThenCheck` check (injInfo1 == injInfo2) empty | isAlgTyCon tc1 && isAlgTyCon tc2 , Just env <- eqVarBndrs emptyRnEnv2 (tyConTyVars tc1) (tyConTyVars tc2) = ASSERT(tc1 == tc2) check (roles1 == roles2) roles_msg `andThenCheck` check (eqListBy (eqTypeX env) (tyConStupidTheta tc1) (tyConStupidTheta tc2)) (text "The datatype contexts do not match") `andThenCheck` eqAlgRhs tc1 (algTyConRhs tc1) (algTyConRhs tc2) | otherwise = Just empty -- two very different types -- should be obvious where roles1 = tyConRoles tc1 roles2 = tyConRoles tc2 roles_msg = text "The roles do not match." $$ (text "Roles on abstract types default to" <+> quotes (text "representational") <+> text "in boot files.") eqAlgRhs tc (AbstractTyCon dis1) rhs2 | dis1 = check (isGenInjAlgRhs rhs2) --Check compatibility (text "The natures of the declarations for" <+> quotes (ppr tc) <+> text "are different") | otherwise = checkSuccess eqAlgRhs _ tc1@DataTyCon{} tc2@DataTyCon{} = checkListBy eqCon (data_cons tc1) (data_cons tc2) (text "constructors") eqAlgRhs _ tc1@NewTyCon{} tc2@NewTyCon{} = eqCon (data_con tc1) (data_con tc2) eqAlgRhs _ _ _ = Just (text "Cannot match a" <+> quotes (text "data") <+> text "definition with a" <+> quotes (text "newtype") <+> text "definition") eqCon c1 c2 = check (name1 == name2) (text "The names" <+> pname1 <+> text "and" <+> pname2 <+> text "differ") `andThenCheck` check (dataConIsInfix c1 == dataConIsInfix c2) (text "The fixities of" <+> pname1 <+> text "differ") `andThenCheck` check (eqListBy eqHsBang (dataConImplBangs c1) (dataConImplBangs c2)) (text "The strictness annotations for" <+> pname1 <+> text "differ") `andThenCheck` check (map flSelector (dataConFieldLabels c1) == map flSelector (dataConFieldLabels c2)) (text "The record label lists for" <+> pname1 <+> text "differ") `andThenCheck` check (eqType (dataConUserType c1) (dataConUserType c2)) (text "The types for" <+> pname1 <+> text "differ") where name1 = dataConName c1 name2 = dataConName c2 pname1 = quotes (ppr name1) pname2 = quotes (ppr name2) eqClosedFamilyAx Nothing Nothing = True eqClosedFamilyAx Nothing (Just _) = False eqClosedFamilyAx (Just _) Nothing = False eqClosedFamilyAx (Just (CoAxiom { co_ax_branches = branches1 })) (Just (CoAxiom { co_ax_branches = branches2 })) = numBranches branches1 == numBranches branches2 && (and $ zipWith eqClosedFamilyBranch branch_list1 branch_list2) where branch_list1 = fromBranches branches1 branch_list2 = fromBranches branches2 eqClosedFamilyBranch (CoAxBranch { cab_tvs = tvs1, cab_cvs = cvs1 , cab_lhs = lhs1, cab_rhs = rhs1 }) (CoAxBranch { cab_tvs = tvs2, cab_cvs = cvs2 , cab_lhs = lhs2, cab_rhs = rhs2 }) | Just env1 <- eqVarBndrs emptyRnEnv2 tvs1 tvs2 , Just env <- eqVarBndrs env1 cvs1 cvs2 = eqListBy (eqTypeX env) lhs1 lhs2 && eqTypeX env rhs1 rhs2 | otherwise = False emptyRnEnv2 :: RnEnv2 emptyRnEnv2 = mkRnEnv2 emptyInScopeSet ---------------- missingBootThing :: Bool -> Name -> String -> SDoc missingBootThing is_boot name what = quotes (ppr name) <+> text "is exported by the" <+> (if is_boot then text "hs-boot" else text "hsig") <+> text "file, but not" <+> text what <+> text "the module" bootMisMatch :: Bool -> SDoc -> TyThing -> TyThing -> SDoc bootMisMatch is_boot extra_info real_thing boot_thing = vcat [ppr real_thing <+> text "has conflicting definitions in the module", text "and its" <+> (if is_boot then text "hs-boot file" else text "hsig file"), text "Main module:" <+> PprTyThing.pprTyThing real_thing, (if is_boot then text "Boot file: " else text "Hsig file: ") <+> PprTyThing.pprTyThing boot_thing, extra_info] instMisMatch :: Bool -> ClsInst -> SDoc instMisMatch is_boot inst = hang (ppr inst) 2 (text "is defined in the" <+> (if is_boot then text "hs-boot" else text "hsig") <+> text "file, but not in the module itself") {- ************************************************************************ * * Type-checking the top level of a module (continued) * * ************************************************************************ -} rnTopSrcDecls :: HsGroup RdrName -> TcM (TcGblEnv, HsGroup Name) -- Fails if there are any errors rnTopSrcDecls group = do { -- Rename the source decls traceRn (text "rn12") ; (tcg_env, rn_decls) <- checkNoErrs $ rnSrcDecls group ; traceRn (text "rn13") ; -- save the renamed syntax, if we want it let { tcg_env' | Just grp <- tcg_rn_decls tcg_env = tcg_env{ tcg_rn_decls = Just (appendGroups grp rn_decls) } | otherwise = tcg_env }; -- Dump trace of renaming part rnDump (ppr rn_decls) ; return (tcg_env', rn_decls) } tcTopSrcDecls :: HsGroup Name -> TcM (TcGblEnv, TcLclEnv) tcTopSrcDecls (HsGroup { hs_tyclds = tycl_decls, hs_instds = inst_decls, hs_derivds = deriv_decls, hs_fords = foreign_decls, hs_defds = default_decls, hs_annds = annotation_decls, hs_ruleds = rule_decls, hs_vects = vect_decls, hs_valds = hs_val_binds@(ValBindsOut val_binds val_sigs) }) = do { -- Type-check the type and class decls, and all imported decls -- The latter come in via tycl_decls traceTc "Tc2 (src)" empty ; -- Source-language instances, including derivings, -- and import the supporting declarations traceTc "Tc3" empty ; (tcg_env, inst_infos, ValBindsOut deriv_binds deriv_sigs) <- tcTyClsInstDecls tycl_decls inst_decls deriv_decls val_binds ; setGblEnv tcg_env $ do { -- Generate Applicative/Monad proposal (AMP) warnings traceTc "Tc3b" empty ; -- Generate Semigroup/Monoid warnings traceTc "Tc3c" empty ; tcSemigroupWarnings ; -- Foreign import declarations next. traceTc "Tc4" empty ; (fi_ids, fi_decls, fi_gres) <- tcForeignImports foreign_decls ; tcExtendGlobalValEnv fi_ids $ do { -- Default declarations traceTc "Tc4a" empty ; default_tys <- tcDefaults default_decls ; updGblEnv (\gbl -> gbl { tcg_default = default_tys }) $ do { -- Now GHC-generated derived bindings, generics, and selectors -- Do not generate warnings from compiler-generated code; -- hence the use of discardWarnings tc_envs <- discardWarnings (tcTopBinds deriv_binds deriv_sigs) ; setEnvs tc_envs $ do { -- Value declarations next traceTc "Tc5" empty ; tc_envs@(tcg_env, tcl_env) <- tcTopBinds val_binds val_sigs; setEnvs tc_envs $ do { -- Environment doesn't change now -- Second pass over class and instance declarations, -- now using the kind-checked decls traceTc "Tc6" empty ; inst_binds <- tcInstDecls2 (tyClGroupConcat tycl_decls) inst_infos ; -- Foreign exports traceTc "Tc7" empty ; (foe_binds, foe_decls, foe_gres) <- tcForeignExports foreign_decls ; -- Annotations annotations <- tcAnnotations annotation_decls ; -- Rules rules <- tcRules rule_decls ; -- Vectorisation declarations vects <- tcVectDecls vect_decls ; -- Wrap up traceTc "Tc7a" empty ; let { all_binds = inst_binds `unionBags` foe_binds ; fo_gres = fi_gres `unionBags` foe_gres ; fo_fvs = foldrBag (\gre fvs -> fvs `addOneFV` gre_name gre) emptyFVs fo_gres ; sig_names = mkNameSet (collectHsValBinders hs_val_binds) `minusNameSet` getTypeSigNames val_sigs -- Extend the GblEnv with the (as yet un-zonked) -- bindings, rules, foreign decls ; tcg_env' = tcg_env { tcg_binds = tcg_binds tcg_env `unionBags` all_binds , tcg_sigs = tcg_sigs tcg_env `unionNameSet` sig_names , tcg_rules = tcg_rules tcg_env ++ flattenRuleDecls rules , tcg_vects = tcg_vects tcg_env ++ vects , tcg_anns = tcg_anns tcg_env ++ annotations , tcg_ann_env = extendAnnEnvList (tcg_ann_env tcg_env) annotations , tcg_fords = tcg_fords tcg_env ++ foe_decls ++ fi_decls , tcg_dus = tcg_dus tcg_env `plusDU` usesOnly fo_fvs } } ; -- tcg_dus: see Note [Newtype constructor usage in foreign declarations] -- See Note [Newtype constructor usage in foreign declarations] addUsedGREs (bagToList fo_gres) ; return (tcg_env', tcl_env) }}}}}} tcTopSrcDecls _ = panic "tcTopSrcDecls: ValBindsIn" tcSemigroupWarnings :: TcM () tcSemigroupWarnings = do traceTc "tcSemigroupWarnings" empty let warnFlag = Opt_WarnSemigroup tcPreludeClashWarn warnFlag sappendName tcMissingParentClassWarn warnFlag monoidClassName semigroupClassName -- | Warn on local definitions of names that would clash with future Prelude -- elements. -- -- A name clashes if the following criteria are met: -- 1. It would is imported (unqualified) from Prelude -- 2. It is locally defined in the current module -- 3. It has the same literal name as the reference function -- 4. It is not identical to the reference function tcPreludeClashWarn :: WarningFlag -> Name -> TcM () tcPreludeClashWarn warnFlag name = do { warn <- woptM warnFlag ; when warn $ do { traceTc "tcPreludeClashWarn/wouldBeImported" empty -- Is the name imported (unqualified) from Prelude? (Point 4 above) ; rnImports <- fmap (map unLoc . tcg_rn_imports) getGblEnv -- (Note that this automatically handles -XNoImplicitPrelude, as Prelude -- will not appear in rnImports automatically if it is set.) -- Continue only the name is imported from Prelude ; when (importedViaPrelude name rnImports) $ do -- Handle 2.-4. { rdrElts <- fmap (concat . occEnvElts . tcg_rdr_env) getGblEnv ; let clashes :: GlobalRdrElt -> Bool clashes x = isLocalDef && nameClashes && isNotInProperModule where isLocalDef = gre_lcl x == True -- Names are identical ... nameClashes = nameOccName (gre_name x) == nameOccName name -- ... but not the actual definitions, because we don't want to -- warn about a bad definition of e.g. <> in Data.Semigroup, which -- is the (only) proper place where this should be defined isNotInProperModule = gre_name x /= name -- List of all offending definitions clashingElts :: [GlobalRdrElt] clashingElts = filter clashes rdrElts ; traceTc "tcPreludeClashWarn/prelude_functions" (hang (ppr name) 4 (sep [ppr clashingElts])) ; let warn_msg x = addWarnAt (Reason warnFlag) (nameSrcSpan (gre_name x)) (hsep [ text "Local definition of" , (quotes . ppr . nameOccName . gre_name) x , text "clashes with a future Prelude name." ] $$ text "This will become an error in a future release." ) ; mapM_ warn_msg clashingElts }}} where -- Is the given name imported via Prelude? -- -- Possible scenarios: -- a) Prelude is imported implicitly, issue warnings. -- b) Prelude is imported explicitly, but without mentioning the name in -- question. Issue no warnings. -- c) Prelude is imported hiding the name in question. Issue no warnings. -- d) Qualified import of Prelude, no warnings. importedViaPrelude :: Name -> [ImportDecl Name] -> Bool importedViaPrelude name = any importViaPrelude where isPrelude :: ImportDecl Name -> Bool isPrelude imp = unLoc (ideclName imp) == pRELUDE_NAME -- Implicit (Prelude) import? isImplicit :: ImportDecl Name -> Bool isImplicit = ideclImplicit -- Unqualified import? isUnqualified :: ImportDecl Name -> Bool isUnqualified = not . ideclQualified -- List of explicitly imported (or hidden) Names from a single import. -- Nothing -> No explicit imports -- Just (False, <names>) -> Explicit import list of <names> -- Just (True , <names>) -> Explicit hiding of <names> importListOf :: ImportDecl Name -> Maybe (Bool, [Name]) importListOf = fmap toImportList . ideclHiding where toImportList (h, loc) = (h, map (ieName . unLoc) (unLoc loc)) isExplicit :: ImportDecl Name -> Bool isExplicit x = case importListOf x of Nothing -> False Just (False, explicit) -> nameOccName name `elem` map nameOccName explicit Just (True, hidden) -> nameOccName name `notElem` map nameOccName hidden -- Check whether the given name would be imported (unqualified) from -- an import declaration. importViaPrelude :: ImportDecl Name -> Bool importViaPrelude x = isPrelude x && isUnqualified x && (isImplicit x || isExplicit x) -- Notation: is* is for classes the type is an instance of, should* for those -- that it should also be an instance of based on the corresponding -- is*. tcMissingParentClassWarn :: WarningFlag -> Name -- ^ Instances of this ... -> Name -- ^ should also be instances of this -> TcM () tcMissingParentClassWarn warnFlag isName shouldName = do { warn <- woptM warnFlag ; when warn $ do { traceTc "tcMissingParentClassWarn" empty ; isClass' <- tcLookupClass_maybe isName ; shouldClass' <- tcLookupClass_maybe shouldName ; case (isClass', shouldClass') of (Just isClass, Just shouldClass) -> do { localInstances <- tcGetInsts ; let isInstance m = is_cls m == isClass isInsts = filter isInstance localInstances ; traceTc "tcMissingParentClassWarn/isInsts" (ppr isInsts) ; forM_ isInsts (checkShouldInst isClass shouldClass) } (is',should') -> traceTc "tcMissingParentClassWarn/notIsShould" (hang (ppr isName <> text "/" <> ppr shouldName) 2 ( (hsep [ quotes (text "Is"), text "lookup for" , ppr isName , text "resulted in", ppr is' ]) $$ (hsep [ quotes (text "Should"), text "lookup for" , ppr shouldName , text "resulted in", ppr should' ]))) }} where -- Check whether the desired superclass exists in a given environment. checkShouldInst :: Class -- ^ Class of existing instance -> Class -- ^ Class there should be an instance of -> ClsInst -- ^ Existing instance -> TcM () checkShouldInst isClass shouldClass isInst = do { instEnv <- tcGetInstEnvs ; let (instanceMatches, shouldInsts, _) = lookupInstEnv False instEnv shouldClass (is_tys isInst) ; traceTc "tcMissingParentClassWarn/checkShouldInst" (hang (ppr isInst) 4 (sep [ppr instanceMatches, ppr shouldInsts])) -- "<location>: Warning: <type> is an instance of <is> but not -- <should>" e.g. "Foo is an instance of Monad but not Applicative" ; let instLoc = srcLocSpan . nameSrcLoc $ getName isInst warnMsg (Just name:_) = addWarnAt (Reason warnFlag) instLoc $ hsep [ (quotes . ppr . nameOccName) name , text "is an instance of" , (ppr . nameOccName . className) isClass , text "but not" , (ppr . nameOccName . className) shouldClass ] <> text "." $$ hsep [ text "This will become an error in" , text "a future release." ] warnMsg _ = pure () ; when (null shouldInsts && null instanceMatches) $ warnMsg (is_tcs isInst) } tcLookupClass_maybe :: Name -> TcM (Maybe Class) tcLookupClass_maybe name = tcLookupImported_maybe name >>= \case Succeeded (ATyCon tc) | cls@(Just _) <- tyConClass_maybe tc -> pure cls _else -> pure Nothing --------------------------- tcTyClsInstDecls :: [TyClGroup Name] -> [LInstDecl Name] -> [LDerivDecl Name] -> [(RecFlag, LHsBinds Name)] -> TcM (TcGblEnv, -- The full inst env [InstInfo Name], -- Source-code instance decls to process; -- contains all dfuns for this module HsValBinds Name) -- Supporting bindings for derived instances tcTyClsInstDecls tycl_decls inst_decls deriv_decls binds = tcAddDataFamConPlaceholders inst_decls $ tcAddPatSynPlaceholders (getPatSynBinds binds) $ do { tcg_env <- tcTyAndClassDecls tycl_decls ; ; setGblEnv tcg_env $ tcInstDecls1 tycl_decls inst_decls deriv_decls } {- ********************************************************************* * * Checking for 'main' * * ************************************************************************ -} checkMain :: Bool -- False => no 'module M(..) where' header at all -> TcM TcGblEnv -- If we are in module Main, check that 'main' is defined. checkMain explicit_mod_hdr = do { dflags <- getDynFlags ; tcg_env <- getGblEnv ; check_main dflags tcg_env explicit_mod_hdr } check_main :: DynFlags -> TcGblEnv -> Bool -> TcM TcGblEnv check_main dflags tcg_env explicit_mod_hdr | mod /= main_mod = traceTc "checkMain not" (ppr main_mod <+> ppr mod) >> return tcg_env | otherwise = do { mb_main <- lookupGlobalOccRn_maybe main_fn -- Check that 'main' is in scope -- It might be imported from another module! ; case mb_main of { Nothing -> do { traceTc "checkMain fail" (ppr main_mod <+> ppr main_fn) ; complain_no_main ; return tcg_env } ; Just main_name -> do { traceTc "checkMain found" (ppr main_mod <+> ppr main_fn) ; let loc = srcLocSpan (getSrcLoc main_name) ; ioTyCon <- tcLookupTyCon ioTyConName ; res_ty <- newFlexiTyVarTy liftedTypeKind ; main_expr <- addErrCtxt mainCtxt $ tcMonoExpr (L loc (HsVar (L loc main_name))) (mkCheckExpType $ mkTyConApp ioTyCon [res_ty]) -- See Note [Root-main Id] -- Construct the binding -- :Main.main :: IO res_ty = runMainIO res_ty main ; run_main_id <- tcLookupId runMainIOName ; let { root_main_name = mkExternalName rootMainKey rOOT_MAIN (mkVarOccFS (fsLit "main")) (getSrcSpan main_name) ; root_main_id = Id.mkExportedVanillaId root_main_name (mkTyConApp ioTyCon [res_ty]) ; co = mkWpTyApps [res_ty] ; rhs = nlHsApp (mkLHsWrap co (nlHsVar run_main_id)) main_expr ; main_bind = mkVarBind root_main_id rhs } ; return (tcg_env { tcg_main = Just main_name, tcg_binds = tcg_binds tcg_env `snocBag` main_bind, tcg_dus = tcg_dus tcg_env `plusDU` usesOnly (unitFV main_name) -- Record the use of 'main', so that we don't -- complain about it being defined but not used }) }}} where mod = tcg_mod tcg_env main_mod = mainModIs dflags main_fn = getMainFun dflags interactive = ghcLink dflags == LinkInMemory complain_no_main = checkTc (interactive && not explicit_mod_hdr) noMainMsg -- In interactive mode, without an explicit module header, don't -- worry about the absence of 'main'. -- In other modes, fail altogether, so that we don't go on -- and complain a second time when processing the export list. mainCtxt = text "When checking the type of the" <+> pp_main_fn noMainMsg = text "The" <+> pp_main_fn <+> text "is not defined in module" <+> quotes (ppr main_mod) pp_main_fn = ppMainFn main_fn -- | Get the unqualified name of the function to use as the \"main\" for the main module. -- Either returns the default name or the one configured on the command line with -main-is getMainFun :: DynFlags -> RdrName getMainFun dflags = case mainFunIs dflags of Just fn -> mkRdrUnqual (mkVarOccFS (mkFastString fn)) Nothing -> main_RDR_Unqual -- If we are in module Main, check that 'main' is exported. checkMainExported :: TcGblEnv -> TcM () checkMainExported tcg_env = case tcg_main tcg_env of Nothing -> return () -- not the main module Just main_name -> do { dflags <- getDynFlags ; let main_mod = mainModIs dflags ; checkTc (main_name `elem` concatMap availNames (tcg_exports tcg_env)) $ text "The" <+> ppMainFn (nameRdrName main_name) <+> text "is not exported by module" <+> quotes (ppr main_mod) } ppMainFn :: RdrName -> SDoc ppMainFn main_fn | rdrNameOcc main_fn == mainOcc = text "IO action" <+> quotes (ppr main_fn) | otherwise = text "main IO action" <+> quotes (ppr main_fn) mainOcc :: OccName mainOcc = mkVarOccFS (fsLit "main") {- Note [Root-main Id] ~~~~~~~~~~~~~~~~~~~ The function that the RTS invokes is always :Main.main, which we call root_main_id. (Because GHC allows the user to have a module not called Main as the main module, we can't rely on the main function being called "Main.main". That's why root_main_id has a fixed module ":Main".) This is unusual: it's a LocalId whose Name has a Module from another module. Tiresomely, we must filter it out again in MkIface, les we get two defns for 'main' in the interface file! ********************************************************* * * GHCi stuff * * ********************************************************* -} runTcInteractive :: HscEnv -> TcRn a -> IO (Messages, Maybe a) -- Initialise the tcg_inst_env with instances from all home modules. -- This mimics the more selective call to hptInstances in tcRnImports runTcInteractive hsc_env thing_inside = initTcInteractive hsc_env $ withTcPlugins hsc_env $ do { traceTc "setInteractiveContext" $ vcat [ text "ic_tythings:" <+> vcat (map ppr (ic_tythings icxt)) , text "ic_insts:" <+> vcat (map (pprBndr LetBind . instanceDFunId) ic_insts) , text "ic_rn_gbl_env (LocalDef)" <+> vcat (map ppr [ local_gres | gres <- occEnvElts (ic_rn_gbl_env icxt) , let local_gres = filter isLocalGRE gres , not (null local_gres) ]) ] ; let getOrphans m = fmap (\iface -> mi_module iface : dep_orphs (mi_deps iface)) (loadSrcInterface (text "runTcInteractive") m False Nothing) ; orphs <- fmap concat . forM (ic_imports icxt) $ \i -> case i of IIModule n -> getOrphans n IIDecl i -> getOrphans (unLoc (ideclName i)) ; let imports = emptyImportAvails { imp_orphs = orphs } ; (gbl_env, lcl_env) <- getEnvs ; let gbl_env' = gbl_env { tcg_rdr_env = ic_rn_gbl_env icxt , tcg_type_env = type_env , tcg_inst_env = extendInstEnvList (extendInstEnvList (tcg_inst_env gbl_env) ic_insts) home_insts , tcg_fam_inst_env = extendFamInstEnvList (extendFamInstEnvList (tcg_fam_inst_env gbl_env) ic_finsts) home_fam_insts , tcg_field_env = mkNameEnv con_fields -- setting tcg_field_env is necessary -- to make RecordWildCards work (test: ghci049) , tcg_fix_env = ic_fix_env icxt , tcg_default = ic_default icxt -- must calculate imp_orphs of the ImportAvails -- so that instance visibility is done correctly , tcg_imports = imports } ; lcl_env' <- tcExtendLocalTypeEnv lcl_env lcl_ids ; setEnvs (gbl_env', lcl_env') thing_inside } where (home_insts, home_fam_insts) = hptInstances hsc_env (\_ -> True) icxt = hsc_IC hsc_env (ic_insts, ic_finsts) = ic_instances icxt (lcl_ids, top_ty_things) = partitionWith is_closed (ic_tythings icxt) is_closed :: TyThing -> Either (Name, TcTyThing) TyThing -- Put Ids with free type variables (always RuntimeUnks) -- in the *local* type environment -- See Note [Initialising the type environment for GHCi] is_closed thing | AnId id <- thing , NotTopLevel <- isClosedLetBndr id = Left (idName id, ATcId { tct_id = id, tct_closed = NotTopLevel }) | otherwise = Right thing type_env1 = mkTypeEnvWithImplicits top_ty_things type_env = extendTypeEnvWithIds type_env1 (map instanceDFunId ic_insts) -- Putting the dfuns in the type_env -- is just to keep Core Lint happy con_fields = [ (dataConName c, dataConFieldLabels c) | ATyCon t <- top_ty_things , c <- tyConDataCons t ] {- Note [Initialising the type environment for GHCi] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Most of the the Ids in ic_things, defined by the user in 'let' stmts, have closed types. E.g. ghci> let foo x y = x && not y However the GHCi debugger creates top-level bindings for Ids whose types have free RuntimeUnk skolem variables, standing for unknown types. If we don't register these free TyVars as global TyVars then the typechecker will try to quantify over them and fall over in zonkQuantifiedTyVar. so we must add any free TyVars to the typechecker's global TyVar set. That is most conveniently by using tcExtendLocalTypeEnv, which automatically extends the global TyVar set. We do this by splitting out the Ids with open types, using 'is_closed' to do the partition. The top-level things go in the global TypeEnv; the open, NotTopLevel, Ids, with free RuntimeUnk tyvars, go in the local TypeEnv. Note that we don't extend the local RdrEnv (tcl_rdr); all the in-scope things are already in the interactive context's GlobalRdrEnv. Extending the local RdrEnv isn't terrible, but it means there is an entry for the same Name in both global and local RdrEnvs, and that lead to duplicate "perhaps you meant..." suggestions (e.g. T5564). We don't bother with the tcl_th_bndrs environment either. -} #ifdef GHCI -- | The returned [Id] is the list of new Ids bound by this statement. It can -- be used to extend the InteractiveContext via extendInteractiveContext. -- -- The returned TypecheckedHsExpr is of type IO [ () ], a list of the bound -- values, coerced to (). tcRnStmt :: HscEnv -> GhciLStmt RdrName -> IO (Messages, Maybe ([Id], LHsExpr Id, FixityEnv)) tcRnStmt hsc_env rdr_stmt = runTcInteractive hsc_env $ do { -- The real work is done here ((bound_ids, tc_expr), fix_env) <- tcUserStmt rdr_stmt ; zonked_expr <- zonkTopLExpr tc_expr ; zonked_ids <- zonkTopBndrs bound_ids ; -- None of the Ids should be of unboxed type, because we -- cast them all to HValues in the end! mapM_ bad_unboxed (filter (isUnliftedType . idType) zonked_ids) ; traceTc "tcs 1" empty ; this_mod <- getModule ; global_ids <- mapM (externaliseAndTidyId this_mod) zonked_ids ; -- Note [Interactively-bound Ids in GHCi] in HscTypes {- --------------------------------------------- At one stage I removed any shadowed bindings from the type_env; they are inaccessible but might, I suppose, cause a space leak if we leave them there. However, with Template Haskell they aren't necessarily inaccessible. Consider this GHCi session Prelude> let f n = n * 2 :: Int Prelude> fName <- runQ [| f |] Prelude> $(return $ AppE fName (LitE (IntegerL 7))) 14 Prelude> let f n = n * 3 :: Int Prelude> $(return $ AppE fName (LitE (IntegerL 7))) In the last line we use 'fName', which resolves to the *first* 'f' in scope. If we delete it from the type env, GHCi crashes because it doesn't expect that. Hence this code is commented out -------------------------------------------------- -} traceOptTcRn Opt_D_dump_tc (vcat [text "Bound Ids" <+> pprWithCommas ppr global_ids, text "Typechecked expr" <+> ppr zonked_expr]) ; return (global_ids, zonked_expr, fix_env) } where bad_unboxed id = addErr (sep [text "GHCi can't bind a variable of unlifted type:", nest 2 (ppr id <+> dcolon <+> ppr (idType id))]) {- -------------------------------------------------------------------------- Typechecking Stmts in GHCi Here is the grand plan, implemented in tcUserStmt What you type The IO [HValue] that hscStmt returns ------------- ------------------------------------ let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...] bindings: [x,y,...] pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...] bindings: [x,y,...] expr (of IO type) ==> expr >>= \ it -> return [coerce HVal it] [NB: result not printed] bindings: [it] expr (of non-IO type, ==> let it = expr in print it >> return [coerce HVal it] result showable) bindings: [it] expr (of non-IO type, result not showable) ==> error -} -- | A plan is an attempt to lift some code into the IO monad. type PlanResult = ([Id], LHsExpr Id) type Plan = TcM PlanResult -- | Try the plans in order. If one fails (by raising an exn), try the next. -- If one succeeds, take it. runPlans :: [Plan] -> TcM PlanResult runPlans [] = panic "runPlans" runPlans [p] = p runPlans (p:ps) = tryTcLIE_ (runPlans ps) p -- | Typecheck (and 'lift') a stmt entered by the user in GHCi into the -- GHCi 'environment'. -- -- By 'lift' and 'environment we mean that the code is changed to -- execute properly in an IO monad. See Note [Interactively-bound Ids -- in GHCi] in HscTypes for more details. We do this lifting by trying -- different ways ('plans') of lifting the code into the IO monad and -- type checking each plan until one succeeds. tcUserStmt :: GhciLStmt RdrName -> TcM (PlanResult, FixityEnv) -- An expression typed at the prompt is treated very specially tcUserStmt (L loc (BodyStmt expr _ _ _)) = do { (rn_expr, fvs) <- checkNoErrs (rnLExpr expr) -- Don't try to typecheck if the renamer fails! ; ghciStep <- getGhciStepIO ; uniq <- newUnique ; interPrintName <- getInteractivePrintName ; let fresh_it = itName uniq loc matches = [mkMatch [] rn_expr (noLoc emptyLocalBinds)] -- [it = expr] the_bind = L loc $ (mkTopFunBind FromSource (L loc fresh_it) matches) { bind_fvs = fvs } -- Care here! In GHCi the expression might have -- free variables, and they in turn may have free type variables -- (if we are at a breakpoint, say). We must put those free vars -- [let it = expr] let_stmt = L loc $ LetStmt $ noLoc $ HsValBinds $ ValBindsOut [(NonRecursive,unitBag the_bind)] [] -- [it <- e] bind_stmt = L loc $ BindStmt (L loc (VarPat (L loc fresh_it))) (nlHsApp ghciStep rn_expr) (mkRnSyntaxExpr bindIOName) noSyntaxExpr PlaceHolder -- [; print it] print_it = L loc $ BodyStmt (nlHsApp (nlHsVar interPrintName) (nlHsVar fresh_it)) (mkRnSyntaxExpr thenIOName) noSyntaxExpr placeHolderType -- The plans are: -- A. [it <- e; print it] but not if it::() -- B. [it <- e] -- C. [let it = e; print it] -- -- Ensure that type errors don't get deferred when type checking the -- naked expression. Deferring type errors here is unhelpful because the -- expression gets evaluated right away anyway. It also would potentially -- emit two redundant type-error warnings, one from each plan. ; plan <- unsetGOptM Opt_DeferTypeErrors $ unsetGOptM Opt_DeferTypedHoles $ runPlans [ -- Plan A do { stuff@([it_id], _) <- tcGhciStmts [bind_stmt, print_it] ; it_ty <- zonkTcType (idType it_id) ; when (isUnitTy $ it_ty) failM ; return stuff }, -- Plan B; a naked bind statment tcGhciStmts [bind_stmt], -- Plan C; check that the let-binding is typeable all by itself. -- If not, fail; if so, try to print it. -- The two-step process avoids getting two errors: one from -- the expression itself, and one from the 'print it' part -- This two-step story is very clunky, alas do { _ <- checkNoErrs (tcGhciStmts [let_stmt]) --- checkNoErrs defeats the error recovery of let-bindings ; tcGhciStmts [let_stmt, print_it] } ] ; fix_env <- getFixityEnv ; return (plan, fix_env) } tcUserStmt rdr_stmt@(L loc _) = do { (([rn_stmt], fix_env), fvs) <- checkNoErrs $ rnStmts GhciStmtCtxt rnLExpr [rdr_stmt] $ \_ -> do fix_env <- getFixityEnv return (fix_env, emptyFVs) -- Don't try to typecheck if the renamer fails! ; traceRn (text "tcRnStmt" <+> vcat [ppr rdr_stmt, ppr rn_stmt, ppr fvs]) ; rnDump (ppr rn_stmt) ; ; ghciStep <- getGhciStepIO ; let gi_stmt | (L loc (BindStmt pat expr op1 op2 ty)) <- rn_stmt = L loc $ BindStmt pat (nlHsApp ghciStep expr) op1 op2 ty | otherwise = rn_stmt ; opt_pr_flag <- goptM Opt_PrintBindResult ; let print_result_plan | opt_pr_flag -- The flag says "print result" , [v] <- collectLStmtBinders gi_stmt -- One binder = [mk_print_result_plan gi_stmt v] | otherwise = [] -- The plans are: -- [stmt; print v] if one binder and not v::() -- [stmt] otherwise ; plan <- runPlans (print_result_plan ++ [tcGhciStmts [gi_stmt]]) ; return (plan, fix_env) } where mk_print_result_plan stmt v = do { stuff@([v_id], _) <- tcGhciStmts [stmt, print_v] ; v_ty <- zonkTcType (idType v_id) ; when (isUnitTy v_ty || not (isTauTy v_ty)) failM ; return stuff } where print_v = L loc $ BodyStmt (nlHsApp (nlHsVar printName) (nlHsVar v)) (mkRnSyntaxExpr thenIOName) noSyntaxExpr placeHolderType -- | Typecheck the statements given and then return the results of the -- statement in the form 'IO [()]'. tcGhciStmts :: [GhciLStmt Name] -> TcM PlanResult tcGhciStmts stmts = do { ioTyCon <- tcLookupTyCon ioTyConName ; ret_id <- tcLookupId returnIOName ; -- return @ IO let { ret_ty = mkListTy unitTy ; io_ret_ty = mkTyConApp ioTyCon [ret_ty] ; tc_io_stmts = tcStmtsAndThen GhciStmtCtxt tcDoStmt stmts (mkCheckExpType io_ret_ty) ; names = collectLStmtsBinders stmts ; } ; -- OK, we're ready to typecheck the stmts traceTc "TcRnDriver.tcGhciStmts: tc stmts" empty ; ((tc_stmts, ids), lie) <- captureConstraints $ tc_io_stmts $ \ _ -> mapM tcLookupId names ; -- Look up the names right in the middle, -- where they will all be in scope -- wanted constraints from static forms stWC <- tcg_static_wc <$> getGblEnv >>= readTcRef ; -- Simplify the context traceTc "TcRnDriver.tcGhciStmts: simplify ctxt" empty ; const_binds <- checkNoErrs (simplifyInteractive (andWC stWC lie)) ; -- checkNoErrs ensures that the plan fails if context redn fails traceTc "TcRnDriver.tcGhciStmts: done" empty ; let { -- mk_return builds the expression -- returnIO @ [()] [coerce () x, .., coerce () z] -- -- Despite the inconvenience of building the type applications etc, -- this *has* to be done in type-annotated post-typecheck form -- because we are going to return a list of *polymorphic* values -- coerced to type (). If we built a *source* stmt -- return [coerce x, ..., coerce z] -- then the type checker would instantiate x..z, and we wouldn't -- get their *polymorphic* values. (And we'd get ambiguity errs -- if they were overloaded, since they aren't applied to anything.) ret_expr = nlHsApp (nlHsTyApp ret_id [ret_ty]) (noLoc $ ExplicitList unitTy Nothing (map mk_item ids)) ; mk_item id = let ty_args = [idType id, unitTy] in nlHsApp (nlHsTyApp unsafeCoerceId (map (getRuntimeRep "tcGhciStmts") ty_args ++ ty_args)) (nlHsVar id) ; stmts = tc_stmts ++ [noLoc (mkLastStmt ret_expr)] } ; return (ids, mkHsDictLet (EvBinds const_binds) $ noLoc (HsDo GhciStmtCtxt (noLoc stmts) io_ret_ty)) } -- | Generate a typed ghciStepIO expression (ghciStep :: Ty a -> IO a) getGhciStepIO :: TcM (LHsExpr Name) getGhciStepIO = do ghciTy <- getGHCiMonad fresh_a <- newUnique loc <- getSrcSpanM let a_tv = mkInternalName fresh_a (mkTyVarOccFS (fsLit "a")) loc ghciM = nlHsAppTy (nlHsTyVar ghciTy) (nlHsTyVar a_tv) ioM = nlHsAppTy (nlHsTyVar ioTyConName) (nlHsTyVar a_tv) step_ty = noLoc $ HsForAllTy { hst_bndrs = [noLoc $ UserTyVar (noLoc a_tv)] , hst_body = nlHsFunTy ghciM ioM } stepTy :: LHsSigWcType Name stepTy = mkEmptyImplicitBndrs (mkEmptyWildCardBndrs step_ty) return (noLoc $ ExprWithTySig (nlHsVar ghciStepIoMName) stepTy) isGHCiMonad :: HscEnv -> String -> IO (Messages, Maybe Name) isGHCiMonad hsc_env ty = runTcInteractive hsc_env $ do rdrEnv <- getGlobalRdrEnv let occIO = lookupOccEnv rdrEnv (mkOccName tcName ty) case occIO of Just [n] -> do let name = gre_name n ghciClass <- tcLookupClass ghciIoClassName userTyCon <- tcLookupTyCon name let userTy = mkTyConApp userTyCon [] _ <- tcLookupInstance ghciClass [userTy] return name Just _ -> failWithTc $ text "Ambiguous type!" Nothing -> failWithTc $ text ("Can't find type:" ++ ty) -- tcRnExpr just finds the type of an expression tcRnExpr :: HscEnv -> LHsExpr RdrName -> IO (Messages, Maybe Type) -- Type checks the expression and returns its most general type tcRnExpr hsc_env rdr_expr = runTcInteractive hsc_env $ do { (rn_expr, _fvs) <- rnLExpr rdr_expr ; failIfErrsM ; -- Now typecheck the expression, and generalise its type -- it might have a rank-2 type (e.g. :t runST) uniq <- newUnique ; let { fresh_it = itName uniq (getLoc rdr_expr) } ; (tclvl, lie, (_tc_expr, res_ty)) <- pushLevelAndCaptureConstraints $ tcInferSigma rn_expr ; ((qtvs, dicts, _), lie_top) <- captureConstraints $ {-# SCC "simplifyInfer" #-} simplifyInfer tclvl False {- No MR for now -} [] {- No sig vars -} [(fresh_it, res_ty)] lie ; -- Wanted constraints from static forms stWC <- tcg_static_wc <$> getGblEnv >>= readTcRef ; -- Ignore the dictionary bindings _ <- simplifyInteractive (andWC stWC lie_top) ; let { all_expr_ty = mkInvForAllTys qtvs (mkPiTypes dicts res_ty) } ; ty <- zonkTcType all_expr_ty ; -- We normalise type families, so that the type of an expression is the -- same as of a bound expression (TcBinds.mkInferredPolyId). See Trac -- #10321 for further discussion. fam_envs <- tcGetFamInstEnvs ; -- normaliseType returns a coercion which we discard, so the Role is -- irrelevant return (snd (normaliseType fam_envs Nominal ty)) } -------------------------- tcRnImportDecls :: HscEnv -> [LImportDecl RdrName] -> IO (Messages, Maybe GlobalRdrEnv) -- Find the new chunk of GlobalRdrEnv created by this list of import -- decls. In contract tcRnImports *extends* the TcGblEnv. tcRnImportDecls hsc_env import_decls = runTcInteractive hsc_env $ do { gbl_env <- updGblEnv zap_rdr_env $ tcRnImports hsc_env import_decls ; return (tcg_rdr_env gbl_env) } where zap_rdr_env gbl_env = gbl_env { tcg_rdr_env = emptyGlobalRdrEnv } -- tcRnType just finds the kind of a type tcRnType :: HscEnv -> Bool -- Normalise the returned type -> LHsType RdrName -> IO (Messages, Maybe (Type, Kind)) tcRnType hsc_env normalise rdr_type = runTcInteractive hsc_env $ setXOptM LangExt.PolyKinds $ -- See Note [Kind-generalise in tcRnType] do { (HsWC { hswc_wcs = wcs, hswc_body = rn_type }, _fvs) <- rnHsWcType GHCiCtx (mkHsWildCardBndrs rdr_type) -- The type can have wild cards, but no implicit -- generalisation; e.g. :kind (T _) ; failIfErrsM -- Now kind-check the type -- It can have any rank or kind -- First bring into scope any wildcards ; traceTc "tcRnType" (vcat [ppr wcs, ppr rn_type]) ; (ty, kind) <- solveEqualities $ tcWildCardBinders wcs $ \ _ -> tcLHsType rn_type -- Do kind generalisation; see Note [Kind-generalise in tcRnType] ; kvs <- kindGeneralize kind ; ty <- zonkTcTypeToType emptyZonkEnv ty ; ty' <- if normalise then do { fam_envs <- tcGetFamInstEnvs ; let (_, ty') = normaliseType fam_envs Nominal ty ; return ty' } else return ty ; ; return (ty', mkInvForAllTys kvs (typeKind ty')) } {- Note [Kind-generalise in tcRnType] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We switch on PolyKinds when kind-checking a user type, so that we will kind-generalise the type, even when PolyKinds is not otherwise on. This gives the right default behaviour at the GHCi prompt, where if you say ":k T", and T has a polymorphic kind, you'd like to see that polymorphism. Of course. If T isn't kind-polymorphic you won't get anything unexpected, but the apparent *loss* of polymorphism, for types that you know are polymorphic, is quite surprising. See Trac #7688 for a discussion. Note that the goal is to generalise the *kind of the type*, not the type itself! Example: ghci> data T m a = MkT (m a) -- T :: forall . (k -> *) -> k -> * ghci> :k T We instantiate T to get (T kappa). We do not want to kind-generalise that to forall k. T k! Rather we want to take its kind T kappa :: (kappa -> *) -> kappa -> * and now kind-generalise that kind, to forall k. (k->*) -> k -> * (It was Trac #10122 that made me realise how wrong the previous approach was.) -} {- ************************************************************************ * * tcRnDeclsi * * ************************************************************************ tcRnDeclsi exists to allow class, data, and other declarations in GHCi. -} tcRnDeclsi :: HscEnv -> [LHsDecl RdrName] -> IO (Messages, Maybe TcGblEnv) tcRnDeclsi hsc_env local_decls = runTcInteractive hsc_env $ tcRnSrcDecls False local_decls externaliseAndTidyId :: Module -> Id -> TcM Id externaliseAndTidyId this_mod id = do { name' <- externaliseName this_mod (idName id) ; return (globaliseAndTidyId (setIdName id name')) } #endif /* GHCi */ {- ************************************************************************ * * More GHCi stuff, to do with browsing and getting info * * ************************************************************************ -} #ifdef GHCI -- | ASSUMES that the module is either in the 'HomePackageTable' or is -- a package module with an interface on disk. If neither of these is -- true, then the result will be an error indicating the interface -- could not be found. getModuleInterface :: HscEnv -> Module -> IO (Messages, Maybe ModIface) getModuleInterface hsc_env mod = runTcInteractive hsc_env $ loadModuleInterface (text "getModuleInterface") mod tcRnLookupRdrName :: HscEnv -> Located RdrName -> IO (Messages, Maybe [Name]) -- ^ Find all the Names that this RdrName could mean, in GHCi tcRnLookupRdrName hsc_env (L loc rdr_name) = runTcInteractive hsc_env $ setSrcSpan loc $ do { -- If the identifier is a constructor (begins with an -- upper-case letter), then we need to consider both -- constructor and type class identifiers. let rdr_names = dataTcOccs rdr_name ; names_s <- mapM lookupInfoOccRn rdr_names ; let names = concat names_s ; when (null names) (addErrTc (text "Not in scope:" <+> quotes (ppr rdr_name))) ; return names } #endif tcRnLookupName :: HscEnv -> Name -> IO (Messages, Maybe TyThing) tcRnLookupName hsc_env name = runTcInteractive hsc_env $ tcRnLookupName' name -- To look up a name we have to look in the local environment (tcl_lcl) -- as well as the global environment, which is what tcLookup does. -- But we also want a TyThing, so we have to convert: tcRnLookupName' :: Name -> TcRn TyThing tcRnLookupName' name = do tcthing <- tcLookup name case tcthing of AGlobal thing -> return thing ATcId{tct_id=id} -> return (AnId id) _ -> panic "tcRnLookupName'" tcRnGetInfo :: HscEnv -> Name -> IO (Messages, Maybe (TyThing, Fixity, [ClsInst], [FamInst])) -- Used to implement :info in GHCi -- -- Look up a RdrName and return all the TyThings it might be -- A capitalised RdrName is given to us in the DataName namespace, -- but we want to treat it as *both* a data constructor -- *and* as a type or class constructor; -- hence the call to dataTcOccs, and we return up to two results tcRnGetInfo hsc_env name = runTcInteractive hsc_env $ do { loadUnqualIfaces hsc_env (hsc_IC hsc_env) -- Load the interface for all unqualified types and classes -- That way we will find all the instance declarations -- (Packages have not orphan modules, and we assume that -- in the home package all relevant modules are loaded.) ; thing <- tcRnLookupName' name ; fixity <- lookupFixityRn name ; (cls_insts, fam_insts) <- lookupInsts thing ; return (thing, fixity, cls_insts, fam_insts) } lookupInsts :: TyThing -> TcM ([ClsInst],[FamInst]) lookupInsts (ATyCon tc) = do { InstEnvs { ie_global = pkg_ie, ie_local = home_ie, ie_visible = vis_mods } <- tcGetInstEnvs ; (pkg_fie, home_fie) <- tcGetFamInstEnvs -- Load all instances for all classes that are -- in the type environment (which are all the ones -- we've seen in any interface file so far) -- Return only the instances relevant to the given thing, i.e. -- the instances whose head contains the thing's name. ; let cls_insts = [ ispec -- Search all | ispec <- instEnvElts home_ie ++ instEnvElts pkg_ie , instIsVisible vis_mods ispec , tc_name `elemNameSet` orphNamesOfClsInst ispec ] ; let fam_insts = [ fispec | fispec <- famInstEnvElts home_fie ++ famInstEnvElts pkg_fie , tc_name `elemNameSet` orphNamesOfFamInst fispec ] ; return (cls_insts, fam_insts) } where tc_name = tyConName tc lookupInsts _ = return ([],[]) loadUnqualIfaces :: HscEnv -> InteractiveContext -> TcM () -- Load the interface for everything that is in scope unqualified -- This is so that we can accurately report the instances for -- something loadUnqualIfaces hsc_env ictxt = initIfaceTcRn $ do mapM_ (loadSysInterface doc) (moduleSetElts (mkModuleSet unqual_mods)) where this_pkg = thisPackage (hsc_dflags hsc_env) unqual_mods = [ nameModule name | gre <- globalRdrEnvElts (ic_rn_gbl_env ictxt) , let name = gre_name gre , nameIsFromExternalPackage this_pkg name , isTcOcc (nameOccName name) -- Types and classes only , unQualOK gre ] -- In scope unqualified doc = text "Need interface for module whose export(s) are in scope unqualified" {- ****************************************************************************** ** Typechecking module exports The renamer makes sure that only the correct pieces of a type or class can be bundled with the type or class in the export list. When it comes to pattern synonyms, in the renamer we have no way to check that whether a pattern synonym should be allowed to be bundled or not so we allow them to be bundled with any type or class. Here we then check that 1) Pattern synonyms are only bundled with types which are able to have data constructors. Datatypes, newtypes and data families. 2) Are the correct type, for example if P is a synonym then if we export Foo(P) then P should be an instance of Foo. ****************************************************************************** -} tcExports :: Maybe [LIE Name] -> TcM () tcExports Nothing = return () tcExports (Just ies) = checkNoErrs $ mapM_ tc_export ies tc_export :: LIE Name -> TcM () tc_export ie@(L _ (IEThingWith name _ names sels)) = addExportErrCtxt ie $ tc_export_with (unLoc name) (map unLoc names ++ map (flSelector . unLoc) sels) tc_export _ = return () addExportErrCtxt :: LIE Name -> TcM a -> TcM a addExportErrCtxt (L l ie) = setSrcSpan l . addErrCtxt exportCtxt where exportCtxt = text "In the export:" <+> ppr ie -- Note: [Types of TyCon] -- -- This check appears to be overlly complicated, Richard asked why it -- is not simply just `isAlgTyCon`. The answer for this is that -- a classTyCon is also an `AlgTyCon` which we explicitly want to disallow. -- (It is either a newtype or data depending on the number of methods) -- -- -- Note: [Typing Pattern Synonym Exports] -- It proved quite a challenge to precisely specify which pattern synonyms -- should be allowed to be bundled with which type constructors. -- In the end it was decided to be quite liberal in what we allow. Below is -- how Simon described the implementation. -- -- "Personally I think we should Keep It Simple. All this talk of -- satisfiability makes me shiver. I suggest this: allow T( P ) in all -- situations except where `P`'s type is ''visibly incompatible'' with -- `T`. -- -- What does "visibly incompatible" mean? `P` is visibly incompatible -- with -- `T` if -- * `P`'s type is of form `... -> S t1 t2` -- * `S` is a data/newtype constructor distinct from `T` -- -- Nothing harmful happens if we allow `P` to be exported with -- a type it can't possibly be useful for, but specifying a tighter -- relationship is very awkward as you have discovered." -- -- Note that this allows *any* pattern synonym to be bundled with any -- datatype type constructor. For example, the following pattern `P` can be -- bundled with any type. -- -- ``` -- pattern P :: (A ~ f) => f -- ``` -- -- So we provide basic type checking in order to help the user out, most -- pattern synonyms are defined with definite type constructors, but don't -- actually prevent a library author completely confusing their users if -- they want to. exportErrCtxt :: Outputable o => String -> o -> SDoc exportErrCtxt herald exp = text "In the" <+> text (herald ++ ":") <+> ppr exp tc_export_with :: Name -- ^ Type constructor -> [Name] -- ^ A mixture of data constructors, pattern syonyms -- , class methods and record selectors. -> TcM () tc_export_with n ns = do ty_con <- tcLookupTyCon n things <- mapM tcLookupGlobal ns let psErr = exportErrCtxt "pattern synonym" selErr = exportErrCtxt "pattern synonym record selector" ps = [(psErr p,p) | AConLike (PatSynCon p) <- things] sels = [(selErr i,p) | AnId i <- things , isId i , RecSelId {sel_tycon = RecSelPatSyn p} <- [idDetails i]] pat_syns = ps ++ sels -- See note [Types of TyCon] checkTc ( null pat_syns || isTyConWithSrcDataCons ty_con) assocClassErr let actual_res_ty = mkTyConApp ty_con (mkTyVarTys (tyConTyVars ty_con)) mapM_ (tc_one_export_with actual_res_ty ty_con ) pat_syns where assocClassErr :: SDoc assocClassErr = text "Pattern synonyms can be bundled only with datatypes." tc_one_export_with :: TcTauType -- ^ TyCon type -> TyCon -- ^ Parent TyCon -> (SDoc, PatSyn) -- ^ Corresponding bundled PatSyn -- and pretty printed origin -> TcM () tc_one_export_with actual_res_ty ty_con (errCtxt, pat_syn) = addErrCtxt errCtxt $ let (_, _, _, _, _, res_ty) = patSynSig pat_syn mtycon = tcSplitTyConApp_maybe res_ty typeMismatchError :: SDoc typeMismatchError = text "Pattern synonyms can only be bundled with matching type constructors" $$ text "Couldn't match expected type of" <+> quotes (ppr actual_res_ty) <+> text "with actual type of" <+> quotes (ppr res_ty) in case mtycon of Nothing -> return () Just (p_ty_con, _) -> -- See note [Typing Pattern Synonym Exports] unless (p_ty_con == ty_con) (addErrTc typeMismatchError) {- ************************************************************************ * * Degugging output * * ************************************************************************ -} rnDump :: SDoc -> TcRn () -- Dump, with a banner, if -ddump-rn rnDump doc = do { traceOptTcRn Opt_D_dump_rn (mkDumpDoc "Renamer" doc) } tcDump :: TcGblEnv -> TcRn () tcDump env = do { dflags <- getDynFlags ; -- Dump short output if -ddump-types or -ddump-tc when (dopt Opt_D_dump_types dflags || dopt Opt_D_dump_tc dflags) (printForUserTcRn short_dump) ; -- Dump bindings if -ddump-tc traceOptTcRn Opt_D_dump_tc (mkDumpDoc "Typechecker" full_dump) } where short_dump = pprTcGblEnv env full_dump = pprLHsBinds (tcg_binds env) -- NB: foreign x-d's have undefined's in their types; -- hence can't show the tc_fords -- It's unpleasant having both pprModGuts and pprModDetails here pprTcGblEnv :: TcGblEnv -> SDoc pprTcGblEnv (TcGblEnv { tcg_type_env = type_env, tcg_insts = insts, tcg_fam_insts = fam_insts, tcg_rules = rules, tcg_vects = vects, tcg_imports = imports }) = vcat [ ppr_types type_env , ppr_tycons fam_insts type_env , ppr_insts insts , ppr_fam_insts fam_insts , vcat (map ppr rules) , vcat (map ppr vects) , text "Dependent modules:" <+> ppr (sortBy cmp_mp $ eltsUFM (imp_dep_mods imports)) , text "Dependent packages:" <+> ppr (sortBy stableUnitIdCmp $ imp_dep_pkgs imports)] where -- The two uses of sortBy are just to reduce unnecessary -- wobbling in testsuite output cmp_mp (mod_name1, is_boot1) (mod_name2, is_boot2) = (mod_name1 `stableModuleNameCmp` mod_name2) `thenCmp` (is_boot1 `compare` is_boot2) ppr_types :: TypeEnv -> SDoc ppr_types type_env = text "TYPE SIGNATURES" $$ nest 2 (ppr_sigs ids) where ids = [id | id <- typeEnvIds type_env, want_sig id] want_sig id | opt_PprStyle_Debug = True | otherwise = isExternalName (idName id) && (not (isDerivedOccName (getOccName id))) -- Top-level user-defined things have External names. -- Suppress internally-generated things unless -dppr-debug ppr_tycons :: [FamInst] -> TypeEnv -> SDoc ppr_tycons fam_insts type_env = vcat [ text "TYPE CONSTRUCTORS" , nest 2 (ppr_tydecls tycons) , text "COERCION AXIOMS" , nest 2 (vcat (map pprCoAxiom (typeEnvCoAxioms type_env))) ] where fi_tycons = famInstsRepTyCons fam_insts tycons = [tycon | tycon <- typeEnvTyCons type_env, want_tycon tycon] want_tycon tycon | opt_PprStyle_Debug = True | otherwise = not (isImplicitTyCon tycon) && isExternalName (tyConName tycon) && not (tycon `elem` fi_tycons) ppr_insts :: [ClsInst] -> SDoc ppr_insts [] = empty ppr_insts ispecs = text "INSTANCES" $$ nest 2 (pprInstances ispecs) ppr_fam_insts :: [FamInst] -> SDoc ppr_fam_insts [] = empty ppr_fam_insts fam_insts = text "FAMILY INSTANCES" $$ nest 2 (pprFamInsts fam_insts) ppr_sigs :: [Var] -> SDoc ppr_sigs ids -- Print type signatures; sort by OccName = vcat (map ppr_sig (sortBy (comparing getOccName) ids)) where ppr_sig id = hang (ppr id <+> dcolon) 2 (ppr (tidyTopType (idType id))) ppr_tydecls :: [TyCon] -> SDoc ppr_tydecls tycons -- Print type constructor info; sort by OccName = vcat (map ppr_tycon (sortBy (comparing getOccName) tycons)) where ppr_tycon tycon = vcat [ ppr (tyThingToIfaceDecl (ATyCon tycon)) ] {- ******************************************************************************** Type Checker Plugins ******************************************************************************** -} withTcPlugins :: HscEnv -> TcM a -> TcM a withTcPlugins hsc_env m = do plugins <- liftIO (loadTcPlugins hsc_env) case plugins of [] -> m -- Common fast case _ -> do (solvers,stops) <- unzip `fmap` mapM startPlugin plugins -- This ensures that tcPluginStop is called even if a type -- error occurs during compilation (Fix of #10078) eitherRes <- tryM $ do updGblEnv (\e -> e { tcg_tc_plugins = solvers }) m mapM_ (flip runTcPluginM Nothing) stops case eitherRes of Left _ -> failM Right res -> return res where startPlugin (TcPlugin start solve stop) = do s <- runTcPluginM start Nothing return (solve s, stop s) loadTcPlugins :: HscEnv -> IO [TcPlugin] #ifndef GHCI loadTcPlugins _ = return [] #else loadTcPlugins hsc_env = do named_plugins <- loadPlugins hsc_env return $ catMaybes $ map load_plugin named_plugins where load_plugin (_, plug, opts) = tcPlugin plug opts #endif
mcschroeder/ghc
compiler/typecheck/TcRnDriver.hs
bsd-3-clause
105,639
21
29
35,459
18,253
9,513
8,740
-1
-1
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- -- (c) The University of Glasgow 2006 -- -- The purpose of this module is to transform an HsExpr into a CoreExpr which -- when evaluated, returns a (Meta.Q Meta.Exp) computation analogous to the -- input HsExpr. We do this in the DsM monad, which supplies access to -- CoreExpr's of the "smart constructors" of the Meta.Exp datatype. -- -- It also defines a bunch of knownKeyNames, in the same way as is done -- in prelude/PrelNames. It's much more convenient to do it here, because -- otherwise we have to recompile PrelNames whenever we add a Name, which is -- a Royal Pain (triggers other recompilation). ----------------------------------------------------------------------------- module DsMeta( dsBracket, templateHaskellNames, qTyConName, nameTyConName, liftName, liftStringName, expQTyConName, patQTyConName, decQTyConName, decsQTyConName, typeQTyConName, decTyConName, typeTyConName, mkNameG_dName, mkNameG_vName, mkNameG_tcName, quoteExpName, quotePatName, quoteDecName, quoteTypeName, tExpTyConName, tExpDataConName, unTypeName, unTypeQName, unsafeTExpCoerceName ) where #include "HsVersions.h" import {-# SOURCE #-} DsExpr ( dsExpr ) import MatchLit import DsMonad import qualified Language.Haskell.TH as TH import HsSyn import Class import PrelNames -- To avoid clashes with DsMeta.varName we must make a local alias for -- OccName.varName we do this by removing varName from the import of -- OccName above, making a qualified instance of OccName and using -- OccNameAlias.varName where varName ws previously used in this file. import qualified OccName( isDataOcc, isVarOcc, isTcOcc, varName, tcName, dataName ) import Module import Id import Name hiding( isVarOcc, isTcOcc, varName, tcName ) import NameEnv import TcType import TyCon import TysWiredIn import TysPrim ( liftedTypeKindTyConName, constraintKindTyConName ) import CoreSyn import MkCore import CoreUtils import SrcLoc import Unique import BasicTypes import Outputable import Bag import DynFlags import FastString import ForeignCall import Util import MonadUtils import Data.Maybe import Control.Monad import Data.List ----------------------------------------------------------------------------- dsBracket :: HsBracket Name -> [PendingTcSplice] -> DsM CoreExpr -- Returns a CoreExpr of type TH.ExpQ -- The quoted thing is parameterised over Name, even though it has -- been type checked. We don't want all those type decorations! dsBracket brack splices = dsExtendMetaEnv new_bit (do_brack brack) where new_bit = mkNameEnv [(n, DsSplice (unLoc e)) | PendingTcSplice n e <- splices] do_brack (VarBr _ n) = do { MkC e1 <- lookupOcc n ; return e1 } do_brack (ExpBr e) = do { MkC e1 <- repLE e ; return e1 } do_brack (PatBr p) = do { MkC p1 <- repTopP p ; return p1 } do_brack (TypBr t) = do { MkC t1 <- repLTy t ; return t1 } do_brack (DecBrG gp) = do { MkC ds1 <- repTopDs gp ; return ds1 } do_brack (DecBrL _) = panic "dsBracket: unexpected DecBrL" do_brack (TExpBr e) = do { MkC e1 <- repLE e ; return e1 } {- -------------- Examples -------------------- [| \x -> x |] ====> gensym (unpackString "x"#) `bindQ` \ x1::String -> lam (pvar x1) (var x1) [| \x -> $(f [| x |]) |] ====> gensym (unpackString "x"#) `bindQ` \ x1::String -> lam (pvar x1) (f (var x1)) -} ------------------------------------------------------- -- Declarations ------------------------------------------------------- repTopP :: LPat Name -> DsM (Core TH.PatQ) repTopP pat = do { ss <- mkGenSyms (collectPatBinders pat) ; pat' <- addBinds ss (repLP pat) ; wrapGenSyms ss pat' } repTopDs :: HsGroup Name -> DsM (Core (TH.Q [TH.Dec])) repTopDs group@(HsGroup { hs_valds = valds , hs_splcds = splcds , hs_tyclds = tyclds , hs_instds = instds , hs_derivds = derivds , hs_fixds = fixds , hs_defds = defds , hs_fords = fords , hs_warnds = warnds , hs_annds = annds , hs_ruleds = ruleds , hs_vects = vects , hs_docs = docs }) = do { let { tv_bndrs = hsSigTvBinders valds ; bndrs = tv_bndrs ++ hsGroupBinders group } ; ss <- mkGenSyms bndrs ; -- Bind all the names mainly to avoid repeated use of explicit strings. -- Thus we get -- do { t :: String <- genSym "T" ; -- return (Data t [] ...more t's... } -- The other important reason is that the output must mention -- only "T", not "Foo:T" where Foo is the current module decls <- addBinds ss ( do { val_ds <- rep_val_binds valds ; _ <- mapM no_splice splcds ; tycl_ds <- mapM repTyClD (tyClGroupConcat tyclds) ; role_ds <- mapM repRoleD (concatMap group_roles tyclds) ; inst_ds <- mapM repInstD instds ; deriv_ds <- mapM repStandaloneDerivD derivds ; fix_ds <- mapM repFixD fixds ; _ <- mapM no_default_decl defds ; for_ds <- mapM repForD fords ; _ <- mapM no_warn (concatMap (wd_warnings . unLoc) warnds) ; ann_ds <- mapM repAnnD annds ; rule_ds <- mapM repRuleD (concatMap (rds_rules . unLoc) ruleds) ; _ <- mapM no_vect vects ; _ <- mapM no_doc docs -- more needed ; return (de_loc $ sort_by_loc $ val_ds ++ catMaybes tycl_ds ++ role_ds ++ (concat fix_ds) ++ inst_ds ++ rule_ds ++ for_ds ++ ann_ds ++ deriv_ds) }) ; decl_ty <- lookupType decQTyConName ; let { core_list = coreList' decl_ty decls } ; dec_ty <- lookupType decTyConName ; q_decs <- repSequenceQ dec_ty core_list ; wrapGenSyms ss q_decs } where no_splice (L loc _) = notHandledL loc "Splices within declaration brackets" empty no_default_decl (L loc decl) = notHandledL loc "Default declarations" (ppr decl) no_warn (L loc (Warning thing _)) = notHandledL loc "WARNING and DEPRECATION pragmas" $ text "Pragma for declaration of" <+> ppr thing no_vect (L loc decl) = notHandledL loc "Vectorisation pragmas" (ppr decl) no_doc (L loc _) = notHandledL loc "Haddock documentation" empty hsSigTvBinders :: HsValBinds Name -> [Name] -- See Note [Scoped type variables in bindings] hsSigTvBinders binds = [hsLTyVarName tv | L _ (TypeSig _ (L _ (HsForAllTy Explicit _ qtvs _ _)) _) <- sigs , tv <- hsQTvBndrs qtvs] where sigs = case binds of ValBindsIn _ sigs -> sigs ValBindsOut _ sigs -> sigs {- Notes Note [Scoped type variables in bindings] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider f :: forall a. a -> a f x = x::a Here the 'forall a' brings 'a' into scope over the binding group. To achieve this we a) Gensym a binding for 'a' at the same time as we do one for 'f' collecting the relevant binders with hsSigTvBinders b) When processing the 'forall', don't gensym The relevant places are signposted with references to this Note Note [Binders and occurrences] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When we desugar [d| data T = MkT |] we want to get Data "T" [] [Con "MkT" []] [] and *not* Data "Foo:T" [] [Con "Foo:MkT" []] [] That is, the new data decl should fit into whatever new module it is asked to fit in. We do *not* clone, though; no need for this: Data "T79" .... But if we see this: data T = MkT foo = reifyDecl T then we must desugar to foo = Data "Foo:T" [] [Con "Foo:MkT" []] [] So in repTopDs we bring the binders into scope with mkGenSyms and addBinds. And we use lookupOcc, rather than lookupBinder in repTyClD and repC. -} -- represent associated family instances -- repTyClD :: LTyClDecl Name -> DsM (Maybe (SrcSpan, Core TH.DecQ)) repTyClD (L loc (FamDecl { tcdFam = fam })) = liftM Just $ repFamilyDecl (L loc fam) repTyClD (L loc (SynDecl { tcdLName = tc, tcdTyVars = tvs, tcdRhs = rhs })) = do { tc1 <- lookupLOcc tc -- See note [Binders and occurrences] ; dec <- addTyClTyVarBinds tvs $ \bndrs -> repSynDecl tc1 bndrs rhs ; return (Just (loc, dec)) } repTyClD (L loc (DataDecl { tcdLName = tc, tcdTyVars = tvs, tcdDataDefn = defn })) = do { tc1 <- lookupLOcc tc -- See note [Binders and occurrences] ; tc_tvs <- mk_extra_tvs tc tvs defn ; dec <- addTyClTyVarBinds tc_tvs $ \bndrs -> repDataDefn tc1 bndrs Nothing (hsLTyVarNames tc_tvs) defn ; return (Just (loc, dec)) } repTyClD (L loc (ClassDecl { tcdCtxt = cxt, tcdLName = cls, tcdTyVars = tvs, tcdFDs = fds, tcdSigs = sigs, tcdMeths = meth_binds, tcdATs = ats, tcdATDefs = [] })) = do { cls1 <- lookupLOcc cls -- See note [Binders and occurrences] ; dec <- addTyVarBinds tvs $ \bndrs -> do { cxt1 <- repLContext cxt ; sigs1 <- rep_sigs sigs ; binds1 <- rep_binds meth_binds ; fds1 <- repLFunDeps fds ; ats1 <- repFamilyDecls ats ; decls1 <- coreList decQTyConName (ats1 ++ sigs1 ++ binds1) ; repClass cxt1 cls1 bndrs fds1 decls1 } ; return $ Just (loc, dec) } -- Un-handled cases repTyClD (L loc d) = putSrcSpanDs loc $ do { warnDs (hang ds_msg 4 (ppr d)) ; return Nothing } ------------------------- repRoleD :: LRoleAnnotDecl Name -> DsM (SrcSpan, Core TH.DecQ) repRoleD (L loc (RoleAnnotDecl tycon roles)) = do { tycon1 <- lookupLOcc tycon ; roles1 <- mapM repRole roles ; roles2 <- coreList roleTyConName roles1 ; dec <- repRoleAnnotD tycon1 roles2 ; return (loc, dec) } ------------------------- repDataDefn :: Core TH.Name -> Core [TH.TyVarBndr] -> Maybe (Core [TH.TypeQ]) -> [Name] -> HsDataDefn Name -> DsM (Core TH.DecQ) repDataDefn tc bndrs opt_tys tv_names (HsDataDefn { dd_ND = new_or_data, dd_ctxt = cxt , dd_cons = cons, dd_derivs = mb_derivs }) = do { cxt1 <- repLContext cxt ; derivs1 <- repDerivs mb_derivs ; case new_or_data of NewType -> do { con1 <- repC tv_names (head cons) ; case con1 of [c] -> repNewtype cxt1 tc bndrs opt_tys c derivs1 _cs -> failWithDs (ptext (sLit "Multiple constructors for newtype:") <+> pprQuotedList (con_names $ unLoc $ head cons)) } DataType -> do { consL <- concatMapM (repC tv_names) cons ; cons1 <- coreList conQTyConName consL ; repData cxt1 tc bndrs opt_tys cons1 derivs1 } } repSynDecl :: Core TH.Name -> Core [TH.TyVarBndr] -> LHsType Name -> DsM (Core TH.DecQ) repSynDecl tc bndrs ty = do { ty1 <- repLTy ty ; repTySyn tc bndrs ty1 } repFamilyDecl :: LFamilyDecl Name -> DsM (SrcSpan, Core TH.DecQ) repFamilyDecl (L loc (FamilyDecl { fdInfo = info, fdLName = tc, fdTyVars = tvs, fdKindSig = opt_kind })) = do { tc1 <- lookupLOcc tc -- See note [Binders and occurrences] ; dec <- addTyClTyVarBinds tvs $ \bndrs -> case (opt_kind, info) of (Nothing, ClosedTypeFamily eqns) -> do { eqns1 <- mapM repTyFamEqn eqns ; eqns2 <- coreList tySynEqnQTyConName eqns1 ; repClosedFamilyNoKind tc1 bndrs eqns2 } (Just ki, ClosedTypeFamily eqns) -> do { eqns1 <- mapM repTyFamEqn eqns ; eqns2 <- coreList tySynEqnQTyConName eqns1 ; ki1 <- repLKind ki ; repClosedFamilyKind tc1 bndrs ki1 eqns2 } (Nothing, _) -> do { info' <- repFamilyInfo info ; repFamilyNoKind info' tc1 bndrs } (Just ki, _) -> do { info' <- repFamilyInfo info ; ki1 <- repLKind ki ; repFamilyKind info' tc1 bndrs ki1 } ; return (loc, dec) } repFamilyDecls :: [LFamilyDecl Name] -> DsM [Core TH.DecQ] repFamilyDecls fds = liftM de_loc (mapM repFamilyDecl fds) ------------------------- mk_extra_tvs :: Located Name -> LHsTyVarBndrs Name -> HsDataDefn Name -> DsM (LHsTyVarBndrs Name) -- If there is a kind signature it must be of form -- k1 -> .. -> kn -> * -- Return type variables [tv1:k1, tv2:k2, .., tvn:kn] mk_extra_tvs tc tvs defn | HsDataDefn { dd_kindSig = Just hs_kind } <- defn = do { extra_tvs <- go hs_kind ; return (tvs { hsq_tvs = hsq_tvs tvs ++ extra_tvs }) } | otherwise = return tvs where go :: LHsKind Name -> DsM [LHsTyVarBndr Name] go (L loc (HsFunTy kind rest)) = do { uniq <- newUnique ; let { occ = mkTyVarOccFS (fsLit "t") ; nm = mkInternalName uniq occ loc ; hs_tv = L loc (KindedTyVar (noLoc nm) kind) } ; hs_tvs <- go rest ; return (hs_tv : hs_tvs) } go (L _ (HsTyVar n)) | n == liftedTypeKindTyConName = return [] go _ = failWithDs (ptext (sLit "Malformed kind signature for") <+> ppr tc) ------------------------- -- represent fundeps -- repLFunDeps :: [Located (FunDep (Located Name))] -> DsM (Core [TH.FunDep]) repLFunDeps fds = repList funDepTyConName repLFunDep fds repLFunDep :: Located (FunDep (Located Name)) -> DsM (Core TH.FunDep) repLFunDep (L _ (xs, ys)) = do xs' <- repList nameTyConName (lookupBinder . unLoc) xs ys' <- repList nameTyConName (lookupBinder . unLoc) ys repFunDep xs' ys' -- represent family declaration flavours -- repFamilyInfo :: FamilyInfo Name -> DsM (Core TH.FamFlavour) repFamilyInfo OpenTypeFamily = rep2 typeFamName [] repFamilyInfo DataFamily = rep2 dataFamName [] repFamilyInfo ClosedTypeFamily {} = panic "repFamilyInfo" -- Represent instance declarations -- repInstD :: LInstDecl Name -> DsM (SrcSpan, Core TH.DecQ) repInstD (L loc (TyFamInstD { tfid_inst = fi_decl })) = do { dec <- repTyFamInstD fi_decl ; return (loc, dec) } repInstD (L loc (DataFamInstD { dfid_inst = fi_decl })) = do { dec <- repDataFamInstD fi_decl ; return (loc, dec) } repInstD (L loc (ClsInstD { cid_inst = cls_decl })) = do { dec <- repClsInstD cls_decl ; return (loc, dec) } repClsInstD :: ClsInstDecl Name -> DsM (Core TH.DecQ) repClsInstD (ClsInstDecl { cid_poly_ty = ty, cid_binds = binds , cid_sigs = prags, cid_tyfam_insts = ats , cid_datafam_insts = adts }) = addTyVarBinds tvs $ \_ -> -- We must bring the type variables into scope, so their -- occurrences don't fail, even though the binders don't -- appear in the resulting data structure -- -- But we do NOT bring the binders of 'binds' into scope -- because they are properly regarded as occurrences -- For example, the method names should be bound to -- the selector Ids, not to fresh names (Trac #5410) -- do { cxt1 <- repContext cxt ; cls_tcon <- repTy (HsTyVar (unLoc cls)) ; cls_tys <- repLTys tys ; inst_ty1 <- repTapps cls_tcon cls_tys ; binds1 <- rep_binds binds ; prags1 <- rep_sigs prags ; ats1 <- mapM (repTyFamInstD . unLoc) ats ; adts1 <- mapM (repDataFamInstD . unLoc) adts ; decls <- coreList decQTyConName (ats1 ++ adts1 ++ binds1 ++ prags1) ; repInst cxt1 inst_ty1 decls } where Just (tvs, cxt, cls, tys) = splitLHsInstDeclTy_maybe ty repStandaloneDerivD :: LDerivDecl Name -> DsM (SrcSpan, Core TH.DecQ) repStandaloneDerivD (L loc (DerivDecl { deriv_type = ty })) = do { dec <- addTyVarBinds tvs $ \_ -> do { cxt' <- repContext cxt ; cls_tcon <- repTy (HsTyVar (unLoc cls)) ; cls_tys <- repLTys tys ; inst_ty <- repTapps cls_tcon cls_tys ; repDeriv cxt' inst_ty } ; return (loc, dec) } where Just (tvs, cxt, cls, tys) = splitLHsInstDeclTy_maybe ty repTyFamInstD :: TyFamInstDecl Name -> DsM (Core TH.DecQ) repTyFamInstD decl@(TyFamInstDecl { tfid_eqn = eqn }) = do { let tc_name = tyFamInstDeclLName decl ; tc <- lookupLOcc tc_name -- See note [Binders and occurrences] ; eqn1 <- repTyFamEqn eqn ; repTySynInst tc eqn1 } repTyFamEqn :: LTyFamInstEqn Name -> DsM (Core TH.TySynEqnQ) repTyFamEqn (L loc (TyFamEqn { tfe_pats = HsWB { hswb_cts = tys , hswb_kvs = kv_names , hswb_tvs = tv_names } , tfe_rhs = rhs })) = do { let hs_tvs = HsQTvs { hsq_kvs = kv_names , hsq_tvs = userHsTyVarBndrs loc tv_names } -- Yuk ; addTyClTyVarBinds hs_tvs $ \ _ -> do { tys1 <- repLTys tys ; tys2 <- coreList typeQTyConName tys1 ; rhs1 <- repLTy rhs ; repTySynEqn tys2 rhs1 } } repDataFamInstD :: DataFamInstDecl Name -> DsM (Core TH.DecQ) repDataFamInstD (DataFamInstDecl { dfid_tycon = tc_name , dfid_pats = HsWB { hswb_cts = tys, hswb_kvs = kv_names, hswb_tvs = tv_names } , dfid_defn = defn }) = do { tc <- lookupLOcc tc_name -- See note [Binders and occurrences] ; let loc = getLoc tc_name hs_tvs = HsQTvs { hsq_kvs = kv_names, hsq_tvs = userHsTyVarBndrs loc tv_names } -- Yuk ; addTyClTyVarBinds hs_tvs $ \ bndrs -> do { tys1 <- repList typeQTyConName repLTy tys ; repDataDefn tc bndrs (Just tys1) tv_names defn } } repForD :: Located (ForeignDecl Name) -> DsM (SrcSpan, Core TH.DecQ) repForD (L loc (ForeignImport name typ _ (CImport (L _ cc) (L _ s) mch cis _))) = do MkC name' <- lookupLOcc name MkC typ' <- repLTy typ MkC cc' <- repCCallConv cc MkC s' <- repSafety s cis' <- conv_cimportspec cis MkC str <- coreStringLit (static ++ chStr ++ cis') dec <- rep2 forImpDName [cc', s', str, name', typ'] return (loc, dec) where conv_cimportspec (CLabel cls) = notHandled "Foreign label" (doubleQuotes (ppr cls)) conv_cimportspec (CFunction DynamicTarget) = return "dynamic" conv_cimportspec (CFunction (StaticTarget fs _ True)) = return (unpackFS fs) conv_cimportspec (CFunction (StaticTarget _ _ False)) = panic "conv_cimportspec: values not supported yet" conv_cimportspec CWrapper = return "wrapper" static = case cis of CFunction (StaticTarget _ _ _) -> "static " _ -> "" chStr = case mch of Nothing -> "" Just (Header h) -> unpackFS h ++ " " repForD decl = notHandled "Foreign declaration" (ppr decl) repCCallConv :: CCallConv -> DsM (Core TH.Callconv) repCCallConv CCallConv = rep2 cCallName [] repCCallConv StdCallConv = rep2 stdCallName [] repCCallConv CApiConv = rep2 cApiCallName [] repCCallConv PrimCallConv = rep2 primCallName [] repCCallConv JavaScriptCallConv = rep2 javaScriptCallName [] repSafety :: Safety -> DsM (Core TH.Safety) repSafety PlayRisky = rep2 unsafeName [] repSafety PlayInterruptible = rep2 interruptibleName [] repSafety PlaySafe = rep2 safeName [] repFixD :: LFixitySig Name -> DsM [(SrcSpan, Core TH.DecQ)] repFixD (L loc (FixitySig names (Fixity prec dir))) = do { MkC prec' <- coreIntLit prec ; let rep_fn = case dir of InfixL -> infixLDName InfixR -> infixRDName InfixN -> infixNDName ; let do_one name = do { MkC name' <- lookupLOcc name ; dec <- rep2 rep_fn [prec', name'] ; return (loc,dec) } ; mapM do_one names } repRuleD :: LRuleDecl Name -> DsM (SrcSpan, Core TH.DecQ) repRuleD (L loc (HsRule n act bndrs lhs _ rhs _)) = do { let bndr_names = concatMap ruleBndrNames bndrs ; ss <- mkGenSyms bndr_names ; rule1 <- addBinds ss $ do { bndrs' <- repList ruleBndrQTyConName repRuleBndr bndrs ; n' <- coreStringLit $ unpackFS $ unLoc n ; act' <- repPhases act ; lhs' <- repLE lhs ; rhs' <- repLE rhs ; repPragRule n' bndrs' lhs' rhs' act' } ; rule2 <- wrapGenSyms ss rule1 ; return (loc, rule2) } ruleBndrNames :: LRuleBndr Name -> [Name] ruleBndrNames (L _ (RuleBndr n)) = [unLoc n] ruleBndrNames (L _ (RuleBndrSig n (HsWB { hswb_kvs = kvs, hswb_tvs = tvs }))) = unLoc n : kvs ++ tvs repRuleBndr :: LRuleBndr Name -> DsM (Core TH.RuleBndrQ) repRuleBndr (L _ (RuleBndr n)) = do { MkC n' <- lookupLBinder n ; rep2 ruleVarName [n'] } repRuleBndr (L _ (RuleBndrSig n (HsWB { hswb_cts = ty }))) = do { MkC n' <- lookupLBinder n ; MkC ty' <- repLTy ty ; rep2 typedRuleVarName [n', ty'] } repAnnD :: LAnnDecl Name -> DsM (SrcSpan, Core TH.DecQ) repAnnD (L loc (HsAnnotation _ ann_prov (L _ exp))) = do { target <- repAnnProv ann_prov ; exp' <- repE exp ; dec <- repPragAnn target exp' ; return (loc, dec) } repAnnProv :: AnnProvenance Name -> DsM (Core TH.AnnTarget) repAnnProv (ValueAnnProvenance (L _ n)) = do { MkC n' <- globalVar n -- ANNs are allowed only at top-level ; rep2 valueAnnotationName [ n' ] } repAnnProv (TypeAnnProvenance (L _ n)) = do { MkC n' <- globalVar n ; rep2 typeAnnotationName [ n' ] } repAnnProv ModuleAnnProvenance = rep2 moduleAnnotationName [] ds_msg :: SDoc ds_msg = ptext (sLit "Cannot desugar this Template Haskell declaration:") ------------------------------------------------------- -- Constructors ------------------------------------------------------- repC :: [Name] -> LConDecl Name -> DsM [Core TH.ConQ] repC _ (L _ (ConDecl { con_names = con, con_qvars = con_tvs, con_cxt = L _ [] , con_details = details, con_res = ResTyH98 })) | null (hsQTvBndrs con_tvs) = do { con1 <- mapM lookupLOcc con -- See Note [Binders and occurrences] ; mapM (\c -> repConstr c details) con1 } repC tvs (L _ (ConDecl { con_names = cons , con_qvars = con_tvs, con_cxt = L _ ctxt , con_details = details , con_res = res_ty })) = do { (eq_ctxt, con_tv_subst) <- mkGadtCtxt tvs res_ty ; let ex_tvs = HsQTvs { hsq_kvs = filterOut (in_subst con_tv_subst) (hsq_kvs con_tvs) , hsq_tvs = filterOut (in_subst con_tv_subst . hsLTyVarName) (hsq_tvs con_tvs) } ; binds <- mapM dupBinder con_tv_subst ; b <- dsExtendMetaEnv (mkNameEnv binds) $ -- Binds some of the con_tvs addTyVarBinds ex_tvs $ \ ex_bndrs -> -- Binds the remaining con_tvs do { cons1 <- mapM lookupLOcc cons -- See Note [Binders and occurrences] ; c' <- mapM (\c -> repConstr c details) cons1 ; ctxt' <- repContext (eq_ctxt ++ ctxt) ; rep2 forallCName ([unC ex_bndrs, unC ctxt'] ++ (map unC c')) } ; return [b] } in_subst :: [(Name,Name)] -> Name -> Bool in_subst [] _ = False in_subst ((n',_):ns) n = n==n' || in_subst ns n mkGadtCtxt :: [Name] -- Tyvars of the data type -> ResType (LHsType Name) -> DsM (HsContext Name, [(Name,Name)]) -- Given a data type in GADT syntax, figure out the equality -- context, so that we can represent it with an explicit -- equality context, because that is the only way to express -- the GADT in TH syntax -- -- Example: -- data T a b c where { MkT :: forall d e. d -> e -> T d [e] e -- mkGadtCtxt [a,b,c] [d,e] (T d [e] e) -- returns -- (b~[e], c~e), [d->a] -- -- This function is fiddly, but not really hard mkGadtCtxt _ ResTyH98 = return ([], []) mkGadtCtxt data_tvs (ResTyGADT _ res_ty) | Just (_, tys) <- hsTyGetAppHead_maybe res_ty , data_tvs `equalLength` tys = return (go [] [] (data_tvs `zip` tys)) | otherwise = failWithDs (ptext (sLit "Malformed constructor result type:") <+> ppr res_ty) where go cxt subst [] = (cxt, subst) go cxt subst ((data_tv, ty) : rest) | Just con_tv <- is_hs_tyvar ty , isTyVarName con_tv , not (in_subst subst con_tv) = go cxt ((con_tv, data_tv) : subst) rest | otherwise = go (eq_pred : cxt) subst rest where loc = getLoc ty eq_pred = L loc (HsEqTy (L loc (HsTyVar data_tv)) ty) is_hs_tyvar (L _ (HsTyVar n)) = Just n -- Type variables *and* tycons is_hs_tyvar (L _ (HsParTy ty)) = is_hs_tyvar ty is_hs_tyvar _ = Nothing repBangTy :: LBangType Name -> DsM (Core (TH.StrictTypeQ)) repBangTy ty= do MkC s <- rep2 str [] MkC t <- repLTy ty' rep2 strictTypeName [s, t] where (str, ty') = case ty of L _ (HsBangTy (HsSrcBang _ (Just True) True) ty) -> (unpackedName, ty) L _ (HsBangTy (HsSrcBang _ _ True) ty) -> (isStrictName, ty) _ -> (notStrictName, ty) ------------------------------------------------------- -- Deriving clause ------------------------------------------------------- repDerivs :: Maybe (Located [LHsType Name]) -> DsM (Core [TH.Name]) repDerivs Nothing = coreList nameTyConName [] repDerivs (Just (L _ ctxt)) = repList nameTyConName rep_deriv ctxt where rep_deriv :: LHsType Name -> DsM (Core TH.Name) -- Deriving clauses must have the simple H98 form rep_deriv ty | Just (cls, []) <- splitHsClassTy_maybe (unLoc ty) = lookupOcc cls | otherwise = notHandled "Non-H98 deriving clause" (ppr ty) ------------------------------------------------------- -- Signatures in a class decl, or a group of bindings ------------------------------------------------------- rep_sigs :: [LSig Name] -> DsM [Core TH.DecQ] rep_sigs sigs = do locs_cores <- rep_sigs' sigs return $ de_loc $ sort_by_loc locs_cores rep_sigs' :: [LSig Name] -> DsM [(SrcSpan, Core TH.DecQ)] -- We silently ignore ones we don't recognise rep_sigs' sigs = do { sigs1 <- mapM rep_sig sigs ; return (concat sigs1) } rep_sig :: LSig Name -> DsM [(SrcSpan, Core TH.DecQ)] rep_sig (L loc (TypeSig nms ty _)) = mapM (rep_ty_sig sigDName loc ty) nms rep_sig (L _ (PatSynSig {})) = notHandled "Pattern type signatures" empty rep_sig (L loc (GenericSig nms ty)) = mapM (rep_ty_sig defaultSigDName loc ty) nms rep_sig d@(L _ (IdSig {})) = pprPanic "rep_sig IdSig" (ppr d) rep_sig (L _ (FixSig {})) = return [] -- fixity sigs at top level rep_sig (L loc (InlineSig nm ispec)) = rep_inline nm ispec loc rep_sig (L loc (SpecSig nm tys ispec)) = concatMapM (\t -> rep_specialise nm t ispec loc) tys rep_sig (L loc (SpecInstSig _ ty)) = rep_specialiseInst ty loc rep_sig (L _ (MinimalSig {})) = notHandled "MINIMAL pragmas" empty rep_ty_sig :: Name -> SrcSpan -> LHsType Name -> Located Name -> DsM (SrcSpan, Core TH.DecQ) rep_ty_sig mk_sig loc (L _ ty) nm = do { nm1 <- lookupLOcc nm ; ty1 <- rep_ty ty ; sig <- repProto mk_sig nm1 ty1 ; return (loc, sig) } where -- We must special-case the top-level explicit for-all of a TypeSig -- See Note [Scoped type variables in bindings] rep_ty (HsForAllTy Explicit _ tvs ctxt ty) = do { let rep_in_scope_tv tv = do { name <- lookupBinder (hsLTyVarName tv) ; repTyVarBndrWithKind tv name } ; bndrs1 <- repList tyVarBndrTyConName rep_in_scope_tv (hsQTvBndrs tvs) ; ctxt1 <- repLContext ctxt ; ty1 <- repLTy ty ; repTForall bndrs1 ctxt1 ty1 } rep_ty ty = repTy ty rep_inline :: Located Name -> InlinePragma -- Never defaultInlinePragma -> SrcSpan -> DsM [(SrcSpan, Core TH.DecQ)] rep_inline nm ispec loc = do { nm1 <- lookupLOcc nm ; inline <- repInline $ inl_inline ispec ; rm <- repRuleMatch $ inl_rule ispec ; phases <- repPhases $ inl_act ispec ; pragma <- repPragInl nm1 inline rm phases ; return [(loc, pragma)] } rep_specialise :: Located Name -> LHsType Name -> InlinePragma -> SrcSpan -> DsM [(SrcSpan, Core TH.DecQ)] rep_specialise nm ty ispec loc = do { nm1 <- lookupLOcc nm ; ty1 <- repLTy ty ; phases <- repPhases $ inl_act ispec ; let inline = inl_inline ispec ; pragma <- if isEmptyInlineSpec inline then -- SPECIALISE repPragSpec nm1 ty1 phases else -- SPECIALISE INLINE do { inline1 <- repInline inline ; repPragSpecInl nm1 ty1 inline1 phases } ; return [(loc, pragma)] } rep_specialiseInst :: LHsType Name -> SrcSpan -> DsM [(SrcSpan, Core TH.DecQ)] rep_specialiseInst ty loc = do { ty1 <- repLTy ty ; pragma <- repPragSpecInst ty1 ; return [(loc, pragma)] } repInline :: InlineSpec -> DsM (Core TH.Inline) repInline NoInline = dataCon noInlineDataConName repInline Inline = dataCon inlineDataConName repInline Inlinable = dataCon inlinableDataConName repInline spec = notHandled "repInline" (ppr spec) repRuleMatch :: RuleMatchInfo -> DsM (Core TH.RuleMatch) repRuleMatch ConLike = dataCon conLikeDataConName repRuleMatch FunLike = dataCon funLikeDataConName repPhases :: Activation -> DsM (Core TH.Phases) repPhases (ActiveBefore i) = do { MkC arg <- coreIntLit i ; dataCon' beforePhaseDataConName [arg] } repPhases (ActiveAfter i) = do { MkC arg <- coreIntLit i ; dataCon' fromPhaseDataConName [arg] } repPhases _ = dataCon allPhasesDataConName ------------------------------------------------------- -- Types ------------------------------------------------------- addTyVarBinds :: LHsTyVarBndrs Name -- the binders to be added -> (Core [TH.TyVarBndr] -> DsM (Core (TH.Q a))) -- action in the ext env -> DsM (Core (TH.Q a)) -- gensym a list of type variables and enter them into the meta environment; -- the computations passed as the second argument is executed in that extended -- meta environment and gets the *new* names on Core-level as an argument addTyVarBinds (HsQTvs { hsq_kvs = kvs, hsq_tvs = tvs }) m = do { fresh_kv_names <- mkGenSyms kvs ; fresh_tv_names <- mkGenSyms (map hsLTyVarName tvs) ; let fresh_names = fresh_kv_names ++ fresh_tv_names ; term <- addBinds fresh_names $ do { kbs <- repList tyVarBndrTyConName mk_tv_bndr (tvs `zip` fresh_tv_names) ; m kbs } ; wrapGenSyms fresh_names term } where mk_tv_bndr (tv, (_,v)) = repTyVarBndrWithKind tv (coreVar v) addTyClTyVarBinds :: LHsTyVarBndrs Name -> (Core [TH.TyVarBndr] -> DsM (Core (TH.Q a))) -> DsM (Core (TH.Q a)) -- Used for data/newtype declarations, and family instances, -- so that the nested type variables work right -- instance C (T a) where -- type W (T a) = blah -- The 'a' in the type instance is the one bound by the instance decl addTyClTyVarBinds tvs m = do { let tv_names = hsLKiTyVarNames tvs ; env <- dsGetMetaEnv ; freshNames <- mkGenSyms (filterOut (`elemNameEnv` env) tv_names) -- Make fresh names for the ones that are not already in scope -- This makes things work for family declarations ; term <- addBinds freshNames $ do { kbs <- repList tyVarBndrTyConName mk_tv_bndr (hsQTvBndrs tvs) ; m kbs } ; wrapGenSyms freshNames term } where mk_tv_bndr tv = do { v <- lookupBinder (hsLTyVarName tv) ; repTyVarBndrWithKind tv v } -- Produce kinded binder constructors from the Haskell tyvar binders -- repTyVarBndrWithKind :: LHsTyVarBndr Name -> Core TH.Name -> DsM (Core TH.TyVarBndr) repTyVarBndrWithKind (L _ (UserTyVar _)) nm = repPlainTV nm repTyVarBndrWithKind (L _ (KindedTyVar _ ki)) nm = repLKind ki >>= repKindedTV nm -- represent a type context -- repLContext :: LHsContext Name -> DsM (Core TH.CxtQ) repLContext (L _ ctxt) = repContext ctxt repContext :: HsContext Name -> DsM (Core TH.CxtQ) repContext ctxt = do preds <- repList typeQTyConName repLTy ctxt repCtxt preds -- yield the representation of a list of types -- repLTys :: [LHsType Name] -> DsM [Core TH.TypeQ] repLTys tys = mapM repLTy tys -- represent a type -- repLTy :: LHsType Name -> DsM (Core TH.TypeQ) repLTy (L _ ty) = repTy ty repTy :: HsType Name -> DsM (Core TH.TypeQ) repTy (HsForAllTy _ _ tvs ctxt ty) = addTyVarBinds tvs $ \bndrs -> do ctxt1 <- repLContext ctxt ty1 <- repLTy ty repTForall bndrs ctxt1 ty1 repTy (HsTyVar n) | isTvOcc occ = do tv1 <- lookupOcc n repTvar tv1 | isDataOcc occ = do tc1 <- lookupOcc n repPromotedTyCon tc1 | otherwise = do tc1 <- lookupOcc n repNamedTyCon tc1 where occ = nameOccName n repTy (HsAppTy f a) = do f1 <- repLTy f a1 <- repLTy a repTapp f1 a1 repTy (HsFunTy f a) = do f1 <- repLTy f a1 <- repLTy a tcon <- repArrowTyCon repTapps tcon [f1, a1] repTy (HsListTy t) = do t1 <- repLTy t tcon <- repListTyCon repTapp tcon t1 repTy (HsPArrTy t) = do t1 <- repLTy t tcon <- repTy (HsTyVar (tyConName parrTyCon)) repTapp tcon t1 repTy (HsTupleTy HsUnboxedTuple tys) = do tys1 <- repLTys tys tcon <- repUnboxedTupleTyCon (length tys) repTapps tcon tys1 repTy (HsTupleTy _ tys) = do tys1 <- repLTys tys tcon <- repTupleTyCon (length tys) repTapps tcon tys1 repTy (HsOpTy ty1 (_, n) ty2) = repLTy ((nlHsTyVar (unLoc n) `nlHsAppTy` ty1) `nlHsAppTy` ty2) repTy (HsParTy t) = repLTy t repTy (HsEqTy t1 t2) = do t1' <- repLTy t1 t2' <- repLTy t2 eq <- repTequality repTapps eq [t1', t2'] repTy (HsKindSig t k) = do t1 <- repLTy t k1 <- repLKind k repTSig t1 k1 repTy (HsSpliceTy splice _) = repSplice splice repTy (HsExplicitListTy _ tys) = do tys1 <- repLTys tys repTPromotedList tys1 repTy (HsExplicitTupleTy _ tys) = do tys1 <- repLTys tys tcon <- repPromotedTupleTyCon (length tys) repTapps tcon tys1 repTy (HsTyLit lit) = do lit' <- repTyLit lit repTLit lit' repTy ty = notHandled "Exotic form of type" (ppr ty) repTyLit :: HsTyLit -> DsM (Core TH.TyLitQ) repTyLit (HsNumTy _ i) = do iExpr <- mkIntegerExpr i rep2 numTyLitName [iExpr] repTyLit (HsStrTy _ s) = do { s' <- mkStringExprFS s ; rep2 strTyLitName [s'] } -- represent a kind -- repLKind :: LHsKind Name -> DsM (Core TH.Kind) repLKind ki = do { let (kis, ki') = splitHsFunType ki ; kis_rep <- mapM repLKind kis ; ki'_rep <- repNonArrowLKind ki' ; kcon <- repKArrow ; let f k1 k2 = repKApp kcon k1 >>= flip repKApp k2 ; foldrM f ki'_rep kis_rep } repNonArrowLKind :: LHsKind Name -> DsM (Core TH.Kind) repNonArrowLKind (L _ ki) = repNonArrowKind ki repNonArrowKind :: HsKind Name -> DsM (Core TH.Kind) repNonArrowKind (HsTyVar name) | name == liftedTypeKindTyConName = repKStar | name == constraintKindTyConName = repKConstraint | isTvOcc (nameOccName name) = lookupOcc name >>= repKVar | otherwise = lookupOcc name >>= repKCon repNonArrowKind (HsAppTy f a) = do { f' <- repLKind f ; a' <- repLKind a ; repKApp f' a' } repNonArrowKind (HsListTy k) = do { k' <- repLKind k ; kcon <- repKList ; repKApp kcon k' } repNonArrowKind (HsTupleTy _ ks) = do { ks' <- mapM repLKind ks ; kcon <- repKTuple (length ks) ; repKApps kcon ks' } repNonArrowKind k = notHandled "Exotic form of kind" (ppr k) repRole :: Located (Maybe Role) -> DsM (Core TH.Role) repRole (L _ (Just Nominal)) = rep2 nominalRName [] repRole (L _ (Just Representational)) = rep2 representationalRName [] repRole (L _ (Just Phantom)) = rep2 phantomRName [] repRole (L _ Nothing) = rep2 inferRName [] ----------------------------------------------------------------------------- -- Splices ----------------------------------------------------------------------------- repSplice :: HsSplice Name -> DsM (Core a) -- See Note [How brackets and nested splices are handled] in TcSplice -- We return a CoreExpr of any old type; the context should know repSplice (HsTypedSplice n _) = rep_splice n repSplice (HsUntypedSplice n _) = rep_splice n repSplice (HsQuasiQuote n _ _ _) = rep_splice n rep_splice :: Name -> DsM (Core a) rep_splice splice_name = do { mb_val <- dsLookupMetaEnv splice_name ; case mb_val of Just (DsSplice e) -> do { e' <- dsExpr e ; return (MkC e') } _ -> pprPanic "HsSplice" (ppr splice_name) } -- Should not happen; statically checked ----------------------------------------------------------------------------- -- Expressions ----------------------------------------------------------------------------- repLEs :: [LHsExpr Name] -> DsM (Core [TH.ExpQ]) repLEs es = repList expQTyConName repLE es -- FIXME: some of these panics should be converted into proper error messages -- unless we can make sure that constructs, which are plainly not -- supported in TH already lead to error messages at an earlier stage repLE :: LHsExpr Name -> DsM (Core TH.ExpQ) repLE (L loc e) = putSrcSpanDs loc (repE e) repE :: HsExpr Name -> DsM (Core TH.ExpQ) repE (HsVar x) = do { mb_val <- dsLookupMetaEnv x ; case mb_val of Nothing -> do { str <- globalVar x ; repVarOrCon x str } Just (DsBound y) -> repVarOrCon x (coreVar y) Just (DsSplice e) -> do { e' <- dsExpr e ; return (MkC e') } } repE e@(HsIPVar _) = notHandled "Implicit parameters" (ppr e) -- Remember, we're desugaring renamer output here, so -- HsOverlit can definitely occur repE (HsOverLit l) = do { a <- repOverloadedLiteral l; repLit a } repE (HsLit l) = do { a <- repLiteral l; repLit a } repE (HsLam (MG { mg_alts = [m] })) = repLambda m repE (HsLamCase _ (MG { mg_alts = ms })) = do { ms' <- mapM repMatchTup ms ; core_ms <- coreList matchQTyConName ms' ; repLamCase core_ms } repE (HsApp x y) = do {a <- repLE x; b <- repLE y; repApp a b} repE (OpApp e1 op _ e2) = do { arg1 <- repLE e1; arg2 <- repLE e2; the_op <- repLE op ; repInfixApp arg1 the_op arg2 } repE (NegApp x _) = do a <- repLE x negateVar <- lookupOcc negateName >>= repVar negateVar `repApp` a repE (HsPar x) = repLE x repE (SectionL x y) = do { a <- repLE x; b <- repLE y; repSectionL a b } repE (SectionR x y) = do { a <- repLE x; b <- repLE y; repSectionR a b } repE (HsCase e (MG { mg_alts = ms })) = do { arg <- repLE e ; ms2 <- mapM repMatchTup ms ; core_ms2 <- coreList matchQTyConName ms2 ; repCaseE arg core_ms2 } repE (HsIf _ x y z) = do a <- repLE x b <- repLE y c <- repLE z repCond a b c repE (HsMultiIf _ alts) = do { (binds, alts') <- liftM unzip $ mapM repLGRHS alts ; expr' <- repMultiIf (nonEmptyCoreList alts') ; wrapGenSyms (concat binds) expr' } repE (HsLet bs e) = do { (ss,ds) <- repBinds bs ; e2 <- addBinds ss (repLE e) ; z <- repLetE ds e2 ; wrapGenSyms ss z } -- FIXME: I haven't got the types here right yet repE e@(HsDo ctxt sts _) | case ctxt of { DoExpr -> True; GhciStmtCtxt -> True; _ -> False } = do { (ss,zs) <- repLSts sts; e' <- repDoE (nonEmptyCoreList zs); wrapGenSyms ss e' } | ListComp <- ctxt = do { (ss,zs) <- repLSts sts; e' <- repComp (nonEmptyCoreList zs); wrapGenSyms ss e' } | otherwise = notHandled "mdo, monad comprehension and [: :]" (ppr e) repE (ExplicitList _ _ es) = do { xs <- repLEs es; repListExp xs } repE e@(ExplicitPArr _ _) = notHandled "Parallel arrays" (ppr e) repE e@(ExplicitTuple es boxed) | not (all tupArgPresent es) = notHandled "Tuple sections" (ppr e) | isBoxed boxed = do { xs <- repLEs [e | L _ (Present e) <- es]; repTup xs } | otherwise = do { xs <- repLEs [e | L _ (Present e) <- es] ; repUnboxedTup xs } repE (RecordCon c _ flds) = do { x <- lookupLOcc c; fs <- repFields flds; repRecCon x fs } repE (RecordUpd e flds _ _ _) = do { x <- repLE e; fs <- repFields flds; repRecUpd x fs } repE (ExprWithTySig e ty _) = do { e1 <- repLE e; t1 <- repLTy ty; repSigExp e1 t1 } repE (ArithSeq _ _ aseq) = case aseq of From e -> do { ds1 <- repLE e; repFrom ds1 } FromThen e1 e2 -> do ds1 <- repLE e1 ds2 <- repLE e2 repFromThen ds1 ds2 FromTo e1 e2 -> do ds1 <- repLE e1 ds2 <- repLE e2 repFromTo ds1 ds2 FromThenTo e1 e2 e3 -> do ds1 <- repLE e1 ds2 <- repLE e2 ds3 <- repLE e3 repFromThenTo ds1 ds2 ds3 repE (HsSpliceE splice) = repSplice splice repE (HsStatic e) = repLE e >>= rep2 staticEName . (:[]) . unC repE e@(PArrSeq {}) = notHandled "Parallel arrays" (ppr e) repE e@(HsCoreAnn {}) = notHandled "Core annotations" (ppr e) repE e@(HsSCC {}) = notHandled "Cost centres" (ppr e) repE e@(HsTickPragma {}) = notHandled "Tick Pragma" (ppr e) repE e@(HsTcBracketOut {}) = notHandled "TH brackets" (ppr e) repE e = notHandled "Expression form" (ppr e) ----------------------------------------------------------------------------- -- Building representations of auxillary structures like Match, Clause, Stmt, repMatchTup :: LMatch Name (LHsExpr Name) -> DsM (Core TH.MatchQ) repMatchTup (L _ (Match _ [p] _ (GRHSs guards wheres))) = do { ss1 <- mkGenSyms (collectPatBinders p) ; addBinds ss1 $ do { ; p1 <- repLP p ; (ss2,ds) <- repBinds wheres ; addBinds ss2 $ do { ; gs <- repGuards guards ; match <- repMatch p1 gs ds ; wrapGenSyms (ss1++ss2) match }}} repMatchTup _ = panic "repMatchTup: case alt with more than one arg" repClauseTup :: LMatch Name (LHsExpr Name) -> DsM (Core TH.ClauseQ) repClauseTup (L _ (Match _ ps _ (GRHSs guards wheres))) = do { ss1 <- mkGenSyms (collectPatsBinders ps) ; addBinds ss1 $ do { ps1 <- repLPs ps ; (ss2,ds) <- repBinds wheres ; addBinds ss2 $ do { gs <- repGuards guards ; clause <- repClause ps1 gs ds ; wrapGenSyms (ss1++ss2) clause }}} repGuards :: [LGRHS Name (LHsExpr Name)] -> DsM (Core TH.BodyQ) repGuards [L _ (GRHS [] e)] = do {a <- repLE e; repNormal a } repGuards other = do { zs <- mapM repLGRHS other ; let (xs, ys) = unzip zs ; gd <- repGuarded (nonEmptyCoreList ys) ; wrapGenSyms (concat xs) gd } repLGRHS :: LGRHS Name (LHsExpr Name) -> DsM ([GenSymBind], (Core (TH.Q (TH.Guard, TH.Exp)))) repLGRHS (L _ (GRHS [L _ (BodyStmt e1 _ _ _)] e2)) = do { guarded <- repLNormalGE e1 e2 ; return ([], guarded) } repLGRHS (L _ (GRHS ss rhs)) = do { (gs, ss') <- repLSts ss ; rhs' <- addBinds gs $ repLE rhs ; guarded <- repPatGE (nonEmptyCoreList ss') rhs' ; return (gs, guarded) } repFields :: HsRecordBinds Name -> DsM (Core [TH.Q TH.FieldExp]) repFields (HsRecFields { rec_flds = flds }) = repList fieldExpQTyConName rep_fld flds where rep_fld (L _ fld) = do { fn <- lookupLOcc (hsRecFieldId fld) ; e <- repLE (hsRecFieldArg fld) ; repFieldExp fn e } ----------------------------------------------------------------------------- -- Representing Stmt's is tricky, especially if bound variables -- shadow each other. Consider: [| do { x <- f 1; x <- f x; g x } |] -- First gensym new names for every variable in any of the patterns. -- both static (x'1 and x'2), and dynamic ((gensym "x") and (gensym "y")) -- if variables didn't shaddow, the static gensym wouldn't be necessary -- and we could reuse the original names (x and x). -- -- do { x'1 <- gensym "x" -- ; x'2 <- gensym "x" -- ; doE [ BindSt (pvar x'1) [| f 1 |] -- , BindSt (pvar x'2) [| f x |] -- , NoBindSt [| g x |] -- ] -- } -- The strategy is to translate a whole list of do-bindings by building a -- bigger environment, and a bigger set of meta bindings -- (like: x'1 <- gensym "x" ) and then combining these with the translations -- of the expressions within the Do ----------------------------------------------------------------------------- -- The helper function repSts computes the translation of each sub expression -- and a bunch of prefix bindings denoting the dynamic renaming. repLSts :: [LStmt Name (LHsExpr Name)] -> DsM ([GenSymBind], [Core TH.StmtQ]) repLSts stmts = repSts (map unLoc stmts) repSts :: [Stmt Name (LHsExpr Name)] -> DsM ([GenSymBind], [Core TH.StmtQ]) repSts (BindStmt p e _ _ : ss) = do { e2 <- repLE e ; ss1 <- mkGenSyms (collectPatBinders p) ; addBinds ss1 $ do { ; p1 <- repLP p; ; (ss2,zs) <- repSts ss ; z <- repBindSt p1 e2 ; return (ss1++ss2, z : zs) }} repSts (LetStmt bs : ss) = do { (ss1,ds) <- repBinds bs ; z <- repLetSt ds ; (ss2,zs) <- addBinds ss1 (repSts ss) ; return (ss1++ss2, z : zs) } repSts (BodyStmt e _ _ _ : ss) = do { e2 <- repLE e ; z <- repNoBindSt e2 ; (ss2,zs) <- repSts ss ; return (ss2, z : zs) } repSts (ParStmt stmt_blocks _ _ : ss) = do { (ss_s, stmt_blocks1) <- mapAndUnzipM rep_stmt_block stmt_blocks ; let stmt_blocks2 = nonEmptyCoreList stmt_blocks1 ss1 = concat ss_s ; z <- repParSt stmt_blocks2 ; (ss2, zs) <- addBinds ss1 (repSts ss) ; return (ss1++ss2, z : zs) } where rep_stmt_block :: ParStmtBlock Name Name -> DsM ([GenSymBind], Core [TH.StmtQ]) rep_stmt_block (ParStmtBlock stmts _ _) = do { (ss1, zs) <- repSts (map unLoc stmts) ; zs1 <- coreList stmtQTyConName zs ; return (ss1, zs1) } repSts [LastStmt e _] = do { e2 <- repLE e ; z <- repNoBindSt e2 ; return ([], [z]) } repSts [] = return ([],[]) repSts other = notHandled "Exotic statement" (ppr other) ----------------------------------------------------------- -- Bindings ----------------------------------------------------------- repBinds :: HsLocalBinds Name -> DsM ([GenSymBind], Core [TH.DecQ]) repBinds EmptyLocalBinds = do { core_list <- coreList decQTyConName [] ; return ([], core_list) } repBinds b@(HsIPBinds _) = notHandled "Implicit parameters" (ppr b) repBinds (HsValBinds decs) = do { let { bndrs = hsSigTvBinders decs ++ collectHsValBinders decs } -- No need to worrry about detailed scopes within -- the binding group, because we are talking Names -- here, so we can safely treat it as a mutually -- recursive group -- For hsSigTvBinders see Note [Scoped type variables in bindings] ; ss <- mkGenSyms bndrs ; prs <- addBinds ss (rep_val_binds decs) ; core_list <- coreList decQTyConName (de_loc (sort_by_loc prs)) ; return (ss, core_list) } rep_val_binds :: HsValBinds Name -> DsM [(SrcSpan, Core TH.DecQ)] -- Assumes: all the binders of the binding are alrady in the meta-env rep_val_binds (ValBindsOut binds sigs) = do { core1 <- rep_binds' (unionManyBags (map snd binds)) ; core2 <- rep_sigs' sigs ; return (core1 ++ core2) } rep_val_binds (ValBindsIn _ _) = panic "rep_val_binds: ValBindsIn" rep_binds :: LHsBinds Name -> DsM [Core TH.DecQ] rep_binds binds = do { binds_w_locs <- rep_binds' binds ; return (de_loc (sort_by_loc binds_w_locs)) } rep_binds' :: LHsBinds Name -> DsM [(SrcSpan, Core TH.DecQ)] rep_binds' = mapM rep_bind . bagToList rep_bind :: LHsBind Name -> DsM (SrcSpan, Core TH.DecQ) -- Assumes: all the binders of the binding are alrady in the meta-env -- Note GHC treats declarations of a variable (not a pattern) -- e.g. x = g 5 as a Fun MonoBinds. This is indicated by a single match -- with an empty list of patterns rep_bind (L loc (FunBind { fun_id = fn, fun_matches = MG { mg_alts = [L _ (Match _ [] _ (GRHSs guards wheres))] } })) = do { (ss,wherecore) <- repBinds wheres ; guardcore <- addBinds ss (repGuards guards) ; fn' <- lookupLBinder fn ; p <- repPvar fn' ; ans <- repVal p guardcore wherecore ; ans' <- wrapGenSyms ss ans ; return (loc, ans') } rep_bind (L loc (FunBind { fun_id = fn, fun_matches = MG { mg_alts = ms } })) = do { ms1 <- mapM repClauseTup ms ; fn' <- lookupLBinder fn ; ans <- repFun fn' (nonEmptyCoreList ms1) ; return (loc, ans) } rep_bind (L loc (PatBind { pat_lhs = pat, pat_rhs = GRHSs guards wheres })) = do { patcore <- repLP pat ; (ss,wherecore) <- repBinds wheres ; guardcore <- addBinds ss (repGuards guards) ; ans <- repVal patcore guardcore wherecore ; ans' <- wrapGenSyms ss ans ; return (loc, ans') } rep_bind (L _ (VarBind { var_id = v, var_rhs = e})) = do { v' <- lookupBinder v ; e2 <- repLE e ; x <- repNormal e2 ; patcore <- repPvar v' ; empty_decls <- coreList decQTyConName [] ; ans <- repVal patcore x empty_decls ; return (srcLocSpan (getSrcLoc v), ans) } rep_bind (L _ (AbsBinds {})) = panic "rep_bind: AbsBinds" rep_bind (L _ dec@(PatSynBind {})) = notHandled "pattern synonyms" (ppr dec) ----------------------------------------------------------------------------- -- Since everything in a Bind is mutually recursive we need rename all -- all the variables simultaneously. For example: -- [| AndMonoBinds (f x = x + g 2) (g x = f 1 + 2) |] would translate to -- do { f'1 <- gensym "f" -- ; g'2 <- gensym "g" -- ; [ do { x'3 <- gensym "x"; fun f'1 [pvar x'3] [| x + g2 |]}, -- do { x'4 <- gensym "x"; fun g'2 [pvar x'4] [| f 1 + 2 |]} -- ]} -- This requires collecting the bindings (f'1 <- gensym "f"), and the -- environment ( f |-> f'1 ) from each binding, and then unioning them -- together. As we do this we collect GenSymBinds's which represent the renamed -- variables bound by the Bindings. In order not to lose track of these -- representations we build a shadow datatype MB with the same structure as -- MonoBinds, but which has slots for the representations ----------------------------------------------------------------------------- -- GHC allows a more general form of lambda abstraction than specified -- by Haskell 98. In particular it allows guarded lambda's like : -- (\ x | even x -> 0 | odd x -> 1) at the moment we can't represent this in -- Haskell Template's Meta.Exp type so we punt if it isn't a simple thing like -- (\ p1 .. pn -> exp) by causing an error. repLambda :: LMatch Name (LHsExpr Name) -> DsM (Core TH.ExpQ) repLambda (L _ (Match _ ps _ (GRHSs [L _ (GRHS [] e)] EmptyLocalBinds))) = do { let bndrs = collectPatsBinders ps ; ; ss <- mkGenSyms bndrs ; lam <- addBinds ss ( do { xs <- repLPs ps; body <- repLE e; repLam xs body }) ; wrapGenSyms ss lam } repLambda (L _ m) = notHandled "Guarded labmdas" (pprMatch (LambdaExpr :: HsMatchContext Name) m) ----------------------------------------------------------------------------- -- Patterns -- repP deals with patterns. It assumes that we have already -- walked over the pattern(s) once to collect the binders, and -- have extended the environment. So every pattern-bound -- variable should already appear in the environment. -- Process a list of patterns repLPs :: [LPat Name] -> DsM (Core [TH.PatQ]) repLPs ps = repList patQTyConName repLP ps repLP :: LPat Name -> DsM (Core TH.PatQ) repLP (L _ p) = repP p repP :: Pat Name -> DsM (Core TH.PatQ) repP (WildPat _) = repPwild repP (LitPat l) = do { l2 <- repLiteral l; repPlit l2 } repP (VarPat x) = do { x' <- lookupBinder x; repPvar x' } repP (LazyPat p) = do { p1 <- repLP p; repPtilde p1 } repP (BangPat p) = do { p1 <- repLP p; repPbang p1 } repP (AsPat x p) = do { x' <- lookupLBinder x; p1 <- repLP p; repPaspat x' p1 } repP (ParPat p) = repLP p repP (ListPat ps _ Nothing) = do { qs <- repLPs ps; repPlist qs } repP (ListPat ps ty1 (Just (_,e))) = do { p <- repP (ListPat ps ty1 Nothing); e' <- repE e; repPview e' p} repP (TuplePat ps boxed _) | isBoxed boxed = do { qs <- repLPs ps; repPtup qs } | otherwise = do { qs <- repLPs ps; repPunboxedTup qs } repP (ConPatIn dc details) = do { con_str <- lookupLOcc dc ; case details of PrefixCon ps -> do { qs <- repLPs ps; repPcon con_str qs } RecCon rec -> do { fps <- repList fieldPatQTyConName rep_fld (rec_flds rec) ; repPrec con_str fps } InfixCon p1 p2 -> do { p1' <- repLP p1; p2' <- repLP p2; repPinfix p1' con_str p2' } } where rep_fld (L _ fld) = do { MkC v <- lookupLOcc (hsRecFieldId fld) ; MkC p <- repLP (hsRecFieldArg fld) ; rep2 fieldPatName [v,p] } repP (NPat (L _ l) Nothing _) = do { a <- repOverloadedLiteral l; repPlit a } repP (ViewPat e p _) = do { e' <- repLE e; p' <- repLP p; repPview e' p' } repP p@(NPat _ (Just _) _) = notHandled "Negative overloaded patterns" (ppr p) repP p@(SigPatIn {}) = notHandled "Type signatures in patterns" (ppr p) -- The problem is to do with scoped type variables. -- To implement them, we have to implement the scoping rules -- here in DsMeta, and I don't want to do that today! -- do { p' <- repLP p; t' <- repLTy t; repPsig p' t' } -- repPsig :: Core TH.PatQ -> Core TH.TypeQ -> DsM (Core TH.PatQ) -- repPsig (MkC p) (MkC t) = rep2 sigPName [p, t] repP (SplicePat splice) = repSplice splice repP other = notHandled "Exotic pattern" (ppr other) ---------------------------------------------------------- -- Declaration ordering helpers sort_by_loc :: [(SrcSpan, a)] -> [(SrcSpan, a)] sort_by_loc xs = sortBy comp xs where comp x y = compare (fst x) (fst y) de_loc :: [(a, b)] -> [b] de_loc = map snd ---------------------------------------------------------- -- The meta-environment -- A name/identifier association for fresh names of locally bound entities type GenSymBind = (Name, Id) -- Gensym the string and bind it to the Id -- I.e. (x, x_id) means -- let x_id = gensym "x" in ... -- Generate a fresh name for a locally bound entity mkGenSyms :: [Name] -> DsM [GenSymBind] -- We can use the existing name. For example: -- [| \x_77 -> x_77 + x_77 |] -- desugars to -- do { x_77 <- genSym "x"; .... } -- We use the same x_77 in the desugared program, but with the type Bndr -- instead of Int -- -- We do make it an Internal name, though (hence localiseName) -- -- Nevertheless, it's monadic because we have to generate nameTy mkGenSyms ns = do { var_ty <- lookupType nameTyConName ; return [(nm, mkLocalId (localiseName nm) var_ty) | nm <- ns] } addBinds :: [GenSymBind] -> DsM a -> DsM a -- Add a list of fresh names for locally bound entities to the -- meta environment (which is part of the state carried around -- by the desugarer monad) addBinds bs m = dsExtendMetaEnv (mkNameEnv [(n,DsBound id) | (n,id) <- bs]) m dupBinder :: (Name, Name) -> DsM (Name, DsMetaVal) dupBinder (new, old) = do { mb_val <- dsLookupMetaEnv old ; case mb_val of Just val -> return (new, val) Nothing -> pprPanic "dupBinder" (ppr old) } -- Look up a locally bound name -- lookupLBinder :: Located Name -> DsM (Core TH.Name) lookupLBinder (L _ n) = lookupBinder n lookupBinder :: Name -> DsM (Core TH.Name) lookupBinder = lookupOcc -- Binders are brought into scope before the pattern or what-not is -- desugared. Moreover, in instance declaration the binder of a method -- will be the selector Id and hence a global; so we need the -- globalVar case of lookupOcc -- Look up a name that is either locally bound or a global name -- -- * If it is a global name, generate the "original name" representation (ie, -- the <module>:<name> form) for the associated entity -- lookupLOcc :: Located Name -> DsM (Core TH.Name) -- Lookup an occurrence; it can't be a splice. -- Use the in-scope bindings if they exist lookupLOcc (L _ n) = lookupOcc n lookupOcc :: Name -> DsM (Core TH.Name) lookupOcc n = do { mb_val <- dsLookupMetaEnv n ; case mb_val of Nothing -> globalVar n Just (DsBound x) -> return (coreVar x) Just (DsSplice _) -> pprPanic "repE:lookupOcc" (ppr n) } globalVar :: Name -> DsM (Core TH.Name) -- Not bound by the meta-env -- Could be top-level; or could be local -- f x = $(g [| x |]) -- Here the x will be local globalVar name | isExternalName name = do { MkC mod <- coreStringLit name_mod ; MkC pkg <- coreStringLit name_pkg ; MkC occ <- occNameLit name ; rep2 mk_varg [pkg,mod,occ] } | otherwise = do { MkC occ <- occNameLit name ; MkC uni <- coreIntLit (getKey (getUnique name)) ; rep2 mkNameLName [occ,uni] } where mod = ASSERT( isExternalName name) nameModule name name_mod = moduleNameString (moduleName mod) name_pkg = packageKeyString (modulePackageKey mod) name_occ = nameOccName name mk_varg | OccName.isDataOcc name_occ = mkNameG_dName | OccName.isVarOcc name_occ = mkNameG_vName | OccName.isTcOcc name_occ = mkNameG_tcName | otherwise = pprPanic "DsMeta.globalVar" (ppr name) lookupType :: Name -- Name of type constructor (e.g. TH.ExpQ) -> DsM Type -- The type lookupType tc_name = do { tc <- dsLookupTyCon tc_name ; return (mkTyConApp tc []) } wrapGenSyms :: [GenSymBind] -> Core (TH.Q a) -> DsM (Core (TH.Q a)) -- wrapGenSyms [(nm1,id1), (nm2,id2)] y -- --> bindQ (gensym nm1) (\ id1 -> -- bindQ (gensym nm2 (\ id2 -> -- y)) wrapGenSyms binds body@(MkC b) = do { var_ty <- lookupType nameTyConName ; go var_ty binds } where [elt_ty] = tcTyConAppArgs (exprType b) -- b :: Q a, so we can get the type 'a' by looking at the -- argument type. NB: this relies on Q being a data/newtype, -- not a type synonym go _ [] = return body go var_ty ((name,id) : binds) = do { MkC body' <- go var_ty binds ; lit_str <- occNameLit name ; gensym_app <- repGensym lit_str ; repBindQ var_ty elt_ty gensym_app (MkC (Lam id body')) } occNameLit :: Name -> DsM (Core String) occNameLit n = coreStringLit (occNameString (nameOccName n)) -- %********************************************************************* -- %* * -- Constructing code -- %* * -- %********************************************************************* ----------------------------------------------------------------------------- -- PHANTOM TYPES for consistency. In order to make sure we do this correct -- we invent a new datatype which uses phantom types. newtype Core a = MkC CoreExpr unC :: Core a -> CoreExpr unC (MkC x) = x rep2 :: Name -> [ CoreExpr ] -> DsM (Core a) rep2 n xs = do { id <- dsLookupGlobalId n ; return (MkC (foldl App (Var id) xs)) } dataCon' :: Name -> [CoreExpr] -> DsM (Core a) dataCon' n args = do { id <- dsLookupDataCon n ; return $ MkC $ mkCoreConApps id args } dataCon :: Name -> DsM (Core a) dataCon n = dataCon' n [] -- Then we make "repConstructors" which use the phantom types for each of the -- smart constructors of the Meta.Meta datatypes. -- %********************************************************************* -- %* * -- The 'smart constructors' -- %* * -- %********************************************************************* --------------- Patterns ----------------- repPlit :: Core TH.Lit -> DsM (Core TH.PatQ) repPlit (MkC l) = rep2 litPName [l] repPvar :: Core TH.Name -> DsM (Core TH.PatQ) repPvar (MkC s) = rep2 varPName [s] repPtup :: Core [TH.PatQ] -> DsM (Core TH.PatQ) repPtup (MkC ps) = rep2 tupPName [ps] repPunboxedTup :: Core [TH.PatQ] -> DsM (Core TH.PatQ) repPunboxedTup (MkC ps) = rep2 unboxedTupPName [ps] repPcon :: Core TH.Name -> Core [TH.PatQ] -> DsM (Core TH.PatQ) repPcon (MkC s) (MkC ps) = rep2 conPName [s, ps] repPrec :: Core TH.Name -> Core [(TH.Name,TH.PatQ)] -> DsM (Core TH.PatQ) repPrec (MkC c) (MkC rps) = rep2 recPName [c,rps] repPinfix :: Core TH.PatQ -> Core TH.Name -> Core TH.PatQ -> DsM (Core TH.PatQ) repPinfix (MkC p1) (MkC n) (MkC p2) = rep2 infixPName [p1, n, p2] repPtilde :: Core TH.PatQ -> DsM (Core TH.PatQ) repPtilde (MkC p) = rep2 tildePName [p] repPbang :: Core TH.PatQ -> DsM (Core TH.PatQ) repPbang (MkC p) = rep2 bangPName [p] repPaspat :: Core TH.Name -> Core TH.PatQ -> DsM (Core TH.PatQ) repPaspat (MkC s) (MkC p) = rep2 asPName [s, p] repPwild :: DsM (Core TH.PatQ) repPwild = rep2 wildPName [] repPlist :: Core [TH.PatQ] -> DsM (Core TH.PatQ) repPlist (MkC ps) = rep2 listPName [ps] repPview :: Core TH.ExpQ -> Core TH.PatQ -> DsM (Core TH.PatQ) repPview (MkC e) (MkC p) = rep2 viewPName [e,p] --------------- Expressions ----------------- repVarOrCon :: Name -> Core TH.Name -> DsM (Core TH.ExpQ) repVarOrCon vc str | isDataOcc (nameOccName vc) = repCon str | otherwise = repVar str repVar :: Core TH.Name -> DsM (Core TH.ExpQ) repVar (MkC s) = rep2 varEName [s] repCon :: Core TH.Name -> DsM (Core TH.ExpQ) repCon (MkC s) = rep2 conEName [s] repLit :: Core TH.Lit -> DsM (Core TH.ExpQ) repLit (MkC c) = rep2 litEName [c] repApp :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repApp (MkC x) (MkC y) = rep2 appEName [x,y] repLam :: Core [TH.PatQ] -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repLam (MkC ps) (MkC e) = rep2 lamEName [ps, e] repLamCase :: Core [TH.MatchQ] -> DsM (Core TH.ExpQ) repLamCase (MkC ms) = rep2 lamCaseEName [ms] repTup :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ) repTup (MkC es) = rep2 tupEName [es] repUnboxedTup :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ) repUnboxedTup (MkC es) = rep2 unboxedTupEName [es] repCond :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repCond (MkC x) (MkC y) (MkC z) = rep2 condEName [x,y,z] repMultiIf :: Core [TH.Q (TH.Guard, TH.Exp)] -> DsM (Core TH.ExpQ) repMultiIf (MkC alts) = rep2 multiIfEName [alts] repLetE :: Core [TH.DecQ] -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repLetE (MkC ds) (MkC e) = rep2 letEName [ds, e] repCaseE :: Core TH.ExpQ -> Core [TH.MatchQ] -> DsM( Core TH.ExpQ) repCaseE (MkC e) (MkC ms) = rep2 caseEName [e, ms] repDoE :: Core [TH.StmtQ] -> DsM (Core TH.ExpQ) repDoE (MkC ss) = rep2 doEName [ss] repComp :: Core [TH.StmtQ] -> DsM (Core TH.ExpQ) repComp (MkC ss) = rep2 compEName [ss] repListExp :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ) repListExp (MkC es) = rep2 listEName [es] repSigExp :: Core TH.ExpQ -> Core TH.TypeQ -> DsM (Core TH.ExpQ) repSigExp (MkC e) (MkC t) = rep2 sigEName [e,t] repRecCon :: Core TH.Name -> Core [TH.Q TH.FieldExp]-> DsM (Core TH.ExpQ) repRecCon (MkC c) (MkC fs) = rep2 recConEName [c,fs] repRecUpd :: Core TH.ExpQ -> Core [TH.Q TH.FieldExp] -> DsM (Core TH.ExpQ) repRecUpd (MkC e) (MkC fs) = rep2 recUpdEName [e,fs] repFieldExp :: Core TH.Name -> Core TH.ExpQ -> DsM (Core (TH.Q TH.FieldExp)) repFieldExp (MkC n) (MkC x) = rep2 fieldExpName [n,x] repInfixApp :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repInfixApp (MkC x) (MkC y) (MkC z) = rep2 infixAppName [x,y,z] repSectionL :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repSectionL (MkC x) (MkC y) = rep2 sectionLName [x,y] repSectionR :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repSectionR (MkC x) (MkC y) = rep2 sectionRName [x,y] ------------ Right hand sides (guarded expressions) ---- repGuarded :: Core [TH.Q (TH.Guard, TH.Exp)] -> DsM (Core TH.BodyQ) repGuarded (MkC pairs) = rep2 guardedBName [pairs] repNormal :: Core TH.ExpQ -> DsM (Core TH.BodyQ) repNormal (MkC e) = rep2 normalBName [e] ------------ Guards ---- repLNormalGE :: LHsExpr Name -> LHsExpr Name -> DsM (Core (TH.Q (TH.Guard, TH.Exp))) repLNormalGE g e = do g' <- repLE g e' <- repLE e repNormalGE g' e' repNormalGE :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core (TH.Q (TH.Guard, TH.Exp))) repNormalGE (MkC g) (MkC e) = rep2 normalGEName [g, e] repPatGE :: Core [TH.StmtQ] -> Core TH.ExpQ -> DsM (Core (TH.Q (TH.Guard, TH.Exp))) repPatGE (MkC ss) (MkC e) = rep2 patGEName [ss, e] ------------- Stmts ------------------- repBindSt :: Core TH.PatQ -> Core TH.ExpQ -> DsM (Core TH.StmtQ) repBindSt (MkC p) (MkC e) = rep2 bindSName [p,e] repLetSt :: Core [TH.DecQ] -> DsM (Core TH.StmtQ) repLetSt (MkC ds) = rep2 letSName [ds] repNoBindSt :: Core TH.ExpQ -> DsM (Core TH.StmtQ) repNoBindSt (MkC e) = rep2 noBindSName [e] repParSt :: Core [[TH.StmtQ]] -> DsM (Core TH.StmtQ) repParSt (MkC sss) = rep2 parSName [sss] -------------- Range (Arithmetic sequences) ----------- repFrom :: Core TH.ExpQ -> DsM (Core TH.ExpQ) repFrom (MkC x) = rep2 fromEName [x] repFromThen :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repFromThen (MkC x) (MkC y) = rep2 fromThenEName [x,y] repFromTo :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repFromTo (MkC x) (MkC y) = rep2 fromToEName [x,y] repFromThenTo :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repFromThenTo (MkC x) (MkC y) (MkC z) = rep2 fromThenToEName [x,y,z] ------------ Match and Clause Tuples ----------- repMatch :: Core TH.PatQ -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.MatchQ) repMatch (MkC p) (MkC bod) (MkC ds) = rep2 matchName [p, bod, ds] repClause :: Core [TH.PatQ] -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.ClauseQ) repClause (MkC ps) (MkC bod) (MkC ds) = rep2 clauseName [ps, bod, ds] -------------- Dec ----------------------------- repVal :: Core TH.PatQ -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.DecQ) repVal (MkC p) (MkC b) (MkC ds) = rep2 valDName [p, b, ds] repFun :: Core TH.Name -> Core [TH.ClauseQ] -> DsM (Core TH.DecQ) repFun (MkC nm) (MkC b) = rep2 funDName [nm, b] repData :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndr] -> Maybe (Core [TH.TypeQ]) -> Core [TH.ConQ] -> Core [TH.Name] -> DsM (Core TH.DecQ) repData (MkC cxt) (MkC nm) (MkC tvs) Nothing (MkC cons) (MkC derivs) = rep2 dataDName [cxt, nm, tvs, cons, derivs] repData (MkC cxt) (MkC nm) (MkC _) (Just (MkC tys)) (MkC cons) (MkC derivs) = rep2 dataInstDName [cxt, nm, tys, cons, derivs] repNewtype :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndr] -> Maybe (Core [TH.TypeQ]) -> Core TH.ConQ -> Core [TH.Name] -> DsM (Core TH.DecQ) repNewtype (MkC cxt) (MkC nm) (MkC tvs) Nothing (MkC con) (MkC derivs) = rep2 newtypeDName [cxt, nm, tvs, con, derivs] repNewtype (MkC cxt) (MkC nm) (MkC _) (Just (MkC tys)) (MkC con) (MkC derivs) = rep2 newtypeInstDName [cxt, nm, tys, con, derivs] repTySyn :: Core TH.Name -> Core [TH.TyVarBndr] -> Core TH.TypeQ -> DsM (Core TH.DecQ) repTySyn (MkC nm) (MkC tvs) (MkC rhs) = rep2 tySynDName [nm, tvs, rhs] repInst :: Core TH.CxtQ -> Core TH.TypeQ -> Core [TH.DecQ] -> DsM (Core TH.DecQ) repInst (MkC cxt) (MkC ty) (MkC ds) = rep2 instanceDName [cxt, ty, ds] repClass :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndr] -> Core [TH.FunDep] -> Core [TH.DecQ] -> DsM (Core TH.DecQ) repClass (MkC cxt) (MkC cls) (MkC tvs) (MkC fds) (MkC ds) = rep2 classDName [cxt, cls, tvs, fds, ds] repDeriv :: Core TH.CxtQ -> Core TH.TypeQ -> DsM (Core TH.DecQ) repDeriv (MkC cxt) (MkC ty) = rep2 standaloneDerivDName [cxt, ty] repPragInl :: Core TH.Name -> Core TH.Inline -> Core TH.RuleMatch -> Core TH.Phases -> DsM (Core TH.DecQ) repPragInl (MkC nm) (MkC inline) (MkC rm) (MkC phases) = rep2 pragInlDName [nm, inline, rm, phases] repPragSpec :: Core TH.Name -> Core TH.TypeQ -> Core TH.Phases -> DsM (Core TH.DecQ) repPragSpec (MkC nm) (MkC ty) (MkC phases) = rep2 pragSpecDName [nm, ty, phases] repPragSpecInl :: Core TH.Name -> Core TH.TypeQ -> Core TH.Inline -> Core TH.Phases -> DsM (Core TH.DecQ) repPragSpecInl (MkC nm) (MkC ty) (MkC inline) (MkC phases) = rep2 pragSpecInlDName [nm, ty, inline, phases] repPragSpecInst :: Core TH.TypeQ -> DsM (Core TH.DecQ) repPragSpecInst (MkC ty) = rep2 pragSpecInstDName [ty] repPragRule :: Core String -> Core [TH.RuleBndrQ] -> Core TH.ExpQ -> Core TH.ExpQ -> Core TH.Phases -> DsM (Core TH.DecQ) repPragRule (MkC nm) (MkC bndrs) (MkC lhs) (MkC rhs) (MkC phases) = rep2 pragRuleDName [nm, bndrs, lhs, rhs, phases] repPragAnn :: Core TH.AnnTarget -> Core TH.ExpQ -> DsM (Core TH.DecQ) repPragAnn (MkC targ) (MkC e) = rep2 pragAnnDName [targ, e] repFamilyNoKind :: Core TH.FamFlavour -> Core TH.Name -> Core [TH.TyVarBndr] -> DsM (Core TH.DecQ) repFamilyNoKind (MkC flav) (MkC nm) (MkC tvs) = rep2 familyNoKindDName [flav, nm, tvs] repFamilyKind :: Core TH.FamFlavour -> Core TH.Name -> Core [TH.TyVarBndr] -> Core TH.Kind -> DsM (Core TH.DecQ) repFamilyKind (MkC flav) (MkC nm) (MkC tvs) (MkC ki) = rep2 familyKindDName [flav, nm, tvs, ki] repTySynInst :: Core TH.Name -> Core TH.TySynEqnQ -> DsM (Core TH.DecQ) repTySynInst (MkC nm) (MkC eqn) = rep2 tySynInstDName [nm, eqn] repClosedFamilyNoKind :: Core TH.Name -> Core [TH.TyVarBndr] -> Core [TH.TySynEqnQ] -> DsM (Core TH.DecQ) repClosedFamilyNoKind (MkC nm) (MkC tvs) (MkC eqns) = rep2 closedTypeFamilyNoKindDName [nm, tvs, eqns] repClosedFamilyKind :: Core TH.Name -> Core [TH.TyVarBndr] -> Core TH.Kind -> Core [TH.TySynEqnQ] -> DsM (Core TH.DecQ) repClosedFamilyKind (MkC nm) (MkC tvs) (MkC ki) (MkC eqns) = rep2 closedTypeFamilyKindDName [nm, tvs, ki, eqns] repTySynEqn :: Core [TH.TypeQ] -> Core TH.TypeQ -> DsM (Core TH.TySynEqnQ) repTySynEqn (MkC lhs) (MkC rhs) = rep2 tySynEqnName [lhs, rhs] repRoleAnnotD :: Core TH.Name -> Core [TH.Role] -> DsM (Core TH.DecQ) repRoleAnnotD (MkC n) (MkC roles) = rep2 roleAnnotDName [n, roles] repFunDep :: Core [TH.Name] -> Core [TH.Name] -> DsM (Core TH.FunDep) repFunDep (MkC xs) (MkC ys) = rep2 funDepName [xs, ys] repProto :: Name -> Core TH.Name -> Core TH.TypeQ -> DsM (Core TH.DecQ) repProto mk_sig (MkC s) (MkC ty) = rep2 mk_sig [s, ty] repCtxt :: Core [TH.PredQ] -> DsM (Core TH.CxtQ) repCtxt (MkC tys) = rep2 cxtName [tys] repConstr :: Core TH.Name -> HsConDeclDetails Name -> DsM (Core TH.ConQ) repConstr con (PrefixCon ps) = do arg_tys <- repList strictTypeQTyConName repBangTy ps rep2 normalCName [unC con, unC arg_tys] repConstr con (RecCon (L _ ips)) = do { args <- concatMapM rep_ip ips ; arg_vtys <- coreList varStrictTypeQTyConName args ; rep2 recCName [unC con, unC arg_vtys] } where rep_ip (L _ ip) = mapM (rep_one_ip (cd_fld_type ip)) (cd_fld_names ip) rep_one_ip t n = do { MkC v <- lookupLOcc n ; MkC ty <- repBangTy t ; rep2 varStrictTypeName [v,ty] } repConstr con (InfixCon st1 st2) = do arg1 <- repBangTy st1 arg2 <- repBangTy st2 rep2 infixCName [unC arg1, unC con, unC arg2] ------------ Types ------------------- repTForall :: Core [TH.TyVarBndr] -> Core TH.CxtQ -> Core TH.TypeQ -> DsM (Core TH.TypeQ) repTForall (MkC tvars) (MkC ctxt) (MkC ty) = rep2 forallTName [tvars, ctxt, ty] repTvar :: Core TH.Name -> DsM (Core TH.TypeQ) repTvar (MkC s) = rep2 varTName [s] repTapp :: Core TH.TypeQ -> Core TH.TypeQ -> DsM (Core TH.TypeQ) repTapp (MkC t1) (MkC t2) = rep2 appTName [t1, t2] repTapps :: Core TH.TypeQ -> [Core TH.TypeQ] -> DsM (Core TH.TypeQ) repTapps f [] = return f repTapps f (t:ts) = do { f1 <- repTapp f t; repTapps f1 ts } repTSig :: Core TH.TypeQ -> Core TH.Kind -> DsM (Core TH.TypeQ) repTSig (MkC ty) (MkC ki) = rep2 sigTName [ty, ki] repTequality :: DsM (Core TH.TypeQ) repTequality = rep2 equalityTName [] repTPromotedList :: [Core TH.TypeQ] -> DsM (Core TH.TypeQ) repTPromotedList [] = repPromotedNilTyCon repTPromotedList (t:ts) = do { tcon <- repPromotedConsTyCon ; f <- repTapp tcon t ; t' <- repTPromotedList ts ; repTapp f t' } repTLit :: Core TH.TyLitQ -> DsM (Core TH.TypeQ) repTLit (MkC lit) = rep2 litTName [lit] --------- Type constructors -------------- repNamedTyCon :: Core TH.Name -> DsM (Core TH.TypeQ) repNamedTyCon (MkC s) = rep2 conTName [s] repTupleTyCon :: Int -> DsM (Core TH.TypeQ) -- Note: not Core Int; it's easier to be direct here repTupleTyCon i = do dflags <- getDynFlags rep2 tupleTName [mkIntExprInt dflags i] repUnboxedTupleTyCon :: Int -> DsM (Core TH.TypeQ) -- Note: not Core Int; it's easier to be direct here repUnboxedTupleTyCon i = do dflags <- getDynFlags rep2 unboxedTupleTName [mkIntExprInt dflags i] repArrowTyCon :: DsM (Core TH.TypeQ) repArrowTyCon = rep2 arrowTName [] repListTyCon :: DsM (Core TH.TypeQ) repListTyCon = rep2 listTName [] repPromotedTyCon :: Core TH.Name -> DsM (Core TH.TypeQ) repPromotedTyCon (MkC s) = rep2 promotedTName [s] repPromotedTupleTyCon :: Int -> DsM (Core TH.TypeQ) repPromotedTupleTyCon i = do dflags <- getDynFlags rep2 promotedTupleTName [mkIntExprInt dflags i] repPromotedNilTyCon :: DsM (Core TH.TypeQ) repPromotedNilTyCon = rep2 promotedNilTName [] repPromotedConsTyCon :: DsM (Core TH.TypeQ) repPromotedConsTyCon = rep2 promotedConsTName [] ------------ Kinds ------------------- repPlainTV :: Core TH.Name -> DsM (Core TH.TyVarBndr) repPlainTV (MkC nm) = rep2 plainTVName [nm] repKindedTV :: Core TH.Name -> Core TH.Kind -> DsM (Core TH.TyVarBndr) repKindedTV (MkC nm) (MkC ki) = rep2 kindedTVName [nm, ki] repKVar :: Core TH.Name -> DsM (Core TH.Kind) repKVar (MkC s) = rep2 varKName [s] repKCon :: Core TH.Name -> DsM (Core TH.Kind) repKCon (MkC s) = rep2 conKName [s] repKTuple :: Int -> DsM (Core TH.Kind) repKTuple i = do dflags <- getDynFlags rep2 tupleKName [mkIntExprInt dflags i] repKArrow :: DsM (Core TH.Kind) repKArrow = rep2 arrowKName [] repKList :: DsM (Core TH.Kind) repKList = rep2 listKName [] repKApp :: Core TH.Kind -> Core TH.Kind -> DsM (Core TH.Kind) repKApp (MkC k1) (MkC k2) = rep2 appKName [k1, k2] repKApps :: Core TH.Kind -> [Core TH.Kind] -> DsM (Core TH.Kind) repKApps f [] = return f repKApps f (k:ks) = do { f' <- repKApp f k; repKApps f' ks } repKStar :: DsM (Core TH.Kind) repKStar = rep2 starKName [] repKConstraint :: DsM (Core TH.Kind) repKConstraint = rep2 constraintKName [] ---------------------------------------------------------- -- Literals repLiteral :: HsLit -> DsM (Core TH.Lit) repLiteral lit = do lit' <- case lit of HsIntPrim _ i -> mk_integer i HsWordPrim _ w -> mk_integer w HsInt _ i -> mk_integer i HsFloatPrim r -> mk_rational r HsDoublePrim r -> mk_rational r _ -> return lit lit_expr <- dsLit lit' case mb_lit_name of Just lit_name -> rep2 lit_name [lit_expr] Nothing -> notHandled "Exotic literal" (ppr lit) where mb_lit_name = case lit of HsInteger _ _ _ -> Just integerLName HsInt _ _ -> Just integerLName HsIntPrim _ _ -> Just intPrimLName HsWordPrim _ _ -> Just wordPrimLName HsFloatPrim _ -> Just floatPrimLName HsDoublePrim _ -> Just doublePrimLName HsChar _ _ -> Just charLName HsString _ _ -> Just stringLName HsRat _ _ -> Just rationalLName _ -> Nothing mk_integer :: Integer -> DsM HsLit mk_integer i = do integer_ty <- lookupType integerTyConName return $ HsInteger "" i integer_ty mk_rational :: FractionalLit -> DsM HsLit mk_rational r = do rat_ty <- lookupType rationalTyConName return $ HsRat r rat_ty mk_string :: FastString -> DsM HsLit mk_string s = return $ HsString "" s repOverloadedLiteral :: HsOverLit Name -> DsM (Core TH.Lit) repOverloadedLiteral (OverLit { ol_val = val}) = do { lit <- mk_lit val; repLiteral lit } -- The type Rational will be in the environment, because -- the smart constructor 'TH.Syntax.rationalL' uses it in its type, -- and rationalL is sucked in when any TH stuff is used mk_lit :: OverLitVal -> DsM HsLit mk_lit (HsIntegral _ i) = mk_integer i mk_lit (HsFractional f) = mk_rational f mk_lit (HsIsString _ s) = mk_string s --------------- Miscellaneous ------------------- repGensym :: Core String -> DsM (Core (TH.Q TH.Name)) repGensym (MkC lit_str) = rep2 newNameName [lit_str] repBindQ :: Type -> Type -- a and b -> Core (TH.Q a) -> Core (a -> TH.Q b) -> DsM (Core (TH.Q b)) repBindQ ty_a ty_b (MkC x) (MkC y) = rep2 bindQName [Type ty_a, Type ty_b, x, y] repSequenceQ :: Type -> Core [TH.Q a] -> DsM (Core (TH.Q [a])) repSequenceQ ty_a (MkC list) = rep2 sequenceQName [Type ty_a, list] ------------ Lists and Tuples ------------------- -- turn a list of patterns into a single pattern matching a list repList :: Name -> (a -> DsM (Core b)) -> [a] -> DsM (Core [b]) repList tc_name f args = do { args1 <- mapM f args ; coreList tc_name args1 } coreList :: Name -- Of the TyCon of the element type -> [Core a] -> DsM (Core [a]) coreList tc_name es = do { elt_ty <- lookupType tc_name; return (coreList' elt_ty es) } coreList' :: Type -- The element type -> [Core a] -> Core [a] coreList' elt_ty es = MkC (mkListExpr elt_ty (map unC es )) nonEmptyCoreList :: [Core a] -> Core [a] -- The list must be non-empty so we can get the element type -- Otherwise use coreList nonEmptyCoreList [] = panic "coreList: empty argument" nonEmptyCoreList xs@(MkC x:_) = MkC (mkListExpr (exprType x) (map unC xs)) coreStringLit :: String -> DsM (Core String) coreStringLit s = do { z <- mkStringExpr s; return(MkC z) } ------------ Literals & Variables ------------------- coreIntLit :: Int -> DsM (Core Int) coreIntLit i = do dflags <- getDynFlags return (MkC (mkIntExprInt dflags i)) coreVar :: Id -> Core TH.Name -- The Id has type Name coreVar id = MkC (Var id) ----------------- Failure ----------------------- notHandledL :: SrcSpan -> String -> SDoc -> DsM a notHandledL loc what doc | isGoodSrcSpan loc = putSrcSpanDs loc $ notHandled what doc | otherwise = notHandled what doc notHandled :: String -> SDoc -> DsM a notHandled what doc = failWithDs msg where msg = hang (text what <+> ptext (sLit "not (yet) handled by Template Haskell")) 2 doc -- %************************************************************************ -- %* * -- The known-key names for Template Haskell -- %* * -- %************************************************************************ -- To add a name, do three things -- -- 1) Allocate a key -- 2) Make a "Name" -- 3) Add the name to knownKeyNames templateHaskellNames :: [Name] -- The names that are implicitly mentioned by ``bracket'' -- Should stay in sync with the import list of DsMeta templateHaskellNames = [ returnQName, bindQName, sequenceQName, newNameName, liftName, mkNameName, mkNameG_vName, mkNameG_dName, mkNameG_tcName, mkNameLName, liftStringName, unTypeName, unTypeQName, unsafeTExpCoerceName, -- Lit charLName, stringLName, integerLName, intPrimLName, wordPrimLName, floatPrimLName, doublePrimLName, rationalLName, -- Pat litPName, varPName, tupPName, unboxedTupPName, conPName, tildePName, bangPName, infixPName, asPName, wildPName, recPName, listPName, sigPName, viewPName, -- FieldPat fieldPatName, -- Match matchName, -- Clause clauseName, -- Exp varEName, conEName, litEName, appEName, infixEName, infixAppName, sectionLName, sectionRName, lamEName, lamCaseEName, tupEName, unboxedTupEName, condEName, multiIfEName, letEName, caseEName, doEName, compEName, fromEName, fromThenEName, fromToEName, fromThenToEName, listEName, sigEName, recConEName, recUpdEName, staticEName, -- FieldExp fieldExpName, -- Body guardedBName, normalBName, -- Guard normalGEName, patGEName, -- Stmt bindSName, letSName, noBindSName, parSName, -- Dec funDName, valDName, dataDName, newtypeDName, tySynDName, classDName, instanceDName, standaloneDerivDName, sigDName, forImpDName, pragInlDName, pragSpecDName, pragSpecInlDName, pragSpecInstDName, pragRuleDName, pragAnnDName, defaultSigDName, familyNoKindDName, familyKindDName, dataInstDName, newtypeInstDName, tySynInstDName, closedTypeFamilyKindDName, closedTypeFamilyNoKindDName, infixLDName, infixRDName, infixNDName, roleAnnotDName, -- Cxt cxtName, -- Strict isStrictName, notStrictName, unpackedName, -- Con normalCName, recCName, infixCName, forallCName, -- StrictType strictTypeName, -- VarStrictType varStrictTypeName, -- Type forallTName, varTName, conTName, appTName, equalityTName, tupleTName, unboxedTupleTName, arrowTName, listTName, sigTName, litTName, promotedTName, promotedTupleTName, promotedNilTName, promotedConsTName, -- TyLit numTyLitName, strTyLitName, -- TyVarBndr plainTVName, kindedTVName, -- Role nominalRName, representationalRName, phantomRName, inferRName, -- Kind varKName, conKName, tupleKName, arrowKName, listKName, appKName, starKName, constraintKName, -- Callconv cCallName, stdCallName, cApiCallName, primCallName, javaScriptCallName, -- Safety unsafeName, safeName, interruptibleName, -- Inline noInlineDataConName, inlineDataConName, inlinableDataConName, -- RuleMatch conLikeDataConName, funLikeDataConName, -- Phases allPhasesDataConName, fromPhaseDataConName, beforePhaseDataConName, -- TExp tExpDataConName, -- RuleBndr ruleVarName, typedRuleVarName, -- FunDep funDepName, -- FamFlavour typeFamName, dataFamName, -- TySynEqn tySynEqnName, -- AnnTarget valueAnnotationName, typeAnnotationName, moduleAnnotationName, -- And the tycons qTyConName, nameTyConName, patTyConName, fieldPatTyConName, matchQTyConName, clauseQTyConName, expQTyConName, fieldExpTyConName, predTyConName, stmtQTyConName, decQTyConName, conQTyConName, strictTypeQTyConName, varStrictTypeQTyConName, typeQTyConName, expTyConName, decTyConName, typeTyConName, tyVarBndrTyConName, matchTyConName, clauseTyConName, patQTyConName, fieldPatQTyConName, fieldExpQTyConName, funDepTyConName, predQTyConName, decsQTyConName, ruleBndrQTyConName, tySynEqnQTyConName, roleTyConName, tExpTyConName, -- Quasiquoting quoteDecName, quoteTypeName, quoteExpName, quotePatName] thSyn, thLib, qqLib :: Module thSyn = mkTHModule (fsLit "Language.Haskell.TH.Syntax") thLib = mkTHModule (fsLit "Language.Haskell.TH.Lib") qqLib = mkTHModule (fsLit "Language.Haskell.TH.Quote") mkTHModule :: FastString -> Module mkTHModule m = mkModule thPackageKey (mkModuleNameFS m) libFun, libTc, thFun, thTc, thCon, qqFun :: FastString -> Unique -> Name libFun = mk_known_key_name OccName.varName thLib libTc = mk_known_key_name OccName.tcName thLib thFun = mk_known_key_name OccName.varName thSyn thTc = mk_known_key_name OccName.tcName thSyn thCon = mk_known_key_name OccName.dataName thSyn qqFun = mk_known_key_name OccName.varName qqLib -------------------- TH.Syntax ----------------------- qTyConName, nameTyConName, fieldExpTyConName, patTyConName, fieldPatTyConName, expTyConName, decTyConName, typeTyConName, tyVarBndrTyConName, matchTyConName, clauseTyConName, funDepTyConName, predTyConName, tExpTyConName :: Name qTyConName = thTc (fsLit "Q") qTyConKey nameTyConName = thTc (fsLit "Name") nameTyConKey fieldExpTyConName = thTc (fsLit "FieldExp") fieldExpTyConKey patTyConName = thTc (fsLit "Pat") patTyConKey fieldPatTyConName = thTc (fsLit "FieldPat") fieldPatTyConKey expTyConName = thTc (fsLit "Exp") expTyConKey decTyConName = thTc (fsLit "Dec") decTyConKey typeTyConName = thTc (fsLit "Type") typeTyConKey tyVarBndrTyConName= thTc (fsLit "TyVarBndr") tyVarBndrTyConKey matchTyConName = thTc (fsLit "Match") matchTyConKey clauseTyConName = thTc (fsLit "Clause") clauseTyConKey funDepTyConName = thTc (fsLit "FunDep") funDepTyConKey predTyConName = thTc (fsLit "Pred") predTyConKey tExpTyConName = thTc (fsLit "TExp") tExpTyConKey returnQName, bindQName, sequenceQName, newNameName, liftName, mkNameName, mkNameG_vName, mkNameG_dName, mkNameG_tcName, mkNameLName, liftStringName, unTypeName, unTypeQName, unsafeTExpCoerceName :: Name returnQName = thFun (fsLit "returnQ") returnQIdKey bindQName = thFun (fsLit "bindQ") bindQIdKey sequenceQName = thFun (fsLit "sequenceQ") sequenceQIdKey newNameName = thFun (fsLit "newName") newNameIdKey liftName = thFun (fsLit "lift") liftIdKey liftStringName = thFun (fsLit "liftString") liftStringIdKey mkNameName = thFun (fsLit "mkName") mkNameIdKey mkNameG_vName = thFun (fsLit "mkNameG_v") mkNameG_vIdKey mkNameG_dName = thFun (fsLit "mkNameG_d") mkNameG_dIdKey mkNameG_tcName = thFun (fsLit "mkNameG_tc") mkNameG_tcIdKey mkNameLName = thFun (fsLit "mkNameL") mkNameLIdKey unTypeName = thFun (fsLit "unType") unTypeIdKey unTypeQName = thFun (fsLit "unTypeQ") unTypeQIdKey unsafeTExpCoerceName = thFun (fsLit "unsafeTExpCoerce") unsafeTExpCoerceIdKey -------------------- TH.Lib ----------------------- -- data Lit = ... charLName, stringLName, integerLName, intPrimLName, wordPrimLName, floatPrimLName, doublePrimLName, rationalLName :: Name charLName = libFun (fsLit "charL") charLIdKey stringLName = libFun (fsLit "stringL") stringLIdKey integerLName = libFun (fsLit "integerL") integerLIdKey intPrimLName = libFun (fsLit "intPrimL") intPrimLIdKey wordPrimLName = libFun (fsLit "wordPrimL") wordPrimLIdKey floatPrimLName = libFun (fsLit "floatPrimL") floatPrimLIdKey doublePrimLName = libFun (fsLit "doublePrimL") doublePrimLIdKey rationalLName = libFun (fsLit "rationalL") rationalLIdKey -- data Pat = ... litPName, varPName, tupPName, unboxedTupPName, conPName, infixPName, tildePName, bangPName, asPName, wildPName, recPName, listPName, sigPName, viewPName :: Name litPName = libFun (fsLit "litP") litPIdKey varPName = libFun (fsLit "varP") varPIdKey tupPName = libFun (fsLit "tupP") tupPIdKey unboxedTupPName = libFun (fsLit "unboxedTupP") unboxedTupPIdKey conPName = libFun (fsLit "conP") conPIdKey infixPName = libFun (fsLit "infixP") infixPIdKey tildePName = libFun (fsLit "tildeP") tildePIdKey bangPName = libFun (fsLit "bangP") bangPIdKey asPName = libFun (fsLit "asP") asPIdKey wildPName = libFun (fsLit "wildP") wildPIdKey recPName = libFun (fsLit "recP") recPIdKey listPName = libFun (fsLit "listP") listPIdKey sigPName = libFun (fsLit "sigP") sigPIdKey viewPName = libFun (fsLit "viewP") viewPIdKey -- type FieldPat = ... fieldPatName :: Name fieldPatName = libFun (fsLit "fieldPat") fieldPatIdKey -- data Match = ... matchName :: Name matchName = libFun (fsLit "match") matchIdKey -- data Clause = ... clauseName :: Name clauseName = libFun (fsLit "clause") clauseIdKey -- data Exp = ... varEName, conEName, litEName, appEName, infixEName, infixAppName, sectionLName, sectionRName, lamEName, lamCaseEName, tupEName, unboxedTupEName, condEName, multiIfEName, letEName, caseEName, doEName, compEName, staticEName :: Name varEName = libFun (fsLit "varE") varEIdKey conEName = libFun (fsLit "conE") conEIdKey litEName = libFun (fsLit "litE") litEIdKey appEName = libFun (fsLit "appE") appEIdKey infixEName = libFun (fsLit "infixE") infixEIdKey infixAppName = libFun (fsLit "infixApp") infixAppIdKey sectionLName = libFun (fsLit "sectionL") sectionLIdKey sectionRName = libFun (fsLit "sectionR") sectionRIdKey lamEName = libFun (fsLit "lamE") lamEIdKey lamCaseEName = libFun (fsLit "lamCaseE") lamCaseEIdKey tupEName = libFun (fsLit "tupE") tupEIdKey unboxedTupEName = libFun (fsLit "unboxedTupE") unboxedTupEIdKey condEName = libFun (fsLit "condE") condEIdKey multiIfEName = libFun (fsLit "multiIfE") multiIfEIdKey letEName = libFun (fsLit "letE") letEIdKey caseEName = libFun (fsLit "caseE") caseEIdKey doEName = libFun (fsLit "doE") doEIdKey compEName = libFun (fsLit "compE") compEIdKey -- ArithSeq skips a level fromEName, fromThenEName, fromToEName, fromThenToEName :: Name fromEName = libFun (fsLit "fromE") fromEIdKey fromThenEName = libFun (fsLit "fromThenE") fromThenEIdKey fromToEName = libFun (fsLit "fromToE") fromToEIdKey fromThenToEName = libFun (fsLit "fromThenToE") fromThenToEIdKey -- end ArithSeq listEName, sigEName, recConEName, recUpdEName :: Name listEName = libFun (fsLit "listE") listEIdKey sigEName = libFun (fsLit "sigE") sigEIdKey recConEName = libFun (fsLit "recConE") recConEIdKey recUpdEName = libFun (fsLit "recUpdE") recUpdEIdKey staticEName = libFun (fsLit "staticE") staticEIdKey -- type FieldExp = ... fieldExpName :: Name fieldExpName = libFun (fsLit "fieldExp") fieldExpIdKey -- data Body = ... guardedBName, normalBName :: Name guardedBName = libFun (fsLit "guardedB") guardedBIdKey normalBName = libFun (fsLit "normalB") normalBIdKey -- data Guard = ... normalGEName, patGEName :: Name normalGEName = libFun (fsLit "normalGE") normalGEIdKey patGEName = libFun (fsLit "patGE") patGEIdKey -- data Stmt = ... bindSName, letSName, noBindSName, parSName :: Name bindSName = libFun (fsLit "bindS") bindSIdKey letSName = libFun (fsLit "letS") letSIdKey noBindSName = libFun (fsLit "noBindS") noBindSIdKey parSName = libFun (fsLit "parS") parSIdKey -- data Dec = ... funDName, valDName, dataDName, newtypeDName, tySynDName, classDName, instanceDName, sigDName, forImpDName, pragInlDName, pragSpecDName, pragSpecInlDName, pragSpecInstDName, pragRuleDName, pragAnnDName, familyNoKindDName, standaloneDerivDName, defaultSigDName, familyKindDName, dataInstDName, newtypeInstDName, tySynInstDName, closedTypeFamilyKindDName, closedTypeFamilyNoKindDName, infixLDName, infixRDName, infixNDName, roleAnnotDName :: Name funDName = libFun (fsLit "funD") funDIdKey valDName = libFun (fsLit "valD") valDIdKey dataDName = libFun (fsLit "dataD") dataDIdKey newtypeDName = libFun (fsLit "newtypeD") newtypeDIdKey tySynDName = libFun (fsLit "tySynD") tySynDIdKey classDName = libFun (fsLit "classD") classDIdKey instanceDName = libFun (fsLit "instanceD") instanceDIdKey standaloneDerivDName = libFun (fsLit "standaloneDerivD") standaloneDerivDIdKey sigDName = libFun (fsLit "sigD") sigDIdKey defaultSigDName = libFun (fsLit "defaultSigD") defaultSigDIdKey forImpDName = libFun (fsLit "forImpD") forImpDIdKey pragInlDName = libFun (fsLit "pragInlD") pragInlDIdKey pragSpecDName = libFun (fsLit "pragSpecD") pragSpecDIdKey pragSpecInlDName = libFun (fsLit "pragSpecInlD") pragSpecInlDIdKey pragSpecInstDName = libFun (fsLit "pragSpecInstD") pragSpecInstDIdKey pragRuleDName = libFun (fsLit "pragRuleD") pragRuleDIdKey pragAnnDName = libFun (fsLit "pragAnnD") pragAnnDIdKey familyNoKindDName = libFun (fsLit "familyNoKindD") familyNoKindDIdKey familyKindDName = libFun (fsLit "familyKindD") familyKindDIdKey dataInstDName = libFun (fsLit "dataInstD") dataInstDIdKey newtypeInstDName = libFun (fsLit "newtypeInstD") newtypeInstDIdKey tySynInstDName = libFun (fsLit "tySynInstD") tySynInstDIdKey closedTypeFamilyKindDName = libFun (fsLit "closedTypeFamilyKindD") closedTypeFamilyKindDIdKey closedTypeFamilyNoKindDName = libFun (fsLit "closedTypeFamilyNoKindD") closedTypeFamilyNoKindDIdKey infixLDName = libFun (fsLit "infixLD") infixLDIdKey infixRDName = libFun (fsLit "infixRD") infixRDIdKey infixNDName = libFun (fsLit "infixND") infixNDIdKey roleAnnotDName = libFun (fsLit "roleAnnotD") roleAnnotDIdKey -- type Ctxt = ... cxtName :: Name cxtName = libFun (fsLit "cxt") cxtIdKey -- data Strict = ... isStrictName, notStrictName, unpackedName :: Name isStrictName = libFun (fsLit "isStrict") isStrictKey notStrictName = libFun (fsLit "notStrict") notStrictKey unpackedName = libFun (fsLit "unpacked") unpackedKey -- data Con = ... normalCName, recCName, infixCName, forallCName :: Name normalCName = libFun (fsLit "normalC") normalCIdKey recCName = libFun (fsLit "recC") recCIdKey infixCName = libFun (fsLit "infixC") infixCIdKey forallCName = libFun (fsLit "forallC") forallCIdKey -- type StrictType = ... strictTypeName :: Name strictTypeName = libFun (fsLit "strictType") strictTKey -- type VarStrictType = ... varStrictTypeName :: Name varStrictTypeName = libFun (fsLit "varStrictType") varStrictTKey -- data Type = ... forallTName, varTName, conTName, tupleTName, unboxedTupleTName, arrowTName, listTName, appTName, sigTName, equalityTName, litTName, promotedTName, promotedTupleTName, promotedNilTName, promotedConsTName :: Name forallTName = libFun (fsLit "forallT") forallTIdKey varTName = libFun (fsLit "varT") varTIdKey conTName = libFun (fsLit "conT") conTIdKey tupleTName = libFun (fsLit "tupleT") tupleTIdKey unboxedTupleTName = libFun (fsLit "unboxedTupleT") unboxedTupleTIdKey arrowTName = libFun (fsLit "arrowT") arrowTIdKey listTName = libFun (fsLit "listT") listTIdKey appTName = libFun (fsLit "appT") appTIdKey sigTName = libFun (fsLit "sigT") sigTIdKey equalityTName = libFun (fsLit "equalityT") equalityTIdKey litTName = libFun (fsLit "litT") litTIdKey promotedTName = libFun (fsLit "promotedT") promotedTIdKey promotedTupleTName = libFun (fsLit "promotedTupleT") promotedTupleTIdKey promotedNilTName = libFun (fsLit "promotedNilT") promotedNilTIdKey promotedConsTName = libFun (fsLit "promotedConsT") promotedConsTIdKey -- data TyLit = ... numTyLitName, strTyLitName :: Name numTyLitName = libFun (fsLit "numTyLit") numTyLitIdKey strTyLitName = libFun (fsLit "strTyLit") strTyLitIdKey -- data TyVarBndr = ... plainTVName, kindedTVName :: Name plainTVName = libFun (fsLit "plainTV") plainTVIdKey kindedTVName = libFun (fsLit "kindedTV") kindedTVIdKey -- data Role = ... nominalRName, representationalRName, phantomRName, inferRName :: Name nominalRName = libFun (fsLit "nominalR") nominalRIdKey representationalRName = libFun (fsLit "representationalR") representationalRIdKey phantomRName = libFun (fsLit "phantomR") phantomRIdKey inferRName = libFun (fsLit "inferR") inferRIdKey -- data Kind = ... varKName, conKName, tupleKName, arrowKName, listKName, appKName, starKName, constraintKName :: Name varKName = libFun (fsLit "varK") varKIdKey conKName = libFun (fsLit "conK") conKIdKey tupleKName = libFun (fsLit "tupleK") tupleKIdKey arrowKName = libFun (fsLit "arrowK") arrowKIdKey listKName = libFun (fsLit "listK") listKIdKey appKName = libFun (fsLit "appK") appKIdKey starKName = libFun (fsLit "starK") starKIdKey constraintKName = libFun (fsLit "constraintK") constraintKIdKey -- data Callconv = ... cCallName, stdCallName, cApiCallName, primCallName, javaScriptCallName :: Name cCallName = libFun (fsLit "cCall") cCallIdKey stdCallName = libFun (fsLit "stdCall") stdCallIdKey cApiCallName = libFun (fsLit "cApi") cApiCallIdKey primCallName = libFun (fsLit "prim") primCallIdKey javaScriptCallName = libFun (fsLit "javaScript") javaScriptCallIdKey -- data Safety = ... unsafeName, safeName, interruptibleName :: Name unsafeName = libFun (fsLit "unsafe") unsafeIdKey safeName = libFun (fsLit "safe") safeIdKey interruptibleName = libFun (fsLit "interruptible") interruptibleIdKey -- data Inline = ... noInlineDataConName, inlineDataConName, inlinableDataConName :: Name noInlineDataConName = thCon (fsLit "NoInline") noInlineDataConKey inlineDataConName = thCon (fsLit "Inline") inlineDataConKey inlinableDataConName = thCon (fsLit "Inlinable") inlinableDataConKey -- data RuleMatch = ... conLikeDataConName, funLikeDataConName :: Name conLikeDataConName = thCon (fsLit "ConLike") conLikeDataConKey funLikeDataConName = thCon (fsLit "FunLike") funLikeDataConKey -- data Phases = ... allPhasesDataConName, fromPhaseDataConName, beforePhaseDataConName :: Name allPhasesDataConName = thCon (fsLit "AllPhases") allPhasesDataConKey fromPhaseDataConName = thCon (fsLit "FromPhase") fromPhaseDataConKey beforePhaseDataConName = thCon (fsLit "BeforePhase") beforePhaseDataConKey -- newtype TExp a = ... tExpDataConName :: Name tExpDataConName = thCon (fsLit "TExp") tExpDataConKey -- data RuleBndr = ... ruleVarName, typedRuleVarName :: Name ruleVarName = libFun (fsLit ("ruleVar")) ruleVarIdKey typedRuleVarName = libFun (fsLit ("typedRuleVar")) typedRuleVarIdKey -- data FunDep = ... funDepName :: Name funDepName = libFun (fsLit "funDep") funDepIdKey -- data FamFlavour = ... typeFamName, dataFamName :: Name typeFamName = libFun (fsLit "typeFam") typeFamIdKey dataFamName = libFun (fsLit "dataFam") dataFamIdKey -- data TySynEqn = ... tySynEqnName :: Name tySynEqnName = libFun (fsLit "tySynEqn") tySynEqnIdKey -- data AnnTarget = ... valueAnnotationName, typeAnnotationName, moduleAnnotationName :: Name valueAnnotationName = libFun (fsLit "valueAnnotation") valueAnnotationIdKey typeAnnotationName = libFun (fsLit "typeAnnotation") typeAnnotationIdKey moduleAnnotationName = libFun (fsLit "moduleAnnotation") moduleAnnotationIdKey matchQTyConName, clauseQTyConName, expQTyConName, stmtQTyConName, decQTyConName, conQTyConName, strictTypeQTyConName, varStrictTypeQTyConName, typeQTyConName, fieldExpQTyConName, patQTyConName, fieldPatQTyConName, predQTyConName, decsQTyConName, ruleBndrQTyConName, tySynEqnQTyConName, roleTyConName :: Name matchQTyConName = libTc (fsLit "MatchQ") matchQTyConKey clauseQTyConName = libTc (fsLit "ClauseQ") clauseQTyConKey expQTyConName = libTc (fsLit "ExpQ") expQTyConKey stmtQTyConName = libTc (fsLit "StmtQ") stmtQTyConKey decQTyConName = libTc (fsLit "DecQ") decQTyConKey decsQTyConName = libTc (fsLit "DecsQ") decsQTyConKey -- Q [Dec] conQTyConName = libTc (fsLit "ConQ") conQTyConKey strictTypeQTyConName = libTc (fsLit "StrictTypeQ") strictTypeQTyConKey varStrictTypeQTyConName = libTc (fsLit "VarStrictTypeQ") varStrictTypeQTyConKey typeQTyConName = libTc (fsLit "TypeQ") typeQTyConKey fieldExpQTyConName = libTc (fsLit "FieldExpQ") fieldExpQTyConKey patQTyConName = libTc (fsLit "PatQ") patQTyConKey fieldPatQTyConName = libTc (fsLit "FieldPatQ") fieldPatQTyConKey predQTyConName = libTc (fsLit "PredQ") predQTyConKey ruleBndrQTyConName = libTc (fsLit "RuleBndrQ") ruleBndrQTyConKey tySynEqnQTyConName = libTc (fsLit "TySynEqnQ") tySynEqnQTyConKey roleTyConName = libTc (fsLit "Role") roleTyConKey -- quasiquoting quoteExpName, quotePatName, quoteDecName, quoteTypeName :: Name quoteExpName = qqFun (fsLit "quoteExp") quoteExpKey quotePatName = qqFun (fsLit "quotePat") quotePatKey quoteDecName = qqFun (fsLit "quoteDec") quoteDecKey quoteTypeName = qqFun (fsLit "quoteType") quoteTypeKey -- TyConUniques available: 200-299 -- Check in PrelNames if you want to change this expTyConKey, matchTyConKey, clauseTyConKey, qTyConKey, expQTyConKey, decQTyConKey, patTyConKey, matchQTyConKey, clauseQTyConKey, stmtQTyConKey, conQTyConKey, typeQTyConKey, typeTyConKey, tyVarBndrTyConKey, decTyConKey, varStrictTypeQTyConKey, strictTypeQTyConKey, fieldExpTyConKey, fieldPatTyConKey, nameTyConKey, patQTyConKey, fieldPatQTyConKey, fieldExpQTyConKey, funDepTyConKey, predTyConKey, predQTyConKey, decsQTyConKey, ruleBndrQTyConKey, tySynEqnQTyConKey, roleTyConKey, tExpTyConKey :: Unique expTyConKey = mkPreludeTyConUnique 200 matchTyConKey = mkPreludeTyConUnique 201 clauseTyConKey = mkPreludeTyConUnique 202 qTyConKey = mkPreludeTyConUnique 203 expQTyConKey = mkPreludeTyConUnique 204 decQTyConKey = mkPreludeTyConUnique 205 patTyConKey = mkPreludeTyConUnique 206 matchQTyConKey = mkPreludeTyConUnique 207 clauseQTyConKey = mkPreludeTyConUnique 208 stmtQTyConKey = mkPreludeTyConUnique 209 conQTyConKey = mkPreludeTyConUnique 210 typeQTyConKey = mkPreludeTyConUnique 211 typeTyConKey = mkPreludeTyConUnique 212 decTyConKey = mkPreludeTyConUnique 213 varStrictTypeQTyConKey = mkPreludeTyConUnique 214 strictTypeQTyConKey = mkPreludeTyConUnique 215 fieldExpTyConKey = mkPreludeTyConUnique 216 fieldPatTyConKey = mkPreludeTyConUnique 217 nameTyConKey = mkPreludeTyConUnique 218 patQTyConKey = mkPreludeTyConUnique 219 fieldPatQTyConKey = mkPreludeTyConUnique 220 fieldExpQTyConKey = mkPreludeTyConUnique 221 funDepTyConKey = mkPreludeTyConUnique 222 predTyConKey = mkPreludeTyConUnique 223 predQTyConKey = mkPreludeTyConUnique 224 tyVarBndrTyConKey = mkPreludeTyConUnique 225 decsQTyConKey = mkPreludeTyConUnique 226 ruleBndrQTyConKey = mkPreludeTyConUnique 227 tySynEqnQTyConKey = mkPreludeTyConUnique 228 roleTyConKey = mkPreludeTyConUnique 229 tExpTyConKey = mkPreludeTyConUnique 230 -- IdUniques available: 200-499 -- If you want to change this, make sure you check in PrelNames returnQIdKey, bindQIdKey, sequenceQIdKey, liftIdKey, newNameIdKey, mkNameIdKey, mkNameG_vIdKey, mkNameG_dIdKey, mkNameG_tcIdKey, mkNameLIdKey, unTypeIdKey, unTypeQIdKey, unsafeTExpCoerceIdKey :: Unique returnQIdKey = mkPreludeMiscIdUnique 200 bindQIdKey = mkPreludeMiscIdUnique 201 sequenceQIdKey = mkPreludeMiscIdUnique 202 liftIdKey = mkPreludeMiscIdUnique 203 newNameIdKey = mkPreludeMiscIdUnique 204 mkNameIdKey = mkPreludeMiscIdUnique 205 mkNameG_vIdKey = mkPreludeMiscIdUnique 206 mkNameG_dIdKey = mkPreludeMiscIdUnique 207 mkNameG_tcIdKey = mkPreludeMiscIdUnique 208 mkNameLIdKey = mkPreludeMiscIdUnique 209 unTypeIdKey = mkPreludeMiscIdUnique 210 unTypeQIdKey = mkPreludeMiscIdUnique 211 unsafeTExpCoerceIdKey = mkPreludeMiscIdUnique 212 -- data Lit = ... charLIdKey, stringLIdKey, integerLIdKey, intPrimLIdKey, wordPrimLIdKey, floatPrimLIdKey, doublePrimLIdKey, rationalLIdKey :: Unique charLIdKey = mkPreludeMiscIdUnique 220 stringLIdKey = mkPreludeMiscIdUnique 221 integerLIdKey = mkPreludeMiscIdUnique 222 intPrimLIdKey = mkPreludeMiscIdUnique 223 wordPrimLIdKey = mkPreludeMiscIdUnique 224 floatPrimLIdKey = mkPreludeMiscIdUnique 225 doublePrimLIdKey = mkPreludeMiscIdUnique 226 rationalLIdKey = mkPreludeMiscIdUnique 227 liftStringIdKey :: Unique liftStringIdKey = mkPreludeMiscIdUnique 228 -- data Pat = ... litPIdKey, varPIdKey, tupPIdKey, unboxedTupPIdKey, conPIdKey, infixPIdKey, tildePIdKey, bangPIdKey, asPIdKey, wildPIdKey, recPIdKey, listPIdKey, sigPIdKey, viewPIdKey :: Unique litPIdKey = mkPreludeMiscIdUnique 240 varPIdKey = mkPreludeMiscIdUnique 241 tupPIdKey = mkPreludeMiscIdUnique 242 unboxedTupPIdKey = mkPreludeMiscIdUnique 243 conPIdKey = mkPreludeMiscIdUnique 244 infixPIdKey = mkPreludeMiscIdUnique 245 tildePIdKey = mkPreludeMiscIdUnique 246 bangPIdKey = mkPreludeMiscIdUnique 247 asPIdKey = mkPreludeMiscIdUnique 248 wildPIdKey = mkPreludeMiscIdUnique 249 recPIdKey = mkPreludeMiscIdUnique 250 listPIdKey = mkPreludeMiscIdUnique 251 sigPIdKey = mkPreludeMiscIdUnique 252 viewPIdKey = mkPreludeMiscIdUnique 253 -- type FieldPat = ... fieldPatIdKey :: Unique fieldPatIdKey = mkPreludeMiscIdUnique 260 -- data Match = ... matchIdKey :: Unique matchIdKey = mkPreludeMiscIdUnique 261 -- data Clause = ... clauseIdKey :: Unique clauseIdKey = mkPreludeMiscIdUnique 262 -- data Exp = ... varEIdKey, conEIdKey, litEIdKey, appEIdKey, infixEIdKey, infixAppIdKey, sectionLIdKey, sectionRIdKey, lamEIdKey, lamCaseEIdKey, tupEIdKey, unboxedTupEIdKey, condEIdKey, multiIfEIdKey, letEIdKey, caseEIdKey, doEIdKey, compEIdKey, fromEIdKey, fromThenEIdKey, fromToEIdKey, fromThenToEIdKey, listEIdKey, sigEIdKey, recConEIdKey, recUpdEIdKey, staticEIdKey :: Unique varEIdKey = mkPreludeMiscIdUnique 270 conEIdKey = mkPreludeMiscIdUnique 271 litEIdKey = mkPreludeMiscIdUnique 272 appEIdKey = mkPreludeMiscIdUnique 273 infixEIdKey = mkPreludeMiscIdUnique 274 infixAppIdKey = mkPreludeMiscIdUnique 275 sectionLIdKey = mkPreludeMiscIdUnique 276 sectionRIdKey = mkPreludeMiscIdUnique 277 lamEIdKey = mkPreludeMiscIdUnique 278 lamCaseEIdKey = mkPreludeMiscIdUnique 279 tupEIdKey = mkPreludeMiscIdUnique 280 unboxedTupEIdKey = mkPreludeMiscIdUnique 281 condEIdKey = mkPreludeMiscIdUnique 282 multiIfEIdKey = mkPreludeMiscIdUnique 283 letEIdKey = mkPreludeMiscIdUnique 284 caseEIdKey = mkPreludeMiscIdUnique 285 doEIdKey = mkPreludeMiscIdUnique 286 compEIdKey = mkPreludeMiscIdUnique 287 fromEIdKey = mkPreludeMiscIdUnique 288 fromThenEIdKey = mkPreludeMiscIdUnique 289 fromToEIdKey = mkPreludeMiscIdUnique 290 fromThenToEIdKey = mkPreludeMiscIdUnique 291 listEIdKey = mkPreludeMiscIdUnique 292 sigEIdKey = mkPreludeMiscIdUnique 293 recConEIdKey = mkPreludeMiscIdUnique 294 recUpdEIdKey = mkPreludeMiscIdUnique 295 staticEIdKey = mkPreludeMiscIdUnique 296 -- type FieldExp = ... fieldExpIdKey :: Unique fieldExpIdKey = mkPreludeMiscIdUnique 310 -- data Body = ... guardedBIdKey, normalBIdKey :: Unique guardedBIdKey = mkPreludeMiscIdUnique 311 normalBIdKey = mkPreludeMiscIdUnique 312 -- data Guard = ... normalGEIdKey, patGEIdKey :: Unique normalGEIdKey = mkPreludeMiscIdUnique 313 patGEIdKey = mkPreludeMiscIdUnique 314 -- data Stmt = ... bindSIdKey, letSIdKey, noBindSIdKey, parSIdKey :: Unique bindSIdKey = mkPreludeMiscIdUnique 320 letSIdKey = mkPreludeMiscIdUnique 321 noBindSIdKey = mkPreludeMiscIdUnique 322 parSIdKey = mkPreludeMiscIdUnique 323 -- data Dec = ... funDIdKey, valDIdKey, dataDIdKey, newtypeDIdKey, tySynDIdKey, classDIdKey, instanceDIdKey, sigDIdKey, forImpDIdKey, pragInlDIdKey, pragSpecDIdKey, pragSpecInlDIdKey, pragSpecInstDIdKey, pragRuleDIdKey, pragAnnDIdKey, familyNoKindDIdKey, familyKindDIdKey, defaultSigDIdKey, dataInstDIdKey, newtypeInstDIdKey, tySynInstDIdKey, standaloneDerivDIdKey, closedTypeFamilyKindDIdKey, closedTypeFamilyNoKindDIdKey, infixLDIdKey, infixRDIdKey, infixNDIdKey, roleAnnotDIdKey :: Unique funDIdKey = mkPreludeMiscIdUnique 330 valDIdKey = mkPreludeMiscIdUnique 331 dataDIdKey = mkPreludeMiscIdUnique 332 newtypeDIdKey = mkPreludeMiscIdUnique 333 tySynDIdKey = mkPreludeMiscIdUnique 334 classDIdKey = mkPreludeMiscIdUnique 335 instanceDIdKey = mkPreludeMiscIdUnique 336 sigDIdKey = mkPreludeMiscIdUnique 337 forImpDIdKey = mkPreludeMiscIdUnique 338 pragInlDIdKey = mkPreludeMiscIdUnique 339 pragSpecDIdKey = mkPreludeMiscIdUnique 340 pragSpecInlDIdKey = mkPreludeMiscIdUnique 341 pragSpecInstDIdKey = mkPreludeMiscIdUnique 342 pragRuleDIdKey = mkPreludeMiscIdUnique 343 pragAnnDIdKey = mkPreludeMiscIdUnique 344 familyNoKindDIdKey = mkPreludeMiscIdUnique 345 familyKindDIdKey = mkPreludeMiscIdUnique 346 dataInstDIdKey = mkPreludeMiscIdUnique 347 newtypeInstDIdKey = mkPreludeMiscIdUnique 348 tySynInstDIdKey = mkPreludeMiscIdUnique 349 closedTypeFamilyKindDIdKey = mkPreludeMiscIdUnique 350 closedTypeFamilyNoKindDIdKey = mkPreludeMiscIdUnique 351 infixLDIdKey = mkPreludeMiscIdUnique 352 infixRDIdKey = mkPreludeMiscIdUnique 353 infixNDIdKey = mkPreludeMiscIdUnique 354 roleAnnotDIdKey = mkPreludeMiscIdUnique 355 standaloneDerivDIdKey = mkPreludeMiscIdUnique 356 defaultSigDIdKey = mkPreludeMiscIdUnique 357 -- type Cxt = ... cxtIdKey :: Unique cxtIdKey = mkPreludeMiscIdUnique 360 -- data Strict = ... isStrictKey, notStrictKey, unpackedKey :: Unique isStrictKey = mkPreludeMiscIdUnique 363 notStrictKey = mkPreludeMiscIdUnique 364 unpackedKey = mkPreludeMiscIdUnique 365 -- data Con = ... normalCIdKey, recCIdKey, infixCIdKey, forallCIdKey :: Unique normalCIdKey = mkPreludeMiscIdUnique 370 recCIdKey = mkPreludeMiscIdUnique 371 infixCIdKey = mkPreludeMiscIdUnique 372 forallCIdKey = mkPreludeMiscIdUnique 373 -- type StrictType = ... strictTKey :: Unique strictTKey = mkPreludeMiscIdUnique 374 -- type VarStrictType = ... varStrictTKey :: Unique varStrictTKey = mkPreludeMiscIdUnique 375 -- data Type = ... forallTIdKey, varTIdKey, conTIdKey, tupleTIdKey, unboxedTupleTIdKey, arrowTIdKey, listTIdKey, appTIdKey, sigTIdKey, equalityTIdKey, litTIdKey, promotedTIdKey, promotedTupleTIdKey, promotedNilTIdKey, promotedConsTIdKey :: Unique forallTIdKey = mkPreludeMiscIdUnique 380 varTIdKey = mkPreludeMiscIdUnique 381 conTIdKey = mkPreludeMiscIdUnique 382 tupleTIdKey = mkPreludeMiscIdUnique 383 unboxedTupleTIdKey = mkPreludeMiscIdUnique 384 arrowTIdKey = mkPreludeMiscIdUnique 385 listTIdKey = mkPreludeMiscIdUnique 386 appTIdKey = mkPreludeMiscIdUnique 387 sigTIdKey = mkPreludeMiscIdUnique 388 equalityTIdKey = mkPreludeMiscIdUnique 389 litTIdKey = mkPreludeMiscIdUnique 390 promotedTIdKey = mkPreludeMiscIdUnique 391 promotedTupleTIdKey = mkPreludeMiscIdUnique 392 promotedNilTIdKey = mkPreludeMiscIdUnique 393 promotedConsTIdKey = mkPreludeMiscIdUnique 394 -- data TyLit = ... numTyLitIdKey, strTyLitIdKey :: Unique numTyLitIdKey = mkPreludeMiscIdUnique 395 strTyLitIdKey = mkPreludeMiscIdUnique 396 -- data TyVarBndr = ... plainTVIdKey, kindedTVIdKey :: Unique plainTVIdKey = mkPreludeMiscIdUnique 397 kindedTVIdKey = mkPreludeMiscIdUnique 398 -- data Role = ... nominalRIdKey, representationalRIdKey, phantomRIdKey, inferRIdKey :: Unique nominalRIdKey = mkPreludeMiscIdUnique 400 representationalRIdKey = mkPreludeMiscIdUnique 401 phantomRIdKey = mkPreludeMiscIdUnique 402 inferRIdKey = mkPreludeMiscIdUnique 403 -- data Kind = ... varKIdKey, conKIdKey, tupleKIdKey, arrowKIdKey, listKIdKey, appKIdKey, starKIdKey, constraintKIdKey :: Unique varKIdKey = mkPreludeMiscIdUnique 404 conKIdKey = mkPreludeMiscIdUnique 405 tupleKIdKey = mkPreludeMiscIdUnique 406 arrowKIdKey = mkPreludeMiscIdUnique 407 listKIdKey = mkPreludeMiscIdUnique 408 appKIdKey = mkPreludeMiscIdUnique 409 starKIdKey = mkPreludeMiscIdUnique 410 constraintKIdKey = mkPreludeMiscIdUnique 411 -- data Callconv = ... cCallIdKey, stdCallIdKey, cApiCallIdKey, primCallIdKey, javaScriptCallIdKey :: Unique cCallIdKey = mkPreludeMiscIdUnique 420 stdCallIdKey = mkPreludeMiscIdUnique 421 cApiCallIdKey = mkPreludeMiscIdUnique 422 primCallIdKey = mkPreludeMiscIdUnique 423 javaScriptCallIdKey = mkPreludeMiscIdUnique 424 -- data Safety = ... unsafeIdKey, safeIdKey, interruptibleIdKey :: Unique unsafeIdKey = mkPreludeMiscIdUnique 430 safeIdKey = mkPreludeMiscIdUnique 431 interruptibleIdKey = mkPreludeMiscIdUnique 432 -- data Inline = ... noInlineDataConKey, inlineDataConKey, inlinableDataConKey :: Unique noInlineDataConKey = mkPreludeDataConUnique 40 inlineDataConKey = mkPreludeDataConUnique 41 inlinableDataConKey = mkPreludeDataConUnique 42 -- data RuleMatch = ... conLikeDataConKey, funLikeDataConKey :: Unique conLikeDataConKey = mkPreludeDataConUnique 43 funLikeDataConKey = mkPreludeDataConUnique 44 -- data Phases = ... allPhasesDataConKey, fromPhaseDataConKey, beforePhaseDataConKey :: Unique allPhasesDataConKey = mkPreludeDataConUnique 45 fromPhaseDataConKey = mkPreludeDataConUnique 46 beforePhaseDataConKey = mkPreludeDataConUnique 47 -- newtype TExp a = ... tExpDataConKey :: Unique tExpDataConKey = mkPreludeDataConUnique 48 -- data FunDep = ... funDepIdKey :: Unique funDepIdKey = mkPreludeMiscIdUnique 440 -- data FamFlavour = ... typeFamIdKey, dataFamIdKey :: Unique typeFamIdKey = mkPreludeMiscIdUnique 450 dataFamIdKey = mkPreludeMiscIdUnique 451 -- data TySynEqn = ... tySynEqnIdKey :: Unique tySynEqnIdKey = mkPreludeMiscIdUnique 460 -- quasiquoting quoteExpKey, quotePatKey, quoteDecKey, quoteTypeKey :: Unique quoteExpKey = mkPreludeMiscIdUnique 470 quotePatKey = mkPreludeMiscIdUnique 471 quoteDecKey = mkPreludeMiscIdUnique 472 quoteTypeKey = mkPreludeMiscIdUnique 473 -- data RuleBndr = ... ruleVarIdKey, typedRuleVarIdKey :: Unique ruleVarIdKey = mkPreludeMiscIdUnique 480 typedRuleVarIdKey = mkPreludeMiscIdUnique 481 -- data AnnTarget = ... valueAnnotationIdKey, typeAnnotationIdKey, moduleAnnotationIdKey :: Unique valueAnnotationIdKey = mkPreludeMiscIdUnique 490 typeAnnotationIdKey = mkPreludeMiscIdUnique 491 moduleAnnotationIdKey = mkPreludeMiscIdUnique 492
christiaanb/ghc
compiler/deSugar/DsMeta.hs
bsd-3-clause
120,720
2,211
26
32,636
25,865
15,130
10,735
2,023
16
{-# LANGUAGE OverloadedStrings #-} module Trombone.Tests.Bootstrap ( runTests ) where import Trombone.Db.Template import Trombone.RoutePattern runTests :: IO () runTests = print [ routePatternTest1 , routePatternTest2 , routePatternTest3 , routePatternTest4 , dbTemplateTest1 ] ------------------------------------------------------------------------------- -- Db.Template ------------------------------------------------------------------------------- dbTemplateTest1 = Right "select id from dispatch where id = \"5\"" == instantiate template [(":id", EscapedText "\"5\"")] where template = DbTemplate [ DbSqlStatic "select id from dispatch where id = " , DbSqlUriParam "id" ] ------------------------------------------------------------------------------- -- RoutePattern ------------------------------------------------------------------------------- routePatternTest1 = Params [("id", "5")] == match (decompose "/product/order/:id/") ["product", "order", "5"] routePatternTest2 = RoutePattern [Atom "a", Variable "b", Atom "c"] == decompose "/a/:b/c/" routePatternTest3 = Params [("name", "bob"), ("order", "11")] == match (decompose "/customer/:name/order/:order/show") ["customer", "bob", "order", "11", "show"] routePatternTest4 = NoMatch == match (decompose "/customer/:name/order/:order/show") ["customer", "bob", "order", "11"]
johanneshilden/trombone
Trombone/Tests/Bootstrap.hs
bsd-3-clause
1,641
0
9
429
276
157
119
26
1
module Instruction ( RegUsage(..), noUsage, NatCmm, NatCmmDecl, NatBasicBlock, Instruction(..) ) where import Reg import BlockId import OldCmm import Platform -- | Holds a list of source and destination registers used by a -- particular instruction. -- -- Machine registers that are pre-allocated to stgRegs are filtered -- out, because they are uninteresting from a register allocation -- standpoint. (We wouldn't want them to end up on the free list!) -- -- As far as we are concerned, the fixed registers simply don't exist -- (for allocation purposes, anyway). -- data RegUsage = RU [Reg] [Reg] -- | No regs read or written to. noUsage :: RegUsage noUsage = RU [] [] -- Our flavours of the Cmm types -- Type synonyms for Cmm populated with native code type NatCmm instr = GenCmmGroup CmmStatics (Maybe CmmStatics) (ListGraph instr) type NatCmmDecl statics instr = GenCmmDecl statics (Maybe CmmStatics) (ListGraph instr) type NatBasicBlock instr = GenBasicBlock instr -- | Common things that we can do with instructions, on all architectures. -- These are used by the shared parts of the native code generator, -- specifically the register allocators. -- class Instruction instr where -- | Get the registers that are being used by this instruction. -- regUsage doesn't need to do any trickery for jumps and such. -- Just state precisely the regs read and written by that insn. -- The consequences of control flow transfers, as far as register -- allocation goes, are taken care of by the register allocator. -- regUsageOfInstr :: instr -> RegUsage -- | Apply a given mapping to all the register references in this -- instruction. patchRegsOfInstr :: instr -> (Reg -> Reg) -> instr -- | Checks whether this instruction is a jump/branch instruction. -- One that can change the flow of control in a way that the -- register allocator needs to worry about. isJumpishInstr :: instr -> Bool -- | Give the possible destinations of this jump instruction. -- Must be defined for all jumpish instructions. jumpDestsOfInstr :: instr -> [BlockId] -- | Change the destination of this jump instruction. -- Used in the linear allocator when adding fixup blocks for join -- points. patchJumpInstr :: instr -> (BlockId -> BlockId) -> instr -- | An instruction to spill a register into a spill slot. mkSpillInstr :: Platform -> Reg -- ^ the reg to spill -> Int -- ^ the current stack delta -> Int -- ^ spill slot to use -> instr -- | An instruction to reload a register from a spill slot. mkLoadInstr :: Platform -> Reg -- ^ the reg to reload. -> Int -- ^ the current stack delta -> Int -- ^ the spill slot to use -> instr -- | See if this instruction is telling us the current C stack delta takeDeltaInstr :: instr -> Maybe Int -- | Check whether this instruction is some meta thing inserted into -- the instruction stream for other purposes. -- -- Not something that has to be treated as a real machine instruction -- and have its registers allocated. -- -- eg, comments, delta, ldata, etc. isMetaInstr :: instr -> Bool -- | Copy the value in a register to another one. -- Must work for all register classes. mkRegRegMoveInstr :: Platform -> Reg -- ^ source register -> Reg -- ^ destination register -> instr -- | Take the source and destination from this reg -> reg move instruction -- or Nothing if it's not one takeRegRegMoveInstr :: instr -> Maybe (Reg, Reg) -- | Make an unconditional jump instruction. -- For architectures with branch delay slots, its ok to put -- a NOP after the jump. Don't fill the delay slot with an -- instruction that references regs or you'll confuse the -- linear allocator. mkJumpInstr :: BlockId -> [instr]
mcmaniac/ghc
compiler/nativeGen/Instruction.hs
bsd-3-clause
4,938
0
10
1,945
392
247
145
72
1
module Genetic.Central ( evolve , Pool, popul , startup, handle , connect ) where -- $Id$ import Autolib.Util.Sort import Autolib.Util.Uniq import Autolib.Util.Perm import Autolib.Util.Zufall import Autolib.Util.Perm import Autolib.ToDoc import Control.Monad import Autolib.FiniteMap import Autolib.Set -- import Autolib.Genetic.Config import Genetic.Config import Data.Maybe import Data.IORef import Control.Concurrent import System.IO data Pool a v = Pool { num :: Int , popul :: [(v, a)] , previous :: v , config :: Config a v , input :: MVar a , outputs :: IORef [ MVar a ] } -- | output the best items after some steps of computation evolve :: (Ord v, ToDoc v, ToDoc a, Ord a) => Config a v -> IO [(v,a)] evolve conf = do pool <- startup conf pool' <- handle pool return $ popul pool' startup conf = do pool <- sequence $ replicate (size conf) (generate conf) v <- newEmptyMVar o <- newIORef [] return $ Pool { config = conf , num = 0 , previous = fitness conf $ head pool , popul = map ( \ g -> ( fitness conf g, g ) ) pool , input = v , outputs = o } handle vpool = do let conf = config vpool trace conf $ popul vpool let tops = filter ( \ (v, g) -> v > previous vpool ) $ popul vpool when ( not $ null tops ) $ present conf tops let good = filter ( \ (v, g) -> v >= threshold conf ) $ popul vpool let continue = case num_steps conf of Just bound -> num vpool < bound Nothing -> True if null good && continue then do vpool' <- step vpool handle vpool' else do return vpool connect :: Pool a v -> Pool a v -> IO ( ) connect p q = do modifyIORef ( outputs p ) ( input q : ) modifyIORef ( outputs q ) ( input p : ) step :: ( Ord a, Ord v, ToDoc v, ToDoc a ) => Pool a v -> IO (Pool a v) step vpool = do let conf = config vpool pool = map snd $ popul vpool malien <- tryTakeMVar $ input vpool let aliens = do x <- maybeToList malien return ( fitness conf x, x ) when ( not $ null aliens ) $ hPutStrLn stderr $ "got aliens " -- ++ show ( toDoc aliens ) -- generate some new ones (crossing) combis <- sequence $ replicate (num_combine conf) $ do [x, y] <- einige 2 pool z <- combine conf x y return (fitness conf z, z) -- mutations mutants <- sequence $ replicate (num_mutate conf) $ do x <- eins pool z <- mutate conf x return $ (fitness conf z, z) let vpool' = take (size conf) $ compact (num_compact conf) $ aliens ++ combis ++ mutants ++ popul vpool -- transport outs <- readIORef $ outputs vpool let ( _, top ) = head vpool' sequence $ do out <- outs return $ do hPutStrLn stderr $ "sending alien " ++ show ( length $ show $ toDoc top ) tryPutMVar out top return $ vpool { num = succ $ num vpool , popul = vpool' , previous = maximum $ map fst $ popul vpool } -- | keep at most fixed number per v class (and sort) compact :: (Ord v, Ord a) => Int -> [(v, a)] -> [(v, a)] compact d vas = reverse $ do let fm = addListToFM_C (++) emptyFM $ do (v, a) <- vas return (v, [a]) (i, (v, as)) <- zip [1..] $ fmToList fm a <- take d $ setToList $ mkSet as return (v, a) -- | entferne k zufΓ€llig gewΓ€hlte elemente remove :: Int -> [a] -> IO [a] remove k xs = do ys <- permIO xs return $ drop k ys update :: [a] -> (Int, a -> a) -> [a] update xs (i, f) = poke xs (i, f $ xs !! i) poke :: [a] -> (Int, a) -> [a] poke xs (i, y) = let (pre, _ : post) = splitAt i xs in pre ++ [y] ++ post pokes :: [a] -> [(Int, a)] -> [a] pokes = foldl poke
Erdwolf/autotool-bonn
src/Genetic/Central.hs
gpl-2.0
3,976
51
19
1,355
1,568
813
755
126
3
-- | This is a new set of XML combinators for Xtract, not standard, -- but based on the standard set in "Text.Xml.Haxml.Combinators". -- The main difference is that the Content Filter type becomes a -- Double Filter. A Double Filter always takes the whole document -- as an extra argument, so you can start to traverse it again from -- the root, when at any inner location within the document tree. -- -- The new combinator definitions are derived from the old ones. -- The same names have the equivalent meaning - use module qualification -- on imports to distinguish between CFilter and DFilter variations. module Text.XML.HaXml.Xtract.Combinators where import Text.XML.HaXml.Types import Text.XML.HaXml.Combinators (CFilter) import qualified Text.XML.HaXml.Combinators as C -- | double content filter - takes document root + local subtree. type DFilter i = Content i -> Content i -> [Content i] -- | lift an ordinary content filter to a double filter. local,global :: CFilter i -> DFilter i local f = \_xml sub-> f sub global f = \ xml _sub-> f xml -- | drop a double filter to an ordinary content filter. -- (permitting interior access to document root) dfilter :: DFilter i -> CFilter i dfilter f = \xml-> f xml xml -- | drop a double filter to an ordinary content filter. -- (Where interior access to the document root is not needed, the -- retaining pointer to the outer element can be pruned away. -- 'cfilter' is more space-efficient than 'dfilter' in this situation.) cfilter :: DFilter i -> CFilter i cfilter f = \xml -> f undefined xml --cfilter f = \xml-> flip f xml -- (case xml of -- CElem (Elem n as cs) i -> CElem (Elem n [] []) i -- _ -> xml) -- | lift a CFilter combinator to a DFilter combinator liftLocal, liftGlobal :: (CFilter i->CFilter i) -> (DFilter i->DFilter i) liftLocal ff = \df-> \xml sub-> (ff (df xml)) sub liftGlobal ff = \df-> \xml _sub-> (ff (df xml)) xml -- | lifted composition over double filters. o :: DFilter i -> DFilter i -> DFilter i g `o` f = \xml-> concatMap (g xml) . (f xml) -- | lifted choice. (|>|) :: (a->b->[c]) -> (a->b->[c]) -> (a->b->[c]) f |>| g = \xml sub-> let first = f xml sub in if null first then g xml sub else first -- | lifted union. union :: (a->b->[c]) -> (a->b->[c]) -> (a->b->[c]) union = lift (++) where lift f g h = \x y-> f (g x y) (h x y) -- | lifted predicates. with, without :: DFilter i -> DFilter i -> DFilter i f `with` g = \xml-> filter (not.null.g xml) . f xml f `without` g = \xml-> filter (null.g xml) . f xml -- | lifted unit and zero. keep, none :: DFilter i keep = \_xml sub-> [sub] -- local C.keep none = \_xml _sub-> [] -- local C.none children, elm, txt :: DFilter i children = local C.children elm = local C.elm txt = local C.txt applypred :: CFilter i -> DFilter i -> CFilter i applypred f p = \xml-> (const f `with` p) xml xml iffind :: String -> (String -> DFilter i) -> DFilter i -> DFilter i iffind key yes no xml c@(CElem (Elem _ as _) _) = case (lookup (N key) as) of Nothing -> no xml c (Just v@(AttValue _)) -> yes (show v) xml c iffind _key _yes no xml other = no xml other ifTxt :: (String->DFilter i) -> DFilter i -> DFilter i ifTxt yes _no xml c@(CString _ s _) = yes s xml c ifTxt _yes no xml c = no xml c cat :: [a->b->[c]] -> (a->b->[c]) cat fs = \xml sub-> concat [ f xml sub | f <- fs ] (/>) :: DFilter i -> DFilter i -> DFilter i f /> g = g `o` children `o` f (</) :: DFilter i -> DFilter i -> DFilter i f </ g = f `with` (g `o` children) deep, deepest, multi :: DFilter i -> DFilter i deep f = f |>| (deep f `o` children) deepest f = (deepest f `o` children) |>| f multi f = f `union` (multi f `o` children)
Ian-Stewart-Binks/courseography
dependencies/HaXml-1.25.3/src/Text/XML/HaXml/Xtract/Combinators.hs
gpl-3.0
3,829
0
12
924
1,324
710
614
54
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.RDS.AddSourceIdentifierToSubscription -- 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. -- | Adds a source identifier to an existing RDS event notification subscription. -- -- <http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_AddSourceIdentifierToSubscription.html> module Network.AWS.RDS.AddSourceIdentifierToSubscription ( -- * Request AddSourceIdentifierToSubscription -- ** Request constructor , addSourceIdentifierToSubscription -- ** Request lenses , asitsSourceIdentifier , asitsSubscriptionName -- * Response , AddSourceIdentifierToSubscriptionResponse -- ** Response constructor , addSourceIdentifierToSubscriptionResponse -- ** Response lenses , asitsrEventSubscription ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.RDS.Types import qualified GHC.Exts data AddSourceIdentifierToSubscription = AddSourceIdentifierToSubscription { _asitsSourceIdentifier :: Text , _asitsSubscriptionName :: Text } deriving (Eq, Ord, Read, Show) -- | 'AddSourceIdentifierToSubscription' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'asitsSourceIdentifier' @::@ 'Text' -- -- * 'asitsSubscriptionName' @::@ 'Text' -- addSourceIdentifierToSubscription :: Text -- ^ 'asitsSubscriptionName' -> Text -- ^ 'asitsSourceIdentifier' -> AddSourceIdentifierToSubscription addSourceIdentifierToSubscription p1 p2 = AddSourceIdentifierToSubscription { _asitsSubscriptionName = p1 , _asitsSourceIdentifier = p2 } -- | The identifier of the event source to be added. An identifier must begin -- with a letter and must contain only ASCII letters, digits, and hyphens; it -- cannot end with a hyphen or contain two consecutive hyphens. -- -- Constraints: -- -- If the source type is a DB instance, then a 'DBInstanceIdentifier' must be -- supplied. If the source type is a DB security group, a 'DBSecurityGroupName' -- must be supplied. If the source type is a DB parameter group, a 'DBParameterGroupName' must be supplied. If the source type is a DB snapshot, a 'DBSnapshotIdentifier' -- must be supplied. asitsSourceIdentifier :: Lens' AddSourceIdentifierToSubscription Text asitsSourceIdentifier = lens _asitsSourceIdentifier (\s a -> s { _asitsSourceIdentifier = a }) -- | The name of the RDS event notification subscription you want to add a source -- identifier to. asitsSubscriptionName :: Lens' AddSourceIdentifierToSubscription Text asitsSubscriptionName = lens _asitsSubscriptionName (\s a -> s { _asitsSubscriptionName = a }) newtype AddSourceIdentifierToSubscriptionResponse = AddSourceIdentifierToSubscriptionResponse { _asitsrEventSubscription :: Maybe EventSubscription } deriving (Eq, Read, Show) -- | 'AddSourceIdentifierToSubscriptionResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'asitsrEventSubscription' @::@ 'Maybe' 'EventSubscription' -- addSourceIdentifierToSubscriptionResponse :: AddSourceIdentifierToSubscriptionResponse addSourceIdentifierToSubscriptionResponse = AddSourceIdentifierToSubscriptionResponse { _asitsrEventSubscription = Nothing } asitsrEventSubscription :: Lens' AddSourceIdentifierToSubscriptionResponse (Maybe EventSubscription) asitsrEventSubscription = lens _asitsrEventSubscription (\s a -> s { _asitsrEventSubscription = a }) instance ToPath AddSourceIdentifierToSubscription where toPath = const "/" instance ToQuery AddSourceIdentifierToSubscription where toQuery AddSourceIdentifierToSubscription{..} = mconcat [ "SourceIdentifier" =? _asitsSourceIdentifier , "SubscriptionName" =? _asitsSubscriptionName ] instance ToHeaders AddSourceIdentifierToSubscription instance AWSRequest AddSourceIdentifierToSubscription where type Sv AddSourceIdentifierToSubscription = RDS type Rs AddSourceIdentifierToSubscription = AddSourceIdentifierToSubscriptionResponse request = post "AddSourceIdentifierToSubscription" response = xmlResponse instance FromXML AddSourceIdentifierToSubscriptionResponse where parseXML = withElement "AddSourceIdentifierToSubscriptionResult" $ \x -> AddSourceIdentifierToSubscriptionResponse <$> x .@? "EventSubscription"
romanb/amazonka
amazonka-rds/gen/Network/AWS/RDS/AddSourceIdentifierToSubscription.hs
mpl-2.0
5,319
0
9
968
495
305
190
63
1
----------------------------------------------------------------------------- -- -- Code generation for coverage -- -- (c) Galois Connections, Inc. 2006 -- ----------------------------------------------------------------------------- module StgCmmHpc ( initHpc, mkTickBox ) where import StgCmmMonad import MkGraph import CmmExpr import CLabel import Module import CmmUtils import StgCmmUtils import HscTypes import StaticFlags mkTickBox :: Module -> Int -> CmmAGraph mkTickBox mod n = mkStore tick_box (CmmMachOp (MO_Add W64) [ CmmLoad tick_box b64 , CmmLit (CmmInt 1 W64) ]) where tick_box = cmmIndex W64 (CmmLit $ CmmLabel $ mkHpcTicksLabel $ mod) n initHpc :: Module -> HpcInfo -> FCode () -- Emit top-level tables for HPC and return code to initialise initHpc _ (NoHpcInfo {}) = return () initHpc this_mod (HpcInfo tickCount _hashNo) = whenC opt_Hpc $ do { emitDataLits (mkHpcTicksLabel this_mod) [ (CmmInt 0 W64) | _ <- take tickCount [0::Int ..] ] }
mcmaniac/ghc
compiler/codeGen/StgCmmHpc.hs
bsd-3-clause
1,199
0
13
376
252
138
114
26
1
module Main where import BasePrelude hiding (assert, isRight, isLeft) import MTLPrelude import Control.Monad.Trans.Either import Data.Either.Combinators import Test.Hspec import Test.QuickCheck import Test.QuickCheck.Instances import Data.Time import qualified Data.Text import qualified Data.Text.Lazy import qualified Data.ByteString import qualified Data.ByteString.Lazy import qualified ListT import qualified Hasql.Backend as Backend import qualified Hasql as H import qualified Hasql.Postgres as HP import qualified Data.Scientific as Scientific import qualified Data.Vector as Vector import qualified PostgreSQLBinary.Encoder as PBE import qualified Data.Aeson as J type Text = Data.Text.Text type LazyText = Data.Text.Lazy.Text type ByteString = Data.ByteString.ByteString type LazyByteString = Data.ByteString.Lazy.ByteString type Scientific = Scientific.Scientific main = do version <- fmap (fst . last . readP_to_S parseVersion . Data.Text.unpack) $ fmap (runIdentity . either (error . show) id) $ session1 $ H.tx Nothing $ H.singleEx [H.stmt| SHOW server_version |] hspec $ do describe "Feature" $ do it "wrongPort" $ do let backendSettings = HP.ParamSettings "localhost" 1 "postgres" "" "postgres" poolSettings = fromJust $ H.poolSettings 6 30 in do r <- session backendSettings poolSettings $ do H.tx Nothing $ H.unitEx [H.stmt|DROP TABLE IF EXISTS a|] shouldSatisfy r $ \case Left (H.CxError _) -> True _ -> False it "sameStatementUsedOnDifferentTypes" $ do flip shouldSatisfy isRight =<< do session1 $ do liftIO . (flip shouldBe) (Just (Identity ("abc" :: Text))) =<< do H.tx Nothing $ H.maybeEx $ [H.stmt|SELECT ?|] ("abc" :: Text) liftIO . (flip shouldBe) (Just (Identity True)) =<< do H.tx Nothing $ H.maybeEx $ [H.stmt|SELECT ?|] True it "rendering" $ do let rows = [("A", 34525), ("B", 324987)] :: [(Text, Int)] (flip shouldBe) (Right $ Just $ head rows) =<< do session1 $ do H.tx Nothing $ do H.unitEx [H.stmt|DROP TABLE IF EXISTS a|] H.unitEx [H.stmt|CREATE TABLE a (id SERIAL NOT NULL, name VARCHAR NOT NULL, birthday INT8, PRIMARY KEY (id))|] forM_ rows $ \(name, birthday) -> do H.unitEx $ [H.stmt|INSERT INTO a (name, birthday) VALUES (?, ?)|] name birthday H.tx Nothing $ do H.maybeEx $ [H.stmt|SELECT name, birthday FROM a WHERE id = ? |] (1 :: Int) it "countEffects" $ do (flip shouldBe) (Right 100) =<< do session1 $ do H.tx Nothing $ do H.unitEx [H.stmt|DROP TABLE IF EXISTS a|] H.unitEx [H.stmt|CREATE TABLE a (id SERIAL NOT NULL, name VARCHAR NOT NULL)|] replicateM_ 100 $ do H.unitEx [H.stmt|INSERT INTO a (name) VALUES ('a')|] H.countEx [H.stmt|DELETE FROM a|] it "autoIncrement" $ do (flip shouldBe) (Right (Just (1 :: Word64), Just (2 :: Word64))) =<< do session1 $ H.tx Nothing $ do H.unitEx [H.stmt|DROP TABLE IF EXISTS a|] H.unitEx [H.stmt|CREATE TABLE a (id SERIAL NOT NULL, v INT8, PRIMARY KEY (id))|] id1 <- (fmap . fmap) runIdentity $ H.maybeEx $ [H.stmt|INSERT INTO a (v) VALUES (1) RETURNING id|] id2 <- (fmap . fmap) runIdentity $ H.maybeEx $ [H.stmt|INSERT INTO a (v) VALUES (2) RETURNING id|] return (id1, id2) it "cursorResultsOrder" $ do flip shouldSatisfy (\case Right r -> (sort r :: [Word]) == r; _ -> False) =<< do session1 $ do H.tx (Just (H.ReadCommitted, Nothing)) $ do ListT.toList . fmap runIdentity =<< do H.streamEx 256 $ [H.stmt|select oid from pg_type ORDER BY oid|] it "cursor" $ do flip shouldSatisfy isRight =<< do session1 $ do r :: [(Word, Text)] <- H.tx (Just (H.ReadCommitted, Nothing)) $ do ListT.toList =<< do H.streamEx 256 $ [H.stmt|select oid, typname from pg_type|] r' :: [(Word, Text)] <- H.tx (Just (H.ReadCommitted, Nothing)) $ do fmap toList $ H.vectorEx $ [H.stmt|select oid, typname from pg_type|] liftIO $ (flip shouldBe) r' r it "select" $ do (flip shouldSatisfy) (either (const False) (not . null)) =<< do session1 $ do fmap toList $ H.tx Nothing $ H.vectorEx $ [H.stmt|select oid, typname from pg_type|] :: Session [(Word, Text)] describe "Mapping of" $ do when (version >= Version [9,2] []) $ describe "JSON" $ do it "encodes and decodes" $ do let v = (1, 'a') :: (Int, Char) json = J.toJSON v in flip shouldBe (Right (Identity json)) =<< do session1 $ H.tx Nothing $ H.singleEx [H.stmt| SELECT ($json :: json) |] describe "Enum" $ do it "casts text" $ do flip shouldSatisfy isRight =<< do session1 $ do H.tx Nothing $ do H.unitEx [H.stmt| DROP TYPE IF EXISTS mood |] H.unitEx [H.stmt| CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy') |] liftIO . (flip shouldBe) (Just (Identity ("ok" :: Text))) =<< do H.tx Nothing $ H.maybeEx $ [H.stmt|SELECT (? :: mood)|] ("ok" :: Text) describe "Unknown" $ do it "encodes to enum" $ do flip shouldSatisfy isRight =<< do session1 $ do H.tx Nothing $ do H.unitEx [H.stmt| DROP TABLE IF EXISTS a |] H.unitEx [H.stmt| DROP TYPE IF EXISTS mood |] H.unitEx [H.stmt| CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy') |] H.unitEx [H.stmt| CREATE TABLE a (id SERIAL NOT NULL, mood mood NOT NULL, PRIMARY KEY (id)) |] H.unitEx $ [H.stmt| INSERT INTO a (mood) VALUES (?) |] (HP.Unknown "ok") H.unitEx $ [H.stmt| INSERT INTO a (mood) VALUES (?) |] (HP.Unknown "ok") H.unitEx $ [H.stmt| INSERT INTO a (mood) VALUES (?) |] (HP.Unknown "happy") liftIO . (flip shouldBe) ([1, 2] :: [Int]) . fmap runIdentity =<< do H.tx Nothing $ fmap toList $ H.vectorEx $ [H.stmt|SELECT id FROM a WHERE mood = ?|] (HP.Unknown "ok") it "encodes Int64 into \"int8\" using a \"postgresql-binary\" encoder" $ do flip shouldSatisfy isRight =<< do session1 $ H.tx Nothing $ H.unitEx $ [H.stmt| SELECT (? :: int8) |] (HP.Unknown . PBE.int8 . Left $ 12345) it "does not encode Int64 into \"int4\" using a \"postgresql-binary\" encoder" $ do flip shouldSatisfy (\case Left (H.TxError _) -> True; _ -> False) =<< do session1 $ H.tx Nothing $ H.unitEx $ [H.stmt| SELECT (? :: int4)|] (HP.Unknown . PBE.int8 . Left $ 12345) it "encodes Int64 into \"int8\" using a \"postgresql-binary\" encoder" $ do flip shouldSatisfy isRight =<< do session1 $ H.tx Nothing $ H.unitEx $ [H.stmt| SELECT (? :: int8) |] (HP.Unknown . PBE.int8 . Left $ 12345) it "encodes Day into \"date\" using a \"postgresql-binary\" encoder" $ do flip shouldSatisfy isRight =<< do session1 $ H.tx Nothing $ H.unitEx $ [H.stmt| SELECT (? :: date) |] (HP.Unknown . PBE.date $ (read "1900-01-01" :: Day)) describe "Maybe" $ do it "" $ do flip shouldSatisfy isRight =<< do session1 $ do validMappingSession (Just '!') validMappingSession (Nothing :: Maybe Bool) describe "List" $ do it "1" $ do let v1 = [v2, v2] v2 = [Just 'a', Nothing, Just 'b'] flip shouldSatisfy isRight =<< do session1 $ do validMappingSession v1 validMappingSession v2 it "2" $ do let v1 = [v2, v2] v2 = [Just (1 :: Int), Just 2, Nothing] flip shouldSatisfy isRight =<< do session1 $ do validMappingSession v1 validMappingSession v2 it "3" $ do flip shouldSatisfy isRight =<< do session1 $ do validMappingSession [" 'a' \"b\" \\c\\ " :: Text] it "4" $ do let v1 = [ [Just 'a', Just 'b'], [Nothing, Just 'c'] ] (flip shouldBe) (Right (Just (Identity v1))) =<< do session1 $ H.tx Nothing $ do H.unitEx $ [H.stmt|DROP TABLE IF EXISTS a|] H.unitEx $ [H.stmt|CREATE TABLE a ("v" char[][])|] H.unitEx $ [H.stmt|INSERT INTO a (v) VALUES (?)|] v1 H.maybeEx $ [H.stmt|SELECT v FROM a|] it "5" $ do flip shouldSatisfy isRight =<< do session1 $ do validMappingSession [" 'a' \"b\" \\c\\ Ρ„" :: ByteString] it "ByteString" $ property $ \(x :: [ByteString]) -> mappingProp x it "LazyByteString" $ property $ \(x :: [LazyByteString]) -> mappingProp x it "LazyText" $ property $ \(v :: LazyText) -> (isNothing $ Data.Text.Lazy.find (== '\NUL') v) ==> mappingProp v it "LazyByteString" $ property $ \(v :: LazyByteString) -> mappingProp v -- * Helpers ------------------------- -- ** Generators ------------------------- scientificGen :: Gen Scientific scientificGen = Scientific.scientific <$> arbitrary <*> arbitrary microsTimeOfDayGen :: Gen TimeOfDay microsTimeOfDayGen = timeToTimeOfDay <$> microsDiffTimeGen microsLocalTimeGen :: Gen LocalTime microsLocalTimeGen = LocalTime <$> arbitrary <*> microsTimeOfDayGen microsDiffTimeGen :: Gen DiffTime microsDiffTimeGen = do fmap picosecondsToDiffTime $ fmap (* (10^6)) $ choose (0, (10^6)*24*60*60) -- ** Session ------------------------- type Session = H.Session HP.Postgres IO selectSelf :: Backend.CxValue HP.Postgres a => a -> Session (Maybe a) selectSelf v = H.tx Nothing $ (fmap . fmap) runIdentity $ H.maybeEx $ [H.stmt| SELECT ? |] v session1 :: Session r -> IO (Either (H.SessionError HP.Postgres) r) session1 = session backendSettings poolSettings where backendSettings = HP.ParamSettings "localhost" 5432 "postgres" "" "postgres" poolSettings = fromJust $ H.poolSettings 6 30 session :: HP.Settings -> H.PoolSettings -> Session r -> IO (Either (H.SessionError HP.Postgres) r) session s1 s2 m = do p <- H.acquirePool s1 s2 r <- H.session p m H.releasePool p return r validMappingSession :: Backend.CxValue HP.Postgres a => Typeable a => Show a => Eq a => a -> Session () validMappingSession v = selectSelf v >>= liftIO . (flip shouldBe) (Just v) -- ** Property ------------------------- floatEqProp :: RealFrac a => Show a => a -> a -> Property floatEqProp a b = counterexample (show a ++ " /~ " ++ show b) $ a + error >= b && a - error <= b where error = max (abs a) 1 / 100 mappingProp :: (Show a, Eq a, Backend.CxValue HP.Postgres a) => a -> Property mappingProp v = Right (Just v) === do unsafePerformIO $ session1 $ selectSelf v
mikeplus64/hasql-postgres
hspec/Main.hs
mit
11,799
7
48
3,908
3,677
1,847
1,830
-1
-1
{- | Module : $Header$ Description : Central GUI for Hets, with display of development graph Copyright : (c) Jorina Freya Gerken, Till Mossakowski, Uni Bremen 2002-2006 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : non-portable (imports Logic) Conversion of development graphs from Logic.DevGraph to abstract graphs of the graph display interface A composition table is used when abstracting the graph and composing multiple edges. It looks like this @ [(\"normal\",\"normal\",\"normal\"), (\"normal\",\"inclusion\",\"normal\"), (\"inclusion\",\"normal\",\"normal\"), (\"inclusion\",\"inclusion\",\"inclusion\")] @ A ginfo can be created with initgraphs. The graph is then created with addnode and addlink. -} module GUI.GraphDisplay (convertGraph, initializeConverter) where import Static.DevGraph import GUI.GraphMenu import GUI.GraphTypes import GUI.GraphLogic (updateGraph) import GUI.GraphAbstraction import qualified GUI.HTkUtils as HTk import Data.IORef import qualified Data.Map as Map (lookup) import Control.Monad import Interfaces.DataTypes initializeConverter :: IO (GInfo, HTk.HTk) initializeConverter = do wishInst <- HTk.initHTk [HTk.withdrawMainWin] gInfo <- emptyGInfo return (gInfo, wishInst) {- | converts the development graph given by its libname into an abstract graph and returns the descriptor of the latter, the graphInfo it is contained in and the conversion maps. -} convertGraph :: ConvFunc convertGraph gInfo title showLib = do let ln = libName gInfo ost <- readIORef $ intState gInfo case i_state ost of Nothing -> error "Something went wrong, no library loaded" Just ist -> do let libEnv = i_libEnv ist case Map.lookup ln libEnv of Just dgraph -> do initializeGraph gInfo title showLib unless (isEmptyDG dgraph) $ updateGraph gInfo (convert dgraph) Nothing -> error $ "development graph with libname " ++ show ln ++ " does not exist" {- | initializes an empty abstract graph with the needed node and edge types, return type equals the one of convertGraph -} initializeGraph :: GInfo -> String -> LibFunc -> IO () initializeGraph gInfo title showLib = do ost <- readIORef $ intState gInfo case i_state ost of Nothing -> return () Just _ -> do let title' = title ++ " for " ++ show (libName gInfo) createGraph gInfo title' convertGraph showLib
keithodulaigh/Hets
GUI/GraphDisplay.hs
gpl-2.0
2,497
0
20
481
420
209
211
39
3
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} {-# OPTIONS_HADDOCK show-extensions #-} -- | -- Module : Yi.Keymap.Emacs.Utils -- License : GPL-2 -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- This module is aimed at being a helper for the Emacs keybindings. -- In particular this should be useful for anyone that has a custom -- keymap derived from or based on the Emacs one. module Yi.Keymap.Emacs.Utils ( UnivArgument , argToInt , askQuitEditor , askSaveEditor , modifiedQuitEditor , withMinibuffer , queryReplaceE , isearchKeymap , cabalConfigureE , cabalBuildE , reloadProjectE , executeExtendedCommandE , evalRegionE , readUniversalArg , scrollDownE , scrollUpE , switchBufferE , killBufferE , insertNextC , findFile , findFileReadOnly , findFileNewTab , promptFile , promptTag , justOneSep , joinLinesE , countWordsRegion ) where import Control.Applicative (Alternative ((<|>), many, some), Applicative (pure), optional, (<$>)) import Control.Lens (use, (.=)) import Control.Monad (filterM, replicateM_, void) import Control.Monad.Base () import Data.List ((\\)) import Data.Maybe (fromMaybe) import Data.Monoid ((<>)) import qualified Data.Text as T (Text, concat, null, pack, singleton, snoc, unpack, unwords) import System.FilePath (takeDirectory, takeFileName, (</>)) import System.FriendlyPath () import Yi.Buffer import Yi.Command (cabalBuildE, cabalConfigureE, reloadProjectE) import Yi.Core (quitEditor) import Yi.Editor import Yi.Eval (execEditorAction, getAllNamesInScope) import Yi.File (deservesSave, editFile, fwriteBufferE, openingNewFile) import Yi.Keymap (Keymap, KeymapM, YiM, write) import Yi.Keymap.Keys import Yi.MiniBuffer import Yi.Misc (promptFile) import Yi.Monad (gets) import Yi.Rectangle (getRectangle) import Yi.Regex (makeSearchOptsM) import qualified Yi.Rope as R (countNewLines, fromText, length, replicateChar, toText, words) import Yi.Search import Yi.String (showT) import Yi.Tag import Yi.Utils (io) type UnivArgument = Maybe Int ---------------------------- -- | Quits the editor if there are no unmodified buffers -- if there are unmodified buffers then we ask individually for -- each modified buffer whether or not the user wishes to save -- it or not. If we get to the end of this list and there are still -- some modified buffers then we ask again if the user wishes to -- quit, but this is then a simple yes or no. askQuitEditor :: YiM () askQuitEditor = askIndividualSave True =<< getModifiedBuffers askSaveEditor :: YiM () askSaveEditor = askIndividualSave False =<< getModifiedBuffers getModifiedBuffers :: YiM [FBuffer] getModifiedBuffers = filterM deservesSave =<< gets bufferSet -------------------------------------------------- -- Takes in a list of buffers which have been identified -- as modified since their last save. askIndividualSave :: Bool -> [FBuffer] -> YiM () askIndividualSave True [] = modifiedQuitEditor askIndividualSave False [] = return () askIndividualSave hasQuit allBuffers@(firstBuffer : others) = void (withEditor (spawnMinibufferE saveMessage (const askKeymap))) where saveMessage = T.concat [ "do you want to save the buffer: " , bufferName , "? (y/n/", if hasQuit then "q/" else "", "c/!)" ] bufferName = identString firstBuffer askKeymap = choice ([ char 'n' ?>>! noAction , char 'y' ?>>! yesAction , char '!' ?>>! allAction , oneOf [char 'c', ctrl $ char 'g'] >>! closeBufferAndWindowE -- cancel ] ++ [char 'q' ?>>! quitEditor | hasQuit]) yesAction = do void $ fwriteBufferE (bkey firstBuffer) withEditor closeBufferAndWindowE continue noAction = do withEditor closeBufferAndWindowE continue allAction = do mapM_ fwriteBufferE $ fmap bkey allBuffers withEditor closeBufferAndWindowE askIndividualSave hasQuit [] continue = askIndividualSave hasQuit others --------------------------- --------------------------- -- | Quits the editor if there are no unmodified buffers -- if there are then simply confirms with the user that they -- with to quit. modifiedQuitEditor :: YiM () modifiedQuitEditor = do modifiedBuffers <- getModifiedBuffers if null modifiedBuffers then quitEditor else withEditor $ void (spawnMinibufferE modifiedMessage (const askKeymap)) where modifiedMessage = "Modified buffers exist really quit? (y/n)" askKeymap = choice [ char 'n' ?>>! noAction , char 'y' ?>>! quitEditor ] noAction = closeBufferAndWindowE ----------------------------- -- isearch selfSearchKeymap :: Keymap selfSearchKeymap = do Event (KASCII c) [] <- anyEvent write . isearchAddE $ T.singleton c searchKeymap :: Keymap searchKeymap = selfSearchKeymap <|> choice [ -- ("C-g", isearchDelE) -- Only if string is not empty. ctrl (char 'r') ?>>! isearchPrevE , ctrl (char 's') ?>>! isearchNextE , ctrl (char 'w') ?>>! isearchWordE , meta (char 'p') ?>>! isearchHistory 1 , meta (char 'n') ?>>! isearchHistory (-1) , spec KBS ?>>! isearchDelE ] isearchKeymap :: Direction -> Keymap isearchKeymap dir = do write $ isearchInitE dir void $ many searchKeymap choice [ ctrl (char 'g') ?>>! isearchCancelE , oneOf [ctrl (char 'm'), spec KEnter] >>! isearchFinishWithE resetRegexE ] <|| write isearchFinishE ---------------------------- -- query-replace queryReplaceE :: YiM () queryReplaceE = withMinibufferFree "Replace:" $ \replaceWhat -> withMinibufferFree "With:" $ \replaceWith -> do b <- gets currentBuffer win <- use currentWindowA let repStr = R.fromText replaceWith replaceKm = choice [ char 'n' ?>>! qrNext win b re , char '!' ?>>! qrReplaceAll win b re repStr , oneOf [char 'y', char ' '] >>! qrReplaceOne win b re repStr , oneOf [char 'q', ctrl (char 'g')] >>! qrFinish ] -- TODO: Yi.Regex to Text Right re = makeSearchOptsM [] (T.unpack replaceWhat) question = T.unwords [ "Replacing", replaceWhat , "with", replaceWith, " (y,n,q,!):" ] withEditor $ do setRegexE re void $ spawnMinibufferE question (const replaceKm) qrNext win b re executeExtendedCommandE :: YiM () executeExtendedCommandE = withMinibuffer "M-x" scope act where act = execEditorAction . T.unpack scope = const $ map T.pack <$> getAllNamesInScope evalRegionE :: YiM () evalRegionE = do -- FIXME: do something sensible. void $ withCurrentBuffer (getSelectRegionB >>= readRegionB) return () -- * Code for various commands -- This ideally should be put in their own module, -- without a prefix, so M-x ... would be easily implemented -- by looking up that module's contents -- | Insert next character, "raw" insertNextC :: UnivArgument -> KeymapM () insertNextC a = do c <- anyEvent write $ replicateM_ (argToInt a) $ insertB (eventToChar c) -- | Convert the universal argument to a number of repetitions argToInt :: UnivArgument -> Int argToInt = fromMaybe 1 digit :: (Event -> Event) -> KeymapM Char digit f = charOf f '0' '9' -- TODO: replace tt by digit meta tt :: KeymapM Char tt = do Event (KASCII c) _ <- foldr1 (<|>) $ fmap (event . metaCh ) ['0'..'9'] return c -- doing the argument precisely is kind of tedious. -- read: http://www.gnu.org/software/emacs/manual/html_node/Arguments.html -- and: http://www.gnu.org/software/emacs/elisp-manual/html_node/elisp_318.html readUniversalArg :: KeymapM (Maybe Int) readUniversalArg = optional ((ctrlCh 'u' ?>> (read <$> some (digit id) <|> pure 4)) <|> (read <$> some tt)) -- | Finds file and runs specified action on the resulting buffer findFileAndDo :: T.Text -- ^ Prompt -> BufferM a -- ^ Action to run on the resulting buffer -> YiM () findFileAndDo prompt act = promptFile prompt $ \filename -> do printMsg $ "loading " <> filename openingNewFile (T.unpack filename) act -- | Open a file using the minibuffer. We have to set up some stuff to -- allow hints and auto-completion. findFile :: YiM () findFile = findFileAndDo "find file:" $ return () -- | Like 'findFile' but sets the resulting buffer to read-only. findFileReadOnly :: YiM () findFileReadOnly = findFileAndDo "find file (read only):" $ readOnlyA .= True -- | Open a file in a new tab using the minibuffer. findFileNewTab :: YiM () findFileNewTab = promptFile "find file (new tab): " $ \filename -> do withEditor newTabE printMsg $ "loading " <> filename void . editFile $ T.unpack filename scrollDownE :: UnivArgument -> BufferM () scrollDownE a = case a of Nothing -> downScreenB Just n -> scrollB n scrollUpE :: UnivArgument -> BufferM () scrollUpE a = case a of Nothing -> upScreenB Just n -> scrollB (negate n) -- | Prompts the user for a buffer name and switches to the chosen buffer. switchBufferE :: YiM () switchBufferE = promptingForBuffer "switch to buffer:" (withEditor . switchToBufferE) (\o b -> (b \\ o) ++ o) -- | Prompts the user for a buffer name and kills the chosen buffer. -- Prompts about really closing if the buffer is marked as changed -- since last save. killBufferE :: YiM () killBufferE = promptingForBuffer "kill buffer:" k (\o b -> o ++ (b \\ o)) where k :: BufferRef -> YiM () k b = do buf <- withEditor . gets $ findBufferWith b ch <- deservesSave buf let askKeymap = choice [ char 'n' ?>>! closeBufferAndWindowE , char 'y' ?>>! delBuf >> closeBufferAndWindowE , ctrlCh 'g' ?>>! closeBufferAndWindowE ] delBuf = deleteBuffer b question = identString buf <> " changed, close anyway? (y/n)" withEditor $ if ch then void $ spawnMinibufferE question (const askKeymap) else delBuf -- | If on separators (space, tab, unicode seps), reduce multiple -- separators to just a single separator (or however many given -- through 'UnivArgument'). -- -- If we aren't looking at a separator, insert a single space. This is -- like emacs β€˜just-one-space’ but doesn't deal with negative argument -- case but works with other separators than just space. What counts -- as a separator is decided by 'isAnySep' modulo @\n@ character. -- -- Further, it will only reduce a single type of separator at once: if -- we have hard tabs followed by spaces, we are able to reduce one and -- not the other. justOneSep :: UnivArgument -> BufferM () justOneSep u = readB >>= \c -> pointB >>= \point -> case point of Point 0 -> if isSep c then deleteSeparators else insertMult c Point x -> if isSep c then deleteSeparators else readAtB (Point $ x - 1) >>= \d -> -- We weren't looking at separator but there might be one behind us if isSep d then moveB Character Backward >> deleteSeparators else insertMult ' ' -- no separators, insert a space just -- like emacs does where isSep c = c /= '\n' && isAnySep c insertMult c = insertN $ R.replicateChar (maybe 1 (max 1) u) c deleteSeparators = do genMaybeMoveB unitSepThisLine (Backward, InsideBound) Backward moveB Character Forward doIfCharB isSep $ deleteB unitSepThisLine Forward -- | Join this line to previous (or next N if universal) joinLinesE :: UnivArgument -> BufferM () joinLinesE Nothing = return () joinLinesE (Just _) = do moveB VLine Forward moveToSol >> transformB (const " ") Character Backward >> justOneSep Nothing -- | Shortcut to use a default list when a blank list is given. -- Used for default values to emacs queries maybeList :: [a] -> [a] -> [a] maybeList def [] = def maybeList _ ls = ls maybeTag :: Tag -> T.Text -> Tag maybeTag def t = if T.null t then def else Tag t -------------------------------------------------- -- TAGS - See Yi.Tag for more info -- | Prompt the user to give a tag and then jump to that tag promptTag :: YiM () promptTag = do -- default tag is where the buffer is on defaultTag <- withCurrentBuffer $ Tag . R.toText <$> readUnitB unitWord -- if we have tags use them to generate hints tagTable <- withEditor getTags -- Hints are expensive - only lazily generate 10 let hinter = return . take 10 . maybe (fail . T.unpack) hintTags tagTable -- Completions are super-cheap. Go wild let completer = return . maybe id completeTag tagTable p = "Find tag: (default " <> _unTag defaultTag `T.snoc` ')' withMinibufferGen "" hinter p completer (const $ return ()) $ -- if the string is "" use the defaultTag gotoTag . maybeTag defaultTag -- | Opens the file that contains @tag@. Uses the global tag table and prompts -- the user to open one if it does not exist gotoTag :: Tag -> YiM () gotoTag tag = visitTagTable $ \tagTable -> case lookupTag tag tagTable of [] -> printMsg $ "No tags containing " <> _unTag tag (filename, line):_ -> openingNewFile filename $ gotoLn line -- | Call continuation @act@ with the TagTable. Uses the global table -- and prompts the user if it doesn't exist visitTagTable :: (TagTable -> YiM ()) -> YiM () visitTagTable act = do posTagTable <- withEditor getTags -- does the tagtable exist? case posTagTable of Just tagTable -> act tagTable Nothing -> promptFile "Visit tags table: (default tags)" $ \path -> do -- default emacs behavior, append tags let p = T.unpack path filename = maybeList "tags" $ takeFileName p tagTable <- io $ importTagTable $ takeDirectory p </> filename withEditor $ setTags tagTable act tagTable -- TODO: use TextUnit to count things inside region for better experience -- | Counts the number of lines, words and characters inside selected -- region. Coresponds to emacs' @count-words-region@. countWordsRegion :: YiM () countWordsRegion = do (l, w, c) <- withEditor $ do t <- withCurrentBuffer $ getRectangle >>= \(reg, _, _) -> readRegionB reg let nls = R.countNewLines t return (if nls == 0 then 1 else nls, length $ R.words t, R.length t) printMsg $ T.unwords [ "Region has", showT l, p l "line" <> "," , showT w, p w "word" <> ", and" , showT c, p w "character" <> "." ] where p x w = if x == 1 then w else w <> "s"
TOSPIO/yi
src/library/Yi/Keymap/Emacs/Utils.hs
gpl-2.0
15,734
0
21
4,272
3,433
1,803
1,630
270
5
{-# OPTIONS_GHC -w -fno-warn-redundant-constraints #-} {-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleContexts, FlexibleInstances, OverlappingInstances, UndecidableInstances, KindSignatures #-} -- Cut down from a larger core-lint error module Q where import Control.Monad (foldM, liftM, ap) data NameId = NameId data Named name a = Named data Arg e = Arg data Range = Range data Name = Name data ALetBinding = ALetBinding data APattern a = APattern data CExpr = CExpr data CPattern = CPattern data NiceDeclaration = QQ data TypeError = NotAValidLetBinding NiceDeclaration data TCState = TCSt { stFreshThings :: FreshThings } data FreshThings = Fresh newtype NewName a = NewName a newtype LetDef = LetDef NiceDeclaration newtype TCMT (m :: * -> *) a = TCM () localToAbstract :: ToAbstract c a => c -> (a -> TCMT IO b) -> TCMT IO b localToAbstract = undefined typeError :: MonadTCM tcm => TypeError -> tcm a typeError = undefined lhsArgs :: [Arg (Named String CPattern)] lhsArgs = undefined freshNoName :: (MonadState s m, HasFresh NameId s) => Range -> m Name freshNoName = undefined class (Monad m) => MonadState s m | m -> s class (Monad m) => MonadIO m class ToAbstract concrete abstract | concrete -> abstract where toAbstract :: concrete -> TCMT IO abstract class (MonadState TCState tcm) => MonadTCM tcm where liftTCM :: TCMT IO a -> tcm a class HasFresh i a where nextFresh :: a -> (i,a) instance ToAbstract c a => ToAbstract [c] [a] where instance ToAbstract c a => ToAbstract (Arg c) (Arg a) where instance ToAbstract c a => ToAbstract (Named name c) (Named name a) where instance ToAbstract CPattern (APattern CExpr) where instance ToAbstract LetDef [ALetBinding] where toAbstract (LetDef d) = do _ <- letToAbstract undefined where letToAbstract = do localToAbstract lhsArgs $ \args -> foldM lambda undefined (undefined :: [a]) lambda _ _ = do x <- freshNoName undefined return undefined lambda _ _ = typeError $ NotAValidLetBinding d instance HasFresh NameId FreshThings where nextFresh = undefined instance HasFresh i FreshThings => HasFresh i TCState where nextFresh = undefined instance Monad m => MonadState TCState (TCMT m) where instance Monad m => MonadTCM (TCMT m) where liftTCM = undefined instance Functor (TCMT m) where fmap = liftM instance Applicative (TCMT m) where pure = return (<*>) = ap instance Monad (TCMT m) where return = undefined (>>=) = undefined instance Monad m => MonadIO (TCMT m) where
sdiehl/ghc
testsuite/tests/typecheck/should_compile/T4969.hs
bsd-3-clause
2,717
0
14
667
834
442
392
-1
-1