code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
module Network.Linx.Gateway.BinaryList ( putList , getList ) where import Control.Monad (replicateM) import Data.Binary hiding (putList) import Network.Linx.Gateway.Types putList :: Binary a => [a] -> Put putList = mapM_ put getList :: Binary a => Length -> Get [a] getList len = replicateM (asInt len) get
kosmoskatten/linx-gateway
src/Network/Linx/Gateway/BinaryList.hs
mit
331
0
8
69
112
63
49
10
1
{-# LANGUAGE TemplateHaskell #-} module Server where -------------------- -- Global Imports -- import Prelude hiding (error) import Network.HTTP.Types.Status import Control.Monad.IO.Class import Data.Aeson.Types import Data.Aeson.TH import Data.IORef import Web.Scotty import Data.Char ------------------- -- Local Imports -- import Minimax import Static import qualified Board as B (state) import Board hiding (state) ---------- -- Code -- -- | A type to represent the @'Board'@ state. data PullResponse = PullResponse { over :: Bool , winner :: Int , turn :: Int , state :: [Int] } $(deriveJSON defaultOptions { constructorTagModifier = map toLower } ''PullResponse) -- | The type to represent a POST request to make a move. data PushRequest = PushRequest { row :: Int , col :: Int } $(deriveJSON defaultOptions { constructorTagModifier = map toLower } ''PushRequest) -- | A type to represent the response to API push requests. data PushResponse = PushResponse { error :: Bool , msg :: String , refresh :: Bool } $(deriveJSON defaultOptions { constructorTagModifier = map toLower } ''PushResponse) -- | Getting the home page. getHomePage :: ScottyM () getHomePage = get "/" $ do status $ ok200 setHeader "Content-Type" "text/html" file "views/home.html" -- | Pulling the current state from the server. getBoardState :: IORef Board -> ScottyM () getBoardState boardRef = get "/api/pull/state" $ do board <- liftIO $ readIORef boardRef json $ PullResponse { over = isOver board , winner = boardStateToInt $ findWinner board , turn = boardStateToInt $ determineTurn board , state = map boardStateToInt $ B.state board } -- | Dealing with a post request to reset the board. postResetBoard :: IORef Board -> ScottyM () postResetBoard boardRef = post "/api/push/reset" $ do liftIO $ writeIORef boardRef defaultBoard json $ PushResponse { error = False , msg = "Game reset!" , refresh = True } -- | Recovering from getting an invalid @'PushRequest'@. rescueFromPushRequest :: a -> ActionM () rescueFromPushRequest _ = json $ PushResponse { error = True , msg = "There was an error in processing the request." , refresh = False } -- | Dealing with a post request to perform a move. postPerformMove :: IORef Board -> ScottyM () postPerformMove boardRef = post "/api/push/move" $ (flip rescue) rescueFromPushRequest $ do postRequest <- jsonData :: ActionM PushRequest board <- liftIO $ readIORef boardRef let ePair = do (board', _) <- updateBoard ((row postRequest, col postRequest), X) board updateBoard (findOptimalMove O board', O) board' case ePair of Left message -> json $ PushResponse { error = False , msg = message , refresh = True } Right (board', message) -> do liftIO $ writeIORef boardRef board' json $ PushResponse { error = True , msg = message , refresh = True } -- | Responding to any request that doesn't get caught earlier on with a 404. handle404 :: ScottyM () handle404 = notFound $ do status $ notFound404 setHeader "Content-Type" "text/html" file "views/404.html" -- | The definition of the server itself. server :: IORef Board -> ScottyM () server boardRef = do serveStatic getHomePage getBoardState boardRef postResetBoard boardRef postPerformMove boardRef handle404
crockeo/tic-taskell
src/Server.hs
mit
4,152
0
17
1,473
846
449
397
85
2
{-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE CPP #-} module Data.Comparaptor.Ord.Tests (tests) where #define TEST(TYPE) testProperty "safeCompare TYPE" (testOrd :: TYPE -> TYPE -> Bool) import qualified Data.ByteString as StrictByteString import Test.Framework (Test, testGroup) import Test.Framework.Providers.QuickCheck2 (testProperty) import Test.QuickCheck (Arbitrary(..)) import Data.Comparaptor.Ord (SafeOrd(..)) type StrictByteString = StrictByteString.ByteString instance Arbitrary StrictByteString where arbitrary = fmap StrictByteString.pack arbitrary testOrd :: (SafeOrd a, Ord a) => a -> a -> Bool testOrd a b = expected == res where expected = a `compare` b res = a `safeCompare` b tests :: Test tests = testGroup "Data.Comparaptor.Ord.Tests" [ TEST(StrictByteString) ]
lambda-llama/comparaptor
tests/Data/Comparaptor/Ord/Tests.hs
mit
820
0
8
126
196
118
78
18
1
module Game.Process.Renderer where import Data.Maybe import Game.Types import Game.Output.Shapes import Game.Util class GameRenderer a where render :: ResolutionSettings -> (Double, a) -> RenderObject instance GameRenderer GameObject where render (_, renderScale) (time, gameObject) = shape where shape = case (oType gameObject) of Just (GameImage imgStr) -> image imgStr Just (GameAnimation dirStr imgCount imgSpeed) -> image $ sprite time dirStr imgCount imgSpeed _ -> error "render object type not supported" posY = renderScale * (oPositionY gameObject) image imgType = image_ imgType (renderScale, renderScale) Nothing & posY_ posY instance GameRenderer GameObjectColumn where render resSettings@(_, renderScale) (time, (GameObjectColumn posX objs)) = scene_ $ map renderObject $ filter objectCondition objs where renderObject obj = render resSettings (time, obj) & posX_ (renderScale * posX) objectCondition obj = isJust $ oType obj instance GameRenderer GameData where render resSettings@(windowSize, renderScale) (time, gameData@(GameData _ (GameSession player curLvl curGamePosX curTries progress progressBest sessionDone) _)) = renderObject where renderObject = scene_ $ backgroundShape ++ levelShape ++ playerShape ++ (if sessionDone then sessionDoneText else []) backgroundShape = [image_ "background" dWindowSize Nothing] levelShape = map renderColumn columns ++ levelText where levelText = [ text_ ("Level: " ++ show curLvl) 40 & pos_ (180 , y - 60) , text_ ("Tries: " ++ show curTries) 40 & pos_ (480, y - 60) , text_ ("Best: " ++ show progressBest ++ "%") 40 & pos_ (800, y - 60) , text_ ("Now: " ++ show progress ++ "%") 40 & pos_ (800, y - 110) ] playerShape = [image_ playerImage (renderScale, renderScale) Nothing & pos_ (toupleF (* renderScale) $ playerPos)] where playerPos = (pPosX player, pPosY player) playerImage | pV player == 0 = sprite time "player/run/" 3 10 | otherwise = "player/jump" sessionDoneText = [ text_ ("Level Done!") 100 & pos_ (250, y / 2) , text_ ("Press space to restart the level!") 40 & pos_ (200, (y / 2) - 60) ] renderColumn col@(GameObjectColumn posX _) = render resSettings $ (time, col { oPositionX = posX - curGamePosX }) columns = filter columnCondition $ currentGameLevel gameData where columnCondition column = and [ oPositionX column < curGamePosX + viewPort , oPositionX column > curGamePosX - 1 ] viewPort = x / renderScale dWindowSize@(x, y) = toupleF fromIntegral windowSize sprite :: Double -> String -> Int -> Double -> String sprite time dir imgCount imgsPerSec = dir ++ show spriteNumber where spriteNumber = (floor (imgsPerSec * time) `mod` imgCount) + 1
flomerz/SchaffschNie
src/Game/Process/Renderer.hs
mit
3,359
0
16
1,135
962
504
458
43
1
module Main where import Shared (primes) main :: IO () main = print $ sum $ takeWhile (< 2000000) primes
jBugman/euler
part1/p010.hs
mit
107
0
7
22
44
25
19
4
1
module Formatter (count) where import Data.IORef import Control.Monad.IO.Class import Test.Hspec.Formatters count :: IO Formatter count = do ref <- newIORef (0 :: Int) return silent { exampleSucceeded = \_ -> liftIO (modifyIORef ref succ) , footerFormatter = liftIO (readIORef ref) >>= writeLine . show }
beni55/hspec
hspec-discover/integration-test/with-io-formatter/Formatter.hs
mit
355
0
14
95
109
60
49
10
1
{-# LANGUAGE NoMonomorphismRestriction #-} module Plugins.Gallery.Gallery.Manual38 where import Diagrams.Prelude dot = circle 1 # fc black mkRow n = hcat' with {sep = 0.5} (replicate n dot) mkTri n = decoratePath (fromOffsets (replicate (n-1) (2.5 *^ unitX)) # rotateBy (1/6)) (map mkRow [n, n-1 .. 1]) example = mkTri 5
andrey013/pluginstest
Plugins/Gallery/Gallery/Manual38.hs
mit
372
0
12
101
142
76
66
10
1
{-# LANGUAGE FlexibleContexts #-} module Parser (Stack, Token(..), burlesque) where import Control.Applicative hiding ((<|>), many) import Data.List (intersperse) import Data.Monoid (mconcat) import Text.Parsec import Text.Printf (printf) data Token = BInt Int | BFloat Double | BString [Char] | BChar Char | BAdd | BReverse | BBlock [Token] | BBlockAccess | BExplode | BLength | BSwap | BDrop | BDup | BAppend | BPrepend deriving Eq instance Show Token where show (BInt i) = show i show (BFloat d) = printf "%f" d show (BString s) = "\"" ++ s ++ "\"" show (BChar c) = '\'':c:[] show BAdd = ".+" show BReverse = "<-" show BBlockAccess = "!!" show BExplode = "XX" show BLength = "L[" show BSwap = "\\/" show BDrop = "vv" show BDup = "^^" show BAppend = "[+" show BPrepend = "+]" show (BBlock ts) = "{" ++ (mconcat $ intersperse " " $ map show ts) ++ "}" (<++>) :: Applicative a => a [b] -> a [b] -> a [b] (<++>) = liftA2 (++) num :: Stream s m Char => ParsecT s u m Token num = comb <$> prefix <*> suffix where prefix = option "" (string "-") <++> many1 digit suffix = optionMaybe $ string "." <++> many1 digit comb i Nothing = BInt . read $ i comb i (Just f) = BFloat . read $ i ++ f str :: Stream s m Char => ParsecT s u m Token str = BString <$> between (char '"') (char '"') (many $ noneOf "\"") chr :: Stream s m Char => ParsecT s u m Token chr = BChar <$> (char '\'' *> anyChar) add :: Stream s m Char => ParsecT s u m Token add = BAdd <$ string ".+" rev :: Stream s m Char => ParsecT s u m Token rev = BReverse <$ string "<-" blockAccess :: Stream s m Char => ParsecT s u m Token blockAccess = BBlockAccess <$ string "!!" block :: Stream s m Char => ParsecT s u m Token block = fmap BBlock $ between prefix suffix toks where prefix = char '{' *> sp suffix = sp <* char '}' explode :: Stream s m Char => ParsecT s u m Token explode = BExplode <$ string "XX" len :: Stream s m Char => ParsecT s u m Token len = BLength <$ string "L[" swap :: Stream s m Char => ParsecT s u m Token swap = BSwap <$ string "\\/" drp :: Stream s m Char => ParsecT s u m Token drp = BDrop <$ string "vv" dup :: Stream s m Char => ParsecT s u m Token dup = BDup <$ string "^^" append :: Stream s m Char => ParsecT s u m Token append = BAppend <$ string "[+" prepend :: Stream s m Char => ParsecT s u m Token prepend = BPrepend <$ string "+]" sp :: Stream s m Char => ParsecT s u m () sp = skipMany $ char ' ' type Stack = [Token] toks :: Stream s m Char => ParsecT s u m [Token] toks = tok `sepBy` sp where tok = choice [num, str, chr, add, rev, blockAccess, block, explode, len, swap, drp, dup, append, prepend] burlesque :: Stream s m Char => ParsecT s u m Stack burlesque = reverse <$> toks <* eof
hgiddens/virtue
src/Parser.hs
mit
2,981
0
11
863
1,254
650
604
83
2
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} module Poi.Migrations.Migrate where import Control.Exception (finally, try, bracket) import Control.Monad (forM_, join, filterM, void) import Data.ByteString.Char8 (unpack) import Data.Char import Data.List (intercalate, isPrefixOf) import Data.Time import Database.PostgreSQL.Simple import Database.PostgreSQL.Simple.SqlQQ import GHC.Int (Int64) import System.Console.ANSI import System.Directory (getDirectoryContents, getCurrentDirectory, createDirectoryIfMissing, withCurrentDirectory) import System.FilePath ((</>)) import System.Process (callCommand) import Text.InterpolatedString.Perl6 (qc) import Text.RawString.QQ (r) import Poi.Migrations.Utils (fileNameFromTimeStamp, timeStampFromFileName, fuzzyFilter, colorPutStrLn) import Poi.Migrations.Types connectionInfo :: ConnectInfo connectionInfo = defaultConnectInfo { connectDatabase = "postgres" , connectPassword = "password" , connectUser = "postgres" } migrate :: MigrateOpts -> [Migration] -> Maybe String -> IO () migrate opts migrations ver = do conn <- connect $ connectInfo opts finally (maybe (case migration opts of Prepare -> prepareMigration conn New migName fileType -> createNewMigration migName fileType Up -> upMigration conn migrations Down -> downMigration conn migrations Redo -> redoMigration conn migrations) (\v -> runSpecificMigration conn (migration opts) migrations v) ver) (do --fileExists <- doesFileExist "Migrations/schema.sql" case migration opts of Up -> generatePGDump conn Down -> generatePGDump conn Redo -> generatePGDump conn _ -> return () close conn) where generatePGDump conn = join $ fmap (maybe (pgDump (opts) "No migrations applied") (pgDump (opts))) (lastRunMigration conn) prepareMigration :: Connection -> IO () prepareMigration conn = do void $ execute_ conn [r| CREATE OR REPLACE FUNCTION trg_update_modified_column() RETURNS TRIGGER AS $$ BEGIN NEW.updated_at = now(); RETURN NEW; END; $$ language 'plpgsql'; CREATE TABLE IF NOT EXISTS schema_migrations (version character varying(255) NOT NULL PRIMARY KEY); |] cd <- getCurrentDirectory let migrationsD = cd </> "Migrations" withCurrentDirectory cd (createDirectoryIfMissing False migrationsD) writeFile (cd </> "Migrations.hs") [r|#!/usr/bin/env stack {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -F -pgmF migrate-autoimporter #-} module Migrations where import Poi.Migrations.Types import Poi.Migrations.Migrate (migrate, connectionInfo) import Poi.Migrations.Utils (migArgs, readConfigWithDefault, dbConfig) runMigrations :: MigrateArgs -> IO () runMigrations (MigrateArgs mode env ver) = do config <- readConfigWithDefault env let opts = MigrateOpts mode (dbConfig config) env migrate opts migrations ver defaultMigrationArgs = MigrateArgs Up "lambda" Nothing main :: IO () main = migArgs runMigrations |] createNewMigration :: String -> FileType -> IO () createNewMigration migName fileType = do cd <- getCurrentDirectory let migrationsD = cd </> "Migrations" time <- getCurrentTime let moduleName = "M" ++ formatTime defaultTimeLocale timeFormat time ++ "_" ++ pascal migName case fileType of Hs -> do let migFile = migrationsD </> (moduleName ++ ".hs") putStrLn migFile writeFile migFile (([r|{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} |] ++ "module Migrations." ++ moduleName ++ " where \n") ++ fillerText) Sql -> do let migFile = migrationsD </> (moduleName ++ ".sql") putStrLn migFile writeFile migFile [r|-- Your migration statements go here |] Yaml -> do let migFile = migrationsD </> (moduleName ++ ".yml") putStrLn migFile writeFile migFile [r|# TODO: Insert your raw SQL in the corresponding blocks up: down: |] upMigration :: Connection -> [Migration] -> IO () upMigration conn migrations = do migs <- filterM (\(name, _) -> didMigrationRun name conn) migrations myForM_ migs (\mig -> withTransaction conn (runMigration conn Up mig)) where myForM_ :: [Migration] -> (Migration -> IO ()) -> IO () myForM_ [] _ = return () myForM_ [x@ (_, _)] f = do f x myForM_ (x:xs) f = do f x myForM_ xs f didMigrationRun :: String -> Connection -> IO Bool didMigrationRun name conn= do xs :: [Only String] <- query conn [sql|SELECT version FROM schema_migrations WHERE version = ? |] [timeStampFromFileName name] return (null xs) downMigration :: Connection -> [Migration] -> IO () downMigration conn migrations = do migName <- fmap (maybe (error "There was no last run migration to roll down.") (id)) (lastRunMigration conn) let mig = findMig migName migrations case mig of Nothing -> colorPutStrLn Red $ "Last run migration not found. Aborting." Just migRun -> withTransaction conn (runMigration conn Down migRun) runMigration :: Connection -> Mode -> Migration -> IO () runMigration conn mode m@(name,(up, down)) = case mode of Up -> do colorPutStrLn Yellow ("Running Migration up " ++ name) result <- try $ execute_ conn up :: IO (Either SqlError Int64) either (\a -> error $ "The Migration " ++ name ++ " could not be run. Aborting.\n" ++ (unpack $ sqlErrorMsg a)) (\b -> do void $ execute conn [r|INSERT INTO schema_migrations SELECT ? WHERE NOT EXISTS (SELECT version FROM schema_migrations WHERE version=?)|] (timeStampFromFileName name, timeStampFromFileName name) colorPutStrLn Green $ "The Migration " ++ name ++ " successfully ran. " ++ show b ++ " rows affected.") result Down -> do colorPutStrLn Yellow ("Running Migration down " ++ name) result <- try $ execute_ conn down :: IO (Either SqlError Int64) either (\a -> error $ "The Migration " ++ name ++ " could not be run. Aborting.\n" ++ (unpack $ sqlErrorMsg a)) (\b -> do void $ execute conn [r|DELETE FROM schema_migrations WHERE version=? |] [timeStampFromFileName name] colorPutStrLn Green $ "The Migration " ++ name ++ " successfully ran. " ++ show b ++ " rows affected.") result Redo -> do runMigration conn Down m runMigration conn Up m _ -> do putStrLn "You should have never reached this far" runSpecificMigration :: Connection -> Mode -> [Migration] -> String -> IO () runSpecificMigration conn mode migrations mig = do let matches = fuzzyFilter mig migrations case matches of [] -> putStrLn $ "Given " ++ mig ++ " didn't match any existing migrations." [x] -> withTransaction conn (runMigration conn mode x) xs -> putStrLn $ "Found these migrations, be more specific. \n" ++ intercalate "\n" (map (show . fst) xs) redoMigration :: Connection -> [Migration] -> IO () redoMigration conn migrations = do migName <- fmap (maybe (error "There was no last run migration to redo.") (id)) (lastRunMigration conn) let mig = findMig migName migrations case mig of Nothing -> colorPutStrLn Red $ "Last run migration not found. Aborting." Just migRun -> withTransaction conn $ do runMigration conn Down migRun runMigration conn Up migRun migrationStatus :: Connection -> IO () migrationStatus conn = do migName <- fmap (maybe (error "There was no last run migration to redo.") (id)) (lastRunMigration conn) mig <- fileNameFromTimeStamp migName migs <- migrationsToRun conn case mig of Nothing -> colorPutStrLn Yellow $ "No migrations run yet :|" Just name -> do colorPutStrLn Green $ [qc|Last applied migration is {name} :) |] if (null migs) then colorPutStrLn Green $ "All migrations are up-to-date" else do putStrLn $ "These migrations are yet to be run. \n" forM_ migs (colorPutStrLn Red) fillerText :: String fillerText = [r|import Database.PostgreSQL.Simple import Database.PostgreSQL.Simple.SqlQQ (sql) import Text.InterpolatedString.Perl6 (qc) import System.Environment migrate :: (Query, Query) migrate = (up, down) -- TODO: Insert your raw SQL just before the closing `| ])` tag up :: Query up = [qc| |] ++ "|]" ++ [r| -- TODO: Insert your raw SQL just before the closing `| ])` tag down :: Query down = [qc| |] ++ "|]\n" lastRunMigration :: Connection -> IO (Maybe String) lastRunMigration conn = do xs ::[Only String] <- query_ conn ("SELECT version FROM schema_migrations ORDER BY version DESC LIMIT 1") if null xs then return Nothing else return $ Just ((\(Only n) -> n) $ head xs) migrationsToRun :: Connection -> IO ([String]) migrationsToRun conn = do migrationFiles <- (filter (isPrefixOf "M")) <$> (getDirectoryContents "./Migrations") migs <- filterM (flip didMigrationRun conn) migrationFiles return migs timeFormat :: String timeFormat = "%Y%m%d%H%M%S" pascal :: String -> String pascal [] = [] pascal (x:xs) = toUpper x : pascal' xs where pascal' [] = [] pascal' [y] = [y] pascal' (y:ys) | y == '_' = y : toUpper (head ys) : pascal' (tail ys) | otherwise = y : pascal' ys pgDump :: MigrateOpts -> String -> IO () pgDump opts name = if env == "development" then callCommand ([qc| \{ echo "-- SCHEMA VERSION {name}" ; pg_dump -d '{db}' -s; pg_dump --data-only --table schema_migrations -d '{db}'; } > Migrations/schema.sql |]) else return () where env = environment opts db = (connectDatabase . connectInfo) opts findMig :: String -> [Migration] -> Maybe Migration findMig _ [] = Nothing findMig migname (m@(name, _) : migs) | migname == (timeStampFromFileName name) = Just m | otherwise = findMig migname migs prepareMigrationWithConfig :: ConnectInfo -> IO () prepareMigrationWithConfig connection = do bracket (connect connection) (close) (prepareMigration) migrationStatusWithConfig :: ConnectInfo -> IO () migrationStatusWithConfig connection = do bracket (connect connection) (close) (migrationStatus)
pranaysashank/poi
poi-bin/src/Poi/Migrations/Migrate.hs
mit
10,525
0
20
2,513
2,712
1,369
1,343
195
8
{-# LANGUAGE RankNTypes #-} module Jank.Interpret where import Jank.Types import Data.Aeson.Types hiding (parse, Parser) import Data.Aeson.Lens import Control.Lens hiding (argument, Empty, op) import qualified Data.Vector as Vector -- This could be refactored to use fold(l) if PrimOp was Foldable path :: AsValue t => PrimOp -> Traversal' t Value path Empty = _Value path (KeyAt k) = key (getKey k) path (IndexAt i) = nth (getIndex i) path AllElements = values path (opA :+: opB) = path opA . path opB interpret :: AsValue s => Expr -> s -> Maybe Value interpret (Get op) json = json ^? path op interpret (Set op val) json = (path op .~ val $ json) ^? _Value -- TODO: Clean up? interpret (GetIndexed op) json = Just $ Array $ Vector.fromList (json ^.. path op) interpret (SetIndexed op val) json = (path op .~ val $ json) ^? _Value
5outh/jank
src/Jank/Interpret.hs
mit
848
0
9
162
325
170
155
22
1
module Splitter where myWords :: String -> [String] myWords "" = [] myWords xs = let notEmpty = (/=) ' ' word = takeWhile notEmpty xs rest = dropWhile notEmpty xs next = if rest == [] then [] else tail rest in word : myWords next str = "hello world hello" firstSen = "Tyger Tyger, burning bright\n" secondSen = "In the forests of the night\n" thirdSen = "What immortal hand or eye\n" fourthSen = "Could frame thy fearful symmetry?" sentences = firstSen ++ secondSen ++ thirdSen ++ fourthSen myLines :: String -> [String] myLines "" = [] myLines xs = let notNewLine = (/=) '\n' line = takeWhile notNewLine xs rest = dropWhile notNewLine xs next = if rest == [] then [] else tail rest in line : myLines next splitOn :: Char -> String -> [String] splitOn char xs = let notChar = (/=) char first = takeWhile notChar xs rest = dropWhile notChar xs next = if rest == [] then [] else splitOn char (tail rest) in first : next
andrewMacmurray/haskell-book-solutions
src/ch9/Splitter.hs
mit
1,017
0
12
274
338
178
160
37
2
module Text.Greek.IO.Utility where import qualified Control.Lens as Lens import qualified Control.Monad.Except as Monad import qualified Text.Greek.Utility as Utility handleIOError :: Show a => IO (Either a b) -> Monad.ExceptT String IO b handleIOError x = Monad.liftIO x >>= handleError handleMaybe :: String -> Maybe a -> Monad.ExceptT String IO a handleMaybe s = handleError . Utility.maybeToEither s handleError :: Show a => Either a b -> Monad.ExceptT String IO b handleError (Left x) = Monad.throwError . show $ x handleError (Right x) = return x showError :: Show a => Either a b -> Either String b showError = Lens.over Lens._Left show
scott-fleischman/greek-grammar
haskell/greek-grammar/src/Text/Greek/IO/Utility.hs
mit
649
0
9
107
240
124
116
13
1
{-| Module: Sally.Config Description: Application configuration type and parser Maintainer: lawrence.dunn.iii@gmail.com License: MIT -} module Sally.Config ( Options.Applicative.execParser , module Sally.Config ) where import Control.Applicative ((<**>)) import Data.Monoid ((<>)) import Options.Applicative data AppConfig = AppConfig { sqliteFile :: String , port :: Int , logLevel :: Int } deriving (Show, Eq) defAppConfig :: AppConfig defAppConfig = AppConfig { sqliteFile = "sally.sqlite3" , port = 80 , logLevel = 9 } data Command = Initialize String | Run AppConfig deriving (Show) commandParserInfo = info commandParser idm commandParser :: Parser Command commandParser = subparser ( command "run" (Run <$> configParserInfo) <> command "initialize" (Initialize <$> initParserInfo) ) -- | Parser for "init" command initParser :: Parser String initParser = strOption ( long "database" <> metavar "DATAFILE" <> help "Sqlite3 database file to create" ) initParserInfo :: ParserInfo String initParserInfo = info (initParser <**> helper) ( fullDesc <> progDesc "Create a sqlite3 database to store user submissions" ) configParser :: Parser AppConfig configParser = AppConfig <$> strOption ( long "database" <> short 'd' <> metavar "DATAFILE" <> help "Sqlite3 database file" ) <*> option auto ( long "port" <> short 'p' <> help "port number" <> showDefault <> value 80 <> metavar "PORT" ) <*> option auto ( long "log" <> help "log verbosity" <> showDefault <> value 2 <> metavar "LOG" ) configParserInfo :: ParserInfo AppConfig configParserInfo = info (configParser <**> helper) ( fullDesc <> progDesc "Run a simple web game on port PORT using the Sqlite3 database DATAFILE" <> header "sally -- a simple web game" )
dunnl/sally
src/Sally/Config.hs
mit
2,123
0
14
663
444
234
210
60
1
{-# LANGUAGE OverloadedStrings #-} module InTheKnow.Routes.Home (routes) where import qualified InTheKnow.Routes.Home.Templates as Template import InTheKnow.Types import Web.Scotty.Blaze (blaze) import Web.Scotty index :: ItkM () index = do r <- renderer liftScotty $ get "/" (r "Home" Template.index) routes = index
jb55/intheknow
InTheKnow/Routes/Home.hs
mit
325
0
11
48
93
54
39
11
1
-- Copyright (c) 2004, 2008 Don Stewart - http://www.cse.unsw.edu.au/~dons -- | Vi keymap for Yi. -- Based on version 1.79 (7\/14\/97) of nex\/nvi -- -- The goal is strict vi emulation module Yi.Keymap.Vi ( keymap, ViMode ) where import Yi.Yi import Yi.Editor -- import Yi.UI as UI import Yi.History import Control.Arrow ((+++)) import Control.Exception ( ioErrors, try, evaluate ) import Control.Monad.State import Data.Char import Data.List ( (\\) ) import Prelude hiding ( any, error ) -- --------------------------------------------------------------------- type ViMode = ViProc () type ViProc a = (Interact Char) a -- -- | Top level. Lazily consume all the input, generating a list of -- actions, which then need to be forced -- -- NB . if there is a (bad) exception, we'll lose any new bindings.. iorefs? -- . also, maybe we shouldn't refresh automatically? -- keymap :: Keymap keymap = do write $ setWindowFillE '~' runVi cmd_mode runVi :: ViMode -> Keymap runVi = comap eventToChar ------------------------------------------------------------------------ -- The vi lexer is divided into several parts, roughly corresponding -- to the different modes of vi. Each mode is in turn broken up into -- separate lexers for each phase of key input in that mode. -- | command mode consits of simple commands that take a count arg - the -- count is stored in the lexer state. also the replace cmd, which -- consumes one char of input, and commands that switch modes. cmd_mode :: ViMode cmd_mode = choice [cmd_eval,eval cmd_move,cmd2other,cmd_op] eval :: ViProc Action -> ViMode eval p = do a <- p; write a -- -- | insert mode is either insertion actions, or the meta \ESC action -- ins_mode :: ViMode ins_mode = many' ins_char >> event '\ESC' >> return () -- -- | replace mode is like insert, except it performs writes, not inserts -- rep_mode :: ViMode rep_mode = many' rep_char >> event '\ESC' >> return () ------------------------------------------------------------------------ -- -- A parser to accumulate digits. -- typically what is needed for integer repetition arguments to commands -- -- ToDo don't handle 0 properly -- count :: ViProc (Maybe Int) count = option Nothing (many1' (satisfy isDigit) >>= return . Just . read) -- --------------------------------------------------------------------- -- | Movement commands -- -- The may be invoked directly, or sometimes as arguments to other -- /operator/ commands (like d). -- cmd_move :: ViProc Action cmd_move = do cnt <- count let x = maybe 1 id cnt choice [event c >> return (a x) | (c,a) <- moveCmdFM] +++ choice [do event c; c' <- anyButEsc; return (a x c') | (c,a) <- move2CmdFM] +++ (do event 'G'; return $ case cnt of Nothing -> botE >> moveToSol Just n -> gotoLn n) -- -- movement commands -- moveCmdFM :: [(Char, Int -> Action)] moveCmdFM = -- left/right [('h', left) ,('\^H', left) ,(keyBackspace, left) ,('\BS', left) ,('l', right) ,(' ', right) ,(keyHome, const firstNonSpaceE) -- vim does moveToSol ,('^', const firstNonSpaceE) ,('$', const moveToEol) ,('|', \i -> moveToSol >> rightOrEolE (i-1)) -- up/down ,('k', up) ,(keyUp, up) ,('\^P', up) ,('j', down) ,(keyDown, down) ,('\^J', down) ,('\^L', const refreshEditor) ,('\^N', down) ,('\r', down) -- words -- ToDo these aren't quite right, but are nice and simple ,('w', \i -> replicateM_ i $ do moveWhileE (isAlphaNum) GoRight moveWhileE (not.isAlphaNum) GoRight ) ,('b', \i -> replicateM_ i $ do moveWhileE (isAlphaNum) GoLeft moveWhileE (not.isAlphaNum) GoLeft ) -- text ,('{', prevNParagraphs) ,('}', nextNParagraphs) -- misc ,('H', \i -> downFromTosB (i - 1)) ,('M', const middleB) ,('L', \i -> upFromBosB (i - 1)) -- bogus entry ,('G', const (return ())) ] where left i = leftOrSolE i right i = rightOrEolE i up i = if i > 100 then gotoLnFromE (-i) else replicateM_ i (execB Move VLine Backward) down i = if i > 100 then gotoLnFromE i else replicateM_ i (execB Move VLine Forward) -- -- more movement commands. these ones are paramaterised by a character -- to find in the buffer. -- move2CmdFM :: [(Char, Int -> Char -> Action)] move2CmdFM = [('f', \i c -> replicateM_ i $ rightB >> moveWhileE (/= c) GoRight) ,('F', \i c -> replicateM_ i $ leftB >> moveWhileE (/= c) GoLeft) ,('t', \i c -> replicateM_ i $ rightB >> moveWhileE (/= c) GoRight >> leftB) ,('T', \i c -> replicateM_ i $ leftB >> moveWhileE (/= c) GoLeft >> rightB) ] -- -- | Other command mode functions -- cmd_eval :: ViMode cmd_eval = do cnt <- count let i = maybe 1 id cnt choice [event c >> write (a i) | (c,a) <- cmdCmdFM ] +++ (do event 'r'; c <- anyButEscOrDel; write (writeE c)) +++ (events ">>" >> write (do replicateM_ i $ moveToSol >> mapM_ insertN " " firstNonSpaceE)) +++ (events "<<" >> write (do moveToSol replicateM_ i $ replicateM_ 4 $ readB >>= \k -> when (isSpace k) deleteN 1 firstNonSpaceE)) +++ (events "ZZ" >> write (viWrite >> quitEditor)) where anyButEscOrDel = oneOf $ any' \\ ('\ESC':delete') -- -- cmd mode commands -- cmdCmdFM :: [(Char, Int -> Action)] cmdCmdFM = [('\^B', upScreensB) ,('\^F', downScreensB) ,('\^G', const viFileInfo) ,('\^W', const nextWinE) ,('\^Z', const suspendEditor) ,('D', killLineE) ,('J', const (moveToEol >> deleteN 1)) -- the "\n" ,('n', const (doSearch Nothing [] GoRight)) ,('X', \i -> do p <- getSelectionMarkPointB leftOrSolE i q <- getSelectionMarkPointB -- how far did we really move? when (p-q > 0) $ deleteNE (p-q) ) ,('x', \i -> do p <- getSelectionMarkPointB -- not handling eol properly rightOrEolE i q <- getSelectionMarkPointB gotoPointE p when (q-p > 0) $ deleteNE (q-p) ) ,('p', (const $ getRegE >>= \s -> moveToEol >> insertN '\n' >> mapM_ insertN s >> moveToSol)) -- ToDo insertNE ,(keyPPage, upScreensB) ,(keyNPage, downScreensB) ,(keyLeft, leftOrSolE) -- not really vi, but fun ,(keyRight, rightOrEolE) ] -- -- | So-called 'operators', which take movement actions as arguments. -- -- How do we achive this? We look for the known operator chars -- (op_char), followed by digits and one of the known movement commands. -- We then consult the lexer table with digits++move_char, to see what -- movement commands they correspond to. We then return an action that -- performs the movement, and then the operator. For example, we 'd' -- command stores the current point, does a movement, then deletes from -- the old to the new point. -- -- We thus elegantly achieve things like 2d4j (2 * delete down 4 times) -- Lazy lexers - you know we're right (tm). -- cmd_op :: ViMode cmd_op = do cnt <- count let i = maybe 1 id cnt choice $ [events "dd" >> write (moveToSol >> killE >> deleteN 1), events "yy" >> write (readLnE >>= setRegE)] ++ [do event c; m <- cmd_move; write (a i m) | (c,a) <- opCmdFM] where -- | operator (i.e. movement-parameterised) actions opCmdFM :: [(Char,Int -> Action -> Action)] opCmdFM = [('d', \i m -> replicateM_ i $ do (p,q) <- withPointMove m deleteNE (max 0 (abs (q - p) + 1)) -- inclusive ), ('y', \_ m -> do (p,q) <- withPointMove m s <- (if p < q then readNM p q else readNM q p) setRegE s -- ToDo registers not global. ) ,('~', const invertCase) -- not right. ] -- invert the case of range described by movement @m@ -- could take 90s on a 64M file. invertCase m = do (p,q) <- withPointMove m mapRangeE (min p q) (max p q) $ \c -> if isUpper c then toLower c else toUpper c -- -- A strange, useful action. Save the current point, move to -- some xlocation specified by the sequence @m@, then return. -- Return the current, and remote point. -- withPointMove :: Action -> EditorM (Int,Int) withPointMove m = do p <- getSelectionMarkPointB m q <- getSelectionMarkPointB when (p < q) $ gotoPointE p return (p,q) -- -- | Switch to another vi mode. -- -- These commands transfer control to another -- process. Some of these commands also perform an action before switching. -- cmd2other :: ViMode cmd2other = do c <- modeSwitchChar case c of ':' -> ex_mode ":" 'R' -> rep_mode 'i' -> ins_mode 'I' -> write moveToSol >> ins_mode 'a' -> write (rightOrEolE 1) >> ins_mode 'A' -> write moveToEol >> ins_mode 'o' -> write (moveToEol >> insertN '\n') >> ins_mode 'O' -> write (moveToSol >> insertN '\n' >> (execB Move VLine Backward)) >> ins_mode 'c' -> write (not_implemented 'c') >> ins_mode 'C' -> write (killLineE) >> ins_mode 'S' -> write (moveToSol >> readLnE >>= setRegE >> killE) >> ins_mode '/' -> ex_mode "/" '\ESC'-> write msgClr s -> write $ errorEditor ("The "++show s++" command is unknown.") where modeSwitchChar = oneOf ":RiIaAoOcCS/?\ESC" -- --------------------------------------------------------------------- -- | vi insert mode -- ins_char :: ViMode ins_char = write . fn =<< anyButEsc where fn c = case c of k | isDel k -> leftB >> deleteN 1 | k == keyPPage -> upScreenB | k == keyNPage -> downScreenB | k == '\t' -> mapM_ insertN " " -- XXX _ -> insertN c -- --------------------------------------------------------------------- -- | vi replace mode -- -- To quote vi: -- In Replace mode, one character in the line is deleted for every character -- you type. If there is no character to delete (at the end of the line), the -- typed character is appended (as in Insert mode). Thus the number of -- characters in a line stays the same until you get to the end of the line. -- If a <NL> is typed, a line break is inserted and no character is deleted. -- -- ToDo implement the undo features -- rep_char :: ViMode rep_char = write . fn =<< anyButEsc where fn c = case c of k | isDel k -> leftB >> deleteN 1 | k == keyPPage -> upScreenB | k == keyNPage -> downScreenB '\t' -> mapM_ insertN " " -- XXX '\r' -> insertN '\n' _ -> do e <- atEolE if e then insertN c else writeE c >> rightB -- --------------------------------------------------------------------- -- Ex mode. We also process regex searching mode here. spawn_ex_buffer :: String -> Action spawn_ex_buffer prompt = do initialBuffer <- gets currentBuffer Just initialWindow <- getWindow -- The above ensures that the action is performed on the buffer that originated the minibuffer. let closeMinibuffer = do b <- gets currentBuffer; closeWindow; deleteBuffer b anyButDelNlArrow = oneOf $ any' \\ (enter' ++ delete' ++ ['\ESC',keyUp,keyDown]) ex_buffer_finish = do historyFinish lineString <- readAllE closeMinibuffer -- UI.setWindow initialWindow switchToBufferE initialBuffer ex_eval (head prompt : lineString) ex_process :: ViMode ex_process = choice [do c <- anyButDelNlArrow; write $ insertNE [c], do enter; write ex_buffer_finish, do event '\ESC'; write closeMinibuffer, do delete; write bdeleteB, do event keyUp; write historyUp, do event keyDown; write historyDown] historyStart spawnMinibufferE prompt (const $ runVi $ forever ex_process) (return ()) ex_mode :: String -> ViMode ex_mode = write . spawn_ex_buffer -- | eval an ex command to an Action, also appends to the ex history ex_eval :: String -> Action ex_eval cmd = do case cmd of -- regex searching ('/':pat) -> doSearch (Just pat) [] GoRight -- TODO: We give up on re-mapping till there exists a generic Yi mechanism to do so. -- add mapping to command mode (_:'m':'a':'p':' ':_cs) -> error "Not yet implemented." -- add mapping to insert mode (_:'m':'a':'p':'!':' ':_cs) -> error "Not yet implemented." -- unmap a binding from command mode (_:'u':'n':'m':'a':'p':' ':_cs) -> error "Not yet implemented." -- unmap a binding from insert mode (_:'u':'n':'m':'a':'p':'!':' ':_cs) -> error "Not yet implemented." -- just a normal ex command (_:src) -> fn src -- can't happen, but deal with it [] -> (return ()) where fn "" = msgClr fn s@(c:_) | isDigit c = do e <- lift $ try $ evaluate $ read s case e of Left _ -> errorEditor $ "The " ++show s++ " command is unknown." Right lineNum -> gotoLn lineNum fn "w" = viWrite fn ('w':' ':f) = viWriteTo f fn "q" = do b <- isUnchangedB if b then closeWindow else errorEditor $ "File modified since last complete write; "++ "write or use ! to override." fn "q!" = closeWindow fn "$" = botE fn "wq" = viWrite >> closeWindow fn "n" = nextBufW fn "p" = prevBufW fn ('s':'p':_) = splitE fn ('e':' ':f) = fnewE f fn ('s':'/':cs) = viSub cs fn "reboot" = rebootE -- ! fn "reload" = reloadEditor >> return () -- ! fn s = errorEditor $ "The "++show s++ " command is unknown." ------------------------------------------------------------------------ not_implemented :: Char -> Action not_implemented c = errorEditor $ "Not implemented: " ++ show c -- --------------------------------------------------------------------- -- Misc functions viFileInfo :: Action viFileInfo = do bufInfo <- bufInfoB msgEditor $ showBufInfo bufInfo where showBufInfo :: BufferFileInfo -> String showBufInfo bufInfo = concat [ show $ bufInfoFileName bufInfo , " Line " , show $ bufInfoLineNo bufInfo , " [" , bufInfoPercent bufInfo , "]" ] -- | Try to write a file in the manner of vi\/vim -- Need to catch any exception to avoid losing bindings viWrite :: Action viWrite = do mf <- fileNameE case mf of Nothing -> errorEditor "no file name associate with buffer" Just f -> do bufInfo <- bufInfoB let s = bufInfoFileName bufInfo let msg = msgEditor $ show f ++" "++show s ++ "C written" catchJustE ioErrors (fwriteToE f >> msg) (msgEditor . show) -- | Try to write to a named file in the manner of vi\/vim viWriteTo :: String -> Action viWriteTo f = do let f' = (takeWhile (/= ' ') . dropWhile (== ' ')) f bufInfo <- bufInfoB let s = bufInfoFileName bufInfo let msg = msgEditor $ show f'++" "++show s ++ "C written" catchJustE ioErrors (fwriteToE f' >> msg) (msgEditor . show) -- | Try to do a substitution viSub :: String -> Action viSub cs = do let (pat,rep') = break (== '/') cs (rep,opts) = case rep' of [] -> ([],[]) (_:ds) -> case break (== '/') ds of (rep'', []) -> (rep'', []) (rep'', (_:fs)) -> (rep'',fs) case opts of [] -> do_single pat rep ['g'] -> do_single pat rep _ -> do_single pat rep-- TODO where do_single p r = do s <- searchAndRepLocal p r if not s then errorEditor ("Pattern not found: "++p) else msgClr {- -- inefficient. we recompile the regex each time. -- stupido do_line p r = do let loop i = do s <- searchAndRepLocal p r if s then loop (i+1) else return i s <- loop (0 :: Int) if s == 0 then msgEditor ("Pattern not found: "++p) else msgClr -} -- --------------------------------------------------------------------- -- | Handle delete chars in a string -- {- clean :: String -> String clean (_:c:cs) | isDel c = clean cs clean (c:cs) | isDel c = clean cs clean (c:cs) = c : clean cs clean [] = [] -} -- | Is a delete sequence isDel :: Char -> Bool isDel '\BS' = True isDel '\127' = True isDel c | c == keyBackspace = True isDel _ = False -- --------------------------------------------------------------------- -- | character ranges -- delete, enter, anyButEsc :: ViProc Char enter = oneOf enter' delete = oneOf delete' anyButEsc = oneOf $ (keyBackspace : any' ++ cursc') \\ ['\ESC'] enter', any', delete' :: String enter' = ['\n', '\r'] delete' = ['\BS', '\127', keyBackspace ] any' = ['\0' .. '\255'] cursc' :: String cursc' = [keyPPage, keyNPage, keyLeft, keyRight, keyDown, keyUp]
codemac/yi-editor
src/Yi/Keymap/Vi.hs
gpl-2.0
18,566
7
20
6,189
4,564
2,415
2,149
300
24
{-# LANGUAGE CPP #-} {- | Module : ./atermlib/src/ATerm/SimpPretty.hs Description : simple pretty printing combinators Copyright : (c) Klaus Luettich, C. Maeder Uni Bremen 2002-2005 License : GPLv2 or higher, see LICENSE.txt Maintainer : Christian.Maeder@dfki.de Stability : provisional Portability : portable Rather than using (slow, sequential) strings create (fast, tree-like) documents and render them later as text for IO. A very simplified version of John Hughes's and Simon Peyton Jones's Pretty Printer Combinators. Only catenable string sequences are left over. -} module ATerm.SimpPretty ( -- * The document type SDoc, -- Abstract -- * Primitive documents empty, comma, -- * Converting values into documents text, -- * Wrapping documents in delimiters parens, brackets, braces, -- * Combining documents (<>), -- * Rendering documents render, fullRender, writeFileSDoc ) where #if __GLASGOW_HASKELL__ >= 803 import Prelude hiding ((<>)) #endif import System.IO infixl 6 <> {- --------------------------------------------------------------------------- The interface -} -- The primitive SDoc values text :: String -> SDoc text = Text empty :: SDoc -- ^ An empty document empty = text "" comma :: SDoc -- ^ A ',' character comma = text "," parens :: SDoc -> SDoc -- ^ Wrap document in @(...)@ parens p = text "(" <> p <> text ")" braces :: SDoc -> SDoc -- ^ Wrap document in @{...}@ braces p = text "{" <> p <> text "}" brackets :: SDoc -> SDoc -- ^ Wrap document in @[...]@ brackets p = text "[" <> p <> text "]" -- Horizontal composition @<>@ (<>) :: SDoc -> SDoc -> SDoc -- ^Beside (<>) = Beside -- Displaying @SDoc@ values. instance Show SDoc where showsPrec = const showSDoc -- | Renders the document as a string using the default style render :: SDoc -> String render doc = showSDoc doc "" {- --------------------------------------------------------------------------- The SDoc data type -} -- | The abstract type of documents data SDoc = Text String | Beside SDoc SDoc {- --------------------------------------------------------------------------- simple layout -} writeFileSDoc :: FilePath -> SDoc -> IO () writeFileSDoc fp sd = do h <- openFile fp WriteMode fullRender (hPutStr h) (>>) sd hClose h showSDoc :: SDoc -> String -> String showSDoc = fullRender showString (.) fullRender :: (String -> a) -> (a -> a -> a) -> SDoc -> a fullRender txt comp = lay where lay (Text s) = txt s lay (Beside p q) = lay p `comp` lay q
spechub/Hets
atermlib/src/ATerm/SimpPretty.hs
gpl-2.0
2,642
0
9
605
479
268
211
43
2
{-#LANGUAGE DeriveDataTypeable#-} {-# LANGUAGE BangPatterns #-} module SSHClient where import Control.Concurrent.HEP as H import Control.Concurrent import Foreign.Marshal.Alloc import Foreign.Ptr import Foreign.C.Types import System.IO as Sys import Data.ByteString.Char8 as C import Data.Typeable import System.Process as P import Control.Monad import Control.Monad.Trans import Control.Monad.Trans.Either import System.Exit import Data.HProxy.Rules import System.Timeout sshclient = "setsid" startSSHClient:: Destination -> String -> String -> (ByteString-> HEP ()) -> (ByteString-> HEP ()) -> (HEP ()) -> HEP Pid startSSHClient (DestinationAddrPort (IPAddress ip) port) username params onRead onError onExit = do prog <- startProgram sshclient [ "ssh" -- , "-n" , username++"@" ++ ip , "-p " ++ show port , params] onRead onError onExit return prog bufferSize = 64 * 1024 data ProgramState = ProgramState { progHIn:: Handle , progHOut:: Handle , progHErr:: Handle , progHandle:: ProcessHandle , progSupervisor:: Pid } deriving Typeable instance HEPLocalState ProgramState data ReaderState = ReaderState { readerBuffer:: Ptr CChar } deriving Typeable instance HEPLocalState ReaderState data WorkerMessage = WorkerStarted ProgramState | WorkerStopped ExitCode deriving Typeable instance Message WorkerMessage data WorkerCommand = WorkerStop deriving Typeable instance Message WorkerCommand data SupervisorState = SupervisorState { superWorkerState:: ProgramState , superReadout :: Pid , superReaderr :: Pid } deriving Typeable instance HEPLocalState SupervisorState data SupervisorCommand = SupervisorStop | SupervisorWrite String deriving Typeable instance Message SupervisorCommand data SupervisorFeedback = SupervisorStarted deriving Typeable instance Message SupervisorFeedback startProgram:: String -- cmd -> [String] --params -> (ByteString-> HEP ()) -- on read stdout -> (ByteString-> HEP ()) -- on read stderr -> HEP () -> HEP Pid startProgram cmd args onRead onError onExit = do inbox <- liftIO newMBox sv <- spawn $! procWithBracket (progSupInit cmd args inbox onRead onError) (onExit >> progSupShutdown) $! H.proc $! supervisorWorker mmsg <- liftIO $! receiveMBoxAfter 10000 inbox return sv progSupInit cmd args outbox onRead onError = do me <- self worker <- spawn $! procWithSubscriber me $! procWithBracket (progInit me cmd args) (progShutdown) $! H.proc $! progWorker addSubscribe worker mmsg <- receiveAfter 10000 case mmsg of Nothing-> procFinished Just mls-> do case fromMessage mls of Nothing-> procFinished Just (WorkerStarted ls) -> do readStdout <- spawn $! procWithSubscriber me $! procWithBracket readerInit readerShutdown $! H.proc $! readerWorker (progHOut ls) onRead readStderr <- spawn $! procWithSubscriber me $! procWithBracket readerInit readerShutdown $! H.proc $! readerWorker (progHErr ls) onError setLocalState $! Just $! SupervisorState { superWorkerState = ls , superReadout = readStdout , superReaderr = readStderr } liftIO $! sendMBox outbox $! SupervisorStarted procRunning progInit:: Pid-> String-> [String]-> HEPProc progInit sv cmd args = do (Just hin, Just hout, Just herr, hcmd) <- liftIO $! createProcess (P.proc cmd args ) { std_in = CreatePipe, std_out = CreatePipe , std_err = CreatePipe} let ls = ProgramState { progHIn = hin , progHOut = hout , progHErr = herr , progHandle = hcmd , progSupervisor = sv } setLocalState $! Just ls send sv $! WorkerStarted ls procRunning progWorker:: HEPProc progWorker = do mmsg <- receiveAfter 1000 Just ls <- localState case mmsg of Just msg -> do case fromMessage msg of Nothing-> procRunning Just WorkerStop-> do liftIO $! terminateProcess $! progHandle ls procRunning Nothing-> do mexit <- liftIO $! getProcessExitCode $! progHandle ls case mexit of Nothing-> procRunning Just somecode -> do send (progSupervisor ls) $! WorkerStopped somecode procFinished progShutdown:: HEPProc progShutdown = do Just ls <- localState liftIO $! do Sys.putStrLn $! "shutting down ssh client" hClose $! progHErr ls hClose $! progHIn ls hClose $! progHOut ls terminateProcess $! progHandle ls procFinished progSupShutdown = procFinished readerInit:: HEPProc readerInit = do buff <- liftIO $! mallocBytes bufferSize setLocalState $! Just $! ReaderState { readerBuffer = buff } procRunning readerShutdown:: HEPProc readerShutdown =do Just ls <- localState liftIO $! free $! readerBuffer ls procFinished readerWorker:: Handle -> (ByteString-> HEP ()) -> HEPProc readerWorker h onRead = do Just ls <- localState let ptr = readerBuffer ls !mread <- liftIO $! timeout 1000000 $! hGetBufSome h ptr bufferSize case mread of Nothing-> procRunning Just read -> case read of 0 -> procFinished _ -> do str <- liftIO $! packCStringLen ( ptr, read) onRead str procRunning supervisorWorker:: HEPProc supervisorWorker = do msg <- receive let handleChildLinkMessage:: Maybe LinkedMessage -> EitherT HEPProcState HEP HEPProcState handleChildLinkMessage Nothing = lift procRunning >>= right handleChildLinkMessage (Just (ProcessFinished pid)) = left =<< lift (do subscribed <- getSubscribed case subscribed of [] -> procFinished _ -> procRunning ) handleServiceMessage:: Maybe SupervisorMessage -> EitherT HEPProcState HEP HEPProcState handleServiceMessage Nothing = lift procRunning >>= right handleServiceMessage (Just (ProcWorkerFailure cpid e _ outbox)) = do left =<< lift (do procFinish outbox procRunning ) handleServiceMessage (Just (ProcInitFailure cpid e _ outbox)) = left =<< lift ( do procFinish outbox procRunning ) handleSupervisorCommand:: Maybe SupervisorCommand-> EitherT HEPProcState HEP HEPProcState handleSupervisorCommand Nothing = right =<< lift procRunning handleSupervisorCommand (Just SupervisorStop) = do left =<< lift (do liftIO $! Sys.putStrLn $! "stopping ssh client" subscribed <- getSubscribed forM subscribed $! \pid -> send pid $! WorkerStop procRunning ) handleSupervisorCommand (Just (SupervisorWrite str)) = do left =<< lift (do Just ls <- localState liftIO $! Sys.hPutStr (progHIn $! superWorkerState ls) str procRunning ) mreq <- runEitherT $! do handleChildLinkMessage $! fromMessage msg handleServiceMessage $! fromMessage msg handleSupervisorCommand $! fromMessage msg case mreq of Left some -> return some Right some -> return some writeInput:: Pid-> String-> HEP () writeInput pid str = do send pid $! SupervisorWrite str return () stopSSHClient:: Pid-> HEP () stopSSHClient pid = do send pid $! SupervisorStop
dambaev/hproxy
src/SSHClient.hs
gpl-2.0
8,300
0
22
2,783
2,092
1,027
1,065
223
8
evalZ :: Expr -> Integer evalZ RZero = 0 evalZ ROne = 1 evalZ (RAdd e1 e2) = evalZ e1 + evalZ e2 evalZ (RMul e1 e2) = evalZ e1 * evalZ e2 evalZ (RNeg e) = -(evalZ e)
hmemcpy/milewski-ctfp-pdf
src/content/3.8/code/haskell/snippet06.hs
gpl-3.0
184
0
7
57
100
48
52
6
1
{-# LANGUAGE OverloadedStrings #-} ------------------------------------------------------------------------------- -- | -- Module : OpenSandbox.World -- Copyright : (c) 2016 Michael Carpenter -- License : GPL3 -- Maintainer : Michael Carpenter <oldmanmike.dev@gmail.com> -- Stability : experimental -- Portability : portable -- ------------------------------------------------------------------------------- module OpenSandbox.World ( module OpenSandbox.World.Chunk , module OpenSandbox.World.Flat , World , WorldType (..) , newWorld , genWorld , pullWorld ) where import OpenSandbox.World.Chunk import OpenSandbox.World.Flat import Control.Concurrent.STM import Data.Int import qualified Data.Map.Lazy as ML import OpenSandbox.Config import OpenSandbox.Event data World = World { _wInbox :: TQueue WorldCommand , _wOutbox :: TQueue Event , _worldStorage :: WorldStorage } data WorldCommand type WorldStorage = ML.Map (Int32,Int32) ChunkColumn newWorld :: WorldType -> Config -> STM (Either String World) newWorld worldType config = do inbox <- newTQueue outbox <- newTQueue let eitherStorage = genWorld worldType config case eitherStorage of Left err -> return $ Left err Right storage -> return $ Right $ World inbox outbox storage genWorld :: WorldType -> Config -> Either String WorldStorage genWorld worldType config = case worldType of Default -> Left "Error: No implemented world gen for Default!" Flat -> ML.fromList <$> ((\layers -> genFlatWorld layers (srvViewDistance config)) =<< (mkChunkLayers classicFlatPreset)) LargeBiomes -> Left "Error: No implemented world gen for LargeBiomes!" Amplified -> Left "Error: No implemented world gen for Amplified!" pullWorld :: World -> [ChunkColumn] pullWorld (World _ _ storage)= ML.elems storage
oldmanmike/opensandbox
src/OpenSandbox/World.hs
gpl-3.0
1,842
0
15
315
396
218
178
-1
-1
{-# LANGUAGE OverloadedStrings #-} module Css.Common (common) where import Clay import Prelude hiding ((**)) import Data.Monoid import Css.Constants {- common - Generates CSS common to all pages. -} common :: Css common = do html ? do margin0 padding0 width100 height100 overflowY auto body ? do margin0 padding0 width100 height100 minHeight $ pct 100 fontSize $ pt 17 fontFamily ["Trebuchet MS", "Arial"] [sansSerif] headerCSS aDefaultCSS disclaimerCSS modalCSS {- headerCSS - Generates the CSS for the header located at the top - of every page -} headerCSS :: Css headerCSS = do ".header" ? do margin0 padding 0 (em 0.5) 0 (em 0.5) backgroundColor $ purple10 border solid (px 1) black color white img ? do display inlineBlock margin 0 0 (px 5) 0 height (px 50) "#nav-links" ? do "list-style" -: "none" minWidth (px 687) paddingTop (px 10) margin nil nil nil nil display inlineBlock a ? do fontWeight normal li <? do textAlign $ alignSide sideCenter display inlineBlock padding 0 (px 10) 0 (px 10) a <? do color white "text-shadow" -: "0 0 2px #000, 0 0 2px #000, 0 0 2px #000, 0 0 2px #000, 0 0 2px #000, 0 0 2px #000, 0 0 2px #000, 0 0 2px #000, 0 0 2px #000, 0 0 2px #000, 0 0 2px #000, 0 0 2px #000, 0 0 2px #000, 0 0 2px #000, 0 0 2px #000, 0 0 2px #000, 0 0 2px #000, 0 0 2px #000, 0 0 2px #000, 0 0 2px #000;" hover & do color darkgray height (px 50) position absolute "#nav-fb" ? do float floatRight height (px 50) "#nav-fb-post" ? do backgroundColor blueFb height (px 40) margin (px 5) (px 10) (px 5) (px 10) padding nil (px 5) nil (px 5) lineHeight (px 40) verticalAlign middle display none a <? do color white borderRadius (px 3) (px 3) (px 3) (px 3) cursor pointer ".fb-login-button" ? do height (px 40) verticalAlign middle width (px 140) overflow hidden margin (px 5) nil (px 5) nil "#courseography-header" ? do width (px 280) height (px 50) paddingBottom (px 3) "#nav-export" ? do cursor pointer {- aDefaultCSS - Generates default CSS. -} aDefaultCSS :: Css aDefaultCSS = do a <> a # hover <> a # visited <> a # active ? do fontWeight bold textDecoration none color $ parse "#4C004C" {- disclaimerCSS - Generates CSS for the disclaimer located at the foot - of all pages. -} disclaimerCSS :: Css disclaimerCSS = "#disclaimerDiv" ? do padding 0 (em 1) 0 (em 1) fontSize (pt 11) {- modalCSS - Generates CSS for the modal that appears - when nodes in the graph are clicked. -} modalCSS :: Css modalCSS = do ".ui-dialog" ? do outline solid (px 0) black color black overflowX hidden overflowY auto backgroundColor white boxShadow (px 8) (px 8) (px 8) black ".ui-widget-overlay" ? do height100 width100 position fixed left nil top nil ".modal-header" ? do color blue3 ".modal-body" ? do overflowY scroll height (px 360) p ? do fontSize (pt 12) margin (pt 5) 0 (pt 5) 0 lineHeight (em 1.3) textAlign $ alignSide sideLeft ".ui-dialog-titlebar" ? do color blue3 cursor move paddingLeft (px 25) height (em 1.8) lineHeight (em 1.8) fontSize (em 1) borderBottom solid (px 1) black ".ui-dialog-titlebar-close" ? do display none ".ui-width-overlay" ? do height100 width100 left nil position fixed top nil ".ui-dialog" ? do tr ? do margin nil auto nil auto "#course-video-div" ? do margin (pt 5) 0 (pt 5) 0 width100 height100 "#course-video" ? do width100 height100 -- new modal CSS, need to remove above later ".modal-header" ? do color blue3 padding0 paddingLeft (px 25) lineHeight (em 1.8) fontSize (em 1) borderBottom solid (px 1) black textAlign $ alignSide sideLeft fbModalCSS fbModalCSS :: Css fbModalCSS = do "#post-image" ? do borderRadius (px 5) (px 5) (px 5) (px 5) margin nil auto (px 10) auto maxWidth (pct 100) "#modal-buttons" ? do float floatRight margin (px 20) auto (px 20) auto ".btn" ? do margin nil (px 5) nil (px 5)
bell-kelly/courseography
app/Css/Common.hs
gpl-3.0
5,121
0
19
2,052
1,509
653
856
167
1
module Lambdacula ( module Lambdacula.Action, module Lambdacula.GameData, module Lambdacula.World, module Lambdacula.Parser, module Lambdacula.Display ) where import Lambdacula.Action as Action import Lambdacula.GameData as Gamedata import Lambdacula.World as World import Lambdacula.Parser as Parser import Lambdacula.Display as Display
Raveline/lambdacula
src/Lambdacula.hs
gpl-3.0
359
0
5
56
71
49
22
11
0
{- Bool is a set with 2 values T, F possible functions T -> F - not F -> T - not T -> T - id F -> F - id * -> T - true * -> F - false -} -- not == complement complement :: Bool -> Bool complement True = False complement False = True -- id == constant constant :: Bool -> Bool constant x = x true :: Bool -> Bool true _ = True false :: Bool -> Bool false _ = False bottom :: Bool -> Bool bottom _ = undefined main :: IO() main = do putStrLn "constant: " putStrLn $ "\tTrue -> " ++ (show $ constant True) putStrLn $ "\tFalse -> " ++ (show $ constant False) putStrLn "complement:" putStrLn $ "\tTrue -> " ++ (show $ complement True) putStrLn $ "\tFalse -> " ++ (show $ complement False) putStrLn "true:" putStrLn $ "\tTrue -> " ++ (show $ true True) putStrLn $ "\tFalse -> " ++ (show $ true False) putStrLn "false:" putStrLn $ "\tTrue -> " ++ (show $ false True) putStrLn $ "\tFalse -> " ++ (show $ false False) putStrLn "bottom:" putStrLn "\t(Attempting to call 'bottom' short circuits the monad, and we get no output.)"
sujeet4github/MyLangUtils
CategoryTheory_BartoszMilewsky/PI_02_Types_and_Functions/Bool.hs
gpl-3.0
1,079
0
10
271
316
152
164
27
1
-- | Types used to define the job queue. module JobsDaemon.Type ( JobId, Job (..), JobType (..) {- from Model -} , JobsQueue (..) , JobsChan (..), JobsDepends (..) ) where import Prelude import Control.Concurrent (MVar, Chan) import qualified Data.Map as M import Model (JobId, Job (..), JobType (..)) -- | Contains the queue of jobs which can be processed and the graph of -- dependencies. data JobsQueue = JobsQueue { jqChan :: JobsChan, jqDepends :: MVar JobsDepends } -- | Contains a queue of background jobs which can be processed right now. -- Each job is associated to an action. newtype JobsChan = JobsChan (Chan (JobId, IO ())) -- | Maps each uncompleted parent job to a list of its dependent jobs. -- Each mapped job contains its id, its action and possibly the list of the -- remaining other dependencies of the job. -- When a job completes, the corresponding entry from the map is removed and -- each mapped job is : -- - added to the 'JobsChan' if the list of remaining dependencies of the -- job is empty ; -- - added to the first job of its remaining dependencies if the list is -- not empty. newtype JobsDepends = JobsDepends (M.Map JobId [(JobId, IO (), [JobId])])
RaphaelJ/getwebb.org
JobsDaemon/Type.hs
gpl-3.0
1,222
0
11
252
194
128
66
10
0
{-# LANGUAGE FlexibleContexts #-} import System.IO (hSetBuffering, stdin, stdout, BufferMode(..)) import Control.Monad.State parseInput :: String -> Int parseInput = read insertScore :: (MonadState Int m) => Int -> m () insertScore input = modify (+ input) calcScore :: (MonadState Int m) => m Int calcScore = get score :: (MonadState Int m, MonadIO m) => m () score = do val <- liftIO $ putStr "> " >> getLine let input = parseInput val if input == 0 then do score <- calcScore liftIO $ print ("exiting with score: " ++ show score) else do liftIO $ print ("Given Input is: " ++ show input) insertScore input score main = do -- this Buffering is for https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=846279 hSetBuffering stdout NoBuffering hSetBuffering stdin NoBuffering evalStateT score 0
muralikrishna8/Haskell-problems
simpleREPLstate.hs
gpl-3.0
868
0
14
203
272
137
135
24
2
import Data.List combinations i x = nub [take i y | y <- permutations x]
nstarke/icc13-introduction-to-haskell
ex26.hs
lgpl-3.0
73
0
9
15
38
18
20
2
1
{-# LANGUAGE OverloadedStrings #-} module Network.Haskoin.Crypto.Mnemonic.Tests (tests) where import Data.Bits (shiftR, (.&.)) import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as C import Data.Either (fromRight) import Data.Serialize (Serialize, encode) import Data.Word (Word32, Word64) import Network.Haskoin.Crypto import Network.Haskoin.Internals (fromMnemonic, getBits) import Network.Haskoin.Test import Test.Framework import Test.Framework.Providers.QuickCheck2 import Test.QuickCheck (Arbitrary, Property, arbitrary, choose, (==>)) tests :: [Test] tests = [ testGroup "Encode mnemonic" [ testProperty "128-bit entropy -> 12 words" toMnemonic128 , testProperty "160-bit entropy -> 18 words" toMnemonic160 , testProperty "256-bit entropy -> 24 words" toMnemonic256 , testProperty "512-bit entropy -> 48 words" toMnemonic512 , testProperty "n-bit entropy -> m words" toMnemonicVar ] , testGroup "Encode/Decode Mnemonic" [ testProperty "128-bit entropy" fromToMnemonic128 , testProperty "160-bit entropy" fromToMnemonic160 , testProperty "256-bit entropy" fromToMnemonic256 , testProperty "512-bit entropy" fromToMnemonic512 , testProperty "n-bit entropy" fromToMnemonicVar ] , testGroup "Mnemonic to seed" [ testProperty "128-bit entropy" mnemonicToSeed128 , testProperty "160-bit entropy" mnemonicToSeed160 , testProperty "256-bit entropy" mnemonicToSeed256 , testProperty "512-bit entropy" mnemonicToSeed512 , testProperty "n-bit entropy" mnemonicToSeedVar ] , testGroup "Get bits from ByteString" [ testProperty "Byte count" getBitsByteCount , testProperty "End bits" getBitsEndBits ] ] binWordsToBS :: Serialize a => [a] -> BS.ByteString binWordsToBS = foldr f BS.empty where f b a = a `BS.append` encode b {- Encode mnemonic -} toMnemonic128 :: (Word64, Word64) -> Bool toMnemonic128 (a, b) = l == 12 where bs = encode a `BS.append` encode b l = length . C.words . fromRight (error "Could not decode mnemonic senttence") $ toMnemonic bs toMnemonic160 :: (Word32, Word64, Word64) -> Bool toMnemonic160 (a, b, c) = l == 15 where bs = BS.concat [encode a, encode b, encode c] l = length . C.words . fromRight (error "Colud not decode mnemonic sentence") $ toMnemonic bs toMnemonic256 :: (Word64, Word64, Word64, Word64) -> Bool toMnemonic256 (a, b, c, d) = l == 24 where bs = BS.concat [encode a, encode b, encode c, encode d] l = length . C.words . fromRight (error "Could not decode mnemonic sentence") $ toMnemonic bs toMnemonic512 :: ((Word64, Word64, Word64, Word64), (Word64, Word64, Word64, Word64)) -> Bool toMnemonic512 ((a, b, c, d), (e, f, g, h)) = l == 48 where bs = BS.concat [ encode a , encode b , encode c , encode d , encode e , encode f , encode g , encode h ] l = length . C.words . fromRight (error "Colud not decode mnemoonic sentence") $ toMnemonic bs toMnemonicVar :: [Word32] -> Property toMnemonicVar ls = not (null ls) && length ls <= 8 ==> l == wc where bs = binWordsToBS ls bl = BS.length bs cb = bl `div` 4 wc = (cb + bl * 8) `div` 11 l = length . C.words . fromRight (error "Could not decode mnemonic sentence") $ toMnemonic bs {- Encode/Decode -} fromToMnemonic128 :: (Word64, Word64) -> Bool fromToMnemonic128 (a, b) = bs == bs' where bs = encode a `BS.append` encode b bs' = fromRight (error "Colud not decode mnemonic entropy") (fromMnemonic =<< toMnemonic bs) fromToMnemonic160 :: (Word32, Word64, Word64) -> Bool fromToMnemonic160 (a, b, c) = bs == bs' where bs = BS.concat [encode a, encode b, encode c] bs' = fromRight (error "Could not decode mnemonic entropy") (fromMnemonic =<< toMnemonic bs) fromToMnemonic256 :: (Word64, Word64, Word64, Word64) -> Bool fromToMnemonic256 (a, b, c, d) = bs == bs' where bs = BS.concat [encode a, encode b, encode c, encode d] bs' = fromRight (error "Could not decode mnemonic entropy") (fromMnemonic =<< toMnemonic bs) fromToMnemonic512 :: ((Word64, Word64, Word64, Word64), (Word64, Word64, Word64, Word64)) -> Bool fromToMnemonic512 ((a, b, c, d), (e, f, g, h)) = bs == bs' where bs = BS.concat [ encode a , encode b , encode c , encode d , encode e , encode f , encode g , encode h ] bs' = fromRight (error "Could not decode mnemonic entropy") (fromMnemonic =<< toMnemonic bs) fromToMnemonicVar :: [Word32] -> Property fromToMnemonicVar ls = not (null ls) && length ls <= 8 ==> bs == bs' where bs = binWordsToBS ls bs' = fromRight (error "Colud not decode mnemonic entropy") (fromMnemonic =<< toMnemonic bs) {- Mnemonic to seed -} mnemonicToSeed128 :: (Word64, Word64) -> Bool mnemonicToSeed128 (a, b) = l == 64 where bs = encode a `BS.append` encode b seed = fromRight (error "Could not decode mnemonic seed") (mnemonicToSeed "" =<< toMnemonic bs) l = BS.length seed mnemonicToSeed160 :: (Word32, Word64, Word64) -> Bool mnemonicToSeed160 (a, b, c) = l == 64 where bs = BS.concat [encode a, encode b, encode c] seed = fromRight (error "Could not decode mnemonic seed") (mnemonicToSeed "" =<< toMnemonic bs) l = BS.length seed mnemonicToSeed256 :: (Word64, Word64, Word64, Word64) -> Bool mnemonicToSeed256 (a, b, c, d) = l == 64 where bs = BS.concat [encode a, encode b, encode c, encode d] seed = fromRight (error "Colud not decode mnemonic seed") (mnemonicToSeed "" =<< toMnemonic bs) l = BS.length seed mnemonicToSeed512 :: ((Word64, Word64, Word64, Word64), (Word64, Word64, Word64, Word64)) -> Bool mnemonicToSeed512 ((a, b, c, d), (e, f, g, h)) = l == 64 where bs = BS.concat [ encode a , encode b , encode c , encode d , encode e , encode f , encode g , encode h ] seed = fromRight (error "Could not decode mnemonic seed") (mnemonicToSeed "" =<< toMnemonic bs) l = BS.length seed mnemonicToSeedVar :: [Word32] -> Property mnemonicToSeedVar ls = not (null ls) && length ls <= 16 ==> l == 64 where bs = binWordsToBS ls seed = fromRight (error "Could not decode mnemonic seed") (mnemonicToSeed "" =<< toMnemonic bs) l = BS.length seed {- Get bits from ByteString -} data ByteCountGen = ByteCountGen BS.ByteString Int deriving Show instance Arbitrary ByteCountGen where arbitrary = do bs <- arbitraryBS i <- choose (0, BS.length bs * 8) return $ ByteCountGen bs i getBitsByteCount :: ByteCountGen -> Bool getBitsByteCount (ByteCountGen bs i) = BS.length bits == l where (q, r) = i `quotRem` 8 bits = getBits i bs l = if r == 0 then q else q + 1 getBitsEndBits :: ByteCountGen -> Bool getBitsEndBits (ByteCountGen bs i) = (r == 0) || (BS.last bits .&. (0xff `shiftR` r) == 0x00) where r = i `mod` 8 bits = getBits i bs
plaprade/haskoin
haskoin-core/test/Network/Haskoin/Crypto/Mnemonic/Tests.hs
unlicense
8,018
0
13
2,620
2,360
1,279
1,081
-1
-1
{- stack --resolver lts-8.0 --install-ghc exec --package base --package quickspec --package QuickCheck --package testing-feat -- ghc -O2 -} -- Copyright 2017 Google Inc. 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. {-# LANGUAGE ScopedTypeVariables, GADTs, KindSignatures, StandaloneDeriving, TemplateHaskell, DeriveGeneric #-} import Prelude hiding (sum) import Control.Applicative (liftA2) import Test.QuickSpec import Test.QuickCheck import Data.Typeable import Test.Feat (deriveEnumerable, uniform) import Test.Feat.Class import Data.Monoid ((<>)) import GHC.Generics data BTree = Leaf | Branch BTree BTree deriving (Eq, Ord, Show, Generic) data Finite' = Empty | Singleton BTree | Sum Finite Finite | Prod Finite Finite | FMap (BTree -> BTree) Finite data Finite = Finite { card :: Integer, fin :: Finite' } empty = Finite 0 Empty singleton x = Finite 1 (Singleton x) sum f1 f2 = Finite (card f1 + card f2) (Sum f1 f2) prod f1 f2 = Finite (card f1 * card f2) (Prod f1 f2) fMap f fi = Finite (card fi) (FMap f fi) index :: Finite -> Integer -> Maybe BTree index (Finite c f) i | i >= c = Nothing | otherwise = index' f where index' (Singleton x) = Just x index' (Sum f1 f2) | i < card f1 = index f1 i | otherwise = index f2 (i - card f1) index' (Prod f1 f2) = liftA2 Branch (index f1 q) (index f2 r) where (q, r) = divMod i (card f2) index' (FMap f fi) = fmap f (index fi i) toList :: Finite -> [Maybe BTree] toList f = [index f i | i <- [0..card f]] instance Eq Finite where f1 == f2 = toList f1 == toList f2 instance Ord Finite where compare f1 f2 = compare (toList f1) (toList f2) instance Enumerable Finite where enumerate = consts [ pure empty , unary singleton , unary (funcurry sum) , unary (funcurry prod) ] instance Arbitrary Finite where arbitrary = sized uniform deriveEnumerable ''BTree instance Arbitrary BTree where arbitrary = sized uniform instance CoArbitrary BTree feat :: [Sig] feat = [ ["x","y","z"] `vars` (undefined :: Finite) , funs (undefined :: BTree) , "empty" `fun0` empty , "sum" `fun2` sum , "prod" `fun2` prod , "fmap" `fun2` fMap ] main = quickSpec feat
polux/snippets
QuickSpecExample.hs
apache-2.0
2,813
0
11
645
839
443
396
61
4
-- | For functions which should have been System.Directory module System.Directory.Extra where import Data.List import System.FilePath -- | Only works with absolute paths. -- -- >>> ancestors "/bin" -- ["/","/bin"] -- -- >>> ancestors "/bin/foo/bar" -- ["/","/bin","/bin/foo","/bin/foo/bar"] ancestors :: FilePath -> [FilePath] ancestors absPath = absPaths where (drive, fullRelPath) = splitDrive absPath reconstruct relPath = joinDrive drive relPath components = splitDirectories fullRelPath relPaths = map joinPath (inits components) absPaths = map reconstruct relPaths
gelisam/hawk
src/System/Directory/Extra.hs
apache-2.0
605
0
9
106
109
62
47
10
1
module Parse (parseArrow) where import Types import Control.Monad.Error (throwError) import Text.ParserCombinators.Parsec import qualified Data.Vector as V validSym = oneOf "!#$%&|*+-/:<=>?@^_~" parseInteger :: Parser Expr parseInteger = do sign <- option "" (string "-") number <- many1 digit return $ Integer (read (sign++number)) parseSymbol :: Parser Expr parseSymbol = do f <- lower <|> validSym r <- many (letter <|> validSym <|> digit) return $ Symbol (f:r) parseList :: Parser Expr parseList = do char '(' skipMany space x <- parseExpr' `sepEndBy` (many1 space) char ')' return $ List x parseQuotedList :: Parser Expr parseQuotedList = do char '\'' List x <- parseList return $ QuotedList x parseVector :: Parser Expr parseVector = do char '[' skipMany space x <- parseExpr' `sepEndBy` (many1 space) char ']' return $ Vector (V.fromList x) parseExpr' :: Parser Expr parseExpr' = (try parseInteger) <|> (try parseSymbol) <|> (try parseList) <|> (try parseQuotedList) <|> (try parseVector) parseExpr :: Parser Expr parseExpr = do skipMany space x <- parseExpr' skipMany space ; eof return x parseArrow :: String -> Result parseArrow source = case (parse parseExpr "" source) of Right x -> return x Left e -> throwError $ show e
dbyrne/arrow
Parse.hs
apache-2.0
1,493
16
12
453
501
246
255
45
2
{-# LANGUAGE GeneralizedNewtypeDeriving #-} import Control.Monad.Error import Control.Monad.State import qualified Data.ByteString.Char8 as B data ParseError = NumericOverflow | EndOfInput | Chatty String deriving (Eq, Ord, Show) instance Error ParseError where noMsg = Chatty "oh noes!" strMsg = Chatty newtype Parser a = P { runP :: ErrorT ParseError (State B.ByteString) a } deriving (Monad, MonadError ParseError)
prt2121/haskell-practice
transformer/src/ParseInt.hs
apache-2.0
542
0
10
180
116
68
48
14
0
{-# LANGUAGE Haskell2010 #-} module A where data A = A other :: Int other = 2 -- | Doc for test2 test2 :: Bool test2 = False -- | Should show up on the page for both modules A and B data X = X -- ^ Doc for consructor -- | Should show up on the page for both modules A and B reExport :: Int reExport = 1
haskell/haddock
html-test/src/A.hs
bsd-2-clause
308
0
5
76
53
34
19
10
1
doubleMe x = x + x doubleUs x y = doubleMe x + doubleMe y doubleSmallNumber x = if x > 100 then x else doubleMe x timCooke = "Tim Cooke"
trcooke/fun-with-haskell
baby.hs
bsd-2-clause
144
4
6
38
65
32
33
6
2
{-# LANGUAGE FlexibleContexts, FlexibleInstances, RankNTypes, KindSignatures, UndecidableInstances #-} module Main (main, arithmetic, comparisons, boolean, conditionals) where import System.Environment (getArgs) import Data.Functor.Compose (Compose(..)) import Data.Map (Map) import qualified Rank2 import Text.Grampa (TokenParsing, LexicalParsing, GrammarBuilder, ParseResults, fixGrammar, parseComplete) import Text.Grampa.ContextFree.LeftRecursive (Parser) import Arithmetic (Arithmetic, arithmetic) import qualified Arithmetic import qualified Boolean import qualified Comparisons import qualified Conditionals import qualified Combined import qualified Lambda type ArithmeticComparisons = Rank2.Product (Arithmetic.Arithmetic Int) (Comparisons.Comparisons Int Bool) type ArithmeticComparisonsBoolean = Rank2.Product ArithmeticComparisons (Boolean.Boolean Bool) type ACBC = Rank2.Product ArithmeticComparisonsBoolean (Conditionals.Conditionals Bool Int) main :: IO () main = do args <- concat <$> getArgs -- let a = fixGrammar (Arithmetic.arithmetic (production id Arithmetic.expr a)) -- let a = fixGrammar (Arithmetic.arithmetic (recursive $ Arithmetic.expr a)) print (getCompose . Lambda.expr $ parseComplete (fixGrammar Lambda.lambdaCalculus) args :: ParseResults String [Lambda.LambdaInitial]) -- print (((\f-> f (mempty :: Map String Int) [1 :: Int]) <$>) <$> parse (fixGrammar Lambda.lambdaCalculus) Lambda.expr args :: ParseResults String Int) print (getCompose . Arithmetic.expr $ parseComplete (fixGrammar arithmetic) args :: ParseResults String [Int]) print (getCompose . Comparisons.test . Rank2.snd $ parseComplete (fixGrammar comparisons) args :: ParseResults String [Bool]) print (getCompose . Boolean.expr . Rank2.snd $ parseComplete (fixGrammar boolean) args :: ParseResults String [Bool]) print (getCompose . Conditionals.expr . Rank2.snd $ parseComplete (fixGrammar conditionals) args :: ParseResults String [Int]) print (((\f-> f (mempty :: Map String Combined.Tagged)) <$>) <$> (getCompose . Combined.expr $ parseComplete (fixGrammar Combined.expression) args) :: ParseResults String [Combined.Tagged]) comparisons :: (LexicalParsing (Parser g String)) => GrammarBuilder ArithmeticComparisons g Parser String comparisons (Rank2.Pair a c) = Rank2.Pair (Arithmetic.arithmetic a) (Comparisons.comparisons c{Comparisons.term= Arithmetic.expr a}) boolean :: (LexicalParsing (Parser g String)) => GrammarBuilder ArithmeticComparisonsBoolean g Parser String boolean (Rank2.Pair ac b) = Rank2.Pair (comparisons ac) (Boolean.boolean (Comparisons.test $ Rank2.snd ac) b) conditionals :: (LexicalParsing (Parser g String)) => GrammarBuilder ACBC g Parser String conditionals (Rank2.Pair acb c) = Rank2.Pair (boolean acb) (Conditionals.conditionals c{Conditionals.test= Boolean.expr (Rank2.snd acb), Conditionals.term= Arithmetic.expr (Rank2.fst $ Rank2.fst acb)}) instance TokenParsing (Parser ArithmeticComparisons String) instance TokenParsing (Parser ArithmeticComparisonsBoolean String) instance TokenParsing (Parser ACBC String) instance TokenParsing (Parser (Lambda.Lambda Lambda.LambdaInitial) String) instance LexicalParsing (Parser ArithmeticComparisons String) instance LexicalParsing (Parser ArithmeticComparisonsBoolean String) instance LexicalParsing (Parser ACBC String) instance LexicalParsing (Parser (Lambda.Lambda Lambda.LambdaInitial) String)
blamario/grampa
grammatical-parsers/examples/Main.hs
bsd-2-clause
3,632
0
16
613
977
511
466
51
1
{-# LANGUAGE Haskell2010 #-} {-# LANGUAGE PatternSynonyms, TypeOperators, TypeFamilies, MultiParamTypeClasses, GADTs #-} {-# LANGUAGE FunctionalDependencies #-} -- | Test operators with or without fixity declarations module Operators where -- | Operator with no fixity (+-) :: a -> a -> a a +- _ = a -- | Operator with infixr 7 (*/) :: a -> a -> a _ */ b = b infixr 7 */ -- | Named function with infixl 3 foo :: a -> a -> a foo a _ = a infixl 3 `foo` -- | Data type with operator constructors data Foo = Foo `Bar` Foo -- ^ Has infixl 3 | Foo :- Foo -- ^ Has infixr 5 infixr 5 :- infixl 3 `Bar` -- | Pattern synonym, infixr 3 pattern (:+) a b <- [a,b] infixr 3 :+ -- | Type name, infixl 6 and GADT constructor data (a <-> b) where (:<->) :: a -> b -> a <-> b infixl 6 <-> infixr 6 :<-> -- | Type family with fixity type family a ++ b infix 3 ++ -- | Data family with fixity data family a ** b infix 9 ** -- | Class with fixity, including associated types class a ><> b | a -> b where -- Dec 2015: Added @a -> b@ functional dependency to clean up ambiguity -- See GHC #11264 type a <>< b :: * data a ><< b (>><), (<<>) :: a -> b -> () -- | Multiple fixities (**>), (**<), (>**), (<**) :: a -> a -> () infixr 1 ><> infixl 2 <>< infixl 3 ><< infixr 4 >>< infixl 5 <<> infixr 8 **>, >** infixl 8 **<, <** -- | Type synonym with fixity type (a >-< b) = a <-> b infixl 6 >-<
haskell/haddock
html-test/src/Operators.hs
bsd-2-clause
1,403
0
9
335
370
238
132
41
1
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-} module Lib ( expandExpr , allExprs , filterExprs , Eval(..) , Digit, Number, Term, Expr, ) where import Control.Monad (join) import Data.List (intercalate) {- Lazily build the list of all expressions, starting with an empty expression. This is done by expansion of a list of expressions, the list of which starts as empty and is expanded progressively into what looks like a "linear" catamorphism. See the code below for details. -} -- some type aliases type Digit = Int -- a digit is a primitive int in the range [1-9] type Number = [Digit] -- a number is a list of digits type Term = [Number] -- a term is a list (multiplication <-> *) of numbers type Expr = [Term] -- an expression is a list (addition <-> +) of terms -- a class for things that can be evaluated into integer values class Eval t where eval :: t -> Int -- evaluate a number to its int value instance Eval Number where eval = foldl1 (\a -> \d -> a*10 + d) -- evaluate a term to its int value instance Eval Term where eval = product . fmap eval -- evaluate an expression to its int value instance Eval Expr where eval = sum . fmap eval -- given a list of expressions, add a digit at the front of each expandExpr :: Digit -> [Expr] -> [Expr] expandExpr dgt [] = [[[[dgt]]]] expandExpr dgt exs = join . fmap (addDigit dgt) $ exs where -- given an expression, add a digit at its front addDigit :: Digit -> Expr -> [Expr] addDigit d ((number:numbers):terms) = [ -- add d as a digit at the left of the current number, to make a longer number (e.g. d=1, current number = 2 <=> 12) ((d:number):numbers):terms, -- or add a digit d as a separate new number in the current term (e.g. d=2, current term = 34 <=> 2*34) ([d]:number:numbers):terms, -- or add a digit d as a separate new term in the expression (e.g. d=2, expression = 3+4 <=> 2+3+4) [[d]]:(number:numbers):terms ] addDigit _ [] = error "addDigit on empty expression" addDigit _ ([]:_) = error "addDigit on empty term" -- all possible expressions (lazily generated, so perf shouldn't be an issue) allExprs :: [Expr] allExprs = foldr expandExpr [] [1..9] -- list as stings all expressions that matches a filtering criteria filterExprs :: (Int -> Bool) -> [String] filterExprs f = asString filteredExprs where filteredExprs = filter (f . eval) allExprs asString = fmap (intercalate "+" . fmap (intercalate "x" . fmap (show . eval)))
smunix/digit-operations
src/Lib.hs
bsd-3-clause
2,555
0
15
584
533
303
230
38
3
module Matasano.SetOne.ChallengeSix (test) where import Data.Bits ((.&.), (.|.), popCount, shift, xor) import Data.Char (chr) import Data.Function (on) import Data.List (maximumBy, minimumBy, tails, transpose) import Data.Map (Map, findWithDefault, fromListWith) import Data.Word (Word8) import Matasano.Util (read64) hamming :: [Word8] -> [Word8] -> Int hamming a b = sum . map popCount $ zipWith xor a b keysize :: [Word8] -> Int -> Int keysize c m = best $ for [1..m] (\n -> (n, normalize n $ distances n)) where for = flip map distances n = average [hamming s t | (s:ts) <- tails c', t <- ts] where average l = fromIntegral (sum l) / fromIntegral (length l) c' = c `groupsOf` n normalize n d = d / fromIntegral n :: Double best = fst . minimumBy (compare `on` snd) groupsOf :: [a] -> Int -> [[a]] groupsOf [] _ = [] groupsOf xs n = front : groupsOf remaining n where (front, remaining) = splitAt n xs solve :: Map Char Integer -> [Word8] -> (String, String) solve freqs ciphertext = applyTuple toString (concat . transpose) . unzip . map (guess freqs) . transpose $ ciphertext `groupsOf` klen where klen = keysize ciphertext 40 toString = map (chr . fromIntegral) applyTuple f g (a, b) = (f a, g b) frequency :: [Char] -> Map Char Integer frequency = fromListWith (+) . flip zip (repeat 1) guess :: Map Char Integer -> [Word8] -> (Word8, String) guess freqs s = maximumBy (compare `on` score . snd) . for [0..255] $ (\k -> (k, toString $ crypt s k)) where for = flip map toString = map (chr . fromIntegral) crypt s k = zipWith xor s (repeat k) score = sum . map (\c -> findWithDefault 0 c freqs) test :: IO () test = do putStrLn "Challenge Six" corpus <- readFile "data/plaintext_corpus.txt" f <- readFile "data/6.txt" let freqs = frequency corpus ciphertext = read64 . concat . lines $ f (key, plaintext) = solve freqs ciphertext putStrLn "Best guess:" putStrLn (" Key : " ++ show key) putStrLn (" Plaintext: " ++ show (take 50 plaintext) ++ "...")
bisserlis/Matasano
src/Matasano/SetOne/ChallengeSix.hs
bsd-3-clause
2,389
0
13
786
920
485
435
-1
-1
{-# LANGUAGE OverloadedStrings #-} -- | Main entry point to renoise. -- -- A Haskell API for Renoise. module Main where import Renoise import Sound.OSC -- | Main entry point. main :: IO () main = withTransport (openTCP ip 8000) (sendBundle (bundle immediately [eval code])) where ip = "10.0.1.55" code = "renoise.song().patterns[1]:clear()\n\ \local pattern = renoise.song().patterns[1]\n\ \local track = pattern.tracks[1]\n\ \for j = 1, #track.lines do\n\ \ local note_column = track.lines[j].note_columns[1]\n\ \ if false and j % 20 == 0 then\n\ \ note_column.note_string = \"F-4\"\n\ \ note_column.volume_value = 126\n\ \ note_column.instrument_value = 0\n\ \ elseif false and j % 12 == 0 then\n\ \ note_column.note_string = \"C-4\"\n\ \ note_column.volume_value = 126\n\ \ note_column.instrument_value = 0\n\ \ end\n\ \end\n\ \track = pattern.tracks[2]\n\ \for j = 1, #track.lines do\n\ \ local note_column = track.lines[j].note_columns[1]\n\ \ if false and (j-1) % 16 == 0 then\n\ \ note_column.note_string = \"E-4\"\n\ \ note_column.volume_value = 126\n\ \ note_column.instrument_value = 2 end\n\ \end\n\ \track = pattern.tracks[3]\n\ \for j = 1, #track.lines do\n\ \ local note_column = track.lines[j].note_columns[1]\n\ \ if false and j % 32 == 0 then\n\ \ note_column.note_string = \"E-4\"\n\ \ note_column.volume_value = 126\n\ \ note_column.instrument_value = 3\n\ \ else\n\ \ note_column.note_value = 121\n\ \ end\n\ \end\n\ \track = pattern.tracks[4]\n\ \for j = 1, #track.lines do\n\ \ local note_column = track.lines[j].note_columns[1]\n\ \ if false and j % == 0 then\n\ \ note_column.note_value = j % 50\n\ \ note_column.volume_value = 126\n\ \ note_column.instrument_value = 4\n\ \ elseif true then\n\ \ note_column.note_value = 120\n\ \ end\n\ \end\n\ \"
chrisdone/renoise
src/Main.hs
bsd-3-clause
1,974
0
11
451
77
44
33
13
1
module Data.Char.Properties.PrivateData where { import Prelude; handleOmittedRange :: a -> (Char -> a) -> Char -> a; handleOmittedRange def _ c | (c < '\x3400') = def; -- optimisiation, catch about 99.9% of cases for non-CJK text handleOmittedRange _ f c | (c > '\x3400') && (c <= '\x4DB5') = f '\x3400'; handleOmittedRange _ f c | (c > '\x4E00') && (c <= '\x9FA5') = f '\x4E00'; handleOmittedRange _ f c | (c > '\xAC00') && (c <= '\xD7A3') = f '\xAC00'; handleOmittedRange _ f c | (c > '\xD800') && (c <= '\xDB7F') = f '\xD800'; handleOmittedRange _ f c | (c > '\xDB80') && (c <= '\xDBFF') = f '\xDB80'; handleOmittedRange _ f c | (c > '\xDC00') && (c <= '\xDFFF') = f '\xDC00'; handleOmittedRange _ f c | (c > '\xE000') && (c <= '\xF8FF') = f '\xE000'; handleOmittedRange _ f c | (c > '\x20000') && (c <= '\x2A6D6') = f '\x20000'; handleOmittedRange _ f c | (c > '\xF0000') && (c <= '\xFFFFD') = f '\xF0000'; handleOmittedRange _ f c | (c > '\x100000') && (c <= '\x10FFFD') = f '\x100000'; handleOmittedRange def _ _ = def; }
seereason/unicode-properties
Data/Char/Properties/PrivateData.hs
bsd-3-clause
1,147
0
10
313
479
246
233
15
1
module Language.BCoPL.DataLevel.Diagram ( -- * Types Diagram (..) -- * Pretty Printer , ppr , textDiag -- * Renderer for a diagram , renderDiagram ) where import Data.Tree (Tree(..)) import Text.PrettyPrint.Boxes (Box,(//),hsep,bottom,cols,text,moveRight,render) data Diagram = Diagram {leading,judgement,trailing :: Int, diagram :: Box} -- | Pretty printer for a derivation tree ppr :: (Show a) => Tree (String,a) -> Diagram ppr (Node (rn,j) ts) = case pprs ts of Diagram tlead tjudge ttrail tdia -> Diagram dlead djudge dtrail ddia where (blead,bjudge,btrail,bdia) = (0,cols bdia,0,text (show j)) bdia' = moveRight blead' bdia (tlead',blead') = if tent > bent then (tlead,blead+(tent-bent)`div`2) else (tlead+(bent-tent)`div`2,blead) (tent,bent) = (2*tlead+tjudge,2*blead+bjudge) tdia' = moveRight (tlead' - tlead) tdia mlead' = tlead' `min` blead' mdia = text $ replicate (tjudge `max` bjudge) '-' ++ "(" ++ rn ++ ")" mdia' = moveRight (tlead' `min` blead') mdia ddia = tdia' // mdia' // bdia' dlead = blead' djudge = cols bdia dtrail = cols ddia - dlead - djudge -- | Pretty printer for a derivation forest pprs :: (Show a) => [Tree (String,a)] -> Diagram pprs [] = Diagram 0 0 0 (text "") pprs ts = Diagram dlead djudge dtrail ddia where bs = map ppr ts dlead = leading $ head bs djudge = cols ddia - dlead - dtrail dtrail = trailing $ last bs ddia = hsep 3 bottom $ map diagram bs -- | Render diagram renderDiagram :: Diagram -> String renderDiagram = render . diagram -- | Text diagram textDiag :: String -> Diagram textDiag txt = Diagram { leading = 0, judgement = length txt, trailing = 0 , diagram = text txt }
nobsun/hs-bcopl
src/Language/BCoPL/DataLevel/Diagram.hs
bsd-3-clause
1,873
0
16
525
678
384
294
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveDataTypeable #-} module Aws.Sign4.Test ( main , tests , testAll ) where import Aws.Sign4 import Aws.Core import System.Locale import System.Environment import System.Exit import System.Directory import System.FilePath import Text.Printf import Control.Applicative import Control.Exception import Data.Char import Data.Time import Data.Attempt import Data.Maybe import Data.Typeable import qualified Data.ByteString.Unsafe as SU import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lex.Integral as LI import qualified Data.Text as T import qualified Data.CaseInsensitive as CI import qualified Network.HTTP.Types as H import Safe import qualified Distribution.TestSuite as TS -- | Detailed-0.9/Cabal-1.14.0 test suite tests :: [TS.Test] tests = map TS.impure test_list -- map TS.impure simple_tests -- | Something for running in ghci testAll :: IO () testAll = scavenge_tests >>= mapM_ test_authz -- | A (run)ghc entry point for running a specific test main :: IO () main = do as <- getArgs rs <- case as of ["hdrs" ,fp] -> test_hdrs fp ["creq" ,fp] -> test_creq fp ["sts" ,fp] -> test_sts fp ["authz",fp] -> test_authz fp _ -> do putStrLn "usage: aws4-test hdrs <request-file>" putStrLn "usage: aws4-test creq <request-file>" putStrLn "usage: aws4-test sts <request-file>" putStrLn "usage: aws4-test authz <request-file>" exitWith $ ExitFailure 1 case rs of True -> return () False -> exitWith $ ExitFailure 2 -- -- The AWS4 Test Suite -- -- The AWS sample credentials used to calculate the AWS test vectors aws_test_credentials :: Credentials aws_test_credentials = Credentials { accessKeyID = "AKIDEXAMPLE" , secretAccessKey = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY" } -- Tests to check the output at each stage auth-header generator: -- -- test_creq => check cannonical request o/p (.creq ) -- test_sts => check string to sign o/p (.sts ) -- test_creq => check authentication header o/p (.authz) -- -- Prints diagnostics indicating progress & pass/failure *and* return -- a boolean indicating whether the test passed. test_creq, test_sts, test_authz :: FilePath -> IO Bool test_creq = report "CREQ " spCreq s4CanonicalRequest test_sts = report "STS " spSts s4StringToSign test_authz = report "AUTHZ " spAuthz s4Authz -- test driver: takes a label, file path of answer file (as SuitePaths -- extractor), the function to be tested and the file path of the input -- file and runs the test, returning True iff it passes. report :: String -> (SuitePaths->FilePath) -> (Sign4->B.ByteString) -> FilePath -> IO Bool report lab chf mk inf = do sp <- check_rqf inf s4 <- mk_sign4 $ spReq sp let ans = mk s4 chk <- B.filter (/='\r') <$> B.readFile (chf sp) putStr $ printf "%s:%-50s: " lab $ spName sp let rst = ans==chk case rst of True -> putStrLn "matched" False -> do putStrLn "MISMATCHED" putStrLn "OURS-----------------------" putStrLn $ B.unpack ans putStrLn "THEIRS---------------------" putStrLn $ B.unpack chk putStrLn "---------------------------" putStrLn "" return rst -- Read in and parse the input HTTP request making up the Sign4 structure. mk_sign4 :: FilePath -> IO Sign4 mk_sign4 rqf = do bs <- B.readFile rqf rq <- case parseRequest bs of Success rq_ -> return rq_ Failure e -> throw e dt <- maybe (ioError $ userError dt_msg) return $ rqDate rq --sd <- signatureData Timestamp aws_test_credentials let Request{..} = rq return Sign4 { s4Credentials = aws_test_credentials , s4Date = dt , s4Endpoint = "us-east-1" , s4Service = "host" , s4Method = rqMethod , s4Path = rqRawPathInfo , s4Headers = rqRequestHeaders , s4Query = rqQuery , s4Body = rqBody , s4SgndHeaders = Nothing , s4CnclHeaders = Nothing } where dt_msg = "date missing or mangled" -- This bundle descibes the name an individual test vector, giving the -- name of the test, the input file and the file paths for the reference -- outputs for each stage of the auth-header generating process. data SuitePaths = SuitePaths { spName :: String , spReq :: FilePath , spCreq :: FilePath , spSts :: FilePath , spAuthz :: FilePath , spSreq :: FilePath } deriving (Show) -- Calculate the SuitePaths from the '.req' filepath of the HTTP input check_rqf :: FilePath -> IO SuitePaths check_rqf rqf = do rbs <- case reverse rqf of 'q':'e':'r':'.':rbs_ -> return rbs_ _ -> ioError $ userError $ printf "expected <foo>.req: %s" rqf let bse = reverse rbs ext = (bse ++) . ("." ++) return SuitePaths { spName = reverse $ takeWhile (/='/') rbs , spReq = ext "req" , spCreq = ext "creq" , spSts = ext "sts" , spAuthz = ext "authz" , spSreq = ext "sreq" } -- -- Test to just print out the header and return True -- test_hdrs :: FilePath -> IO Bool test_hdrs fp = fmap (const True) $ do bs <- B.readFile fp rq <- case parseRequest bs of Success rq_ -> return rq_ Failure e -> throw e let Request{..} = rq fmt "Method" rqMethod fmt "HttpVersion" rqHttpVersion fmt "RawPathInfo" rqRawPathInfo fmt "RawQueryString" rqRawQueryString fmt "ServerName" rqServerName fmt "RequestHeaders" rqRequestHeaders fmt "PathInfo" rqPathInfo fmt "QueryString" rqQuery fmt "Date" rqDate fmt "ContentLength" rqContentLength fmt "Body" rqBody where fmt :: Show a => String -> a -> IO () fmt lb vl = putStr $ printf "%-30s %s\n" lb $ show vl -- -- parseRequest (adapted from http-proxy) -- parseRequest :: B.ByteString -> Attempt Request parseRequest = parse_rq . lex_headers data Request = Request { rqMethod :: H.Method , rqHttpVersion :: H.HttpVersion -- From the first line of the header, -- before the '?' , rqRawPathInfo :: B.ByteString -- From the first line of the header, -- from the '?' onwards, but empty if none , rqRawQueryString :: B.ByteString , rqServerName :: B.ByteString -- The request headers , rqRequestHeaders :: H.RequestHeaders -- Parsed path info , rqPathInfo :: [T.Text] -- Parsed query string information , rqQuery :: H.Query -- Just <date>, iff present , rqDate :: Maybe UTCTime -- Just <content-length>, iff present , rqContentLength :: Maybe Int -- Body of request , rqBody :: B.ByteString } deriving (Typeable) data InvalidRequest = NotEnoughLines [String] | BadFirstLine String | NonHttp | IncompleteHeaders | ConnectionClosedByPeer | OverLargeHeader deriving (Show, Typeable, Eq) instance Exception InvalidRequest -- Parse a set of header lines and body into a 'Request' parse_rq :: ([B.ByteString],B.ByteString) -> Attempt Request parse_rq ([] ,_ ) = Failure $ NotEnoughLines [] parse_rq (fln:rst,bdy) = parse_first fln >>= return . parse_rq' rst bdy parse_rq' :: [B.ByteString] -> B.ByteString -> FirstLine -> Request parse_rq' rst bdy fl = Request { rqMethod = mth , rqHttpVersion = hvn , rqRawPathInfo = rpt , rqRawQueryString = gets , rqServerName = snm , rqRequestHeaders = hds , rqPathInfo = H.decodePathSegments rpt , rqQuery = H.parseQuery $ fudge_semi gets , rqDate = dte , rqContentLength = len , rqBody = bdy } where (hst0,rpt) | B.null rpt0 = ("", "/") | "http://" `B.isPrefixOf` rpt0 = B.break (=='/') $ B.drop 7 rpt0 | otherwise = ("", rpt0) snm = takeUntil ':' hst hst = fromMaybe hst0 $ lookup "host" hds dte = parse_rfc1123 =<< lookup "date" hds len = LI.readDecimal_ <$> lookup "content-length" hds mth = flMethd fl rpt0 = flRpath fl gets = flQuery fl hvn = flVersn fl hds = map parse_header rst -- FIXME: resolve this: according to post-vanilla-query-nonunreserved -- test vector AWS seem to treat ';' as unreserved in a URL query -- so we fudge the reading of their example header here, but is this -- what we should be doing anyway? fudge_semi :: B.ByteString -> B.ByteString fudge_semi = B.pack . concat . map fudge . B.unpack where fudge ';' = "%3B" fudge c = [c] takeUntil :: Char -> B.ByteString -> B.ByteString takeUntil c bs = case B.elemIndex c bs of Just !idx -> SU.unsafeTake idx bs Nothing -> bs {-# INLINE takeUntil #-} -- parse first line of HTTP header data FirstLine = FirstLine { flMethd :: B.ByteString , flRpath :: B.ByteString , flQuery :: B.ByteString , flVersn :: H.HttpVersion } deriving (Show) parse_first :: B.ByteString -> Attempt FirstLine parse_first bs = case extr $ B.split ' ' bs of Nothing -> Failure $ BadFirstLine $ B.unpack bs Just (mth,qry,vrn) -> case B.map toUpper vf == "HTTP/" of True -> return $ FirstLine mth rpt qst hvn where (rpt,qst) = B.break (=='?') qry hvn = case vs of "1.1" -> H.http11 _ -> H.http10 False -> Failure NonHttp where (vf,vs) = B.splitAt 5 vrn where extr (mth:pth0:nxt:rst) = Just (mth,pth0,lastDef nxt rst) extr _ = Nothing parse_header :: B.ByteString -> H.Header parse_header bs = (CI.mk hnm, val) where val = case rln > 1 && SU.unsafeHead rst == 58 {- ':' -} of True -> B.dropWhile isSpace $ SU.unsafeTail rst False -> rst rln = B.length rst (hnm,rst) = B.break (==':') bs --test_lex :: String -> ([B.ByteString],B.ByteString) --test_lex = lex_headers . B.pack -- -- lex_headers -- -- Split a ByteString into headers and body, batching up continuation lines lex_headers :: B.ByteString -> ([B.ByteString],B.ByteString) lex_headers bs = (hds,bdy) where hds = case hls of [] -> [] hln:rst -> grph [hln] rst (hls,bdy) = scan bs -- group header lines, batching up space-starting continuation lines into -- the header line grph :: [B.ByteString] -> [B.ByteString] -> [B.ByteString] grph rhs [] = reverse rhs grph rhs lst = case lst of [] -> [hdr] hln:rst -> case B.null hln of True -> grph (hln:rhs) rst False -> hdr : grph [hln] rst where hdr = B.intercalate (B.singleton '\n') $ reverse rhs -- scan request into header lines and the body scan :: B.ByteString -> ([B.ByteString],B.ByteString) scan bs0 = scn [] bs0 where scn rhs bs = case B.null bs of True -> (reverse rhs,bs) False -> case B.null nxt of True -> (reverse rhs,rst) False -> scn (nxt:rhs) rst where (nxt,rst) = nxt_ln bs -- split off next line tolerantly (CRLF or LF [or indeed CR] lines handled) nxt_ln :: B.ByteString -> (B.ByteString,B.ByteString) nxt_ln bs0 | B.null bs0 = (B.empty,B.empty) | otherwise = case B.find eol bs0 of Nothing -> (bs0,B.empty) Just '\r' -> nl_cr bs0 _ -> nl_lf bs0 where nl_cr bs = case B.elemIndex '\r' bs of Nothing -> error "nxt_ln:nl_cr: oops" Just n -> (B.take n bs,tl_lf $ B.drop (n+1) bs) nl_lf bs = case B.elemIndex '\n' bs of Nothing -> error "nxt_ln:nl_lf: oops" Just n -> (B.take n bs, B.drop (n+1) bs) tl_lf bs = case B.uncons bs of Just ('\n',bs') -> bs' _ -> bs eol '\r' = True eol '\n' = True eol _ = False parse_rfc1123 :: B.ByteString -> Maybe UTCTime parse_rfc1123 = parseTime defaultTimeLocale "%a, %d %b %Y %T %Z" . B.unpack -- -- Test Infrastructure -- test_dir :: FilePath test_dir = "aws4_testsuite" newtype SimpleTest = ST { _ST :: FilePath } deriving (Show,Eq) instance TS.TestOptions SimpleTest where name = name_test options = const [] defaultOptions = const $ return $ TS.Options [] check = const $ const $ return [] instance TS.ImpureTestable SimpleTest where runM (ST fp) _ = case fp of "" -> test_tests _ -> fmap cnv $ test_authz fp where cnv ok = if ok then TS.Pass else TS.Fail "Failed" -- SimpleTest with empty file path => precheck (check list of tests consistent -- with input test files in the file system) name_test :: SimpleTest -> String name_test (ST fp) = case fp of "" -> "[precheck]" _ -> fst $ splitExtension $ snd $ splitFileName fp -- Cabal seems to need a static list of tests: list them in board and -- provide a test for checking it is up-to-date test_tests :: IO TS.Result test_tests = do fps <- scavenge_tests case map ST fps == test_list' of True -> return TS.Pass False -> return $ TS.Fail "list of tests out of date" test_list, test_list' :: [SimpleTest] test_list = ST "" : test_list' test_list' = map ST [ "aws4_testsuite/get-header-key-duplicate.req" , "aws4_testsuite/get-unreserved.req" , "aws4_testsuite/get-vanilla-empty-query-key.req" , "aws4_testsuite/get-slash.req" , "aws4_testsuite/get-relative-relative.req" , "aws4_testsuite/get-vanilla-query-order-value.req" , "aws4_testsuite/get-utf8.req" , "aws4_testsuite/get-slash-dot-slash.req" , "aws4_testsuite/get-vanilla-query.req" , "aws4_testsuite/get-header-value-order.req" , "aws4_testsuite/get-vanilla-query-unreserved.req" , "aws4_testsuite/post-vanilla-query-space.req" , "aws4_testsuite/post-vanilla.req" , "aws4_testsuite/get-relative.req" , "aws4_testsuite/post-header-key-sort.req" , "aws4_testsuite/get-vanilla-ut8-query.req" , "aws4_testsuite/get-header-value-trim.req" , "aws4_testsuite/get-space.req" , "aws4_testsuite/get-slash-pointless-dot.req" , "aws4_testsuite/post-x-www-form-urlencoded.req" , "aws4_testsuite/post-header-key-case.req" , "aws4_testsuite/post-x-www-form-urlencoded-parameters.req" , "aws4_testsuite/post-vanilla-empty-query-value.req" , "aws4_testsuite/get-slashes.req" , "aws4_testsuite/get-vanilla.req" , "aws4_testsuite/post-header-value-case.req" , "aws4_testsuite/post-vanilla-query.req" , "aws4_testsuite/post-vanilla-query-nonunreserved.req" , "aws4_testsuite/get-vanilla-query-order-key.req" , "aws4_testsuite/get-vanilla-query-order-key-case.req" ] -- Pick Out All of the .req files from aws4_testsuite/ scavenge_tests :: IO [FilePath] scavenge_tests = map g <$> filter f <$> getDirectoryContents test_dir where f ('.':_) = False f fp = snd (splitExtension fp) == ".req" g = (test_dir </>)
cdornan/aws-sign4
Aws/Sign4/Test.hs
bsd-3-clause
16,969
0
16
5,760
3,709
1,962
1,747
356
8
module Main where import System.IO import Control.Applicative import Control.Monad import Data.Tuple import Data.Maybe import qualified Data.List as L import Data.Ord import Control.Arrow import Debug.Trace import qualified Data.IntMap as M import Data.IntMap ((!)) import qualified Data.IntSet as S type V = Int type E = (V, V) newtype G = G { vertexM :: M.IntMap S.IntSet } deriving Show mkGraph :: [[Int]] -> G mkGraph ds = G { vertexM = M.fromListWith S.union [(a, S.singleton b) | (a,b) <- es ++ map swap es] } where es = concat $ zipWith (\a bs -> zip (repeat a) bs) [1..] ds {- checkPart :: G -> [V] -> S.IntSet -> Bool checkPart g vs s = all (\v -> checkP1 g v s) vs where checkP1 g v s = case decomp v g of Nothing -> True Just (ns, _) -> if S.member v s then all (\n -> not (S.member n s)) $ S.toList ns else all (\n -> S.member n s) $ S.toList ns -} readInt :: String -> Int readInt = read decomp :: V -> G -> Maybe (S.IntSet, G) decomp v g = do ns <- M.lookup v (vertexM g) return (ns, G $ M.delete v (vertexM g)) anyVertex :: G -> Maybe V anyVertex g = case M.toList $ vertexM g of [] -> Nothing ((v,_):_) -> Just v bfs :: G -> [V] -> [V] bfs g [] = case anyVertex g of Nothing -> [] Just v -> bfs g [v] bfs g (v:vs) = case decomp v g of Nothing -> bfs g vs Just (ns, g') -> v : bfs g' (S.toList ns ++ vs) partition :: G -> [V] -> Maybe S.IntSet partition g vs = do (_, s) <- foldM (flip (part1 g)) (S.empty, S.empty) vs return s part1 :: G -> V -> (S.IntSet, S.IntSet) -> Maybe (S.IntSet, S.IntSet) part1 g v (red, blue) = case decomp v g of Nothing -> error "Vertex should be in the graph" Just (ns, _) -> case (S.member v red, S.member v blue) of (True, False) -> if all (not . flip S.member red) (S.toList ns) then Just (red, S.union ns blue) else Nothing (False, True) -> if all (not . flip S.member blue) (S.toList ns) then Just (S.union ns red, blue) else Nothing (True, True) -> Nothing (False, False) -> Just (S.insert v red, S.union ns blue) colors :: S.IntSet -> Int -> String colors s n = map (\i -> if S.member i s then '1' else '0') [1..n] main :: IO () main = do d <- readLn ds <- replicateM d $ map readInt . init . words <$> getLine let g = mkGraph ds let vs = M.keys $ vertexM g let p = partition g (bfs g [1]) --vs case p of --case checkPart g vs p of Nothing -> print (-1) Just s -> putStrLn $ colors s d
wuerges/solutions_for_graph_problems
app/Prob1080.hs
bsd-3-clause
3,061
0
16
1,208
1,109
584
525
64
7
-- | Building hierarchy from unstructured hierarchical paths. module Language.ImProve.Tree ( Tree (..) , tree ) where import Data.Function import Data.List data Tree a b = Branch a [Tree a b] | Leaf a b tree :: (Eq a, Ord a) => (b -> [a]) -> [b] -> [Tree a b] tree path leaves = foldl mergeTrees [] [ singleTree (path leaf) leaf | leaf <- leaves ] label :: Tree a b -> a label (Branch a _) = a label (Leaf a _) = a isBranch :: Tree a b -> Bool isBranch (Branch _ _) = True isBranch _ = False singleTree :: [a] -> b -> Tree a b singleTree [] _ = undefined singleTree [a] b = Leaf a b singleTree (a:b) c = Branch a [singleTree b c] mergeTrees :: (Eq a, Ord a) => [Tree a b] -> Tree a b -> [Tree a b] mergeTrees trees t@(Leaf _ _) = insertTree t trees mergeTrees trees t@(Branch n branches) = case find' (\ t -> isBranch t && label t == n) trees of Nothing -> insertTree t trees Just (Branch n trees1, trees2) -> insertTree (Branch n (foldl mergeTrees trees1 branches)) trees2 Just (Leaf _ _, _) -> undefined insertTree :: Ord a => Tree a b -> [Tree a b] -> [Tree a b] insertTree a b = insertBy (compare `on` label) a b find' :: (a -> Bool) -> [a] -> Maybe (a, [a]) find' _ [] = Nothing find' f (a:b) | f a = Just (a, b) | otherwise = do (found, rest) <- find' f b return (found, a : rest)
tomahawkins/improve
Language/ImProve/Tree.hs
bsd-3-clause
1,341
0
12
328
706
364
342
34
3
module D16Lib where import Data.List import Data.Maybe data Step = Spin Int | Exchange Int Int | Partner Char Char deriving (Eq, Show) type Dancer = Char iterations :: Int iterations = 1000000000 -- 1 billion dancers :: [Dancer] dancers = ['a'..'p'] run :: [Dancer] -> [Step] -> [Dancer] run = foldl' step step :: [Dancer] -> Step -> [Dancer] step ds (Spin x) = let (h, t) = splitAt (length ds - x) ds in t ++ h step ds (Exchange x y) | x == y = ds | x > y = step ds (Exchange y x) | otherwise = let (h0, (d0:t0)) = splitAt x ds (h1, (d1:t1)) = splitAt (y - x - 1) t0 in h0 ++ (d1 : h1) ++ (d0: t1) step ds (Partner x y) = let p1 = fromMaybe (error "invalid dancer id") $ findIndex (== x) ds p2 = fromMaybe (error "invalid dancer id") $ findIndex (== y) ds in step ds $ Exchange p1 p2 cycleLength :: [Dancer] -> [Step] -> Int cycleLength ds ss = go ds 0 where go ds' i | ds == run ds' ss = i + 1 | otherwise = go (run ds' ss) (i + 1) runTimes :: [Dancer] -> [Step] -> Int -> [Dancer] runTimes ds ss is | is <= 0 = ds | otherwise = runTimes (run ds ss) ss (is - 1)
wfleming/advent-of-code-2016
2017/D16/src/D16Lib.hs
bsd-3-clause
1,151
0
13
322
598
309
289
36
1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 -} {-# LANGUAGE CPP, DeriveDataTypeable, FlexibleContexts #-} {-# LANGUAGE NamedFieldPuns #-} -- | CoreSyn holds all the main data types for use by for the Glasgow Haskell Compiler midsection module CoreSyn ( -- * Main data types Expr(..), Alt, Bind(..), AltCon(..), Arg, Tickish(..), TickishScoping(..), TickishPlacement(..), CoreProgram, CoreExpr, CoreAlt, CoreBind, CoreArg, CoreBndr, TaggedExpr, TaggedAlt, TaggedBind, TaggedArg, TaggedBndr(..), deTagExpr, -- * In/Out type synonyms InId, InBind, InExpr, InAlt, InArg, InType, InKind, InBndr, InVar, InCoercion, InTyVar, InCoVar, OutId, OutBind, OutExpr, OutAlt, OutArg, OutType, OutKind, OutBndr, OutVar, OutCoercion, OutTyVar, OutCoVar, -- ** 'Expr' construction mkLet, mkLets, mkLetNonRec, mkLetRec, mkLams, mkApps, mkTyApps, mkCoApps, mkVarApps, mkTyArg, mkIntLit, mkIntLitInt, mkWordLit, mkWordLitWord, mkWord64LitWord64, mkInt64LitInt64, mkCharLit, mkStringLit, mkFloatLit, mkFloatLitFloat, mkDoubleLit, mkDoubleLitDouble, mkConApp, mkConApp2, mkTyBind, mkCoBind, varToCoreExpr, varsToCoreExprs, isId, cmpAltCon, cmpAlt, ltAlt, -- ** Simple 'Expr' access functions and predicates bindersOf, bindersOfBinds, rhssOfBind, rhssOfAlts, collectBinders, collectTyBinders, collectTyAndValBinders, collectNBinders, collectArgs, collectArgsTicks, flattenBinds, exprToType, exprToCoercion_maybe, applyTypeToArg, isValArg, isTypeArg, isTyCoArg, valArgCount, valBndrCount, isRuntimeArg, isRuntimeVar, -- * Tick-related functions tickishCounts, tickishScoped, tickishScopesLike, tickishFloatable, tickishCanSplit, mkNoCount, mkNoScope, tickishIsCode, tickishPlace, tickishContains, -- * Unfolding data types Unfolding(..), UnfoldingGuidance(..), UnfoldingSource(..), -- ** Constructing 'Unfolding's noUnfolding, bootUnfolding, evaldUnfolding, mkOtherCon, unSaturatedOk, needSaturated, boringCxtOk, boringCxtNotOk, -- ** Predicates and deconstruction on 'Unfolding' unfoldingTemplate, expandUnfolding_maybe, maybeUnfoldingTemplate, otherCons, isValueUnfolding, isEvaldUnfolding, isCheapUnfolding, isExpandableUnfolding, isConLikeUnfolding, isCompulsoryUnfolding, isStableUnfolding, isFragileUnfolding, hasSomeUnfolding, isBootUnfolding, canUnfold, neverUnfoldGuidance, isStableSource, -- * Annotated expression data types AnnExpr, AnnExpr'(..), AnnBind(..), AnnAlt, -- ** Operations on annotated expressions collectAnnArgs, collectAnnArgsTicks, -- ** Operations on annotations deAnnotate, deAnnotate', deAnnAlt, deAnnBind, collectAnnBndrs, collectNAnnBndrs, -- * Orphanhood IsOrphan(..), isOrphan, notOrphan, chooseOrphanAnchor, -- * Core rule data types CoreRule(..), RuleBase, RuleName, RuleFun, IdUnfoldingFun, InScopeEnv, RuleEnv(..), mkRuleEnv, emptyRuleEnv, -- ** Operations on 'CoreRule's ruleArity, ruleName, ruleIdName, ruleActivation, setRuleIdName, ruleModule, isBuiltinRule, isLocalRule, isAutoRule, -- * Core vectorisation declarations data type CoreVect(..) ) where #include "HsVersions.h" import GhcPrelude import CostCentre import VarEnv( InScopeSet ) import Var import Type import Coercion import Name import NameSet import NameEnv( NameEnv, emptyNameEnv ) import Literal import DataCon import Module import TyCon import BasicTypes import DynFlags import Outputable import Util import UniqSet import SrcLoc ( RealSrcSpan, containsSpan ) import Binary import Data.Data hiding (TyCon) import Data.Int import Data.Word infixl 4 `mkApps`, `mkTyApps`, `mkVarApps`, `App`, `mkCoApps` -- Left associative, so that we can say (f `mkTyApps` xs `mkVarApps` ys) {- ************************************************************************ * * \subsection{The main data types} * * ************************************************************************ These data types are the heart of the compiler -} -- | This is the data type that represents GHCs core intermediate language. Currently -- GHC uses System FC <https://www.microsoft.com/en-us/research/publication/system-f-with-type-equality-coercions/> for this purpose, -- which is closely related to the simpler and better known System F <http://en.wikipedia.org/wiki/System_F>. -- -- We get from Haskell source to this Core language in a number of stages: -- -- 1. The source code is parsed into an abstract syntax tree, which is represented -- by the data type 'HsExpr.HsExpr' with the names being 'RdrName.RdrNames' -- -- 2. This syntax tree is /renamed/, which attaches a 'Unique.Unique' to every 'RdrName.RdrName' -- (yielding a 'Name.Name') to disambiguate identifiers which are lexically identical. -- For example, this program: -- -- @ -- f x = let f x = x + 1 -- in f (x - 2) -- @ -- -- Would be renamed by having 'Unique's attached so it looked something like this: -- -- @ -- f_1 x_2 = let f_3 x_4 = x_4 + 1 -- in f_3 (x_2 - 2) -- @ -- But see Note [Shadowing] below. -- -- 3. The resulting syntax tree undergoes type checking (which also deals with instantiating -- type class arguments) to yield a 'HsExpr.HsExpr' type that has 'Id.Id' as it's names. -- -- 4. Finally the syntax tree is /desugared/ from the expressive 'HsExpr.HsExpr' type into -- this 'Expr' type, which has far fewer constructors and hence is easier to perform -- optimization, analysis and code generation on. -- -- The type parameter @b@ is for the type of binders in the expression tree. -- -- The language consists of the following elements: -- -- * Variables -- -- * Primitive literals -- -- * Applications: note that the argument may be a 'Type'. -- See Note [CoreSyn let/app invariant] -- See Note [Levity polymorphism invariants] -- -- * Lambda abstraction -- See Note [Levity polymorphism invariants] -- -- * Recursive and non recursive @let@s. Operationally -- this corresponds to allocating a thunk for the things -- bound and then executing the sub-expression. -- -- #top_level_invariant# -- #letrec_invariant# -- -- The right hand sides of all top-level and recursive @let@s -- /must/ be of lifted type (see "Type#type_classification" for -- the meaning of /lifted/ vs. /unlifted/). There is one exception -- to this rule, top-level @let@s are allowed to bind primitive -- string literals, see Note [CoreSyn top-level string literals]. -- -- See Note [CoreSyn let/app invariant] -- See Note [Levity polymorphism invariants] -- -- #type_let# -- We allow a /non-recursive/ let to bind a type variable, thus: -- -- > Let (NonRec tv (Type ty)) body -- -- This can be very convenient for postponing type substitutions until -- the next run of the simplifier. -- -- At the moment, the rest of the compiler only deals with type-let -- in a Let expression, rather than at top level. We may want to revist -- this choice. -- -- * Case expression. Operationally this corresponds to evaluating -- the scrutinee (expression examined) to weak head normal form -- and then examining at most one level of resulting constructor (i.e. you -- cannot do nested pattern matching directly with this). -- -- The binder gets bound to the value of the scrutinee, -- and the 'Type' must be that of all the case alternatives -- -- #case_invariants# -- This is one of the more complicated elements of the Core language, -- and comes with a number of restrictions: -- -- 1. The list of alternatives may be empty; -- See Note [Empty case alternatives] -- -- 2. The 'DEFAULT' case alternative must be first in the list, -- if it occurs at all. -- -- 3. The remaining cases are in order of increasing -- tag (for 'DataAlts') or -- lit (for 'LitAlts'). -- This makes finding the relevant constructor easy, -- and makes comparison easier too. -- -- 4. The list of alternatives must be exhaustive. An /exhaustive/ case -- does not necessarily mention all constructors: -- -- @ -- data Foo = Red | Green | Blue -- ... case x of -- Red -> True -- other -> f (case x of -- Green -> ... -- Blue -> ... ) ... -- @ -- -- The inner case does not need a @Red@ alternative, because @x@ -- can't be @Red@ at that program point. -- -- 5. Floating-point values must not be scrutinised against literals. -- See Trac #9238 and Note [Rules for floating-point comparisons] -- in PrelRules for rationale. -- -- * Cast an expression to a particular type. -- This is used to implement @newtype@s (a @newtype@ constructor or -- destructor just becomes a 'Cast' in Core) and GADTs. -- -- * Notes. These allow general information to be added to expressions -- in the syntax tree -- -- * A type: this should only show up at the top level of an Arg -- -- * A coercion -- If you edit this type, you may need to update the GHC formalism -- See Note [GHC Formalism] in coreSyn/CoreLint.hs data Expr b = Var Id | Lit Literal | App (Expr b) (Arg b) | Lam b (Expr b) | Let (Bind b) (Expr b) | Case (Expr b) b Type [Alt b] -- See #case_invariants# | Cast (Expr b) Coercion | Tick (Tickish Id) (Expr b) | Type Type | Coercion Coercion deriving Data -- | Type synonym for expressions that occur in function argument positions. -- Only 'Arg' should contain a 'Type' at top level, general 'Expr' should not type Arg b = Expr b -- | A case split alternative. Consists of the constructor leading to the alternative, -- the variables bound from the constructor, and the expression to be executed given that binding. -- The default alternative is @(DEFAULT, [], rhs)@ -- If you edit this type, you may need to update the GHC formalism -- See Note [GHC Formalism] in coreSyn/CoreLint.hs type Alt b = (AltCon, [b], Expr b) -- | A case alternative constructor (i.e. pattern match) -- If you edit this type, you may need to update the GHC formalism -- See Note [GHC Formalism] in coreSyn/CoreLint.hs data AltCon = DataAlt DataCon -- ^ A plain data constructor: @case e of { Foo x -> ... }@. -- Invariant: the 'DataCon' is always from a @data@ type, and never from a @newtype@ | LitAlt Literal -- ^ A literal: @case e of { 1 -> ... }@ -- Invariant: always an *unlifted* literal -- See Note [Literal alternatives] | DEFAULT -- ^ Trivial alternative: @case e of { _ -> ... }@ deriving (Eq, Data) -- This instance is a bit shady. It can only be used to compare AltCons for -- a single type constructor. Fortunately, it seems quite unlikely that we'll -- ever need to compare AltCons for different type constructors. -- The instance adheres to the order described in [CoreSyn case invariants] instance Ord AltCon where compare (DataAlt con1) (DataAlt con2) = ASSERT( dataConTyCon con1 == dataConTyCon con2 ) compare (dataConTag con1) (dataConTag con2) compare (DataAlt _) _ = GT compare _ (DataAlt _) = LT compare (LitAlt l1) (LitAlt l2) = compare l1 l2 compare (LitAlt _) DEFAULT = GT compare DEFAULT DEFAULT = EQ compare DEFAULT _ = LT -- | Binding, used for top level bindings in a module and local bindings in a @let@. -- If you edit this type, you may need to update the GHC formalism -- See Note [GHC Formalism] in coreSyn/CoreLint.hs data Bind b = NonRec b (Expr b) | Rec [(b, (Expr b))] deriving Data {- Note [Shadowing] ~~~~~~~~~~~~~~~~ While various passes attempt to rename on-the-fly in a manner that avoids "shadowing" (thereby simplifying downstream optimizations), neither the simplifier nor any other pass GUARANTEES that shadowing is avoided. Thus, all passes SHOULD work fine even in the presence of arbitrary shadowing in their inputs. In particular, scrutinee variables `x` in expressions of the form `Case e x t` are often renamed to variables with a prefix "wild_". These "wild" variables may appear in the body of the case-expression, and further, may be shadowed within the body. So the Unique in a Var is not really unique at all. Still, it's very useful to give a constant-time equality/ordering for Vars, and to give a key that can be used to make sets of Vars (VarSet), or mappings from Vars to other things (VarEnv). Moreover, if you do want to eliminate shadowing, you can give a new Unique to an Id without changing its printable name, which makes debugging easier. Note [Literal alternatives] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Literal alternatives (LitAlt lit) are always for *un-lifted* literals. We have one literal, a literal Integer, that is lifted, and we don't allow in a LitAlt, because LitAlt cases don't do any evaluation. Also (see Trac #5603) if you say case 3 of S# x -> ... J# _ _ -> ... (where S#, J# are the constructors for Integer) we don't want the simplifier calling findAlt with argument (LitAlt 3). No no. Integer literals are an opaque encoding of an algebraic data type, not of an unlifted literal, like all the others. Also, we do not permit case analysis with literal patterns on floating-point types. See Trac #9238 and Note [Rules for floating-point comparisons] in PrelRules for the rationale for this restriction. -------------------------- CoreSyn INVARIANTS --------------------------- Note [CoreSyn top-level invariant] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ See #toplevel_invariant# Note [CoreSyn letrec invariant] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ See #letrec_invariant# Note [CoreSyn top-level string literals] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ As an exception to the usual rule that top-level binders must be lifted, we allow binding primitive string literals (of type Addr#) of type Addr# at the top level. This allows us to share string literals earlier in the pipeline and crucially allows other optimizations in the Core2Core pipeline to fire. Consider, f n = let a::Addr# = "foo"# in \x -> blah In order to be able to inline `f`, we would like to float `a` to the top. Another option would be to inline `a`, but that would lead to duplicating string literals, which we want to avoid. See Trac #8472. The solution is simply to allow top-level unlifted binders. We can't allow arbitrary unlifted expression at the top-level though, unlifted binders cannot be thunks, so we just allow string literals. It is important to note that top-level primitive string literals cannot be wrapped in Ticks, as is otherwise done with lifted bindings. CoreToStg expects to see just a plain (Lit (MachStr ...)) expression on the RHS of primitive string bindings; anything else and things break. CoreLint checks this invariant. Also see Note [Compilation plan for top-level string literals]. Note [Compilation plan for top-level string literals] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Here is a summary on how top-level string literals are handled by various parts of the compilation pipeline. * In the source language, there is no way to bind a primitive string literal at the top leve. * In Core, we have a special rule that permits top-level Addr# bindings. See Note [CoreSyn top-level string literals]. Core-to-core passes may introduce new top-level string literals. * In STG, top-level string literals are explicitly represented in the syntax tree. * A top-level string literal may end up exported from a module. In this case, in the object file, the content of the exported literal is given a label with the _bytes suffix. Note [CoreSyn let/app invariant] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The let/app invariant the right hand side of a non-recursive 'Let', and the argument of an 'App', /may/ be of unlifted type, but only if the expression is ok-for-speculation or the 'Let' is for a join point. This means that the let can be floated around without difficulty. For example, this is OK: y::Int# = x +# 1# But this is not, as it may affect termination if the expression is floated out: y::Int# = fac 4# In this situation you should use @case@ rather than a @let@. The function 'CoreUtils.needsCaseBinding' can help you determine which to generate, or alternatively use 'MkCore.mkCoreLet' rather than this constructor directly, which will generate a @case@ if necessary The let/app invariant is initially enforced by mkCoreLet and mkCoreApp in coreSyn/MkCore. Note [CoreSyn case invariants] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ See #case_invariants# Note [Levity polymorphism invariants] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The levity-polymorphism invariants are these (as per "Levity Polymorphism", PLDI '17): * The type of a term-binder must not be levity-polymorphic, unless it is a let(rec)-bound join point (see Note [Invariants on join points]) * The type of the argument of an App must not be levity-polymorphic. A type (t::TYPE r) is "levity polymorphic" if 'r' has any free variables. For example \(r::RuntimeRep). \(a::TYPE r). \(x::a). e is illegal because x's type has kind (TYPE r), which has 'r' free. See Note [Levity polymorphism checking] in DsMonad to see where these invariants are established for user-written code. Note [CoreSyn let goal] ~~~~~~~~~~~~~~~~~~~~~~~ * The simplifier tries to ensure that if the RHS of a let is a constructor application, its arguments are trivial, so that the constructor can be inlined vigorously. Note [Type let] ~~~~~~~~~~~~~~~ See #type_let# Note [Empty case alternatives] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The alternatives of a case expression should be exhaustive. But this exhaustive list can be empty! * A case expression can have empty alternatives if (and only if) the scrutinee is bound to raise an exception or diverge. When do we know this? See Note [Bottoming expressions] in CoreUtils. * The possiblity of empty alternatives is one reason we need a type on the case expression: if the alternatives are empty we can't get the type from the alternatives! * In the case of empty types (see Note [Bottoming expressions]), say data T we do NOT want to replace case (x::T) of Bool {} --> error Bool "Inaccessible case" because x might raise an exception, and *that*'s what we want to see! (Trac #6067 is an example.) To preserve semantics we'd have to say x `seq` error Bool "Inaccessible case" but the 'seq' is just a case, so we are back to square 1. Or I suppose we could say x |> UnsafeCoerce T Bool but that loses all trace of the fact that this originated with an empty set of alternatives. * We can use the empty-alternative construct to coerce error values from one type to another. For example f :: Int -> Int f n = error "urk" g :: Int -> (# Char, Bool #) g x = case f x of { 0 -> ..., n -> ... } Then if we inline f in g's RHS we get case (error Int "urk") of (# Char, Bool #) { ... } and we can discard the alternatives since the scrutinee is bottom to give case (error Int "urk") of (# Char, Bool #) {} This is nicer than using an unsafe coerce between Int ~ (# Char,Bool #), if for no other reason that we don't need to instantiate the (~) at an unboxed type. * We treat a case expression with empty alternatives as trivial iff its scrutinee is (see CoreUtils.exprIsTrivial). This is actually important; see Note [Empty case is trivial] in CoreUtils * An empty case is replaced by its scrutinee during the CoreToStg conversion; remember STG is un-typed, so there is no need for the empty case to do the type conversion. Note [Join points] ~~~~~~~~~~~~~~~~~~ In Core, a *join point* is a specially tagged function whose only occurrences are saturated tail calls. A tail call can appear in these places: 1. In the branches (not the scrutinee) of a case 2. Underneath a let (value or join point) 3. Inside another join point We write a join-point declaration as join j @a @b x y = e1 in e2, like a let binding but with "join" instead (or "join rec" for "let rec"). Note that we put the parameters before the = rather than using lambdas; this is because it's relevant how many parameters the join point takes *as a join point.* This number is called the *join arity,* distinct from arity because it counts types as well as values. Note that a join point may return a lambda! So join j x = x + 1 is different from join j = \x -> x + 1 The former has join arity 1, while the latter has join arity 0. The identifier for a join point is called a join id or a *label.* An invocation is called a *jump.* We write a jump using the jump keyword: jump j 3 The words *label* and *jump* are evocative of assembly code (or Cmm) for a reason: join points are indeed compiled as labeled blocks, and jumps become actual jumps (plus argument passing and stack adjustment). There is no closure allocated and only a fraction of the function-call overhead. Hence we would like as many functions as possible to become join points (see OccurAnal) and the type rules for join points ensure we preserve the properties that make them efficient. In the actual AST, a join point is indicated by the IdDetails of the binder: a local value binding gets 'VanillaId' but a join point gets a 'JoinId' with its join arity. For more details, see the paper: Luke Maurer, Paul Downen, Zena Ariola, and Simon Peyton Jones. "Compiling without continuations." Submitted to PLDI'17. https://www.microsoft.com/en-us/research/publication/compiling-without-continuations/ Note [Invariants on join points] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Join points must follow these invariants: 1. All occurrences must be tail calls. Each of these tail calls must pass the same number of arguments, counting both types and values; we call this the "join arity" (to distinguish from regular arity, which only counts values). 2. For join arity n, the right-hand side must begin with at least n lambdas. No ticks, no casts, just lambdas! C.f. CoreUtils.joinRhsArity. 2a. Moreover, this same constraint applies to any unfolding of the binder. Reason: if we want to push a continuation into the RHS we must push it into the unfolding as well. 3. If the binding is recursive, then all other bindings in the recursive group must also be join points. 4. The binding's type must not be polymorphic in its return type (as defined in Note [The polymorphism rule of join points]). However, join points have simpler invariants in other ways 5. A join point can have an unboxed type without the RHS being ok-for-speculation (i.e. drop the let/app invariant) e.g. let j :: Int# = factorial x in ... 6. A join point can have a levity-polymorphic RHS e.g. let j :: r :: TYPE l = fail void# in ... This happened in an intermediate program Trac #13394 Examples: join j1 x = 1 + x in jump j (jump j x) -- Fails 1: non-tail call join j1' x = 1 + x in if even a then jump j1 a else jump j1 a b -- Fails 1: inconsistent calls join j2 x = flip (+) x in j2 1 2 -- Fails 2: not enough lambdas join j2' x = \y -> x + y in j3 1 -- Passes: extra lams ok join j @a (x :: a) = x -- Fails 4: polymorphic in ret type Invariant 1 applies to left-hand sides of rewrite rules, so a rule for a join point must have an exact call as its LHS. Strictly speaking, invariant 3 is redundant, since a call from inside a lazy binding isn't a tail call. Since a let-bound value can't invoke a free join point, then, they can't be mutually recursive. (A Core binding group *can* include spurious extra bindings if the occurrence analyser hasn't run, so invariant 3 does still need to be checked.) For the rigorous definition of "tail call", see Section 3 of the paper (Note [Join points]). Invariant 4 is subtle; see Note [The polymorphism rule of join points]. Core Lint will check these invariants, anticipating that any binder whose OccInfo is marked AlwaysTailCalled will become a join point as soon as the simplifier (or simpleOptPgm) runs. Note [The type of a join point] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A join point has the same type it would have as a function. That is, if it takes an Int and a Bool and its body produces a String, its type is `Int -> Bool -> String`. Natural as this may seem, it can be awkward. A join point shouldn't be thought to "return" in the same sense a function does---a jump is one-way. This is crucial for understanding how case-of-case interacts with join points: case (join j :: Int -> Bool -> String j x y = ... in jump j z w) of "" -> True _ -> False The simplifier will pull the case into the join point (see Note [Case-of-case and join points] in Simplify): join j :: Int -> Bool -> Bool -- changed! j x y = case ... of "" -> True _ -> False in jump j z w The body of the join point now returns a Bool, so the label `j` has to have its type updated accordingly. Inconvenient though this may be, it has the advantage that 'CoreUtils.exprType' can still return a type for any expression, including a jump. This differs from the paper (see Note [Invariants on join points]). In the paper, we instead give j the type `Int -> Bool -> forall a. a`. Then each jump carries the "return type" as a parameter, exactly the way other non-returning functions like `error` work: case (join j :: Int -> Bool -> forall a. a j x y = ... in jump j z w @String) of "" -> True _ -> False Now we can move the case inward and we only have to change the jump: join j :: Int -> Bool -> forall a. a j x y = case ... of "" -> True _ -> False in jump j z w @Bool (Core Lint would still check that the body of the join point has the right type; that type would simply not be reflected in the join id.) Note [The polymorphism rule of join points] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Invariant 4 of Note [Invariants on join points] forbids a join point to be polymorphic in its return type. That is, if its type is forall a1 ... ak. t1 -> ... -> tn -> r where its join arity is k+n, none of the type parameters ai may occur free in r. In some way, this falls out of the fact that given join j @a1 ... @ak x1 ... xn = e1 in e2 then all calls to `j` are in tail-call positions of `e`, and expressions in tail-call positions in `e` have the same type as `e`. Therefore the type of `e1` -- the return type of the join point -- must be the same as the type of e2. Since the type variables aren't bound in `e2`, its type can't include them, and thus neither can the type of `e1`. This unfortunately prevents the `go` in the following code from being a join-point: iter :: forall a. Int -> (a -> a) -> a -> a iter @a n f x = go @a n f x where go :: forall a. Int -> (a -> a) -> a -> a go @a 0 _ x = x go @a n f x = go @a (n-1) f (f x) In this case, a static argument transformation would fix that (see ticket #14620): iter :: forall a. Int -> (a -> a) -> a -> a iter @a n f x = go' @a n f x where go' :: Int -> (a -> a) -> a -> a go' 0 _ x = x go' n f x = go' (n-1) f (f x) In general, loopification could be employed to do that (see #14068.) Can we simply drop the requirement, and allow `go` to be a join-point? We could, and it would work. But we could not longer apply the case-of-join-point transformation universally. This transformation would do: case (join go @a n f x = case n of 0 -> x n -> go @a (n-1) f (f x) in go @Bool n neg True) of True -> e1; False -> e2 ===> join go @a n f x = case n of 0 -> case x of True -> e1; False -> e2 n -> go @a (n-1) f (f x) in go @Bool n neg True but that is ill-typed, as `x` is type `a`, not `Bool`. This is also justifies why we do not consider the `e` in `e |> co` to be in tail position: A cast changes the type, but the type must be the same. But operationally, casts are vacuous, so this is a bit unfortunate! See #14610 for ideas how to fix this. ************************************************************************ * * In/Out type synonyms * * ********************************************************************* -} {- Many passes apply a substitution, and it's very handy to have type synonyms to remind us whether or not the substitution has been applied -} -- Pre-cloning or substitution type InBndr = CoreBndr type InType = Type type InKind = Kind type InBind = CoreBind type InExpr = CoreExpr type InAlt = CoreAlt type InArg = CoreArg type InCoercion = Coercion -- Post-cloning or substitution type OutBndr = CoreBndr type OutType = Type type OutKind = Kind type OutCoercion = Coercion type OutBind = CoreBind type OutExpr = CoreExpr type OutAlt = CoreAlt type OutArg = CoreArg {- ********************************************************************* * * Ticks * * ************************************************************************ -} -- | Allows attaching extra information to points in expressions -- If you edit this type, you may need to update the GHC formalism -- See Note [GHC Formalism] in coreSyn/CoreLint.hs data Tickish id = -- | An @{-# SCC #-}@ profiling annotation, either automatically -- added by the desugarer as a result of -auto-all, or added by -- the user. ProfNote { profNoteCC :: CostCentre, -- ^ the cost centre profNoteCount :: !Bool, -- ^ bump the entry count? profNoteScope :: !Bool -- ^ scopes over the enclosed expression -- (i.e. not just a tick) } -- | A "tick" used by HPC to track the execution of each -- subexpression in the original source code. | HpcTick { tickModule :: Module, tickId :: !Int } -- | A breakpoint for the GHCi debugger. This behaves like an HPC -- tick, but has a list of free variables which will be available -- for inspection in GHCi when the program stops at the breakpoint. -- -- NB. we must take account of these Ids when (a) counting free variables, -- and (b) substituting (don't substitute for them) | Breakpoint { breakpointId :: !Int , breakpointFVs :: [id] -- ^ the order of this list is important: -- it matches the order of the lists in the -- appropriate entry in HscTypes.ModBreaks. -- -- Careful about substitution! See -- Note [substTickish] in CoreSubst. } -- | A source note. -- -- Source notes are pure annotations: Their presence should neither -- influence compilation nor execution. The semantics are given by -- causality: The presence of a source note means that a local -- change in the referenced source code span will possibly provoke -- the generated code to change. On the flip-side, the functionality -- of annotated code *must* be invariant against changes to all -- source code *except* the spans referenced in the source notes -- (see "Causality of optimized Haskell" paper for details). -- -- Therefore extending the scope of any given source note is always -- valid. Note that it is still undesirable though, as this reduces -- their usefulness for debugging and profiling. Therefore we will -- generally try only to make use of this property where it is -- necessary to enable optimizations. | SourceNote { sourceSpan :: RealSrcSpan -- ^ Source covered , sourceName :: String -- ^ Name for source location -- (uses same names as CCs) } deriving (Eq, Ord, Data) -- | A "counting tick" (where tickishCounts is True) is one that -- counts evaluations in some way. We cannot discard a counting tick, -- and the compiler should preserve the number of counting ticks as -- far as possible. -- -- However, we still allow the simplifier to increase or decrease -- sharing, so in practice the actual number of ticks may vary, except -- that we never change the value from zero to non-zero or vice versa. tickishCounts :: Tickish id -> Bool tickishCounts n@ProfNote{} = profNoteCount n tickishCounts HpcTick{} = True tickishCounts Breakpoint{} = True tickishCounts _ = False -- | Specifies the scoping behaviour of ticks. This governs the -- behaviour of ticks that care about the covered code and the cost -- associated with it. Important for ticks relating to profiling. data TickishScoping = -- | No scoping: The tick does not care about what code it -- covers. Transformations can freely move code inside as well as -- outside without any additional annotation obligations NoScope -- | Soft scoping: We want all code that is covered to stay -- covered. Note that this scope type does not forbid -- transformations from happening, as long as all results of -- the transformations are still covered by this tick or a copy of -- it. For example -- -- let x = tick<...> (let y = foo in bar) in baz -- ===> -- let x = tick<...> bar; y = tick<...> foo in baz -- -- Is a valid transformation as far as "bar" and "foo" is -- concerned, because both still are scoped over by the tick. -- -- Note though that one might object to the "let" not being -- covered by the tick any more. However, we are generally lax -- with this - constant costs don't matter too much, and given -- that the "let" was effectively merged we can view it as having -- lost its identity anyway. -- -- Also note that this scoping behaviour allows floating a tick -- "upwards" in pretty much any situation. For example: -- -- case foo of x -> tick<...> bar -- ==> -- tick<...> case foo of x -> bar -- -- While this is always leagl, we want to make a best effort to -- only make us of this where it exposes transformation -- opportunities. | SoftScope -- | Cost centre scoping: We don't want any costs to move to other -- cost-centre stacks. This means we not only want no code or cost -- to get moved out of their cost centres, but we also object to -- code getting associated with new cost-centre ticks - or -- changing the order in which they get applied. -- -- A rule of thumb is that we don't want any code to gain new -- annotations. However, there are notable exceptions, for -- example: -- -- let f = \y -> foo in tick<...> ... (f x) ... -- ==> -- tick<...> ... foo[x/y] ... -- -- In-lining lambdas like this is always legal, because inlining a -- function does not change the cost-centre stack when the -- function is called. | CostCentreScope deriving (Eq) -- | Returns the intended scoping rule for a Tickish tickishScoped :: Tickish id -> TickishScoping tickishScoped n@ProfNote{} | profNoteScope n = CostCentreScope | otherwise = NoScope tickishScoped HpcTick{} = NoScope tickishScoped Breakpoint{} = CostCentreScope -- Breakpoints are scoped: eventually we're going to do call -- stacks, but also this helps prevent the simplifier from moving -- breakpoints around and changing their result type (see #1531). tickishScoped SourceNote{} = SoftScope -- | Returns whether the tick scoping rule is at least as permissive -- as the given scoping rule. tickishScopesLike :: Tickish id -> TickishScoping -> Bool tickishScopesLike t scope = tickishScoped t `like` scope where NoScope `like` _ = True _ `like` NoScope = False SoftScope `like` _ = True _ `like` SoftScope = False CostCentreScope `like` _ = True -- | Returns @True@ for ticks that can be floated upwards easily even -- where it might change execution counts, such as: -- -- Just (tick<...> foo) -- ==> -- tick<...> (Just foo) -- -- This is a combination of @tickishSoftScope@ and -- @tickishCounts@. Note that in principle splittable ticks can become -- floatable using @mkNoTick@ -- even though there's currently no -- tickish for which that is the case. tickishFloatable :: Tickish id -> Bool tickishFloatable t = t `tickishScopesLike` SoftScope && not (tickishCounts t) -- | Returns @True@ for a tick that is both counting /and/ scoping and -- can be split into its (tick, scope) parts using 'mkNoScope' and -- 'mkNoTick' respectively. tickishCanSplit :: Tickish id -> Bool tickishCanSplit ProfNote{profNoteScope = True, profNoteCount = True} = True tickishCanSplit _ = False mkNoCount :: Tickish id -> Tickish id mkNoCount n | not (tickishCounts n) = n | not (tickishCanSplit n) = panic "mkNoCount: Cannot split!" mkNoCount n@ProfNote{} = n {profNoteCount = False} mkNoCount _ = panic "mkNoCount: Undefined split!" mkNoScope :: Tickish id -> Tickish id mkNoScope n | tickishScoped n == NoScope = n | not (tickishCanSplit n) = panic "mkNoScope: Cannot split!" mkNoScope n@ProfNote{} = n {profNoteScope = False} mkNoScope _ = panic "mkNoScope: Undefined split!" -- | Return @True@ if this source annotation compiles to some backend -- code. Without this flag, the tickish is seen as a simple annotation -- that does not have any associated evaluation code. -- -- What this means that we are allowed to disregard the tick if doing -- so means that we can skip generating any code in the first place. A -- typical example is top-level bindings: -- -- foo = tick<...> \y -> ... -- ==> -- foo = \y -> tick<...> ... -- -- Here there is just no operational difference between the first and -- the second version. Therefore code generation should simply -- translate the code as if it found the latter. tickishIsCode :: Tickish id -> Bool tickishIsCode SourceNote{} = False tickishIsCode _tickish = True -- all the rest for now -- | Governs the kind of expression that the tick gets placed on when -- annotating for example using @mkTick@. If we find that we want to -- put a tickish on an expression ruled out here, we try to float it -- inwards until we find a suitable expression. data TickishPlacement = -- | Place ticks exactly on run-time expressions. We can still -- move the tick through pure compile-time constructs such as -- other ticks, casts or type lambdas. This is the most -- restrictive placement rule for ticks, as all tickishs have in -- common that they want to track runtime processes. The only -- legal placement rule for counting ticks. PlaceRuntime -- | As @PlaceRuntime@, but we float the tick through all -- lambdas. This makes sense where there is little difference -- between annotating the lambda and annotating the lambda's code. | PlaceNonLam -- | In addition to floating through lambdas, cost-centre style -- tickishs can also be moved from constructors, non-function -- variables and literals. For example: -- -- let x = scc<...> C (scc<...> y) (scc<...> 3) in ... -- -- Neither the constructor application, the variable or the -- literal are likely to have any cost worth mentioning. And even -- if y names a thunk, the call would not care about the -- evaluation context. Therefore removing all annotations in the -- above example is safe. | PlaceCostCentre deriving (Eq) -- | Placement behaviour we want for the ticks tickishPlace :: Tickish id -> TickishPlacement tickishPlace n@ProfNote{} | profNoteCount n = PlaceRuntime | otherwise = PlaceCostCentre tickishPlace HpcTick{} = PlaceRuntime tickishPlace Breakpoint{} = PlaceRuntime tickishPlace SourceNote{} = PlaceNonLam -- | Returns whether one tick "contains" the other one, therefore -- making the second tick redundant. tickishContains :: Eq b => Tickish b -> Tickish b -> Bool tickishContains (SourceNote sp1 n1) (SourceNote sp2 n2) = containsSpan sp1 sp2 && n1 == n2 -- compare the String last tickishContains t1 t2 = t1 == t2 {- ************************************************************************ * * Orphans * * ************************************************************************ -} -- | Is this instance an orphan? If it is not an orphan, contains an 'OccName' -- witnessing the instance's non-orphanhood. -- See Note [Orphans] data IsOrphan = IsOrphan | NotOrphan OccName -- The OccName 'n' witnesses the instance's non-orphanhood -- In that case, the instance is fingerprinted as part -- of the definition of 'n's definition deriving Data -- | Returns true if 'IsOrphan' is orphan. isOrphan :: IsOrphan -> Bool isOrphan IsOrphan = True isOrphan _ = False -- | Returns true if 'IsOrphan' is not an orphan. notOrphan :: IsOrphan -> Bool notOrphan NotOrphan{} = True notOrphan _ = False chooseOrphanAnchor :: NameSet -> IsOrphan -- Something (rule, instance) is relate to all the Names in this -- list. Choose one of them to be an "anchor" for the orphan. We make -- the choice deterministic to avoid gratuitious changes in the ABI -- hash (Trac #4012). Specifically, use lexicographic comparison of -- OccName rather than comparing Uniques -- -- NB: 'minimum' use Ord, and (Ord OccName) works lexicographically -- chooseOrphanAnchor local_names | isEmptyNameSet local_names = IsOrphan | otherwise = NotOrphan (minimum occs) where occs = map nameOccName $ nonDetEltsUniqSet local_names -- It's OK to use nonDetEltsUFM here, see comments above instance Binary IsOrphan where put_ bh IsOrphan = putByte bh 0 put_ bh (NotOrphan n) = do putByte bh 1 put_ bh n get bh = do h <- getByte bh case h of 0 -> return IsOrphan _ -> do n <- get bh return $ NotOrphan n {- Note [Orphans] ~~~~~~~~~~~~~~ Class instances, rules, and family instances are divided into orphans and non-orphans. Roughly speaking, an instance/rule is an orphan if its left hand side mentions nothing defined in this module. Orphan-hood has two major consequences * A module that contains orphans is called an "orphan module". If the module being compiled depends (transitively) on an oprhan module M, then M.hi is read in regardless of whether M is oherwise needed. This is to ensure that we don't miss any instance decls in M. But it's painful, because it means we need to keep track of all the orphan modules below us. * A non-orphan is not finger-printed separately. Instead, for fingerprinting purposes it is treated as part of the entity it mentions on the LHS. For example data T = T1 | T2 instance Eq T where .... The instance (Eq T) is incorprated as part of T's fingerprint. In contrast, orphans are all fingerprinted together in the mi_orph_hash field of the ModIface. See MkIface.addFingerprints. Orphan-hood is computed * For class instances: when we make a ClsInst (because it is needed during instance lookup) * For rules and family instances: when we generate an IfaceRule (MkIface.coreRuleToIfaceRule) or IfaceFamInst (MkIface.instanceToIfaceInst) -} {- ************************************************************************ * * \subsection{Transformation rules} * * ************************************************************************ The CoreRule type and its friends are dealt with mainly in CoreRules, but CoreFVs, Subst, PprCore, CoreTidy also inspect the representation. -} -- | Gathers a collection of 'CoreRule's. Maps (the name of) an 'Id' to its rules type RuleBase = NameEnv [CoreRule] -- The rules are unordered; -- we sort out any overlaps on lookup -- | A full rule environment which we can apply rules from. Like a 'RuleBase', -- but it also includes the set of visible orphans we use to filter out orphan -- rules which are not visible (even though we can see them...) data RuleEnv = RuleEnv { re_base :: RuleBase , re_visible_orphs :: ModuleSet } mkRuleEnv :: RuleBase -> [Module] -> RuleEnv mkRuleEnv rules vis_orphs = RuleEnv rules (mkModuleSet vis_orphs) emptyRuleEnv :: RuleEnv emptyRuleEnv = RuleEnv emptyNameEnv emptyModuleSet -- | A 'CoreRule' is: -- -- * \"Local\" if the function it is a rule for is defined in the -- same module as the rule itself. -- -- * \"Orphan\" if nothing on the LHS is defined in the same module -- as the rule itself data CoreRule = Rule { ru_name :: RuleName, -- ^ Name of the rule, for communication with the user ru_act :: Activation, -- ^ When the rule is active -- Rough-matching stuff -- see comments with InstEnv.ClsInst( is_cls, is_rough ) ru_fn :: Name, -- ^ Name of the 'Id.Id' at the head of this rule ru_rough :: [Maybe Name], -- ^ Name at the head of each argument to the left hand side -- Proper-matching stuff -- see comments with InstEnv.ClsInst( is_tvs, is_tys ) ru_bndrs :: [CoreBndr], -- ^ Variables quantified over ru_args :: [CoreExpr], -- ^ Left hand side arguments -- And the right-hand side ru_rhs :: CoreExpr, -- ^ Right hand side of the rule -- Occurrence info is guaranteed correct -- See Note [OccInfo in unfoldings and rules] -- Locality ru_auto :: Bool, -- ^ @True@ <=> this rule is auto-generated -- (notably by Specialise or SpecConstr) -- @False@ <=> generated at the user's behest -- See Note [Trimming auto-rules] in TidyPgm -- for the sole purpose of this field. ru_origin :: !Module, -- ^ 'Module' the rule was defined in, used -- to test if we should see an orphan rule. ru_orphan :: !IsOrphan, -- ^ Whether or not the rule is an orphan. ru_local :: Bool -- ^ @True@ iff the fn at the head of the rule is -- defined in the same module as the rule -- and is not an implicit 'Id' (like a record selector, -- class operation, or data constructor). This -- is different from 'ru_orphan', where a rule -- can avoid being an orphan if *any* Name in -- LHS of the rule was defined in the same -- module as the rule. } -- | Built-in rules are used for constant folding -- and suchlike. They have no free variables. -- A built-in rule is always visible (there is no such thing as -- an orphan built-in rule.) | BuiltinRule { ru_name :: RuleName, -- ^ As above ru_fn :: Name, -- ^ As above ru_nargs :: Int, -- ^ Number of arguments that 'ru_try' consumes, -- if it fires, including type arguments ru_try :: RuleFun -- ^ This function does the rewrite. It given too many -- arguments, it simply discards them; the returned 'CoreExpr' -- is just the rewrite of 'ru_fn' applied to the first 'ru_nargs' args } -- See Note [Extra args in rule matching] in Rules.hs type RuleFun = DynFlags -> InScopeEnv -> Id -> [CoreExpr] -> Maybe CoreExpr type InScopeEnv = (InScopeSet, IdUnfoldingFun) type IdUnfoldingFun = Id -> Unfolding -- A function that embodies how to unfold an Id if you need -- to do that in the Rule. The reason we need to pass this info in -- is that whether an Id is unfoldable depends on the simplifier phase isBuiltinRule :: CoreRule -> Bool isBuiltinRule (BuiltinRule {}) = True isBuiltinRule _ = False isAutoRule :: CoreRule -> Bool isAutoRule (BuiltinRule {}) = False isAutoRule (Rule { ru_auto = is_auto }) = is_auto -- | The number of arguments the 'ru_fn' must be applied -- to before the rule can match on it ruleArity :: CoreRule -> Int ruleArity (BuiltinRule {ru_nargs = n}) = n ruleArity (Rule {ru_args = args}) = length args ruleName :: CoreRule -> RuleName ruleName = ru_name ruleModule :: CoreRule -> Maybe Module ruleModule Rule { ru_origin } = Just ru_origin ruleModule BuiltinRule {} = Nothing ruleActivation :: CoreRule -> Activation ruleActivation (BuiltinRule { }) = AlwaysActive ruleActivation (Rule { ru_act = act }) = act -- | The 'Name' of the 'Id.Id' at the head of the rule left hand side ruleIdName :: CoreRule -> Name ruleIdName = ru_fn isLocalRule :: CoreRule -> Bool isLocalRule = ru_local -- | Set the 'Name' of the 'Id.Id' at the head of the rule left hand side setRuleIdName :: Name -> CoreRule -> CoreRule setRuleIdName nm ru = ru { ru_fn = nm } {- ************************************************************************ * * \subsection{Vectorisation declarations} * * ************************************************************************ Representation of desugared vectorisation declarations that are fed to the vectoriser (via 'ModGuts'). -} data CoreVect = Vect Id CoreExpr | NoVect Id | VectType Bool TyCon (Maybe TyCon) | VectClass TyCon -- class tycon | VectInst Id -- instance dfun (always SCALAR) !!!FIXME: should be superfluous now {- ************************************************************************ * * Unfoldings * * ************************************************************************ The @Unfolding@ type is declared here to avoid numerous loops -} -- | Records the /unfolding/ of an identifier, which is approximately the form the -- identifier would have if we substituted its definition in for the identifier. -- This type should be treated as abstract everywhere except in "CoreUnfold" data Unfolding = NoUnfolding -- ^ We have no information about the unfolding. | BootUnfolding -- ^ We have no information about the unfolding, because -- this 'Id' came from an @hi-boot@ file. -- See Note [Inlining and hs-boot files] in ToIface -- for what this is used for. | OtherCon [AltCon] -- ^ It ain't one of these constructors. -- @OtherCon xs@ also indicates that something has been evaluated -- and hence there's no point in re-evaluating it. -- @OtherCon []@ is used even for non-data-type values -- to indicated evaluated-ness. Notably: -- -- > data C = C !(Int -> Int) -- > case x of { C f -> ... } -- -- Here, @f@ gets an @OtherCon []@ unfolding. | DFunUnfolding { -- The Unfolding of a DFunId -- See Note [DFun unfoldings] -- df = /\a1..am. \d1..dn. MkD t1 .. tk -- (op1 a1..am d1..dn) -- (op2 a1..am d1..dn) df_bndrs :: [Var], -- The bound variables [a1..m],[d1..dn] df_con :: DataCon, -- The dictionary data constructor (never a newtype datacon) df_args :: [CoreExpr] -- Args of the data con: types, superclasses and methods, } -- in positional order | CoreUnfolding { -- An unfolding for an Id with no pragma, -- or perhaps a NOINLINE pragma -- (For NOINLINE, the phase, if any, is in the -- InlinePragInfo for this Id.) uf_tmpl :: CoreExpr, -- Template; occurrence info is correct uf_src :: UnfoldingSource, -- Where the unfolding came from uf_is_top :: Bool, -- True <=> top level binding uf_is_value :: Bool, -- exprIsHNF template (cached); it is ok to discard -- a `seq` on this variable uf_is_conlike :: Bool, -- True <=> applicn of constructor or CONLIKE function -- Cached version of exprIsConLike uf_is_work_free :: Bool, -- True <=> doesn't waste (much) work to expand -- inside an inlining -- Cached version of exprIsCheap uf_expandable :: Bool, -- True <=> can expand in RULE matching -- Cached version of exprIsExpandable uf_guidance :: UnfoldingGuidance -- Tells about the *size* of the template. } -- ^ An unfolding with redundant cached information. Parameters: -- -- uf_tmpl: Template used to perform unfolding; -- NB: Occurrence info is guaranteed correct: -- see Note [OccInfo in unfoldings and rules] -- -- uf_is_top: Is this a top level binding? -- -- uf_is_value: 'exprIsHNF' template (cached); it is ok to discard a 'seq' on -- this variable -- -- uf_is_work_free: Does this waste only a little work if we expand it inside an inlining? -- Basically this is a cached version of 'exprIsWorkFree' -- -- uf_guidance: Tells us about the /size/ of the unfolding template ------------------------------------------------ data UnfoldingSource = -- See also Note [Historical note: unfoldings for wrappers] InlineRhs -- The current rhs of the function -- Replace uf_tmpl each time around | InlineStable -- From an INLINE or INLINABLE pragma -- INLINE if guidance is UnfWhen -- INLINABLE if guidance is UnfIfGoodArgs/UnfoldNever -- (well, technically an INLINABLE might be made -- UnfWhen if it was small enough, and then -- it will behave like INLINE outside the current -- module, but that is the way automatic unfoldings -- work so it is consistent with the intended -- meaning of INLINABLE). -- -- uf_tmpl may change, but only as a result of -- gentle simplification, it doesn't get updated -- to the current RHS during compilation as with -- InlineRhs. -- -- See Note [InlineStable] | InlineCompulsory -- Something that *has* no binding, so you *must* inline it -- Only a few primop-like things have this property -- (see MkId.hs, calls to mkCompulsoryUnfolding). -- Inline absolutely always, however boring the context. -- | 'UnfoldingGuidance' says when unfolding should take place data UnfoldingGuidance = UnfWhen { -- Inline without thinking about the *size* of the uf_tmpl -- Used (a) for small *and* cheap unfoldings -- (b) for INLINE functions -- See Note [INLINE for small functions] in CoreUnfold ug_arity :: Arity, -- Number of value arguments expected ug_unsat_ok :: Bool, -- True <=> ok to inline even if unsaturated ug_boring_ok :: Bool -- True <=> ok to inline even if the context is boring -- So True,True means "always" } | UnfIfGoodArgs { -- Arose from a normal Id; the info here is the -- result of a simple analysis of the RHS ug_args :: [Int], -- Discount if the argument is evaluated. -- (i.e., a simplification will definitely -- be possible). One elt of the list per *value* arg. ug_size :: Int, -- The "size" of the unfolding. ug_res :: Int -- Scrutinee discount: the discount to substract if the thing is in } -- a context (case (thing args) of ...), -- (where there are the right number of arguments.) | UnfNever -- The RHS is big, so don't inline it deriving (Eq) {- Note [Historical note: unfoldings for wrappers] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We used to have a nice clever scheme in interface files for wrappers. A wrapper's unfolding can be reconstructed from its worker's id and its strictness. This decreased .hi file size (sometimes significantly, for modules like GHC.Classes with many high-arity w/w splits) and had a slight corresponding effect on compile times. However, when we added the second demand analysis, this scheme lead to some Core lint errors. The second analysis could change the strictness signatures, which sometimes resulted in a wrapper's regenerated unfolding applying the wrapper to too many arguments. Instead of repairing the clever .hi scheme, we abandoned it in favor of simplicity. The .hi sizes are usually insignificant (excluding the +1M for base libraries), and compile time barely increases (~+1% for nofib). The nicer upshot is that the UnfoldingSource no longer mentions an Id, so, eg, substitutions need not traverse them. Note [DFun unfoldings] ~~~~~~~~~~~~~~~~~~~~~~ The Arity in a DFunUnfolding is total number of args (type and value) that the DFun needs to produce a dictionary. That's not necessarily related to the ordinary arity of the dfun Id, esp if the class has one method, so the dictionary is represented by a newtype. Example class C a where { op :: a -> Int } instance C a -> C [a] where op xs = op (head xs) The instance translates to $dfCList :: forall a. C a => C [a] -- Arity 2! $dfCList = /\a.\d. $copList {a} d |> co $copList :: forall a. C a => [a] -> Int -- Arity 2! $copList = /\a.\d.\xs. op {a} d (head xs) Now we might encounter (op (dfCList {ty} d) a1 a2) and we want the (op (dfList {ty} d)) rule to fire, because $dfCList has all its arguments, even though its (value) arity is 2. That's why we record the number of expected arguments in the DFunUnfolding. Note that although it's an Arity, it's most convenient for it to give the *total* number of arguments, both type and value. See the use site in exprIsConApp_maybe. -} -- Constants for the UnfWhen constructor needSaturated, unSaturatedOk :: Bool needSaturated = False unSaturatedOk = True boringCxtNotOk, boringCxtOk :: Bool boringCxtOk = True boringCxtNotOk = False ------------------------------------------------ noUnfolding :: Unfolding -- ^ There is no known 'Unfolding' evaldUnfolding :: Unfolding -- ^ This unfolding marks the associated thing as being evaluated noUnfolding = NoUnfolding evaldUnfolding = OtherCon [] -- | There is no known 'Unfolding', because this came from an -- hi-boot file. bootUnfolding :: Unfolding bootUnfolding = BootUnfolding mkOtherCon :: [AltCon] -> Unfolding mkOtherCon = OtherCon isStableSource :: UnfoldingSource -> Bool -- Keep the unfolding template isStableSource InlineCompulsory = True isStableSource InlineStable = True isStableSource InlineRhs = False -- | Retrieves the template of an unfolding: panics if none is known unfoldingTemplate :: Unfolding -> CoreExpr unfoldingTemplate = uf_tmpl -- | Retrieves the template of an unfolding if possible -- maybeUnfoldingTemplate is used mainly wnen specialising, and we do -- want to specialise DFuns, so it's important to return a template -- for DFunUnfoldings maybeUnfoldingTemplate :: Unfolding -> Maybe CoreExpr maybeUnfoldingTemplate (CoreUnfolding { uf_tmpl = expr }) = Just expr maybeUnfoldingTemplate (DFunUnfolding { df_bndrs = bndrs, df_con = con, df_args = args }) = Just (mkLams bndrs (mkApps (Var (dataConWorkId con)) args)) maybeUnfoldingTemplate _ = Nothing -- | The constructors that the unfolding could never be: -- returns @[]@ if no information is available otherCons :: Unfolding -> [AltCon] otherCons (OtherCon cons) = cons otherCons _ = [] -- | Determines if it is certainly the case that the unfolding will -- yield a value (something in HNF): returns @False@ if unsure isValueUnfolding :: Unfolding -> Bool -- Returns False for OtherCon isValueUnfolding (CoreUnfolding { uf_is_value = is_evald }) = is_evald isValueUnfolding _ = False -- | Determines if it possibly the case that the unfolding will -- yield a value. Unlike 'isValueUnfolding' it returns @True@ -- for 'OtherCon' isEvaldUnfolding :: Unfolding -> Bool -- Returns True for OtherCon isEvaldUnfolding (OtherCon _) = True isEvaldUnfolding (CoreUnfolding { uf_is_value = is_evald }) = is_evald isEvaldUnfolding _ = False -- | @True@ if the unfolding is a constructor application, the application -- of a CONLIKE function or 'OtherCon' isConLikeUnfolding :: Unfolding -> Bool isConLikeUnfolding (OtherCon _) = True isConLikeUnfolding (CoreUnfolding { uf_is_conlike = con }) = con isConLikeUnfolding _ = False -- | Is the thing we will unfold into certainly cheap? isCheapUnfolding :: Unfolding -> Bool isCheapUnfolding (CoreUnfolding { uf_is_work_free = is_wf }) = is_wf isCheapUnfolding _ = False isExpandableUnfolding :: Unfolding -> Bool isExpandableUnfolding (CoreUnfolding { uf_expandable = is_expable }) = is_expable isExpandableUnfolding _ = False expandUnfolding_maybe :: Unfolding -> Maybe CoreExpr -- Expand an expandable unfolding; this is used in rule matching -- See Note [Expanding variables] in Rules.hs -- The key point here is that CONLIKE things can be expanded expandUnfolding_maybe (CoreUnfolding { uf_expandable = True, uf_tmpl = rhs }) = Just rhs expandUnfolding_maybe _ = Nothing isCompulsoryUnfolding :: Unfolding -> Bool isCompulsoryUnfolding (CoreUnfolding { uf_src = InlineCompulsory }) = True isCompulsoryUnfolding _ = False isStableUnfolding :: Unfolding -> Bool -- True of unfoldings that should not be overwritten -- by a CoreUnfolding for the RHS of a let-binding isStableUnfolding (CoreUnfolding { uf_src = src }) = isStableSource src isStableUnfolding (DFunUnfolding {}) = True isStableUnfolding _ = False -- | Only returns False if there is no unfolding information available at all hasSomeUnfolding :: Unfolding -> Bool hasSomeUnfolding NoUnfolding = False hasSomeUnfolding BootUnfolding = False hasSomeUnfolding _ = True isBootUnfolding :: Unfolding -> Bool isBootUnfolding BootUnfolding = True isBootUnfolding _ = False neverUnfoldGuidance :: UnfoldingGuidance -> Bool neverUnfoldGuidance UnfNever = True neverUnfoldGuidance _ = False isFragileUnfolding :: Unfolding -> Bool -- An unfolding is fragile if it mentions free variables or -- is otherwise subject to change. A robust one can be kept. -- See Note [Fragile unfoldings] isFragileUnfolding (CoreUnfolding {}) = True isFragileUnfolding (DFunUnfolding {}) = True isFragileUnfolding _ = False -- NoUnfolding, BootUnfolding, OtherCon are all non-fragile canUnfold :: Unfolding -> Bool canUnfold (CoreUnfolding { uf_guidance = g }) = not (neverUnfoldGuidance g) canUnfold _ = False {- Note [Fragile unfoldings] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ An unfolding is "fragile" if it mentions free variables (and hence would need substitution) or might be affected by optimisation. The non-fragile ones are NoUnfolding, BootUnfolding OtherCon {} If we know this binder (say a lambda binder) will be bound to an evaluated thing, we want to retain that info in simpleOptExpr; see Trac #13077. We consider even a StableUnfolding as fragile, because it needs substitution. Note [InlineStable] ~~~~~~~~~~~~~~~~~ When you say {-# INLINE f #-} f x = <rhs> you intend that calls (f e) are replaced by <rhs>[e/x] So we should capture (\x.<rhs>) in the Unfolding of 'f', and never meddle with it. Meanwhile, we can optimise <rhs> to our heart's content, leaving the original unfolding intact in Unfolding of 'f'. For example all xs = foldr (&&) True xs any p = all . map p {-# INLINE any #-} We optimise any's RHS fully, but leave the InlineRule saying "all . map p", which deforests well at the call site. So INLINE pragma gives rise to an InlineRule, which captures the original RHS. Moreover, it's only used when 'f' is applied to the specified number of arguments; that is, the number of argument on the LHS of the '=' sign in the original source definition. For example, (.) is now defined in the libraries like this {-# INLINE (.) #-} (.) f g = \x -> f (g x) so that it'll inline when applied to two arguments. If 'x' appeared on the left, thus (.) f g x = f (g x) it'd only inline when applied to three arguments. This slightly-experimental change was requested by Roman, but it seems to make sense. See also Note [Inlining an InlineRule] in CoreUnfold. Note [OccInfo in unfoldings and rules] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In unfoldings and rules, we guarantee that the template is occ-analysed, so that the occurrence info on the binders is correct. This is important, because the Simplifier does not re-analyse the template when using it. If the occurrence info is wrong - We may get more simplifier iterations than necessary, because once-occ info isn't there - More seriously, we may get an infinite loop if there's a Rec without a loop breaker marked ************************************************************************ * * AltCon * * ************************************************************************ -} -- The Ord is needed for the FiniteMap used in the lookForConstructor -- in SimplEnv. If you declared that lookForConstructor *ignores* -- constructor-applications with LitArg args, then you could get -- rid of this Ord. instance Outputable AltCon where ppr (DataAlt dc) = ppr dc ppr (LitAlt lit) = ppr lit ppr DEFAULT = text "__DEFAULT" cmpAlt :: (AltCon, a, b) -> (AltCon, a, b) -> Ordering cmpAlt (con1, _, _) (con2, _, _) = con1 `cmpAltCon` con2 ltAlt :: (AltCon, a, b) -> (AltCon, a, b) -> Bool ltAlt a1 a2 = (a1 `cmpAlt` a2) == LT cmpAltCon :: AltCon -> AltCon -> Ordering -- ^ Compares 'AltCon's within a single list of alternatives -- DEFAULT comes out smallest, so that sorting by AltCon -- puts alternatives in the order required by #case_invariants# cmpAltCon DEFAULT DEFAULT = EQ cmpAltCon DEFAULT _ = LT cmpAltCon (DataAlt d1) (DataAlt d2) = dataConTag d1 `compare` dataConTag d2 cmpAltCon (DataAlt _) DEFAULT = GT cmpAltCon (LitAlt l1) (LitAlt l2) = l1 `compare` l2 cmpAltCon (LitAlt _) DEFAULT = GT cmpAltCon con1 con2 = WARN( True, text "Comparing incomparable AltCons" <+> ppr con1 <+> ppr con2 ) LT {- ************************************************************************ * * \subsection{Useful synonyms} * * ************************************************************************ Note [CoreProgram] ~~~~~~~~~~~~~~~~~~ The top level bindings of a program, a CoreProgram, are represented as a list of CoreBind * Later bindings in the list can refer to earlier ones, but not vice versa. So this is OK NonRec { x = 4 } Rec { p = ...q...x... ; q = ...p...x } Rec { f = ...p..x..f.. } NonRec { g = ..f..q...x.. } But it would NOT be ok for 'f' to refer to 'g'. * The occurrence analyser does strongly-connected component analysis on each Rec binding, and splits it into a sequence of smaller bindings where possible. So the program typically starts life as a single giant Rec, which is then dependency-analysed into smaller chunks. -} -- If you edit this type, you may need to update the GHC formalism -- See Note [GHC Formalism] in coreSyn/CoreLint.hs type CoreProgram = [CoreBind] -- See Note [CoreProgram] -- | The common case for the type of binders and variables when -- we are manipulating the Core language within GHC type CoreBndr = Var -- | Expressions where binders are 'CoreBndr's type CoreExpr = Expr CoreBndr -- | Argument expressions where binders are 'CoreBndr's type CoreArg = Arg CoreBndr -- | Binding groups where binders are 'CoreBndr's type CoreBind = Bind CoreBndr -- | Case alternatives where binders are 'CoreBndr's type CoreAlt = Alt CoreBndr {- ************************************************************************ * * \subsection{Tagging} * * ************************************************************************ -} -- | Binders are /tagged/ with a t data TaggedBndr t = TB CoreBndr t -- TB for "tagged binder" type TaggedBind t = Bind (TaggedBndr t) type TaggedExpr t = Expr (TaggedBndr t) type TaggedArg t = Arg (TaggedBndr t) type TaggedAlt t = Alt (TaggedBndr t) instance Outputable b => Outputable (TaggedBndr b) where ppr (TB b l) = char '<' <> ppr b <> comma <> ppr l <> char '>' deTagExpr :: TaggedExpr t -> CoreExpr deTagExpr (Var v) = Var v deTagExpr (Lit l) = Lit l deTagExpr (Type ty) = Type ty deTagExpr (Coercion co) = Coercion co deTagExpr (App e1 e2) = App (deTagExpr e1) (deTagExpr e2) deTagExpr (Lam (TB b _) e) = Lam b (deTagExpr e) deTagExpr (Let bind body) = Let (deTagBind bind) (deTagExpr body) deTagExpr (Case e (TB b _) ty alts) = Case (deTagExpr e) b ty (map deTagAlt alts) deTagExpr (Tick t e) = Tick t (deTagExpr e) deTagExpr (Cast e co) = Cast (deTagExpr e) co deTagBind :: TaggedBind t -> CoreBind deTagBind (NonRec (TB b _) rhs) = NonRec b (deTagExpr rhs) deTagBind (Rec prs) = Rec [(b, deTagExpr rhs) | (TB b _, rhs) <- prs] deTagAlt :: TaggedAlt t -> CoreAlt deTagAlt (con, bndrs, rhs) = (con, [b | TB b _ <- bndrs], deTagExpr rhs) {- ************************************************************************ * * \subsection{Core-constructing functions with checking} * * ************************************************************************ -} -- | Apply a list of argument expressions to a function expression in a nested fashion. Prefer to -- use 'MkCore.mkCoreApps' if possible mkApps :: Expr b -> [Arg b] -> Expr b -- | Apply a list of type argument expressions to a function expression in a nested fashion mkTyApps :: Expr b -> [Type] -> Expr b -- | Apply a list of coercion argument expressions to a function expression in a nested fashion mkCoApps :: Expr b -> [Coercion] -> Expr b -- | Apply a list of type or value variables to a function expression in a nested fashion mkVarApps :: Expr b -> [Var] -> Expr b -- | Apply a list of argument expressions to a data constructor in a nested fashion. Prefer to -- use 'MkCore.mkCoreConApps' if possible mkConApp :: DataCon -> [Arg b] -> Expr b mkApps f args = foldl App f args mkCoApps f args = foldl (\ e a -> App e (Coercion a)) f args mkVarApps f vars = foldl (\ e a -> App e (varToCoreExpr a)) f vars mkConApp con args = mkApps (Var (dataConWorkId con)) args mkTyApps f args = foldl (\ e a -> App e (mkTyArg a)) f args mkConApp2 :: DataCon -> [Type] -> [Var] -> Expr b mkConApp2 con tys arg_ids = Var (dataConWorkId con) `mkApps` map Type tys `mkApps` map varToCoreExpr arg_ids mkTyArg :: Type -> Expr b mkTyArg ty | Just co <- isCoercionTy_maybe ty = Coercion co | otherwise = Type ty -- | Create a machine integer literal expression of type @Int#@ from an @Integer@. -- If you want an expression of type @Int@ use 'MkCore.mkIntExpr' mkIntLit :: DynFlags -> Integer -> Expr b -- | Create a machine integer literal expression of type @Int#@ from an @Int@. -- If you want an expression of type @Int@ use 'MkCore.mkIntExpr' mkIntLitInt :: DynFlags -> Int -> Expr b mkIntLit dflags n = Lit (mkMachInt dflags n) mkIntLitInt dflags n = Lit (mkMachInt dflags (toInteger n)) -- | Create a machine word literal expression of type @Word#@ from an @Integer@. -- If you want an expression of type @Word@ use 'MkCore.mkWordExpr' mkWordLit :: DynFlags -> Integer -> Expr b -- | Create a machine word literal expression of type @Word#@ from a @Word@. -- If you want an expression of type @Word@ use 'MkCore.mkWordExpr' mkWordLitWord :: DynFlags -> Word -> Expr b mkWordLit dflags w = Lit (mkMachWord dflags w) mkWordLitWord dflags w = Lit (mkMachWord dflags (toInteger w)) mkWord64LitWord64 :: Word64 -> Expr b mkWord64LitWord64 w = Lit (mkMachWord64 (toInteger w)) mkInt64LitInt64 :: Int64 -> Expr b mkInt64LitInt64 w = Lit (mkMachInt64 (toInteger w)) -- | Create a machine character literal expression of type @Char#@. -- If you want an expression of type @Char@ use 'MkCore.mkCharExpr' mkCharLit :: Char -> Expr b -- | Create a machine string literal expression of type @Addr#@. -- If you want an expression of type @String@ use 'MkCore.mkStringExpr' mkStringLit :: String -> Expr b mkCharLit c = Lit (mkMachChar c) mkStringLit s = Lit (mkMachString s) -- | Create a machine single precision literal expression of type @Float#@ from a @Rational@. -- If you want an expression of type @Float@ use 'MkCore.mkFloatExpr' mkFloatLit :: Rational -> Expr b -- | Create a machine single precision literal expression of type @Float#@ from a @Float@. -- If you want an expression of type @Float@ use 'MkCore.mkFloatExpr' mkFloatLitFloat :: Float -> Expr b mkFloatLit f = Lit (mkMachFloat f) mkFloatLitFloat f = Lit (mkMachFloat (toRational f)) -- | Create a machine double precision literal expression of type @Double#@ from a @Rational@. -- If you want an expression of type @Double@ use 'MkCore.mkDoubleExpr' mkDoubleLit :: Rational -> Expr b -- | Create a machine double precision literal expression of type @Double#@ from a @Double@. -- If you want an expression of type @Double@ use 'MkCore.mkDoubleExpr' mkDoubleLitDouble :: Double -> Expr b mkDoubleLit d = Lit (mkMachDouble d) mkDoubleLitDouble d = Lit (mkMachDouble (toRational d)) -- | Bind all supplied binding groups over an expression in a nested let expression. Assumes -- that the rhs satisfies the let/app invariant. Prefer to use 'MkCore.mkCoreLets' if -- possible, which does guarantee the invariant mkLets :: [Bind b] -> Expr b -> Expr b -- | Bind all supplied binders over an expression in a nested lambda expression. Prefer to -- use 'MkCore.mkCoreLams' if possible mkLams :: [b] -> Expr b -> Expr b mkLams binders body = foldr Lam body binders mkLets binds body = foldr mkLet body binds mkLet :: Bind b -> Expr b -> Expr b -- The desugarer sometimes generates an empty Rec group -- which Lint rejects, so we kill it off right away mkLet (Rec []) body = body mkLet bind body = Let bind body -- | @mkLetNonRec bndr rhs body@ wraps @body@ in a @let@ binding @bndr@. mkLetNonRec :: b -> Expr b -> Expr b -> Expr b mkLetNonRec b rhs body = Let (NonRec b rhs) body -- | @mkLetRec binds body@ wraps @body@ in a @let rec@ with the given set of -- @binds@ if binds is non-empty. mkLetRec :: [(b, Expr b)] -> Expr b -> Expr b mkLetRec [] body = body mkLetRec bs body = Let (Rec bs) body -- | Create a binding group where a type variable is bound to a type. Per "CoreSyn#type_let", -- this can only be used to bind something in a non-recursive @let@ expression mkTyBind :: TyVar -> Type -> CoreBind mkTyBind tv ty = NonRec tv (Type ty) -- | Create a binding group where a type variable is bound to a type. Per "CoreSyn#type_let", -- this can only be used to bind something in a non-recursive @let@ expression mkCoBind :: CoVar -> Coercion -> CoreBind mkCoBind cv co = NonRec cv (Coercion co) -- | Convert a binder into either a 'Var' or 'Type' 'Expr' appropriately varToCoreExpr :: CoreBndr -> Expr b varToCoreExpr v | isTyVar v = Type (mkTyVarTy v) | isCoVar v = Coercion (mkCoVarCo v) | otherwise = ASSERT( isId v ) Var v varsToCoreExprs :: [CoreBndr] -> [Expr b] varsToCoreExprs vs = map varToCoreExpr vs {- ************************************************************************ * * Getting a result type * * ************************************************************************ These are defined here to avoid a module loop between CoreUtils and CoreFVs -} applyTypeToArg :: Type -> CoreExpr -> Type -- ^ Determines the type resulting from applying an expression with given type -- to a given argument expression applyTypeToArg fun_ty arg = piResultTy fun_ty (exprToType arg) -- | If the expression is a 'Type', converts. Otherwise, -- panics. NB: This does /not/ convert 'Coercion' to 'CoercionTy'. exprToType :: CoreExpr -> Type exprToType (Type ty) = ty exprToType _bad = pprPanic "exprToType" empty -- | If the expression is a 'Coercion', converts. exprToCoercion_maybe :: CoreExpr -> Maybe Coercion exprToCoercion_maybe (Coercion co) = Just co exprToCoercion_maybe _ = Nothing {- ************************************************************************ * * \subsection{Simple access functions} * * ************************************************************************ -} -- | Extract every variable by this group bindersOf :: Bind b -> [b] -- If you edit this function, you may need to update the GHC formalism -- See Note [GHC Formalism] in coreSyn/CoreLint.hs bindersOf (NonRec binder _) = [binder] bindersOf (Rec pairs) = [binder | (binder, _) <- pairs] -- | 'bindersOf' applied to a list of binding groups bindersOfBinds :: [Bind b] -> [b] bindersOfBinds binds = foldr ((++) . bindersOf) [] binds rhssOfBind :: Bind b -> [Expr b] rhssOfBind (NonRec _ rhs) = [rhs] rhssOfBind (Rec pairs) = [rhs | (_,rhs) <- pairs] rhssOfAlts :: [Alt b] -> [Expr b] rhssOfAlts alts = [e | (_,_,e) <- alts] -- | Collapse all the bindings in the supplied groups into a single -- list of lhs\/rhs pairs suitable for binding in a 'Rec' binding group flattenBinds :: [Bind b] -> [(b, Expr b)] flattenBinds (NonRec b r : binds) = (b,r) : flattenBinds binds flattenBinds (Rec prs1 : binds) = prs1 ++ flattenBinds binds flattenBinds [] = [] -- | We often want to strip off leading lambdas before getting down to -- business. Variants are 'collectTyBinders', 'collectValBinders', -- and 'collectTyAndValBinders' collectBinders :: Expr b -> ([b], Expr b) collectTyBinders :: CoreExpr -> ([TyVar], CoreExpr) collectValBinders :: CoreExpr -> ([Id], CoreExpr) collectTyAndValBinders :: CoreExpr -> ([TyVar], [Id], CoreExpr) -- | Strip off exactly N leading lambdas (type or value). Good for use with -- join points. collectNBinders :: Int -> Expr b -> ([b], Expr b) collectBinders expr = go [] expr where go bs (Lam b e) = go (b:bs) e go bs e = (reverse bs, e) collectTyBinders expr = go [] expr where go tvs (Lam b e) | isTyVar b = go (b:tvs) e go tvs e = (reverse tvs, e) collectValBinders expr = go [] expr where go ids (Lam b e) | isId b = go (b:ids) e go ids body = (reverse ids, body) collectTyAndValBinders expr = (tvs, ids, body) where (tvs, body1) = collectTyBinders expr (ids, body) = collectValBinders body1 collectNBinders orig_n orig_expr = go orig_n [] orig_expr where go 0 bs expr = (reverse bs, expr) go n bs (Lam b e) = go (n-1) (b:bs) e go _ _ _ = pprPanic "collectNBinders" $ int orig_n -- | Takes a nested application expression and returns the function -- being applied and the arguments to which it is applied collectArgs :: Expr b -> (Expr b, [Arg b]) collectArgs expr = go expr [] where go (App f a) as = go f (a:as) go e as = (e, as) -- | Like @collectArgs@, but also collects looks through floatable -- ticks if it means that we can find more arguments. collectArgsTicks :: (Tickish Id -> Bool) -> Expr b -> (Expr b, [Arg b], [Tickish Id]) collectArgsTicks skipTick expr = go expr [] [] where go (App f a) as ts = go f (a:as) ts go (Tick t e) as ts | skipTick t = go e as (t:ts) go e as ts = (e, as, reverse ts) {- ************************************************************************ * * \subsection{Predicates} * * ************************************************************************ At one time we optionally carried type arguments through to runtime. @isRuntimeVar v@ returns if (Lam v _) really becomes a lambda at runtime, i.e. if type applications are actual lambdas because types are kept around at runtime. Similarly isRuntimeArg. -} -- | Will this variable exist at runtime? isRuntimeVar :: Var -> Bool isRuntimeVar = isId -- | Will this argument expression exist at runtime? isRuntimeArg :: CoreExpr -> Bool isRuntimeArg = isValArg -- | Returns @True@ for value arguments, false for type args -- NB: coercions are value arguments (zero width, to be sure, -- like State#, but still value args). isValArg :: Expr b -> Bool isValArg e = not (isTypeArg e) -- | Returns @True@ iff the expression is a 'Type' or 'Coercion' -- expression at its top level isTyCoArg :: Expr b -> Bool isTyCoArg (Type {}) = True isTyCoArg (Coercion {}) = True isTyCoArg _ = False -- | Returns @True@ iff the expression is a 'Type' expression at its -- top level. Note this does NOT include 'Coercion's. isTypeArg :: Expr b -> Bool isTypeArg (Type {}) = True isTypeArg _ = False -- | The number of binders that bind values rather than types valBndrCount :: [CoreBndr] -> Int valBndrCount = count isId -- | The number of argument expressions that are values rather than types at their top level valArgCount :: [Arg b] -> Int valArgCount = count isValArg {- ************************************************************************ * * \subsection{Annotated core} * * ************************************************************************ -} -- | Annotated core: allows annotation at every node in the tree type AnnExpr bndr annot = (annot, AnnExpr' bndr annot) -- | A clone of the 'Expr' type but allowing annotation at every tree node data AnnExpr' bndr annot = AnnVar Id | AnnLit Literal | AnnLam bndr (AnnExpr bndr annot) | AnnApp (AnnExpr bndr annot) (AnnExpr bndr annot) | AnnCase (AnnExpr bndr annot) bndr Type [AnnAlt bndr annot] | AnnLet (AnnBind bndr annot) (AnnExpr bndr annot) | AnnCast (AnnExpr bndr annot) (annot, Coercion) -- Put an annotation on the (root of) the coercion | AnnTick (Tickish Id) (AnnExpr bndr annot) | AnnType Type | AnnCoercion Coercion -- | A clone of the 'Alt' type but allowing annotation at every tree node type AnnAlt bndr annot = (AltCon, [bndr], AnnExpr bndr annot) -- | A clone of the 'Bind' type but allowing annotation at every tree node data AnnBind bndr annot = AnnNonRec bndr (AnnExpr bndr annot) | AnnRec [(bndr, AnnExpr bndr annot)] -- | Takes a nested application expression and returns the function -- being applied and the arguments to which it is applied collectAnnArgs :: AnnExpr b a -> (AnnExpr b a, [AnnExpr b a]) collectAnnArgs expr = go expr [] where go (_, AnnApp f a) as = go f (a:as) go e as = (e, as) collectAnnArgsTicks :: (Tickish Var -> Bool) -> AnnExpr b a -> (AnnExpr b a, [AnnExpr b a], [Tickish Var]) collectAnnArgsTicks tickishOk expr = go expr [] [] where go (_, AnnApp f a) as ts = go f (a:as) ts go (_, AnnTick t e) as ts | tickishOk t = go e as (t:ts) go e as ts = (e, as, reverse ts) deAnnotate :: AnnExpr bndr annot -> Expr bndr deAnnotate (_, e) = deAnnotate' e deAnnotate' :: AnnExpr' bndr annot -> Expr bndr deAnnotate' (AnnType t) = Type t deAnnotate' (AnnCoercion co) = Coercion co deAnnotate' (AnnVar v) = Var v deAnnotate' (AnnLit lit) = Lit lit deAnnotate' (AnnLam binder body) = Lam binder (deAnnotate body) deAnnotate' (AnnApp fun arg) = App (deAnnotate fun) (deAnnotate arg) deAnnotate' (AnnCast e (_,co)) = Cast (deAnnotate e) co deAnnotate' (AnnTick tick body) = Tick tick (deAnnotate body) deAnnotate' (AnnLet bind body) = Let (deAnnBind bind) (deAnnotate body) deAnnotate' (AnnCase scrut v t alts) = Case (deAnnotate scrut) v t (map deAnnAlt alts) deAnnAlt :: AnnAlt bndr annot -> Alt bndr deAnnAlt (con,args,rhs) = (con,args,deAnnotate rhs) deAnnBind :: AnnBind b annot -> Bind b deAnnBind (AnnNonRec var rhs) = NonRec var (deAnnotate rhs) deAnnBind (AnnRec pairs) = Rec [(v,deAnnotate rhs) | (v,rhs) <- pairs] -- | As 'collectBinders' but for 'AnnExpr' rather than 'Expr' collectAnnBndrs :: AnnExpr bndr annot -> ([bndr], AnnExpr bndr annot) collectAnnBndrs e = collect [] e where collect bs (_, AnnLam b body) = collect (b:bs) body collect bs body = (reverse bs, body) -- | As 'collectNBinders' but for 'AnnExpr' rather than 'Expr' collectNAnnBndrs :: Int -> AnnExpr bndr annot -> ([bndr], AnnExpr bndr annot) collectNAnnBndrs orig_n e = collect orig_n [] e where collect 0 bs body = (reverse bs, body) collect n bs (_, AnnLam b body) = collect (n-1) (b:bs) body collect _ _ _ = pprPanic "collectNBinders" $ int orig_n
shlevy/ghc
compiler/coreSyn/CoreSyn.hs
bsd-3-clause
89,300
0
14
23,699
9,305
5,286
4,019
654
5
module Day8 where import Data.Array.Repa ((:.) (..), All (..), Any (..)) import qualified Data.Array.Repa as Repa import Data.List (intercalate) import Text.Megaparsec import Text.Megaparsec.Lexer hiding (space) import Text.Megaparsec.String data Ins = Rect Int Int | RotR Int Int | RotD Int Int deriving (Show) type Display = Repa.Array Repa.D Repa.DIM2 Bool insP :: Parser Ins insP = rect <|> rotR <|> rotD where rect = Rect <$> (string "rect " *> int <* char 'x') <*> int rotR = RotR <$> (string "rotate row y=" *> int) <*> (string " by " *> int) rotD = RotD <$> (string "rotate column x=" *> int) <*> (string " by " *> int) int = fromInteger <$> integer -- :: Parser Int toPixel :: Bool -> Char toPixel False = ' ' toPixel True = '#' apply :: Display -> Ins -> Display apply disp (Rect cols rows) = Repa.traverse disp id draw where draw at sh@(Repa.Z :. r :. c) | r < rows && c < cols = True | otherwise = at sh apply disp (RotR row n) = Repa.traverse disp id rot where (Repa.Z :. _ :. width) = Repa.extent disp rot at sh@(Repa.Z :. r :. c) | r == row = at (Repa.Z :. r :. (c - n) `mod` width) | otherwise = at sh apply disp (RotD col n) = Repa.traverse disp id rot where (Repa.Z :. height :. _) = Repa.extent disp rot at sh@(Repa.Z :. r :. c) | c == col = at (Repa.Z :. (r - n) `mod` height :. c) | otherwise = at sh render :: Display -> [String] render disp = map renderRow [0 .. height] where (Repa.Z :. height :. _) = Repa.extent disp renderRow row = Repa.toList $ Repa.map toPixel $ Repa.slice disp (Any :. (row :: Int) :. All) part1 :: Display -> Int part1 = length . filter id . Repa.toList part2 :: Display -> String part2 = intercalate "\n" . render main :: IO () main = do let inputFile = "input/day8.txt" input <- readFile inputFile let Right instructions = parse (insP `endBy` newline) inputFile input let blank = Repa.fromFunction (Repa.ix2 6 50) (const False) display = foldl apply blank instructions print $ part1 display putStrLn $ part2 display
liff/adventofcode-2016
app/Day8.hs
bsd-3-clause
2,198
0
14
608
919
477
442
57
1
{-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- | -- Module : Hasmin.Parser.BasicShape -- Copyright : (c) 2017 Cristian Adrián Ontivero -- License : BSD3 -- Stability : experimental -- Portability : unknown -- -- Parsers for CSS <https://www.w3.org/TR/css-shapes/#typedef-basic-shape \<basic-shape>> values. -- ----------------------------------------------------------------------------- module Hasmin.Parser.BasicShape where import Control.Applicative ((<|>), optional, many) import Data.Attoparsec.Text (Parser) import qualified Data.Attoparsec.Text as A import Data.List.NonEmpty (NonEmpty((:|))) import Hasmin.Parser.Utils import Hasmin.Parser.PercentageLength import Hasmin.Parser.Position import Hasmin.Parser.BorderRadius import Hasmin.Types.BasicShape import Hasmin.Utils -- inset( <shape-arg>{1,4} [round <border-radius>]? ) inset :: Parser BasicShape inset = do sa <- percentageLength <* skipComments sas <- atMost 3 (percentageLength <* skipComments) br <- optional (A.asciiCI "round" *> skipComments *> borderRadius) pure $ Inset (sa:|sas) br -- circle( [<shape-radius>]? [at <position>]? ) circle :: Parser BasicShape circle = Circle <$> optional (shapeRadius <* skipComments) <*> optional (A.asciiCI "at" *> skipComments *> position) -- ellipse( [<shape-radius>{2}]? [at <position>]? ) ellipse :: Parser BasicShape ellipse = Ellipse <$> twoSR <*> optional atPosition where atPosition = lexeme (A.asciiCI "at") *> position twoSR = A.option None $ do sr1 <- shapeRadius (Two sr1 <$> (skipComments *> shapeRadius)) <|> pure (One sr1) -- polygon( [<fill-rule>,]? [<shape-arg> <shape-arg>]# ) polygon :: Parser BasicShape polygon = Polygon <$> optional fillrule <*> shapeargs where shapeargs = (:|) <$> pairOf percentageLength <*> many (comma *> pairOf percentageLength) fillrule = parserFromPairs [("nonzero", pure NonZero) ,("evenodd", pure EvenOdd)] <* comma pairOf p = mzip (p <* skipComments) p shapeRadius :: Parser ShapeRadius shapeRadius = either SRPercentage SRLength <$> percentageLength <|> parserFromPairs [("closest-side", pure SRClosestSide) ,("farthest-side", pure SRFarthestSide)]
contivero/hasmin
src/Hasmin/Parser/BasicShape.hs
bsd-3-clause
2,399
0
14
474
517
285
232
40
1
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-| Module : Numeric.AERN.RmToRn Description : real function operations (except pointwise ones) Copyright : (c) Michal Konecny License : BSD3 Maintainer : mikkonecny@gmail.com Stability : experimental Portability : portable Common real function operations (except pointwise ones). -} module Numeric.AERN.RmToRn ( module Numeric.AERN.RmToRn.Domain, module Numeric.AERN.RmToRn.New, module Numeric.AERN.RmToRn.Evaluation, module Numeric.AERN.RmToRn.Integration, module Numeric.AERN.RmToRn.Differentiation, RoundedRealFn(..) ) where import Numeric.AERN.RmToRn.Domain import Numeric.AERN.RmToRn.New import Numeric.AERN.RmToRn.Evaluation import Numeric.AERN.RmToRn.Integration import Numeric.AERN.RmToRn.Differentiation --import Numeric.AERN.RealArithmetic.ExactOps --import Numeric.AERN.RealArithmetic.Measures -- --import qualified Numeric.AERN.RealArithmetic.NumericOrderRounding as ArithUpDn import qualified Numeric.AERN.RealArithmetic.RefinementOrderRounding as ArithInOut -- --import qualified Numeric.AERN.NumericOrder as NumOrd import qualified Numeric.AERN.RefinementOrder as RefOrd -- --import Numeric.AERN.Basics.Effort {-| An aggregate class collecting together all functionality normally expected from approximations to real number functions such as polynomial enclosures. It also provides a single aggregate effort indicator type from which effort indicators for all the rounded operations can be extracted. -} class (ArithInOut.RoundedReal f, ArithInOut.RoundedReal (Domain f), RefOrd.IntervalLike (Domain f), HasDomainBox f, GeneratableVariables (Var f), HasConstFns f, HasProjections f, CanEvaluate f ) => RoundedRealFn f where type RoundedRealFnEffortIndicator f roundedRealFnDefaultEffort :: f -> RoundedRealFnEffortIndicator f fnEffortReal :: f -> (RoundedRealFnEffortIndicator f) -> (ArithInOut.RoundedRealEffortIndicator f) fnEffortDomReal :: f -> (RoundedRealFnEffortIndicator f) -> (ArithInOut.RoundedRealEffortIndicator (Domain f)) fnEffortDomGetEndpoints :: f -> (RoundedRealFnEffortIndicator f) -> (RefOrd.GetEndpointsEffortIndicator (Domain f)) fnEffortDomFromEndpoints :: f -> (RoundedRealFnEffortIndicator f) -> (RefOrd.FromEndpointsEffortIndicator (Domain f)) fnEffortEval :: f -> (RoundedRealFnEffortIndicator f) -> EvaluationEffortIndicator f
michalkonecny/aern
aern-realfn/src/Numeric/AERN/RmToRn.hs
bsd-3-clause
2,570
0
12
424
371
221
150
33
0
module Data.Geo.GPX.Lens.LinksL where import Data.Geo.GPX.Type.Link import Data.Lens.Common class LinksL a where linksL :: Lens a [Link]
tonymorris/geo-gpx
src/Data/Geo/GPX/Lens/LinksL.hs
bsd-3-clause
142
0
8
21
45
28
17
5
0
----------------------------------------------------------------------------- -- -- The register allocator -- -- (c) The University of Glasgow 2004 -- ----------------------------------------------------------------------------- {- The algorithm is roughly: 1) Compute strongly connected components of the basic block list. 2) Compute liveness (mapping from pseudo register to point(s) of death?). 3) Walk instructions in each basic block. We keep track of (a) Free real registers (a bitmap?) (b) Current assignment of temporaries to machine registers and/or spill slots (call this the "assignment"). (c) Partial mapping from basic block ids to a virt-to-loc mapping. When we first encounter a branch to a basic block, we fill in its entry in this table with the current mapping. For each instruction: (a) For each temporary *read* by the instruction: If the temporary does not have a real register allocation: - Allocate a real register from the free list. If the list is empty: - Find a temporary to spill. Pick one that is not used in this instruction (ToDo: not used for a while...) - generate a spill instruction - If the temporary was previously spilled, generate an instruction to read the temp from its spill loc. (optimisation: if we can see that a real register is going to be used soon, then don't use it for allocation). (b) For each real register clobbered by this instruction: If a temporary resides in it, If the temporary is live after this instruction, Move the temporary to another (non-clobbered & free) reg, or spill it to memory. Mark the temporary as residing in both memory and a register if it was spilled (it might need to be read by this instruction). (ToDo: this is wrong for jump instructions?) We do this after step (a), because if we start with movq v1, %rsi which is an instruction that clobbers %rsi, if v1 currently resides in %rsi we want to get movq %rsi, %freereg movq %rsi, %rsi -- will disappear instead of movq %rsi, %freereg movq %freereg, %rsi (c) Update the current assignment (d) If the instruction is a branch: if the destination block already has a register assignment, Generate a new block with fixup code and redirect the jump to the new block. else, Update the block id->assignment mapping with the current assignment. (e) Delete all register assignments for temps which are read (only) and die here. Update the free register list. (f) Mark all registers clobbered by this instruction as not free, and mark temporaries which have been spilled due to clobbering as in memory (step (a) marks then as in both mem & reg). (g) For each temporary *written* by this instruction: Allocate a real register as for (b), spilling something else if necessary. - except when updating the assignment, drop any memory locations that the temporary was previously in, since they will be no longer valid after this instruction. (h) Delete all register assignments for temps which are written and die here (there should rarely be any). Update the free register list. (i) Rewrite the instruction with the new mapping. (j) For each spilled reg known to be now dead, re-add its stack slot to the free list. -} module RegAlloc.Linear.Main ( regAlloc, module RegAlloc.Linear.Base, module RegAlloc.Linear.Stats ) where #include "HsVersions.h" import RegAlloc.Linear.State import RegAlloc.Linear.Base import RegAlloc.Linear.StackMap import RegAlloc.Linear.FreeRegs import RegAlloc.Linear.Stats import RegAlloc.Linear.JoinToTargets import qualified RegAlloc.Linear.PPC.FreeRegs as PPC import qualified RegAlloc.Linear.SPARC.FreeRegs as SPARC import qualified RegAlloc.Linear.X86.FreeRegs as X86 import qualified RegAlloc.Linear.X86_64.FreeRegs as X86_64 import TargetReg import RegAlloc.Liveness import Instruction import Reg import BlockId import Cmm hiding (RegSet) import Digraph import DynFlags import Unique import UniqSet import UniqFM import UniqSupply import Outputable import Platform import Data.Maybe import Data.List import Control.Monad -- ----------------------------------------------------------------------------- -- Top level of the register allocator -- Allocate registers regAlloc :: (Outputable instr, Instruction instr) => DynFlags -> LiveCmmDecl statics instr -> UniqSM ( NatCmmDecl statics instr , Maybe Int -- number of extra stack slots required, -- beyond maxSpillSlots , Maybe RegAllocStats) regAlloc _ (CmmData sec d) = return ( CmmData sec d , Nothing , Nothing ) regAlloc _ (CmmProc (LiveInfo info _ _ _) lbl live []) = return ( CmmProc info lbl live (ListGraph []) , Nothing , Nothing ) regAlloc dflags (CmmProc static lbl live sccs) | LiveInfo info entry_ids@(first_id:_) (Just block_live) _ <- static = do -- do register allocation on each component. (final_blocks, stats, stack_use) <- linearRegAlloc dflags entry_ids block_live sccs -- make sure the block that was first in the input list -- stays at the front of the output let ((first':_), rest') = partition ((== first_id) . blockId) final_blocks let max_spill_slots = maxSpillSlots dflags extra_stack | stack_use > max_spill_slots = Just (stack_use - max_spill_slots) | otherwise = Nothing return ( CmmProc info lbl live (ListGraph (first' : rest')) , extra_stack , Just stats) -- bogus. to make non-exhaustive match warning go away. regAlloc _ (CmmProc _ _ _ _) = panic "RegAllocLinear.regAlloc: no match" -- ----------------------------------------------------------------------------- -- Linear sweep to allocate registers -- | Do register allocation on some basic blocks. -- But be careful to allocate a block in an SCC only if it has -- an entry in the block map or it is the first block. -- linearRegAlloc :: (Outputable instr, Instruction instr) => DynFlags -> [BlockId] -- ^ entry points -> BlockMap RegSet -- ^ live regs on entry to each basic block -> [SCC (LiveBasicBlock instr)] -- ^ instructions annotated with "deaths" -> UniqSM ([NatBasicBlock instr], RegAllocStats, Int) linearRegAlloc dflags entry_ids block_live sccs = let platform = targetPlatform dflags in case platformArch platform of ArchX86 -> linearRegAlloc' dflags (frInitFreeRegs platform :: X86.FreeRegs) entry_ids block_live sccs ArchX86_64 -> linearRegAlloc' dflags (frInitFreeRegs platform :: X86_64.FreeRegs) entry_ids block_live sccs ArchSPARC -> linearRegAlloc' dflags (frInitFreeRegs platform :: SPARC.FreeRegs) entry_ids block_live sccs ArchPPC -> linearRegAlloc' dflags (frInitFreeRegs platform :: PPC.FreeRegs) entry_ids block_live sccs ArchARM _ _ _ -> panic "linearRegAlloc ArchARM" ArchPPC_64 -> panic "linearRegAlloc ArchPPC_64" ArchAlpha -> panic "linearRegAlloc ArchAlpha" ArchMipseb -> panic "linearRegAlloc ArchMipseb" ArchMipsel -> panic "linearRegAlloc ArchMipsel" ArchJavaScript -> panic "linearRegAlloc ArchJavaScript" ArchUnknown -> panic "linearRegAlloc ArchUnknown" linearRegAlloc' :: (FR freeRegs, Outputable instr, Instruction instr) => DynFlags -> freeRegs -> [BlockId] -- ^ entry points -> BlockMap RegSet -- ^ live regs on entry to each basic block -> [SCC (LiveBasicBlock instr)] -- ^ instructions annotated with "deaths" -> UniqSM ([NatBasicBlock instr], RegAllocStats, Int) linearRegAlloc' dflags initFreeRegs entry_ids block_live sccs = do us <- getUs let (_, stack, stats, blocks) = runR dflags emptyBlockMap initFreeRegs emptyRegMap (emptyStackMap dflags) us $ linearRA_SCCs entry_ids block_live [] sccs return (blocks, stats, getStackUse stack) linearRA_SCCs :: (FR freeRegs, Instruction instr, Outputable instr) => [BlockId] -> BlockMap RegSet -> [NatBasicBlock instr] -> [SCC (LiveBasicBlock instr)] -> RegM freeRegs [NatBasicBlock instr] linearRA_SCCs _ _ blocksAcc [] = return $ reverse blocksAcc linearRA_SCCs entry_ids block_live blocksAcc (AcyclicSCC block : sccs) = do blocks' <- processBlock block_live block linearRA_SCCs entry_ids block_live ((reverse blocks') ++ blocksAcc) sccs linearRA_SCCs entry_ids block_live blocksAcc (CyclicSCC blocks : sccs) = do blockss' <- process entry_ids block_live blocks [] (return []) False linearRA_SCCs entry_ids block_live (reverse (concat blockss') ++ blocksAcc) sccs {- from John Dias's patch 2008/10/16: The linear-scan allocator sometimes allocates a block before allocating one of its predecessors, which could lead to inconsistent allocations. Make it so a block is only allocated if a predecessor has set the "incoming" assignments for the block, or if it's the procedure's entry block. BL 2009/02: Careful. If the assignment for a block doesn't get set for some reason then this function will loop. We should probably do some more sanity checking to guard against this eventuality. -} process :: (FR freeRegs, Instruction instr, Outputable instr) => [BlockId] -> BlockMap RegSet -> [GenBasicBlock (LiveInstr instr)] -> [GenBasicBlock (LiveInstr instr)] -> [[NatBasicBlock instr]] -> Bool -> RegM freeRegs [[NatBasicBlock instr]] process _ _ [] [] accum _ = return $ reverse accum process entry_ids block_live [] next_round accum madeProgress | not madeProgress {- BUGS: There are so many unreachable blocks in the code the warnings are overwhelming. pprTrace "RegAlloc.Linear.Main.process: no progress made, bailing out." ( text "Unreachable blocks:" $$ vcat (map ppr next_round)) -} = return $ reverse accum | otherwise = process entry_ids block_live next_round [] accum False process entry_ids block_live (b@(BasicBlock id _) : blocks) next_round accum madeProgress = do block_assig <- getBlockAssigR if isJust (mapLookup id block_assig) || id `elem` entry_ids then do b' <- processBlock block_live b process entry_ids block_live blocks next_round (b' : accum) True else process entry_ids block_live blocks (b : next_round) accum madeProgress -- | Do register allocation on this basic block -- processBlock :: (FR freeRegs, Outputable instr, Instruction instr) => BlockMap RegSet -- ^ live regs on entry to each basic block -> LiveBasicBlock instr -- ^ block to do register allocation on -> RegM freeRegs [NatBasicBlock instr] -- ^ block with registers allocated processBlock block_live (BasicBlock id instrs) = do initBlock id block_live (instrs', fixups) <- linearRA block_live [] [] id instrs return $ BasicBlock id instrs' : fixups -- | Load the freeregs and current reg assignment into the RegM state -- for the basic block with this BlockId. initBlock :: FR freeRegs => BlockId -> BlockMap RegSet -> RegM freeRegs () initBlock id block_live = do dflags <- getDynFlags let platform = targetPlatform dflags block_assig <- getBlockAssigR case mapLookup id block_assig of -- no prior info about this block: we must consider -- any fixed regs to be allocated, but we can ignore -- virtual regs (presumably this is part of a loop, -- and we'll iterate again). The assignment begins -- empty. Nothing -> do -- pprTrace "initFreeRegs" (text $ show initFreeRegs) (return ()) case mapLookup id block_live of Nothing -> setFreeRegsR (frInitFreeRegs platform) Just live -> setFreeRegsR $ foldr (frAllocateReg platform) (frInitFreeRegs platform) [ r | RegReal r <- uniqSetToList live ] setAssigR emptyRegMap -- load info about register assignments leading into this block. Just (freeregs, assig) -> do setFreeRegsR freeregs setAssigR assig -- | Do allocation for a sequence of instructions. linearRA :: (FR freeRegs, Outputable instr, Instruction instr) => BlockMap RegSet -- ^ map of what vregs are live on entry to each block. -> [instr] -- ^ accumulator for instructions already processed. -> [NatBasicBlock instr] -- ^ accumulator for blocks of fixup code. -> BlockId -- ^ id of the current block, for debugging. -> [LiveInstr instr] -- ^ liveness annotated instructions in this block. -> RegM freeRegs ( [instr] -- instructions after register allocation , [NatBasicBlock instr]) -- fresh blocks of fixup code. linearRA _ accInstr accFixup _ [] = return ( reverse accInstr -- instrs need to be returned in the correct order. , accFixup) -- it doesn't matter what order the fixup blocks are returned in. linearRA block_live accInstr accFixups id (instr:instrs) = do (accInstr', new_fixups) <- raInsn block_live accInstr id instr linearRA block_live accInstr' (new_fixups ++ accFixups) id instrs -- | Do allocation for a single instruction. raInsn :: (FR freeRegs, Outputable instr, Instruction instr) => BlockMap RegSet -- ^ map of what vregs are love on entry to each block. -> [instr] -- ^ accumulator for instructions already processed. -> BlockId -- ^ the id of the current block, for debugging -> LiveInstr instr -- ^ the instr to have its regs allocated, with liveness info. -> RegM freeRegs ( [instr] -- new instructions , [NatBasicBlock instr]) -- extra fixup blocks raInsn _ new_instrs _ (LiveInstr ii Nothing) | Just n <- takeDeltaInstr ii = do setDeltaR n return (new_instrs, []) raInsn _ new_instrs _ (LiveInstr ii Nothing) | isMetaInstr ii = return (new_instrs, []) raInsn block_live new_instrs id (LiveInstr (Instr instr) (Just live)) = do assig <- getAssigR -- If we have a reg->reg move between virtual registers, where the -- src register is not live after this instruction, and the dst -- register does not already have an assignment, -- and the source register is assigned to a register, not to a spill slot, -- then we can eliminate the instruction. -- (we can't eliminate it if the source register is on the stack, because -- we do not want to use one spill slot for different virtual registers) case takeRegRegMoveInstr instr of Just (src,dst) | src `elementOfUniqSet` (liveDieRead live), isVirtualReg dst, not (dst `elemUFM` assig), isRealReg src || isInReg src assig -> do case src of (RegReal rr) -> setAssigR (addToUFM assig dst (InReg rr)) -- if src is a fixed reg, then we just map dest to this -- reg in the assignment. src must be an allocatable reg, -- otherwise it wouldn't be in r_dying. _virt -> case lookupUFM assig src of Nothing -> panic "raInsn" Just loc -> setAssigR (addToUFM (delFromUFM assig src) dst loc) -- we have eliminated this instruction {- freeregs <- getFreeRegsR assig <- getAssigR pprTrace "raInsn" (text "ELIMINATED: " <> docToSDoc (pprInstr instr) $$ ppr r_dying <+> ppr w_dying $$ text (show freeregs) $$ ppr assig) $ do -} return (new_instrs, []) _ -> genRaInsn block_live new_instrs id instr (uniqSetToList $ liveDieRead live) (uniqSetToList $ liveDieWrite live) raInsn _ _ _ instr = pprPanic "raInsn" (text "no match for:" <> ppr instr) -- ToDo: what can we do about -- -- R1 = x -- jump I64[x] // [R1] -- -- where x is mapped to the same reg as R1. We want to coalesce x and -- R1, but the register allocator doesn't know whether x will be -- assigned to again later, in which case x and R1 should be in -- different registers. Right now we assume the worst, and the -- assignment to R1 will clobber x, so we'll spill x into another reg, -- generating another reg->reg move. isInReg :: Reg -> RegMap Loc -> Bool isInReg src assig | Just (InReg _) <- lookupUFM assig src = True | otherwise = False genRaInsn :: (FR freeRegs, Instruction instr, Outputable instr) => BlockMap RegSet -> [instr] -> BlockId -> instr -> [Reg] -> [Reg] -> RegM freeRegs ([instr], [NatBasicBlock instr]) genRaInsn block_live new_instrs block_id instr r_dying w_dying = do dflags <- getDynFlags let platform = targetPlatform dflags case regUsageOfInstr platform instr of { RU read written -> do let real_written = [ rr | (RegReal rr) <- written ] let virt_written = [ vr | (RegVirtual vr) <- written ] -- we don't need to do anything with real registers that are -- only read by this instr. (the list is typically ~2 elements, -- so using nub isn't a problem). let virt_read = nub [ vr | (RegVirtual vr) <- read ] -- debugging {- freeregs <- getFreeRegsR assig <- getAssigR pprDebugAndThen (defaultDynFlags Settings{ sTargetPlatform=platform }) trace "genRaInsn" (ppr instr $$ text "r_dying = " <+> ppr r_dying $$ text "w_dying = " <+> ppr w_dying $$ text "virt_read = " <+> ppr virt_read $$ text "virt_written = " <+> ppr virt_written $$ text "freeregs = " <+> text (show freeregs) $$ text "assig = " <+> ppr assig) $ do -} -- (a), (b) allocate real regs for all regs read by this instruction. (r_spills, r_allocd) <- allocateRegsAndSpill True{-reading-} virt_read [] [] virt_read -- (c) save any temporaries which will be clobbered by this instruction clobber_saves <- saveClobberedTemps real_written r_dying -- (d) Update block map for new destinations -- NB. do this before removing dead regs from the assignment, because -- these dead regs might in fact be live in the jump targets (they're -- only dead in the code that follows in the current basic block). (fixup_blocks, adjusted_instr) <- joinToTargets block_live block_id instr -- (e) Delete all register assignments for temps which are read -- (only) and die here. Update the free register list. releaseRegs r_dying -- (f) Mark regs which are clobbered as unallocatable clobberRegs real_written -- (g) Allocate registers for temporaries *written* (only) (w_spills, w_allocd) <- allocateRegsAndSpill False{-writing-} virt_written [] [] virt_written -- (h) Release registers for temps which are written here and not -- used again. releaseRegs w_dying let -- (i) Patch the instruction patch_map = listToUFM [ (t, RegReal r) | (t, r) <- zip virt_read r_allocd ++ zip virt_written w_allocd ] patched_instr = patchRegsOfInstr adjusted_instr patchLookup patchLookup x = case lookupUFM patch_map x of Nothing -> x Just y -> y -- (j) free up stack slots for dead spilled regs -- TODO (can't be bothered right now) -- erase reg->reg moves where the source and destination are the same. -- If the src temp didn't die in this instr but happened to be allocated -- to the same real reg as the destination, then we can erase the move anyway. let squashed_instr = case takeRegRegMoveInstr patched_instr of Just (src, dst) | src == dst -> [] _ -> [patched_instr] let code = squashed_instr ++ w_spills ++ reverse r_spills ++ clobber_saves ++ new_instrs -- pprTrace "patched-code" ((vcat $ map (docToSDoc . pprInstr) code)) $ do -- pprTrace "pached-fixup" ((ppr fixup_blocks)) $ do return (code, fixup_blocks) } -- ----------------------------------------------------------------------------- -- releaseRegs releaseRegs :: FR freeRegs => [Reg] -> RegM freeRegs () releaseRegs regs = do dflags <- getDynFlags let platform = targetPlatform dflags assig <- getAssigR free <- getFreeRegsR let loop _ free _ | free `seq` False = undefined loop assig free [] = do setAssigR assig; setFreeRegsR free; return () loop assig free (RegReal rr : rs) = loop assig (frReleaseReg platform rr free) rs loop assig free (r:rs) = case lookupUFM assig r of Just (InBoth real _) -> loop (delFromUFM assig r) (frReleaseReg platform real free) rs Just (InReg real) -> loop (delFromUFM assig r) (frReleaseReg platform real free) rs _ -> loop (delFromUFM assig r) free rs loop assig free regs -- ----------------------------------------------------------------------------- -- Clobber real registers -- For each temp in a register that is going to be clobbered: -- - if the temp dies after this instruction, do nothing -- - otherwise, put it somewhere safe (another reg if possible, -- otherwise spill and record InBoth in the assignment). -- - for allocateRegs on the temps *read*, -- - clobbered regs are allocatable. -- -- for allocateRegs on the temps *written*, -- - clobbered regs are not allocatable. -- saveClobberedTemps :: (Outputable instr, Instruction instr, FR freeRegs) => [RealReg] -- real registers clobbered by this instruction -> [Reg] -- registers which are no longer live after this insn -> RegM freeRegs [instr] -- return: instructions to spill any temps that will -- be clobbered. saveClobberedTemps [] _ = return [] saveClobberedTemps clobbered dying = do assig <- getAssigR let to_spill = [ (temp,reg) | (temp, InReg reg) <- ufmToList assig , any (realRegsAlias reg) clobbered , temp `notElem` map getUnique dying ] (instrs,assig') <- clobber assig [] to_spill setAssigR assig' return instrs where clobber assig instrs [] = return (instrs, assig) clobber assig instrs ((temp, reg) : rest) = do dflags <- getDynFlags let platform = targetPlatform dflags freeRegs <- getFreeRegsR let regclass = targetClassOfRealReg platform reg freeRegs_thisClass = frGetFreeRegs platform regclass freeRegs case filter (`notElem` clobbered) freeRegs_thisClass of -- (1) we have a free reg of the right class that isn't -- clobbered by this instruction; use it to save the -- clobbered value. (my_reg : _) -> do setFreeRegsR (frAllocateReg platform my_reg freeRegs) let new_assign = addToUFM assig temp (InReg my_reg) let instr = mkRegRegMoveInstr platform (RegReal reg) (RegReal my_reg) clobber new_assign (instr : instrs) rest -- (2) no free registers: spill the value [] -> do (spill, slot) <- spillR (RegReal reg) temp -- record why this reg was spilled for profiling recordSpill (SpillClobber temp) let new_assign = addToUFM assig temp (InBoth reg slot) clobber new_assign (spill : instrs) rest -- | Mark all these real regs as allocated, -- and kick out their vreg assignments. -- clobberRegs :: FR freeRegs => [RealReg] -> RegM freeRegs () clobberRegs [] = return () clobberRegs clobbered = do dflags <- getDynFlags let platform = targetPlatform dflags freeregs <- getFreeRegsR setFreeRegsR $! foldr (frAllocateReg platform) freeregs clobbered assig <- getAssigR setAssigR $! clobber assig (ufmToList assig) where -- if the temp was InReg and clobbered, then we will have -- saved it in saveClobberedTemps above. So the only case -- we have to worry about here is InBoth. Note that this -- also catches temps which were loaded up during allocation -- of read registers, not just those saved in saveClobberedTemps. clobber assig [] = assig clobber assig ((temp, InBoth reg slot) : rest) | any (realRegsAlias reg) clobbered = clobber (addToUFM assig temp (InMem slot)) rest clobber assig (_:rest) = clobber assig rest -- ----------------------------------------------------------------------------- -- allocateRegsAndSpill -- Why are we performing a spill? data SpillLoc = ReadMem StackSlot -- reading from register only in memory | WriteNew -- writing to a new variable | WriteMem -- writing to register only in memory -- Note that ReadNew is not valid, since you don't want to be reading -- from an uninitialized register. We also don't need the location of -- the register in memory, since that will be invalidated by the write. -- Technically, we could coalesce WriteNew and WriteMem into a single -- entry as well. -- EZY -- This function does several things: -- For each temporary referred to by this instruction, -- we allocate a real register (spilling another temporary if necessary). -- We load the temporary up from memory if necessary. -- We also update the register assignment in the process, and -- the list of free registers and free stack slots. allocateRegsAndSpill :: (FR freeRegs, Outputable instr, Instruction instr) => Bool -- True <=> reading (load up spilled regs) -> [VirtualReg] -- don't push these out -> [instr] -- spill insns -> [RealReg] -- real registers allocated (accum.) -> [VirtualReg] -- temps to allocate -> RegM freeRegs ( [instr] , [RealReg]) allocateRegsAndSpill _ _ spills alloc [] = return (spills, reverse alloc) allocateRegsAndSpill reading keep spills alloc (r:rs) = do assig <- getAssigR let doSpill = allocRegsAndSpill_spill reading keep spills alloc r rs assig case lookupUFM assig r of -- case (1a): already in a register Just (InReg my_reg) -> allocateRegsAndSpill reading keep spills (my_reg:alloc) rs -- case (1b): already in a register (and memory) -- NB1. if we're writing this register, update its assignment to be -- InReg, because the memory value is no longer valid. -- NB2. This is why we must process written registers here, even if they -- are also read by the same instruction. Just (InBoth my_reg _) -> do when (not reading) (setAssigR (addToUFM assig r (InReg my_reg))) allocateRegsAndSpill reading keep spills (my_reg:alloc) rs -- Not already in a register, so we need to find a free one... Just (InMem slot) | reading -> doSpill (ReadMem slot) | otherwise -> doSpill WriteMem Nothing | reading -> pprPanic "allocateRegsAndSpill: Cannot read from uninitialized register" (ppr r) -- NOTE: if the input to the NCG contains some -- unreachable blocks with junk code, this panic -- might be triggered. Make sure you only feed -- sensible code into the NCG. In CmmPipeline we -- call removeUnreachableBlocks at the end for this -- reason. | otherwise -> doSpill WriteNew -- reading is redundant with reason, but we keep it around because it's -- convenient and it maintains the recursive structure of the allocator. -- EZY allocRegsAndSpill_spill :: (FR freeRegs, Instruction instr, Outputable instr) => Bool -> [VirtualReg] -> [instr] -> [RealReg] -> VirtualReg -> [VirtualReg] -> UniqFM Loc -> SpillLoc -> RegM freeRegs ([instr], [RealReg]) allocRegsAndSpill_spill reading keep spills alloc r rs assig spill_loc = do dflags <- getDynFlags let platform = targetPlatform dflags freeRegs <- getFreeRegsR let freeRegs_thisClass = frGetFreeRegs platform (classOfVirtualReg r) freeRegs case freeRegs_thisClass of -- case (2): we have a free register (my_reg : _) -> do spills' <- loadTemp r spill_loc my_reg spills setAssigR (addToUFM assig r $! newLocation spill_loc my_reg) setFreeRegsR $ frAllocateReg platform my_reg freeRegs allocateRegsAndSpill reading keep spills' (my_reg : alloc) rs -- case (3): we need to push something out to free up a register [] -> do let keep' = map getUnique keep -- the vregs we could kick out that are already in a slot let candidates_inBoth = [ (temp, reg, mem) | (temp, InBoth reg mem) <- ufmToList assig , temp `notElem` keep' , targetClassOfRealReg platform reg == classOfVirtualReg r ] -- the vregs we could kick out that are only in a reg -- this would require writing the reg to a new slot before using it. let candidates_inReg = [ (temp, reg) | (temp, InReg reg) <- ufmToList assig , temp `notElem` keep' , targetClassOfRealReg platform reg == classOfVirtualReg r ] let result -- we have a temporary that is in both register and mem, -- just free up its register for use. | (temp, my_reg, slot) : _ <- candidates_inBoth = do spills' <- loadTemp r spill_loc my_reg spills let assig1 = addToUFM assig temp (InMem slot) let assig2 = addToUFM assig1 r $! newLocation spill_loc my_reg setAssigR assig2 allocateRegsAndSpill reading keep spills' (my_reg:alloc) rs -- otherwise, we need to spill a temporary that currently -- resides in a register. | (temp_to_push_out, (my_reg :: RealReg)) : _ <- candidates_inReg = do (spill_insn, slot) <- spillR (RegReal my_reg) temp_to_push_out let spill_store = (if reading then id else reverse) [ -- COMMENT (fsLit "spill alloc") spill_insn ] -- record that this temp was spilled recordSpill (SpillAlloc temp_to_push_out) -- update the register assignment let assig1 = addToUFM assig temp_to_push_out (InMem slot) let assig2 = addToUFM assig1 r $! newLocation spill_loc my_reg setAssigR assig2 -- if need be, load up a spilled temp into the reg we've just freed up. spills' <- loadTemp r spill_loc my_reg spills allocateRegsAndSpill reading keep (spill_store ++ spills') (my_reg:alloc) rs -- there wasn't anything to spill, so we're screwed. | otherwise = pprPanic ("RegAllocLinear.allocRegsAndSpill: no spill candidates\n") $ vcat [ text "allocating vreg: " <> text (show r) , text "assignment: " <> text (show $ ufmToList assig) , text "freeRegs: " <> text (show freeRegs) , text "initFreeRegs: " <> text (show (frInitFreeRegs platform `asTypeOf` freeRegs)) ] result -- | Calculate a new location after a register has been loaded. newLocation :: SpillLoc -> RealReg -> Loc -- if the tmp was read from a slot, then now its in a reg as well newLocation (ReadMem slot) my_reg = InBoth my_reg slot -- writes will always result in only the register being available newLocation _ my_reg = InReg my_reg -- | Load up a spilled temporary if we need to (read from memory). loadTemp :: (Outputable instr, Instruction instr) => VirtualReg -- the temp being loaded -> SpillLoc -- the current location of this temp -> RealReg -- the hreg to load the temp into -> [instr] -> RegM freeRegs [instr] loadTemp vreg (ReadMem slot) hreg spills = do insn <- loadR (RegReal hreg) slot recordSpill (SpillLoad $ getUnique vreg) return $ {- COMMENT (fsLit "spill load") : -} insn : spills loadTemp _ _ _ spills = return spills
hferreiro/replay
compiler/nativeGen/RegAlloc/Linear/Main.hs
bsd-3-clause
36,812
3
25
12,983
5,716
2,922
2,794
-1
-1
module VSim.Data.Line where data Line = Line { lineFilename :: FilePath , lineLine :: Int , lineColumn :: Int } deriving (Show,Eq, Ord) showLine :: Line -> String showLine l = lineFilename l ++ ":" ++ show (lineLine l) ++ ":" ++ show (lineColumn l) ++ ":"
ierton/vsim
src/VSim/Data/Line.hs
bsd-3-clause
297
0
11
88
107
58
49
8
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} module Text.Toml.Types ( Table , emptyTable , VTArray , VArray , Node (..) , Explicitness (..) , isExplicit , insert , ToJSON (..) , ToBsJSON (..) ) where import Control.Monad (when) import Text.Parsec import Data.Aeson.Types import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as M import Data.Int (Int64) import Data.List (intersect) import Data.Set (Set) import qualified Data.Set as S import Data.Text (Text) import qualified Data.Text as T import Data.Time.Clock (UTCTime) import Data.Time.Format () import Data.Vector (Vector) import qualified Data.Vector as V -- | The TOML 'Table' is a mapping ('HashMap') of 'Text' keys to 'Node' values. type Table = HashMap Text Node -- | Contruct an empty 'Table'. emptyTable :: Table emptyTable = M.empty -- | An array of 'Table's, implemented using a 'Vector'. type VTArray = Vector Table -- | A \"value\" array that may contain zero or more 'Node's, implemented using a 'Vector'. type VArray = Vector Node -- | A 'Node' may contain any type of value that may be put in a 'VArray'. data Node = VTable !Table | VTArray !VTArray | VString !Text | VInteger !Int64 | VFloat !Double | VBoolean !Bool | VDatetime !UTCTime | VArray !VArray deriving (Eq, Show) -- | To mark whether or not a 'Table' has been explicitly defined. -- See: https://github.com/toml-lang/toml/issues/376 data Explicitness = Explicit | Implicit deriving (Eq, Show) -- | Convenience function to get a boolean value. isExplicit :: Explicitness -> Bool isExplicit Explicit = True isExplicit Implicit = False -- | Inserts a table, 'Table', with the namespaced name, '[Text]', (which -- may be part of a table array) into a 'Table'. -- It may result in an error in the 'ParsecT' monad for redefinitions. insert :: Explicitness -> ([Text], Node) -> Table -> Parsec Text (Set [Text]) Table insert _ ([], _) _ = parserFail "FATAL: Cannot call 'insert' without a name." insert ex ([name], node) ttbl = -- In case 'name' is final (a top-level name) case M.lookup name ttbl of Nothing -> do when (isExplicit ex) $ updateExState [name] node return $ M.insert name node ttbl Just (VTable t) -> case node of (VTable nt) -> case merge t nt of Left ds -> nameInsertError ds name Right r -> do when (isExplicit ex) $ updateExStateOrError [name] node return $ M.insert name (VTable r) ttbl _ -> commonInsertError node [name] Just (VTArray a) -> case node of (VTArray na) -> return $ M.insert name (VTArray $ a V.++ na) ttbl _ -> commonInsertError node [name] Just _ -> commonInsertError node [name] insert ex (fullName@(name:ns), node) ttbl = -- In case 'name' is not final (not a top-level name) case M.lookup name ttbl of Nothing -> do r <- insert Implicit (ns, node) emptyTable when (isExplicit ex) $ updateExState fullName node return $ M.insert name (VTable r) ttbl Just (VTable t) -> do r <- insert Implicit (ns, node) t when (isExplicit ex) $ updateExStateOrError fullName node return $ M.insert name (VTable r) ttbl Just (VTArray a) -> if V.null a then parserFail "FATAL: Call to 'insert' found impossibly empty VArray." else do r <- insert Implicit (ns, node) (V.last a) return $ M.insert name (VTArray $ (V.init a) `V.snoc` r) ttbl Just _ -> commonInsertError node fullName -- | Merge two tables, resulting in an error when overlapping keys are -- found ('Left' will contain those keys). When no overlapping keys are -- found the result will contain the union of both tables in a 'Right'. merge :: Table -> Table -> Either [Text] Table merge existing new = case M.keys existing `intersect` M.keys new of [] -> Right $ M.union existing new ds -> Left $ ds -- TOML tables maybe redefined when first definition was implicit. -- For instance a top-level table `a` can implicitly defined by defining a non top-level -- table `b` under it (namely with `[a.b]`). Once the table `a` is subsequently defined -- explicitly (namely with `[a]`), it is then not possible to (re-)define it again. -- A parser state of all explicitly defined tables is maintained, which allows -- raising errors for illegal redefinitions of such. updateExStateOrError :: [Text] -> Node -> Parsec Text (Set [Text]) () updateExStateOrError name node@(VTable _) = do explicitlyDefinedNames <- getState when (S.member name explicitlyDefinedNames) $ tableClashError name updateExState name node updateExStateOrError _ _ = return () -- | Like 'updateExStateOrError' but does not raise errors. Only use this when sure -- that redefinitions cannot occur. updateExState :: [Text] -> Node -> Parsec Text (S.Set [Text]) () updateExState name (VTable _) = modifyState $ S.insert name updateExState _ _ = return () -- * Parse errors resulting from invalid TOML -- | Key(s) redefintion error. nameInsertError :: [Text] -> Text -> Parsec Text (Set [Text]) a nameInsertError ns name = parserFail . T.unpack $ T.concat [ "Cannot redefine key(s) (", T.intercalate ", " ns , "), from table named '", name, "'." ] -- | Table redefinition error. tableClashError :: [Text] -> Parsec Text (Set [Text]) a tableClashError name = parserFail . T.unpack $ T.concat [ "Cannot redefine table named: '", T.intercalate "." name, "'." ] -- | Common redefinition error. commonInsertError :: Node -> [Text] -> Parsec Text (Set [Text]) a commonInsertError what name = parserFail . concat $ [ "Cannot insert ", w, " as '", n, "' since key already exists." ] where n = T.unpack $ T.intercalate "." name w = case what of (VTable _) -> "tables" _ -> "array of tables" -- * Regular ToJSON instances -- | 'ToJSON' instances for the 'Node' type that produce Aeson (JSON) -- in line with the TOML specification. instance ToJSON Node where toJSON (VTable v) = toJSON v toJSON (VTArray v) = toJSON v toJSON (VString v) = toJSON v toJSON (VInteger v) = toJSON v toJSON (VFloat v) = toJSON v toJSON (VBoolean v) = toJSON v toJSON (VDatetime v) = toJSON v toJSON (VArray v) = toJSON v -- * Special BurntSushi ToJSON type class and instances -- | Type class for conversion to BurntSushi-style JSON. -- -- BurntSushi has made a language agnostic test suite available that -- this library uses. This test suit expects that values are encoded -- as JSON objects with a 'type' and a 'value' member. class ToBsJSON a where toBsJSON :: a -> Value -- | Provide a 'toBsJSON' instance to the 'VTArray'. instance (ToBsJSON a) => ToBsJSON (Vector a) where toBsJSON = Array . V.map toBsJSON {-# INLINE toBsJSON #-} -- | Provide a 'toBsJSON' instance to the 'NTable'. instance (ToBsJSON v) => ToBsJSON (M.HashMap Text v) where toBsJSON = Object . M.map toBsJSON {-# INLINE toBsJSON #-} -- | 'ToBsJSON' instances for the 'TValue' type that produce Aeson (JSON) -- in line with BurntSushi's language agnostic TOML test suite. -- -- As seen in this function, BurntSushi's JSON encoding explicitly -- specifies the types of the values. instance ToBsJSON Node where toBsJSON (VTable v) = toBsJSON v toBsJSON (VTArray v) = toBsJSON v toBsJSON (VString v) = object [ "type" .= toJSON ("string" :: String) , "value" .= toJSON v ] toBsJSON (VInteger v) = object [ "type" .= toJSON ("integer" :: String) , "value" .= toJSON (show v) ] toBsJSON (VFloat v) = object [ "type" .= toJSON ("float" :: String) , "value" .= toJSON (show v) ] toBsJSON (VBoolean v) = object [ "type" .= toJSON ("bool" :: String) , "value" .= toJSON (if v then "true" else "false" :: String) ] toBsJSON (VDatetime v) = object [ "type" .= toJSON ("datetime" :: String) , "value" .= toJSON (let s = show v z = take (length s - 4) s ++ "Z" d = take (length z - 10) z t = drop (length z - 9) z in d ++ "T" ++ t) ] toBsJSON (VArray v) = object [ "type" .= toJSON ("array" :: String) , "value" .= toBsJSON v ]
cies/htoml
src/Text/Toml/Types.hs
bsd-3-clause
8,971
0
19
2,614
2,215
1,165
1,050
158
11
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-} -- | A valid transaction must be balanced--that is, for each -- commodity, the debits must be equal to the credits. This module -- contains types and functions that help ensure that an entire -- collection of postings--that is, a transaction--is balanced. module Penny.Ents ( Ents , entsToSeqEnt , entsToImbalance , appendTrio , prependTrio , Balanced , balancedToSeqEnt , entsToBalanced , ImbalancedError(..) , restrictedBalanced , twoPostingBalanced ) where import Control.Lens ((<|), (|>)) import qualified Control.Lens as Lens import Data.Sequence (Seq, viewl, ViewL(EmptyL, (:<))) import Data.Sequence.NonEmpty (NonEmptySeq) import qualified Data.Sequence.NonEmpty as NE import qualified Data.Sequence as S import Data.Monoid ((<>)) import qualified Data.Foldable as F import qualified Data.Traversable as T import qualified Data.Map as M import Penny.Arrangement import Penny.Balance import Penny.Commodity import Penny.Copper.Decopperize (dBrimAnyRadix, c'Decimal'RepAnyRadix) import Penny.Decimal import Penny.Polar import Penny.Rep import Penny.Trio import qualified Penny.Troika as Y -- | An 'Ents' contains a collection of postings. The collection is -- not necessarily balanced. The 'Ents' keeps track of whether the -- collection of postings is imbalanced and, if so, by how much. -- -- Each posting is represented only by a 'Y.Troika' along with any -- arbitrary metadata. Typically the metadata will have a 'Seq' of -- 'Penny.Tree.Tree' to represent arbitrary metadata, and a 'Trio' -- to hold the original representation of the quantity and -- commodity. data Ents a = Ents { entsToSeqEnt :: Seq (Y.Troika, a) , entsToImbalance :: Imbalance } deriving Show instance Functor Ents where fmap f (Ents s b) = Ents (fmap (fmap f) s) b instance Monoid (Ents m) where mempty = Ents mempty mempty mappend (Ents s1 b1) (Ents s2 b2) = Ents (s1 <> s2) (b1 <> b2) instance Foldable Ents where foldr f z = F.foldr f z . fmap snd . entsToSeqEnt instance Traversable Ents where sequenceA (Ents sq bl) = fmap (flip Ents bl) . go $ sq where go es = case viewl es of EmptyL -> pure S.empty e :< xs -> (<|) <$> T.sequenceA e <*> go xs -- | Contains a sequence of 'Y.Troika' along with arbitrary metadata -- but, unlike an 'Ents', this is always guaranteed to be balanced. newtype Balanced a = Balanced { balancedToSeqEnt :: Seq (Y.Troika, a) } deriving Show instance Functor Balanced where fmap f (Balanced sq) = Balanced $ fmap (fmap f) sq instance Monoid (Balanced a) where mempty = Balanced mempty mappend (Balanced x) (Balanced y) = Balanced (x <> y) instance Foldable Balanced where foldr f z = F.foldr f z . fmap snd . balancedToSeqEnt instance Traversable Balanced where sequenceA (Balanced sq) = fmap Balanced . go $ sq where go es = case viewl es of EmptyL -> pure S.empty e :< xs -> (<|) <$> T.sequenceA e <*> go xs appendTrio :: Ents a -> Trio -> Either TrioError (a -> Ents a) appendTrio (Ents sq imb) trio = fmap f $ Y.trioToTroiload imb trio where f (troiload, cy) = \meta -> Ents (sq |> (tm, meta)) imb' where tm = Y.Troika cy troiload imb' = imb <> c'Imbalance'Amount (Y.c'Amount'Troika tm) prependTrio :: Ents a -> Trio -> Either TrioError (a -> Ents a) prependTrio (Ents sq imb) trio = fmap f $ Y.trioToTroiload imb trio where f (troiload, cy) = \meta -> Ents ((tm, meta) <| sq) imb' where tm = Y.Troika cy troiload imb' = imb <> c'Imbalance'Amount (Y.c'Amount'Troika tm) data ImbalancedError = ImbalancedError (Commodity, DecNonZero) [(Commodity, DecNonZero)] deriving Show entsToBalanced :: Ents a -> Either ImbalancedError (Balanced a) entsToBalanced (Ents sq (Imbalance m)) = case M.toList m of [] -> return $ Balanced sq x:xs -> Left $ ImbalancedError x xs -- | Creates a 'Balanced'; never fails. Less flexible than -- 'entsToBalanced' but guaranteed not to fail. restrictedBalanced :: NonEmptySeq (BrimAnyRadix, a) -- ^ List of quantities and metadata. There must be at least one quantity. -> Pole -- ^ All given quantities will be on this side. -> Commodity -- ^ All quantities will have this commodity. -> Arrangement -- ^ All given quantities and commodities will be arranged in this -- fashion. -> a -- ^ Metadata for the offsetting 'Y.Troika' -> Balanced a -- ^ A single offsetting 'Y.Troika' is created that is a 'Y.E' that -- is on the opposite side of the quantities given above. All other -- 'Y.Troika' are 'Y.QC'. restrictedBalanced ne pole cy ar meta = Balanced ((fmap mkPair $ NE.nonEmptySeqToSeq ne) |> offset) where mkPair (brim, meta) = (Y.Troika cy $ Y.QC rar ar, meta) where rar = c'RepAnyRadix'BrimAnyRadix pole brim offset = (Y.Troika cy $ Y.E dnz, meta) where dnz = c'DecNonZero'DecPositive (opposite pole) $ foldl addDecPositive b1 bs where NE.NonEmptySeq b1 bs = fmap (dBrimAnyRadix . fst) ne -- | Creates a 'Balanced'; never fails. Unlike 'restrictedBalanced' -- this function creates only transactions that have exactly two -- postings. The advantage of this function over 'restrictedBalanced' -- is that the quantity can be zero. -- -- If the 'RepAnyRadix' is not zero, the offsetting posting is a -- 'Y.E'. Otherwise, the offsetting posting is a 'Y.QC'. twoPostingBalanced :: (RepAnyRadix, a) -- ^ Quantity and metadata for main posting -> Commodity -- ^ Both postings will have this commodity -> Arrangement -- ^ Both postings will be arranged in this fashion. -> a -- ^ Metadata for the offsetting posting -> Balanced a twoPostingBalanced (rar, metaMain) cy ar metaOffset = Balanced [(troikaMain, metaMain), (troikaOffset, metaOffset)] where (troikaMain, troikaOffset) = case decimalToDecNonZero dec of Nothing -> (tMain, tMain) Just dnz -> (tMain, tE) where tE = Y.Troika cy (Y.E (Lens.over poleDecNonZero opposite dnz)) where dec = c'Decimal'RepAnyRadix rar tMain = Y.Troika cy (Y.QC rar ar)
massysett/penny
penny/lib/Penny/Ents.hs
bsd-3-clause
6,273
0
17
1,345
1,567
856
711
112
2
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} module Plot where import ClassyPrelude as CP import Graphics.Rendering.Chart.Easy import Graphics.Rendering.Chart.Backend.Diagrams import Data.Time hiding (readTime) import Data.Colour.SRGB readTime :: TimeZone -> (String, String) -> Either String (LocalTime, Double) readTime tz (t, v) = do time <- parseTimeM True defaultTimeLocale "%e %b %Y %X %Z" t case readMay v of Nothing -> Left $ "Could not read " <> show v Just dbl -> Right $ (utcToLocalTime tz time, dbl) valLines :: TimeZone -> [(String, String)] -> Either String (PlotLines LocalTime Double) valLines tz vals = do times <- mapM (readTime tz) vals return $ plot_lines_values .~ [times] $ def layout :: TimeZone -> [(String, String)] -> Either String (Layout LocalTime Double) layout tz vals = do ls <- valLines tz vals return $ layout_plots .~ [toPlot ls] $ def indexIt :: Int -> [a] -> Maybe (a, a) indexIt idx l = do time <- CP.index l 0 val <- CP.index l idx return (time, val) plotIt :: (PlotValue x0, PlotValue y0) => [([(x0, y0)], String)] -> Layout x0 y0 plotIt vals = layout_plots .~ fmap (toPlot . toLines) valColours $ def where toLines ((v, label), colour) = plot_lines_values .~ [v] $ plot_lines_style . line_color .~ opaque colour $ plot_lines_title .~ label $ def valColours = zip vals $ colours ^.. cycled traverse -- colours = [dodgerblue, burlywood, slategray, yellowgreen, firebrick, purple, palevioletred, mediumaquamarine] colours = [ sRGB 0.27450980392156865 0.5254901960784314 0.7686274509803922 , sRGB 0.7803921568627451 0.30196078431372547 0.26666666666666666 , sRGB 0.6196078431372549 0.7372549019607844 0.3254901960784314 , sRGB 0.5686274509803921 0.4666666666666667 0.7019607843137254 , sRGB 0.22745098039215686 0.6901960784313725 0.8 , sRGB 0.9647058823529412 0.5843137254901961 0.18823529411764706 , sRGB 0.615686274509804 0.7058823529411765 0.8352941176470589 , sRGB24read "4D4D4D" ]
limaner2002/EPC-tools
plots/src/Plot.hs
bsd-3-clause
2,099
0
14
425
622
327
295
-1
-1
{-# LANGUAGE GADTs, TypeFamilies, DeriveFunctor, RankNTypes #-} -- | A data type for computations with requests that can be batched together -- and possibly executed more efficiently. -- -- Inspired by Facebook's <https://github.com/facebook/Haxl Haxl>, but the implementation is pure (no IO). -- -- Things to improve: -- -- * encode the first Handler law in the type (like the Cartesian Store -- Comonad from Multiplate paper) -- -- * support multiple response types (request type indexed by response type) -- module Control.Monad.Batch ( -- * The monad BatchT -- * Usage -- | To use 'BatchT' effectively, you have to provide several things: -- -- * a request type @req@, -- * a response type @'Result' req@, -- * a handler function of type @'Handler' req m@, running in monad @m@. -- , Result , Handler -- ** Making requests -- | The 'BatchT' monad transformer adds one special operation to the underlying monad: , request -- ** Running computations , runBatchT -- ** Pure usage , Batch , runBatch ) where import Control.Applicative import Control.Monad import Control.Monad.Identity import Control.Monad.Trans (MonadTrans, lift) import Data.List (splitAt) -- | Mapping from request type to result type. -- You have to provide an instance for your request type. type family Result req :: * -- | Handler function for batched requests. -- Functions @handler :: Handler req m@ should satisfy the following laws: -- -- > pure (length xs) = length (handler xs) -- > pure handler (xs ++ ys) = liftA2 (++) (handler xs) (handler ys) -- type Handler req m = [req] -> m [Result req] -- | The BatchT monad transformer. -- -- Applicative combinator @'<*>'@ will batch 'request's together. newtype BatchT r (m :: * -> *) a = BatchT { view :: m (View r m a) } deriving (Functor) -- Naming conventions: -- -- * m - monadic values -- * k - continuations -- * f - pure functions, monadic functions (when using >>=) -- * x - values applied to functions -- * r - request lists instance Applicative m => Applicative (BatchT r m) where pure = BatchT . pure . Pure mf <*> mx = BatchT $ liftA2 (<*>) (view mf) (view mx) instance Monad m => Monad (BatchT r m) where return = lift . return m >>= f = BatchT $ view m >>= bindView f where -- Plumbing required to traverse all the monads. bindView f (Pure x) = view $ f x bindView f (More reqs k) = return $ More reqs (k >=> f) instance MonadTrans (BatchT r) where lift = BatchT . (>>= return . Pure) -- | Internal type, representing state of the computation. data View r m a where -- Finished with a value. Pure :: a -> View r m a -- Blocked on some requests. The continuation is in @BatchT r m@ monad, -- so after handling requests it may issue another batch. More :: [r] -> ([Result r] -> BatchT r m a) -> View r m a instance Functor m => Functor (View r m) where -- can't set @fmap f x = pure f <*> x@, because fmap itself is used in (<*>). fmap f (Pure x) = Pure $ f x fmap f (More reqs k) = More reqs (fmap f . k) instance Applicative m => Applicative (View r m) where pure = Pure Pure f <*> mx = f <$> mx mf <*> Pure x = ($ x) <$> mf -- Actual magic happens here. More rf kf <*> More rx kx = More (rf ++ rx) $ \results -> let (resultsF, resultsX) = splitAt (length rf) results in kf resultsF <*> kx resultsX -- | Introduce a request into the computation. -- When ran it will be passed to handler function for processing - possibly -- with other requests. request :: Applicative m => r -> BatchT r m (Result r) request req = BatchT $ pure $ More [req] (pure . head) -- | Run the computation. -- -- The resulting monad doesn't have to be the same as transformed monad. -- Therefore a natural transformation from transformed monad to running monad -- must be provided. runBatchT :: (Monad tm, Monad m) => Handler r m -- ^ function to handle requests -> (forall b. tm b -> m b) -- ^ function to run lifted @tm@ actions in @m@ -> BatchT r tm a -> m a runBatchT handle lift' = (lift' . view) >=> eval where eval (Pure x) = return x eval (More reqs k) = handle reqs >>= runBatchT handle lift' . k -- | 'BatchT' specialized to 'Identity' monad. type Batch r = BatchT r Identity -- | Run a pure computation (in a monad). runBatch :: Monad m => Handler r m -> Batch r a -> m a runBatch handle = runBatchT handle (return . runIdentity)
zyla/monad-batch
Control/Monad/Batch.hs
bsd-3-clause
4,520
0
14
1,082
984
537
447
53
2
{-# LANGUAGE OverloadedStrings #-} import Data.IterIO import Data.IterIO.Http import Data.IterIO.HttpClient import OpenSSL import qualified OpenSSL.Session as SSL import qualified Data.ByteString.Char8 as S8 import qualified Data.ByteString.Lazy as L import System.Environment import Control.Concurrent main :: IO () main = withOpenSSL $ do args <- getArgs case read . head $ args of 0 -> httpExample 1 -> httpsExample 2 -> httpChunkedExample 3 -> httpsChunkedExample _ -> return () httpExample = do res <- simpleGetHttp "http://tools.ietf.org/html/rfc2616" enumHttpResp res |$ stdoutI httpsExample = do ctx <- SSL.context SSL.contextSetCADirectory ctx "/etc/ssl/certs/" res <- simpleGetHttps "https://tools.ietf.org/html/rfc2616" ctx enumHttpResp res |$ stdoutI httpChunkedExample = do res <- simpleGetHttp "http://www.google.com" enumHttpResp res |$ stdoutI httpsChunkedExample = do ctx <- SSL.context SSL.contextSetCADirectory ctx "/etc/ssl/certs/" res <- simpleGetHttps "https://encrypted.google.com" ctx enumHttpResp res |$ stdoutI
scslab/iterIO
Examples/httpClient.hs
bsd-3-clause
1,088
0
12
175
276
139
137
35
5
import Data.Maybe import Data.List -- | A subsequence of a permutation is a collection of elements of the -- permutation in the order that they appear. -- -- For example, (5, 3, 4) is a subsequence of (5, 1, 3, 4, 2). -- -- A subsequence is increasing if the elements of the subsequence increase, -- and decreasing if the elements decrease. -- -- For example, given the permutation (8, 2, 1, 6, 5, 7, 4, 3, 9), -- an increasing subsequence is (2, 6, 7, 9), and -- a decreasing subsequence is (8, 6, 5, 4, 3). -- -- Given a positive n <= 10000 followed by a permutation of length n -- Return a longest increasing subsequence of n -- followed by a longest decreasing subsequence of n. -- -- >>> 5 -- >>> 5 1 4 2 3 -- 1 2 3 -- 5 4 2 -- -- Note: this is a brute force solution that will time out (> 5 min) -- when solving a rosalind dataset (array of size ~10k) -- | helper structure to deliniate things that are done vs in progress data InProgress a = InProgress { done :: [a] , notDone :: [a] } deriving Show -- | for capturing intermediate results type Pipeline a = ([[a]], [InProgress a]) lgis :: Ord a => [a] -> (a -> a -> Bool) -> [[a]] lgis xs ord = let segments = (putInProgress . (rmUnordered ord)) <$> tails xs answer = resolve ord 0 [] $ catMaybes segments in reverse <$> answer -- | resolves all elements that are InProgress given some ordering resolve :: Ord a => (a -> a -> Bool) -> Int -> [[a]] -> [InProgress a] -> [[a]] resolve ord l done [] = done resolve ord l done (x:xs) = let (d, p) = resolveOne ord x (m, n) = foldl pickLongest (l, done) d in resolve ord m n (p ++ xs) -- | given (currentLength, xs) compares the length against ys pickLongest :: (Int, [[a]]) -> [a] -> (Int, [[a]]) pickLongest (l, xs) ys = let m = length ys in case compare l m of EQ -> (l, ys:xs) GT -> (l, xs) LT -> (m, [ys]) -- | puts a list (x:xs) into InProgress [x] xs putInProgress [] = Nothing putInProgress (x:xs) = Just $ InProgress [x] xs -- | removes elements in the list that are not (>) or (<) than the previous -- e.g. (>) -> [3,2,5,8,7] -> [3,5,8.7] rmUnordered :: Ord t => (t -> t -> Bool) -> [t] -> [t] rmUnordered ord [] = [] rmUnordered ord (x:xs) = let y = filter (flip ord x) xs in x:y -- | resolves one InProgress element into a tuple of (done, stillInProgress) resolveOne :: Ord a => (a -> a -> Bool) -> InProgress a -> Pipeline a resolveOne ord (InProgress d []) = ([d],[]) resolveOne ord (InProgress d n) = let expand = reverse <$> foldl (forkOrAppend ord) [] n in foldl (moveOne d) ([],[]) expand -- | moves one item into the pipeline moveOne :: [a] -> Pipeline a -> [a] -> Pipeline a moveOne d (done, remaining) ps = case ps of (x:[]) -> ((x:d):done, remaining) (x:xs) -> (done, (InProgress (x:d) xs): remaining) _ -> (done, remaining) -- | given a new element n, append to elms in xs that matches -- the test, else if no matches, fork as a new element -- e.g. -- (>) -> [[5],[4],[2]] -> 3 -> [[3,2],[5],[4]] (append) -- (>) -> [[5],[4]] -> 3 -> [[5],[4],[3]] (fork) forkOrAppend :: Ord a => (a -> a -> Bool) -> [[a]] -> a -> [[a]] forkOrAppend ord xs n = case partition ((ord n) . last) xs of -- 'last' is O(n), ouch ([], _ ) -> [n] : xs (ys, zs) -> map (n:) ys ++ zs -- copied from perm.hs show' :: Show a => [a] -> String show' = intercalate " " . map show main :: IO () main = do _ <- getLine strSeq <- getLine let intSeq = map (\x -> read x :: Int) $ words strSeq ascSeq = lgis intSeq (>) descSeq = lgis intSeq (<) print "ascending" mapM_ putStrLn $ map show' ascSeq print "descending" mapM_ putStrLn $ map show' descSeq
mitochon/hoosalind
src/problems/lgis.hs
mit
3,688
0
14
864
1,186
644
542
57
3
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} -- TODO rename the module / move defintions / whatever. -- It's not about the network at all. module Pos.Listener.Update ( UpdateMode , handleProposal , handleVote ) where import Universum import Formatting (build, sformat, (%)) import UnliftIO (MonadUnliftIO) import Pos.Chain.Genesis as Genesis (Config) import Pos.Chain.Update (UpdateConfiguration, UpdateParams, UpdateProposal (..), UpdateVote (..)) import Pos.DB.Class (MonadDB, MonadGState) import Pos.DB.Lrc (HasLrcContext) import Pos.DB.Update (UpdateContext, processProposal, processVote) import Pos.Infra.Recovery.Info (MonadRecoveryInfo) import Pos.Infra.Reporting (MonadReporting) import Pos.Infra.Shutdown.Class (HasShutdownContext) import Pos.Infra.Slotting (MonadSlots) import Pos.Infra.StateLock (StateLock) import Pos.Util.Util (HasLens (..)) import Pos.Util.Wlog (WithLogger, logNotice, logWarning) type UpdateMode ctx m = ( WithLogger m , MonadIO m , MonadUnliftIO m , MonadMask m , MonadGState m , MonadDB m , MonadReader ctx m , HasLrcContext ctx , HasLens UpdateContext ctx UpdateContext , HasLens UpdateConfiguration ctx UpdateConfiguration , HasLens UpdateParams ctx UpdateParams , HasLens StateLock ctx StateLock , HasShutdownContext ctx , MonadReporting m , MonadRecoveryInfo ctx m , MonadSlots ctx m ) handleProposal :: forall ctx m . UpdateMode ctx m => Genesis.Config -> (UpdateProposal, [UpdateVote]) -> m Bool handleProposal genesisConfig (proposal, votes) = do res <- processProposal genesisConfig proposal logProp proposal res let processed = isRight res processed <$ when processed (mapM_ processVoteLog votes) where processVoteLog :: UpdateVote -> m () processVoteLog vote = processVote genesisConfig vote >>= logVote vote logVote vote (Left cause) = logWarning $ sformat ("Proposal is accepted but vote "%build% " is rejected, the reason is: "%build) vote cause logVote vote (Right _) = logVoteAccepted vote logProp prop (Left cause) = logWarning $ sformat ("Processing of proposal "%build% " failed, the reason is: "%build) prop cause -- Update proposals are accepted rarely (at least before Shelley), -- so it deserves 'Notice' severity. logProp prop (Right _) = logNotice $ sformat ("Processing of proposal "%build%" is successful") prop ---------------------------------------------------------------------------- -- UpdateVote ---------------------------------------------------------------------------- handleVote :: UpdateMode ctx m => Genesis.Config -> UpdateVote -> m Bool handleVote genesisConfig uv = do res <- processVote genesisConfig uv logProcess uv res pure $ isRight res where logProcess vote (Left cause) = logWarning $ sformat ("Processing of vote "%build% "failed, the reason is: "%build) vote cause logProcess vote (Right _) = logVoteAccepted vote ---------------------------------------------------------------------------- -- Helpers ---------------------------------------------------------------------------- -- Update votes are accepted rarely (at least before Shelley), so -- it deserves 'Notice' severity. logVoteAccepted :: WithLogger m => UpdateVote -> m () logVoteAccepted = logNotice . sformat ("Processing of vote "%build%"is successfull")
input-output-hk/pos-haskell-prototype
lib/src/Pos/Listener/Update.hs
mit
3,847
0
12
1,022
816
445
371
80
3
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DeriveDataTypeable #-} -- | -- Module: Aws.Sns.Commands.Publish -- Copyright: Copyright © 2014 AlephCloud Systems, Inc. -- License: MIT -- Maintainer: Lars Kuhtz <lars@alephcloud.com> -- Stability: experimental -- -- /API Version: 2013-03-31/ -- -- Sends a message to all of a topic's subscribed endpoints. When a messageId -- is returned, the message has been saved and Amazon SNS will attempt to -- deliver it to the topic's subscribers shortly. The format of the outgoing -- message to each subscribed endpoint depends on the notification protocol -- selected. -- -- To use the Publish action for sending a message to a mobile endpoint, such -- as an app on a Kindle device or mobile phone, you must specify the -- EndpointArn. The EndpointArn is returned when making a call with the -- CreatePlatformEndpoint action. The second example below shows a request and -- response for publishing to a mobile endpoint. -- -- <http://docs.aws.amazon.com/sns/2010-03-31/APIReference/API_Publish.html> -- module Aws.Sns.Commands.Publish ( SnsMessage(..) , MessageId(..) , snsMessage , SqsNotification(..) , Publish(..) , PublishResponse(..) , PublishErrors(..) ) where import Aws.Core import Aws.General import Aws.Sns.Core import Aws.Sns.Internal import Control.Applicative import Data.Aeson (ToJSON(..), FromJSON(..), (.:), withObject, encode) import qualified Data.ByteString.Lazy as LB import qualified Data.Map as M import Data.Monoid import Data.String import qualified Data.Text as T import qualified Data.Text.Encoding as T import Data.Time.Clock import Data.Typeable import qualified Network.HTTP.Types as HTTP import Text.XML.Cursor (($//), (&/)) import qualified Text.XML.Cursor as CU publishAction :: SnsAction publishAction = SnsActionPublish -- -------------------------------------------------------------------------- -- -- SNS Messages data SnsMessage = SnsMessage { snsMessageDefault :: !T.Text , snsMessageMap :: !(M.Map SnsProtocol T.Text) } deriving (Show, Read, Eq, Ord, Typeable) snsMessageParameters :: SnsMessage -> (Method, HTTP.QueryText) snsMessageParameters SnsMessage{..} = if M.null snsMessageMap then (Get,) [ ("Message", Just snsMessageDefault) ] else (PostQuery,) [ ("MessageStructure", Just "json") , ("Message", (Just . T.decodeUtf8 . LB.toStrict) msg) ] where msg = encode . M.insert "default" snsMessageDefault . M.mapKeys (toText :: SnsProtocol -> String) $ snsMessageMap snsMessage :: T.Text -> SnsMessage snsMessage t = SnsMessage t M.empty -- | Unique identifier assigned to a published message. -- -- Length Constraint: Maximum 100 characters -- newtype MessageId = MessageId { messageIdText :: T.Text } deriving (Show, Read, Eq, Ord, Monoid, IsString, Typeable, FromJSON, ToJSON) -- -------------------------------------------------------------------------- -- -- SQS Notification Message -- | The format of messages used with 'SnsProtocolSqs' -- -- The format is described informally at -- -- <http://docs.aws.amazon.com/sns/latest/dg/SendMessageToSQS.html> -- data SqsNotification = SqsNotification { sqsNotificationMessageId :: !MessageId , sqsNotificationTopicArn :: !Arn , sqsNotificationSubject :: !(Maybe T.Text) , sqsNotificationMessage :: !T.Text , sqsNotificationTimestamp :: !UTCTime , sqsNotificationSignatureVersion :: !T.Text , sqsNotificationSignature :: !T.Text , sqsNotificationSigningCertURL :: !T.Text , sqsNotificationUnsubscribeURL :: !T.Text } deriving (Show, Read, Eq, Ord, Typeable) instance FromJSON SqsNotification where parseJSON = withObject "SqsNotification" $ \o -> SqsNotification <$> o .: "MessageId" <*> o .: "TopicArn" <*> o .: "Subject" <*> o .: "Message" <*> o .: "Timestamp" <*> o .: "SignatureVersion" <*> o .: "Signature" <*> o .: "SigningCertURL" <*> o .: "UnsubscribeURL" <* (o .: "Type" >>= expectValue ("Notification" :: T.Text)) -- -------------------------------------------------------------------------- -- -- Publish data Publish = Publish { publishMessage :: !SnsMessage -- ^ The message you want to send to the topic. -- -- If you want to send the same message to all transport protocols, include -- the text of the message as a String value. -- -- If you want to send different messages for each transport protocol add -- these to the 'snsMessageMap' map. -- -- Constraints: Messages must be UTF-8 encoded strings at most 256 KB in -- size (262144 bytes, not 262144 characters). -- , publishMessageAttributes_entry_N :: Maybe () -- TODO what's that? -- ^ Message attributes for Publish action. , publishSubject :: !(Maybe T.Text) -- ^ Optional parameter to be used as the "Subject" line when the message -- is delivered to email endpoints. This field will also be included, if -- present, in the standard JSON messages delivered to other endpoints. -- -- Constraints: Subjects must be ASCII text that begins with a letter, -- number, or punctuation mark; must not include line breaks or control -- characters; and must be less than 100 characters long. -- , publishArn :: !(Either Arn Arn) -- ^ Either TopicArn (left) or EndpointArn (right). } deriving (Show, Read, Eq, Ord, Typeable) data PublishResponse = PublishResponse { publishMessageId :: !MessageId -- ^ Unique identifier assigned to the published message. } deriving (Show, Read, Eq, Ord, Typeable) instance ResponseConsumer r PublishResponse where type ResponseMetadata PublishResponse = SnsMetadata responseConsumer _ = snsXmlResponseConsumer p where p el = PublishResponse . MessageId <$> arn el arn el = force "Missing Message Id" $ el $// CU.laxElement "PublishResult" &/ CU.laxElement "MessageId" &/ CU.content instance SignQuery Publish where type ServiceConfiguration Publish = SnsConfiguration signQuery Publish{..} = snsSignQuery SnsQuery { snsQueryMethod = method , snsQueryAction = publishAction , snsQueryParameters = msgQuery <> subject <> arn <> entry , snsQueryBody = Nothing } where (method, msgQuery) = snsMessageParameters publishMessage subject = maybe [] (\x -> [("Subject", Just x)]) publishSubject arn = case publishArn of Left a -> [("TopicArn", Just $ toText a)] Right a -> [("TargetArn", Just $ toText a)] entry = [] -- TODO instance Transaction Publish PublishResponse instance AsMemoryResponse PublishResponse where type MemoryResponse PublishResponse = PublishResponse loadToMemory = return -- -------------------------------------------------------------------------- -- -- Errors -- -- Currently not used for requests. It's included for future usage -- and as reference. data PublishErrors = PublishAuthorizationError -- ^ Indicates that the user has been denied access to the requested resource. -- -- /Code 403/ | PublishInternalError -- ^ Indicates an internal service error. -- -- /Code 500/ | PublishInvalidParameter -- ^ Indicates that a request parameter does not comply with the associated constraints. -- -- /Code 400/ | PublishEndpointDisabled -- ^ Exception error indicating endpoint disabled. -- -- /Code 400/ | PublishInvalidParameterValue -- ^ Indicates that a request parameter does not comply with the associated constraints. -- -- /Code 400/ | PublishNotFound -- ^ Indicates that the requested resource does not exist. -- -- /Code 404/ | PublishApplicationDisabled -- ^ Exception error indicating platform application disabled. -- -- /Code 400/ deriving (Show, Read, Eq, Ord, Enum, Bounded, Typeable)
ababkin/hs-aws-sns
src/Aws/Sns/Commands/Publish.hs
mit
8,243
0
26
1,724
1,323
787
536
150
2
{-# LANGUAGE TemplateHaskell, FlexibleInstances, DeriveDataTypeable, ViewPatterns #-} {-# OPTIONS_GHC -fno-warn-incomplete-patterns #-} -- spurious warnings for view patterns -- | -- Copyright : (c) 2011-2012 Benedikt Schmidt -- License : GPL v3 (see LICENSE) -- -- Maintainer : Benedikt Schmidt <beschmi@gmail.com> -- -- Subterm rewriting rules. module Term.SubtermRule ( StRhs(..) , StRule(..) , rRuleToStRule , stRuleToRRule -- * Pretty Printing , prettyStRule , module Term.Rewriting.Definitions ) where import Control.DeepSeq import Data.DeriveTH import Data.Binary import Term.LTerm import Term.Positions import Term.Rewriting.Definitions import Text.PrettyPrint.Highlight -- | The righthand-side of a subterm rewrite rule. -- Does not enforce that the term for RhsGround must be ground. data StRhs = RhsGround LNTerm | RhsPosition Position deriving (Show,Ord,Eq) -- | A subterm rewrite rule. data StRule = StRule LNTerm StRhs deriving (Show,Ord,Eq) -- | Convert a rewrite rule to a subterm rewrite rule if possible. rRuleToStRule :: RRule LNTerm -> Maybe StRule rRuleToStRule (lhs `RRule` rhs) | frees rhs == [] = Just $ StRule lhs (RhsGround rhs) | otherwise = case findSubterm lhs [] of []:_ -> Nothing -- proper subterm required pos:_ -> Just $ StRule lhs (RhsPosition (reverse pos)) [] -> Nothing where findSubterm t rpos | t == rhs = [rpos] findSubterm (viewTerm -> FApp _ args) rpos = concat $ zipWith (\t i -> findSubterm t (i:rpos)) args [0..] findSubterm (viewTerm -> Lit _) _ = [] -- | Convert a subterm rewrite rule to a rewrite rule. stRuleToRRule :: StRule -> RRule LNTerm stRuleToRRule (StRule lhs rhs) = case rhs of RhsGround t -> lhs `RRule` t RhsPosition p -> lhs `RRule` (lhs `atPos` p) ------------------------------------------------------------------------------ -- Pretty Printing ------------------------------------------------------------------------------ -- | Pretty print an 'StRule' prettyStRule :: HighlightDocument d => StRule -> d prettyStRule r = case stRuleToRRule r of (lhs `RRule` rhs) -> sep [ nest 2 $ prettyLNTerm lhs , operator_ "=" <-> prettyLNTerm rhs ] -- derived instances -------------------- $(derive makeBinary ''StRhs) $(derive makeBinary ''StRule) $(derive makeNFData ''StRhs) $(derive makeNFData ''StRule)
ekr/tamarin-prover
lib/term/src/Term/SubtermRule.hs
gpl-3.0
2,563
0
14
624
593
318
275
43
5
{-# 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.EC2.DescribeVPCPeeringConnections -- 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) -- -- Describes one or more of your VPC peering connections. -- -- /See:/ <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeVPCPeeringConnections.html AWS API Reference> for DescribeVPCPeeringConnections. module Network.AWS.EC2.DescribeVPCPeeringConnections ( -- * Creating a Request describeVPCPeeringConnections , DescribeVPCPeeringConnections -- * Request Lenses , dvpcpcFilters , dvpcpcVPCPeeringConnectionIds , dvpcpcDryRun -- * Destructuring the Response , describeVPCPeeringConnectionsResponse , DescribeVPCPeeringConnectionsResponse -- * Response Lenses , dvpcpcrsVPCPeeringConnections , dvpcpcrsResponseStatus ) where import Network.AWS.EC2.Types import Network.AWS.EC2.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'describeVPCPeeringConnections' smart constructor. data DescribeVPCPeeringConnections = DescribeVPCPeeringConnections' { _dvpcpcFilters :: !(Maybe [Filter]) , _dvpcpcVPCPeeringConnectionIds :: !(Maybe [Text]) , _dvpcpcDryRun :: !(Maybe Bool) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DescribeVPCPeeringConnections' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dvpcpcFilters' -- -- * 'dvpcpcVPCPeeringConnectionIds' -- -- * 'dvpcpcDryRun' describeVPCPeeringConnections :: DescribeVPCPeeringConnections describeVPCPeeringConnections = DescribeVPCPeeringConnections' { _dvpcpcFilters = Nothing , _dvpcpcVPCPeeringConnectionIds = Nothing , _dvpcpcDryRun = Nothing } -- | One or more filters. -- -- - 'accepter-vpc-info.cidr-block' - The CIDR block of the peer VPC. -- -- - 'accepter-vpc-info.owner-id' - The AWS account ID of the owner of -- the peer VPC. -- -- - 'accepter-vpc-info.vpc-id' - The ID of the peer VPC. -- -- - 'expiration-time' - The expiration date and time for the VPC peering -- connection. -- -- - 'requester-vpc-info.cidr-block' - The CIDR block of the requester\'s -- VPC. -- -- - 'requester-vpc-info.owner-id' - The AWS account ID of the owner of -- the requester VPC. -- -- - 'requester-vpc-info.vpc-id' - The ID of the requester VPC. -- -- - 'status-code' - The status of the VPC peering connection -- ('pending-acceptance' | 'failed' | 'expired' | 'provisioning' | -- 'active' | 'deleted' | 'rejected'). -- -- - 'status-message' - A message that provides more information about -- the status of the VPC peering connection, if applicable. -- -- - 'tag':/key/=/value/ - The key\/value combination of a tag assigned -- to the resource. -- -- - 'tag-key' - The key of a tag assigned to the resource. This filter -- is independent of the 'tag-value' filter. For example, if you use -- both the filter \"tag-key=Purpose\" and the filter \"tag-value=X\", -- you get any resources assigned both the tag key Purpose (regardless -- of what the tag\'s value is), and the tag value X (regardless of -- what the tag\'s key is). If you want to list only resources where -- Purpose is X, see the 'tag':/key/=/value/ filter. -- -- - 'tag-value' - The value of a tag assigned to the resource. This -- filter is independent of the 'tag-key' filter. -- -- - 'vpc-peering-connection-id' - The ID of the VPC peering connection. -- dvpcpcFilters :: Lens' DescribeVPCPeeringConnections [Filter] dvpcpcFilters = lens _dvpcpcFilters (\ s a -> s{_dvpcpcFilters = a}) . _Default . _Coerce; -- | One or more VPC peering connection IDs. -- -- Default: Describes all your VPC peering connections. dvpcpcVPCPeeringConnectionIds :: Lens' DescribeVPCPeeringConnections [Text] dvpcpcVPCPeeringConnectionIds = lens _dvpcpcVPCPeeringConnectionIds (\ s a -> s{_dvpcpcVPCPeeringConnectionIds = a}) . _Default . _Coerce; -- | Checks whether you have the required permissions for the action, without -- actually making the request, and provides an error response. If you have -- the required permissions, the error response is 'DryRunOperation'. -- Otherwise, it is 'UnauthorizedOperation'. dvpcpcDryRun :: Lens' DescribeVPCPeeringConnections (Maybe Bool) dvpcpcDryRun = lens _dvpcpcDryRun (\ s a -> s{_dvpcpcDryRun = a}); instance AWSRequest DescribeVPCPeeringConnections where type Rs DescribeVPCPeeringConnections = DescribeVPCPeeringConnectionsResponse request = postQuery eC2 response = receiveXML (\ s h x -> DescribeVPCPeeringConnectionsResponse' <$> (x .@? "vpcPeeringConnectionSet" .!@ mempty >>= may (parseXMLList "item")) <*> (pure (fromEnum s))) instance ToHeaders DescribeVPCPeeringConnections where toHeaders = const mempty instance ToPath DescribeVPCPeeringConnections where toPath = const "/" instance ToQuery DescribeVPCPeeringConnections where toQuery DescribeVPCPeeringConnections'{..} = mconcat ["Action" =: ("DescribeVpcPeeringConnections" :: ByteString), "Version" =: ("2015-04-15" :: ByteString), toQuery (toQueryList "Filter" <$> _dvpcpcFilters), toQuery (toQueryList "VpcPeeringConnectionId" <$> _dvpcpcVPCPeeringConnectionIds), "DryRun" =: _dvpcpcDryRun] -- | /See:/ 'describeVPCPeeringConnectionsResponse' smart constructor. data DescribeVPCPeeringConnectionsResponse = DescribeVPCPeeringConnectionsResponse' { _dvpcpcrsVPCPeeringConnections :: !(Maybe [VPCPeeringConnection]) , _dvpcpcrsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DescribeVPCPeeringConnectionsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dvpcpcrsVPCPeeringConnections' -- -- * 'dvpcpcrsResponseStatus' describeVPCPeeringConnectionsResponse :: Int -- ^ 'dvpcpcrsResponseStatus' -> DescribeVPCPeeringConnectionsResponse describeVPCPeeringConnectionsResponse pResponseStatus_ = DescribeVPCPeeringConnectionsResponse' { _dvpcpcrsVPCPeeringConnections = Nothing , _dvpcpcrsResponseStatus = pResponseStatus_ } -- | Information about the VPC peering connections. dvpcpcrsVPCPeeringConnections :: Lens' DescribeVPCPeeringConnectionsResponse [VPCPeeringConnection] dvpcpcrsVPCPeeringConnections = lens _dvpcpcrsVPCPeeringConnections (\ s a -> s{_dvpcpcrsVPCPeeringConnections = a}) . _Default . _Coerce; -- | The response status code. dvpcpcrsResponseStatus :: Lens' DescribeVPCPeeringConnectionsResponse Int dvpcpcrsResponseStatus = lens _dvpcpcrsResponseStatus (\ s a -> s{_dvpcpcrsResponseStatus = a});
olorin/amazonka
amazonka-ec2/gen/Network/AWS/EC2/DescribeVPCPeeringConnections.hs
mpl-2.0
7,693
0
15
1,539
811
497
314
93
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.EC2.AssociateDHCPOptions -- 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) -- -- Associates a set of DHCP options (that you\'ve previously created) with -- the specified VPC, or associates no DHCP options with the VPC. -- -- After you associate the options with the VPC, any existing instances and -- all new instances that you launch in that VPC use the options. You -- don\'t need to restart or relaunch the instances. They automatically -- pick up the changes within a few hours, depending on how frequently the -- instance renews its DHCP lease. You can explicitly renew the lease using -- the operating system on the instance. -- -- For more information, see -- <http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_DHCP_Options.html DHCP Options Sets> -- in the /Amazon Virtual Private Cloud User Guide/. -- -- /See:/ <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-AssociateDHCPOptions.html AWS API Reference> for AssociateDHCPOptions. module Network.AWS.EC2.AssociateDHCPOptions ( -- * Creating a Request associateDHCPOptions , AssociateDHCPOptions -- * Request Lenses , adoDryRun , adoDHCPOptionsId , adoVPCId -- * Destructuring the Response , associateDHCPOptionsResponse , AssociateDHCPOptionsResponse ) where import Network.AWS.EC2.Types import Network.AWS.EC2.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'associateDHCPOptions' smart constructor. data AssociateDHCPOptions = AssociateDHCPOptions' { _adoDryRun :: !(Maybe Bool) , _adoDHCPOptionsId :: !Text , _adoVPCId :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'AssociateDHCPOptions' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'adoDryRun' -- -- * 'adoDHCPOptionsId' -- -- * 'adoVPCId' associateDHCPOptions :: Text -- ^ 'adoDHCPOptionsId' -> Text -- ^ 'adoVPCId' -> AssociateDHCPOptions associateDHCPOptions pDHCPOptionsId_ pVPCId_ = AssociateDHCPOptions' { _adoDryRun = Nothing , _adoDHCPOptionsId = pDHCPOptionsId_ , _adoVPCId = pVPCId_ } -- | Checks whether you have the required permissions for the action, without -- actually making the request, and provides an error response. If you have -- the required permissions, the error response is 'DryRunOperation'. -- Otherwise, it is 'UnauthorizedOperation'. adoDryRun :: Lens' AssociateDHCPOptions (Maybe Bool) adoDryRun = lens _adoDryRun (\ s a -> s{_adoDryRun = a}); -- | The ID of the DHCP options set, or 'default' to associate no DHCP -- options with the VPC. adoDHCPOptionsId :: Lens' AssociateDHCPOptions Text adoDHCPOptionsId = lens _adoDHCPOptionsId (\ s a -> s{_adoDHCPOptionsId = a}); -- | The ID of the VPC. adoVPCId :: Lens' AssociateDHCPOptions Text adoVPCId = lens _adoVPCId (\ s a -> s{_adoVPCId = a}); instance AWSRequest AssociateDHCPOptions where type Rs AssociateDHCPOptions = AssociateDHCPOptionsResponse request = postQuery eC2 response = receiveNull AssociateDHCPOptionsResponse' instance ToHeaders AssociateDHCPOptions where toHeaders = const mempty instance ToPath AssociateDHCPOptions where toPath = const "/" instance ToQuery AssociateDHCPOptions where toQuery AssociateDHCPOptions'{..} = mconcat ["Action" =: ("AssociateDhcpOptions" :: ByteString), "Version" =: ("2015-04-15" :: ByteString), "DryRun" =: _adoDryRun, "DhcpOptionsId" =: _adoDHCPOptionsId, "VpcId" =: _adoVPCId] -- | /See:/ 'associateDHCPOptionsResponse' smart constructor. data AssociateDHCPOptionsResponse = AssociateDHCPOptionsResponse' deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'AssociateDHCPOptionsResponse' with the minimum fields required to make a request. -- associateDHCPOptionsResponse :: AssociateDHCPOptionsResponse associateDHCPOptionsResponse = AssociateDHCPOptionsResponse'
olorin/amazonka
amazonka-ec2/gen/Network/AWS/EC2/AssociateDHCPOptions.hs
mpl-2.0
4,776
0
11
925
531
326
205
71
1
import Sprockell prog :: [Instruction] prog = [ Branch regSprID (Rel 6) -- target "beginLoop" , Load (ImmValue 13) regC , WriteInstr regC (DirAddr 1) -- Sprockell 1 must jump to second EndProg , WriteInstr regC (DirAddr 2) -- Sprockell 2 must jump to second EndProg , WriteInstr regC (DirAddr 3) -- Sprockell 3 must jump to second EndProg , Jump (Abs 12) -- Sprockell 0 jumps to first EndProg -- beginLoop , ReadInstr (IndAddr regSprID) , Receive regA , Compute Equal regA reg0 regB , Branch regB (Rel (-3)) -- endLoop , WriteInstr regA numberIO , Jump (Ind regA) -- 12: Sprockell 0 is sent here , EndProg -- 13: Sprockells 1, 2 and 3 are sent here , EndProg ] main = runWithDebugger (debuggerSimplePrintAndWait myShow) [prog,prog,prog,prog]
wouwouwou/2017_module_8
src/haskell/PP-project-2017/lib/sprockell-2017/src/DemoMultipleSprockells.hs
apache-2.0
935
0
10
321
211
115
96
18
1
module GoToSymbolFunction_BehaveWhenCaretOutsideAFunction where <caret> test :: IO Int test = do seven <- return 7 return $ seven + 1
charleso/intellij-haskforce
tests/gold/codeInsight/GoToSymbolFunction_BehaveWhenCaretOutsideAFunction.hs
apache-2.0
137
3
8
23
47
22
25
-1
-1
module Main where import Data.Monoid import Options.Applicative import Server -- | Argument line options data Options = Options { -- | Path to config, if not set, the app will not start configPath :: FilePath } -- | Command line parser optionsParser :: Parser Options optionsParser = Options <$> strOption ( long "conf" <> metavar "CONFIG" <> help "Path to configuration file" ) -- | Execute server with given options runServer :: Options -> IO () runServer Options{..} = do cfg <- readConfig configPath runExampleServer cfg main :: IO () main = execParser opts >>= runServer where opts = info (helper <*> optionsParser) ( fullDesc <> progDesc "Example server for servant-auth-token" <> header "servant-auth-token-example-persistent - example of integration of servant token auth library" )
NCrashed/servant-auth-token
example/persistent/src/Main.hs
bsd-3-clause
854
0
11
187
178
92
86
-1
-1
{-# LANGUAGE FlexibleInstances #-} module Cooper where {- This file is based upon an implementation of a Pressburger arithmetic solver written by John Harrison in OCaml which was copyright (c) 2003. It was translated to Haskell by Tim Sheard in 2006. As a derivative of that work, it is subject to the following License in addition to the general Omega license. -------------------------------------------------------------------- IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. By downloading, copying, installing or using the software you agree to this license. If you do not agree to this license, do not download, install, copy or use the software. Copyright (c) 2003, John Harrison All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The name of John Harrison may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} import Data.Char(isDigit) import Data.List(sortBy,nub) import Auxillary(plist,plistf,DispElem(..)) import RankN(Tau(..),Pred(..),warnM,TcTv) import Monads(fio,fio2Mtc) -- To import ParserAll you must define CommentDef.hs and TokenDef.hs -- These should be in the same directory as this file. import ParserAll(symbol,try,identifier,integer,comma,reserved ,parens, sepBy, (<?>), (<|>),parse,parse2,chainl1,many1) ------------------------------------------------ -- from fol.ml data Term = Var String | Fn (String,[Term]) deriving (Eq,Ord) data Fol = R (String,[Term]) deriving Eq {- There is a bug in this somewhere instance Ord Term where (Var _) < (Fn _) = True (Var s) < (Var y) = s<y (Fn _) < (Var _) = False (Fn(f,xs)) < (Fn(g,ys)) = case compare f g of EQ -> xs < ys LT -> True GT -> False Right(u1,_) = parse2 term "(-1 * z659 + 1 * z605 + 1 * z589 + 1 * z507 + -1)" Right(u2,_) = parse2 term "(-1 * z659 + 1 * z605 + 1 * z589 + 1 * z507 + 0)" -- goes into infinite loop, but if I derive Ord for Term we're OK testu = union [u1] [u2] -} fvt (Var x) = [x] fvt (Fn(f,args)) = itlist (union . fvt) args [] fv fm = case fm of FalseF -> [] TrueF -> [] Atom(R(p,args)) -> itlist (union . fvt) args [] Not(p) -> fv p And(p,q) -> union (fv p) (fv q) Or(p,q) -> union (fv p) (fv q) Imp(p,q) -> union (fv p) (fv q) Iff(p,q) -> union (fv p) (fv q) Forall(x,p) -> subtractSet (fv p) [x] Exists(x,p) -> subtractSet (fv p) [x] ------------------------------------------------ -- from lib.ml earlier :: Eq a => [a] -> a -> a -> Bool earlier [] x y = False earlier (h:t) x y = if h == y then False else if h == x then True else earlier t x y -- Handy list operations. -- n (--) m = [n .. m] -- Merging of sorted lists (maintaining repetitions). merge ord l1 l2 = case l1 of [] -> l2 h1:t1 -> case l2 of [] -> l1 h2:t2 -> if ord h1 h2 then h1:(merge ord t1 l2) else h2:(merge ord l1 t2) -- Bottom-up mergesort. sort ord l = if null l then [] else mergepairs [] (map (\ x -> [x]) l) where mergepairs l1 l2 = case (l1,l2) of ([s],[]) -> s (l,[]) -> mergepairs [] l (l,[s1]) -> mergepairs (s1:l) [] (l,(s1:s2:ss)) -> mergepairs ((merge ord s1 s2):l) ss -- Set operations on ordered lists. setify l = if canonical l then l else nub (sort (<=) l) where canonical (x: rest@(y: _)) = x<y && canonical rest canonical _ = True union s1 s2 = union (setify s1) (setify s2) where union l1 l2 = case (l1,l2) of ([],l2) -> l2 (l1,[]) -> l1 (l1@(h1:t1),l2@(h2:t2)) -> if h1 == h2 then h1:(union t1 t2) else if h1 < h2 then h1:(union t1 l2) else h2:(union l1 t2) subtractSet s1 s2 = sub (setify s1) (setify s2) where sub l1 l2 = case (l1,l2) of ([],l2) -> [] (l1,[]) -> l1 (l1@(h1:t1),l2@(h2:t2)) -> if h1 == h2 then sub t1 t2 else if h1 < h2 then h1:(sub t1 l2) else sub l1 t2 end_itlist :: Monad m => (b -> b -> b) -> [b] -> m b end_itlist f l = case l of [] -> fail "end_itlist" [x] -> return x (h:t) -> do { yy <- end_itlist f t; return(f h yy)} itlist :: (a -> b -> b) -> [a] -> b -> b itlist f [] b = b itlist f (h:t) b = f h (itlist f t b) partition :: (a -> Bool) -> [a] -> ([a],[a]) partition p l = itlist (\ a (yes,no) -> if p a then (a:yes,no) else (yes,a:no)) l ([],[]) ------------------------------------------------ -- from skolem.ml -- Routine simplification. Like "psimplify" but with quantifier clauses. simplify1 fm = case fm of Forall(x,p) -> if elem x (fv p) then fm else p Exists(x,p) -> if elem x (fv p) then fm else p _ -> psimplify1 fm simplify :: Formula Fol -> Formula Fol simplify fm = case fm of Not p -> simplify1 (Not(simplify p)) And(p,q) -> simplify1 (And(simplify p,simplify q)) Or(p,q) -> simplify1 (Or(simplify p,simplify q)) Imp(p,q) -> simplify1 (Imp(simplify p,simplify q)) Iff(p,q) -> simplify1 (Iff(simplify p,simplify q)) Forall(x,p) -> simplify1(Forall(x,simplify p)) Exists(x,p) -> simplify1(Exists(x,simplify p)) _ -> fm cnnf :: (Formula Fol -> Formula Fol) -> Formula Fol -> Formula Fol cnnf lfn term = (simplify . help . simplify) term where help fm = case fm of And(p,q) -> And(help p,help q) Or(p,q) -> Or(help p,help q) Imp(p,q) -> Or(help(Not p),help q) Iff(p,q) -> Or(And(help p,help q),And(help(Not p),help(Not q))) Not(Not p) -> help p Not(And(p,q)) -> Or(help(Not p),help(Not q)) Not(Or(And(p,q),And(p',r))) | p' == negateF p -> Or(help (And(p,Not q)),help (And(p',Not r))) Not(Or(p,q)) -> And(help(Not p),help(Not q)) Not(Imp(p,q)) -> And(help p,help(Not q)) Not(Iff(p,q)) -> Or(And(help p,help(Not q)), And(help(Not p),help q)) _ -> lfn fm cnnfM :: Monad m => (Formula Fol -> m(Formula Fol)) -> Formula Fol -> m(Formula Fol) cnnfM lfn term = do { x1 <- help(simplify term); return(simplify x1)} where help fm = case fm of And(p,q) -> andM(help p,help q) Or(p,q) -> orM(help p,help q) Imp(p,q) -> orM(help(Not p),help q) Iff(p,q) -> orM(andM(help p,help q), andM(help(Not p),help(Not q))) Not(Not p) -> help p Not(And(p,q)) -> orM(help(Not p),help(Not q)) Not(Or(And(p,q),And(p',r))) | p' == negateF p -> orM(help (And(p,Not q)),help (And(p',Not r))) Not(Or(p,q)) -> andM(help(Not p),help(Not q)) Not(Imp(p,q)) -> andM(help p,help(Not q)) Not(Iff(p,q)) -> orM(andM(help p,help(Not q)), andM(help(Not p),help q)) _ -> lfn fm ------------------------------------------------ -- from formulas.ml data Formula a = FalseF | TrueF | Atom a | Not (Formula a) | And (Formula a,Formula a) | Or (Formula a,Formula a) | Imp (Formula a,Formula a) | Iff (Formula a,Formula a) | Forall (String,Formula a) | Exists (String,Formula a) deriving Eq andM (x,y) = lift2 And (x,y) orM (x,y) = lift2 Or (x,y) notM x = lift1 Not x impM x = lift2 Imp x iffM x = lift2 Iff x onAtoms fn fm = case fm of Atom(a) -> fn a Not(p) -> Not(onAtoms fn p) And(p,q) -> And(onAtoms fn p,onAtoms fn q) Or(p,q) -> Or(onAtoms fn p,onAtoms fn q) Imp(p,q) -> Imp(onAtoms fn p,onAtoms fn q) Iff(p,q) -> Iff(onAtoms fn p,onAtoms fn q) Forall(x,p) -> Forall(x,onAtoms fn p) Exists(x,p) -> Exists(x,onAtoms fn p) _ -> fm onAtomsM fn fm = case fm of Atom(a) -> fn a Not(p) -> lift1 Not(onAtomsM fn p) And(p,q) -> lift2 And(onAtomsM fn p,onAtomsM fn q) Or(p,q) -> lift2 Or(onAtomsM fn p,onAtomsM fn q) Imp(p,q) -> lift2 Imp(onAtomsM fn p,onAtomsM fn q) Iff(p,q) -> lift2 Iff(onAtomsM fn p,onAtomsM fn q) Forall(x,p) -> lift2 Forall(return x,onAtomsM fn p) Exists(x,p) -> lift2 Exists(return x,onAtomsM fn p) _ -> return fm ------------------------------------------------ -- from prop.ml -- Disjunctive normal form (DNF) via truth tables. list_conj :: [Formula a] -> Formula a list_conj [] = TrueF list_conj [x] = x list_conj (x: xs@(_:_)) = And(x,list_conj xs) list_disj :: [Formula a] -> Formula a list_disj [] = FalseF list_disj [x] = x list_disj (x: xs@(_:_)) = Or(x,list_disj xs) --list_disj [] = return FalseF --list_disj l = end_itlist (\ p q -> Or(p,q)) l negateF (Not p) = p negateF p = Not p -- Routine simplification. psimplify1 fm = case fm of Not FalseF -> TrueF Not TrueF -> FalseF And(FalseF,q) -> FalseF And(p,FalseF) -> FalseF And(TrueF,q) -> q And(p,TrueF) -> p Or(FalseF,q) -> q Or(p,FalseF) -> p Or(TrueF,q) -> TrueF Or(p,TrueF) -> TrueF Imp(FalseF,q) -> TrueF Imp(TrueF,q) -> q Imp(p,TrueF) -> TrueF Imp(p,FalseF) -> Not p Iff(TrueF,q) -> q Iff(p,TrueF) -> p Iff(FalseF,q) -> Not q Iff(p,FalseF) -> Not p _ -> fm psimplify fm = case fm of Not p -> psimplify1 (Not(psimplify p)) And(p,q) -> psimplify1 (And(psimplify p,psimplify q)) Or(p,q) -> psimplify1 (Or(psimplify p,psimplify q)) Imp(p,q) -> psimplify1 (Imp(psimplify p,psimplify q)) Iff(p,q) -> psimplify1 (Iff(psimplify p,psimplify q)) _ -> fm ------------------------------------------------ -- from cooper.ml -- Lift operations up to numerals. mk_numeral:: Int -> Term mk_numeral n = Fn(show n,[]) dest_numeral:: Monad m => Int -> Term -> m Int dest_numeral n t@(Fn(ns,[])) = if is_numeral t then return (read ns) else fail (show n ++" dest_numeral "++show t) dest_numeral n t = fail (show n ++" dest_numeral "++ show t) is_numeral:: Term -> Bool is_numeral (Fn('-':ns,[])) = all isDigit ns is_numeral (Fn(ns,[])) = all isDigit ns is_numeral _ = False numeral1 :: Monad m => (Int -> Int) -> Term -> m Term numeral1 fn n = do { m <- dest_numeral 1 n; return(mk_numeral (fn m))} numeral2 :: Monad m => (Int -> Int -> Int) -> Term -> Term -> m Term numeral2 fn m n = do { a <- dest_numeral 2 m ; b <- dest_numeral 3 n ; return(mk_numeral (fn a b))} -- ------------------------------- -- Operations on canonical linear terms c1 * x1 + ... + cn * xn + k *) -- Note that we're quite strict: the ci must be present even if 1 *) -- (but if 0 we expect the monomial to be omitted) and k must be there *) -- even if it's zero. Thus, it's a constant iff not an addition term. -- ------------------------------ linear_cmul :: Monad m => Int -> Term -> m Term linear_cmul 0 tm = return(Fn("0",[])) linear_cmul n (Fn("+",[Fn("*",[c1,x1]),rest])) = do { zzz <- numeral1 (* n) c1 ; yyy <- linear_cmul n rest ; return(Fn("+",[Fn("*",[zzz, x1]),yyy]))} linear_cmul n k = numeral1 (* n) k earlierv :: [String] -> Term -> Term -> Bool earlierv vars (Var x) (Var y) = earlier vars x y linear_add :: Monad m => [String] -> Term -> Term -> m Term linear_add vars tm1@(Fn("+",[Fn("*",[c1, x1]), rest1])) tm2@(Fn("+",[Fn("*",[c2, x2]), rest2])) = do { c <- numeral2 (+) c1 c2 ; if x1 == x2 then do { tail <- linear_add vars rest1 rest2 ; case c of Fn("0",[]) -> return tail c -> return(Fn("+",[Fn("*",[c, x1]), tail]))} else if earlierv vars x1 x2 then do { tail <- linear_add vars rest1 tm2 ; return(Fn("+",[Fn("*",[c1, x1]), tail]))} else do { tail <- linear_add vars tm1 rest2 ; return(Fn("+",[Fn("*",[c2, x2]), tail]))}} linear_add vars tm1@(Fn("+",[Fn("*",[c1, x1]), rest1])) tm2 = do { tail <- linear_add vars rest1 tm2 ; return( Fn("+",[Fn("*",[c1, x1]), tail]))} linear_add vars tm1 tm2@(Fn("+",[Fn("*",[c2, x2]), rest2])) = do { tail <- linear_add vars tm1 rest2 ; return( Fn("+",[Fn("*",[c2, x2]), tail]) )} linear_add vars tm1 tm2 = numeral2 (+) tm1 tm2 linear_neg :: Monad m => Term -> m Term linear_neg tm = linear_cmul (-1) tm linear_sub :: Monad m => [String] -> Term -> Term -> m Term linear_sub vars tm1 tm2 = do { tm2' <- linear_neg tm2 ; linear_add vars tm1 tm2'} ------------------------------- -- Linearize a term. ------------------------------- lint :: Monad m => [String] -> Term -> m Term lint vars tm@(Var x) = return (Fn("+",[Fn("*",[Fn("1",[]), tm]), Fn("0",[])])) lint vars (Fn("-",[t])) = do { t2 <- (lint vars t); linear_neg t2} lint vars (Fn("+",[s,t])) = do { s' <- lint vars s; t' <- lint vars t; linear_add vars s' t'} lint vars (Fn("-",[s,t])) = do { s' <- lint vars s; t' <- lint vars t; linear_sub vars s' t'} lint vars (Fn("*",[s,t])) = do { s' <- lint vars s ; t' <- lint vars t ; if is_numeral s' then do { c <- dest_numeral 4 s'; linear_cmul c t'} else if is_numeral t' then do { c <- dest_numeral 5 t'; linear_cmul c s'} else fail "lint: apparent nonlinearity"} lint vars tm = if is_numeral tm then return tm else fail "lint: unknown term" ------------------------------------------------------------------------- -- Linearize the atoms in a formula, and eliminate non-strict inequalities. ------------------------------------------------------------------------- mkatom vars p t = do { zz <- lint vars t; ; return (Atom(R(p,[Fn("0",[]),zz])))} linform :: Monad m => [String] -> Formula Fol -> m (Formula Fol) linform vars (Atom(R("divides",[c,t]))) = do { yy <- lint vars t ; c2 <- dest_numeral 6 c ; let c' = mk_numeral(abs c2) ; return( Atom(R("divides",[c', yy])) )} linform vars (Atom(R("=",[s,t]))) = mkatom vars "=" (Fn("-",[t,s])) linform vars (Atom(R("<",[s,t]))) = mkatom vars "<" (Fn("-",[t,s])) linform vars (Atom(R(">",[s,t]))) = mkatom vars "<" (Fn("-",[s,t])) linform vars (Atom(R("<=",[s,t]))) = mkatom vars "<" (Fn("-",[Fn("+",[t,Fn("1",[])]),s])) linform vars (Atom(R(">=",[s,t]))) = mkatom vars "<" (Fn("-",[Fn("+",[s,Fn("1",[])]),t])) linform vars fm = return fm -------------------------------------------------------------- -- Post-NNF transformation eliminating negated inequalities. -------------------------------------------------------------- posineq :: Monad m => Formula Fol -> m (Formula Fol) posineq fm@(Not(Atom(R("<",[Fn("0",[]), t])))) = do { zz <- linear_sub [] (Fn("1",[])) t ; return( Atom(R("<",[Fn("0",[]), zz])) )} posineq fm = return fm ------------------------------------------------- -- Find the LCM of the coefficients of x. ------------------------------------------------- formlcm :: Monad m => Term -> Formula Fol -> m Int formlcm x fm@(Atom(R(p,[_,Fn("+",[Fn("*",[c,y]),z])]))) | y == x = do { n <- dest_numeral 7 c; return (abs n)} formlcm x fm@(Not(p)) = formlcm x p formlcm x fm@(And(p,q)) = do { a <- formlcm x p; b <- formlcm x q; return(lcm a b)} formlcm x fm@(Or(p,q)) = do { a <- formlcm x p; b <- formlcm x q; return(lcm a b)} formlcm x fm = return 1 ------------------------------------------------------------------------ -- Adjust all coefficients of x in formula; fold in reduction to +/- 1. ------------------------------------------------------------------------ lift1 f x = do { a <- x; return(f a) } lift2 f (x,y) = do { a <- x; b <- y; return(f (a,b))} adjustcoeff :: Monad m => Term -> Int -> Formula Fol -> m (Formula Fol) adjustcoeff x l fm@(Atom(R(p,[d, Fn("+",[Fn("*",[c,y]),z])]))) | y == x = do { c1 <- dest_numeral 8 c ; let m = l `div` c1 n = if p == "<" then abs(m) else m xtm = Fn("*",[mk_numeral(m `div` n), x]) ; xx <- linear_cmul (abs m) d ; yy <- linear_cmul n z ; return( Atom(R(p,[xx,Fn("+",[xtm,yy])])) )} adjustcoeff x l fm@(Not(p)) = lift1 Not(adjustcoeff x l p) adjustcoeff x l fm@(And(p,q)) = lift2 And(adjustcoeff x l p,adjustcoeff x l q) adjustcoeff x l fm@(Or(p,q)) = lift2 Or(adjustcoeff x l p,adjustcoeff x l q) adjustcoeff x l fm = return fm ---------------------------------------------------------------- -- Hence make coefficient of x one in existential formula. ---------------------------------------------------------------- unitycoeff x fm = do { l <- formlcm x fm ; fm' <- adjustcoeff x l fm ; if l == 1 then return fm' else do { yy <- adjustcoeff x l fm ; let xp = Fn("+",[Fn("*",[Fn("1",[]),x]), Fn("0",[])]) ; return(And(Atom(R("divides",[mk_numeral l, xp])),yy)) }} -------------------------------- -- The "minus infinity" version. -------------------------------- minusinf x fm = case fm of Atom(R("=",[Fn("0",[]), Fn("+",[Fn("*",[Fn("1",[]),y]),z])])) | y == x -> FalseF Atom(R("<",[Fn("0",[]), Fn("+",[Fn("*",[pm1,y]),z])])) | y == x -> if pm1 == Fn("1",[]) then FalseF else TrueF Not(p) -> Not(minusinf x p) And(p,q) -> And(minusinf x p,minusinf x q) Or(p,q) -> Or(minusinf x p,minusinf x q) _ -> fm ---------------------------------------------- -- The LCM of all the divisors that involve x. ---------------------------------------------- -- a curried version of lift2 liftC f x y = do { a <- x; b <- y; return(f a b)} divlcm :: Monad m => Term -> Formula Fol -> m Int divlcm x fm = case fm of Atom(R("divides",[d,Fn("+",[Fn("*",[c,y]),z])])) | y == x -> dest_numeral 9 d Not(p) -> divlcm x p And(p,q) -> liftC lcm (divlcm x p) (divlcm x q) Or(p,q) -> liftC lcm (divlcm x p) (divlcm x q) _ -> return 1 ---------------------------- -- Construct the B-set. ---------------------------- one x = [x] bset x fm = case fm of Not(Atom(R("=",[Fn("0",[]), Fn("+",[Fn("*",[Fn("1",[]),y]),a])]))) | y==x -> do { ww <- (linear_neg a) ; return [ww]} Atom(R("=",[Fn("0",[]), Fn("+",[Fn("*",[Fn("1",[]),y]),a])])) | y==x -> do { yy <- linear_add [] a (Fn("1",[])) ; zz <- linear_neg(yy) ; return[zz]} Atom(R("<",[Fn("0",[]), Fn("+",[Fn("*",[Fn("1",[]),y]),a])])) | y==x -> lift1 one (linear_neg a) Not(p) -> bset x p And(p,q) -> do { ps <- (bset x p) ; qs <- (bset x q) ;return (union ps qs)} Or(p,q) -> liftC union (bset x p) (bset x q) _ -> return [] ------------------------------------------------------------------------- -- Replace top variable with another linear form, retaining canonicality. ------------------------------------------------------------------------- linrep vars x t fm = case fm of Atom(R(p,[d, Fn("+",[Fn("*",[c,y]),z])])) | y==x -> do { c1 <- dest_numeral 10 c ; ct <- linear_cmul c1 t ; yy <- linear_add vars ct z ; return(Atom(R(p,[d, yy])))} Not(p) -> lift1 Not(linrep vars x t p) And(p,q) -> lift2 And(linrep vars x t p,linrep vars x t q) Or(p,q) -> lift2 Or(linrep vars x t p,linrep vars x t q) _ -> return fm -------------------------------------------- -- Evaluation of constant expressions. -------------------------------------------- operations :: [(String,Int -> Int -> Bool)] operations = [("=",(==)), ("<",(<)), (">",(>)), ("<=",(<=)), (">=",(>=)), ("divides",\ x y -> mod y x == 0)] evalc_atom :: Fol -> Formula Fol evalc_atom at@(R(p,[s,t])) = case lookup p operations of Nothing -> Atom at Just f -> case (dest_numeral 11 s,dest_numeral 12 t) of (Just a, Just b) -> if (f a b) then TrueF else FalseF other -> Atom at evalc_atom at = (Atom at) evalc :: Formula Fol -> Formula Fol evalc x = onAtoms evalc_atom x; ----------------------------------------------------- -- Hence the core quantifier elimination procedure. ----------------------------------------------------- cooper vars fm@(Exists(x0,p0)) = do { let x = Var x0 ; p <- unitycoeff x p0 ; let p_inf = simplify(minusinf x p) ; bs <- bset x p ; nn <- divlcm x p ; let js = [1 .. nn] p_element j b = do { yy <- linear_add vars b (mk_numeral j) ; linrep vars x yy p} stage j = do { xx <- linrep vars x (mk_numeral j) p_inf ; ys <- mapM (p_element j) bs ; return(list_disj(xx:ys))} ; zs <- mapM stage js ; return(list_disj zs) } cooper vars fm = fail "cooper: not an existential formula" ---------------------- -- Overall function. ---------------------- -- integer_qelim :: Monad a => Formula Fol -> a (Formula Fol) integer_qelim term = do { let normform x = cnnfM posineq (evalc x) ; term1 <- linform (fv term) term ; term2 <- lift_qelimM linform normform cooper term1 ; return(simplify (evalc term2)) } --------------------------------------------------- -- from qelim.ml disjuncts (Or(p,q)) = disjuncts p ++ disjuncts q disjuncts x = [x] conjuncts (And(p,q)) = conjuncts p ++ conjuncts q conjuncts x = [x] -- Lift procedure given literal modifier, formula normalizer, and a basic -- elimination procedure for existential formulas with conjunctive body. lift_qelim :: ([String] -> Formula Fol -> Formula Fol) -> (Formula Fol -> Formula Fol) -> ([String] -> Formula Fol -> Formula Fol) -> Formula Fol -> Formula Fol lift_qelim afn nfn qfn fm = simplify(qelift (fv fm) fm) where qelift vars fm = case fm of Atom(R(_,_)) -> afn vars fm Not(p) -> Not(qelift vars p) And(p,q) -> And(qelift vars p,qelift vars q) Or(p,q) -> Or(qelift vars p,qelift vars q) Imp(p,q) -> Imp(qelift vars p,qelift vars q) Iff(p,q) -> Iff(qelift vars p,qelift vars q) Forall(x,p) -> Not(qelift vars (Exists(x,Not p))) Exists(x,p) -> let djs = disjuncts(nfn(qelift (x:vars) p)) in list_disj(map (qelim x vars) djs) _ -> fm qelim x vars p = let cjs = conjuncts p (ycjs,ncjs) = partition (elem x . fv) cjs in if null ycjs then p else let q = qfn vars (Exists(x,list_conj ycjs)) in foldr (\ p q -> And(p,q)) q ncjs -- A monadic version {- lift_qelimM :: Monad m => ([String] -> Formula Fol -> m(Formula Fol)) -> (Formula Fol -> m(Formula Fol)) -> ([String] -> Formula Fol -> m(Formula Fol)) -> Formula Fol -> m(Formula Fol) -} waitQ = putStrLn "return to continue" >> (getLine) lift_qelimM afn nfn qfn fm = do {x <- qelift (fv fm) fm ; return(simplify x)} where qelift vars fm = case fm of Atom(R(_,_)) -> afn vars fm Not(p) -> notM(qelift vars p) And(p,q) -> andM(qelift vars p,qelift vars q) Or(p,q) -> orM(qelift vars p,qelift vars q) Imp(p,q) -> impM(qelift vars p,qelift vars q) Iff(p,q) -> iffM(qelift vars p,qelift vars q) Forall(x,p) -> notM(qelift vars (Exists(x,Not p))) Exists(x,p) -> do { p1 <- qelift (x:vars) p ; p2 <- nfn p1 ; let djs = disjuncts p2 ; djs2 <- mapM (qelim x vars) djs ; return(list_disj djs2)} _ -> return fm qelim x vars p = let cjs = conjuncts p (ycjs,ncjs) = partition (elem x . fv) cjs in if null ycjs then return p else do { q <- qfn vars (Exists(x,list_conj ycjs)) ; return (foldr (\ p q -> And(p,q)) q ncjs)} ----------------------------------------------------------------- -- Parsing oneOf p [] = fail "oneOf" oneOf p (s:ss) = (try (p s)) <|> oneOf p ss --lit :: Parser Term lit = do {n <- integer; return(mk_numeral(fromInteger n))} --var:: Parser Term var = do { x <- identifier; return(Var x)} --factor:: Parser Term factor = lit <|> var <|> parens term --prod:: Parser Term prod = chainl1 factor (symbol "*" >> return times) where times x y = Fn("*",[x,y]) --term:: Parser Term term = chainl1 prod oper where op name x y = Fn(name,[x,y]) oper = do { x <- oneOf symbol ["+","-"] ; return(op x)} --rel:: Parser (Formula Fol) rel = (try (symbol "true" >> return TrueF)) <|> (try (symbol "false" >> return FalseF)) <|> (try quant) <|> (try (do { symbol "~"; x <- rel; return(Not x)})) <|> (parens form) <|> (do { x <- term -- always put those which are prefixes later ; f <- oneOf symbol ["=","/=","<=","<",">=",">"] ; y <- term ; case f of "/=" -> return(Not(Atom(R("=",[x,y])))) op -> return(Atom(R(f,[x,y])))}) keyword s = reserved s >> return s --quant:: Parser (Formula Fol) quant = do { f <- oneOf symbol ["exists","forall"] ; vs <- many1 identifier ; symbol "." ; body <- form ; case f of "exists" -> return(exF vs body) "forall" -> return(allF vs body)} exF [] body = body exF (v:vs) body = Exists(v,exF vs body) allF [] body = body allF (v:vs) body = Forall(v,allF vs body) --form:: Parser (Formula Fol) form = (chainl1 rel oper) where op "&&" x y = And(x,y) op "||" x y = Or(x,y) op "==>" x y = Imp(x,y) op "<=>" x y = Iff(x,y) oper = do { x <- (symbol "&&") <|> (symbol "||") <|> (symbol "==>") <|> (symbol "<=>") ; return(op x)} go s = parse2 form s -------------------------------------------------------------------- -- showing formula plusP (Fn("+",_)) = True plusP (Fn("-",_)) = True plusP _ = False showp p x = if p x then "("++show x++")" else show x instance Show Term where show (Var s) = s show (Fn("+",[x,y])) = show x ++ " + " ++ show y show (Fn("-",[x,y])) = show x ++ " - " ++ show y show (Fn("*",[x,y])) = showp plusP x ++ " * " ++ showp plusP y show (Fn("=",[x,y])) = show x ++ " = " ++ show y show (Fn("/=",[x,y])) = show x ++ " /= " ++ show y show (Fn("<",[x,y])) = show x ++ " < " ++ show y show (Fn("<=",[x,y])) = show x ++ " <= " ++ show y show (Fn(">",[x,y])) = show x ++ " > " ++ show y show (Fn(">=",[x,y])) = show x ++ " >= " ++ show y show (Fn('-':xs,_)) | all isDigit xs = "-"++xs show (Fn(x,[])) | all isDigit x = x show (Fn(f,xs)) = plist (f++"(") xs "," ")" instance Show Fol where show (R(x,y)) = show (Fn(x,y)) gNot (Forall _ ) = False gNot (Exists _) = False gNot (Atom(R(_,[]))) = False gNot (Atom(R _)) = True gNot (Not _) = False gNot _ = True gAnd (And _ ) = False gAnd x = gNot x gOr (Or _) = False gOr x = gAnd x gImp (Imp _) = False gImp x = gOr x gIff (Iff _) = False gIff x = gImp x instance Show (Formula Fol) where show form = case form of TrueF -> "true" FalseF -> "false" Atom(x) -> show x Not(p) -> "~"++ showp gNot p And(p,q) -> showp gAnd p ++ " && "++showp gAnd q Or(p,q) -> showp gOr p ++ " || "++showp gOr q Imp(p,q) -> showp gImp p ++ " ==> "++showp gImp q Iff(p,q) -> showp gIff p ++ " <=> "++showp gIff q Forall(x,p) -> let (vs,p) = allVs [] form in "(forall "++plistf id "" vs " " ". "++show p++")" Exists(x,p) -> let (vs,p) = exVs [] form in "(exists "++plistf id "" vs " " ". "++show p++")" exVs xs (Exists(x,body)) = exVs (x:xs) body exVs xs body = (reverse xs,body) allVs xs (Forall(x,body)) = allVs (x:xs) body allVs xs body = (reverse xs,body) ------------------------------------------------------------------- readForm s = case parse2 form s of Right(x,[])-> putStrLn (show x) >> return x Right(x,more) -> putStrLn ("Unconsumed input: "++more) >> return FalseF Left s -> putStrLn ("Parse error: "++ s) >> return FalseF test s = do { form <- readForm s ; ans <- integer_qelim form ; putStrLn (show ans) ; return (form,ans)} ex1 = test "forall x y. x < y ==> 2 * x + 1 < 2 * y" ex2 = test "forall x y. ~(2 * x + 1 = 2 * y)" ex3 = test "exists x y. x > 0 && y >= 0 && 3 * x - 5 * y = 1" ex4 = test "exists x y z. 4 * x - 6 * y = 1" ex5 = test "forall x. b < x ==> a <= x" ex6 = test "forall x. a < 3 * x ==> b < 3 * x" ex7 = test "forall x y. x <= y ==> 2 * x + 1 < 2 * y" ex8 = test "(exists d. y = 65 * d) ==> (exists d. y = 5 * d)" ex9 = test "forall y. (exists d. y = 65 * d) ==> (exists d. y = 5 * d)" ex10 = test "forall x y. ~(2 * x + 1 = 2 * y)" ex11 = test "forall x y z. (2 * x + 1 = 2 * y) ==> x + y + z > 129" ex12 = test "forall x. a < x ==> b < x" ex13 = test "forall x. a <= x ==> b < x" ex14 = test "forall x. (exists y. x = 2*y) && (exists y. x = 3*y) ==> (exists y. x = 6*y)" set1 = [ex1,ex2,ex3,ex4,ex5,ex6,ex7,ex8,ex9,ex10,ex11,ex12,ex13,ex14] ex00 = test $ "forall a b c d e f."++ "(1 + e + 1 + f = a + 1 + b) && "++ "(e + 1 + f = c + 1 + d) ==> (a + b = 1 + c + d)" ex20 = test "forall n. exists m w. n+n = 2+m ==> (n = w+1 && m = w+w)" exhalf = test "forall n m w . (n+n = 2+m) && (n = w+1) ==> (m = w+w)" -------------------------------------------- ex15 = test "(z1900 + 0 + 0 = z1900 + 0) && (z1890 + z1900 + 0 + z1900 + 0 = z1738 + z1820 + z1836) ==> (z1890 + z1900 + z1824 + z1840 + z1900 + z1824 + z1840 = z1738 + z1820 + z1824 + z1824 + z1836 + z1840 + z1840)" -- ripple carry adder example next = do { (a,b) <- ex15 ; let b2 = universal b ; putStrLn (show b2) ; case (Just b2) of --integer_qelim b2 of Just as -> putStrLn (show as) Nothing -> putStrLn "Ooops" ; return () } ss = ("forall z507 z589 z593 z605 z609 z659 z669. (z669 + 0 = z669 + 0) "++ "&& (z659 + z669 + 0 + z669 + 0 = z507 + z589 + z605) ==> "++ "(z659 + z669 + z593 + z609+ z669 + z593 + z609 = "++ "z507 + z589 + z593 + z593 + z605 + z609 + z609)") ex16 = test ss ----------------------------------------------------------------- universal form = allF all_vs (exF ex_vs form) where total_vs = (fv form) universal ('_':xs) = True universal x = False (all_vs,ex_vs) = partition universal total_vs type Map = [(TcTv,String)] tauTerm:: Map -> Tau -> Maybe Term tauTerm env v@(TcTv x) = case lookup x env of Nothing -> Just(Var(show v)) Just s -> Just(Var s) tauTerm env (TyFun "plus" k [x,y]) = do { a <- tauTerm env x ; b <- tauTerm env y ; return(Fn("+",[a,b]))} tauTerm env (TyFun "times" k [x,y]) = do { a <- tauTerm env x ; b <- tauTerm env y ; return(Fn("*",[a,b]))} tauTerm env (TyCon sx lev "Z" k) = return(mk_numeral 0) tauTerm env (TyApp (TyCon sx _ "S" k) x) = do { x2 <- tauTerm env x ; case x2 of x | is_numeral x -> do { n <- dest_numeral 0 x; return(mk_numeral(n+1))} (Fn("+",[y,x])) | is_numeral y -> do { n <- dest_numeral 0 y; return(Fn("+",[mk_numeral(n+1),x]))} x -> return(Fn("+",[mk_numeral 1,x]))} tauTerm env x = Nothing predForm:: Map -> Pred -> Maybe Term predForm env (Equality x y) = do { a <- tauTerm env x ; b <- tauTerm env y ; return(Fn("=",[a,b]))} predForm env (Rel _) = Nothing toForm (Fn(f,xs)) = Just(R(f,xs)) toForm _ = Nothing toF:: Map -> Tau -> Maybe [Formula Fol] toF env (TyFun "and" _ [x,y]) = do { x' <- toF env x ; y' <- toF env y ; return(x' ++ y')} toF env (TyApp (TyApp (TyCon sx _ "Equal" _) lhs) rhs) = do { lhsterm <- tauTerm env lhs ; rhsterm <- tauTerm env rhs ; return [Atom(R("=",[lhsterm,rhsterm]))] } toFormula:: Map -> [(Tau,Tau)] -> Tau -> Maybe (Formula Fol,Formula Fol) toFormula env truths concl = do { terms <- mapM (predForm env) (map (uncurry Equality) truths) ; fols <- mapM toForm terms ; let hyp = (map Atom fols) ; body <- toF env concl ; let (prefix,tail ) = case body of [x] -> ([],x) xs -> (init xs,last xs) ; let formula = (Imp(list_conj(hyp++prefix),tail)) ; return (universal formula,formula) }
cartazio/omega
src/Cooper.hs
bsd-3-clause
33,374
98
36
8,829
15,011
7,831
7,180
680
19
{-# LANGUAGE DataKinds , GADTs , FlexibleContexts , KindSignatures , PolyKinds #-} {-# OPTIONS_GHC -Wall -fwarn-tabs #-} ---------------------------------------------------------------- -- 2016.04.21 -- | -- Module : Language.Hakaru.Observe -- Copyright : Copyright (c) 2016 the Hakaru team -- License : BSD3 -- Maintainer : ppaml@indiana.edu -- Stability : experimental -- Portability : GHC-only -- -- A simpler version of the work done in 'Language.Hakaru.Disintegrate' -- -- In principle, this module's functionality is entirely subsumed -- by the work done in Language.Hakaru.Disintegrate, so we can hope -- to define observe in terms of disintegrate. This is still useful -- as a guide to those that want something more in line with what other -- probabilisitc programming systems support. ---------------------------------------------------------------- module Language.Hakaru.Observe where import Language.Hakaru.Syntax.AST import Language.Hakaru.Syntax.ABT import Language.Hakaru.Types.DataKind import Language.Hakaru.Types.Sing import qualified Language.Hakaru.Syntax.Prelude as P import Language.Hakaru.Syntax.TypeOf observe :: (ABT Term abt) => abt '[] ('HMeasure a) -> abt '[] a -> abt '[] ('HMeasure a) observe m a = observeAST (LC_ m) (LC_ a) -- TODO: move this to ABT.hs freshenVarRe :: ABT syn abt => Variable (a :: k) -> abt '[] (b :: k) -> Variable a freshenVarRe x m = x {varID = nextFree m `max` nextBind m} observeAST :: (ABT Term abt) => LC_ abt ('HMeasure a) -> LC_ abt a -> abt '[] ('HMeasure a) observeAST (LC_ m) (LC_ a) = caseVarSyn m observeVar $ \ast -> case ast of -- TODO: Add a name supply Let_ :$ e1 :* e2 :* End -> caseBind e2 $ \x e2' -> let x' = freshenVarRe x m e2'' = rename x x' e2' in syn (Let_ :$ e1 :* bind x' (observe e2'' a) :* End) --Dirac :$ e :* End -> P.if_ (e P.== a) (P.dirac a) P.reject -- TODO: Add a name supply MBind :$ e1 :* e2 :* End -> caseBind e2 $ \x e2' -> let x' = freshenVarRe x m e2'' = rename x x' e2' in syn (MBind :$ e1 :* bind x' (observe e2'' a) :* End) Plate :$ e1 :* e2 :* End -> caseBind e2 $ \x e2' -> let a' = syn (ArrayOp_ (Index (sUnMeasure $ typeOf e2')) :$ a :* var x :* End) in syn (Plate :$ e1 :* bind x (observe e2' a') :* End) MeasureOp_ op :$ es -> observeMeasureOp op es a _ -> error "observe can only be applied to measure primitives" -- This function can't inspect a variable due to -- calls to subst that happens in Let_ and Bind_ observeVar :: Variable a -> r observeVar = error "observe can only be applied measure primitives" observeMeasureOp :: (ABT Term abt, typs ~ UnLCs args, args ~ LCs typs) => MeasureOp typs a -> SArgs abt args -> abt '[] a -> abt '[] ('HMeasure a) observeMeasureOp Normal = \(mu :* sd :* End) a -> P.withWeight (P.densityNormal mu sd a) (P.dirac a) observeMeasureOp Uniform = \(lo :* hi :* End) a -> P.if_ (lo P.<= a P.&& a P.<= hi) (P.withWeight (P.unsafeProb $ P.recip $ hi P.- lo) (P.dirac a)) (P.reject (SMeasure SReal)) observeMeasureOp _ = error "TODO{Observe:observeMeasureOp}"
zaxtax/hakaru
haskell/Language/Hakaru/Observe.hs
bsd-3-clause
3,533
0
26
1,052
954
495
459
63
5
module String00003 where s = "\ \Strings should allow \"escaped double quotes\"\ \as well as multi-line strings. Also, the closing\ \quote of this string can be preceded by a backslash\ \since the backslash indicates line continuation, not\ \quote escaping!\ \"
charleso/intellij-haskforce
tests/gold/parser/String00003.hs
apache-2.0
283
0
4
61
9
6
3
2
1
import Control.Concurrent import Control.Monad import Data.ByteString.Lazy(pack) import qualified Data.ByteString.Lazy as BS import Data.Word import Hypervisor.Console import Hypervisor.Debug import Hypervisor.XenStore import XenDevice.Disk main :: IO () main = do writeDebugConsole "Starting system!\n" con <- initXenConsole writeConsole con "Starting Disk device tests.\n" xs <- initXenStore writeDebugConsole "XenStore initialized!\n" disks <- listDisks xs threadDelay (1000000) writeConsole con ("Found " ++ show (length disks) ++ " disks:\n") forM_ disks $ \ d -> writeConsole con (" " ++ d ++ "\n") writeConsole con "\n" diskinfos <- zip disks `fmap` mapM (openDisk xs) disks forM_ diskinfos $ \ (dname, d) -> do writeConsole con ("Information about " ++ dname ++ ":\n") writeConsole con (" # Sectors: " ++ show (diskSectors d) ++ "\n") writeConsole con (" Sector size: " ++ show (diskSectorSize d) ++ "\n") writeConsole con (" isReadOnly: " ++ show (isDiskReadOnly d) ++ "\n") writeConsole con (" isDiskRemovable: " ++ show (isDiskRemovable d)++"\n") writeConsole con (" diskSupportsBarrier: " ++ show (diskSupportsBarrier d) ++ "\n") writeConsole con (" diskSupportsFlush: " ++ show (diskSupportsFlush d) ++ "\n") writeConsole con (" diskSupportsDiscard: " ++ show (diskSupportsDiscard d) ++ "\n") writeConsole con "\n" case lookup "hdb" diskinfos of Just disk -> do writeConsole con "Verifying read only disk hdb\n" checkROSectors con disk 0 0 (diskSectors disk) Nothing -> writeConsole con "Could not find RO disk hdb\n" case lookup "hda" diskinfos of Just disk -> do writeConsole con "Verifying read/write disk hda\n" checkRWBlocks con disk writeConsole con "Done!\n" checkROSectors :: Console -> Disk -> Word -> Word8 -> Word -> IO () checkROSectors con disk cursec val endsec | cursec == endsec = writeConsole con (" --> Verified " ++ show endsec ++ " sectors.\n") | otherwise = do nextSec <- readDisk disk (diskSectorSize disk) cursec let example = pack (replicate 512 val) unless (example == nextSec) $ do writeConsole con (" --> Verification FAILED at sector " ++ show cursec ++ "\n") fail "Verification failed!" checkROSectors con disk (cursec + 1) (val + 1) endsec checkRWBlocks :: Console -> Disk -> IO () checkRWBlocks con disk = do writeTest 0 0 (diskSectors disk) writeDebugConsole "Completed write portion.\n" diskWriteBarrier disk writeDebugConsole "Executed write barrier.\n" readTest 0 0 (diskSectors disk) where secsPerBlock = 8192 `div` diskSectorSize disk -- writeTest x cur top | cur == top = writeConsole con (" --> Wrote " ++ show top ++ " sectors\n") | otherwise = do let example = pack (replicate 8192 x) writeDisk disk example cur writeTest (x + 1) (cur + secsPerBlock) top -- readTest x cur top | cur == top = writeConsole con (" --> Verified " ++ show top ++ " sectors\n") | otherwise = do let example = pack (replicate 8192 x) bstr <- readDisk disk 8192 cur unless (example == bstr) $ do writeConsole con (" --> Verification FAILED at sector " ++ show cur ++ "\n") writeDebugConsole ("Start of example: " ++ show (BS.take 16 example) ++ "\n") writeDebugConsole ("Start of block: " ++ show (BS.take 16 bstr) ++ "\n") writeDebugConsole ("lengths: " ++ show (BS.length example) ++ " / " ++ show (BS.length bstr) ++ "\n") fail "Verification failed!" readTest (x + 1) (cur + secsPerBlock) top
thumphries/HaLVM
examples/XenDevice/VBDTest/VBDTest.hs
bsd-3-clause
3,771
0
22
969
1,224
571
653
87
2
<?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="el-GR"> <title>Linux WebDrivers</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>Search</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>
kingthorin/zap-extensions
addOns/webdrivers/webdriverlinux/src/main/javahelp/org/zaproxy/zap/extension/webdriverlinux/resources/help_el_GR/helpset_el_GR.hs
apache-2.0
961
77
66
156
407
206
201
-1
-1
module B1 where data Data1 a = C1 a Int Int | C2 Int | C3 Float g (C1 x y z) = y g (C2 x) = x g (C3 x) = 42
mpickering/HaRe
old/testing/addCon/B1.hs
bsd-3-clause
121
0
7
47
74
40
34
5
1
module Main (main) where import qualified HIndent main :: IO () main = return ()
sighingnow/hindent
src/main/TestGenerate.hs
bsd-3-clause
83
0
6
17
33
19
14
4
1
{-# LANGUAGE MagicHash, UnboxedTuples #-} module Bug ( box, wrap, proxy ) where import GHC.Prim box :: (# Proxy# a, b #) -> b box (# x, y #) = y wrap :: b -> Proxy# a -> (# Proxy# a, b #) wrap x = \i# -> (# i#, x #) proxy :: () -> Proxy# a proxy () = proxy#
ezyang/ghc
testsuite/tests/ghci/scripts/T12520.hs
bsd-3-clause
263
0
8
67
117
64
53
9
1
import Data.List (sortBy) import Data.Word (Word64) main = putStrLn $ show solve solve :: Word64 solve = head $ sortBy (\x y -> compare y x) $ digitProducts 13 digits digitProducts :: Int -> [Word64] -> [Word64] digitProducts n ds = digitProductsHelper (take n ds) (drop n ds) where digitProductsHelper _ [] = [] digitProductsHelper a@(_:xs) (y:ys) = (product a) : (digitProductsHelper (xs ++ [y]) ys) digits :: [Word64] digits = [ 7, 3, 1, 6, 7, 1, 7, 6, 5, 3, 1, 3, 3, 0, 6, 2, 4, 9, 1, 9, 2, 2, 5, 1, 1, 9, 6, 7, 4, 4, 2, 6, 5, 7, 4, 7, 4, 2, 3, 5, 5, 3, 4, 9, 1, 9, 4, 9, 3, 4, 9, 6, 9, 8, 3, 5, 2, 0, 3, 1, 2, 7, 7, 4, 5, 0, 6, 3, 2, 6, 2, 3, 9, 5, 7, 8, 3, 1, 8, 0, 1, 6, 9, 8, 4, 8, 0, 1, 8, 6, 9, 4, 7, 8, 8, 5, 1, 8, 4, 3, 8, 5, 8, 6, 1, 5, 6, 0, 7, 8, 9, 1, 1, 2, 9, 4, 9, 4, 9, 5, 4, 5, 9, 5, 0, 1, 7, 3, 7, 9, 5, 8, 3, 3, 1, 9, 5, 2, 8, 5, 3, 2, 0, 8, 8, 0, 5, 5, 1, 1, 1, 2, 5, 4, 0, 6, 9, 8, 7, 4, 7, 1, 5, 8, 5, 2, 3, 8, 6, 3, 0, 5, 0, 7, 1, 5, 6, 9, 3, 2, 9, 0, 9, 6, 3, 2, 9, 5, 2, 2, 7, 4, 4, 3, 0, 4, 3, 5, 5, 7, 6, 6, 8, 9, 6, 6, 4, 8, 9, 5, 0, 4, 4, 5, 2, 4, 4, 5, 2, 3, 1, 6, 1, 7, 3, 1, 8, 5, 6, 4, 0, 3, 0, 9, 8, 7, 1, 1, 1, 2, 1, 7, 2, 2, 3, 8, 3, 1, 1, 3, 6, 2, 2, 2, 9, 8, 9, 3, 4, 2, 3, 3, 8, 0, 3, 0, 8, 1, 3, 5, 3, 3, 6, 2, 7, 6, 6, 1, 4, 2, 8, 2, 8, 0, 6, 4, 4, 4, 4, 8, 6, 6, 4, 5, 2, 3, 8, 7, 4, 9, 3, 0, 3, 5, 8, 9, 0, 7, 2, 9, 6, 2, 9, 0, 4, 9, 1, 5, 6, 0, 4, 4, 0, 7, 7, 2, 3, 9, 0, 7, 1, 3, 8, 1, 0, 5, 1, 5, 8, 5, 9, 3, 0, 7, 9, 6, 0, 8, 6, 6, 7, 0, 1, 7, 2, 4, 2, 7, 1, 2, 1, 8, 8, 3, 9, 9, 8, 7, 9, 7, 9, 0, 8, 7, 9, 2, 2, 7, 4, 9, 2, 1, 9, 0, 1, 6, 9, 9, 7, 2, 0, 8, 8, 8, 0, 9, 3, 7, 7, 6, 6, 5, 7, 2, 7, 3, 3, 3, 0, 0, 1, 0, 5, 3, 3, 6, 7, 8, 8, 1, 2, 2, 0, 2, 3, 5, 4, 2, 1, 8, 0, 9, 7, 5, 1, 2, 5, 4, 5, 4, 0, 5, 9, 4, 7, 5, 2, 2, 4, 3, 5, 2, 5, 8, 4, 9, 0, 7, 7, 1, 1, 6, 7, 0, 5, 5, 6, 0, 1, 3, 6, 0, 4, 8, 3, 9, 5, 8, 6, 4, 4, 6, 7, 0, 6, 3, 2, 4, 4, 1, 5, 7, 2, 2, 1, 5, 5, 3, 9, 7, 5, 3, 6, 9, 7, 8, 1, 7, 9, 7, 7, 8, 4, 6, 1, 7, 4, 0, 6, 4, 9, 5, 5, 1, 4, 9, 2, 9, 0, 8, 6, 2, 5, 6, 9, 3, 2, 1, 9, 7, 8, 4, 6, 8, 6, 2, 2, 4, 8, 2, 8, 3, 9, 7, 2, 2, 4, 1, 3, 7, 5, 6, 5, 7, 0, 5, 6, 0, 5, 7, 4, 9, 0, 2, 6, 1, 4, 0, 7, 9, 7, 2, 9, 6, 8, 6, 5, 2, 4, 1, 4, 5, 3, 5, 1, 0, 0, 4, 7, 4, 8, 2, 1, 6, 6, 3, 7, 0, 4, 8, 4, 4, 0, 3, 1, 9, 9, 8, 9, 0, 0, 0, 8, 8, 9, 5, 2, 4, 3, 4, 5, 0, 6, 5, 8, 5, 4, 1, 2, 2, 7, 5, 8, 8, 6, 6, 6, 8, 8, 1, 1, 6, 4, 2, 7, 1, 7, 1, 4, 7, 9, 9, 2, 4, 4, 4, 2, 9, 2, 8, 2, 3, 0, 8, 6, 3, 4, 6, 5, 6, 7, 4, 8, 1, 3, 9, 1, 9, 1, 2, 3, 1, 6, 2, 8, 2, 4, 5, 8, 6, 1, 7, 8, 6, 6, 4, 5, 8, 3, 5, 9, 1, 2, 4, 5, 6, 6, 5, 2, 9, 4, 7, 6, 5, 4, 5, 6, 8, 2, 8, 4, 8, 9, 1, 2, 8, 8, 3, 1, 4, 2, 6, 0, 7, 6, 9, 0, 0, 4, 2, 2, 4, 2, 1, 9, 0, 2, 2, 6, 7, 1, 0, 5, 5, 6, 2, 6, 3, 2, 1, 1, 1, 1, 1, 0, 9, 3, 7, 0, 5, 4, 4, 2, 1, 7, 5, 0, 6, 9, 4, 1, 6, 5, 8, 9, 6, 0, 4, 0, 8, 0, 7, 1, 9, 8, 4, 0, 3, 8, 5, 0, 9, 6, 2, 4, 5, 5, 4, 4, 4, 3, 6, 2, 9, 8, 1, 2, 3, 0, 9, 8, 7, 8, 7, 9, 9, 2, 7, 2, 4, 4, 2, 8, 4, 9, 0, 9, 1, 8, 8, 8, 4, 5, 8, 0, 1, 5, 6, 1, 6, 6, 0, 9, 7, 9, 1, 9, 1, 3, 3, 8, 7, 5, 4, 9, 9, 2, 0, 0, 5, 2, 4, 0, 6, 3, 6, 8, 9, 9, 1, 2, 5, 6, 0, 7, 1, 7, 6, 0, 6, 0, 5, 8, 8, 6, 1, 1, 6, 4, 6, 7, 1, 0, 9, 4, 0, 5, 0, 7, 7, 5, 4, 1, 0, 0, 2, 2, 5, 6, 9, 8, 3, 1, 5, 5, 2, 0, 0, 0, 5, 5, 9, 3, 5, 7, 2, 9, 7, 2, 5, 7, 1, 6, 3, 6, 2, 6, 9, 5, 6, 1, 8, 8, 2, 6, 7, 0, 4, 2, 8, 2, 5, 2, 4, 8, 3, 6, 0, 0, 8, 2, 3, 2, 5, 7, 5, 3, 0, 4, 2, 0, 7, 5, 2, 9, 6, 3, 4, 5, 0]
pshendry/project-euler-solutions
0008/solution.hs
mit
3,545
0
12
1,185
3,208
2,111
1,097
31
2
{- add :: Num a => a -> a -> a add x y = x + y -} add :: Num a => a -> a -> a add = (+)
fmi-lab/fp-elective-2017
exercises/11/add.hs
mit
89
0
7
33
29
16
13
2
1
{-# LANGUAGE RecordWildCards #-} module GhostLang.RuntimeState.Counter ( Counter (..) , HttpStatus (..) , emptyCounter , incPatternExecTime' , incInstrInvoked' , incLoopCmds' , incConcCmds' , incProcCalls' , updHttpGETCounters' , updHttpPUTCounters' , getProcCalls , getTotalProcCalls , incPatternRuns' , getPatternRuns , getTotalPatternRuns ) where import Data.Maybe (fromMaybe) import Data.Text (Text) import Data.Time (NominalDiffTime) import GHC.Int (Int64) import qualified Data.Map.Strict as Map data HttpStatus = Success | Failure deriving (Eq, Show) -- | Statistics counter for Ghost lang code execution. data Counter = Counter { patternExecTime :: !NominalDiffTime -- ^ The total execution time in seconds. , instrInvoked :: {-# UNPACK #-} !Int64 -- ^ The number of instructions invoked during the -- execution. , loopCmds :: {-# UNPACK #-} !Int64 -- ^ The number of loop commands run during the execution. , concCmds :: {-# UNPACK #-} !Int64 , procCalls :: !(Map.Map Text Int64) -- ^ Book keeping of the number of times certain -- procedures are called. , patternRuns :: !(Map.Map Text Int64) -- ^ Book keeping of the number of times certain patterns -- are executed. , httpGETExecTime :: !NominalDiffTime , httpGETBytes :: {-# UNPACK #-} !Int64 , httpGETSuccess :: {-# UNPACK #-} !Int64 , httpGETFailures :: {-# UNPACK #-} !Int64 -- ^ Counters for http GET. , httpPUTExecTime :: !NominalDiffTime , httpPUTBytes :: {-# UNPACK #-} !Int64 , httpPUTSuccess :: {-# UNPACK #-} !Int64 , httpPUTFailures :: {-# UNPACK #-} !Int64 -- ^ Counters for http PUT. } deriving Show -- | Create an empty counter. emptyCounter :: Counter emptyCounter = Counter { patternExecTime = toEnum 0 , instrInvoked = 0 , loopCmds = 0 , concCmds = 0 , procCalls = Map.empty , patternRuns = Map.empty , httpGETExecTime = toEnum 0 , httpGETBytes = 0 , httpGETSuccess = 0 , httpGETFailures = 0 , httpPUTExecTime = toEnum 0 , httpPUTBytes = 0 , httpPUTSuccess = 0 , httpPUTFailures = 0 } -- | Increase the pattern execution time. incPatternExecTime' :: NominalDiffTime -> Counter -> Counter incPatternExecTime' d c@Counter {..} = c { patternExecTime = patternExecTime + d } -- | Increase the invoke counter by 1. incInstrInvoked' :: Counter -> Counter incInstrInvoked' c@Counter {..} = c { instrInvoked = instrInvoked + 1 } -- | Increase the loop command counter by 1. incLoopCmds' :: Counter -> Counter incLoopCmds' c@Counter {..} = c { loopCmds = loopCmds + 1 } -- | Increase the concurrently command counter by 1. incConcCmds' :: Counter -> Counter incConcCmds' c@Counter {..} = c { concCmds = concCmds + 1 } -- | Increase the procedure call counter for procedure 'p' by one. incProcCalls' :: Text -> Counter -> Counter incProcCalls' p c@Counter {..} = let g = maybe (Just 1) (Just . (1 +)) in c { procCalls = Map.alter g p procCalls } -- | Update counters for http GET updHttpGETCounters' :: NominalDiffTime -> Int64 -> HttpStatus -> Counter -> Counter updHttpGETCounters' d bytes status c@Counter {..} = let incSuccCount = if status == Success then 1 else 0 incFailCount = if status == Failure then 1 else 0 in c { httpGETExecTime = httpGETExecTime + d , httpGETBytes = httpGETBytes + bytes , httpGETSuccess = httpGETSuccess + incSuccCount , httpGETFailures = httpGETFailures + incFailCount } -- | Update counters for http PUT. updHttpPUTCounters' :: NominalDiffTime -> Int64 -> HttpStatus -> Counter -> Counter updHttpPUTCounters' d bytes status c@Counter {..} = let incSuccCount = if status == Success then 1 else 0 incFailCount = if status == Failure then 1 else 0 in c { httpPUTExecTime = httpPUTExecTime + d , httpPUTBytes = httpPUTBytes + bytes , httpPUTSuccess = httpPUTSuccess + incSuccCount , httpPUTFailures = httpPUTFailures + incFailCount } -- | Get the value for the procedure call counter for procedure 'p'. getProcCalls :: Text -> Counter -> Int64 getProcCalls p Counter {..} = fromMaybe 0 (Map.lookup p procCalls) -- | Get the total number of procedure calls. getTotalProcCalls :: Counter -> Int64 getTotalProcCalls Counter {..} = Map.foldl' (+) 0 procCalls -- | Increase the pattern run counter for pattern 'p' by one. incPatternRuns' :: Text -> Counter -> Counter incPatternRuns' p c@Counter {..} = let g = maybe (Just 1) (Just . (1 +)) in c { patternRuns = Map.alter g p patternRuns } -- | Get the value for the pattern run counter for pattern 'p'. getPatternRuns :: Text -> Counter -> Int64 getPatternRuns p Counter {..} = fromMaybe 0 (Map.lookup p patternRuns) -- | Get the total number of pattern runs. getTotalPatternRuns :: Counter -> Int64 getTotalPatternRuns Counter {..} = Map.foldl' (+) 0 patternRuns
kosmoskatten/ghost-lang
ghost-lang/src/GhostLang/RuntimeState/Counter.hs
mit
5,427
0
12
1,569
1,135
653
482
109
3
{-# LANGUAGE OverloadedStrings #-} {- Connect4 implementation in Haskell. - NOTE: I know the comments in this file are a bit much extense. This has been - on purpose, so in case someone stumbles upon this source code and wants - to learn Haskell, they can somewhat understand what is going on (while - helping myself remember the concepts I have learned about Haskell). -} import Control.Lens import Control.Monad.Reader import Control.Monad.State import Data.Functor (($>)) import Data.Maybe (fromJust, isNothing) import qualified Data.Text as T import System.Random import Safe (readMay) import Board import GameState import qualified UI.Graphics as UI import Strategy.Greedy import Strategy.Negamax -- |Type alias for the state monad used in this file. -- We will be using the state monad transformer so we can have a mutable game -- state as well as we can use the capabilities of the IO monad (access to the -- real world, i.e: reading from stdin and outputting to stdout) -- Update: Also we add the "ReaderT" transformer so we can access the -- GraphicsHandler. type GameMonad = ReaderT UI.GraphicsHandle (StateT GameState IO) -- Algebraic data structure that may contain an (exceptional) action to -- do about the game. data GameAction = Exit | Restart -- Takes an UI.Action (from the UI.Graphics module) and converts it to either -- a GameAction or a column number. fromUIInput :: UI.Input -> Either GameAction Int fromUIInput uiAct = case uiAct of UI.Exit -> Left Exit UI.Restart -> Left Restart UI.ColSelected col -> Right col -- |The 'runGame' function evaluates the whole stack of a GameMonad monad. -- We pass it the reader configuration and the initial state. runGame :: GameMonad a -> UI.GraphicsHandle -> GameState -> IO a runGame gm uiHandle initState = (gm `runReaderT` uiHandle) `evalStateT` initState -- |Returns the strategy for the given player ('Nothing' = human controlled). playerStrategy :: Player -> Maybe GameStrategy playerStrategy pl = pick strategies where pick | pl == X = fst | pl == O = snd -- Define player strategies. strategies = (Nothing, Just $ negamaxStrategy 5) -- |Reads player input using a 'GameStrategy' or reading from the user. playerInput :: Maybe GameStrategy -> GameMonad (Either GameAction Int) playerInput Nothing = do -- No strategy -> human user. uiHandle <- ask board <- use gsBoard fromUIInput <$> UI.getInput board uiHandle playerInput (Just strat) = do -- Run the strategy. state <- get liftIO . fmap Right $ strat `runStrategy` state -- |Play a turn for a given player (i.e: read column and place piece). -- Returns the input received from the player. playTurn :: GameMonad (Either GameAction ()) playTurn = do -- The 'lens' package provides some functions analogous to the ones defined -- in the state monad. For example: 'use' is like 'gets', but the former -- lets us use a lens as a getter, while the later needs a explicit -- function over the state. currentPlayer <- use gsCurrentPlayer curBoard <- use gsBoard let mStrat = playerStrategy currentPlayer -- Obtain input from the strategy or human player. input <- playerInput mStrat case input of Left _ -> return (input $> ()) Right col -> let mboard = putPiece currentPlayer col curBoard -- Check validity of the board, returning it if it's valid, or -- asking again for the column if it's not the case. in case mboard of Nothing -> playTurn Just newBoard -> do assign gsBoard newBoard gsCurrentPlayer %= nextPlayer return $ Right () -- |Function called when the game ends. Shows final board and winner. gameOver :: Maybe Player -> GameMonad () gameOver mwinner = do finalBoard <- use gsBoard uiHandle <- ask UI.render finalBoard uiHandle -- Indicates that the game has ended, disabling interaction with the board. assign gsGameEnded True liftIO $ UI.showMessageWindow "Game over" (maybe "The game ended in a draw" (T.append "The winner of the game is " . T.pack . toColor ) mwinner) uiHandle -- |Loop of the game. This function repeats itself until there is a winner -- (or no more plays are possible). mainLoop :: GameMonad () mainLoop = do -- Display current state of the board. doRender -- Check if game ended. hasMatchEnded <- use gsGameEnded if hasMatchEnded then do -- If the match has ended, disable all interactions with the board board <- use gsBoard uiHandle <- ask action <- UI.getPassiveInput board uiHandle case fromUIInput action of Left action -> runAction action Right _ -> error "ColSelected event is not expected now" else do -- If the game is still ongoing, just play the next turn. eInput <- playTurn either runAction continueGame eInput where doRender = do board <- use gsBoard uiHandle <- ask UI.render board uiHandle runAction Exit = do uiHandle <- ask UI.cleanup uiHandle runAction Restart = do stdGen <- use gsStdGen initState <- liftIO $ initialState (Just stdGen) put initState doRender mainLoop continueGame () = do newBoard <- use gsBoard let matchSt = getMatchState newBoard case matchSt of NotEnd -> return () Win w -> gameOver $ Just w Tie -> gameOver Nothing mainLoop -- |Returns the initial state. initialState :: Maybe StdGen -> IO GameState initialState prevStdGen = do stdGen <- maybe getStdGen return prevStdGen let (initialPlayer, newGen) = random stdGen return $ GameState emptyBoard newGen initialPlayer False -- |Main function, entry point to the application. main :: IO () main = do initState <- initialState Nothing uiHandle <- UI.initUI runGame mainLoop uiHandle initState
joslugd/connect4-haskell
src/Main.hs
mit
6,348
0
19
1,805
1,139
560
579
111
6
-------------------------------------------------------------------------------- -- | -- Module : Network.URL -- Copyright : (c) Galois, Inc. 2007, 2008 -- License : BSD3 -- -- Maintainer : Iavor S. Diatchki -- Stability : Provisional -- Portability : Portable -- -- Provides a convenient way for working with HTTP URLs. -- Based on RFC 1738. -- See also: RFC 3986 module Network.URL ( URL(..), URLType(..), Host(..), Protocol(..) , secure, secure_prot , exportURL, importURL, exportHost , add_param , decString, encString , ok_host, ok_url, ok_param, ok_path , exportParams, importParams ) where import Data.Char (isAlpha, isAscii, isDigit) import Data.List (intersperse) import Data.Word (Word8) import Numeric (readHex, showHex) import qualified Codec.Binary.UTF8.String as UTF8 -- | Contains information about the connection to the host. data Host = Host { protocol :: Protocol , host :: String , port :: Maybe Integer } deriving (Eq,Ord,Show) -- | The type of known protocols. data Protocol = HTTP Bool -- ^ True for https, False for http | FTP Bool -- ^ True for ftps, False for ftp | RawProt String deriving (Eq,Ord,Show) -- | Is this a \"secure\" protocol. This works only for known protocols, -- for 'RawProt' values we return 'False'. secure_prot :: Protocol -> Bool secure_prot (HTTP s) = s secure_prot (FTP s) = s secure_prot (RawProt _) = False -- | Does this host use a \"secure\" protocol (e.g., https). secure :: Host -> Bool secure = secure_prot . protocol -- | Different types of URL. data URLType = Absolute Host -- ^ Has a host | HostRelative -- ^ Does not have a host | PathRelative -- ^ Relative to another URL deriving (Eq, Ord, Show) -- | A type for working with URL. -- The parameters are in @application\/x-www-form-urlencoded@ format: -- <http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1> data URL = URL { url_type :: URLType , url_path :: String , url_params :: [(String,String)] } deriving (Eq,Ord,Show) -- | Add a (key,value) parameter to a URL. add_param :: URL -> (String,String) -> URL add_param url x = url { url_params = x : url_params url } -- | Convert a list of \"bytes\" to a URL. importURL :: String -> Maybe URL importURL cs0 = do (ho,cs5) <- front cs0 (pa,cs6) <- the_path cs5 as <- the_args cs6 return URL { url_type = ho, url_path = pa, url_params = as } where front ('/':cs) = return (HostRelative,cs) front cs = case the_prot cs of Just (pr,cs1) -> do let (ho,cs2) = the_host cs1 (po,cs3) <- the_port cs2 cs4 <- case cs3 of [] -> return [] '/':cs5 -> return cs5 _ -> Nothing return (Absolute Host { protocol = pr , host = ho , port = po }, cs4) _ -> return (PathRelative,cs) the_prot :: String -> Maybe (Protocol, String) the_prot urlStr = case break (':' ==) urlStr of (as@(_:_), ':' : '/' : '/' : bs) -> Just (prot, bs) where prot = case as of "https" -> HTTP True "http" -> HTTP False "ftps" -> FTP True "ftp" -> FTP False _ -> RawProt as _ -> Nothing the_host = span ok_host the_port (':':cs) = case span isDigit cs of ([],_) -> Nothing (xs,ds) -> Just (Just (read xs),ds) the_port cs5 = return (Nothing, cs5) the_path cs = do let (as,bs) = break end_path cs s <- decString False as return (s,bs) where end_path c = c == '#' || c == '?' the_args ('?' : cs) = importParams cs the_args _ = return [] importParams :: String -> Maybe [(String,String)] importParams [] = return [] importParams ds = mapM a_param (breaks ('&'==) ds) where a_param cs = do let (as,bs) = break ('=' ==) cs k <- decString True as v <- case bs of "" -> return "" _:xs -> decString True xs return (k,v) -- | Convert the host part of a URL to a list of \"bytes\". exportHost :: Host -> String exportHost absol = the_prot ++ "://" ++ host absol ++ the_port where the_prot = exportProt (protocol absol) the_port = maybe "" (\x -> ':' : show x) (port absol) -- | Convert the host part of a URL to a list of \"bytes\". -- WARNING: We output \"raw\" protocols as they are. exportProt :: Protocol -> String exportProt prot = case prot of HTTP True -> "https" HTTP False -> "http" FTP True -> "ftps" FTP False -> "ftp" RawProt s -> s -- | Convert a URL to a list of \"bytes\". -- We represent non-ASCII characters using UTF8. exportURL :: URL -> String exportURL url = absol ++ the_path ++ the_params where absol = case url_type url of Absolute hst -> exportHost hst ++ "/" HostRelative -> "/" PathRelative -> "" the_path = encString False ok_path (url_path url) the_params = case url_params url of [] -> "" xs -> '?' : exportParams xs exportParams :: [(String,String)] -> String exportParams ps = concat (intersperse "&" $ map a_param ps) where a_param (k,mv) = encString True ok_param k ++ case mv of "" -> "" v -> '=' : encString True ok_param v -- | Convert a string to bytes by escaping the characters that -- do not satisfy the input predicate. The first argument specifies -- if we should replace spaces with +. encString :: Bool -> (Char -> Bool) -> String -> String encString pl p ys = foldr enc1 [] ys where enc1 ' ' xs | pl = '+' : xs enc1 x xs = if p x then x : xs else encChar x ++ xs -- | %-encode a character. Uses UTF8 to represent characters as bytes. encChar :: Char -> String encChar c = concatMap encByte (UTF8.encode [c]) -- | %-encode a byte. encByte :: Word8 -> String encByte b = '%' : case showHex b "" of d@[_] -> '0' : d d -> d -- | Decode a list of \"bytes\" to a string. -- Performs % and UTF8 decoding. decString :: Bool -> String -> Maybe String decString b = fmap UTF8.decode . decStrBytes b -- Convert a list of \"bytes\" to actual bytes. -- Performs %-decoding. The boolean specifies if we should turn pluses into -- spaces. decStrBytes :: Bool -> String -> Maybe [Word8] decStrBytes _ [] = Just [] decStrBytes p ('%' : cs) = do (n,cs1) <- decByte cs fmap (n:) (decStrBytes p cs1) decStrBytes p (c : cs) = let b = if p && c == '+' then 32 -- space else fromIntegral (fromEnum c) in (b :) `fmap` decStrBytes p cs -- truncates "large bytes". -- | Parse a percent-encoded byte. decByte :: String -> Maybe (Word8,String) decByte (x : y : cs) = case readHex [x,y] of [(n,"")] -> Just (n,cs) _ -> Nothing decByte _ = Nothing -- Classification of characters. -- Note that these only return True for ASCII characters; this is important. -------------------------------------------------------------------------------- ok_host :: Char -> Bool ok_host c = isDigit c || isAlphaASCII c || c == '.' || c == '-' ok_param :: Char -> Bool ok_param c = ok_host c || c `elem` "~;:@$_!*'()," -- | Characters that can appear non % encoded in the path part of the URL ok_path :: Char -> Bool ok_path c = ok_param c || c `elem` "/=&" -- XXX: others? check RFC -- | Characters that do not need to be encoded in URL ok_url :: Char -> Bool ok_url c = isDigit c || isAlphaASCII c || c `elem` ".-;:@$_!*'(),/=&?~+" -- Misc -------------------------------------------------------------------------------- isAlphaASCII :: Char -> Bool isAlphaASCII x = isAscii x && isAlpha x breaks :: (a -> Bool) -> [a] -> [[a]] breaks p xs = case break p xs of (as,[]) -> [as] (as,_:bs) -> as : breaks p bs
yav/url
Network/URL.hs
mit
8,585
0
17
2,837
2,318
1,241
1,077
155
13
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE DeriveDataTypeable #-} module JSDOM.Custom.PositionError ( module Generated , PositionErrorCode(..) , PositionException(..) , throwPositionException ) where import Prelude () import Prelude.Compat import Data.Typeable (Typeable) import Control.Exception (Exception, throwIO) import Control.Monad.IO.Class (MonadIO(..)) import JSDOM.Types (MonadDOM) import JSDOM.Generated.PositionError as Generated data PositionErrorCode = PositionPermissionDenied | PositionUnavailable | PositionTimeout deriving (Show, Eq, Enum) data PositionException = PositionException { positionErrorCode :: PositionErrorCode, positionErrorMessage :: String } deriving (Show, Eq, Typeable) instance Exception PositionException throwPositionException :: MonadDOM m => PositionError -> m a throwPositionException error = do positionErrorCode <- (toEnum . subtract 1 . fromIntegral) <$> getCode error positionErrorMessage <- getMessage error liftIO $ throwIO (PositionException{..})
ghcjs/jsaddle-dom
src/JSDOM/Custom/PositionError.hs
mit
1,050
0
12
157
254
146
108
24
1
import qualified Data.Aeson as Aeson import qualified Data.ByteString.Lazy as ByteString import qualified Data.Conf as Conf import Data.Monoid import qualified Data.Text.IO as Text import qualified Data.Yaml as Yaml import System.Environment import System.FilePath import qualified Text.Megaparsec as Megaparsec main :: IO () main = do as <- getArgs case as of (fp:output:_) -> do mv <- case takeExtension fp of ".yaml" -> Yaml.decodeFile fp ".json" -> Aeson.decode <$> ByteString.readFile fp case mv of Just v -> do let conf :: Aeson.Result Conf.Conf conf = Aeson.fromJSON v writeFile output $ show $ case conf of Aeson.Success c -> Conf.pPrintConf c Aeson.Error e -> error ("Tranformation failure: " <> e) Nothing -> error ("Parse failure " <> fp) _ -> error "Usage: toconf <inputfile> <outputfile>"
beijaflor-io/haskell-language-conf
bin/ToConf.hs
mit
1,102
0
23
421
276
145
131
26
5
module Main where import LispREPL import System.Environment main :: IO () main = do args <- getArgs case length args of 0 -> runRepl 1 -> runOne $ args !! 0 otherwise -> putStrLn "Program takes only 0 or 1 output"
Bolt64/wyas
src/Main.hs
mit
268
0
11
95
73
37
36
9
3
{-# LANGUAGE OverloadedStrings, FlexibleContexts #-} module DiG.Config where import Data.ByteString.Char8 (ByteString, pack) import Data.ConfigFile import Control.Monad.Error import Data.Either (rights) data DocSet = DocSet { name :: ByteString , repo :: ByteString , prefixes :: [ByteString] , rootDir :: Maybe ByteString , index :: ByteString , posProc :: Maybe ByteString } deriving (Show) buildConf :: String -> IO (Either CPError [DocSet]) buildConf file = do conf <- runErrorT $ do conf <- join $ liftIO $ readfile emptyCP file let ds = sections conf liftIO $ putStrLn $ show ds let ds' = rights $ map (buildDocSet conf) ds liftIO $ putStrLn $ show ds' return ds' return conf buildDocSet :: ConfigParser -> String -> Either CPError DocSet buildDocSet conf n = do r <- get conf n "repo" p <- get conf n "tags" let d = getOpt' conf n "root" i <- get conf n "index" let proc = getOpt' conf n "proc" return $ doc r p d i proc where doc r p d i proc = DocSet { name = pack n , repo = pack r , prefixes = map pack $ words p , rootDir = d , index = pack i , posProc = proc } getOpt' :: ConfigParser -> String -> String -> Maybe ByteString getOpt' conf s i = fromEither $ get conf s i where fromEither (Left _) = Nothing fromEither (Right x) = Just $ pack x readSection :: ConfigParser -> String-> [(String, String)] readSection _ _ = undefined
oforero/DiG
src/DiG/Config.hs
mit
1,806
0
17
713
548
278
270
43
2
{-# LANGUAGE CPP #-} #if MIN_VERSION_base(4,8,1) #define HAS_SOURCE_LOCATIONS {-# LANGUAGE ImplicitParams #-} #endif module Test.Hspec.ExpectationsSpec (spec) where import Control.Exception import Data.List import Test.Hspec (Spec, describe, it) import Test.HUnit.Lang import Test.Hspec.Expectations #ifdef HAS_SOURCE_LOCATIONS import GHC.SrcLoc import GHC.Stack expectationFailed :: (?loc :: CallStack) => String -> HUnitFailure -> Bool #else expectationFailed :: String -> HUnitFailure -> Bool #endif expectationFailed msg (HUnitFailure err) = (location ++ msg) == err where location :: String #ifdef HAS_SOURCE_LOCATIONS location = case reverse (getCallStack ?loc) of (_, loc) : _ -> srcLocFile loc ++ ":" ++ (show $ srcLocStartLine loc) ++ ":\n" _ -> "" #else location = "" #endif spec :: Spec spec = do describe "shouldBe" $ do it "succeeds if arguments are equal" $ do "foo" `shouldBe` "foo" it "fails if arguments are not equal" $ do ("foo" `shouldBe` "bar") `shouldThrow` expectationFailed "expected: \"bar\"\n but got: \"foo\"" describe "shouldSatisfy" $ do it "succeeds if value satisfies predicate" $ do "" `shouldSatisfy` null it "fails if value does not satisfy predicate" $ do ("foo" `shouldSatisfy` null) `shouldThrow` expectationFailed "predicate failed on: \"foo\"" describe "shouldReturn" $ do it "succeeds if arguments represent equal values" $ do return "foo" `shouldReturn` "foo" it "fails if arguments do not represent equal values" $ do (return "foo" `shouldReturn` "bar") `shouldThrow` expectationFailed "expected: \"bar\"\n but got: \"foo\"" describe "shouldStartWith" $ do it "succeeds if second is prefix of first" $ do "hello world" `shouldStartWith` "hello" it "fails if second is not prefix of first" $ do ("hello world" `shouldStartWith` "world") `shouldThrow` expectationFailed "\"hello world\" does not start with \"world\"" describe "shouldEndWith" $ do it "succeeds if second is suffix of first" $ do "hello world" `shouldEndWith` "world" it "fails if second is not suffix of first" $ do ("hello world" `shouldEndWith` "hello") `shouldThrow` expectationFailed "\"hello world\" does not end with \"hello\"" describe "shouldContain" $ do it "succeeds if second argument is contained in the first" $ do "I'm an hello world message" `shouldContain` "an hello" it "fails if first argument does not contain the second" $ do ("foo" `shouldContain` "bar") `shouldThrow` expectationFailed "\"foo\" does not contain \"bar\"" describe "shouldNotBe" $ do it "succeeds if arguments are not equal" $ do "foo" `shouldNotBe` "bar" it "fails if arguments are equal" $ do ("foo" `shouldNotBe` "foo") `shouldThrow` expectationFailed "not expected: \"foo\"" describe "shouldNotSatisfy" $ do it "succeeds if value does not satisfy predicate" $ do "bar" `shouldNotSatisfy` null it "fails if the value does satisfy predicate" $ do ("" `shouldNotSatisfy` null) `shouldThrow` expectationFailed "predicate succeded on: \"\"" describe "shouldNotReturn" $ do it "succeeds if arguments does not represent equal values" $ do return "foo" `shouldNotReturn` "bar" it "fails if arguments do represent equal values" $ do (return "foo" `shouldNotReturn` "foo") `shouldThrow` expectationFailed "not expected: \"foo\"" describe "shouldNotContain" $ do it "succeeds if second argument is not contained in the first" $ do "I'm an hello world message" `shouldNotContain` "test" it "fails if first argument does contain the second" $ do ("foo abc def" `shouldNotContain` "def") `shouldThrow` expectationFailed "\"foo abc def\" does contain \"def\"" describe "shouldThrow" $ do it "can be used to require a specific exception" $ do throwIO DivideByZero `shouldThrow` (== DivideByZero) it "can be used to require any exception" $ do error "foobar" `shouldThrow` anyException it "can be used to require an exception of a specific type" $ do error "foobar" `shouldThrow` anyErrorCall it "can be used to require a specific exception" $ do error "foobar" `shouldThrow` errorCall "foobar" it "fails, if a required specific exception is not thrown" $ do (throwIO Overflow `shouldThrow` (== DivideByZero)) `shouldThrow` expectationFailed "predicate failed on expected exception: ArithException (arithmetic overflow)" it "fails, if any exception is required, but no exception occurs" $ do (return () `shouldThrow` anyException) `shouldThrow` expectationFailed "did not get expected exception: SomeException" it "fails, if a required exception of a specific type is not thrown" $ do (return () `shouldThrow` anyErrorCall) `shouldThrow` expectationFailed "did not get expected exception: ErrorCall" it "fails, if a required specific exception is not thrown" $ do (error "foo" `shouldThrow` errorCall "foobar") `shouldThrow` expectationFailed "predicate failed on expected exception: ErrorCall (foo)"
soenkehahn/hspec-expectations
test/Test/Hspec/ExpectationsSpec.hs
mit
5,213
0
17
1,104
1,066
535
531
80
1
{-# LANGUAGE OverloadedStrings #-} module Text.Marquee.Writers.HTML (renderHtml, writeHtml, writeHtmlDocument) where -- Control and Data imports import Control.Monad (forM_) import qualified Data.Text as T import Data.List (intercalate) -- Blaze imports import Text.Blaze.Html5 as H import Text.Blaze.Html5.Attributes as A hiding (id) import qualified Text.Blaze.Html.Renderer.String as H -- Own imports import Data.List.Marquee import Text.Marquee.SyntaxTrees.AST hiding (codespan, em) renderHtml :: Html -> String renderHtml = H.renderHtml writeHtml :: Markdown -> Html writeHtml = writeHtml' writeHtmlDocument :: String -> Maybe String -> Markdown -> Html writeHtmlDocument title Nothing md = docTypeHtml $ do H.head . H.title . toHtml $ title H.body . writeHtml' $ md writeHtmlDocument title (Just cssFile) md = docTypeHtml $ do H.head $ do H.title . toHtml $ title H.link ! A.rel "stylesheet" ! A.type_ "text/css" ! (A.href . toValue $ cssFile) H.body . writeHtml' $ md writeHtml' :: Markdown -> Html writeHtml' [] = return () writeHtml' (x:xs) = writeElement x >> writeHtml' xs writeNestedHtml :: Markdown -> Html writeNestedHtml (x : []) = writeSingleElement x writeNestedHtml xs = writeHtml' xs writeElement :: MarkdownElement -> Html writeElement (ThematicBreak) = hr writeElement (Heading n x) = (lookupOr h4 n headings) $ writeInline x writeElement (Indented str) = codeblock "" str writeElement (Fenced info str) = codeblock info str writeElement (HTML x) = preEscapedText x writeElement (Paragraph x) = p $ writeInline x writeElement (Blockquote x) = H.blockquote $ writeHtml' x writeElement (UnorderedList x) = ul $ forM_ x (li . writeNestedHtml) writeElement (OrderedList x) | first /= 1 = ol ! start (toValue first) $ forM_ x (li . writeNestedHtml . snd) | otherwise = ol $ forM_ x (li . writeNestedHtml . snd) where first = fst . Prelude.head $ x writeElement _ = return () writeSingleElement :: MarkdownElement -> Html writeSingleElement (Paragraph x) = writeInline x writeSingleElement x = writeElement x writeInline :: MarkdownInline -> Html writeInline (HardLineBreak) = br writeInline (LineBreak) = toHtml (" " :: String) writeInline (Text x) = H.text x writeInline (Codespan x) = code . H.text $ x writeInline (Bold x) = strong $ writeInline x writeInline (Italic x) = em $ writeInline x writeInline (Link x url Nothing) = (a $ writeInline x) ! href (textValue url) writeInline (Link x url (Just title)) = (a $ writeInline x) ! href (textValue url) ! A.title (textValue title) writeInline (Image x dest mtitle) = img ! alt (textValue . plain $ x) ! src (textValue dest) writeInline (HTMLText x) = preEscapedText x writeInline (Cons x y) = writeInline x >> writeInline y writeInline _ = return () codeblock :: T.Text -> T.Text -> Html codeblock info xs = codeblock' (T.unpack info) (T.unpack $ xs `T.append` "\n") where codeblock' :: String -> String -> Html codeblock' [] = pre . code . toHtml codeblock' info = pre . flip (!) (class_ $ toValue $ "language-" ++ info) . code . toHtml headings :: [(Int, Html -> Html)] headings = [(1, h1), (2, h2), (3, h3), (4, h4), (5, h5), (6, h6)]
DanielRS/marquee
src/Text/Marquee/Writers/HTML.hs
mit
3,395
0
15
782
1,270
662
608
66
2
module ProgrammingInHaskell2.Chap11 where import Data.Char import Data.List import System.IO size :: Int size = 3 type Grid = [[Player]] data Player = O | B | X deriving (Eq, Ord, Show) next :: Player -> Player next O = X next B = B next X = O empty :: Grid empty = replicate size (replicate size B) -- interleave inserts a value between each element in a list. interleave :: a -> [a] -> [a] interleave x [] = [] interleave x [y] = [y] interleave x (y:ys) = y : x : interleave x ys
akimichi/haskell-labo
src/ProgrammingInHaskell2/Chap11.hs
mit
504
0
7
119
207
115
92
19
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-parallelismconfiguration.html module Stratosphere.ResourceProperties.KinesisAnalyticsV2ApplicationParallelismConfiguration where import Stratosphere.ResourceImports -- | Full data type definition for -- KinesisAnalyticsV2ApplicationParallelismConfiguration. See -- 'kinesisAnalyticsV2ApplicationParallelismConfiguration' for a more -- convenient constructor. data KinesisAnalyticsV2ApplicationParallelismConfiguration = KinesisAnalyticsV2ApplicationParallelismConfiguration { _kinesisAnalyticsV2ApplicationParallelismConfigurationAutoScalingEnabled :: Maybe (Val Bool) , _kinesisAnalyticsV2ApplicationParallelismConfigurationConfigurationType :: Val Text , _kinesisAnalyticsV2ApplicationParallelismConfigurationParallelism :: Maybe (Val Integer) , _kinesisAnalyticsV2ApplicationParallelismConfigurationParallelismPerKPU :: Maybe (Val Integer) } deriving (Show, Eq) instance ToJSON KinesisAnalyticsV2ApplicationParallelismConfiguration where toJSON KinesisAnalyticsV2ApplicationParallelismConfiguration{..} = object $ catMaybes [ fmap (("AutoScalingEnabled",) . toJSON) _kinesisAnalyticsV2ApplicationParallelismConfigurationAutoScalingEnabled , (Just . ("ConfigurationType",) . toJSON) _kinesisAnalyticsV2ApplicationParallelismConfigurationConfigurationType , fmap (("Parallelism",) . toJSON) _kinesisAnalyticsV2ApplicationParallelismConfigurationParallelism , fmap (("ParallelismPerKPU",) . toJSON) _kinesisAnalyticsV2ApplicationParallelismConfigurationParallelismPerKPU ] -- | Constructor for 'KinesisAnalyticsV2ApplicationParallelismConfiguration' -- containing required fields as arguments. kinesisAnalyticsV2ApplicationParallelismConfiguration :: Val Text -- ^ 'kavapcConfigurationType' -> KinesisAnalyticsV2ApplicationParallelismConfiguration kinesisAnalyticsV2ApplicationParallelismConfiguration configurationTypearg = KinesisAnalyticsV2ApplicationParallelismConfiguration { _kinesisAnalyticsV2ApplicationParallelismConfigurationAutoScalingEnabled = Nothing , _kinesisAnalyticsV2ApplicationParallelismConfigurationConfigurationType = configurationTypearg , _kinesisAnalyticsV2ApplicationParallelismConfigurationParallelism = Nothing , _kinesisAnalyticsV2ApplicationParallelismConfigurationParallelismPerKPU = Nothing } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-parallelismconfiguration.html#cfn-kinesisanalyticsv2-application-parallelismconfiguration-autoscalingenabled kavapcAutoScalingEnabled :: Lens' KinesisAnalyticsV2ApplicationParallelismConfiguration (Maybe (Val Bool)) kavapcAutoScalingEnabled = lens _kinesisAnalyticsV2ApplicationParallelismConfigurationAutoScalingEnabled (\s a -> s { _kinesisAnalyticsV2ApplicationParallelismConfigurationAutoScalingEnabled = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-parallelismconfiguration.html#cfn-kinesisanalyticsv2-application-parallelismconfiguration-configurationtype kavapcConfigurationType :: Lens' KinesisAnalyticsV2ApplicationParallelismConfiguration (Val Text) kavapcConfigurationType = lens _kinesisAnalyticsV2ApplicationParallelismConfigurationConfigurationType (\s a -> s { _kinesisAnalyticsV2ApplicationParallelismConfigurationConfigurationType = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-parallelismconfiguration.html#cfn-kinesisanalyticsv2-application-parallelismconfiguration-parallelism kavapcParallelism :: Lens' KinesisAnalyticsV2ApplicationParallelismConfiguration (Maybe (Val Integer)) kavapcParallelism = lens _kinesisAnalyticsV2ApplicationParallelismConfigurationParallelism (\s a -> s { _kinesisAnalyticsV2ApplicationParallelismConfigurationParallelism = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-parallelismconfiguration.html#cfn-kinesisanalyticsv2-application-parallelismconfiguration-parallelismperkpu kavapcParallelismPerKPU :: Lens' KinesisAnalyticsV2ApplicationParallelismConfiguration (Maybe (Val Integer)) kavapcParallelismPerKPU = lens _kinesisAnalyticsV2ApplicationParallelismConfigurationParallelismPerKPU (\s a -> s { _kinesisAnalyticsV2ApplicationParallelismConfigurationParallelismPerKPU = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/KinesisAnalyticsV2ApplicationParallelismConfiguration.hs
mit
4,595
0
13
310
449
255
194
38
1
{- Copyright (C) 2001, 2004 Ian Lynagh <igloo@earth.li> Modified by Einar Karttunen to remove dependency on packed strings and autoconf. Modified by John Meacham for code cleanups. 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, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -} {-# OPTIONS -funbox-strict-fields -fglasgow-exts -fno-warn-name-shadowing -O2 #-} module Util.SHA1 (sha1String,sha1file,sha1Bytes,hashToBytes,sha1Handle,ABCDE(..),Hash,emptyHash) where import Control.Monad (unless) import Data.Char (intToDigit,ord) import Foreign import Foreign.C import System.IO import System.IO.Unsafe (unsafePerformIO) type Hash = ABCDE data ABCDE = ABCDE !Word32 !Word32 !Word32 !Word32 !Word32 deriving(Eq,Ord) emptyHash = ABCDE 0 0 0 0 0 data XYZ = XYZ !Word32 !Word32 !Word32 sha1String :: String -> Hash sha1String ss = sha1Bytes (toUTF ss) where -- | Convert Unicode characters to UTF-8. toUTF :: String -> [Word8] toUTF [] = [] toUTF (x:xs) | ord x<=0x007F = (fromIntegral $ ord x):toUTF xs | ord x<=0x07FF = fromIntegral (0xC0 .|. ((ord x `shift` (-6)) .&. 0x1F)): fromIntegral (0x80 .|. (ord x .&. 0x3F)): toUTF xs | otherwise = fromIntegral (0xE0 .|. ((ord x `shift` (-12)) .&. 0x0F)): fromIntegral (0x80 .|. ((ord x `shift` (-6)) .&. 0x3F)): fromIntegral (0x80 .|. (ord x .&. 0x3F)): toUTF xs sha1Bytes :: [Word8] -> Hash sha1Bytes ss = unsafePerformIO $ do let len = length ss plen = sha1_step_1_2_plength len allocaBytes plen $ \ptr -> do pokeArray ptr ss let num_nuls = (55 - len) `mod` 64 pokeArray (advancePtr ptr len) ((128:replicate num_nuls 0)++(reverse $ size_split 8 (fromIntegral len*8))) let abcde = sha1_step_3_init let ptr' = castPtr ptr unless big_endian $ fiddle_endianness ptr' plen res <- sha1_step_4_main abcde ptr' plen return res {-# NOINLINE sha1Handle #-} sha1Handle :: Handle -> IO Hash sha1Handle h = do hSeek h AbsoluteSeek 0 len <- hFileSize h len <- return $ fromIntegral len let plen = sha1_step_1_2_plength len allocaBytes plen $ \ptr -> do cnt <- hGetBuf h ptr len unless (cnt == len) $ fail "sha1File - read returned too few bytes" hSeek h AbsoluteSeek 0 let num_nuls = (55 - len) `mod` 64 pokeArray (advancePtr ptr len) ((128:replicate num_nuls 0)++(reverse $ size_split 8 (fromIntegral len*8))) let abcde = sha1_step_3_init let ptr' = castPtr ptr unless big_endian $ fiddle_endianness ptr' plen res <- sha1_step_4_main abcde ptr' plen return res {-# NOINLINE sha1file #-} sha1file :: FilePath -> IO Hash sha1file fp = do h <- openBinaryFile fp ReadMode hash <- sha1Handle h hClose h return hash big_endian = unsafePerformIO $ do let x :: Word32 x = 0x12345678 s <- with x $ \ptr -> peekCStringLen (castPtr ptr,4) case s of "\x12\x34\x56\x78" -> return True "\x78\x56\x34\x12" -> return False _ -> error "Testing endianess failed" fiddle_endianness :: Ptr Word32 -> Int -> IO () fiddle_endianness p 0 = p `seq` return () fiddle_endianness p n = do x <- peek p poke p $ shiftL x 24 .|. shiftL (x .&. 0xff00) 8 .|. (shiftR x 8 .&. 0xff00) .|. shiftR x 24 fiddle_endianness (p `advancePtr` 1) (n - 4) -- sha1_step_1_2_pad_length assumes the length is at most 2^61. -- This seems reasonable as the Int used to represent it is normally 32bit, -- but obviously could go wrong with large inputs on 64bit machines. -- The PackedString library should probably move to Word64s if this is an -- issue, though. -- -- sha1_step_1_2_pad_length :: PackedString -> PackedString -- sha1_step_1_2_pad_length s -- = let len = lengthPS s -- num_nuls = (55 - len) `mod` 64 -- padding = 128:replicate num_nuls 0 -- len_w8s = reverse $ size_split 8 (fromIntegral len*8) -- in concatLenPS (len + 1 + num_nuls + 8) -- [s, packWords padding, packWords len_w8s] sha1_step_1_2_plength :: Int -> Int sha1_step_1_2_plength len = (len + 1 + num_nuls + 8) where num_nuls = (55 - len) `mod` 64 size_split :: Int -> Integer -> [Word8] size_split 0 _ = [] size_split p n = fromIntegral d:size_split (p-1) n' where (n', d) = divMod n 256 sha1_step_3_init :: ABCDE sha1_step_3_init = ABCDE 0x67452301 0xefcdab89 0x98badcfe 0x10325476 0xc3d2e1f0 sha1_step_4_main :: ABCDE -> Ptr Word32 -> Int -> IO ABCDE sha1_step_4_main abcde _ 0 = return $! abcde sha1_step_4_main (ABCDE a0@a b0@b c0@c d0@d e0@e) s len = do (e, b) <- doit f1 0x5a827999 (x 0) a b c d e (d, a) <- doit f1 0x5a827999 (x 1) e a b c d (c, e) <- doit f1 0x5a827999 (x 2) d e a b c (b, d) <- doit f1 0x5a827999 (x 3) c d e a b (a, c) <- doit f1 0x5a827999 (x 4) b c d e a (e, b) <- doit f1 0x5a827999 (x 5) a b c d e (d, a) <- doit f1 0x5a827999 (x 6) e a b c d (c, e) <- doit f1 0x5a827999 (x 7) d e a b c (b, d) <- doit f1 0x5a827999 (x 8) c d e a b (a, c) <- doit f1 0x5a827999 (x 9) b c d e a (e, b) <- doit f1 0x5a827999 (x 10) a b c d e (d, a) <- doit f1 0x5a827999 (x 11) e a b c d (c, e) <- doit f1 0x5a827999 (x 12) d e a b c (b, d) <- doit f1 0x5a827999 (x 13) c d e a b (a, c) <- doit f1 0x5a827999 (x 14) b c d e a (e, b) <- doit f1 0x5a827999 (x 15) a b c d e (d, a) <- doit f1 0x5a827999 (m 16) e a b c d (c, e) <- doit f1 0x5a827999 (m 17) d e a b c (b, d) <- doit f1 0x5a827999 (m 18) c d e a b (a, c) <- doit f1 0x5a827999 (m 19) b c d e a (e, b) <- doit f2 0x6ed9eba1 (m 20) a b c d e (d, a) <- doit f2 0x6ed9eba1 (m 21) e a b c d (c, e) <- doit f2 0x6ed9eba1 (m 22) d e a b c (b, d) <- doit f2 0x6ed9eba1 (m 23) c d e a b (a, c) <- doit f2 0x6ed9eba1 (m 24) b c d e a (e, b) <- doit f2 0x6ed9eba1 (m 25) a b c d e (d, a) <- doit f2 0x6ed9eba1 (m 26) e a b c d (c, e) <- doit f2 0x6ed9eba1 (m 27) d e a b c (b, d) <- doit f2 0x6ed9eba1 (m 28) c d e a b (a, c) <- doit f2 0x6ed9eba1 (m 29) b c d e a (e, b) <- doit f2 0x6ed9eba1 (m 30) a b c d e (d, a) <- doit f2 0x6ed9eba1 (m 31) e a b c d (c, e) <- doit f2 0x6ed9eba1 (m 32) d e a b c (b, d) <- doit f2 0x6ed9eba1 (m 33) c d e a b (a, c) <- doit f2 0x6ed9eba1 (m 34) b c d e a (e, b) <- doit f2 0x6ed9eba1 (m 35) a b c d e (d, a) <- doit f2 0x6ed9eba1 (m 36) e a b c d (c, e) <- doit f2 0x6ed9eba1 (m 37) d e a b c (b, d) <- doit f2 0x6ed9eba1 (m 38) c d e a b (a, c) <- doit f2 0x6ed9eba1 (m 39) b c d e a (e, b) <- doit f3 0x8f1bbcdc (m 40) a b c d e (d, a) <- doit f3 0x8f1bbcdc (m 41) e a b c d (c, e) <- doit f3 0x8f1bbcdc (m 42) d e a b c (b, d) <- doit f3 0x8f1bbcdc (m 43) c d e a b (a, c) <- doit f3 0x8f1bbcdc (m 44) b c d e a (e, b) <- doit f3 0x8f1bbcdc (m 45) a b c d e (d, a) <- doit f3 0x8f1bbcdc (m 46) e a b c d (c, e) <- doit f3 0x8f1bbcdc (m 47) d e a b c (b, d) <- doit f3 0x8f1bbcdc (m 48) c d e a b (a, c) <- doit f3 0x8f1bbcdc (m 49) b c d e a (e, b) <- doit f3 0x8f1bbcdc (m 50) a b c d e (d, a) <- doit f3 0x8f1bbcdc (m 51) e a b c d (c, e) <- doit f3 0x8f1bbcdc (m 52) d e a b c (b, d) <- doit f3 0x8f1bbcdc (m 53) c d e a b (a, c) <- doit f3 0x8f1bbcdc (m 54) b c d e a (e, b) <- doit f3 0x8f1bbcdc (m 55) a b c d e (d, a) <- doit f3 0x8f1bbcdc (m 56) e a b c d (c, e) <- doit f3 0x8f1bbcdc (m 57) d e a b c (b, d) <- doit f3 0x8f1bbcdc (m 58) c d e a b (a, c) <- doit f3 0x8f1bbcdc (m 59) b c d e a (e, b) <- doit f2 0xca62c1d6 (m 60) a b c d e (d, a) <- doit f2 0xca62c1d6 (m 61) e a b c d (c, e) <- doit f2 0xca62c1d6 (m 62) d e a b c (b, d) <- doit f2 0xca62c1d6 (m 63) c d e a b (a, c) <- doit f2 0xca62c1d6 (m 64) b c d e a (e, b) <- doit f2 0xca62c1d6 (m 65) a b c d e (d, a) <- doit f2 0xca62c1d6 (m 66) e a b c d (c, e) <- doit f2 0xca62c1d6 (m 67) d e a b c (b, d) <- doit f2 0xca62c1d6 (m 68) c d e a b (a, c) <- doit f2 0xca62c1d6 (m 69) b c d e a (e, b) <- doit f2 0xca62c1d6 (m 70) a b c d e (d, a) <- doit f2 0xca62c1d6 (m 71) e a b c d (c, e) <- doit f2 0xca62c1d6 (m 72) d e a b c (b, d) <- doit f2 0xca62c1d6 (m 73) c d e a b (a, c) <- doit f2 0xca62c1d6 (m 74) b c d e a (e, b) <- doit f2 0xca62c1d6 (m 75) a b c d e (d, a) <- doit f2 0xca62c1d6 (m 76) e a b c d (c, e) <- doit f2 0xca62c1d6 (m 77) d e a b c (b, d) <- doit f2 0xca62c1d6 (m 78) c d e a b (a, c) <- doit f2 0xca62c1d6 (m 79) b c d e a let abcde' = ABCDE (a0 + a) (b0 + b) (c0 + c) (d0 + d) (e0 + e) sha1_step_4_main abcde' (s `advancePtr` 16) (len - 64) where {-# INLINE f1 #-} f1 (XYZ x y z) = (x .&. y) .|. ((complement x) .&. z) {-# INLINE f2 #-} f2 (XYZ x y z) = x `xor` y `xor` z {-# INLINE f3 #-} f3 (XYZ x y z) = (x .&. y) .|. (x .&. z) .|. (y .&. z) {-# INLINE x #-} x n = peek (s `advancePtr` n) {-# INLINE m #-} m n = do let base = s `advancePtr` (n .&. 15) x0 <- peek base x1 <- peek (s `advancePtr` ((n - 14) .&. 15)) x2 <- peek (s `advancePtr` ((n - 8) .&. 15)) x3 <- peek (s `advancePtr` ((n - 3) .&. 15)) let res = rotateL (x0 `xor` x1 `xor` x2 `xor` x3) 1 poke base res return res {-# INLINE doit #-} doit f k i a b c d e = a `seq` c `seq` do i' <- i return (rotateL a 5 + f (XYZ b c d) + e + i' + k, rotateL b 30) hashToBytes :: Hash -> [Word8] hashToBytes (ABCDE a b c d e) = tb a . tb b . tb c . tb d . tb e $ [] where tb :: Word32 -> [Word8] -> [Word8] tb n = showIt 4 n showIt :: Int -> Word32 -> [Word8] -> [Word8] showIt 0 _ r = r showIt i x r = case quotRem x 256 of (y, z) -> let c = fromIntegral z in c `seq` showIt (i-1) y (c:r) instance Show ABCDE where showsPrec _ (ABCDE a b c d e) = showAsHex a . showAsHex b . showAsHex c . showAsHex d . showAsHex e showAsHex :: Word32 -> ShowS showAsHex n = showIt 8 n where showIt :: Int -> Word32 -> String -> String showIt 0 _ r = r showIt i x r = case quotRem x 16 of (y, z) -> let c = intToDigit (fromIntegral z) in c `seq` showIt (i-1) y (c:r)
dec9ue/jhc_copygc
src/Util/SHA1.hs
gpl-2.0
11,601
0
20
3,853
5,236
2,638
2,598
-1
-1
{-# OPTIONS_GHC -F -pgmF hspec-discover #-} -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or (at -- your option) any later version. -- -- This program is distributed in the hope that it will be useful, but -- WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>.
pharpend/comarkdown
tests/Spec.hs
gpl-3.0
693
0
2
122
15
14
1
1
0
-- Copyright (C) 2014 Boucher, Antoni <bouanto@gmail.com> -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. {-| Module : PrettyPrinter Description : Pretty printer for HaTeX documents. Copyright : © Antoni Boucher, 2014 License : GPL-3 Maintener : bouanto@zoho.com Stability : experimental Portability : POSIX This module provides a pretty printer for HaTeX documents which outputs a human-readable LaTeX document. -} module PrettyPrinter (prettyPrint) where import Data.Monoid (mconcat) import Text.LaTeX.Base.Syntax (LaTeX (TeXComm, TeXCommS, TeXComment, TeXEmpty, TeXEnv, TeXLineBreak, TeXRaw, TeXSeq), TeXArg (FixArg, OptArg)) import Text.PrettyPrint.Free (Pretty (pretty), (<>), Doc, backslash, braces, brackets, empty, indent, line, space, text) -- |Pretty print a LaTeX document in a human-readable format. prettyPrint :: LaTeX -> String prettyPrint latex = show (latex2Doc latex False) latex2Doc :: LaTeX -> Bool -> Doc () latex2Doc (TeXComm n []) _ = backslash <> text n <> text "{}" <> line <> line latex2Doc (TeXComm "cookingpart" args) _ = backslash <> text "cookingpart" <> mconcat (map latexArg2Doc args) <> line latex2Doc (TeXComm "item" args@[_]) _ = backslash <> text "item" <> mconcat (map latexArg2Doc args) <> space latex2Doc (TeXComm n args) newLine = backslash <> text n <> mconcat (map latexArg2Doc args) <> line <> newLineOrEmpty newLine latex2Doc (TeXCommS n) newLine = backslash <> text n <> newLineOrEmpty newLine latex2Doc (TeXComment comment) _ = text "% " <> pretty comment <> line <> line latex2Doc (TeXEnv environment _ latex) _ = backslash <> text "begin" <> braces (text environment) <> line <> indent 4 (latex2Doc latex False) <> line <> backslash <> text "end" <> braces (text environment) <> line <> newLineOrEmpty (environment /= "steps") latex2Doc TeXEmpty _ = empty latex2Doc (TeXLineBreak _ _) _ = text "\\\\" <> line latex2Doc (TeXRaw rawText) newLine = pretty rawText <> newLineOrEmpty newLine latex2Doc (TeXSeq latex1@(TeXCommS "item ") latex2@(TeXSeq _ _)) _ = latex2Doc latex1 False <> latex2Doc latex2 True latex2Doc (TeXSeq latex1@(TeXCommS "item ") latex2) _ = latex2Doc latex1 False <> latex2Doc latex2 False latex2Doc (TeXSeq latex1 latex2) newLine = latex2Doc latex1 newLine <> latex2Doc latex2 True latexArg2Doc :: TeXArg -> Doc () latexArg2Doc (FixArg arg) = braces $ latex2Doc arg False latexArg2Doc (OptArg arg) = brackets $ latex2Doc arg False newLineOrEmpty :: Bool -> Doc () newLineOrEmpty newLine = if newLine then line else empty
antoyo/recettesduquebec2tex
src/PrettyPrinter.hs
gpl-3.0
3,146
0
16
534
801
421
380
29
2
import Control.Applicative import Control.Concurrent import Control.Monad import Control.Monad.IfElse import Data.IORef import Debug.Trace import FRP.Yampa as Yampa import Text.Printf import Game import Display import Input import Graphics.UI.Extra.SDL main :: IO () main = do initializeDisplay timeRef <- initializeTimeRef controllerRef <- initializeInputDevices res <- loadResources initGraphs res reactimate (senseInput controllerRef) (\_ -> do -- Get clock and new input mInput <- senseInput controllerRef dtSecs <- senseTime timeRef mInput -- trace ("Time : " ++ printf "%.5f" dtSecs) $ return (if controllerPause mInput then 0 else dtSecs, Just mInput) ) (\_ (e,c) -> do render res e return (controllerExit c) ) (wholeGame &&& arr id) senseTime :: IORef Int -> Controller -> IO DTime senseTime timeRef = \mInput -> let tt = if controllerSlow mInput then (/10) else id tt1 = if controllerSuperSlow mInput then (/100) else tt tt2 = if controllerFast mInput then (*10) else tt1 in (tt2 . milisecsToSecs) <$> senseTimeRef timeRef
keera-studios/pang-a-lambda
Experiments/splitballs/Main.hs
gpl-3.0
1,269
0
15
388
339
179
160
33
4
{-# LANGUAGE NamedFieldPuns #-} module Frame.Goaway ( getPayload , putPayload , Payload , mkPayload , getErrorCode , getDebugData , toString ) where import Data.Binary.Get (Get) import qualified Data.Binary.Get as Get import Data.Binary.Put (Put) import qualified Data.Binary.Put as Put import Control.Monad.Except (ExceptT) import qualified Control.Monad.Except as Except import Control.Monad.Trans (lift) import qualified Data.Bits as Bits import Data.ByteString.Lazy (ByteString) import ProjectPrelude import ErrorCodes data Payload = Payload { lastStreamId :: StreamId , errorCode :: ErrorCode , debugData :: ByteString } mkPayload :: ErrorCode -> ByteString -> Payload mkPayload errorCode debugData = Payload { lastStreamId = StreamId 1, errorCode, debugData } getErrorCode :: Payload -> ErrorCode getErrorCode = errorCode getDebugData :: Payload -> ByteString getDebugData = debugData getPayload :: FrameLength -> FrameFlags -> StreamId -> ExceptT ConnError Get Payload getPayload fLength _ _ = if fLength < 8 then Except.throwError $ ConnError ConnectionError FrameSizeError else do lastSid <- lift $ flip Bits.clearBit 31 <$> Get.getWord32be errorCode <- lift $ errorCodeFromWord32 <$> Get.getWord32be debugData <- lift $ Get.getLazyByteString (fromIntegral $ fLength - 8) return $ Payload { lastStreamId = StreamId lastSid, errorCode, debugData } putPayload :: Payload -> Put putPayload (Payload {lastStreamId = StreamId lastSid, errorCode, debugData }) = do Put.putWord32be lastSid Put.putWord32be $ errorCodeToWord32 errorCode Put.putLazyByteString debugData toString :: String -> Payload -> String toString prefix Payload { lastStreamId, errorCode, debugData } = unlines $ map (prefix++) [ "last stream id: " ++ show lastStreamId, "error code: " ++ show errorCode, "debug data: " ++ show debugData ]
authchir/SoSe17-FFP-haskell-http2-server
src/Frame/Goaway.hs
gpl-3.0
2,004
0
13
437
516
289
227
49
2
{-# language FlexibleInstances #-} module Rasa.Internal.Utility ( Width , Height , Renderable(..) , RenderInfo(..) , ScrollPos , cropToViewport , styleText ) where import Eve import Rasa.Internal.Styles import Rasa.Internal.BufActions import Rasa.Internal.Buffer import Rasa.Internal.Range import Control.Lens import Data.Bifunctor import qualified Yi.Rope as Y type Width = Int type Height = Int -- | RenderInfo is the data necessary to render something; it consists of a block of -- text with its associated styles. It is a Monoid and can be appended with other 'RenderInfo's. data RenderInfo = RenderInfo Y.YiString Styles -- | Appends to RenderInfo by appending the text and styles while preserving -- proper text/style alignment instance Monoid RenderInfo where mempty = RenderInfo mempty mempty RenderInfo txtA stylesA `mappend` RenderInfo txtB stylesB = RenderInfo (txtA `mappend` txtB) (mappend stylesA $ first (moveRange (sizeOf txtA)) <$> stylesB) -- | Represents how to render an entity class Renderable r where render :: Width -> Height -> ScrollPos -> r -> App (Maybe RenderInfo) instance Renderable r => Renderable (Maybe r) where render width height scrollPos (Just r) = render width height scrollPos r render _ _ _ Nothing = return Nothing instance Renderable BufRef where render _ height scrollPos bufRef = bufDo bufRef $ do txt <- getText styles <- getStyles return $ cropToViewport height scrollPos (RenderInfo txt styles) instance Renderable Y.YiString where render _ height scrollPos txt = return . Just $ cropToViewport height scrollPos (RenderInfo txt []) instance Renderable RenderInfo where render _ _ _ r = return (Just r) type ScrollPos = Int -- | Crop text verticaly to only the visible portion according to viewport height and -- scroll position. cropToViewport :: Height -> ScrollPos -> RenderInfo -> RenderInfo cropToViewport height scrollAmt (RenderInfo txt styles) = RenderInfo trimmedText adjustedStyles where adjustedStyles :: Styles adjustedStyles = first adjustStylePositions <$> styles adjustStylePositions :: CrdRange -> CrdRange adjustStylePositions = both.coordRow -~ scrollAmt trimmedText :: Y.YiString trimmedText = Y.concat . take height . drop scrollAmt . Y.lines' $ txt -- | Add a style to some text resulting in a 'RenderInfo' styleText :: Y.YiString -> Style -> RenderInfo styleText txt style = RenderInfo txt [Span (Range (Coord 0 0) (sizeOf txt)) style]
samcal/rasa
rasa/src/Rasa/Internal/Utility.hs
gpl-3.0
2,510
0
14
465
637
337
300
-1
-1
module P11CurrencySpec (main,spec) where import Test.Hspec import Test.Hspec.QuickCheck import P11Currency hiding (main) import Text.Printf (printf) main :: IO () main = hspec spec spec = do describe "getDollars" $ do prop "has the property of showing twice any number when the rateTo is 200 (i.e. 200%)" $ \x -> getDollars x 200 `shouldBe` printf "%0.2f" (2*x) prop "has the property of showing half any number when the rateTo is 50" $ \x -> getDollars x 50 `shouldBe` printf "%0.2f" (0.5*x) describe "rateTo" $ do prop "has the property of of converting any amount of euros valued at $200 to the equivalent exchange rate" $ \x -> rateTo "200" x `shouldBe` (x/200) * 100
ciderpunx/57-exercises-for-programmers
test/P11CurrencySpec.hs
gpl-3.0
710
0
15
151
198
104
94
16
1
-- | Mathematical utility functions. module Util.Maths (percentage, roundUp) where -- | Calculate the first argument as a percentage of the second. percentage :: Int -> Int -> Float percentage num denom = fromIntegral (num * 100) / fromIntegral denom -- | Round-up integer n to the nearest m. E.g. roundUp 67 20 = 80. roundUp :: Int -> Int -> Int roundUp n m = (n + m - 1) `div` m * m
dwdyer/anorak
src/haskell/Util/Maths.hs
gpl-3.0
407
0
9
97
101
56
45
6
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE RecordWildCards #-} {-# OPTIONS_GHC -fno-warn-orphans #-} -- | -- Module : Network.Bouquet -- Copyright : (c) 2013 Kim Altintop <kim.altintop@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 : Kim Altintop <kim.altintop@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- module Network.Bouquet ( Bouquet , BouquetConf(..) -- * operations on the Bouquet monad , runBouquet , retry , reconsider -- * running IO actions in the Bouquet monad , async , latencyAware , pinned -- * monitoring and diagnostics , getLatencies -- * re-exports , Async ) where import Control.Applicative import Control.Concurrent (threadDelay) import Control.Concurrent.Async (Async) import Control.Concurrent.STM hiding (retry) import Control.Monad import Control.Monad.CatchIO import Control.Monad.IO.Class import Control.Monad.Trans.Reader import Data.Bits (shiftL) import Data.Hashable import Data.HashMap.Strict (HashMap) import Data.IORef import Data.List ((\\), intersect, sortBy) import Data.Ord (comparing) import Data.Pool import Data.Word import qualified Control.Concurrent.Async as Async import qualified Control.Exception as E import qualified Data.HashMap.Strict as H import Network.Bouquet.Internal data LeBouquet k a = LeB { _pools :: !(HashMap k (Pool a)) , _weighteds :: [k] , _scores :: !(HashMap k [Double]) } data BouquetEnv k a = Env { _le_bouquet :: !(TVar (LeBouquet k a)) , _refcount :: !(IORef Word) , _sampleWin :: !Int } newtype Bouquet h r a = Bouquet { unBouquet :: ReaderT (BouquetEnv h r) IO a } deriving (Applicative, Functor, Monad, MonadIO, MonadCatchIO, MonadPlus) instance Alternative (Bouquet h r) where empty = Bouquet $! mzero (<|>) = mplus data BouquetConf h a = BouquetConf { addrs :: [h] , acquire :: h -> IO a , release :: a -> IO () , sampleWindow :: Int } -- | Run the 'Bouquet' monad runBouquet :: (Eq h, Hashable h, MonadIO m) => BouquetConf h r -> Bouquet h r a -> m a runBouquet BouquetConf{..} b = liftIO $ bracket setup destroy (runReaderT (unBouquet b)) where setup = do pools <- H.fromList . zip addrs <$> mapM createPool' addrs refcnt <- newIORef 1 let scores = H.fromList $ flip (,) [] `map` addrs le <- newTVarIO $ LeB pools [] scores return $ Env le refcnt sampleWindow createPool' addr = createPool (acquire addr) release 1 1 1 -- | Run the 'Bouquet' monad asynchronously. 'wait' from the async package can -- be used to block on the result. async :: Bouquet h r a -> Bouquet h r (Async a) async b = Bouquet $ do e <- ask liftIO $ do atomicModifyIORef' (_refcount e) $ \ n -> (succ n, ()) Async.async $ runReaderT (unBouquet b) e `E.finally` destroy e -- | Run the action by trying to acquire a connection from the given host pool. -- -- The function returns immediately if no connection from the given host pool -- can be acquired. The latency of the action is sampled, so that it affects -- subsequent use of 'latencyAware'. pinned :: (Eq h, Hashable h) => h -> (r -> IO a) -> Bouquet h r (Maybe a) pinned host act = Bouquet $ do le <- asks _le_bouquet sw <- asks _sampleWin pools <- liftIO $ _pools <$> readTVarIO le maybe (return Nothing) (\ pool -> do res <- liftIO $ tryWithResource pool (measure . act) case res of Nothing -> return Nothing Just (lat,a) -> do !_ <- liftIO $ sample host lat sw le return (Just a)) (H.lookup host pools) -- | Run the action by trying to acquire a connection from the least-latency -- host pool. -- -- Note that the function returns immediately with 'Nothing' if no connection -- can be acquired. You may want to use 'retrying' to increase the chance of -- getting a connection to another host. -- -- Also note that exceptions thrown from the action are not handled. latencyAware :: (Eq h, Hashable h) => (r -> IO a) -> Bouquet h r (Maybe a) latencyAware act = Bouquet $ do le_tv <- asks _le_bouquet sw <- asks _sampleWin le <- liftIO $ readTVarIO le_tv let pools = _pools le whs = _weighteds le host = head whs pool = pools H.! host res <- liftIO $ tryWithResource pool (measure . act) case res of Nothing -> return Nothing Just (lat,a) -> do liftIO $ do reshuffle <- sample host lat sw le_tv when reshuffle . atomically . modifyTVar le_tv $ \ le' -> le' { _weighteds = map fst . sortBy (comparing snd) $ map scores' (H.toList (_scores le')) } return $ Just a where scores' :: (k, [Double]) -> (k, Double) scores' (k, ss) = let avg = sum ss / fromIntegral (length ss) in (k, avg) -- | Repeatedly run the 'Bouquet' monad up to N times if an exception occurs. -- -- If after N attempts we still don't have a result value, we return the last -- exception in a 'Left'. Note that subsequent attempts are subject to -- expontential backoff, using 'threadDelay' to sleep in between attempts. Thus, -- you may want to run this within 'async'. -- -- Warning: using 'retry' is never a sane default. Since we handle all -- exceptions uniformly, it is impossible to tell whether it is safe to retry. retry :: Exception e => Int -> Bouquet h r a -> Bouquet h r (Either e a) retry max_attempts b = Bouquet $ ask >>= liftIO . go 0 where go attempt e = do _ <- liftIO $ threadDelay (backoff attempt * 1000) x <- (Right <$> runReaderT (unBouquet b) e) `catch` (return . Left) if isRight x || attempt == max_attempts then return x else go (attempt + 1) e isRight (Right _) = True isRight (Left _) = False backoff attempt = 1 `shiftL` (attempt - 1) -- | Update the bouquet with a new list of hosts. -- -- Note that this function is threadsafe (it is safe to use any other function -- in this package concurrently), but not atomic: running multiple -- 'reconsider'ations concurrently may yield unexpected results. It is therefore -- recommended to only allow one thread per program to 'reconsider' the bouquet. reconsider :: (Eq h, Hashable h) => [h] -> (h -> IO r) -> (r -> IO ()) -> Bouquet h r () reconsider hs acquire release = Bouquet $ do le_tv <- asks _le_bouquet liftIO $ do -- 'createPool' requires IO, thus we can determine additions only -- through a snapshot read add <- (hs \\) . H.keys . _pools <$> readTVarIO le_tv pools' <- zip add <$> mapM createPool' add let scores' = flip (,) [] `map` add atomically . modifyTVar le_tv $ \ le -> let rm = H.keys (_pools le) \\ hs pools'' = update (_pools le) pools' rm scores'' = update (_scores le) scores' rm whs' = _weighteds le `intersect` hs ++ (hs \\ _weighteds le) in le { _pools = pools'', _scores = scores'', _weighteds = whs' } where update m ins del = foldl hdelete (foldl hinsert m ins) del hinsert m (x,y) = H.insert x y m hdelete = flip H.delete createPool' addr = createPool (acquire addr) release 1 1 1 -- | Get the currently sampled latencies getLatencies :: Bouquet h r (HashMap h [Double]) getLatencies = Bouquet $ do le_tv <- asks _le_bouquet liftIO $ _scores <$> readTVarIO le_tv -- -- Internal -- -- | Sample a latency value for the given host. Returns 'True' if the sample -- window is full. sample :: (Eq h, Hashable h) => h -> Double -> Int -> TVar (LeBouquet h a) -> IO Bool sample host score sampleWindow tv = atomically $ do scores <- _scores <$> readTVar tv maybe (return False) (\ xs -> do let full = length xs >= sampleWindow avg = sum xs / fromIntegral (length xs) scores' = H.insert host (score : if full then [avg] else xs) scores modifyTVar' tv $ \ le -> le { _scores = scores' } return full) (H.lookup host scores) destroy :: BouquetEnv h r -> IO () destroy Env{..} = do n <- atomicModifyIORef' _refcount $ \ n -> (pred n, n) when (n == 1) . atomically . writeTVar _le_bouquet $ LeB H.empty [] H.empty -- todo: can't do anything about live resources in the pools, except letting -- GC kick in return ()
kim/bouquet
src/Network/Bouquet.hs
mpl-2.0
9,348
0
25
2,904
2,446
1,282
1,164
176
3
{-# 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.Plus.Activities.List -- 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) -- -- Shut down. See https:\/\/developers.google.com\/+\/api-shutdown for more -- details. -- -- /See:/ <https://developers.google.com/+/api/ Google+ API Reference> for @plus.activities.list@. module Network.Google.Resource.Plus.Activities.List ( -- * REST Resource ActivitiesListResource -- * Creating a Request , activitiesList , ActivitiesList -- * Request Lenses , alCollection , alUserId , alPageToken , alMaxResults ) where import Network.Google.Plus.Types import Network.Google.Prelude -- | A resource alias for @plus.activities.list@ method which the -- 'ActivitiesList' request conforms to. type ActivitiesListResource = "plus" :> "v1" :> "people" :> Capture "userId" Text :> "activities" :> Capture "collection" ActivitiesListCollection :> QueryParam "pageToken" Text :> QueryParam "maxResults" (Textual Word32) :> QueryParam "alt" AltJSON :> Get '[JSON] ActivityFeed -- | Shut down. See https:\/\/developers.google.com\/+\/api-shutdown for more -- details. -- -- /See:/ 'activitiesList' smart constructor. data ActivitiesList = ActivitiesList' { _alCollection :: !ActivitiesListCollection , _alUserId :: !Text , _alPageToken :: !(Maybe Text) , _alMaxResults :: !(Textual Word32) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ActivitiesList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'alCollection' -- -- * 'alUserId' -- -- * 'alPageToken' -- -- * 'alMaxResults' activitiesList :: ActivitiesListCollection -- ^ 'alCollection' -> Text -- ^ 'alUserId' -> ActivitiesList activitiesList pAlCollection_ pAlUserId_ = ActivitiesList' { _alCollection = pAlCollection_ , _alUserId = pAlUserId_ , _alPageToken = Nothing , _alMaxResults = 20 } -- | The collection of activities to list. alCollection :: Lens' ActivitiesList ActivitiesListCollection alCollection = lens _alCollection (\ s a -> s{_alCollection = a}) -- | The ID of the user to get activities for. The special value \"me\" can -- be used to indicate the authenticated user. alUserId :: Lens' ActivitiesList Text alUserId = lens _alUserId (\ s a -> s{_alUserId = a}) -- | The continuation token, which is used to page through large result sets. -- To get the next page of results, set this parameter to the value of -- \"nextPageToken\" from the previous response. alPageToken :: Lens' ActivitiesList (Maybe Text) alPageToken = lens _alPageToken (\ s a -> s{_alPageToken = a}) -- | The maximum number of activities to include in the response, which is -- used for paging. For any response, the actual number returned might be -- less than the specified maxResults. alMaxResults :: Lens' ActivitiesList Word32 alMaxResults = lens _alMaxResults (\ s a -> s{_alMaxResults = a}) . _Coerce instance GoogleRequest ActivitiesList where type Rs ActivitiesList = ActivityFeed type Scopes ActivitiesList = '["https://www.googleapis.com/auth/plus.login", "https://www.googleapis.com/auth/plus.me"] requestClient ActivitiesList'{..} = go _alUserId _alCollection _alPageToken (Just _alMaxResults) (Just AltJSON) plusService where go = buildClient (Proxy :: Proxy ActivitiesListResource) mempty
brendanhay/gogol
gogol-plus/gen/Network/Google/Resource/Plus/Activities/List.hs
mpl-2.0
4,327
0
16
977
561
333
228
83
1
module Shapes ( Point(..) , Shape(..) , area , nudge , baseCircle , baseRect ) where data Point = Point Float Float deriving (Show) data Shape = Circle Point Float | Rectangle Point Point deriving (Show) area :: Shape -> Float area (Circle _ r) = pi * r^2 area (Rectangle (Point x1 y1) (Point x2 y2)) = (abs $ x2 - x1) * (abs $ y2 - y1) nudge :: Shape -> Float -> Float -> Shape nudge (Circle (Point x y) r) dx dy = Circle (Point (x + dx) (y + dy)) r nudge (Rectangle (Point x1 y1) (Point x2 y2)) dx dy = Rectangle (Point (x1 + dx) (y1 + dy)) (Point (x2 + dx) (y2 + dy)) baseCircle :: Float -> Shape baseCircle r = Circle (Point 0 0) r baseRect :: Float -> Float -> Shape baseRect width height = Rectangle (Point 0 0) (Point width height)
alexliew/learn_you_a_haskell
code/shapes.hs
unlicense
747
0
9
161
397
211
186
20
1
module Traffic (TrafficLight(..) )where data TrafficLight = Red | Yellow | Green instance Eq TrafficLight where Red == Red = True Yellow == Yellow = True Green == Green = True _ == _ = False instance Show TrafficLight where show Red = "Red light" show Yellow = "Yellow light" show Green = "Green light"
EricYT/Haskell
src/chapter-7-4.hs
apache-2.0
335
0
6
87
110
57
53
12
0
module Handler.AboutUs where import Import getAboutUsR :: Handler RepHtml getAboutUsR = defaultLayout $ do liftIO $ logd "GET AboutUs" h2id <- lift newIdent setTitle "WebToInk AboutUs" $(widgetFile "aboutUs")
thlorenz/WebToInk
webtoink/Handler/AboutUs.hs
bsd-2-clause
228
0
10
47
62
29
33
8
1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QPrintDialog.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:21 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QPrintDialog ( QqPrintDialog(..) ,qPrintDialog_delete ,qPrintDialog_deleteLater ) where import Foreign.C.Types import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Enums.Gui.QPaintDevice import Qtc.Enums.Core.Qt 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 (QPrintDialog ()) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QPrintDialog_userMethod cobj_qobj (toCInt evid) foreign import ccall "qtc_QPrintDialog_userMethod" qtc_QPrintDialog_userMethod :: Ptr (TQPrintDialog a) -> CInt -> IO () instance QuserMethod (QPrintDialogSc a) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QPrintDialog_userMethod cobj_qobj (toCInt evid) instance QuserMethod (QPrintDialog ()) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QPrintDialog_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj foreign import ccall "qtc_QPrintDialog_userMethodVariant" qtc_QPrintDialog_userMethodVariant :: Ptr (TQPrintDialog a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) instance QuserMethod (QPrintDialogSc a) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QPrintDialog_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj class QqPrintDialog x1 where qPrintDialog :: x1 -> IO (QPrintDialog ()) instance QqPrintDialog ((QPrinter t1)) where qPrintDialog (x1) = withQPrintDialogResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog cobj_x1 foreign import ccall "qtc_QPrintDialog" qtc_QPrintDialog :: Ptr (TQPrinter t1) -> IO (Ptr (TQPrintDialog ())) instance QqPrintDialog ((QPrinter t1, QWidget t2)) where qPrintDialog (x1, x2) = withQPrintDialogResult $ withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QPrintDialog1 cobj_x1 cobj_x2 foreign import ccall "qtc_QPrintDialog1" qtc_QPrintDialog1 :: Ptr (TQPrinter t1) -> Ptr (TQWidget t2) -> IO (Ptr (TQPrintDialog ())) instance QeventFilter (QPrintDialog ()) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QPrintDialog_eventFilter_h cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QPrintDialog_eventFilter_h" qtc_QPrintDialog_eventFilter_h :: Ptr (TQPrintDialog a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance QeventFilter (QPrintDialogSc a) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QPrintDialog_eventFilter_h cobj_x0 cobj_x1 cobj_x2 instance Qexec (QPrintDialog ()) (()) (IO (Int)) where exec x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_exec_h cobj_x0 foreign import ccall "qtc_QPrintDialog_exec_h" qtc_QPrintDialog_exec_h :: Ptr (TQPrintDialog a) -> IO CInt instance Qexec (QPrintDialogSc a) (()) (IO (Int)) where exec x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_exec_h cobj_x0 qPrintDialog_delete :: QPrintDialog a -> IO () qPrintDialog_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_delete cobj_x0 foreign import ccall "qtc_QPrintDialog_delete" qtc_QPrintDialog_delete :: Ptr (TQPrintDialog a) -> IO () qPrintDialog_deleteLater :: QPrintDialog a -> IO () qPrintDialog_deleteLater x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_deleteLater cobj_x0 foreign import ccall "qtc_QPrintDialog_deleteLater" qtc_QPrintDialog_deleteLater :: Ptr (TQPrintDialog a) -> IO () instance Qaccept (QPrintDialog ()) (()) where accept x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_accept_h cobj_x0 foreign import ccall "qtc_QPrintDialog_accept_h" qtc_QPrintDialog_accept_h :: Ptr (TQPrintDialog a) -> IO () instance Qaccept (QPrintDialogSc a) (()) where accept x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_accept_h cobj_x0 instance QadjustPosition (QPrintDialog ()) ((QWidget t1)) where adjustPosition x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_adjustPosition cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_adjustPosition" qtc_QPrintDialog_adjustPosition :: Ptr (TQPrintDialog a) -> Ptr (TQWidget t1) -> IO () instance QadjustPosition (QPrintDialogSc a) ((QWidget t1)) where adjustPosition x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_adjustPosition cobj_x0 cobj_x1 instance QcloseEvent (QPrintDialog ()) ((QCloseEvent t1)) where closeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_closeEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_closeEvent_h" qtc_QPrintDialog_closeEvent_h :: Ptr (TQPrintDialog a) -> Ptr (TQCloseEvent t1) -> IO () instance QcloseEvent (QPrintDialogSc a) ((QCloseEvent t1)) where closeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_closeEvent_h cobj_x0 cobj_x1 instance QcontextMenuEvent (QPrintDialog ()) ((QContextMenuEvent t1)) where contextMenuEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_contextMenuEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_contextMenuEvent_h" qtc_QPrintDialog_contextMenuEvent_h :: Ptr (TQPrintDialog a) -> Ptr (TQContextMenuEvent t1) -> IO () instance QcontextMenuEvent (QPrintDialogSc a) ((QContextMenuEvent t1)) where contextMenuEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_contextMenuEvent_h cobj_x0 cobj_x1 instance Qdone (QPrintDialog ()) ((Int)) where done x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_done_h cobj_x0 (toCInt x1) foreign import ccall "qtc_QPrintDialog_done_h" qtc_QPrintDialog_done_h :: Ptr (TQPrintDialog a) -> CInt -> IO () instance Qdone (QPrintDialogSc a) ((Int)) where done x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_done_h cobj_x0 (toCInt x1) instance Qevent (QPrintDialog ()) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_event_h cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_event_h" qtc_QPrintDialog_event_h :: Ptr (TQPrintDialog a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent (QPrintDialogSc a) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_event_h cobj_x0 cobj_x1 instance QkeyPressEvent (QPrintDialog ()) ((QKeyEvent t1)) where keyPressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_keyPressEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_keyPressEvent_h" qtc_QPrintDialog_keyPressEvent_h :: Ptr (TQPrintDialog a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyPressEvent (QPrintDialogSc a) ((QKeyEvent t1)) where keyPressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_keyPressEvent_h cobj_x0 cobj_x1 instance QqminimumSizeHint (QPrintDialog ()) (()) where qminimumSizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_minimumSizeHint_h cobj_x0 foreign import ccall "qtc_QPrintDialog_minimumSizeHint_h" qtc_QPrintDialog_minimumSizeHint_h :: Ptr (TQPrintDialog a) -> IO (Ptr (TQSize ())) instance QqminimumSizeHint (QPrintDialogSc a) (()) where qminimumSizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_minimumSizeHint_h cobj_x0 instance QminimumSizeHint (QPrintDialog ()) (()) where minimumSizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QPrintDialog_minimumSizeHint_qth_h" qtc_QPrintDialog_minimumSizeHint_qth_h :: Ptr (TQPrintDialog a) -> Ptr CInt -> Ptr CInt -> IO () instance QminimumSizeHint (QPrintDialogSc a) (()) where minimumSizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h instance Qreject (QPrintDialog ()) (()) where reject x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_reject_h cobj_x0 foreign import ccall "qtc_QPrintDialog_reject_h" qtc_QPrintDialog_reject_h :: Ptr (TQPrintDialog a) -> IO () instance Qreject (QPrintDialogSc a) (()) where reject x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_reject_h cobj_x0 instance QresizeEvent (QPrintDialog ()) ((QResizeEvent t1)) where resizeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_resizeEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_resizeEvent_h" qtc_QPrintDialog_resizeEvent_h :: Ptr (TQPrintDialog a) -> Ptr (TQResizeEvent t1) -> IO () instance QresizeEvent (QPrintDialogSc a) ((QResizeEvent t1)) where resizeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_resizeEvent_h cobj_x0 cobj_x1 instance QsetVisible (QPrintDialog ()) ((Bool)) where setVisible x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_setVisible_h cobj_x0 (toCBool x1) foreign import ccall "qtc_QPrintDialog_setVisible_h" qtc_QPrintDialog_setVisible_h :: Ptr (TQPrintDialog a) -> CBool -> IO () instance QsetVisible (QPrintDialogSc a) ((Bool)) where setVisible x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_setVisible_h cobj_x0 (toCBool x1) instance QshowEvent (QPrintDialog ()) ((QShowEvent t1)) where showEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_showEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_showEvent_h" qtc_QPrintDialog_showEvent_h :: Ptr (TQPrintDialog a) -> Ptr (TQShowEvent t1) -> IO () instance QshowEvent (QPrintDialogSc a) ((QShowEvent t1)) where showEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_showEvent_h cobj_x0 cobj_x1 instance QqsizeHint (QPrintDialog ()) (()) where qsizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_sizeHint_h cobj_x0 foreign import ccall "qtc_QPrintDialog_sizeHint_h" qtc_QPrintDialog_sizeHint_h :: Ptr (TQPrintDialog a) -> IO (Ptr (TQSize ())) instance QqsizeHint (QPrintDialogSc a) (()) where qsizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_sizeHint_h cobj_x0 instance QsizeHint (QPrintDialog ()) (()) where sizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QPrintDialog_sizeHint_qth_h" qtc_QPrintDialog_sizeHint_qth_h :: Ptr (TQPrintDialog a) -> Ptr CInt -> Ptr CInt -> IO () instance QsizeHint (QPrintDialogSc a) (()) where sizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h instance QactionEvent (QPrintDialog ()) ((QActionEvent t1)) where actionEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_actionEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_actionEvent_h" qtc_QPrintDialog_actionEvent_h :: Ptr (TQPrintDialog a) -> Ptr (TQActionEvent t1) -> IO () instance QactionEvent (QPrintDialogSc a) ((QActionEvent t1)) where actionEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_actionEvent_h cobj_x0 cobj_x1 instance QaddAction (QPrintDialog ()) ((QAction t1)) (IO ()) where addAction x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_addAction cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_addAction" qtc_QPrintDialog_addAction :: Ptr (TQPrintDialog a) -> Ptr (TQAction t1) -> IO () instance QaddAction (QPrintDialogSc a) ((QAction t1)) (IO ()) where addAction x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_addAction cobj_x0 cobj_x1 instance QchangeEvent (QPrintDialog ()) ((QEvent t1)) where changeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_changeEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_changeEvent_h" qtc_QPrintDialog_changeEvent_h :: Ptr (TQPrintDialog a) -> Ptr (TQEvent t1) -> IO () instance QchangeEvent (QPrintDialogSc a) ((QEvent t1)) where changeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_changeEvent_h cobj_x0 cobj_x1 instance Qcreate (QPrintDialog ()) (()) (IO ()) where create x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_create cobj_x0 foreign import ccall "qtc_QPrintDialog_create" qtc_QPrintDialog_create :: Ptr (TQPrintDialog a) -> IO () instance Qcreate (QPrintDialogSc a) (()) (IO ()) where create x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_create cobj_x0 instance Qcreate (QPrintDialog ()) ((QVoid t1)) (IO ()) where create x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_create1 cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_create1" qtc_QPrintDialog_create1 :: Ptr (TQPrintDialog a) -> Ptr (TQVoid t1) -> IO () instance Qcreate (QPrintDialogSc a) ((QVoid t1)) (IO ()) where create x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_create1 cobj_x0 cobj_x1 instance Qcreate (QPrintDialog ()) ((QVoid t1, Bool)) (IO ()) where create x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_create2 cobj_x0 cobj_x1 (toCBool x2) foreign import ccall "qtc_QPrintDialog_create2" qtc_QPrintDialog_create2 :: Ptr (TQPrintDialog a) -> Ptr (TQVoid t1) -> CBool -> IO () instance Qcreate (QPrintDialogSc a) ((QVoid t1, Bool)) (IO ()) where create x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_create2 cobj_x0 cobj_x1 (toCBool x2) instance Qcreate (QPrintDialog ()) ((QVoid t1, Bool, Bool)) (IO ()) where create x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3) foreign import ccall "qtc_QPrintDialog_create3" qtc_QPrintDialog_create3 :: Ptr (TQPrintDialog a) -> Ptr (TQVoid t1) -> CBool -> CBool -> IO () instance Qcreate (QPrintDialogSc a) ((QVoid t1, Bool, Bool)) (IO ()) where create x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3) instance Qdestroy (QPrintDialog ()) (()) where destroy x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_destroy cobj_x0 foreign import ccall "qtc_QPrintDialog_destroy" qtc_QPrintDialog_destroy :: Ptr (TQPrintDialog a) -> IO () instance Qdestroy (QPrintDialogSc a) (()) where destroy x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_destroy cobj_x0 instance Qdestroy (QPrintDialog ()) ((Bool)) where destroy x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_destroy1 cobj_x0 (toCBool x1) foreign import ccall "qtc_QPrintDialog_destroy1" qtc_QPrintDialog_destroy1 :: Ptr (TQPrintDialog a) -> CBool -> IO () instance Qdestroy (QPrintDialogSc a) ((Bool)) where destroy x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_destroy1 cobj_x0 (toCBool x1) instance Qdestroy (QPrintDialog ()) ((Bool, Bool)) where destroy x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_destroy2 cobj_x0 (toCBool x1) (toCBool x2) foreign import ccall "qtc_QPrintDialog_destroy2" qtc_QPrintDialog_destroy2 :: Ptr (TQPrintDialog a) -> CBool -> CBool -> IO () instance Qdestroy (QPrintDialogSc a) ((Bool, Bool)) where destroy x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_destroy2 cobj_x0 (toCBool x1) (toCBool x2) instance QdevType (QPrintDialog ()) (()) where devType x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_devType_h cobj_x0 foreign import ccall "qtc_QPrintDialog_devType_h" qtc_QPrintDialog_devType_h :: Ptr (TQPrintDialog a) -> IO CInt instance QdevType (QPrintDialogSc a) (()) where devType x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_devType_h cobj_x0 instance QdragEnterEvent (QPrintDialog ()) ((QDragEnterEvent t1)) where dragEnterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_dragEnterEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_dragEnterEvent_h" qtc_QPrintDialog_dragEnterEvent_h :: Ptr (TQPrintDialog a) -> Ptr (TQDragEnterEvent t1) -> IO () instance QdragEnterEvent (QPrintDialogSc a) ((QDragEnterEvent t1)) where dragEnterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_dragEnterEvent_h cobj_x0 cobj_x1 instance QdragLeaveEvent (QPrintDialog ()) ((QDragLeaveEvent t1)) where dragLeaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_dragLeaveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_dragLeaveEvent_h" qtc_QPrintDialog_dragLeaveEvent_h :: Ptr (TQPrintDialog a) -> Ptr (TQDragLeaveEvent t1) -> IO () instance QdragLeaveEvent (QPrintDialogSc a) ((QDragLeaveEvent t1)) where dragLeaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_dragLeaveEvent_h cobj_x0 cobj_x1 instance QdragMoveEvent (QPrintDialog ()) ((QDragMoveEvent t1)) where dragMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_dragMoveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_dragMoveEvent_h" qtc_QPrintDialog_dragMoveEvent_h :: Ptr (TQPrintDialog a) -> Ptr (TQDragMoveEvent t1) -> IO () instance QdragMoveEvent (QPrintDialogSc a) ((QDragMoveEvent t1)) where dragMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_dragMoveEvent_h cobj_x0 cobj_x1 instance QdropEvent (QPrintDialog ()) ((QDropEvent t1)) where dropEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_dropEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_dropEvent_h" qtc_QPrintDialog_dropEvent_h :: Ptr (TQPrintDialog a) -> Ptr (TQDropEvent t1) -> IO () instance QdropEvent (QPrintDialogSc a) ((QDropEvent t1)) where dropEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_dropEvent_h cobj_x0 cobj_x1 instance QenabledChange (QPrintDialog ()) ((Bool)) where enabledChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_enabledChange cobj_x0 (toCBool x1) foreign import ccall "qtc_QPrintDialog_enabledChange" qtc_QPrintDialog_enabledChange :: Ptr (TQPrintDialog a) -> CBool -> IO () instance QenabledChange (QPrintDialogSc a) ((Bool)) where enabledChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_enabledChange cobj_x0 (toCBool x1) instance QenterEvent (QPrintDialog ()) ((QEvent t1)) where enterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_enterEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_enterEvent_h" qtc_QPrintDialog_enterEvent_h :: Ptr (TQPrintDialog a) -> Ptr (TQEvent t1) -> IO () instance QenterEvent (QPrintDialogSc a) ((QEvent t1)) where enterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_enterEvent_h cobj_x0 cobj_x1 instance QfocusInEvent (QPrintDialog ()) ((QFocusEvent t1)) where focusInEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_focusInEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_focusInEvent_h" qtc_QPrintDialog_focusInEvent_h :: Ptr (TQPrintDialog a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusInEvent (QPrintDialogSc a) ((QFocusEvent t1)) where focusInEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_focusInEvent_h cobj_x0 cobj_x1 instance QfocusNextChild (QPrintDialog ()) (()) where focusNextChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_focusNextChild cobj_x0 foreign import ccall "qtc_QPrintDialog_focusNextChild" qtc_QPrintDialog_focusNextChild :: Ptr (TQPrintDialog a) -> IO CBool instance QfocusNextChild (QPrintDialogSc a) (()) where focusNextChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_focusNextChild cobj_x0 instance QfocusNextPrevChild (QPrintDialog ()) ((Bool)) where focusNextPrevChild x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_focusNextPrevChild cobj_x0 (toCBool x1) foreign import ccall "qtc_QPrintDialog_focusNextPrevChild" qtc_QPrintDialog_focusNextPrevChild :: Ptr (TQPrintDialog a) -> CBool -> IO CBool instance QfocusNextPrevChild (QPrintDialogSc a) ((Bool)) where focusNextPrevChild x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_focusNextPrevChild cobj_x0 (toCBool x1) instance QfocusOutEvent (QPrintDialog ()) ((QFocusEvent t1)) where focusOutEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_focusOutEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_focusOutEvent_h" qtc_QPrintDialog_focusOutEvent_h :: Ptr (TQPrintDialog a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusOutEvent (QPrintDialogSc a) ((QFocusEvent t1)) where focusOutEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_focusOutEvent_h cobj_x0 cobj_x1 instance QfocusPreviousChild (QPrintDialog ()) (()) where focusPreviousChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_focusPreviousChild cobj_x0 foreign import ccall "qtc_QPrintDialog_focusPreviousChild" qtc_QPrintDialog_focusPreviousChild :: Ptr (TQPrintDialog a) -> IO CBool instance QfocusPreviousChild (QPrintDialogSc a) (()) where focusPreviousChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_focusPreviousChild cobj_x0 instance QfontChange (QPrintDialog ()) ((QFont t1)) where fontChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_fontChange cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_fontChange" qtc_QPrintDialog_fontChange :: Ptr (TQPrintDialog a) -> Ptr (TQFont t1) -> IO () instance QfontChange (QPrintDialogSc a) ((QFont t1)) where fontChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_fontChange cobj_x0 cobj_x1 instance QheightForWidth (QPrintDialog ()) ((Int)) where heightForWidth x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_heightForWidth_h cobj_x0 (toCInt x1) foreign import ccall "qtc_QPrintDialog_heightForWidth_h" qtc_QPrintDialog_heightForWidth_h :: Ptr (TQPrintDialog a) -> CInt -> IO CInt instance QheightForWidth (QPrintDialogSc a) ((Int)) where heightForWidth x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_heightForWidth_h cobj_x0 (toCInt x1) instance QhideEvent (QPrintDialog ()) ((QHideEvent t1)) where hideEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_hideEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_hideEvent_h" qtc_QPrintDialog_hideEvent_h :: Ptr (TQPrintDialog a) -> Ptr (TQHideEvent t1) -> IO () instance QhideEvent (QPrintDialogSc a) ((QHideEvent t1)) where hideEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_hideEvent_h cobj_x0 cobj_x1 instance QinputMethodEvent (QPrintDialog ()) ((QInputMethodEvent t1)) where inputMethodEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_inputMethodEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_inputMethodEvent" qtc_QPrintDialog_inputMethodEvent :: Ptr (TQPrintDialog a) -> Ptr (TQInputMethodEvent t1) -> IO () instance QinputMethodEvent (QPrintDialogSc a) ((QInputMethodEvent t1)) where inputMethodEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_inputMethodEvent cobj_x0 cobj_x1 instance QinputMethodQuery (QPrintDialog ()) ((InputMethodQuery)) where inputMethodQuery x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QPrintDialog_inputMethodQuery_h" qtc_QPrintDialog_inputMethodQuery_h :: Ptr (TQPrintDialog a) -> CLong -> IO (Ptr (TQVariant ())) instance QinputMethodQuery (QPrintDialogSc a) ((InputMethodQuery)) where inputMethodQuery x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1) instance QkeyReleaseEvent (QPrintDialog ()) ((QKeyEvent t1)) where keyReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_keyReleaseEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_keyReleaseEvent_h" qtc_QPrintDialog_keyReleaseEvent_h :: Ptr (TQPrintDialog a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyReleaseEvent (QPrintDialogSc a) ((QKeyEvent t1)) where keyReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_keyReleaseEvent_h cobj_x0 cobj_x1 instance QlanguageChange (QPrintDialog ()) (()) where languageChange x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_languageChange cobj_x0 foreign import ccall "qtc_QPrintDialog_languageChange" qtc_QPrintDialog_languageChange :: Ptr (TQPrintDialog a) -> IO () instance QlanguageChange (QPrintDialogSc a) (()) where languageChange x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_languageChange cobj_x0 instance QleaveEvent (QPrintDialog ()) ((QEvent t1)) where leaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_leaveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_leaveEvent_h" qtc_QPrintDialog_leaveEvent_h :: Ptr (TQPrintDialog a) -> Ptr (TQEvent t1) -> IO () instance QleaveEvent (QPrintDialogSc a) ((QEvent t1)) where leaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_leaveEvent_h cobj_x0 cobj_x1 instance Qmetric (QPrintDialog ()) ((PaintDeviceMetric)) where metric x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_metric cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QPrintDialog_metric" qtc_QPrintDialog_metric :: Ptr (TQPrintDialog a) -> CLong -> IO CInt instance Qmetric (QPrintDialogSc a) ((PaintDeviceMetric)) where metric x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_metric cobj_x0 (toCLong $ qEnum_toInt x1) instance QmouseDoubleClickEvent (QPrintDialog ()) ((QMouseEvent t1)) where mouseDoubleClickEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_mouseDoubleClickEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_mouseDoubleClickEvent_h" qtc_QPrintDialog_mouseDoubleClickEvent_h :: Ptr (TQPrintDialog a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseDoubleClickEvent (QPrintDialogSc a) ((QMouseEvent t1)) where mouseDoubleClickEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_mouseDoubleClickEvent_h cobj_x0 cobj_x1 instance QmouseMoveEvent (QPrintDialog ()) ((QMouseEvent t1)) where mouseMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_mouseMoveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_mouseMoveEvent_h" qtc_QPrintDialog_mouseMoveEvent_h :: Ptr (TQPrintDialog a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseMoveEvent (QPrintDialogSc a) ((QMouseEvent t1)) where mouseMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_mouseMoveEvent_h cobj_x0 cobj_x1 instance QmousePressEvent (QPrintDialog ()) ((QMouseEvent t1)) where mousePressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_mousePressEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_mousePressEvent_h" qtc_QPrintDialog_mousePressEvent_h :: Ptr (TQPrintDialog a) -> Ptr (TQMouseEvent t1) -> IO () instance QmousePressEvent (QPrintDialogSc a) ((QMouseEvent t1)) where mousePressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_mousePressEvent_h cobj_x0 cobj_x1 instance QmouseReleaseEvent (QPrintDialog ()) ((QMouseEvent t1)) where mouseReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_mouseReleaseEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_mouseReleaseEvent_h" qtc_QPrintDialog_mouseReleaseEvent_h :: Ptr (TQPrintDialog a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseReleaseEvent (QPrintDialogSc a) ((QMouseEvent t1)) where mouseReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_mouseReleaseEvent_h cobj_x0 cobj_x1 instance Qmove (QPrintDialog ()) ((Int, Int)) where move x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_move1 cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QPrintDialog_move1" qtc_QPrintDialog_move1 :: Ptr (TQPrintDialog a) -> CInt -> CInt -> IO () instance Qmove (QPrintDialogSc a) ((Int, Int)) where move x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_move1 cobj_x0 (toCInt x1) (toCInt x2) instance Qmove (QPrintDialog ()) ((Point)) where move x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> qtc_QPrintDialog_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y foreign import ccall "qtc_QPrintDialog_move_qth" qtc_QPrintDialog_move_qth :: Ptr (TQPrintDialog a) -> CInt -> CInt -> IO () instance Qmove (QPrintDialogSc a) ((Point)) where move x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> qtc_QPrintDialog_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y instance Qqmove (QPrintDialog ()) ((QPoint t1)) where qmove x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_move cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_move" qtc_QPrintDialog_move :: Ptr (TQPrintDialog a) -> Ptr (TQPoint t1) -> IO () instance Qqmove (QPrintDialogSc a) ((QPoint t1)) where qmove x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_move cobj_x0 cobj_x1 instance QmoveEvent (QPrintDialog ()) ((QMoveEvent t1)) where moveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_moveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_moveEvent_h" qtc_QPrintDialog_moveEvent_h :: Ptr (TQPrintDialog a) -> Ptr (TQMoveEvent t1) -> IO () instance QmoveEvent (QPrintDialogSc a) ((QMoveEvent t1)) where moveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_moveEvent_h cobj_x0 cobj_x1 instance QpaintEngine (QPrintDialog ()) (()) where paintEngine x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_paintEngine_h cobj_x0 foreign import ccall "qtc_QPrintDialog_paintEngine_h" qtc_QPrintDialog_paintEngine_h :: Ptr (TQPrintDialog a) -> IO (Ptr (TQPaintEngine ())) instance QpaintEngine (QPrintDialogSc a) (()) where paintEngine x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_paintEngine_h cobj_x0 instance QpaintEvent (QPrintDialog ()) ((QPaintEvent t1)) where paintEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_paintEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_paintEvent_h" qtc_QPrintDialog_paintEvent_h :: Ptr (TQPrintDialog a) -> Ptr (TQPaintEvent t1) -> IO () instance QpaintEvent (QPrintDialogSc a) ((QPaintEvent t1)) where paintEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_paintEvent_h cobj_x0 cobj_x1 instance QpaletteChange (QPrintDialog ()) ((QPalette t1)) where paletteChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_paletteChange cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_paletteChange" qtc_QPrintDialog_paletteChange :: Ptr (TQPrintDialog a) -> Ptr (TQPalette t1) -> IO () instance QpaletteChange (QPrintDialogSc a) ((QPalette t1)) where paletteChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_paletteChange cobj_x0 cobj_x1 instance Qrepaint (QPrintDialog ()) (()) where repaint x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_repaint cobj_x0 foreign import ccall "qtc_QPrintDialog_repaint" qtc_QPrintDialog_repaint :: Ptr (TQPrintDialog a) -> IO () instance Qrepaint (QPrintDialogSc a) (()) where repaint x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_repaint cobj_x0 instance Qrepaint (QPrintDialog ()) ((Int, Int, Int, Int)) where repaint x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) foreign import ccall "qtc_QPrintDialog_repaint2" qtc_QPrintDialog_repaint2 :: Ptr (TQPrintDialog a) -> CInt -> CInt -> CInt -> CInt -> IO () instance Qrepaint (QPrintDialogSc a) ((Int, Int, Int, Int)) where repaint x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) instance Qrepaint (QPrintDialog ()) ((QRegion t1)) where repaint x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_repaint1 cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_repaint1" qtc_QPrintDialog_repaint1 :: Ptr (TQPrintDialog a) -> Ptr (TQRegion t1) -> IO () instance Qrepaint (QPrintDialogSc a) ((QRegion t1)) where repaint x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_repaint1 cobj_x0 cobj_x1 instance QresetInputContext (QPrintDialog ()) (()) where resetInputContext x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_resetInputContext cobj_x0 foreign import ccall "qtc_QPrintDialog_resetInputContext" qtc_QPrintDialog_resetInputContext :: Ptr (TQPrintDialog a) -> IO () instance QresetInputContext (QPrintDialogSc a) (()) where resetInputContext x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_resetInputContext cobj_x0 instance Qresize (QPrintDialog ()) ((Int, Int)) (IO ()) where resize x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_resize1 cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QPrintDialog_resize1" qtc_QPrintDialog_resize1 :: Ptr (TQPrintDialog a) -> CInt -> CInt -> IO () instance Qresize (QPrintDialogSc a) ((Int, Int)) (IO ()) where resize x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_resize1 cobj_x0 (toCInt x1) (toCInt x2) instance Qqresize (QPrintDialog ()) ((QSize t1)) where qresize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_resize cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_resize" qtc_QPrintDialog_resize :: Ptr (TQPrintDialog a) -> Ptr (TQSize t1) -> IO () instance Qqresize (QPrintDialogSc a) ((QSize t1)) where qresize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_resize cobj_x0 cobj_x1 instance Qresize (QPrintDialog ()) ((Size)) (IO ()) where resize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCSize x1 $ \csize_x1_w csize_x1_h -> qtc_QPrintDialog_resize_qth cobj_x0 csize_x1_w csize_x1_h foreign import ccall "qtc_QPrintDialog_resize_qth" qtc_QPrintDialog_resize_qth :: Ptr (TQPrintDialog a) -> CInt -> CInt -> IO () instance Qresize (QPrintDialogSc a) ((Size)) (IO ()) where resize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCSize x1 $ \csize_x1_w csize_x1_h -> qtc_QPrintDialog_resize_qth cobj_x0 csize_x1_w csize_x1_h instance QsetGeometry (QPrintDialog ()) ((Int, Int, Int, Int)) where setGeometry x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) foreign import ccall "qtc_QPrintDialog_setGeometry1" qtc_QPrintDialog_setGeometry1 :: Ptr (TQPrintDialog a) -> CInt -> CInt -> CInt -> CInt -> IO () instance QsetGeometry (QPrintDialogSc a) ((Int, Int, Int, Int)) where setGeometry x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) instance QqsetGeometry (QPrintDialog ()) ((QRect t1)) where qsetGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_setGeometry cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_setGeometry" qtc_QPrintDialog_setGeometry :: Ptr (TQPrintDialog a) -> Ptr (TQRect t1) -> IO () instance QqsetGeometry (QPrintDialogSc a) ((QRect t1)) where qsetGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_setGeometry cobj_x0 cobj_x1 instance QsetGeometry (QPrintDialog ()) ((Rect)) where setGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h -> qtc_QPrintDialog_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h foreign import ccall "qtc_QPrintDialog_setGeometry_qth" qtc_QPrintDialog_setGeometry_qth :: Ptr (TQPrintDialog a) -> CInt -> CInt -> CInt -> CInt -> IO () instance QsetGeometry (QPrintDialogSc 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_QPrintDialog_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h instance QsetMouseTracking (QPrintDialog ()) ((Bool)) where setMouseTracking x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_setMouseTracking cobj_x0 (toCBool x1) foreign import ccall "qtc_QPrintDialog_setMouseTracking" qtc_QPrintDialog_setMouseTracking :: Ptr (TQPrintDialog a) -> CBool -> IO () instance QsetMouseTracking (QPrintDialogSc a) ((Bool)) where setMouseTracking x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_setMouseTracking cobj_x0 (toCBool x1) instance QtabletEvent (QPrintDialog ()) ((QTabletEvent t1)) where tabletEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_tabletEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_tabletEvent_h" qtc_QPrintDialog_tabletEvent_h :: Ptr (TQPrintDialog a) -> Ptr (TQTabletEvent t1) -> IO () instance QtabletEvent (QPrintDialogSc a) ((QTabletEvent t1)) where tabletEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_tabletEvent_h cobj_x0 cobj_x1 instance QupdateMicroFocus (QPrintDialog ()) (()) where updateMicroFocus x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_updateMicroFocus cobj_x0 foreign import ccall "qtc_QPrintDialog_updateMicroFocus" qtc_QPrintDialog_updateMicroFocus :: Ptr (TQPrintDialog a) -> IO () instance QupdateMicroFocus (QPrintDialogSc a) (()) where updateMicroFocus x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_updateMicroFocus cobj_x0 instance QwheelEvent (QPrintDialog ()) ((QWheelEvent t1)) where wheelEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_wheelEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_wheelEvent_h" qtc_QPrintDialog_wheelEvent_h :: Ptr (TQPrintDialog a) -> Ptr (TQWheelEvent t1) -> IO () instance QwheelEvent (QPrintDialogSc a) ((QWheelEvent t1)) where wheelEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_wheelEvent_h cobj_x0 cobj_x1 instance QwindowActivationChange (QPrintDialog ()) ((Bool)) where windowActivationChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_windowActivationChange cobj_x0 (toCBool x1) foreign import ccall "qtc_QPrintDialog_windowActivationChange" qtc_QPrintDialog_windowActivationChange :: Ptr (TQPrintDialog a) -> CBool -> IO () instance QwindowActivationChange (QPrintDialogSc a) ((Bool)) where windowActivationChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_windowActivationChange cobj_x0 (toCBool x1) instance QchildEvent (QPrintDialog ()) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_childEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_childEvent" qtc_QPrintDialog_childEvent :: Ptr (TQPrintDialog a) -> Ptr (TQChildEvent t1) -> IO () instance QchildEvent (QPrintDialogSc a) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_childEvent cobj_x0 cobj_x1 instance QconnectNotify (QPrintDialog ()) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QPrintDialog_connectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QPrintDialog_connectNotify" qtc_QPrintDialog_connectNotify :: Ptr (TQPrintDialog a) -> CWString -> IO () instance QconnectNotify (QPrintDialogSc a) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QPrintDialog_connectNotify cobj_x0 cstr_x1 instance QcustomEvent (QPrintDialog ()) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_customEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_customEvent" qtc_QPrintDialog_customEvent :: Ptr (TQPrintDialog a) -> Ptr (TQEvent t1) -> IO () instance QcustomEvent (QPrintDialogSc a) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_customEvent cobj_x0 cobj_x1 instance QdisconnectNotify (QPrintDialog ()) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QPrintDialog_disconnectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QPrintDialog_disconnectNotify" qtc_QPrintDialog_disconnectNotify :: Ptr (TQPrintDialog a) -> CWString -> IO () instance QdisconnectNotify (QPrintDialogSc a) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QPrintDialog_disconnectNotify cobj_x0 cstr_x1 instance Qreceivers (QPrintDialog ()) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QPrintDialog_receivers cobj_x0 cstr_x1 foreign import ccall "qtc_QPrintDialog_receivers" qtc_QPrintDialog_receivers :: Ptr (TQPrintDialog a) -> CWString -> IO CInt instance Qreceivers (QPrintDialogSc a) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QPrintDialog_receivers cobj_x0 cstr_x1 instance Qsender (QPrintDialog ()) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_sender cobj_x0 foreign import ccall "qtc_QPrintDialog_sender" qtc_QPrintDialog_sender :: Ptr (TQPrintDialog a) -> IO (Ptr (TQObject ())) instance Qsender (QPrintDialogSc a) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPrintDialog_sender cobj_x0 instance QtimerEvent (QPrintDialog ()) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_timerEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QPrintDialog_timerEvent" qtc_QPrintDialog_timerEvent :: Ptr (TQPrintDialog a) -> Ptr (TQTimerEvent t1) -> IO () instance QtimerEvent (QPrintDialogSc a) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPrintDialog_timerEvent cobj_x0 cobj_x1
keera-studios/hsQt
Qtc/Gui/QPrintDialog.hs
bsd-2-clause
46,365
0
14
7,401
14,919
7,564
7,355
-1
-1
{-# LANGUAGE CPP #-} #if __GLASGOW_HASKELL__ >= 701 {-# LANGUAGE Trustworthy #-} #endif -- -- | -- Module : System.Environment.UTF8 -- Copyright : (c) Eric Mertens 2009 -- License : BSD3-style (see LICENSE) -- -- Maintainer: emertens@galois.com -- Stability : experimental -- Portability : portable -- -- Support for UTF-8 based environment manipulation -- module System.Environment.UTF8 (getArgs, getProgName, getEnv, withArgs, withProgName, getEnvironment) where import Codec.Binary.UTF8.String (decodeString) import qualified System.Environment as Sys getArgs :: IO [String] getArgs = map decodeString `fmap` Sys.getArgs getProgName :: IO String getProgName = decodeString `fmap` Sys.getProgName getEnv :: String -> IO String getEnv x = decodeString `fmap` Sys.getEnv x withArgs :: [String] -> IO a -> IO a withArgs = Sys.withArgs withProgName :: String -> IO a -> IO a withProgName = Sys.withProgName getEnvironment :: IO [(String,String)] getEnvironment = map f `fmap` Sys.getEnvironment where f (a,b) = (decodeString a, decodeString b)
ghc/packages-utf8-string
System/Environment/UTF8.hs
bsd-3-clause
1,076
0
8
179
258
153
105
18
1