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 MessageProperties where
import Data.Binary
import qualified Data.ByteString.Lazy as LBS
import Network.Linx.Gateway.Message
import Network.Linx.Gateway.Types
import Generators ()
prop_message :: Message -> Bool
prop_message message@(Message _ msgPayload) =
let encodedMessage = encode message
(encHeader, encPayload) = LBS.splitAt 8 encodedMessage
Header msgType (Length len) = decode encHeader
msgPayload' = decodeProtocolPayload msgType encPayload
in msgPayload == msgPayload'
&& (fromIntegral len) == (LBS.length encPayload) | kosmoskatten/linx-gateway | test/MessageProperties.hs | mit | 598 | 0 | 11 | 123 | 155 | 85 | 70 | 14 | 1 |
-- Copyright (c) 2014 Zachary King
import System.Environment
import Data.Time
data Entry = Entry { line :: String
, time :: UTCTime
} deriving (Show)
type Index = [Entry]
emptyIndex :: Index
emptyIndex = []
main :: IO ()
main = loop emptyIndex
loop :: Index -> IO ()
loop index = do
putStrLn "command:"
line <- getLine
time <- getCurrentTime
if line /= "exit"
then do
let index2 = index ++ [Entry line time]
print index2
loop index2
else
-- quit
return ()
| zakandrewking/eightball | eightball.hs | mit | 557 | 0 | 15 | 185 | 175 | 90 | 85 | 21 | 2 |
module Grammar
( Grammar (..)
, ProductionElement (..)
, Production (..)
, isDiscardable
, isSymbol
, fromSymbol
) where
import qualified Data.Map as Map
data Grammar terminals productionNames symbols = Grammar
{ startSymbol :: symbols
, productions :: Map.Map productionNames (Production terminals symbols)
}
data Production terminals symbols
= Production
{ productionSymbol :: symbols
-- Some productions serve only to define precedence, which is unambiguous in a tree, so they can be discarded
-- Those must not have more than 1 non-discardable production element
, productionDiscardable :: Bool
, productionString :: [ProductionElement terminals symbols]
}
data ProductionElement terminals symbols
= Terminal terminals
-- Many terminals are only used in one production so the productionName uniquely identifies the result and they are discardable
| DiscardableTerminal terminals
| Symbol symbols
deriving (Eq, Ord)
instance (Show terminals, Show symbols) => Show (ProductionElement terminals symbols) where
show (Terminal t) = show t
show (DiscardableTerminal t) = "(" ++ show t ++ ")"
show (Symbol s) = "<" ++ show s ++ ">"
instance (Show terminals, Show symbols) => Show (Production terminals symbols) where
show (Production symbol discardable string) = foldl (\ l r -> l ++ " " ++ show r) accum string
where accum = "<" ++ show symbol ++ ">" ++ if discardable then " (discardable)" else "" ++ " ::="
instance (Show terminals, Show symbols, Eq symbols, Show productionNames, Ord productionNames)
=> Show (Grammar terminals symbols productionNames) where
show (Grammar startSymbol productions)
= Map.foldlWithKey concatProduction
( Map.foldlWithKey concatProduction "== Grammar ==\n= Start Symbol ="
(Map.filter isStartProduction productions)
++ "\n\n= Rest ="
)
$ Map.filter (not . isStartProduction) productions
where
isStartProduction prod = productionSymbol prod == startSymbol
concatProduction accum productionName production
= accum ++ "\n" ++ show productionName ++ ":\n "
++ show production
isDiscardable :: ProductionElement terminals symbols -> Bool
isDiscardable (DiscardableTerminal _) = True
isDiscardable _ = False
isSymbol :: ProductionElement terminals symbols -> Bool
isSymbol (Symbol _) = True
isSymbol _ = False
fromSymbol :: ProductionElement terminals symbols -> symbols
fromSymbol (Symbol s) = s
| mrwonko/wonkococo | wcc/Grammar.hs | mit | 2,590 | 0 | 13 | 603 | 633 | 337 | 296 | 48 | 1 |
import Test.HUnit (Assertion, (@=?), runTestTT, Test(..))
import Control.Monad (void)
import Gigasecond (fromDay)
import Data.Time.Calendar (fromGregorian)
testCase :: String -> Assertion -> Test
testCase label assertion = TestLabel label (TestCase assertion)
main :: IO ()
main = void $ runTestTT $ TestList
[ TestList gigasecondTests ]
gigasecondTests :: [Test]
gigasecondTests =
[ testCase "from apr 25 2011" $
fromGregorian 2043 1 1 @=? fromDay (fromGregorian 2011 04 25)
, testCase "from jun 13 1977" $
fromGregorian 2009 2 19 @=? fromDay (fromGregorian 1977 6 13)
, testCase "from jul 19 1959" $
fromGregorian 1991 3 27 @=? fromDay (fromGregorian 1959 7 19)
-- customize this to test your birthday and find your gigasecond date:
]
| tfausak/exercism-solutions | haskell/gigasecond/gigasecond_test.hs | mit | 771 | 0 | 9 | 148 | 237 | 125 | 112 | 17 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Application
( makeApplication
, getApplicationDev
, makeFoundation
) where
import Import
import Settings
import Yesod.Auth
import Yesod.Default.Config
import Yesod.Default.Main
import Yesod.Default.Handlers
import Network.Wai.Middleware.RequestLogger
import qualified Database.Persist
import Database.Persist.Sql (runMigration)
import Network.HTTP.Conduit (newManager, def)
import Control.Monad.Logger (runLoggingT)
import System.IO (stdout)
import System.Log.FastLogger (mkLogger)
-- Import all relevant handler modules here.
-- Don't forget to add new modules to your cabal file!
import Handler.Home
import Handler.WishList
import Handler.Register
import Handler.WishHandler
import Handler.WishListLogin
-- This line actually creates our YesodDispatch instance. It is the second half
-- of the call to mkYesodData which occurs in Foundation.hs. Please see the
-- comments there for more details.
mkYesodDispatch "App" resourcesApp
-- This function allocates resources (such as a database connection pool),
-- performs initialization and creates a WAI application. This is also the
-- place to put your migrate statements to have automatic database
-- migrations handled by Yesod.
makeApplication :: AppConfig DefaultEnv Extra -> IO Application
makeApplication conf = do
foundation <- makeFoundation conf
-- Initialize the logging middleware
logWare <- mkRequestLogger def
{ outputFormat =
if development
then Detailed True
else Apache FromSocket
, destination = Logger $ appLogger foundation
}
-- Create the WAI application and apply middlewares
app <- toWaiAppPlain foundation
return $ logWare app
-- | Loads up any necessary settings, creates your foundation datatype, and
-- performs some initialization.
makeFoundation :: AppConfig DefaultEnv Extra -> IO App
makeFoundation conf = do
manager <- newManager def
s <- staticSite
dbconf <- withYamlEnvironment "config/sqlite.yml" (appEnv conf)
Database.Persist.loadConfig >>=
Database.Persist.applyEnv
p <- Database.Persist.createPoolConfig (dbconf :: Settings.PersistConf)
logger <- mkLogger True stdout
let foundation = App conf s p manager dbconf logger
-- Perform database migration using our application's logging settings.
runLoggingT
(Database.Persist.runPool dbconf (runMigration migrateAll) p)
(messageLoggerSource foundation logger)
return foundation
-- for yesod devel
getApplicationDev :: IO (Int, Application)
getApplicationDev =
defaultDevelApp loader makeApplication
where
loader = Yesod.Default.Config.loadConfig (configSettings Development)
{ csParseExtra = parseExtra
}
| lulf/wishsys | Application.hs | mit | 2,809 | 0 | 12 | 543 | 483 | 263 | 220 | -1 | -1 |
--------------------------------------------------------------------------------
{-# LANGUAGE OverloadedStrings #-}
import Control.Applicative ((<$>))
import Data.Monoid (mconcat,(<>))
import Data.Function (on)
import Data.List (sortBy,intersperse,intercalate,isInfixOf)
import Data.List.Split (chunksOf)
import qualified Data.Map as M
import Hakyll
import System.FilePath (dropExtension,takeBaseName)
import Text.Blaze.Html.Renderer.String (renderHtml)
import Text.Blaze ((!), toValue)
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
import Debug.Trace
-------------------------------------------------------------------------------
debug s = trace ("STUFF: " ++ show s) s
articlesPerIndexPage :: Int
articlesPerIndexPage = 2
hakyllConf :: Configuration
hakyllConf = defaultConfiguration {
deployCommand =
"rsync -ave ssh _site/ " ++ "ben@benkolera.com:/opt/blog/"
}
main :: IO ()
main = doHakyll
doHakyll :: IO ()
doHakyll = hakyllWith hakyllConf $ do
match "static/**" $ do
route $ gsubRoute "static/" (const "")
compile copyFileCompiler
match ("md/pages/**.md") $ do
route $ gsubRoute "md/pages/" (const "") `composeRoutes` setExtension ".html"
compile staticCompiler
match "templates/*" $ compile templateCompiler
-- Build tags
tags <- buildTags "md/posts/*" (fromCapture "tags/*.html")
-- Render each and every post
match "md/posts/*.md" $ do
route $ gsubRoute "md/" (const "") `composeRoutes` setExtension ".html"
compile $ templatedPandoc "templates/post.html" tags
create ["posts.html"] $ do
route idRoute
compile $ do
posts <- recentFirst =<< loadAllSnapshots "md/posts/**" "content"
let ctx = listField "posts" (postCtx tags) (return . debug $ posts) <> baseCtx
makeItem ""
>>= loadAndApplyTemplate "templates/posts.html" ctx
>>= loadAndApplyTemplate "templates/default.html" ctx
>>= relativizeUrls
match "less/*.less" $ compile getResourceBody
d <- makePatternDependency "less/**/*.less"
rulesExtraDependencies [d] $ create ["css/blog.css"] $ do
route idRoute
compile $ loadBody "less/blog.less"
>>= makeItem
>>= withItemBody
(unixFilter "node_modules/less/bin/lessc" ["-","--include-path=less/"])
--------------------------------------------------------------------------------
templatedPandoc :: Identifier -> Tags -> Compiler (Item String)
templatedPandoc templatePath tags = pandocCompiler
>>= saveSnapshot "content"
>>= loadAndApplyTemplate templatePath (postCtx tags)
>>= defaultCompiler baseCtx
staticCompiler :: Compiler (Item String)
staticCompiler = pandocCompiler >>= defaultCompiler baseCtx
defaultCompiler :: Show a => Context a -> Item a -> Compiler (Item String)
defaultCompiler ctx item =
loadAndApplyTemplate "templates/default.html" ctx item
>>= relativizeUrls
postCtx tags = mconcat
[ modificationTimeField "mtime" "%U"
, tagsField "tags" tags
, baseCtx
]
baseCtx :: Context String
baseCtx =
mconcat [
functionField "pagetitle" pageTitle
, dateField "today" "%B %e, %Y"
, defaultContext
]
where
pageTitle _ i = do
m <- getMetadata $ itemIdentifier i
return $ "Confessions of a Typeholic" ++ (maybe "" (" | "++ ) (M.lookup "title" m))
| benkolera/blog | hs/Site.hs | mit | 3,428 | 8 | 21 | 682 | 873 | 443 | 430 | 77 | 1 |
-- |This module, and the corresponding 'Zeno.Isabellable' modules,
-- deal with the conversion a 'ProofSet' into Isabelle/HOL code, outputting this
-- code into a file and then checking this file with Isabelle.
module Zeno.Isabelle (
toIsabelle
) where
import Prelude ()
import Zeno.Prelude
import Zeno.Core
import Zeno.Proof
import Zeno.Isabellable.Class
import Zeno.Isabellable.Proof
import Zeno.Isabellable.Core
import qualified Data.Map as Map
import qualified Data.Text as Text
instance Isabellable ZProofSet where
toIsabelle (ProofSet pgm named_proofs) =
"theory Zeno\nimports Main List\nbegin"
++ isa_dtypes ++ isa_binds ++ isa_proofs ++ "\n\nend\n"
where
flags = programFlags pgm
(names, proofs) = unzip named_proofs
names' = map convert names
all_vars =
(nubOrd . concatMap (toList . proofGoal)) proofs
isa_proofs = foldl (++) mempty
$ zipWith namedIsabelleProof names' proofs
binds = sortBindings binds'
(dtypes, binds')
| flagIsabelleAll flags =
( Map.elems . programDataTypes $ pgm,
programBindings $ pgm )
| otherwise =
dependencies pgm all_vars
builtInType dt = show dt `elem`
["list", "bool", "(,)", "(,,)", "(,,,)"]
isa_binds = foldl (++) mempty
. map toIsabelle
$ binds
isa_dtypes = foldl (++) mempty
. map toIsabelle
. filter (not . builtInType)
$ dtypes
| Gurmeet-Singh/Zeno | src/Zeno/Isabelle.hs | mit | 1,484 | 0 | 13 | 391 | 347 | 191 | 156 | 38 | 0 |
-- Simple Haskell program that generates KB clauses for the position functions.
n (x,y) = (x,y-1)
e (x,y) = (x+1,y)
s (x,y) = (x,y+1)
w (x,y) = (x-1,y)
ne (x,y) = (x+1,y-1)
se (x,y) = (x+1,y+1)
nw (x,y) = (x-1,y-1)
sw (x,y) = (x-1,y+1)
xrange = [1..4]
yrange = [1..4]
valid (x,y) = x `elem` xrange && y `elem` yrange
kb1 fname (x,y) (x',y') = "KB: "++ fname ++"(p" ++ show x ++ show y ++")=p" ++ show x' ++ show y' ++ " "
kb f fn = unlines $ [ foldr (++) "" $ map (uncurry (kb1 fn)) $ filter (\(_,p) -> valid p) $ map (\p -> (p, f p)) $ [(x,y) | x <- xrange] | y <- yrange]
main = putStrLn $ unlines $ map (uncurry kb) [(n,"n"),(e,"e"),(s,"s"),(w,"w"),(ne,"ne"),(se,"se"),(sw,"sw"),(nw,"nw")]
| schwering/limbo | examples/tui/battleship-pos.hs | mit | 700 | 0 | 15 | 140 | 548 | 309 | 239 | 14 | 1 |
module Main where
import Day7.Main
main = run
| brsunter/AdventOfCodeHaskell | src/Main.hs | mit | 46 | 0 | 4 | 8 | 14 | 9 | 5 | 3 | 1 |
main :: IO ()
main = do
p1 <- getLine
p2 <- getLine
let [x1, y1] = map (\x -> read x :: Int) (words p1)
[x2, y2] = map (\x -> read x :: Int) (words p2)
print $ abs (x1 - x2) + abs (y1 - y2) + 1
| knuu/competitive-programming | atcoder/other/idn_qb_1.hs | mit | 208 | 0 | 13 | 65 | 143 | 72 | 71 | 7 | 1 |
{-# LANGUAGE LambdaCase #-}
module Main where
import Control.Concurrent hiding (Chan)
import Control.Concurrent.GoChan
import Control.Monad
import Data.IORef
import Test.Hspec
main :: IO ()
main =
hspec $
do describe "with buffer size 0" $
do it "chanMake doesn't blow up" $ do void (chanMake 0 :: IO (Chan Int))
it "send & recv doesn't blow up" $ do sendRecv 0 1 10 sendN drain
it "send & recv/select doesn't blow up" $
do sendRecv 0 1 10 sendN drainSelect
it "send/select & recv doesn't blow up" $
do sendRecv 0 1 10 sendNSelect drain
it "send/select & recv/select doesn't blow up" $
do sendRecv 0 1 10 sendNSelect drainSelect
it "multi-case select doesn't blow up" $ do multiTest 0
describe "with buffer size 1" $
do it "chanMake doesn't blow up" $ void (chanMake 1 :: IO (Chan Int))
it "send & recv doesn't blow up" $ do sendRecv 1 1 10 sendN drain
it "send & recv/select doesn't blow up" $
do sendRecv 1 1 10 sendN drainSelect
it "send/select & recv doesn't blow up" $
do sendRecv 1 1 10 sendNSelect drain
it "send/select & recv/select doesn't blow up" $
do sendRecv 1 1 10 sendNSelect drainSelect
it "multi-case select doesn't blow up" $ do multiTest 1
describe "with buffer size 2" $
do it "chanMake doesn't blow up" $ void (chanMake 2 :: IO (Chan Int))
it "send & recv doesn't blow up" $ do sendRecv 2 1 10 sendN drain
it "send & recv/select doesn't blow up" $
do sendRecv 2 1 10 sendN drainSelect
it "send/select & recv doesn't blow up" $
do sendRecv 2 1 10 sendNSelect drain
it "send/select & recv/select doesn't blow up" $
do sendRecv 2 1 10 sendNSelect drainSelect
it "multi-case select doesn't blow up" $ do multiTest 2
describe "with buffer size 3" $
do it "chanMake doesn't blow up" $ do void (chanMake 3 :: IO (Chan Int))
it "send & recv doesn't blow up" $ do sendRecv 3 1 10 sendN drain
it "send & recv/select doesn't blow up" $
do sendRecv 3 1 10 sendN drainSelect
it "send/select & recv doesn't blow up" $
do sendRecv 3 1 10 sendNSelect drain
it "send/select & recv/select doesn't blow up" $
do sendRecv 3 1 10 sendNSelect drainSelect
it "multi-case select doesn't blow up" $ do multiTest 3
type Sender = Chan Int -> Int -> Int -> IO ()
type Drainer = Chan Int -> (Int -> IO ()) -> IO () -> IO ()
drain :: Drainer
drain ch recvAct closeAct = do
mn <- chanRecv ch
case mn of
Msg n -> do
recvAct n
drain ch recvAct closeAct
_ -> closeAct
drainSelect :: Drainer
drainSelect ch recvAct closeAct = do
chanSelect
[ Recv
ch
(\case
Msg n -> do
recvAct n
drainSelect ch recvAct closeAct
_ -> closeAct)]
Nothing
sendN :: Sender
sendN ch low hi = do
chanSend ch low
when (low < hi) (sendN ch (low + 1) hi)
sendNSelect :: Sender
sendNSelect ch low hi = do
chanSelect [Send ch low (return ())] Nothing
when (low < hi) (sendNSelect ch (low + 1) hi)
sendRecv :: Int -> Int -> Int -> Sender -> Drainer -> Expectation
sendRecv size low hi sender drainer = do
lock <- newEmptyMVar
c <- chanMake size
totalRef <- newIORef 0
forkIO $
do sender c low hi
chanClose c
drainer
c
(\n ->
modifyIORef' totalRef (+ n))
(when (size > 0) (putMVar lock ()))
readIORef totalRef
-- when the channel is un-buffered, draining should act as synchronization;
-- only lock when the buffer size is greater than 0.
when
(size > 0)
(takeMVar lock)
total <- readIORef totalRef
total `shouldBe` sum [low .. hi]
multiTest :: Int -> Expectation
multiTest size = do
lock1 <- newEmptyMVar
lock2 <- newEmptyMVar
c1 <- chanMake size
c2 <- chanMake size
c1sentRef <- newIORef 0
c1recvdRef <- newIORef 0
c2sentRef <- newIORef 0
c2recvdRef <- newIORef 0
forkIO $ ping2 c1sentRef c2sentRef c1 c2 0 (putMVar lock2 ())
pong2 c1recvdRef c2recvdRef c1 c2 0 (putMVar lock1 ())
takeMVar lock1
takeMVar lock2
c1sent <- readIORef c1sentRef
c1recvd <- readIORef c1recvdRef
c2sent <- readIORef c2sentRef
c2recvd <- readIORef c2recvdRef
-- each channel should recv as often as it is sent on.
(c1sent, c2sent) `shouldBe`
(c1recvd, c2recvd)
ping2
:: IORef Int
-> IORef Int
-> Chan Int
-> Chan Int
-> Int
-> IO ()
-> IO ()
ping2 ref1 ref2 c1 c2 n doneAct = do
if (n < 20)
then do
chanSelect
[ Send c1 n (void (modifyIORef' ref1 (+ 1)))
, Send c2 n (void (modifyIORef' ref2 (+ 1)))]
Nothing
ping2 ref1 ref2 c1 c2 (n + 1) doneAct
else doneAct
pong2
:: IORef Int
-> IORef Int
-> Chan Int
-> Chan Int
-> Int
-> IO ()
-> IO ()
pong2 ref1 ref2 c1 c2 n doneAct = do
if (n < 20)
then do
chanSelect
[ Recv
c1
(\case
Msg n -> modifyIORef' ref1 (+ 1))
, Recv
c2
(\case
Msg n -> modifyIORef' ref2 (+ 1))]
Nothing
pong2 ref1 ref2 c1 c2 (n + 1) doneAct
else doneAct
| cstrahan/gochan | fuzz/Main.hs | mit | 5,923 | 0 | 18 | 2,272 | 1,784 | 821 | 963 | 158 | 2 |
module Problem16 where
import Data.Char (digitToInt)
main = print . sum . map digitToInt . show $ 2^1000
| DevJac/haskell-project-euler | src/Problem16.hs | mit | 107 | 0 | 9 | 20 | 42 | 23 | 19 | 3 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE StandaloneDeriving #-}
-- | /Warning/: This is an internal module and subject
-- to change without notice.
module System.ZMQ4.Internal
( Context (..)
, Socket (..)
, SocketRepr (..)
, SocketType (..)
, SocketLike (..)
, Message (..)
, Flag (..)
, Timeout
, Size
, Switch (..)
, EventType (..)
, EventMsg (..)
, SecurityMechanism (..)
, KeyFormat (..)
, messageOf
, messageOfLazy
, messageClose
, messageFree
, messageInit
, messageInitSize
, setIntOpt
, setStrOpt
, getIntOpt
, getStrOpt
, getInt32Option
, setInt32OptFromRestricted
, ctxIntOption
, setCtxIntOption
, getByteStringOpt
, setByteStringOpt
, z85Encode
, z85Decode
, toZMQFlag
, combine
, combineFlags
, mkSocketRepr
, closeSock
, onSocket
, bool2cint
, toSwitch
, fromSwitch
, events2cint
, eventMessage
, toMechanism
, fromMechanism
, getKey
) where
import Control.Applicative
import Control.Monad (foldM_, when, void)
import Control.Monad.IO.Class
import Control.Exception
import Data.IORef (IORef, mkWeakIORef, readIORef, atomicModifyIORef)
import Foreign hiding (throwIfNull, void)
import Foreign.C.String
import Foreign.C.Types (CInt, CSize)
import Data.IORef (newIORef)
import Data.Restricted
import Data.Typeable
import Prelude
import System.Posix.Types (Fd(..))
import System.ZMQ4.Internal.Base
import System.ZMQ4.Internal.Error
import qualified Data.ByteString as SB
import qualified Data.ByteString.Lazy as LB
import qualified Data.ByteString.Unsafe as UB
type Timeout = Int64
type Size = Word
-- | Flags to apply on send operations (cf. man zmq_send)
data Flag =
DontWait -- ^ ZMQ_DONTWAIT (Only relevant on Windows.)
| SendMore -- ^ ZMQ_SNDMORE
deriving (Eq, Ord, Show)
-- | Configuration switch
data Switch =
Default -- ^ Use default setting
| On -- ^ Activate setting
| Off -- ^ De-activate setting
deriving (Eq, Ord, Show)
-- | Event types to monitor.
data EventType =
ConnectedEvent
| ConnectDelayedEvent
| ConnectRetriedEvent
| ListeningEvent
| BindFailedEvent
| AcceptedEvent
| AcceptFailedEvent
| ClosedEvent
| CloseFailedEvent
| DisconnectedEvent
| MonitorStoppedEvent
| AllEvents
deriving (Eq, Ord, Show)
-- | Event Message to receive when monitoring socket events.
data EventMsg =
Connected !SB.ByteString !Fd
| ConnectDelayed !SB.ByteString
| ConnectRetried !SB.ByteString !Int
| Listening !SB.ByteString !Fd
| BindFailed !SB.ByteString !Int
| Accepted !SB.ByteString !Fd
| AcceptFailed !SB.ByteString !Int
| Closed !SB.ByteString !Fd
| CloseFailed !SB.ByteString !Int
| Disconnected !SB.ByteString !Fd
| MonitorStopped !SB.ByteString !Int
deriving (Eq, Show)
data SecurityMechanism
= Null
| Plain
| Curve
deriving (Eq, Show)
data KeyFormat a where
BinaryFormat :: KeyFormat Div4
TextFormat :: KeyFormat Div5
deriving instance Eq (KeyFormat a)
deriving instance Show (KeyFormat a)
-- | A 0MQ context representation.
newtype Context = Context { _ctx :: ZMQCtx }
deriving instance Typeable Context
-- | A 0MQ Socket.
newtype Socket a = Socket
{ _socketRepr :: SocketRepr }
data SocketRepr = SocketRepr
{ _socket :: ZMQSocket
, _sockLive :: IORef Bool
}
-- | Socket types.
class SocketType a where
zmqSocketType :: a -> ZMQSocketType
class SocketLike s where
toSocket :: s t -> Socket t
instance SocketLike Socket where
toSocket = id
-- A 0MQ Message representation.
newtype Message = Message { msgPtr :: ZMQMsgPtr }
-- internal helpers:
onSocket :: String -> Socket a -> (ZMQSocket -> IO b) -> IO b
onSocket _func (Socket (SocketRepr sock _state)) act = act sock
{-# INLINE onSocket #-}
mkSocketRepr :: SocketType t => t -> Context -> IO SocketRepr
mkSocketRepr t c = do
let ty = typeVal (zmqSocketType t)
s <- throwIfNull "mkSocketRepr" (c_zmq_socket (_ctx c) ty)
ref <- newIORef True
addFinalizer ref $ do
alive <- readIORef ref
when alive $ c_zmq_close s >> return ()
return (SocketRepr s ref)
where
addFinalizer r f = mkWeakIORef r f >> return ()
closeSock :: SocketRepr -> IO ()
closeSock (SocketRepr s status) = do
alive <- atomicModifyIORef status (\b -> (False, b))
when alive $ throwIfMinus1_ "close" . c_zmq_close $ s
messageOf :: SB.ByteString -> IO Message
messageOf b = UB.unsafeUseAsCStringLen b $ \(cstr, len) -> do
msg <- messageInitSize (fromIntegral len)
data_ptr <- c_zmq_msg_data (msgPtr msg)
copyBytes data_ptr cstr len
return msg
messageOfLazy :: LB.ByteString -> IO Message
messageOfLazy lbs = do
msg <- messageInitSize (fromIntegral len)
data_ptr <- c_zmq_msg_data (msgPtr msg)
let fn offset bs = UB.unsafeUseAsCStringLen bs $ \(cstr, str_len) -> do
copyBytes (data_ptr `plusPtr` offset) cstr str_len
return (offset + str_len)
foldM_ fn 0 (LB.toChunks lbs)
return msg
where
len = LB.length lbs
messageClose :: Message -> IO ()
messageClose (Message ptr) = do
throwIfMinus1_ "messageClose" $ c_zmq_msg_close ptr
free ptr
messageFree :: Message -> IO ()
messageFree (Message ptr) = free ptr
messageInit :: IO Message
messageInit = do
ptr <- new (ZMQMsg nullPtr)
throwIfMinus1_ "messageInit" $ c_zmq_msg_init ptr
return (Message ptr)
messageInitSize :: Size -> IO Message
messageInitSize s = do
ptr <- new (ZMQMsg nullPtr)
throwIfMinus1_ "messageInitSize" $
c_zmq_msg_init_size ptr (fromIntegral s)
return (Message ptr)
setIntOpt :: (Storable b, Integral b) => Socket a -> ZMQOption -> b -> IO ()
setIntOpt sock (ZMQOption o) i = onSocket "setIntOpt" sock $ \s ->
throwIfMinus1Retry_ "setIntOpt" $ with i $ \ptr ->
c_zmq_setsockopt s (fromIntegral o)
(castPtr ptr)
(fromIntegral . sizeOf $ i)
setCStrOpt :: ZMQSocket -> ZMQOption -> CStringLen -> IO CInt
setCStrOpt s (ZMQOption o) (cstr, len) =
c_zmq_setsockopt s (fromIntegral o) (castPtr cstr) (fromIntegral len)
setByteStringOpt :: Socket a -> ZMQOption -> SB.ByteString -> IO ()
setByteStringOpt sock opt str = onSocket "setByteStringOpt" sock $ \s ->
throwIfMinus1Retry_ "setByteStringOpt" . UB.unsafeUseAsCStringLen str $ setCStrOpt s opt
setStrOpt :: Socket a -> ZMQOption -> String -> IO ()
setStrOpt sock opt str = onSocket "setStrOpt" sock $ \s ->
throwIfMinus1Retry_ "setStrOpt" . withCStringLen str $ setCStrOpt s opt
getIntOpt :: (Storable b, Integral b) => Socket a -> ZMQOption -> b -> IO b
getIntOpt sock (ZMQOption o) i = onSocket "getIntOpt" sock $ \s -> do
bracket (new i) free $ \iptr ->
bracket (new (fromIntegral . sizeOf $ i :: CSize)) free $ \jptr -> do
throwIfMinus1Retry_ "getIntOpt" $
c_zmq_getsockopt s (fromIntegral o) (castPtr iptr) jptr
peek iptr
getCStrOpt :: (CStringLen -> IO s) -> Socket a -> ZMQOption -> IO s
getCStrOpt peekA sock (ZMQOption o) = onSocket "getCStrOpt" sock $ \s ->
bracket (mallocBytes 255) free $ \bPtr ->
bracket (new (255 :: CSize)) free $ \sPtr -> do
throwIfMinus1Retry_ "getCStrOpt" $
c_zmq_getsockopt s (fromIntegral o) (castPtr bPtr) sPtr
peek sPtr >>= \len -> peekA (bPtr, fromIntegral len)
getStrOpt :: Socket a -> ZMQOption -> IO String
getStrOpt = getCStrOpt (peekCString . fst)
getByteStringOpt :: Socket a -> ZMQOption -> IO SB.ByteString
getByteStringOpt = getCStrOpt SB.packCStringLen
getInt32Option :: ZMQOption -> Socket a -> IO Int
getInt32Option o s = fromIntegral <$> getIntOpt s o (0 :: CInt)
setInt32OptFromRestricted :: Integral i => ZMQOption -> Restricted r i -> Socket b -> IO ()
setInt32OptFromRestricted o x s = setIntOpt s o ((fromIntegral . rvalue $ x) :: CInt)
ctxIntOption :: Integral i => String -> ZMQCtxOption -> Context -> IO i
ctxIntOption name opt ctx = fromIntegral <$>
(throwIfMinus1 name $ c_zmq_ctx_get (_ctx ctx) (ctxOptVal opt))
setCtxIntOption :: Integral i => String -> ZMQCtxOption -> i -> Context -> IO ()
setCtxIntOption name opt val ctx = throwIfMinus1_ name $
c_zmq_ctx_set (_ctx ctx) (ctxOptVal opt) (fromIntegral val)
z85Encode :: (MonadIO m) => Restricted Div4 SB.ByteString -> m SB.ByteString
z85Encode b = liftIO $ UB.unsafeUseAsCStringLen (rvalue b) $ \(c, s) ->
allocaBytes ((s * 5) `div` 4 + 1) $ \w -> do
void . throwIfNull "z85Encode" $
c_zmq_z85_encode w (castPtr c) (fromIntegral s)
SB.packCString w
z85Decode :: (MonadIO m) => Restricted Div5 SB.ByteString -> m SB.ByteString
z85Decode b = liftIO $ SB.useAsCStringLen (rvalue b) $ \(c, s) -> do
let size = (s * 4) `div` 5
allocaBytes size $ \w -> do
void . throwIfNull "z85Decode" $
c_zmq_z85_decode (castPtr w) (castPtr c)
SB.packCStringLen (w, size)
getKey :: KeyFormat f -> Socket a -> ZMQOption -> IO SB.ByteString
getKey kf sock (ZMQOption o) = onSocket "getKey" sock $ \s -> do
let len = case kf of
BinaryFormat -> 32
TextFormat -> 41
with len $ \lenptr -> allocaBytes len $ \w -> do
throwIfMinus1Retry_ "getKey" $
c_zmq_getsockopt s (fromIntegral o) (castPtr w) (castPtr lenptr)
SB.packCString w
toZMQFlag :: Flag -> ZMQFlag
toZMQFlag DontWait = dontWait
toZMQFlag SendMore = sndMore
combineFlags :: [Flag] -> CInt
combineFlags = fromIntegral . combine . map (flagVal . toZMQFlag)
combine :: (Integral i, Bits i) => [i] -> i
combine = foldr (.|.) 0
bool2cint :: Bool -> CInt
bool2cint True = 1
bool2cint False = 0
toSwitch :: (Show a, Integral a) => String -> a -> Switch
toSwitch _ (-1) = Default
toSwitch _ 0 = Off
toSwitch _ 1 = On
toSwitch m n = error $ m ++ ": " ++ show n
fromSwitch :: Integral a => Switch -> a
fromSwitch Default = -1
fromSwitch Off = 0
fromSwitch On = 1
toZMQEventType :: EventType -> ZMQEventType
toZMQEventType AllEvents = allEvents
toZMQEventType ConnectedEvent = connected
toZMQEventType ConnectDelayedEvent = connectDelayed
toZMQEventType ConnectRetriedEvent = connectRetried
toZMQEventType ListeningEvent = listening
toZMQEventType BindFailedEvent = bindFailed
toZMQEventType AcceptedEvent = accepted
toZMQEventType AcceptFailedEvent = acceptFailed
toZMQEventType ClosedEvent = closed
toZMQEventType CloseFailedEvent = closeFailed
toZMQEventType DisconnectedEvent = disconnected
toZMQEventType MonitorStoppedEvent = monitorStopped
toMechanism :: SecurityMechanism -> ZMQSecMechanism
toMechanism Null = secNull
toMechanism Plain = secPlain
toMechanism Curve = secCurve
fromMechanism :: String -> Int -> SecurityMechanism
fromMechanism s m
| m == secMechanism secNull = Null
| m == secMechanism secPlain = Plain
| m == secMechanism secCurve = Curve
| otherwise = error $ s ++ ": " ++ show m
events2cint :: [EventType] -> CInt
events2cint = fromIntegral . foldr ((.|.) . eventTypeVal . toZMQEventType) 0
eventMessage :: SB.ByteString -> ZMQEvent -> EventMsg
eventMessage str (ZMQEvent e v)
| e == connected = Connected str (Fd . fromIntegral $ v)
| e == connectDelayed = ConnectDelayed str
| e == connectRetried = ConnectRetried str (fromIntegral $ v)
| e == listening = Listening str (Fd . fromIntegral $ v)
| e == bindFailed = BindFailed str (fromIntegral $ v)
| e == accepted = Accepted str (Fd . fromIntegral $ v)
| e == acceptFailed = AcceptFailed str (fromIntegral $ v)
| e == closed = Closed str (Fd . fromIntegral $ v)
| e == closeFailed = CloseFailed str (fromIntegral $ v)
| e == disconnected = Disconnected str (fromIntegral $ v)
| e == monitorStopped = MonitorStopped str (fromIntegral $ v)
| otherwise = error $ "unknown event type: " ++ show e
| twittner/zeromq-haskell | src/System/ZMQ4/Internal.hs | mit | 12,198 | 0 | 18 | 2,917 | 3,892 | 1,996 | 1,896 | -1 | -1 |
{-
Copyright (C) 2017 WATANABE Yuki <magicant@wonderwand.net>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-}
{-# LANGUAGE Safe #-}
{-|
Copyright : (C) 2017 WATANABE Yuki
License : GPL-2
Portability : portable
This module defines the abstract syntax tree of the shell language.
-}
module Flesh.Language.Syntax (
-- * Names
isPosixNameChar, isPosixNameString, isSpecialParameter,
-- * Tokens
DoubleQuoteUnit(..), unquoteDoubleQuoteUnit,
WordUnit(..), unquoteWordUnit,
EWord(..), wordUnits, wordText,
Token(..), tokenUnits, tokenWord, tokenText, unquoteToken, positionOfToken,
posixNameFromToken,
Assignment(..),
-- * Redirections
HereDocOp(..), FileOp(..), Redirection(..), fd,
-- * Syntax
IfThenList, CaseItem, CompoundCommand(..), Command(..), Pipeline(..),
AndOrCondition(..), ConditionalPipeline(..), AndOrList(..),
showSeparatedList, CommandList) where
import Control.Monad (guard)
import Data.Char (isAsciiLower, isAsciiUpper, isDigit)
import Data.List.NonEmpty (NonEmpty((:|)), toList)
import Data.Monoid (Endo(Endo), appEndo)
import Data.Text (Text, pack, unpack)
import Flesh.Source.Position (Position, Positioned)
import Numeric.Natural (Natural)
-- Utility for Show instances
showSpace :: ShowS
showSpace = showChar ' '
-- | Returns true iff the argument character can be used in POSIX names.
isPosixNameChar :: Char -> Bool
isPosixNameChar c | isDigit c = True
| isAsciiLower c = True
| isAsciiUpper c = True
| c == '_' = True
| otherwise = False
-- | Returns true iff the argument is an unquoted POSIX name.
isPosixNameString :: String -> Bool
isPosixNameString [] = False
isPosixNameString cs@(c:_) = not (isDigit c) && all isPosixNameChar cs
-- | Returns true iff the argument char is a special parameter name.
isSpecialParameter :: Char -> Bool
isSpecialParameter = flip elem "@*#?-$!0"
-- | Element of double quotes.
data DoubleQuoteUnit =
-- | Single bear character.
Char !Char
-- | Character escaped by a backslash.
| Backslashed !Char
-- | Parameter expansion.
| Parameter Text -- TODO prefix, TODO modifier
-- | @$(...)@
| CommandSubstitution String
-- | @`...`@
| Backquoted String
-- | @$((...))@ where the inner EWord is of the form @(...)@
| Arithmetic EWord
deriving (Eq)
instance Show DoubleQuoteUnit where
showsPrec _ (Char c) = showChar c
showsPrec _ (Backslashed c) = \s -> '\\':c:s
showsPrec _ (Parameter name) =
showString "${" . showString (unpack name) . showChar '}'
showsPrec _ (CommandSubstitution cs) =
showString "$(" . showString cs . showChar ')'
showsPrec n (Backquoted cs) = bq . f (n /= 0) cs . bq
where bq = showChar '`'
f _ "" = id
f dq (c':cs') | c' == '`' || c' == '\\' || (dq && c' == '"') =
showChar '\\' . showChar c' . f dq cs'
| otherwise =
showChar c' . f dq cs'
-- In (Arithmetic w), w always has an open and close parenthesis, so the
-- number of parentheses is correct here.
showsPrec _ (Arithmetic w) = showString "$(" . shows w . showChar ')'
-- | Just joins the given units, without enclosing double quotes.
{-
showList [] = id
showList (u:us) = shows u . showList us
-}
showList = foldr ((.) . shows) id
-- | Converts a backslashed character to a bare character. Other double-quote
-- units are returned intact. The Boolean is True iff conversion was
-- performed.
unquoteDoubleQuoteUnit :: DoubleQuoteUnit -> (Bool, DoubleQuoteUnit)
unquoteDoubleQuoteUnit (Backslashed c) = (True, Char c)
unquoteDoubleQuoteUnit u = (False, u)
-- | Element of words.
data WordUnit =
-- | Unquoted double-quote unit as a word unit.
Unquoted !DoubleQuoteUnit
-- | Double-quote.
| DoubleQuote [Positioned DoubleQuoteUnit]
-- | Single-quote.
| SingleQuote [Positioned Char]
deriving (Eq)
instance Show WordUnit where
showsPrec n (Unquoted unit) = showsPrec n unit
showsPrec _ (DoubleQuote units) =
showChar '"' . (\s -> foldr (showsPrec 1 . snd) s units) . showChar '"'
showsPrec _ (SingleQuote chars) =
showChar '\'' . (\s -> foldr (showChar . snd) s chars) . showChar '\''
{-
showList [] = id
showList (u:us) = shows u . showList us
-}
showList = foldr ((.) . shows) id
-- | Removes backslash escapes, double-quotes, and single-quotes without word
-- expansion. The Boolean is true iff quotation was removed.
unquoteWordUnit :: WordUnit -> (Bool, [DoubleQuoteUnit])
unquoteWordUnit (Unquoted u) = (b, [u'])
where ~(b, u') = unquoteDoubleQuoteUnit u
unquoteWordUnit (DoubleQuote us) = (True, unq <$> us)
where unq = snd . unquoteDoubleQuoteUnit . snd
unquoteWordUnit (SingleQuote cs) = (True, Char . snd <$> cs)
-- | Expandable word, a possibly empty list of word units.
newtype EWord = EWord [Positioned WordUnit]
deriving (Eq)
-- | Returns the content of a word.
wordUnits :: EWord -> [Positioned WordUnit]
wordUnits (EWord us) = us
-- | If the given word consists of constant unquoted characters only, then
-- returns the content as a text.
wordText :: EWord -> Maybe Text
wordText us = fmap pack $ traverse (constChar . snd) $ wordUnits us
where constChar (Unquoted (Char c)) = Just c
constChar _ = Nothing
instance Show EWord where
showsPrec n (EWord us) s = foldr (showsPrec n . snd) s us
showList [] = id
showList [w] = shows w
showList (w:ws) = shows w . showSpace . showList ws
-- | Non-empty word, defined as a (lexical) token with the token identifier
-- @TOKEN@ in POSIX.
newtype Token = Token (NonEmpty (Positioned WordUnit))
deriving (Eq)
-- | Returns the content of a token.
tokenUnits :: Token -> NonEmpty (Positioned WordUnit)
tokenUnits (Token us) = us
-- | Converts a token to a word.
tokenWord :: Token -> EWord
tokenWord = EWord . toList . tokenUnits
-- | If the given token consists of constant unquoted characters only, then
-- returns the content as a text.
tokenText :: Token -> Maybe Text
tokenText = wordText . tokenWord
-- | Removes backslash escapes, double-quotes, and single-quotes without word
-- expansion. The Boolean is true iff quotation was removed.
unquoteToken :: Token -> (Bool, [DoubleQuoteUnit])
unquoteToken t = (or bs, concat uss)
where ~(bs, uss) = unq t
unq = unzip . fmap unquoteWordUnit . toList . fmap snd . tokenUnits
-- | Returns the position of the token
positionOfToken :: Token -> Position
positionOfToken (Token ((p, _) :| _)) = p
-- | Returns the token text only if the argument is an unquoted POSIX name.
posixNameFromToken :: Token -> Maybe Text
posixNameFromToken t = do
let ttt = tokenText t
tx <- ttt
guard $ isPosixNameString $ unpack tx
ttt
instance Show Token where
showsPrec n t = showsPrec n (tokenWord t)
showList ts = showList (fmap tokenWord ts)
-- | Assignment.
data Assignment = Assignment Token EWord
deriving (Eq)
instance Show Assignment where
showsPrec n (Assignment name value) =
showsPrec n name . showChar '=' . showsPrec n value
showList [] = id
showList [a] = shows a
showList (a:as) = shows a . showSpace . showList as
-- | Here document redirection operator.
data HereDocOp = HereDocOp {
hereDocOpPos :: Position,
hereDocFd :: !Natural,
isTabbed :: !Bool,
delimiter :: Token}
deriving (Eq)
instance Show HereDocOp where
showsPrec n o =
showsPrec n (hereDocFd o) . showString s . showsPrec n (delimiter o)
where s = if isTabbed o then "<<-" else "<<"
-- | Types of file redirection operations.
data FileOp =
In -- ^ @<@
| InOut -- ^ @<>@
| Out -- ^ @>@
| Append -- ^ @>>@
| Clobber -- ^ @>|@
| DupIn -- ^ @<&@
| DupOut -- ^ @>&@
deriving (Eq)
instance Show FileOp where
showsPrec _ In = showString "<"
showsPrec _ InOut = showString "<>"
showsPrec _ Out = showString ">"
showsPrec _ Append = showString ">>"
showsPrec _ Clobber = showString ">|"
showsPrec _ DupIn = showString "<&"
showsPrec _ DupOut = showString ">&"
-- | Redirection.
data Redirection =
FileRedirection {
fileOpPos :: Position,
fileOpFd :: !Natural,
fileOp :: !FileOp,
fileOpTarget :: Token}
| HereDoc {
hereDocOp :: !HereDocOp,
content :: [Positioned DoubleQuoteUnit]}
deriving (Eq)
instance Show Redirection where
showsPrec n (FileRedirection _ fd' op f) =
showsPrec n fd' . showsPrec n op . showsPrec n f
showsPrec n (HereDoc o _) = showsPrec n o -- content is ignored
showList [] = id
showList [r] = shows r
showList (r:rs) = shows r . showSpace . showList rs
-- | Returns the target file descriptor of the given redirection.
fd :: Redirection -> Natural
fd (FileRedirection _ fd' _ _) = fd'
fd (HereDoc (HereDocOp _ fd' _ _) _) = fd'
-- | List of (el)if-then clauses. Each pair represents a condition and
-- corresponding statement.
type IfThenList = NonEmpty (CommandList, CommandList)
-- | Body of the case command. One or more patterns and zero or more and-or
-- lists.
type CaseItem = (NonEmpty Token, [AndOrList])
-- | Commands that can contain other commands.
data CompoundCommand =
-- | one or more and-or lists.
Grouping CommandList
-- | one or more and-or lists.
| Subshell CommandList
-- | name, optional words, and loop body.
| For Token (Maybe [Token]) CommandList
-- | word and case items.
| Case Token [CaseItem]
-- | list of (el)if-then clauses and optional else clause.
| If IfThenList (Maybe CommandList)
-- | loop condition and body.
| While CommandList CommandList
-- | loop condition and body.
| Until CommandList CommandList
-- TODO Ksh-style function definition.
deriving (Eq)
showEach :: (a -> ShowS) -> [a] -> ShowS
showEach f = appEndo . mconcat . fmap (Endo . f)
showPattern :: Token -> ShowS
showPattern p = showString " | " . shows p
showCaseItem :: CaseItem -> ShowS
showCaseItem (p :| ps, ls) =
showChar '(' . shows p . showEach showPattern ps . showString ") " .
showList ls . showString ";; "
showDoGroup :: CommandList -> ShowS
showDoGroup c =
showString " do " . showSeparatedList (toList c) . showString " done"
showWhileUntilTail :: CommandList -> CommandList -> ShowS
showWhileUntilTail c b = showSeparatedList (toList c) . showDoGroup b
instance Show CompoundCommand where
showsPrec _ (Grouping ls) =
showString "{ " . showSeparatedList (toList ls) . showString " }"
showsPrec _ (Subshell ls) =
showChar '(' . showList (toList ls) . showChar ')'
showsPrec _ (For name optwords ls) =
showString "for " . shows name . showForWords optwords . showDoGroup ls
where showForWords Nothing = id
showForWords (Just ws) =
showString " in " . shows ws . showChar ';'
showsPrec _ (Case w is) =
showString "case " . shows w . showString " in " .
showEach showCaseItem is . showString "esac"
showsPrec _ (If its me) =
showIfThenList its . maybeShowElse me . showString " fi"
where showIfThenList (ifthen :| elifthens) =
showIfThen ifthen . showElifThenList elifthens
showElifThenList [] = id
showElifThenList (h:t) =
showString " el" . showIfThen h . showElifThenList t
showIfThen (c, t) =
showString "if " . showSeparatedList (toList c) .
showString " then " . showSeparatedList (toList t)
maybeShowElse Nothing = id
maybeShowElse (Just e) =
showString " else " . showSeparatedList (toList e)
showsPrec _ (While c b) =
showString "while " . showWhileUntilTail c b
showsPrec _ (Until c b) =
showString "until " . showWhileUntilTail c b
-- | Element of pipelines.
data Command =
-- | Simple command.
SimpleCommand [Token] [Assignment] [Redirection]
-- | Compound commands
| CompoundCommand (Positioned CompoundCommand) [Redirection]
-- | Bourne-style function definition.
| FunctionDefinition Text Command
deriving (Eq)
instance Show Command where
showsPrec _ (SimpleCommand [] [] []) = id
showsPrec _ (SimpleCommand ts [] []) = showList ts
showsPrec _ (SimpleCommand [] as []) = showList as
showsPrec _ (SimpleCommand [] [] rs) = showList rs
showsPrec _ (SimpleCommand ts [] rs) = showList ts . showSpace . showList rs
showsPrec n (SimpleCommand ts as rs) =
showList as . showSpace . showsPrec n (SimpleCommand ts [] rs)
showsPrec n (CompoundCommand (_, cc) []) = showsPrec n cc
showsPrec n (CompoundCommand (_, cc) rs) =
showsPrec n cc . showSpace . showList rs
showsPrec n (FunctionDefinition name cmd) =
showString (unpack name) . showString "() " . showsPrec n cmd
-- | Element of and-or lists. Optionally negated sequence of one or more
-- commands.
data Pipeline = Pipeline {
pipeCommands :: NonEmpty Command,
isNegated :: !Bool}
deriving (Eq)
instance Show Pipeline where
showsPrec n (Pipeline cs True) =
showString "! " . showsPrec n (Pipeline cs False)
showsPrec n (Pipeline (h :| t) False) = showsPrec n h . ft
where ft s = foldr step s t
step c = showString " | " . shows c
-- | Condition that determines if a pipeline should be executed in an and-or
-- list.
data AndOrCondition = AndThen | OrElse
deriving (Eq)
instance Show AndOrCondition where
show AndThen = "&&"
show OrElse = "||"
-- | Pipeline executed conditionally in an and-or list.
newtype ConditionalPipeline = ConditionalPipeline (AndOrCondition, Pipeline)
deriving (Eq)
instance Show ConditionalPipeline where
showsPrec n (ConditionalPipeline (c, p)) =
showsPrec n c . showSpace . showsPrec n p
showList [] = id
showList [p] = shows p
showList (p:ps) = shows p . showSpace . showList ps
-- | One or more pipelines executed conditionally in sequence. The entire
-- sequence can be executed either synchronously or asynchronously.
data AndOrList = AndOrList {
andOrHead :: Pipeline,
andOrTail :: [ConditionalPipeline],
isAsynchronous :: !Bool}
deriving (Eq)
showAndOrHeadTail :: Pipeline -> [ConditionalPipeline] -> ShowS
showAndOrHeadTail h [] = shows h
showAndOrHeadTail h t = shows h . showSpace . showList t
instance Show AndOrList where
showsPrec n (AndOrList h t False) | n <= 0 = showAndOrHeadTail h t
showsPrec _ (AndOrList h t isAsync) = showAndOrHeadTail h t . showChar c
where c = if isAsync then '&' else ';'
showList [] = id
showList [l] = shows l
showList (l:ls) = showsPrec 1 l . showSpace . showList ls
-- | Shows a list of and-or lists. Unlike 'showList', the trailing separator
-- for the last and-or list is never omitted.
showSeparatedList :: [AndOrList] -> ShowS
showSeparatedList [] = id
showSeparatedList [l] = showsPrec 1 l
showSeparatedList (l:ls) = showsPrec 1 l . showSpace . showSeparatedList ls
-- | Sequence of one or more and-or lists. In POSIX, CommandList is simply
-- referred to as "list".
type CommandList = NonEmpty AndOrList
-- vim: set et sw=2 sts=2 tw=78:
| magicant/flesh | src/Flesh/Language/Syntax.hs | gpl-2.0 | 15,553 | 0 | 14 | 3,415 | 4,209 | 2,205 | 2,004 | 304 | 2 |
import qualified Data.Vector as V
import qualified Data.List as L
accSum :: Num t => [t] -> [t]
accSum xs = aux xs 0
where aux [] a = []
aux (x:xs') a = (a + x) : aux xs' (a + x)
lowerBound :: (Num a, Ord a) => V.Vector a -> a -> Int
lowerBound vec target = aux 0 ((V.length vec) - 1)
where
aux l r = if l > r then l
else let mid = (l + r) `div` 2
in if vec V.! mid >= target then
aux l (mid - 1)
else aux (mid + 1) r
upperBound :: (Num a, Ord a) => V.Vector a -> a -> Int
upperBound vec target = aux 0 ((V.length vec) - 1)
where
aux l r = if l > r then l
else let mid = (l + r) `div` 2
in if vec V.! mid > target then
aux l (mid - 1)
else aux (mid + 1) r
solve :: (Num a, Ord a) => [a] -> [a] -> [Int]
solve xs queries =
let vec = V.fromList $ accSum $ reverse (L.sort xs)
f x = if x <= V.length vec then x else -1
in map (\x -> f $ lowerBound vec x + 1) queries
main = do
_ <- getLine
arr <- getLine
_ <- getLine
queries <- getContents
let xs = map (read :: String -> Int) (words arr)
qs = map (read :: String -> Int) (lines queries)
mapM_ (putStrLn . show) $ solve xs qs
| m00nlight/hackerrank | functional/ad-hoc/Subset-Sum/main.hs | gpl-2.0 | 1,328 | 0 | 14 | 515 | 657 | 341 | 316 | 33 | 3 |
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TupleSections #-}
module ProcessPool
( Job(jobValue)
, Result(..)
, Process(Process,inHandle,outHandle)
, makePropertyJob
, makeTimingJob
, cleanupTimings
, cleanupOutput
, cleanupProperties
, processJobsParallel
, processJobsParallelWithSharedPool
, withProcessPool
) where
import Control.Monad (guard, unless, void)
import Control.Monad.Catch (onError, try, uninterruptibleMask_)
import Control.Monad.Logger (Loc, LogLevel, LogSource, LogStr, LoggingT)
import qualified Control.Monad.Logger as Log
import Control.Monad.Trans.Resource (ReleaseKey, allocate, register, release)
import Data.Acquire (withAcquire, mkAcquireType, ReleaseType(ReleaseException))
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Builder as BS
import Data.Conduit (ConduitT)
import Data.Maybe (fromMaybe)
import Data.Pool (Pool)
import qualified Data.Pool as Pool
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Time.LocalTime as Time
import Data.Time.Calendar (DayOfWeek(Saturday,Sunday), dayOfWeek)
import Network.HostName (getHostName)
import System.Directory (removeFile)
import System.Exit (ExitCode(ExitFailure))
import System.FilePath ((<.>))
import System.IO (BufferMode(LineBuffering), Handle)
import qualified System.IO as System
import System.IO.Error (isDoesNotExistError)
import System.Posix.Signals (sigKILL, signalProcess)
import System.Process (CreateProcess(..), ProcessHandle, Pid, StdStream(..))
import qualified System.Process as Proc
import BroadcastChan.Conduit
import Core
import ProcessTools (UnexpectedTermination, unexpectedTermination)
import RuntimeData (getKernelExecutable, getKernelLibPath)
import Query (MonadQuery)
import Schema
import Sql (MonadSql, (+=.), getGlobalVar)
import qualified Sql
data Job a = Job
{ jobValue :: a
, jobVariant :: Key Variant
, jobLabel :: Text
, jobCommand :: Text
, jobLogProperties :: Bool
} deriving (Functor, Foldable, Show, Traversable)
makeJob
:: Bool
-> a
-> Key Variant
-> Maybe (Key Platform, Text)
-> [Text]
-> Job a
makeJob logProps val variantId implName args = Job
{ jobValue = val
, jobVariant = variantId
, jobLabel = label
, jobCommand = T.unwords $ "\"" <> label <> "\"" : finalArgs
, jobLogProperties = logProps
}
where
finalArgs
| logProps = "-k switch --log" : logFile : args
| otherwise = args
logFile = "\"" <> label <> ".log" <> "\""
label = case implName of
Nothing -> showSqlKey variantId
Just (platformId, name) -> mconcat
[ showSqlKey platformId, " ", showSqlKey variantId, " ", name ]
makePropertyJob
:: a -> Key Variant -> Maybe (Key Platform, Text) -> [Text] -> Job a
makePropertyJob = makeJob True
makeTimingJob
:: a -> Key Variant -> Maybe (Key Platform, Text) -> [Text] -> Job a
makeTimingJob = makeJob False
data Result a = Result
{ resultValue :: a
, resultVariant :: Key Variant
, resultLabel :: Text
, resultAlgorithmVersion :: CommitId
, resultOutput :: (FilePath, ReleaseKey)
, resultTimings :: (FilePath, ReleaseKey)
, resultPropLog :: Maybe (FilePath, ReleaseKey)
} deriving (Functor, Foldable, Traversable)
cleanupOutput :: MonadIO m => Result a -> m ()
cleanupOutput Result{resultOutput = (_, key)} = release key
cleanupTimings :: MonadIO m => Result a -> m ()
cleanupTimings Result{resultTimings = (_, key)} = release key
cleanupProperties :: MonadIO m => Result a -> m ()
cleanupProperties Result{resultPropLog} = case resultPropLog of
Just (_, key) -> release key
Nothing -> return ()
data Timeout = Timeout deriving (Show)
instance Pretty Timeout where
pretty Timeout = "Job killed by timeout"
instance Exception Timeout where
toException = toRuntimeError
fromException = fromRuntimeError
displayException = show . pretty
nonBlockingLogHandle :: (MonadIO m, MonadLogger m) => Handle -> m ()
nonBlockingLogHandle hnd = do
initial <- liftIO $ BS.hGetNonBlocking hnd 4096
unless (BS.null initial) $ do
fullOutput <- liftIO $ go (BS.byteString initial)
Log.logWithoutLoc "Process#Error" Log.LevelDebug fullOutput
where
go :: BS.Builder -> IO LBS.ByteString
go start = do
rest <- BS.hGetNonBlocking hnd 4096
if BS.null rest
then return $ BS.toLazyByteString start
else go (start <> BS.byteString rest)
data Process =
Process
{ inHandle :: Handle
, outHandle :: Handle
, errHandle :: Handle
, procHandle :: ProcessHandle
, procId :: Pid
, procToException :: ExitCode -> UnexpectedTermination
}
getJobTimeOut :: MonadIO m => m [String]
getJobTimeOut = liftIO $ do
localTime <- Time.zonedTimeToLocalTime <$> Time.getZonedTime
let dayHour = Time.todHour $ Time.localTimeOfDay localTime
return $ case dayOfWeek (Time.localDay localTime) of
Sunday -> timeoutFlag 8
Saturday -> timeoutFlag 8
_ | dayHour > 20 -> timeoutFlag 8
| dayHour < 8 -> timeoutFlag $ 8 - (dayHour + 1)
| otherwise -> []
where
timeoutFlag :: Int -> [String]
timeoutFlag h | h > 0 = ["-t", show h ++ ":00:00"]
| otherwise = []
type LogFun = Loc -> LogSource -> LogLevel -> LogStr -> IO ()
withProcessPool
:: (MonadLoggerIO m, MonadResource m, MonadQuery m)
=> Int -> Platform -> (Pool Process -> m a) -> m a
withProcessPool n Platform{platformName,platformFlags} f = do
hostName <- liftIO getHostName
logFun <- Log.askLoggerIO
makeRunnerProc <- runnerCreator
(releaseKey, pool) <- allocate
(createProcessPool logFun hostName makeRunnerProc)
destroyProcessPool
f pool <* release releaseKey
where
createProcessPool
:: LogFun
-> String
-> ([String] -> IO CreateProcess)
-> IO (Pool Process)
createProcessPool logFun hostName makeRunnerProc = Pool.createPool
(unLog $ allocateProcess makeRunnerProc)
(unLog . destroyProcess hostName)
1
3153600000
n
where
unLog act = Log.runLoggingT act logFun
destroyProcessPool :: Pool Process -> IO ()
destroyProcessPool = liftIO . Pool.destroyAllResources
customRunner :: Text -> [String] -> IO CreateProcess
customRunner txtCmd args = return . Proc.proc cmd $ runnerArgs ++ args
where
cmd = T.unpack txtCmd
runnerArgs = flags ++ ["--"]
flags = map T.unpack $ case platformFlags of
Nothing -> [platformName]
Just t -> T.splitOn " " t
defaultRunner :: [String] -> IO CreateProcess
defaultRunner args = do
timeout <- getJobTimeOut
return . Proc.proc "srun" $ timeout ++ runnerArgs ++ args
where
runnerArgs = ["-Q", "--gres=gpu:1"] ++ flags ++ ["--"]
flags = map T.unpack $ case platformFlags of
Nothing -> ["-C", platformName]
Just t -> T.splitOn " " t
runnerCreator :: MonadQuery m => m ([String] -> IO CreateProcess)
runnerCreator = do
result <- getGlobalVar RunCommand
case result of
Just cmd -> return $ customRunner cmd
Nothing -> return $ defaultRunner
allocateProcess :: ([String] -> IO CreateProcess) -> LoggingT IO Process
allocateProcess createRunnerProc = do
exePath <- getKernelExecutable
libPath <- getKernelLibPath
proc@Process{procId,errHandle} <- liftIO $ do
runnerProc <- createRunnerProc [exePath, "-L", libPath, "-W", "-S"]
let p = runnerProc
{ std_in = CreatePipe
, std_out = CreatePipe
, std_err = CreatePipe
}
procToException = unexpectedTermination p
(Just inHandle, Just outHandle, Just errHandle, procHandle) <-
Proc.createProcess p
System.hSetBuffering inHandle LineBuffering
System.hSetBuffering outHandle LineBuffering
System.hSetBuffering errHandle LineBuffering
Just procId <- Proc.getPid procHandle
return Process{..}
nonBlockingLogHandle errHandle
proc <$ logDebugNS "Process#Start" (showText procId)
destroyProcess :: String -> Process -> LoggingT IO ()
destroyProcess hostName Process{..} = do
uninterruptibleMask_ $ do
err <- liftIO $ do
Proc.getPid procHandle >>= mapM_ (signalProcess sigKILL)
System.hClose inHandle
System.hClose outHandle
Proc.waitForProcess procHandle
T.hGetContents errHandle <* System.hClose errHandle
logDebugNS "Process#ExitError" err
tryRemoveFile $ "kernel-runner.0" <.> show procId <.> hostName
tryRemoveFile $ ".PRUN_ENVIRONMENT" <.> show procId <.> hostName
logDebugNS "Process#End" $ showText procId
tryRemoveFile :: MonadIO m => FilePath -> m ()
tryRemoveFile path = liftIO $
void (try $ removeFile path :: IO (Either SomeException ()))
checkProcess :: (MonadIO m, MonadLogger m, MonadThrow m) => Process -> m ()
checkProcess Process{..} = do
result <- liftIO $ Proc.getProcessExitCode procHandle
case result of
Just (ExitFailure 2) -> logThrowM Timeout
Just code -> logThrowM $ procToException code
Nothing -> return ()
liftIO $ do
System.hIsReadable outHandle >>= guard
System.hIsWritable inHandle >>= guard
withResource :: MonadUnliftIO m => Pool a -> (a -> m b) -> m b
withResource pool f = withAcquire (mkAcquireType alloc clean) $ f . fst
where
alloc = Pool.takeResource pool
clean (res, localPool) ty = case ty of
ReleaseException -> Pool.destroyResource pool localPool res
_ -> Pool.putResource localPool res
processJobsParallel
:: ( MonadLoggerIO m
, MonadQuery m
, MonadMask m
, MonadUnliftIO m
)
=> Int -> Platform -> ConduitT (Job a) (Result a) m ()
processJobsParallel numNodes platform = withProcessPool numNodes platform $
processJobsParallelWithSharedPool numNodes
processJobsParallelWithSharedPool
:: ( MonadLoggerIO m
, MonadQuery m
, MonadMask m
, MonadUnliftIO m
)
=> Int -> Pool Process -> ConduitT (Job a) (Result a) m ()
processJobsParallelWithSharedPool numNodes procPool =
parMapM taskHandler numNodes $ \Job{..} -> do
let fileStem = T.unpack jobLabel
outputFile = fileStem <.> "output"
timingFile = fileStem <.> "timings"
logFile = fileStem <.> "log"
handleErrors act = act `onError` do
logErrorN ("Failed: " <> jobCommand)
tryRemoveFile $ outputFile
tryRemoveFile $ timingFile
tryRemoveFile $ logFile
withResource procPool $ \proc@Process{inHandle,outHandle,errHandle} -> do
checkProcess proc
handleErrors $ do
logDebugNS "Process#Job#Start" jobCommand
result <- liftIO $ do
T.hPutStrLn inHandle jobCommand
T.hGetLine outHandle
let (label, commit) = case T.splitOn ":" result of
(version:rest) -> (T.concat rest, version)
[] -> ("", "")
logDebugNS "Process#Job#End" jobCommand
outputKey <- registerFile outputFile
timingKey <- registerFile timingFile
logKey <- if jobLogProperties
then Just <$> registerFile logFile
else return Nothing
nonBlockingLogHandle errHandle
return $ Result
{ resultValue = jobValue
, resultVariant = jobVariant
, resultLabel = label
, resultAlgorithmVersion = CommitId commit
, resultOutput = outputKey
, resultTimings = timingKey
, resultPropLog = logKey
}
where
checkNotExist :: SomeException -> Bool
checkNotExist e = fromMaybe False $ isDoesNotExistError <$> fromException e
registerFile :: MonadResource m => FilePath -> m (FilePath, ReleaseKey)
registerFile path = fmap (path,) . register $ removeFile path
tryRemoveFile path = do
result <- try . liftIO $ removeFile path
case result of
Left exc
| checkNotExist exc -> return ()
| otherwise -> logErrorN . T.pack $ displayException exc
Right () -> return ()
taskHandler :: MonadSql m => Handler m (Job a)
taskHandler = Handle handler
where
handler :: MonadSql m => Job a -> SomeException -> m Action
handler Job{jobVariant} exc
| Just Timeout <- fromException exc = return Retry
| otherwise = do
retries <- variantRetryCount <$> Sql.getJust jobVariant
if retries >= 5
then return Drop
else Retry <$ Sql.update jobVariant [ VariantRetryCount +=. 1 ]
| merijn/GPU-benchmarks | benchmark-analysis/ingest-src/ProcessPool.hs | gpl-3.0 | 13,530 | 0 | 24 | 3,756 | 3,851 | 1,990 | 1,861 | 321 | 4 |
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE TypeFamilies #-}
module Mescaline.Pattern (
-- *Patterns
Pattern
, module Mescaline.Pattern.Ppar
, ptrace
-- *Base module
, module Sound.SC3.Lang.Pattern.P
-- Re-exports from base
, (<>)
-- *Events
, module Mescaline.Pattern.Event
) where
import Data.Monoid ((<>))
import GHC.Exts (IsList(..))
import Mescaline.Pattern.Event
import Mescaline.Pattern.Ppar
import Sound.SC3.Lang.Pattern.P
import Data.String (IsString(..))
import qualified Debug.Trace as Debug
ptrace :: Show a => String -> P a -> P a
ptrace tag = fmap (\a -> Debug.trace (tag ++ show a) a)
type Pattern a = P a
instance IsString (Pattern Event) where
fromString = return . sound
instance IsList (Pattern Event) where
type Item (Pattern Event) = Pattern Event
fromList = pconcat
toList = (:[])
| kaoskorobase/mescaline | lib/mescaline-patterns/src/Mescaline/Pattern.hs | gpl-3.0 | 1,018 | 0 | 11 | 231 | 262 | 159 | 103 | 28 | 1 |
{-# LANGUAGE NoImplicitPrelude, DeriveGeneric, DeriveFunctor, DeriveFoldable, DeriveTraversable, GeneralizedNewtypeDeriving, RecordWildCards #-}
module Lamdu.Expr.Val
( Leaf(..)
, Literal(..), litType, litData
, Body(..)
, Apply(..), applyFunc, applyArg
, GetField(..), getFieldRecord, getFieldTag
, Inject(..), injectVal, injectTag
, Case(..), caseTag, caseMatch, caseMismatch
, Lam(..), lamParamId, lamResult
, RecExtend(..), recTag, recFieldVal, recRest
, Nom(..), nomId, nomVal
, Val(..), body, payload, alphaEq
, Var(..)
, GlobalId(..)
, pPrintUnannotated
) where
import Prelude.Compat hiding (any)
import Control.DeepSeq (NFData(..))
import Control.DeepSeq.Generics (genericRnf)
import Control.Lens (Lens, Lens')
import Control.Lens.Operators
import Data.Binary (Binary)
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as BS8
import qualified Data.Foldable as Foldable
import Data.Hashable (Hashable(..))
import Data.Hashable.Generic (gHashWithSalt)
import qualified Data.Map as Map
import Data.Maybe (fromMaybe)
import Data.String (IsString(..))
import GHC.Generics (Generic)
import Lamdu.Expr.Identifier (Identifier)
import qualified Lamdu.Expr.Type as T
import Text.PrettyPrint ((<+>), (<>))
import qualified Text.PrettyPrint as PP
import Text.PrettyPrint.HughesPJClass.Compat (Pretty(..), PrettyLevel, maybeParens)
{-# ANN module "HLint: ignore Use const" #-}
newtype Var = Var { vvName :: Identifier }
deriving (Eq, Ord, Show, NFData, IsString, Pretty, Binary, Hashable)
newtype GlobalId = GlobalId { globalId :: Identifier }
deriving (Eq, Ord, Show, NFData, IsString, Pretty, Binary, Hashable)
data Literal = Literal
{ _litType :: {-# UNPACK #-} !T.PrimId
, _litData :: {-# UNPACK #-} !ByteString
} deriving (Generic, Show, Eq, Ord)
instance NFData Literal where rnf = genericRnf
instance Binary Literal
instance Hashable Literal where hashWithSalt = gHashWithSalt
litType :: Lens' Literal T.PrimId
litType f Literal{..} = f _litType <&> \_litType -> Literal{..}
litData :: Lens' Literal ByteString
litData f Literal{..} = f _litData <&> \_litData -> Literal{..}
data Leaf
= LVar {-# UNPACK #-}!Var
| LGlobal {-# UNPACK #-}!GlobalId
| LHole
| LLiteral {-# UNPACK #-} !Literal
| LRecEmpty
| LAbsurd
deriving (Generic, Show, Eq)
instance NFData Leaf where rnf = genericRnf
instance Binary Leaf
instance Hashable Leaf where hashWithSalt = gHashWithSalt
class Match f where
match :: (a -> b -> c) -> f a -> f b -> Maybe (f c)
data Apply exp = Apply
{ _applyFunc :: exp
, _applyArg :: exp
} deriving (Functor, Foldable, Traversable, Generic, Show, Eq)
instance NFData exp => NFData (Apply exp) where rnf = genericRnf
instance Binary exp => Binary (Apply exp)
instance Hashable exp => Hashable (Apply exp) where hashWithSalt = gHashWithSalt
instance Match Apply where
match f (Apply f0 a0) (Apply f1 a1) = Just $ Apply (f f0 f1) (f a0 a1)
applyFunc :: Lens' (Apply exp) exp
applyFunc f (Apply func arg) = (`Apply` arg) <$> f func
applyArg :: Lens' (Apply exp) exp
applyArg f (Apply func arg) = Apply func <$> f arg
data GetField exp = GetField
{ _getFieldRecord :: exp
, _getFieldTag :: T.Tag
} deriving (Functor, Foldable, Traversable, Generic, Show, Eq)
instance NFData exp => NFData (GetField exp) where rnf = genericRnf
instance Binary exp => Binary (GetField exp)
instance Hashable exp => Hashable (GetField exp) where hashWithSalt = gHashWithSalt
instance Match GetField where
match f (GetField r0 t0) (GetField r1 t1)
| t0 == t1 = Just $ GetField (f r0 r1) t0
| otherwise = Nothing
getFieldRecord :: Lens (GetField a) (GetField b) a b
getFieldRecord f GetField {..} = f _getFieldRecord <&> \_getFieldRecord -> GetField {..}
getFieldTag :: Lens' (GetField exp) T.Tag
getFieldTag f GetField {..} = f _getFieldTag <&> \_getFieldTag -> GetField {..}
data Inject exp = Inject
{ _injectTag :: T.Tag
, _injectVal :: exp
} deriving (Functor, Foldable, Traversable, Generic, Show, Eq)
instance NFData exp => NFData (Inject exp) where rnf = genericRnf
instance Binary exp => Binary (Inject exp)
instance Hashable exp => Hashable (Inject exp) where hashWithSalt = gHashWithSalt
instance Match Inject where
match f (Inject t0 r0) (Inject t1 r1)
| t0 == t1 = Just $ Inject t0 (f r0 r1)
| otherwise = Nothing
injectVal :: Lens (Inject a) (Inject b) a b
injectVal f Inject {..} = f _injectVal <&> \_injectVal -> Inject {..}
injectTag :: Lens' (Inject exp) T.Tag
injectTag f Inject {..} = f _injectTag <&> \_injectTag -> Inject {..}
data Case exp = Case
{ _caseTag :: T.Tag
, _caseMatch :: exp
, _caseMismatch :: exp
} deriving (Functor, Foldable, Traversable, Generic, Show, Eq)
instance NFData exp => NFData (Case exp) where rnf = genericRnf
instance Binary exp => Binary (Case exp)
instance Hashable exp => Hashable (Case exp) where hashWithSalt = gHashWithSalt
instance Match Case where
match f (Case t0 h0 hr0) (Case t1 h1 hr1)
| t0 == t1 = Just $ Case t0 (f h0 h1) (f hr0 hr1)
| otherwise = Nothing
caseTag :: Lens' (Case exp) T.Tag
caseTag f Case {..} = f _caseTag <&> \_caseTag -> Case {..}
caseMatch :: Lens' (Case exp) exp
caseMatch f Case {..} = f _caseMatch <&> \_caseMatch -> Case {..}
caseMismatch :: Lens' (Case exp) exp
caseMismatch f Case {..} = f _caseMismatch <&> \_caseMismatch -> Case {..}
data Lam exp = Lam
{ _lamParamId :: Var
, _lamResult :: exp
} deriving (Functor, Foldable, Traversable, Generic, Show, Eq)
instance NFData exp => NFData (Lam exp) where rnf = genericRnf
instance Hashable exp => Hashable (Lam exp) where hashWithSalt = gHashWithSalt
instance Binary exp => Binary (Lam exp)
lamParamId :: Lens' (Lam exp) Var
lamParamId f Lam {..} = f _lamParamId <&> \_lamParamId -> Lam {..}
lamResult :: Lens (Lam a) (Lam b) a b
lamResult f Lam {..} = f _lamResult <&> \_lamResult -> Lam {..}
data RecExtend exp = RecExtend
{ _recTag :: T.Tag
, _recFieldVal :: exp
, _recRest :: exp
} deriving (Functor, Foldable, Traversable, Generic, Show, Eq)
instance NFData exp => NFData (RecExtend exp) where rnf = genericRnf
instance Binary exp => Binary (RecExtend exp)
instance Hashable exp => Hashable (RecExtend exp) where hashWithSalt = gHashWithSalt
instance Match RecExtend where
match f (RecExtend t0 f0 r0) (RecExtend t1 f1 r1)
| t0 == t1 = Just $ RecExtend t0 (f f0 f1) (f r0 r1)
| otherwise = Nothing
recTag :: Lens' (RecExtend exp) T.Tag
recTag f RecExtend {..} = f _recTag <&> \_recTag -> RecExtend {..}
recFieldVal :: Lens' (RecExtend exp) exp
recFieldVal f RecExtend {..} = f _recFieldVal <&> \_recFieldVal -> RecExtend {..}
recRest :: Lens' (RecExtend exp) exp
recRest f RecExtend {..} = f _recRest <&> \_recRest -> RecExtend {..}
data Nom exp = Nom
{ _nomId :: T.NominalId
, _nomVal :: exp
} deriving (Functor, Foldable, Traversable, Generic, Show, Eq)
instance NFData exp => NFData (Nom exp) where rnf = genericRnf
instance Hashable exp => Hashable (Nom exp) where hashWithSalt = gHashWithSalt
instance Binary exp => Binary (Nom exp)
instance Match Nom where
match f (Nom i0 v0) (Nom i1 v1)
| i0 == i1 = Just $ Nom i0 (f v0 v1)
| otherwise = Nothing
nomId :: Lens' (Nom exp) T.NominalId
nomId f Nom {..} = f _nomId <&> \_nomId -> Nom {..}
nomVal :: Lens (Nom a) (Nom b) a b
nomVal f Nom {..} = f _nomVal <&> \_nomVal -> Nom {..}
data Body exp
= BApp {-# UNPACK #-}!(Apply exp)
| BAbs {-# UNPACK #-}!(Lam exp)
| BGetField {-# UNPACK #-}!(GetField exp)
| BRecExtend {-# UNPACK #-}!(RecExtend exp)
| BInject {-# UNPACK #-}!(Inject exp)
| BCase {-# UNPACK #-}!(Case exp)
| -- Convert to Nominal type
BToNom {-# UNPACK #-}!(Nom exp)
| -- Convert from Nominal type
BFromNom {-# UNPACK #-}!(Nom exp)
| BLeaf Leaf
deriving (Functor, Foldable, Traversable, Generic, Show, Eq)
-- NOTE: Careful of Eq, it's not alpha-eq!
instance NFData exp => NFData (Body exp) where rnf = genericRnf
instance Hashable exp => Hashable (Body exp) where hashWithSalt = gHashWithSalt
instance Binary exp => Binary (Body exp)
data Val a = Val
{ _valPayload :: a
, _valBody :: !(Body (Val a))
} deriving (Functor, Foldable, Traversable, Generic, Show, Eq)
instance NFData a => NFData (Val a) where rnf = genericRnf
instance Hashable a => Hashable (Val a) where hashWithSalt = gHashWithSalt
instance Binary a => Binary (Val a)
body :: Lens' (Val a) (Body (Val a))
body f (Val pl b) = Val pl <$> f b
payload :: Lens' (Val a) a
payload f (Val pl b) = (`Val` b) <$> f pl
pPrintPrecBody :: Pretty pl => PrettyLevel -> Rational -> Body (Val pl) -> PP.Doc
pPrintPrecBody lvl prec b =
case b of
BLeaf (LVar var) -> pPrint var
BLeaf (LGlobal tag) -> pPrint tag
BLeaf (LLiteral (Literal _p d)) -> PP.text (BS8.unpack d)
BLeaf LHole -> PP.text "?"
BLeaf LAbsurd -> PP.text "absurd"
BApp (Apply e1 e2) -> maybeParens (10 < prec) $
pPrintPrec lvl 10 e1 <+> pPrintPrec lvl 11 e2
BAbs (Lam n e) -> maybeParens (0 < prec) $
PP.char '\\' <> pPrint n <+>
PP.text "->" <+>
pPrint e
BGetField (GetField e n) -> maybeParens (12 < prec) $
pPrintPrec lvl 12 e <> PP.char '.' <> pPrint n
BInject (Inject n e) -> maybeParens (12 < prec) $
pPrint n <> PP.char '{' <> pPrintPrec lvl 12 e <> PP.char '}'
BCase (Case n m mm) -> maybeParens (0 < prec) $
PP.vcat
[ PP.text "case of"
, pPrint n <> PP.text " -> " <> pPrint m
, PP.text "_" <> PP.text " -> " <> pPrint mm
]
BToNom (Nom ident val) -> PP.text "[ ->" <+> pPrint ident <+> pPrint val <+> PP.text "]"
BFromNom (Nom ident val) -> PP.text "[" <+> pPrint ident <+> pPrint val <+> PP.text "-> ]"
BLeaf LRecEmpty -> PP.text "{}"
BRecExtend (RecExtend tag val rest) ->
PP.text "{" <+>
prField <>
PP.comma <+>
pPrint rest <+>
PP.text "}"
where
prField = pPrint tag <+> PP.text "=" <+> pPrint val
instance Pretty a => Pretty (Val a) where
pPrintPrec lvl prec (Val pl b)
| PP.isEmpty plDoc = pPrintPrecBody lvl prec b
| otherwise =
maybeParens (13 < prec) $ mconcat
[ pPrintPrecBody lvl 14 b, PP.text "{", plDoc, PP.text "}" ]
where
plDoc = pPrintPrec lvl 0 pl
data EmptyDoc = EmptyDoc
instance Pretty EmptyDoc where
pPrint _ = PP.empty
pPrintUnannotated :: Val a -> PP.Doc
pPrintUnannotated = pPrint . (EmptyDoc <$)
alphaEq :: Val () -> Val () -> Bool
alphaEq =
go Map.empty
where
xToYConv xToY x =
fromMaybe x $ Map.lookup x xToY
go xToY (Val _ xBody) (Val _ yBody) =
case (xBody, yBody) of
(BAbs (Lam xvar xresult),
BAbs (Lam yvar yresult)) ->
go (Map.insert xvar yvar xToY) xresult yresult
(BLeaf (LVar x), BLeaf (LVar y)) ->
-- TODO: This is probably not 100% correct for various
-- shadowing corner cases
xToYConv xToY x == y
(BLeaf x, BLeaf y) -> x == y
(BApp x, BApp y) -> goRecurse x y
(BGetField x, BGetField y) -> goRecurse x y
(BRecExtend x, BRecExtend y) -> goRecurse x y
(BCase x, BCase y) -> goRecurse x y
(BInject x, BInject y) -> goRecurse x y
(BFromNom x, BFromNom y) -> goRecurse x y
(BToNom x, BToNom y) -> goRecurse x y
(_, _) -> False
where
goRecurse x y = maybe False Foldable.and $ match (go xToY) x y
| da-x/Algorithm-W-Step-By-Step | Lamdu/Expr/Val.hs | gpl-3.0 | 12,399 | 0 | 14 | 3,447 | 4,639 | 2,397 | 2,242 | 264 | 14 |
{- Test for Program -}
module TestProgram where
import Program
p, p1 :: Program.T
p = fromString ("\
\read k;\
\read n;\
\m := 1;\
\while n-m do\
\ begin\
\ if m - m/k*k then\
\ skip;\
\ else\
\ write m;\
\ m := m + 1;\
\ end")
p1 = fromString ("\
\read n;\
\read b;\
\m := 1;\
\s := 0;\
\p := 1;\
\while n do\
\ begin\
\ q := n/b;\
\ r := n - q*b;\
\ write r;\
\ s := p*r+s;\
\ p := p*10;\
\ n :=q;\
\ end\
\write s;")
p2 = fromString ("\
\read n;\
\s := 0;\
\repeat\
\ begin\
\ s := s+n;\
\ n := n-1;\
\ end\
\until 1-n;\
\write s;")
sp = putStr (toString p)
rp = Program.exec p [3,16]
rp1 = Program.exec p1 [1024, 2]
rp2 = Program.exec p2 [1]
| nevvi/Declarative-D7012E | lab2/TestProgram.hs | gpl-3.0 | 720 | 19 | 8 | 222 | 144 | 85 | 59 | 10 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.AppEngine.Apps.Services.Versions.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)
--
-- Lists the versions of a service.
--
-- /See:/ <https://cloud.google.com/appengine/docs/admin-api/ Google App Engine Admin API Reference> for @appengine.apps.services.versions.list@.
module Network.Google.Resource.AppEngine.Apps.Services.Versions.List
(
-- * REST Resource
AppsServicesVersionsListResource
-- * Creating a Request
, appsServicesVersionsList
, AppsServicesVersionsList
-- * Request Lenses
, asvlXgafv
, asvlUploadProtocol
, asvlPp
, asvlAccessToken
, asvlUploadType
, asvlBearerToken
, asvlAppsId
, asvlView
, asvlPageToken
, asvlServicesId
, asvlPageSize
, asvlCallback
) where
import Network.Google.AppEngine.Types
import Network.Google.Prelude
-- | A resource alias for @appengine.apps.services.versions.list@ method which the
-- 'AppsServicesVersionsList' request conforms to.
type AppsServicesVersionsListResource =
"v1" :>
"apps" :>
Capture "appsId" Text :>
"services" :>
Capture "servicesId" Text :>
"versions" :>
QueryParam "$.xgafv" Text :>
QueryParam "upload_protocol" Text :>
QueryParam "pp" Bool :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "bearer_token" Text :>
QueryParam "view" Text :>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListVersionsResponse
-- | Lists the versions of a service.
--
-- /See:/ 'appsServicesVersionsList' smart constructor.
data AppsServicesVersionsList = AppsServicesVersionsList'
{ _asvlXgafv :: !(Maybe Text)
, _asvlUploadProtocol :: !(Maybe Text)
, _asvlPp :: !Bool
, _asvlAccessToken :: !(Maybe Text)
, _asvlUploadType :: !(Maybe Text)
, _asvlBearerToken :: !(Maybe Text)
, _asvlAppsId :: !Text
, _asvlView :: !(Maybe Text)
, _asvlPageToken :: !(Maybe Text)
, _asvlServicesId :: !Text
, _asvlPageSize :: !(Maybe (Textual Int32))
, _asvlCallback :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'AppsServicesVersionsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'asvlXgafv'
--
-- * 'asvlUploadProtocol'
--
-- * 'asvlPp'
--
-- * 'asvlAccessToken'
--
-- * 'asvlUploadType'
--
-- * 'asvlBearerToken'
--
-- * 'asvlAppsId'
--
-- * 'asvlView'
--
-- * 'asvlPageToken'
--
-- * 'asvlServicesId'
--
-- * 'asvlPageSize'
--
-- * 'asvlCallback'
appsServicesVersionsList
:: Text -- ^ 'asvlAppsId'
-> Text -- ^ 'asvlServicesId'
-> AppsServicesVersionsList
appsServicesVersionsList pAsvlAppsId_ pAsvlServicesId_ =
AppsServicesVersionsList'
{ _asvlXgafv = Nothing
, _asvlUploadProtocol = Nothing
, _asvlPp = True
, _asvlAccessToken = Nothing
, _asvlUploadType = Nothing
, _asvlBearerToken = Nothing
, _asvlAppsId = pAsvlAppsId_
, _asvlView = Nothing
, _asvlPageToken = Nothing
, _asvlServicesId = pAsvlServicesId_
, _asvlPageSize = Nothing
, _asvlCallback = Nothing
}
-- | V1 error format.
asvlXgafv :: Lens' AppsServicesVersionsList (Maybe Text)
asvlXgafv
= lens _asvlXgafv (\ s a -> s{_asvlXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
asvlUploadProtocol :: Lens' AppsServicesVersionsList (Maybe Text)
asvlUploadProtocol
= lens _asvlUploadProtocol
(\ s a -> s{_asvlUploadProtocol = a})
-- | Pretty-print response.
asvlPp :: Lens' AppsServicesVersionsList Bool
asvlPp = lens _asvlPp (\ s a -> s{_asvlPp = a})
-- | OAuth access token.
asvlAccessToken :: Lens' AppsServicesVersionsList (Maybe Text)
asvlAccessToken
= lens _asvlAccessToken
(\ s a -> s{_asvlAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
asvlUploadType :: Lens' AppsServicesVersionsList (Maybe Text)
asvlUploadType
= lens _asvlUploadType
(\ s a -> s{_asvlUploadType = a})
-- | OAuth bearer token.
asvlBearerToken :: Lens' AppsServicesVersionsList (Maybe Text)
asvlBearerToken
= lens _asvlBearerToken
(\ s a -> s{_asvlBearerToken = a})
-- | Part of \`parent\`. Name of the parent Service resource. Example:
-- apps\/myapp\/services\/default.
asvlAppsId :: Lens' AppsServicesVersionsList Text
asvlAppsId
= lens _asvlAppsId (\ s a -> s{_asvlAppsId = a})
-- | Controls the set of fields returned in the List response.
asvlView :: Lens' AppsServicesVersionsList (Maybe Text)
asvlView = lens _asvlView (\ s a -> s{_asvlView = a})
-- | Continuation token for fetching the next page of results.
asvlPageToken :: Lens' AppsServicesVersionsList (Maybe Text)
asvlPageToken
= lens _asvlPageToken
(\ s a -> s{_asvlPageToken = a})
-- | Part of \`parent\`. See documentation of \`appsId\`.
asvlServicesId :: Lens' AppsServicesVersionsList Text
asvlServicesId
= lens _asvlServicesId
(\ s a -> s{_asvlServicesId = a})
-- | Maximum results to return per page.
asvlPageSize :: Lens' AppsServicesVersionsList (Maybe Int32)
asvlPageSize
= lens _asvlPageSize (\ s a -> s{_asvlPageSize = a})
. mapping _Coerce
-- | JSONP
asvlCallback :: Lens' AppsServicesVersionsList (Maybe Text)
asvlCallback
= lens _asvlCallback (\ s a -> s{_asvlCallback = a})
instance GoogleRequest AppsServicesVersionsList where
type Rs AppsServicesVersionsList =
ListVersionsResponse
type Scopes AppsServicesVersionsList =
'["https://www.googleapis.com/auth/appengine.admin",
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only"]
requestClient AppsServicesVersionsList'{..}
= go _asvlAppsId _asvlServicesId _asvlXgafv
_asvlUploadProtocol
(Just _asvlPp)
_asvlAccessToken
_asvlUploadType
_asvlBearerToken
_asvlView
_asvlPageToken
_asvlPageSize
_asvlCallback
(Just AltJSON)
appEngineService
where go
= buildClient
(Proxy :: Proxy AppsServicesVersionsListResource)
mempty
| rueshyna/gogol | gogol-appengine/gen/Network/Google/Resource/AppEngine/Apps/Services/Versions/List.hs | mpl-2.0 | 7,481 | 0 | 24 | 1,946 | 1,203 | 692 | 511 | 171 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.YouTubeReporting.Types
-- 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)
--
module Network.Google.YouTubeReporting.Types
(
-- * Service Configuration
youTubeReportingService
-- * OAuth Scopes
, youTubeAnalyticsReadOnlyScope
, youTubeAnalyticsMonetaryReadOnlyScope
-- * ListReportsResponse
, ListReportsResponse
, listReportsResponse
, lrrNextPageToken
, lrrReports
-- * Empty
, Empty
, empty
-- * Report
, Report
, report
, rJobId
, rStartTime
, rDownloadURL
, rEndTime
, rId
, rCreateTime
, rJobExpireTime
-- * ListReportTypesResponse
, ListReportTypesResponse
, listReportTypesResponse
, lrtrNextPageToken
, lrtrReportTypes
-- * Media
, Media
, media
, mResourceName
-- * Job
, Job
, job
, jName
, jId
, jSystemManaged
, jReportTypeId
, jExpireTime
, jCreateTime
-- * Xgafv
, Xgafv (..)
-- * ListJobsResponse
, ListJobsResponse
, listJobsResponse
, ljrNextPageToken
, ljrJobs
-- * ReportType
, ReportType
, reportType
, rtName
, rtId
, rtDeprecateTime
, rtSystemManaged
) where
import Network.Google.Prelude
import Network.Google.YouTubeReporting.Types.Product
import Network.Google.YouTubeReporting.Types.Sum
-- | Default request referring to version 'v1' of the YouTube Reporting API. This contains the host and root path used as a starting point for constructing service requests.
youTubeReportingService :: ServiceConfig
youTubeReportingService
= defaultService (ServiceId "youtubereporting:v1")
"youtubereporting.googleapis.com"
-- | View YouTube Analytics reports for your YouTube content
youTubeAnalyticsReadOnlyScope :: Proxy '["https://www.googleapis.com/auth/yt-analytics.readonly"]
youTubeAnalyticsReadOnlyScope = Proxy;
-- | View monetary and non-monetary YouTube Analytics reports for your
-- YouTube content
youTubeAnalyticsMonetaryReadOnlyScope :: Proxy '["https://www.googleapis.com/auth/yt-analytics-monetary.readonly"]
youTubeAnalyticsMonetaryReadOnlyScope = Proxy;
| rueshyna/gogol | gogol-youtube-reporting/gen/Network/Google/YouTubeReporting/Types.hs | mpl-2.0 | 2,608 | 0 | 7 | 586 | 256 | 176 | 80 | 63 | 1 |
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DataKinds #-}
module Main
( main
) where
import GHC.Generics ( Generic, Generic1 )
import qualified Data.Foldable as F
import Control.Monad ( void )
import Graphics.Rendering.Chart hiding ( x0 )
import Graphics.Rendering.Chart.Backend.Cairo
import Data.Default.Class
import Data.Colour
import Data.Colour.Names
import Control.Lens
import Linear ( Additive(..) )
import Casadi.MX ( MX )
import Dyno.Nlp
import Dyno.NlpUtils
import Dyno.Solvers
import Dyno.Vectorize
import Dyno.View.View
import Dyno.View.JVec
import Dyno.MultipleShooting
-- state/control/parameter definitions
data X a = X a a deriving (Functor, Generic, Generic1, Show)
data U a = U a deriving (Functor, Generic, Generic1, Show)
data P a = P deriving (Functor, Generic, Generic1, Show)
-- boilerplate
instance Vectorize X
instance Vectorize U
instance Vectorize P
instance Applicative X where {pure = vpure; (<*>) = vapply}
instance Applicative U where {pure = vpure; (<*>) = vapply}
instance Applicative P where {pure = vpure; (<*>) = vapply}
instance Additive X where
zero = pure 0
-- ocp specification
ocp :: MsOcp X U P
ocp =
MsOcp
{ msOde = ode
, msEndTime = 10
, msXBnds = X (Just (-2), Just 2) (Just (-2), Just 2)
, msUBnds = U (Just (-3), Just 3)
, msPBnds = P
, msMayer = \_ -> 0
, msLagrangeSum = \(X p v) (U u) -> p*p + v*v + u*u
, msX0 = X (Just 0) (Just 0)
, msXF = X (Just 1) (Just 1)
, msNumRk4Steps = Just 10
}
-- dynamics
ode :: Floating a => X a -> U a -> P a -> a -> X a
ode (X x v) (U u) _p _t = X v (-x -0.1*v + u)
-- run the thing
main :: IO ()
main = do
myNlp <- makeMsNlp ocp :: IO (Nlp (MsDvs X U P 40) (JV None) (MsConstraints X 40) MX)
(_, eopt) <- solveNlp "multiple_shooting" ipoptSolver myNlp Nothing
opt <- case eopt of
Left err -> error $ "nlp solver returned status " ++ show err
Right r -> return r
let xopt = split $ xOpt opt
splitXU xu = (splitJV x, splitJV u)
where
JTuple x u = split xu
(xs', us) = unzip $ map splitXU $ F.toList $ unJVec $ split (dvXus xopt)
xf = splitJV (dvXf xopt)
xs = xs' ++ [xf]
renderable :: Renderable ()
renderable = charts [ ("u", zip [0..] (map (\(U u) -> u) us))
, ("p", zip [0..] (map (\(X p _) -> p) xs))
, ("v", zip [0..] (map (\(X _ v) -> v) xs))
]
fileOptions :: FileOptions
fileOptions =
fo_format .~ SVG
$ fo_size .~ (600, 600)
$ def
path = "./multiple_shooting.svg"
putStrLn $ "writing solution plot to " ++ show path
void $ renderableToFile fileOptions path renderable
charts :: [(String,[(Double,Double)])] -> Renderable ()
charts vals = toRenderable slayouts
where
plots :: (String, [(Double, Double)]) -> StackedLayout Double
plots (name, xys) = StackedLayout layout
where
lines' :: PlotLines Double Double
lines' = plot_lines_values .~ [xys]
$ plot_lines_title .~ name
$ def
points :: PlotPoints Double Double
points = plot_points_style .~ filledCircles 2 (opaque red)
$ plot_points_values .~ [(x,y) | (x,y) <- xys]
$ plot_points_title .~ name
$ def
layout :: Layout Double Double
layout = layout_title .~ name
$ layout_plots .~ [toPlot lines', toPlot points]
$ def
slayouts :: StackedLayouts Double
slayouts = slayouts_compress_legend .~ False
$ slayouts_layouts .~ (map plots vals)
$ def
| ghorn/dynobud | dynobud/examples/MultipleShooting.hs | lgpl-3.0 | 3,763 | 0 | 19 | 1,061 | 1,391 | 757 | 634 | 97 | 2 |
module Problems011to020 where
import Data.Char
import Data.Function
import Data.List
import Data.Time
import Data.Time.Calendar.WeekDate
import Util
-- In the 20x20 grid below, four numbers along a diagonal line have been marked in red.
--
-- 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
-- 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
-- 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
-- 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
-- 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
-- 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
-- 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
-- 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
-- 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
-- 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
-- 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
-- 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
-- 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
-- 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
-- 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
-- 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
-- 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
-- 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
-- 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
-- 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
--
-- The product of these numbers is 26 � 63 � 78 � 14 = 1788696.
-- What is the greatest product of four adjacent numbers in the same direction
-- (up, down, left, right, or diagonally) in the 20�20 grid?
problem011 :: String
problem011 =
show . maximum $ map product adjacentNumbers
where
adjacentNumbers =
map (getCombos (+) const) comboIndicesDR -- to right
++ map (getCombos const (+)) comboIndicesDR -- to lower
++ map (getCombos (+) (+)) comboIndicesDR -- to lower right
++ map (getCombos (+) (-)) comboIndicesUR -- to upper right
getCombos fa fb (x,y) = map getValue [(a,b) | n <- [0..3], let a = fa x n, let b = fb y n]
comboIndicesDR = [(x,y) | x<-[1..16], y<-[1..16]]
comboIndicesUR = [(x,y) | x<-[1..16], y<-[3..19]]
getValue (x,y) = values !! (20*y + x)
values =
[
08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91, 08,
49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 04, 56, 62, 00,
81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 03, 49, 13, 36, 65,
52, 70, 95, 23, 04, 60, 11, 42, 69, 24, 68, 56, 01, 32, 56, 71, 37, 02, 36, 91,
22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80,
24, 47, 32, 60, 99, 03, 45, 02, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50,
32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70,
67, 26, 20, 68, 02, 62, 12, 20, 95, 63, 94, 39, 63, 08, 40, 91, 66, 49, 94, 21,
24, 55, 58, 05, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72,
21, 36, 23, 09, 75, 00, 76, 44, 20, 45, 35, 14, 00, 61, 33, 97, 34, 31, 33, 95,
78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 03, 80, 04, 62, 16, 14, 09, 53, 56, 92,
16, 39, 05, 42, 96, 35, 31, 47, 55, 58, 88, 24, 00, 17, 54, 24, 36, 29, 85, 57,
86, 56, 00, 48, 35, 71, 89, 07, 05, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58,
19, 80, 81, 68, 05, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 04, 89, 55, 40,
04, 52, 08, 83, 97, 35, 99, 16, 07, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66,
88, 36, 68, 87, 57, 62, 20, 72, 03, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69,
04, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 08, 46, 29, 32, 40, 62, 76, 36,
20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 04, 36, 16,
20, 73, 35, 29, 78, 31, 90, 01, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 05, 54,
01, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 01, 89, 19, 67, 48
] :: [Int]
-- The sequence of triangle numbers is generated by adding the natural numbers.
-- So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.
-- The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
--
-- Let us list the factors of the first seven triangle numbers:
--
-- 1: 1
-- 3: 1,3
-- 6: 1,2,3,6
-- 10: 1,2,5,10
-- 15: 1,3,5,15
-- 21: 1,3,7,21
-- 28: 1,2,4,7,14,28
--
-- We can see that 28 is the first triangle number to have over five divisors.
-- What is the value of the first triangle number to have over five hundred divisors?
problem012 :: String
problem012 =
case find numOfDivisorsGreaterThan500 triangleNumbers of
Nothing -> error "WTF ?!?"
Just value -> show value
where
numOfDivisorsGreaterThan500 n = divisorCount n > 500
-- Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.
--
-- 37107287533902102798797998220837590246510135740250
-- 46376937677490009712648124896970078050417018260538
-- 74324986199524741059474233309513058123726617309629
-- 91942213363574161572522430563301811072406154908250
-- 23067588207539346171171980310421047513778063246676
-- 89261670696623633820136378418383684178734361726757
-- 28112879812849979408065481931592621691275889832738
-- 44274228917432520321923589422876796487670272189318
-- 47451445736001306439091167216856844588711603153276
-- 70386486105843025439939619828917593665686757934951
-- 62176457141856560629502157223196586755079324193331
-- 64906352462741904929101432445813822663347944758178
-- 92575867718337217661963751590579239728245598838407
-- 58203565325359399008402633568948830189458628227828
-- 80181199384826282014278194139940567587151170094390
-- 35398664372827112653829987240784473053190104293586
-- 86515506006295864861532075273371959191420517255829
-- 71693888707715466499115593487603532921714970056938
-- 54370070576826684624621495650076471787294438377604
-- 53282654108756828443191190634694037855217779295145
-- 36123272525000296071075082563815656710885258350721
-- 45876576172410976447339110607218265236877223636045
-- 17423706905851860660448207621209813287860733969412
-- 81142660418086830619328460811191061556940512689692
-- 51934325451728388641918047049293215058642563049483
-- 62467221648435076201727918039944693004732956340691
-- 15732444386908125794514089057706229429197107928209
-- 55037687525678773091862540744969844508330393682126
-- 18336384825330154686196124348767681297534375946515
-- 80386287592878490201521685554828717201219257766954
-- 78182833757993103614740356856449095527097864797581
-- 16726320100436897842553539920931837441497806860984
-- 48403098129077791799088218795327364475675590848030
-- 87086987551392711854517078544161852424320693150332
-- 59959406895756536782107074926966537676326235447210
-- 69793950679652694742597709739166693763042633987085
-- 41052684708299085211399427365734116182760315001271
-- 65378607361501080857009149939512557028198746004375
-- 35829035317434717326932123578154982629742552737307
-- 94953759765105305946966067683156574377167401875275
-- 88902802571733229619176668713819931811048770190271
-- 25267680276078003013678680992525463401061632866526
-- 36270218540497705585629946580636237993140746255962
-- 24074486908231174977792365466257246923322810917141
-- 91430288197103288597806669760892938638285025333403
-- 34413065578016127815921815005561868836468420090470
-- 23053081172816430487623791969842487255036638784583
-- 11487696932154902810424020138335124462181441773470
-- 63783299490636259666498587618221225225512486764533
-- 67720186971698544312419572409913959008952310058822
-- 95548255300263520781532296796249481641953868218774
-- 76085327132285723110424803456124867697064507995236
-- 37774242535411291684276865538926205024910326572967
-- 23701913275725675285653248258265463092207058596522
-- 29798860272258331913126375147341994889534765745501
-- 18495701454879288984856827726077713721403798879715
-- 38298203783031473527721580348144513491373226651381
-- 34829543829199918180278916522431027392251122869539
-- 40957953066405232632538044100059654939159879593635
-- 29746152185502371307642255121183693803580388584903
-- 41698116222072977186158236678424689157993532961922
-- 62467957194401269043877107275048102390895523597457
-- 23189706772547915061505504953922979530901129967519
-- 86188088225875314529584099251203829009407770775672
-- 11306739708304724483816533873502340845647058077308
-- 82959174767140363198008187129011875491310547126581
-- 97623331044818386269515456334926366572897563400500
-- 42846280183517070527831839425882145521227251250327
-- 55121603546981200581762165212827652751691296897789
-- 32238195734329339946437501907836945765883352399886
-- 75506164965184775180738168837861091527357929701337
-- 62177842752192623401942399639168044983993173312731
-- 32924185707147349566916674687634660915035914677504
-- 99518671430235219628894890102423325116913619626622
-- 73267460800591547471830798392868535206946944540724
-- 76841822524674417161514036427982273348055556214818
-- 97142617910342598647204516893989422179826088076852
-- 87783646182799346313767754307809363333018982642090
-- 10848802521674670883215120185883543223812876952786
-- 71329612474782464538636993009049310363619763878039
-- 62184073572399794223406235393808339651327408011116
-- 66627891981488087797941876876144230030984490851411
-- 60661826293682836764744779239180335110989069790714
-- 85786944089552990653640447425576083659976645795096
-- 66024396409905389607120198219976047599490197230297
-- 64913982680032973156037120041377903785566085089252
-- 16730939319872750275468906903707539413042652315011
-- 94809377245048795150954100921645863754710598436791
-- 78639167021187492431995700641917969777599028300699
-- 15368713711936614952811305876380278410754449733078
-- 40789923115535562561142322423255033685442488917353
-- 44889911501440648020369068063960672322193204149535
-- 41503128880339536053299340368006977710650566631954
-- 81234880673210146739058568557934581403627822703280
-- 82616570773948327592232845941706525094512325230608
-- 22918802058777319719839450180888072429661980811197
-- 77158542502016545090413245809786882778948721859617
-- 72107838435069186155435662884062257473692284509516
-- 20849603980134001723930671666823555245252804609722
-- 53503534226472524250874054075591789781264330331690
problem013 :: String
problem013 = take 10 . show . sum $ values
where
values =
[
37107287533902102798797998220837590246510135740250,
46376937677490009712648124896970078050417018260538,
74324986199524741059474233309513058123726617309629,
91942213363574161572522430563301811072406154908250,
23067588207539346171171980310421047513778063246676,
89261670696623633820136378418383684178734361726757,
28112879812849979408065481931592621691275889832738,
44274228917432520321923589422876796487670272189318,
47451445736001306439091167216856844588711603153276,
70386486105843025439939619828917593665686757934951,
62176457141856560629502157223196586755079324193331,
64906352462741904929101432445813822663347944758178,
92575867718337217661963751590579239728245598838407,
58203565325359399008402633568948830189458628227828,
80181199384826282014278194139940567587151170094390,
35398664372827112653829987240784473053190104293586,
86515506006295864861532075273371959191420517255829,
71693888707715466499115593487603532921714970056938,
54370070576826684624621495650076471787294438377604,
53282654108756828443191190634694037855217779295145,
36123272525000296071075082563815656710885258350721,
45876576172410976447339110607218265236877223636045,
17423706905851860660448207621209813287860733969412,
81142660418086830619328460811191061556940512689692,
51934325451728388641918047049293215058642563049483,
62467221648435076201727918039944693004732956340691,
15732444386908125794514089057706229429197107928209,
55037687525678773091862540744969844508330393682126,
18336384825330154686196124348767681297534375946515,
80386287592878490201521685554828717201219257766954,
78182833757993103614740356856449095527097864797581,
16726320100436897842553539920931837441497806860984,
48403098129077791799088218795327364475675590848030,
87086987551392711854517078544161852424320693150332,
59959406895756536782107074926966537676326235447210,
69793950679652694742597709739166693763042633987085,
41052684708299085211399427365734116182760315001271,
65378607361501080857009149939512557028198746004375,
35829035317434717326932123578154982629742552737307,
94953759765105305946966067683156574377167401875275,
88902802571733229619176668713819931811048770190271,
25267680276078003013678680992525463401061632866526,
36270218540497705585629946580636237993140746255962,
24074486908231174977792365466257246923322810917141,
91430288197103288597806669760892938638285025333403,
34413065578016127815921815005561868836468420090470,
23053081172816430487623791969842487255036638784583,
11487696932154902810424020138335124462181441773470,
63783299490636259666498587618221225225512486764533,
67720186971698544312419572409913959008952310058822,
95548255300263520781532296796249481641953868218774,
76085327132285723110424803456124867697064507995236,
37774242535411291684276865538926205024910326572967,
23701913275725675285653248258265463092207058596522,
29798860272258331913126375147341994889534765745501,
18495701454879288984856827726077713721403798879715,
38298203783031473527721580348144513491373226651381,
34829543829199918180278916522431027392251122869539,
40957953066405232632538044100059654939159879593635,
29746152185502371307642255121183693803580388584903,
41698116222072977186158236678424689157993532961922,
62467957194401269043877107275048102390895523597457,
23189706772547915061505504953922979530901129967519,
86188088225875314529584099251203829009407770775672,
11306739708304724483816533873502340845647058077308,
82959174767140363198008187129011875491310547126581,
97623331044818386269515456334926366572897563400500,
42846280183517070527831839425882145521227251250327,
55121603546981200581762165212827652751691296897789,
32238195734329339946437501907836945765883352399886,
75506164965184775180738168837861091527357929701337,
62177842752192623401942399639168044983993173312731,
32924185707147349566916674687634660915035914677504,
99518671430235219628894890102423325116913619626622,
73267460800591547471830798392868535206946944540724,
76841822524674417161514036427982273348055556214818,
97142617910342598647204516893989422179826088076852,
87783646182799346313767754307809363333018982642090,
10848802521674670883215120185883543223812876952786,
71329612474782464538636993009049310363619763878039,
62184073572399794223406235393808339651327408011116,
66627891981488087797941876876144230030984490851411,
60661826293682836764744779239180335110989069790714,
85786944089552990653640447425576083659976645795096,
66024396409905389607120198219976047599490197230297,
64913982680032973156037120041377903785566085089252,
16730939319872750275468906903707539413042652315011,
94809377245048795150954100921645863754710598436791,
78639167021187492431995700641917969777599028300699,
15368713711936614952811305876380278410754449733078,
40789923115535562561142322423255033685442488917353,
44889911501440648020369068063960672322193204149535,
41503128880339536053299340368006977710650566631954,
81234880673210146739058568557934581403627822703280,
82616570773948327592232845941706525094512325230608,
22918802058777319719839450180888072429661980811197,
77158542502016545090413245809786882778948721859617,
72107838435069186155435662884062257473692284509516,
20849603980134001723930671666823555245252804609722,
53503534226472524250874054075591789781264330331690
]
-- The following iterative sequence is defined for the set of positive integers:
--
-- n -> n/2 (n is even)
-- n -> 3n + 1 (n is odd)
--
-- Using the rule above and starting with 13, we generate the following sequence:
-- 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
--
-- It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms.
-- Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
-- Which starting number, under one million, produces the longest chain?
-- NOTE: Once the chain starts the terms are allowed to go above one million.
problem014 :: String
problem014 = show . fst . greatest $ chainLengths
where
greatest = maximumBy (compare `on` snd)
chainLengths = map chainLength [1..1000000]
chainLength n = (n, chainLength' n 0)
chainLength' n l = case n of
1 -> l
x -> chainLength' (next x) (l+1)
next x = if even x then x `div` 2 else 3*x + 1
-- Starting in the top left corner of a 2x2 grid,
-- and only being able to move to the right and down,
-- there are exactly 6 routes to the bottom right corner.
--
-- How many such routes are there through a 20x20 grid?
problem015 :: String
problem015 = show $ noverk 40 20
-- 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
-- What is the sum of the digits of the number 2^1000?
problem016 :: String
problem016 = show . sum $ digits
where
digits = map digitToInt $ show (2^1000 :: Integer)
-- If the numbers 1 to 5 are written out in words: one, two, three, four, five,
-- then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
-- If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words,
-- how many letters would be used?
-- NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two)
-- contains 23 letters and 115 (one hundred and fifteen) contains 20 letters.
-- The use of "and" when writing out numbers is in compliance with British usage.
problem017 :: String
problem017 = show . sum $ map countLetters [1..1000]
where
countLetters number
| number == 1000 = 11
| number > 99 && number `isDivisibleBy` 100 = lettersFor (number `div` 100) + 7
| number > 99 = countLetters (number `div` 100) + 10 + countLetters (number `mod` 100)
| number < 20 || number `isDivisibleBy` 10 = lettersFor number
| otherwise = let m = number `mod` 10 in lettersFor (number - m) + lettersFor m
lettersFor n
| n == 17 = 9
| n `elem` [1, 2, 6, 10] = 3
| n `elem` [4, 5, 9] = 4
| n `elem` [3, 7, 8, 50, 60] = 5
| n `elem` [11, 12, 20, 30, 40, 80, 90] = 6
| n `elem` [15, 16, 70] = 7
| n `elem` [13, 14, 18, 19] = 8
| otherwise = error ("WTF ?!?: " ++ show n)
-- By starting at the top of the triangle below and moving to adjacent numbers on the row below,
-- the maximum total from top to bottom is 23.
--
-- 3
-- 7 4
-- 2 4 6
-- 8 5 9 3
--
-- That is, 3 + 7 + 4 + 9 = 23.
--
-- Find the maximum total from top to bottom of the triangle below:
--
-- 75
-- 95 64
-- 17 47 82
-- 18 35 87 10
-- 20 04 82 47 65
-- 19 01 23 75 03 34
-- 88 02 77 73 07 63 67
-- 99 65 04 28 06 16 70 92
-- 41 41 26 56 83 40 80 70 33
-- 41 48 72 33 47 32 37 16 94 29
-- 53 71 44 65 25 43 91 52 97 51 14
-- 70 11 33 28 77 73 17 78 39 68 17 57
-- 91 71 52 38 17 14 91 43 58 50 27 29 48
-- 63 66 04 68 89 53 67 30 73 16 69 87 40 31
-- 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
--
-- NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route.
-- However, Problem 67, is the same challenge with a triangle containing one-hundred rows;
-- it cannot be solved by brute force, and requires a clever method! ;o)
problem018 :: String
problem018 = show . reduce . parseTree $ treeString
where
reduce t = case t of
Leaf n -> n
Branch n left right -> reduce (Leaf (n + maximum [reduce left, reduce right]))
parseTree tree = parseTree' 0 $ combine tree
parseTree' _ [] = error "WTF ?!?"
parseTree' index (lastRow:[]) = Leaf (lastRow !! index)
parseTree' index (row:rows) = Branch (row !! index) (parseTree' index rows) (parseTree' (index+1) rows)
combine tree = map (toInt . words) $ lines tree
toInt = map read :: [String] -> [Int]
treeString = " 75\n"
++ " 95 64\n"
++ " 17 47 82\n"
++ " 18 35 87 10\n"
++ " 20 04 82 47 65\n"
++ " 19 01 23 75 03 34\n"
++ " 88 02 77 73 07 63 67\n"
++ " 99 65 04 28 06 16 70 92\n"
++ " 41 41 26 56 83 40 80 70 33\n"
++ " 41 48 72 33 47 32 37 16 94 29\n"
++ " 53 71 44 65 25 43 91 52 97 51 14\n"
++ " 70 11 33 28 77 73 17 78 39 68 17 57\n"
++ " 91 71 52 38 17 14 91 43 58 50 27 29 48\n"
++ " 63 66 04 68 89 53 67 30 73 16 69 87 40 31\n"
++ "04 62 98 27 23 09 70 98 73 93 38 53 60 04 23\n"
data Tree = Branch Int Tree Tree | Leaf Int
-- You are given the following information, but you may prefer to do some research for yourself.
--
-- 1 Jan 1900 was a Monday.
-- Thirty days has September,
-- April, June and November.
-- All the rest have thirty-one,
-- Saving February alone,
-- Which has twenty-eight, rain or shine.
-- And on leap years, twenty-nine.
-- A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
--
-- How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
problem019 :: String
problem019 = show . length $ filter isMonday firstMonthDays
where
isMonday date = check $ toWeekDate date
where check (_, _, d) = d == 7
firstMonthDays = [fromGregorian y m 1 | y <- [1901..2000], m <- [1..12]]
-- n! means n * (n - 1) * ... * 3 * 2 * 1
-- For example, 10! = 10 * 9 * ... * 3 * 2 * 1 = 3628800,
-- and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
-- Find the sum of the digits in the number 100!
problem020 :: String
problem020 = show . sum . digits $ factorial
where
factorial = product [1..100]
digits number = map digitToInt $ show number
| wey/projecteuler | Haskell/ProjectEuler/src/Problems011to020.hs | unlicense | 25,299 | 0 | 20 | 6,822 | 3,259 | 2,039 | 1,220 | 219 | 4 |
{-#LANGUAGE OverloadedStrings#-}
module Data.P440.XML.Instances.Render.ROO where
import qualified Data.P440.Domain.ROO as ROO
import Data.P440.Domain.ComplexTypes
import Data.P440.XML.Render
import qualified Data.P440.XML.Instances.Render.ComplexTypes as C
import qualified Data.P440.XML.Instances.Render.RPO
instance ToNode ROO.Файл where
toNode (ROO.Файл идЭС типИнф версПрог телОтпр
должнОтпр фамОтпр версФорм
решноотмен) =
complex "Файл"
["ИдЭС" =: идЭС
,"ТипИнф" =: типИнф
,"ВерсПрог" =: версПрог
,"ТелОтпр" =: телОтпр
,"ДолжнОтпр" =: должнОтпр
,"ФамОтпр" =: фамОтпр
,"ВерсФорм" =: версФорм
]
[Sequence [решноотмен]]
instance ToNode ROO.РЕШНООТМЕН where
toNode (ROO.РЕШНООТМЕН номРешОт датаПодп кодОснов видРеш номРешВО
датаРешВО номРешПр датаРешПр бик
наимБ номФ свНО свПл
счетИлиКЭСП руководитель) =
complex "РЕШНООТМЕН"
["НомРешОт" =: номРешОт
,"ДатаПодп" =: датаПодп
,"КодОснов" =: кодОснов
,"ВидРеш" =: видРеш
,"НомРешВО" =: номРешВО
,"ДатаРешВО" =: датаРешВО
,"НомРешПр" =: номРешПр
,"ДатаРешПр" =: датаРешПр
,"БИК" =: бик
,"НаимБ" =: наимБ
,"НомФ" =: номФ]
[Sequence [C.свНО "СвНО" свНО]
,Sequence [свПл]
,Sequence счетИлиКЭСП
,Sequence [C.рукНО "Руководитель" руководитель]]
| Macil-dev/p440 | src/Data/P440/XML/Instances/Render/ROO.hs | unlicense | 2,284 | 0 | 11 | 704 | 1,001 | 516 | 485 | 41 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Haste.DOM (withElems, getValue, setProp)
import Haste.Events (onEvent, MouseEvent(Click))
import Haste.Foreign (ffi)
import qualified Language.ZOWIE.Parser as Parser
import qualified Language.ZOWIE.Machine as Machine
getCh :: IO Char
getCh = ffi "(function() {var i=document.getElementById('prog-input'); var s=i.value; i.value=s.substring(1); return s.charCodeAt(0);})"
putCh :: Char -> IO ()
putCh = ffi "(function(c) {var o=document.getElementById('prog-output'); o.textContent += String.fromCharCode(c);})"
clearOutput :: IO ()
clearOutput = ffi "(function(c) {var o=document.getElementById('prog-output'); o.textContent = '';})"
main = withElems ["prog", "result", "run-button"] driver
driver [progElem, resultElem, runButtonElem] =
onEvent runButtonElem Click $ \_ -> do
Just text <- getValue progElem
clearOutput
case Parser.parseZOWIE text of
Right prog -> do
Machine.loadAndRunWithIO (getCh) (putCh) prog
return ()
Left error ->
setProp resultElem "textContent" $ show error
| catseye/ZOWIE | impl/zowie-hs/src/HasteMain.hs | unlicense | 1,153 | 0 | 15 | 229 | 256 | 137 | 119 | 24 | 2 |
module Data.Hadoop.SequenceFile.Types
( Header(..)
, MD5(..)
, RecordBlock(..)
) where
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.Text (Text)
import Text.Printf (printf)
import Data.Hadoop.Writable
------------------------------------------------------------------------
-- | The header of a sequence file. Contains the names of the Java classes
-- used to encode the file and potentially some metadata.
data Header = Header
{ hdKeyType :: !Text -- ^ Package qualified class name of the key type.
, hdValueType :: !Text -- ^ Package qualified class name of the value type.
, hdCompressionType :: !Text -- ^ Package qualified class name of the compression codec.
, hdMetadata :: ![(Text, Text)] -- ^ File metadata.
, hdSync :: !MD5 -- ^ The synchronization pattern used to check for
-- corruption throughout the file.
} deriving (Eq, Ord, Show)
-- | An MD5 hash. Stored between each record block in a sequence file to check
-- for corruption.
newtype MD5 = MD5 { unMD5 :: ByteString }
deriving (Eq, Ord)
-- | A block of key\/value pairs. The key at index /i/ always relates to the
-- value at index /i/. Both vectors will always be the same size.
data RecordBlock k v = RecordBlock
{ rbCount :: Int -- ^ The number of records.
, rbKeys :: Collection k -- ^ The keys.
, rbValues :: Collection v -- ^ The values.
}
------------------------------------------------------------------------
instance Show MD5 where
show (MD5 bs) = printf "MD5 %0x%0x%0x%0x%0x%0x"
(bs `B.index` 0)
(bs `B.index` 1)
(bs `B.index` 2)
(bs `B.index` 3)
(bs `B.index` 4)
(bs `B.index` 5)
| jystic/hadoop-formats | src/Data/Hadoop/SequenceFile/Types.hs | apache-2.0 | 1,943 | 0 | 11 | 596 | 322 | 202 | 120 | 40 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Web.Actions.User where
import Web.Utils
import Model.ResponseTypes
import Model.CoreTypes
import System.Random
import Database.Persist
import Database.Persist.Sql
import Data.Word8
import Control.Monad
import Data.Time
import Control.Monad.Trans
import qualified Data.ByteString as BS
import qualified Crypto.Hash.SHA512 as SHA
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
randomBytes:: Int -> StdGen -> [Word8]
randomBytes 0 _ = []
randomBytes ct g =
let (value, nextG) = next g
in fromIntegral value:randomBytes (ct - 1) nextG
randomBS :: Int -> StdGen -> BS.ByteString
randomBS len g =
BS.pack $ randomBytes len g
hashPassword :: T.Text -> BS.ByteString -> BS.ByteString
hashPassword password salt =
SHA.finalize $ SHA.updates SHA.init [salt, T.encodeUtf8 $ password]
createSession :: UserId -> SqlPersistM SessionId
createSession userId =
do now <- liftIO getCurrentTime
insert (Session (addUTCTime (5 * 3600) now) userId)
killSessions :: UserId -> SqlPersistM ()
killSessions userId =
deleteWhere [ SessionUserId ==. userId ]
loginUser :: T.Text -> T.Text -> SqlPersistM (Maybe UserId)
loginUser username password =
do mUserU <- getBy (UniqueUsername username)
mUserE <- getBy (UniqueEmail username)
case mUserU `mplus` mUserE of
Just userEntity ->
let user = entityVal userEntity
in if userPassword user == (makeHex $ hashPassword password (decodeHex $ userSalt user))
then return $ Just (entityKey userEntity)
else return Nothing
Nothing ->
return Nothing
loadUser :: SessionId -> SqlPersistM (Maybe (UserId, User))
loadUser sessId =
do mSess <- get sessId
now <- liftIO getCurrentTime
case mSess of
Just sess | sessionValidUntil sess > now ->
do mUser <- get (sessionUserId sess)
return $ fmap (\user -> (sessionUserId sess, user)) mUser
_ ->
return Nothing
registerUser :: T.Text -> T.Text -> T.Text -> SqlPersistM CommonResponse
registerUser username email password =
do mUserU <- getBy (UniqueUsername username)
mUserE <- getBy (UniqueEmail email)
case (mUserU, mUserE) of
(Just _, _) ->
return (CommonError "Username already taken!")
(_, Just _) ->
return (CommonError "Email already registered!")
(Nothing, Nothing) ->
do g <- liftIO $ getStdGen
let salt = randomBS 512 g
hash = hashPassword password salt
_ <- insert (User username (makeHex hash) (makeHex salt) email False False)
return (CommonSuccess "Signup complete. You may now login.")
| agrafix/funblog | src/Web/Actions/User.hs | apache-2.0 | 2,807 | 0 | 19 | 729 | 884 | 446 | 438 | 71 | 3 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE PackageImports #-}
{-
Copyright 2019 The CodeWorld Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
--------------------------------------------------------------------------------
-- |The standard set of functions and variables available to all programs.
--
-- You may use any of these functions and variables without defining them.
module Prelude (
module Internal.Exports
-- * Numbers
, module Internal.Num
-- * Text
, module Internal.Text
-- * General purpose functions
, module Internal.Prelude
, IO
) where
import Internal.Exports
import "base" Prelude (IO)
import Internal.Num
import Internal.Prelude hiding (randomsFrom)
import Internal.Text hiding (fromCWText, toCWText)
import Internal.CodeWorld
import Internal.Color
import Internal.Event
import Internal.Picture
| alphalambda/codeworld | codeworld-base/src/Prelude.hs | apache-2.0 | 1,393 | 0 | 5 | 246 | 107 | 72 | 35 | 17 | 0 |
-- 1533776805
import Data.List.Ordered(isect, member)
import Euler(triangular, pentagonal, hexagonal)
nn = 143
-- walk the pentagonal and triangular lists
-- check whether the hexagonal value is in them
-- also provide the remainder of each list for the next check
walkSet n ps ts = (member n $ isect ps2 ts2, ps3, ts3)
where (ps2,ps3) = span (n>=) ps
(ts2,ts3) = span (n>=) ts
findTriple0 [] _ _ = error "findTriple0: empty"
findTriple0 (x:xs) ps ts = if f then x else nf
where (f,ps2,ts2) = walkSet x ps ts
nf = findTriple0 xs ps2 ts2
findTriple n = findTriple0 (drop n hexagonal) pentagonal triangular
main = putStrLn $ show $ findTriple nn
| higgsd/euler | hs/45.hs | bsd-2-clause | 676 | 0 | 8 | 145 | 234 | 128 | 106 | 12 | 2 |
module Chart.Distribution (renderContinuousDistribution,
renderDiscreteDistribution,
continuousDistributionPlot,
discreteDistributionPlot) where
import Graphics.Rendering.Chart
import Graphics.Rendering.Chart.Backend.Cairo
import Data.Colour
import Data.Default.Class
import Control.Lens ((&), (.~))
import Data.List (sort, span)
import qualified Data.Map as M
renderContinuousDistribution :: FilePath -> [Double] -> IO (PickFn ())
renderContinuousDistribution file xs = renderableToFile def renderable file
where renderable = toRenderable $ def
& layout_plots .~ [plotBars $ continuousDistributionPlot xs]
& layout_left_axis_visibility .~ nolabel
nolabel = def & axis_show_labels .~ False
& axis_show_ticks .~ False
renderDiscreteDistribution :: (Ord k, Show k) => FilePath -> [k] -> IO (PickFn ())
renderDiscreteDistribution file xs = renderableToFile def renderable file
where renderable = toRenderable $ def
& layout_plots .~ [plotBars $ discreteDistributionPlot $ map snd counts]
& layout_left_axis_visibility .~ nolabel
& layout_x_axis . laxis_generate .~ (autoIndexAxis $ map (show . fst) counts)
nolabel = def & axis_show_labels .~ False
& axis_show_ticks .~ False
counts = M.toList $ M.fromListWith (+) $ map (\x->(x,1)) xs
continuousDistributionPlot :: [Double] -> PlotBars Double Double
continuousDistributionPlot xs = def & plot_bars_alignment .~ BarsRight
& plot_bars_spacing .~ BarsFixGap 0 0
& plot_bars_values .~ (zip binmaxes $ map (:[]) bindensity)
where sorted = sort xs
numberofbins = ceiling $ 2 * (fromIntegral $ length xs) ** (0.333) -- rice rule
min = minimum sorted
max = maximum sorted
range = max - min
binwidths = range / (fromIntegral numberofbins)
binmaxes = map (\x-> min + (fromIntegral x)*binwidths) [1..numberofbins]
binranges = zip (min:binmaxes) (binmaxes++[max])
bincounts = map fromIntegral $ allBinCounts binranges sorted
bindensity = map (\(x,y) -> y/x) $ zip (repeat binwidths) bincounts
singleBinCount :: (Double,Double) -> [Double] -> (Int,[Double])
singleBinCount (min,max) xs = (length included, rest)
where (included, rest) = span (<max) xs
allBinCounts :: [(Double,Double)] -> [Double] -> [Int]
allBinCounts [] _ = []
allBinCounts (b:bs) xs = c : (allBinCounts bs rest)
where (c,rest) = singleBinCount b xs
discreteDistributionPlot :: [Double] -> PlotBars PlotIndex Double
discreteDistributionPlot vals = def
& plot_bars_values .~ (addIndexes $ map (:[]) vals)
& plot_bars_spacing .~ BarsFixGap 30 5
| richardfergie/chart-distribution | Chart/Distribution.hs | bsd-3-clause | 2,929 | 0 | 15 | 805 | 891 | 484 | 407 | -1 | -1 |
module Unregister where
import InstalledPackages
import Distribution.Text
import Distribution.Package (PackageId)
import Distribution.Simple.PackageIndex
import Distribution.InstalledPackageInfo
import Distribution.Simple.GHC
import Distribution.Simple.Program.HcPkg
import Distribution.Simple.Compiler (PackageDB(..))
import Distribution.Verbosity (normal)
import Config
import GraphExtraction
-- | Unregister the given list of packages and return
-- the full list of unregistered packages.
main :: Config -> [String] -> IO ()
main config pkgStrs =
do (_,pgmConfig) <- getProgramConfiguration config
let hcPkg = hcPkgInfo pgmConfig
pkgIds <- traverse parsePkg pkgStrs
pkgIndex <- getUserPackages config
let plan = computePlan pkgIds pkgIndex
mapM_ (unregister hcPkg normal UserPackageDB) plan
parsePkg :: String -> IO PackageId
parsePkg str =
case simpleParse str of
Nothing -> fail ("Unable to parse package: " ++ str)
Just p -> return p
computePlan ::
[PackageId] ->
PackageIndex InstalledPackageInfo ->
[PackageId]
computePlan rootIds pkgIndex = sourcePackageId . lookupVertex <$> plan
where
rootPkgs = lookupSourcePackageId pkgIndex =<< rootIds
rootVertexes = unitIdToVertex' . installedUnitId <$> rootPkgs
plan = extract pkgGraph rootVertexes
(pkgGraph, lookupVertex, unitIdToVertex) = dependencyGraph pkgIndex
unitIdToVertex' i =
case unitIdToVertex i of
Nothing -> error ("computePlan: " ++ show i)
Just v -> v
| glguy/GhcPkgUtils | Unregister.hs | bsd-3-clause | 1,525 | 0 | 13 | 283 | 385 | 200 | 185 | 38 | 2 |
{-|
Module : Idris.Elab.Term
Description : Code to elaborate terms.
Copyright :
License : BSD3
Maintainer : The Idris Community.
-}
{-# LANGUAGE LambdaCase, PatternGuards, ViewPatterns #-}
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
module Idris.Elab.Term where
import Idris.AbsSyntax
import Idris.AbsSyntaxTree
import Idris.DSL
import Idris.Delaborate
import Idris.Error
import Idris.ProofSearch
import Idris.Output (pshow)
import Idris.Core.CaseTree (SC, SC'(STerm), findCalls, findUsedArgs)
import Idris.Core.Elaborate hiding (Tactic(..))
import Idris.Core.TT
import Idris.Core.Evaluate
import Idris.Core.Unify
import Idris.Core.ProofTerm (getProofTerm)
import Idris.Core.Typecheck (check, recheck, converts, isType)
import Idris.Core.WHNF (whnf)
import Idris.Coverage (buildSCG, checkDeclTotality, checkPositive, genClauses, recoverableCoverage, validCoverageCase)
import Idris.ErrReverse (errReverse)
import Idris.Elab.Quasiquote (extractUnquotes)
import Idris.Elab.Utils
import Idris.Elab.Rewrite
import Idris.Reflection
import qualified Util.Pretty as U
import Control.Applicative ((<$>))
import Control.Monad
import Control.Monad.State.Strict
import Data.Foldable (for_)
import Data.List
import qualified Data.Map as M
import Data.Maybe (mapMaybe, fromMaybe, catMaybes, maybeToList)
import qualified Data.Set as S
import qualified Data.Text as T
import Debug.Trace
data ElabMode = ETyDecl | ETransLHS | ELHS | ERHS
deriving Eq
data ElabResult = ElabResult {
-- | The term resulting from elaboration
resultTerm :: Term
-- | Information about new metavariables
, resultMetavars :: [(Name, (Int, Maybe Name, Type, [Name]))]
-- | Deferred declarations as the meaning of case blocks
, resultCaseDecls :: [PDecl]
-- | The potentially extended context from new definitions
, resultContext :: Context
-- | Meta-info about the new type declarations
, resultTyDecls :: [RDeclInstructions]
-- | Saved highlights from elaboration
, resultHighlighting :: [(FC, OutputAnnotation)]
-- | The new global name counter
, resultName :: Int
}
-- | Using the elaborator, convert a term in raw syntax to a fully
-- elaborated, typechecked term.
--
-- If building a pattern match, we convert undeclared variables from
-- holes to pattern bindings.
--
-- Also find deferred names in the term and their types
build :: IState
-> ElabInfo
-> ElabMode
-> FnOpts
-> Name
-> PTerm
-> ElabD ElabResult
build ist info emode opts fn tm
= do elab ist info emode opts fn tm
let tmIn = tm
let inf = case lookupCtxt fn (idris_tyinfodata ist) of
[TIPartial] -> True
_ -> False
hs <- get_holes
ivs <- get_instances
ptm <- get_term
-- Resolve remaining type classes. Two passes - first to get the
-- default Num instances, second to clean up the rest
when (not pattern) $
mapM_ (\n -> when (n `elem` hs) $
do focus n
g <- goal
try (resolveTC' True True 10 g fn ist)
(movelast n)) ivs
ivs <- get_instances
hs <- get_holes
when (not pattern) $
mapM_ (\n -> when (n `elem` hs) $
do focus n
g <- goal
ptm <- get_term
resolveTC' True True 10 g fn ist) ivs
when (not pattern) $ solveAutos ist fn False
tm <- get_term
ctxt <- get_context
probs <- get_probs
u <- getUnifyLog
hs <- get_holes
when (not pattern) $
traceWhen u ("Remaining holes:\n" ++ show hs ++ "\n" ++
"Remaining problems:\n" ++ qshow probs) $
do unify_all; matchProblems True; unifyProblems
when (not pattern) $ solveAutos ist fn True
probs <- get_probs
case probs of
[] -> return ()
((_,_,_,_,e,_,_):es) -> traceWhen u ("Final problems:\n" ++ qshow probs ++ "\nin\n" ++ show tm) $
if inf then return ()
else lift (Error e)
when tydecl (do mkPat
update_term liftPats
update_term orderPats)
EState is _ impls highlights _ _ <- getAux
tt <- get_term
ctxt <- get_context
let (tm, ds) = runState (collectDeferred (Just fn) (map fst is) ctxt tt) []
log <- getLog
g_nextname <- get_global_nextname
if log /= ""
then trace log $ return (ElabResult tm ds (map snd is) ctxt impls highlights g_nextname)
else return (ElabResult tm ds (map snd is) ctxt impls highlights g_nextname)
where pattern = emode == ELHS
tydecl = emode == ETyDecl
mkPat = do hs <- get_holes
tm <- get_term
case hs of
(h: hs) -> do patvar h; mkPat
[] -> return ()
-- | Build a term autogenerated as a typeclass method definition.
--
-- (Separate, so we don't go overboard resolving things that we don't
-- know about yet on the LHS of a pattern def)
buildTC :: IState -> ElabInfo -> ElabMode -> FnOpts -> Name ->
[Name] -> -- Cached names in the PTerm, before adding PAlternatives
PTerm ->
ElabD ElabResult
buildTC ist info emode opts fn ns tm
= do let tmIn = tm
let inf = case lookupCtxt fn (idris_tyinfodata ist) of
[TIPartial] -> True
_ -> False
-- set name supply to begin after highest index in tm
initNextNameFrom ns
elab ist info emode opts fn tm
probs <- get_probs
tm <- get_term
case probs of
[] -> return ()
((_,_,_,_,e,_,_):es) -> if inf then return ()
else lift (Error e)
dots <- get_dotterm
-- 'dots' are the PHidden things which have not been solved by
-- unification
when (not (null dots)) $
lift (Error (CantMatch (getInferTerm tm)))
EState is _ impls highlights _ _ <- getAux
tt <- get_term
ctxt <- get_context
let (tm, ds) = runState (collectDeferred (Just fn) (map fst is) ctxt tt) []
log <- getLog
g_nextname <- get_global_nextname
if (log /= "")
then trace log $ return (ElabResult tm ds (map snd is) ctxt impls highlights g_nextname)
else return (ElabResult tm ds (map snd is) ctxt impls highlights g_nextname)
where pattern = emode == ELHS
-- | return whether arguments of the given constructor name can be
-- matched on. If they're polymorphic, no, unless the type has beed
-- made concrete by the time we get around to elaborating the
-- argument.
getUnmatchable :: Context -> Name -> [Bool]
getUnmatchable ctxt n | isDConName n ctxt && n /= inferCon
= case lookupTyExact n ctxt of
Nothing -> []
Just ty -> checkArgs [] [] ty
where checkArgs :: [Name] -> [[Name]] -> Type -> [Bool]
checkArgs env ns (Bind n (Pi _ t _) sc)
= let env' = case t of
TType _ -> n : env
_ -> env in
checkArgs env' (intersect env (refsIn t) : ns)
(instantiate (P Bound n t) sc)
checkArgs env ns t
= map (not . null) (reverse ns)
getUnmatchable ctxt n = []
data ElabCtxt = ElabCtxt { e_inarg :: Bool,
e_isfn :: Bool, -- ^ Function part of application
e_guarded :: Bool,
e_intype :: Bool,
e_qq :: Bool,
e_nomatching :: Bool -- ^ can't pattern match
}
initElabCtxt = ElabCtxt False False False False False False
goal_polymorphic :: ElabD Bool
goal_polymorphic =
do ty <- goal
case ty of
P _ n _ -> do env <- get_env
case lookup n env of
Nothing -> return False
_ -> return True
_ -> return False
-- | Returns the set of declarations we need to add to complete the
-- definition (most likely case blocks to elaborate) as well as
-- declarations resulting from user tactic scripts (%runElab)
elab :: IState
-> ElabInfo
-> ElabMode
-> FnOpts
-> Name
-> PTerm
-> ElabD ()
elab ist info emode opts fn tm
= do let loglvl = opt_logLevel (idris_options ist)
when (loglvl > 5) $ unifyLog True
compute -- expand type synonyms, etc
let fc = maybe "(unknown)"
elabE initElabCtxt (elabFC info) tm -- (in argument, guarded, in type, in qquote)
est <- getAux
sequence_ (get_delayed_elab est)
end_unify
ptm <- get_term
when (pattern || intransform) -- convert remaining holes to pattern vars
(do unify_all
matchProblems False -- only the ones we matched earlier
unifyProblems
mkPat
update_term liftPats)
where
pattern = emode == ELHS
intransform = emode == ETransLHS
bindfree = emode == ETyDecl || emode == ELHS || emode == ETransLHS
autoimpls = opt_autoimpls (idris_options ist)
get_delayed_elab est =
let ds = delayed_elab est in
map snd $ sortBy (\(p1, _) (p2, _) -> compare p1 p2) ds
tcgen = Dictionary `elem` opts
reflection = Reflection `elem` opts
isph arg = case getTm arg of
Placeholder -> (True, priority arg)
tm -> (False, priority arg)
toElab ina arg = case getTm arg of
Placeholder -> Nothing
v -> Just (priority arg, elabE ina (elabFC info) v)
toElab' ina arg = case getTm arg of
Placeholder -> Nothing
v -> Just (elabE ina (elabFC info) v)
mkPat = do hs <- get_holes
tm <- get_term
case hs of
(h: hs) -> do patvar h; mkPat
[] -> return ()
elabRec = elabE initElabCtxt Nothing
-- | elabE elaborates an expression, possibly wrapping implicit coercions
-- and forces/delays. If you make a recursive call in elab', it is
-- normally correct to call elabE - the ones that don't are desugarings
-- typically
elabE :: ElabCtxt -> Maybe FC -> PTerm -> ElabD ()
elabE ina fc' t =
do solved <- get_recents
as <- get_autos
hs <- get_holes
-- If any of the autos use variables which have recently been solved,
-- have another go at solving them now.
mapM_ (\(a, (failc, ns)) ->
if any (\n -> n `elem` solved) ns && head hs /= a
then solveAuto ist fn False (a, failc)
else return ()) as
apt <- expandToArity t
itm <- if not pattern then insertImpLam ina apt else return apt
ct <- insertCoerce ina itm
t' <- insertLazy ct
g <- goal
tm <- get_term
ps <- get_probs
hs <- get_holes
--trace ("Elaborating " ++ show t' ++ " in " ++ show g
-- ++ "\n" ++ show tm
-- ++ "\nholes " ++ show hs
-- ++ "\nproblems " ++ show ps
-- ++ "\n-----------\n") $
--trace ("ELAB " ++ show t') $
env <- get_env
let fc = fileFC "Force"
handleError (forceErr t' env)
(elab' ina fc' t')
(elab' ina fc' (PApp fc (PRef fc [] (sUN "Force"))
[pimp (sUN "t") Placeholder True,
pimp (sUN "a") Placeholder True,
pexp ct]))
forceErr orig env (CantUnify _ (t,_) (t',_) _ _ _)
| (P _ (UN ht) _, _) <- unApply (normalise (tt_ctxt ist) env t),
ht == txt "Delayed" = notDelay orig
forceErr orig env (CantUnify _ (t,_) (t',_) _ _ _)
| (P _ (UN ht) _, _) <- unApply (normalise (tt_ctxt ist) env t'),
ht == txt "Delayed" = notDelay orig
forceErr orig env (InfiniteUnify _ t _)
| (P _ (UN ht) _, _) <- unApply (normalise (tt_ctxt ist) env t),
ht == txt "Delayed" = notDelay orig
forceErr orig env (Elaborating _ _ _ t) = forceErr orig env t
forceErr orig env (ElaboratingArg _ _ _ t) = forceErr orig env t
forceErr orig env (At _ t) = forceErr orig env t
forceErr orig env t = False
notDelay t@(PApp _ (PRef _ _ (UN l)) _) | l == txt "Delay" = False
notDelay _ = True
local f = do e <- get_env
return (f `elem` map fst e)
-- | Is a constant a type?
constType :: Const -> Bool
constType (AType _) = True
constType StrType = True
constType VoidType = True
constType _ = False
-- "guarded" means immediately under a constructor, to help find patvars
elab' :: ElabCtxt -- ^ (in an argument, guarded, in a type, in a quasiquote)
-> Maybe FC -- ^ The closest FC in the syntax tree, if applicable
-> PTerm -- ^ The term to elaborate
-> ElabD ()
elab' ina fc (PNoImplicits t) = elab' ina fc t -- skip elabE step
elab' ina fc (PType fc') =
do apply RType []
solve
highlightSource fc' (AnnType "Type" "The type of types")
elab' ina fc (PUniverse u) = do apply (RUType u) []; solve
-- elab' (_,_,inty) (PConstant c)
-- | constType c && pattern && not reflection && not inty
-- = lift $ tfail (Msg "Typecase is not allowed")
elab' ina fc tm@(PConstant fc' c)
| pattern && not reflection && not (e_qq ina) && not (e_intype ina)
&& isTypeConst c
= lift $ tfail $ Msg ("No explicit types on left hand side: " ++ show tm)
| pattern && not reflection && not (e_qq ina) && e_nomatching ina
= lift $ tfail $ Msg ("Attempting concrete match on polymorphic argument: " ++ show tm)
| otherwise = do apply (RConstant c) []
solve
highlightSource fc' (AnnConst c)
elab' ina fc (PQuote r) = do fill r; solve
elab' ina _ (PTrue fc _) =
do hnf_compute
g <- goal
case g of
TType _ -> elab' ina (Just fc) (PRef fc [] unitTy)
UType _ -> elab' ina (Just fc) (PRef fc [] unitTy)
_ -> elab' ina (Just fc) (PRef fc [] unitCon)
elab' ina fc (PResolveTC (FC "HACK" _ _)) -- for chasing parent classes
= do g <- goal; resolveTC False False 5 g fn elabRec ist
elab' ina fc (PResolveTC fc')
= do c <- getNameFrom (sMN 0 "__class")
instanceArg c
-- Elaborate the equality type first homogeneously, then
-- heterogeneously as a fallback
elab' ina _ (PApp fc (PRef _ _ n) args)
| n == eqTy, [Placeholder, Placeholder, l, r] <- map getTm args
= try (do tyn <- getNameFrom (sMN 0 "aqty")
claim tyn RType
movelast tyn
elab' ina (Just fc) (PApp fc (PRef fc [] eqTy)
[pimp (sUN "A") (PRef NoFC [] tyn) True,
pimp (sUN "B") (PRef NoFC [] tyn) False,
pexp l, pexp r]))
(do atyn <- getNameFrom (sMN 0 "aqty")
btyn <- getNameFrom (sMN 0 "bqty")
claim atyn RType
movelast atyn
claim btyn RType
movelast btyn
elab' ina (Just fc) (PApp fc (PRef fc [] eqTy)
[pimp (sUN "A") (PRef NoFC [] atyn) True,
pimp (sUN "B") (PRef NoFC [] btyn) False,
pexp l, pexp r]))
elab' ina _ (PPair fc hls _ l r)
= do hnf_compute
g <- goal
let (tc, _) = unApply g
case g of
TType _ -> elab' ina (Just fc) (PApp fc (PRef fc hls pairTy)
[pexp l,pexp r])
UType _ -> elab' ina (Just fc) (PApp fc (PRef fc hls upairTy)
[pexp l,pexp r])
_ -> case tc of
P _ n _ | n == upairTy
-> elab' ina (Just fc) (PApp fc (PRef fc hls upairCon)
[pimp (sUN "A") Placeholder False,
pimp (sUN "B") Placeholder False,
pexp l, pexp r])
_ -> elab' ina (Just fc) (PApp fc (PRef fc hls pairCon)
[pimp (sUN "A") Placeholder False,
pimp (sUN "B") Placeholder False,
pexp l, pexp r])
elab' ina _ (PDPair fc hls p l@(PRef nfc hl n) t r)
= case p of
IsType -> asType
IsTerm -> asValue
TypeOrTerm ->
do hnf_compute
g <- goal
case g of
TType _ -> asType
_ -> asValue
where asType = elab' ina (Just fc) (PApp fc (PRef NoFC hls sigmaTy)
[pexp t,
pexp (PLam fc n nfc Placeholder r)])
asValue = elab' ina (Just fc) (PApp fc (PRef fc hls sigmaCon)
[pimp (sMN 0 "a") t False,
pimp (sMN 0 "P") Placeholder True,
pexp l, pexp r])
elab' ina _ (PDPair fc hls p l t r) = elab' ina (Just fc) (PApp fc (PRef fc hls sigmaCon)
[pimp (sMN 0 "a") t False,
pimp (sMN 0 "P") Placeholder True,
pexp l, pexp r])
elab' ina fc (PAlternative ms (ExactlyOne delayok) as)
= do as_pruned <- doPrune as
-- Finish the mkUniqueNames job with the pruned set, rather than
-- the full set.
uns <- get_usedns
let as' = map (mkUniqueNames (uns ++ map snd ms) ms) as_pruned
(h : hs) <- get_holes
ty <- goal
case as' of
[] -> do hds <- mapM showHd as
lift $ tfail $ NoValidAlts hds
[x] -> elab' ina fc x
-- If there's options, try now, and if that fails, postpone
-- to later.
_ -> handleError isAmbiguous
(do hds <- mapM showHd as'
tryAll (zip (map (elab' ina fc) as')
hds))
(do movelast h
delayElab 5 $ do
hs <- get_holes
when (h `elem` hs) $ do
focus h
as'' <- doPrune as'
case as'' of
[x] -> elab' ina fc x
_ -> do hds <- mapM showHd as''
tryAll' False (zip (map (elab' ina fc) as'')
hds))
where showHd (PApp _ (PRef _ _ (UN l)) [_, _, arg])
| l == txt "Delay" = showHd (getTm arg)
showHd (PApp _ (PRef _ _ n) _) = return n
showHd (PRef _ _ n) = return n
showHd (PApp _ h _) = showHd h
showHd x = getNameFrom (sMN 0 "_") -- We probably should do something better than this here
doPrune as =
do compute
ty <- goal
let (tc, _) = unApply (unDelay ty)
env <- get_env
return $ pruneByType env tc (unDelay ty) ist as
unDelay t | (P _ (UN l) _, [_, arg]) <- unApply t,
l == txt "Delayed" = unDelay arg
| otherwise = t
isAmbiguous (CantResolveAlts _) = delayok
isAmbiguous (Elaborating _ _ _ e) = isAmbiguous e
isAmbiguous (ElaboratingArg _ _ _ e) = isAmbiguous e
isAmbiguous (At _ e) = isAmbiguous e
isAmbiguous _ = False
elab' ina fc (PAlternative ms FirstSuccess as_in)
= do -- finish the mkUniqueNames job
uns <- get_usedns
let as = map (mkUniqueNames (uns ++ map snd ms) ms) as_in
trySeq as
where -- if none work, take the error from the first
trySeq (x : xs) = let e1 = elab' ina fc x in
try' e1 (trySeq' e1 xs) True
trySeq [] = fail "Nothing to try in sequence"
trySeq' deferr [] = do deferr; unifyProblems
trySeq' deferr (x : xs)
= try' (tryCatch (do elab' ina fc x
solveAutos ist fn False
unifyProblems)
(\_ -> trySeq' deferr []))
(trySeq' deferr xs) True
elab' ina fc (PAlternative ms TryImplicit (orig : alts)) = do
env <- get_env
compute
ty <- goal
let doelab = elab' ina fc orig
tryCatch doelab
(\err ->
if recoverableErr err
then -- trace ("NEED IMPLICIT! " ++ show orig ++ "\n" ++
-- show alts ++ "\n" ++
-- showQuick err) $
-- Prune the coercions so that only the ones
-- with the right type to fix the error will be tried!
case pruneAlts err alts env of
[] -> lift $ tfail err
alts' -> do
try' (elab' ina fc (PAlternative ms (ExactlyOne False) alts'))
(lift $ tfail err) -- take error from original if all fail
True
else lift $ tfail err)
where
recoverableErr (CantUnify _ _ _ _ _ _) = True
recoverableErr (TooManyArguments _) = False
recoverableErr (CantSolveGoal _ _) = False
recoverableErr (CantResolveAlts _) = False
recoverableErr (NoValidAlts _) = True
recoverableErr (ProofSearchFail (Msg _)) = True
recoverableErr (ProofSearchFail _) = False
recoverableErr (ElaboratingArg _ _ _ e) = recoverableErr e
recoverableErr (At _ e) = recoverableErr e
recoverableErr (ElabScriptDebug _ _ _) = False
recoverableErr _ = True
pruneAlts (CantUnify _ (inc, _) (outc, _) _ _ _) alts env
= case unApply (normalise (tt_ctxt ist) env inc) of
(P (TCon _ _) n _, _) -> filter (hasArg n env) alts
(Constant _, _) -> alts
_ -> filter isLend alts -- special case hack for 'Borrowed'
pruneAlts (ElaboratingArg _ _ _ e) alts env = pruneAlts e alts env
pruneAlts (At _ e) alts env = pruneAlts e alts env
pruneAlts (NoValidAlts as) alts env = alts
pruneAlts err alts _ = filter isLend alts
hasArg n env ap | isLend ap = True -- special case hack for 'Borrowed'
hasArg n env (PApp _ (PRef _ _ a) _)
= case lookupTyExact a (tt_ctxt ist) of
Just ty -> let args = map snd (getArgTys (normalise (tt_ctxt ist) env ty)) in
any (fnIs n) args
Nothing -> False
hasArg n env (PAlternative _ _ as) = any (hasArg n env) as
hasArg n _ tm = False
isLend (PApp _ (PRef _ _ l) _) = l == sNS (sUN "lend") ["Ownership"]
isLend _ = False
fnIs n ty = case unApply ty of
(P _ n' _, _) -> n == n'
_ -> False
showQuick (CantUnify _ (l, _) (r, _) _ _ _)
= show (l, r)
showQuick (ElaboratingArg _ _ _ e) = showQuick e
showQuick (At _ e) = showQuick e
showQuick (ProofSearchFail (Msg _)) = "search fail"
showQuick _ = "No chance"
elab' ina _ (PPatvar fc n) | bindfree
= do patvar n
update_term liftPats
highlightSource fc (AnnBoundName n False)
-- elab' (_, _, inty) (PRef fc f)
-- | isTConName f (tt_ctxt ist) && pattern && not reflection && not inty
-- = lift $ tfail (Msg "Typecase is not allowed")
elab' ec _ tm@(PRef fc hl n)
| pattern && not reflection && not (e_qq ec) && not (e_intype ec)
&& isTConName n (tt_ctxt ist)
= lift $ tfail $ Msg ("No explicit types on left hand side: " ++ show tm)
| pattern && not reflection && not (e_qq ec) && e_nomatching ec
= lift $ tfail $ Msg ("Attempting concrete match on polymorphic argument: " ++ show tm)
| (pattern || intransform || (bindfree && bindable n)) && not (inparamBlock n) && not (e_qq ec)
= do ty <- goal
testImplicitWarning fc n ty
let ina = e_inarg ec
guarded = e_guarded ec
inty = e_intype ec
ctxt <- get_context
let defined = case lookupTy n ctxt of
[] -> False
_ -> True
-- this is to stop us resolve type classes recursively
-- trace (show (n, guarded)) $
if (tcname n && ina && not intransform)
then erun fc $
do patvar n
update_term liftPats
highlightSource fc (AnnBoundName n False)
else if (defined && not guarded)
then do apply (Var n) []
annot <- findHighlight n
solve
highlightSource fc annot
else try (do apply (Var n) []
annot <- findHighlight n
solve
highlightSource fc annot)
(do patvar n
update_term liftPats
highlightSource fc (AnnBoundName n False))
where inparamBlock n = case lookupCtxtName n (inblock info) of
[] -> False
_ -> True
bindable (NS _ _) = False
bindable (MN _ _) = True
bindable n = implicitable n && autoimpls
elab' ina _ f@(PInferRef fc hls n) = elab' ina (Just fc) (PApp NoFC f [])
elab' ina fc' tm@(PRef fc hls n)
| pattern && not reflection && not (e_qq ina) && not (e_intype ina)
&& isTConName n (tt_ctxt ist)
= lift $ tfail $ Msg ("No explicit types on left hand side: " ++ show tm)
| pattern && not reflection && not (e_qq ina) && e_nomatching ina
= lift $ tfail $ Msg ("Attempting concrete match on polymorphic argument: " ++ show tm)
| otherwise =
do fty <- get_type (Var n) -- check for implicits
ctxt <- get_context
env <- get_env
let a' = insertScopedImps fc (normalise ctxt env fty) []
if null a'
then erun fc $
do apply (Var n) []
hilite <- findHighlight n
solve
mapM_ (uncurry highlightSource) $
(fc, hilite) : map (\f -> (f, hilite)) hls
else elab' ina fc' (PApp fc tm [])
elab' ina _ (PLam _ _ _ _ PImpossible) = lift . tfail . Msg $ "Only pattern-matching lambdas can be impossible"
elab' ina _ (PLam fc n nfc Placeholder sc)
= do -- if n is a type constructor name, this makes no sense...
ctxt <- get_context
when (isTConName n ctxt) $
lift $ tfail (Msg $ "Can't use type constructor " ++ show n ++ " here")
checkPiGoal n
attack; intro (Just n);
addPSname n -- okay for proof search
-- trace ("------ intro " ++ show n ++ " ---- \n" ++ show ptm)
elabE (ina { e_inarg = True } ) (Just fc) sc; solve
highlightSource nfc (AnnBoundName n False)
elab' ec _ (PLam fc n nfc ty sc)
= do tyn <- getNameFrom (sMN 0 "lamty")
-- if n is a type constructor name, this makes no sense...
ctxt <- get_context
when (isTConName n ctxt) $
lift $ tfail (Msg $ "Can't use type constructor " ++ show n ++ " here")
checkPiGoal n
claim tyn RType
explicit tyn
attack
ptm <- get_term
hs <- get_holes
introTy (Var tyn) (Just n)
addPSname n -- okay for proof search
focus tyn
elabE (ec { e_inarg = True, e_intype = True }) (Just fc) ty
elabE (ec { e_inarg = True }) (Just fc) sc
solve
highlightSource nfc (AnnBoundName n False)
elab' ina fc (PPi p n nfc Placeholder sc)
= do attack; arg n (is_scoped p) (sMN 0 "ty")
addAutoBind p n
addPSname n -- okay for proof search
elabE (ina { e_inarg = True, e_intype = True }) fc sc
solve
highlightSource nfc (AnnBoundName n False)
elab' ina fc (PPi p n nfc ty sc)
= do attack; tyn <- getNameFrom (sMN 0 "ty")
claim tyn RType
n' <- case n of
MN _ _ -> unique_hole n
_ -> return n
forall n' (is_scoped p) (Var tyn)
addAutoBind p n'
addPSname n' -- okay for proof search
focus tyn
let ec' = ina { e_inarg = True, e_intype = True }
elabE ec' fc ty
elabE ec' fc sc
solve
highlightSource nfc (AnnBoundName n False)
elab' ina _ tm@(PLet fc n nfc ty val sc)
= do attack
ivs <- get_instances
tyn <- getNameFrom (sMN 0 "letty")
claim tyn RType
valn <- getNameFrom (sMN 0 "letval")
claim valn (Var tyn)
explicit valn
letbind n (Var tyn) (Var valn)
addPSname n
case ty of
Placeholder -> return ()
_ -> do focus tyn
explicit tyn
elabE (ina { e_inarg = True, e_intype = True })
(Just fc) ty
focus valn
elabE (ina { e_inarg = True, e_intype = True })
(Just fc) val
ivs' <- get_instances
env <- get_env
elabE (ina { e_inarg = True }) (Just fc) sc
when (not (pattern || intransform)) $
mapM_ (\n -> do focus n
g <- goal
hs <- get_holes
if all (\n -> n == tyn || not (n `elem` hs)) (freeNames g)
then handleError (tcRecoverable emode)
(resolveTC True False 10 g fn elabRec ist)
(movelast n)
else movelast n)
(ivs' \\ ivs)
-- HACK: If the name leaks into its type, it may leak out of
-- scope outside, so substitute in the outer scope.
expandLet n (case lookup n env of
Just (Let t v) -> v
other -> error ("Value not a let binding: " ++ show other))
solve
highlightSource nfc (AnnBoundName n False)
elab' ina _ (PGoal fc r n sc) = do
rty <- goal
attack
tyn <- getNameFrom (sMN 0 "letty")
claim tyn RType
valn <- getNameFrom (sMN 0 "letval")
claim valn (Var tyn)
letbind n (Var tyn) (Var valn)
focus valn
elabE (ina { e_inarg = True, e_intype = True }) (Just fc) (PApp fc r [pexp (delab ist rty)])
env <- get_env
computeLet n
elabE (ina { e_inarg = True }) (Just fc) sc
solve
-- elab' ina fc (PLet n Placeholder
-- (PApp fc r [pexp (delab ist rty)]) sc)
elab' ina _ tm@(PApp fc (PInferRef _ _ f) args) = do
rty <- goal
ds <- get_deferred
ctxt <- get_context
-- make a function type a -> b -> c -> ... -> rty for the
-- new function name
env <- get_env
argTys <- claimArgTys env args
fn <- getNameFrom (sMN 0 "inf_fn")
let fty = fnTy argTys rty
-- trace (show (ptm, map fst argTys)) $ focus fn
-- build and defer the function application
attack; deferType (mkN f) fty (map fst argTys); solve
-- elaborate the arguments, to unify their types. They all have to
-- be explicit.
mapM_ elabIArg (zip argTys args)
where claimArgTys env [] = return []
claimArgTys env (arg : xs) | Just n <- localVar env (getTm arg)
= do nty <- get_type (Var n)
ans <- claimArgTys env xs
return ((n, (False, forget nty)) : ans)
claimArgTys env (_ : xs)
= do an <- getNameFrom (sMN 0 "inf_argTy")
aval <- getNameFrom (sMN 0 "inf_arg")
claim an RType
claim aval (Var an)
ans <- claimArgTys env xs
return ((aval, (True, (Var an))) : ans)
fnTy [] ret = forget ret
fnTy ((x, (_, xt)) : xs) ret = RBind x (Pi Nothing xt RType) (fnTy xs ret)
localVar env (PRef _ _ x)
= case lookup x env of
Just _ -> Just x
_ -> Nothing
localVar env _ = Nothing
elabIArg ((n, (True, ty)), def) =
do focus n; elabE ina (Just fc) (getTm def)
elabIArg _ = return () -- already done, just a name
mkN n@(NS _ _) = n
mkN n@(SN _) = n
mkN n = case namespace info of
xs@(_:_) -> sNS n xs
_ -> n
elab' ina _ (PMatchApp fc fn)
= do (fn', imps) <- case lookupCtxtName fn (idris_implicits ist) of
[(n, args)] -> return (n, map (const True) args)
_ -> lift $ tfail (NoSuchVariable fn)
ns <- match_apply (Var fn') (map (\x -> (x,0)) imps)
solve
-- if f is local, just do a simple_app
-- FIXME: Anyone feel like refactoring this mess? - EB
elab' ina topfc tm@(PApp fc (PRef ffc hls f) args_in)
| pattern && not reflection && not (e_qq ina) && e_nomatching ina
= lift $ tfail $ Msg ("Attempting concrete match on polymorphic argument: " ++ show tm)
| otherwise = implicitApp $
do env <- get_env
ty <- goal
fty <- get_type (Var f)
ctxt <- get_context
annot <- findHighlight f
mapM_ checkKnownImplicit args_in
let args = insertScopedImps fc (normalise ctxt env fty) args_in
let unmatchableArgs = if pattern
then getUnmatchable (tt_ctxt ist) f
else []
-- trace ("BEFORE " ++ show f ++ ": " ++ show ty) $
when (pattern && not reflection && not (e_qq ina) && not (e_intype ina)
&& isTConName f (tt_ctxt ist)) $
lift $ tfail $ Msg ("No explicit types on left hand side: " ++ show tm)
-- trace (show (f, args_in, args)) $
if (f `elem` map fst env && length args == 1 && length args_in == 1)
then -- simple app, as below
do simple_app False
(elabE (ina { e_isfn = True }) (Just fc) (PRef ffc hls f))
(elabE (ina { e_inarg = True }) (Just fc) (getTm (head args)))
(show tm)
solve
mapM (uncurry highlightSource) $
(ffc, annot) : map (\f -> (f, annot)) hls
return []
else
do ivs <- get_instances
ps <- get_probs
-- HACK: we shouldn't resolve type classes if we're defining an instance
-- function or default definition.
let isinf = f == inferCon || tcname f
-- if f is a type class, we need to know its arguments so that
-- we can unify with them
case lookupCtxt f (idris_classes ist) of
[] -> return ()
_ -> do mapM_ setInjective (map getTm args)
-- maybe more things are solvable now
unifyProblems
let guarded = isConName f ctxt
-- trace ("args is " ++ show args) $ return ()
ns <- apply (Var f) (map isph args)
-- trace ("ns is " ++ show ns) $ return ()
-- mark any type class arguments as injective
when (not pattern) $ mapM_ checkIfInjective (map snd ns)
unifyProblems -- try again with the new information,
-- to help with disambiguation
ulog <- getUnifyLog
annot <- findHighlight f
mapM (uncurry highlightSource) $
(ffc, annot) : map (\f -> (f, annot)) hls
elabArgs ist (ina { e_inarg = e_inarg ina || not isinf })
[] fc False f
(zip ns (unmatchableArgs ++ repeat False))
(f == sUN "Force")
(map (\x -> getTm x) args) -- TODO: remove this False arg
imp <- if (e_isfn ina) then
do guess <- get_guess
env <- get_env
case safeForgetEnv (map fst env) guess of
Nothing ->
return []
Just rguess -> do
gty <- get_type rguess
let ty_n = normalise ctxt env gty
return $ getReqImps ty_n
else return []
-- Now we find out how many implicits we needed at the
-- end of the application by looking at the goal again
-- - Have another go, but this time add the
-- implicits (can't think of a better way than this...)
case imp of
rs@(_:_) | not pattern -> return rs -- quit, try again
_ -> do solve
hs <- get_holes
ivs' <- get_instances
-- Attempt to resolve any type classes which have 'complete' types,
-- i.e. no holes in them
when (not pattern || (e_inarg ina && not tcgen &&
not (e_guarded ina))) $
mapM_ (\n -> do focus n
g <- goal
env <- get_env
hs <- get_holes
if all (\n -> not (n `elem` hs)) (freeNames g)
then handleError (tcRecoverable emode)
(resolveTC False False 10 g fn elabRec ist)
(movelast n)
else movelast n)
(ivs' \\ ivs)
return []
where
-- Run the elaborator, which returns how many implicit
-- args were needed, then run it again with those args. We need
-- this because we have to elaborate the whole application to
-- find out whether any computations have caused more implicits
-- to be needed.
implicitApp :: ElabD [ImplicitInfo] -> ElabD ()
implicitApp elab
| pattern || intransform = do elab; return ()
| otherwise
= do s <- get
imps <- elab
case imps of
[] -> return ()
es -> do put s
elab' ina topfc (PAppImpl tm es)
checkKnownImplicit imp
| UnknownImp `elem` argopts imp
= lift $ tfail $ UnknownImplicit (pname imp) f
checkKnownImplicit _ = return ()
getReqImps (Bind x (Pi (Just i) ty _) sc)
= i : getReqImps sc
getReqImps _ = []
checkIfInjective n = do
env <- get_env
case lookup n env of
Nothing -> return ()
Just b ->
case unApply (normalise (tt_ctxt ist) env (binderTy b)) of
(P _ c _, args) ->
case lookupCtxtExact c (idris_classes ist) of
Nothing -> return ()
Just ci -> -- type class, set as injective
do mapM_ setinjArg (getDets 0 (class_determiners ci) args)
-- maybe we can solve more things now...
ulog <- getUnifyLog
probs <- get_probs
traceWhen ulog ("Injective now " ++ show args ++ "\n" ++ qshow probs) $
unifyProblems
probs <- get_probs
traceWhen ulog (qshow probs) $ return ()
_ -> return ()
setinjArg (P _ n _) = setinj n
setinjArg _ = return ()
getDets i ds [] = []
getDets i ds (a : as) | i `elem` ds = a : getDets (i + 1) ds as
| otherwise = getDets (i + 1) ds as
tacTm (PTactics _) = True
tacTm (PProof _) = True
tacTm _ = False
setInjective (PRef _ _ n) = setinj n
setInjective (PApp _ (PRef _ _ n) _) = setinj n
setInjective _ = return ()
elab' ina _ tm@(PApp fc f [arg]) =
erun fc $
do simple_app (not $ headRef f)
(elabE (ina { e_isfn = True }) (Just fc) f)
(elabE (ina { e_inarg = True }) (Just fc) (getTm arg))
(show tm)
solve
where headRef (PRef _ _ _) = True
headRef (PApp _ f _) = headRef f
headRef (PAlternative _ _ as) = all headRef as
headRef _ = False
elab' ina fc (PAppImpl f es) = do appImpl (reverse es) -- not that we look...
solve
where appImpl [] = elab' (ina { e_isfn = False }) fc f -- e_isfn not set, so no recursive expansion of implicits
appImpl (e : es) = simple_app False
(appImpl es)
(elab' ina fc Placeholder)
(show f)
elab' ina fc Placeholder
= do (h : hs) <- get_holes
movelast h
elab' ina fc (PMetavar nfc n) =
do ptm <- get_term
-- When building the metavar application, leave out the unique
-- names which have been used elsewhere in the term, since we
-- won't be able to use them in the resulting application.
let unique_used = getUniqueUsed (tt_ctxt ist) ptm
let n' = metavarName (namespace info) n
attack
psns <- getPSnames
n' <- defer unique_used n'
solve
highlightSource nfc (AnnName n' (Just MetavarOutput) Nothing Nothing)
elab' ina fc (PProof ts) = do compute; mapM_ (runTac True ist (elabFC info) fn) ts
elab' ina fc (PTactics ts)
| not pattern = do mapM_ (runTac False ist fc fn) ts
| otherwise = elab' ina fc Placeholder
elab' ina fc (PElabError e) = lift $ tfail e
elab' ina mfc (PRewrite fc substfn rule sc newg)
= elabRewrite (elab' ina mfc) ist fc substfn rule sc newg
elab' ina _ c@(PCase fc scr opts)
= do attack
tyn <- getNameFrom (sMN 0 "scty")
claim tyn RType
valn <- getNameFrom (sMN 0 "scval")
scvn <- getNameFrom (sMN 0 "scvar")
claim valn (Var tyn)
letbind scvn (Var tyn) (Var valn)
-- Start filling in the scrutinee type, if we can work one
-- out from the case options
let scrTy = getScrType (map fst opts)
case scrTy of
Nothing -> return ()
Just ty -> do focus tyn
elabE ina (Just fc) ty
focus valn
elabE (ina { e_inarg = True }) (Just fc) scr
-- Solve any remaining implicits - we need to solve as many
-- as possible before making the 'case' type
unifyProblems
matchProblems True
args <- get_env
envU <- mapM (getKind args) args
let namesUsedInRHS = nub $ scvn : concatMap (\(_,rhs) -> allNamesIn rhs) opts
-- Drop the unique arguments used in the term already
-- and in the scrutinee (since it's
-- not valid to use them again anyway)
--
-- Also drop unique arguments which don't appear explicitly
-- in either case branch so they don't count as used
-- unnecessarily (can only do this for unique things, since we
-- assume they don't appear implicitly in types)
ptm <- get_term
let inOpts = (filter (/= scvn) (map fst args)) \\ (concatMap (\x -> allNamesIn (snd x)) opts)
let argsDropped = filter (isUnique envU)
(nub $ allNamesIn scr ++ inApp ptm ++
inOpts)
let args' = filter (\(n, _) -> n `notElem` argsDropped) args
attack
cname' <- defer argsDropped (mkN (mkCaseName fc fn))
solve
-- if the scrutinee is one of the 'args' in env, we should
-- inspect it directly, rather than adding it as a new argument
let newdef = PClauses fc [] cname'
(caseBlock fc cname' scr
(map (isScr scr) (reverse args')) opts)
-- elaborate case
updateAux (\e -> e { case_decls = (cname', newdef) : case_decls e } )
-- if we haven't got the type yet, hopefully we'll get it later!
movelast tyn
solve
where mkCaseName fc (NS n ns) = NS (mkCaseName fc n) ns
mkCaseName fc n = SN (CaseN (FC' fc) n)
-- mkCaseName (UN x) = UN (x ++ "_case")
-- mkCaseName (MN i x) = MN i (x ++ "_case")
mkN n@(NS _ _) = n
mkN n = case namespace info of
xs@(_:_) -> sNS n xs
_ -> n
getScrType [] = Nothing
getScrType (f : os) = maybe (getScrType os) Just (getAppType f)
getAppType (PRef _ _ n) =
case lookupTyName n (tt_ctxt ist) of
[(n', ty)] | isDConName n' (tt_ctxt ist) ->
case unApply (getRetTy ty) of
(P _ tyn _, args) ->
Just (PApp fc (PRef fc [] tyn)
(map pexp (map (const Placeholder) args)))
_ -> Nothing
_ -> Nothing -- ambiguity is no help to us!
getAppType (PApp _ t as) = getAppType t
getAppType _ = Nothing
inApp (P _ n _) = [n]
inApp (App _ f a) = inApp f ++ inApp a
inApp (Bind n (Let _ v) sc) = inApp v ++ inApp sc
inApp (Bind n (Guess _ v) sc) = inApp v ++ inApp sc
inApp (Bind n b sc) = inApp sc
inApp _ = []
isUnique envk n = case lookup n envk of
Just u -> u
_ -> False
getKind env (n, _)
= case lookup n env of
Nothing -> return (n, False) -- can't happen, actually...
Just b ->
do ty <- get_type (forget (binderTy b))
case ty of
UType UniqueType -> return (n, True)
UType AllTypes -> return (n, True)
_ -> return (n, False)
tcName tm | (P _ n _, _) <- unApply tm
= case lookupCtxt n (idris_classes ist) of
[_] -> True
_ -> False
tcName _ = False
usedIn ns (n, b)
= n `elem` ns
|| any (\x -> x `elem` ns) (allTTNames (binderTy b))
elab' ina fc (PUnifyLog t) = do unifyLog True
elab' ina fc t
unifyLog False
elab' ina fc (PQuasiquote t goalt)
= do -- First extract the unquoted subterms, replacing them with fresh
-- names in the quasiquoted term. Claim their reflections to be
-- an inferred type (to support polytypic quasiquotes).
finalTy <- goal
(t, unq) <- extractUnquotes 0 t
let unquoteNames = map fst unq
mapM_ (\uqn -> claim uqn (forget finalTy)) unquoteNames
-- Save the old state - we need a fresh proof state to avoid
-- capturing lexically available variables in the quoted term.
ctxt <- get_context
datatypes <- get_datatypes
g_nextname <- get_global_nextname
saveState
updatePS (const .
newProof (sMN 0 "q") (constraintNS info) ctxt datatypes g_nextname $
P Ref (reflm "TT") Erased)
-- Re-add the unquotes, letting Idris infer the (fictional)
-- types. Here, they represent the real type rather than the type
-- of their reflection.
mapM_ (\n -> do ty <- getNameFrom (sMN 0 "unqTy")
claim ty RType
movelast ty
claim n (Var ty)
movelast n)
unquoteNames
-- Determine whether there's an explicit goal type, and act accordingly
-- Establish holes for the type and value of the term to be
-- quasiquoted
qTy <- getNameFrom (sMN 0 "qquoteTy")
claim qTy RType
movelast qTy
qTm <- getNameFrom (sMN 0 "qquoteTm")
claim qTm (Var qTy)
-- Let-bind the result of elaborating the contained term, so that
-- the hole doesn't disappear
nTm <- getNameFrom (sMN 0 "quotedTerm")
letbind nTm (Var qTy) (Var qTm)
-- Fill out the goal type, if relevant
case goalt of
Nothing -> return ()
Just gTy -> do focus qTy
elabE (ina { e_qq = True }) fc gTy
-- Elaborate the quasiquoted term into the hole
focus qTm
elabE (ina { e_qq = True }) fc t
end_unify
-- We now have an elaborated term. Reflect it and solve the
-- original goal in the original proof state, preserving highlighting
env <- get_env
EState _ _ _ hs _ _ <- getAux
loadState
updateAux (\aux -> aux { highlighting = hs })
let quoted = fmap (explicitNames . binderVal) $ lookup nTm env
isRaw = case unApply (normaliseAll ctxt env finalTy) of
(P _ n _, []) | n == reflm "Raw" -> True
_ -> False
case quoted of
Just q -> do ctxt <- get_context
(q', _, _) <- lift $ recheck (constraintNS info) ctxt [(uq, Lam Erased) | uq <- unquoteNames] (forget q) q
if pattern
then if isRaw
then reflectRawQuotePattern unquoteNames (forget q')
else reflectTTQuotePattern unquoteNames q'
else do if isRaw
then -- we forget q' instead of using q to ensure rechecking
fill $ reflectRawQuote unquoteNames (forget q')
else fill $ reflectTTQuote unquoteNames q'
solve
Nothing -> lift . tfail . Msg $ "Broken elaboration of quasiquote"
-- Finally fill in the terms or patterns from the unquotes. This
-- happens last so that their holes still exist while elaborating
-- the main quotation.
mapM_ elabUnquote unq
where elabUnquote (n, tm)
= do focus n
elabE (ina { e_qq = False }) fc tm
elab' ina fc (PUnquote t) = fail "Found unquote outside of quasiquote"
elab' ina fc (PQuoteName n False nfc) =
do fill $ reflectName n
solve
elab' ina fc (PQuoteName n True nfc) =
do ctxt <- get_context
env <- get_env
case lookup n env of
Just _ -> do fill $ reflectName n
solve
highlightSource nfc (AnnBoundName n False)
Nothing ->
case lookupNameDef n ctxt of
[(n', _)] -> do fill $ reflectName n'
solve
highlightSource nfc (AnnName n' Nothing Nothing Nothing)
[] -> lift . tfail . NoSuchVariable $ n
more -> lift . tfail . CantResolveAlts $ map fst more
elab' ina fc (PAs _ n t) = lift . tfail . Msg $ "@-pattern not allowed here"
elab' ina fc (PHidden t)
| reflection = elab' ina fc t
| otherwise
= do (h : hs) <- get_holes
-- Dotting a hole means that either the hole or any outer
-- hole (a hole outside any occurrence of it)
-- must be solvable by unification as well as being filled
-- in directly.
-- Delay dotted things to the end, then when we elaborate them
-- we can check the result against what was inferred
movelast h
delayElab 10 $ do hs <- get_holes
when (h `elem` hs) $ do
focus h
dotterm
elab' ina fc t
elab' ina fc (PRunElab fc' tm ns) =
do attack
n <- getNameFrom (sMN 0 "tacticScript")
let scriptTy = RApp (Var (sNS (sUN "Elab")
["Elab", "Reflection", "Language"]))
(Var unitTy)
claim n scriptTy
focus n
attack -- to get an extra hole
elab' ina (Just fc') tm
script <- get_guess
fullyElaborated script
solve -- eliminate the hole. Becuase there are no references, the script is only in the binding
env <- get_env
runElabAction info ist (maybe fc' id fc) env script ns
solve
elab' ina fc (PConstSugar constFC tm) =
-- Here we elaborate the contained term, then calculate
-- highlighting for constFC. The highlighting is the
-- highlighting for the outermost constructor of the result of
-- evaluating the elaborated term, if one exists (it always
-- should, but better to fail gracefully for something silly
-- like highlighting info). This is how implicit applications of
-- fromInteger get highlighted.
do saveState -- so we don't pollute the elaborated term
n <- getNameFrom (sMN 0 "cstI")
n' <- getNameFrom (sMN 0 "cstIhole")
g <- forget <$> goal
claim n' g
movelast n'
-- In order to intercept the elaborated value, we need to
-- let-bind it.
attack
letbind n g (Var n')
focus n'
elab' ina fc tm
env <- get_env
ctxt <- get_context
let v = fmap (normaliseAll ctxt env . finalise . binderVal)
(lookup n env)
loadState -- we have the highlighting - re-elaborate the value
elab' ina fc tm
case v of
Just val -> highlightConst constFC val
Nothing -> return ()
where highlightConst fc (P _ n _) =
highlightSource fc (AnnName n Nothing Nothing Nothing)
highlightConst fc (App _ f _) =
highlightConst fc f
highlightConst fc (Constant c) =
highlightSource fc (AnnConst c)
highlightConst _ _ = return ()
elab' ina fc x = fail $ "Unelaboratable syntactic form " ++ showTmImpls x
-- delay elaboration of 't', with priority 'pri' until after everything
-- else is done.
-- The delayed things with lower numbered priority will be elaborated
-- first. (In practice, this means delayed alternatives, then PHidden
-- things.)
delayElab pri t
= updateAux (\e -> e { delayed_elab = delayed_elab e ++ [(pri, t)] })
isScr :: PTerm -> (Name, Binder Term) -> (Name, (Bool, Binder Term))
isScr (PRef _ _ n) (n', b) = (n', (n == n', b))
isScr _ (n', b) = (n', (False, b))
caseBlock :: FC -> Name
-> PTerm -- original scrutinee
-> [(Name, (Bool, Binder Term))] -> [(PTerm, PTerm)] -> [PClause]
caseBlock fc n scr env opts
= let args' = findScr env
args = map mkarg (map getNmScr args') in
map (mkClause args) opts
where -- Find the variable we want as the scrutinee and mark it as
-- 'True'. If the scrutinee is in the environment, match on that
-- otherwise match on the new argument we're adding.
findScr ((n, (True, t)) : xs)
= (n, (True, t)) : scrName n xs
findScr [(n, (_, t))] = [(n, (True, t))]
findScr (x : xs) = x : findScr xs
-- [] can't happen since scrutinee is in the environment!
findScr [] = error "The impossible happened - the scrutinee was not in the environment"
-- To make sure top level pattern name remains in scope, put
-- it at the end of the environment
scrName n [] = []
scrName n [(_, t)] = [(n, t)]
scrName n (x : xs) = x : scrName n xs
getNmScr (n, (s, _)) = (n, s)
mkarg (n, s) = (PRef fc [] n, s)
-- may be shadowed names in the new pattern - so replace the
-- old ones with an _
-- Also, names which don't appear on the rhs should not be
-- fixed on the lhs, or this restricts the kind of matching
-- we can do to non-dependent types.
mkClause args (l, r)
= let args' = map (shadowed (allNamesIn l)) args
args'' = map (implicitable (allNamesIn r ++
keepscrName scr)) args'
lhs = PApp (getFC fc l) (PRef NoFC [] n)
(map (mkLHSarg l) args'') in
PClause (getFC fc l) n lhs [] r []
-- Keep scrutinee available if it's just a name (this makes
-- the names in scope look better when looking at a hole on
-- the rhs of a case)
keepscrName (PRef _ _ n) = [n]
keepscrName _ = []
mkLHSarg l (tm, True) = pexp l
mkLHSarg l (tm, False) = pexp tm
shadowed new (PRef _ _ n, s) | n `elem` new = (Placeholder, s)
shadowed new t = t
implicitable rhs (PRef _ _ n, s) | n `notElem` rhs = (Placeholder, s)
implicitable rhs t = t
getFC d (PApp fc _ _) = fc
getFC d (PRef fc _ _) = fc
getFC d (PAlternative _ _ (x:_)) = getFC d x
getFC d x = d
-- Fail if a term is not yet fully elaborated (e.g. if it contains
-- case block functions that don't yet exist)
fullyElaborated :: Term -> ElabD ()
fullyElaborated (P _ n _) =
do estate <- getAux
case lookup n (case_decls estate) of
Nothing -> return ()
Just _ -> lift . tfail $ ElabScriptStaging n
fullyElaborated (Bind n b body) = fullyElaborated body >> for_ b fullyElaborated
fullyElaborated (App _ l r) = fullyElaborated l >> fullyElaborated r
fullyElaborated (Proj t _) = fullyElaborated t
fullyElaborated _ = return ()
-- If the goal type is a "Lazy", then try elaborating via 'Delay'
-- first. We need to do this brute force approach, rather than anything
-- more precise, since there may be various other ambiguities to resolve
-- first.
insertLazy :: PTerm -> ElabD PTerm
insertLazy t@(PApp _ (PRef _ _ (UN l)) _) | l == txt "Delay" = return t
insertLazy t@(PApp _ (PRef _ _ (UN l)) _) | l == txt "Force" = return t
insertLazy (PCoerced t) = return t
-- Don't add a delay to pattern variables, since they can be forced
-- on the rhs
insertLazy t@(PPatvar _ _) | pattern = return t
insertLazy t =
do ty <- goal
env <- get_env
let (tyh, _) = unApply (normalise (tt_ctxt ist) env ty)
let tries = [mkDelay env t, t]
case tyh of
P _ (UN l) _ | l == txt "Delayed"
-> return (PAlternative [] FirstSuccess tries)
_ -> return t
where
mkDelay env (PAlternative ms b xs) = PAlternative ms b (map (mkDelay env) xs)
mkDelay env t
= let fc = fileFC "Delay" in
addImplBound ist (map fst env) (PApp fc (PRef fc [] (sUN "Delay"))
[pexp t])
-- Don't put implicit coercions around applications which are marked
-- as '%noImplicit', or around case blocks, otherwise we get exponential
-- blowup especially where there are errors deep in large expressions.
notImplicitable (PApp _ f _) = notImplicitable f
-- TMP HACK no coercing on bind (make this configurable)
notImplicitable (PRef _ _ n)
| [opts] <- lookupCtxt n (idris_flags ist)
= NoImplicit `elem` opts
notImplicitable (PAlternative _ _ as) = any notImplicitable as
-- case is tricky enough without implicit coercions! If they are needed,
-- they can go in the branches separately.
notImplicitable (PCase _ _ _) = True
notImplicitable _ = False
-- Elaboration works more smoothly if we expand function applications
-- to their full arity and elaborate it all at once (better error messages
-- in particular)
expandToArity tm@(PApp fc f a) = do
env <- get_env
case fullApp tm of
-- if f is global, leave it alone because we've already
-- expanded it to the right arity
PApp fc ftm@(PRef _ _ f) args | Just aty <- lookup f env ->
do let a = length (getArgTys (normalise (tt_ctxt ist) env (binderTy aty)))
return (mkPApp fc a ftm args)
_ -> return tm
expandToArity t = return t
fullApp (PApp _ (PApp fc f args) xs) = fullApp (PApp fc f (args ++ xs))
fullApp x = x
insertScopedImps fc (Bind n (Pi im@(Just i) _ _) sc) xs
| tcinstance i && not (toplevel_imp i)
= pimp n (PResolveTC fc) True : insertScopedImps fc sc xs
| not (toplevel_imp i)
= pimp n Placeholder True : insertScopedImps fc sc xs
insertScopedImps fc (Bind n (Pi _ _ _) sc) (x : xs)
= x : insertScopedImps fc sc xs
insertScopedImps _ _ xs = xs
insertImpLam ina t =
do ty <- goal
env <- get_env
let ty' = normalise (tt_ctxt ist) env ty
addLam ty' t
where
-- just one level at a time
addLam (Bind n (Pi (Just _) _ _) sc) t =
do impn <- unique_hole n -- (sMN 0 "scoped_imp")
if e_isfn ina -- apply to an implicit immediately
then return (PApp emptyFC
(PLam emptyFC impn NoFC Placeholder t)
[pexp Placeholder])
else return (PLam emptyFC impn NoFC Placeholder t)
addLam _ t = return t
insertCoerce ina t@(PCase _ _ _) = return t
insertCoerce ina t | notImplicitable t = return t
insertCoerce ina t =
do ty <- goal
-- Check for possible coercions to get to the goal
-- and add them as 'alternatives'
env <- get_env
let ty' = normalise (tt_ctxt ist) env ty
let cs = getCoercionsTo ist ty'
let t' = case (t, cs) of
(PCoerced tm, _) -> tm
(_, []) -> t
(_, cs) -> PAlternative [] TryImplicit
(t : map (mkCoerce env t) cs)
return t'
where
mkCoerce env (PAlternative ms aty tms) n
= PAlternative ms aty (map (\t -> mkCoerce env t n) tms)
mkCoerce env t n = let fc = maybe (fileFC "Coercion") id (highestFC t) in
addImplBound ist (map fst env)
(PApp fc (PRef fc [] n) [pexp (PCoerced t)])
-- | Elaborate the arguments to a function
elabArgs :: IState -- ^ The current Idris state
-> ElabCtxt -- ^ (in an argument, guarded, in a type, in a qquote)
-> [Bool]
-> FC -- ^ Source location
-> Bool
-> Name -- ^ Name of the function being applied
-> [((Name, Name), Bool)] -- ^ (Argument Name, Hole Name, unmatchable)
-> Bool -- ^ under a 'force'
-> [PTerm] -- ^ argument
-> ElabD ()
elabArgs ist ina failed fc retry f [] force _ = return ()
elabArgs ist ina failed fc r f (((argName, holeName), unm):ns) force (t : args)
= do hs <- get_holes
if holeName `elem` hs then
do focus holeName
case t of
Placeholder -> do movelast holeName
elabArgs ist ina failed fc r f ns force args
_ -> elabArg t
else elabArgs ist ina failed fc r f ns force args
where elabArg t =
do -- solveAutos ist fn False
now_elaborating fc f argName
wrapErr f argName $ do
hs <- get_holes
tm <- get_term
-- No coercing under an explicit Force (or it can Force/Delay
-- recursively!)
let elab = if force then elab' else elabE
failed' <- -- trace (show (n, t, hs, tm)) $
-- traceWhen (not (null cs)) (show ty ++ "\n" ++ showImp True t) $
do focus holeName;
g <- goal
-- Can't pattern match on polymorphic goals
poly <- goal_polymorphic
ulog <- getUnifyLog
traceWhen ulog ("Elaborating argument " ++ show (argName, holeName, g)) $
elab (ina { e_nomatching = unm && poly }) (Just fc) t
return failed
done_elaborating_arg f argName
elabArgs ist ina failed fc r f ns force args
wrapErr f argName action =
do elabState <- get
while <- elaborating_app
let while' = map (\(x, y, z)-> (y, z)) while
(result, newState) <- case runStateT action elabState of
OK (res, newState) -> return (res, newState)
Error e -> do done_elaborating_arg f argName
lift (tfail (elaboratingArgErr while' e))
put newState
return result
elabArgs _ _ _ _ _ _ (((arg, hole), _) : _) _ [] =
fail $ "Can't elaborate these args: " ++ show arg ++ " " ++ show hole
addAutoBind :: Plicity -> Name -> ElabD ()
addAutoBind (Imp _ _ _ _ False) n
= updateAux (\est -> est { auto_binds = n : auto_binds est })
addAutoBind _ _ = return ()
testImplicitWarning :: FC -> Name -> Type -> ElabD ()
testImplicitWarning fc n goal
| implicitable n && emode == ETyDecl
= do env <- get_env
est <- getAux
when (n `elem` auto_binds est) $
tryUnify env (lookupTyName n (tt_ctxt ist))
| otherwise = return ()
where
tryUnify env [] = return ()
tryUnify env ((nm, ty) : ts)
= do inj <- get_inj
hs <- get_holes
case unify (tt_ctxt ist) env (ty, Nothing) (goal, Nothing)
inj hs [] [] of
OK _ ->
updateAux (\est -> est { implicit_warnings =
(fc, nm) : implicit_warnings est })
_ -> tryUnify env ts
-- For every alternative, look at the function at the head. Automatically resolve
-- any nested alternatives where that function is also at the head
pruneAlt :: [PTerm] -> [PTerm]
pruneAlt xs = map prune xs
where
prune (PApp fc1 (PRef fc2 hls f) as)
= PApp fc1 (PRef fc2 hls f) (fmap (fmap (choose f)) as)
prune t = t
choose f (PAlternative ms a as)
= let as' = fmap (choose f) as
fs = filter (headIs f) as' in
case fs of
[a] -> a
_ -> PAlternative ms a as'
choose f (PApp fc f' as) = PApp fc (choose f f') (fmap (fmap (choose f)) as)
choose f t = t
headIs f (PApp _ (PRef _ _ f') _) = f == f'
headIs f (PApp _ f' _) = headIs f f'
headIs f _ = True -- keep if it's not an application
-- Rule out alternatives that don't return the same type as the head of the goal
-- (If there are none left as a result, do nothing)
pruneByType :: Env -> Term -> -- head of the goal
Type -> -- goal
IState -> [PTerm] -> [PTerm]
-- if an alternative has a locally bound name at the head, take it
pruneByType env t goalty c as
| Just a <- locallyBound as = [a]
where
locallyBound [] = Nothing
locallyBound (t:ts)
| Just n <- getName t,
n `elem` map fst env = Just t
| otherwise = locallyBound ts
getName (PRef _ _ n) = Just n
getName (PApp _ (PRef _ _ (UN l)) [_, _, arg]) -- ignore Delays
| l == txt "Delay" = getName (getTm arg)
getName (PApp _ f _) = getName f
getName (PHidden t) = getName t
getName _ = Nothing
-- 'n' is the name at the head of the goal type
pruneByType env (P _ n _) goalty ist as
-- if the goal type is polymorphic, keep everything
| Nothing <- lookupTyExact n ctxt = as
-- if the goal type is a ?metavariable, keep everything
| Just _ <- lookup n (idris_metavars ist) = as
| otherwise
= let asV = filter (headIs True n) as
as' = filter (headIs False n) as in
case as' of
[] -> asV
_ -> as'
where
ctxt = tt_ctxt ist
-- Get the function at the head of the alternative and see if it's
-- a plausible match against the goal type. Keep if so. Also keep if
-- there is a possible coercion to the goal type.
headIs var f (PRef _ _ f') = typeHead var f f'
headIs var f (PApp _ (PRef _ _ (UN l)) [_, _, arg])
| l == txt "Delay" = headIs var f (getTm arg)
headIs var f (PApp _ (PRef _ _ f') _) = typeHead var f f'
headIs var f (PApp _ f' _) = headIs var f f'
headIs var f (PPi _ _ _ _ sc) = headIs var f sc
headIs var f (PHidden t) = headIs var f t
headIs var f t = True -- keep if it's not an application
typeHead var f f'
= -- trace ("Trying " ++ show f' ++ " for " ++ show n) $
case lookupTyExact f' ctxt of
Just ty -> case unApply (getRetTy ty) of
(P _ ctyn _, _) | isTConName ctyn ctxt && not (ctyn == f)
-> False
_ -> let ty' = normalise ctxt [] ty in
-- trace ("Trying " ++ show (getRetTy ty') ++ " for " ++ show goalty) $
case unApply (getRetTy ty') of
(V _, _) ->
isPlausible ist var env n ty
_ -> matching (getRetTy ty') goalty
|| isCoercion (getRetTy ty') goalty
-- May be useful to keep for debugging purposes for a bit:
-- let res = matching (getRetTy ty') goalty in
-- traceWhen (not res)
-- ("Rejecting " ++ show (getRetTy ty', goalty)) res
_ -> False
-- If the goal is a constructor, it must match the suggested function type
matching (P _ ctyn _) (P _ n' _)
| isTConName n' ctxt = ctyn == n'
| otherwise = True
-- Variables match anything
matching (V _) _ = True
matching _ (V _) = True
matching _ (P _ n _) = not (isTConName n ctxt)
matching (P _ n _) _ = not (isTConName n ctxt)
-- Binders are a plausible match, so keep them
matching (Bind n _ sc) _ = True
matching _ (Bind n _ sc) = True
-- If we hit a function name, it's a plausible match
matching (App _ (P _ f _) _) _ | not (isConName f ctxt) = True
matching _ (App _ (P _ f _) _) | not (isConName f ctxt) = True
-- Otherwise, match the rest of the structure
matching (App _ f a) (App _ f' a') = matching f f' && matching a a'
matching (TType _) (TType _) = True
matching (UType _) (UType _) = True
matching l r = l == r
-- Return whether there is a possible coercion between the return type
-- of an alternative and the goal type
isCoercion rty gty | (P _ r _, _) <- unApply rty
= not (null (getCoercionsBetween r gty))
isCoercion _ _ = False
getCoercionsBetween :: Name -> Type -> [Name]
getCoercionsBetween r goal
= let cs = getCoercionsTo ist goal in
findCoercions r cs
where findCoercions t [] = []
findCoercions t (n : ns) =
let ps = case lookupTy n (tt_ctxt ist) of
[ty'] -> let as = map snd (getArgTys (normalise (tt_ctxt ist) [] ty')) in
[n | any useR as]
_ -> [] in
ps ++ findCoercions t ns
useR ty =
case unApply (getRetTy ty) of
(P _ t _, _) -> t == r
_ -> False
pruneByType _ t _ _ as = as
-- Could the name feasibly be the return type?
-- If there is a type class constraint on the return type, and no instance
-- in the environment or globally for that name, then no
-- Otherwise, yes
-- (FIXME: This isn't complete, but I'm leaving it here and coming back
-- to it later - just returns 'var' for now. EB)
isPlausible :: IState -> Bool -> Env -> Name -> Type -> Bool
isPlausible ist var env n ty
= let (hvar, classes) = collectConstraints [] [] ty in
case hvar of
Nothing -> True
Just rth -> var -- trace (show (rth, classes)) var
where
collectConstraints :: [Name] -> [(Term, [Name])] -> Type ->
(Maybe Name, [(Term, [Name])])
collectConstraints env tcs (Bind n (Pi _ ty _) sc)
= let tcs' = case unApply ty of
(P _ c _, _) ->
case lookupCtxtExact c (idris_classes ist) of
Just tc -> ((ty, map fst (class_instances tc))
: tcs)
Nothing -> tcs
_ -> tcs
in
collectConstraints (n : env) tcs' sc
collectConstraints env tcs t
| (V i, _) <- unApply t = (Just (env !! i), tcs)
| otherwise = (Nothing, tcs)
-- | Use the local elab context to work out the highlighting for a name
findHighlight :: Name -> ElabD OutputAnnotation
findHighlight n = do ctxt <- get_context
env <- get_env
case lookup n env of
Just _ -> return $ AnnBoundName n False
Nothing -> case lookupTyExact n ctxt of
Just _ -> return $ AnnName n Nothing Nothing Nothing
Nothing -> lift . tfail . InternalMsg $
"Can't find name " ++ show n
-- Try again to solve auto implicits
solveAuto :: IState -> Name -> Bool -> (Name, [FailContext]) -> ElabD ()
solveAuto ist fn ambigok (n, failc)
= do hs <- get_holes
when (not (null hs)) $ do
env <- get_env
g <- goal
handleError cantsolve (when (n `elem` hs) $ do
focus n
isg <- is_guess -- if it's a guess, we're working on it recursively, so stop
when (not isg) $
proofSearch' ist True ambigok 100 True Nothing fn [] [])
(lift $ Error (addLoc failc
(CantSolveGoal g (map (\(n, b) -> (n, binderTy b)) env))))
return ()
where addLoc (FailContext fc f x : prev) err
= At fc (ElaboratingArg f x
(map (\(FailContext _ f' x') -> (f', x')) prev) err)
addLoc _ err = err
cantsolve (CantSolveGoal _ _) = True
cantsolve (InternalMsg _) = True
cantsolve (At _ e) = cantsolve e
cantsolve (Elaborating _ _ _ e) = cantsolve e
cantsolve (ElaboratingArg _ _ _ e) = cantsolve e
cantsolve _ = False
solveAutos :: IState -> Name -> Bool -> ElabD ()
solveAutos ist fn ambigok
= do autos <- get_autos
mapM_ (solveAuto ist fn ambigok) (map (\(n, (fc, _)) -> (n, fc)) autos)
-- Return true if the given error suggests a type class failure is
-- recoverable
tcRecoverable :: ElabMode -> Err -> Bool
tcRecoverable ERHS (CantResolve f g _) = f
tcRecoverable ETyDecl (CantResolve f g _) = f
tcRecoverable e (ElaboratingArg _ _ _ err) = tcRecoverable e err
tcRecoverable e (At _ err) = tcRecoverable e err
tcRecoverable _ _ = True
trivial' ist
= trivial (elab ist toplevel ERHS [] (sMN 0 "tac")) ist
trivialHoles' psn h ist
= trivialHoles psn h (elab ist toplevel ERHS [] (sMN 0 "tac")) ist
proofSearch' ist rec ambigok depth prv top n psns hints
= do unifyProblems
proofSearch rec prv ambigok (not prv) depth
(elab ist toplevel ERHS [] (sMN 0 "tac")) top n psns hints ist
resolveTC' di mv depth tm n ist
= resolveTC di mv depth tm n (elab ist toplevel ERHS [] (sMN 0 "tac")) ist
collectDeferred :: Maybe Name -> [Name] -> Context ->
Term -> State [(Name, (Int, Maybe Name, Type, [Name]))] Term
collectDeferred top casenames ctxt tm = cd [] tm
where
cd env (Bind n (GHole i psns t) app) =
do ds <- get
t' <- collectDeferred top casenames ctxt t
when (not (n `elem` map fst ds)) $ put (ds ++ [(n, (i, top, t', psns))])
cd env app
cd env (Bind n b t)
= do b' <- cdb b
t' <- cd ((n, b) : env) t
return (Bind n b' t')
where
cdb (Let t v) = liftM2 Let (cd env t) (cd env v)
cdb (Guess t v) = liftM2 Guess (cd env t) (cd env v)
cdb b = do ty' <- cd env (binderTy b)
return (b { binderTy = ty' })
cd env (App s f a) = liftM2 (App s) (cd env f)
(cd env a)
cd env t = return t
case_ :: Bool -> Bool -> IState -> Name -> PTerm -> ElabD ()
case_ ind autoSolve ist fn tm = do
attack
tyn <- getNameFrom (sMN 0 "ity")
claim tyn RType
valn <- getNameFrom (sMN 0 "ival")
claim valn (Var tyn)
letn <- getNameFrom (sMN 0 "irule")
letbind letn (Var tyn) (Var valn)
focus valn
elab ist toplevel ERHS [] (sMN 0 "tac") tm
env <- get_env
let (Just binding) = lookup letn env
let val = binderVal binding
if ind then induction (forget val)
else casetac (forget val)
when autoSolve solveAll
-- | Compute the appropriate name for a top-level metavariable
metavarName :: [String] -> Name -> Name
metavarName _ n@(NS _ _) = n
metavarName (ns@(_:_)) n = sNS n ns
metavarName _ n = n
runElabAction :: ElabInfo -> IState -> FC -> Env -> Term -> [String] -> ElabD Term
runElabAction info ist fc env tm ns = do tm' <- eval tm
runTacTm tm'
where
eval tm = do ctxt <- get_context
return $ normaliseAll ctxt env (finalise tm)
returnUnit = return $ P (DCon 0 0 False) unitCon (P (TCon 0 0) unitTy Erased)
patvars :: [(Name, Term)] -> Term -> ([(Name, Term)], Term)
patvars ns (Bind n (PVar t) sc) = patvars ((n, t) : ns) (instantiate (P Bound n t) sc)
patvars ns tm = (ns, tm)
pullVars :: (Term, Term) -> ([(Name, Term)], Term, Term)
pullVars (lhs, rhs) = (fst (patvars [] lhs), snd (patvars [] lhs), snd (patvars [] rhs)) -- TODO alpha-convert rhs
requireError :: Err -> ElabD a -> ElabD ()
requireError orErr elab =
do state <- get
case runStateT elab state of
OK (_, state') -> lift (tfail orErr)
Error e -> return ()
-- create a fake TT term for the LHS of an impossible case
fakeTT :: Raw -> Term
fakeTT (Var n) =
case lookupNameDef n (tt_ctxt ist) of
[(n', TyDecl nt _)] -> P nt n' Erased
_ -> P Ref n Erased
fakeTT (RBind n b body) = Bind n (fmap fakeTT b) (fakeTT body)
fakeTT (RApp f a) = App Complete (fakeTT f) (fakeTT a)
fakeTT RType = TType (UVar [] (-1))
fakeTT (RUType u) = UType u
fakeTT (RConstant c) = Constant c
defineFunction :: RFunDefn Raw -> ElabD ()
defineFunction (RDefineFun n clauses) =
do ctxt <- get_context
ty <- maybe (fail "no type decl") return $ lookupTyExact n ctxt
let info = CaseInfo True True False -- TODO document and figure out
clauses' <- forM clauses (\case
RMkFunClause lhs rhs ->
do (lhs', lty) <- lift $ check ctxt [] lhs
(rhs', rty) <- lift $ check ctxt [] rhs
lift $ converts ctxt [] lty rty
return $ Right (lhs', rhs')
RMkImpossibleClause lhs ->
do requireError (Msg "Not an impossible case") . lift $
check ctxt [] lhs
return $ Left (fakeTT lhs))
let clauses'' = map (\case Right c -> pullVars c
Left lhs -> let (ns, lhs') = patvars [] lhs
in (ns, lhs', Impossible))
clauses'
let clauses''' = map (\(ns, lhs, rhs) -> (map fst ns, lhs, rhs)) clauses''
ctxt'<- lift $
addCasedef n (const [])
info False (STerm Erased)
True False -- TODO what are these?
(map snd $ getArgTys ty) [] -- TODO inaccessible types
clauses'
clauses'''
clauses'''
clauses'''
clauses'''
ty
ctxt
set_context ctxt'
updateAux $ \e -> e { new_tyDecls = RClausesInstrs n clauses'' : new_tyDecls e}
return ()
checkClosed :: Raw -> Elab' aux (Term, Type)
checkClosed tm = do ctxt <- get_context
(val, ty) <- lift $ check ctxt [] tm
return $! (finalise val, finalise ty)
-- | Add another argument to a Pi
mkPi :: RFunArg -> Raw -> Raw
mkPi arg rTy = RBind (argName arg) (Pi Nothing (argTy arg) (RUType AllTypes)) rTy
mustBeType ctxt tm ty =
case normaliseAll ctxt [] (finalise ty) of
UType _ -> return ()
TType _ -> return ()
ty' -> lift . tfail . InternalMsg $
show tm ++ " is not a type: it's " ++ show ty'
mustNotBeDefined ctxt n =
case lookupDefExact n ctxt of
Just _ -> lift . tfail . InternalMsg $
show n ++ " is already defined."
Nothing -> return ()
-- | Prepare a constructor to be added to a datatype being defined here
prepareConstructor :: Name -> RConstructorDefn -> ElabD (Name, [PArg], Type)
prepareConstructor tyn (RConstructor cn args resTy) =
do ctxt <- get_context
-- ensure the constructor name is not qualified, and
-- construct a qualified one
notQualified cn
let qcn = qualify cn
-- ensure that the constructor name is not defined already
mustNotBeDefined ctxt qcn
-- construct the actual type for the constructor
let cty = foldr mkPi resTy args
(checkedTy, ctyTy) <- lift $ check ctxt [] cty
mustBeType ctxt checkedTy ctyTy
-- ensure that the constructor builds the right family
case unApply (getRetTy (normaliseAll ctxt [] (finalise checkedTy))) of
(P _ n _, _) | n == tyn -> return ()
t -> lift . tfail . Msg $ "The constructor " ++ show cn ++
" doesn't construct " ++ show tyn ++
" (return type is " ++ show t ++ ")"
-- add temporary type declaration for constructor (so it can
-- occur in later constructor types)
set_context (addTyDecl qcn (DCon 0 0 False) checkedTy ctxt)
-- Save the implicits for high-level Idris
let impls = map rFunArgToPArg args
return (qcn, impls, checkedTy)
where
notQualified (NS _ _) = lift . tfail . Msg $ "Constructor names may not be qualified"
notQualified _ = return ()
qualify n = case tyn of
(NS _ ns) -> NS n ns
_ -> n
getRetTy :: Type -> Type
getRetTy (Bind _ (Pi _ _ _) sc) = getRetTy sc
getRetTy ty = ty
elabScriptStuck :: Term -> ElabD a
elabScriptStuck x = lift . tfail $ ElabScriptStuck x
-- Should be dependent
tacTmArgs :: Int -> Term -> [Term] -> ElabD [Term]
tacTmArgs l t args | length args == l = return args
| otherwise = elabScriptStuck t -- Probably should be an argument size mismatch internal error
-- | Do a step in the reflected elaborator monad. The input is the
-- step, the output is the (reflected) term returned.
runTacTm :: Term -> ElabD Term
runTacTm tac@(unApply -> (P _ n _, args))
| n == tacN "Prim__Solve"
= do ~[] <- tacTmArgs 0 tac args -- patterns are irrefutable because `tacTmArgs` returns lists of exactly the size given to it as first argument
solve
returnUnit
| n == tacN "Prim__Goal"
= do ~[] <- tacTmArgs 0 tac args
hs <- get_holes
case hs of
(h : _) -> do t <- goal
fmap fst . checkClosed $
rawPair (Var (reflm "TTName"), Var (reflm "TT"))
(reflectName h, reflect t)
[] -> lift . tfail . Msg $
"Elaboration is complete. There are no goals."
| n == tacN "Prim__Holes"
= do ~[] <- tacTmArgs 0 tac args
hs <- get_holes
fmap fst . checkClosed $
mkList (Var $ reflm "TTName") (map reflectName hs)
| n == tacN "Prim__Guess"
= do ~[] <- tacTmArgs 0 tac args
g <- get_guess
fmap fst . checkClosed $ reflect g
| n == tacN "Prim__LookupTy"
= do ~[name] <- tacTmArgs 1 tac args
n' <- reifyTTName name
ctxt <- get_context
let getNameTypeAndType = \case Function ty _ -> (Ref, ty)
TyDecl nt ty -> (nt, ty)
Operator ty _ _ -> (Ref, ty)
CaseOp _ ty _ _ _ _ -> (Ref, ty)
-- Idris tuples nest to the right
reflectTriple (x, y, z) =
raw_apply (Var pairCon) [ Var (reflm "TTName")
, raw_apply (Var pairTy) [Var (reflm "NameType"), Var (reflm "TT")]
, x
, raw_apply (Var pairCon) [ Var (reflm "NameType"), Var (reflm "TT")
, y, z]]
let defs = [ reflectTriple (reflectName n, reflectNameType nt, reflect ty)
| (n, def) <- lookupNameDef n' ctxt
, let (nt, ty) = getNameTypeAndType def ]
fmap fst . checkClosed $
rawList (raw_apply (Var pairTy) [ Var (reflm "TTName")
, raw_apply (Var pairTy) [ Var (reflm "NameType")
, Var (reflm "TT")]])
defs
| n == tacN "Prim__LookupDatatype"
= do ~[name] <- tacTmArgs 1 tac args
n' <- reifyTTName name
datatypes <- get_datatypes
ctxt <- get_context
fmap fst . checkClosed $
rawList (Var (tacN "Datatype"))
(map reflectDatatype (buildDatatypes ist n'))
| n == tacN "Prim__LookupFunDefn"
= do ~[name] <- tacTmArgs 1 tac args
n' <- reifyTTName name
fmap fst . checkClosed $
rawList (RApp (Var $ tacN "FunDefn") (Var $ reflm "TT"))
(map reflectFunDefn (buildFunDefns ist n'))
| n == tacN "Prim__LookupArgs"
= do ~[name] <- tacTmArgs 1 tac args
n' <- reifyTTName name
let listTy = Var (sNS (sUN "List") ["List", "Prelude"])
listFunArg = RApp listTy (Var (tacN "FunArg"))
-- Idris tuples nest to the right
let reflectTriple (x, y, z) =
raw_apply (Var pairCon) [ Var (reflm "TTName")
, raw_apply (Var pairTy) [listFunArg, Var (reflm "Raw")]
, x
, raw_apply (Var pairCon) [listFunArg, Var (reflm "Raw")
, y, z]]
let out =
[ reflectTriple (reflectName fn, reflectList (Var (tacN "FunArg")) (map reflectArg args), reflectRaw res)
| (fn, pargs) <- lookupCtxtName n' (idris_implicits ist)
, (args, res) <- getArgs pargs . forget <$>
maybeToList (lookupTyExact fn (tt_ctxt ist))
]
fmap fst . checkClosed $
rawList (raw_apply (Var pairTy) [Var (reflm "TTName")
, raw_apply (Var pairTy) [ RApp listTy
(Var (tacN "FunArg"))
, Var (reflm "Raw")]])
out
| n == tacN "Prim__SourceLocation"
= do ~[] <- tacTmArgs 0 tac args
fmap fst . checkClosed $
reflectFC fc
| n == tacN "Prim__Namespace"
= do ~[] <- tacTmArgs 0 tac args
fmap fst . checkClosed $
rawList (RConstant StrType) (map (RConstant . Str) ns)
| n == tacN "Prim__Env"
= do ~[] <- tacTmArgs 0 tac args
env <- get_env
fmap fst . checkClosed $ reflectEnv env
| n == tacN "Prim__Fail"
= do ~[_a, errs] <- tacTmArgs 2 tac args
errs' <- eval errs
parts <- reifyReportParts errs'
lift . tfail $ ReflectionError [parts] (Msg "")
| n == tacN "Prim__PureElab"
= do ~[_a, tm] <- tacTmArgs 2 tac args
return tm
| n == tacN "Prim__BindElab"
= do ~[_a, _b, first, andThen] <- tacTmArgs 4 tac args
first' <- eval first
res <- eval =<< runTacTm first'
next <- eval (App Complete andThen res)
runTacTm next
| n == tacN "Prim__Try"
= do ~[_a, first, alt] <- tacTmArgs 3 tac args
first' <- eval first
alt' <- eval alt
try' (runTacTm first') (runTacTm alt') True
| n == tacN "Prim__Fill"
= do ~[raw] <- tacTmArgs 1 tac args
raw' <- reifyRaw =<< eval raw
apply raw' []
returnUnit
| n == tacN "Prim__Apply" || n == tacN "Prim__MatchApply"
= do ~[raw, argSpec] <- tacTmArgs 2 tac args
raw' <- reifyRaw =<< eval raw
argSpec' <- map (\b -> (b, 0)) <$> reifyList reifyBool argSpec
let op = if n == tacN "Prim__Apply"
then apply
else match_apply
ns <- op raw' argSpec'
fmap fst . checkClosed $
rawList (rawPairTy (Var $ reflm "TTName") (Var $ reflm "TTName"))
[ rawPair (Var $ reflm "TTName", Var $ reflm "TTName")
(reflectName n1, reflectName n2)
| (n1, n2) <- ns
]
| n == tacN "Prim__Gensym"
= do ~[hint] <- tacTmArgs 1 tac args
hintStr <- eval hint
case hintStr of
Constant (Str h) -> do
n <- getNameFrom (sMN 0 h)
fmap fst $ get_type_val (reflectName n)
_ -> fail "no hint"
| n == tacN "Prim__Claim"
= do ~[n, ty] <- tacTmArgs 2 tac args
n' <- reifyTTName n
ty' <- reifyRaw ty
claim n' ty'
returnUnit
| n == tacN "Prim__Check"
= do ~[env', raw] <- tacTmArgs 2 tac args
env <- reifyEnv env'
raw' <- reifyRaw =<< eval raw
ctxt <- get_context
(tm, ty) <- lift $ check ctxt env raw'
fmap fst . checkClosed $
rawPair (Var (reflm "TT"), Var (reflm "TT"))
(reflect tm, reflect ty)
| n == tacN "Prim__Attack"
= do ~[] <- tacTmArgs 0 tac args
attack
returnUnit
| n == tacN "Prim__Rewrite"
= do ~[rule] <- tacTmArgs 1 tac args
r <- reifyRaw rule
rewrite r
returnUnit
| n == tacN "Prim__Focus"
= do ~[what] <- tacTmArgs 1 tac args
n' <- reifyTTName what
hs <- get_holes
if elem n' hs
then focus n' >> returnUnit
else lift . tfail . Msg $ "The name " ++ show n' ++ " does not denote a hole"
| n == tacN "Prim__Unfocus"
= do ~[what] <- tacTmArgs 1 tac args
n' <- reifyTTName what
movelast n'
returnUnit
| n == tacN "Prim__Intro"
= do ~[mn] <- tacTmArgs 1 tac args
n <- case fromTTMaybe mn of
Nothing -> return Nothing
Just name -> fmap Just $ reifyTTName name
intro n
returnUnit
| n == tacN "Prim__Forall"
= do ~[n, ty] <- tacTmArgs 2 tac args
n' <- reifyTTName n
ty' <- reifyRaw ty
forall n' Nothing ty'
returnUnit
| n == tacN "Prim__PatVar"
= do ~[n] <- tacTmArgs 1 tac args
n' <- reifyTTName n
patvar' n'
returnUnit
| n == tacN "Prim__PatBind"
= do ~[n] <- tacTmArgs 1 tac args
n' <- reifyTTName n
patbind n'
returnUnit
| n == tacN "Prim__LetBind"
= do ~[n, ty, tm] <- tacTmArgs 3 tac args
n' <- reifyTTName n
ty' <- reifyRaw ty
tm' <- reifyRaw tm
letbind n' ty' tm'
returnUnit
| n == tacN "Prim__Compute"
= do ~[] <- tacTmArgs 0 tac args; compute ; returnUnit
| n == tacN "Prim__Normalise"
= do ~[env, tm] <- tacTmArgs 2 tac args
env' <- reifyEnv env
tm' <- reifyTT tm
ctxt <- get_context
let out = normaliseAll ctxt env' (finalise tm')
fmap fst . checkClosed $ reflect out
| n == tacN "Prim__Whnf"
= do ~[tm] <- tacTmArgs 1 tac args
tm' <- reifyTT tm
ctxt <- get_context
fmap fst . checkClosed . reflect $ whnf ctxt tm'
| n == tacN "Prim__Converts"
= do ~[env, tm1, tm2] <- tacTmArgs 3 tac args
env' <- reifyEnv env
tm1' <- reifyTT tm1
tm2' <- reifyTT tm2
ctxt <- get_context
lift $ converts ctxt env' tm1' tm2'
returnUnit
| n == tacN "Prim__DeclareType"
= do ~[decl] <- tacTmArgs 1 tac args
(RDeclare n args res) <- reifyTyDecl decl
ctxt <- get_context
let rty = foldr mkPi res args
(checked, ty') <- lift $ check ctxt [] rty
mustBeType ctxt checked ty'
mustNotBeDefined ctxt n
let decl = TyDecl Ref checked
ctxt' = addCtxtDef n decl ctxt
set_context ctxt'
updateAux $ \e -> e { new_tyDecls = (RTyDeclInstrs n fc (map rFunArgToPArg args) checked) :
new_tyDecls e }
returnUnit
| n == tacN "Prim__DefineFunction"
= do ~[decl] <- tacTmArgs 1 tac args
defn <- reifyFunDefn decl
defineFunction defn
returnUnit
| n == tacN "Prim__DeclareDatatype"
= do ~[decl] <- tacTmArgs 1 tac args
RDeclare n args resTy <- reifyTyDecl decl
ctxt <- get_context
let tcTy = foldr mkPi resTy args
(checked, ty') <- lift $ check ctxt [] tcTy
mustBeType ctxt checked ty'
mustNotBeDefined ctxt n
let ctxt' = addTyDecl n (TCon 0 0) checked ctxt
set_context ctxt'
updateAux $ \e -> e { new_tyDecls = RDatatypeDeclInstrs n (map rFunArgToPArg args) : new_tyDecls e }
returnUnit
| n == tacN "Prim__DefineDatatype"
= do ~[defn] <- tacTmArgs 1 tac args
RDefineDatatype n ctors <- reifyRDataDefn defn
ctxt <- get_context
tyconTy <- case lookupTyExact n ctxt of
Just t -> return t
Nothing -> lift . tfail . Msg $ "Type not previously declared"
datatypes <- get_datatypes
case lookupCtxtName n datatypes of
[] -> return ()
_ -> lift . tfail . Msg $ show n ++ " is already defined as a datatype."
-- Prepare the constructors
ctors' <- mapM (prepareConstructor n) ctors
ttag <- do ES (ps, aux) str prev <- get
let i = global_nextname ps
put $ ES (ps { global_nextname = global_nextname ps + 1 },
aux)
str
prev
return i
let ctxt' = addDatatype (Data n ttag tyconTy False (map (\(cn, _, cty) -> (cn, cty)) ctors')) ctxt
set_context ctxt'
-- the rest happens in a bit
updateAux $ \e -> e { new_tyDecls = RDatatypeDefnInstrs n tyconTy ctors' : new_tyDecls e }
returnUnit
| n == tacN "Prim__AddInstance"
= do ~[cls, inst] <- tacTmArgs 2 tac args
className <- reifyTTName cls
instName <- reifyTTName inst
updateAux $ \e -> e { new_tyDecls = RAddInstance className instName :
new_tyDecls e }
returnUnit
| n == tacN "Prim__IsTCName"
= do ~[n] <- tacTmArgs 1 tac args
n' <- reifyTTName n
case lookupCtxtExact n' (idris_classes ist) of
Just _ -> fmap fst . checkClosed $ Var (sNS (sUN "True") ["Bool", "Prelude"])
Nothing -> fmap fst . checkClosed $ Var (sNS (sUN "False") ["Bool", "Prelude"])
| n == tacN "Prim__ResolveTC"
= do ~[fn] <- tacTmArgs 1 tac args
g <- goal
fn <- reifyTTName fn
resolveTC' False True 100 g fn ist
returnUnit
| n == tacN "Prim__Search"
= do ~[depth, hints] <- tacTmArgs 2 tac args
d <- eval depth
hints' <- eval hints
case (d, unList hints') of
(Constant (I i), Just hs) ->
do actualHints <- mapM reifyTTName hs
unifyProblems
let psElab = elab ist toplevel ERHS [] (sMN 0 "tac")
proofSearch True True False False i psElab Nothing (sMN 0 "search ") [] actualHints ist
returnUnit
(Constant (I _), Nothing ) ->
lift . tfail . InternalMsg $ "Not a list: " ++ show hints'
(_, _) -> lift . tfail . InternalMsg $ "Can't reify int " ++ show d
| n == tacN "Prim__RecursiveElab"
= do ~[goal, script] <- tacTmArgs 2 tac args
goal' <- reifyRaw goal
ctxt <- get_context
script <- eval script
(goalTT, goalTy) <- lift $ check ctxt [] goal'
lift $ isType ctxt [] goalTy
recH <- getNameFrom (sMN 0 "recElabHole")
aux <- getAux
datatypes <- get_datatypes
env <- get_env
g_next <- get_global_nextname
(ctxt', ES (p, aux') _ _) <-
do (ES (current_p, _) _ _) <- get
lift $ runElab aux
(do runElabAction info ist fc [] script ns
ctxt' <- get_context
return ctxt')
((newProof recH (constraintNS info) ctxt datatypes g_next goalTT)
{ nextname = nextname current_p })
set_context ctxt'
let tm_out = getProofTerm (pterm p)
do (ES (prf, _) s e) <- get
let p' = prf { nextname = nextname p
, global_nextname = global_nextname p
}
put (ES (p', aux') s e)
env' <- get_env
(tm, ty, _) <- lift $ recheck (constraintNS info) ctxt' env (forget tm_out) tm_out
let (tm', ty') = (reflect tm, reflect ty)
fmap fst . checkClosed $
rawPair (Var $ reflm "TT", Var $ reflm "TT")
(tm', ty')
| n == tacN "Prim__Metavar"
= do ~[n] <- tacTmArgs 1 tac args
n' <- reifyTTName n
ctxt <- get_context
ptm <- get_term
-- See documentation above in the elab case for PMetavar
let unique_used = getUniqueUsed ctxt ptm
let mvn = metavarName ns n'
attack
defer unique_used mvn
solve
returnUnit
| n == tacN "Prim__Fixity"
= do ~[op'] <- tacTmArgs 1 tac args
opTm <- eval op'
case opTm of
Constant (Str op) ->
let opChars = ":!#$%&*+./<=>?@\\^|-~"
invalidOperators = [":", "=>", "->", "<-", "=", "?=", "|", "**", "==>", "\\", "%", "~", "?", "!"]
fixities = idris_infixes ist
in if not (all (flip elem opChars) op) || elem op invalidOperators
then lift . tfail . Msg $ "'" ++ op ++ "' is not a valid operator name."
else case nub [f | Fix f someOp <- fixities, someOp == op] of
[] -> lift . tfail . Msg $ "No fixity found for operator '" ++ op ++ "'."
[f] -> fmap fst . checkClosed $ reflectFixity f
many -> lift . tfail . InternalMsg $ "Ambiguous fixity for '" ++ op ++ "'! Found " ++ show many
_ -> lift . tfail . Msg $ "Not a constant string for an operator name: " ++ show opTm
| n == tacN "Prim__Debug"
= do ~[ty, msg] <- tacTmArgs 2 tac args
msg' <- eval msg
parts <- reifyReportParts msg
debugElaborator parts
runTacTm x = elabScriptStuck x
-- Running tactics directly
-- if a tactic adds unification problems, return an error
runTac :: Bool -> IState -> Maybe FC -> Name -> PTactic -> ElabD ()
runTac autoSolve ist perhapsFC fn tac
= do env <- get_env
g <- goal
let tac' = fmap (addImplBound ist (map fst env)) tac
if autoSolve
then runT tac'
else no_errors (runT tac')
(Just (CantSolveGoal g (map (\(n, b) -> (n, binderTy b)) env)))
where
runT (Intro []) = do g <- goal
attack; intro (bname g)
where
bname (Bind n _ _) = Just n
bname _ = Nothing
runT (Intro xs) = mapM_ (\x -> do attack; intro (Just x)) xs
runT Intros = do g <- goal
attack;
intro (bname g)
try' (runT Intros)
(return ()) True
where
bname (Bind n _ _) = Just n
bname _ = Nothing
runT (Exact tm) = do elab ist toplevel ERHS [] (sMN 0 "tac") tm
when autoSolve solveAll
runT (MatchRefine fn)
= do fnimps <-
case lookupCtxtName fn (idris_implicits ist) of
[] -> do a <- envArgs fn
return [(fn, a)]
ns -> return (map (\ (n, a) -> (n, map (const True) a)) ns)
let tacs = map (\ (fn', imps) ->
(match_apply (Var fn') (map (\x -> (x, 0)) imps),
fn')) fnimps
tryAll tacs
when autoSolve solveAll
where envArgs n = do e <- get_env
case lookup n e of
Just t -> return $ map (const False)
(getArgTys (binderTy t))
_ -> return []
runT (Refine fn [])
= do fnimps <-
case lookupCtxtName fn (idris_implicits ist) of
[] -> do a <- envArgs fn
return [(fn, a)]
ns -> return (map (\ (n, a) -> (n, map isImp a)) ns)
let tacs = map (\ (fn', imps) ->
(apply (Var fn') (map (\x -> (x, 0)) imps),
fn')) fnimps
tryAll tacs
when autoSolve solveAll
where isImp (PImp _ _ _ _ _) = True
isImp _ = False
envArgs n = do e <- get_env
case lookup n e of
Just t -> return $ map (const False)
(getArgTys (binderTy t))
_ -> return []
runT (Refine fn imps) = do ns <- apply (Var fn) (map (\x -> (x,0)) imps)
when autoSolve solveAll
runT DoUnify = do unify_all
when autoSolve solveAll
runT (Claim n tm) = do tmHole <- getNameFrom (sMN 0 "newGoal")
claim tmHole RType
claim n (Var tmHole)
focus tmHole
elab ist toplevel ERHS [] (sMN 0 "tac") tm
focus n
runT (Equiv tm) -- let bind tm, then
= do attack
tyn <- getNameFrom (sMN 0 "ety")
claim tyn RType
valn <- getNameFrom (sMN 0 "eqval")
claim valn (Var tyn)
letn <- getNameFrom (sMN 0 "equiv_val")
letbind letn (Var tyn) (Var valn)
focus tyn
elab ist toplevel ERHS [] (sMN 0 "tac") tm
focus valn
when autoSolve solveAll
runT (Rewrite tm) -- to elaborate tm, let bind it, then rewrite by that
= do attack; -- (h:_) <- get_holes
tyn <- getNameFrom (sMN 0 "rty")
-- start_unify h
claim tyn RType
valn <- getNameFrom (sMN 0 "rval")
claim valn (Var tyn)
letn <- getNameFrom (sMN 0 "rewrite_rule")
letbind letn (Var tyn) (Var valn)
focus valn
elab ist toplevel ERHS [] (sMN 0 "tac") tm
rewrite (Var letn)
when autoSolve solveAll
runT (Induction tm) -- let bind tm, similar to the others
= case_ True autoSolve ist fn tm
runT (CaseTac tm)
= case_ False autoSolve ist fn tm
runT (LetTac n tm)
= do attack
tyn <- getNameFrom (sMN 0 "letty")
claim tyn RType
valn <- getNameFrom (sMN 0 "letval")
claim valn (Var tyn)
letn <- unique_hole n
letbind letn (Var tyn) (Var valn)
focus valn
elab ist toplevel ERHS [] (sMN 0 "tac") tm
when autoSolve solveAll
runT (LetTacTy n ty tm)
= do attack
tyn <- getNameFrom (sMN 0 "letty")
claim tyn RType
valn <- getNameFrom (sMN 0 "letval")
claim valn (Var tyn)
letn <- unique_hole n
letbind letn (Var tyn) (Var valn)
focus tyn
elab ist toplevel ERHS [] (sMN 0 "tac") ty
focus valn
elab ist toplevel ERHS [] (sMN 0 "tac") tm
when autoSolve solveAll
runT Compute = compute
runT Trivial = do trivial' ist; when autoSolve solveAll
runT TCInstance = runT (Exact (PResolveTC emptyFC))
runT (ProofSearch rec prover depth top psns hints)
= do proofSearch' ist rec False depth prover top fn psns hints
when autoSolve solveAll
runT (Focus n) = focus n
runT Unfocus = do hs <- get_holes
case hs of
[] -> return ()
(h : _) -> movelast h
runT Solve = solve
runT (Try l r) = do try' (runT l) (runT r) True
runT (TSeq l r) = do runT l; runT r
runT (ApplyTactic tm) = do tenv <- get_env -- store the environment
tgoal <- goal -- store the goal
attack -- let f : List (TTName, Binder TT) -> TT -> Tactic = tm in ...
script <- getNameFrom (sMN 0 "script")
claim script scriptTy
scriptvar <- getNameFrom (sMN 0 "scriptvar" )
letbind scriptvar scriptTy (Var script)
focus script
elab ist toplevel ERHS [] (sMN 0 "tac") tm
(script', _) <- get_type_val (Var scriptvar)
-- now that we have the script apply
-- it to the reflected goal and context
restac <- getNameFrom (sMN 0 "restac")
claim restac tacticTy
focus restac
fill (raw_apply (forget script')
[reflectEnv tenv, reflect tgoal])
restac' <- get_guess
solve
-- normalise the result in order to
-- reify it
ctxt <- get_context
env <- get_env
let tactic = normalise ctxt env restac'
runReflected tactic
where tacticTy = Var (reflm "Tactic")
listTy = Var (sNS (sUN "List") ["List", "Prelude"])
scriptTy = (RBind (sMN 0 "__pi_arg")
(Pi Nothing (RApp listTy envTupleType) RType)
(RBind (sMN 1 "__pi_arg")
(Pi Nothing (Var $ reflm "TT") RType) tacticTy))
runT (ByReflection tm) -- run the reflection function 'tm' on the
-- goal, then apply the resulting reflected Tactic
= do tgoal <- goal
attack
script <- getNameFrom (sMN 0 "script")
claim script scriptTy
scriptvar <- getNameFrom (sMN 0 "scriptvar" )
letbind scriptvar scriptTy (Var script)
focus script
ptm <- get_term
elab ist toplevel ERHS [] (sMN 0 "tac")
(PApp emptyFC tm [pexp (delabTy' ist [] tgoal True True)])
(script', _) <- get_type_val (Var scriptvar)
-- now that we have the script apply
-- it to the reflected goal
restac <- getNameFrom (sMN 0 "restac")
claim restac tacticTy
focus restac
fill (forget script')
restac' <- get_guess
solve
-- normalise the result in order to
-- reify it
ctxt <- get_context
env <- get_env
let tactic = normalise ctxt env restac'
runReflected tactic
where tacticTy = Var (reflm "Tactic")
scriptTy = tacticTy
runT (Reflect v) = do attack -- let x = reflect v in ...
tyn <- getNameFrom (sMN 0 "letty")
claim tyn RType
valn <- getNameFrom (sMN 0 "letval")
claim valn (Var tyn)
letn <- getNameFrom (sMN 0 "letvar")
letbind letn (Var tyn) (Var valn)
focus valn
elab ist toplevel ERHS [] (sMN 0 "tac") v
(value, _) <- get_type_val (Var letn)
ctxt <- get_context
env <- get_env
let value' = hnf ctxt env value
runTac autoSolve ist perhapsFC fn (Exact $ PQuote (reflect value'))
runT (Fill v) = do attack -- let x = fill x in ...
tyn <- getNameFrom (sMN 0 "letty")
claim tyn RType
valn <- getNameFrom (sMN 0 "letval")
claim valn (Var tyn)
letn <- getNameFrom (sMN 0 "letvar")
letbind letn (Var tyn) (Var valn)
focus valn
elab ist toplevel ERHS [] (sMN 0 "tac") v
(value, _) <- get_type_val (Var letn)
ctxt <- get_context
env <- get_env
let value' = normalise ctxt env value
rawValue <- reifyRaw value'
runTac autoSolve ist perhapsFC fn (Exact $ PQuote rawValue)
runT (GoalType n tac) = do g <- goal
case unApply g of
(P _ n' _, _) ->
if nsroot n' == sUN n
then runT tac
else fail "Wrong goal type"
_ -> fail "Wrong goal type"
runT ProofState = do g <- goal
return ()
runT Skip = return ()
runT (TFail err) = lift . tfail $ ReflectionError [err] (Msg "")
runT SourceFC =
case perhapsFC of
Nothing -> lift . tfail $ Msg "There is no source location available."
Just fc ->
do fill $ reflectFC fc
solve
runT Qed = lift . tfail $ Msg "The qed command is only valid in the interactive prover"
runT x = fail $ "Not implemented " ++ show x
runReflected t = do t' <- reify ist t
runTac autoSolve ist perhapsFC fn t'
elaboratingArgErr :: [(Name, Name)] -> Err -> Err
elaboratingArgErr [] err = err
elaboratingArgErr ((f,x):during) err = fromMaybe err (rewrite err)
where rewrite (ElaboratingArg _ _ _ _) = Nothing
rewrite (ProofSearchFail e) = fmap ProofSearchFail (rewrite e)
rewrite (At fc e) = fmap (At fc) (rewrite e)
rewrite err = Just (ElaboratingArg f x during err)
withErrorReflection :: Idris a -> Idris a
withErrorReflection x = idrisCatch x (\ e -> handle e >>= ierror)
where handle :: Err -> Idris Err
handle e@(ReflectionError _ _) = do logElab 3 "Skipping reflection of error reflection result"
return e -- Don't do meta-reflection of errors
handle e@(ReflectionFailed _ _) = do logElab 3 "Skipping reflection of reflection failure"
return e
-- At and Elaborating are just plumbing - error reflection shouldn't rewrite them
handle e@(At fc err) = do logElab 3 "Reflecting body of At"
err' <- handle err
return (At fc err')
handle e@(Elaborating what n ty err) = do logElab 3 "Reflecting body of Elaborating"
err' <- handle err
return (Elaborating what n ty err')
handle e@(ElaboratingArg f a prev err) = do logElab 3 "Reflecting body of ElaboratingArg"
hs <- getFnHandlers f a
err' <- if null hs
then handle err
else applyHandlers err hs
return (ElaboratingArg f a prev err')
-- ProofSearchFail is an internal detail - so don't expose it
handle (ProofSearchFail e) = handle e
-- TODO: argument-specific error handlers go here for ElaboratingArg
handle e = do ist <- getIState
logElab 2 "Starting error reflection"
logElab 5 (show e)
let handlers = idris_errorhandlers ist
applyHandlers e handlers
getFnHandlers :: Name -> Name -> Idris [Name]
getFnHandlers f arg = do ist <- getIState
let funHandlers = maybe M.empty id .
lookupCtxtExact f .
idris_function_errorhandlers $ ist
return . maybe [] S.toList . M.lookup arg $ funHandlers
applyHandlers e handlers =
do ist <- getIState
let err = fmap (errReverse ist) e
logElab 3 $ "Using reflection handlers " ++
concat (intersperse ", " (map show handlers))
let reports = map (\n -> RApp (Var n) (reflectErr err)) handlers
-- Typecheck error handlers - if this fails, then something else was wrong earlier!
handlers <- case mapM (check (tt_ctxt ist) []) reports of
Error e -> ierror $ ReflectionFailed "Type error while constructing reflected error" e
OK hs -> return hs
-- Normalize error handler terms to produce the new messages
-- Need to use 'normaliseAll' since we have to reduce private
-- names in error handlers too
ctxt <- getContext
let results = map (normaliseAll ctxt []) (map fst handlers)
logElab 3 $ "New error message info: " ++ concat (intersperse " and " (map show results))
-- For each handler term output, either discard it if it is Nothing or reify it the Haskell equivalent
let errorpartsTT = mapMaybe unList (mapMaybe fromTTMaybe results)
errorparts <- case mapM (mapM reifyReportPart) errorpartsTT of
Left err -> ierror err
Right ok -> return ok
return $ case errorparts of
[] -> e
parts -> ReflectionError errorparts e
solveAll = try (do solve; solveAll) (return ())
-- | Do the left-over work after creating declarations in reflected
-- elaborator scripts
processTacticDecls :: ElabInfo -> [RDeclInstructions] -> Idris ()
processTacticDecls info steps =
-- The order of steps is important: type declarations might
-- establish metavars that later function bodies resolve.
forM_ (reverse steps) $ \case
RTyDeclInstrs n fc impls ty ->
do logElab 3 $ "Declaration from tactics: " ++ show n ++ " : " ++ show ty
logElab 3 $ " It has impls " ++ show impls
updateIState $ \i -> i { idris_implicits =
addDef n impls (idris_implicits i) }
addIBC (IBCImp n)
ds <- checkDef info fc (\_ e -> e) True [(n, (-1, Nothing, ty, []))]
addIBC (IBCDef n)
ctxt <- getContext
case lookupDef n ctxt of
(TyDecl _ _ : _) ->
-- If the function isn't defined at the end of the elab script,
-- then it must be added as a metavariable. This needs guarding
-- to prevent overwriting case defs with a metavar, if the case
-- defs come after the type decl in the same script!
let ds' = map (\(n, (i, top, t, ns)) -> (n, (i, top, t, ns, True, True))) ds
in addDeferred ds'
_ -> return ()
RDatatypeDeclInstrs n impls ->
do addIBC (IBCDef n)
updateIState $ \i -> i { idris_implicits = addDef n impls (idris_implicits i) }
addIBC (IBCImp n)
RDatatypeDefnInstrs tyn tyconTy ctors ->
do let cn (n, _, _) = n
cimpls (_, impls, _) = impls
cty (_, _, t) = t
addIBC (IBCDef tyn)
mapM_ (addIBC . IBCDef . cn) ctors
ctxt <- getContext
let params = findParams tyn (normalise ctxt [] tyconTy) (map cty ctors)
let typeInfo = TI (map cn ctors) False [] params []
-- implicit precondition to IBCData is that idris_datatypes on the IState is populated.
-- otherwise writing the IBC just fails silently!
updateIState $ \i -> i { idris_datatypes =
addDef tyn typeInfo (idris_datatypes i) }
addIBC (IBCData tyn)
ttag <- getName -- from AbsSyntax.hs, really returns a disambiguating Int
let metainf = DataMI params
addIBC (IBCMetaInformation tyn metainf)
updateContext (setMetaInformation tyn metainf)
for_ ctors $ \(cn, impls, _) ->
do updateIState $ \i -> i { idris_implicits = addDef cn impls (idris_implicits i) }
addIBC (IBCImp cn)
for_ ctors $ \(ctorN, _, _) ->
do totcheck (NoFC, ctorN)
ctxt <- tt_ctxt <$> getIState
case lookupTyExact ctorN ctxt of
Just cty -> do checkPositive (tyn : map cn ctors) (ctorN, cty)
return ()
Nothing -> return ()
case ctors of
[ctor] -> do setDetaggable (cn ctor); setDetaggable tyn
addIBC (IBCOpt (cn ctor)); addIBC (IBCOpt tyn)
_ -> return ()
-- TODO: inaccessible
RAddInstance className instName ->
do -- The type class resolution machinery relies on a special
logElab 2 $ "Adding elab script instance " ++ show instName ++
" for " ++ show className
addInstance False True className instName
addIBC (IBCInstance False True className instName)
RClausesInstrs n cs ->
do logElab 3 $ "Pattern-matching definition from tactics: " ++ show n
solveDeferred emptyFC n
let lhss = map (\(_, lhs, _) -> lhs) cs
let fc = fileFC "elab_reflected"
pmissing <-
do ist <- getIState
possible <- genClauses fc n lhss
(map (\lhs ->
delab' ist lhs True True) lhss)
missing <- filterM (checkPossible n) possible
return (filter (noMatch ist lhss) missing)
let tot = if null pmissing
then Unchecked -- still need to check recursive calls
else Partial NotCovering -- missing cases implies not total
setTotality n tot
updateIState $ \i -> i { idris_patdefs =
addDef n (cs, pmissing) $ idris_patdefs i }
addIBC (IBCDef n)
ctxt <- getContext
case lookupDefExact n ctxt of
Just (CaseOp _ _ _ _ _ cd) ->
-- Here, we populate the call graph with a list of things
-- we refer to, so that if they aren't total, the whole
-- thing won't be.
let (scargs, sc) = cases_compiletime cd
calls = map fst $ findCalls sc scargs
in do logElab 2 $ "Called names in reflected elab: " ++ show calls
addCalls n calls
addIBC $ IBCCG n
Just _ -> return () -- TODO throw internal error
Nothing -> return ()
-- checkDeclTotality requires that the call graph be present
-- before calling it.
-- TODO: reduce code duplication with Idris.Elab.Clause
buildSCG (fc, n)
-- Actually run the totality checker. In the main clause
-- elaborator, this is deferred until after. Here, we run it
-- now to get totality information as early as possible.
tot' <- checkDeclTotality (fc, n)
setTotality n tot'
when (tot' /= Unchecked) $ addIBC (IBCTotal n tot')
where
-- TODO: see if the code duplication with Idris.Elab.Clause can be
-- reduced or eliminated.
checkPossible :: Name -> PTerm -> Idris Bool
checkPossible fname lhs_in =
do ctxt <- getContext
ist <- getIState
let lhs = addImplPat ist lhs_in
let fc = fileFC "elab_reflected_totality"
let tcgen = False -- TODO: later we may support dictionary generation
case elaborate (constraintNS info) ctxt (idris_datatypes ist) (idris_name ist) (sMN 0 "refPatLHS") infP initEState
(erun fc (buildTC ist info ELHS [] fname (allNamesIn lhs_in)
(infTerm lhs))) of
OK (ElabResult lhs' _ _ _ _ _ name', _) ->
do -- not recursively calling here, because we don't
-- want to run infinitely many times
let lhs_tm = orderPats (getInferTerm lhs')
updateIState $ \i -> i { idris_name = name' }
case recheck (constraintNS info) ctxt [] (forget lhs_tm) lhs_tm of
OK _ -> return True
err -> return False
-- if it's a recoverable error, the case may become possible
Error err -> if tcgen then return (recoverableCoverage ctxt err)
else return (validCoverageCase ctxt err ||
recoverableCoverage ctxt err)
-- TODO: Attempt to reduce/eliminate code duplication with Idris.Elab.Clause
noMatch i cs tm = all (\x -> case matchClause i (delab' i x True True) tm of
Right _ -> False
Left _ -> True) cs
| KaneTW/Idris-dev | src/Idris/Elab/Term.hs | bsd-3-clause | 132,339 | 1,239 | 18 | 57,320 | 15,601 | 12,008 | 3,593 | 2,350 | 239 |
{-# language CPP #-}
-- No documentation found for Chapter "ExternalMemoryFeatureFlagBits"
module Vulkan.Core11.Enums.ExternalMemoryFeatureFlagBits ( ExternalMemoryFeatureFlags
, ExternalMemoryFeatureFlagBits( EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT
, EXTERNAL_MEMORY_FEATURE_EXPORTABLE_BIT
, EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT
, ..
)
) where
import Vulkan.Internal.Utils (enumReadPrec)
import Vulkan.Internal.Utils (enumShowsPrec)
import GHC.Show (showString)
import Numeric (showHex)
import Vulkan.Zero (Zero)
import Data.Bits (Bits)
import Data.Bits (FiniteBits)
import Foreign.Storable (Storable)
import GHC.Read (Read(readPrec))
import GHC.Show (Show(showsPrec))
import Vulkan.Core10.FundamentalTypes (Flags)
type ExternalMemoryFeatureFlags = ExternalMemoryFeatureFlagBits
-- | VkExternalMemoryFeatureFlagBits - Bitmask specifying features of an
-- external memory handle type
--
-- = Description
--
-- Because their semantics in external APIs roughly align with that of an
-- image or buffer with a dedicated allocation in Vulkan, implementations
-- are /required/ to report 'EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT'
-- for the following external handle types:
--
-- Implementations /must/ not report
-- 'EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT' for buffers with external
-- handle type
-- 'Vulkan.Core11.Enums.ExternalMemoryHandleTypeFlagBits.EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID'.
-- Implementations /must/ not report
-- 'EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT' for images or buffers with
-- external handle type
-- 'Vulkan.Core11.Enums.ExternalMemoryHandleTypeFlagBits.EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT',
-- or
-- 'Vulkan.Core11.Enums.ExternalMemoryHandleTypeFlagBits.EXTERNAL_MEMORY_HANDLE_TYPE_HOST_MAPPED_FOREIGN_MEMORY_BIT_EXT'.
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_1 VK_VERSION_1_1>,
-- 'ExternalMemoryFeatureFlags'
newtype ExternalMemoryFeatureFlagBits = ExternalMemoryFeatureFlagBits Flags
deriving newtype (Eq, Ord, Storable, Zero, Bits, FiniteBits)
-- | 'EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT' specifies that images or
-- buffers created with the specified parameters and handle type /must/ use
-- the mechanisms defined by
-- 'Vulkan.Core11.Promoted_From_VK_KHR_dedicated_allocation.MemoryDedicatedRequirements'
-- and
-- 'Vulkan.Core11.Promoted_From_VK_KHR_dedicated_allocation.MemoryDedicatedAllocateInfo'
-- to create (or import) a dedicated allocation for the image or buffer.
pattern EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT = ExternalMemoryFeatureFlagBits 0x00000001
-- | 'EXTERNAL_MEMORY_FEATURE_EXPORTABLE_BIT' specifies that handles of this
-- type /can/ be exported from Vulkan memory objects.
pattern EXTERNAL_MEMORY_FEATURE_EXPORTABLE_BIT = ExternalMemoryFeatureFlagBits 0x00000002
-- | 'EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT' specifies that handles of this
-- type /can/ be imported as Vulkan memory objects.
pattern EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT = ExternalMemoryFeatureFlagBits 0x00000004
conNameExternalMemoryFeatureFlagBits :: String
conNameExternalMemoryFeatureFlagBits = "ExternalMemoryFeatureFlagBits"
enumPrefixExternalMemoryFeatureFlagBits :: String
enumPrefixExternalMemoryFeatureFlagBits = "EXTERNAL_MEMORY_FEATURE_"
showTableExternalMemoryFeatureFlagBits :: [(ExternalMemoryFeatureFlagBits, String)]
showTableExternalMemoryFeatureFlagBits =
[ (EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT, "DEDICATED_ONLY_BIT")
, (EXTERNAL_MEMORY_FEATURE_EXPORTABLE_BIT , "EXPORTABLE_BIT")
, (EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT , "IMPORTABLE_BIT")
]
instance Show ExternalMemoryFeatureFlagBits where
showsPrec = enumShowsPrec enumPrefixExternalMemoryFeatureFlagBits
showTableExternalMemoryFeatureFlagBits
conNameExternalMemoryFeatureFlagBits
(\(ExternalMemoryFeatureFlagBits x) -> x)
(\x -> showString "0x" . showHex x)
instance Read ExternalMemoryFeatureFlagBits where
readPrec = enumReadPrec enumPrefixExternalMemoryFeatureFlagBits
showTableExternalMemoryFeatureFlagBits
conNameExternalMemoryFeatureFlagBits
ExternalMemoryFeatureFlagBits
| expipiplus1/vulkan | src/Vulkan/Core11/Enums/ExternalMemoryFeatureFlagBits.hs | bsd-3-clause | 4,826 | 1 | 10 | 1,037 | 404 | 253 | 151 | -1 | -1 |
{-|
Module : ChainFlyer
Copyright : (c) Tatsuya Hirose, 2015
License : BSD3
Maintainer : tatsuya.hirose.0804@gmail.com
-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}
module Servant.ChainFlyer.Types.Transaction
( TransactionInput(..)
, TransactionOutput(..)
, Transaction(..)
) where
import Control.Monad (mzero)
import Data.Aeson
import Data.Time.Clock
import Data.Time.Format
import GHC.Generics
-- | Input of a transaction.
data TransactionInput = TransactionInput
{ prev_hash :: String
, prev_index :: Integer
, in_value :: Integer
, in_script :: String
, in_address :: String
, sequence :: Integer
} deriving (Show, Generic)
instance FromJSON TransactionInput where
parseJSON (Object v) = TransactionInput
<$> v .: "prev_hash"
<*> v .: "prev_index"
<*> v .: "value"
<*> v .: "script"
<*> v .: "address"
<*> v .: "sequence"
parseJSON _ = mzero
instance ToJSON TransactionInput where
toJSON (TransactionInput prev_hash prev_index value script address sequence) =
object [ "prev_hash" .= prev_hash
, "prev_index" .= prev_index
, "value" .= value
, "script" .= script
, "address" .= address
, "sequence" .= sequence
]
-- | Output of a transaction.
data TransactionOutput = TransactionOutput
{ out_value :: Integer
, out_script :: String
, out_address :: String
} deriving (Show, Generic)
instance FromJSON TransactionOutput where
parseJSON (Object v) = TransactionOutput
<$> v .: "value"
<*> v .: "script"
<*> v .: "address"
parseJSON _ = mzero
instance ToJSON TransactionOutput where
toJSON (TransactionOutput value script address) =
object [ "value" .= value
, "script" .= script
, "address" .= address
]
-- | Transaction.
data Transaction = Transaction
{ tx_hash :: String
, block_height :: Int
, confirmed :: Int
, fees :: Integer
, size :: Int
, received_date :: UTCTime
, version :: Int
, lock_time :: Int
, inputs :: [TransactionInput]
, outputs :: [TransactionOutput]
} deriving (Show, Generic)
instance FromJSON Transaction where
parseJSON (Object v) = Transaction
<$> v .: "tx_hash"
<*> v .: "block_height"
<*> v .: "confirmed"
<*> v .: "fees"
<*> v .: "size"
<*> (v .: "received_date" >>= parseTimeM True defaultTimeLocale "%Y-%m-%dT%H:%M:%S" . takeWhile (/='.'))
<*> v .: "version"
<*> v .: "lock_time"
<*> v .: "inputs"
<*> v .: "outputs"
parseJSON _ = mzero
instance ToJSON Transaction
| lotz84/chainFlyer | src/Servant/ChainFlyer/Types/Transaction.hs | bsd-3-clause | 3,091 | 0 | 24 | 1,119 | 650 | 365 | 285 | 78 | 0 |
module JIT where
import Foreign.Ptr (FunPtr, castFunPtr)
import Control.Monad.Except
import qualified LLVM.General.AST as AST
import LLVM.General.Context
import qualified LLVM.General.ExecutionEngine as EE
import LLVM.General.Module as Mod
import LLVM.General.PassManager
foreign import ccall "dynamic" haskFun :: FunPtr (IO Int) -> IO Int
run :: FunPtr a -> IO Int
run fn = haskFun (castFunPtr fn :: FunPtr (IO Int))
jit :: Context -> (EE.MCJIT -> IO a) -> IO a
jit c = EE.withMCJIT c optlevel model ptrelim fastins
where
optlevel = Just 2
model = Nothing
ptrelim = Nothing
fastins = Nothing
passes :: PassSetSpec
passes = defaultCuratedPassSetSpec {optLevel = Just 3}
runJIT :: AST.Module -> IO (Either String AST.Module)
runJIT mod =
withContext $ \context ->
jit context $ \executionEngine ->
runExceptT $
withModuleFromAST context mod $ \m ->
withPassManager passes $ \pm -> do
_ <- runPassManager pm m
optmod <- moduleAST m
s <- moduleLLVMAssembly m
putStrLn s
EE.withModuleInEngine executionEngine m $ \ee -> do
mainfn <- EE.getFunction ee (AST.Name "main")
case mainfn of
Just fn -> do
res <- run fn
putStrLn $ "Evaluated to: " ++ show res
Nothing -> return ()
return optmod
| jjingram/satori | src/JIT.hs | bsd-3-clause | 1,379 | 0 | 25 | 383 | 447 | 228 | 219 | 38 | 2 |
-- parser produced by Happy Version 1.13
{-
%
% (c) The GRASP/AQUA Project, Glasgow University, 1998
%
% @(#) $Docid: Jul. 12th 2001 10:08 Sigbjorn Finne $
% @(#) $Contactid: sof@galconn.com $
%
A grammar for OMG CORBA IDL
-}
module OmgParser ( parseIDL ) where
import LexM
import Lex
import IDLToken
import IDLSyn
import BasicTypes
import Literal
{-
BEGIN_GHC_ONLY
import GlaExts
END_GHC_ONLY
-}
data HappyAbsSyn
= HappyTerminal IDLToken
| HappyErrorToken Int
| HappyAbsSyn4 ([Defn])
| HappyAbsSyn6 (Defn)
| HappyAbsSyn10 ((Id, Inherit))
| HappyAbsSyn13 (Inherit)
| HappyAbsSyn15 (String)
| HappyAbsSyn18 (Type)
| HappyAbsSyn19 (Expr)
| HappyAbsSyn27 (UnaryOp)
| HappyAbsSyn29 (Literal)
| HappyAbsSyn32 ((Type, [Id]))
| HappyAbsSyn38 ([Id])
| HappyAbsSyn39 (Id)
| HappyAbsSyn50 ([Member])
| HappyAbsSyn51 (Member)
| HappyAbsSyn54 ([Switch])
| HappyAbsSyn55 (Switch)
| HappyAbsSyn56 ([CaseLabel])
| HappyAbsSyn57 (CaseLabel)
| HappyAbsSyn58 (SwitchArm)
| HappyAbsSyn60 ([(Id,[Attribute],Maybe Expr)])
| HappyAbsSyn64 ((Id, [Expr]))
| HappyAbsSyn65 ([Expr])
| HappyAbsSyn68 (Bool)
| HappyAbsSyn76 ([Param])
| HappyAbsSyn78 (Param)
| HappyAbsSyn79 (Attribute)
| HappyAbsSyn80 (Maybe Raises)
| HappyAbsSyn81 (Maybe Context)
| HappyAbsSyn82 ([String])
| HappyAbsSyn87 (IntegerLit)
type HappyReduction =
Int
-> (IDLToken)
-> HappyState (IDLToken) (HappyStk HappyAbsSyn -> LexM(HappyAbsSyn))
-> [HappyState (IDLToken) (HappyStk HappyAbsSyn -> LexM(HappyAbsSyn))]
-> HappyStk HappyAbsSyn
-> LexM(HappyAbsSyn)
action_0,
action_1,
action_2,
action_3,
action_4,
action_5,
action_6,
action_7,
action_8,
action_9,
action_10,
action_11,
action_12,
action_13,
action_14,
action_15,
action_16,
action_17,
action_18,
action_19,
action_20,
action_21,
action_22,
action_23,
action_24,
action_25,
action_26,
action_27,
action_28,
action_29,
action_30,
action_31,
action_32,
action_33,
action_34,
action_35,
action_36,
action_37,
action_38,
action_39,
action_40,
action_41,
action_42,
action_43,
action_44,
action_45,
action_46,
action_47,
action_48,
action_49,
action_50,
action_51,
action_52,
action_53,
action_54,
action_55,
action_56,
action_57,
action_58,
action_59,
action_60,
action_61,
action_62,
action_63,
action_64,
action_65,
action_66,
action_67,
action_68,
action_69,
action_70,
action_71,
action_72,
action_73,
action_74,
action_75,
action_76,
action_77,
action_78,
action_79,
action_80,
action_81,
action_82,
action_83,
action_84,
action_85,
action_86,
action_87,
action_88,
action_89,
action_90,
action_91,
action_92,
action_93,
action_94,
action_95,
action_96,
action_97,
action_98,
action_99,
action_100,
action_101,
action_102,
action_103,
action_104,
action_105,
action_106,
action_107,
action_108,
action_109,
action_110,
action_111,
action_112,
action_113,
action_114,
action_115,
action_116,
action_117,
action_118,
action_119,
action_120,
action_121,
action_122,
action_123,
action_124,
action_125,
action_126,
action_127,
action_128,
action_129,
action_130,
action_131,
action_132,
action_133,
action_134,
action_135,
action_136,
action_137,
action_138,
action_139,
action_140,
action_141,
action_142,
action_143,
action_144,
action_145,
action_146,
action_147,
action_148,
action_149,
action_150,
action_151,
action_152,
action_153,
action_154,
action_155,
action_156,
action_157,
action_158,
action_159,
action_160,
action_161,
action_162,
action_163,
action_164,
action_165,
action_166,
action_167,
action_168,
action_169,
action_170,
action_171,
action_172,
action_173,
action_174,
action_175,
action_176,
action_177,
action_178,
action_179,
action_180,
action_181,
action_182,
action_183,
action_184,
action_185,
action_186,
action_187,
action_188,
action_189,
action_190,
action_191,
action_192,
action_193,
action_194,
action_195,
action_196,
action_197,
action_198,
action_199,
action_200,
action_201,
action_202,
action_203,
action_204,
action_205,
action_206,
action_207,
action_208,
action_209,
action_210,
action_211,
action_212,
action_213,
action_214,
action_215,
action_216,
action_217,
action_218,
action_219,
action_220,
action_221,
action_222,
action_223,
action_224,
action_225,
action_226,
action_227,
action_228,
action_229,
action_230,
action_231,
action_232,
action_233,
action_234,
action_235,
action_236,
action_237,
action_238,
action_239,
action_240,
action_241,
action_242,
action_243,
action_244,
action_245,
action_246,
action_247,
action_248,
action_249,
action_250,
action_251,
action_252,
action_253,
action_254,
action_255,
action_256,
action_257,
action_258,
action_259,
action_260,
action_261,
action_262,
action_263,
action_264,
action_265,
action_266,
action_267,
action_268,
action_269,
action_270,
action_271,
action_272,
action_273,
action_274,
action_275,
action_276,
action_277 :: Int -> HappyReduction
happyReduce_1,
happyReduce_2,
happyReduce_3,
happyReduce_4,
happyReduce_5,
happyReduce_6,
happyReduce_7,
happyReduce_8,
happyReduce_9,
happyReduce_10,
happyReduce_11,
happyReduce_12,
happyReduce_13,
happyReduce_14,
happyReduce_15,
happyReduce_16,
happyReduce_17,
happyReduce_18,
happyReduce_19,
happyReduce_20,
happyReduce_21,
happyReduce_22,
happyReduce_23,
happyReduce_24,
happyReduce_25,
happyReduce_26,
happyReduce_27,
happyReduce_28,
happyReduce_29,
happyReduce_30,
happyReduce_31,
happyReduce_32,
happyReduce_33,
happyReduce_34,
happyReduce_35,
happyReduce_36,
happyReduce_37,
happyReduce_38,
happyReduce_39,
happyReduce_40,
happyReduce_41,
happyReduce_42,
happyReduce_43,
happyReduce_44,
happyReduce_45,
happyReduce_46,
happyReduce_47,
happyReduce_48,
happyReduce_49,
happyReduce_50,
happyReduce_51,
happyReduce_52,
happyReduce_53,
happyReduce_54,
happyReduce_55,
happyReduce_56,
happyReduce_57,
happyReduce_58,
happyReduce_59,
happyReduce_60,
happyReduce_61,
happyReduce_62,
happyReduce_63,
happyReduce_64,
happyReduce_65,
happyReduce_66,
happyReduce_67,
happyReduce_68,
happyReduce_69,
happyReduce_70,
happyReduce_71,
happyReduce_72,
happyReduce_73,
happyReduce_74,
happyReduce_75,
happyReduce_76,
happyReduce_77,
happyReduce_78,
happyReduce_79,
happyReduce_80,
happyReduce_81,
happyReduce_82,
happyReduce_83,
happyReduce_84,
happyReduce_85,
happyReduce_86,
happyReduce_87,
happyReduce_88,
happyReduce_89,
happyReduce_90,
happyReduce_91,
happyReduce_92,
happyReduce_93,
happyReduce_94,
happyReduce_95,
happyReduce_96,
happyReduce_97,
happyReduce_98,
happyReduce_99,
happyReduce_100,
happyReduce_101,
happyReduce_102,
happyReduce_103,
happyReduce_104,
happyReduce_105,
happyReduce_106,
happyReduce_107,
happyReduce_108,
happyReduce_109,
happyReduce_110,
happyReduce_111,
happyReduce_112,
happyReduce_113,
happyReduce_114,
happyReduce_115,
happyReduce_116,
happyReduce_117,
happyReduce_118,
happyReduce_119,
happyReduce_120,
happyReduce_121,
happyReduce_122,
happyReduce_123,
happyReduce_124,
happyReduce_125,
happyReduce_126,
happyReduce_127,
happyReduce_128,
happyReduce_129,
happyReduce_130,
happyReduce_131,
happyReduce_132,
happyReduce_133,
happyReduce_134,
happyReduce_135,
happyReduce_136,
happyReduce_137,
happyReduce_138,
happyReduce_139,
happyReduce_140,
happyReduce_141,
happyReduce_142,
happyReduce_143,
happyReduce_144,
happyReduce_145,
happyReduce_146,
happyReduce_147,
happyReduce_148,
happyReduce_149,
happyReduce_150,
happyReduce_151,
happyReduce_152,
happyReduce_153,
happyReduce_154,
happyReduce_155,
happyReduce_156,
happyReduce_157,
happyReduce_158,
happyReduce_159,
happyReduce_160,
happyReduce_161,
happyReduce_162,
happyReduce_163,
happyReduce_164,
happyReduce_165,
happyReduce_166,
happyReduce_167,
happyReduce_168,
happyReduce_169,
happyReduce_170,
happyReduce_171,
happyReduce_172,
happyReduce_173,
happyReduce_174,
happyReduce_175,
happyReduce_176 :: HappyReduction
action_0 (4) = happyGoto action_3
action_0 (5) = happyGoto action_2
action_0 _ = happyReduce_2
action_1 (5) = happyGoto action_2
action_1 _ = happyFail
action_2 (91) = happyShift action_15
action_2 (92) = happyShift action_16
action_2 (101) = happyShift action_17
action_2 (116) = happyShift action_18
action_2 (125) = happyShift action_19
action_2 (126) = happyShift action_20
action_2 (130) = happyShift action_21
action_2 (154) = happyShift action_22
action_2 (158) = happyShift action_23
action_2 (159) = happyShift action_24
action_2 (160) = happyShift action_25
action_2 (6) = happyGoto action_4
action_2 (7) = happyGoto action_5
action_2 (8) = happyGoto action_6
action_2 (9) = happyGoto action_7
action_2 (10) = happyGoto action_8
action_2 (17) = happyGoto action_9
action_2 (31) = happyGoto action_10
action_2 (49) = happyGoto action_11
action_2 (52) = happyGoto action_12
action_2 (59) = happyGoto action_13
action_2 (70) = happyGoto action_14
action_2 _ = happyReduce_1
action_3 (162) = happyAccept
action_3 _ = happyFail
action_4 _ = happyReduce_3
action_5 (90) = happyShift action_87
action_5 _ = happyFail
action_6 (90) = happyShift action_86
action_6 _ = happyFail
action_7 _ = happyReduce_13
action_8 (95) = happyShift action_85
action_8 _ = happyFail
action_9 (90) = happyShift action_84
action_9 _ = happyFail
action_10 (90) = happyShift action_83
action_10 _ = happyFail
action_11 _ = happyReduce_68
action_12 _ = happyReduce_69
action_13 _ = happyReduce_70
action_14 (90) = happyShift action_82
action_14 _ = happyFail
action_15 (141) = happyShift action_27
action_15 (89) = happyGoto action_81
action_15 _ = happyFail
action_16 (141) = happyShift action_27
action_16 (89) = happyGoto action_80
action_16 _ = happyFail
action_17 (98) = happyShift action_53
action_17 (118) = happyShift action_54
action_17 (119) = happyShift action_55
action_17 (120) = happyShift action_56
action_17 (121) = happyShift action_57
action_17 (122) = happyShift action_58
action_17 (123) = happyShift action_59
action_17 (124) = happyShift action_60
action_17 (141) = happyShift action_61
action_17 (146) = happyShift action_62
action_17 (147) = happyShift action_63
action_17 (153) = happyShift action_79
action_17 (15) = happyGoto action_69
action_17 (18) = happyGoto action_70
action_17 (41) = happyGoto action_71
action_17 (42) = happyGoto action_72
action_17 (43) = happyGoto action_73
action_17 (44) = happyGoto action_74
action_17 (45) = happyGoto action_75
action_17 (62) = happyGoto action_76
action_17 (63) = happyGoto action_77
action_17 (86) = happyGoto action_78
action_17 _ = happyFail
action_18 (98) = happyShift action_53
action_18 (118) = happyShift action_54
action_18 (119) = happyShift action_55
action_18 (120) = happyShift action_56
action_18 (121) = happyShift action_57
action_18 (122) = happyShift action_58
action_18 (123) = happyShift action_59
action_18 (124) = happyShift action_60
action_18 (125) = happyShift action_19
action_18 (126) = happyShift action_20
action_18 (130) = happyShift action_21
action_18 (141) = happyShift action_61
action_18 (146) = happyShift action_62
action_18 (147) = happyShift action_63
action_18 (148) = happyShift action_64
action_18 (149) = happyShift action_65
action_18 (150) = happyShift action_66
action_18 (151) = happyShift action_67
action_18 (153) = happyShift action_68
action_18 (15) = happyGoto action_31
action_18 (32) = happyGoto action_32
action_18 (33) = happyGoto action_33
action_18 (34) = happyGoto action_34
action_18 (35) = happyGoto action_35
action_18 (36) = happyGoto action_36
action_18 (37) = happyGoto action_37
action_18 (41) = happyGoto action_38
action_18 (42) = happyGoto action_39
action_18 (43) = happyGoto action_40
action_18 (44) = happyGoto action_41
action_18 (45) = happyGoto action_42
action_18 (46) = happyGoto action_43
action_18 (47) = happyGoto action_44
action_18 (48) = happyGoto action_45
action_18 (49) = happyGoto action_46
action_18 (52) = happyGoto action_47
action_18 (59) = happyGoto action_48
action_18 (61) = happyGoto action_49
action_18 (62) = happyGoto action_50
action_18 (63) = happyGoto action_51
action_18 (85) = happyGoto action_52
action_18 _ = happyFail
action_19 (141) = happyShift action_27
action_19 (89) = happyGoto action_30
action_19 _ = happyFail
action_20 (141) = happyShift action_27
action_20 (89) = happyGoto action_29
action_20 _ = happyFail
action_21 (141) = happyShift action_27
action_21 (89) = happyGoto action_28
action_21 _ = happyFail
action_22 (141) = happyShift action_27
action_22 (89) = happyGoto action_26
action_22 _ = happyFail
action_23 _ = happyReduce_10
action_24 _ = happyReduce_11
action_25 _ = happyReduce_9
action_26 (95) = happyShift action_108
action_26 _ = happyFail
action_27 _ = happyReduce_176
action_28 (95) = happyShift action_107
action_28 _ = happyFail
action_29 (127) = happyShift action_106
action_29 _ = happyFail
action_30 (95) = happyShift action_105
action_30 _ = happyFail
action_31 (98) = happyShift action_94
action_31 _ = happyReduce_76
action_32 _ = happyReduce_67
action_33 (141) = happyShift action_27
action_33 (38) = happyGoto action_102
action_33 (40) = happyGoto action_103
action_33 (89) = happyGoto action_104
action_33 _ = happyFail
action_34 _ = happyReduce_72
action_35 _ = happyReduce_74
action_36 _ = happyReduce_75
action_37 _ = happyReduce_73
action_38 _ = happyReduce_77
action_39 _ = happyReduce_78
action_40 _ = happyReduce_79
action_41 _ = happyReduce_80
action_42 _ = happyReduce_81
action_43 _ = happyReduce_82
action_44 _ = happyReduce_83
action_45 _ = happyReduce_84
action_46 _ = happyReduce_89
action_47 _ = happyReduce_90
action_48 _ = happyReduce_91
action_49 _ = happyReduce_85
action_50 _ = happyReduce_86
action_51 _ = happyReduce_87
action_52 _ = happyReduce_88
action_53 (141) = happyShift action_101
action_53 _ = happyFail
action_54 _ = happyReduce_97
action_55 _ = happyReduce_98
action_56 (119) = happyShift action_100
action_56 _ = happyFail
action_57 (119) = happyShift action_99
action_57 _ = happyFail
action_58 _ = happyReduce_101
action_59 _ = happyReduce_102
action_60 _ = happyReduce_103
action_61 _ = happyReduce_27
action_62 (131) = happyShift action_98
action_62 _ = happyReduce_131
action_63 (131) = happyShift action_97
action_63 _ = happyReduce_133
action_64 (131) = happyShift action_96
action_64 _ = happyFail
action_65 _ = happyReduce_106
action_66 _ = happyReduce_105
action_67 _ = happyReduce_104
action_68 (131) = happyShift action_95
action_68 _ = happyFail
action_69 (98) = happyShift action_94
action_69 _ = happyReduce_41
action_70 (141) = happyShift action_27
action_70 (89) = happyGoto action_93
action_70 _ = happyFail
action_71 _ = happyReduce_37
action_72 _ = happyReduce_33
action_73 _ = happyReduce_34
action_74 _ = happyReduce_35
action_75 _ = happyReduce_36
action_76 _ = happyReduce_38
action_77 _ = happyReduce_39
action_78 _ = happyReduce_40
action_79 _ = happyReduce_173
action_80 (95) = happyReduce_24
action_80 (97) = happyShift action_92
action_80 (13) = happyGoto action_90
action_80 (14) = happyGoto action_91
action_80 _ = happyReduce_14
action_81 (95) = happyShift action_89
action_81 _ = happyFail
action_82 _ = happyReduce_6
action_83 _ = happyReduce_4
action_84 _ = happyReduce_5
action_85 (11) = happyGoto action_88
action_85 _ = happyReduce_17
action_86 _ = happyReduce_7
action_87 _ = happyReduce_8
action_88 (96) = happyShift action_154
action_88 (101) = happyShift action_17
action_88 (116) = happyShift action_18
action_88 (125) = happyShift action_19
action_88 (126) = happyShift action_20
action_88 (130) = happyShift action_21
action_88 (142) = happyReduce_140
action_88 (152) = happyShift action_155
action_88 (154) = happyShift action_22
action_88 (157) = happyShift action_156
action_88 (12) = happyGoto action_146
action_88 (17) = happyGoto action_147
action_88 (31) = happyGoto action_148
action_88 (49) = happyGoto action_11
action_88 (52) = happyGoto action_12
action_88 (59) = happyGoto action_13
action_88 (67) = happyGoto action_149
action_88 (68) = happyGoto action_150
action_88 (70) = happyGoto action_151
action_88 (73) = happyGoto action_152
action_88 (74) = happyGoto action_153
action_88 _ = happyReduce_149
action_89 (5) = happyGoto action_145
action_89 _ = happyReduce_2
action_90 _ = happyReduce_16
action_91 _ = happyReduce_25
action_92 (98) = happyShift action_53
action_92 (141) = happyShift action_61
action_92 (15) = happyGoto action_144
action_92 _ = happyFail
action_93 (102) = happyShift action_143
action_93 _ = happyFail
action_94 (141) = happyShift action_142
action_94 _ = happyFail
action_95 (98) = happyShift action_53
action_95 (113) = happyShift action_135
action_95 (139) = happyShift action_136
action_95 (141) = happyShift action_61
action_95 (143) = happyShift action_137
action_95 (145) = happyShift action_138
action_95 (15) = happyGoto action_122
action_95 (19) = happyGoto action_123
action_95 (20) = happyGoto action_124
action_95 (21) = happyGoto action_125
action_95 (22) = happyGoto action_126
action_95 (23) = happyGoto action_127
action_95 (24) = happyGoto action_128
action_95 (25) = happyGoto action_129
action_95 (26) = happyGoto action_130
action_95 (27) = happyGoto action_131
action_95 (28) = happyGoto action_132
action_95 (29) = happyGoto action_133
action_95 (30) = happyGoto action_141
action_95 _ = happyFail
action_96 (98) = happyShift action_53
action_96 (118) = happyShift action_54
action_96 (119) = happyShift action_55
action_96 (120) = happyShift action_56
action_96 (121) = happyShift action_57
action_96 (122) = happyShift action_58
action_96 (123) = happyShift action_59
action_96 (124) = happyShift action_60
action_96 (141) = happyShift action_61
action_96 (146) = happyShift action_62
action_96 (147) = happyShift action_63
action_96 (148) = happyShift action_64
action_96 (149) = happyShift action_65
action_96 (150) = happyShift action_66
action_96 (151) = happyShift action_67
action_96 (153) = happyShift action_68
action_96 (15) = happyGoto action_31
action_96 (34) = happyGoto action_140
action_96 (35) = happyGoto action_35
action_96 (36) = happyGoto action_36
action_96 (41) = happyGoto action_38
action_96 (42) = happyGoto action_39
action_96 (43) = happyGoto action_40
action_96 (44) = happyGoto action_41
action_96 (45) = happyGoto action_42
action_96 (46) = happyGoto action_43
action_96 (47) = happyGoto action_44
action_96 (48) = happyGoto action_45
action_96 (61) = happyGoto action_49
action_96 (62) = happyGoto action_50
action_96 (63) = happyGoto action_51
action_96 (85) = happyGoto action_52
action_96 _ = happyFail
action_97 (98) = happyShift action_53
action_97 (113) = happyShift action_135
action_97 (139) = happyShift action_136
action_97 (141) = happyShift action_61
action_97 (143) = happyShift action_137
action_97 (145) = happyShift action_138
action_97 (15) = happyGoto action_122
action_97 (19) = happyGoto action_123
action_97 (20) = happyGoto action_124
action_97 (21) = happyGoto action_125
action_97 (22) = happyGoto action_126
action_97 (23) = happyGoto action_127
action_97 (24) = happyGoto action_128
action_97 (25) = happyGoto action_129
action_97 (26) = happyGoto action_130
action_97 (27) = happyGoto action_131
action_97 (28) = happyGoto action_132
action_97 (29) = happyGoto action_133
action_97 (30) = happyGoto action_139
action_97 _ = happyFail
action_98 (98) = happyShift action_53
action_98 (113) = happyShift action_135
action_98 (139) = happyShift action_136
action_98 (141) = happyShift action_61
action_98 (143) = happyShift action_137
action_98 (145) = happyShift action_138
action_98 (15) = happyGoto action_122
action_98 (19) = happyGoto action_123
action_98 (20) = happyGoto action_124
action_98 (21) = happyGoto action_125
action_98 (22) = happyGoto action_126
action_98 (23) = happyGoto action_127
action_98 (24) = happyGoto action_128
action_98 (25) = happyGoto action_129
action_98 (26) = happyGoto action_130
action_98 (27) = happyGoto action_131
action_98 (28) = happyGoto action_132
action_98 (29) = happyGoto action_133
action_98 (30) = happyGoto action_134
action_98 _ = happyFail
action_99 _ = happyReduce_99
action_100 _ = happyReduce_100
action_101 _ = happyReduce_28
action_102 (99) = happyShift action_121
action_102 _ = happyReduce_71
action_103 _ = happyReduce_92
action_104 (135) = happyShift action_120
action_104 (65) = happyGoto action_118
action_104 (66) = happyGoto action_119
action_104 _ = happyReduce_95
action_105 (98) = happyShift action_53
action_105 (118) = happyShift action_54
action_105 (119) = happyShift action_55
action_105 (120) = happyShift action_56
action_105 (121) = happyShift action_57
action_105 (122) = happyShift action_58
action_105 (123) = happyShift action_59
action_105 (124) = happyShift action_60
action_105 (125) = happyShift action_19
action_105 (126) = happyShift action_20
action_105 (130) = happyShift action_21
action_105 (141) = happyShift action_61
action_105 (146) = happyShift action_62
action_105 (147) = happyShift action_63
action_105 (148) = happyShift action_64
action_105 (149) = happyShift action_65
action_105 (150) = happyShift action_66
action_105 (151) = happyShift action_67
action_105 (153) = happyShift action_68
action_105 (15) = happyGoto action_31
action_105 (33) = happyGoto action_109
action_105 (34) = happyGoto action_34
action_105 (35) = happyGoto action_35
action_105 (36) = happyGoto action_36
action_105 (37) = happyGoto action_37
action_105 (41) = happyGoto action_38
action_105 (42) = happyGoto action_39
action_105 (43) = happyGoto action_40
action_105 (44) = happyGoto action_41
action_105 (45) = happyGoto action_42
action_105 (46) = happyGoto action_43
action_105 (47) = happyGoto action_44
action_105 (48) = happyGoto action_45
action_105 (49) = happyGoto action_46
action_105 (50) = happyGoto action_116
action_105 (51) = happyGoto action_117
action_105 (52) = happyGoto action_47
action_105 (59) = happyGoto action_48
action_105 (61) = happyGoto action_49
action_105 (62) = happyGoto action_50
action_105 (63) = happyGoto action_51
action_105 (85) = happyGoto action_52
action_105 _ = happyFail
action_106 (93) = happyShift action_115
action_106 _ = happyFail
action_107 (141) = happyShift action_27
action_107 (60) = happyGoto action_113
action_107 (89) = happyGoto action_114
action_107 _ = happyFail
action_108 (98) = happyShift action_53
action_108 (118) = happyShift action_54
action_108 (119) = happyShift action_55
action_108 (120) = happyShift action_56
action_108 (121) = happyShift action_57
action_108 (122) = happyShift action_58
action_108 (123) = happyShift action_59
action_108 (124) = happyShift action_60
action_108 (125) = happyShift action_19
action_108 (126) = happyShift action_20
action_108 (130) = happyShift action_21
action_108 (141) = happyShift action_61
action_108 (146) = happyShift action_62
action_108 (147) = happyShift action_63
action_108 (148) = happyShift action_64
action_108 (149) = happyShift action_65
action_108 (150) = happyShift action_66
action_108 (151) = happyShift action_67
action_108 (153) = happyShift action_68
action_108 (15) = happyGoto action_31
action_108 (33) = happyGoto action_109
action_108 (34) = happyGoto action_34
action_108 (35) = happyGoto action_35
action_108 (36) = happyGoto action_36
action_108 (37) = happyGoto action_37
action_108 (41) = happyGoto action_38
action_108 (42) = happyGoto action_39
action_108 (43) = happyGoto action_40
action_108 (44) = happyGoto action_41
action_108 (45) = happyGoto action_42
action_108 (46) = happyGoto action_43
action_108 (47) = happyGoto action_44
action_108 (48) = happyGoto action_45
action_108 (49) = happyGoto action_46
action_108 (51) = happyGoto action_110
action_108 (52) = happyGoto action_47
action_108 (59) = happyGoto action_48
action_108 (61) = happyGoto action_49
action_108 (62) = happyGoto action_50
action_108 (63) = happyGoto action_51
action_108 (71) = happyGoto action_111
action_108 (72) = happyGoto action_112
action_108 (85) = happyGoto action_52
action_108 _ = happyReduce_144
action_109 (141) = happyShift action_27
action_109 (38) = happyGoto action_205
action_109 (40) = happyGoto action_103
action_109 (89) = happyGoto action_104
action_109 _ = happyFail
action_110 _ = happyReduce_146
action_111 (96) = happyShift action_204
action_111 _ = happyFail
action_112 (98) = happyShift action_53
action_112 (118) = happyShift action_54
action_112 (119) = happyShift action_55
action_112 (120) = happyShift action_56
action_112 (121) = happyShift action_57
action_112 (122) = happyShift action_58
action_112 (123) = happyShift action_59
action_112 (124) = happyShift action_60
action_112 (125) = happyShift action_19
action_112 (126) = happyShift action_20
action_112 (130) = happyShift action_21
action_112 (141) = happyShift action_61
action_112 (146) = happyShift action_62
action_112 (147) = happyShift action_63
action_112 (148) = happyShift action_64
action_112 (149) = happyShift action_65
action_112 (150) = happyShift action_66
action_112 (151) = happyShift action_67
action_112 (153) = happyShift action_68
action_112 (15) = happyGoto action_31
action_112 (33) = happyGoto action_109
action_112 (34) = happyGoto action_34
action_112 (35) = happyGoto action_35
action_112 (36) = happyGoto action_36
action_112 (37) = happyGoto action_37
action_112 (41) = happyGoto action_38
action_112 (42) = happyGoto action_39
action_112 (43) = happyGoto action_40
action_112 (44) = happyGoto action_41
action_112 (45) = happyGoto action_42
action_112 (46) = happyGoto action_43
action_112 (47) = happyGoto action_44
action_112 (48) = happyGoto action_45
action_112 (49) = happyGoto action_46
action_112 (51) = happyGoto action_203
action_112 (52) = happyGoto action_47
action_112 (59) = happyGoto action_48
action_112 (61) = happyGoto action_49
action_112 (62) = happyGoto action_50
action_112 (63) = happyGoto action_51
action_112 (85) = happyGoto action_52
action_112 _ = happyReduce_145
action_113 (96) = happyShift action_201
action_113 (99) = happyShift action_202
action_113 _ = happyFail
action_114 _ = happyReduce_126
action_115 (98) = happyShift action_53
action_115 (119) = happyShift action_55
action_115 (120) = happyShift action_56
action_115 (121) = happyShift action_57
action_115 (122) = happyShift action_58
action_115 (124) = happyShift action_60
action_115 (130) = happyShift action_21
action_115 (141) = happyShift action_61
action_115 (15) = happyGoto action_195
action_115 (42) = happyGoto action_196
action_115 (43) = happyGoto action_197
action_115 (45) = happyGoto action_198
action_115 (53) = happyGoto action_199
action_115 (59) = happyGoto action_200
action_115 _ = happyFail
action_116 (96) = happyShift action_194
action_116 (98) = happyShift action_53
action_116 (118) = happyShift action_54
action_116 (119) = happyShift action_55
action_116 (120) = happyShift action_56
action_116 (121) = happyShift action_57
action_116 (122) = happyShift action_58
action_116 (123) = happyShift action_59
action_116 (124) = happyShift action_60
action_116 (125) = happyShift action_19
action_116 (126) = happyShift action_20
action_116 (130) = happyShift action_21
action_116 (141) = happyShift action_61
action_116 (146) = happyShift action_62
action_116 (147) = happyShift action_63
action_116 (148) = happyShift action_64
action_116 (149) = happyShift action_65
action_116 (150) = happyShift action_66
action_116 (151) = happyShift action_67
action_116 (153) = happyShift action_68
action_116 (15) = happyGoto action_31
action_116 (33) = happyGoto action_109
action_116 (34) = happyGoto action_34
action_116 (35) = happyGoto action_35
action_116 (36) = happyGoto action_36
action_116 (37) = happyGoto action_37
action_116 (41) = happyGoto action_38
action_116 (42) = happyGoto action_39
action_116 (43) = happyGoto action_40
action_116 (44) = happyGoto action_41
action_116 (45) = happyGoto action_42
action_116 (46) = happyGoto action_43
action_116 (47) = happyGoto action_44
action_116 (48) = happyGoto action_45
action_116 (49) = happyGoto action_46
action_116 (51) = happyGoto action_193
action_116 (52) = happyGoto action_47
action_116 (59) = happyGoto action_48
action_116 (61) = happyGoto action_49
action_116 (62) = happyGoto action_50
action_116 (63) = happyGoto action_51
action_116 (85) = happyGoto action_52
action_116 _ = happyFail
action_117 _ = happyReduce_108
action_118 (135) = happyShift action_120
action_118 (66) = happyGoto action_192
action_118 _ = happyReduce_96
action_119 _ = happyReduce_135
action_120 (98) = happyShift action_53
action_120 (113) = happyShift action_135
action_120 (139) = happyShift action_136
action_120 (141) = happyShift action_61
action_120 (143) = happyShift action_137
action_120 (145) = happyShift action_138
action_120 (15) = happyGoto action_122
action_120 (19) = happyGoto action_123
action_120 (20) = happyGoto action_124
action_120 (21) = happyGoto action_125
action_120 (22) = happyGoto action_126
action_120 (23) = happyGoto action_127
action_120 (24) = happyGoto action_128
action_120 (25) = happyGoto action_129
action_120 (26) = happyGoto action_130
action_120 (27) = happyGoto action_131
action_120 (28) = happyGoto action_132
action_120 (29) = happyGoto action_133
action_120 (30) = happyGoto action_191
action_120 _ = happyFail
action_121 (141) = happyShift action_27
action_121 (40) = happyGoto action_190
action_121 (89) = happyGoto action_104
action_121 _ = happyFail
action_122 (98) = happyShift action_94
action_122 _ = happyReduce_63
action_123 _ = happyReduce_66
action_124 (105) = happyShift action_189
action_124 _ = happyReduce_42
action_125 (107) = happyShift action_188
action_125 _ = happyReduce_43
action_126 (108) = happyShift action_187
action_126 _ = happyReduce_45
action_127 (110) = happyShift action_186
action_127 _ = happyReduce_47
action_128 (143) = happyShift action_184
action_128 (145) = happyShift action_185
action_128 _ = happyReduce_49
action_129 (111) = happyShift action_181
action_129 (112) = happyShift action_182
action_129 (144) = happyShift action_183
action_129 _ = happyReduce_51
action_130 _ = happyReduce_54
action_131 (98) = happyShift action_53
action_131 (139) = happyShift action_136
action_131 (141) = happyShift action_61
action_131 (15) = happyGoto action_122
action_131 (28) = happyGoto action_180
action_131 (29) = happyGoto action_133
action_131 _ = happyFail
action_132 _ = happyReduce_59
action_133 _ = happyReduce_64
action_134 (133) = happyShift action_179
action_134 _ = happyFail
action_135 _ = happyReduce_62
action_136 _ = happyReduce_65
action_137 _ = happyReduce_61
action_138 _ = happyReduce_60
action_139 (133) = happyShift action_178
action_139 _ = happyFail
action_140 (99) = happyShift action_176
action_140 (133) = happyShift action_177
action_140 _ = happyFail
action_141 (99) = happyShift action_175
action_141 _ = happyFail
action_142 _ = happyReduce_29
action_143 (98) = happyShift action_53
action_143 (113) = happyShift action_135
action_143 (139) = happyShift action_136
action_143 (141) = happyShift action_61
action_143 (143) = happyShift action_137
action_143 (145) = happyShift action_138
action_143 (15) = happyGoto action_122
action_143 (19) = happyGoto action_174
action_143 (20) = happyGoto action_124
action_143 (21) = happyGoto action_125
action_143 (22) = happyGoto action_126
action_143 (23) = happyGoto action_127
action_143 (24) = happyGoto action_128
action_143 (25) = happyGoto action_129
action_143 (26) = happyGoto action_130
action_143 (27) = happyGoto action_131
action_143 (28) = happyGoto action_132
action_143 (29) = happyGoto action_133
action_143 _ = happyFail
action_144 (98) = happyShift action_94
action_144 (99) = happyShift action_173
action_144 (16) = happyGoto action_172
action_144 _ = happyReduce_30
action_145 (91) = happyShift action_15
action_145 (92) = happyShift action_16
action_145 (96) = happyShift action_171
action_145 (101) = happyShift action_17
action_145 (116) = happyShift action_18
action_145 (125) = happyShift action_19
action_145 (126) = happyShift action_20
action_145 (130) = happyShift action_21
action_145 (154) = happyShift action_22
action_145 (158) = happyShift action_23
action_145 (159) = happyShift action_24
action_145 (160) = happyShift action_25
action_145 (6) = happyGoto action_4
action_145 (7) = happyGoto action_5
action_145 (8) = happyGoto action_6
action_145 (9) = happyGoto action_7
action_145 (10) = happyGoto action_8
action_145 (17) = happyGoto action_9
action_145 (31) = happyGoto action_10
action_145 (49) = happyGoto action_11
action_145 (52) = happyGoto action_12
action_145 (59) = happyGoto action_13
action_145 (70) = happyGoto action_14
action_145 _ = happyFail
action_146 _ = happyReduce_18
action_147 (90) = happyShift action_170
action_147 _ = happyFail
action_148 (90) = happyShift action_169
action_148 _ = happyFail
action_149 (90) = happyShift action_168
action_149 _ = happyFail
action_150 (142) = happyShift action_167
action_150 _ = happyFail
action_151 (90) = happyShift action_166
action_151 _ = happyFail
action_152 (90) = happyShift action_165
action_152 _ = happyFail
action_153 (98) = happyShift action_53
action_153 (118) = happyShift action_54
action_153 (119) = happyShift action_55
action_153 (120) = happyShift action_56
action_153 (121) = happyShift action_57
action_153 (122) = happyShift action_58
action_153 (123) = happyShift action_59
action_153 (124) = happyShift action_60
action_153 (137) = happyShift action_164
action_153 (141) = happyShift action_61
action_153 (146) = happyShift action_62
action_153 (147) = happyShift action_63
action_153 (149) = happyShift action_65
action_153 (150) = happyShift action_66
action_153 (151) = happyShift action_67
action_153 (153) = happyShift action_68
action_153 (15) = happyGoto action_157
action_153 (35) = happyGoto action_158
action_153 (41) = happyGoto action_38
action_153 (42) = happyGoto action_39
action_153 (43) = happyGoto action_40
action_153 (44) = happyGoto action_41
action_153 (45) = happyGoto action_42
action_153 (46) = happyGoto action_43
action_153 (47) = happyGoto action_44
action_153 (48) = happyGoto action_45
action_153 (62) = happyGoto action_159
action_153 (63) = happyGoto action_160
action_153 (75) = happyGoto action_161
action_153 (84) = happyGoto action_162
action_153 (85) = happyGoto action_163
action_153 _ = happyFail
action_154 _ = happyReduce_15
action_155 _ = happyReduce_150
action_156 _ = happyReduce_139
action_157 (98) = happyShift action_94
action_157 _ = happyReduce_171
action_158 _ = happyReduce_167
action_159 _ = happyReduce_168
action_160 _ = happyReduce_169
action_161 (141) = happyShift action_27
action_161 (89) = happyGoto action_224
action_161 _ = happyFail
action_162 _ = happyReduce_151
action_163 _ = happyReduce_170
action_164 _ = happyReduce_152
action_165 _ = happyReduce_23
action_166 _ = happyReduce_21
action_167 (98) = happyShift action_53
action_167 (118) = happyShift action_54
action_167 (119) = happyShift action_55
action_167 (120) = happyShift action_56
action_167 (121) = happyShift action_57
action_167 (122) = happyShift action_58
action_167 (123) = happyShift action_59
action_167 (124) = happyShift action_60
action_167 (141) = happyShift action_61
action_167 (146) = happyShift action_62
action_167 (147) = happyShift action_63
action_167 (149) = happyShift action_65
action_167 (150) = happyShift action_66
action_167 (151) = happyShift action_67
action_167 (153) = happyShift action_68
action_167 (15) = happyGoto action_157
action_167 (35) = happyGoto action_158
action_167 (41) = happyGoto action_38
action_167 (42) = happyGoto action_39
action_167 (43) = happyGoto action_40
action_167 (44) = happyGoto action_41
action_167 (45) = happyGoto action_42
action_167 (46) = happyGoto action_43
action_167 (47) = happyGoto action_44
action_167 (48) = happyGoto action_45
action_167 (62) = happyGoto action_159
action_167 (63) = happyGoto action_160
action_167 (84) = happyGoto action_223
action_167 (85) = happyGoto action_163
action_167 _ = happyFail
action_168 _ = happyReduce_22
action_169 _ = happyReduce_19
action_170 _ = happyReduce_20
action_171 _ = happyReduce_12
action_172 _ = happyReduce_26
action_173 (98) = happyShift action_53
action_173 (141) = happyShift action_61
action_173 (15) = happyGoto action_222
action_173 _ = happyFail
action_174 _ = happyReduce_32
action_175 (139) = happyShift action_221
action_175 (87) = happyGoto action_220
action_175 _ = happyFail
action_176 (98) = happyShift action_53
action_176 (113) = happyShift action_135
action_176 (139) = happyShift action_136
action_176 (141) = happyShift action_61
action_176 (143) = happyShift action_137
action_176 (145) = happyShift action_138
action_176 (15) = happyGoto action_122
action_176 (19) = happyGoto action_123
action_176 (20) = happyGoto action_124
action_176 (21) = happyGoto action_125
action_176 (22) = happyGoto action_126
action_176 (23) = happyGoto action_127
action_176 (24) = happyGoto action_128
action_176 (25) = happyGoto action_129
action_176 (26) = happyGoto action_130
action_176 (27) = happyGoto action_131
action_176 (28) = happyGoto action_132
action_176 (29) = happyGoto action_133
action_176 (30) = happyGoto action_219
action_176 _ = happyFail
action_177 _ = happyReduce_129
action_178 _ = happyReduce_132
action_179 _ = happyReduce_130
action_180 _ = happyReduce_58
action_181 (98) = happyShift action_53
action_181 (113) = happyShift action_135
action_181 (139) = happyShift action_136
action_181 (141) = happyShift action_61
action_181 (143) = happyShift action_137
action_181 (145) = happyShift action_138
action_181 (15) = happyGoto action_122
action_181 (26) = happyGoto action_218
action_181 (27) = happyGoto action_131
action_181 (28) = happyGoto action_132
action_181 (29) = happyGoto action_133
action_181 _ = happyFail
action_182 (98) = happyShift action_53
action_182 (113) = happyShift action_135
action_182 (139) = happyShift action_136
action_182 (141) = happyShift action_61
action_182 (143) = happyShift action_137
action_182 (145) = happyShift action_138
action_182 (15) = happyGoto action_122
action_182 (26) = happyGoto action_217
action_182 (27) = happyGoto action_131
action_182 (28) = happyGoto action_132
action_182 (29) = happyGoto action_133
action_182 _ = happyFail
action_183 (98) = happyShift action_53
action_183 (113) = happyShift action_135
action_183 (139) = happyShift action_136
action_183 (141) = happyShift action_61
action_183 (143) = happyShift action_137
action_183 (145) = happyShift action_138
action_183 (15) = happyGoto action_122
action_183 (26) = happyGoto action_216
action_183 (27) = happyGoto action_131
action_183 (28) = happyGoto action_132
action_183 (29) = happyGoto action_133
action_183 _ = happyFail
action_184 (98) = happyShift action_53
action_184 (113) = happyShift action_135
action_184 (139) = happyShift action_136
action_184 (141) = happyShift action_61
action_184 (143) = happyShift action_137
action_184 (145) = happyShift action_138
action_184 (15) = happyGoto action_122
action_184 (25) = happyGoto action_215
action_184 (26) = happyGoto action_130
action_184 (27) = happyGoto action_131
action_184 (28) = happyGoto action_132
action_184 (29) = happyGoto action_133
action_184 _ = happyFail
action_185 (98) = happyShift action_53
action_185 (113) = happyShift action_135
action_185 (139) = happyShift action_136
action_185 (141) = happyShift action_61
action_185 (143) = happyShift action_137
action_185 (145) = happyShift action_138
action_185 (15) = happyGoto action_122
action_185 (25) = happyGoto action_214
action_185 (26) = happyGoto action_130
action_185 (27) = happyGoto action_131
action_185 (28) = happyGoto action_132
action_185 (29) = happyGoto action_133
action_185 _ = happyFail
action_186 (98) = happyShift action_53
action_186 (113) = happyShift action_135
action_186 (139) = happyShift action_136
action_186 (141) = happyShift action_61
action_186 (143) = happyShift action_137
action_186 (145) = happyShift action_138
action_186 (15) = happyGoto action_122
action_186 (24) = happyGoto action_213
action_186 (25) = happyGoto action_129
action_186 (26) = happyGoto action_130
action_186 (27) = happyGoto action_131
action_186 (28) = happyGoto action_132
action_186 (29) = happyGoto action_133
action_186 _ = happyFail
action_187 (98) = happyShift action_53
action_187 (113) = happyShift action_135
action_187 (139) = happyShift action_136
action_187 (141) = happyShift action_61
action_187 (143) = happyShift action_137
action_187 (145) = happyShift action_138
action_187 (15) = happyGoto action_122
action_187 (23) = happyGoto action_212
action_187 (24) = happyGoto action_128
action_187 (25) = happyGoto action_129
action_187 (26) = happyGoto action_130
action_187 (27) = happyGoto action_131
action_187 (28) = happyGoto action_132
action_187 (29) = happyGoto action_133
action_187 _ = happyFail
action_188 (98) = happyShift action_53
action_188 (113) = happyShift action_135
action_188 (139) = happyShift action_136
action_188 (141) = happyShift action_61
action_188 (143) = happyShift action_137
action_188 (145) = happyShift action_138
action_188 (15) = happyGoto action_122
action_188 (22) = happyGoto action_211
action_188 (23) = happyGoto action_127
action_188 (24) = happyGoto action_128
action_188 (25) = happyGoto action_129
action_188 (26) = happyGoto action_130
action_188 (27) = happyGoto action_131
action_188 (28) = happyGoto action_132
action_188 (29) = happyGoto action_133
action_188 _ = happyFail
action_189 (98) = happyShift action_53
action_189 (113) = happyShift action_135
action_189 (139) = happyShift action_136
action_189 (141) = happyShift action_61
action_189 (143) = happyShift action_137
action_189 (145) = happyShift action_138
action_189 (15) = happyGoto action_122
action_189 (21) = happyGoto action_210
action_189 (22) = happyGoto action_126
action_189 (23) = happyGoto action_127
action_189 (24) = happyGoto action_128
action_189 (25) = happyGoto action_129
action_189 (26) = happyGoto action_130
action_189 (27) = happyGoto action_131
action_189 (28) = happyGoto action_132
action_189 (29) = happyGoto action_133
action_189 _ = happyFail
action_190 _ = happyReduce_93
action_191 (136) = happyShift action_209
action_191 _ = happyFail
action_192 _ = happyReduce_136
action_193 _ = happyReduce_109
action_194 _ = happyReduce_107
action_195 (98) = happyShift action_94
action_195 _ = happyReduce_116
action_196 _ = happyReduce_112
action_197 _ = happyReduce_113
action_198 _ = happyReduce_114
action_199 (94) = happyShift action_208
action_199 _ = happyFail
action_200 _ = happyReduce_115
action_201 _ = happyReduce_125
action_202 (141) = happyShift action_27
action_202 (89) = happyGoto action_207
action_202 _ = happyFail
action_203 _ = happyReduce_147
action_204 _ = happyReduce_143
action_205 (90) = happyShift action_206
action_205 (99) = happyShift action_121
action_205 _ = happyFail
action_206 _ = happyReduce_110
action_207 _ = happyReduce_127
action_208 (95) = happyShift action_233
action_208 _ = happyFail
action_209 _ = happyReduce_137
action_210 (107) = happyShift action_188
action_210 _ = happyReduce_44
action_211 (108) = happyShift action_187
action_211 _ = happyReduce_46
action_212 (110) = happyShift action_186
action_212 _ = happyReduce_48
action_213 (143) = happyShift action_184
action_213 (145) = happyShift action_185
action_213 _ = happyReduce_50
action_214 (111) = happyShift action_181
action_214 (112) = happyShift action_182
action_214 (144) = happyShift action_183
action_214 _ = happyReduce_53
action_215 (111) = happyShift action_181
action_215 (112) = happyShift action_182
action_215 (144) = happyShift action_183
action_215 _ = happyReduce_52
action_216 _ = happyReduce_55
action_217 _ = happyReduce_57
action_218 _ = happyReduce_56
action_219 (133) = happyShift action_232
action_219 _ = happyFail
action_220 (133) = happyShift action_231
action_220 _ = happyFail
action_221 _ = happyReduce_174
action_222 (98) = happyShift action_94
action_222 (99) = happyShift action_173
action_222 (16) = happyGoto action_230
action_222 _ = happyReduce_30
action_223 (141) = happyShift action_27
action_223 (39) = happyGoto action_227
action_223 (69) = happyGoto action_228
action_223 (89) = happyGoto action_229
action_223 _ = happyFail
action_224 (93) = happyShift action_226
action_224 (76) = happyGoto action_225
action_224 _ = happyFail
action_225 (155) = happyShift action_247
action_225 (80) = happyGoto action_246
action_225 _ = happyReduce_159
action_226 (94) = happyShift action_244
action_226 (138) = happyShift action_245
action_226 (77) = happyGoto action_241
action_226 (78) = happyGoto action_242
action_226 (79) = happyGoto action_243
action_226 _ = happyFail
action_227 _ = happyReduce_141
action_228 (99) = happyShift action_240
action_228 _ = happyReduce_138
action_229 _ = happyReduce_94
action_230 _ = happyReduce_31
action_231 _ = happyReduce_172
action_232 _ = happyReduce_128
action_233 (128) = happyShift action_238
action_233 (129) = happyShift action_239
action_233 (54) = happyGoto action_234
action_233 (55) = happyGoto action_235
action_233 (56) = happyGoto action_236
action_233 (57) = happyGoto action_237
action_233 _ = happyFail
action_234 (96) = happyShift action_261
action_234 (128) = happyShift action_238
action_234 (129) = happyShift action_239
action_234 (55) = happyGoto action_260
action_234 (56) = happyGoto action_236
action_234 (57) = happyGoto action_237
action_234 _ = happyFail
action_235 _ = happyReduce_117
action_236 (98) = happyShift action_53
action_236 (118) = happyShift action_54
action_236 (119) = happyShift action_55
action_236 (120) = happyShift action_56
action_236 (121) = happyShift action_57
action_236 (122) = happyShift action_58
action_236 (123) = happyShift action_59
action_236 (124) = happyShift action_60
action_236 (125) = happyShift action_19
action_236 (126) = happyShift action_20
action_236 (128) = happyShift action_238
action_236 (129) = happyShift action_239
action_236 (130) = happyShift action_21
action_236 (141) = happyShift action_61
action_236 (146) = happyShift action_62
action_236 (147) = happyShift action_63
action_236 (148) = happyShift action_64
action_236 (149) = happyShift action_65
action_236 (150) = happyShift action_66
action_236 (151) = happyShift action_67
action_236 (153) = happyShift action_68
action_236 (15) = happyGoto action_31
action_236 (33) = happyGoto action_257
action_236 (34) = happyGoto action_34
action_236 (35) = happyGoto action_35
action_236 (36) = happyGoto action_36
action_236 (37) = happyGoto action_37
action_236 (41) = happyGoto action_38
action_236 (42) = happyGoto action_39
action_236 (43) = happyGoto action_40
action_236 (44) = happyGoto action_41
action_236 (45) = happyGoto action_42
action_236 (46) = happyGoto action_43
action_236 (47) = happyGoto action_44
action_236 (48) = happyGoto action_45
action_236 (49) = happyGoto action_46
action_236 (52) = happyGoto action_47
action_236 (57) = happyGoto action_258
action_236 (58) = happyGoto action_259
action_236 (59) = happyGoto action_48
action_236 (61) = happyGoto action_49
action_236 (62) = happyGoto action_50
action_236 (63) = happyGoto action_51
action_236 (85) = happyGoto action_52
action_236 _ = happyFail
action_237 _ = happyReduce_120
action_238 (98) = happyShift action_53
action_238 (113) = happyShift action_135
action_238 (139) = happyShift action_136
action_238 (141) = happyShift action_61
action_238 (143) = happyShift action_137
action_238 (145) = happyShift action_138
action_238 (15) = happyGoto action_122
action_238 (19) = happyGoto action_256
action_238 (20) = happyGoto action_124
action_238 (21) = happyGoto action_125
action_238 (22) = happyGoto action_126
action_238 (23) = happyGoto action_127
action_238 (24) = happyGoto action_128
action_238 (25) = happyGoto action_129
action_238 (26) = happyGoto action_130
action_238 (27) = happyGoto action_131
action_238 (28) = happyGoto action_132
action_238 (29) = happyGoto action_133
action_238 _ = happyFail
action_239 (97) = happyShift action_255
action_239 _ = happyFail
action_240 (141) = happyShift action_27
action_240 (39) = happyGoto action_254
action_240 (89) = happyGoto action_229
action_240 _ = happyFail
action_241 (94) = happyShift action_252
action_241 (99) = happyShift action_253
action_241 _ = happyFail
action_242 _ = happyReduce_155
action_243 (98) = happyShift action_53
action_243 (118) = happyShift action_54
action_243 (119) = happyShift action_55
action_243 (120) = happyShift action_56
action_243 (121) = happyShift action_57
action_243 (122) = happyShift action_58
action_243 (123) = happyShift action_59
action_243 (124) = happyShift action_60
action_243 (141) = happyShift action_61
action_243 (146) = happyShift action_62
action_243 (147) = happyShift action_63
action_243 (149) = happyShift action_65
action_243 (150) = happyShift action_66
action_243 (151) = happyShift action_67
action_243 (153) = happyShift action_68
action_243 (15) = happyGoto action_157
action_243 (35) = happyGoto action_158
action_243 (41) = happyGoto action_38
action_243 (42) = happyGoto action_39
action_243 (43) = happyGoto action_40
action_243 (44) = happyGoto action_41
action_243 (45) = happyGoto action_42
action_243 (46) = happyGoto action_43
action_243 (47) = happyGoto action_44
action_243 (48) = happyGoto action_45
action_243 (62) = happyGoto action_159
action_243 (63) = happyGoto action_160
action_243 (84) = happyGoto action_251
action_243 (85) = happyGoto action_163
action_243 _ = happyFail
action_244 _ = happyReduce_154
action_245 _ = happyReduce_158
action_246 (156) = happyShift action_250
action_246 (81) = happyGoto action_249
action_246 _ = happyReduce_161
action_247 (93) = happyShift action_248
action_247 _ = happyFail
action_248 (98) = happyShift action_53
action_248 (141) = happyShift action_61
action_248 (15) = happyGoto action_268
action_248 (82) = happyGoto action_269
action_248 _ = happyFail
action_249 _ = happyReduce_148
action_250 (93) = happyShift action_267
action_250 _ = happyFail
action_251 (141) = happyShift action_27
action_251 (39) = happyGoto action_266
action_251 (89) = happyGoto action_229
action_251 _ = happyFail
action_252 _ = happyReduce_153
action_253 (138) = happyShift action_245
action_253 (78) = happyGoto action_265
action_253 (79) = happyGoto action_243
action_253 _ = happyFail
action_254 _ = happyReduce_142
action_255 _ = happyReduce_123
action_256 (97) = happyShift action_264
action_256 _ = happyFail
action_257 (141) = happyShift action_27
action_257 (40) = happyGoto action_263
action_257 (89) = happyGoto action_104
action_257 _ = happyFail
action_258 _ = happyReduce_121
action_259 (90) = happyShift action_262
action_259 _ = happyFail
action_260 _ = happyReduce_118
action_261 _ = happyReduce_111
action_262 _ = happyReduce_119
action_263 _ = happyReduce_124
action_264 _ = happyReduce_122
action_265 _ = happyReduce_156
action_266 _ = happyReduce_157
action_267 (140) = happyShift action_273
action_267 (83) = happyGoto action_272
action_267 _ = happyFail
action_268 (98) = happyShift action_94
action_268 _ = happyReduce_163
action_269 (94) = happyShift action_270
action_269 (99) = happyShift action_271
action_269 _ = happyFail
action_270 _ = happyReduce_160
action_271 (98) = happyShift action_53
action_271 (141) = happyShift action_61
action_271 (15) = happyGoto action_276
action_271 _ = happyFail
action_272 (94) = happyShift action_274
action_272 (99) = happyShift action_275
action_272 _ = happyFail
action_273 _ = happyReduce_165
action_274 _ = happyReduce_162
action_275 (140) = happyShift action_277
action_275 _ = happyFail
action_276 (98) = happyShift action_94
action_276 _ = happyReduce_164
action_277 _ = happyReduce_166
happyReduce_1 = happySpecReduce_1 4 happyReduction_1
happyReduction_1 (HappyAbsSyn4 happy_var_1)
= HappyAbsSyn4
((reverse happy_var_1)
)
happyReduction_1 _ = notHappyAtAll
happyReduce_2 = happySpecReduce_0 5 happyReduction_2
happyReduction_2 = HappyAbsSyn4
([]
)
happyReduce_3 = happySpecReduce_2 5 happyReduction_3
happyReduction_3 (HappyAbsSyn6 happy_var_2)
(HappyAbsSyn4 happy_var_1)
= HappyAbsSyn4
(happy_var_2 : happy_var_1
)
happyReduction_3 _ _ = notHappyAtAll
happyReduce_4 = happySpecReduce_2 6 happyReduction_4
happyReduction_4 _
(HappyAbsSyn6 happy_var_1)
= HappyAbsSyn6
(happy_var_1
)
happyReduction_4 _ _ = notHappyAtAll
happyReduce_5 = happySpecReduce_2 6 happyReduction_5
happyReduction_5 _
(HappyAbsSyn6 happy_var_1)
= HappyAbsSyn6
(happy_var_1
)
happyReduction_5 _ _ = notHappyAtAll
happyReduce_6 = happySpecReduce_2 6 happyReduction_6
happyReduction_6 _
(HappyAbsSyn6 happy_var_1)
= HappyAbsSyn6
(happy_var_1
)
happyReduction_6 _ _ = notHappyAtAll
happyReduce_7 = happySpecReduce_2 6 happyReduction_7
happyReduction_7 _
(HappyAbsSyn6 happy_var_1)
= HappyAbsSyn6
(happy_var_1
)
happyReduction_7 _ _ = notHappyAtAll
happyReduce_8 = happySpecReduce_2 6 happyReduction_8
happyReduction_8 _
(HappyAbsSyn6 happy_var_1)
= HappyAbsSyn6
(happy_var_1
)
happyReduction_8 _ _ = notHappyAtAll
happyReduce_9 = happySpecReduce_1 6 happyReduction_9
happyReduction_9 (HappyTerminal (T_pragma happy_var_1))
= HappyAbsSyn6
(Pragma happy_var_1
)
happyReduction_9 _ = notHappyAtAll
happyReduce_10 = happySpecReduce_1 6 happyReduction_10
happyReduction_10 (HappyTerminal (T_include_start happy_var_1))
= HappyAbsSyn6
(IncludeStart happy_var_1
)
happyReduction_10 _ = notHappyAtAll
happyReduce_11 = happySpecReduce_1 6 happyReduction_11
happyReduction_11 _
= HappyAbsSyn6
(IncludeEnd
)
happyReduce_12 = happyReduce 5 7 happyReduction_12
happyReduction_12 (_ `HappyStk`
(HappyAbsSyn4 happy_var_4) `HappyStk`
_ `HappyStk`
(HappyAbsSyn39 happy_var_2) `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn6
(Module happy_var_2 (reverse happy_var_4)
) `HappyStk` happyRest
happyReduce_13 = happySpecReduce_1 8 happyReduction_13
happyReduction_13 (HappyAbsSyn6 happy_var_1)
= HappyAbsSyn6
(happy_var_1
)
happyReduction_13 _ = notHappyAtAll
happyReduce_14 = happySpecReduce_2 8 happyReduction_14
happyReduction_14 (HappyAbsSyn39 happy_var_2)
_
= HappyAbsSyn6
(Forward happy_var_2
)
happyReduction_14 _ _ = notHappyAtAll
happyReduce_15 = happyReduce 4 9 happyReduction_15
happyReduction_15 (_ `HappyStk`
(HappyAbsSyn4 happy_var_3) `HappyStk`
_ `HappyStk`
(HappyAbsSyn10 happy_var_1) `HappyStk`
happyRest)
= HappyAbsSyn6
(let (ids,inherit) = happy_var_1 in Interface ids inherit (reverse happy_var_3)
) `HappyStk` happyRest
happyReduce_16 = happySpecReduce_3 10 happyReduction_16
happyReduction_16 (HappyAbsSyn13 happy_var_3)
(HappyAbsSyn39 happy_var_2)
_
= HappyAbsSyn10
((happy_var_2,happy_var_3)
)
happyReduction_16 _ _ _ = notHappyAtAll
happyReduce_17 = happySpecReduce_0 11 happyReduction_17
happyReduction_17 = HappyAbsSyn4
([]
)
happyReduce_18 = happySpecReduce_2 11 happyReduction_18
happyReduction_18 (HappyAbsSyn6 happy_var_2)
(HappyAbsSyn4 happy_var_1)
= HappyAbsSyn4
(happy_var_2 : happy_var_1
)
happyReduction_18 _ _ = notHappyAtAll
happyReduce_19 = happySpecReduce_2 12 happyReduction_19
happyReduction_19 _
(HappyAbsSyn6 happy_var_1)
= HappyAbsSyn6
(happy_var_1
)
happyReduction_19 _ _ = notHappyAtAll
happyReduce_20 = happySpecReduce_2 12 happyReduction_20
happyReduction_20 _
(HappyAbsSyn6 happy_var_1)
= HappyAbsSyn6
(happy_var_1
)
happyReduction_20 _ _ = notHappyAtAll
happyReduce_21 = happySpecReduce_2 12 happyReduction_21
happyReduction_21 _
(HappyAbsSyn6 happy_var_1)
= HappyAbsSyn6
(happy_var_1
)
happyReduction_21 _ _ = notHappyAtAll
happyReduce_22 = happySpecReduce_2 12 happyReduction_22
happyReduction_22 _
(HappyAbsSyn6 happy_var_1)
= HappyAbsSyn6
(happy_var_1
)
happyReduction_22 _ _ = notHappyAtAll
happyReduce_23 = happySpecReduce_2 12 happyReduction_23
happyReduction_23 _
(HappyAbsSyn6 happy_var_1)
= HappyAbsSyn6
(happy_var_1
)
happyReduction_23 _ _ = notHappyAtAll
happyReduce_24 = happySpecReduce_0 13 happyReduction_24
happyReduction_24 = HappyAbsSyn13
([]
)
happyReduce_25 = happySpecReduce_1 13 happyReduction_25
happyReduction_25 (HappyAbsSyn13 happy_var_1)
= HappyAbsSyn13
(happy_var_1
)
happyReduction_25 _ = notHappyAtAll
happyReduce_26 = happySpecReduce_3 14 happyReduction_26
happyReduction_26 (HappyAbsSyn13 happy_var_3)
(HappyAbsSyn15 happy_var_2)
_
= HappyAbsSyn13
(happy_var_2:(reverse happy_var_3)
)
happyReduction_26 _ _ _ = notHappyAtAll
happyReduce_27 = happySpecReduce_1 15 happyReduction_27
happyReduction_27 (HappyTerminal (T_id happy_var_1))
= HappyAbsSyn15
(happy_var_1
)
happyReduction_27 _ = notHappyAtAll
happyReduce_28 = happySpecReduce_2 15 happyReduction_28
happyReduction_28 (HappyTerminal (T_id happy_var_2))
_
= HappyAbsSyn15
(("::"++ happy_var_2)
)
happyReduction_28 _ _ = notHappyAtAll
happyReduce_29 = happySpecReduce_3 15 happyReduction_29
happyReduction_29 (HappyTerminal (T_id happy_var_3))
_
(HappyAbsSyn15 happy_var_1)
= HappyAbsSyn15
(happy_var_1 ++ ':':':':happy_var_3
)
happyReduction_29 _ _ _ = notHappyAtAll
happyReduce_30 = happySpecReduce_0 16 happyReduction_30
happyReduction_30 = HappyAbsSyn13
([]
)
happyReduce_31 = happySpecReduce_3 16 happyReduction_31
happyReduction_31 (HappyAbsSyn13 happy_var_3)
(HappyAbsSyn15 happy_var_2)
_
= HappyAbsSyn13
(happy_var_2 : happy_var_3
)
happyReduction_31 _ _ _ = notHappyAtAll
happyReduce_32 = happyReduce 5 17 happyReduction_32
happyReduction_32 ((HappyAbsSyn19 happy_var_5) `HappyStk`
_ `HappyStk`
(HappyAbsSyn39 happy_var_3) `HappyStk`
(HappyAbsSyn18 happy_var_2) `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn6
(Constant happy_var_3 [] happy_var_2 happy_var_5
) `HappyStk` happyRest
happyReduce_33 = happySpecReduce_1 18 happyReduction_33
happyReduction_33 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_33 _ = notHappyAtAll
happyReduce_34 = happySpecReduce_1 18 happyReduction_34
happyReduction_34 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_34 _ = notHappyAtAll
happyReduce_35 = happySpecReduce_1 18 happyReduction_35
happyReduction_35 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_35 _ = notHappyAtAll
happyReduce_36 = happySpecReduce_1 18 happyReduction_36
happyReduction_36 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_36 _ = notHappyAtAll
happyReduce_37 = happySpecReduce_1 18 happyReduction_37
happyReduction_37 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_37 _ = notHappyAtAll
happyReduce_38 = happySpecReduce_1 18 happyReduction_38
happyReduction_38 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_38 _ = notHappyAtAll
happyReduce_39 = happySpecReduce_1 18 happyReduction_39
happyReduction_39 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_39 _ = notHappyAtAll
happyReduce_40 = happySpecReduce_1 18 happyReduction_40
happyReduction_40 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_40 _ = notHappyAtAll
happyReduce_41 = happySpecReduce_1 18 happyReduction_41
happyReduction_41 (HappyAbsSyn15 happy_var_1)
= HappyAbsSyn18
(TyName happy_var_1 Nothing
)
happyReduction_41 _ = notHappyAtAll
happyReduce_42 = happySpecReduce_1 19 happyReduction_42
happyReduction_42 (HappyAbsSyn19 happy_var_1)
= HappyAbsSyn19
(happy_var_1
)
happyReduction_42 _ = notHappyAtAll
happyReduce_43 = happySpecReduce_1 20 happyReduction_43
happyReduction_43 (HappyAbsSyn19 happy_var_1)
= HappyAbsSyn19
(happy_var_1
)
happyReduction_43 _ = notHappyAtAll
happyReduce_44 = happySpecReduce_3 20 happyReduction_44
happyReduction_44 (HappyAbsSyn19 happy_var_3)
_
(HappyAbsSyn19 happy_var_1)
= HappyAbsSyn19
(Binary Or happy_var_1 happy_var_3
)
happyReduction_44 _ _ _ = notHappyAtAll
happyReduce_45 = happySpecReduce_1 21 happyReduction_45
happyReduction_45 (HappyAbsSyn19 happy_var_1)
= HappyAbsSyn19
(happy_var_1
)
happyReduction_45 _ = notHappyAtAll
happyReduce_46 = happySpecReduce_3 21 happyReduction_46
happyReduction_46 (HappyAbsSyn19 happy_var_3)
_
(HappyAbsSyn19 happy_var_1)
= HappyAbsSyn19
(Binary Xor happy_var_1 happy_var_3
)
happyReduction_46 _ _ _ = notHappyAtAll
happyReduce_47 = happySpecReduce_1 22 happyReduction_47
happyReduction_47 (HappyAbsSyn19 happy_var_1)
= HappyAbsSyn19
(happy_var_1
)
happyReduction_47 _ = notHappyAtAll
happyReduce_48 = happySpecReduce_3 22 happyReduction_48
happyReduction_48 (HappyAbsSyn19 happy_var_3)
_
(HappyAbsSyn19 happy_var_1)
= HappyAbsSyn19
(Binary And happy_var_1 happy_var_3
)
happyReduction_48 _ _ _ = notHappyAtAll
happyReduce_49 = happySpecReduce_1 23 happyReduction_49
happyReduction_49 (HappyAbsSyn19 happy_var_1)
= HappyAbsSyn19
(happy_var_1
)
happyReduction_49 _ = notHappyAtAll
happyReduce_50 = happySpecReduce_3 23 happyReduction_50
happyReduction_50 (HappyAbsSyn19 happy_var_3)
(HappyTerminal (T_shift happy_var_2))
(HappyAbsSyn19 happy_var_1)
= HappyAbsSyn19
(Binary (Shift happy_var_2) happy_var_1 happy_var_3
)
happyReduction_50 _ _ _ = notHappyAtAll
happyReduce_51 = happySpecReduce_1 24 happyReduction_51
happyReduction_51 (HappyAbsSyn19 happy_var_1)
= HappyAbsSyn19
(happy_var_1
)
happyReduction_51 _ = notHappyAtAll
happyReduce_52 = happySpecReduce_3 24 happyReduction_52
happyReduction_52 (HappyAbsSyn19 happy_var_3)
_
(HappyAbsSyn19 happy_var_1)
= HappyAbsSyn19
(Binary Add happy_var_1 happy_var_3
)
happyReduction_52 _ _ _ = notHappyAtAll
happyReduce_53 = happySpecReduce_3 24 happyReduction_53
happyReduction_53 (HappyAbsSyn19 happy_var_3)
_
(HappyAbsSyn19 happy_var_1)
= HappyAbsSyn19
(Binary Sub happy_var_1 happy_var_3
)
happyReduction_53 _ _ _ = notHappyAtAll
happyReduce_54 = happySpecReduce_1 25 happyReduction_54
happyReduction_54 (HappyAbsSyn19 happy_var_1)
= HappyAbsSyn19
(happy_var_1
)
happyReduction_54 _ = notHappyAtAll
happyReduce_55 = happySpecReduce_3 25 happyReduction_55
happyReduction_55 (HappyAbsSyn19 happy_var_3)
_
(HappyAbsSyn19 happy_var_1)
= HappyAbsSyn19
(Binary Mul happy_var_1 happy_var_3
)
happyReduction_55 _ _ _ = notHappyAtAll
happyReduce_56 = happySpecReduce_3 25 happyReduction_56
happyReduction_56 (HappyAbsSyn19 happy_var_3)
_
(HappyAbsSyn19 happy_var_1)
= HappyAbsSyn19
(Binary Div happy_var_1 happy_var_3
)
happyReduction_56 _ _ _ = notHappyAtAll
happyReduce_57 = happySpecReduce_3 25 happyReduction_57
happyReduction_57 (HappyAbsSyn19 happy_var_3)
_
(HappyAbsSyn19 happy_var_1)
= HappyAbsSyn19
(Binary Mod happy_var_1 happy_var_3
)
happyReduction_57 _ _ _ = notHappyAtAll
happyReduce_58 = happySpecReduce_2 26 happyReduction_58
happyReduction_58 (HappyAbsSyn19 happy_var_2)
(HappyAbsSyn27 happy_var_1)
= HappyAbsSyn19
(Unary happy_var_1 happy_var_2
)
happyReduction_58 _ _ = notHappyAtAll
happyReduce_59 = happySpecReduce_1 26 happyReduction_59
happyReduction_59 (HappyAbsSyn19 happy_var_1)
= HappyAbsSyn19
(happy_var_1
)
happyReduction_59 _ = notHappyAtAll
happyReduce_60 = happySpecReduce_1 27 happyReduction_60
happyReduction_60 _
= HappyAbsSyn27
(Minus
)
happyReduce_61 = happySpecReduce_1 27 happyReduction_61
happyReduction_61 _
= HappyAbsSyn27
(Plus
)
happyReduce_62 = happySpecReduce_1 27 happyReduction_62
happyReduction_62 _
= HappyAbsSyn27
(Not
)
happyReduce_63 = happySpecReduce_1 28 happyReduction_63
happyReduction_63 (HappyAbsSyn15 happy_var_1)
= HappyAbsSyn19
(Var happy_var_1
)
happyReduction_63 _ = notHappyAtAll
happyReduce_64 = happySpecReduce_1 28 happyReduction_64
happyReduction_64 (HappyAbsSyn29 happy_var_1)
= HappyAbsSyn19
(Lit happy_var_1
)
happyReduction_64 _ = notHappyAtAll
happyReduce_65 = happySpecReduce_1 29 happyReduction_65
happyReduction_65 (HappyTerminal (T_literal happy_var_1))
= HappyAbsSyn29
(happy_var_1
)
happyReduction_65 _ = notHappyAtAll
happyReduce_66 = happySpecReduce_1 30 happyReduction_66
happyReduction_66 (HappyAbsSyn19 happy_var_1)
= HappyAbsSyn19
(happy_var_1
)
happyReduction_66 _ = notHappyAtAll
happyReduce_67 = happySpecReduce_2 31 happyReduction_67
happyReduction_67 (HappyAbsSyn32 happy_var_2)
_
= HappyAbsSyn6
(let (spec, decls) = happy_var_2 in Typedef spec [] decls
)
happyReduction_67 _ _ = notHappyAtAll
happyReduce_68 = happySpecReduce_1 31 happyReduction_68
happyReduction_68 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn6
(TypeDecl happy_var_1
)
happyReduction_68 _ = notHappyAtAll
happyReduce_69 = happySpecReduce_1 31 happyReduction_69
happyReduction_69 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn6
(TypeDecl happy_var_1
)
happyReduction_69 _ = notHappyAtAll
happyReduce_70 = happySpecReduce_1 31 happyReduction_70
happyReduction_70 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn6
(TypeDecl happy_var_1
)
happyReduction_70 _ = notHappyAtAll
happyReduce_71 = happySpecReduce_2 32 happyReduction_71
happyReduction_71 (HappyAbsSyn38 happy_var_2)
(HappyAbsSyn18 happy_var_1)
= HappyAbsSyn32
((happy_var_1,happy_var_2)
)
happyReduction_71 _ _ = notHappyAtAll
happyReduce_72 = happySpecReduce_1 33 happyReduction_72
happyReduction_72 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_72 _ = notHappyAtAll
happyReduce_73 = happySpecReduce_1 33 happyReduction_73
happyReduction_73 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_73 _ = notHappyAtAll
happyReduce_74 = happySpecReduce_1 34 happyReduction_74
happyReduction_74 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_74 _ = notHappyAtAll
happyReduce_75 = happySpecReduce_1 34 happyReduction_75
happyReduction_75 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_75 _ = notHappyAtAll
happyReduce_76 = happySpecReduce_1 34 happyReduction_76
happyReduction_76 (HappyAbsSyn15 happy_var_1)
= HappyAbsSyn18
(TyName happy_var_1 Nothing
)
happyReduction_76 _ = notHappyAtAll
happyReduce_77 = happySpecReduce_1 35 happyReduction_77
happyReduction_77 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_77 _ = notHappyAtAll
happyReduce_78 = happySpecReduce_1 35 happyReduction_78
happyReduction_78 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_78 _ = notHappyAtAll
happyReduce_79 = happySpecReduce_1 35 happyReduction_79
happyReduction_79 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_79 _ = notHappyAtAll
happyReduce_80 = happySpecReduce_1 35 happyReduction_80
happyReduction_80 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_80 _ = notHappyAtAll
happyReduce_81 = happySpecReduce_1 35 happyReduction_81
happyReduction_81 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_81 _ = notHappyAtAll
happyReduce_82 = happySpecReduce_1 35 happyReduction_82
happyReduction_82 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_82 _ = notHappyAtAll
happyReduce_83 = happySpecReduce_1 35 happyReduction_83
happyReduction_83 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_83 _ = notHappyAtAll
happyReduce_84 = happySpecReduce_1 35 happyReduction_84
happyReduction_84 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_84 _ = notHappyAtAll
happyReduce_85 = happySpecReduce_1 36 happyReduction_85
happyReduction_85 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_85 _ = notHappyAtAll
happyReduce_86 = happySpecReduce_1 36 happyReduction_86
happyReduction_86 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_86 _ = notHappyAtAll
happyReduce_87 = happySpecReduce_1 36 happyReduction_87
happyReduction_87 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_87 _ = notHappyAtAll
happyReduce_88 = happySpecReduce_1 36 happyReduction_88
happyReduction_88 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_88 _ = notHappyAtAll
happyReduce_89 = happySpecReduce_1 37 happyReduction_89
happyReduction_89 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_89 _ = notHappyAtAll
happyReduce_90 = happySpecReduce_1 37 happyReduction_90
happyReduction_90 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_90 _ = notHappyAtAll
happyReduce_91 = happySpecReduce_1 37 happyReduction_91
happyReduction_91 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_91 _ = notHappyAtAll
happyReduce_92 = happySpecReduce_1 38 happyReduction_92
happyReduction_92 (HappyAbsSyn39 happy_var_1)
= HappyAbsSyn38
([happy_var_1]
)
happyReduction_92 _ = notHappyAtAll
happyReduce_93 = happySpecReduce_3 38 happyReduction_93
happyReduction_93 (HappyAbsSyn39 happy_var_3)
_
(HappyAbsSyn38 happy_var_1)
= HappyAbsSyn38
(happy_var_3 : happy_var_1
)
happyReduction_93 _ _ _ = notHappyAtAll
happyReduce_94 = happySpecReduce_1 39 happyReduction_94
happyReduction_94 (HappyAbsSyn39 happy_var_1)
= HappyAbsSyn39
(happy_var_1
)
happyReduction_94 _ = notHappyAtAll
happyReduce_95 = happySpecReduce_1 40 happyReduction_95
happyReduction_95 (HappyAbsSyn39 happy_var_1)
= HappyAbsSyn39
(happy_var_1
)
happyReduction_95 _ = notHappyAtAll
happyReduce_96 = happySpecReduce_2 40 happyReduction_96
happyReduction_96 (HappyAbsSyn65 happy_var_2)
(HappyAbsSyn39 happy_var_1)
= HappyAbsSyn39
(ArrayId happy_var_1 happy_var_2
)
happyReduction_96 _ _ = notHappyAtAll
happyReduce_97 = happySpecReduce_1 41 happyReduction_97
happyReduction_97 (HappyTerminal (T_float happy_var_1))
= HappyAbsSyn18
(TyFloat happy_var_1
)
happyReduction_97 _ = notHappyAtAll
happyReduce_98 = happySpecReduce_1 42 happyReduction_98
happyReduction_98 (HappyTerminal (T_int happy_var_1))
= HappyAbsSyn18
(TyInteger happy_var_1
)
happyReduction_98 _ = notHappyAtAll
happyReduce_99 = happySpecReduce_2 42 happyReduction_99
happyReduction_99 (HappyTerminal (T_int happy_var_2))
_
= HappyAbsSyn18
(TyApply (TySigned True) (TyInteger happy_var_2)
)
happyReduction_99 _ _ = notHappyAtAll
happyReduce_100 = happySpecReduce_2 42 happyReduction_100
happyReduction_100 (HappyTerminal (T_int happy_var_2))
_
= HappyAbsSyn18
(TyApply (TySigned False) (TyInteger happy_var_2)
)
happyReduction_100 _ _ = notHappyAtAll
happyReduce_101 = happySpecReduce_1 43 happyReduction_101
happyReduction_101 _
= HappyAbsSyn18
(TyChar
)
happyReduce_102 = happySpecReduce_1 44 happyReduction_102
happyReduction_102 _
= HappyAbsSyn18
(TyWChar
)
happyReduce_103 = happySpecReduce_1 45 happyReduction_103
happyReduction_103 _
= HappyAbsSyn18
(TyBool
)
happyReduce_104 = happySpecReduce_1 46 happyReduction_104
happyReduction_104 _
= HappyAbsSyn18
(TyOctet
)
happyReduce_105 = happySpecReduce_1 47 happyReduction_105
happyReduction_105 _
= HappyAbsSyn18
(TyAny
)
happyReduce_106 = happySpecReduce_1 48 happyReduction_106
happyReduction_106 _
= HappyAbsSyn18
(TyObject
)
happyReduce_107 = happyReduce 5 49 happyReduction_107
happyReduction_107 (_ `HappyStk`
(HappyAbsSyn50 happy_var_4) `HappyStk`
_ `HappyStk`
(HappyAbsSyn39 happy_var_2) `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn18
(TyStruct (Just happy_var_2) happy_var_4 Nothing
) `HappyStk` happyRest
happyReduce_108 = happySpecReduce_1 50 happyReduction_108
happyReduction_108 (HappyAbsSyn51 happy_var_1)
= HappyAbsSyn50
([happy_var_1]
)
happyReduction_108 _ = notHappyAtAll
happyReduce_109 = happySpecReduce_2 50 happyReduction_109
happyReduction_109 (HappyAbsSyn51 happy_var_2)
(HappyAbsSyn50 happy_var_1)
= HappyAbsSyn50
(happy_var_2:happy_var_1
)
happyReduction_109 _ _ = notHappyAtAll
happyReduce_110 = happySpecReduce_3 51 happyReduction_110
happyReduction_110 _
(HappyAbsSyn38 happy_var_2)
(HappyAbsSyn18 happy_var_1)
= HappyAbsSyn51
((happy_var_1,[],happy_var_2)
)
happyReduction_110 _ _ _ = notHappyAtAll
happyReduce_111 = happyReduce 9 52 happyReduction_111
happyReduction_111 (_ `HappyStk`
(HappyAbsSyn54 happy_var_8) `HappyStk`
_ `HappyStk`
_ `HappyStk`
(HappyAbsSyn18 happy_var_5) `HappyStk`
_ `HappyStk`
_ `HappyStk`
(HappyAbsSyn39 happy_var_2) `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn18
(TyUnion (Just happy_var_2) happy_var_5 (Id "tagged_union") Nothing (reverse happy_var_8)
) `HappyStk` happyRest
happyReduce_112 = happySpecReduce_1 53 happyReduction_112
happyReduction_112 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_112 _ = notHappyAtAll
happyReduce_113 = happySpecReduce_1 53 happyReduction_113
happyReduction_113 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_113 _ = notHappyAtAll
happyReduce_114 = happySpecReduce_1 53 happyReduction_114
happyReduction_114 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_114 _ = notHappyAtAll
happyReduce_115 = happySpecReduce_1 53 happyReduction_115
happyReduction_115 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_115 _ = notHappyAtAll
happyReduce_116 = happySpecReduce_1 53 happyReduction_116
happyReduction_116 (HappyAbsSyn15 happy_var_1)
= HappyAbsSyn18
(TyName happy_var_1 Nothing
)
happyReduction_116 _ = notHappyAtAll
happyReduce_117 = happySpecReduce_1 54 happyReduction_117
happyReduction_117 (HappyAbsSyn55 happy_var_1)
= HappyAbsSyn54
([happy_var_1]
)
happyReduction_117 _ = notHappyAtAll
happyReduce_118 = happySpecReduce_2 54 happyReduction_118
happyReduction_118 (HappyAbsSyn55 happy_var_2)
(HappyAbsSyn54 happy_var_1)
= HappyAbsSyn54
(happy_var_2:happy_var_1
)
happyReduction_118 _ _ = notHappyAtAll
happyReduce_119 = happySpecReduce_3 55 happyReduction_119
happyReduction_119 _
(HappyAbsSyn58 happy_var_2)
(HappyAbsSyn56 happy_var_1)
= HappyAbsSyn55
(Switch happy_var_1 (Just happy_var_2)
)
happyReduction_119 _ _ _ = notHappyAtAll
happyReduce_120 = happySpecReduce_1 56 happyReduction_120
happyReduction_120 (HappyAbsSyn57 happy_var_1)
= HappyAbsSyn56
([happy_var_1]
)
happyReduction_120 _ = notHappyAtAll
happyReduce_121 = happySpecReduce_2 56 happyReduction_121
happyReduction_121 (HappyAbsSyn57 happy_var_2)
(HappyAbsSyn56 happy_var_1)
= HappyAbsSyn56
(happy_var_2:happy_var_1
)
happyReduction_121 _ _ = notHappyAtAll
happyReduce_122 = happySpecReduce_3 57 happyReduction_122
happyReduction_122 _
(HappyAbsSyn19 happy_var_2)
_
= HappyAbsSyn57
(Case [happy_var_2]
)
happyReduction_122 _ _ _ = notHappyAtAll
happyReduce_123 = happySpecReduce_2 57 happyReduction_123
happyReduction_123 _
_
= HappyAbsSyn57
(Default
)
happyReduce_124 = happySpecReduce_2 58 happyReduction_124
happyReduction_124 (HappyAbsSyn39 happy_var_2)
(HappyAbsSyn18 happy_var_1)
= HappyAbsSyn58
((Param happy_var_2 happy_var_1 [])
)
happyReduction_124 _ _ = notHappyAtAll
happyReduce_125 = happyReduce 5 59 happyReduction_125
happyReduction_125 (_ `HappyStk`
(HappyAbsSyn60 happy_var_4) `HappyStk`
_ `HappyStk`
(HappyAbsSyn39 happy_var_2) `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn18
(TyEnum (Just happy_var_2) (reverse happy_var_4)
) `HappyStk` happyRest
happyReduce_126 = happySpecReduce_1 60 happyReduction_126
happyReduction_126 (HappyAbsSyn39 happy_var_1)
= HappyAbsSyn60
([(happy_var_1,[],Nothing)]
)
happyReduction_126 _ = notHappyAtAll
happyReduce_127 = happySpecReduce_3 60 happyReduction_127
happyReduction_127 (HappyAbsSyn39 happy_var_3)
_
(HappyAbsSyn60 happy_var_1)
= HappyAbsSyn60
(((happy_var_3,[],Nothing):happy_var_1)
)
happyReduction_127 _ _ _ = notHappyAtAll
happyReduce_128 = happyReduce 6 61 happyReduction_128
happyReduction_128 (_ `HappyStk`
(HappyAbsSyn19 happy_var_5) `HappyStk`
_ `HappyStk`
(HappyAbsSyn18 happy_var_3) `HappyStk`
_ `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn18
(TySequence happy_var_3 (Just happy_var_5)
) `HappyStk` happyRest
happyReduce_129 = happyReduce 4 61 happyReduction_129
happyReduction_129 (_ `HappyStk`
(HappyAbsSyn18 happy_var_3) `HappyStk`
_ `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn18
(TySequence happy_var_3 Nothing
) `HappyStk` happyRest
happyReduce_130 = happyReduce 4 62 happyReduction_130
happyReduction_130 (_ `HappyStk`
(HappyAbsSyn19 happy_var_3) `HappyStk`
_ `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn18
(TyString (Just happy_var_3)
) `HappyStk` happyRest
happyReduce_131 = happySpecReduce_1 62 happyReduction_131
happyReduction_131 _
= HappyAbsSyn18
(TyString Nothing
)
happyReduce_132 = happyReduce 4 63 happyReduction_132
happyReduction_132 (_ `HappyStk`
(HappyAbsSyn19 happy_var_3) `HappyStk`
_ `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn18
(TyWString (Just happy_var_3)
) `HappyStk` happyRest
happyReduce_133 = happySpecReduce_1 63 happyReduction_133
happyReduction_133 _
= HappyAbsSyn18
(TyWString Nothing
)
happyReduce_134 = happySpecReduce_2 64 happyReduction_134
happyReduction_134 (HappyAbsSyn65 happy_var_2)
(HappyAbsSyn39 happy_var_1)
= HappyAbsSyn64
((happy_var_1, reverse happy_var_2)
)
happyReduction_134 _ _ = notHappyAtAll
happyReduce_135 = happySpecReduce_1 65 happyReduction_135
happyReduction_135 (HappyAbsSyn19 happy_var_1)
= HappyAbsSyn65
([happy_var_1]
)
happyReduction_135 _ = notHappyAtAll
happyReduce_136 = happySpecReduce_2 65 happyReduction_136
happyReduction_136 (HappyAbsSyn19 happy_var_2)
(HappyAbsSyn65 happy_var_1)
= HappyAbsSyn65
(happy_var_2:happy_var_1
)
happyReduction_136 _ _ = notHappyAtAll
happyReduce_137 = happySpecReduce_3 66 happyReduction_137
happyReduction_137 _
(HappyAbsSyn19 happy_var_2)
_
= HappyAbsSyn19
(happy_var_2
)
happyReduction_137 _ _ _ = notHappyAtAll
happyReduce_138 = happyReduce 4 67 happyReduction_138
happyReduction_138 ((HappyAbsSyn38 happy_var_4) `HappyStk`
(HappyAbsSyn18 happy_var_3) `HappyStk`
_ `HappyStk`
(HappyAbsSyn68 happy_var_1) `HappyStk`
happyRest)
= HappyAbsSyn6
(Attribute (reverse happy_var_4) happy_var_1 happy_var_3
) `HappyStk` happyRest
happyReduce_139 = happySpecReduce_1 68 happyReduction_139
happyReduction_139 _
= HappyAbsSyn68
(True
)
happyReduce_140 = happySpecReduce_0 68 happyReduction_140
happyReduction_140 = HappyAbsSyn68
(False
)
happyReduce_141 = happySpecReduce_1 69 happyReduction_141
happyReduction_141 (HappyAbsSyn39 happy_var_1)
= HappyAbsSyn38
([happy_var_1]
)
happyReduction_141 _ = notHappyAtAll
happyReduce_142 = happySpecReduce_3 69 happyReduction_142
happyReduction_142 (HappyAbsSyn39 happy_var_3)
_
(HappyAbsSyn38 happy_var_1)
= HappyAbsSyn38
(happy_var_3:happy_var_1
)
happyReduction_142 _ _ _ = notHappyAtAll
happyReduce_143 = happyReduce 5 70 happyReduction_143
happyReduction_143 (_ `HappyStk`
(HappyAbsSyn50 happy_var_4) `HappyStk`
_ `HappyStk`
(HappyAbsSyn39 happy_var_2) `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn6
(Exception happy_var_2 happy_var_4
) `HappyStk` happyRest
happyReduce_144 = happySpecReduce_0 71 happyReduction_144
happyReduction_144 = HappyAbsSyn50
([]
)
happyReduce_145 = happySpecReduce_1 71 happyReduction_145
happyReduction_145 (HappyAbsSyn50 happy_var_1)
= HappyAbsSyn50
(happy_var_1
)
happyReduction_145 _ = notHappyAtAll
happyReduce_146 = happySpecReduce_1 72 happyReduction_146
happyReduction_146 (HappyAbsSyn51 happy_var_1)
= HappyAbsSyn50
([happy_var_1]
)
happyReduction_146 _ = notHappyAtAll
happyReduce_147 = happySpecReduce_2 72 happyReduction_147
happyReduction_147 (HappyAbsSyn51 happy_var_2)
(HappyAbsSyn50 happy_var_1)
= HappyAbsSyn50
(happy_var_2:happy_var_1
)
happyReduction_147 _ _ = notHappyAtAll
happyReduce_148 = happyReduce 6 73 happyReduction_148
happyReduction_148 ((HappyAbsSyn81 happy_var_6) `HappyStk`
(HappyAbsSyn80 happy_var_5) `HappyStk`
(HappyAbsSyn76 happy_var_4) `HappyStk`
(HappyAbsSyn39 happy_var_3) `HappyStk`
(HappyAbsSyn18 happy_var_2) `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn6
(Operation (FunId happy_var_3 Nothing happy_var_4) happy_var_2 happy_var_5 happy_var_6
) `HappyStk` happyRest
happyReduce_149 = happySpecReduce_0 74 happyReduction_149
happyReduction_149 = HappyAbsSyn68
(False
)
happyReduce_150 = happySpecReduce_1 74 happyReduction_150
happyReduction_150 _
= HappyAbsSyn68
(True
)
happyReduce_151 = happySpecReduce_1 75 happyReduction_151
happyReduction_151 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_151 _ = notHappyAtAll
happyReduce_152 = happySpecReduce_1 75 happyReduction_152
happyReduction_152 _
= HappyAbsSyn18
(TyVoid
)
happyReduce_153 = happySpecReduce_3 76 happyReduction_153
happyReduction_153 _
(HappyAbsSyn76 happy_var_2)
_
= HappyAbsSyn76
((reverse happy_var_2)
)
happyReduction_153 _ _ _ = notHappyAtAll
happyReduce_154 = happySpecReduce_2 76 happyReduction_154
happyReduction_154 _
_
= HappyAbsSyn76
([]
)
happyReduce_155 = happySpecReduce_1 77 happyReduction_155
happyReduction_155 (HappyAbsSyn78 happy_var_1)
= HappyAbsSyn76
([happy_var_1]
)
happyReduction_155 _ = notHappyAtAll
happyReduce_156 = happySpecReduce_3 77 happyReduction_156
happyReduction_156 (HappyAbsSyn78 happy_var_3)
_
(HappyAbsSyn76 happy_var_1)
= HappyAbsSyn76
(happy_var_3:happy_var_1
)
happyReduction_156 _ _ _ = notHappyAtAll
happyReduce_157 = happySpecReduce_3 78 happyReduction_157
happyReduction_157 (HappyAbsSyn39 happy_var_3)
(HappyAbsSyn18 happy_var_2)
(HappyAbsSyn79 happy_var_1)
= HappyAbsSyn78
(Param happy_var_3 happy_var_2 [happy_var_1]
)
happyReduction_157 _ _ _ = notHappyAtAll
happyReduce_158 = happySpecReduce_1 79 happyReduction_158
happyReduction_158 (HappyTerminal (T_mode happy_var_1))
= HappyAbsSyn79
(Mode happy_var_1
)
happyReduction_158 _ = notHappyAtAll
happyReduce_159 = happySpecReduce_0 80 happyReduction_159
happyReduction_159 = HappyAbsSyn80
(Nothing
)
happyReduce_160 = happyReduce 4 80 happyReduction_160
happyReduction_160 (_ `HappyStk`
(HappyAbsSyn82 happy_var_3) `HappyStk`
_ `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn80
(Just (reverse happy_var_3)
) `HappyStk` happyRest
happyReduce_161 = happySpecReduce_0 81 happyReduction_161
happyReduction_161 = HappyAbsSyn81
(Nothing
)
happyReduce_162 = happyReduce 4 81 happyReduction_162
happyReduction_162 (_ `HappyStk`
(HappyAbsSyn82 happy_var_3) `HappyStk`
_ `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn81
(Just (reverse happy_var_3)
) `HappyStk` happyRest
happyReduce_163 = happySpecReduce_1 82 happyReduction_163
happyReduction_163 (HappyAbsSyn15 happy_var_1)
= HappyAbsSyn82
([happy_var_1]
)
happyReduction_163 _ = notHappyAtAll
happyReduce_164 = happySpecReduce_3 82 happyReduction_164
happyReduction_164 (HappyAbsSyn15 happy_var_3)
_
(HappyAbsSyn82 happy_var_1)
= HappyAbsSyn82
(happy_var_3:happy_var_1
)
happyReduction_164 _ _ _ = notHappyAtAll
happyReduce_165 = happySpecReduce_1 83 happyReduction_165
happyReduction_165 (HappyTerminal (T_string_lit happy_var_1))
= HappyAbsSyn82
([happy_var_1]
)
happyReduction_165 _ = notHappyAtAll
happyReduce_166 = happySpecReduce_3 83 happyReduction_166
happyReduction_166 (HappyTerminal (T_string_lit happy_var_3))
_
(HappyAbsSyn82 happy_var_1)
= HappyAbsSyn82
(happy_var_3:happy_var_1
)
happyReduction_166 _ _ _ = notHappyAtAll
happyReduce_167 = happySpecReduce_1 84 happyReduction_167
happyReduction_167 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_167 _ = notHappyAtAll
happyReduce_168 = happySpecReduce_1 84 happyReduction_168
happyReduction_168 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_168 _ = notHappyAtAll
happyReduce_169 = happySpecReduce_1 84 happyReduction_169
happyReduction_169 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_169 _ = notHappyAtAll
happyReduce_170 = happySpecReduce_1 84 happyReduction_170
happyReduction_170 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_170 _ = notHappyAtAll
happyReduce_171 = happySpecReduce_1 84 happyReduction_171
happyReduction_171 (HappyAbsSyn15 happy_var_1)
= HappyAbsSyn18
(TyName happy_var_1 Nothing
)
happyReduction_171 _ = notHappyAtAll
happyReduce_172 = happyReduce 6 85 happyReduction_172
happyReduction_172 (_ `HappyStk`
(HappyAbsSyn87 happy_var_5) `HappyStk`
_ `HappyStk`
(HappyAbsSyn19 happy_var_3) `HappyStk`
_ `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn18
(TyFixed (Just (happy_var_3,happy_var_5))
) `HappyStk` happyRest
happyReduce_173 = happySpecReduce_1 86 happyReduction_173
happyReduction_173 _
= HappyAbsSyn18
(TyFixed Nothing
)
happyReduce_174 = happySpecReduce_1 87 happyReduction_174
happyReduction_174 (HappyTerminal (T_literal happy_var_1))
= HappyAbsSyn87
(let (IntegerLit il) = happy_var_1 in il
)
happyReduction_174 _ = notHappyAtAll
happyReduce_175 = happySpecReduce_1 88 happyReduction_175
happyReduction_175 (HappyTerminal (T_string_lit happy_var_1))
= HappyAbsSyn15
(happy_var_1
)
happyReduction_175 _ = notHappyAtAll
happyReduce_176 = happySpecReduce_1 89 happyReduction_176
happyReduction_176 (HappyTerminal (T_id happy_var_1))
= HappyAbsSyn39
((Id happy_var_1)
)
happyReduction_176 _ = notHappyAtAll
happyNewToken action sts stk
= lexIDL(\tk ->
let cont i = action i i tk (HappyState action) sts stk in
case tk of {
T_eof -> action 162 162 (error "reading EOF!") (HappyState action) sts stk;
T_semi -> cont 90;
T_module -> cont 91;
T_interface -> cont 92;
T_oparen -> cont 93;
T_cparen -> cont 94;
T_ocurly -> cont 95;
T_ccurly -> cont 96;
T_colon -> cont 97;
T_dcolon -> cont 98;
T_comma -> cont 99;
T_dot -> cont 100;
T_const -> cont 101;
T_equal -> cont 102;
T_eqeq -> cont 103;
T_neq -> cont 104;
T_or -> cont 105;
T_rel_or -> cont 106;
T_xor -> cont 107;
T_and -> cont 108;
T_rel_and -> cont 109;
T_shift happy_dollar_dollar -> cont 110;
T_div -> cont 111;
T_mod -> cont 112;
T_not -> cont 113;
T_negate -> cont 114;
T_question -> cont 115;
T_typedef -> cont 116;
T_type happy_dollar_dollar -> cont 117;
T_float happy_dollar_dollar -> cont 118;
T_int happy_dollar_dollar -> cont 119;
T_unsigned -> cont 120;
T_signed -> cont 121;
T_char -> cont 122;
T_wchar -> cont 123;
T_boolean -> cont 124;
T_struct -> cont 125;
T_union -> cont 126;
T_switch -> cont 127;
T_case -> cont 128;
T_default -> cont 129;
T_enum -> cont 130;
T_lt -> cont 131;
T_le -> cont 132;
T_gt -> cont 133;
T_ge -> cont 134;
T_osquare -> cont 135;
T_csquare -> cont 136;
T_void -> cont 137;
T_mode happy_dollar_dollar -> cont 138;
T_literal happy_dollar_dollar -> cont 139;
T_string_lit happy_dollar_dollar -> cont 140;
T_id happy_dollar_dollar -> cont 141;
T_attribute -> cont 142;
T_plus -> cont 143;
T_times -> cont 144;
T_minus -> cont 145;
T_string -> cont 146;
T_wstring -> cont 147;
T_sequence -> cont 148;
T_object -> cont 149;
T_any -> cont 150;
T_octet -> cont 151;
T_oneway -> cont 152;
T_fixed -> cont 153;
T_exception -> cont 154;
T_raises -> cont 155;
T_context -> cont 156;
T_readonly -> cont 157;
T_include_start happy_dollar_dollar -> cont 158;
T_include_end -> cont 159;
T_pragma happy_dollar_dollar -> cont 160;
T_unknown happy_dollar_dollar -> cont 161;
_ -> happyError
})
happyThen :: LexM a -> (a -> LexM b) -> LexM b
happyThen = (thenLexM)
happyReturn :: a -> LexM a
happyReturn = (returnLexM)
happyThen1 = happyThen
happyReturn1 = happyReturn
parseIDL = happyThen (happyParse action_0) (\x -> case x of {HappyAbsSyn4 z -> happyReturn z; _other -> notHappyAtAll })
happySeq = happyDontSeq
happyError :: LexM a
happyError = do
l <- getSrcLoc
str <- getStream
ioToLexM (ioError (userError (show l ++ ": Parse error: " ++ takeWhile (/='\n') str)))
{-# LINE 1 "GenericTemplate.hs" #-}
-- $Id: GenericTemplate.hs,v 1.23 2002/05/23 09:24:27 simonmar Exp $
{-# LINE 15 "GenericTemplate.hs" #-}
infixr 9 `HappyStk`
data HappyStk a = HappyStk a (HappyStk a)
-----------------------------------------------------------------------------
-- starting the parse
happyParse start_state = happyNewToken start_state notHappyAtAll notHappyAtAll
-----------------------------------------------------------------------------
-- Accepting the parse
happyAccept j tk st sts (HappyStk ans _) =
(happyReturn1 ans)
-----------------------------------------------------------------------------
-- Arrays only: do the next action
{-# LINE 150 "GenericTemplate.hs" #-}
-----------------------------------------------------------------------------
-- HappyState data type (not arrays)
newtype HappyState b c = HappyState
(Int -> -- token number
Int -> -- token number (yes, again)
b -> -- token semantic value
HappyState b c -> -- current state
[HappyState b c] -> -- state stack
c)
-----------------------------------------------------------------------------
-- Shifting a token
happyShift new_state (1) tk st sts stk@(x `HappyStk` _) =
let i = (case x of { HappyErrorToken (i) -> i }) in
-- trace "shifting the error token" $
new_state i i tk (HappyState (new_state)) ((st):(sts)) (stk)
happyShift new_state i tk st sts stk =
happyNewToken new_state ((st):(sts)) ((HappyTerminal (tk))`HappyStk`stk)
-- happyReduce is specialised for the common cases.
happySpecReduce_0 i fn (1) tk st sts stk
= happyFail (1) tk st sts stk
happySpecReduce_0 nt fn j tk st@((HappyState (action))) sts stk
= action nt j tk st ((st):(sts)) (fn `HappyStk` stk)
happySpecReduce_1 i fn (1) tk st sts stk
= happyFail (1) tk st sts stk
happySpecReduce_1 nt fn j tk _ sts@(((st@(HappyState (action))):(_))) (v1`HappyStk`stk')
= let r = fn v1 in
happySeq r (action nt j tk st sts (r `HappyStk` stk'))
happySpecReduce_2 i fn (1) tk st sts stk
= happyFail (1) tk st sts stk
happySpecReduce_2 nt fn j tk _ ((_):(sts@(((st@(HappyState (action))):(_))))) (v1`HappyStk`v2`HappyStk`stk')
= let r = fn v1 v2 in
happySeq r (action nt j tk st sts (r `HappyStk` stk'))
happySpecReduce_3 i fn (1) tk st sts stk
= happyFail (1) tk st sts stk
happySpecReduce_3 nt fn j tk _ ((_):(((_):(sts@(((st@(HappyState (action))):(_))))))) (v1`HappyStk`v2`HappyStk`v3`HappyStk`stk')
= let r = fn v1 v2 v3 in
happySeq r (action nt j tk st sts (r `HappyStk` stk'))
happyReduce k i fn (1) tk st sts stk
= happyFail (1) tk st sts stk
happyReduce k nt fn j tk st sts stk
= case happyDrop (k - ((1) :: Int)) sts of
sts1@(((st1@(HappyState (action))):(_))) ->
let r = fn stk in -- it doesn't hurt to always seq here...
happyDoSeq r (action nt j tk st1 sts1 r)
happyMonadReduce k nt fn (1) tk st sts stk
= happyFail (1) tk st sts stk
happyMonadReduce k nt fn j tk st sts stk =
happyThen1 (fn stk) (\r -> action nt j tk st1 sts1 (r `HappyStk` drop_stk))
where sts1@(((st1@(HappyState (action))):(_))) = happyDrop k ((st):(sts))
drop_stk = happyDropStk k stk
happyDrop (0) l = l
happyDrop n ((_):(t)) = happyDrop (n - ((1) :: Int)) t
happyDropStk (0) l = l
happyDropStk n (x `HappyStk` xs) = happyDropStk (n - ((1)::Int)) xs
-----------------------------------------------------------------------------
-- Moving to a new state after a reduction
happyGoto action j tk st = action j j tk (HappyState action)
-----------------------------------------------------------------------------
-- Error recovery ((1) is the error token)
-- parse error if we are in recovery and we fail again
happyFail (1) tk old_st _ stk =
-- trace "failing" $
happyError
{- We don't need state discarding for our restricted implementation of
"error". In fact, it can cause some bogus parses, so I've disabled it
for now --SDM
-- discard a state
happyFail (1) tk old_st (((HappyState (action))):(sts))
(saved_tok `HappyStk` _ `HappyStk` stk) =
-- trace ("discarding state, depth " ++ show (length stk)) $
action (1) (1) tk (HappyState (action)) sts ((saved_tok`HappyStk`stk))
-}
-- Enter error recovery: generate an error token,
-- save the old token and carry on.
happyFail i tk (HappyState (action)) sts stk =
-- trace "entering error recovery" $
action (1) (1) tk (HappyState (action)) sts ( (HappyErrorToken (i)) `HappyStk` stk)
-- Internal happy errors:
notHappyAtAll = error "Internal Happy error\n"
-----------------------------------------------------------------------------
-- Hack to get the typechecker to accept our action functions
-----------------------------------------------------------------------------
-- Seq-ing. If the --strict flag is given, then Happy emits
-- happySeq = happyDoSeq
-- otherwise it emits
-- happySeq = happyDontSeq
happyDoSeq, happyDontSeq :: a -> b -> b
happyDoSeq a b = a `seq` b
happyDontSeq a b = b
-----------------------------------------------------------------------------
-- Don't inline any functions from the template. GHC has a nasty habit
-- of deciding to inline happyGoto everywhere, which increases the size of
-- the generated parser quite a bit.
{-# NOINLINE happyShift #-}
{-# NOINLINE happySpecReduce_0 #-}
{-# NOINLINE happySpecReduce_1 #-}
{-# NOINLINE happySpecReduce_2 #-}
{-# NOINLINE happySpecReduce_3 #-}
{-# NOINLINE happyReduce #-}
{-# NOINLINE happyMonadReduce #-}
{-# NOINLINE happyGoto #-}
{-# NOINLINE happyFail #-}
-- end of Happy Template.
| dchagniot/hdirect | src/OmgParser.hs | bsd-3-clause | 98,554 | 3,947 | 20 | 17,795 | 27,862 | 14,967 | 12,895 | 2,864 | 74 |
module Cz.MartinDobias.ChristmasKoma.PadCracker (
Message,
PossibleKeystrokes,
Passphrase(..),
crack,
decode,
zipAll
) where
import Data.Char(ord, chr)
import Data.Bits(xor)
type Message = String
type PossibleKeystrokes = [Char]
type AvailableChars = [Char]
type Passphrase = [PossibleKeystrokes]
zipAll :: [Message] -> [AvailableChars]
zipAll [] = []
zipAll xs = map head (filterEmpty xs) : zipAll (filterEmpty (map tail (filterEmpty xs)))
where filterEmpty = filter (not . null)
legalOutput = ['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] ++ " ,.:!-\'"
legalOutputInitial = ['A'..'Z'] ++ ['0'..'9']
possibleCandidates = [(chr 0) .. (chr 255)]
candecode :: [Char] -> Char -> AvailableChars -> Bool
candecode l c = all (\x -> chr(ord c `xor` ord x) `elem` l)
valid :: [Char] -> AvailableChars -> PossibleKeystrokes -> PossibleKeystrokes
valid l xs ps = [p | p <- ps, candecode l p xs]
findCandidates :: [AvailableChars] -> [PossibleKeystrokes] -> [PossibleKeystrokes]
findCandidates [] _ = []
findCandidates (x : xs) (p : ps) = (if null p then valid legalOutput x possibleCandidates else valid legalOutput x p) : findCandidates xs ps
findCandidatesInitial :: [AvailableChars] -> [PossibleKeystrokes] -> [PossibleKeystrokes]
findCandidatesInitial [] _ = []
findCandidatesInitial (x : xs) (p : ps) = (if null p then valid legalOutputInitial x possibleCandidates else valid legalOutputInitial x p) : findCandidates xs ps
crack :: [Message] -> Passphrase -> Passphrase
crack ms ps = findCandidatesInitial (zipAll ms) (infinitePassphrase ps)
infinitePassphrase p = p ++ infinitePassphrase p
decodeOrHide [] = []
decodeOrHide ((_, []) : m) = '_' : decodeOrHide m
decodeOrHide ((c, [p]) : m) = chr (ord c `xor` ord p) : decodeOrHide m
decodeOrHide ((_, p : ps) : m) = '_' : decodeOrHide m
decode :: Passphrase -> Message -> String
decode cs m = decodeOrHide zipped
where zipped = zip m (infinitePassphrase cs)
| martindobias/christmass-koma | src/Cz/MartinDobias/ChristmasKoma/PadCracker.hs | bsd-3-clause | 1,989 | 0 | 12 | 381 | 790 | 427 | 363 | 40 | 2 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
module FPNLA.Operations.BLAS.Strategies.SYRK.MonadPar.DefPar () where
import Control.DeepSeq (NFData)
import Control.Monad.Par as MP (parMap,
runPar)
import FPNLA.Matrix (MatrixVector,
foldr_v,
fromCols_vm,
generate_v)
import FPNLA.Operations.BLAS (SYRK (syrk))
import FPNLA.Operations.BLAS.Strategies.DataTypes (DefPar_MP)
import FPNLA.Operations.Parameters (Elt,
TransType (..),
blasResultM,
dimTrans_m,
dimTriang,
elemSymm,
elemTrans_m)
instance (NFData (v e), Elt e, MatrixVector m v e) => SYRK DefPar_MP m v e where
syrk _ alpha pmA beta pmB
| p /= p' = error "syrk: incompatible ranges"
| otherwise = blasResultM $ generatePar_m p p (\i j -> (alpha * pmAMultIJ i j) + beta * elemSymm i j pmB)
where
(p, p') = dimTriang pmB
matMultIJ i j tmA tmB = foldr_v (+) 0 (generate_v (snd $ dimTrans_m tmA) (\k -> (*) (elemTrans_m i k tmA) (elemTrans_m k j tmB)) :: v e)
pmAMultIJ i j =
case pmA of
(NoTrans mA) -> matMultIJ i j pmA (Trans mA)
(Trans mA) -> matMultIJ i j (Trans mA) pmA
(ConjTrans mA) -> matMultIJ i j (Trans mA) pmA
generatePar_m m n gen = fromCols_vm . MP.runPar . MP.parMap (\j -> generate_v m (`gen` j) :: v e) $ [0 .. (n - 1)]
| mauroblanco/fpnla-examples | src/FPNLA/Operations/BLAS/Strategies/SYRK/MonadPar/DefPar.hs | bsd-3-clause | 2,251 | 0 | 15 | 1,162 | 518 | 285 | 233 | 33 | 0 |
{-# LANGUAGE GeneralizedNewtypeDeriving, ScopedTypeVariables, KindSignatures, GADTs, InstanceSigs, TypeOperators, MultiParamTypeClasses, FlexibleInstances, OverloadedStrings #-}
module Text.AFrame where
import Control.Applicative
import Data.Char (isSpace)
import Data.Generic.Diff
import Data.Map(Map)
import Data.String
import Data.Text(Text,pack,unpack)
import qualified Data.Text as T
import qualified Data.Text.Lazy as LT
import Data.Maybe (listToMaybe)
import Data.List as L
import Data.Monoid ((<>))
--import Text.XML.Light as X
import Data.Aeson
import Data.Monoid
import qualified Text.Taggy as T
import qualified Data.HashMap.Strict as H
-- | 'AFrame' describes the contents of an a-frame scene,
-- and is stored as a classical rose tree.
-- 'AFrame' follows the DOM, except there are no textual
-- content; it is tags all the way down.
--
-- An xception is that \<script>ABC\</script> is encoded using
-- \<script text=\"ABC\">\</script>
data AFrame = AFrame Primitive [Attribute] [AFrame]
deriving (Show, Eq)
newtype Primitive = Primitive Text
deriving (Show, Eq, Ord, IsString, ToJSON, FromJSON)
newtype Label = Label Text
deriving (Show, Eq, Ord, IsString, ToJSON, FromJSON)
newtype Property = Property Text
deriving (Show, Eq, Ord, IsString, ToJSON, FromJSON)
type Attribute = (Label,Property)
-- | A valid css or jquerty-style path, in Haskell from.
-- An example of the string form might be
-- $('a-scene > a-entity:nth-of-type(2) > a-collada-model:nth-of-type(1) > a-animation:nth-of-type(1)')
data Path = Path Primitive [(Int,Primitive)]
deriving (Show, Eq, Ord)
-------------------------------------------------------------------------------------------------
instance ToJSON Path where
toJSON (Path p ps) = toJSON $
toJSON p : concat
[ [toJSON i,toJSON p]
| (i,p) <- ps
]
instance FromJSON Path where
parseJSON as = do
xs :: [Value] <- parseJSON as
toPath xs
where toPath [p] = do
txt <- parseJSON p
return $ Path txt []
toPath (p1:i1:rest) = do
txt :: Primitive <- parseJSON p1
n :: Int <- parseJSON i1
Path p ps <- toPath rest
return $ Path txt ((n,p):ps)
toPath _ = fail "bad Path"
-------------------------------------------------------------------------------------------------
setAttribute :: Label -> Property -> AFrame -> AFrame
setAttribute lbl prop (AFrame p as af) = AFrame p ((lbl,prop) : [ (l,p) | (l,p) <- as, l /= lbl ]) af
getAttribute :: Label -> AFrame -> Maybe Property
getAttribute lbl (AFrame p as af) = lookup lbl as
resetAttribute :: Label -> AFrame -> AFrame
resetAttribute lbl (AFrame p as af) = AFrame p [ (l,p) | (l,p) <- as, l /= lbl ] af
-------------------------------------------------------------------------------------------------
--setPath :: Path -> Label -> Property -> AFrame -> AFrame
--getPath :: Path -> Label -> AFrame -> Mabe Property
getElementById :: AFrame -> Text -> Maybe AFrame
getElementById af@(AFrame p as is) i =
case lookup "id" as of
Just (Property i') | i == i' -> return af
_ -> listToMaybe [ af' | Just af' <- map (flip getElementById i) is ]
-------------------------------------------------------------------------------------------------
-- | 'aFrameToElement' converts an 'AFrame' to an (XML) 'Element'. Total.
aFrameToElement :: AFrame -> T.Element
aFrameToElement (AFrame prim attrs rest) = T.Element prim' attrs' rest'
where
Primitive prim' = prim
attrs' = H.fromList
$ [ (a,p)
| (Label a,Property p) <- attrs
, not (prim' == "script" && a == "text")
]
rest' = [ T.NodeContent p
| (Label "text",Property p) <- attrs
, prim' == "script"
]
++ map (T.NodeElement . aFrameToElement) rest
-- | 'aFrameToElement' converts an (HTML) 'Element' to an 'AFrame'. Total.
-- Strips out any text (which is not used by 'AFrame' anyway.)
elementToAFrame :: T.Element -> AFrame
elementToAFrame ele = AFrame prim' attrs' content'
where
prim' = Primitive $ T.eltName $ ele
attrs' = [ (Label a,Property p)| (a,p) <- H.toList $ T.eltAttrs ele ]
++ [ (Label "text",Property txt)| T.NodeContent txt <- T.eltChildren ele ]
content' = [ elementToAFrame ele' | T.NodeElement ele' <- T.eltChildren ele ]
-- | reads an aframe document. This can be enbedded in an XML-style document (such as HTML)
readAFrame :: String -> Maybe AFrame
readAFrame str = do
let doms = T.parseDOM True (LT.fromStrict $ pack str)
case doms of
[T.NodeElement dom] -> do
let aframe = elementToAFrame dom
findAFrame aframe
_ -> error $ show ("found strange DOM",doms)
where
findAFrame :: AFrame -> Maybe AFrame
findAFrame a@(AFrame (Primitive "a-scene") _ _) = return a
findAFrame (AFrame _ _ xs) = listToMaybe
[ x
| Just x <- map findAFrame xs
]
showAFrame :: AFrame -> String
showAFrame = LT.unpack . T.renderWith False . aFrameToElement
-- | inject 'AFrame' into an existing (HTML) file. Replaces complete "<a-scene>" element.
injectAFrame :: AFrame -> String -> String
injectAFrame aframe str = findScene str 0
where
openTag = "<a-scene"
closeTag = "</a-scene>"
findScene :: String -> Int -> String
findScene xs n | openTag `L.isPrefixOf` xs = insertScene (drop (length openTag) xs) n
findScene (x:xs) n =
case x of
' ' -> x : findScene xs (n+1)
_ -> x : findScene xs 0
findScene [] n = []
insertScene :: String -> Int -> String
insertScene xs n = unlines (s : map (spaces ++) (ss ++ [remainingScene xs]))
where
(s:ss) = lines $ showAFrame $ aframe
spaces = take n $ repeat ' '
-- This will mess up if the closeTag strict appears in the scene.
remainingScene :: String -> String
remainingScene xs | closeTag `L.isPrefixOf` xs = drop (length closeTag) xs
remainingScene (x:xs) = remainingScene xs
remainingScene [] = []
------
-- Adding gdiff support
------
data AFrameFamily :: * -> * -> * where
AFrame' :: AFrameFamily AFrame (Cons Primitive
(Cons [Attribute]
(Cons [AFrame] Nil)))
ConsAttr' :: AFrameFamily [Attribute] (Cons Attribute (Cons [Attribute] Nil))
NilAttr' :: AFrameFamily [Attribute] Nil
ConsAFrame' :: AFrameFamily [AFrame] (Cons AFrame (Cons [AFrame] Nil))
NilAFrame' :: AFrameFamily [AFrame] Nil
Primitive' :: Primitive -> AFrameFamily Primitive Nil
Attribute' :: Attribute -> AFrameFamily Attribute Nil
instance Family AFrameFamily where
decEq :: AFrameFamily tx txs -> AFrameFamily ty tys -> Maybe (tx :~: ty, txs :~: tys)
decEq AFrame' AFrame' = Just (Refl, Refl)
decEq ConsAttr' ConsAttr' = Just (Refl, Refl)
decEq NilAttr' NilAttr' = Just (Refl, Refl)
decEq ConsAFrame' ConsAFrame' = Just (Refl, Refl)
decEq NilAFrame' NilAFrame' = Just (Refl, Refl)
decEq (Primitive' p1) (Primitive' p2) | p1 == p2 = Just (Refl, Refl)
decEq (Attribute' a1) (Attribute' a2) | a1 == a2 = Just (Refl, Refl)
decEq _ _ = Nothing
fields :: AFrameFamily t ts -> t -> Maybe ts
fields AFrame' (AFrame prim attrs fs)
= Just $ CCons prim $ CCons attrs $ CCons fs $ CNil
fields ConsAttr' ((lbl,prop):xs)
= Just $ CCons (lbl,prop) $ CCons xs $ CNil
fields NilAttr' [] = Just CNil
fields ConsAFrame' (x:xs)
= Just $ CCons x $ CCons xs $ CNil
fields NilAFrame' [] = Just CNil
fields (Primitive' _) _ = Just CNil
fields (Attribute' _) _ = Just CNil
fields _ _ = Nothing
apply :: AFrameFamily t ts -> ts -> t
apply AFrame' (CCons prim (CCons attrs (CCons fs CNil)))
= AFrame prim attrs fs
apply ConsAttr' (CCons (lbl,prop) (CCons xs CNil)) = (lbl,prop) : xs
apply NilAttr' CNil = []
apply ConsAFrame' (CCons x (CCons xs CNil)) = x : xs
apply NilAFrame' CNil = []
apply (Primitive' p1) CNil = p1
apply (Attribute' a1) CNil = a1
string :: AFrameFamily t ts -> String
string AFrame' = "AFrame"
string ConsAttr' = "ConsAttr"
string NilAttr' = "NilAttr"
string ConsAFrame' = "ConsAFrame"
string NilAFrame' = "NilAFrame"
string (Primitive' l1) = show l1
string (Attribute' p1) = show p1
instance Type AFrameFamily AFrame where
constructors = [Concr AFrame']
instance Type AFrameFamily Primitive where
constructors = [Abstr Primitive']
instance Type AFrameFamily [Attribute] where
constructors = [Concr ConsAttr',Concr NilAttr']
instance Type AFrameFamily [AFrame] where
constructors = [Concr ConsAFrame',Concr NilAFrame']
instance Type AFrameFamily Attribute where
constructors = [Abstr Attribute']
data AFrameUpdate = AFrameUpdate
{ aframePath :: Path
, aframeLabel :: Label
, aframeProperty :: Property
}
{-
compareAFrame :: AFrame -> AFrame -> Maybe [([Text],Attribute)]
compareAFrame aframe1 aframe2 = fmap (fmap (\ (xs,a) -> (intercalate " > " xs,a)))
$ deltaAFrame aframe1 aframe2
-}
deltaAFrame :: AFrame -> AFrame -> Maybe [(Path,Attribute)]
deltaAFrame (AFrame p1@(Primitive primName) attrs1 aframes1)
(AFrame p2 attrs2 aframes2)
| p1 /= p2 = fail "element name does not match in deltasAFrame"
| length aframes1 /= length aframes2
= fail "sub elements count do not match in deltasAFrame"
| otherwise = do
attrsD <- fmap (\ a -> (Path p1 [],a)) <$> deltaAttributes attrs1 attrs2
let ps = [ p | AFrame p _ _ <- aframes1 ]
xs = [ length [ () | x' <- xs, x' == x ] | (x:xs) <- tail $ scanl (flip (:)) [] ps ]
aframesD <- concat <$> sequence
[ do ds <- deltaAFrame a1 a2
return $ fmap (\ (Path p ps,at) -> (Path p1 ((x,p):ps),at)) ds
| (a1,a2,x) <- zip3 aframes1 aframes2 xs
]
return $ attrsD ++ aframesD
deltaAttributes :: [Attribute] -> [Attribute] -> Maybe [Attribute]
deltaAttributes xs ys | length xs /= length ys = fail "different number of arguments for deltaAttributes"
deltaAttributes xs ys = concat <$> sequence [ deltaAttribute x y | (x,y) <- xs `zip` ys ]
deltaAttribute :: Attribute -> Attribute -> Maybe [Attribute]
deltaAttribute attr1@(lbl1,_) attr2@(lbl2,_)
| attr1 == attr2 = return [] -- same result
| lbl1 == lbl2 = return [attr2] -- true update
| otherwise = fail "labels do not match in deltaAttributes"
------------------------------------------------------------------------------------------
unpackProperty :: Property -> [(Label,Property)]
unpackProperty (Property prop) =
[ (Label (T.dropWhile isSpace l), Property (T.dropWhile (\ c -> isSpace c || c == ':') p))
| (l,p) <- map (T.span (/= ':')) (T.splitOn ";" prop)
, not (T.null p)
]
packProperty :: [(Label,Property)] -> Property
packProperty = Property
. T.intercalate "; "
. map (\ (Label lbl,Property txt) -> lbl <> ": " <> txt)
------------------------------------------------------------------------------------------
preOrderFrame :: Monad m => (AFrame -> m AFrame) -> AFrame -> m AFrame
preOrderFrame f af = do
AFrame prim attrs aframes <- f af
aframes' <- traverse (preOrderFrame f) aframes
return $ AFrame prim attrs aframes'
-- This finds \<script src=\"...\"> and inserts the text=\"..\" into the \<script>.
resolveScript :: Monad m => (Text -> m LT.Text) -> AFrame -> m AFrame
resolveScript rf = preOrderFrame fn
where
fn af@(AFrame "script" attrs aframes) = case lookup "src" attrs of
Nothing -> return af
Just (Property path) ->
do txt <- rf path
return $ AFrame "script"
((Label "text",Property (LT.toStrict txt))
: [(l,p) | (l,p) <- attrs, l `notElem` ["src","text"]]
)
aframes
fn af = return af
instantiateTemplates :: Monad m => ([Attribute] -> AFrame -> m AFrame) -> AFrame -> m AFrame
instantiateTemplates f root = preOrderFrame fn root
where
fn (aEntity@(AFrame "a-entity" attrs aframes)) = case lookup "template" attrs of
Nothing -> return aEntity
Just templ -> case lookup "src" (unpackProperty templ) of
Nothing -> return aEntity
Just (Property src) | T.take 1 src == "#" ->
case getElementById root (T.drop 1 src) of
Just (script@(AFrame "script" attrs _)) -> do
txt <- f attrs script
return aEntity
_ -> return aEntity -- id not found
fn af = return af
| ku-fpg/aframe | src/Text/AFrame.hs | bsd-3-clause | 13,322 | 0 | 22 | 3,737 | 4,141 | 2,129 | 2,012 | 232 | 6 |
-- | This module provides the /TcT/ monad.
module Tct.Core.Data.TctM
(
-- * Tct Monad
TctM (..)
, TctROState (..)
, TctStatus (..)
, askState
, setState
, setKvPair
, getKvPair
, askStatus
-- * Lifted IO functions
, async
, wait
, timed
, paused
, raceWith
, concurrently
) where
import Control.Applicative ((<|>))
import Control.Concurrent (threadDelay)
import qualified Control.Concurrent.Async as Async
import Control.Monad (liftM)
import Control.Monad.Reader (ask, liftIO, local, runReaderT)
import qualified Data.Map as M
import Data.Maybe (fromMaybe)
import qualified System.Time as Time
import Tct.Core.Data.Types
-- | Returns the state of the Monad.
askState :: TctM TctROState
askState = ask
-- | Sets (locally) the state of the Monad.
setState :: (TctROState -> TctROState) -> TctM a -> TctM a
setState = local
-- | Sets (locally) a key-value pair.
setKvPair :: (String, [String]) -> TctM a -> TctM a
setKvPair (k,v) = local $ \st -> st { kvPairs = M.insert k v (kvPairs st) }
-- | Given a key; asks for a value. Returns [] if there is no value.
getKvPair :: String -> TctM [String]
getKvPair s = (get . kvPairs) <$> ask
where get m = [] `fromMaybe` M.lookup s m
-- | Returns 'TctStatus' which is obtained from 'TctROState' during runtime.
--
-- > runningTime = now - startTime
-- > remainingTime = max (0, now - stopTime)
askStatus :: prob -> TctM (TctStatus prob)
askStatus prob = do
st <- askState
now <- liftIO Time.getClockTime
return TctStatus
{ currentProblem = prob
, runningTime = Time.tdSec (Time.diffClockTimes now (startTime st))
, remainingTime = (max 0 . Time.tdSec . flip Time.diffClockTimes now) `fmap` stopTime st }
toIO :: TctM a -> TctM (IO a)
toIO m = runReaderT (runTctM m) `fmap` askState
-- | Lifts 'Async.async'.
async :: TctM a -> TctM (Async.Async a)
async m = toIO m >>= liftIO . Async.async
-- | Lifts 'Async.wait'.
wait :: Async.Async a -> TctM a
wait = liftIO . Async.wait
--waitEither :: Async.Async a -> Async.Async b -> TctM (Either a b)
--waitEither a1 a2 = liftIO $ Async.waitEither a1 a2
-- | Lifts 'Async.concurrently'.
concurrently :: TctM a -> TctM b -> TctM (a,b)
concurrently m1 m2 = do
io1 <- toIO m1
io2 <- toIO m2
liftIO $ Async.withAsync io1 $ \a1 ->
liftIO $ Async.withAsync io2 $ \a2 ->
liftIO $ Async.waitBoth a1 a2
-- | @'raceWith' p1 m1 m2@ runs @m1@ and @m2@ in parallel.
--
-- * Returns the first result that satisfies @p1@.
-- * Otherwise returns the latter result.
raceWith :: (a -> Bool) -> TctM a -> TctM a -> TctM a
raceWith p1 m1 m2 = do
io1 <- toIO m1
io2 <- toIO m2
liftIO $ raceWithIO p1 io1 io2
raceWithIO :: (a -> Bool) -> IO a -> IO a -> IO a
raceWithIO p1 m1 m2 =
Async.withAsync m1 $ \a1 ->
Async.withAsync m2 $ \a2 -> do
e <- Async.waitEither a1 a2
case e of
Left r1
| p1 r1 -> Async.cancel a2 >> return r1
| otherwise -> Async.wait a2
Right r2
| p1 r2 -> Async.cancel a1 >> return r2
| otherwise -> Async.wait a1
-- | @'timed' seconds m@ wraps the Tct action in timeout, and locally sets 'stopTime'.
-- When @seconds@
--
-- * is negative, no timeout is set;
-- * is @0@, the computation aborts immediately, returning 'Nothing';
-- * is positive the computation runs at most @i@ seconds.
--
-- Returns 'Nothing' if @m@ does not end before the timeout.
--
-- Sets 'stopTime'.
--
-- > stopTime = min (now + timeout) stopTime
timed :: Int -> TctM a -> TctM (Maybe a)
timed n m
| n < 0 = Just `liftM` m
| n == 0 = return Nothing
| otherwise = do
e <- toIO m' >>= liftIO . Async.race (threadDelay $ toMicroSec n)
return $ either (const Nothing) Just e
where
m' = do
Time.TOD sec pico <- liftIO Time.getClockTime
let newTime = Just $ Time.TOD (sec + toInteger n) pico
local (\ r -> r { stopTime = min newTime (stopTime r) <|> newTime }) m
-- | @'wait' seconds m@ pauses seconds
paused :: Int -> TctM a -> TctM a
paused n m
| n <= 0 = m
| otherwise = liftIO (threadDelay (toMicroSec n)) >> m
toMicroSec :: Num a => a -> a
toMicroSec i = i*1000000
| ComputationWithBoundedResources/tct-core | src/Tct/Core/Data/TctM.hs | bsd-3-clause | 4,268 | 0 | 17 | 1,085 | 1,296 | 672 | 624 | 89 | 2 |
module Dir.CoerceType(CoerceType(..)) where
newtype CoerceType = CoerceType Int
| ndmitchell/weeder | test/foo/src/Dir/CoerceType.hs | bsd-3-clause | 81 | 0 | 5 | 9 | 23 | 15 | 8 | 2 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Rede.Workers.VeryBasic(
veryBasic
,bad404ResponseData
,bad404ResponseHeaders
) where
import qualified Data.ByteString as B
import Data.Conduit
import Data.ByteString.Char8 (pack)
import Rede.MainLoop.CoherentWorker
trivialHeaders :: [(B.ByteString, B.ByteString)]
trivialHeaders = [
(":status", "200"),
("server", "reh0m")
]
veryBasic :: CoherentWorker
veryBasic (headers, _) = do
let data_and_conclussion = yield "Hello world!"
putStrLn "Got these headers: "
print headers
return (trivialHeaders, [], data_and_conclussion)
bad404ResponseData :: B.ByteString
bad404ResponseData = "404: ReH: Didn't find that"
bad404ResponseHeaders :: Headers
bad404ResponseHeaders = [
(":status", "404")
,(":version", "HTTP/1.1")
,("content-length", (pack.show $ B.length bad404ResponseData))
,("content-type", "text/plain")
,("server", "ReHv0.0")
] | loadimpact/http2-test | hs-src/Rede/Workers/VeryBasic.hs | bsd-3-clause | 1,060 | 0 | 10 | 275 | 231 | 138 | 93 | 28 | 1 |
import Data.Aeson
import qualified Data.ByteString.Lazy as B
import qualified Data.Map as Map
jsonFile :: FilePath
jsonFile = "kataids.json"
hsFile :: FilePath
hsFile = "Kataids.hs"
getJSON :: IO B.ByteString
getJSON = B.readFile jsonFile
kidspref = "module Kataids where\n\
\import qualified Data.Map as Map\n\
\kataids = Map."
main = do
d <- (eitherDecode <$> getJSON) :: IO (Either String (Map.Map String String))
case d of
Left err -> putStrLn err
Right kids -> writeFile hsFile $ kidspref ++ (show kids)
| klpn/lablinkfix | kataidsgen.hs | bsd-3-clause | 558 | 0 | 13 | 127 | 156 | 83 | 73 | 15 | 2 |
{-
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
\section[SimplCore]{Driver for simplifying @Core@ programs}
-}
{-# LANGUAGE CPP #-}
module SimplCore ( core2core, simplifyExpr ) where
#include "HsVersions.h"
import GhcPrelude
import DynFlags
import CoreSyn
import HscTypes
import CSE ( cseProgram )
import Rules ( mkRuleBase, unionRuleBase,
extendRuleBaseList, ruleCheckProgram, addRuleInfo, )
import PprCore ( pprCoreBindings, pprCoreExpr )
import OccurAnal ( occurAnalysePgm, occurAnalyseExpr )
import IdInfo
import CoreStats ( coreBindsSize, coreBindsStats, exprSize )
import CoreUtils ( mkTicks, stripTicksTop )
import CoreLint ( endPass, lintPassResult, dumpPassResult,
lintAnnots )
import Simplify ( simplTopBinds, simplExpr, simplRules )
import SimplUtils ( simplEnvForGHCi, activeRule, activeUnfolding )
import SimplEnv
import SimplMonad
import CoreMonad
import qualified ErrUtils as Err
import FloatIn ( floatInwards )
import FloatOut ( floatOutwards )
import FamInstEnv
import Id
import ErrUtils ( withTiming )
import BasicTypes ( CompilerPhase(..), isDefaultInlinePragma )
import VarSet
import VarEnv
import LiberateCase ( liberateCase )
import SAT ( doStaticArgs )
import Specialise ( specProgram)
import SpecConstr ( specConstrProgram)
import DmdAnal ( dmdAnalProgram )
import CallArity ( callArityAnalProgram )
import Exitify ( exitifyProgram )
import WorkWrap ( wwTopBinds )
import Vectorise ( vectorise )
import SrcLoc
import Util
import Module
import Maybes
import UniqSupply ( UniqSupply, mkSplitUniqSupply, splitUniqSupply )
import UniqFM
import Outputable
import Control.Monad
import qualified GHC.LanguageExtensions as LangExt
#if defined(GHCI)
import DynamicLoading ( loadPlugins )
import Plugins ( installCoreToDos )
#else
import DynamicLoading ( pluginError )
#endif
{-
************************************************************************
* *
\subsection{The driver for the simplifier}
* *
************************************************************************
-}
core2core :: HscEnv -> ModGuts -> IO ModGuts
core2core hsc_env guts@(ModGuts { mg_module = mod
, mg_loc = loc
, mg_deps = deps
, mg_rdr_env = rdr_env })
= do { us <- mkSplitUniqSupply 's'
-- make sure all plugins are loaded
; let builtin_passes = getCoreToDo dflags
orph_mods = mkModuleSet (mod : dep_orphs deps)
;
; (guts2, stats) <- runCoreM hsc_env hpt_rule_base us mod
orph_mods print_unqual loc $
do { all_passes <- addPluginPasses builtin_passes
; runCorePasses all_passes guts }
; Err.dumpIfSet_dyn dflags Opt_D_dump_simpl_stats
"Grand total simplifier statistics"
(pprSimplCount stats)
; return guts2 }
where
dflags = hsc_dflags hsc_env
home_pkg_rules = hptRules hsc_env (dep_mods deps)
hpt_rule_base = mkRuleBase home_pkg_rules
print_unqual = mkPrintUnqualified dflags rdr_env
-- mod: get the module out of the current HscEnv so we can retrieve it from the monad.
-- This is very convienent for the users of the monad (e.g. plugins do not have to
-- consume the ModGuts to find the module) but somewhat ugly because mg_module may
-- _theoretically_ be changed during the Core pipeline (it's part of ModGuts), which
-- would mean our cached value would go out of date.
{-
************************************************************************
* *
Generating the main optimisation pipeline
* *
************************************************************************
-}
getCoreToDo :: DynFlags -> [CoreToDo]
getCoreToDo dflags
= flatten_todos core_todo
where
opt_level = optLevel dflags
phases = simplPhases dflags
max_iter = maxSimplIterations dflags
rule_check = ruleCheck dflags
call_arity = gopt Opt_CallArity dflags
exitification = gopt Opt_Exitification dflags
strictness = gopt Opt_Strictness dflags
full_laziness = gopt Opt_FullLaziness dflags
do_specialise = gopt Opt_Specialise dflags
do_float_in = gopt Opt_FloatIn dflags
cse = gopt Opt_CSE dflags
spec_constr = gopt Opt_SpecConstr dflags
liberate_case = gopt Opt_LiberateCase dflags
late_dmd_anal = gopt Opt_LateDmdAnal dflags
static_args = gopt Opt_StaticArgumentTransformation dflags
rules_on = gopt Opt_EnableRewriteRules dflags
eta_expand_on = gopt Opt_DoLambdaEtaExpansion dflags
ww_on = gopt Opt_WorkerWrapper dflags
vectorise_on = gopt Opt_Vectorise dflags
static_ptrs = xopt LangExt.StaticPointers dflags
maybe_rule_check phase = runMaybe rule_check (CoreDoRuleCheck phase)
maybe_strictness_before phase
= runWhen (phase `elem` strictnessBefore dflags) CoreDoStrictness
base_mode = SimplMode { sm_phase = panic "base_mode"
, sm_names = []
, sm_dflags = dflags
, sm_rules = rules_on
, sm_eta_expand = eta_expand_on
, sm_inline = True
, sm_case_case = True }
simpl_phase phase names iter
= CoreDoPasses
$ [ maybe_strictness_before phase
, CoreDoSimplify iter
(base_mode { sm_phase = Phase phase
, sm_names = names })
, maybe_rule_check (Phase phase) ]
-- Vectorisation can introduce a fair few common sub expressions involving
-- DPH primitives. For example, see the Reverse test from dph-examples.
-- We need to eliminate these common sub expressions before their definitions
-- are inlined in phase 2. The CSE introduces lots of v1 = v2 bindings,
-- so we also run simpl_gently to inline them.
++ (if vectorise_on && phase == 3
then [CoreCSE, simpl_gently]
else [])
vectorisation
= runWhen vectorise_on $
CoreDoPasses [ simpl_gently, CoreDoVectorisation ]
-- By default, we have 2 phases before phase 0.
-- Want to run with inline phase 2 after the specialiser to give
-- maximum chance for fusion to work before we inline build/augment
-- in phase 1. This made a difference in 'ansi' where an
-- overloaded function wasn't inlined till too late.
-- Need phase 1 so that build/augment get
-- inlined. I found that spectral/hartel/genfft lost some useful
-- strictness in the function sumcode' if augment is not inlined
-- before strictness analysis runs
simpl_phases = CoreDoPasses [ simpl_phase phase ["main"] max_iter
| phase <- [phases, phases-1 .. 1] ]
-- initial simplify: mk specialiser happy: minimum effort please
simpl_gently = CoreDoSimplify max_iter
(base_mode { sm_phase = InitialPhase
, sm_names = ["Gentle"]
, sm_rules = rules_on -- Note [RULEs enabled in SimplGently]
, sm_inline = not vectorise_on
-- See Note [Inline in InitialPhase]
, sm_case_case = False })
-- Don't do case-of-case transformations.
-- This makes full laziness work better
strictness_pass = if ww_on
then [CoreDoStrictness,CoreDoWorkerWrapper]
else [CoreDoStrictness]
-- New demand analyser
demand_analyser = (CoreDoPasses (
strictness_pass ++
[simpl_phase 0 ["post-worker-wrapper"] max_iter]
))
-- Static forms are moved to the top level with the FloatOut pass.
-- See Note [Grand plan for static forms] in StaticPtrTable.
static_ptrs_float_outwards =
runWhen static_ptrs $ CoreDoPasses
[ simpl_gently -- Float Out can't handle type lets (sometimes created
-- by simpleOptPgm via mkParallelBindings)
, CoreDoFloatOutwards FloatOutSwitches
{ floatOutLambdas = Just 0
, floatOutConstants = True
, floatOutOverSatApps = False
, floatToTopLevelOnly = True
}
]
core_todo =
if opt_level == 0 then
[ vectorisation,
static_ptrs_float_outwards,
CoreDoSimplify max_iter
(base_mode { sm_phase = Phase 0
, sm_names = ["Non-opt simplification"] })
]
else {- opt_level >= 1 -} [
-- We want to do the static argument transform before full laziness as it
-- may expose extra opportunities to float things outwards. However, to fix
-- up the output of the transformation we need at do at least one simplify
-- after this before anything else
runWhen static_args (CoreDoPasses [ simpl_gently, CoreDoStaticArgs ]),
-- We run vectorisation here for now, but we might also try to run
-- it later
vectorisation,
-- initial simplify: mk specialiser happy: minimum effort please
simpl_gently,
-- Specialisation is best done before full laziness
-- so that overloaded functions have all their dictionary lambdas manifest
runWhen do_specialise CoreDoSpecialising,
if full_laziness then
CoreDoFloatOutwards FloatOutSwitches {
floatOutLambdas = Just 0,
floatOutConstants = True,
floatOutOverSatApps = False,
floatToTopLevelOnly = False }
-- Was: gentleFloatOutSwitches
--
-- I have no idea why, but not floating constants to
-- top level is very bad in some cases.
--
-- Notably: p_ident in spectral/rewrite
-- Changing from "gentle" to "constantsOnly"
-- improved rewrite's allocation by 19%, and
-- made 0.0% difference to any other nofib
-- benchmark
--
-- Not doing floatOutOverSatApps yet, we'll do
-- that later on when we've had a chance to get more
-- accurate arity information. In fact it makes no
-- difference at all to performance if we do it here,
-- but maybe we save some unnecessary to-and-fro in
-- the simplifier.
else
-- Even with full laziness turned off, we still need to float static
-- forms to the top level. See Note [Grand plan for static forms] in
-- StaticPtrTable.
static_ptrs_float_outwards,
simpl_phases,
-- Phase 0: allow all Ids to be inlined now
-- This gets foldr inlined before strictness analysis
-- At least 3 iterations because otherwise we land up with
-- huge dead expressions because of an infelicity in the
-- simplifier.
-- let k = BIG in foldr k z xs
-- ==> let k = BIG in letrec go = \xs -> ...(k x).... in go xs
-- ==> let k = BIG in letrec go = \xs -> ...(BIG x).... in go xs
-- Don't stop now!
simpl_phase 0 ["main"] (max max_iter 3),
runWhen do_float_in CoreDoFloatInwards,
-- Run float-inwards immediately before the strictness analyser
-- Doing so pushes bindings nearer their use site and hence makes
-- them more likely to be strict. These bindings might only show
-- up after the inlining from simplification. Example in fulsom,
-- Csg.calc, where an arg of timesDouble thereby becomes strict.
runWhen call_arity $ CoreDoPasses
[ CoreDoCallArity
, simpl_phase 0 ["post-call-arity"] max_iter
],
runWhen strictness demand_analyser,
runWhen exitification CoreDoExitify,
-- See note [Placement of the exitification pass]
runWhen full_laziness $
CoreDoFloatOutwards FloatOutSwitches {
floatOutLambdas = floatLamArgs dflags,
floatOutConstants = True,
floatOutOverSatApps = True,
floatToTopLevelOnly = False },
-- nofib/spectral/hartel/wang doubles in speed if you
-- do full laziness late in the day. It only happens
-- after fusion and other stuff, so the early pass doesn't
-- catch it. For the record, the redex is
-- f_el22 (f_el21 r_midblock)
runWhen cse CoreCSE,
-- We want CSE to follow the final full-laziness pass, because it may
-- succeed in commoning up things floated out by full laziness.
-- CSE used to rely on the no-shadowing invariant, but it doesn't any more
runWhen do_float_in CoreDoFloatInwards,
maybe_rule_check (Phase 0),
-- Case-liberation for -O2. This should be after
-- strictness analysis and the simplification which follows it.
runWhen liberate_case (CoreDoPasses [
CoreLiberateCase,
simpl_phase 0 ["post-liberate-case"] max_iter
]), -- Run the simplifier after LiberateCase to vastly
-- reduce the possibility of shadowing
-- Reason: see Note [Shadowing] in SpecConstr.hs
runWhen spec_constr CoreDoSpecConstr,
maybe_rule_check (Phase 0),
-- Final clean-up simplification:
simpl_phase 0 ["final"] max_iter,
runWhen late_dmd_anal $ CoreDoPasses (
strictness_pass ++
[simpl_phase 0 ["post-late-ww"] max_iter]
),
-- Final run of the demand_analyser, ensures that one-shot thunks are
-- really really one-shot thunks. Only needed if the demand analyser
-- has run at all. See Note [Final Demand Analyser run] in DmdAnal
-- It is EXTREMELY IMPORTANT to run this pass, otherwise execution
-- can become /exponentially/ more expensive. See Trac #11731, #12996.
runWhen (strictness || late_dmd_anal) CoreDoStrictness,
maybe_rule_check (Phase 0)
]
-- Remove 'CoreDoNothing' and flatten 'CoreDoPasses' for clarity.
flatten_todos [] = []
flatten_todos (CoreDoNothing : rest) = flatten_todos rest
flatten_todos (CoreDoPasses passes : rest) =
flatten_todos passes ++ flatten_todos rest
flatten_todos (todo : rest) = todo : flatten_todos rest
-- Loading plugins
addPluginPasses :: [CoreToDo] -> CoreM [CoreToDo]
#if !defined(GHCI)
addPluginPasses builtin_passes
= do { dflags <- getDynFlags
; let pluginMods = pluginModNames dflags
; unless (null pluginMods) (pluginError pluginMods)
; return builtin_passes }
#else
addPluginPasses builtin_passes
= do { hsc_env <- getHscEnv
; named_plugins <- liftIO (loadPlugins hsc_env)
; foldM query_plug builtin_passes named_plugins }
where
query_plug todos (_, plug, options) = installCoreToDos plug options todos
#endif
{- Note [Inline in InitialPhase]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In GHC 8 and earlier we did not inline anything in the InitialPhase. But that is
confusing for users because when they say INLINE they expect the function to inline
right away.
So now we do inlining immediately, even in the InitialPhase, assuming that the
Id's Activation allows it.
This is a surprisingly big deal. Compiler performance improved a lot
when I made this change:
perf/compiler/T5837.run T5837 [stat too good] (normal)
perf/compiler/parsing001.run parsing001 [stat too good] (normal)
perf/compiler/T12234.run T12234 [stat too good] (optasm)
perf/compiler/T9020.run T9020 [stat too good] (optasm)
perf/compiler/T3064.run T3064 [stat too good] (normal)
perf/compiler/T9961.run T9961 [stat too good] (normal)
perf/compiler/T13056.run T13056 [stat too good] (optasm)
perf/compiler/T9872d.run T9872d [stat too good] (normal)
perf/compiler/T783.run T783 [stat too good] (normal)
perf/compiler/T12227.run T12227 [stat too good] (normal)
perf/should_run/lazy-bs-alloc.run lazy-bs-alloc [stat too good] (normal)
perf/compiler/T1969.run T1969 [stat too good] (normal)
perf/compiler/T9872a.run T9872a [stat too good] (normal)
perf/compiler/T9872c.run T9872c [stat too good] (normal)
perf/compiler/T9872b.run T9872b [stat too good] (normal)
perf/compiler/T9872d.run T9872d [stat too good] (normal)
Note [RULEs enabled in SimplGently]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
RULES are enabled when doing "gentle" simplification. Two reasons:
* We really want the class-op cancellation to happen:
op (df d1 d2) --> $cop3 d1 d2
because this breaks the mutual recursion between 'op' and 'df'
* I wanted the RULE
lift String ===> ...
to work in Template Haskell when simplifying
splices, so we get simpler code for literal strings
But watch out: list fusion can prevent floating. So use phase control
to switch off those rules until after floating.
************************************************************************
* *
The CoreToDo interpreter
* *
************************************************************************
-}
runCorePasses :: [CoreToDo] -> ModGuts -> CoreM ModGuts
runCorePasses passes guts
= foldM do_pass guts passes
where
do_pass guts CoreDoNothing = return guts
do_pass guts (CoreDoPasses ps) = runCorePasses ps guts
do_pass guts pass
= withTiming getDynFlags
(ppr pass <+> brackets (ppr mod))
(const ()) $ do
{ guts' <- lintAnnots (ppr pass) (doCorePass pass) guts
; endPass pass (mg_binds guts') (mg_rules guts')
; return guts' }
mod = mg_module guts
doCorePass :: CoreToDo -> ModGuts -> CoreM ModGuts
doCorePass pass@(CoreDoSimplify {}) = {-# SCC "Simplify" #-}
simplifyPgm pass
doCorePass CoreCSE = {-# SCC "CommonSubExpr" #-}
doPass cseProgram
doCorePass CoreLiberateCase = {-# SCC "LiberateCase" #-}
doPassD liberateCase
doCorePass CoreDoFloatInwards = {-# SCC "FloatInwards" #-}
floatInwards
doCorePass (CoreDoFloatOutwards f) = {-# SCC "FloatOutwards" #-}
doPassDUM (floatOutwards f)
doCorePass CoreDoStaticArgs = {-# SCC "StaticArgs" #-}
doPassU doStaticArgs
doCorePass CoreDoCallArity = {-# SCC "CallArity" #-}
doPassD callArityAnalProgram
doCorePass CoreDoExitify = {-# SCC "Exitify" #-}
doPass exitifyProgram
doCorePass CoreDoStrictness = {-# SCC "NewStranal" #-}
doPassDFM dmdAnalProgram
doCorePass CoreDoWorkerWrapper = {-# SCC "WorkWrap" #-}
doPassDFU wwTopBinds
doCorePass CoreDoSpecialising = {-# SCC "Specialise" #-}
specProgram
doCorePass CoreDoSpecConstr = {-# SCC "SpecConstr" #-}
specConstrProgram
doCorePass CoreDoVectorisation = {-# SCC "Vectorise" #-}
vectorise
doCorePass CoreDoPrintCore = observe printCore
doCorePass (CoreDoRuleCheck phase pat) = ruleCheckPass phase pat
doCorePass CoreDoNothing = return
doCorePass (CoreDoPasses passes) = runCorePasses passes
#if defined(GHCI)
doCorePass (CoreDoPluginPass _ pass) = {-# SCC "Plugin" #-} pass
#endif
doCorePass pass = pprPanic "doCorePass" (ppr pass)
{-
************************************************************************
* *
\subsection{Core pass combinators}
* *
************************************************************************
-}
printCore :: DynFlags -> CoreProgram -> IO ()
printCore dflags binds
= Err.dumpIfSet dflags True "Print Core" (pprCoreBindings binds)
ruleCheckPass :: CompilerPhase -> String -> ModGuts -> CoreM ModGuts
ruleCheckPass current_phase pat guts =
withTiming getDynFlags
(text "RuleCheck"<+>brackets (ppr $ mg_module guts))
(const ()) $ do
{ rb <- getRuleBase
; dflags <- getDynFlags
; vis_orphs <- getVisibleOrphanMods
; liftIO $ putLogMsg dflags NoReason Err.SevDump noSrcSpan
(defaultDumpStyle dflags)
(ruleCheckProgram current_phase pat
(RuleEnv rb vis_orphs) (mg_binds guts))
; return guts }
doPassDUM :: (DynFlags -> UniqSupply -> CoreProgram -> IO CoreProgram) -> ModGuts -> CoreM ModGuts
doPassDUM do_pass = doPassM $ \binds -> do
dflags <- getDynFlags
us <- getUniqueSupplyM
liftIO $ do_pass dflags us binds
doPassDM :: (DynFlags -> CoreProgram -> IO CoreProgram) -> ModGuts -> CoreM ModGuts
doPassDM do_pass = doPassDUM (\dflags -> const (do_pass dflags))
doPassD :: (DynFlags -> CoreProgram -> CoreProgram) -> ModGuts -> CoreM ModGuts
doPassD do_pass = doPassDM (\dflags -> return . do_pass dflags)
doPassDU :: (DynFlags -> UniqSupply -> CoreProgram -> CoreProgram) -> ModGuts -> CoreM ModGuts
doPassDU do_pass = doPassDUM (\dflags us -> return . do_pass dflags us)
doPassU :: (UniqSupply -> CoreProgram -> CoreProgram) -> ModGuts -> CoreM ModGuts
doPassU do_pass = doPassDU (const do_pass)
doPassDFM :: (DynFlags -> FamInstEnvs -> CoreProgram -> IO CoreProgram) -> ModGuts -> CoreM ModGuts
doPassDFM do_pass guts = do
dflags <- getDynFlags
p_fam_env <- getPackageFamInstEnv
let fam_envs = (p_fam_env, mg_fam_inst_env guts)
doPassM (liftIO . do_pass dflags fam_envs) guts
doPassDFU :: (DynFlags -> FamInstEnvs -> UniqSupply -> CoreProgram -> CoreProgram) -> ModGuts -> CoreM ModGuts
doPassDFU do_pass guts = do
dflags <- getDynFlags
us <- getUniqueSupplyM
p_fam_env <- getPackageFamInstEnv
let fam_envs = (p_fam_env, mg_fam_inst_env guts)
doPass (do_pass dflags fam_envs us) guts
-- Most passes return no stats and don't change rules: these combinators
-- let us lift them to the full blown ModGuts+CoreM world
doPassM :: Monad m => (CoreProgram -> m CoreProgram) -> ModGuts -> m ModGuts
doPassM bind_f guts = do
binds' <- bind_f (mg_binds guts)
return (guts { mg_binds = binds' })
doPass :: (CoreProgram -> CoreProgram) -> ModGuts -> CoreM ModGuts
doPass bind_f guts = return $ guts { mg_binds = bind_f (mg_binds guts) }
-- Observer passes just peek; don't modify the bindings at all
observe :: (DynFlags -> CoreProgram -> IO a) -> ModGuts -> CoreM ModGuts
observe do_pass = doPassM $ \binds -> do
dflags <- getDynFlags
_ <- liftIO $ do_pass dflags binds
return binds
{-
************************************************************************
* *
Gentle simplification
* *
************************************************************************
-}
simplifyExpr :: DynFlags -- includes spec of what core-to-core passes to do
-> CoreExpr
-> IO CoreExpr
-- simplifyExpr is called by the driver to simplify an
-- expression typed in at the interactive prompt
--
-- Also used by Template Haskell
simplifyExpr dflags expr
= withTiming (pure dflags) (text "Simplify [expr]") (const ()) $
do {
; us <- mkSplitUniqSupply 's'
; let sz = exprSize expr
; (expr', counts) <- initSmpl dflags emptyRuleEnv
emptyFamInstEnvs us sz
(simplExprGently (simplEnvForGHCi dflags) expr)
; Err.dumpIfSet dflags (dopt Opt_D_dump_simpl_stats dflags)
"Simplifier statistics" (pprSimplCount counts)
; Err.dumpIfSet_dyn dflags Opt_D_dump_simpl "Simplified expression"
(pprCoreExpr expr')
; return expr'
}
simplExprGently :: SimplEnv -> CoreExpr -> SimplM CoreExpr
-- Simplifies an expression
-- does occurrence analysis, then simplification
-- and repeats (twice currently) because one pass
-- alone leaves tons of crud.
-- Used (a) for user expressions typed in at the interactive prompt
-- (b) the LHS and RHS of a RULE
-- (c) Template Haskell splices
--
-- The name 'Gently' suggests that the SimplMode is SimplGently,
-- and in fact that is so.... but the 'Gently' in simplExprGently doesn't
-- enforce that; it just simplifies the expression twice
-- It's important that simplExprGently does eta reduction; see
-- Note [Simplifying the left-hand side of a RULE] above. The
-- simplifier does indeed do eta reduction (it's in Simplify.completeLam)
-- but only if -O is on.
simplExprGently env expr = do
expr1 <- simplExpr env (occurAnalyseExpr expr)
simplExpr env (occurAnalyseExpr expr1)
{-
************************************************************************
* *
\subsection{The driver for the simplifier}
* *
************************************************************************
-}
simplifyPgm :: CoreToDo -> ModGuts -> CoreM ModGuts
simplifyPgm pass guts
= do { hsc_env <- getHscEnv
; us <- getUniqueSupplyM
; rb <- getRuleBase
; liftIOWithCount $
simplifyPgmIO pass hsc_env us rb guts }
simplifyPgmIO :: CoreToDo
-> HscEnv
-> UniqSupply
-> RuleBase
-> ModGuts
-> IO (SimplCount, ModGuts) -- New bindings
simplifyPgmIO pass@(CoreDoSimplify max_iterations mode)
hsc_env us hpt_rule_base
guts@(ModGuts { mg_module = this_mod
, mg_rdr_env = rdr_env
, mg_deps = deps
, mg_binds = binds, mg_rules = rules
, mg_fam_inst_env = fam_inst_env })
= do { (termination_msg, it_count, counts_out, guts')
<- do_iteration us 1 [] binds rules
; Err.dumpIfSet dflags (dopt Opt_D_verbose_core2core dflags &&
dopt Opt_D_dump_simpl_stats dflags)
"Simplifier statistics for following pass"
(vcat [text termination_msg <+> text "after" <+> ppr it_count
<+> text "iterations",
blankLine,
pprSimplCount counts_out])
; return (counts_out, guts')
}
where
dflags = hsc_dflags hsc_env
print_unqual = mkPrintUnqualified dflags rdr_env
simpl_env = mkSimplEnv mode
active_rule = activeRule mode
active_unf = activeUnfolding mode
do_iteration :: UniqSupply
-> Int -- Counts iterations
-> [SimplCount] -- Counts from earlier iterations, reversed
-> CoreProgram -- Bindings in
-> [CoreRule] -- and orphan rules
-> IO (String, Int, SimplCount, ModGuts)
do_iteration us iteration_no counts_so_far binds rules
-- iteration_no is the number of the iteration we are
-- about to begin, with '1' for the first
| iteration_no > max_iterations -- Stop if we've run out of iterations
= WARN( debugIsOn && (max_iterations > 2)
, hang (text "Simplifier bailing out after" <+> int max_iterations
<+> text "iterations"
<+> (brackets $ hsep $ punctuate comma $
map (int . simplCountN) (reverse counts_so_far)))
2 (text "Size =" <+> ppr (coreBindsStats binds)))
-- Subtract 1 from iteration_no to get the
-- number of iterations we actually completed
return ( "Simplifier baled out", iteration_no - 1
, totalise counts_so_far
, guts { mg_binds = binds, mg_rules = rules } )
-- Try and force thunks off the binds; significantly reduces
-- space usage, especially with -O. JRS, 000620.
| let sz = coreBindsSize binds
, () <- sz `seq` () -- Force it
= do {
-- Occurrence analysis
let { -- Note [Vectorisation declarations and occurrences]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- During the 'InitialPhase' (i.e., before vectorisation), we need to make sure
-- that the right-hand sides of vectorisation declarations are taken into
-- account during occurrence analysis. After the 'InitialPhase', we need to ensure
-- that the binders representing variable vectorisation declarations are kept alive.
-- (In contrast to automatically vectorised variables, their unvectorised versions
-- don't depend on them.)
vectVars = mkVarSet $
catMaybes [ fmap snd $ lookupDVarEnv (vectInfoVar (mg_vect_info guts)) bndr
| Vect bndr _ <- mg_vect_decls guts]
++
catMaybes [ fmap snd $ lookupDVarEnv (vectInfoVar (mg_vect_info guts)) bndr
| bndr <- bindersOfBinds binds]
-- FIXME: This second comprehensions is only needed as long as we
-- have vectorised bindings where we get "Could NOT call
-- vectorised from original version".
; (maybeVects, maybeVectVars)
= case sm_phase mode of
InitialPhase -> (mg_vect_decls guts, vectVars)
_ -> ([], vectVars)
; tagged_binds = {-# SCC "OccAnal" #-}
occurAnalysePgm this_mod active_unf active_rule rules
maybeVects maybeVectVars binds
} ;
Err.dumpIfSet_dyn dflags Opt_D_dump_occur_anal "Occurrence analysis"
(pprCoreBindings tagged_binds);
-- Get any new rules, and extend the rule base
-- See Note [Overall plumbing for rules] in Rules.hs
-- We need to do this regularly, because simplification can
-- poke on IdInfo thunks, which in turn brings in new rules
-- behind the scenes. Otherwise there's a danger we'll simply
-- miss the rules for Ids hidden inside imported inlinings
eps <- hscEPS hsc_env ;
let { rule_base1 = unionRuleBase hpt_rule_base (eps_rule_base eps)
; rule_base2 = extendRuleBaseList rule_base1 rules
; fam_envs = (eps_fam_inst_env eps, fam_inst_env)
; vis_orphs = this_mod : dep_orphs deps } ;
-- Simplify the program
((binds1, rules1), counts1) <-
initSmpl dflags (mkRuleEnv rule_base2 vis_orphs) fam_envs us1 sz $
do { (floats, env1) <- {-# SCC "SimplTopBinds" #-}
simplTopBinds simpl_env tagged_binds
-- Apply the substitution to rules defined in this module
-- for imported Ids. Eg RULE map my_f = blah
-- If we have a substitution my_f :-> other_f, we'd better
-- apply it to the rule to, or it'll never match
; rules1 <- simplRules env1 Nothing rules
; return (getTopFloatBinds floats, rules1) } ;
-- Stop if nothing happened; don't dump output
if isZeroSimplCount counts1 then
return ( "Simplifier reached fixed point", iteration_no
, totalise (counts1 : counts_so_far) -- Include "free" ticks
, guts { mg_binds = binds1, mg_rules = rules1 } )
else do {
-- Short out indirections
-- We do this *after* at least one run of the simplifier
-- because indirection-shorting uses the export flag on *occurrences*
-- and that isn't guaranteed to be ok until after the first run propagates
-- stuff from the binding site to its occurrences
--
-- ToDo: alas, this means that indirection-shorting does not happen at all
-- if the simplifier does nothing (not common, I know, but unsavoury)
let { binds2 = {-# SCC "ZapInd" #-} shortOutIndirections binds1 } ;
-- Dump the result of this iteration
dump_end_iteration dflags print_unqual iteration_no counts1 binds2 rules1 ;
lintPassResult hsc_env pass binds2 ;
-- Loop
do_iteration us2 (iteration_no + 1) (counts1:counts_so_far) binds2 rules1
} }
| otherwise = panic "do_iteration"
where
(us1, us2) = splitUniqSupply us
-- Remember the counts_so_far are reversed
totalise :: [SimplCount] -> SimplCount
totalise = foldr (\c acc -> acc `plusSimplCount` c)
(zeroSimplCount dflags)
simplifyPgmIO _ _ _ _ _ = panic "simplifyPgmIO"
-------------------
dump_end_iteration :: DynFlags -> PrintUnqualified -> Int
-> SimplCount -> CoreProgram -> [CoreRule] -> IO ()
dump_end_iteration dflags print_unqual iteration_no counts binds rules
= dumpPassResult dflags print_unqual mb_flag hdr pp_counts binds rules
where
mb_flag | dopt Opt_D_dump_simpl_iterations dflags = Just Opt_D_dump_simpl_iterations
| otherwise = Nothing
-- Show details if Opt_D_dump_simpl_iterations is on
hdr = text "Simplifier iteration=" <> int iteration_no
pp_counts = vcat [ text "---- Simplifier counts for" <+> hdr
, pprSimplCount counts
, text "---- End of simplifier counts for" <+> hdr ]
{-
************************************************************************
* *
Shorting out indirections
* *
************************************************************************
If we have this:
x_local = <expression>
...bindings...
x_exported = x_local
where x_exported is exported, and x_local is not, then we replace it with this:
x_exported = <expression>
x_local = x_exported
...bindings...
Without this we never get rid of the x_exported = x_local thing. This
save a gratuitous jump (from \tr{x_exported} to \tr{x_local}), and
makes strictness information propagate better. This used to happen in
the final phase, but it's tidier to do it here.
Note [Transferring IdInfo]
~~~~~~~~~~~~~~~~~~~~~~~~~~
We want to propagage any useful IdInfo on x_local to x_exported.
STRICTNESS: if we have done strictness analysis, we want the strictness info on
x_local to transfer to x_exported. Hence the copyIdInfo call.
RULES: we want to *add* any RULES for x_local to x_exported.
Note [Messing up the exported Id's RULES]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We must be careful about discarding (obviously) or even merging the
RULES on the exported Id. The example that went bad on me at one stage
was this one:
iterate :: (a -> a) -> a -> [a]
[Exported]
iterate = iterateList
iterateFB c f x = x `c` iterateFB c f (f x)
iterateList f x = x : iterateList f (f x)
[Not exported]
{-# RULES
"iterate" forall f x. iterate f x = build (\c _n -> iterateFB c f x)
"iterateFB" iterateFB (:) = iterateList
#-}
This got shorted out to:
iterateList :: (a -> a) -> a -> [a]
iterateList = iterate
iterateFB c f x = x `c` iterateFB c f (f x)
iterate f x = x : iterate f (f x)
{-# RULES
"iterate" forall f x. iterate f x = build (\c _n -> iterateFB c f x)
"iterateFB" iterateFB (:) = iterate
#-}
And now we get an infinite loop in the rule system
iterate f x -> build (\cn -> iterateFB c f x)
-> iterateFB (:) f x
-> iterate f x
Old "solution":
use rule switching-off pragmas to get rid
of iterateList in the first place
But in principle the user *might* want rules that only apply to the Id
he says. And inline pragmas are similar
{-# NOINLINE f #-}
f = local
local = <stuff>
Then we do not want to get rid of the NOINLINE.
Hence hasShortableIdinfo.
Note [Rules and indirection-zapping]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Problem: what if x_exported has a RULE that mentions something in ...bindings...?
Then the things mentioned can be out of scope! Solution
a) Make sure that in this pass the usage-info from x_exported is
available for ...bindings...
b) If there are any such RULES, rec-ify the entire top-level.
It'll get sorted out next time round
Other remarks
~~~~~~~~~~~~~
If more than one exported thing is equal to a local thing (i.e., the
local thing really is shared), then we do one only:
\begin{verbatim}
x_local = ....
x_exported1 = x_local
x_exported2 = x_local
==>
x_exported1 = ....
x_exported2 = x_exported1
\end{verbatim}
We rely on prior eta reduction to simplify things like
\begin{verbatim}
x_exported = /\ tyvars -> x_local tyvars
==>
x_exported = x_local
\end{verbatim}
Hence,there's a possibility of leaving unchanged something like this:
\begin{verbatim}
x_local = ....
x_exported1 = x_local Int
\end{verbatim}
By the time we've thrown away the types in STG land this
could be eliminated. But I don't think it's very common
and it's dangerous to do this fiddling in STG land
because we might elminate a binding that's mentioned in the
unfolding for something.
Note [Indirection zapping and ticks]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unfortunately this is another place where we need a special case for
ticks. The following happens quite regularly:
x_local = <expression>
x_exported = tick<x> x_local
Which we want to become:
x_exported = tick<x> <expression>
As it makes no sense to keep the tick and the expression on separate
bindings. Note however that that this might increase the ticks scoping
over the execution of x_local, so we can only do this for floatable
ticks. More often than not, other references will be unfoldings of
x_exported, and therefore carry the tick anyway.
-}
type IndEnv = IdEnv (Id, [Tickish Var]) -- Maps local_id -> exported_id, ticks
shortOutIndirections :: CoreProgram -> CoreProgram
shortOutIndirections binds
| isEmptyVarEnv ind_env = binds
| no_need_to_flatten = binds' -- See Note [Rules and indirect-zapping]
| otherwise = [Rec (flattenBinds binds')] -- for this no_need_to_flatten stuff
where
ind_env = makeIndEnv binds
-- These exported Ids are the subjects of the indirection-elimination
exp_ids = map fst $ nonDetEltsUFM ind_env
-- It's OK to use nonDetEltsUFM here because we forget the ordering
-- by immediately converting to a set or check if all the elements
-- satisfy a predicate.
exp_id_set = mkVarSet exp_ids
no_need_to_flatten = all (null . ruleInfoRules . idSpecialisation) exp_ids
binds' = concatMap zap binds
zap (NonRec bndr rhs) = [NonRec b r | (b,r) <- zapPair (bndr,rhs)]
zap (Rec pairs) = [Rec (concatMap zapPair pairs)]
zapPair (bndr, rhs)
| bndr `elemVarSet` exp_id_set = []
| Just (exp_id, ticks) <- lookupVarEnv ind_env bndr
= [(transferIdInfo exp_id bndr,
mkTicks ticks rhs),
(bndr, Var exp_id)]
| otherwise = [(bndr,rhs)]
makeIndEnv :: [CoreBind] -> IndEnv
makeIndEnv binds
= foldr add_bind emptyVarEnv binds
where
add_bind :: CoreBind -> IndEnv -> IndEnv
add_bind (NonRec exported_id rhs) env = add_pair (exported_id, rhs) env
add_bind (Rec pairs) env = foldr add_pair env pairs
add_pair :: (Id,CoreExpr) -> IndEnv -> IndEnv
add_pair (exported_id, exported) env
| (ticks, Var local_id) <- stripTicksTop tickishFloatable exported
, shortMeOut env exported_id local_id
= extendVarEnv env local_id (exported_id, ticks)
add_pair _ env = env
-----------------
shortMeOut :: IndEnv -> Id -> Id -> Bool
shortMeOut ind_env exported_id local_id
-- The if-then-else stuff is just so I can get a pprTrace to see
-- how often I don't get shorting out because of IdInfo stuff
= if isExportedId exported_id && -- Only if this is exported
isLocalId local_id && -- Only if this one is defined in this
-- module, so that we *can* change its
-- binding to be the exported thing!
not (isExportedId local_id) && -- Only if this one is not itself exported,
-- since the transformation will nuke it
not (local_id `elemVarEnv` ind_env) -- Only if not already substituted for
then
if hasShortableIdInfo exported_id
then True -- See Note [Messing up the exported Id's IdInfo]
else WARN( True, text "Not shorting out:" <+> ppr exported_id )
False
else
False
-----------------
hasShortableIdInfo :: Id -> Bool
-- True if there is no user-attached IdInfo on exported_id,
-- so we can safely discard it
-- See Note [Messing up the exported Id's IdInfo]
hasShortableIdInfo id
= isEmptyRuleInfo (ruleInfo info)
&& isDefaultInlinePragma (inlinePragInfo info)
&& not (isStableUnfolding (unfoldingInfo info))
where
info = idInfo id
-----------------
transferIdInfo :: Id -> Id -> Id
-- See Note [Transferring IdInfo]
-- If we have
-- lcl_id = e; exp_id = lcl_id
-- and lcl_id has useful IdInfo, we don't want to discard it by going
-- gbl_id = e; lcl_id = gbl_id
-- Instead, transfer IdInfo from lcl_id to exp_id
-- Overwriting, rather than merging, seems to work ok.
transferIdInfo exported_id local_id
= modifyIdInfo transfer exported_id
where
local_info = idInfo local_id
transfer exp_info = exp_info `setStrictnessInfo` strictnessInfo local_info
`setUnfoldingInfo` unfoldingInfo local_info
`setInlinePragInfo` inlinePragInfo local_info
`setRuleInfo` addRuleInfo (ruleInfo exp_info) new_info
new_info = setRuleInfoHead (idName exported_id)
(ruleInfo local_info)
-- Remember to set the function-name field of the
-- rules as we transfer them from one function to another
| shlevy/ghc | compiler/simplCore/SimplCore.hs | bsd-3-clause | 45,493 | 2 | 22 | 15,166 | 5,714 | 3,085 | 2,629 | 479 | 8 |
module System.Build.Access.Top where
class Top r where
top ::
Maybe String
-> r
-> r
getTop ::
r
-> Maybe String
| tonymorris/lastik | System/Build/Access/Top.hs | bsd-3-clause | 144 | 0 | 8 | 52 | 45 | 24 | 21 | 9 | 0 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-}
module Data.Typewriter.Data.List where
import Data.Typewriter.Core
type family Head xs :: *
type instance Head (h :*: t) = h
type family Tail xs :: *
type instance Tail (h :*: t) = t
type family Length xs :: *
type instance Length Unit = Z
type instance Length (h :*: t) = S (Length t)
type family Concat xs ys :: *
type instance Concat Unit ys = ys
type instance Concat (x :*: xs) ys = x :*: Concat xs ys
type family Map (f :: * -> *) xs :: *
type instance Map f Unit = Unit
type instance Map f (x :*: xs) = f x :*: Map f xs
type family FoldR (f :: * -> * -> *) z xs :: *
type instance FoldR f z Unit = z
type instance FoldR f z (x :*: xs) = f x (FoldR f z xs)
class List l where
tConcat :: (List a) => l -> a -> Concat l a
tLength :: l -> Length l
tMap :: (forall x. x -> f x) -> l -> Map f l
tFoldR :: (forall x y. x -> y -> f x y) -> z -> l -> FoldR f z l
instance List Unit where
tConcat Unit ys = ys
tLength Unit = Zero
tMap _ Unit = Unit
tFoldR _ z Unit = z
instance (List t) => List (h :*: t) where
tConcat (x :*: xs) ys = x :*: tConcat xs ys
tLength (_ :*: xs) = Succ (tLength xs)
tMap f (x :*: xs) = f x :*: tMap f xs
tFoldR f z (x :*: xs) = f x (tFoldR f z xs)
type family Reverse xs :: *
type instance Reverse Unit = Unit
type instance Reverse (x :*: xs) = Concat (Reverse xs) (x :*: Unit)
instance ListReverse Unit where
tReverse Unit = Unit
class (List l, List (Reverse l)) => ListReverse l where
tReverse :: l -> Reverse l
type family ZipWith (f :: * -> * -> *) xs ys :: *
type instance ZipWith f xs Unit = Unit
type instance ZipWith f Unit ys = Unit
type instance ZipWith f (x :*: xs) (y :*: ys) = f x y :*: ZipWith f xs ys
class (List xs, List ys) => Zip xs ys where
tZipWith :: (forall x y. x -> y -> f x y) -> xs -> ys -> ZipWith f xs ys
instance (Zip xs ys) => Zip (x :*: xs) (y :*: ys) where
tZipWith f (x :*: xs) (y :*: ys) = f x y :*: tZipWith f xs ys
instance (List xs) => Zip (x :*: xs) Unit where
tZipWith _ _ Unit = Unit
instance (List ys) => Zip Unit (y :*: ys) where
tZipWith _ Unit _ = Unit
instance Zip Unit Unit where
tZipWith _ Unit Unit = Unit
| isomorphism/typewriter | Data/Typewriter/Data/List.hs | bsd-3-clause | 2,383 | 0 | 12 | 616 | 1,073 | 583 | 490 | 60 | 0 |
module Events.LeaveChannelConfirm where
import Prelude ()
import Prelude.MH
import qualified Graphics.Vty as Vty
import State.Channels
import Types
onEventLeaveChannelConfirm :: Vty.Event -> MH ()
onEventLeaveChannelConfirm (Vty.EvKey k []) = do
case k of
Vty.KChar c | c `elem` ("yY"::String) ->
leaveCurrentChannel
_ -> return ()
setMode Main
onEventLeaveChannelConfirm _ = return ()
| aisamanra/matterhorn | src/Events/LeaveChannelConfirm.hs | bsd-3-clause | 467 | 0 | 14 | 132 | 135 | 71 | 64 | 14 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Data.GraphQL.AST.Transform where
import Control.Applicative (empty)
import Control.Monad ((<=<))
import Data.Bifunctor (first)
import Data.Either (partitionEithers)
import Data.Foldable (fold, foldMap)
import qualified Data.List.NonEmpty as NonEmpty
import Data.Monoid (Alt(Alt,getAlt), (<>))
import Data.Text (Text)
import qualified Data.GraphQL.AST as Full
import qualified Data.GraphQL.AST.Core as Core
import qualified Data.GraphQL.Schema as Schema
type Name = Text
-- | Replaces a fragment name by a list of 'Field'. If the name doesn't match an
-- empty list is returned.
type Fragmenter = Name -> [Core.Field]
-- TODO: Replace Maybe by MonadThrow with CustomError
document :: Schema.Subs -> Full.Document -> Maybe Core.Document
document subs doc = operations subs fr ops
where
(fr, ops) = first foldFrags
. partitionEithers
. NonEmpty.toList
$ defrag subs
<$> doc
foldFrags :: [Fragmenter] -> Fragmenter
foldFrags fs n = getAlt $ foldMap (Alt . ($ n)) fs
-- * Operation
-- TODO: Replace Maybe by MonadThrow CustomError
operations
:: Schema.Subs
-> Fragmenter
-> [Full.OperationDefinition]
-> Maybe Core.Document
operations subs fr = NonEmpty.nonEmpty <=< traverse (operation subs fr)
-- TODO: Replace Maybe by MonadThrow CustomError
operation
:: Schema.Subs
-> Fragmenter
-> Full.OperationDefinition
-> Maybe Core.Operation
operation subs fr (Full.OperationSelectionSet sels) =
operation subs fr $ Full.OperationDefinition Full.Query empty empty empty sels
-- TODO: Validate Variable definitions with substituter
operation subs fr (Full.OperationDefinition ot _n _vars _dirs sels) =
case ot of
Full.Query -> Core.Query <$> node
Full.Mutation -> Core.Mutation <$> node
where
node = traverse (hush . selection subs fr) sels
selection
:: Schema.Subs
-> Fragmenter
-> Full.Selection
-> Either [Core.Field] Core.Field
selection subs fr (Full.SelectionField fld) =
Right $ field subs fr fld
selection _ fr (Full.SelectionFragmentSpread (Full.FragmentSpread n _dirs)) =
Left $ fr n
selection _ _ (Full.SelectionInlineFragment _) =
error "Inline fragments not supported yet"
-- * Fragment replacement
-- | Extract Fragments into a single Fragmenter function and a Operation
-- Definition.
defrag
:: Schema.Subs
-> Full.Definition
-> Either Fragmenter Full.OperationDefinition
defrag _ (Full.DefinitionOperation op) =
Right op
defrag subs (Full.DefinitionFragment fragDef) =
Left $ fragmentDefinition subs fragDef
fragmentDefinition :: Schema.Subs -> Full.FragmentDefinition -> Fragmenter
fragmentDefinition subs (Full.FragmentDefinition name _tc _dirs sels) name' =
-- TODO: Support fragments within fragments. Fold instead of map.
if name == name'
then either id pure =<< NonEmpty.toList (selection subs mempty <$> sels)
else empty
field :: Schema.Subs -> Fragmenter -> Full.Field -> Core.Field
field subs fr (Full.Field a n args _dirs sels) =
Core.Field a n (fold $ argument subs `traverse` args) (foldr go empty sels)
where
go :: Full.Selection -> [Core.Field] -> [Core.Field]
go (Full.SelectionFragmentSpread (Full.FragmentSpread name _dirs)) = (fr name <>)
go sel = (either id pure (selection subs fr sel) <>)
argument :: Schema.Subs -> Full.Argument -> Maybe Core.Argument
argument subs (Full.Argument n v) = Core.Argument n <$> value subs v
value :: Schema.Subs -> Full.Value -> Maybe Core.Value
value subs (Full.ValueVariable n) = subs n
value _ (Full.ValueInt i) = pure $ Core.ValueInt i
value _ (Full.ValueFloat f) = pure $ Core.ValueFloat f
value _ (Full.ValueString x) = pure $ Core.ValueString x
value _ (Full.ValueBoolean b) = pure $ Core.ValueBoolean b
value _ Full.ValueNull = pure Core.ValueNull
value _ (Full.ValueEnum e) = pure $ Core.ValueEnum e
value subs (Full.ValueList l) =
Core.ValueList <$> traverse (value subs) l
value subs (Full.ValueObject o) =
Core.ValueObject <$> traverse (objectField subs) o
objectField :: Schema.Subs -> Full.ObjectField -> Maybe Core.ObjectField
objectField subs (Full.ObjectField n v) = Core.ObjectField n <$> value subs v
hush :: Either a b -> Maybe b
hush = either (const Nothing) Just
| jdnavarro/graphql-haskell | Data/GraphQL/AST/Transform.hs | bsd-3-clause | 4,328 | 0 | 12 | 822 | 1,357 | 707 | 650 | 90 | 2 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE UndecidableInstances #-}
-----------------------------------------------------------------------------
-- |
-- Copyright : (c) Edward Kmett 2011-2015
-- License : BSD3
--
-- Maintainer : ekmett@gmail.com
-- Stability : experimental
-- Portability : non-portable
--
-- Results and Parse Errors
-----------------------------------------------------------------------------
module Text.Trifecta.Result
(
-- * Parse Results
Result(..)
, AsResult(..)
, _Success
, _Failure
-- * Parsing Errors
, Err(..), HasErr(..), Errable(..)
, ErrInfo(..)
, explain
, failed
) where
import Control.Applicative as Alternative
import Control.Lens hiding (snoc, cons)
import Control.Monad (guard)
import Data.Foldable
import Data.Maybe (fromMaybe, isJust)
import qualified Data.List as List
import Data.Semigroup
import Data.Set as Set hiding (empty, toList)
import Text.PrettyPrint.ANSI.Leijen as Pretty hiding (line, (<>), (<$>), empty)
import Text.Trifecta.Instances ()
import Text.Trifecta.Rendering
import Text.Trifecta.Delta as Delta
data ErrInfo = ErrInfo
{ _errDoc :: Doc
, _errDeltas :: [Delta]
} deriving (Show)
-- | This is used to report an error. What went wrong, some supplemental docs and a set of things expected
-- at the current location. This does not, however, include the actual location.
data Err = Err
{ _reason :: Maybe Doc
, _footnotes :: [Doc]
, _expected :: Set String
, _finalDeltas :: [Delta]
, _ignoredErr :: Maybe Err
}
makeClassy ''Err
instance Semigroup Err where
Err md mds mes delta1 ig1 <> Err nd nds nes delta2 ig2
= Err (nd <|> md) (if isJust nd then nds else if isJust md then mds else nds ++ mds) (mes <> nes) (delta1 <> delta2) (ig1 <> ig2)
{-# INLINE (<>) #-}
instance Monoid Err where
mempty = Err Nothing [] mempty mempty Nothing
{-# INLINE mempty #-}
mappend = (<>)
{-# INLINE mappend #-}
-- | Generate a simple 'Err' word-wrapping the supplied message.
failed :: String -> Err
failed m = Err (Just (fillSep (pretty <$> words m))) [] mempty mempty Nothing
{-# INLINE failed #-}
-- | Convert a location and an 'Err' into a 'Doc'
explain :: Rendering -> Err -> Doc
explain r (Err mm as es _ _)
| Set.null es = report (withEx mempty)
| isJust mm = report $ withEx $ Pretty.char ',' <+> expecting
| otherwise = report expecting
where
now = spaceHack $ toList es
spaceHack [""] = ["space"]
spaceHack xs = List.filter (/= "") xs
withEx x = fromMaybe (fillSep $ text <$> words "unspecified error") mm <> x
expecting = text "expected:" <+> fillSep (punctuate (Pretty.char ',') (text <$> now))
report txt = vsep $ [pretty (delta r) <> Pretty.char ':' <+> red (text "error") <> Pretty.char ':' <+> nest 4 txt]
<|> pretty r <$ guard (not (nullRendering r))
<|> as
class Errable m where
raiseErr :: Err -> m a
instance Monoid ErrInfo where
mempty = ErrInfo mempty mempty
mappend (ErrInfo xs d1) (ErrInfo ys d2) = ErrInfo (vsep [xs, ys]) (max d1 d2)
-- | The result of parsing. Either we succeeded or something went wrong.
data Result a
= Success a
| Failure ErrInfo
deriving (Show,Functor,Foldable,Traversable)
-- | A 'Prism' that lets you embed or retrieve a 'Result' in a potentially larger type.
class AsResult s t a b | s -> a, t -> b, s b -> t, t a -> s where
_Result :: Prism s t (Result a) (Result b)
instance AsResult (Result a) (Result b) a b where
_Result = id
{-# INLINE _Result #-}
-- | The 'Prism' for the 'Success' constructor of 'Result'
_Success :: AsResult s t a b => Prism s t a b
_Success = _Result . dimap seta (either id id) . right' . rmap (fmap Success) where
seta (Success a) = Right a
seta (Failure e) = Left (pure (Failure e))
{-# INLINE _Success #-}
-- | The 'Prism' for the 'Failure' constructor of 'Result'
_Failure :: AsResult s s a a => Prism' s ErrInfo
_Failure = _Result . dimap seta (either id id) . right' . rmap (fmap Failure) where
seta (Failure e) = Right e
seta (Success a) = Left (pure (Success a))
{-# INLINE _Failure #-}
instance Show a => Pretty (Result a) where
pretty (Success a) = pretty (show a)
pretty (Failure xs) = pretty . _errDoc $ xs
instance Applicative Result where
pure = Success
{-# INLINE pure #-}
Success f <*> Success a = Success (f a)
Success _ <*> Failure y = Failure y
Failure x <*> Success _ = Failure x
Failure x <*> Failure y = Failure $ ErrInfo (vsep [_errDoc x, _errDoc y]) (_errDeltas x <> _errDeltas y)
{-# INLINE (<*>) #-}
instance Alternative Result where
Failure x <|> Failure y =
Failure $ ErrInfo (vsep [_errDoc x, _errDoc y]) (_errDeltas x <> _errDeltas y)
Success a <|> Success _ = Success a
Success a <|> Failure _ = Success a
Failure _ <|> Success a = Success a
{-# INLINE (<|>) #-}
empty = Failure mempty
{-# INLINE empty #-}
| mikeplus64/trifecta | src/Text/Trifecta/Result.hs | bsd-3-clause | 5,198 | 0 | 18 | 1,076 | 1,608 | 853 | 755 | 113 | 2 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.EXT.FourTwoTwoPixels
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/EXT/422_pixels.txt EXT_422_pixels> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.EXT.FourTwoTwoPixels (
-- * Enums
gl_422_AVERAGE_EXT,
gl_422_EXT,
gl_422_REV_AVERAGE_EXT,
gl_422_REV_EXT
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
| phaazon/OpenGLRaw | src/Graphics/Rendering/OpenGL/Raw/EXT/FourTwoTwoPixels.hs | bsd-3-clause | 707 | 0 | 4 | 87 | 46 | 37 | 9 | 6 | 0 |
{-# LANGUAGE DeriveDataTypeable, RecordWildCards #-}
module Main where
import Control.Monad (liftM, when)
import Data.Bits
import Data.Char
import Data.List (foldl', nub)
import Numeric
import System.Console.CmdArgs.Implicit
import System.IO
import System.Directory
import System.Exit
data Opts = Opts
{ hex :: [String]
, dec :: [String]
, oct :: [String]
, bin :: [String]
, file_hex :: [FilePath]
, file_dec :: [FilePath]
, file_oct :: [FilePath]
, file_bin :: [FilePath]
, stdin_hex :: Bool
, out_hex :: Bool
, out_dec :: Bool
, out_oct :: Bool
, out_bin :: Bool
} deriving (Data, Typeable, Show, Eq)
progOpts :: Opts
progOpts = Opts
{ hex = [] &= name "x" &= typ "HEXADECIMAL" &= help "Additional hashes in hexadecimal to XOR into (use this flag once for each additional hash; also, do not prefix the hex with `0x'; e.g., use `f3' instead of `0xf3'). Leading zeroes are ignored; trailing non-hex characters (as well as non-leading-hex strings) are also ignored."
, dec = [] &= typ "DECIMAL" &= help "Like --hex, but in decimal (0-9)."
, oct = [] &= name "o" &= typ "OCTAL" &= help "Like --hex, but in octal (0-7)."
, bin = [] &= typ "BINARY" &= help "Like --hex, but in binary (0s and 1s)."
, file_hex = [] &= name "X" &= typFile &= help "Read hex hashes from a file; the expected format of the file is the output of the sha1sum(1) program. You can use this flag multiple times for multiple files."
, file_dec = [] &= name "D" &= typFile &= help "Like --file-hex, but read in decimal values."
, file_oct = [] &= name "O" &= typFile &= help "Like --file-hex, but read in octal values."
, file_bin = [] &= name "B" &= typFile &= help "Like --file-hex, but read in binary values."
, stdin_hex = False &= help "Enable reading from STDIN. Only hexadecimal values (sha1sum(1) format) are read in with this option. If no input files are specified with --file-{hex,dec,bin}, and no other hashes are specified with --{hex,dec,bin}, then this flag is automatically turned on. In other words, if no arguments are specified, then panxor expects input from STDIN."
, out_hex = False &= help "Output the final hash in hexadecimal (without the leading `0x'). If no output format is specified with --out-{hex,dec,bin}, then this flag is turned on automatically."
, out_dec = False &= help "Output the final hash in decimal."
, out_oct = False &= help "Output the final hash in octal."
, out_bin = False &= help "Output the final hash in binary."
}
&= details
[ "Notes:"
, ""
, " Panxor can read in any arbitrarily long hex, decimal, or binary string, and is also compatible with the sha1sum(1) format."
]
getOpts :: IO Opts
getOpts = cmdArgs $ progOpts
&= summary (_PROGRAM_INFO ++ ", " ++ _COPYRIGHT)
&= program _PROGRAM_NAME
&= help _PROGRAM_DESC
&= helpArg [explicit, name "help", name "h"]
&= versionArg [explicit, name "version", name "v", summary _PROGRAM_INFO]
_PROGRAM_NAME
, _PROGRAM_VERSION
, _PROGRAM_INFO
, _PROGRAM_DESC
, _COPYRIGHT :: String
_PROGRAM_NAME = "panxor"
_PROGRAM_VERSION = "0.0.2"
_PROGRAM_INFO = _PROGRAM_NAME ++ " version " ++ _PROGRAM_VERSION
_PROGRAM_DESC = "binary XOR multiple hex, decimal, octal, or binary values"
_COPYRIGHT = "(C) Linus Arver 2012"
data Color
= Red
| Green
| Yellow
| Blue
| Magenta
| Cyan
deriving (Show, Eq)
colorize :: Color -> String -> String
colorize c s = c' ++ s ++ e
where
c' = "\x1b[" ++ case c of
Red -> "1;31m"
Green -> "1;32m"
Yellow -> "1;33m"
Blue -> "1;34m"
Magenta -> "1;35m"
Cyan -> "1;36m"
e = "\x1b[0m"
argsCheck :: Opts -> IO Int
argsCheck Opts{..}
| otherwise = return 0
-- Verify that the --file and --list arguments actually make sense.
filesCheck :: [Bool] -> IO Int
filesCheck fs
| elem False fs = errMsgNum "an argument to --file does not exist" 1
| otherwise = return 0
main :: IO ()
main = do
hSetBuffering stdout NoBuffering
hSetBuffering stderr NoBuffering
hSetEcho stdin False -- disable terminal echo
opts <- getOpts
(\e -> when (e > 0) . exitWith $ ExitFailure e) =<< argsCheck opts
let
opts'@Opts{..} = autoOpts opts -- automatically use sane defaults
stdinHashHex <- return . xorNum NumHex =<< (if stdin_hex
then getContents
else return [])
fs <- mapM doesFileExist (file_hex ++ file_dec ++ file_oct ++ file_bin)
(\e -> when (e > 0) . exitWith $ ExitFailure e) =<< filesCheck fs
errNo' <- filesCheck fs
when (errNo' > 0) $ exitWith $ ExitFailure errNo'
prog opts' stdinHashHex file_hex file_dec file_oct file_bin
autoOpts :: Opts -> Opts
autoOpts opts@Opts{..} = opts
{ stdin_hex = null
(hex
++ dec
++ oct
++ bin
++ file_hex
++ file_dec
++ file_oct
++ file_bin)
}
prog
:: Opts
-> Integer
-> [FilePath]
-> [FilePath]
-> [FilePath]
-> [FilePath]
-> IO ()
prog Opts{..} stdinHashHex filesHex filesDec filesOct filesBin = do
filesHashHex <- mapM (return . liftM (xorNum NumHex) =<< readFile) filesHex
filesHashDec <- mapM (return . liftM (xorNum NumDec) =<< readFile) filesDec
filesHashOct <- mapM (return . liftM (xorNum NumOct) =<< readFile) filesOct
filesHashBin <- mapM (return . liftM (xorNum NumBin) =<< readFile) filesBin
let
hashesHex = map (xorNum NumHex) hex
hashesDec = map (xorNum NumDec) dec
hashesOct = map (xorNum NumOct) oct
hashesBin = map (xorNum NumBin) bin
hash = foldl' xor stdinHashHex
( filesHashHex
++ filesHashDec
++ filesHashOct
++ filesHashBin
++ hashesHex
++ hashesDec
++ hashesOct
++ hashesBin
)
putStrLn $ showStyle hash []
where
showStyle :: (Integral a, Show a) => a -> ShowS
showStyle
| out_hex = showHex
| out_dec = showInt
| out_oct = showOct
| out_bin = showIntAtBase 2 intToDigit
| otherwise = showHex
data NumBase
= NumHex
| NumDec
| NumOct
| NumBin
deriving (Eq)
-- Takes a sha1sum(1) formatted string (hex hashes), and XORs all of the hashes in there.
xorNum :: NumBase -> String -> Integer
xorNum b = foldl' xor 0
. map
( (\x -> if null x
then 0
else fst $ head x)
. (case b of
NumHex -> readHex
NumDec -> readDec
NumOct -> readOct
NumBin -> readInt 2 isBinaryDigit digitToBinaryInt
)
)
. nub
. filter (not . null)
. lines
where
isBinaryDigit :: Char -> Bool
isBinaryDigit c = c == '0' || c == '1'
digitToBinaryInt :: Char -> Int
digitToBinaryInt c
| c == '0' = 0
| c == '1' = 1
| otherwise = error $ "digitToBinaryInt: not a binary digit " ++ squote (show c)
errMsg :: String -> IO ()
errMsg msg = hPutStrLn stderr $ "error: " ++ msg
errMsgNum :: String -> Int -> IO Int
errMsgNum str num = errMsg str >> return num
squote :: String -> String
squote s = "`" ++ s ++ "'"
| listx/syscfg | script/panxor.hs | bsd-3-clause | 6,620 | 56 | 18 | 1,355 | 1,972 | 1,015 | 957 | 183 | 6 |
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE FlexibleContexts #-}
module EFA.Application.Simulation where
import EFA.Application.Utility (quantityTopology)
import qualified EFA.Application.Optimisation.Sweep as Sweep
import EFA.Application.Optimisation.Params (Name(Name))
import qualified EFA.Application.Optimisation.Params as Params
import qualified EFA.Flow.Topology.Absolute as EqSys
import qualified EFA.Flow.Topology.Quantity as FlowTopo
import qualified EFA.Flow.Topology.Index as XIdx
import qualified EFA.Flow.Topology.Variable as Variable
import EFA.Flow.Topology.Absolute ( (.=), (=.=) )
import qualified EFA.Flow.Absolute as EqAbs
import qualified EFA.Equation.Arithmetic as Arith
import qualified EFA.Equation.RecordIndex as RecIdx
import qualified EFA.Equation.Verify as Verify
import EFA.Equation.Result (Result)
import qualified EFA.Graph.Topology.Node as Node
import qualified EFA.Graph.Topology as Topo
import qualified EFA.Signal.Vector as SV
import qualified EFA.Signal.Signal as Sig
import qualified EFA.Signal.Record as Record
import qualified EFA.Signal.Data as Data
import EFA.Signal.Data (Data(Data), Nil,(:>))
import qualified UniqueLogic.ST.TF.System as ULSystem
import qualified Data.Map as Map
import qualified Data.Foldable as Fold
import Data.Map (Map)
import Data.Monoid((<>))
solve ::
(Ord c, Show c, Arith.ZeroTestable c, Arith.Constant c,
SV.Storage t c, SV.Storage t Bool, SV.Singleton t, SV.Len (t d),
Node.C node, SV.Zipper t, SV.Walker t,
SV.FromList t) =>
Topo.Topology node ->
Map (XIdx.Position node) (Name, Name) ->
Map Name (Params.EtaFunction c c) ->
Record.Record s s1 typ t1 (XIdx.Position node) t d c ->
FlowTopo.Section node (EFA.Equation.Result.Result (Data (t :> Nil) c))
solve topology etaAssign etaFunc powerRecord =
EqSys.solve (quantityTopology topology) $
givenSimulate etaAssign etaFunc powerRecord
givenSimulate ::
(Ord c, Show c, Arith.Constant c, Node.C node,
Verify.GlobalVar mode
(Data (t :> Nil) c)
(RecIdx.Record RecIdx.Absolute (Variable.Signal node)),
SV.Zipper t, SV.Walker t, SV.Storage t c, SV.Len (t d),
SV.FromList t) =>
Map (XIdx.Position node) (Name, Name) ->
Map Name (Params.EtaFunction c c) ->
Record.Record s1 s2 typ t1 (XIdx.Position node) t d c ->
EqSys.EquationSystem mode node s (Data (t :> Nil) c)
givenSimulate etaAssign etaFunc (Record.Record t xs) =
(XIdx.dTime .=
(Data $ SV.fromList $ replicate (Sig.len t) $ Arith.one))
<> EqSys.withExpressionGraph (makeEtaFuncGiven etaAssign etaFunc)
<> Fold.fold (Map.mapWithKey f xs)
where
f ppos p = XIdx.powerFromPosition ppos .= Sig.unpack p
-- | Generate given equations using efficiency curves or functions for a specified section
makeEtaFuncGiven ::
(Ord node, Ord d1, Show d1,
ULSystem.Value mode (Data c d1),
Arith.Constant d1, Data.ZipWith c, Data.Storage c d1) =>
Map (XIdx.Position node) (Name, Name) ->
Map Name (Params.EtaFunction d1 d1) ->
FlowTopo.Section node (EqAbs.Expression mode vars s (Data c d1)) ->
EqAbs.VariableSystem mode vars s
makeEtaFuncGiven etaAssign etaFunc topo =
Fold.fold $
Map.mapWithKey
(\se (strP, strN) ->
Fold.foldMap
(\(eta, power) ->
eta
=.=
EqAbs.liftF
(Data.map (absEtaFunction strP strN etaFunc))
power)
(FlowTopo.lookupAutoDirSection
(\flow -> (FlowTopo.flowEta flow, FlowTopo.flowPowerOut flow))
(\flow -> (FlowTopo.flowEta flow, FlowTopo.flowPowerIn flow))
id se topo))
etaAssign
makeEtaFuncGiven2 ::
(Ord node, Ord a, Show a, ULSystem.Value mode (sweep vec a),
Arith.Sum (sweep vec a), Arith.Constant a,
Sweep.SweepMap sweep vec a a) =>
Map (XIdx.Position node) (Name, Name) ->
Map Name (Params.EtaFunction a a) ->
FlowTopo.Section node (EqAbs.Expression mode vars s (sweep vec a)) ->
EqAbs.VariableSystem mode vars s
makeEtaFuncGiven2 etaAssign etaFunc topo =
Fold.fold $
Map.mapWithKey
(\se (strP, strN) ->
Fold.foldMap
(\(eta, power) ->
eta =.= EqAbs.liftF (Sweep.map (absEtaFunction strP strN etaFunc)) power)
(FlowTopo.lookupAutoDirSection
(\flow -> (FlowTopo.flowEta flow, FlowTopo.flowPowerOut flow))
(\flow -> (FlowTopo.flowEta flow, FlowTopo.flowPowerIn flow))
id se topo))
etaAssign
absEtaFunction ::
(Ord a, Show a, Arith.Constant a, Arith.Product b) =>
Name -> Name -> Map Name (Params.EtaFunction a b) -> a -> b
absEtaFunction strP strN etaFunc =
let fpos = check strP id $ Map.lookup strP $ Map.map Params.func etaFunc
fneg = check strN rev $ Map.lookup strN $ Map.map Params.func etaFunc
rev h = Arith.recip . h . Arith.negate
check (Name str) =
maybe (\x -> error ("not defined: '" ++ str ++ "' for " ++ show x))
in \x -> if x >= Arith.zero then fpos x else fneg x
| energyflowanalysis/efa-2.1 | src/EFA/Application/Simulation.hs | bsd-3-clause | 5,080 | 0 | 17 | 1,078 | 1,774 | 966 | 808 | 115 | 2 |
{-# LANGUAGE ViewPatterns, TupleSections #-}
-- | Easy logging of images and matrices(palnned) for CV research.
-- messages are send via TCP connection as MessagePack objects.
--
-- * ["str", utf8 string]: string
--
-- * ["uni", "u8", shape, raw]: uniform array
--
module Main where
import Control.Concurrent
import Control.Concurrent.Chan
import Control.Concurrent.MVar
import Data.IORef
import Data.List
import Control.Monad
import Graphics.UI.Gtk
import Graphics.UI.Gtk.Gdk.Events as Ev
import Graphics.Rendering.Cairo
import System.IO
import qualified Data.ByteString as BS
import Text.Printf
import Network
import Data.Word
import Data.Array.MArray
import Data.MessagePack as MP
import Data.Attoparsec.ByteString as Atto
import qualified Data.Array.Base as Unsafe
import qualified Codec.Binary.UTF8.String
import qualified Data.Foldable as Fold
import qualified Data.Sequence as Seq
import qualified Data.Set as Set
type Model = (MVar (Seq.Seq Message), MVar (Set.Set String))
data Message =
StringMessage String |
UniformArrayMessage [Int] BS.ByteString
deriving(Show)
main = do
let port = 8001
(mseq, mClients) <- runServer port
initGUI
window <- windowNew
vb <- vBoxNew False 1
status <- hBoxNew False 0
lb <- labelNew (Just $ printf "listening on port %d" port)
lbClients <- labelNew (Just "")
clear <- buttonNewFromStock "gtk-clear"
on clear buttonActivated $ void $ swapMVar mseq Seq.empty
hb <- hBoxNew False 0
tb <- vBoxNew False 0
refill mseq tb 0
adj <- adjustmentNew 0 1 100 1 20 20
onScroll window $ \ev->do
v0 <- adjustmentGetValue adj
delta <- adjustmentGetPageIncrement adj
case Ev.eventDirection ev of
ScrollDown -> adjustmentSetValue adj (v0+delta/3)
ScrollUp -> adjustmentSetValue adj (v0-delta/3)
_ -> return ()
return True
scr <- vScrollbarNew adj
on scr valueChanged (adjustmentGetValue adj >>= refill mseq tb)
boxPackStart hb tb PackGrow 0
boxPackStart hb scr PackNatural 0
boxPackStart status lb PackGrow 0
boxPackStart status clear PackNatural 0
boxPackStart vb status PackNatural 0
boxPackStart vb lbClients PackNatural 0
boxPackStart vb hb PackGrow 0
set window [containerChild := vb]
nmseq <- newIORef 0
nmcls <- newIORef 0
let
updateLog=do
prev_n <- readIORef nmseq
curr_n <- withMVar mseq (return . Seq.length)
when (curr_n/=prev_n) $ do
adjustmentSetUpper adj $ fromIntegral curr_n
adjustmentGetValue adj >>= refill mseq tb
writeIORef nmseq curr_n
updateClients = do
prev_n <- readIORef nmcls
curr_n <- withMVar mClients (return . Set.size)
when (curr_n/=prev_n) $ do
str <- withMVar mClients (return . intercalate " / " . Fold.toList)
labelSetText lbClients str
writeIORef nmcls curr_n
timeoutAdd (updateLog >> updateClients >> return True) 50
onDestroy window mainQuit
widgetShowAll window
mainGUI
-- seems ok
refill mseq box fromd=do
let from=floor $ realToFrac fromd-1
mapM_ widgetDestroy =<< containerGetChildren box
msgs <- withMVar mseq $ return . Fold.toList . fst . Seq.splitAt 20 . snd . Seq.splitAt from
mapM_ (\msg->do{l<-instantiateView msg; boxPackStart box l PackNatural 0}) msgs
widgetShowAll box
instantiateView :: Message -> IO Widget
instantiateView (StringMessage x)=do
l <- labelNew (Just x)
set l [miscXalign := 0]
return $ castToWidget l
instantiateView (UniformArrayMessage shape raw)=do
l <- drawingAreaNew
surf <- arrayToSurface shape raw
widgetSetSizeRequest l (-1) $ max 25 (head shape)
onExpose l $ \ev -> do
dw <- widgetGetDrawWindow l
w <- imageSurfaceGetWidth surf
renderWithDrawable dw $ do
save
when (w<15) $ scale 3 3
setSourceSurface surf 0 0
getSource >>= flip patternSetFilter FilterNearest
paint
restore
return True
return $ castToWidget l
arrayToSurface :: [Int] -> BS.ByteString -> IO Surface
arrayToSurface [h,w] raw = arrayToSurface [h,w,1] raw
arrayToSurface [h,w,c] raw = do
surf <- createImageSurface FormatRGB24 w h
arr <- imageSurfaceGetPixels surf -- BGRA packing
case c of
1 -> mapM_ (\i -> transfer1 arr i) [0..w*h-1]
3 -> mapM_ (\i -> transfer3 arr i) [0..w*h-1]
_ -> mapM_ (\i -> transfer arr i) [0..w*h-1]
return surf
where
transfer arr i = do
mapM_ (\d -> Unsafe.unsafeWrite arr (i*4+d) $ BS.index raw (i*c+d)) [0..min c 3-1]
transfer1 arr i = do
let v = BS.index raw i
Unsafe.unsafeWrite arr (i*4+0) v
Unsafe.unsafeWrite arr (i*4+1) v
Unsafe.unsafeWrite arr (i*4+2) v
transfer3 arr i = do
Unsafe.unsafeWrite arr (i*4+0) $ BS.index raw (i*3+2)
Unsafe.unsafeWrite arr (i*4+1) $ BS.index raw (i*3+1)
Unsafe.unsafeWrite arr (i*4+2) $ BS.index raw (i*3+0)
arrayToSurface shape _ = do
putStrLn "unknown shape"
print shape
createImageSurface FormatRGB24 1 1
runServer :: Int -> IO Model
runServer port = do
mLog <- newMVar Seq.empty
mClients <- newMVar Set.empty
ch <- newChan
forkIO $ forever $ do
x <- readChan ch
modifyMVar_ mLog $ return . (Seq.|> x)
sock <- listenOn (PortNumber $ fromIntegral port)
putStrLn "started listening"
forkIO $ forever $ do
(h, host, port) <- accept sock
let clientName = printf "%s %s" host (show port)
modifyMVar_ mClients $ return . Set.insert clientName
hSetBuffering h NoBuffering
forkIO $ do
handleConn ch h (Atto.parse MP.get)
modifyMVar_ mClients $ return . Set.delete clientName
return (mLog, mClients)
handleConn ch h parse_cont = BS.hGet h 1024 >>= resolveFull parse_cont
where
resolveFull parse_cont x = do
case parse_cont x of
Fail _ ctx err -> putStrLn "wrong packet"
Partial f -> handleConn ch h f
Done rest packet -> do
case translateMessage packet of
Nothing -> return () -- ignore
Just msg -> writeChan ch msg
resolveFull (Atto.parse MP.get) rest
translateMessage :: [MP.Object] -> Maybe Message
translateMessage
[ObjectRAW (decodeUTF8 -> "str"),
(ObjectRAW msg)]=Just $ StringMessage $ decodeUTF8 msg
translateMessage
[ObjectRAW (decodeUTF8 -> "uni"),
ObjectRAW (decodeUTF8 -> "u8"),
shape_raw,
ObjectRAW raw]=do
shape <- MP.fromObject shape_raw
if BS.length raw==product shape
then return $ UniformArrayMessage shape raw
else Nothing
translateMessage _=Nothing
decodeUTF8 :: BS.ByteString -> String
decodeUTF8 = Codec.Binary.UTF8.String.decode . BS.unpack
| xanxys/mmterm | Main.hs | bsd-3-clause | 7,101 | 0 | 20 | 1,984 | 2,426 | 1,164 | 1,262 | 180 | 4 |
module DTW
(
dtw, cdtw, gdtw
) where
import Data.Array
import Data.List (foldl1')
add :: (Double, Int) -> (Double, Int) -> (Double, Int)
add (a, b) (c, d) = (a+c, b+d)
quo :: (Double, Int) -> Double
quo (a, b) = a/(fromIntegral b)
-- Unconstrained DTW
dtw :: Eq a => ( a -> a -> Double ) -> [a] -> [a] -> Double
dtw measure s [] = gdtw measure [] s
dtw measure [] _ = error "Can not compare empty series!"
dtw measure s o = quo $ a!(n,m) where
n = length s
s' = listArray (1, n) s
m = length o
o' = listArray (1, m) o
a = array ((0,0),(n,m))
([((i,j), (1/0, 0)) | i <- [0..n], j <- [0..m]] ++
[((0,0), (0, 0))] ++
[((i,j), (measure (s'!i) (o'!j), 1) `add` minimum [a!(i,j-1), a!(i-1,j-1), a!(i-1,j)])
| i <- [1..n], j <- [1..m]])
-- Constrained DTW
cdtw :: Eq a => ( a -> a -> Double ) -> Int -> [a] -> [a] -> Double
cdtw measure w s [] = gdtw measure [] s
cdtw measure w [] _ = error "Can not compare empty series!"
cdtw measure w s o = quo $ a!(n,m) where
n = length s
s' = listArray (1, n) s
m = length o
o' = listArray (1, m) o
a = array ((0,0),(n,m))
([((i,j), (1/0, 1)) | i <- [0..n], j <- [0..m]] ++
[((0,0), (0, 1))] ++
[((i,j), (measure (s'!i) (o'!j), 1) `add` minimum [a!(i,j-1), a!(i-1,j-1), a!(i-1,j)] )
| i <- [1..n], j <- [max 1 (i-w)..min m (i+w)]])
-- Greedy dtw
gdtw :: Eq a => ( a -> a -> Double ) -> [a] -> [a] -> Double
gdtw measure s [] = gdtw measure [] s
gdtw measure [] _ = error "Can not compare empty series!"
gdtw measure s o = quo $ gdtw' measure s o (measure (head s) (head o), 1) where
gdtw' measure [a] s (r,l) = (r + foldl1' (+) (map (measure a) s), l + length s)
gdtw' measure s [a] (r,l) = gdtw' measure [a] s (r,l)
gdtw' measure s o (r,l) | left == min = gdtw' measure (tail s) o (r + left, l+1)
| middle == min = gdtw' measure (tail s) (tail o) (r + middle, l+1)
| right == min = gdtw' measure s (tail o) (r + right, l+1)
where
left = measure ((head.tail) s) (head o)
middle = measure ((head.tail) s) ((head.tail) o)
right = measure (head s) ((head.tail) o)
min = minimum [left, middle, right] | kirel/detexify-hs-backend | src/DTW.hs | mit | 2,359 | 0 | 17 | 758 | 1,456 | 802 | 654 | 48 | 3 |
{-# LANGUAGE ScopedTypeVariables
, GADTs
#-}
{-# OPTIONS_GHC
-F
-pgmF hspec-discover
-optF --module-name=Spec
-fno-warn-implicit-prelude
#-}
| hanepjiv/make10_hs | test/spec/Spec.hs | mit | 183 | 0 | 2 | 57 | 4 | 3 | 1 | 3 | 0 |
{-# LANGUAGE PatternGuards #-}
module Lambda.Text.Reduction
( rNF
, rHNF
, reduce1
, isNF
, isHNF
) where
import Lambda.Text.Term
import Lambda.Text.InputSet
import qualified Lambda.Text.Substitution as S
reduce2NF :: NormalForm -> InputSet -> Term -> Term
reduce2NF nf ips t = undefined
sequentialize :: InputSet -> Term -> [Term]
sequentialize ips t = seqize ips t []
seqize :: InputSet -> Term -> [Term] -> [Term]
seqize ips (Var a) ap = undefined
seqize ips (Abs a t) ap = undefined
seqize ips (App p q) ap | (Var a) <- p = undefined
seqize ips (App p q) ap | (Abs a t) <- p = undefined
seqize ips (App p q) ap | (App t u) <- p = undefined
{-
f x y z
= (f x) y z
= ((f x) y) z
-}
-- ????????????????????????????
-- Q: not in Δ => is a Δ-redex
-- ????????????????????????????
{- ######################################### -}
rNF :: InputSet -> Term -> Maybe Term
rNF is (Var a) = Just (Var a)
rNF is (Abs a t) | Just u <- rNF is t = if t == u
then Nothing else Just (Abs a u)
rNF is (Abs a t) | Nothing <- rNF is t = Nothing
rNF is (App p q) | Just s <- rNF is p
, Just t <- rNF is q
= if (s == p || t == q)
then Nothing
else if isRedex is (App s t)
then let u = reduce1 is (App s t) in
if u == (App s t)
then Nothing
else rNF is u
else Just (App s t)
rNF is (App p q) | otherwise
= Nothing
rHNF :: InputSet -> Term -> Maybe Term
rHNF = rNF
isNF :: InputSet -> Term -> Bool
isNF = undefined
isHNF :: InputSet -> Term -> Bool
isHNF = undefined
reduce1 :: InputSet -> Term -> Term
reduce1 is (Var a) = Var a
reduce1 is (Abs a t) = Abs a (reduce1 is t)
--
reduce1 is (App p q) | not $ inInputSet is q
, isRedex is q
= App p (reduce1 is q)
reduce1 is (App p q) | not $ inInputSet is q
, not $ isRedex is q
, not $ isRedex is p
= (App p q)
--
reduce1 is (App p q) | not $ inInputSet is q
, not $ isRedex is q
, isRedex is p
, isHNF is p
= S.subs t q a where (Abs a t) = p
--
reduce1 is (App p q) | not $ isHNF is p
= reduce1 is (App p q)
--
| jaiyalas/haha | src/Lambda/Text/Reduction.hs | mit | 2,478 | 0 | 14 | 979 | 982 | 489 | 493 | 60 | 5 |
module Dampf.ConfigFile.Pretty
( pShowDampfConfig
) where
import Control.Lens
import qualified Data.Map.Strict as Map
import qualified Data.Text as T
import Text.PrettyPrint
import Dampf.ConfigFile.Types
pShowDampfConfig :: DampfConfig -> String
pShowDampfConfig = render . hang (text "Config File:") 4 . pprDampfConfig
pprDampfConfig :: DampfConfig -> Doc
pprDampfConfig cfg = vcat
[ pprDatabaseServer d
]
where
d = cfg ^. postgres
pprLiveCertificate :: Maybe FilePath -> Doc
pprLiveCertificate (Just l) = vcat
[ text "Live Certificate:"
, text ""
, nest 4 (text l)
, text ""
]
pprLiveCertificate Nothing = empty
pprDatabaseServer :: Maybe PostgresConfig -> Doc
pprDatabaseServer (Just s) = vcat
[ text "Database Server:"
, text ""
, nest 4 (pprPostgresConfig s)
, text ""
]
pprDatabaseServer Nothing = empty
pprPostgresConfig :: PostgresConfig -> Doc
pprPostgresConfig cfg = vcat
[ text "host:" <+> text h
, text "port:" <+> int p
, text "users:"
, nest 4 (pprMap u)
]
where
h = cfg ^. host . to T.unpack
p = cfg ^. port
u = cfg ^. users . to Map.toList
pprMap :: (Show a) => [(a, a)] -> Doc
pprMap kvs = vcat
$ fmap (\(k, v) -> text (show k) <> colon <+> text (show v)) kvs
| diffusionkinetics/open | dampf/lib/Dampf/ConfigFile/Pretty.hs | mit | 1,322 | 0 | 13 | 344 | 450 | 236 | 214 | -1 | -1 |
module Main where
import Console.Options
import Data.Char (isDigit)
import Data.Monoid
data MyADT = A | B | C
deriving (Show,Eq)
main = defaultMain $ do
programName "my-simple-program"
programDescription "an optional description of your program that can be found in the help"
-- a simple boolean flag -v or --verbose
showFlag <- flag (FlagShort 'v' <> FlagLong "verbose" <> FlagDescription "activate verbose mode")
-- a flag '-n' or '--name' requiring a string as parameter
nameFlag <- flagParam (FlagShort 'n' <> FlagLong "name" <> FlagDescription "name of something")
(FlagRequired $ \s -> Right s)
-- a flag 'i' or '--int' requiring an integer as parameter
valueFlag <- flagParam (FlagShort 'i' <> FlagLong "int" <> FlagDescription "an integer value")
(FlagRequired $ \s -> if all isDigit s then Right (read s :: Int) else Left "invalid integer")
-- a flag with an optional parameter, defaulting to some value
xyzFlag <- flagParam (FlagShort 'x' <> FlagLong "xyz" <> FlagDescription "some ADT option")
(FlagOptional B (\s -> if s == "A" then Right A else if s == "B" then Right B else if s == "C" then Right C else Left "invalid value"))
action $ \toParam -> do
putStrLn $ show $ toParam showFlag
putStrLn $ show $ toParam nameFlag
putStrLn $ show $ toParam valueFlag
putStrLn $ show $ toParam xyzFlag
| NicolasDP/hs-cli | examples/Simple.hs | bsd-3-clause | 1,477 | 0 | 17 | 390 | 386 | 190 | 196 | 21 | 5 |
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Arrays where
import Language.VHDL (Mode(..))
import Language.Embedded.Hardware
import Control.Monad.Identity
import Control.Monad.Operational.Higher
import Data.ALaCarte
import Data.Int
import Data.Word
import Text.PrettyPrint
import Prelude hiding (and, or, not)
--------------------------------------------------------------------------------
-- * Example of a program that words with variable length bit arrarys.
--------------------------------------------------------------------------------
-- | Command set used for our programs.
type CMD =
SignalCMD
:+: VariableCMD
:+: ArrayCMD
:+: VArrayCMD
:+: LoopCMD
:+: ConditionalCMD
:+: ComponentCMD
:+: ProcessCMD
:+: VHDLCMD
type HProg = Program CMD (Param2 HExp HType)
type HSig = Sig CMD HExp HType Identity
--------------------------------------------------------------------------------
arrays :: HProg ()
arrays =
do a :: Array Word8 <- newArray 20
b :: VArray Word8 <- newVArray 10
setArray a 0 0
setVArray b 1 1
resetArray a 1
va :: HExp Word8 <- getArray a 0
vb :: HExp Word8 <- getVArray b 1
setArray a 0 (va + 2 - vb)
setVArray b 1 (vb + 2 - va)
copyArray (a, 0) (a, 2) 4
--------------------------------------------------------------------------------
test = icompile arrays
--------------------------------------------------------------------------------
| markus-git/imperative-edsl-vhdl | examples/Array.hs | bsd-3-clause | 1,557 | 0 | 12 | 281 | 342 | 181 | 161 | 39 | 1 |
{-# LANGUAGE CPP #-}
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702
{-# LANGUAGE Trustworthy #-}
#endif
------------------------------------------------------------------------
-- |
-- Module : Data.Hashable
-- Copyright : (c) Milan Straka 2010
-- (c) Johan Tibell 2011
-- (c) Bryan O'Sullivan 2011, 2012
-- License : BSD-style
-- Maintainer : johan.tibell@gmail.com
-- Stability : provisional
-- Portability : portable
--
-- This module defines a class, 'Hashable', for types that can be
-- converted to a hash value. This class exists for the benefit of
-- hashing-based data structures. The module provides instances for
-- most standard types. Efficient instances for other types can be
-- generated automatically and effortlessly using the generics support
-- in GHC 7.2 and above.
--
-- The easiest way to get started is to use the 'hash' function. Here
-- is an example session with @ghci@.
--
-- > ghci> import Data.Hashable
-- > ghci> hash "foo"
-- > 60853164
module Data.Hashable
(
-- * Hashing and security
-- $security
-- * Computing hash values
Hashable(..)
-- * Creating new instances
-- | There are two ways to create new instances: by deriving
-- instances automatically using GHC's generic programming
-- support or by writing instances manually.
-- ** Generic instances
-- $generics
-- *** Understanding a compiler error
-- $generic_err
-- ** Writing instances by hand
-- $blocks
-- *** Hashing contructors with multiple fields
-- $multiple-fields
-- *** Hashing types with multiple constructors
-- $multiple-ctors
, hashUsing
, hashPtr
, hashPtrWithSalt
#if defined(__GLASGOW_HASKELL__)
, hashByteArray
, hashByteArrayWithSalt
#endif
) where
import Data.Hashable.Class
#ifdef GENERICS
import Data.Hashable.Generic ()
#endif
-- $security
-- #security#
--
-- Applications that use hash-based data structures to store input
-- from untrusted users can be susceptible to \"hash DoS\", a class of
-- denial-of-service attack that uses deliberately chosen colliding
-- inputs to force an application into unexpectedly behaving with
-- quadratic time complexity.
--
-- At this time, the string hashing functions used in this library are
-- susceptible to such attacks and users are recommended to either use
-- a 'Data.Map' to store keys derived from untrusted input or to use a
-- hash function (e.g. SipHash) that's resistant to such attacks. A
-- future version of this library might ship with such hash functions.
-- $generics
--
-- Beginning with GHC 7.2, the recommended way to make instances of
-- 'Hashable' for most types is to use the compiler's support for
-- automatically generating default instances.
--
-- > {-# LANGUAGE DeriveGeneric #-}
-- >
-- > import GHC.Generics (Generic)
-- > import Data.Hashable
-- >
-- > data Foo a = Foo a String
-- > deriving (Eq, Generic)
-- >
-- > instance Hashable a => Hashable (Foo a)
-- >
-- > data Colour = Red | Green | Blue
-- > deriving Generic
-- >
-- > instance Hashable Colour
--
-- If you omit a body for the instance declaration, GHC will generate
-- a default instance that correctly and efficiently hashes every
-- constructor and parameter.
-- $generic_err
--
-- Suppose you intend to use the generic machinery to automatically
-- generate a 'Hashable' instance.
--
-- > data Oops = Oops
-- > -- forgot to add "deriving Generic" here!
-- >
-- > instance Hashable Oops
--
-- And imagine that, as in the example above, you forget to add a
-- \"@deriving 'Generic'@\" clause to your data type. At compile time,
-- you will get an error message from GHC that begins roughly as
-- follows:
--
-- > No instance for (GHashable (Rep Oops))
--
-- This error can be confusing, as 'GHashable' is not exported (it is
-- an internal typeclass used by this library's generics machinery).
-- The correct fix is simply to add the missing \"@deriving
-- 'Generic'@\".
-- $blocks
--
-- To maintain high quality hashes, new 'Hashable' instances should be
-- built using existing 'Hashable' instances, combinators, and hash
-- functions.
--
-- The functions below can be used when creating new instances of
-- 'Hashable'. For example, for many string-like types the
-- 'hashWithSalt' method can be defined in terms of either
-- 'hashPtrWithSalt' or 'hashByteArrayWithSalt'. Here's how you could
-- implement an instance for the 'B.ByteString' data type, from the
-- @bytestring@ package:
--
-- > import qualified Data.ByteString as B
-- > import qualified Data.ByteString.Internal as B
-- > import qualified Data.ByteString.Unsafe as B
-- > import Data.Hashable
-- > import Foreign.Ptr (castPtr)
-- >
-- > instance Hashable B.ByteString where
-- > hashWithSalt salt bs = B.inlinePerformIO $
-- > B.unsafeUseAsCStringLen bs $ \(p, len) ->
-- > hashPtrWithSalt p (fromIntegral len) salt
-- $multiple-fields
--
-- Hash constructors with multiple fields by chaining 'hashWithSalt':
--
-- > data Date = Date Int Int Int
-- >
-- > instance Hashable Date where
-- > hashWithSalt s (Date yr mo dy) =
-- > s `hashWithSalt`
-- > yr `hashWithSalt`
-- > mo `hashWithSalt` dy
--
-- If you need to chain hashes together, use 'hashWithSalt' and follow
-- this recipe:
--
-- > combineTwo h1 h2 = h1 `hashWithSalt` h2
-- $multiple-ctors
--
-- For a type with several value constructors, there are a few
-- possible approaches to writing a 'Hashable' instance.
--
-- If the type is an instance of 'Enum', the easiest path is to
-- convert it to an 'Int', and use the existing 'Hashable' instance
-- for 'Int'.
--
-- > data Color = Red | Green | Blue
-- > deriving Enum
-- >
-- > instance Hashable Color where
-- > hashWithSalt = hashUsing fromEnum
--
-- If the type's constructors accept parameters, it is important to
-- distinguish the constructors. To distinguish the constructors, add
-- a different integer to the hash computation of each constructor:
--
-- > data Time = Days Int
-- > | Weeks Int
-- > | Months Int
-- >
-- > instance Hashable Time where
-- > hashWithSalt s (Days n) = s `hashWithSalt`
-- > (0::Int) `hashWithSalt` n
-- > hashWithSalt s (Weeks n) = s `hashWithSalt`
-- > (1::Int) `hashWithSalt` n
-- > hashWithSalt s (Months n) = s `hashWithSalt`
-- > (2::Int) `hashWithSalt` n
| ekmett/hashable | Data/Hashable.hs | bsd-3-clause | 6,626 | 0 | 5 | 1,508 | 222 | 207 | 15 | 8 | 0 |
module WithCli.Normalize (
normalize,
matches,
) where
import Data.Char
matches :: String -> String -> Bool
matches a b =
normalize a == normalize b
normalize :: String -> String
normalize s =
if all (not . isAllowedChar) s
then s
else
slugify $
dropWhile (== '-') $
filter isAllowedChar $
map (\ c -> if c == '_' then '-' else c) $
s
where
slugify (a : r)
| isUpper a = slugify (toLower a : r)
slugify (a : b : r)
| isUpper b = a : '-' : slugify (toLower b : r)
| otherwise = a : slugify (b : r)
slugify x = x
isAllowedChar :: Char -> Bool
isAllowedChar c = (isAscii c && isAlphaNum c) || (c `elem` "-_")
| kosmikus/getopt-generics | src/WithCli/Normalize.hs | bsd-3-clause | 700 | 0 | 12 | 222 | 301 | 154 | 147 | 24 | 5 |
{-# LANGUAGE Unsafe #-}
{-# LANGUAGE NoImplicitPrelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : System.IO.Unsafe
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- \"Unsafe\" IO operations.
--
-----------------------------------------------------------------------------
module System.IO.Unsafe (
-- * Unsafe 'System.IO.IO' operations
unsafePerformIO,
unsafeDupablePerformIO,
unsafeInterleaveIO,
unsafeFixIO,
) where
import GHC.Base
import GHC.IO
import GHC.IORef
import GHC.Exception
import Control.Exception
-- | A slightly faster version of `System.IO.fixIO` that may not be
-- safe to use with multiple threads. The unsafety arises when used
-- like this:
--
-- > unsafeFixIO $ \r -> do
-- > forkIO (print r)
-- > return (...)
--
-- In this case, the child thread will receive a @NonTermination@
-- exception instead of waiting for the value of @r@ to be computed.
--
-- @since 4.5.0.0
unsafeFixIO :: (a -> IO a) -> IO a
unsafeFixIO k = do
ref <- newIORef (throw NonTermination)
ans <- unsafeDupableInterleaveIO (readIORef ref)
result <- k ans
writeIORef ref result
return result
| alexander-at-github/eta | libraries/base/System/IO/Unsafe.hs | bsd-3-clause | 1,363 | 0 | 10 | 242 | 161 | 96 | 65 | 19 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-- | Notebook demo (include Spinner animation).
-- Author : Andy Stewart
-- Copyright : (c) 2010 Andy Stewart <lazycat.manatee@gmail.com>
module Main where
import Control.Monad
import Control.Monad.IO.Class
import Data.Maybe
import Data.Text (Text)
import Data.Monoid ((<>))
import Graphics.UI.Gtk
import qualified Data.Text as T (unpack)
data NotebookTab =
NotebookTab {ntBox :: HBox
,ntSpinner :: Spinner
,ntLabel :: Label
,ntCloseButton :: ToolButton
,ntSize :: Int}
-- | Main
main :: IO ()
main = do
-- Init.
initGUI
-- Create window and notebook.
window <- windowNew
notebook <- notebookNew
-- Set window.
windowSetDefaultSize window 800 600
windowSetPosition window WinPosCenter
set window [windowTitle := ("Press Ctrl + n to create new tab."::Text)]
-- Handle key press action.
window `on` keyPressEvent $ tryEvent $ do
-- Create new tab when user press Ctrl+n
[Control] <- eventModifier
"n" <- eventKeyName
liftIO $ do
-- Create text view.
textView <- textViewNew
widgetShowAll textView -- must show before add notebook,
-- otherwise notebook won't display child widget
-- even have add in notebook.
-- Create notebook tab.
tab <- notebookTabNew (Just "Cool tab") Nothing
menuLabel <- labelNew (Nothing :: Maybe Text)
-- Add widgets in notebook.
notebookAppendPageMenu notebook textView (ntBox tab) menuLabel
-- Start spinner animation when create tab.
notebookTabStart tab
-- Stop spinner animation after finish load.
timeoutAdd (notebookTabStop tab >> return False) 5000
-- Close tab when click button.
ntCloseButton tab `onToolButtonClicked` do
index <- notebookPageNum notebook textView
index ?>= \i -> notebookRemovePage notebook i
return ()
-- Show window.
window `containerAdd` notebook
widgetShowAll window
on window objectDestroy mainQuit
mainGUI
-- | Create notebook tab.
notebookTabNew :: Maybe Text -> Maybe Int -> IO NotebookTab
notebookTabNew name size = do
-- Init.
let iconSize = fromMaybe 12 size
box <- hBoxNew False 0
spinner <- spinnerNew
label <- labelNew name
image <- imageNewFromIcon "window-close" iconSize
closeButton <- toolButtonNew (Just image) (Nothing::Maybe Text)
-- Show.
boxPackStart box label PackNatural 0
boxPackStart box closeButton PackNatural 0
widgetShowAll box
return $ NotebookTab box spinner label closeButton iconSize
-- | Set tab name.
notebookTabSetName :: NotebookTab -> Text -> IO ()
notebookTabSetName tab =
labelSetText (ntLabel tab)
-- | Start spinner animation.
notebookTabStart :: NotebookTab -> IO ()
notebookTabStart NotebookTab {ntBox = box
,ntSpinner = spinner
,ntSize = size} = do
boxTryPack box spinner PackNatural (Just 0) (size `div` 2)
spinnerStart spinner
widgetShow spinner
-- | Stop spinner animation.
notebookTabStop :: NotebookTab -> IO ()
notebookTabStop NotebookTab {ntBox = box
,ntSpinner = spinner} = do
containerTryRemove box spinner
spinnerStop spinner
-- | Create image widget with given icon name and size.
imageNewFromIcon :: Text -> Int -> IO Image
imageNewFromIcon iconName size = do
iconTheme <- iconThemeGetDefault
pixbuf <- do
-- Function 'iconThemeLoadIcon' can scale icon with specified size.
pixbuf <- iconThemeLoadIcon iconTheme iconName size IconLookupUseBuiltin
case pixbuf of
Just p -> return p
Nothing -> error $ "imageNewFromIcon : search icon " <> T.unpack iconName <> " failed."
imageNewFromPixbuf pixbuf
-- | Try to packing widget in box.
-- If @child@ have exist parent, do nothing,
-- otherwise, add @child@ to @parent@.
boxTryPack :: (BoxClass parent, WidgetClass child) => parent -> child -> Packing -> Maybe Int -> Int -> IO ()
boxTryPack box widget packing order space = do
parent <- widgetGetParent widget
when (isNothing parent) $ do
boxPackStart box widget packing space
order ?>= boxReorderChild box widget
-- | Try to remove child from parent.
containerTryRemove :: (ContainerClass parent, WidgetClass child) => parent -> child -> IO ()
containerTryRemove parent widget = do
hasParent <- widgetGetParent widget
unless (isNothing hasParent) $ containerRemove parent widget
-- | Maybe.
(?>=) :: Monad m => Maybe a -> (a -> m ()) -> m ()
m ?>= f = maybe (return ()) f m
| k0001/gtk2hs | gtk/demo/notebook/Notebook.hs | gpl-3.0 | 4,697 | 0 | 18 | 1,200 | 1,110 | 551 | 559 | 90 | 2 |
module MonadIn2 where
f (a, b, c)
= do let (z, y) = (a, b)
case (z, y) of
(l, m) -> return (l, m)
f_1 (a, b, c)
= do let (z, y) = (a, b)
case (z, y) of
(l, m) -> return 0
| kmate/HaRe | old/testing/simplifyExpr/MonadIn2AST.hs | bsd-3-clause | 238 | 0 | 11 | 113 | 144 | 81 | 63 | 9 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-----------------------------------------------------------------------------
--
-- Module : IDE.NotebookFlipper
-- Copyright : 2007-2011 Juergen Nicklisch-Franken, Hamish Mackenzie
-- License : GPL
--
-- Maintainer : <maintainer@leksah.org>
-- Stability : provisional
-- Portability :
--
-- |
--
-----------------------------------------------------------------------------
module IDE.NotebookFlipper (
flipDown
, flipUp
) where
import Graphics.UI.Gtk
(treeSelectionGetSelectedRows,
treeSelectionSelectionChanged, treeViewGetSelection, rowActivated,
treeViewSetCursor, treeViewGetCursor, treeModelIterNChildren,
treeViewGetModel, treeViewRowActivated, treeViewGetColumn,
widgetShowAll, windowWindowPosition, widgetDestroy, widgetHide,
listStoreGetValue, keyReleaseEvent,
treeViewHeadersVisible, cellText, cellLayoutSetAttributes,
treeViewColumnPackStart, cellRendererTextNew, treeViewAppendColumn,
treeViewColumnNew, treeViewSetModel, listStoreNew, treeViewNew,
containerAdd, windowResizable, windowTransientFor,
windowNewPopup, TreeViewClass, WindowPosition(..),
signalDisconnect, AttrOp(..), set, EventM, EKey, eventKeyName,
windowGetSize, windowTypeHint, WindowTypeHint(..), windowDecorated,
windowDefaultWidth, windowDefaultHeight, scrolledWindowNew)
import IDE.Core.State hiding (window, name)
import Control.Monad (when)
import IDE.Pane.SourceBuffer(recentSourceBuffers)
import Control.Monad.IO.Class (MonadIO(..))
import System.Glib.Signals (on)
import qualified Control.Monad.Reader as Gtk (liftIO)
flipDown :: IDEAction
flipDown = do
currentState' <- readIDE currentState
case currentState' of
IsFlipping tv -> moveFlipperDown tv
IsRunning -> initFlipper True
_ -> return ()
flipUp :: IDEAction
flipUp = do
currentState' <- readIDE currentState
case currentState' of
IsFlipping tv -> moveFlipperUp tv
IsRunning -> initFlipper False
_ -> return ()
-- | Moves down in the Flipper state
moveFlipperDown :: TreeViewClass alpha => alpha -> IDEAction
moveFlipperDown tree = liftIO $ do
mbStore <- treeViewGetModel tree
case mbStore of
Nothing -> throwIDE "NotebookFlipper>>setFlipper: no store"
Just store -> do
n <- treeModelIterNChildren store Nothing
when (n /= 0) $ do
(cl, _) <- treeViewGetCursor tree
case cl of
(current:_) -> let next = if current == n - 1
then 0
else current + 1
in treeViewSetCursor tree [min (n-1) next] Nothing
[] -> treeViewSetCursor tree [1] Nothing
-- | Moves up in the Flipper state
moveFlipperUp :: TreeViewClass alpha => alpha -> IDEAction
moveFlipperUp tree = liftIO $ do
mbStore <- treeViewGetModel tree
case mbStore of
Nothing -> throwIDE "NotebookFlipper>>setFlipper: no store"
Just store -> do
n <- treeModelIterNChildren store Nothing
when (n /= 0) $ do
(cl, _) <- treeViewGetCursor tree
case cl of
(current:_) -> let next = if current == 0
then n - 1
else current - 1
in treeViewSetCursor tree [min (n-1) next] Nothing
[] -> treeViewSetCursor tree [n-1] Nothing
-- | Initiate Filpper , If True moves down, if false up
initFlipper :: Bool -> IDEAction
initFlipper direction = do
mainWindow <- getMainWindow
recentPanes' <- recentSourceBuffers
(tree', store') <- reifyIDE $ \ideR -> do
window <- windowNewPopup
(_, height) <- windowGetSize mainWindow
set window [
windowTypeHint := WindowTypeHintUtility,
windowDecorated := False,
windowResizable := True,
windowDefaultWidth := 200,
windowDefaultHeight := height,
windowTransientFor := mainWindow]
scrolledWindow <- scrolledWindowNew Nothing Nothing
containerAdd window scrolledWindow
tree <- treeViewNew
containerAdd scrolledWindow tree
store <- listStoreNew recentPanes'
treeViewSetModel tree store
column <- treeViewColumnNew
_ <- treeViewAppendColumn tree column
renderer <- cellRendererTextNew
treeViewColumnPackStart column renderer True
cellLayoutSetAttributes column renderer store
(\str -> [ cellText := str])
set tree [treeViewHeadersVisible := False]
cid <- mainWindow `on` keyReleaseEvent $ handleKeyRelease tree ideR
_ <- tree `on` rowActivated $ \treePath _column -> do
signalDisconnect cid
let [row] = treePath
string <- listStoreGetValue store row
reflectIDE (do
mbPane <- mbPaneFromName string
case mbPane of
Just (PaneC pane) -> do
makeActive pane
modifyIDE_ $ \ide -> ide{
recentPanes = paneName pane : filter (/= paneName pane) (recentPanes ide)}
Nothing -> return ()) ideR
widgetHide window
widgetDestroy window
reflectIDE (modifyIDE_ (\ide -> ide{currentState = IsRunning})) ideR
treeSelection <- treeViewGetSelection tree
_ <- treeSelection `on` treeSelectionSelectionChanged $ do
rows <- treeSelectionGetSelectedRows treeSelection
case rows of
[[row]] -> do
string <- listStoreGetValue store row
reflectIDE (do
mbPane <- mbPaneFromName string
case mbPane of
Just (PaneC pane) -> makeActive pane
Nothing -> return ()) ideR
_ -> return ()
set window [windowWindowPosition := WinPosCenterOnParent]
widgetShowAll window
return (tree, store)
modifyIDE_ (\ide -> ide{currentState = IsFlipping tree'})
liftIO $ do
-- This is done after currentState is set so we know not to update the
-- previous panes list
n <- treeModelIterNChildren store' Nothing
treeViewSetCursor tree' [if direction then min 1 (n - 1) else n - 1] Nothing
return ()
handleKeyRelease :: TreeViewClass alpha => alpha -> IDERef -> EventM EKey Bool
handleKeyRelease tree ideR = do
name <- eventKeyName
Gtk.liftIO $ case name of
ctrl | (ctrl == "Control_L") || (ctrl == "Control_R") -> do
currentState' <- reflectIDE (readIDE currentState) ideR
case currentState' of
IsFlipping _tv -> do
(treePath, _) <- treeViewGetCursor tree
Just column <- treeViewGetColumn tree 0
treeViewRowActivated tree treePath column
return False
_ -> return False
_ -> return False
| 573/leksah | src/IDE/NotebookFlipper.hs | gpl-2.0 | 7,399 | 0 | 33 | 2,451 | 1,708 | 863 | 845 | 146 | 5 |
{-# LANGUAGE ConstraintKinds, RankNTypes #-}
module Data.Cache
( Cache, Key
, new, peek, touch, lookup
, FuncId
, memo, memoS, unmemoS
, lookupS
-- For lower-level memoization
, KeyBS, bsOfKey
) where
import Control.Applicative ((<$>))
import Control.Lens.Operators
import Control.Monad.Trans.State (StateT(..), evalStateT, state, execState)
import Control.MonadA (MonadA)
import Data.Binary (Binary)
import Data.Binary.Utils (encodeS)
import Data.Cache.Types
import Data.Map (Map)
import Data.Maybe (fromMaybe)
import Data.Maybe.Utils (unsafeUnjust)
import Data.Typeable (Typeable, TypeRep, typeOf, cast)
import Prelude hiding (lookup)
import qualified Control.Lens as Lens
import qualified Crypto.Hash.SHA1 as SHA1
import qualified Data.ByteString as SBS
import qualified Data.Map as Map
new :: Int -> Cache
new maxSize =
Cache
{ _cEntries = Map.empty
, _cPriorities = Map.empty
, _cCounter = 0
, _cSize = 0
, cMaxSize = maxSize
}
bsOfKey :: (Binary k, Typeable k) => k -> KeyBS
bsOfKey key = SHA1.hash $ encodeS (show (typeOf key), key)
castUnmaybe :: (Typeable a, Typeable b) => String -> a -> b
castUnmaybe suffix x =
result
where
msg =
concat
[ "cast of ", show (typeOf x), " to ", show (typeOf result)
, " attempted in (", suffix, ")"
]
result = unsafeUnjust msg $ cast x
cacheValMap :: Typeable k => k -> Lens.Traversal' Cache ValMap
cacheValMap key = cEntries . Lens.ix (typeOf key)
lookupKey :: (Typeable k, Typeable v) => k -> Cache -> Maybe (ValEntry v)
lookupKey key cache =
findKey =<< cache ^? cacheValMap key
where
findKey (ValMap m) =
Map.lookup (castUnmaybe "lookupKey:key" key) m
<&> (veValue %~ \(AnyVal val) -> castUnmaybe "lookupKey:val" val)
-- TODO: Convert to Lens.at so you can poke too
peek :: (Key k, Typeable v) => k -> Cache -> Maybe v
peek key cache = (^. veValue) <$> lookupKey key cache
insertNew :: Ord k => String -> k -> v -> Map k v -> Map k v
insertNew msg k v =
Map.alter f k
where
f Nothing = Just v
f (Just _) = error $ "insertNew found old key: " ++ show msg
addKey ::
(Key k, Typeable v) => k -> ValEntry v ->
Map TypeRep ValMap -> Map TypeRep ValMap
addKey key entry =
Map.alter f $ typeOf key
where
anyValEntry = entry & veValue %~ AnyVal
f Nothing = Just . ValMap $ Map.singleton key anyValEntry
f (Just (ValMap valMap)) =
Just . ValMap $
insertNew "addKey" (castUnmaybe "addKey:key" key) anyValEntry valMap
lookupHelper :: Key k => r -> (Cache -> AnyVal -> r) -> k -> Cache -> r
lookupHelper onMiss onHit key cache =
fromMaybe onMiss $ findKey =<< cache ^? cacheValMap key
where
findKey (ValMap m) =
case Map.lookup ckey m of
Nothing -> Nothing
Just (ValEntry prevPriority val) ->
Just $ onHit newCache val
where
newCache =
cache
& cEntries %~ Map.insert (typeOf key) (ValMap $ Map.insert ckey (ValEntry newPriority val) m)
& cPriorities %~
Map.insert newPriority (AnyKey key) .
Map.delete prevPriority
& cCounter +~ 1
newPriority =
prevPriority { pRecentUse = cache ^. cCounter }
where
ckey = castUnmaybe "lookupHelper:key" key
touch :: Key k => k -> Cache -> Cache
touch key cache = lookupHelper cache const key cache
lookup :: (Key k, Typeable v) => k -> Cache -> (Maybe v, Cache)
lookup key cache =
lookupHelper (Nothing, cache) onHit key cache
where
onHit newCache (AnyVal val) = (Just (castUnmaybe "lookup:val" val), newCache)
lookupS :: MonadA m => (Key k, Typeable v) => k -> StateT Cache m (Maybe v)
lookupS = state . lookup
evictLowestScore :: Cache -> Cache
evictLowestScore =
execState $
clearEntry =<<
Lens.zoom cPriorities (state Map.deleteFindMin)
where
clearEntry (priorityData, AnyKey key) = do
cSize -= pMemoryConsumption priorityData
cEntries %= Map.alter deleteKey (typeOf key)
where
deleteKey Nothing = error "Key pointed by cPriorities not found in Cache?!"
deleteKey (Just (ValMap m)) =
case Map.delete (castUnmaybe "lookupHelper:key" key) m of
res
| Map.null res -> Nothing
| otherwise -> Just $ ValMap res
evict :: Cache -> Cache
evict cache
| cache ^. cSize <= cMaxSize cache = cache
| otherwise = evict $ evictLowestScore cache
-- Assumes key was not in the cache before.
insertHelper :: (Key k, Typeable v, Binary v) => k -> v -> Cache -> Cache
insertHelper key val cache =
evict .
(cSize +~ valLen) .
(cEntries %~ addKey key entry) .
(cPriorities %~ insertNew "insertHelper" priority (AnyKey key)) .
(cCounter +~ 1) $
cache
where
entry = ValEntry priority val
valLen = SBS.length $ encodeS val
priority = PriorityData (cache ^. cCounter) valLen
type FuncId = String
-- Actually requires only Pointed Functor.
memo ::
(Key k, Binary v, Typeable v, MonadA m) =>
FuncId -> (k -> m v) -> k -> Cache -> m (v, Cache)
memo funcId f rawKey cache =
lookupHelper onMiss onHit key cache
where
key = (funcId, rawKey)
onMiss = do
val <- f rawKey
return (val, insertHelper key val cache)
onHit newCache (AnyVal val) = return (castUnmaybe (funcId ++ ":memo:val") val, newCache)
memoS ::
(Key k, Binary v, Typeable v, MonadA m) =>
FuncId -> (k -> m v) -> k -> StateT Cache m v
memoS funcId f key = StateT $ memo funcId f key
unmemoS :: MonadA m => StateT Cache m a -> m a
unmemoS = (`evalStateT` new 0)
| sinelaw/lamdu | bottlelib/Data/Cache.hs | gpl-3.0 | 5,541 | 0 | 23 | 1,347 | 2,018 | 1,053 | 965 | -1 | -1 |
module DemoSpec where
import Test.Hspec
spec :: Spec
spec =
describe "demo" $
specify "trivial" $
() `shouldBe` ()
| Javran/misc | yesod-min/test/DemoSpec.hs | mit | 130 | 0 | 8 | 34 | 43 | 24 | 19 | 7 | 1 |
{-# OPTIONS -XOverloadedStrings #-}
import Network.AMQP
import qualified Data.ByteString.Lazy.Char8 as BL
main :: IO ()
main = do
conn <- openConnection "127.0.0.1" "/" "guest" "guest"
ch <- openChannel conn
declareQueue ch newQueue {queueName = "hello",
queueAutoDelete = False,
queueDurable = False}
publishMsg ch "" "hello"
(newMsg {msgBody = (BL.pack "Hello World!"),
msgDeliveryMode = Just NonPersistent})
putStrLn " [x] Sent 'Hello World!'"
closeConnection conn
| yepesasecas/rabbitmq-tutorials | haskell/send.hs | apache-2.0 | 625 | 1 | 13 | 220 | 141 | 72 | 69 | 15 | 1 |
-- !!! test RealFrac ops (ceiling/floor/etc.) on Floats/Doubles
--
main =
putStr $
unlines
[ -- just for fun, we show the floats to
-- exercise the code responsible.
'A' : show (float_list :: [Float])
, 'B' : show (double_list :: [Double])
-- {Float,Double} inputs, {Int,Integer} outputs
, 'C' : show ((map ceiling small_float_list) :: [Int])
, 'D' : show ((map ceiling float_list) :: [Integer])
, 'E' : show ((map ceiling small_double_list) :: [Int])
, 'F' : show ((map ceiling double_list) :: [Integer])
, 'G' : show ((map floor small_float_list) :: [Int])
, 'H' : show ((map floor float_list) :: [Integer])
, 'I' : show ((map floor small_double_list) :: [Int])
, 'J' : show ((map floor double_list) :: [Integer])
, 'K' : show ((map truncate small_float_list) :: [Int])
, 'L' : show ((map truncate float_list) :: [Integer])
, 'M' : show ((map truncate small_double_list) :: [Int])
, 'N' : show ((map truncate double_list) :: [Integer])
, 'n' : show ((map round small_float_list) :: [Int])
, 'O' : show ((map round float_list) :: [Integer])
, 'P' : show ((map round small_double_list) :: [Int])
, 'Q' : show ((map round double_list) :: [Integer])
, 'R' : show ((map properFraction small_float_list) :: [(Int,Float)])
, 'S' : show ((map properFraction float_list) :: [(Integer,Float)])
, 'T' : show ((map properFraction small_double_list) :: [(Int,Double)])
, 'U' : show ((map properFraction double_list) :: [(Integer,Double)])
]
where
-- these fit into an Int when truncated. Truncation when the
-- result does not fit into the target is undefined - not explicitly
-- so in Haskell 98, but that's the interpretation we've taken in GHC.
-- See bug #1254
small_float_list :: [Float]
small_float_list = [
0.0, -0.0, 1.1, 2.8, 3.5, 4.5, -1.0000000001, -2.9999995,
-3.50000000001, -4.49999999999, 1000012.0, 123.456, 100.25,
102.5, 0.0012, -0.00000012, 1.7e4, -1.7e-4, 0.15e-6, pi
]
float_list :: [Float]
float_list = small_float_list ++ [
1.18088e+11, 1.2111e+14
]
-- these fit into an Int
small_double_list :: [Double]
small_double_list = [
0.0, -0.0, 1.1, 2.8, 3.5, 4.5, -1.0000000001, -2.9999995,
-3.50000000001, -4.49999999999, 1000012.0, 123.456, 100.25,
102.5, 0.0012, -0.00000012, 1.7e4, -1.7e-4, 0.15e-6, pi
]
double_list :: [Double]
double_list = small_double_list ++ [
1.18088e+11, 1.2111e+14
]
| siddhanathan/ghc | testsuite/tests/numeric/should_run/arith005.hs | bsd-3-clause | 2,533 | 23 | 10 | 583 | 872 | 503 | 369 | 42 | 1 |
-- | Test for GHC 7.10+'s @BinaryLiterals@ extensions (see GHC #9224)
{-# LANGUAGE BinaryLiterals #-}
{-# LANGUAGE MagicHash #-}
module Main where
import GHC.Types
main = do
print [ I# 0b0#, I# -0b0#, I# 0b1#, I# -0b1#
, I# 0b00000000000000000000000000000000000000000000000000000000000000000000000000001#
, I# -0b00000000000000000000000000000000000000000000000000000000000000000000000000001#
, I# -0b11001001#, I# -0b11001001#
, I# -0b11111111#, I# -0b11111111#
]
print [ W# 0b0##, W# 0b1##, W# 0b11001001##, W# 0b11##, W# 0b11111111##
, W# 0b00000000000000000000000000000000000000000000000000000000000000000000000000001##
]
print [ 0b0, 0b1, 0b10, 0b11, 0b100, 0b101, 0b110, 0b111 :: Integer
, -0b0, -0b1, -0b10, -0b11, -0b100, -0b101, -0b110, -0b111
, 0b11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
, -0b11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
]
| urbanslug/ghc | testsuite/tests/parser/should_run/BinaryLiterals1.hs | bsd-3-clause | 1,148 | 0 | 9 | 223 | 213 | 120 | 93 | 16 | 1 |
{-# LANGUAGE Trustworthy #-}
module Main where
import Prelude
import safe M_SafePkg6
main = putStrLn "test"
| urbanslug/ghc | testsuite/tests/safeHaskell/check/pkg01/ImpSafeOnly07.hs | bsd-3-clause | 111 | 1 | 5 | 19 | 20 | 13 | 7 | 5 | 1 |
module Test where
data Fun = MkFun (Fun -> Fun)
data LList a = Nill | Conss a (LList a)
g :: Fun -> Fun
g f = f
| siddhanathan/ghc | testsuite/tests/stranal/should_compile/fun.hs | bsd-3-clause | 113 | 0 | 8 | 30 | 58 | 33 | 25 | 5 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module ModelTests
( vertexFileParts
, normalFileParts
, texCoordFileParts
, vertexOnlyFaceFileParts
, vertexNormalFaceFileParts
, completeFaceFileParts
, completeModel
, splittedFileParts
, assembleVertP
, assembleVertPN
, assembleVertPNTx
) where
import Test.HUnit
import qualified BigE.Attribute.Vert_P as Vert_P
import qualified BigE.Attribute.Vert_P_N as Vert_P_N
import qualified BigE.Attribute.Vert_P_N_Tx as Vert_P_N_Tx
import qualified BigE.Model.Assembler as Assembler
import BigE.Model.Parser (FilePart (..), Point (..), parser,
splitParts)
import Data.ByteString.Lazy.Char8 (ByteString)
import qualified Data.ByteString.Lazy.Char8 as LBS
import Linear (V2 (..), V3 (..))
import Text.Megaparsec (runParser)
-- | Test parsing of vertex 'FilePart's only.
vertexFileParts :: Assertion
vertexFileParts = do
let parts1 = runParser parser "test" "v 1.1 2.2 3.3"
parts2 = runParser parser "test" "v 1.1 2.2 3.3\nv 4.4 5.5 6.6"
Right [ Vertex $ V3 1.1 2.2 3.3 ] @=? parts1
Right [ Vertex $ V3 1.1 2.2 3.3
, Vertex $ V3 4.4 5.5 6.6 ] @=? parts2
-- | Test parsing of vertex 'FilePart's only.
normalFileParts :: Assertion
normalFileParts = do
let parts1 = runParser parser "test" "vn 1.1 2.2 3.3"
parts2 = runParser parser "test" "vn 1.1 2.2 3.3\nvn 4.4 5.5 6.6"
Right [ Normal $ V3 1.1 2.2 3.3 ] @=? parts1
Right [ Normal $ V3 1.1 2.2 3.3
, Normal $ V3 4.4 5.5 6.6 ] @=? parts2
-- | Test parsing of texture coordinates 'FilePart's only.
texCoordFileParts :: Assertion
texCoordFileParts = do
let parts1 = runParser parser "test" "vt 1.1 2.2"
parts2 = runParser parser "test" "vt 1.1 2.2\nvt 4.4 5.5"
Right [ TexCoord $ V2 1.1 2.2 ] @=? parts1
Right [ TexCoord $ V2 1.1 2.2
, TexCoord $ V2 4.4 5.5 ] @=? parts2
-- | Test parsing of face coordinates for vertex only triangle faces.
vertexOnlyFaceFileParts :: Assertion
vertexOnlyFaceFileParts = do
let parts1 = runParser parser "test" "f 1// 2// 3//"
parts2 = runParser parser "test" "f 1// 2// 3//\nf 4// 5// 6//"
Right [ Triangle (Point 1 Nothing Nothing)
(Point 2 Nothing Nothing)
(Point 3 Nothing Nothing)
] @=? parts1
Right [ Triangle (Point 1 Nothing Nothing)
(Point 2 Nothing Nothing)
(Point 3 Nothing Nothing)
, Triangle (Point 4 Nothing Nothing)
(Point 5 Nothing Nothing)
(Point 6 Nothing Nothing)
] @=? parts2
-- | Test parsing of face coordinates for vertex//normal triangle faces.
vertexNormalFaceFileParts :: Assertion
vertexNormalFaceFileParts = do
let parts1 = runParser parser "test" "f 1//1 2//2 3//3"
parts2 = runParser parser "test" "f 1//1 2//2 3//3\nf 4//4 5//5 6//6"
Right [ Triangle (Point 1 Nothing (Just 1))
(Point 2 Nothing (Just 2))
(Point 3 Nothing (Just 3))
] @=? parts1
Right [ Triangle (Point 1 Nothing (Just 1))
(Point 2 Nothing (Just 2))
(Point 3 Nothing (Just 3))
, Triangle (Point 4 Nothing (Just 4))
(Point 5 Nothing (Just 5))
(Point 6 Nothing (Just 6))
] @=? parts2
-- | Test parsing of face coordinates for vertex/tex/normal triangle faces.
completeFaceFileParts :: Assertion
completeFaceFileParts = do
let parts1 = runParser parser "test" "f 1/2/3 2/3/4 3/4/5"
parts2 = runParser parser "test" "f 1/2/3 2/3/4 3/4/5\nf 4/5/6 5/6/7 6/7/8"
Right [ Triangle (Point 1 (Just 2) (Just 3))
(Point 2 (Just 3) (Just 4))
(Point 3 (Just 4) (Just 5))
] @=? parts1
Right [ Triangle (Point 1 (Just 2) (Just 3))
(Point 2 (Just 3) (Just 4))
(Point 3 (Just 4) (Just 5))
, Triangle (Point 4 (Just 5) (Just 6))
(Point 5 (Just 6) (Just 7))
(Point 6 (Just 7) (Just 8))
] @=? parts2
-- | Split the list of file parts into a tuple of components.
splittedFileParts :: Assertion
splittedFileParts = do
let (verts, normals, texCoords, triangles) = splitParts modelParts
[ Vertex $ V3 1 1 1, Vertex $ V3 (-1) 0 (-1) ] @=? verts
[ Normal $ V3 1 0 0, Normal $ V3 0.7 0.7 0 ] @=? normals
[ TexCoord $ V2 0 1, TexCoord $ V2 1 0 ] @=? texCoords
[ Triangle (Point 1 (Just 2) (Just 3)) (Point 2 (Just 3) (Just 4)) (Point 3 (Just 4) (Just 5))
, Triangle (Point 4 (Just 5) (Just 6)) (Point 5 (Just 6) (Just 7)) (Point 6 (Just 7) (Just 8))] @=? triangles
-- | Test parsing of a complete model.
completeModel :: Assertion
completeModel =
Right modelParts @=? runParser parser "test" model
-- | Test assembly of a simple model to vert_Ps.
assembleVertP :: Assertion
assembleVertP =
Just ([ Vert_P.Vertex { Vert_P.position = V3 1 1 0 }
, Vert_P.Vertex { Vert_P.position = V3 (-1) 1 0 }
, Vert_P.Vertex { Vert_P.position = V3 (-1) (-1) 0 }
, Vert_P.Vertex { Vert_P.position = V3 1 (-1) 0 }
], [0, 1, 2, 0, 2, 3])
@=? Assembler.assembleVertP squareParts
-- | Test assembly of a simple model to vert_P_Ns.
assembleVertPN :: Assertion
assembleVertPN =
Just ([ Vert_P_N.Vertex { Vert_P_N.position = V3 1 1 0
, Vert_P_N.normal = V3 0 0 1
}
, Vert_P_N.Vertex { Vert_P_N.position = V3 (-1) 1 0
, Vert_P_N.normal = V3 0 0 1
}
, Vert_P_N.Vertex { Vert_P_N.position = V3 (-1) (-1) 0
, Vert_P_N.normal = V3 0 0 1
}
, Vert_P_N.Vertex { Vert_P_N.position = V3 1 (-1) 0
, Vert_P_N.normal = V3 0 0 1
}
], [0, 1, 2, 0, 2, 3])
@=? Assembler.assembleVertPN squareParts
-- | Test assembly of a simple model to vert_P_N_Txs.
assembleVertPNTx :: Assertion
assembleVertPNTx =
Just ([ Vert_P_N_Tx.Vertex { Vert_P_N_Tx.position = V3 1 1 0
, Vert_P_N_Tx.normal = V3 0 0 1
, Vert_P_N_Tx.texCoord = V2 1 1
}
, Vert_P_N_Tx.Vertex { Vert_P_N_Tx.position = V3 (-1) 1 0
, Vert_P_N_Tx.normal = V3 0 0 1
, Vert_P_N_Tx.texCoord = V2 0 1
}
, Vert_P_N_Tx.Vertex { Vert_P_N_Tx.position = V3 (-1) (-1) 0
, Vert_P_N_Tx.normal = V3 0 0 1
, Vert_P_N_Tx.texCoord = V2 0 0
}
, Vert_P_N_Tx.Vertex { Vert_P_N_Tx.position = V3 1 (-1) 0
, Vert_P_N_Tx.normal = V3 0 0 1
, Vert_P_N_Tx.texCoord = V2 1 0
}
], [0, 1, 2, 0, 2, 3])
@=? Assembler.assembleVertPNTx squareParts
-- | Dummy model. Makes no sense geometerically.
model :: ByteString
model = LBS.pack $ unlines
[ "# Test model"
, "mtllib test.mtl"
, "# Vertices"
, "v 1.0 1.0 1.0"
, "v -1.0 0.0 -1.0"
, "# Texture coordinates"
, "vt 0.0 1.0"
, "vt 1.0 0.0"
, "# Normals"
, "vn 1.0 0.0 0.0"
, "vn 0.7 0.7 0.0"
, "usemtl test.png"
, "s off"
, "# Faces"
, "f 1/2/3 2/3/4 3/4/5"
, "f 4/5/6 5/6/7 6/7/8"
]
-- | The file parts that should be the result of the above model.
modelParts :: [FilePart]
modelParts =
[ Mtllib "test.mtl"
, Vertex $ V3 1 1 1
, Vertex $ V3 (-1) 0 (-1)
, TexCoord $ V2 0 1
, TexCoord $ V2 1 0
, Normal $ V3 1 0 0
, Normal $ V3 0.7 0.7 0
, Usemtl "test.png"
, Smooth "off"
, Triangle (Point 1 (Just 2) (Just 3))
(Point 2 (Just 3) (Just 4))
(Point 3 (Just 4) (Just 5))
, Triangle (Point 4 (Just 5) (Just 6))
(Point 5 (Just 6) (Just 7))
(Point 6 (Just 7) (Just 8))
]
-- | Simple model which shall result in a square.
squareParts :: [FilePart]
squareParts =
[ Vertex $ V3 1 1 0
, Vertex $ V3 (-1) 1 0
, Vertex $ V3 (-1) (-1) 0
, Vertex $ V3 1 (-1) 0
, Normal $ V3 0 0 1
, TexCoord $ V2 0 0
, TexCoord $ V2 1 0
, TexCoord $ V2 0 1
, TexCoord $ V2 1 1
, Triangle (Point 1 (Just 4) (Just 1))
(Point 2 (Just 3) (Just 1))
(Point 3 (Just 1) (Just 1))
, Triangle (Point 1 (Just 4) (Just 1))
(Point 3 (Just 1) (Just 1))
(Point 4 (Just 2) (Just 1))
]
| psandahl/big-engine | test/ModelTests.hs | mit | 8,876 | 0 | 14 | 3,114 | 2,770 | 1,463 | 1,307 | 189 | 1 |
{-# LANGUAGE RecursiveDo #-}
module Widgets where
import Reflex.Dom
import qualified GHCJS.DOM.HTMLInputElement as J
import qualified GHCJS.DOM.Element as J
import Control.Lens (view, (^.))
import Data.Monoid ((<>))
import Control.Monad (forM)
--------------- a link opening on a new tab ------
linkNewTab :: MonadWidget t m => String -> String -> m ()
linkNewTab href s = elAttr "a" ("href" =: href <> "target" =: "_blank") $ text s
------------------ radio checkboxes ----------------------
--
radiocheckW :: (MonadHold t m,MonadWidget t m) => Eq a => a -> [(String,a)] -> m (Event t a)
radiocheckW j xs = do
rec es <- forM xs $ \(s,x) -> divClass "icheck" $ do
let d = def & setValue .~ (fmap (== x) $ updated result)
e <- fmap (const x) <$> view checkbox_change <$> checkbox (x == j) d
text s
return e
result <- holdDyn j $ leftmost es
return $ updated result
---------------- input widgets -----------------------------------------------
insertAt :: Int -> String -> String -> (Int, String)
insertAt n e s = let (u,v) = splitAt n s
in (n + length e, u ++ e ++ v)
attachSelectionStart :: MonadWidget t m => TextInput t -> Event t a -> m (Event t (Int, a))
attachSelectionStart t ev = performEvent . ffor ev $ \e -> do
n <- J.getSelectionStart (t ^. textInput_element)
return (n,e)
setCaret :: MonadWidget t m => TextInput t -> Event t Int -> m ()
setCaret t e = performEvent_ . ffor e $ \n -> do
let el = t ^. textInput_element
J.setSelectionStart el n
J.setSelectionEnd el n
inputW :: MonadWidget t m => m (Event t String)
inputW = do
rec let send = ffilter (==13) $ view textInput_keypress input -- send signal firing on *return* key press
input <- textInput $ def & setValue .~ fmap (const "") send -- textInput with content reset on send
return $ tag (current $ view textInput_value input) send -- tag the send signal with the inputText value BEFORE resetting
selInputW
:: MonadWidget t m =>
Event t String -> Event t String -> Event t b -> m (Dynamic t String)
selInputW insertionE refreshE resetE = do
rec insertionLocE <- attachSelectionStart t insertionE
let newE = attachWith (\s (n,e) -> insertAt n e s) (current (value t)) insertionLocE
setCaret t (fmap fst newE)
t <- textInput $ def & setValue .~ leftmost [fmap snd newE, fmap (const "") resetE, refreshE]
return $ view textInput_value t
| paolino/LambdaCalculus | Widgets.hs | mit | 2,506 | 0 | 22 | 608 | 946 | 471 | 475 | -1 | -1 |
module Indexing where
import Types
import Control.Monad.State
import Control.Lens ((^.), (&), (+~), (-~))
import Data.List
indexing :: UnIndexedTerm -> IndexedTerm
indexing t = evalState (indexing' t) []
indexing' :: UnIndexedTerm -> State [Name] IndexedTerm
indexing' t = case t of
TmApp t1 t2 -> TmApp <$> indexing' t1 <*> indexing' t2
TmLambda nameStr t1 -> do
modify incrementIndex
modify (\xs -> Name nameStr 0 : xs)
TmLambda nameStr <$> indexing' t1
TmName nameStr -> do
nameMaybe <- findName nameStr
return $ case nameMaybe of
Nothing -> NoRuleApplies ("undefined value:" ++ nameStr)
Just n -> TmName . Name nameStr $ (n^.index)
TmZero -> return TmZero
TmTrue -> return TmTrue
TmFalse -> return TmFalse
TmIsZero -> return TmIsZero
TmPred -> return TmPred
TmSucc -> return TmSucc
TmIf -> return TmIf
NoRuleApplies str -> return $ NoRuleApplies str
incrementIndex :: [Name] -> [Name]
incrementIndex = map (\n -> n&index+~1)
decrementIndex :: [Name] -> [Name]
decrementIndex = map (\n -> n&index-~1)
type Key = String
findName :: Key -> State [Name] (Maybe Name)
findName key = find (\n -> (n^.name) == key) <$> get
betaReduction :: IndexedTerm -> IndexedTerm -> IndexedTerm
betaReduction = betaReduction' 0
betaReduction' :: Int -- index
-> IndexedTerm -- source
-> IndexedTerm -- source内のindexと一致したものをこの項で置換
-> IndexedTerm -- output
betaReduction' i t1 var = case t1 of
TmApp t11 t12 -> TmApp (betaReduction' i t11 var) (betaReduction' i t12 var)
TmLambda n t11 -> TmLambda n $ betaReduction' (i+1) t11 var
TmName n -> if i == n^.index then var else TmName n
TmZero -> TmZero
TmTrue -> TmTrue
TmFalse -> TmFalse
TmIsZero -> TmIsZero
TmPred -> TmPred
TmSucc -> TmSucc
TmIf -> TmIf
NoRuleApplies str -> NoRuleApplies str
| eliza0x/Mikan | src/Indexing.hs | mit | 2,271 | 0 | 16 | 792 | 683 | 347 | 336 | 52 | 12 |
module Rebase.Data.Vector.Mutable
(
module Data.Vector.Mutable
)
where
import Data.Vector.Mutable
| nikita-volkov/rebase | library/Rebase/Data/Vector/Mutable.hs | mit | 101 | 0 | 5 | 12 | 23 | 16 | 7 | 4 | 0 |
module Test where
import Prelude ()
import Zeno
data Nat = Zero | Succ Nat
length :: [a] -> Nat
length [] = Zero
length (x:xs) = Succ (length xs)
(++) :: [a] -> [a] -> [a]
[] ++ ys = ys
(x:xs) ++ ys = x : (xs ++ ys)
class Num a where
(+) :: a -> a -> a
instance Num Nat where
Zero + y = y
Succ x + y = Succ (x + y)
class Eq a where
(==) :: a -> a -> Bool
instance Eq Nat where
Zero == Zero = True
Succ x == Succ y = x == y
_ == _ = False
prop_eq_ref :: Nat -> Prop
prop_eq_ref x = proveBool (x == x)
prop_length :: [a] -> [a] -> Prop
prop_length xs ys
= prove (length (xs ++ ys) :=: length xs + length ys)
elem :: Eq a => a -> [a] -> Bool
elem _ [] = False
elem n (x:xs)
| n == x = True
| otherwise = elem n xs
prop_elem :: Nat -> [Nat] -> [Nat] -> Prop
prop_elem n xs ys
= givenBool (n `elem` ys)
$ proveBool (n `elem` (xs ++ ys))
| Gurmeet-Singh/Zeno | test/test.hs | mit | 868 | 0 | 11 | 239 | 511 | 265 | 246 | 35 | 1 |
module SpecHelper where
import Control.Monad (void)
import qualified System.IO.Error as E
import System.Environment (getEnv)
import qualified Data.ByteString.Base64 as B64 (encode, decodeLenient)
import Data.CaseInsensitive (CI(..))
import qualified Data.Set as S
import qualified Data.Map.Strict as M
import Data.List (lookup)
import Text.Regex.TDFA ((=~))
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy as BL
import System.Process (readProcess)
import Text.Heredoc
import PostgREST.Config (AppConfig(..))
import PostgREST.Types (JSPathExp(..))
import Test.Hspec
import Test.Hspec.Wai
import Network.HTTP.Types
import Network.Wai.Test (SResponse(simpleStatus, simpleHeaders, simpleBody))
import Data.Maybe (fromJust)
import Data.Aeson (decode, Value(..))
import qualified JSONSchema.Draft4 as D4
import Protolude
matchContentTypeJson :: MatchHeader
matchContentTypeJson = "Content-Type" <:> "application/json; charset=utf-8"
matchContentTypeSingular :: MatchHeader
matchContentTypeSingular = "Content-Type" <:> "application/vnd.pgrst.object+json; charset=utf-8"
validateOpenApiResponse :: [Header] -> WaiSession ()
validateOpenApiResponse headers = do
r <- request methodGet "/" headers ""
liftIO $
let respStatus = simpleStatus r in
respStatus `shouldSatisfy`
\s -> s == Status { statusCode = 200, statusMessage="OK" }
liftIO $
let respHeaders = simpleHeaders r in
respHeaders `shouldSatisfy`
\hs -> ("Content-Type", "application/openapi+json; charset=utf-8") `elem` hs
liftIO $
let respBody = simpleBody r
schema :: D4.Schema
schema = D4.emptySchema { D4._schemaRef = Just "openapi.json" }
schemaContext :: D4.SchemaWithURI D4.Schema
schemaContext = D4.SchemaWithURI
{ D4._swSchema = schema
, D4._swURI = Just "test/fixtures/openapi.json"
}
in
D4.fetchFilesystemAndValidate schemaContext ((fromJust . decode) respBody) `shouldReturn` Right ()
getEnvVarWithDefault :: Text -> Text -> IO Text
getEnvVarWithDefault var def = toS <$>
getEnv (toS var) `E.catchIOError` const (return $ toS def)
_baseCfg :: AppConfig
_baseCfg = -- Connection Settings
AppConfig mempty "postgrest_test_anonymous" Nothing "test" "localhost" 3000
-- Jwt settings
(Just $ encodeUtf8 "reallyreallyreallyreallyverysafe") False Nothing
-- Connection Modifiers
10 Nothing (Just "test.switch_role")
-- Debug Settings
True
[ ("app.settings.app_host", "localhost")
, ("app.settings.external_api_secret", "0123456789abcdef")
]
-- Default role claim key
(Right [JSPKey "role"])
-- Empty db-extra-search-path
[]
testCfg :: Text -> AppConfig
testCfg testDbConn = _baseCfg { configDatabase = testDbConn }
testCfgNoJWT :: Text -> AppConfig
testCfgNoJWT testDbConn = (testCfg testDbConn) { configJwtSecret = Nothing }
testUnicodeCfg :: Text -> AppConfig
testUnicodeCfg testDbConn = (testCfg testDbConn) { configSchema = "تست" }
testLtdRowsCfg :: Text -> AppConfig
testLtdRowsCfg testDbConn = (testCfg testDbConn) { configMaxRows = Just 2 }
testProxyCfg :: Text -> AppConfig
testProxyCfg testDbConn = (testCfg testDbConn) { configProxyUri = Just "https://postgrest.com/openapi.json" }
testCfgBinaryJWT :: Text -> AppConfig
testCfgBinaryJWT testDbConn = (testCfg testDbConn) {
configJwtSecret = Just . B64.decodeLenient $
"cmVhbGx5cmVhbGx5cmVhbGx5cmVhbGx5dmVyeXNhZmU="
}
testCfgAudienceJWT :: Text -> AppConfig
testCfgAudienceJWT testDbConn = (testCfg testDbConn) {
configJwtSecret = Just . B64.decodeLenient $
"cmVhbGx5cmVhbGx5cmVhbGx5cmVhbGx5dmVyeXNhZmU=",
configJwtAudience = Just "youraudience"
}
testCfgAsymJWK :: Text -> AppConfig
testCfgAsymJWK testDbConn = (testCfg testDbConn) {
configJwtSecret = Just $ encodeUtf8
[str|{"alg":"RS256","e":"AQAB","key_ops":["verify"],"kty":"RSA","n":"0etQ2Tg187jb04MWfpuogYGV75IFrQQBxQaGH75eq_FpbkyoLcEpRUEWSbECP2eeFya2yZ9vIO5ScD-lPmovePk4Aa4SzZ8jdjhmAbNykleRPCxMg0481kz6PQhnHRUv3nF5WP479CnObJKqTVdEagVL66oxnX9VhZG9IZA7k0Th5PfKQwrKGyUeTGczpOjaPqbxlunP73j9AfnAt4XCS8epa-n3WGz1j-wfpr_ys57Aq-zBCfqP67UYzNpeI1AoXsJhD9xSDOzvJgFRvc3vm2wjAW4LEMwi48rCplamOpZToIHEPIaPzpveYQwDnB1HFTR1ove9bpKJsHmi-e2uzQ","use":"sig"}|]
}
testCfgAsymJWKSet :: Text -> AppConfig
testCfgAsymJWKSet testDbConn = (testCfg testDbConn) {
configJwtSecret = Just $ encodeUtf8
[str|{"keys": [{"alg":"RS256","e":"AQAB","key_ops":["verify"],"kty":"RSA","n":"0etQ2Tg187jb04MWfpuogYGV75IFrQQBxQaGH75eq_FpbkyoLcEpRUEWSbECP2eeFya2yZ9vIO5ScD-lPmovePk4Aa4SzZ8jdjhmAbNykleRPCxMg0481kz6PQhnHRUv3nF5WP479CnObJKqTVdEagVL66oxnX9VhZG9IZA7k0Th5PfKQwrKGyUeTGczpOjaPqbxlunP73j9AfnAt4XCS8epa-n3WGz1j-wfpr_ys57Aq-zBCfqP67UYzNpeI1AoXsJhD9xSDOzvJgFRvc3vm2wjAW4LEMwi48rCplamOpZToIHEPIaPzpveYQwDnB1HFTR1ove9bpKJsHmi-e2uzQ","use":"sig"}]}|]
}
testNonexistentSchemaCfg :: Text -> AppConfig
testNonexistentSchemaCfg testDbConn = (testCfg testDbConn) { configSchema = "nonexistent" }
testCfgExtraSearchPath :: Text -> AppConfig
testCfgExtraSearchPath testDbConn = (testCfg testDbConn) { configExtraSearchPath = ["public", "extensions"] }
setupDb :: Text -> IO ()
setupDb dbConn = do
loadFixture dbConn "database"
loadFixture dbConn "roles"
loadFixture dbConn "schema"
loadFixture dbConn "jwt"
loadFixture dbConn "privileges"
resetDb dbConn
resetDb :: Text -> IO ()
resetDb dbConn = loadFixture dbConn "data"
loadFixture :: Text -> FilePath -> IO()
loadFixture dbConn name =
void $ readProcess "psql" [toS dbConn, "-a", "-f", "test/fixtures/" ++ name ++ ".sql"] []
rangeHdrs :: ByteRange -> [Header]
rangeHdrs r = [rangeUnit, (hRange, renderByteRange r)]
rangeHdrsWithCount :: ByteRange -> [Header]
rangeHdrsWithCount r = ("Prefer", "count=exact") : rangeHdrs r
acceptHdrs :: BS.ByteString -> [Header]
acceptHdrs mime = [(hAccept, mime)]
rangeUnit :: Header
rangeUnit = ("Range-Unit" :: CI BS.ByteString, "items")
matchHeader :: CI BS.ByteString -> BS.ByteString -> [Header] -> Bool
matchHeader name valRegex headers =
maybe False (=~ valRegex) $ lookup name headers
authHeaderBasic :: BS.ByteString -> BS.ByteString -> Header
authHeaderBasic u p =
(hAuthorization, "Basic " <> (toS . B64.encode . toS $ u <> ":" <> p))
authHeaderJWT :: BS.ByteString -> Header
authHeaderJWT token =
(hAuthorization, "Bearer " <> token)
-- | Tests whether the text can be parsed as a json object comtaining
-- the key "message", and optional keys "details", "hint", "code",
-- and no extraneous keys
isErrorFormat :: BL.ByteString -> Bool
isErrorFormat s =
"message" `S.member` keys &&
S.null (S.difference keys validKeys)
where
obj = decode s :: Maybe (M.Map Text Value)
keys = maybe S.empty M.keysSet obj
validKeys = S.fromList ["message", "details", "hint", "code"]
| begriffs/postgrest | test/SpecHelper.hs | mit | 6,950 | 0 | 15 | 1,128 | 1,619 | 898 | 721 | -1 | -1 |
module Lib
( pythagoreanTripletSummingTo
) where
pythagoreanTripletSummingTo :: Integer -> [Integer]
pythagoreanTripletSummingTo n =
head [ [a,b,c] | a <- [1..n-4], b <- [a+1..n-3], c <- [b+1..n-2], -- max. c can only be n-2, since a & b must be at least 1.
a^2 + b^2 == c^2,
a + b + c == n]
| JohnL4/ProjectEuler | Haskell/Problem009/src/Lib.hs | mit | 321 | 0 | 12 | 84 | 144 | 78 | 66 | 7 | 1 |
-- Use a partially applied function to define a function that will return half
-- of a number and another that will append \n to the end of any string.
module Main where
half x = (/ 2)
addNewline s = (++ "\n")
| ryanplusplus/seven-languages-in-seven-weeks | haskell/day2/partial.hs | mit | 215 | 0 | 5 | 48 | 30 | 19 | 11 | 3 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Grammatik.Type
( module Grammatik.Type
, module Autolib.Set
)
where
import Autolib.Set
import Autolib.Size
import Autolib.Hash
import Autolib.ToDoc
import Autolib.Reader
import Data.Typeable
data Grammatik = Grammatik
{ terminale :: Set Char
, variablen :: Set Char
, start :: Char
, regeln :: Set (String, String)
}
deriving ( Eq, Typeable )
example :: Grammatik
example = Grammatik
{ terminale = mkSet "ab"
, variablen = mkSet "S"
, start = 'S'
, regeln = mkSet [ ("S", ""), ("S", "aSbS") ]
}
$(derives [makeReader, makeToDoc] [''Grammatik])
instance Hash Grammatik where
hash g = hash [ hash $ terminale g
, hash $ variablen g
, hash $ start g
, hash $ regeln g
]
terms = setToList . terminale
vars = setToList . variablen
rules = setToList . regeln
instance Size Grammatik where size = cardinality . regeln
-- | for compatibility:
nichtterminale = variablen
startsymbol = start
-- local variables:
-- mode: haskell
-- end:
| florianpilz/autotool | src/Grammatik/Type.hs | gpl-2.0 | 1,158 | 31 | 9 | 353 | 330 | 185 | 145 | 34 | 1 |
{- |
Module : $Header$
Description : Interface to the theorem prover e-krhyper in CASC-mode.
Copyright : (c) Jonathan von Schroeder, DFKI GmbH 2010
License : GPLv2 or higher, see LICENSE.txt
Maintainer : jonathan.von_schroeder@dfki.de
Stability : provisional
Portability : needs POSIX
see <http://fmv.jku.at/depqbf/ for more information
on the depqbf prover and <http://www.qbflib.org/qdimacs.html>
and <http://www.qbflib.org/Draft/qDimacs.ps.gz>
for more information on the qdimacs input format
-}
module QBF.ProveDepQBF (depQBFProver)
where
import Logic.Prover
import Common.ProofTree
import qualified Common.Result as Result
import Common.AS_Annotation as AS_Anno
import Common.Timing
import Common.Utils
import Propositional.Sign
import QBF.ProverState
import qualified QBF.AS_BASIC_QBF as AS
import QBF.Morphism
import QBF.Sublogic (QBFSL, top)
import GUI.GenericATP
import Proofs.BatchProcessing
import Interfaces.GenericATPState
import System.Directory
import System.Process
import Control.Monad (when)
import qualified Control.Concurrent as Concurrent
import System.Exit (ExitCode (..))
import Data.List
import Data.Time.LocalTime (TimeOfDay)
-- Prover
-- | The Prover implementation.
depQBFProver :: Prover Sign AS.FORMULA Morphism QBFSL ProofTree
depQBFProver = mkAutomaticProver "depqbf" top depQBFGUI depQBFCMDLautomaticBatch
{- |
Record for prover specific functions. This is used by both GUI and command
line interface.
-}
atpFun :: String -- ^ theory name
-> ATPFunctions Sign AS.FORMULA Morphism ProofTree QBFProverState
atpFun thName = ATPFunctions
{ initialProverState = qbfProverState
, atpTransSenName = transSenName
, atpInsertSentence = insertSentence
, goalOutput = showQDIMACSProblem thName
, proverHelpText = "for more information visit " ++
"http://fmv.jku.at/depqbf/"
, batchTimeEnv = ""
, fileExtensions = FileExtensions
{ problemOutput = ".qdimacs"
, proverOutput = "" -- prover doesn't output any files
, theoryConfiguration = "" -- prover doesn't use any configuration files
}
, runProver = runDepQBF
, createProverOptions = extraOpts }
{- |
Invokes the generic prover GUI.
-}
depQBFGUI :: String -- ^ theory name
-> Theory Sign AS.FORMULA ProofTree
-> [FreeDefMorphism AS.FORMULA Morphism] -- ^ freeness constraints
-> IO [ProofStatus ProofTree] -- ^ proof status for each goal
depQBFGUI thName th freedefs =
genericATPgui (atpFun thName) True (proverName depQBFProver) thName th
freedefs emptyProofTree
{- |
Implementation of 'Logic.Prover.proveCMDLautomaticBatch' which provides an
automatic command line interface to the prover.
-}
depQBFCMDLautomaticBatch ::
Bool -- ^ True means include proved theorems
-> Bool -- ^ True means save problem file
-> Concurrent.MVar (Result.Result [ProofStatus ProofTree])
-- ^ used to store the result of the batch run
-> String -- ^ theory name
-> TacticScript -- ^ default tactic script
-> Theory Sign AS.FORMULA ProofTree
-> [FreeDefMorphism AS.FORMULA Morphism] -- ^ freeness constraints
-> IO (Concurrent.ThreadId, Concurrent.MVar ())
{- ^ fst: identifier of the batch thread for killing it
snd: MVar to wait for the end of the thread -}
depQBFCMDLautomaticBatch inclProvedThs saveProblem_batch resultMVar
thName defTS th freedefs =
genericCMDLautomaticBatch (atpFun thName) inclProvedThs saveProblem_batch
resultMVar (proverName depQBFProver) thName
(parseTacticScript batchTimeLimit [] defTS) th freedefs emptyProofTree
runDepQBF :: QBFProverState
{- ^ logical part containing the input Sign and axioms and possibly
goals that have been proved earlier as additional axioms -}
-> GenericConfig ProofTree -- ^ configuration to use
-> Bool -- ^ True means save QDIMACS file
-> String -- ^ name of the theory in the DevGraph
-> AS_Anno.Named AS.FORMULA -- ^ goal to prove
-> IO (ATPRetval, GenericConfig ProofTree)
-- ^ (retval, configuration with proof status and complete output)
runDepQBF ps cfg saveQDIMACS thName nGoal = do
let saveFile = basename thName ++ '_' : AS_Anno.senAttr nGoal ++ ".qdimacs"
tl = configTimeLimit cfg
prob <- showQDIMACSProblem thName ps nGoal []
when saveQDIMACS (writeFile saveFile prob)
stpTmpFile <- getTempFile prob saveFile
t_start <- getHetsTime
(exitCode, stdoutC, stderrC) <- readProcessWithExitCode "depqbf"
(show tl : extraOpts cfg ++ [stpTmpFile]) ""
t_end <- getHetsTime
removeFile stpTmpFile
let t_u = diffHetsTime t_end t_start
exitCode' = case exitCode of
ExitSuccess -> 0
ExitFailure i -> i
(pStat, ret) <- examineProof ps cfg stdoutC stderrC exitCode' nGoal t_u tl
return (pStat, cfg
{ proofStatus = ret
, resultOutput = lines (stdoutC ++ stderrC)
, timeUsed = usedTime ret })
-- | examine Prover output
examineProof :: QBFProverState
-> GenericConfig ProofTree
-> String
-> String
-> Int
-> AS_Anno.Named AS.FORMULA
-> TimeOfDay
-> Int
-> IO (ATPRetval, ProofStatus ProofTree)
examineProof ps _ stdoutC _ exitCode nGoal tUsed _ =
let
defaultStatus =
ProofStatus { goalName = senAttr nGoal
, goalStatus = openGoalStatus
, usedAxioms = []
, usedProver = proverName depQBFProver
, proofTree = emptyProofTree
, usedTime = tUsed
, tacticScript = TacticScript "" }
getAxioms = map AS_Anno.senAttr (initialAxioms ps)
in case getDepQBFResult exitCode stdoutC of
DepQBFProved -> return (ATPSuccess, defaultStatus
{
goalStatus = Proved True
, usedAxioms = getAxioms
})
DepQBFTimeout -> return (ATPTLimitExceeded, defaultStatus)
DepQBFDisproved -> return (ATPSuccess, defaultStatus
{
goalStatus = Disproved
, usedAxioms = getAxioms
})
DepQBFError s -> return (ATPError ("Internal Errorr."
++ "\nMessage:\n\n" ++ s)
, defaultStatus)
data DepQBFResult = DepQBFProved | DepQBFDisproved
| DepQBFTimeout | DepQBFError String
getDepQBFResult :: Int -> String -> DepQBFResult
getDepQBFResult exitCode out = case exitCode of
10 -> if "SAT" `isPrefixOf` out
then DepQBFProved
else DepQBFError
"Unexpected behaviour of prover!"
20 -> if "UNSAT" `isPrefixOf` out
then DepQBFDisproved
else DepQBFError
"Unexpected behaviour of prover!"
_ -> if "SIGALRM" `isInfixOf` out
then DepQBFTimeout
else DepQBFError
("Uknown error: " ++ out)
| nevrenato/Hets_Fork | QBF/ProveDepQBF.hs | gpl-2.0 | 7,769 | 0 | 15 | 2,568 | 1,289 | 700 | 589 | 134 | 6 |
-- |
-- Module : Dependencies
-- Copyright : (C) 2012-2016 Jens Petersen
--
-- Maintainer : Jens Petersen <petersen@fedoraproject.org>
-- Stability : alpha
-- Portability : portable
--
-- Explanation: Dependency info
-- 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.
module Dependencies (
dependencies,
missingPackages,
notInstalled,
packageDependencies,
showDep,
testsuiteDependencies
) where
import PackageUtils (packageName)
import SysCmd (cmd, cmdBool, repoquery, (+-+))
import Control.Applicative ((<$>))
import Control.Monad (filterM, when)
import Data.List (delete, nub)
import Data.Maybe (catMaybes, isNothing)
import Distribution.Package (Dependency (..), PackageName (..))
import Distribution.PackageDescription (PackageDescription (..),
allBuildInfo,
BuildInfo (..),
TestSuite (..),
hasExes)
import System.Directory (doesDirectoryExist, doesFileExist)
import System.IO (hPutStrLn, stderr)
excludedPkgs :: String -> Bool
excludedPkgs = flip notElem ["Cabal", "base", "ghc-prim", "integer-gmp"]
-- returns list of deps and whether package is self-dependent
buildDependencies :: PackageDescription -> String -> ([String], Bool)
buildDependencies pkgDesc self =
let deps = nub $ map depName (buildDepends pkgDesc) in
(filter excludedPkgs (delete self deps), self `elem` deps && hasExes pkgDesc)
depName :: Dependency -> String
depName (Dependency (PackageName n) _) = n
showDep :: String -> String
showDep p = "ghc-" ++ p ++ "-devel"
dependencies :: PackageDescription -- ^pkg description
-> IO ([String], [String], [String], [String], Bool)
-- ^depends, tools, c-libs, pkgcfg, selfdep
dependencies pkgDesc = do
let self = packageName $ package pkgDesc
(deps, selfdep) = buildDependencies pkgDesc self
buildinfo = allBuildInfo pkgDesc
tools = nub $ map depName (concatMap buildTools buildinfo)
pkgcfgs = nub $ map depName $ concatMap pkgconfigDepends buildinfo
clibs = concatMap extraLibs buildinfo
return (deps, tools, nub clibs, pkgcfgs, selfdep)
data QueryBackend = Rpm | Repoquery deriving Eq
resolveLib :: String -> IO (Maybe String)
resolveLib lib = do
lib64 <- doesDirectoryExist "/usr/lib64"
let libsuffix = if lib64 then "64" else ""
let lib_path = "/usr/lib" ++ libsuffix ++ "/lib" ++ lib ++ ".so"
libInst <- doesFileExist lib_path
if libInst
then rpmqueryFile Rpm lib_path
else do
putStrLn $ "Running repoquery on" +-+ "lib" ++ lib
rpmqueryFile Repoquery lib_path
-- use repoquery or rpm -q to query which package provides file
rpmqueryFile :: QueryBackend -> FilePath -> IO (Maybe String)
rpmqueryFile backend file = do
-- FIXME dnf repoquery does not support -f !
let args = ["-q", "--qf=%{name}", "-f"]
out <- if backend == Rpm
then cmd "rpm" (args ++ [file])
else repoquery args file
let pkgs = nub $ words out
-- EL5 repoquery can return "No package provides <file>"
case pkgs of
[pkg] -> return $ Just pkg
[] -> do
warning $ "Could not resolve package that provides" +-+ file
return Nothing
_ -> do
warning $ "More than one package seems to provide" +-+ file ++ ": " +-+ unwords pkgs
return Nothing
warning :: String -> IO ()
warning s = hPutStrLn stderr $ "Warning:" +-+ s
packageDependencies :: Bool -- ^strict mode: True means abort on unknown dependencies
-> PackageDescription -- ^pkg description
-> IO ([String], [String], [String], [String], Bool)
-- ^depends, tools, c-libs, pkgcfg, selfdep
packageDependencies strict pkgDesc = do
(deps, tools', clibs', pkgcfgs, selfdep) <- dependencies pkgDesc
let excludedTools n = n `notElem` ["ghc", "hsc2hs", "perl"]
mapTools "gtk2hsC2hs" = "gtk2hs-buildtools"
mapTools "gtk2hsHookGenerator" = "gtk2hs-buildtools"
mapTools "gtk2hsTypeGen" = "gtk2hs-buildtools"
mapTools tool = tool
chrpath = ["chrpath" | selfdep]
tools = filter excludedTools $ nub $ map mapTools tools' ++ chrpath
clibsWithErrors <- mapM resolveLib clibs'
when (strict && any isNothing clibsWithErrors) $
fail "cannot resolve all package dependencies"
let clibs = catMaybes clibsWithErrors
let showPkgCfg p = "pkgconfig(" ++ p ++ ")"
return (map showDep deps, tools, nub clibs, map showPkgCfg pkgcfgs, selfdep)
testsuiteDependencies :: PackageDescription -- ^pkg description
-> String -- ^self
-> [String] -- ^depends
testsuiteDependencies pkgDesc self =
map showDep . delete self . filter excludedPkgs . nub . map depName $ concatMap (targetBuildDepends . testBuildInfo) (testSuites pkgDesc)
missingPackages :: PackageDescription -> IO [String]
missingPackages pkgDesc = do
(deps, tools, clibs, pkgcfgs, _) <- packageDependencies False pkgDesc
pcpkgs <- mapM derefPkg pkgcfgs
filterM notInstalled $ deps ++ ["ghc-Cabal-devel", "ghc-rpm-macros"] ++ tools ++ clibs ++ pcpkgs
notInstalled :: String -> IO Bool
notInstalled dep =
fmap not $ cmdBool $ "rpm -q --whatprovides" +-+ shellQuote dep
where
shellQuote :: String -> String
shellQuote (c:cs) = (if c `elem` "()" then (['\\', c] ++) else (c:)) (shellQuote cs)
shellQuote "" = ""
derefPkg :: String -> IO String
derefPkg req = do
res <- singleLine <$> repoquery ["--qf", "%{name}", "--whatprovides"] req
if null res
then error $ req +-+ "provider not found by repoquery"
else return res
where
singleLine :: String -> String
singleLine "" = ""
singleLine s = (head . lines) s
| mimi1vx/cabal-rpm | src/Dependencies.hs | gpl-3.0 | 5,996 | 0 | 15 | 1,419 | 1,576 | 841 | 735 | 113 | 4 |
module Handler.SetPhaseSpec (spec) where
import TestImport
spec :: Spec
spec = withApp $ do
describe "postSetPhaseR" $ do
error "Spec not implemented: postSetPhaseR"
| ackao/APRICoT | web/conference-management-system/test/Handler/SetPhaseSpec.hs | gpl-3.0 | 182 | 0 | 11 | 39 | 44 | 23 | 21 | 6 | 1 |
-- | A module for synthetizing real electronic circuits (soldering), the fun chapter of the book.
module Dep.Algorithms.Fun where
| KommuSoft/dep-software | Dep.Algorithms.Fun.hs | gpl-3.0 | 131 | 0 | 3 | 20 | 8 | 6 | 2 | 1 | 0 |
-- | Convert Text ToNoms to their own sugar construct
{-# LANGUAGE NoImplicitPrelude #-}
module Lamdu.Sugar.Convert.Text
( text
) where
import Control.Lens.Operators
import Control.Monad (guard, mzero)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Maybe (MaybeT(..))
import qualified Data.ByteString.UTF8 as UTF8
import Data.Maybe.Utils (maybeToMPlus)
import Data.Store.Property (Property(..))
import qualified Data.Store.Property as Property
import qualified Lamdu.Builtins.Anchors as Builtins
import qualified Lamdu.Builtins.PrimVal as PrimVal
import qualified Lamdu.Calc.Val as V
import Lamdu.Calc.Val.Annotated (Val(..))
import qualified Lamdu.Expr.IRef as ExprIRef
import qualified Lamdu.Expr.Lens as ExprLens
import Lamdu.Sugar.Convert.Expression.Actions (addActions)
import qualified Lamdu.Sugar.Convert.Input as Input
import Lamdu.Sugar.Convert.Monad (ConvertM)
import Lamdu.Sugar.Internal
import Lamdu.Sugar.Types
import Prelude.Compat
text ::
(Monad m, Monoid a) =>
V.Nom (Val (Input.Payload m a)) -> Input.Payload m a ->
MaybeT (ConvertM m) (ExpressionU m a)
text (V.Nom tid (Val litPl body)) toNomPl =
do
guard $ tid == Builtins.textTid
lit <- body ^? ExprLens.valBodyLiteral & maybeToMPlus
utf8Bytes <-
case PrimVal.toKnown lit of
PrimVal.Bytes utf8Bytes -> return utf8Bytes
_ -> mzero
Property
{ _pVal = UTF8.toString utf8Bytes
, _pSet =
ExprIRef.writeValBody litIRef . V.BLeaf . V.LLiteral .
PrimVal.fromKnown . PrimVal.Bytes . UTF8.fromString
} & LiteralText & BodyLiteral & addActions toNomPl
<&> rPayload . plData <>~ litPl ^. Input.userData
& lift
where
litIRef = litPl ^. Input.stored . Property.pVal
| da-x/lamdu | Lamdu/Sugar/Convert/Text.hs | gpl-3.0 | 1,963 | 0 | 23 | 519 | 501 | 293 | 208 | -1 | -1 |
module Biobase.Fasta.Pipes where
import Control.Lens
import Control.Monad (join, unless, forM_)
import Pipes
import Data.ByteString (ByteString)
import Data.ByteString as BS
import Data.ByteString.Char8 as BS8
import Pipes.ByteString as PBS
import Pipes.Group as PG
import Data.Monoid
import Pipes as P
import Data.Semigroup
import qualified Data.List as L
import qualified Pipes.Prelude as PP
import qualified Data.ByteString.Lazy.Char8 as BSL8
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import Biobase.Fasta.Types
-- | Improper lens that splits off the first @FASTA@ entry. Newlines are still intact.
fastaEntry ∷ Monad m ⇒ Lens' (Producer ByteString m x) (Producer ByteString m (Producer ByteString m x))
fastaEntry k p0 = fmap join (k (go 1 p0))
where
-- If @hdrCount == 1@, then we have a first line where we assume to have a
-- @>@ symbol and *don't* want to split before that symbol.
go hdrCount p = do
x ← lift (next p)
case x of
Left r → return (return r)
Right (bs, p')
| BS.null bs → go hdrCount p'
| h `BS8.elem` hdrChar →
case BS8.findIndex (`BS8.elem` hdrChar) (BS8.drop hdrCount bs)
-- no header char found, yield characters and continue on
of Nothing → yield bs >> go 0 p'
-- already have seen header char, only yield
(Just z) → let (this,that) = BS.splitAt (z+hdrCount) bs
in yield this >> return (yield that >> p')
where h = BS8.head bs
{-# Inlinable fastaEntry #-}
hdrChar = BS8.pack ">;"
-- ** Test stuff
test1 :: Monad m ⇒ Producer ByteString m (Producer ByteString m ())
test1 = view fastaEntry (fromLazy $ BSL8.pack ">a\naaa\n>b\nbbb")
test2 = PP.toList (void test1)
-- TODO list for reading fasta.
--
-- Skip lines until first line starting with ">" discovered. Note (in the info
-- structure to be returned) the number of skipped header lines.
--
-- Each fasta entry should start with ">". This is the title line.
--
-- Following lines should have all '\n' stripped. And concatenated to become
-- the fasta entry. Remove internal '\r' parts.
-- Keep track of some FASTA information.
data TrackedFasta
-- | A new header has shown up.
= TrackedHeader
{ _trackedLine ∷ !Int
-- ^ which line are we in
, _trackedHeader ∷ !ByteString
-- ^ keep the header
}
-- | Fasta entries.
| TrackedFasta
{ _trackedLine ∷ !Int
-- ^ which line are we in
, _trackedPosition ∷ !Int
-- ^ position of first character in this FASTA entry.
-- TODO use typed things that shows if we are 1- or 0-based.
, _trackedData ∷ !ByteString
-- ^ the payload line
, _trackedHeader ∷ !ByteString
-- ^ keep the header
}
makeLenses ''TrackedFasta
data TF = TF
{ _tfLine ∷ !Int
, _tfPos ∷ !Int
, _tfHdr ∷ !ByteString
}
makeLenses ''TF
-- | Transforms bytestrings into tracked fasta entries. This is a
-- pre-transform: header entries can be split over multiple @TrackedHeader@
-- constructors and @TrackedFasta@ constructors hold different line lengths and
-- their corresponding header is not yet set.
tracked ∷ Monad m ⇒ Producer ByteString (Producer TrackedFasta m) x → Producer TrackedFasta m x
tracked p = next p >>= goPrepare (TF 1 1 BS.empty)
where
-- Remove all lines before the first line starting with @'>'@.
goPrepare tf = \case
Left l → return l
Right (r',p') → let r = lineprep r' in case BS8.uncons r of
-- not a single character?
Nothing → next p' >>= goPrepare tf
-- start of a FASTA header
Just (h,_) | h=='>'
→ goHdr tf $ Right (r,p')
-- remove first line and check the beginning of the next line
| Just k ← BS8.findIndex (=='\n') r
→ goPrepare (over tfLine (+1) tf) $ Right (BS8.drop k r, p')
-- we are somewhere in the first line of crap and need to pull more
-- stuff
| otherwise
→ next p' >>= goPrepare tf
-- Start emitting @TrackedHeader@. Does not do an additional check!
goHdr tf = \case
Left l → return l
Right (r',p') → let r = lineprep r' in case BS8.findIndex (=='\n') r of
-- header continues into the next fragment.
Nothing → do yield $ TrackedHeader (tf^.tfLine) r
next p' >>= goHdr tf
-- one header line, goData has to do the check on what the next line
-- is.
Just k → do yield $ TrackedHeader (tf^.tfLine) (BS8.take k r)
-- goData should be at the first character of the next
-- line now.
goData (over tfLine (+1) tf) $ Right (BS8.drop (k+1) r, p')
-- Start emitting @TrackedFasta@, but check each line for being a header.
-- This will emit @TrackedFasta@ of (at most) line length elements, but
-- sometimes (whenever @next@ is not at line boundaries) yield the same
-- line with different positions.
--
-- TODO need to remove all @\n@ and @\r@.
goData tf = \case
Left l → return l
Right (r',p') → let r = lineprep r' in case BS8.uncons r of
-- need to get more data first.
Nothing → next p' >>= goData tf
Just (h,_) | h=='>'
-- this is a header that needs to be handled.
→ goHdr tf $ Right (r,p')
-- we have at least two lines, emit the first and handle the
-- remaining bytes next.
-- the fasta header will be set by a combining function later.
| Just k ← BS8.findIndex (=='\n') r
→ do yield $ TrackedFasta (tf^.tfLine) (tf^.tfPos) (BS8.take k r) BS.empty
goData (set tfPos 1 $ over tfLine (+1) tf) $ Right (BS8.drop (k+1) r, p')
-- we have only the beginning of a line.
| otherwise
→ do yield $ TrackedFasta (tf^.tfLine) (tf^.tfPos) r BS.empty
next p' >>= goData (over tfPos (+ BS.length r) tf)
lineprep = BS8.filter (/='\r')
data RetrackOptions = RetrackOptions
{ _maxHeaderLength ∷ Maybe Int
-- ^ if @Nothing@, any size is fine, just collapse, if @Just@, then cut off
-- after these many bytes.
, _windowLength ∷ Maybe Int
-- ^ if @Nothing@ then do not re-arrange, if @Just@ then set into windows of
-- this size.
}
makeLenses ''RetrackOptions
-- | This function collapses header objects, sets the header in each window,
-- and sets window sizes if requested.
--
-- This traverses the collected elements twice.
--retracked ∷ Monad m ⇒ RetrackOptions → Producer TrackedFasta (Producer TrackedFasta m) x → Producer TrackedFasta m x
retracked o p = next p >>= goHdr Seq.empty
where
goHdr (hs ∷ Seq TrackedFasta) = \case
Left l → do unless (Seq.null hs) $ yield $ buildHeader hs
return l
Right (r,p')
| TrackedHeader{} ← r → next p' >>= goHdr (hs Seq.|> clampHdr hs r)
| otherwise → do
let hdr = buildHeader hs
yield hdr
goData hdr Seq.empty $ Right (r,p')
goData (hdr ∷ TrackedFasta) (ds ∷ Seq TrackedFasta) = \case
Left l → do case Seq.viewr ds of
Seq.EmptyR → return ()
(is Seq.:> i) → buildData True hdr is i >> return l
Right (r,p')
| TrackedHeader{} ← r → goHdr Seq.empty $ Right (r,p')
| otherwise → do ds' ← buildData False hdr ds r
next p' >>= goData hdr ds'
-- clamp all headers to maximal length.
-- TODO this is @O(n)@ time for each call.
clampHdr ∷ Seq TrackedFasta → TrackedFasta → TrackedFasta
clampHdr hs h = let Sum t = hs^.traverse.trackedHeader.to BS8.length._Unwrapped
in maybe h (\l → over trackedHeader (BS8.take (t-l)) h) $ o^.maxHeaderLength
-- builds up a header entry
buildHeader ∷ Seq TrackedFasta → TrackedFasta
buildHeader hs = let Min t = hs^.traverse.trackedLine._Unwrapped
in TrackedHeader t (hs^.traverse.trackedHeader)
-- builds data and attaches line and position information where necessary.
buildData flush hdr ds d
-- do nothing with the payload
| Nothing ← o^.windowLength
= if Seq.null ds then yield (set trackedHeader (hdr^.trackedHeader) d)
>> return Seq.empty
else error "buildData: invariant not valid"
-- flush last element.
| flush = do let y = ds Seq.|> d
(h Seq.:< _) = Seq.viewl y
yield $ TrackedFasta
{ _trackedLine = h ^. trackedLine
, _trackedPosition = _trackedPosition h
, _trackedData = y^.traverse.trackedData
, _trackedHeader = hdr^.trackedHeader
}
return Seq.empty
| Just k ← o^.windowLength
-- TODO what if @k@ is smaller than the line length, this does not work like this...
= do let es = ds Seq.|> d
Sum l = es^.traverse.trackedData.to BS8.length._Unwrapped
h Seq.:< _ = Seq.viewl es
if | k > l → return es
| k > undefined → undefined
| otherwise → do
let bs = es^.traverse.trackedData
(this,that) = BS8.splitAt k bs
y = TrackedFasta
{ _trackedLine = h^.trackedLine
, _trackedPosition = _trackedPosition h
, _trackedData = this
, _trackedHeader = hdr^.trackedHeader
}
r = TrackedFasta
{ _trackedLine = d^.trackedLine
, _trackedPosition = 1 + BS8.length (d^.trackedData) - BS8.length that
, _trackedData = that
, _trackedHeader = hdr^.trackedHeader
}
yield y
return (Seq.singleton r)
ups = PP.toList . goncats . go . view PG.groups $ P.each "122333455"
where
goncats f = do
lift (runFreeT f) >>= \case
Pure r → return r
Free p → do
f' ← p
goncats f'
go ∷ Monad m ⇒ FreeT (Producer a m) m x → FreeT (Producer a m) m x
go f = FreeT $ do
g ← runFreeT f
case g of
Pure _ → return g
Free h → do
h' ← P.runEffect $ P.for h P.discard
runFreeT $ go h'
| choener/BiobaseFasta | _old/Pipes.hs | gpl-3.0 | 10,892 | 0 | 24 | 3,630 | 2,708 | 1,371 | 1,337 | -1 | -1 |
module TopicPart where
import Data.Text (Text)
-- | Periodic update of topics
data TopicPart =
TopicPart { tag :: ByteString -- ^ Starting tag
, update :: IO Text -- ^ Updating function
, interval :: Integer -- ^ Microseconds between updates
}
-- | Seconds in a minute. Makes code more readable.
minute :: Integer
minute = 60000000
| zouppen/irc-markets | src/TopicPart.hs | gpl-3.0 | 386 | 0 | 9 | 113 | 59 | 38 | 21 | 8 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Mirror.Timeline.Update
-- 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)
--
-- Updates a timeline item in place.
--
-- /See:/ <https://developers.google.com/glass Google Mirror API Reference> for @mirror.timeline.update@.
module Network.Google.Resource.Mirror.Timeline.Update
(
-- * REST Resource
TimelineUpdateResource
-- * Creating a Request
, timelineUpdate
, TimelineUpdate
-- * Request Lenses
, tuPayload
, tuId
) where
import Network.Google.Mirror.Types
import Network.Google.Prelude
-- | A resource alias for @mirror.timeline.update@ method which the
-- 'TimelineUpdate' request conforms to.
type TimelineUpdateResource =
"mirror" :>
"v1" :>
"timeline" :>
Capture "id" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] TimelineItem :>
Put '[JSON] TimelineItem
:<|>
"upload" :>
"mirror" :>
"v1" :>
"timeline" :>
Capture "id" Text :>
QueryParam "alt" AltJSON :>
QueryParam "uploadType" Multipart :>
MultipartRelated '[JSON] TimelineItem :>
Put '[JSON] TimelineItem
-- | Updates a timeline item in place.
--
-- /See:/ 'timelineUpdate' smart constructor.
data TimelineUpdate = TimelineUpdate'
{ _tuPayload :: !TimelineItem
, _tuId :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'TimelineUpdate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tuPayload'
--
-- * 'tuId'
timelineUpdate
:: TimelineItem -- ^ 'tuPayload'
-> Text -- ^ 'tuId'
-> TimelineUpdate
timelineUpdate pTuPayload_ pTuId_ =
TimelineUpdate'
{ _tuPayload = pTuPayload_
, _tuId = pTuId_
}
-- | Multipart request metadata.
tuPayload :: Lens' TimelineUpdate TimelineItem
tuPayload
= lens _tuPayload (\ s a -> s{_tuPayload = a})
-- | The ID of the timeline item.
tuId :: Lens' TimelineUpdate Text
tuId = lens _tuId (\ s a -> s{_tuId = a})
instance GoogleRequest TimelineUpdate where
type Rs TimelineUpdate = TimelineItem
type Scopes TimelineUpdate =
'["https://www.googleapis.com/auth/glass.location",
"https://www.googleapis.com/auth/glass.timeline"]
requestClient TimelineUpdate'{..}
= go _tuId (Just AltJSON) _tuPayload mirrorService
where go :<|> _
= buildClient (Proxy :: Proxy TimelineUpdateResource)
mempty
instance GoogleRequest (MediaUpload TimelineUpdate)
where
type Rs (MediaUpload TimelineUpdate) = TimelineItem
type Scopes (MediaUpload TimelineUpdate) =
Scopes TimelineUpdate
requestClient (MediaUpload TimelineUpdate'{..} body)
= go _tuId (Just AltJSON) (Just Multipart) _tuPayload
body
mirrorService
where _ :<|> go
= buildClient (Proxy :: Proxy TimelineUpdateResource)
mempty
| rueshyna/gogol | gogol-mirror/gen/Network/Google/Resource/Mirror/Timeline/Update.hs | mpl-2.0 | 3,849 | 0 | 22 | 1,057 | 581 | 328 | 253 | 81 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Classroom.Invitations.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)
--
-- Returns a list of invitations that the requesting user is permitted to
-- view, restricted to those that match the list request. *Note:* At least
-- one of \`user_id\` or \`course_id\` must be supplied. Both fields can be
-- supplied. This method returns the following error codes: *
-- \`PERMISSION_DENIED\` for access errors.
--
-- /See:/ <https://developers.google.com/classroom/ Google Classroom API Reference> for @classroom.invitations.list@.
module Network.Google.Resource.Classroom.Invitations.List
(
-- * REST Resource
InvitationsListResource
-- * Creating a Request
, invitationsList
, InvitationsList
-- * Request Lenses
, ilXgafv
, ilUploadProtocol
, ilPp
, ilCourseId
, ilAccessToken
, ilUploadType
, ilUserId
, ilBearerToken
, ilPageToken
, ilPageSize
, ilCallback
) where
import Network.Google.Classroom.Types
import Network.Google.Prelude
-- | A resource alias for @classroom.invitations.list@ method which the
-- 'InvitationsList' request conforms to.
type InvitationsListResource =
"v1" :>
"invitations" :>
QueryParam "$.xgafv" Text :>
QueryParam "upload_protocol" Text :>
QueryParam "pp" Bool :>
QueryParam "courseId" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "userId" Text :>
QueryParam "bearer_token" Text :>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListInvitationsResponse
-- | Returns a list of invitations that the requesting user is permitted to
-- view, restricted to those that match the list request. *Note:* At least
-- one of \`user_id\` or \`course_id\` must be supplied. Both fields can be
-- supplied. This method returns the following error codes: *
-- \`PERMISSION_DENIED\` for access errors.
--
-- /See:/ 'invitationsList' smart constructor.
data InvitationsList = InvitationsList'
{ _ilXgafv :: !(Maybe Text)
, _ilUploadProtocol :: !(Maybe Text)
, _ilPp :: !Bool
, _ilCourseId :: !(Maybe Text)
, _ilAccessToken :: !(Maybe Text)
, _ilUploadType :: !(Maybe Text)
, _ilUserId :: !(Maybe Text)
, _ilBearerToken :: !(Maybe Text)
, _ilPageToken :: !(Maybe Text)
, _ilPageSize :: !(Maybe (Textual Int32))
, _ilCallback :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'InvitationsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ilXgafv'
--
-- * 'ilUploadProtocol'
--
-- * 'ilPp'
--
-- * 'ilCourseId'
--
-- * 'ilAccessToken'
--
-- * 'ilUploadType'
--
-- * 'ilUserId'
--
-- * 'ilBearerToken'
--
-- * 'ilPageToken'
--
-- * 'ilPageSize'
--
-- * 'ilCallback'
invitationsList
:: InvitationsList
invitationsList =
InvitationsList'
{ _ilXgafv = Nothing
, _ilUploadProtocol = Nothing
, _ilPp = True
, _ilCourseId = Nothing
, _ilAccessToken = Nothing
, _ilUploadType = Nothing
, _ilUserId = Nothing
, _ilBearerToken = Nothing
, _ilPageToken = Nothing
, _ilPageSize = Nothing
, _ilCallback = Nothing
}
-- | V1 error format.
ilXgafv :: Lens' InvitationsList (Maybe Text)
ilXgafv = lens _ilXgafv (\ s a -> s{_ilXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
ilUploadProtocol :: Lens' InvitationsList (Maybe Text)
ilUploadProtocol
= lens _ilUploadProtocol
(\ s a -> s{_ilUploadProtocol = a})
-- | Pretty-print response.
ilPp :: Lens' InvitationsList Bool
ilPp = lens _ilPp (\ s a -> s{_ilPp = a})
-- | Restricts returned invitations to those for a course with the specified
-- identifier.
ilCourseId :: Lens' InvitationsList (Maybe Text)
ilCourseId
= lens _ilCourseId (\ s a -> s{_ilCourseId = a})
-- | OAuth access token.
ilAccessToken :: Lens' InvitationsList (Maybe Text)
ilAccessToken
= lens _ilAccessToken
(\ s a -> s{_ilAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
ilUploadType :: Lens' InvitationsList (Maybe Text)
ilUploadType
= lens _ilUploadType (\ s a -> s{_ilUploadType = a})
-- | Restricts returned invitations to those for a specific user. The
-- identifier can be one of the following: * the numeric identifier for the
-- user * the email address of the user * the string literal \`\"me\"\`,
-- indicating the requesting user
ilUserId :: Lens' InvitationsList (Maybe Text)
ilUserId = lens _ilUserId (\ s a -> s{_ilUserId = a})
-- | OAuth bearer token.
ilBearerToken :: Lens' InvitationsList (Maybe Text)
ilBearerToken
= lens _ilBearerToken
(\ s a -> s{_ilBearerToken = a})
-- | nextPageToken value returned from a previous list call, indicating that
-- the subsequent page of results should be returned. The list request must
-- be otherwise identical to the one that resulted in this token.
ilPageToken :: Lens' InvitationsList (Maybe Text)
ilPageToken
= lens _ilPageToken (\ s a -> s{_ilPageToken = a})
-- | Maximum number of items to return. Zero means no maximum. The server may
-- return fewer than the specified number of results.
ilPageSize :: Lens' InvitationsList (Maybe Int32)
ilPageSize
= lens _ilPageSize (\ s a -> s{_ilPageSize = a}) .
mapping _Coerce
-- | JSONP
ilCallback :: Lens' InvitationsList (Maybe Text)
ilCallback
= lens _ilCallback (\ s a -> s{_ilCallback = a})
instance GoogleRequest InvitationsList where
type Rs InvitationsList = ListInvitationsResponse
type Scopes InvitationsList =
'["https://www.googleapis.com/auth/classroom.rosters",
"https://www.googleapis.com/auth/classroom.rosters.readonly"]
requestClient InvitationsList'{..}
= go _ilXgafv _ilUploadProtocol (Just _ilPp)
_ilCourseId
_ilAccessToken
_ilUploadType
_ilUserId
_ilBearerToken
_ilPageToken
_ilPageSize
_ilCallback
(Just AltJSON)
classroomService
where go
= buildClient
(Proxy :: Proxy InvitationsListResource)
mempty
| rueshyna/gogol | gogol-classroom/gen/Network/Google/Resource/Classroom/Invitations/List.hs | mpl-2.0 | 7,342 | 0 | 21 | 1,851 | 1,133 | 657 | 476 | 151 | 1 |
module Hermes.Protocol
(
) where
| bbangert/hermes-hs | src/Hermes/Protocol.hs | mpl-2.0 | 41 | 0 | 3 | 13 | 9 | 6 | 3 | 2 | 0 |
-- | Parsing of objects.
module Data.GI.GIR.Object
( Object(..)
, parseObject
) where
import Data.Text (Text)
import Data.GI.GIR.Method (Method, parseMethod, MethodType(..))
import Data.GI.GIR.Property (Property, parseProperty)
import Data.GI.GIR.Signal (Signal, parseSignal)
import Data.GI.GIR.Parser
data Object = Object {
objParent :: Maybe Name,
objTypeInit :: Text,
objTypeName :: Text,
objInterfaces :: [Name],
objDeprecated :: Maybe DeprecationInfo,
objDocumentation :: Maybe Documentation,
objMethods :: [Method],
objProperties :: [Property],
objSignals :: [Signal]
} deriving Show
parseObject :: Parser (Name, Object)
parseObject = do
name <- parseName
deprecated <- parseDeprecation
doc <- parseDocumentation
methods <- parseChildrenWithLocalName "method" (parseMethod OrdinaryMethod)
constructors <- parseChildrenWithLocalName "constructor" (parseMethod Constructor)
functions <- parseChildrenWithLocalName "function" (parseMethod MemberFunction)
parent <- optionalAttr "parent" Nothing (fmap Just . qualifyName)
interfaces <- parseChildrenWithLocalName "implements" parseName
props <- parseChildrenWithLocalName "property" parseProperty
typeInit <- getAttrWithNamespace GLibGIRNS "get-type"
typeName <- getAttrWithNamespace GLibGIRNS "type-name"
signals <- parseChildrenWithNSName GLibGIRNS "signal" parseSignal
return (name,
Object {
objParent = parent
, objTypeInit = typeInit
, objTypeName = typeName
, objInterfaces = interfaces
, objDeprecated = deprecated
, objDocumentation = doc
, objMethods = constructors ++ methods ++ functions
, objProperties = props
, objSignals = signals
})
| hamishmack/haskell-gi | lib/Data/GI/GIR/Object.hs | lgpl-2.1 | 1,795 | 0 | 12 | 377 | 433 | 243 | 190 | 44 | 1 |
-- contigHead("aaabbbaaa") -> "aaa"
-- chop("aaabbbaaa") -> "aaa", "bbbaaa"
-- first((a, b)) -> a
-- pack("aaabbbaaa") -> "aaa", "bbb", "aaa"
contigHead :: [Char] -> [Char]
contigHead str
| length str == 0 = ""
| otherwise =
if length ts == 0 then [h]
else
if h == head ts
then h : contigHead ts
else [h]
where h : ts = str
chop :: [Char] -> ([Char], [Char])
chop str
| length str == 0 = ("", "")
| length str == 1 = (str, "")
| otherwise = (hs, ts)
where
hs = contigHead str
ts = drop (length hs) str
pack :: [Char] -> [[Char]]
pack str
| length str == 0 = []
| otherwise = [hs] ++ pack ts
where (hs, ts) = chop str
| ekalosak/haskell-practice | 9.hs | lgpl-3.0 | 728 | 0 | 9 | 241 | 296 | 154 | 142 | 21 | 3 |
{- | Support for resource pagination.
-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
module Pos.Util.Pagination (
Page(..)
, PerPage(..)
, maxPerPageEntries
, defaultPerPageEntries
, PaginationMetadata(..)
, PaginationParams(..)
) where
import Universum
import Control.Lens (at, ix, (?~))
import Data.Aeson (Value (Number))
import qualified Data.Aeson.Options as Aeson
import Data.Aeson.TH
import qualified Data.Char as Char
import Data.Default
import Data.Swagger as S
import Formatting (bprint, build, (%))
import qualified Formatting.Buildable
import Test.QuickCheck (Arbitrary (..), choose, getPositive)
import Web.HttpApiData
-- | A `Page` is used in paginated endpoints to request access to a particular
-- subset of a collection.
newtype Page = Page Int
deriving (Show, Eq, Ord, Num)
deriveJSON Aeson.defaultOptions ''Page
instance Arbitrary Page where
arbitrary = Page . getPositive <$> arbitrary
instance FromHttpApiData Page where
parseQueryParam qp = case parseQueryParam qp of
Right (p :: Int) | p < 1 -> Left "A page number cannot be less than 1."
Right (p :: Int) -> Right (Page p)
Left e -> Left e
instance ToHttpApiData Page where
toQueryParam (Page p) = fromString (show p)
instance ToSchema Page where
declareNamedSchema =
pure . NamedSchema (Just "Page") . paramSchemaToSchema
instance ToParamSchema Page where
toParamSchema _ = mempty
& type_ ?~ SwaggerInteger
& default_ ?~ (Number 1) -- Always show the first page by default.
& minimum_ ?~ 1
-- | If not specified otherwise, return first page.
instance Default Page where
def = Page 1
instance Buildable Page where
build (Page p) = bprint build p
-- | A `PerPage` is used to specify the number of entries which should be returned
-- as part of a paginated response.
newtype PerPage = PerPage Int
deriving (Show, Eq, Num, Ord)
deriveJSON Aeson.defaultOptions ''PerPage
instance ToSchema PerPage where
declareNamedSchema =
pure . NamedSchema (Just "PerPage") . paramSchemaToSchema
instance ToParamSchema PerPage where
toParamSchema _ = mempty
& type_ ?~ SwaggerInteger
& default_ ?~ (Number $ fromIntegral defaultPerPageEntries)
& minimum_ ?~ 1
& maximum_ ?~ (fromIntegral maxPerPageEntries)
-- | The maximum number of entries a paginated request can return on a single call.
-- This value is currently arbitrary and it might need to be tweaked down to strike
-- the right balance between number of requests and load of each of them on the system.
maxPerPageEntries :: Int
maxPerPageEntries = 50
-- | If not specified otherwise, a default number of 10 entries from the collection will
-- be returned as part of each paginated response.
defaultPerPageEntries :: Int
defaultPerPageEntries = 10
instance Arbitrary PerPage where
arbitrary = PerPage <$> choose (1, maxPerPageEntries)
instance FromHttpApiData PerPage where
parseQueryParam qp = case parseQueryParam qp of
Right (p :: Int) | p < 1 -> Left "per_page should be at least 1."
Right (p :: Int) | p > maxPerPageEntries ->
Left $ fromString $ "per_page cannot be greater than " <> show maxPerPageEntries <> "."
Right (p :: Int) -> Right (PerPage p)
Left e -> Left e
instance ToHttpApiData PerPage where
toQueryParam (PerPage p) = fromString (show p)
instance Default PerPage where
def = PerPage defaultPerPageEntries
instance Buildable PerPage where
build (PerPage p) = bprint build p
-- | Extra information associated with pagination
data PaginationMetadata = PaginationMetadata
{ metaTotalPages :: Int -- ^ The total pages returned by this query.
, metaPage :: Page -- ^ The current page number (index starts at 1).
, metaPerPage :: PerPage -- ^ The number of entries contained in this page.
, metaTotalEntries :: Int -- ^ The total number of entries in the collection.
} deriving (Show, Eq, Generic)
deriveJSON Aeson.defaultOptions ''PaginationMetadata
instance Arbitrary PaginationMetadata where
arbitrary = PaginationMetadata <$> fmap getPositive arbitrary
<*> arbitrary
<*> arbitrary
<*> fmap getPositive arbitrary
instance ToSchema PaginationMetadata where
declareNamedSchema proxy = do
schm <- genericDeclareNamedSchema defaultSchemaOptions
{ S.fieldLabelModifier =
over (ix 0) Char.toLower . drop 4 -- length "meta"
} proxy
pure $ over schema (over properties adjustPropsSchema) schm
where
totalSchema = Inline $ mempty
& type_ ?~ SwaggerNumber
& minimum_ ?~ 0
& maximum_ ?~ fromIntegral (maxBound :: Int)
adjustPropsSchema s = s
& at "totalPages" ?~ totalSchema
& at "totalEntries" ?~ totalSchema
instance Buildable PaginationMetadata where
build PaginationMetadata{..} =
bprint (build%"/"%build%" total="%build%" per_page="%build)
metaPage
metaTotalPages
metaTotalEntries
metaPerPage
-- | `PaginationParams` is datatype which combines request params related
-- to pagination together.
data PaginationParams = PaginationParams
{ ppPage :: Page -- ^ Greater than 0.
, ppPerPage :: PerPage
} deriving (Show, Eq, Generic)
instance Buildable PaginationParams where
build PaginationParams{..} =
bprint ("page=" % build % ", per_page=" % build)
ppPage
ppPerPage
| input-output-hk/cardano-sl | lib/src/Pos/Util/Pagination.hs | apache-2.0 | 5,923 | 0 | 15 | 1,593 | 1,264 | 672 | 592 | -1 | -1 |
module Binary.A309576 (a309576, a309576_rows) where
import Helpers.Binary (lastBits)
-- Table read by rows: T(n, k) is the last k bits of n, 0 <= k <= A070939 n.
a309576_rows :: [[Int]]
a309576_rows = map (\n -> lastBits n ++ [n]) [1..]
a309576_list :: [Int]
a309576_list = concat a309576_rows
a309576 :: Int -> Int
a309576 n = a309576_list !! (n - 1)
| peterokagey/haskellOEIS | src/Binary/A309576.hs | apache-2.0 | 355 | 0 | 9 | 64 | 111 | 64 | 47 | 8 | 1 |
{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, LambdaCase #-}
module HERMIT.Dictionary.Kure
( -- * KURE Strategies
externals
, anyCallR
, betweenR
, anyCallR_LCore
, testQuery
, hfocusR
, hfocusT
) where
import Control.Arrow
import Control.Monad (liftM)
import HERMIT.Core
import HERMIT.Context
import HERMIT.GHC
import HERMIT.Kure
import HERMIT.External
------------------------------------------------------------------------------------
-- | -- This list contains reflections of the KURE strategies as 'External's.
externals :: [External]
externals = map (.+ KURE)
[ external "id" (idR :: RewriteH LCore)
[ "Perform an identity rewrite."] .+ Shallow
, external "id" (idR :: RewriteH LCoreTC)
[ "Perform an identity rewrite."] .+ Shallow
, external "success" (successT :: TransformH LCore ())
[ "An always succeeding translation." ]
, external "fail" (fail :: String -> RewriteH LCore)
[ "A failing rewrite."]
, external "<+" ((<+) :: RewriteH LCore -> RewriteH LCore -> RewriteH LCore)
[ "Perform the first rewrite, and then, if it fails, perform the second rewrite." ]
, external "<+" ((<+) :: TransformH LCore () -> TransformH LCore () -> TransformH LCore ())
[ "Perform the first check, and then, if it fails, perform the second check." ]
, external ">>>" ((>>>) :: RewriteH LCore -> RewriteH LCore -> RewriteH LCore)
[ "Compose rewrites, requiring both to succeed." ]
, external ">>>" ((>>>) :: BiRewriteH LCore -> BiRewriteH LCore -> BiRewriteH LCore)
[ "Compose bidirectional rewrites, requiring both to succeed." ]
, external ">>>" ((>>>) :: RewriteH LCoreTC -> RewriteH LCoreTC -> RewriteH LCoreTC)
[ "Compose rewrites, requiring both to succeed." ]
, external ">+>" ((>+>) :: RewriteH LCore -> RewriteH LCore -> RewriteH LCore)
[ "Compose rewrites, allowing one to fail." ]
, external "try" (tryR :: RewriteH LCore -> RewriteH LCore)
[ "Try a rewrite, and perform the identity if the rewrite fails." ]
, external "repeat" (repeatR :: RewriteH LCore -> RewriteH LCore)
[ "Repeat a rewrite until it would fail." ] .+ Loop
, external "replicate" ((\ n -> andR . replicate n) :: Int -> RewriteH LCore -> RewriteH LCore)
[ "Repeat a rewrite n times." ]
, external "all" (allR :: RewriteH LCore -> RewriteH LCore)
[ "Apply a rewrite to all children of the node, requiring success at every child." ] .+ Shallow
, external "any" (anyR :: RewriteH LCore -> RewriteH LCore)
[ "Apply a rewrite to all children of the node, requiring success for at least one child." ] .+ Shallow
, external "one" (oneR :: RewriteH LCore -> RewriteH LCore)
[ "Apply a rewrite to the first child of the node for which it can succeed." ] .+ Shallow
, external "all-bu" (allbuR :: RewriteH LCore -> RewriteH LCore)
[ "Promote a rewrite to operate over an entire tree in bottom-up order, requiring success at every node." ] .+ Deep
, external "all-td" (alltdR :: RewriteH LCore -> RewriteH LCore)
[ "Promote a rewrite to operate over an entire tree in top-down order, requiring success at every node." ] .+ Deep
, external "all-du" (allduR :: RewriteH LCore -> RewriteH LCore)
[ "Apply a rewrite twice, in a top-down and bottom-up way, using one single tree traversal,",
"succeeding if they all succeed."] .+ Deep
, external "any-bu" (anybuR :: RewriteH LCore -> RewriteH LCore)
[ "Promote a rewrite to operate over an entire tree in bottom-up order, requiring success for at least one node." ] .+ Deep
, external "any-td" (anytdR :: RewriteH LCore -> RewriteH LCore)
[ "Promote a rewrite to operate over an entire tree in top-down order, requiring success for at least one node." ] .+ Deep
, external "any-du" (anyduR :: RewriteH LCore -> RewriteH LCore)
[ "Apply a rewrite twice, in a top-down and bottom-up way, using one single tree traversal,",
"succeeding if any succeed."] .+ Deep
, external "one-td" (onetdR :: RewriteH LCore -> RewriteH LCore)
[ "Apply a rewrite to the first node (in a top-down order) for which it can succeed." ] .+ Deep
, external "one-bu" (onebuR :: RewriteH LCore -> RewriteH LCore)
[ "Apply a rewrite to the first node (in a bottom-up order) for which it can succeed." ] .+ Deep
, external "prune-td" (prunetdR :: RewriteH LCore -> RewriteH LCore)
[ "Attempt to apply a rewrite in a top-down manner, prunning at successful rewrites." ] .+ Deep
, external "innermost" (innermostR :: RewriteH LCore -> RewriteH LCore)
[ "A fixed-point traveral, starting with the innermost term." ] .+ Deep .+ Loop
, external "focus" (hfocusR :: TransformH LCoreTC LocalPathH -> RewriteH LCoreTC -> RewriteH LCoreTC)
[ "Apply a rewrite to a focal point."] .+ Navigation .+ Deep
, external "focus" (hfocusT :: TransformH LCoreTC LocalPathH -> TransformH LCoreTC String -> TransformH LCoreTC String)
[ "Apply a query at a focal point."] .+ Navigation .+ Deep
, external "focus" ((\p -> hfocusR (return p)) :: LocalPathH -> RewriteH LCoreTC -> RewriteH LCoreTC)
[ "Apply a rewrite to a focal point."] .+ Navigation .+ Deep
, external "focus" ((\p -> hfocusT (return p)) :: LocalPathH -> TransformH LCoreTC String -> TransformH LCoreTC String)
[ "Apply a query at a focal point."] .+ Navigation .+ Deep
, external "focus" (hfocusR :: TransformH LCore LocalPathH -> RewriteH LCore -> RewriteH LCore)
[ "Apply a rewrite to a focal point."] .+ Navigation .+ Deep
, external "focus" (hfocusT :: TransformH LCore LocalPathH -> TransformH LCore String -> TransformH LCore String)
[ "Apply a query at a focal point."] .+ Navigation .+ Deep
, external "focus" ((\p -> hfocusR (return p)) :: LocalPathH -> RewriteH LCore -> RewriteH LCore)
[ "Apply a rewrite to a focal point."] .+ Navigation .+ Deep
, external "focus" ((\p -> hfocusT (return p)) :: LocalPathH -> TransformH LCore String -> TransformH LCore String)
[ "Apply a query at a focal point."] .+ Navigation .+ Deep
, external "when" ((>>) :: TransformH LCore () -> RewriteH LCore -> RewriteH LCore)
[ "Apply a rewrite only if the check succeeds." ] .+ Predicate
, external "not" (notM :: TransformH LCore () -> TransformH LCore ())
[ "Cause a failing check to succeed, a succeeding check to fail." ] .+ Predicate
, external "invert" (invertBiT :: BiRewriteH LCore -> BiRewriteH LCore)
[ "Reverse a bidirectional rewrite." ]
, external "forward" (forwardT :: BiRewriteH LCore -> RewriteH LCore)
[ "Apply a bidirectional rewrite forewards." ]
, external "backward" (backwardT :: BiRewriteH LCore -> RewriteH LCore)
[ "Apply a bidirectional rewrite backwards." ]
, external "test" (testQuery :: RewriteH LCore -> TransformH LCore String)
[ "Determine if a rewrite could be successfully applied." ]
, external "any-call" (anyCallR_LCore :: RewriteH LCore -> RewriteH LCore)
[ "any-call (.. unfold command ..) applies an unfold command to all applications."
, "Preference is given to applications with more arguments." ] .+ Deep
, external "promote" (promoteR :: RewriteH LCore -> RewriteH LCoreTC)
[ "Promote a RewriteCore to a RewriteCoreTC" ]
, external "extract" (extractR :: RewriteH LCoreTC -> RewriteH LCore)
[ "Extract a RewriteCore from a RewriteCoreTC" ]
, external "extract" (extractT :: TransformH LCoreTC String -> TransformH LCore String)
[ "Extract a TransformLCoreString from a TransformLCoreTCString" ]
, external "between" (betweenR :: Int -> Int -> RewriteH LCoreTC -> RewriteH LCoreTC)
[ "between x y rr -> perform rr at least x times and at most y times." ]
, external "atPath" (flip hfocusT idR :: TransformH LCore LocalPathH -> TransformH LCore LCore)
[ "return the expression found at the given path" ]
, external "atPath" (flip hfocusT idR :: TransformH LCoreTC LocalPathH -> TransformH LCoreTC LCoreTC)
[ "return the expression found at the given path" ]
, external "atPath" (extractT . flip hfocusT projectT :: TransformH LCoreTC LocalPathH -> TransformH LCore LCore)
[ "return the expression found at the given path" ]
]
------------------------------------------------------------------------------------
hfocusR :: (ExtendPath c Crumb, ReadPath c Crumb, AddBindings c, HasEmptyContext c, Walker c u, MonadCatch m)
=> Transform c m u LocalPathH -> Rewrite c m u -> Rewrite c m u
hfocusR tp r = do lp <- tp
localPathR lp r
{-# INLINE hfocusR #-}
hfocusT :: (ExtendPath c Crumb, ReadPath c Crumb, AddBindings c, HasEmptyContext c, Walker c u, MonadCatch m)
=> Transform c m u LocalPathH -> Transform c m u b -> Transform c m u b
hfocusT tp t = do lp <- tp
localPathT lp t
{-# INLINE hfocusT #-}
------------------------------------------------------------------------------------
-- | Test if a rewrite would succeed, producing a string describing the result.
testQuery :: MonadCatch m => Rewrite c m g -> Transform c m g String
testQuery r = f `liftM` testM r
where
f :: Bool -> String
f True = "Rewrite would succeed."
f False = "Rewrite would fail."
{-# INLINE testQuery #-}
------------------------------------------------------------------------------------
-- | Top-down traversal tuned to matching function calls.
anyCallR :: forall c m. (ExtendPath c Crumb, ReadPath c Crumb, AddBindings c, HasEmptyContext c, MonadCatch m)
=> Rewrite c m Core -> Rewrite c m Core
anyCallR rr = prefixFailMsg "any-call failed: " $
readerT $ \case
ExprCore (App {}) -> childR App_Arg (anyCallR rr)
>+> (rr <+ childR App_Fun (anyCallR rr))
ExprCore (Var {}) -> rr
_ -> anyR (anyCallR rr)
-- | Top-down traversal tuned to matching function calls.
anyCallR_LCore :: forall c m. (ExtendPath c Crumb, ReadPath c Crumb, AddBindings c, HasEmptyContext c, LemmaContext c, MonadCatch m)
=> Rewrite c m LCore -> Rewrite c m LCore
anyCallR_LCore rr = prefixFailMsg "any-call failed: " $
readerT $ \case
LCore (ExprCore (App {})) -> childR App_Arg (anyCallR_LCore rr)
>+> (rr <+ childR App_Fun (anyCallR_LCore rr))
LCore (ExprCore (Var {})) -> rr
_ -> anyR (anyCallR_LCore rr)
-- TODO: sort out this duplication
------------------------------------------------------------------------------------
-- | betweenR x y rr -> perform rr at least x times and at most y times.
betweenR :: MonadCatch m => Int -> Int -> Rewrite c m a -> Rewrite c m a
betweenR l h rr | l < 0 = fail "betweenR: lower limit below zero"
| h < l = fail "betweenR: upper limit less than lower limit"
| otherwise = go 0
where -- 'c' is number of times rr has run already
go c | c >= h = idR -- done
| c < l = rr >>> go (c+1) -- haven't hit lower bound yet
| otherwise = tryR (rr >>> go (c+1)) -- met lower bound
------------------------------------------------------------------------------------
| beni55/hermit | src/HERMIT/Dictionary/Kure.hs | bsd-2-clause | 11,723 | 0 | 15 | 3,014 | 2,736 | 1,408 | 1,328 | 157 | 3 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QErrorMessage.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:18
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QErrorMessage (
QqErrorMessage(..)
,qErrorMessageQtHandler
,qErrorMessage_delete
,qErrorMessage_deleteLater
)
where
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 (QErrorMessage ()) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QErrorMessage_userMethod cobj_qobj (toCInt evid)
foreign import ccall "qtc_QErrorMessage_userMethod" qtc_QErrorMessage_userMethod :: Ptr (TQErrorMessage a) -> CInt -> IO ()
instance QuserMethod (QErrorMessageSc a) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QErrorMessage_userMethod cobj_qobj (toCInt evid)
instance QuserMethod (QErrorMessage ()) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QErrorMessage_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
foreign import ccall "qtc_QErrorMessage_userMethodVariant" qtc_QErrorMessage_userMethodVariant :: Ptr (TQErrorMessage a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
instance QuserMethod (QErrorMessageSc a) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QErrorMessage_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
class QqErrorMessage x1 where
qErrorMessage :: x1 -> IO (QErrorMessage ())
instance QqErrorMessage (()) where
qErrorMessage ()
= withQErrorMessageResult $
qtc_QErrorMessage
foreign import ccall "qtc_QErrorMessage" qtc_QErrorMessage :: IO (Ptr (TQErrorMessage ()))
instance QqErrorMessage ((QWidget t1)) where
qErrorMessage (x1)
= withQErrorMessageResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage1 cobj_x1
foreign import ccall "qtc_QErrorMessage1" qtc_QErrorMessage1 :: Ptr (TQWidget t1) -> IO (Ptr (TQErrorMessage ()))
instance QchangeEvent (QErrorMessage ()) ((QEvent t1)) where
changeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_changeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_changeEvent_h" qtc_QErrorMessage_changeEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQEvent t1) -> IO ()
instance QchangeEvent (QErrorMessageSc a) ((QEvent t1)) where
changeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_changeEvent_h cobj_x0 cobj_x1
instance Qdone (QErrorMessage ()) ((Int)) where
done x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_done cobj_x0 (toCInt x1)
foreign import ccall "qtc_QErrorMessage_done" qtc_QErrorMessage_done :: Ptr (TQErrorMessage a) -> CInt -> IO ()
instance Qdone (QErrorMessageSc a) ((Int)) where
done x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_done cobj_x0 (toCInt x1)
qErrorMessageQtHandler :: (()) -> IO (QErrorMessage ())
qErrorMessageQtHandler ()
= withQErrorMessageResult $
qtc_QErrorMessage_qtHandler
foreign import ccall "qtc_QErrorMessage_qtHandler" qtc_QErrorMessage_qtHandler :: IO (Ptr (TQErrorMessage ()))
instance QshowMessage (QErrorMessage a) ((String)) where
showMessage x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QErrorMessage_showMessage cobj_x0 cstr_x1
foreign import ccall "qtc_QErrorMessage_showMessage" qtc_QErrorMessage_showMessage :: Ptr (TQErrorMessage a) -> CWString -> IO ()
qErrorMessage_delete :: QErrorMessage a -> IO ()
qErrorMessage_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_delete cobj_x0
foreign import ccall "qtc_QErrorMessage_delete" qtc_QErrorMessage_delete :: Ptr (TQErrorMessage a) -> IO ()
qErrorMessage_deleteLater :: QErrorMessage a -> IO ()
qErrorMessage_deleteLater x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_deleteLater cobj_x0
foreign import ccall "qtc_QErrorMessage_deleteLater" qtc_QErrorMessage_deleteLater :: Ptr (TQErrorMessage a) -> IO ()
instance Qaccept (QErrorMessage ()) (()) where
accept x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_accept_h cobj_x0
foreign import ccall "qtc_QErrorMessage_accept_h" qtc_QErrorMessage_accept_h :: Ptr (TQErrorMessage a) -> IO ()
instance Qaccept (QErrorMessageSc a) (()) where
accept x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_accept_h cobj_x0
instance QadjustPosition (QErrorMessage ()) ((QWidget t1)) where
adjustPosition x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_adjustPosition cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_adjustPosition" qtc_QErrorMessage_adjustPosition :: Ptr (TQErrorMessage a) -> Ptr (TQWidget t1) -> IO ()
instance QadjustPosition (QErrorMessageSc a) ((QWidget t1)) where
adjustPosition x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_adjustPosition cobj_x0 cobj_x1
instance QcloseEvent (QErrorMessage ()) ((QCloseEvent t1)) where
closeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_closeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_closeEvent_h" qtc_QErrorMessage_closeEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQCloseEvent t1) -> IO ()
instance QcloseEvent (QErrorMessageSc a) ((QCloseEvent t1)) where
closeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_closeEvent_h cobj_x0 cobj_x1
instance QcontextMenuEvent (QErrorMessage ()) ((QContextMenuEvent t1)) where
contextMenuEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_contextMenuEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_contextMenuEvent_h" qtc_QErrorMessage_contextMenuEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent (QErrorMessageSc a) ((QContextMenuEvent t1)) where
contextMenuEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_contextMenuEvent_h cobj_x0 cobj_x1
instance Qevent (QErrorMessage ()) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_event_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_event_h" qtc_QErrorMessage_event_h :: Ptr (TQErrorMessage a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent (QErrorMessageSc a) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_event_h cobj_x0 cobj_x1
instance QeventFilter (QErrorMessage ()) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QErrorMessage_eventFilter cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QErrorMessage_eventFilter" qtc_QErrorMessage_eventFilter :: Ptr (TQErrorMessage a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter (QErrorMessageSc a) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QErrorMessage_eventFilter cobj_x0 cobj_x1 cobj_x2
instance QkeyPressEvent (QErrorMessage ()) ((QKeyEvent t1)) where
keyPressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_keyPressEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_keyPressEvent_h" qtc_QErrorMessage_keyPressEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent (QErrorMessageSc a) ((QKeyEvent t1)) where
keyPressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_keyPressEvent_h cobj_x0 cobj_x1
instance QqminimumSizeHint (QErrorMessage ()) (()) where
qminimumSizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_minimumSizeHint_h cobj_x0
foreign import ccall "qtc_QErrorMessage_minimumSizeHint_h" qtc_QErrorMessage_minimumSizeHint_h :: Ptr (TQErrorMessage a) -> IO (Ptr (TQSize ()))
instance QqminimumSizeHint (QErrorMessageSc a) (()) where
qminimumSizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_minimumSizeHint_h cobj_x0
instance QminimumSizeHint (QErrorMessage ()) (()) where
minimumSizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QErrorMessage_minimumSizeHint_qth_h" qtc_QErrorMessage_minimumSizeHint_qth_h :: Ptr (TQErrorMessage a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QminimumSizeHint (QErrorMessageSc a) (()) where
minimumSizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
instance Qreject (QErrorMessage ()) (()) where
reject x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_reject_h cobj_x0
foreign import ccall "qtc_QErrorMessage_reject_h" qtc_QErrorMessage_reject_h :: Ptr (TQErrorMessage a) -> IO ()
instance Qreject (QErrorMessageSc a) (()) where
reject x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_reject_h cobj_x0
instance QresizeEvent (QErrorMessage ()) ((QResizeEvent t1)) where
resizeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_resizeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_resizeEvent_h" qtc_QErrorMessage_resizeEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQResizeEvent t1) -> IO ()
instance QresizeEvent (QErrorMessageSc a) ((QResizeEvent t1)) where
resizeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_resizeEvent_h cobj_x0 cobj_x1
instance QsetVisible (QErrorMessage ()) ((Bool)) where
setVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_setVisible_h cobj_x0 (toCBool x1)
foreign import ccall "qtc_QErrorMessage_setVisible_h" qtc_QErrorMessage_setVisible_h :: Ptr (TQErrorMessage a) -> CBool -> IO ()
instance QsetVisible (QErrorMessageSc a) ((Bool)) where
setVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_setVisible_h cobj_x0 (toCBool x1)
instance QshowEvent (QErrorMessage ()) ((QShowEvent t1)) where
showEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_showEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_showEvent_h" qtc_QErrorMessage_showEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQShowEvent t1) -> IO ()
instance QshowEvent (QErrorMessageSc a) ((QShowEvent t1)) where
showEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_showEvent_h cobj_x0 cobj_x1
instance QqsizeHint (QErrorMessage ()) (()) where
qsizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_sizeHint_h cobj_x0
foreign import ccall "qtc_QErrorMessage_sizeHint_h" qtc_QErrorMessage_sizeHint_h :: Ptr (TQErrorMessage a) -> IO (Ptr (TQSize ()))
instance QqsizeHint (QErrorMessageSc a) (()) where
qsizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_sizeHint_h cobj_x0
instance QsizeHint (QErrorMessage ()) (()) where
sizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QErrorMessage_sizeHint_qth_h" qtc_QErrorMessage_sizeHint_qth_h :: Ptr (TQErrorMessage a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QsizeHint (QErrorMessageSc a) (()) where
sizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
instance QactionEvent (QErrorMessage ()) ((QActionEvent t1)) where
actionEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_actionEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_actionEvent_h" qtc_QErrorMessage_actionEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQActionEvent t1) -> IO ()
instance QactionEvent (QErrorMessageSc a) ((QActionEvent t1)) where
actionEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_actionEvent_h cobj_x0 cobj_x1
instance QaddAction (QErrorMessage ()) ((QAction t1)) (IO ()) where
addAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_addAction cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_addAction" qtc_QErrorMessage_addAction :: Ptr (TQErrorMessage a) -> Ptr (TQAction t1) -> IO ()
instance QaddAction (QErrorMessageSc a) ((QAction t1)) (IO ()) where
addAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_addAction cobj_x0 cobj_x1
instance Qcreate (QErrorMessage ()) (()) (IO ()) where
create x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_create cobj_x0
foreign import ccall "qtc_QErrorMessage_create" qtc_QErrorMessage_create :: Ptr (TQErrorMessage a) -> IO ()
instance Qcreate (QErrorMessageSc a) (()) (IO ()) where
create x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_create cobj_x0
instance Qcreate (QErrorMessage ()) ((QVoid t1)) (IO ()) where
create x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_create1 cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_create1" qtc_QErrorMessage_create1 :: Ptr (TQErrorMessage a) -> Ptr (TQVoid t1) -> IO ()
instance Qcreate (QErrorMessageSc a) ((QVoid t1)) (IO ()) where
create x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_create1 cobj_x0 cobj_x1
instance Qcreate (QErrorMessage ()) ((QVoid t1, Bool)) (IO ()) where
create x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_create2 cobj_x0 cobj_x1 (toCBool x2)
foreign import ccall "qtc_QErrorMessage_create2" qtc_QErrorMessage_create2 :: Ptr (TQErrorMessage a) -> Ptr (TQVoid t1) -> CBool -> IO ()
instance Qcreate (QErrorMessageSc a) ((QVoid t1, Bool)) (IO ()) where
create x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_create2 cobj_x0 cobj_x1 (toCBool x2)
instance Qcreate (QErrorMessage ()) ((QVoid t1, Bool, Bool)) (IO ()) where
create x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3)
foreign import ccall "qtc_QErrorMessage_create3" qtc_QErrorMessage_create3 :: Ptr (TQErrorMessage a) -> Ptr (TQVoid t1) -> CBool -> CBool -> IO ()
instance Qcreate (QErrorMessageSc a) ((QVoid t1, Bool, Bool)) (IO ()) where
create x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3)
instance Qdestroy (QErrorMessage ()) (()) where
destroy x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_destroy cobj_x0
foreign import ccall "qtc_QErrorMessage_destroy" qtc_QErrorMessage_destroy :: Ptr (TQErrorMessage a) -> IO ()
instance Qdestroy (QErrorMessageSc a) (()) where
destroy x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_destroy cobj_x0
instance Qdestroy (QErrorMessage ()) ((Bool)) where
destroy x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_destroy1 cobj_x0 (toCBool x1)
foreign import ccall "qtc_QErrorMessage_destroy1" qtc_QErrorMessage_destroy1 :: Ptr (TQErrorMessage a) -> CBool -> IO ()
instance Qdestroy (QErrorMessageSc a) ((Bool)) where
destroy x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_destroy1 cobj_x0 (toCBool x1)
instance Qdestroy (QErrorMessage ()) ((Bool, Bool)) where
destroy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_destroy2 cobj_x0 (toCBool x1) (toCBool x2)
foreign import ccall "qtc_QErrorMessage_destroy2" qtc_QErrorMessage_destroy2 :: Ptr (TQErrorMessage a) -> CBool -> CBool -> IO ()
instance Qdestroy (QErrorMessageSc a) ((Bool, Bool)) where
destroy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_destroy2 cobj_x0 (toCBool x1) (toCBool x2)
instance QdevType (QErrorMessage ()) (()) where
devType x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_devType_h cobj_x0
foreign import ccall "qtc_QErrorMessage_devType_h" qtc_QErrorMessage_devType_h :: Ptr (TQErrorMessage a) -> IO CInt
instance QdevType (QErrorMessageSc a) (()) where
devType x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_devType_h cobj_x0
instance QdragEnterEvent (QErrorMessage ()) ((QDragEnterEvent t1)) where
dragEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_dragEnterEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_dragEnterEvent_h" qtc_QErrorMessage_dragEnterEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQDragEnterEvent t1) -> IO ()
instance QdragEnterEvent (QErrorMessageSc a) ((QDragEnterEvent t1)) where
dragEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_dragEnterEvent_h cobj_x0 cobj_x1
instance QdragLeaveEvent (QErrorMessage ()) ((QDragLeaveEvent t1)) where
dragLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_dragLeaveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_dragLeaveEvent_h" qtc_QErrorMessage_dragLeaveEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQDragLeaveEvent t1) -> IO ()
instance QdragLeaveEvent (QErrorMessageSc a) ((QDragLeaveEvent t1)) where
dragLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_dragLeaveEvent_h cobj_x0 cobj_x1
instance QdragMoveEvent (QErrorMessage ()) ((QDragMoveEvent t1)) where
dragMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_dragMoveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_dragMoveEvent_h" qtc_QErrorMessage_dragMoveEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQDragMoveEvent t1) -> IO ()
instance QdragMoveEvent (QErrorMessageSc a) ((QDragMoveEvent t1)) where
dragMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_dragMoveEvent_h cobj_x0 cobj_x1
instance QdropEvent (QErrorMessage ()) ((QDropEvent t1)) where
dropEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_dropEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_dropEvent_h" qtc_QErrorMessage_dropEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQDropEvent t1) -> IO ()
instance QdropEvent (QErrorMessageSc a) ((QDropEvent t1)) where
dropEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_dropEvent_h cobj_x0 cobj_x1
instance QenabledChange (QErrorMessage ()) ((Bool)) where
enabledChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_enabledChange cobj_x0 (toCBool x1)
foreign import ccall "qtc_QErrorMessage_enabledChange" qtc_QErrorMessage_enabledChange :: Ptr (TQErrorMessage a) -> CBool -> IO ()
instance QenabledChange (QErrorMessageSc a) ((Bool)) where
enabledChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_enabledChange cobj_x0 (toCBool x1)
instance QenterEvent (QErrorMessage ()) ((QEvent t1)) where
enterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_enterEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_enterEvent_h" qtc_QErrorMessage_enterEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQEvent t1) -> IO ()
instance QenterEvent (QErrorMessageSc a) ((QEvent t1)) where
enterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_enterEvent_h cobj_x0 cobj_x1
instance QfocusInEvent (QErrorMessage ()) ((QFocusEvent t1)) where
focusInEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_focusInEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_focusInEvent_h" qtc_QErrorMessage_focusInEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent (QErrorMessageSc a) ((QFocusEvent t1)) where
focusInEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_focusInEvent_h cobj_x0 cobj_x1
instance QfocusNextChild (QErrorMessage ()) (()) where
focusNextChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_focusNextChild cobj_x0
foreign import ccall "qtc_QErrorMessage_focusNextChild" qtc_QErrorMessage_focusNextChild :: Ptr (TQErrorMessage a) -> IO CBool
instance QfocusNextChild (QErrorMessageSc a) (()) where
focusNextChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_focusNextChild cobj_x0
instance QfocusNextPrevChild (QErrorMessage ()) ((Bool)) where
focusNextPrevChild x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_focusNextPrevChild cobj_x0 (toCBool x1)
foreign import ccall "qtc_QErrorMessage_focusNextPrevChild" qtc_QErrorMessage_focusNextPrevChild :: Ptr (TQErrorMessage a) -> CBool -> IO CBool
instance QfocusNextPrevChild (QErrorMessageSc a) ((Bool)) where
focusNextPrevChild x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_focusNextPrevChild cobj_x0 (toCBool x1)
instance QfocusOutEvent (QErrorMessage ()) ((QFocusEvent t1)) where
focusOutEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_focusOutEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_focusOutEvent_h" qtc_QErrorMessage_focusOutEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent (QErrorMessageSc a) ((QFocusEvent t1)) where
focusOutEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_focusOutEvent_h cobj_x0 cobj_x1
instance QfocusPreviousChild (QErrorMessage ()) (()) where
focusPreviousChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_focusPreviousChild cobj_x0
foreign import ccall "qtc_QErrorMessage_focusPreviousChild" qtc_QErrorMessage_focusPreviousChild :: Ptr (TQErrorMessage a) -> IO CBool
instance QfocusPreviousChild (QErrorMessageSc a) (()) where
focusPreviousChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_focusPreviousChild cobj_x0
instance QfontChange (QErrorMessage ()) ((QFont t1)) where
fontChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_fontChange cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_fontChange" qtc_QErrorMessage_fontChange :: Ptr (TQErrorMessage a) -> Ptr (TQFont t1) -> IO ()
instance QfontChange (QErrorMessageSc a) ((QFont t1)) where
fontChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_fontChange cobj_x0 cobj_x1
instance QheightForWidth (QErrorMessage ()) ((Int)) where
heightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_heightForWidth_h cobj_x0 (toCInt x1)
foreign import ccall "qtc_QErrorMessage_heightForWidth_h" qtc_QErrorMessage_heightForWidth_h :: Ptr (TQErrorMessage a) -> CInt -> IO CInt
instance QheightForWidth (QErrorMessageSc a) ((Int)) where
heightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_heightForWidth_h cobj_x0 (toCInt x1)
instance QhideEvent (QErrorMessage ()) ((QHideEvent t1)) where
hideEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_hideEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_hideEvent_h" qtc_QErrorMessage_hideEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQHideEvent t1) -> IO ()
instance QhideEvent (QErrorMessageSc a) ((QHideEvent t1)) where
hideEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_hideEvent_h cobj_x0 cobj_x1
instance QinputMethodEvent (QErrorMessage ()) ((QInputMethodEvent t1)) where
inputMethodEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_inputMethodEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_inputMethodEvent" qtc_QErrorMessage_inputMethodEvent :: Ptr (TQErrorMessage a) -> Ptr (TQInputMethodEvent t1) -> IO ()
instance QinputMethodEvent (QErrorMessageSc a) ((QInputMethodEvent t1)) where
inputMethodEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_inputMethodEvent cobj_x0 cobj_x1
instance QinputMethodQuery (QErrorMessage ()) ((InputMethodQuery)) where
inputMethodQuery x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QErrorMessage_inputMethodQuery_h" qtc_QErrorMessage_inputMethodQuery_h :: Ptr (TQErrorMessage a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery (QErrorMessageSc a) ((InputMethodQuery)) where
inputMethodQuery x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1)
instance QkeyReleaseEvent (QErrorMessage ()) ((QKeyEvent t1)) where
keyReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_keyReleaseEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_keyReleaseEvent_h" qtc_QErrorMessage_keyReleaseEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent (QErrorMessageSc a) ((QKeyEvent t1)) where
keyReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_keyReleaseEvent_h cobj_x0 cobj_x1
instance QlanguageChange (QErrorMessage ()) (()) where
languageChange x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_languageChange cobj_x0
foreign import ccall "qtc_QErrorMessage_languageChange" qtc_QErrorMessage_languageChange :: Ptr (TQErrorMessage a) -> IO ()
instance QlanguageChange (QErrorMessageSc a) (()) where
languageChange x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_languageChange cobj_x0
instance QleaveEvent (QErrorMessage ()) ((QEvent t1)) where
leaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_leaveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_leaveEvent_h" qtc_QErrorMessage_leaveEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQEvent t1) -> IO ()
instance QleaveEvent (QErrorMessageSc a) ((QEvent t1)) where
leaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_leaveEvent_h cobj_x0 cobj_x1
instance Qmetric (QErrorMessage ()) ((PaintDeviceMetric)) where
metric x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_metric cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QErrorMessage_metric" qtc_QErrorMessage_metric :: Ptr (TQErrorMessage a) -> CLong -> IO CInt
instance Qmetric (QErrorMessageSc a) ((PaintDeviceMetric)) where
metric x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_metric cobj_x0 (toCLong $ qEnum_toInt x1)
instance QmouseDoubleClickEvent (QErrorMessage ()) ((QMouseEvent t1)) where
mouseDoubleClickEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_mouseDoubleClickEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_mouseDoubleClickEvent_h" qtc_QErrorMessage_mouseDoubleClickEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent (QErrorMessageSc a) ((QMouseEvent t1)) where
mouseDoubleClickEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_mouseDoubleClickEvent_h cobj_x0 cobj_x1
instance QmouseMoveEvent (QErrorMessage ()) ((QMouseEvent t1)) where
mouseMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_mouseMoveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_mouseMoveEvent_h" qtc_QErrorMessage_mouseMoveEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseMoveEvent (QErrorMessageSc a) ((QMouseEvent t1)) where
mouseMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_mouseMoveEvent_h cobj_x0 cobj_x1
instance QmousePressEvent (QErrorMessage ()) ((QMouseEvent t1)) where
mousePressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_mousePressEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_mousePressEvent_h" qtc_QErrorMessage_mousePressEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmousePressEvent (QErrorMessageSc a) ((QMouseEvent t1)) where
mousePressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_mousePressEvent_h cobj_x0 cobj_x1
instance QmouseReleaseEvent (QErrorMessage ()) ((QMouseEvent t1)) where
mouseReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_mouseReleaseEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_mouseReleaseEvent_h" qtc_QErrorMessage_mouseReleaseEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseReleaseEvent (QErrorMessageSc a) ((QMouseEvent t1)) where
mouseReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_mouseReleaseEvent_h cobj_x0 cobj_x1
instance Qmove (QErrorMessage ()) ((Int, Int)) where
move x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_move1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QErrorMessage_move1" qtc_QErrorMessage_move1 :: Ptr (TQErrorMessage a) -> CInt -> CInt -> IO ()
instance Qmove (QErrorMessageSc a) ((Int, Int)) where
move x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_move1 cobj_x0 (toCInt x1) (toCInt x2)
instance Qmove (QErrorMessage ()) ((Point)) where
move x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QErrorMessage_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y
foreign import ccall "qtc_QErrorMessage_move_qth" qtc_QErrorMessage_move_qth :: Ptr (TQErrorMessage a) -> CInt -> CInt -> IO ()
instance Qmove (QErrorMessageSc a) ((Point)) where
move x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QErrorMessage_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y
instance Qqmove (QErrorMessage ()) ((QPoint t1)) where
qmove x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_move cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_move" qtc_QErrorMessage_move :: Ptr (TQErrorMessage a) -> Ptr (TQPoint t1) -> IO ()
instance Qqmove (QErrorMessageSc a) ((QPoint t1)) where
qmove x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_move cobj_x0 cobj_x1
instance QmoveEvent (QErrorMessage ()) ((QMoveEvent t1)) where
moveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_moveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_moveEvent_h" qtc_QErrorMessage_moveEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQMoveEvent t1) -> IO ()
instance QmoveEvent (QErrorMessageSc a) ((QMoveEvent t1)) where
moveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_moveEvent_h cobj_x0 cobj_x1
instance QpaintEngine (QErrorMessage ()) (()) where
paintEngine x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_paintEngine_h cobj_x0
foreign import ccall "qtc_QErrorMessage_paintEngine_h" qtc_QErrorMessage_paintEngine_h :: Ptr (TQErrorMessage a) -> IO (Ptr (TQPaintEngine ()))
instance QpaintEngine (QErrorMessageSc a) (()) where
paintEngine x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_paintEngine_h cobj_x0
instance QpaintEvent (QErrorMessage ()) ((QPaintEvent t1)) where
paintEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_paintEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_paintEvent_h" qtc_QErrorMessage_paintEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQPaintEvent t1) -> IO ()
instance QpaintEvent (QErrorMessageSc a) ((QPaintEvent t1)) where
paintEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_paintEvent_h cobj_x0 cobj_x1
instance QpaletteChange (QErrorMessage ()) ((QPalette t1)) where
paletteChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_paletteChange cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_paletteChange" qtc_QErrorMessage_paletteChange :: Ptr (TQErrorMessage a) -> Ptr (TQPalette t1) -> IO ()
instance QpaletteChange (QErrorMessageSc a) ((QPalette t1)) where
paletteChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_paletteChange cobj_x0 cobj_x1
instance Qrepaint (QErrorMessage ()) (()) where
repaint x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_repaint cobj_x0
foreign import ccall "qtc_QErrorMessage_repaint" qtc_QErrorMessage_repaint :: Ptr (TQErrorMessage a) -> IO ()
instance Qrepaint (QErrorMessageSc a) (()) where
repaint x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_repaint cobj_x0
instance Qrepaint (QErrorMessage ()) ((Int, Int, Int, Int)) where
repaint x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QErrorMessage_repaint2" qtc_QErrorMessage_repaint2 :: Ptr (TQErrorMessage a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance Qrepaint (QErrorMessageSc a) ((Int, Int, Int, Int)) where
repaint x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
instance Qrepaint (QErrorMessage ()) ((QRegion t1)) where
repaint x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_repaint1 cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_repaint1" qtc_QErrorMessage_repaint1 :: Ptr (TQErrorMessage a) -> Ptr (TQRegion t1) -> IO ()
instance Qrepaint (QErrorMessageSc a) ((QRegion t1)) where
repaint x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_repaint1 cobj_x0 cobj_x1
instance QresetInputContext (QErrorMessage ()) (()) where
resetInputContext x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_resetInputContext cobj_x0
foreign import ccall "qtc_QErrorMessage_resetInputContext" qtc_QErrorMessage_resetInputContext :: Ptr (TQErrorMessage a) -> IO ()
instance QresetInputContext (QErrorMessageSc a) (()) where
resetInputContext x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_resetInputContext cobj_x0
instance Qresize (QErrorMessage ()) ((Int, Int)) (IO ()) where
resize x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_resize1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QErrorMessage_resize1" qtc_QErrorMessage_resize1 :: Ptr (TQErrorMessage a) -> CInt -> CInt -> IO ()
instance Qresize (QErrorMessageSc a) ((Int, Int)) (IO ()) where
resize x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_resize1 cobj_x0 (toCInt x1) (toCInt x2)
instance Qqresize (QErrorMessage ()) ((QSize t1)) where
qresize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_resize cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_resize" qtc_QErrorMessage_resize :: Ptr (TQErrorMessage a) -> Ptr (TQSize t1) -> IO ()
instance Qqresize (QErrorMessageSc a) ((QSize t1)) where
qresize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_resize cobj_x0 cobj_x1
instance Qresize (QErrorMessage ()) ((Size)) (IO ()) where
resize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QErrorMessage_resize_qth cobj_x0 csize_x1_w csize_x1_h
foreign import ccall "qtc_QErrorMessage_resize_qth" qtc_QErrorMessage_resize_qth :: Ptr (TQErrorMessage a) -> CInt -> CInt -> IO ()
instance Qresize (QErrorMessageSc a) ((Size)) (IO ()) where
resize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QErrorMessage_resize_qth cobj_x0 csize_x1_w csize_x1_h
instance QsetGeometry (QErrorMessage ()) ((Int, Int, Int, Int)) where
setGeometry x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QErrorMessage_setGeometry1" qtc_QErrorMessage_setGeometry1 :: Ptr (TQErrorMessage a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetGeometry (QErrorMessageSc a) ((Int, Int, Int, Int)) where
setGeometry x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
instance QqsetGeometry (QErrorMessage ()) ((QRect t1)) where
qsetGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_setGeometry cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_setGeometry" qtc_QErrorMessage_setGeometry :: Ptr (TQErrorMessage a) -> Ptr (TQRect t1) -> IO ()
instance QqsetGeometry (QErrorMessageSc a) ((QRect t1)) where
qsetGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_setGeometry cobj_x0 cobj_x1
instance QsetGeometry (QErrorMessage ()) ((Rect)) where
setGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QErrorMessage_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
foreign import ccall "qtc_QErrorMessage_setGeometry_qth" qtc_QErrorMessage_setGeometry_qth :: Ptr (TQErrorMessage a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetGeometry (QErrorMessageSc 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_QErrorMessage_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
instance QsetMouseTracking (QErrorMessage ()) ((Bool)) where
setMouseTracking x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_setMouseTracking cobj_x0 (toCBool x1)
foreign import ccall "qtc_QErrorMessage_setMouseTracking" qtc_QErrorMessage_setMouseTracking :: Ptr (TQErrorMessage a) -> CBool -> IO ()
instance QsetMouseTracking (QErrorMessageSc a) ((Bool)) where
setMouseTracking x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_setMouseTracking cobj_x0 (toCBool x1)
instance QtabletEvent (QErrorMessage ()) ((QTabletEvent t1)) where
tabletEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_tabletEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_tabletEvent_h" qtc_QErrorMessage_tabletEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQTabletEvent t1) -> IO ()
instance QtabletEvent (QErrorMessageSc a) ((QTabletEvent t1)) where
tabletEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_tabletEvent_h cobj_x0 cobj_x1
instance QupdateMicroFocus (QErrorMessage ()) (()) where
updateMicroFocus x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_updateMicroFocus cobj_x0
foreign import ccall "qtc_QErrorMessage_updateMicroFocus" qtc_QErrorMessage_updateMicroFocus :: Ptr (TQErrorMessage a) -> IO ()
instance QupdateMicroFocus (QErrorMessageSc a) (()) where
updateMicroFocus x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_updateMicroFocus cobj_x0
instance QwheelEvent (QErrorMessage ()) ((QWheelEvent t1)) where
wheelEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_wheelEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_wheelEvent_h" qtc_QErrorMessage_wheelEvent_h :: Ptr (TQErrorMessage a) -> Ptr (TQWheelEvent t1) -> IO ()
instance QwheelEvent (QErrorMessageSc a) ((QWheelEvent t1)) where
wheelEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_wheelEvent_h cobj_x0 cobj_x1
instance QwindowActivationChange (QErrorMessage ()) ((Bool)) where
windowActivationChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_windowActivationChange cobj_x0 (toCBool x1)
foreign import ccall "qtc_QErrorMessage_windowActivationChange" qtc_QErrorMessage_windowActivationChange :: Ptr (TQErrorMessage a) -> CBool -> IO ()
instance QwindowActivationChange (QErrorMessageSc a) ((Bool)) where
windowActivationChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_windowActivationChange cobj_x0 (toCBool x1)
instance QchildEvent (QErrorMessage ()) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_childEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_childEvent" qtc_QErrorMessage_childEvent :: Ptr (TQErrorMessage a) -> Ptr (TQChildEvent t1) -> IO ()
instance QchildEvent (QErrorMessageSc a) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_childEvent cobj_x0 cobj_x1
instance QconnectNotify (QErrorMessage ()) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QErrorMessage_connectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QErrorMessage_connectNotify" qtc_QErrorMessage_connectNotify :: Ptr (TQErrorMessage a) -> CWString -> IO ()
instance QconnectNotify (QErrorMessageSc a) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QErrorMessage_connectNotify cobj_x0 cstr_x1
instance QcustomEvent (QErrorMessage ()) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_customEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_customEvent" qtc_QErrorMessage_customEvent :: Ptr (TQErrorMessage a) -> Ptr (TQEvent t1) -> IO ()
instance QcustomEvent (QErrorMessageSc a) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_customEvent cobj_x0 cobj_x1
instance QdisconnectNotify (QErrorMessage ()) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QErrorMessage_disconnectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QErrorMessage_disconnectNotify" qtc_QErrorMessage_disconnectNotify :: Ptr (TQErrorMessage a) -> CWString -> IO ()
instance QdisconnectNotify (QErrorMessageSc a) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QErrorMessage_disconnectNotify cobj_x0 cstr_x1
instance Qreceivers (QErrorMessage ()) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QErrorMessage_receivers cobj_x0 cstr_x1
foreign import ccall "qtc_QErrorMessage_receivers" qtc_QErrorMessage_receivers :: Ptr (TQErrorMessage a) -> CWString -> IO CInt
instance Qreceivers (QErrorMessageSc a) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QErrorMessage_receivers cobj_x0 cstr_x1
instance Qsender (QErrorMessage ()) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_sender cobj_x0
foreign import ccall "qtc_QErrorMessage_sender" qtc_QErrorMessage_sender :: Ptr (TQErrorMessage a) -> IO (Ptr (TQObject ()))
instance Qsender (QErrorMessageSc a) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QErrorMessage_sender cobj_x0
instance QtimerEvent (QErrorMessage ()) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_timerEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QErrorMessage_timerEvent" qtc_QErrorMessage_timerEvent :: Ptr (TQErrorMessage a) -> Ptr (TQTimerEvent t1) -> IO ()
instance QtimerEvent (QErrorMessageSc a) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QErrorMessage_timerEvent cobj_x0 cobj_x1
| uduki/hsQt | Qtc/Gui/QErrorMessage.hs | bsd-2-clause | 46,961 | 0 | 14 | 7,372 | 14,857 | 7,534 | 7,323 | -1 | -1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QStyleOptionButton.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:15
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QStyleOptionButton (
QqStyleOptionButton(..)
,QqStyleOptionButton_nf(..)
,qStyleOptionButton_delete
)
where
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Gui.QStyleOptionButton
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
class QqStyleOptionButton x1 where
qStyleOptionButton :: x1 -> IO (QStyleOptionButton ())
instance QqStyleOptionButton (()) where
qStyleOptionButton ()
= withQStyleOptionButtonResult $
qtc_QStyleOptionButton
foreign import ccall "qtc_QStyleOptionButton" qtc_QStyleOptionButton :: IO (Ptr (TQStyleOptionButton ()))
instance QqStyleOptionButton ((QStyleOptionButton t1)) where
qStyleOptionButton (x1)
= withQStyleOptionButtonResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionButton1 cobj_x1
foreign import ccall "qtc_QStyleOptionButton1" qtc_QStyleOptionButton1 :: Ptr (TQStyleOptionButton t1) -> IO (Ptr (TQStyleOptionButton ()))
class QqStyleOptionButton_nf x1 where
qStyleOptionButton_nf :: x1 -> IO (QStyleOptionButton ())
instance QqStyleOptionButton_nf (()) where
qStyleOptionButton_nf ()
= withObjectRefResult $
qtc_QStyleOptionButton
instance QqStyleOptionButton_nf ((QStyleOptionButton t1)) where
qStyleOptionButton_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionButton1 cobj_x1
instance Qfeatures (QStyleOptionButton a) (()) (IO (ButtonFeatures)) where
features x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionButton_features cobj_x0
foreign import ccall "qtc_QStyleOptionButton_features" qtc_QStyleOptionButton_features :: Ptr (TQStyleOptionButton a) -> IO CLong
instance Qicon (QStyleOptionButton a) (()) (IO (QIcon ())) where
icon x0 ()
= withQIconResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionButton_icon cobj_x0
foreign import ccall "qtc_QStyleOptionButton_icon" qtc_QStyleOptionButton_icon :: Ptr (TQStyleOptionButton a) -> IO (Ptr (TQIcon ()))
instance QqiconSize (QStyleOptionButton a) (()) where
qiconSize x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionButton_iconSize cobj_x0
foreign import ccall "qtc_QStyleOptionButton_iconSize" qtc_QStyleOptionButton_iconSize :: Ptr (TQStyleOptionButton a) -> IO (Ptr (TQSize ()))
instance QiconSize (QStyleOptionButton a) (()) where
iconSize x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionButton_iconSize_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QStyleOptionButton_iconSize_qth" qtc_QStyleOptionButton_iconSize_qth :: Ptr (TQStyleOptionButton a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QsetFeatures (QStyleOptionButton a) ((ButtonFeatures)) where
setFeatures x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionButton_setFeatures cobj_x0 (toCLong $ qFlags_toInt x1)
foreign import ccall "qtc_QStyleOptionButton_setFeatures" qtc_QStyleOptionButton_setFeatures :: Ptr (TQStyleOptionButton a) -> CLong -> IO ()
instance QsetIcon (QStyleOptionButton a) ((QIcon t1)) where
setIcon x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionButton_setIcon cobj_x0 cobj_x1
foreign import ccall "qtc_QStyleOptionButton_setIcon" qtc_QStyleOptionButton_setIcon :: Ptr (TQStyleOptionButton a) -> Ptr (TQIcon t1) -> IO ()
instance QqsetIconSize (QStyleOptionButton a) ((QSize t1)) where
qsetIconSize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionButton_setIconSize cobj_x0 cobj_x1
foreign import ccall "qtc_QStyleOptionButton_setIconSize" qtc_QStyleOptionButton_setIconSize :: Ptr (TQStyleOptionButton a) -> Ptr (TQSize t1) -> IO ()
instance QsetIconSize (QStyleOptionButton a) ((Size)) where
setIconSize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QStyleOptionButton_setIconSize_qth cobj_x0 csize_x1_w csize_x1_h
foreign import ccall "qtc_QStyleOptionButton_setIconSize_qth" qtc_QStyleOptionButton_setIconSize_qth :: Ptr (TQStyleOptionButton a) -> CInt -> CInt -> IO ()
instance QsetText (QStyleOptionButton a) ((String)) where
setText x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QStyleOptionButton_setText cobj_x0 cstr_x1
foreign import ccall "qtc_QStyleOptionButton_setText" qtc_QStyleOptionButton_setText :: Ptr (TQStyleOptionButton a) -> CWString -> IO ()
instance Qtext (QStyleOptionButton a) (()) (IO (String)) where
text x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionButton_text cobj_x0
foreign import ccall "qtc_QStyleOptionButton_text" qtc_QStyleOptionButton_text :: Ptr (TQStyleOptionButton a) -> IO (Ptr (TQString ()))
qStyleOptionButton_delete :: QStyleOptionButton a -> IO ()
qStyleOptionButton_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionButton_delete cobj_x0
foreign import ccall "qtc_QStyleOptionButton_delete" qtc_QStyleOptionButton_delete :: Ptr (TQStyleOptionButton a) -> IO ()
| uduki/hsQt | Qtc/Gui/QStyleOptionButton.hs | bsd-2-clause | 5,615 | 0 | 12 | 800 | 1,465 | 754 | 711 | -1 | -1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE CPP #-}
#ifdef LANGUAGE_DeriveDataTypeable
{-# LANGUAGE DeriveDataTypeable #-}
#endif
#if __GLASGOW_HASKELL__ >= 706
{-# LANGUAGE PolyKinds #-}
#endif
#if __GLASGOW_HASKELL__ >= 702 && __GLASGOW_HASKELL__ < 710
{-# LANGUAGE Trustworthy #-}
#endif
----------------------------------------------------------------------------
-- |
-- Module : Data.Functor.Trans.Tagged
-- Copyright : 2011-2013 Edward Kmett
-- License : BSD3
--
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Stability : experimental
-- Portability : portable
--
-------------------------------------------------------------------------------
module Data.Functor.Trans.Tagged
(
-- * Tagged values
TaggedT(..), Tagged
, tag, tagT
, untag
, retag
, mapTaggedT
, reflected, reflectedM
, asTaggedTypeOf
, proxy, proxyT
, unproxy, unproxyT
, tagSelf, tagTSelf
, untagSelf, untagTSelf
, tagWith, tagTWith
, witness, witnessT
) where
#if defined(__GLASGOW_HASKELL__) && (__GLASGOW_HASKELL__ >= 706)
import Prelude hiding (foldr, foldl, mapM, sequence, foldr1, foldl1)
#else
import Prelude hiding (catch, foldr, foldl, mapM, sequence, foldr1, foldl1)
#endif
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative (Alternative(..), Applicative(..), (<$), (<$>))
#else
import Control.Applicative (Alternative(..))
#endif
import Control.Monad (liftM, MonadPlus(..))
import Control.Monad.Catch (MonadCatch(..), MonadThrow(..), MonadMask(..))
import Control.Monad.Fix (MonadFix(..))
import Control.Monad.Identity (Identity, runIdentity)
import Control.Monad.Trans (MonadIO(..), MonadTrans(..))
import Control.Monad.Reader (MonadReader(..))
import Control.Monad.Writer (MonadWriter(..))
import Control.Monad.State (MonadState(..))
import Control.Monad.Cont (MonadCont(..))
import Control.Comonad.Trans.Class (ComonadTrans(..))
import Control.Comonad.Hoist.Class (ComonadHoist(..))
import Control.Comonad (Comonad(..))
import Data.Traversable (Traversable(..))
import Data.Typeable
import Data.Foldable (Foldable(..))
import Data.Distributive (Distributive(..))
import Data.Functor.Bind (Apply(..), Bind(..))
import Data.Functor.Extend (Extend(..))
import Data.Functor.Plus (Alt(..), Plus(..))
import Data.Functor.Contravariant (Contravariant(..))
#if !(defined(__GLASGOW_HASKELL__)) || __GLASGOW_HASKELL__ < 707
import Data.Proxy (Proxy(..))
#endif
import Data.Reflection (Reifies(..))
-- ---------------------------------------------------------------------------
-- | A @'Tagged' s b@ value is a value @b@ with an attached phantom type @s@.
-- This can be used in place of the more traditional but less safe idiom of
-- passing in an undefined value with the type, because unlike an @(s -> b)@,
-- a @'Tagged' s b@ can't try to use the argument @s@ as a real value.
--
-- Moreover, you don't have to rely on the compiler to inline away the extra
-- argument, because the newtype is \"free\"
type Tagged s b = TaggedT s Identity b
-- | Tag a value in Identity monad
tag :: b -> Tagged s b
tag = TagT . return
{-# INLINE tag #-}
-- | Untag a value in Identity monad
untag :: Tagged s b -> b
untag = runIdentity . untagT
{-# INLINE untag #-}
-- | Convert from a 'Tagged' representation to a representation
-- based on a 'Proxy'.
proxy :: Tagged s b -> Proxy s -> b
proxy x _ = untag x
{-# INLINE proxy #-}
-- | Convert from a representation based on a 'Proxy' to a 'Tagged'
-- representation.
unproxy :: (Proxy s -> a) -> Tagged s a
unproxy f = TagT (return $ f Proxy)
{-# INLINE unproxy #-}
-- | Tag a value with its own type.
tagSelf :: a -> Tagged a a
tagSelf = TagT . return
{-# INLINE tagSelf #-}
-- | 'untagSelf' is a type-restricted version of 'untag'.
untagSelf :: Tagged a a -> a
untagSelf = untag
{-# INLINE untagSelf #-}
-- | Another way to convert a proxy to a tag.
tagWith :: proxy s -> a -> Tagged s a
tagWith _ = TagT . return
{-# INLINE tagWith #-}
witness :: Tagged a b -> a -> b
witness x _ = untag x
{-# INLINE witness #-}
-- ---------------------------------------------------------------------------
-- | A Tagged monad parameterized by:
--
-- * @s@ - the phantom type
--
-- * @m@ - the inner monad
--
-- * @b@ - the tagged value
--
-- | A @'TaggedT' s m b@ value is a monadic value @m b@ with an attached phantom type @s@.
-- This can be used in place of the more traditional but less safe idiom of
-- passing in an undefined value with the type, because unlike an @(s -> m b)@,
-- a @'TaggedT' s m b@ can't try to use the argument @s@ as a real value.
--
-- Moreover, you don't have to rely on the compiler to inline away the extra
-- argument, because the newtype is \"free\"
newtype TaggedT s m b = TagT { untagT :: m b }
deriving ( Eq, Ord, Read, Show
#if __GLASGOW_HASKELL__ >= 707
, Typeable
#endif
)
instance Functor m => Functor (TaggedT s m) where
fmap f (TagT x) = TagT (fmap f x)
{-# INLINE fmap #-}
b <$ (TagT x) = TagT (b <$ x)
{-# INLINE (<$) #-}
instance Contravariant m => Contravariant (TaggedT s m) where
contramap f (TagT x) = TagT (contramap f x)
{-# INLINE contramap #-}
instance Apply m => Apply (TaggedT s m) where
TagT f <.> TagT x = TagT (f <.> x)
{-# INLINE (<.>) #-}
TagT f .> TagT x = TagT (f .> x)
{-# INLINE ( .>) #-}
TagT f <. TagT x = TagT (f <. x)
{-# INLINE (<. ) #-}
instance Applicative m => Applicative (TaggedT s m) where
pure = TagT . pure
{-# INLINE pure #-}
TagT f <*> TagT x = TagT (f <*> x)
{-# INLINE (<*>) #-}
TagT f *> TagT x = TagT (f *> x)
{-# INLINE ( *>) #-}
TagT f <* TagT x = TagT (f <* x)
{-# INLINE (<* ) #-}
instance Bind m => Bind (TaggedT s m) where
TagT m >>- k = TagT (m >>- untagT . k)
{-# INLINE (>>-) #-}
instance Monad m => Monad (TaggedT s m) where
TagT m >>= k = TagT (m >>= untagT . k)
{-# INLINE (>>=) #-}
#if !(MIN_VERSION_base(4,11,0))
return = TagT . return
{-# INLINE return #-}
TagT m >> TagT n = TagT (m >> n)
{-# INLINE (>>) #-}
#endif
instance Alt m => Alt (TaggedT s m) where
TagT a <!> TagT b = TagT (a <!> b)
{-# INLINE (<!>) #-}
instance Alternative m => Alternative (TaggedT s m) where
empty = TagT empty
{-# INLINE empty #-}
TagT a <|> TagT b = TagT (a <|> b)
{-# INLINE (<|>) #-}
instance Plus m => Plus (TaggedT s m) where
zero = TagT zero
{-# INLINE zero #-}
instance MonadPlus m => MonadPlus (TaggedT s m) where
mzero = TagT mzero
{-# INLINE mzero #-}
mplus (TagT a) (TagT b) = TagT (mplus a b)
{-# INLINE mplus #-}
instance MonadFix m => MonadFix (TaggedT s m) where
mfix f = TagT $ mfix (untagT . f)
{-# INLINE mfix #-}
instance MonadTrans (TaggedT s) where
lift = TagT
{-# INLINE lift #-}
instance MonadIO m => MonadIO (TaggedT s m) where
liftIO = lift . liftIO
{-# INLINE liftIO #-}
instance MonadWriter w m => MonadWriter w (TaggedT s m) where
#if MIN_VERSION_mtl(2,1,0)
writer = lift . writer
{-# INLINE writer #-}
#endif
tell = lift . tell
{-# INLINE tell #-}
listen = lift . listen . untagT
{-# INLINE listen #-}
pass = lift . pass . untagT
{-# INLINE pass #-}
instance MonadReader r m => MonadReader r (TaggedT s m) where
ask = lift ask
{-# INLINE ask #-}
local f = lift . local f . untagT
{-# INLINE local #-}
#if MIN_VERSION_mtl(2,1,0)
reader = lift . reader
{-# INLINE reader #-}
#endif
instance MonadState t m => MonadState t (TaggedT s m) where
get = lift get
{-# INLINE get #-}
put = lift . put
{-# INLINE put #-}
#if MIN_VERSION_mtl(2,1,0)
state = lift . state
{-# INLINE state #-}
#endif
instance MonadCont m => MonadCont (TaggedT s m) where
callCC f = lift . callCC $ \k -> untagT (f (TagT . k))
{-# INLINE callCC #-}
instance Foldable f => Foldable (TaggedT s f) where
foldMap f (TagT x) = foldMap f x
{-# INLINE foldMap #-}
fold (TagT x) = fold x
{-# INLINE fold #-}
foldr f z (TagT x) = foldr f z x
{-# INLINE foldr #-}
foldl f z (TagT x) = foldl f z x
{-# INLINE foldl #-}
foldl1 f (TagT x) = foldl1 f x
{-# INLINE foldl1 #-}
foldr1 f (TagT x) = foldr1 f x
{-# INLINE foldr1 #-}
instance Traversable f => Traversable (TaggedT s f) where
traverse f (TagT x) = TagT <$> traverse f x
{-# INLINE traverse #-}
sequenceA (TagT x) = TagT <$> sequenceA x
{-# INLINE sequenceA #-}
mapM f (TagT x) = liftM TagT (mapM f x)
{-# INLINE mapM #-}
sequence (TagT x) = liftM TagT (sequence x)
{-# INLINE sequence #-}
instance Distributive f => Distributive (TaggedT s f) where
distribute = TagT . distribute . fmap untagT
{-# INLINE distribute #-}
instance Extend f => Extend (TaggedT s f) where
extended f (TagT w) = TagT (extended (f . TagT) w)
{-# INLINE extended #-}
instance Comonad w => Comonad (TaggedT s w) where
extract (TagT w) = extract w
{-# INLINE extract #-}
duplicate (TagT w) = TagT (extend TagT w)
{-# INLINE duplicate #-}
instance ComonadTrans (TaggedT s) where
lower (TagT w) = w
{-# INLINE lower #-}
instance ComonadHoist (TaggedT s) where
cohoist f = TagT . f . untagT
{-# INLINE cohoist #-}
instance MonadThrow m => MonadThrow (TaggedT s m) where
throwM e = lift $ throwM e
{-# INLINE throwM #-}
instance MonadCatch m => MonadCatch (TaggedT s m) where
catch m f = TagT (catch (untagT m) (untagT . f))
{-# INLINE catch #-}
instance MonadMask m => MonadMask (TaggedT s m) where
mask a = TagT $ mask $ \u -> untagT (a $ q u)
where q u = TagT . u . untagT
{-# INLINE mask #-}
uninterruptibleMask a = TagT $ uninterruptibleMask $ \u -> untagT (a $ q u)
where q u = TagT . u . untagT
{-# INLINE uninterruptibleMask#-}
#if MIN_VERSION_exceptions(0,10,0)
generalBracket acquire release use = TagT $
generalBracket
(untagT acquire)
(\resource exitCase -> untagT (release resource exitCase))
(\resource -> untagT (use resource))
#endif
-- | Easier to type alias for 'TagT'
tagT :: m b -> TaggedT s m b
tagT = TagT
{-# INLINE tagT #-}
-- | Some times you need to change the tag you have lying around.
-- Idiomatic usage is to make a new combinator for the relationship between the
-- tags that you want to enforce, and define that combinator using 'retag'.
--
-- > data Succ n
-- > retagSucc :: Tagged n a -> Tagged (Succ n) a
-- > retagSucc = retag
retag :: TaggedT s m b -> TaggedT t m b
retag = TagT . untagT
{-# INLINE retag #-}
-- | Lift an operation on underlying monad
mapTaggedT :: (m a -> n b) -> TaggedT s m a -> TaggedT s n b
mapTaggedT f = TagT . f . untagT
{-# INLINE mapTaggedT #-}
-- | Reflect reified value back in 'Applicative' context
reflected :: forall s m a. (Applicative m, Reifies s a) => TaggedT s m a
reflected = TagT . pure . reflect $ (Proxy :: Proxy s)
{-# INLINE reflected #-}
-- | Reflect reified value back in 'Monad' context
reflectedM :: forall s m a. (Monad m, Reifies s a) => TaggedT s m a
reflectedM = TagT . return . reflect $ (Proxy :: Proxy s)
{-# INLINE reflectedM #-}
-- | 'asTaggedTypeOf' is a type-restricted version of 'const'. It is usually used as an infix operator, and its typing forces its first argument (which is usually overloaded) to have the same type as the tag of the second.
asTaggedTypeOf :: s -> TaggedT s m b -> s
asTaggedTypeOf = const
{-# INLINE asTaggedTypeOf #-}
-- | Convert from a 'TaggedT' representation to a representation
-- based on a 'Proxy'.
proxyT :: TaggedT s m b -> Proxy s -> m b
proxyT x _ = untagT x
{-# INLINE proxyT #-}
-- | Convert from a representation based on a 'Proxy' to a 'TaggedT'
-- representation.
unproxyT :: (Proxy s -> m a) -> TaggedT s m a
unproxyT f = TagT (f Proxy)
{-# INLINE unproxyT #-}
-- | Tag a value with its own type.
tagTSelf :: m a -> TaggedT a m a
tagTSelf = TagT
{-# INLINE tagTSelf #-}
-- | 'untagSelf' is a type-restricted version of 'untag'.
untagTSelf :: TaggedT a m a -> m a
untagTSelf = untagT
{-# INLINE untagTSelf #-}
-- | Another way to convert a proxy to a tag.
tagTWith :: proxy s -> m a -> TaggedT s m a
tagTWith _ = TagT
{-# INLINE tagTWith #-}
witnessT :: TaggedT a m b -> a -> m b
witnessT x _ = untagT x
{-# INLINE witnessT #-}
| ekmett/tagged-transformer | src/Data/Functor/Trans/Tagged.hs | bsd-2-clause | 12,208 | 0 | 12 | 2,496 | 3,225 | 1,758 | 1,467 | -1 | -1 |
-- |
-- Module : $Header$
-- Copyright : (c) 2013-2014 Galois, Inc.
-- License : BSD3
-- Maintainer : cryptol@galois.com
-- Stability : provisional
-- Portability : portable
module Cryptol.ModuleSystem.NamingEnv where
import Cryptol.ModuleSystem.Interface
import Cryptol.Parser.AST
import Cryptol.Parser.Names (namesP)
import Cryptol.Parser.Position
import qualified Cryptol.TypeCheck.AST as T
import Cryptol.Utils.PP
import Cryptol.Utils.Panic (panic)
import Data.Monoid (Monoid(..))
import Data.Foldable (foldMap)
import qualified Data.Map as Map
-- Name Locations --------------------------------------------------------------
data NameOrigin = Local (Located QName)
| Imported QName
deriving (Show)
instance PP NameOrigin where
ppPrec _ o = case o of
Local lqn -> pp lqn
Imported (QName m n) -> pp n <+> trailer
where
trailer = case m of
Just mn -> text "from module" <+> pp mn
_ -> empty
-- Names -----------------------------------------------------------------------
data EName = EFromBind (Located QName)
| EFromNewtype (Located QName)
| EFromMod QName
deriving (Show)
data TName = TFromParam QName
| TFromSyn (Located QName)
| TFromNewtype (Located QName)
| TFromMod QName
deriving (Show)
class HasQName a where
qname :: a -> QName
origin :: a -> NameOrigin
instance HasQName TName where
qname tn = case tn of
TFromParam qn -> qn
TFromSyn lqn -> thing lqn
TFromNewtype lqn -> thing lqn
TFromMod qn -> qn
origin tn = case tn of
TFromParam qn -> Local Located { srcRange = emptyRange, thing = qn }
TFromSyn lqn -> Local lqn
TFromNewtype lqn -> Local lqn
TFromMod qn -> Imported qn
instance HasQName EName where
qname en = case en of
EFromBind lqn -> thing lqn
EFromNewtype lqn -> thing lqn
EFromMod qn -> qn
origin en = case en of
EFromBind lqn -> Local lqn
EFromNewtype lqn -> Local lqn
EFromMod qn -> Imported qn
-- Naming Environment ----------------------------------------------------------
data NamingEnv = NamingEnv { neExprs :: Map.Map QName [EName]
-- ^ Expr renaming environment
, neTypes :: Map.Map QName [TName]
-- ^ Type renaming environment
} deriving (Show)
instance Monoid NamingEnv where
mempty =
NamingEnv { neExprs = Map.empty
, neTypes = Map.empty }
mappend l r =
NamingEnv { neExprs = Map.unionWith (++) (neExprs l) (neExprs r)
, neTypes = Map.unionWith (++) (neTypes l) (neTypes r) }
mconcat envs =
NamingEnv { neExprs = Map.unionsWith (++) (map neExprs envs)
, neTypes = Map.unionsWith (++) (map neTypes envs) }
-- | Singleton type renaming environment.
singletonT :: QName -> TName -> NamingEnv
singletonT qn tn = mempty { neTypes = Map.singleton qn [tn] }
-- | Singleton expression renaming environment.
singletonE :: QName -> EName -> NamingEnv
singletonE qn en = mempty { neExprs = Map.singleton qn [en] }
-- | Like mappend, but when merging, prefer values on the lhs.
shadowing :: NamingEnv -> NamingEnv -> NamingEnv
shadowing l r = NamingEnv
{ neExprs = Map.union (neExprs l) (neExprs r)
, neTypes = Map.union (neTypes l) (neTypes r) }
-- | Things that define exported names.
class BindsNames a where
namingEnv :: a -> NamingEnv
instance BindsNames NamingEnv where
namingEnv = id
instance BindsNames a => BindsNames (Maybe a) where
namingEnv = foldMap namingEnv
instance BindsNames a => BindsNames [a] where
namingEnv = foldMap namingEnv
-- | Generate a type renaming environment from the parameters that are bound by
-- this schema.
instance BindsNames Schema where
namingEnv (Forall ps _ _ _) = foldMap namingEnv ps
-- | Produce a naming environment from an interface file, that contains a
-- mapping only from unqualified names to qualified ones.
instance BindsNames Iface where
namingEnv = namingEnv . ifPublic
-- | Translate a set of declarations from an interface into a naming
-- environment.
instance BindsNames IfaceDecls where
namingEnv binds = mconcat [ types, newtypes, vars ]
where
types = mempty
{ neTypes = Map.map (map (TFromMod . ifTySynName)) (ifTySyns binds)
}
newtypes = mempty
{ neTypes = Map.map (map (TFromMod . T.ntName)) (ifNewtypes binds)
, neExprs = Map.map (map (EFromMod . T.ntName)) (ifNewtypes binds)
}
vars = mempty
{ neExprs = Map.map (map (EFromMod . ifDeclName)) (ifDecls binds)
}
-- | Translate names bound by the patterns of a match into a renaming
-- environment.
instance BindsNames Match where
namingEnv m = case m of
Match p _ -> namingEnv p
MatchLet b -> namingEnv b
instance BindsNames Bind where
namingEnv b = singletonE (thing qn) (EFromBind qn)
where
qn = bName b
-- | Generate the naming environment for a type parameter.
instance BindsNames TParam where
namingEnv p = singletonT qn (TFromParam qn)
where
qn = mkUnqual (tpName p)
-- | Generate an expression renaming environment from a pattern. This ignores
-- type parameters that can be bound by the pattern.
instance BindsNames Pattern where
namingEnv p = foldMap unqualBind (namesP p)
where
unqualBind qn = singletonE (thing qn) (EFromBind qn)
-- | The naming environment for a single module. This is the mapping from
-- unqualified internal names to fully qualified names.
instance BindsNames Module where
namingEnv m = foldMap topDeclEnv (mDecls m)
where
topDeclEnv td = case td of
Decl d -> declEnv (tlValue d)
TDNewtype n -> newtypeEnv (tlValue n)
Include _ -> mempty
qual = fmap (\qn -> mkQual (thing (mName m)) (unqual qn))
qualBind ln = singletonE (thing ln) (EFromBind (qual ln))
qualType ln = singletonT (thing ln) (TFromSyn (qual ln))
declEnv d = case d of
DSignature ns _sig -> foldMap qualBind ns
DPragma ns _p -> foldMap qualBind ns
DBind b -> qualBind (bName b)
DPatBind _pat _e -> panic "ModuleSystem" ["Unexpected pattern binding"]
DType (TySyn lqn _ _) -> qualType lqn
DLocated d' _ -> declEnv d'
newtypeEnv n = singletonT (thing qn) (TFromNewtype (qual qn))
`mappend` singletonE (thing qn) (EFromNewtype (qual qn))
where
qn = nName n
-- | The naming environment for a single declaration, unqualified. This is
-- meanat to be used for things like where clauses.
instance BindsNames Decl where
namingEnv d = case d of
DSignature ns _sig -> foldMap qualBind ns
DPragma ns _p -> foldMap qualBind ns
DBind b -> qualBind (bName b)
DPatBind _pat _e -> panic "ModuleSystem" ["Unexpected pattern binding"]
DType (TySyn lqn _ _) -> qualType lqn
DLocated d' _ -> namingEnv d'
where
qualBind ln = singletonE (thing ln) (EFromBind ln)
qualType ln = singletonT (thing ln) (TFromSyn ln)
| dylanmc/cryptol | src/Cryptol/ModuleSystem/NamingEnv.hs | bsd-3-clause | 7,203 | 0 | 15 | 1,897 | 2,009 | 1,032 | 977 | 137 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.