code
stringlengths 2
1.05M
| repo_name
stringlengths 5
101
| path
stringlengths 4
991
| language
stringclasses 3
values | license
stringclasses 5
values | size
int64 2
1.05M
|
|---|---|---|---|---|---|
module Language.Ptlish.Simplify (simplify) where
import Language.Ptlish.AST
import Control.Monad.State
import qualified Data.Map as Map
import Data.Maybe
type SimplifyM = State SimplifyState
data SimplifyState = SimplifyState {
stNextExprId :: Int,
stExtra :: [(Name,Expr)],
stExprMap :: Map.Map Expr Name,
stScope :: Map.Map Name Expr
}
initState :: SimplifyState
initState = SimplifyState 1 [] Map.empty Map.empty
simplify :: Ptlish -> Ptlish
simplify ptl = let (v, s) = runState (simplify' ptl) initState in
[ (Def n e) | (n,e) <- reverse $ stExtra s ] ++ v
simplify' :: [Stmt] -> SimplifyM [Stmt]
simplify' = (fmap catMaybes) . mapM simplifyStmt
notLambda :: Expr -> Bool
notLambda (LambdaExpr _ _) = False
notLambda _ = True
simplifyStmt :: Stmt -> SimplifyM (Maybe Stmt)
simplifyStmt (Def n e) = do
e' <- simplifyExpr e
s <- get
put $ s { stScope = Map.insert n e (stScope s) }
return $ if notLambda e'
then Just $ (Def n e')
else Nothing
simplifyStmt (Trigger n as) = do
as' <- mapM simplifyAction as
return $ Just $ Trigger n as'
simplifyAction :: Action -> SimplifyM Action
simplifyAction (Action n exprs) = do
exprs' <- mapM simplifyExpr exprs
return $ Action n exprs'
simplifyExpr :: Expr -> SimplifyM Expr
simplifyExpr (UnExpr op e) = do
e' <- simplifyExpr e
matchExpr (UnExpr op e')
simplifyExpr (BinExpr op e1 e2) = do
e1' <- simplifyExpr e1
e2' <- simplifyExpr e2
matchExpr (BinExpr op e1' e2')
simplifyExpr ce@(ConstExpr _) = do
return ce
simplifyExpr (IfExpr i t e) = do
i' <- simplifyExpr i
t' <- simplifyExpr t
e' <- simplifyExpr e
matchExpr (IfExpr i' t' e')
simplifyExpr ve@(VarExpr v e) = do
e' <- simplifyExpr e
return $ VarExpr v e'
simplifyExpr re@(RefExpr _) = do
e <- normalize re
simplifyExpr e
simplifyExpr ue@(UnboundExpr _) = return ue
simplifyExpr ae@(ApplyExpr _ _) = do
ae' <- normalize ae
simplifyExpr ae'
simplifyExpr le@(LambdaExpr n e) = do
e' <- normalize e
matchExpr (LambdaExpr n e')
matchExpr :: Expr -> SimplifyM Expr
matchExpr e = do
s <- get
case Map.lookup e (stExprMap s) of
Just n -> return $ RefExpr n
Nothing -> if notLambda e
then do
let n = "_" ++ (show $ stNextExprId s)
put $ s {
stExprMap = Map.insert e n (stExprMap s),
stScope = Map.insert n e (stScope s),
stNextExprId = stNextExprId s + 1,
stExtra = (n,e):stExtra s
}
return $ RefExpr n
else return e
normalize :: Expr -> SimplifyM Expr
normalize (UnExpr op e) = do
e' <- normalize e
return $ UnExpr op e'
normalize (BinExpr op e1 e2) = do
e1' <- normalize e1
e2' <- normalize e2
return $ BinExpr op e1' e2'
normalize (ConstExpr i) = return $ ConstExpr i
normalize (IfExpr i t e) = do
i' <- normalize i
t' <- normalize t
e' <- normalize e
return $ IfExpr i' t' e'
normalize (VarExpr n e) = do
e' <- normalize e
return $ VarExpr n e'
normalize (RefExpr n) = do
s <- get
case Map.lookup n (stScope s) of
Just e -> normalize e
Nothing -> fail $ "Reference to undeclared identifier: " ++ n
normalize u@(UnboundExpr n) = return u
normalize (ApplyExpr e1 e2) = do
e1' <- normalize e1
e2' <- normalize e2
apply e1' e2'
normalize (LambdaExpr n e) = do
e' <- normalize e
return $ LambdaExpr n e'
apply :: Expr -> Expr -> SimplifyM Expr
apply (LambdaExpr n e1) e2 = bind n e2 e1
apply e _ = fail $ "Cannot apply:" ++ (show e)
bind :: Name -> Expr -> Expr -> SimplifyM Expr
bind n be (UnExpr op e) = do
e' <- bind n be e
return $ UnExpr op e'
bind n be (BinExpr op e1 e2) = do
e1' <- bind n be e1
e2' <- bind n be e2
return $ BinExpr op e1' e2'
bind _ _ ce@(ConstExpr _) = return $ ce
bind n be (IfExpr i t e) = do
i' <- bind n be i
t' <- bind n be t
e' <- bind n be e
return $ IfExpr i' t' e'
bind n be (VarExpr vn e) = do
e' <- bind n be e
return $ VarExpr vn e'
bind n be re@(RefExpr en) = return $ re
bind n be ue@(UnboundExpr n') = return $ if n == n' then be else ue
bind n be ae@(ApplyExpr _ _) = fail $ "Apply not allowed when binding: " ++ (show ae)
bind n be le@(LambdaExpr n' e) = do
e' <- bind n be e
return $ if n == n' then le else LambdaExpr n' e'
|
tlaitinen/ptlish
|
Language/Ptlish/Simplify.hs
|
Haskell
|
bsd-2-clause
| 4,544
|
{-# LANGUAGE OverloadedStrings #-}
import System.Directory
import System.Time
import System.IO
import qualified Data.List as L
import Text.ParserCombinators.Parsec
import Text.Blaze.Html5 as H
import Text.Blaze.Html5.Attributes as A
import Text.Blaze.Html.Renderer.Pretty
import qualified Text.Blaze.Internal as I
import Text.Pandoc
import Text.Pandoc.Readers.Markdown
import Control.Monad
data Entry = Entry {
entryUrl :: String,
entryDate :: CalendarTime,
entryTitle :: String,
entryTags :: String,
entryBody :: String}
deriving (Eq, Show)
instance Ord Entry where
compare e1 e2 = compare (entryDate e1) (entryDate e2)
metadata :: String -> Parser String
metadata s = do
string ("<!--- " ++ s ++ ": ")
manyTill anyChar (try (string " -->"))
entryParser :: Parser [String]
entryParser = do
u <- metadata "url"
spaces
d <- metadata "date"
spaces
ti <- metadata "title"
spaces
ta <- metadata "tags"
spaces
b <- manyTill anyChar eof
return [u, d, ti, ta, b]
dateParser :: Parser CalendarTime
dateParser = do
d <- manyTill digit (char '/')
m <- manyTill digit (char '/')
y <- many digit
let defaultDate = CalendarTime 2012 January 1 0 0 0 0 Sunday 0 "GMT" 0 False
let dt = defaultDate {ctYear = 2000 + read y
, ctMonth = toEnum (read m - 1)
, ctDay = read d}
return $ toUTCTime $ toClockTime dt
date :: String -> CalendarTime
date s = case parse dateParser "Error parsing date string" s of
Left e -> error $ show e
Right d -> d
ymd :: CalendarTime -> String
ymd cal = let yyyy = show $ ctYear cal
m = show (1 + (fromEnum $ ctMonth cal))
d = show $ ctDay cal
mm = if L.length m == 1 then '0' : m else m
dd = if L.length d == 1 then '0' : d else d
in yyyy ++ "-" ++ mm ++ "-" ++ dd
rfc882 :: Entry -> String
rfc882 e = let cal = entryDate e
dow = (take 3 $ show $ ctWDay cal) ++ ", "
day = (show $ ctDay cal) ++ " "
mon = (take 3 $ show $ ctMonth cal) ++ " "
year = (show $ ctYear cal) ++ " "
in dow ++ day ++ mon ++ year ++ "20:00:00 GMT"
expireDate :: Entry -> String
expireDate e = let cal = entryDate e
cty = ctYear cal
d = cal {ctYear = cty + 1}
in rfc882 $ e {entryDate = d}
publishedOn :: Entry -> String
publishedOn e = let cal = entryDate e
month = (show $ ctMonth cal) ++ " "
day = (show $ ctDay cal) ++ ", "
year = show $ ctYear cal
in month ++ day ++ year
absoluteUrl :: Entry -> String
absoluteUrl e = "http://www.adrienhaxaire.org/" ++ entryUrl e ++ ".html"
entry :: String -> Entry
entry s = case parse entryParser "Error in entry string" s of
Left e -> error $ show e
Right [u, d, ti, ta, b] -> Entry u (date d) ti ta (markdownToHtml b)
markdownToHtml :: String -> String
markdownToHtml s = let md = readMarkdown defaultParserState {stateStrict = True} s
in writeHtmlString defaultWriterOptions md
htmlHead :: String -> Markup
htmlHead t = do
H.head $ do
meta ! httpEquiv "content-type" ! content "text/html; charset=UTF-8"
meta ! name "google-site-verification" ! content "6vhHz6JpHz2tcB6ElSHx7ev3bzmZo-skd2iRRHiwCjw"
meta ! name "keywords" ! content "adrien haxaire, adrienhaxaire, existence et applications"
link ! type_ "text/css" ! rel "stylesheet" ! media "all" ! href "base.css"
H.title $ toHtml ("Existence et Applications" ++ t)
entryHead :: Entry -> Markup
entryHead e = do
H.head $ do
meta ! httpEquiv "content-type" ! content "text/html; charset=UTF-8"
meta ! httpEquiv "Last-Modified" ! content (toValue $ show $ rfc882 e)
meta ! httpEquiv "expires" ! content (toValue $ show $ expireDate e)
meta ! name "google-site-verification" ! content "6vhHz6JpHz2tcB6ElSHx7ev3bzmZo-skd2iRRHiwCjw"
meta ! name "keywords" ! content "adrien haxaire, adrienhaxaire, existence et applications"
meta ! name "keywords" ! content (toValue $ show $ entryTitle e)
meta ! name "keywords" ! content (toValue $ show $ entryTags e)
link ! type_ "text/css" ! rel "stylesheet" ! media "all" ! href "base.css"
H.title $ toHtml ("Existence et Applications | " ++ entryTitle e)
htmlBody :: Html -> Markup
htmlBody contents = H.body $ do
entete
contents
htmlFooter
googleAnalytics
entete :: Markup
entete = do
H.div ! A.id "entete" $ do
h1 $ a ! href "/" $ "Existence et Applications"
H.div ! A.id "nav" $ do
a ! href "/" $ "home"
a ! href "archive.html" $ "archive"
a ! href "rss.xml" $ "rss"
a ! href "about.html" $ "about"
htmlTemplate :: String -> Html -> Html
htmlTemplate pageTitle contents = docTypeHtml ! lang "en" $ do
htmlHead pageTitle
htmlBody contents
entryTemplate :: Entry -> Html
entryTemplate e = docTypeHtml ! lang "en" $ do
entryHead e
htmlBody $ entryContents e
entryContents :: Entry -> Html
entryContents e = do
H.div ! A.id "contents" ! A.class_ "container" $ I.preEscapedString (entryBody e ++ "\n<p> " ++ publishedOn e ++ "</p>\n")
comments e
markdownEntries :: IO [String]
markdownEntries = do
es <- getDirectoryContents "entries/"
return $ L.map (\x -> "entries/" ++ x) (filterMarkdown es)
where
filterMarkdown = L.delete "." . L.delete ".." . L.filter (L.isSuffixOf ".md")
writeEntry :: Entry -> IO ()
writeEntry e = writeFile filename (renderHtml $ entryTemplate e)
where
filename = "public/" ++ entryUrl e ++ ".html"
entries :: IO [Entry]
entries = liftM (L.map entry) (markdownEntries >>= mapM readFile)
updateEntries :: [Entry] -> IO ()
updateEntries = mapM_ writeEntry
updateIndex :: [Entry] -> IO ()
updateIndex es = let filename = "public/index.html"
contents = entryContents $ maximum es
in writeFile filename (renderHtml $ htmlTemplate "" contents)
updateArchive :: [Entry] -> IO ()
updateArchive es = let filename = "public/archive.html"
contents = archiveContents es
in writeFile filename (renderHtml $ htmlTemplate " | Archive" contents)
archiveContents :: [Entry] -> Html
archiveContents es = let ses = reverse $ L.sort es
in do
H.div ! A.id "contents" ! A.class_ "container" $ do
p "Previous posts:"
forM_ ses archiveLine
archiveLine :: Entry -> Markup
archiveLine e = do
p $ do
a ! href (toValue $ absoluteUrl e) $ toHtml (entryTitle e)
toHtml (", " ++ (publishedOn e))
rss :: [Entry] -> String
rss es = let ses = reverse $ L.sort es
lastBuild = rfc882 $ maximum ses
rssItems = foldl1 (++) $ L.map rssItem ses
in "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n"
++ "<rss version=\"2.0\" xmlns:atom=\"http://www.w3.org/2005/Atom\">\n"
++ " <channel>"
++ " <title>Existence et Applications</title>\n"
++ " <link>http://www.adrienhaxaire.org</link>\n"
++ " <description>Adrien Haxaire's Existence et Applications blog</description>\n"
++ " <lastBuildDate>" ++ lastBuild ++ "</lastBuildDate>\n"
++ " <atom:link href=\"http://www.adrienhaxaire.org/rss.xml\" rel=\"self\" type=\"application/rss+xml\" />"
++ rssItems
++ " </channel>\n"
++ "</rss>"
rssItem :: Entry -> String
rssItem e = " <item>\n"
++ " <title>" ++ entryTitle e++ "</title>\n"
++ " <link>" ++ absoluteUrl e ++ "</link>\n"
++ " <guid>" ++ absoluteUrl e ++ "</guid>\n"
++ " <pubDate>" ++ rfc882 e ++ "</pubDate>\n"
++ " <description><![CDATA[" ++ entryBody e ++ "]]></description>\n"
++ " </item>\n"
updateRSS :: [Entry] -> IO ()
updateRSS es = writeFile "public/rss.xml" $ rss es
sitemap :: [Entry] -> String
sitemap es = let lastmod = ymd $ entryDate $ maximum es
sitemapUrls = foldl1 (++) $ L.map sitemapUrl es
in "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
++ "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n"
++ "<url>\n <loc>http://www.adrienhaxaire.org</loc>\n"
++ " <lastmod>" ++ lastmod ++ "</lastmod>\n</url>\n"
++ "<url>\n <loc>http://www.adrienhaxaire.org/about.html</loc>\n"
++ " <lastmod>" ++ lastmod ++ "</lastmod>\n</url>\n"
++ "<url>\n <loc>http://www.adrienhaxaire.org/archive.html</loc>\n"
++ " <lastmod>" ++ lastmod ++ "</lastmod>\n</url>\n"
++ sitemapUrls
++ "</urlset>"
sitemapUrl :: Entry -> String
sitemapUrl e = "<url>\n"
++ " <loc>" ++ absoluteUrl e ++ "</loc>\n"
++ " <lastmod>" ++ (ymd $ entryDate e) ++ "</lastmod>\n"
++ " <changefreq>never</changefreq>"
++ "</url>\n"
updateSitemap :: [Entry] -> IO ()
updateSitemap es = writeFile "public/sitemap.xml" $ sitemap es
googleAnalytics :: Html
googleAnalytics = script ! type_ "text/javascript" $ "var _gaq = _gaq || [];\n _gaq.push(['_setAccount', 'UA-13136595-1']);\n _gaq.push(['_trackPageview']);\n (function() {\n var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;\n ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';\n var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);\n })();"
htmlFooter :: Html
htmlFooter = H.div ! A.id "licence" $ I.preEscapedString "<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nd/3.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"http://i.creativecommons.org/l/by-nd/3.0/88x31.png\" /></a><br /><span xmlns:dct=\"http://purl.org/dc/terms/\" href=\"http://purl.org/dc/dcmitype/Text\" property=\"dct:title\" rel=\"dct:type\">Existence et Applications</span> by Adrien Haxaire</a> is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nd/3.0/\">Creative Commons Attribution-NoDerivs 3.0 Unported License</a>.<br />Find more on <a href=\"http://twitter.com/adrienhaxaire\">Twitter</a> and <a href=\"https://plus.google.com/109821515852278704885?rel=author\">Google</a>."
comments :: Entry -> Html
comments e = do
H.div ! A.id "comments" ! A.class_ "container" $ do
h2 "Comments"
H.div ! A.id "disqus_thread" $ ""
script ! type_ "text/javascript" $ disqus e
noscript $ I.preEscapedString "Please enable JavaScript to view the <a href=\"http://disqus.com/?ref_noscript\">comments powered by Disqus.</a>"
a ! href "http://disqus.com" ! A.class_ "dsq-brlink" $ I.preEscapedString "comments powered by <span class=\"logo-disqus\">Disqus</span>"
disqus :: Entry -> Html
disqus e = toHtml $ "var disqus_shortname = 'adrienhaxaire';\n"
++ " var disqus_identifier = '" ++ entryUrl e ++ "'\n"
++ " var disqus_url = '" ++ absoluteUrl e ++ "';\n"
++ " var disqus_title = '" ++ entryTitle e ++ "';\n"
++ " (function() {var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;"
++ " dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js'; "
++ " (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);})();"
main :: IO ()
main = do
es <- entries
updateEntries es
updateIndex es
updateArchive es
updateRSS es
updateSitemap es
|
adrienhaxaire/adrienhaxaire.org
|
update.hs
|
Haskell
|
bsd-3-clause
| 12,406
|
---------------------------------------------------------------------------
-- |
-- module : Control.Monad.Trans.Cont
-- Copyright : (c) Evgeniy Permyakov 2010
-- License : BSD-style (see the LICENSE file in the distribution)
--
-- Maintainer : permeakra@gmail.com
-- Stability : experimental
-- Portability : portable (haskell - 2010)
-- Actually, this module is redundant, because Coroutines provides superset of this functional.
-- However, it is simplier to use, so it is provided.
module Control.Monad.Trans.Invoke where
import Control.Monad.Trans.Class
import Control.Monad.IO.Class
newtype InvokeT p m a = InvokeT ( (p -> m () ) -> m a )
invokeT :: ( (p -> m () ) -> m a ) -> InvokeT p m a
invokeT = InvokeT
runInvokeT :: InvokeT p m a -> ( p -> m () ) -> m a
runInvokeT (InvokeT a) f = a f
instance Functor m => Functor (InvokeT p m) where
fmap f m = invokeT $ \i -> fmap f (runInvokeT m i)
instance Monad m => Monad (InvokeT p m) where
return a = invokeT $ \_ -> return a
m >>= k = invokeT $ \f -> runInvokeT m f >>= \x -> runInvokeT (k x) f
invoke :: p -> InvokeT p m ()
invoke p = invokeT $ \f -> f p
|
permeakra/yamtl
|
Control/Monad/Trans/Invoke.hs
|
Haskell
|
bsd-3-clause
| 1,150
|
-- | Bookstore Example
-- example from Realworld Haskell Chapter 03
module Week02.BookStore where
data BookInfo = Book Integer String [String]
deriving (Show)
data MagazineInfo = Magazine Integer String [String]
deriving (Show)
-- Type synonyms
type CustomerID = Int
type CardHolder = String
type CardNumber = String
type Address = [String]
type ReviewBody = String
data BookReview = BookReview BookInfo CustomerID String
data BetterReview = BetterReview BookInfo CustomerID ReviewBody
myInfo :: BookInfo
myInfo = Book 9780135072455 "Algerbra of Programming"
["Richard Bird", "Oege de Moor"]
type BookRecord = (BookInfo, BookReview)
data BillingInfo = CreditCard CardNumber CardHolder Address
| CashOnDelivery
| Invoice CustomerID
deriving (Show)
bookID :: BookInfo -> Integer
bookID (Book bid _ _) = bid
bookTitle :: BookInfo -> String
bookTitle (Book _ title _) = title
bookAuthors :: BookInfo -> [String]
bookAuthors (Book _ _ authors) = authors
data Customer = Customer {
customerID :: CustomerID
, customerName :: String
, customerAddress :: Address
} deriving (Show)
customer2 :: Customer
customer2 = Customer {
customerID = 271828
, customerAddress = ["1048576 Disk Drive",
"Milpitas, CA 95134",
"USA"]
, customerName = "Jane Q. Citizen"
}
|
emaphis/Haskell-Practice
|
cis194/src/Week02/BookStore.hs
|
Haskell
|
bsd-3-clause
| 1,484
|
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
Pattern-matching bindings (HsBinds and MonoBinds)
Handles @HsBinds@; those at the top level require different handling,
in that the @Rec@/@NonRec@/etc structure is thrown away (whereas at
lower levels it is preserved with @let@/@letrec@s).
-}
{-# LANGUAGE CPP #-}
module Language.Haskell.Liquid.Desugar710.DsBinds ( dsTopLHsBinds, dsLHsBinds, decomposeRuleLhs, dsSpec,
dsHsWrapper, dsTcEvBinds, dsEvBinds
) where
-- #include "HsVersions.h"
import {-# SOURCE #-} Language.Haskell.Liquid.Desugar710.DsExpr( dsLExpr )
import {-# SOURCE #-} Language.Haskell.Liquid.Desugar710.Match( matchWrapper )
import DsMonad
import Language.Haskell.Liquid.Desugar710.DsGRHSs
import Language.Haskell.Liquid.Desugar710.DsUtils
import HsSyn -- lots of things
import CoreSyn -- lots of things
import Literal ( Literal(MachStr) )
import CoreSubst
import OccurAnal ( occurAnalyseExpr )
import MkCore
import CoreUtils
import CoreArity ( etaExpand )
import CoreUnfold
import CoreFVs
import UniqSupply
import Digraph
import Module
import PrelNames
import TysPrim ( mkProxyPrimTy )
import TyCon ( tyConDataCons_maybe
, tyConName, isPromotedTyCon, isPromotedDataCon )
import TcEvidence
import TcType
import Type
import Coercion hiding (substCo)
import TysWiredIn ( eqBoxDataCon, coercibleDataCon, tupleCon )
import Id
import MkId(proxyHashId)
import Class
import DataCon ( dataConWorkId )
import Name
import MkId ( seqId )
import IdInfo ( IdDetails(..) )
import Var
import VarSet
import Rules
import VarEnv
import Outputable
import SrcLoc
import Maybes
import OrdList
import Bag
import BasicTypes hiding ( TopLevel )
import DynFlags
import FastString
import ErrUtils( MsgDoc )
import ListSetOps( getNth )
import Util
import Control.Monad( when )
import MonadUtils
import Control.Monad(liftM)
import Fingerprint(Fingerprint(..), fingerprintString)
{-
************************************************************************
* *
\subsection[dsMonoBinds]{Desugaring a @MonoBinds@}
* *
************************************************************************
-}
dsTopLHsBinds :: LHsBinds Id -> DsM (OrdList (Id,CoreExpr))
dsTopLHsBinds binds = ds_lhs_binds binds
dsLHsBinds :: LHsBinds Id -> DsM [(Id,CoreExpr)]
dsLHsBinds binds = do { binds' <- ds_lhs_binds binds
; return (fromOL binds') }
------------------------
ds_lhs_binds :: LHsBinds Id -> DsM (OrdList (Id,CoreExpr))
ds_lhs_binds binds = do { ds_bs <- mapBagM dsLHsBind binds
; return (foldBag appOL id nilOL ds_bs) }
dsLHsBind :: LHsBind Id -> DsM (OrdList (Id,CoreExpr))
dsLHsBind (L loc bind) = putSrcSpanDs loc $ dsHsBind bind
dsHsBind :: HsBind Id -> DsM (OrdList (Id,CoreExpr))
dsHsBind (VarBind { var_id = var, var_rhs = expr, var_inline = inline_regardless })
= do { dflags <- getDynFlags
; core_expr <- dsLExpr expr
-- Dictionary bindings are always VarBinds,
-- so we only need do this here
; let var' | inline_regardless = var `setIdUnfolding` mkCompulsoryUnfolding core_expr
| otherwise = var
; return (unitOL (makeCorePair dflags var' False 0 core_expr)) }
dsHsBind (FunBind { fun_id = L _ fun, fun_matches = matches
, fun_co_fn = co_fn, fun_tick = tick
, fun_infix = inf })
= do { dflags <- getDynFlags
; (args, body) <- matchWrapper (FunRhs (idName fun) inf) matches
; let body' = mkOptTickBox tick body
; rhs <- dsHsWrapper co_fn (mkLams args body')
; {- pprTrace "dsHsBind" (ppr fun <+> ppr (idInlinePragma fun)) $ -}
return (unitOL (makeCorePair dflags fun False 0 rhs)) }
dsHsBind (PatBind { pat_lhs = pat, pat_rhs = grhss, pat_rhs_ty = ty
, pat_ticks = (rhs_tick, var_ticks) })
= do { body_expr <- dsGuarded grhss ty
; let body' = mkOptTickBox rhs_tick body_expr
; sel_binds <- mkSelectorBinds var_ticks pat body'
-- We silently ignore inline pragmas; no makeCorePair
-- Not so cool, but really doesn't matter
; return (toOL sel_binds) }
-- A common case: one exported variable
-- Non-recursive bindings come through this way
-- So do self-recursive bindings, and recursive bindings
-- that have been chopped up with type signatures
dsHsBind (AbsBinds { abs_tvs = tyvars, abs_ev_vars = dicts
, abs_exports = [export]
, abs_ev_binds = ev_binds, abs_binds = binds })
| ABE { abe_wrap = wrap, abe_poly = global
, abe_mono = local, abe_prags = prags } <- export
= do { dflags <- getDynFlags
; bind_prs <- ds_lhs_binds binds
; let core_bind = Rec (fromOL bind_prs)
; ds_binds <- dsTcEvBinds ev_binds
; rhs <- dsHsWrapper wrap $ -- Usually the identity
mkLams tyvars $ mkLams dicts $
mkCoreLets ds_binds $
Let core_bind $
Var local
; (spec_binds, rules) <- dsSpecs rhs prags
; let global' = addIdSpecialisations global rules
main_bind = makeCorePair dflags global' (isDefaultMethod prags)
(dictArity dicts) rhs
; return (main_bind `consOL` spec_binds) }
dsHsBind (AbsBinds { abs_tvs = tyvars, abs_ev_vars = dicts
, abs_exports = exports, abs_ev_binds = ev_binds
, abs_binds = binds })
-- See Note [Desugaring AbsBinds]
= do { dflags <- getDynFlags
; bind_prs <- ds_lhs_binds binds
; let core_bind = Rec [ makeCorePair dflags (add_inline lcl_id) False 0 rhs
| (lcl_id, rhs) <- fromOL bind_prs ]
-- Monomorphic recursion possible, hence Rec
locals = map abe_mono exports
tup_expr = mkBigCoreVarTup locals
tup_ty = exprType tup_expr
; ds_binds <- dsTcEvBinds ev_binds
; let poly_tup_rhs = mkLams tyvars $ mkLams dicts $
mkCoreLets ds_binds $
Let core_bind $
tup_expr
; poly_tup_id <- newSysLocalDs (exprType poly_tup_rhs)
; let mk_bind (ABE { abe_wrap = wrap, abe_poly = global
, abe_mono = local, abe_prags = spec_prags })
= do { tup_id <- newSysLocalDs tup_ty
; rhs <- dsHsWrapper wrap $
mkLams tyvars $ mkLams dicts $
mkTupleSelector locals local tup_id $
mkVarApps (Var poly_tup_id) (tyvars ++ dicts)
; let rhs_for_spec = Let (NonRec poly_tup_id poly_tup_rhs) rhs
; (spec_binds, rules) <- dsSpecs rhs_for_spec spec_prags
; let global' = (global `setInlinePragma` defaultInlinePragma)
`addIdSpecialisations` rules
-- Kill the INLINE pragma because it applies to
-- the user written (local) function. The global
-- Id is just the selector. Hmm.
; return ((global', rhs) `consOL` spec_binds) }
; export_binds_s <- mapM mk_bind exports
; return ((poly_tup_id, poly_tup_rhs) `consOL`
concatOL export_binds_s) }
where
inline_env :: IdEnv Id -- Maps a monomorphic local Id to one with
-- the inline pragma from the source
-- The type checker put the inline pragma
-- on the *global* Id, so we need to transfer it
inline_env = mkVarEnv [ (lcl_id, setInlinePragma lcl_id prag)
| ABE { abe_mono = lcl_id, abe_poly = gbl_id } <- exports
, let prag = idInlinePragma gbl_id ]
add_inline :: Id -> Id -- tran
add_inline lcl_id = lookupVarEnv inline_env lcl_id `orElse` lcl_id
dsHsBind (PatSynBind{}) = panic "dsHsBind: PatSynBind"
------------------------
makeCorePair :: DynFlags -> Id -> Bool -> Arity -> CoreExpr -> (Id, CoreExpr)
makeCorePair dflags gbl_id is_default_method dict_arity rhs
| is_default_method -- Default methods are *always* inlined
= (gbl_id `setIdUnfolding` mkCompulsoryUnfolding rhs, rhs)
| DFunId _ is_newtype <- idDetails gbl_id
= (mk_dfun_w_stuff is_newtype, rhs)
| otherwise
= case inlinePragmaSpec inline_prag of
EmptyInlineSpec -> (gbl_id, rhs)
NoInline -> (gbl_id, rhs)
Inlinable -> (gbl_id `setIdUnfolding` inlinable_unf, rhs)
Inline -> inline_pair
where
inline_prag = idInlinePragma gbl_id
inlinable_unf = mkInlinableUnfolding dflags rhs
inline_pair
| Just arity <- inlinePragmaSat inline_prag
-- Add an Unfolding for an INLINE (but not for NOINLINE)
-- And eta-expand the RHS; see Note [Eta-expanding INLINE things]
, let real_arity = dict_arity + arity
-- NB: The arity in the InlineRule takes account of the dictionaries
= ( gbl_id `setIdUnfolding` mkInlineUnfolding (Just real_arity) rhs
, etaExpand real_arity rhs)
| otherwise
= pprTrace "makeCorePair: arity missing" (ppr gbl_id) $
(gbl_id `setIdUnfolding` mkInlineUnfolding Nothing rhs, rhs)
-- See Note [ClassOp/DFun selection] in TcInstDcls
-- See Note [Single-method classes] in TcInstDcls
mk_dfun_w_stuff is_newtype
| is_newtype
= gbl_id `setIdUnfolding` mkInlineUnfolding (Just 0) rhs
`setInlinePragma` alwaysInlinePragma { inl_sat = Just 0 }
| otherwise
= gbl_id `setIdUnfolding` mkDFunUnfolding dfun_bndrs dfun_constr dfun_args
`setInlinePragma` dfunInlinePragma
(dfun_bndrs, dfun_body) = collectBinders (simpleOptExpr rhs)
(dfun_con, dfun_args, _) = collectArgsTicks (const True) dfun_body
dfun_constr | Var id <- dfun_con
, DataConWorkId con <- idDetails id
= con
| otherwise = pprPanic "makeCorePair: dfun" (ppr rhs)
dictArity :: [Var] -> Arity
-- Don't count coercion variables in arity
dictArity dicts = count isId dicts
{-
[Desugaring AbsBinds]
~~~~~~~~~~~~~~~~~~~~~
In the general AbsBinds case we desugar the binding to this:
tup a (d:Num a) = let fm = ...gm...
gm = ...fm...
in (fm,gm)
f a d = case tup a d of { (fm,gm) -> fm }
g a d = case tup a d of { (fm,gm) -> fm }
Note [Rules and inlining]
~~~~~~~~~~~~~~~~~~~~~~~~~
Common special case: no type or dictionary abstraction
This is a bit less trivial than you might suppose
The naive way woudl be to desguar to something like
f_lcl = ...f_lcl... -- The "binds" from AbsBinds
M.f = f_lcl -- Generated from "exports"
But we don't want that, because if M.f isn't exported,
it'll be inlined unconditionally at every call site (its rhs is
trivial). That would be ok unless it has RULES, which would
thereby be completely lost. Bad, bad, bad.
Instead we want to generate
M.f = ...f_lcl...
f_lcl = M.f
Now all is cool. The RULES are attached to M.f (by SimplCore),
and f_lcl is rapidly inlined away.
This does not happen in the same way to polymorphic binds,
because they desugar to
M.f = /\a. let f_lcl = ...f_lcl... in f_lcl
Although I'm a bit worried about whether full laziness might
float the f_lcl binding out and then inline M.f at its call site
Note [Specialising in no-dict case]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Even if there are no tyvars or dicts, we may have specialisation pragmas.
Class methods can generate
AbsBinds [] [] [( ... spec-prag]
{ AbsBinds [tvs] [dicts] ...blah }
So the overloading is in the nested AbsBinds. A good example is in GHC.Float:
class (Real a, Fractional a) => RealFrac a where
round :: (Integral b) => a -> b
instance RealFrac Float where
{-# SPECIALIZE round :: Float -> Int #-}
The top-level AbsBinds for $cround has no tyvars or dicts (because the
instance does not). But the method is locally overloaded!
Note [Abstracting over tyvars only]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When abstracting over type variable only (not dictionaries), we don't really need to
built a tuple and select from it, as we do in the general case. Instead we can take
AbsBinds [a,b] [ ([a,b], fg, fl, _),
([b], gg, gl, _) ]
{ fl = e1
gl = e2
h = e3 }
and desugar it to
fg = /\ab. let B in e1
gg = /\b. let a = () in let B in S(e2)
h = /\ab. let B in e3
where B is the *non-recursive* binding
fl = fg a b
gl = gg b
h = h a b -- See (b); note shadowing!
Notice (a) g has a different number of type variables to f, so we must
use the mkArbitraryType thing to fill in the gaps.
We use a type-let to do that.
(b) The local variable h isn't in the exports, and rather than
clone a fresh copy we simply replace h by (h a b), where
the two h's have different types! Shadowing happens here,
which looks confusing but works fine.
(c) The result is *still* quadratic-sized if there are a lot of
small bindings. So if there are more than some small
number (10), we filter the binding set B by the free
variables of the particular RHS. Tiresome.
Why got to this trouble? It's a common case, and it removes the
quadratic-sized tuple desugaring. Less clutter, hopefully faster
compilation, especially in a case where there are a *lot* of
bindings.
Note [Eta-expanding INLINE things]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
foo :: Eq a => a -> a
{-# INLINE foo #-}
foo x = ...
If (foo d) ever gets floated out as a common sub-expression (which can
happen as a result of method sharing), there's a danger that we never
get to do the inlining, which is a Terribly Bad thing given that the
user said "inline"!
To avoid this we pre-emptively eta-expand the definition, so that foo
has the arity with which it is declared in the source code. In this
example it has arity 2 (one for the Eq and one for x). Doing this
should mean that (foo d) is a PAP and we don't share it.
Note [Nested arities]
~~~~~~~~~~~~~~~~~~~~~
For reasons that are not entirely clear, method bindings come out looking like
this:
AbsBinds [] [] [$cfromT <= [] fromT]
$cfromT [InlPrag=INLINE] :: T Bool -> Bool
{ AbsBinds [] [] [fromT <= [] fromT_1]
fromT :: T Bool -> Bool
{ fromT_1 ((TBool b)) = not b } } }
Note the nested AbsBind. The arity for the InlineRule on $cfromT should be
gotten from the binding for fromT_1.
It might be better to have just one level of AbsBinds, but that requires more
thought!
Note [Implementing SPECIALISE pragmas]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Example:
f :: (Eq a, Ix b) => a -> b -> Bool
{-# SPECIALISE f :: (Ix p, Ix q) => Int -> (p,q) -> Bool #-}
f = <poly_rhs>
From this the typechecker generates
AbsBinds [ab] [d1,d2] [([ab], f, f_mono, prags)] binds
SpecPrag (wrap_fn :: forall a b. (Eq a, Ix b) => XXX
-> forall p q. (Ix p, Ix q) => XXX[ Int/a, (p,q)/b ])
Note that wrap_fn can transform *any* function with the right type prefix
forall ab. (Eq a, Ix b) => XXX
regardless of XXX. It's sort of polymorphic in XXX. This is
useful: we use the same wrapper to transform each of the class ops, as
well as the dict.
From these we generate:
Rule: forall p, q, (dp:Ix p), (dq:Ix q).
f Int (p,q) dInt ($dfInPair dp dq) = f_spec p q dp dq
Spec bind: f_spec = wrap_fn <poly_rhs>
Note that
* The LHS of the rule may mention dictionary *expressions* (eg
$dfIxPair dp dq), and that is essential because the dp, dq are
needed on the RHS.
* The RHS of f_spec, <poly_rhs> has a *copy* of 'binds', so that it
can fully specialise it.
-}
------------------------
dsSpecs :: CoreExpr -- Its rhs
-> TcSpecPrags
-> DsM ( OrdList (Id,CoreExpr) -- Binding for specialised Ids
, [CoreRule] ) -- Rules for the Global Ids
-- See Note [Implementing SPECIALISE pragmas]
dsSpecs _ IsDefaultMethod = return (nilOL, [])
dsSpecs poly_rhs (SpecPrags sps)
= do { pairs <- mapMaybeM (dsSpec (Just poly_rhs)) sps
; let (spec_binds_s, rules) = unzip pairs
; return (concatOL spec_binds_s, rules) }
dsSpec :: Maybe CoreExpr -- Just rhs => RULE is for a local binding
-- Nothing => RULE is for an imported Id
-- rhs is in the Id's unfolding
-> Located TcSpecPrag
-> DsM (Maybe (OrdList (Id,CoreExpr), CoreRule))
dsSpec mb_poly_rhs (L loc (SpecPrag poly_id spec_co spec_inl))
| isJust (isClassOpId_maybe poly_id)
= putSrcSpanDs loc $
do { warnDs (ptext (sLit "Ignoring useless SPECIALISE pragma for class method selector")
<+> quotes (ppr poly_id))
; return Nothing } -- There is no point in trying to specialise a class op
-- Moreover, classops don't (currently) have an inl_sat arity set
-- (it would be Just 0) and that in turn makes makeCorePair bleat
| no_act_spec && isNeverActive rule_act
= putSrcSpanDs loc $
do { warnDs (ptext (sLit "Ignoring useless SPECIALISE pragma for NOINLINE function:")
<+> quotes (ppr poly_id))
; return Nothing } -- Function is NOINLINE, and the specialiation inherits that
-- See Note [Activation pragmas for SPECIALISE]
| otherwise
= putSrcSpanDs loc $
do { uniq <- newUnique
; let poly_name = idName poly_id
spec_occ = mkSpecOcc (getOccName poly_name)
spec_name = mkInternalName uniq spec_occ (getSrcSpan poly_name)
; (bndrs, ds_lhs) <- liftM collectBinders
(dsHsWrapper spec_co (Var poly_id))
; let spec_ty = mkPiTypes bndrs (exprType ds_lhs)
; -- pprTrace "dsRule" (vcat [ ptext (sLit "Id:") <+> ppr poly_id
-- , ptext (sLit "spec_co:") <+> ppr spec_co
-- , ptext (sLit "ds_rhs:") <+> ppr ds_lhs ]) $
case decomposeRuleLhs bndrs ds_lhs of {
Left msg -> do { warnDs msg; return Nothing } ;
Right (rule_bndrs, _fn, args) -> do
{ dflags <- getDynFlags
; let fn_unf = realIdUnfolding poly_id
unf_fvs = stableUnfoldingVars fn_unf `orElse` emptyVarSet
in_scope = mkInScopeSet (unf_fvs `unionVarSet` exprsFreeVars args)
spec_unf = specUnfolding dflags (mkEmptySubst in_scope) bndrs args fn_unf
spec_id = mkLocalId spec_name spec_ty
`setInlinePragma` inl_prag
`setIdUnfolding` spec_unf
rule = mkRule False {- Not auto -} is_local_id
(mkFastString ("SPEC " ++ showPpr dflags poly_name))
rule_act poly_name
rule_bndrs args
(mkVarApps (Var spec_id) bndrs)
; spec_rhs <- dsHsWrapper spec_co poly_rhs
; when (isInlinePragma id_inl && wopt Opt_WarnPointlessPragmas dflags)
(warnDs (specOnInline poly_name))
; return (Just (unitOL (spec_id, spec_rhs), rule))
-- NB: do *not* use makeCorePair on (spec_id,spec_rhs), because
-- makeCorePair overwrites the unfolding, which we have
-- just created using specUnfolding
} } }
where
is_local_id = isJust mb_poly_rhs
poly_rhs | Just rhs <- mb_poly_rhs
= rhs -- Local Id; this is its rhs
| Just unfolding <- maybeUnfoldingTemplate (realIdUnfolding poly_id)
= unfolding -- Imported Id; this is its unfolding
-- Use realIdUnfolding so we get the unfolding
-- even when it is a loop breaker.
-- We want to specialise recursive functions!
| otherwise = pprPanic "dsImpSpecs" (ppr poly_id)
-- The type checker has checked that it *has* an unfolding
id_inl = idInlinePragma poly_id
-- See Note [Activation pragmas for SPECIALISE]
inl_prag | not (isDefaultInlinePragma spec_inl) = spec_inl
| not is_local_id -- See Note [Specialising imported functions]
-- in OccurAnal
, isStrongLoopBreaker (idOccInfo poly_id) = neverInlinePragma
| otherwise = id_inl
-- Get the INLINE pragma from SPECIALISE declaration, or,
-- failing that, from the original Id
spec_prag_act = inlinePragmaActivation spec_inl
-- See Note [Activation pragmas for SPECIALISE]
-- no_act_spec is True if the user didn't write an explicit
-- phase specification in the SPECIALISE pragma
no_act_spec = case inlinePragmaSpec spec_inl of
NoInline -> isNeverActive spec_prag_act
_ -> isAlwaysActive spec_prag_act
rule_act | no_act_spec = inlinePragmaActivation id_inl -- Inherit
| otherwise = spec_prag_act -- Specified by user
specOnInline :: Name -> MsgDoc
specOnInline f = ptext (sLit "SPECIALISE pragma on INLINE function probably won't fire:")
<+> quotes (ppr f)
{-
Note [Activation pragmas for SPECIALISE]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
From a user SPECIALISE pragma for f, we generate
a) A top-level binding spec_fn = rhs
b) A RULE f dOrd = spec_fn
We need two pragma-like things:
* spec_fn's inline pragma: inherited from f's inline pragma (ignoring
activation on SPEC), unless overriden by SPEC INLINE
* Activation of RULE: from SPECIALISE pragma (if activation given)
otherwise from f's inline pragma
This is not obvious (see Trac #5237)!
Examples Rule activation Inline prag on spec'd fn
---------------------------------------------------------------------
SPEC [n] f :: ty [n] Always, or NOINLINE [n]
copy f's prag
NOINLINE f
SPEC [n] f :: ty [n] NOINLINE
copy f's prag
NOINLINE [k] f
SPEC [n] f :: ty [n] NOINLINE [k]
copy f's prag
INLINE [k] f
SPEC [n] f :: ty [n] INLINE [k]
copy f's prag
SPEC INLINE [n] f :: ty [n] INLINE [n]
(ignore INLINE prag on f,
same activation for rule and spec'd fn)
NOINLINE [k] f
SPEC f :: ty [n] INLINE [k]
************************************************************************
* *
\subsection{Adding inline pragmas}
* *
************************************************************************
-}
decomposeRuleLhs :: [Var] -> CoreExpr -> Either SDoc ([Var], Id, [CoreExpr])
-- (decomposeRuleLhs bndrs lhs) takes apart the LHS of a RULE,
-- The 'bndrs' are the quantified binders of the rules, but decomposeRuleLhs
-- may add some extra dictionary binders (see Note [Free dictionaries])
--
-- Returns Nothing if the LHS isn't of the expected shape
-- Note [Decomposing the left-hand side of a RULE]
decomposeRuleLhs orig_bndrs orig_lhs
| not (null unbound) -- Check for things unbound on LHS
-- See Note [Unused spec binders]
= Left (vcat (map dead_msg unbound))
| Var fn_var <- fun
, not (fn_var `elemVarSet` orig_bndr_set)
= -- pprTrace "decmposeRuleLhs" (vcat [ ptext (sLit "orig_bndrs:") <+> ppr orig_bndrs
-- , ptext (sLit "orig_lhs:") <+> ppr orig_lhs
-- , ptext (sLit "lhs1:") <+> ppr lhs1
-- , ptext (sLit "bndrs1:") <+> ppr bndrs1
-- , ptext (sLit "fn_var:") <+> ppr fn_var
-- , ptext (sLit "args:") <+> ppr args]) $
Right (bndrs1, fn_var, args)
| Case scrut bndr ty [(DEFAULT, _, body)] <- fun
, isDeadBinder bndr -- Note [Matching seqId]
, let args' = [Type (idType bndr), Type ty, scrut, body]
= Right (bndrs1, seqId, args' ++ args)
| otherwise
= Left bad_shape_msg
where
lhs1 = drop_dicts orig_lhs
lhs2 = simpleOptExpr lhs1 -- See Note [Simplify rule LHS]
(fun,args) = collectArgs lhs2
lhs_fvs = exprFreeVars lhs2
unbound = filterOut (`elemVarSet` lhs_fvs) orig_bndrs
bndrs1 = orig_bndrs ++ extra_dict_bndrs
orig_bndr_set = mkVarSet orig_bndrs
-- Add extra dict binders: Note [Free dictionaries]
extra_dict_bndrs = [ mkLocalId (localiseName (idName d)) (idType d)
| d <- varSetElems (lhs_fvs `delVarSetList` orig_bndrs)
, isDictId d ]
bad_shape_msg = hang (ptext (sLit "RULE left-hand side too complicated to desugar"))
2 (vcat [ text "Optimised lhs:" <+> ppr lhs2
, text "Orig lhs:" <+> ppr orig_lhs])
dead_msg bndr = hang (sep [ ptext (sLit "Forall'd") <+> pp_bndr bndr
, ptext (sLit "is not bound in RULE lhs")])
2 (vcat [ text "Orig bndrs:" <+> ppr orig_bndrs
, text "Orig lhs:" <+> ppr orig_lhs
, text "optimised lhs:" <+> ppr lhs2 ])
pp_bndr bndr
| isTyVar bndr = ptext (sLit "type variable") <+> quotes (ppr bndr)
| Just pred <- evVarPred_maybe bndr = ptext (sLit "constraint") <+> quotes (ppr pred)
| otherwise = ptext (sLit "variable") <+> quotes (ppr bndr)
drop_dicts :: CoreExpr -> CoreExpr
drop_dicts e
= wrap_lets needed bnds body
where
needed = orig_bndr_set `minusVarSet` exprFreeVars body
(bnds, body) = split_lets (occurAnalyseExpr e)
-- The occurAnalyseExpr drops dead bindings which is
-- crucial to ensure that every binding is used later;
-- which in turn makes wrap_lets work right
split_lets :: CoreExpr -> ([(DictId,CoreExpr)], CoreExpr)
split_lets e
| Let (NonRec d r) body <- e
, isDictId d
, (bs, body') <- split_lets body
= ((d,r):bs, body')
| otherwise
= ([], e)
wrap_lets :: VarSet -> [(DictId,CoreExpr)] -> CoreExpr -> CoreExpr
wrap_lets _ [] body = body
wrap_lets needed ((d, r) : bs) body
| rhs_fvs `intersectsVarSet` needed = Let (NonRec d r) (wrap_lets needed' bs body)
| otherwise = wrap_lets needed bs body
where
rhs_fvs = exprFreeVars r
needed' = (needed `minusVarSet` rhs_fvs) `extendVarSet` d
{-
Note [Decomposing the left-hand side of a RULE]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There are several things going on here.
* drop_dicts: see Note [Drop dictionary bindings on rule LHS]
* simpleOptExpr: see Note [Simplify rule LHS]
* extra_dict_bndrs: see Note [Free dictionaries]
Note [Drop dictionary bindings on rule LHS]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
drop_dicts drops dictionary bindings on the LHS where possible.
E.g. let d:Eq [Int] = $fEqList $fEqInt in f d
--> f d
Reasoning here is that there is only one d:Eq [Int], and so we can
quantify over it. That makes 'd' free in the LHS, but that is later
picked up by extra_dict_bndrs (Note [Dead spec binders]).
NB 1: We can only drop the binding if the RHS doesn't bind
one of the orig_bndrs, which we assume occur on RHS.
Example
f :: (Eq a) => b -> a -> a
{-# SPECIALISE f :: Eq a => b -> [a] -> [a] #-}
Here we want to end up with
RULE forall d:Eq a. f ($dfEqList d) = f_spec d
Of course, the ($dfEqlist d) in the pattern makes it less likely
to match, but ther is no other way to get d:Eq a
NB 2: We do drop_dicts *before* simplOptEpxr, so that we expect all
the evidence bindings to be wrapped around the outside of the
LHS. (After simplOptExpr they'll usually have been inlined.)
dsHsWrapper does dependency analysis, so that civilised ones
will be simple NonRec bindings. We don't handle recursive
dictionaries!
NB3: In the common case of a non-overloaded, but perhaps-polymorphic
specialisation, we don't need to bind *any* dictionaries for use
in the RHS. For example (Trac #8331)
{-# SPECIALIZE INLINE useAbstractMonad :: ReaderST s Int #-}
useAbstractMonad :: MonadAbstractIOST m => m Int
Here, deriving (MonadAbstractIOST (ReaderST s)) is a lot of code
but the RHS uses no dictionaries, so we want to end up with
RULE forall s (d :: MonadBstractIOST (ReaderT s)).
useAbstractMonad (ReaderT s) d = $suseAbstractMonad s
Trac #8848 is a good example of where there are some intersting
dictionary bindings to discard.
The drop_dicts algorithm is based on these observations:
* Given (let d = rhs in e) where d is a DictId,
matching 'e' will bind e's free variables.
* So we want to keep the binding if one of the needed variables (for
which we need a binding) is in fv(rhs) but not already in fv(e).
* The "needed variables" are simply the orig_bndrs. Consider
f :: (Eq a, Show b) => a -> b -> String
... SPECIALISE f :: (Show b) => Int -> b -> String ...
Then orig_bndrs includes the *quantified* dictionaries of the type
namely (dsb::Show b), but not the one for Eq Int
So we work inside out, applying the above criterion at each step.
Note [Simplify rule LHS]
~~~~~~~~~~~~~~~~~~~~~~~~
simplOptExpr occurrence-analyses and simplifies the LHS:
(a) Inline any remaining dictionary bindings (which hopefully
occur just once)
(b) Substitute trivial lets so that they don't get in the way
Note that we substitute the function too; we might
have this as a LHS: let f71 = M.f Int in f71
(c) Do eta reduction. To see why, consider the fold/build rule,
which without simplification looked like:
fold k z (build (/\a. g a)) ==> ...
This doesn't match unless you do eta reduction on the build argument.
Similarly for a LHS like
augment g (build h)
we do not want to get
augment (\a. g a) (build h)
otherwise we don't match when given an argument like
augment (\a. h a a) (build h)
Note [Matching seqId]
~~~~~~~~~~~~~~~~~~~
The desugarer turns (seq e r) into (case e of _ -> r), via a special-case hack
and this code turns it back into an application of seq!
See Note [Rules for seq] in MkId for the details.
Note [Unused spec binders]
~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
f :: a -> a
... SPECIALISE f :: Eq a => a -> a ...
It's true that this *is* a more specialised type, but the rule
we get is something like this:
f_spec d = f
RULE: f = f_spec d
Note that the rule is bogus, because it mentions a 'd' that is
not bound on the LHS! But it's a silly specialisation anyway, because
the constraint is unused. We could bind 'd' to (error "unused")
but it seems better to reject the program because it's almost certainly
a mistake. That's what the isDeadBinder call detects.
Note [Free dictionaries]
~~~~~~~~~~~~~~~~~~~~~~~~
When the LHS of a specialisation rule, (/\as\ds. f es) has a free dict,
which is presumably in scope at the function definition site, we can quantify
over it too. *Any* dict with that type will do.
So for example when you have
f :: Eq a => a -> a
f = <rhs>
... SPECIALISE f :: Int -> Int ...
Then we get the SpecPrag
SpecPrag (f Int dInt)
And from that we want the rule
RULE forall dInt. f Int dInt = f_spec
f_spec = let f = <rhs> in f Int dInt
But be careful! That dInt might be GHC.Base.$fOrdInt, which is an External
Name, and you can't bind them in a lambda or forall without getting things
confused. Likewise it might have an InlineRule or something, which would be
utterly bogus. So we really make a fresh Id, with the same unique and type
as the old one, but with an Internal name and no IdInfo.
************************************************************************
* *
Desugaring evidence
* *
************************************************************************
-}
dsHsWrapper :: HsWrapper -> CoreExpr -> DsM CoreExpr
dsHsWrapper WpHole e = return e
dsHsWrapper (WpTyApp ty) e = return $ App e (Type ty)
dsHsWrapper (WpLet ev_binds) e = do bs <- dsTcEvBinds ev_binds
return (mkCoreLets bs e)
dsHsWrapper (WpCompose c1 c2) e = do { e1 <- dsHsWrapper c2 e
; dsHsWrapper c1 e1 }
dsHsWrapper (WpFun c1 c2 t1 _) e = do { x <- newSysLocalDs t1
; e1 <- dsHsWrapper c1 (Var x)
; e2 <- dsHsWrapper c2 (e `mkCoreAppDs` e1)
; return (Lam x e2) }
dsHsWrapper (WpCast co) e = -- ASSERT(tcCoercionRole co == Representational)
dsTcCoercion co (mkCast e)
dsHsWrapper (WpEvLam ev) e = return $ Lam ev e
dsHsWrapper (WpTyLam tv) e = return $ Lam tv e
dsHsWrapper (WpEvApp tm) e = liftM (App e) (dsEvTerm tm)
--------------------------------------
dsTcEvBinds :: TcEvBinds -> DsM [CoreBind]
dsTcEvBinds (TcEvBinds {}) = panic "dsEvBinds" -- Zonker has got rid of this
dsTcEvBinds (EvBinds bs) = dsEvBinds bs
dsEvBinds :: Bag EvBind -> DsM [CoreBind]
dsEvBinds bs = mapM ds_scc (sccEvBinds bs)
where
ds_scc (AcyclicSCC (EvBind v r)) = liftM (NonRec v) (dsEvTerm r)
ds_scc (CyclicSCC bs) = liftM Rec (mapM ds_pair bs)
ds_pair (EvBind v r) = liftM ((,) v) (dsEvTerm r)
sccEvBinds :: Bag EvBind -> [SCC EvBind]
sccEvBinds bs = stronglyConnCompFromEdgedVertices edges
where
edges :: [(EvBind, EvVar, [EvVar])]
edges = foldrBag ((:) . mk_node) [] bs
mk_node :: EvBind -> (EvBind, EvVar, [EvVar])
mk_node b@(EvBind var term) = (b, var, varSetElems (evVarsOfTerm term))
---------------------------------------
dsEvTerm :: EvTerm -> DsM CoreExpr
dsEvTerm (EvId v) = return (Var v)
dsEvTerm (EvCast tm co)
= do { tm' <- dsEvTerm tm
; dsTcCoercion co $ mkCast tm' }
-- 'v' is always a lifted evidence variable so it is
-- unnecessary to call varToCoreExpr v here.
dsEvTerm (EvDFunApp df tys tms) = do { tms' <- mapM dsEvTerm tms
; return (Var df `mkTyApps` tys `mkApps` tms') }
dsEvTerm (EvCoercion (TcCoVarCo v)) = return (Var v) -- See Note [Simple coercions]
dsEvTerm (EvCoercion co) = dsTcCoercion co mkEqBox
dsEvTerm (EvTupleSel v n)
= do { tm' <- dsEvTerm v
; let scrut_ty = exprType tm'
(tc, tys) = splitTyConApp scrut_ty
Just [dc] = tyConDataCons_maybe tc
xs = mkTemplateLocals tys
the_x = getNth xs n
; -- ASSERT( isTupleTyCon tc )
return $
Case tm' (mkWildValBinder scrut_ty) (idType the_x) [(DataAlt dc, xs, Var the_x)] }
dsEvTerm (EvTupleMk tms)
= do { tms' <- mapM dsEvTerm tms
; let tys = map exprType tms'
; return $ Var (dataConWorkId dc) `mkTyApps` tys `mkApps` tms' }
where
dc = tupleCon ConstraintTuple (length tms)
dsEvTerm (EvSuperClass d n)
= do { d' <- dsEvTerm d
; let (cls, tys) = getClassPredTys (exprType d')
sc_sel_id = classSCSelId cls n -- Zero-indexed
; return $ Var sc_sel_id `mkTyApps` tys `App` d' }
where
dsEvTerm (EvDelayedError ty msg) = return $ Var errorId `mkTyApps` [ty] `mkApps` [litMsg]
where
errorId = rUNTIME_ERROR_ID
litMsg = Lit (MachStr (fastStringToByteString msg))
dsEvTerm (EvLit l) =
case l of
EvNum n -> mkIntegerExpr n
EvStr s -> mkStringExprFS s
dsEvTerm (EvTypeable ev) = dsEvTypeable ev
dsEvTypeable :: EvTypeable -> DsM CoreExpr
dsEvTypeable ev =
do tyCl <- dsLookupTyCon typeableClassName
typeRepTc <- dsLookupTyCon typeRepTyConName
let tyRepType = mkTyConApp typeRepTc []
(ty, rep) <-
case ev of
EvTypeableTyCon tc ks ->
do ctr <- dsLookupGlobalId mkPolyTyConAppName
mkTyCon <- dsLookupGlobalId mkTyConName
dflags <- getDynFlags
let mkRep cRep kReps tReps =
mkApps (Var ctr) [ cRep, mkListExpr tyRepType kReps
, mkListExpr tyRepType tReps ]
let kindRep k =
case splitTyConApp_maybe k of
Nothing -> panic "dsEvTypeable: not a kind constructor"
Just (kc,ks) ->
do kcRep <- tyConRep dflags mkTyCon kc
reps <- mapM kindRep ks
return (mkRep kcRep [] reps)
tcRep <- tyConRep dflags mkTyCon tc
kReps <- mapM kindRep ks
return ( mkTyConApp tc ks
, mkRep tcRep kReps []
)
EvTypeableTyApp t1 t2 ->
do e1 <- getRep tyCl t1
e2 <- getRep tyCl t2
ctr <- dsLookupGlobalId mkAppTyName
return ( mkAppTy (snd t1) (snd t2)
, mkApps (Var ctr) [ e1, e2 ]
)
EvTypeableTyLit ty ->
do str <- case (isNumLitTy ty, isStrLitTy ty) of
(Just n, _) -> return (show n)
(_, Just n) -> return (show n)
_ -> panic "dsEvTypeable: malformed TyLit evidence"
ctr <- dsLookupGlobalId typeLitTypeRepName
tag <- mkStringExpr str
return (ty, mkApps (Var ctr) [ tag ])
-- TyRep -> Typeable t
-- see also: Note [Memoising typeOf]
repName <- newSysLocalDs tyRepType
let proxyT = mkProxyPrimTy (typeKind ty) ty
method = bindNonRec repName rep
$ mkLams [mkWildValBinder proxyT] (Var repName)
-- package up the method as `Typeable` dictionary
return $ mkCast method $ mkSymCo $ getTypeableCo tyCl ty
where
-- co: method -> Typeable k t
getTypeableCo tc t =
case instNewTyCon_maybe tc [typeKind t, t] of
Just (_,co) -> co
_ -> panic "Class `Typeable` is not a `newtype`."
-- Typeable t -> TyRep
getRep tc (ev,t) =
do typeableExpr <- dsEvTerm ev
let co = getTypeableCo tc t
method = mkCast typeableExpr co
proxy = mkTyApps (Var proxyHashId) [typeKind t, t]
return (mkApps method [proxy])
-- This part could be cached
tyConRep dflags mkTyCon tc =
do pkgStr <- mkStringExprFS pkg_fs
modStr <- mkStringExprFS modl_fs
nameStr <- mkStringExprFS name_fs
return (mkApps (Var mkTyCon) [ int64 high, int64 low
, pkgStr, modStr, nameStr
])
where
tycon_name = tyConName tc
modl = nameModule tycon_name
pkg = modulePackageKey modl
modl_fs = moduleNameFS (moduleName modl)
pkg_fs = packageKeyFS pkg
name_fs = occNameFS (nameOccName tycon_name)
hash_name_fs
| isPromotedTyCon tc = appendFS (mkFastString "$k") name_fs
| isPromotedDataCon tc = appendFS (mkFastString "$c") name_fs
| otherwise = name_fs
hashThis = unwords $ map unpackFS [pkg_fs, modl_fs, hash_name_fs]
Fingerprint high low = fingerprintString hashThis
int64
| wORD_SIZE dflags == 4 = mkWord64LitWord64
| otherwise = mkWordLit dflags . fromIntegral
{- Note [Memoising typeOf]
~~~~~~~~~~~~~~~~~~~~~~~~~~
See #3245, #9203
IMPORTANT: we don't want to recalculate the TypeRep once per call with
the proxy argument. This is what went wrong in #3245 and #9203. So we
help GHC by manually keeping the 'rep' *outside* the lambda.
-}
---------------------------------------
dsTcCoercion :: TcCoercion -> (Coercion -> CoreExpr) -> DsM CoreExpr
-- This is the crucial function that moves
-- from TcCoercions to Coercions; see Note [TcCoercions] in Coercion
-- e.g. dsTcCoercion (trans g1 g2) k
-- = case g1 of EqBox g1# ->
-- case g2 of EqBox g2# ->
-- k (trans g1# g2#)
-- thing_inside will get a coercion at the role requested
dsTcCoercion co thing_inside
= do { us <- newUniqueSupply
; let eqvs_covs :: [(EqVar,CoVar)]
eqvs_covs = zipWith mk_co_var (varSetElems (coVarsOfTcCo co))
(uniqsFromSupply us)
subst = mkCvSubst emptyInScopeSet [(eqv, mkCoVarCo cov) | (eqv, cov) <- eqvs_covs]
result_expr = thing_inside (ds_tc_coercion subst co)
result_ty = exprType result_expr
; return (foldr (wrap_in_case result_ty) result_expr eqvs_covs) }
where
mk_co_var :: Id -> Unique -> (Id, Id)
mk_co_var eqv uniq = (eqv, mkUserLocal occ uniq ty loc)
where
eq_nm = idName eqv
occ = nameOccName eq_nm
loc = nameSrcSpan eq_nm
ty = mkCoercionType (getEqPredRole (evVarPred eqv)) ty1 ty2
(ty1, ty2) = getEqPredTys (evVarPred eqv)
wrap_in_case result_ty (eqv, cov) body
= case getEqPredRole (evVarPred eqv) of
Nominal -> Case (Var eqv) eqv result_ty [(DataAlt eqBoxDataCon, [cov], body)]
Representational -> Case (Var eqv) eqv result_ty [(DataAlt coercibleDataCon, [cov], body)]
Phantom -> panic "wrap_in_case/phantom"
ds_tc_coercion :: CvSubst -> TcCoercion -> Coercion
-- If the incoming TcCoercion if of type (a ~ b) (resp. Coercible a b)
-- the result is of type (a ~# b) (reps. a ~# b)
-- The VarEnv maps EqVars of type (a ~ b) to Coercions of type (a ~# b) (resp. and so on)
-- No need for InScope set etc because the
ds_tc_coercion subst tc_co
= go tc_co
where
go (TcRefl r ty) = Refl r (Coercion.substTy subst ty)
go (TcTyConAppCo r tc cos) = mkTyConAppCo r tc (map go cos)
go (TcAppCo co1 co2) = mkAppCo (go co1) (go co2)
go (TcForAllCo tv co) = mkForAllCo tv' (ds_tc_coercion subst' co)
where
(subst', tv') = Coercion.substTyVarBndr subst tv
go (TcAxiomInstCo ax ind cos)
= AxiomInstCo ax ind (map go cos)
go (TcPhantomCo ty1 ty2) = UnivCo (fsLit "ds_tc_coercion") Phantom ty1 ty2
go (TcSymCo co) = mkSymCo (go co)
go (TcTransCo co1 co2) = mkTransCo (go co1) (go co2)
go (TcNthCo n co) = mkNthCo n (go co)
go (TcLRCo lr co) = mkLRCo lr (go co)
go (TcSubCo co) = mkSubCo (go co)
go (TcLetCo bs co) = ds_tc_coercion (ds_co_binds bs) co
go (TcCastCo co1 co2) = mkCoCast (go co1) (go co2)
go (TcCoVarCo v) = ds_ev_id subst v
go (TcAxiomRuleCo co ts cs) = AxiomRuleCo co (map (Coercion.substTy subst) ts) (map go cs)
go (TcCoercion co) = co
ds_co_binds :: TcEvBinds -> CvSubst
ds_co_binds (EvBinds bs) = foldl ds_scc subst (sccEvBinds bs)
ds_co_binds eb@(TcEvBinds {}) = pprPanic "ds_co_binds" (ppr eb)
ds_scc :: CvSubst -> SCC EvBind -> CvSubst
ds_scc subst (AcyclicSCC (EvBind v ev_term))
= extendCvSubstAndInScope subst v (ds_co_term subst ev_term)
ds_scc _ (CyclicSCC other) = pprPanic "ds_scc:cyclic" (ppr other $$ ppr tc_co)
ds_co_term :: CvSubst -> EvTerm -> Coercion
ds_co_term subst (EvCoercion tc_co) = ds_tc_coercion subst tc_co
ds_co_term subst (EvId v) = ds_ev_id subst v
ds_co_term subst (EvCast tm co) = mkCoCast (ds_co_term subst tm) (ds_tc_coercion subst co)
ds_co_term _ other = pprPanic "ds_co_term" (ppr other $$ ppr tc_co)
ds_ev_id :: CvSubst -> EqVar -> Coercion
ds_ev_id subst v
| Just co <- Coercion.lookupCoVar subst v = co
| otherwise = pprPanic "ds_tc_coercion" (ppr v $$ ppr tc_co)
{-
Note [Simple coercions]
~~~~~~~~~~~~~~~~~~~~~~~
We have a special case for coercions that are simple variables.
Suppose cv :: a ~ b is in scope
Lacking the special case, if we see
f a b cv
we'd desguar to
f a b (case cv of EqBox (cv# :: a ~# b) -> EqBox cv#)
which is a bit stupid. The special case does the obvious thing.
This turns out to be important when desugaring the LHS of a RULE
(see Trac #7837). Suppose we have
normalise :: (a ~ Scalar a) => a -> a
normalise_Double :: Double -> Double
{-# RULES "normalise" normalise = normalise_Double #-}
Then the RULE we want looks like
forall a, (cv:a~Scalar a).
normalise a cv = normalise_Double
But without the special case we generate the redundant box/unbox,
which simpleOpt (currently) doesn't remove. So the rule never matches.
Maybe simpleOpt should be smarter. But it seems like a good plan
to simply never generate the redundant box/unbox in the first place.
-}
|
spinda/liquidhaskell
|
src/Language/Haskell/Liquid/Desugar710/DsBinds.hs
|
Haskell
|
bsd-3-clause
| 46,621
|
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Network.EasyBitcoin.BitcoinUnits
( btc
, mBTC
, satoshis
, asBtc
, asMbtc
, asSatoshis
, showAsBtc
, showAsMbtc
, showAsSatoshis
, BTC()
)where
import Network.EasyBitcoin.NetworkParams
import Network.EasyBitcoin.Internal.InstanciationHelpers
import Control.Arrow(first)
import Control.Applicative((<$>))
import Data.Aeson
-- | Bitcoins are represented internally as an integer value, but showed and read as a decimal values.
-- When importing them, extra significative digits will be silently dropped.
newtype BTC a = Satoshis Int deriving (Eq,Ord,Num)
btc :: Double -> BTC net
btc x = Satoshis $ round (x*100000000)
mBTC :: Double -> BTC net
mBTC x = Satoshis $ round (x*100000)
satoshis :: Int -> BTC net
satoshis = Satoshis
asBtc :: BTC net -> Double
asBtc (Satoshis x) = fromIntegral x/100000000
asMbtc :: BTC net -> Double
asMbtc (Satoshis x) = fromIntegral x /100000
asSatoshis :: BTC net -> Int
asSatoshis (Satoshis x) = x
showAsBtc :: BTC net -> String
showAsBtc (Satoshis x) = let str = reverse (show x) ++ replicate 9 '0'
(smallers,biggers) = splitAt 8 str
in if all (=='0') biggers
then "0." ++ reverse smallers
else dropWhile (=='0') $ reverse biggers ++ "." ++ reverse smallers
showAsMbtc :: BTC net -> String
showAsMbtc (Satoshis x) = let str = reverse (show x) ++ replicate 6 '0'
(smallers,biggers) = splitAt 5 str
in if all (=='0') biggers
then "0." ++ reverse smallers
else dropWhile (=='0') $ reverse biggers ++ "." ++ reverse smallers
showAsSatoshis :: BTC net -> String
showAsSatoshis = show.asSatoshis
instance Show (BTC a) where
show = showAsBtc
instance Read (BTC a) where
readsPrec n str = first btc <$> (readsPrec n str:: [(Double,String)])
instance ToJSON (BTC a) where
toJSON = toJSON.asBtc
|
vwwv/easy-bitcoin
|
Network/EasyBitcoin/BitcoinUnits.hs
|
Haskell
|
bsd-3-clause
| 2,212
|
module Tunagui.Widget.Component.Part
(
ClickableArea (..)
, mkClickableArea
, TextContent (..)
, mkTextContent
) where
import Control.Monad (void)
import Control.Monad.IO.Class (liftIO)
import Control.Concurrent (forkIO)
import Control.Concurrent.MVar
import FRP.Sodium
import qualified Data.Text as T
import Linear.V2
import Data.Maybe (fromMaybe)
import Graphics.UI.SDL.TTF.FFI (TTFFont)
import qualified Tunagui.General.Data as D
import Tunagui.General.Types (Point(..), Size(..), Shape(..), within)
import qualified Tunagui.Internal.Render as R
import Tunagui.Internal.Render (runRender)
data ClickableArea = ClickableArea
{ clickEvent :: Event (Point Int)
, crossBoundary :: Event Bool
}
mkClickableArea ::
Behavior (Point Int) ->
Behavior (Shape Int) ->
Event (Point Int) ->
Event (Point Int) ->
Event (Point Int) -> -- Mouse motion
Reactive ClickableArea
mkClickableArea bPos bShape eClick eRelease eMotion = do
behWaitingRls <- hold False ((const True <$> eClkOn) `merge` (const False <$> eRelease))
let eClk = (fst . fst) <$> filterE snd (snapshot (,) eRlsOn behWaitingRls)
ClickableArea
<$> pure eClk
<*> mkMotion
where
within' = uncurry within
bArea = (,) <$> bPos <*> bShape
-- Click
eClkOn = filterE within' $ snapshot (,) eClick bArea
eRlsOn = filterE within' $ snapshot (,) eRelease bArea
-- Motion
mkMotion = do
(behPre, pushPre) <- newBehavior False
_ <- listen eMotionOn $ void . forkIO . sync . pushPre
return $ fst <$> filterE (uncurry (/=)) (snapshot (,) eMotionOn behPre)
where
eMotionOn = within' <$> snapshot (,) eMotion bArea
data TextContent = TextContent
{ tcText :: Behavior T.Text
, tcWidth :: Behavior Int
, tcHeight :: Behavior Int
--
, modifyText :: (T.Text -> T.Text) -> Reactive ()
}
mkTextContent :: D.Window -> TTFFont -> Maybe T.Text -> Reactive TextContent
mkTextContent win font mtext = do
(behCW, pushCW) <- newBehavior 0
(behCH, pushCH) <- newBehavior 0
(behText, pushText) <- newBehavior $ T.pack ""
_ <- listen (updates behText) $ \text ->
void . forkIO $ do
(S (V2 w h)) <- withMVar (D.wRenderer win) $ \r ->
runRender r $ R.textSize font text
liftIO . sync $ do
pushCW w
pushCH h
pushText $ fromMaybe (T.pack "") mtext
return TextContent
{ tcText = behText
, tcWidth = behCW
, tcHeight = behCH
--
, modifyText = \f -> pushText . f =<< sample behText
}
|
masatoko/tunagui
|
src/Tunagui/Widget/Component/Part.hs
|
Haskell
|
bsd-3-clause
| 2,600
|
import Language.Mira.RegExpParser as Parser
import Control.Monad
import System.Environment
main = liftM head getArgs >>= print . Parser.regex . Parser.lexer
|
AidanDelaney/Mira
|
src/examples/ParserExample.hs
|
Haskell
|
bsd-3-clause
| 158
|
{-# LANGUAGE ViewPatterns #-}
module Lib
( someFunc
, Point
, LineSegment
, distance
, perpendicularDistance
, splitAtMaxDistance
, douglasPeucker
) where
import Data.Sequence as D
type Point = (Double,Double)
type LineSegment = (Point,Point)
distance :: Point -> Point -> Double
distance (x1,y1) (x2,y2) = sqrt(((x1 - x2) ^ 2) + ((y1 - y2) ^ 2))
-- http://paulbourke.net/geometry/pointlineplane/DistancePoint.java
perpendicularDistance :: Point -> LineSegment -> Double
perpendicularDistance p@(pX, pY) (a@(aX, aY), b@(bX, bY))
| a == b = distance p a
| u < 0 = distance p a
| u > 1 = distance p b
| otherwise = distance p (aX + u * deltaX, aY + u * deltaY)
where
(deltaX, deltaY) = (bX - aX, bY - aY)
u = ((pX - aX) * deltaX + (pY - aY) * deltaY) / (deltaX * deltaX + deltaY * deltaY)
-- https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm
douglasPeucker :: Double -> Seq Point -> Seq Point
douglasPeucker epsilon points
| points == D.empty = D.empty
| dmax > epsilon = douglasPeucker epsilon left >< allButFirst(douglasPeucker epsilon right)
| otherwise = first points <| Lib.last points <| D.empty
where
(left, right) = (D.take index points, D.drop (index - 1) points)
(dmax, index) = splitAtMaxDistance points
splitAtMaxDistance :: Seq Point -> (Double, Int)
splitAtMaxDistance points =
D.foldlWithIndex (\(max, index) ni a -> if cp a ls > max then (cp a ls, ni + 1) else (max, index)) (0.0, D.length points) points
where
ls = (first points, Lib.last points)
cp = perpendicularDistance
last :: Seq a -> a
last (viewr -> xs :> x) = x
first :: Seq a -> a
first (viewl -> x :< xs) = x
allButFirst :: Seq a -> Seq a
allButFirst (viewl -> x :< xs) = xs
-- douglasPeucker 1.0 (fromList [(0.0,0.0),(1.0,0.1), (2.0,-0.1),(3.0,5.0), (4.0,6.0),(5.0,7.0), (6.0,8.1),(7.0,9.0), (8.0,9.0),(9.0,9.0)])
-- fromList [(0.0,0.0),(2.0,-0.1),(3.0,5.0),(7.0,9.0),(9.0,9.0)]
someFunc :: IO ()
someFunc = putStrLn "someFunc"
|
newmana/simplify
|
src/Lib.hs
|
Haskell
|
bsd-3-clause
| 2,067
|
import qualified Data.List
is_int x = x == fromInteger (round x)
calc_min_path :: Integer -> Integer -> Integer -> Double
calc_min_path w l h = (sqrt . fromInteger . minimum) [
l^2 + (w+h)^2,
w^2 + (l+h)^2,
h^2 + (l+w)^2]
calc_n_int_min_paths_up_to :: Integer -> Integer
calc_n_int_min_paths_up_to m =
(toInteger . length) $ filter
is_int
[calc_min_path w l h
| w <- [1..m]
, l <- [w..m]
, h <- [l..m]]
add_new_m :: Integer -> Integer -> Integer
add_new_m m m_minus_one_value =
m_minus_one_value + ((toInteger . length) $ filter is_int min_paths)
where min_paths = [calc_min_path w l h | w <- [1..m], l <- [w..m], h <- [m]]
subtract_new_m :: Integer -> Integer -> Integer
subtract_new_m m m_plus_one_value =
m_plus_one_value - ((toInteger . length) $ filter is_int min_paths)
where min_paths = [calc_min_path w l h | w <- [1..(m+1)], l <- [w..(m+1)], h <- [m+1]]
add_new_m_pow_2 :: Integer -> Integer
add_new_m_pow_2 m =
(toInteger . length) $ filter is_int min_paths
where min_paths = [calc_min_path w l h | h <- [((m `div` 2) + 1)..m], w <- [1..h], l <- [w..h]]
add_new_m_given_lower_m :: Integer -> Integer -> Integer
add_new_m_given_lower_m m lower_m =
(toInteger . length) $ filter is_int min_paths
where min_paths = [calc_min_path w l h | h <- [(lower_m + 1)..m], w <- [1..h], l <- [w..h]]
bsearch :: Integer -> Integer -> Integer -> Integer -> Integer -> [Integer]
bsearch lb m ub bound lb_num_paths =
case n_paths `compare` bound of
LT -> case n_paths_succ `compare` bound of
LT -> m : (bsearch (m+1) case_lt_m ub bound n_paths_succ)
EQ -> [m + 2]
GT -> [m + 1]
EQ -> [m + 1]
GT -> m : (bsearch lb case_gt_m m bound lb_num_paths)
where n_paths = lb_num_paths + (add_new_m_given_lower_m m lb)
n_paths_succ = (add_new_m (m+1) n_paths)
case_lt_m = (m + ub) `div` 2
case_gt_m = (lb + m) `div` 2
initial_ms = map (2^) [0..]
n_paths = scanl1 (+) $ map add_new_m_pow_2 initial_ms
n_paths_with_ms = zipWith (\m -> \x -> (m, x)) initial_ms n_paths
bound = 1000000
--first_m_over = (\(Just x) -> fst x) (Data.List.find
-- (\(m, x) -> x > bound)
-- n_paths_with_ms)
first_m_over = 2048 -- calculated via above formula
ub = first_m_over
lb = first_m_over `div` 2
curr_m = (ub + lb) `div` 2
sought = bsearch lb curr_m ub bound (calc_n_int_min_paths_up_to lb)
main = do
(putStrLn . show) sought
|
bgwines/project-euler
|
src/solved/problem86.hs
|
Haskell
|
bsd-3-clause
| 2,525
|
{-# LANGUAGE UnicodeSyntax #-}
module Shake.It.Rust
( module Rust
) where
import Shake.It.Rust.Cargo as Rust
|
Heather/Shake.it.off
|
src/Shake/It/Rust.hs
|
Haskell
|
bsd-3-clause
| 125
|
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE TemplateHaskell #-}
module Test.Examples.IArraySpec
( spec
) where
import Test.Hspec (Spec, describe, it)
import Test.QuickCheck (NonNegative (..), Property, Small (..), property, (==>))
import Universum
import Test.Arbitrary ()
import Test.Execution (describeExecWays, (>-*->))
import Test.Util (VerySmall (..))
import Toy.Base
import Toy.Execution (ExecWay (..), Executable, TranslateToSM, defCompileX86,
transShow, translateLang, (<~~>))
import Toy.Exp
import Toy.Lang (Stmt (..))
import qualified Toy.Lang as L
spec :: Spec
spec = do
let ways :: forall l. (Executable l, Show l, TranslateToSM l) => [ExecWay l]
ways =
[ Ex transShow
, Ex translateLang
, Ex $ translateLang <~~> defCompileX86
]
describeExecWays ways $ \way -> do
describe "examples" $ do
describe "arrays" $ do
it "allocation" $
property $ arrayAllocTest way
it "allocation of two arrays subsequently" $
property $ arrayAlloc2Test way
it "arrlen" $
property $ arrayLengthTest way
it "simple" $
property $ arraySimpleTest way
it "safe store" $
property $ safeStoreTest way
it "deep" $
property $ arrayDeepTest way
it "long nested" $
property $ arrayLongNestedTest way
it "set gc" $
property $ arraySetGcTest way
describeExecWays ways $ \way -> do
describe "examples" $ do
describe "arrays" $ do
describe "funs" $ do
it "array argument" $
arrayArgTest way
it "array return" $
arrayReturnTest way
arrayAllocTest :: ExecWay Stmt -> Property
arrayAllocTest = sample & [] >-*-> []
where
sample = "a" `L.storeArrayS` []
arrayAlloc2Test :: ExecWay Stmt -> Property
arrayAlloc2Test = sample & [] >-*-> []
where
sample = mconcat . replicate 2 $ "a" `L.storeArrayS` []
arrayLengthTest :: ExecWay Stmt -> (NonNegative (Small Value)) -> Property
arrayLengthTest way (NonNegative (Small k)) =
sample & [] >-*-> [k] $ way
where
sample = L.writeS $ FunE "arrlen" [ArrayUninitE $ fromIntegral k]
arraySimpleTest :: ExecWay Stmt -> (NonNegative (Small Value)) -> Property
arraySimpleTest way (NonNegative (Small k)) =
k `elem` range ==> ([k] >-*-> [k]) sample way
where
sample = mconcat
[ "a" `L.storeArrayS` (ValueE <$> range)
, "i" := readE
, L.writeS ("a" !!: "i")
]
range = [0 .. 5]
safeStoreTest :: ExecWay Stmt -> Property
safeStoreTest = sample & [] >-*-> [11]
where
sample = mconcat
[ "a" `L.storeArrayS` [11]
, "a" := "a"
, L.writeS ("a" !!: 0)
]
arrayDeepTest :: ExecWay Stmt
-> NonNegative (VerySmall Value)
-> NonNegative (VerySmall Value)
-> Property
arrayDeepTest way (NonNegative (VerySmall k1)) (NonNegative (VerySmall k2)) =
k1 == k2 ==> ([] >-*-> [7]) sample way
where
sample = mconcat
[ "a" := 7
, mconcat . replicate (fromIntegral k1) $ -- {{{... 1 ...}}}
("a" :=) `L.arrayS` ["a"]
, L.forS ("i" := 0, "i" <: ValueE k2, "i" := "i" + 1) $
"a" := "a" !!: 0
, L.writeS "a"
]
arrayLongNestedTest :: ExecWay Stmt -> ([Value], [Value]) -> Property
arrayLongNestedTest way (vs0, vs1) = sample & [] >-*-> [100500] $ way
where
sample = mconcat
[ "a0" `L.storeArrayS` (ValueE <$> vs0)
, "a1" `L.storeArrayS` (ValueE <$> vs1)
, "a" `L.storeArrayS` ["a0", "a1"]
, L.writeS 100500
]
arraySetGcTest :: ExecWay Stmt -> Property
arraySetGcTest = sample & [] >-*-> []
where
sample = mconcat
[ "a0" `L.storeArrayS` (ValueE <$> [1])
, "a0_" `L.storeArrayS` (ValueE <$> [2])
, "a" `L.storeArrayS` ["a0"]
, ArrayAssign "a" 0 "a0_"
]
arrayArgTest :: ExecWay L.Program -> Property
arrayArgTest = sample & [] >-*-> [5]
where
fun = ("lol", (FunSign "lol" ["x"], L.writeS $ ArrayAccessE "x" 0))
sample =
L.Program [fun] $ mconcat
[ "a" `L.storeArrayS` [5]
, L.funCallS "lol" ["a"]
]
arrayReturnTest :: ExecWay L.Program -> Property
arrayReturnTest = sample & [] >-*-> [7]
where
fun = ("lol", (FunSign "lol" [], L.Return `L.arrayS` [7]))
sample =
L.Program [fun] $ mconcat
[ L.writeS $ FunE "lol" [] `ArrayAccessE` 0
]
|
Martoon-00/toy-compiler
|
test/Test/Examples/IArraySpec.hs
|
Haskell
|
bsd-3-clause
| 4,920
|
-- |
-- Module : Crypto.Hash.MD2
-- License : BSD-style
-- Maintainer : Vincent Hanquez <vincent@snarc.org>
-- Stability : experimental
-- Portability : unknown
--
-- module containing the binding functions to work with the
-- MD2 cryptographic hash.
--
{-# LANGUAGE ForeignFunctionInterface #-}
module Crypto.Hash.MD2 ( MD2 (..) ) where
import Crypto.Hash.Types
import Foreign.Ptr (Ptr)
import Data.Word (Word8, Word32)
-- | MD2 cryptographic hash algorithm
data MD2 = MD2
deriving (Show)
instance HashAlgorithm MD2 where
hashBlockSize _ = 16
hashDigestSize _ = 16
hashInternalContextSize _ = 96
hashInternalInit = c_md2_init
hashInternalUpdate = c_md2_update
hashInternalFinalize = c_md2_finalize
foreign import ccall unsafe "cryptonite_md2_init"
c_md2_init :: Ptr (Context a)-> IO ()
foreign import ccall "cryptonite_md2_update"
c_md2_update :: Ptr (Context a) -> Ptr Word8 -> Word32 -> IO ()
foreign import ccall unsafe "cryptonite_md2_finalize"
c_md2_finalize :: Ptr (Context a) -> Ptr (Digest a) -> IO ()
|
nomeata/cryptonite
|
Crypto/Hash/MD2.hs
|
Haskell
|
bsd-3-clause
| 1,139
|
module LibrarySpec where
import qualified Data.Matrix as Mx
import qualified Data.Vector as Vec
import Library
import Test.Hspec
suite :: SpecWith ()
suite =
describe "Library" $ do
it "compares 0.1 + 0.2 = 0.3" $
nearZero (0.3 - (0.1 + 0.2)) `shouldBe` True
it "finds correct L∞ norm of (0, -5, 3)" $
lInftyNorm (Vec.fromList [0, -5, 3]) `shouldBe` 5
it "finds correct L∞ norm of (-1, 3)" $
lInftyNorm (Vec.fromList [-1, 3]) `shouldBe` 3
it "find correct L∞ unit vector of (0, 5)" $
toLInftyNormUnit (Vec.fromList [0, 5]) `shouldBe` Vec.fromList [0, 1]
it "find correct L∞ unit vector of (3, -5)" $
toLInftyNormUnit (Vec.fromList [3, -5]) `shouldBe` Vec.fromList [0.6, -1]
it "multiplies {{3, 4}, {2, 8}} by (1, 2)" $
Mx.fromLists [[3, 4], [2, 8]] `mulMxByVec` Vec.fromList [1, 2] `shouldBe` Vec.fromList [11, 18]
|
hrsrashid/nummet
|
tests/LibrarySpec.hs
|
Haskell
|
bsd-3-clause
| 913
|
{-# LANGUAGE FlexibleInstances #-}
{-|
Module : $Header$
CopyRight : (c) 8c6794b6, 2011, 2012
License : BSD3
Maintainer : 8c6794b6@gmail.com
Stability : experimental
Portability : portable
Benchmark for comparing FFT with repa-fftw to repa-algorithms.
-}
module Main where
import Control.DeepSeq (NFData(..))
import Data.Complex
import System.Random
import Criterion.Main
import Data.Array.Repa ((:.)(..), Array, U, DIM1, Z(..))
import Data.Array.Repa.Repr.ForeignPtr (F)
import qualified Data.Array.Repa as R
import qualified Data.Array.Repa.Eval as Eval
import qualified Data.Array.Repa.Algorithms.FFT as FFT
import qualified Data.Array.Repa.FFTW as FFTW
type RFFTArr = Array U DIM1 (Double, Double)
main :: IO ()
main = do
rs <- randomRs (0,1) `fmap` newStdGen
is <- randomRs (0,1) `fmap` newStdGen
let bench_fft n =
let mkarr ks = Eval.fromList (Z:.n) $ take n ks
ts = R.fromListUnboxed (Z:.n) $ take n $ zip rs is
cs = mkarr $ zipWith (:+) rs is
ra = FFT.fft1dP FFT.Forward :: RFFTArr -> IO RFFTArr
in ts `seq` cs `seq`
bgroup ("n="++show n)
[ bench "repa-algorithms" (nfIO (ra ts))
, bench "repa-fftw" (nf FFTW.fft cs)
]
defaultMain $ map (\k -> bench_fft (2^k)) [9..13::Int]
instance NFData (Array U DIM1 (Double, Double)) where
rnf arr = arr `R.deepSeqArray` ()
instance NFData (Array F DIM1 (Complex Double)) where
rnf arr = arr `R.deepSeqArray` ()
|
8c6794b6/repa-fftw
|
exec/bench.hs
|
Haskell
|
bsd-3-clause
| 1,499
|
module CradleSpec where
import Control.Applicative
import Data.List (isSuffixOf)
import Language.Haskell.GhcMod.Cradle
import Language.Haskell.GhcMod.Types
import System.Directory (canonicalizePath,getCurrentDirectory)
import System.FilePath ((</>), pathSeparator)
import Test.Hspec
import Dir
spec :: Spec
spec = do
describe "findCradle" $ do
it "returns the current directory" $ do
withDirectory_ "/" $ do
curDir <- stripLastDot <$> canonicalizePath "/"
res <- findCradle
res `shouldBe` Cradle {
cradleCurrentDir = curDir
, cradleRootDir = curDir
, cradleCabalFile = Nothing
, cradlePkgDbStack = [GlobalDb]
}
it "finds a cabal file and a sandbox" $ do
cwd <- getCurrentDirectory
withDirectory "test/data/subdir1/subdir2" $ \dir -> do
res <- relativeCradle dir <$> findCradle
res `shouldBe` Cradle {
cradleCurrentDir = "test" </> "data" </> "subdir1" </> "subdir2"
, cradleRootDir = "test" </> "data"
, cradleCabalFile = Just ("test" </> "data" </> "cabalapi.cabal")
, cradlePkgDbStack = [GlobalDb, PackageDb (cwd </> "test/data/.cabal-sandbox/i386-osx-ghc-7.6.3-packages.conf.d")]
}
it "works even if a sandbox config file is broken" $ do
withDirectory "test/data/broken-sandbox" $ \dir -> do
res <- relativeCradle dir <$> findCradle
res `shouldBe` Cradle {
cradleCurrentDir = "test" </> "data" </> "broken-sandbox"
, cradleRootDir = "test" </> "data" </> "broken-sandbox"
, cradleCabalFile = Just ("test" </> "data" </> "broken-sandbox" </> "dummy.cabal")
, cradlePkgDbStack = [GlobalDb, UserDb]
}
relativeCradle :: FilePath -> Cradle -> Cradle
relativeCradle dir cradle = cradle {
cradleCurrentDir = toRelativeDir dir $ cradleCurrentDir cradle
, cradleRootDir = toRelativeDir dir $ cradleRootDir cradle
, cradleCabalFile = toRelativeDir dir <$> cradleCabalFile cradle
}
-- Work around GHC 7.2.2 where `canonicalizePath "/"` returns "/.".
stripLastDot :: FilePath -> FilePath
stripLastDot path
| (pathSeparator:'.':"") `isSuffixOf` path = init path
| otherwise = path
|
carlohamalainen/ghc-mod
|
test/CradleSpec.hs
|
Haskell
|
bsd-3-clause
| 2,487
|
-- | This module provides automatic differentiation for Quantities.
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
module Numeric.Units.Dimensional.AD (FAD, diff, Lift (lift), undim, todim) where
import Numeric.Units.Dimensional (Dimensional (Dimensional), Quantity, type (/))
import Numeric.Units.Dimensional.Coercion
import Numeric.AD (AD, Mode, auto, Scalar)
import qualified Numeric.AD (diff)
import Numeric.AD.Mode.Forward (Forward)
-- | Unwrap a Dimensional's numeric representation.
undim :: Quantity d a -> a
undim = coerce
todim :: a -> Quantity d a
todim = coerce
type FAD tag a = AD tag (Forward a)
-- | @diff f x@ computes the derivative of the function @f(x)@ for the
-- given value of @x@.
diff :: Num a
=> (forall tag. Quantity d1 (FAD tag a) -> Quantity d2 (FAD tag a))
-> Quantity d1 a -> Quantity ((/) d2 d1) a
diff f = todim . Numeric.AD.diff (undim . f . todim) . undim
-- | Class to provide 'Numeric.AD.lift'ing of constant data structures
-- (data structures with numeric constants used in a differentiated
-- function).
class Lift w where
-- | Embed a constant data structure.
lift :: (Mode t) => w (Scalar t) -> w t
instance Lift (Quantity d)
where lift = todim . auto . undim
|
bjornbm/dimensional-experimental
|
src/Numeric/Units/Dimensional/AD.hs
|
Haskell
|
bsd-3-clause
| 1,353
|
-----------------------------------------------------------------------------
-- Kind: Kinds
--
-- Part of `Typing Haskell in Haskell', version of November 23, 2000
-- Copyright (c) Mark P Jones and the Oregon Graduate Institute
-- of Science and Technology, 1999-2000
--
-- This program is distributed as Free Software under the terms
-- in the file "License" that is included in the distribution
-- of this software, copies of which may be obtained from:
-- http://www.cse.ogi.edu/~mpj/thih/
--
-----------------------------------------------------------------------------
module Kind where
import PPrint
data Kind = Star | Kfun Kind Kind
deriving Eq
instance PPrint Kind where
pprint = ppkind 0
parPprint = ppkind 10
ppkind :: Int -> Kind -> Doc
ppkind d Star = text "Star"
ppkind d (Kfun l r) = ppParen (d>=10)
(text "Kfun" <+> ppkind 10 l <+> ppkind 0 r)
-----------------------------------------------------------------------------
|
elben/typing-haskell-in-haskell
|
Kind.hs
|
Haskell
|
bsd-3-clause
| 1,053
|
{-# LANGUAGE Rank2Types, TypeFamilies, FlexibleContexts, UndecidableInstances #-}
import Data.Reflection -- from reflection
import Data.Monoid -- from base
import Data.Proxy -- from tagged
-- | Values in our dynamically constructed monoid over 'a'
newtype M a s = M { runM :: a } deriving (Eq,Ord)
-- | A dictionary describing the contents of a monoid
data Monoid_ a = Monoid_ { mappend_ :: a -> a -> a, mempty_ :: a }
instance Reifies s (Monoid_ a) => Monoid (M a s) where
mappend a b = M $ mappend_ (reflect a) (runM a) (runM b)
mempty = a where a = M $ mempty_ (reflect a)
-- > ghci> withMonoid (+) 0 $ mempty <> M 2
-- > 2
withMonoid :: (a -> a -> a) -> a -> (forall s. Reifies s (Monoid_ a) => M a s) -> a
withMonoid f z v = reify (Monoid_ f z) (runM . asProxyOf v)
asProxyOf :: f s -> Proxy s -> f s
asProxyOf a _ = a
|
ehird/reflection
|
examples/Monoid.hs
|
Haskell
|
bsd-3-clause
| 849
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
-- | Test interaction between parsing output and logstash
module Logstash where
import Control.Monad
import Control.Monad.Logger
import Control.Monad.Reader
import qualified Data.Aeson as Aeson
import qualified Data.ByteString.Lazy as BSL
import qualified Data.HashMap.Strict as HMap
import Data.Monoid
import Data.Text ( Text )
import qualified Data.Text as Text
import qualified Data.Text.Encoding as Text
import Logging
import NejlaCommon
import Shelly
import Test.Hspec.Expectations
import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.TH
-- Set the default string type to Text so we don't get ambiguity errors
default ( Text )
exampleInput :: Text
exampleInput = "[Debug#test] test123\n[Debug#test] test345\n"
logstashConfNames :: [Text]
logstashConfNames =
[ "1-input-stdin.conf", "2-filter-parse-logs.conf", "3-output-stdout.conf" ]
mkLogsstashConfPaths :: Text -> Text -> (Text, Text)
mkLogsstashConfPaths pwd name =
(pwd <> "/tests/logstash/conf.d/" <> name, "/etc/logstash/conf.d/" <> name)
confVolume :: Text -> Text -> [Text]
confVolume pwd name =
[ "-v"
, let (lPath, dPath) = mkLogsstashConfPaths pwd name
in lPath <> ":" <> dPath
]
checkConfFiles :: Sh ()
checkConfFiles = do
workdir <- toTextIgnore <$> pwd
forM_ logstashConfNames $ \name -> do
let (path, _) = mkLogsstashConfPaths workdir name
unlessM (test_f $ fromText path) . terror $
"File" <> path <> " does not exist"
docker :: Text -> [Text] -> Sh Text
docker cmnd args = command "docker" [ cmnd ] args
logstash :: [Text] -> Sh Text
logstash parameters = do
workdir <- toTextIgnore <$> pwd
docker "run" $
concat [ [ "--rm", "-i" ]
, concat $ confVolume workdir <$> logstashConfNames
, [ "elk_logstash", "logstash", "-f", "/etc/logstash/conf.d" ]
, parameters
]
runLogstash :: MonadIO m => IORefLogger a -> m [Text]
runLogstash f = shelly . silently $ do
checkConfFiles
logs <- liftIO $ captureLogs f
setStdin . Text.unlines $ Text.decodeUtf8 <$> logs
out <- logstash [ "-w", "1", "--quiet", "-l", "/dev/null" ]
stripped
<- case Text.stripPrefix "Sending logstash logs to /dev/null.\n" out of
Nothing -> terror "Expected output prefix \
\ \"Sending logstash logs to /dev/null.\\n\""
Just s -> return s
return $ splitLines stripped
where
splitLines lines = case Text.breakOn "}{" lines of
(rest, "") -> [ rest ]
(first, last) -> (first <> "}") : splitLines (Text.drop 1 last)
case_logstash :: IO ()
case_logstash = do
res <- runLogstash $ do
logEvent logTest1
logWarnNS "database" "foo"
let rows = Aeson.decode . BSL.fromStrict . Text.encodeUtf8 <$> res
case rows of
[ Just (Aeson.Object row1), Just (Aeson.Object row2) ] -> do
withRow row1 $ do
"event" `shouldDecodeTo` ("test" :: Text)
"time" `shouldDecodeTo` log1TestTime
"level" `shouldDecodeTo` (5 :: Int)
"foo" `shouldDecodeTo` False
"bar" `shouldDecodeTo` True
"parsed_json" `shouldDecodeTo` True
withRow row2 $ do
"type" `shouldDecodeTo` ("logs" :: Text)
"component" `shouldDecodeTo` ("database" :: Text)
"level" `shouldDecodeTo` (4 :: Int)
"message" `shouldDecodeTo` ("foo" :: Text)
_ -> assertFailure $ "Expected 1 row, instead got "
<> unlines (Text.unpack <$> res)
where
shouldDecodeTo x y = ReaderT $ \o -> case HMap.lookup x o of
Nothing -> assertFailure $ "could not find element" <> show x
Just v -> case Aeson.fromJSON v of
Aeson.Error e ->
assertFailure $ "Could not decode " <> show x <> " because " <> e
Aeson.Success v -> v `shouldBe` y
withRow row m = runReaderT m row
tests :: TestTree
tests = $testGroupGenerator
|
nejla/nejla-common
|
tests/Logstash.hs
|
Haskell
|
bsd-3-clause
| 4,103
|
{-# LANGUAGE StandaloneDeriving,DeriveFunctor #-}
module Main where
import GameDSL hiding (Rule,Action)
import qualified GameDSL as GameDSL (Rule,Action)
import Graphics.Gloss
import Control.Monad (guard)
data Tag = Selected | Stone
deriving instance Eq Tag
deriving instance Ord Tag
deriving instance Show Tag
data Attribute = XPosition | YPosition
deriving instance Eq Attribute
deriving instance Ord Attribute
deriving instance Show Attribute
type Rule = GameDSL.Rule Tag Attribute
type Action = GameDSL.Action Tag Attribute
move :: Rule
move = do
selected <- entityTagged Selected
x <- getAttribute XPosition selected
y <- getAttribute YPosition selected
(dx,dy) <- for [(1,0),(-1,0),(0,1),(0,-1)]
let (nx,ny) = (x + dx, y + dy)
(tx,ty) = (nx + dx, ny + dy)
other <- stoneAt nx ny
ensureNot (stoneAt tx ty)
return (trigger (clickInRect (fieldRect tx ty) (do
delete other
setAttribute XPosition selected tx
setAttribute YPosition selected ty)))
stoneAt :: Integer -> Integer -> Query Tag Attribute Entity
stoneAt x y = do
stone <- entityTagged Stone
x' <- getAttribute XPosition stone
y' <- getAttribute YPosition stone
guard (x == x')
guard (y == y')
return stone
select :: Rule
select = do
stone <- entityTagged Stone
x <- getAttribute XPosition stone
y <- getAttribute YPosition stone
selected <- entityTagged Selected
return (trigger (clickInRect (fieldRect x y) (do
unsetTag Selected selected
setTag Selected stone)))
setupBoard :: Action ()
setupBoard = do
mapM_ (uncurry newStone) (
[(x,y) | x <- [-1,0,1], y <- [-1,0,1], not (x == 0 && y == 0)] ++
[(x,y) | x <- [-1,0,1], y <- [2,3]] ++
[(x,y) | x <- [-1,0,1], y <- [-2,-3]] ++
[(x,y) | x <- [2,3], y <- [-1,0,1]] ++
[(x,y) | x <- [-2,-3], y <- [-1,0,1]])
setTag Selected 0
newStone :: Integer -> Integer -> Action ()
newStone x y = do
stone <- new
setTag Stone stone
setAttribute XPosition stone x
setAttribute YPosition stone y
renderStone :: Rule
renderStone = do
stone <- entityTagged Stone
x <- getAttribute XPosition stone
y <- getAttribute YPosition stone
return (draw (translate (fieldCoordinate x) (fieldCoordinate y) (circleSolid 20)))
renderSelected :: Rule
renderSelected = do
selected <- entityTagged Selected
x <- getAttribute XPosition selected
y <- getAttribute YPosition selected
return (draw (translate (fieldCoordinate x) (fieldCoordinate y) (color red (circleSolid 18))))
fieldRect :: Integer -> Integer -> Rect
fieldRect x y = Rect (fieldCoordinate x) (fieldCoordinate y) 40 40
fieldCoordinate :: Integer -> Float
fieldCoordinate x = fromIntegral x * 40
main :: IO ()
main = runGame setupBoard [select,move,renderStone,renderSelected]
|
phischu/game-dsl
|
peg-solitaire/Main.hs
|
Haskell
|
bsd-3-clause
| 2,856
|
-----------------------------------------------------------------------------
-- |
-- Module : Control.Lens.Operators
-- Copyright : (C) 2012-14 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Stability : experimental
-- Portability : non-portable
--
-- This module exists for users who like to work with qualified imports
-- but want access to the operators from Lens.
--
-- > import qualified Control.Lens as L
-- > import Control.Lens.Operators
----------------------------------------------------------------------------
module Control.Lens.Operators
( -- output from scripts/operators -h
-- * "Control.Lens.Action"
(^!)
, (^!!)
, (^!?)
, (^@!)
, (^@!!)
, (^@!?)
-- * "Control.Lens.Cons"
, (<|)
, (|>)
-- * "Control.Lens.Fold"
, (^..)
, (^?)
, (^?!)
, (^@..)
, (^@?)
, (^@?!)
-- * "Control.Lens.Getter"
, (^.)
, (^@.)
-- * "Control.Lens.Indexed"
, (<.)
, (.>)
, (<.>)
-- * "Control.Lens.Lens"
, (%%~)
, (%%=)
, (&)
, (<&>)
, (??)
, (<%~)
, (<+~)
, (<-~)
, (<*~)
, (<//~)
, (<^~)
, (<^^~)
, (<**~)
, (<||~)
, (<&&~)
, (<<%~)
, (<<.~)
, (<<+~)
, (<<-~)
, (<<*~)
, (<<//~)
, (<<^~)
, (<<^^~)
, (<<**~)
, (<<||~)
, (<<&&~)
, (<<<>~)
, (<%=)
, (<+=)
, (<-=)
, (<*=)
, (<//=)
, (<^=)
, (<^^=)
, (<**=)
, (<||=)
, (<&&=)
, (<<%=)
, (<<.=)
, (<<+=)
, (<<-=)
, (<<*=)
, (<<//=)
, (<<^=)
, (<<^^=)
, (<<**=)
, (<<||=)
, (<<&&=)
, (<<<>=)
, (<<~)
, (<<>~)
, (<<>=)
, (<%@~)
, (<<%@~)
, (%%@~)
, (%%@=)
, (<%@=)
, (<<%@=)
, (^#)
, ( #~ )
, ( #%~ )
, ( #%%~ )
, ( #= )
, ( #%= )
, (<#%~)
, (<#%=)
, ( #%%= )
, (<#~)
, (<#=)
-- * "Control.Lens.Plated"
, (...)
-- * "Control.Lens.Review"
, ( # )
-- * "Control.Lens.Setter"
, (%~)
, (.~)
, (?~)
, (<.~)
, (<?~)
, (+~)
, (*~)
, (-~)
, (//~)
, (^~)
, (^^~)
, (**~)
, (||~)
, (&&~)
, (.=)
, (%=)
, (?=)
, (+=)
, (-=)
, (*=)
, (//=)
, (^=)
, (^^=)
, (**=)
, (&&=)
, (||=)
, (<~)
, (<.=)
, (<?=)
, (<>~)
, (<>=)
, (%@~)
, (%@=)
) where
import Control.Lens
|
hvr/lens
|
src/Control/Lens/Operators.hs
|
Haskell
|
bsd-3-clause
| 2,242
|
{-# LANGUAGE FlexibleInstances #-}
-- Algorithm for tiling the diagram with diamond calissons.
module Hexagrid.Tiling where
import Control.Arrow (first, (&&&))
import Core.Function
import Core.Math (l1dist)
import Data.Color
import Data.Entropy
import qualified Data.IntMap as M
import qualified Data.IntSet as IntSet
import Data.List (foldl')
import Data.List (nub)
import Data.Maybe (isJust, fromJust)
import Data.Monoid (Sum(Sum), getSum)
import Data.MapUtil (Map, foldl1WithKey, getValues)
import qualified Debug.Trace as T
import Diagrams.Prelude (blue, green, red)
import Data.BinarySearch (Binary, insert, remove, search, get, emptyBinary, binarySize)
import Hexagrid.Grid
import Hexagrid.Hexacycle
import Hexagrid.Path
import Hexagrid.TriangleCell
-- fixme improve these names
mpget k pToC = mget (posToInt k) (positionToColorMap pToC)
mpmget k posIntMap = mget (posToInt k) posIntMap
mpinsert k v pToC = M.insert (posToInt k) v (positionToColorMap pToC)
mpminsert k v posIntMap = M.insert (posToInt k) v posIntMap
type PositionToColorMap = Map ColorCode
data Tiling = Tiling {
tilingRadius :: Int, -- easier to store than recompute when needed.
-- colors induced by tiling (the pairs of triangles in a calisson is not explicitly stored)
positionToColorMap :: PositionToColorMap,
-- "upper left corners" of unit-hexagons populated by 3 different tiles, which can be rotated/mirrored
-- to generate a different valid tiling
tilingUsableHexagons :: PositionSet
} deriving (Show, Read)
class PositionSetClass a where
instance PositionSetClass IntSet.IntSet where
instance PositionSetClass (Binary Position) where
type PositionSet =
IntSet.IntSet
-- Binary Position
--fixme typeclass for this switcher and implementations
getImpl intSet bsearch =
intSet
-- bseach
asBinary = getImpl undefined id
asIntSet = getImpl id undefined
-- fixme O(n) traversal to get element
-- Use a "Binary (Measure (MinMax Position))" to maintain a tree of these.
-- getNth :: PositionSet -> Int -> Int
getNth tilingUsableHexagons n =
getImpl
((IntSet.toList tilingUsableHexagons) !! n)
(posToInt $ fromJust $ get (asBinary tilingUsableHexagons) n)
insertToPositionSet :: Int -> PositionSet-> PositionSet
insertToPositionSet =
getImpl
IntSet.insert
(insert . intToPos)
removeFromPositionSet :: Int -> PositionSet-> PositionSet
removeFromPositionSet =
getImpl
IntSet.delete
(remove . intToPos)
emptyPositionSet :: PositionSet
emptyPositionSet =
getImpl
IntSet.empty
(emptyBinary :: Binary Position)
size =
getImpl
IntSet.size
(getSum . binarySize)
initialTiling spec =
let radius = (gridRadius spec) in
let pToCM = mkCanonicalTiling (mkCornerColors radius ) (orientations spec) in
(Tiling radius pToCM (mkUsableHexagons (orientations spec) pToCM))
mkUsableHexagons :: Map TriangleOrientation -> PositionToColorMap -> PositionSet
mkUsableHexagons theOrientations pToCM =
-- T.trace "mkUsableHexagons"
foldl' (flip insertToPositionSet) emptyPositionSet $
filter
(\posInt ->
-- T.trace ("mkUsableHexagons: checking usability of hexagon: " ++ show (intToPos posInt)) $
let orientation = mget posInt theOrientations in
isJust (getHexacycleIfUsable orientation (intToPos posInt) pToCM))
(IntSet.toList $ M.keysSet pToCM)
-- A Hexacycle's position is just the position of its top-left corner.
type HexacyclePosition = Position
posToIntFlattenAndDedup :: [[Position]] -> [Int]
posToIntFlattenAndDedup = IntSet.toList .
foldl' (\set poss -> foldl' (\set pos -> IntSet.insert (posToInt pos) set)
set
poss)
IntSet.empty
updateUsableHexagons :: Map TriangleOrientation -> PositionToColorMap -> PositionSet -> [HexacyclePosition] -> PositionSet
updateUsableHexagons theOrientations newColorization oldUsableHexagons changedPositions =
let getOverlappingHexacycles pos = overlappingHexacycles pos (mpmget pos theOrientations) newColorization in
let overlappingHexacylePosInts = posToIntFlattenAndDedup (map getOverlappingHexacycles changedPositions) in
foldl' go oldUsableHexagons overlappingHexacylePosInts
where
go oldUsableHexagons posInt =
-- T.trace ("updateUsableHexagons: checking usability of hexagon: " ++ show (intToPos posInt)) $
let update = case getHexacycleIfUsable (mget posInt theOrientations) (intToPos posInt) newColorization of
Nothing ->
-- T.trace ("remove unusable hexagon: " ++ show (intToPos posInt)) $
removeFromPositionSet
Just _ ->
-- T.trace ("add usable hexagon: " ++ show (intToPos posInt)) $
insertToPositionSet
in
update posInt oldUsableHexagons
-- validPositions for its keys
overlappingHexacycles :: Position -> TriangleOrientation -> Map a -> [Position]
overlappingHexacycles pos orientation validPositions =
let paths = case orientation of
-- paths to hexacycle-positions determined by inspecting a diagram
PointingLeft ->
[[],
[blueToRed, blueToGreen],
[blueToRed, greenToRed]]
PointingRight ->
[[greenToRed, blueToRed, blueToGreen], -- equivalent to bg,br,gr
[greenToRed],
[blueToGreen]]
in
filter (isValidPosition validPositions) (map (walk' pos) paths)
-- map of positions to position's colors
-- Map TriangleOrientations is used only for the keys
mkCanonicalTiling :: PositionToColorMap -> Map TriangleOrientation -> PositionToColorMap
mkCanonicalTiling cornerColors positionToDummy =
M.fromList . map (id &&& (getNearestCornerColor cornerColors . intToPos))
$ M.keys positionToDummy
-- generate map of positions to color of positions' home corner
getNearestCornerColor :: PositionToColorMap -> Position -> ColorCode
getNearestCornerColor cornerColors cell@(Position (row, col)) =
let fcell = (row,col) in
snd $ foldl1WithKey
(\(nearest, ncolor) corner ccolor ->
-- fixme ugh
if l1dist fcell (toTuple $ intToPos corner) < l1dist fcell (toTuple $ intToPos nearest)
then (corner, ccolor)
else (nearest, ncolor))
cornerColors
-- map of home postions to colors
mkCornerColors :: Int -> PositionToColorMap
mkCornerColors radius = let s = fromIntegral radius in
M.fromList . map (first posToInt) $ [
(Position (-(4*s), 0) , Red)
, (Position (2*s, -2*s), Green) -- todo, use `rows` instead of `size` ?
, (Position (2*s, 2*s), Blue)
]
getColor :: PositionToColorMap -> Position -> ColorCode
getColor pToC position = mpmget position pToC
applyATiling :: Spec source -> Maybe Tiling -> Tiling
applyATiling spec mInitialTiling = shuffleColors spec $
case mInitialTiling of
Nothing -> initialTiling spec
Just tiling -> tiling
-- Computes a position's color by applying a shuffle function to the "positionColors" scheme
shuffleColors:: Spec source -> Tiling -> Tiling
shuffleColors spec positionColors =
let entropy = specPositionEntropy spec in
map fst (iterate (withEntropyAndRetry (shuffleOnce spec)) (positionColors, entropy))
!! specShuffles spec
-- warning! this is a "transient" method, (returns an invalid tiling!)
-- caller must do work to maintain invariants!
copyColorFrom :: PositionToColorMap -> (Position, Position) -> PositionToColorMap -> PositionToColorMap
copyColorFrom sourcePToC (srcPos, destPos) destPToC = mpminsert destPos (mpmget srcPos sourcePToC) destPToC
-- A 'shuffle' rotates a unit-hexagon a half-turn, if that would be a valid tiling (flips)
-- Our convention is to use the upper-left corner as the starting-point,
-- so only PointingLeft triangles are valid
-- FIXME! Very few grid positions are valid -- but they are predictable.
-- Build an index at start, and update it (as part of PositionToColor)
shuffleOnce :: Spec source -> Int -> Tiling -> Maybe (Maybe Tiling)
shuffleOnce spec entropyForCellIndex tiling =
let numUsableHexagons = size (tilingUsableHexagons tiling) in
case numUsableHexagons of
0 ->
T.trace ("ERROR!: No usable hexagons to shuffle colors!") $
Nothing
_ ->
let theOrientations = orientations spec in
-- todo: pos<->int conversion happens and roundtrip. better to normalize on 'int', for performance
let hexagonIndex = entropyForCellIndex `mod` numUsableHexagons in
let posInt = getNth (tilingUsableHexagons tiling) hexagonIndex in
let pos = intToPos posInt in
-- T.trace ("shuffleOnce: " ++ show cellIndex) $
let orientation = mget posInt theOrientations in
let pToCM = (positionToColorMap tiling) in
-- rendundant check oh usability, but good for validating computations
case getHexacycleIfUsable orientation pos pToCM of
Just hexacycle ->
-- T.trace ("yep: " ++ show pos) $
let hexagonPositions = take 6 hexacycle in
let hexagonOpposites = take 6 (zip hexacycle (drop 3 hexacycle)) in
let prevUsableHexagons = (tilingUsableHexagons tiling) in
let newPToCM = (foldl' (flip ($)) pToCM (map (copyColorFrom pToCM) hexagonOpposites)) in
Just $ Just $ Tiling (gridRadius spec) newPToCM (updateUsableHexagons theOrientations newPToCM prevUsableHexagons hexagonPositions)
Nothing ->
T.trace ("SHOULD NEVER HAPPEN: unsable hexacycle in hexacycle-cache: " ++ show pos) $
Just Nothing
getHexacycleIfUsable :: TriangleOrientation -> HexacyclePosition -> PositionToColorMap -> Maybe [Position]
getHexacycleIfUsable orientation pos pToC =
-- determine which triangles to include in unit-hexagon
-- if on a hexagon with 3 diff color, reflect colors across center of hexagon.
-- T.trace ("orient: " ++ show orientation) $
let hexacycle = cyclePathPositions orientation pos in
if (orientation == PointingLeft) && usableCycle hexacycle pToC
then Just hexacycle
else Nothing
-- warning: cyclic!
usableCycle :: [Position] -> PositionToColorMap -> Bool
usableCycle ps ptoc =
-- fixme: inefficient list access
let colorAtPos pos = mpmget pos ptoc in
let colorAt i = colorAtPos (ps !! i) in
let hexagon = take 6 ps in
let hexagonColors = map colorAtPos hexagon in
let colorNub = nub hexagonColors in
-- T.trace ("hexagon : " ++ show hexagon) $
all (isValidPosition ptoc) hexagon
-- Our "upper-left corner, PointingLeft" convention means that only 'red' and 'blue' corners are valid
&& (
-- T.trace ("hexagonColors : " ++ show hexagonColors) $
(hexagonColors !! 0) `elem` [Red, Blue])
&& wellCycledColors hexagonColors
-- adjacent colors are same/diff/... around cycle
wellCycledColors :: Eq a => [a] -> Bool -- [a] must be cyclic!
-- 5/tail because the first pairing is checked to establish parity.
wellCycledColors (x1:x2:xs) = wellCycledColors' 5 (tail (cycle xs)) (x1 == x2)
--FIXME
wellCycledColors' 0 xs _ = True
wellCycledColors' n (x1:x2:xs) parity =
((x1 == x2) == not parity) && wellCycledColors' (n-1) (x2:xs) (not parity)
isValidPosition :: Map a -> Position -> Bool
isValidPosition validPositionSet p = isJust $ M.lookup (posToInt p) validPositionSet
|
misterbeebee/calisson-hs
|
src/Hexagrid/Tiling.hs
|
Haskell
|
bsd-3-clause
| 11,889
|
module Main where
import Control.Applicative
import Control.Monad
import qualified System.Environment
import Path
import Run
import qualified Paths_runstaskell
getBinDir :: IO (Path Bin)
getBinDir = Path <$> Paths_runstaskell.getBinDir
getProgName :: IO (Path ProgName)
getProgName = Path <$> System.Environment.getProgName
getDataDir :: IO (Path DataDir)
getDataDir = Path <$> Paths_runstaskell.getDataDir
main :: IO ()
main = join (run <$> getProgName <*> getBinDir <*> getDataDir)
|
soenkehahn/runstaskell
|
src/Main.hs
|
Haskell
|
bsd-3-clause
| 532
|
#!/usr/bin/env stack
-- stack runghc --package universum --package lens --package lens-aeson --package time --package cassava --package split --package text --package fmt --package directory --package filepath --package megaparsec
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE ViewPatterns #-}
import Universum
import Unsafe
import qualified Control.Lens as L
import qualified Data.Aeson.Lens as L
import qualified Data.Csv as CSV
import Data.List (isInfixOf)
import qualified Data.List.Split as Split
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TL
import qualified Data.Text.Lazy.IO as TL
import qualified Data.Time as Time
import Fmt (Buildable (..), genericF)
import qualified System.Directory as Dir
import System.FilePath (takeFileName, (</>))
import qualified Text.Megaparsec as P
import Text.Megaparsec.Text ()
-- Usage: Give it path to the directory with logs
main :: IO ()
main = do
[logsDir] <- getArgs
logs <- readLogFiles logsDir
putStrLn . TL.decodeUtf8 $
CSV.encodeDefaultOrderedByName (concatMap processLog logs)
type Log = (FilePath, (LText, LText), LText)
-- | Each tuple contains directory, client.info & payload.json, and log.
readLogFiles :: FilePath -> IO [Log]
readLogFiles dir = do
ds <- map (dir </>) <$> Dir.listDirectory dir
fmap catMaybes $ mapM readLogDir ds
readLogDir :: FilePath -> IO (Maybe Log)
readLogDir dir = do
fs <- Dir.listDirectory dir
clientInfo <- if "client.info" `elem` fs
then Just <$> TL.readFile (dir </> "client.info")
else pure Nothing
payload <- if "payload.json" `elem` fs
then Just <$> TL.readFile (dir </> "payload.json")
else pure Nothing
logFile <- case find ("main" `isPrefixOf`) fs of
Just f -> Just <$> TL.readFile (dir </> f)
Nothing -> pure Nothing
pure $ (takeFileName dir,,)
<$> ((,) <$> clientInfo <*> payload)
<*> logFile
-- | Extract IP, OS, and version from JSON files.
getClientInfo :: (LText, LText) -> Maybe (Text, Text, Text)
getClientInfo (info, payload) =
(,,) <$> (info ^? strKey "addr" . L.to (T.takeWhile (/= ':')))
<*> (payload ^? strKey "os")
<*> (payload ^? strKey "version")
where
strKey k = L.key k . L._String
data Event = NodeStart | WalletStart | Adoption Count
deriving (Eq, Show, Generic)
instance Buildable Event where
build = genericF
data Count = One | Many
deriving (Eq, Show, Generic)
instance Buildable Count where
build = genericF
type Line = (Time.UTCTime, Event)
parseLine :: Text -> Maybe Line
parseLine = P.parseMaybe @P.Dec $ do
let inside a b = P.char a >> P.manyTill P.anyChar (P.char b)
inside '[' ']' >> P.space
time <- maybe empty pure . readMaybe =<< inside '[' ']'
msg <- P.manyTill P.anyChar P.eof
if | "Generated dht key" `isInfixOf` msg ->
pure (time, NodeStart)
| "DAEDALUS has STARTED" `isInfixOf` msg ->
pure (time, WalletStart)
| "Blocks have been adopted" `isInfixOf` msg ->
pure (time, Adoption Many)
| "Block has been adopted" `isInfixOf` msg ->
pure (time, Adoption One)
| otherwise ->
P.parserFail "unknown event type"
type Run = [Line]
getRuns :: [Line] -> [Run]
getRuns = Split.split
(Split.dropInitBlank $
Split.keepDelimsL $
Split.whenElt ((== NodeStart) . snd))
getWalletStartingTime :: Run -> Maybe Time.NominalDiffTime
getWalletStartingTime r = do
(t1, _) <- head r
(t2, _) <- find ((== WalletStart) . snd) r
pure (Time.diffUTCTime t2 t1)
getBlocksLoadingTime :: Run -> Maybe Time.NominalDiffTime
getBlocksLoadingTime r = do
(t1, _) <- head r
(t2, _) <- lastMay (filter ((== Adoption Many) . snd) r)
pure (Time.diffUTCTime t2 t1)
isValidRun :: Run -> Bool
isValidRun [] = False
isValidRun (map snd -> (x:xs)) =
and [ x == NodeStart
, count WalletStart xs <= 1
, dedup [a | Adoption a <- xs] `elem` [[], [One], [Many], [Many,One]]
]
data Entry = Entry
{ logDir :: FilePath
, clientIP :: Text
, clientOS :: Text
, clientVer :: Text
, walletStartingTime :: Maybe Time.NominalDiffTime
, blocksLoadingTime :: Maybe Time.NominalDiffTime
} deriving (Eq, Show, Generic)
instance CSV.ToNamedRecord Entry
instance CSV.DefaultOrdered Entry
processLog :: Log -> [Entry]
processLog (logDir, clientInfo, logFile) = do
(clientIP, clientOS, clientVer) <- maybeToList (getClientInfo clientInfo)
run <- getRuns $ mapMaybe (parseLine . toText) (TL.lines logFile)
guard (isValidRun run)
let walletStartingTime = getWalletStartingTime run
blocksLoadingTime = getBlocksLoadingTime run
pure Entry{..}
----------------------------------------------------------------------------
-- Utils
----------------------------------------------------------------------------
count :: Eq a => a -> [a] -> Int
count x = length . filter (x ==)
dedup :: Eq a => [a] -> [a]
dedup = map unsafeHead . group
----------------------------------------------------------------------------
-- Instances
----------------------------------------------------------------------------
instance CSV.ToField Time.NominalDiffTime where
toField = CSV.toField @Double . realToFrac
|
input-output-hk/cardano-sl
|
scripts/analyze/logs.hs
|
Haskell
|
apache-2.0
| 5,696
|
module SubPatternIn1 where
data T = C1 [Int] Int [Float] | C2 Int
g :: Int -> T -> Int
g z (C1 x b c)
= case c of
c@[] -> b
c@(b_1 : b_2) -> b
g z (C1 x b c) = b
g z (C2 x) = x
f :: [Int] -> Int
f x@[] = (hd x) + (hd (tl x))
f x@((y : ys)) = (hd x) + (hd (tl x))
hd x = head x
tl x = tail x
|
mpickering/HaRe
|
old/testing/introCase/SubPatternIn1AST.hs
|
Haskell
|
bsd-3-clause
| 334
|
{-# LANGUAGE ScopedTypeVariables, TypeSynonymInstances, FlexibleInstances #-}
-- |Binary serialization/deserialization utilities for types used in
-- ROS messages. This module is used by generated code for .msg types.
-- NOTE: The native byte ordering of the host is used to support the
-- common scenario of same-machine transport.
module Ros.Internal.RosBinary where
import Control.Applicative ((<$>), (<*>))
import Control.Monad (replicateM)
import Data.Binary.Get
import Data.Binary.Put
import Data.Int
import qualified Data.Vector.Storable as V
import Data.Word
import Unsafe.Coerce (unsafeCoerce)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC8
import Foreign.Storable (sizeOf, Storable)
import Ros.Internal.RosTypes
import Ros.Internal.Util.BytesToVector
-- |A type class for binary serialization of ROS messages. Very like
-- the standard Data.Binary type class, but with different, more
-- compact, instances for base types and an extra class method for
-- dealing with message headers.
class RosBinary a where
-- |Serialize a value to a ByteString.
put :: a -> Put
-- |Deserialize a value from a ByteString.
get :: Get a
-- |Serialize a ROS message given a sequence number. This number
-- may be used by message types with headers. The default
-- implementation ignores the sequence number.
putMsg :: Word32 -> a -> Put
putMsg _ = put
instance RosBinary Bool where
put True = putWord8 1
put False = putWord8 0
get = (> 0) <$> getWord8
instance RosBinary Int8 where
put = putWord8 . fromIntegral
get = fromIntegral <$> getWord8
instance RosBinary Word8 where
put = putWord8
get = getWord8
instance RosBinary Int16 where
put = putWord16host . fromIntegral
get = fromIntegral <$> getWord16host
instance RosBinary Word16 where
put = putWord16host
get = getWord16host
instance RosBinary Int where
put = putWord32host . fromIntegral
get = fromIntegral <$> getWord32host
instance RosBinary Word32 where
put = putWord32host
get = getWord32host
instance RosBinary Int64 where
put = putWord64host . fromIntegral
get = fromIntegral <$> getWord64host
instance RosBinary Word64 where
put = putWord64host
get = getWord64host
instance RosBinary Float where
put = putWord32le . unsafeCoerce
get = unsafeCoerce <$> getWord32le
instance RosBinary Double where
put = putWord64le . unsafeCoerce
get = unsafeCoerce <$> getWord64le
getAscii :: Get Char
getAscii = toEnum . fromEnum <$> getWord8
putAscii :: Char -> Put
putAscii = putWord8 . toEnum . fromEnum
putUnit :: Put
putUnit = putWord8 0
getUnit :: Get ()
getUnit = getWord8 >> return ()
instance RosBinary String where
put s = let s' = BC8.pack s
in putInt32 (BC8.length s') >> putByteString s'
get = getInt32 >>= (BC8.unpack <$>) . getByteString
instance RosBinary B.ByteString where
put b = putInt32 (B.length b) >> putByteString b
get = getInt32 >>= getByteString
instance RosBinary ROSTime where
put (s,n) = putWord32host s >> putWord32host n
get = (,) <$> getWord32host <*> getWord32host
putList :: RosBinary a => [a] -> Put
putList xs = putInt32 (length xs) >> mapM_ put xs
getList :: RosBinary a => Get [a]
getList = getInt32 >>= flip replicateM get
putFixedList :: RosBinary a => [a] -> Put
putFixedList = mapM_ put
getFixedList :: RosBinary a => Int -> Get [a]
getFixedList = flip replicateM get
{-
instance RosBinary ROSDuration where
put (s,n) = putWord32host s >> putWord32host n
get = (,) <$> getWord32host <*> getWord32host
-}
getInt32 :: Get Int
getInt32 = fromIntegral <$> getWord32le
putInt32 :: Int -> Put
putInt32 = putWord32le . fromIntegral
instance (RosBinary a, Storable a) => RosBinary (V.Vector a) where
put v = putInt32 (V.length v) >> putByteString (vectorToBytes v)
get = getInt32 >>= getFixed
getFixed :: forall a. Storable a => Int -> Get (V.Vector a)
getFixed n = bytesToVector n <$> getByteString (n*(sizeOf (undefined::a)))
putFixed :: (Storable a, RosBinary a) => V.Vector a -> Put
putFixed = putByteString . vectorToBytes
|
bitemyapp/roshask
|
src/Ros/Internal/RosBinary.hs
|
Haskell
|
bsd-3-clause
| 4,152
|
module T15723A where
{-# INLINE foo #-}
foo :: Int -> Int
foo x = {-# SCC foo1 #-} bar x
{-# NOINLINE bar #-}
bar :: Int -> Int
bar x = x
|
sdiehl/ghc
|
testsuite/tests/codeGen/should_compile/T15723A.hs
|
Haskell
|
bsd-3-clause
| 140
|
{-# LANGUAGE CPP #-}
module Vectorise.Utils.Base
( voidType
, newLocalVVar
, mkDataConTag, dataConTagZ
, mkWrapType
, mkClosureTypes
, mkPReprType
, mkPDataType, mkPDatasType
, splitPrimTyCon
, mkBuiltinCo
, wrapNewTypeBodyOfWrap
, unwrapNewTypeBodyOfWrap
, wrapNewTypeBodyOfPDataWrap
, unwrapNewTypeBodyOfPDataWrap
, wrapNewTypeBodyOfPDatasWrap
, unwrapNewTypeBodyOfPDatasWrap
, pdataReprTyCon
, pdataReprTyConExact
, pdatasReprTyConExact
, pdataUnwrapScrut
, preprSynTyCon
) where
import Vectorise.Monad
import Vectorise.Vect
import Vectorise.Builtins
import CoreSyn
import CoreUtils
import FamInstEnv
import Coercion
import Type
import TyCon
import DataCon
import MkId
import DynFlags
import FastString
#include "HsVersions.h"
-- Simple Types ---------------------------------------------------------------
voidType :: VM Type
voidType = mkBuiltinTyConApp voidTyCon []
-- Name Generation ------------------------------------------------------------
newLocalVVar :: FastString -> Type -> VM VVar
newLocalVVar fs vty
= do
lty <- mkPDataType vty
vv <- newLocalVar fs vty
lv <- newLocalVar fs lty
return (vv,lv)
-- Constructors ---------------------------------------------------------------
mkDataConTag :: DynFlags -> DataCon -> CoreExpr
mkDataConTag dflags = mkIntLitInt dflags . dataConTagZ
dataConTagZ :: DataCon -> Int
dataConTagZ con = dataConTag con - fIRST_TAG
-- Type Construction ----------------------------------------------------------
-- |Make an application of the 'Wrap' type constructor.
--
mkWrapType :: Type -> VM Type
mkWrapType ty = mkBuiltinTyConApp wrapTyCon [ty]
-- |Make an application of the closure type constructor.
--
mkClosureTypes :: [Type] -> Type -> VM Type
mkClosureTypes = mkBuiltinTyConApps closureTyCon
-- |Make an application of the 'PRepr' type constructor.
--
mkPReprType :: Type -> VM Type
mkPReprType ty = mkBuiltinTyConApp preprTyCon [ty]
-- | Make an appliction of the 'PData' tycon to some argument.
--
mkPDataType :: Type -> VM Type
mkPDataType ty = mkBuiltinTyConApp pdataTyCon [ty]
-- | Make an application of the 'PDatas' tycon to some argument.
--
mkPDatasType :: Type -> VM Type
mkPDatasType ty = mkBuiltinTyConApp pdatasTyCon [ty]
-- Make an application of a builtin type constructor to some arguments.
--
mkBuiltinTyConApp :: (Builtins -> TyCon) -> [Type] -> VM Type
mkBuiltinTyConApp get_tc tys
= do { tc <- builtin get_tc
; return $ mkTyConApp tc tys
}
-- Make a cascading application of a builtin type constructor.
--
mkBuiltinTyConApps :: (Builtins -> TyCon) -> [Type] -> Type -> VM Type
mkBuiltinTyConApps get_tc tys ty
= do { tc <- builtin get_tc
; return $ foldr (mk tc) ty tys
}
where
mk tc ty1 ty2 = mkTyConApp tc [ty1,ty2]
-- Type decomposition ---------------------------------------------------------
-- |Checks if a type constructor is defined in 'GHC.Prim' (e.g., 'Int#'); if so, returns it.
--
splitPrimTyCon :: Type -> Maybe TyCon
splitPrimTyCon ty
| Just (tycon, []) <- splitTyConApp_maybe ty
, isPrimTyCon tycon
= Just tycon
| otherwise = Nothing
-- Coercion Construction -----------------------------------------------------
-- |Make a representational coersion to some builtin type.
--
mkBuiltinCo :: (Builtins -> TyCon) -> VM Coercion
mkBuiltinCo get_tc
= do { tc <- builtin get_tc
; return $ mkTyConAppCo Representational tc []
}
-- Wrapping and unwrapping the 'Wrap' newtype ---------------------------------
-- |Apply the constructor wrapper of the 'Wrap' /newtype/.
--
wrapNewTypeBodyOfWrap :: CoreExpr -> Type -> VM CoreExpr
wrapNewTypeBodyOfWrap e ty
= do { wrap_tc <- builtin wrapTyCon
; return $ wrapNewTypeBody wrap_tc [ty] e
}
-- |Strip the constructor wrapper of the 'Wrap' /newtype/.
--
unwrapNewTypeBodyOfWrap :: CoreExpr -> Type -> VM CoreExpr
unwrapNewTypeBodyOfWrap e ty
= do { wrap_tc <- builtin wrapTyCon
; return $ unwrapNewTypeBody wrap_tc [ty] e
}
-- |Apply the constructor wrapper of the 'PData' /newtype/ instance of 'Wrap'.
--
wrapNewTypeBodyOfPDataWrap :: CoreExpr -> Type -> VM CoreExpr
wrapNewTypeBodyOfPDataWrap e ty
= do { wrap_tc <- builtin wrapTyCon
; pwrap_tc <- pdataReprTyConExact wrap_tc
; return $ wrapNewTypeBody pwrap_tc [ty] e
}
-- |Strip the constructor wrapper of the 'PData' /newtype/ instance of 'Wrap'.
--
unwrapNewTypeBodyOfPDataWrap :: CoreExpr -> Type -> VM CoreExpr
unwrapNewTypeBodyOfPDataWrap e ty
= do { wrap_tc <- builtin wrapTyCon
; pwrap_tc <- pdataReprTyConExact wrap_tc
; return $ unwrapNewTypeBody pwrap_tc [ty] (unwrapFamInstScrut pwrap_tc [ty] e)
}
-- |Apply the constructor wrapper of the 'PDatas' /newtype/ instance of 'Wrap'.
--
wrapNewTypeBodyOfPDatasWrap :: CoreExpr -> Type -> VM CoreExpr
wrapNewTypeBodyOfPDatasWrap e ty
= do { wrap_tc <- builtin wrapTyCon
; pwrap_tc <- pdatasReprTyConExact wrap_tc
; return $ wrapNewTypeBody pwrap_tc [ty] e
}
-- |Strip the constructor wrapper of the 'PDatas' /newtype/ instance of 'Wrap'.
--
unwrapNewTypeBodyOfPDatasWrap :: CoreExpr -> Type -> VM CoreExpr
unwrapNewTypeBodyOfPDatasWrap e ty
= do { wrap_tc <- builtin wrapTyCon
; pwrap_tc <- pdatasReprTyConExact wrap_tc
; return $ unwrapNewTypeBody pwrap_tc [ty] (unwrapFamInstScrut pwrap_tc [ty] e)
}
-- 'PData' representation types ----------------------------------------------
-- |Get the representation tycon of the 'PData' data family for a given type.
--
-- This tycon does not appear explicitly in the source program — see Note [PData TyCons] in
-- 'Vectorise.Generic.Description':
--
-- @pdataReprTyCon {Sum2} = {PDataSum2}@
--
-- The type for which we look up a 'PData' instance may be more specific than the type in the
-- instance declaration. In that case the second component of the result will be more specific than
-- a set of distinct type variables.
--
pdataReprTyCon :: Type -> VM (TyCon, [Type])
pdataReprTyCon ty
= do
{ FamInstMatch { fim_instance = famInst
, fim_tys = tys } <- builtin pdataTyCon >>= (`lookupFamInst` [ty])
; return (dataFamInstRepTyCon famInst, tys)
}
-- |Get the representation tycon of the 'PData' data family for a given type constructor.
--
-- For example, for a binary type constructor 'T', we determine the representation type constructor
-- for 'PData (T a b)'.
--
pdataReprTyConExact :: TyCon -> VM TyCon
pdataReprTyConExact tycon
= do { -- look up the representation tycon; if there is a match at all, it will be be exact
; -- (i.e.,' _tys' will be distinct type variables)
; (ptycon, _tys) <- pdataReprTyCon (tycon `mkTyConApp` mkTyVarTys (tyConTyVars tycon))
; return ptycon
}
-- |Get the representation tycon of the 'PDatas' data family for a given type constructor.
--
-- For example, for a binary type constructor 'T', we determine the representation type constructor
-- for 'PDatas (T a b)'.
--
pdatasReprTyConExact :: TyCon -> VM TyCon
pdatasReprTyConExact tycon
= do { -- look up the representation tycon; if there is a match at all, it will be be exact
; (FamInstMatch { fim_instance = ptycon }) <- pdatasReprTyCon (tycon `mkTyConApp` mkTyVarTys (tyConTyVars tycon))
; return $ dataFamInstRepTyCon ptycon
}
where
pdatasReprTyCon ty = builtin pdatasTyCon >>= (`lookupFamInst` [ty])
-- |Unwrap a 'PData' representation scrutinee.
--
pdataUnwrapScrut :: VExpr -> VM (CoreExpr, CoreExpr, DataCon)
pdataUnwrapScrut (ve, le)
= do { (tc, arg_tys) <- pdataReprTyCon ty
; let [dc] = tyConDataCons tc
; return (ve, unwrapFamInstScrut tc arg_tys le, dc)
}
where
ty = exprType ve
-- 'PRepr' representation types ----------------------------------------------
-- |Get the representation tycon of the 'PRepr' type family for a given type.
--
preprSynTyCon :: Type -> VM FamInstMatch
preprSynTyCon ty = builtin preprTyCon >>= (`lookupFamInst` [ty])
|
spacekitteh/smcghc
|
compiler/vectorise/Vectorise/Utils/Base.hs
|
Haskell
|
bsd-3-clause
| 8,068
|
{-# LANGUAGE ImplicitParams, TypeSynonymInstances, FlexibleInstances, ConstrainedClassMethods #-}
-- Similar to tc024, but cross module
module TcRun025_B where
import Data.List( sort )
-- This class has no tyvars in its class op context
-- One uses a newtype, the other a data type
class C1 a where
fc1 :: (?p :: String) => a;
class C2 a where
fc2 :: (?p :: String) => a;
opc :: a
instance C1 String where
fc1 = ?p;
instance C2 String where
fc2 = ?p;
opc = "x"
-- This class constrains no new type variables in
-- its class op context
class D1 a where
fd1 :: (Ord a) => [a] -> [a]
class D2 a where
fd2 :: (Ord a) => [a] -> [a]
opd :: a
instance D1 (Maybe a) where
fd1 xs = sort xs
instance D2 (Maybe a) where
fd2 xs = sort xs
opd = Nothing
|
ezyang/ghc
|
testsuite/tests/typecheck/should_run/TcRun025_B.hs
|
Haskell
|
bsd-3-clause
| 998
|
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fwarn-duplicate-exports #-}
module T2436( C(..), T(..), module T2436a, S(..) ) where
import T2436a
class C a where
data T a
instance C Int where
data T Int = TInt Int
data instance S Int = SInt
|
snoyberg/ghc
|
testsuite/tests/rename/should_compile/T2436.hs
|
Haskell
|
bsd-3-clause
| 250
|
module T10233 where
import T10233a( Constraint, Int )
|
urbanslug/ghc
|
testsuite/tests/module/T10233.hs
|
Haskell
|
bsd-3-clause
| 54
|
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -ddump-splices #-}
module T3600 where
import T3600a
$(test)
|
siddhanathan/ghc
|
testsuite/tests/th/T3600.hs
|
Haskell
|
bsd-3-clause
| 109
|
module Language.Tiger.AST
( module AST) where
import Language.Tiger.AST.Declaration as AST
|
zeling/tiger
|
src/Language/Tiger/AST.hs
|
Haskell
|
mit
| 99
|
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.SubtleCrypto
(js_encrypt, encrypt, js_decrypt, decrypt, js_sign, sign,
js_verify, verify, js_digest, digest, js_generateKey, generateKey,
js_importKey, importKey, js_exportKey, exportKey, js_wrapKey,
wrapKey, js_unwrapKey, unwrapKey, SubtleCrypto, castToSubtleCrypto,
gTypeSubtleCrypto)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSRef(..), JSString, castRef)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSRef(..), FromJSRef(..))
import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.Enums
foreign import javascript unsafe "$1[\"encrypt\"]($2, $3, $4)"
js_encrypt ::
JSRef SubtleCrypto ->
JSString ->
JSRef CryptoKey -> JSRef [Maybe data'] -> IO (JSRef Promise)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitSubtleCrypto.encrypt Mozilla WebKitSubtleCrypto.encrypt documentation>
encrypt ::
(MonadIO m, ToJSString algorithm, IsCryptoOperationData data') =>
SubtleCrypto ->
algorithm -> Maybe CryptoKey -> [Maybe data'] -> m (Maybe Promise)
encrypt self algorithm key data'
= liftIO
((toJSRef data' >>=
\ data'' ->
js_encrypt (unSubtleCrypto self) (toJSString algorithm)
(maybe jsNull pToJSRef key)
data'')
>>= fromJSRef)
foreign import javascript unsafe "$1[\"decrypt\"]($2, $3, $4)"
js_decrypt ::
JSRef SubtleCrypto ->
JSString ->
JSRef CryptoKey -> JSRef [Maybe data'] -> IO (JSRef Promise)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitSubtleCrypto.decrypt Mozilla WebKitSubtleCrypto.decrypt documentation>
decrypt ::
(MonadIO m, ToJSString algorithm, IsCryptoOperationData data') =>
SubtleCrypto ->
algorithm -> Maybe CryptoKey -> [Maybe data'] -> m (Maybe Promise)
decrypt self algorithm key data'
= liftIO
((toJSRef data' >>=
\ data'' ->
js_decrypt (unSubtleCrypto self) (toJSString algorithm)
(maybe jsNull pToJSRef key)
data'')
>>= fromJSRef)
foreign import javascript unsafe "$1[\"sign\"]($2, $3, $4)" js_sign
::
JSRef SubtleCrypto ->
JSString ->
JSRef CryptoKey -> JSRef [Maybe data'] -> IO (JSRef Promise)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitSubtleCrypto.sign Mozilla WebKitSubtleCrypto.sign documentation>
sign ::
(MonadIO m, ToJSString algorithm, IsCryptoOperationData data') =>
SubtleCrypto ->
algorithm -> Maybe CryptoKey -> [Maybe data'] -> m (Maybe Promise)
sign self algorithm key data'
= liftIO
((toJSRef data' >>=
\ data'' ->
js_sign (unSubtleCrypto self) (toJSString algorithm)
(maybe jsNull pToJSRef key)
data'')
>>= fromJSRef)
foreign import javascript unsafe "$1[\"verify\"]($2, $3, $4, $5)"
js_verify ::
JSRef SubtleCrypto ->
JSString ->
JSRef CryptoKey ->
JSRef CryptoOperationData ->
JSRef [Maybe data'] -> IO (JSRef Promise)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitSubtleCrypto.verify Mozilla WebKitSubtleCrypto.verify documentation>
verify ::
(MonadIO m, ToJSString algorithm, IsCryptoOperationData signature,
IsCryptoOperationData data') =>
SubtleCrypto ->
algorithm ->
Maybe CryptoKey ->
Maybe signature -> [Maybe data'] -> m (Maybe Promise)
verify self algorithm key signature data'
= liftIO
((toJSRef data' >>=
\ data'' ->
js_verify (unSubtleCrypto self) (toJSString algorithm)
(maybe jsNull pToJSRef key)
(maybe jsNull (unCryptoOperationData . toCryptoOperationData)
signature)
data'')
>>= fromJSRef)
foreign import javascript unsafe "$1[\"digest\"]($2, $3)" js_digest
::
JSRef SubtleCrypto ->
JSString -> JSRef [Maybe data'] -> IO (JSRef Promise)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitSubtleCrypto.digest Mozilla WebKitSubtleCrypto.digest documentation>
digest ::
(MonadIO m, ToJSString algorithm, IsCryptoOperationData data') =>
SubtleCrypto -> algorithm -> [Maybe data'] -> m (Maybe Promise)
digest self algorithm data'
= liftIO
((toJSRef data' >>=
\ data'' ->
js_digest (unSubtleCrypto self) (toJSString algorithm) data'')
>>= fromJSRef)
foreign import javascript unsafe "$1[\"generateKey\"]($2, $3, $4)"
js_generateKey ::
JSRef SubtleCrypto ->
JSString -> Bool -> JSRef [KeyUsage] -> IO (JSRef Promise)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitSubtleCrypto.generateKey Mozilla WebKitSubtleCrypto.generateKey documentation>
generateKey ::
(MonadIO m, ToJSString algorithm) =>
SubtleCrypto ->
algorithm -> Bool -> [KeyUsage] -> m (Maybe Promise)
generateKey self algorithm extractable keyUsages
= liftIO
((toJSRef keyUsages >>=
\ keyUsages' ->
js_generateKey (unSubtleCrypto self) (toJSString algorithm)
extractable
keyUsages')
>>= fromJSRef)
foreign import javascript unsafe
"$1[\"importKey\"]($2, $3, $4, $5,\n$6)" js_importKey ::
JSRef SubtleCrypto ->
JSString ->
JSRef CryptoOperationData ->
JSString -> Bool -> JSRef [KeyUsage] -> IO (JSRef Promise)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitSubtleCrypto.importKey Mozilla WebKitSubtleCrypto.importKey documentation>
importKey ::
(MonadIO m, ToJSString format, IsCryptoOperationData keyData,
ToJSString algorithm) =>
SubtleCrypto ->
format ->
Maybe keyData ->
algorithm -> Bool -> [KeyUsage] -> m (Maybe Promise)
importKey self format keyData algorithm extractable keyUsages
= liftIO
((toJSRef keyUsages >>=
\ keyUsages' ->
js_importKey (unSubtleCrypto self) (toJSString format)
(maybe jsNull (unCryptoOperationData . toCryptoOperationData)
keyData)
(toJSString algorithm)
extractable
keyUsages')
>>= fromJSRef)
foreign import javascript unsafe "$1[\"exportKey\"]($2, $3)"
js_exportKey ::
JSRef SubtleCrypto ->
JSString -> JSRef CryptoKey -> IO (JSRef Promise)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitSubtleCrypto.exportKey Mozilla WebKitSubtleCrypto.exportKey documentation>
exportKey ::
(MonadIO m, ToJSString format) =>
SubtleCrypto -> format -> Maybe CryptoKey -> m (Maybe Promise)
exportKey self format key
= liftIO
((js_exportKey (unSubtleCrypto self) (toJSString format)
(maybe jsNull pToJSRef key))
>>= fromJSRef)
foreign import javascript unsafe "$1[\"wrapKey\"]($2, $3, $4, $5)"
js_wrapKey ::
JSRef SubtleCrypto ->
JSString ->
JSRef CryptoKey ->
JSRef CryptoKey -> JSString -> IO (JSRef Promise)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitSubtleCrypto.wrapKey Mozilla WebKitSubtleCrypto.wrapKey documentation>
wrapKey ::
(MonadIO m, ToJSString format, ToJSString wrapAlgorithm) =>
SubtleCrypto ->
format ->
Maybe CryptoKey ->
Maybe CryptoKey -> wrapAlgorithm -> m (Maybe Promise)
wrapKey self format key wrappingKey wrapAlgorithm
= liftIO
((js_wrapKey (unSubtleCrypto self) (toJSString format)
(maybe jsNull pToJSRef key)
(maybe jsNull pToJSRef wrappingKey)
(toJSString wrapAlgorithm))
>>= fromJSRef)
foreign import javascript unsafe
"$1[\"unwrapKey\"]($2, $3, $4, $5,\n$6, $7, $8)" js_unwrapKey ::
JSRef SubtleCrypto ->
JSString ->
JSRef CryptoOperationData ->
JSRef CryptoKey ->
JSString ->
JSString -> Bool -> JSRef [KeyUsage] -> IO (JSRef Promise)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitSubtleCrypto.unwrapKey Mozilla WebKitSubtleCrypto.unwrapKey documentation>
unwrapKey ::
(MonadIO m, ToJSString format, IsCryptoOperationData wrappedKey,
ToJSString unwrapAlgorithm, ToJSString unwrappedKeyAlgorithm) =>
SubtleCrypto ->
format ->
Maybe wrappedKey ->
Maybe CryptoKey ->
unwrapAlgorithm ->
unwrappedKeyAlgorithm -> Bool -> [KeyUsage] -> m (Maybe Promise)
unwrapKey self format wrappedKey unwrappingKey unwrapAlgorithm
unwrappedKeyAlgorithm extractable keyUsages
= liftIO
((toJSRef keyUsages >>=
\ keyUsages' ->
js_unwrapKey (unSubtleCrypto self) (toJSString format)
(maybe jsNull (unCryptoOperationData . toCryptoOperationData)
wrappedKey)
(maybe jsNull pToJSRef unwrappingKey)
(toJSString unwrapAlgorithm)
(toJSString unwrappedKeyAlgorithm)
extractable
keyUsages')
>>= fromJSRef)
|
plow-technologies/ghcjs-dom
|
src/GHCJS/DOM/JSFFI/Generated/SubtleCrypto.hs
|
Haskell
|
mit
| 9,991
|
import Control.Monad
filter' _ [] = [-1]
filter' _ (_:xs) = xs
main = do
n <- readLn :: IO Int
replicateM_ n $ do
line <- getLine
arrLine <- getLine
let k = read (words line !! 1) :: Int
let arr = map (\x -> read x :: Int) (words arrLine)
putStrLn $ unwords (map show (filter' k arr))
|
ahavrylyuk/hackerrank
|
haskell/filter-elements.hs
|
Haskell
|
mit
| 312
|
{-# LANGUAGE GeneralizedNewtypeDeriving, TemplateHaskell #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleInstances #-}
module IRC.Types where
import Control.Lens
import CAH.Cards.Types
import Data.Set (Set)
import Data.Map (Map)
import Data.Bimap (Bimap)
import qualified IRC.Raw.Types as Raw
import IRC.Raw.Monad
import Common.Types
import CAH.Cards.Types
import Data.ByteString (ByteString)
import Data.Monoid
import Data.Dynamic
import Data.Text (Text)
import Control.Applicative
import System.Random
import Control.Monad.Trans.Class
import qualified Control.Monad.Ether.State.Strict as ES
import qualified Control.Monad.Ether.Reader as ER
import Control.Ether.TH
ethereal "GameState" "gameState"
ethereal "CardSet" "cardSet"
ethereal "Tracker" "nickTracker"
ethereal "GameInfoT" "gameInfo"
type TrackerMonad = ES.MonadState Tracker NickTracker
type GameMonad r m = (ES.MonadState GameState (GS r) m, ER.MonadReader CardSet [Pack] m, ER.MonadReader GameInfoT GameInfo m, Applicative m)
data Cmd = N Int
| S ByteString
deriving (Show,Eq,Ord) -- used by IRC.Commands
data User = User Nick Ident Host
deriving (Show,Eq)
newtype UID = UID Integer
deriving (Show,Eq,Ord)
data TrackEvent
= Login Nick Account
| Logout Nick
| NickChange Nick Nick
deriving (Show,Eq, Typeable)
data NickTracker
= Tracker
!UID -- ^ next uid to use
!(Bimap Nick UID) -- ^ bimap keeping the mapping from nicks to UIDs
!(Map UID Account) -- ^ maps from user IDs to textual "user account", missing key means the user doesn't have a registered account
deriving (Show,Eq)
data Players a = Players (Bimap UID Account) (Map Account a)
deriving (Show,Eq)
userNick :: User -> Nick
userNick (User n _ _) = n
newtype Channel = Channel Text
deriving (Show,Eq)
newtype Nick = Nick Text
deriving (Show,Eq,Ord)
newtype Message = Message Text
deriving (Show,Eq,Monoid)
newtype Target = Target Text
deriving (Show,Eq)
newtype Account = Account Text
deriving (Show,Eq,Ord)
type Ident = Text
type Host = Text
data Mode = Plus Char
| Minus Char
deriving (Show,Eq)
data CMode = CMode Nick Mode
deriving (Show,Eq)
data SASLCfg = SASLCfg {
sasl_username :: String
,sasl_password :: String
} deriving (Show,Eq)
data ChannelCfg = ChannelCfg {
channel_name :: Channel
,channel_password :: Maybe String
} deriving (Show,Eq)
data IRCConfig = IRCConfig {
config_network :: String
,config_port :: Int
,config_nick :: Nick
,config_sasl :: Maybe SASLCfg
,config_channels :: [ChannelCfg]
} deriving (Show,Eq)
type Player = Account
data NatN = Nat_Zero
| Nat_Succ NatN
data T_GameState {-(p :: NatN)-} a
= T_NoGameBeingPlayed
| T_WaitingFor a
deriving (Typeable)
data T_Waiting
= T_Players
| T_Czar
deriving (Typeable)
type family ToLogicTag (x :: *) :: T_GameState T_Waiting where
ToLogicTag NoGame = T_NoGameBeingPlayed
ToLogicTag (Current WFCzar) = T_WaitingFor T_Czar
ToLogicTag (Current WFPlayers) = T_WaitingFor T_Players
data LogicCommand st where
PlayerJoin :: Nick -> Account -> LogicCommand a
PlayerLeave :: Nick -> Account -> LogicCommand a
StartGame :: Nick -> Account -> LogicCommand T_NoGameBeingPlayed
PlayerPick :: Nick -> Account -> [WhiteCard] -> LogicCommand (T_WaitingFor T_Players)
CzarPick :: Nick -> Account -> ChoiceN -> LogicCommand (T_WaitingFor T_Czar)
ShowTable :: LogicCommand (T_WaitingFor a)
ShowCards :: Nick -> Account -> LogicCommand (T_WaitingFor a)
data TextMessage
= NoError
| UserNotPlaying Nick
| UserNotIdentified Nick
| NotEnoughPlayers Integer
| AlreadyPlaying Nick
| GameStarted [Nick]
| GameAlreadyBeingPlayed
| JoinPlayer Nick
| LeavePlayer Nick
| AlreadyPlayed Nick
| ReplacingOld Nick Nick -- the first nick is the "old" one
| MustPickNCards Nick Integer
| PlayersWin [Nick] Points
| CzarPicked Nick Nick BlackCard [WhiteCard] Points -- first is czar
| CzarDoesn'tPlay Nick
| YourCardsAre Nick [(Integer, WhiteCard)]
| TheCardsAre
| CardsPicked Nick Integer BlackCard [WhiteCard]
| PlayersList [Nick]
| CzarLeft Nick
| Table Nick BlackCard
| StatusWaitingCzar Nick
| StatusWaitPlayers Nick [Nick] -- first is czar
| Debug Text
newtype ChoiceN = ChoiceN Integer
deriving (Show,Eq,Ord)
newtype Points = Points Integer
deriving (Show,Eq,Ord,Num)
type Game r m
= ES.StateT GameState (GS r)
( ES.StateT EventsTag Events
( ES.StateT Tracker NickTracker
( ER.ReaderT CardSet [Pack]
( ER.ReaderT GameInfoT GameInfo
(IRC m)))))
data GameInfo = GameInfo {
_gameChannel :: Channel
,_botNick :: Nick
} deriving (Show)
data GS a = GS {
_stdGen :: StdGen
,_whiteCards :: Set WhiteCard
,_blackCards :: Set BlackCard
,_players :: Players (Set WhiteCard) -- ^ current players (and their cards)
,_current :: a
} deriving (Show,Functor)
changing :: Monad m => (GS r -> GS r') -> Game r' m a -> Game r m a
changing f gs = do
x <- ES.get gameState
lift $ ES.evalStateT gameState gs (f x)
data NoGame = NoGame
deriving (Show)
data Current w = Current {
_points :: Map Player Points
,_czar :: Player
,_blackCard :: BlackCard
,_currentB :: w
} deriving (Show,Functor)
data WFCzar = WFCzar {
_picks :: Map Integer (Player, [WhiteCard])
} deriving (Show)
data WFPlayers = WFPlayers {
_waitingFor :: Set Player -- ^ players we're waiting for
,_alreadyPlayed :: Map Player [WhiteCard] -- ^ players with their picks
} deriving (Show)
makeLenses ''GS
makeLenses ''Current
makeLenses ''WFCzar
makeLenses ''WFPlayers
makeLenses ''GameInfo
|
EXio4/ircah
|
src/IRC/Types.hs
|
Haskell
|
mit
| 6,577
|
{-# LANGUAGE TemplateHaskell
, TypeFamilies, OverloadedStrings #-}
module Main where
import System.Environment
import Generics.BiGUL.TH
import GHC.Generics
import Data.Aeson
import Data.Text
import Control.Applicative
import Control.Monad
import qualified Data.ByteString.Lazy as B
import SourceModel
import qualified AutoScalingBX as ASBX
import qualified FirewallBX as FWBX
import qualified RedundancyBX as REDBX
import qualified ExecutionBX as EXBX
import qualified AutoScalingModel as ASV
import qualified FirewallModel as FWV
import qualified RedundancyModel as REDV
import qualified ExecutionModel as EXV
import qualified AutoscalingFailureModel as ASFV
import qualified AutoscalingFailureBX as ASFBX
import qualified FailureModel as FAV
import qualified FailureBX as FABX
doGet bx source param = case bx of
"autoscalingFailure" -> case result of
Just res -> encode res
where result = (ASFBX.get (ASFBX.autoscalingFailureUpd param) source)
"redundancy" -> case result of
Just res -> encode res
where result = (REDBX.get REDBX.redundancyUpd source)
"firewall" -> case result of
Just res -> encode res
where result = (FWBX.get FWBX.firewallUpd source)
"execution" -> encode (EXBX.getExecution source)
doGet' bx source = case bx of
"failure" -> case result of
Just res -> encode res
where result = (FABX.get FABX.failureUpd source)
"autoScaling" -> case result of
Just res -> encode res
where result = (ASBX.get ASBX.autoScalingUpd source)
doASPut source view = case result of
Just res -> encode res
where result = (ASBX.put ASBX.autoScalingUpd source view)
doREDPut source view = case result of
Just res -> encode res
where result = (REDBX.put REDBX.redundancyUpd source view)
doFWPut source view = case result of
Just res -> encode res
where result = (FWBX.put FWBX.firewallUpd source view)
doEXPut source view = case result of
Just res -> encode res
where result = (EXBX.put EXBX.executionUpd source view)
doASFPut source view param = case result of
Just res -> encode res
where result = (ASFBX.put (ASFBX.autoscalingFailureUpd param) source view)
doFAPut source view = case result of
Just res -> encode res
where result = (FABX.put FABX.failureUpd source view)
-- arguments are:
-- dir: the direction, either get or put
-- bx: the name of the transformation
-- param: a parameter to pass to the bx (not all BX need this)
-- Example: ./Main get autoScaling as.json
main :: IO ()
main = do
[dir, bx, param] <- getArgs
putStrLn "Starting"
case bx of
"autoscalingFailure" -> do
doAutoscalingFailure dir param
"autoScaling" -> do
doAutoScaling dir
"failure" -> do
doFailure dir
"execution" -> do
doExecution dir
"firewall" -> do
doFirewall dir
doExecution dir = do
src <- (eitherDecode <$> (B.readFile "source.json")) :: IO (Either String Model)
case src of
Left err -> putStrLn err
Right source -> case dir of
"get" -> do
B.writeFile "execution.json" (doGet "execution" source "")
"put" -> do
v <- (eitherDecode <$> (B.readFile "execution.json")) :: IO (Either String EXV.View)
case v of
Left err -> do
putStrLn "Error parse execution.json"
putStrLn err
Right vw -> B.writeFile "source.json" (doEXPut source vw)
doAutoscalingFailure dir param = do
src <- (eitherDecode <$> (B.readFile "source.json")) :: IO (Either String Model)
case src of
Left err -> putStrLn err
Right source -> case dir of
"get" -> do
B.writeFile "autoscalingFailure.json" (doGet "autoscalingFailure" source param)
"put" -> do
v <- (eitherDecode <$> (B.readFile "autoscalingFailure.json")) :: IO (Either String ASFV.AutoscalingFailure)
case v of
Left err -> do
putStrLn "Error parse autoscalingFailure.json"
putStrLn err
Right vw -> B.writeFile "source.json" (doASFPut source vw param)
doAutoScaling dir = do
src <- (eitherDecode <$> (B.readFile "autoscalingFailure.json")) :: IO (Either String ASFV.AutoscalingFailure)
case src of
Left err -> putStrLn err
Right source -> case dir of
"get" -> do
B.writeFile "autoScaling.json" (doGet' "autoScaling" source)
"put" -> do
v <- (eitherDecode <$> (B.readFile "autoScaling.json")) :: IO (Either String ASV.View)
case v of
Left err -> do
putStrLn "Error parse autoScaling.json"
putStrLn err
Right vw -> B.writeFile "autoscalingFailure.json" (doASPut source vw)
doFailure dir = do
src <- (eitherDecode <$> (B.readFile "autoscalingFailure.json")) :: IO (Either String ASFV.AutoscalingFailure)
case src of
Left err -> putStrLn err
Right source -> case dir of
"get" -> do
B.writeFile "failure.json" (doGet' "failure" source)
"put" -> do
v <- (eitherDecode <$> (B.readFile "failure.json")) :: IO (Either String FAV.FailureView)
case v of
Left err -> do
putStrLn "Error parse failure.json"
putStrLn err
Right vw -> B.writeFile "autoscalingFailure.json" (doFAPut source vw)
doFirewall dir = do
src <- (eitherDecode <$> (B.readFile "source.json")) :: IO (Either String Model)
case src of
Left err -> putStrLn err
Right source -> case dir of
"get" -> do
B.writeFile "firewall.json" (doGet "firewall" source "")
"put" -> do
v <- (eitherDecode <$> (B.readFile "firewall.json")) :: IO (Either String FWV.View)
case v of
Left err -> do
putStrLn "Error parse firewall.json"
putStrLn err
Right vw -> B.writeFile "source.json" (doFWPut source vw)
{-
Zhenjiang: the following two functions can be used to generate the Haskell
representations from the JSON representation of soruce/view for simple
testing of FirewallBX.hs.
-}
jsonSource2Haskell :: IO ()
jsonSource2Haskell = do
src <- (eitherDecode <$> B.readFile "source.json") :: IO (Either String Model)
case src of
Right s -> putStrLn (show s)
Left _ -> putStrLn "JSON parse error (source)"
jsonFirewallView2Haskell :: IO ()
jsonFirewallView2Haskell = do
view <- (eitherDecode <$> B.readFile "firewall.json") :: IO (Either String FWV.View)
case view of
Right v -> putStrLn (show v)
Left _ -> putStrLn "JSON parse error (firewall)"
|
prl-tokyo/MAPE-knowledge-base
|
Haskell/Main.hs
|
Haskell
|
mit
| 6,424
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Main where
import Data.Int (Int32)
import Database.HDBC.PostgreSQL (Connection)
import Database.HDBC.Session (handleSqlError', withConnectionIO)
import HRR.Commands (Command (..), Flag (..),
runAndPrintCommand)
import HRR.DataSource (connect')
import System.Console.GetOpt (ArgDescr (..), ArgOrder (..),
OptDescr (..), getOpt, usageInfo)
import System.Environment (getArgs)
import System.Exit (ExitCode (..), exitSuccess, exitWith)
import System.IO (hPutStrLn, stderr)
--------------------------------------------------------------------------------
-- | Flags with their corresponding description
flags :: [OptDescr Flag]
flags = [ Option ['d'] ["due-by"] (ReqArg DueBy "DATE")
"Get todos due by a certain date"
, Option ['l'] ["late"] (NoArg Late)
"Get todos that are late"
, Option ['w'] ["with-hashtags"] (NoArg WithHashtags)
"Get todos with the associated hashtags"
, Option ['h'] ["hashtags"] (ReqArg SearchHashtag "HASHTAGS")
"Get todos for a certain hashtag"
, Option ['o'] ["order-by-priority"] (NoArg OrderByPriority)
"Get todos ordered by priority"
, Option ['p'] ["priority"] (ReqArg SetPriority "PRIORITY")
"When adding a todo, you can set its priority"
, Option ['d'] ["debug"] (NoArg Debug)
"Debug sql executed"
, Option ['h'] ["help"] (NoArg Help)
"Show help menu"
, Option ['v'] ["version"] (NoArg Version)
"Show version"
]
header :: String
header = "todos <command> [options]\n\n\
\Available commands: find, add, complete, list\n"
--------------------------------------------------------------------------------
-- | Parse the command and the corresponding flags (if any)
parse :: [String] -> Either String (Command, [Flag])
-- | Simple parsing of commands
parse [] = Left "Wrong number of arguments."
parse ("-h":_) = Left (usageInfo header flags)
parse ("--help":_) = Left (usageInfo header flags)
parse ("-v":_) = Left "0.1.0.0"
parse ("--version":_) = Left "0.1.0.0"
parse args = case args of
("find":x:argv) -> makeCommand (Find (read x :: Int32)) argv
("add":x:argv) -> makeCommand (Add x) argv
("complete":x:_) -> makeCommand (Complete (read x :: Int32)) []
("list":argv) -> makeCommand List argv
("report":_) -> makeCommand Reports []
_ -> Left "Unrecognized command or wrong \
\number of arguments."
makeCommand :: Command -> [String] -> Either String (Command, [Flag])
makeCommand c argv = case getOpt Permute flags argv of
(args', _, []) -> Right(c, args')
(_, _, errs) -> Left (concat errs)
--------------------------------------------------------------------------------
-- | Gets the results of a command and its corresponding flags
getResults :: Connection -> Either String (Command, [Flag]) -> IO ()
-- | An error happened
getResults _ (Left s) = hPutStrLn stderr s
>> exitWith (ExitFailure 1)
-- | We have an appropriate command and its results
getResults conn (Right (c, flags')) = runAndPrintCommand conn c flags'
>> exitSuccess
main :: IO ()
main = handleSqlError' $ withConnectionIO connect' $ \conn -> do
parsed <- fmap parse getArgs
getResults conn parsed
|
charlydagos/haskell-sql-edsl-demo
|
code/hrr/src/Main.hs
|
Haskell
|
mit
| 3,975
|
import Data.Array.IArray
import Data.Char
import Data.Maybe
import Data.List
--------------------------------------------------------------------------------
data Cell = Value Int
| Values (Array Int Bool) Int
deriving Show
isCellSet :: Cell -> Bool
isCellSet (Value _) = True
isCellSet (Values _ _) = False
--------------------------------------------------------------------------------
type Coord = (Int, Int)
next :: Coord -> Coord
next (8, 8) = (0, 0)
next (i, 8) = (i+1, 0)
next (i, j) = (i, j+1)
linkedWith (i, j) = [(i , j' ) | j' <- [0..8]] ++
[(i' , j ) | i' <- [0..8]] ++
[(i0 + i', j0 + j') | let i0 = 3 * (div i 3),
let j0 = 3 * (div j 3),
i' <- [0..2],
j' <- [0..2]]
--------------------------------------------------------------------------------
type Board = Array Coord Cell
--------------------------------------------------------------------------------
set :: Board -> Coord -> Int -> Maybe Board
set board coord val
= case (board ! coord) of
Value v -> if (v == val) then Just board else Nothing
Values arr len -> if (arr ! val) then board' else Nothing
where
board' = unset (board // [(coord, Value val)]) (linkedWith coord)
unset :: Board -> [Coord] -> Maybe Board
unset b [] = (Just b)
unset b (c:cs)
| c == coord = unset b cs
| otherwise = case (b ! c) of
Value v -> if v == val then Nothing else unset b cs
Values arr len ->
let
arr' = arr // [(val, False)]
b' = set b c (fst $ head $ filter snd $ assocs (arr'))
in
case () of
_| not (arr ! val) -> unset b cs
| len == 1 -> Nothing
| len == 2 -> case b' of
Just b'' -> unset b'' cs
Nothing -> Nothing
| otherwise -> unset (b // [(c, Values arr' (len-1))]) cs
--------------------------------------------------------------------------------
fork :: Board -> [Board]
fork board = map fromJust $ filter isJust $ map (\val -> set board pivot val) values
where
candidates = [(coord, len) | (coord, Values _ len) <- assocs board]
pivot = pivot' (9, 9) 10 candidates
where
pivot' coord len [] = coord
pivot' coord len ((coord', len'):ls)
| len' == 2 = coord'
| len' < len = pivot' coord' len' ls
| otherwise = pivot' coord len ls
Values arr _ = board ! pivot
values = map fst $ filter snd $ assocs arr
--------------------------------------------------------------------------------
isDone :: Board -> Bool
isDone board = all isCellSet $ elems board
--------------------------------------------------------------------------------
solve :: Board -> [Board]
solve board = if isDone board then [board]
else concat $ map solve $ fork board
--------------------------------------------------------------------------------
mkBoard :: [Int] -> Maybe Board
mkBoard ns
| length ns == 81 = fst $ foldl' setter (Just nullBoard, (0, 0)) ns
| otherwise = error ("mkBoard: wrong input list length: " ++ show ns)
where
setter :: (Maybe Board, Coord) -> Int -> (Maybe Board, Coord)
setter (Nothing, _) _ = (Nothing, (0, 0))
setter (Just board, coord) val
| val == 0 = (Just board, next coord)
| 1 <= val && val <= 9 = ((set board coord val), next coord)
| otherwise = error ("mkBoard: wrong input value '" ++ show (val) ++
"' at " ++ show (coord))
nullBoard = listArray ((0, 0), (8, 8)) (replicate 81 nullCell)
nullCell = Values (listArray (1, 9) (replicate 9 True)) 9
--------------------------------------------------------------------------------
convert :: String -> [Maybe Board]
convert str = convert' $ filter (\s -> head s /= 'G') $ (lines str)
where
convert' :: [String] -> [Maybe Board]
convert' [] = []
convert' strs = let (h, t) = (splitAt 9 strs) in (mkBoard $ map digitToInt $ concat h) : convert' t
--------------------------------------------------------------------------------
euler :: [Board] -> Int
euler boards = foldl' (\acc board -> euler1 board + acc) 0 boards
where
euler1 :: Board -> Int
euler1 board = 100 * val1 + 10 * val2 + val3
where
Value val1 = board!(0, 0)
Value val2 = board!(0, 1)
Value val3 = board!(0, 2)
--------------------------------------------------------------------------------
main = do
file <- readFile "z:/euler/euler_0096.txt"
putStrLn $ show $ euler $ concat $ map solve $ map fromJust $ filter isJust $ convert file
--------------------------------------------------------------------------------
-- Debugging functions
--------------------------------------------------------------------------------
showBoard :: (Array Coord String) -> String
showBoard board
= concat [concat [(board ! (i, j)) ++ (if j == 8 then "\n" else " ") | j <- [0..8]] | i <- [0..8]]
showBoard' :: Maybe Board -> String
showBoard' Nothing = "Nothing\n"
showBoard' (Just board) = showBoard $ amap showCell board
showCell :: Cell -> String
showCell (Value v) = show v
showCell (Values _ _) = "."
showFree :: Cell -> String
showFree (Value v) = "*"
showFree (Values _ len) = show len
--------------------------------------------------------------------------------
|
dpieroux/euler
|
0/0096_array.hs
|
Haskell
|
mit
| 5,755
|
module SyntaxParser where
import LexicalParser
import Text.Parsec
import Text.Parsec.String
import Data.List
data CompilationUnit = PackageDecl TypeName | ImportDecls [ImportDecl] | TypeDecls [TypeDecl]
deriving (Eq,Ord,Show)
data ImportDecl = ImportDecl TypeName
deriving (Eq,Ord,Show)
data TypeDecl = ClassDecl ClassDeclaration | EnumDecl EnumDeclaration
deriving (Eq,Ord,Show)
data ClassDeclaration = ClassDeclaration [ClassModifier] Ident [TypeParameter] SuperClass [SuperInterface] ClassBody
deriving (Eq,Ord,Show)
data EnumDeclaration = EnumDeclaration String -- TODO
deriving (Eq, Ord, Show)
data TypeName = TypeName String
deriving (Eq,Ord,Show)
data ClassModifier = ClassModifier String
deriving (Eq, Ord, Show)
data Ident = Ident InputElement
deriving (Eq, Ord, Show)
data TypeParameter = TypeParameter String
deriving (Eq, Ord, Show)
data SuperClass = SuperClass ClassType
deriving (Eq, Ord, Show)
data SuperInterface = SuperInterface ClassType
deriving (Eq, Ord, Show)
data ClassType = ClassType Ident [TypeParameter]
deriving (Eq, Ord, Show)
data ClassBody = ClassBody [InputElement] -- TODO
deriving (Eq, Ord, Show)
type JParser = GenParser InputElement ()
satisfy' p = tokenPrim showTok nextPos testTok
where
showTok t = show t
testTok t = if p t then Just t else Nothing
nextPos pos t ts = incSourceColumn pos 1
anyElement :: Monad m => ParsecT [InputElement] u m InputElement
anyElement = satisfy' p <?> "input element"
where p el = True
keyword :: Monad m => String -> ParsecT [InputElement] u m InputElement
keyword kw = satisfy' p <?> ("keyword " ++ kw)
where p el = case el of
T (Keyword keyword) -> keyword == kw
_ -> False
identifier :: Monad m => ParsecT [InputElement] u m InputElement
identifier = satisfy' p <?> "identifier"
where p el = case el of
T (Identifier _) -> True
_ -> False
separator :: Monad m => String -> ParsecT [InputElement] u m InputElement
separator s = satisfy' p <?> ("separator '" ++ s ++ "'")
where p el = case el of
T (Separator sep) -> sep == s
_ -> False
-- compilationUnit :: Parser CompilationUnit
-- compilationUnit = packageDeclaration <|> (many importDeclaration) <|> (many typeDeclaration)
packageDeclaration :: JParser CompilationUnit
packageDeclaration = do
keyword "package"
result <- typeName
separator ";"
return $ PackageDecl result
importDeclaration :: JParser ImportDecl
importDeclaration = do
keyword "import"
result <- typeName
separator ";"
return $ ImportDecl result
typeDeclaration :: JParser TypeDecl
typeDeclaration = classDeclaration <|> interfaceDeclaration
typeName :: JParser TypeName
typeName = do
result <- identifier `sepBy` (separator ".")
let nameParts = map (\(T (Identifier x)) -> x) result
return $ TypeName (intercalate "." nameParts)
classDeclaration :: JParser TypeDecl
classDeclaration = normalClass <|> enumClass
interfaceDeclaration = undefined
normalClass :: JParser TypeDecl
normalClass = do
modifiers <- many classModifier
keyword "class"
name <- identifier
typeParams <- classTypeParams
superClass <- (try $ keyword "extends") >> classType
superInterfaces <- (try $ keyword "implements") >> (classType `sepBy` (separator ","))
separator "{"
classBody <- many anyElement
separator "}"
let classDecl = ClassDeclaration
modifiers (Ident name) typeParams
(SuperClass superClass) (map (\x -> SuperInterface x ) superInterfaces)
(ClassBody classBody)
return $ ClassDecl classDecl
classModifier :: JParser ClassModifier
classModifier = undefined
classTypeParams :: JParser [TypeParameter]
classTypeParams = undefined
classType :: JParser ClassType
classType = undefined
enumClass :: JParser TypeDecl
enumClass = undefined
-- parseSyntax :: String -> Either ParseError CompilationUnit
-- parseSyntax input = parse compilationUnit "unknown" input
parseJava input = parse elements "unknown" input
parseSyntax input = parse importDeclaration "" tokens
where tokens = case (parseJava input) of
Right toks -> filter (not . isWhitespace) toks
_ -> []
isWhitespace t = case t of
Whitespace -> True
_ -> False
|
dimsuz/java-ast
|
src/SyntaxParser.hs
|
Haskell
|
mit
| 4,581
|
module FieldMarshal.Marshal where
import qualified FieldMarshal.CSharp as CSharp
import qualified FieldMarshal.Cpp as Cpp
data MarshalType =
MarshalDefault Cpp.Type CSharp.Type
| MarshalAs Cpp.Type CSharp.Type UnmanagedType
| MarshalWrap Cpp.Type CSharp.Type [CppTypeWrapper]
| MarshalPlatform Cpp.Type CSharp.Type [(Platform, CppTypeWrapper)]
deriving (Eq, Show)
newtype UnmanagedType = UnmanagedType String
deriving (Eq, Show)
data Platform = Microsoft | Mono
deriving (Eq, Show)
data ConversionCode = ConversionCode UnmanagedType Cpp.Type [String] [String]
deriving (Eq, Show)
data CppTypeWrapper =
WrapToCppOwned ConversionCode
| WrapToCppUnowned ConversionCode
| WrapToCSharpOwned ConversionCode
| WrapToCSharpUnowned ConversionCode
deriving (Eq, Show)
|
scott-fleischman/field-marshal
|
FieldMarshal.Marshal.hs
|
Haskell
|
mit
| 793
|
module Handler.Frontend where
import Import
-- will redirect to login page if not authenticated
getFrontendR :: [Text] -> Handler Html
getFrontendR _ = do
_ <- requireAuth
defaultLayout $ do
setTitle "happy scheduler"
$(widgetFile "frontend")
|
frt/happyscheduler
|
Handler/Frontend.hs
|
Haskell
|
mit
| 269
|
module Data.NGH.Formats.FastQ
( fastQConduit
, fastQparse
, fastQread
, fastQwrite
) where
import Data.Word
import qualified Data.ByteString as B
import qualified Data.ByteString as S
import qualified Data.ByteString.Char8 as S8
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Lazy.Char8 as L8
import Data.NGH.FastQ
import Data.Conduit
import Control.Monad
import qualified Data.Conduit.Binary as CB
-- | fastQConduit is a Conduit from B.ByteString to DNAwQuality
fastQConduit :: (Monad m) => Word8 -> Conduit B.ByteString m DNAwQuality
fastQConduit q = CB.lines =$= fastQConduit' q
fastQConduit' :: (Monad m) => Word8 -> Conduit B.ByteString m DNAwQuality
fastQConduit' qualN = read1 >>= maybe (return ()) (\s -> yield s >> fastQConduit' qualN)
where read1 = await >>= maybe (return Nothing)
(\h -> do
Just sq <- await
void await
Just qs <- await
return . Just $ DNAwQuality { dna_seq = sq, header = h, qualities = B.map (flip (-) qualN) qs })
-- | fastQparse read a list of lines and returns a lazy list of DNAwQuality
fastQparse :: Word8 -> [B.ByteString] -> [DNAwQuality]
fastQparse _ [] = []
fastQparse qualN (h:sq:_:qs:rest) = (first:fastQparse qualN rest)
where first = DNAwQuality { dna_seq=sq, header=h, qualities=B.map (flip (-) qualN) qs }
fastQparse _ _ = error "Data.NGH.FastQ.fastQparse: incomplete record"
fastQread :: Word8 -> L.ByteString -> [DNAwQuality]
fastQread qualN = fastQparse qualN . map (S.concat . L.toChunks) . L8.lines
-- | fastQwrite is to write in FastQ format. It does no IO, but formats it as a string
fastQwrite :: Word8 -> DNAwQuality -> L.ByteString
fastQwrite qualN DNAwQuality {header=h,dna_seq=s,qualities=qs} = L.fromChunks
[h
,S8.pack "\n"
,s
,S8.pack "\n+\n"
,S.map (+ qualN) qs
,S8.pack "\n"]
|
luispedro/NGH
|
Data/NGH/Formats/FastQ.hs
|
Haskell
|
mit
| 1,996
|
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
module PresentDrop
( initialModel
, update
, view
) where
import Control.Distributed.Process
import Control.Lens (at, ix, makeLenses, over, set, toListOf)
import qualified Control.Lens as Lens
import Data.Aeson
import Data.Aeson.Casing
import Data.Binary
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Text (Text)
import GHC.Generics
import Network.GameEngine
import System.Random
data Coords = Coords
{ _x :: Double
, _y :: Double
} deriving (Show, Eq, Binary, Generic)
data Player = Player
{ _position :: Coords
, _score :: Integer
, _name :: Text
, _color :: Text
} deriving (Show, Eq, Binary, Generic)
data Gps = Gps
{ _gpsPosition :: Coords
, _variance :: Double
} deriving (Show, Eq, Binary, Generic)
data Model = Model
{ _players :: Map SendPortId Player
, _gpss :: [Gps]
, _present :: Coords
, _rng :: StdGen
} deriving (Show)
makeLenses ''Coords
makeLenses ''Player
makeLenses ''Gps
makeLenses ''Model
instance FromJSON Coords where
parseJSON = genericParseJSON $ aesonDrop 1 camelCase
instance ToJSON Coords where
toJSON = genericToJSON $ aesonDrop 1 camelCase
instance ToJSON Player where
toJSON = genericToJSON $ aesonDrop 1 camelCase
data View = View
{ viewPlayers :: [Player]
, viewGpss :: [ViewGps]
, viewSampleCommands :: [Msg]
} deriving (Show, Eq, Binary, Generic)
data ViewGps = ViewGps
{ viewGpsPosition :: Coords
, viewGpsDistance :: Double
} deriving (Show, Eq, Binary, Generic)
instance ToJSON View where
toJSON = genericToJSON $ aesonPrefix camelCase
instance ToJSON ViewGps where
toJSON = genericToJSON $ aesonDrop 7 camelCase
------------------------------------------------------------
hypotenuse
:: Floating r
=> r -> r -> r
hypotenuse dx dy = sqrt $ (dx ^ (2 :: Int)) + (dy ^ (2 :: Int))
normalise
:: (Floating r, Ord r)
=> (r, r) -> (r, r)
normalise (dx, dy) =
if h <= 1
then (dx, dy)
else (dx / h, dy / h)
where
h = hypotenuse dx dy
distanceBetween :: Coords -> Coords -> Double
distanceBetween a b = hypotenuse dx dy
where
dx = Lens.view x a - Lens.view x b
dy = Lens.view y a - Lens.view y b
randomPair
:: (RandomGen g, Random a)
=> (a, a) -> g -> ((a, a), g)
randomPair range stdGen = ((a, b), stdGen'')
where
(a, stdGen') = randomR range stdGen
(b, stdGen'') = randomR range stdGen'
------------------------------------------------------------
initialModel :: StdGen -> Model
initialModel stdGen =
Model
{ _players = Map.empty
, _gpss =
[ Gps
{ _gpsPosition = Coords (-10) (-8)
, _variance = 0
}
, Gps
{ _gpsPosition = Coords 12 (-5)
, _variance = 0
}
, Gps
{ _gpsPosition = Coords (-4) 9
, _variance = 0
}
]
, _present = Coords 5 3
, _rng = stdGen
}
newPlayer :: Player
newPlayer =
Player
{ _name = "<Your Name Here>"
, _score = 0
, _position = Coords 0 0
, _color = "white"
}
data Msg
= SetName Text
| SetColor Text
| Move Coords
deriving (Show, Eq, Binary, Generic, FromJSON, ToJSON)
update :: EngineMsg Msg -> Model -> Model
update msg = handleWin . handleMsg msg
handleWin :: Model -> Model
handleWin model =
if null overlappingPlayers
then model
else let withIncrementedScores aModel =
Map.foldlWithKey
(\aModel' portId _ ->
over (players . ix portId . score) (+ 1) aModel')
aModel
overlappingPlayers
in movePresent . withIncrementedScores $ model
where
overlappingPlayers :: Map SendPortId Player
overlappingPlayers = Map.filter inRange (Lens.view players model)
inRange :: Player -> Bool
inRange player =
distanceBetween (Lens.view present model) (Lens.view position player) < 1
movePresent :: Model -> Model
movePresent model = set rng newRng $ set present (Coords newX newY) model
where
((newX, newY), newRng) = randomPair (-10, 10) $ Lens.view rng model
handleMsg :: EngineMsg Msg -> Model -> Model
handleMsg (Join playerId) = set (players . at playerId) (Just newPlayer)
handleMsg (Leave playerId) = set (players . at playerId) Nothing
handleMsg (GameMsg playerId (SetName newName)) =
set (players . ix playerId . name) newName
handleMsg (GameMsg playerId (SetColor text)) =
set (players . ix playerId . color) text
handleMsg (GameMsg playerId (Move moveTo)) =
over (players . ix playerId . position) updatePosition
where
updatePosition = over x (dx +) . over y (dy +)
(dx, dy) = normalise (Lens.view x moveTo, Lens.view y moveTo)
view :: Model -> View
view model =
View
{ viewPlayers = toListOf (players . traverse) model
, viewGpss = viewGps (Lens.view present model) <$> Lens.view gpss model
, viewSampleCommands =
[SetName "Kris", SetColor "#ff0000", Move $ Coords 1.0 (-2.0)]
}
viewGps :: Coords -> Gps -> ViewGps
viewGps presentPosition gps =
ViewGps
{ viewGpsPosition = Lens.view gpsPosition gps
, viewGpsDistance =
distanceBetween presentPosition (Lens.view gpsPosition gps) +
Lens.view variance gps
}
|
topliceanu/learn
|
elm/Cloud-Haskell-Game/server/src/PresentDrop.hs
|
Haskell
|
mit
| 5,315
|
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Preprocessor (PreprocessorState, preprocessProg, resolveExpr) where
import Expr
import Program
import Control.Monad.State
import Text.Printf (printf)
import qualified Data.Map.Strict as Map
type Offset = Int
type ConstExprMap = Map.Map String Expr
data PreprocessorState =
PreprocessorState {currOffset :: Offset
,constexprs :: ConstExprMap}
deriving (Show)
initialPreprocessorState :: PreprocessorState
initialPreprocessorState =
PreprocessorState {currOffset = 0
,constexprs = Map.empty}
newtype Preprocessor a =
Preprocessor {runPreprocessor :: State PreprocessorState a}
deriving (Functor,Applicative,Monad,MonadState PreprocessorState)
incrOffset :: Int -> Preprocessor ()
incrOffset n = modify $ \s -> s {currOffset = (currOffset s) + 1}
modifyConstExprs
:: (ConstExprMap -> ConstExprMap) -> Preprocessor ()
modifyConstExprs f = modify $ \s -> s {constexprs = f (constexprs s)}
insertConstExpr
:: String -> Expr -> Preprocessor ()
insertConstExpr n e = modifyConstExprs $ Map.insert n e
preprocessStmt :: Stmt -> Preprocessor ()
preprocessStmt (StInsn _) = incrOffset 1
preprocessStmt (StLabel name) =
do coff <- gets currOffset
insertConstExpr name (ExprInteger (toInteger coff))
preprocessStmt (StConstExpr name expr) = insertConstExpr name expr
execPreprocessor
:: Preprocessor a -> PreprocessorState
execPreprocessor m = execState (runPreprocessor m) initialPreprocessorState
preprocessProg
:: Program -> Either String PreprocessorState
preprocessProg prog = Right $ execPreprocessor $ mapM_ preprocessStmt prog
resolveExpr
:: PreprocessorState -> Expr -> Either String Expr
resolveExpr p (ExprRef n) =
let ces = constexprs p
lu = Map.lookup n ces
in case lu of
Nothing -> Left $ printf "Failed to resolve constexpr ref \"%s\"" n
Just e -> resolveExpr p e
resolveExpr _ e
| (resolved e) = Right e
| otherwise = Left $ printf "failed to resolve constexpr: %s" (show e)
|
nyaxt/dmix
|
nkmd/as/Preprocessor.hs
|
Haskell
|
mit
| 2,042
|
module PlasmaCutter where
import BasicTypes
import LineSintaticScanner
import BoolExprSintaticScanner
extractCode :: [String] -> Environment -> [String]
extractCode [] _ = []
extractCode (x:xs) env = extr ++ (extractCode xs newEnv)
where
extr = [snd $ extractLine (parseLine x) env]
newEnv = fst $ extractLine (parseLine x) env
extractLine :: Line -> Environment -> (Environment, String)
extractLine (Condition line) (var,st) = ((var, newSt), [])
where
evRes = evaluateCondition line var
newSt = [evRes] ++ st
extractLine (EndCondition) (var,st) = ((var, tail st), [])
extractLine (CodeLine line) env@(_,st) = if head st then (env, line) else (env, [])
evaluateCondition :: String -> Variables -> Bool
evaluateCondition fun env = evalFunction env $ parseFunction fun
evalFunction :: Variables -> Expression -> Bool
evalFunction env (And lhs rhs) = (evalFunction env lhs) && (evalFunction env rhs)
evalFunction env (Or lhs rhs) = (evalFunction env lhs) || (evalFunction env rhs)
evalFunction env (Not exp) = not (evalFunction env exp)
evalFunction env (ExpId var) =
let exp = [snd x | x <- env, var == fst x]
in case exp of
[] -> error (var ++ " not in scope.")
[x] -> x
|
hephaestus-pl/hephaestus
|
willian/hephaestus-parser-only/PlasmaCutter.hs
|
Haskell
|
mit
| 1,212
|
import Data.List.Split
type State = [[Int]]
type Pos = (Int, Int)
main :: IO ()
main = do
print $ lightsOn $ iterate nextState (lightCorners initialState) !! 100
return ()
prettifyState :: State -> String
prettifyState = concatMap ((++"\n") . show)
lightsOn :: State -> Int
lightsOn s = length $ filter (==1) $ concat s
initialStateExample :: State
initialStateExample = [
[0,1,0,1,0,1],
[0,0,0,1,1,0],
[1,0,0,0,0,1],
[0,0,1,0,0,0],
[1,0,1,0,0,1],
[1,1,1,1,0,0]
]
lightCorners :: State -> State
lightCorners s = chunksOf (nbrOfCols s) [ valueOfPos' s (x,y) | x <- [0..(nbrOfRows s - 1)], y <- [0..(nbrOfCols s - 1)] ]
nextState :: State -> State
nextState s = chunksOf (nbrOfCols s) $ [ calculatePos s (x,y) | x <- [0..(nbrOfRows s - 1)], y <- [0..(nbrOfCols s - 1)] ]
nbrOfRows :: State -> Int
nbrOfRows = length
nbrOfCols :: State -> Int
nbrOfCols = length . head
calculatePos :: State -> Pos -> Int
calculatePos s p = case valueOfPos' s p of
1 -> if isCorner s p || f (length (filter (==1) nbs)) then 1 else 0
0 -> if length (filter (==1) nbs) == 3 then 1 else 0
where
f i = i == 3 || i == 2
nbs = neighbors s p
neighbors :: State -> Pos -> [Int]
neighbors s (x,y) = [valueOfPos' s (x',y') | x' <- [x-1..x+1], y' <- [y-1..y+1], (x',y') /= (x,y) ]
valueOfPos' :: State -> Pos -> Int
valueOfPos' s p@(x,y) | isOutSide s p = 0
| isCorner s p = 1
| otherwise = (s !! x) !! y
isOutSide :: State -> Pos -> Bool
isOutSide s (x,y) = x >= nbrOfRows s || x < 0 || y >= nbrOfCols s || y < 0
isCorner :: State -> Pos -> Bool
isCorner s (x,y) = ((nbrOfRows s - 1) == x && yCorner) || (x == 0 && yCorner)
where
yCorner = nbrOfCols s - 1 == y || y == 0
valueOfPos :: State -> Pos -> Int
valueOfPos s (x,y) = if isOutSide s (x,y) then 0 else (s !! x) !! y
where
isOutSide :: State -> Pos -> Bool
isOutSide s (x,y) = x >= nbrOfRows s || x < 0 || y >= nbrOfCols s || y < 0
initialState :: State
initialState = s
where
s = [[1,0,0,0,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,1,0,1,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0,1,1,0,1,0,1,0,1,1,1,0,1,0,1,0,0,1,0,0,1,0,0,0,0,0,0,1,1,1,1,0,0,1,0,0,0,0,0,0,1,1,1,0,1,0,1,0,0,0,0,1,0,0,1,1,0,0,1,1,1,0,0],
[1,1,1,1,0,0,1,0,1,0,0,0,1,0,0,0,0,1,0,1,1,1,1,1,0,1,1,0,1,1,0,1,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,1,0,1,1,0,0,0,1,1,1,0,1,1,1,0,0,1,0,1,0,1,0,0,0,0,0,0,0,0,1,0,0,1,0,1,0,1,1,0,0,0,1,1,0,0,1,0,1,1,1,1,0,1],
[0,0,0,1,0,0,1,1,0,0,0,1,0,1,0,1,1,1,0,1,0,1,1,1,0,0,1,0,1,1,0,1,1,1,1,0,1,1,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,0,0,1,1,0,1,0,1,1,0,1,0,1,1,1,0,0,0,1,0,1,0,0,1,1,1,0,0,0,0,1,0,1,1,1,0,1,0,0,1,0],
[0,1,0,0,0,1,1,0,0,0,1,1,1,1,0,1,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,1,0,1,0,1,1,0,0,0,1,0,0,0,1,1,0,0,1,0,1,0,1,1,1,0,0,0,0,1,0,0,1,1,1,0,0,0,0,0,1,1,0,0,1,0,1,1,1,0,0,1,1,1,0,0,0,0,0,1,1,0,0,1,1,1,0,0,0,1],
[0,0,1,1,0,1,1,1,1,1,0,0,0,0,1,1,0,0,1,0,1,0,0,1,1,0,1,1,0,0,1,1,1,1,1,1,0,0,0,1,0,0,1,1,1,0,1,1,1,1,1,1,0,0,0,0,0,1,0,0,1,1,0,0,0,1,0,1,0,0,1,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,1,1,0,1,0,1,0,1,0,1,0,0,0],
[0,1,1,1,0,1,1,1,0,1,1,1,0,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0,0,1,1,0,1,1,1,0,1,0,0,0,0,0,1,1,0,0,1,1,0,1,0,1,1,1,1,1,1,1,1,1,0,0,0,1,1,0,0,1,1,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,1,1,1,0,0,1,0,1,0,1,0,1,1,1,1,1],
[1,0,1,1,1,1,1,0,0,1,1,1,0,1,1,1,0,1,1,0,1,1,0,1,0,0,0,1,0,1,0,1,0,1,0,0,1,0,1,1,1,0,0,0,1,0,0,1,1,0,1,1,1,0,1,0,0,0,1,1,1,1,0,1,0,0,1,0,1,0,0,0,0,0,1,1,1,0,0,1,0,0,1,1,1,1,0,0,1,0,1,0,1,0,0,0,1,1,0,0],
[0,0,0,0,1,0,0,0,1,1,0,0,0,0,0,1,0,0,0,0,1,1,1,1,0,1,1,0,1,0,1,1,1,0,0,1,0,1,0,1,1,0,0,1,0,1,0,0,0,1,1,0,1,1,1,0,1,1,1,0,0,1,0,1,1,0,0,1,0,1,0,1,1,0,0,1,1,0,0,1,0,1,1,0,1,1,1,0,0,1,0,1,0,1,1,1,0,1,1,1],
[1,1,0,1,1,0,0,0,1,0,1,1,0,0,0,1,0,1,0,0,1,0,1,0,0,1,0,0,0,1,1,1,0,0,0,1,1,1,0,1,0,0,1,0,0,1,0,1,1,1,1,1,0,0,1,1,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,1,1,1,0,1,1,1,1,1,0,1,0,1,0,0,1,0,1,0,1,0,1,1,0,0,1,0,1,0],
[1,0,1,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,1,0,1,0,0,1,1,0,0,0,1,1,1,0,0,1,1,0,0,0,1,1,0,0,0,1,1,1,0,1,0,1,1,1,0,1,0,0,1,0,1,0,1,1,1,0,0,0,1,1,0,0,1,1,0,0,1,0,1,1,1,0,0,0,1,0,1,1,1,1,1,1,1,0,1,0,0,0,1,0,1,0],
[1,0,1,0,0,0,0,0,1,1,1,1,0,1,0,0,1,0,1,1,0,0,0,1,0,1,1,0,0,0,0,1,1,1,1,1,0,1,1,1,0,1,0,0,0,0,0,1,1,1,1,1,0,0,0,0,1,1,1,0,0,1,0,0,0,0,0,0,0,0,1,1,0,0,1,1,1,1,0,0,0,1,0,0,0,1,0,1,1,1,0,0,0,0,1,0,0,1,1,1],
[1,1,0,1,0,1,1,0,0,1,0,1,0,1,1,0,1,0,0,0,0,0,1,1,0,1,0,0,0,0,0,1,1,1,0,1,1,1,1,0,1,0,0,1,1,1,1,1,1,0,0,0,0,0,1,1,1,1,0,1,0,1,0,0,1,1,0,1,0,1,1,0,0,0,1,0,0,1,0,1,0,0,0,0,0,1,0,1,1,1,1,0,1,0,0,0,0,0,0,0],
[1,0,0,1,0,0,1,0,1,0,0,1,0,1,1,1,1,1,1,0,1,1,0,0,1,1,0,1,1,1,1,0,0,0,0,0,1,1,0,1,0,1,1,0,1,0,1,1,1,1,1,1,0,0,1,0,1,0,0,0,0,1,0,1,0,0,0,1,0,1,0,0,1,0,0,1,0,1,0,1,1,1,0,1,0,0,1,0,1,0,1,0,0,1,0,0,0,1,1,1],
[1,1,1,1,0,0,1,1,1,1,0,1,0,1,0,1,1,1,0,0,0,0,0,1,0,1,0,1,0,1,1,0,0,1,0,1,1,0,1,1,0,1,1,0,1,0,0,1,1,0,0,1,1,0,1,0,1,1,0,0,0,0,0,1,0,1,0,0,1,0,1,1,1,1,0,0,0,0,0,1,1,1,0,1,0,0,1,0,1,1,1,1,0,1,0,1,0,0,1,1],
[1,1,1,0,1,1,0,0,1,1,0,1,0,1,1,0,0,1,0,0,1,1,0,0,0,1,0,1,1,1,1,1,0,1,1,0,1,0,0,0,0,1,1,0,1,1,1,1,0,1,0,1,1,0,0,0,0,1,0,0,1,1,1,0,1,0,1,0,1,1,0,0,0,1,0,0,0,0,0,1,0,1,0,1,0,1,0,1,0,0,1,1,0,1,0,1,0,0,1,0],
[0,0,0,0,0,0,1,0,0,1,1,1,1,0,0,0,1,1,0,1,1,0,0,0,1,0,1,1,0,1,1,0,0,0,1,1,0,0,1,0,0,1,1,0,1,1,1,0,0,1,0,0,0,1,0,0,1,1,0,0,0,1,0,1,0,0,0,0,1,1,1,0,1,1,1,1,0,0,0,1,0,1,1,0,1,1,1,0,1,0,1,1,0,1,1,1,1,0,1,1],
[0,0,1,0,0,0,1,1,1,1,1,0,1,0,1,0,0,1,0,1,1,0,0,0,0,1,0,0,1,0,0,0,1,0,0,1,1,1,1,0,0,0,0,0,1,1,1,0,0,0,1,1,0,1,1,1,0,0,0,0,1,0,0,1,0,1,1,1,0,0,0,1,0,0,0,0,0,0,0,0,1,0,1,0,1,1,0,0,1,0,0,1,0,1,0,0,0,0,0,1],
[1,1,1,1,1,1,1,0,1,0,1,0,1,1,1,0,1,1,1,0,0,1,1,1,1,1,1,0,1,1,0,0,1,1,1,1,1,0,1,1,0,1,1,1,0,1,1,1,0,0,0,0,1,1,1,1,0,1,0,0,1,1,0,1,1,0,0,0,1,1,1,0,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,0,0,0,0,1,1,0,1],
[1,0,1,0,0,0,1,1,0,1,1,1,0,1,0,1,1,1,0,0,1,0,1,0,1,0,1,0,1,0,1,0,0,1,1,0,0,1,1,1,1,0,1,0,0,1,1,0,0,0,0,0,1,0,1,1,0,0,1,0,1,1,0,0,0,1,1,0,1,0,0,1,1,0,0,1,0,1,0,1,0,0,0,0,1,1,0,0,0,0,1,1,0,1,0,0,1,0,1,0],
[0,0,1,0,1,0,1,1,1,1,0,0,0,0,0,1,1,1,0,0,1,1,1,1,1,1,1,0,1,0,1,0,1,0,1,0,0,0,1,1,0,1,1,1,1,1,0,0,0,0,0,1,1,0,0,0,1,1,0,0,0,1,1,0,1,1,1,0,0,1,1,1,1,1,1,0,1,1,1,0,0,1,0,0,0,1,1,1,1,0,1,0,0,1,1,1,0,1,1,1],
[0,1,0,1,1,0,0,0,0,1,0,1,0,1,1,0,0,1,1,0,1,0,1,1,0,1,1,0,0,1,1,1,1,1,1,0,0,0,1,0,0,0,0,0,1,0,0,1,0,1,0,1,0,1,0,0,0,0,0,1,0,1,0,0,1,1,0,1,0,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0],
[0,0,1,1,1,0,1,1,0,1,1,0,0,1,1,0,0,0,0,1,0,1,1,1,0,0,0,1,0,0,0,0,0,1,1,0,0,1,1,0,0,0,0,0,0,1,1,1,0,0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,0,1,1,1,0,1,0,1,0,1,0,1,1,1,0,1,1,1,0,1,0,1,0,0,0,1,1,1,0,0,1,0,0,0],
[0,1,1,0,1,0,1,0,0,0,1,0,0,0,1,1,0,1,0,1,0,0,0,1,0,0,1,0,0,1,0,1,0,0,0,1,1,0,1,0,1,1,0,0,0,1,1,0,0,1,0,0,0,0,1,0,1,0,0,1,1,0,1,0,0,1,0,1,0,0,1,0,1,0,0,0,0,0,1,0,0,1,0,1,0,0,0,1,1,1,1,1,1,1,0,1,0,1,1,0],
[0,0,0,1,1,1,1,0,0,0,0,1,0,1,1,1,0,1,0,0,1,1,1,0,0,1,1,0,0,0,1,1,0,0,1,0,1,0,1,0,1,1,1,0,0,0,1,0,0,1,1,0,1,1,0,1,1,0,0,1,1,0,1,0,0,0,1,0,0,1,0,1,1,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,1,0,0,1,0,1,0,1,1,1,1],
[0,0,0,0,0,1,1,0,0,1,1,1,0,0,0,1,0,0,0,0,1,0,1,0,1,0,1,0,0,0,1,1,1,0,1,1,1,0,0,0,1,0,1,0,0,0,1,0,1,0,1,1,1,1,0,0,0,0,1,0,0,1,1,1,1,0,0,0,1,1,1,0,0,1,0,0,1,1,1,1,1,1,0,0,1,1,0,1,1,0,0,1,1,1,0,1,1,1,1,1],
[1,1,1,1,1,0,1,1,0,0,1,0,0,0,0,1,1,1,0,1,1,1,0,0,0,0,1,1,0,0,0,0,0,1,0,1,0,0,1,0,0,0,0,1,0,1,1,1,1,1,0,1,1,0,1,0,1,1,1,1,0,1,0,1,1,0,0,0,1,0,0,1,1,1,0,0,0,1,1,1,0,0,1,1,0,0,0,1,0,1,1,1,0,1,1,1,1,1,0,0],
[1,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,0,0,0,0,1,1,1,1,0,1,1,1,0,1,0,0,1,1,0,0,0,1,0,1,1,0,1,1,1,1,0,1,0,0,0,0,0,1,1,0,0,1,1,1,1,1,0,0,1,1,1,0,0,0,1,1,1,1,1,0,0,0,0,0,1,0,1,0,1],
[1,1,0,0,1,1,1,1,1,0,1,1,0,1,0,1,1,1,1,1,0,1,0,1,1,0,1,1,0,0,1,0,1,1,0,0,0,0,1,1,1,1,1,1,1,1,0,1,1,1,1,1,0,1,0,0,0,1,0,1,1,1,0,1,1,0,0,0,1,0,1,1,1,0,1,0,1,0,0,1,0,0,0,0,1,1,0,1,0,0,1,0,0,0,1,0,1,0,1,0],
[0,1,1,0,1,0,0,0,0,1,0,0,1,0,0,0,1,0,0,1,1,1,1,1,0,0,1,0,0,1,1,0,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,1,0,0,1,0,0,0,1,0,0,0,0,0,1,1,1,1,0,1,0,0,0,1,1,0,0,0,1,0,1,1,1,0,1,0,1,0,0,1,1,0,1],
[0,1,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,0,0,1,0,1,0,1,0,0,1,1,0,1,1,0,1,1,1,0,1,0,0,1,1,0,0,1,0,0,0,1,1,1,0,1,1,0,1,1,1,0,1,1,1,1,1,0,1,0,1,1,1,0,0,1,0,0,1,1,1,0,1,0,0,0,1,0,1,1,1,0,1,0,0,0,1,0,0,1,0,1,0,1],
[0,1,0,0,1,0,0,1,0,1,0,0,1,0,0,1,1,1,0,0,1,0,0,0,0,1,1,1,0,1,1,1,1,0,1,1,0,1,0,1,1,1,0,1,0,1,1,0,1,1,1,0,1,0,1,1,0,1,1,1,0,1,1,1,0,0,0,1,1,1,0,0,0,1,1,1,0,1,0,0,0,1,1,1,1,0,0,0,1,0,1,1,0,1,1,0,1,0,1,0],
[1,1,1,0,0,1,1,0,0,0,1,1,1,0,0,0,1,0,0,1,1,0,1,0,0,1,0,1,0,0,0,1,1,0,0,0,0,1,1,1,0,1,1,0,1,1,0,0,1,1,1,1,1,0,0,0,0,1,1,1,0,0,1,0,0,1,0,0,0,0,1,0,0,1,1,1,0,1,1,1,0,1,0,0,0,1,0,1,1,0,0,0,1,0,1,0,1,0,0,1],
[1,0,0,0,0,1,0,0,0,0,0,0,0,1,1,0,0,0,0,0,1,0,1,1,0,0,0,1,0,0,1,0,1,1,1,0,1,0,1,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,1,1,1,0,0,1,1,0,1,1,0,0,0,1,1,1,1,1,0,1,0,0,1,1,1,1,1,0,0,1,1,1,1,1,0,0,1,1,1,1,1,0,0,0,0,1],
[0,1,1,1,1,0,1,1,1,1,0,0,0,0,1,1,1,0,0,1,1,1,0,1,0,1,1,0,1,1,1,1,0,1,1,0,1,0,0,0,1,1,1,1,0,1,0,1,1,1,0,1,0,0,0,0,0,1,0,0,0,1,1,1,1,0,0,1,1,1,1,1,0,1,1,1,0,0,1,0,1,0,1,1,1,0,1,1,0,1,1,0,0,0,1,1,0,0,1,0],
[1,1,1,1,0,0,1,1,0,0,0,1,1,0,1,1,1,1,1,1,1,1,0,0,0,1,1,0,0,1,1,1,0,0,1,0,0,1,1,1,0,1,1,0,1,0,1,0,1,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,1,0,0,0,1,0,1,1,1,0,1,1,1,1,0,1,0,0,1,1,1,1,0,0,1,0,1,0,1,0,0,0,0,1,1],
[1,1,1,0,1,0,0,1,0,0,0,1,1,1,0,1,0,0,1,0,0,1,0,1,1,1,0,0,0,1,1,0,0,1,1,1,0,1,1,0,1,0,1,0,0,0,1,0,0,1,0,0,0,1,1,1,1,0,0,1,1,0,0,0,0,1,0,1,0,0,1,0,0,1,1,0,1,0,1,0,0,0,1,1,1,1,1,0,1,1,1,0,1,0,0,1,0,1,0,1],
[0,0,0,1,1,0,0,0,0,1,0,1,1,1,0,1,0,1,0,0,1,1,0,0,0,1,1,0,1,1,1,0,1,0,0,1,0,0,1,0,0,0,0,0,0,1,0,0,0,1,0,1,0,0,1,1,1,1,0,1,0,1,1,0,0,1,1,1,1,1,1,0,1,1,1,1,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,1,0,1,0,1,0,1,1,0],
[1,1,0,1,1,1,1,0,1,0,0,0,1,0,0,1,0,1,0,1,1,0,0,1,1,0,1,0,1,0,1,1,1,0,0,1,1,0,0,0,1,1,1,1,0,0,0,0,0,0,1,0,0,1,1,1,1,1,1,0,1,0,0,0,0,0,0,1,0,1,1,0,1,0,0,0,0,1,1,0,0,0,1,1,1,0,1,0,1,0,0,1,0,0,0,0,0,0,1,1],
[1,0,0,0,0,0,1,0,0,0,1,1,1,1,1,1,1,0,1,1,0,1,0,0,1,0,1,0,0,0,1,1,1,0,1,0,0,1,0,1,1,1,1,0,0,0,0,1,0,1,0,1,1,0,1,0,1,1,0,0,0,1,1,1,0,0,1,0,0,0,1,0,1,1,1,0,1,1,0,0,1,0,1,1,1,0,0,1,0,1,1,0,0,0,1,1,1,1,1,0],
[1,1,1,1,1,0,1,1,0,0,0,1,0,0,1,0,1,0,1,0,0,0,0,0,0,0,1,0,1,1,0,0,1,1,1,1,1,0,0,1,1,1,1,1,0,0,0,1,1,1,0,0,1,1,0,1,0,1,0,0,1,1,1,0,1,0,1,1,1,1,1,0,1,1,1,1,0,0,1,0,1,0,0,1,1,0,0,0,1,0,1,1,0,0,0,1,0,1,1,1],
[0,1,1,0,1,0,0,1,1,1,1,1,1,1,0,1,1,1,0,1,0,1,1,1,1,0,0,0,0,0,1,1,0,0,0,1,0,1,1,0,1,0,1,0,0,1,0,0,0,1,1,0,0,0,0,1,1,1,1,0,0,0,0,0,0,1,1,1,1,1,1,0,1,0,0,1,1,1,1,1,1,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,1,1,0],
[1,1,0,0,0,1,0,1,0,0,1,0,1,1,0,1,1,1,0,1,0,1,0,1,0,1,1,0,1,1,1,0,1,1,0,0,1,1,0,1,1,0,1,1,0,0,0,1,0,1,0,0,1,1,1,0,1,1,1,1,1,1,1,0,0,1,0,0,0,0,0,1,1,1,1,1,0,0,1,0,0,0,0,1,1,1,1,1,1,0,1,0,0,1,1,0,0,1,1,1],
[0,1,0,1,0,1,1,1,0,0,0,0,0,1,0,0,1,1,0,0,1,0,1,0,0,1,1,0,0,1,0,1,1,1,0,0,0,1,1,1,0,1,0,0,1,1,0,0,0,1,0,0,0,1,0,1,1,1,1,1,0,1,0,1,1,1,1,1,0,0,1,1,1,0,1,0,0,1,0,0,0,1,1,0,0,1,0,1,0,0,1,0,0,1,1,1,1,0,0,0],
[0,1,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,1,1,1,1,0,1,1,1,0,0,0,0,1,1,0,1,1,1,0,0,0,0,0,1,1,1,0,1,1,0,0,0,0,0,0,0,0,1,0,1,1,1,0,1,1,0,0,1,0,0,1,0,1,1,1,1,1,1,1,0,1,0,1,1,1,1,1,1,0,0,1,1,0,0,1,1,1,0,0,0,0,0],
[0,0,1,1,0,1,0,1,0,0,1,0,1,1,0,0,0,1,0,1,1,1,0,1,1,1,0,0,0,1,1,1,1,1,1,0,0,1,0,0,1,0,1,0,0,1,0,0,0,0,1,1,1,0,1,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,1,0,1,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,1,1,1,0],
[1,1,1,0,1,1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1,0,0,1,1,0,0,0,0,0,1,1,0,0,0,0,0,1,0,0,1,1,1,1,1,1,1,0,1,0,0,1,0,1,0,1,0,1,1,1,1,0,1,1,1,0,0,1,1,1,0,1,0,1,0,0,1,0,1,1,0,1,1,0,1,1,1,1,0,1,1,1,0,1,1,1,1],
[1,0,1,0,1,0,0,1,0,0,0,0,1,1,1,1,1,1,1,1,0,1,0,0,1,0,0,1,0,0,0,1,1,0,0,1,0,1,1,0,0,1,0,1,0,0,1,1,0,0,1,1,1,1,0,0,0,1,1,0,0,0,0,0,1,0,1,1,0,1,0,1,0,0,0,1,1,1,1,1,1,1,1,0,0,1,0,1,1,1,0,1,0,0,1,0,1,0,1,1],
[0,1,1,0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,1,1,0,1,1,0,0,0,0,1,1,1,0,0,0,1,1,0,0,1,0,1,1,1,1,0,0,0,1,0,0,1,0,1,0,0,1,0,0,1,0,1,1,0,0,1,0,1,1,1,0,1,1,0,1,1,1,1,0,1,1,0,0,1,1,1,1,0,0,0,0,0,1,1,0,1,0,0,0,0,0,1],
[0,0,0,0,1,1,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,0,1,1,0,1,0,1,1,1,1,1,1,0,1,1,0,1,1,1,1,0,0,1,0,0,0,1,1,1,1,0,1,0,0,1,1,1,0,1,0,1,0,0,1,0,0,1,1,0,1,0,1,0,0,0,0,0,1,1,0,1,1,1,1,1,0,1,0,1,1,1,1,0,0,0,1,0,1,0],
[1,0,0,1,1,1,1,1,0,1,1,1,1,1,0,0,0,0,0,1,1,0,0,0,0,1,1,1,1,1,1,0,0,1,1,0,0,0,0,1,0,0,1,0,1,0,1,1,1,0,1,1,1,1,1,0,0,0,0,0,1,1,0,1,1,0,1,1,1,1,0,1,0,0,0,1,1,0,0,0,1,0,1,1,0,1,0,1,1,1,1,1,0,1,1,0,1,0,0,0],
[1,1,0,1,1,1,1,0,0,1,1,1,0,1,0,0,0,0,1,0,0,0,1,0,1,0,1,0,1,0,1,1,1,0,1,1,1,1,1,0,1,0,1,1,1,1,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,0,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,0,1,1,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,1,0,0,0],
[0,1,1,1,0,1,0,1,0,1,0,1,0,0,1,1,1,1,0,1,1,0,1,0,0,1,1,1,1,1,1,0,0,1,0,1,0,1,1,1,0,0,0,0,0,1,0,1,0,0,0,0,0,0,1,0,1,0,1,0,1,0,0,1,1,1,1,0,1,1,0,0,0,1,1,0,1,1,1,1,1,0,1,0,1,1,0,0,1,1,0,0,1,0,0,1,0,1,0,0],
[0,0,0,0,0,1,1,1,0,0,0,1,0,0,0,1,0,1,1,1,1,0,1,1,1,0,1,0,1,0,1,0,1,0,0,0,0,0,1,0,0,0,0,1,0,1,1,1,1,0,1,1,1,0,1,1,0,1,1,0,1,1,0,1,1,1,1,1,1,1,0,0,0,0,0,0,1,0,1,1,1,1,0,0,0,0,0,0,1,0,0,0,0,1,1,0,0,0,0,0],
[1,1,0,0,1,0,0,1,0,1,0,1,1,0,0,1,0,0,0,1,0,0,1,1,0,1,1,0,1,1,0,0,1,1,1,0,1,0,0,0,0,1,1,0,1,1,0,0,0,0,1,1,1,1,0,1,0,1,1,0,1,1,1,0,0,0,0,1,0,1,1,0,1,0,1,0,1,1,0,0,0,1,1,0,1,1,1,0,0,0,1,0,0,1,0,0,1,1,1,1],
[0,0,0,1,0,1,0,0,1,1,0,0,1,1,0,1,0,0,0,1,1,0,1,1,0,0,0,1,0,1,0,0,0,0,0,0,1,0,1,0,1,1,0,0,1,1,1,0,0,0,0,1,1,1,1,0,1,1,0,0,0,1,0,1,0,1,1,1,0,1,0,0,1,0,0,1,0,1,1,1,1,0,0,1,1,0,0,1,1,0,0,1,1,1,1,1,0,1,1,1],
[0,1,1,0,1,1,0,0,1,1,1,1,1,1,1,1,1,1,0,1,1,0,0,0,1,0,1,1,0,1,1,1,1,0,1,0,1,1,1,1,1,1,1,0,1,1,0,1,0,1,1,0,1,1,0,0,1,0,0,0,1,1,0,0,0,0,1,1,1,1,1,1,1,1,0,1,1,1,0,0,1,1,0,1,1,0,1,1,0,1,0,0,1,1,0,1,0,1,0,1],
[1,1,1,1,1,0,1,0,0,0,0,1,0,1,1,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,1,1,0,1,1,0,0,1,0,1,1,0,1,1,1,0,0,1,1,0,0,0,0,0,0,0,1,1,1,0,0,1,1,0,1,0,1,1,1,0,1,1,0,1,1,1,0,0,0,0,1,1,1,1,0,1,0,0,1,0,1,1,1,0,0,1,0,1,0,1],
[0,1,0,0,0,1,0,0,1,0,1,1,0,0,0,0,1,1,0,0,0,0,1,0,0,0,1,1,1,1,0,0,0,0,1,0,0,0,1,0,0,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,0,1,1,1,0,1,0,0,1,1,0,1,0,1,0,1,1,0,0,1,1,1,0,0,1,0,1,0,1,1,1,0,0,0,0,0,1,1,0,1],
[1,1,0,0,1,1,0,0,0,0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,1,1,0,1,1,0,1,1,1,1,0,1,1,0,1,1,1,1,0,1,0,1,0,0,0,0,1,0,0,1,0,0,0,1,0,0,1,0,1,0,0,1,0,1,1,1,0,1,0,0,0,1,0,0,0,1,0,0,1,1,0,1,1,0,0,0,1,0,0,1,1,1,1,1,1,1],
[0,0,0,0,0,1,1,0,0,1,1,1,0,0,1,1,0,0,0,1,1,1,1,1,0,1,0,1,0,0,0,0,0,1,1,1,0,1,0,1,0,0,1,1,1,1,0,0,0,1,0,1,0,1,0,0,1,0,0,1,1,1,1,0,0,1,1,0,1,0,0,1,1,1,0,1,1,1,1,0,1,0,0,0,0,1,1,0,0,1,1,1,0,0,0,0,1,0,0,1],
[1,0,1,0,1,1,0,1,0,0,0,0,1,0,1,1,1,1,1,0,1,0,0,0,0,1,1,0,0,0,1,0,0,0,1,1,0,0,0,1,1,0,0,0,0,1,0,1,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,1,0,0,0,1,1,1,0,1,1,1,0,1,0,1,1,1,1,0,0,1,1,1,1,0,0,0,0,1,0,1,1,0,1,0,1,0],
[0,0,1,1,0,0,0,1,1,0,0,1,1,1,0,1,0,1,0,1,1,0,1,0,0,1,0,0,0,0,1,0,1,0,0,0,0,0,1,1,0,1,1,1,0,1,0,1,1,1,0,1,1,1,0,0,0,0,0,1,0,0,0,1,0,1,0,0,1,1,1,1,1,1,1,0,1,1,1,1,1,0,0,1,0,1,1,1,0,0,0,1,1,0,0,0,0,0,0,1],
[1,0,0,0,0,0,0,1,1,1,0,0,1,0,0,0,0,1,0,1,0,0,1,0,1,1,1,0,1,1,0,1,0,0,0,1,1,0,0,1,1,1,0,1,1,1,1,0,1,0,1,0,0,0,0,1,0,1,1,0,0,1,0,1,1,1,0,0,1,1,0,1,0,0,1,1,1,1,1,0,0,1,1,0,1,1,1,0,0,0,0,0,1,0,0,1,1,1,0,0],
[1,1,0,1,0,1,1,0,0,1,1,0,1,1,1,0,1,0,0,1,1,0,0,0,0,0,1,0,1,1,0,0,0,0,0,1,1,1,0,0,0,0,1,1,0,1,1,1,1,0,1,1,1,1,1,1,0,1,0,0,0,1,0,0,1,1,1,0,0,0,0,1,0,1,0,0,0,1,0,1,1,0,0,0,0,0,1,1,1,0,0,0,0,1,0,0,1,0,1,0],
[0,1,1,0,1,0,1,0,1,0,1,1,0,0,1,0,1,0,1,0,0,1,1,0,0,1,0,1,1,1,0,1,1,1,1,0,0,0,0,1,0,0,1,1,1,0,1,1,1,1,1,1,0,0,1,1,1,1,0,1,0,0,0,0,0,1,1,1,0,1,1,0,0,1,0,0,0,1,1,1,0,1,0,0,1,1,1,1,1,1,0,1,1,0,1,0,1,1,0,0],
[0,0,0,1,1,0,1,1,1,1,0,1,0,0,1,1,0,1,1,1,1,1,0,1,1,0,1,0,0,0,1,1,0,0,1,0,0,1,0,0,0,1,0,1,0,1,0,1,1,1,1,1,0,0,0,1,0,0,0,0,1,0,0,1,1,1,0,0,0,1,0,0,1,0,0,0,0,1,0,1,0,1,1,0,1,0,1,1,1,1,1,1,0,1,0,0,1,1,1,1],
[0,0,1,0,1,0,1,0,1,0,0,0,1,0,1,1,1,1,1,1,0,1,0,0,0,0,0,1,0,0,1,0,1,0,0,1,1,1,0,0,0,0,1,0,1,0,1,1,1,1,1,1,1,1,0,0,0,1,0,0,0,0,1,0,1,0,1,1,0,0,1,0,0,0,1,1,0,0,0,1,0,1,0,0,1,0,1,0,1,1,1,0,0,0,0,1,1,0,0,0],
[1,1,1,1,1,0,0,1,0,0,1,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,1,0,1,1,0,1,0,0,0,0,1,1,1,1,1,0,1,1,1,1,0,1,1,0,1,0,1,1,1,0,0,1,1,0,0,1,1,0,0,0,0,1,0,0,0,0,0,1,0,1,1,1,1,1,0,1,0,0,0,1,0,1,1,1,1,1,0,1,1,0,1,0,1,0],
[1,0,1,0,0,1,1,1,1,1,0,0,0,1,1,1,1,0,1,1,1,0,1,1,1,0,0,0,0,0,1,1,1,1,0,1,1,1,0,0,0,0,0,1,1,0,0,0,1,1,0,0,0,1,0,0,1,0,0,1,1,1,1,1,1,1,0,1,0,1,1,0,0,0,0,1,1,0,0,1,1,1,1,0,0,0,0,0,1,1,0,0,0,1,0,0,1,0,0,1],
[1,0,1,0,1,1,1,0,1,0,1,0,0,1,1,0,0,1,0,0,0,0,1,0,1,0,0,0,1,0,1,0,1,1,0,1,1,0,0,1,0,1,1,0,0,0,0,0,1,1,0,0,0,1,0,1,0,0,1,1,0,0,0,0,0,0,0,1,1,0,1,0,1,1,1,0,0,1,1,1,1,1,0,1,0,1,1,0,0,0,0,1,0,1,1,0,0,0,0,0],
[0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,1,0,1,0,1,1,1,1,0,1,0,1,1,1,0,1,1,1,0,0,1,0,0,0,0,1,0,0,1,1,0,1,0,0,1,1,1,1,0,0,0,0,0,0,0,0,1,0,1,1,0,0,1,0,0,0,1,0,1,0,0,0,1,1,1,0,1,0,0,1,0,1,0,1,0,0,0,1,0,0,0,1,0,0],
[0,0,0,1,1,0,1,1,1,1,1,0,1,1,0,1,0,1,1,1,0,1,1,0,1,1,0,1,0,1,1,0,0,1,1,0,1,0,1,0,1,0,1,0,1,0,1,1,0,1,0,0,1,1,0,0,0,1,1,0,1,0,1,0,0,1,0,0,1,1,0,1,1,0,1,1,1,1,1,0,1,0,1,1,1,0,0,0,1,1,1,1,1,0,0,1,0,0,1,0],
[1,1,1,1,1,1,1,0,1,0,0,1,0,0,1,0,0,0,0,1,1,0,1,0,1,0,0,1,1,1,1,0,1,0,0,1,0,0,1,1,1,0,0,0,1,0,0,1,0,0,0,0,0,0,0,1,1,1,0,1,0,1,0,1,1,1,1,0,0,0,0,1,0,1,1,1,0,0,0,1,0,1,0,1,1,1,0,1,0,1,0,1,0,1,0,0,1,1,1,0],
[0,0,1,1,0,1,1,0,1,0,1,1,0,1,1,1,0,0,0,0,1,1,1,0,1,1,0,1,0,1,1,1,0,1,0,0,0,1,0,0,0,0,1,0,1,1,1,1,0,0,1,1,1,0,0,1,1,1,0,1,0,1,0,0,1,0,0,0,1,1,0,1,0,1,0,1,0,0,1,1,0,1,1,1,0,0,1,1,1,0,1,0,1,1,0,0,0,1,1,1],
[1,1,1,1,1,1,0,0,1,1,1,1,1,1,0,0,1,1,0,0,1,1,0,1,0,1,0,1,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,0,1,0,1,1,0,0,1,0,1,0,0,0,1,0,0,0,1,0,1,0,1,0,0,1,1,1,1,1,1,0,1,0,0,1,0,1,0,1,1,1,1,1,1,0,0,1,0,0,0,0,0,0,1,1,0,1],
[1,0,1,1,1,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,1,1,1,0,1,1,0,0,0,1,0,0,0,1,1,0,1,0,1,0,0,1,0,0,0,1,1,1,1,1,0,0,0,1,0,0,0,1,0,0,1,0,1,1,1,0,1,0,0,1,0,1,0,0,0,1,1,1,0,1,0,1,0,1,0,0,0,1,0],
[1,0,0,0,0,1,1,0,0,0,0,1,1,1,0,0,0,1,1,0,1,1,0,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,1,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,0,1,1,1,1,1,1,0,1,1,1,1,1,0,0,1,0,0,1,1,1,0,1,1,1,0,1,0,0,0,1,0,1,0,1,1,0,1,1,1,1,1,1,0,0,0],
[1,0,1,0,0,0,1,1,1,0,1,0,1,1,1,0,1,1,0,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1,1,0,1,1,1,0,1,1,0,0,1,0,1,0,1,0,0,0,1,1,1,1,1,1,0,1,1,0,1,1,1,1,0,1,1,0,0,1,0,1,0,1,0,1,0,0,0,0,0,0,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,1],
[0,0,1,1,1,0,0,1,1,0,0,0,0,1,0,0,0,0,0,1,1,0,0,0,1,0,1,0,1,1,1,0,1,0,1,0,0,0,0,0,1,1,0,1,0,0,0,1,1,1,0,1,1,1,1,0,1,0,0,0,1,0,0,0,1,1,0,0,1,1,0,1,0,1,0,1,1,1,1,0,0,1,1,1,0,0,0,1,1,1,1,1,1,0,0,0,0,1,0,1],
[0,0,1,1,1,0,1,0,1,1,0,1,1,1,1,0,1,0,0,1,0,1,1,0,0,0,0,1,1,0,0,1,1,1,1,1,0,0,0,0,1,0,0,1,1,0,1,1,0,1,0,0,1,1,1,1,1,1,1,0,0,0,1,0,1,1,1,1,0,0,0,1,1,0,1,0,1,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],
[0,1,1,0,1,0,0,0,1,0,1,1,1,1,0,0,1,0,1,0,0,0,1,0,1,1,0,0,1,1,1,1,1,1,0,1,1,0,0,1,1,0,1,0,1,1,1,0,1,1,0,0,1,1,1,0,1,1,1,0,0,0,0,1,1,0,0,1,0,1,1,0,1,1,0,0,1,1,0,1,0,0,0,1,1,1,0,1,1,0,1,1,0,1,1,1,0,0,0,0],
[1,0,0,0,1,1,1,0,1,1,1,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1,1,1,0,0,1,0,1,1,1,0,1,1,0,1,1,0,0,0,0,1,0,1,1,1,1,0,1,0,1,1,1,1,0,1,1,0,0,1,1,0,0,1,0,0,1,0,0,0,0,0,1,0,0,0,0,1,1,0,1,0,1,0],
[0,1,1,0,1,0,0,1,0,0,1,0,1,1,0,0,0,0,0,0,0,1,0,1,1,1,1,0,1,1,1,1,1,1,1,0,0,0,0,0,1,0,1,1,0,1,1,0,1,0,0,0,0,0,1,0,1,0,0,1,0,0,0,0,1,1,1,1,1,1,0,1,0,0,1,1,1,0,1,1,0,1,1,0,0,0,0,0,1,0,1,1,1,1,0,0,1,1,0,1],
[1,1,1,0,0,1,0,1,1,1,0,1,0,0,1,1,1,1,0,0,0,0,0,1,1,0,0,0,0,1,0,0,1,1,1,1,0,0,0,0,1,0,1,1,0,1,1,0,0,1,0,0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,0,0,0,1,0,1,0,0,0,0,1,1,0,0,0,1,1,1,0,1,0,0,1,0,1,1,0,0,0,1,0],
[1,0,0,1,1,1,0,0,1,1,0,0,1,0,1,0,1,1,0,1,1,1,0,1,0,1,0,1,1,0,0,0,1,1,1,0,1,0,0,0,1,1,0,1,1,0,0,1,0,1,1,1,0,0,0,0,1,1,1,0,0,1,0,1,0,0,0,1,0,1,1,1,0,0,1,1,1,1,1,1,0,1,0,0,1,0,1,1,1,0,0,1,0,0,1,0,0,1,0,1],
[0,1,0,0,0,0,0,0,0,0,1,1,0,1,0,1,1,1,0,0,1,1,1,0,1,0,1,0,1,1,0,0,0,0,0,1,1,0,1,1,0,1,0,1,0,0,0,1,1,0,0,1,0,1,1,0,0,0,0,1,1,1,0,0,1,0,1,0,1,0,1,0,1,1,0,0,0,0,1,0,1,1,0,0,1,0,1,0,0,0,1,1,1,0,0,0,1,0,0,0],
[1,1,1,1,0,1,1,1,1,0,0,1,0,0,0,0,1,0,1,0,1,0,0,1,0,0,1,1,0,0,0,0,0,0,0,1,1,0,1,1,1,1,0,0,0,1,1,1,0,1,1,0,0,1,0,1,0,1,1,0,1,0,0,1,1,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,0,1,0,1,1,0,0,1,0,0,0,1,0,0,0,0,0,1],
[0,0,1,0,0,1,0,0,1,1,1,0,0,1,1,0,1,1,0,0,1,1,1,1,1,1,0,1,0,0,1,1,1,0,0,1,1,1,0,1,0,1,1,0,0,1,1,0,1,0,0,1,1,1,1,1,0,1,0,1,0,1,0,1,1,0,0,1,0,1,1,0,0,1,1,0,1,1,0,0,0,0,0,0,1,1,1,1,0,1,0,0,0,0,0,0,0,0,0,0],
[0,0,0,1,1,0,1,1,0,0,1,1,1,0,1,0,0,0,1,1,1,0,0,0,0,1,0,1,0,1,0,1,0,0,0,0,0,1,0,1,1,0,0,0,0,0,1,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,1,1,1,1,0,0,0,1,1,0,1,1,0,0,0,0,1,1,0,1,0,0,1,0,1,1,1,1,0,1,0,0,1,1,1,0,1,0],
[0,0,1,0,0,0,0,0,1,1,1,1,0,1,0,1,1,1,0,1,1,1,1,1,0,0,1,0,0,1,1,1,0,0,1,0,0,1,0,1,0,0,0,1,1,1,1,1,0,0,0,1,1,1,0,1,1,1,0,0,0,0,1,0,1,1,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,1,0,0,0,0],
[0,0,1,1,0,1,1,1,1,1,0,0,0,1,1,1,0,1,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,1,0,1,1,1,1,0,1,1,0,0,1,0,1,0,0,1,0,1,0,0,0,1,0,0,0,1,1,0,1,1,0,1,1,0,0,1,0,1,0,1,1,0,1,1,1,1,1,1,1,1,0,0,0,0,0,0,1,1,1,1,1,0,0,0],
[0,0,0,1,1,1,0,1,0,1,0,0,1,0,0,0,1,0,1,1,1,0,1,1,1,0,0,0,0,0,0,0,1,1,0,1,1,1,0,1,0,0,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,0,0,1,0,1,0,1,0,1,1,0,1,0,1,1,1,0,0,0,1,1,1,1,1,1,0,0,1,0,1,0,0,0,1,1,1,0,1,1,0,0,0],
[0,1,0,1,0,1,1,1,1,1,1,1,0,1,0,0,1,1,0,1,1,0,0,1,1,0,0,0,1,0,0,0,1,1,1,1,0,0,0,1,0,0,1,1,1,1,1,0,1,0,0,1,1,0,0,0,1,1,1,0,1,0,1,0,0,0,1,0,1,1,0,0,0,1,0,0,0,0,0,0,1,0,0,1,1,0,1,1,1,1,0,0,1,0,0,0,0,0,1,1],
[0,1,1,0,1,1,0,1,0,1,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,1,1,1,0,0,0,0,0,1,1,0,1,0,1,1,0,0,1,1,1,0,0,0,0,0,0,1,0,0,0,0,1,1,1,1,0,0,0,1,0,1,1,1,0,1,0,1,1,0,1,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,1,0,0,0,0,0,1,1],
[1,0,0,0,1,0,1,1,1,0,1,0,1,1,0,0,0,1,1,0,1,1,1,1,0,0,0,0,1,0,0,0,1,0,1,1,1,0,0,1,0,1,0,0,0,0,0,1,0,1,0,0,0,0,1,0,1,0,1,0,1,1,0,0,0,1,0,1,0,0,1,1,1,1,1,0,1,0,1,0,0,1,0,0,1,0,0,1,0,0,0,0,1,0,0,0,1,1,1,1],
[0,0,0,0,0,1,1,0,0,0,1,1,1,0,0,0,0,0,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,0,0,0,1,1,0,1,0,1,1,1,1,1,0,0,1,1,0,0,0,1,0,1,0,1,0,1,0,1,1,1,0,0,0,1,1,1,0,1,1,0,1,1,1,1,0,0,1,0,1,0,0,1,0,1,0,0,1,0,1,1,1,1,0,1,1],
[1,0,0,1,0,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,0,1,0,0,1,1,1,0,0,0,0,1,1,1,0,1,1,0,1,0,1,1,0,1,0,0,0,1,0,1,0,0,1,0,0,0,1,0,0,0,0,1,1,1,0,1,0,0,1,0,1,0,1,1,1,1,1,1,0,1,0,0,0,1,1,1,1,0,0,1,0,0,1,1,0,1,0,1],
[1,0,0,1,0,1,0,0,1,0,0,0,1,1,1,0,1,0,0,1,1,0,1,0,0,0,1,0,0,0,1,1,0,1,0,0,0,0,0,0,1,0,0,0,1,0,0,1,0,0,1,1,1,1,0,0,1,1,0,0,0,0,0,1,0,1,1,1,0,0,0,1,0,1,0,0,1,0,1,0,0,0,0,1,0,1,1,1,1,1,0,1,1,0,1,1,1,0,0,0],
[1,1,1,0,0,0,0,1,0,1,0,0,1,0,1,0,0,1,1,1,0,0,1,0,1,1,0,0,0,0,0,0,1,0,0,0,1,0,0,1,0,0,1,1,0,1,0,0,1,1,1,0,0,1,1,0,0,1,0,0,1,0,1,1,1,1,0,0,1,0,0,0,1,1,1,1,1,1,1,1,0,0,1,1,0,1,0,1,1,0,1,0,1,0,1,0,0,0,1,0],
[0,1,0,1,0,1,1,0,1,1,0,1,1,1,0,0,1,0,0,0,1,0,1,0,0,0,0,1,0,0,1,0,1,1,0,0,1,0,1,0,1,0,1,0,1,1,0,1,1,0,1,1,1,1,1,0,0,0,1,0,0,0,0,0,0,0,0,1,1,1,1,0,0,1,1,1,0,0,1,1,1,1,0,1,1,1,1,1,0,0,1,0,1,1,0,1,0,1,1,0]]
|
Dr-Horv/Advent-of-code
|
day18/day18.hs
|
Haskell
|
mit
| 23,798
|
module Chapter5
where
import Chapter4 (rjustify)
-- 5.1.3
binom :: Int -> Int -> Int
binom n k
| n < 0 =
0
| k == 0 =
1
| otherwise =
binom (n - 1) k + binom (n - 1) (k - 1)
binomSum :: Int -> Int
binomSum n =
sum [binom n k | k <- [0..n]]
pascal :: Int -> [[Int]]
pascal x =
[map (uncurry binom) xs | xs <- xss]
where
elemCount =
x + 1
xss =
[take elemCount (drop n elems) | n <- [0, elemCount..(length elems - elemCount)]]
elems =
[(a, b) | a <- [0..x], b <- [0..x]]
printPascal :: Int -> IO()
printPascal x =
mapM_ putStr table
where
pascalTriangle =
pascal x
table =
header ++ ["\n"] ++ divisor ++ ["\n"] ++ content
justification =
1 + (longestDigit pascalTriangle)
divisor =
take (2 + (length pascalTriangle + 1) * justification) (repeat "-")
content =
map row (zip pascalTriangle [0..length pascalTriangle])
row (r, idx) =
rowIndex idx ++ rowContent (rjustify justification) r
rowIndex idx =
(rjustify justification (show idx)) ++ " |"
header =
[" " ++ rjustify justification "|"] ++ map ((rjustify justification) . show) [0..length pascalTriangle - 1]
rowContent rjustified xs =
foldr ((++) . rjustified . showNonZero) "\n" xs
showNonZero y =
if y > 0 then show y else " "
longestDigit :: [[Int]] -> Int
longestDigit =
-- maximum . concat . map (map digits)
maximum . map localLongestDigit
localLongestDigit :: [Int] -> Int
localLongestDigit =
maximum . map digitCount
digitCount :: Integral a => Int -> a
digitCount n =
floor $ logBase 10.0 (fromIntegral n) + 1
(!) :: [a] -> Int -> a
(!) [] _ =
error "empty list"
(!) (x:xs) i
| i == 0 =
x
| otherwise =
xs ! (i - 1)
takewhile :: (a -> Bool) -> [a] -> [a]
takewhile _ [] =
[]
takewhile p (x:xs)
| p x =
x : takewhile p xs
| otherwise =
[]
dropwhile :: (a -> Bool) -> [a] -> [a]
dropwhile _ [] =
[]
dropwhile p ys@(x:xs)
| p x =
dropwhile p xs
| otherwise =
ys
inits :: [a] -> [[a]]
inits [] =
[[]]
inits (x:xs) =
[[]] ++ map (x:) (inits xs)
subs :: [a] -> [[a]]
subs [] =
[[]]
subs (x:xs) =
subs' ++ map (x:) subs'
where
subs' =
subs xs
intersperse :: a -> [a] -> [[a]]
intersperse x [] =
[[x]]
intersperse x (y:ys) =
[x:y:ys] ++ map (y:) (intersperse x ys)
perms :: [a] -> [[a]]
perms [] =
[[]]
perms (x:xs) =
concat . map (intersperse x) $ perms xs
perms' :: [a] -> [[a]]
perms' [] =
[[]]
perms' (x:xs) =
[zs | ys <- perms xs, zs <- intersperse x ys]
-- 5.6.1
-- length segs = sum [1..length xs] + 1
segs :: [a] -> [[a]]
segs [] =
[[]]
segs (x:xs) =
segs xs ++ map (x:) (inits xs)
segs' :: [a] -> [[a]]
segs' xs =
segstr xs [[]]
-- segstr xs []
where
segstr [] acc =
acc
-- [[]] ++ acc
segstr (y:ys) acc =
segstr ys (map (y:) (inits ys) ++ acc)
-- 5.6.2
-- length (choose k xs) == binom (length xs) k
choose :: Int -> [a] -> [[a]]
choose _ [] =
[[]]
choose 0 _ =
[[]]
choose k xs@(y:ys)
| length xs == k =
[xs]
| otherwise =
choose k ys ++ map (y:) (choose (k - 1) ys)
|
futtetennista/IntroductionToFunctionalProgramming
|
itfp/src/Chapter5.hs
|
Haskell
|
mit
| 3,207
|
module Language.Tiny.Analysis.Grammar where
data Program
= Program [Declaration]
deriving (Eq, Show)
data Declaration
= FunctionDeclaration Annotation String [Parameter] Block
| VariableDeclaration Variable
deriving (Eq, Show)
data Variable
= Variable Annotation String
deriving (Eq, Show)
data Parameter
= Parameter Annotation String
deriving (Eq, Show)
data Annotation
= IntAnnotation
| CharAnnotation
| ArrayAnnotation Annotation Expression
deriving (Eq, Ord, Show)
data Block
= Block [Variable] [Statement]
deriving (Eq, Show)
data Statement
= Conditional Expression Statement
| Alternative Expression Statement Statement
| Loop Expression Statement
| Statements Block
| Assignment Lefthand Expression
| ArrayAssignment Lefthand Expression
| ReturnStatement Expression
| VoidCall String [Expression]
| Output Expression
| Input Lefthand
| Nop
deriving (Eq, Show)
data Lefthand
= ScalarAccess String
| ArrayAccess Lefthand Expression
deriving (Eq, Ord, Show)
data Expression
= Lefthand Lefthand
| Add Expression Expression
| Subtract Expression Expression
| Multiply Expression Expression
| Divide Expression Expression
| Equality Expression Expression
| Inequality Expression Expression
| GreaterThan Expression Expression
| LessThan Expression Expression
| Negate Expression
| Not Expression
| IntValue Int
| Call String [Expression]
| CharValue Char
| ArrayLength Lefthand
deriving (Eq, Ord, Show)
|
dmeysman/tiny-compiler
|
src/Language/Tiny/Analysis/Grammar.hs
|
Haskell
|
mit
| 1,505
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-tagrequest.html
module Stratosphere.ResourceProperties.EC2EC2FleetTagRequest where
import Stratosphere.ResourceImports
-- | Full data type definition for EC2EC2FleetTagRequest. See
-- 'ec2EC2FleetTagRequest' for a more convenient constructor.
data EC2EC2FleetTagRequest =
EC2EC2FleetTagRequest
{ _eC2EC2FleetTagRequestKey :: Maybe (Val Text)
, _eC2EC2FleetTagRequestValue :: Maybe (Val Text)
} deriving (Show, Eq)
instance ToJSON EC2EC2FleetTagRequest where
toJSON EC2EC2FleetTagRequest{..} =
object $
catMaybes
[ fmap (("Key",) . toJSON) _eC2EC2FleetTagRequestKey
, fmap (("Value",) . toJSON) _eC2EC2FleetTagRequestValue
]
-- | Constructor for 'EC2EC2FleetTagRequest' containing required fields as
-- arguments.
ec2EC2FleetTagRequest
:: EC2EC2FleetTagRequest
ec2EC2FleetTagRequest =
EC2EC2FleetTagRequest
{ _eC2EC2FleetTagRequestKey = Nothing
, _eC2EC2FleetTagRequestValue = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-tagrequest.html#cfn-ec2-ec2fleet-tagrequest-key
ececftrKey :: Lens' EC2EC2FleetTagRequest (Maybe (Val Text))
ececftrKey = lens _eC2EC2FleetTagRequestKey (\s a -> s { _eC2EC2FleetTagRequestKey = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-tagrequest.html#cfn-ec2-ec2fleet-tagrequest-value
ececftrValue :: Lens' EC2EC2FleetTagRequest (Maybe (Val Text))
ececftrValue = lens _eC2EC2FleetTagRequestValue (\s a -> s { _eC2EC2FleetTagRequestValue = a })
|
frontrowed/stratosphere
|
library-gen/Stratosphere/ResourceProperties/EC2EC2FleetTagRequest.hs
|
Haskell
|
mit
| 1,756
|
{-# LANGUAGE OverloadedStrings #-}
{-
Custom prettyprinter for JMacro AST
- uses the jmacro prettyprinter for most of the work
- fixme: need a better way to make a customized prettyprinter, without duplicating 5 cases
-}
module Gen2.Printer where
import Data.Char (isAlpha, isDigit)
import qualified Data.Map as M
import qualified Data.Text.Lazy as TL
import qualified Data.Text as T
import Prelude
import Text.PrettyPrint.Leijen.Text (Doc, align, char, comma,
fillSep, hcat, nest, parens,
punctuate, text, vcat, (<+>))
import qualified Text.PrettyPrint.Leijen.Text as PP
import Compiler.JMacro (Ident, JExpr(..), JStat(..), JOp(..),
JVal(..), jsToDocR, RenderJs(..), defaultRenderJs)
pretty :: JStat -> Doc
pretty = jsToDocR ghcjsRenderJs
ghcjsRenderJs :: RenderJs
ghcjsRenderJs = defaultRenderJs { renderJsV = ghcjsRenderJsV
, renderJsS = ghcjsRenderJsS
}
-- attempt to resugar some of the common constructs
ghcjsRenderJsS :: RenderJs -> JStat -> Doc
ghcjsRenderJsS r (BlockStat xs) = prettyBlock r (flattenBlocks xs)
ghcjsRenderJsS r s = renderJsS defaultRenderJs r s
-- don't quote keys in our object literals, so closure compiler works
ghcjsRenderJsV :: RenderJs -> JVal -> Doc
ghcjsRenderJsV r (JHash m)
| M.null m = text "{}"
| otherwise = braceNest . fillSep . punctuate comma .
map (\(x,y) -> quoteIfRequired x <> PP.colon <+> jsToDocR r y) $ M.toList m
where
quoteIfRequired x
| isUnquotedKey x = text (TL.fromStrict x)
| otherwise = PP.squotes (text (TL.fromStrict x))
isUnquotedKey x | T.null x = False
| T.all isDigit x = True
| otherwise = validFirstIdent (T.head x) && T.all validOtherIdent (T.tail x)
-- fixme, this will quote some idents that don't really need to be quoted
validFirstIdent c = c == '_' || c == '$' || isAlpha c
validOtherIdent c = isAlpha c || isDigit c
ghcjsRenderJsV r v = renderJsV defaultRenderJs r v
prettyBlock :: RenderJs -> [JStat] -> Doc
prettyBlock r xs = vcat $ map addSemi (prettyBlock' r xs)
-- recognize common patterns in a block and convert them to more idiomatic/concise javascript
prettyBlock' :: RenderJs -> [JStat] -> [Doc]
-- resugar for loops with/without var declaration
prettyBlock' r ( (DeclStat i)
: (AssignStat (ValExpr (JVar i')) v0)
: (WhileStat False p (BlockStat bs))
: xs
)
| i == i' && not (null flat) && isForUpdStat (last flat)
= mkFor r True i v0 p (last flat) (init flat) : prettyBlock' r xs
where
flat = flattenBlocks bs
prettyBlock' r ( (AssignStat (ValExpr (JVar i)) v0)
: (WhileStat False p (BlockStat bs))
: xs
)
| not (null flat) && isForUpdStat (last flat)
= mkFor r False i v0 p (last flat) (init flat) : prettyBlock' r xs
where
flat = flattenBlocks bs
-- global function (does not preserve semantics but works for GHCJS)
prettyBlock' r ( (DeclStat i)
: (AssignStat (ValExpr (JVar i')) (ValExpr (JFunc is b)))
: xs
)
| i == i' = (text "function" <+> jsToDocR r i
<> parens (fillSep . punctuate comma . map (jsToDocR r) $ is)
$$ braceNest' (jsToDocR r b)
) : prettyBlock' r xs
-- declare/assign
prettyBlock' r ( (DeclStat i)
: (AssignStat (ValExpr (JVar i')) v)
: xs
)
| i == i' = (text "var" <+> jsToDocR r i <+> char '=' <+> jsToDocR r v) : prettyBlock' r xs
-- modify/assign operators (fixme this should be more general, but beware of side effects like PPostExpr)
prettyBlock' r ( (AssignStat (ValExpr (JVar i)) (InfixExpr AddOp (ValExpr (JVar i')) (ValExpr (JInt 1))))
: xs
)
| i == i' = ("++" <> jsToDocR r i) : prettyBlock' r xs
prettyBlock' r ( (AssignStat (ValExpr (JVar i)) (InfixExpr SubOp (ValExpr (JVar i')) (ValExpr (JInt 1))))
: xs
)
| i == i' = ("--" <> jsToDocR r i) : prettyBlock' r xs
prettyBlock' r ( (AssignStat (ValExpr (JVar i)) (InfixExpr AddOp (ValExpr (JVar i')) e))
: xs
)
| i == i' = (jsToDocR r i <+> text "+=" <+> jsToDocR r e) : prettyBlock' r xs
prettyBlock' r ( (AssignStat (ValExpr (JVar i)) (InfixExpr SubOp (ValExpr (JVar i')) e))
: xs
)
| i == i' = (jsToDocR r i <+> text "-=" <+> jsToDocR r e) : prettyBlock' r xs
prettyBlock' r (x:xs) = jsToDocR r x : prettyBlock' r xs
prettyBlock' _ [] = []
-- build the for block
mkFor :: RenderJs -> Bool -> Ident -> JExpr -> JExpr -> JStat -> [JStat] -> Doc
mkFor r decl i v0 p s1 sb = text "for" <> forCond <+> braceNest'' (jsToDocR r $ BlockStat sb)
where
c0 | decl = text "var" <+> jsToDocR r i <+> char '=' <+> jsToDocR r v0
| otherwise = jsToDocR r i <+> char '=' <+> jsToDocR r v0
forCond = parens $ hcat $ interSemi
[ c0
, jsToDocR r p
, parens (jsToDocR r s1)
]
-- check if a statement is suitable to be converted to something in the for(;;x) position
isForUpdStat :: JStat -> Bool
isForUpdStat UOpStat {} = True
isForUpdStat AssignStat {} = True
isForUpdStat ApplStat {} = True
isForUpdStat _ = False
interSemi :: [Doc] -> [Doc]
interSemi [] = [PP.empty]
interSemi [s] = [s]
interSemi (x:xs) = x <> text ";" : interSemi xs
addSemi :: Doc -> Doc
addSemi x = x <> text ";"
-- stuff below is from jmacro
infixl 5 $$, $+$
($+$), ($$), ($$$) :: Doc -> Doc -> Doc
x $+$ y = x PP.<$> y
x $$ y = align (x $+$ y)
x $$$ y = align (nest 2 $ x $+$ y)
flattenBlocks :: [JStat] -> [JStat]
flattenBlocks (BlockStat y:ys) = flattenBlocks y ++ flattenBlocks ys
flattenBlocks (y:ys) = y : flattenBlocks ys
flattenBlocks [] = []
braceNest :: Doc -> Doc
braceNest x = char '{' <+> nest 2 x $$ char '}'
braceNest' :: Doc -> Doc
braceNest' x = nest 2 (char '{' $+$ x) $$ char '}'
-- somewhat more compact (egyptian style) braces
braceNest'' :: Doc -> Doc
braceNest'' x = nest 2 (char '{' PP.<$> x) PP.<$> char '}'
|
ghcjs/ghcjs
|
src/Gen2/Printer.hs
|
Haskell
|
mit
| 6,578
|
import Data.List
import Data.Function
import Control.Applicative
import Control.Monad
import Control.Arrow
getGrid :: String -> IO [[Float]]
getGrid filename = map (map read . filter ((>0) . length) . filter (',' `notElem`) . groupBy ((==) `on` (== ','))) . lines <$> readFile filename
getMod3 :: Int -> [a] -> [a]
getMod3 res xs = map fst $ filter ((== res) . (`mod` 3) . snd) $ zip xs [0..]
zipCoords :: [[a]] -> [[((Int,Int),a)]]
zipCoords xss = zipWith (\r xs -> zipWith (\c x -> ((r,c),x)) [0..] xs) [0..] xss
mod3Sum :: Int -> Int -> [[Float]] -> Float
mod3Sum rm cm = sum . concat . getMod3 rm . map (getMod3 cm)
mod3Slant s (r,c) = ((r-c+s+1) `mod` 3, (r+c+2) `mod` 3)
-- second coord: (r+c+2) or (s-r+2) or (2-c-s)
mod3SlantSum :: Int -> Int -> Int -> [[Float]] -> Float
mod3SlantSum s rm cm = sum . map snd . filter ((== (rm,cm)) . fst) . map (mod3Slant s *** id) . concat . zipCoords
dumpGrid :: Int -> IO ()
dumpGrid n = do
g <- getGrid ("s" ++ show n ++ ".txt")
putStrLn $ "== " ++ show n ++ " =="
forM_ [0..2] (\rm ->
putStrLn $ intercalate "\t" $ map (\cm -> show $ mod3SlantSum n rm cm g) [0..2])
main = mapM_ dumpGrid [3..25]
|
betaveros/probabilistic-poliwraths
|
mod3.hs
|
Haskell
|
mit
| 1,156
|
module WordNumber where
import Data.List (intersperse, intercalate)
digitToWord :: Int -> String
digitToWord n
| n == 1 = "one"
| n == 2 = "two"
| n == 3 = "three"
| n == 4 = "four"
| n == 5 = "five"
| n == 6 = "six"
| n == 7 = "seven"
| n == 8 = "eight"
| n == 9 = "nine"
digits :: Int -> [Int]
{- digits n = go n
where
leng = length (show n)
divider = (^) 10 (leng -1)
go n = divider -}
-- (mod n 10) - retrieve the last digit
-- (div n 10) - retrieve remaining digits minus the last one
digits n = go n []
where
go n result
| ((div n 10) > 0) = go (div n 10) ((mod n 10) : result)
| otherwise = n : result
wordNumber :: Int -> String
wordNumber n = concat (intersperse "-" (map digitToWord (digits n)))
|
Numberartificial/workflow
|
haskell-first-principles/haskell-from-first-principles-master/08/08.06.05-numbers-into-words.hs
|
Haskell
|
mit
| 781
|
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}
module Language.C.Obfuscate.CPS
where
import Data.Char
import Data.List (nubBy)
import Data.Maybe
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Language.C.Syntax.AST as AST
import qualified Language.C.Data.Node as N
import Language.C.Syntax.Constants
import Language.C.Data.Ident
import Language.C.Obfuscate.Var
import Language.C.Obfuscate.ASTUtils
import Language.C.Obfuscate.CFG
import Language.C.Obfuscate.SSA
-- import for testing
import Language.C (parseCFile, parseCFilePre)
import Language.C.System.GCC (newGCC)
import Language.C.Pretty (pretty)
import Text.PrettyPrint.HughesPJ (render, text, (<+>), hsep)
import System.IO.Unsafe (unsafePerformIO)
-- TODO LIST:
testCPS = do
{ let opts = []
; ast <- errorOnLeftM "Parse Error" $ parseCFile (newGCC "gcc") Nothing opts "test/sort.c" -- -} "test/fibiter.c"
; case ast of
{ AST.CTranslUnit (AST.CFDefExt fundef:_) nodeInfo ->
case runCFG fundef of
{ CFGOk (_, state) -> do
{ -- putStrLn $ show $ buildDTree (cfg state)
; -- putStrLn $ show $ buildDF (cfg state)
; let (SSA scopedDecls labelledBlocks sdom _ _) = buildSSA (cfg state) (formalArgs state)
-- ; putStrLn $ show $ visitors
-- ; putStrLn $ show $ exits
; let cps = ssa2cps fundef (buildSSA (cfg state) (formalArgs state))
; putStrLn $ prettyCPS $ cps
; -- putStrLn $ render $ pretty (cps_ctxt cps)
; -- mapM_ (\d -> putStrLn $ render $ pretty d) (cps_funcsigs cps)
; -- mapM_ (\f -> putStrLn $ render $ pretty f) ((cps_funcs cps) ++ [cps_main cps])
}
; CFGError s -> error s
}
; _ -> error "not fundec"
}
}
prettyCPS :: CPS -> String
prettyCPS cps =
let declExts = map (\d -> AST.CDeclExt d) ([(cps_ctxt cps)] ++ (cps_typedefs cps) ++ (cps_funcsigs cps))
funDeclExts = map (\f -> AST.CFDefExt f) ((cps_funcs cps) ++ [cps_main cps])
in render $ pretty (AST.CTranslUnit (declExts ++ funDeclExts) N.undefNode)
-- ^ a CPS function declaration AST
data CPS = CPS { cps_decls :: [AST.CCompoundBlockItem N.NodeInfo] -- ^ main function decls
, cps_stmts :: [AST.CCompoundBlockItem N.NodeInfo] -- ^ main function stmts
, cps_funcsigs :: [AST.CDeclaration N.NodeInfo] -- ^ the signatures decls of the auxillary functions
, cps_funcs :: [AST.CFunctionDef N.NodeInfo] -- ^ the auxillary functions
, cps_ctxt :: AST.CDeclaration N.NodeInfo -- ^ the context for the closure
, cps_typedefs :: [AST.CDeclaration N.NodeInfo] -- ^ type defs
, cps_main :: AST.CFunctionDef N.NodeInfo -- ^ the main function
} deriving Show
-- global (parameter) name prefices
bindName = "bind"
bindPushName = "bind_push"
bindPeekMName = "bind_peek_m"
bindPeekFName = "bind_peek_f"
bindPopName = "bind_pop"
lambdaBindName = "lambda_bind"
ifcCondName = "ifcCond"
ifcTrName = "ifcTr"
ifcFlName = "ifcFl"
ifcName = "ifc"
ifcPushName = "ifc_push"
ifcPeekCName = "ifc_peek_c"
ifcPeekTrName = "ifc_peek_tr"
ifcPeekFlName = "ifc_peek_fl"
ifcPopName = "ifc_pop"
lambdaIfcName = "lambda_ifc"
loopCondName = "loopcCond"
loopVisitName = "loopcVisit"
loopExitName = "loopcExit"
loopName = "loopc"
loopPushName = "loopc_push"
loopPeekCName = "loopc_peek_c"
loopPeekVName = "loopc_peek_v"
loopPeekEName = "loopc_peek_e"
loopPopName = "loopc_pop"
lambdaLoopName = "lambda_loopc"
kPeekName = "k_peek"
kPopName = "k_pop"
kPushName = "k_push"
retName = "ret"
idName = "id"
ctxt_arr_bool = "ctxt_arr_bool"
ctxt_arr_void = "ctxt_arr_void"
ctxtParamName = "ctxtParam"
kParamName = "kParam"
mParamName = "mParam"
fParamName = "fParam"
condParamName = "condParam"
visitorParamName = "visitorParam"
exitParamName = "exitParam"
trueParamName = "trueParam"
falseParamName = "falseParam"
kStackTop = "k_stack_top"
loopStackTop = "loop_stack_top"
ifcStackTop = "ifc_stack_top"
bindStackTop = "bind_stack_top"
kStackName = "k_stack"
loopStackCName = "loopc_stack_c"
loopStackVName = "loopc_stack_v"
loopStackEName = "loopc_stack_e"
ifcStackCName = "ifc_stack_c"
ifcStackTrName = "ifc_stack_tr"
ifcStackFlName = "ifc_stack_fl"
bindStackFName = "bind_stack_f"
bindStackMName = "bind_stack_m"
{-
class CPSize ssa cps where
cps_trans :: ssa -> cps
instance CPSize a b => CPSize [a] [b] where
cps_trans as = map cps_trans as
instance CPSize (Ident, LabeledBlock) (AST.CFunctionDef N.NodeInfo) where
cps_trans (label, lb) = undefined
{-
translation d => D
t => T x => X
----------------------
t x => T X
-}
instance CPSize (AST.CDeclaration N.NodeInfo) (AST.CDeclaration N.NodeInfo) where
cps_trans decl = case decl of
{ AST.CDecl tyspec tripls nodeInfo ->
let tyspec' = cps_trans tyspec
tripls' = map (\(mb_decltr, mb_init, mb_size) ->
let mb_decltr' = case mb_decltr of
{ Nothing -> Nothing
; Just decltr -> Just decltr -- todo
}
mb_init' = case mb_init of
{ Nothing -> Nothing
; Just init -> Just init -- todo
}
mb_size' = case mb_size of
{ Nothing -> Nothing
; Just size -> Just size -- todo
}
in (mb_decltr', mb_init', mb_size')
) tripls
in AST.CDecl tyspec' tripls' nodeInfo
-- ; AST.CStaticAssert e lit nodeInfo -> undefined
}
-}
{-
translation t => T
-----------
int => int
-----------
bool => bool
t => t
-------------
t* => T*
t => T
------------
t[] => T*
-------------
void => void
-}
{-
data CDeclarationSpecifier a
= CStorageSpec (CStorageSpecifier a) -- ^ storage-class specifier or typedef
| CTypeSpec (CTypeSpecifier a) -- ^ type name
| CTypeQual (CTypeQualifier a) -- ^ type qualifier
| CFunSpec (CFunctionSpecifier a) -- ^ function specifier
| CAlignSpec (CAlignmentSpecifier a) -- ^ alignment specifier
deriving (Show, Data,Typeable {-! ,CNode ,Functor, Annotated !-})
-}
{-
--------- (Var)
x => X
-}
-- fn, K, \bar{\Delta} |- \bar{b} => \bar{P}
--translating the labeled blocks to function decls
{-
fn, K, \bar{\Delta}, \bar{b} |- b_i => P_i
---------------------------------------------
fn, K, \bar{\Delta} |- \bar{b} => \bar{P}
-}
type ContextName = String
type Visitors = M.Map Ident Ident -- ^ last label of the visitor -> label of the loop
type Exits = M.Map Ident Ident -- ^ label of the exit -> label of the loop
-- CL_cps
cps_trans_lb :: Bool -> -- ^ is return void
S.Set Ident -> -- ^ local vars
S.Set Ident -> -- ^ formal args
ContextName ->
Ident -> -- ^ top level function name
--
Ident -> -- ^ label for the current block
M.Map Ident LabeledBlock -> -- ^ KEnv
SSA -> -- ^ functions as the cfg
([AST.CFunctionDef N.NodeInfo], AST.CExpression N.NodeInfo)
cps_trans_lb isReturnVoid localVars fargs ctxtName fname l_i kenv cfg =
case adjacent cfg l_i of
{ [ l_j ] ->
{-
-- in target langauge
CL_cps l_i kenv cfg
| \exists l_j: (l_i,l_j) \in cfg /\
\not (\exists l_k : l_j \= l_k /\ (l_i, l_k) \in cfg)
= (D::\overline{D}, bind(f_i,E))
where (\overline{D}, E) = CL_cps l_j kenv cfg
(\overline{phi}, s) = kenv l_i
k is a fresh variable
S = CS_cps s kenv l_i k
D = (void => void) => void f_i = (void => void k) => { S }
-- in c
CL_cps l_i kenv cfg
| \exists l_j: (l_i,l_j) \in cfg /\
\not (\exists l_k : l_j \= l_k /\ (l_i, l_k) \in cfg)
= (D::Bind_i::\overline{D}, bind_i)
where (\overline{D}, E) = CL_cps l_j kenv cfg
(\overline{phi}, s) = kenv l_i
k is a fresh variable
S = CS_cps s kenv l_i k
D = void f_i (ctxt* c) { S }
Bind_i = void bind_i (ctxt* c) { bind_push(&f_i, &E, c); lambda_bind(c); }
-}
let f_iname = fname `app` l_i
tyVoid = [AST.CTypeSpec (AST.CVoidType N.undefNode)]
tyCtxt = [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)]
paramCtxt = (iid ctxtParamName) .::*. tyCtxt -- ctxt* ctxt
k = iid kParamName
lb = fromJust (M.lookup l_i kenv)
stmts' = cps_trans_stmts isReturnVoid localVars fargs ctxtName fname k kenv l_i (lb_stmts lb)
f_iD = fun tyVoid f_iname [paramCtxt] stmts'
(ds,e) = cps_trans_lb isReturnVoid localVars fargs ctxtName fname l_j kenv cfg
-- NOTE: each bind, loop and ifc, ret operators need to be "qualified" by the function name
bind = fname `app` iid bindName
bindpush = fname `app` iid bindPushName
lambdabind = fname `app` iid lambdaBindName
bind_i = bind `app` l_i
bindPush = AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar bindpush) [ (adr $ cvar f_iname), (adr e),(cvar $ iid ctxtParamName)] N.undefNode)) N.undefNode) -- bind_push(&f_i, &e, ctxt)
lambdaBindApp = AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar lambdabind) [(cvar $ iid ctxtParamName)] N.undefNode)) N.undefNode) -- lambdaBind(ctxt)
bindStmts = [ bindPush, lambdaBindApp]
bind_iD = fun tyVoid bind_i [paramCtxt] bindStmts
in (f_iD:bind_iD:ds, cvar bind_i)
; [ l_j, l_k ] | pathExists cfg l_j l_i && pathExists cfg l_k l_i -> error ("syntactic non-terminating loop" ++ (show (M.lookup l_i kenv)))
; [ l_j, l_k ] | pathExists cfg l_j l_i ->
{-
-- in target langauge
CL_cps l_i kenv cfg
| \exists l_j, l_k: l_j \= l_k /\ (l_i,l_j) \in cfg /\ (l_i, l_k) \in cfg
/\ \exists l' : (l_j, l', l_i) \in cfg
/\ \not (\exists l'' : (l_k, l'', l_i) \in cfg)
= (\overline{D_j} ++ \overline{D_k}, loop( () => { return E}, E_j,E_k ))
where (\overline{\phi}, if e { goto l_j; } else { goto l_k; }) = kenv(l_i)
(\overline{D_j}, E_j) = CL_cps l_j kenv (cfg - last(l_j, \overline{l'}, l_i))
(\overline{D_k}, E_k) = CL_cps l_k kenv cfg
E = CE_cps e
-- in c
CL_cps l_i kenv cfg
| \exists l_j, l_k: l_j \= l_k /\ (l_i,l_j) \in cfg /\ (l_i, l_k) \in cfg
/\ \exists l' : (l_j, l', l_i) \in cfg
/\ \not (\exists l'' : (l_k, l'', l_i) \in cfg)
= (\overline{D_j} ++ \overline{D_k}, loop( () => { return E}, E_j,E_k ))
where (\overline{\phi}, if e { goto l_j; } else { goto l_k; }) = kenv(l_i)
(\overline{D_j}, E_j) = CL_cps l_j kenv (cfg - last(l_j, \overline{l'}, l_i))
(\overline{D_k}, E_k) = CL_cps l_k kenv cfg
E = CE_cps e
LoopCond_i = int loopCond_i (ctxt* c) { return E;}
LoopVisit_i = void loopExit_i (ctxt* c) { (CF_cps l_i l_j); return E_j(ctxt); }
LoopExit_i = void loopExit_i (ctxt* c) { (CF_cps l_i l_k); return E_k(ctxt); }
Loop_i = void loop_i (ctxt* c) { loop_push(&loopCind_i, &loopVisit_i, &Loop_Exit_i, c); lambda_loop(c); }
-}
case M.lookup l_i kenv of
{ Just n -> case lb_stmts n of
{ [ AST.CBlockStmt
(AST.CIf exp trueStmt@(AST.CGoto l_j _) (Just falseStmt@(AST.CGoto l_k _)) nodeInfo) ] ->
let (d_j,e_j) = cps_trans_lb isReturnVoid localVars fargs ctxtName fname l_j kenv (removeEdges cfg l_j l_i) -- we need to remove all edges
(d_k,e_k) = cps_trans_lb isReturnVoid localVars fargs ctxtName fname l_k kenv cfg
exp' = cps_trans_exp localVars fargs ctxtName exp
tyVoid = [AST.CTypeSpec (AST.CVoidType N.undefNode)]
tyInt = [AST.CTypeSpec (AST.CIntType N.undefNode)]
tyCtxt = [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)]
paramCtxt = (iid ctxtParamName) .::*. tyCtxt -- ctxt* ctxt
loopCond = fname `app` iid loopCondName
loopCond_i = loopCond `app` l_i
loopCondStmts = [AST.CBlockStmt (AST.CReturn (Just exp') N.undefNode)]
loopCond_iD = fun tyInt loopCond_i [paramCtxt] loopCondStmts
loopVisit = fname `app` iid loopVisitName
loopVisit_i = loopVisit `app` l_i
loopVisitPhis = case M.lookup l_j kenv of
{ Nothing -> []
; Just n -> cps_trans_phis ctxtName l_i l_j (lb_phis n)
}
loopVisitStmts = loopVisitPhis ++ [AST.CBlockStmt (AST.CExpr (Just (funCall e_j [ cvar $ iid ctxtParamName])) N.undefNode)]
loopVisit_iD = fun tyVoid loopVisit_i [paramCtxt] loopVisitStmts
loopExit = fname `app` iid loopExitName
loopExit_i = loopExit `app` l_i
loopExitPhis = case M.lookup l_k kenv of
{ Nothing -> []
; Just n -> cps_trans_phis ctxtName l_i l_k (lb_phis n)
}
loopExitStmts = loopExitPhis ++ [AST.CBlockStmt (AST.CExpr (Just (funCall e_k [ cvar $ iid ctxtParamName])) N.undefNode)]
loopExit_iD = fun tyVoid loopExit_i [paramCtxt] loopExitStmts
loop = fname `app` iid loopName
loop_i = loop `app` l_i
loopPush = fname `app` iid loopPushName
lambdaloop = fname `app` iid lambdaLoopName
loopStmts = [ AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar loopPush) [ (adr (cvar loopCond_i)), (adr (cvar loopVisit_i)), (adr (cvar loopExit_i)), (cvar $ iid ctxtParamName) ] N.undefNode)) N.undefNode)
, (AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar lambdaloop) [ (cvar $ iid ctxtParamName) ] N.undefNode)) N.undefNode))
]
loop_iD = fun tyVoid loop_i [paramCtxt] loopStmts
in ([loopCond_iD, loopVisit_iD, loopExit_iD, loop_iD] ++ d_j ++ d_k, cvar loop_i)
; _ -> error "not possible"
}
; _ -> error "not possible"
}
; [ l_j, l_k ] | pathExists cfg l_k l_i -> -- same as the above case, just swapping k and j
case M.lookup l_i kenv of
{ Just n -> case lb_stmts n of
{ [ AST.CBlockStmt
(AST.CIf exp trueStmt@(AST.CGoto l_j _) (Just falseStmt@(AST.CGoto l_k _)) nodeInfo) ] ->
let (d_j,e_j) = cps_trans_lb isReturnVoid localVars fargs ctxtName fname l_j kenv cfg
(d_k,e_k) = cps_trans_lb isReturnVoid localVars fargs ctxtName fname l_k kenv (removeEdges cfg l_k l_i)
exp' = cps_trans_exp localVars fargs ctxtName exp
tyVoid = [AST.CTypeSpec (AST.CVoidType N.undefNode)]
tyInt = [AST.CTypeSpec (AST.CIntType N.undefNode)]
tyCtxt = [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)]
paramCtxt = (iid ctxtParamName) .::*. tyCtxt -- ctxt* ctxt
loopCond = fname `app` iid loopCondName
loopCond_i = loopCond `app` l_i
loopCondStmts = [AST.CBlockStmt (AST.CReturn (Just exp') N.undefNode)]
loopCond_iD = fun tyInt loopCond_i [paramCtxt] loopCondStmts
loopVisit = fname `app` iid loopVisitName
loopVisit_i = loopVisit `app` l_i
loopVisitPhis = case M.lookup l_k kenv of
{ Nothing -> []
; Just n -> cps_trans_phis ctxtName l_i l_k (lb_phis n)
}
loopVisitStmts = loopVisitPhis ++ [AST.CBlockStmt (AST.CExpr (Just (funCall e_k [ cvar $ iid ctxtParamName])) N.undefNode)]
loopVisit_iD = fun tyVoid loopVisit_i [paramCtxt] loopVisitStmts
loopExit = fname `app` iid loopExitName
loopExit_i = loopExit `app` l_i
loopExitPhis = case M.lookup l_j kenv of
{ Nothing -> []
; Just n -> cps_trans_phis ctxtName l_i l_j (lb_phis n)
}
loopExitStmts = loopExitPhis ++ [AST.CBlockStmt (AST.CExpr (Just (funCall e_j [ cvar $ iid ctxtParamName])) N.undefNode)]
loopExit_iD = fun tyVoid loopExit_i [paramCtxt] loopExitStmts
loop = fname `app` iid loopName
loop_i = loop `app` l_i
loopPush = fname `app` iid loopPushName
lambdaloop = fname `app` iid lambdaLoopName
loopStmts = [ AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar loopPush) [ (adr (cvar loopCond_i)), (adr (cvar loopVisit_i)), (adr (cvar loopExit_i)), (cvar $ iid ctxtParamName) ] N.undefNode)) N.undefNode)
, (AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar lambdaloop) [ (cvar $ iid ctxtParamName) ] N.undefNode)) N.undefNode))
]
loop_iD = fun tyVoid loop_i [paramCtxt] loopStmts
in ([loopCond_iD, loopVisit_iD, loopExit_iD, loop_iD] ++ d_j ++ d_k, cvar loop_i)
; _ -> error "not possible"
}
; _ -> error "not possible"
}
; [ l_j, l_k ] | otherwise ->
{-
-- in target langauge
CL_cps l_i kenv cfg
| \exists l_j, l_k: l_j \= l_k /\ (l_i,l_j) \in cfg /\ (l_i, l_k) \in cfg
/\ \not (\exists l' : (l_j, l', l_i) \in cfg \/ (l_k, l', l_i) \in cfg)
= (\overline{D_j} ++ \overline{D_k}, ifc( () => { return E}, E_j,E_k ))
where (\overline{\phi}, if e { goto l_j; } else { goto l_k; }) = kenv(l_i)
(\overline{D_j}, E_j) = CL_cps l_j kenv cfg
(\overline{D_k}, E_k) = CL_cps l_k kenv cfg
E = CE_cps e
-- in c
CL_cps l_i kenv cfg
| \exists l_j, l_k: l_j \= l_k /\ (l_i,l_j) \in cfg /\ (l_i, l_k) \in cfg
/\ \not (\exists l' : (l_j, l', l_i) \in cfg \/ (l_k, l', l_i) \in cfg)
= (Ifc_i::IfTr_i::IfFl_i::\overline{D_j} ++ \overline{D_k}, Ifc_i)
where (\overline{\phi}, if e { goto l_j; } else { goto l_k; }) = kenv(l_i)
(\overline{D_j}, E_j) = CL_cps l_j kenv cfg
(\overline{D_k}, E_k) = CL_cps l_k kenv cfg
E = CE_cps e
IfCond_i = int ifcond_i (ctxt* c) { return E; }
IfTr_i = void iftr_i (ctxt* c) { (CF_cps l_i l_j); return E_j(ctxt); }
IfFl_i = void iffl_i (ctxt* c) { (CF_cps l_i l_k); return E_k(ctxt); }
Ifc_i = void ifc_i (ctxt* c) { ifc_push(&ifcond_i, &iftr_i, &iftf_i,c); lambda_ifc(c); }
-}
case M.lookup l_i kenv of
{ Just n -> case lb_stmts n of
{ [ AST.CBlockStmt
(AST.CIf exp trueStmt@(AST.CGoto l_j _) (Just falseStmt@(AST.CGoto l_k _)) nodeInfo) ] ->
let (d_j,e_j) = cps_trans_lb isReturnVoid localVars fargs ctxtName fname l_j kenv cfg
(d_k,e_k) = cps_trans_lb isReturnVoid localVars fargs ctxtName fname l_k kenv cfg
exp' = cps_trans_exp localVars fargs ctxtName exp
tyVoid = [AST.CTypeSpec (AST.CVoidType N.undefNode)]
tyInt = [AST.CTypeSpec (AST.CIntType N.undefNode)]
tyCtxt = [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)]
paramCtxt = (iid ctxtParamName) .::*. tyCtxt -- ctxt* ctxt
ifcCond = fname `app` iid ifcCondName
ifcCond_i = ifcCond `app` l_i
ifcCondStmts = [AST.CBlockStmt (AST.CReturn (Just exp') N.undefNode)]
ifcCond_iD = fun tyInt ifcCond_i [paramCtxt] ifcCondStmts
ifcTrue = fname `app` iid ifcTrName
ifcTrue_i = ifcTrue `app` l_i
ifcTruePhis = case M.lookup l_j kenv of
{ Nothing -> []
; Just n -> cps_trans_phis ctxtName l_i l_j (lb_phis n)
}
ifcTrueStmts = ifcTruePhis ++ [AST.CBlockStmt (AST.CExpr (Just (funCall e_j [ cvar $ iid ctxtParamName])) N.undefNode)]
ifcTrue_iD = fun tyVoid ifcTrue_i [paramCtxt] ifcTrueStmts
ifcFalse = fname `app` iid ifcFlName
ifcFalse_i = ifcFalse `app` l_i
ifcFalsePhis = case M.lookup l_k kenv of
{ Nothing -> []
; Just n -> cps_trans_phis ctxtName l_i l_k (lb_phis n)
}
ifcFalseStmts = ifcFalsePhis ++ [AST.CBlockStmt (AST.CExpr (Just (funCall e_k [ cvar $ iid ctxtParamName])) N.undefNode)]
ifcFalse_iD = fun tyVoid ifcFalse_i [paramCtxt] ifcFalseStmts
ifc = fname `app` iid ifcName
ifc_i = ifc `app` l_i
ifcPush = fname `app` iid ifcPushName
lambdaifc = fname `app` iid lambdaIfcName
ifcStmts = [ AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar ifcPush) [ (adr (cvar ifcCond_i)), (adr (cvar ifcTrue_i)), (adr (cvar ifcFalse_i)), (cvar $ iid ctxtParamName) ] N.undefNode)) N.undefNode)
, (AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar lambdaifc) [ (cvar $ iid ctxtParamName) ] N.undefNode)) N.undefNode))
]
ifc_iD = fun tyVoid ifc_i [paramCtxt]ifcStmts
in ([ifcCond_iD, ifcTrue_iD, ifcFalse_iD, ifc_iD] ++ d_j ++ d_k, cvar ifc_i)
; _ -> error "not possible"
}
; _ -> error "not possible"
}
; [] ->
{-
-- in target langauge
CL_cps l_i kenv cfg
| \not (\exists l_j : (l_i,l_j) \in cfg)
= ([D], bind( f_i, () => { return ret()})
where (\overline{\phi}, s) = kenv(l_i)
k is fresh
S = CS_cps s kenv l_i k
D = (void => void) => void f_i = (void => void k) = { S }
-- in c
CL_cps l_i kenv cfg
| \not (\exists l_j : (l_i,l_j) \in cfg)
= ([D], bind( f_i, () => { return ret()})
where (\overline{\phi}, s) = kenv(l_i)
k is fresh
S = CS_cps s kenv l_i k
D = void f_i = (ctxt* c) = { S }
Bind_i = void bind_i (ctxt* c) { bind_push(&f_i, &ret, c); lambda_bind(c); }
-}
let f_iname = fname `app` l_i
tyVoid = [AST.CTypeSpec (AST.CVoidType N.undefNode)]
paramCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt
[(Just (AST.CDeclr (Just (iid ctxtParamName)) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode
k = iid kParamName
lb = fromJust (M.lookup l_i kenv)
stmts' = cps_trans_stmts isReturnVoid localVars fargs ctxtName fname k kenv l_i (lb_stmts lb)
f_iD = fun tyVoid f_iname [paramCtxt] stmts'
bind = fname `app` iid bindName -- todo need to add fname prefix?
bindpush = fname `app` iid bindPushName
lambdabind = fname `app` iid lambdaBindName
id = fname `app` iid idName -- id is ret
bind_i = bind `app` l_i
bindPush = AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar bindpush) [ (adr $ cvar f_iname), (adr $ cvar id), (cvar $ iid ctxtParamName)] N.undefNode)) N.undefNode) -- bind_push(&f_i, &e, ctxt)
lambdaBindApp = AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar lambdabind) [(cvar $ iid ctxtParamName)] N.undefNode)) N.undefNode) -- lambdaBind(ctxt)
bindStmts = [ bindPush, lambdaBindApp]
bind_iD = fun tyVoid bind_i [paramCtxt] bindStmts
in (f_iD:bind_iD:[], cvar bind_i)
; unhandled_cases -> error ("unhandle case " ++ (show unhandled_cases) ++ " " ++ (show (M.lookup l_i kenv)))
}
cps_trans_stmts :: Bool -> -- ^ is return type void
S.Set Ident -> -- ^ local vars
S.Set Ident -> -- ^ formal args
ContextName ->
Ident -> -- ^ fname
Ident -> -- ^ K
-- ^ \bar{\Delta} become part of the labelled block flag (loop)
M.Map Ident LabeledBlock -> -- ^ \bar{b} kenv
Ident -> -- ^ label for the current block
[AST.CCompoundBlockItem N.NodeInfo] -> -- ^ stmts
[AST.CCompoundBlockItem N.NodeInfo]
cps_trans_stmts isReturnVoid localVars fargs ctxtName fname k kenv l_i stmts = -- todo: maybe pattern match the CCompound constructor here?
concatMap (\stmt -> cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k kenv l_i stmt) stmts
-- fn, K, \bar{\Delta}, \bar{b} |-_l s => S
cps_trans_stmt :: Bool -> -- ^ is return type void
S.Set Ident -> -- ^ local vars
S.Set Ident -> -- ^ formal args
ContextName ->
Ident -> -- ^ fname
Ident -> -- ^ K
-- ^ \bar{\Delta} become part of the labelled block flag (loop)
M.Map Ident LabeledBlock -> -- ^ \bar{b} kenv
Ident -> -- ^ label for the current block
AST.CCompoundBlockItem N.NodeInfo ->
[AST.CCompoundBlockItem N.NodeInfo]
{-
-- in target language
CS_cps (goto l_i) kenv l_j k = \overline{X = E}; return k();
where (\overline{\phi}, s) = kenv l_i
\overline{(X,E)} = CF_cps \overline{\phi} l_j
-- in C
CS_cps (goto l_i) kenv l_j k = \overline{X = E}; ctxt_arr_void k = kpeek(ctxt); kpop(ctxt); return (*k)(ctxt);
where (\overline{\phi}, s) = kenv l_i
\overline{(X,E)} = CF_cps \overline{\phi} l_j
-}
-- note that our target is C, hence besides k, the function call include argument such as context
cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k kenv l_j (AST.CBlockStmt (AST.CGoto l_i nodeInfo)) = case M.lookup l_i kenv of
{ Just lb ->
let
asgmts = cps_trans_phis ctxtName l_j l_i (lb_phis lb)
peek_ty = [AST.CTypeSpec (AST.CTypeDef (fname `app` (iid ctxt_arr_void)) N.undefNode)]
peek_var = Just (AST.CDeclr (Just (fname `app` k)) [] Nothing [] N.undefNode)
peek_rhs = Just (AST.CInitExpr (AST.CCall (cvar (fname `app` (iid kPeekName))) [cvar $ iid ctxtParamName] N.undefNode) N.undefNode)
peek = AST.CBlockDecl (AST.CDecl peek_ty [(peek_var, peek_rhs, Nothing)] N.undefNode)
pop = AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar (fname `app` (iid kPopName))) [cvar $ iid ctxtParamName] N.undefNode)) N.undefNode)
kApp = AST.CBlockStmt (AST.CExpr (Just (AST.CCall (ind $ cvar (fname `app` k)) [cvar $ iid ctxtParamName] N.undefNode)) N.undefNode) -- (*k)(ctxt)
in asgmts ++ [ peek, pop, kApp ]
; Nothing -> error "cps_trans_stmt failed at a non existent label."
}
cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k kenv l_j (AST.CBlockStmt (AST.CExpr (Just e) nodeInfo)) = -- exp
let e' = cps_trans_exp localVars fargs ctxtName e
in [AST.CBlockStmt (AST.CExpr (Just e') nodeInfo)]
{-
-- target language
CS_cps (return e) kenv l_j k = res = E; return k();
where E = CE_cps e
-- c language
-- CS_cps (return e) kenv l_j k = res = E; ctxt_arr_void k = kpeek(ctxt); kpop(ctxt); return (*k)(ctxt);
CS_cps (return e) kenv l_j k = res = E; ret(ctxt);
-}
cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k kenv l_i (AST.CBlockStmt (AST.CReturn Nothing nodeInfo)) =
let
{-
peek_ty = [AST.CTypeSpec (AST.CTypeDef (fname `app` (iid ctxt_arr_void)) N.undefNode)]
peek_var = Just (AST.CDeclr (Just (fname `app` k)) [] Nothing [] N.undefNode)
peek_rhs = Just (AST.CInitExpr (AST.CCall (cvar (fname `app` (iid kPeekName))) [cvar $ iid ctxtParamName] N.undefNode) N.undefNode)
peek = AST.CBlockDecl (AST.CDecl peek_ty [(peek_var, peek_rhs, Nothing)] N.undefNode)
pop = AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar (fname `app` (iid kPopName))) [cvar $ iid ctxtParamName] N.undefNode)) N.undefNode)
kApp = AST.CBlockStmt (AST.CExpr (Just (AST.CCall (ind $ cvar (fname `app` k)) [cvar $ iid ctxtParamName] N.undefNode)) N.undefNode) -- (*k)(ctxt)
in [ peek, pop, kApp ]
-}
retApp = AST.CBlockStmt (AST.CExpr (Just (funCall (cvar (fname `app` iid retName)) [cvar $ iid ctxtParamName])) N.undefNode)
in [ retApp ]
cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k kenv l_i (AST.CBlockStmt (AST.CReturn (Just e) nodeInfo)) =
let
{-
peek_ty = [AST.CTypeSpec (AST.CTypeDef (fname `app` (iid ctxt_arr_void)) N.undefNode)]
peek_var = Just (AST.CDeclr (Just (fname `app` k)) [] Nothing [] N.undefNode)
peek_rhs = Just (AST.CInitExpr (AST.CCall (cvar (fname `app` (iid kPeekName))) [cvar $ iid ctxtParamName] N.undefNode) N.undefNode)
peek = AST.CBlockDecl (AST.CDecl peek_ty [(peek_var, peek_rhs, Nothing)] N.undefNode)
pop = AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar (fname `app` (iid kPopName))) [cvar $ iid ctxtParamName] N.undefNode)) N.undefNode)
kApp = AST.CBlockStmt (AST.CExpr (Just (AST.CCall (ind $ cvar (fname `app` k)) [cvar $ iid ctxtParamName] N.undefNode)) N.undefNode) -- (*k)(ctxt)
-}
e' = cps_trans_exp localVars fargs ctxtName e
assign_or_e | isReturnVoid = e'
| otherwise = ((cvar (iid ctxtParamName)) .->. (iid "func_result")) .=. e'
stmt = AST.CBlockStmt (AST.CExpr (Just assign_or_e) N.undefNode)
retApp = AST.CBlockStmt (AST.CExpr (Just (funCall (cvar (fname `app` iid retName)) [cvar $ iid ctxtParamName])) N.undefNode)
-- in [ stmt, peek, pop, kApp ]
in[ stmt, retApp]
cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k kenv l_i (AST.CBlockStmt (AST.CCompound ids stmts nodeInfo)) =
-- todo: do we need to do anything with the ids (local labels)?
let stmts' = cps_trans_stmts isReturnVoid localVars fargs ctxtName fname k kenv l_i stmts
in [AST.CBlockStmt (AST.CCompound ids stmts' nodeInfo)]
cps_trans_stmt isReturnVoid localVars fargs ctxtName fname k kenv l_i stmt =
error ("cps_trans_stmt error: unhandled case" ++ (show stmt)) -- (render $ pretty stmt))
cps_trans_phis :: ContextName ->
Ident -> -- ^ source block label (where goto is invoked)
Ident -> -- ^ destination block label (where goto is jumping to)
[( Ident -- ^ var being redefined
, [(Ident, Maybe Ident)])] -> -- ^ incoming block x renamed variables
[AST.CCompoundBlockItem N.NodeInfo]
cps_trans_phis ctxtName src_lb dest_lb ps = map (cps_trans_phi ctxtName src_lb dest_lb) ps
{-
---------------------------------------
l_s, l_d |- \bar{i} => \bar{x = e}
-}
cps_trans_phi :: ContextName ->
Ident -> -- ^ source block label (where goto is invoked)
Ident -> -- ^ destination block label (where goto is jumping to)
(Ident, [(Ident, Maybe Ident)]) ->
AST.CCompoundBlockItem N.NodeInfo
cps_trans_phi ctxtName src_lb dest_lb (var, pairs) =
case lookup src_lb pairs of -- look for the matching label according to the source label
{ Nothing -> error "cps_trans_phi failed: can't find the source label from the incoming block labels."
; Just redefined_lb -> -- lbl in which the var is redefined (it could be the precedence of src_lb)
let lhs = (cvar (iid ctxtParamName)) .->. (var `app` dest_lb)
rhs = (cvar (iid ctxtParamName)) .->. case redefined_lb of
{ Just l -> (var `app` l)
; Nothing -> var
}
in AST.CBlockStmt (AST.CExpr (Just (lhs .=. rhs)) N.undefNode) -- todo check var has been renamed with label
}
-- e => E
{-
--------- (ExpVal)
v => V
e => E, e_i => E_i
-------------------------- (ExpApp)
e(\bar{e}) => E(\bar{E})
-}
-- it seems just to be identical
-- for C target, we need to rename x to ctxt->x
cps_trans_exp :: S.Set Ident -> S.Set Ident -> ContextName -> AST.CExpression N.NodeInfo -> AST.CExpression N.NodeInfo
cps_trans_exp localVars fargs ctxtName (AST.CAssign op lhs rhs nodeInfo) = AST.CAssign op (cps_trans_exp localVars fargs ctxtName lhs) (cps_trans_exp localVars fargs ctxtName rhs) nodeInfo
cps_trans_exp localVars fargs ctxtName (AST.CComma es nodeInfo) = AST.CComma (map (cps_trans_exp localVars fargs ctxtName) es) nodeInfo
cps_trans_exp localVars fargs ctxtName (AST.CCond e1 Nothing e3 nodeInfo) = AST.CCond (cps_trans_exp localVars fargs ctxtName e1) Nothing (cps_trans_exp localVars fargs ctxtName e3) nodeInfo
cps_trans_exp localVars fargs ctxtName (AST.CCond e1 (Just e2) e3 nodeInfo) = AST.CCond (cps_trans_exp localVars fargs ctxtName e1) (Just $ cps_trans_exp localVars fargs ctxtName e2) (cps_trans_exp localVars fargs ctxtName e3) nodeInfo
cps_trans_exp localVars fargs ctxtName (AST.CBinary op e1 e2 nodeInfo) = AST.CBinary op (cps_trans_exp localVars fargs ctxtName e1) (cps_trans_exp localVars fargs ctxtName e2) nodeInfo
cps_trans_exp localVars fargs ctxtName (AST.CCast decl e nodeInfo) = AST.CCast decl (cps_trans_exp localVars fargs ctxtName e) nodeInfo
cps_trans_exp localVars fargs ctxtName (AST.CUnary op e nodeInfo) = AST.CUnary op (cps_trans_exp localVars fargs ctxtName e) nodeInfo
cps_trans_exp localVars fargs ctxtName (AST.CSizeofExpr e nodeInfo) = AST.CSizeofExpr (cps_trans_exp localVars fargs ctxtName e) nodeInfo
cps_trans_exp localVars fargs ctxtName (AST.CSizeofType decl nodeInfo) = AST.CSizeofType decl nodeInfo
cps_trans_exp localVars fargs ctxtName (AST.CAlignofExpr e nodeInfo) = AST.CAlignofExpr (cps_trans_exp localVars fargs ctxtName e) nodeInfo
cps_trans_exp localVars fargs ctxtName (AST.CAlignofType decl nodeInfo) = AST.CAlignofType decl nodeInfo
cps_trans_exp localVars fargs ctxtName (AST.CComplexReal e nodeInfo) = AST.CComplexReal (cps_trans_exp localVars fargs ctxtName e) nodeInfo
cps_trans_exp localVars fargs ctxtName (AST.CComplexImag e nodeInfo) = AST.CComplexImag (cps_trans_exp localVars fargs ctxtName e) nodeInfo
cps_trans_exp localVars fargs ctxtName (AST.CIndex arr idx nodeInfo) = AST.CIndex (cps_trans_exp localVars fargs ctxtName arr) (cps_trans_exp localVars fargs ctxtName idx) nodeInfo
cps_trans_exp localVars fargs ctxtName (AST.CCall f args nodeInfo) = AST.CCall (cps_trans_exp localVars fargs ctxtName f) (map (cps_trans_exp localVars fargs ctxtName) args) nodeInfo
cps_trans_exp localVars fargs ctxtName (AST.CMember e ident deref nodeInfo) = AST.CMember (cps_trans_exp localVars fargs ctxtName e) ident deref nodeInfo
cps_trans_exp localVars fargs ctxtName (AST.CVar id _) =
case unApp id of
{ Nothing -> cvar id
; Just id' | id' `S.member` (localVars `S.union` fargs) ->
-- let io = unsafePerformIO $ print (localVars `S.union` fargs) >> print id'
-- in io `seq`
(cvar (iid ctxtParamName)) .->. id
| otherwise -> cvar id -- global
}
cps_trans_exp localVars fargs ctxtName (AST.CConst c) = AST.CConst c
cps_trans_exp localVars fargs ctxtName (AST.CCompoundLit decl initList nodeInfo) = AST.CCompoundLit decl initList nodeInfo -- todo check this
cps_trans_exp localVars fargs ctxtName (AST.CStatExpr stmt nodeInfo ) = AST.CStatExpr stmt nodeInfo -- todo GNU C compount statement as expr
cps_trans_exp localVars fargs ctxtName (AST.CLabAddrExpr ident nodeInfo ) = AST.CLabAddrExpr ident nodeInfo -- todo
cps_trans_exp localVars fargs ctxtName (AST.CBuiltinExpr builtin ) = AST.CBuiltinExpr builtin -- todo build in expression
{-
top level translation p => P
CP_cps (t' f (t x) { \overline{d}; \overline{b} }) = T' F (T X) { \overline{D''}; T' res; void ign ; ign = E(id) ; return res; }
where T' = t' F = f T = t X = x
\overline{D} = CD_cps \overline{d}
(kenv, l_entry) = B_ssa \overline{b}
(\overline{D'}, E) = CL_cps l_entry kenv G(kenv)
\overline{D''} = \overline{D}; loopDelc; idDecl; seqDelc; condDecl; retDecl; \overline{D'}
-}
-- our target language C differs from the above specification.
-- 1. the top function's type signature is not captured within SSA
-- 2. \Delta is captured as the loop flag in LabaledBlock
-- 3. there is no lambda expression, closure needs to be created as a context
-- aux function that has type (void => void) => void should be in fact
-- (void => void, ctxt*) => void
-- 4. \bar{D} should be the context malloc and initialization
-- 5. all the formal args should be copied to context
ssa2cps :: (AST.CFunctionDef N.NodeInfo) -> SSA -> CPS
ssa2cps fundef ssa@(SSA scopedDecls labelledBlocks sdom local_decl_vars fargs) =
let -- scraping the information from the top level function under obfuscation
funName = case getFunName fundef of { Just s -> s ; Nothing -> "unanmed" }
formalArgDecls :: [AST.CDeclaration N.NodeInfo]
formalArgDecls = getFormalArgs fundef
formalArgIds :: [Ident]
formalArgIds = concatMap (\declaration -> getFormalArgIds declaration) formalArgDecls
(returnTy,ptrArrs) = getFunReturnTy fundef
isReturnVoid = isVoidDeclSpec returnTy
ctxtStructName = funName ++ "Ctxt"
-- the context struct declaration
context = mkContext ctxtStructName labelledBlocks formalArgDecls scopedDecls returnTy ptrArrs local_decl_vars fargs
ctxtName = map toLower ctxtStructName -- alias name is inlower case and will be used in the the rest of the code
-- loop_cps, loop_lambda, id and pop and push
loop_cps = loopCPS ctxtName funName
lambda_loop_cps = lambdaLoopCPS ctxtName funName
loop_push_cps = loopPushCPS ctxtName funName
loop_pop_cps = loopPopCPS ctxtName funName
loop_peek_c_cps = loopPeekCCPS ctxtName funName
loop_peek_v_cps = loopPeekVCPS ctxtName funName
loop_peek_e_cps = loopPeekECPS ctxtName funName
bind_cps = bindCPS ctxtName funName
lambda_bind_cps = lambdaBindCPS ctxtName funName
bind_push_cps = bindPushCPS ctxtName funName
bind_pop_cps = bindPopCPS ctxtName funName
bind_peek_m_cps = bindPeekMCPS ctxtName funName
bind_peek_f_cps = bindPeekFCPS ctxtName funName
ifc_cps = ifcCPS ctxtName funName
lambda_ifc_cps = lambdaIfcCPS ctxtName funName
ifc_push_cps = ifcPushCPS ctxtName funName
ifc_pop_cps = ifcPopCPS ctxtName funName
ifc_peek_c_cps = ifcPeekCCPS ctxtName funName
ifc_peek_tr_cps = ifcPeekTrCPS ctxtName funName
ifc_peek_fl_cps = ifcPeekFlCPS ctxtName funName
id_cps = idCPS ctxtName funName
ret_cps = retCPS ctxtName funName
k_push_cps = kPushCPS ctxtName funName
k_peek_cps = kPeekCPS ctxtName funName
k_pop_cps = kPopCPS ctxtName funName
combinators = [loop_cps, lambda_loop_cps, loop_push_cps, loop_pop_cps, loop_peek_c_cps, loop_peek_v_cps, loop_peek_e_cps,
bind_cps, lambda_bind_cps, bind_push_cps, bind_pop_cps, bind_peek_m_cps, bind_peek_f_cps,
ifc_cps, lambda_ifc_cps, ifc_push_cps,ifc_pop_cps, ifc_peek_c_cps, ifc_peek_tr_cps, ifc_peek_fl_cps,
id_cps, ret_cps, k_push_cps, k_peek_cps,k_pop_cps]
-- all the "nested/helper" function declarations
-- todo: packing all the variable into a record
l_0 = iid (labPref ++ "0" )
(ps,entryExp) = cps_trans_lb isReturnVoid local_decl_vars fargs ctxtName (iid funName) l_0 labelledBlocks ssa
-- remove duplication functioni defintions in ps (caused by multiple blocks merge blocks)
ps' = nubBy (\p1 p2 ->
let n1 = getFunName p1
n2 = getFunName p2
in (isJust n1) && (isJust n2) && (n1 == n2)) ps
-- all function signatures
funcSignatures = map funSig (ps' ++ combinators ++ [fundef]) -- include the source func, in case of recursion
main_decls =
-- 1. malloc the context obj in the main func
-- ctxtTy * ctxt = (ctxtTy *) malloc(sizeof(ctxtTy));
[ AST.CBlockDecl (AST.CDecl
[AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)]
[(Just (AST.CDeclr (Just (iid ctxtParamName)) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),
Just (AST.CInitExpr
(AST.CCast (AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)]
[(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode)
(AST.CCall (AST.CVar (iid "malloc") N.undefNode)
[AST.CSizeofType (AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] [] N.undefNode) N.undefNode] N.undefNode) N.undefNode) N.undefNode),Nothing)] N.undefNode)
]
main_stmts =
-- 2. initialize the counter-part in the context of the formal args
-- forall arg. ctxt->arg_label0 = arg
[ AST.CBlockStmt (AST.CExpr (Just (((cvar (iid ctxtParamName)) .->. (arg `app` (iid $ labPref ++ "0" ))) .=. (AST.CVar arg N.undefNode))) N.undefNode) | arg <- formalArgIds] ++
-- 3. initialize the collection which are the local vars, e.g. a locally declared array
-- int a[3];
-- will be reinitialized as ctxt->a_0 = (int *)malloc(sizeof(int)*3);
[ AST.CBlockStmt (AST.CExpr (Just (((cvar (iid ctxtParamName)) .->. (var `app` (iid $ labPref ++ "0" ))) .=. rhs)) N.undefNode)
| scopedDecl <- scopedDecls
, isJust (containerDeclToInit scopedDecl)
, let (Just (var,rhs)) = containerDeclToInit $ dropStorageQual $ dropConstTyQual scopedDecl ] ++ -- need to drop storage qualifier see test/arrayinitlist.c
-- 4. initialize the context->stack_top = 0;
[ AST.CBlockStmt (AST.CExpr (Just (((cvar (iid ctxtParamName)) .->. (iid stackTop) .=. (AST.CConst (AST.CIntConst (cInteger 0) N.undefNode))))) N.undefNode) | stackTop <- [ kStackTop,loopStackTop, ifcStackTop, bindStackTop ] ] ++
-- 5. calling entry expression
[ AST.CBlockStmt (AST.CExpr (Just (funCall entryExp [ cvar (iid ctxtParamName) ])) N.undefNode)
, if isReturnVoid
then AST.CBlockStmt (AST.CReturn Nothing N.undefNode)
else AST.CBlockStmt (AST.CReturn (Just $ (cvar (iid ctxtParamName)) .->. (iid "func_result")) N.undefNode)
]
main_func = case fundef of
{ AST.CFunDef tySpecfs declarator decls _ nodeInfo ->
AST.CFunDef tySpecfs declarator decls (AST.CCompound [] (main_decls ++ main_stmts) N.undefNode) nodeInfo
}
typedefs = [ ctxt_arr_voidDecl ctxtName funName,
ctxt_arr_boolDecl ctxtName funName]
in CPS main_decls main_stmts funcSignatures (ps' ++ combinators) context typedefs main_func
-- ^ turn a scope declaration into a rhs initalization.
-- ^ refer to local_array.c
containerDeclToInit :: AST.CDeclaration N.NodeInfo -> Maybe (Ident, AST.CExpression N.NodeInfo)
containerDeclToInit (AST.CDecl typespecs tripls nodeInfo0) = case tripls of
{ (Just decl@(AST.CDeclr (Just arrName) [arrDecl] _ _ _), mb_init, _):_ ->
case arrDecl of
{ AST.CArrDeclr _ (AST.CArrSize _ size) _ ->
let
ptrToTy = AST.CDecl typespecs [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode
malloc = AST.CCall (AST.CVar (iid "malloc") N.undefNode)
[AST.CBinary AST.CMulOp (AST.CSizeofType (AST.CDecl typespecs [] N.undefNode) N.undefNode) size N.undefNode] N.undefNode
cast = AST.CCast ptrToTy malloc N.undefNode
in Just (arrName, cast)
{- not needed, the size is recovered during the construction of SSA, see Var.hs splitDecl
; AST.CArrDeclr _ (AST.CNoArrSize _) _ -> -- no size of the array, derive from the init list
case mb_init of
{ Just (AST.CInitList l _) ->
let size = AST.CConst (AST.CIntConst (cInteger (fromIntegral $ length l)) N.undefNode)
ptrToTy = AST.CDecl typespecs [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode
malloc = AST.CCall (AST.CVar (iid "malloc") N.undefNode)
[AST.CBinary AST.CMulOp (AST.CSizeofType (AST.CDecl typespecs [] N.undefNode) N.undefNode) size N.undefNode] N.undefNode
cast = AST.CCast ptrToTy malloc N.undefNode
in Just (arrName, cast)
; Nothing -> Nothing
}
-}
; _ -> Nothing
}
; _ -> Nothing
}
-- ^ push
{-
void loop_push(ctxt_arr_bool cond,
ctxt_arr_void visitor,
ctxt_arr_void exit,
ctxt *ctxt) {
ctxt->loop_c[ctxt->curr_stack_size] = cond;
ctxt->loop_v[ctxt->curr_stack_size] = visitor;
ctxt->loop_e[ctxt->curr_stack_size] = exit;
ctxt->loop_stack_top = ctxt->curr_stack_size + 1;
}
-}
genPushCPS :: ContextName ->
String -> -- function name prefix
String -> -- operator name (loop or ifc)
String -> -- stackTop name
String -> -- fst para name (cond)
String -> -- snd para name (visitor or tr)
String -> -- third para name (exit or fl)
String -> -- stack fst name
String -> -- stack snd name
String -> -- stack third name
AST.CFunctionDef N.NodeInfo
genPushCPS ctxtName fname operatorName stackTop condParaName sndParamName thirdParamName stackCName stackSndName stackThirdName =
let cond = iid condParaName
formalArgCond = AST.CDecl [AST.CTypeSpec intTy] -- int (*cond)(ctxt *)
[(Just (AST.CDeclr (Just cond)
[ AST.CPtrDeclr [] N.undefNode
, AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode) ]
[(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)]
N.undefNode], False)
) [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode
formalArgX x = AST.CDecl [AST.CTypeSpec voidTy] -- void (*x)(ctxt *)
[(Just (AST.CDeclr (Just x)
[ AST.CPtrDeclr [] N.undefNode
, AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode) ]
[(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)]
N.undefNode], False)
) [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode
second = iid sndParamName
formalArgSecond = formalArgX second
third = iid thirdParamName
formalArgThird = formalArgX third
ctxt = iid ctxtParamName
formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt
[(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode
in fun [AST.CTypeSpec voidTy] (iid fname `app` iid operatorName) [formalArgCond, formalArgSecond, formalArgThird, formalArgCtxt]
[ AST.CBlockStmt (AST.CExpr (Just (((cvar ctxt .->. (iid stackCName)) .!!. (cvar ctxt .->. (iid stackTop))) .=. (cvar cond))) N.undefNode)
, AST.CBlockStmt (AST.CExpr (Just (((cvar ctxt .->. (iid stackSndName)) .!!. (cvar ctxt .->. (iid stackTop))) .=. (cvar second))) N.undefNode)
, AST.CBlockStmt (AST.CExpr (Just (((cvar ctxt .->. (iid stackThirdName)) .!!. (cvar ctxt .->. (iid stackTop))) .=. (cvar third))) N.undefNode)
, AST.CBlockStmt (AST.CExpr (Just ((cvar ctxt .->. (iid stackTop)) .=. (AST.CBinary AST.CAddOp (cvar ctxt .->. (iid stackTop)) (AST.CConst (AST.CIntConst (cInteger 1) N.undefNode)) N.undefNode))) N.undefNode)
]
loopPushCPS :: ContextName ->
String -> -- function name prefix
AST.CFunctionDef N.NodeInfo
loopPushCPS ctxtName fname = genPushCPS ctxtName fname loopPushName loopStackTop condParamName visitorParamName exitParamName loopStackCName loopStackVName loopStackEName
ifcPushCPS :: ContextName ->
String -> -- function name prefix
AST.CFunctionDef N.NodeInfo
ifcPushCPS ctxtName fname = genPushCPS ctxtName fname ifcPushName ifcStackTop condParamName trueParamName falseParamName ifcStackCName ifcStackTrName ifcStackFlName
{-
void pop(sortctxt *ctxt) {
ctxt->curr_stack_size = ctxt->curr_stack_size - 1;
}
-}
genPopCPS :: ContextName ->
String -> -- ^ function name prefix
String -> -- ^ operator name
String -> -- ^ stackTop
AST.CFunctionDef N.NodeInfo
genPopCPS ctxtName fname operatorName stackTop =
let ctxt = iid ctxtParamName
tyCtxt = [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)]
formalArgCtxt = ctxt .::*. tyCtxt
in fun [AST.CTypeSpec voidTy] (iid fname `app` iid operatorName) [formalArgCtxt]
[ AST.CBlockStmt (AST.CExpr (Just ((cvar ctxt .->. (iid stackTop)) .=. (AST.CBinary AST.CSubOp (cvar ctxt .->. (iid stackTop)) (AST.CConst (AST.CIntConst (cInteger 1) N.undefNode)) N.undefNode))) N.undefNode)
]
kPopCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo
kPopCPS ctxtName fname = genPopCPS ctxtName fname kPopName kStackTop
loopPopCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo
loopPopCPS ctxtName fname = genPopCPS ctxtName fname loopPopName loopStackTop
ifcPopCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo
ifcPopCPS ctxtName fname = genPopCPS ctxtName fname ifcPopName ifcStackTop
bindPopCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo
bindPopCPS ctxtName fname = genPopCPS ctxtName fname bindPopName bindStackTop
-- ^ loop_cps
{-
void loop_cps(int (*cond)(sortctxt*),
void (*visitor)(sortctxt*),
void (*exit)(sortctxt*),
sortctxt* ctxt) {
if ((*cond)(ctxt)) {
k_push(&lambda_loop_cps, ctxt);
(*visitor)(ctxt);
} else {
loop_pop(c);
(*exit)(ctxt);
}
}
-}
loopCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo
loopCPS ctxtName fname =
let cond = iid condParamName
formalArgCond = AST.CDecl [AST.CTypeSpec intTy] -- int (*cond)(ctxt *)
[(Just (AST.CDeclr (Just cond)
[ AST.CPtrDeclr [] N.undefNode
, AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode) ]
[(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)]
N.undefNode], False)
) [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode
formalArgX x = AST.CDecl [AST.CTypeSpec voidTy] -- void (*x)(ctxt *)
[(Just (AST.CDeclr (Just x)
[ AST.CPtrDeclr [] N.undefNode
, AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode) ]
[(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)]
N.undefNode], False)
) [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode
visitor = iid visitorParamName
formalArgVisitor = formalArgX visitor
exit = iid exitParamName
formalArgExit = formalArgX exit
-- k = iid kParamName
ctxt = iid ctxtParamName
formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt
[(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode
in fun [AST.CTypeSpec voidTy] (iid fname `app` iid loopName) [formalArgCond, formalArgVisitor, formalArgExit, formalArgCtxt]
[
AST.CBlockStmt (AST.CIf (funCall (ind (cvar cond)) [(cvar ctxt)])
(AST.CCompound [] [
AST.CBlockStmt (AST.CExpr (Just $ funCall (cvar $ (iid fname) `app` (iid kPushName)) [adr (cvar (iid fname `app` iid lambdaLoopName))
, cvar ctxt ]) N.undefNode )
, AST.CBlockStmt ( AST.CExpr (Just $ funCall (ind (cvar visitor)) [ cvar ctxt ]) N.undefNode ) ] N.undefNode)
(Just (AST.CCompound [] [
AST.CBlockStmt ( AST.CExpr (Just $ funCall (cvar $ (iid fname ) `app` (iid loopPopName)) [ cvar ctxt ]) N.undefNode )
, AST.CBlockStmt ( AST.CExpr (Just $ funCall (ind (cvar exit)) [ cvar ctxt ]) N.undefNode) ] N.undefNode))
N.undefNode)
]
{-
void lambda_loop_cps(sortctxt* c) {
ctxt_arr_bool cc = loop_peek_cond(c);
ctxt_arr_void v = loop_peek_v(c);
ctxt_arr_void e = loop_peek_e(c);
return loop_cps(cc,v,e,c);}
-}
lambdaLoopCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo
lambdaLoopCPS ctxtName fname =
let ctxt = iid ctxtParamName
formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt
[(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode
ty_ctxt_arr_bool = [AST.CTypeSpec (AST.CTypeDef (iid fname `app` (iid ctxt_arr_bool)) N.undefNode)]
cc = iid fname `app` iid "cc"
cc_var = Just (AST.CDeclr (Just cc) [] Nothing [] N.undefNode)
cc_rhs = Just (AST.CInitExpr (funCall (cvar (iid fname `app` (iid loopPeekCName))) [cvar $ iid ctxtParamName]) N.undefNode)
ccDecl = AST.CBlockDecl (AST.CDecl ty_ctxt_arr_bool [(cc_var, cc_rhs, Nothing)] N.undefNode)
ty_ctxt_arr_void = [AST.CTypeSpec (AST.CTypeDef (iid fname `app` (iid ctxt_arr_void)) N.undefNode)]
v = iid fname `app` iid "v"
v_var = Just (AST.CDeclr (Just v) [] Nothing [] N.undefNode)
v_rhs = Just (AST.CInitExpr (funCall (cvar (iid fname `app` (iid loopPeekVName))) [cvar $ iid ctxtParamName]) N.undefNode)
vDecl = AST.CBlockDecl (AST.CDecl ty_ctxt_arr_void [(v_var, v_rhs, Nothing)] N.undefNode)
e = iid fname `app` iid "e"
e_var = Just (AST.CDeclr (Just e) [] Nothing [] N.undefNode)
e_rhs = Just (AST.CInitExpr (funCall (cvar (iid fname `app` (iid loopPeekEName))) [cvar $ iid ctxtParamName]) N.undefNode)
eDecl = AST.CBlockDecl (AST.CDecl ty_ctxt_arr_void [(e_var, e_rhs, Nothing)] N.undefNode)
in fun [AST.CTypeSpec voidTy] (iid fname `app` iid lambdaLoopName) [formalArgCtxt]
[ ccDecl, vDecl, eDecl, AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar (iid fname `app` iid loopName))
[ cvar cc, cvar v, cvar e
, (cvar ctxt)
] N.undefNode)) N.undefNode) ]
{-
void id(sortctxt *ctxt) {
ctxt_arr_void k = k_peek(ctxt);
k_pop(ctxt);
return (*k)(ctxt);
}
-}
idCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo
idCPS ctxtName fname =
let ctxt = iid ctxtParamName
formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt
[(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode
ty_ctxt_arr_void = [AST.CTypeSpec (AST.CTypeDef (iid fname `app` (iid ctxt_arr_void)) N.undefNode)]
k = iid fname `app` iid "k"
k_var = Just (AST.CDeclr (Just k) [] Nothing [] N.undefNode)
k_rhs = Just (AST.CInitExpr (funCall (cvar (iid fname `app` (iid kPeekName))) [cvar $ iid ctxtParamName]) N.undefNode)
kDecl = AST.CBlockDecl (AST.CDecl ty_ctxt_arr_void [(k_var, k_rhs, Nothing)] N.undefNode)
in fun [AST.CTypeSpec voidTy] (iid fname `app` iid idName ) [formalArgCtxt]
[ kDecl
, AST.CBlockStmt (AST.CExpr (Just (funCall (cvar (iid fname `app` iid kPopName)) [ cvar ctxt ])) N.undefNode)
, AST.CBlockStmt (AST.CReturn (Just (funCall (ind (cvar k)) [ cvar ctxt ])) N.undefNode) ]
{-
void ret(sortctxt *c) {
return;
}
-}
-- ^ abort the context
retCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo
retCPS ctxtName fname =
let ctxt = iid ctxtParamName
formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt
[(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode
in fun [AST.CTypeSpec voidTy] (iid fname `app` iid retName ) [formalArgCtxt]
[ AST.CBlockStmt (AST.CReturn Nothing N.undefNode) ]
{-
ctxt_arr_bool loop_peek_cond(sortctxt* c) {
return c->loop_c[c->loop_stack_top-1];
}
-}
loopPeekCCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo
loopPeekCCPS ctxtName fname =
let ctxt = iid ctxtParamName
formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt
[(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode
return_ty = [AST.CTypeSpec (AST.CTypeDef (iid fname `app` (iid ctxt_arr_bool)) N.undefNode)]
exp = ((cvar ctxt) .->. (iid loopStackCName)) .!!. (AST.CBinary AST.CSubOp ((cvar ctxt) .->. (iid loopStackTop)) (AST.CConst (AST.CIntConst (cInteger 1) N.undefNode)) N.undefNode)
in fun return_ty (iid fname `app` iid loopPeekCName ) [ formalArgCtxt ]
[ AST.CBlockStmt (AST.CReturn (Just exp) N.undefNode) ]
{-
ctxt_arr_void loop_peek_v(sortctxt* c) {
return c->loop_v[c->loop_stack_top-1];
}
-}
loopPeekVCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo
loopPeekVCPS ctxtName fname =
let ctxt = iid ctxtParamName
formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt
[(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode
return_ty = [AST.CTypeSpec (AST.CTypeDef (iid fname `app` (iid ctxt_arr_void)) N.undefNode)]
exp = ((cvar ctxt) .->. (iid loopStackVName)) .!!. (AST.CBinary AST.CSubOp ((cvar ctxt) .->. (iid loopStackTop)) (AST.CConst (AST.CIntConst (cInteger 1) N.undefNode)) N.undefNode)
in fun return_ty (iid fname `app` iid loopPeekVName ) [ formalArgCtxt ]
[ AST.CBlockStmt (AST.CReturn (Just exp) N.undefNode) ]
{-
ctxt_arr_void loop_peek_e(sortctxt* c) {
return c->loop_e[c->loop_stack_top-1];
}
-}
loopPeekECPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo
loopPeekECPS ctxtName fname =
let ctxt = iid ctxtParamName
formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt
[(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode
return_ty = [AST.CTypeSpec (AST.CTypeDef (iid fname `app` (iid ctxt_arr_void)) N.undefNode)]
exp = ((cvar ctxt) .->. (iid loopStackEName)) .!!. (AST.CBinary AST.CSubOp ((cvar ctxt) .->. (iid loopStackTop)) (AST.CConst (AST.CIntConst (cInteger 1) N.undefNode)) N.undefNode)
in fun return_ty (iid fname `app` iid loopPeekEName ) [ formalArgCtxt ]
[ AST.CBlockStmt (AST.CReturn (Just exp) N.undefNode) ]
{-
void lambda_bind_cps(sortctxt* c) {
ctxt_arr_void m = bind_peek_m(c);
ctxt_arr_void f = bind_peek_f(c);
bind_pop(c);
return bind_cps(m,f,c);
}
-}
lambdaBindCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo
lambdaBindCPS ctxtName fname =
let ctxt = iid ctxtParamName
formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt
[(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode
ty_ctxt_arr_void = [AST.CTypeSpec (AST.CTypeDef (iid fname `app` (iid ctxt_arr_void)) N.undefNode)]
m = iid fname `app` iid "m"
m_var = Just (AST.CDeclr (Just m) [] Nothing [] N.undefNode)
m_rhs = Just (AST.CInitExpr (funCall (cvar (iid fname `app` (iid bindPeekMName))) [cvar $ iid ctxtParamName]) N.undefNode)
mDecl = AST.CBlockDecl (AST.CDecl ty_ctxt_arr_void [(m_var, m_rhs, Nothing)] N.undefNode)
f = iid fname `app` iid "f"
f_var = Just (AST.CDeclr (Just f) [] Nothing [] N.undefNode)
f_rhs = Just (AST.CInitExpr (funCall (cvar (iid fname `app` (iid bindPeekFName))) [cvar $ iid ctxtParamName]) N.undefNode)
fDecl = AST.CBlockDecl (AST.CDecl ty_ctxt_arr_void [(f_var, f_rhs, Nothing)] N.undefNode)
in fun [AST.CTypeSpec voidTy] (iid fname `app` iid lambdaBindName) [formalArgCtxt]
[ mDecl, fDecl, AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar (iid fname `app` iid bindPopName)) [ cvar ctxt ] N.undefNode)) N.undefNode),
AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar (iid fname `app` iid bindName))
[ cvar m, cvar f
, (cvar ctxt)
] N.undefNode)) N.undefNode) ]
{-
void bind_cps(ctxt_arr_void m, ctxt_arr_void f, sortctxt* c) {
k_push(f,c);
return (*m)(c);
}
-}
bindCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo
bindCPS ctxtName fname =
let cond = iid condParamName
formalArgX x = AST.CDecl [AST.CTypeSpec voidTy] -- void (*x)(ctxt *) --todo: ctxt_arr_void x
[(Just (AST.CDeclr (Just x)
[ AST.CPtrDeclr [] N.undefNode
, AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode) ]
[(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)]
N.undefNode], False)
) [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode
m = iid mParamName
formalArgM = formalArgX m
f = iid fParamName
formalArgF = formalArgX f
ctxt = iid ctxtParamName
formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt
[(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode
in fun [AST.CTypeSpec voidTy] (iid fname `app` iid bindName) [formalArgM, formalArgF, formalArgCtxt]
[ AST.CBlockStmt (AST.CExpr (Just $ funCall (cvar $ (iid fname) `app` (iid kPushName)) [ cvar f
, cvar ctxt ]) N.undefNode )
, AST.CBlockStmt ( AST.CExpr (Just $ funCall (ind (cvar m)) [ cvar ctxt ]) N.undefNode )
]
{-
void bind_push(ctxt_arr_void m, ctxt_arr_void f, sortctxt* c) {
c->bind_m[c->bind_stack_top] = m;
c->bind_f[c->bind_stack_top] = f;
c->bind_stack_top +=1;
return;
}
-}
bindPushCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo
bindPushCPS ctxtName fname =
let
formalArgX x = AST.CDecl [AST.CTypeSpec voidTy] -- void (*x)(ctxt *)
[(Just (AST.CDeclr (Just x)
[ AST.CPtrDeclr [] N.undefNode
, AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode) ]
[(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)]
N.undefNode], False)
) [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode
second = iid mParamName
formalArgSecond = formalArgX second
third = iid fParamName
formalArgThird = formalArgX third
ctxt = iid ctxtParamName
formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt
[(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode
in fun [AST.CTypeSpec voidTy] (iid fname `app` iid bindPushName) [formalArgSecond, formalArgThird, formalArgCtxt]
[ AST.CBlockStmt (AST.CExpr (Just (((cvar ctxt .->. (iid bindStackMName)) .!!. (cvar ctxt .->. (iid bindStackTop))) .=. (cvar second))) N.undefNode)
, AST.CBlockStmt (AST.CExpr (Just (((cvar ctxt .->. (iid bindStackFName)) .!!. (cvar ctxt .->. (iid bindStackTop))) .=. (cvar third))) N.undefNode)
, AST.CBlockStmt (AST.CExpr (Just ((cvar ctxt .->. (iid bindStackTop)) .=. (AST.CBinary AST.CAddOp (cvar ctxt .->. (iid bindStackTop)) (AST.CConst (AST.CIntConst (cInteger 1) N.undefNode)) N.undefNode))) N.undefNode)
]
{-
ctxt_arr_void bind_peek_m(sortctxt* c) {
return c->bind_m[c->bind_stack_top-1];
}
ctxt_arr_void bind_peek_f(sortctxt* c) {
return c->bind_f[c->bind_stack_top-1];
}
-}
bindPeekMCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo
bindPeekMCPS ctxtName fname =
let ctxt = iid ctxtParamName
formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt
[(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode
return_ty = [AST.CTypeSpec (AST.CTypeDef (iid fname `app` (iid ctxt_arr_void)) N.undefNode)]
exp = ((cvar ctxt) .->. (iid bindStackMName)) .!!. (AST.CBinary AST.CSubOp ((cvar ctxt) .->. (iid bindStackTop)) (AST.CConst (AST.CIntConst (cInteger 1) N.undefNode)) N.undefNode)
in fun return_ty (iid fname `app` iid bindPeekMName ) [ formalArgCtxt ]
[ AST.CBlockStmt (AST.CReturn (Just exp) N.undefNode) ]
bindPeekFCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo
bindPeekFCPS ctxtName fname =
let ctxt = iid ctxtParamName
formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt
[(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode
return_ty = [AST.CTypeSpec (AST.CTypeDef (iid fname `app` (iid ctxt_arr_void)) N.undefNode)]
exp = ((cvar ctxt) .->. (iid bindStackFName)) .!!. (AST.CBinary AST.CSubOp ((cvar ctxt) .->. (iid bindStackTop)) (AST.CConst (AST.CIntConst (cInteger 1) N.undefNode)) N.undefNode)
in fun return_ty (iid fname `app` iid bindPeekFName ) [ formalArgCtxt ]
[ AST.CBlockStmt (AST.CReturn (Just exp) N.undefNode) ]
{-
void ifc_cps(ctxt_arr_bool cond, ctxt_arr_void t, ctxt_arr_void f, sortctxt* c) {
ifc_pop(c);
if ((*cond)(c)) {
return (*t)(c);
} else {
return (*f)(c);
}
}
-}
ifcCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo
ifcCPS ctxtName fname =
let cond = iid condParamName
formalArgCond = AST.CDecl [AST.CTypeSpec intTy] -- int (*cond)(ctxt *) -- todo change to ctxt_arr_bool cond
[(Just (AST.CDeclr (Just cond)
[ AST.CPtrDeclr [] N.undefNode
, AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode) ]
[(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)]
N.undefNode], False)
) [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode
formalArgX x = AST.CDecl [AST.CTypeSpec voidTy] -- void (*x)(ctxt *)
[(Just (AST.CDeclr (Just x)
[ AST.CPtrDeclr [] N.undefNode
, AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode) ]
[(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)]
N.undefNode], False)
) [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode
tr = iid trueParamName
formalArgTr = formalArgX tr
fl = iid falseParamName
formalArgFl = formalArgX fl
-- k = iid kParamName
ctxt = iid ctxtParamName
formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt
[(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode
in fun [AST.CTypeSpec voidTy] (iid fname `app` iid ifcName) [formalArgCond, formalArgTr, formalArgFl, formalArgCtxt]
[ AST.CBlockStmt ( AST.CExpr (Just $ funCall (cvar $ (iid fname ) `app` (iid ifcPopName)) [ cvar ctxt ]) N.undefNode )
,AST.CBlockStmt (AST.CIf (funCall (ind (cvar cond)) [(cvar ctxt)])
(AST.CCompound [] [AST.CBlockStmt ( AST.CExpr (Just $ funCall (ind (cvar tr)) [ cvar ctxt ]) N.undefNode ) ] N.undefNode)
(Just (AST.CCompound [] [AST.CBlockStmt ( AST.CExpr (Just $ funCall (ind (cvar fl)) [ cvar ctxt ]) N.undefNode) ] N.undefNode))
N.undefNode)
]
{-
void lambda_ifc_cps(sortctxt* c) {
ctxt_arr_bool cc = ifc_peek_c(c);
ctxt_arr_void tr = ifc_peek_tr(c);
ctxt_arr_void fl = ifc_peek_fl(c);
return ifc_cps(cc,tr,fl,c);
}
-}
lambdaIfcCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo
lambdaIfcCPS ctxtName fname =
let ctxt = iid ctxtParamName
formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt
[(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode
ty_ctxt_arr_bool = [AST.CTypeSpec (AST.CTypeDef (iid fname `app` (iid ctxt_arr_bool)) N.undefNode)]
cc = iid fname `app` iid "cc"
cc_var = Just (AST.CDeclr (Just cc) [] Nothing [] N.undefNode)
cc_rhs = Just (AST.CInitExpr (funCall (cvar (iid fname `app` (iid ifcPeekCName))) [cvar $ iid ctxtParamName]) N.undefNode)
ccDecl = AST.CBlockDecl (AST.CDecl ty_ctxt_arr_bool [(cc_var, cc_rhs, Nothing)] N.undefNode)
ty_ctxt_arr_void = [AST.CTypeSpec (AST.CTypeDef (iid fname `app` (iid ctxt_arr_void)) N.undefNode)]
tr = iid fname `app` iid "tr"
tr_var = Just (AST.CDeclr (Just tr) [] Nothing [] N.undefNode)
tr_rhs = Just (AST.CInitExpr (funCall (cvar (iid fname `app` (iid ifcPeekTrName))) [cvar $ iid ctxtParamName]) N.undefNode)
trDecl = AST.CBlockDecl (AST.CDecl ty_ctxt_arr_void [(tr_var, tr_rhs, Nothing)] N.undefNode)
fl = iid fname `app` iid "fl"
fl_var = Just (AST.CDeclr (Just fl) [] Nothing [] N.undefNode)
fl_rhs = Just (AST.CInitExpr (funCall (cvar (iid fname `app` (iid ifcPeekFlName))) [cvar $ iid ctxtParamName]) N.undefNode)
flDecl = AST.CBlockDecl (AST.CDecl ty_ctxt_arr_void [(fl_var, fl_rhs, Nothing)] N.undefNode)
in fun [AST.CTypeSpec voidTy] (iid fname `app` iid lambdaIfcName) [formalArgCtxt]
[ ccDecl, trDecl, flDecl, AST.CBlockStmt (AST.CExpr (Just (AST.CCall (cvar (iid fname `app` iid ifcName))
[ cvar cc, cvar tr, cvar fl
, (cvar ctxt)
] N.undefNode)) N.undefNode) ]
{-
ctxt_arr_bool ifc_peek_c(sortctxt* c) {
return c->ifc_c[c->ifc_stack_top-1];
}
-}
ifcPeekCCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo
ifcPeekCCPS ctxtName fname =
let ctxt = iid ctxtParamName
formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt
[(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode
return_ty = [AST.CTypeSpec (AST.CTypeDef (iid fname `app` (iid ctxt_arr_bool)) N.undefNode)]
exp = ((cvar ctxt) .->. (iid ifcStackCName)) .!!. (AST.CBinary AST.CSubOp ((cvar ctxt) .->. (iid ifcStackTop)) (AST.CConst (AST.CIntConst (cInteger 1) N.undefNode)) N.undefNode)
in fun return_ty (iid fname `app` iid ifcPeekCName ) [ formalArgCtxt ]
[ AST.CBlockStmt (AST.CReturn (Just exp) N.undefNode) ]
{-
ctxt_arr_void ifc_peek_tr(sortctxt* c) {
return c->ifc_tr[c->ifc_stack_top-1];
}
-}
ifcPeekTrCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo
ifcPeekTrCPS ctxtName fname =
let ctxt = iid ctxtParamName
formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt
[(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode
return_ty = [AST.CTypeSpec (AST.CTypeDef (iid fname `app` (iid ctxt_arr_void)) N.undefNode)]
exp = ((cvar ctxt) .->. (iid ifcStackTrName)) .!!. (AST.CBinary AST.CSubOp ((cvar ctxt) .->. (iid ifcStackTop)) (AST.CConst (AST.CIntConst (cInteger 1) N.undefNode)) N.undefNode)
in fun return_ty (iid fname `app` iid ifcPeekTrName ) [ formalArgCtxt ]
[ AST.CBlockStmt (AST.CReturn (Just exp) N.undefNode) ]
{-
ctxt_arr_void ifc_peek_fl(sortctxt* c) {
return c->ifc_fl[c->ifc_stack_top-1];
}
-}
ifcPeekFlCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo
ifcPeekFlCPS ctxtName fname =
let ctxt = iid ctxtParamName
formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt
[(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode
return_ty = [AST.CTypeSpec (AST.CTypeDef (iid fname `app` (iid ctxt_arr_void)) N.undefNode)]
exp = ((cvar ctxt) .->. (iid ifcStackFlName)) .!!. (AST.CBinary AST.CSubOp ((cvar ctxt) .->. (iid ifcStackTop)) (AST.CConst (AST.CIntConst (cInteger 1) N.undefNode)) N.undefNode)
in fun return_ty (iid fname `app` iid ifcPeekFlName ) [ formalArgCtxt ]
[ AST.CBlockStmt (AST.CReturn (Just exp) N.undefNode) ]
{-
void k_push(ctxt_arr_void k, sortctxt* c) {
c->k[c->k_stack_top] = k;
c->k_stack_top +=1;
return;
}
-}
kPushCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo
kPushCPS ctxtName fname =
let formalArgX x = AST.CDecl [AST.CTypeSpec voidTy] -- void (*x)(ctxt *)
[(Just (AST.CDeclr (Just x)
[ AST.CPtrDeclr [] N.undefNode
, AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode) ]
[(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)]
N.undefNode], False)
) [] N.undefNode] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode
k = iid kParamName
formalArgK = formalArgX k
ctxt = iid ctxtParamName
formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt
[(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode
in fun [AST.CTypeSpec voidTy] (iid fname `app` iid kPushName) [formalArgK, formalArgCtxt]
[ AST.CBlockStmt (AST.CExpr (Just (((cvar ctxt .->. (iid kStackName)) .!!. (cvar ctxt .->. (iid kStackTop))) .=. (cvar k))) N.undefNode)
, AST.CBlockStmt (AST.CExpr (Just ((cvar ctxt .->. (iid kStackTop)) .=. (AST.CBinary AST.CAddOp (cvar ctxt .->. (iid kStackTop)) (AST.CConst (AST.CIntConst (cInteger 1) N.undefNode)) N.undefNode))) N.undefNode)
]
{-
ctxt_arr_void k_peek(sortctxt* c) {
return c->k[c->k_stack_top-1];
}
-}
kPeekCPS :: ContextName -> String -> AST.CFunctionDef N.NodeInfo
kPeekCPS ctxtName fname =
let ctxt = iid ctxtParamName
formalArgCtxt = AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] -- ctxt* ctxt
[(Just (AST.CDeclr (Just ctxt) [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode
return_ty = [AST.CTypeSpec (AST.CTypeDef (iid fname `app` (iid ctxt_arr_void)) N.undefNode)]
exp = ((cvar ctxt) .->. (iid kStackName)) .!!. (AST.CBinary AST.CSubOp ((cvar ctxt) .->. (iid kStackTop)) (AST.CConst (AST.CIntConst (cInteger 1) N.undefNode)) N.undefNode)
in fun return_ty (iid fname `app` iid kPeekName ) [ formalArgCtxt ]
[ AST.CBlockStmt (AST.CReturn (Just exp) N.undefNode) ]
-- ^ generate function signature declaration from function definition
funSig :: AST.CFunctionDef N.NodeInfo -> AST.CDeclaration N.NodeInfo
funSig (AST.CFunDef tySpecfs declarator op_decls stmt nodeInfo) = AST.CDecl tySpecfs [(Just declarator, Nothing, Nothing)] N.undefNode
-- ^ making the context struct declaration
mkContext :: String -> -- ^ context name
M.Map Ident LabeledBlock -> -- ^ labeled blocks
[AST.CDeclaration N.NodeInfo] -> -- ^ formal arguments
[AST.CDeclaration N.NodeInfo] -> -- ^ local variable declarations
[AST.CDeclarationSpecifier N.NodeInfo] -> -- ^ return Type
[AST.CDerivedDeclarator N.NodeInfo] -> -- ^ the pointer or array postfix
S.Set Ident -> S.Set Ident ->
AST.CDeclaration N.NodeInfo
mkContext name labeledBlocks formal_arg_decls local_var_decls returnType ptrArrs local_decl_vars fargs =
let structName = iid name
ctxtAlias = AST.CDeclr (Just (internalIdent (map toLower name))) [] Nothing [] N.undefNode
attrs = []
stackSize = 20
isReturnVoid = isVoidDeclSpec returnType
unaryFuncStack ty fname = AST.CDecl [AST.CTypeSpec ty] -- void (*loop_ks[2])(struct FuncCtxt*);
-- todo : these are horrible to read, can be simplified via some combinators
[(Just (AST.CDeclr (Just $ iid fname) [ AST.CArrDeclr [] (AST.CArrSize False (AST.CConst (AST.CIntConst (cInteger stackSize) N.undefNode))) N.undefNode
, AST.CPtrDeclr [] N.undefNode
, AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CSUType (AST.CStruct AST.CStructTag (Just structName) Nothing [] N.undefNode) N.undefNode)] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode],False)) [] N.undefNode] Nothing [] N.undefNode) ,Nothing,Nothing)] N.undefNode
kStack = unaryFuncStack voidTy kStackName
loopCStack = unaryFuncStack intTy loopStackCName
loopVStack = unaryFuncStack voidTy loopStackVName
loopEStack = unaryFuncStack voidTy loopStackEName
ifcCStatck = unaryFuncStack intTy ifcStackCName
ifcTrStack = unaryFuncStack voidTy ifcStackTrName
ifcFlStack = unaryFuncStack voidTy ifcStackFlName
bindMStack = unaryFuncStack voidTy bindStackMName
bindFStack = unaryFuncStack voidTy bindStackFName
stackTop name = AST.CDecl [AST.CTypeSpec intTy] [(Just (AST.CDeclr (Just $ iid name) [] Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode
kTop = stackTop kStackTop
loopTop = stackTop loopStackTop
ifcTop = stackTop ifcStackTop
bindTop = stackTop bindStackTop
funcResult | isReturnVoid = []
| otherwise = [AST.CDecl returnType [(Just (AST.CDeclr (Just $ iid "func_result") ptrArrs Nothing [] N.undefNode), Nothing, Nothing)] N.undefNode]
decls' = -- formal_arg_decls ++
-- note: we remove local decl duplicate, maybe we should let different label block to have different type decl in the ctxt, see test/scoped_dup_var.c
concatMap (\d -> renameDeclWithLabeledBlocks d labeledBlocks local_decl_vars fargs) (nubBy declLHSEq $ map (cps_trans_declaration . dropConstTyQual . dropStorageQual) (formal_arg_decls ++ local_var_decls)) ++ [kStack, loopCStack, loopVStack, loopEStack, ifcCStatck, ifcTrStack, ifcFlStack, bindMStack, bindFStack, kTop, loopTop, ifcTop, bindTop ] ++ funcResult
tyDef = AST.CStorageSpec (AST.CTypedef N.undefNode)
structDef =
AST.CTypeSpec (AST.CSUType
(AST.CStruct AST.CStructTag (Just structName) (Just decls') attrs N.undefNode) N.undefNode)
in AST.CDecl [tyDef, structDef] [(Just ctxtAlias, Nothing, Nothing)] N.undefNode
ctxt_arr_voidDecl :: String -> -- ^ context name
String -> -- ^ function name
AST.CDeclaration N.NodeInfo
ctxt_arr_voidDecl ctxtName fname =
let
tyDef = AST.CStorageSpec (AST.CTypedef N.undefNode)
voidTyDef = AST.CTypeSpec voidTy
def = AST.CDeclr (Just (iid fname `app` iid ctxt_arr_void))
[AST.CPtrDeclr [] N.undefNode,
AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode],False)) [] N.undefNode] Nothing [] N.undefNode
in AST.CDecl [tyDef, voidTyDef] [(Just def, Nothing, Nothing)] N.undefNode
ctxt_arr_boolDecl :: String -> -- ^ context name
String -> -- ^ function name
AST.CDeclaration N.NodeInfo
ctxt_arr_boolDecl ctxtName fname =
let
tyDef = AST.CStorageSpec (AST.CTypedef N.undefNode)
intTyDef = AST.CTypeSpec intTy
def = AST.CDeclr (Just (iid fname `app` iid ctxt_arr_bool))
[AST.CPtrDeclr [] N.undefNode,
AST.CFunDeclr (Right ([AST.CDecl [AST.CTypeSpec (AST.CTypeDef (iid ctxtName) N.undefNode)] [(Just (AST.CDeclr Nothing [AST.CPtrDeclr [] N.undefNode] Nothing [] N.undefNode),Nothing,Nothing)] N.undefNode],False)) [] N.undefNode] Nothing [] N.undefNode
in AST.CDecl [tyDef, intTyDef] [(Just def, Nothing, Nothing)] N.undefNode
-- eq for the declaration nub, see the above
declLHSEq (AST.CDecl declSpecifiers1 trips1 _) (AST.CDecl declSpecifiers2 trips2 _) =
let getIds trips = map (\(mb_decl, mb_init, mb_size) -> case mb_decl of
{ Just (AST.CDeclr mb_id derivedDeclarators mb_strLit attrs nInfo) -> mb_id
; Nothing -> Nothing }) trips
in (getIds trips1) == (getIds trips2)
-- we need to drop the constant type specifier since we need to initialize them in block 0, see test/const.c
dropConstTyQual :: AST.CDeclaration N.NodeInfo -> AST.CDeclaration N.NodeInfo
dropConstTyQual decl = case decl of
{ AST.CDecl declSpecifiers trips ni -> AST.CDecl (filter (not . isConst) declSpecifiers) trips ni }
where isConst (AST.CTypeQual (AST.CConstQual _)) = True
isConst _ = False
-- we need to drop the static storage specifier since we need to initialize them in block 0, see test/arrayinitlist.c
dropStorageQual :: AST.CDeclaration N.NodeInfo -> AST.CDeclaration N.NodeInfo
dropStorageQual decl = case decl of
{ AST.CDecl declSpecifiers trips ni -> AST.CDecl (filter (not . isStorageQual) declSpecifiers) trips ni }
-- renameDeclWithLabels :: AST.CDeclaration N.NodeInfo -> [Ident] -> [AST.CDeclaration N.NodeInfo]
-- renameDeclWithLabels decl labels = map (renameDeclWithLabel decl) labels
renameDeclWithLabeledBlocks :: AST.CDeclaration N.NodeInfo -> M.Map Ident LabeledBlock -> S.Set Ident -> S.Set Ident -> [AST.CDeclaration N.NodeInfo]
renameDeclWithLabeledBlocks decl labeledBlocks local_decl_vars fargs =
let idents = getFormalArgIds decl
in do
{ ident <- idents
; (lb,blk) <- M.toList labeledBlocks
; if (null (lb_preds blk)) || -- it's the entry block
(ident `elem` (lb_lvars blk)) || -- the var is in the lvars
(ident `elem` (map fst (lb_phis blk))) || -- the var is in the phi
(ident `elem` (lb_containers blk)) -- the var is one of the lhs container ids such as array or members
then return (renameDeclWithLabel decl lb local_decl_vars fargs)
else []
}
renameDeclWithLabel decl label local_decl_vars fargs =
let rnState = RSt label M.empty [] [] local_decl_vars fargs
in case renamePure rnState decl of
{ (decl', rstate', containers) -> decl' }
{-
translation t => T
-----------
int => int
-----------
bool => bool
t => t
-------------
t* => T*
t => T
------------
t[] => T*
-------------
void => void
-}
cps_trans_declaration :: AST.CDeclaration N.NodeInfo -> AST.CDeclaration N.NodeInfo
cps_trans_declaration (AST.CDecl declSpecifiers trips ni) =
AST.CDecl (map cps_trans_declspec declSpecifiers) (map (\(mb_decl, mb_init, mb_size) ->
let mb_decl' = case mb_decl of
{ Nothing -> Nothing
; Just decl -> Just (cps_trans_decltr decl)
}
in (mb_decl', mb_init, mb_size)) trips) ni
-- lhs of a declaration
cps_trans_declspec :: AST.CDeclarationSpecifier N.NodeInfo -> AST.CDeclarationSpecifier N.NodeInfo
cps_trans_declspec (AST.CStorageSpec storageSpec) = AST.CStorageSpec storageSpec -- auto, register, static, extern etc
cps_trans_declspec (AST.CTypeSpec tySpec) = AST.CTypeSpec tySpec -- simple type, void, int, bool etc
cps_trans_declspec (AST.CTypeQual tyQual) = AST.CTypeQual tyQual -- qual, CTypeQual, CVolatQual, etc
-- cps_trans_declspec (AST.CFunSpec funSpec) = AST.CFunSpec funSpec -- todo
-- cps_trans_declspec (AST.CAlignSpec alignSpec) = AST.CAlignSpec alignSpec -- todo
-- rhs (after the variable)
cps_trans_decltr :: AST.CDeclarator N.NodeInfo -> AST.CDeclarator N.NodeInfo
cps_trans_decltr (AST.CDeclr mb_id derivedDeclarators mb_strLit attrs nInfo) =
AST.CDeclr mb_id (map cps_trans_derived_decltr derivedDeclarators) mb_strLit attrs nInfo
cps_trans_derived_decltr :: AST.CDerivedDeclarator N.NodeInfo -> AST.CDerivedDeclarator N.NodeInfo
cps_trans_derived_decltr (AST.CPtrDeclr tyQuals ni) = AST.CPtrDeclr tyQuals ni
cps_trans_derived_decltr (AST.CArrDeclr tyQuals arrSize ni) = AST.CPtrDeclr tyQuals ni
cps_trans_derived_decltr (AST.CFunDeclr either_id_decls attrs ni) = AST.CFunDeclr either_id_decls attrs ni
{-
data CDeclarationSpecifier a
= CStorageSpec (CStorageSpecifier a) -- ^ storage-class specifier or typedef
| CTypeSpec (CTypeSpecifier a) -- ^ type name
| CTypeQual (CTypeQualifier a) -- ^ type qualifier
| CFunSpec (CFunctionSpecifier a) -- ^ function specifier
| CAlignSpec (CAlignmentSpecifier a) -- ^ alignment specifier
deriving (Show, Data,Typeable {-! ,CNode ,Functor, Annotated !-})
-}
|
luzhuomi/cpp-obs
|
Language/C/Obfuscate/CPS.hs
|
Haskell
|
apache-2.0
| 92,814
|
module Main
( main
) where
import Protolude
import Test.Tasty (defaultMain, testGroup)
import qualified Spake2
import qualified Groups
import qualified Integration
main :: IO ()
main = sequence tests >>= defaultMain . testGroup "Spake2"
where
tests =
[ Spake2.tests
, Groups.tests
, Integration.tests
]
|
jml/haskell-spake2
|
tests/Tasty.hs
|
Haskell
|
apache-2.0
| 341
|
-- | Domain of terms.
module Akarui.FOL.Domain where
import Data.Set (Set)
import Akarui.Parser
import Text.Parsec
import Text.Parsec.String (Parser)
import qualified Data.Set as Set
-- | Domain of variables and constants.
data Domain =
Any
| Interval Double Double
| Finite (Set String)
-- | Parse a clause (a disjunction of positive and negative literals).
--
-- @
-- dom1={1, 2, 3, 4}
-- person = { Elaine, George, Jerry, Cosmo, Newman }
-- @
parseDomain :: String -> Either ParseError (String, Set String)
parseDomain = parse (contents parseDs) "<stdin>"
parseDs :: Parser (String, Set String)
parseDs = do
n <- identifier
reservedOp "="
reservedOp "{"
elems <- commaSep identifier
reservedOp "}"
return (n, Set.fromList elems)
|
PhDP/Manticore
|
Akarui/FOL/Domain.hs
|
Haskell
|
apache-2.0
| 763
|
module Reddit.Routes.Search where
import Reddit.Types.Options
import Reddit.Types.Post
import Reddit.Types.Subreddit
import qualified Reddit.Types.SearchOptions as Search
import Data.Maybe
import Data.Text (Text)
import Network.API.Builder.Routes
searchRoute :: Maybe SubredditName -> Options PostID -> Search.Order -> Maybe Text -> Text -> Route
searchRoute r opts sorder engine q =
Route (path r)
[ "after" =. after opts
, "before" =. before opts
, "restrict_sr" =. isJust r
, "sort" =. sorder
, "syntax" =. engine
, "limit" =. limit opts
, "q" =. Just q ]
"GET"
where
path (Just (R sub)) = [ "r", sub, "search" ]
path Nothing = [ "search" ]
|
intolerable/reddit
|
src/Reddit/Routes/Search.hs
|
Haskell
|
bsd-2-clause
| 723
|
{-# LANGUAGE FlexibleContexts #-}
module Application.DiagramDrawer.Coroutine where
import Control.Monad.Coroutine
import Control.Monad.State
import Control.Monad.Coroutine.SuspensionFunctors
import Data.IORef
import Application.DiagramDrawer.Type
bouncecallback :: IORef (Await DiagramEvent (Iteratee DiagramEvent DiagramStateIO ()))
-> IORef DiagramState
-> DiagramEvent
-> IO ()
bouncecallback tref sref input = do
Await cont <- readIORef tref
st <- readIORef sref
(nr,st') <- runStateT (resume (cont input)) st
case nr of
Left naw -> do writeIORef tref naw
writeIORef sref st'
Right val -> do putStrLn $ show val
writeIORef tref (Await (\_ -> return ()))
writeIORef sref st'
putStrLn "one step"
return ()
|
wavewave/diagdrawer
|
lib/Application/DiagramDrawer/Coroutine.hs
|
Haskell
|
bsd-2-clause
| 852
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QFileInfo.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:31
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Core.QFileInfo (
QqFileInfo(..)
,QqFileInfo_nf(..)
,absoluteDir
,baseName
,bundleName
,caching
,canonicalFilePath
,completeBaseName
,completeSuffix
,created
,dir
,groupId
,isBundle
,ownerId
,permission
,setCaching
,qFileInfo_delete
)
where
import Foreign.C.Types
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Core.QFile
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
class QqFileInfo x1 where
qFileInfo :: x1 -> IO (QFileInfo ())
instance QqFileInfo (()) where
qFileInfo ()
= withQFileInfoResult $
qtc_QFileInfo
foreign import ccall "qtc_QFileInfo" qtc_QFileInfo :: IO (Ptr (TQFileInfo ()))
instance QqFileInfo ((QFile t1)) where
qFileInfo (x1)
= withQFileInfoResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QFileInfo1 cobj_x1
foreign import ccall "qtc_QFileInfo1" qtc_QFileInfo1 :: Ptr (TQFile t1) -> IO (Ptr (TQFileInfo ()))
instance QqFileInfo ((QFileInfo t1)) where
qFileInfo (x1)
= withQFileInfoResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QFileInfo2 cobj_x1
foreign import ccall "qtc_QFileInfo2" qtc_QFileInfo2 :: Ptr (TQFileInfo t1) -> IO (Ptr (TQFileInfo ()))
instance QqFileInfo ((String)) where
qFileInfo (x1)
= withQFileInfoResult $
withCWString x1 $ \cstr_x1 ->
qtc_QFileInfo3 cstr_x1
foreign import ccall "qtc_QFileInfo3" qtc_QFileInfo3 :: CWString -> IO (Ptr (TQFileInfo ()))
instance QqFileInfo ((QDir t1, String)) where
qFileInfo (x1, x2)
= withQFileInfoResult $
withObjectPtr x1 $ \cobj_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QFileInfo4 cobj_x1 cstr_x2
foreign import ccall "qtc_QFileInfo4" qtc_QFileInfo4 :: Ptr (TQDir t1) -> CWString -> IO (Ptr (TQFileInfo ()))
class QqFileInfo_nf x1 where
qFileInfo_nf :: x1 -> IO (QFileInfo ())
instance QqFileInfo_nf (()) where
qFileInfo_nf ()
= withObjectRefResult $
qtc_QFileInfo
instance QqFileInfo_nf ((QFile t1)) where
qFileInfo_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QFileInfo1 cobj_x1
instance QqFileInfo_nf ((QFileInfo t1)) where
qFileInfo_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QFileInfo2 cobj_x1
instance QqFileInfo_nf ((String)) where
qFileInfo_nf (x1)
= withObjectRefResult $
withCWString x1 $ \cstr_x1 ->
qtc_QFileInfo3 cstr_x1
instance QqFileInfo_nf ((QDir t1, String)) where
qFileInfo_nf (x1, x2)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QFileInfo4 cobj_x1 cstr_x2
absoluteDir :: QFileInfo a -> (()) -> IO (QDir ())
absoluteDir x0 ()
= withQDirResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_absoluteDir cobj_x0
foreign import ccall "qtc_QFileInfo_absoluteDir" qtc_QFileInfo_absoluteDir :: Ptr (TQFileInfo a) -> IO (Ptr (TQDir ()))
instance QabsoluteFilePath (QFileInfo a) (()) where
absoluteFilePath x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_absoluteFilePath cobj_x0
foreign import ccall "qtc_QFileInfo_absoluteFilePath" qtc_QFileInfo_absoluteFilePath :: Ptr (TQFileInfo a) -> IO (Ptr (TQString ()))
instance QabsolutePath (QFileInfo a) (()) where
absolutePath x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_absolutePath cobj_x0
foreign import ccall "qtc_QFileInfo_absolutePath" qtc_QFileInfo_absolutePath :: Ptr (TQFileInfo a) -> IO (Ptr (TQString ()))
baseName :: QFileInfo a -> (()) -> IO (String)
baseName x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_baseName cobj_x0
foreign import ccall "qtc_QFileInfo_baseName" qtc_QFileInfo_baseName :: Ptr (TQFileInfo a) -> IO (Ptr (TQString ()))
bundleName :: QFileInfo a -> (()) -> IO (String)
bundleName x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_bundleName cobj_x0
foreign import ccall "qtc_QFileInfo_bundleName" qtc_QFileInfo_bundleName :: Ptr (TQFileInfo a) -> IO (Ptr (TQString ()))
caching :: QFileInfo a -> (()) -> IO (Bool)
caching x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_caching cobj_x0
foreign import ccall "qtc_QFileInfo_caching" qtc_QFileInfo_caching :: Ptr (TQFileInfo a) -> IO CBool
canonicalFilePath :: QFileInfo a -> (()) -> IO (String)
canonicalFilePath x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_canonicalFilePath cobj_x0
foreign import ccall "qtc_QFileInfo_canonicalFilePath" qtc_QFileInfo_canonicalFilePath :: Ptr (TQFileInfo a) -> IO (Ptr (TQString ()))
instance QcanonicalPath (QFileInfo a) (()) where
canonicalPath x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_canonicalPath cobj_x0
foreign import ccall "qtc_QFileInfo_canonicalPath" qtc_QFileInfo_canonicalPath :: Ptr (TQFileInfo a) -> IO (Ptr (TQString ()))
completeBaseName :: QFileInfo a -> (()) -> IO (String)
completeBaseName x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_completeBaseName cobj_x0
foreign import ccall "qtc_QFileInfo_completeBaseName" qtc_QFileInfo_completeBaseName :: Ptr (TQFileInfo a) -> IO (Ptr (TQString ()))
completeSuffix :: QFileInfo a -> (()) -> IO (String)
completeSuffix x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_completeSuffix cobj_x0
foreign import ccall "qtc_QFileInfo_completeSuffix" qtc_QFileInfo_completeSuffix :: Ptr (TQFileInfo a) -> IO (Ptr (TQString ()))
created :: QFileInfo a -> (()) -> IO (QDateTime ())
created x0 ()
= withQDateTimeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_created cobj_x0
foreign import ccall "qtc_QFileInfo_created" qtc_QFileInfo_created :: Ptr (TQFileInfo a) -> IO (Ptr (TQDateTime ()))
instance Qdetach (QFileInfo a) (()) where
detach x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_detach cobj_x0
foreign import ccall "qtc_QFileInfo_detach" qtc_QFileInfo_detach :: Ptr (TQFileInfo a) -> IO ()
dir :: QFileInfo a -> (()) -> IO (QDir ())
dir x0 ()
= withQDirResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_dir cobj_x0
foreign import ccall "qtc_QFileInfo_dir" qtc_QFileInfo_dir :: Ptr (TQFileInfo a) -> IO (Ptr (TQDir ()))
instance Qexists (QFileInfo a) (()) where
exists x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_exists cobj_x0
foreign import ccall "qtc_QFileInfo_exists" qtc_QFileInfo_exists :: Ptr (TQFileInfo a) -> IO CBool
instance QfileName (QFileInfo a) (()) where
fileName x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_fileName cobj_x0
foreign import ccall "qtc_QFileInfo_fileName" qtc_QFileInfo_fileName :: Ptr (TQFileInfo a) -> IO (Ptr (TQString ()))
instance QfilePath (QFileInfo a) (()) where
filePath x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_filePath cobj_x0
foreign import ccall "qtc_QFileInfo_filePath" qtc_QFileInfo_filePath :: Ptr (TQFileInfo a) -> IO (Ptr (TQString ()))
instance Qgroup (QFileInfo a) (()) (IO (String)) where
group x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_group cobj_x0
foreign import ccall "qtc_QFileInfo_group" qtc_QFileInfo_group :: Ptr (TQFileInfo a) -> IO (Ptr (TQString ()))
groupId :: QFileInfo a -> (()) -> IO (Int)
groupId x0 ()
= withUnsignedIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_groupId cobj_x0
foreign import ccall "qtc_QFileInfo_groupId" qtc_QFileInfo_groupId :: Ptr (TQFileInfo a) -> IO CUInt
instance QisAbsolute (QFileInfo a) (()) where
isAbsolute x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_isAbsolute cobj_x0
foreign import ccall "qtc_QFileInfo_isAbsolute" qtc_QFileInfo_isAbsolute :: Ptr (TQFileInfo a) -> IO CBool
isBundle :: QFileInfo a -> (()) -> IO (Bool)
isBundle x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_isBundle cobj_x0
foreign import ccall "qtc_QFileInfo_isBundle" qtc_QFileInfo_isBundle :: Ptr (TQFileInfo a) -> IO CBool
instance QisDir (QFileInfo a) (()) where
isDir x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_isDir cobj_x0
foreign import ccall "qtc_QFileInfo_isDir" qtc_QFileInfo_isDir :: Ptr (TQFileInfo a) -> IO CBool
instance QisExecutable (QFileInfo a) (()) where
isExecutable x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_isExecutable cobj_x0
foreign import ccall "qtc_QFileInfo_isExecutable" qtc_QFileInfo_isExecutable :: Ptr (TQFileInfo a) -> IO CBool
instance QisFile (QFileInfo a) (()) where
isFile x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_isFile cobj_x0
foreign import ccall "qtc_QFileInfo_isFile" qtc_QFileInfo_isFile :: Ptr (TQFileInfo a) -> IO CBool
instance QisHidden (QFileInfo a) (()) where
isHidden x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_isHidden cobj_x0
foreign import ccall "qtc_QFileInfo_isHidden" qtc_QFileInfo_isHidden :: Ptr (TQFileInfo a) -> IO CBool
instance QisReadable (QFileInfo a) (()) where
isReadable x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_isReadable cobj_x0
foreign import ccall "qtc_QFileInfo_isReadable" qtc_QFileInfo_isReadable :: Ptr (TQFileInfo a) -> IO CBool
instance QisRelative (QFileInfo a) (()) where
isRelative x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_isRelative cobj_x0
foreign import ccall "qtc_QFileInfo_isRelative" qtc_QFileInfo_isRelative :: Ptr (TQFileInfo a) -> IO CBool
instance QisRoot (QFileInfo a) (()) where
isRoot x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_isRoot cobj_x0
foreign import ccall "qtc_QFileInfo_isRoot" qtc_QFileInfo_isRoot :: Ptr (TQFileInfo a) -> IO CBool
instance QisSymLink (QFileInfo a) (()) where
isSymLink x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_isSymLink cobj_x0
foreign import ccall "qtc_QFileInfo_isSymLink" qtc_QFileInfo_isSymLink :: Ptr (TQFileInfo a) -> IO CBool
instance QisWritable (QFileInfo a) (()) where
isWritable x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_isWritable cobj_x0
foreign import ccall "qtc_QFileInfo_isWritable" qtc_QFileInfo_isWritable :: Ptr (TQFileInfo a) -> IO CBool
instance QlastModified (QFileInfo a) (()) where
lastModified x0 ()
= withQDateTimeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_lastModified cobj_x0
foreign import ccall "qtc_QFileInfo_lastModified" qtc_QFileInfo_lastModified :: Ptr (TQFileInfo a) -> IO (Ptr (TQDateTime ()))
instance QlastRead (QFileInfo a) (()) where
lastRead x0 ()
= withQDateTimeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_lastRead cobj_x0
foreign import ccall "qtc_QFileInfo_lastRead" qtc_QFileInfo_lastRead :: Ptr (TQFileInfo a) -> IO (Ptr (TQDateTime ()))
instance QmakeAbsolute (QFileInfo a) (()) where
makeAbsolute x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_makeAbsolute cobj_x0
foreign import ccall "qtc_QFileInfo_makeAbsolute" qtc_QFileInfo_makeAbsolute :: Ptr (TQFileInfo a) -> IO CBool
instance Qowner (QFileInfo a) (()) where
owner x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_owner cobj_x0
foreign import ccall "qtc_QFileInfo_owner" qtc_QFileInfo_owner :: Ptr (TQFileInfo a) -> IO (Ptr (TQString ()))
ownerId :: QFileInfo a -> (()) -> IO (Int)
ownerId x0 ()
= withUnsignedIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_ownerId cobj_x0
foreign import ccall "qtc_QFileInfo_ownerId" qtc_QFileInfo_ownerId :: Ptr (TQFileInfo a) -> IO CUInt
instance Qpath (QFileInfo a) (()) (IO (String)) where
path x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_path cobj_x0
foreign import ccall "qtc_QFileInfo_path" qtc_QFileInfo_path :: Ptr (TQFileInfo a) -> IO (Ptr (TQString ()))
permission :: QFileInfo a -> ((Permissions)) -> IO (Bool)
permission x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_permission cobj_x0 (toCLong $ qFlags_toInt x1)
foreign import ccall "qtc_QFileInfo_permission" qtc_QFileInfo_permission :: Ptr (TQFileInfo a) -> CLong -> IO CBool
instance Qpermissions (QFileInfo a) (()) (IO (Permissions)) where
permissions x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_permissions cobj_x0
foreign import ccall "qtc_QFileInfo_permissions" qtc_QFileInfo_permissions :: Ptr (TQFileInfo a) -> IO CLong
instance QreadLink (QFileInfo a) (()) where
readLink x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_readLink cobj_x0
foreign import ccall "qtc_QFileInfo_readLink" qtc_QFileInfo_readLink :: Ptr (TQFileInfo a) -> IO (Ptr (TQString ()))
instance Qrefresh (QFileInfo a) (()) where
refresh x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_refresh cobj_x0
foreign import ccall "qtc_QFileInfo_refresh" qtc_QFileInfo_refresh :: Ptr (TQFileInfo a) -> IO ()
setCaching :: QFileInfo a -> ((Bool)) -> IO ()
setCaching x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_setCaching cobj_x0 (toCBool x1)
foreign import ccall "qtc_QFileInfo_setCaching" qtc_QFileInfo_setCaching :: Ptr (TQFileInfo a) -> CBool -> IO ()
instance QsetFile (QFileInfo a) ((QDir t1, String)) where
setFile x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QFileInfo_setFile2 cobj_x0 cobj_x1 cstr_x2
foreign import ccall "qtc_QFileInfo_setFile2" qtc_QFileInfo_setFile2 :: Ptr (TQFileInfo a) -> Ptr (TQDir t1) -> CWString -> IO ()
instance QsetFile (QFileInfo a) ((QFile t1)) where
setFile x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QFileInfo_setFile1 cobj_x0 cobj_x1
foreign import ccall "qtc_QFileInfo_setFile1" qtc_QFileInfo_setFile1 :: Ptr (TQFileInfo a) -> Ptr (TQFile t1) -> IO ()
instance QsetFile (QFileInfo a) ((String)) where
setFile x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QFileInfo_setFile cobj_x0 cstr_x1
foreign import ccall "qtc_QFileInfo_setFile" qtc_QFileInfo_setFile :: Ptr (TQFileInfo a) -> CWString -> IO ()
instance Qqsize (QFileInfo a) (()) (IO (Int)) where
qsize x0 ()
= withLongLongResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_size cobj_x0
foreign import ccall "qtc_QFileInfo_size" qtc_QFileInfo_size :: Ptr (TQFileInfo a) -> IO CLLong
instance Qsuffix (QFileInfo a) (()) where
suffix x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_suffix cobj_x0
foreign import ccall "qtc_QFileInfo_suffix" qtc_QFileInfo_suffix :: Ptr (TQFileInfo a) -> IO (Ptr (TQString ()))
instance QsymLinkTarget (QFileInfo a) (()) where
symLinkTarget x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_symLinkTarget cobj_x0
foreign import ccall "qtc_QFileInfo_symLinkTarget" qtc_QFileInfo_symLinkTarget :: Ptr (TQFileInfo a) -> IO (Ptr (TQString ()))
qFileInfo_delete :: QFileInfo a -> IO ()
qFileInfo_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QFileInfo_delete cobj_x0
foreign import ccall "qtc_QFileInfo_delete" qtc_QFileInfo_delete :: Ptr (TQFileInfo a) -> IO ()
|
keera-studios/hsQt
|
Qtc/Core/QFileInfo.hs
|
Haskell
|
bsd-2-clause
| 15,873
|
module Main (main) where
import Paths_eclogues_impl (getDataFileName)
import Language.Haskell.HLint (hlint)
import System.Exit (exitFailure, exitSuccess)
paths :: [String]
paths =
[ "app"
, "test"
]
arguments :: IO [String]
arguments = go <$> getDataFileName "HLint.hints"
where
go p = ("--hint=" ++ p) : paths
main :: IO ()
main = do
hints <- hlint =<< arguments
if null hints then exitSuccess else exitFailure
|
futufeld/eclogues
|
eclogues-impl/test/HLint.hs
|
Haskell
|
bsd-3-clause
| 442
|
module Database.Riak (
M.RiakException(..),
M.VClock(..),
M.BucketName(..),
M.Key(..),
M.ClientId(..),
M.Quorum(..),
B.Riak,
B.Basic(..),
B.Pong(..),
B.ping,
B.getClientId,
B.setClientId,
B.getServerInfo,
B.get,
B.put,
B.delete,
B.listBuckets,
B.listKeys,
B.getBucket,
B.setBucket,
B.mapReduce,
B.indexQuery,
B.searchQuery,
B.runRiak,
numFound,
maxScore,
documents,
start,
sort,
rows,
query,
presort,
operation,
fieldsLimit,
searchFilter,
df,
returnHead,
returnBody,
ifNotModified,
ifNoneMatch,
response,
phase,
request,
buckets,
tag,
rangeMin,
rangeMax,
qtype,
serverVersion,
node,
unchanged,
notFoundOk,
ifModified,
onlyHead,
deletedVClock,
basicQuorum,
errorMessage,
errorCode,
rw,
vTag,
userMeta,
links,
lastModUsecs,
lastMod,
indexes,
deleted,
contentEncoding,
charset,
nVal,
allowMult,
r,
pr,
keys,
contentType,
done,
value,
w,
pw,
dw,
vClock,
key,
content,
indexValue,
bucket,
clientId,
props,
L.HasR,
L.HasPR,
L.HasKeys,
L.HasContentType,
L.HasDone,
L.HasValue,
L.HasW,
L.HasPW,
L.HasDW,
L.HasVClock,
L.HasKey,
L.HasContent,
L.HasIndex,
L.HasBucket,
L.HasClientId,
L.HasProps,
BucketProps,
Content,
DeleteRequest,
ErrorResponse,
GetBucketRequest,
GetBucketResponse,
GetClientIDResponse,
GetRequest,
GetResponse,
GetServerInfoResponse,
IndexRequest,
IndexQueryType,
IndexResponse,
Link,
ListBucketsResponse,
ListKeysRequest,
ListKeysResponse,
MapReduceRequest,
MapReduceResponse,
Pair,
PutRequest,
PutResponse,
SearchDocument,
SearchQueryRequest,
SearchQueryResponse,
SetBucketRequest,
SetClientIDRequest,
module Database.Riak.Connection
) where
import qualified Control.Lens as Lens
import Data.ByteString.Lazy (ByteString)
import Data.Sequence (Seq)
import Data.Word
import qualified Database.Riak.Basic as B
import Database.Riak.Connection
import qualified Database.Riak.Messages as M
import qualified Database.Riak.Lens as L
import Database.Riak.Protocol.BucketProps (BucketProps)
import Database.Riak.Protocol.Content (Content)
import Database.Riak.Protocol.DeleteRequest (DeleteRequest)
import Database.Riak.Protocol.ErrorResponse (ErrorResponse)
import Database.Riak.Protocol.GetBucketRequest (GetBucketRequest)
import Database.Riak.Protocol.GetBucketResponse (GetBucketResponse)
import Database.Riak.Protocol.GetClientIDResponse (GetClientIDResponse)
import Database.Riak.Protocol.GetRequest (GetRequest)
import Database.Riak.Protocol.GetResponse (GetResponse)
import Database.Riak.Protocol.GetServerInfoResponse (GetServerInfoResponse)
import Database.Riak.Protocol.IndexRequest (IndexRequest)
import Database.Riak.Protocol.IndexRequest.IndexQueryType (IndexQueryType)
import Database.Riak.Protocol.IndexResponse (IndexResponse)
import Database.Riak.Protocol.Link (Link)
import Database.Riak.Protocol.ListBucketsResponse (ListBucketsResponse)
import Database.Riak.Protocol.ListKeysRequest (ListKeysRequest)
import Database.Riak.Protocol.ListKeysResponse (ListKeysResponse)
import Database.Riak.Protocol.MapReduceRequest (MapReduceRequest)
import Database.Riak.Protocol.MapReduceResponse (MapReduceResponse)
import Database.Riak.Protocol.Pair (Pair)
import Database.Riak.Protocol.PutRequest (PutRequest)
import Database.Riak.Protocol.PutResponse (PutResponse)
import Database.Riak.Protocol.SearchDocument (SearchDocument)
import Database.Riak.Protocol.SearchQueryRequest (SearchQueryRequest)
import Database.Riak.Protocol.SearchQueryResponse (SearchQueryResponse)
import Database.Riak.Protocol.SetBucketRequest (SetBucketRequest)
import Database.Riak.Protocol.SetClientIDRequest (SetClientIDRequest)
numFound :: Lens.Simple Lens.Lens SearchQueryResponse (Maybe Word32)
numFound = L.numFound
maxScore :: Lens.Simple Lens.Lens SearchQueryResponse (Maybe Float)
maxScore = L.maxScore
documents :: Lens.Simple Lens.Lens SearchQueryResponse (Seq SearchDocument)
documents = L.documents
start :: Lens.Simple Lens.Lens SearchQueryRequest (Maybe Word32)
start = L.start
sort :: Lens.Simple Lens.Lens SearchQueryRequest (Maybe ByteString)
sort = L.sort
rows :: Lens.Simple Lens.Lens SearchQueryRequest (Maybe Word32)
rows = L.rows
query :: Lens.Simple Lens.Lens SearchQueryRequest ByteString
query = L.searchQuery
presort :: Lens.Simple Lens.Lens SearchQueryRequest (Maybe ByteString)
presort = L.presort
operation :: Lens.Simple Lens.Lens SearchQueryRequest (Maybe ByteString)
operation = L.operation
fieldsLimit :: Lens.Simple Lens.Lens SearchQueryRequest (Seq ByteString)
fieldsLimit = L.fieldsLimit
searchFilter :: Lens.Simple Lens.Lens SearchQueryRequest (Maybe ByteString)
searchFilter = L.searchFilter
df :: Lens.Simple Lens.Lens SearchQueryRequest (Maybe ByteString)
df = L.df
returnHead :: Lens.Simple Lens.Lens PutRequest (Maybe Bool)
returnHead = L.returnHead
returnBody :: Lens.Simple Lens.Lens PutRequest (Maybe Bool)
returnBody = L.returnBody
ifNotModified :: Lens.Simple Lens.Lens PutRequest (Maybe Bool)
ifNotModified = L.ifNotModified
ifNoneMatch :: Lens.Simple Lens.Lens PutRequest (Maybe Bool)
ifNoneMatch = L.ifNoneMatch
response :: Lens.Simple Lens.Lens MapReduceResponse (Maybe ByteString)
response = L.response
phase :: Lens.Simple Lens.Lens MapReduceResponse (Maybe Word32)
phase = L.phase
request :: Lens.Simple Lens.Lens MapReduceRequest ByteString
request = L.request
buckets :: Lens.Simple Lens.Lens ListBucketsResponse (Seq ByteString)
buckets = L.buckets
tag :: Lens.Simple Lens.Lens Link (Maybe ByteString)
tag = L.tag
rangeMin :: Lens.Simple Lens.Lens IndexRequest (Maybe ByteString)
rangeMin = L.rangeMin
rangeMax :: Lens.Simple Lens.Lens IndexRequest (Maybe ByteString)
rangeMax = L.rangeMax
qtype :: Lens.Simple Lens.Lens IndexRequest IndexQueryType
qtype = L.qtype
serverVersion :: Lens.Simple Lens.Lens GetServerInfoResponse (Maybe ByteString)
serverVersion = L.serverVersion
node :: Lens.Simple Lens.Lens GetServerInfoResponse (Maybe ByteString)
node = L.node
unchanged :: Lens.Simple Lens.Lens GetResponse (Maybe Bool)
unchanged = L.unchanged
notFoundOk :: Lens.Simple Lens.Lens GetRequest (Maybe Bool)
notFoundOk = L.notfoundOk
ifModified :: Lens.Simple Lens.Lens GetRequest (Maybe ByteString)
ifModified = L.ifModified
onlyHead :: Lens.Simple Lens.Lens GetRequest (Maybe Bool)
onlyHead = L.onlyHead
deletedVClock :: Lens.Simple Lens.Lens GetRequest (Maybe Bool)
deletedVClock = L.deletedVClock
basicQuorum :: Lens.Simple Lens.Lens GetRequest (Maybe Bool)
basicQuorum = L.basicQuorum
errorMessage :: Lens.Simple Lens.Lens ErrorResponse ByteString
errorMessage = L.errmsg
errorCode :: Lens.Simple Lens.Lens ErrorResponse Word32
errorCode = L.errcode
rw :: Lens.Simple Lens.Lens DeleteRequest (Maybe Word32)
rw = L.rw
vTag :: Lens.Simple Lens.Lens Content (Maybe ByteString)
vTag = L.vtag
userMeta :: Lens.Simple Lens.Lens Content (Seq Pair)
userMeta = L.usermeta
links :: Lens.Simple Lens.Lens Content (Seq Link)
links = L.links
lastModUsecs :: Lens.Simple Lens.Lens Content (Maybe Word32)
lastModUsecs = L.lastModUsecs
lastMod :: Lens.Simple Lens.Lens Content (Maybe Word32)
lastMod = L.lastMod
indexes :: Lens.Simple Lens.Lens Content (Seq Pair)
indexes = L.indexes
deleted :: Lens.Simple Lens.Lens Content (Maybe Bool)
deleted = L.deleted
contentEncoding :: Lens.Simple Lens.Lens Content (Maybe ByteString)
contentEncoding = L.contentEncoding
charset :: Lens.Simple Lens.Lens Content (Maybe ByteString)
charset = L.charset
nVal :: Lens.Simple Lens.Lens BucketProps (Maybe Word32)
nVal = L.nVal
allowMult :: Lens.Simple Lens.Lens BucketProps (Maybe Bool)
allowMult = L.allowMult
r :: L.HasR a => Lens.Simple Lens.Lens a (Maybe M.Quorum)
r = L.r
pr :: L.HasPR a => Lens.Simple Lens.Lens a (Maybe M.Quorum)
pr = L.pr
keys :: L.HasKeys a => Lens.Simple Lens.Lens a (Seq ByteString)
keys = L.keys
contentType :: L.HasContentType a => Lens.Simple Lens.Lens a (L.ContentTypeValue a)
contentType = L.contentType
done :: L.HasDone a => Lens.Simple Lens.Lens a (Maybe Bool)
done = L.done
value :: L.HasValue a => Lens.Simple Lens.Lens a (L.Value a)
value = L.value
w :: L.HasW a => Lens.Simple Lens.Lens a (Maybe M.Quorum)
w = L.w
pw :: L.HasPW a => Lens.Simple Lens.Lens a (Maybe M.Quorum)
pw = L.pw
dw :: L.HasDW a => Lens.Simple Lens.Lens a (Maybe M.Quorum)
dw = L.dw
vClock :: L.HasVClock a => Lens.Simple Lens.Lens a (Maybe ByteString)
vClock = L.vclock
key :: L.HasKey a => Lens.Simple Lens.Lens a (L.KeyValue a)
key = L.key
content :: L.HasContent a => Lens.Simple Lens.Lens a (L.ContentValue a)
content = L.content
indexValue :: L.HasIndex a => Lens.Simple Lens.Lens a ByteString
indexValue = L.index
bucket :: L.HasBucket a => Lens.Simple Lens.Lens a (L.BucketValue a)
bucket = L.bucket
clientId :: L.HasClientId a => Lens.Simple Lens.Lens a ByteString
clientId = L.clientId
props :: L.HasProps a => Lens.Simple Lens.Lens a BucketProps
props = L.props
|
iand675/hiker
|
Database/Riak.hs
|
Haskell
|
bsd-3-clause
| 9,059
|
{-# LANGUAGE TypeFamilies #-}
-- | Number representations that are not part of the grammar.
--
-- To convert these types to 'Penny.Decimal.Decimal' and the like,
-- functions are available in "Penny.Copper.Decopperize".
module Penny.Rep where
import qualified Control.Lens as Lens
import qualified Control.Lens.Extras as Lens (is)
import Data.Coerce (coerce)
import Data.Monoid ((<>))
import Data.Sequence (Seq, (<|))
import qualified Data.Sequence as Seq
import qualified Data.Sequence.NonEmpty as NE
import Penny.Copper.Types
import Penny.Copper.Terminalizers
import Penny.Polar
-- | Qty representations with a comma radix that may be either nil
-- or brim. Stored along with the side if the number is non-nil.
type RepRadCom = Moderated (NilRadCom Char ()) (BrimRadCom Char ())
-- | Qty representations with a period radix that may be either nil
-- or brim. Stored along with the side if the number is non-nil.
type RepRadPer = Moderated (NilRadPer Char ()) (BrimRadPer Char ())
-- | Qty representations that may be neutral or non-neutral and that
-- have a period or comma radix. Stored along with the side if the
-- number is non-nil.
type RepAnyRadix = Either RepRadCom RepRadPer
oppositeRepAnyRadix :: RepAnyRadix -> RepAnyRadix
oppositeRepAnyRadix
= Lens.over Lens._Left oppositeModerated
. Lens.over Lens._Right oppositeModerated
-- | True if the 'RepAnyRadix' is zero.
repAnyRadixIsZero :: RepAnyRadix -> Bool
repAnyRadixIsZero rar
= Lens.is (Lens._Left . _Moderate) rar
|| Lens.is (Lens._Right . _Moderate) rar
-- | A non-neutral representation that does not include a side.
type BrimAnyRadix = Either (BrimRadCom Char ()) (BrimRadPer Char ())
-- | A neutral representation of any radix.
type NilAnyRadix = Either (NilRadCom Char ()) (NilRadPer Char ())
-- | Number representation that may be neutral or non-neutral, with
-- either a period or comma radix. Does not have a polarity.
type NilOrBrimAnyRadix
= Either (NilOrBrimRadCom Char ()) (NilOrBrimRadPer Char ())
c'RepAnyRadix'BrimAnyRadix
:: Pole
-- ^ Use this side
-> BrimAnyRadix
-> RepAnyRadix
c'RepAnyRadix'BrimAnyRadix pole b = case b of
Left brc -> Left . Extreme $ Polarized brc pole
Right brp -> Right . Extreme $ Polarized brp pole
t'NilOrBrimAnyRadix
:: NilOrBrimAnyRadix
-> Seq Char
t'NilOrBrimAnyRadix
= NE.nonEmptySeqToSeq
. fmap fst
. either t'NilOrBrimRadCom t'NilOrBrimRadPer
splitNilOrBrimAnyRadix
:: NilOrBrimAnyRadix
-> Either NilAnyRadix BrimAnyRadix
splitNilOrBrimAnyRadix x = case x of
Left nobCom -> case nobCom of
NilOrBrimRadCom'NilRadCom nilCom -> Left (Left nilCom)
NilOrBrimRadCom'BrimRadCom brimCom -> Right (Left brimCom)
Right nobPer -> case nobPer of
NilOrBrimRadPer'NilRadPer nilPer -> Left (Right nilPer)
NilOrBrimRadPer'BrimRadPer brimPer -> Right (Right brimPer)
groupers'DigitGroupRadCom'Star
:: DigitGroupRadCom'Star t a
-> Seq (GrpRadCom t a)
groupers'DigitGroupRadCom'Star
= fmap _r'DigitGroupRadCom'0'GrpRadCom . coerce
groupers'DigitGroupRadPer'Star
:: DigitGroupRadPer'Star t a
-> Seq (GrpRadPer t a)
groupers'DigitGroupRadPer'Star
= fmap _r'DigitGroupRadPer'0'GrpRadPer . coerce
groupers'BG7RadCom
:: BG7RadCom t a
-> Seq (GrpRadCom t a)
groupers'BG7RadCom (BG7ZeroesRadCom _ _ b8)
= groupers'BG8RadCom b8
groupers'BG7RadCom (BG7NovemRadCom _ _ digs)
= groupers'DigitGroupRadCom'Star digs
groupers'BG8RadCom
:: BG8RadCom t a
-> Seq (GrpRadCom t a)
groupers'BG8RadCom (BG8NovemRadCom _ _ digs)
= groupers'DigitGroupRadCom'Star digs
groupers'BG8RadCom (BG8GroupRadCom grpr b7)
= grpr <| groupers'BG7RadCom b7
groupers'BG7RadPer
:: BG7RadPer t a
-> Seq (GrpRadPer t a)
groupers'BG7RadPer (BG7ZeroesRadPer _ _ b8)
= groupers'BG8RadPer b8
groupers'BG7RadPer (BG7NovemRadPer _ _ digs)
= groupers'DigitGroupRadPer'Star digs
groupers'BG8RadPer
:: BG8RadPer t a
-> Seq (GrpRadPer t a)
groupers'BG8RadPer (BG8NovemRadPer _ _ digs)
= groupers'DigitGroupRadPer'Star digs
groupers'BG8RadPer (BG8GroupRadPer grpr b7)
= grpr <| groupers'BG7RadPer b7
groupers'BG6RadCom
:: BG6RadCom t a
-> Seq (GrpRadCom t a)
groupers'BG6RadCom (BG6NovemRadCom _ _ g1 _ _ gs)
= g1 <| groupers'DigitGroupRadCom'Star gs
groupers'BG6RadCom (BG6GroupRadCom g1 b7) = g1 <| groupers'BG7RadCom b7
groupers'BG6RadPer
:: BG6RadPer t a
-> Seq (GrpRadPer t a)
groupers'BG6RadPer (BG6NovemRadPer _ _ g1 _ _ gs)
= g1 <| groupers'DigitGroupRadPer'Star gs
groupers'BG6RadPer (BG6GroupRadPer g1 b7) = g1 <| groupers'BG7RadPer b7
groupers'BG5RadCom
:: BG5RadCom t a
-> Seq (GrpRadCom t a)
groupers'BG5RadCom (BG5NovemRadCom _ _ g1 _ _ gs)
= g1 <| groupers'DigitGroupRadCom'Star gs
groupers'BG5RadCom (BG5ZeroRadCom _ _ b6)
= groupers'BG6RadCom b6
groupers'BG5RadPer
:: BG5RadPer t a
-> Seq (GrpRadPer t a)
groupers'BG5RadPer (BG5NovemRadPer _ _ g1 _ _ gs)
= g1 <| groupers'DigitGroupRadPer'Star gs
groupers'BG5RadPer (BG5ZeroRadPer _ _ b6)
= groupers'BG6RadPer b6
groupers'BG4RadCom
:: BG4RadCom t a
-> Seq (GrpRadCom t a)
groupers'BG4RadCom (BG4DigitRadCom _ _ digs)
= groupers'DigitGroupRadCom'Star digs
groupers'BG4RadCom BG4NilRadCom = Seq.empty
groupers'BG4RadPer
:: BG4RadPer t a
-> Seq (GrpRadPer t a)
groupers'BG4RadPer (BG4DigitRadPer _ _ digs)
= groupers'DigitGroupRadPer'Star digs
groupers'BG4RadPer BG4NilRadPer = Seq.empty
groupers'BG3RadCom
:: BG3RadCom t a
-> Seq (GrpRadCom t a)
groupers'BG3RadCom (BG3RadixRadCom _ b4)
= groupers'BG4RadCom b4
groupers'BG3RadCom BG3NilRadCom = Seq.empty
groupers'BG3RadPer
:: BG3RadPer t a
-> Seq (GrpRadPer t a)
groupers'BG3RadPer (BG3RadixRadPer _ b4)
= groupers'BG4RadPer b4
groupers'BG3RadPer BG3NilRadPer = Seq.empty
groupers'BG1RadCom
:: BG1RadCom t a
-> Seq (GrpRadCom t a)
groupers'BG1RadCom (BG1GroupOnLeftRadCom g1 _ _ digs b3)
= g1 <| groupers'DigitGroupRadCom'Star digs <> groupers'BG3RadCom b3
groupers'BG1RadCom (BG1GroupOnRightRadCom _ _ _ g1 _ _ digs)
= g1 <| groupers'DigitGroupRadCom'Star digs
groupers'BG1RadPer
:: BG1RadPer t a
-> Seq (GrpRadPer t a)
groupers'BG1RadPer (BG1GroupOnLeftRadPer g1 _ _ digs b3)
= g1 <| groupers'DigitGroupRadPer'Star digs <> groupers'BG3RadPer b3
groupers'BG1RadPer (BG1GroupOnRightRadPer _ _ _ g1 _ _ digs)
= g1 <| groupers'DigitGroupRadPer'Star digs
groupers'BrimGroupedRadCom
:: BrimGroupedRadCom t a
-> Seq (GrpRadCom t a)
groupers'BrimGroupedRadCom (BGGreaterThanOneRadCom _ _ bg1)
= groupers'BG1RadCom bg1
groupers'BrimGroupedRadCom (BGLessThanOneRadCom _ _ b5)
= groupers'BG5RadCom b5
groupers'BrimGroupedRadPer
:: BrimGroupedRadPer t a
-> Seq (GrpRadPer t a)
groupers'BrimGroupedRadPer (BGGreaterThanOneRadPer _ _ bg1)
= groupers'BG1RadPer bg1
groupers'BrimGroupedRadPer (BGLessThanOneRadPer _ _ b5)
= groupers'BG5RadPer b5
groupers'ZeroGroupRadCom
:: ZeroGroupRadCom t a
-> Seq (GrpRadCom t a)
groupers'ZeroGroupRadCom (ZeroGroupRadCom g _ _) = Seq.singleton g
groupers'ZeroGroupRadPer
:: ZeroGroupRadPer t a
-> Seq (GrpRadPer t a)
groupers'ZeroGroupRadPer (ZeroGroupRadPer g _ _) = Seq.singleton g
groupers'NilGroupedRadCom
:: NilGroupedRadCom t a
-> Seq (GrpRadCom t a)
groupers'NilGroupedRadCom
(NilGroupedRadCom _ _ _ _ (ZeroGroupRadCom'Plus (NE.NonEmptySeq g1 gs)))
= addGroup g1 (foldr addGroup Seq.empty gs)
where
addGroup g acc = groupers'ZeroGroupRadCom g <> acc
groupers'NilGroupedRadPer
:: NilGroupedRadPer t a
-> Seq (GrpRadPer t a)
groupers'NilGroupedRadPer
(NilGroupedRadPer _ _ _ _ (ZeroGroupRadPer'Plus (NE.NonEmptySeq g1 gs)))
= addGroup g1 (foldr addGroup Seq.empty gs)
where
addGroup g acc = groupers'ZeroGroupRadPer g <> acc
groupers'NilRadCom
:: NilRadCom t a
-> Seq (GrpRadCom t a)
groupers'NilRadCom (NilRadCom'NilUngroupedRadCom _)
= Seq.empty
groupers'NilRadCom (NilRadCom'NilGroupedRadCom x)
= groupers'NilGroupedRadCom x
groupers'NilRadPer
:: NilRadPer t a
-> Seq (GrpRadPer t a)
groupers'NilRadPer (NilRadPer'NilUngroupedRadPer _)
= Seq.empty
groupers'NilRadPer (NilRadPer'NilGroupedRadPer x)
= groupers'NilGroupedRadPer x
groupers'BrimRadCom
:: BrimRadCom t a
-> Seq (GrpRadCom t a)
groupers'BrimRadCom (BrimRadCom'BrimUngroupedRadCom _)
= Seq.empty
groupers'BrimRadCom (BrimRadCom'BrimGroupedRadCom b)
= groupers'BrimGroupedRadCom b
groupers'BrimRadPer
:: BrimRadPer t a
-> Seq (GrpRadPer t a)
groupers'BrimRadPer (BrimRadPer'BrimUngroupedRadPer _)
= Seq.empty
groupers'BrimRadPer (BrimRadPer'BrimGroupedRadPer b)
= groupers'BrimGroupedRadPer b
groupers'RepRadCom
:: RepRadCom
-> Seq (GrpRadCom Char ())
groupers'RepRadCom x = case x of
Moderate n -> groupers'NilRadCom n
Extreme (Polarized o _) -> groupers'BrimRadCom o
groupers'RepRadPer
:: RepRadPer
-> Seq (GrpRadPer Char ())
groupers'RepRadPer x = case x of
Moderate n -> groupers'NilRadPer n
Extreme (Polarized o _) -> groupers'BrimRadPer o
groupers'RepAnyRadix
:: RepAnyRadix
-> Either (Seq (GrpRadCom Char ())) (Seq (GrpRadPer Char ()))
groupers'RepAnyRadix = either (Left . groupers'RepRadCom)
(Right . groupers'RepRadPer)
groupers'BrimAnyRadix
:: BrimAnyRadix
-> Either (Seq (GrpRadCom Char ())) (Seq (GrpRadPer Char ()))
groupers'BrimAnyRadix = either (Left . groupers'BrimRadCom)
(Right . groupers'BrimRadPer)
-- | Removes the 'Side' from a 'RepAnyRadix'.
c'NilOrBrimAnyRadix'RepAnyRadix
:: RepAnyRadix
-> NilOrBrimAnyRadix
c'NilOrBrimAnyRadix'RepAnyRadix ei = case ei of
Left rc -> Left $ case rc of
Moderate n -> NilOrBrimRadCom'NilRadCom n
Extreme (Polarized c _) -> NilOrBrimRadCom'BrimRadCom c
Right rp -> Right $ case rp of
Moderate n -> NilOrBrimRadPer'NilRadPer n
Extreme (Polarized c _) -> NilOrBrimRadPer'BrimRadPer c
-- | Removes the 'Side' from a 'RepAnyRadix' and returns either Nil
-- or a Brim with the side.
splitRepAnyRadix
:: RepAnyRadix
-> Either NilAnyRadix (BrimAnyRadix, Pole)
splitRepAnyRadix ei = case ei of
Left rc -> case rc of
Moderate n -> Left . Left $ n
Extreme (Polarized brim pole) -> Right (Left brim, pole)
Right rp -> case rp of
Moderate n -> Left . Right $ n
Extreme (Polarized brim pole) -> Right (Right brim, pole)
c'NilOrBrimAnyRadix'BrimAnyRadix
:: BrimAnyRadix
-> NilOrBrimAnyRadix
c'NilOrBrimAnyRadix'BrimAnyRadix brim = case brim of
Left brc -> Left (NilOrBrimRadCom'BrimRadCom brc)
Right brp -> Right (NilOrBrimRadPer'BrimRadPer brp)
c'NilOrBrimAnyRadix'NilAnyRadix
:: NilAnyRadix
-> NilOrBrimAnyRadix
c'NilOrBrimAnyRadix'NilAnyRadix nil = case nil of
Left nrc -> Left (NilOrBrimRadCom'NilRadCom nrc)
Right nrp -> Right (NilOrBrimRadPer'NilRadPer nrp)
-- # Poles
pole'RepRadCom :: RepRadCom -> Maybe Pole
pole'RepRadCom = pole'Moderated
pole'RepRadPer :: RepRadPer -> Maybe Pole
pole'RepRadPer = pole'Moderated
pole'RepAnyRadix :: RepAnyRadix -> Maybe Pole
pole'RepAnyRadix = either pole'RepRadCom pole'RepRadPer
|
massysett/penny
|
penny/lib/Penny/Rep.hs
|
Haskell
|
bsd-3-clause
| 10,925
|
test_disassembler :: IO ()
test_disassembler =
let table = [
(Mov (Register 12) (Register 14), "\xce\x2c"),
(Cli, "\xf8\x94"),
(Sei, "\x78\x94"),
(Clc, "\x88\x94"),
(Clh, "\xd8\x94"),
(Cln, "\xa8\x94"),
(Cls, "\xc8\x94"),
(Clv, "\xb8\x94"),
(Clz, "\x98\x94"),
(Clt, "\xe8\x94"),
(Sec, "\x08\x94"),
(Seh, "\x58\x94"),
(Sen, "\x28\x94"),
(Ses, "\x48\x94"),
(Sev, "\x38\x94"),
(Sez, "\x18\x94"),
(Set, "\x68\x94"),
(Jmp 50, "\x0c\x94\x19\x00"),
(Ijmp, "\x09\x94"),
(Rjmp 50, "\x19\xc0"),
(Add 10 15, "\xaf\x0c"),
(Adc 10 15, "\xaf\x1c"),
(Sub 10 15, "\x05\x18"),
(Sbc 10 15, "\x05\x08"),
(Andi 10 5, "\xa5\x70"),
(Ldi 10 5, "\xa5\xe0"),
(Cpi 10 5, "\xa5\x30"),
(Ori 10 5, "\xa5\x60"),
(Subi 10 5, "\xa0\x50"),
(Sbci 10 5, "\xa5\x40"),
(In 15 5, "\xf5\xb0"),
(Out 5 15, "\xf5\xb8"),
(Sbi 15 3, "\x03\x9a"),
(Cbi 15 3, "\x03\x98"),
(Sbic 15 3, "\x03\x99"),
(Sbis 15 3, "\x03\x9b"),
(Sbrc 15 3, "\xf3\xfc"),
(Sbrs 15 3, "\xf3\xfe"),
(Cpse 15 20, "\xf4\x12"),
(Bld 15 3, "\x53\xf8"),
(Bst 15 3, "\x53\xfa"),
(Adiw (Reg16 RX), "\xd2\x96"),
(Sbiw (mkReg16 24), "\x06\x97"),
(Movw (mkReg16 16), "\x80\x01"),
(Push 15, "\xff\x92"),
(Pop 15, "\xff\x90"),
(Brcc 50, "\xc8\xf4"),
(Brcs 50, "\xc8\xf0"),
(Brtc 50, "\xce\xf4"),
(Brts 50, "\xce\xf0"),
(Breq 50, "\xc9\xf0"),
(Brne 50, "\xc9\xf4"),
(Brlt 50, "\xcc\xf0"),
(Brge 50, "\xcc\xf4"),
(Brpl 50, "\xca\xf4"),
(Brmi 50, "\xca\xf0"),
(Cp 15 20, "\xf4\x16"),
(Cpc 15 20, "\xf4\x06"),
(Inc 15, "\xf3\x94"),
(Dec 15, "\xfa\x94"),
(Ldxp 15, "\xfd\x90"),
(Ldxm 15, "\xfc\x90"),
(Ldyp 15, "\xf9\x90"),
(Ldym 15, "\xf8\x80"),
(Ldzp 15, "\xf1\x90"),
(Ldzm 15, "\xf0\x80"),
(Lds 15 20, "\xf0\x90\x14\x00"),
(Lddx 15 3, "\xfb\x80"),
(Lddy 15 3, "\xfb\x80"),
(Stxp 15, "\xfd\x92"),
(Stxm 15, "\xfc\x92"),
(Styp 15, "\xf9\x92"),
(Sts 20 15, "\xf0\x92\x14\x00"),
(Stdz 41 15, "\x01\xa7"),
(Lpmzp 15, "\x05\x90"),
(Call 1234, "\x0e\x94\x69\x02"),
(Rcall 50, "\x0e\x94\x19\x00"),
(Icall, "\x09\x95"),
(Ret, "\x08\x95"),
(Com 15, "\xf0\x94"),
(Neg 15, "\xf1\x94"),
(And 15 16, "\xf0\x22"),
(Eor 15 16, "\xf0\x26"),
(Or 15 16, "\xf0\x2a"),
(Ror 15, "\xf7\x94"),
(Lsr 15, "\xf6\x94"),
(Lsl 15, "\x0f\x0c"),
(Swap 15, "\xf2\x94"),
(Mul 8 16, "\x80\x9e"),
(Break, "\x98\x95"),
(Reti, "\x18\x95"),
(Nop, "\x00\x00")
)
main :: IO ()
main = putStrLn "Test suite not yet implemented"
|
MichaelBurge/stockfighter-jailbreak
|
test/Spec.hs
|
Haskell
|
bsd-3-clause
| 3,047
|
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DisambiguateRecordFields, NamedFieldPuns #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE CPP #-}
-- | This module contains types and functions that are mostly
-- intended for the test suite, and should be considered internal
-- for all other purposes
module Text.Xml.Tiny.Internal
(
-- * XML Nodes
Node(..), Attribute(..)
-- * ParseDetails
, ParseDetails(..), AttributeParseDetails(..)
-- * Slices
, Slice(..)
, fromOpen, fromOpenClose, fromIndexPtr
, empty
, start, end
, take, drop, null
, vector, render, toList
-- * Errors
, SrcLoc(..), Error(..), ErrorType(..)
) where
import Control.Exception
import Data.ByteString.Char8 (ByteString)
import Data.ByteString.Internal (ByteString(..))
import Data.List (genericTake)
import Data.Vector.Storable (Vector, (!))
import qualified Data.Vector.Storable as V
import Data.Word
import GHC.Stack hiding (SrcLoc)
import Foreign.ForeignPtr (ForeignPtr)
import Foreign
import Prelude hiding (length, null, take, drop)
import Text.Printf
import Config
-- A subset of a vector defined by an offset and length
data Slice =
Slice { offset, length :: !Int32 }
deriving (Eq,Ord,Show)
sInt :: Int
sInt = sizeOf(0::Int32)
instance Storable Slice where
sizeOf _ = sInt * 2
alignment _ = alignment (0 :: Int64)
peek p = Slice <$> peekByteOff p 0 <*> peekByteOff p sInt
poke p Slice{..} = pokeByteOff p 0 offset >> pokeByteOff p sInt length
{-# INLINE empty #-}
empty :: Slice
empty = Slice 0 0
fromOpen:: Config => Integral a => a -> Slice
fromOpen o = Slice (fromIntegral o) 0
{-# INLINE fromOpenClose #-}
fromOpenClose :: Config => (Integral a1, Integral a) => a -> a1 -> Slice
fromOpenClose (fromIntegral->open) (fromIntegral->close) = Slice open (close-open)
{-# INLINE null #-}
null :: Config => Slice -> Bool
null (Slice _ l) = l == 0
{-# INLINE take #-}
take :: Config => Integral a => a -> Slice -> Slice
take !(fromIntegral -> i) (Slice o l) = assert (l>=i) $ Slice o i
{-# INLINE drop #-}
drop :: Config => Integral t => t -> Slice -> Slice
drop !(fromIntegral -> i) (Slice o l) = assert (l>=i || error(printf "drop %d (Slice %d %d)" i o l)) $ Slice (o+i) (l-i)
-- | Inclusive
start :: Config => Slice -> Int32
start = offset
-- | Non inclusive
end :: Config => Slice -> Int32
end (Slice o l) = o + l
-- | Returns a list of indexes
toList :: Config => Slice -> [Int]
toList (Slice o l) = genericTake l [ fromIntegral o ..]
{-# INLINE fromIndexPtr #-}
-- | Apply a slice to a foreign ptr of word characters and wrap as a bytestring
fromIndexPtr :: Config => Slice -> ForeignPtr Word8 -> ByteString
fromIndexPtr (Slice o l) fptr = PS fptr (fromIntegral o) (fromIntegral l)
-- | Apply a slice to a bytestring
render :: Config => Slice -> ByteString -> ByteString
render(Slice o l) _ | trace (printf "Render slice %d %d" o l) False = undefined
render(Slice o l) _ | assert (o >= 0 && l >= 0) False = undefined
render(Slice o l) (PS fptr _ _) = PS fptr (fromIntegral o) (fromIntegral l)
-- | Apply a slice to a vector
vector :: Config => Storable a => Slice -> Vector a -> [a]
vector s v = [ v ! i
| i <- toList s
, assert (i < V.length v) True ]
-- * XML Nodes
-- | A parsed XML node
data Node =
Node{ attributesV :: !(Vector AttributeParseDetails) -- ^ All the attributes in the document
, nodesV :: !(Vector ParseDetails) -- ^ All the nodes in the document
, source :: !ByteString -- ^ The document bytes
, slices :: !ParseDetails -- ^ Details for this node
}
-- | A parsed XML attribute
data Attribute = Attribute { attributeName, attributeValue :: !ByteString } deriving (Eq, Show)
data ParseDetails =
ParseDetails
{ name :: {-# UNPACK #-} !Slice -- ^ bytestring slice
, inner :: {-# UNPACK #-} !Slice -- ^ bytestring slice
, outer :: {-# UNPACK #-} !Slice -- ^ bytestring slice
, attributes :: {-# UNPACK #-} !Slice -- ^ ParseDetailsAttribute slice
, nodeContents :: {-# UNPACK #-} !Slice -- ^ ParseDetails slice of children
}
-- | An incompletely defined set of parse details
| ProtoParseDetails { name, attributes :: !Slice, innerStart, outerStart :: !Int32 }
deriving (Show)
-- | Assumes that a name can never be the empty slice
instance Storable ParseDetails where
sizeOf _ = sizeOf empty * 5
alignment _ = alignment(0::Int)
poke !q (ParseDetails a b c d e) = let p = castPtr q in pokeElemOff p 0 a >> pokeElemOff p 1 b >> pokeElemOff p 2 c >> pokeElemOff p 3 d >> pokeElemOff p 4 e
poke !q (ProtoParseDetails (Slice no nl) (Slice ao al) i o) = do
let !p = castPtr q
pokeElemOff p 0 no
pokeElemOff p 1 (0::Int32)
pokeElemOff p 2 nl
pokeElemOff p 3 ao
pokeElemOff p 4 al
pokeElemOff p 5 i
pokeElemOff p 6 o
peek q = do
let !p = castPtr q
!header <- peekElemOff p 1
if header == (0::Int32)
then protoNode <$> peekElemOff p 0 <*> peekElemOff p 2 <*> peekElemOff p 3 <*> peekElemOff p 4 <*> peekElemOff p 5 <*> peekElemOff p 6
else let !p = castPtr q in ParseDetails <$> peekElemOff p 0 <*> peekElemOff p 1 <*> peekElemOff p 2 <*> peekElemOff p 3 <*> peekElemOff p 4
where
protoNode no nl ao al = ProtoParseDetails (Slice no nl) (Slice ao al)
data AttributeParseDetails =
AttributeParseDetails
{ nameA :: {-# UNPACK #-} !Slice,
value :: {-# UNPACK #-} !Slice
}
deriving (Eq, Show)
instance Storable AttributeParseDetails where
sizeOf _ = sizeOf empty * 2
alignment _ = alignment (0 :: Int)
peek !q = do
let !p = castPtr q :: Ptr Slice
!a <- peekElemOff p 0
!b <- peekElemOff p 1
return (AttributeParseDetails a b)
poke !q (AttributeParseDetails a b)= do
let !p = castPtr q :: Ptr Slice
pokeElemOff p 0 a
pokeElemOff p 1 b
-- * Error types
newtype SrcLoc = SrcLoc Int deriving Show
data Error = Error ErrorType CallStack
data ErrorType =
UnterminatedComment SrcLoc
| UnterminatedTag String SrcLoc
| ClosingTagMismatch String SrcLoc
| JunkAtTheEnd Slice SrcLoc
| UnexpectedEndOfStream
| BadAttributeForm SrcLoc
| BadTagForm SrcLoc
| UnfinishedComment SrcLoc
| Garbage SrcLoc
| InvalidNullName SrcLoc
deriving Show
#if __GLASGOW_HASKELL__ < 800
prettyCallStack = show
#endif
instance Exception Error
instance Show Error where
show (Error etype cs) = show etype ++ prettyCallStack cs
|
pepeiborra/bytestring-xml
|
src/Text/Xml/Tiny/Internal.hs
|
Haskell
|
bsd-3-clause
| 6,677
|
module FP.Pretty.HTML where
import FP.Prelude
import FP.Pretty.Color
import FP.Pretty.Pretty
htmlFGCode :: Color -> 𝕊 -> 𝕊
htmlFGCode c s = "<span style='color:" ⧺ (htmlColorFrom256 #! c) ⧺ "'>" ⧺ s ⧺ "</span>"
htmlBGCode :: Color -> 𝕊 -> 𝕊
htmlBGCode c s = "<span style='background-color:" ⧺ (htmlColorFrom256 #! c) ⧺ "'>" ⧺ s ⧺ "</span>"
htmlULCode :: 𝕊 -> 𝕊
htmlULCode s = "<u>" ⧺ s ⧺ "</u>"
htmlBDCode :: 𝕊 -> 𝕊
htmlBDCode s = "<b>" ⧺ s ⧺ "</b>"
formatHTML :: Format -> 𝕊 -> 𝕊
formatHTML (FormatFG c) = htmlFGCode c
formatHTML (FormatBG c) = htmlBGCode c
formatHTML FormatUL = htmlULCode
formatHTML FormatBD = htmlBDCode
htmlEscapeChar ∷ ℂ → 𝕊
htmlEscapeChar c
| c == '&' = "&"
| c == '<' = "<"
| c == '>' = ">"
| otherwise = 𝕤 $ single c
htmlEscape ∷ 𝕊 → 𝕊
htmlEscape = concat ∘ map htmlEscapeChar ∘ list
renderChunkHTML ∷ Chunk → 𝕊
renderChunkHTML Newline = "\n"
renderChunkHTML (Text s) = htmlEscape s
renderHTML ∷ PrettyOut → 𝕊
renderHTML (ChunkOut c) = renderChunkHTML c
renderHTML (FormatOut f o) = compose (map formatHTML f) $ renderHTML o
renderHTML NullOut = ""
renderHTML (AppendOut o₁ o₂) = renderHTML o₁ ⧺ renderHTML o₂
prettyHTML ∷ (Pretty a) ⇒ a → 𝕊
prettyHTML = renderHTML ∘ renderDoc ∘ ppFinal ∘ pretty
prettyHTMLStandalone ∷ (Pretty a) ⇒ a → 𝕊
prettyHTMLStandalone x = concat $ intersperse "\n"
[ "<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>"
, "<pre>"
, prettyHTML x
, "</pre>"
]
htmlColorFrom256 :: Color ⇰ 𝕊
htmlColorFrom256 = dict $ map (mapFst color)
[ (000, "#000000")
, (001, "#800000")
, (002, "#008000")
, (003, "#808000")
, (004, "#000080")
, (005, "#800080")
, (006, "#008080")
, (007, "#c0c0c0")
, (008, "#808080")
, (009, "#ff0000")
, (010, "#00ff00")
, (011, "#ffff00")
, (012, "#0000ff")
, (013, "#ff00ff")
, (014, "#00ffff")
, (015, "#ffffff")
, (016, "#000000")
, (017, "#00005f")
, (018, "#000087")
, (019, "#0000af")
, (020, "#0000d7")
, (021, "#0000ff")
, (022, "#005f00")
, (023, "#005f5f")
, (024, "#005f87")
, (025, "#005faf")
, (026, "#005fd7")
, (027, "#005fff")
, (028, "#008700")
, (029, "#00875f")
, (030, "#008787")
, (031, "#0087af")
, (032, "#0087d7")
, (033, "#0087ff")
, (034, "#00af00")
, (035, "#00af5f")
, (036, "#00af87")
, (037, "#00afaf")
, (038, "#00afd7")
, (039, "#00afff")
, (040, "#00d700")
, (041, "#00d75f")
, (042, "#00d787")
, (043, "#00d7af")
, (044, "#00d7d7")
, (045, "#00d7ff")
, (046, "#00ff00")
, (047, "#00ff5f")
, (048, "#00ff87")
, (049, "#00ffaf")
, (050, "#00ffd7")
, (051, "#00ffff")
, (052, "#5f0000")
, (053, "#5f005f")
, (054, "#5f0087")
, (055, "#5f00af")
, (056, "#5f00d7")
, (057, "#5f00ff")
, (058, "#5f5f00")
, (059, "#5f5f5f")
, (060, "#5f5f87")
, (061, "#5f5faf")
, (062, "#5f5fd7")
, (063, "#5f5fff")
, (064, "#5f8700")
, (065, "#5f875f")
, (066, "#5f8787")
, (067, "#5f87af")
, (068, "#5f87d7")
, (069, "#5f87ff")
, (070, "#5faf00")
, (071, "#5faf5f")
, (072, "#5faf87")
, (073, "#5fafaf")
, (074, "#5fafd7")
, (075, "#5fafff")
, (076, "#5fd700")
, (077, "#5fd75f")
, (078, "#5fd787")
, (079, "#5fd7af")
, (080, "#5fd7d7")
, (081, "#5fd7ff")
, (082, "#5fff00")
, (083, "#5fff5f")
, (084, "#5fff87")
, (085, "#5fffaf")
, (086, "#5fffd7")
, (087, "#5fffff")
, (088, "#870000")
, (089, "#87005f")
, (090, "#870087")
, (091, "#8700af")
, (092, "#8700d7")
, (093, "#8700ff")
, (094, "#875f00")
, (095, "#875f5f")
, (096, "#875f87")
, (097, "#875faf")
, (098, "#875fd7")
, (099, "#875fff")
, (100, "#878700")
, (101, "#87875f")
, (102, "#878787")
, (103, "#8787af")
, (104, "#8787d7")
, (105, "#8787ff")
, (106, "#87af00")
, (107, "#87af5f")
, (108, "#87af87")
, (109, "#87afaf")
, (110, "#87afd7")
, (111, "#87afff")
, (112, "#87d700")
, (113, "#87d75f")
, (114, "#87d787")
, (115, "#87d7af")
, (116, "#87d7d7")
, (117, "#87d7ff")
, (118, "#87ff00")
, (119, "#87ff5f")
, (120, "#87ff87")
, (121, "#87ffaf")
, (122, "#87ffd7")
, (123, "#87ffff")
, (124, "#af0000")
, (125, "#af005f")
, (126, "#af0087")
, (127, "#af00af")
, (128, "#af00d7")
, (129, "#af00ff")
, (130, "#af5f00")
, (131, "#af5f5f")
, (132, "#af5f87")
, (133, "#af5faf")
, (134, "#af5fd7")
, (135, "#af5fff")
, (136, "#af8700")
, (137, "#af875f")
, (138, "#af8787")
, (139, "#af87af")
, (140, "#af87d7")
, (141, "#af87ff")
, (142, "#afaf00")
, (143, "#afaf5f")
, (144, "#afaf87")
, (145, "#afafaf")
, (146, "#afafd7")
, (147, "#afafff")
, (148, "#afd700")
, (149, "#afd75f")
, (150, "#afd787")
, (151, "#afd7af")
, (152, "#afd7d7")
, (153, "#afd7ff")
, (154, "#afff00")
, (155, "#afff5f")
, (156, "#afff87")
, (157, "#afffaf")
, (158, "#afffd7")
, (159, "#afffff")
, (160, "#d70000")
, (161, "#d7005f")
, (162, "#d70087")
, (163, "#d700af")
, (164, "#d700d7")
, (165, "#d700ff")
, (166, "#d75f00")
, (167, "#d75f5f")
, (168, "#d75f87")
, (169, "#d75faf")
, (170, "#d75fd7")
, (171, "#d75fff")
, (172, "#d78700")
, (173, "#d7875f")
, (174, "#d78787")
, (175, "#d787af")
, (176, "#d787d7")
, (177, "#d787ff")
, (178, "#d7af00")
, (179, "#d7af5f")
, (180, "#d7af87")
, (181, "#d7afaf")
, (182, "#d7afd7")
, (183, "#d7afff")
, (184, "#d7d700")
, (185, "#d7d75f")
, (186, "#d7d787")
, (187, "#d7d7af")
, (188, "#d7d7d7")
, (189, "#d7d7ff")
, (190, "#d7ff00")
, (191, "#d7ff5f")
, (192, "#d7ff87")
, (193, "#d7ffaf")
, (194, "#d7ffd7")
, (195, "#d7ffff")
, (196, "#ff0000")
, (197, "#ff005f")
, (198, "#ff0087")
, (199, "#ff00af")
, (200, "#ff00d7")
, (201, "#ff00ff")
, (202, "#ff5f00")
, (203, "#ff5f5f")
, (204, "#ff5f87")
, (205, "#ff5faf")
, (206, "#ff5fd7")
, (207, "#ff5fff")
, (208, "#ff8700")
, (209, "#ff875f")
, (210, "#ff8787")
, (211, "#ff87af")
, (212, "#ff87d7")
, (213, "#ff87ff")
, (214, "#ffaf00")
, (215, "#ffaf5f")
, (216, "#ffaf87")
, (217, "#ffafaf")
, (218, "#ffafd7")
, (219, "#ffafff")
, (220, "#ffd700")
, (221, "#ffd75f")
, (222, "#ffd787")
, (223, "#ffd7af")
, (224, "#ffd7d7")
, (225, "#ffd7ff")
, (226, "#ffff00")
, (227, "#ffff5f")
, (228, "#ffff87")
, (229, "#ffffaf")
, (230, "#ffffd7")
, (231, "#ffffff")
, (232, "#080808")
, (233, "#121212")
, (234, "#1c1c1c")
, (235, "#262626")
, (236, "#303030")
, (237, "#3a3a3a")
, (238, "#444444")
, (239, "#4e4e4e")
, (240, "#585858")
, (241, "#626262")
, (242, "#6c6c6c")
, (243, "#767676")
, (244, "#808080")
, (245, "#8a8a8a")
, (246, "#949494")
, (247, "#9e9e9e")
, (248, "#a8a8a8")
, (249, "#b2b2b2")
, (250, "#bcbcbc")
, (251, "#c6c6c6")
, (252, "#d0d0d0")
, (253, "#dadada")
, (254, "#e4e4e4")
, (255, "#eeeeee")
]
|
davdar/darailude
|
src/FP/Pretty/HTML.hs
|
Haskell
|
bsd-3-clause
| 7,055
|
module GL.Types
(
V2FL,
V3FL,
Coor2(..),
Coor3(..),
fromDegrees
) where
import Graphics.Rendering.OpenGL as GL
type V2FL = Vertex2 GLfloat
type V3FL = Vertex3 GLfloat
data Coor2 = D2 {x,y::GLfloat} deriving Show
data Coor3 = D3 {xx,yy,zz::GLfloat} deriving (Show)
fromDegrees deg = deg * pi / 180
|
xruzzz/ax-fp-gl-haskell
|
src/GL/Types.hs
|
Haskell
|
bsd-3-clause
| 346
|
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
module ZM.Types
( module Data.Model.Types
, AbsTypeModel
, AbsType
, AbsRef(..)
, absRef
, AbsADT
, AbsEnv
, ADTRef(..)
, getADTRef
, toTypeRef
, substAbsADT
, asIdentifier
, Identifier(..)
, UnicodeLetter(..)
, UnicodeLetterOrNumberOrLine(..)
, UnicodeSymbol(..)
, SHA3_256_6(..)
, SHAKE128_48(..)
, shake128_48
, shake128_48_BS
, NonEmptyList(..)
, nonEmptyList
, Word7
-- * Encodings
, FlatEncoding(..)
, UTF8Encoding(..)
, UTF16LEEncoding(..)
, NoEncoding(..)
-- * Exceptions and Errors
, TypedDecoded
, TypedDecodeException(..)
, ZMError(..)
-- *Other Re-exports
, NFData()
, Flat
, ZigZag(..)
, LeastSignificantFirst(..)
, MostSignificantFirst(..)
--, Value(..)
--, Val(..)
--, SpecialValue(..)
-- , Binder(..)
-- , Void1
)
where
-- , Label(..)
-- , label
--, Pattern(..)
--, PatternSpecial(..)
import Control.DeepSeq
import Control.Exception
import qualified Data.ByteString as B
import Data.Char
import Data.Digest.Keccak
import Data.Either.Validation
import Flat
import Data.Foldable
-- import qualified Data.Map as M
import Data.Model hiding ( Name )
import Data.Model.Types hiding ( Name )
import Data.Word
import ZM.Model ( )
import ZM.Type.BLOB
import ZM.Type.NonEmptyList
import ZM.Type.Words ( LeastSignificantFirst(..)
, MostSignificantFirst(..)
, Word7
, ZigZag(..)
)
-- |An absolute type, a type identifier that depends only on the definition of the type
type AbsType = Type AbsRef
-- |A reference to an absolute data type definition, in the form of a hash of the data type definition itself
-- data AbsRef = AbsRef (SHA3_256_6 AbsADT) deriving (Eq, Ord, Show, NFData, Generic, Flat)
newtype AbsRef = AbsRef (SHAKE128_48 AbsADT)
deriving (Eq, Ord, Show, NFData, Generic, Flat)
-- type AbsRef = SHAKE128_48 AbsADT
-- |Return the absolute reference of the given value
absRef :: AbsADT -> AbsRef
absRef = AbsRef . shake128_48
-- |Return the SHAKE128_48 reference of the given value
shake128_48 :: Flat a => a -> SHAKE128_48 a
shake128_48 = shake128_48_BS . flat
-- |Return the SHAKE128_48 reference of the given ByteString
shake128_48_BS :: B.ByteString -> SHAKE128_48 a
shake128_48_BS bs = case B.unpack . shake_128 6 $ bs of
[w1, w2, w3, w4, w5, w6] -> SHAKE128_48 w1 w2 w3 w4 w5 w6
_ -> error "impossible"
-- |A hash of a value, the first 6 bytes of the value's SHA3-256 hash
data SHA3_256_6 a = SHA3_256_6 Word8 Word8 Word8 Word8 Word8 Word8
deriving (Eq, Ord, Show, NFData, Generic, Flat)
-- |A hash of a value, the first 48 bits (6 bytes) of the value's SHAKE128 hash
data SHAKE128_48 a = SHAKE128_48 Word8 Word8 Word8 Word8 Word8 Word8
deriving (Eq, Ord, Show, NFData, Generic, Flat)
-- CHECK: Same syntax for adt and constructor names
-- |An absolute data type definition, a definition that refers only to other absolute definitions
type AbsADT = ADT Identifier Identifier (ADTRef AbsRef)
-- |An absolute type model, an absolute type and its associated environment
type AbsTypeModel = TypeModel Identifier Identifier (ADTRef AbsRef) AbsRef
-- |An environments of absolute types
type AbsEnv = TypeEnv Identifier Identifier (ADTRef AbsRef) AbsRef
-- type ADTEnv = M.Map AbsRef AbsADT
-- FIX: add a custom type for Var
-- |A reference inside an ADT to another ADT
data ADTRef r = Var Word8 -- ^Variable, standing for a type
| Rec -- ^Recursive reference to the ADT itself
| Ext r -- ^Reference to another ADT
deriving (Eq, Ord, Show, NFData, Generic, Functor, Foldable, Traversable, Flat)
-- |Return an external reference, if present
getADTRef :: ADTRef a -> Maybe a
getADTRef (Ext r) = Just r
getADTRef _ = Nothing
toTypeRef :: name -> ADTRef name -> TypeRef name
toTypeRef _ (Var n) = TypVar n
toTypeRef _ (Ext k) = TypRef k
toTypeRef adtRef Rec = TypRef adtRef
substAbsADT :: (AbsRef -> b) -> AbsADT -> ADT Identifier Identifier (TypeRef b)
substAbsADT f adt = (f <$>) <$> (toTypeRef (absRef adt) <$> adt)
-- CHECK: Is it necessary to specify a syntax for identifiers?
-- |An Identifier, the name of an ADT
data Identifier = Name UnicodeLetter [UnicodeLetterOrNumberOrLine]
| Symbol (NonEmptyList UnicodeSymbol)
deriving (Eq, Ord, Show, NFData, Generic, Flat)
-- instance Flat [UnicodeLetterOrNumberOrLine]
instance Convertible String Identifier where
-- safeConvert = errorsToConvertResult asIdentifier
safeConvert = errorsToConvertResult (validationToEither . asIdentifier)
instance Convertible Identifier String where
safeConvert (Name (UnicodeLetter h) t) =
Right $ h : map (\(UnicodeLetterOrNumberOrLine s) -> s) t
safeConvert (Symbol l) = Right $ map (\(UnicodeSymbol s) -> s) . toList $ l
{-|Validate a string as an Identifier
>>> asIdentifier "Id_1"
Success (Name (UnicodeLetter 'I') [UnicodeLetterOrNumberOrLine 'd',UnicodeLetterOrNumberOrLine '_',UnicodeLetterOrNumberOrLine '1'])
>>> asIdentifier "<>"
Success (Symbol (Cons (UnicodeSymbol '<') (Elem (UnicodeSymbol '>'))))
>>> asIdentifier ""
Failure ["identifier cannot be empty"]
>>> asIdentifier "a*^"
Failure ["In a*^: '*' is not an Unicode Letter or Number or a _","In a*^: '^' is not an Unicode Letter or Number or a _"]
-}
asIdentifier :: String -> Validation Errors Identifier
asIdentifier [] = err ["identifier cannot be empty"]
asIdentifier i@(h : t) = errsInContext i $ if isLetter h
then Name <$> asLetter h <*> traverse asLetterOrNumber t
else Symbol . nonEmptyList <$> traverse asSymbol i
-- |A character that is either a `UnicodeLetter`, a `UnicodeNumber` or the special character '_'
newtype UnicodeLetterOrNumberOrLine = UnicodeLetterOrNumberOrLine Char
deriving (Eq, Ord, Show, NFData, Generic, Flat)
{-|
A character that is included in one of the following Unicode classes:
UppercaseLetter
LowercaseLetter
TitlecaseLetter
ModifierLetter
OtherLetter
-}
newtype UnicodeLetter = UnicodeLetter Char
deriving (Eq, Ord, Show, NFData, Generic, Flat)
{-|
A character that is included in one of the following Unicode classes:
DecimalNumber
LetterNumber
OtherNumber
-}
newtype UnicodeNumber = UnicodeNumber Char
deriving (Eq, Ord, Show, NFData, Generic, Flat)
{-|
A character that is included in one of the following Unicode classes:
MathSymbol
CurrencySymbol
ModifierSymbol
OtherSymbol
-}
newtype UnicodeSymbol = UnicodeSymbol Char
deriving (Eq, Ord, Show, NFData, Generic, Flat)
asSymbol :: Char -> Validation Errors UnicodeSymbol
asSymbol c | isSymbol c = ok $ UnicodeSymbol c
| otherwise = err [show c, "is not an Unicode Symbol"]
asLetter :: Char -> Validation Errors UnicodeLetter
asLetter c | isLetter c = ok $ UnicodeLetter c
| otherwise = err [show c, "is not an Unicode Letter"]
asLetterOrNumber :: Char -> Validation Errors UnicodeLetterOrNumberOrLine
asLetterOrNumber c
| isLetter c || isNumber c || isAlsoOK c = ok $ UnicodeLetterOrNumberOrLine c
| otherwise = err [show c, "is not an Unicode Letter or Number or a _"]
ok :: a -> Validation e a
ok = Success
err :: [String] -> Validation Errors a
err = Failure . (: []) . unwords
-- CHECK: IS '_' REALLY NEEDED?
isAlsoOK :: Char -> Bool
isAlsoOK '_' = True
isAlsoOK _ = False
-- |Violations of ZM model constrains
data ZMError t =
UnknownType t
| WrongKind { reference :: t, expectedArity, actualArity :: Int }
| MutuallyRecursive [t]
deriving (Show, Functor, Foldable)
-- -- -- |An optionally labeled value
-- data Label a label =
-- Label a (Maybe label)
-- deriving (Eq, Ord, Show, NFData, Generic, Flat)
-- label :: (Functor f, Ord k) => M.Map k a -> (a -> l) -> f k -> f (Label k l)
-- label env f o = (\ref -> Label ref (f <$> M.lookup ref env)) <$> o
type TypedDecoded a = Either TypedDecodeException a
-- |An exception thrown if the decoding of a type value fails
data TypedDecodeException =
UnknownMetaModel AbsType
| WrongType { expectedType :: AbsType, actualType :: AbsType }
| DecodeError DecodeException
deriving (Show, Eq, Ord)
instance Exception TypedDecodeException
-- newtype LocalName = LocalName Identifier deriving (Eq, Ord, Show, NFData, Generic, Flat)
-- Flat instances for data types in the 'model' package
instance (Flat adtName, Flat consName, Flat inRef, Flat exRef, Ord exRef)
=> Flat (TypeModel adtName consName inRef exRef)
instance (Flat a, Flat b, Flat c) => Flat (ADT a b c)
instance (Flat a, Flat b) => Flat (ConTree a b)
-- instance (Flat a,Flat b) => Flat [(a,Type b)]
-- instance Flat a => Flat [Type a]
instance Flat a => Flat (Type a)
instance Flat a => Flat (TypeRef a)
-- Model instances
instance (Model a, Model b, Model c) => Model (ADT a b c)
instance (Model a, Model b) => Model (ConTree a b)
instance Model a => Model (ADTRef a)
instance Model a => Model (Type a)
instance Model a => Model (TypeRef a)
instance (Model adtName, Model consName, Model inRef, Model exRef)
=> Model (TypeModel adtName consName inRef exRef)
instance Model Identifier
instance Model UnicodeLetter
instance Model UnicodeLetterOrNumberOrLine
instance Model UnicodeSymbol
instance Model a => Model (SHA3_256_6 a)
instance Model a => Model (SHAKE128_48 a)
instance Model AbsRef
instance Model a => Model (PostAligned a)
|
tittoassini/typed
|
src/ZM/Types.hs
|
Haskell
|
bsd-3-clause
| 9,975
|
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
module Language.Sunroof.Active
( JSTime
, JSDuration
, reifyActive
) where
import Control.Newtype ( Newtype(..) )
import Data.Active
( Clock(..), Deadline(..), Waiting(..)
, Active
, FractionalOf
, toFractionalOf, onActive, runDynamic
, start, era, end )
import Data.VectorSpace ( VectorSpace(..) )
import Data.AffineSpace ( AffineSpace(..) )
import Data.AdditiveGroup ( AdditiveGroup(..) )
import Data.Boolean
( BooleanOf, IfB(..), OrdB(..)
, minB, maxB )
import Language.Sunroof.Types
( T(..)
, JS, SunroofThread
, JSFunction
, function )
import Language.Sunroof.Classes ( Sunroof, SunroofValue(..), SunroofArgument(..) )
import Language.Sunroof.JS.Bool ( JSBool )
import Language.Sunroof.JS.Number ( JSNumber )
-- -------------------------------------------------------------
-- JSTime Type
-- -------------------------------------------------------------
newtype JSTime = JSTime { unJSTime :: JSNumber }
deriving ( Show )
instance Newtype JSTime JSNumber where
pack = JSTime
unpack = unJSTime
instance AffineSpace JSTime where
type Diff JSTime = JSDuration
(JSTime t1) .-. (JSTime t2) = JSDuration (t1 - t2)
(JSTime t) .+^ (JSDuration d) = JSTime (t + d)
instance Clock JSTime where
firstTime (JSTime t1) (JSTime t2) = JSTime (minB t1 t2)
lastTime (JSTime t1) (JSTime t2) = JSTime (maxB t1 t2)
toTime = JSTime . js . toRational
fromTime = toFractionalOf
instance FractionalOf JSTime JSNumber where
toFractionalOf = unJSTime
--instance (BooleanOf a ~ JSBool, IfB a) => Deadline JSTime a where
-- choose (JSTime t1) (JSTime t2) = ifB (t1 <=* t2)
instance (BooleanOf b ~ JSBool, IfB b, Deadline JSTime b) => Deadline JSTime (a -> b) where
choose (JSTime t1) (JSTime t2) f1 f2 a = ifB (t1 <=* t2) (f1 a) (f2 a)
instance (Sunroof a, SunroofArgument a, SunroofThread t) => Deadline JSTime (JS t a) where
choose (JSTime t1) (JSTime t2) = ifB (t1 <=* t2)
instance Deadline JSTime JSNumber where
choose (JSTime t1) (JSTime t2) = ifB (t1 <=* t2)
instance Deadline JSTime JSBool where
choose (JSTime t1) (JSTime t2) = ifB (t1 <=* t2)
--instance (BooleanOf a ~ JSBool, IfB a) => Deadline JSTime (f -> a) where
-- choose (JSTime t1) (JSTime t2) x y c = ifB (t1 <=* t2) (x c) (y c)
-- -------------------------------------------------------------
-- JSDuration Type
-- -------------------------------------------------------------
newtype JSDuration = JSDuration { unJSDuration :: JSNumber }
deriving ( Show, AdditiveGroup )
instance Newtype JSDuration JSNumber where
pack = JSDuration
unpack = unJSDuration
instance VectorSpace JSDuration where
type Scalar JSDuration = JSNumber
s *^ (JSDuration d) = JSDuration (s * d)
instance Waiting JSDuration where
toDuration = JSDuration . js . toRational
fromDuration = toFractionalOf
instance FractionalOf JSDuration JSNumber where
toFractionalOf = unJSDuration
-- -------------------------------------------------------------
-- Active Combinators
-- -------------------------------------------------------------
--ex1 :: Active JSTime (JS t JSNumber)
--ex1 = fmap return ui
reifyActive :: Active JSTime (JS A ())
-> JS A (JSNumber, JSNumber, JSFunction JSNumber ())
reifyActive = onActive
(\ x -> do
f <- function (\ _ -> x)
return ( 0, 0, f )
)
(\ d -> do
f <- function (runDynamic d . JSTime)
return ( fromTime $ start $ era d
, fromTime $ end $ era d
, f )
)
{-
compileActiveJS t :: Active JSTime (JS t JSNumber) -> String
compileActiveJS t act = a ++ " ; return " ++ b
where (a,b) = compileJS t $ do
obj :: JSFunction JSNumber JSNumber <- function (runActive act . JSTime)
apply obj 0
-}
|
ku-fpg/sunroof-active
|
Language/Sunroof/Active.hs
|
Haskell
|
bsd-3-clause
| 4,089
|
module More.MonadTs where
import Control.Monad.Trans.Class
import Control.Monad.Trans.Reader
import Control.Monad.Trans.State
import Control.Monad.Trans.Maybe
import Control.Monad.Identity
import Control.Monad.IO.Class
import Control.Monad
rDec :: Num a => Reader a a
rDec = ReaderT $ return . ((+) (-1))
rShow :: Show a => ReaderT a Identity String
rShow = ReaderT $ Identity . show
rPrintAndInc :: (Num a, Show a) => ReaderT a IO a
rPrintAndInc = ReaderT $ \r -> do
putStrLn $ "Hi: " ++ show r
return $ r + 1
sPrintIncAccum :: (Num a, Show a) => StateT a IO String
sPrintIncAccum = StateT $ \r -> do
putStrLn $ "Hi: " ++ show r
return $ (show r, r + 1)
isValid :: String -> Bool
isValid v = '!' `elem` v
hungryText :: MaybeT IO String
hungryText = do
v <- lift getLine
guard (isValid v)
return v
main :: IO ()
main = do
putStrLn "say something."
excite <- runMaybeT hungryText
case excite of
Nothing -> putStrLn "Nothing! Nothing was said!"
Just e -> putStrLn ("Boom! what was said: " ++ e)
|
stites/composition
|
src/MoreReaderT.hs
|
Haskell
|
bsd-3-clause
| 1,133
|
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
{-# LANGUAGE GADTs #-}
{-# LANGUAGE NoRebindableSyntax #-}
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Time.PT.Rules
( rules ) where
import qualified Data.Text as Text
import Prelude
import Duckling.Dimensions.Types
import Duckling.Numeral.Helpers (parseInt)
import Duckling.Regex.Types
import Duckling.Time.Helpers
import Duckling.Time.Types (TimeData (..))
import qualified Duckling.Time.Types as TTime
import qualified Duckling.TimeGrain.Types as TG
import Duckling.Types
ruleNamedday :: Rule
ruleNamedday = Rule
{ name = "named-day"
, pattern =
[ regex "segunda((\\s|\\-)feira)?|seg\\.?"
]
, prod = \_ -> tt $ dayOfWeek 1
}
ruleSHourmintimeofday :: Rule
ruleSHourmintimeofday = Rule
{ name = "às <hour-min>(time-of-day)"
, pattern =
[ regex "(\x00e0|a)s?"
, Predicate isATimeOfDay
, regex "horas?"
]
, prod = \tokens -> case tokens of
(_:x:_) -> Just x
_ -> Nothing
}
ruleTheDayAfterTomorrow :: Rule
ruleTheDayAfterTomorrow = Rule
{ name = "the day after tomorrow"
, pattern =
[ regex "depois de amanh(\x00e3|a)"
]
, prod = \_ -> tt $ cycleNth TG.Day 2
}
ruleNamedmonth12 :: Rule
ruleNamedmonth12 = Rule
{ name = "named-month"
, pattern =
[ regex "dezembro|dez\\.?"
]
, prod = \_ -> tt $ month 12
}
ruleNamedday2 :: Rule
ruleNamedday2 = Rule
{ name = "named-day"
, pattern =
[ regex "ter(\x00e7|c)a((\\s|\\-)feira)?|ter\\.?"
]
, prod = \_ -> tt $ dayOfWeek 2
}
ruleNatal :: Rule
ruleNatal = Rule
{ name = "natal"
, pattern =
[ regex "natal"
]
, prod = \_ -> tt $ monthDay 12 25
}
ruleNaoDate :: Rule
ruleNaoDate = Rule
{ name = "n[ao] <date>"
, pattern =
[ regex "n[ao]"
, Predicate $ isGrainOfTime TG.Day
]
, prod = \tokens -> case tokens of
(_:Token Time td:_) -> tt $ notLatent td
_ -> Nothing
}
ruleIntersectByDaOrDe :: Rule
ruleIntersectByDaOrDe = Rule
{ name = "intersect by `da` or `de`"
, pattern =
[ Predicate isNotLatent
, regex "d[ae]"
, Predicate isNotLatent
]
, prod = \tokens -> case tokens of
(Token Time td1:_:Token Time td2:_) ->
Token Time <$> intersect td1 td2
_ -> Nothing
}
rulePassadosNCycle :: Rule
rulePassadosNCycle = Rule
{ name = "passados n <cycle>"
, pattern =
[ regex "passad(a|o)s?"
, Predicate $ isIntegerBetween 2 9999
, dimension TimeGrain
]
, prod = \tokens -> case tokens of
(_:token:Token TimeGrain grain:_) -> do
v <- getIntValue token
tt $ cycleN True grain (- v)
_ -> Nothing
}
ruleLastTime :: Rule
ruleLastTime = Rule
{ name = "last <time>"
, pattern =
[ regex "(\x00fa|u)ltim[ao]s?"
, dimension Time
]
, prod = \tokens -> case tokens of
(_:Token Time td:_) ->
tt $ predNth (-1) False td
_ -> Nothing
}
ruleNamedday6 :: Rule
ruleNamedday6 = Rule
{ name = "named-day"
, pattern =
[ regex "s(\x00e1|a)bado|s(\x00e1|a)b\\.?"
]
, prod = \_ -> tt $ dayOfWeek 6
}
ruleDatetimeDatetimeInterval :: Rule
ruleDatetimeDatetimeInterval = Rule
{ name = "<datetime> - <datetime> (interval)"
, pattern =
[ Predicate isNotLatent
, regex "\\-|a"
, Predicate isNotLatent
]
, prod = \tokens -> case tokens of
(Token Time td1:_:Token Time td2:_) ->
Token Time <$> interval TTime.Open td1 td2
_ -> Nothing
}
ruleNamedmonth7 :: Rule
ruleNamedmonth7 = Rule
{ name = "named-month"
, pattern =
[ regex "julho|jul\\.?"
]
, prod = \_ -> tt $ month 7
}
ruleEvening :: Rule
ruleEvening = Rule
{ name = "evening"
, pattern =
[ regex "noite"
]
, prod = \_ ->
let from = hour False 18
to = hour False 0
in Token Time . mkLatent . partOfDay <$>
interval TTime.Open from to
}
ruleDayOfMonthSt :: Rule
ruleDayOfMonthSt = Rule
{ name = "day of month (1st)"
, pattern =
[ regex "primeiro|um|1o"
]
, prod = \_ -> tt $ dayOfMonth 1
}
ruleNow :: Rule
ruleNow = Rule
{ name = "now"
, pattern =
[ regex "(hoje)|(neste|nesse) momento"
]
, prod = \_ -> tt $ cycleNth TG.Day 0
}
ruleDimTimeDaMadrugada :: Rule
ruleDimTimeDaMadrugada = Rule
{ name = "<dim time> da madrugada"
, pattern =
[ dimension Time
, regex "(da|na|pela) madruga(da)?"
]
, prod = \tokens -> case tokens of
(Token Time td:_) -> do
td2 <- mkLatent . partOfDay <$>
interval TTime.Open (hour False 1) (hour False 4)
Token Time <$> intersect td td2
_ -> Nothing
}
ruleHhhmmTimeofday :: Rule
ruleHhhmmTimeofday = Rule
{ name = "hh(:|.|h)mm (time-of-day)"
, pattern =
[ regex "((?:[01]?\\d)|(?:2[0-3]))[:h\\.]([0-5]\\d)"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (m1:m2:_)):_) -> do
h <- parseInt m1
m <- parseInt m2
tt $ hourMinute True h m
_ -> Nothing
}
ruleNamedday4 :: Rule
ruleNamedday4 = Rule
{ name = "named-day"
, pattern =
[ regex "quinta((\\s|\\-)feira)?|qui\\.?"
]
, prod = \_ -> tt $ dayOfWeek 4
}
ruleProximoCycle :: Rule
ruleProximoCycle = Rule
{ name = "proximo <cycle> "
, pattern =
[ regex "pr(\x00f3|o)xim(o|a)s?"
, dimension TimeGrain
]
, prod = \tokens -> case tokens of
(_:Token TimeGrain grain:_) ->
tt $ cycleNth grain 1
_ -> Nothing
}
ruleCycleAntesDeTime :: Rule
ruleCycleAntesDeTime = Rule
{ name = "<cycle> antes de <time>"
, pattern =
[ dimension TimeGrain
, regex "antes d[eo]"
, dimension Time
]
, prod = \tokens -> case tokens of
(Token TimeGrain grain:_:Token Time td:_) ->
tt $ cycleNthAfter False grain (-1) td
_ -> Nothing
}
ruleEsteCycle :: Rule
ruleEsteCycle = Rule
{ name = "este <cycle>"
, pattern =
[ regex "(n?es[st](es?|as?))"
, dimension TimeGrain
]
, prod = \tokens -> case tokens of
(_:Token TimeGrain grain:_) ->
tt $ cycleNth grain 0
_ -> Nothing
}
ruleSHourminTimeofday :: Rule
ruleSHourminTimeofday = Rule
{ name = "às <hour-min> <time-of-day>"
, pattern =
[ regex "(\x00e0|a)s"
, Predicate isNotLatent
, regex "da"
, Predicate isATimeOfDay
]
, prod = \tokens -> case tokens of
(_:Token Time td1:_:Token Time td2:_) ->
Token Time <$> intersect td1 td2
_ -> Nothing
}
ruleSeason4 :: Rule
ruleSeason4 = Rule
{ name = "season"
, pattern =
[ regex "primavera"
]
, prod = \_ ->
let from = monthDay 3 20
to = monthDay 6 21
in Token Time <$> interval TTime.Open from to
}
ruleYearLatent2 :: Rule
ruleYearLatent2 = Rule
{ name = "year (latent)"
, pattern =
[ Predicate $ isIntegerBetween 2101 10000
]
, prod = \tokens -> case tokens of
(token:_) -> do
n <- getIntValue token
tt . mkLatent $ year n
_ -> Nothing
}
ruleDiaDayofmonthDeNamedmonth :: Rule
ruleDiaDayofmonthDeNamedmonth = Rule
{ name = "dia <day-of-month> de <named-month>"
, pattern =
[ regex "dia"
, Predicate isDOMInteger
, regex "de|\\/"
, Predicate isAMonth
]
, prod = \tokens -> case tokens of
(_:token:_:Token Time td:_) -> Token Time <$> intersectDOM td token
_ -> Nothing
}
ruleNoon :: Rule
ruleNoon = Rule
{ name = "noon"
, pattern =
[ regex "meio[\\s\\-]?dia"
]
, prod = \_ -> tt $ hour False 12
}
ruleProximasNCycle :: Rule
ruleProximasNCycle = Rule
{ name = "proximas n <cycle>"
, pattern =
[ regex "pr(\x00f3|o)xim(o|a)s?"
, Predicate $ isIntegerBetween 2 9999
, dimension TimeGrain
]
, prod = \tokens -> case tokens of
(_:token:Token TimeGrain grain:_) -> do
v <- getIntValue token
tt $ cycleN True grain v
_ -> Nothing
}
ruleThisnextDayofweek :: Rule
ruleThisnextDayofweek = Rule
{ name = "this|next <day-of-week>"
, pattern =
[ regex "es[ts][ae]|pr(\x00f3|o)xim[ao]"
, Predicate isADayOfWeek
]
, prod = \tokens -> case tokens of
(_:Token Time td:_) ->
tt $ predNth 0 True td
_ -> Nothing
}
ruleTheDayBeforeYesterday :: Rule
ruleTheDayBeforeYesterday = Rule
{ name = "the day before yesterday"
, pattern =
[ regex "anteontem|antes de ontem"
]
, prod = \_ -> tt . cycleNth TG.Day $ - 2
}
ruleHourofdayIntegerAsRelativeMinutes :: Rule
ruleHourofdayIntegerAsRelativeMinutes = Rule
{ name = "<hour-of-day> <integer> (as relative minutes)"
, pattern =
[ Predicate isAnHourOfDay
, Predicate $ isIntegerBetween 1 59
]
, prod = \tokens -> case tokens of
(Token Time TimeData {TTime.form = Just (TTime.TimeOfDay (Just hours) is12H)}:
token:
_) -> do
n <- getIntValue token
tt $ hourMinute is12H hours n
_ -> Nothing
}
ruleHourofdayAndRelativeMinutes :: Rule
ruleHourofdayAndRelativeMinutes = Rule
{ name = "<hour-of-day> and <relative minutes>"
, pattern =
[ Predicate isAnHourOfDay
, regex "e"
, Predicate $ isIntegerBetween 1 59
]
, prod = \tokens -> case tokens of
(Token Time TimeData {TTime.form = Just (TTime.TimeOfDay (Just hours) is12H)}:
_:
token:
_) -> do
n <- getIntValue token
tt $ hourMinute is12H hours n
_ -> Nothing
}
ruleIntegerParaAsHourofdayAsRelativeMinutes :: Rule
ruleIntegerParaAsHourofdayAsRelativeMinutes = Rule
{ name = "<integer> para as <hour-of-day> (as relative minutes)"
, pattern =
[ Predicate $ isIntegerBetween 1 59
, regex "para ((o|a|\x00e0)s?)?"
, Predicate isAnHourOfDay
]
, prod = \tokens -> case tokens of
(token:_:Token Time td:_) -> do
n <- getIntValue token
t <- minutesBefore n td
Just $ Token Time t
_ -> Nothing
}
ruleHourofdayIntegerAsRelativeMinutes2 :: Rule
ruleHourofdayIntegerAsRelativeMinutes2 = Rule
{ name = "<hour-of-day> <integer> (as relative minutes) minutos"
, pattern =
[ Predicate isAnHourOfDay
, Predicate $ isIntegerBetween 1 59
, regex "min\\.?(uto)?s?"
]
, prod = \tokens -> case tokens of
(Token Time TimeData {TTime.form = Just (TTime.TimeOfDay (Just hours) is12H)}:
token:
_) -> do
n <- getIntValue token
tt $ hourMinute is12H hours n
_ -> Nothing
}
ruleHourofdayAndRelativeMinutes2 :: Rule
ruleHourofdayAndRelativeMinutes2 = Rule
{ name = "<hour-of-day> and <relative minutes> minutos"
, pattern =
[ Predicate isAnHourOfDay
, regex "e"
, Predicate $ isIntegerBetween 1 59
, regex "min\\.?(uto)?s?"
]
, prod = \tokens -> case tokens of
(Token Time TimeData {TTime.form = Just (TTime.TimeOfDay (Just hours) is12H)}:
_:
token:
_) -> do
n <- getIntValue token
tt $ hourMinute is12H hours n
_ -> Nothing
}
ruleIntegerParaAsHourofdayAsRelativeMinutes2 :: Rule
ruleIntegerParaAsHourofdayAsRelativeMinutes2 = Rule
{ name = "<integer> minutos para as <hour-of-day> (as relative minutes)"
, pattern =
[ Predicate $ isIntegerBetween 1 59
, regex "min\\.?(uto)?s?"
, regex "para ((o|a|\x00e0)s?)?"
, Predicate isAnHourOfDay
]
, prod = \tokens -> case tokens of
(token:_:_:Token Time td:_) -> do
n <- getIntValue token
t <- minutesBefore n td
Just $ Token Time t
_ -> Nothing
}
ruleHourofdayQuarter :: Rule
ruleHourofdayQuarter = Rule
{ name = "<hour-of-day> quarter (as relative minutes)"
, pattern =
[ Predicate isAnHourOfDay
, regex "quinze"
]
, prod = \tokens -> case tokens of
(Token Time TimeData {TTime.form = Just (TTime.TimeOfDay (Just hours) is12H)}:
_) -> tt $ hourMinute is12H hours 15
_ -> Nothing
}
ruleHourofdayAndQuarter :: Rule
ruleHourofdayAndQuarter = Rule
{ name = "<hour-of-day> and quinze"
, pattern =
[ Predicate isAnHourOfDay
, regex "e quinze"
]
, prod = \tokens -> case tokens of
(Token Time TimeData {TTime.form = Just (TTime.TimeOfDay (Just hours) is12H)}:
_) -> tt $ hourMinute is12H hours 15
_ -> Nothing
}
ruleQuarterParaAsHourofdayAsRelativeMinutes :: Rule
ruleQuarterParaAsHourofdayAsRelativeMinutes = Rule
{ name = "quinze para as <hour-of-day> (as relative minutes)"
, pattern =
[ regex "quinze para ((o|a|\x00e0)s?)?"
, Predicate isAnHourOfDay
]
, prod = \tokens -> case tokens of
(_:Token Time td:_) -> Token Time <$> minutesBefore 15 td
_ -> Nothing
}
ruleHourofdayHalf :: Rule
ruleHourofdayHalf = Rule
{ name = "<hour-of-day> half (as relative minutes)"
, pattern =
[ Predicate isAnHourOfDay
, regex "meia|trinta"
]
, prod = \tokens -> case tokens of
(Token Time TimeData {TTime.form = Just (TTime.TimeOfDay (Just hours) is12H)}:
_) -> tt $ hourMinute is12H hours 30
_ -> Nothing
}
ruleHourofdayAndHalf :: Rule
ruleHourofdayAndHalf = Rule
{ name = "<hour-of-day> and half"
, pattern =
[ Predicate isAnHourOfDay
, regex "e (meia|trinta)"
]
, prod = \tokens -> case tokens of
(Token Time TimeData {TTime.form = Just (TTime.TimeOfDay (Just hours) is12H)}:
_) -> tt $ hourMinute is12H hours 30
_ -> Nothing
}
ruleHalfParaAsHourofdayAsRelativeMinutes :: Rule
ruleHalfParaAsHourofdayAsRelativeMinutes = Rule
{ name = "half para as <hour-of-day> (as relative minutes)"
, pattern =
[ regex "(meia|trinta) para ((o|a|\x00e0)s?)?"
, Predicate isAnHourOfDay
]
, prod = \tokens -> case tokens of
(_:Token Time td:_) -> Token Time <$> minutesBefore 30 td
_ -> Nothing
}
ruleHourofdayThreeQuarter :: Rule
ruleHourofdayThreeQuarter = Rule
{ name = "<hour-of-day> 3/4 (as relative minutes)"
, pattern =
[ Predicate isAnHourOfDay
, regex "quarenta e cinco"
]
, prod = \tokens -> case tokens of
(Token Time TimeData {TTime.form = Just (TTime.TimeOfDay (Just hours) is12H)}:
_) -> tt $ hourMinute is12H hours 45
_ -> Nothing
}
ruleHourofdayAndThreeQuarter :: Rule
ruleHourofdayAndThreeQuarter = Rule
{ name = "<hour-of-day> and 3/4"
, pattern =
[ Predicate isAnHourOfDay
, regex "e quarenta e cinco"
]
, prod = \tokens -> case tokens of
(Token Time TimeData {TTime.form = Just (TTime.TimeOfDay (Just hours) is12H)}:
_) -> tt $ hourMinute is12H hours 45
_ -> Nothing
}
ruleThreeQuarterParaAsHourofdayAsRelativeMinutes :: Rule
ruleThreeQuarterParaAsHourofdayAsRelativeMinutes = Rule
{ name = "3/4 para as <hour-of-day> (as relative minutes)"
, pattern =
[ regex "quarenta e cinco para ((o|a|\x00e0)s?)?"
, Predicate isAnHourOfDay
]
, prod = \tokens -> case tokens of
(_:Token Time td:_) -> Token Time <$> minutesBefore 45 td
_ -> Nothing
}
ruleNamedmonth :: Rule
ruleNamedmonth = Rule
{ name = "named-month"
, pattern =
[ regex "janeiro|jan\\.?"
]
, prod = \_ -> tt $ month 1
}
ruleTiradentes :: Rule
ruleTiradentes = Rule
{ name = "Tiradentes"
, pattern =
[ regex "tiradentes"
]
, prod = \_ -> tt $ monthDay 4 21
}
ruleInThePartofday :: Rule
ruleInThePartofday = Rule
{ name = "in the <part-of-day>"
, pattern =
[ regex "(de|pela)"
, Predicate isAPartOfDay
]
, prod = \tokens -> case tokens of
(_:Token Time td:_) ->
tt $ notLatent td
_ -> Nothing
}
rulePartofdayDessaSemana :: Rule
rulePartofdayDessaSemana = Rule
{ name = "<part-of-day> dessa semana"
, pattern =
[ Predicate isNotLatent
, regex "(d?es[ts]a semana)|agora"
]
, prod = \tokens -> case tokens of
(Token Time td:_) ->
Token Time . partOfDay <$> intersect (cycleNth TG.Day 0) td
_ -> Nothing
}
ruleNamedmonth3 :: Rule
ruleNamedmonth3 = Rule
{ name = "named-month"
, pattern =
[ regex "mar(\x00e7|c)o|mar\\.?"
]
, prod = \_ -> tt $ month 3
}
ruleDepoisDasTimeofday :: Rule
ruleDepoisDasTimeofday = Rule
{ name = "depois das <time-of-day>"
, pattern =
[ regex "(depois|ap(\x00f3|o)s) d?((a|\x00e1|\x00e0)[so]?|os?)"
, dimension Time
]
, prod = \tokens -> case tokens of
(_:Token Time td:_) ->
tt $ withDirection TTime.After td
_ -> Nothing
}
ruleDdmm :: Rule
ruleDdmm = Rule
{ name = "dd[/-]mm"
, pattern =
[ regex "(3[01]|[12]\\d|0?[1-9])[\\/\\-](0?[1-9]|1[0-2])"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (dd:mm:_)):_) -> do
m <- parseInt mm
d <- parseInt dd
tt $ monthDay m d
_ -> Nothing
}
ruleEmDuration :: Rule
ruleEmDuration = Rule
{ name = "em <duration>"
, pattern =
[ regex "em"
, dimension Duration
]
, prod = \tokens -> case tokens of
(_:Token Duration dd:_) ->
tt $ inDuration dd
_ -> Nothing
}
ruleAfternoon :: Rule
ruleAfternoon = Rule
{ name = "afternoon"
, pattern =
[ regex "tarde"
]
, prod = \_ ->
let from = hour False 12
to = hour False 19
in Token Time . mkLatent . partOfDay <$>
interval TTime.Open from to
}
ruleNamedmonth4 :: Rule
ruleNamedmonth4 = Rule
{ name = "named-month"
, pattern =
[ regex "abril|abr\\.?"
]
, prod = \_ -> tt $ month 4
}
ruleDimTimeDaManha :: Rule
ruleDimTimeDaManha = Rule
{ name = "<dim time> da manha"
, pattern =
[ Predicate $ isGrainFinerThan TG.Year
, regex "(da|na|pela) manh(\x00e3|a)"
]
, prod = \tokens -> case tokens of
(Token Time td:_) -> do
td2 <- mkLatent . partOfDay <$>
interval TTime.Open (hour False 4) (hour False 12)
Token Time <$> intersect td td2
_ -> Nothing
}
ruleNCycleProximoqueVem :: Rule
ruleNCycleProximoqueVem = Rule
{ name = "n <cycle> (proximo|que vem)"
, pattern =
[ Predicate $ isIntegerBetween 2 9999
, dimension TimeGrain
, regex "(pr(\x00f3|o)xim(o|a)s?|que vem?|seguintes?)"
]
, prod = \tokens -> case tokens of
(token:Token TimeGrain grain:_) -> do
v <- getIntValue token
tt $ cycleN True grain v
_ -> Nothing
}
ruleMidnight :: Rule
ruleMidnight = Rule
{ name = "midnight"
, pattern =
[ regex "meia[\\s\\-]?noite"
]
, prod = \_ -> tt $ hour False 0
}
ruleNamedday5 :: Rule
ruleNamedday5 = Rule
{ name = "named-day"
, pattern =
[ regex "sexta((\\s|\\-)feira)?|sex\\.?"
]
, prod = \_ -> tt $ dayOfWeek 5
}
ruleDdddMonthinterval :: Rule
ruleDdddMonthinterval = Rule
{ name = "dd-dd <month>(interval)"
, pattern =
[ regex "(3[01]|[12]\\d|0?[1-9])"
, regex "\\-|a"
, regex "(3[01]|[12]\\d|0?[1-9])"
, regex "de"
, Predicate isAMonth
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (m1:_)):
_:
Token RegexMatch (GroupMatch (m2:_)):
_:
Token Time td:
_) -> do
d1 <- parseInt m1
d2 <- parseInt m2
from <- intersect (dayOfMonth d1) td
to <- intersect (dayOfMonth d2) td
Token Time <$> interval TTime.Closed from to
_ -> Nothing
}
ruleTimeofdayLatent :: Rule
ruleTimeofdayLatent = Rule
{ name = "time-of-day (latent)"
, pattern =
[ Predicate $ isIntegerBetween 0 23
]
, prod = \tokens -> case tokens of
(token:_) -> do
v <- getIntValue token
tt . mkLatent $ hour True v
_ -> Nothing
}
ruleUltimoTime :: Rule
ruleUltimoTime = Rule
{ name = "ultimo <time>"
, pattern =
[ regex "(u|\x00fa)ltimo"
, dimension Time
]
, prod = \tokens -> case tokens of
(_:Token Time td:_) ->
tt $ predNth (-1) False td
_ -> Nothing
}
ruleNamedmonth2 :: Rule
ruleNamedmonth2 = Rule
{ name = "named-month"
, pattern =
[ regex "fevereiro|fev\\.?"
]
, prod = \_ -> tt $ month 2
}
ruleNamedmonthnameddayPast :: Rule
ruleNamedmonthnameddayPast = Rule
{ name = "<named-month|named-day> past"
, pattern =
[ Predicate isNotLatent
, regex "(da semana)? passad(o|a)"
]
, prod = \tokens -> case tokens of
(Token Time td:_) ->
tt $ predNth (-1) False td
_ -> Nothing
}
ruleSeason3 :: Rule
ruleSeason3 = Rule
{ name = "season"
, pattern =
[ regex "inverno"
]
, prod = \_ ->
let from = monthDay 12 21
to = monthDay 3 20
in Token Time <$> interval TTime.Open from to
}
ruleSeason :: Rule
ruleSeason = Rule
{ name = "season"
, pattern =
[ regex "ver(\x00e3|a)o"
]
, prod = \_ ->
let from = monthDay 6 21
to = monthDay 9 23
in Token Time <$> interval TTime.Open from to
}
ruleRightNow :: Rule
ruleRightNow = Rule
{ name = "right now"
, pattern =
[ regex "agora|j(\x00e1|a)|(nesse|neste) instante"
]
, prod = \_ -> tt $ cycleNth TG.Second 0
}
ruleFazemDuration :: Rule
ruleFazemDuration = Rule
{ name = "fazem <duration>"
, pattern =
[ regex "faz(em)?"
, dimension Duration
]
, prod = \tokens -> case tokens of
(_:Token Duration dd:_) ->
tt $ durationAgo dd
_ -> Nothing
}
ruleAmanhPelaPartofday :: Rule
ruleAmanhPelaPartofday = Rule
{ name = "amanhã pela <part-of-day>"
, pattern =
[ dimension Time
, regex "(da|na|pela|a)"
, Predicate isAPartOfDay
]
, prod = \tokens -> case tokens of
(Token Time td1:_:Token Time td2:_) ->
Token Time <$> intersect td1 td2
_ -> Nothing
}
ruleHhmmMilitaryTimeofday :: Rule
ruleHhmmMilitaryTimeofday = Rule
{ name = "hhmm (military time-of-day)"
, pattern =
[ regex "((?:[01]?\\d)|(?:2[0-3]))([0-5]\\d)"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (m1:m2:_)):_) -> do
h <- parseInt m1
m <- parseInt m2
tt . mkLatent $ hourMinute False h m
_ -> Nothing
}
ruleNamedmonthnameddayNext :: Rule
ruleNamedmonthnameddayNext = Rule
{ name = "<named-month|named-day> next"
, pattern =
[ dimension Time
, regex "(da pr(o|\x00f3)xima semana)|(da semana)? que vem"
]
, prod = \tokens -> case tokens of
(Token Time td:_) ->
tt $ predNth 1 False td
_ -> Nothing
}
ruleIntersect :: Rule
ruleIntersect = Rule
{ name = "intersect"
, pattern =
[ Predicate isNotLatent
, Predicate isNotLatent
]
, prod = \tokens -> case tokens of
(Token Time td1:Token Time td2:_) ->
Token Time <$> intersect td1 td2
_ -> Nothing
}
ruleTimeofdayPartofday :: Rule
ruleTimeofdayPartofday = Rule
{ name = "<time-of-day> <part-of-day>"
, pattern =
[ dimension Time
, regex "(da|na|pela)"
, Predicate isAPartOfDay
]
, prod = \tokens -> case tokens of
(Token Time td1:_:Token Time td2:_) ->
Token Time <$> intersect td1 td2
_ -> Nothing
}
ruleDeDatetimeDatetimeInterval :: Rule
ruleDeDatetimeDatetimeInterval = Rule
{ name = "de <datetime> - <datetime> (interval)"
, pattern =
[ regex "de?"
, dimension Time
, regex "\\-|a"
, dimension Time
]
, prod = \tokens -> case tokens of
(_:Token Time td1:_:Token Time td2:_) ->
Token Time <$> interval TTime.Open td1 td2
_ -> Nothing
}
ruleNamedmonth6 :: Rule
ruleNamedmonth6 = Rule
{ name = "named-month"
, pattern =
[ regex "junho|jun\\.?"
]
, prod = \_ -> tt $ month 6
}
ruleDentroDeDuration :: Rule
ruleDentroDeDuration = Rule
{ name = "dentro de <duration>"
, pattern =
[ regex "(dentro de)|em"
, dimension Duration
]
, prod = \tokens -> case tokens of
(_:Token Duration dd:_) ->
let from = cycleNth TG.Second 0
to = inDuration dd
in Token Time <$> interval TTime.Open from to
_ -> Nothing
}
ruleSTimeofday :: Rule
ruleSTimeofday = Rule
{ name = "às <time-of-day>"
, pattern =
[ regex "(\x00e0|a)s?"
, Predicate isATimeOfDay
]
, prod = \tokens -> case tokens of
(_:Token Time td:_) ->
tt $ notLatent td
_ -> Nothing
}
ruleNamedmonth8 :: Rule
ruleNamedmonth8 = Rule
{ name = "named-month"
, pattern =
[ regex "agosto|ago\\.?"
]
, prod = \_ -> tt $ month 8
}
ruleDimTimeDaTarde :: Rule
ruleDimTimeDaTarde = Rule
{ name = "<dim time> da tarde"
, pattern =
[ dimension Time
, regex "(da|na|pela) tarde"
]
, prod = \tokens -> case tokens of
(Token Time td:_) -> do
td2 <- mkLatent . partOfDay <$>
interval TTime.Open (hour False 12) (hour False 18)
Token Time <$> intersect td td2
_ -> Nothing
}
ruleWeekend :: Rule
ruleWeekend = Rule
{ name = "week-end"
, pattern =
[ regex "final de semana|fim de semana|fds"
]
, prod = \_ -> do
from <- intersect (dayOfWeek 5) (hour False 18)
to <- intersect (dayOfWeek 1) (hour False 0)
Token Time <$> interval TTime.Open from to
}
ruleDayofweekSHourmin :: Rule
ruleDayofweekSHourmin = Rule
{ name = "<day-of-week> às <hour-min>"
, pattern =
[ Predicate isATimeOfDay
, regex "(\x00e0|a)s"
, Predicate isNotLatent
, regex "da|pela"
, Predicate isATimeOfDay
]
, prod = \tokens -> case tokens of
(Token Time td1:_:Token Time td2:_:Token Time td3:_) -> do
td <- intersect td1 td2
Token Time <$> intersect td td3
_ -> Nothing
}
ruleCycleQueVem :: Rule
ruleCycleQueVem = Rule
{ name = "<cycle> (que vem)"
, pattern =
[ dimension TimeGrain
, regex "que vem|seguintes?"
]
, prod = \tokens -> case tokens of
(Token TimeGrain grain:_) -> tt $ cycleNth grain 1
_ -> Nothing
}
ruleAnoNovo :: Rule
ruleAnoNovo = Rule
{ name = "ano novo"
, pattern =
[ regex "ano novo|reveillon"
]
, prod = \_ -> tt $ monthDay 1 1
}
ruleNextTime :: Rule
ruleNextTime = Rule
{ name = "next <time>"
, pattern =
[ regex "(d[ao]) pr(\x00f3|o)xim[ao]s?|que vem"
, Predicate isNotLatent
]
, prod = \tokens -> case tokens of
(_:Token Time td:_) ->
tt $ predNth 0 True td
_ -> Nothing
}
ruleDeYear :: Rule
ruleDeYear = Rule
{ name = "de <year>"
, pattern =
[ regex "de|do ano"
, Predicate $ isIntegerBetween 1000 2100
]
, prod = \tokens -> case tokens of
(_:token:_) -> do
n <- getIntValue token
tt $ year n
_ -> Nothing
}
ruleVesperaDeAnoNovo :: Rule
ruleVesperaDeAnoNovo = Rule
{ name = "vespera de ano novo"
, pattern =
[ regex "v(\x00e9|e)spera d[eo] ano[\\s\\-]novo"
]
, prod = \_ -> tt $ monthDay 12 31
}
ruleNPassadosCycle :: Rule
ruleNPassadosCycle = Rule
{ name = "n passados <cycle>"
, pattern =
[ Predicate $ isIntegerBetween 2 9999
, regex "passad(a|o)s?"
, dimension TimeGrain
]
, prod = \tokens -> case tokens of
(token:_:Token TimeGrain grain:_) -> do
v <- getIntValue token
tt $ cycleN True grain (- v)
_ -> Nothing
}
ruleDiaDayofmonthNonOrdinal :: Rule
ruleDiaDayofmonthNonOrdinal = Rule
{ name = "dia <day-of-month> (non ordinal)"
, pattern =
[ regex "dia"
, Predicate isDOMInteger
]
, prod = \tokens -> case tokens of
(_:token:_) -> do
v <- getIntValue token
tt . mkLatent $ dayOfMonth v
_ -> Nothing
}
ruleYyyymmdd :: Rule
ruleYyyymmdd = Rule
{ name = "yyyy-mm-dd"
, pattern =
[ regex "(\\d{2,4})-(0?[1-9]|1[0-2])-(3[01]|[12]\\d|0?[1-9])"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (yy:mm:dd:_)):_) -> do
y <- parseInt yy
m <- parseInt mm
d <- parseInt dd
tt $ yearMonthDay y m d
_ -> Nothing
}
ruleTimeofdayHoras :: Rule
ruleTimeofdayHoras = Rule
{ name = "<time-of-day> horas"
, pattern =
[ Predicate isATimeOfDay
, regex "h\\.?(ora)?s?"
]
, prod = \tokens -> case tokens of
(Token Time td:_) ->
tt $ notLatent td
_ -> Nothing
}
ruleTwoTimeTokensSeparatedBy :: Rule
ruleTwoTimeTokensSeparatedBy = Rule
{ name = "two time tokens separated by \",\""
, pattern =
[ Predicate isNotLatent
, regex ","
, Predicate isNotLatent
]
, prod = \tokens -> case tokens of
(Token Time td1:_:Token Time td2:_) ->
Token Time <$> intersect td1 td2
_ -> Nothing
}
ruleTwoTimeTokensSeparatedBy2 :: Rule
ruleTwoTimeTokensSeparatedBy2 = Rule
{ name = "two time tokens separated by \",\"2"
, pattern =
[ Predicate isNotLatent
, regex ","
, Predicate isNotLatent
]
, prod = \tokens -> case tokens of
(Token Time td1:_:Token Time td2:_) ->
Token Time <$> intersect td2 td1
_ -> Nothing
}
ruleMorning :: Rule
ruleMorning = Rule
{ name = "morning"
, pattern =
[ regex "manh(\x00e3|a)"
]
, prod = \_ ->
let from = hour False 4
to = hour False 12
in Token Time . mkLatent . partOfDay <$>
interval TTime.Open from to
}
ruleThisPartofday :: Rule
ruleThisPartofday = Rule
{ name = "this <part-of-day>"
, pattern =
[ regex "es[ts]a"
, Predicate isAPartOfDay
]
, prod = \tokens -> case tokens of
(_:Token Time td:_) ->
Token Time . partOfDay <$> intersect (cycleNth TG.Day 0) td
_ -> Nothing
}
ruleThisTime :: Rule
ruleThisTime = Rule
{ name = "this <time>"
, pattern =
[ regex "es[ts][ae]"
, dimension Time
]
, prod = \tokens -> case tokens of
(_:Token Time td:_) ->
tt $ predNth 0 False td
_ -> Nothing
}
ruleProclamaoDaRepblica :: Rule
ruleProclamaoDaRepblica = Rule
{ name = "Proclamação da República"
, pattern =
[ regex "proclama(c|\x00e7)(a|\x00e3)o da rep(\x00fa|u)blica"
]
, prod = \_ -> tt $ monthDay 11 15
}
ruleYearLatent :: Rule
ruleYearLatent = Rule
{ name = "year (latent)"
, pattern =
[ Predicate $ isIntegerBetween (- 10000) 999
]
, prod = \tokens -> case tokens of
(token:_) -> do
n <- getIntValue token
tt . mkLatent $ year n
_ -> Nothing
}
ruleYesterday :: Rule
ruleYesterday = Rule
{ name = "yesterday"
, pattern =
[ regex "ontem"
]
, prod = \_ -> tt . cycleNth TG.Day $ - 1
}
ruleSeason2 :: Rule
ruleSeason2 = Rule
{ name = "season"
, pattern =
[ regex "outono"
]
, prod = \_ ->
let from = monthDay 9 23
to = monthDay 12 21
in Token Time <$> interval TTime.Open from to
}
ruleDiaDoTrabalhador :: Rule
ruleDiaDoTrabalhador = Rule
{ name = "Dia do trabalhador"
, pattern =
[ regex "dia do trabalh(o|ador)"
]
, prod = \_ -> tt $ monthDay 5 1
}
ruleNCycleAtras :: Rule
ruleNCycleAtras = Rule
{ name = "n <cycle> atras"
, pattern =
[ Predicate $ isIntegerBetween 2 9999
, dimension TimeGrain
, regex "atr(a|\x00e1)s"
]
, prod = \tokens -> case tokens of
(token:Token TimeGrain grain:_) -> do
v <- getIntValue token
tt $ cycleN True grain (- v)
_ -> Nothing
}
ruleTimeofdayAmpm :: Rule
ruleTimeofdayAmpm = Rule
{ name = "<time-of-day> am|pm"
, pattern =
[ Predicate isATimeOfDay
, regex "([ap])\\.?m?\\.?"
]
, prod = \tokens -> case tokens of
(Token Time td:Token RegexMatch (GroupMatch (ap:_)):_) ->
tt . timeOfDayAMPM td $ Text.toLower ap == "a"
_ -> Nothing
}
ruleDayofmonthDeNamedmonth :: Rule
ruleDayofmonthDeNamedmonth = Rule
{ name = "<day-of-month> de <named-month>"
, pattern =
[ Predicate isDOMInteger
, regex "de|\\/"
, Predicate isAMonth
]
, prod = \tokens -> case tokens of
(token:_:Token Time td:_) -> Token Time <$> intersectDOM td token
_ -> Nothing
}
ruleEntreDatetimeEDatetimeInterval :: Rule
ruleEntreDatetimeEDatetimeInterval = Rule
{ name = "entre <datetime> e <datetime> (interval)"
, pattern =
[ regex "entre"
, dimension Time
, regex "e"
, dimension Time
]
, prod = \tokens -> case tokens of
(_:Token Time td1:_:Token Time td2:_) ->
Token Time <$> interval TTime.Open td1 td2
_ -> Nothing
}
ruleEntreDdEtDdMonthinterval :: Rule
ruleEntreDdEtDdMonthinterval = Rule
{ name = "entre dd et dd <month>(interval)"
, pattern =
[ regex "entre"
, regex "(0?[1-9]|[12]\\d|3[01])"
, regex "e?"
, regex "(0?[1-9]|[12]\\d|3[01])"
, regex "de"
, Predicate isAMonth
]
, prod = \tokens -> case tokens of
(_:
Token RegexMatch (GroupMatch (d1:_)):
_:
Token RegexMatch (GroupMatch (d2:_)):
_:
Token Time td:
_) -> do
dd1 <- parseInt d1
dd2 <- parseInt d2
dom1 <- intersect (dayOfMonth dd1) td
dom2 <- intersect (dayOfMonth dd2) td
Token Time <$> interval TTime.Closed dom1 dom2
_ -> Nothing
}
ruleCyclePassado :: Rule
ruleCyclePassado = Rule
{ name = "<cycle> passado"
, pattern =
[ dimension TimeGrain
, regex "passad(a|o)s?"
]
, prod = \tokens -> case tokens of
(Token TimeGrain grain:_) ->
tt . cycleNth grain $ - 1
_ -> Nothing
}
ruleNamedmonth5 :: Rule
ruleNamedmonth5 = Rule
{ name = "named-month"
, pattern =
[ regex "maio|mai\\.?"
]
, prod = \_ -> tt $ month 5
}
ruleNamedday7 :: Rule
ruleNamedday7 = Rule
{ name = "named-day"
, pattern =
[ regex "domingo|dom\\.?"
]
, prod = \_ -> tt $ dayOfWeek 7
}
ruleNossaSenhoraAparecida :: Rule
ruleNossaSenhoraAparecida = Rule
{ name = "Nossa Senhora Aparecida"
, pattern =
[ regex "nossa senhora (aparecida)?"
]
, prod = \_ -> tt $ monthDay 10 12
}
ruleFinados :: Rule
ruleFinados = Rule
{ name = "Finados"
, pattern =
[ regex "finados|dia dos mortos"
]
, prod = \_ -> tt $ monthDay 11 2
}
ruleYear :: Rule
ruleYear = Rule
{ name = "year"
, pattern =
[ Predicate $ isIntegerBetween 1000 2100
]
, prod = \tokens -> case tokens of
(token:_) -> do
n <- getIntValue token
tt $ year n
_ -> Nothing
}
ruleNamedmonth10 :: Rule
ruleNamedmonth10 = Rule
{ name = "named-month"
, pattern =
[ regex "outubro|out\\.?"
]
, prod = \_ -> tt $ month 10
}
ruleAntesDasTimeofday :: Rule
ruleAntesDasTimeofday = Rule
{ name = "antes das <time-of-day>"
, pattern =
[ regex "(antes|at(e|\x00e9)|n(a|\x00e3)o mais que) (d?(o|a|\x00e0)s?)?"
, dimension Time
]
, prod = \tokens -> case tokens of
(_:Token Time td:_) ->
tt $ withDirection TTime.Before td
_ -> Nothing
}
ruleNProximasCycle :: Rule
ruleNProximasCycle = Rule
{ name = "n proximas <cycle>"
, pattern =
[ Predicate $ isIntegerBetween 2 9999
, regex "pr(\x00f3|o)xim(o|a)s?"
, dimension TimeGrain
]
, prod = \tokens -> case tokens of
(token:_:Token TimeGrain grain:_) -> do
v <- getIntValue token
tt $ cycleN True grain v
_ -> Nothing
}
ruleDdmmyyyy :: Rule
ruleDdmmyyyy = Rule
{ name = "dd[/-.]mm[/-.]yyyy"
, pattern =
[ regex "(3[01]|[12]\\d|0?[1-9])[\\.\\/\\-](0?[1-9]|1[0-2])[\\.\\/\\-](\\d{2,4})"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (m1:m2:m3:_)):_) -> do
y <- parseInt m3
m <- parseInt m2
d <- parseInt m1
tt $ yearMonthDay y m d
_ -> Nothing
}
ruleNamedmonth11 :: Rule
ruleNamedmonth11 = Rule
{ name = "named-month"
, pattern =
[ regex "novembro|nov\\.?"
]
, prod = \_ -> tt $ month 11
}
ruleIndependecia :: Rule
ruleIndependecia = Rule
{ name = "Independecia"
, pattern =
[ regex "independ(\x00ea|e)ncia"
]
, prod = \_ -> tt $ monthDay 9 7
}
ruleNamedday3 :: Rule
ruleNamedday3 = Rule
{ name = "named-day"
, pattern =
[ regex "quarta((\\s|\\-)feira)?|qua\\.?"
]
, prod = \_ -> tt $ dayOfWeek 3
}
ruleTomorrow :: Rule
ruleTomorrow = Rule
{ name = "tomorrow"
, pattern =
[ regex "amanh(\x00e3|a)"
]
, prod = \_ -> tt $ cycleNth TG.Day 1
}
ruleNamedmonth9 :: Rule
ruleNamedmonth9 = Rule
{ name = "named-month"
, pattern =
[ regex "setembro|set\\.?"
]
, prod = \_ -> tt $ month 9
}
ruleTimezone :: Rule
ruleTimezone = Rule
{ name = "<time> timezone"
, pattern =
[ Predicate isATimeOfDay
, regex "\\b(YEKT|YEKST|YAKT|YAKST|WITA|WIT|WIB|WGT|WGST|WFT|WET|WEST|WAT|WAST|VUT|VLAT|VLAST|VET|UZT|UYT|UYST|UTC|ULAT|TVT|TMT|TLT|TKT|TJT|TFT|TAHT|SST|SRT|SGT|SCT|SBT|SAST|SAMT|RET|PYT|PYST|PWT|PST|PONT|PMST|PMDT|PKT|PHT|PHOT|PGT|PETT|PETST|PET|PDT|OMST|OMSST|NZST|NZDT|NUT|NST|NPT|NOVT|NOVST|NFT|NDT|NCT|MYT|MVT|MUT|MST|MSK|MSD|MMT|MHT|MDT|MAWT|MART|MAGT|MAGST|LINT|LHST|LHDT|KUYT|KST|KRAT|KRAST|KGT|JST|IST|IRST|IRKT|IRKST|IRDT|IOT|IDT|ICT|HOVT|HKT|GYT|GST|GMT|GILT|GFT|GET|GAMT|GALT|FNT|FKT|FKST|FJT|FJST|EST|EGT|EGST|EET|EEST|EDT|ECT|EAT|EAST|EASST|DAVT|ChST|CXT|CVT|CST|COT|CLT|CLST|CKT|CHAST|CHADT|CET|CEST|CDT|CCT|CAT|CAST|BTT|BST|BRT|BRST|BOT|BNT|AZT|AZST|AZOT|AZOST|AWST|AWDT|AST|ART|AQTT|ANAT|ANAST|AMT|AMST|ALMT|AKST|AKDT|AFT|AEST|AEDT|ADT|ACST|ACDT)\\b"
]
, prod = \tokens -> case tokens of
(Token Time td:
Token RegexMatch (GroupMatch (tz:_)):
_) -> Token Time <$> inTimezone tz td
_ -> Nothing
}
rules :: [Rule]
rules =
[ ruleAfternoon
, ruleAmanhPelaPartofday
, ruleAnoNovo
, ruleAntesDasTimeofday
, ruleDatetimeDatetimeInterval
, ruleDayOfMonthSt
, ruleDayofmonthDeNamedmonth
, ruleDayofweekSHourmin
, ruleDdddMonthinterval
, ruleDdmm
, ruleDdmmyyyy
, ruleDeDatetimeDatetimeInterval
, ruleDeYear
, ruleDentroDeDuration
, ruleDepoisDasTimeofday
, ruleDiaDayofmonthDeNamedmonth
, ruleDiaDayofmonthNonOrdinal
, ruleDiaDoTrabalhador
, ruleDimTimeDaMadrugada
, ruleDimTimeDaManha
, ruleDimTimeDaTarde
, ruleEmDuration
, ruleEntreDatetimeEDatetimeInterval
, ruleEntreDdEtDdMonthinterval
, ruleEsteCycle
, ruleEvening
, ruleFazemDuration
, ruleFinados
, ruleHhhmmTimeofday
, ruleHhmmMilitaryTimeofday
, ruleHourofdayAndRelativeMinutes
, ruleHourofdayAndRelativeMinutes2
, ruleHourofdayAndQuarter
, ruleHourofdayAndThreeQuarter
, ruleHourofdayAndHalf
, ruleHourofdayIntegerAsRelativeMinutes
, ruleHourofdayIntegerAsRelativeMinutes2
, ruleHourofdayQuarter
, ruleHourofdayHalf
, ruleHourofdayThreeQuarter
, ruleInThePartofday
, ruleIndependecia
, ruleIntegerParaAsHourofdayAsRelativeMinutes
, ruleIntegerParaAsHourofdayAsRelativeMinutes2
, ruleHalfParaAsHourofdayAsRelativeMinutes
, ruleQuarterParaAsHourofdayAsRelativeMinutes
, ruleThreeQuarterParaAsHourofdayAsRelativeMinutes
, ruleIntersect
, ruleIntersectByDaOrDe
, ruleLastTime
, ruleMidnight
, ruleMorning
, ruleNCycleAtras
, ruleNCycleProximoqueVem
, ruleNPassadosCycle
, ruleNProximasCycle
, ruleNamedday
, ruleNamedday2
, ruleNamedday3
, ruleNamedday4
, ruleNamedday5
, ruleNamedday6
, ruleNamedday7
, ruleNamedmonth
, ruleNamedmonth10
, ruleNamedmonth11
, ruleNamedmonth12
, ruleNamedmonth2
, ruleNamedmonth3
, ruleNamedmonth4
, ruleNamedmonth5
, ruleNamedmonth6
, ruleNamedmonth7
, ruleNamedmonth8
, ruleNamedmonth9
, ruleNamedmonthnameddayNext
, ruleNamedmonthnameddayPast
, ruleNaoDate
, ruleNatal
, ruleNextTime
, ruleCycleQueVem
, ruleProximoCycle
, ruleNoon
, ruleNossaSenhoraAparecida
, ruleNow
, ruleCycleAntesDeTime
, ruleCyclePassado
, rulePartofdayDessaSemana
, rulePassadosNCycle
, ruleProclamaoDaRepblica
, ruleProximasNCycle
, ruleRightNow
, ruleSHourminTimeofday
, ruleSHourmintimeofday
, ruleSTimeofday
, ruleSeason
, ruleSeason2
, ruleSeason3
, ruleSeason4
, ruleTheDayAfterTomorrow
, ruleTheDayBeforeYesterday
, ruleThisPartofday
, ruleThisTime
, ruleThisnextDayofweek
, ruleTimeofdayAmpm
, ruleTimeofdayHoras
, ruleTimeofdayLatent
, ruleTimeofdayPartofday
, ruleTiradentes
, ruleTomorrow
, ruleTwoTimeTokensSeparatedBy
, ruleTwoTimeTokensSeparatedBy2
, ruleUltimoTime
, ruleVesperaDeAnoNovo
, ruleWeekend
, ruleYear
, ruleYearLatent
, ruleYearLatent2
, ruleYesterday
, ruleYyyymmdd
, ruleTimezone
]
|
rfranek/duckling
|
Duckling/Time/PT/Rules.hs
|
Haskell
|
bsd-3-clause
| 40,248
|
-----------------------------------------------------------------------------
--
-- GHCi Interactive debugging commands
--
-- Pepe Iborra (supported by Google SoC) 2006
--
-- ToDo: lots of violation of layering here. This module should
-- decide whether it is above the GHC API (import GHC and nothing
-- else) or below it.
--
-----------------------------------------------------------------------------
module Debugger (pprintClosureCommand, showTerm, pprTypeAndContents) where
import Linker
import RtClosureInspect
import GhcMonad
import HscTypes
import Id
import Name
import Var hiding ( varName )
import VarSet
import UniqSupply
import Type
import Kind
import GHC
import Outputable
import PprTyThing
import MonadUtils
import DynFlags
import Exception
import Control.Monad
import Data.List
import Data.Maybe
import Data.IORef
import GHC.Exts
-------------------------------------
-- | The :print & friends commands
-------------------------------------
pprintClosureCommand :: GhcMonad m => Bool -> Bool -> String -> m ()
pprintClosureCommand bindThings force str = do
tythings <- (catMaybes . concat) `liftM`
mapM (\w -> GHC.parseName w >>=
mapM GHC.lookupName)
(words str)
let ids = [id | AnId id <- tythings]
-- Obtain the terms and the recovered type information
(subst, terms) <- mapAccumLM go emptyTvSubst ids
-- Apply the substitutions obtained after recovering the types
modifySession $ \hsc_env ->
hsc_env{hsc_IC = substInteractiveContext (hsc_IC hsc_env) subst}
-- Finally, print the Terms
unqual <- GHC.getPrintUnqual
docterms <- mapM showTerm terms
dflags <- getDynFlags
liftIO $ (printOutputForUser dflags unqual . vcat)
(zipWith (\id docterm -> ppr id <+> char '=' <+> docterm)
ids
docterms)
where
-- Do the obtainTerm--bindSuspensions-computeSubstitution dance
go :: GhcMonad m => TvSubst -> Id -> m (TvSubst, Term)
go subst id = do
let id' = id `setIdType` substTy subst (idType id)
term_ <- GHC.obtainTermFromId maxBound force id'
term <- tidyTermTyVars term_
term' <- if bindThings &&
False == isUnliftedTypeKind (termType term)
then bindSuspensions term
else return term
-- Before leaving, we compare the type obtained to see if it's more specific
-- Then, we extract a substitution,
-- mapping the old tyvars to the reconstructed types.
let reconstructed_type = termType term
hsc_env <- getSession
case (improveRTTIType hsc_env (idType id) (reconstructed_type)) of
Nothing -> return (subst, term')
Just subst' -> do { traceOptIf Opt_D_dump_rtti
(fsep $ [text "RTTI Improvement for", ppr id,
text "is the substitution:" , ppr subst'])
; return (subst `unionTvSubst` subst', term')}
tidyTermTyVars :: GhcMonad m => Term -> m Term
tidyTermTyVars t =
withSession $ \hsc_env -> do
let env_tvs = tyThingsTyVars $ ic_tythings $ hsc_IC hsc_env
my_tvs = termTyVars t
tvs = env_tvs `minusVarSet` my_tvs
tyvarOccName = nameOccName . tyVarName
tidyEnv = (initTidyOccEnv (map tyvarOccName (varSetElems tvs))
, env_tvs `intersectVarSet` my_tvs)
return$ mapTermType (snd . tidyOpenType tidyEnv) t
-- | Give names, and bind in the interactive environment, to all the suspensions
-- included (inductively) in a term
bindSuspensions :: GhcMonad m => Term -> m Term
bindSuspensions t = do
hsc_env <- getSession
inScope <- GHC.getBindings
let ictxt = hsc_IC hsc_env
prefix = "_t"
alreadyUsedNames = map (occNameString . nameOccName . getName) inScope
availNames = map ((prefix++) . show) [(1::Int)..] \\ alreadyUsedNames
availNames_var <- liftIO $ newIORef availNames
(t', stuff) <- liftIO $ foldTerm (nameSuspensionsAndGetInfos availNames_var) t
let (names, tys, hvals) = unzip3 stuff
let ids = [ mkVanillaGlobal name ty
| (name,ty) <- zip names tys]
new_ic = extendInteractiveContext ictxt (map AnId ids)
liftIO $ extendLinkEnv (zip names hvals)
modifySession $ \_ -> hsc_env {hsc_IC = new_ic }
return t'
where
-- Processing suspensions. Give names and recopilate info
nameSuspensionsAndGetInfos :: IORef [String] ->
TermFold (IO (Term, [(Name,Type,HValue)]))
nameSuspensionsAndGetInfos freeNames = TermFold
{
fSuspension = doSuspension freeNames
, fTerm = \ty dc v tt -> do
tt' <- sequence tt
let (terms,names) = unzip tt'
return (Term ty dc v terms, concat names)
, fPrim = \ty n ->return (Prim ty n,[])
, fNewtypeWrap =
\ty dc t -> do
(term, names) <- t
return (NewtypeWrap ty dc term, names)
, fRefWrap = \ty t -> do
(term, names) <- t
return (RefWrap ty term, names)
}
doSuspension freeNames ct ty hval _name = do
name <- atomicModifyIORef freeNames (\x->(tail x, head x))
n <- newGrimName name
return (Suspension ct ty hval (Just n), [(n,ty,hval)])
-- A custom Term printer to enable the use of Show instances
showTerm :: GhcMonad m => Term -> m SDoc
showTerm term = do
dflags <- GHC.getSessionDynFlags
if gopt Opt_PrintEvldWithShow dflags
then cPprTerm (liftM2 (++) (\_y->[cPprShowable]) cPprTermBase) term
else cPprTerm cPprTermBase term
where
cPprShowable prec t@Term{ty=ty, val=val} =
if not (isFullyEvaluatedTerm t)
then return Nothing
else do
hsc_env <- getSession
dflags <- GHC.getSessionDynFlags
do
(new_env, bname) <- bindToFreshName hsc_env ty "showme"
setSession new_env
-- XXX: this tries to disable logging of errors
-- does this still do what it is intended to do
-- with the changed error handling and logging?
let noop_log _ _ _ _ _ = return ()
expr = "show " ++ showPpr dflags bname
_ <- GHC.setSessionDynFlags dflags{log_action=noop_log}
txt_ <- withExtendedLinkEnv [(bname, val)]
(GHC.compileExpr expr)
let myprec = 10 -- application precedence. TODO Infix constructors
let txt = unsafeCoerce# txt_
if not (null txt) then
return $ Just $ cparen (prec >= myprec && needsParens txt)
(text txt)
else return Nothing
`gfinally` do
setSession hsc_env
GHC.setSessionDynFlags dflags
cPprShowable prec NewtypeWrap{ty=new_ty,wrapped_term=t} =
cPprShowable prec t{ty=new_ty}
cPprShowable _ _ = return Nothing
needsParens ('"':_) = False -- some simple heuristics to see whether parens
-- are redundant in an arbitrary Show output
needsParens ('(':_) = False
needsParens txt = ' ' `elem` txt
bindToFreshName hsc_env ty userName = do
name <- newGrimName userName
let id = AnId $ mkVanillaGlobal name ty
new_ic = extendInteractiveContext (hsc_IC hsc_env) [id]
return (hsc_env {hsc_IC = new_ic }, name)
-- Create new uniques and give them sequentially numbered names
newGrimName :: MonadIO m => String -> m Name
newGrimName userName = do
us <- liftIO $ mkSplitUniqSupply 'b'
let unique = uniqFromSupply us
occname = mkOccName varName userName
name = mkInternalName unique occname noSrcSpan
return name
pprTypeAndContents :: GhcMonad m => Id -> m SDoc
pprTypeAndContents id = do
dflags <- GHC.getSessionDynFlags
let pefas = gopt Opt_PrintExplicitForalls dflags
pcontents = gopt Opt_PrintBindContents dflags
pprdId = (PprTyThing.pprTyThing pefas . AnId) id
if pcontents
then do
let depthBound = 100
-- If the value is an exception, make sure we catch it and
-- show the exception, rather than propagating the exception out.
e_term <- gtry $ GHC.obtainTermFromId depthBound False id
docs_term <- case e_term of
Right term -> showTerm term
Left exn -> return (text "*** Exception:" <+>
text (show (exn :: SomeException)))
return $ pprdId <+> equals <+> docs_term
else return pprdId
--------------------------------------------------------------
-- Utils
traceOptIf :: GhcMonad m => DumpFlag -> SDoc -> m ()
traceOptIf flag doc = do
dflags <- GHC.getSessionDynFlags
when (dopt flag dflags) $ liftIO $ printInfoForUser dflags alwaysQualify doc
|
ekmett/ghc
|
compiler/ghci/Debugger.hs
|
Haskell
|
bsd-3-clause
| 9,338
|
{-# LANGUAGE MultiParamTypeClasses, GeneralizedNewtypeDeriving #-}
{-# LANGUAGE FlexibleInstances, UndecidableInstances, Rank2Types #-}
module Control.Monad.Launcher
( Launcher
, setVersion, checkVersion
, withThreadIdDo, putThreadId, clunkTag
, withFileDo, withoutFileDo, putFile, clunkFile
) where
import Control.Concurrent (ThreadId)
import Control.Monad.Except(throwError)
import Control.Monad.State(get, put, modify)
import Data.Word (Word16, Word32)
import System.IO (Handle)
import qualified Data.Map as M
import Data.Accessor
import Data.Accessor.Tuple
import Control.Concurrent.MState (MState)
import Network.NineP.Server.File.Internal
import Network.NineP.Server.Error
import Network.NineP.Server.Utils
import qualified Network.NineP.Binary as B
type LauncherState s
= (Maybe String, M.Map Word32 (File' s), M.Map Word16 ThreadId)
type Launcher s a
= MState (LauncherState s) (NineP s) a
setVersion :: Handle -> Word16 -> Word32
-> Launcher s (Maybe String) -> Launcher s ()
setVersion h tag sz f =
do
mver <- f
case mver of
Nothing ->
sendRMsg h tag $ B.Rversion sz "unknown"
Just ver -> do
put (mver, M.empty, M.empty)
sendRMsg h tag $ B.Rversion sz ver
checkVersion :: Launcher s () -> Launcher s ()
checkVersion f =
do
(ver, _, _) <- get
if (ver == Nothing)
then throwError ErrProto
else f
withThreadIdDo :: Word16 -> (ThreadId -> Launcher s ()) -> Launcher s ()
withThreadIdDo tag f =
do
(_, _, mp) <- get
case M.lookup tag mp of
Just tid -> f tid
Nothing -> throwError ErrProto
putThreadId :: Word16 -> ThreadId -> Launcher s ()
putThreadId tag tid =
modify $ third3 ^: M.insert tag tid
clunkTag :: Word16 -> Launcher s ()
clunkTag tag =
modify $ third3 ^: M.delete tag
withFileDo :: Word32 -> (File' s -> Launcher s ()) -> Launcher s ()
withFileDo fid f =
do
(_, mp, _) <- get
case M.lookup fid mp of
Just file -> f file
Nothing -> throwError ErrFidUnknown
withoutFileDo :: Word32 -> (Launcher s ()) -> Launcher s ()
withoutFileDo fid f =
do
(_, mp, _) <- get
case M.lookup fid mp of
Just _ -> throwError ErrFidInUse
Nothing -> f
putFile :: Word32 -> File' s -> Launcher s ()
putFile fid file =
modify $ second3 ^: M.insert fid file
clunkFile :: Word32 -> Launcher s ()
clunkFile fid =
modify $ second3 ^: M.delete fid
|
Elemir/network-ninep
|
src/Control/Monad/Launcher.hs
|
Haskell
|
bsd-3-clause
| 2,446
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE MagicHash #-}
module Blip.Interpreter.HashTable.IntArray
( IntArray
, Elem
, elemMask
, primWordToElem
, elemToInt
, elemToInt#
, newArray
, readArray
, writeArray
, length
, toPtr
) where
------------------------------------------------------------------------------
-- import Control.Monad.ST
import Data.Bits
import qualified Data.Primitive.ByteArray as A
-- import Data.Primitive.Types (Addr (..))
import GHC.Exts
import GHC.Word
import Data.Word (Word8)
import Prelude hiding (length)
-- import Control.Monad.Primitive (RealWorld)
------------------------------------------------------------------------------
#ifdef BOUNDS_CHECKING
#define BOUNDS_MSG(sz,i) concat [ "[", __FILE__, ":", \
show (__LINE__ :: Int), \
"] bounds check exceeded: ", \
"size was ", show (sz), " i was ", show (i) ]
#define BOUNDS_CHECK(arr,i) let sz = (A.sizeofMutableByteArray (arr) \
`div` wordSizeInBytes) in \
if (i) < 0 || (i) >= sz \
then error (BOUNDS_MSG(sz,(i))) \
else return ()
#else
#define BOUNDS_CHECK(arr,i)
#endif
------------------------------------------------------------------------------
newtype IntArray = IA (A.MutableByteArray RealWorld)
type Elem = Word16
------------------------------------------------------------------------------
primWordToElem :: Word# -> Elem
primWordToElem = W16#
------------------------------------------------------------------------------
elemToInt :: Elem -> Int
elemToInt e = let !i# = elemToInt# e
in (I# i#)
------------------------------------------------------------------------------
elemToInt# :: Elem -> Int#
elemToInt# (W16# w#) = word2Int# w#
------------------------------------------------------------------------------
elemMask :: Int
elemMask = 0xffff
------------------------------------------------------------------------------
wordSizeInBytes :: Int
wordSizeInBytes = bitSize (0::Elem) `div` 8
------------------------------------------------------------------------------
-- | Cache line size, in bytes
cacheLineSize :: Int
cacheLineSize = 64
------------------------------------------------------------------------------
newArray :: Int -> IO IntArray
newArray n = do
let !sz = n * wordSizeInBytes
!arr <- A.newAlignedPinnedByteArray sz cacheLineSize
A.fillByteArray arr 0 sz 0
return $! IA arr
------------------------------------------------------------------------------
readArray :: IntArray -> Int -> IO Elem
readArray (IA a) idx = do
BOUNDS_CHECK(a,idx)
A.readByteArray a idx
------------------------------------------------------------------------------
writeArray :: IntArray -> Int -> Elem -> IO ()
writeArray (IA a) idx val = do
BOUNDS_CHECK(a,idx)
A.writeByteArray a idx val
------------------------------------------------------------------------------
length :: IntArray -> Int
length (IA a) = A.sizeofMutableByteArray a `div` wordSizeInBytes
------------------------------------------------------------------------------
toPtr :: IntArray -> Ptr Word8
toPtr (IA a) = A.mutableByteArrayContents a
{-
toPtr (IA a) = Ptr a#
where
!(Addr !a#) = A.mutableByteArrayContents a
-}
|
bjpop/blip
|
blipinterpreter/src/Blip/Interpreter/HashTable/IntArray.hs
|
Haskell
|
bsd-3-clause
| 3,680
|
{-|
Module : Idris.IBC
Description : Core representations and code to generate IBC files.
Copyright :
License : BSD3
Maintainer : The Idris Community.
-}
{-# LANGUAGE FlexibleInstances, TypeSynonymInstances #-}
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
module Idris.IBC (loadIBC, loadPkgIndex,
writeIBC, writePkgIndex,
hasValidIBCVersion, IBCPhase(..)) where
import Idris.AbsSyntax
import Idris.Core.Binary
import Idris.Core.CaseTree
import Idris.Core.Evaluate
import Idris.Core.TT
import Idris.DeepSeq
import Idris.Delaborate
import Idris.Docstrings (Docstring)
import qualified Idris.Docstrings as D
import Idris.Error
import Idris.Imports
import Idris.Options
import Idris.Output
import IRTS.System (getIdrisLibDir)
import Paths_idris
import qualified Cheapskate.Types as CT
import Codec.Archive.Zip
import Control.DeepSeq
import Control.Monad
import Control.Monad.State.Strict hiding (get, put)
import qualified Control.Monad.State.Strict as ST
import Data.Binary
import Data.ByteString.Lazy as B hiding (elem, length, map)
import Data.Functor
import Data.List as L
import Data.Maybe (catMaybes)
import qualified Data.Set as S
import qualified Data.Text as T
import Data.Vector.Binary
import Debug.Trace
import System.Directory
import System.FilePath
ibcVersion :: Word16
ibcVersion = 162
-- | When IBC is being loaded - we'll load different things (and omit
-- different structures/definitions) depending on which phase we're in.
data IBCPhase = IBC_Building -- ^ when building the module tree
| IBC_REPL Bool -- ^ when loading modules for the REPL Bool = True for top level module
deriving (Show, Eq)
data IBCFile = IBCFile {
ver :: Word16
, sourcefile :: FilePath
, ibc_reachablenames :: ![Name]
, ibc_imports :: ![(Bool, FilePath)]
, ibc_importdirs :: ![FilePath]
, ibc_sourcedirs :: ![FilePath]
, ibc_implicits :: ![(Name, [PArg])]
, ibc_fixes :: ![FixDecl]
, ibc_statics :: ![(Name, [Bool])]
, ibc_interfaces :: ![(Name, InterfaceInfo)]
, ibc_records :: ![(Name, RecordInfo)]
, ibc_implementations :: ![(Bool, Bool, Name, Name)]
, ibc_dsls :: ![(Name, DSL)]
, ibc_datatypes :: ![(Name, TypeInfo)]
, ibc_optimise :: ![(Name, OptInfo)]
, ibc_syntax :: ![Syntax]
, ibc_keywords :: ![String]
, ibc_objs :: ![(Codegen, FilePath)]
, ibc_libs :: ![(Codegen, String)]
, ibc_cgflags :: ![(Codegen, String)]
, ibc_dynamic_libs :: ![String]
, ibc_hdrs :: ![(Codegen, String)]
, ibc_totcheckfail :: ![(FC, String)]
, ibc_flags :: ![(Name, [FnOpt])]
, ibc_fninfo :: ![(Name, FnInfo)]
, ibc_cg :: ![(Name, CGInfo)]
, ibc_docstrings :: ![(Name, (Docstring D.DocTerm, [(Name, Docstring D.DocTerm)]))]
, ibc_moduledocs :: ![(Name, Docstring D.DocTerm)]
, ibc_transforms :: ![(Name, (Term, Term))]
, ibc_errRev :: ![(Term, Term)]
, ibc_errReduce :: ![Name]
, ibc_coercions :: ![Name]
, ibc_lineapps :: ![(FilePath, Int, PTerm)]
, ibc_namehints :: ![(Name, Name)]
, ibc_metainformation :: ![(Name, MetaInformation)]
, ibc_errorhandlers :: ![Name]
, ibc_function_errorhandlers :: ![(Name, Name, Name)] -- fn, arg, handler
, ibc_metavars :: ![(Name, (Maybe Name, Int, [Name], Bool, Bool))]
, ibc_patdefs :: ![(Name, ([([(Name, Term)], Term, Term)], [PTerm]))]
, ibc_postulates :: ![Name]
, ibc_externs :: ![(Name, Int)]
, ibc_parsedSpan :: !(Maybe FC)
, ibc_usage :: ![(Name, Int)]
, ibc_exports :: ![Name]
, ibc_autohints :: ![(Name, Name)]
, ibc_deprecated :: ![(Name, String)]
, ibc_defs :: ![(Name, Def)]
, ibc_total :: ![(Name, Totality)]
, ibc_injective :: ![(Name, Injectivity)]
, ibc_access :: ![(Name, Accessibility)]
, ibc_fragile :: ![(Name, String)]
, ibc_constraints :: ![(FC, UConstraint)]
}
deriving Show
{-!
deriving instance Binary IBCFile
!-}
initIBC :: IBCFile
initIBC = IBCFile ibcVersion "" [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] Nothing [] [] [] [] [] [] [] [] [] []
hasValidIBCVersion :: FilePath -> Idris Bool
hasValidIBCVersion fp = do
archiveFile <- runIO $ B.readFile fp
case toArchiveOrFail archiveFile of
Left _ -> return False
Right archive -> do ver <- getEntry 0 "ver" archive
return (ver == ibcVersion)
loadIBC :: Bool -- ^ True = reexport, False = make everything private
-> IBCPhase
-> FilePath -> Idris ()
loadIBC reexport phase fp
= do imps <- getImported
case lookup fp imps of
Nothing -> load True
Just p -> if (not p && reexport) then load False else return ()
where
load fullLoad = do
logIBC 1 $ "Loading ibc " ++ fp ++ " " ++ show reexport
archiveFile <- runIO $ B.readFile fp
case toArchiveOrFail archiveFile of
Left _ -> do
ifail $ fp ++ " isn't loadable, it may have an old ibc format.\n"
++ "Please clean and rebuild it."
Right archive -> do
if fullLoad
then process reexport phase archive fp
else unhide phase fp archive
addImported reexport fp
-- | Load an entire package from its index file
loadPkgIndex :: String -> Idris ()
loadPkgIndex pkg = do ddir <- runIO getIdrisLibDir
addImportDir (ddir </> pkg)
fp <- findPkgIndex pkg
loadIBC True IBC_Building fp
makeEntry :: (Binary b) => String -> [b] -> Maybe Entry
makeEntry name val = if L.null val
then Nothing
else Just $ toEntry name 0 (encode val)
entries :: IBCFile -> [Entry]
entries i = catMaybes [Just $ toEntry "ver" 0 (encode $ ver i),
makeEntry "sourcefile" (sourcefile i),
makeEntry "ibc_imports" (ibc_imports i),
makeEntry "ibc_importdirs" (ibc_importdirs i),
makeEntry "ibc_sourcedirs" (ibc_sourcedirs i),
makeEntry "ibc_implicits" (ibc_implicits i),
makeEntry "ibc_fixes" (ibc_fixes i),
makeEntry "ibc_statics" (ibc_statics i),
makeEntry "ibc_interfaces" (ibc_interfaces i),
makeEntry "ibc_records" (ibc_records i),
makeEntry "ibc_implementations" (ibc_implementations i),
makeEntry "ibc_dsls" (ibc_dsls i),
makeEntry "ibc_datatypes" (ibc_datatypes i),
makeEntry "ibc_optimise" (ibc_optimise i),
makeEntry "ibc_syntax" (ibc_syntax i),
makeEntry "ibc_keywords" (ibc_keywords i),
makeEntry "ibc_objs" (ibc_objs i),
makeEntry "ibc_libs" (ibc_libs i),
makeEntry "ibc_cgflags" (ibc_cgflags i),
makeEntry "ibc_dynamic_libs" (ibc_dynamic_libs i),
makeEntry "ibc_hdrs" (ibc_hdrs i),
makeEntry "ibc_totcheckfail" (ibc_totcheckfail i),
makeEntry "ibc_flags" (ibc_flags i),
makeEntry "ibc_fninfo" (ibc_fninfo i),
makeEntry "ibc_cg" (ibc_cg i),
makeEntry "ibc_docstrings" (ibc_docstrings i),
makeEntry "ibc_moduledocs" (ibc_moduledocs i),
makeEntry "ibc_transforms" (ibc_transforms i),
makeEntry "ibc_errRev" (ibc_errRev i),
makeEntry "ibc_errReduce" (ibc_errReduce i),
makeEntry "ibc_coercions" (ibc_coercions i),
makeEntry "ibc_lineapps" (ibc_lineapps i),
makeEntry "ibc_namehints" (ibc_namehints i),
makeEntry "ibc_metainformation" (ibc_metainformation i),
makeEntry "ibc_errorhandlers" (ibc_errorhandlers i),
makeEntry "ibc_function_errorhandlers" (ibc_function_errorhandlers i),
makeEntry "ibc_metavars" (ibc_metavars i),
makeEntry "ibc_patdefs" (ibc_patdefs i),
makeEntry "ibc_postulates" (ibc_postulates i),
makeEntry "ibc_externs" (ibc_externs i),
toEntry "ibc_parsedSpan" 0 . encode <$> ibc_parsedSpan i,
makeEntry "ibc_usage" (ibc_usage i),
makeEntry "ibc_exports" (ibc_exports i),
makeEntry "ibc_autohints" (ibc_autohints i),
makeEntry "ibc_deprecated" (ibc_deprecated i),
makeEntry "ibc_defs" (ibc_defs i),
makeEntry "ibc_total" (ibc_total i),
makeEntry "ibc_injective" (ibc_injective i),
makeEntry "ibc_access" (ibc_access i),
makeEntry "ibc_fragile" (ibc_fragile i)]
-- TODO: Put this back in shortly after minimising/pruning constraints
-- makeEntry "ibc_constraints" (ibc_constraints i)]
writeArchive :: FilePath -> IBCFile -> Idris ()
writeArchive fp i = do let a = L.foldl (\x y -> addEntryToArchive y x) emptyArchive (entries i)
runIO $ B.writeFile fp (fromArchive a)
writeIBC :: FilePath -> FilePath -> Idris ()
writeIBC src f
= do
logIBC 2 $ "Writing IBC for: " ++ show f
iReport 2 $ "Writing IBC for: " ++ show f
i <- getIState
-- case (Data.List.map fst (idris_metavars i)) \\ primDefs of
-- (_:_) -> ifail "Can't write ibc when there are unsolved metavariables"
-- [] -> return ()
resetNameIdx
ibcf <- mkIBC (ibc_write i) (initIBC { sourcefile = src })
idrisCatch (do runIO $ createDirectoryIfMissing True (dropFileName f)
writeArchive f ibcf
logIBC 2 "Written")
(\c -> do logIBC 2 $ "Failed " ++ pshow i c)
return ()
-- | Write a package index containing all the imports in the current
-- IState Used for ':search' of an entire package, to ensure
-- everything is loaded.
writePkgIndex :: FilePath -> Idris ()
writePkgIndex f
= do i <- getIState
let imps = map (\ (x, y) -> (True, x)) $ idris_imported i
logIBC 2 $ "Writing package index " ++ show f ++ " including\n" ++
show (map snd imps)
resetNameIdx
let ibcf = initIBC { ibc_imports = imps }
idrisCatch (do runIO $ createDirectoryIfMissing True (dropFileName f)
writeArchive f ibcf
logIBC 2 "Written")
(\c -> do logIBC 2 $ "Failed " ++ pshow i c)
return ()
mkIBC :: [IBCWrite] -> IBCFile -> Idris IBCFile
mkIBC [] f = return f
mkIBC (i:is) f = do ist <- getIState
logIBC 5 $ show i ++ " " ++ show (L.length is)
f' <- ibc ist i f
mkIBC is f'
ibc :: IState -> IBCWrite -> IBCFile -> Idris IBCFile
ibc i (IBCFix d) f = return f { ibc_fixes = d : ibc_fixes f }
ibc i (IBCImp n) f = case lookupCtxtExact n (idris_implicits i) of
Just v -> return f { ibc_implicits = (n,v): ibc_implicits f }
_ -> ifail "IBC write failed"
ibc i (IBCStatic n) f
= case lookupCtxtExact n (idris_statics i) of
Just v -> return f { ibc_statics = (n,v): ibc_statics f }
_ -> ifail "IBC write failed"
ibc i (IBCInterface n) f
= case lookupCtxtExact n (idris_interfaces i) of
Just v -> return f { ibc_interfaces = (n,v): ibc_interfaces f }
_ -> ifail "IBC write failed"
ibc i (IBCRecord n) f
= case lookupCtxtExact n (idris_records i) of
Just v -> return f { ibc_records = (n,v): ibc_records f }
_ -> ifail "IBC write failed"
ibc i (IBCImplementation int res n ins) f
= return f { ibc_implementations = (int, res, n, ins) : ibc_implementations f }
ibc i (IBCDSL n) f
= case lookupCtxtExact n (idris_dsls i) of
Just v -> return f { ibc_dsls = (n,v): ibc_dsls f }
_ -> ifail "IBC write failed"
ibc i (IBCData n) f
= case lookupCtxtExact n (idris_datatypes i) of
Just v -> return f { ibc_datatypes = (n,v): ibc_datatypes f }
_ -> ifail "IBC write failed"
ibc i (IBCOpt n) f = case lookupCtxtExact n (idris_optimisation i) of
Just v -> return f { ibc_optimise = (n,v): ibc_optimise f }
_ -> ifail "IBC write failed"
ibc i (IBCSyntax n) f = return f { ibc_syntax = n : ibc_syntax f }
ibc i (IBCKeyword n) f = return f { ibc_keywords = n : ibc_keywords f }
ibc i (IBCImport n) f = return f { ibc_imports = n : ibc_imports f }
ibc i (IBCImportDir n) f = return f { ibc_importdirs = n : ibc_importdirs f }
ibc i (IBCSourceDir n) f = return f { ibc_sourcedirs = n : ibc_sourcedirs f }
ibc i (IBCObj tgt n) f = return f { ibc_objs = (tgt, n) : ibc_objs f }
ibc i (IBCLib tgt n) f = return f { ibc_libs = (tgt, n) : ibc_libs f }
ibc i (IBCCGFlag tgt n) f = return f { ibc_cgflags = (tgt, n) : ibc_cgflags f }
ibc i (IBCDyLib n) f = return f {ibc_dynamic_libs = n : ibc_dynamic_libs f }
ibc i (IBCHeader tgt n) f = return f { ibc_hdrs = (tgt, n) : ibc_hdrs f }
ibc i (IBCDef n) f
= do f' <- case lookupDefExact n (tt_ctxt i) of
Just v -> return f { ibc_defs = (n,v) : ibc_defs f }
_ -> ifail "IBC write failed"
case lookupCtxtExact n (idris_patdefs i) of
Just v -> return f' { ibc_patdefs = (n,v) : ibc_patdefs f }
_ -> return f' -- Not a pattern definition
ibc i (IBCDoc n) f = case lookupCtxtExact n (idris_docstrings i) of
Just v -> return f { ibc_docstrings = (n,v) : ibc_docstrings f }
_ -> ifail "IBC write failed"
ibc i (IBCCG n) f = case lookupCtxtExact n (idris_callgraph i) of
Just v -> return f { ibc_cg = (n,v) : ibc_cg f }
_ -> ifail "IBC write failed"
ibc i (IBCCoercion n) f = return f { ibc_coercions = n : ibc_coercions f }
ibc i (IBCAccess n a) f = return f { ibc_access = (n,a) : ibc_access f }
ibc i (IBCFlags n) f
= case lookupCtxtExact n (idris_flags i) of
Just a -> return f { ibc_flags = (n,a): ibc_flags f }
_ -> ifail "IBC write failed"
ibc i (IBCFnInfo n a) f = return f { ibc_fninfo = (n,a) : ibc_fninfo f }
ibc i (IBCTotal n a) f = return f { ibc_total = (n,a) : ibc_total f }
ibc i (IBCInjective n a) f = return f { ibc_injective = (n,a) : ibc_injective f }
ibc i (IBCTrans n t) f = return f { ibc_transforms = (n, t) : ibc_transforms f }
ibc i (IBCErrRev t) f = return f { ibc_errRev = t : ibc_errRev f }
ibc i (IBCErrReduce t) f = return f { ibc_errReduce = t : ibc_errReduce f }
ibc i (IBCLineApp fp l t) f
= return f { ibc_lineapps = (fp,l,t) : ibc_lineapps f }
ibc i (IBCNameHint (n, ty)) f
= return f { ibc_namehints = (n, ty) : ibc_namehints f }
ibc i (IBCMetaInformation n m) f = return f { ibc_metainformation = (n,m) : ibc_metainformation f }
ibc i (IBCErrorHandler n) f = return f { ibc_errorhandlers = n : ibc_errorhandlers f }
ibc i (IBCFunctionErrorHandler fn a n) f =
return f { ibc_function_errorhandlers = (fn, a, n) : ibc_function_errorhandlers f }
ibc i (IBCMetavar n) f =
case lookup n (idris_metavars i) of
Nothing -> return f
Just t -> return f { ibc_metavars = (n, t) : ibc_metavars f }
ibc i (IBCPostulate n) f = return f { ibc_postulates = n : ibc_postulates f }
ibc i (IBCExtern n) f = return f { ibc_externs = n : ibc_externs f }
ibc i (IBCTotCheckErr fc err) f = return f { ibc_totcheckfail = (fc, err) : ibc_totcheckfail f }
ibc i (IBCParsedRegion fc) f = return f { ibc_parsedSpan = Just fc }
ibc i (IBCModDocs n) f = case lookupCtxtExact n (idris_moduledocs i) of
Just v -> return f { ibc_moduledocs = (n,v) : ibc_moduledocs f }
_ -> ifail "IBC write failed"
ibc i (IBCUsage n) f = return f { ibc_usage = n : ibc_usage f }
ibc i (IBCExport n) f = return f { ibc_exports = n : ibc_exports f }
ibc i (IBCAutoHint n h) f = return f { ibc_autohints = (n, h) : ibc_autohints f }
ibc i (IBCDeprecate n r) f = return f { ibc_deprecated = (n, r) : ibc_deprecated f }
ibc i (IBCFragile n r) f = return f { ibc_fragile = (n,r) : ibc_fragile f }
ibc i (IBCConstraint fc u) f = return f { ibc_constraints = (fc, u) : ibc_constraints f }
getEntry :: (Binary b, NFData b) => b -> FilePath -> Archive -> Idris b
getEntry alt f a = case findEntryByPath f a of
Nothing -> return alt
Just e -> return $! (force . decode . fromEntry) e
unhide :: IBCPhase -> FilePath -> Archive -> Idris ()
unhide phase fp ar = do
processImports True phase fp ar
processAccess True phase ar
process :: Bool -- ^ Reexporting
-> IBCPhase
-> Archive -> FilePath -> Idris ()
process reexp phase archive fn = do
ver <- getEntry 0 "ver" archive
when (ver /= ibcVersion) $ do
logIBC 2 "ibc out of date"
let e = if ver < ibcVersion
then "an earlier" else "a later"
ldir <- runIO $ getIdrisLibDir
let start = if ldir `L.isPrefixOf` fn
then "This external module"
else "This module"
let end = case L.stripPrefix ldir fn of
Nothing -> "Please clean and rebuild."
Just ploc -> unwords ["Please reinstall:", L.head $ splitDirectories ploc]
ifail $ unlines [ unwords ["Incompatible ibc version for:", show fn]
, unwords [start
, "was built with"
, e
, "version of Idris."]
, end
]
source <- getEntry "" "sourcefile" archive
srcok <- runIO $ doesFileExist source
when srcok $ timestampOlder source fn
processImportDirs archive
processSourceDirs archive
processImports reexp phase fn archive
processImplicits archive
processInfix archive
processStatics archive
processInterfaces archive
processRecords archive
processImplementations archive
processDSLs archive
processDatatypes archive
processOptimise archive
processSyntax archive
processKeywords archive
processObjectFiles fn archive
processLibs archive
processCodegenFlags archive
processDynamicLibs archive
processHeaders archive
processPatternDefs archive
processFlags archive
processFnInfo archive
processTotalityCheckError archive
processCallgraph archive
processDocs archive
processModuleDocs archive
processCoercions archive
processTransforms archive
processErrRev archive
processErrReduce archive
processLineApps archive
processNameHints archive
processMetaInformation archive
processErrorHandlers archive
processFunctionErrorHandlers archive
processMetaVars archive
processPostulates archive
processExterns archive
processParsedSpan archive
processUsage archive
processExports archive
processAutoHints archive
processDeprecate archive
processDefs archive
processTotal archive
processInjective archive
processAccess reexp phase archive
processFragile archive
processConstraints archive
timestampOlder :: FilePath -> FilePath -> Idris ()
timestampOlder src ibc = do
srct <- runIO $ getModificationTime src
ibct <- runIO $ getModificationTime ibc
if (srct > ibct)
then ifail $ unlines [ "Module needs reloading:"
, unwords ["\tSRC :", show src]
, unwords ["\tModified at:", show srct]
, unwords ["\tIBC :", show ibc]
, unwords ["\tModified at:", show ibct]
]
else return ()
processPostulates :: Archive -> Idris ()
processPostulates ar = do
ns <- getEntry [] "ibc_postulates" ar
updateIState (\i -> i { idris_postulates = idris_postulates i `S.union` S.fromList ns })
processExterns :: Archive -> Idris ()
processExterns ar = do
ns <- getEntry [] "ibc_externs" ar
updateIState (\i -> i{ idris_externs = idris_externs i `S.union` S.fromList ns })
processParsedSpan :: Archive -> Idris ()
processParsedSpan ar = do
fc <- getEntry Nothing "ibc_parsedSpan" ar
updateIState (\i -> i { idris_parsedSpan = fc })
processUsage :: Archive -> Idris ()
processUsage ar = do
ns <- getEntry [] "ibc_usage" ar
updateIState (\i -> i { idris_erasureUsed = ns ++ idris_erasureUsed i })
processExports :: Archive -> Idris ()
processExports ar = do
ns <- getEntry [] "ibc_exports" ar
updateIState (\i -> i { idris_exports = ns ++ idris_exports i })
processAutoHints :: Archive -> Idris ()
processAutoHints ar = do
ns <- getEntry [] "ibc_autohints" ar
mapM_ (\(n,h) -> addAutoHint n h) ns
processDeprecate :: Archive -> Idris ()
processDeprecate ar = do
ns <- getEntry [] "ibc_deprecated" ar
mapM_ (\(n,reason) -> addDeprecated n reason) ns
processFragile :: Archive -> Idris ()
processFragile ar = do
ns <- getEntry [] "ibc_fragile" ar
mapM_ (\(n,reason) -> addFragile n reason) ns
processConstraints :: Archive -> Idris ()
processConstraints ar = do
cs <- getEntry [] "ibc_constraints" ar
mapM_ (\ (fc, c) -> addConstraints fc (0, [c])) cs
processImportDirs :: Archive -> Idris ()
processImportDirs ar = do
fs <- getEntry [] "ibc_importdirs" ar
mapM_ addImportDir fs
processSourceDirs :: Archive -> Idris ()
processSourceDirs ar = do
fs <- getEntry [] "ibc_sourcedirs" ar
mapM_ addSourceDir fs
processImports :: Bool -> IBCPhase -> FilePath -> Archive -> Idris ()
processImports reexp phase fname ar = do
fs <- getEntry [] "ibc_imports" ar
mapM_ (\(re, f) -> do
i <- getIState
ibcsd <- valIBCSubDir i
ids <- rankedImportDirs fname
putIState (i { imported = f : imported i })
let phase' = case phase of
IBC_REPL _ -> IBC_REPL False
p -> p
fp <- findIBC ids ibcsd f
case fp of
Nothing -> do logIBC 2 $ "Failed to load ibc " ++ f
Just fn -> do loadIBC (reexp && re) phase' fn) fs
processImplicits :: Archive -> Idris ()
processImplicits ar = do
imps <- getEntry [] "ibc_implicits" ar
mapM_ (\ (n, imp) -> do
i <- getIState
case lookupDefAccExact n False (tt_ctxt i) of
Just (n, Hidden) -> return ()
Just (n, Private) -> return ()
_ -> putIState (i { idris_implicits = addDef n imp (idris_implicits i) })) imps
processInfix :: Archive -> Idris ()
processInfix ar = do
f <- getEntry [] "ibc_fixes" ar
updateIState (\i -> i { idris_infixes = sort $ f ++ idris_infixes i })
processStatics :: Archive -> Idris ()
processStatics ar = do
ss <- getEntry [] "ibc_statics" ar
mapM_ (\ (n, s) ->
updateIState (\i -> i { idris_statics = addDef n s (idris_statics i) })) ss
processInterfaces :: Archive -> Idris ()
processInterfaces ar = do
cs <- getEntry [] "ibc_interfaces" ar
mapM_ (\ (n, c) -> do
i <- getIState
-- Don't lose implementations from previous IBCs, which
-- could have loaded in any order
let is = case lookupCtxtExact n (idris_interfaces i) of
Just ci -> interface_implementations ci
_ -> []
let c' = c { interface_implementations = interface_implementations c ++ is }
putIState (i { idris_interfaces = addDef n c' (idris_interfaces i) })) cs
processRecords :: Archive -> Idris ()
processRecords ar = do
rs <- getEntry [] "ibc_records" ar
mapM_ (\ (n, r) ->
updateIState (\i -> i { idris_records = addDef n r (idris_records i) })) rs
processImplementations :: Archive -> Idris ()
processImplementations ar = do
cs <- getEntry [] "ibc_implementations" ar
mapM_ (\ (i, res, n, ins) -> addImplementation i res n ins) cs
processDSLs :: Archive -> Idris ()
processDSLs ar = do
cs <- getEntry [] "ibc_dsls" ar
mapM_ (\ (n, c) -> updateIState (\i ->
i { idris_dsls = addDef n c (idris_dsls i) })) cs
processDatatypes :: Archive -> Idris ()
processDatatypes ar = do
cs <- getEntry [] "ibc_datatypes" ar
mapM_ (\ (n, c) -> updateIState (\i ->
i { idris_datatypes = addDef n c (idris_datatypes i) })) cs
processOptimise :: Archive -> Idris ()
processOptimise ar = do
cs <- getEntry [] "ibc_optimise" ar
mapM_ (\ (n, c) -> updateIState (\i ->
i { idris_optimisation = addDef n c (idris_optimisation i) })) cs
processSyntax :: Archive -> Idris ()
processSyntax ar = do
s <- getEntry [] "ibc_syntax" ar
updateIState (\i -> i { syntax_rules = updateSyntaxRules s (syntax_rules i) })
processKeywords :: Archive -> Idris ()
processKeywords ar = do
k <- getEntry [] "ibc_keywords" ar
updateIState (\i -> i { syntax_keywords = k ++ syntax_keywords i })
processObjectFiles :: FilePath -> Archive -> Idris ()
processObjectFiles fn ar = do
os <- getEntry [] "ibc_objs" ar
mapM_ (\ (cg, obj) -> do
dirs <- rankedImportDirs fn
o <- runIO $ findInPath dirs obj
addObjectFile cg o) os
processLibs :: Archive -> Idris ()
processLibs ar = do
ls <- getEntry [] "ibc_libs" ar
mapM_ (uncurry addLib) ls
processCodegenFlags :: Archive -> Idris ()
processCodegenFlags ar = do
ls <- getEntry [] "ibc_cgflags" ar
mapM_ (uncurry addFlag) ls
processDynamicLibs :: Archive -> Idris ()
processDynamicLibs ar = do
ls <- getEntry [] "ibc_dynamic_libs" ar
res <- mapM (addDyLib . return) ls
mapM_ checkLoad res
where
checkLoad (Left _) = return ()
checkLoad (Right err) = ifail err
processHeaders :: Archive -> Idris ()
processHeaders ar = do
hs <- getEntry [] "ibc_hdrs" ar
mapM_ (uncurry addHdr) hs
processPatternDefs :: Archive -> Idris ()
processPatternDefs ar = do
ds <- getEntry [] "ibc_patdefs" ar
mapM_ (\ (n, d) -> updateIState (\i ->
i { idris_patdefs = addDef n (force d) (idris_patdefs i) })) ds
processDefs :: Archive -> Idris ()
processDefs ar = do
ds <- getEntry [] "ibc_defs" ar
mapM_ (\ (n, d) -> do
d' <- updateDef d
case d' of
TyDecl _ _ -> return ()
_ -> do
logIBC 2 $ "SOLVING " ++ show n
solveDeferred emptyFC n
updateIState (\i -> i { tt_ctxt = addCtxtDef n d' (tt_ctxt i) })) ds
where
updateDef (CaseOp c t args o s cd) = do
o' <- mapM updateOrig o
cd' <- updateCD cd
return $ CaseOp c t args o' s cd'
updateDef t = return t
updateOrig (Left t) = liftM Left (update t)
updateOrig (Right (l, r)) = do
l' <- update l
r' <- update r
return $ Right (l', r')
updateCD (CaseDefs (cs, c) (rs, r)) = do
c' <- updateSC c
r' <- updateSC r
return $ CaseDefs (cs, c') (rs, r')
updateSC (Case t n alts) = do
alts' <- mapM updateAlt alts
return (Case t n alts')
updateSC (ProjCase t alts) = do
alts' <- mapM updateAlt alts
return (ProjCase t alts')
updateSC (STerm t) = do
t' <- update t
return (STerm t')
updateSC c = return c
updateAlt (ConCase n i ns t) = do
t' <- updateSC t
return (ConCase n i ns t')
updateAlt (FnCase n ns t) = do
t' <- updateSC t
return (FnCase n ns t')
updateAlt (ConstCase c t) = do
t' <- updateSC t
return (ConstCase c t')
updateAlt (SucCase n t) = do
t' <- updateSC t
return (SucCase n t')
updateAlt (DefaultCase t) = do
t' <- updateSC t
return (DefaultCase t')
-- We get a lot of repetition in sub terms and can save a fair chunk
-- of memory if we make sure they're shared. addTT looks for a term
-- and returns it if it exists already, while also keeping stats of
-- how many times a subterm is repeated.
update t = do
tm <- addTT t
case tm of
Nothing -> update' t
Just t' -> return t'
update' (P t n ty) = do
n' <- getSymbol n
return $ P t n' ty
update' (App s f a) = liftM2 (App s) (update' f) (update' a)
update' (Bind n b sc) = do
b' <- updateB b
sc' <- update sc
return $ Bind n b' sc'
where
updateB (Let t v) = liftM2 Let (update' t) (update' v)
updateB b = do
ty' <- update' (binderTy b)
return (b { binderTy = ty' })
update' (Proj t i) = do
t' <- update' t
return $ Proj t' i
update' t = return t
processDocs :: Archive -> Idris ()
processDocs ar = do
ds <- getEntry [] "ibc_docstrings" ar
mapM_ (\(n, a) -> addDocStr n (fst a) (snd a)) ds
processModuleDocs :: Archive -> Idris ()
processModuleDocs ar = do
ds <- getEntry [] "ibc_moduledocs" ar
mapM_ (\ (n, d) -> updateIState (\i ->
i { idris_moduledocs = addDef n d (idris_moduledocs i) })) ds
processAccess :: Bool -- ^ Reexporting?
-> IBCPhase
-> Archive -> Idris ()
processAccess reexp phase ar = do
ds <- getEntry [] "ibc_access" ar
mapM_ (\ (n, a_in) -> do
let a = if reexp then a_in else Hidden
logIBC 3 $ "Setting " ++ show (a, n) ++ " to " ++ show a
updateIState (\i -> i { tt_ctxt = setAccess n a (tt_ctxt i) })
if (not reexp)
then do
logIBC 2 $ "Not exporting " ++ show n
setAccessibility n Hidden
else logIBC 2 $ "Exporting " ++ show n
-- Everything should be available at the REPL from
-- things imported publicly
when (phase == IBC_REPL True) $ setAccessibility n Public) ds
processFlags :: Archive -> Idris ()
processFlags ar = do
ds <- getEntry [] "ibc_flags" ar
mapM_ (\ (n, a) -> setFlags n a) ds
processFnInfo :: Archive -> Idris ()
processFnInfo ar = do
ds <- getEntry [] "ibc_fninfo" ar
mapM_ (\ (n, a) -> setFnInfo n a) ds
processTotal :: Archive -> Idris ()
processTotal ar = do
ds <- getEntry [] "ibc_total" ar
mapM_ (\ (n, a) -> updateIState (\i -> i { tt_ctxt = setTotal n a (tt_ctxt i) })) ds
processInjective :: Archive -> Idris ()
processInjective ar = do
ds <- getEntry [] "ibc_injective" ar
mapM_ (\ (n, a) -> updateIState (\i -> i { tt_ctxt = setInjective n a (tt_ctxt i) })) ds
processTotalityCheckError :: Archive -> Idris ()
processTotalityCheckError ar = do
es <- getEntry [] "ibc_totcheckfail" ar
updateIState (\i -> i { idris_totcheckfail = idris_totcheckfail i ++ es })
processCallgraph :: Archive -> Idris ()
processCallgraph ar = do
ds <- getEntry [] "ibc_cg" ar
mapM_ (\ (n, a) -> addToCG n a) ds
processCoercions :: Archive -> Idris ()
processCoercions ar = do
ns <- getEntry [] "ibc_coercions" ar
mapM_ (\ n -> addCoercion n) ns
processTransforms :: Archive -> Idris ()
processTransforms ar = do
ts <- getEntry [] "ibc_transforms" ar
mapM_ (\ (n, t) -> addTrans n t) ts
processErrRev :: Archive -> Idris ()
processErrRev ar = do
ts <- getEntry [] "ibc_errRev" ar
mapM_ addErrRev ts
processErrReduce :: Archive -> Idris ()
processErrReduce ar = do
ts <- getEntry [] "ibc_errReduce" ar
mapM_ addErrReduce ts
processLineApps :: Archive -> Idris ()
processLineApps ar = do
ls <- getEntry [] "ibc_lineapps" ar
mapM_ (\ (f, i, t) -> addInternalApp f i t) ls
processNameHints :: Archive -> Idris ()
processNameHints ar = do
ns <- getEntry [] "ibc_namehints" ar
mapM_ (\ (n, ty) -> addNameHint n ty) ns
processMetaInformation :: Archive -> Idris ()
processMetaInformation ar = do
ds <- getEntry [] "ibc_metainformation" ar
mapM_ (\ (n, m) -> updateIState (\i ->
i { tt_ctxt = setMetaInformation n m (tt_ctxt i) })) ds
processErrorHandlers :: Archive -> Idris ()
processErrorHandlers ar = do
ns <- getEntry [] "ibc_errorhandlers" ar
updateIState (\i -> i { idris_errorhandlers = idris_errorhandlers i ++ ns })
processFunctionErrorHandlers :: Archive -> Idris ()
processFunctionErrorHandlers ar = do
ns <- getEntry [] "ibc_function_errorhandlers" ar
mapM_ (\ (fn,arg,handler) -> addFunctionErrorHandlers fn arg [handler]) ns
processMetaVars :: Archive -> Idris ()
processMetaVars ar = do
ns <- getEntry [] "ibc_metavars" ar
updateIState (\i -> i { idris_metavars = L.reverse ns ++ idris_metavars i })
----- For Cheapskate and docstrings
instance Binary a => Binary (D.Docstring a) where
put (D.DocString opts lines) = do put opts ; put lines
get = do opts <- get
lines <- get
return (D.DocString opts lines)
instance Binary CT.Options where
put (CT.Options x1 x2 x3 x4) = do put x1 ; put x2 ; put x3 ; put x4
get = do x1 <- get
x2 <- get
x3 <- get
x4 <- get
return (CT.Options x1 x2 x3 x4)
instance Binary D.DocTerm where
put D.Unchecked = putWord8 0
put (D.Checked t) = putWord8 1 >> put t
put (D.Example t) = putWord8 2 >> put t
put (D.Failing e) = putWord8 3 >> put e
get = do i <- getWord8
case i of
0 -> return D.Unchecked
1 -> fmap D.Checked get
2 -> fmap D.Example get
3 -> fmap D.Failing get
_ -> error "Corrupted binary data for DocTerm"
instance Binary a => Binary (D.Block a) where
put (D.Para lines) = do putWord8 0 ; put lines
put (D.Header i lines) = do putWord8 1 ; put i ; put lines
put (D.Blockquote bs) = do putWord8 2 ; put bs
put (D.List b t xs) = do putWord8 3 ; put b ; put t ; put xs
put (D.CodeBlock attr txt src) = do putWord8 4 ; put attr ; put txt ; put src
put (D.HtmlBlock txt) = do putWord8 5 ; put txt
put D.HRule = putWord8 6
get = do i <- getWord8
case i of
0 -> fmap D.Para get
1 -> liftM2 D.Header get get
2 -> fmap D.Blockquote get
3 -> liftM3 D.List get get get
4 -> liftM3 D.CodeBlock get get get
5 -> liftM D.HtmlBlock get
6 -> return D.HRule
_ -> error "Corrupted binary data for Block"
instance Binary a => Binary (D.Inline a) where
put (D.Str txt) = do putWord8 0 ; put txt
put D.Space = putWord8 1
put D.SoftBreak = putWord8 2
put D.LineBreak = putWord8 3
put (D.Emph xs) = putWord8 4 >> put xs
put (D.Strong xs) = putWord8 5 >> put xs
put (D.Code xs tm) = putWord8 6 >> put xs >> put tm
put (D.Link a b c) = putWord8 7 >> put a >> put b >> put c
put (D.Image a b c) = putWord8 8 >> put a >> put b >> put c
put (D.Entity a) = putWord8 9 >> put a
put (D.RawHtml x) = putWord8 10 >> put x
get = do i <- getWord8
case i of
0 -> liftM D.Str get
1 -> return D.Space
2 -> return D.SoftBreak
3 -> return D.LineBreak
4 -> liftM D.Emph get
5 -> liftM D.Strong get
6 -> liftM2 D.Code get get
7 -> liftM3 D.Link get get get
8 -> liftM3 D.Image get get get
9 -> liftM D.Entity get
10 -> liftM D.RawHtml get
_ -> error "Corrupted binary data for Inline"
instance Binary CT.ListType where
put (CT.Bullet c) = putWord8 0 >> put c
put (CT.Numbered nw i) = putWord8 1 >> put nw >> put i
get = do i <- getWord8
case i of
0 -> liftM CT.Bullet get
1 -> liftM2 CT.Numbered get get
_ -> error "Corrupted binary data for ListType"
instance Binary CT.CodeAttr where
put (CT.CodeAttr a b) = put a >> put b
get = liftM2 CT.CodeAttr get get
instance Binary CT.NumWrapper where
put (CT.PeriodFollowing) = putWord8 0
put (CT.ParenFollowing) = putWord8 1
get = do i <- getWord8
case i of
0 -> return CT.PeriodFollowing
1 -> return CT.ParenFollowing
_ -> error "Corrupted binary data for NumWrapper"
----- Generated by 'derive'
instance Binary SizeChange where
put x
= case x of
Smaller -> putWord8 0
Same -> putWord8 1
Bigger -> putWord8 2
Unknown -> putWord8 3
get
= do i <- getWord8
case i of
0 -> return Smaller
1 -> return Same
2 -> return Bigger
3 -> return Unknown
_ -> error "Corrupted binary data for SizeChange"
instance Binary CGInfo where
put (CGInfo x1 x2 x3 x4)
= do put x1
-- put x3 -- Already used SCG info for totality check
put x2
put x4
get
= do x1 <- get
x2 <- get
x3 <- get
return (CGInfo x1 x2 [] x3)
instance Binary CaseType where
put x = case x of
Updatable -> putWord8 0
Shared -> putWord8 1
get = do i <- getWord8
case i of
0 -> return Updatable
1 -> return Shared
_ -> error "Corrupted binary data for CaseType"
instance Binary SC where
put x
= case x of
Case x1 x2 x3 -> do putWord8 0
put x1
put x2
put x3
ProjCase x1 x2 -> do putWord8 1
put x1
put x2
STerm x1 -> do putWord8 2
put x1
UnmatchedCase x1 -> do putWord8 3
put x1
ImpossibleCase -> do putWord8 4
get
= do i <- getWord8
case i of
0 -> do x1 <- get
x2 <- get
x3 <- get
return (Case x1 x2 x3)
1 -> do x1 <- get
x2 <- get
return (ProjCase x1 x2)
2 -> do x1 <- get
return (STerm x1)
3 -> do x1 <- get
return (UnmatchedCase x1)
4 -> return ImpossibleCase
_ -> error "Corrupted binary data for SC"
instance Binary CaseAlt where
put x
= {-# SCC "putCaseAlt" #-}
case x of
ConCase x1 x2 x3 x4 -> do putWord8 0
put x1
put x2
put x3
put x4
ConstCase x1 x2 -> do putWord8 1
put x1
put x2
DefaultCase x1 -> do putWord8 2
put x1
FnCase x1 x2 x3 -> do putWord8 3
put x1
put x2
put x3
SucCase x1 x2 -> do putWord8 4
put x1
put x2
get
= do i <- getWord8
case i of
0 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
return (ConCase x1 x2 x3 x4)
1 -> do x1 <- get
x2 <- get
return (ConstCase x1 x2)
2 -> do x1 <- get
return (DefaultCase x1)
3 -> do x1 <- get
x2 <- get
x3 <- get
return (FnCase x1 x2 x3)
4 -> do x1 <- get
x2 <- get
return (SucCase x1 x2)
_ -> error "Corrupted binary data for CaseAlt"
instance Binary CaseDefs where
put (CaseDefs x1 x2)
= do put x1
put x2
get
= do x1 <- get
x2 <- get
return (CaseDefs x1 x2)
instance Binary CaseInfo where
put x@(CaseInfo x1 x2 x3) = do put x1
put x2
put x3
get = do x1 <- get
x2 <- get
x3 <- get
return (CaseInfo x1 x2 x3)
instance Binary Def where
put x
= {-# SCC "putDef" #-}
case x of
Function x1 x2 -> do putWord8 0
put x1
put x2
TyDecl x1 x2 -> do putWord8 1
put x1
put x2
-- all primitives just get added at the start, don't write
Operator x1 x2 x3 -> do return ()
-- no need to add/load original patterns, because they're not
-- used again after totality checking
CaseOp x1 x2 x3 _ _ x4 -> do putWord8 3
put x1
put x2
put x3
put x4
get
= do i <- getWord8
case i of
0 -> do x1 <- get
x2 <- get
return (Function x1 x2)
1 -> do x1 <- get
x2 <- get
return (TyDecl x1 x2)
-- Operator isn't written, don't read
3 -> do x1 <- get
x2 <- get
x3 <- get
-- x4 <- get
-- x3 <- get always []
x5 <- get
return (CaseOp x1 x2 x3 [] [] x5)
_ -> error "Corrupted binary data for Def"
instance Binary Accessibility where
put x
= case x of
Public -> putWord8 0
Frozen -> putWord8 1
Private -> putWord8 2
Hidden -> putWord8 3
get
= do i <- getWord8
case i of
0 -> return Public
1 -> return Frozen
2 -> return Private
3 -> return Hidden
_ -> error "Corrupted binary data for Accessibility"
safeToEnum :: (Enum a, Bounded a, Integral int) => String -> int -> a
safeToEnum label x' = result
where
x = fromIntegral x'
result
| x < fromEnum (minBound `asTypeOf` result)
|| x > fromEnum (maxBound `asTypeOf` result)
= error $ label ++ ": corrupted binary representation in IBC"
| otherwise = toEnum x
instance Binary PReason where
put x
= case x of
Other x1 -> do putWord8 0
put x1
Itself -> putWord8 1
NotCovering -> putWord8 2
NotPositive -> putWord8 3
Mutual x1 -> do putWord8 4
put x1
NotProductive -> putWord8 5
BelieveMe -> putWord8 6
UseUndef x1 -> do putWord8 7
put x1
ExternalIO -> putWord8 8
get
= do i <- getWord8
case i of
0 -> do x1 <- get
return (Other x1)
1 -> return Itself
2 -> return NotCovering
3 -> return NotPositive
4 -> do x1 <- get
return (Mutual x1)
5 -> return NotProductive
6 -> return BelieveMe
7 -> do x1 <- get
return (UseUndef x1)
8 -> return ExternalIO
_ -> error "Corrupted binary data for PReason"
instance Binary Totality where
put x
= case x of
Total x1 -> do putWord8 0
put x1
Partial x1 -> do putWord8 1
put x1
Unchecked -> do putWord8 2
Productive -> do putWord8 3
Generated -> do putWord8 4
get
= do i <- getWord8
case i of
0 -> do x1 <- get
return (Total x1)
1 -> do x1 <- get
return (Partial x1)
2 -> return Unchecked
3 -> return Productive
4 -> return Generated
_ -> error "Corrupted binary data for Totality"
instance Binary MetaInformation where
put x
= case x of
EmptyMI -> do putWord8 0
DataMI x1 -> do putWord8 1
put x1
get = do i <- getWord8
case i of
0 -> return EmptyMI
1 -> do x1 <- get
return (DataMI x1)
_ -> error "Corrupted binary data for MetaInformation"
instance Binary DataOpt where
put x = case x of
Codata -> putWord8 0
DefaultEliminator -> putWord8 1
DataErrRev -> putWord8 2
DefaultCaseFun -> putWord8 3
get = do i <- getWord8
case i of
0 -> return Codata
1 -> return DefaultEliminator
2 -> return DataErrRev
3 -> return DefaultCaseFun
_ -> error "Corrupted binary data for DataOpt"
instance Binary FnOpt where
put x
= case x of
Inlinable -> putWord8 0
TotalFn -> putWord8 1
Dictionary -> putWord8 2
AssertTotal -> putWord8 3
Specialise x -> do putWord8 4
put x
AllGuarded -> putWord8 5
PartialFn -> putWord8 6
Implicit -> putWord8 7
Reflection -> putWord8 8
ErrorHandler -> putWord8 9
ErrorReverse -> putWord8 10
CoveringFn -> putWord8 11
NoImplicit -> putWord8 12
Constructor -> putWord8 13
CExport x1 -> do putWord8 14
put x1
AutoHint -> putWord8 15
PEGenerated -> putWord8 16
StaticFn -> putWord8 17
OverlappingDictionary -> putWord8 18
ErrorReduce -> putWord8 20
get
= do i <- getWord8
case i of
0 -> return Inlinable
1 -> return TotalFn
2 -> return Dictionary
3 -> return AssertTotal
4 -> do x <- get
return (Specialise x)
5 -> return AllGuarded
6 -> return PartialFn
7 -> return Implicit
8 -> return Reflection
9 -> return ErrorHandler
10 -> return ErrorReverse
11 -> return CoveringFn
12 -> return NoImplicit
13 -> return Constructor
14 -> do x1 <- get
return $ CExport x1
15 -> return AutoHint
16 -> return PEGenerated
17 -> return StaticFn
18 -> return OverlappingDictionary
20 -> return ErrorReduce
_ -> error "Corrupted binary data for FnOpt"
instance Binary Fixity where
put x
= case x of
Infixl x1 -> do putWord8 0
put x1
Infixr x1 -> do putWord8 1
put x1
InfixN x1 -> do putWord8 2
put x1
PrefixN x1 -> do putWord8 3
put x1
get
= do i <- getWord8
case i of
0 -> do x1 <- get
return (Infixl x1)
1 -> do x1 <- get
return (Infixr x1)
2 -> do x1 <- get
return (InfixN x1)
3 -> do x1 <- get
return (PrefixN x1)
_ -> error "Corrupted binary data for Fixity"
instance Binary FixDecl where
put (Fix x1 x2)
= do put x1
put x2
get
= do x1 <- get
x2 <- get
return (Fix x1 x2)
instance Binary ArgOpt where
put x
= case x of
HideDisplay -> putWord8 0
InaccessibleArg -> putWord8 1
AlwaysShow -> putWord8 2
UnknownImp -> putWord8 3
get
= do i <- getWord8
case i of
0 -> return HideDisplay
1 -> return InaccessibleArg
2 -> return AlwaysShow
3 -> return UnknownImp
_ -> error "Corrupted binary data for Static"
instance Binary Static where
put x
= case x of
Static -> putWord8 0
Dynamic -> putWord8 1
get
= do i <- getWord8
case i of
0 -> return Static
1 -> return Dynamic
_ -> error "Corrupted binary data for Static"
instance Binary Plicity where
put x
= case x of
Imp x1 x2 x3 x4 _ x5 ->
do putWord8 0
put x1
put x2
put x3
put x4
put x5
Exp x1 x2 x3 x4 ->
do putWord8 1
put x1
put x2
put x3
put x4
Constraint x1 x2 x3 ->
do putWord8 2
put x1
put x2
put x3
TacImp x1 x2 x3 x4 ->
do putWord8 3
put x1
put x2
put x3
put x4
get
= do i <- getWord8
case i of
0 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
return (Imp x1 x2 x3 x4 False x5)
1 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
return (Exp x1 x2 x3 x4)
2 -> do x1 <- get
x2 <- get
x3 <- get
return (Constraint x1 x2 x3)
3 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
return (TacImp x1 x2 x3 x4)
_ -> error "Corrupted binary data for Plicity"
instance (Binary t) => Binary (PDecl' t) where
put x
= case x of
PFix x1 x2 x3 -> do putWord8 0
put x1
put x2
put x3
PTy x1 x2 x3 x4 x5 x6 x7 x8
-> do putWord8 1
put x1
put x2
put x3
put x4
put x5
put x6
put x7
put x8
PClauses x1 x2 x3 x4 -> do putWord8 2
put x1
put x2
put x3
put x4
PData x1 x2 x3 x4 x5 x6 ->
do putWord8 3
put x1
put x2
put x3
put x4
put x5
put x6
PParams x1 x2 x3 -> do putWord8 4
put x1
put x2
put x3
PNamespace x1 x2 x3 -> do putWord8 5
put x1
put x2
put x3
PRecord x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 ->
do putWord8 6
put x1
put x2
put x3
put x4
put x5
put x6
put x7
put x8
put x9
put x10
put x11
put x12
PInterface x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12
-> do putWord8 7
put x1
put x2
put x3
put x4
put x5
put x6
put x7
put x8
put x9
put x10
put x11
put x12
PImplementation x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 ->
do putWord8 8
put x1
put x2
put x3
put x4
put x5
put x6
put x7
put x8
put x9
put x10
put x11
put x12
put x13
put x14
put x15
PDSL x1 x2 -> do putWord8 9
put x1
put x2
PCAF x1 x2 x3 -> do putWord8 10
put x1
put x2
put x3
PMutual x1 x2 -> do putWord8 11
put x1
put x2
PPostulate x1 x2 x3 x4 x5 x6 x7 x8
-> do putWord8 12
put x1
put x2
put x3
put x4
put x5
put x6
put x7
put x8
PSyntax x1 x2 -> do putWord8 13
put x1
put x2
PDirective x1 -> error "Cannot serialize PDirective"
PProvider x1 x2 x3 x4 x5 x6 ->
do putWord8 15
put x1
put x2
put x3
put x4
put x5
put x6
PTransform x1 x2 x3 x4 -> do putWord8 16
put x1
put x2
put x3
put x4
PRunElabDecl x1 x2 x3 -> do putWord8 17
put x1
put x2
put x3
POpenInterfaces x1 x2 x3 -> do putWord8 18
put x1
put x2
put x3
get
= do i <- getWord8
case i of
0 -> do x1 <- get
x2 <- get
x3 <- get
return (PFix x1 x2 x3)
1 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
x6 <- get
x7 <- get
x8 <- get
return (PTy x1 x2 x3 x4 x5 x6 x7 x8)
2 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
return (PClauses x1 x2 x3 x4)
3 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
x6 <- get
return (PData x1 x2 x3 x4 x5 x6)
4 -> do x1 <- get
x2 <- get
x3 <- get
return (PParams x1 x2 x3)
5 -> do x1 <- get
x2 <- get
x3 <- get
return (PNamespace x1 x2 x3)
6 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
x6 <- get
x7 <- get
x8 <- get
x9 <- get
x10 <- get
x11 <- get
x12 <- get
return (PRecord x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12)
7 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
x6 <- get
x7 <- get
x8 <- get
x9 <- get
x10 <- get
x11 <- get
x12 <- get
return (PInterface x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12)
8 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
x6 <- get
x7 <- get
x8 <- get
x9 <- get
x10 <- get
x11 <- get
x12 <- get
x13 <- get
x14 <- get
x15 <- get
return (PImplementation x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15)
9 -> do x1 <- get
x2 <- get
return (PDSL x1 x2)
10 -> do x1 <- get
x2 <- get
x3 <- get
return (PCAF x1 x2 x3)
11 -> do x1 <- get
x2 <- get
return (PMutual x1 x2)
12 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
x6 <- get
x7 <- get
x8 <- get
return (PPostulate x1 x2 x3 x4 x5 x6 x7 x8)
13 -> do x1 <- get
x2 <- get
return (PSyntax x1 x2)
14 -> do error "Cannot deserialize PDirective"
15 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
x6 <- get
return (PProvider x1 x2 x3 x4 x5 x6)
16 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
return (PTransform x1 x2 x3 x4)
17 -> do x1 <- get
x2 <- get
x3 <- get
return (PRunElabDecl x1 x2 x3)
18 -> do x1 <- get
x2 <- get
x3 <- get
return (POpenInterfaces x1 x2 x3)
_ -> error "Corrupted binary data for PDecl'"
instance Binary t => Binary (ProvideWhat' t) where
put (ProvTerm x1 x2) = do putWord8 0
put x1
put x2
put (ProvPostulate x1) = do putWord8 1
put x1
get = do y <- getWord8
case y of
0 -> do x1 <- get
x2 <- get
return (ProvTerm x1 x2)
1 -> do x1 <- get
return (ProvPostulate x1)
_ -> error "Corrupted binary data for ProvideWhat"
instance Binary Using where
put (UImplicit x1 x2) = do putWord8 0; put x1; put x2
put (UConstraint x1 x2) = do putWord8 1; put x1; put x2
get = do i <- getWord8
case i of
0 -> do x1 <- get; x2 <- get; return (UImplicit x1 x2)
1 -> do x1 <- get; x2 <- get; return (UConstraint x1 x2)
_ -> error "Corrupted binary data for Using"
instance Binary SyntaxInfo where
put (Syn x1 x2 x3 x4 _ _ x5 x6 x7 _ _ x8 _ _ _)
= do put x1
put x2
put x3
put x4
put x5
put x6
put x7
put x8
get
= do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
x6 <- get
x7 <- get
x8 <- get
return (Syn x1 x2 x3 x4 [] id x5 x6 x7 Nothing 0 x8 0 True True)
instance (Binary t) => Binary (PClause' t) where
put x
= case x of
PClause x1 x2 x3 x4 x5 x6 -> do putWord8 0
put x1
put x2
put x3
put x4
put x5
put x6
PWith x1 x2 x3 x4 x5 x6 x7 -> do putWord8 1
put x1
put x2
put x3
put x4
put x5
put x6
put x7
PClauseR x1 x2 x3 x4 -> do putWord8 2
put x1
put x2
put x3
put x4
PWithR x1 x2 x3 x4 x5 -> do putWord8 3
put x1
put x2
put x3
put x4
put x5
get
= do i <- getWord8
case i of
0 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
x6 <- get
return (PClause x1 x2 x3 x4 x5 x6)
1 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
x6 <- get
x7 <- get
return (PWith x1 x2 x3 x4 x5 x6 x7)
2 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
return (PClauseR x1 x2 x3 x4)
3 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
return (PWithR x1 x2 x3 x4 x5)
_ -> error "Corrupted binary data for PClause'"
instance (Binary t) => Binary (PData' t) where
put x
= case x of
PDatadecl x1 x2 x3 x4 -> do putWord8 0
put x1
put x2
put x3
put x4
PLaterdecl x1 x2 x3 -> do putWord8 1
put x1
put x2
put x3
get
= do i <- getWord8
case i of
0 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
return (PDatadecl x1 x2 x3 x4)
1 -> do x1 <- get
x2 <- get
x3 <- get
return (PLaterdecl x1 x2 x3)
_ -> error "Corrupted binary data for PData'"
instance Binary PunInfo where
put x
= case x of
TypeOrTerm -> putWord8 0
IsType -> putWord8 1
IsTerm -> putWord8 2
get
= do i <- getWord8
case i of
0 -> return TypeOrTerm
1 -> return IsType
2 -> return IsTerm
_ -> error "Corrupted binary data for PunInfo"
instance Binary PTerm where
put x
= case x of
PQuote x1 -> do putWord8 0
put x1
PRef x1 x2 x3 -> do putWord8 1
put x1
put x2
put x3
PInferRef x1 x2 x3 -> do putWord8 2
put x1
put x2
put x3
PPatvar x1 x2 -> do putWord8 3
put x1
put x2
PLam x1 x2 x3 x4 x5 -> do putWord8 4
put x1
put x2
put x3
put x4
put x5
PPi x1 x2 x3 x4 x5 -> do putWord8 5
put x1
put x2
put x3
put x4
put x5
PLet x1 x2 x3 x4 x5 x6 -> do putWord8 6
put x1
put x2
put x3
put x4
put x5
put x6
PTyped x1 x2 -> do putWord8 7
put x1
put x2
PAppImpl x1 x2 -> error "PAppImpl in final term"
PApp x1 x2 x3 -> do putWord8 8
put x1
put x2
put x3
PAppBind x1 x2 x3 -> do putWord8 9
put x1
put x2
put x3
PMatchApp x1 x2 -> do putWord8 10
put x1
put x2
PCase x1 x2 x3 -> do putWord8 11
put x1
put x2
put x3
PTrue x1 x2 -> do putWord8 12
put x1
put x2
PResolveTC x1 -> do putWord8 15
put x1
PRewrite x1 x2 x3 x4 x5 -> do putWord8 17
put x1
put x2
put x3
put x4
put x5
PPair x1 x2 x3 x4 x5 -> do putWord8 18
put x1
put x2
put x3
put x4
put x5
PDPair x1 x2 x3 x4 x5 x6 -> do putWord8 19
put x1
put x2
put x3
put x4
put x5
put x6
PAlternative x1 x2 x3 -> do putWord8 20
put x1
put x2
put x3
PHidden x1 -> do putWord8 21
put x1
PType x1 -> do putWord8 22
put x1
PGoal x1 x2 x3 x4 -> do putWord8 23
put x1
put x2
put x3
put x4
PConstant x1 x2 -> do putWord8 24
put x1
put x2
Placeholder -> putWord8 25
PDoBlock x1 -> do putWord8 26
put x1
PIdiom x1 x2 -> do putWord8 27
put x1
put x2
PMetavar x1 x2 -> do putWord8 29
put x1
put x2
PProof x1 -> do putWord8 30
put x1
PTactics x1 -> do putWord8 31
put x1
PImpossible -> putWord8 33
PCoerced x1 -> do putWord8 34
put x1
PUnifyLog x1 -> do putWord8 35
put x1
PNoImplicits x1 -> do putWord8 36
put x1
PDisamb x1 x2 -> do putWord8 37
put x1
put x2
PUniverse x1 x2 -> do putWord8 38
put x1
put x2
PRunElab x1 x2 x3 -> do putWord8 39
put x1
put x2
put x3
PAs x1 x2 x3 -> do putWord8 40
put x1
put x2
put x3
PElabError x1 -> do putWord8 41
put x1
PQuasiquote x1 x2 -> do putWord8 42
put x1
put x2
PUnquote x1 -> do putWord8 43
put x1
PQuoteName x1 x2 x3 -> do putWord8 44
put x1
put x2
put x3
PIfThenElse x1 x2 x3 x4 -> do putWord8 45
put x1
put x2
put x3
put x4
PConstSugar x1 x2 -> do putWord8 46
put x1
put x2
PWithApp x1 x2 x3 -> do putWord8 47
put x1
put x2
put x3
get
= do i <- getWord8
case i of
0 -> do x1 <- get
return (PQuote x1)
1 -> do x1 <- get
x2 <- get
x3 <- get
return (PRef x1 x2 x3)
2 -> do x1 <- get
x2 <- get
x3 <- get
return (PInferRef x1 x2 x3)
3 -> do x1 <- get
x2 <- get
return (PPatvar x1 x2)
4 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
return (PLam x1 x2 x3 x4 x5)
5 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
return (PPi x1 x2 x3 x4 x5)
6 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
x6 <- get
return (PLet x1 x2 x3 x4 x5 x6)
7 -> do x1 <- get
x2 <- get
return (PTyped x1 x2)
8 -> do x1 <- get
x2 <- get
x3 <- get
return (PApp x1 x2 x3)
9 -> do x1 <- get
x2 <- get
x3 <- get
return (PAppBind x1 x2 x3)
10 -> do x1 <- get
x2 <- get
return (PMatchApp x1 x2)
11 -> do x1 <- get
x2 <- get
x3 <- get
return (PCase x1 x2 x3)
12 -> do x1 <- get
x2 <- get
return (PTrue x1 x2)
15 -> do x1 <- get
return (PResolveTC x1)
17 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
return (PRewrite x1 x2 x3 x4 x5)
18 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
return (PPair x1 x2 x3 x4 x5)
19 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
x6 <- get
return (PDPair x1 x2 x3 x4 x5 x6)
20 -> do x1 <- get
x2 <- get
x3 <- get
return (PAlternative x1 x2 x3)
21 -> do x1 <- get
return (PHidden x1)
22 -> do x1 <- get
return (PType x1)
23 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
return (PGoal x1 x2 x3 x4)
24 -> do x1 <- get
x2 <- get
return (PConstant x1 x2)
25 -> return Placeholder
26 -> do x1 <- get
return (PDoBlock x1)
27 -> do x1 <- get
x2 <- get
return (PIdiom x1 x2)
29 -> do x1 <- get
x2 <- get
return (PMetavar x1 x2)
30 -> do x1 <- get
return (PProof x1)
31 -> do x1 <- get
return (PTactics x1)
33 -> return PImpossible
34 -> do x1 <- get
return (PCoerced x1)
35 -> do x1 <- get
return (PUnifyLog x1)
36 -> do x1 <- get
return (PNoImplicits x1)
37 -> do x1 <- get
x2 <- get
return (PDisamb x1 x2)
38 -> do x1 <- get
x2 <- get
return (PUniverse x1 x2)
39 -> do x1 <- get
x2 <- get
x3 <- get
return (PRunElab x1 x2 x3)
40 -> do x1 <- get
x2 <- get
x3 <- get
return (PAs x1 x2 x3)
41 -> do x1 <- get
return (PElabError x1)
42 -> do x1 <- get
x2 <- get
return (PQuasiquote x1 x2)
43 -> do x1 <- get
return (PUnquote x1)
44 -> do x1 <- get
x2 <- get
x3 <- get
return (PQuoteName x1 x2 x3)
45 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
return (PIfThenElse x1 x2 x3 x4)
46 -> do x1 <- get
x2 <- get
return (PConstSugar x1 x2)
47 -> do x1 <- get
x2 <- get
x3 <- get
return (PWithApp x1 x2 x3)
_ -> error "Corrupted binary data for PTerm"
instance Binary PAltType where
put x
= case x of
ExactlyOne x1 -> do putWord8 0
put x1
FirstSuccess -> putWord8 1
TryImplicit -> putWord8 2
get
= do i <- getWord8
case i of
0 -> do x1 <- get
return (ExactlyOne x1)
1 -> return FirstSuccess
2 -> return TryImplicit
_ -> error "Corrupted binary data for PAltType"
instance (Binary t) => Binary (PTactic' t) where
put x
= case x of
Intro x1 -> do putWord8 0
put x1
Focus x1 -> do putWord8 1
put x1
Refine x1 x2 -> do putWord8 2
put x1
put x2
Rewrite x1 -> do putWord8 3
put x1
LetTac x1 x2 -> do putWord8 4
put x1
put x2
Exact x1 -> do putWord8 5
put x1
Compute -> putWord8 6
Trivial -> putWord8 7
Solve -> putWord8 8
Attack -> putWord8 9
ProofState -> putWord8 10
ProofTerm -> putWord8 11
Undo -> putWord8 12
Try x1 x2 -> do putWord8 13
put x1
put x2
TSeq x1 x2 -> do putWord8 14
put x1
put x2
Qed -> putWord8 15
ApplyTactic x1 -> do putWord8 16
put x1
Reflect x1 -> do putWord8 17
put x1
Fill x1 -> do putWord8 18
put x1
Induction x1 -> do putWord8 19
put x1
ByReflection x1 -> do putWord8 20
put x1
ProofSearch x1 x2 x3 x4 x5 x6 -> do putWord8 21
put x1
put x2
put x3
put x4
put x5
put x6
DoUnify -> putWord8 22
CaseTac x1 -> do putWord8 23
put x1
SourceFC -> putWord8 24
Intros -> putWord8 25
Equiv x1 -> do putWord8 26
put x1
Claim x1 x2 -> do putWord8 27
put x1
put x2
Unfocus -> putWord8 28
MatchRefine x1 -> do putWord8 29
put x1
LetTacTy x1 x2 x3 -> do putWord8 30
put x1
put x2
put x3
TCImplementation -> putWord8 31
GoalType x1 x2 -> do putWord8 32
put x1
put x2
TCheck x1 -> do putWord8 33
put x1
TEval x1 -> do putWord8 34
put x1
TDocStr x1 -> do putWord8 35
put x1
TSearch x1 -> do putWord8 36
put x1
Skip -> putWord8 37
TFail x1 -> do putWord8 38
put x1
Abandon -> putWord8 39
get
= do i <- getWord8
case i of
0 -> do x1 <- get
return (Intro x1)
1 -> do x1 <- get
return (Focus x1)
2 -> do x1 <- get
x2 <- get
return (Refine x1 x2)
3 -> do x1 <- get
return (Rewrite x1)
4 -> do x1 <- get
x2 <- get
return (LetTac x1 x2)
5 -> do x1 <- get
return (Exact x1)
6 -> return Compute
7 -> return Trivial
8 -> return Solve
9 -> return Attack
10 -> return ProofState
11 -> return ProofTerm
12 -> return Undo
13 -> do x1 <- get
x2 <- get
return (Try x1 x2)
14 -> do x1 <- get
x2 <- get
return (TSeq x1 x2)
15 -> return Qed
16 -> do x1 <- get
return (ApplyTactic x1)
17 -> do x1 <- get
return (Reflect x1)
18 -> do x1 <- get
return (Fill x1)
19 -> do x1 <- get
return (Induction x1)
20 -> do x1 <- get
return (ByReflection x1)
21 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
x6 <- get
return (ProofSearch x1 x2 x3 x4 x5 x6)
22 -> return DoUnify
23 -> do x1 <- get
return (CaseTac x1)
24 -> return SourceFC
25 -> return Intros
26 -> do x1 <- get
return (Equiv x1)
27 -> do x1 <- get
x2 <- get
return (Claim x1 x2)
28 -> return Unfocus
29 -> do x1 <- get
return (MatchRefine x1)
30 -> do x1 <- get
x2 <- get
x3 <- get
return (LetTacTy x1 x2 x3)
31 -> return TCImplementation
32 -> do x1 <- get
x2 <- get
return (GoalType x1 x2)
33 -> do x1 <- get
return (TCheck x1)
34 -> do x1 <- get
return (TEval x1)
35 -> do x1 <- get
return (TDocStr x1)
36 -> do x1 <- get
return (TSearch x1)
37 -> return Skip
38 -> do x1 <- get
return (TFail x1)
39 -> return Abandon
_ -> error "Corrupted binary data for PTactic'"
instance (Binary t) => Binary (PDo' t) where
put x
= case x of
DoExp x1 x2 -> do putWord8 0
put x1
put x2
DoBind x1 x2 x3 x4 -> do putWord8 1
put x1
put x2
put x3
put x4
DoBindP x1 x2 x3 x4 -> do putWord8 2
put x1
put x2
put x3
put x4
DoLet x1 x2 x3 x4 x5 -> do putWord8 3
put x1
put x2
put x3
put x4
put x5
DoLetP x1 x2 x3 -> do putWord8 4
put x1
put x2
put x3
DoRewrite x1 x2 -> do putWord8 5
put x1
put x2
get
= do i <- getWord8
case i of
0 -> do x1 <- get
x2 <- get
return (DoExp x1 x2)
1 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
return (DoBind x1 x2 x3 x4)
2 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
return (DoBindP x1 x2 x3 x4)
3 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
return (DoLet x1 x2 x3 x4 x5)
4 -> do x1 <- get
x2 <- get
x3 <- get
return (DoLetP x1 x2 x3)
5 -> do
x1 <- get
x2 <- get
return (DoRewrite x1 x2)
_ -> error "Corrupted binary data for PDo'"
instance (Binary t) => Binary (PArg' t) where
put x
= case x of
PImp x1 x2 x3 x4 x5 ->
do putWord8 0
put x1
put x2
put x3
put x4
put x5
PExp x1 x2 x3 x4 ->
do putWord8 1
put x1
put x2
put x3
put x4
PConstraint x1 x2 x3 x4 ->
do putWord8 2
put x1
put x2
put x3
put x4
PTacImplicit x1 x2 x3 x4 x5 ->
do putWord8 3
put x1
put x2
put x3
put x4
put x5
get
= do i <- getWord8
case i of
0 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
return (PImp x1 x2 x3 x4 x5)
1 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
return (PExp x1 x2 x3 x4)
2 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
return (PConstraint x1 x2 x3 x4)
3 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
return (PTacImplicit x1 x2 x3 x4 x5)
_ -> error "Corrupted binary data for PArg'"
instance Binary InterfaceInfo where
put (CI x1 x2 x3 x4 x5 x6 x7 _ x8)
= do put x1
put x2
put x3
put x4
put x5
put x6
put x7
put x8
get
= do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
x6 <- get
x7 <- get
x8 <- get
return (CI x1 x2 x3 x4 x5 x6 x7 [] x8)
instance Binary RecordInfo where
put (RI x1 x2 x3)
= do put x1
put x2
put x3
get
= do x1 <- get
x2 <- get
x3 <- get
return (RI x1 x2 x3)
instance Binary OptInfo where
put (Optimise x1 x2 x3)
= do put x1
put x2
put x3
get
= do x1 <- get
x2 <- get
x3 <- get
return (Optimise x1 x2 x3)
instance Binary FnInfo where
put (FnInfo x1)
= put x1
get
= do x1 <- get
return (FnInfo x1)
instance Binary TypeInfo where
put (TI x1 x2 x3 x4 x5 x6) = do put x1
put x2
put x3
put x4
put x5
put x6
get = do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
x6 <- get
return (TI x1 x2 x3 x4 x5 x6)
instance Binary SynContext where
put x
= case x of
PatternSyntax -> putWord8 0
TermSyntax -> putWord8 1
AnySyntax -> putWord8 2
get
= do i <- getWord8
case i of
0 -> return PatternSyntax
1 -> return TermSyntax
2 -> return AnySyntax
_ -> error "Corrupted binary data for SynContext"
instance Binary Syntax where
put (Rule x1 x2 x3)
= do putWord8 0
put x1
put x2
put x3
put (DeclRule x1 x2)
= do putWord8 1
put x1
put x2
get
= do i <- getWord8
case i of
0 -> do x1 <- get
x2 <- get
x3 <- get
return (Rule x1 x2 x3)
1 -> do x1 <- get
x2 <- get
return (DeclRule x1 x2)
_ -> error "Corrupted binary data for Syntax"
instance (Binary t) => Binary (DSL' t) where
put (DSL x1 x2 x3 x4 x5 x6 x7 x8 x9)
= do put x1
put x2
put x3
put x4
put x5
put x6
put x7
put x8
put x9
get
= do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
x6 <- get
x7 <- get
x8 <- get
x9 <- get
return (DSL x1 x2 x3 x4 x5 x6 x7 x8 x9)
instance Binary SSymbol where
put x
= case x of
Keyword x1 -> do putWord8 0
put x1
Symbol x1 -> do putWord8 1
put x1
Expr x1 -> do putWord8 2
put x1
SimpleExpr x1 -> do putWord8 3
put x1
Binding x1 -> do putWord8 4
put x1
get
= do i <- getWord8
case i of
0 -> do x1 <- get
return (Keyword x1)
1 -> do x1 <- get
return (Symbol x1)
2 -> do x1 <- get
return (Expr x1)
3 -> do x1 <- get
return (SimpleExpr x1)
4 -> do x1 <- get
return (Binding x1)
_ -> error "Corrupted binary data for SSymbol"
instance Binary Codegen where
put x
= case x of
Via ir str -> do putWord8 0
put ir
put str
Bytecode -> putWord8 1
get
= do i <- getWord8
case i of
0 -> do x1 <- get
x2 <- get
return (Via x1 x2)
1 -> return Bytecode
_ -> error "Corrupted binary data for Codegen"
instance Binary IRFormat where
put x = case x of
IBCFormat -> putWord8 0
JSONFormat -> putWord8 1
get = do i <- getWord8
case i of
0 -> return IBCFormat
1 -> return JSONFormat
_ -> error "Corrupted binary data for IRFormat"
|
markuspf/Idris-dev
|
src/Idris/IBC.hs
|
Haskell
|
bsd-3-clause
| 102,813
|
{-# LANGUAGE DeriveDataTypeable #-}
module Latex
( texString
, writeTexStdOut
, writeTexToFile
, writeTemplateToFile
) where
import Data.List
import System.IO
import System.Directory
import System.FilePath.Posix
import Args
import Lib
texString :: Arguments -> String
texString (Install {}) = error "Cannot form a LaTeX string while installing"
texString a@Generate {} = intercalate "\n" [ assembleFileHeader a
, assemblePackages $ pkg a
, "\\author{" ++ author a ++ "}"
, "\\title{" ++ title a ++ "}"
, "\\date{" ++ date a ++ "}"
, beginDocument
, makeTitle
, documentBody
, endDocument
]
where
fullLineComment = replicate 80 '%'
commentString :: String -> String
commentString xs = "%% " ++ xs
beginDocument = "\n\n\\begin{document}"
endDocument = "\n\n\\end{document}"
makeTitle = "\\maketitle"
documentBody = "\n\n" ++ "%% Your latex code goes here"
assembleFileHeader :: Arguments -> String
assembleFileHeader a =
fullLineComment ++
intercalate "\n%% " (
["\n%% Author: " ++ author a
,"Title: " ++ title a
,"Date: Current Date Here"
] ++ ( notes a) )
++ ('\n':fullLineComment)
-- formatPackage s = "\usepackage" ++ extractPackageOptions s
formPackageString :: String -> String
formPackageString xs = let
(pkgName, pkgOpt) = span (/= '[') xs in
"\\usepackage" ++ pkgOpt ++ ( '{' : (pkgName ++ "}"))
assemblePackages = intercalate "\n" . map formPackageString
templateString :: Arguments -> IO String
templateString Install {} = error "Install is not a Template"
templateString Generate {} = error "Generate is not a Template"
templateString a@Template {} = do
appDir <- getAppUserDataDirectory programName
let filePath = appDir </> "templates" </> name_ a
readFile filePath
writeTexStdOut :: Arguments -> IO ()
writeTexStdOut Install{} = error "Cannot form a LaTeX string while installing"
writeTexStdOut Template{} = error "writeTexStdOut(Template)!! unimplemented"
writeTexStdOut a = putStrLn $ texString a
writeTexToFile :: Arguments -> IO ()
writeTexToFile Install {} = error "Cannot form a LaTeX string while installing"
writeTexToFile Template {} = error "writeTexToFile(Template)!! unimplemented"
writeTexToFile a = writeFile (fileName a) (texString a)
writeTemplateToFile :: Arguments -> IO ()
writeTemplateToFile Install {} = error "Install is not a template"
writeTemplateToFile Generate {} = error "Run is not a template"
writeTemplateToFile a = do
contents <- templateString a
writeFile (fileName a) contents
|
bkushigian/makeltx
|
src/Latex.hs
|
Haskell
|
bsd-3-clause
| 2,932
|
{-# LANGUAGE MultiParamTypeClasses, FlexibleContexts, FlexibleInstances,
TypeFamilies, Rank2Types, FunctionalDependencies #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Matrix.Banded.Base
-- Copyright : Copyright (c) , Patrick Perry <patperry@stanford.edu>
-- License : BSD3
-- Maintainer : Patrick Perry <patperry@stanford.edu>
-- Stability : experimental
--
module Data.Matrix.Banded.Base
where
import Control.Monad
import Control.Monad.Interleave
import Control.Monad.ST
import Data.AEq
import Data.Maybe
import Data.Ix
import System.IO.Unsafe
import BLAS.Internal( clearArray, checkedRow, checkedCol, checkedDiag,
diagLen, inlinePerformIO )
import Data.Elem.BLAS
import Data.Tensor.Class
import Data.Tensor.Class.ITensor
import Data.Tensor.Class.MTensor
import Data.Matrix.Class
import Data.Matrix.Class.IMatrixBase
import Data.Matrix.Class.MMatrixBase
import Data.Matrix.Class.ISolveBase
import Data.Matrix.Class.MSolveBase
import Data.Matrix.Herm
import Data.Matrix.Tri
import Data.Vector.Dense.ST( runSTVector )
import Data.Vector.Dense.Base( BaseVector, ReadVector, WriteVector, Vector(..),
STVector(..), dim, unsafeVectorToIOVector, unsafePerformIOWithVector,
unsafeConvertIOVector, newZeroVector, newCopyVector )
import Data.Matrix.Dense.ST( runSTMatrix )
import Data.Matrix.Dense.Base( BaseMatrix, ReadMatrix, WriteMatrix, Matrix(..),
STMatrix(..), unsafeMatrixToIOMatrix, unsafePerformIOWithMatrix )
import Data.Matrix.Banded.IOBase( IOBanded(..) )
import qualified Data.Matrix.Banded.IOBase as IO
-- | Immutable banded matrices. The type arguments are as follows:
--
-- * @e@: the element type of the matrix. Only certain element types
-- are supported.
--
newtype Banded e = Banded (IOBanded e)
freezeIOBanded :: IOBanded e -> IO (Banded e)
freezeIOBanded x = do
y <- IO.newCopyIOBanded x
return (Banded y)
thawIOBanded :: Banded e -> IO (IOBanded e)
thawIOBanded (Banded x) =
IO.newCopyIOBanded x
unsafeFreezeIOBanded :: IOBanded e -> IO (Banded e)
unsafeFreezeIOBanded = return . Banded
unsafeThawIOBanded :: Banded e -> IO (IOBanded e)
unsafeThawIOBanded (Banded x) = return x
-- | Common functionality for all banded matrix types.
class ( MatrixShaped a,
HasHerm a,
HasVectorView a,
HasMatrixStorage a,
BaseVector (VectorView a),
BaseMatrix (MatrixStorage a) ) => BaseBanded a where
-- | Get the number of lower diagonals in the banded matrix.
numLower :: a e -> Int
-- | Get the number of upper diagonals in the banded matrix
numUpper :: a e -> Int
-- | Get the range of valid diagonals in the banded matrix.
-- @bandwidthds a@ is equal to @(numLower a, numUpper a)@.
bandwidths :: a e -> (Int,Int)
-- | Get the leading dimension of the underlying storage of the
-- banded matrix.
ldaBanded :: a e -> Int
-- | Get the storage type of the banded matrix.
transEnumBanded :: a e -> TransEnum
-- | Indicate whether or not the banded matrix storage is
-- transposed and conjugated.
isHermBanded :: a e -> Bool
isHermBanded = (ConjTrans ==) . transEnumBanded
{-# INLINE isHermBanded #-}
-- | Get a matrix with the underlying storage of the banded matrix.
-- This will fail if the banded matrix is hermed.
maybeMatrixStorageFromBanded :: a e -> Maybe (MatrixStorage a e)
-- | Given a shape and bandwidths, possibly view the elements stored
-- in a dense matrix as a banded matrix. This will if the matrix
-- storage is hermed. An error will be called if the number of rows
-- in the matrix does not equal the desired number of diagonals or
-- if the number of columns in the matrix does not equal the desired
-- number of columns.
maybeBandedFromMatrixStorage :: (Int,Int)
-> (Int,Int)
-> MatrixStorage a e
-> Maybe (a e)
-- | View a vector as a banded matrix of the given shape. The vector
-- must have length equal to one of the specified dimensions.
viewVectorAsBanded :: (Int,Int) -> VectorView a e -> a e
-- | View a vector as a diagonal banded matrix.
viewVectorAsDiagBanded :: VectorView a e -> a e
viewVectorAsDiagBanded x = let
n = dim x
in viewVectorAsBanded (n,n) x
{-# INLINE viewVectorAsBanded #-}
-- | If the banded matrix has only a single diagonal, return a view
-- into that diagonal. Otherwise, return @Nothing@.
maybeViewBandedAsVector :: a e -> Maybe (VectorView a e)
unsafeDiagViewBanded :: a e -> Int -> VectorView a e
unsafeRowViewBanded :: a e -> Int -> (Int, VectorView a e, Int)
unsafeColViewBanded :: a e -> Int -> (Int, VectorView a e, Int)
-- | Unsafe cast from a matrix to an 'IOBanded'.
unsafeBandedToIOBanded :: a e -> IOBanded e
unsafeIOBandedToBanded :: IOBanded e -> a e
-- | Banded matrices that can be read in a monad.
class ( BaseBanded a,
MonadInterleave m,
ReadTensor a (Int,Int) m,
MMatrix a m,
MMatrix (Herm a) m,
MMatrix (Tri a) m, MSolve (Tri a) m,
ReadVector (VectorView a) m,
ReadMatrix (MatrixStorage a) m ) => ReadBanded a m where
-- | Cast the banded matrix to an 'IOBanded', perform an @IO@ action, and
-- convert the @IO@ action to an action in the monad @m@. This
-- operation is /very/ unsafe.
unsafePerformIOWithBanded :: a e -> (IOBanded e -> IO r) -> m r
-- | Convert a mutable banded matrix to an immutable one by taking a
-- complete copy of it.
freezeBanded :: a e -> m (Banded e)
unsafeFreezeBanded :: a e -> m (Banded e)
-- | Banded matrices that can be created or modified in a monad.
class ( ReadBanded a m,
WriteTensor a (Int,Int) m,
WriteVector (VectorView a) m,
WriteMatrix (MatrixStorage a) m ) => WriteBanded a m | m -> a where
-- | Creates a new banded matrix of the given shape and bandwidths.
-- The elements will be uninitialized.
newBanded_ :: (Elem e) => (Int,Int) -> (Int,Int) -> m (a e)
-- | Unsafely convert an 'IO' action that creates an 'IOBanded' into
-- an action in @m@ that creates a matrix.
unsafeConvertIOBanded :: IO (IOBanded e) -> m (a e)
-- | Convert an immutable banded matrix to a mutable one by taking a
-- complete copy of it.
thawBanded :: Banded e -> m (a e)
unsafeThawBanded :: Banded e -> m (a e)
-- | Create a banded matrix with the given shape, bandwidths, and
-- associations. The indices in the associations list must all fall
-- in the bandwidth of the matrix. Unspecified elements will be set
-- to zero.
newBanded :: (WriteBanded a m, Elem e) =>
(Int,Int) -> (Int,Int) -> [((Int,Int), e)] -> m (a e)
newBanded = newBandedHelp writeElem
{-# INLINE newBanded #-}
unsafeNewBanded :: (WriteBanded a m, Elem e) =>
(Int,Int) -> (Int,Int) -> [((Int,Int), e)] -> m (a e)
unsafeNewBanded = newBandedHelp unsafeWriteElem
{-# INLINE unsafeNewBanded #-}
newBandedHelp :: (WriteBanded a m, Elem e) =>
(IOBanded e -> (Int,Int) -> e -> IO ())
-> (Int,Int) -> (Int,Int) -> [((Int,Int),e)] -> m (a e)
newBandedHelp set (m,n) (kl,ku) ijes =
unsafeConvertIOBanded $ do
x <- newBanded_ (m,n) (kl,ku)
IO.withIOBanded x $ flip clearArray ((kl+1+ku)*n)
mapM_ (uncurry $ set x) ijes
return x
{-# INLINE newBandedHelp #-}
-- | Create a banded matrix of the given shape and bandwidths by specifying
-- its diagonal elements. The lists must all have the same length, equal
-- to the number of elements in the main diagonal of the matrix. The
-- sub-diagonals are specified first, then the super-diagonals. In
-- subdiagonal @i@, the first @i@ elements of the list are ignored.
newListsBanded :: (WriteBanded a m, Elem e) =>
(Int,Int) -> (Int,Int) -> [[e]] -> m (a e)
newListsBanded (m,n) (kl,ku) xs = do
a <- newBanded_ (m,n) (kl,ku)
zipWithM_ (writeDiagElems a) [(negate kl)..ku] xs
return a
where
writeDiagElems :: (WriteBanded a m, Elem e)
=> a e -> Int -> [e] -> m ()
writeDiagElems a i es =
let d = unsafeDiagViewBanded a i
nb = max 0 (negate i)
es' = drop nb es
in zipWithM_ (unsafeWriteElem d) [0..(dim d - 1)] es'
{-# INLINE newListsBanded #-}
-- | Create a zero banded matrix with the specified shape and bandwidths.
newZeroBanded :: (WriteBanded a m, Elem e)
=> (Int,Int) -> (Int,Int) -> m (a e)
newZeroBanded mn bw = unsafeConvertIOBanded $
IO.newZeroIOBanded mn bw
{-# INLINE newZeroBanded #-}
-- | Create a constant banded matrix of the specified shape and bandwidths.
newConstantBanded :: (WriteBanded a m, Elem e)
=> (Int,Int) -> (Int,Int) -> e -> m (a e)
newConstantBanded mn bw e = unsafeConvertIOBanded $
IO.newConstantIOBanded mn bw e
{-# INLINE newConstantBanded #-}
-- | Set every element of a banded matrix to zero.
setZeroBanded :: (WriteBanded a m) => a e -> m ()
setZeroBanded a =
unsafePerformIOWithBanded a $ IO.setZeroIOBanded
{-# INLINE setZeroBanded #-}
-- | Set every element of a banded matrix to a constant.
setConstantBanded :: (WriteBanded a m) => e -> a e -> m ()
setConstantBanded e a =
unsafePerformIOWithBanded a $ IO.setConstantIOBanded e
{-# INLINE setConstantBanded #-}
-- | Create a new banded matrix by taking a copy of another one.
newCopyBanded :: (ReadBanded a m, WriteBanded b m)
=> a e -> m (b e)
newCopyBanded a = unsafeConvertIOBanded $
IO.newCopyIOBanded (unsafeBandedToIOBanded a)
{-# INLINE newCopyBanded #-}
-- | Copy the elements of one banded matrix into another. The two matrices
-- must have the same shape and badwidths.
copyBanded :: (WriteBanded b m, ReadBanded a m) =>
b e -> a e -> m ()
copyBanded dst src
| shape dst /= shape src =
error "Shape mismatch in copyBanded."
| bandwidths dst /= bandwidths src =
error "Bandwidth mismatch in copyBanded."
| otherwise =
unsafeCopyBanded dst src
{-# INLINE copyBanded #-}
unsafeCopyBanded :: (WriteBanded b m, ReadBanded a m)
=> b e -> a e -> m ()
unsafeCopyBanded dst src =
unsafePerformIOWithBanded dst $ \dst' ->
IO.unsafeCopyIOBanded dst' (unsafeBandedToIOBanded src)
{-# INLINE unsafeCopyBanded #-}
-- | Get a view of a diagonal of the banded matrix. This will fail if
-- the index is outside of the bandwidth.
diagViewBanded :: (BaseBanded a)
=> a e -> Int -> VectorView a e
diagViewBanded a i
| i < -(numLower a) || i > numUpper a =
error $ "Tried to get a diagonal view outside of the bandwidth."
| otherwise =
unsafeDiagViewBanded a i
{-# INLINE diagViewBanded #-}
-- | Get a view into the partial row of the banded matrix, along with the
-- number of zeros to pad before and after the view.
rowViewBanded :: (BaseBanded a) =>
a e -> Int -> (Int, VectorView a e, Int)
rowViewBanded a = checkedRow (shape a) (unsafeRowViewBanded a)
{-# INLINE rowViewBanded #-}
-- | Get a view into the partial column of the banded matrix, along with the
-- number of zeros to pad before and after the view.
colViewBanded :: (BaseBanded a) =>
a e -> Int -> (Int, VectorView a e, Int)
colViewBanded a = checkedCol (shape a) (unsafeColViewBanded a)
{-# INLINE colViewBanded #-}
-- | Get a copy of the given diagonal of a banded matrix.
getDiagBanded :: (ReadBanded a m, WriteVector y m, Elem e) =>
a e -> Int -> m (y e)
getDiagBanded a i | i >= -kl && i <= ku =
newCopyVector $ diagViewBanded a i
| otherwise =
newZeroVector $ diagLen (m,n) i
where
(m,n) = shape a
(kl,ku) = bandwidths a
{-# INLINE getDiagBanded #-}
unsafeGetDiagBanded :: (ReadBanded a m, WriteVector y m, Elem e) =>
a e -> Int -> m (y e)
unsafeGetDiagBanded a i =
newCopyVector $ unsafeDiagViewBanded a i
{-# INLINE unsafeGetDiagBanded #-}
unsafeGetRowBanded :: (ReadBanded a m, WriteVector y m, Elem e) =>
a e -> Int -> m (y e)
unsafeGetRowBanded a i = unsafeConvertIOVector $
IO.unsafeGetRowIOBanded (unsafeBandedToIOBanded a) i
{-# INLINE unsafeGetRowBanded #-}
unsafeGetColBanded :: (ReadBanded a m, WriteVector y m, Elem e) =>
a e -> Int -> m (y e)
unsafeGetColBanded a i = unsafeConvertIOVector $
IO.unsafeGetColIOBanded (unsafeBandedToIOBanded a) i
{-# INLINE unsafeGetColBanded #-}
gbmv :: (ReadBanded a m, ReadVector x m, WriteVector y m, BLAS2 e) =>
e -> a e -> x e -> e -> y e -> m ()
gbmv alpha a x beta y =
unsafePerformIOWithVector y $
IO.gbmv alpha (unsafeBandedToIOBanded a) (unsafeVectorToIOVector x) beta
{-# INLINE gbmv #-}
gbmm :: (ReadBanded a m, ReadMatrix b m, WriteMatrix c m, BLAS2 e) =>
e -> a e -> b e -> e -> c e -> m ()
gbmm alpha a b beta c =
unsafePerformIOWithMatrix c $
IO.gbmm alpha (unsafeBandedToIOBanded a) (unsafeMatrixToIOMatrix b) beta
{-# INLINE gbmm #-}
unsafeGetColHermBanded :: (ReadBanded a m, WriteVector x m, Elem e)
=> Herm a e -> Int -> m (x e)
unsafeGetColHermBanded a i = unsafeConvertIOVector $
IO.unsafeGetColHermIOBanded (mapHerm unsafeBandedToIOBanded a) i
{-# INLINE unsafeGetColHermBanded #-}
unsafeGetRowHermBanded :: (ReadBanded a m, WriteVector x m, Elem e)
=> Herm a e -> Int -> m (x e)
unsafeGetRowHermBanded a i = unsafeConvertIOVector $
IO.unsafeGetRowHermIOBanded (mapHerm unsafeBandedToIOBanded a) i
{-# INLINE unsafeGetRowHermBanded #-}
hbmv :: (ReadBanded a m, ReadVector x m, WriteVector y m, BLAS2 e) =>
e -> Herm a e -> x e -> e -> y e -> m ()
hbmv alpha a x beta y =
unsafePerformIOWithVector y $
IO.hbmv alpha (mapHerm unsafeBandedToIOBanded a) (unsafeVectorToIOVector x) beta
{-# INLINE hbmv #-}
hbmm :: (ReadBanded a m, ReadMatrix b m, WriteMatrix c m, BLAS2 e) =>
e -> Herm a e -> b e -> e -> c e -> m ()
hbmm alpha a b beta c =
unsafePerformIOWithMatrix c $
IO.hbmm alpha (mapHerm unsafeBandedToIOBanded a) (unsafeMatrixToIOMatrix b) beta
{-# INLINE hbmm #-}
unsafeGetColTriBanded :: (ReadBanded a m, WriteVector x m, Elem e)
=> Tri a e -> Int -> m (x e)
unsafeGetColTriBanded a i = unsafeConvertIOVector $
IO.unsafeGetColTriIOBanded (mapTri unsafeBandedToIOBanded a) i
{-# INLINE unsafeGetColTriBanded #-}
unsafeGetRowTriBanded :: (ReadBanded a m, WriteVector x m, Elem e)
=> Tri a e -> Int -> m (x e)
unsafeGetRowTriBanded a i = unsafeConvertIOVector $
IO.unsafeGetRowTriIOBanded (mapTri unsafeBandedToIOBanded a) i
{-# INLINE unsafeGetRowTriBanded #-}
tbmv :: (ReadBanded a m, WriteVector y m, BLAS2 e) =>
e -> Tri a e -> y e -> m ()
tbmv alpha a x =
unsafePerformIOWithVector x $
IO.tbmv alpha (mapTri unsafeBandedToIOBanded a)
{-# INLINE tbmv #-}
tbmm :: (ReadBanded a m, WriteMatrix b m, BLAS2 e) =>
e -> Tri a e -> b e -> m ()
tbmm alpha a b =
unsafePerformIOWithMatrix b $
IO.tbmm alpha (mapTri unsafeBandedToIOBanded a)
{-# INLINE tbmm #-}
tbmv' :: (ReadBanded a m, ReadVector x m, WriteVector y m, BLAS2 e) =>
e -> Tri a e -> x e -> e -> y e -> m ()
tbmv' alpha a x beta y =
unsafePerformIOWithVector y $
IO.tbmv' alpha (mapTri unsafeBandedToIOBanded a) (unsafeVectorToIOVector x) beta
{-# INLINE tbmv' #-}
tbmm' :: (ReadBanded a m, ReadMatrix b m, WriteMatrix c m, BLAS2 e) =>
e -> Tri a e -> b e -> e -> c e -> m ()
tbmm' alpha a b beta c =
unsafePerformIOWithMatrix c $
IO.tbmm' alpha (mapTri unsafeBandedToIOBanded a) (unsafeMatrixToIOMatrix b) beta
{-# INLINE tbmm' #-}
tbsv :: (ReadBanded a m, WriteVector y m, BLAS2 e) =>
e -> Tri a e -> y e -> m ()
tbsv alpha a x =
unsafePerformIOWithVector x $
IO.tbmv alpha (mapTri unsafeBandedToIOBanded a)
{-# INLINE tbsv #-}
tbsm :: (ReadBanded a m, WriteMatrix b m, BLAS2 e) =>
e -> Tri a e -> b e -> m ()
tbsm alpha a b =
unsafePerformIOWithMatrix b $
IO.tbsm alpha (mapTri unsafeBandedToIOBanded a)
{-# INLINE tbsm #-}
tbsv' :: (ReadBanded a m, ReadVector y m, WriteVector x m, BLAS2 e)
=> e -> Tri a e -> y e -> x e -> m ()
tbsv' alpha a y x =
unsafePerformIOWithVector x $
IO.tbsv' alpha (mapTri unsafeBandedToIOBanded a) (unsafeVectorToIOVector y)
{-# INLINE tbsv' #-}
tbsm' :: (ReadBanded a m, ReadMatrix c m, WriteMatrix b m, BLAS2 e)
=> e -> Tri a e -> c e -> b e -> m ()
tbsm' alpha a c b =
unsafePerformIOWithMatrix b $
IO.tbsm' alpha (mapTri unsafeBandedToIOBanded a) (unsafeMatrixToIOMatrix c)
{-# INLINE tbsm' #-}
instance BaseBanded IOBanded where
numLower = IO.numLowerIOBanded
{-# INLINE numLower #-}
numUpper = IO.numUpperIOBanded
{-# INLINE numUpper #-}
bandwidths = IO.bandwidthsIOBanded
{-# INLINE bandwidths #-}
ldaBanded = IO.ldaIOBanded
{-# INLINE ldaBanded #-}
transEnumBanded = IO.transEnumIOBanded
{-# INLINE transEnumBanded #-}
maybeMatrixStorageFromBanded = IO.maybeMatrixStorageFromIOBanded
{-# INLINE maybeMatrixStorageFromBanded #-}
maybeBandedFromMatrixStorage = IO.maybeIOBandedFromMatrixStorage
{-# INLINE maybeBandedFromMatrixStorage #-}
viewVectorAsBanded = IO.viewVectorAsIOBanded
{-# INLINE viewVectorAsBanded #-}
maybeViewBandedAsVector = IO.maybeViewIOBandedAsVector
{-# INLINE maybeViewBandedAsVector #-}
unsafeDiagViewBanded = IO.unsafeDiagViewIOBanded
{-# INLINE unsafeDiagViewBanded #-}
unsafeRowViewBanded = IO.unsafeRowViewIOBanded
{-# INLINE unsafeRowViewBanded #-}
unsafeColViewBanded = IO.unsafeColViewIOBanded
{-# INLINE unsafeColViewBanded #-}
unsafeIOBandedToBanded = id
{-# INLINE unsafeIOBandedToBanded #-}
unsafeBandedToIOBanded = id
{-# INLINE unsafeBandedToIOBanded #-}
instance ReadBanded IOBanded IO where
unsafePerformIOWithBanded a f = f a
{-# INLINE unsafePerformIOWithBanded #-}
freezeBanded = freezeIOBanded
{-# INLINE freezeBanded #-}
unsafeFreezeBanded = unsafeFreezeIOBanded
{-# INLINE unsafeFreezeBanded #-}
instance WriteBanded IOBanded IO where
newBanded_ = IO.newIOBanded_
{-# INLINE newBanded_ #-}
unsafeConvertIOBanded = id
{-# INLINE unsafeConvertIOBanded #-}
thawBanded = thawIOBanded
{-# INLINE thawBanded #-}
unsafeThawBanded = unsafeThawIOBanded
{-# INLINE unsafeThawBanded #-}
-- | Create a banded matrix with the given shape, bandwidths, and
-- associations. The indices in the associations list must all fall
-- in the bandwidth of the matrix. Unspecified elements will be set
-- to zero.
banded :: (Elem e)
=> (Int,Int) -> (Int,Int) -> [((Int,Int), e)] -> Banded e
banded mn kl ies = unsafePerformIO $
unsafeFreezeIOBanded =<< IO.newIOBanded mn kl ies
unsafeBanded :: (Elem e)
=> (Int,Int) -> (Int,Int) -> [((Int,Int), e)] -> Banded e
unsafeBanded mn kl ies = unsafePerformIO $
unsafeFreezeIOBanded =<< IO.unsafeNewIOBanded mn kl ies
-- | Create a banded matrix of the given shape and bandwidths by specifying
-- its diagonal elements. The lists must all have the same length, equal
-- to the number of elements in the main diagonal of the matrix. The
-- sub-diagonals are specified first, then the super-diagonals. In
-- subdiagonal @i@, the first @i@ elements of the list are ignored.
listsBanded :: (Elem e)
=> (Int,Int) -> (Int,Int) -> [[e]] -> Banded e
listsBanded mn kl xs = unsafePerformIO $
unsafeFreezeIOBanded =<< IO.newListsIOBanded mn kl xs
-- | Create a zero banded matrix with the specified shape and bandwidths.
zeroBanded :: (Elem e)
=> (Int,Int) -> (Int,Int) -> Banded e
zeroBanded mn kl = unsafePerformIO $
unsafeFreezeIOBanded =<< IO.newZeroIOBanded mn kl
-- | Create a constant banded matrix of the specified shape and bandwidths.
constantBanded :: (Elem e)
=> (Int,Int) -> (Int,Int) -> e -> Banded e
constantBanded mn kl e = unsafePerformIO $
unsafeFreezeIOBanded =<< IO.newConstantIOBanded mn kl e
-- | Create a banded matrix from a vector. The vector must have length
-- equal to one of the specified dimension sizes.
bandedFromVector :: (Int,Int) -> Vector e -> Banded e
bandedFromVector = viewVectorAsBanded
{-# INLINE bandedFromVector #-}
-- | Create a diagonal banded matrix from a vector.
diagBandedFromVector :: Vector e -> Banded e
diagBandedFromVector = viewVectorAsDiagBanded
{-# INLINE diagBandedFromVector #-}
-- | Convert a diagonal banded matrix to a vector. Fail if the banded
-- matrix has more than one diagonal
maybeVectorFromBanded :: Banded e -> Maybe (Vector e)
maybeVectorFromBanded = maybeViewBandedAsVector
{-# INLINE maybeVectorFromBanded #-}
-- | Get a the given diagonal in a banded matrix. Negative indices correspond
-- to sub-diagonals.
diagBanded :: Banded e -> Int -> Vector e
diagBanded a = checkedDiag (shape a) (unsafeDiagBanded a)
{-# INLINE diagBanded #-}
unsafeDiagBanded :: Banded e -> Int -> Vector e
unsafeDiagBanded a@(Banded (IOBanded _ _ _ _ _ _ _ _)) i
| i >= -kl && i <= ku = unsafeDiagViewBanded a i
| otherwise = runSTVector $ newZeroVector $ diagLen (shape a) i
where
(kl,ku) = bandwidths a
{-# INLINE unsafeDiagBanded #-}
listsFromBanded :: Banded e -> ((Int,Int), (Int,Int),[[e]])
listsFromBanded a@(Banded (IOBanded _ _ _ _ _ _ _ _)) = ( (m,n)
, (kl,ku)
, map paddedDiag [(-kl)..ku]
)
where
(m,n) = shape a
(kl,ku) = bandwidths a
padBegin i = replicate (max (-i) 0) 0
padEnd i = replicate (max (m-n+i) 0) 0
paddedDiag i = ( padBegin i
++ elems (unsafeDiagViewBanded a i)
++ padEnd i
)
instance (Show e) => Show (Banded e) where
show a
| isHermBanded a =
"herm (" ++ show (herm a) ++ ")"
| otherwise =
let (mn,kl,es) = listsFromBanded a
in "listsBanded " ++ show mn ++ " " ++ show kl ++ " " ++ show es
compareBandedHelp :: (e -> e -> Bool)
-> Banded e -> Banded e -> Bool
compareBandedHelp cmp a b
| shape a /= shape b =
False
| isHermBanded a == isHermBanded b && bandwidths a == bandwidths b =
let elems' = if isHermBanded a then elems . herm
else elems
in
and $ zipWith cmp (elems' a) (elems' b)
| otherwise =
let l = max (numLower a) (numLower b)
u = max (numUpper a) (numUpper b)
in
and $ zipWith cmp (diagElems (-l,u) a) (diagElems (-l,u) b)
where
diagElems bw c = concatMap elems [ diagBanded c i | i <- range bw ]
instance (Eq e) => Eq (Banded e) where
(==) = compareBandedHelp (==)
instance (AEq e) => AEq (Banded e) where
(===) = compareBandedHelp (===)
(~==) = compareBandedHelp (~==)
replaceBandedHelp :: (IOBanded e -> (Int,Int) -> e -> IO ())
-> Banded e -> [((Int,Int), e)] -> Banded e
replaceBandedHelp set x ies = unsafePerformIO $ do
y <- IO.newCopyIOBanded =<< unsafeThawIOBanded x
mapM_ (uncurry $ set y) ies
unsafeFreezeIOBanded y
{-# NOINLINE replaceBandedHelp #-}
tmapBanded :: (e -> e) -> Banded e -> Banded e
tmapBanded f a@(Banded (IOBanded _ _ _ _ _ _ _ _)) =
case maybeMatrixStorageFromBanded a of
Just a' -> fromJust $
maybeBandedFromMatrixStorage (shape a) (bandwidths a) (tmap f a')
Nothing ->
let f' = conjugate . f . conjugate
in herm (tmapBanded f' (herm a))
instance ITensor Banded (Int,Int) where
(//) = replaceBandedHelp writeElem
{-# INLINE (//) #-}
unsafeReplace = replaceBandedHelp unsafeWriteElem
{-# INLINE unsafeReplace #-}
unsafeAt (Banded a) i = inlinePerformIO (unsafeReadElem a i)
{-# INLINE unsafeAt #-}
size (Banded a) = IO.sizeIOBanded a
{-# INLINE size #-}
elems (Banded a) = inlinePerformIO $ getElems a
{-# INLINE elems #-}
indices (Banded a) = IO.indicesIOBanded a
{-# INLINE indices #-}
assocs (Banded a) = inlinePerformIO $ getAssocs a
{-# INLINE assocs #-}
tmap f = tmapBanded f
{-# INLINE tmap #-}
instance (Monad m) => ReadTensor Banded (Int,Int) m where
getSize = return . size
{-# INLINE getSize #-}
getAssocs = return . assocs
{-# INLINE getAssocs #-}
getIndices = return . indices
{-# INLINE getIndices #-}
getElems = return . elems
{-# INLINE getElems #-}
getAssocs' = return . assocs
{-# INLINE getAssocs' #-}
getIndices' = return . indices
{-# INLINE getIndices' #-}
getElems' = return . elems
{-# INLINE getElems' #-}
unsafeReadElem x i = return (unsafeAt x i)
{-# INLINE unsafeReadElem #-}
instance HasVectorView Banded where
type VectorView Banded = Vector
instance HasMatrixStorage Banded where
type MatrixStorage Banded = Matrix
instance Shaped Banded (Int,Int) where
shape (Banded a) = IO.shapeIOBanded a
{-# INLINE shape #-}
bounds (Banded a) = IO.boundsIOBanded a
{-# INLINE bounds #-}
instance MatrixShaped Banded where
instance HasHerm Banded where
herm (Banded a) = Banded $ IO.hermIOBanded a
{-# INLINE herm #-}
instance BaseBanded Banded where
numLower (Banded a) = IO.numLowerIOBanded a
{-# INLINE numLower #-}
numUpper (Banded a) = IO.numUpperIOBanded a
{-# INLINE numUpper #-}
bandwidths (Banded a) = IO.bandwidthsIOBanded a
{-# INLINE bandwidths #-}
ldaBanded (Banded a) = IO.ldaIOBanded a
{-# INLINE ldaBanded #-}
transEnumBanded (Banded a) = IO.transEnumIOBanded a
{-# INLINE transEnumBanded #-}
maybeMatrixStorageFromBanded (Banded a) = liftM Matrix $ IO.maybeMatrixStorageFromIOBanded a
{-# INLINE maybeMatrixStorageFromBanded #-}
maybeBandedFromMatrixStorage mn kl (Matrix a) =
liftM Banded $ IO.maybeIOBandedFromMatrixStorage mn kl a
{-# INLINE maybeBandedFromMatrixStorage #-}
viewVectorAsBanded mn (Vector x) = Banded $ IO.viewVectorAsIOBanded mn x
{-# INLINE viewVectorAsBanded #-}
maybeViewBandedAsVector (Banded a) =
liftM Vector $ IO.maybeViewIOBandedAsVector a
{-# INLINE maybeViewBandedAsVector #-}
unsafeDiagViewBanded (Banded a) i = Vector $ IO.unsafeDiagViewIOBanded a i
{-# INLINE unsafeDiagViewBanded #-}
unsafeRowViewBanded (Banded a) i =
case IO.unsafeRowViewIOBanded a i of (nb,x,na) -> (nb, Vector x, na)
{-# INLINE unsafeRowViewBanded #-}
unsafeColViewBanded (Banded a) j =
case IO.unsafeColViewIOBanded a j of (nb,x,na) -> (nb, Vector x, na)
{-# INLINE unsafeColViewBanded #-}
unsafeIOBandedToBanded = Banded
{-# INLINE unsafeIOBandedToBanded #-}
unsafeBandedToIOBanded (Banded a) = a
{-# INLINE unsafeBandedToIOBanded #-}
-- The NOINLINE pragmas and the strictness annotations here are *really*
-- important. Otherwise, the compiler might think that certain actions
-- don't need to be run.
instance (MonadInterleave m) => ReadBanded Banded m where
freezeBanded (Banded a) = return $! unsafePerformIO $ freezeIOBanded a
{-# NOINLINE freezeBanded #-}
unsafeFreezeBanded = return . id
{-# INLINE unsafeFreezeBanded #-}
unsafePerformIOWithBanded (Banded a) f = return $! unsafePerformIO $ f a
{-# NOINLINE unsafePerformIOWithBanded #-}
instance (MonadInterleave m) => MMatrix Banded m where
unsafeDoSApplyAddVector = gbmv
{-# INLINE unsafeDoSApplyAddVector #-}
unsafeDoSApplyAddMatrix = gbmm
{-# INLINE unsafeDoSApplyAddMatrix #-}
unsafeGetRow = unsafeGetRowBanded
{-# INLINE unsafeGetRow #-}
unsafeGetCol = unsafeGetColBanded
{-# INLINE unsafeGetCol #-}
instance (MonadInterleave m) => MMatrix (Herm Banded) m where
unsafeDoSApplyAddVector = hbmv
{-# INLINE unsafeDoSApplyAddVector #-}
unsafeDoSApplyAddMatrix = hbmm
{-# INLINE unsafeDoSApplyAddMatrix #-}
unsafeGetRow = unsafeGetRowHermBanded
{-# INLINE unsafeGetRow #-}
unsafeGetCol = unsafeGetColHermBanded
{-# INLINE unsafeGetCol #-}
instance (MonadInterleave m) => MMatrix (Tri Banded) m where
unsafeDoSApplyVector_ = tbmv
{-# INLINE unsafeDoSApplyVector_ #-}
unsafeDoSApplyMatrix_ = tbmm
{-# INLINE unsafeDoSApplyMatrix_ #-}
unsafeDoSApplyAddVector = tbmv'
{-# INLINE unsafeDoSApplyAddVector #-}
unsafeDoSApplyAddMatrix = tbmm'
{-# INLINE unsafeDoSApplyAddMatrix #-}
unsafeGetRow = unsafeGetRowTriBanded
{-# INLINE unsafeGetRow #-}
unsafeGetCol = unsafeGetColTriBanded
{-# INLINE unsafeGetCol #-}
instance (MonadInterleave m) => MSolve (Tri Banded) m where
unsafeDoSSolveVector_ = tbsv
{-# INLINE unsafeDoSSolveVector_ #-}
unsafeDoSSolveMatrix_ = tbsm
{-# INLINE unsafeDoSSolveMatrix_ #-}
unsafeDoSSolveVector = tbsv'
{-# INLINE unsafeDoSSolveVector #-}
unsafeDoSSolveMatrix = tbsm'
{-# INLINE unsafeDoSSolveMatrix #-}
instance IMatrix Banded where
unsafeSApplyVector alpha a x = runSTVector $ unsafeGetSApplyVector alpha a x
{-# INLINE unsafeSApplyVector #-}
unsafeSApplyMatrix alpha a b = runSTMatrix $ unsafeGetSApplyMatrix alpha a b
{-# INLINE unsafeSApplyMatrix #-}
unsafeRow a i = runSTVector $ unsafeGetRow a i
{-# INLINE unsafeRow #-}
unsafeCol a j = runSTVector $ unsafeGetCol a j
{-# INLINE unsafeCol #-}
instance IMatrix (Herm Banded) where
unsafeSApplyVector alpha a x = runSTVector $ unsafeGetSApplyVector alpha a x
{-# INLINE unsafeSApplyVector #-}
unsafeSApplyMatrix alpha a b = runSTMatrix $ unsafeGetSApplyMatrix alpha a b
{-# INLINE unsafeSApplyMatrix #-}
unsafeRow a i = runSTVector $ unsafeGetRow a i
{-# INLINE unsafeRow #-}
unsafeCol a j = runSTVector $ unsafeGetCol a j
{-# INLINE unsafeCol #-}
instance IMatrix (Tri Banded) where
unsafeSApplyVector alpha a x = runSTVector $ unsafeGetSApplyVector alpha a x
{-# INLINE unsafeSApplyVector #-}
unsafeSApplyMatrix alpha a b = runSTMatrix $ unsafeGetSApplyMatrix alpha a b
{-# INLINE unsafeSApplyMatrix #-}
unsafeRow a i = runSTVector $ unsafeGetRow a i
{-# INLINE unsafeRow #-}
unsafeCol a j = runSTVector $ unsafeGetCol a j
{-# INLINE unsafeCol #-}
instance ISolve (Tri Banded) where
unsafeSSolveVector alpha a y = runSTVector $ unsafeGetSSolveVector alpha a y
{-# NOINLINE unsafeSSolveVector #-}
unsafeSSolveMatrix alpha a c = runSTMatrix $ unsafeGetSSolveMatrix alpha a c
{-# NOINLINE unsafeSSolveMatrix #-}
-- | Banded matrix in the 'ST' monad. The type arguments are as follows:
--
-- * @s@: the state variable argument for the 'ST' type
--
-- * @e@: the element type of the matrix. Only certain element types
-- are supported.
--
newtype STBanded s e = STBanded (IOBanded e)
-- | A safe way to create and work with a mutable banded matrix before returning
-- an immutable one for later perusal. This function avoids copying
-- the matrix before returning it - it uses unsafeFreezeBanded internally,
-- but this wrapper is a safe interface to that function.
runSTBanded :: (forall s . ST s (STBanded s e)) -> Banded e
runSTBanded mx =
runST $ mx >>= \(STBanded x) -> return (Banded x)
instance HasVectorView (STBanded s) where
type VectorView (STBanded s) = STVector s
instance HasMatrixStorage (STBanded s) where
type MatrixStorage (STBanded s) = (STMatrix s)
instance Shaped (STBanded s) (Int,Int) where
shape (STBanded a) = IO.shapeIOBanded a
{-# INLINE shape #-}
bounds (STBanded a) = IO.boundsIOBanded a
{-# INLINE bounds #-}
instance MatrixShaped (STBanded s) where
instance HasHerm (STBanded s) where
herm (STBanded a) = STBanded $ IO.hermIOBanded a
{-# INLINE herm #-}
instance ReadTensor (STBanded s) (Int,Int) (ST s) where
getSize (STBanded a) = unsafeIOToST $ IO.getSizeIOBanded a
{-# INLINE getSize #-}
getAssocs (STBanded a) = unsafeIOToST $ IO.getAssocsIOBanded a
{-# INLINE getAssocs #-}
getIndices (STBanded a) = unsafeIOToST $ IO.getIndicesIOBanded a
{-# INLINE getIndices #-}
getElems (STBanded a) = unsafeIOToST $ IO.getElemsIOBanded a
{-# INLINE getElems #-}
getAssocs' (STBanded a) = unsafeIOToST $ IO.getAssocsIOBanded' a
{-# INLINE getAssocs' #-}
getIndices' (STBanded a) = unsafeIOToST $ IO.getIndicesIOBanded' a
{-# INLINE getIndices' #-}
getElems' (STBanded a) = unsafeIOToST $ IO.getElemsIOBanded' a
{-# INLINE getElems' #-}
unsafeReadElem (STBanded a) i = unsafeIOToST $ IO.unsafeReadElemIOBanded a i
{-# INLINE unsafeReadElem #-}
instance WriteTensor (STBanded s) (Int,Int) (ST s) where
setConstant k (STBanded a) = unsafeIOToST $ IO.setConstantIOBanded k a
{-# INLINE setConstant #-}
setZero (STBanded a) = unsafeIOToST $ IO.setZeroIOBanded a
{-# INLINE setZero #-}
modifyWith f (STBanded a) = unsafeIOToST $ IO.modifyWithIOBanded f a
{-# INLINE modifyWith #-}
unsafeWriteElem (STBanded a) i e = unsafeIOToST $ IO.unsafeWriteElemIOBanded a i e
{-# INLINE unsafeWriteElem #-}
canModifyElem (STBanded a) i = unsafeIOToST $ IO.canModifyElemIOBanded a i
{-# INLINE canModifyElem #-}
instance BaseBanded (STBanded s) where
numLower (STBanded a) = IO.numLowerIOBanded a
{-# INLINE numLower #-}
numUpper (STBanded a) = IO.numUpperIOBanded a
{-# INLINE numUpper #-}
bandwidths (STBanded a) = IO.bandwidthsIOBanded a
{-# INLINE bandwidths #-}
ldaBanded (STBanded a) = IO.ldaIOBanded a
{-# INLINE ldaBanded #-}
transEnumBanded (STBanded a) = IO.transEnumIOBanded a
{-# INLINE transEnumBanded #-}
maybeMatrixStorageFromBanded (STBanded a) =
liftM STMatrix $ IO.maybeMatrixStorageFromIOBanded a
{-# INLINE maybeMatrixStorageFromBanded #-}
maybeBandedFromMatrixStorage mn kl (STMatrix a) =
liftM STBanded $ IO.maybeIOBandedFromMatrixStorage mn kl a
{-# INLINE maybeBandedFromMatrixStorage #-}
viewVectorAsBanded mn (STVector x) = STBanded $ IO.viewVectorAsIOBanded mn x
{-# INLINE viewVectorAsBanded #-}
maybeViewBandedAsVector (STBanded a) =
liftM STVector $ IO.maybeViewIOBandedAsVector a
{-# INLINE maybeViewBandedAsVector #-}
unsafeDiagViewBanded (STBanded a) i =
STVector $ IO.unsafeDiagViewIOBanded a i
{-# INLINE unsafeDiagViewBanded #-}
unsafeRowViewBanded (STBanded a) i =
case IO.unsafeRowViewIOBanded a i of (nb,x,na) -> (nb, STVector x, na)
{-# INLINE unsafeRowViewBanded #-}
unsafeColViewBanded (STBanded a) j =
case IO.unsafeColViewIOBanded a j of (nb,x,na) -> (nb, STVector x, na)
{-# INLINE unsafeColViewBanded #-}
unsafeIOBandedToBanded = STBanded
{-# INLINE unsafeIOBandedToBanded #-}
unsafeBandedToIOBanded (STBanded a) = a
{-# INLINE unsafeBandedToIOBanded #-}
instance ReadBanded (STBanded s) (ST s) where
unsafePerformIOWithBanded (STBanded a) f = unsafeIOToST $ f a
{-# INLINE unsafePerformIOWithBanded #-}
freezeBanded (STBanded a) = unsafeIOToST $ freezeIOBanded a
{-# INLINE freezeBanded #-}
unsafeFreezeBanded (STBanded a) = unsafeIOToST $ unsafeFreezeIOBanded a
{-# INLINE unsafeFreezeBanded #-}
instance WriteBanded (STBanded s) (ST s) where
newBanded_ mn bw = unsafeIOToST $ liftM STBanded $ IO.newIOBanded_ mn bw
{-# INLINE newBanded_ #-}
thawBanded = unsafeIOToST . liftM STBanded . thawIOBanded
{-# INLINE thawBanded #-}
unsafeThawBanded = unsafeIOToST . liftM STBanded . unsafeThawIOBanded
{-# INLINE unsafeThawBanded #-}
unsafeConvertIOBanded ioa = unsafeIOToST $ liftM STBanded ioa
{-# INLINE unsafeConvertIOBanded #-}
instance MMatrix (STBanded s) (ST s) where
unsafeDoSApplyAddVector = gbmv
{-# INLINE unsafeDoSApplyAddVector #-}
unsafeDoSApplyAddMatrix = gbmm
{-# INLINE unsafeDoSApplyAddMatrix #-}
unsafeGetRow = unsafeGetRowBanded
{-# INLINE unsafeGetRow #-}
unsafeGetCol = unsafeGetColBanded
{-# INLINE unsafeGetCol #-}
instance MMatrix (Herm (STBanded s)) (ST s) where
unsafeDoSApplyAddVector = hbmv
{-# INLINE unsafeDoSApplyAddVector #-}
unsafeDoSApplyAddMatrix = hbmm
{-# INLINE unsafeDoSApplyAddMatrix #-}
unsafeGetRow = unsafeGetRowHermBanded
{-# INLINE unsafeGetRow #-}
unsafeGetCol = unsafeGetColHermBanded
{-# INLINE unsafeGetCol #-}
instance MMatrix (Tri (STBanded s)) (ST s) where
unsafeDoSApplyVector_ = tbmv
{-# INLINE unsafeDoSApplyVector_ #-}
unsafeDoSApplyMatrix_ = tbmm
{-# INLINE unsafeDoSApplyMatrix_ #-}
unsafeDoSApplyAddVector = tbmv'
{-# INLINE unsafeDoSApplyAddVector #-}
unsafeDoSApplyAddMatrix = tbmm'
{-# INLINE unsafeDoSApplyAddMatrix #-}
unsafeGetRow = unsafeGetRowTriBanded
{-# INLINE unsafeGetRow #-}
unsafeGetCol = unsafeGetColTriBanded
{-# INLINE unsafeGetCol #-}
instance MSolve (Tri (STBanded s)) (ST s) where
unsafeDoSSolveVector_ = tbsv
{-# INLINE unsafeDoSSolveVector_ #-}
unsafeDoSSolveMatrix_ = tbsm
{-# INLINE unsafeDoSSolveMatrix_ #-}
unsafeDoSSolveVector = tbsv'
{-# INLINE unsafeDoSSolveVector #-}
unsafeDoSSolveMatrix = tbsm'
{-# INLINE unsafeDoSSolveMatrix #-}
|
patperry/hs-linear-algebra
|
lib/Data/Matrix/Banded/Base.hs
|
Haskell
|
bsd-3-clause
| 37,697
|
--------------------------------------------------------------------------------
-- |
-- Module : Test.Connection
-- Copyright : (C) 2017 Yorick Laupa
-- License : (see the file LICENSE)
--
-- Maintainer : Yorick Laupa <yo.eight@gmail.com>
-- Stability : provisional
-- Portability : non-portable
--
--------------------------------------------------------------------------------
module Test.Connection (spec) where
--------------------------------------------------------------------------------
import Database.EventStore.Internal.Test hiding (i)
--------------------------------------------------------------------------------
import Test.Bogus.Connection
import Test.Common
import Test.Tasty.Hspec
spec :: Spec
spec = beforeAll (createLoggerRef testGlobalLog) $ do
specify "Connection should retry on connection failure" $ \logRef -> do
counter <- newCounter
bus <- newBus logRef testSettings
let builder = alwaysFailConnectionBuilder $ incrCounter counter
disc = staticEndPointDiscovery "localhost" 2000
exec <- newExec testSettings bus builder disc
atomically $ do
i <- readCounterSTM counter
when (i /= 3) retrySTM
publishWith exec SystemShutdown
execWaitTillClosed exec
specify "Connection should close on heartbeat timeout" $ \logRef -> do
counter <- newCounter
bus <- newBus logRef testSettings
let builder = silentConnectionBuilder $ incrCounter counter
disc = staticEndPointDiscovery "localhost" 2000
exec <- newExec testSettings bus builder disc
atomically $ do
i <- readCounterSTM counter
unless (i > 1) retrySTM
publishWith exec SystemShutdown
execWaitTillClosed exec
|
YoEight/eventstore
|
tests/Test/Connection.hs
|
Haskell
|
bsd-3-clause
| 1,708
|
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
-----------------------------------------------------------------
-- Auto-generated by regenClassifiers
--
-- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
-- @generated
-----------------------------------------------------------------
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Ranking.Classifiers.RO (classifiers) where
import Prelude
import Duckling.Ranking.Types
import qualified Data.HashMap.Strict as HashMap
import Data.String
classifiers :: Classifiers
classifiers
= HashMap.fromList
[("integer (numeric)",
Classifier{okData =
ClassData{prior = -0.2876820724517809,
unseen = -2.0794415416798357,
likelihoods = HashMap.fromList [("", 0.0)], n = 6},
koData =
ClassData{prior = -1.3862943611198906,
unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2}}),
("absorption of , after named day",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.9459101490553135,
likelihoods =
HashMap.fromList
[("day", -0.6931471805599453),
("named-day", -0.6931471805599453)],
n = 2},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("acum",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("intersect",
Classifier{okData =
ClassData{prior = -0.13353139262452263,
unseen = -3.1354942159291497,
likelihoods =
HashMap.fromList
[("daymonth", -1.9924301646902063),
("dayday", -1.2992829841302609),
("<named-day> <day-of-month> (number)named-month",
-1.9924301646902063),
("absorption of , after named day<day-of-month>(number) <named-month>",
-1.9924301646902063),
("absorption of , after named day<day-of-month> (non ordinal) <named-month>",
-1.9924301646902063),
("named-daythe <day-of-month> (number)", -2.3978952727983707)],
n = 7},
koData =
ClassData{prior = -2.0794415416798357,
unseen = -2.3978952727983707,
likelihoods =
HashMap.fromList
[("named-month<hour-of-day> <integer> (as relative minutes)",
-1.6094379124341003),
("monthminute", -1.6094379124341003)],
n = 1}}),
("<named-day> <day-of-month> (number)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.4849066497880004,
likelihoods =
HashMap.fromList
[("named-dayinteger (numeric)", -1.2992829841302609),
("day", -0.7884573603642702),
("absorption of , after named dayinteger (numeric)",
-1.2992829841302609)],
n = 4},
koData =
ClassData{prior = -infinity, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [], n = 0}}),
("named-month",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [("", 0.0)], n = 5},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("numbers prefix with - or minus",
Classifier{okData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("integer (numeric)", 0.0)],
n = 1}}),
("craciun",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("the <day-of-month> (number)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("integer (numeric)", 0.0)],
n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("time-of-day (latent)",
Classifier{okData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("integer (numeric)", 0.0)],
n = 1}}),
("ieri",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("intersect by \",\"",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.4849066497880004,
likelihoods =
HashMap.fromList
[("dayday", -0.7884573603642702),
("named-day<day-of-month>(number) <named-month>",
-1.2992829841302609),
("named-day<day-of-month> (non ordinal) <named-month>",
-1.2992829841302609)],
n = 4},
koData =
ClassData{prior = -infinity, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [], n = 0}}),
("azi",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("named-day",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.1780538303479458,
likelihoods = HashMap.fromList [("", 0.0)], n = 22},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<named-day> pe <day-of-month> (number)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("named-dayinteger (numeric)", -0.6931471805599453),
("day", -0.6931471805599453)],
n = 1},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("integer (0..10)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<time> (aceasta|acesta|[a\259]sta)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.9459101490553135,
likelihoods =
HashMap.fromList
[("day", -0.6931471805599453),
("named-day", -0.6931471805599453)],
n = 2},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("<named-month> <day-of-month> (non ordinal)",
Classifier{okData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("named-monthinteger (numeric)", -0.6931471805599453),
("month", -0.6931471805599453)],
n = 1}}),
("<day-of-month> (non ordinal) <named-month>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.4849066497880004,
likelihoods =
HashMap.fromList
[("integer (numeric)named-month", -1.0116009116784799),
("integer (0..10)named-month", -1.7047480922384253),
("month", -0.7884573603642702)],
n = 4},
koData =
ClassData{prior = -infinity, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [], n = 0}}),
("this|next <day-of-week>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.9459101490553135,
likelihoods =
HashMap.fromList
[("day", -0.6931471805599453),
("named-day", -0.6931471805599453)],
n = 2},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("maine",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<month> dd-dd (interval)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("named-month", -0.6931471805599453),
("month", -0.6931471805599453)],
n = 1},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("<hour-of-day> <integer> (as relative minutes)",
Classifier{okData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("time-of-day (latent)integer (numeric)", -0.6931471805599453),
("hour", -0.6931471805599453)],
n = 1}}),
("<day-of-month>(number) <named-month>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.4849066497880004,
likelihoods =
HashMap.fromList
[("integer (numeric)named-month", -1.0116009116784799),
("integer (0..10)named-month", -1.7047480922384253),
("month", -0.7884573603642702)],
n = 4},
koData =
ClassData{prior = -infinity, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [], n = 0}})]
|
rfranek/duckling
|
Duckling/Ranking/Classifiers/RO.hs
|
Haskell
|
bsd-3-clause
| 14,669
|
module Main where
import File
import Git
main :: IO ()
main = do
pullFilesToDisk
addCommitPush "Feeling hard working today!"
|
gaoyuan/CodeThief
|
src/Main.hs
|
Haskell
|
bsd-3-clause
| 131
|
{-# LANGUAGE TemplateHaskell, RankNTypes, ScopedTypeVariables #-}
{-# LANGUAGE ViewPatterns, DeriveGeneric #-}
-- | This analysis identifies the addRef and decRef functions for a library,
-- along with the set of types that is reference counted. This analysis is
-- unsound and incomplete, but still useful.
--
-- It first identifies the decRef function with a heuristic:
--
-- 1) Find a function that conditionally calls a finalizer
--
-- 2) The finalizer call is guarded by a conditional check of an
-- access path p (whose *base* is reachable from an argument to the
-- function), and
--
-- 3) That same access path p is decremented
--
-- The incRef function is simply the function that increments access
-- path p
--
-- The set of types that are reference counted by a given
-- incRef/decRef pair are those types that are structural subtypes of
-- the argument to decRef (after derefencing the pointer, since all of
-- these types are passed by pointer).
module Foreign.Inference.Analysis.RefCount (
RefCountSummary,
identifyRefCounting,
-- * Testing
refCountSummaryToTestFormat
) where
import GHC.Generics ( Generic )
import Control.Arrow
import Control.DeepSeq
import Control.DeepSeq.Generics ( genericRnf )
import Control.Lens ( Getter, Lens', makeLenses, view, to, (%~), (^.), (.~) )
import Data.Foldable ( find )
import Data.HashSet ( HashSet )
import qualified Data.HashSet as HS
import Data.HashMap.Strict ( HashMap )
import qualified Data.HashMap.Strict as HM
import Data.Map ( Map )
import qualified Data.Map as M
import Data.Maybe ( catMaybes, mapMaybe )
import Data.Monoid
import LLVM.Analysis
import LLVM.Analysis.AccessPath
import LLVM.Analysis.CFG
import LLVM.Analysis.CallGraphSCCTraversal
import Foreign.Inference.AnalysisMonad
import Foreign.Inference.Analysis.Finalize
import Foreign.Inference.Analysis.ScalarEffects
import Foreign.Inference.Diagnostics
import Foreign.Inference.Interface
-- import Text.Printf
-- import Debug.Trace
-- debug = flip trace
-- | The data needed to track unref functions. The
-- @unrefCountAccessPath@ is the access path to the struct field that
-- serves as the reference count (and is decremented in the unref
-- function).
--
-- The @unrefFuncPtrCalls@ are the access paths of function pointers
-- called in the unref function. The idea is that these functions
-- will tell us the types that are involved in reference counting for
-- object systems like glib. For example, assuming the following line
-- is in an unref function
--
-- > obj->finalize(obj)
--
-- and (in some other function)
--
-- > obj->class = cls;
-- > cls->finalize = finalizeFoo;
--
-- and
--
-- > void finalizeFoo(Object *o) {
-- > RealObject* obj = (RealObject*)o;
-- > // use obj
-- > }
--
-- This tells us that the type RealObject is reference counted. We
-- just need to look at places where the field recorded here is
-- initialized with a function and then analyze the types used by that
-- function.
data UnrefData =
UnrefData { unrefCountAccessPath :: AbstractAccessPath
, unrefFuncPtrCalls :: [AbstractAccessPath]
, unrefWitnesses :: [Witness]
}
deriving (Eq, Generic)
instance NFData UnrefData where
rnf = genericRnf
-- | Summary information for the reference counting analysis
data RefCountSummary =
RefCountSummary { _conditionalFinalizers :: HashSet Function
, _unrefArguments :: HashMap Argument UnrefData
, _refArguments :: HashMap Argument (AbstractAccessPath, [Witness])
, _refCountedTypes :: HashMap (String, String) (HashSet Type)
, _refCountDiagnostics :: !Diagnostics
}
deriving (Generic)
$(makeLenses ''RefCountSummary)
instance Monoid RefCountSummary where
mempty = RefCountSummary mempty mempty mempty mempty mempty
mappend (RefCountSummary s1 a1 r1 rcts1 d1) (RefCountSummary s2 a2 r2 rcts2 d2) =
RefCountSummary { _conditionalFinalizers = s1 `mappend` s2
, _unrefArguments = a1 `mappend` a2
, _refArguments = r1 `mappend` r2
, _refCountedTypes = HM.unionWith HS.union rcts1 rcts2
, _refCountDiagnostics = d1 `mappend` d2
}
instance NFData RefCountSummary where
rnf = genericRnf
instance Eq RefCountSummary where
(RefCountSummary s1 a1 r1 rcts1 _) == (RefCountSummary s2 a2 r2 rcts2 _) =
s1 == s2 && a1 == a2 && r1 == r2 && rcts1 == rcts2
instance HasDiagnostics RefCountSummary where
diagnosticLens = refCountDiagnostics
-- | The summarizing functions match incref and decref functions. We
-- need to do that here rather than on the fly since either could be
-- analyzed before the other, so every analysis step would have to try
-- to match up any outstanding references. Here we can just do it on
-- demand.
--
-- Matching is done based on argument type and the access path used to
-- modify the reference count parameter. If an unref function matches
-- up with exactly one ref function, they are paired by name. The
-- code generator should deal with it appropriately.
instance SummarizeModule RefCountSummary where
summarizeFunction _ _ = []
summarizeArgument a (RefCountSummary _ unrefArgs refArgs _ _) =
case HM.lookup a unrefArgs of
Nothing ->
case HM.lookup a refArgs of
Nothing -> []
Just (fieldPath, ws) ->
case matchingTypeAndPath (argumentType a) fieldPath unrefCountAccessPath unrefArgs of
Nothing -> [(PAAddRef "", ws)]
Just fname -> [(PAAddRef fname, ws)]
Just (UnrefData fieldPath fptrPaths ws) ->
case matchingTypeAndPath (argumentType a) fieldPath fst refArgs of
Nothing -> [(PAUnref "" (mapMaybe externalizeAccessPath fptrPaths) [], ws)]
Just fname ->
let unrefFunc = argumentFunction a
unrefName = identifierAsString (functionName unrefFunc)
ssts = HS.toList $ argumentCastedTypes a
structuralSupertypes = mapMaybe (structTypeToName . stripPointerTypes) ssts
in [(PAUnref fname (mapMaybe externalizeAccessPath fptrPaths) structuralSupertypes, ws)]
summarizeType t (RefCountSummary _ _ _ rcTypes _) =
case t of
CStruct n _ ->
case find entryForType (HM.toList rcTypes) of
Nothing -> []
Just ((addRef, decRef), _) -> [(TARefCounted addRef decRef, [])]
where
entryForType (_, typeSet) =
let groupTypeNames = mapMaybe (structTypeToName . stripPointerTypes) (HS.toList typeSet)
in n `elem` groupTypeNames
_ -> []
matchingTypeAndPath :: Type
-> AbstractAccessPath
-> (a -> AbstractAccessPath)
-> HashMap Argument a
-> Maybe String
matchingTypeAndPath t accPath toPath m =
case filter matchingPair pairs of
[(singleMatch, _)] ->
let f = argumentFunction singleMatch
in Just $ identifierAsString (functionName f)
_ -> Nothing
where
pairs = HM.toList m
matchingPair (arg, d) = argumentType arg == t && (toPath d) == accPath
type Analysis = AnalysisMonad () ()
-- | The main analysis to identify both incref and decref functions.
identifyRefCounting :: forall compositeSummary funcLike . (FuncLike funcLike, HasFunction funcLike, HasCFG funcLike)
=> DependencySummary
-> Lens' compositeSummary RefCountSummary
-> Getter compositeSummary FinalizerSummary
-> Getter compositeSummary ScalarEffectSummary
-> ComposableAnalysis compositeSummary funcLike
identifyRefCounting ds lns depLens1 depLens2 =
composableDependencyAnalysisM runner refCountAnalysis lns depLens
where
runner a = runAnalysis a ds () ()
depLens :: Getter compositeSummary (FinalizerSummary, ScalarEffectSummary)
depLens = to (view depLens1 &&& view depLens2)
-- | Check to see if the given function is a conditional finalizer.
-- If it is, return the call instruction that (conditionally) invokes
-- a finalizer AND the argument being finalized.
--
-- This argument is needed for later steps.
--
-- Note that no finalizer is allowed to be a conditional finalizer
isConditionalFinalizer :: FinalizerSummary
-> Function
-> Analysis (Maybe (Instruction, Argument))
isConditionalFinalizer summ f = do
fin <- functionIsFinalizer summ f
case fin of
True -> return Nothing
False -> do
-- Find the list of all arguments that are finalized in the
-- function.
finArgs <- mapM (isFinalizerCall summ) (functionInstructions f)
case catMaybes finArgs of
-- case mapMaybe (isFinalizerCall summ) (functionInstructions f) of
[] -> return Nothing
-- If there is more than one match, ensure that they all
-- finalize the same argument. If that is not the case,
-- return Nothing
x@(_, a) : rest ->
case all (==a) (map snd rest) of
False -> return Nothing
True -> return (Just x)
isFinalizerCall :: FinalizerSummary
-> Instruction
-> Analysis (Maybe (Instruction, Argument))
isFinalizerCall summ i =
case i of
CallInst { callFunction = callee, callArguments = args } ->
callFinalizes summ i callee (map fst args)
InvokeInst { invokeFunction = callee, invokeArguments = args } ->
callFinalizes summ i callee (map fst args)
_ -> return Nothing
-- | If the given call (value + args) is a finalizer, return the
-- Argument it is finalizing. If it is a finalizer but does not
-- finalize an argument, returns Nothing.
callFinalizes :: FinalizerSummary
-> Instruction
-> Value -- ^ The called value
-> [Value] -- ^ Actual arguments
-> Analysis (Maybe (Instruction, Argument))
callFinalizes fs i callee args = do
finArgs <- mapM isFinalizedArgument (zip [0..] args)
case catMaybes finArgs of
[finArg] -> return $ Just (i, finArg)
_ -> return Nothing
where
isFinalizedArgument (ix, arg) = do
annots <- lookupArgumentSummaryList fs callee ix
case (PAFinalize `elem` annots, valueContent' arg) of
(False, _) -> return Nothing
-- We only return a hit if this is an Argument to the *caller*
-- that is being finalized
(True, ArgumentC a) -> return (Just a)
(True, _) -> return Nothing
functionIsFinalizer :: FinalizerSummary -> Function -> Analysis Bool
functionIsFinalizer fs f = do
allArgAnnots <- mapM (lookupArgumentSummaryList fs f) [0..maxArg]
return $ any argFinalizes allArgAnnots
where
maxArg = length (functionParameters f) - 1
argFinalizes annots = PAFinalize `elem` annots
refCountAnalysis :: (FuncLike funcLike, HasCFG funcLike, HasFunction funcLike)
=> (FinalizerSummary, ScalarEffectSummary)
-> funcLike
-> RefCountSummary
-> Analysis RefCountSummary
refCountAnalysis (finSumm, seSumm) funcLike summ = do
let summ' = incRefAnalysis seSumm f summ
condFinData <- isConditionalFinalizer finSumm f
rcTypes <- refCountTypes f
let summ'' = (refCountedTypes %~ HM.unionWith HS.union rcTypes) summ'
case condFinData of
Nothing -> return summ''
Just (cfi, cfa) ->
let summWithCondFin = (conditionalFinalizers %~ HS.insert f) summ''
finWitness = Witness cfi "condfin"
fptrAccessPaths = mapMaybe (indirectCallAccessPath cfa) (functionInstructions f)
-- If this is a conditional finalizer, figure out which
-- field (if any) is unrefed.
newUnref = case (decRefCountFields seSumm f, functionParameters f) of
([(accPath, decWitness)], [a]) ->
let ud = UnrefData accPath fptrAccessPaths [finWitness, decWitness]
in HM.insert a ud
_ -> id
summWithUnref = (unrefArguments %~ newUnref) summWithCondFin
in return summWithUnref
where
f = getFunction funcLike
refCountTypes :: Function -> Analysis (HashMap (String, String) (HashSet Type))
refCountTypes f = do
ds <- getDependencySummary
let fptrFuncs = mapMaybe (identifyIndicatorFields ds) (functionInstructions f)
rcTypesByField = map (id *** unaryFuncToCastedArgTypes) fptrFuncs
structuralRefTypes = mapMaybe (subtypeRefCountTypes ds) interfaceTypes
rcTypes = rcTypesByField ++ structuralRefTypes
return $ foldr (\(k, v) m -> HM.insertWith HS.union k v m) mempty rcTypes
where
interfaceTypes = functionReturnType f : map argumentType (functionParameters f)
identifyIndicatorFields ds i =
case i of
StoreInst { storeValue = (valueContent' -> FunctionC sv) } ->
case accessPath i of
Nothing -> Nothing
Just cAccPath -> do
let aAccPath = abstractAccessPath cAccPath
refFuncs <- refCountFunctionsForField ds aAccPath
return (refFuncs, sv)
_ -> Nothing
subtypeRefCountTypes :: DependencySummary
-> Type
-> Maybe ((String, String), HashSet Type)
subtypeRefCountTypes ds t0 = go t1
where
t1 = stripPointerTypes t0
go t = case t of
TypeStruct _ (structuralParent:_) _ -> do
-- If this type is known to be ref counted, just return.
-- Otherwise, check if any structural parents of this type are
-- known to be ref counted. We check this by considering the
-- constituent types of t. If the first one is a struct type,
-- that is the structural parent (since they are
-- interchangable to code expecting the parent type).
case isRefCountedObject ds t of
Just rcFuncs -> return (rcFuncs, HS.singleton t1)
Nothing -> go structuralParent
TypeStruct _ _ _ -> do
rcFuncs <- isRefCountedObject ds t
return (rcFuncs, HS.singleton t1)
_ -> Nothing
-- | If the function is unary, return a set with the type of that
-- argument along with all of the types it is casted to in the body of
-- the function
unaryFuncToCastedArgTypes :: Function -> HashSet Type
unaryFuncToCastedArgTypes f =
case functionParameters f of
[p] -> argumentCastedTypes p
_ -> mempty
argumentCastedTypes :: Argument -> HashSet Type
argumentCastedTypes a =
fst $ foldr captureCastedType s0 (functionInstructions f)
where
f = argumentFunction a
s0 = (HS.singleton (argumentType a), HS.singleton (toValue a))
captureCastedType i acc@(ts, vs) =
case i of
BitcastInst { castedValue = cv } ->
case cv `HS.member` vs of
False -> acc
True -> (HS.insert (valueType i) ts, HS.insert (toValue i) vs)
_ -> acc
incRefAnalysis :: ScalarEffectSummary -> Function -> RefCountSummary -> RefCountSummary
incRefAnalysis seSumm f summ =
case (incRefCountFields seSumm f, functionParameters f) of
([], _) -> summ
([(fieldPath, w)], [a]) ->
let newAddRef = HM.insert a (fieldPath, [w]) (summ ^. refArguments)
in (refArguments .~ newAddRef) summ
_ -> summ
-- Note, here pass in the argument that is conditionally finalized. It should
-- be an argument to this indirect call. Additionally, the base of the access
-- path should be this argument
-- | If the instruction is an indirect function call, return the
-- *concrete* AccessPath from which the function pointer was obtained.
indirectCallAccessPath :: Argument -> Instruction -> Maybe AbstractAccessPath
indirectCallAccessPath arg i =
case i of
CallInst { callFunction = f, callArguments = actuals } ->
notDirect f (map fst actuals)
InvokeInst { invokeFunction = f, invokeArguments = actuals } ->
notDirect f (map fst actuals)
_ -> Nothing
where
-- The only indirect calls occur through a load instruction.
-- Additionally, we want the Argument input to the caller to
-- appear in the argument list of the indirect call.
--
-- Ideally, we would like to ensure that the function pointer
-- being invoked is in some way derived from the argument being
-- finalized. This is a kind of backwards reachability from the
-- base of the access path
notDirect v actuals =
case (any (isSameArg arg) actuals, valueContent' v) of
(True, InstructionC callee@LoadInst {}) -> do
accPath <- accessPath callee
return $! abstractAccessPath accPath
_ -> Nothing
isSameArg :: Argument -> Value -> Bool
isSameArg arg v =
case valueContent' v of
ArgumentC a -> arg == a
_ -> False
-- FIXME: Equality with arg isn't enough because of bitcasts
-- | Find all of the fields of argument objects that are decremented
-- in the given Function, returning the affected AbstractAccessPaths
decRefCountFields :: ScalarEffectSummary -> Function -> [(AbstractAccessPath, Witness)]
decRefCountFields seSumm f = mapMaybe (checkDecRefCount seSumm) allInsts
where
allInsts = concatMap basicBlockInstructions (functionBody f)
-- | Likewise, but for incremented fields
incRefCountFields :: ScalarEffectSummary -> Function -> [(AbstractAccessPath, Witness)]
incRefCountFields seSumm f = mapMaybe (checkIncRefCount seSumm) allInsts
where
allInsts = concatMap basicBlockInstructions (functionBody f)
-- | This function checks whether or not the given 'Instruction'
-- decrements a reference count (really, any integer field embedded in
-- an object). If it does, the function returns the
-- AbstractAccessPath that was decremented.
--
-- FIXME: Add support for cmpxchg?
checkDecRefCount :: ScalarEffectSummary
-> Instruction
-> Maybe (AbstractAccessPath, Witness)
checkDecRefCount seSumm i = do
p <- case i of
AtomicRMWInst { atomicRMWOperation = AOSub
, atomicRMWValue = (valueContent ->
ConstantC ConstantInt { constantIntValue = 1 })} ->
absPathIfArg i
AtomicRMWInst { atomicRMWOperation = AOAdd
, atomicRMWValue =
(valueContent -> ConstantC ConstantInt { constantIntValue = -1 })} ->
absPathIfArg i
StoreInst { storeValue = (valueContent' ->
InstructionC SubInst { binaryRhs = (valueContent' ->
ConstantC ConstantInt { constantIntValue = 1 })
, binaryLhs = (valueContent' ->
InstructionC oldRefCount) })} ->
absPathIfArg oldRefCount
StoreInst { storeValue = (valueContent' ->
InstructionC AddInst { binaryRhs = (valueContent' ->
ConstantC ConstantInt { constantIntValue = -1 })
, binaryLhs = (valueContent' ->
InstructionC oldRefCount) })} ->
absPathIfArg oldRefCount
StoreInst { storeValue = (valueContent' ->
InstructionC AddInst { binaryLhs = (valueContent' ->
ConstantC ConstantInt { constantIntValue = -1 })
, binaryRhs = (valueContent' ->
InstructionC oldRefCount) })} ->
absPathIfArg oldRefCount
CallInst { callFunction = (valueContent' -> FunctionC f)
, callArguments = [(a,_)]
} ->
absPathThroughCall seSumm scalarEffectSubOne (functionParameters f) a
InvokeInst { invokeFunction = (valueContent' -> FunctionC f)
, invokeArguments = [(a,_)]
} ->
absPathThroughCall seSumm scalarEffectSubOne (functionParameters f) a
_ -> Nothing
return (p, Witness i "decr")
-- | Analogous to 'checkDecRefCount', but for increments
checkIncRefCount :: ScalarEffectSummary
-> Instruction
-> Maybe (AbstractAccessPath, Witness)
checkIncRefCount seSumm i = do
p <- case i of
AtomicRMWInst { atomicRMWOperation = AOAdd
, atomicRMWValue = (valueContent ->
ConstantC ConstantInt { constantIntValue = 1 })} ->
absPathIfArg i
AtomicRMWInst { atomicRMWOperation = AOSub
, atomicRMWValue =
(valueContent -> ConstantC ConstantInt { constantIntValue = -1 })} ->
absPathIfArg i
StoreInst { storeValue = (valueContent' ->
InstructionC SubInst { binaryRhs = (valueContent' ->
ConstantC ConstantInt { constantIntValue = -1 })
, binaryLhs = (valueContent' ->
InstructionC oldRefCount) })} ->
absPathIfArg oldRefCount
StoreInst { storeValue = (valueContent' ->
InstructionC AddInst { binaryRhs = (valueContent' ->
ConstantC ConstantInt { constantIntValue = 1 })
, binaryLhs = (valueContent' ->
InstructionC oldRefCount) })} ->
absPathIfArg oldRefCount
StoreInst { storeValue = (valueContent' ->
InstructionC AddInst { binaryLhs = (valueContent' ->
ConstantC ConstantInt { constantIntValue = 1 })
, binaryRhs = (valueContent' ->
InstructionC oldRefCount) })} ->
absPathIfArg oldRefCount
CallInst { callFunction = (valueContent' -> FunctionC f)
, callArguments = [(a,_)]
} ->
absPathThroughCall seSumm scalarEffectAddOne (functionParameters f) a
InvokeInst { invokeFunction = (valueContent' -> FunctionC f)
, invokeArguments = [(a,_)]
} ->
absPathThroughCall seSumm scalarEffectAddOne (functionParameters f) a
_ -> Nothing
return (p, Witness i "incr")
-- | At a call site, if the callee has a scalar effect on its argument,
-- match up the access path of the actual argument passed to the callee
-- with the access path affected by the callee.
--
-- The scalar effect desired is controlled by the second argument and
-- should probably be one of
--
-- * scalarEffectAddOne
--
-- * scalarEffectSubOne
--
-- This function is meant to determine the effective abstract access
-- path of increments/decrements performed by called functions on data
-- in the caller. For example:
--
-- > void decRef(Object * o) {
-- > atomic_dec(&o->refCount);
-- > }
--
-- In this example, @atomic_dec@ only decrements the location passed
-- to it. The abstract access path of the call instruction, however,
-- (and the value returned by this function) is Object/refCount.
--
-- This function deals only with single-argument callees
absPathThroughCall :: ScalarEffectSummary
-> (ScalarEffectSummary -> Argument -> Maybe AbstractAccessPath) -- ^ Type of access
-> [Argument] -- ^ Argument list of the callee
-> Value -- ^ Actual argument at call site
-> Maybe AbstractAccessPath
absPathThroughCall seSumm effect [singleFormal] actual = do
-- This is the access path of the argument of the callee (if and
-- only if the function subtracts one from an int component of the
-- argument). The access path describes *which* component of the
-- argument is modified.
calleeAccessPath <- effect seSumm singleFormal
case valueContent' actual of
InstructionC i -> do
actualAccessPath <- accessPath i
-- Now see if the actual passed to this call is derived from one
-- of the formal parameters of the current function. This
-- access path tells us which component of the argument was
-- passed to the callee.
case valueContent' (accessPathBaseValue actualAccessPath) of
-- If it really was derived from an argument, connect up
-- the access paths for the caller and callee so we have a
-- single description of the field that was modified
-- (interprocedurally).
ArgumentC _ ->
abstractAccessPath actualAccessPath `appendAccessPath` calleeAccessPath
_ -> Nothing
_ -> Nothing
absPathThroughCall _ _ _ _ = Nothing
-- | If the Instruction produces an access path rooted at an Argument,
-- return the corresponding AbstractAccessPath
absPathIfArg :: Instruction -> Maybe AbstractAccessPath
absPathIfArg i =
case accessPath i of
Nothing -> Nothing
Just cap ->
case valueContent' (accessPathBaseValue cap) of
ArgumentC _ -> Just (abstractAccessPath cap)
_ -> Nothing
-- Testing
-- | Extract a map of unref functions to ref functions
refCountSummaryToTestFormat :: RefCountSummary -> Map String String
refCountSummaryToTestFormat (RefCountSummary _ unrefArgs refArgs _ _) =
foldr addIfRefFound mempty (HM.toList unrefArgs)
where
addIfRefFound (uarg, UnrefData fieldPath _ _) acc =
let ufunc = identifierAsString $ functionName $ argumentFunction uarg
in case matchingTypeAndPath (argumentType uarg) fieldPath fst refArgs of
Nothing -> acc
Just rfunc -> M.insert ufunc rfunc acc
|
travitch/foreign-inference
|
src/Foreign/Inference/Analysis/RefCount.hs
|
Haskell
|
bsd-3-clause
| 24,835
|
{-# LANGUAGE OverloadedStrings #-}
module Juno.Monitoring.EkgSnap
( startServer
) where
import Control.Exception (throwIO)
import Control.Monad.IO.Class (liftIO)
import qualified Data.ByteString as S
import qualified Data.ByteString.Char8 as S8
import Data.Function (on)
import qualified Data.HashMap.Strict as M
import qualified Data.List as List
import qualified Data.Text.Encoding as T
import Data.Word (Word8)
import Network.Socket (NameInfoFlag(NI_NUMERICHOST), addrAddress, getAddrInfo,
getNameInfo)
import Prelude hiding (read)
import Snap.Core (MonadSnap, Request, Snap, finishWith, getHeaders, getRequest,
getResponse, method, Method(GET), modifyResponse, pass,
rqPathInfo, setContentType, setResponseStatus,
writeLBS)
import Snap.Http.Server (httpServe)
import qualified Snap.Http.Server.Config as Config
import System.Metrics
-- Juno Change!
import Juno.Monitoring.EkgJson
import qualified Snap.Core as Snap
------------------------------------------------------------------------
-- | Convert a host name (e.g. \"localhost\" or \"127.0.0.1\") to a
-- numeric host address (e.g. \"127.0.0.1\").
getNumericHostAddress :: S.ByteString -> IO S.ByteString
getNumericHostAddress host = do
ais <- getAddrInfo Nothing (Just (S8.unpack host)) Nothing
case ais of
[] -> unsupportedAddressError
(ai:_) -> do
ni <- getNameInfo [NI_NUMERICHOST] True False (addrAddress ai)
case ni of
(Just numericHost, _) -> return $! S8.pack numericHost
_ -> unsupportedAddressError
where
unsupportedAddressError = throwIO $
userError $ "unsupported address: " ++ S8.unpack host
startServer :: Store
-> S.ByteString -- ^ Host to listen on (e.g. \"localhost\")
-> Int -- ^ Port to listen on (e.g. 8000)
-> IO ()
startServer store host port = do
-- Snap doesn't allow for non-numeric host names in
-- 'Snap.setBind'. We work around that limitation by converting a
-- possible non-numeric host name to a numeric address.
numericHost <- getNumericHostAddress host
let conf = Config.setVerbose False $
Config.setErrorLog Config.ConfigNoLog $
Config.setAccessLog Config.ConfigNoLog $
Config.setPort port $
Config.setHostname host $
Config.setBind numericHost $
Config.defaultConfig
httpServe conf (monitor store)
-- | A handler that can be installed into an existing Snap application.
monitor :: Store -> Snap ()
monitor store = do
-- Juno Change!
Snap.modifyResponse $ Snap.addHeader "Access-Control-Allow-Origin" "*"
jsonHandler $ serve store
where
jsonHandler = wrapHandler "application/json"
wrapHandler fmt handler = method GET $ format fmt $ handler
-- | The Accept header of the request.
acceptHeader :: Request -> Maybe S.ByteString
acceptHeader req = S.intercalate "," <$> getHeaders "Accept" req
-- | Runs a Snap monad action only if the request's Accept header
-- matches the given MIME type.
format :: MonadSnap m => S.ByteString -> m a -> m a
format fmt action = do
req <- getRequest
let acceptHdr = (List.head . parseHttpAccept) <$> acceptHeader req
case acceptHdr of
Just hdr | hdr == fmt -> action
_ -> pass
-- | Serve all counter, gauges and labels, built-in or not, as a
-- nested JSON object.
serve :: MonadSnap m => Store -> m ()
serve store = do
req <- getRequest
modifyResponse $ setContentType "application/json"
if S.null (rqPathInfo req)
then serveAll
else serveOne (rqPathInfo req)
where
serveAll = do
metrics <- liftIO $ sampleAll store
writeLBS $ encodeAll metrics
serveOne pathInfo = do
let segments = S8.split '/' pathInfo
nameBytes = S8.intercalate "." segments
case T.decodeUtf8' nameBytes of
Left _ -> do
modifyResponse $ setResponseStatus 400 "Bad Request"
r <- getResponse
finishWith r
Right name -> do
metrics <- liftIO $ sampleAll store
case M.lookup name metrics of
Nothing -> pass
Just metric -> writeLBS $ encodeOne metric
------------------------------------------------------------------------
-- Utilities for working with accept headers
-- | Parse the HTTP accept string to determine supported content types.
parseHttpAccept :: S.ByteString -> [S.ByteString]
parseHttpAccept = List.map fst
. List.sortBy (rcompare `on` snd)
. List.map grabQ
. S.split 44 -- comma
where
rcompare :: Double -> Double -> Ordering
rcompare = flip compare
grabQ s =
let (s', q) = breakDiscard 59 s -- semicolon
(_, q') = breakDiscard 61 q -- equals sign
in (trimWhite s', readQ $ trimWhite q')
readQ s = case reads $ S8.unpack s of
(x, _):_ -> x
_ -> 1.0
trimWhite = S.dropWhile (== 32) -- space
breakDiscard :: Word8 -> S.ByteString -> (S.ByteString, S.ByteString)
breakDiscard w s =
let (x, y) = S.break (== w) s
in (x, S.drop 1 y)
|
buckie/juno
|
src/Juno/Monitoring/EkgSnap.hs
|
Haskell
|
bsd-3-clause
| 5,304
|
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE LambdaCase #-}
module Pusher where
import Network.Google.Logging.Types
import Data.Scientific (fromFloatDigits)
import Data.Bifunctor (second)
import Data.Bits (shiftR, xor, (.&.))
import Data.Word (Word32)
import GHC.Int (Int32, Int64)
import Data.Time (UTCTime)
import Data.Time.Format (defaultTimeLocale, formatTime)
import Data.Time.Clock.POSIX (posixSecondsToUTCTime)
import Data.Maybe (fromMaybe)
import Data.ProtoLens.Encoding (decodeMessage)
import GHC.Generics (Generic)
import Network.Wai
(Application, rawPathInfo, responseLBS, Request, Response,
lazyRequestBody)
import Network.HTTP.Types.Status
(status404, status400, status422, status204)
import Data.Aeson (eitherDecode, FromJSON)
import Data.Text (Text)
import Network.Google.PubSub (PubsubMessage, pmData)
import Control.Lens ((^.), (.~), (&), (^?))
import Control.Monad.Log (Handler)
import qualified Data.Aeson as Aeson
import qualified Data.Text as Text
import qualified Data.ByteString.Lazy.Char8 as BSLC8
import qualified Proto.CommonLogRep as ProtoBuf
import qualified Proto.Timestamp as ProtoBuf
import qualified Proto.Struct as ProtoBuf
import qualified Data.HashMap.Strict as HashMap
import qualified Data.Map.Strict as Map
import qualified Data.Vector as Vector
-- | Push request body
-- https://cloud.google.com/pubsub/docs/subscriber#receive
data PushMessage = PushMessage
{ message :: PubsubMessage
, subscription :: Text
} deriving (Generic)
instance FromJSON PushMessage
app :: Handler IO LogEntry -> Application
app logger request respond =
case rawPathInfo request of
"/push" -> pusher logger request >>= respond
_ ->
respond
(responseLBS
status404
[("Content-Type", "plain/text")]
"not found - 404")
pusher :: Handler IO LogEntry -> Request -> IO Response
pusher logger request =
lazyRequestBody request >>=
\body ->
case eitherDecode body :: Either String PushMessage of
Left err ->
return
(responseLBS
status400
[("Content-Type", "plain/text")]
(BSLC8.pack err))
Right res ->
case decodeMessage (fromMaybe "" ((message res) ^. pmData)) :: Either String ProtoBuf.LogEntry of
Left err ->
return
(responseLBS
status422
[("Content-Type", "plain/text")]
(BSLC8.pack err))
Right res' ->
logger ( localiso res' ) >>
return
(responseLBS
status204
[("Content-Type", "plain/text")]
"ok")
localiso :: ProtoBuf.LogEntry -> LogEntry
localiso le =
((((((((logEntry & leJSONPayload .~ (jsonpayload' <$> le ^? ProtoBuf.jsonpayload))
& leOperation .~ (operation' <$> le ^? ProtoBuf.operation))
& leLabels .~ ((logEntryLabels . HashMap.fromList . Map.toList) <$> le ^? ProtoBuf.labels))
& leHTTPRequest .~ (httprequest' <$> le ^? ProtoBuf.httprequest))
& leSeverity .~ (showSeverity <$> le ^? ProtoBuf.severity))
& leTimestamp .~ (showTimestamp <$> (le ^? ProtoBuf.timestamp)))
& leResource .~ (resource' <$> (le ^? ProtoBuf.resource)))
& leLogName .~ (le ^? ProtoBuf.logname))
jsonpayload' :: ProtoBuf.Struct -> LogEntryJSONPayload
jsonpayload' jsonstruct =
(logEntryJSONPayload
(fromProtoBufStructToJson jsonstruct))
operation' :: ProtoBuf.LogEntryOperation -> LogEntryOperation
operation' oprtn =
((((logEntryOperation & leoLast .~ (oprtn ^? ProtoBuf.last))
& leoFirst .~ (oprtn ^? ProtoBuf.first))
& leoProducer .~ (oprtn ^? ProtoBuf.producer))
& leoId .~ (oprtn ^? ProtoBuf.id))
httprequest' :: ProtoBuf.HttpRequest -> HTTPRequest
httprequest' httpr =
((((((((((((hTTPRequest & httprCacheValidatedWithOriginServer .~ (httpr ^? ProtoBuf.cachevalidatewithoriginserver))
& httprCacheHit .~ (httpr ^? ProtoBuf.cachehit))
& httprCacheLookup .~ (httpr ^? ProtoBuf.cachelookup))
& httprReferer .~ (httpr ^? ProtoBuf.referer))
& httprRemoteIP .~ (httpr ^? ProtoBuf.remoteip))
& httprUserAgent .~ (httpr ^? ProtoBuf.useragent))
& httprResponseSize .~ (fromTextToInt64 <$> httpr ^? ProtoBuf.responsesize))
& httprRequestMethod .~ (httpr ^? ProtoBuf.requestmethod))
& httprRequestSize .~ (fromTextToInt64 <$> httpr ^? ProtoBuf.requestsize))
& httprCacheFillBytes .~ (fromTextToInt64 <$> httpr ^? ProtoBuf.cachefillbytes))
& httprRequestURL .~ (httpr ^? ProtoBuf.requesturl))
& httprStatus .~ (zzDecode32 <$> (httpr ^? ProtoBuf.status)))
resource' :: ProtoBuf.MonitoredResource -> MonitoredResource
resource' res =
let labels' =
case res ^? ProtoBuf.labels of
Nothing -> Nothing
Just res' ->
Just
(monitoredResourceLabels
(HashMap.fromList (Map.toList res')))
in ((monitoredResource & mrType .~ (res ^? ProtoBuf.type'))
& mrLabels .~ labels')
fromTimestampToUTCTime :: ProtoBuf.Timestamp -> UTCTime
fromTimestampToUTCTime tmstp =
posixSecondsToUTCTime
(fromInteger (fromIntegral (tmstp ^. ProtoBuf.seconds)))
-- | A timestamp in RFC3339 UTC "Zulu" format, accurate to nanoseconds.
-- Example: "2014-10-02T15:01:23.045123456Z".
showTimestamp :: ProtoBuf.Timestamp -> UTCTime
showTimestamp =
fromTimestampToUTCTime
showSeverity :: ProtoBuf.LogSeverity -> LogEntrySeverity
showSeverity =
\case
ProtoBuf.DEFAULT -> Default
ProtoBuf.DEBUG -> Debug
ProtoBuf.INFO -> Info
ProtoBuf.NOTICE -> Notice
ProtoBuf.WARNING -> Warning
ProtoBuf.ERROR -> Error'
ProtoBuf.CRITICAL -> Critical
ProtoBuf.ALERT -> Alert
ProtoBuf.EMERGENCY -> Emergency
-- | I took from
-- <https://www.stackage.org/haddock/lts-7.4/protobuf-0.2.1.1/src/Data.ProtocolBuffers.Wire.html#zzDecode32 protobuf>
-- see where find this solution them ;)
zzDecode32 :: Word32 -> Int32
zzDecode32 w =
fromIntegral (w `shiftR` 1) `xor` negate (fromIntegral (w .&. 1))
fromTextToInt64 :: Text -> Int64
fromTextToInt64 = read . Text.unpack
fromProtoBufStructValueToAesonValue :: ProtoBuf.Value -> Aeson.Value
fromProtoBufStructValueToAesonValue value =
case value ^? ProtoBuf.numberValue of
Just num -> Aeson.Number (fromFloatDigits num)
Nothing ->
case value ^? ProtoBuf.stringValue of
Just str -> Aeson.String str
Nothing ->
case value ^? ProtoBuf.boolValue of
Just bln -> Aeson.Bool bln
Nothing ->
case value ^? ProtoBuf.structValue of
Just obj ->
Aeson.Object (fromProtoBufStructToJson obj)
Nothing ->
case value ^? ProtoBuf.listValue of
Just arr ->
Aeson.Array
(Vector.fromList
(map
fromProtoBufStructValueToAesonValue
(arr ^.
ProtoBuf.values)))
Nothing ->
case value ^? ProtoBuf.nullValue of
Just _ -> Aeson.Null
Nothing -> Aeson.Null
fromProtoBufStructToJson :: ProtoBuf.Struct -> HashMap.HashMap Text Aeson.Value
fromProtoBufStructToJson jsonstruct =
HashMap.fromList
(map
(second fromProtoBufStructValueToAesonValue)
(Map.toList (jsonstruct ^. ProtoBuf.fields)))
|
dp-cylme/labourer
|
src/Pusher.hs
|
Haskell
|
bsd-3-clause
| 8,865
|
{-# LANGUAGE OverloadedStrings #-}
{- |
Module : Network.MPD.Applicative.ClientToClient
Copyright : (c) Joachim Fasting 2013
License : MIT
Maintainer : joachim.fasting@gmail.com
Stability : stable
Portability : unportable
Client to client communication.
-}
module Network.MPD.Applicative.ClientToClient
( -- * Types
ChannelName
, MessageText
-- * Subscribing to channels
, subscribe
, unsubscribe
, channels
-- * Communicating with other clients
, readMessages
, sendMessage
) where
import Control.Applicative
import Network.MPD.Commands.Arg hiding (Command)
import Network.MPD.Applicative.Internal
import Network.MPD.Applicative.Util
import Network.MPD.Util
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.UTF8 as UTF8
------------------------------------------------------------------------
type ChannelName = String
type MessageText = String
------------------------------------------------------------------------
subscribe :: ChannelName -> Command ()
subscribe name = Command emptyResponse ["subscribe" <@> name]
unsubscribe :: ChannelName -> Command ()
unsubscribe name = Command emptyResponse ["unsubscribe" <@> name]
channels :: Command [ChannelName]
channels = Command p ["channels"]
where
p = map UTF8.toString . takeValues <$> getResponse
------------------------------------------------------------------------
readMessages :: Command [(ChannelName, MessageText)]
readMessages = Command (liftParser p) ["readmessages"]
where
p = mapM parseMessage . splitGroups ["channel"] . toAssocList
parseMessage :: [(ByteString, ByteString)] -> Either String (ChannelName, MessageText)
parseMessage [("channel", ch),("message", msg)] = Right (UTF8.toString ch, UTF8.toString msg)
parseMessage _ = Left "Unexpected result from readMessages"
sendMessage :: ChannelName -> MessageText -> Command ()
sendMessage name text = Command emptyResponse ["sendmessage" <@> name <++> text]
|
beni55/libmpd-haskell
|
src/Network/MPD/Applicative/ClientToClient.hs
|
Haskell
|
mit
| 2,070
|
import qualified Data.Map as Map
import qualified Protein as P
-- | The prefix spectrum of a weighted string is the collection of all its
-- prefix weights. Given a list L of n (n≤100) positive real numbers,
-- return a protein string of length n−1 whose prefix spectrum is equal to L.
--
-- Notes:
-- If multiple solutions exist, pick any.
-- Consult the monoisotopic mass table.
--
-- >>> 3524.8542
-- >>> 3710.9335
-- >>> 3841.974
-- >>> 3970.0326
-- >>> 4057.0646
-- WMQS
-- | looks up a mass weights and returns list of possible proteins
spec :: Foldable t => t Double -> [[P.AminoAcid]]
spec masses =
let parseWeight = \acc m -> findMatches m : acc
findMatches m = Map.foldrWithKey (compareMass m) [] P.massTable
compareMass m = \k v acc -> if (abs(v-m) < 0.001) then k : acc else acc
in reverse $ foldl parseWeight [] masses
main = do
inp <- getContents
let weights = map (\l -> read l :: Double) $ lines inp
masses = zip weights (tail weights)
prots = spec $ map (\(a,b) -> abs(a-b)) masses
if length weights < 2
then print "not enough elements" >> print weights
else print (concat prots)
|
mitochon/hoosalind
|
src/problems/spec.hs
|
Haskell
|
mit
| 1,153
|
yes = [(foo bar)]
|
bitemyapp/apply-refact
|
tests/examples/Bracket10.hs
|
Haskell
|
bsd-3-clause
| 17
|
{-# LANGUAGE Unsafe #-}
{-# LANGUAGE ExistentialQuantification, NoImplicitPrelude #-}
module GHC.Event.Internal
(
-- * Event back end
Backend
, backend
, delete
, poll
, modifyFd
, modifyFdOnce
-- * Event type
, Event
, evtRead
, evtWrite
, evtClose
, eventIs
-- * Lifetimes
, Lifetime(..)
, EventLifetime
, eventLifetime
, elLifetime
, elEvent
-- * Timeout type
, Timeout(..)
-- * Helpers
, throwErrnoIfMinus1NoRetry
) where
import Data.Bits ((.|.), (.&.))
import Data.OldList (foldl', filter, intercalate, null)
import Foreign.C.Error (eINTR, getErrno, throwErrno)
import System.Posix.Types (Fd)
import GHC.Base
import GHC.Word (Word64)
import GHC.Num (Num(..))
import GHC.Show (Show(..))
import Data.Semigroup.Internal (stimesMonoid)
-- | An I\/O event.
newtype Event = Event Int
deriving Eq -- ^ @since 4.4.0.0
evtNothing :: Event
evtNothing = Event 0
{-# INLINE evtNothing #-}
-- | Data is available to be read.
evtRead :: Event
evtRead = Event 1
{-# INLINE evtRead #-}
-- | The file descriptor is ready to accept a write.
evtWrite :: Event
evtWrite = Event 2
{-# INLINE evtWrite #-}
-- | Another thread closed the file descriptor.
evtClose :: Event
evtClose = Event 4
{-# INLINE evtClose #-}
eventIs :: Event -> Event -> Bool
eventIs (Event a) (Event b) = a .&. b /= 0
-- | @since 4.4.0.0
instance Show Event where
show e = '[' : (intercalate "," . filter (not . null) $
[evtRead `so` "evtRead",
evtWrite `so` "evtWrite",
evtClose `so` "evtClose"]) ++ "]"
where ev `so` disp | e `eventIs` ev = disp
| otherwise = ""
-- | @since 4.10.0.0
instance Semigroup Event where
(<>) = evtCombine
stimes = stimesMonoid
-- | @since 4.4.0.0
instance Monoid Event where
mempty = evtNothing
mconcat = evtConcat
evtCombine :: Event -> Event -> Event
evtCombine (Event a) (Event b) = Event (a .|. b)
{-# INLINE evtCombine #-}
evtConcat :: [Event] -> Event
evtConcat = foldl' evtCombine evtNothing
{-# INLINE evtConcat #-}
-- | The lifetime of an event registration.
--
-- @since 4.8.1.0
data Lifetime = OneShot -- ^ the registration will be active for only one
-- event
| MultiShot -- ^ the registration will trigger multiple times
deriving ( Show -- ^ @since 4.8.1.0
, Eq -- ^ @since 4.8.1.0
)
-- | The longer of two lifetimes.
elSupremum :: Lifetime -> Lifetime -> Lifetime
elSupremum OneShot OneShot = OneShot
elSupremum _ _ = MultiShot
{-# INLINE elSupremum #-}
-- | @since 4.10.0.0
instance Semigroup Lifetime where
(<>) = elSupremum
stimes = stimesMonoid
-- | @mappend@ takes the longer of two lifetimes.
--
-- @since 4.8.0.0
instance Monoid Lifetime where
mempty = OneShot
-- | A pair of an event and lifetime
--
-- Here we encode the event in the bottom three bits and the lifetime
-- in the fourth bit.
newtype EventLifetime = EL Int
deriving ( Show -- ^ @since 4.8.0.0
, Eq -- ^ @since 4.8.0.0
)
-- | @since 4.11.0.0
instance Semigroup EventLifetime where
EL a <> EL b = EL (a .|. b)
-- | @since 4.8.0.0
instance Monoid EventLifetime where
mempty = EL 0
eventLifetime :: Event -> Lifetime -> EventLifetime
eventLifetime (Event e) l = EL (e .|. lifetimeBit l)
where
lifetimeBit OneShot = 0
lifetimeBit MultiShot = 8
{-# INLINE eventLifetime #-}
elLifetime :: EventLifetime -> Lifetime
elLifetime (EL x) = if x .&. 8 == 0 then OneShot else MultiShot
{-# INLINE elLifetime #-}
elEvent :: EventLifetime -> Event
elEvent (EL x) = Event (x .&. 0x7)
{-# INLINE elEvent #-}
-- | A type alias for timeouts, specified in nanoseconds.
data Timeout = Timeout {-# UNPACK #-} !Word64
| Forever
deriving Show -- ^ @since 4.4.0.0
-- | Event notification backend.
data Backend = forall a. Backend {
_beState :: !a
-- | Poll backend for new events. The provided callback is called
-- once per file descriptor with new events.
, _bePoll :: a -- backend state
-> Maybe Timeout -- timeout in milliseconds ('Nothing' for non-blocking poll)
-> (Fd -> Event -> IO ()) -- I/O callback
-> IO Int
-- | Register, modify, or unregister interest in the given events
-- on the given file descriptor.
, _beModifyFd :: a
-> Fd -- file descriptor
-> Event -- old events to watch for ('mempty' for new)
-> Event -- new events to watch for ('mempty' to delete)
-> IO Bool
-- | Register interest in new events on a given file descriptor, set
-- to be deactivated after the first event.
, _beModifyFdOnce :: a
-> Fd -- file descriptor
-> Event -- new events to watch
-> IO Bool
, _beDelete :: a -> IO ()
}
backend :: (a -> Maybe Timeout -> (Fd -> Event -> IO ()) -> IO Int)
-> (a -> Fd -> Event -> Event -> IO Bool)
-> (a -> Fd -> Event -> IO Bool)
-> (a -> IO ())
-> a
-> Backend
backend bPoll bModifyFd bModifyFdOnce bDelete state =
Backend state bPoll bModifyFd bModifyFdOnce bDelete
{-# INLINE backend #-}
poll :: Backend -> Maybe Timeout -> (Fd -> Event -> IO ()) -> IO Int
poll (Backend bState bPoll _ _ _) = bPoll bState
{-# INLINE poll #-}
-- | Returns 'True' if the modification succeeded.
-- Returns 'False' if this backend does not support
-- event notifications on this type of file.
modifyFd :: Backend -> Fd -> Event -> Event -> IO Bool
modifyFd (Backend bState _ bModifyFd _ _) = bModifyFd bState
{-# INLINE modifyFd #-}
-- | Returns 'True' if the modification succeeded.
-- Returns 'False' if this backend does not support
-- event notifications on this type of file.
modifyFdOnce :: Backend -> Fd -> Event -> IO Bool
modifyFdOnce (Backend bState _ _ bModifyFdOnce _) = bModifyFdOnce bState
{-# INLINE modifyFdOnce #-}
delete :: Backend -> IO ()
delete (Backend bState _ _ _ bDelete) = bDelete bState
{-# INLINE delete #-}
-- | Throw an 'Prelude.IOError' corresponding to the current value of
-- 'getErrno' if the result value of the 'IO' action is -1 and
-- 'getErrno' is not 'eINTR'. If the result value is -1 and
-- 'getErrno' returns 'eINTR' 0 is returned. Otherwise the result
-- value is returned.
throwErrnoIfMinus1NoRetry :: (Eq a, Num a) => String -> IO a -> IO a
throwErrnoIfMinus1NoRetry loc f = do
res <- f
if res == -1
then do
err <- getErrno
if err == eINTR then return 0 else throwErrno loc
else return res
|
sdiehl/ghc
|
libraries/base/GHC/Event/Internal.hs
|
Haskell
|
bsd-3-clause
| 6,918
|
module Docs.AST where
import qualified Data.Map as Map
import qualified Elm.Compiler.Type as Type
import qualified Reporting.Annotation as A
-- FULL DOCUMENTATION
data Docs t = Docs
{ comment :: String
, aliases :: Map.Map String (A.Located Alias)
, types :: Map.Map String (A.Located Union)
, values :: Map.Map String (A.Located (Value t))
}
type Centralized = Docs (Maybe Type.Type)
type Checked = Docs Type.Type
-- VALUE DOCUMENTATION
data Alias = Alias
{ aliasComment :: Maybe String
, aliasArgs :: [String]
, aliasType :: Type.Type
}
data Union = Union
{ unionComment :: Maybe String
, unionArgs :: [String]
, unionCases :: [(String, [Type.Type])]
}
data Value t = Value
{ valueComment :: Maybe String
, valueType :: t
, valueAssocPrec :: Maybe (String,Int)
}
|
pairyo/elm-compiler
|
src/Docs/AST.hs
|
Haskell
|
bsd-3-clause
| 848
|
module Fail2 where
f = let g xs = map (+1) xs in g list
where
list = [1,1,2,3,4]
|
kmate/HaRe
|
old/testing/letToWhere/Fail2_TokOut.hs
|
Haskell
|
bsd-3-clause
| 101
|
{-# htermination addListToFM_C :: (b -> b -> b) -> FiniteMap Char b -> [(Char,b)] -> FiniteMap Char b #-}
import FiniteMap
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/FiniteMap_addListToFM_C_3.hs
|
Haskell
|
mit
| 123
|
module Text.ParserCombinators.TagWiki where
import Control.Applicative hiding ( many, (<|>) )
import Data.List
import Text.ParserCombinators.Parsec
class Parseable a where
parser :: GenParser Char st a
-- Parses and reads one or more digits
number :: GenParser Char st Int
number = read <$> many1 digit
real :: (RealFrac r, Read r) => GenParser Char st r
real = read <$> str where
str = (++) <$> int <*> option "" decimal
decimal = char '.' *> int
int = many1 digit
-- \s → \\\\
quadrupleHack :: GenParser Char st String
quadrupleHack = hack *> char 's' *> return "\\\\\\\\"
-- Excludes newlines
whitespace :: GenParser Char st String
whitespace = many $ oneOf " \t"
-- Includes newlines
anyWhite :: GenParser Char st String
anyWhite = many $ oneOf " \t\n"
-- newline or EOF
eol :: GenParser Char st String
eol = try (return <$> newline) <|> (eof *> return "")
-- \\ -> \
hackhack :: GenParser Char st Char
hackhack = hack *> hack *> return '\\'
-- '\ ' -> space, \t -> tab, '\n' -> newline
escWhite :: GenParser Char st Char
escWhite = try (hack *> space)
<|> try (hack *> tab)
<|> try (hack *> newline)
<?> "escaped whitespace"
-- Ignored hack
hack :: GenParser Char st ()
hack = char '\\' *> return ()
-- Parses a character not present in `chars`, unless escaped with a backslash.
-- If escaped, 'unescapes' the character in the parsed string.
-- Ex.
-- parseTest (escaping "abc") "\a \b \c" → "a b c"
-- parseTest (escaping "abc") "a \b \c" → error (unescaped a)
escaping :: String -> GenParser Char st Char
escaping chars = try hackhack
<|> try (hack *> oneOf chars)
<|> noneOf (nub chars)
<?> "[^" ++ oneLine chars ++ "] or an escape sequence"
where oneLine = intercalate "\\n" . lines
-- Parse a whole string of escaping characters
except :: String -> GenParser Char st String
except = many1 . escaping
-- A whitespace-wrapped parser
floating :: GenParser Char st a -> GenParser Char st a
floating p = anyWhite *> p <* anyWhite
-- An multiline operator
operator :: String -> GenParser Char st ()
operator c = anyWhite *> string c *> anyWhite *> return ()
-- A symbol with optional whitespace preciding it
designator :: String -> GenParser Char st ()
designator c = whitespace *> string c *> return ()
-- A symbol with optional whitespace before and after (no newlines)
marker :: String -> GenParser Char st ()
marker c = whitespace *> string c *> whitespace *> return ()
|
Soares/tagwiki
|
src/Text/ParserCombinators/TagWiki.hs
|
Haskell
|
mit
| 2,500
|
module Y2018.M08.D15.Exercise where
{--
Today we have a list of the top 5000 English language words (by frequency) from
https://www.wordfrequency.info. We are going to parse this file and answer
a question.
--}
import Prelude hiding (Word)
import Data.Array
import Data.Map
-- below modules available via 1HaskellADay git repository
import Control.Scan.CSV
import qualified Data.MultiMap as MM
exDir, tsvFile :: FilePath
exDir = "Y2018/M08/D15/"
tsvFile = "words_counts.tsv"
-- The TSV file has a header and footer, so watch out. Parse the file into
-- the following structure:
type Word = String
type PartOfSpeech = Char
data WordFreq = WF { word :: Word, partOfSpeech :: PartOfSpeech,
freq :: Int, dispersion :: Float }
deriving Show
-- the parts of speech are catalogued here: ... um ... okay, bad link.
-- deal with it: guess away.
-- So, our word frequencies:
readWordFreqs :: FilePath -> IO (Array Int WordFreq)
readWordFreqs file = undefined
-- What is the part-of-speech that has the most words? second most? etc?
partsOfSpeech :: Array Int WordFreq -> Map PartOfSpeech [Word]
partsOfSpeech wordfreqs = undefined
-- you can use a multi-map to construct the above result if you'd like
-- What are the words of length 5 in this list? Or, more generally, what are
-- the words of length n?
type Length = Int
nwords :: Array Int WordFreq -> Map Length [Word]
nwords wordfreqs = undefined
-- Again, use a multi-map if you'd like
|
geophf/1HaskellADay
|
exercises/HAD/Y2018/M08/D15/Exercise.hs
|
Haskell
|
mit
| 1,475
|
{-# LANGUAGE Rank2Types #-}
module Battle (
ix,
ixM,
ixIM,
BattleState(..),
Board (Board),
Tactic,
TacticList,
addTactic,
runBoard,
player,
enemy,
turn,
tacticList,
battleState,
module Character
) where
import Control.Arrow
import Control.Monad.State
import Data.List
import qualified Data.Map as M
import qualified Data.IntMap as IM
import Lens.Family2
import Lens.Family2.State.Lazy
import Lens.Family2.Unchecked
import Character
ix :: Int -> Lens' [a] a
ix n = lens (!! n) (\l x -> take (n-1) l ++ [x] ++ drop (n+1) l)
ixM :: (Ord a) => a -> Lens' (M.Map a b) b
ixM n = lens (M.! n) (\l x -> M.insert n x l)
ixIM :: Int -> Lens' (IM.IntMap b) b
ixIM n = lens (IM.! n) (\l x -> IM.insert n x l)
getCommand :: CommandList -> (Command, CommandList)
getCommand cl = ((cl ^. commandMap) IM.! (cl ^. index), cl & index .~ nextIndex) where
nextIndex = if (cl^.index) == (cl^.listSize) - 1 then 0 else cl^.index + 1
type Tactic = M.Map String CommandList
type TacticList = IM.IntMap Tactic
addTactic :: Tactic -> TacticList -> TacticList
addTactic x tt = IM.insert (mi + 1) x tt where
mi = maximum $ IM.keys tt
data BattleState = Waiting | Win | Lose | Battling deriving (Eq, Show)
data Board = Board {
_player :: [Character],
_enemy :: [Character],
_turn :: Int,
_tacticList :: TacticList,
_battleState :: BattleState
} deriving (Show)
player :: Lens' Board [Character]
player = lens _player (\f x -> f { _player = x })
enemy :: Lens' Board [Character]
enemy = lens _enemy (\f x -> f { _enemy = x })
turn :: Lens' Board Int
turn = lens _turn (\f x -> f { _turn = x })
tacticList :: Lens' Board TacticList
tacticList = lens _tacticList (\f x -> f { _tacticList = x })
battleState :: Lens' Board BattleState
battleState = lens _battleState (\f x -> f { _battleState = x })
attackCalc :: Character -> Int
attackCalc ch = (ch ^. strength) * 5
defenceCalc :: Character -> Int
defenceCalc ch = (ch ^. vitality) * 2
damageCalc :: Character -> Character -> Int
damageCalc s t = attackCalc s - defenceCalc t
toAction :: Target -> Command -> Action
toAction t Attack = AttackTo t
toAction t com = Iso com
runCommand :: Int -> StateT Board IO [Command]
runCommand tti = do
tt <- use (tacticList . ixIM tti)
forM (M.assocs tt) $ \(chara, cl) -> do
let (com, cl') = getCommand cl
tacticList . ixIM tti . ixM chara .= cl'
return com
runBoard :: StateT Board IO ()
runBoard = do
turn += 1
comp <- runCommand 0
pair1 <- liftM2 zip (return $ fmap (toAction ToEnemy) comp) (use player)
es <- use enemy
let (come, enemy') = unzip $ fmap (\e -> second (\cl -> e & commandList .~ cl) $ getCommand $ e^.commandList) es
enemy .= enemy'
pair2 <- liftM2 zip (return $ fmap (toAction ToPlayer) come) (use enemy)
let ps = sortBy (\(_,a) (_,b) -> compare (a^.agility) (b^.agility)) $ concat [pair1,pair2]
forM_ ps $ \(com,chara) -> case com of
AttackTo ToPlayer -> do
pchara <- use $ player . ix 0
player . ix 0 . hp -= damageCalc chara pchara
AttackTo ToEnemy -> do
penemy <- use $ enemy . ix 0
enemy . ix 0 . hp -= damageCalc chara penemy
Iso _ -> return ()
lift . print =<< use player
lift . print =<< use enemy
es <- use enemy
when (all (\e -> e ^. hp <= 0) es) $ do
battleState .= Win
ps <- use player
when (all (\p -> p ^. hp <= 0) ps) $ do
battleState .= Lose
main = do
let b = Board [princess, madman] [enemy1] 0 (IM.fromList []) Waiting
execStateT (runBoard >> runBoard >> runBoard >> runBoard >> runBoard) b
{-
- STR: 攻撃ダメージ比率と攻撃ヒット率が上がる
- INT: 最大MPが上がる 回復スキルの回復量が上がる
- TEC: スキルダメージ比率が上がる 攻撃スキルの追加効果発生率が少し上がる
- VIT: 最大HPが上がる 防御力が上がる
- AGI: 速度補正率が上がる 回避率が少し上がる
- LUC: 確率スキルと装備品の成功率が上がる
-}
|
myuon/OoP
|
src/Battle.hs
|
Haskell
|
mit
| 3,968
|
{-# LANGUAGE OverloadedStrings #-}
module BigTable.TypeOfHtml where
import Criterion.Main (Benchmark, bench, nf)
import Data.Text.Lazy (Text)
import Html
import Weigh (Weigh, func)
-- | Render the argument matrix as an HTML table.
--
bigTable :: [[Int]] -- ^ Matrix.
-> Text -- ^ Result.
bigTable rows = renderText $
h1_ ("i am a real big old table\n" :: Text)
# p_ ("i am good at lots of static data\n" :: Text)
# p_ ("i am glab at lots of static data\n" :: Text)
# p_ ("i am glob at lots of static data\n" :: Text)
# p_ ("i am glib at lots of static data\n" :: Text)
# p_ ("i am glub at lots of static data\n" :: Text)
# p_ ("i am glom at lots of static data\n" :: Text)
# p_ ("i am glof at lots of static data\n" :: Text)
# p_ ("i am gref at lots of static data\n" :: Text)
# p_ ("i am greg at lots of static data\n" :: Text)
# table_ (
thead_ (tr_ (map (th_ . show) [1..10 :: Int]))
# tbody_ (map row rows))
# p_ ("i am good at lots of static data\n" :: Text)
# p_ ("i am glab at lots of static data\n" :: Text)
# p_ ("i am glob at lots of static data\n" :: Text)
# p_ ("i am glib at lots of static data\n" :: Text)
# p_ ("i am glub at lots of static data\n" :: Text)
# p_ ("i am glom at lots of static data\n" :: Text)
# p_ ("i am glof at lots of static data\n" :: Text)
# p_ ("i am gref at lots of static data\n" :: Text)
# p_ ("i am greg at lots of static data\n" :: Text)
where
row r = tr_ (map
(\t -> td_ $
p_ ("hi!\n" :: Text)
# show t
# p_ ("hello!\n" :: Text))
r)
benchmark :: [[Int]] -> Benchmark
benchmark rows = bench "type-of-html" (bigTable `nf` rows)
weight :: [[Int]] -> Weigh ()
weight i = func (show (length i) ++ "/type-of-html") bigTable i
|
TransportEngineering/nice-html
|
benchmarks/BigTable/TypeOfHtml.hs
|
Haskell
|
mit
| 1,874
|
-- a program for testing the alignment algorithm
{-# LANGUAGE OverloadedStrings #-}
import System.Environment
import Data.Text as ST
import Data.Text.IO as STIO
import Data.Text.Lazy as LT
import FastA
import Alignment
import NucModel
import PWMModel
import Align
smallprob = 0.0001
scale = 1000
main = do
[mod, seq] <- getArgs
let modf = FastA "mod" $ LT.pack mod
let moda = fastARecordsToAln [modf]
let modn = alnToNucModel smallprob scale "model" moda
let modc = NucPWMModel modn
let alnres = msalign defScScheme modc $ ST.pack seq
STIO.putStrLn alnres
|
tjunier/mlgsc
|
src/alntoy.hs
|
Haskell
|
mit
| 583
|
{-# LANGUAGE NoImplicitPrelude #-}
module Nix (
module Nix.Expr,
module Nix.Parser,
module Nix.LicenseType
) where
import Nix.Common
import Nix.Expr
import Nix.Parser
import Nix.LicenseType
|
adnelson/simple-nix
|
src/Nix.hs
|
Haskell
|
mit
| 205
|
{-# LANGUAGE Arrows, TupleSections #-}
module Server.Simulation(
mainWire
) where
import Control.DeepSeq
import Core
import Data.Text (Text)
import FRP.Netwire
import Prelude hiding (id, (.))
import Server.Game.Player
import Server.Game.World
mainWire :: GameMonad (GameWire () ())
mainWire = do
logInfo "Starting default world..."
return $ proc _ -> do
-- Running predefined world
(w, wid) <- runIndexed (world "default") -< ()
-- When player connects, add to default world
cplayers <- liftEvent spawnPlayers . playersConnected -< ()
putMessagesE . mapE (fmap $ second SpawnPlayer) -< fmap (wid,) <$> cplayers
-- When player disconnect, remove from world
dplayers <- playersDisconnected -< ()
putMessagesE . mapE (fmap $ second DespawnPlayer) -< fmap (wid,) <$> dplayers
forceNF -< w `deepseq` ()
where
spawnPlayers :: GameWire [Text] [Player]
spawnPlayers = liftGameMonad1 $ mapM $ \name -> do
i <- registerObject
return $! Player i name
|
NCrashed/sinister
|
src/server/Server/Simulation.hs
|
Haskell
|
mit
| 1,030
|
module BankAccount
( BankAccount
, closeAccount
, getBalance
, incrementBalance
, openAccount
) where
import Control.Concurrent.STM (TVar, atomically, modifyTVar, newTVarIO, readTVarIO, writeTVar)
data BankAccount = BankAccount { balance :: TVar (Maybe Integer) }
openAccount :: IO BankAccount
openAccount = do
startingBalance <- newTVarIO (Just 0)
return BankAccount { balance = startingBalance }
getBalance :: BankAccount -> IO (Maybe Integer)
getBalance = readTVarIO . balance
incrementBalance :: BankAccount -> Integer -> IO (Maybe Integer)
incrementBalance account amount = do
atomically $ modifyTVar (balance account) (fmap (+ amount))
getBalance account
closeAccount :: BankAccount -> IO ()
closeAccount = atomically . flip writeTVar Nothing . balance
|
tfausak/exercism-solutions
|
haskell/bank-account/BankAccount.hs
|
Haskell
|
mit
| 781
|
{-# OPTIONS -Wall #-}
import Helpers.Grid (Grid, (!))
import qualified Helpers.Grid as Grid
main :: IO ()
main = do
heightMap <- Grid.fromDigits <$> getContents
let lowestPoints = findLowestPoints heightMap
print $ sum $ map succ lowestPoints
findLowestPoints :: Grid Int -> [Int]
findLowestPoints heightMap =
[ heightMap ! points
| points <- Grid.allPointsList heightMap,
let value = heightMap ! points
in all (value <) (Grid.neighboringValues points heightMap)
]
|
SamirTalwar/advent-of-code
|
2021/AOC_09_1.hs
|
Haskell
|
mit
| 495
|
-- | Specification for the exercises of Chapter 2.
module Chapter02Spec where
import Chapter02 (myInit, myInit', myLast, myLast')
import Test.Hspec (Spec, describe, it)
import Test.QuickCheck (Property, property, (==>))
checkLastDef :: ([Int] -> Int) -> Property
checkLastDef lastImpl = property $ \xs -> not (null xs)
==> lastImpl xs == last xs
checkInitDef :: ([Int] -> [Int]) -> Property
checkInitDef initImpl =
property $ \xs -> not (null xs) ==> initImpl xs == init xs
spec :: Spec
spec = do
describe "myLast" $ do
it "correctly implements last" $ checkLastDef myLast
describe "myLast'" $ do
it "correctly implements last" $ checkLastDef myLast'
describe "myInit" $ do
it "correctly implements init" $ checkInitDef myInit
describe "myInit'" $ do
it "correctly implements init" $ checkInitDef myInit'
|
EindhovenHaskellMeetup/meetup
|
courses/programming-in-haskell/pih-exercises/test/Chapter02Spec.hs
|
Haskell
|
mit
| 886
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.