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
------------------------------------------------------------------------------ -- | Defines a simple proxy type for complicated type classes. module Snap.Snaplet.Rest.Proxy ( Proxy (..) ) where ------------------------------------------------------------------------------ -- | Uses a phantom type to indicate to the type system which class instance -- to use when it may be ambiguous. data Proxy t = Proxy
zmthy/snaplet-rest
src/Snap/Snaplet/Rest/Proxy.hs
mit
417
0
5
58
30
22
8
3
0
-- file: ch03/MySecond.hs mySecond :: [a] -> a mySecond xs = if null (tail xs) then error "List too short" else head (tail xs) -- We can use the Maybe type for a more controlled approach safeSecond :: [a] -> Maybe a safeSecond [] = Nothing safeSecond xs = if null (tail xs) then Nothing else Just (head (tail xs)) -- Lets' improve the readability with pattern matching: tidySecond :: [a] -> Maybe a tidySecond (_:x:_) = Just x tidySecond _ = Nothing
supermitch/learn-haskell
real-world-haskell/ch03/MySecond.hs
mit
522
0
10
155
163
84
79
12
2
-- Error vs. Exception -- ref: https://wiki.haskell.org/Error_vs._Exception -- ref: https://wiki.haskell.org/Error -- ref: https://wiki.haskell.org/Exception -- Error {- An error denotes a programming error. The Prelude function error represents an error with a message, undefined represents an error with a standard message. For a Haskell program, an undefined value cannot be distinguished from an infinite loop, e.g. let x=x+1 in x :: Int. Almost not. So error and undefined value are somehow synonyms in Haskell. Since Haskell is non-strict, the occurence of an error within an expression is not necessarily an error, if the erroneous value is ignored somewhere, e.g. False && undefined. However, if an expression finally evaluates to bottom or hangs in an infinite loop, then this is definitely a programming error. -} -- Exception {- An exception denotes an unpredictable situation at runtime, like "out of disk storage", "read protected file", "user removed disk while reading", "syntax error in user input". These are situation which occur relatively seldom and thus their immediate handling would clutter the code which should describe the regular processing. Since exceptions must be expected at runtime there are also mechanisms for (selectively) handling them. (Control.Exception.try, Control.Exception.catch) Unfortunately Haskell's standard library names common exceptions of IO actions IOError and the module Control.Monad.Error is about exception handling not error handling. In general you should be very careful not to mix up exceptions with errors. Actually, an unhandled exception is an error. -} -- Implementation -- Exception Monad -- error_code vs. exception in C++ -- Functions return error codes, but the handling of error codes does not uglify the calling code. in Haskell -- First we implement exception handling for non-monadic functions. Since no IO functions are involved, we still cannot handle exceptional situations induced from outside the world, but we can handle situations where it is unacceptable for the caller to check a priori whether the call can succeed. data Exceptional e a = Success a | Exception e deriving (Show) instance Monad (Exceptional e) where return = Success Exception l >>= _ = Exception l Success r >>= k = k r throw :: e -> Exceptional e a throw = Exception catch :: Exceptional e a -> (e -> Exceptional e a) -> Exceptional e a catch (Exception l) h = h l catch (Success r) _ = Success r newtype ExceptionalT e m a = ExceptionalT {runExceptionalT :: m (Exceptional e a)} instance Monad m => Monad (ExceptionalT e m) where return = ExceptionalT . return . Success m >>= k = ExceptionalT $ runExceptionalT m >>= \ a -> case a of Exception e -> return (Exception e) Success r -> runExceptionalT (k r) throwT :: Monad m => e -> ExceptionalT e m a throwT = ExceptionalT . return . Exception catchT :: Monad m => ExceptionalT e m a -> (e -> ExceptionalT e m a) -> ExceptionalT e m a catchT m h = ExceptionalT $ runExceptionalT m >>= \ a -> case a of Exception l -> runExceptionalT (h l) Success r -> return (Success r) bracketT :: Monad m => ExceptionalT e m h -> (h -> ExceptionalT e m ()) -> (h -> ExceptionalT e m a) -> ExceptionalT e m a bracketT open close body = open >>= (\ h -> ExceptionalT $ do a <- runExceptionalT (body h) runExceptionalT (close h) return a) data IOException = DiskFull | FileDoesNotExist | ReadProtected | WriteProtected | NoSpaceOnDevice deriving (Show, Eq, Enum) open :: FilePath -> ExceptionalT IOException IO Handle close :: Handle -> ExceptionalT IOException IO () read :: Handle -> ExceptionalT IOException IO String write :: Handle -> String -> ExceptionalT IOException IO () readText :: FilePath -> ExceptionalT IOException IO String readText fileName = bracketT (open fileName) close $ \h -> read h -- Finally we can escape from the Exception monad if we handle the exceptions completely. {- main :: IO () main = do result <- runExceptionalT (readText "test") case result of Exception e -> putStrLn ("When reading file 'test' we encountered exception " ++ show e) Success x -> putStrLn ("Content of the file 'test'\n" ++ x) -} -- Processing individual exceptions {- So far I used the sum type IOException that subsumes a bunch of exceptions. However, not all of these exceptions can be thrown by all of the IO functions. E.g. a read function cannot throw WriteProtected or NoSpaceOnDevice. Thus when handling exceptions we do not want to handle WriteProtected if we know that it cannot occur in the real world. We like to express this in the type and actually we can express this in the type. Consider two exceptions: ReadException and WriteException. In order to be able to freely combine these exceptions, we use type classes, since type constraints of two function calls are automatically merged. -} import Control.Monad.Exception.Synchronous (ExceptionalT, ) class ThrowsRead e where throwRead :: e class ThrowsWrite e where throwWrite :: e readFile :: ThrowsRead e => FilePath -> ExceptionalT e IO String writeFile :: ThrowsWrite e => FilePath -> String -> ExceptionalT e IO () {- copyFile src dst = writeFile dst =<< readFile src copyFile :: (ThrowsWrite e, ThrowsRead e) => FilePath -> FilePath -> ExceptionalT e IO () -} data ApplicationException = ReadException | WriteException instance ThrowsRead ApplicationException where throwRead = ReadException instance ThrowsWrite ApplicationException where throwWrite = WriteException -- Defining exception types as a sum of "this particular exception" and "another exception" lets us compose concrete types that can carry a certain set of exceptions on the fly. This is very similar to switching from particular monads to monad transformers. Thanks to the type class approach the order of composition needs not to be fixed by the throwing function but is determined by the order of catching. We even do not have to fix the nested exception type fully when catching an exception. It is enough to fix the part that is interesting for catch: data ReadException e = ReadException | NoReadException e instance ThrowsRead (ReadException e) where throwRead = ReadException instance ThrowsWrite e => ThrowsWrite (ReadException e) where throwWrite = NoReadException throwWrite data WriteException e = WriteException | NoWriteException e instance ThrowsRead e => ThrowsRead (WriteException e) where throwRead = NoWriteException throwRead instance ThrowsWrite (WriteException e) where throwWrite = WriteException import Control.Monad.Exception.Synchronous (Exceptional(Success,Exception)) catchRead :: ReadException e -> Exceptional e String catchRead ReadException = Success "catched a read exception" catchRead (NoReadException e) = Exception e throwReadWrite :: (ThrowsRead e, ThrowsWrite e) => e throwReadWrite = asTypeOf throwRead throwWrite exampleCatchRead :: (ThrowsWrite e) => Exceptional e String exampleCatchRead = catchRead throwReadWrite -- Note how in exampleCatchRead the constraint ThrowsRead is removed from the constraint list of throwReadWrite. -- the term exception for expected but irregular situations at runtime -- the term error for mistakes in the running program that can be resolved only by fixing the program. -- Haskell's error is just sugar for undefined -- ways of exceptions -- Maybe/Either/IO exceptions -- Exceptions: Prelude.catch, Control.Exception.catch, Control.Exception.try, IOError, Control.Monad.Error -- Errors: error, assert, Control.Exception.catch, Debug.Trace.trace {- My conclusion is that (programming) errors can only be handled by the programmer, not by the running program. Thus the term "error handling" sounds contradictory to me. However supporting a programmer with finding errors (bugs) in their programs is a good thing. I just wouldn't call it "error handling" but "debugging". An important example in Haskell is the module Debug.Trace. It provides the function trace that looks like a non-I/O function but actually outputs something on the console. It is natural that debugging functions employ hacks. For finding a programming error it would be inappropriate to transform the program code to allow I/O in a set of functions that do not need it otherwise. The change would only persist until the bug is detected and fixed. Summarized, hacks in debugging functions are necessary for quickly finding problems without large restructuring of the program and they are not problematic, because they only exist until the bug is removed. Different from that exceptions are things you cannot fix in advance. You will always have to live with files that cannot be found and user input that is malformed. You can insist that the user does not hit the X key, but your program has to be prepared to receive a "X key pressed" message nonetheless. Thus exceptions belong to the program and the program must be adapted to treat exceptional values where they can occur. No hacks can be accepted for exception handling. -} -- When exceptions -> errors -- It is an error to not handle an exception. If a file cannot be opened you must respect that result. You can proceed as if the file could be opened, though. If you do so you might crash the machine or the runtime system terminates your program. All of these effects are possible consequences of a (programming) error. -- Again, it does not matter whether the exceptional situation is signaled by a return code that you ignore or an IO exception for which you did not run a catch. -- When errors -> exceptions -- Typical examples are: A process in an operating system shall not crash the whole system if it crashes itself. A buggy browser plugin shall not terminate the browser. A corrupt CGI script shall not bring the web server down, where it runs on. -- Errors and Type system -- It is generally considered, that errors in a program imply a lack in the type system. If the type system would be strong enough and the programmers would be patient enough to work out the proofs imposed by library functions, then there would be no errors in programs at all, only exceptions. -- An alternative to extending the type system to dependent type system that allows for a wide range of proofs is the Extended Static Checking. For example: {-# CONTRACT head :: { xs | not (null xs) } -> Ok #-} head :: [a] -> a head [] = error "head: empty list" head (x:_) = x -- Call stacks -- Escaping from control structures -- break/return... in imperative languages -- what exception handlers and resource deallocators shall be run when you leave a loop or function using break? Analogously exceptions can also be used to escape from custom control structures (yeah, higher order functions are also possible in imperative languages) or deep recursive searches. In imperative languages exceptions are often implemented in a way that is especially efficient when deep recursions have to be aborted. -- Escaping from a control structure is just the irregular case with respect to the regular case of looping/descending in recursion. In Haskell, when you use exception monads like Control.Monad.Exception.Synchronous or Control.Monad.Error, exceptions are just an automated handling of return codes.
Airtnp/Freshman_Simple_Haskell_Lib
Idioms/Error-vs-Exception.hs
mit
11,867
0
14
2,547
1,184
620
564
-1
-1
module Stripe ( runStripe , subscribeToPlan , cancelSubscription ) where import Import import Control.Monad.Except (ExceptT, runExceptT, throwError) import Web.Stripe ((-&-)) import qualified Web.Stripe as S import qualified Web.Stripe.Customer as S import qualified Web.Stripe.Error as S import qualified Web.Stripe.Subscription as S type Stripe = ReaderT S.StripeConfig (ExceptT S.StripeError IO) runStripe :: Stripe a -> Handler (Maybe a) runStripe f = do stripeKey <- stripeKeysSecretKey . appStripeKeys <$> getYesod result <- liftIO $ runExceptT $ runReaderT f $ S.StripeConfig $ S.StripeKey $ encodeUtf8 stripeKey case result of Left err -> do $(logError) $ pack $ show err return Nothing Right x -> return $ Just x subscribeToPlan :: S.TokenId -> S.Email -> S.PlanId -> Maybe S.CustomerId -> Stripe S.CustomerId subscribeToPlan token email planId mstripeId = do stripeId <- findOrCreateCustomer token email mstripeId void $ request $ S.createSubscription stripeId planId return stripeId cancelSubscription :: Maybe S.CustomerId -> Stripe () cancelSubscription Nothing = return () cancelSubscription (Just stripeId) = do subs <- S.list <$> (request $ S.getSubscriptions stripeId) forM_ subs $ \sub -> void $ request $ S.cancelSubscription stripeId (S.subscriptionId sub) -&- S.AtPeriodEnd False findOrCreateCustomer :: S.TokenId -> S.Email -> Maybe S.CustomerId -> Stripe S.CustomerId findOrCreateCustomer _ _ (Just stripeId) = return stripeId findOrCreateCustomer token email _ = S.customerId <$> request (S.createCustomer -&- token -&- email) request :: FromJSON (S.StripeReturn a) => S.StripeRequest a -> Stripe (S.StripeReturn a) request f = do config <- ask result <- liftIO $ S.stripe config f either throwError return result
thoughtbot/carnival
Stripe.hs
mit
1,951
0
15
455
618
309
309
-1
-1
{-- Copyright (c) 2014 Gorka Suárez García Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --} {- *************************************************************** The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143? *************************************************************** -} module Problem0003 (main) where squareRoot :: (Integral a) => a -> a squareRoot x = truncate $ sqrt $ fromIntegral x multipleOf :: (Integral a) => a -> a -> Bool multipleOf a b = (mod a b) == 0 isPrime :: (Integral a) => a -> Bool isPrime 2 = True isPrime n = not $ or [multipleOf n x | x <- 2:[3,5..upperLimit]] where upperLimit = squareRoot n + 1 reduceByFactor :: (Integral a) => a -> a -> a reduceByFactor n x = if multipleOf n x then reduceByFactor (div n x) x else n getFactors :: (Integral a) => a -> [a] getFactors number = gf number [x | x <- [2..], isPrime x] [] where gf n (p:ps) rs = if p > n then rs else if multipleOf n p then gf (reduceByFactor n p) ps (p:rs) else gf n ps rs largestPrimeFactor :: Integer -> Integer largestPrimeFactor n = head (getFactors n) main = do putStr "The largest prime factor of the number " putStrLn (show number ++ " = " ++ show result) where number = 600851475143 result = largestPrimeFactor number -- *************************************************************** primesList = [x | x <- [1..], isPrime x] isPrime' :: (Integral a) => a -> Bool isPrime' n = not $ or [multipleOf n x | x <- [2..(n - 1)]] isPrime'' :: (Integral a) => a -> Bool isPrime'' number = ip number 2 where nextNum 2 = 3 nextNum n = n + 2 ip n x = if x >= n then True else if multipleOf n x then False else ip n (nextNum x) largestPrimeFactor' :: Integer -> Integer largestPrimeFactor' n = head $ filter selector inverseList where inverseList = [n,(n - 1)..1] selector x = multipleOf n x && isPrime x primeFactorOf :: (Integral a) => a -> a -> Bool primeFactorOf a b = multipleOf a b && isPrime b largestPrimeFactor'' :: Integer -> Integer largestPrimeFactor'' n = lpf n where lpf x = if primeFactorOf n x then x else lpf (x - 1) -- ***************************************************************
gorkinovich/Haskell
Problems/Problem0003.hs
mit
3,389
0
12
803
795
412
383
47
4
{-# LANGUAGE TupleSections, OverloadedStrings #-} module Barch.Cart where import Import import Prelude import Data.Maybe (catMaybes, fromMaybe) import Data.Set as S (Set, delete, empty, insert, toList) import Data.Text (unpack, pack) listCart::Handler [ReferenceId] listCart = do oldCart <- lookupSession "citationCart" let cart = toList . fromMaybe empty $ read . unpack <$> oldCart return cart listCartItems::Handler [Entity Reference] listCartItems = do cartIds <- listCart maybeCartItems <- mapM runDB $ get <$> cartIds let cartItems = catMaybes . zipWith (\key val -> Entity key <$> val) cartIds $ maybeCartItems return cartItems modifyCart::(Set ReferenceId->Set ReferenceId)->Handler () modifyCart f = do oldCart <- lookupSession "citationCart" let cart = f . fromMaybe empty $ read . unpack <$> oldCart setSession "citationCart" (pack . show $ cart) addToCart::ReferenceId->Handler () addToCart refid = modifyCart (S.insert refid) removeFromCart::ReferenceId->Handler () removeFromCart refid = modifyCart (S.delete refid) clearCart::Handler () clearCart = modifyCart (\_ -> empty)
klarh/barch
Barch/Cart.hs
mit
1,117
0
16
172
396
200
196
29
1
module Paradise.Client ( VesselID , PlayerData (..) ) where import qualified Data.ByteString.Char8 as B type VesselID = B.ByteString data PlayerData = PlayerData { vessel :: VesselID }
Hamcha/netslum
Paradise/Client.hs
mit
228
0
8
70
50
33
17
6
0
{--*-Mode:haskell;coding:utf-8;tab-width:4;c-basic-offset:4;indent-tabs-mode:()-*- ex: set ft=haskell fenc=utf-8 sts=4 ts=4 sw=4 et nomod: -} {- MIT License Copyright (c) 2017 Michael Truog <mjtruog at protonmail dot com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -} module Foreign.Erlang.Function ( Function(..) ) where import qualified Data.ByteString as ByteString import qualified Data.Word as Word type ByteString = ByteString.ByteString type Word8 = Word.Word8 data Function = Function { tag :: !Word8 , value :: !ByteString } deriving (Ord, Eq, Show)
CloudI/CloudI
src/api/haskell/src/Foreign/Erlang/Function.hs
mit
1,604
0
9
295
88
56
32
14
0
module Shipper.Event ( readAllEvents, maxPacketSize ) where import Shipper.Types import Control.Concurrent.STM (atomically) import Control.Concurrent.STM.TBQueue import Control.Concurrent -- This is the maximum number of events that an output will try to stick into -- one packet. Assuming they're doin' it right. -- -- TODO: Tune this to a good match with ZMQ over low latency intertube in mind. maxPacketSize :: Int maxPacketSize = 1024 allowedTime :: Int allowedTime = 100000 -- 100ms -- This was originally in the STM monad, however was moved to IO just to call -- yield. The yield is needed when testing with a channel size of one, to -- ensure that no extremely non-linear performance characteristics emerge. -- -- We call this in order to read at most a packet sized array of events from -- the given channel. readAllEvents :: TBQueue ChannelPayload -> IO [Event] readAllEvents ch = readAllEvents' ch maxPacketSize allowedTime where readAllEvents' :: TBQueue ChannelPayload -> Int -> Int -> IO [Event] readAllEvents' _ 0 _ = return [] readAllEvents' _ _ 0 = return [] readAllEvents' ch' current_size start_time = do me <- atomically $ tryReadTBQueue ch' case me of Nothing -> let delay = 10000 in do -- 10ms threadDelay delay readAllEvents' ch current_size (start_time - delay) Just payload -> do -- This allows other (read: input) threads control over -- execution, which, worst case scenario is handed off to -- another output thread. -- -- This should be fine due to the round robin nature of the -- current RTS scheduler in GHC. -- -- Should the scheduler (theoretically) become pathologically -- biased towards an output thread, there's not much we can do -- here to achieve a full packet 100% of the time. -- -- But the scheduler would have to become really really dumb -- for that. And I'm super lucky like that. yield rest <- readAllEvents' ch (current_size - 1) start_time case payload of Single e -> return $ e : rest Multiple es -> return $ es ++ rest
christian-marie/pill-bug
Shipper/Event.hs
mit
2,366
0
18
729
329
177
152
27
5
module SourceParser ( parseExpr, parse ) where import Text.ParserCombinators.Parsec hiding (spaces) import DataTypes import Numeric (readHex, readOct) import Control.Monad {-import Control.Applicative hiding ((<|>), many)-} symbol :: Parser Char symbol = oneOf "!$#%&|*+-/:<=>?@^_~" spaces :: Parser () spaces = skipMany1 space escapeCharacters = ['\\', '"', 'n', 't', 'r'] transformChar :: Char -> Char transformChar x = case x of 'n' -> '\n' 't' -> '\t' 'r' -> '\r' otherwise -> x escape :: Parser Char escape = do slash <- char '\\' escapeCode <- oneOf escapeCharacters return $ transformChar escapeCode nonEscape :: Parser Char nonEscape = noneOf "\\\"" parseString :: Parser LispVal parseString = do char '"' x <- many $ nonEscape <|> escape char '"' return $ LispString x parseChar :: Parser LispVal parseChar = (\x -> LispChar x) <$> (string "#\\" *> (nonEscape <|> escape)) parseAtom :: Parser LispVal parseAtom = do first <- letter <|> symbol rest <- many (letter <|> digit <|> symbol) let atom = [first] ++ rest return $ case atom of "#t" -> LispBool True "#f" -> LispBool False otherwise -> Atom atom parseNumber :: Parser LispVal parseNumber = do x <- try negativeNumber <|> try decimal <|> try octal <|> try hexadecimal <|> number return $ (Number . read) x where negativeNumber = char '-' *> fmap (show . multNegOne) parseNumber number = many1 digit decimal = string "#d" *> number octal = string "#o" *> fmap (show . fst . head . readOct) (many1 octDigit) hexadecimal = string "#x" *> fmap (show . fst . head . readHex) (many1 hexDigit) multNegOne (Number x) = (-1)*x parseGaussian :: Parser LispVal parseGaussian = do real <- many1 digit char 'i' char '+' imag <- many1 digit char 'j' return $ Gaussian (read real, read imag) parseList :: Parser LispVal parseList = liftM List $ sepBy parseExpr spaces parseDottedList :: Parser LispVal parseDottedList = do head <- endBy parseExpr spaces tail <- char '.' >> spaces >> parseExpr return $ DottedList head tail parseQuoted :: Parser LispVal parseQuoted = do char '\'' x <- parseExpr return $ List [Atom "quote", x] parseEitherList :: Parser LispVal parseEitherList = do char '(' x <- (try parseList) <|> parseDottedList char ')' return x parseExpr :: Parser LispVal parseExpr = try parseChar <|> try parseGaussian <|> parseNumber <|> parseString <|> parseAtom <|> parseQuoted <|> parseEitherList
Bolt64/wyas
src/SourceParser.hs
mit
3,078
0
12
1,105
895
436
459
79
4
{-# LANGUAGE OverloadedStrings, RankNTypes #-} module Lightstreamer.Client ( OK , StreamContext(info, threadId) , changeConstraints , destroySession , newStreamConnection , reconfigureSubscription , requestRebind , sendAsyncMessage , sendMessage , subscribe ) where import Control.Exception (try, throwIO) import Control.Concurrent (ThreadId, myThreadId) import Control.Concurrent.MVar (newEmptyMVar, takeMVar) import Data.Functor ((<$>)) import Data.Attoparsec.ByteString.Char8 (endOfLine) import Data.ByteString (ByteString) import Data.ByteString.Char8 (pack, unpack) import Data.Conduit (Consumer) import Lightstreamer.Error import Lightstreamer.Http import Lightstreamer.Request import Lightstreamer.Streaming import qualified Data.Attoparsec.ByteString as AB data StreamContext = StreamContext { info :: StreamInfo , threadId :: ThreadId } data OK = OK newStreamConnection :: StreamHandler h => ConnectionSettings -> StreamRequest -> h -> IO (Either LsError StreamContext) newStreamConnection settings req handler = do varInfo <- newEmptyMVar establishStreamConnection settings Nothing req (streamCorrupted handler) (streamConsumer varInfo st) (\tId -> takeMVar varInfo >>= \val -> return $ StreamContext val tId) where st = StreamState { streamHandler = handler, rebindSession = rebind } rebind sId = do tId <- myThreadId result <- establishStreamConnection settings (Just tId) (mkBindRequest sId req) (streamCorrupted handler) (streamContinuationConsumer sId st) (\_ -> return ()) case result of Left err -> throwIO . StreamException $ case err of LsError _ msg -> msg ConnectionError msg -> msg ErrorPage msg -> msg HttpError _ msg -> msg Unexpected msg -> msg _ -> return () establishStreamConnection :: RequestConverter r => ConnectionSettings -> Maybe ThreadId -> r -> (String -> IO ()) -> (IO () -> Consumer [ByteString] IO ()) -> (ThreadId -> IO a) -> IO (Either LsError a) establishStreamConnection settings tId req errHandle consumer resHandle = do result <- try action case result of Left err -> return . Left . ConnectionError $ showException err Right x -> return x where action = do conn <- newConnection settings sendHttpRequest conn req response <- readStreamedResponse conn tId (errHandle . unpack) (consumer $ closeConnection conn) case response of Left err -> return . Left $ ConnectionError err Right res -> if resStatusCode res /= 200 then return . Left $ HttpError (resStatusCode res) (resReason res) else case resBody res of ContentBody b -> return . Left . either (Unexpected . pack) id $ AB.parseOnly errorParser b StreamingBody newId -> Right <$> resHandle newId _ -> return . Left $ Unexpected "new stream response." subscribe :: ConnectionSettings -> SubscriptionRequest -> IO (Either LsError OK) subscribe = withSimpleRequest withSimpleRequest :: RequestConverter r => ConnectionSettings -> r -> IO (Either LsError OK) withSimpleRequest settings req = do conn <- newConnection settings result <- try $ either (Left . ConnectionError) doAction <$> simpleHttpRequest conn req closeConnection conn case result of Left err -> return . Left . ConnectionError $ showException err Right x -> return x where doAction res = if resStatusCode res /= 200 then Left $ HttpError (resStatusCode res) (resReason res) else case resBody res of ContentBody b -> parseSimpleResponse b _ -> Left $ Unexpected "response" parseSimpleResponse :: ByteString -> Either LsError OK parseSimpleResponse = either (Left . Unexpected . pack) id . AB.parseOnly resParser where resParser = AB.choice [Right <$> okParser, Left <$> errorParser] okParser = do _ <- AB.string "OK" endOfLine return OK reconfigureSubscription :: ConnectionSettings -> ReconfigureRequest -> IO (Either LsError OK) reconfigureSubscription = withSimpleRequest changeConstraints :: ConnectionSettings -> ConstraintsRequest -> IO (Either LsError OK) changeConstraints = withSimpleRequest requestRebind :: ConnectionSettings -> ByteString -> IO (Either LsError OK) requestRebind settings = withSimpleRequest settings . RebindRequest destroySession :: ConnectionSettings -> ByteString -> IO (Either LsError OK) destroySession settings = withSimpleRequest settings . DestroyRequest sendMessage :: ConnectionSettings -> MessageRequest -> IO (Either LsError OK) sendMessage = withSimpleRequest sendAsyncMessage :: ConnectionSettings -> AsyncMessageRequest -> IO (Either LsError OK) sendAsyncMessage = withSimpleRequest
jm4games/lightstreamer
src/Lightstreamer/Client.hs
mit
5,637
0
20
1,842
1,408
710
698
131
6
-- Another one down—the Survival of the Fittest! -- http://www.codewars.com/kata/563ce9b8b91d25a5750000b6/ module Codewars.Kata.RemoveSmallest where import Data.List (delete) removeSmallest :: Int -> [Int] -> [Int] removeSmallest n | n <= 0 = id | otherwise = (!!n) . iterate f where f xs = delete (minimum xs) xs
gafiatulin/codewars
src/6 kyu/RemoveSmallest 2.hs
mit
353
0
9
83
97
52
45
6
1
module EitherLib where lefts' :: [Either a b] -> [a] lefts' = foldr (\x acc -> if isLeft x then (left x):acc else acc) [] where isLeft (Left a) = True isLeft _ = False left (Left a) = a -- Too much repetition here. Should I move it to foldr somehow? -- Now I think we can use Maybe to write Right and Left extractors, but it looks like -- overhead for current context. rights' :: [Either a b] -> [b] rights' = foldr (\x acc -> if isRight x then (right x):acc else acc) [] where isRight (Right a) = True isRight _ = False right (Right a) = a partitionEithers' :: [Either a b] -> ([a], [b]) partitionEithers' xs = (lefts' xs, rights' xs) eitherMaybe' :: (b -> c) -> Either a b -> Maybe c eitherMaybe' f (Left a) = Nothing eitherMaybe' f (Right a) = Just $ f a either' :: (a -> c) -> (b -> c) -> Either a b -> c either' f _ (Left a) = f a either' _ f (Right b) = f b -- Not sure, I understand the idea correctly. eitherMaybe'' :: (b -> c) -> Either a b -> Maybe c eitherMaybe'' _ (Right a) = Nothing eitherMaybe'' f e@(Left b) = Just $ either' undefined f e
raventid/coursera_learning
haskell/chapter12/either_lib.hs
mit
1,098
0
11
265
478
249
229
22
3
{-# LANGUAGE NoMonomorphismRestriction #-} module Plugins.Gallery.Gallery.Manual14 where import Diagrams.Prelude example = beside (r2 (20,30)) (circle 1 # fc orange) (circle 1.5 # fc purple) # showOrigin
andrey013/pluginstest
Plugins/Gallery/Gallery/Manual14.hs
mit
260
0
9
82
68
37
31
7
1
dupli :: [a] -> [a] dupli x = repli x 2 repli :: [a] -> Int -> [a] repli [] _ = [] repli (x:xs) n = replicate n x ++ repli xs n dropEvery :: [a] -> Int -> [a] dropEvery x n = take (n - 1) x ++ dropEvery (drop n x) n split :: [a] -> Int -> ([a], [a]) split x n = (take n x, drop n x) slice :: [a] -> Int -> Int -> [a] slice x a b = drop (a - 1) . take b $ x rotate :: [a] -> Int -> [a] rotate x n | (n > 0) = drop n x ++ take n x | otherwise = drop realnum x ++ take realnum x where realnum = length x + n removeAt :: Int -> [a] -> (a, [a]) removeAt n x = (x !! (n - 1), take (n - 1) x ++ drop n x) main = do print $ dupli [1, 2, 3] print $ repli "abc" 3 --print $ dropEvery "abcdefghik" 3 print $ split "abcdefghik" 3 print $ slice ['a','b','c','d','e','f','g','h','i','k'] 3 7 print $ rotate ['a','b','c','d','e','f','g','h'] 3 print $ rotate ['a','b','c','d','e','f','g','h'] (-2) print $ removeAt 2 "abcd"
maggy96/haskell
99 Problems/11_20.hs
mit
976
0
10
274
609
322
287
26
1
module SpecHelper ( withBiegunkaTempDirectory ) where import qualified System.IO.Temp as IO withBiegunkaTempDirectory :: (FilePath -> IO a) -> IO a withBiegunkaTempDirectory = IO.withSystemTempDirectory "biegunka"
biegunka/biegunka
test/spec/SpecHelper.hs
mit
221
0
8
31
50
29
21
5
1
{-# LANGUAGE OverloadedStrings #-} import System.Taffybar import System.Taffybar.Information.CPU import System.Taffybar.SimpleConfig import System.Taffybar.Widget import System.Taffybar.Widget.Generic.Graph import System.Taffybar.Widget.Generic.PollingGraph cpuCallback = do (_, systemLoad, totalLoad) <- cpuLoad return [ totalLoad, systemLoad ] main = do let cpuCfg = defaultGraphConfig { graphDataColors = [ (0, 1, 0, 1), (1, 0, 1, 0.5)] , graphLabel = Just "cpu" } clock = textClockNew Nothing "<span fgcolor='orange'>%a %b %_d %H:%M</span>" 1 cpu = pollingGraphNew cpuCfg 0.5 cpuCallback workspaces = workspacesNew defaultWorkspacesConfig simpleConfig = defaultSimpleTaffyConfig { startWidgets = [ workspaces ] , endWidgets = [ {-sniTrayNew,-} clock, cpu ] } startTaffybar $ toTaffyConfig simpleConfig
Ericson2314/nixos-configuration
user/graphical/taffybar.hs
cc0-1.0
977
0
13
267
207
123
84
20
1
{- | Module : $Header$ Description : analyse kinds using a class map Copyright : (c) Christian Maeder and Uni Bremen 2003-2005 License : GPLv2 or higher, see LICENSE.txt Maintainer : Christian.Maeder@dfki.de Stability : experimental Portability : portable analyse kinds using a class map -} module HasCASL.ClassAna where import HasCASL.As import HasCASL.AsUtils import HasCASL.PrintAs () import Common.Id import HasCASL.Le import qualified Data.Map as Map import qualified Data.Set as Set import Common.Lib.State import Common.Result import Common.DocUtils import Common.Utils -- * analyse kinds -- | check the kind and compute the raw kind anaKindM :: Kind -> ClassMap -> Result RawKind anaKindM k cm = case k of ClassKind ci -> if k == universe then return rStar else case Map.lookup ci cm of Just (ClassInfo rk _) -> return rk Nothing -> Result [mkDiag Error "not a class" ci] $ Just rStar FunKind v k1 k2 ps -> do rk1 <- anaKindM k1 cm rk2 <- anaKindM k2 cm return $ FunKind v rk1 rk2 ps -- | get minimal function kinds of (class) kind getFunKinds :: Monad m => ClassMap -> Kind -> m (Set.Set Kind) getFunKinds cm k = case k of FunKind _ _ _ _ -> return $ Set.singleton k ClassKind c -> case Map.lookup c cm of Just info -> do ks <- mapM (getFunKinds cm) $ Set.toList $ classKinds info return $ keepMinKinds cm ks _ -> fail $ "not a function kind '" ++ showId c "'" -- | compute arity from a raw kind kindArity :: RawKind -> Int kindArity k = case k of ClassKind _ -> 0 FunKind _ _ rk _ -> 1 + kindArity rk -- | check if a class occurs in one of its super kinds cyclicClassId :: ClassMap -> Id -> Kind -> Bool cyclicClassId cm ci k = case k of FunKind _ k1 k2 _ -> cyclicClassId cm ci k1 || cyclicClassId cm ci k2 ClassKind cj -> cj /= universeId && (cj == ci || not (Set.null $ Set.filter (cyclicClassId cm ci) $ classKinds $ Map.findWithDefault (error "cyclicClassId") cj cm)) -- * subkinding -- | keep only minimal elements according to 'lesserKind' keepMinKinds :: ClassMap -> [Set.Set Kind] -> Set.Set Kind keepMinKinds cm = Set.fromDistinctAscList . keepMins (lesserKind cm) . Set.toList . Set.unions -- | no kind of the set is lesser than the new kind newKind :: ClassMap -> Kind -> Set.Set Kind -> Bool newKind cm k = Set.null . Set.filter (flip (lesserKind cm) k) -- | add a new kind to a set addNewKind :: ClassMap -> Kind -> Set.Set Kind -> Set.Set Kind addNewKind cm k = Set.insert k . Set.filter (not . lesserKind cm k) lesserVariance :: Variance -> Variance -> Bool lesserVariance v1 v2 = case v1 of InVar -> True _ -> case v2 of NonVar -> True _ -> v1 == v2 -- | revert variance revVariance :: Variance -> Variance revVariance v = case v of InVar -> NonVar CoVar -> ContraVar ContraVar -> CoVar NonVar -> InVar -- | compute the minimal variance minVariance :: Variance -> Variance -> Variance minVariance v1 v2 = case v1 of NonVar -> v2 _ -> case v2 of NonVar -> v1 _ -> if v1 == v2 then v1 else InVar -- | check subkinding (kinds with variances are greater) lesserKind :: ClassMap -> Kind -> Kind -> Bool lesserKind cm k1 k2 = case k1 of ClassKind c1 -> (case k2 of ClassKind c2 -> c1 == c2 || if k1 == universe then False else k2 == universe _ -> False) || case Map.lookup c1 cm of Just info -> not $ newKind cm k2 $ classKinds info _ -> False FunKind v1 a1 r1 _ -> case k2 of FunKind v2 a2 r2 _ -> lesserVariance v1 v2 && lesserKind cm r1 r2 && lesserKind cm a2 a1 _ -> False -- | compare raw kinds lesserRawKind :: RawKind -> RawKind -> Bool lesserRawKind k1 k2 = case k1 of ClassKind _ -> case k2 of ClassKind _ -> True _ -> False FunKind v1 a1 r1 _ -> case k2 of FunKind v2 a2 r2 _ -> lesserVariance v1 v2 && lesserRawKind r1 r2 && lesserRawKind a2 a1 _ -> False minRawKind :: Monad m => String -> RawKind -> RawKind -> m RawKind minRawKind str k1 k2 = let err = fail $ diffKindString str k1 k2 in case k1 of ClassKind _ -> case k2 of ClassKind _ -> return $ ClassKind () _ -> err FunKind v1 a1 r1 ps -> case k2 of FunKind v2 a2 r2 qs -> do a3 <- minRawKind str a2 a1 r3 <- minRawKind str r1 r2 return $ FunKind (minVariance v1 v2) a3 r3 $ appRange ps qs _ -> err rawToKind :: RawKind -> Kind rawToKind = mapKind (const universeId) -- * diagnostic messages -- | create message for different kinds diffKindString :: String -> RawKind -> RawKind -> String diffKindString a k1 k2 = "incompatible kind of: " ++ a ++ expected (rawToKind k1) (rawToKind k2) -- | create diagnostic for different kinds diffKindDiag :: (GetRange a, Pretty a) => a -> RawKind -> RawKind -> [Diagnosis] diffKindDiag a k1 k2 = [Diag Error (diffKindString (showDoc a "") k1 k2) $ getRange a] -- | check if raw kinds are compatible checkKinds :: (GetRange a, Pretty a) => a -> RawKind -> RawKind -> [Diagnosis] checkKinds p k1 k2 = maybe (diffKindDiag p k1 k2) (const []) $ minRawKind "" k1 k2 -- | analyse class decls anaClassDecls :: ClassDecl -> State Env ClassDecl anaClassDecls (ClassDecl cls k ps) = do cm <- gets classMap let Result ds (Just rk) = anaKindM k cm addDiags ds let ak = if null ds then k else universe mapM_ (addClassDecl rk ak) cls return $ ClassDecl cls ak ps -- | store a class addClassDecl :: RawKind -> Kind -> Id -> State Env () -- check with merge addClassDecl rk kind ci = if ci == universeId then addDiags [mkDiag Warning "void universe class declaration" ci] else do e <- get let cm = classMap e tm = typeMap e tvs = localTypeVars e case Map.lookup ci tm of Just _ -> addDiags [mkDiag Error "class name already a type" ci] Nothing -> case Map.lookup ci tvs of Just _ -> addDiags [mkDiag Error "class name already a type variable" ci] Nothing -> case Map.lookup ci cm of Nothing -> do addSymbol $ idToClassSymbol ci rk putClassMap $ Map.insert ci (ClassInfo rk $ Set.singleton kind) cm Just (ClassInfo ork superClasses) -> let Result ds mk = minRawKind (showDoc ci "") rk ork in case mk of Nothing -> addDiags ds Just nk -> if cyclicClassId cm ci kind then addDiags [mkDiag Error "cyclic class" ci] else do addSymbol $ idToClassSymbol ci nk if newKind cm kind superClasses then do addDiags [mkDiag Warning "refined class" ci] putClassMap $ Map.insert ci (ClassInfo nk $ addNewKind cm kind superClasses) cm else addDiags [mkDiag Warning "unchanged class" ci]
nevrenato/Hets_Fork
HasCASL/ClassAna.hs
gpl-2.0
7,254
0
32
2,246
2,272
1,109
1,163
152
8
{-# LANGUAGE DeriveDataTypeable #-} {- | Module : ./RelationalScheme/Sign.hs Description : signaturefor Relational Schemes Copyright : Dominik Luecke, Uni Bremen 2008 License : GPLv2 or higher, see LICENSE.txt or LIZENZ.txt Maintainer : luecke@informatik.uni-bremen.de Stability : provisional Portability : portable Signature for Relational Schemes -} module RelationalScheme.Sign ( RSIsKey , RSDatatype (..) , RSRawSymbol , RSColumn (..) , RSTable (..) , RSTables (..) , Sign , RSMorphism (..) , RSTMap (..) , emptyRSSign , isRSSubsig , idMor , rsInclusion , uniteSig , comp_rst_mor , RSSymbol (..) , RSSymbolKind (..) , sym_kind ) where import RelationalScheme.Keywords import Common.AS_Annotation import Common.Doc import Common.DocUtils import Common.Id import Common.Result import Common.Utils import Data.Data import qualified Data.Map as Map import qualified Data.Set as Set type RSIsKey = Bool data RSDatatype = RSboolean | RSbinary | RSdate | RSdatetime | RSdecimal | RSfloat | RSinteger | RSstring | RStext | RStime | RStimestamp | RSdouble | RSnonPosInteger | RSnonNegInteger | RSlong | RSPointer deriving (Eq, Ord, Typeable, Data) type RSRawSymbol = Id data RSSymbol = STable Id | -- id of a table SColumn Id -- id of the symbol Id -- id of the table RSDatatype -- datatype of the symbol RSIsKey -- is it a key? deriving (Eq, Ord, Show, Typeable, Data) data RSSymbolKind = STableK | SColumnK deriving (Eq, Ord, Show, Typeable, Data) sym_kind :: RSSymbol -> RSSymbolKind sym_kind (STable _) = STableK sym_kind _ = SColumnK instance Pretty RSSymbolKind where pretty STableK = text "table" pretty SColumnK = text "colum" instance GetRange RSSymbol data RSColumn = RSColumn { c_name :: Id , c_data :: RSDatatype , c_key :: RSIsKey } deriving (Eq, Ord, Show, Typeable, Data) data RSTable = RSTable { t_name :: Id , columns :: [RSColumn] , rsannos :: [Annotation] , t_keys :: Set.Set (Id, RSDatatype) } deriving (Show, Typeable, Data) data RSTables = RSTables { tables :: Set.Set RSTable } deriving (Eq, Ord, Show, Typeable, Data) instance GetRange RSTables isRSSubsig :: RSTables -> RSTables -> Bool isRSSubsig t1 t2 = t1 <= t2 uniteSig :: (Monad m) => RSTables -> RSTables -> m RSTables uniteSig s1 s2 = if s1 `isRSSubsig` s2 || s2 `isRSSubsig` s1 || s1 `isDisjoint` s2 then return $ RSTables $ tables s1 `Set.union` tables s2 else fail $ "Tables " ++ showDoc s1 "\nand " ++ showDoc s2 "\ncannot be united." type Sign = RSTables data RSTMap = RSTMap { col_map :: Map.Map Id Id } deriving (Eq, Ord, Show, Typeable, Data) data RSMorphism = RSMorphism { domain :: RSTables , codomain :: RSTables , table_map :: Map.Map Id Id , column_map :: Map.Map Id RSTMap } deriving (Eq, Ord, Show, Typeable, Data) -- I hope that this works right, I do not want to debug this apply_comp_c_map :: RSTable -> Map.Map Id Id -> RSMorphism -> RSMorphism -> (Id, RSTMap) apply_comp_c_map rst t_map imap imor = let i = t_name rst c2 = column_map imor in case Map.lookup i $ column_map imap of Just iM -> case Map.lookup (Map.findWithDefault i i t_map) c2 of Just iM2 -> let c_set = Map.fromList . map (\ c -> (c_name c, ())) $ columns rst oM = composeMap c_set (col_map iM) (col_map iM2) in (i, RSTMap oM) Nothing -> (i, iM) Nothing -> (i, Map.findWithDefault (RSTMap Map.empty) (Map.findWithDefault i i t_map) c2) -- composition of Rel morphisms comp_rst_mor :: RSMorphism -> RSMorphism -> Result RSMorphism comp_rst_mor mor1 mor2 = let d1 = domain mor1 t1 = Set.toList $ tables d1 t_set = Map.fromList $ map (\ t -> (t_name t, ())) t1 t_map = composeMap t_set (table_map mor1) (table_map mor2) cm_map = Map.fromList $ map (\ x -> apply_comp_c_map x t_map mor1 mor2) t1 in return RSMorphism { domain = d1 , codomain = codomain mor2 , table_map = t_map , column_map = cm_map } emptyRSSign :: RSTables emptyRSSign = RSTables { tables = Set.empty } -- ^ id-morphism for RS idMor :: RSTables -> RSMorphism idMor t = RSMorphism { domain = t , codomain = t , table_map = foldl (\ y x -> Map.insert (t_name x) (t_name x) y) Map.empty $ Set.toList $ tables t , column_map = let makeRSTMap i = foldl (\ y x -> Map.insert (c_name x) (c_name x) y) Map.empty $ columns i in foldl (\ y x -> Map.insert (t_name x) (RSTMap $ makeRSTMap x) y) Map.empty $ Set.toList $ tables t } rsInclusion :: RSTables -> RSTables -> Result RSMorphism rsInclusion t1 t2 = return RSMorphism { domain = t1 , codomain = t2 , table_map = foldl (\ y x -> Map.insert (t_name x) (t_name x) y) Map.empty $ Set.toList $ tables t1 , column_map = let makeRSTMap i = foldl (\ y x -> Map.insert (c_name x) (c_name x) y) Map.empty $ columns i in foldl (\ y x -> Map.insert (t_name x) (RSTMap $ makeRSTMap x) y) Map.empty $ Set.toList $ tables t1 } -- pretty printing stuff instance Pretty RSColumn where pretty c = (if c_key c then keyword rsKey else empty) <+> pretty (c_name c) <+> colon <+> pretty (c_data c) instance Pretty RSTable where pretty t = pretty (t_name t) <> parens (ppWithCommas $ columns t) $+$ printAnnotationList (rsannos t) instance Pretty RSTables where pretty t = keyword rsTables $+$ vcat (map pretty $ Set.toList $ tables t) instance Pretty RSTMap where pretty = pretty . col_map instance Pretty RSMorphism where pretty m = pretty (domain m) $+$ mapsto <+> pretty (codomain m) $+$ pretty (table_map m) $+$ pretty (column_map m) instance Pretty RSSymbol where pretty s = case s of STable i -> pretty i SColumn i _ t k -> pretty $ RSColumn i t k instance Show RSDatatype where show dt = case dt of RSboolean -> rsBool RSbinary -> rsBin RSdate -> rsDate RSdatetime -> rsDatetime RSdecimal -> rsDecimal RSfloat -> rsFloat RSinteger -> rsInteger RSstring -> rsString RStext -> rsText RStime -> rsTime RStimestamp -> rsTimestamp RSdouble -> rsDouble RSnonPosInteger -> rsNonPosInteger RSnonNegInteger -> rsNonNegInteger RSlong -> rsLong RSPointer -> rsPointer instance Pretty RSDatatype where pretty = keyword . show {- we need an explicit instance declaration of Eq and Ord that correctly deals with tables -} instance Ord RSTable where compare t1 t2 = compare (t_name t1, Set.fromList $ columns t1) (t_name t2, Set.fromList $ columns t2) instance Eq RSTable where a == b = compare a b == EQ isDisjoint :: RSTables -> RSTables -> Bool isDisjoint s1 s2 = let t1 = Set.map t_name $ tables s1 t2 = Set.map t_name $ tables s2 in Set.fold (\ x y -> y && (x `Set.notMember` t2)) True t1 && Set.fold (\ x y -> y && (x `Set.notMember` t1)) True t2
spechub/Hets
RelationalScheme/Sign.hs
gpl-2.0
8,467
0
23
3,174
2,361
1,250
1,111
194
3
--The following iterative sequence is defined for the set of positive integers: -- --n → n/2 (n is even) --n → 3n + 1 (n is odd) -- --Using the rule above and starting with 13, we generate the following sequence: --13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 -- --It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. -- --Which starting number, under one million, produces the longest chain? -- -- 837799, 524 length chain -- --NOTE: Once the chain starts the terms are allowed to go above one million. import Data.List import Data.Array import Data.Ord (comparing) main1 :: IO () main1 = print . head $ longestChainTo 1000000 -- fairly slow unless you compile. longestChainTo :: Int -> [Int] longestChainTo n = maximumBy (comparing length) $ map chainOf [1..n] chainOf :: Int -> [Int] chainOf n | n == 1 = [1] | n `mod` 2 == 0 = n:chainOf (n `div` 2) | otherwise = n:chainOf (3 * n + 1) -- Could memoize with an array for performance (from the wiki) syrs :: Int -> Array Int Int syrs n = a where a = listArray (1,n) $ 0:[1 + syr n x | x <- [2..n]] syr n' x = if x' <= n' then a ! x' else 1 + syr n' x' where x' = if even x then x `div` 2 else 3 * x + 1 main2 :: IO () main2 = print $ maximumBy (comparing snd) $ assocs $ syrs 1000000 main = main2
ciderpunx/project_euler_in_haskell
euler014.hs
gpl-2.0
1,478
6
11
357
390
211
179
23
3
{-| Module : $Header$ Copyright : (c) 2014 Edward O'Callaghan License : GPL-2 Maintainer : eocallaghan@alterapraxis.com Stability : provisional Portability : portable -} {-# LANGUAGE Safe #-} module BTS.Version where import qualified GitRev commitHash :: String commitHash = GitRev.hash commitShortHash :: String commitShortHash = take 7 GitRev.hash commitBranch :: String commitBranch = GitRev.branch commitDirty :: Bool commitDirty = GitRev.dirty
victoredwardocallaghan/hbts
src/BTS/Version.hs
gpl-2.0
482
0
6
92
65
39
26
11
1
import Graphics.Rendering.Cairo import Data.List (transpose) import Text.Printf data Point = Point Double Double deriving Show data Vector = Vector Double Double deriving Show data RGBA = RGB Double Double Double | RGBA Double Double Double Double tau = 6.28318530717958647692 uncurry3 f (a,b,c) = f a b c mkVector (Point x0 y0) (Point x1 y1) = Vector (x1 - x0) (y1 - y0) toPoint (Point x0 y0) (Vector dx dy) = Point (x0 + dx) (y0 + dy) toPoint1 (Vector dx dy) = Point dx dy normal (Vector dx dy) = Vector (-dy) dx dist (Point x0 y0) (Point x1 y1) = sqrt ((sqr dx) + (sqr dy)) where sqr x = x * x dx = x1 - x0 dy = y1 - y0 magnitude (Vector dx dy) = dist (Point 0 0) (Point dx dy) darkPoly = [Point 170 50, Point 55 180, Point 75 340, Point 150 180, Point 345 110] unit r (Vector dx dy) = Vector (r * dx / mag) (r * dy / mag) where mag = magnitude (Vector dx dy) rotList n xs = take size (drop (n `mod` size) (cycle xs)) where size = length xs points = darkPoly ptTriplets = transpose [rotList r points | r <- [-1,0,1]] dirVecs2 = map (\[a,b,c] -> [(b,mkVector b a),(b,mkVector b c)]) ptTriplets dirVecs = concat dirVecs2 dirUnits50 = map (\(s,v) -> (s, unit 50 v)) dirVecs dirUnits60 = map (\(s,v) -> (s, unit 65 v)) dirVecs dirUnits = map (\(s,v) -> unit 1.00 v) dirVecs dirAngles = map vectorAngle dirUnits white = RGBA 1.00 1.00 1.00 1.00 black = RGB 0.00 0.00 0.00 red = RGB 0.88 0.29 0.22 orange = RGB 0.98 0.63 0.15 yellow = RGB 0.97 0.85 0.39 green = RGB 0.38 0.74 0.43 blue = RGB 0.33 0.67 0.82 darkGreen = RGB 0.00 0.66 0.52 darkBlue = RGB 0.17 0.51 0.79 fileName = "blue-angles-text.png" vectorAngle (Vector x y) | y >= 0 = acos x | otherwise = -(acos x) setColor (RGBA r g b a) = setSourceRGBA r g b a setColor (RGB r g b) = setColor (RGBA r g b 0.8) drawMarkerAt color (Point x y) = do let bw = 10.0 save translate x y setColor color rectangle (-0.5*bw) (-0.5*bw) bw bw fill restore drawArc color r (Point x y) angle1 angle2 = do setColor color arc x y r angle1 angle2 stroke drawLine color (Point x0 y0) (Point x1 y1) = do setColor color moveTo x0 y0 lineTo x1 y1 stroke drawVector color (Point x y) (Vector dx dy) = do setColor color moveTo x y relLineTo dx dy stroke drawText (((Point x y), (Vector dx dy)), angle) = do moveTo (x+dx-10) (y+dy+5) setColor black showText (printf "%.2f" angle) drawPair (s,v) = do drawVector blue s v paintCanvas = do setSourceRGB 1 1 1 paint mapM_ (drawMarkerAt darkGreen) darkPoly mapM_ drawPair dirUnits50 mapM_ drawText (zip dirUnits60 dirAngles) createPng fileName = do let w = 400 h = 400 img <- createImageSurface FormatARGB32 w h renderWith img paintCanvas surfaceWriteToPNG img fileName liftIO ( do putStrLn "points = " print points putStrLn "ptTriplets = " print ptTriplets putStrLn "dirVecs = " print dirVecs putStrLn "dirAngles = " print dirAngles putStrLn ("Created: " ++ fileName) putStrLn ("Size: " ++ show w ++ "x" ++ show h ++ " pixels") ) main = do createPng fileName
jsavatgy/xroads-game
code/blue-angles-text.hs
gpl-2.0
3,169
0
17
793
1,513
745
768
109
1
--- * doc -- Lines beginning "--- *" are collapsible orgstruct nodes. Emacs users, -- (add-hook 'haskell-mode-hook -- (lambda () (set-variable 'orgstruct-heading-prefix-regexp "--- " t)) -- 'orgstruct-mode) -- and press TAB on nodes to expand/collapse. {-| Some common parsers and helpers used by several readers. Some of these might belong in Hledger.Read.JournalReader or Hledger.Read. -} --- * module {-# LANGUAGE CPP, DeriveDataTypeable, RecordWildCards, NamedFieldPuns, NoMonoLocalBinds, ScopedTypeVariables, FlexibleContexts, TupleSections, OverloadedStrings #-} module Hledger.Read.Common where --- * imports import Prelude () import Prelude.Compat hiding (readFile) import Control.Monad.Compat import Control.Monad.Except (ExceptT(..), runExceptT, throwError) --, catchError) import Control.Monad.State.Strict import Data.Char (isNumber) import Data.Data import Data.Default import Data.Functor.Identity import Data.List.Compat import Data.List.NonEmpty (NonEmpty(..)) import Data.List.Split (wordsBy) import Data.Maybe import Data.Monoid import Data.Text (Text) import qualified Data.Text as T import Data.Time.Calendar import Data.Time.LocalTime import Safe import System.Time (getClockTime) import Text.Megaparsec.Compat import Hledger.Data import Hledger.Utils -- $setup -- | Various options to use when reading journal files. -- Similar to CliOptions.inputflags, simplifies the journal-reading functions. data InputOpts = InputOpts { -- files_ :: [FilePath] mformat_ :: Maybe StorageFormat -- ^ a file/storage format to try, unless overridden -- by a filename prefix. Nothing means try all. ,mrules_file_ :: Maybe FilePath -- ^ a conversion rules file to use (when reading CSV) ,aliases_ :: [String] -- ^ account name aliases to apply ,anon_ :: Bool -- ^ do light anonymisation/obfuscation of the data ,ignore_assertions_ :: Bool -- ^ don't check balance assertions ,new_ :: Bool -- ^ read only new transactions since this file was last read ,new_save_ :: Bool -- ^ save latest new transactions state for next time ,pivot_ :: String -- ^ use the given field's value as the account name } deriving (Show, Data) --, Typeable) instance Default InputOpts where def = definputopts definputopts :: InputOpts definputopts = InputOpts def def def def def def True def rawOptsToInputOpts :: RawOpts -> InputOpts rawOptsToInputOpts rawopts = InputOpts{ -- files_ = map (T.unpack . stripquotes . T.pack) $ listofstringopt "file" rawopts mformat_ = Nothing ,mrules_file_ = maybestringopt "rules-file" rawopts ,aliases_ = map (T.unpack . stripquotes . T.pack) $ listofstringopt "alias" rawopts ,anon_ = boolopt "anon" rawopts ,ignore_assertions_ = boolopt "ignore-assertions" rawopts ,new_ = boolopt "new" rawopts ,new_save_ = True ,pivot_ = stringopt "pivot" rawopts } --- * parsing utils -- | Run a string parser with no state in the identity monad. runTextParser, rtp :: TextParser Identity a -> Text -> Either (ParseError Char MPErr) a runTextParser p t = runParser p "" t rtp = runTextParser -- | Run a journal parser with a null journal-parsing state. runJournalParser, rjp :: Monad m => TextParser m a -> Text -> m (Either (ParseError Char MPErr) a) runJournalParser p t = runParserT p "" t rjp = runJournalParser -- | Run an error-raising journal parser with a null journal-parsing state. runErroringJournalParser, rejp :: Monad m => ErroringJournalParser m a -> Text -> m (Either String a) runErroringJournalParser p t = runExceptT $ runJournalParser (evalStateT p mempty) t >>= either (throwError . parseErrorPretty) return rejp = runErroringJournalParser genericSourcePos :: SourcePos -> GenericSourcePos genericSourcePos p = GenericSourcePos (sourceName p) (fromIntegral . unPos $ sourceLine p) (fromIntegral . unPos $ sourceColumn p) journalSourcePos :: SourcePos -> SourcePos -> GenericSourcePos journalSourcePos p p' = JournalSourcePos (sourceName p) (fromIntegral . unPos $ sourceLine p, fromIntegral $ line') where line' | (unPos $ sourceColumn p') == 1 = unPos (sourceLine p') - 1 | otherwise = unPos $ sourceLine p' -- might be at end of file withat last new-line -- | Given a megaparsec ParsedJournal parser, balance assertion flag, file -- path and file content: parse and post-process a Journal, or give an error. parseAndFinaliseJournal :: ErroringJournalParser IO ParsedJournal -> Bool -> FilePath -> Text -> ExceptT String IO Journal parseAndFinaliseJournal parser assrt f txt = do t <- liftIO getClockTime y <- liftIO getCurrentYear ep <- runParserT (evalStateT parser nulljournal {jparsedefaultyear=Just y}) f txt case ep of Right pj -> case journalFinalise t f txt assrt pj of Right j -> return j Left e -> throwError e Left e -> throwError $ parseErrorPretty e parseAndFinaliseJournal' :: JournalParser Identity ParsedJournal -> Bool -> FilePath -> Text -> ExceptT String IO Journal parseAndFinaliseJournal' parser assrt f txt = do t <- liftIO getClockTime y <- liftIO getCurrentYear let ep = runParser (evalStateT parser nulljournal {jparsedefaultyear=Just y}) f txt case ep of Right pj -> case journalFinalise t f txt assrt pj of Right j -> return j Left e -> throwError e Left e -> throwError $ parseErrorPretty e setYear :: Year -> JournalParser m () setYear y = modify' (\j -> j{jparsedefaultyear=Just y}) getYear :: JournalParser m (Maybe Year) getYear = fmap jparsedefaultyear get setDefaultCommodityAndStyle :: (CommoditySymbol,AmountStyle) -> JournalParser m () setDefaultCommodityAndStyle cs = modify' (\j -> j{jparsedefaultcommodity=Just cs}) getDefaultCommodityAndStyle :: JournalParser m (Maybe (CommoditySymbol,AmountStyle)) getDefaultCommodityAndStyle = jparsedefaultcommodity `fmap` get pushAccount :: AccountName -> JournalParser m () pushAccount acct = modify' (\j -> j{jaccounts = acct : jaccounts j}) pushParentAccount :: AccountName -> JournalParser m () pushParentAccount acct = modify' (\j -> j{jparseparentaccounts = acct : jparseparentaccounts j}) popParentAccount :: JournalParser m () popParentAccount = do j <- get case jparseparentaccounts j of [] -> unexpected (Tokens ('E' :| "nd of apply account block with no beginning")) (_:rest) -> put j{jparseparentaccounts=rest} getParentAccount :: JournalParser m AccountName getParentAccount = fmap (concatAccountNames . reverse . jparseparentaccounts) get addAccountAlias :: MonadState Journal m => AccountAlias -> m () addAccountAlias a = modify' (\(j@Journal{..}) -> j{jparsealiases=a:jparsealiases}) getAccountAliases :: MonadState Journal m => m [AccountAlias] getAccountAliases = fmap jparsealiases get clearAccountAliases :: MonadState Journal m => m () clearAccountAliases = modify' (\(j@Journal{..}) -> j{jparsealiases=[]}) -- getTransactionCount :: MonadState Journal m => m Integer -- getTransactionCount = fmap jparsetransactioncount get -- -- setTransactionCount :: MonadState Journal m => Integer -> m () -- setTransactionCount i = modify' (\j -> j{jparsetransactioncount=i}) -- -- -- | Increment the transaction index by one and return the new value. -- incrementTransactionCount :: MonadState Journal m => m Integer -- incrementTransactionCount = do -- modify' (\j -> j{jparsetransactioncount=jparsetransactioncount j + 1}) -- getTransactionCount journalAddFile :: (FilePath,Text) -> Journal -> Journal journalAddFile f j@Journal{jfiles=fs} = j{jfiles=fs++[f]} -- append, unlike the other fields, even though we do a final reverse, -- to compensate for additional reversal due to including/monoid-concatting -- -- | Terminate parsing entirely, returning the given error message -- -- with the current parse position prepended. -- parserError :: String -> ErroringJournalParser a -- parserError s = do -- pos <- getPosition -- parserErrorAt pos s -- | Terminate parsing entirely, returning the given error message -- with the given parse position prepended. parserErrorAt :: Monad m => SourcePos -> String -> ErroringJournalParser m a parserErrorAt pos s = throwError $ sourcePosPretty pos ++ ":\n" ++ s --- * parsers --- ** transaction bits statusp :: TextParser m Status statusp = choice' [ many spacenonewline >> char '*' >> return Cleared , many spacenonewline >> char '!' >> return Pending , return Unmarked ] <?> "cleared status" codep :: TextParser m String codep = try (do { some spacenonewline; char '(' <?> "codep"; anyChar `manyTill` char ')' } ) <|> return "" descriptionp :: JournalParser m String descriptionp = many (noneOf (";\n" :: [Char])) --- ** dates -- | Parse a date in YYYY/MM/DD format. -- Hyphen (-) and period (.) are also allowed as separators. -- The year may be omitted if a default year has been set. -- Leading zeroes may be omitted. datep :: JournalParser m Day datep = do -- hacky: try to ensure precise errors for invalid dates -- XXX reported error position is not too good -- pos <- genericSourcePos <$> getPosition datestr <- do c <- digitChar cs <- lift $ many $ choice' [digitChar, datesepchar] return $ c:cs let sepchars = nub $ sort $ filter (`elem` datesepchars) datestr when (length sepchars /= 1) $ fail $ "bad date, different separators used: " ++ datestr let dateparts = wordsBy (`elem` datesepchars) datestr currentyear <- getYear [y,m,d] <- case (dateparts,currentyear) of ([m,d],Just y) -> return [show y,m,d] ([_,_],Nothing) -> fail $ "partial date "++datestr++" found, but the current year is unknown" ([y,m,d],_) -> return [y,m,d] _ -> fail $ "bad date: " ++ datestr let maybedate = fromGregorianValid (read y) (read m) (read d) case maybedate of Nothing -> fail $ "bad date: " ++ datestr Just date -> return date <?> "full or partial date" -- | Parse a date and time in YYYY/MM/DD HH:MM[:SS][+-ZZZZ] format. -- Hyphen (-) and period (.) are also allowed as date separators. -- The year may be omitted if a default year has been set. -- Seconds are optional. -- The timezone is optional and ignored (the time is always interpreted as a local time). -- Leading zeroes may be omitted (except in a timezone). datetimep :: JournalParser m LocalTime datetimep = do day <- datep lift $ some spacenonewline h <- some digitChar let h' = read h guard $ h' >= 0 && h' <= 23 char ':' m <- some digitChar let m' = read m guard $ m' >= 0 && m' <= 59 s <- optional $ char ':' >> some digitChar let s' = case s of Just sstr -> read sstr Nothing -> 0 guard $ s' >= 0 && s' <= 59 {- tz <- -} optional $ do plusminus <- oneOf ("-+" :: [Char]) d1 <- digitChar d2 <- digitChar d3 <- digitChar d4 <- digitChar return $ plusminus:d1:d2:d3:d4:"" -- ltz <- liftIO $ getCurrentTimeZone -- let tz' = maybe ltz (fromMaybe ltz . parseTime defaultTimeLocale "%z") tz -- return $ localTimeToUTC tz' $ LocalTime day $ TimeOfDay h' m' (fromIntegral s') return $ LocalTime day $ TimeOfDay h' m' (fromIntegral s') secondarydatep :: Day -> JournalParser m Day secondarydatep primarydate = do char '=' -- kludgy way to use primary date for default year let withDefaultYear d p = do y <- getYear let (y',_,_) = toGregorian d in setYear y' r <- p when (isJust y) $ setYear $ fromJust y -- XXX -- mapM setYear <$> y return r withDefaultYear primarydate datep -- | -- >> parsewith twoorthreepartdatestringp "2016/01/2" -- Right "2016/01/2" -- twoorthreepartdatestringp = do -- n1 <- some digitChar -- c <- datesepchar -- n2 <- some digitChar -- mn3 <- optional $ char c >> some digitChar -- return $ n1 ++ c:n2 ++ maybe "" (c:) mn3 --- ** account names -- | Parse an account name, then apply any parent account prefix and/or account aliases currently in effect. modifiedaccountnamep :: JournalParser m AccountName modifiedaccountnamep = do parent <- getParentAccount aliases <- getAccountAliases a <- lift accountnamep return $ accountNameApplyAliases aliases $ -- XXX accountNameApplyAliasesMemo ? doesn't seem to make a difference joinAccountNames parent a -- | Parse an account name. Account names start with a non-space, may -- have single spaces inside them, and are terminated by two or more -- spaces (or end of input). Also they have one or more components of -- at least one character, separated by the account separator char. -- (This parser will also consume one following space, if present.) accountnamep :: TextParser m AccountName accountnamep = do astr <- do c <- nonspace cs <- striptrailingspace <$> many (nonspace <|> singlespace) return $ c:cs let a = T.pack astr when (accountNameFromComponents (accountNameComponents a) /= a) (fail $ "account name seems ill-formed: "++astr) return a where singlespace = try (do {spacenonewline; do {notFollowedBy spacenonewline; return ' '}}) striptrailingspace "" = "" striptrailingspace s = if last s == ' ' then init s else s -- accountnamechar = notFollowedBy (oneOf "()[]") >> nonspace -- <?> "account name character (non-bracket, non-parenthesis, non-whitespace)" --- ** amounts -- | Parse whitespace then an amount, with an optional left or right -- currency symbol and optional price, or return the special -- "missing" marker amount. spaceandamountormissingp :: Monad m => JournalParser m MixedAmount spaceandamountormissingp = try (do lift $ some spacenonewline (Mixed . (:[])) `fmap` amountp <|> return missingmixedamt ) <|> return missingmixedamt #ifdef TESTS assertParseEqual' :: (Show a, Eq a) => (Either ParseError a) -> a -> Assertion assertParseEqual' parse expected = either (assertFailure.show) (`is'` expected) parse is' :: (Eq a, Show a) => a -> a -> Assertion a `is'` e = assertEqual e a test_spaceandamountormissingp = do assertParseEqual' (parseWithState mempty spaceandamountormissingp " $47.18") (Mixed [usd 47.18]) assertParseEqual' (parseWithState mempty spaceandamountormissingp "$47.18") missingmixedamt assertParseEqual' (parseWithState mempty spaceandamountormissingp " ") missingmixedamt assertParseEqual' (parseWithState mempty spaceandamountormissingp "") missingmixedamt #endif -- | Parse a single-commodity amount, with optional symbol on the left or -- right, optional unit or total price, and optional (ignored) -- ledger-style balance assertion or fixed lot price declaration. amountp :: Monad m => JournalParser m Amount amountp = try leftsymbolamountp <|> try rightsymbolamountp <|> nosymbolamountp #ifdef TESTS test_amountp = do assertParseEqual' (parseWithState mempty amountp "$47.18") (usd 47.18) assertParseEqual' (parseWithState mempty amountp "$1.") (usd 1 `withPrecision` 0) -- ,"amount with unit price" ~: do assertParseEqual' (parseWithState mempty amountp "$10 @ €0.5") (usd 10 `withPrecision` 0 `at` (eur 0.5 `withPrecision` 1)) -- ,"amount with total price" ~: do assertParseEqual' (parseWithState mempty amountp "$10 @@ €5") (usd 10 `withPrecision` 0 @@ (eur 5 `withPrecision` 0)) #endif -- | Parse an amount from a string, or get an error. amountp' :: String -> Amount amountp' s = case runParser (evalStateT (amountp <* eof) mempty) "" (T.pack s) of Right amt -> amt Left err -> error' $ show err -- XXX should throwError -- | Parse a mixed amount from a string, or get an error. mamountp' :: String -> MixedAmount mamountp' = Mixed . (:[]) . amountp' signp :: TextParser m String signp = do sign <- optional $ oneOf ("+-" :: [Char]) return $ case sign of Just '-' -> "-" _ -> "" multiplierp :: TextParser m Bool multiplierp = do multiplier <- optional $ oneOf ("*" :: [Char]) return $ case multiplier of Just '*' -> True _ -> False leftsymbolamountp :: Monad m => JournalParser m Amount leftsymbolamountp = do sign <- lift signp m <- lift multiplierp c <- lift commoditysymbolp sp <- lift $ many spacenonewline (q,prec,mdec,mgrps) <- lift numberp let s = amountstyle{ascommodityside=L, ascommodityspaced=not $ null sp, asprecision=prec, asdecimalpoint=mdec, asdigitgroups=mgrps} p <- priceamountp let applysign = if sign=="-" then negate else id return $ applysign $ Amount c q p s m <?> "left-symbol amount" rightsymbolamountp :: Monad m => JournalParser m Amount rightsymbolamountp = do m <- lift multiplierp (q,prec,mdec,mgrps) <- lift numberp sp <- lift $ many spacenonewline c <- lift commoditysymbolp p <- priceamountp let s = amountstyle{ascommodityside=R, ascommodityspaced=not $ null sp, asprecision=prec, asdecimalpoint=mdec, asdigitgroups=mgrps} return $ Amount c q p s m <?> "right-symbol amount" nosymbolamountp :: Monad m => JournalParser m Amount nosymbolamountp = do m <- lift multiplierp (q,prec,mdec,mgrps) <- lift numberp p <- priceamountp -- apply the most recently seen default commodity and style to this commodityless amount defcs <- getDefaultCommodityAndStyle let (c,s) = case defcs of Just (defc,defs) -> (defc, defs{asprecision=max (asprecision defs) prec}) Nothing -> ("", amountstyle{asprecision=prec, asdecimalpoint=mdec, asdigitgroups=mgrps}) return $ Amount c q p s m <?> "no-symbol amount" commoditysymbolp :: TextParser m CommoditySymbol commoditysymbolp = (quotedcommoditysymbolp <|> simplecommoditysymbolp) <?> "commodity symbol" quotedcommoditysymbolp :: TextParser m CommoditySymbol quotedcommoditysymbolp = do char '"' s <- some $ noneOf (";\n\"" :: [Char]) char '"' return $ T.pack s simplecommoditysymbolp :: TextParser m CommoditySymbol simplecommoditysymbolp = T.pack <$> some (noneOf nonsimplecommoditychars) priceamountp :: Monad m => JournalParser m Price priceamountp = try (do lift (many spacenonewline) char '@' try (do char '@' lift (many spacenonewline) a <- amountp -- XXX can parse more prices ad infinitum, shouldn't return $ TotalPrice a) <|> (do lift (many spacenonewline) a <- amountp -- XXX can parse more prices ad infinitum, shouldn't return $ UnitPrice a)) <|> return NoPrice partialbalanceassertionp :: Monad m => JournalParser m BalanceAssertion partialbalanceassertionp = try (do lift (many spacenonewline) sourcepos <- genericSourcePos <$> lift getPosition char '=' lift (many spacenonewline) a <- amountp -- XXX should restrict to a simple amount return $ Just (a, sourcepos)) <|> return Nothing -- balanceassertion :: Monad m => TextParser m (Maybe MixedAmount) -- balanceassertion = -- try (do -- lift (many spacenonewline) -- string "==" -- lift (many spacenonewline) -- a <- amountp -- XXX should restrict to a simple amount -- return $ Just $ Mixed [a]) -- <|> return Nothing -- http://ledger-cli.org/3.0/doc/ledger3.html#Fixing-Lot-Prices fixedlotpricep :: Monad m => JournalParser m (Maybe Amount) fixedlotpricep = try (do lift (many spacenonewline) char '{' lift (many spacenonewline) char '=' lift (many spacenonewline) a <- amountp -- XXX should restrict to a simple amount lift (many spacenonewline) char '}' return $ Just a) <|> return Nothing -- | Parse a string representation of a number for its value and display -- attributes. -- -- Some international number formats are accepted, eg either period or comma -- may be used for the decimal point, and the other of these may be used for -- separating digit groups in the integer part. See -- http://en.wikipedia.org/wiki/Decimal_separator for more examples. -- -- This returns: the parsed numeric value, the precision (number of digits -- seen following the decimal point), the decimal point character used if any, -- and the digit group style if any. -- numberp :: TextParser m (Quantity, Int, Maybe Char, Maybe DigitGroupStyle) numberp = do -- a number is an optional sign followed by a sequence of digits possibly -- interspersed with periods, commas, or both -- ptrace "numberp" sign <- signp parts <- some $ choice' [some digitChar, some $ char ',', some $ char '.'] dbg8 "numberp parsed" (sign,parts) `seq` return () -- check the number is well-formed and identify the decimal point and digit -- group separator characters used, if any let (numparts, puncparts) = partition numeric parts (ok, mdecimalpoint, mseparator) = case (numparts, puncparts) of ([],_) -> (False, Nothing, Nothing) -- no digits, not ok (_,[]) -> (True, Nothing, Nothing) -- digits with no punctuation, ok (_,[[d]]) -> (True, Just d, Nothing) -- just a single punctuation of length 1, assume it's a decimal point (_,[_]) -> (False, Nothing, Nothing) -- a single punctuation of some other length, not ok (_,_:_:_) -> -- two or more punctuations let (s:ss, d) = (init puncparts, last puncparts) -- the leftmost is a separator and the rightmost may be a decimal point in if any ((/=1).length) puncparts -- adjacent punctuation chars, not ok || any (s/=) ss -- separator chars vary, not ok || head parts == s -- number begins with a separator char, not ok then (False, Nothing, Nothing) else if s == d then (True, Nothing, Just $ head s) -- just one kind of punctuation - must be separators else (True, Just $ head d, Just $ head s) -- separator(s) and a decimal point unless ok $ fail $ "number seems ill-formed: "++concat parts -- get the digit group sizes and digit group style if any let (intparts',fracparts') = span ((/= mdecimalpoint) . Just . head) parts (intparts, fracpart) = (filter numeric intparts', filter numeric fracparts') groupsizes = reverse $ case map length intparts of (a:b:cs) | a < b -> b:cs gs -> gs mgrps = (`DigitGroups` groupsizes) <$> mseparator -- put the parts back together without digit group separators, get the precision and parse the value let int = concat $ "":intparts frac = concat $ "":fracpart precision = length frac int' = if null int then "0" else int frac' = if null frac then "0" else frac quantity = read $ sign++int'++"."++frac' -- this read should never fail return $ dbg8 "numberp quantity,precision,mdecimalpoint,mgrps" (quantity,precision,mdecimalpoint,mgrps) <?> "numberp" where numeric = isNumber . headDef '_' -- test_numberp = do -- let s `is` n = assertParseEqual (parseWithState mempty numberp s) n -- assertFails = assertBool . isLeft . parseWithState mempty numberp -- assertFails "" -- "0" `is` (0, 0, '.', ',', []) -- "1" `is` (1, 0, '.', ',', []) -- "1.1" `is` (1.1, 1, '.', ',', []) -- "1,000.1" `is` (1000.1, 1, '.', ',', [3]) -- "1.00.000,1" `is` (100000.1, 1, ',', '.', [3,2]) -- "1,000,000" `is` (1000000, 0, '.', ',', [3,3]) -- "1." `is` (1, 0, '.', ',', []) -- "1," `is` (1, 0, ',', '.', []) -- ".1" `is` (0.1, 1, '.', ',', []) -- ",1" `is` (0.1, 1, ',', '.', []) -- assertFails "1,000.000,1" -- assertFails "1.000,000.1" -- assertFails "1,000.000.1" -- assertFails "1,,1" -- assertFails "1..1" -- assertFails ".1," -- assertFails ",1." --- ** comments multilinecommentp :: JournalParser m () multilinecommentp = do string "comment" >> lift (many spacenonewline) >> newline go where go = try (eof <|> (string "end comment" >> newline >> return ())) <|> (anyLine >> go) anyLine = anyChar `manyTill` newline emptyorcommentlinep :: JournalParser m () emptyorcommentlinep = do lift (many spacenonewline) >> (linecommentp <|> (lift (many spacenonewline) >> newline >> return "")) return () -- | Parse a possibly multi-line comment following a semicolon. followingcommentp :: JournalParser m Text followingcommentp = -- ptrace "followingcommentp" do samelinecomment <- lift (many spacenonewline) >> (try commentp <|> (newline >> return "")) newlinecomments <- many (try (lift (some spacenonewline) >> commentp)) return $ T.unlines $ samelinecomment:newlinecomments -- | Parse a possibly multi-line comment following a semicolon, and -- any tags and/or posting dates within it. Posting dates can be -- expressed with "date"/"date2" tags and/or bracketed dates. The -- dates are parsed in full here so that errors are reported in the -- right position. Missing years can be inferred if a default date is -- provided. -- -- >>> rejp (followingcommentandtagsp (Just $ fromGregorian 2000 1 2)) "; a:b, date:3/4, [=5/6]" -- Right ("a:b, date:3/4, [=5/6]\n",[("a","b"),("date","3/4")],Just 2000-03-04,Just 2000-05-06) -- -- Year unspecified and no default provided -> unknown year error, at correct position: -- >>> rejp (followingcommentandtagsp Nothing) " ; xxx date:3/4\n ; second line" -- Left ...1:22...partial date 3/4 found, but the current year is unknown... -- -- Date tag value contains trailing text - forgot the comma, confused: -- the syntaxes ? We'll accept the leading date anyway -- >>> rejp (followingcommentandtagsp (Just $ fromGregorian 2000 1 2)) "; date:3/4=5/6" -- Right ("date:3/4=5/6\n",[("date","3/4=5/6")],Just 2000-03-04,Nothing) -- followingcommentandtagsp :: MonadIO m => Maybe Day -> ErroringJournalParser m (Text, [Tag], Maybe Day, Maybe Day) followingcommentandtagsp mdefdate = do -- pdbg 0 "followingcommentandtagsp" -- Parse a single or multi-line comment, starting on this line or the next one. -- Save the starting position and preserve all whitespace for the subsequent re-parsing, -- to get good error positions. startpos <- getPosition commentandwhitespace :: String <- do let commentp' = (:) <$> char ';' <*> anyChar `manyTill` eolof sp1 <- lift (many spacenonewline) l1 <- try (lift commentp') <|> (newline >> return "") ls <- lift . many $ try ((++) <$> some spacenonewline <*> commentp') return $ unlines $ (sp1 ++ l1) : ls let comment = T.pack $ unlines $ map (lstrip . dropWhile (==';') . strip) $ lines commentandwhitespace -- pdbg 0 $ "commentws:"++show commentandwhitespace -- pdbg 0 $ "comment:"++show comment -- Reparse the comment for any tags. tags <- case runTextParser (setPosition startpos >> tagsp) $ T.pack commentandwhitespace of Right ts -> return ts Left e -> throwError $ parseErrorPretty e -- pdbg 0 $ "tags: "++show tags -- Reparse the comment for any posting dates. Use the transaction date for defaults, if provided. epdates <- liftIO $ rejp (setPosition startpos >> postingdatesp mdefdate) $ T.pack commentandwhitespace pdates <- case epdates of Right ds -> return ds Left e -> throwError e -- pdbg 0 $ "pdates: "++show pdates let mdate = headMay $ map snd $ filter ((=="date").fst) pdates mdate2 = headMay $ map snd $ filter ((=="date2").fst) pdates return (comment, tags, mdate, mdate2) -- A transaction/posting comment must start with a semicolon. -- This parser ignores leading whitespace. commentp :: JournalParser m Text commentp = commentStartingWithp ";" -- A line (file-level) comment can start with a semicolon, hash, -- or star (allowing org nodes). This parser ignores leading whitespace. linecommentp :: JournalParser m Text linecommentp = commentStartingWithp ";#*" commentStartingWithp :: [Char] -> JournalParser m Text commentStartingWithp cs = do -- ptrace "commentStartingWith" oneOf cs lift (many spacenonewline) l <- anyChar `manyTill` (lift eolof) optional newline return $ T.pack l --- ** tags -- | Extract any tags (name:value ended by comma or newline) embedded in a string. -- -- >>> commentTags "a b:, c:c d:d, e" -- [("b",""),("c","c d:d")] -- -- >>> commentTags "a [1/1/1] [1/1] [1], [=1/1/1] [=1/1] [=1] [1/1=1/1/1] [1=1/1/1] b:c" -- [("b","c")] -- -- --[("date","1/1/1"),("date","1/1"),("date2","1/1/1"),("date2","1/1"),("date","1/1"),("date2","1/1/1"),("date","1"),("date2","1/1/1")] -- -- >>> commentTags "\na b:, \nd:e, f" -- [("b",""),("d","e")] -- commentTags :: Text -> [Tag] commentTags s = case runTextParser tagsp s of Right r -> r Left _ -> [] -- shouldn't happen -- | Parse all tags found in a string. tagsp :: SimpleTextParser [Tag] tagsp = -- do -- pdbg 0 $ "tagsp" many (try (nontagp >> tagp)) -- | Parse everything up till the first tag. -- -- >>> rtp nontagp "\na b:, \nd:e, f" -- Right "\na " nontagp :: SimpleTextParser String nontagp = -- do -- pdbg 0 "nontagp" -- anyChar `manyTill` (lookAhead (try (tagorbracketeddatetagsp Nothing >> return ()) <|> eof)) anyChar `manyTill` lookAhead (try (void tagp) <|> eof) -- XXX costly ? -- | Tags begin with a colon-suffixed tag name (a word beginning with -- a letter) and are followed by a tag value (any text up to a comma -- or newline, whitespace-stripped). -- -- >>> rtp tagp "a:b b , c AuxDate: 4/2" -- Right ("a","b b") -- tagp :: SimpleTextParser Tag tagp = do -- pdbg 0 "tagp" n <- tagnamep v <- tagvaluep return (n,v) -- | -- >>> rtp tagnamep "a:" -- Right "a" tagnamep :: SimpleTextParser Text tagnamep = -- do -- pdbg 0 "tagnamep" T.pack <$> some (noneOf (": \t\n" :: [Char])) <* char ':' tagvaluep :: TextParser m Text tagvaluep = do -- ptrace "tagvalue" v <- anyChar `manyTill` (void (try (char ',')) <|> eolof) return $ T.pack $ strip $ reverse $ dropWhile (==',') $ reverse $ strip v --- ** posting dates -- | Parse all posting dates found in a string. Posting dates can be -- expressed with date/date2 tags and/or bracketed dates. The dates -- are parsed fully to give useful errors. Missing years can be -- inferred only if a default date is provided. -- postingdatesp :: Monad m => Maybe Day -> ErroringJournalParser m [(TagName,Day)] postingdatesp mdefdate = do -- pdbg 0 $ "postingdatesp" let p = ((:[]) <$> datetagp mdefdate) <|> bracketeddatetagsp mdefdate nonp = many (notFollowedBy p >> anyChar) -- anyChar `manyTill` (lookAhead (try (p >> return ()) <|> eof)) concat <$> many (try (nonp >> p)) --- ** date tags -- | Date tags are tags with name "date" or "date2". Their value is -- parsed as a date, using the provided default date if any for -- inferring a missing year if needed. Any error in date parsing is -- reported and terminates parsing. -- -- >>> rejp (datetagp Nothing) "date: 2000/1/2 " -- Right ("date",2000-01-02) -- -- >>> rejp (datetagp (Just $ fromGregorian 2001 2 3)) "date2:3/4" -- Right ("date2",2001-03-04) -- -- >>> rejp (datetagp Nothing) "date: 3/4" -- Left ...1:9...partial date 3/4 found, but the current year is unknown... -- datetagp :: Monad m => Maybe Day -> ErroringJournalParser m (TagName,Day) datetagp mdefdate = do -- pdbg 0 "datetagp" string "date" n <- fromMaybe "" <$> optional (mptext "2") char ':' startpos <- getPosition v <- lift tagvaluep -- re-parse value as a date. j <- get let ep :: Either (ParseError Char MPErr) Day ep = parseWithState' j{jparsedefaultyear=first3.toGregorian <$> mdefdate} -- The value extends to a comma, newline, or end of file. -- It seems like ignoring any extra stuff following a date -- gives better errors here. (do setPosition startpos datep) -- <* eof) v case ep of Left e -> throwError $ parseErrorPretty e Right d -> return ("date"<>n, d) --- ** bracketed dates -- tagorbracketeddatetagsp :: Monad m => Maybe Day -> TextParser u m [Tag] -- tagorbracketeddatetagsp mdefdate = -- bracketeddatetagsp mdefdate <|> ((:[]) <$> tagp) -- | Parse Ledger-style bracketed posting dates ([DATE=DATE2]), as -- "date" and/or "date2" tags. Anything that looks like an attempt at -- this (a square-bracketed sequence of 0123456789/-.= containing at -- least one digit and one date separator) is also parsed, and will -- throw an appropriate error. -- -- The dates are parsed in full here so that errors are reported in -- the right position. A missing year in DATE can be inferred if a -- default date is provided. A missing year in DATE2 will be inferred -- from DATE. -- -- >>> rejp (bracketeddatetagsp Nothing) "[2016/1/2=3/4]" -- Right [("date",2016-01-02),("date2",2016-03-04)] -- -- >>> rejp (bracketeddatetagsp Nothing) "[1]" -- Left ...not a bracketed date... -- -- >>> rejp (bracketeddatetagsp Nothing) "[2016/1/32]" -- Left ...1:11:...bad date: 2016/1/32... -- -- >>> rejp (bracketeddatetagsp Nothing) "[1/31]" -- Left ...1:6:...partial date 1/31 found, but the current year is unknown... -- -- >>> rejp (bracketeddatetagsp Nothing) "[0123456789/-.=/-.=]" -- Left ...1:15:...bad date, different separators... -- bracketeddatetagsp :: Monad m => Maybe Day -> ErroringJournalParser m [(TagName, Day)] bracketeddatetagsp mdefdate = do -- pdbg 0 "bracketeddatetagsp" char '[' startpos <- getPosition let digits = "0123456789" s <- some (oneOf $ '=':digits++datesepchars) char ']' unless (any (`elem` s) digits && any (`elem` datesepchars) s) $ fail "not a bracketed date" -- looks sufficiently like a bracketed date, now we -- re-parse as dates and throw any errors j <- get let ep :: Either (ParseError Char MPErr) (Maybe Day, Maybe Day) ep = parseWithState' j{jparsedefaultyear=first3.toGregorian <$> mdefdate} (do setPosition startpos md1 <- optional datep maybe (return ()) (setYear.first3.toGregorian) md1 md2 <- optional $ char '=' >> datep eof return (md1,md2) ) (T.pack s) case ep of Left e -> throwError $ parseErrorPretty e Right (md1,md2) -> return $ catMaybes [("date",) <$> md1, ("date2",) <$> md2]
ony/hledger
hledger-lib/Hledger/Read/Common.hs
gpl-3.0
35,166
0
23
8,157
7,488
3,910
3,578
468
10
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE Rank2Types #-} module Language.UHIM.Dictionary.Yaml where import Control.Lens import Control.Lens.TH () import Data.Aeson.TH import Data.Aeson.Types (FromJSON, ToJSON, Value(..), pairs, parseJSON, typeMismatch) import qualified Data.Aeson.Types as AE import qualified Data.ByteString as BS import qualified Data.Map as M import Data.Map (Map) import qualified Data.Text as T import qualified Data.Yaml as Y import qualified Data.Yaml.Include as YI import GHC.Generics import Language.UHIM.Japanese.Prim import Language.UHIM.Japanese.Verb import Language.UHIM.Japanese.Adjective import Language.UHIM.Dictionary.Yaml.Prim data Pron = Pron { pron日呉 :: Maybe JaYomi , pron日漢 :: Maybe JaYomi , pron日訓 :: Maybe JaYomi , pron日慣用 :: Maybe JaYomi , pron日送 :: Maybe JaYomi , pron日迎 :: Maybe JaYomi , pron日音 :: Maybe JaYomi } deriving (Eq, Ord, Show, Read) deriveJSON jsonOptions{fieldLabelModifier = drop 4} ''Pron makeLenses ''Pron emptyPron :: Pron emptyPron = Pron { pron日漢 = Nothing , pron日呉 = Nothing , pron日訓 = Nothing , pron日慣用 = Nothing , pron日送 = Nothing , pron日迎 = Nothing , pron日音 = Nothing } data KanjiShapes = KanjiShapes (Map String String) deriving (Eq, Ord, Show, Read, Generic) instance ToJSON KanjiShapes where toEncoding (KanjiShapes vks) = pairs . mconcat . map (\(k, v)-> T.pack k AE..= v) . M.toList $ vks instance FromJSON KanjiShapes where parseJSON v@(Object _) = do xs <- parseJSON v pure $ KanjiShapes xs parseJSON (String v) = pure . KanjiShapes . M.fromList $ [(commonKanjiKey, T.unpack v)] parseJSON v = typeMismatch "JaYomi" v commonKanjiKey, kyuKanjiKey, shinKanjiKey, jaKanjiKey :: String commonKanjiKey = "共通" kyuKanjiKey = "日舊" shinKanjiKey = "日新" jaKanjiKey = "日" data ShapeClass = JaCommon | JaTrad String | JaSimp String | Other String deriving (Show, Read, Ord, Eq) readShapeKey :: String -> ShapeClass readShapeKey "日" = JaCommon readShapeKey ('日':'舊':v) = JaTrad v readShapeKey ('日':'新':v) = JaSimp v readShapeKey v = Other v defaultKanjiKeyOrder :: String -> String -> Ordering defaultKanjiKeyOrder x y = compare (readShapeKey x) (readShapeKey y) kanYomiKey, goYomiKey, touYomiKey :: String kanyoYomiKey, okuriYomiKey, mukaeYomiKey :: String kanYomiKey = "日漢" goYomiKey = "日呉" touYomiKey = "日唐" kanyoYomiKey = "日慣用" okuriYomiKey = "日送" mukaeYomiKey = "日迎" {- deriveJSON defaultOptions ''KanjiShapes -} data KanjiDeclaration = KanjiDeclaration { kanjiDeclarationDecl體 :: KanjiShapes , kanjiDeclarationDecl音 :: [Pron] , kanjiDeclarationDecl形 :: Maybe (Map String String) , kanjiDeclarationDecl義 :: Maybe [String] , kanjiDeclarationDecl鍵 :: Maybe (Map String String) , kanjiDeclarationDecl頻度 :: Maybe Double , kanjiDeclarationDecl簽 :: Maybe [String] } deriving (Eq, Ord, Show, Read) deriveJSON jsonOptions{fieldLabelModifier = drop 20} ''KanjiDeclaration makeFields ''KanjiDeclaration emptyKanjiDeclaration :: KanjiDeclaration emptyKanjiDeclaration = KanjiDeclaration { kanjiDeclarationDecl體 = KanjiShapes M.empty , kanjiDeclarationDecl音 = [] , kanjiDeclarationDecl形 = Nothing , kanjiDeclarationDecl義 = Nothing , kanjiDeclarationDecl鍵 = Nothing , kanjiDeclarationDecl頻度 = Nothing , kanjiDeclarationDecl簽 = Nothing } data WordConvPair = WordConvPair { wordConvPairDecl字 :: KanjiShapes , wordConvPairDecl讀 :: Pron } deriving (Eq, Ord, Show, Read) deriveJSON jsonOptions{fieldLabelModifier = drop 16} ''WordConvPair makeFields ''WordConvPair data WordDeclaration = WordDeclaration { wordDeclarationDecl聯 :: [WordConvPair] , wordDeclarationDecl義 :: Maybe [String] , wordDeclarationDecl頻度 :: Maybe Double , wordDeclarationDecl簽 :: Maybe [String] } deriving (Eq, Ord, Show, Read) deriveJSON jsonOptions{fieldLabelModifier = drop 19} ''WordDeclaration makeFields ''WordDeclaration data JaVerbDeclaration = JaVerbDeclaration { jaVerbDeclarationDecl類 :: [JaVerbConjugation] , jaVerbDeclarationDecl聯 :: [WordConvPair] , jaVerbDeclarationDecl義 :: Maybe [String] , jaVerbDeclarationDecl頻度 :: Maybe Double , jaVerbDeclarationDecl簽 :: Maybe [String] } deriving (Eq, Ord, Show, Read) deriveJSON jsonOptions{fieldLabelModifier = drop 21} ''JaVerbDeclaration makeFields ''JaVerbDeclaration data JaAdjDeclaration = JaAdjDeclaration { jaAdjDeclarationDecl類 :: [JaAdjConjugation] , jaAdjDeclarationDecl聯 :: [WordConvPair] , jaAdjDeclarationDecl義 :: Maybe [String] , jaAdjDeclarationDecl頻度 :: Maybe Double , jaAdjDeclarationDecl簽 :: Maybe [String] } deriving (Eq, Ord, Show, Read) deriveJSON jsonOptions{fieldLabelModifier = drop 20} ''JaAdjDeclaration makeFields ''JaAdjDeclaration data DictEntry = Entry字 KanjiDeclaration | Entry語 WordDeclaration | Entry日動詞 JaVerbDeclaration | Entry日形容詞 JaAdjDeclaration | Entry日副詞 WordDeclaration deriving (Show, Read, Eq, Ord) deriveJSON jsonOptions{constructorTagModifier = drop 5, sumEncoding = ObjectWithSingleField} ''DictEntry makePrisms ''DictEntry instance HasDecl義 DictEntry (Maybe [String]) where decl義 = lens g s where g (Entry字 d) = d ^. decl義 g (Entry語 d) = d ^. decl義 g (Entry日動詞 d) = d ^. decl義 g (Entry日形容詞 d) = d ^. decl義 g (Entry日副詞 d) = d ^. decl義 s (Entry字 d) v = Entry字 $ d & decl義 .~ v s (Entry語 d) v = Entry語 $ d & decl義 .~ v s (Entry日動詞 d) v = Entry日動詞 $ d & decl義 .~ v s (Entry日形容詞 d) v = Entry日形容詞 $ d & decl義 .~ v s (Entry日副詞 d) v = Entry日副詞 $ d & decl義 .~ v instance HasDecl頻度 DictEntry (Maybe Double) where decl頻度 = lens g s where g (Entry字 d) = d ^. decl頻度 g (Entry語 d) = d ^. decl頻度 g (Entry日動詞 d) = d ^. decl頻度 g (Entry日形容詞 d) = d ^. decl頻度 g (Entry日副詞 d) = d ^. decl頻度 s (Entry字 d) v = Entry字 $ d & decl頻度 .~ v s (Entry語 d) v = Entry語 $ d & decl頻度 .~ v s (Entry日動詞 d) v = Entry日動詞 $ d & decl頻度 .~ v s (Entry日形容詞 d) v = Entry日形容詞 $ d & decl頻度 .~ v s (Entry日副詞 d) v = Entry日副詞 $ d & decl頻度 .~ v instance HasDecl簽 DictEntry (Maybe [String]) where decl簽 = lens g s where g (Entry字 d) = d ^. decl簽 g (Entry語 d) = d ^. decl簽 g (Entry日動詞 d) = d ^. decl簽 g (Entry日形容詞 d) = d ^. decl簽 g (Entry日副詞 d) = d ^. decl簽 s (Entry字 d) v = Entry字 $ d & decl簽 .~ v s (Entry語 d) v = Entry語 $ d & decl簽 .~ v s (Entry日動詞 d) v = Entry日動詞 $ d & decl簽 .~ v s (Entry日形容詞 d) v = Entry日形容詞 $ d & decl簽 .~ v s (Entry日副詞 d) v = Entry日副詞 $ d & decl簽 .~ v type Position = [(String, Integer)] type Dictionary = [(Position, DictEntry)] readFromFile :: FilePath -> IO (Either Y.ParseException Dictionary) readFromFile fp = do es <- YI.decodeFileEither fp return $ fmap (map (\(i, x) -> ([(fp, i)], x)) . zip [0..]) es readFromBS :: String -> BS.ByteString -> Either Y.ParseException Dictionary readFromBS fp str = do es <- Y.decodeEither' str return $ map (\(i, x) -> ([(fp, i)], x)) $ zip [0..] es writeToFile :: Dictionary -> FilePath -> IO () writeToFile d fp = Y.encodeFile fp $ map snd d writeToBS :: Dictionary -> BS.ByteString writeToBS = Y.encode . map snd entryLabel :: DictEntry -> Maybe [String] entryLabel d = d ^. decl簽 frequency :: DictEntry -> Maybe Double frequency d = d ^. decl頻度 -- Utils convExtToTrad :: Char -> Char convExtToTrad '\x1b000' = 'エ' convExtToTrad '\x1b001' = 'え' convExtToTrad x = x extractShinKana :: JaYomi -> Maybe Kana extractShinKana (NonChange x) = Just x extractShinKana (Changed "" _) = Nothing extractShinKana (Changed x _) = Just x extractKyuKana :: JaYomi -> Maybe Kana extractKyuKana (NonChange x) = Just $ map convExtToTrad x extractKyuKana (Changed _ "") = Nothing extractKyuKana (Changed _ x) = Just $ map convExtToTrad x extractExtKyuKana :: JaYomi -> Maybe Kana extractExtKyuKana (NonChange x) = Just x extractExtKyuKana (Changed _ "") = Nothing extractExtKyuKana (Changed _ x) = Just x extractShinKanji :: KanjiShapes -> Maybe Kanji extractShinKanji (KanjiShapes vks) = mconcat $ map (`M.lookup` vks) [ shinKanjiKey , jaKanjiKey , commonKanjiKey ] extractKyuKanji :: KanjiShapes -> Maybe Kanji extractKyuKanji (KanjiShapes vks) = mconcat $ map (`M.lookup` vks) [ kyuKanjiKey , jaKanjiKey , commonKanjiKey ] extractJaPronList :: Pron -> [(String, JaYomi)] extractJaPronList p@Pron{pron日漢 = Just x} = ("日漢", x) : extractJaPronList (p {pron日漢 = Nothing}) extractJaPronList p@Pron{pron日呉 = Just x} = ("日呉", x) : extractJaPronList (p {pron日呉 = Nothing}) extractJaPronList p@Pron{pron日慣用 = Just x} = ("日慣用", x) : extractJaPronList (p {pron日慣用 = Nothing}) extractJaPronList p@Pron{pron日訓 = Just x} = ("日呉", x) : extractJaPronList (p {pron日訓 = Nothing}) extractJaPronList p@Pron{pron日送 = Just x} = ("日送", x) : extractJaPronList (p {pron日送 = Nothing}) extractJaPronList p@Pron{pron日迎 = Just x} = ("日迎", x) : extractJaPronList (p {pron日迎 = Nothing}) extractJaPronList p@Pron{pron日音 = Just x} = ("日音", x) : extractJaPronList (p {pron日音 = Nothing}) extractJaPronList _ = [] extractJaPron :: Pron -> Maybe JaYomi extractJaPron (Pron (Just x) Nothing Nothing Nothing Nothing Nothing Nothing) = Just x extractJaPron (Pron Nothing (Just x) Nothing Nothing Nothing Nothing Nothing) = Just x extractJaPron (Pron Nothing Nothing (Just x) Nothing Nothing Nothing Nothing) = Just x extractJaPron (Pron Nothing Nothing Nothing (Just x) Nothing Nothing Nothing) = Just x extractJaPron (Pron Nothing Nothing Nothing Nothing (Just x) Nothing Nothing) = Just x extractJaPron (Pron Nothing Nothing Nothing Nothing Nothing (Just x) Nothing) = Just x extractJaPron (Pron Nothing Nothing Nothing Nothing Nothing Nothing (Just x)) = Just x extractJaPron _ = Nothing extractJaProns :: Pron -> [JaYomi] extractJaProns = map snd . extractJaPronList okurigana :: JaYomi -> WordConvPair okurigana s = WordConvPair { wordConvPairDecl字 = KanjiShapes $ M.singleton jaKanjiKey kanaMark , wordConvPairDecl讀 = emptyPron { pron日送 = Just s } } nonOkuriganaMark :: String nonOkuriganaMark = "$" kanaMark :: String kanaMark = "$$"
na4zagin3/uhim-dict
src/Language/UHIM/Dictionary/Yaml.hs
gpl-3.0
12,818
313
16
3,826
3,923
2,092
1,831
238
1
{-# LANGUAGE DeriveDataTypeable #-} module Flatten3 where import Data.Typeable (Typeable) import List import HipSpec import Prelude hiding ((++)) import Control.Monad data Tree a = B (Tree a) (Tree a) | Leaf a deriving (Typeable,Eq,Ord,Show) instance Arbitrary a => Arbitrary (Tree a) where arbitrary = sized arbTree where arbTree s = frequency [ (1,liftM Leaf arbitrary) , (s,liftM2 B (arbTree (s`div`2)) (arbTree (s`div`2))) ] instance Names (Tree a) where names _ = ["p","q","r"] -- Koen's suggestion: pick up the commonly used names from the source code :) flat1 :: Tree a -> [a] flat1 (B l r) = flat1 l ++ flat1 r flat1 (Leaf a) = [a] flat2 :: Tree a -> [a] flat2 (B (B l r) q) = flat2 (B l (B r q)) flat2 (B (Leaf x) r) = x : flat2 r flat2 (Leaf x) = [x] flat3 :: [Tree a] -> [a] flat3 [] = [] flat3 (Leaf x:xs) = x:flat3 xs flat3 (B l r:xs) = flat3 (l:r:xs) prop_flat3 x = flat3 [x] =:= flat2 x
danr/hipspec
examples/Flatten3.hs
gpl-3.0
970
0
15
240
491
260
231
28
1
module RLESpec where import Control.Monad import Test.Hspec import Test.Hspec.QuickCheck import Test.QuickCheck import Compression import Data.ByteString.Lazy as L import ArbInstances oneByte :: ByteString oneByte = L.pack [42] thousandSameBytes :: ByteString thousandSameBytes = L.replicate 1000 42 compress = caCompress rleAlg extract = caExtract rleAlg spec :: Spec spec = do modifyMaxSuccess (const 1000) $ describe "Message isomorphism" $ do it "compresses empty to empty" $ compress (pure L.empty) `shouldReturn` L.empty it "extracts empty to empty" $ extract (pure L.empty) `shouldReturn` L.empty it "isomorphic on 1 byte sequence of 42" $ extract (compress (pure oneByte)) `shouldReturn` oneByte it "isomorphic on 1000 byte sequence of 42" $ extract (compress (pure thousandSameBytes)) `shouldReturn` thousandSameBytes it "has isomorphic property on random ByteString with repeatable chunks" $ property $ \(ArbByteStringRepChunks s) -> extract (compress (pure s)) `shouldReturn` s it "has isomorphic property on randomly random ByteString" $ property $ \(ArbRandByteString s) -> extract (compress (pure s)) `shouldReturn` s it "shouldn't break on byte boundary" $ do let s = L.replicate 258 0 extract (compress (pure s)) `shouldReturn` s
kravitz/har
test/RLESpec.hs
gpl-3.0
1,330
0
18
255
385
196
189
32
1
{-# LANGUAGE OverlappingInstances, FlexibleInstances,FlexibleContexts #-} -- Does not yet check put/get properties! module MonadState where import Hip.Prelude import Prelude (Int,Eq) -- Poor man's equality instance Eq b => Eq (Int -> b) type State s a = s -> (a,s) uncurry f (a,b) = f a b uncurry' f t = f (fst t) (snd t) fst (a,b) = a snd (a,b) = b bind_strict :: State s a -> (a -> State s b) -> State s b (m `bind_strict` f) s = uncurry f (m s) bind_lazy :: State s a -> (a -> State s b) -> State s b (m `bind_lazy` f) s = uncurry' f (m s) bind_let :: State s a -> (a -> State s b) -> State s b (m `bind_let` f) s = let a = fst (m s) s' = snd (m s) in f a s' bind_strict_lambda :: State s a -> (a -> State s b) -> State s b m `bind_strict_lambda` f = \s -> uncurry f (m s) bind_lazy_lambda :: State s a -> (a -> State s b) -> State s b m `bind_lazy_lambda` f = \s -> uncurry' f (m s) bind_let_lambda :: State s a -> (a -> State s b) -> State s b m `bind_let_lambda` f = \s -> let a = fst (m s) s' = snd (m s) in f a s' return :: a -> State s a return x s = (x,s) returnl :: a -> State s a returnl x = \s -> (x,s) -- Bind without lambda -------------------------------------------------------- prop_return_left_strict :: (s -> (a,s)) -> Prop (s -> (a,s)) prop_return_left_strict f = (f `bind_strict` return) =:= f prop_return_left_lazy :: (s -> (a,s)) -> Prop (s -> (a,s)) prop_return_left_lazy f = (f `bind_lazy` return) =:= f prop_return_left_let :: (s -> (a,s)) -> Prop (s -> (a,s)) prop_return_left_let f = (f `bind_let` return) =:= f prop_return_right_lazy :: (a -> s -> (a,s)) -> a -> Prop (s -> (a,s)) prop_return_right_lazy f a = (return a `bind_lazy` f) =:= f a prop_return_right_strict :: (a -> s -> (a,s)) -> a -> Prop (s -> (a,s)) prop_return_right_strict f a = (return a `bind_strict` f) =:= f a prop_return_right_let :: (a -> s -> (a,s)) -> a -> Prop (s -> (a,s)) prop_return_right_let f a = (return a `bind_let` f) =:= f a prop_assoc_strict :: (s -> (a,s)) -> (a -> s -> (b,s)) -> (b -> s -> (c,s)) -> Prop (s -> (c,s)) prop_assoc_strict m f g = ((m `bind_strict` f) `bind_strict` g) =:= (m `bind_strict` (\x -> f x `bind_strict` g)) prop_assoc_lazy :: (s -> (a,s)) -> (a -> s -> (b,s)) -> (b -> s -> (c,s)) -> Prop (s -> (c,s)) prop_assoc_lazy m f g = ((m `bind_lazy` f) `bind_lazy` g) =:= (m `bind_lazy` (\x -> f x `bind_lazy` g)) prop_assoc_let :: (s -> (a,s)) -> (a -> s -> (b,s)) -> (b -> s -> (c,s)) -> Prop (s -> (c,s)) prop_assoc_let m f g = ((m `bind_let` f) `bind_let` g) =:= (m `bind_let` (\x -> f x `bind_let` g)) -- Lambda definition ---------------------------------------------------------- prop_return_left_strict_lambda :: (s -> (a,s)) -> Prop (s -> (a,s)) prop_return_left_strict_lambda f = (f `bind_strict_lambda` return) =:= f prop_return_left_lazy_lambda :: (s -> (a,s)) -> Prop (s -> (a,s)) prop_return_left_lazy_lambda f = (f `bind_lazy_lambda` return) =:= f prop_return_left_let_lambda :: (s -> (a,s)) -> Prop (s -> (a,s)) prop_return_left_let_lambda f = (f `bind_let_lambda` return) =:= f prop_return_right_strict_lambda :: (a -> s -> (a,s)) -> a -> Prop (s -> (a,s)) prop_return_right_strict_lambda f a = (return a `bind_strict_lambda` f) =:= f a prop_return_right_lazy_lambda :: (a -> s -> (a,s)) -> a -> Prop (s -> (a,s)) prop_return_right_lazy_lambda f a = (return a `bind_lazy_lambda` f) =:= f a prop_return_right_let_lambda :: (a -> s -> (a,s)) -> a -> Prop (s -> (a,s)) prop_return_right_let_lambda f a = (return a `bind_let_lambda` f) =:= f a prop_assoc_strict_lambda :: (s -> (a,s)) -> (a -> s -> (b,s)) -> (b -> s -> (c,s)) -> Prop (s -> (c,s)) prop_assoc_strict_lambda m f g = ((m `bind_strict_lambda` f) `bind_strict_lambda` g) =:= (m `bind_strict_lambda` (\x -> f x `bind_strict_lambda` g)) prop_assoc_lazy_lambda :: (s -> (a,s)) -> (a -> s -> (b,s)) -> (b -> s -> (c,s)) -> Prop (s -> (c,s)) prop_assoc_lazy_lambda m f g = ((m `bind_lazy_lambda` f) `bind_lazy_lambda` g) =:= (m `bind_lazy_lambda` (\x -> f x `bind_lazy_lambda` g)) prop_assoc_let_lambda :: (s -> (a,s)) -> (a -> s -> (b,s)) -> (b -> s -> (c,s)) -> Prop (s -> (c,s)) prop_assoc_let_lambda m f g = ((m `bind_let_lambda` f) `bind_let_lambda` g) =:= (m `bind_let_lambda` (\x -> f x `bind_let_lambda` g)) -- And the same with return as lambda ----------------------------------------- prop_return_lambda_left_strict :: (s -> (a,s)) -> Prop (s -> (a,s)) prop_return_lambda_left_strict f = (f `bind_strict` returnl) =:= f prop_return_lambda_left_lazy :: (s -> (a,s)) -> Prop (s -> (a,s)) prop_return_lambda_left_lazy f = (f `bind_lazy` returnl) =:= f prop_return_lambda_right_lazy :: (a -> s -> (a,s)) -> a -> Prop (s -> (a,s)) prop_return_lambda_right_lazy f a = (returnl a `bind_lazy` f) =:= f a prop_return_lambda_right_strict :: (a -> s -> (a,s)) -> a -> Prop (s -> (a,s)) prop_return_lambda_right_strict f a = (returnl a `bind_strict` f) =:= f a prop_return_lambda_left_let :: (s -> (a,s)) -> Prop (s -> (a,s)) prop_return_lambda_left_let f = (f `bind_let` returnl) =:= f prop_return_lambda_right_let :: (a -> s -> (a,s)) -> a -> Prop (s -> (a,s)) prop_return_lambda_right_let f a = (returnl a `bind_let` f) =:= f a prop_return_lambda_left_strict_lambda :: (s -> (a,s)) -> Prop (s -> (a,s)) prop_return_lambda_left_strict_lambda f = (f `bind_strict_lambda` returnl) =:= f prop_return_lambda_left_lazy_lambda :: (s -> (a,s)) -> Prop (s -> (a,s)) prop_return_lambda_left_lazy_lambda f = (f `bind_lazy_lambda` returnl) =:= f prop_return_lambda_left_let_lambda :: (s -> (a,s)) -> Prop (s -> (a,s)) prop_return_lambda_left_let_lambda f = (f `bind_let_lambda` returnl) =:= f prop_return_lambda_right_strict_lambda :: (a -> s -> (a,s)) -> a -> Prop (s -> (a,s)) prop_return_lambda_right_strict_lambda f a = (returnl a `bind_strict_lambda` f) =:= f a prop_return_lambda_right_lazy_lambda :: (a -> s -> (a,s)) -> a -> Prop (s -> (a,s)) prop_return_lambda_right_lazy_lambda f a = (returnl a `bind_lazy_lambda` f) =:= f a prop_return_lambda_right_let_lambda :: (a -> s -> (a,s)) -> a -> Prop (s -> (a,s)) prop_return_lambda_right_let_lambda f a = (returnl a `bind_let_lambda` f) =:= f a -- Let's also try something with kliesli-composition (>=>) :: (a -> State s b) -> (b -> State s c) -> a -> State s c m >=> n = \a s -> uncurry n (m a s) prop_right_kliesli :: (a -> s -> (a,s)) -> Prop (a -> s -> (a,s)) prop_right_kliesli f = (f >=> return) =:= f prop_left_kliesli :: (a -> s -> (a,s)) -> Prop (a -> s -> (a,s)) prop_left_kliesli f = (return >=> f) =:= f prop_assoc_kliesli :: (a -> s -> (b,s)) -> (b -> s -> (c,s)) -> (c -> s -> (d,s)) -> Prop (a -> s -> (d,s)) prop_assoc_kliesli f g h = ((f >=> g) >=> h) =:= (f >=> (g >=> h)) (>==>) :: (a -> State s b) -> (b -> State s c) -> a -> State s c m >==> n = \a s -> uncurry' n (m a s) prop_right_kliesli_strict :: (a -> s -> (a,s)) -> Prop (a -> s -> (a,s)) prop_right_kliesli_strict f = (f >==> return) =:= f prop_left_kliesli_strict :: (a -> s -> (a,s)) -> Prop (a -> s -> (a,s)) prop_left_kliesli_strict f = (return >==> f) =:= f prop_assoc_kliesli_strict :: (a -> s -> (b,s)) -> (b -> s -> (c,s)) -> (c -> s -> (d,s)) -> Prop (a -> s -> (d,s)) prop_assoc_kliesli_strict f g h = ((f >==> g) >==> h) =:= (f >==> (g >==> h)) -- Let's join and fmap these beasts ------------------------------------------- id x = x fmap_strict_lambda f m = m `bind_strict_lambda` (\x -> return (f x)) join_strict_lambda n = n `bind_strict_lambda` id fmap_lazy_lambda f m = m `bind_lazy_lambda` (\x -> return (f x)) join_lazy_lambda n = n `bind_lazy_lambda` id fmap_let_lambda f m = m `bind_let_lambda` (\x -> return (f x)) join_let_lambda n = n `bind_let_lambda` id fmap_strict f m = m `bind_strict` (\x -> return (f x)) join_strict n = n `bind_strict` id fmap_lazy f m = m `bind_lazy` (\x -> return (f x)) join_lazy n = n `bind_lazy` id fmap_let f m = m `bind_let` (\x -> return (f x)) join_let n = n `bind_let` id prop_fmap_id_strict :: Prop ((s -> (a,s)) -> (s -> (a,s))) prop_fmap_id_strict = fmap_strict id =:= id prop_fmap_id_lazy :: Prop ((s -> (a,s)) -> (s -> (a,s))) prop_fmap_id_lazy = fmap_lazy id =:= id prop_fmap_id_let :: Prop ((s -> (a,s)) -> (s -> (a,s))) prop_fmap_id_let = fmap_let id =:= id prop_fmap_id_strict_lambda :: Prop ((s -> (a,s)) -> (s -> (a,s))) prop_fmap_id_strict_lambda = fmap_strict_lambda id =:= id prop_fmap_id_lazy_lambda :: Prop ((s -> (a,s)) -> (s -> (a,s))) prop_fmap_id_lazy_lambda = fmap_lazy_lambda id =:= id prop_fmap_id_let_lambda :: Prop ((s -> (a,s)) -> (s -> (a,s))) prop_fmap_id_let_lambda = fmap_let_lambda id =:= id -- Let's just go with the non-lambda definition (f . g) x = f (g x) prop_fmap_comp_strict :: (b -> c) -> (a -> b) -> Prop ((s -> (a,s)) -> s -> (c,s)) prop_fmap_comp_strict f g = fmap_strict (f . g) =:= fmap_strict f . fmap_strict g prop_fmap_comp_lazy :: (b -> c) -> (a -> b) -> Prop ((s -> (a,s)) -> s -> (c,s)) prop_fmap_comp_lazy f g = fmap_lazy (f . g) =:= fmap_lazy f . fmap_lazy g prop_fmap_comp_let :: (b -> c) -> (a -> b) -> Prop ((s -> (a,s)) -> s -> (c,s)) prop_fmap_comp_let f g = fmap_let (f . g) =:= fmap_let f . fmap_let g prop_fmap_comp_strict_lambda :: (b -> c) -> (a -> b) -> Prop ((s -> (a,s)) -> s -> (c,s)) prop_fmap_comp_strict_lambda f g = fmap_strict_lambda (f . g) =:= fmap_strict_lambda f . fmap_strict_lambda g prop_fmap_comp_lazy_lambda :: (b -> c) -> (a -> b) -> Prop ((s -> (a,s)) -> s -> (c,s)) prop_fmap_comp_lazy_lambda f g = fmap_lazy_lambda (f . g) =:= fmap_lazy_lambda f . fmap_lazy_lambda g prop_fmap_comp_let_lambda :: (b -> c) -> (a -> b) -> Prop ((s -> (a,s)) -> s -> (c,s)) prop_fmap_comp_let_lambda f g = fmap_let_lambda (f . g) =:= fmap_let_lambda f . fmap_let_lambda g main = do quickCheck (printTestCase "prop_return_left_strict" (prop_return_left_strict :: (Int -> (Int,Int)) -> Prop (Int -> (Int,Int)))) quickCheck (printTestCase "prop_return_right_strict" (prop_return_right_strict :: (Int -> Int -> (Int,Int)) -> Int -> Prop (Int -> (Int,Int)))) quickCheck (printTestCase "prop_assoc_strict" (prop_assoc_strict :: (Int -> (Int,Int)) -> (Int -> Int -> (Int,Int)) -> (Int -> Int -> (Int,Int)) -> Prop (Int -> (Int,Int)))) quickCheck (printTestCase "prop_return_left_lazy" (prop_return_left_lazy :: (Int -> (Int,Int)) -> Prop (Int -> (Int,Int)))) quickCheck (printTestCase "prop_return_right_lazy" (prop_return_right_lazy :: (Int -> Int -> (Int,Int)) -> Int -> Prop (Int -> (Int,Int)))) quickCheck (printTestCase "prop_assoc_lazy" (prop_assoc_lazy :: (Int -> (Int,Int)) -> (Int -> Int -> (Int,Int)) -> (Int -> Int -> (Int,Int)) -> Prop (Int -> (Int,Int)))) quickCheck (printTestCase "prop_return_left_let" (prop_return_left_let :: (Int -> (Int,Int)) -> Prop (Int -> (Int,Int)))) quickCheck (printTestCase "prop_return_right_let" (prop_return_right_let :: (Int -> Int -> (Int,Int)) -> Int -> Prop (Int -> (Int,Int)))) quickCheck (printTestCase "prop_assoc_let" (prop_assoc_let :: (Int -> (Int,Int)) -> (Int -> Int -> (Int,Int)) -> (Int -> Int -> (Int,Int)) -> Prop (Int -> (Int,Int)))) quickCheck (printTestCase "prop_return_left_strict_lambda" (prop_return_left_strict_lambda :: (Int -> (Int,Int)) -> Prop (Int -> (Int,Int)))) quickCheck (printTestCase "prop_return_right_strict_lambda" (prop_return_right_strict_lambda :: (Int -> Int -> (Int,Int)) -> Int -> Prop (Int -> (Int,Int)))) quickCheck (printTestCase "prop_assoc_strict_lambda" (prop_assoc_strict_lambda :: (Int -> (Int,Int)) -> (Int -> Int -> (Int,Int)) -> (Int -> Int -> (Int,Int)) -> Prop (Int -> (Int,Int)))) quickCheck (printTestCase "prop_return_left_lazy_lambda" (prop_return_left_lazy_lambda :: (Int -> (Int,Int)) -> Prop (Int -> (Int,Int)))) quickCheck (printTestCase "prop_return_right_lazy_lambda" (prop_return_right_lazy_lambda :: (Int -> Int -> (Int,Int)) -> Int -> Prop (Int -> (Int,Int)))) quickCheck (printTestCase "prop_assoc_lazy_lambda" (prop_assoc_lazy_lambda :: (Int -> (Int,Int)) -> (Int -> Int -> (Int,Int)) -> (Int -> Int -> (Int,Int)) -> Prop (Int -> (Int,Int)))) quickCheck (printTestCase "prop_return_left_let_lambda" (prop_return_left_let_lambda :: (Int -> (Int,Int)) -> Prop (Int -> (Int,Int)))) quickCheck (printTestCase "prop_return_right_let_lambda" (prop_return_right_let_lambda :: (Int -> Int -> (Int,Int)) -> Int -> Prop (Int -> (Int,Int)))) quickCheck (printTestCase "prop_assoc_let_lambda" (prop_assoc_let_lambda :: (Int -> (Int,Int)) -> (Int -> Int -> (Int,Int)) -> (Int -> Int -> (Int,Int)) -> Prop (Int -> (Int,Int)))) quickCheck (printTestCase "prop_return_lambda_left_strict" (prop_return_lambda_left_strict :: (Int -> (Int,Int)) -> Prop (Int -> (Int,Int)))) quickCheck (printTestCase "prop_return_lambda_right_strict" (prop_return_lambda_right_strict :: (Int -> Int -> (Int,Int)) -> Int -> Prop (Int -> (Int,Int)))) quickCheck (printTestCase "prop_return_lambda_left_lazy" (prop_return_lambda_left_lazy :: (Int -> (Int,Int)) -> Prop (Int -> (Int,Int)))) quickCheck (printTestCase "prop_return_lambda_right_lazy" (prop_return_lambda_right_lazy :: (Int -> Int -> (Int,Int)) -> Int -> Prop (Int -> (Int,Int)))) quickCheck (printTestCase "prop_return_lambda_left_let" (prop_return_lambda_left_let :: (Int -> (Int,Int)) -> Prop (Int -> (Int,Int)))) quickCheck (printTestCase "prop_return_lambda_right_let" (prop_return_lambda_right_let :: (Int -> Int -> (Int,Int)) -> Int -> Prop (Int -> (Int,Int)))) quickCheck (printTestCase "prop_return_lambda_left_strict_lambda" (prop_return_lambda_left_strict_lambda :: (Int -> (Int,Int)) -> Prop (Int -> (Int,Int)))) quickCheck (printTestCase "prop_return_lambda_right_strict_lambda" (prop_return_lambda_right_strict_lambda :: (Int -> Int -> (Int,Int)) -> Int -> Prop (Int -> (Int,Int)))) quickCheck (printTestCase "prop_return_lambda_left_lazy_lambda" (prop_return_lambda_left_lazy_lambda :: (Int -> (Int,Int)) -> Prop (Int -> (Int,Int)))) quickCheck (printTestCase "prop_return_lambda_right_lazy_lambda" (prop_return_lambda_right_lazy_lambda :: (Int -> Int -> (Int,Int)) -> Int -> Prop (Int -> (Int,Int)))) quickCheck (printTestCase "prop_return_lambda_left_let_lambda" (prop_return_lambda_left_let_lambda :: (Int -> (Int,Int)) -> Prop (Int -> (Int,Int)))) quickCheck (printTestCase "prop_return_lambda_right_let_lambda" (prop_return_lambda_right_let_lambda :: (Int -> Int -> (Int,Int)) -> Int -> Prop (Int -> (Int,Int)))) quickCheck (printTestCase "prop_right_kliesli" (prop_right_kliesli :: (Int -> Int -> (Int,Int)) -> Prop (Int -> Int -> (Int,Int)))) quickCheck (printTestCase "prop_left_kliesli" (prop_left_kliesli :: (Int -> Int -> (Int,Int)) -> Prop (Int -> Int -> (Int,Int)))) quickCheck (printTestCase "prop_assoc_kliesli" (prop_assoc_kliesli :: (Int -> Int -> (Int,Int)) -> (Int -> Int -> (Int,Int)) -> (Int -> Int -> (Int,Int)) -> Prop (Int -> Int -> (Int,Int)))) quickCheck (printTestCase "prop_fmap_id_strict_lambda" (prop_fmap_id_strict_lambda :: Prop ((Int -> (Int,Int)) -> (Int -> (Int,Int))))) quickCheck (printTestCase "prop_fmap_id_lazy_lambda" (prop_fmap_id_lazy_lambda :: Prop ((Int -> (Int,Int)) -> (Int -> (Int,Int))))) quickCheck (printTestCase "prop_fmap_id_let_lambda" (prop_fmap_id_let_lambda :: Prop ((Int -> (Int,Int)) -> (Int -> (Int,Int))))) quickCheck (printTestCase "prop_fmap_id_strict" (prop_fmap_id_strict :: Prop ((Int -> (Int,Int)) -> (Int -> (Int,Int))))) quickCheck (printTestCase "prop_fmap_id_lazy" (prop_fmap_id_lazy :: Prop ((Int -> (Int,Int)) -> (Int -> (Int,Int))))) quickCheck (printTestCase "prop_fmap_id_let" (prop_fmap_id_let :: Prop ((Int -> (Int,Int)) -> (Int -> (Int,Int))))) quickCheck (printTestCase "prop_fmap_comp_strict_lambda" (prop_fmap_comp_strict_lambda :: (Int -> Int) -> (Int -> Int) -> Prop ((Int -> (Int,Int)) -> Int -> (Int,Int)))) quickCheck (printTestCase "prop_fmap_comp_lazy_lambda" (prop_fmap_comp_lazy_lambda :: (Int -> Int) -> (Int -> Int) -> Prop ((Int -> (Int,Int)) -> Int -> (Int,Int)))) quickCheck (printTestCase "prop_fmap_comp_let_lambda" (prop_fmap_comp_let_lambda :: (Int -> Int) -> (Int -> Int) -> Prop ((Int -> (Int,Int)) -> Int -> (Int,Int)))) quickCheck (printTestCase "prop_fmap_comp_strict" (prop_fmap_comp_strict :: (Int -> Int) -> (Int -> Int) -> Prop ((Int -> (Int,Int)) -> Int -> (Int,Int)))) quickCheck (printTestCase "prop_fmap_comp_lazy" (prop_fmap_comp_lazy :: (Int -> Int) -> (Int -> Int) -> Prop ((Int -> (Int,Int)) -> Int -> (Int,Int)))) quickCheck (printTestCase "prop_fmap_comp_let" (prop_fmap_comp_let :: (Int -> Int) -> (Int -> Int) -> Prop ((Int -> (Int,Int)) -> Int -> (Int,Int)))) {- more properties for later :) return . f = fmap f . return join . fmap join = join . join join . fmap return = join . return = id join . fmap (fmap f) = fmap f . join -}
danr/hipspec
examples/old-examples/hip/MonadState.hs
gpl-3.0
16,849
4
18
2,814
7,930
4,373
3,557
-1
-1
module CCTK.Group ( Group(..), (<>), i, ) where import Control.Monad (join) import Data.Monoid infixl 6 |/| infixl 7 |^| i :: Group g => g i = mempty class Monoid g => Group g where inv :: g -> g (|^|) :: g -> Integer -> g _ |^| 0 = i g |^| 1 = g g |^| n | n < 0 = inv $ g |^| (0-n) | odd n = g <> (g |^| (n-1)) | otherwise = join (<>) (g |^| (n `quot` 2)) (|/|) :: g -> g -> g a |/| b = a <> inv b (|\|) :: g -> g -> g a |\| b = inv a <> b
maugier/cctk
src/CCTK/Group.hs
gpl-3.0
530
0
12
208
292
156
136
22
1
{-# LANGUAGE DeriveGeneric #-} module Types where import Vector import Keyboard (Key(..)) --import FRP.Helm.Color (rgba, Color, yellow, red, blue, green) import Graphics.UI.SDL.Types (Texture (..), Rect (..)) import Foreign.Ptr (Ptr(..)) import Data.Serialize (Serialize) import GHC.Generics (Generic) -- data Color = Color deriving Generic instance Serialize Color -- type Time = Double type Image = FilePath data Event = HitEnemy !Enemy | SpawnEnemy !Position | AttackEnemy !Enemy type Events = [Event] type EnemyID = Int data EnemyState = Alive | Dead | Stunned deriving (Eq, Generic) instance Serialize EnemyState data Enemy = Enemy { eimg :: !Image , epos :: !Position , estate :: !EnemyState , eid :: !EnemyID , highlight :: !(Maybe Color) } deriving (Generic) instance Serialize Enemy instance Eq Enemy where e == f = eid e == eid f type Enemies = [Enemy] data PlayerAction = Waiting | Flying { flyFrom :: !Position , flyTo :: !Enemy , flyDuration :: !Time , flyElapsed :: !Time} deriving (Eq, Generic) instance Serialize PlayerAction data Player = Player { pimg :: !Image , ppos :: !Position , zoneRadius :: !Double , pact :: !PlayerAction } deriving (Generic) instance Serialize Player data Zone = UpZone | DownZone | LeftZone | RightZone | OutZone deriving (Eq, Enum)
ZSarver/DungeonDash
src/Types.hs
gpl-3.0
1,645
0
11
571
418
241
177
73
0
{-# LANGUAGE OverloadedLists, OverloadedStrings, QuasiQuotes, ScopedTypeVariables #-} module Nirum.PackageSpec where import Data.Either (isLeft, isRight) import Data.Proxy (Proxy (Proxy)) import Data.Text import System.IO.Error (isDoesNotExistError) import qualified Data.SemVer as SV import System.FilePath ((</>)) import Test.Hspec.Meta import Text.InterpolatedString.Perl6 (qq) import qualified Text.Parsec.Error as PE import Text.Parsec.Pos (sourceColumn, sourceLine) import Nirum.Constructs.Module import Nirum.Constructs.ModulePath (ModulePath) import Nirum.Package hiding (modules, target) import Nirum.Package.Metadata ( Metadata ( Metadata , authors , target , version , description , license , keywords ) , MetadataError (FormatError) , Target (targetName) ) import Nirum.Package.MetadataSpec (DummyTarget (DummyTarget)) import Nirum.Package.ModuleSet ( ImportError (MissingModulePathError) , fromList ) import Nirum.Package.ModuleSetSpec (validModules) import Nirum.Parser (parseFile) import Nirum.Targets.Python (Python (Python)) import Nirum.Targets.Python.CodeGen (minimumRuntime) createPackage :: Metadata t -> [(ModulePath, Module)] -> Package t createPackage metadata' modules' = case fromList modules' of Right ms -> Package metadata' ms Left e -> error $ "errored: " ++ show e createValidPackage :: t -> Package t createValidPackage t = createPackage Metadata { version = SV.initial , authors = [] , description = Nothing , license = Nothing , keywords = [] , target = t } validModules spec :: Spec spec = do testPackage (Python "nirum-examples" minimumRuntime [] classifiers') testPackage DummyTarget where classifiers' :: [Text] classifiers' = [ "Development Status :: 3 - Alpha" , append "License :: OSI Approved :: " "GNU General Public License v3 or later (GPLv3+)" ] testPackage :: forall t . Target t => t -> Spec testPackage target' = do let targetName' = targetName (Proxy :: Proxy t) validPackage = createValidPackage target' describe [qq|Package (target: $targetName')|] $ do specify "resolveModule" $ do resolveModule ["foo"] validPackage `shouldBe` Just (Module [] $ Just "foo") resolveModule ["foo", "bar"] validPackage `shouldBe` Just (Module [] $ Just "foo.bar") resolveModule ["qux"] validPackage `shouldBe` Just (Module [] $ Just "qux") resolveModule ["baz"] validPackage `shouldBe` Nothing describe "scanPackage" $ do it "returns Package value when all is well" $ do let path = "." </> "examples" package' <- scanPackage' path package' `shouldSatisfy` isRight let Right package = package' Right blockchainM <- parseFile (path </> "blockchain.nrm") Right builtinsM <- parseFile (path </> "builtins.nrm") Right productM <- parseFile (path </> "product.nrm") Right shapesM <- parseFile (path </> "shapes.nrm") Right countriesM <- parseFile (path </> "countries.nrm") Right addressM <- parseFile (path </> "address.nrm") Right pdfServiceM <- parseFile (path </> "pdf-service.nrm") Right geoM <- parseFile (path </> "geo.nrm") let modules = [ (["blockchain"], blockchainM) , (["builtins"], builtinsM) , (["geo"], geoM) , (["product"], productM) , (["shapes"], shapesM) , (["countries"], countriesM) , (["address"], addressM) , (["pdf-service"], pdfServiceM) ] :: [(ModulePath, Module)] metadata' = Metadata { version = SV.version 0 3 0 [] [] , authors = [] , description = Nothing , license = Nothing , keywords = [] , target = target' } metadata package `shouldBe` metadata' package `shouldBe` createPackage metadata' modules let testDir = "." </> "test" it "returns ScanError if the directory lacks package.toml" $ do scanResult <- scanPackage' $ testDir </> "scan_error" scanResult `shouldSatisfy` isLeft let Left (ScanError filePath ioError') = scanResult filePath `shouldBe` testDir </> "scan_error" </> "package.toml" ioError' `shouldSatisfy` isDoesNotExistError it "returns MetadataError if the package.toml is invalid" $ do scanResult <- scanPackage' $ testDir </> "metadata_error" scanResult `shouldSatisfy` isLeft let Left (MetadataError (FormatError e)) = scanResult sourceLine (PE.errorPos e) `shouldBe` 3 sourceColumn (PE.errorPos e) `shouldBe` 14 it "returns ImportError if a module imports an absent module" $ do scanResult <- scanPackage' $ testDir </> "import_error" scanResult `shouldSatisfy` isLeft let Left (ImportError l) = scanResult l `shouldBe` [MissingModulePathError ["import_error"] ["foo"]] specify "scanModules" $ do let path = "." </> "examples" mods' <- scanModules path mods' `shouldBe` [ (["blockchain"], path </> "blockchain.nrm") , (["builtins"], path </> "builtins.nrm") , (["geo"], path </> "geo.nrm") , (["product"], path </> "product.nrm") , (["shapes"], path </> "shapes.nrm") , (["countries"], path </> "countries.nrm") , (["address"], path </> "address.nrm") , (["pdf-service"], path </> "pdf-service.nrm") ] where scanPackage' :: FilePath -> IO (Either PackageError (Package t)) scanPackage' = scanPackage
spoqa/nirum
test/Nirum/PackageSpec.hs
gpl-3.0
7,140
0
23
2,896
1,584
863
721
129
2
module Example.Eg44 (eg44) where import Graphics.Radian import ExampleUtils eg44 :: IO Html eg44 = do let x = [0, 2 * pi / 100 .. 2 * pi] plot = ((p1 ||| p2) === (p3 ||| p4)) # [height.=800, aspect.=1, strokeWidth.=2, axisXLabel.="Time"] p1 = Plot [Lines x (map sin x)] # [title.="Top left", stroke.="red", axisYLabel.="sin(x)"] p2 = Plot [Lines x (map cos x)] # [title.="Top right", stroke.="blue", axisYLabel.="cos(x)"] p3 = Plot [Lines x (map cos x)] # [title.="Bottom left", stroke.="blue", axisYLabel.="cos(x)"] p4 = Plot [Lines x (map sin x)] # [title.="Bottom right", stroke.="red", axisYLabel.="sin(x)"] source = exampleSource "Eg44.hs" return [shamlet| <h3> Example 44 (layout #3) <p> Laid out as a 2 &times; 2 grid (manual): ^{plot} ^{source} |]
openbrainsrc/hRadian
examples/Example/Eg44.hs
mpl-2.0
874
10
15
236
344
182
162
-1
-1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Calendar.Events.Instances -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Returns instances of the specified recurring event. -- -- /See:/ <https://developers.google.com/google-apps/calendar/firstapp Calendar API Reference> for @calendar.events.instances@. module Network.Google.Resource.Calendar.Events.Instances ( -- * REST Resource EventsInstancesResource -- * Creating a Request , eventsInstances , EventsInstances -- * Request Lenses , eCalendarId , eTimeMin , eShowDeleted , eOriginalStart , eMaxAttendees , ePageToken , eTimeZone , eMaxResults , eAlwaysIncludeEmail , eTimeMax , eEventId ) where import Network.Google.AppsCalendar.Types import Network.Google.Prelude -- | A resource alias for @calendar.events.instances@ method which the -- 'EventsInstances' request conforms to. type EventsInstancesResource = "calendar" :> "v3" :> "calendars" :> Capture "calendarId" Text :> "events" :> Capture "eventId" Text :> "instances" :> QueryParam "timeMin" DateTime' :> QueryParam "showDeleted" Bool :> QueryParam "originalStart" Text :> QueryParam "maxAttendees" (Textual Int32) :> QueryParam "pageToken" Text :> QueryParam "timeZone" Text :> QueryParam "maxResults" (Textual Int32) :> QueryParam "alwaysIncludeEmail" Bool :> QueryParam "timeMax" DateTime' :> QueryParam "alt" AltJSON :> Get '[JSON] Events -- | Returns instances of the specified recurring event. -- -- /See:/ 'eventsInstances' smart constructor. data EventsInstances = EventsInstances' { _eCalendarId :: !Text , _eTimeMin :: !(Maybe DateTime') , _eShowDeleted :: !(Maybe Bool) , _eOriginalStart :: !(Maybe Text) , _eMaxAttendees :: !(Maybe (Textual Int32)) , _ePageToken :: !(Maybe Text) , _eTimeZone :: !(Maybe Text) , _eMaxResults :: !(Maybe (Textual Int32)) , _eAlwaysIncludeEmail :: !(Maybe Bool) , _eTimeMax :: !(Maybe DateTime') , _eEventId :: !Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'EventsInstances' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'eCalendarId' -- -- * 'eTimeMin' -- -- * 'eShowDeleted' -- -- * 'eOriginalStart' -- -- * 'eMaxAttendees' -- -- * 'ePageToken' -- -- * 'eTimeZone' -- -- * 'eMaxResults' -- -- * 'eAlwaysIncludeEmail' -- -- * 'eTimeMax' -- -- * 'eEventId' eventsInstances :: Text -- ^ 'eCalendarId' -> Text -- ^ 'eEventId' -> EventsInstances eventsInstances pECalendarId_ pEEventId_ = EventsInstances' { _eCalendarId = pECalendarId_ , _eTimeMin = Nothing , _eShowDeleted = Nothing , _eOriginalStart = Nothing , _eMaxAttendees = Nothing , _ePageToken = Nothing , _eTimeZone = Nothing , _eMaxResults = Nothing , _eAlwaysIncludeEmail = Nothing , _eTimeMax = Nothing , _eEventId = pEEventId_ } -- | Calendar identifier. To retrieve calendar IDs call the calendarList.list -- method. If you want to access the primary calendar of the currently -- logged in user, use the \"primary\" keyword. eCalendarId :: Lens' EventsInstances Text eCalendarId = lens _eCalendarId (\ s a -> s{_eCalendarId = a}) -- | Lower bound (inclusive) for an event\'s end time to filter by. Optional. -- The default is not to filter by end time. Must be an RFC3339 timestamp -- with mandatory time zone offset. eTimeMin :: Lens' EventsInstances (Maybe UTCTime) eTimeMin = lens _eTimeMin (\ s a -> s{_eTimeMin = a}) . mapping _DateTime -- | Whether to include deleted events (with status equals \"cancelled\") in -- the result. Cancelled instances of recurring events will still be -- included if singleEvents is False. Optional. The default is False. eShowDeleted :: Lens' EventsInstances (Maybe Bool) eShowDeleted = lens _eShowDeleted (\ s a -> s{_eShowDeleted = a}) -- | The original start time of the instance in the result. Optional. eOriginalStart :: Lens' EventsInstances (Maybe Text) eOriginalStart = lens _eOriginalStart (\ s a -> s{_eOriginalStart = a}) -- | The maximum number of attendees to include in the response. If there are -- more than the specified number of attendees, only the participant is -- returned. Optional. eMaxAttendees :: Lens' EventsInstances (Maybe Int32) eMaxAttendees = lens _eMaxAttendees (\ s a -> s{_eMaxAttendees = a}) . mapping _Coerce -- | Token specifying which result page to return. Optional. ePageToken :: Lens' EventsInstances (Maybe Text) ePageToken = lens _ePageToken (\ s a -> s{_ePageToken = a}) -- | Time zone used in the response. Optional. The default is the time zone -- of the calendar. eTimeZone :: Lens' EventsInstances (Maybe Text) eTimeZone = lens _eTimeZone (\ s a -> s{_eTimeZone = a}) -- | Maximum number of events returned on one result page. By default the -- value is 250 events. The page size can never be larger than 2500 events. -- Optional. eMaxResults :: Lens' EventsInstances (Maybe Int32) eMaxResults = lens _eMaxResults (\ s a -> s{_eMaxResults = a}) . mapping _Coerce -- | Deprecated and ignored. A value will always be returned in the email -- field for the organizer, creator and attendees, even if no real email -- address is available (i.e. a generated, non-working value will be -- provided). eAlwaysIncludeEmail :: Lens' EventsInstances (Maybe Bool) eAlwaysIncludeEmail = lens _eAlwaysIncludeEmail (\ s a -> s{_eAlwaysIncludeEmail = a}) -- | Upper bound (exclusive) for an event\'s start time to filter by. -- Optional. The default is not to filter by start time. Must be an RFC3339 -- timestamp with mandatory time zone offset. eTimeMax :: Lens' EventsInstances (Maybe UTCTime) eTimeMax = lens _eTimeMax (\ s a -> s{_eTimeMax = a}) . mapping _DateTime -- | Recurring event identifier. eEventId :: Lens' EventsInstances Text eEventId = lens _eEventId (\ s a -> s{_eEventId = a}) instance GoogleRequest EventsInstances where type Rs EventsInstances = Events type Scopes EventsInstances = '["https://www.googleapis.com/auth/calendar", "https://www.googleapis.com/auth/calendar.events", "https://www.googleapis.com/auth/calendar.events.readonly", "https://www.googleapis.com/auth/calendar.readonly"] requestClient EventsInstances'{..} = go _eCalendarId _eEventId _eTimeMin _eShowDeleted _eOriginalStart _eMaxAttendees _ePageToken _eTimeZone _eMaxResults _eAlwaysIncludeEmail _eTimeMax (Just AltJSON) appsCalendarService where go = buildClient (Proxy :: Proxy EventsInstancesResource) mempty
brendanhay/gogol
gogol-apps-calendar/gen/Network/Google/Resource/Calendar/Events/Instances.hs
mpl-2.0
7,925
0
24
1,991
1,182
682
500
163
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.CivicInfo.Representatives.RepresentativeInfoByAddress -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Looks up political geography and representative information for a single -- address. -- -- /See:/ <https://developers.google.com/civic-information/ Google Civic Information API Reference> for @civicinfo.representatives.representativeInfoByAddress@. module Network.Google.Resource.CivicInfo.Representatives.RepresentativeInfoByAddress ( -- * REST Resource RepresentativesRepresentativeInfoByAddressResource -- * Creating a Request , representativesRepresentativeInfoByAddress , RepresentativesRepresentativeInfoByAddress -- * Request Lenses , rribaXgafv , rribaRoles , rribaUploadProtocol , rribaAccessToken , rribaUploadType , rribaAddress , rribaIncludeOffices , rribaLevels , rribaCallback ) where import Network.Google.CivicInfo.Types import Network.Google.Prelude -- | A resource alias for @civicinfo.representatives.representativeInfoByAddress@ method which the -- 'RepresentativesRepresentativeInfoByAddress' request conforms to. type RepresentativesRepresentativeInfoByAddressResource = "civicinfo" :> "v2" :> "representatives" :> QueryParam "$.xgafv" Xgafv :> QueryParams "roles" RepresentativesRepresentativeInfoByAddressRoles :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "address" Text :> QueryParam "includeOffices" Bool :> QueryParams "levels" RepresentativesRepresentativeInfoByAddressLevels :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] RepresentativeInfoResponse -- | Looks up political geography and representative information for a single -- address. -- -- /See:/ 'representativesRepresentativeInfoByAddress' smart constructor. data RepresentativesRepresentativeInfoByAddress = RepresentativesRepresentativeInfoByAddress' { _rribaXgafv :: !(Maybe Xgafv) , _rribaRoles :: !(Maybe [RepresentativesRepresentativeInfoByAddressRoles]) , _rribaUploadProtocol :: !(Maybe Text) , _rribaAccessToken :: !(Maybe Text) , _rribaUploadType :: !(Maybe Text) , _rribaAddress :: !(Maybe Text) , _rribaIncludeOffices :: !Bool , _rribaLevels :: !(Maybe [RepresentativesRepresentativeInfoByAddressLevels]) , _rribaCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'RepresentativesRepresentativeInfoByAddress' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rribaXgafv' -- -- * 'rribaRoles' -- -- * 'rribaUploadProtocol' -- -- * 'rribaAccessToken' -- -- * 'rribaUploadType' -- -- * 'rribaAddress' -- -- * 'rribaIncludeOffices' -- -- * 'rribaLevels' -- -- * 'rribaCallback' representativesRepresentativeInfoByAddress :: RepresentativesRepresentativeInfoByAddress representativesRepresentativeInfoByAddress = RepresentativesRepresentativeInfoByAddress' { _rribaXgafv = Nothing , _rribaRoles = Nothing , _rribaUploadProtocol = Nothing , _rribaAccessToken = Nothing , _rribaUploadType = Nothing , _rribaAddress = Nothing , _rribaIncludeOffices = True , _rribaLevels = Nothing , _rribaCallback = Nothing } -- | V1 error format. rribaXgafv :: Lens' RepresentativesRepresentativeInfoByAddress (Maybe Xgafv) rribaXgafv = lens _rribaXgafv (\ s a -> s{_rribaXgafv = a}) -- | A list of office roles to filter by. Only offices fulfilling one of -- these roles will be returned. Divisions that don\'t contain a matching -- office will not be returned. rribaRoles :: Lens' RepresentativesRepresentativeInfoByAddress [RepresentativesRepresentativeInfoByAddressRoles] rribaRoles = lens _rribaRoles (\ s a -> s{_rribaRoles = a}) . _Default . _Coerce -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). rribaUploadProtocol :: Lens' RepresentativesRepresentativeInfoByAddress (Maybe Text) rribaUploadProtocol = lens _rribaUploadProtocol (\ s a -> s{_rribaUploadProtocol = a}) -- | OAuth access token. rribaAccessToken :: Lens' RepresentativesRepresentativeInfoByAddress (Maybe Text) rribaAccessToken = lens _rribaAccessToken (\ s a -> s{_rribaAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). rribaUploadType :: Lens' RepresentativesRepresentativeInfoByAddress (Maybe Text) rribaUploadType = lens _rribaUploadType (\ s a -> s{_rribaUploadType = a}) -- | The address to look up. May only be specified if the field ocdId is not -- given in the URL rribaAddress :: Lens' RepresentativesRepresentativeInfoByAddress (Maybe Text) rribaAddress = lens _rribaAddress (\ s a -> s{_rribaAddress = a}) -- | Whether to return information about offices and officials. If false, -- only the top-level district information will be returned. rribaIncludeOffices :: Lens' RepresentativesRepresentativeInfoByAddress Bool rribaIncludeOffices = lens _rribaIncludeOffices (\ s a -> s{_rribaIncludeOffices = a}) -- | A list of office levels to filter by. Only offices that serve at least -- one of these levels will be returned. Divisions that don\'t contain a -- matching office will not be returned. rribaLevels :: Lens' RepresentativesRepresentativeInfoByAddress [RepresentativesRepresentativeInfoByAddressLevels] rribaLevels = lens _rribaLevels (\ s a -> s{_rribaLevels = a}) . _Default . _Coerce -- | JSONP rribaCallback :: Lens' RepresentativesRepresentativeInfoByAddress (Maybe Text) rribaCallback = lens _rribaCallback (\ s a -> s{_rribaCallback = a}) instance GoogleRequest RepresentativesRepresentativeInfoByAddress where type Rs RepresentativesRepresentativeInfoByAddress = RepresentativeInfoResponse type Scopes RepresentativesRepresentativeInfoByAddress = '[] requestClient RepresentativesRepresentativeInfoByAddress'{..} = go _rribaXgafv (_rribaRoles ^. _Default) _rribaUploadProtocol _rribaAccessToken _rribaUploadType _rribaAddress (Just _rribaIncludeOffices) (_rribaLevels ^. _Default) _rribaCallback (Just AltJSON) civicInfoService where go = buildClient (Proxy :: Proxy RepresentativesRepresentativeInfoByAddressResource) mempty
brendanhay/gogol
gogol-civicinfo/gen/Network/Google/Resource/CivicInfo/Representatives/RepresentativeInfoByAddress.hs
mpl-2.0
7,631
0
20
1,753
977
568
409
151
1
{-# LANGUAGE OverloadedStrings, MultiParamTypeClasses #-} module Blog.Common ( AppSettings, newAppSettings, BlogSettings, AdminSettings , verifyCSRF, httpManager, remoteIp , baseDomain, withBlogDomain, currentBlog, dashboard , routeAny , module Web.Simple.PostgreSQL ) where import Control.Monad import Control.Monad.IO.Class import Data.Aeson (Value(Object), toJSON) import qualified Data.ByteString as S import qualified Data.ByteString.Char8 as S8 import qualified Data.HashMap.Strict as H import Data.Maybe import Data.Monoid import Data.Text.Encoding (decodeUtf8) import Network.HTTP.Client (Manager, newManager, defaultManagerSettings) import Network.Socket import Web.Simple import Web.Simple.PostgreSQL import Web.Simple.Templates import Web.Simple.Session import Blog.Helpers import Blog.Models.Blog (Blog, findByUsername) import Blog.Models.Hostname (findByHostname) import System.Environment (getEnv) data AppSettings = AppSettings { appDB :: PostgreSQLConn , appHttpManager :: Manager , appBaseDomain :: S8.ByteString , appSession :: Maybe Session } data BlogSettings = BlogSettings { blogAppSettings :: AppSettings , blogBlog :: Blog } data AdminSettings = AdminSettings { adminAppSettings :: AppSettings , adminBlog :: Blog } newAppSettings :: IO AppSettings newAppSettings = do envBaseDomain <- S8.pack <$> getEnv "BASE_DOMAIN" db <- createPostgreSQLConn mgr <- newManager defaultManagerSettings return $ AppSettings { appDB = db , appSession = Nothing , appBaseDomain = envBaseDomain , appHttpManager = mgr } instance HasPostgreSQL AppSettings where postgreSQLConn = appDB instance HasSession AppSettings where getSession = appSession setSession sess = do cs <- controllerState putState $ cs { appSession = Just sess } instance HasTemplates IO AppSettings where defaultLayout = Just <$> getTemplate "layouts/main.html" functionMap = return $ defaultFunctionMap <> helperFunctions baseDomain :: Controller AppSettings S8.ByteString baseDomain = appBaseDomain <$> controllerState instance HasPostgreSQL BlogSettings where postgreSQLConn = appDB . blogAppSettings instance HasSession BlogSettings where getSession = appSession . blogAppSettings setSession sess = do cs <- controllerState putState $ cs { blogAppSettings = (blogAppSettings cs) { appSession = Just sess } } instance HasTemplates IO BlogSettings where defaultLayout = Just <$> getTemplate "layouts/blog.html" functionMap = return $ defaultFunctionMap <> helperFunctions layoutObject pageContent pageValue = do (Object obj) <- defaultLayoutObject pageContent pageValue blog <- currentBlog return $ Object $ H.insert "blog" (toJSON blog) obj instance HasPostgreSQL AdminSettings where postgreSQLConn = appDB . adminAppSettings instance HasSession AdminSettings where getSession = appSession . adminAppSettings setSession sess = do cs <- controllerState putState $ cs { adminAppSettings = (adminAppSettings cs) { appSession = Just sess } } instance HasTemplates IO AdminSettings where defaultLayout = Just <$> getTemplate "layouts/admin.html" functionMap = return $ defaultFunctionMap <> helperFunctions layoutObject pageContent pageValue = do (Object obj) <- defaultLayoutObject pageContent pageValue blog <- currentBlog domain <- decodeUtf8 <$> (appBaseDomain . adminAppSettings) <$> controllerState return $ Object $ H.insert "base_domain" (toJSON domain) $ H.insert "blog" (toJSON blog) obj class HasBlog s where currentBlog :: Controller s Blog instance HasBlog BlogSettings where currentBlog = blogBlog <$> controllerState instance HasBlog AdminSettings where currentBlog = adminBlog <$> controllerState verifyCSRF :: HasSession s => [(S.ByteString, S.ByteString)] -> Controller s () verifyCSRF params = do sessionCsrf <- sessionLookup "csrf_token" let formCsrf = lookup "csrf_token" params when (any isNothing [sessionCsrf, formCsrf] || sessionCsrf /= formCsrf) $ respond badRequest httpManager :: Controller BlogSettings Manager httpManager = (appHttpManager . blogAppSettings) <$> controllerState withBlogDomain :: Controller BlogSettings () -> Controller AppSettings () withBlogDomain act = do mhostname <- requestHeader "Host" case mhostname of Nothing -> return () Just hostname -> do domain <- baseDomain let (username, hDomain) = S8.break (== '.') hostname if hDomain == '.' `S8.cons` domain then do mblog <- withConnection $ \conn -> liftIO $ findByUsername conn $ decodeUtf8 username switchState mblog else do mblog <- withConnection $ \conn -> liftIO $ findByHostname conn $ decodeUtf8 hostname switchState mblog where switchState :: Maybe Blog -> Controller AppSettings () switchState mblog = do case mblog of Just blog -> do st <- controllerState req <- request let newst = BlogSettings { blogAppSettings = st, blogBlog = blog } (eres, s) <- liftIO $ runController act newst req putState $ blogAppSettings s case eres of Left resp -> respond resp Right a -> return a Nothing -> return () dashboard :: Controller AdminSettings () -> Controller AppSettings () dashboard act = do mbloggerId <- sessionLookup "blogger_id" case mbloggerId of Just blogId -> do mblog <- withConnection $ \conn -> liftIO $ findRow conn $ read $ S8.unpack $ blogId case mblog of Just blog -> do st <- controllerState req <- request let newst = AdminSettings { adminAppSettings = st, adminBlog = blog } (eres, s) <- liftIO $ runController act newst req putState $ adminAppSettings s case eres of Left resp -> respond resp Right a -> return a Nothing -> return () _ -> return () remoteIp :: Controller s S.ByteString remoteIp = do req <- request let hdrs = requestHeaders req mrip = listToMaybe . catMaybes $ [lookup "x-real-ip" hdrs , S8.takeWhile (/= ',') <$> lookup "x-forwarded-for" hdrs] nonProxyIp <- liftIO $ getNameInfo [NI_NUMERICHOST] True False $ remoteHost req return $ case mrip of Just ip -> ip Nothing -> S8.pack <$> fromMaybe "no-client-address" $ fst nonProxyIp routeAny :: [Controller s () -> Controller s ()] -> Controller s () -> Controller s () routeAny routes ctrl = do forM_ routes $ \rt -> rt ctrl
alevy/mappend
src/Blog/Common.hs
agpl-3.0
6,908
0
21
1,740
1,875
959
916
167
5
multThree :: Int -> Int -> Int -> Int -- multThree :: Int -> (Int -> (Int -> Int)) multThree x y z = x * y * z compareWithHundred :: Int -> Ordering -- compareWithHundred x = compare 100 x -- can be rewritten as compareWithHundred = compare 100 divideByTen :: (Floating a) => a -> a -- brackets around a partially applied infix function indicate a section divideByTen = (/ 10) dividesTen :: (Floating a) => a -> a dividesTen = (10 /) applyTwice :: (a -> a) -> a -> a applyTwice f x = f (f x) zipWith' :: (a -> b -> c) -> [a] -> [b] -> [c] zipWith' _ [] _ = [] zipWith' _ _ [] = [] zipWith' f (x:xs) (y:ys) = f x y : zipWith' f xs ys flip' :: (a -> b -> c) -> (b -> a -> c) flip' f = g where g x y = f y x -- flip' f y x = f x y map' :: (a -> b) -> [a] -> [b] map' _ [] = [] map' f (x:xs) = f x : map f xs quicksort2 :: (Ord a) => [a] -> [a] quicksort2 [] = [] quicksort2 (x:xs) = let smallerThanOrEqual = filter (<= x) xs largerThan = filter (> x) xs in quicksort2 smallerThanOrEqual ++ [x] ++ quicksort2 largerThan largestDivisible :: Integer largestDivisible = head (filter p [100000, 99999..]) where p x = x `mod` 3829 == 0 chain :: Integer -> [Integer] chain 1 = [1] chain n | even n = n:chain (n `div` 2) | odd n = n:chain (n*3 + 1) numLongChains :: Int --numLongChains = length (filter isLong (map chain [1..100])) -- where isLong xs = length xs > 15 numLongChains = length (filter (\xs -> length xs > 15) (map chain [1..100])) sum' :: (Num a) => [a] -> a --sum' xs = foldl (\acc x -> acc + x) 0 xs --by looking at the structure of the function we can simplify this function --rule of thumb is probably that if you don't touch an argument, you can probably remove it from both sides of the definition sum' = foldl (+) 0 foldl' :: (a -> b -> a) -> a -> [b] -> a foldl' _ initial [] = initial foldl' f initial (x:xs) = foldl' f (f initial x) xs foldr' :: (a -> b -> b) -> b -> [a] -> b foldr' _ initial [] = initial foldr' f initial (x:xs) = f x (foldr' f initial xs) --foldr' f initial (x:xs) = foldr' f (f x initial) xs --foldr' f initial xs++[x] = foldr' f (f x initial) xs sum2 :: (Num a) => [a] -> a sum2 = foldl (+) 0 reverse' :: [a] -> [a] reverse' = foldl (\acc x -> x:acc) [] --reverse' xs = foldr (\x acc -> acc ++ [x]) xs [] and' :: [Bool] -> Bool and' xs = foldr (&&) True xs sqrtSums :: Int sqrtSums = length (takeWhile (<1000) (scanl1 (+) (map sqrt [1..]))) + 1 oddSquareSum :: Integer --oddSquareSum = sum (takeWhile (<10000) (filter odd (map (^2) [1..]))) oddSquareSum = sum . takeWhile (<10000) . filter odd . map (^2) $ [1..]
alexliew/learn_you_a_haskell
code/hof.hs
unlicense
2,590
0
13
589
1,072
578
494
54
1
{-# LANGUAGE PolyKinds #-} module Data.Proxify (module Data.Proxify, module X) where import Data.Proxy as X -- === Utils === -- type family Proxified a where Proxified (Proxy a) = a Proxified a = a proxify :: a -> Proxy (Proxified a) proxify _ = Proxy type family Deproxy p where Deproxy (Proxy a) = a
wdanilo/typelevel
src/Data/Proxify.hs
apache-2.0
326
0
8
79
103
60
43
-1
-1
{- Copyright 2020 The CodeWorld Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} program = drawingOf(rectangle(2,2,2,2))
google/codeworld
codeworld-compiler/test/testcases/tooManyArguments/source.hs
apache-2.0
650
0
8
118
28
16
12
1
1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QAbstractSpinBox.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:25 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QAbstractSpinBox ( QqAbstractSpinBox(..) ,correctionMode ,interpretText ,isAccelerated ,keyboardTracking ,setAccelerated ,setCorrectionMode ,setKeyboardTracking ,setSpecialValueText ,specialValueText ,stepDown ,stepUp ,qAbstractSpinBox_delete ,qAbstractSpinBox_deleteLater ) where import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Enums.Gui.QPaintDevice import Qtc.Enums.Core.Qt import Qtc.Enums.Gui.QAbstractSpinBox 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 (QAbstractSpinBox ()) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QAbstractSpinBox_userMethod cobj_qobj (toCInt evid) foreign import ccall "qtc_QAbstractSpinBox_userMethod" qtc_QAbstractSpinBox_userMethod :: Ptr (TQAbstractSpinBox a) -> CInt -> IO () instance QuserMethod (QAbstractSpinBoxSc a) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QAbstractSpinBox_userMethod cobj_qobj (toCInt evid) instance QuserMethod (QAbstractSpinBox ()) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QAbstractSpinBox_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj foreign import ccall "qtc_QAbstractSpinBox_userMethodVariant" qtc_QAbstractSpinBox_userMethodVariant :: Ptr (TQAbstractSpinBox a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) instance QuserMethod (QAbstractSpinBoxSc a) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QAbstractSpinBox_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj class QqAbstractSpinBox x1 where qAbstractSpinBox :: x1 -> IO (QAbstractSpinBox ()) instance QqAbstractSpinBox (()) where qAbstractSpinBox () = withQAbstractSpinBoxResult $ qtc_QAbstractSpinBox foreign import ccall "qtc_QAbstractSpinBox" qtc_QAbstractSpinBox :: IO (Ptr (TQAbstractSpinBox ())) instance QqAbstractSpinBox ((QWidget t1)) where qAbstractSpinBox (x1) = withQAbstractSpinBoxResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox1 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox1" qtc_QAbstractSpinBox1 :: Ptr (TQWidget t1) -> IO (Ptr (TQAbstractSpinBox ())) instance Qalignment (QAbstractSpinBox a) (()) where alignment x0 () = withQFlagsResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_alignment cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_alignment" qtc_QAbstractSpinBox_alignment :: Ptr (TQAbstractSpinBox a) -> IO CLong instance QbuttonSymbols (QAbstractSpinBox a) (()) where buttonSymbols x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_buttonSymbols cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_buttonSymbols" qtc_QAbstractSpinBox_buttonSymbols :: Ptr (TQAbstractSpinBox a) -> IO CLong instance QchangeEvent (QAbstractSpinBox ()) ((QEvent t1)) where changeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_changeEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_changeEvent_h" qtc_QAbstractSpinBox_changeEvent_h :: Ptr (TQAbstractSpinBox a) -> Ptr (TQEvent t1) -> IO () instance QchangeEvent (QAbstractSpinBoxSc a) ((QEvent t1)) where changeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_changeEvent_h cobj_x0 cobj_x1 instance Qclear (QAbstractSpinBox ()) (()) where clear x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_clear_h cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_clear_h" qtc_QAbstractSpinBox_clear_h :: Ptr (TQAbstractSpinBox a) -> IO () instance Qclear (QAbstractSpinBoxSc a) (()) where clear x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_clear_h cobj_x0 instance QcloseEvent (QAbstractSpinBox ()) ((QCloseEvent t1)) where closeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_closeEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_closeEvent_h" qtc_QAbstractSpinBox_closeEvent_h :: Ptr (TQAbstractSpinBox a) -> Ptr (TQCloseEvent t1) -> IO () instance QcloseEvent (QAbstractSpinBoxSc a) ((QCloseEvent t1)) where closeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_closeEvent_h cobj_x0 cobj_x1 instance QcontextMenuEvent (QAbstractSpinBox ()) ((QContextMenuEvent t1)) where contextMenuEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_contextMenuEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_contextMenuEvent_h" qtc_QAbstractSpinBox_contextMenuEvent_h :: Ptr (TQAbstractSpinBox a) -> Ptr (TQContextMenuEvent t1) -> IO () instance QcontextMenuEvent (QAbstractSpinBoxSc a) ((QContextMenuEvent t1)) where contextMenuEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_contextMenuEvent_h cobj_x0 cobj_x1 correctionMode :: QAbstractSpinBox a -> (()) -> IO (CorrectionMode) correctionMode x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_correctionMode cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_correctionMode" qtc_QAbstractSpinBox_correctionMode :: Ptr (TQAbstractSpinBox a) -> IO CLong instance Qevent (QAbstractSpinBox ()) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_event_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_event_h" qtc_QAbstractSpinBox_event_h :: Ptr (TQAbstractSpinBox a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent (QAbstractSpinBoxSc a) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_event_h cobj_x0 cobj_x1 instance QfocusInEvent (QAbstractSpinBox ()) ((QFocusEvent t1)) where focusInEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_focusInEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_focusInEvent_h" qtc_QAbstractSpinBox_focusInEvent_h :: Ptr (TQAbstractSpinBox a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusInEvent (QAbstractSpinBoxSc a) ((QFocusEvent t1)) where focusInEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_focusInEvent_h cobj_x0 cobj_x1 instance QfocusOutEvent (QAbstractSpinBox ()) ((QFocusEvent t1)) where focusOutEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_focusOutEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_focusOutEvent_h" qtc_QAbstractSpinBox_focusOutEvent_h :: Ptr (TQAbstractSpinBox a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusOutEvent (QAbstractSpinBoxSc a) ((QFocusEvent t1)) where focusOutEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_focusOutEvent_h cobj_x0 cobj_x1 instance QhasAcceptableInput (QAbstractSpinBox a) (()) where hasAcceptableInput x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_hasAcceptableInput cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_hasAcceptableInput" qtc_QAbstractSpinBox_hasAcceptableInput :: Ptr (TQAbstractSpinBox a) -> IO CBool instance QhasFrame (QAbstractSpinBox a) (()) where hasFrame x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_hasFrame cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_hasFrame" qtc_QAbstractSpinBox_hasFrame :: Ptr (TQAbstractSpinBox a) -> IO CBool instance QhideEvent (QAbstractSpinBox ()) ((QHideEvent t1)) where hideEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_hideEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_hideEvent_h" qtc_QAbstractSpinBox_hideEvent_h :: Ptr (TQAbstractSpinBox a) -> Ptr (TQHideEvent t1) -> IO () instance QhideEvent (QAbstractSpinBoxSc a) ((QHideEvent t1)) where hideEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_hideEvent_h cobj_x0 cobj_x1 instance QinitStyleOption (QAbstractSpinBox ()) ((QStyleOptionSpinBox t1)) where initStyleOption x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_initStyleOption cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_initStyleOption" qtc_QAbstractSpinBox_initStyleOption :: Ptr (TQAbstractSpinBox a) -> Ptr (TQStyleOptionSpinBox t1) -> IO () instance QinitStyleOption (QAbstractSpinBoxSc a) ((QStyleOptionSpinBox t1)) where initStyleOption x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_initStyleOption cobj_x0 cobj_x1 interpretText :: QAbstractSpinBox a -> (()) -> IO () interpretText x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_interpretText cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_interpretText" qtc_QAbstractSpinBox_interpretText :: Ptr (TQAbstractSpinBox a) -> IO () isAccelerated :: QAbstractSpinBox a -> (()) -> IO (Bool) isAccelerated x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_isAccelerated cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_isAccelerated" qtc_QAbstractSpinBox_isAccelerated :: Ptr (TQAbstractSpinBox a) -> IO CBool instance QisReadOnly (QAbstractSpinBox a) (()) where isReadOnly x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_isReadOnly cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_isReadOnly" qtc_QAbstractSpinBox_isReadOnly :: Ptr (TQAbstractSpinBox a) -> IO CBool instance QkeyPressEvent (QAbstractSpinBox ()) ((QKeyEvent t1)) where keyPressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_keyPressEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_keyPressEvent_h" qtc_QAbstractSpinBox_keyPressEvent_h :: Ptr (TQAbstractSpinBox a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyPressEvent (QAbstractSpinBoxSc a) ((QKeyEvent t1)) where keyPressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_keyPressEvent_h cobj_x0 cobj_x1 instance QkeyReleaseEvent (QAbstractSpinBox ()) ((QKeyEvent t1)) where keyReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_keyReleaseEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_keyReleaseEvent_h" qtc_QAbstractSpinBox_keyReleaseEvent_h :: Ptr (TQAbstractSpinBox a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyReleaseEvent (QAbstractSpinBoxSc a) ((QKeyEvent t1)) where keyReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_keyReleaseEvent_h cobj_x0 cobj_x1 keyboardTracking :: QAbstractSpinBox a -> (()) -> IO (Bool) keyboardTracking x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_keyboardTracking cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_keyboardTracking" qtc_QAbstractSpinBox_keyboardTracking :: Ptr (TQAbstractSpinBox a) -> IO CBool instance QlineEdit (QAbstractSpinBox ()) (()) where lineEdit x0 () = withQLineEditResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_lineEdit cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_lineEdit" qtc_QAbstractSpinBox_lineEdit :: Ptr (TQAbstractSpinBox a) -> IO (Ptr (TQLineEdit ())) instance QlineEdit (QAbstractSpinBoxSc a) (()) where lineEdit x0 () = withQLineEditResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_lineEdit cobj_x0 instance QqminimumSizeHint (QAbstractSpinBox ()) (()) where qminimumSizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_minimumSizeHint_h cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_minimumSizeHint_h" qtc_QAbstractSpinBox_minimumSizeHint_h :: Ptr (TQAbstractSpinBox a) -> IO (Ptr (TQSize ())) instance QqminimumSizeHint (QAbstractSpinBoxSc a) (()) where qminimumSizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_minimumSizeHint_h cobj_x0 instance QminimumSizeHint (QAbstractSpinBox ()) (()) where minimumSizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QAbstractSpinBox_minimumSizeHint_qth_h" qtc_QAbstractSpinBox_minimumSizeHint_qth_h :: Ptr (TQAbstractSpinBox a) -> Ptr CInt -> Ptr CInt -> IO () instance QminimumSizeHint (QAbstractSpinBoxSc a) (()) where minimumSizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h instance QmouseMoveEvent (QAbstractSpinBox ()) ((QMouseEvent t1)) where mouseMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_mouseMoveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_mouseMoveEvent_h" qtc_QAbstractSpinBox_mouseMoveEvent_h :: Ptr (TQAbstractSpinBox a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseMoveEvent (QAbstractSpinBoxSc a) ((QMouseEvent t1)) where mouseMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_mouseMoveEvent_h cobj_x0 cobj_x1 instance QmousePressEvent (QAbstractSpinBox ()) ((QMouseEvent t1)) where mousePressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_mousePressEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_mousePressEvent_h" qtc_QAbstractSpinBox_mousePressEvent_h :: Ptr (TQAbstractSpinBox a) -> Ptr (TQMouseEvent t1) -> IO () instance QmousePressEvent (QAbstractSpinBoxSc a) ((QMouseEvent t1)) where mousePressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_mousePressEvent_h cobj_x0 cobj_x1 instance QmouseReleaseEvent (QAbstractSpinBox ()) ((QMouseEvent t1)) where mouseReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_mouseReleaseEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_mouseReleaseEvent_h" qtc_QAbstractSpinBox_mouseReleaseEvent_h :: Ptr (TQAbstractSpinBox a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseReleaseEvent (QAbstractSpinBoxSc a) ((QMouseEvent t1)) where mouseReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_mouseReleaseEvent_h cobj_x0 cobj_x1 instance QpaintEvent (QAbstractSpinBox ()) ((QPaintEvent t1)) where paintEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_paintEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_paintEvent_h" qtc_QAbstractSpinBox_paintEvent_h :: Ptr (TQAbstractSpinBox a) -> Ptr (TQPaintEvent t1) -> IO () instance QpaintEvent (QAbstractSpinBoxSc a) ((QPaintEvent t1)) where paintEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_paintEvent_h cobj_x0 cobj_x1 instance QresizeEvent (QAbstractSpinBox ()) ((QResizeEvent t1)) where resizeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_resizeEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_resizeEvent_h" qtc_QAbstractSpinBox_resizeEvent_h :: Ptr (TQAbstractSpinBox a) -> Ptr (TQResizeEvent t1) -> IO () instance QresizeEvent (QAbstractSpinBoxSc a) ((QResizeEvent t1)) where resizeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_resizeEvent_h cobj_x0 cobj_x1 instance QselectAll (QAbstractSpinBox a) (()) where selectAll x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_selectAll cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_selectAll" qtc_QAbstractSpinBox_selectAll :: Ptr (TQAbstractSpinBox a) -> IO () setAccelerated :: QAbstractSpinBox a -> ((Bool)) -> IO () setAccelerated x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_setAccelerated cobj_x0 (toCBool x1) foreign import ccall "qtc_QAbstractSpinBox_setAccelerated" qtc_QAbstractSpinBox_setAccelerated :: Ptr (TQAbstractSpinBox a) -> CBool -> IO () instance QsetAlignment (QAbstractSpinBox a) ((Alignment)) (IO ()) where setAlignment x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_setAlignment cobj_x0 (toCLong $ qFlags_toInt x1) foreign import ccall "qtc_QAbstractSpinBox_setAlignment" qtc_QAbstractSpinBox_setAlignment :: Ptr (TQAbstractSpinBox a) -> CLong -> IO () instance QsetButtonSymbols (QAbstractSpinBox a) ((ButtonSymbols)) where setButtonSymbols x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_setButtonSymbols cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QAbstractSpinBox_setButtonSymbols" qtc_QAbstractSpinBox_setButtonSymbols :: Ptr (TQAbstractSpinBox a) -> CLong -> IO () setCorrectionMode :: QAbstractSpinBox a -> ((CorrectionMode)) -> IO () setCorrectionMode x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_setCorrectionMode cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QAbstractSpinBox_setCorrectionMode" qtc_QAbstractSpinBox_setCorrectionMode :: Ptr (TQAbstractSpinBox a) -> CLong -> IO () instance QsetFrame (QAbstractSpinBox a) ((Bool)) where setFrame x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_setFrame cobj_x0 (toCBool x1) foreign import ccall "qtc_QAbstractSpinBox_setFrame" qtc_QAbstractSpinBox_setFrame :: Ptr (TQAbstractSpinBox a) -> CBool -> IO () setKeyboardTracking :: QAbstractSpinBox a -> ((Bool)) -> IO () setKeyboardTracking x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_setKeyboardTracking cobj_x0 (toCBool x1) foreign import ccall "qtc_QAbstractSpinBox_setKeyboardTracking" qtc_QAbstractSpinBox_setKeyboardTracking :: Ptr (TQAbstractSpinBox a) -> CBool -> IO () instance QsetLineEdit (QAbstractSpinBox ()) ((QLineEdit t1)) where setLineEdit x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_setLineEdit cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_setLineEdit" qtc_QAbstractSpinBox_setLineEdit :: Ptr (TQAbstractSpinBox a) -> Ptr (TQLineEdit t1) -> IO () instance QsetLineEdit (QAbstractSpinBoxSc a) ((QLineEdit t1)) where setLineEdit x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_setLineEdit cobj_x0 cobj_x1 instance QsetReadOnly (QAbstractSpinBox a) ((Bool)) where setReadOnly x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_setReadOnly cobj_x0 (toCBool x1) foreign import ccall "qtc_QAbstractSpinBox_setReadOnly" qtc_QAbstractSpinBox_setReadOnly :: Ptr (TQAbstractSpinBox a) -> CBool -> IO () setSpecialValueText :: QAbstractSpinBox a -> ((String)) -> IO () setSpecialValueText x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QAbstractSpinBox_setSpecialValueText cobj_x0 cstr_x1 foreign import ccall "qtc_QAbstractSpinBox_setSpecialValueText" qtc_QAbstractSpinBox_setSpecialValueText :: Ptr (TQAbstractSpinBox a) -> CWString -> IO () instance QsetWrapping (QAbstractSpinBox a) ((Bool)) where setWrapping x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_setWrapping cobj_x0 (toCBool x1) foreign import ccall "qtc_QAbstractSpinBox_setWrapping" qtc_QAbstractSpinBox_setWrapping :: Ptr (TQAbstractSpinBox a) -> CBool -> IO () instance QshowEvent (QAbstractSpinBox ()) ((QShowEvent t1)) where showEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_showEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_showEvent_h" qtc_QAbstractSpinBox_showEvent_h :: Ptr (TQAbstractSpinBox a) -> Ptr (TQShowEvent t1) -> IO () instance QshowEvent (QAbstractSpinBoxSc a) ((QShowEvent t1)) where showEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_showEvent_h cobj_x0 cobj_x1 instance QqsizeHint (QAbstractSpinBox ()) (()) where qsizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_sizeHint_h cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_sizeHint_h" qtc_QAbstractSpinBox_sizeHint_h :: Ptr (TQAbstractSpinBox a) -> IO (Ptr (TQSize ())) instance QqsizeHint (QAbstractSpinBoxSc a) (()) where qsizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_sizeHint_h cobj_x0 instance QsizeHint (QAbstractSpinBox ()) (()) where sizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QAbstractSpinBox_sizeHint_qth_h" qtc_QAbstractSpinBox_sizeHint_qth_h :: Ptr (TQAbstractSpinBox a) -> Ptr CInt -> Ptr CInt -> IO () instance QsizeHint (QAbstractSpinBoxSc a) (()) where sizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h specialValueText :: QAbstractSpinBox a -> (()) -> IO (String) specialValueText x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_specialValueText cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_specialValueText" qtc_QAbstractSpinBox_specialValueText :: Ptr (TQAbstractSpinBox a) -> IO (Ptr (TQString ())) instance QstepBy (QAbstractSpinBox ()) ((Int)) where stepBy x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_stepBy_h cobj_x0 (toCInt x1) foreign import ccall "qtc_QAbstractSpinBox_stepBy_h" qtc_QAbstractSpinBox_stepBy_h :: Ptr (TQAbstractSpinBox a) -> CInt -> IO () instance QstepBy (QAbstractSpinBoxSc a) ((Int)) where stepBy x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_stepBy_h cobj_x0 (toCInt x1) stepDown :: QAbstractSpinBox a -> (()) -> IO () stepDown x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_stepDown cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_stepDown" qtc_QAbstractSpinBox_stepDown :: Ptr (TQAbstractSpinBox a) -> IO () instance QstepEnabled (QAbstractSpinBox ()) (()) where stepEnabled x0 () = withQFlagsResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_stepEnabled cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_stepEnabled" qtc_QAbstractSpinBox_stepEnabled :: Ptr (TQAbstractSpinBox a) -> IO CLong instance QstepEnabled (QAbstractSpinBoxSc a) (()) where stepEnabled x0 () = withQFlagsResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_stepEnabled cobj_x0 stepUp :: QAbstractSpinBox a -> (()) -> IO () stepUp x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_stepUp cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_stepUp" qtc_QAbstractSpinBox_stepUp :: Ptr (TQAbstractSpinBox a) -> IO () instance Qtext (QAbstractSpinBox a) (()) (IO (String)) where text x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_text cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_text" qtc_QAbstractSpinBox_text :: Ptr (TQAbstractSpinBox a) -> IO (Ptr (TQString ())) instance QtimerEvent (QAbstractSpinBox ()) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_timerEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_timerEvent" qtc_QAbstractSpinBox_timerEvent :: Ptr (TQAbstractSpinBox a) -> Ptr (TQTimerEvent t1) -> IO () instance QtimerEvent (QAbstractSpinBoxSc a) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_timerEvent cobj_x0 cobj_x1 instance QwheelEvent (QAbstractSpinBox ()) ((QWheelEvent t1)) where wheelEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_wheelEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_wheelEvent_h" qtc_QAbstractSpinBox_wheelEvent_h :: Ptr (TQAbstractSpinBox a) -> Ptr (TQWheelEvent t1) -> IO () instance QwheelEvent (QAbstractSpinBoxSc a) ((QWheelEvent t1)) where wheelEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_wheelEvent_h cobj_x0 cobj_x1 instance Qwrapping (QAbstractSpinBox a) (()) where wrapping x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_wrapping cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_wrapping" qtc_QAbstractSpinBox_wrapping :: Ptr (TQAbstractSpinBox a) -> IO CBool qAbstractSpinBox_delete :: QAbstractSpinBox a -> IO () qAbstractSpinBox_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_delete cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_delete" qtc_QAbstractSpinBox_delete :: Ptr (TQAbstractSpinBox a) -> IO () qAbstractSpinBox_deleteLater :: QAbstractSpinBox a -> IO () qAbstractSpinBox_deleteLater x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_deleteLater cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_deleteLater" qtc_QAbstractSpinBox_deleteLater :: Ptr (TQAbstractSpinBox a) -> IO () instance QactionEvent (QAbstractSpinBox ()) ((QActionEvent t1)) where actionEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_actionEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_actionEvent_h" qtc_QAbstractSpinBox_actionEvent_h :: Ptr (TQAbstractSpinBox a) -> Ptr (TQActionEvent t1) -> IO () instance QactionEvent (QAbstractSpinBoxSc a) ((QActionEvent t1)) where actionEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_actionEvent_h cobj_x0 cobj_x1 instance QaddAction (QAbstractSpinBox ()) ((QAction t1)) (IO ()) where addAction x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_addAction cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_addAction" qtc_QAbstractSpinBox_addAction :: Ptr (TQAbstractSpinBox a) -> Ptr (TQAction t1) -> IO () instance QaddAction (QAbstractSpinBoxSc a) ((QAction t1)) (IO ()) where addAction x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_addAction cobj_x0 cobj_x1 instance Qcreate (QAbstractSpinBox ()) (()) (IO ()) where create x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_create cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_create" qtc_QAbstractSpinBox_create :: Ptr (TQAbstractSpinBox a) -> IO () instance Qcreate (QAbstractSpinBoxSc a) (()) (IO ()) where create x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_create cobj_x0 instance Qcreate (QAbstractSpinBox ()) ((QVoid t1)) (IO ()) where create x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_create1 cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_create1" qtc_QAbstractSpinBox_create1 :: Ptr (TQAbstractSpinBox a) -> Ptr (TQVoid t1) -> IO () instance Qcreate (QAbstractSpinBoxSc a) ((QVoid t1)) (IO ()) where create x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_create1 cobj_x0 cobj_x1 instance Qcreate (QAbstractSpinBox ()) ((QVoid t1, Bool)) (IO ()) where create x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_create2 cobj_x0 cobj_x1 (toCBool x2) foreign import ccall "qtc_QAbstractSpinBox_create2" qtc_QAbstractSpinBox_create2 :: Ptr (TQAbstractSpinBox a) -> Ptr (TQVoid t1) -> CBool -> IO () instance Qcreate (QAbstractSpinBoxSc a) ((QVoid t1, Bool)) (IO ()) where create x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_create2 cobj_x0 cobj_x1 (toCBool x2) instance Qcreate (QAbstractSpinBox ()) ((QVoid t1, Bool, Bool)) (IO ()) where create x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3) foreign import ccall "qtc_QAbstractSpinBox_create3" qtc_QAbstractSpinBox_create3 :: Ptr (TQAbstractSpinBox a) -> Ptr (TQVoid t1) -> CBool -> CBool -> IO () instance Qcreate (QAbstractSpinBoxSc a) ((QVoid t1, Bool, Bool)) (IO ()) where create x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3) instance Qdestroy (QAbstractSpinBox ()) (()) where destroy x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_destroy cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_destroy" qtc_QAbstractSpinBox_destroy :: Ptr (TQAbstractSpinBox a) -> IO () instance Qdestroy (QAbstractSpinBoxSc a) (()) where destroy x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_destroy cobj_x0 instance Qdestroy (QAbstractSpinBox ()) ((Bool)) where destroy x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_destroy1 cobj_x0 (toCBool x1) foreign import ccall "qtc_QAbstractSpinBox_destroy1" qtc_QAbstractSpinBox_destroy1 :: Ptr (TQAbstractSpinBox a) -> CBool -> IO () instance Qdestroy (QAbstractSpinBoxSc a) ((Bool)) where destroy x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_destroy1 cobj_x0 (toCBool x1) instance Qdestroy (QAbstractSpinBox ()) ((Bool, Bool)) where destroy x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_destroy2 cobj_x0 (toCBool x1) (toCBool x2) foreign import ccall "qtc_QAbstractSpinBox_destroy2" qtc_QAbstractSpinBox_destroy2 :: Ptr (TQAbstractSpinBox a) -> CBool -> CBool -> IO () instance Qdestroy (QAbstractSpinBoxSc a) ((Bool, Bool)) where destroy x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_destroy2 cobj_x0 (toCBool x1) (toCBool x2) instance QdevType (QAbstractSpinBox ()) (()) where devType x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_devType_h cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_devType_h" qtc_QAbstractSpinBox_devType_h :: Ptr (TQAbstractSpinBox a) -> IO CInt instance QdevType (QAbstractSpinBoxSc a) (()) where devType x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_devType_h cobj_x0 instance QdragEnterEvent (QAbstractSpinBox ()) ((QDragEnterEvent t1)) where dragEnterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_dragEnterEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_dragEnterEvent_h" qtc_QAbstractSpinBox_dragEnterEvent_h :: Ptr (TQAbstractSpinBox a) -> Ptr (TQDragEnterEvent t1) -> IO () instance QdragEnterEvent (QAbstractSpinBoxSc a) ((QDragEnterEvent t1)) where dragEnterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_dragEnterEvent_h cobj_x0 cobj_x1 instance QdragLeaveEvent (QAbstractSpinBox ()) ((QDragLeaveEvent t1)) where dragLeaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_dragLeaveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_dragLeaveEvent_h" qtc_QAbstractSpinBox_dragLeaveEvent_h :: Ptr (TQAbstractSpinBox a) -> Ptr (TQDragLeaveEvent t1) -> IO () instance QdragLeaveEvent (QAbstractSpinBoxSc a) ((QDragLeaveEvent t1)) where dragLeaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_dragLeaveEvent_h cobj_x0 cobj_x1 instance QdragMoveEvent (QAbstractSpinBox ()) ((QDragMoveEvent t1)) where dragMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_dragMoveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_dragMoveEvent_h" qtc_QAbstractSpinBox_dragMoveEvent_h :: Ptr (TQAbstractSpinBox a) -> Ptr (TQDragMoveEvent t1) -> IO () instance QdragMoveEvent (QAbstractSpinBoxSc a) ((QDragMoveEvent t1)) where dragMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_dragMoveEvent_h cobj_x0 cobj_x1 instance QdropEvent (QAbstractSpinBox ()) ((QDropEvent t1)) where dropEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_dropEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_dropEvent_h" qtc_QAbstractSpinBox_dropEvent_h :: Ptr (TQAbstractSpinBox a) -> Ptr (TQDropEvent t1) -> IO () instance QdropEvent (QAbstractSpinBoxSc a) ((QDropEvent t1)) where dropEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_dropEvent_h cobj_x0 cobj_x1 instance QenabledChange (QAbstractSpinBox ()) ((Bool)) where enabledChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_enabledChange cobj_x0 (toCBool x1) foreign import ccall "qtc_QAbstractSpinBox_enabledChange" qtc_QAbstractSpinBox_enabledChange :: Ptr (TQAbstractSpinBox a) -> CBool -> IO () instance QenabledChange (QAbstractSpinBoxSc a) ((Bool)) where enabledChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_enabledChange cobj_x0 (toCBool x1) instance QenterEvent (QAbstractSpinBox ()) ((QEvent t1)) where enterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_enterEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_enterEvent_h" qtc_QAbstractSpinBox_enterEvent_h :: Ptr (TQAbstractSpinBox a) -> Ptr (TQEvent t1) -> IO () instance QenterEvent (QAbstractSpinBoxSc a) ((QEvent t1)) where enterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_enterEvent_h cobj_x0 cobj_x1 instance QfocusNextChild (QAbstractSpinBox ()) (()) where focusNextChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_focusNextChild cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_focusNextChild" qtc_QAbstractSpinBox_focusNextChild :: Ptr (TQAbstractSpinBox a) -> IO CBool instance QfocusNextChild (QAbstractSpinBoxSc a) (()) where focusNextChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_focusNextChild cobj_x0 instance QfocusNextPrevChild (QAbstractSpinBox ()) ((Bool)) where focusNextPrevChild x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_focusNextPrevChild cobj_x0 (toCBool x1) foreign import ccall "qtc_QAbstractSpinBox_focusNextPrevChild" qtc_QAbstractSpinBox_focusNextPrevChild :: Ptr (TQAbstractSpinBox a) -> CBool -> IO CBool instance QfocusNextPrevChild (QAbstractSpinBoxSc a) ((Bool)) where focusNextPrevChild x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_focusNextPrevChild cobj_x0 (toCBool x1) instance QfocusPreviousChild (QAbstractSpinBox ()) (()) where focusPreviousChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_focusPreviousChild cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_focusPreviousChild" qtc_QAbstractSpinBox_focusPreviousChild :: Ptr (TQAbstractSpinBox a) -> IO CBool instance QfocusPreviousChild (QAbstractSpinBoxSc a) (()) where focusPreviousChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_focusPreviousChild cobj_x0 instance QfontChange (QAbstractSpinBox ()) ((QFont t1)) where fontChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_fontChange cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_fontChange" qtc_QAbstractSpinBox_fontChange :: Ptr (TQAbstractSpinBox a) -> Ptr (TQFont t1) -> IO () instance QfontChange (QAbstractSpinBoxSc a) ((QFont t1)) where fontChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_fontChange cobj_x0 cobj_x1 instance QheightForWidth (QAbstractSpinBox ()) ((Int)) where heightForWidth x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_heightForWidth_h cobj_x0 (toCInt x1) foreign import ccall "qtc_QAbstractSpinBox_heightForWidth_h" qtc_QAbstractSpinBox_heightForWidth_h :: Ptr (TQAbstractSpinBox a) -> CInt -> IO CInt instance QheightForWidth (QAbstractSpinBoxSc a) ((Int)) where heightForWidth x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_heightForWidth_h cobj_x0 (toCInt x1) instance QinputMethodEvent (QAbstractSpinBox ()) ((QInputMethodEvent t1)) where inputMethodEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_inputMethodEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_inputMethodEvent" qtc_QAbstractSpinBox_inputMethodEvent :: Ptr (TQAbstractSpinBox a) -> Ptr (TQInputMethodEvent t1) -> IO () instance QinputMethodEvent (QAbstractSpinBoxSc a) ((QInputMethodEvent t1)) where inputMethodEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_inputMethodEvent cobj_x0 cobj_x1 instance QinputMethodQuery (QAbstractSpinBox ()) ((InputMethodQuery)) where inputMethodQuery x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QAbstractSpinBox_inputMethodQuery_h" qtc_QAbstractSpinBox_inputMethodQuery_h :: Ptr (TQAbstractSpinBox a) -> CLong -> IO (Ptr (TQVariant ())) instance QinputMethodQuery (QAbstractSpinBoxSc a) ((InputMethodQuery)) where inputMethodQuery x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1) instance QlanguageChange (QAbstractSpinBox ()) (()) where languageChange x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_languageChange cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_languageChange" qtc_QAbstractSpinBox_languageChange :: Ptr (TQAbstractSpinBox a) -> IO () instance QlanguageChange (QAbstractSpinBoxSc a) (()) where languageChange x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_languageChange cobj_x0 instance QleaveEvent (QAbstractSpinBox ()) ((QEvent t1)) where leaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_leaveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_leaveEvent_h" qtc_QAbstractSpinBox_leaveEvent_h :: Ptr (TQAbstractSpinBox a) -> Ptr (TQEvent t1) -> IO () instance QleaveEvent (QAbstractSpinBoxSc a) ((QEvent t1)) where leaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_leaveEvent_h cobj_x0 cobj_x1 instance Qmetric (QAbstractSpinBox ()) ((PaintDeviceMetric)) where metric x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_metric cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QAbstractSpinBox_metric" qtc_QAbstractSpinBox_metric :: Ptr (TQAbstractSpinBox a) -> CLong -> IO CInt instance Qmetric (QAbstractSpinBoxSc a) ((PaintDeviceMetric)) where metric x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_metric cobj_x0 (toCLong $ qEnum_toInt x1) instance QmouseDoubleClickEvent (QAbstractSpinBox ()) ((QMouseEvent t1)) where mouseDoubleClickEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_mouseDoubleClickEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_mouseDoubleClickEvent_h" qtc_QAbstractSpinBox_mouseDoubleClickEvent_h :: Ptr (TQAbstractSpinBox a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseDoubleClickEvent (QAbstractSpinBoxSc a) ((QMouseEvent t1)) where mouseDoubleClickEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_mouseDoubleClickEvent_h cobj_x0 cobj_x1 instance Qmove (QAbstractSpinBox ()) ((Int, Int)) where move x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_move1 cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QAbstractSpinBox_move1" qtc_QAbstractSpinBox_move1 :: Ptr (TQAbstractSpinBox a) -> CInt -> CInt -> IO () instance Qmove (QAbstractSpinBoxSc a) ((Int, Int)) where move x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_move1 cobj_x0 (toCInt x1) (toCInt x2) instance Qmove (QAbstractSpinBox ()) ((Point)) where move x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> qtc_QAbstractSpinBox_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y foreign import ccall "qtc_QAbstractSpinBox_move_qth" qtc_QAbstractSpinBox_move_qth :: Ptr (TQAbstractSpinBox a) -> CInt -> CInt -> IO () instance Qmove (QAbstractSpinBoxSc a) ((Point)) where move x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> qtc_QAbstractSpinBox_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y instance Qqmove (QAbstractSpinBox ()) ((QPoint t1)) where qmove x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_move cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_move" qtc_QAbstractSpinBox_move :: Ptr (TQAbstractSpinBox a) -> Ptr (TQPoint t1) -> IO () instance Qqmove (QAbstractSpinBoxSc a) ((QPoint t1)) where qmove x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_move cobj_x0 cobj_x1 instance QmoveEvent (QAbstractSpinBox ()) ((QMoveEvent t1)) where moveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_moveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_moveEvent_h" qtc_QAbstractSpinBox_moveEvent_h :: Ptr (TQAbstractSpinBox a) -> Ptr (TQMoveEvent t1) -> IO () instance QmoveEvent (QAbstractSpinBoxSc a) ((QMoveEvent t1)) where moveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_moveEvent_h cobj_x0 cobj_x1 instance QpaintEngine (QAbstractSpinBox ()) (()) where paintEngine x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_paintEngine_h cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_paintEngine_h" qtc_QAbstractSpinBox_paintEngine_h :: Ptr (TQAbstractSpinBox a) -> IO (Ptr (TQPaintEngine ())) instance QpaintEngine (QAbstractSpinBoxSc a) (()) where paintEngine x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_paintEngine_h cobj_x0 instance QpaletteChange (QAbstractSpinBox ()) ((QPalette t1)) where paletteChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_paletteChange cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_paletteChange" qtc_QAbstractSpinBox_paletteChange :: Ptr (TQAbstractSpinBox a) -> Ptr (TQPalette t1) -> IO () instance QpaletteChange (QAbstractSpinBoxSc a) ((QPalette t1)) where paletteChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_paletteChange cobj_x0 cobj_x1 instance Qrepaint (QAbstractSpinBox ()) (()) where repaint x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_repaint cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_repaint" qtc_QAbstractSpinBox_repaint :: Ptr (TQAbstractSpinBox a) -> IO () instance Qrepaint (QAbstractSpinBoxSc a) (()) where repaint x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_repaint cobj_x0 instance Qrepaint (QAbstractSpinBox ()) ((Int, Int, Int, Int)) where repaint x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) foreign import ccall "qtc_QAbstractSpinBox_repaint2" qtc_QAbstractSpinBox_repaint2 :: Ptr (TQAbstractSpinBox a) -> CInt -> CInt -> CInt -> CInt -> IO () instance Qrepaint (QAbstractSpinBoxSc a) ((Int, Int, Int, Int)) where repaint x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) instance Qrepaint (QAbstractSpinBox ()) ((QRegion t1)) where repaint x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_repaint1 cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_repaint1" qtc_QAbstractSpinBox_repaint1 :: Ptr (TQAbstractSpinBox a) -> Ptr (TQRegion t1) -> IO () instance Qrepaint (QAbstractSpinBoxSc a) ((QRegion t1)) where repaint x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_repaint1 cobj_x0 cobj_x1 instance QresetInputContext (QAbstractSpinBox ()) (()) where resetInputContext x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_resetInputContext cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_resetInputContext" qtc_QAbstractSpinBox_resetInputContext :: Ptr (TQAbstractSpinBox a) -> IO () instance QresetInputContext (QAbstractSpinBoxSc a) (()) where resetInputContext x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_resetInputContext cobj_x0 instance Qresize (QAbstractSpinBox ()) ((Int, Int)) (IO ()) where resize x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_resize1 cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QAbstractSpinBox_resize1" qtc_QAbstractSpinBox_resize1 :: Ptr (TQAbstractSpinBox a) -> CInt -> CInt -> IO () instance Qresize (QAbstractSpinBoxSc a) ((Int, Int)) (IO ()) where resize x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_resize1 cobj_x0 (toCInt x1) (toCInt x2) instance Qqresize (QAbstractSpinBox ()) ((QSize t1)) where qresize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_resize cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_resize" qtc_QAbstractSpinBox_resize :: Ptr (TQAbstractSpinBox a) -> Ptr (TQSize t1) -> IO () instance Qqresize (QAbstractSpinBoxSc a) ((QSize t1)) where qresize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_resize cobj_x0 cobj_x1 instance Qresize (QAbstractSpinBox ()) ((Size)) (IO ()) where resize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCSize x1 $ \csize_x1_w csize_x1_h -> qtc_QAbstractSpinBox_resize_qth cobj_x0 csize_x1_w csize_x1_h foreign import ccall "qtc_QAbstractSpinBox_resize_qth" qtc_QAbstractSpinBox_resize_qth :: Ptr (TQAbstractSpinBox a) -> CInt -> CInt -> IO () instance Qresize (QAbstractSpinBoxSc a) ((Size)) (IO ()) where resize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCSize x1 $ \csize_x1_w csize_x1_h -> qtc_QAbstractSpinBox_resize_qth cobj_x0 csize_x1_w csize_x1_h instance QsetGeometry (QAbstractSpinBox ()) ((Int, Int, Int, Int)) where setGeometry x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) foreign import ccall "qtc_QAbstractSpinBox_setGeometry1" qtc_QAbstractSpinBox_setGeometry1 :: Ptr (TQAbstractSpinBox a) -> CInt -> CInt -> CInt -> CInt -> IO () instance QsetGeometry (QAbstractSpinBoxSc a) ((Int, Int, Int, Int)) where setGeometry x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) instance QqsetGeometry (QAbstractSpinBox ()) ((QRect t1)) where qsetGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_setGeometry cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_setGeometry" qtc_QAbstractSpinBox_setGeometry :: Ptr (TQAbstractSpinBox a) -> Ptr (TQRect t1) -> IO () instance QqsetGeometry (QAbstractSpinBoxSc a) ((QRect t1)) where qsetGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_setGeometry cobj_x0 cobj_x1 instance QsetGeometry (QAbstractSpinBox ()) ((Rect)) where setGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h -> qtc_QAbstractSpinBox_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h foreign import ccall "qtc_QAbstractSpinBox_setGeometry_qth" qtc_QAbstractSpinBox_setGeometry_qth :: Ptr (TQAbstractSpinBox a) -> CInt -> CInt -> CInt -> CInt -> IO () instance QsetGeometry (QAbstractSpinBoxSc a) ((Rect)) where setGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h -> qtc_QAbstractSpinBox_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h instance QsetMouseTracking (QAbstractSpinBox ()) ((Bool)) where setMouseTracking x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_setMouseTracking cobj_x0 (toCBool x1) foreign import ccall "qtc_QAbstractSpinBox_setMouseTracking" qtc_QAbstractSpinBox_setMouseTracking :: Ptr (TQAbstractSpinBox a) -> CBool -> IO () instance QsetMouseTracking (QAbstractSpinBoxSc a) ((Bool)) where setMouseTracking x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_setMouseTracking cobj_x0 (toCBool x1) instance QsetVisible (QAbstractSpinBox ()) ((Bool)) where setVisible x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_setVisible_h cobj_x0 (toCBool x1) foreign import ccall "qtc_QAbstractSpinBox_setVisible_h" qtc_QAbstractSpinBox_setVisible_h :: Ptr (TQAbstractSpinBox a) -> CBool -> IO () instance QsetVisible (QAbstractSpinBoxSc a) ((Bool)) where setVisible x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_setVisible_h cobj_x0 (toCBool x1) instance QtabletEvent (QAbstractSpinBox ()) ((QTabletEvent t1)) where tabletEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_tabletEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_tabletEvent_h" qtc_QAbstractSpinBox_tabletEvent_h :: Ptr (TQAbstractSpinBox a) -> Ptr (TQTabletEvent t1) -> IO () instance QtabletEvent (QAbstractSpinBoxSc a) ((QTabletEvent t1)) where tabletEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_tabletEvent_h cobj_x0 cobj_x1 instance QupdateMicroFocus (QAbstractSpinBox ()) (()) where updateMicroFocus x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_updateMicroFocus cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_updateMicroFocus" qtc_QAbstractSpinBox_updateMicroFocus :: Ptr (TQAbstractSpinBox a) -> IO () instance QupdateMicroFocus (QAbstractSpinBoxSc a) (()) where updateMicroFocus x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_updateMicroFocus cobj_x0 instance QwindowActivationChange (QAbstractSpinBox ()) ((Bool)) where windowActivationChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_windowActivationChange cobj_x0 (toCBool x1) foreign import ccall "qtc_QAbstractSpinBox_windowActivationChange" qtc_QAbstractSpinBox_windowActivationChange :: Ptr (TQAbstractSpinBox a) -> CBool -> IO () instance QwindowActivationChange (QAbstractSpinBoxSc a) ((Bool)) where windowActivationChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_windowActivationChange cobj_x0 (toCBool x1) instance QchildEvent (QAbstractSpinBox ()) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_childEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_childEvent" qtc_QAbstractSpinBox_childEvent :: Ptr (TQAbstractSpinBox a) -> Ptr (TQChildEvent t1) -> IO () instance QchildEvent (QAbstractSpinBoxSc a) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_childEvent cobj_x0 cobj_x1 instance QconnectNotify (QAbstractSpinBox ()) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QAbstractSpinBox_connectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QAbstractSpinBox_connectNotify" qtc_QAbstractSpinBox_connectNotify :: Ptr (TQAbstractSpinBox a) -> CWString -> IO () instance QconnectNotify (QAbstractSpinBoxSc a) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QAbstractSpinBox_connectNotify cobj_x0 cstr_x1 instance QcustomEvent (QAbstractSpinBox ()) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_customEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QAbstractSpinBox_customEvent" qtc_QAbstractSpinBox_customEvent :: Ptr (TQAbstractSpinBox a) -> Ptr (TQEvent t1) -> IO () instance QcustomEvent (QAbstractSpinBoxSc a) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QAbstractSpinBox_customEvent cobj_x0 cobj_x1 instance QdisconnectNotify (QAbstractSpinBox ()) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QAbstractSpinBox_disconnectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QAbstractSpinBox_disconnectNotify" qtc_QAbstractSpinBox_disconnectNotify :: Ptr (TQAbstractSpinBox a) -> CWString -> IO () instance QdisconnectNotify (QAbstractSpinBoxSc a) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QAbstractSpinBox_disconnectNotify cobj_x0 cstr_x1 instance QeventFilter (QAbstractSpinBox ()) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QAbstractSpinBox_eventFilter_h cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QAbstractSpinBox_eventFilter_h" qtc_QAbstractSpinBox_eventFilter_h :: Ptr (TQAbstractSpinBox a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance QeventFilter (QAbstractSpinBoxSc a) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QAbstractSpinBox_eventFilter_h cobj_x0 cobj_x1 cobj_x2 instance Qreceivers (QAbstractSpinBox ()) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QAbstractSpinBox_receivers cobj_x0 cstr_x1 foreign import ccall "qtc_QAbstractSpinBox_receivers" qtc_QAbstractSpinBox_receivers :: Ptr (TQAbstractSpinBox a) -> CWString -> IO CInt instance Qreceivers (QAbstractSpinBoxSc a) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QAbstractSpinBox_receivers cobj_x0 cstr_x1 instance Qsender (QAbstractSpinBox ()) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_sender cobj_x0 foreign import ccall "qtc_QAbstractSpinBox_sender" qtc_QAbstractSpinBox_sender :: Ptr (TQAbstractSpinBox a) -> IO (Ptr (TQObject ())) instance Qsender (QAbstractSpinBoxSc a) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QAbstractSpinBox_sender cobj_x0
uduki/hsQt
Qtc/Gui/QAbstractSpinBox.hs
bsd-2-clause
57,194
0
14
8,559
17,207
8,720
8,487
-1
-1
{-| The following example program shows how to use 'execute' to spawn the shell command @(grep -v foo)@. This program forwards @Pipes.ByteString.'Pipes.ByteString.stdin'@ to the standard input of @grep@ and merges the standard output and standard error of @grep@ to @Pipes.ByteString.'Pipes.ByteString.stdout'@: > import Control.Applicative ((<|>)) > import Pipes (runEffect, (>->)) > import Pipes.ByteString (stdin, stdout) > import Pipes.Process > > main = execute (proc "grep" ["-v", "foo"]) $ \grepIn grepOut grepErr -> do > forkIO $ runEffect $ stdin >-> toOutput grepIn > forkIO $ runEffect $ fromInput (grepOut <|> grepErr) >-> stdout -} module Pipes.Process ( -- * Types Stdin , Stdout , Stderr -- * Spawn processes , execute , execute' -- * Re-exports -- $reexports , module Data.ByteString , module Pipes.Concurrent , module System.Exit , module System.Process ) where import Data.Foldable (forM_) import Data.ByteString (ByteString) import Pipes (runEffect, (>->)) import Pipes.ByteString (fromHandle, toHandle) import Pipes.Concurrent import System.Exit (ExitCode) import System.Process -- | Use 'send' or 'toOutput' to write to 'Stdin' type Stdin = Output ByteString -- | Use 'recv' or 'fromInput' to read from 'Stdout' type Stdout = Input ByteString -- | Use 'recv' or 'fromInput' to read from 'Stdin' type Stderr = Input ByteString {-| Spawn a process as specified by 'CreateProcess', returning: * An 'Output' that writes to standard input for the process * An 'Input' that reads from standard output for the process * An 'Input' that reads from standard error for the process 'execute' buffers these three interfaces using an 'Unbounded' buffer. Use 'execute'' to specify alternative 'Buffer's. 'execute' terminates when the process terminates. -} execute :: CreateProcess -- ^ Process instructions -> (Stdin -> Stdout -> Stderr -> IO r) -- ^ Callback -> IO (ExitCode, r) execute c k = execute' Unbounded Unbounded Unbounded c $ \oIn _ iOut _ iErr _ -> k oIn iOut iErr {-# INLINABLE execute #-} {-| This is a more general variation on 'execute' that also lets you: * specify how to 'Buffer' 'Stdin' \/ 'Stdout' \/ 'Stderr', and: * seal each 'Buffer' manually. -} execute' :: Buffer ByteString -- ^ Buffer for standard input -> Buffer ByteString -- ^ Buffer for standard output -> Buffer ByteString -- ^ Buffer for standard error -> CreateProcess -- ^ Process instructions -> (Stdin -> STM () -> Stdout -> STM () -> Stderr -> STM () -> IO r) -- ^ Callback with seal actions for each buffer -> IO (ExitCode, r) execute' bufIn bufOut bufErr c k = do (oIn , iIn , sIn ) <- spawn' bufIn (oOut, iOut, sOut) <- spawn' bufOut (oErr, iErr, sErr) <- spawn' bufErr (mIn, mOut, mErr, ph) <- createProcess c forM_ mIn $ \hIn -> runEffect $ fromInput iIn >-> toHandle hIn forM_ mOut $ \hOut -> runEffect $ fromHandle hOut >-> toOutput oOut forM_ mErr $ \hErr -> runEffect $ fromHandle hErr >-> toOutput oErr r <- k oIn sIn iOut sOut iErr sErr atomically $ do sIn sOut sErr ec <- waitForProcess ph return (ec, r) {-# INLINABLE execute' #-} {- $reexports "Data.ByteString" re-exports 'ByteString' "Pipes.Concurrent" re-exports everything "System.Exit" re-exports 'ExitCode' "System.Process" re-exports everything -}
Gabriel439/pipes-process
src/Pipes/Process.hs
bsd-3-clause
3,512
0
18
813
573
306
267
48
1
{-# LANGUAGE PackageImports #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MonoLocalBinds #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE UndecidableInstances #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Generics.Sum.Subtype -- Copyright : (C) 2020 Csongor Kiss -- License : BSD3 -- Maintainer : Csongor Kiss <kiss.csongor.kiss@gmail.com> -- Stability : experimental -- Portability : non-portable -- -- Structural subtype relationships between sum types. -- ----------------------------------------------------------------------------- module Data.Generics.Sum.Subtype ( -- *Prisms -- -- $setup AsSubtype (..) ) where import "this" Data.Generics.Internal.VL.Prism import "generic-lens-core" Data.Generics.Internal.Void import qualified "generic-lens-core" Data.Generics.Sum.Internal.Subtype as Core -- $setup -- == /Running example:/ -- -- >>> :set -XTypeApplications -- >>> :set -XDataKinds -- >>> :set -XDeriveGeneric -- >>> import GHC.Generics -- >>> import Control.Lens -- >>> :{ -- data Animal -- = Dog Dog -- | Cat Name Age -- | Duck Age -- deriving (Generic, Show) -- data FourLeggedAnimal -- = Dog4 Dog -- | Cat4 Name Age -- deriving (Generic, Show) -- data Dog = MkDog -- { name :: Name -- , age :: Age -- } -- deriving (Generic, Show) -- type Name = String -- type Age = Int -- dog, cat, duck :: Animal -- dog = Dog (MkDog "Shep" 3) -- cat = Cat "Mog" 5 -- duck = Duck 2 -- dog4, cat4 :: FourLeggedAnimal -- dog4 = Dog4 (MkDog "Snowy" 4) -- cat4 = Cat4 "Garfield" 6 -- :} -- |Structural subtyping between sums. A sum 'Sub' is a subtype of another sum -- 'Sup' if a value of 'Sub' can be given (modulo naming of constructors) -- whenever a value of 'Sup' is expected. In the running example for instance, -- 'FourLeggedAnimal` is a subtype of 'Animal' since a value of the former can -- be given as a value of the latter (renaming 'Dog4' to 'Dog' and 'Cat4' to -- 'Cat'). class AsSubtype sub sup where -- |A prism that captures structural subtyping. Allows a substructure to be -- injected (upcast) into a superstructure or a superstructure to be downcast -- into a substructure (which may fail). -- -- >>> _Sub # dog4 :: Animal -- Dog (MkDog {name = "Snowy", age = 4}) -- -- >>> cat ^? _Sub :: Maybe FourLeggedAnimal -- Just (Cat4 "Mog" 5) -- -- >>> duck ^? _Sub :: Maybe FourLeggedAnimal -- Nothing _Sub :: Prism' sup sub _Sub = prism injectSub (\i -> maybe (Left i) Right (projectSub i)) {-# INLINE _Sub #-} -- |Injects a subtype into a supertype (upcast). injectSub :: sub -> sup injectSub = build (_Sub @sub @sup) -- |Projects a subtype from a supertype (downcast). projectSub :: sup -> Maybe sub projectSub = either (const Nothing) Just . match (_Sub @sub @sup) {-# MINIMAL (injectSub, projectSub) | _Sub #-} instance Core.Context sub sup => AsSubtype sub sup where _Sub f = prism2prismvl Core.derived f {-# INLINE _Sub #-} -- | Reflexive case -- >>> _Sub # dog :: Animal -- Dog (MkDog {name = "Shep", age = 3}) instance {-# OVERLAPPING #-} AsSubtype a a where _Sub = id {-# INLINE _Sub #-} -- | See Note [Uncluttering type signatures] --_Sub -- :: (AsSubtype sub sup, Data.Profunctor.Choice.Choice p, -- Applicative f) => -- p sub (f sub) -> p sup (f sup) instance {-# OVERLAPPING #-} AsSubtype a Void where injectSub = undefined projectSub = undefined -- | See Note [Uncluttering type signatures] -- >>> :t +d _Sub @Int -- _Sub @Int -- :: (AsSubtype Int sup, Choice p, Applicative f) => -- p Int (f Int) -> p sup (f sup) instance {-# OVERLAPPING #-} AsSubtype Void a where injectSub = undefined projectSub = undefined
kcsongor/generic-lens
generic-lens/src/Data/Generics/Sum/Subtype.hs
bsd-3-clause
3,989
0
12
826
369
247
122
39
0
{-# LANGUAGE TupleSections #-} module CPD.GlobalControl where import qualified CPD.LocalControl as LC import Data.List (find, partition) import Data.Tuple import Descend import Debug.Trace (trace) import Embed import qualified Eval as E import qualified FreshNames as FN import Generalization (Generalizer) import Prelude hiding (sequence) import qualified Subst import Syntax import Text.Printf ( printf ) import Util.Miscellaneous import qualified Environment as Env import Control.Monad.State (runState) data GlobalTree = Leaf (Descend [G S]) Generalizer Subst.Subst | Node (Descend [G S]) Generalizer LC.SldTree [GlobalTree] | Prune (Descend [G S]) Subst.Subst sequence :: Descend a -> [a] sequence = getAncs getNodes (Leaf _ _ _) = [] getNodes (Node _ _ (LC.Leaf _ _ _) _) = [] -- This happens because of the instance check getNodes (Node d _ sld ch) = (getCurr d, sld) : concatMap getNodes ch {- branch :: GlobalTree -> Set [G S] branch (Leaf d _ _) = sequence d branch (Node d _ _ _) = sequence d leaves :: GlobalTree -> Set [G S] leaves (Leaf d _ _ ) = Set.singleton $ LC.getCurr d leaves (Node _ _ _ ch) = let sets = map leaves ch in foldr Set.union Set.empty sets -} -- initial splitting into maximally connected suconjunctions, may be something else part :: [G S] -> [[G S]] part = LC.mcs abstract :: Descend [G S] -> [G S] -> FN.FreshNames -> ([([G S], Generalizer)], FN.FreshNames) abstract descend goals d = let qCurly = part goals in let result = go (map (, Subst.empty) qCurly) d in result where go [] d = ([], d) go ((m, gen):gs) d = case whistle descend m of Nothing -> let (goals, delta) = go gs d in ((m, gen) : goals, delta) Just b -> let (goals, delta) = generalize m b d in -- trace ("generalize done " ++ show' goals) $ let (blah, halb) = go gs delta in (goals ++ blah, halb) whistle :: Descend [G S] -> [G S] -> Maybe [G S] whistle descend m = find (\b -> Embed.embed b m && not (Embed.isVariant b m)) (sequence descend) generalize :: [G S] -> [G S] -> FN.FreshNames -> ([([G S], Generalizer)], FN.FreshNames) generalize m b d = let ((m1, m2), genOrig, delta) = LC.split d b m in -- TODO PCHM let genTrue = genOrig in --let (generalized, _, gen, delta') = D.generalizeGoals d m1 b in -- trace (printf "\nAfter split\n%s\n" (show' $ LC.mcs m1)) $ (map (project genTrue) (LC.mcs m1) ++ map (project Subst.empty) (LC.mcs m2), delta) -- (map (project genTrue) [m1] ++ map (project []) (LC.mcs m2), delta) where project gen goals = (goals, {- filter (\(x, _) -> (V x) `elem` concatMap LC.vars goals) -} gen) abstractChild :: [[G S]] -> (Subst.Subst, [G S], Maybe Env.Env) -> [(Subst.Subst, [G S], Generalizer, Env.Env)] abstractChild _ (_, _, Nothing) = [] abstractChild ancs (subst, g, Just env) = let (abstracted, d') = abstract (Descend.Descend g ancs) g (Env.getFreshNames env) in map (\(g, gen) -> (subst, g, gen, Env.updateNames env d')) abstracted topLevel :: Program -> LC.Heuristic -> (GlobalTree, G S, [S]) topLevel (Program defs goal) heuristic = let env = Env.fromDefs defs in let ((logicGoal, names), env') = runState (E.preEval goal) env in -- trace (printf "\nGoal:\n%s\nNames:\n%s\n" (show goal) (show names)) $ let nodes = [[logicGoal]] in (fst $ go nodes (Descend.Descend [logicGoal] []) env' Subst.empty Subst.empty, logicGoal, names) where go nodes d@(Descend.Descend goal ancs) env subst generalizer = -- if head (Env.getFreshNames env) > 10 -- then (Prune d subst, nodes) -- else let subst = Subst.empty in -- let newNodes = (delete goal nodes) in let newNodes = filter (not . Embed.isVariant goal) nodes in let sldTree = LC.sldResolution goal env subst newNodes heuristic in let (substs, bodies) = partition (null . snd3) $ LC.resultants sldTree in if null bodies then (Node d Subst.empty sldTree [], nodes) else let ancs' = goal : ancs in let abstracted = map (abstractChild ancs') bodies in let (toUnfold, toNotUnfold, newNodes) = foldl (\ (yes, no, seen) gs -> let (variants, brandNew) = partition (\(_, g, _, _) -> null g || any (Embed.isVariant g) seen) gs in -- let (variants, brandNew) = partition (\(_, g, _, _) -> null g || any (LC.isInst g) seen) gs in (yes ++ brandNew, no ++ variants, map snd4 brandNew ++ seen) ) ([], [], nodes) abstracted in let (ch, everythingSeenSoFar) = (swap . (reverse <$>) . swap) $ foldl (\(trees, seen) (subst, g, gen, env) -> let (t, s) = go seen (Descend.Descend g (goal : ancs)) env subst gen in (t:trees, s) ) ([], newNodes) toUnfold in let forgetEnv = map (\(x, y, _) -> (x, y, Subst.empty)) in let forgetStuff = map (\(x, y, gen, _) -> (x,y, gen)) in let substLeaves = forgetEnv substs in let leaves = forgetStuff toNotUnfold in (Node d generalizer sldTree (map (\(subst, g, gen) -> Leaf (Descend.Descend g []) Subst.empty subst) (substLeaves ++ leaves) ++ ch), everythingSeenSoFar)
kajigor/uKanren_transformations
src/CPD/GlobalControl.hs
bsd-3-clause
5,664
0
42
1,716
1,925
1,034
891
90
3
{-# LANGUAGE RecursiveDo, ScopedTypeVariables #-} module Main where import LOGL.Application import LOGL.Camera import Foreign.Ptr import Graphics.UI.GLFW as GLFW import Graphics.Rendering.OpenGL.GL as GL hiding (normalize, position) import Graphics.GLUtil import System.FilePath import Graphics.Rendering.OpenGL.GL.Shaders.ProgramObjects import Linear.Matrix import Linear.V3 import Linear.Vector import Linear.Quaternion import Linear.Projection import Linear.Metric import Reactive.Banana.Frameworks import Reactive.Banana.Combinators hiding (empty) import LOGL.FRP import LOGL.Objects main :: IO () main = do GLFW.init w <- createAppWindow 800 600 "LearnOpenGL" setCursorInputMode (window w) CursorInputMode'Disabled depthFunc $= Just Less lampShader <- simpleShaderProgram ("data" </> "2_Lighting" </> "1_Colors" </> "lamp.vs") ("data" </> "2_Lighting" </> "1_Colors" </> "lamp.frag") lightingShader <- simpleShaderProgram ("data" </> "2_Lighting" </> "4_Lighting-maps" </> "specular.vs") ("data" </> "2_Lighting" </> "4_Lighting-maps" </> "specular.frag") diffuseMap <- createTexture ("data" </> "2_Lighting" </> "4_Lighting-maps" </> "container2.png") specularMap <- createTexture ("data" </> "2_Lighting" </> "4_Lighting-maps" </> "container2_specular.png") currentProgram $= Just (program lightingShader) activeTexture $= TextureUnit 0 textureBinding Texture2D $= Just diffuseMap setUniform lightingShader "material.diffuse" (TextureUnit 0) activeTexture $= TextureUnit 1 textureBinding Texture2D $= Just specularMap setUniform lightingShader "material.specular" (TextureUnit 1) cubeVBO <- createCubeVBO containerVAO <- createContVAO cubeVBO lightVAO <- createLampVAO cubeVBO --polygonMode $= (Line, Line) let networkDescription :: MomentIO () networkDescription = mdo idleE <- idleEvent w camB <- createAppCamera w (V3 0.0 0.0 3.0) reactimate $ drawScene lightingShader containerVAO lampShader lightVAO w <$> (camB <@ idleE) runAppLoopEx w networkDescription deleteObjectName lightVAO deleteObjectName containerVAO deleteObjectName cubeVBO terminate drawScene :: ShaderProgram -> VertexArrayObject -> ShaderProgram -> VertexArrayObject -> AppWindow -> Camera GLfloat -> IO () drawScene lightingShader contVAO lampShader lightVAO w cam = do pollEvents clearColor $= Color4 0.1 0.1 0.1 1.0 clear [ColorBuffer, DepthBuffer] Just time <- getTime -- draw the container cube currentProgram $= Just (program lightingShader) let lightX = 1.0 + 2.0 * sin time lightY = sin (time / 2.0) lightPos = V3 (realToFrac lightX) (realToFrac lightY) (2.0 :: GLfloat) setUniform lightingShader "light.position" lightPos setUniform lightingShader "viewPos" (position cam) setUniform lightingShader "light.ambient" (V3 (0.2 :: GLfloat) 0.2 0.2) setUniform lightingShader "light.diffuse" (V3 (0.5 :: GLfloat) 0.5 0.5) setUniform lightingShader "light.specular" (V3 (1.0 :: GLfloat) 1.0 1.0) setUniform lightingShader "material.shininess" (64.0 :: GLfloat) let view = viewMatrix cam projection = perspective (radians (zoom cam)) (800.0 / 600.0) 0.1 (100.0 :: GLfloat) setUniform lightingShader "view" view setUniform lightingShader "projection" projection let model = identity :: M44 GLfloat setUniform lightingShader "model" model withVAO contVAO $ drawArrays Triangles 0 36 -- draw the lamp currentProgram $= Just (program lampShader) setUniform lampShader "view" view setUniform lampShader "projection" projection let model = mkTransformationMat (0.2 *!! identity) lightPos setUniform lampShader "model" model withVAO lightVAO $ drawArrays Triangles 0 36 swap w createCubeVBO :: IO BufferObject createCubeVBO = makeBuffer ArrayBuffer cubeWithNormalsAndTexture createContVAO :: BufferObject -> IO VertexArrayObject createContVAO vbo = do vao <- genObjectName bindVertexArrayObject $= Just vao bindBuffer ArrayBuffer $= Just vbo vertexAttribPointer (AttribLocation 0) $= (ToFloat, VertexArrayDescriptor 3 Float (8*4) offset0) vertexAttribArray (AttribLocation 0) $= Enabled vertexAttribPointer (AttribLocation 1) $= (ToFloat, VertexArrayDescriptor 3 Float (8*4) (offsetPtr (3*4))) vertexAttribArray (AttribLocation 1) $= Enabled vertexAttribPointer (AttribLocation 2) $= (ToFloat, VertexArrayDescriptor 2 Float (8*4) (offsetPtr (6*4))) vertexAttribArray (AttribLocation 2) $= Enabled bindVertexArrayObject $= Nothing return vao createLampVAO :: BufferObject -> IO VertexArrayObject createLampVAO vbo = do vao <- genObjectName bindVertexArrayObject $= Just vao bindBuffer ArrayBuffer $= Just vbo vertexAttribPointer (AttribLocation 0) $= (ToFloat, VertexArrayDescriptor 3 Float (8*4) offset0) vertexAttribArray (AttribLocation 0) $= Enabled bindVertexArrayObject $= Nothing return vao
atwupack/LearnOpenGL
app/2_Lighting/4_Lighting-maps/Lighting-maps-specular.hs
bsd-3-clause
5,062
0
15
936
1,434
687
747
106
1
module Language.Haskell.GhcMod.List (listModules, listMods) where import Control.Applicative ((<$>)) import Control.Monad (void) import Data.List (nub, sort) import GHC (Ghc) import qualified GHC as G import Language.Haskell.GhcMod.GHCApi import Language.Haskell.GhcMod.Types import Packages (pkgIdMap, exposedModules, sourcePackageId, display) import UniqFM (eltsUFM) ---------------------------------------------------------------- -- | Listing installed modules. listModules :: Options -> Cradle -> IO String listModules opt cradle = convert opt . nub . sort . map dropPkgs <$> withGHCDummyFile (listMods opt cradle) where dropPkgs (name, pkg) | detailed opt = name ++ " " ++ pkg | otherwise = name -- | Listing installed modules. listMods :: Options -> Cradle -> Ghc [(String, String)] listMods opt cradle = do void $ initializeFlagsWithCradle opt cradle [] False getExposedModules <$> G.getSessionDynFlags where getExposedModules = concatMap exposedModules' . eltsUFM . pkgIdMap . G.pkgState exposedModules' p = map G.moduleNameString (exposedModules p) `zip` repeat (display $ sourcePackageId p)
yuga/ghc-mod
Language/Haskell/GhcMod/List.hs
bsd-3-clause
1,185
2
11
222
336
184
152
25
1
module Dickmine.ParseSpec where import Test.Hspec import Data.Time import Dickmine.Parse import Dickmine.Types import System.Locale incorrectLogEntry :: [String] incorrectLogEntry = [ "07/06/2015 08:46:41 am 37.201.171.211 /", "Country: (Unknown Country?) (XX)", "City: (Unknown City?)", "Latitude:", "Longitude:", "IP: 37.201.171.211" ] correctLogEntry :: [String] correctLogEntry = [ "Rick Roll Type: Docs", "Date: 07/08/2015 04:31:56 am", "URL: /api/docs/", "Country: IRELAND (IE)", "City: Dublin", "Latitude: 53.3333", "Longitude: -6.25", "IP: 137.43.28.224" ] spec = do describe "split Date + IP + Route Line" $ do it "splits Date from IP from Route" $ do splitDateIPRoute "07/06/2015 08:46:41 am 37.201.171.211 /" `shouldBe` ("07/06/2015 08:46:41 am", "37.201.171.211", "/") describe "parse Date" $ do it "fails to parse a malformed date" $ do parseDateString "0213asdjk213" `shouldBe` Nothing it "parses a dateString" $ do parseDateString "Date: 07/06/2015 08:46:41 am" `shouldBe` Just (readTime defaultTimeLocale "%m/%d/%Y %I:%M:%S %p" "07/06/2015 08:46:41 AM") describe "parse IP" $ do it "fails to parse a malformed IP" $ do parseIP "asdh" `shouldBe` Nothing it "parses a correct IP" $ do parseIP "IP: 37.201.171.211" `shouldBe` Just "37.201.171.211" describe "parse Country" $ do it "fails to parse a malformed country String" $ do parseCountry "Countasd: (Whatever)" `shouldBe` Nothing it "parses a correct Country String" $ do parseCountry "Country: (Unknown Country?) (XX)" `shouldBe` Just "(Unknown Country?) (XX)" describe "parse City" $ do it "fails to parse a malformed city String" $ do parseCity "Countasd: (Whatever)" `shouldBe` Nothing it "parses a correct city String" $ do parseCity "City: (Unknown City?)" `shouldBe` Just "(Unknown City?)" describe "parse Latitude" $ do it "failes to parse a malformed Latitude" $ do parseLatitude "Counasdmh:asdkj" `shouldBe` Nothing parseLatitude "Latitude: asd" `shouldBe` Nothing parseLatitude "Latitude:" `shouldBe` Nothing it "parses a Latitude" $ do parseLatitude "Latitude: 42.12" `shouldBe` Just 42.12 describe "parseLogEntry" $ do it "fails to parse on empty Input" $ do parseLogEntry [] `shouldBe` Nothing it "fails to parse an incorrect Log Entry" $ do parseLogEntry incorrectLogEntry `shouldBe` Nothing it "parses a correct Log Entry" $ do parseLogEntry correctLogEntry `shouldBe` Just Pagehit { ip = "137.43.28.224", page = "/api/docs/", country = "IRELAND (IE)", city = "Dublin", latitude = 53.3333, longitude = -6.25, timestamp = readTime defaultTimeLocale "%m/%d/%Y %I:%M:%S %p" "07/08/2015 04:31:56 am", rrType = "Docs" }
kRITZCREEK/dickminer
test/Dickmine/ParseSpec.hs
bsd-3-clause
3,092
0
17
852
604
301
303
74
1
module Extractor where import HJS.Parser import HJS.Parser.JavaScript import Data.List data XType = XType { typeName :: String , typeFields :: [String] } deriving (Show, Eq) class ExtractC t where extract :: t -> [XType] -> [XType] instance ExtractC SourceElement where extract (Stmt s) c = extract s c extract (SEFuncDecl fd) c = c instance ExtractC MemberExpr where extract (MemPrimExpr p) c = c extract (ArrayExpr me e) c = c extract (MemberNew me e) c = c extract (MemberCall me e) c = case me of MemberCall me "prototype" -> case me of MemPrimExpr (Ident s) -> insert_xtype XType {typeName=s, typeFields=[e]} c _ -> [] _ -> [] insert_xtype :: XType -> [XType] -> [XType] insert_xtype xtype current_list = if any (\p -> new_name == (typeName p)) current_list then map (\oldtype -> if (typeName oldtype) == new_name then XType {typeName=new_name, typeFields=(typeFields oldtype) ++ (new_fields)} else oldtype) current_list else current_list ++ [xtype] where new_name = (typeName xtype) new_fields = (typeFields xtype) instance ExtractC Stmt where extract (StmtPos p s) c = extract s c instance ExtractC Expr where extract (AssignE p) c = extract p c instance ExtractC AssignE where extract (Assign left AssignNormal right) c = (extract left c) ++ (extract right c) extract (Assign left op right) c = (extract left c) ++ (extract right c) -- TODO: these will need to change extract (CondE p) c = c extract (AEFuncDecl fd) c = c instance ExtractC LeftExpr where extract (CallExpr x) c = extract x c instance ExtractC CallExpr where extract (CallPrim p) c = extract p c extract (CallMember m args) c = c instance ExtractC Stmt' where extract (ExprStmt p) c = extract p c extract (IfStmt p) c = c extract (Block xs) c = c extract (ItStmt p) c = c extract (ReturnStmt (Just p)) c = c extract (ReturnStmt Nothing) c = c extract (BreakStmt s) c = c extract (ContStmt s) c = c extract (EmptyStmt) c = c extract (VarStmt v) c = c extract (ThrowExpr e) c = c extract (TryStmt e) c = c extract (Switch e s) c = c runExtractor :: [SourceElement] -> [XType] runExtractor (x:[]) = extract x [] runExtractor (x:xs) = (extract x (runExtractor xs))
disnet/jscheck
src/Extractor.hs
bsd-3-clause
2,315
0
15
551
978
506
472
62
3
----------------------------------------------------------------------------- -- -- Module : Text.XML.Plist.PlObject -- Copyright : (c) Yuras Shumovich 2009, Michael Tolly 2012 -- License : BSD3 -- -- Maintainer : shumovichy@gmail.com -- Stability : experimental -- Portability : portable -- -- |PlObject data type -- ----------------------------------------------------------------------------- module Text.XML.Plist.PlObject ( PlObject(..), fromPlString, fromPlBool, fromPlInteger, fromPlReal, fromPlArray, fromPlDict ) where import Data.Word -- | Data type that represents plist object data PlObject = PlString String -- ^ string | PlBool Bool -- ^ bool | PlInteger Int -- ^ integer | PlReal Double -- ^ real | PlArray [PlObject] -- ^ array | PlDict [(String, PlObject)] -- ^ dictionary | PlData [Word8] -- ^ raw data | PlDate String -- ^ date (ISO 8601, but currently it is not validated) deriving (Eq, Ord, Show, Read) fromPlString :: Monad m => PlObject -> m String fromPlString (PlString str) = return str fromPlString o = fail $ "not a string: " ++ show o fromPlBool :: Monad m => PlObject -> m Bool fromPlBool (PlBool bool) = return bool fromPlBool o = fail $ "not a bool: " ++ show o fromPlInteger :: Monad m => PlObject -> m Int fromPlInteger (PlInteger i) = return i fromPlInteger o = fail $ "not an integer: " ++ show o fromPlReal :: Monad m => PlObject -> m Double fromPlReal (PlReal r) = return r fromPlReal o = fail $ "not a real: " ++ show o fromPlArray :: Monad m => PlObject -> m [PlObject] fromPlArray (PlArray arr) = return arr fromPlArray o = fail $ "not an array: " ++ show o fromPlDict :: Monad m => PlObject -> m [(String, PlObject)] fromPlDict (PlDict d) = return d fromPlDict o = fail $ "not a dictionary: " ++ show o
Yuras/plist
src/Text/XML/Plist/PlObject.hs
bsd-3-clause
1,795
0
9
340
482
259
223
37
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. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. {-# LANGUAGE OverloadedStrings #-} module Duckling.Distance.RO.Corpus ( corpus ) where import Prelude import Data.String import Duckling.Distance.Types import Duckling.Lang import Duckling.Resolve import Duckling.Testing.Types corpus :: Corpus corpus = (testContext {lang = RO}, allExamples) allExamples :: [Example] allExamples = concat [ examples (DistanceValue Kilometre 3) [ "3 kilometri" , "3 km" , "3km" , "3,0 km" ] , examples (DistanceValue Mile 8) [ "8 mile" ] , examples (DistanceValue Metre 9) [ "9m" , "9 m" ] , examples (DistanceValue Centimetre 2) [ "2cm" , "2 centimetri" ] , examples (DistanceValue Foot 10) [ "zece picioare" ] ]
rfranek/duckling
Duckling/Distance/RO/Corpus.hs
bsd-3-clause
1,163
0
9
365
200
119
81
28
1
{-# LANGUAGE CPP, GeneralizedNewtypeDeriving #-} -- | Tests for the 'Data.HashSet' module. We test functions by -- comparing them to a simpler model, a list. module Main (main) where import qualified Data.Foldable as Foldable import Data.Hashable (Hashable(hashWithSalt)) import qualified Data.List as L import qualified Data.HashSet as S import qualified Data.Set as Set import Data.Ord (comparing) import Test.QuickCheck (Arbitrary, Property, (==>), (===)) import Test.Framework (Test, defaultMain, testGroup) import Test.Framework.Providers.QuickCheck2 (testProperty) -- Key type that generates more hash collisions. newtype Key = K { unK :: Int } deriving (Arbitrary, Enum, Eq, Integral, Num, Ord, Read, Show, Real) instance Hashable Key where hashWithSalt salt k = hashWithSalt salt (unK k) `mod` 20 ------------------------------------------------------------------------ -- * Properties ------------------------------------------------------------------------ -- ** Instances pEq :: [Key] -> [Key] -> Bool pEq xs = (Set.fromList xs ==) `eq` (S.fromList xs ==) pNeq :: [Key] -> [Key] -> Bool pNeq xs = (Set.fromList xs /=) `eq` (S.fromList xs /=) -- We cannot compare to `Data.Map` as ordering is different. pOrd1 :: [Key] -> Bool pOrd1 xs = compare x x == EQ where x = S.fromList xs pOrd2 :: [Key] -> [Key] -> [Key] -> Bool pOrd2 xs ys zs = case (compare x y, compare y z) of (EQ, o) -> compare x z == o (o, EQ) -> compare x z == o (LT, LT) -> compare x z == LT (GT, GT) -> compare x z == GT (LT, GT) -> True -- ys greater than xs and zs. (GT, LT) -> True where x = S.fromList xs y = S.fromList ys z = S.fromList zs pReadShow :: [Key] -> Bool pReadShow xs = Set.fromList xs == read (show (Set.fromList xs)) pFoldable :: [Int] -> Bool pFoldable = (L.sort . Foldable.foldr (:) []) `eq` (L.sort . Foldable.foldr (:) []) pPermutationEq :: [Key] -> [Int] -> Bool pPermutationEq xs is = S.fromList xs == S.fromList ys where ys = shuffle is xs shuffle idxs = L.map snd . L.sortBy (comparing fst) . L.zip (idxs ++ [L.maximum (0:is) + 1 ..]) pHashable :: [Key] -> [Int] -> Int -> Property pHashable xs is salt = x == y ==> hashWithSalt salt x === hashWithSalt salt y where xs' = L.nub xs ys = shuffle is xs' x = S.fromList xs' y = S.fromList ys shuffle idxs = L.map snd . L.sortBy (comparing fst) . L.zip (idxs ++ [L.maximum (0:is) + 1 ..]) ------------------------------------------------------------------------ -- ** Basic interface pSize :: [Key] -> Bool pSize = Set.size `eq` S.size pMember :: Key -> [Key] -> Bool pMember k = Set.member k `eq` S.member k pInsert :: Key -> [Key] -> Bool pInsert a = Set.insert a `eq_` S.insert a pDelete :: Key -> [Key] -> Bool pDelete a = Set.delete a `eq_` S.delete a ------------------------------------------------------------------------ -- ** Combine pUnion :: [Key] -> [Key] -> Bool pUnion xs ys = Set.union (Set.fromList xs) `eq_` S.union (S.fromList xs) $ ys ------------------------------------------------------------------------ -- ** Transformations pMap :: [Key] -> Bool pMap = Set.map (+ 1) `eq_` S.map (+ 1) ------------------------------------------------------------------------ -- ** Folds pFoldr :: [Int] -> Bool pFoldr = (L.sort . foldrSet (:) []) `eq` (L.sort . S.foldr (:) []) foldrSet :: (a -> b -> b) -> b -> Set.Set a -> b #if MIN_VERSION_containers(0,4,2) foldrSet = Set.foldr #else foldrSet = Foldable.foldr #endif pFoldl' :: Int -> [Int] -> Bool pFoldl' z0 = foldl'Set (+) z0 `eq` S.foldl' (+) z0 foldl'Set :: (a -> b -> a) -> a -> Set.Set b -> a #if MIN_VERSION_containers(0,4,2) foldl'Set = Set.foldl' #else foldl'Set = Foldable.foldl' #endif ------------------------------------------------------------------------ -- ** Filter pFilter :: [Key] -> Bool pFilter = Set.filter odd `eq_` S.filter odd ------------------------------------------------------------------------ -- ** Conversions pToList :: [Key] -> Bool pToList = Set.toAscList `eq` toAscList ------------------------------------------------------------------------ -- * Test list tests :: [Test] tests = [ -- Instances testGroup "instances" [ testProperty "==" pEq , testProperty "Permutation ==" pPermutationEq , testProperty "/=" pNeq , testProperty "Read/Show" pReadShow , testProperty "Foldable" pFoldable , testProperty "Hashable" pHashable ] -- Basic interface , testGroup "basic interface" [ testProperty "size" pSize , testProperty "member" pMember , testProperty "insert" pInsert , testProperty "delete" pDelete ] -- Combine , testProperty "union" pUnion -- Transformations , testProperty "map" pMap -- Folds , testGroup "folds" [ testProperty "foldr" pFoldr , testProperty "foldl'" pFoldl' ] -- Filter , testGroup "filter" [ testProperty "filter" pFilter ] -- Conversions , testGroup "conversions" [ testProperty "toList" pToList ] ] ------------------------------------------------------------------------ -- * Model -- Invariant: the list is sorted in ascending order, by key. type Model a = Set.Set a -- | Check that a function operating on a 'HashMap' is equivalent to -- one operating on a 'Model'. eq :: (Eq a, Hashable a, Ord a, Eq b) => (Model a -> b) -- ^ Function that modifies a 'Model' in the same -- way -> (S.HashSet a -> b) -- ^ Function that modified a 'HashSet' -> [a] -- ^ Initial content of the 'HashSet' and 'Model' -> Bool -- ^ True if the functions are equivalent eq f g xs = g (S.fromList xs) == f (Set.fromList xs) eq_ :: (Eq a, Hashable a, Ord a) => (Model a -> Model a) -- ^ Function that modifies a 'Model' -> (S.HashSet a -> S.HashSet a) -- ^ Function that modified a -- 'HashSet' in the same way -> [a] -- ^ Initial content of the 'HashSet' -- and 'Model' -> Bool -- ^ True if the functions are -- equivalent eq_ f g = (Set.toAscList . f) `eq` (toAscList . g) ------------------------------------------------------------------------ -- * Test harness main :: IO () main = defaultMain tests ------------------------------------------------------------------------ -- * Helpers toAscList :: Ord a => S.HashSet a -> [a] toAscList = L.sort . S.toList
bgamari/unordered-containers
tests/HashSetProperties.hs
bsd-3-clause
6,704
0
15
1,632
1,949
1,077
872
121
6
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1993-1998 -} {-# LANGUAGE CPP #-} module IfaceSyn ( module IfaceType, IfaceDecl(..), IfaceFamTyConFlav(..), IfaceClassOp(..), IfaceAT(..), IfaceConDecl(..), IfaceConDecls(..), IfaceEqSpec, IfaceExpr(..), IfaceAlt, IfaceLetBndr(..), IfaceBinding(..), IfaceConAlt(..), IfaceIdInfo(..), IfaceIdDetails(..), IfaceUnfolding(..), IfaceInfoItem(..), IfaceRule(..), IfaceAnnotation(..), IfaceAnnTarget, IfaceClsInst(..), IfaceFamInst(..), IfaceTickish(..), IfaceBang(..), IfaceAxBranch(..), IfaceTyConParent(..), -- Misc ifaceDeclImplicitBndrs, visibleIfConDecls, ifaceDeclFingerprints, -- Free Names freeNamesIfDecl, freeNamesIfRule, freeNamesIfFamInst, -- Pretty printing pprIfaceExpr, pprIfaceDecl, ShowSub(..), ShowHowMuch(..) ) where #include "HsVersions.h" import IfaceType import PprCore() -- Printing DFunArgs import Demand import Class import NameSet import CoAxiom ( BranchIndex, Role ) import Name import CostCentre import Literal import ForeignCall import Annotations( AnnPayload, AnnTarget ) import BasicTypes import Outputable import FastString import Module import SrcLoc import Fingerprint import Binary import BooleanFormula ( BooleanFormula ) import HsBinds import TyCon (Role (..)) import StaticFlags (opt_PprStyle_Debug) import Util( filterOut ) import InstEnv import Control.Monad import System.IO.Unsafe import Data.Maybe (isJust) infixl 3 &&& {- ************************************************************************ * * Declarations * * ************************************************************************ -} type IfaceTopBndr = OccName -- It's convenient to have an OccName in the IfaceSyn, altough in each -- case the namespace is implied by the context. However, having an -- OccNames makes things like ifaceDeclImplicitBndrs and ifaceDeclFingerprints -- very convenient. -- -- We don't serialise the namespace onto the disk though; rather we -- drop it when serialising and add it back in when deserialising. data IfaceDecl = IfaceId { ifName :: IfaceTopBndr, ifType :: IfaceType, ifIdDetails :: IfaceIdDetails, ifIdInfo :: IfaceIdInfo } | IfaceData { ifName :: IfaceTopBndr, -- Type constructor ifCType :: Maybe CType, -- C type for CAPI FFI ifTyVars :: [IfaceTvBndr], -- Type variables ifRoles :: [Role], -- Roles ifCtxt :: IfaceContext, -- The "stupid theta" ifCons :: IfaceConDecls, -- Includes new/data/data family info ifRec :: RecFlag, -- Recursive or not? ifPromotable :: Bool, -- Promotable to kind level? ifGadtSyntax :: Bool, -- True <=> declared using -- GADT syntax ifParent :: IfaceTyConParent -- The axiom, for a newtype, -- or data/newtype family instance } | IfaceSynonym { ifName :: IfaceTopBndr, -- Type constructor ifTyVars :: [IfaceTvBndr], -- Type variables ifRoles :: [Role], -- Roles ifSynKind :: IfaceKind, -- Kind of the *rhs* (not of -- the tycon) ifSynRhs :: IfaceType } | IfaceFamily { ifName :: IfaceTopBndr, -- Type constructor ifTyVars :: [IfaceTvBndr], -- Type variables ifFamKind :: IfaceKind, -- Kind of the *rhs* (not of -- the tycon) ifFamFlav :: IfaceFamTyConFlav } | IfaceClass { ifCtxt :: IfaceContext, -- Context... ifName :: IfaceTopBndr, -- Name of the class TyCon ifTyVars :: [IfaceTvBndr], -- Type variables ifRoles :: [Role], -- Roles ifFDs :: [FunDep FastString], -- Functional dependencies ifATs :: [IfaceAT], -- Associated type families ifSigs :: [IfaceClassOp], -- Method signatures ifMinDef :: BooleanFormula IfLclName, -- Minimal complete definition ifRec :: RecFlag -- Is newtype/datatype associated -- with the class recursive? } | IfaceAxiom { ifName :: IfaceTopBndr, -- Axiom name ifTyCon :: IfaceTyCon, -- LHS TyCon ifRole :: Role, -- Role of axiom ifAxBranches :: [IfaceAxBranch] -- Branches } | IfacePatSyn { ifName :: IfaceTopBndr, -- Name of the pattern synonym ifPatIsInfix :: Bool, ifPatMatcher :: (IfExtName, Bool), ifPatBuilder :: Maybe (IfExtName, Bool), -- Everything below is redundant, -- but needed to implement pprIfaceDecl ifPatUnivTvs :: [IfaceTvBndr], ifPatExTvs :: [IfaceTvBndr], ifPatProvCtxt :: IfaceContext, ifPatReqCtxt :: IfaceContext, ifPatArgs :: [IfaceType], ifPatTy :: IfaceType } data IfaceTyConParent = IfNoParent | IfDataInstance IfExtName IfaceTyCon IfaceTcArgs data IfaceFamTyConFlav = IfaceOpenSynFamilyTyCon | IfaceClosedSynFamilyTyCon IfExtName -- name of associated axiom [IfaceAxBranch] -- for pretty printing purposes only | IfaceAbstractClosedSynFamilyTyCon | IfaceBuiltInSynFamTyCon -- for pretty printing purposes only data IfaceClassOp = IfaceClassOp IfaceTopBndr DefMethSpec IfaceType -- Nothing => no default method -- Just False => ordinary polymorphic default method -- Just True => generic default method data IfaceAT = IfaceAT -- See Class.ClassATItem IfaceDecl -- The associated type declaration (Maybe IfaceType) -- Default associated type instance, if any -- This is just like CoAxBranch data IfaceAxBranch = IfaceAxBranch { ifaxbTyVars :: [IfaceTvBndr] , ifaxbLHS :: IfaceTcArgs , ifaxbRoles :: [Role] , ifaxbRHS :: IfaceType , ifaxbIncomps :: [BranchIndex] } -- See Note [Storing compatibility] in CoAxiom data IfaceConDecls = IfAbstractTyCon Bool -- c.f TyCon.AbstractTyCon | IfDataFamTyCon -- Data family | IfDataTyCon [IfaceConDecl] -- Data type decls | IfNewTyCon IfaceConDecl -- Newtype decls data IfaceConDecl = IfCon { ifConOcc :: IfaceTopBndr, -- Constructor name ifConWrapper :: Bool, -- True <=> has a wrapper ifConInfix :: Bool, -- True <=> declared infix -- The universal type variables are precisely those -- of the type constructor of this data constructor -- This is *easy* to guarantee when creating the IfCon -- but it's not so easy for the original TyCon/DataCon -- So this guarantee holds for IfaceConDecl, but *not* for DataCon ifConExTvs :: [IfaceTvBndr], -- Existential tyvars ifConEqSpec :: IfaceEqSpec, -- Equality constraints ifConCtxt :: IfaceContext, -- Non-stupid context ifConArgTys :: [IfaceType], -- Arg types ifConFields :: [IfaceTopBndr], -- ...ditto... (field labels) ifConStricts :: [IfaceBang]} -- Empty (meaning all lazy), -- or 1-1 corresp with arg tys type IfaceEqSpec = [(IfLclName,IfaceType)] data IfaceBang = IfNoBang | IfStrict | IfUnpack | IfUnpackCo IfaceCoercion data IfaceClsInst = IfaceClsInst { ifInstCls :: IfExtName, -- See comments with ifInstTys :: [Maybe IfaceTyCon], -- the defn of ClsInst ifDFun :: IfExtName, -- The dfun ifOFlag :: OverlapFlag, -- Overlap flag ifInstOrph :: IsOrphan } -- See Note [Orphans] in InstEnv -- There's always a separate IfaceDecl for the DFun, which gives -- its IdInfo with its full type and version number. -- The instance declarations taken together have a version number, -- and we don't want that to wobble gratuitously -- If this instance decl is *used*, we'll record a usage on the dfun; -- and if the head does not change it won't be used if it wasn't before -- The ifFamInstTys field of IfaceFamInst contains a list of the rough -- match types data IfaceFamInst = IfaceFamInst { ifFamInstFam :: IfExtName -- Family name , ifFamInstTys :: [Maybe IfaceTyCon] -- See above , ifFamInstAxiom :: IfExtName -- The axiom , ifFamInstOrph :: IsOrphan -- Just like IfaceClsInst } data IfaceRule = IfaceRule { ifRuleName :: RuleName, ifActivation :: Activation, ifRuleBndrs :: [IfaceBndr], -- Tyvars and term vars ifRuleHead :: IfExtName, -- Head of lhs ifRuleArgs :: [IfaceExpr], -- Args of LHS ifRuleRhs :: IfaceExpr, ifRuleAuto :: Bool, ifRuleOrph :: IsOrphan -- Just like IfaceClsInst } data IfaceAnnotation = IfaceAnnotation { ifAnnotatedTarget :: IfaceAnnTarget, ifAnnotatedValue :: AnnPayload } type IfaceAnnTarget = AnnTarget OccName -- Here's a tricky case: -- * Compile with -O module A, and B which imports A.f -- * Change function f in A, and recompile without -O -- * When we read in old A.hi we read in its IdInfo (as a thunk) -- (In earlier GHCs we used to drop IdInfo immediately on reading, -- but we do not do that now. Instead it's discarded when the -- ModIface is read into the various decl pools.) -- * The version comparison sees that new (=NoInfo) differs from old (=HasInfo *) -- and so gives a new version. data IfaceIdInfo = NoInfo -- When writing interface file without -O | HasInfo [IfaceInfoItem] -- Has info, and here it is data IfaceInfoItem = HsArity Arity | HsStrictness StrictSig | HsInline InlinePragma | HsUnfold Bool -- True <=> isStrongLoopBreaker is true IfaceUnfolding -- See Note [Expose recursive functions] | HsNoCafRefs -- NB: Specialisations and rules come in separately and are -- only later attached to the Id. Partial reason: some are orphans. data IfaceUnfolding = IfCoreUnfold Bool IfaceExpr -- True <=> INLINABLE, False <=> regular unfolding -- Possibly could eliminate the Bool here, the information -- is also in the InlinePragma. | IfCompulsory IfaceExpr -- Only used for default methods, in fact | IfInlineRule Arity -- INLINE pragmas Bool -- OK to inline even if *un*-saturated Bool -- OK to inline even if context is boring IfaceExpr | IfDFunUnfold [IfaceBndr] [IfaceExpr] -- We only serialise the IdDetails of top-level Ids, and even then -- we only need a very limited selection. Notably, none of the -- implicit ones are needed here, because they are not put it -- interface files data IfaceIdDetails = IfVanillaId | IfRecSelId IfaceTyCon Bool | IfDFunId Int -- Number of silent args {- Note [Versioning of instances] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ See [http://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/RecompilationAvoidance#Instances] ************************************************************************ * * Functions over declarations * * ************************************************************************ -} visibleIfConDecls :: IfaceConDecls -> [IfaceConDecl] visibleIfConDecls (IfAbstractTyCon {}) = [] visibleIfConDecls IfDataFamTyCon = [] visibleIfConDecls (IfDataTyCon cs) = cs visibleIfConDecls (IfNewTyCon c) = [c] ifaceDeclImplicitBndrs :: IfaceDecl -> [OccName] -- *Excludes* the 'main' name, but *includes* the implicitly-bound names -- Deeply revolting, because it has to predict what gets bound, -- especially the question of whether there's a wrapper for a datacon -- See Note [Implicit TyThings] in HscTypes -- N.B. the set of names returned here *must* match the set of -- TyThings returned by HscTypes.implicitTyThings, in the sense that -- TyThing.getOccName should define a bijection between the two lists. -- This invariant is used in LoadIface.loadDecl (see note [Tricky iface loop]) -- The order of the list does not matter. ifaceDeclImplicitBndrs IfaceData {ifCons = IfAbstractTyCon {}} = [] -- Newtype ifaceDeclImplicitBndrs (IfaceData {ifName = tc_occ, ifCons = IfNewTyCon ( IfCon { ifConOcc = con_occ })}) = -- implicit newtype coercion (mkNewTyCoOcc tc_occ) : -- JPM: newtype coercions shouldn't be implicit -- data constructor and worker (newtypes don't have a wrapper) [con_occ, mkDataConWorkerOcc con_occ] ifaceDeclImplicitBndrs (IfaceData {ifName = _tc_occ, ifCons = IfDataTyCon cons }) = -- for each data constructor in order, -- data constructor, worker, and (possibly) wrapper concatMap dc_occs cons where dc_occs con_decl | has_wrapper = [con_occ, work_occ, wrap_occ] | otherwise = [con_occ, work_occ] where con_occ = ifConOcc con_decl -- DataCon namespace wrap_occ = mkDataConWrapperOcc con_occ -- Id namespace work_occ = mkDataConWorkerOcc con_occ -- Id namespace has_wrapper = ifConWrapper con_decl -- This is the reason for -- having the ifConWrapper field! ifaceDeclImplicitBndrs (IfaceClass {ifCtxt = sc_ctxt, ifName = cls_tc_occ, ifSigs = sigs, ifATs = ats }) = -- (possibly) newtype coercion co_occs ++ -- data constructor (DataCon namespace) -- data worker (Id namespace) -- no wrapper (class dictionaries never have a wrapper) [dc_occ, dcww_occ] ++ -- associated types [ifName at | IfaceAT at _ <- ats ] ++ -- superclass selectors [mkSuperDictSelOcc n cls_tc_occ | n <- [1..n_ctxt]] ++ -- operation selectors [op | IfaceClassOp op _ _ <- sigs] where n_ctxt = length sc_ctxt n_sigs = length sigs co_occs | is_newtype = [mkNewTyCoOcc cls_tc_occ] | otherwise = [] dcww_occ = mkDataConWorkerOcc dc_occ dc_occ = mkClassDataConOcc cls_tc_occ is_newtype = n_sigs + n_ctxt == 1 -- Sigh ifaceDeclImplicitBndrs _ = [] -- ----------------------------------------------------------------------------- -- The fingerprints of an IfaceDecl -- We better give each name bound by the declaration a -- different fingerprint! So we calculate the fingerprint of -- each binder by combining the fingerprint of the whole -- declaration with the name of the binder. (#5614, #7215) ifaceDeclFingerprints :: Fingerprint -> IfaceDecl -> [(OccName,Fingerprint)] ifaceDeclFingerprints hash decl = (ifName decl, hash) : [ (occ, computeFingerprint' (hash,occ)) | occ <- ifaceDeclImplicitBndrs decl ] where computeFingerprint' = unsafeDupablePerformIO . computeFingerprint (panic "ifaceDeclFingerprints") {- ************************************************************************ * * Expressions * * ************************************************************************ -} data IfaceExpr = IfaceLcl IfLclName | IfaceExt IfExtName | IfaceType IfaceType | IfaceCo IfaceCoercion | IfaceTuple TupleSort [IfaceExpr] -- Saturated; type arguments omitted | IfaceLam IfaceLamBndr IfaceExpr | IfaceApp IfaceExpr IfaceExpr | IfaceCase IfaceExpr IfLclName [IfaceAlt] | IfaceECase IfaceExpr IfaceType -- See Note [Empty case alternatives] | IfaceLet IfaceBinding IfaceExpr | IfaceCast IfaceExpr IfaceCoercion | IfaceLit Literal | IfaceFCall ForeignCall IfaceType | IfaceTick IfaceTickish IfaceExpr -- from Tick tickish E data IfaceTickish = IfaceHpcTick Module Int -- from HpcTick x | IfaceSCC CostCentre Bool Bool -- from ProfNote | IfaceSource RealSrcSpan String -- from SourceNote -- no breakpoints: we never export these into interface files type IfaceAlt = (IfaceConAlt, [IfLclName], IfaceExpr) -- Note: IfLclName, not IfaceBndr (and same with the case binder) -- We reconstruct the kind/type of the thing from the context -- thus saving bulk in interface files data IfaceConAlt = IfaceDefault | IfaceDataAlt IfExtName | IfaceLitAlt Literal data IfaceBinding = IfaceNonRec IfaceLetBndr IfaceExpr | IfaceRec [(IfaceLetBndr, IfaceExpr)] -- IfaceLetBndr is like IfaceIdBndr, but has IdInfo too -- It's used for *non-top-level* let/rec binders -- See Note [IdInfo on nested let-bindings] data IfaceLetBndr = IfLetBndr IfLclName IfaceType IfaceIdInfo {- Note [Empty case alternatives] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In IfaceSyn an IfaceCase does not record the types of the alternatives, unlike CorSyn Case. But we need this type if the alternatives are empty. Hence IfaceECase. See Note [Empty case alternatives] in CoreSyn. Note [Expose recursive functions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For supercompilation we want to put *all* unfoldings in the interface file, even for functions that are recursive (or big). So we need to know when an unfolding belongs to a loop-breaker so that we can refrain from inlining it (except during supercompilation). Note [IdInfo on nested let-bindings] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Occasionally we want to preserve IdInfo on nested let bindings. The one that came up was a NOINLINE pragma on a let-binding inside an INLINE function. The user (Duncan Coutts) really wanted the NOINLINE control to cross the separate compilation boundary. In general we retain all info that is left by CoreTidy.tidyLetBndr, since that is what is seen by importing module with --make ************************************************************************ * * Printing IfaceDecl * * ************************************************************************ -} pprAxBranch :: SDoc -> IfaceAxBranch -> SDoc -- The TyCon might be local (just an OccName), or this might -- be a branch for an imported TyCon, so it would be an ExtName -- So it's easier to take an SDoc here pprAxBranch pp_tc (IfaceAxBranch { ifaxbTyVars = tvs , ifaxbLHS = pat_tys , ifaxbRHS = rhs , ifaxbIncomps = incomps }) = hang (pprUserIfaceForAll tvs) 2 (hang pp_lhs 2 (equals <+> ppr rhs)) $+$ nest 2 maybe_incomps where pp_lhs = hang pp_tc 2 (pprParendIfaceTcArgs pat_tys) maybe_incomps = ppUnless (null incomps) $ parens $ ptext (sLit "incompatible indices:") <+> ppr incomps instance Outputable IfaceAnnotation where ppr (IfaceAnnotation target value) = ppr target <+> colon <+> ppr value instance HasOccName IfaceClassOp where occName (IfaceClassOp n _ _) = n instance HasOccName IfaceConDecl where occName = ifConOcc instance HasOccName IfaceDecl where occName = ifName instance Outputable IfaceDecl where ppr = pprIfaceDecl showAll data ShowSub = ShowSub { ss_ppr_bndr :: OccName -> SDoc -- Pretty-printer for binders in IfaceDecl -- See Note [Printing IfaceDecl binders] , ss_how_much :: ShowHowMuch } data ShowHowMuch = ShowHeader -- Header information only, not rhs | ShowSome [OccName] -- [] <=> Print all sub-components -- (n:ns) <=> print sub-component 'n' with ShowSub=ns -- elide other sub-components to "..." -- May 14: the list is max 1 element long at the moment | ShowIface -- Everything including GHC-internal information (used in --show-iface) showAll :: ShowSub showAll = ShowSub { ss_how_much = ShowIface, ss_ppr_bndr = ppr } ppShowIface :: ShowSub -> SDoc -> SDoc ppShowIface (ShowSub { ss_how_much = ShowIface }) doc = doc ppShowIface _ _ = Outputable.empty ppShowRhs :: ShowSub -> SDoc -> SDoc ppShowRhs (ShowSub { ss_how_much = ShowHeader }) _ = Outputable.empty ppShowRhs _ doc = doc showSub :: HasOccName n => ShowSub -> n -> Bool showSub (ShowSub { ss_how_much = ShowHeader }) _ = False showSub (ShowSub { ss_how_much = ShowSome (n:_) }) thing = n == occName thing showSub (ShowSub { ss_how_much = _ }) _ = True {- Note [Printing IfaceDecl binders] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The binders in an IfaceDecl are just OccNames, so we don't know what module they come from. But when we pretty-print a TyThing by converting to an IfaceDecl (see PprTyThing), the TyThing may come from some other module so we really need the module qualifier. We solve this by passing in a pretty-printer for the binders. When printing an interface file (--show-iface), we want to print everything unqualified, so we can just print the OccName directly. -} ppr_trim :: [Maybe SDoc] -> [SDoc] -- Collapse a group of Nothings to a single "..." ppr_trim xs = snd (foldr go (False, []) xs) where go (Just doc) (_, so_far) = (False, doc : so_far) go Nothing (True, so_far) = (True, so_far) go Nothing (False, so_far) = (True, ptext (sLit "...") : so_far) isIfaceDataInstance :: IfaceTyConParent -> Bool isIfaceDataInstance IfNoParent = False isIfaceDataInstance _ = True pprIfaceDecl :: ShowSub -> IfaceDecl -> SDoc -- NB: pprIfaceDecl is also used for pretty-printing TyThings in GHCi -- See Note [Pretty-printing TyThings] in PprTyThing pprIfaceDecl ss (IfaceData { ifName = tycon, ifCType = ctype, ifCtxt = context, ifTyVars = tc_tyvars, ifRoles = roles, ifCons = condecls, ifParent = parent, ifRec = isrec, ifGadtSyntax = gadt, ifPromotable = is_prom }) | gadt_style = vcat [ pp_roles , pp_nd <+> pp_lhs <+> pp_where , nest 2 (vcat pp_cons) , nest 2 $ ppShowIface ss pp_extra ] | otherwise = vcat [ pp_roles , hang (pp_nd <+> pp_lhs) 2 (add_bars pp_cons) , nest 2 $ ppShowIface ss pp_extra ] where is_data_instance = isIfaceDataInstance parent gadt_style = gadt || any (not . isVanillaIfaceConDecl) cons cons = visibleIfConDecls condecls pp_where = ppWhen (gadt_style && not (null cons)) $ ptext (sLit "where") pp_cons = ppr_trim (map show_con cons) :: [SDoc] pp_lhs = case parent of IfNoParent -> pprIfaceDeclHead context ss tycon tc_tyvars _ -> ptext (sLit "instance") <+> pprIfaceTyConParent parent pp_roles | is_data_instance = Outputable.empty | otherwise = pprRoles (== Representational) (pprPrefixIfDeclBndr ss tycon) tc_tyvars roles -- Don't display roles for data family instances (yet) -- See discussion on Trac #8672. add_bars [] = Outputable.empty add_bars (c:cs) = sep ((equals <+> c) : map (char '|' <+>) cs) ok_con dc = showSub ss dc || any (showSub ss) (ifConFields dc) show_con dc | ok_con dc = Just $ pprIfaceConDecl ss gadt_style mk_user_con_res_ty dc | otherwise = Nothing mk_user_con_res_ty :: IfaceEqSpec -> ([IfaceTvBndr], SDoc) -- See Note [Result type of a data family GADT] mk_user_con_res_ty eq_spec | IfDataInstance _ tc tys <- parent = (con_univ_tvs, pprIfaceType (IfaceTyConApp tc (substIfaceTcArgs gadt_subst tys))) | otherwise = (con_univ_tvs, sdocWithDynFlags (ppr_tc_app gadt_subst)) where gadt_subst = mkFsEnv eq_spec done_univ_tv (tv,_) = isJust (lookupFsEnv gadt_subst tv) con_univ_tvs = filterOut done_univ_tv tc_tyvars ppr_tc_app gadt_subst dflags = pprPrefixIfDeclBndr ss tycon <+> sep [ pprParendIfaceType (substIfaceTyVar gadt_subst tv) | (tv,_kind) <- stripIfaceKindVars dflags tc_tyvars ] pp_nd = case condecls of IfAbstractTyCon d -> ptext (sLit "abstract") <> ppShowIface ss (parens (ppr d)) IfDataFamTyCon -> ptext (sLit "data family") IfDataTyCon _ -> ptext (sLit "data") IfNewTyCon _ -> ptext (sLit "newtype") pp_extra = vcat [pprCType ctype, pprRec isrec, pp_prom] pp_prom | is_prom = ptext (sLit "Promotable") | otherwise = Outputable.empty pprIfaceDecl ss (IfaceClass { ifATs = ats, ifSigs = sigs, ifRec = isrec , ifCtxt = context, ifName = clas , ifTyVars = tyvars, ifRoles = roles , ifFDs = fds }) = vcat [ pprRoles (== Nominal) (pprPrefixIfDeclBndr ss clas) tyvars roles , ptext (sLit "class") <+> pprIfaceDeclHead context ss clas tyvars <+> pprFundeps fds <+> pp_where , nest 2 (vcat [vcat asocs, vcat dsigs, pprec])] where pp_where = ppShowRhs ss $ ppUnless (null sigs && null ats) (ptext (sLit "where")) asocs = ppr_trim $ map maybeShowAssoc ats dsigs = ppr_trim $ map maybeShowSig sigs pprec = ppShowIface ss (pprRec isrec) maybeShowAssoc :: IfaceAT -> Maybe SDoc maybeShowAssoc asc@(IfaceAT d _) | showSub ss d = Just $ pprIfaceAT ss asc | otherwise = Nothing maybeShowSig :: IfaceClassOp -> Maybe SDoc maybeShowSig sg | showSub ss sg = Just $ pprIfaceClassOp ss sg | otherwise = Nothing pprIfaceDecl ss (IfaceSynonym { ifName = tc , ifTyVars = tv , ifSynRhs = mono_ty }) = hang (ptext (sLit "type") <+> pprIfaceDeclHead [] ss tc tv <+> equals) 2 (sep [pprIfaceForAll tvs, pprIfaceContextArr theta, ppr tau]) where (tvs, theta, tau) = splitIfaceSigmaTy mono_ty pprIfaceDecl ss (IfaceFamily { ifName = tycon, ifTyVars = tyvars , ifFamFlav = rhs, ifFamKind = kind }) = vcat [ hang (text "type family" <+> pprIfaceDeclHead [] ss tycon tyvars <+> dcolon) 2 (ppr kind <+> ppShowRhs ss (pp_rhs rhs)) , ppShowRhs ss (nest 2 (pp_branches rhs)) ] where pp_rhs IfaceOpenSynFamilyTyCon = ppShowIface ss (ptext (sLit "open")) pp_rhs IfaceAbstractClosedSynFamilyTyCon = ppShowIface ss (ptext (sLit "closed, abstract")) pp_rhs (IfaceClosedSynFamilyTyCon _ (_:_)) = ptext (sLit "where") pp_rhs IfaceBuiltInSynFamTyCon = ppShowIface ss (ptext (sLit "built-in")) pp_rhs _ = panic "pprIfaceDecl syn" pp_branches (IfaceClosedSynFamilyTyCon ax brs) = vcat (map (pprAxBranch (pprPrefixIfDeclBndr ss tycon)) brs) $$ ppShowIface ss (ptext (sLit "axiom") <+> ppr ax) pp_branches _ = Outputable.empty pprIfaceDecl _ (IfacePatSyn { ifName = name, ifPatBuilder = builder, ifPatUnivTvs = univ_tvs, ifPatExTvs = ex_tvs, ifPatProvCtxt = prov_ctxt, ifPatReqCtxt = req_ctxt, ifPatArgs = arg_tys, ifPatTy = pat_ty} ) = pprPatSynSig name is_bidirectional (pprUserIfaceForAll tvs) (pprIfaceContextMaybe prov_ctxt) (pprIfaceContextMaybe req_ctxt) (pprIfaceType ty) where is_bidirectional = isJust builder tvs = univ_tvs ++ ex_tvs ty = foldr IfaceFunTy pat_ty arg_tys pprIfaceDecl ss (IfaceId { ifName = var, ifType = ty, ifIdDetails = details, ifIdInfo = info }) = vcat [ hang (pprPrefixIfDeclBndr ss var <+> dcolon) 2 (pprIfaceSigmaType ty) , ppShowIface ss (ppr details) , ppShowIface ss (ppr info) ] pprIfaceDecl _ (IfaceAxiom { ifName = name, ifTyCon = tycon , ifAxBranches = branches }) = hang (ptext (sLit "axiom") <+> ppr name <> dcolon) 2 (vcat $ map (pprAxBranch (ppr tycon)) branches) pprCType :: Maybe CType -> SDoc pprCType Nothing = Outputable.empty pprCType (Just cType) = ptext (sLit "C type:") <+> ppr cType -- if, for each role, suppress_if role is True, then suppress the role -- output pprRoles :: (Role -> Bool) -> SDoc -> [IfaceTvBndr] -> [Role] -> SDoc pprRoles suppress_if tyCon tyvars roles = sdocWithDynFlags $ \dflags -> let froles = suppressIfaceKinds dflags tyvars roles in ppUnless (all suppress_if roles || null froles) $ ptext (sLit "type role") <+> tyCon <+> hsep (map ppr froles) pprRec :: RecFlag -> SDoc pprRec NonRecursive = Outputable.empty pprRec Recursive = ptext (sLit "RecFlag: Recursive") pprInfixIfDeclBndr, pprPrefixIfDeclBndr :: ShowSub -> OccName -> SDoc pprInfixIfDeclBndr (ShowSub { ss_ppr_bndr = ppr_bndr }) occ = pprInfixVar (isSymOcc occ) (ppr_bndr occ) pprPrefixIfDeclBndr (ShowSub { ss_ppr_bndr = ppr_bndr }) occ = parenSymOcc occ (ppr_bndr occ) instance Outputable IfaceClassOp where ppr = pprIfaceClassOp showAll pprIfaceClassOp :: ShowSub -> IfaceClassOp -> SDoc pprIfaceClassOp ss (IfaceClassOp n dm ty) = hang opHdr 2 (pprIfaceSigmaType ty) where opHdr = pprPrefixIfDeclBndr ss n <+> ppShowIface ss (ppr dm) <+> dcolon instance Outputable IfaceAT where ppr = pprIfaceAT showAll pprIfaceAT :: ShowSub -> IfaceAT -> SDoc pprIfaceAT ss (IfaceAT d mb_def) = vcat [ pprIfaceDecl ss d , case mb_def of Nothing -> Outputable.empty Just rhs -> nest 2 $ ptext (sLit "Default:") <+> ppr rhs ] instance Outputable IfaceTyConParent where ppr p = pprIfaceTyConParent p pprIfaceTyConParent :: IfaceTyConParent -> SDoc pprIfaceTyConParent IfNoParent = Outputable.empty pprIfaceTyConParent (IfDataInstance _ tc tys) = sdocWithDynFlags $ \dflags -> let ftys = stripKindArgs dflags tys in pprIfaceTypeApp tc ftys pprIfaceDeclHead :: IfaceContext -> ShowSub -> OccName -> [IfaceTvBndr] -> SDoc pprIfaceDeclHead context ss tc_occ tv_bndrs = sdocWithDynFlags $ \ dflags -> sep [ pprIfaceContextArr context , pprPrefixIfDeclBndr ss tc_occ <+> pprIfaceTvBndrs (stripIfaceKindVars dflags tv_bndrs) ] isVanillaIfaceConDecl :: IfaceConDecl -> Bool isVanillaIfaceConDecl (IfCon { ifConExTvs = ex_tvs , ifConEqSpec = eq_spec , ifConCtxt = ctxt }) = (null ex_tvs) && (null eq_spec) && (null ctxt) pprIfaceConDecl :: ShowSub -> Bool -> (IfaceEqSpec -> ([IfaceTvBndr], SDoc)) -> IfaceConDecl -> SDoc pprIfaceConDecl ss gadt_style mk_user_con_res_ty (IfCon { ifConOcc = name, ifConInfix = is_infix, ifConExTvs = ex_tvs, ifConEqSpec = eq_spec, ifConCtxt = ctxt, ifConArgTys = arg_tys, ifConStricts = stricts, ifConFields = labels }) | gadt_style = pp_prefix_con <+> dcolon <+> ppr_ty | otherwise = ppr_fields tys_w_strs where tys_w_strs :: [(IfaceBang, IfaceType)] tys_w_strs = zip stricts arg_tys pp_prefix_con = pprPrefixIfDeclBndr ss name (univ_tvs, pp_res_ty) = mk_user_con_res_ty eq_spec ppr_ty = pprIfaceForAllPart (univ_tvs ++ ex_tvs) ctxt pp_tau -- A bit gruesome this, but we can't form the full con_tau, and ppr it, -- because we don't have a Name for the tycon, only an OccName pp_tau = case map pprParendIfaceType arg_tys ++ [pp_res_ty] of (t:ts) -> fsep (t : map (arrow <+>) ts) [] -> panic "pp_con_taus" ppr_bang IfNoBang = ppWhen opt_PprStyle_Debug $ char '_' ppr_bang IfStrict = char '!' ppr_bang IfUnpack = ptext (sLit "{-# UNPACK #-}") ppr_bang (IfUnpackCo co) = ptext (sLit "! {-# UNPACK #-}") <> pprParendIfaceCoercion co pprParendBangTy (bang, ty) = ppr_bang bang <> pprParendIfaceType ty pprBangTy (bang, ty) = ppr_bang bang <> ppr ty maybe_show_label (lbl,bty) | showSub ss lbl = Just (pprPrefixIfDeclBndr ss lbl <+> dcolon <+> pprBangTy bty) | otherwise = Nothing ppr_fields [ty1, ty2] | is_infix && null labels = sep [pprParendBangTy ty1, pprInfixIfDeclBndr ss name, pprParendBangTy ty2] ppr_fields fields | null labels = pp_prefix_con <+> sep (map pprParendBangTy fields) | otherwise = pp_prefix_con <+> (braces $ sep $ punctuate comma $ ppr_trim $ map maybe_show_label (zip labels fields)) instance Outputable IfaceRule where ppr (IfaceRule { ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs, ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs }) = sep [hsep [doubleQuotes (ftext name), ppr act, ptext (sLit "forall") <+> pprIfaceBndrs bndrs], nest 2 (sep [ppr fn <+> sep (map pprParendIfaceExpr args), ptext (sLit "=") <+> ppr rhs]) ] instance Outputable IfaceClsInst where ppr (IfaceClsInst { ifDFun = dfun_id, ifOFlag = flag , ifInstCls = cls, ifInstTys = mb_tcs}) = hang (ptext (sLit "instance") <+> ppr flag <+> ppr cls <+> brackets (pprWithCommas ppr_rough mb_tcs)) 2 (equals <+> ppr dfun_id) instance Outputable IfaceFamInst where ppr (IfaceFamInst { ifFamInstFam = fam, ifFamInstTys = mb_tcs , ifFamInstAxiom = tycon_ax}) = hang (ptext (sLit "family instance") <+> ppr fam <+> pprWithCommas (brackets . ppr_rough) mb_tcs) 2 (equals <+> ppr tycon_ax) ppr_rough :: Maybe IfaceTyCon -> SDoc ppr_rough Nothing = dot ppr_rough (Just tc) = ppr tc {- Note [Result type of a data family GADT] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider data family T a data instance T (p,q) where T1 :: T (Int, Maybe c) T2 :: T (Bool, q) The IfaceDecl actually looks like data TPr p q where T1 :: forall p q. forall c. (p~Int,q~Maybe c) => TPr p q T2 :: forall p q. (p~Bool) => TPr p q To reconstruct the result types for T1 and T2 that we want to pretty print, we substitute the eq-spec [p->Int, q->Maybe c] in the arg pattern (p,q) to give T (Int, Maybe c) Remember that in IfaceSyn, the TyCon and DataCon share the same universal type variables. ----------------------------- Printing IfaceExpr ------------------------------------ -} instance Outputable IfaceExpr where ppr e = pprIfaceExpr noParens e noParens :: SDoc -> SDoc noParens pp = pp pprParendIfaceExpr :: IfaceExpr -> SDoc pprParendIfaceExpr = pprIfaceExpr parens -- | Pretty Print an IfaceExpre -- -- The first argument should be a function that adds parens in context that need -- an atomic value (e.g. function args) pprIfaceExpr :: (SDoc -> SDoc) -> IfaceExpr -> SDoc pprIfaceExpr _ (IfaceLcl v) = ppr v pprIfaceExpr _ (IfaceExt v) = ppr v pprIfaceExpr _ (IfaceLit l) = ppr l pprIfaceExpr _ (IfaceFCall cc ty) = braces (ppr cc <+> ppr ty) pprIfaceExpr _ (IfaceType ty) = char '@' <+> pprParendIfaceType ty pprIfaceExpr _ (IfaceCo co) = text "@~" <+> pprParendIfaceCoercion co pprIfaceExpr add_par app@(IfaceApp _ _) = add_par (pprIfaceApp app []) pprIfaceExpr _ (IfaceTuple c as) = tupleParens c (interpp'SP as) pprIfaceExpr add_par i@(IfaceLam _ _) = add_par (sep [char '\\' <+> sep (map pprIfaceLamBndr bndrs) <+> arrow, pprIfaceExpr noParens body]) where (bndrs,body) = collect [] i collect bs (IfaceLam b e) = collect (b:bs) e collect bs e = (reverse bs, e) pprIfaceExpr add_par (IfaceECase scrut ty) = add_par (sep [ ptext (sLit "case") <+> pprIfaceExpr noParens scrut , ptext (sLit "ret_ty") <+> pprParendIfaceType ty , ptext (sLit "of {}") ]) pprIfaceExpr add_par (IfaceCase scrut bndr [(con, bs, rhs)]) = add_par (sep [ptext (sLit "case") <+> pprIfaceExpr noParens scrut <+> ptext (sLit "of") <+> ppr bndr <+> char '{' <+> ppr_con_bs con bs <+> arrow, pprIfaceExpr noParens rhs <+> char '}']) pprIfaceExpr add_par (IfaceCase scrut bndr alts) = add_par (sep [ptext (sLit "case") <+> pprIfaceExpr noParens scrut <+> ptext (sLit "of") <+> ppr bndr <+> char '{', nest 2 (sep (map ppr_alt alts)) <+> char '}']) pprIfaceExpr _ (IfaceCast expr co) = sep [pprParendIfaceExpr expr, nest 2 (ptext (sLit "`cast`")), pprParendIfaceCoercion co] pprIfaceExpr add_par (IfaceLet (IfaceNonRec b rhs) body) = add_par (sep [ptext (sLit "let {"), nest 2 (ppr_bind (b, rhs)), ptext (sLit "} in"), pprIfaceExpr noParens body]) pprIfaceExpr add_par (IfaceLet (IfaceRec pairs) body) = add_par (sep [ptext (sLit "letrec {"), nest 2 (sep (map ppr_bind pairs)), ptext (sLit "} in"), pprIfaceExpr noParens body]) pprIfaceExpr add_par (IfaceTick tickish e) = add_par (pprIfaceTickish tickish <+> pprIfaceExpr noParens e) ppr_alt :: (IfaceConAlt, [IfLclName], IfaceExpr) -> SDoc ppr_alt (con, bs, rhs) = sep [ppr_con_bs con bs, arrow <+> pprIfaceExpr noParens rhs] ppr_con_bs :: IfaceConAlt -> [IfLclName] -> SDoc ppr_con_bs con bs = ppr con <+> hsep (map ppr bs) ppr_bind :: (IfaceLetBndr, IfaceExpr) -> SDoc ppr_bind (IfLetBndr b ty info, rhs) = sep [hang (ppr b <+> dcolon <+> ppr ty) 2 (ppr info), equals <+> pprIfaceExpr noParens rhs] ------------------ pprIfaceTickish :: IfaceTickish -> SDoc pprIfaceTickish (IfaceHpcTick m ix) = braces (text "tick" <+> ppr m <+> ppr ix) pprIfaceTickish (IfaceSCC cc tick scope) = braces (pprCostCentreCore cc <+> ppr tick <+> ppr scope) pprIfaceTickish (IfaceSource src _names) = braces (pprUserRealSpan True src) ------------------ pprIfaceApp :: IfaceExpr -> [SDoc] -> SDoc pprIfaceApp (IfaceApp fun arg) args = pprIfaceApp fun $ nest 2 (pprParendIfaceExpr arg) : args pprIfaceApp fun args = sep (pprParendIfaceExpr fun : args) ------------------ instance Outputable IfaceConAlt where ppr IfaceDefault = text "DEFAULT" ppr (IfaceLitAlt l) = ppr l ppr (IfaceDataAlt d) = ppr d ------------------ instance Outputable IfaceIdDetails where ppr IfVanillaId = Outputable.empty ppr (IfRecSelId tc b) = ptext (sLit "RecSel") <+> ppr tc <+> if b then ptext (sLit "<naughty>") else Outputable.empty ppr (IfDFunId ns) = ptext (sLit "DFunId") <> brackets (int ns) instance Outputable IfaceIdInfo where ppr NoInfo = Outputable.empty ppr (HasInfo is) = ptext (sLit "{-") <+> pprWithCommas ppr is <+> ptext (sLit "-}") instance Outputable IfaceInfoItem where ppr (HsUnfold lb unf) = ptext (sLit "Unfolding") <> ppWhen lb (ptext (sLit "(loop-breaker)")) <> colon <+> ppr unf ppr (HsInline prag) = ptext (sLit "Inline:") <+> ppr prag ppr (HsArity arity) = ptext (sLit "Arity:") <+> int arity ppr (HsStrictness str) = ptext (sLit "Strictness:") <+> pprIfaceStrictSig str ppr HsNoCafRefs = ptext (sLit "HasNoCafRefs") instance Outputable IfaceUnfolding where ppr (IfCompulsory e) = ptext (sLit "<compulsory>") <+> parens (ppr e) ppr (IfCoreUnfold s e) = (if s then ptext (sLit "<stable>") else Outputable.empty) <+> parens (ppr e) ppr (IfInlineRule a uok bok e) = sep [ptext (sLit "InlineRule") <+> ppr (a,uok,bok), pprParendIfaceExpr e] ppr (IfDFunUnfold bs es) = hang (ptext (sLit "DFun:") <+> sep (map ppr bs) <> dot) 2 (sep (map pprParendIfaceExpr es)) {- ************************************************************************ * * Finding the Names in IfaceSyn * * ************************************************************************ This is used for dependency analysis in MkIface, so that we fingerprint a declaration before the things that depend on it. It is specific to interface-file fingerprinting in the sense that we don't collect *all* Names: for example, the DFun of an instance is recorded textually rather than by its fingerprint when fingerprinting the instance, so DFuns are not dependencies. -} freeNamesIfDecl :: IfaceDecl -> NameSet freeNamesIfDecl (IfaceId _s t d i) = freeNamesIfType t &&& freeNamesIfIdInfo i &&& freeNamesIfIdDetails d freeNamesIfDecl d@IfaceData{} = freeNamesIfTvBndrs (ifTyVars d) &&& freeNamesIfaceTyConParent (ifParent d) &&& freeNamesIfContext (ifCtxt d) &&& freeNamesIfConDecls (ifCons d) freeNamesIfDecl d@IfaceSynonym{} = freeNamesIfTvBndrs (ifTyVars d) &&& freeNamesIfType (ifSynRhs d) &&& freeNamesIfKind (ifSynKind d) -- IA0_NOTE: because of promotion, we -- return names in the kind signature freeNamesIfDecl d@IfaceFamily{} = freeNamesIfTvBndrs (ifTyVars d) &&& freeNamesIfFamFlav (ifFamFlav d) &&& freeNamesIfKind (ifFamKind d) -- IA0_NOTE: because of promotion, we -- return names in the kind signature freeNamesIfDecl d@IfaceClass{} = freeNamesIfTvBndrs (ifTyVars d) &&& freeNamesIfContext (ifCtxt d) &&& fnList freeNamesIfAT (ifATs d) &&& fnList freeNamesIfClsSig (ifSigs d) freeNamesIfDecl d@IfaceAxiom{} = freeNamesIfTc (ifTyCon d) &&& fnList freeNamesIfAxBranch (ifAxBranches d) freeNamesIfDecl d@IfacePatSyn{} = unitNameSet (fst (ifPatMatcher d)) &&& maybe emptyNameSet (unitNameSet . fst) (ifPatBuilder d) &&& freeNamesIfTvBndrs (ifPatUnivTvs d) &&& freeNamesIfTvBndrs (ifPatExTvs d) &&& freeNamesIfContext (ifPatProvCtxt d) &&& freeNamesIfContext (ifPatReqCtxt d) &&& fnList freeNamesIfType (ifPatArgs d) &&& freeNamesIfType (ifPatTy d) freeNamesIfAxBranch :: IfaceAxBranch -> NameSet freeNamesIfAxBranch (IfaceAxBranch { ifaxbTyVars = tyvars , ifaxbLHS = lhs , ifaxbRHS = rhs }) = freeNamesIfTvBndrs tyvars &&& freeNamesIfTcArgs lhs &&& freeNamesIfType rhs freeNamesIfIdDetails :: IfaceIdDetails -> NameSet freeNamesIfIdDetails (IfRecSelId tc _) = freeNamesIfTc tc freeNamesIfIdDetails _ = emptyNameSet -- All other changes are handled via the version info on the tycon freeNamesIfFamFlav :: IfaceFamTyConFlav -> NameSet freeNamesIfFamFlav IfaceOpenSynFamilyTyCon = emptyNameSet freeNamesIfFamFlav (IfaceClosedSynFamilyTyCon ax br) = unitNameSet ax &&& fnList freeNamesIfAxBranch br freeNamesIfFamFlav IfaceAbstractClosedSynFamilyTyCon = emptyNameSet freeNamesIfFamFlav IfaceBuiltInSynFamTyCon = emptyNameSet freeNamesIfContext :: IfaceContext -> NameSet freeNamesIfContext = fnList freeNamesIfType freeNamesIfAT :: IfaceAT -> NameSet freeNamesIfAT (IfaceAT decl mb_def) = freeNamesIfDecl decl &&& case mb_def of Nothing -> emptyNameSet Just rhs -> freeNamesIfType rhs freeNamesIfClsSig :: IfaceClassOp -> NameSet freeNamesIfClsSig (IfaceClassOp _n _dm ty) = freeNamesIfType ty freeNamesIfConDecls :: IfaceConDecls -> NameSet freeNamesIfConDecls (IfDataTyCon c) = fnList freeNamesIfConDecl c freeNamesIfConDecls (IfNewTyCon c) = freeNamesIfConDecl c freeNamesIfConDecls _ = emptyNameSet freeNamesIfConDecl :: IfaceConDecl -> NameSet freeNamesIfConDecl c = freeNamesIfTvBndrs (ifConExTvs c) &&& freeNamesIfContext (ifConCtxt c) &&& fnList freeNamesIfType (ifConArgTys c) &&& fnList freeNamesIfType (map snd (ifConEqSpec c)) -- equality constraints freeNamesIfKind :: IfaceType -> NameSet freeNamesIfKind = freeNamesIfType freeNamesIfTcArgs :: IfaceTcArgs -> NameSet freeNamesIfTcArgs (ITC_Type t ts) = freeNamesIfType t &&& freeNamesIfTcArgs ts freeNamesIfTcArgs (ITC_Kind k ks) = freeNamesIfKind k &&& freeNamesIfTcArgs ks freeNamesIfTcArgs ITC_Nil = emptyNameSet freeNamesIfType :: IfaceType -> NameSet freeNamesIfType (IfaceTyVar _) = emptyNameSet freeNamesIfType (IfaceAppTy s t) = freeNamesIfType s &&& freeNamesIfType t freeNamesIfType (IfaceTyConApp tc ts) = freeNamesIfTc tc &&& freeNamesIfTcArgs ts freeNamesIfType (IfaceLitTy _) = emptyNameSet freeNamesIfType (IfaceForAllTy tv t) = freeNamesIfTvBndr tv &&& freeNamesIfType t freeNamesIfType (IfaceFunTy s t) = freeNamesIfType s &&& freeNamesIfType t freeNamesIfType (IfaceDFunTy s t) = freeNamesIfType s &&& freeNamesIfType t freeNamesIfCoercion :: IfaceCoercion -> NameSet freeNamesIfCoercion (IfaceReflCo _ t) = freeNamesIfType t freeNamesIfCoercion (IfaceFunCo _ c1 c2) = freeNamesIfCoercion c1 &&& freeNamesIfCoercion c2 freeNamesIfCoercion (IfaceTyConAppCo _ tc cos) = freeNamesIfTc tc &&& fnList freeNamesIfCoercion cos freeNamesIfCoercion (IfaceAppCo c1 c2) = freeNamesIfCoercion c1 &&& freeNamesIfCoercion c2 freeNamesIfCoercion (IfaceForAllCo tv co) = freeNamesIfTvBndr tv &&& freeNamesIfCoercion co freeNamesIfCoercion (IfaceCoVarCo _) = emptyNameSet freeNamesIfCoercion (IfaceAxiomInstCo ax _ cos) = unitNameSet ax &&& fnList freeNamesIfCoercion cos freeNamesIfCoercion (IfaceUnivCo _ _ t1 t2) = freeNamesIfType t1 &&& freeNamesIfType t2 freeNamesIfCoercion (IfaceSymCo c) = freeNamesIfCoercion c freeNamesIfCoercion (IfaceTransCo c1 c2) = freeNamesIfCoercion c1 &&& freeNamesIfCoercion c2 freeNamesIfCoercion (IfaceNthCo _ co) = freeNamesIfCoercion co freeNamesIfCoercion (IfaceLRCo _ co) = freeNamesIfCoercion co freeNamesIfCoercion (IfaceInstCo co ty) = freeNamesIfCoercion co &&& freeNamesIfType ty freeNamesIfCoercion (IfaceSubCo co) = freeNamesIfCoercion co freeNamesIfCoercion (IfaceAxiomRuleCo _ax tys cos) -- the axiom is just a string, so we don't count it as a name. = fnList freeNamesIfType tys &&& fnList freeNamesIfCoercion cos freeNamesIfTvBndrs :: [IfaceTvBndr] -> NameSet freeNamesIfTvBndrs = fnList freeNamesIfTvBndr freeNamesIfBndr :: IfaceBndr -> NameSet freeNamesIfBndr (IfaceIdBndr b) = freeNamesIfIdBndr b freeNamesIfBndr (IfaceTvBndr b) = freeNamesIfTvBndr b freeNamesIfLetBndr :: IfaceLetBndr -> NameSet -- Remember IfaceLetBndr is used only for *nested* bindings -- The IdInfo can contain an unfolding (in the case of -- local INLINE pragmas), so look there too freeNamesIfLetBndr (IfLetBndr _name ty info) = freeNamesIfType ty &&& freeNamesIfIdInfo info freeNamesIfTvBndr :: IfaceTvBndr -> NameSet freeNamesIfTvBndr (_fs,k) = freeNamesIfKind k -- kinds can have Names inside, because of promotion freeNamesIfIdBndr :: IfaceIdBndr -> NameSet freeNamesIfIdBndr = freeNamesIfTvBndr freeNamesIfIdInfo :: IfaceIdInfo -> NameSet freeNamesIfIdInfo NoInfo = emptyNameSet freeNamesIfIdInfo (HasInfo i) = fnList freeNamesItem i freeNamesItem :: IfaceInfoItem -> NameSet freeNamesItem (HsUnfold _ u) = freeNamesIfUnfold u freeNamesItem _ = emptyNameSet freeNamesIfUnfold :: IfaceUnfolding -> NameSet freeNamesIfUnfold (IfCoreUnfold _ e) = freeNamesIfExpr e freeNamesIfUnfold (IfCompulsory e) = freeNamesIfExpr e freeNamesIfUnfold (IfInlineRule _ _ _ e) = freeNamesIfExpr e freeNamesIfUnfold (IfDFunUnfold bs es) = fnList freeNamesIfBndr bs &&& fnList freeNamesIfExpr es freeNamesIfExpr :: IfaceExpr -> NameSet freeNamesIfExpr (IfaceExt v) = unitNameSet v freeNamesIfExpr (IfaceFCall _ ty) = freeNamesIfType ty freeNamesIfExpr (IfaceType ty) = freeNamesIfType ty freeNamesIfExpr (IfaceCo co) = freeNamesIfCoercion co freeNamesIfExpr (IfaceTuple _ as) = fnList freeNamesIfExpr as freeNamesIfExpr (IfaceLam (b,_) body) = freeNamesIfBndr b &&& freeNamesIfExpr body freeNamesIfExpr (IfaceApp f a) = freeNamesIfExpr f &&& freeNamesIfExpr a freeNamesIfExpr (IfaceCast e co) = freeNamesIfExpr e &&& freeNamesIfCoercion co freeNamesIfExpr (IfaceTick _ e) = freeNamesIfExpr e freeNamesIfExpr (IfaceECase e ty) = freeNamesIfExpr e &&& freeNamesIfType ty freeNamesIfExpr (IfaceCase s _ alts) = freeNamesIfExpr s &&& fnList fn_alt alts &&& fn_cons alts where fn_alt (_con,_bs,r) = freeNamesIfExpr r -- Depend on the data constructors. Just one will do! -- Note [Tracking data constructors] fn_cons [] = emptyNameSet fn_cons ((IfaceDefault ,_,_) : xs) = fn_cons xs fn_cons ((IfaceDataAlt con,_,_) : _ ) = unitNameSet con fn_cons (_ : _ ) = emptyNameSet freeNamesIfExpr (IfaceLet (IfaceNonRec bndr rhs) body) = freeNamesIfLetBndr bndr &&& freeNamesIfExpr rhs &&& freeNamesIfExpr body freeNamesIfExpr (IfaceLet (IfaceRec as) x) = fnList fn_pair as &&& freeNamesIfExpr x where fn_pair (bndr, rhs) = freeNamesIfLetBndr bndr &&& freeNamesIfExpr rhs freeNamesIfExpr _ = emptyNameSet freeNamesIfTc :: IfaceTyCon -> NameSet freeNamesIfTc tc = unitNameSet (ifaceTyConName tc) -- ToDo: shouldn't we include IfaceIntTc & co.? freeNamesIfRule :: IfaceRule -> NameSet freeNamesIfRule (IfaceRule { ifRuleBndrs = bs, ifRuleHead = f , ifRuleArgs = es, ifRuleRhs = rhs }) = unitNameSet f &&& fnList freeNamesIfBndr bs &&& fnList freeNamesIfExpr es &&& freeNamesIfExpr rhs freeNamesIfFamInst :: IfaceFamInst -> NameSet freeNamesIfFamInst (IfaceFamInst { ifFamInstFam = famName , ifFamInstAxiom = axName }) = unitNameSet famName &&& unitNameSet axName freeNamesIfaceTyConParent :: IfaceTyConParent -> NameSet freeNamesIfaceTyConParent IfNoParent = emptyNameSet freeNamesIfaceTyConParent (IfDataInstance ax tc tys) = unitNameSet ax &&& freeNamesIfTc tc &&& freeNamesIfTcArgs tys -- helpers (&&&) :: NameSet -> NameSet -> NameSet (&&&) = unionNameSet fnList :: (a -> NameSet) -> [a] -> NameSet fnList f = foldr (&&&) emptyNameSet . map f {- Note [Tracking data constructors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In a case expression case e of { C a -> ...; ... } You might think that we don't need to include the datacon C in the free names, because its type will probably show up in the free names of 'e'. But in rare circumstances this may not happen. Here's the one that bit me: module DynFlags where import {-# SOURCE #-} Packages( PackageState ) data DynFlags = DF ... PackageState ... module Packages where import DynFlags data PackageState = PS ... lookupModule (df :: DynFlags) = case df of DF ...p... -> case p of PS ... -> ... Now, lookupModule depends on DynFlags, but the transitive dependency on the *locally-defined* type PackageState is not visible. We need to take account of the use of the data constructor PS in the pattern match. ************************************************************************ * * Binary instances * * ************************************************************************ -} instance Binary IfaceDecl where put_ bh (IfaceId name ty details idinfo) = do putByte bh 0 put_ bh (occNameFS name) put_ bh ty put_ bh details put_ bh idinfo put_ bh (IfaceData a1 a2 a3 a4 a5 a6 a7 a8 a9 a10) = do putByte bh 2 put_ bh (occNameFS a1) put_ bh a2 put_ bh a3 put_ bh a4 put_ bh a5 put_ bh a6 put_ bh a7 put_ bh a8 put_ bh a9 put_ bh a10 put_ bh (IfaceSynonym a1 a2 a3 a4 a5) = do putByte bh 3 put_ bh (occNameFS a1) put_ bh a2 put_ bh a3 put_ bh a4 put_ bh a5 put_ bh (IfaceFamily a1 a2 a3 a4) = do putByte bh 4 put_ bh (occNameFS a1) put_ bh a2 put_ bh a3 put_ bh a4 put_ bh (IfaceClass a1 a2 a3 a4 a5 a6 a7 a8 a9) = do putByte bh 5 put_ bh a1 put_ bh (occNameFS a2) put_ bh a3 put_ bh a4 put_ bh a5 put_ bh a6 put_ bh a7 put_ bh a8 put_ bh a9 put_ bh (IfaceAxiom a1 a2 a3 a4) = do putByte bh 6 put_ bh (occNameFS a1) put_ bh a2 put_ bh a3 put_ bh a4 put_ bh (IfacePatSyn name a2 a3 a4 a5 a6 a7 a8 a9 a10) = do putByte bh 7 put_ bh (occNameFS name) put_ bh a2 put_ bh a3 put_ bh a4 put_ bh a5 put_ bh a6 put_ bh a7 put_ bh a8 put_ bh a9 put_ bh a10 get bh = do h <- getByte bh case h of 0 -> do name <- get bh ty <- get bh details <- get bh idinfo <- get bh occ <- return $! mkVarOccFS name return (IfaceId occ ty details idinfo) 1 -> error "Binary.get(TyClDecl): ForeignType" 2 -> do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh a5 <- get bh a6 <- get bh a7 <- get bh a8 <- get bh a9 <- get bh a10 <- get bh occ <- return $! mkTcOccFS a1 return (IfaceData occ a2 a3 a4 a5 a6 a7 a8 a9 a10) 3 -> do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh a5 <- get bh occ <- return $! mkTcOccFS a1 return (IfaceSynonym occ a2 a3 a4 a5) 4 -> do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh occ <- return $! mkTcOccFS a1 return (IfaceFamily occ a2 a3 a4) 5 -> do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh a5 <- get bh a6 <- get bh a7 <- get bh a8 <- get bh a9 <- get bh occ <- return $! mkClsOccFS a2 return (IfaceClass a1 occ a3 a4 a5 a6 a7 a8 a9) 6 -> do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh occ <- return $! mkTcOccFS a1 return (IfaceAxiom occ a2 a3 a4) 7 -> do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh a5 <- get bh a6 <- get bh a7 <- get bh a8 <- get bh a9 <- get bh a10 <- get bh occ <- return $! mkDataOccFS a1 return (IfacePatSyn occ a2 a3 a4 a5 a6 a7 a8 a9 a10) _ -> panic (unwords ["Unknown IfaceDecl tag:", show h]) instance Binary IfaceFamTyConFlav where put_ bh IfaceOpenSynFamilyTyCon = putByte bh 0 put_ bh (IfaceClosedSynFamilyTyCon ax br) = putByte bh 1 >> put_ bh ax >> put_ bh br put_ bh IfaceAbstractClosedSynFamilyTyCon = putByte bh 2 put_ _ IfaceBuiltInSynFamTyCon = pprPanic "Cannot serialize IfaceBuiltInSynFamTyCon, used for pretty-printing only" Outputable.empty get bh = do { h <- getByte bh ; case h of 0 -> return IfaceOpenSynFamilyTyCon 1 -> do { ax <- get bh ; br <- get bh ; return (IfaceClosedSynFamilyTyCon ax br) } _ -> return IfaceAbstractClosedSynFamilyTyCon } instance Binary IfaceClassOp where put_ bh (IfaceClassOp n def ty) = do put_ bh (occNameFS n) put_ bh def put_ bh ty get bh = do n <- get bh def <- get bh ty <- get bh occ <- return $! mkVarOccFS n return (IfaceClassOp occ def ty) instance Binary IfaceAT where put_ bh (IfaceAT dec defs) = do put_ bh dec put_ bh defs get bh = do dec <- get bh defs <- get bh return (IfaceAT dec defs) instance Binary IfaceAxBranch where put_ bh (IfaceAxBranch a1 a2 a3 a4 a5) = do put_ bh a1 put_ bh a2 put_ bh a3 put_ bh a4 put_ bh a5 get bh = do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh a5 <- get bh return (IfaceAxBranch a1 a2 a3 a4 a5) instance Binary IfaceConDecls where put_ bh (IfAbstractTyCon d) = putByte bh 0 >> put_ bh d put_ bh IfDataFamTyCon = putByte bh 1 put_ bh (IfDataTyCon cs) = putByte bh 2 >> put_ bh cs put_ bh (IfNewTyCon c) = putByte bh 3 >> put_ bh c get bh = do h <- getByte bh case h of 0 -> liftM IfAbstractTyCon $ get bh 1 -> return IfDataFamTyCon 2 -> liftM IfDataTyCon $ get bh _ -> liftM IfNewTyCon $ get bh instance Binary IfaceConDecl where put_ bh (IfCon a1 a2 a3 a4 a5 a6 a7 a8 a9) = do put_ bh a1 put_ bh a2 put_ bh a3 put_ bh a4 put_ bh a5 put_ bh a6 put_ bh a7 put_ bh a8 put_ bh a9 get bh = do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh a5 <- get bh a6 <- get bh a7 <- get bh a8 <- get bh a9 <- get bh return (IfCon a1 a2 a3 a4 a5 a6 a7 a8 a9) instance Binary IfaceBang where put_ bh IfNoBang = putByte bh 0 put_ bh IfStrict = putByte bh 1 put_ bh IfUnpack = putByte bh 2 put_ bh (IfUnpackCo co) = putByte bh 3 >> put_ bh co get bh = do h <- getByte bh case h of 0 -> do return IfNoBang 1 -> do return IfStrict 2 -> do return IfUnpack _ -> do { a <- get bh; return (IfUnpackCo a) } instance Binary IfaceClsInst where put_ bh (IfaceClsInst cls tys dfun flag orph) = do put_ bh cls put_ bh tys put_ bh dfun put_ bh flag put_ bh orph get bh = do cls <- get bh tys <- get bh dfun <- get bh flag <- get bh orph <- get bh return (IfaceClsInst cls tys dfun flag orph) instance Binary IfaceFamInst where put_ bh (IfaceFamInst fam tys name orph) = do put_ bh fam put_ bh tys put_ bh name put_ bh orph get bh = do fam <- get bh tys <- get bh name <- get bh orph <- get bh return (IfaceFamInst fam tys name orph) instance Binary IfaceRule where put_ bh (IfaceRule a1 a2 a3 a4 a5 a6 a7 a8) = do put_ bh a1 put_ bh a2 put_ bh a3 put_ bh a4 put_ bh a5 put_ bh a6 put_ bh a7 put_ bh a8 get bh = do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh a5 <- get bh a6 <- get bh a7 <- get bh a8 <- get bh return (IfaceRule a1 a2 a3 a4 a5 a6 a7 a8) instance Binary IfaceAnnotation where put_ bh (IfaceAnnotation a1 a2) = do put_ bh a1 put_ bh a2 get bh = do a1 <- get bh a2 <- get bh return (IfaceAnnotation a1 a2) instance Binary IfaceIdDetails where put_ bh IfVanillaId = putByte bh 0 put_ bh (IfRecSelId a b) = putByte bh 1 >> put_ bh a >> put_ bh b put_ bh (IfDFunId n) = do { putByte bh 2; put_ bh n } get bh = do h <- getByte bh case h of 0 -> return IfVanillaId 1 -> do { a <- get bh; b <- get bh; return (IfRecSelId a b) } _ -> do { n <- get bh; return (IfDFunId n) } instance Binary IfaceIdInfo where put_ bh NoInfo = putByte bh 0 put_ bh (HasInfo i) = putByte bh 1 >> lazyPut bh i -- NB lazyPut get bh = do h <- getByte bh case h of 0 -> return NoInfo _ -> liftM HasInfo $ lazyGet bh -- NB lazyGet instance Binary IfaceInfoItem where put_ bh (HsArity aa) = putByte bh 0 >> put_ bh aa put_ bh (HsStrictness ab) = putByte bh 1 >> put_ bh ab put_ bh (HsUnfold lb ad) = putByte bh 2 >> put_ bh lb >> put_ bh ad put_ bh (HsInline ad) = putByte bh 3 >> put_ bh ad put_ bh HsNoCafRefs = putByte bh 4 get bh = do h <- getByte bh case h of 0 -> liftM HsArity $ get bh 1 -> liftM HsStrictness $ get bh 2 -> do lb <- get bh ad <- get bh return (HsUnfold lb ad) 3 -> liftM HsInline $ get bh _ -> return HsNoCafRefs instance Binary IfaceUnfolding where put_ bh (IfCoreUnfold s e) = do putByte bh 0 put_ bh s put_ bh e put_ bh (IfInlineRule a b c d) = do putByte bh 1 put_ bh a put_ bh b put_ bh c put_ bh d put_ bh (IfDFunUnfold as bs) = do putByte bh 2 put_ bh as put_ bh bs put_ bh (IfCompulsory e) = do putByte bh 3 put_ bh e get bh = do h <- getByte bh case h of 0 -> do s <- get bh e <- get bh return (IfCoreUnfold s e) 1 -> do a <- get bh b <- get bh c <- get bh d <- get bh return (IfInlineRule a b c d) 2 -> do as <- get bh bs <- get bh return (IfDFunUnfold as bs) _ -> do e <- get bh return (IfCompulsory e) instance Binary IfaceExpr where put_ bh (IfaceLcl aa) = do putByte bh 0 put_ bh aa put_ bh (IfaceType ab) = do putByte bh 1 put_ bh ab put_ bh (IfaceCo ab) = do putByte bh 2 put_ bh ab put_ bh (IfaceTuple ac ad) = do putByte bh 3 put_ bh ac put_ bh ad put_ bh (IfaceLam (ae, os) af) = do putByte bh 4 put_ bh ae put_ bh os put_ bh af put_ bh (IfaceApp ag ah) = do putByte bh 5 put_ bh ag put_ bh ah put_ bh (IfaceCase ai aj ak) = do putByte bh 6 put_ bh ai put_ bh aj put_ bh ak put_ bh (IfaceLet al am) = do putByte bh 7 put_ bh al put_ bh am put_ bh (IfaceTick an ao) = do putByte bh 8 put_ bh an put_ bh ao put_ bh (IfaceLit ap) = do putByte bh 9 put_ bh ap put_ bh (IfaceFCall as at) = do putByte bh 10 put_ bh as put_ bh at put_ bh (IfaceExt aa) = do putByte bh 11 put_ bh aa put_ bh (IfaceCast ie ico) = do putByte bh 12 put_ bh ie put_ bh ico put_ bh (IfaceECase a b) = do putByte bh 13 put_ bh a put_ bh b get bh = do h <- getByte bh case h of 0 -> do aa <- get bh return (IfaceLcl aa) 1 -> do ab <- get bh return (IfaceType ab) 2 -> do ab <- get bh return (IfaceCo ab) 3 -> do ac <- get bh ad <- get bh return (IfaceTuple ac ad) 4 -> do ae <- get bh os <- get bh af <- get bh return (IfaceLam (ae, os) af) 5 -> do ag <- get bh ah <- get bh return (IfaceApp ag ah) 6 -> do ai <- get bh aj <- get bh ak <- get bh return (IfaceCase ai aj ak) 7 -> do al <- get bh am <- get bh return (IfaceLet al am) 8 -> do an <- get bh ao <- get bh return (IfaceTick an ao) 9 -> do ap <- get bh return (IfaceLit ap) 10 -> do as <- get bh at <- get bh return (IfaceFCall as at) 11 -> do aa <- get bh return (IfaceExt aa) 12 -> do ie <- get bh ico <- get bh return (IfaceCast ie ico) 13 -> do a <- get bh b <- get bh return (IfaceECase a b) _ -> panic ("get IfaceExpr " ++ show h) instance Binary IfaceTickish where put_ bh (IfaceHpcTick m ix) = do putByte bh 0 put_ bh m put_ bh ix put_ bh (IfaceSCC cc tick push) = do putByte bh 1 put_ bh cc put_ bh tick put_ bh push put_ bh (IfaceSource src name) = do putByte bh 2 put_ bh (srcSpanFile src) put_ bh (srcSpanStartLine src) put_ bh (srcSpanStartCol src) put_ bh (srcSpanEndLine src) put_ bh (srcSpanEndCol src) put_ bh name get bh = do h <- getByte bh case h of 0 -> do m <- get bh ix <- get bh return (IfaceHpcTick m ix) 1 -> do cc <- get bh tick <- get bh push <- get bh return (IfaceSCC cc tick push) 2 -> do file <- get bh sl <- get bh sc <- get bh el <- get bh ec <- get bh let start = mkRealSrcLoc file sl sc end = mkRealSrcLoc file el ec name <- get bh return (IfaceSource (mkRealSrcSpan start end) name) _ -> panic ("get IfaceTickish " ++ show h) instance Binary IfaceConAlt where put_ bh IfaceDefault = putByte bh 0 put_ bh (IfaceDataAlt aa) = putByte bh 1 >> put_ bh aa put_ bh (IfaceLitAlt ac) = putByte bh 2 >> put_ bh ac get bh = do h <- getByte bh case h of 0 -> return IfaceDefault 1 -> liftM IfaceDataAlt $ get bh _ -> liftM IfaceLitAlt $ get bh instance Binary IfaceBinding where put_ bh (IfaceNonRec aa ab) = putByte bh 0 >> put_ bh aa >> put_ bh ab put_ bh (IfaceRec ac) = putByte bh 1 >> put_ bh ac get bh = do h <- getByte bh case h of 0 -> do { aa <- get bh; ab <- get bh; return (IfaceNonRec aa ab) } _ -> do { ac <- get bh; return (IfaceRec ac) } instance Binary IfaceLetBndr where put_ bh (IfLetBndr a b c) = do put_ bh a put_ bh b put_ bh c get bh = do a <- get bh b <- get bh c <- get bh return (IfLetBndr a b c) instance Binary IfaceTyConParent where put_ bh IfNoParent = putByte bh 0 put_ bh (IfDataInstance ax pr ty) = do putByte bh 1 put_ bh ax put_ bh pr put_ bh ty get bh = do h <- getByte bh case h of 0 -> return IfNoParent _ -> do ax <- get bh pr <- get bh ty <- get bh return $ IfDataInstance ax pr ty
bitemyapp/ghc
compiler/iface/IfaceSyn.hs
bsd-3-clause
70,388
76
27
23,556
17,400
8,654
8,746
1,343
11
module UnionFind(UF, Replacement((:>)), newSym, (=:=), rep, evalUF, execUF, runUF, S, isRep, initial) where import Prelude hiding (min) import Control.Monad.State.Strict import Data.IntMap(IntMap) import qualified Data.IntMap as IntMap data S = S { links :: IntMap Int, sym :: Int } type UF = State S data Replacement = Int :> Int runUF :: S -> UF a -> (a, S) runUF s m = runState m s evalUF :: S -> UF a -> a evalUF s m = fst (runUF s m) execUF :: S -> UF a -> S execUF s m = snd (runUF s m) initial :: Int -> S initial n = S IntMap.empty n modifyLinks f = modify (\s -> s { links = f (links s) }) modifySym f = modify (\s -> s { sym = f (sym s) }) putLinks l = modifyLinks (const l) newSym :: UF Int newSym = do s <- get modifySym (+1) return (sym s) (=:=) :: Int -> Int -> UF (Maybe Replacement) s =:= t | s == t = return Nothing s =:= t = do rs <- rep s rt <- rep t if (rs /= rt) then do modifyLinks (IntMap.insert rs rt) return (Just (rs :> rt)) else return Nothing rep :: Int -> UF Int rep t = do m <- fmap links get case IntMap.lookup t m of Nothing -> return t Just t' -> do r <- rep t' when (t' /= r) $ modifyLinks (IntMap.insert t r) return r isRep :: Int -> UF Bool isRep t = do t' <- rep t return (t == t')
jystic/QuickSpec
UnionFind.hs
bsd-3-clause
1,304
0
16
354
679
346
333
50
2
{-# LANGUAGE FlexibleContexts #-} import Test.Hspec import Text.Parsec import Control.Monad.State intS :: Monad m => ParsecT String s m String intS = many1 digit getNext k s | x > n2 = n1 * base + x | x <= n2 = (1 + n1) * base + x where base = 10 ^ (length s) (n1, n2) = k `quotRem` base x = read s dashed :: MonadState Int m => ParsecT String s m [Int] dashed = do from <- liftM2 getNext get intS char '-' to <- intS let next = getNext from to put next return $! [from .. next] coloned2 :: MonadState Int m => ParsecT String s m [Int] coloned2 = do from <- liftM2 getNext get intS char ':' to <- intS char ':' step <- read <$> intS let next = getNext from to put next return $! [from, from + step .. next] coloned1 :: MonadState Int m => ParsecT String s m [Int] coloned1 = do from <- liftM2 getNext get intS char ',' to <- intS char ':' step <- intS let from' = getNext from to next = getNext from' step put next return $! from : [from'..next] dotted :: MonadState Int m => ParsecT String s m [Int] dotted = do from <- liftM2 getNext get intS string ".." to <- intS let next = getNext from to put next return [from .. next] intP :: MonadState Int m => ParsecT String s m [Int] intP = do next <- liftM2 getNext get intS put next return [next] rangedP :: MonadState Int m => ParsecT String s m [Int] rangedP = try coloned1 <|> try coloned2 <|> try dashed <|> try dotted <|> intP parser :: MonadState Int m => ParsecT String s m [Int] parser = concat <$> sepBy rangedP (char ',') parseRangedInts :: String -> Either ParseError [Int] parseRangedInts s = evalState (runParserT parser 0 "<stdin>" s) (-1) testcases :: [ (String, Either ParseError [Int]) ] testcases = [("1,3,7,2,4,1", pure [1,3,7,12,14,21]),("1-3,1-2", pure [1,2,3,11,12]),("1:5:2", pure [1,3,5]),("104-2", pure [104,105,106,107,108,109,110,111,112]),("104..02", pure [104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202]),("545,64:11", pure (545:[564..611]))] main :: IO () main = hspec $ do describe "pass all initial test cases" $ do it "all success.." $ do and (map (\(i, o) -> parseRangedInts i == o) testcases) `shouldBe` True
wangbj/excises
e292.hs
bsd-3-clause
2,607
2
21
547
1,331
717
614
70
1
{-# LANGUAGE OverloadedStrings, RankNTypes, TypeSynonymInstances, FlexibleInstances, OverloadedLists, DeriveGeneric, DeriveAnyClass #-} {- Column datastore approach. Starting with a lightweight directory structure - 1 database per 1 running instance, thus: SYSDIR |---- metadata: file with database metadata |---- Table1Dir: folder for a specific table |------ metadata: file with table structure metadata |------ RAW: folder with raw columns |------ metadata: file with raw columns metadata (names and types basically?) |------ column0: file with Column0 raw data |------ column1: file with Column1 raw data (automatically parsed into GenericColumn with correct type) |------ OPTIMIZED: folder with optimized columns (first of all, Text - only unique text values plus hashmap) |------ INDEX: folder with indices (in the future) -} module Quark.Base.Storage ( saveGenColumn, loadGenColumn, createTableMetadata, saveCTable, loadCTable -- saveColumn, -- loadColumn ) where import Quark.Base.Column import System.Directory -- directory manipulations import Data.Binary import qualified Data.ByteString.Lazy as BL import qualified Data.Vector.Generic as G import qualified Data.HashMap.Strict as Map import Data.Hashable import Data.Text import GHC.Generics (Generic) data TableMetadata = TableMetadata { rawColumnsMeta :: [(Text, FilePath)] -- name of the column and full link to the column file } deriving(Show, Generic) instance Binary TableMetadata -- pure function that creates TableMetadata from a given Table and table directory path createTableMetadata :: CTable -- CTable -> FilePath -- system directory (Now, FLAT - so we put everything in this dir) -> TableMetadata -- resulting metadata createTableMetadata ct fp = TableMetadata {rawColumnsMeta = fst $ Map.foldlWithKey' proc ([], 0) ct} where proc (lst, i) k v = ( (k, fp ++ "/column" ++ show i) : lst, i + 1) -- | save a CTable - starting with only RAW columns saveCTable :: CTable -- ^ CTable to save -> FilePath -- ^ System Directory path -> IO () saveCTable table sysDir = do let meta = createTableMetadata table sysDir BL.writeFile (sysDir ++ "/metadata") (encode meta) -- saving metadata first mapM_ proc (rawColumnsMeta meta) -- processing columns where proc (n, fp) = do let col = Map.lookup n table case col of Just c -> saveGenColumn fp c Nothing -> return () -- | load a CTable previously saved with saveCTable loadCTable :: FilePath -- ^ directory with table metadata -> IO CTable -- ^ resulting CTable with loaded columns (how to handle errors?) loadCTable fp = do metafile <- BL.readFile (fp ++ "/metadata") -- reading metadata file from a given folder let meta = decode metafile :: TableMetadata -- decoding metadata file ls <- mapM proc (rawColumnsMeta meta) -- loading all columns in order return (Map.fromList ls) -- returning CTable where proc (n, fpath) = do gc <- loadGenColumn fpath return (n, gc) -- Generic column serialization saveGenColumn :: FilePath -> GenericColumn -> IO () saveGenColumn file col = BL.writeFile file (encode col) loadGenColumn :: FilePath -> IO GenericColumn loadGenColumn file = BL.readFile file >>= return . decode listFiles = getDirectoryContents {- saveColumn :: (G.Vector v a, Binary (v a )) => FilePath -> Column v a -> IO () saveColumn file col = BL.writeFile file (encode col) loadColumn :: (G.Vector v a, Binary (v a )) => FilePath -> IO (Column v a) loadColumn file = BL.readFile file >>= return . decode -}
jhoxray/muon
src/Quark/Base/Storage.hs
bsd-3-clause
4,113
0
13
1,212
602
328
274
54
2
{-# LANGUAGE Rank2Types, TemplateHaskell #-} module Data.Zippable1 where import Control.Arrow import Data.Functor1 import Language.Haskell.TH import Language.Haskell.TH.Util class Zippable1 t where zip1 :: (forall a. f a -> g a -> h a) -> t f -> t g -> t h data Pair1 f g a = Pair1 { unPair1 :: (f a, g a) } mkPair1 :: f a -> g a -> Pair1 f g a mkPair1 f g = Pair1 (f, g) zip1_3 :: (Functor1 t, Zippable1 t) => (forall a. f a -> g a -> h a -> i a) -> t f -> t g -> t h -> t i zip1_3 z fa ga ha = fmap1 (\(Pair1 (f,Pair1 (g,h))) -> z f g h) $ zip1 mkPair1 fa (zip1 mkPair1 ga ha) zip1_4 :: (Functor1 t, Zippable1 t) => (forall a. f a -> g a -> h a -> i a -> j a) -> t f -> t g -> t h -> t i -> t j zip1_4 z fa ga ha ia = fmap1 (\(Pair1 (Pair1 (f, g), Pair1 (h,i))) -> z f g h i) $ zip1 mkPair1 (zip1 mkPair1 fa ga) (zip1 mkPair1 ha ia) mkZippable1 :: Name -> Q [Dec] mkZippable1 = withTyConReify mkZippable1' mkZippable1' :: Dec -> Q [Dec] mkZippable1' (DataD _ tnm pars [con] _) = do names <- mapM newName $ map (('v':) . show) [1..(30 :: Int)] names2 <- mapM newName $ map (('v':) . show) [1..(30 :: Int)] let (ps, f) = (\(x: xs) -> (reverse xs, x)) $ reverse $ map getTV pars (cnm, tps) = getCons con funcName = mkName "f" mkType (vn1, vn2) (AppT tf a) | tf == VarT f = ([], VarE funcName `AppE` VarE vn1 `AppE` VarE vn2) | a == VarT f = ([tf], VarE (mkName "zip1") `AppE` VarE funcName `AppE` VarE vn1 `AppE` VarE vn2) mkType _ _ = error "Not a valid field type" (preds, exps) = first concat . unzip $ zipWith mkType (zip names names2) tps cls = Clause [ VarP funcName, ConP cnm $ map VarP $ take (length exps) names , ConP cnm $ map VarP $ take (length exps) names2 ] (NormalB $ foldl AppE (ConE cnm) exps) [] return [InstanceD (map (ClassP (mkName "Zippable1") . (:[])) preds) (ConT (mkName "Zippable1") `AppT` (foldl AppT (ConT tnm) $ map VarT ps)) [FunD (mkName "zip1") [cls]] ] mkZippable1' _ = error "Can only derive Zippable1 for data type"
craffit/flexdb
src/Data/Zippable1.hs
bsd-3-clause
2,225
0
17
684
1,120
570
550
43
2
module BLAKE ( benchmarks -- :: IO [Benchmark] ) where import Criterion.Main import Crypto.Hash.BLAKE import qualified Data.ByteString as B import Util () benchmarks :: IO [Benchmark] benchmarks = return [ bench "blake256" $ nf blake256 (B.replicate 512 3) , bench "blake512" $ nf blake512 (B.replicate 512 3) ]
thoughtpolice/hs-nacl
benchmarks/BLAKE.hs
bsd-3-clause
380
0
11
116
104
58
46
10
1
{-# LANGUAGE Arrows #-} {-# LANGUAGE RecordWildCards #-} module Parse.Command where import Spec.Command import Parse.Utils import Parse.CType import Text.XML.HXT.Core parseCommand :: ParseArrow XmlTree Command parseCommand = hasName "command" >>> (extract `orElse` failA "Failed to extract command fields") where extract = proc command -> do proto <- onlyChildWithName "proto" -< command cName <- getAllText <<< onlyChildWithName "name" -< proto cReturnType <- parseCType <<< getAllText <<< processChildren (neg (hasName "name")) -< proto cParameters <- listA (parseParam <<< getChildren) -< command cImplicitExternSyncParams <- oneRequired "implicit extern sync params" (optional (parseIESPBlock <<< getChildren)) -< command cQueues <- optionalCommaSepListAttr "queues" -< command cRenderPass <- optionalAttrValue "renderpass" -< command cCommandBufferLevels <- optionalCommaSepListAttr "cmdbufferlevel" -< command cSuccessCodes <- optionalCommaSepListAttr "successcodes" -< command cErrorCodes <- optionalCommaSepListAttr "errorcodes" -< command cUsage <- oneRequired "usage" (optional (parseValidityBlock <<< getChildren)) -< command returnA -< Command{..} -- | Implicit External Sync Params parseIESPBlock :: ArrowXml a => a XmlTree [String] parseIESPBlock = hasName "implicitexternsyncparams" >>> listA (getChildren >>> hasName "param" >>> getAllText) parseParam :: ParseArrow XmlTree Parameter parseParam = hasName "param" >>> (extract `orElse` failA "Failed to extract param fields") where extract = proc param -> do pName <- getAllText <<< onlyChildWithName "name" -< param pType <- parseCType <<< getAllText <<< processChildren (neg (hasName "name")) -< param pIsOptional <- traverseMaybeA (mapA parseBool) <<< optionalCommaSepListAttr "optional" -< param pIsExternSync <- fmap parseExternSync ^<< optionalAttrValue "externsync" -< param pLengths <- optionalCommaSepListAttr "len" -< param pNoAutoValidity <- (traverseMaybeA parseBool `orElse` failA "Failed to parse autovalidity attribute") <<< optionalAttrValue "noautovalidity" -< param returnA -< Parameter{..} parseExternSync :: String -> ExternSync parseExternSync "true" = ExternSyncTrue parseExternSync ss = ExternSyncParams (commaSepList ss)
oldmanmike/vulkan
generate/src/Parse/Command.hs
bsd-3-clause
2,673
2
17
727
596
289
307
52
1
{-# LANGUAGE TypeOperators, DataKinds #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Metrology.SI.Poly -- Copyright : (C) 2013 Richard Eisenberg -- License : BSD-style (see LICENSE) -- Maintainer : Richard Eisenberg (rae@cs.brynmawr.edu) -- Stability : experimental -- Portability : non-portable -- -- This module exports definitions for the SI system, with the intent -- of using these definitions in a polymorphic manner -- that is, -- with multiple LCSUs. ----------------------------------------------------------------------------- module Data.Metrology.SI.Poly ( SI, module Data.Metrology.SI.PolyTypes, module Data.Units.SI.Prefixes, module Data.Units.SI, module Data.Units.SI.Parser ) where import Data.Metrology.SI.PolyTypes import Data.Units.SI.Prefixes import Data.Units.SI import qualified Data.Dimensions.SI as D import Data.Metrology import Data.Units.SI.Parser type SI = MkLCSU '[ (D.Length, Meter) , (D.Mass, Kilo :@ Gram) , (D.Time, Second) , (D.Current, Ampere) , (D.Temperature, Kelvin) , (D.AmountOfSubstance, Mole) , (D.LuminousIntensity, Lumen) , (D.PlaneAngle, Radian) , (D.SolidAngle, Steradian) ]
goldfirere/units
units-defs/Data/Metrology/SI/Poly.hs
bsd-3-clause
1,376
0
9
330
213
146
67
22
0
{-# LANGUAGE DeriveDataTypeable #-} module Sgf.Control.Exception ( FileException (..) , doesFileExist' ) where import Data.Typeable import Control.Monad import Control.Monad.IO.Class import Control.Exception import System.Directory data FileException = FileDoesNotExist FilePath deriving (Typeable) instance Show FileException where show (FileDoesNotExist e) = "File does not exist: '" ++ e ++ "'" instance Exception FileException where doesFileExist' :: MonadIO m => FilePath -> m () doesFileExist' x = do b <- liftIO (doesFileExist x) unless b $ throw (FileDoesNotExist x)
sgf-dma/sgf-haskell-common
src/Sgf/Control/Exception.hs
bsd-3-clause
615
0
10
115
165
88
77
18
1
{-# LANGUAGE ImplicitParams #-} module Frontend.ExprFlatten(exprFlatten, exprFlatten', flattenName, unflattenName) where import Data.List.Split import Name import Frontend.Expr import {-# SOURCE #-} Frontend.ExprOps import Frontend.InstTree import Frontend.Type import Frontend.Spec import Frontend.NS import Frontend.Template import Pos -- Flatten static enum or const name by prepending template name to it flattenName :: (WithName a) => Template -> a -> Ident flattenName t x = Ident (pos $ name x) $ (sname t) ++ "::" ++ (sname x) unflattenName :: Ident -> StaticSym unflattenName n = map (Ident nopos) $ splitOn "::" (sname n) exprFlatten :: (?spec::Spec) => IID -> Scope -> Expr -> Expr exprFlatten iid s e = mapExpr (exprFlatten' iid) s e exprFlatten' :: (?spec::Spec) => IID -> Scope -> Expr -> Expr exprFlatten' iid s e@(ETerm p n) = case getTerm s n of ObjGVar _ v -> ETerm p [itreeFlattenName iid (name v)] ObjWire _ w -> ETerm p [itreeFlattenName iid (name w)] ObjEnum (Type (ScopeTemplate t) _) en -> ETerm p [flattenName t en] ObjConst (ScopeTemplate t) c -> ETerm p [flattenName t c] _ -> e exprFlatten' iid s (EField p e f) = let ?scope = s in case exprTypeSpec e of TemplateTypeSpec _ tn -> case objGet (ObjTemplate $ getTemplate tn) f of ObjGVar _ v -> ETerm p [itreeFlattenName (itreeRelToAbsPath iid (epath e)) (name v)] ObjWire _ w -> ETerm p [itreeFlattenName (itreeRelToAbsPath iid (epath e)) (name w)] where epath (ETerm _ n) = n epath (EField _ e' n) = epath e' ++ [n] _ -> EField p e f exprFlatten' iid _ (EApply p (MethodRef p' n) as) = EApply p (MethodRef p' [itreeFlattenName (itreeRelToAbsPath iid (init n)) (last n)]) as exprFlatten' iid _ (EAtLab p l) = EAtLab p $ itreeFlattenName iid l exprFlatten' iid _ (ERel p n as) = ERel p (itreeFlattenName iid n) as exprFlatten' _ _ e = e
termite2/tsl
Frontend/ExprFlatten.hs
bsd-3-clause
2,436
0
19
934
794
400
394
41
8
data X = X { foo :: Int, bar :: String } deriving ( Eq , Ord , Show ) f x = x
itchyny/vim-haskell-indent
test/recordtype/after_deriving_lines_comma_first.in.hs
mit
78
0
8
24
45
25
20
-1
-1
-- -- -- ----------------- -- Exercise 5.32. ----------------- -- -- -- module E'5'32 where import E'5'27 ( Book , Person ) type Database'' = [(Person, [Book])] exampleDB'' :: Database'' exampleDB'' = [ ( "Alice" , ["Tintin", "Asterix"] ) , ( "Anna" , ["Little Women"] ) , ( "Rory" , ["Tintin"] ) ] bookListsListToList :: [[Book]] -> [Book] bookListsListToList bookListsList = [ currentBook | bookList <- bookListsList, currentBook <- bookList ] {- GHCi> bookListsListToList [ ["A"] ,["B"] ] -} -- [ "A" , "B" ] books'' :: Database'' -> Person -> [Book] books'' database person = bookListsListToList bookListList where bookListList :: [[Book]] bookListList = [ bookList | ( currentPerson , bookList ) <- database, currentPerson == person ] {- GHCi> books'' exampleDB'' "Alice" -} -- [ "Tintin", "Asterix" ] makeLoan'' :: Database'' -> Person -> Book -> Database'' makeLoan'' database person book | not (person `elem` persons) = database ++ [(person, [book])] | otherwise = personLoaned ++ other where persons :: [Person] persons = [ currentPerson | (currentPerson, _) <- database ] personLoaned :: [(Person, [Book])] personLoaned = [ ( currentPerson , currentBookList ++ [book] ) | ( currentPerson , currentBookList ) <- database, currentPerson == person ] other :: [(Person, [Book])] other = [ ( currentPerson , currentBookList ) | (currentPerson, currentBookList) <- database, currentPerson /= person ] {- GHCi> makeLoan'' exampleDB'' "Alice" "New Book" -} -- [ -- ( "Alice" , ["Tintin", "Asterix" , "New Book"] ) , -- ( "Anna" , ["Little Women"] ) , -- ( "Rory" , ["Tintin"] ) -- ] returnLoan'' :: Database'' -> Person -> Book -> Database'' returnLoan'' database person book = personReturned ++ other where bookListsList :: [[Book]] bookListsList = [ currentBookList | (currentPerson, currentBookList) <- database, currentPerson == person ] bookReturned :: [Book] bookReturned = [ currentBook | currentBook <- (bookListsListToList bookListsList), currentBook /= book ] personReturned :: [(Person, [Book])] personReturned = [ ( currentPerson , bookReturned ) | ( currentPerson , _ ) <- database, currentPerson == person ] other :: [(Person, [Book])] other = [ ( currentPerson , currentBookList ) | ( currentPerson , currentBookList ) <- database, currentPerson /= person ] {- GHCi> returnLoan'' exampleDB'' "Alice" "Tintin" -} -- [ -- ( "Alice" , ["Asterix"] ) , -- ( "Anna" , ["Little Women"] ) , -- ( "Rory" , ["Tintin"] ) -- ] -- Note: I didn't use higher order functions, because this represents the -- solution if you chose a linear approach (reading the book, starting -- at the first and ending with the last page) and not using materials -- or knowledge (you might already have) to ease the pain. It feels like -- this is the authors intention. If you do this, you note lots of subtleties. -- Its training your thinking (and your eyes) to spot lots of problems in an -- very early state of development.
pascal-knodel/haskell-craft
_/links/E'5'32.hs
mit
3,748
0
11
1,308
672
405
267
56
1
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_HADDOCK show-extensions #-} {-# LANGUAGE MultiWayIf #-} -- | -- Module : Yi.Buffer.HighLevel -- License : GPL-2 -- Maintainer : yi-devel@googlegroups.com -- Stability : experimental -- Portability : portable -- -- High level operations on buffers. module Yi.Buffer.HighLevel ( atEof , atEol , atLastLine , atSol , atSof , bdeleteB , bdeleteLineB , bkillWordB , botB , bufInfoB , BufferFileInfo (..) , capitaliseWordB , deleteBlankLinesB , deleteHorizontalSpaceB , deleteRegionWithStyleB , deleteToEol , deleteTrailingSpaceB , downFromTosB , downScreenB , downScreensB , exchangePointAndMarkB , fillParagraph , findMatchingPairB , firstNonSpaceB , flipRectangleB , getBookmarkB , getLineAndCol , getLineAndColOfPoint , getNextLineB , getNextNonBlankLineB , getRawestSelectRegionB , getSelectionMarkPointB , getSelectRegionB , gotoCharacterB , hasWhiteSpaceBefore , incrementNextNumberByB , insertRopeWithStyleB , isCurrentLineAllWhiteSpaceB , isCurrentLineEmptyB , isNumberB , killWordB , lastNonSpaceB , leftEdgesOfRegionB , leftOnEol , lineMoveVisRel , linePrefixSelectionB , lineStreamB , lowercaseWordB , middleB , modifyExtendedSelectionB , moveNonspaceOrSol , movePercentageFileB , moveToMTB , moveToEol , moveToSol , moveXorEol , moveXorSol , nextCExc , nextCInc , nextCInLineExc , nextCInLineInc , nextNParagraphs , nextWordB , prevCExc , prevCInc , prevCInLineExc , prevCInLineInc , prevNParagraphs , prevWordB , readCurrentWordB , readLnB , readPrevWordB , readRegionRopeWithStyleB , replaceBufferContent , revertB , rightEdgesOfRegionB , scrollB , scrollCursorToBottomB , scrollCursorToTopB , scrollScreensB , scrollToCursorB , scrollToLineAboveWindowB , scrollToLineBelowWindowB , selectNParagraphs , setSelectionMarkPointB , setSelectRegionB , shapeOfBlockRegionB , sortLines , sortLinesWithRegion , snapInsB , snapScreenB , splitBlockRegionToContiguousSubRegionsB , swapB , switchCaseChar , test3CharB , testHexB , toggleCommentB , topB , unLineCommentSelectionB , upFromBosB , uppercaseWordB , upScreenB , upScreensB , vimScrollB , vimScrollByB , markWord ) where import Lens.Micro.Platform (over, use, (%=), (.=), _last) import Control.Monad (forM, forM_, replicateM_, unless, void, when) import Control.Monad.RWS.Strict (ask) import Control.Monad.State (gets) import Data.Char (isDigit, isHexDigit, isOctDigit, isSpace, isUpper, toLower, toUpper) import Data.List (intersperse, sort) import Data.List.NonEmpty (NonEmpty(..)) import Data.Maybe (catMaybes, fromMaybe, listToMaybe) import Data.Monoid ((<>)) import qualified Data.Set as Set import qualified Data.Text as T (Text, toLower, toUpper, unpack) import Data.Time (UTCTime) import Data.Tuple (swap) import Numeric (readHex, readOct, showHex, showOct) import Yi.Buffer.Basic (Direction (..), Mark, Point (..), Size (Size)) import Yi.Buffer.Misc import Yi.Buffer.Normal import Yi.Buffer.Region import Yi.Config.Misc (ScrollStyle (SingleLine)) import Yi.Rope (YiString) import qualified Yi.Rope as R import Yi.String (capitalizeFirst, fillText, isBlank, mapLines, onLines, overInit) import Yi.Utils (SemiNum ((+~), (-~))) import Yi.Window (Window (actualLines, width, wkey)) -- --------------------------------------------------------------------- -- Movement operations -- | Move point between the middle, top and bottom of the screen -- If the point stays at the middle, it'll be gone to the top -- else if the point stays at the top, it'll be gone to the bottom -- else it'll be gone to the middle moveToMTB :: BufferM () moveToMTB = (==) <$> curLn <*> screenMidLn >>= \case True -> downFromTosB 0 _ -> (==) <$> curLn <*> screenTopLn >>= \case True -> upFromBosB 0 _ -> downFromTosB =<< (-) <$> screenMidLn <*> screenTopLn -- | Move point to start of line moveToSol :: BufferM () moveToSol = maybeMoveB Line Backward -- | Move point to end of line moveToEol :: BufferM () moveToEol = maybeMoveB Line Forward -- | Move cursor to origin topB :: BufferM () topB = moveTo 0 -- | Move cursor to end of buffer botB :: BufferM () botB = moveTo =<< sizeB -- | Move left if on eol, but not on blank line leftOnEol :: BufferM () -- @savingPrefCol@ is needed, because deep down @leftB@ contains @forgetPrefCol@ -- which messes up vertical cursor motion in Vim normal mode leftOnEol = savingPrefCol $ do eol <- atEol sol <- atSol when (eol && not sol) leftB -- | Move @x@ chars back, or to the sol, whichever is less moveXorSol :: Int -> BufferM () moveXorSol x = replicateM_ x $ do c <- atSol; unless c leftB -- | Move @x@ chars forward, or to the eol, whichever is less moveXorEol :: Int -> BufferM () moveXorEol x = replicateM_ x $ do c <- atEol; unless c rightB -- | Move to first char of next word forwards nextWordB :: BufferM () nextWordB = moveB unitWord Forward -- | Move to first char of next word backwards prevWordB :: BufferM () prevWordB = moveB unitWord Backward -- * Char-based movement actions. gotoCharacterB :: Char -> Direction -> RegionStyle -> Bool -> BufferM () gotoCharacterB c dir style stopAtLineBreaks = do start <- pointB let predicate = if stopAtLineBreaks then (`elem` [c, '\n']) else (== c) (move, moveBack) = if dir == Forward then (rightB, leftB) else (leftB, rightB) doUntilB_ (predicate <$> readB) move b <- readB if stopAtLineBreaks && b == '\n' then moveTo start else when (style == Exclusive && b == c) moveBack -- | Move to the next occurence of @c@ nextCInc :: Char -> BufferM () nextCInc c = gotoCharacterB c Forward Inclusive False nextCInLineInc :: Char -> BufferM () nextCInLineInc c = gotoCharacterB c Forward Inclusive True -- | Move to the character before the next occurence of @c@ nextCExc :: Char -> BufferM () nextCExc c = gotoCharacterB c Forward Exclusive False nextCInLineExc :: Char -> BufferM () nextCInLineExc c = gotoCharacterB c Forward Exclusive True -- | Move to the previous occurence of @c@ prevCInc :: Char -> BufferM () prevCInc c = gotoCharacterB c Backward Inclusive False prevCInLineInc :: Char -> BufferM () prevCInLineInc c = gotoCharacterB c Backward Inclusive True -- | Move to the character after the previous occurence of @c@ prevCExc :: Char -> BufferM () prevCExc c = gotoCharacterB c Backward Exclusive False prevCInLineExc :: Char -> BufferM () prevCInLineExc c = gotoCharacterB c Backward Exclusive True -- | Move to first non-space character in this line firstNonSpaceB :: BufferM () firstNonSpaceB = do moveToSol untilB_ ((||) <$> atEol <*> ((not . isSpace) <$> readB)) rightB -- | Move to the last non-space character in this line lastNonSpaceB :: BufferM () lastNonSpaceB = do moveToEol untilB_ ((||) <$> atSol <*> ((not . isSpace) <$> readB)) leftB -- | Go to the first non space character in the line; -- if already there, then go to the beginning of the line. moveNonspaceOrSol :: BufferM () moveNonspaceOrSol = do prev <- readPreviousOfLnB if R.all isSpace prev then moveToSol else firstNonSpaceB -- | True if current line consists of just a newline (no whitespace) isCurrentLineEmptyB :: BufferM Bool isCurrentLineEmptyB = savingPointB $ moveToSol >> atEol -- | Note: Returns False if line doesn't have any characters besides a newline isCurrentLineAllWhiteSpaceB :: BufferM Bool isCurrentLineAllWhiteSpaceB = savingPointB $ do isEmpty <- isCurrentLineEmptyB if isEmpty then return False else do let go = do eol <- atEol if eol then return True else do c <- readB if isSpace c then rightB >> go else return False moveToSol go ------------ -- | Move down next @n@ paragraphs nextNParagraphs :: Int -> BufferM () nextNParagraphs n = replicateM_ n $ moveB unitEmacsParagraph Forward -- | Move up prev @n@ paragraphs prevNParagraphs :: Int -> BufferM () prevNParagraphs n = replicateM_ n $ moveB unitEmacsParagraph Backward -- | Select next @n@ paragraphs selectNParagraphs :: Int -> BufferM () selectNParagraphs n = do getVisibleSelection >>= \case True -> exchangePointAndMarkB >> nextNParagraphs n >> (setVisibleSelection True) >> exchangePointAndMarkB False -> nextNParagraphs n >> (setVisibleSelection True) >> pointB >>= setSelectionMarkPointB >> prevNParagraphs n -- ! Examples: -- @goUnmatchedB Backward '(' ')'@ -- Move to the previous unmatched '(' -- @goUnmatchedB Forward '{' '}'@ -- Move to the next unmatched '}' goUnmatchedB :: Direction -> Char -> Char -> BufferM () goUnmatchedB dir cStart' cStop' = getLineAndCol >>= \position -> stepB >> readB >>= go position (0::Int) where go pos opened c | c == cStop && opened == 0 = return () | c == cStop = goIfNotEofSof pos (opened-1) | c == cStart = goIfNotEofSof pos (opened+1) | otherwise = goIfNotEofSof pos opened goIfNotEofSof pos opened = atEof >>= \eof -> atSof >>= \sof -> if not eof && not sof then stepB >> readB >>= go pos opened else gotoLn (fst pos) >> moveToColB (snd pos) (stepB, cStart, cStop) | dir == Forward = (rightB, cStart', cStop') | otherwise = (leftB, cStop', cStart') ----------------------------------------------------------------------- -- Queries -- | Return true if the current point is the start of a line atSol :: BufferM Bool atSol = atBoundaryB Line Backward -- | Return true if the current point is the end of a line atEol :: BufferM Bool atEol = atBoundaryB Line Forward -- | True if point at start of file atSof :: BufferM Bool atSof = atBoundaryB Document Backward -- | True if point at end of file atEof :: BufferM Bool atEof = atBoundaryB Document Forward -- | True if point at the last line atLastLine :: BufferM Bool atLastLine = savingPointB $ do moveToEol (==) <$> sizeB <*> pointB -- | Get the current line and column number getLineAndCol :: BufferM (Int, Int) getLineAndCol = (,) <$> curLn <*> curCol getLineAndColOfPoint :: Point -> BufferM (Int, Int) getLineAndColOfPoint p = savingPointB $ moveTo p >> getLineAndCol -- | Read the line the point is on readLnB :: BufferM YiString readLnB = readUnitB Line -- | Read from point to beginning of line readPreviousOfLnB :: BufferM YiString readPreviousOfLnB = readRegionB =<< regionOfPartB Line Backward hasWhiteSpaceBefore :: BufferM Bool hasWhiteSpaceBefore = fmap isSpace (prevPointB >>= readAtB) -- | Get the previous point, unless at the beginning of the file prevPointB :: BufferM Point prevPointB = do sof <- atSof if sof then pointB else do p <- pointB return $ Point (fromPoint p - 1) -- | Reads in word at point. readCurrentWordB :: BufferM YiString readCurrentWordB = readUnitB unitWord -- | Reads in word before point. readPrevWordB :: BufferM YiString readPrevWordB = readPrevUnitB unitViWordOnLine ------------------------- -- Deletes -- | Delete one character backward bdeleteB :: BufferM () bdeleteB = deleteB Character Backward -- | Delete forward whitespace or non-whitespace depending on -- the character under point. killWordB :: BufferM () killWordB = deleteB unitWord Forward -- | Delete backward whitespace or non-whitespace depending on -- the character before point. bkillWordB :: BufferM () bkillWordB = deleteB unitWord Backward -- | Delete backward to the sof or the new line character bdeleteLineB :: BufferM () bdeleteLineB = atSol >>= \sol -> if sol then bdeleteB else deleteB Line Backward -- UnivArgument is in Yi.Keymap.Emacs.Utils but we can't import it due -- to cyclic imports. -- | emacs' @delete-horizontal-space@ with the optional argument. deleteHorizontalSpaceB :: Maybe Int -> BufferM () deleteHorizontalSpaceB u = do c <- curCol reg <- regionOfB Line text <- readRegionB reg let (r, jb) = deleteSpaces c text modifyRegionB (const r) reg -- Jump backwards to where the now-deleted spaces have started so -- it's consistent and feels natural instead of leaving us somewhere -- in the text. moveToColB $ c - jb where deleteSpaces :: Int -> R.YiString -> (R.YiString, Int) deleteSpaces c l = let (f, b) = R.splitAt c l f' = R.dropWhileEnd isSpace f cleaned = f' <> case u of Nothing -> R.dropWhile isSpace b Just _ -> b -- We only want to jump back the number of spaces before the -- point, not the total number of characters we're removing. in (cleaned, R.length f - R.length f') ---------------------------------------- -- Transform operations -- | capitalise the word under the cursor uppercaseWordB :: BufferM () uppercaseWordB = transformB (R.withText T.toUpper) unitWord Forward -- | lowerise word under the cursor lowercaseWordB :: BufferM () lowercaseWordB = transformB (R.withText T.toLower) unitWord Forward -- | capitalise the first letter of this word capitaliseWordB :: BufferM () capitaliseWordB = transformB capitalizeFirst unitWord Forward switchCaseChar :: Char -> Char switchCaseChar c = if isUpper c then toLower c else toUpper c -- | Delete to the end of line, excluding it. deleteToEol :: BufferM () deleteToEol = deleteRegionB =<< regionOfPartB Line Forward -- | Transpose two characters, (the Emacs C-t action) swapB :: BufferM () swapB = do eol <- atEol when eol leftB transposeB Character Forward -- | Delete trailing whitespace from all lines. Uses 'savingPositionB' -- to get back to where it was. deleteTrailingSpaceB :: BufferM () deleteTrailingSpaceB = regionOfB Document >>= savingPositionB . modifyRegionB (tru . mapLines stripEnd) where -- Strips the space from the end of each line, preserving -- newlines. stripEnd :: R.YiString -> R.YiString stripEnd x = case R.last x of Nothing -> x Just '\n' -> (`R.snoc` '\n') $ R.dropWhileEnd isSpace x _ -> R.dropWhileEnd isSpace x -- | Cut off trailing newlines, making sure to preserve one. tru :: R.YiString -> R.YiString tru x = if R.length x == 0 then x else (`R.snoc` '\n') $ R.dropWhileEnd (== '\n') x -- ---------------------------------------------------- -- | Marks -- | Set the current buffer selection mark setSelectionMarkPointB :: Point -> BufferM () setSelectionMarkPointB p = (.= p) . markPointA =<< selMark <$> askMarks -- | Get the current buffer selection mark getSelectionMarkPointB :: BufferM Point getSelectionMarkPointB = use . markPointA =<< selMark <$> askMarks -- | Exchange point & mark. exchangePointAndMarkB :: BufferM () exchangePointAndMarkB = do m <- getSelectionMarkPointB p <- pointB setSelectionMarkPointB p moveTo m getBookmarkB :: String -> BufferM Mark getBookmarkB = getMarkB . Just -- --------------------------------------------------------------------- -- Buffer operations data BufferFileInfo = BufferFileInfo { bufInfoFileName :: FilePath , bufInfoSize :: Int , bufInfoLineNo :: Int , bufInfoColNo :: Int , bufInfoCharNo :: Point , bufInfoPercent :: T.Text , bufInfoModified :: Bool } -- | File info, size in chars, line no, col num, char num, percent bufInfoB :: BufferM BufferFileInfo bufInfoB = do s <- sizeB p <- pointB m <- gets isUnchangedBuffer l <- curLn c <- curCol nm <- gets identString let bufInfo = BufferFileInfo { bufInfoFileName = T.unpack nm , bufInfoSize = fromIntegral s , bufInfoLineNo = l , bufInfoColNo = c , bufInfoCharNo = p , bufInfoPercent = getPercent p s , bufInfoModified = not m } return bufInfo ----------------------------- -- Window-related operations upScreensB :: Int -> BufferM () upScreensB = scrollScreensB . negate downScreensB :: Int -> BufferM () downScreensB = scrollScreensB -- | Scroll up 1 screen upScreenB :: BufferM () upScreenB = scrollScreensB (-1) -- | Scroll down 1 screen downScreenB :: BufferM () downScreenB = scrollScreensB 1 -- | Scroll by n screens (negative for up) scrollScreensB :: Int -> BufferM () scrollScreensB n = do h <- askWindow actualLines scrollB $ n * max 0 (h - 1) -- subtract some amount to get some overlap (emacs-like). -- | Same as scrollB, but also moves the cursor vimScrollB :: Int -> BufferM () vimScrollB n = do scrollB n void $ lineMoveRel n -- | Same as scrollByB, but also moves the cursor vimScrollByB :: (Int -> Int) -> Int -> BufferM () vimScrollByB f n = do h <- askWindow actualLines vimScrollB $ n * f h -- | Move to middle line in screen scrollToCursorB :: BufferM () scrollToCursorB = do MarkSet f i _ <- markLines h <- askWindow actualLines let m = f + (h `div` 2) scrollB $ i - m -- | Move cursor to the top of the screen scrollCursorToTopB :: BufferM () scrollCursorToTopB = do MarkSet f i _ <- markLines scrollB $ i - f -- | Move cursor to the bottom of the screen scrollCursorToBottomB :: BufferM () scrollCursorToBottomB = do -- NOTE: This is only an approximation. -- The correct scroll amount depends on how many lines just above -- the current viewport are going to be wrapped. We don't have this -- information here as wrapping is done in the frontend. MarkSet f i _ <- markLines h <- askWindow actualLines scrollB $ i - f - h + 1 -- | Scroll by n lines. scrollB :: Int -> BufferM () scrollB n = do MarkSet fr _ _ <- askMarks savingPointB $ do moveTo =<< use (markPointA fr) void $ gotoLnFrom n (markPointA fr .=) =<< pointB w <- askWindow wkey pointFollowsWindowA %= Set.insert w -- Scroll line above window to the bottom. scrollToLineAboveWindowB :: BufferM () scrollToLineAboveWindowB = do downFromTosB 0 replicateM_ 1 lineUp scrollCursorToBottomB -- Scroll line below window to the top. scrollToLineBelowWindowB :: BufferM () scrollToLineBelowWindowB = do upFromBosB 0 replicateM_ 1 lineDown scrollCursorToTopB -- | Move the point to inside the viewable region snapInsB :: BufferM () snapInsB = do w <- askWindow wkey movePoint <- Set.member w <$> use pointFollowsWindowA when movePoint $ do r <- winRegionB p <- pointB moveTo $ max (regionStart r) $ min (regionEnd r) p -- | return index of Sol on line @n@ above current line indexOfSolAbove :: Int -> BufferM Point indexOfSolAbove n = pointAt $ gotoLnFrom (negate n) data RelPosition = Above | Below | Within deriving (Show) -- | return relative position of the point @p@ -- relative to the region defined by the points @rs@ and @re@ pointScreenRelPosition :: Point -> Point -> Point -> RelPosition pointScreenRelPosition p rs re | rs > p && p > re = Within | p < rs = Above | p > re = Below pointScreenRelPosition _ _ _ = Within -- just to disable the non-exhaustive pattern match warning -- | Move the visible region to include the point snapScreenB :: Maybe ScrollStyle -> BufferM Bool snapScreenB style = do w <- askWindow wkey movePoint <- Set.member w <$> use pointFollowsWindowA if movePoint then return False else do inWin <- pointInWindowB =<< pointB if inWin then return False else do h <- askWindow actualLines r <- winRegionB p <- pointB let gap = case style of Just SingleLine -> case pointScreenRelPosition p (regionStart r) (regionEnd r) of Above -> 0 Below -> h - 1 Within -> 0 -- Impossible but handle it anyway _ -> h `div` 2 i <- indexOfSolAbove gap f <- fromMark <$> askMarks markPointA f .= i return True -- | Move to @n@ lines down from top of screen downFromTosB :: Int -> BufferM () downFromTosB n = do moveTo =<< use . markPointA =<< fromMark <$> askMarks replicateM_ n lineDown -- | Move to @n@ lines up from the bottom of the screen upFromBosB :: Int -> BufferM () upFromBosB n = do r <- winRegionB moveTo (regionEnd r - 1) moveToSol replicateM_ n lineUp -- | Move to middle line in screen middleB :: BufferM () middleB = do w <- ask f <- fromMark <$> askMarks moveTo =<< use (markPointA f) replicateM_ (actualLines w `div` 2) lineDown pointInWindowB :: Point -> BufferM Bool pointInWindowB p = nearRegion p <$> winRegionB ----------------------------- -- Region-related operations -- | Return the region between point and mark getRawestSelectRegionB :: BufferM Region getRawestSelectRegionB = do m <- getSelectionMarkPointB p <- pointB return $ mkRegion p m -- | Return the empty region if the selection is not visible. getRawSelectRegionB :: BufferM Region getRawSelectRegionB = do s <- use highlightSelectionA if s then getRawestSelectRegionB else do p <- pointB return $ mkRegion p p -- | Get the current region boundaries. Extended to the current selection unit. getSelectRegionB :: BufferM Region getSelectRegionB = do regionStyle <- getRegionStyle r <- getRawSelectRegionB convertRegionToStyleB r regionStyle -- | Select the given region: set the selection mark at the 'regionStart' -- and the current point at the 'regionEnd'. setSelectRegionB :: Region -> BufferM () setSelectRegionB region = do highlightSelectionA .= True setSelectionMarkPointB $ regionStart region moveTo $ regionEnd region ------------------------------------------ -- Some line related movements/operations deleteBlankLinesB :: BufferM () deleteBlankLinesB = do isThisBlank <- isBlank <$> readLnB when isThisBlank $ do p <- pointB -- go up to the 1st blank line in the group void $ whileB (R.null <$> getNextLineB Backward) lineUp q <- pointB -- delete the whole blank region. deleteRegionB $ mkRegion p q -- | Get a (lazy) stream of lines in the buffer, starting at the /next/ line -- in the given direction. lineStreamB :: Direction -> BufferM [YiString] lineStreamB dir = fmap rev . R.lines <$> (streamB dir =<< pointB) where rev = case dir of Forward -> id Backward -> R.reverse -- | Get the next line of text in the given direction. This returns -- simply 'Nothing' if there no such line. getMaybeNextLineB :: Direction -> BufferM (Maybe YiString) getMaybeNextLineB dir = listToMaybe <$> lineStreamB dir -- | The same as 'getMaybeNextLineB' but avoids the use of the 'Maybe' -- type in the return by returning the empty string if there is no -- next line. getNextLineB :: Direction -> BufferM YiString getNextLineB dir = fromMaybe R.empty <$> getMaybeNextLineB dir -- | Get closest line to the current line (not including the current -- line) in the given direction which satisfies the given condition. -- Returns 'Nothing' if there is no line which satisfies the -- condition. getNextLineWhichB :: Direction -> (YiString -> Bool) -> BufferM (Maybe YiString) getNextLineWhichB dir cond = listToMaybe . filter cond <$> lineStreamB dir -- | Returns the closest line to the current line which is non-blank, -- in the given direction. Returns the empty string if there is no -- such line (for example if we are on the top line already). getNextNonBlankLineB :: Direction -> BufferM YiString getNextNonBlankLineB dir = fromMaybe R.empty <$> getNextLineWhichB dir (not . R.null) ------------------------------------------------ -- Some more utility functions involving -- regions (generally that which is selected) modifyExtendedSelectionB :: TextUnit -> (R.YiString -> R.YiString) -> BufferM () modifyExtendedSelectionB unit transform = modifyRegionB transform =<< unitWiseRegion unit =<< getSelectRegionB -- | Prefix each line in the selection using the given string. linePrefixSelectionB :: R.YiString -- ^ The string that starts a line comment -> BufferM () linePrefixSelectionB s = modifyExtendedSelectionB Line . overInit $ mapLines (s <>) -- | Uncomments the selection using the given line comment -- starting string. This only works for the comments which -- begin at the start of the line. unLineCommentSelectionB :: R.YiString -- ^ The string which begins a -- line comment -> R.YiString -- ^ A potentially shorter -- string that begins a comment -> BufferM () unLineCommentSelectionB s1 s2 = modifyExtendedSelectionB Line $ mapLines unCommentLine where (l1, l2) = (R.length s1, R.length s2) unCommentLine :: R.YiString -> R.YiString unCommentLine line = case (R.splitAt l1 line, R.splitAt l2 line) of ((f, s) , (f', s')) | s1 == f -> s | s2 == f' -> s' | otherwise -> line -- | Just like 'toggleCommentSelectionB' but automatically inserts a -- whitespace suffix to the inserted comment string. In fact: toggleCommentB :: R.YiString -> BufferM () toggleCommentB c = toggleCommentSelectionB (c `R.snoc` ' ') c -- | Toggle line comments in the selection by adding or removing a -- prefix to each line. toggleCommentSelectionB :: R.YiString -> R.YiString -> BufferM () toggleCommentSelectionB insPrefix delPrefix = do l <- readUnitB Line if delPrefix == R.take (R.length delPrefix) l then unLineCommentSelectionB insPrefix delPrefix else linePrefixSelectionB insPrefix -- | Replace the contents of the buffer with some string replaceBufferContent :: YiString -> BufferM () replaceBufferContent newvalue = do r <- regionOfB Document replaceRegionB r newvalue -- | Fill the text in the region so it fits nicely 80 columns. fillRegion :: Region -> BufferM () fillRegion = modifyRegionB (R.unlines . fillText 80) fillParagraph :: BufferM () fillParagraph = fillRegion =<< regionOfB unitParagraph -- | Sort the lines of the region. sortLines :: BufferM () sortLines = modifyExtendedSelectionB Line (onLines sort) -- | Forces an extra newline into the region (if one exists) modifyExtendedLRegion :: Region -> (R.YiString -> R.YiString) -> BufferM () modifyExtendedLRegion region transform = do reg <- unitWiseRegion Line region modifyRegionB transform (fixR reg) where fixR reg = mkRegion (regionStart reg) $ regionEnd reg + 1 sortLinesWithRegion :: Region -> BufferM () sortLinesWithRegion region = modifyExtendedLRegion region (onLines sort') where sort' [] = [] sort' lns = if hasnl (last lns) then sort lns else over _last -- should be completely safe since every element contains newline (fromMaybe (error "sortLinesWithRegion fromMaybe") . R.init) . sort $ over _last (`R.snoc` '\n') lns hasnl t | R.last t == Just '\n' = True | otherwise = False -- | Helper function: revert the buffer contents to its on-disk version revertB :: YiString -> UTCTime -> BufferM () revertB s now = do r <- regionOfB Document replaceRegionB r s markSavedB now -- get lengths of parts covered by block region -- -- Consider block region starting at 'o' and ending at 'z': -- -- start -- | -- \|/ -- def foo(bar): -- baz -- -- ab -- xyz0 -- /|\ -- | -- finish -- -- shapeOfBlockRegionB returns (regionStart, [2, 2, 0, 1, 2]) -- TODO: accept stickToEol flag shapeOfBlockRegionB :: Region -> BufferM (Point, [Int]) shapeOfBlockRegionB reg = savingPointB $ do (l0, c0) <- getLineAndColOfPoint $ regionStart reg (l1, c1) <- getLineAndColOfPoint $ regionEnd reg let (left, top, bottom, right) = (min c0 c1, min l0 l1, max l0 l1, max c0 c1) lengths <- forM [top .. bottom] $ \l -> do void $ gotoLn l moveToColB left currentLeft <- curCol if currentLeft /= left then return 0 else do moveToColB right rightAtEol <- atEol leftOnEol currentRight <- curCol return $ if currentRight == 0 && rightAtEol then 0 else currentRight - currentLeft + 1 startingPoint <- pointOfLineColB top left return (startingPoint, lengths) leftEdgesOfRegionB :: RegionStyle -> Region -> BufferM [Point] leftEdgesOfRegionB Block reg = savingPointB $ do (l0, _) <- getLineAndColOfPoint $ regionStart reg (l1, _) <- getLineAndColOfPoint $ regionEnd reg moveTo $ regionStart reg fmap catMaybes $ forM [0 .. abs (l0 - l1)] $ \i -> savingPointB $ do void $ lineMoveRel i p <- pointB eol <- atEol return (if not eol then Just p else Nothing) leftEdgesOfRegionB LineWise reg = savingPointB $ do lastSol <- do moveTo $ regionEnd reg moveToSol pointB let go acc p = do moveTo p moveToSol edge <- pointB if edge >= lastSol then return $ reverse (edge:acc) else do void $ lineMoveRel 1 go (edge:acc) =<< pointB go [] (regionStart reg) leftEdgesOfRegionB _ r = return [regionStart r] rightEdgesOfRegionB :: RegionStyle -> Region -> BufferM [Point] rightEdgesOfRegionB Block reg = savingPointB $ do (l0, _) <- getLineAndColOfPoint $ regionStart reg (l1, _) <- getLineAndColOfPoint $ regionEnd reg moveTo $ 1 + regionEnd reg fmap reverse $ forM [0 .. abs (l0 - l1)] $ \i -> savingPointB $ do void $ lineMoveRel $ -i pointB rightEdgesOfRegionB LineWise reg = savingPointB $ do lastEol <- do moveTo $ regionEnd reg moveToEol pointB let go acc p = do moveTo p moveToEol edge <- pointB if edge >= lastEol then return $ reverse (edge:acc) else do void $ lineMoveRel 1 go (edge:acc) =<< pointB go [] (regionStart reg) rightEdgesOfRegionB _ reg = savingPointB $ do moveTo $ regionEnd reg leftOnEol fmap return pointB splitBlockRegionToContiguousSubRegionsB :: Region -> BufferM [Region] splitBlockRegionToContiguousSubRegionsB reg = savingPointB $ do (start, lengths) <- shapeOfBlockRegionB reg forM (zip [0..] lengths) $ \(i, l) -> do moveTo start void $ lineMoveRel i p0 <- pointB moveXorEol l p1 <- pointB let subRegion = mkRegion p0 p1 return subRegion -- Return list containing a single point for all non-block styles. -- For Block return all the points along the left edge of the region deleteRegionWithStyleB :: Region -> RegionStyle -> BufferM (NonEmpty Point) deleteRegionWithStyleB reg Block = savingPointB $ do (start, lengths) <- shapeOfBlockRegionB reg moveTo start points <- forM (zip [1..] lengths) $ \(i, l) -> do deleteN l p <- pointB moveTo start lineMoveRel i return (if l == 0 then Nothing else Just p) return $ start :| drop 1 (catMaybes points) deleteRegionWithStyleB reg style = savingPointB $ do effectiveRegion <- convertRegionToStyleB reg style deleteRegionB effectiveRegion return $! pure (regionStart effectiveRegion) readRegionRopeWithStyleB :: Region -> RegionStyle -> BufferM YiString readRegionRopeWithStyleB reg Block = savingPointB $ do (start, lengths) <- shapeOfBlockRegionB reg moveTo start chunks <- forM lengths $ \l -> if l == 0 then lineMoveRel 1 >> return mempty else do p <- pointB r <- readRegionB $ mkRegion p (p +~ Size l) void $ lineMoveRel 1 return r return $ R.intersperse '\n' chunks readRegionRopeWithStyleB reg style = readRegionB =<< convertRegionToStyleB reg style insertRopeWithStyleB :: YiString -> RegionStyle -> BufferM () insertRopeWithStyleB rope Block = savingPointB $ do let ls = R.lines rope advanceLine = atLastLine >>= \case False -> void $ lineMoveRel 1 True -> do col <- curCol moveToEol newlineB insertN $ R.replicateChar col ' ' sequence_ $ intersperse advanceLine $ fmap (savingPointB . insertN) ls insertRopeWithStyleB rope LineWise = do moveToSol savingPointB $ insertN rope insertRopeWithStyleB rope _ = insertN rope -- consider the following buffer content -- -- 123456789 -- qwertyuio -- asdfgh -- -- The following examples use characters from that buffer as points. -- h' denotes the newline after h -- -- 1 r -> 4 q -- 9 q -> 1 o -- q h -> y a -- a o -> h' q -- o a -> q h' -- 1 a -> 1 a -- -- property: fmap swap (flipRectangleB a b) = flipRectangleB b a flipRectangleB :: Point -> Point -> BufferM (Point, Point) flipRectangleB p0 p1 = savingPointB $ do (_, c0) <- getLineAndColOfPoint p0 (_, c1) <- getLineAndColOfPoint p1 case compare c0 c1 of EQ -> return (p0, p1) GT -> swap <$> flipRectangleB p1 p0 LT -> do -- now we know that c0 < c1 moveTo p0 moveXorEol $ c1 - c0 flippedP0 <- pointB return (flippedP0, p1 -~ Size (c1 - c0)) movePercentageFileB :: Int -> BufferM () movePercentageFileB i = do let f :: Double f = case fromIntegral i / 100.0 of x | x > 1.0 -> 1.0 | x < 0.0 -> 0.0 -- Impossible? | otherwise -> x lineCount <- lineCountB void $ gotoLn $ floor (fromIntegral lineCount * f) firstNonSpaceB findMatchingPairB :: BufferM () findMatchingPairB = do let go dir a b = goUnmatchedB dir a b >> return True goToMatch = do c <- readB case c of '(' -> go Forward '(' ')' ')' -> go Backward '(' ')' '{' -> go Forward '{' '}' '}' -> go Backward '{' '}' '[' -> go Forward '[' ']' ']' -> go Backward '[' ']' _ -> otherChar otherChar = do eof <- atEof eol <- atEol if eof || eol then return False else rightB >> goToMatch p <- pointB foundMatch <- goToMatch unless foundMatch $ moveTo p -- Vim numbers -- | Increase (or decrease if negative) next number on line by n. incrementNextNumberByB :: Int -> BufferM () incrementNextNumberByB n = do start <- pointB untilB_ (not <$> isNumberB) $ moveXorSol 1 untilB_ isNumberB $ moveXorEol 1 begin <- pointB beginIsEol <- atEol untilB_ (not <$> isNumberB) $ moveXorEol 1 end <- pointB if beginIsEol then moveTo start else do modifyRegionB (increment n) (mkRegion begin end) moveXorSol 1 -- | Increment number in string by n. increment :: Int -> R.YiString -> R.YiString increment n l = R.fromString $ go (R.toString l) where go ('0':'x':xs) = (\ys -> '0':'x':ys) . (`showHex` "") . (+ n) . fst . head . readHex $ xs go ('0':'o':xs) = (\ys -> '0':'o':ys) . (`showOct` "") . (+ n) . fst . head . readOct $ xs go s = show . (+ n) . (\x -> read x :: Int) $ s -- | Is character under cursor a number. isNumberB :: BufferM Bool isNumberB = do eol <- atEol sol <- atSol if sol then isDigit <$> readB else if eol then return False else test3CharB -- | Used by isNumber to test if current character under cursor is a number. test3CharB :: BufferM Bool test3CharB = do moveXorSol 1 previous <- readB moveXorEol 2 next <- readB moveXorSol 1 current <- readB if | previous == '0' && current == 'o' && isOctDigit next -> return True -- octal format | previous == '0' && current == 'x' && isHexDigit next -> return True -- hex format | current == '-' && isDigit next -> return True -- negative numbers | isDigit current -> return True -- all decimal digits | isHexDigit current -> testHexB -- ['a'..'f'] for hex | otherwise -> return False -- | Characters ['a'..'f'] are part of a hex number only if preceded by 0x. -- Test if the current occurence of ['a'..'f'] is part of a hex number. testHexB :: BufferM Bool testHexB = savingPointB $ do untilB_ (not . isHexDigit <$> readB) (moveXorSol 1) leftChar <- readB moveXorSol 1 leftToLeftChar <- readB if leftChar == 'x' && leftToLeftChar == '0' then return True else return False -- | Move point down by @n@ lines -- If line extends past width of window, count moving -- a single line as moving width points to the right. lineMoveVisRel :: Int -> BufferM () lineMoveVisRel = movingToPrefVisCol . lineMoveVisRelUp lineMoveVisRelUp :: Int -> BufferM () lineMoveVisRelUp 0 = return () lineMoveVisRelUp n | n < 0 = lineMoveVisRelDown $ negate n | otherwise = do wid <- width <$> use lastActiveWindowA col <- curCol len <- pointB >>= eolPointB >>= colOf let jumps = (len `div` wid) - (col `div` wid) next = n - jumps if next <= 0 then moveXorEol (n * wid) else do moveXorEol (jumps * wid) void $ gotoLnFrom 1 lineMoveVisRelUp $ next - 1 lineMoveVisRelDown :: Int -> BufferM () lineMoveVisRelDown 0 = return () lineMoveVisRelDown n | n < 0 = lineMoveVisRelUp $ negate n | otherwise = do wid <- width <$> use lastActiveWindowA col <- curCol let jumps = col `div` wid next = n - jumps if next <= 0 then leftN (n * wid) else do leftN (jumps * wid) void $ gotoLnFrom $ -1 moveToEol lineMoveVisRelDown $ next - 1 -- | Implements the same logic that emacs' `mark-word` does. -- Checks the mark point and moves it forth (or backward) for one word. markWord :: BufferM () markWord = do curPos <- pointB curMark <- getSelectionMarkPointB isVisible <- getVisibleSelection savingPointB $ do if not isVisible then nextWordB else do moveTo curMark if curMark < curPos then prevWordB else nextWordB setVisibleSelection True pointB >>= setSelectionMarkPointB
noughtmare/yi
yi-core/src/Yi/Buffer/HighLevel.hs
gpl-2.0
40,031
0
22
11,158
9,583
4,882
4,701
832
8
{-# OPTIONS_GHC -fno-warn-unused-imports #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.Tar -- Copyright : (c) 2007 Bjorn Bringert, -- 2008 Andrea Vezzosi, -- 2008-2009 Duncan Coutts -- License : BSD3 -- -- Maintainer : duncan@community.haskell.org -- Portability : portable -- -- Reading, writing and manipulating \"@.tar@\" archive files. -- ----------------------------------------------------------------------------- module Distribution.Client.Tar ( -- * High level \"all in one\" operations createTarGzFile, extractTarGzFile, -- * Converting between internal and external representation read, write, writeEntries, -- * Packing and unpacking files to\/from internal representation pack, unpack, -- * Tar entry and associated types Entry(..), entryPath, EntryContent(..), Ownership(..), FileSize, Permissions, EpochTime, DevMajor, DevMinor, TypeCode, Format(..), buildTreeRefTypeCode, buildTreeSnapshotTypeCode, isBuildTreeRefTypeCode, entrySizeInBlocks, entrySizeInBytes, -- * Constructing simple entry values simpleEntry, fileEntry, directoryEntry, -- * TarPath type TarPath, toTarPath, fromTarPath, -- ** Sequences of tar entries Entries(..), foldrEntries, foldlEntries, unfoldrEntries, mapEntries, filterEntries, entriesIndex, ) where import Data.Char (ord) import Data.Int (Int64) import Data.Bits (Bits, shiftL, testBit) import Data.List (foldl') import Numeric (readOct, showOct) import Control.Monad (MonadPlus(mplus), when) import qualified Data.Map as Map import qualified Data.ByteString.Lazy as BS import qualified Data.ByteString.Lazy.Char8 as BS.Char8 import Data.ByteString.Lazy (ByteString) import qualified Codec.Compression.GZip as GZip import qualified Distribution.Client.GZipUtils as GZipUtils import System.FilePath ( (</>) ) import qualified System.FilePath as FilePath.Native import qualified System.FilePath.Windows as FilePath.Windows import qualified System.FilePath.Posix as FilePath.Posix import System.Directory ( getDirectoryContents, doesDirectoryExist , getPermissions, createDirectoryIfMissing, copyFile ) import qualified System.Directory as Permissions ( Permissions(executable) ) import Distribution.Client.Compat.FilePerms ( setFileExecutable ) import System.Posix.Types ( FileMode ) import Distribution.Client.Compat.Time import System.IO ( IOMode(ReadMode), openBinaryFile, hFileSize ) import System.IO.Unsafe (unsafeInterleaveIO) import Prelude hiding (read) -- -- * High level operations -- createTarGzFile :: FilePath -- ^ Full Tarball path -> FilePath -- ^ Base directory -> FilePath -- ^ Directory to archive, relative to base dir -> IO () createTarGzFile tar base dir = BS.writeFile tar . GZip.compress . write =<< pack base [dir] extractTarGzFile :: FilePath -- ^ Destination directory -> FilePath -- ^ Expected subdir (to check for tarbombs) -> FilePath -- ^ Tarball -> IO () extractTarGzFile dir expected tar = unpack dir . checkTarbomb expected . read . GZipUtils.maybeDecompress =<< BS.readFile tar -- -- * Entry type -- type FileSize = Int64 type DevMajor = Int type DevMinor = Int type TypeCode = Char type Permissions = FileMode -- | Tar archive entry. -- data Entry = Entry { -- | The path of the file or directory within the archive. This is in a -- tar-specific form. Use 'entryPath' to get a native 'FilePath'. entryTarPath :: !TarPath, -- | The real content of the entry. For 'NormalFile' this includes the -- file data. An entry usually contains a 'NormalFile' or a 'Directory'. entryContent :: !EntryContent, -- | File permissions (Unix style file mode). entryPermissions :: !Permissions, -- | The user and group to which this file belongs. entryOwnership :: !Ownership, -- | The time the file was last modified. entryTime :: !EpochTime, -- | The tar format the archive is using. entryFormat :: !Format } -- | Type code for the local build tree reference entry type. We don't use the -- symbolic link entry type because it allows only 100 ASCII characters for the -- path. buildTreeRefTypeCode :: TypeCode buildTreeRefTypeCode = 'C' -- | Type code for the local build tree snapshot entry type. buildTreeSnapshotTypeCode :: TypeCode buildTreeSnapshotTypeCode = 'S' -- | Is this a type code for a build tree reference? isBuildTreeRefTypeCode :: TypeCode -> Bool isBuildTreeRefTypeCode typeCode | (typeCode == buildTreeRefTypeCode || typeCode == buildTreeSnapshotTypeCode) = True | otherwise = False -- | Native 'FilePath' of the file or directory within the archive. -- entryPath :: Entry -> FilePath entryPath = fromTarPath . entryTarPath -- | Return the size of an entry in bytes. entrySizeInBytes :: Entry -> FileSize entrySizeInBytes = (*512) . fromIntegral . entrySizeInBlocks -- | Return the number of blocks in an entry. entrySizeInBlocks :: Entry -> Int entrySizeInBlocks entry = 1 + case entryContent entry of NormalFile _ size -> bytesToBlocks size OtherEntryType _ _ size -> bytesToBlocks size _ -> 0 where bytesToBlocks s = 1 + ((fromIntegral s - 1) `div` 512) -- | The content of a tar archive entry, which depends on the type of entry. -- -- Portable archives should contain only 'NormalFile' and 'Directory'. -- data EntryContent = NormalFile ByteString !FileSize | Directory | SymbolicLink !LinkTarget | HardLink !LinkTarget | CharacterDevice !DevMajor !DevMinor | BlockDevice !DevMajor !DevMinor | NamedPipe | OtherEntryType !TypeCode ByteString !FileSize data Ownership = Ownership { -- | The owner user name. Should be set to @\"\"@ if unknown. ownerName :: String, -- | The owner group name. Should be set to @\"\"@ if unknown. groupName :: String, -- | Numeric owner user id. Should be set to @0@ if unknown. ownerId :: !Int, -- | Numeric owner group id. Should be set to @0@ if unknown. groupId :: !Int } -- | There have been a number of extensions to the tar file format over the -- years. They all share the basic entry fields and put more meta-data in -- different extended headers. -- data Format = -- | This is the classic Unix V7 tar format. It does not support owner and -- group names, just numeric Ids. It also does not support device numbers. V7Format -- | The \"USTAR\" format is an extension of the classic V7 format. It was -- later standardised by POSIX. It has some restructions but is the most -- portable format. -- | UstarFormat -- | The GNU tar implementation also extends the classic V7 format, though -- in a slightly different way from the USTAR format. In general for new -- archives the standard USTAR/POSIX should be used. -- | GnuFormat deriving Eq -- | @rw-r--r--@ for normal files ordinaryFilePermissions :: Permissions ordinaryFilePermissions = 0o0644 -- | @rwxr-xr-x@ for executable files executableFilePermissions :: Permissions executableFilePermissions = 0o0755 -- | @rwxr-xr-x@ for directories directoryPermissions :: Permissions directoryPermissions = 0o0755 isExecutable :: Permissions -> Bool isExecutable p = testBit p 0 || testBit p 6 -- user or other exectuable -- | An 'Entry' with all default values except for the file name and type. It -- uses the portable USTAR/POSIX format (see 'UstarHeader'). -- -- You can use this as a basis and override specific fields, eg: -- -- > (emptyEntry name HardLink) { linkTarget = target } -- simpleEntry :: TarPath -> EntryContent -> Entry simpleEntry tarpath content = Entry { entryTarPath = tarpath, entryContent = content, entryPermissions = case content of Directory -> directoryPermissions _ -> ordinaryFilePermissions, entryOwnership = Ownership "" "" 0 0, entryTime = 0, entryFormat = UstarFormat } -- | A tar 'Entry' for a file. -- -- Entry fields such as file permissions and ownership have default values. -- -- You can use this as a basis and override specific fields. For example if you -- need an executable file you could use: -- -- > (fileEntry name content) { fileMode = executableFileMode } -- fileEntry :: TarPath -> ByteString -> Entry fileEntry name fileContent = simpleEntry name (NormalFile fileContent (BS.length fileContent)) -- | A tar 'Entry' for a directory. -- -- Entry fields such as file permissions and ownership have default values. -- directoryEntry :: TarPath -> Entry directoryEntry name = simpleEntry name Directory -- -- * Tar paths -- -- | The classic tar format allowed just 100 characters for the file name. The -- USTAR format extended this with an extra 155 characters, however it uses a -- complex method of splitting the name between the two sections. -- -- Instead of just putting any overflow into the extended area, it uses the -- extended area as a prefix. The aggravating insane bit however is that the -- prefix (if any) must only contain a directory prefix. That is the split -- between the two areas must be on a directory separator boundary. So there is -- no simple calculation to work out if a file name is too long. Instead we -- have to try to find a valid split that makes the name fit in the two areas. -- -- The rationale presumably was to make it a bit more compatible with old tar -- programs that only understand the classic format. A classic tar would be -- able to extract the file name and possibly some dir prefix, but not the -- full dir prefix. So the files would end up in the wrong place, but that's -- probably better than ending up with the wrong names too. -- -- So it's understandable but rather annoying. -- -- * Tar paths use posix format (ie @\'/\'@ directory separators), irrespective -- of the local path conventions. -- -- * The directory separator between the prefix and name is /not/ stored. -- data TarPath = TarPath FilePath -- path name, 100 characters max. FilePath -- path prefix, 155 characters max. deriving (Eq, Ord) -- | Convert a 'TarPath' to a native 'FilePath'. -- -- The native 'FilePath' will use the native directory separator but it is not -- otherwise checked for validity or sanity. In particular: -- -- * The tar path may be invalid as a native path, eg the filename @\"nul\"@ is -- not valid on Windows. -- -- * The tar path may be an absolute path or may contain @\"..\"@ components. -- For security reasons this should not usually be allowed, but it is your -- responsibility to check for these conditions (eg using 'checkSecurity'). -- fromTarPath :: TarPath -> FilePath fromTarPath (TarPath name prefix) = adjustDirectory $ FilePath.Native.joinPath $ FilePath.Posix.splitDirectories prefix ++ FilePath.Posix.splitDirectories name where adjustDirectory | FilePath.Posix.hasTrailingPathSeparator name = FilePath.Native.addTrailingPathSeparator | otherwise = id -- | Convert a native 'FilePath' to a 'TarPath'. -- -- The conversion may fail if the 'FilePath' is too long. See 'TarPath' for a -- description of the problem with splitting long 'FilePath's. -- toTarPath :: Bool -- ^ Is the path for a directory? This is needed because for -- directories a 'TarPath' must always use a trailing @\/@. -> FilePath -> Either String TarPath toTarPath isDir = splitLongPath . addTrailingSep . FilePath.Posix.joinPath . FilePath.Native.splitDirectories where addTrailingSep | isDir = FilePath.Posix.addTrailingPathSeparator | otherwise = id -- | Take a sanitized path, split on directory separators and try to pack it -- into the 155 + 100 tar file name format. -- -- The stragey is this: take the name-directory components in reverse order -- and try to fit as many components into the 100 long name area as possible. -- If all the remaining components fit in the 155 name area then we win. -- splitLongPath :: FilePath -> Either String TarPath splitLongPath path = case packName nameMax (reverse (FilePath.Posix.splitPath path)) of Left err -> Left err Right (name, []) -> Right (TarPath name "") Right (name, first:rest) -> case packName prefixMax remainder of Left err -> Left err Right (_ , _ : _) -> Left "File name too long (cannot split)" Right (prefix, []) -> Right (TarPath name prefix) where -- drop the '/' between the name and prefix: remainder = init first : rest where nameMax, prefixMax :: Int nameMax = 100 prefixMax = 155 packName _ [] = Left "File name empty" packName maxLen (c:cs) | n > maxLen = Left "File name too long" | otherwise = Right (packName' maxLen n [c] cs) where n = length c packName' maxLen n ok (c:cs) | n' <= maxLen = packName' maxLen n' (c:ok) cs where n' = n + length c packName' _ _ ok cs = (FilePath.Posix.joinPath ok, cs) -- | The tar format allows just 100 ASCII characters for the 'SymbolicLink' and -- 'HardLink' entry types. -- newtype LinkTarget = LinkTarget FilePath deriving (Eq, Ord) -- | Convert a tar 'LinkTarget' to a native 'FilePath'. -- fromLinkTarget :: LinkTarget -> FilePath fromLinkTarget (LinkTarget path) = adjustDirectory $ FilePath.Native.joinPath $ FilePath.Posix.splitDirectories path where adjustDirectory | FilePath.Posix.hasTrailingPathSeparator path = FilePath.Native.addTrailingPathSeparator | otherwise = id -- -- * Entries type -- -- | A tar archive is a sequence of entries. data Entries = Next Entry Entries | Done | Fail String unfoldrEntries :: (a -> Either String (Maybe (Entry, a))) -> a -> Entries unfoldrEntries f = unfold where unfold x = case f x of Left err -> Fail err Right Nothing -> Done Right (Just (e, x')) -> Next e (unfold x') foldrEntries :: (Entry -> a -> a) -> a -> (String -> a) -> Entries -> a foldrEntries next done fail' = fold where fold (Next e es) = next e (fold es) fold Done = done fold (Fail err) = fail' err foldlEntries :: (a -> Entry -> a) -> a -> Entries -> Either String a foldlEntries f = fold where fold a (Next e es) = (fold $! f a e) es fold a Done = Right a fold _ (Fail err) = Left err mapEntries :: (Entry -> Entry) -> Entries -> Entries mapEntries f = foldrEntries (Next . f) Done Fail filterEntries :: (Entry -> Bool) -> Entries -> Entries filterEntries p = foldrEntries (\entry rest -> if p entry then Next entry rest else rest) Done Fail checkEntries :: (Entry -> Maybe String) -> Entries -> Entries checkEntries checkEntry = foldrEntries (\entry rest -> case checkEntry entry of Nothing -> Next entry rest Just err -> Fail err) Done Fail entriesIndex :: Entries -> Either String (Map.Map TarPath Entry) entriesIndex = foldlEntries (\m e -> Map.insert (entryTarPath e) e m) Map.empty -- -- * Checking -- -- | This function checks a sequence of tar entries for file name security -- problems. It checks that: -- -- * file paths are not absolute -- -- * file paths do not contain any path components that are \"@..@\" -- -- * file names are valid -- -- These checks are from the perspective of the current OS. That means we check -- for \"@C:\blah@\" files on Windows and \"\/blah\" files on unix. For archive -- entry types 'HardLink' and 'SymbolicLink' the same checks are done for the -- link target. A failure in any entry terminates the sequence of entries with -- an error. -- checkSecurity :: Entries -> Entries checkSecurity = checkEntries checkEntrySecurity checkTarbomb :: FilePath -> Entries -> Entries checkTarbomb expectedTopDir = checkEntries (checkEntryTarbomb expectedTopDir) checkEntrySecurity :: Entry -> Maybe String checkEntrySecurity entry = case entryContent entry of HardLink link -> check (entryPath entry) `mplus` check (fromLinkTarget link) SymbolicLink link -> check (entryPath entry) `mplus` check (fromLinkTarget link) _ -> check (entryPath entry) where check name | not (FilePath.Native.isRelative name) = Just $ "Absolute file name in tar archive: " ++ show name | not (FilePath.Native.isValid name) = Just $ "Invalid file name in tar archive: " ++ show name | ".." `elem` FilePath.Native.splitDirectories name = Just $ "Invalid file name in tar archive: " ++ show name | otherwise = Nothing checkEntryTarbomb :: FilePath -> Entry -> Maybe String checkEntryTarbomb _ entry | nonFilesystemEntry = Nothing where -- Ignore some special entries we will not unpack anyway nonFilesystemEntry = case entryContent entry of OtherEntryType 'g' _ _ -> True --PAX global header OtherEntryType 'x' _ _ -> True --PAX individual header _ -> False checkEntryTarbomb expectedTopDir entry = case FilePath.Native.splitDirectories (entryPath entry) of (topDir:_) | topDir == expectedTopDir -> Nothing s -> Just $ "File in tar archive is not in the expected directory. " ++ "Expected: " ++ show expectedTopDir ++ " but got the following hierarchy: " ++ show s -- -- * Reading -- read :: ByteString -> Entries read = unfoldrEntries getEntry getEntry :: ByteString -> Either String (Maybe (Entry, ByteString)) getEntry bs | BS.length header < 512 = Left "truncated tar archive" -- Tar files end with at least two blocks of all '0'. Checking this serves -- two purposes. It checks the format but also forces the tail of the data -- which is necessary to close the file if it came from a lazily read file. | BS.head bs == 0 = case BS.splitAt 1024 bs of (end, trailing) | BS.length end /= 1024 -> Left "short tar trailer" | not (BS.all (== 0) end) -> Left "bad tar trailer" | not (BS.all (== 0) trailing) -> Left "tar file has trailing junk" | otherwise -> Right Nothing | otherwise = partial $ do case (chksum_, format_) of (Ok chksum, _ ) | correctChecksum header chksum -> return () (Ok _, Ok _) -> fail "tar checksum error" _ -> fail "data is not in tar format" -- These fields are partial, have to check them format <- format_; mode <- mode_; uid <- uid_; gid <- gid_; size <- size_; mtime <- mtime_; devmajor <- devmajor_; devminor <- devminor_; let content = BS.take size (BS.drop 512 bs) padding = (512 - size) `mod` 512 bs' = BS.drop (512 + size + padding) bs entry = Entry { entryTarPath = TarPath name prefix, entryContent = case typecode of '\0' -> NormalFile content size '0' -> NormalFile content size '1' -> HardLink (LinkTarget linkname) '2' -> SymbolicLink (LinkTarget linkname) '3' -> CharacterDevice devmajor devminor '4' -> BlockDevice devmajor devminor '5' -> Directory '6' -> NamedPipe '7' -> NormalFile content size _ -> OtherEntryType typecode content size, entryPermissions = mode, entryOwnership = Ownership uname gname uid gid, entryTime = mtime, entryFormat = format } return (Just (entry, bs')) where header = BS.take 512 bs name = getString 0 100 header mode_ = getOct 100 8 header uid_ = getOct 108 8 header gid_ = getOct 116 8 header size_ = getOct 124 12 header mtime_ = getOct 136 12 header chksum_ = getOct 148 8 header typecode = getByte 156 header linkname = getString 157 100 header magic = getChars 257 8 header uname = getString 265 32 header gname = getString 297 32 header devmajor_ = getOct 329 8 header devminor_ = getOct 337 8 header prefix = getString 345 155 header -- trailing = getBytes 500 12 header format_ = case magic of "\0\0\0\0\0\0\0\0" -> return V7Format "ustar\NUL00" -> return UstarFormat "ustar \NUL" -> return GnuFormat _ -> fail "tar entry not in a recognised format" correctChecksum :: ByteString -> Int -> Bool correctChecksum header checksum = checksum == checksum' where -- sum of all 512 bytes in the header block, -- treating each byte as an 8-bit unsigned value checksum' = BS.Char8.foldl' (\x y -> x + ord y) 0 header' -- treating the 8 bytes of chksum as blank characters. header' = BS.concat [BS.take 148 header, BS.Char8.replicate 8 ' ', BS.drop 156 header] -- * TAR format primitive input getOct :: (Integral a, Bits a) => Int64 -> Int64 -> ByteString -> Partial a getOct off len header | BS.head bytes == 128 = parseBinInt (BS.unpack (BS.tail bytes)) | null octstr = return 0 | otherwise = case readOct octstr of [(x,[])] -> return x _ -> fail "tar header is malformed (bad numeric encoding)" where bytes = getBytes off len header octstr = BS.Char8.unpack . BS.Char8.takeWhile (\c -> c /= '\NUL' && c /= ' ') . BS.Char8.dropWhile (== ' ') $ bytes -- Some tar programs switch into a binary format when they try to represent -- field values that will not fit in the required width when using the text -- octal format. In particular, the UID/GID fields can only hold up to 2^21 -- while in the binary format can hold up to 2^32. The binary format uses -- '\128' as the header which leaves 7 bytes. Only the last 4 are used. parseBinInt [0, 0, 0, byte3, byte2, byte1, byte0] = return $! shiftL (fromIntegral byte3) 24 + shiftL (fromIntegral byte2) 16 + shiftL (fromIntegral byte1) 8 + shiftL (fromIntegral byte0) 0 parseBinInt _ = fail "tar header uses non-standard number encoding" getBytes :: Int64 -> Int64 -> ByteString -> ByteString getBytes off len = BS.take len . BS.drop off getByte :: Int64 -> ByteString -> Char getByte off bs = BS.Char8.index bs off getChars :: Int64 -> Int64 -> ByteString -> String getChars off len = BS.Char8.unpack . getBytes off len getString :: Int64 -> Int64 -> ByteString -> String getString off len = BS.Char8.unpack . BS.Char8.takeWhile (/='\0') . getBytes off len data Partial a = Error String | Ok a partial :: Partial a -> Either String a partial (Error msg) = Left msg partial (Ok x) = Right x instance Monad Partial where return = Ok Error m >>= _ = Error m Ok x >>= k = k x fail = Error -- -- * Writing -- -- | Create the external representation of a tar archive by serialising a list -- of tar entries. -- -- * The conversion is done lazily. -- write :: [Entry] -> ByteString write es = BS.concat $ map putEntry es ++ [BS.replicate (512*2) 0] -- | Same as 'write', but for 'Entries'. writeEntries :: Entries -> ByteString writeEntries entries = BS.concat $ foldrEntries (\e res -> putEntry e : res) [BS.replicate (512*2) 0] error entries putEntry :: Entry -> ByteString putEntry entry = case entryContent entry of NormalFile content size -> BS.concat [ header, content, padding size ] OtherEntryType _ content size -> BS.concat [ header, content, padding size ] _ -> header where header = putHeader entry padding size = BS.replicate paddingSize 0 where paddingSize = fromIntegral (negate size `mod` 512) putHeader :: Entry -> ByteString putHeader entry = BS.concat [ BS.take 148 block , BS.Char8.pack $ putOct 7 checksum , BS.Char8.singleton ' ' , BS.drop 156 block ] where -- putHeaderNoChkSum returns a String, so we convert it to the final -- representation before calculating the checksum. block = BS.Char8.pack . putHeaderNoChkSum $ entry checksum = BS.Char8.foldl' (\x y -> x + ord y) 0 block putHeaderNoChkSum :: Entry -> String putHeaderNoChkSum Entry { entryTarPath = TarPath name prefix, entryContent = content, entryPermissions = permissions, entryOwnership = ownership, entryTime = modTime, entryFormat = format } = concat [ putString 100 $ name , putOct 8 $ permissions , putOct 8 $ ownerId ownership , putOct 8 $ groupId ownership , putOct 12 $ contentSize , putOct 12 $ modTime , fill 8 $ ' ' -- dummy checksum , putChar8 $ typeCode , putString 100 $ linkTarget ] ++ case format of V7Format -> fill 255 '\NUL' UstarFormat -> concat [ putString 8 $ "ustar\NUL00" , putString 32 $ ownerName ownership , putString 32 $ groupName ownership , putOct 8 $ deviceMajor , putOct 8 $ deviceMinor , putString 155 $ prefix , fill 12 $ '\NUL' ] GnuFormat -> concat [ putString 8 $ "ustar \NUL" , putString 32 $ ownerName ownership , putString 32 $ groupName ownership , putGnuDev 8 $ deviceMajor , putGnuDev 8 $ deviceMinor , putString 155 $ prefix , fill 12 $ '\NUL' ] where (typeCode, contentSize, linkTarget, deviceMajor, deviceMinor) = case content of NormalFile _ size -> ('0' , size, [], 0, 0) Directory -> ('5' , 0, [], 0, 0) SymbolicLink (LinkTarget link) -> ('2' , 0, link, 0, 0) HardLink (LinkTarget link) -> ('1' , 0, link, 0, 0) CharacterDevice major minor -> ('3' , 0, [], major, minor) BlockDevice major minor -> ('4' , 0, [], major, minor) NamedPipe -> ('6' , 0, [], 0, 0) OtherEntryType code _ size -> (code, size, [], 0, 0) putGnuDev w n = case content of CharacterDevice _ _ -> putOct w n BlockDevice _ _ -> putOct w n _ -> replicate w '\NUL' -- * TAR format primitive output type FieldWidth = Int putString :: FieldWidth -> String -> String putString n s = take n s ++ fill (n - length s) '\NUL' --TODO: check integer widths, eg for large file sizes putOct :: (Show a, Integral a) => FieldWidth -> a -> String putOct n x = let octStr = take (n-1) $ showOct x "" in fill (n - length octStr - 1) '0' ++ octStr ++ putChar8 '\NUL' putChar8 :: Char -> String putChar8 c = [c] fill :: FieldWidth -> Char -> String fill n c = replicate n c -- -- * Unpacking -- unpack :: FilePath -> Entries -> IO () unpack baseDir entries = unpackEntries [] (checkSecurity entries) >>= emulateLinks where -- We're relying here on 'checkSecurity' to make sure we're not scribbling -- files all over the place. unpackEntries _ (Fail err) = fail err unpackEntries links Done = return links unpackEntries links (Next entry es) = case entryContent entry of NormalFile file _ -> extractFile entry path file >> unpackEntries links es Directory -> extractDir path >> unpackEntries links es HardLink link -> (unpackEntries $! saveLink path link links) es SymbolicLink link -> (unpackEntries $! saveLink path link links) es _ -> unpackEntries links es --ignore other file types where path = entryPath entry extractFile entry path content = do -- Note that tar archives do not make sure each directory is created -- before files they contain, indeed we may have to create several -- levels of directory. createDirectoryIfMissing True absDir BS.writeFile absPath content when (isExecutable (entryPermissions entry)) (setFileExecutable absPath) where absDir = baseDir </> FilePath.Native.takeDirectory path absPath = baseDir </> path extractDir path = createDirectoryIfMissing True (baseDir </> path) saveLink path link links = seq (length path) $ seq (length link') $ (path, link'):links where link' = fromLinkTarget link emulateLinks = mapM_ $ \(relPath, relLinkTarget) -> let absPath = baseDir </> relPath absTarget = FilePath.Native.takeDirectory absPath </> relLinkTarget in copyFile absTarget absPath -- -- * Packing -- pack :: FilePath -- ^ Base directory -> [FilePath] -- ^ Files and directories to pack, relative to the base dir -> IO [Entry] pack baseDir paths0 = preparePaths baseDir paths0 >>= packPaths baseDir preparePaths :: FilePath -> [FilePath] -> IO [FilePath] preparePaths baseDir paths = fmap concat $ interleave [ do isDir <- doesDirectoryExist (baseDir </> path) if isDir then do entries <- getDirectoryContentsRecursive (baseDir </> path) return (FilePath.Native.addTrailingPathSeparator path : map (path </>) entries) else return [path] | path <- paths ] packPaths :: FilePath -> [FilePath] -> IO [Entry] packPaths baseDir paths = interleave [ do tarpath <- either fail return (toTarPath isDir relpath) if isDir then packDirectoryEntry filepath tarpath else packFileEntry filepath tarpath | relpath <- paths , let isDir = FilePath.Native.hasTrailingPathSeparator filepath filepath = baseDir </> relpath ] interleave :: [IO a] -> IO [a] interleave = unsafeInterleaveIO . go where go [] = return [] go (x:xs) = do x' <- x xs' <- interleave xs return (x':xs') packFileEntry :: FilePath -- ^ Full path to find the file on the local disk -> TarPath -- ^ Path to use for the tar Entry in the archive -> IO Entry packFileEntry filepath tarpath = do mtime <- getModTime filepath perms <- getPermissions filepath file <- openBinaryFile filepath ReadMode size <- hFileSize file content <- BS.hGetContents file return (simpleEntry tarpath (NormalFile content (fromIntegral size))) { entryPermissions = if Permissions.executable perms then executableFilePermissions else ordinaryFilePermissions, entryTime = mtime } packDirectoryEntry :: FilePath -- ^ Full path to find the file on the local disk -> TarPath -- ^ Path to use for the tar Entry in the archive -> IO Entry packDirectoryEntry filepath tarpath = do mtime <- getModTime filepath return (directoryEntry tarpath) { entryTime = mtime } getDirectoryContentsRecursive :: FilePath -> IO [FilePath] getDirectoryContentsRecursive dir0 = fmap tail (recurseDirectories dir0 [""]) recurseDirectories :: FilePath -> [FilePath] -> IO [FilePath] recurseDirectories _ [] = return [] recurseDirectories base (dir:dirs) = unsafeInterleaveIO $ do (files, dirs') <- collect [] [] =<< getDirectoryContents (base </> dir) files' <- recurseDirectories base (dirs' ++ dirs) return (dir : files ++ files') where collect files dirs' [] = return (reverse files, reverse dirs') collect files dirs' (entry:entries) | ignore entry = collect files dirs' entries collect files dirs' (entry:entries) = do let dirEntry = dir </> entry dirEntry' = FilePath.Native.addTrailingPathSeparator dirEntry isDirectory <- doesDirectoryExist (base </> dirEntry) if isDirectory then collect files (dirEntry':dirs') entries else collect (dirEntry:files) dirs' entries ignore ['.'] = True ignore ['.', '.'] = True ignore _ = False
jwiegley/ghc-release
libraries/Cabal/cabal-install/Distribution/Client/Tar.hs
gpl-3.0
33,029
0
19
9,167
7,184
3,813
3,371
600
15
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.Glacier.DeleteVaultAccessPolicy -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- This operation deletes the access policy associated with the specified -- vault. The operation is eventually consistent; that is, it might take -- some time for Amazon Glacier to completely remove the access policy, and -- you might still see the effect of the policy for a short time after you -- send the delete request. -- -- This operation is idempotent. You can invoke delete multiple times, even -- if there is no policy associated with the vault. For more information -- about vault access policies, see -- <http://docs.aws.amazon.com/amazonglacier/latest/dev/vault-access-policy.html Amazon Glacier Access Control with Vault Access Policies>. -- -- /See:/ <http://docs.aws.amazon.com/amazonglacier/latest/dev/api-DeleteVaultAccessPolicy.html AWS API Reference> for DeleteVaultAccessPolicy. module Network.AWS.Glacier.DeleteVaultAccessPolicy ( -- * Creating a Request deleteVaultAccessPolicy , DeleteVaultAccessPolicy -- * Request Lenses , dvapAccountId , dvapVaultName -- * Destructuring the Response , deleteVaultAccessPolicyResponse , DeleteVaultAccessPolicyResponse ) where import Network.AWS.Glacier.Types import Network.AWS.Glacier.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | DeleteVaultAccessPolicy input. -- -- /See:/ 'deleteVaultAccessPolicy' smart constructor. data DeleteVaultAccessPolicy = DeleteVaultAccessPolicy' { _dvapAccountId :: !Text , _dvapVaultName :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DeleteVaultAccessPolicy' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dvapAccountId' -- -- * 'dvapVaultName' deleteVaultAccessPolicy :: Text -- ^ 'dvapAccountId' -> Text -- ^ 'dvapVaultName' -> DeleteVaultAccessPolicy deleteVaultAccessPolicy pAccountId_ pVaultName_ = DeleteVaultAccessPolicy' { _dvapAccountId = pAccountId_ , _dvapVaultName = pVaultName_ } -- | The 'AccountId' value is the AWS account ID of the account that owns the -- vault. You can either specify an AWS account ID or optionally a single -- apos'-'apos (hyphen), in which case Amazon Glacier uses the AWS account -- ID associated with the credentials used to sign the request. If you use -- an account ID, do not include any hyphens (apos-apos) in the ID. dvapAccountId :: Lens' DeleteVaultAccessPolicy Text dvapAccountId = lens _dvapAccountId (\ s a -> s{_dvapAccountId = a}); -- | The name of the vault. dvapVaultName :: Lens' DeleteVaultAccessPolicy Text dvapVaultName = lens _dvapVaultName (\ s a -> s{_dvapVaultName = a}); instance AWSRequest DeleteVaultAccessPolicy where type Rs DeleteVaultAccessPolicy = DeleteVaultAccessPolicyResponse request = delete glacier response = receiveNull DeleteVaultAccessPolicyResponse' instance ToHeaders DeleteVaultAccessPolicy where toHeaders = const mempty instance ToPath DeleteVaultAccessPolicy where toPath DeleteVaultAccessPolicy'{..} = mconcat ["/", toBS _dvapAccountId, "/vaults/", toBS _dvapVaultName, "/access-policy"] instance ToQuery DeleteVaultAccessPolicy where toQuery = const mempty -- | /See:/ 'deleteVaultAccessPolicyResponse' smart constructor. data DeleteVaultAccessPolicyResponse = DeleteVaultAccessPolicyResponse' deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DeleteVaultAccessPolicyResponse' with the minimum fields required to make a request. -- deleteVaultAccessPolicyResponse :: DeleteVaultAccessPolicyResponse deleteVaultAccessPolicyResponse = DeleteVaultAccessPolicyResponse'
fmapfmapfmap/amazonka
amazonka-glacier/gen/Network/AWS/Glacier/DeleteVaultAccessPolicy.hs
mpl-2.0
4,500
0
9
813
434
268
166
62
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.IAM.RemoveRoleFromInstanceProfile -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Removes the specified role from the specified instance profile. -- -- Make sure you do not have any Amazon EC2 instances running with the role -- you are about to remove from the instance profile. Removing a role from -- an instance profile that is associated with a running instance will -- break any applications running on the instance. -- -- For more information about roles, go to -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html Working with Roles>. -- For more information about instance profiles, go to -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/AboutInstanceProfiles.html About Instance Profiles>. -- -- /See:/ <http://docs.aws.amazon.com/IAM/latest/APIReference/API_RemoveRoleFromInstanceProfile.html AWS API Reference> for RemoveRoleFromInstanceProfile. module Network.AWS.IAM.RemoveRoleFromInstanceProfile ( -- * Creating a Request removeRoleFromInstanceProfile , RemoveRoleFromInstanceProfile -- * Request Lenses , rrfipInstanceProfileName , rrfipRoleName -- * Destructuring the Response , removeRoleFromInstanceProfileResponse , RemoveRoleFromInstanceProfileResponse ) where import Network.AWS.IAM.Types import Network.AWS.IAM.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'removeRoleFromInstanceProfile' smart constructor. data RemoveRoleFromInstanceProfile = RemoveRoleFromInstanceProfile' { _rrfipInstanceProfileName :: !Text , _rrfipRoleName :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'RemoveRoleFromInstanceProfile' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rrfipInstanceProfileName' -- -- * 'rrfipRoleName' removeRoleFromInstanceProfile :: Text -- ^ 'rrfipInstanceProfileName' -> Text -- ^ 'rrfipRoleName' -> RemoveRoleFromInstanceProfile removeRoleFromInstanceProfile pInstanceProfileName_ pRoleName_ = RemoveRoleFromInstanceProfile' { _rrfipInstanceProfileName = pInstanceProfileName_ , _rrfipRoleName = pRoleName_ } -- | The name of the instance profile to update. rrfipInstanceProfileName :: Lens' RemoveRoleFromInstanceProfile Text rrfipInstanceProfileName = lens _rrfipInstanceProfileName (\ s a -> s{_rrfipInstanceProfileName = a}); -- | The name of the role to remove. rrfipRoleName :: Lens' RemoveRoleFromInstanceProfile Text rrfipRoleName = lens _rrfipRoleName (\ s a -> s{_rrfipRoleName = a}); instance AWSRequest RemoveRoleFromInstanceProfile where type Rs RemoveRoleFromInstanceProfile = RemoveRoleFromInstanceProfileResponse request = postQuery iAM response = receiveNull RemoveRoleFromInstanceProfileResponse' instance ToHeaders RemoveRoleFromInstanceProfile where toHeaders = const mempty instance ToPath RemoveRoleFromInstanceProfile where toPath = const "/" instance ToQuery RemoveRoleFromInstanceProfile where toQuery RemoveRoleFromInstanceProfile'{..} = mconcat ["Action" =: ("RemoveRoleFromInstanceProfile" :: ByteString), "Version" =: ("2010-05-08" :: ByteString), "InstanceProfileName" =: _rrfipInstanceProfileName, "RoleName" =: _rrfipRoleName] -- | /See:/ 'removeRoleFromInstanceProfileResponse' smart constructor. data RemoveRoleFromInstanceProfileResponse = RemoveRoleFromInstanceProfileResponse' deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'RemoveRoleFromInstanceProfileResponse' with the minimum fields required to make a request. -- removeRoleFromInstanceProfileResponse :: RemoveRoleFromInstanceProfileResponse removeRoleFromInstanceProfileResponse = RemoveRoleFromInstanceProfileResponse'
olorin/amazonka
amazonka-iam/gen/Network/AWS/IAM/RemoveRoleFromInstanceProfile.hs
mpl-2.0
4,626
0
9
826
448
275
173
65
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="de-DE"> <title>Python Scripting</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Suche</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/jython/src/main/javahelp/org/zaproxy/zap/extension/jython/resources/help_de_DE/helpset_de_DE.hs
apache-2.0
961
79
66
157
409
207
202
-1
-1
{-# LANGUAGE LambdaCase #-} module Language.K3.Driver.Interactive where import Control.Monad import System.Console.Readline import System.Exit import Language.K3.Interpreter import Language.K3.Parser import Language.K3.Pretty -- | Run an interactive prompt, reading evaulating and printing at each step. runInteractive :: IO () runInteractive = readline ">>> " >>= \case Nothing -> exitSuccess Just input -> addHistory input >> repl input >> runInteractive -- | A single round of parsing, interpretation and pretty-printing. repl :: String -> IO () repl input = do case runK3Parser Nothing expr input of Left e -> print e Right t -> do putStr $ pretty t i <- runInterpretation [] $ expression t print i
DaMSL/K3
src/Language/K3/Driver/Interactive.hs
apache-2.0
773
0
15
174
190
96
94
20
2
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Distribution.Types.Module ( Module(..) ) where import Prelude () import Distribution.Compat.Prelude import qualified Distribution.Compat.ReadP as Parse import qualified Text.PrettyPrint as Disp import Distribution.Text import Distribution.Types.UnitId import Distribution.ModuleName -- | A module identity uniquely identifies a Haskell module by -- qualifying a 'ModuleName' with the 'UnitId' which defined -- it. This type distinguishes between two packages -- which provide a module with the same name, or a module -- from the same package compiled with different dependencies. -- There are a few cases where Cabal needs to know about -- module identities, e.g., when writing out reexported modules in -- the 'InstalledPackageInfo'. data Module = Module DefUnitId ModuleName deriving (Generic, Read, Show, Eq, Ord, Typeable, Data) instance Binary Module instance Text Module where disp (Module uid mod_name) = disp uid <<>> Disp.text ":" <<>> disp mod_name parse = do uid <- parse _ <- Parse.char ':' mod_name <- parse return (Module uid mod_name) instance NFData Module where rnf (Module uid mod_name) = rnf uid `seq` rnf mod_name
mydaum/cabal
Cabal/Distribution/Types/Module.hs
bsd-3-clause
1,326
0
10
252
245
136
109
26
0
{-# LANGUAGE DataKinds #-} -- | Finding files. module Path.Find (findFileUp ,findDirUp ,findFiles) where import Control.Monad import Control.Monad.Catch import Control.Monad.IO.Class import System.IO.Error (isPermissionError) import Data.List import Path import Path.IO -- | Find the location of a file matching the given predicate. findFileUp :: (MonadIO m,MonadThrow m) => Path Abs Dir -- ^ Start here. -> (Path Abs File -> Bool) -- ^ Predicate to match the file. -> Maybe (Path Abs Dir) -- ^ Do not ascend above this directory. -> m (Maybe (Path Abs File)) -- ^ Absolute file path. findFileUp s p d = findPathUp snd s p d -- | Find the location of a directory matching the given predicate. findDirUp :: (MonadIO m,MonadThrow m) => Path Abs Dir -- ^ Start here. -> (Path Abs Dir -> Bool) -- ^ Predicate to match the directory. -> Maybe (Path Abs Dir) -- ^ Do not ascend above this directory. -> m (Maybe (Path Abs Dir)) -- ^ Absolute directory path. findDirUp s p d = findPathUp fst s p d -- | Find the location of a path matching the given predicate. findPathUp :: (MonadIO m,MonadThrow m) => (([Path Abs Dir],[Path Abs File]) -> [Path Abs t]) -- ^ Choose path type from pair. -> Path Abs Dir -- ^ Start here. -> (Path Abs t -> Bool) -- ^ Predicate to match the path. -> Maybe (Path Abs Dir) -- ^ Do not ascend above this directory. -> m (Maybe (Path Abs t)) -- ^ Absolute path. findPathUp pathType dir p upperBound = do entries <- listDirectory dir case find p (pathType entries) of Just path -> return (Just path) Nothing | Just dir == upperBound -> return Nothing | parent dir == dir -> return Nothing | otherwise -> findPathUp pathType (parent dir) p upperBound -- | Find files matching predicate below a root directory. findFiles :: Path Abs Dir -- ^ Root directory to begin with. -> (Path Abs File -> Bool) -- ^ Predicate to match files. -> (Path Abs Dir -> Bool) -- ^ Predicate for which directories to traverse. -> IO [Path Abs File] -- ^ List of matching files. findFiles dir p traversep = do (dirs,files) <- catchJust (\ e -> if isPermissionError e then Just () else Nothing) (listDirectory dir) (\ _ -> return ([], [])) subResults <- forM dirs (\entry -> if traversep entry then findFiles entry p traversep else return []) return (concat (filter p files : subResults))
mathhun/stack
src/Path/Find.hs
bsd-3-clause
2,885
0
14
1,013
728
376
352
54
3
------------------------------------------------------------------ -- A primop-table mangling program -- ------------------------------------------------------------------ module Main where import Parser import Syntax import Data.Char import Data.List import Data.Maybe ( catMaybes ) import System.Environment ( getArgs ) vecOptions :: Entry -> [(String,String,Int)] vecOptions i = concat [vecs | OptionVector vecs <- opts i] desugarVectorSpec :: Entry -> [Entry] desugarVectorSpec i@(Section {}) = [i] desugarVectorSpec i = case vecOptions i of [] -> [i] vos -> map genVecEntry vos where genVecEntry :: (String,String,Int) -> Entry genVecEntry (con,repCon,n) = case i of PrimOpSpec {} -> PrimVecOpSpec { cons = "(" ++ concat (intersperse " " [cons i, vecCat, show n, vecWidth]) ++ ")" , name = name' , prefix = pfx , veclen = n , elemrep = con ++ "ElemRep" , ty = desugarTy (ty i) , cat = cat i , desc = desc i , opts = opts i } PrimTypeSpec {} -> PrimVecTypeSpec { ty = desugarTy (ty i) , prefix = pfx , veclen = n , elemrep = con ++ "ElemRep" , desc = desc i , opts = opts i } _ -> error "vector options can only be given for primops and primtypes" where vecCons = con++"X"++show n++"#" vecCat = conCat con vecWidth = conWidth con pfx = lowerHead con++"X"++show n vecTyName = pfx++"PrimTy" name' | Just pre <- splitSuffix (name i) "Array#" = pre++vec++"Array#" | Just pre <- splitSuffix (name i) "OffAddr#" = pre++vec++"OffAddr#" | Just pre <- splitSuffix (name i) "ArrayAs#" = pre++con++"ArrayAs"++vec++"#" | Just pre <- splitSuffix (name i) "OffAddrAs#" = pre++con++"OffAddrAs"++vec++"#" | otherwise = init (name i)++vec ++"#" where vec = con++"X"++show n splitSuffix :: Eq a => [a] -> [a] -> Maybe [a] splitSuffix s suf | drop len s == suf = Just (take len s) | otherwise = Nothing where len = length s - length suf lowerHead s = toLower (head s) : tail s desugarTy :: Ty -> Ty desugarTy (TyF s d) = TyF (desugarTy s) (desugarTy d) desugarTy (TyC s d) = TyC (desugarTy s) (desugarTy d) desugarTy (TyApp SCALAR []) = TyApp (TyCon repCon) [] desugarTy (TyApp VECTOR []) = TyApp (VecTyCon vecCons vecTyName) [] desugarTy (TyApp VECTUPLE []) = TyUTup (replicate n (TyApp (TyCon repCon) [])) desugarTy (TyApp tycon ts) = TyApp tycon (map desugarTy ts) desugarTy t@(TyVar {}) = t desugarTy (TyUTup ts) = TyUTup (map desugarTy ts) conCat :: String -> String conCat "Int8" = "IntVec" conCat "Int16" = "IntVec" conCat "Int32" = "IntVec" conCat "Int64" = "IntVec" conCat "Word8" = "WordVec" conCat "Word16" = "WordVec" conCat "Word32" = "WordVec" conCat "Word64" = "WordVec" conCat "Float" = "FloatVec" conCat "Double" = "FloatVec" conCat con = error $ "conCat: unknown type constructor " ++ con ++ "\n" conWidth :: String -> String conWidth "Int8" = "W8" conWidth "Int16" = "W16" conWidth "Int32" = "W32" conWidth "Int64" = "W64" conWidth "Word8" = "W8" conWidth "Word16" = "W16" conWidth "Word32" = "W32" conWidth "Word64" = "W64" conWidth "Float" = "W32" conWidth "Double" = "W64" conWidth con = error $ "conWidth: unknown type constructor " ++ con ++ "\n" main :: IO () main = getArgs >>= \args -> if length args /= 1 || head args `notElem` known_args then error ("usage: genprimopcode command < primops.txt > ...\n" ++ " where command is one of\n" ++ unlines (map (" "++) known_args) ) else do s <- getContents case parse s of Left err -> error ("parse error at " ++ (show err)) Right p_o_specs@(Info _ _) -> seq (sanityTop p_o_specs) ( case head args of "--data-decl" -> putStr (gen_data_decl p_o_specs) "--has-side-effects" -> putStr (gen_switch_from_attribs "has_side_effects" "primOpHasSideEffects" p_o_specs) "--out-of-line" -> putStr (gen_switch_from_attribs "out_of_line" "primOpOutOfLine" p_o_specs) "--commutable" -> putStr (gen_switch_from_attribs "commutable" "commutableOp" p_o_specs) "--code-size" -> putStr (gen_switch_from_attribs "code_size" "primOpCodeSize" p_o_specs) "--can-fail" -> putStr (gen_switch_from_attribs "can_fail" "primOpCanFail" p_o_specs) "--strictness" -> putStr (gen_switch_from_attribs "strictness" "primOpStrictness" p_o_specs) "--fixity" -> putStr (gen_switch_from_attribs "fixity" "primOpFixity" p_o_specs) "--primop-primop-info" -> putStr (gen_primop_info p_o_specs) "--primop-tag" -> putStr (gen_primop_tag p_o_specs) "--primop-list" -> putStr (gen_primop_list p_o_specs) "--primop-vector-uniques" -> putStr (gen_primop_vector_uniques p_o_specs) "--primop-vector-tys" -> putStr (gen_primop_vector_tys p_o_specs) "--primop-vector-tys-exports" -> putStr (gen_primop_vector_tys_exports p_o_specs) "--primop-vector-tycons" -> putStr (gen_primop_vector_tycons p_o_specs) "--make-haskell-wrappers" -> putStr (gen_wrappers p_o_specs) "--make-haskell-source" -> putStr (gen_hs_source p_o_specs) "--make-latex-doc" -> putStr (gen_latex_doc p_o_specs) _ -> error "Should not happen, known_args out of sync?" ) known_args :: [String] known_args = [ "--data-decl", "--has-side-effects", "--out-of-line", "--commutable", "--code-size", "--can-fail", "--strictness", "--fixity", "--primop-primop-info", "--primop-tag", "--primop-list", "--primop-vector-uniques", "--primop-vector-tys", "--primop-vector-tys-exports", "--primop-vector-tycons", "--make-haskell-wrappers", "--make-haskell-source", "--make-latex-doc" ] ------------------------------------------------------------------ -- Code generators ----------------------------------------------- ------------------------------------------------------------------ gen_hs_source :: Info -> String gen_hs_source (Info defaults entries) = "{-\n" ++ "This is a generated file (generated by genprimopcode).\n" ++ "It is not code to actually be used. Its only purpose is to be\n" ++ "consumed by haddock.\n" ++ "-}\n" ++ "\n" ++ (replicate 77 '-' ++ "\n") -- For 80-col cleanliness ++ "-- |\n" ++ "-- Module : GHC.Prim\n" ++ "-- \n" ++ "-- Maintainer : ghc-devs@haskell.org\n" ++ "-- Stability : internal\n" ++ "-- Portability : non-portable (GHC extensions)\n" ++ "--\n" ++ "-- GHC\'s primitive types and operations.\n" ++ "-- Use GHC.Exts from the base package instead of importing this\n" ++ "-- module directly.\n" ++ "--\n" ++ (replicate 77 '-' ++ "\n") -- For 80-col cleanliness ++ "{-# LANGUAGE Unsafe #-}\n" ++ "{-# LANGUAGE MagicHash #-}\n" ++ "{-# LANGUAGE MultiParamTypeClasses #-}\n" ++ "{-# LANGUAGE NoImplicitPrelude #-}\n" ++ "{-# LANGUAGE UnboxedTuples #-}\n" ++ "{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}\n" -- We generate a binding for coerce, like -- coerce :: Coercible a b => a -> b -- coerce = let x = x in x -- and we don't want a complaint that the constraint is redundant -- Remember, this silly file is only for Haddock's consumption ++ "module GHC.Prim (\n" ++ unlines (map ((" " ++) . hdr) entries') ++ ") where\n" ++ "\n" ++ "{-\n" ++ unlines (map opt defaults) ++ "-}\n" ++ "import GHC.Types (Coercible)\n" ++ "default ()" -- If we don't say this then the default type include Integer -- so that runs off and loads modules that are not part of -- pacakge ghc-prim at all. And that in turn somehow ends up -- with Declaration for $fEqMaybe: -- attempting to use module ‘GHC.Classes’ -- (libraries/ghc-prim/./GHC/Classes.hs) which is not loaded -- coming from LoadIface.homeModError -- I'm not sure precisely why; but I *am* sure that we don't need -- any type-class defaulting; and it's clearly wrong to need -- the base package when haddocking ghc-prim -- Now the main payload ++ unlines (concatMap ent entries') ++ "\n\n\n" where entries' = concatMap desugarVectorSpec entries opt (OptionFalse n) = n ++ " = False" opt (OptionTrue n) = n ++ " = True" opt (OptionString n v) = n ++ " = { " ++ v ++ "}" opt (OptionInteger n v) = n ++ " = " ++ show v opt (OptionVector _) = "" opt (OptionFixity mf) = "fixity" ++ " = " ++ show mf hdr s@(Section {}) = sec s hdr (PrimOpSpec { name = n }) = wrapOp n ++ "," hdr (PrimVecOpSpec { name = n }) = wrapOp n ++ "," hdr (PseudoOpSpec { name = n }) = wrapOp n ++ "," hdr (PrimTypeSpec { ty = TyApp (TyCon n) _ }) = wrapTy n ++ "," hdr (PrimTypeSpec {}) = error $ "Illegal type spec" hdr (PrimVecTypeSpec { ty = TyApp (VecTyCon n _) _ }) = wrapTy n ++ "," hdr (PrimVecTypeSpec {}) = error $ "Illegal type spec" ent (Section {}) = [] ent o@(PrimOpSpec {}) = spec o ent o@(PrimVecOpSpec {}) = spec o ent o@(PrimTypeSpec {}) = spec o ent o@(PrimVecTypeSpec {}) = spec o ent o@(PseudoOpSpec {}) = spec o sec s = "\n-- * " ++ escape (title s) ++ "\n" ++ (unlines $ map ("-- " ++ ) $ lines $ unlatex $ escape $ "|" ++ desc s) ++ "\n" spec o = comm : decls where decls = case o of -- See Note [Placeholder declarations] PrimOpSpec { name = n, ty = t, opts = options } -> prim_fixity n options ++ prim_decl n t PrimVecOpSpec { name = n, ty = t, opts = options } -> prim_fixity n options ++ prim_decl n t PseudoOpSpec { name = n, ty = t } -> prim_decl n t PrimTypeSpec { ty = t } -> [ "data " ++ pprTy t ] PrimVecTypeSpec { ty = t } -> [ "data " ++ pprTy t ] Section { } -> [] comm = case (desc o) of [] -> "" d -> "\n" ++ (unlines $ map ("-- " ++ ) $ lines $ unlatex $ escape $ "|" ++ d) prim_fixity n options = [ pprFixity fixity n | OptionFixity (Just fixity) <- options ] prim_decl n t = [ wrapOp n ++ " :: " ++ pprTy t, wrapOp n ++ " = " ++ wrapOpRhs n ] wrapOp nm | isAlpha (head nm) = nm | otherwise = "(" ++ nm ++ ")" wrapTy nm | isAlpha (head nm) = nm | otherwise = "(" ++ nm ++ ")" wrapOpRhs "tagToEnum#" = "let x = x in x" wrapOpRhs nm = wrapOp nm -- Special case for tagToEnum#: see Note [Placeholder declarations] unlatex s = case s of '\\':'t':'e':'x':'t':'t':'t':'{':cs -> markup "@" "@" cs '{':'\\':'t':'t':cs -> markup "@" "@" cs '{':'\\':'i':'t':cs -> markup "/" "/" cs c : cs -> c : unlatex cs [] -> [] markup s t xs = s ++ mk (dropWhile isSpace xs) where mk "" = t mk ('\n':cs) = ' ' : mk cs mk ('}':cs) = t ++ unlatex cs mk (c:cs) = c : mk cs escape = concatMap (\c -> if c `elem` special then '\\':c:[] else c:[]) where special = "/'`\"@<" pprFixity (Fixity _ i d) n = pprFixityDir d ++ " " ++ show i ++ " " ++ n {- Note [Placeholder declarations] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We are generating fake declarations for things in GHC.Prim, just to keep GHC's renamer and typechecker happy enough for what Haddock needs. Our main plan is to say foo :: <type> foo = foo We have to silence GHC's complaints about unboxed-top-level declarations with an ad-hoc fix in TcBinds: see Note [Compiling GHC.Prim] in TcBinds. That works for all the primitive functions except tagToEnum#. If we generate the binding tagToEnum# = tagToEnum# GHC will complain about "tagToEnum# must appear applied to one argument". We could hack GHC to silence this complaint when compiling GHC.Prim, but it seems easier to generate tagToEnum# = let x = x in x We don't do this for *all* bindings because for ones with an unboxed RHS we would get other complaints (e.g.can't unify "*" with "#"). -} pprTy :: Ty -> String pprTy = pty where pty (TyF t1 t2) = pbty t1 ++ " -> " ++ pty t2 pty (TyC t1 t2) = pbty t1 ++ " => " ++ pty t2 pty t = pbty t pbty (TyApp tc ts) = show tc ++ concat (map (' ' :) (map paty ts)) pbty (TyUTup ts) = "(# " ++ concat (intersperse "," (map pty ts)) ++ " #)" pbty t = paty t paty (TyVar tv) = tv paty t = "(" ++ pty t ++ ")" gen_latex_doc :: Info -> String gen_latex_doc (Info defaults entries) = "\\primopdefaults{" ++ mk_options defaults ++ "}\n" ++ (concat (map mk_entry entries)) where mk_entry (PrimOpSpec {cons=constr,name=n,ty=t,cat=c,desc=d,opts=o}) = "\\primopdesc{" ++ latex_encode constr ++ "}{" ++ latex_encode n ++ "}{" ++ latex_encode (zencode n) ++ "}{" ++ latex_encode (show c) ++ "}{" ++ latex_encode (mk_source_ty t) ++ "}{" ++ latex_encode (mk_core_ty t) ++ "}{" ++ d ++ "}{" ++ mk_options o ++ "}\n" mk_entry (PrimVecOpSpec {}) = "" mk_entry (Section {title=ti,desc=d}) = "\\primopsection{" ++ latex_encode ti ++ "}{" ++ d ++ "}\n" mk_entry (PrimTypeSpec {ty=t,desc=d,opts=o}) = "\\primtypespec{" ++ latex_encode (mk_source_ty t) ++ "}{" ++ latex_encode (mk_core_ty t) ++ "}{" ++ d ++ "}{" ++ mk_options o ++ "}\n" mk_entry (PrimVecTypeSpec {}) = "" mk_entry (PseudoOpSpec {name=n,ty=t,desc=d,opts=o}) = "\\pseudoopspec{" ++ latex_encode (zencode n) ++ "}{" ++ latex_encode (mk_source_ty t) ++ "}{" ++ latex_encode (mk_core_ty t) ++ "}{" ++ d ++ "}{" ++ mk_options o ++ "}\n" mk_source_ty typ = pty typ where pty (TyF t1 t2) = pbty t1 ++ " -> " ++ pty t2 pty (TyC t1 t2) = pbty t1 ++ " => " ++ pty t2 pty t = pbty t pbty (TyApp tc ts) = show tc ++ (concat (map (' ':) (map paty ts))) pbty (TyUTup ts) = "(# " ++ (concat (intersperse "," (map pty ts))) ++ " #)" pbty t = paty t paty (TyVar tv) = tv paty t = "(" ++ pty t ++ ")" mk_core_ty typ = foralls ++ (pty typ) where pty (TyF t1 t2) = pbty t1 ++ " -> " ++ pty t2 pty (TyC t1 t2) = pbty t1 ++ " => " ++ pty t2 pty t = pbty t pbty (TyApp tc ts) = (zencode (show tc)) ++ (concat (map (' ':) (map paty ts))) pbty (TyUTup ts) = (zencode (utuplenm (length ts))) ++ (concat ((map (' ':) (map paty ts)))) pbty t = paty t paty (TyVar tv) = zencode tv paty (TyApp tc []) = zencode (show tc) paty t = "(" ++ pty t ++ ")" utuplenm 1 = "(# #)" utuplenm n = "(#" ++ (replicate (n-1) ',') ++ "#)" foralls = if tvars == [] then "" else "%forall " ++ (tbinds tvars) tvars = tvars_of typ tbinds [] = ". " tbinds ("o":tbs) = "(o::?) " ++ (tbinds tbs) tbinds (tv:tbs) = tv ++ " " ++ (tbinds tbs) tvars_of (TyF t1 t2) = tvars_of t1 `union` tvars_of t2 tvars_of (TyC t1 t2) = tvars_of t1 `union` tvars_of t2 tvars_of (TyApp _ ts) = foldl union [] (map tvars_of ts) tvars_of (TyUTup ts) = foldr union [] (map tvars_of ts) tvars_of (TyVar tv) = [tv] mk_options o = "\\primoptions{" ++ mk_has_side_effects o ++ "}{" ++ mk_out_of_line o ++ "}{" ++ mk_commutable o ++ "}{" ++ mk_needs_wrapper o ++ "}{" ++ mk_can_fail o ++ "}{" ++ mk_fixity o ++ "}{" ++ latex_encode (mk_strictness o) ++ "}{" ++ "}" mk_has_side_effects o = mk_bool_opt o "has_side_effects" "Has side effects." "Has no side effects." mk_out_of_line o = mk_bool_opt o "out_of_line" "Implemented out of line." "Implemented in line." mk_commutable o = mk_bool_opt o "commutable" "Commutable." "Not commutable." mk_needs_wrapper o = mk_bool_opt o "needs_wrapper" "Needs wrapper." "Needs no wrapper." mk_can_fail o = mk_bool_opt o "can_fail" "Can fail." "Cannot fail." mk_bool_opt o opt_name if_true if_false = case lookup_attrib opt_name o of Just (OptionTrue _) -> if_true Just (OptionFalse _) -> if_false Just (OptionString _ _) -> error "String value for boolean option" Just (OptionInteger _ _) -> error "Integer value for boolean option" Just (OptionFixity _) -> error "Fixity value for boolean option" Just (OptionVector _) -> error "vector template for boolean option" Nothing -> "" mk_strictness o = case lookup_attrib "strictness" o of Just (OptionString _ s) -> s -- for now Just _ -> error "Wrong value for strictness" Nothing -> "" mk_fixity o = case lookup_attrib "fixity" o of Just (OptionFixity (Just (Fixity _ i d))) -> pprFixityDir d ++ " " ++ show i _ -> "" zencode xs = case maybe_tuple xs of Just n -> n -- Tuples go to Z2T etc Nothing -> concat (map encode_ch xs) where maybe_tuple "(# #)" = Just("Z1H") maybe_tuple ('(' : '#' : cs) = case count_commas (0::Int) cs of (n, '#' : ')' : _) -> Just ('Z' : shows (n+1) "H") _ -> Nothing maybe_tuple "()" = Just("Z0T") maybe_tuple ('(' : cs) = case count_commas (0::Int) cs of (n, ')' : _) -> Just ('Z' : shows (n+1) "T") _ -> Nothing maybe_tuple _ = Nothing count_commas :: Int -> String -> (Int, String) count_commas n (',' : cs) = count_commas (n+1) cs count_commas n cs = (n,cs) unencodedChar :: Char -> Bool -- True for chars that don't need encoding unencodedChar 'Z' = False unencodedChar 'z' = False unencodedChar c = isAlphaNum c encode_ch :: Char -> String encode_ch c | unencodedChar c = [c] -- Common case first -- Constructors encode_ch '(' = "ZL" -- Needed for things like (,), and (->) encode_ch ')' = "ZR" -- For symmetry with ( encode_ch '[' = "ZM" encode_ch ']' = "ZN" encode_ch ':' = "ZC" encode_ch 'Z' = "ZZ" -- Variables encode_ch 'z' = "zz" encode_ch '&' = "za" encode_ch '|' = "zb" encode_ch '^' = "zc" encode_ch '$' = "zd" encode_ch '=' = "ze" encode_ch '>' = "zg" encode_ch '#' = "zh" encode_ch '.' = "zi" encode_ch '<' = "zl" encode_ch '-' = "zm" encode_ch '!' = "zn" encode_ch '+' = "zp" encode_ch '\'' = "zq" encode_ch '\\' = "zr" encode_ch '/' = "zs" encode_ch '*' = "zt" encode_ch '_' = "zu" encode_ch '%' = "zv" encode_ch c = 'z' : shows (ord c) "U" latex_encode [] = [] latex_encode (c:cs) | c `elem` "#$%&_^{}" = "\\" ++ c:(latex_encode cs) latex_encode ('~':cs) = "\\verb!~!" ++ (latex_encode cs) latex_encode ('\\':cs) = "$\\backslash$" ++ (latex_encode cs) latex_encode (c:cs) = c:(latex_encode cs) gen_wrappers :: Info -> String gen_wrappers (Info _ entries) = "{-# LANGUAGE MagicHash, NoImplicitPrelude, UnboxedTuples #-}\n" -- Dependencies on Prelude must be explicit in libraries/base, but we -- don't need the Prelude here so we add NoImplicitPrelude. ++ "module GHC.PrimopWrappers where\n" ++ "import qualified GHC.Prim\n" ++ "import GHC.Tuple ()\n" ++ "import GHC.Prim (" ++ types ++ ")\n" ++ unlines (concatMap f specs) where specs = filter (not.dodgy) $ filter (not.is_llvm_only) $ filter is_primop entries tycons = foldr union [] $ map (tyconsIn . ty) specs tycons' = filter (`notElem` [TyCon "()", TyCon "Bool"]) tycons types = concat $ intersperse ", " $ map show tycons' f spec = let args = map (\n -> "a" ++ show n) [1 .. arity (ty spec)] src_name = wrap (name spec) lhs = src_name ++ " " ++ unwords args rhs = "(GHC.Prim." ++ name spec ++ ") " ++ unwords args in ["{-# NOINLINE " ++ src_name ++ " #-}", src_name ++ " :: " ++ pprTy (ty spec), lhs ++ " = " ++ rhs] wrap nm | isLower (head nm) = nm | otherwise = "(" ++ nm ++ ")" dodgy spec = name spec `elem` [-- tagToEnum# is really magical, and can't have -- a wrapper since its implementation depends on -- the type of its result "tagToEnum#" ] is_llvm_only :: Entry -> Bool is_llvm_only entry = case lookup_attrib "llvm_only" (opts entry) of Just (OptionTrue _) -> True _ -> False gen_primop_list :: Info -> String gen_primop_list (Info _ entries) = unlines ( [ " [" ++ cons first ] ++ map (\p -> " , " ++ cons p) rest ++ [ " ]" ] ) where (first:rest) = concatMap desugarVectorSpec (filter is_primop entries) mIN_VECTOR_UNIQUE :: Int mIN_VECTOR_UNIQUE = 300 gen_primop_vector_uniques :: Info -> String gen_primop_vector_uniques (Info _ entries) = unlines $ concatMap mkVecUnique (specs `zip` [mIN_VECTOR_UNIQUE..]) where specs = concatMap desugarVectorSpec (filter is_vector (filter is_primtype entries)) mkVecUnique :: (Entry, Int) -> [String] mkVecUnique (i, unique) = [ key_id ++ " :: Unique" , key_id ++ " = mkPreludeTyConUnique " ++ show unique ] where key_id = prefix i ++ "PrimTyConKey" gen_primop_vector_tys :: Info -> String gen_primop_vector_tys (Info _ entries) = unlines $ concatMap mkVecTypes specs where specs = concatMap desugarVectorSpec (filter is_vector (filter is_primtype entries)) mkVecTypes :: Entry -> [String] mkVecTypes i = [ name_id ++ " :: Name" , name_id ++ " = mkPrimTc (fsLit \"" ++ pprTy (ty i) ++ "\") " ++ key_id ++ " " ++ tycon_id , ty_id ++ " :: Type" , ty_id ++ " = mkTyConTy " ++ tycon_id , tycon_id ++ " :: TyCon" , tycon_id ++ " = pcPrimTyCon0 " ++ name_id ++ " (VecRep " ++ show (veclen i) ++ " " ++ elemrep i ++ ")" ] where key_id = prefix i ++ "PrimTyConKey" name_id = prefix i ++ "PrimTyConName" ty_id = prefix i ++ "PrimTy" tycon_id = prefix i ++ "PrimTyCon" gen_primop_vector_tys_exports :: Info -> String gen_primop_vector_tys_exports (Info _ entries) = unlines $ map mkVecTypes specs where specs = concatMap desugarVectorSpec (filter is_vector (filter is_primtype entries)) mkVecTypes :: Entry -> String mkVecTypes i = " " ++ ty_id ++ ", " ++ tycon_id ++ "," where ty_id = prefix i ++ "PrimTy" tycon_id = prefix i ++ "PrimTyCon" gen_primop_vector_tycons :: Info -> String gen_primop_vector_tycons (Info _ entries) = unlines $ map mkVecTypes specs where specs = concatMap desugarVectorSpec (filter is_vector (filter is_primtype entries)) mkVecTypes :: Entry -> String mkVecTypes i = " , " ++ tycon_id where tycon_id = prefix i ++ "PrimTyCon" gen_primop_tag :: Info -> String gen_primop_tag (Info _ entries) = unlines (max_def_type : max_def : tagOf_type : zipWith f primop_entries [1 :: Int ..]) where primop_entries = concatMap desugarVectorSpec $ filter is_primop entries tagOf_type = "primOpTag :: PrimOp -> Int" f i n = "primOpTag " ++ cons i ++ " = " ++ show n max_def_type = "maxPrimOpTag :: Int" max_def = "maxPrimOpTag = " ++ show (length primop_entries) gen_data_decl :: Info -> String gen_data_decl (Info _ entries) = "data PrimOp\n = " ++ head conss ++ "\n" ++ unlines (map (" | "++) (tail conss)) where conss = map genCons (filter is_primop entries) genCons :: Entry -> String genCons entry = case vecOptions entry of [] -> cons entry _ -> cons entry ++ " PrimOpVecCat Length Width" gen_switch_from_attribs :: String -> String -> Info -> String gen_switch_from_attribs attrib_name fn_name (Info defaults entries) = let defv = lookup_attrib attrib_name defaults alternatives = catMaybes (map mkAlt (filter is_primop entries)) getAltRhs (OptionFalse _) = "False" getAltRhs (OptionTrue _) = "True" getAltRhs (OptionInteger _ i) = show i getAltRhs (OptionString _ s) = s getAltRhs (OptionVector _) = "True" getAltRhs (OptionFixity mf) = show mf mkAlt po = case lookup_attrib attrib_name (opts po) of Nothing -> Nothing Just xx -> case vecOptions po of [] -> Just (fn_name ++ " " ++ cons po ++ " = " ++ getAltRhs xx) _ -> Just (fn_name ++ " (" ++ cons po ++ " _ _ _) = " ++ getAltRhs xx) in case defv of Nothing -> error ("gen_switch_from: " ++ attrib_name) Just xx -> unlines alternatives ++ fn_name ++ " _ = " ++ getAltRhs xx ++ "\n" ------------------------------------------------------------------ -- Create PrimOpInfo text from PrimOpSpecs ----------------------- ------------------------------------------------------------------ gen_primop_info :: Info -> String gen_primop_info (Info _ entries) = unlines (map mkPOItext (concatMap desugarVectorSpec (filter is_primop entries))) mkPOItext :: Entry -> String mkPOItext i = mkPOI_LHS_text i ++ mkPOI_RHS_text i mkPOI_LHS_text :: Entry -> String mkPOI_LHS_text i = "primOpInfo " ++ cons i ++ " = " mkPOI_RHS_text :: Entry -> String mkPOI_RHS_text i = case cat i of Compare -> case ty i of TyF t1 (TyF _ _) -> "mkCompare " ++ sl_name i ++ ppType t1 _ -> error "Type error in comparison op" Monadic -> case ty i of TyF t1 _ -> "mkMonadic " ++ sl_name i ++ ppType t1 _ -> error "Type error in monadic op" Dyadic -> case ty i of TyF t1 (TyF _ _) -> "mkDyadic " ++ sl_name i ++ ppType t1 _ -> error "Type error in dyadic op" GenPrimOp -> let (argTys, resTy) = flatTys (ty i) tvs = nub (tvsIn (ty i)) in "mkGenPrimOp " ++ sl_name i ++ " " ++ listify (map ppTyVar tvs) ++ " " ++ listify (map ppType argTys) ++ " " ++ "(" ++ ppType resTy ++ ")" sl_name :: Entry -> String sl_name i = "(fsLit \"" ++ name i ++ "\") " ppTyVar :: String -> String ppTyVar "a" = "alphaTyVar" ppTyVar "b" = "betaTyVar" ppTyVar "c" = "gammaTyVar" ppTyVar "s" = "deltaTyVar" ppTyVar "o" = "levity1TyVar, openAlphaTyVar" ppTyVar _ = error "Unknown type var" ppType :: Ty -> String ppType (TyApp (TyCon "Any") []) = "anyTy" ppType (TyApp (TyCon "Bool") []) = "boolTy" ppType (TyApp (TyCon "Int#") []) = "intPrimTy" ppType (TyApp (TyCon "Int32#") []) = "int32PrimTy" ppType (TyApp (TyCon "Int64#") []) = "int64PrimTy" ppType (TyApp (TyCon "Char#") []) = "charPrimTy" ppType (TyApp (TyCon "Word#") []) = "wordPrimTy" ppType (TyApp (TyCon "Word32#") []) = "word32PrimTy" ppType (TyApp (TyCon "Word64#") []) = "word64PrimTy" ppType (TyApp (TyCon "Addr#") []) = "addrPrimTy" ppType (TyApp (TyCon "Float#") []) = "floatPrimTy" ppType (TyApp (TyCon "Double#") []) = "doublePrimTy" ppType (TyApp (TyCon "ByteArray#") []) = "byteArrayPrimTy" ppType (TyApp (TyCon "RealWorld") []) = "realWorldTy" ppType (TyApp (TyCon "ThreadId#") []) = "threadIdPrimTy" ppType (TyApp (TyCon "ForeignObj#") []) = "foreignObjPrimTy" ppType (TyApp (TyCon "BCO#") []) = "bcoPrimTy" ppType (TyApp (TyCon "()") []) = "unitTy" -- unitTy is TysWiredIn's name for () ppType (TyVar "a") = "alphaTy" ppType (TyVar "b") = "betaTy" ppType (TyVar "c") = "gammaTy" ppType (TyVar "s") = "deltaTy" ppType (TyVar "o") = "openAlphaTy" ppType (TyApp (TyCon "State#") [x]) = "mkStatePrimTy " ++ ppType x ppType (TyApp (TyCon "MutVar#") [x,y]) = "mkMutVarPrimTy " ++ ppType x ++ " " ++ ppType y ppType (TyApp (TyCon "MutableArray#") [x,y]) = "mkMutableArrayPrimTy " ++ ppType x ++ " " ++ ppType y ppType (TyApp (TyCon "MutableArrayArray#") [x]) = "mkMutableArrayArrayPrimTy " ++ ppType x ppType (TyApp (TyCon "SmallMutableArray#") [x,y]) = "mkSmallMutableArrayPrimTy " ++ ppType x ++ " " ++ ppType y ppType (TyApp (TyCon "MutableByteArray#") [x]) = "mkMutableByteArrayPrimTy " ++ ppType x ppType (TyApp (TyCon "Array#") [x]) = "mkArrayPrimTy " ++ ppType x ppType (TyApp (TyCon "ArrayArray#") []) = "mkArrayArrayPrimTy" ppType (TyApp (TyCon "SmallArray#") [x]) = "mkSmallArrayPrimTy " ++ ppType x ppType (TyApp (TyCon "Weak#") [x]) = "mkWeakPrimTy " ++ ppType x ppType (TyApp (TyCon "StablePtr#") [x]) = "mkStablePtrPrimTy " ++ ppType x ppType (TyApp (TyCon "StableName#") [x]) = "mkStableNamePrimTy " ++ ppType x ppType (TyApp (TyCon "MVar#") [x,y]) = "mkMVarPrimTy " ++ ppType x ++ " " ++ ppType y ppType (TyApp (TyCon "TVar#") [x,y]) = "mkTVarPrimTy " ++ ppType x ++ " " ++ ppType y ppType (TyApp (VecTyCon _ pptc) []) = pptc ppType (TyUTup ts) = "(mkTupleTy Unboxed " ++ listify (map ppType ts) ++ ")" ppType (TyF s d) = "(mkFunTy (" ++ ppType s ++ ") (" ++ ppType d ++ "))" ppType (TyC s d) = "(mkFunTy (" ++ ppType s ++ ") (" ++ ppType d ++ "))" ppType other = error ("ppType: can't handle: " ++ show other ++ "\n") pprFixityDir :: FixityDirection -> String pprFixityDir InfixN = "infix" pprFixityDir InfixL = "infixl" pprFixityDir InfixR = "infixr" listify :: [String] -> String listify ss = "[" ++ concat (intersperse ", " ss) ++ "]" flatTys :: Ty -> ([Ty],Ty) flatTys (TyF t1 t2) = case flatTys t2 of (ts,t) -> (t1:ts,t) flatTys (TyC t1 t2) = case flatTys t2 of (ts,t) -> (t1:ts,t) flatTys other = ([],other) tvsIn :: Ty -> [TyVar] tvsIn (TyF t1 t2) = tvsIn t1 ++ tvsIn t2 tvsIn (TyC t1 t2) = tvsIn t1 ++ tvsIn t2 tvsIn (TyApp _ tys) = concatMap tvsIn tys tvsIn (TyVar tv) = [tv] tvsIn (TyUTup tys) = concatMap tvsIn tys tyconsIn :: Ty -> [TyCon] tyconsIn (TyF t1 t2) = tyconsIn t1 `union` tyconsIn t2 tyconsIn (TyC t1 t2) = tyconsIn t1 `union` tyconsIn t2 tyconsIn (TyApp tc tys) = foldr union [tc] $ map tyconsIn tys tyconsIn (TyVar _) = [] tyconsIn (TyUTup tys) = foldr union [] $ map tyconsIn tys arity :: Ty -> Int arity = length . fst . flatTys
nushio3/ghc
utils/genprimopcode/Main.hs
bsd-3-clause
36,795
0
39
14,602
9,908
4,988
4,920
686
74
{-# LANGUAGE FlexibleInstances #-} {-# OPTIONS -fno-warn-orphans #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS -fno-warn-name-shadowing #-} -- | Yesod foundation. module HL.Foundation (module HL.Static ,App(..) ,Route(..) ,Handler ,Widget ,resourcesApp ,Slug(..) ,Human(..)) where import Data.Monoid import Data.Text (pack) import HL.Static import HL.Types import Data.Text (Text) import Network.Wai.Logger import System.Log.FastLogger import Yesod import Yesod.Core.Types import Yesod.Static -- | Generate boilerplate. mkYesodData "App" $(parseRoutesFile "config/routes") -- | Don't log anything to stdout. instance Yesod App where makeLogger _ = do set <- newFileLoggerSet 1000 "/dev/null" (date,_) <- clockDateCacher return (Logger {loggerSet = set ,loggerDate = date}) instance Human (Route App) where toHuman r = case r of CommunityR -> "Community" IrcR -> "IRC" DocumentationR -> "Documentation" HomeR -> "Home" ReloadR -> "Reload" MailingListsR -> "Mailing Lists" NewsR -> "News" StaticR{} -> "Static" DownloadsR -> "Downloads" DownloadsForR os -> "Downloads for " <> toHuman os WikiR t -> "Wiki: " <> t ReportR i _ -> "Report " <> pack (show i) ReportHomeR i -> "Report " <> pack (show i) WikiHomeR{} -> "Wiki" instance Slug (Route App) where toSlug r = case r of CommunityR -> "community" IrcR -> "irc" DocumentationR -> "documentation" HomeR -> "home" ReloadR -> "reload" MailingListsR -> "mailing-lists" NewsR -> "news" StaticR{} -> "static" DownloadsR -> "downloads" WikiR{} -> "wiki" ReportR{} -> "report" ReportHomeR{} -> "report" WikiHomeR{} -> "wiki" DownloadsForR{} -> "downloads"
chrisdone/hl
src/HL/Foundation.hs
bsd-3-clause
2,081
0
12
646
503
269
234
66
0
module Records where import GHC.CString -- This import interprets Strings as constants! import DataBase data Value = I Int {-@ rec :: {v:Dict <{\x y -> true}> String Value | listElts (ddom v) ~~ (Set_sng "bar")} @-} rec :: Dict String Value rec = ("foo" := I 8) += empty unsafe :: Dict String Value unsafe = ("bar" := I 8) += empty
Kyly/liquidhaskell
benchmarks/icfp15/neg/Records.hs
bsd-3-clause
344
0
8
75
81
45
36
8
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.Redshift.CopyClusterSnapshot -- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Copies the specified automated cluster snapshot to a new manual cluster -- snapshot. The source must be an automated snapshot and it must be in the -- available state. -- -- When you delete a cluster, Amazon Redshift deletes any automated snapshots -- of the cluster. Also, when the retention period of the snapshot expires, -- Amazon Redshift automatically deletes it. If you want to keep an automated -- snapshot for a longer period, you can make a manual copy of the snapshot. -- Manual snapshots are retained until you delete them. -- -- For more information about working with snapshots, go to <http://docs.aws.amazon.com/redshift/latest/mgmt/working-with-snapshots.html Amazon RedshiftSnapshots> in the /Amazon Redshift Cluster Management Guide/. -- -- <http://docs.aws.amazon.com/redshift/latest/APIReference/API_CopyClusterSnapshot.html> module Network.AWS.Redshift.CopyClusterSnapshot ( -- * Request CopyClusterSnapshot -- ** Request constructor , copyClusterSnapshot -- ** Request lenses , ccsSourceSnapshotClusterIdentifier , ccsSourceSnapshotIdentifier , ccsTargetSnapshotIdentifier -- * Response , CopyClusterSnapshotResponse -- ** Response constructor , copyClusterSnapshotResponse -- ** Response lenses , ccsrSnapshot ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.Redshift.Types import qualified GHC.Exts data CopyClusterSnapshot = CopyClusterSnapshot { _ccsSourceSnapshotClusterIdentifier :: Maybe Text , _ccsSourceSnapshotIdentifier :: Text , _ccsTargetSnapshotIdentifier :: Text } deriving (Eq, Ord, Read, Show) -- | 'CopyClusterSnapshot' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ccsSourceSnapshotClusterIdentifier' @::@ 'Maybe' 'Text' -- -- * 'ccsSourceSnapshotIdentifier' @::@ 'Text' -- -- * 'ccsTargetSnapshotIdentifier' @::@ 'Text' -- copyClusterSnapshot :: Text -- ^ 'ccsSourceSnapshotIdentifier' -> Text -- ^ 'ccsTargetSnapshotIdentifier' -> CopyClusterSnapshot copyClusterSnapshot p1 p2 = CopyClusterSnapshot { _ccsSourceSnapshotIdentifier = p1 , _ccsTargetSnapshotIdentifier = p2 , _ccsSourceSnapshotClusterIdentifier = Nothing } -- | The identifier of the cluster the source snapshot was created from. This -- parameter is required if your IAM user has a policy containing a snapshot -- resource element that specifies anything other than * for the cluster name. -- -- Constraints: -- -- Must be the identifier for a valid cluster. ccsSourceSnapshotClusterIdentifier :: Lens' CopyClusterSnapshot (Maybe Text) ccsSourceSnapshotClusterIdentifier = lens _ccsSourceSnapshotClusterIdentifier (\s a -> s { _ccsSourceSnapshotClusterIdentifier = a }) -- | The identifier for the source snapshot. -- -- Constraints: -- -- Must be the identifier for a valid automated snapshot whose state is 'available'. ccsSourceSnapshotIdentifier :: Lens' CopyClusterSnapshot Text ccsSourceSnapshotIdentifier = lens _ccsSourceSnapshotIdentifier (\s a -> s { _ccsSourceSnapshotIdentifier = a }) -- | The identifier given to the new manual snapshot. -- -- Constraints: -- -- Cannot be null, empty, or blank. Must contain from 1 to 255 alphanumeric -- characters or hyphens. First character must be a letter. Cannot end with a -- hyphen or contain two consecutive hyphens. Must be unique for the AWS account -- that is making the request. ccsTargetSnapshotIdentifier :: Lens' CopyClusterSnapshot Text ccsTargetSnapshotIdentifier = lens _ccsTargetSnapshotIdentifier (\s a -> s { _ccsTargetSnapshotIdentifier = a }) newtype CopyClusterSnapshotResponse = CopyClusterSnapshotResponse { _ccsrSnapshot :: Maybe Snapshot } deriving (Eq, Read, Show) -- | 'CopyClusterSnapshotResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ccsrSnapshot' @::@ 'Maybe' 'Snapshot' -- copyClusterSnapshotResponse :: CopyClusterSnapshotResponse copyClusterSnapshotResponse = CopyClusterSnapshotResponse { _ccsrSnapshot = Nothing } ccsrSnapshot :: Lens' CopyClusterSnapshotResponse (Maybe Snapshot) ccsrSnapshot = lens _ccsrSnapshot (\s a -> s { _ccsrSnapshot = a }) instance ToPath CopyClusterSnapshot where toPath = const "/" instance ToQuery CopyClusterSnapshot where toQuery CopyClusterSnapshot{..} = mconcat [ "SourceSnapshotClusterIdentifier" =? _ccsSourceSnapshotClusterIdentifier , "SourceSnapshotIdentifier" =? _ccsSourceSnapshotIdentifier , "TargetSnapshotIdentifier" =? _ccsTargetSnapshotIdentifier ] instance ToHeaders CopyClusterSnapshot instance AWSRequest CopyClusterSnapshot where type Sv CopyClusterSnapshot = Redshift type Rs CopyClusterSnapshot = CopyClusterSnapshotResponse request = post "CopyClusterSnapshot" response = xmlResponse instance FromXML CopyClusterSnapshotResponse where parseXML = withElement "CopyClusterSnapshotResult" $ \x -> CopyClusterSnapshotResponse <$> x .@? "Snapshot"
romanb/amazonka
amazonka-redshift/gen/Network/AWS/Redshift/CopyClusterSnapshot.hs
mpl-2.0
6,175
0
9
1,190
584
364
220
72
1
module Main where import System.Directory (findExecutable) import System.Exit (exitFailure) import System.IO import qualified CommandLine.Arguments as Arguments import qualified Manager main :: IO () main = do requireGit manager <- Arguments.parse env <- Manager.defaultEnvironment result <- Manager.run env manager case result of Right () -> return () Left err -> errExit ("\nError: " ++ err ++ newline) where newline = if last err == '\n' then "" else "\n" errExit :: String -> IO () errExit msg = do hPutStrLn stderr msg exitFailure requireGit :: IO () requireGit = do maybePath <- findExecutable "git" case maybePath of Just _ -> return () Nothing -> errExit gitNotInstalledMessage where gitNotInstalledMessage = "\n\ \elm-package relies on git to download libraries and manage versions.\n\ \ It appears that you do not have git installed though!\n\ \ Get it from <http://git-scm.com/downloads> to continue."
laszlopandy/elm-package
src/Main.hs
bsd-3-clause
1,090
0
14
314
254
127
127
30
3
#!/usr/bin/env runhaskell module Main (main) where import Distribution.Simple main :: IO () main = defaultMain
tkonolige/dbignore
bytestring-trie/Setup.hs
bsd-3-clause
114
0
6
18
30
18
12
4
1
module Test7 where -- uses a variable in the lhs of f which is not used f x y = y + 1 g = 1 + 1
SAdams601/HaRe
old/testing/refacFunDef/Test7.hs
bsd-3-clause
101
0
5
33
28
16
12
3
1
module LiftOneLevel.WhereIn1 where --A definition can be lifted from a where or let to the top level binding group. --Lifting a definition widens the scope of the definition. --In this example, lift 'sq' in 'sumSquares' --This example aims to test add parameters to 'sq'. sumSquares x y = sq x + sq y where sq 0 = 0 sq z = z^pow pow=2 anotherFun 0 y = sq y where sq x = x^2
RefactoringTools/HaRe
test/testdata/LiftOneLevel/WhereIn1.hs
bsd-3-clause
445
0
7
145
84
44
40
7
2
----------------------------------------------------------------------------- -- -- Pretty-printing assembly language -- -- (c) The University of Glasgow 1993-2005 -- ----------------------------------------------------------------------------- {-# OPTIONS_GHC -fno-warn-orphans #-} module PPC.Ppr ( pprNatCmmDecl, pprBasicBlock, pprSectionHeader, pprData, pprInstr, pprSize, pprImm, pprDataItem, ) where import PPC.Regs import PPC.Instr import PPC.Cond import PprBase import Instruction import Size import Reg import RegClass import TargetReg import Cmm hiding (topInfoTable) import BlockId import CLabel import Unique ( pprUnique, Uniquable(..) ) import Platform import FastString import Outputable import Data.Word import Data.Bits -- ----------------------------------------------------------------------------- -- Printing this stuff out pprNatCmmDecl :: NatCmmDecl CmmStatics Instr -> SDoc pprNatCmmDecl (CmmData section dats) = pprSectionHeader section $$ pprDatas dats pprNatCmmDecl proc@(CmmProc top_info lbl _ (ListGraph blocks)) = case topInfoTable proc of Nothing -> case blocks of [] -> -- special case for split markers: pprLabel lbl blocks -> -- special case for code without info table: pprSectionHeader Text $$ pprLabel lbl $$ -- blocks guaranteed not null, so label needed vcat (map (pprBasicBlock top_info) blocks) Just (Statics info_lbl _) -> sdocWithPlatform $ \platform -> (if platformHasSubsectionsViaSymbols platform then pprSectionHeader Text $$ ppr (mkDeadStripPreventer info_lbl) <> char ':' else empty) $$ vcat (map (pprBasicBlock top_info) blocks) $$ -- above: Even the first block gets a label, because with branch-chain -- elimination, it might be the target of a goto. (if platformHasSubsectionsViaSymbols platform then -- If we are using the .subsections_via_symbols directive -- (available on recent versions of Darwin), -- we have to make sure that there is some kind of reference -- from the entry code to a label on the _top_ of of the info table, -- so that the linker will not think it is unreferenced and dead-strip -- it. That's why the label is called a DeadStripPreventer (_dsp). text "\t.long " <+> ppr info_lbl <+> char '-' <+> ppr (mkDeadStripPreventer info_lbl) else empty) pprBasicBlock :: BlockEnv CmmStatics -> NatBasicBlock Instr -> SDoc pprBasicBlock info_env (BasicBlock blockid instrs) = maybe_infotable $$ pprLabel (mkAsmTempLabel (getUnique blockid)) $$ vcat (map pprInstr instrs) where maybe_infotable = case mapLookup blockid info_env of Nothing -> empty Just (Statics info_lbl info) -> pprSectionHeader Text $$ vcat (map pprData info) $$ pprLabel info_lbl pprDatas :: CmmStatics -> SDoc pprDatas (Statics lbl dats) = vcat (pprLabel lbl : map pprData dats) pprData :: CmmStatic -> SDoc pprData (CmmString str) = pprASCII str pprData (CmmUninitialised bytes) = keyword <> int bytes where keyword = sdocWithPlatform $ \platform -> case platformOS platform of OSDarwin -> ptext (sLit ".space ") _ -> ptext (sLit ".skip ") pprData (CmmStaticLit lit) = pprDataItem lit pprGloblDecl :: CLabel -> SDoc pprGloblDecl lbl | not (externallyVisibleCLabel lbl) = empty | otherwise = ptext (sLit ".globl ") <> ppr lbl pprTypeAndSizeDecl :: CLabel -> SDoc pprTypeAndSizeDecl lbl = sdocWithPlatform $ \platform -> if platformOS platform == OSLinux && externallyVisibleCLabel lbl then ptext (sLit ".type ") <> ppr lbl <> ptext (sLit ", @object") else empty pprLabel :: CLabel -> SDoc pprLabel lbl = pprGloblDecl lbl $$ pprTypeAndSizeDecl lbl $$ (ppr lbl <> char ':') pprASCII :: [Word8] -> SDoc pprASCII str = vcat (map do1 str) $$ do1 0 where do1 :: Word8 -> SDoc do1 w = ptext (sLit "\t.byte\t") <> int (fromIntegral w) -- ----------------------------------------------------------------------------- -- pprInstr: print an 'Instr' instance Outputable Instr where ppr instr = pprInstr instr pprReg :: Reg -> SDoc pprReg r = case r of RegReal (RealRegSingle i) -> ppr_reg_no i RegReal (RealRegPair{}) -> panic "PPC.pprReg: no reg pairs on this arch" RegVirtual (VirtualRegI u) -> text "%vI_" <> pprUnique u RegVirtual (VirtualRegHi u) -> text "%vHi_" <> pprUnique u RegVirtual (VirtualRegF u) -> text "%vF_" <> pprUnique u RegVirtual (VirtualRegD u) -> text "%vD_" <> pprUnique u RegVirtual (VirtualRegSSE u) -> text "%vSSE_" <> pprUnique u where ppr_reg_no :: Int -> SDoc ppr_reg_no i = sdocWithPlatform $ \platform -> case platformOS platform of OSDarwin -> ptext (case i of { 0 -> sLit "r0"; 1 -> sLit "r1"; 2 -> sLit "r2"; 3 -> sLit "r3"; 4 -> sLit "r4"; 5 -> sLit "r5"; 6 -> sLit "r6"; 7 -> sLit "r7"; 8 -> sLit "r8"; 9 -> sLit "r9"; 10 -> sLit "r10"; 11 -> sLit "r11"; 12 -> sLit "r12"; 13 -> sLit "r13"; 14 -> sLit "r14"; 15 -> sLit "r15"; 16 -> sLit "r16"; 17 -> sLit "r17"; 18 -> sLit "r18"; 19 -> sLit "r19"; 20 -> sLit "r20"; 21 -> sLit "r21"; 22 -> sLit "r22"; 23 -> sLit "r23"; 24 -> sLit "r24"; 25 -> sLit "r25"; 26 -> sLit "r26"; 27 -> sLit "r27"; 28 -> sLit "r28"; 29 -> sLit "r29"; 30 -> sLit "r30"; 31 -> sLit "r31"; 32 -> sLit "f0"; 33 -> sLit "f1"; 34 -> sLit "f2"; 35 -> sLit "f3"; 36 -> sLit "f4"; 37 -> sLit "f5"; 38 -> sLit "f6"; 39 -> sLit "f7"; 40 -> sLit "f8"; 41 -> sLit "f9"; 42 -> sLit "f10"; 43 -> sLit "f11"; 44 -> sLit "f12"; 45 -> sLit "f13"; 46 -> sLit "f14"; 47 -> sLit "f15"; 48 -> sLit "f16"; 49 -> sLit "f17"; 50 -> sLit "f18"; 51 -> sLit "f19"; 52 -> sLit "f20"; 53 -> sLit "f21"; 54 -> sLit "f22"; 55 -> sLit "f23"; 56 -> sLit "f24"; 57 -> sLit "f25"; 58 -> sLit "f26"; 59 -> sLit "f27"; 60 -> sLit "f28"; 61 -> sLit "f29"; 62 -> sLit "f30"; 63 -> sLit "f31"; _ -> sLit "very naughty powerpc register" }) _ | i <= 31 -> int i -- GPRs | i <= 63 -> int (i-32) -- FPRs | otherwise -> ptext (sLit "very naughty powerpc register") pprSize :: Size -> SDoc pprSize x = ptext (case x of II8 -> sLit "b" II16 -> sLit "h" II32 -> sLit "w" FF32 -> sLit "fs" FF64 -> sLit "fd" _ -> panic "PPC.Ppr.pprSize: no match") pprCond :: Cond -> SDoc pprCond c = ptext (case c of { ALWAYS -> sLit ""; EQQ -> sLit "eq"; NE -> sLit "ne"; LTT -> sLit "lt"; GE -> sLit "ge"; GTT -> sLit "gt"; LE -> sLit "le"; LU -> sLit "lt"; GEU -> sLit "ge"; GU -> sLit "gt"; LEU -> sLit "le"; }) pprImm :: Imm -> SDoc pprImm (ImmInt i) = int i pprImm (ImmInteger i) = integer i pprImm (ImmCLbl l) = ppr l pprImm (ImmIndex l i) = ppr l <> char '+' <> int i pprImm (ImmLit s) = s pprImm (ImmFloat _) = ptext (sLit "naughty float immediate") pprImm (ImmDouble _) = ptext (sLit "naughty double immediate") pprImm (ImmConstantSum a b) = pprImm a <> char '+' <> pprImm b pprImm (ImmConstantDiff a b) = pprImm a <> char '-' <> lparen <> pprImm b <> rparen pprImm (LO i) = sdocWithPlatform $ \platform -> if platformOS platform == OSDarwin then hcat [ text "lo16(", pprImm i, rparen ] else pprImm i <> text "@l" pprImm (HI i) = sdocWithPlatform $ \platform -> if platformOS platform == OSDarwin then hcat [ text "hi16(", pprImm i, rparen ] else pprImm i <> text "@h" pprImm (HA i) = sdocWithPlatform $ \platform -> if platformOS platform == OSDarwin then hcat [ text "ha16(", pprImm i, rparen ] else pprImm i <> text "@ha" pprAddr :: AddrMode -> SDoc pprAddr (AddrRegReg r1 r2) = pprReg r1 <+> ptext (sLit ", ") <+> pprReg r2 pprAddr (AddrRegImm r1 (ImmInt i)) = hcat [ int i, char '(', pprReg r1, char ')' ] pprAddr (AddrRegImm r1 (ImmInteger i)) = hcat [ integer i, char '(', pprReg r1, char ')' ] pprAddr (AddrRegImm r1 imm) = hcat [ pprImm imm, char '(', pprReg r1, char ')' ] pprSectionHeader :: Section -> SDoc pprSectionHeader seg = sdocWithPlatform $ \platform -> let osDarwin = platformOS platform == OSDarwin in case seg of Text -> ptext (sLit ".text\n.align 2") Data -> ptext (sLit ".data\n.align 2") ReadOnlyData | osDarwin -> ptext (sLit ".const\n.align 2") | otherwise -> ptext (sLit ".section .rodata\n\t.align 2") RelocatableReadOnlyData | osDarwin -> ptext (sLit ".const_data\n.align 2") | otherwise -> ptext (sLit ".data\n\t.align 2") UninitialisedData | osDarwin -> ptext (sLit ".const_data\n.align 2") | otherwise -> ptext (sLit ".section .bss\n\t.align 2") ReadOnlyData16 | osDarwin -> ptext (sLit ".const\n.align 4") | otherwise -> ptext (sLit ".section .rodata\n\t.align 4") OtherSection _ -> panic "PprMach.pprSectionHeader: unknown section" pprDataItem :: CmmLit -> SDoc pprDataItem lit = sdocWithDynFlags $ \dflags -> vcat (ppr_item (cmmTypeSize $ cmmLitType dflags lit) lit) where imm = litToImm lit ppr_item II8 _ = [ptext (sLit "\t.byte\t") <> pprImm imm] ppr_item II32 _ = [ptext (sLit "\t.long\t") <> pprImm imm] ppr_item FF32 (CmmFloat r _) = let bs = floatToBytes (fromRational r) in map (\b -> ptext (sLit "\t.byte\t") <> pprImm (ImmInt b)) bs ppr_item FF64 (CmmFloat r _) = let bs = doubleToBytes (fromRational r) in map (\b -> ptext (sLit "\t.byte\t") <> pprImm (ImmInt b)) bs ppr_item II16 _ = [ptext (sLit "\t.short\t") <> pprImm imm] ppr_item II64 (CmmInt x _) = [ptext (sLit "\t.long\t") <> int (fromIntegral (fromIntegral (x `shiftR` 32) :: Word32)), ptext (sLit "\t.long\t") <> int (fromIntegral (fromIntegral x :: Word32))] ppr_item _ _ = panic "PPC.Ppr.pprDataItem: no match" pprInstr :: Instr -> SDoc pprInstr (COMMENT _) = empty -- nuke 'em {- pprInstr (COMMENT s) = if platformOS platform == OSLinux then ptext (sLit "# ") <> ftext s else ptext (sLit "; ") <> ftext s -} pprInstr (DELTA d) = pprInstr (COMMENT (mkFastString ("\tdelta = " ++ show d))) pprInstr (NEWBLOCK _) = panic "PprMach.pprInstr: NEWBLOCK" pprInstr (LDATA _ _) = panic "PprMach.pprInstr: LDATA" {- pprInstr (SPILL reg slot) = hcat [ ptext (sLit "\tSPILL"), char '\t', pprReg reg, comma, ptext (sLit "SLOT") <> parens (int slot)] pprInstr (RELOAD slot reg) = hcat [ ptext (sLit "\tRELOAD"), char '\t', ptext (sLit "SLOT") <> parens (int slot), comma, pprReg reg] -} pprInstr (LD sz reg addr) = hcat [ char '\t', ptext (sLit "l"), ptext (case sz of II8 -> sLit "bz" II16 -> sLit "hz" II32 -> sLit "wz" FF32 -> sLit "fs" FF64 -> sLit "fd" _ -> panic "PPC.Ppr.pprInstr: no match" ), case addr of AddrRegImm _ _ -> empty AddrRegReg _ _ -> char 'x', char '\t', pprReg reg, ptext (sLit ", "), pprAddr addr ] pprInstr (LA sz reg addr) = hcat [ char '\t', ptext (sLit "l"), ptext (case sz of II8 -> sLit "ba" II16 -> sLit "ha" II32 -> sLit "wa" FF32 -> sLit "fs" FF64 -> sLit "fd" _ -> panic "PPC.Ppr.pprInstr: no match" ), case addr of AddrRegImm _ _ -> empty AddrRegReg _ _ -> char 'x', char '\t', pprReg reg, ptext (sLit ", "), pprAddr addr ] pprInstr (ST sz reg addr) = hcat [ char '\t', ptext (sLit "st"), pprSize sz, case addr of AddrRegImm _ _ -> empty AddrRegReg _ _ -> char 'x', char '\t', pprReg reg, ptext (sLit ", "), pprAddr addr ] pprInstr (STU sz reg addr) = hcat [ char '\t', ptext (sLit "st"), pprSize sz, ptext (sLit "u\t"), case addr of AddrRegImm _ _ -> empty AddrRegReg _ _ -> char 'x', pprReg reg, ptext (sLit ", "), pprAddr addr ] pprInstr (LIS reg imm) = hcat [ char '\t', ptext (sLit "lis"), char '\t', pprReg reg, ptext (sLit ", "), pprImm imm ] pprInstr (LI reg imm) = hcat [ char '\t', ptext (sLit "li"), char '\t', pprReg reg, ptext (sLit ", "), pprImm imm ] pprInstr (MR reg1 reg2) | reg1 == reg2 = empty | otherwise = hcat [ char '\t', sdocWithPlatform $ \platform -> case targetClassOfReg platform reg1 of RcInteger -> ptext (sLit "mr") _ -> ptext (sLit "fmr"), char '\t', pprReg reg1, ptext (sLit ", "), pprReg reg2 ] pprInstr (CMP sz reg ri) = hcat [ char '\t', op, char '\t', pprReg reg, ptext (sLit ", "), pprRI ri ] where op = hcat [ ptext (sLit "cmp"), pprSize sz, case ri of RIReg _ -> empty RIImm _ -> char 'i' ] pprInstr (CMPL sz reg ri) = hcat [ char '\t', op, char '\t', pprReg reg, ptext (sLit ", "), pprRI ri ] where op = hcat [ ptext (sLit "cmpl"), pprSize sz, case ri of RIReg _ -> empty RIImm _ -> char 'i' ] pprInstr (BCC cond blockid) = hcat [ char '\t', ptext (sLit "b"), pprCond cond, char '\t', ppr lbl ] where lbl = mkAsmTempLabel (getUnique blockid) pprInstr (BCCFAR cond blockid) = vcat [ hcat [ ptext (sLit "\tb"), pprCond (condNegate cond), ptext (sLit "\t$+8") ], hcat [ ptext (sLit "\tb\t"), ppr lbl ] ] where lbl = mkAsmTempLabel (getUnique blockid) pprInstr (JMP lbl) = hcat [ -- an alias for b that takes a CLabel char '\t', ptext (sLit "b"), char '\t', ppr lbl ] pprInstr (MTCTR reg) = hcat [ char '\t', ptext (sLit "mtctr"), char '\t', pprReg reg ] pprInstr (BCTR _ _) = hcat [ char '\t', ptext (sLit "bctr") ] pprInstr (BL lbl _) = hcat [ ptext (sLit "\tbl\t"), ppr lbl ] pprInstr (BCTRL _) = hcat [ char '\t', ptext (sLit "bctrl") ] pprInstr (ADD reg1 reg2 ri) = pprLogic (sLit "add") reg1 reg2 ri pprInstr (ADDIS reg1 reg2 imm) = hcat [ char '\t', ptext (sLit "addis"), char '\t', pprReg reg1, ptext (sLit ", "), pprReg reg2, ptext (sLit ", "), pprImm imm ] pprInstr (ADDC reg1 reg2 reg3) = pprLogic (sLit "addc") reg1 reg2 (RIReg reg3) pprInstr (ADDE reg1 reg2 reg3) = pprLogic (sLit "adde") reg1 reg2 (RIReg reg3) pprInstr (SUBF reg1 reg2 reg3) = pprLogic (sLit "subf") reg1 reg2 (RIReg reg3) pprInstr (MULLW reg1 reg2 ri@(RIReg _)) = pprLogic (sLit "mullw") reg1 reg2 ri pprInstr (MULLW reg1 reg2 ri@(RIImm _)) = pprLogic (sLit "mull") reg1 reg2 ri pprInstr (DIVW reg1 reg2 reg3) = pprLogic (sLit "divw") reg1 reg2 (RIReg reg3) pprInstr (DIVWU reg1 reg2 reg3) = pprLogic (sLit "divwu") reg1 reg2 (RIReg reg3) pprInstr (MULLW_MayOflo reg1 reg2 reg3) = vcat [ hcat [ ptext (sLit "\tmullwo\t"), pprReg reg1, ptext (sLit ", "), pprReg reg2, ptext (sLit ", "), pprReg reg3 ], hcat [ ptext (sLit "\tmfxer\t"), pprReg reg1 ], hcat [ ptext (sLit "\trlwinm\t"), pprReg reg1, ptext (sLit ", "), pprReg reg1, ptext (sLit ", "), ptext (sLit "2, 31, 31") ] ] -- for some reason, "andi" doesn't exist. -- we'll use "andi." instead. pprInstr (AND reg1 reg2 (RIImm imm)) = hcat [ char '\t', ptext (sLit "andi."), char '\t', pprReg reg1, ptext (sLit ", "), pprReg reg2, ptext (sLit ", "), pprImm imm ] pprInstr (AND reg1 reg2 ri) = pprLogic (sLit "and") reg1 reg2 ri pprInstr (OR reg1 reg2 ri) = pprLogic (sLit "or") reg1 reg2 ri pprInstr (XOR reg1 reg2 ri) = pprLogic (sLit "xor") reg1 reg2 ri pprInstr (XORIS reg1 reg2 imm) = hcat [ char '\t', ptext (sLit "xoris"), char '\t', pprReg reg1, ptext (sLit ", "), pprReg reg2, ptext (sLit ", "), pprImm imm ] pprInstr (EXTS sz reg1 reg2) = hcat [ char '\t', ptext (sLit "exts"), pprSize sz, char '\t', pprReg reg1, ptext (sLit ", "), pprReg reg2 ] pprInstr (NEG reg1 reg2) = pprUnary (sLit "neg") reg1 reg2 pprInstr (NOT reg1 reg2) = pprUnary (sLit "not") reg1 reg2 pprInstr (SLW reg1 reg2 ri) = pprLogic (sLit "slw") reg1 reg2 (limitShiftRI ri) pprInstr (SRW reg1 reg2 (RIImm (ImmInt i))) | i > 31 || i < 0 = -- Handle the case where we are asked to shift a 32 bit register by -- less than zero or more than 31 bits. We convert this into a clear -- of the destination register. -- Fixes ticket http://ghc.haskell.org/trac/ghc/ticket/5900 pprInstr (XOR reg1 reg2 (RIReg reg2)) pprInstr (SRW reg1 reg2 ri) = pprLogic (sLit "srw") reg1 reg2 (limitShiftRI ri) pprInstr (SRAW reg1 reg2 ri) = pprLogic (sLit "sraw") reg1 reg2 (limitShiftRI ri) pprInstr (RLWINM reg1 reg2 sh mb me) = hcat [ ptext (sLit "\trlwinm\t"), pprReg reg1, ptext (sLit ", "), pprReg reg2, ptext (sLit ", "), int sh, ptext (sLit ", "), int mb, ptext (sLit ", "), int me ] pprInstr (FADD sz reg1 reg2 reg3) = pprBinaryF (sLit "fadd") sz reg1 reg2 reg3 pprInstr (FSUB sz reg1 reg2 reg3) = pprBinaryF (sLit "fsub") sz reg1 reg2 reg3 pprInstr (FMUL sz reg1 reg2 reg3) = pprBinaryF (sLit "fmul") sz reg1 reg2 reg3 pprInstr (FDIV sz reg1 reg2 reg3) = pprBinaryF (sLit "fdiv") sz reg1 reg2 reg3 pprInstr (FNEG reg1 reg2) = pprUnary (sLit "fneg") reg1 reg2 pprInstr (FCMP reg1 reg2) = hcat [ char '\t', ptext (sLit "fcmpu\tcr0, "), -- Note: we're using fcmpu, not fcmpo -- The difference is with fcmpo, compare with NaN is an invalid operation. -- We don't handle invalid fp ops, so we don't care pprReg reg1, ptext (sLit ", "), pprReg reg2 ] pprInstr (FCTIWZ reg1 reg2) = pprUnary (sLit "fctiwz") reg1 reg2 pprInstr (FRSP reg1 reg2) = pprUnary (sLit "frsp") reg1 reg2 pprInstr (CRNOR dst src1 src2) = hcat [ ptext (sLit "\tcrnor\t"), int dst, ptext (sLit ", "), int src1, ptext (sLit ", "), int src2 ] pprInstr (MFCR reg) = hcat [ char '\t', ptext (sLit "mfcr"), char '\t', pprReg reg ] pprInstr (MFLR reg) = hcat [ char '\t', ptext (sLit "mflr"), char '\t', pprReg reg ] pprInstr (FETCHPC reg) = vcat [ ptext (sLit "\tbcl\t20,31,1f"), hcat [ ptext (sLit "1:\tmflr\t"), pprReg reg ] ] pprInstr LWSYNC = ptext (sLit "\tlwsync") -- pprInstr _ = panic "pprInstr (ppc)" pprLogic :: LitString -> Reg -> Reg -> RI -> SDoc pprLogic op reg1 reg2 ri = hcat [ char '\t', ptext op, case ri of RIReg _ -> empty RIImm _ -> char 'i', char '\t', pprReg reg1, ptext (sLit ", "), pprReg reg2, ptext (sLit ", "), pprRI ri ] pprUnary :: LitString -> Reg -> Reg -> SDoc pprUnary op reg1 reg2 = hcat [ char '\t', ptext op, char '\t', pprReg reg1, ptext (sLit ", "), pprReg reg2 ] pprBinaryF :: LitString -> Size -> Reg -> Reg -> Reg -> SDoc pprBinaryF op sz reg1 reg2 reg3 = hcat [ char '\t', ptext op, pprFSize sz, char '\t', pprReg reg1, ptext (sLit ", "), pprReg reg2, ptext (sLit ", "), pprReg reg3 ] pprRI :: RI -> SDoc pprRI (RIReg r) = pprReg r pprRI (RIImm r) = pprImm r pprFSize :: Size -> SDoc pprFSize FF64 = empty pprFSize FF32 = char 's' pprFSize _ = panic "PPC.Ppr.pprFSize: no match" -- limit immediate argument for shift instruction to range 0..31 limitShiftRI :: RI -> RI limitShiftRI (RIImm (ImmInt i)) | i > 31 || i < 0 = panic $ "PPC.Ppr: Shift by " ++ show i ++ " bits is not allowed." limitShiftRI x = x
frantisekfarka/ghc-dsi
compiler/nativeGen/PPC/Ppr.hs
bsd-3-clause
22,463
0
18
8,045
7,215
3,552
3,663
540
72
main = print (id2 (id2 id2) (42::Int)) -- where -- id2 = s k k -- id2 x = s k k x id2 = s k k s x y z = x z (y z) k x y = x
olsner/ghc
testsuite/tests/codeGen/should_run/cgrun003.hs
bsd-3-clause
138
0
9
56
75
39
36
4
1
{-# LANGUAGE TypeFamilies #-} module T2436a( S ) where data family S a
ezyang/ghc
testsuite/tests/rename/should_compile/T2436a.hs
bsd-3-clause
72
0
4
14
15
11
4
3
0
{-# LANGUAGE FlexibleContexts #-} module GrammarParser where import Data.Char (isSpace) import Text.Parsec import Grammar grammarParser :: Stream s m Char => ParsecT s u m Grammar grammarParser = do spaces prules <- many prule eof return (Grammar prules) prule :: Stream s m Char => ParsecT s u m Production prule = do nt <- lexeme nonterminal lexeme (string "->") right <- many (lexeme (terminal <|> nonterminal)) spaces return (nt ::= right) nonterminal :: Stream s m Char => ParsecT s u m Symbol nonterminal = do symbol <- many1 (letter <|> digit <|> char '_' <|> char '\'') return (N symbol) terminal :: Stream s m Char => ParsecT s u m Symbol terminal = do char '"' symbol <- many1 ( satisfy (\x -> x /= '"' && x /= '\\' && x /= '\n') <|> (char '\\' >> ( (char '"' >> return '"') <|> (char '\\' >> return '\\')))) char '"' return (T symbol) lexeme :: Stream s m Char => ParsecT s u m b -> ParsecT s u m b lexeme p = do x <- p skipMany (satisfy (\c -> isSpace c && c /= '\n')) return x
romildo/gsynt
src/GrammarParser.hs
isc
1,209
0
18
414
480
228
252
38
1
{-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE StandaloneDeriving #-} -- | This module defines the concept of a type environment as a -- mapping from variable names to 'Type's. Convenience facilities are -- also provided to communicate that some monad or applicative functor -- maintains type information. module Futhark.Representation.AST.Attributes.Scope ( HasScope (..) , NameInfo (..) , LocalScope (..) , Scope , Scoped(..) , inScopeOf , scopeOfLParams , scopeOfFParams , scopeOfPattern , scopeOfPatElem , SameScope , castScope , castNameInfo -- * Extended type environment , ExtendedScope , extendedScope ) where import Control.Applicative import Control.Monad.Reader import qualified Control.Monad.RWS.Strict import qualified Control.Monad.RWS.Lazy import Data.List import Data.Maybe import Data.Monoid import qualified Data.Map.Strict as M import Prelude import Futhark.Representation.AST.Annotations import Futhark.Representation.AST.Syntax import Futhark.Representation.AST.Attributes.Types import Futhark.Representation.AST.Attributes.Patterns -- | How some name in scope was bound. data NameInfo lore = LetInfo (LetAttr lore) | FParamInfo (FParamAttr lore) | LParamInfo (LParamAttr lore) | IndexInfo IntType deriving instance Annotations lore => Show (NameInfo lore) instance Annotations lore => Typed (NameInfo lore) where typeOf (LetInfo attr) = typeOf attr typeOf (FParamInfo attr) = typeOf attr typeOf (LParamInfo attr) = typeOf attr typeOf (IndexInfo it) = Prim $ IntType it -- | A scope is a mapping from variable names to information about -- that name. type Scope lore = M.Map VName (NameInfo lore) -- | The class of applicative functors (or more common in practice: -- monads) that permit the lookup of variable types. A default method -- for 'lookupType' exists, which is sufficient (if not always -- maximally efficient, and using 'error' to fail) when 'askScope' -- is defined. class (Applicative m, Annotations lore) => HasScope lore m | m -> lore where -- | Return the type of the given variable, or fail if it is not in -- the type environment. lookupType :: VName -> m Type lookupType = fmap typeOf . lookupInfo -- | Return the info of the given variable, or fail if it is not in -- the type environment. lookupInfo :: VName -> m (NameInfo lore) lookupInfo name = asksScope (M.findWithDefault notFound name) where notFound = error $ "Scope.lookupInfo: Name " ++ pretty name ++ " not found in type environment." -- | Return the type environment contained in the applicative -- functor. askScope :: m (Scope lore) -- | Return the result of applying some function to the type -- environment. asksScope :: (Scope lore -> a) -> m a asksScope f = f <$> askScope instance (Applicative m, Monad m, Annotations lore) => HasScope lore (ReaderT (Scope lore) m) where askScope = ask instance (Applicative m, Monad m, Monoid w, Annotations lore) => HasScope lore (Control.Monad.RWS.Strict.RWST (Scope lore) w s m) where askScope = ask instance (Applicative m, Monad m, Monoid w, Annotations lore) => HasScope lore (Control.Monad.RWS.Lazy.RWST (Scope lore) w s m) where askScope = ask -- | The class of monads that not only provide a 'Scope', but also -- the ability to locally extend it. A 'Reader' containing a -- 'Scope' is the prototypical example of such a monad. class (HasScope lore m, Monad m) => LocalScope lore m where -- | Run a computation with an extended type environment. Note that -- this is intended to *add* to the current type environment, it -- does not replace it. localScope :: Scope lore -> m a -> m a instance (Applicative m, Monad m, Annotations lore) => LocalScope lore (ReaderT (Scope lore) m) where localScope = local . M.union instance (Applicative m, Monad m, Monoid w, Annotations lore) => LocalScope lore (Control.Monad.RWS.Strict.RWST (Scope lore) w s m) where localScope = local . M.union instance (Applicative m, Monad m, Monoid w, Annotations lore) => LocalScope lore (Control.Monad.RWS.Lazy.RWST (Scope lore) w s m) where localScope = local . M.union -- | The class of things that can provide a scope. There is no -- overarching rule for what this means. For a 'Stm', it is the -- corresponding pattern. For a 'Lambda', is is the parameters -- (including index). class Scoped lore a | a -> lore where scopeOf :: a -> Scope lore inScopeOf :: (Scoped lore a, LocalScope lore m) => a -> m b -> m b inScopeOf = localScope . scopeOf instance Scoped lore a => Scoped lore [a] where scopeOf = mconcat . map scopeOf instance Scoped lore (Stm lore) where scopeOf = scopeOfPattern . stmPattern instance Scoped lore (FunDef lore) where scopeOf = scopeOfFParams . funDefParams instance Scoped lore (VName, NameInfo lore) where scopeOf = uncurry M.singleton instance Scoped lore (LoopForm lore) where scopeOf (WhileLoop _) = mempty scopeOf (ForLoop i it _ xs) = M.insert i (IndexInfo it) $ scopeOfLParams (map fst xs) scopeOfPattern :: LetAttr lore ~ attr => PatternT attr -> Scope lore scopeOfPattern = mconcat . map scopeOfPatElem . patternElements scopeOfPatElem :: LetAttr lore ~ attr => PatElemT attr -> Scope lore scopeOfPatElem (PatElem name _ attr) = M.singleton name $ LetInfo attr scopeOfLParams :: LParamAttr lore ~ attr => [ParamT attr] -> Scope lore scopeOfLParams = M.fromList . map f where f param = (paramName param, LParamInfo $ paramAttr param) scopeOfFParams :: FParamAttr lore ~ attr => [ParamT attr] -> Scope lore scopeOfFParams = M.fromList . map f where f param = (paramName param, FParamInfo $ paramAttr param) instance Scoped lore (Lambda lore) where scopeOf lam = scopeOfLParams $ lambdaParams lam instance Scoped lore (ExtLambda lore) where scopeOf lam = scopeOfLParams $ extLambdaParams lam type SameScope lore1 lore2 = (LetAttr lore1 ~ LetAttr lore2, FParamAttr lore1 ~ FParamAttr lore2, LParamAttr lore1 ~ LParamAttr lore2) -- | If two scopes are really the same, then you can convert one to -- the other. castScope :: SameScope fromlore tolore => Scope fromlore -> Scope tolore castScope = M.map castNameInfo castNameInfo :: SameScope fromlore tolore => NameInfo fromlore -> NameInfo tolore castNameInfo (LetInfo attr) = LetInfo attr castNameInfo (FParamInfo attr) = FParamInfo attr castNameInfo (LParamInfo attr) = LParamInfo attr castNameInfo (IndexInfo it) = IndexInfo it -- | A monad transformer that carries around an extended 'Scope'. -- Its 'lookupType' method will first look in the extended 'Scope', -- and then use the 'lookupType' method of the underlying monad. newtype ExtendedScope lore m a = ExtendedScope (ReaderT (Scope lore) m a) deriving (Functor, Applicative, Monad, MonadReader (Scope lore)) instance (HasScope lore m, Monad m) => HasScope lore (ExtendedScope lore m) where lookupType name = do res <- asks $ fmap typeOf . M.lookup name maybe (ExtendedScope $ lift $ lookupType name) return res askScope = M.union <$> ask <*> ExtendedScope (lift askScope) -- | Run a computation in the extended type environment. extendedScope :: ExtendedScope lore m a -> Scope lore -> m a extendedScope (ExtendedScope m) = runReaderT m
ihc/futhark
src/Futhark/Representation/AST/Attributes/Scope.hs
isc
7,916
0
11
1,781
1,925
1,019
906
141
1
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.SVGFilterPrimitiveStandardAttributes (js_getX, getX, js_getY, getY, js_getWidth, getWidth, js_getHeight, getHeight, js_getResult, getResult, SVGFilterPrimitiveStandardAttributes, castToSVGFilterPrimitiveStandardAttributes, gTypeSVGFilterPrimitiveStandardAttributes) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSRef(..), JSString, castRef) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSRef(..), FromJSRef(..)) import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.Enums foreign import javascript unsafe "$1[\"x\"]" js_getX :: JSRef SVGFilterPrimitiveStandardAttributes -> IO (JSRef SVGAnimatedLength) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFilterPrimitiveStandardAttributes.x Mozilla SVGFilterPrimitiveStandardAttributes.x documentation> getX :: (MonadIO m) => SVGFilterPrimitiveStandardAttributes -> m (Maybe SVGAnimatedLength) getX self = liftIO ((js_getX (unSVGFilterPrimitiveStandardAttributes self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"y\"]" js_getY :: JSRef SVGFilterPrimitiveStandardAttributes -> IO (JSRef SVGAnimatedLength) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFilterPrimitiveStandardAttributes.y Mozilla SVGFilterPrimitiveStandardAttributes.y documentation> getY :: (MonadIO m) => SVGFilterPrimitiveStandardAttributes -> m (Maybe SVGAnimatedLength) getY self = liftIO ((js_getY (unSVGFilterPrimitiveStandardAttributes self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"width\"]" js_getWidth :: JSRef SVGFilterPrimitiveStandardAttributes -> IO (JSRef SVGAnimatedLength) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFilterPrimitiveStandardAttributes.width Mozilla SVGFilterPrimitiveStandardAttributes.width documentation> getWidth :: (MonadIO m) => SVGFilterPrimitiveStandardAttributes -> m (Maybe SVGAnimatedLength) getWidth self = liftIO ((js_getWidth (unSVGFilterPrimitiveStandardAttributes self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"height\"]" js_getHeight :: JSRef SVGFilterPrimitiveStandardAttributes -> IO (JSRef SVGAnimatedLength) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFilterPrimitiveStandardAttributes.height Mozilla SVGFilterPrimitiveStandardAttributes.height documentation> getHeight :: (MonadIO m) => SVGFilterPrimitiveStandardAttributes -> m (Maybe SVGAnimatedLength) getHeight self = liftIO ((js_getHeight (unSVGFilterPrimitiveStandardAttributes self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"result\"]" js_getResult :: JSRef SVGFilterPrimitiveStandardAttributes -> IO (JSRef SVGAnimatedString) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFilterPrimitiveStandardAttributes.result Mozilla SVGFilterPrimitiveStandardAttributes.result documentation> getResult :: (MonadIO m) => SVGFilterPrimitiveStandardAttributes -> m (Maybe SVGAnimatedString) getResult self = liftIO ((js_getResult (unSVGFilterPrimitiveStandardAttributes self)) >>= fromJSRef)
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/SVGFilterPrimitiveStandardAttributes.hs
mit
3,891
30
11
609
753
434
319
71
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE NoMonomorphismRestriction #-} module Network.Xmpp.Xep.Jingle where import Network.Xmpp.Xep.Jingle.Types import Control.Arrow (first) import Control.Concurrent import Control.Concurrent.STM import Control.Monad import Data.List import qualified Data.Map as Map import qualified Data.Text as Text import Data.XML.Types import Data.XML.Pickle (ppUnpickleError) import qualified Network.Xmpp as Xmpp import Network.Xmpp.Xep.Jingle.Picklers import Network.Xmpp.Xep.Jingle.Types import System.Log.Logger import System.Log.Logger (errorM, infoM, debugM) equivClasses :: (a -> a -> Bool) -> [a] -> [[a]] equivClasses p = unfoldr (\xs -> case xs of [] -> Nothing (y:ys) -> Just . first (y:) $ partition (p y) ys) serviceUnavailable :: Xmpp.StanzaError serviceUnavailable = Xmpp.StanzaError Xmpp.Cancel Xmpp.ServiceUnavailable Nothing Nothing badRequest :: Xmpp.StanzaError badRequest = Xmpp.StanzaError Xmpp.Cancel Xmpp.BadRequest Nothing Nothing dummyContentHandler :: ApplicationHandler dummyContentHandler = ApplicationHandler { chTransportType = Datagram , chNamespace = "dummycontent" , chHandler = \_ -> return () } errorUnavailable :: Xmpp.IQRequestTicket -> Xmpp.Session -> IO () errorUnavailable ticket session = void $ Xmpp.answerIQ ticket (Left serviceUnavailable) errorBadRequest :: Xmpp.IQRequestTicket -> IO () errorBadRequest ticket = void $ Xmpp.answerIQ ticket (Left badRequest) jingleTerminate reasonType sid = Jingle { action = SessionTerminate , initiator = Nothing , responder = Nothing , sid = sid , content = [] , reason = Just JingleReason { reasonType = reasonType , reasonText = Nothing , reasonElement = Nothing } , jinglePayload = [] } startJingle :: HandlerFunc -> (Xmpp.IQRequest -> IO Bool) -> Xmpp.Session -> IO (Maybe JingleHandler) startJingle handleContent policy xmppSession = do sessions <- newTVarIO Map.empty infoM "Pontarius.Xmpp.Jingle" "getting IQ channel" chan' <- Xmpp.listenIQChan Xmpp.Set "urn:xmpp:jingle:1" xmppSession case chan' of Left _ -> errorM "Pontarius.Xmpp.Jingle" "Jingle channel is already in use" >> return Nothing Right chan -> do infoM "Pontarius.Xmpp.Jingle" "Got channel, starting worker thread" thread <- forkIO . forever $ do ticket <- atomically $ readTChan chan tid <- myThreadId let request = Xmpp.iqRequestBody ticket jh = JingleHandler { jingleSessions = sessions , jingleThread = tid , jingleXmppSession = xmppSession } case unpickleElem xpJingle $ Xmpp.iqRequestPayload request of Left e -> do errorM "Pontarius.Xmpp.Jingle" $ "Could not unpickle jingle element:\n" ++ ppUnpickleError e Right ji -> case action ji of SessionInitiate -> sessionInitiate sessions ji ticket jh _ -> handleSession sessions ji ticket jh return . Just $ JingleHandler { jingleSessions = sessions , jingleThread = thread , jingleXmppSession = xmppSession } where sessionInitiate sessions ji ticket jh = do debugM "Pontarius.Xmpp.Jingle" $ "Recevied session-initiate: " ++ Text.unpack (sid ji) sess <- atomically $ readTVar sessions case Map.lookup (sid ji) sess of Nothing -> do stateRef <- newTVarIO PENDING requestsRef <- newTChanIO mbs <- newSession jh ji ticket stateRef requestsRef case mbs of Nothing -> return () Just s -> do atomically . modifyTVar sessions $ Map.insert (sSid s) s Just _ -> return () -- TODO handleSession sessions ji ticket jh = do sess <- atomically $ readTVar sessions case Map.lookup (sid ji) sess of Nothing -> do errorM "Pontarius.Xmpp.Jingle" $ "Session not found: " ++ show ( sid ji) checkPolicy ticket $ do return () -- TODO? Just session -> do debugM "Pontarius.Xmpp.Jingle" $ "Got message for session " ++ Text.unpack (sid ji) if (Xmpp.iqRequestFrom $ Xmpp.iqRequestBody ticket) == (Just $ sRemote session) then if isSessionPing ji then do Xmpp.answerIQ ticket (Right Nothing) return () else sRequests session session ticket ji else errorUnavailable ticket xmppSession checkPolicy ticket f = do answer <- policy (Xmpp.iqRequestBody ticket) if answer then f else errorUnavailable ticket xmppSession newSession jh ji ticket stateRef requestsRef = case ( Xmpp.iqRequestFrom $ Xmpp.iqRequestBody ticket) of (Just remote) -> do Xmpp.answerIQ ticket (Right Nothing) handle <- handleContent remote ji stateRef requestsRef jh case handle of Just handlerFunc -> do return . Just $ Session { sState = stateRef , sSid = sid ji , sRemote = remote , sRequests = handlerFunc } Nothing -> return Nothing -- The handler has to decline the -- session _ -> errorBadRequest ticket >> return Nothing isSessionPing Jingle{ action = SessionInfo , initiator = Nothing , responder = Nothing , content = [] , reason = Nothing } = True isSessionPing _ = False addSession :: Session -> JingleHandler -> IO Bool addSession s JingleHandler{jingleSessions = href} = atomically $ do hs <- readTVar href case Map.member (sSid s) hs of True -> return False False -> do writeTVar href $ Map.insert (sSid s) s hs return True -- | Remove session without sending session-terminate (e.g. when we received session-terminate) endSession s jh = atomically $ modifyTVar (jingleSessions jh) (Map.delete s) -- | Send session-terminate and end session terminateSession sid JingleHandler{ jingleSessions = href , jingleXmppSession = xmppSession } reason = do s <- atomically $ do sessions <- readTVar href let (s, sessions') = Map.updateLookupWithKey (\_ _ -> Nothing) sid sessions writeTVar href sessions' return s case s of Nothing -> return () Just s' -> do let terminate = Jingle { action = SessionTerminate , initiator = Nothing , responder = Nothing , sid = sSid s' , content = [] , jinglePayload = [] , reason = Just reason } terminateE = pickleElem xpJingle terminate _ <- Xmpp.sendIQ Nothing (Just $ sRemote s') Xmpp.Set Nothing terminateE xmppSession return ()
Philonous/hs-jingle
source/Network/Xmpp/Xep/Jingle.hs
mit
8,568
0
23
3,660
1,879
953
926
166
13
{-# LANGUAGE OverloadedStrings #-} module CommandSwitch ( cmdSwitch ) where import Control.Monad import Data.Char import Data.Maybe import System.Directory import System.Environment import System.Exit import Text.ParserCombinators.ReadP as P import Turtle.Prelude import qualified Data.Text as T import qualified Data.Text.IO as T import Common {- kernel info: (<item number>, (<kernel version>, <is selected>)) -} parseKernelInfo :: T.Text -> Maybe (Int, (String, Bool)) parseKernelInfo t = case readP_to_S (skipSpaces *> kernelInfoP <* P.eof) (T.unpack t) of [(r,"")] -> Just r _ -> Nothing kernelInfoP :: ReadP (Int, (String,Bool)) kernelInfoP = do w <- read <$> (P.char '[' *> munch1 isDigit <* P.char ']' <* skipSpaces) kerVer <- munch1 (not . isSpace) <* skipSpaces selected <- P.option False (True <$ P.char '*') <* skipSpaces pure (w, (kerVer, selected)) cmdSwitch :: IO () cmdSwitch = do -- get info about existing kernel versions (ExitSuccess, out) <- procStrict "eselect" ["kernel", "list"] "" let _:rawKVers = T.lines out kVers = fromJust . parseKernelInfo <$> rawKVers latestKVer = last kVers -- switch to latest (last) kernel version if we haven't done so. if snd . snd $ latestKVer then putStrLn "Skipping kernel version switch ..." else do putStrLn "Switching to latest kernel version ..." (ExitSuccess, _) <- procStrict "eselect" ["kernel", "set", T.pack . show . fst $ latestKVer] "" pure () -- copy over .config from current kernel if the file is missing cfgFileExist <- doesFileExist "/usr/src/linux/.config" unless cfgFileExist $ do putStrLn "Creating .config from current running config." (ExitSuccess, cfgContent) <- procStrict "zcat" ["/proc/config.gz"] "" T.writeFile "/usr/src/linux/.config" cfgContent pure () diveInSubshell diveInSubshell :: IO () diveInSubshell = do putStrLn "Will now switch to subshell for `make oldconfig && make` to happen." putStrLn "When done, feel free to continute with `kernel-tool install`." cd "/usr/src/linux" shBin <- getEnv "SHELL" _ <- shDive shBin [] pure ()
Javran/misc
kernel-tool/src/CommandSwitch.hs
mit
2,169
0
16
442
593
304
289
55
2
#!/usr/bin/env stack -- stack runghc --resolver lts-7.15 --install-ghc --package text --package cassava {-# LANGUAGE DeriveGeneric #-} import qualified Data.Text as T import qualified System.Environment as Env import qualified Data.Csv as Csv import Data.Csv ((.!)) import qualified Data.Vector as V import qualified Data.ByteString.Lazy as BL import GHC.Generics data SurveyFields = SurveyFields { contactDetails :: T.Text, age :: T.Text, membershipLength :: T.Text, assistantInstructor :: T.Text , otherInstuctor :: T.Text , instructorText :: T.Text } deriving (Generic, Show) instance Csv.ToNamedRecord SurveyFields instance Csv.DefaultOrdered SurveyFields instance Csv.FromRecord SurveyFields where parseRecord v = SurveyFields <$> v .! 104 <*> v .! 16 <*> v .! 15 <*> v .! 36 <*> v .! 38 <*> v .! 39 readCSVLines filePath = do csvData <- BL.readFile filePath case Csv.decode Csv.HasHeader csvData :: Either String (V.Vector SurveyFields) of Left err -> do putStrLn err return V.empty Right v -> return v filterBlankSurveyLine :: SurveyFields -> Bool filterBlankSurveyLine survey = (T.length (assistantInstructor survey) /= 0) || (T.length (otherInstuctor survey) /= 0) || (T.length (instructorText survey) /= 0) main = do [filePath] <- Env.getArgs csvLines <- readCSVLines filePath let filteredLines = filter filterBlankSurveyLine $ V.toList csvLines BL.putStr $ Csv.encodeDefaultOrderedByName filteredLines
NickAger/SGBASurveyExtraction
extractInstructors.hs
mit
1,487
0
17
265
442
233
209
29
2
module Main where import Control.Monad (forever) import Data.Char (toLower) import Data.Maybe (isJust) import Data.List (intersperse) import System.Exit (exitSuccess) import System.Random (randomRIO) newtype WordList = WordList [String] deriving (Eq, Show) allWords :: IO WordList allWords = do dict <- readFile "data/dict.txt" return $ WordList (lines dict) minWordLength :: Int minWordLength = 5 maxWordLength :: Int maxWordLength = 9 gameWords :: IO WordList gameWords = do (WordList aw) <- allWords return $ WordList (filter gameLength aw) where gameLength w = let l = length (w :: String) in l > minWordLength && l < maxWordLength randomWord :: WordList -> IO String randomWord (WordList wl) = do randomIndex <- randomRIO (0, (length wl - 1)) return $ wl !! randomIndex randomWord' :: IO String randomWord' = gameWords >>= randomWord data Puzzle = Puzzle String [Maybe Char] [Char] instance Show Puzzle where show (Puzzle _ discovered guessed) = (intersperse ' ' $ fmap renderPuzzleChar discovered) ++ " Guessed so far: " ++ guessed renderPuzzleChar :: Maybe Char -> Char renderPuzzleChar x = case x of (Just x) -> x Nothing -> '_' freshPuzzle :: String -> Puzzle freshPuzzle word = Puzzle word (map (\x -> Nothing) word) "" charInWord :: Puzzle -> Char -> Bool charInWord (Puzzle puzzle _ _) c = elem c puzzle alreadyGuessed :: Puzzle -> Char -> Bool alreadyGuessed (Puzzle _ _ guessed) c = elem c guessed fillInCharacter :: Puzzle -> Char -> Puzzle fillInCharacter (Puzzle word filledInSoFar s) c = Puzzle word newFilledInSoFar (c : s) where zipper guessed wordChar guessChar = if wordChar == guessed then Just wordChar else guessChar newFilledInSoFar = zipWith (zipper c) word filledInSoFar handleGuess :: Puzzle -> Char -> IO Puzzle handleGuess puzzle guess = do putStrLn $ "Your guess was: " ++ [guess] case (charInWord puzzle guess, alreadyGuessed puzzle guess) of (_, True) -> do putStrLn "You already guessed that\ \ character, pick something else!" return puzzle (True, _) -> do putStrLn "This character was in the word,\ \ filling in the word accordingly" return (fillInCharacter puzzle guess) (False, _) -> do putStrLn "This character wasn't in\ \ the word, try again." return (fillInCharacter puzzle guess) gameOver :: Puzzle -> IO () gameOver (Puzzle wordToGuess _ guessed) = if (length guessed) > 7 then do putStrLn "You lose!" putStrLn $ "The word was: " ++ wordToGuess exitSuccess else return () gameWin :: Puzzle -> IO () gameWin (Puzzle _ filledInSoFar _) = if all isJust filledInSoFar then do putStrLn "You win!" exitSuccess else return () runGame :: Puzzle -> IO () runGame puzzle = forever $ do gameOver puzzle gameWin puzzle putStrLn $ "Current puzzle is: " ++ show puzzle putStr "Guess a letter: " guess <- getLine case guess of [c] -> handleGuess puzzle c >>= runGame _ -> putStrLn "Your guess must\ \ be a single character" main :: IO () main = do word <- randomWord' let puzzle = freshPuzzle (fmap toLower word) runGame puzzle
diminishedprime/.org
reading-list/haskell_programming_from_first_principles/hangman/src/Main.hs
mit
3,290
0
14
818
1,066
530
536
96
3
module AppManagedEntity.Data.Virus ( Virus(..) , VirusDiscoveredAt(..) , VirusId(..) , VirusName(..) , bpsDiscoveredAt , bpsVirusName , brnDiscoveredAt , brnVirusName , bpsVirus , brnVirus ) where import Data.Int (Int64) import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Time as Time data Virus = Virus { virusId :: VirusId , virusName :: VirusName , virusDiscoveredAt :: VirusDiscoveredAt } deriving (Show, Eq) newtype VirusId = VirusId { unVirusId :: Int64 } deriving (Bounded, Enum, Eq, Show, Ord) newtype VirusName = VirusName { unVirusName :: Text } deriving (Show, Eq) newtype VirusDiscoveredAt = VirusDiscoveredAt { unVirusDiscoveredAt :: Time.UTCTime } deriving (Show, Eq) bpsVirusName :: VirusName bpsVirusName = VirusName (Text.pack "Bovine popular stomachitis") brnVirusName :: VirusName brnVirusName = VirusName (Text.pack "Black raspberry necrosis") bpsDiscoveredAt :: VirusDiscoveredAt bpsDiscoveredAt = VirusDiscoveredAt $ Time.UTCTime (Time.fromGregorian 1969 1 1) 0 brnDiscoveredAt :: VirusDiscoveredAt brnDiscoveredAt = VirusDiscoveredAt $ Time.UTCTime (Time.fromGregorian 1800 12 25) 0 bpsVirus :: Virus bpsVirus = Virus { virusId = VirusId 1 , virusName = bpsVirusName , virusDiscoveredAt = bpsDiscoveredAt } brnVirus :: Virus brnVirus = Virus { virusId = VirusId 2 , virusName = brnVirusName , virusDiscoveredAt = brnDiscoveredAt }
flipstone/orville
orville-postgresql/test/AppManagedEntity/Data/Virus.hs
mit
1,477
0
9
278
389
233
156
51
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} module Test.Smoke.Bless ( blessResult, ) where import Control.Exception (catch, throwIO) import Control.Monad (foldM) import Data.Map.Strict ((!)) import qualified Data.Map.Strict as Map import Data.Text (Text) import qualified Data.Text as Text import Data.Vector (Vector) import qualified Data.Vector as Vector import Test.Smoke.Paths import Test.Smoke.Types blessResult :: ResolvedPath Dir -> TestResult -> IO TestResult blessResult _ (TestResult TestPlan {planTest = test} (EqualityFailure _ (Actual (Status actualStatus))) _ _ _) = failed test $ CouldNotBlessInlineFixture "status" (Text.pack (show actualStatus)) blessResult location result@(TestResult TestPlan {planTest = test} _ stdOut stdErr files) = do serializedStdOut <- serialize (testStdOut test) stdOut serializedStdErr <- serialize (testStdErr test) stdErr serializedFiles <- Map.traverseWithKey (\path fileResult -> serialize (testFiles test ! path) fileResult) files foldM (\r f -> f r) result ( writeFixture serializedStdOut (\a r -> r {resultStdOut = a}) : writeFixture serializedStdErr (\a r -> r {resultStdErr = a}) : map (\(path, serializedFile) -> writeFixture serializedFile (\a r -> r {resultFiles = Map.insert path a (resultFiles r)})) (Map.assocs serializedFiles) ) `catch` (\(e :: SmokeBlessError) -> failed test e) `catch` (failed test . BlessIOException) where writeFixture :: Maybe (RelativePath File, Text) -> (AssertionResult a -> TestResult -> TestResult) -> TestResult -> IO TestResult writeFixture Nothing _ before = return before writeFixture (Just (path, text)) makeAfter before = do createParent (location </> path) writeToPath (location </> path) text return $ makeAfter AssertionSuccess before blessResult _ result = return result serialize :: forall a. FixtureType a => Vector (TestOutput a) -> AssertionResult a -> IO (Maybe (RelativePath File, Text)) serialize _ AssertionSuccess = return Nothing serialize outputs (AssertionFailure result) = case Vector.length outputs of 1 -> serializeFailure (Vector.head outputs) result 0 -> throwIO $ CouldNotBlessAMissingValue (fixtureName @a) _ -> throwIO $ CouldNotBlessWithMultipleValues (fixtureName @a) serializeFailure :: forall a. FixtureType a => TestOutput a -> AssertionFailures a -> IO (Maybe (RelativePath File, Text)) serializeFailure (TestOutput _ (FileLocation path)) (SingleAssertionFailure (AssertionFailureDiff _ (Actual actual))) = return $ Just (path, serializeFixture actual) serializeFailure (TestOutput _ (Inline _)) (SingleAssertionFailure (AssertionFailureDiff _ (Actual actual))) = throwIO $ CouldNotBlessInlineFixture (fixtureName @a) (serializeFixture actual) serializeFailure (TestOutput _ _) (SingleAssertionFailure (AssertionFailureContains _ (Actual actual))) = throwIO $ CouldNotBlessContainsAssertion (fixtureName @a) (serializeFixture actual) serializeFailure (TestOutput _ (FileLocation path)) (SingleAssertionFailure (AssertionFailureExpectedFileError _ (Actual actual))) = return $ Just (path, serializeFixture actual) serializeFailure (TestOutput _ (Inline _)) (SingleAssertionFailure (AssertionFailureExpectedFileError _ (Actual actual))) = throwIO $ CouldNotBlessInlineFixture (fixtureName @a) (serializeFixture actual) serializeFailure (TestOutput _ _) (SingleAssertionFailure (AssertionFailureActualFileError _)) = return Nothing serializeFailure _ (MultipleAssertionFailures _) = throwIO $ CouldNotBlessWithMultipleValues (fixtureName @a) failed :: Applicative f => Test -> SmokeBlessError -> f TestResult failed test = pure . TestError test . BlessError
SamirTalwar/Smoke
src/lib/Test/Smoke/Bless.hs
mit
3,804
0
22
602
1,269
651
618
67
3
{-# LANGUAGE OverloadedStrings, OverloadedLists, LambdaCase #-} module Text.EasyJson.AST where import Data.Text (Text) import qualified Data.Text as T import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as H import Data.List (intercalate) import Data.Monoid import Data.Vector (Vector) import qualified Data.Vector as V data Json = Number Double | String Text | Bool Bool | Null | Array (Vector Json) | Object (HashMap Text Json) deriving (Eq) instance Show Json where show json = case json of Number n -> show n String s -> show s Bool True -> "true" Bool False -> "false" Null -> "null" Array js -> surround "[" "]" $ V.toList $ fmap show js Object obj -> surround "{" "}" $ map showT $ H.toList obj where surround l r list = l <> intercalate "," list <> r showT (n, j) = show n <> ":" <> show j jsonType :: Json -> Text jsonType = \case Number _ -> "number" String _ -> "string" Bool _ -> "bool" Null -> "null" Array _ -> "array" Object _ -> "object"
thinkpad20/easyjson
src/Text/EasyJson/AST.hs
mit
1,095
0
11
291
381
199
182
36
6
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.WebKitCSSMatrix (js_newWebKitCSSMatrix, newWebKitCSSMatrix, js_setMatrixValue, setMatrixValue, js_multiply, multiply, js_inverse, inverse, js_translate, translate, js_scale, scale, js_rotate, rotate, js_rotateAxisAngle, rotateAxisAngle, js_skewX, skewX, js_skewY, skewY, js_toString, toString, js_setA, setA, js_getA, getA, js_setB, setB, js_getB, getB, js_setC, setC, js_getC, getC, js_setD, setD, js_getD, getD, js_setE, setE, js_getE, getE, js_setF, setF, js_getF, getF, js_setM11, setM11, js_getM11, getM11, js_setM12, setM12, js_getM12, getM12, js_setM13, setM13, js_getM13, getM13, js_setM14, setM14, js_getM14, getM14, js_setM21, setM21, js_getM21, getM21, js_setM22, setM22, js_getM22, getM22, js_setM23, setM23, js_getM23, getM23, js_setM24, setM24, js_getM24, getM24, js_setM31, setM31, js_getM31, getM31, js_setM32, setM32, js_getM32, getM32, js_setM33, setM33, js_getM33, getM33, js_setM34, setM34, js_getM34, getM34, js_setM41, setM41, js_getM41, getM41, js_setM42, setM42, js_getM42, getM42, js_setM43, setM43, js_getM43, getM43, js_setM44, setM44, js_getM44, getM44, WebKitCSSMatrix, castToWebKitCSSMatrix, gTypeWebKitCSSMatrix) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "new window[\"WebKitCSSMatrix\"]($1)" js_newWebKitCSSMatrix :: JSString -> IO WebKitCSSMatrix -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix Mozilla WebKitCSSMatrix documentation> newWebKitCSSMatrix :: (MonadIO m, ToJSString cssValue) => cssValue -> m WebKitCSSMatrix newWebKitCSSMatrix cssValue = liftIO (js_newWebKitCSSMatrix (toJSString cssValue)) foreign import javascript unsafe "$1[\"setMatrixValue\"]($2)" js_setMatrixValue :: WebKitCSSMatrix -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.setMatrixValue Mozilla WebKitCSSMatrix.setMatrixValue documentation> setMatrixValue :: (MonadIO m, ToJSString string) => WebKitCSSMatrix -> string -> m () setMatrixValue self string = liftIO (js_setMatrixValue (self) (toJSString string)) foreign import javascript unsafe "$1[\"multiply\"]($2)" js_multiply :: WebKitCSSMatrix -> Nullable WebKitCSSMatrix -> IO (Nullable WebKitCSSMatrix) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.multiply Mozilla WebKitCSSMatrix.multiply documentation> multiply :: (MonadIO m) => WebKitCSSMatrix -> Maybe WebKitCSSMatrix -> m (Maybe WebKitCSSMatrix) multiply self secondMatrix = liftIO (nullableToMaybe <$> (js_multiply (self) (maybeToNullable secondMatrix))) foreign import javascript unsafe "$1[\"inverse\"]()" js_inverse :: WebKitCSSMatrix -> IO (Nullable WebKitCSSMatrix) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.inverse Mozilla WebKitCSSMatrix.inverse documentation> inverse :: (MonadIO m) => WebKitCSSMatrix -> m (Maybe WebKitCSSMatrix) inverse self = liftIO (nullableToMaybe <$> (js_inverse (self))) foreign import javascript unsafe "$1[\"translate\"]($2, $3, $4)" js_translate :: WebKitCSSMatrix -> Double -> Double -> Double -> IO (Nullable WebKitCSSMatrix) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.translate Mozilla WebKitCSSMatrix.translate documentation> translate :: (MonadIO m) => WebKitCSSMatrix -> Double -> Double -> Double -> m (Maybe WebKitCSSMatrix) translate self x y z = liftIO (nullableToMaybe <$> (js_translate (self) x y z)) foreign import javascript unsafe "$1[\"scale\"]($2, $3, $4)" js_scale :: WebKitCSSMatrix -> Double -> Double -> Double -> IO (Nullable WebKitCSSMatrix) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.scale Mozilla WebKitCSSMatrix.scale documentation> scale :: (MonadIO m) => WebKitCSSMatrix -> Double -> Double -> Double -> m (Maybe WebKitCSSMatrix) scale self scaleX scaleY scaleZ = liftIO (nullableToMaybe <$> (js_scale (self) scaleX scaleY scaleZ)) foreign import javascript unsafe "$1[\"rotate\"]($2, $3, $4)" js_rotate :: WebKitCSSMatrix -> Double -> Double -> Double -> IO (Nullable WebKitCSSMatrix) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.rotate Mozilla WebKitCSSMatrix.rotate documentation> rotate :: (MonadIO m) => WebKitCSSMatrix -> Double -> Double -> Double -> m (Maybe WebKitCSSMatrix) rotate self rotX rotY rotZ = liftIO (nullableToMaybe <$> (js_rotate (self) rotX rotY rotZ)) foreign import javascript unsafe "$1[\"rotateAxisAngle\"]($2, $3,\n$4, $5)" js_rotateAxisAngle :: WebKitCSSMatrix -> Double -> Double -> Double -> Double -> IO (Nullable WebKitCSSMatrix) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.rotateAxisAngle Mozilla WebKitCSSMatrix.rotateAxisAngle documentation> rotateAxisAngle :: (MonadIO m) => WebKitCSSMatrix -> Double -> Double -> Double -> Double -> m (Maybe WebKitCSSMatrix) rotateAxisAngle self x y z angle = liftIO (nullableToMaybe <$> (js_rotateAxisAngle (self) x y z angle)) foreign import javascript unsafe "$1[\"skewX\"]($2)" js_skewX :: WebKitCSSMatrix -> Double -> IO (Nullable WebKitCSSMatrix) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.skewX Mozilla WebKitCSSMatrix.skewX documentation> skewX :: (MonadIO m) => WebKitCSSMatrix -> Double -> m (Maybe WebKitCSSMatrix) skewX self angle = liftIO (nullableToMaybe <$> (js_skewX (self) angle)) foreign import javascript unsafe "$1[\"skewY\"]($2)" js_skewY :: WebKitCSSMatrix -> Double -> IO (Nullable WebKitCSSMatrix) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.skewY Mozilla WebKitCSSMatrix.skewY documentation> skewY :: (MonadIO m) => WebKitCSSMatrix -> Double -> m (Maybe WebKitCSSMatrix) skewY self angle = liftIO (nullableToMaybe <$> (js_skewY (self) angle)) foreign import javascript unsafe "$1[\"toString\"]()" js_toString :: WebKitCSSMatrix -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.toString Mozilla WebKitCSSMatrix.toString documentation> toString :: (MonadIO m, FromJSString result) => WebKitCSSMatrix -> m result toString self = liftIO (fromJSString <$> (js_toString (self))) foreign import javascript unsafe "$1[\"a\"] = $2;" js_setA :: WebKitCSSMatrix -> Double -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.a Mozilla WebKitCSSMatrix.a documentation> setA :: (MonadIO m) => WebKitCSSMatrix -> Double -> m () setA self val = liftIO (js_setA (self) val) foreign import javascript unsafe "$1[\"a\"]" js_getA :: WebKitCSSMatrix -> IO Double -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.a Mozilla WebKitCSSMatrix.a documentation> getA :: (MonadIO m) => WebKitCSSMatrix -> m Double getA self = liftIO (js_getA (self)) foreign import javascript unsafe "$1[\"b\"] = $2;" js_setB :: WebKitCSSMatrix -> Double -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.b Mozilla WebKitCSSMatrix.b documentation> setB :: (MonadIO m) => WebKitCSSMatrix -> Double -> m () setB self val = liftIO (js_setB (self) val) foreign import javascript unsafe "$1[\"b\"]" js_getB :: WebKitCSSMatrix -> IO Double -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.b Mozilla WebKitCSSMatrix.b documentation> getB :: (MonadIO m) => WebKitCSSMatrix -> m Double getB self = liftIO (js_getB (self)) foreign import javascript unsafe "$1[\"c\"] = $2;" js_setC :: WebKitCSSMatrix -> Double -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.c Mozilla WebKitCSSMatrix.c documentation> setC :: (MonadIO m) => WebKitCSSMatrix -> Double -> m () setC self val = liftIO (js_setC (self) val) foreign import javascript unsafe "$1[\"c\"]" js_getC :: WebKitCSSMatrix -> IO Double -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.c Mozilla WebKitCSSMatrix.c documentation> getC :: (MonadIO m) => WebKitCSSMatrix -> m Double getC self = liftIO (js_getC (self)) foreign import javascript unsafe "$1[\"d\"] = $2;" js_setD :: WebKitCSSMatrix -> Double -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.d Mozilla WebKitCSSMatrix.d documentation> setD :: (MonadIO m) => WebKitCSSMatrix -> Double -> m () setD self val = liftIO (js_setD (self) val) foreign import javascript unsafe "$1[\"d\"]" js_getD :: WebKitCSSMatrix -> IO Double -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.d Mozilla WebKitCSSMatrix.d documentation> getD :: (MonadIO m) => WebKitCSSMatrix -> m Double getD self = liftIO (js_getD (self)) foreign import javascript unsafe "$1[\"e\"] = $2;" js_setE :: WebKitCSSMatrix -> Double -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.e Mozilla WebKitCSSMatrix.e documentation> setE :: (MonadIO m) => WebKitCSSMatrix -> Double -> m () setE self val = liftIO (js_setE (self) val) foreign import javascript unsafe "$1[\"e\"]" js_getE :: WebKitCSSMatrix -> IO Double -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.e Mozilla WebKitCSSMatrix.e documentation> getE :: (MonadIO m) => WebKitCSSMatrix -> m Double getE self = liftIO (js_getE (self)) foreign import javascript unsafe "$1[\"f\"] = $2;" js_setF :: WebKitCSSMatrix -> Double -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.f Mozilla WebKitCSSMatrix.f documentation> setF :: (MonadIO m) => WebKitCSSMatrix -> Double -> m () setF self val = liftIO (js_setF (self) val) foreign import javascript unsafe "$1[\"f\"]" js_getF :: WebKitCSSMatrix -> IO Double -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.f Mozilla WebKitCSSMatrix.f documentation> getF :: (MonadIO m) => WebKitCSSMatrix -> m Double getF self = liftIO (js_getF (self)) foreign import javascript unsafe "$1[\"m11\"] = $2;" js_setM11 :: WebKitCSSMatrix -> Double -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m11 Mozilla WebKitCSSMatrix.m11 documentation> setM11 :: (MonadIO m) => WebKitCSSMatrix -> Double -> m () setM11 self val = liftIO (js_setM11 (self) val) foreign import javascript unsafe "$1[\"m11\"]" js_getM11 :: WebKitCSSMatrix -> IO Double -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m11 Mozilla WebKitCSSMatrix.m11 documentation> getM11 :: (MonadIO m) => WebKitCSSMatrix -> m Double getM11 self = liftIO (js_getM11 (self)) foreign import javascript unsafe "$1[\"m12\"] = $2;" js_setM12 :: WebKitCSSMatrix -> Double -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m12 Mozilla WebKitCSSMatrix.m12 documentation> setM12 :: (MonadIO m) => WebKitCSSMatrix -> Double -> m () setM12 self val = liftIO (js_setM12 (self) val) foreign import javascript unsafe "$1[\"m12\"]" js_getM12 :: WebKitCSSMatrix -> IO Double -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m12 Mozilla WebKitCSSMatrix.m12 documentation> getM12 :: (MonadIO m) => WebKitCSSMatrix -> m Double getM12 self = liftIO (js_getM12 (self)) foreign import javascript unsafe "$1[\"m13\"] = $2;" js_setM13 :: WebKitCSSMatrix -> Double -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m13 Mozilla WebKitCSSMatrix.m13 documentation> setM13 :: (MonadIO m) => WebKitCSSMatrix -> Double -> m () setM13 self val = liftIO (js_setM13 (self) val) foreign import javascript unsafe "$1[\"m13\"]" js_getM13 :: WebKitCSSMatrix -> IO Double -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m13 Mozilla WebKitCSSMatrix.m13 documentation> getM13 :: (MonadIO m) => WebKitCSSMatrix -> m Double getM13 self = liftIO (js_getM13 (self)) foreign import javascript unsafe "$1[\"m14\"] = $2;" js_setM14 :: WebKitCSSMatrix -> Double -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m14 Mozilla WebKitCSSMatrix.m14 documentation> setM14 :: (MonadIO m) => WebKitCSSMatrix -> Double -> m () setM14 self val = liftIO (js_setM14 (self) val) foreign import javascript unsafe "$1[\"m14\"]" js_getM14 :: WebKitCSSMatrix -> IO Double -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m14 Mozilla WebKitCSSMatrix.m14 documentation> getM14 :: (MonadIO m) => WebKitCSSMatrix -> m Double getM14 self = liftIO (js_getM14 (self)) foreign import javascript unsafe "$1[\"m21\"] = $2;" js_setM21 :: WebKitCSSMatrix -> Double -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m21 Mozilla WebKitCSSMatrix.m21 documentation> setM21 :: (MonadIO m) => WebKitCSSMatrix -> Double -> m () setM21 self val = liftIO (js_setM21 (self) val) foreign import javascript unsafe "$1[\"m21\"]" js_getM21 :: WebKitCSSMatrix -> IO Double -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m21 Mozilla WebKitCSSMatrix.m21 documentation> getM21 :: (MonadIO m) => WebKitCSSMatrix -> m Double getM21 self = liftIO (js_getM21 (self)) foreign import javascript unsafe "$1[\"m22\"] = $2;" js_setM22 :: WebKitCSSMatrix -> Double -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m22 Mozilla WebKitCSSMatrix.m22 documentation> setM22 :: (MonadIO m) => WebKitCSSMatrix -> Double -> m () setM22 self val = liftIO (js_setM22 (self) val) foreign import javascript unsafe "$1[\"m22\"]" js_getM22 :: WebKitCSSMatrix -> IO Double -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m22 Mozilla WebKitCSSMatrix.m22 documentation> getM22 :: (MonadIO m) => WebKitCSSMatrix -> m Double getM22 self = liftIO (js_getM22 (self)) foreign import javascript unsafe "$1[\"m23\"] = $2;" js_setM23 :: WebKitCSSMatrix -> Double -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m23 Mozilla WebKitCSSMatrix.m23 documentation> setM23 :: (MonadIO m) => WebKitCSSMatrix -> Double -> m () setM23 self val = liftIO (js_setM23 (self) val) foreign import javascript unsafe "$1[\"m23\"]" js_getM23 :: WebKitCSSMatrix -> IO Double -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m23 Mozilla WebKitCSSMatrix.m23 documentation> getM23 :: (MonadIO m) => WebKitCSSMatrix -> m Double getM23 self = liftIO (js_getM23 (self)) foreign import javascript unsafe "$1[\"m24\"] = $2;" js_setM24 :: WebKitCSSMatrix -> Double -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m24 Mozilla WebKitCSSMatrix.m24 documentation> setM24 :: (MonadIO m) => WebKitCSSMatrix -> Double -> m () setM24 self val = liftIO (js_setM24 (self) val) foreign import javascript unsafe "$1[\"m24\"]" js_getM24 :: WebKitCSSMatrix -> IO Double -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m24 Mozilla WebKitCSSMatrix.m24 documentation> getM24 :: (MonadIO m) => WebKitCSSMatrix -> m Double getM24 self = liftIO (js_getM24 (self)) foreign import javascript unsafe "$1[\"m31\"] = $2;" js_setM31 :: WebKitCSSMatrix -> Double -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m31 Mozilla WebKitCSSMatrix.m31 documentation> setM31 :: (MonadIO m) => WebKitCSSMatrix -> Double -> m () setM31 self val = liftIO (js_setM31 (self) val) foreign import javascript unsafe "$1[\"m31\"]" js_getM31 :: WebKitCSSMatrix -> IO Double -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m31 Mozilla WebKitCSSMatrix.m31 documentation> getM31 :: (MonadIO m) => WebKitCSSMatrix -> m Double getM31 self = liftIO (js_getM31 (self)) foreign import javascript unsafe "$1[\"m32\"] = $2;" js_setM32 :: WebKitCSSMatrix -> Double -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m32 Mozilla WebKitCSSMatrix.m32 documentation> setM32 :: (MonadIO m) => WebKitCSSMatrix -> Double -> m () setM32 self val = liftIO (js_setM32 (self) val) foreign import javascript unsafe "$1[\"m32\"]" js_getM32 :: WebKitCSSMatrix -> IO Double -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m32 Mozilla WebKitCSSMatrix.m32 documentation> getM32 :: (MonadIO m) => WebKitCSSMatrix -> m Double getM32 self = liftIO (js_getM32 (self)) foreign import javascript unsafe "$1[\"m33\"] = $2;" js_setM33 :: WebKitCSSMatrix -> Double -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m33 Mozilla WebKitCSSMatrix.m33 documentation> setM33 :: (MonadIO m) => WebKitCSSMatrix -> Double -> m () setM33 self val = liftIO (js_setM33 (self) val) foreign import javascript unsafe "$1[\"m33\"]" js_getM33 :: WebKitCSSMatrix -> IO Double -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m33 Mozilla WebKitCSSMatrix.m33 documentation> getM33 :: (MonadIO m) => WebKitCSSMatrix -> m Double getM33 self = liftIO (js_getM33 (self)) foreign import javascript unsafe "$1[\"m34\"] = $2;" js_setM34 :: WebKitCSSMatrix -> Double -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m34 Mozilla WebKitCSSMatrix.m34 documentation> setM34 :: (MonadIO m) => WebKitCSSMatrix -> Double -> m () setM34 self val = liftIO (js_setM34 (self) val) foreign import javascript unsafe "$1[\"m34\"]" js_getM34 :: WebKitCSSMatrix -> IO Double -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m34 Mozilla WebKitCSSMatrix.m34 documentation> getM34 :: (MonadIO m) => WebKitCSSMatrix -> m Double getM34 self = liftIO (js_getM34 (self)) foreign import javascript unsafe "$1[\"m41\"] = $2;" js_setM41 :: WebKitCSSMatrix -> Double -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m41 Mozilla WebKitCSSMatrix.m41 documentation> setM41 :: (MonadIO m) => WebKitCSSMatrix -> Double -> m () setM41 self val = liftIO (js_setM41 (self) val) foreign import javascript unsafe "$1[\"m41\"]" js_getM41 :: WebKitCSSMatrix -> IO Double -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m41 Mozilla WebKitCSSMatrix.m41 documentation> getM41 :: (MonadIO m) => WebKitCSSMatrix -> m Double getM41 self = liftIO (js_getM41 (self)) foreign import javascript unsafe "$1[\"m42\"] = $2;" js_setM42 :: WebKitCSSMatrix -> Double -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m42 Mozilla WebKitCSSMatrix.m42 documentation> setM42 :: (MonadIO m) => WebKitCSSMatrix -> Double -> m () setM42 self val = liftIO (js_setM42 (self) val) foreign import javascript unsafe "$1[\"m42\"]" js_getM42 :: WebKitCSSMatrix -> IO Double -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m42 Mozilla WebKitCSSMatrix.m42 documentation> getM42 :: (MonadIO m) => WebKitCSSMatrix -> m Double getM42 self = liftIO (js_getM42 (self)) foreign import javascript unsafe "$1[\"m43\"] = $2;" js_setM43 :: WebKitCSSMatrix -> Double -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m43 Mozilla WebKitCSSMatrix.m43 documentation> setM43 :: (MonadIO m) => WebKitCSSMatrix -> Double -> m () setM43 self val = liftIO (js_setM43 (self) val) foreign import javascript unsafe "$1[\"m43\"]" js_getM43 :: WebKitCSSMatrix -> IO Double -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m43 Mozilla WebKitCSSMatrix.m43 documentation> getM43 :: (MonadIO m) => WebKitCSSMatrix -> m Double getM43 self = liftIO (js_getM43 (self)) foreign import javascript unsafe "$1[\"m44\"] = $2;" js_setM44 :: WebKitCSSMatrix -> Double -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m44 Mozilla WebKitCSSMatrix.m44 documentation> setM44 :: (MonadIO m) => WebKitCSSMatrix -> Double -> m () setM44 self val = liftIO (js_setM44 (self) val) foreign import javascript unsafe "$1[\"m44\"]" js_getM44 :: WebKitCSSMatrix -> IO Double -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSMatrix.m44 Mozilla WebKitCSSMatrix.m44 documentation> getM44 :: (MonadIO m) => WebKitCSSMatrix -> m Double getM44 self = liftIO (js_getM44 (self))
manyoo/ghcjs-dom
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/WebKitCSSMatrix.hs
mit
21,654
408
11
3,499
4,888
2,606
2,282
301
1
module MemorySetQueue ( Q , empty , enque , deque , fromList , toList , getSet , getAll ) where import Prelude hiding (all) import qualified Data.Set as S data Q e t = Q [e] [e] [e] (S.Set t) (e -> t) enque :: Ord t => e -> Q e t -> Q e t enque x (Q [] _ _ _ f) = Q [x] [] [x] (S.singleton $ f x) f enque x q@(Q as zs all set f) | f x `S.member` set = q | otherwise = Q as (x:zs) (x:all) (S.insert (f x) set) f deque :: Ord t => Q e t -> Maybe (e, Q e t) deque (Q [] _ _ _ _) = Nothing deque (Q (a:as) zs all set f) | null as = Just (a, Q (reverse zs) [] all set f) | otherwise = Just (a, Q as zs all set f) empty :: Ord t => (e -> t) -> Q e t empty = Q [] [] [] S.empty getSet :: Ord t => Q e t -> S.Set t getSet (Q _ _ _ set _) = set getAll :: Q e t -> [e] getAll (Q _ _ all _ _) = all fromList :: Ord t => (e -> t) -> [e] -> Q e t fromList f as = Q as [] as (S.fromList $ map f as) f toList :: Q e t -> [e] toList (Q as zs _ _ _) = as ++ reverse zs
ornicar/haskant
src/MemorySetQueue.hs
mit
1,067
0
10
373
680
349
331
30
1
{-# LANGUAGE OverloadedStrings #-} -- Cards in The Gathering Storm expansion module Game.RftG.Cards.Promo where import Game.RftG.Core import Game.RftG.Card ------------------------------------------------------------------------------- -- Cards -- reference: http://racepics.weihwa.com/tgs.html ------------------------------------------------------------------------------- abandonedMineSquatters :: Card abandonedMineSquatters = Card (World $ Production RareElements) "ABANDONED MINE SQUATTERS" (Defense 2) (VP 0) Nothing [] [Settle, Produce] galacticTradeEmissaries :: Card galacticTradeEmissaries = Card (World Grey) "GALACTIC TRADE EMISSARIES" (Cost 2) (VP 1) Nothing [] [Settle, Consume] gatewayStation :: Card gatewayStation = Card (World $ Windfall NoveltyGoods) "GATEWAY STATION" (Cost 2) (VP 1) Nothing [] [Consume] industrialRobots :: Card industrialRobots = Card (World Grey) "INDUSTRIAL ROBOTS" (Cost 2) (VP 1) Nothing [] [Develop, Produce] starNomadRaiders :: Card starNomadRaiders = Card (World Grey) "STAR NOMAD RAIDERS" (Defense 2) (VP 1) Nothing [] [Settle, Trade] terraformingColonists :: Card terraformingColonists = Card (World Grey) "TERRAFORMING COLONISTS" (Cost 2) (VP 1) Nothing [Terraforming] [Settle, Produce] ------------------------------------------------------------------------------- -- Collections ------------------------------------------------------------------------------- promoStartWorlds :: [Card] promoStartWorlds = [ abandonedMineSquatters , gatewayStation , starNomadRaiders , terraformingColonists , galacticTradeEmissaries , industrialRobots ] promoCards :: [Card] promoCards = [ abandonedMineSquatters , galacticTradeEmissaries , gatewayStation , industrialRobots , starNomadRaiders , terraformingColonists ]
gspindles/rftg-cards
src/Game/RftG/Cards/Promo.hs
mit
1,887
0
8
310
403
228
175
74
1
module Hearthstone.CardType ( CardType(..) , toCardType , fromCardType ) where import Control.Lens data CardType = CtMinion -- 4 | CtSpell -- 5 deriving (Show, Eq) fromCardType :: CardType -> Int fromCardType CtMinion = 4 fromCardType CtSpell = 5 toCardType :: Int -> Maybe CardType toCardType 4 = Just CtMinion toCardType 5 = Just CtSpell toCardType _ = Nothing
jb55/hearthstone-cards
src/Hearthstone/CardType.hs
mit
401
0
6
96
116
64
52
15
1
{- Raybox.hs; Mun Hon Cheong (mhch295@cse.unsw.edu.au) 2005 This module performs collision tests between AABBs, spheres and rays. -} module Raybox where import Matrix -- tests if a ray intersects a box rayBox :: (Double,Double,Double) -> (Double,Double,Double) -> (Double,Double,Double) -> (Double,Double,Double) -> Bool rayBox (rayOx,rayOy,rayOz) (rayDx,rayDy,rayDz) (minx,miny,minz)(maxx,maxy,maxz) | (rayOx,rayOy,rayOz) == (rayDx,rayDy,rayDz) = False | otherwise = not ((txmin > tymax) || (tymin > txmax)) && intersectz where (txmin,txmax) = getT rayOx rayDx minx maxx (tymin,tymax) = getT rayOy rayDy miny maxy (tzmin,tzmax) = getT rayOz rayDz minz maxz intersectz = not ((max txmin tymin > tzmax) || (tzmin > min txmax tymax)) getT :: Double -> Double -> Double -> Double -> (Double, Double) getT rayO rayD mn mx | dd >= 0 = ((mn-rayO)*dd, (mx-rayO)*dd) | otherwise = ((mx-rayO)*dd, (mn-rayO)*dd) where dd = 1/(rayO-rayD) -- tests if 2 AABBs intersect boxBox :: Vec3 -> Vec3 -> Vec3 -> Vec3 -> Bool boxBox (x1,y1,z1) (w1,h1,d1) (x2,y2,z2) (w2,h2,d2) | abs (x1 - x2) <= w1+w2 = True | abs (y1 - y2) <= h1+h2 = True | abs (z1 - z2) <= d1+d2 = True | otherwise = False -- tests if an AABB intersects a sphere boxSphere :: Vec3 -> Vec3 -> Vec3 -> Double -> Bool boxSphere (x1,y1,z1) (w1,h1,d1) (x2,y2,z2) rad | abs (x1 - x2) <= (w1+rad) = True | abs (y1 - y2) <= (h1+rad) = True | abs (z1 - z2) <= (d1+rad) = True | otherwise = False -- test if two spheres intersect sphereSphere :: Vec3 -> Vec3 -> Double -> Double -> Bool sphereSphere (x1,y1,z1) (x2,y2,z2) rad1 rad2 = (sqrt ((x1-x2)*(x1-x2))+((y1-y2)*(y1-y2))+((z1-z2)*(z1-z2))) <= (rad1+rad2) -- tests if a point lies within a sphere spherePoint :: Vec3 -> Vec3 -> Double -> Bool spherePoint (x1,y1,z1) (x2,y2,z2) rad = sqrt (((x1-x2)*(x1-x2)) + ((y1-y2)*(y1-y2)) + ((z1-z2)*(z1-z2))) <= rad -- test if a point lies in an AABB pointBox :: Vec3 -> Vec3 -> Vec3 -> Bool pointBox (x1,y1,z1) (x2,y2,z2) (w,h,d) | abs (x1 - x2) <= w && abs (y1 - y2) <= h && abs (z1 - z2) <= d = True | otherwise = False
pushkinma/frag
src/Raybox.hs
gpl-2.0
2,202
0
15
497
1,130
620
510
40
1
module Account where import Control.Concurrent import Control.Concurrent.STM -- Represent the balance of the account type Account = TVar Int -- transfer `amount` from account `from` to account `to` transfer :: Account -> Account -> Int -> IO () transfer from to amount = atomically ( do deposit to amount withdraw from amount ) deposit :: Account -> Int -> STM () deposit acc amt = do balance <- readTVar acc writeTVar acc (balance + amt) withdraw :: Account -> Int -> STM () withdraw acc amt = deposit acc (- amt) showAccount :: Account -> IO String showAccount acc = do bal <- (atomically . readTVar) acc return $ show bal displayAccount :: String -> Account -> IO () displayAccount label acc = do bal <- showAccount acc putStrLn $ label ++ ": " ++ bal transferFromAccountAToAccountB :: IO () transferFromAccountAToAccountB = do accA <- accountA accB <- accountB displayAccount "A" accA displayAccount "B" accB transfer accA accB 10 putStrLn "Transfer 10 from A to B: " displayAccount "A" accA displayAccount "B" accB where accountA :: IO Account accountA = atomically . newTVar $ (100 :: Int) accountB :: IO Account accountB = atomically . newTVar $ (300 :: Int) -- *Account> transferFromAccountAToAccountB -- A: 100 -- B: 300 -- Transfer 10 from A to B: -- A: 90 -- B: 310 limitedWithdraw :: Account -> Int -> STM () limitedWithdraw acc amt = do balance <- readTVar acc check (0 <= amt && amt <= balance) writeTVar acc (balance - amt) -- Beware signature is different from deposit one delayDeposit :: Account -> Int -> IO () delayDeposit acc amt = do threadDelay 3000000 -- wait 3 seconds atomically ( deposit acc amt ) withdrawFromAccountAWithRetry :: IO () withdrawFromAccountAWithRetry = do accA <- accountA displayAccount "A" accA putStrLn "Transfer 11 from A (waiting if not enough money)..." forkIO(delayDeposit accA 1) atomically ( limitedWithdraw accA 11 ) displayAccount "A" accA where accountA :: IO Account accountA = atomically . newTVar $ (10 :: Int) -- *Account> withdrawFromAccountAWithRetry -- A: 10 -- Transfer 11 from A (waiting if not enough money)... -- A: 0
ardumont/haskell-lab
src/concurrency/account.hs
gpl-2.0
2,288
0
11
558
641
313
328
55
1
{- pandoc-crossref is a pandoc filter for numbering figures, equations, tables and cross-references to them. Copyright (C) 2015 Nikolay Yakimov <root@livid.pp.ru> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -} {- | Module : Text.Pandoc.CrossRef Copyright : Copyright (C) 2015 Nikolay Yakimov License : GNU GPL, version 2 or above Maintainer : Nikolay Yakimov <root@livid.pp.ru> Stability : alpha Portability : portable Public interface to pandoc-crossref library Example of use: > import Text.Pandoc > import Text.Pandoc.JSON > > import Text.Pandoc.CrossRef > > main :: IO () > main = toJSONFilter go > where > go fmt p@(Pandoc meta _) = runCrossRefIO meta fmt action p > where > action (Pandoc _ bs) = do > meta' <- crossRefMeta > bs' <- crossRefBlocks bs > return $ Pandoc meta' bs' This module also exports utility functions for setting up meta-settings for pandoc-crossref. Refer to documentation for a complete list of metadata field names. All functions accept a single argument of type, returned by "Text.Pandoc.Builder" functions, and return 'Meta'. Example: > runCrossRefIO meta fmt crossRefBlocks blocks > where > meta = > figureTitle (str "Figura") > <> tableTitle (str "Tabla") > <> figPrefix (str "fig.") > <> eqnPrefix (str "ec.") > <> tblPrefix (str "tbl.") > <> loftitle (header 1 $ text "Lista de figuras") > <> lotTitle (header 1 $ text "Lista de tablas") > <> chaptersDepth (MetaString "2") -} {-# LANGUAGE RankNTypes #-} module Text.Pandoc.CrossRef ( crossRefBlocks , crossRefMeta , defaultCrossRefAction , runCrossRef , runCrossRefIO , module SG , defaultMeta , CrossRefM , CrossRefEnv(..) ) where import Control.Monad.State import qualified Control.Monad.Reader as R import Text.Pandoc import Text.Pandoc.CrossRef.References import Text.Pandoc.CrossRef.Util.Settings import Text.Pandoc.CrossRef.Util.Options as O import Text.Pandoc.CrossRef.Util.CodeBlockCaptions import Text.Pandoc.CrossRef.Util.ModifyMeta import Text.Pandoc.CrossRef.Util.Settings.Gen as SG -- | Enviromnent for 'CrossRefM' data CrossRefEnv = CrossRefEnv { creSettings :: Meta -- ^Metadata settings , creOptions :: Options -- ^Internal pandoc-crossref options } -- | Essentially a reader monad for basic pandoc-crossref environment type CrossRefM a = R.Reader CrossRefEnv a {- | Walk over blocks, while inserting cross-references, list-of, etc. Works in 'CrossRefM' monad. -} crossRefBlocks :: [Block] -> CrossRefM [Block] crossRefBlocks blocks = do opts <- R.asks creOptions let doWalk = bottomUpM (mkCodeBlockCaptions opts) blocks >>= replaceAll opts >>= bottomUpM (replaceRefs opts) >>= bottomUpM (listOf opts) (result, st) = runState doWalk def st `seq` return result {- | Modifies metadata for LaTeX output, adding header-includes instructions to setup custom and builtin environments. Note, that if output format is not "latex", this function does nothing. Works in 'CrossRefM' monad. -} crossRefMeta :: CrossRefM Meta crossRefMeta = do opts <- R.asks creOptions dtv <- R.asks creSettings return $ modifyMeta opts dtv {- | Combines 'crossRefMeta' and 'crossRefBlocks' Works in 'CrossRefM' monad. -} defaultCrossRefAction :: Pandoc -> CrossRefM Pandoc defaultCrossRefAction (Pandoc _ bs) = do meta' <- crossRefMeta bs' <- crossRefBlocks bs return $ Pandoc meta' bs' {- | Run an action in 'CrossRefM' monad with argument, and return pure result. This is primary function to work with 'CrossRefM' -} runCrossRef :: forall a b. Meta -> Maybe Format -> (a -> CrossRefM b) -> a -> b runCrossRef meta fmt action arg = R.runReader (action arg) env where settings = defaultMeta <> meta env = CrossRefEnv { creSettings = settings , creOptions = getOptions settings fmt } {- | Run an action in 'CrossRefM' monad with argument, and return 'IO' result. This function will attempt to read pandoc-crossref settings from settings file specified by crossrefYaml metadata field. -} runCrossRefIO :: forall a b. Meta -> Maybe Format -> (a -> CrossRefM b) -> a -> IO b runCrossRefIO meta fmt action arg = do settings <- getSettings fmt meta let env = CrossRefEnv { creSettings = settings , creOptions = getOptions settings fmt } return $ R.runReader (action arg) env
lierdakil/pandoc-crossref
lib/Text/Pandoc/CrossRef.hs
gpl-2.0
5,161
0
15
1,110
605
333
272
59
1
{- | Module : ./Common/AnnoParser.hs Description : parsers for annotations and annoted items Copyright : (c) Klaus Luettich, Christian Maeder and Uni Bremen 2002-2006 License : GPLv2 or higher, see LICENSE.txt Maintainer : Christian.Maeder@dfki.de Stability : provisional Portability : portable Parsers for annotations and annoted items Follows Chap. II:5 of the CASL Reference Manual. uses Lexer, Keywords and Token rather than CaslLanguage semantic annotations now end immediately after the keyword! -} module Common.AnnoParser ( annotationL , annotations , fromPos , parseAnno , parseAnnoId , commentLine , newlineOrEof ) where import Text.ParserCombinators.Parsec import Text.ParserCombinators.Parsec.Error import Text.ParserCombinators.Parsec.Pos as Pos import Common.Parsec import Common.Lexer import Common.Token import Common.Id as Id import Common.IRI as IRI import Common.Keywords import Common.AS_Annotation import Common.Utils (trimRight) import qualified Data.Map as Map import Data.List comment :: GenParser Char st Annotation comment = commentLine <|> commentGroup parseAnnoId :: GenParser Char st Id parseAnnoId = let keys = ([], []) in mixId keys keys charOrEof :: Char -> GenParser Char st () charOrEof c = forget (char c) <|> eof newlineOrEof :: GenParser Char st () newlineOrEof = lookAhead $ charOrEof '\n' mkLineAnno :: String -> Annote_text mkLineAnno s = let r = unwords $ words s in Line_anno $ [' ' | not (null r) && isPrefixOf " " s] ++ r commentLine :: GenParser Char st Annotation commentLine = do p <- getPos tryString percents line <- manyTill anyChar newlineOrEof q <- getPos return $ Unparsed_anno Comment_start (mkLineAnno line) (Range [p, dec q]) dec :: Pos -> Pos dec p = Id.incSourceColumn p (-1) mylines :: String -> [String] mylines s = let strip = unwords . words in case lines s ++ ["" | isSuffixOf "\n" s] of [] -> [] [x] -> let x0 = strip x in [if null x0 then x0 else [' ' | head x == ' '] ++ x0 ++ [' ' | last x == ' ']] (x : r) -> let x0 = strip x e = last r e0 = strip e needsBlank = not (null x0) && head x == ' ' addBlank y = [' ' | not (null y) && needsBlank] ++ y in addBlank x0 : map (addBlank . strip) (init r) ++ [if null e then e else if null e0 then [' ' | needsBlank] else addBlank e0 ++ [' ' | last e == ' ']] commentGroup :: GenParser Char st Annotation commentGroup = do p <- getPos textLines <- plainBlock "%{" "}%" q <- getPos return $ Unparsed_anno Comment_start (Group_anno $ mylines textLines) (Range [p, dec q]) annote :: GenParser Char st Annotation annote = annoLabel <|> do p <- getPos i <- try annoIdent anno <- annoteGroup p i <|> annoteLine p i case parseAnno anno p of Left err -> do setPosition (errorPos err) fail (tail (showErrorMessages "or" "unknown parse error" "expecting" "unexpected" "end of input" (errorMessages err))) Right pa -> return pa annoLabel :: GenParser Char st Annotation annoLabel = do p <- getPos labelLines <- plainBlock "%(" ")%" q <- getPos return $ Label (mylines labelLines) $ Range [p, dec q] annoIdent :: GenParser Char st Annote_word annoIdent = fmap Annote_word $ string percentS >> (scanAnyWords <|> fail "wrong comment or annotation starting with a single %") annoteGroup :: Pos -> Annote_word -> GenParser Char st Annotation annoteGroup p s = let aP = do annoteLines <- plainBlock "(" ")%" q <- getPos return $ Unparsed_anno s (Group_anno $ mylines annoteLines) $ Range [p, dec q] in case s of Annote_word w -> case lookup w $ swapTable semantic_anno_table of Just sa -> return $ Semantic_anno sa $ Range [p, Id.incSourceColumn p $ length (show sa) - 3] Nothing -> aP _ -> aP annoteLine :: Pos -> Annote_word -> GenParser Char st Annotation annoteLine p s = do line <- manyTill anyChar newlineOrEof q <- getPos return $ Unparsed_anno s (mkLineAnno line) $ Range [p, dec q] annotationL :: GenParser Char st Annotation annotationL = comment <|> annote <?> "\"%\"" annotations :: GenParser Char st [Annotation] annotations = many (annotationL << skip) {- --------------------------------------- parser for the contents of annotations --------------------------------------- -} commaIds :: GenParser Char st [Id] commaIds = commaSep1 parseAnnoId parseAnno :: Annotation -> Pos -> Either ParseError Annotation parseAnno anno sp = case anno of Unparsed_anno (Annote_word kw) txt qs -> let nsp = Id.incSourceColumn sp (length kw + 1) inp = annoArg txt mkAssoc dir p = do res <- p return (Assoc_anno dir res qs) in Map.findWithDefault (Right anno) kw $ Map.map ( \ p -> parseInternal p nsp inp) $ Map.fromList [ (left_assocS, mkAssoc ALeft commaIds) , (right_assocS, mkAssoc ARight commaIds) , (precS , precAnno qs) , (displayS , displayAnno qs) , (numberS , numberAnno qs) , (stringS , stringAnno qs) , (listS , listAnno qs) , (floatingS, floatingAnno qs) , (prefixS, prefixAnno qs)] _ -> Right anno fromPos :: Pos -> SourcePos fromPos p = Pos.newPos (Id.sourceName p) (Id.sourceLine p) (Id.sourceColumn p) parseInternal :: GenParser Char () a -> Pos -> String -> Either ParseError a parseInternal p sp = parse (do setPosition $ fromPos sp spaces res <- p eof return res) (Id.sourceName sp) checkForPlaces :: [Token] -> GenParser Char st [Token] checkForPlaces ts = do let ps = filter isPlace ts if null ps then nextListToks $ topMix3 ([], []) -- topMix3 starts with square brackets else if isSingle ps then return [] else unexpected "multiple places" nextListToks :: GenParser Char st [Token] -> GenParser Char st [Token] nextListToks f = do ts <- f cs <- checkForPlaces ts return (ts ++ cs) caslListBrackets :: GenParser Char st Id caslListBrackets = do l <- nextListToks $ afterPlace ([], []) (c, p) <- option ([], nullRange) $ comps ([], []) return $ Id l c p precAnno, numberAnno, stringAnno, listAnno, floatingAnno :: Range -> GenParser Char st Annotation precAnno ps = do leftIds <- braces commaIds sign <- (tryString "<>" <|> string "<") << spaces rightIds <- braces commaIds return $ Prec_anno (if sign == "<" then Lower else BothDirections) leftIds rightIds ps numberAnno ps = do n <- parseAnnoId return $ Number_anno n ps listAnno ps = do bs <- caslListBrackets commaT ni <- parseAnnoId commaT ci <- parseAnnoId return $ List_anno bs ni ci ps stringAnno ps = literal2idsAnno ps String_anno floatingAnno ps = literal2idsAnno ps Float_anno prefixAnno :: Range -> GenParser Char st Annotation prefixAnno ps = do prefixes <- many $ do p <- (string colonS >> return "") <|> (IRI.ncname << string colonS) spaces i <- angles iri spaces return (p, i) return $ Prefix_anno prefixes ps literal2idsAnno :: Range -> (Id -> Id -> Range -> Annotation) -> GenParser Char st Annotation literal2idsAnno ps con = do i1 <- parseAnnoId commaT i2 <- parseAnnoId return $ con i1 i2 ps displayAnno :: Range -> GenParser Char st Annotation displayAnno ps = do ident <- parseAnnoId tls <- many $ foldl1 (<|>) $ map dispSymb display_format_table return (Display_anno ident tls ps) dispSymb :: (Display_format, String) -> GenParser Char st (Display_format, String) dispSymb (dfSymb, symb) = do tryString (percentS ++ symb) << spaces str <- manyTill anyChar $ lookAhead $ charOrEof '%' return (dfSymb, trimRight str)
gnn/Hets
Common/AnnoParser.hs
gpl-2.0
8,171
0
20
2,261
2,679
1,326
1,353
208
6
module Machine.Akzeptieren where -- $Id$ import Machine.Class -- import Machine.Vorrechnen import Machine.History import Control.Monad (guard) import Autolib.Reporter hiding ( output ) import Autolib.ToDoc import Autolib.Set -- | einige akzeptierende Rechnungen akzeptierend :: Machine m dat conf => Int -> m -> conf -> [ conf ] akzeptierend cut m c = do k <- akzeptierend_oder_ohne_nachfolger cut m c guard $ accepting m k return k -- | einige Rechnungen akzeptierend_oder_ohne_nachfolger :: Machine m dat conf => Int -> m -> conf -> [ conf ] akzeptierend_oder_ohne_nachfolger cut m c = do k <- take cut $ nachfolger_cut cut m $ c guard $ accepting m k || ( isEmptySet $ next m $ k ) return k check_liste :: ( Machine m dat conf, ToDoc [dat] ) => Bool -- soll akzeptieren? -> Int -> m -> [dat] -> Reporter () check_liste acc cut m xs = mapM_ ( check_item acc cut m ) xs check_item :: ( Machine m dat conf, ToDoc dat ) => Bool -- soll akzeptieren? -> Int -> m -> dat -> Reporter () check_item acc cut m x = nested 4 $ do ip <- input_reporter m x let ks = akzeptierend_oder_ohne_nachfolger cut m ip alle = take cut $ nachfolger_cut cut m ip as = filter ( accepting m ) ks logs = if not (null as) then as else if not (null ks) then ks else selection 2 alle selection d xs = take d xs ++ selection (d+1) ( drop d xs ) ok = acc == not (null as) let msg = vcat [ fsep [ text ( if ok then "Richtig:" else "Falsch:" ) , text "die Eingabe" <+> toDoc x , text "wurde" , text ( if null as then "nicht" else "" ) , text "akzeptiert." ] , text "einige Rechnungen der Maschine sind:" , nest 4 $ vcat $ take 3 $ map present $ logs ] if ok then inform msg else reject msg positiv_liste :: ( Machine m dat conf, ToDoc [dat] ) => Int -> m -> [dat] -> Reporter () positiv_liste cut m xss = do inform $ vcat [ text "Ich prüfe, daß jede dieser Eingaben akzeptiert wird:" , nest 4 $ toDoc xss ] check_liste True cut m xss negativ_liste :: ( Machine m dat conf, ToDoc [dat] ) => Int -> m -> [dat] -> Reporter () negativ_liste cut m xss = do inform $ vcat [ text "Ich prüfe, daß keine dieser Eingaben akzeptiert wird:" , nest 4 $ toDoc xss ] check_liste False cut m xss
florianpilz/autotool
src/Machine/Akzeptieren.hs
gpl-2.0
2,479
52
12
757
878
453
425
-1
-1
--- 9. ukol - #2 (ceasar) --- --- Petr Belohlavek --- import Data.Char -- caesar n slovo - prevede slovo na ceaserovskou sifru s posunem n -- funguje i na zaporna n -- prevedi mala pismena, velka pismena a cislice -- ostatni znaky necha jak jsou -- pr: ---- > caesar 3 "Caesar123,.!?" ---- "Fdhvdu456,.!?" ---- > caesar (-3) "Fdhvdu456,.!?" ---- "Caesar123,.!?" -- predpoklada, ze jednotlive abecedy a-z, A-Z, 0-9 ---- jsou v kodovani tesne za sebou caesar :: Int -> String -> String -- prazdna slova jsou trivialni caesar _ [] = [] -- slozena slova vzniknou rotaci prvniho znaku a rekurzivne se zbytekem slova caesar n (x:xs) | (isLower x) = [chr (((((ord x) - (ord 'a')) + n) `mod` ((ord 'z') - (ord 'a') + 1)) + (ord 'a'))] ++ (caesar n xs) | (isUpper x) = [chr (((((ord x) - (ord 'A')) + n) `mod` ((ord 'Z') - (ord 'A') + 1)) + (ord 'A'))] ++ (caesar n xs) | (isDigit x) = [chr (((((ord x) - (ord '0')) + n) `mod` ((ord '9') - (ord '0') + 1)) + (ord '0'))] ++ (caesar n xs) | True = [x] ++ (caesar n xs)
machl/NPRG005-non-procedural-programming
task9/caesar.hs
gpl-2.0
1,067
0
18
257
405
217
188
7
1
-- -*- mode: haskell -*- {-# LANGUAGE TemplateHaskell, DeriveDataTypeable, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses #-} module Boolean.Instance where -- $Id$ import Boolean.Op import qualified Autolib.TES.Binu as B import qualified Boolean.Equiv import Challenger.Partial import qualified Autolib.Reporter.Set import Data.Typeable import Autolib.ToDoc import Autolib.Multilingual import Autolib.Reader import Autolib.Reporter import Autolib.Set import Inter.Types data Boolean = Boolean deriving ( Eq, Ord, Typeable ) instance OrderScore Boolean where scoringOrder _ = Increasing $(derives [makeReader, makeToDoc] [''Boolean]) data BI = BI { formula :: Exp Bool , operators :: Set ( Op Bool ) } deriving ( Typeable ) $(derives [makeReader, makeToDoc] [''BI]) data BIC = BIC { formula_size :: Int , operators_in_instance :: B.Binu ( Op Bool ) , operators_in_solution :: Set ( Op Bool ) } deriving ( Typeable ) $(derives [makeReader, makeToDoc] [''BIC]) instance Partial Boolean BI ( Exp Bool ) where describe p i = vcat [ multitext [ (DE, "Gesucht ist ein aussagenlogischer Ausdruck, der äquivalent ist zu:") , (UK, "Find an expression in propositional logic that is equivalent to:") ] , nest 4 $ toDoc $ formula i , text "" , parens $ vcat [ multitext [ (DE, "die Baumstruktur dieses Ausdrucks ist:" ) , (UK, "the expression tree is:") ] , nest 4 $ draw $ formula i ] , multitext [ (DE, "und nur diese Operatoren enthält:") , (UK, "and which contains only these operators:") ] , nest 4 $ toDoc $ operators i ] initial p i = formula i partial p i b = do inform $ vcat [ multitext [ (DE, "Die Baumstruktur Ihrer Einsendung ist:") , (UK, "The tree structure of your submission is:") ] , nest 4 $ draw b , text "" ] Autolib.Reporter.Set.subeq ( parens $ multitext [ (DE, "benutzte Operatoren") , (UK, "operators used") ] , syms b ) ( parens $ multitext [ ( DE, "erlaubte Operatoren" ) , ( UK, "operators allowed" ) ] , operators i ) Autolib.Reporter.Set.subeq ( parens $ multitext [ (DE, "benutzte Variablen") , (UK, "variables used") ] , vars b ) ( parens $ multitext [ (DE, "Variablen der Aufgabenstellung") , (UK, "variables given") ] ,vars $ formula i ) total p i b = do Boolean.Equiv.check ( formula i ) b make :: Make make = direct Boolean $ BI { formula = read "x == (y == z)" , operators = mkSet $ read "[ false, true, !, ||, && ]" }
Erdwolf/autotool-bonn
src/Boolean/Instance.hs
gpl-2.0
2,652
64
16
690
781
438
343
68
1