code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
tanh x = sinh x / cosh x
| scravy/nodash | doc/Math/tanh.hs | mit | 25 | 0 | 6 | 8 | 19 | 8 | 11 | 1 | 1 |
{-|
Core is the internal implementation of joebot2.
For the most part, only parts of Core are exposed to
the plugin writer, namely "Core.Types" and "Core.Cmds".
-}
module Joebot.Core (module C) where
import Joebot.Core.Cmds as C
import Joebot.Core.Types as C
| joeschmo/joebot2 | src/Joebot/Core.hs | mit | 268 | 0 | 4 | 49 | 29 | 21 | 8 | 3 | 0 |
module Golf where
skips :: [a] -> [[a]]
skips [] = []
skips [x] = [[x]]
skips xs = skips' 1 xs
where
skips' :: Int -> [a] -> [[a]]
skips' n xs
| n > length xs = []
| otherwise = everyNth n xs : skips' (n+1) xs
everyNth :: Int -> [a] -> [a]
everyNth 0 _ = []
everyNth 1 xs = xs
everyNth n xs = everyNth' 1 n xs
where
everyNth' :: Int -> Int -> [a] -> [a]
everyNth' _ _ [] = []
everyNth' cur n (x:xs)
| cur == n = x : everyNth' 1 n xs
| otherwise = everyNth' (cur+1) n xs
localMaxima :: [Integer] -> [Integer]
localMaxima [] = []
localMaxima [x] = []
localMaxima [x, y] = []
localMaxima (x:y:z:zs)
| y > x && y > z = y : localMaxima (y:z:zs)
| otherwise = localMaxima (y:z:zs)
| CreaturePhil/cis194 | Golf.hs | mit | 751 | 0 | 11 | 227 | 443 | 228 | 215 | 25 | 2 |
{- |
Module : $Header$
Description : hets server queries
Copyright : (c) Christian Maeder, DFKI GmbH 2010
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : non-portable (via imports)
query strings
-}
module PGIP.Query where
{-
As a path we expect an existing directory, a file or library name or a
number (Int) referecing a current LibEnv (or Session). The session also stores
the top-level library name.
In order to address other (i.e. imported) libraries of a session given by a
number this number should be part of a query containing "dg=<id>" with the
library name as path.
As queries we basically allow actions to be taken, like displaying:
- the whole LibEnv
- the development graph (for a library name)
- as xml or svg
- a specific node or edge from a development graph (given by id=<id>)
in various format (like local or global theory)
other actions are commands like performing global decomposition (or "auto")
on a graph or individual proofs on a node or edge.
But rather than requiring a full query like "?dg=5&command=display&format=xml"
it should be sufficient to write "/5?xml" or "/5?auto". The notation "dg=5" is
only necessary to address an imported library of the session. Also some
default display should be generated for a missing query like just "/5".
State changing commands like "auto" (or other proofs) will generate a new
numbers for the new graphs (i.e. "dg=6").
The default display for a LibEnv should be:
- the current top-level library name
- links to every imported library
- links to display the current top-level development graphs in various formats.
- links to perform the possible global commands
- (several) links for every node
- (several) links for every edge
-}
import Common.Utils
import Data.Char
import Data.List
import Data.Maybe
import qualified Data.Map as Map
import Driver.Options
import Numeric
ppList :: [String]
ppList = map (show . PrettyOut) prettyList ++ ["pdf"]
displayTypes :: [String]
displayTypes =
["svg", "xml", "dot", "symbols", "session"] ++ ppList
comorphs :: [String]
comorphs = ["provers", "translations"]
data NodeCmd = Node | Info | Theory | Symbols
deriving (Show, Eq, Bounded, Enum)
nodeCmds :: [NodeCmd]
nodeCmds = [minBound .. maxBound]
showNodeCmd :: NodeCmd -> String
showNodeCmd = map toLower . show
nodeCommands :: [String]
nodeCommands = map showNodeCmd nodeCmds ++ comorphs ++ ["prove"]
proveParams :: [String]
proveParams = ["timeout", "include", "prover", "translation", "theorems"]
edgeCommands :: [String]
edgeCommands = ["edge"]
-- Lib- and node name can be IRIs now (the query id is the session number)
data DGQuery = DGQuery
{ queryId :: Int
, optQueryLibPath :: Maybe String
}
| NewDGQuery
{ queryLib :: FilePath
, commands :: [String]
}
data Query = Query
{ dgQuery :: DGQuery
, queryKind :: QueryKind
}
type NodeIdOrName = Either Int String
type QueryPair = (String, Maybe String)
data QueryKind =
DisplayQuery (Maybe String)
| GlobCmdQuery String
| GlProvers ProverMode (Maybe String)
| GlTranslations
| GlShowProverWindow ProverMode
| GlAutoProve ProveCmd
| NodeQuery NodeIdOrName NodeCommand
| EdgeQuery Int String
data ProverMode = GlProofs | GlConsistency
data ProveCmd = ProveCmd
{ pcProverMode :: ProverMode
, pcInclTheorems :: Bool
, pcProver :: Maybe String
, pcTranslation :: Maybe String
, pcTimeout :: Maybe Int
, pcTheoremsOrNodes :: [String]
, pcXmlResult :: Bool }
data NodeCommand =
NcCmd NodeCmd
| NcProvers ProverMode (Maybe String) -- optional comorphism
| NcTranslations (Maybe String) -- optional prover name
| ProveNode ProveCmd
-- | the path is not empty and leading slashes are removed
anaUri :: [String] -> [QueryPair] -> [String] -> Either String Query
anaUri pathBits query globals = case anaQuery query globals of
Left err -> Left err
Right (mi, qk) -> let path = intercalate "/" pathBits in
case (mi, readMaybe path) of
(Just i, Just j) | i /= j -> Left "different dg ids"
(_, mj) -> Right $ Query
(case catMaybes [mi, mj] of
[] -> NewDGQuery path []
i : _ -> DGQuery i $ if isJust mj then Nothing else Just path)
qk
isNat :: String -> Bool
isNat s = all isDigit s && not (null s) && length s < 11
-- | a leading question mark is removed, possibly a session id is returned
anaQuery :: [QueryPair] -> [String] -> Either String (Maybe Int, QueryKind)
anaQuery q' globals =
let (atP, q'') = partition ((== "autoproof") . fst) q'
(atC, q) = partition ((== "consistency") . fst) q''
(q1, qm) = partition (\ l -> case l of
(x, Nothing) -> isNat x || elem x
(displayTypes ++ globals
++ ["include", "autoproof"]
++ nodeCommands ++ edgeCommands)
_ -> False) q
(q2, qr) = partition (\ l -> case l of
(x, Just y) ->
elem x (["dg", "id", "session"]
++ edgeCommands)
&& isNat y
|| x == "command" &&
elem y globals
|| x == "format" && elem y displayTypes
|| elem x ("name" : tail proveParams
++ nodeCommands)
-- note: allows illegal timeout values
|| x == "timeout"
-- without timeout, see above
_ -> False) qm
(fs, r1) = partition (`elem` displayTypes) $ map fst q1
(gs, r2) = partition (`elem` globals) r1
(ns, r3) = partition (`elem` nodeCommands) r2
(es, r4) = partition (`elem` edgeCommands) r3
(incls, is) = partition (== "include") r4
(fs2, p1) = partition ((== "format") . fst) q2
(cs2, p2) = partition ((== "command") . fst) p1
(is2, p3) = partition ((`elem` ["dg", "session"]) . fst) p2
(ns2, p4) = partition ((`elem` nodeCommands) . fst) p3
(es2, p5) = partition ((`elem` edgeCommands) . fst) p4
(nns, p6) = partition ((== "name") . fst) p5
(ids, pps) = partition ((== "id") . fst) p6
snds = mapMaybe snd
afs = nubOrd $ fs ++ snds fs2
ags = nubOrd $ gs ++ snds cs2
ans = nubOrd $ ns ++ map fst ns2
aes = nubOrd $ es ++ map fst es2
ais = nubOrd $ is ++ snds is2
aids = nubOrd . snds $ ns2 ++ es2 ++ ids ++ nns
mi = fmap read $ listToMaybe ais
(theorems, qqr) = partition ((== Just "on") . snd) qr
noPP = null pps && null incls && null theorems
-- TODO i kind of abused this functions structure for autoproofs here
in if not $ null atP then Right (mi, GlShowProverWindow GlProofs) else
if not $ null atC then Right (mi, GlShowProverWindow GlConsistency)
else
if null qqr && length ais < 2 then case (afs, ags, ans, aes, aids) of
(_, [], [], [], []) | noPP -> if length afs > 1
then Left $ "non-unique format " ++ show afs
else Right (mi, DisplayQuery $ listToMaybe afs)
(_, c : r, [], [], []) | noPP -> if null r
then Right (mi, GlobCmdQuery c)
else Left $ "non-unique command " ++ show r
(_, [], _, [], [_]) -> fmap (\ qk -> (mi, qk)) $
anaNodeQuery ans (getIdOrName ids nns ns2) (map fst theorems)
incls pps
(_, [], [], e : r, i : s) | noPP ->
if null r && null s && null nns && null ns2
then Right (mi, EdgeQuery (read i) e)
else Left $ "non-unique edge " ++ show (aes ++ aids)
_ -> Left $ "non-unique query " ++ show q
else Left $ if null qqr then "non-unique dg " ++ show q else
"ill-formed query " ++ show qqr
getIdOrName :: [QueryPair] -> [QueryPair] -> [QueryPair] -> NodeIdOrName
getIdOrName ids nns ns2 = case ids of
(_, Just v) : _ -> Left $ read v
_ -> case nns of
(_, Just v) : _ -> Right v
_ -> case ns2 of
(_, Just v) : _ -> if isNat v then Left $ read v else Right v
_ -> error "getIdOrName"
escMap :: [(Char, Char)]
escMap = map (\ l -> let [f, s] = l in (f, s))
[ "+P"
, "&A"
, "=E"
, ";S"
, " B"
, "XX" ]
escStr :: String -> String
escStr = concatMap (\ c -> case Map.lookup c $ Map.fromList escMap of
Nothing -> [c]
Just e -> ['X', e])
unEsc :: String -> String
unEsc s = let m = Map.fromList $ map (\ (a, b) -> (b, a)) escMap
in case s of
"" -> ""
'X' : c : r -> Map.findWithDefault c c m : unEsc r
c : r -> c : unEsc r
encodeForQuery :: String -> String
encodeForQuery = concatMap (\ c -> let n = ord c in case c of
_ | isAscii c && isAlphaNum c || elem c "_.-" -> [c]
' ' -> "+"
_ | n <= 255 -> '%' : (if n < 16 then "0" else "") ++ showHex n ""
_ -> "") -- ignore real unicode stuff
decodePlus :: Char -> Char
decodePlus c = if c == '+' then ' ' else c
decodeQuery :: String -> String
decodeQuery s = case s of
"" -> ""
'%' : h1 : h2 : r -> case readHex [h1, h2] of
(i, "") : _ -> [decodePlus $ chr i]
_ -> ['%', h1, h2]
++ decodeQuery r
c : r -> decodePlus c : decodeQuery r
getFragOfCode :: String -> String
getFragOfCode = getFragment . decodeQuery
getFragment :: String -> String
getFragment s = case dropWhile (/= '#') s of
_ : t -> t
"" -> s
anaNodeQuery :: [String] -> NodeIdOrName -> [String] -> [String]
-> [QueryPair] -> Either String QueryKind
anaNodeQuery ans i moreTheorems incls pss =
let pps = foldr (\ l -> case l of
(x, Just y) -> ((x, y) :)
_ -> id) [] pss
incl = lookup "include" pps
trans = fmap decodeQuery $ lookup "translation" pps
prover = lookup "prover" pps
theorems = map unEsc moreTheorems
++ case lookup "theorems" pps of
Nothing -> []
Just str -> map unEsc $ splitOn ' ' $ decodeQuery str
timeLimit = maybe Nothing readMaybe $ lookup "timeout" pps
pp = ProveNode $ ProveCmd GlProofs (not (null incls) || case incl of
Nothing -> True
Just str -> map toLower str `notElem` ["f", "false"])
prover trans timeLimit theorems False
noPP = null incls && null pps
noIncl = null incls && isNothing incl && isNothing timeLimit
cmds = map (\ a -> (showNodeCmd a, a)) nodeCmds
in case ans of
[] -> Right $ NodeQuery i
$ if noPP then NcCmd minBound else pp
[cmd] -> case cmd of
"prove" -> Right $ NodeQuery i pp
"provers" | noIncl && isNothing prover ->
Right $ NodeQuery i $ NcProvers GlProofs trans
"translations" | noIncl && isNothing trans ->
Right $ NodeQuery i $ NcTranslations prover
_ -> case lookup cmd cmds of
Just nc | noPP -> Right $ NodeQuery i $ NcCmd nc
_ -> Left $ "unknown node command '" ++ cmd ++ "' "
++ shows incls " " ++ show pss
_ -> Left $ "non-unique node command " ++ show ans
| nevrenato/HetsAlloy | PGIP/Query.hs | gpl-2.0 | 11,342 | 0 | 28 | 3,447 | 3,502 | 1,861 | 1,641 | 220 | 14 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
module Main where
import qualified Clay as C
import Control.Monad
import Data.Aeson (FromJSON, fromJSON)
import qualified Data.Aeson as Aeson
import Data.List (sortOn)
import Data.Map (Map)
import Data.Maybe (fromJust)
import qualified Data.Map.Strict as Map
import qualified Data.Text as T
import qualified Data.Text.Lazy as LT
import Data.Text (Text)
import Development.Shake
import GHC.Generics (Generic)
import Lucid
import Lucid.Base
import Main.Utf8
import Rib (IsRoute)
import qualified Rib
--import qualified Rib.Parser.Pandoc as Pandoc
import PyF
-- My modules
import qualified CV
import CSS
import RSS
import Pandoc
import SiteData
-- | Route corresponding to each generated static page.
--
-- The `a` parameter specifies the data (typically Markdown document) used to
-- generate the final page text.
data Route a where
Route_Index :: Route [(Route Pandoc, Pandoc)]
Route_CV :: Route [(Route Pandoc, Pandoc)]
Route_Tags :: Route (Map Text [(Route Pandoc, Pandoc)])
Route_Article :: FilePath -> Route Pandoc
Route_Feed :: Route [(Route Pandoc, Pandoc)]
-- | The `IsRoute` instance allows us to determine the target .html path for
-- each route. This affects what `routeUrl` will return.
instance IsRoute Route where
routeFile = \case
Route_Index -> pure "index.html"
Route_Tags -> pure "tags/index.html"
Route_CV -> pure "cv.html"
Route_Article srcPath -> do
let (year, month, _day, slug) = parseJekyllFilename srcPath
pure $ year ++ "/" ++ month ++ "/" ++ slug ++ "/index.html"
Route_Feed -> pure "feed.xml"
parseJekyllFilename :: FilePath -> (String, String, String, String)
parseJekyllFilename fn =
case T.splitOn "-" (T.pack fn) of
y : m : d : rest ->
(T.unpack y, T.unpack m, T.unpack d, T.unpack $ T.intercalate "-" rest)
_ ->
error "Malformed filename"
-- | Main entry point to our generator.
--
-- `Rib.run` handles CLI arguments, and takes three parameters here.
--
-- 1. Directory `content`, from which static files will be read.
-- 2. Directory `dest`, under which target files will be generated.
-- 3. Shake action to run.
--
-- In the shake action you would expect to use the utility functions
-- provided by Rib to do the actual generation of your static site.
main :: IO ()
main = withUtf8 $ Rib.run "content" "dest" generateSite
-- | Shake action for generating the static site
generateSite :: Action ()
generateSite = do
-- Copy over the static files
Rib.buildStaticFiles [ "assets/**"
, "images/**"
, "projects/**"
, "presentations/**"
]
let writeHtmlRoute :: Route a -> a -> Action ()
writeHtmlRoute r = Rib.writeRoute r . Lucid.renderText . renderPage r
writeXmlRoute r = Rib.writeRoute r . RSS.renderFeed . toPosts r
-- Build individual sources, generating .html for each.
articles <-
Rib.forEvery ["posts/*.md"] $ \srcPath -> do
let r = Route_Article $ cleanPath srcPath
doc <- Pandoc.parse Pandoc.readMarkdown srcPath
writeHtmlRoute r doc
pure (r, doc)
writeHtmlRoute Route_CV articles
writeHtmlRoute Route_Tags $ groupByTag articles
writeHtmlRoute Route_Index $ reverse articles
writeXmlRoute Route_Feed $ articles
where
cleanPath path = drop 6 (take (length path - 3) path)
groupByTag as =
Map.fromListWith (<>) $ flip concatMap as $ \(r, doc) ->
(,[(r, doc)]) <$> tags (getMeta doc)
-- | Convert the posts we've read into Post types that can be read
-- by the RSS/Atom module.
toPosts :: Route a -> [(Route Pandoc, Pandoc)] -> [Post]
toPosts r docs = [toPost r doc | doc <- docs] where
toPost :: Route a -> (Route Pandoc, Pandoc) -> Post
toPost r (r', doc) = RSS.Post postDate postUrl postContent postTitle where
postDate = date (getMeta doc)
postUrl = SiteData.domain <> Rib.routeUrl r'
postContent = pandocToText doc
postTitle = title (getMeta doc)
pandocToText :: Pandoc -> T.Text
pandocToText doc = LT.toStrict $ Lucid.renderText $ Pandoc.render doc
stylesheet url = link_ [rel_ "stylesheet", href_ url]
script url = script_ [src_ url, async_ T.empty] T.empty
-- | Define your site HTML here
renderPage :: Route a -> a -> Html ()
renderPage route val = html_ [lang_ "en"] $ do
head_ $ do
meta_ [httpEquiv_ "Content-Type", content_ "text/html; charset=utf-8"]
title_ routeTitle
mapM_ stylesheet [ "/assets/css/spectre.min.css"
, "//fonts.googleapis.com/css?family=Montserrat|Raleway"
, "//cdn.jsdelivr.net/gh/highlightjs/[email protected]/build/styles/default.min.css"
]
link_ [ rel_ "icon", href_ "/images/favicon.svg", sizes_ "any", type_ "image/svg+xml" ]
-- <link rel="icon" href="images/favicon.svg" sizes="any" type="image/svg+xml">
style_ [type_ "text/css"] $ C.render CSS.pageStyle
style_ [type_ "text/css"] ("@page{margin: 3cm;}" :: Html ())
body_ $ do
div_ [id_ "headerWrapper"] $ do
header_ [class_ "navbar"] $ do
section_ [class_ "navbar-section"] $ do
a_ [class_ "navbar-brand", href_ $ Rib.routeUrl Route_Index] $ do
"Jonathan Reeve: "
span_ [] "Computational Literary Analysis"
section_ [class_ "navbar-section"] $ do
ul_ [class_ "nav"] $ do
navItem Route_Index "posts"
navItem Route_CV "cv"
navItem Route_Tags "tags"
navItem Route_Feed "feed"
div_ [class_ "container"] $ do
content
footer_ [ ] $ do
div_ [ class_ "container" ] $ do
div_ [ class_ "columns" ] $ do
div_ [ class_ "column col-8" ] $ CV.md2Html coda
div_ [ class_ "column col-4" ] $ do
div_ [ class_ "icons" ] $ do
a_ [href_ "http://github.com/JonathanReeve"] gitHubIcon
a_ [href_ "http://twitter.com/j0_0n"] twitterIcon
a_ [href_ "mailto:[email protected]"] emailIcon
script_ [ makeAttribute "data-goatcounter" "https://jonreeve.goatcounter.com/count"
, async_ T.empty, src_ "//gc.zgo.at/count.js" ] T.empty
script_ [ src_ "/assets/js/jquery-3.5.1.min.js" ] T.empty
script_ [ src_ "/assets/js/main.js" ] T.empty
script_ [src_ "//cdn.jsdelivr.net/gh/highlightjs/[email protected]/build/highlight.min.js"] T.empty
script_ [] ("hljs.initHighlightingOnLoad();" :: Html ())
where
navItem :: Route a -> Html () -> Html ()
navItem navRoute label = li_ [class_ "nav-item"] $ a_ [href_ $ Rib.routeUrl navRoute ] label
routeTitle :: Html ()
routeTitle = case route of
Route_Index -> "Posts"
Route_Tags -> "Tags"
Route_CV -> "CV"
Route_Article _ -> toHtml $ title $ getMeta val
Route_Feed -> "Feed"
content :: Html ()
content = case route of
Route_Index -> do
section_ [id_ "greeting"] $ do
CV.md2Html SiteData.greeting
div_ [class_ "icons"] $ do
img_ [src_ "assets/images/noun_Book_1593490.svg"]
span_ [] "+"
img_ [src_ "assets/images/noun_retro computer_1905469.svg"]
span_ [] "="
img_ [src_ "assets/images/noun_education_1909997.svg"]
main_ [class_ "container" ] $ forM_ val $ \(r, src) -> do
section_ [id_ "postList"] $ do
li_ [class_ "post" ] $ do
let meta = getMeta src
div_ [vocab_ "https://schema.org", typeof_ "blogPosting"] $ do
h2_ [class_ "postTitle", property_ "headline"] $ a_ [href_ (Rib.routeUrl r)] $ toHtml $ title meta
p_ [class_ "meta"] $ do
span_ [class_ "date", property_ "datePublished", content_ (date meta)] $ toHtml $ T.concat ["(", date meta, ")"]
span_ [class_ "tags", property_ "keywords", content_ (T.intercalate "," (tags meta))] $ do
" in"
mapM_ (a_ [class_ "chip", rel_ "tag", href_ ""] . toHtml) (tags meta)
Route_Tags -> do
h1_ routeTitle
div_ $ forM_ (sortOn (T.toLower . fst) $ Map.toList val) $ \(tag, rs) -> do
a_ [id_ tag] mempty
h2_ $ toHtml tag
ul_ $ forM_ rs $ \(r, src) -> do
li_ [class_ "pages"] $ do
let meta = getMeta src
b_ $ a_ [href_ (Rib.routeUrl r)] $ toHtml $ title meta
Route_CV -> do
main_ [class_ "container" ] $ do
h1_ "Curriculum Vitae"
h2_ "Jonathan Reeve"
CV.cv
Route_Article srcPath -> do
h1_ routeTitle
let (y, m, d, _) = parseJekyllFilename srcPath
p_ [fmt|Posted {y}-{m}-{d}|]
article_ $
Pandoc.render val
script_ [src_ "https://hypothes.is/embed.js" ] T.empty
Route_Feed -> h1_ "RSS feed in development. Coming soon."
-- | Metadata in our markdown sources
data SrcMeta
= SrcMeta
{ title :: Text,
date :: Text,
tags :: [Text]
}
deriving (Show, Eq, Generic, FromJSON)
-- | Get metadata from Markdown's YAML block
getMeta :: Pandoc -> SrcMeta
getMeta src = case Pandoc.extractMeta src of
Nothing -> error "No YAML metadata"
Just (Left e) -> error $ T.unpack e
Just (Right val) -> case fromJSON val of
Aeson.Error e -> error $ "JSON error: " <> e
Aeson.Success v -> v
-- Schema.org RDFa
vocab_, typeof_, property_ :: Text -> Attribute
vocab_ = makeAttribute "vocab"
typeof_ = makeAttribute "typeof"
property_ = makeAttribute "property"
path_ :: Applicative m => [Attribute] -> HtmlT m ()
path_ = with (makeElementNoEnd "path")
viewBox_ :: Text -> Attribute
viewBox_ = makeAttribute "viewBox"
d_ :: Text -> Attribute
d_ = makeAttribute "d"
fill_ :: Text -> Attribute
fill_ = makeAttribute "fill"
svgObj_ :: Functor m => [Attribute] -> HtmlT m a -> HtmlT m a
svgObj_ = with (makeElement "svg")
svgIcon_ :: Text -> Html ()
svgIcon_ svgPath = svgObj_ [ xmlns_ "http://www.w3.org/2000/svg"
, viewBox_ "0 0 448 512"
, fill_ "#fafafa", width_ "3em" , height_ "3em"
] $ path_ [ d_ svgPath ]
twitterIcon :: Html ()
twitterIcon = svgIcon_ [fmt|M400 32H48C21.5 32 0 53.5 0 80v352c0 26.5 21.5 48
48 48h352c26.5 0 48-21.5 48-48V80c0-26.5-21.5-48-48-48zm-48.9 158.8c.2 2.8.2
5.7.2 8.5 0 86.7-66 186.6-186.6 186.6-37.2 0-71.7-10.8-100.7-29.4 5.3.6 10.4.8
15.8.8 30.7 0 58.9-10.4 81.4-28-28.8-.6-53-19.5-61.3-45.5 10.1 1.5 19.2 1.5
29.6-1.2-30-6.1-52.5-32.5-52.5-64.4v-.8c8.7 4.9 18.9 7.9 29.6 8.3a65.447 65.447
0 0 1-29.2-54.6c0-12.2 3.2-23.4 8.9-33.1 32.3 39.8 80.8 65.8 135.2 68.6-9.3-44.5
24-80.6 64-80.6 18.9 0 35.9 7.9 47.9 20.7 14.8-2.8 29-8.3 41.6-15.8-4.9
15.2-15.2 28-28.8 36.1 13.2-1.4 26-5.1 37.8-10.2-8.9 13.1-20.1 24.7-32.9 34z|]
gitHubIcon :: Html ()
gitHubIcon = svgIcon_ [fmt|M400 32H48C21.5 32 0 53.5 0 80v352c0 26.5 21.5 48 48
48h352c26.5 0 48-21.5 48-48V80c0-26.5-21.5-48-48-48zM277.3 415.7c-8.4
1.5-11.5-3.7-11.5-8 0-5.4.2-33 .2-55.3 0-15.6-5.2-25.5-11.3-30.7 37-4.1 76-9.2
76-73.1 0-18.2-6.5-27.3-17.1-39 1.7-4.3 7.4-22-1.7-45-13.9-4.3-45.7 17.9-45.7
17.9-13.2-3.7-27.5-5.6-41.6-5.6-14.1 0-28.4 1.9-41.6 5.6 0
0-31.8-22.2-45.7-17.9-9.1 22.9-3.5 40.6-1.7 45-10.6 11.7-15.6 20.8-15.6 39 0
63.6 37.3 69 74.3 73.1-4.8 4.3-9.1 11.7-10.6 22.3-9.5 4.3-33.8
11.7-48.3-13.9-9.1-15.8-25.5-17.1-25.5-17.1-16.2-.2-1.1 10.2-1.1 10.2 10.8 5
18.4 24.2 18.4 24.2 9.7 29.7 56.1 19.7 56.1 19.7 0 13.9.2 36.5.2 40.6 0 4.3-3
9.5-11.5 8-66-22.1-112.2-84.9-112.2-158.3 0-91.8 70.2-161.5 162-161.5S388 165.6
388 257.4c.1 73.4-44.7 136.3-110.7
158.3zm-98.1-61.1c-1.9.4-3.7-.4-3.9-1.7-.2-1.5 1.1-2.8 3-3.2 1.9-.2 3.7.6 3.9
1.9.3 1.3-1 2.6-3 3zm-9.5-.9c0 1.3-1.5 2.4-3.5 2.4-2.2.2-3.7-.9-3.7-2.4 0-1.3
1.5-2.4 3.5-2.4 1.9-.2 3.7.9 3.7 2.4zm-13.7-1.1c-.4 1.3-2.4 1.9-4.1
1.3-1.9-.4-3.2-1.9-2.8-3.2.4-1.3 2.4-1.9 4.1-1.5 2 .6 3.3 2.1 2.8
3.4zm-12.3-5.4c-.9 1.1-2.8.9-4.3-.6-1.5-1.3-1.9-3.2-.9-4.1.9-1.1 2.8-.9 4.3.6
1.3 1.3 1.8 3.3.9 4.1zm-9.1-9.1c-.9.6-2.6 0-3.7-1.5s-1.1-3.2 0-3.9c1.1-.9 2.8-.2
3.7 1.3 1.1 1.5 1.1 3.3 0
4.1zm-6.5-9.7c-.9.9-2.4.4-3.5-.6-1.1-1.3-1.3-2.8-.4-3.5.9-.9 2.4-.4 3.5.6 1.1
1.3 1.3 2.8.4 3.5zm-6.7-7.4c-.4.9-1.7 1.1-2.8.4-1.3-.6-1.9-1.7-1.5-2.6.4-.6
1.5-.9 2.8-.4 1.3.7 1.9 1.8 1.5 2.6z|]
emailIcon :: Html ()
emailIcon = svgIcon_ [fmt|M400 32H48C21.49 32 0 53.49 0 80v352c0 26.51 21.49 48
48 48h352c26.51 0 48-21.49 48-48V80c0-26.51-21.49-48-48-48zM178.117
262.104C87.429 196.287 88.353 196.121 64 177.167V152c0-13.255 10.745-24
24-24h272c13.255 0 24 10.745 24 24v25.167c-24.371 18.969-23.434 19.124-114.117
84.938-10.5 7.655-31.392 26.12-45.883
25.894-14.503.218-35.367-18.227-45.883-25.895zM384 217.775V360c0 13.255-10.745
24-24 24H88c-13.255 0-24-10.745-24-24V217.775c13.958 10.794 33.329 25.236 95.303
70.214 14.162 10.341 37.975 32.145 64.694 32.01 26.887.134 51.037-22.041
64.72-32.025 61.958-44.965 81.325-59.406 95.283-70.199z|]
| JonathanReeve/JonathanReeve.github.io | src/Main.hs | gpl-2.0 | 13,230 | 0 | 37 | 2,969 | 3,065 | 1,521 | 1,544 | 226 | 9 |
{-# OPTIONS -fglasgow-exts -fallow-undecidable-instances -fallow-overlapping-instances #-}
----------------------------------------------------------------------------
-- |
-- Module : Text.XML.Serializer
-- Copyright : (c) Simon Foster 2005
-- License : GPL version 2 (see COPYING)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : non-portable (ghc >= 6 only)
--
-- A Generic XML Serializer using HXT and the Generics package (SYB3). This new version of
-- GXS is based on type classes, and thus allows modular customization. More coming soon.
--
-- This is a working serialize shell, with a number of default serialization rules imported.
-- As a result this module requires overlapping instances. If you don't want them, you need
-- to import Text.XML.Serializer.Core and write your own rules.
--
-- @This file is part of HAIFA.@
--
-- @HAIFA is free software; you can redistribute it and\/or modify it under the terms of the
-- GNU General Public License as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.@
--
-- @HAIFA is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
-- even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.@
--
-- @You should have received a copy of the GNU General Public License along with HAIFA; if not,
-- write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA@
----------------------------------------------------------------------------
module Text.XML.Serializer ( module Text.XML.Serializer.Core
, module Text.XML.Serializer.Datatypes
, module Text.XML.Serializer.DefaultRules
, module Text.XML.Serializer.Derive
, module Text.XML.Serializer.Encoders
) where
import Text.XML.Serializer.Core
import Text.XML.Serializer.Datatypes
import Text.XML.Serializer.DefaultRules
import Text.XML.Serializer.Derive
import Text.XML.Serializer.Encoders
| twopoint718/haifa | src/Text/XML/Serializer.hs | gpl-2.0 | 2,160 | 0 | 5 | 399 | 115 | 92 | 23 | 11 | 0 |
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances, OverloadedStrings, Arrows #-}
module Csvstuff
(
csvFile, dread, rownames, colnames, Col, line, isdouble, vlookup, toBool, columns, rows
) where
import Prelude hiding (id)
import Numeric (readFloat)
import CsvParser
import CsvDatabase
{-------------------------------------------
Some operations on a Db
--------------------------------------------}
-- takes a row and a column and returns the value
vlookup :: (Eq a, Read a) => Db a -> String -> String -> Maybe (Value a)
vlookup db id colname = select (CellName colname) r
where
s1 = CellName "Id" -- the selector for the house column
v = map Char id -- the value
r = head $ exec [(s1,v)] db -- gets just the row for the house
-- if Just 1.0, goes to TRUE otherwise FALSE
toBool :: (Eq a, Fractional a) => Maybe (Value a) -> Maybe Bool
toBool (Just (Right (Just 1.0))) = Just True
toBool _ = Nothing
-- Takes the keys as the column names
colnames :: Db a ->[String]
colnames = map fst . head
-- Takes the first column as the row names
rownames :: (Show a) => Db a ->[String]
rownames = map (show . snd . head) . tail
-- The data rows - ie tail! - no, all rows!!
rows :: Db a -> Db a
rows = tail
-- The data columns
columns :: Db a -> Db a
columns db = tail $ foldl add_on (map (\x->[x]) (head $ rows db)) (tail $ rows db)
where
add_on xss ys = zipWith (\xs y -> xs++[y]) xss ys
-- Some functions to play with columns
-- Reads a strings to Maybe Double
dread :: String -> Maybe Double
dread s = case readFloat s of
[(n,_)]-> Just n
_ -> Nothing
| b1g3ar5/CsvDatabase | src/Csvstuff.hs | gpl-3.0 | 1,720 | 0 | 11 | 458 | 512 | 277 | 235 | 29 | 2 |
module While.ParserSpec (spec) where
import Test.Hspec
import Test.QuickCheck
import Test.Hspec.QuickCheck
import System.Directory
import Data.List
import qualified Data.Map.Strict as Map
import While.AST
import While.ASTGenerator()
import While.Parser
import While.Compiler
spec :: Spec
spec =
modifyMaxSuccess (*10) $
modifyMaxDiscardRatio (*10) $
modifyMaxSize (`div` 3) $
parallel $ do
describe "parseString" $ do
it "parses an empty string" $
parseString "" `shouldBe` Skip
it "parses whitespaces-only string" $ do
parseString " " `shouldBe` Skip
parseString "\n" `shouldBe` Skip
parseString "\r" `shouldBe` Skip
parseString "\t" `shouldBe` Skip
parseString " " `shouldBe` Skip
it "parses skip" $
parseString "skip" `shouldBe` Skip
it "parses skip with spaces and parentesis" $ do
parseString " skip " `shouldBe` Skip
parseString "(skip)" `shouldBe` Skip
parseString "((skip))" `shouldBe` Skip
parseString "(((skip)))" `shouldBe` Skip
parseString " ( ( skip ) ) " `shouldBe` Skip
it "parses concatenated skips" $ do
parseString "skip;skip" `shouldBe` Seq Skip Skip
parseString "skip;skip;skip" `shouldBe` Seq Skip (Seq Skip Skip)
parseString "skip;skip;skip;skip" `shouldBe` Seq Skip (Seq Skip (Seq Skip Skip))
it "parses concatenated skips with spaces" $
parseString "skip ; skip" `shouldBe` Seq Skip Skip
it "parses program terminating with semicolon" $
parseString "skip;" `shouldBe` Skip
it "parses concatenated skips with simple parentesis" $ do
parseString "skip;(skip);skip" `shouldBe` Seq Skip (Seq Skip Skip)
parseString "skip;(skip;skip);skip" `shouldBe` Seq Skip (Seq (Seq Skip Skip) Skip)
it "parses concatenated skips with complex parentesis" $ do
parseString "skip;((skip));skip;skip" `shouldBe` Seq Skip (Seq Skip (Seq Skip Skip))
parseString "skip;((skip;skip));skip" `shouldBe` Seq Skip (Seq (Seq Skip Skip) Skip)
it "parses skip and while loop" $ do
parseString "skip;while true do skip;" `shouldBe` Seq Skip (While (BoolConst True) Skip)
parseString "skip; while true do skip;" `shouldBe` Seq Skip (While (BoolConst True) Skip)
it "parses while loop and skip" $
parseString "while true do skip; skip" `shouldBe` Seq (While (BoolConst True) Skip) Skip
it "parses assignment and while loop" $
parseString "x := 5; while true do skip;" `shouldBe`
Seq
(Assign "x" (IntConst 5))
(While (BoolConst True) Skip)
it "parses assignment and complex while loop" $
parseString "value := -5; while value < 5 do( value := 1 + value; );" `shouldBe`
Seq
(Assign "value" (AUnary Neg (IntConst 5)))
(While
(RBinary Less (Var "value") (IntConst 5))
(Assign "value" (ABinary Add (IntConst 1) (Var "value")))
)
it "parses simple condition" $ do
parseString "if false then skip else skip" `shouldBe`
If (BoolConst False) Skip Skip
parseString "if false then skip; else skip;" `shouldBe`
If (BoolConst False) Skip Skip
it "parses simple condition and skip" $ do
parseString "if false then skip else skip; skip" `shouldBe`
Seq (If (BoolConst False) Skip Skip) Skip
parseString "if false then skip; else skip; skip" `shouldBe`
Seq (If (BoolConst False) Skip Skip) Skip
it "parses condition with complex test" $
parseString "if (x-5) < (x/2) then skip else skip" `shouldBe`
If
(RBinary Less
(ABinary Subtract (Var "x") (IntConst 5))
(ABinary Divide (Var "x") (IntConst 2)))
Skip
Skip
context "when used to parse the rapresentation of an AST" $ do
it "produces the same AST" $
let tree = Seq (Seq Skip Skip) (Seq Skip Skip)
in (parseString . compileStmt) tree `shouldBe` tree
it "produces the same AST randomly generated" $ property $
\tree -> (parseString . compileStmt) tree == tree
describe "parseFile" $
context "files in data/*.wl" $ do
let expectated = Map.fromList [
("loop.wl", While (BoolConst True) Skip)
]
whileFiles <- runIO $ do
allFiles <- getDirectoryContents "data"
return $ filter (isSuffixOf ".wl") allFiles
let testParseFile filename =
it ("parses without errors file data/"++filename) $ do
stmt <- parseFile ("data/"++filename)
case Map.lookup filename expectated of
Just result -> stmt `shouldBe` result
Nothing -> return ()
mapM_ testParseFile whileFiles
| fpoli/abstat | test/While/ParserSpec.hs | gpl-3.0 | 5,341 | 0 | 21 | 1,865 | 1,344 | 653 | 691 | 103 | 2 |
import Numeric.Odeint
import Numeric.Odeint.Examples
import Data.Array.Repa as Repa
import Criterion.Main
takeNth :: Int -> Double
takeNth n = ((iterate teo v0) !! n) ! (Z :. 0)
where
teo = lorenz63 (10, 28, 8.0/3.0)
v0 = fromListUnboxed (Z :. 3) [1, 0, 0]
main :: IO ()
main = defaultMain [
bgroup "Lorenz63" [ bench "steps=10k" $ whnf takeNth 10000
, bench "steps=100k" $ whnf takeNth 100000
]
]
| termoshtt/odeint | app/Bench.hs | gpl-3.0 | 456 | 0 | 10 | 127 | 173 | 94 | 79 | 12 | 1 |
{-
Copyright 2011 Alexander Midgley
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-}
module Main where
import Control.DeepSeq
import Control.Parallel.Strategies
import Data.Time.Clock
import System.IO
import GrahamScan
instance NFData a => NFData (Point a) where
rnf (Point xx yy) = rnf xx `seq` rnf yy `seq` ()
makePoint [x, y] =
let sx = read x
sy = read y
in sx `seq` sy `seq` Point sx sy
evaluate points = do
start <- getCurrentTime
grahamScan points `deepseq` return ()
end <- getCurrentTime
hPutStrLn stderr . show $ diffUTCTime end start
main = do
coords <- fmap (map words . lines) getContents
let points :: [Point Float]
points = parMap rdeepseq makePoint coords
points `seq` evaluate points | shadwstalkr/GrahamScanDemo | test.hs | gpl-3.0 | 1,313 | 0 | 11 | 259 | 264 | 135 | 129 | 22 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving
, ScopedTypeVariables
#-}
module HW07.Editor where
import System.IO
import HW07.Buffer
import Control.Exception
import Control.Monad.State
import Control.Applicative
import Control.Arrow (first, second)
import Data.Char
import Data.List
-- Editor commands
data Command = View
| Edit
| Load String
| Line Int
| Next
| Prev
| Quit
| Help
| Noop
deriving (Eq, Show, Read)
commands :: [String]
commands = map show [View, Edit, Next, Prev, Quit]
-- Editor monad
newtype Editor b a = Editor (StateT (b,Int) IO a)
deriving (Functor, Monad, MonadIO, MonadState (b,Int))
runEditor :: Buffer b => Editor b a -> b -> IO a
runEditor (Editor e) b = evalStateT e (b,0)
getCurLine :: Editor b Int
getCurLine = gets snd
setCurLine :: Int -> Editor b ()
setCurLine = modify . second . const
onBuffer :: (b -> a) -> Editor b a
onBuffer f = gets (f . fst)
getBuffer :: Editor b b
getBuffer = onBuffer id
modBuffer :: (b -> b) -> Editor b ()
modBuffer = modify . first
io :: MonadIO m => IO a -> m a
io = liftIO
-- Utility functions
readMay :: Read a => String -> Maybe a
readMay s = case reads s of
[(r,_)] -> Just r
_ -> Nothing
-- Main editor loop
editor :: Buffer b => Editor b ()
editor = io (hSetBuffering stdout NoBuffering) >> loop
where loop = do prompt
cmd <- getCommand
when (cmd /= Quit) (doCommand cmd >> loop)
prompt :: Buffer b => Editor b ()
prompt = do
s <- onBuffer value
io $ putStr (show s ++ "> ")
getCommand :: Editor b Command
getCommand = io $ readCom <$> getLine
where
readCom "" = Noop
readCom inp@(c:cs) | isDigit c = maybe Noop Line (readMay inp)
| toUpper c == 'L' = Load (unwords $ words cs)
| c == '?' = Help
| otherwise = maybe Noop read $
find ((== toUpper c) . head) commands
doCommand :: Buffer b => Command -> Editor b ()
doCommand View = do
cur <- getCurLine
let ls = [(cur - 2) .. (cur + 2)]
ss <- mapM (\l -> onBuffer $ line l) ls
zipWithM_ (showL cur) ls ss
where
showL _ _ Nothing = return ()
showL l n (Just s) = io $ putStrLn (m ++ show n ++ ": " ++ s)
where m | n == l = "*"
| otherwise = " "
doCommand Edit = do
l <- getCurLine
io $ putStr $ "Replace line " ++ show l ++ ": "
new <- io getLine
modBuffer $ replaceLine l new
doCommand (Load filename) = do
mstr <- io $ handle (\(_ :: IOException) ->
putStrLn "File not found." >> return Nothing
) $ do
h <- openFile filename ReadMode
hSetEncoding h utf8
Just <$> hGetContents h
maybe (return ()) (modBuffer . const . fromString) mstr
doCommand (Line n) = modCurLine (const n) >> doCommand View
doCommand Next = modCurLine (+1) >> doCommand View
doCommand Prev = modCurLine (subtract 1) >> doCommand View
doCommand Quit = return () -- do nothing, main loop notices this and quits
doCommand Help = io . putStr . unlines $
[ "v --- view the current location in the document"
, "n --- move to the next line"
, "p --- move to the previous line"
, "l --- load a file into the editor"
, "e --- edit the current line"
, "q --- quit"
, "? --- show this list of commands"
]
doCommand Noop = return ()
inBuffer :: Buffer b => Int -> Editor b Bool
inBuffer n = do
nl <- onBuffer numLines
return (n >= 0 && n < nl)
modCurLine :: Buffer b => (Int -> Int) -> Editor b ()
modCurLine f = do
l <- getCurLine
nl <- onBuffer numLines
setCurLine . max 0 . min (nl - 1) $ f l
| martinvlk/cis194-homeworks | src/HW07/Editor.hs | gpl-3.0 | 3,809 | 0 | 14 | 1,194 | 1,422 | 713 | 709 | 105 | 2 |
module Main where
import NBTrain (tsvToStats, tsvToModel)
import NB (testUtterance, NBModel, trainUtterance)
import System.IO (hSetBuffering, stdout, BufferMode (NoBuffering), isEOF)
import Data.Char (toLower)
endToEnd :: IO (Int, Int, Float)
endToEnd = tsvToStats "../data/train.tsv" "../data/test.tsv"
main :: IO ()
main = do
hSetBuffering stdout NoBuffering
model <- tsvToModel "../data/train.tsv"
loop model
loop :: NBModel -> IO ()
loop model = do
putStrLn "Enter a tech/biz headline to classify. Empty string to exit"
putStr "> "
done <- isEOF
if done then
putStrLn "Bye."
else
do
sent <- getLine
case sent of
"" -> putStrLn "Bye."
_ -> processSentence sent model
processSentence :: String -> NBModel -> IO ()
processSentence sent model = do
let klass = testUtterance model sent
printClass sent $ case klass of
"t" -> "Technology"
_ -> "Business"
answer <- checkAnswer
if answer then
do
putStrLn "Great!"
let newModel = trainUtterance model klass sent
loop newModel
else
do
putStrLn "OK, I stand corrected."
let correct = reverseClass klass
let newModel = trainUtterance model correct sent
loop newModel
printClass :: String -> String -> IO ()
printClass sent c = putStrLn $ " I believe '" ++ sent ++ "' belongs to: " ++ c
checkAnswer :: IO Bool
checkAnswer = do
putStrLn "Was this classification correct? Y(es)/N(o)"
putStr "> "
answer <- getLine
case answer of
"" -> checkAnswer
_ -> do
let c = toLower $ head answer
case c of
'y' -> return True
'n' -> return False
_ -> checkAnswer
reverseClass :: String -> String
reverseClass c = case c of
"t" -> "b"
_ -> "t"
| dimidd/senths | src/Main.hs | gpl-3.0 | 2,215 | 0 | 16 | 905 | 546 | 263 | 283 | 60 | 4 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.EC2.DescribeInstances
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Describes one or more of your instances.
--
-- If you specify one or more instance IDs, Amazon EC2 returns information for
-- those instances. If you do not specify instance IDs, Amazon EC2 returns
-- information for all relevant instances. If you specify an instance ID that is
-- not valid, an error is returned. If you specify an instance that you do not
-- own, it is not included in the returned results.
--
-- Recently terminated instances might appear in the returned results. This
-- interval is usually less than one hour.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeInstances.html>
module Network.AWS.EC2.DescribeInstances
(
-- * Request
DescribeInstances
-- ** Request constructor
, describeInstances
-- ** Request lenses
, di1DryRun
, di1Filters
, di1InstanceIds
, di1MaxResults
, di1NextToken
-- * Response
, DescribeInstancesResponse
-- ** Response constructor
, describeInstancesResponse
-- ** Response lenses
, dirNextToken
, dirReservations
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.EC2.Types
import qualified GHC.Exts
data DescribeInstances = DescribeInstances
{ _di1DryRun :: Maybe Bool
, _di1Filters :: List "Filter" Filter
, _di1InstanceIds :: List "InstanceId" Text
, _di1MaxResults :: Maybe Int
, _di1NextToken :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'DescribeInstances' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'di1DryRun' @::@ 'Maybe' 'Bool'
--
-- * 'di1Filters' @::@ ['Filter']
--
-- * 'di1InstanceIds' @::@ ['Text']
--
-- * 'di1MaxResults' @::@ 'Maybe' 'Int'
--
-- * 'di1NextToken' @::@ 'Maybe' 'Text'
--
describeInstances :: DescribeInstances
describeInstances = DescribeInstances
{ _di1DryRun = Nothing
, _di1InstanceIds = mempty
, _di1Filters = mempty
, _di1NextToken = Nothing
, _di1MaxResults = Nothing
}
di1DryRun :: Lens' DescribeInstances (Maybe Bool)
di1DryRun = lens _di1DryRun (\s a -> s { _di1DryRun = a })
-- | One or more filters.
--
-- 'architecture' - The instance architecture ('i386' | 'x86_64').
--
-- 'availability-zone' - The Availability Zone of the instance.
--
-- 'block-device-mapping.attach-time' - The attach time for an Amazon EBS
-- volume mapped to the instance, for example, '2010-09-15T17:15:20.000Z'.
--
-- 'block-device-mapping.delete-on-termination' - A Boolean that indicates
-- whether the Amazon EBS volume is deleted on instance termination.
--
-- 'block-device-mapping.device-name' - The device name for the Amazon EBS
-- volume (for example, '/dev/sdh').
--
-- 'block-device-mapping.status' - The status for the Amazon EBS volume ('attaching' | 'attached' | 'detaching' | 'detached').
--
-- 'block-device-mapping.volume-id' - The volume ID of the Amazon EBS volume.
--
-- 'client-token' - The idempotency token you provided when you launched the
-- instance.
--
-- 'dns-name' - The public DNS name of the instance.
--
-- 'group-id' - The ID of the security group for the instance. EC2-Classic only.
--
-- 'group-name' - The name of the security group for the instance. EC2-Classic
-- only.
--
-- 'hypervisor' - The hypervisor type of the instance ('ovm' | 'xen').
--
-- 'iam-instance-profile.arn' - The instance profile associated with the
-- instance. Specified as an ARN.
--
-- 'image-id' - The ID of the image used to launch the instance.
--
-- 'instance-id' - The ID of the instance.
--
-- 'instance-lifecycle' - Indicates whether this is a Spot Instance ('spot').
--
-- 'instance-state-code' - The state of the instance, as a 16-bit unsigned
-- integer. The high byte is an opaque internal value and should be ignored. The
-- low byte is set based on the state represented. The valid values are: 0
-- (pending), 16 (running), 32 (shutting-down), 48 (terminated), 64 (stopping),
-- and 80 (stopped).
--
-- 'instance-state-name' - The state of the instance ('pending' | 'running' | 'shutting-down' | 'terminated' | 'stopping' | 'stopped').
--
-- 'instance-type' - The type of instance (for example, 'm1.small').
--
-- 'instance.group-id' - The ID of the security group for the instance.
--
-- 'instance.group-name' - The name of the security group for the instance.
--
-- 'ip-address' - The public IP address of the instance.
--
-- 'kernel-id' - The kernel ID.
--
-- 'key-name' - The name of the key pair used when the instance was launched.
--
-- 'launch-index' - When launching multiple instances, this is the index for
-- the instance in the launch group (for example, 0, 1, 2, and so on).
--
-- 'launch-time' - The time when the instance was launched.
--
-- 'monitoring-state' - Indicates whether monitoring is enabled for the
-- instance ('disabled' | 'enabled').
--
-- 'owner-id' - The AWS account ID of the instance owner.
--
-- 'placement-group-name' - The name of the placement group for the instance.
--
-- 'platform' - The platform. Use 'windows' if you have Windows instances;
-- otherwise, leave blank.
--
-- 'private-dns-name' - The private DNS name of the instance.
--
-- 'private-ip-address' - The private IP address of the instance.
--
-- 'product-code' - The product code associated with the AMI used to launch the
-- instance.
--
-- 'product-code.type' - The type of product code ('devpay' | 'marketplace').
--
-- 'ramdisk-id' - The RAM disk ID.
--
-- 'reason' - The reason for the current state of the instance (for example,
-- shows "User Initiated [date]" when you stop or terminate the instance).
-- Similar to the state-reason-code filter.
--
-- 'requester-id' - The ID of the entity that launched the instance on your
-- behalf (for example, AWS Management Console, Auto Scaling, and so on).
--
-- 'reservation-id' - The ID of the instance's reservation. A reservation ID is
-- created any time you launch an instance. A reservation ID has a one-to-one
-- relationship with an instance launch request, but can be associated with more
-- than one instance if you launch multiple instances using the same launch
-- request. For example, if you launch one instance, you'll get one reservation
-- ID. If you launch ten instances using the same launch request, you'll also
-- get one reservation ID.
--
-- 'root-device-name' - The name of the root device for the instance (for
-- example, '/dev/sda1').
--
-- 'root-device-type' - The type of root device that the instance uses ('ebs' | 'instance-store').
--
-- 'source-dest-check' - Indicates whether the instance performs
-- source/destination checking. A value of 'true' means that checking is enabled,
-- and 'false' means checking is disabled. The value must be 'false' for the
-- instance to perform network address translation (NAT) in your VPC.
--
-- 'spot-instance-request-id' - The ID of the Spot Instance request.
--
-- 'state-reason-code' - The reason code for the state change.
--
-- 'state-reason-message' - A message that describes the state change.
--
-- 'subnet-id' - The ID of the subnet for the instance.
--
-- 'tag':/key/=/value/ - The key/value combination of a tag assigned to the
-- resource, where 'tag':/key/ is the tag's key.
--
-- 'tag-key' - The key of a tag assigned to the resource. This filter is
-- independent of the 'tag-value' filter. For example, if you use both the filter
-- "tag-key=Purpose" and the filter "tag-value=X", you get any resources
-- assigned both the tag key Purpose (regardless of what the tag's value is),
-- and the tag value X (regardless of what the tag's key is). If you want to
-- list only resources where Purpose is X, see the 'tag':/key/=/value/ filter.
--
-- 'tag-value' - The value of a tag assigned to the resource. This filter is
-- independent of the 'tag-key' filter.
--
-- 'tenancy' - The tenancy of an instance ('dedicated' | 'default').
--
-- 'virtualization-type' - The virtualization type of the instance ('paravirtual'
-- | 'hvm').
--
-- 'vpc-id' - The ID of the VPC that the instance is running in.
--
-- 'network-interface.description' - The description of the network interface.
--
-- 'network-interface.subnet-id' - The ID of the subnet for the network
-- interface.
--
-- 'network-interface.vpc-id' - The ID of the VPC for the network interface.
--
-- 'network-interface.network-interface.id' - The ID of the network interface.
--
-- 'network-interface.owner-id' - The ID of the owner of the network interface.
--
-- 'network-interface.availability-zone' - The Availability Zone for the
-- network interface.
--
-- 'network-interface.requester-id' - The requester ID for the network
-- interface.
--
-- 'network-interface.requester-managed' - Indicates whether the network
-- interface is being managed by AWS.
--
-- 'network-interface.status' - The status of the network interface ('available')
-- | 'in-use').
--
-- 'network-interface.mac-address' - The MAC address of the network interface.
--
-- 'network-interface-private-dns-name' - The private DNS name of the network
-- interface.
--
-- 'network-interface.source-destination-check' - Whether the network interface
-- performs source/destination checking. A value of 'true' means checking is
-- enabled, and 'false' means checking is disabled. The value must be 'false' for
-- the network interface to perform network address translation (NAT) in your
-- VPC.
--
-- 'network-interface.group-id' - The ID of a security group associated with
-- the network interface.
--
-- 'network-interface.group-name' - The name of a security group associated
-- with the network interface.
--
-- 'network-interface.attachment.attachment-id' - The ID of the interface
-- attachment.
--
-- 'network-interface.attachment.instance-id' - The ID of the instance to which
-- the network interface is attached.
--
-- 'network-interface.attachment.instance-owner-id' - The owner ID of the
-- instance to which the network interface is attached.
--
-- 'network-interface.addresses.private-ip-address' - The private IP address
-- associated with the network interface.
--
-- 'network-interface.attachment.device-index' - The device index to which the
-- network interface is attached.
--
-- 'network-interface.attachment.status' - The status of the attachment ('attaching' | 'attached' | 'detaching' | 'detached').
--
-- 'network-interface.attachment.attach-time' - The time that the network
-- interface was attached to an instance.
--
-- 'network-interface.attachment.delete-on-termination' - Specifies whether the
-- attachment is deleted when an instance is terminated.
--
-- 'network-interface.addresses.primary' - Specifies whether the IP address of
-- the network interface is the primary private IP address.
--
-- 'network-interface.addresses.association.public-ip' - The ID of the
-- association of an Elastic IP address with a network interface.
--
-- 'network-interface.addresses.association.ip-owner-id' - The owner ID of the
-- private IP address associated with the network interface.
--
-- 'association.public-ip' - The address of the Elastic IP address bound to the
-- network interface.
--
-- 'association.ip-owner-id' - The owner of the Elastic IP address associated
-- with the network interface.
--
-- 'association.allocation-id' - The allocation ID returned when you allocated
-- the Elastic IP address for your network interface.
--
-- 'association.association-id' - The association ID returned when the network
-- interface was associated with an IP address.
--
--
di1Filters :: Lens' DescribeInstances [Filter]
di1Filters = lens _di1Filters (\s a -> s { _di1Filters = a }) . _List
-- | One or more instance IDs.
--
-- Default: Describes all your instances.
di1InstanceIds :: Lens' DescribeInstances [Text]
di1InstanceIds = lens _di1InstanceIds (\s a -> s { _di1InstanceIds = a }) . _List
-- | The maximum number of items to return for this call. The call also returns a
-- token that you can specify in a subsequent call to get the next set of
-- results. If the value is greater than 1000, we return only 1000 items.
di1MaxResults :: Lens' DescribeInstances (Maybe Int)
di1MaxResults = lens _di1MaxResults (\s a -> s { _di1MaxResults = a })
-- | The token for the next set of items to return. (You received this token from
-- a prior call.)
di1NextToken :: Lens' DescribeInstances (Maybe Text)
di1NextToken = lens _di1NextToken (\s a -> s { _di1NextToken = a })
data DescribeInstancesResponse = DescribeInstancesResponse
{ _dirNextToken :: Maybe Text
, _dirReservations :: List "item" Reservation
} deriving (Eq, Read, Show)
-- | 'DescribeInstancesResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dirNextToken' @::@ 'Maybe' 'Text'
--
-- * 'dirReservations' @::@ ['Reservation']
--
describeInstancesResponse :: DescribeInstancesResponse
describeInstancesResponse = DescribeInstancesResponse
{ _dirReservations = mempty
, _dirNextToken = Nothing
}
-- | The token to use when requesting the next set of items. If there are no
-- additional items to return, the string is empty.
dirNextToken :: Lens' DescribeInstancesResponse (Maybe Text)
dirNextToken = lens _dirNextToken (\s a -> s { _dirNextToken = a })
-- | One or more reservations.
dirReservations :: Lens' DescribeInstancesResponse [Reservation]
dirReservations = lens _dirReservations (\s a -> s { _dirReservations = a }) . _List
instance ToPath DescribeInstances where
toPath = const "/"
instance ToQuery DescribeInstances where
toQuery DescribeInstances{..} = mconcat
[ "DryRun" =? _di1DryRun
, "Filter" `toQueryList` _di1Filters
, "InstanceId" `toQueryList` _di1InstanceIds
, "MaxResults" =? _di1MaxResults
, "NextToken" =? _di1NextToken
]
instance ToHeaders DescribeInstances
instance AWSRequest DescribeInstances where
type Sv DescribeInstances = EC2
type Rs DescribeInstances = DescribeInstancesResponse
request = post "DescribeInstances"
response = xmlResponse
instance FromXML DescribeInstancesResponse where
parseXML x = DescribeInstancesResponse
<$> x .@? "nextToken"
<*> x .@? "reservationSet" .!@ mempty
instance AWSPager DescribeInstances where
page rq rs
| stop (rs ^. dirNextToken) = Nothing
| otherwise = (\x -> rq & di1NextToken ?~ x)
<$> (rs ^. dirNextToken)
| dysinger/amazonka | amazonka-ec2/gen/Network/AWS/EC2/DescribeInstances.hs | mpl-2.0 | 15,365 | 0 | 11 | 2,750 | 1,091 | 741 | 350 | 87 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module PreludeSpec(spec) where
import PPrelude
import Testing
import qualified Data.ByteString as BS
import Test.Hspec
import Test.QuickCheck
spec :: Spec
spec = do
describe "decodeInt" $ do
it "should decode what it encodes (ints)" $ property $ \n ->
(n :: Int) >= 0 ==> (decodeInt . encodeInt $ n) `shouldBe` Just n
it "fails to decode zero-prefixed integers" $ property $ \n padding ->
padding > 0 && n >= 0 ==>
let padded = BS.replicate padding 0 <> encodeInt (n :: Int)
in decodeInt padded `shouldBe` Nothing
describe "encodeInt" $ do
it "should encode 15" $ encodeInt 15 `shouldBe` "\x0f"
it "should encode 1024" $ encodeInt 1024 `shouldBe` "\x04\x00"
| haroldcarr/learn-haskell-coq-ml-etc | haskell/playpen/blockchain/ben-kirwin-merkle/test/PreludeSpec.hs | unlicense | 789 | 0 | 19 | 210 | 232 | 121 | 111 | 19 | 1 |
module Foundation where
import Import.NoFoundation
import Text.Hamlet (hamletFile)
import Text.Jasmine (minifym)
import Yesod.Core.Types (Logger)
import Yesod.Default.Util (addStaticContentExternal)
import qualified Yesod.Core.Unsafe as Unsafe
import qualified Data.CaseInsensitive as CI
import qualified Data.Text.Encoding as TE
-- | The foundation datatype for your application. This can be a good place to
-- keep settings and values requiring initialization before your application
-- starts running, such as database connections. Every handler will have
-- access to the data present here.
data App = App
{ appSettings :: AppSettings
, appStatic :: Static -- ^ Settings for static file serving.
, appHttpManager :: Manager
, appLogger :: Logger
}
-- This is where we define all of the routes in our application. For a full
-- explanation of the syntax, please see:
-- http://www.yesodweb.com/book/routing-and-handlers
--
-- Note that this is really half the story; in Application.hs, mkYesodDispatch
-- generates the rest of the code. Please see the following documentation
-- for an explanation for this split:
-- http://www.yesodweb.com/book/scaffolding-and-the-site-template#scaffolding-and-the-site-template_foundation_and_application_modules
--
-- This function also generates the following type synonyms:
-- type Handler = HandlerT App IO
-- type Widget = WidgetT App IO ()
mkYesodData "App" $(parseRoutesFile "config/routes")
-- | A convenient synonym for creating forms.
type Form x = Html -> MForm (HandlerT App IO) (FormResult x, Widget)
-- Please see the documentation for the Yesod typeclass. There are a number
-- of settings which can be configured by overriding methods here.
instance Yesod App where
-- Controls the base of generated URLs. For more information on modifying,
-- see: https://github.com/yesodweb/yesod/wiki/Overriding-approot
approot = ApprootRequest $ \app req ->
case appRoot $ appSettings app of
Nothing -> getApprootText guessApproot app req
Just root -> root
-- Store session data on the client in encrypted cookies,
-- default session idle timeout is 120 minutes
makeSessionBackend _ = Just <$> defaultClientSessionBackend
120 -- timeout in minutes
"config/client_session_key.aes"
-- Yesod Middleware allows you to run code before and after each handler function.
-- The defaultYesodMiddleware adds the response header "Vary: Accept, Accept-Language" and performs authorization checks.
-- Some users may also want to add the defaultCsrfMiddleware, which:
-- a) Sets a cookie with a CSRF token in it.
-- b) Validates that incoming write requests include that token in either a header or POST parameter.
-- For details, see the CSRF documentation in the Yesod.Core.Handler module of the yesod-core package.
yesodMiddleware = defaultYesodMiddleware
defaultLayout widget = do
master <- getYesod
mmsg <- getMessage
-- We break up the default layout into two components:
-- default-layout is the contents of the body tag, and
-- default-layout-wrapper is the entire page. Since the final
-- value passed to hamletToRepHtml cannot be a widget, this allows
-- you to use normal widget features in default-layout.
pc <- widgetToPageContent $ do
addStylesheet $ StaticR css_bootstrap_css
$(widgetFile "default-layout")
withUrlRenderer $(hamletFile "templates/default-layout-wrapper.hamlet")
-- Routes not requiring authenitcation.
isAuthorized FaviconR _ = return Authorized
isAuthorized RobotsR _ = return Authorized
-- Default to Authorized for now.
isAuthorized _ _ = return Authorized
-- This function creates static content files in the static folder
-- and names them based on a hash of their content. This allows
-- expiration dates to be set far in the future without worry of
-- users receiving stale content.
addStaticContent ext mime content = do
master <- getYesod
let staticDir = appStaticDir $ appSettings master
addStaticContentExternal
minifym
genFileName
staticDir
(StaticR . flip StaticRoute [])
ext
mime
content
where
-- Generate a unique filename based on the content itself
genFileName lbs = "autogen-" ++ base64md5 lbs
-- What messages should be logged. The following includes all messages when
-- in development, and warnings and errors in production.
shouldLog app _source level =
appShouldLogAll (appSettings app)
|| level == LevelWarn
|| level == LevelError
makeLogger = return . appLogger
-- This instance is required to use forms. You can modify renderMessage to
-- achieve customized and internationalized form validation messages.
instance RenderMessage App FormMessage where
renderMessage _ _ = defaultFormMessage
-- Useful when writing code that is re-usable outside of the Handler context.
-- An example is background jobs that send email.
-- This can also be useful for writing code that works across multiple Yesod applications.
instance HasHttpManager App where
getHttpManager = appHttpManager
unsafeHandler :: App -> Handler a -> IO a
unsafeHandler = Unsafe.fakeHandlerGetLogger appLogger
-- Note: Some functionality previously present in the scaffolding has been
-- moved to documentation in the Wiki. Following are some hopefully helpful
-- links:
--
-- https://github.com/yesodweb/yesod/wiki/Sending-email
-- https://github.com/yesodweb/yesod/wiki/Serve-static-files-from-a-separate-domain
-- https://github.com/yesodweb/yesod/wiki/i18n-messages-in-the-scaffolding
| philipmw/yesod-website | Foundation.hs | unlicense | 5,872 | 0 | 14 | 1,280 | 591 | 332 | 259 | -1 | -1 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="id-ID">
<title>DOM XSS Active Scan Rule | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | 0xkasun/security-tools | src/org/zaproxy/zap/extension/domxss/resources/help_id_ID/helpset_id_ID.hs | apache-2.0 | 986 | 80 | 66 | 163 | 421 | 213 | 208 | -1 | -1 |
module ToHoTTSQLTest where
import ToHoTTSQL
import CosetteParser
import qualified Test.HUnit as H
xs :: HSSchema
xs = MakeSchema "xs" [("a", "int"), ("k", "int")]
ys :: HSSchema
ys = MakeSchema "ys" [("k", "int")]
env :: HSEnv
env = MakeHSEnv [("x", "xs"), ("y", "ys")] [xs, ys]
q2hst :: Either String HSQueryExpr
q2hst = toHSQuery env HSEmpty query2
toHoTTTest1 :: (Either String HSQueryExpr, String)
toHoTTTest1 = (q2hst, "(SELECT right\8901left\8901a FROM (product ((SELECT (combine right\8901a right\8901k) FROM (table x) WHERE true)) (table y)) WHERE (equal right\8901left\8901k right\8901right\8901k))")
makeToHoTTTest :: (Either String HSQueryExpr, String) -> H.Test
makeToHoTTTest (v, exp) = H.TestLabel (show v) $ H.TestCase $ do
case v of
Left e -> H.assertFailure $ show e
Right a -> H.assertEqual (show v) exp (toCoq a)
main :: IO H.Counts
main = H.runTestTT $ H.TestList $ (makeToHoTTTest <$> [toHoTTTest1])
| uwdb/Cosette | dsl/ToHoTTSQLTest.hs | bsd-2-clause | 941 | 0 | 13 | 154 | 312 | 173 | 139 | 21 | 2 |
---
--- ktemkin's xmonad.hs
--- (Three monitors; dzen/conky based status bar;
---
import Data.Monoid
import Control.Monad
--XMonad Core
--(This exposes the window manager itself.)
import XMonad
import XMonad.Core
--XMonad Hooks
--(These allow the addition of user functionality to WM functions.)
import XMonad.Hooks.SetWMName
import XMonad.Hooks.DynamicLog
import XMonad.Hooks.ManageDocks
import XMonad.Hooks.UrgencyHook
--Workspace Utilities
--(These provide support functions for working with workspaces.)
import XMonad.Util.WorkspaceCompare
--Compatibility Layer
--(Adds compatibility with some common programs, like Chromium.)
import XMonad.Hooks.EwmhDesktops
--Windowing Layouts
--(These provide the algorithms that determine the window layout.)
import XMonad.Layout
import XMonad.Layout.IM
import XMonad.Layout.Grid
import XMonad.Layout.Spiral
import XMonad.Layout.NoBorders
import XMonad.Layout.PerWorkspace
import XMonad.Layout.ResizableTile
import XMonad.Layout.Tabbed
import XMonad.Layout.Reflect
--Prompt Features
--(These allow dmenu style prompts, via a tool such as dzen.)
import XMonad.Prompt
import XMonad.Prompt.Man
import XMonad.Prompt.Shell
import XMonad.Prompt.Window
--Statusbar Dependencies
--(These enable the usage of a status bar to display tags.)
import System.IO
import XMonad.Util.Run
import qualified Data.Map as M
--Key Actions
--(These enable actions to be performed on at shortcut keys.)
import qualified XMonad.StackSet as S
import XMonad.Actions.PerWorkspaceKeys
--Cycle Workspaces
--(This allows using the keyboard and mouse to switch screen and workspace.)
import XMonad.Actions.CycleWS
--'Mouse follows focus'
--(Allows the mouse pointer to snap to the focused XMonad window.)
import XMonad.Actions.UpdatePointer
--Layout hints:
--Allow xmonad windows to repspect size hints.
--(This fixes some gvim/wine stuff.)
import XMonad.Layout.LayoutHints
-- *********************************************************************
--Appearance/Theming Options
-- *********************************************************************
-- Top Bar Colors
--(These colors provide the 'themeing' for the dzen status bars.)
mySeperatorColor = "white"
myFgColor = "#729FCF"
myBgColor = "#2B2B2B"
myHighlightedFgColor = "white"
myHighlightedBgColor = "#BDBDBD"
myActiveBorderColor = "#00FFF7" --"#00FF00"
myInactiveBorderColor = "gray20"
myCurrentWsFgColor = "white"
myCurrentWsBgColor = "#3D5670"
myVisibleWsFgColor = "gray80"
myVisibleWsBgColor = "#3C4752"
myHiddenWsFgColor = "white"
myHiddenEmptyWsFgColor = "gray40"
myUrgentWsFgColor = "white"
myUrgentWsBgColor = "#729FCF"
myTitleFgColor = "#729FCF"
myUrgencyHintFgColor = "white"
myUrgencyHintBgColor = "#63AFFF"
-- Top Bars Font
-- (The top bar text will be rendered in this font.)
tagBarFont = "Terminus-9"
--Note that pretty fonts like this require dzen2-xft
--(which is incidentally in the Arch User Repository.)
-- Stats Bar Images
-- (Provides tiny images identifying the computer statistics.)
statusBarImages = "/home/ktemkin/.dzen/bitmaps/"
--Top Bar Formatting Options
--(These options determine how the top bars look; see the dzen manpage
-- for more info.)
topBarOptions = "-fg '" ++ myFgColor ++ "' -bg '" ++ myBgColor ++ "' -h 14 -xs 2 -fn '" ++ tagBarFont ++ "' -e ''"
--Tag Bar Command
--(This command displays the system tags, layout, and currently focused window title.)
tagBar = "dzen2 -ta l " ++ topBarOptions
--Statistics Bar Command
--(This command displays information about the computer, and the time.)
statsBar = "sleep 0.2s && conky -c ~/.conky_bar | dzen2 -x 1000 -w 855 " ++ topBarOptions
--System Tray Command
--(This command displays a small system tray.)
systemTray = "trayer --edge top --align right --widthtype pixel --transparent true --alpha 0 --tint 0x2B2B2B --heighttype pixel --width 60 --expand true --height 14"
--Monitor Width
monWidth = "1920"
-- *********************************************************************
--Window Manager (Haskell) Code
-- *********************************************************************
--Past this point, this is the code that _runs_ XMonad.
--Most of the real work is done in the modules imported above.
--Define the XMonad entry point configuration. ("Main function.")
main =
do
--Spawn the tag bar.
tagBarPipe <- spawnPipe tagBar
--and spawn the overlapping stats bar
spawn statsBar
--set the system cursor to a left-pointer
spawn "xsetroot -cursor_name left_ptr"
--display wallpaper?
spawn "xloadimage -onroot -tile ~/Pictures/archlinux-zenburn-wide.jpg"
--Run XMonad.
--This does the core of the backend work.
--This file does the frontend. ;)
xmonad
--Handle 'urgent' application events;
--these are equivalent to the flashing taskbar items in Windows.
$ urgentEventHook
--Start xmonad with a modified default configuration:
$ ewmh defaultConfig
{
--Set the default terminal binary.
terminal = "roxterm",
--Set up window borders,
focusedBorderColor = myActiveBorderColor,
normalBorderColor = myInactiveBorderColor,
--Specify rules for window placement;
--these include items such as "don't place windows on the status bars"
--and "use the IM layout for the gimp".
manageHook = manageDocks <+> localManagementHook <+> manageHook defaultConfig,
--Specify which windowing algorithms to use
--to determine window layout.
layoutHook = avoidStruts $ localLayouts,
--Allow windows to go fullscreen, and fix focus follows mouse across multiple X screens
handleEventHook = fullscreenEventHook, -- <+> xFocusFollowsMouse,
--turn off Focus Follows Mouse, as we replace it below
--focusFollowsMouse = False,
--Upon startup, change the Window Manager's name
--from XMonad to LG3D, as Java recognizes LG3D
--as a non reparenting WM and adjusts some of its
--interaction routines. These routines work (more)
--correctly on XMonad.
startupHook = setWMName "LG3D",
--When an event is written to the internel log,
--extract information via a Pretty Print (PP)
--routine, and pass it to the tag bar.
logHook = (dynamicLogWithPP $ tagBarPP tagBarPipe) >> javaLogHook, -- >> mouseLogHook,
--Use the left Windows key as the normal mod mask,
--instead of the default of alt, which interferes
--with some programs.
modMask = mod4Mask,
--Specify mouse actions for the WM;
--each mouse button (including 'wheel up' and
--'wheel down) is mapped to a function.
mouseBindings = localMouse,
--Specify "shorcut" keys for the WM.
--The name shortcut isn't quite appropriate, as
--most of the functions aren't implemented elsewhere.
keys = localKeys,
--Set the name of each of the "workspaces"
--to a custom tag name.
workspaces = localTags
}
-- Tags / Named Workspaces
-- (These named workspaces provide an easy way of organizing running applications.)
localTags =
[
" 1:term ", --Terminals / dashboard / etc
" 2:web ", --Web browser
" 3:code ", --IDEs, text editing
" 4 ", --general purpose
" 5 ", --general purpose
" 6:ref ", --reference material
" 7:ref ", --reference material
" 8:file ", --file explorer
" 9:media " --media
]
--Mouse functionality, which is processed each time XMonad
--processes the
--mouseLogHook = ( updatePointer (Relative 0.5 0.5) )
mouseLogHook = ( updatePointer (TowardsCentre 0.5 0.5) )
--Allow Java applications to run correctly by tricking Java into believing this is LG3D
--(another non-reparenting window manager.)
javaLogHook = ( setWMName "LG3D" )
--Tag Bar PrettyPrinter
--(This determines the output which is sent to dzen2. For markup reference,
-- consult the dzen2 manual.)
tagBarPP h =
--Derive our pretty-printer from the default, as they're
--very similar.
defaultPP
{
--Output as a string to the standard input via System.IO.
ppOutput = hPutStrLn h,
--The seperator between the tags, the layout, and the title.
--(In this case, it's just a very thin line.)
ppSep = "^bg(" ++ mySeperatorColor ++ ")^r(1,15)^bg()",
--The tag names are not divided by any spaces- this allows us
--to better color the backgrounds. (Spaces are included instead
--in the tag names.)
ppWsSep = "",
--Colorize the current tag with the theme color.
--(See the wrapFgBg function defined below.)
ppCurrent = wrapFgBg myCurrentWsFgColor myCurrentWsBgColor,
--Colorize visible (but not focused) tags.
ppVisible = wrapFgBg myVisibleWsFgColor myVisibleWsBgColor,
--Colorize tags which have windows, but are not visible.
ppHidden = wrapFg myHiddenWsFgColor,
--Colorize tags which have no windows, and are non-visible.
ppHiddenNoWindows = wrapFg myHiddenEmptyWsFgColor,
--Colorize workspaces that have windows marked 'urgent',
ppUrgent = wrapFgBg myUrgentWsFgColor myUrgentWsBgColor,
--Colorize the current window's title based on the theme.
ppTitle = (\x -> " " ++ wrapFg myTitleFgColor x),
--Convert the internal layout names to short text (which can be
--interpreted as an image thanks to dzen).
ppLayout = dzenColor myFgColor"" .
(\x -> case x of
"Hinted ResizableTall" -> wrapBitmap "rob/tall.xbm"
"Mirror ResizableTall" -> wrapBitmap "rob/mtall.xbm"
"Full" -> wrapBitmap "rob/full.xbm"
"IM Grid" -> " IM "
"Spiral" -> " S "
"Tabbed Simplest" -> " T "
-- "Hinted ResizableTall" -> " H "
"IM ReflectX IM Full" -> " G "
_ -> x
)
}
where
--These string modification functions simply add dzen color markers.
--See the dzen manual for more information.
wrapFgBg fgColor bgColor content= wrap ("^fg(" ++ fgColor ++ ")^bg(" ++ bgColor ++ ")") "^fg()^bg()" content
wrapFg color content = wrap ("^fg(" ++ color ++ ")") "^fg()" content
wrapBg color content = wrap ("^bg(" ++ color ++ ")") "^bg()" content
wrapBitmap bitmap = "^p(5)^i(" ++ statusBarImages ++ bitmap ++ ")^p(5)"
-- Layouts
-- (These specify the layout algorithms to be executed by the xmonad backend.
-- These can be anything from whole algorithms, implemented inplace, to simple
-- references to existing algorithms.)
localLayouts =
--Smart Border Filter
--(Interceps border assignments and disables borders on fullscreen items,
-- when there's only one item, or when the window in focus is similarly
-- unambiguous.)
smartBorders
--Per Workspace Layout
--(Allows the user to specify default layouts on a per-workspace basis.)
$ perWSLayouts
--These layout functions are available to every terminal, unless overridden.
--(Note that pieces of the items listed here are defined below.)
$
(
tiledHinted ||| --Standard Tall tiled layout.
Mirror tiled ||| --Same thing, but rotated 90 degrees.
Full ||| --Single application is fullscreen.
spiral (6/7) ||| --Many applications of descending size. "Spiral"
imLayout ||| --Many similar/identically sized windows.
--tiledHinted ||| -- normal tiled, but with Layout Hints
gimp --special paneled layout for the gimp
)
where
--Shortcut to the standard, XMonad tall layout.
tiled = ResizableTall 1 (3/100) ratio []
tiledHinted = layoutHints tiled
--Shortbut to the 1/10th size IM layout, suitable for instant messengers.
imLayout = withIM (1/10) (Role "roster") Grid
--Calculation of the golden ratio, which keeps the host window feeling like
--a nice, square window. Can be adjusted to anything between 0 and 1.
ratio = toRational (2/(1+sqrt(5)::Double)) -- golden
--Gimp Layout
gimp = withIM (0.11) (Role "gimp-toolbox") $
reflectHoriz $
withIM(0.15) (Role "gimp-dock") Full
--Per Workspace Layouts
--(Specifies special layouts for the given workspaces.)
perWSLayouts =
--This line defines the specific rules for the Terminal workspace.
(onWorkspace " 1:term " (imLayout ||| tiledHinted ||| Mirror tiled ||| Full)) .
(onWorkspace " 2:web " (tiledHinted ||| simpleTabbed ||| Mirror tiled ||| Full))
where
--Shortcut to the standard, XMonad tall layout.
tiled = ResizableTall 1 (3/100) ratio []
tiledHinted = layoutHints tiled
--Shortbut to the 1/10th size IM layout, suitable for instant messengers.
imLayout = withIM (1/10) (Role "roster") Grid
--Calculation of the golden ratio, which keeps the host window feeling like
--a nice, square window. Can be adjusted to anything between 0 and 1.
ratio = toRational (2/(1+sqrt(5)::Double)) -- golden
-- Urgency Hints
-- (This allows windows such as instant messengers to get the user's
-- attention, so the conversation doesn't sit in the background
-- unnoticed. )
urgentEventHook =
--If an application states it has urgent info, create a new
--dzen instance with the following options.
--withUrgencyHook NoUrgencyHook
withUrgencyHook dzenUrgencyHook
{
--Last for 10 seconds.
duration = 10000000,
--Command line arguments for dzen.
args = [
--Occur across the whole top (?)
"-x", "1036",
"-y", "0",
"-h", "14",
"-w", "895",
"-ta", "c",
"-xs", "1",
"-fn", tagBarFont,
--Use themed colors.
"-fg", "" ++ myUrgencyHintFgColor ++ "",
"-bg", "" ++ "#4A8FD9"
]
}
--Automatic layout rules.
--(The example rule given places windows of the class gimp into floating
-- mode. Window class can be determined using the 'xprop' utility.)
localManagementHook =
composeAll . concat $
--Automatically float gimp windows.
[
[ title =? "Spyder" --> doFloat ]
]
--Create a function that defines a new set of keybindings.
--(Defines a list of keybindings based on the configuration argument.)
newKeys conf@(XConfig {XMonad.modMask = modm}) =
[
--MOD+P: Shell prompt; allows the user to type a command, with suggestions.
--((modm, xK_p), shellPrompt inputBar),
((modm, xK_p), spawn "dmenu_run -b"),
--MOD+Q: Reload xmonad. Kills all status bars in the process, preventing duplicates
-- when the new status bars load.
((modm, xK_q), spawn "killall -9 conky dzen2 trayer; /home/ktemkin/.xmonad/dorestart.sh"),
--MOD+G: Allows the user to type the name of the window into the inputbar to go to it.
((modm, xK_g ), windowPromptGoto inputBar { autoComplete = Just 500000 }),
--SHIFT+MOD+B: Brings the given window _to_ the user, using the inputbar.
((modm .|. shiftMask, xK_b ), windowPromptBring inputBar),
--MOD+W: Switches the user's view to any windows that have declared urgency.
((modm .|. shiftMask, xK_w ), focusUrgent),
--MOD+B: Hide or show the top bar.
((modm, xK_b ), sendMessage ToggleStruts),
--Microsoft Favorites Key
--(Spawns the given application depending on workspace.)
((modm, xK_f),
bindOn [
(" 1:term ", spawn "roxterm"),
(" 2:web ", spawn "chromium"),
(" 3:code ", spawn "gvim"),
(" 4 ", shellPrompt inputBar),
(" 5 ", shellPrompt inputBar),
(" 6:ref ", shellPrompt inputBar),
(" 7:ref", shellPrompt inputBar),
(" 8:file ", spawn "thunar"),
(" 9:media ", shellPrompt inputBar)
]
),
--Play/pause key
--In my case, I want it to spawn the program "mpc toggle".
((0, xK_Menu), spawn "mpc toggle"),
--Volume keys;
--I handle these here, as most of the various OSDs don't
--work with multihead. (Thanks, gnome-settings-daemon.)
((modm, xK_Up), spawn "amixer -c 0 sset Master 3%+"),
((modm, xK_Down), spawn "amixer -c 0 sset Master 3%-"),
--Back/foward keys:
--Use these to switch the focused monitor.
--((mod1Mask, xK_Right), nextScreen),
--((mod1Mask, xK_Left), prevScreen),
--Push the active window onto the other stackset
((modm, xK_z), spawn "yubiauth --code2e"),
((modm, xK_x), spawn "yubiauth --code1e"),
--Monitor switch key:
--Switch _focused_ monitors when the menu key is pressed;
--this really speeds up three monitor operation.
--((0, 0xff67), prevScreen),
--Calculator key
((0, 0x1008ff1d), spawn "gnome-genius")
]
++
--
-- mod-[1..9], Switch to workspace N
--
-- mod-[1..9], Switch to workspace N
-- mod-shift-[1..9], Move client to workspace N
--
[((m .|. modm, k), windows $ f i)
| (i, k) <- zip (XMonad.workspaces conf) [xK_exclam, xK_at, xK_numbersign, xK_dollar, xK_percent, xK_asciicircum, xK_ampersand, xK_asterisk, xK_parenleft, xK_parenright]
, (f, m) <- [(S.greedyView, 0), (S.shift, shiftMask)]]
--STANDARD MOUSE
--Create a function that defines a new set of mouse bindings.
--(Defines a list of mouse bindings based on the configuration argument.)
newMouse (XConfig {XMonad.modMask = modMask}) =
[
--Use the back/forward thumb buttons to switch the window in focus.
((0, 9 :: Button),(\_ -> nextScreen)),
((0, 8 :: Button), (\_ -> prevScreen )),
--Use the thumb button to switch monitors.
((0, 10 :: Button), (\_ -> windows S.focusUp))
]
--TRACKBALL
----Create a function that defines a new set of mouse bindings.
----(Defines a list of mouse bindings based on the configuration argument.)
--newMouse (XConfig {XMonad.modMask = modMask}) =
--[
----Use the back/forward thumb buttons to switch the window in focus.
----((0, 8 :: Button),(\_ -> windows S.focusUp)),
----((0, 9 :: Button), (\_ -> windows S.focusDown)),
----Use the thumb button to switch monitors.
--((0, 2 :: Button), (\_ -> nextScreen))
--]
--Combine the default bindings with our new bindings, to create functions which
--returns a complete list of bindings from a configuration.
localKeys x = M.union (M.fromList (newKeys x)) (keys defaultConfig x)
localMouse x = M.union (M.fromList (newMouse x)) (mouseBindings defaultConfig x)
-- Input Bar
--(This is a dmenu-like bar that allows the user to quickly execute a
-- given command or program, with suggestions.)
inputBar =
defaultXPConfig
{
--Appear at the bottom of the screen, without a border.
position = Bottom,
promptBorderWidth = 0,
--Specify height and color; themeing.
height = 15,
bgColor = myBgColor,
fgColor = myFgColor,
fgHLight = myHighlightedFgColor,
bgHLight = myHighlightedBgColor
}
--Special X event hook, which fixes the behavior of focusFollowsMouse when multiple X screens are present
xFocusFollowsMouse :: Event -> X All
xFocusFollowsMouse e@(CrossingEvent {ev_window = w, ev_event_type = t})
| t == enterNotify && ev_mode e == notifyNormal
= do
focus w
setFocusX w
takeFocusX w
return (All True)
xFocusFollowsMouse _ = return (All True)
--Java Compatibility
--
takeFocusX ::
Window
-> X ()
takeFocusX w =
withWindowSet . const $ do
dpy <- asks display
wmtakef <- atom_WM_TAKE_FOCUS
wmprot <- atom_WM_PROTOCOLS
protocols <- io $ getWMProtocols dpy w
when (wmtakef `elem` protocols) $
io . allocaXEvent $ \ev -> do
setEventType ev clientMessage
setClientMessageEvent ev w wmprot 32 wmtakef currentTime
sendEvent dpy w False noEventMask ev
takeTopFocus ::
X ()
takeTopFocus =
withWindowSet $ maybe (setFocusX =<< asks theRoot) takeFocusX . S.peek
| ktemkin/dotfiles | xmonad/xmonad.hs | bsd-2-clause | 22,175 | 0 | 14 | 6,770 | 2,578 | 1,549 | 1,029 | 229 | 8 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MonoLocalBinds #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
module Roguelike.Game
( initGameLoop
, gameLoop
-- re-export from Model
, GameState
, RoundResult (..)
) where
import Control.Eff
import Control.Eff.State.Lazy
import Control.Monad (when)
import Roguelike.Actions
import Roguelike.Dungeon
import Roguelike.Model
import Roguelike.Random (RNG)
newPlayerHealth :: Int
newPlayerHealth = 10
newPlayer :: String -> Coords -> Player
newPlayer playerName playerPosition = Player playerName newPlayerHealth playerPosition
initGameLoop :: RNG -> String -> GameState
initGameLoop rng playerName =
let (playerCoords, newDungeon) = dungeonGenerator rng in
GameState newDungeon (newPlayer playerName playerCoords)
gameLoop :: Member (State GameState) e => Action -> Eff e RoundResult
gameLoop (Go dir) = do
gs <- get
let direction = actionToDirection dir
thePlayer = player gs
theBoard = board gs
when (canPlayerMove direction theBoard thePlayer) $ modify $ \st ->
let (newPos, newBoard) = move direction (position thePlayer) theBoard
in st { board = newBoard, player = thePlayer {position = newPos}}
return Continue
where actionToDirection North = north
actionToDirection South = south
actionToDirection West = west
actionToDirection East = east
gameLoop (Meta Quit) =
return GameOver
gameLoop _ =
return Continue
| tr00per/roguelike0 | src/Roguelike/Game.hs | bsd-2-clause | 1,620 | 0 | 15 | 424 | 401 | 211 | 190 | 42 | 4 |
-- |
-- Module: $HEADER$
-- Description: Class for constructing characters from ASCI values.
-- Copyright: (c) 2013 Peter Trsko
-- License: BSD3
--
-- Maintainer: [email protected]
-- Stability: stable
-- Portability: portable
--
-- Class for constructing characters from ASCI values. This allows to abstract
-- from actual character implementation and as a consequence it also doesn't
-- dictate any string\/text implementation.
module Text.Pwgen.FromAscii.Class (FromAscii(..))
where
import Data.Char (chr)
import Data.Word (Word8)
-- | Class of things that can be constructed from ASCI value of characters.
class FromAscii a where
-- | Construct character/sequence from ASCI value.
fromAscii :: Word8 -> a
instance FromAscii Char where
fromAscii = chr . fromIntegral
{-# INLINE fromAscii #-}
-- | Implemented as identity.
instance FromAscii Word8 where
fromAscii = id
{-# INLINE fromAscii #-}
-- | Constructs a singleton instance of list.
instance FromAscii a => FromAscii [a] where
fromAscii = (: []) . fromAscii
{-# INLINE fromAscii #-}
| trskop/hpwgen | src/Text/Pwgen/FromAscii/Class.hs | bsd-3-clause | 1,109 | 0 | 8 | 220 | 138 | 87 | 51 | 14 | 0 |
module Data.SSTable.Reader
( openReader
, closeReader
, withReader
, scan
, leastUpperBound
) where
import qualified Data.ByteString as B
import System.IO (openFile, hSeek, hClose, Handle, SeekMode(..), IOMode(..))
import System.IO.Unsafe (unsafeInterleaveIO)
import Control.Monad (when, liftM)
import Data.Array (Array, Ix, bounds, (!))
import Data.Array.IO
import Data.Int
import Text.Printf (printf)
import qualified Data.SSTable
import Data.SSTable (Index, IndexEntry)
import Data.SSTable.Packing
type IOIndex = IOArray Int IndexEntry
data Reader = Reader
{ handle :: Handle
, index :: Index }
openReader :: String -> IO Reader
openReader path = do
h <- openFile path ReadMode
version <- hGet32 h
when (version /= Data.SSTable.version) $
error $ printf "mismatched versions (expecting %d, got %d)"
Data.SSTable.version version
-- Fetch the index.
numBlocks <- hGet32 h >>= return . fromIntegral
indexOffset <- hGet64 h >>= return . fromIntegral
hSeek h AbsoluteSeek indexOffset
-- Read the index as an array.
index <- newArray_ (1, numBlocks) :: IO IOIndex
copy 1 (numBlocks + 1) h index
-- We don't want to copy the whole index once more, hence the unsafe
-- freeze.
liftM (Reader h) $ unsafeFreeze index
where
copy i n h index
| i == n = return ()
| otherwise = do
keyLen <- hGet32 h
off <- hGet64 h
blockLen <- hGet32 h
key <- B.hGet h (fromIntegral keyLen)
writeArray index i (key, fromIntegral off, fromIntegral blockLen)
copy (i + 1) n h index
closeReader :: Reader -> IO ()
closeReader (Reader h _) = hClose h
withReader :: String -> (Reader -> IO a) -> IO a
withReader path f = do
reader <- openReader path
a <- f reader
closeReader reader
return a
scan :: Reader -> B.ByteString -> IO [(B.ByteString, B.ByteString)]
scan (Reader h index) begin =
case leastUpperBound index begin of
Just n -> scan' n
Nothing -> return []
where
scan' n
| n > upperIndexBound = return []
| otherwise = do
block <- fetch n
scanBlock n block
-- TODO: this might be nicer with continuations.
scanBlock n block
| B.null block = scan' $ n + 1
| otherwise = do
let (header, rest) = B.splitAt 8 block
(keyLenBytes, entryLenBytes) = B.splitAt 4 header
keyLen = unpackInt keyLenBytes
entryLen = unpackInt entryLenBytes
(bytes, block') = B.splitAt (keyLen + entryLen) rest
(key, entry) = B.splitAt keyLen bytes
if key < begin -- we may need to skip initial entries
then scanBlock n block'
else do
next <- unsafeInterleaveIO $ scanBlock n block'
return $ (key, entry):next
fetch n = do
-- (a bounds check has already been performed here)
let (_, off, len) = index!n
hSeek h AbsoluteSeek $ fromIntegral off
B.hGet h $ fromIntegral len
(_, upperIndexBound) = bounds index
unpackInt = fromIntegral . unpack32 . B.unpack
-- | /O(log n) in index size./ Find the smallest value in the index
-- greater than or equal to the given key using binary search. We
-- don't specialize the type to 'Index' in order to retain
-- compatibility with our quickcheck tests.
leastUpperBound :: Index -> B.ByteString -> Maybe Int
leastUpperBound index key =
if lowerBound > upperBound
then Nothing
else go indexBounds
where
indexBounds@(lowerBound, upperBound) = bounds index
go (lower, upper)
-- Standard binary search. Keep in mind the bounds are
-- inclusive.
| key == this = Just mid
| key < this && mid /= lower = go (lower, mid - 1)
| key > this && mid /= upper = go (mid + 1, upper)
-- We failed to descend (and thus to find our exact
-- value). `lower' and `upper' are individually either a bounds
-- on our search key, or they are the extremes of the index
-- values.
--
-- Thus to find our least upper bound:
--
-- If the key is greater than our current value and we are not
-- at the table extreme, choose our current upper bound.
| key > this && mid /= upperBound = Just $ mid + 1
-- If the key is smaller than our current value, select our
-- current value (the next value down either does not exist or
-- is smaller than our key by implication of the bounds)
| key < this = Just mid
-- Otherwise we fail our search. This happens if the largest
-- value in the table is smaller than our search key.
| otherwise = Nothing
where
mid = lower + (upper - lower) `div` 2
(this, off, _) = index!mid
| mariusae/sstable | src/Data/SSTable/Reader.hs | bsd-3-clause | 4,864 | 0 | 15 | 1,435 | 1,305 | 670 | 635 | 96 | 3 |
module App.Layouts.Default where
import Config.Master
import Turbinado.Layout
import Turbinado.View
import Turbinado.View.Helpers
import Control.Monad.Trans
import Data.List
import qualified Network.HTTP as HTTP
import Network.URI as URI
markup = <html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>A poor-man's blog</title>
<meta name="keywords" content="turbinado, haskell, mvc, model, view, controller, ruby, rails" > </meta>
<meta name="description" content="This is a small Blog application written in Turbinado, which is a Model-View-Controller-ish web framework written in Haskell." > </meta>
<% styleSheet "default" "screen"%>
</head>
<body>
----start header --------------
<div id="header">
<div id="menu">
<ul>
<li class="current_page_item"><a href="/Posts/Index"><span class="numbertxt">01 </span>Homepage</a></li>
<li><a href="/Posts/About"><span class="numbertxt">02 </span>About</a></li>
<li class="last"> <a href="/Manage/Home"><span class="numbertxt">03 </span>Manage</a></li>
</ul>
</div>
</div>
<div id="logo">
<h1><a href="#"> A poor-man's</a></h1>
<h1> blog</h1>
</div>
--------end header-------------
--------star page--------------
<div id="page">
<div id="content">
<% insertDefaultView %>
</div>
--- end content --
-- start sidebar --
<div id="sidebar">
<ul>
<li id="search">
<h2>Search</h2>
<form method="post" action="/Posts/Search" >
<fieldset>
<input type="text" id="s" name="s" value=""> </input>
<input type="submit" value="Search" > </input>
</fieldset>
</form>
</li>
</ul>
</div>
-- end sidebar --
<div style="clear: both;"> </div>
</div>
--end page------
-- start footer --
<div id="footer">
<div id="footer-wrap">
<p id="legal">(c) 2009 A poor-man's blog. Design by <a href="http://www.freecsstemplates.org/">Free CSS Templates</a>.</p>
</div>
</div>
-- end footer --
</body>
</html>
-- SPLIT HERE
markup :: View XML
| abuiles/turbinado-blog | tmp/compiled/App/Layouts/Default.hs | bsd-3-clause | 2,503 | 147 | 82 | 811 | 838 | 421 | 417 | -1 | -1 |
import Common.Numbers.Primes (primes')
main = print (primes' !! 10000)
| foreverbell/project-euler-solutions | src/7.hs | bsd-3-clause | 72 | 0 | 7 | 10 | 27 | 15 | 12 | 2 | 1 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
module DecisionTests where
import Control.Applicative
import Control.Lens
import Control.Monad.Catch.Pure
import Control.Monad.Reader
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy as LB
import qualified Data.HashMap.Strict as HashMap
import Data.Monoid
import Network.HTTP.Date
import Network.HTTP.Media
import Network.HTTP.Types
import Test.Tasty
import Test.Tasty.HUnit
import Webcrank
import Webcrank.Internal
import Webcrank.Internal.DecisionCore
import Webcrank.Internal.Halt
import TestServerAPI
decisionTests :: TestTree
decisionTests = testGroup "Decision tests"
[ b13Tests
, b12Tests
, b11Tests
, b10Tests
, b9Tests
, b8Tests
, b7Tests
, b6Tests
, b5Tests
, b4Tests
, b3Tests
, c3Tests
, c4Tests
, d4Tests
, d5Tests
, e5Tests
, e6Tests
, f6Tests
, f7Tests
, g7Tests
, g8Tests
, g9Tests
, g11Tests
, h7Tests
, h10Tests
, h11Tests
, h12Tests
, i4Tests
, i7Tests
, i12Tests
, i13Tests
, j18Tests
, k5Tests
, k7Tests
, k13Tests
, l5Tests
, l7Tests
, l13Tests
, l14Tests
, l15Tests
, l17Tests
, m5Tests
, m7Tests
, m16Tests
, m20Tests
, n5Tests
, n11Tests
, n16Tests
, o14Tests
, o16Tests
, o18Tests
, o20Tests
, p3Tests
, p11Tests
]
b13Tests :: TestTree
b13Tests = decisionTestGroup "b13" "Service available?"
[ testCase "True ==> b12" $
after' b13 resource req @?= Decision' "b12"
, testCase "False ==> 503 Service Unavailable" $
let r = resource { serviceAvailable = return False }
in after' b13 r req @?= error' serviceUnavailable503
]
b12Tests :: TestTree
b12Tests = decisionTestGroup "b12" "Known method?" ts where
ts = mk <$> ms
mk (m, r) = testCase (mconcat [show m, " ==> ", show r]) $
after' b12 resource (req { reqMethod = m }) @?= r
ms = ("QWERTY", error' notImplemented501) : ((, Decision' "b11") <$> [methodGet, methodHead, methodPost, methodPut, methodDelete, methodTrace, methodConnect, methodOptions])
b11Tests :: TestTree
b11Tests = decisionTestGroup "b11" "URI too long?"
[ testCase "True ==> 414 Request-URI Too Long" $
let r = resource { uriTooLong = return True }
in after' b11 r req @?= error' requestURITooLong414
, testCase "False ==> b11" $
after' b11 resource req @?= Decision' "b10"
]
b10Tests :: TestTree
b10Tests = decisionTestGroup "b10" "Method allowed?"
[ testCase "True ==> b9" $
after' b10 resource req @?= Decision' "b9"
, testCase "False ==> 405 Method Not Allowed" $
let rq = req { reqMethod = methodPost }
in afterHdrs b10 resource rq @?=
(error' methodNotAllowed405, HashMap.singleton hAllow ["GET, HEAD"])
]
b9Tests :: TestTree
b9Tests = decisionTestGroup "b9" "Malformed?"
[ testCase "True ==> 400 Malformed Request" $
let r = resource { malformedRequest = return True }
in after' b9 r req @?= error' badRequest400
, testCase "False ==> b8" $
after' b9 resource req @?= Decision' "b8"
]
b8Tests :: TestTree
b8Tests = decisionTestGroup "b8" "Authorized?"
[ testCase "True ==> b7" $
after' b8 resource req @?= Decision' "b7"
, testCase "False ==> 401 Unauthorized" $
let r = resource { isAuthorized = return $ Unauthorized "Basic realm=\"W\"" }
in afterHdrs b8 r req @?=
(error' unauthorized401, HashMap.singleton hWWWAuthenticate ["Basic realm=\"W\""])
]
b7Tests :: TestTree
b7Tests = decisionTestGroup "b7" "Forbidden?"
[ testCase "True ==> 403 Forbidden" $
let r = resource { forbidden = return True }
in after' b7 r req @?= error' forbidden403
, testCase "False ==> b6" $
after' b7 resource req @?= Decision' "b6"
]
b6Tests :: TestTree
b6Tests = decisionTestGroup "b6" "Okay Content-* Headers?"
[ testCase "True ==> b5" $
after' b6 resource req @?= Decision' "b5"
, testCase "False ==> 501 Not Implemented" $
let r = resource { validContentHeaders = return False }
in after' b6 r req @?= error' notImplemented501
]
b5Tests :: TestTree
b5Tests = decisionTestGroup "b5" "Known Content-Type?"
[ testCase "True ==> b4" $
after' b5 resource req @?= Decision' "b4"
, testCase "False ==> 415 Unsupported Media Type" $
let r = resource { knownContentType = return False }
in after' b5 r req @?= error' unsupportedMediaType415
]
b4Tests :: TestTree
b4Tests = decisionTestGroup "b4" "Req Entity Too Large?"
[ testCase "True ==> b3" $
after' b4 resource req @?= Decision' "b3"
, testCase "False ==> 413 Request Entity Too Large" $
let r = resource { validEntityLength = return False }
in after' b4 r req @?= error' requestEntityTooLarge413
]
b3Tests :: TestTree
b3Tests = decisionTestGroup "b3" "OPTIONS?"
[ testCase "True ==> 200 Ok" $
let
r = resource { options = return [("X-Tra", "Webcrank")] }
rq = req { reqMethod = methodOptions }
in afterHdrs b3 r rq @?= (Done' ok200, HashMap.singleton "X-Tra" ["Webcrank"])
, testCase "False ==> c3" $
after' b3 resource req @?= Decision' "c3"
]
c3Tests :: TestTree
c3Tests = decisionTestGroup "c3" "Accept exists?"
[ testCase "True ==> c4 + default media type" $
let rq = req { reqHeaders = HashMap.singleton hAccept ["text/html"] }
in afterMediaType c3 resource rq @?= (Decision' "c4", "application" // "octet-stream")
, testCase "False ==> c4 w/o media type" $
let
r = resource { contentTypesProvided = return [("text" // "html", return "")] }
in afterMediaType c3 r req @?= (Decision' "d4", "text" // "html")
] where
afterMediaType s r rq = case after s r rq of
(d, rd) -> (d, _reqDataRespMediaType rd)
c4Tests :: TestTree
c4Tests = decisionTestGroup "c4" "Acceptable media type available?"
[ testCase "True ==> d4" $
let r = resource { contentTypesProvided = return [("text" // "html", return "")] }
in after' (c4 "text/html") r req @?= Decision' "d4"
, testCase "False ==> 406 Not Acceptable" $
after' (c4 "text/html") resource req @?= Error' notAcceptable406 "No acceptable media type available"
]
d4Tests :: TestTree
d4Tests = decisionTestGroup "d4" "Accept-Language exists?"
[ testCase "True ==> d5" $
let rq = req { reqHeaders = HashMap.singleton hAcceptLanguage ["en"] }
in after' d4 resource rq @?= Decision' "d5"
, testCase "False ==> e5" $
after' d4 resource req @?= Decision' "e5"
]
-- just a placeholder
d5Tests :: TestTree
d5Tests = decisionTestGroup "d5" "Acceptable language available?"
[ testCase "Always ==> e5" $
after' (d5 "en") resource req @?= Decision' "e5"
]
e5Tests :: TestTree
e5Tests = decisionTestGroup "e5" "Accept-Charset exists?"
[ testCase "True ==> e6" $
let rq = req { reqHeaders = HashMap.singleton hAcceptCharset ["utf-8"] }
in after' e5 resource rq @?= Decision' "e6"
, testCase "False + no charsets provided ==> f6 w/o charset" $
afterCharset e5 resource req @?= (Decision' "f6", Nothing)
, testCase "False + charset provided ==> f6 + charset" $
let r = resource { charsetsProvided = provideCharsets $ return ("utf-8", id) }
in afterCharset e5 r req @?= (Decision' "f6", Just "utf-8")
]
e6Tests :: TestTree
e6Tests = decisionTestGroup "e6" "Acceptable Charset available?"
[ testCase "True ==> f6" $
let r = resource { charsetsProvided = provideCharsets $ return ("utf-8", id) }
in afterCharset (e6 "utf-8") r req @?= (Decision' "f6", Just "utf-8")
, testCase "no charsets provided ==> f6 w/o charset" $
afterCharset (e6 "utf-8") resource req @?= (Decision' "f6", Nothing)
, testCase "False ==> 406 Not Acceptable" $
let r = resource { charsetsProvided = provideCharsets $ return ("wtf-9", id) }
in after' (e6 "utf-8") r req @?= Error' notAcceptable406 "No acceptable charset available"
]
f6Tests :: TestTree
f6Tests = decisionTestGroup "f6" "Accept-Encoding exists?"
[ testCase "True ==> f7" $
let rq = req { reqHeaders = HashMap.singleton hAcceptEncoding ["gzip"] }
in after' f6 resource rq @?= Decision' "f7"
, testCase "False ==> g7" $
after' f6 resource req @?= Decision' "g7"
]
f7Tests :: TestTree
f7Tests = decisionTestGroup "f7" "Acceptable encoding available?"
[ testCase "True ==> g7 + encoding" $
let r = resource { encodingsProvided = return [("gzip", id)] }
in afterEnc (f7 "gzip") r req @?= (Decision' "g7", Just "gzip")
, testCase "False ==> g7 + identity" $
afterEnc (f7 "gzip") resource req @?= (Decision' "g7", Nothing)
] where
afterEnc s r rq = case after s r rq of
(d, rd) -> (d, _reqDataRespEncoding rd)
g7Tests :: TestTree
g7Tests = decisionTestGroup "g7" "Resource exists?"
[ testCase "True ==> g8" $
after' g7 resource req @?= Decision' "g8"
, testCase "False ==> h7" $
let r = resource { resourceExists = return False }
in after' g7 r req @?= Decision' "h7"
]
g8Tests :: TestTree
g8Tests = decisionTestGroup "g8" "If-Match exists?"
[ testCase "True ==> g9" $
let rq = req { reqHeaders = HashMap.singleton hIfMatch ["webcrank"] }
in after' g8 resource rq @?= Decision' "g9"
, testCase "False ==> h10" $
after' g8 resource req @?= Decision' "h10"
]
g9Tests :: TestTree
g9Tests = decisionTestGroup "g9" "If-Match: * exists?"
[ testCase "True ==> h10" $
after' (g9 "*") resource req @?= Decision' "h10"
, testCase "False ==> g11" $
let rq = req { reqHeaders = HashMap.singleton hIfMatch ["webcrank"] }
in after' (g9 "webcrank") resource rq @?= Decision' "g11"
]
g11Tests :: TestTree
g11Tests = decisionTestGroup "g11" "ETag in If-Match?"
[ testCase "True ==> h10" $
let r = resource { generateETag = return $ StrongETag "webcrank" }
in after' (g11 "\"webcrank\"") r req @?= Decision' "h10"
, testCase "False (no ETag) ==> 412 Precondition Failed" $
after' (g11 "\"webcrank\"") resource req @?= error' preconditionFailed412
, testCase "False (mismatch ETag) ==> 412 Precondition Failed" $
let r = resource { generateETag = return $ StrongETag "webcrank123" }
in after' (g11 "\"webcrank456\"") r req @?= error' preconditionFailed412
]
h7Tests :: TestTree
h7Tests = decisionTestGroup "h7" "If-Match exists? (no existing resource)"
[ testCase "True ==> 412 Precondition Failed" $
let rq = req { reqHeaders = HashMap.singleton hIfMatch ["webcrank"] }
in after' h7 resource rq @?= error' preconditionFailed412
, testCase "False ==> i7" $
after' h7 resource req @?= Decision' "i7"
]
h10Tests :: TestTree
h10Tests = decisionTestGroup "h10" "If-Unmodified-Since exists?"
[ testCase "True ==> h11" $
let rq = req { reqHeaders = HashMap.singleton hIfUnmodifiedSince [dateStr] }
in after' h10 resource rq @?= Decision' "h11"
, testCase "False ==> i12" $
after' h10 resource req @?= Decision' "i12"
]
h11Tests :: TestTree
h11Tests = decisionTestGroup "h11" "If-Unmodified-Since is valid date?"
[ testCase "True ==> h12" $
after' (h11 dateStr) resource req @?= Decision' "h12"
, testCase "False ==> i12" $
after' (h11 "not a date") resource req @?= Decision' "i12"
]
h12Tests :: TestTree
h12Tests = decisionTestGroup "h12" "Last-Modified > If-Unmodified-Since?"
[ testCase "True ==> 412 Precondition Failed" $
after' (h12 $ date { hdDay = 10 }) r req @?= error' preconditionFailed412
, testCase "False ==> i12" $
after' (h12 $ date { hdDay = 20 }) r req @?= Decision' "i12"
] where
r = resource { lastModified = return date }
i4Tests :: TestTree
i4Tests = decisionTestGroup "i4" "Moved permanently? (apply PUT to different URI)"
[ testCase "True ==> 301 Moved Permanently" $
let
loc = "http://example.com/abc"
r = resource { movedPermanently = return loc }
in afterHdrs i4 r req @?= (Done' movedPermanently301, HashMap.singleton hLocation [loc])
, testCase "False ==> p3" $
after' i4 resource req @?= Decision' "p3"
]
i7Tests :: TestTree
i7Tests = decisionTestGroup "i7" "PUT?"
[ testCase "True ==> i4" $
let rq = req { reqMethod = methodPut }
in after' i7 resource rq @?= Decision' "i4"
, testCase "False ==> k7" $
after' i7 resource req @?= Decision' "k7"
]
i12Tests :: TestTree
i12Tests = decisionTestGroup "i12" "If-None-Match exists?"
[ testCase "True ==> i13" $
let rq = req { reqHeaders = HashMap.singleton hIfNoneMatch ["webcrank"] }
in after' i12 resource rq @?= Decision' "i13"
, testCase "False ==> l13" $
after' i12 resource req @?= Decision' "l13"
]
i13Tests :: TestTree
i13Tests = decisionTestGroup "i13" "If-None-Match: * exists?"
[ testCase "True ==> j18" $
after' (i13 "*") resource req @?= Decision' "j18"
, testCase "False ==> k13" $
after' (i13 "webcrank") resource req @?= Decision' "k13"
]
j18Tests :: TestTree
j18Tests = decisionTestGroup "j18" "GET or HEAD? (resource exists)"
[ testCase "True (GET) ==> 304 Not Modified" $
after' j18 resource req @?= Done' notModified304
, testCase "True (HEAD) ==> 304 Not Modified" $
let rq = req { reqMethod = methodHead }
in after' j18 resource rq @?= Done' notModified304
, testCase "False ==> 412 Precondition Failed" $
let rq = req { reqMethod = methodPost }
in after' j18 resource rq @?= error' preconditionFailed412
]
k5Tests :: TestTree
k5Tests = decisionTestGroup "k5" "Moved permanently? (non-PUT variant)"
[ testCase "True ==> 301 Moved Permanently" $
let
uri = "http://example.com/abc"
r = resource { movedPermanently = return uri }
in afterHdrs k5 r req @?= (Done' movedPermanently301, HashMap.singleton hLocation [uri])
, testCase "False ==> l5" $
after' k5 resource req @?= Decision' "l5"
]
k7Tests :: TestTree
k7Tests = decisionTestGroup "k7" "Previously existed?"
[ testCase "True ==> k5" $
let r = resource { previouslyExisted = return True }
in after' k7 r req @?= Decision' "k5"
, testCase "False ==> l7" $
after' k7 resource req @?= Decision' "l7"
]
k13Tests :: TestTree
k13Tests = decisionTestGroup "k13" "ETag in If-None-Match?"
[ testCase "True ==> j18" $
let r = resource { generateETag = return $ StrongETag "webcrank" }
in after' (k13 "\"webcrank\"") r req @?= Decision' "j18"
, testCase "False (no ETag) ==> l13" $
after' (k13 "\"webcrank\"") resource req @?= Decision' "l13"
, testCase "False (mismatch ETag) ==> l13" $
let r = resource { generateETag = return $ StrongETag "webcrank123" }
in after' (k13 "\"webcrank456\"") r req @?= Decision' "l13"
]
l5Tests :: TestTree
l5Tests = decisionTestGroup "l5" "Moved temporarily?"
[ testCase "True ==> 307 Moved Temporarily" $
let
uri = "http://example.com/abc"
r = resource { movedTemporarily = return uri }
in afterHdrs l5 r req @?= (Done' temporaryRedirect307, HashMap.singleton hLocation [uri])
, testCase "False ==> m5" $
after' l5 resource req @?= Decision' "m5"
]
l7Tests :: TestTree
l7Tests = decisionTestGroup "l7" "POST? (no existing resource)"
[ testCase "True ==> m7" $
let rq = req { reqMethod = methodPost }
in after' l7 resource rq @?= Decision' "m7"
, testCase "False ==> 404 Not Found" $
after' l7 resource req @?= error' notFound404
]
l13Tests :: TestTree
l13Tests = decisionTestGroup "l17" "If-Modified-Since exists?"
[ testCase "True ==> l14" $
let rq = req { reqHeaders = HashMap.singleton hIfModifiedSince [dateStr] }
in after' l13 resource rq @?= Decision' "l14"
, testCase "False ==> m16" $
after' l13 resource req @?= Decision' "m16"
]
l14Tests :: TestTree
l14Tests = decisionTestGroup "l14" "If-Modified-Since is a valid date?"
[ testCase "True ==> l15" $
after' (l14 dateStr) resource req @?= Decision' "l15"
, testCase "False ==> m16" $
after' (l14 "not a date") resource req @?= Decision' "m16"
]
l15Tests :: TestTree
l15Tests = decisionTestGroup "l15" "If-Modified-Since > Now?"
[ testCase "True ==> m16" $
let rq = req { reqTime = date { hdDay = 10 } }
in after' (l15 date) resource rq @?= Decision' "m16"
, testCase "False ==> l17" $
after' (l15 date) resource req @?= Decision' "l17"
]
l17Tests :: TestTree
l17Tests = decisionTestGroup "l17" "Last-Modified > If-Modified-Since?"
[ testCase "True ==> m16" $
let r = resource { lastModified = return $ date { hdDay = 20 } }
in after' (l17 date) r req @?= Decision' "m16"
, testCase "No last modified ==> m16" $
after' (l17 date) resource req @?= Decision' "m16"
, testCase "False ==> 304 Not Modified" $
let r = resource { lastModified = return $ date { hdDay = 10 } }
in after' (l17 date) r req @?= Done' notModified304
]
m5Tests :: TestTree
m5Tests = decisionTestGroup "m5" "POST? (resource previously existed)"
[ testCase "True ==> n5" $
let rq = req { reqMethod = methodPost }
in after' m5 resource rq @?= Decision' "n5"
, testCase "False ==> 410 Gone" $
after' m5 resource req @?= error' gone410
]
m7Tests :: TestTree
m7Tests = decisionTestGroup "m7" "Server allows POST to missing resource?"
[ testCase "True ==> n11" $
let r = resource { allowMissingPost = return True }
in after' m7 r req @?= Decision' "n11"
, testCase "False ==> 404 Not Found" $
after' m7 resource req @?= error' notFound404
]
m16Tests :: TestTree
m16Tests = decisionTestGroup "m16" "DELETE?"
[ testCase "True ==> m20" $
let rq = req { reqMethod = methodDelete }
in after' m16 resource rq @?= Decision' "m20"
, testCase "False ==> n16" $
after' m16 resource req @?= Decision' "n16"
]
m20Tests :: TestTree
m20Tests = decisionTestGroup "m20" "Delete enacted?"
[ testCase "True + completed ==> n11" $
let r = resource { deleteResource = return True }
in after' m20 r req @?= Decision' "n11"
, testCase "True + not completed ==> 202 Accepted" $
let r = resource { deleteResource = return True, deleteCompleted = return False }
in after' m20 r req @?= Done' accepted202
, testCase "False ==> 500 Internal Server Error" $
after' m20 resource req @?= error' internalServerError500
]
n5Tests :: TestTree
n5Tests = decisionTestGroup "n5" "Server allows POST to missing resource? (resource did not exist previously)"
[ testCase "True ==> n11" $
let r = resource { allowMissingPost = return True }
in after' n5 r req @?= Decision' "n11"
, testCase "False ==> 410 Gone" $
after' n5 resource req @?= error' gone410
]
n11Tests :: TestTree
n11Tests = decisionTestGroup "n11" "Redirect?"
[ testCase "True + created + content type accepted ==> 303 See Other" $
let
r = resource
{ postAction = return . PostCreateRedir $ ["webcrank"]
, contentTypesAccepted = return [("text" // "html", return ())]
}
rq = req { reqHeaders = HashMap.singleton hContentType ["text/html"] }
aft = case after n11 r rq of
(d, rd) -> (d, HashMap.lookup hLocation $_reqDataRespHeaders rd, _reqDataDispPath rd)
in aft @?= (Done' seeOther303, Just ["http://example.com/webcrank"], ["webcrank"])
, testCase "True + created + no content type accepted ==> 415 Unsupported Media Type" $
let
r = resource
{ postAction = return . PostCreateRedir $ ["webcrank"]
, contentTypesAccepted = return [("text" // "html", return ())]
}
rq = req { reqHeaders = HashMap.singleton hContentType ["text/plain"] }
in after' n11 r rq @?= error' unsupportedMediaType415
, testCase "True + process ==> 303 See Other" $
let r = resource { postAction = return $ PostProcessRedir $ return "http://example.com/webcrank" }
in afterHdrs n11 r req @?=
(Done' seeOther303, HashMap.singleton hLocation ["http://example.com/webcrank"])
, testCase "False + created + content type accepted ==> p11" $
let
r = resource
{ postAction = return . PostCreate $ ["webcrank"]
, contentTypesAccepted = return [("text" // "html", return ())]
}
rq = req { reqHeaders = HashMap.singleton hContentType ["text/html"] }
in afterHdrs n11 r rq @?=
(Decision' "p11", HashMap.singleton hLocation ["http://example.com/webcrank"])
, testCase "False + created + no content type accepted ==> p11" $
let
r = resource
{ postAction = return . PostCreate $ ["webcrank"]
, contentTypesAccepted = return [("text" // "html", return ())]
}
rq = req { reqHeaders = HashMap.singleton hContentType ["text/plain"] }
in afterHdrs n11 r rq @?=
(error' unsupportedMediaType415, HashMap.singleton hLocation ["http://example.com/webcrank"])
, testCase "False + process ==> p11" $
let r = resource { postAction = return $ PostProcess $ return () }
in after' n11 r req @?= Decision' "p11"
]
n16Tests :: TestTree
n16Tests = decisionTestGroup "n16" "POST? (resource exists)"
[ testCase "True ==> n11" $
let rq = req { reqMethod = methodPost }
in after' n16 resource rq @?= Decision' "n11"
, testCase "False ==> o16" $
after' n16 resource req @?= Decision' "o16"
]
o14Tests :: TestTree
o14Tests = decisionTestGroup "o14" "Conflict? (resource exists)"
[ testCase "True ==> 409 Conflict" $
let r = resource { isConflict = return True }
in after' o14 r req @?= error' conflict409
, testCase "False + no acceptable content type ==> 415 Unsupported Media Type" $
after' o14 resource req @?= error' unsupportedMediaType415
, testCase "False + acceptable content type ==> p11" $
let
r = resource { contentTypesAccepted = return [("text" // "html", return ())] }
rq = req { reqHeaders = HashMap.singleton hContentType ["text/html"] }
in after' o14 r rq @?= Decision' "p11"
]
o16Tests :: TestTree
o16Tests = decisionTestGroup "o16" "PUT? (resource exists)"
[ testCase "True ==> o14" $
let rq = req { reqMethod = methodPut }
in after' o16 resource rq @?= Decision' "o14"
, testCase "False ==> o18" $
after' o16 resource req @?= Decision' "o18"
]
o18Tests :: TestTree
o18Tests = decisionTestGroup "o18" "Multiple representations?"
[ testCase "True ==> 300 Multiple Choices" $
let r = resource { multipleChoices = return True }
in after' o18 r req @?= Done' multipleChoices300
, testCase "False ==> 200 Ok" $
after' o18 resource req @?= Done' ok200
]
o20Tests :: TestTree
o20Tests = decisionTestGroup "o20" "Response includes an entity?"
[ testCase "True ==> o18" $
let
body rd = rd { _reqDataRespBody = Just "webcrank" }
aft = fst $ afterWith o20 resource req body
in aft @?= Decision' "o18"
, testCase "False ==> 204 No Content" $
after' o20 resource req @?= Done' noContent204
]
p3Tests :: TestTree
p3Tests = decisionTestGroup "p3" "Conflict? (resource doesn't exist)"
[ testCase "True ==> 409 Conflict" $
let r = resource { isConflict = return True }
in after' p3 r req @?= error' conflict409
, testCase "False + no acceptable content types ==> 415 Unsupported Media Type" $
after' p3 resource req @?= error' unsupportedMediaType415
, testCase "False + acceptable content type ==> p11" $
let
r = resource { contentTypesAccepted = return [("text" // "html", return ())] }
rq = req { reqHeaders = HashMap.singleton hContentType ["text/html"] }
in after' p3 r rq @?= Decision' "p11"
]
p11Tests :: TestTree
p11Tests = decisionTestGroup "p11" "New resource?"
[ testCase "True ==> 201 Created" $
let
loc rd = rd { _reqDataRespHeaders = HashMap.singleton hLocation ["http://example.com/abc"] }
aft = fst $ afterWith p11 resource req loc
in aft @?= Done' created201
, testCase "False ==> o20" $
after' p11 resource req @?= Decision' "o20"
]
decisionTestGroup :: TestName -> TestName -> [TestTree] -> TestTree
decisionTestGroup s n = testGroup (s <> ". " <> n)
date :: HTTPDate
date = defaultHTTPDate
{ hdYear = 1994
, hdMonth = 11
, hdDay = 15
, hdHour = 8
, hdMinute = 12
, hdSecond = 31
, hdWkday = 2
}
dateStr :: ByteString
dateStr = formatHTTPDate date
after
:: FlowChart (HaltT TestCrank) Status
-> Resource TestCrank
-> Req
-> (Decision', ReqData)
after s r rq = afterWith s r rq id
afterWith
:: FlowChart (HaltT TestCrank) Status
-> Resource TestCrank
-> Req
-> (ReqData -> ReqData)
-> (Decision', ReqData)
afterWith s r rq f = run where
run = case runReader (runCatchT $ step s r f) rq of
Left e -> error $ show e
Right a -> a
step
:: FlowChart (HaltT TestCrank) Status
-> Resource TestCrank
-> (ReqData -> ReqData)
-> TestState (Decision', ReqData)
step s r f = do
let rd = f newReqData
case s of
Decision _ a -> runTestCrank (runHaltT a) r rd >>= \case
(Left (Halt sc), rd', _) -> return (Done' sc, rd')
(Left (Error sc e), rd', _) -> return (Error' sc e, rd')
(Right (Decision l _), rd', _) -> return (Decision' l, rd')
(Right (Done a'), rd', _) -> runTestCrank (runHaltT a') r rd' <&> \case
(Left (Halt sc), rd'', _) -> (Done' sc, rd'')
(Left (Error sc e), rd'', _) -> (Error' sc e, rd'')
(Right sc, rd'', _) -> (Done' sc, rd'')
Done _ -> error "can't look past end state of flow chart"
after'
:: FlowChart (HaltT TestCrank) Status
-> Resource TestCrank
-> Req
-> Decision'
after' s r = fst . after s r
afterHdrs
:: FlowChart (HaltT TestCrank) Status
-> Resource TestCrank
-> Req
-> (Decision', HeadersMap)
afterHdrs s r rq = case after s r rq of
(d, rd) -> (d, _reqDataRespHeaders rd)
afterCharset
:: FlowChart (HaltT TestCrank) Status
-> Resource TestCrank
-> Req
-> (Decision', Maybe Charset)
afterCharset s r rq = case after s r rq of
(d, rd) -> (d, _reqDataRespCharset rd)
data Decision'
= Error' Status LB.ByteString
| Done' Status
| Decision' String
deriving Eq
error' :: Status -> Decision'
error' s = Error' s (LB.fromStrict $ statusMessage s)
instance Show Decision' where
show = \case
Error' sc e -> mconcat
[ show $ statusCode sc
, " "
, B.unpack $ statusMessage sc
, " - "
, show . B.unpack . LB.toStrict $ e
]
Done' sc -> mconcat [show $ statusCode sc, " ", B.unpack $ statusMessage sc ]
Decision' l -> l
| webcrank/webcrank.hs | test/DecisionTests.hs | bsd-3-clause | 26,589 | 0 | 21 | 6,236 | 7,772 | 3,944 | 3,828 | -1 | -1 |
import System.IO (BufferMode(..), hSetBuffering, stdout, stderr)
-- Tests
import Test.Game.Ur as Game.Ur
main :: IO ()
main = do
hSetBuffering stdout LineBuffering
hSetBuffering stderr LineBuffering
_results <- sequence [
Game.Ur.tests
]
pure ()
| taksuyu/game-of-ur | tests/Test.hs | bsd-3-clause | 266 | 0 | 10 | 53 | 90 | 48 | 42 | 9 | 1 |
{-|
Module providing the scotty backend for the digestive-functors library
>{-# LANGUAGE OverloadedStrings #-}
>
>import Web.Scotty
>
>import Text.Digestive
>import Text.Digestive.Scotty
>
>import Control.Applicative ((<$>), (<*>))
>
>data FormData = FormData { field1 :: String
> , field2 :: Integer
> }
>
>testForm :: Monad m => Form String m FormData
>testForm = FormData
> <$> "field1" .: string Nothing
> <*> "field2" .: stringRead "read failed" Nothing
>
>main :: IO ()
>main = scotty 3000 $ do
> get "/" $ do
> setHeader "Content-Type" "text/html"
> raw " <html><body><form enctype='multipart/form-data' method='post'> \
> \ <input type='text' name='test-form.field1'/> \
> \ <input type='text' name='test-form.field2'/> \
> \ <input type='submit'/> \
> \ </form></body></html>"
>
> post "/" $ do
> (view, result) <- runForm "test-form" testForm
> case result of
> Just d -> ... Success! `d` contains constructed FormData.
> _ -> ... Failure! Use `view` variable to access error messages.
-}
module Text.Digestive.Scotty
( runForm
) where
import Control.Monad ( liftM )
import qualified Data.Text as T
import qualified Data.ByteString.Char8 as B
import qualified Data.Text.Lazy as TL
import qualified Web.Scotty.Trans as Scotty
import Network.Wai ( requestMethod )
import Network.Wai.Parse ( fileName )
import Network.HTTP.Types ( methodGet )
import Text.Digestive.Form
import Text.Digestive.Types
import Text.Digestive.View
scottyEnv :: (Monad m, Scotty.ScottyError e) => Env (Scotty.ActionT e m)
scottyEnv path = do
inputs <- parse (TextInput . TL.toStrict) Scotty.params
files <- parse (FileInput . B.unpack . fileName) Scotty.files
return $ inputs ++ files
where parse f = liftM $ map (f . snd) . filter ((== name) . fst)
name = TL.fromStrict . fromPath $ path
-- | Runs a form with the HTTP input provided by Scotty.
runForm :: (Monad m, Scotty.ScottyError e)
=> T.Text -- ^ Name of the form
-> Form v (Scotty.ActionT e m) a -- ^ Form to run
-> (Scotty.ActionT e m) (View v, Maybe a) -- ^ Result
runForm name form = Scotty.request >>= \rq ->
if requestMethod rq == methodGet
then getForm name form >>= \v -> return (v, Nothing)
else postForm name form $ const (return scottyEnv)
| mmartin/digestive-functors-scotty | src/Text/Digestive/Scotty.hs | bsd-3-clause | 2,492 | 0 | 12 | 649 | 424 | 235 | 189 | 28 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
module DataKinds where
data Access = Public | Private deriving (Show, Eq)
data Object (n::Access) = Object Int deriving (Show, Eq)
instance Num (Object n) where
Object x + Object y = Object $ x + y
| notae/haskell-exercise | type/DataKinds.hs | bsd-3-clause | 286 | 0 | 7 | 55 | 94 | 52 | 42 | 8 | 0 |
-- 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 NoRebindableSyntax #-}
{-# LANGUAGE RecordWildCards #-}
module Duckling.Ranking.Generate
( regenAllClassifiers
, regenClassifiers
) where
import qualified Data.HashMap.Strict as HashMap
import qualified Data.HashSet as HashSet
import qualified Data.Text as Text
import Prelude
import Language.Haskell.Exts as F
import Duckling.Dimensions.Types
import Duckling.Lang
import Duckling.Ranking.Train
import Duckling.Ranking.Types
import Duckling.Rules
import Duckling.Testing.Types
import qualified Duckling.Time.DA.Corpus as DATime
import qualified Duckling.Time.DE.Corpus as DETime
import qualified Duckling.Time.EN.Corpus as ENTime
import qualified Duckling.Time.ES.Corpus as ESTime
import qualified Duckling.Time.FR.Corpus as FRTime
import qualified Duckling.Time.GA.Corpus as GATime
import qualified Duckling.Time.HR.Corpus as HRTime
import qualified Duckling.Time.HE.Corpus as HETime
import qualified Duckling.Time.IT.Corpus as ITTime
import qualified Duckling.Time.KO.Corpus as KOTime
import qualified Duckling.Time.NB.Corpus as NBTime
import qualified Duckling.Time.PL.Corpus as PLTime
import qualified Duckling.Time.PT.Corpus as PTTime
import qualified Duckling.Time.RO.Corpus as ROTime
import qualified Duckling.Time.SV.Corpus as SVTime
import qualified Duckling.Time.VI.Corpus as VITime
import qualified Duckling.Time.ZH.Corpus as ZHTime
-- -----------------------------------------------------------------
-- Main
regenAllClassifiers :: IO ()
regenAllClassifiers = mapM_ regenClassifiers [minBound .. maxBound]
-- | Run this function to overwrite the file with Classifiers data
regenClassifiers :: Lang -> IO ()
regenClassifiers lang = do
putStrLn $ "Regenerating " ++ filepath ++ "..."
writeFile filepath $
(headerComment ++) $
prettyPrintWithMode baseMode $ (noLoc <$) m
putStrLn "Done!"
where
filepath = "Duckling/Ranking/Classifiers/" ++ show lang ++ ".hs"
rules = rulesFor lang . HashSet.singleton $ This Time
-- | The trained classifier to write out
classifiers = makeClassifiers rules trainSet
-- | The training set (corpus)
trainSet = case lang of
AR -> (testContext, [])
CS -> (testContext, [])
DA -> DATime.corpus
DE -> DETime.corpus
EN -> ENTime.corpus
ES -> ESTime.corpus
ET -> (testContext, [])
FR -> FRTime.corpus
GA -> GATime.corpus
HR -> HRTime.corpus
HE -> HETime.corpus
ID -> (testContext, [])
IT -> ITTime.corpus
JA -> (testContext, [])
KO -> KOTime.corpus
MY -> (testContext, [])
NB -> NBTime.corpus
NL -> (testContext, [])
PL -> PLTime.corpus
PT -> PTTime.corpus
RO -> ROTime.corpus
RU -> (testContext, [])
SV -> SVTime.corpus
TR -> (testContext, [])
UK -> (testContext, [])
VI -> VITime.corpus
ZH -> ZHTime.corpus
-- Data structure for the module
m = Module () (Just header) pragmas imports decls
-- Declares the top level options pragma
pragmas = [ LanguagePragma () [Ident () "OverloadedStrings"] ]
-- Declares the header for the module
-- "module Duckling.Ranking.Classifiers (classifiers) where"
header = ModuleHead ()
(ModuleName () $ "Duckling.Ranking.Classifiers." ++ show lang)
Nothing $
Just $ ExportSpecList ()
[ EVar () (unQual "classifiers")
]
-- All imports the file will need
imports =
[ genImportModule "Prelude"
, genImportModule "Duckling.Ranking.Types"
, (genImportModule "Data.HashMap.Strict")
{ importQualified = True
, importAs = Just (ModuleName () "HashMap")
}
, genImportModule "Data.String"
]
-- The code body
decls =
[ -- Type Signature
TypeSig () [Ident () "classifiers"] (TyCon () (unQual "Classifiers"))
-- function body
, FunBind ()
[ Match () (Ident () "classifiers") []
(UnGuardedRhs () (genList classifiers)) Nothing
]
]
headerComment :: String
headerComment = "\
\-- Copyright (c) 2016-present, Facebook, Inc.\n\
\-- All rights reserved.\n\
\--\n\
\-- This source code is licensed under the BSD-style license found in the\n\
\-- LICENSE file in the root directory of this source tree. An additional grant\n\
\-- of patent rights can be found in the PATENTS file in the same directory.\n\n\
\-----------------------------------------------------------------\n\
\-- Auto-generated by regenClassifiers\n\
\--\n\
\-- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING\n\
\-- @" ++ "generated\n\
\-----------------------------------------------------------------\n"
-- -----------------------------------------------------------------
-- Source generators
-- | Generates a line for an import
--
-- `genImportModule "Foo.Bar"` spits out:
-- "import Foo.Bar" in the code
genImportModule :: String -> ImportDecl ()
genImportModule name = ImportDecl
{ importAnn = ()
, importModule = ModuleName () name
, importQualified = False
, importSrc = False
, importSafe = False
, importPkg = Nothing
, importAs = Nothing
, importSpecs = Nothing
}
-- | Creates the expression to build the HashMap object
genList :: Classifiers -> Exp ()
genList cs = appFromList $ map genClassifier $ HashMap.toList cs
where
-- "fromList ..."
appFromList exprs = App ()
(Var () (Qual () (ModuleName () "HashMap") (Ident () "fromList")))
(List () exprs)
-- ("name", Classifier { okData ....
genClassifier (name, Classifier{..}) =
let uname = Text.unpack name in
Tuple () Boxed
[ Lit () $ F.String () uname uname
, RecConstr () (unQual "Classifier")
[ genClassData okData "okData"
, genClassData koData "koData"
]
]
-- ClassData { prior = -0.123, unseen = ...
genClassData ClassData{..} name = FieldUpdate () (unQual name) $
RecConstr () (unQual "ClassData")
[ FieldUpdate () (unQual "prior") $ floatSym prior
, FieldUpdate () (unQual "unseen") $ floatSym unseen
, FieldUpdate () (unQual "likelihoods") $
appFromList $ map genLikelihood $ HashMap.toList likelihoods
, FieldUpdate () (unQual "n") $
Lit () (Int () (fromIntegral n) (show n))
]
-- ("feature", 0.0)
genLikelihood (f, d) =
let uf = Text.unpack f in
Tuple () Boxed
[ Lit () $ F.String () uf uf
, floatSym d
]
-- Helper to print out doubles
floatSym :: Double -> Exp ()
floatSym val
| isInfinite val = if val < 0
then NegApp () inf
else inf
| otherwise = Lit () (Frac () (realToFrac val) $ show val)
where
inf = Var () $ unQual "infinity"
-- Helper for unqualified things
unQual :: String -> QName ()
unQual name = UnQual () (Ident () name)
-- -----------------------------------------------------------------
-- Printing helpers
baseMode :: PPHsMode
baseMode = PPHsMode
{ classIndent = 2
, doIndent = 3
, multiIfIndent = 3
, caseIndent = 2
, letIndent = 2
, whereIndent = 2
, onsideIndent = 2
, spacing = True
, layout = PPOffsideRule
, linePragmas = False
}
| rfranek/duckling | exe/Duckling/Ranking/Generate.hs | bsd-3-clause | 7,535 | 0 | 15 | 1,737 | 1,769 | 991 | 778 | 152 | 27 |
module Main where
import JavaScript
main = print "Hello"
| ku-fpg/wakarusa | wakarusa-examples/sunroof-lite/Main.hs | bsd-3-clause | 59 | 0 | 5 | 11 | 15 | 9 | 6 | 3 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE MagicHash #-}
module Blip.Interpreter.HashTable.CacheLine
( cacheLineSearch
, cacheLineSearch2
, cacheLineSearch3
, forwardSearch2
, forwardSearch3
, isCacheLineAligned
, advanceByCacheLineSize
, prefetchRead
, prefetchWrite
, bl_abs#
, sign#
, mask#
, maskw#
) where
import Control.Monad
-- XXX reconsider this?
#define NO_C_SEARCH
#if MIN_VERSION_base(4,4,0)
-- import Control.Monad.ST (ST)
-- import Control.Monad.ST.Unsafe
#else
-- import Control.Monad.ST
#endif
import Blip.Interpreter.HashTable.IntArray (Elem, IntArray)
import qualified Blip.Interpreter.HashTable.IntArray as M
#ifndef NO_C_SEARCH
import Foreign.C.Types
#else
import Data.Bits
import Data.Int
import qualified Data.Vector.Unboxed as U
import GHC.Int
#endif
import Blip.Interpreter.HashTable.Utils
import GHC.Exts
#if __GLASGOW_HASKELL__ >= 707
import GHC.Exts (isTrue#)
#else
isTrue# :: Bool -> Bool
isTrue# = id
#endif
{-# INLINE prefetchRead #-}
{-# INLINE prefetchWrite #-}
prefetchRead :: IntArray -> Int -> IO ()
prefetchWrite :: IntArray -> Int -> IO ()
#ifndef NO_C_SEARCH
foreign import ccall unsafe "line_search"
c_lineSearch :: Ptr a -> CInt -> CUShort -> IO CInt
foreign import ccall unsafe "line_search_2"
c_lineSearch_2 :: Ptr a -> CInt -> CUShort -> CUShort -> IO CInt
foreign import ccall unsafe "line_search_2"
c_lineSearch_3 :: Ptr a -> CInt -> CUShort -> CUShort -> CUShort -> IO CInt
foreign import ccall unsafe "forward_search_2"
c_forwardSearch_2 :: Ptr a -> CInt -> CInt -> CUShort -> CUShort -> IO CInt
foreign import ccall unsafe "forward_search_3"
c_forwardSearch_3 :: Ptr a -> CInt -> CInt -> CUShort -> CUShort -> CUShort
-> IO CInt
foreign import ccall unsafe "prefetch_cacheline_read"
prefetchCacheLine_read :: Ptr a -> CInt -> IO ()
foreign import ccall unsafe "prefetch_cacheline_write"
prefetchCacheLine_write :: Ptr a -> CInt -> IO ()
fI :: (Num b, Integral a) => a -> b
fI = fromIntegral
-- prefetchRead a i = unsafeIOToST $ prefetchCacheLine_read v x
prefetchRead a i = prefetchCacheLine_read v x
where
v = M.toPtr a
x = fI i
-- prefetchWrite a i = unsafeIOToST $ prefetchCacheLine_write v x
prefetchWrite a i = prefetchCacheLine_write v x
where
v = M.toPtr a
x = fI i
{-# INLINE forwardSearch2 #-}
forwardSearch2 :: IntArray -> Int -> Int -> Elem -> Elem -> IO Int
forwardSearch2 !vec !start !end !x1 !x2 =
-- liftM fromEnum $! unsafeIOToST c
liftM fromEnum $! c
where
c = c_forwardSearch_2 (M.toPtr vec) (fI start) (fI end) (fI x1) (fI x2)
{-# INLINE forwardSearch3 #-}
forwardSearch3 :: IntArray -> Int -> Int -> Elem -> Elem -> Elem -> IO Int
forwardSearch3 !vec !start !end !x1 !x2 !x3 =
-- liftM fromEnum $! unsafeIOToST c
liftM fromEnum $! c
where
c = c_forwardSearch_3 (M.toPtr vec) (fI start) (fI end)
(fI x1) (fI x2) (fI x3)
{-# INLINE lineSearch #-}
lineSearch :: IntArray -> Int -> Elem -> IO Int
lineSearch !vec !start !value =
-- liftM fromEnum $! unsafeIOToST c
liftM fromEnum $! c
where
c = c_lineSearch (M.toPtr vec) (fI start) (fI value)
{-# INLINE lineSearch2 #-}
lineSearch2 :: IntArray -> Int -> Elem -> Elem -> IO Int
lineSearch2 !vec !start !x1 !x2 =
-- liftM fromEnum $! unsafeIOToST c
liftM fromEnum $! c
where
c = c_lineSearch_2 (M.toPtr vec) (fI start) (fI x1) (fI x2)
{-# INLINE lineSearch3 #-}
lineSearch3 :: IntArray -> Int -> Elem -> Elem -> Elem -> IO Int
lineSearch3 !vec !start !x1 !x2 !x3 =
-- liftM fromEnum $! unsafeIOToST c
liftM fromEnum $! c
where
c = c_lineSearch_3 (M.toPtr vec) (fI start) (fI x1) (fI x2) (fI x3)
#endif
{-# INLINE advanceByCacheLineSize #-}
advanceByCacheLineSize :: Int -> Int -> Int
advanceByCacheLineSize !(I# start0#) !(I# vecSize#) = out
where
!(I# clm#) = cacheLineIntMask
!clmm# = not# (int2Word# clm#)
!start# = word2Int# (clmm# `and#` int2Word# start0#)
!(I# nw#) = numElemsInCacheLine
!start'# = start# +# nw#
!s# = sign# (vecSize# -# start'# -# 1#)
!m# = not# (int2Word# s#)
!r# = int2Word# start'# `and#` m#
!out = I# (word2Int# r#)
{-# INLINE isCacheLineAligned #-}
isCacheLineAligned :: Int -> Bool
isCacheLineAligned (I# x#) = isTrue# (r# ==# 0#)
where
!(I# m#) = cacheLineIntMask
!mw# = int2Word# m#
!w# = int2Word# x#
!r# = word2Int# (mw# `and#` w#)
{-# INLINE sign# #-}
-- | Returns 0 if x is positive, -1 otherwise
sign# :: Int# -> Int#
sign# !x# = x# `uncheckedIShiftRA#` wordSizeMinus1#
where
!(I# wordSizeMinus1#) = wordSize-1
{-# INLINE bl_abs# #-}
-- | Abs of an integer, branchless
bl_abs# :: Int# -> Int#
bl_abs# !x# = word2Int# r#
where
!m# = sign# x#
!r# = (int2Word# (m# +# x#)) `xor#` int2Word# m#
{-# INLINE mask# #-}
-- | Returns 0xfff..fff (aka -1) if a# == b#, 0 otherwise.
mask# :: Int# -> Int# -> Int#
mask# !a# !b# = dest#
where
!d# = a# -# b#
!r# = bl_abs# d# -# 1#
!dest# = sign# r#
{- note: this code should be:
mask# :: Int# -> Int# -> Int#
mask# !a# !b# = let !(I# z#) = fromEnum (a# ==# b#)
!q# = negateInt# z#
in q#
but GHC doesn't properly optimize this as straight-line code at the moment.
-}
{-# INLINE maskw# #-}
maskw# :: Int# -> Int# -> Word#
maskw# !a# !b# = int2Word# (mask# a# b#)
#ifdef NO_C_SEARCH
prefetchRead _ _ = return ()
prefetchWrite _ _ = return ()
{-# INLINE forwardSearch2 #-}
forwardSearch2 :: IntArray -> Int -> Int -> Elem -> Elem -> IO Int
forwardSearch2 !vec !start !end !x1 !x2 = go start end False
where
next !i !e !b = let !j = i+1
in if j == e
then (if b then (-1,e,True) else (0,start,True))
else (j,e,b)
go !i !e !b = do
h <- M.readArray vec i
if h == x1 || h == x2
then return i
else do
let (!i',!e',!b') = next i e b
if (i' < 0) then return (-1) else go i' e' b'
{-# INLINE forwardSearch3 #-}
forwardSearch3 :: IntArray -> Int -> Int -> Elem -> Elem -> Elem -> IO Int
forwardSearch3 !vec !start !end !x1 !x2 !x3 = go start end False
where
next !i !e !b = let !j = i+1
in if j == e
then (if b then (-1,e,True) else (0,start,True))
else (j,e,b)
go !i !e !b = do
h <- M.readArray vec i
if h == x1 || h == x2 || h == x3
then return i
else do
let (!i',!e',!b') = next i e b
if (i' < 0) then return (-1) else go i' e' b'
deBruijnBitPositions :: U.Vector Int8
deBruijnBitPositions =
U.fromList [
0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
]
{-# INLINE firstBitSet# #-}
-- only works with 32-bit values -- ok for us here
firstBitSet# :: Int# -> Int#
firstBitSet# i# = word2Int# ((or# zeroCase# posw#))
where
!zeroCase# = int2Word# (mask# 0# i#)
!w# = int2Word# i#
!iLowest# = word2Int# (and# w# (int2Word# (negateInt# i#)))
!idxW# = uncheckedShiftRL#
(narrow32Word# (timesWord# (int2Word# iLowest#)
(int2Word# 0x077CB531#)))
27#
!idx = I# (word2Int# idxW#)
!(I8# pos8#) = U.unsafeIndex deBruijnBitPositions idx
!posw# = int2Word# pos8#
#endif
#ifdef NO_C_SEARCH
lineResult# :: Word# -- ^ mask
-> Int -- ^ start value
-> Int
lineResult# bitmask# (I# start#) = I# (word2Int# rv#)
where
!p# = firstBitSet# (word2Int# bitmask#)
!mm# = maskw# p# (-1#)
!nmm# = not# mm#
!rv# = mm# `or#` (nmm# `and#` (int2Word# (start# +# p#)))
{-# INLINE lineResult# #-}
-- Required: unlike in C search, required that the start index is
-- cache-line-aligned and array has at least 32 elements after the start index
lineSearch :: IntArray -- ^ vector to search
-> Int -- ^ start index
-> Elem -- ^ value to search for
-> IO Int -- ^ dest index where it can be found, or
-- \"-1\" if not found
lineSearch !vec !start !elem1 = do
let !(I# v1#) = fromIntegral elem1
!(I# x1#) <- liftM fromIntegral $ M.readArray vec start
let !p1# = (and# (maskw# x1# v1#) (int2Word# 0x1#))
!(I# x2#) <- liftM fromIntegral $ M.readArray vec $! start + 1
let !p2# = or# p1# (and# (maskw# x2# v1#) (int2Word# 0x2#))
!(I# x3#) <- liftM fromIntegral $ M.readArray vec $! start + 2
let !p3# = or# p2# (and# (maskw# x3# v1#) (int2Word# 0x4#))
!(I# x4#) <- liftM fromIntegral $ M.readArray vec $! start + 3
let !p4# = or# p3# (and# (maskw# x4# v1#) (int2Word# 0x8#))
!(I# x5#) <- liftM fromIntegral $ M.readArray vec $! start + 4
let !p5# = or# p4# (and# (maskw# x5# v1#) (int2Word# 0x10#))
!(I# x6#) <- liftM fromIntegral $ M.readArray vec $! start + 5
let !p6# = or# p5# (and# (maskw# x6# v1#) (int2Word# 0x20#))
!(I# x7#) <- liftM fromIntegral $ M.readArray vec $! start + 6
let !p7# = or# p6# (and# (maskw# x7# v1#) (int2Word# 0x40#))
!(I# x8#) <- liftM fromIntegral $ M.readArray vec $! start + 7
let !p8# = or# p7# (and# (maskw# x8# v1#) (int2Word# 0x80#))
!(I# x9#) <- liftM fromIntegral $ M.readArray vec $! start + 8
let !p9# = or# p8# (and# (maskw# x9# v1#) (int2Word# 0x100#))
!(I# x10#) <- liftM fromIntegral $ M.readArray vec $! start + 9
let !p10# = or# p9# (and# (maskw# x10# v1#) (int2Word# 0x200#))
!(I# x11#) <- liftM fromIntegral $ M.readArray vec $! start + 10
let !p11# = or# p10# (and# (maskw# x11# v1#) (int2Word# 0x400#))
!(I# x12#) <- liftM fromIntegral $ M.readArray vec $! start + 11
let !p12# = or# p11# (and# (maskw# x12# v1#) (int2Word# 0x800#))
!(I# x13#) <- liftM fromIntegral $ M.readArray vec $! start + 12
let !p13# = or# p12# (and# (maskw# x13# v1#) (int2Word# 0x1000#))
!(I# x14#) <- liftM fromIntegral $ M.readArray vec $! start + 13
let !p14# = or# p13# (and# (maskw# x14# v1#) (int2Word# 0x2000#))
!(I# x15#) <- liftM fromIntegral $ M.readArray vec $! start + 14
let !p15# = or# p14# (and# (maskw# x15# v1#) (int2Word# 0x4000#))
!(I# x16#) <- liftM fromIntegral $ M.readArray vec $! start + 15
let !p16# = or# p15# (and# (maskw# x16# v1#) (int2Word# 0x8000#))
!(I# x17#) <- liftM fromIntegral $ M.readArray vec $! start + 16
let !p17# = or# p16# (and# (maskw# x17# v1#) (int2Word# 0x10000#))
!(I# x18#) <- liftM fromIntegral $ M.readArray vec $! start + 17
let !p18# = or# p17# (and# (maskw# x18# v1#) (int2Word# 0x20000#))
!(I# x19#) <- liftM fromIntegral $ M.readArray vec $! start + 18
let !p19# = or# p18# (and# (maskw# x19# v1#) (int2Word# 0x40000#))
!(I# x20#) <- liftM fromIntegral $ M.readArray vec $! start + 19
let !p20# = or# p19# (and# (maskw# x20# v1#) (int2Word# 0x80000#))
!(I# x21#) <- liftM fromIntegral $ M.readArray vec $! start + 20
let !p21# = or# p20# (and# (maskw# x21# v1#) (int2Word# 0x100000#))
!(I# x22#) <- liftM fromIntegral $ M.readArray vec $! start + 21
let !p22# = or# p21# (and# (maskw# x22# v1#) (int2Word# 0x200000#))
!(I# x23#) <- liftM fromIntegral $ M.readArray vec $! start + 22
let !p23# = or# p22# (and# (maskw# x23# v1#) (int2Word# 0x400000#))
!(I# x24#) <- liftM fromIntegral $ M.readArray vec $! start + 23
let !p24# = or# p23# (and# (maskw# x24# v1#) (int2Word# 0x800000#))
!(I# x25#) <- liftM fromIntegral $ M.readArray vec $! start + 24
let !p25# = or# p24# (and# (maskw# x25# v1#) (int2Word# 0x1000000#))
!(I# x26#) <- liftM fromIntegral $ M.readArray vec $! start + 25
let !p26# = or# p25# (and# (maskw# x26# v1#) (int2Word# 0x2000000#))
!(I# x27#) <- liftM fromIntegral $ M.readArray vec $! start + 26
let !p27# = or# p26# (and# (maskw# x27# v1#) (int2Word# 0x4000000#))
!(I# x28#) <- liftM fromIntegral $ M.readArray vec $! start + 27
let !p28# = or# p27# (and# (maskw# x28# v1#) (int2Word# 0x8000000#))
!(I# x29#) <- liftM fromIntegral $ M.readArray vec $! start + 28
let !p29# = or# p28# (and# (maskw# x29# v1#) (int2Word# 0x10000000#))
!(I# x30#) <- liftM fromIntegral $ M.readArray vec $! start + 29
let !p30# = or# p29# (and# (maskw# x30# v1#) (int2Word# 0x20000000#))
!(I# x31#) <- liftM fromIntegral $ M.readArray vec $! start + 30
let !p31# = or# p30# (and# (maskw# x31# v1#) (int2Word# 0x40000000#))
!(I# x32#) <- liftM fromIntegral $ M.readArray vec $! start + 31
let !p32# = or# p31# (and# (maskw# x32# v1#) (int2Word# 0x80000000#))
return $! lineResult# p32# start
-- Required: unlike in C search, required that the start index is
-- cache-line-aligned and array has at least 32 elements after the start index
lineSearch2 :: IntArray -- ^ vector to search
-> Int -- ^ start index
-> Elem -- ^ value to search for
-> Elem -- ^ second value to search for
-> IO Int -- ^ dest index where it can be found, or
-- \"-1\" if not found
lineSearch2 !vec !start !elem1 !elem2 = do
let !(I# v1#) = fromIntegral elem1
let !(I# v2#) = fromIntegral elem2
!(I# x1#) <- liftM fromIntegral $ M.readArray vec start
let !p1# = (and# (int2Word# 0x1#)
(or# (maskw# x1# v1#) (maskw# x1# v2#)))
!(I# x2#) <- liftM fromIntegral $ M.readArray vec $! start + 1
let !p2# = or# p1# (and# (int2Word# 0x2#)
(or# (maskw# x2# v1#) (maskw# x2# v2#)))
!(I# x3#) <- liftM fromIntegral $ M.readArray vec $! start + 2
let !p3# = or# p2# (and# (int2Word# 0x4#)
(or# (maskw# x3# v1#) (maskw# x3# v2#)))
!(I# x4#) <- liftM fromIntegral $ M.readArray vec $! start + 3
let !p4# = or# p3# (and# (int2Word# 0x8#)
(or# (maskw# x4# v1#) (maskw# x4# v2#)))
!(I# x5#) <- liftM fromIntegral $ M.readArray vec $! start + 4
let !p5# = or# p4# (and# (int2Word# 0x10#)
(or# (maskw# x5# v1#) (maskw# x5# v2#)))
!(I# x6#) <- liftM fromIntegral $ M.readArray vec $! start + 5
let !p6# = or# p5# (and# (int2Word# 0x20#)
(or# (maskw# x6# v1#) (maskw# x6# v2#)))
!(I# x7#) <- liftM fromIntegral $ M.readArray vec $! start + 6
let !p7# = or# p6# (and# (int2Word# 0x40#)
(or# (maskw# x7# v1#) (maskw# x7# v2#)))
!(I# x8#) <- liftM fromIntegral $ M.readArray vec $! start + 7
let !p8# = or# p7# (and# (int2Word# 0x80#)
(or# (maskw# x8# v1#) (maskw# x8# v2#)))
!(I# x9#) <- liftM fromIntegral $ M.readArray vec $! start + 8
let !p9# = or# p8# (and# (int2Word# 0x100#)
(or# (maskw# x9# v1#) (maskw# x9# v2#)))
!(I# x10#) <- liftM fromIntegral $ M.readArray vec $! start + 9
let !p10# = or# p9# (and# (int2Word# 0x200#)
(or# (maskw# x10# v1#) (maskw# x10# v2#)))
!(I# x11#) <- liftM fromIntegral $ M.readArray vec $! start + 10
let !p11# = or# p10# (and# (int2Word# 0x400#)
(or# (maskw# x11# v1#) (maskw# x11# v2#)))
!(I# x12#) <- liftM fromIntegral $ M.readArray vec $! start + 11
let !p12# = or# p11# (and# (int2Word# 0x800#)
(or# (maskw# x12# v1#) (maskw# x12# v2#)))
!(I# x13#) <- liftM fromIntegral $ M.readArray vec $! start + 12
let !p13# = or# p12# (and# (int2Word# 0x1000#)
(or# (maskw# x13# v1#) (maskw# x13# v2#)))
!(I# x14#) <- liftM fromIntegral $ M.readArray vec $! start + 13
let !p14# = or# p13# (and# (int2Word# 0x2000#)
(or# (maskw# x14# v1#) (maskw# x14# v2#)))
!(I# x15#) <- liftM fromIntegral $ M.readArray vec $! start + 14
let !p15# = or# p14# (and# (int2Word# 0x4000#)
(or# (maskw# x15# v1#) (maskw# x15# v2#)))
!(I# x16#) <- liftM fromIntegral $ M.readArray vec $! start + 15
let !p16# = or# p15# (and# (int2Word# 0x8000#)
(or# (maskw# x16# v1#) (maskw# x16# v2#)))
!(I# x17#) <- liftM fromIntegral $ M.readArray vec $! start + 16
let !p17# = or# p16# (and# (int2Word# 0x10000#)
(or# (maskw# x17# v1#) (maskw# x17# v2#)))
!(I# x18#) <- liftM fromIntegral $ M.readArray vec $! start + 17
let !p18# = or# p17# (and# (int2Word# 0x20000#)
(or# (maskw# x18# v1#) (maskw# x18# v2#)))
!(I# x19#) <- liftM fromIntegral $ M.readArray vec $! start + 18
let !p19# = or# p18# (and# (int2Word# 0x40000#)
(or# (maskw# x19# v1#) (maskw# x19# v2#)))
!(I# x20#) <- liftM fromIntegral $ M.readArray vec $! start + 19
let !p20# = or# p19# (and# (int2Word# 0x80000#)
(or# (maskw# x20# v1#) (maskw# x20# v2#)))
!(I# x21#) <- liftM fromIntegral $ M.readArray vec $! start + 20
let !p21# = or# p20# (and# (int2Word# 0x100000#)
(or# (maskw# x21# v1#) (maskw# x21# v2#)))
!(I# x22#) <- liftM fromIntegral $ M.readArray vec $! start + 21
let !p22# = or# p21# (and# (int2Word# 0x200000#)
(or# (maskw# x22# v1#) (maskw# x22# v2#)))
!(I# x23#) <- liftM fromIntegral $ M.readArray vec $! start + 22
let !p23# = or# p22# (and# (int2Word# 0x400000#)
(or# (maskw# x23# v1#) (maskw# x23# v2#)))
!(I# x24#) <- liftM fromIntegral $ M.readArray vec $! start + 23
let !p24# = or# p23# (and# (int2Word# 0x800000#)
(or# (maskw# x24# v1#) (maskw# x24# v2#)))
!(I# x25#) <- liftM fromIntegral $ M.readArray vec $! start + 24
let !p25# = or# p24# (and# (int2Word# 0x1000000#)
(or# (maskw# x25# v1#) (maskw# x25# v2#)))
!(I# x26#) <- liftM fromIntegral $ M.readArray vec $! start + 25
let !p26# = or# p25# (and# (int2Word# 0x2000000#)
(or# (maskw# x26# v1#) (maskw# x26# v2#)))
!(I# x27#) <- liftM fromIntegral $ M.readArray vec $! start + 26
let !p27# = or# p26# (and# (int2Word# 0x4000000#)
(or# (maskw# x27# v1#) (maskw# x27# v2#)))
!(I# x28#) <- liftM fromIntegral $ M.readArray vec $! start + 27
let !p28# = or# p27# (and# (int2Word# 0x8000000#)
(or# (maskw# x28# v1#) (maskw# x28# v2#)))
!(I# x29#) <- liftM fromIntegral $ M.readArray vec $! start + 28
let !p29# = or# p28# (and# (int2Word# 0x10000000#)
(or# (maskw# x29# v1#) (maskw# x29# v2#)))
!(I# x30#) <- liftM fromIntegral $ M.readArray vec $! start + 29
let !p30# = or# p29# (and# (int2Word# 0x20000000#)
(or# (maskw# x30# v1#) (maskw# x30# v2#)))
!(I# x31#) <- liftM fromIntegral $ M.readArray vec $! start + 30
let !p31# = or# p30# (and# (int2Word# 0x40000000#)
(or# (maskw# x31# v1#) (maskw# x31# v2#)))
!(I# x32#) <- liftM fromIntegral $ M.readArray vec $! start + 31
let !p32# = or# p31# (and# (int2Word# 0x80000000#)
(or# (maskw# x32# v1#) (maskw# x32# v2#)))
return $! lineResult# p32# start
-- Required: unlike in C search, required that the start index is
-- cache-line-aligned and array has at least 32 elements after the start index
lineSearch3 :: IntArray -- ^ vector to search
-> Int -- ^ start index
-> Elem -- ^ value to search for
-> Elem -- ^ second value to search for
-> Elem -- ^ third value to search for
-> IO Int -- ^ dest index where it can be found, or
-- \"-1\" if not found
lineSearch3 !vec !start !elem1 !elem2 !elem3 = do
let !(I# v1#) = fromIntegral elem1
let !(I# v2#) = fromIntegral elem2
let !(I# v3#) = fromIntegral elem3
!(I# x1#) <- liftM fromIntegral $ M.readArray vec start
let !p1# = (and# (int2Word# 0x1#)
(or# (maskw# x1# v1#)
(or# (maskw# x1# v2#) (maskw# x1# v3#))))
!(I# x2#) <- liftM fromIntegral $ M.readArray vec $! start + 1
let !p2# = or# p1# (and# (int2Word# 0x2#)
(or# (maskw# x2# v1#)
(or# (maskw# x2# v2#) (maskw# x2# v3#))))
!(I# x3#) <- liftM fromIntegral $ M.readArray vec $! start + 2
let !p3# = or# p2# (and# (int2Word# 0x4#)
(or# (maskw# x3# v1#)
(or# (maskw# x3# v2#) (maskw# x3# v3#))))
!(I# x4#) <- liftM fromIntegral $ M.readArray vec $! start + 3
let !p4# = or# p3# (and# (int2Word# 0x8#)
(or# (maskw# x4# v1#)
(or# (maskw# x4# v2#) (maskw# x4# v3#))))
!(I# x5#) <- liftM fromIntegral $ M.readArray vec $! start + 4
let !p5# = or# p4# (and# (int2Word# 0x10#)
(or# (maskw# x5# v1#)
(or# (maskw# x5# v2#) (maskw# x5# v3#))))
!(I# x6#) <- liftM fromIntegral $ M.readArray vec $! start + 5
let !p6# = or# p5# (and# (int2Word# 0x20#)
(or# (maskw# x6# v1#)
(or# (maskw# x6# v2#) (maskw# x6# v3#))))
!(I# x7#) <- liftM fromIntegral $ M.readArray vec $! start + 6
let !p7# = or# p6# (and# (int2Word# 0x40#)
(or# (maskw# x7# v1#)
(or# (maskw# x7# v2#) (maskw# x7# v3#))))
!(I# x8#) <- liftM fromIntegral $ M.readArray vec $! start + 7
let !p8# = or# p7# (and# (int2Word# 0x80#)
(or# (maskw# x8# v1#)
(or# (maskw# x8# v2#) (maskw# x8# v3#))))
!(I# x9#) <- liftM fromIntegral $ M.readArray vec $! start + 8
let !p9# = or# p8# (and# (int2Word# 0x100#)
(or# (maskw# x9# v1#)
(or# (maskw# x9# v2#) (maskw# x9# v3#))))
!(I# x10#) <- liftM fromIntegral $ M.readArray vec $! start + 9
let !p10# = or# p9# (and# (int2Word# 0x200#)
(or# (maskw# x10# v1#)
(or# (maskw# x10# v2#) (maskw# x10# v3#))))
!(I# x11#) <- liftM fromIntegral $ M.readArray vec $! start + 10
let !p11# = or# p10# (and# (int2Word# 0x400#)
(or# (maskw# x11# v1#)
(or# (maskw# x11# v2#) (maskw# x11# v3#))))
!(I# x12#) <- liftM fromIntegral $ M.readArray vec $! start + 11
let !p12# = or# p11# (and# (int2Word# 0x800#)
(or# (maskw# x12# v1#)
(or# (maskw# x12# v2#) (maskw# x12# v3#))))
!(I# x13#) <- liftM fromIntegral $ M.readArray vec $! start + 12
let !p13# = or# p12# (and# (int2Word# 0x1000#)
(or# (maskw# x13# v1#)
(or# (maskw# x13# v2#) (maskw# x13# v3#))))
!(I# x14#) <- liftM fromIntegral $ M.readArray vec $! start + 13
let !p14# = or# p13# (and# (int2Word# 0x2000#)
(or# (maskw# x14# v1#)
(or# (maskw# x14# v2#) (maskw# x14# v3#))))
!(I# x15#) <- liftM fromIntegral $ M.readArray vec $! start + 14
let !p15# = or# p14# (and# (int2Word# 0x4000#)
(or# (maskw# x15# v1#)
(or# (maskw# x15# v2#) (maskw# x15# v3#))))
!(I# x16#) <- liftM fromIntegral $ M.readArray vec $! start + 15
let !p16# = or# p15# (and# (int2Word# 0x8000#)
(or# (maskw# x16# v1#)
(or# (maskw# x16# v2#) (maskw# x16# v3#))))
!(I# x17#) <- liftM fromIntegral $ M.readArray vec $! start + 16
let !p17# = or# p16# (and# (int2Word# 0x10000#)
(or# (maskw# x17# v1#)
(or# (maskw# x17# v2#) (maskw# x17# v3#))))
!(I# x18#) <- liftM fromIntegral $ M.readArray vec $! start + 17
let !p18# = or# p17# (and# (int2Word# 0x20000#)
(or# (maskw# x18# v1#)
(or# (maskw# x18# v2#) (maskw# x18# v3#))))
!(I# x19#) <- liftM fromIntegral $ M.readArray vec $! start + 18
let !p19# = or# p18# (and# (int2Word# 0x40000#)
(or# (maskw# x19# v1#)
(or# (maskw# x19# v2#) (maskw# x19# v3#))))
!(I# x20#) <- liftM fromIntegral $ M.readArray vec $! start + 19
let !p20# = or# p19# (and# (int2Word# 0x80000#)
(or# (maskw# x20# v1#)
(or# (maskw# x20# v2#) (maskw# x20# v3#))))
!(I# x21#) <- liftM fromIntegral $ M.readArray vec $! start + 20
let !p21# = or# p20# (and# (int2Word# 0x100000#)
(or# (maskw# x21# v1#)
(or# (maskw# x21# v2#) (maskw# x21# v3#))))
!(I# x22#) <- liftM fromIntegral $ M.readArray vec $! start + 21
let !p22# = or# p21# (and# (int2Word# 0x200000#)
(or# (maskw# x22# v1#)
(or# (maskw# x22# v2#) (maskw# x22# v3#))))
!(I# x23#) <- liftM fromIntegral $ M.readArray vec $! start + 22
let !p23# = or# p22# (and# (int2Word# 0x400000#)
(or# (maskw# x23# v1#)
(or# (maskw# x23# v2#) (maskw# x23# v3#))))
!(I# x24#) <- liftM fromIntegral $ M.readArray vec $! start + 23
let !p24# = or# p23# (and# (int2Word# 0x800000#)
(or# (maskw# x24# v1#)
(or# (maskw# x24# v2#) (maskw# x24# v3#))))
!(I# x25#) <- liftM fromIntegral $ M.readArray vec $! start + 24
let !p25# = or# p24# (and# (int2Word# 0x1000000#)
(or# (maskw# x25# v1#)
(or# (maskw# x25# v2#) (maskw# x25# v3#))))
!(I# x26#) <- liftM fromIntegral $ M.readArray vec $! start + 25
let !p26# = or# p25# (and# (int2Word# 0x2000000#)
(or# (maskw# x26# v1#)
(or# (maskw# x26# v2#) (maskw# x26# v3#))))
!(I# x27#) <- liftM fromIntegral $ M.readArray vec $! start + 26
let !p27# = or# p26# (and# (int2Word# 0x4000000#)
(or# (maskw# x27# v1#)
(or# (maskw# x27# v2#) (maskw# x27# v3#))))
!(I# x28#) <- liftM fromIntegral $ M.readArray vec $! start + 27
let !p28# = or# p27# (and# (int2Word# 0x8000000#)
(or# (maskw# x28# v1#)
(or# (maskw# x28# v2#) (maskw# x28# v3#))))
!(I# x29#) <- liftM fromIntegral $ M.readArray vec $! start + 28
let !p29# = or# p28# (and# (int2Word# 0x10000000#)
(or# (maskw# x29# v1#)
(or# (maskw# x29# v2#) (maskw# x29# v3#))))
!(I# x30#) <- liftM fromIntegral $ M.readArray vec $! start + 29
let !p30# = or# p29# (and# (int2Word# 0x20000000#)
(or# (maskw# x30# v1#)
(or# (maskw# x30# v2#) (maskw# x30# v3#))))
!(I# x31#) <- liftM fromIntegral $ M.readArray vec $! start + 30
let !p31# = or# p30# (and# (int2Word# 0x40000000#)
(or# (maskw# x31# v1#)
(or# (maskw# x31# v2#) (maskw# x31# v3#))))
!(I# x32#) <- liftM fromIntegral $ M.readArray vec $! start + 31
let !p32# = or# p31# (and# (int2Word# 0x80000000#)
(or# (maskw# x32# v1#)
(or# (maskw# x32# v2#) (maskw# x32# v3#))))
return $! lineResult# p32# start
------------------------------------------------------------------------------
-- | Search through a mutable vector for a given int value. The number of
-- things to search for must be at most the number of things remaining in the
-- vector.
naiveSearch :: IntArray -- ^ vector to search
-> Int -- ^ start index
-> Int -- ^ number of things to search
-> Elem -- ^ value to search for
-> IO Int -- ^ dest index where it can be found, or
-- \"-1\" if not found
naiveSearch !vec !start !nThings !value = go start
where
!doneIdx = start + nThings
go !i | i >= doneIdx = return (-1)
| otherwise = do
x <- M.readArray vec i
if x == value then return i else go (i+1)
{-# INLINE naiveSearch #-}
------------------------------------------------------------------------------
naiveSearch2 :: IntArray -- ^ vector to search
-> Int -- ^ start index
-> Int -- ^ number of things to search
-> Elem -- ^ value to search for
-> Elem -- ^ value 2 to search for
-> IO Int -- ^ dest index where it can be found, or
-- \"-1\" if not found
naiveSearch2 !vec !start !nThings !value1 !value2 = go start
where
!doneIdx = start + nThings
go !i | i >= doneIdx = return (-1)
| otherwise = do
x <- M.readArray vec i
if x == value1 || x == value2 then return i else go (i+1)
{-# INLINE naiveSearch2 #-}
------------------------------------------------------------------------------
naiveSearch3 :: IntArray -- ^ vector to search
-> Int -- ^ start index
-> Int -- ^ number of things to search
-> Elem -- ^ value to search for
-> Elem -- ^ value 2 to search for
-> Elem -- ^ value 3 to search for
-> IO Int -- ^ dest index where it can be found, or
-- \"-1\" if not found
naiveSearch3 !vec !start !nThings !value1 !value2 !value3 = go start
where
!doneIdx = start + nThings
go !i | i >= doneIdx = return (-1)
| otherwise = do
x <- M.readArray vec i
if x == value1 || x == value2 || x == value3
then return i
else go (i+1)
{-# INLINE naiveSearch3 #-}
-- end #if NO_C_SEARCH
#endif
------------------------------------------------------------------------------
-- | Search through a mutable vector for a given int value, cache-line aligned.
-- If the start index is cache-line aligned, and there is more than a
-- cache-line's room between the start index and the end of the vector, we will
-- search the cache-line all at once using an efficient branchless
-- bit-twiddling technique. Otherwise, we will use a typical loop.
--
cacheLineSearch :: IntArray -- ^ vector to search
-> Int -- ^ start index
-> Elem -- ^ value to search for
-> IO Int -- ^ dest index where it can be found, or
-- \"-1\" if not found
cacheLineSearch !vec !start !value = do
#ifdef NO_C_SEARCH
let !vlen = M.length vec
let !st1 = vlen - start
let !nvlen = numElemsInCacheLine - st1
let adv = (start + cacheLineIntMask) .&. complement cacheLineIntMask
let st2 = adv - start
if nvlen > 0 || not (isCacheLineAligned start)
then naiveSearch vec start (min st1 st2) value
else lineSearch vec start value
#else
lineSearch vec start value
#endif
{-# INLINE cacheLineSearch #-}
------------------------------------------------------------------------------
-- | Search through a mutable vector for one of two given int values,
-- cache-line aligned. If the start index is cache-line aligned, and there is
-- more than a cache-line's room between the start index and the end of the
-- vector, we will search the cache-line all at once using an efficient
-- branchless bit-twiddling technique. Otherwise, we will use a typical loop.
--
cacheLineSearch2 :: IntArray -- ^ vector to search
-> Int -- ^ start index
-> Elem -- ^ value to search for
-> Elem -- ^ value 2 to search for
-> IO Int -- ^ dest index where it can be found, or
-- \"-1\" if not found
cacheLineSearch2 !vec !start !value !value2 = do
#ifdef NO_C_SEARCH
let !vlen = M.length vec
let !st1 = vlen - start
let !nvlen = numElemsInCacheLine - st1
let adv = (start + cacheLineIntMask) .&. complement cacheLineIntMask
let st2 = adv - start
if nvlen > 0 || not (isCacheLineAligned start)
then naiveSearch2 vec start (min st1 st2) value value2
else lineSearch2 vec start value value2
#else
lineSearch2 vec start value value2
#endif
{-# INLINE cacheLineSearch2 #-}
------------------------------------------------------------------------------
-- | Search through a mutable vector for one of three given int values,
-- cache-line aligned. If the start index is cache-line aligned, and there is
-- more than a cache-line's room between the start index and the end of the
-- vector, we will search the cache-line all at once using an efficient
-- branchless bit-twiddling technique. Otherwise, we will use a typical loop.
--
cacheLineSearch3 :: IntArray -- ^ vector to search
-> Int -- ^ start index
-> Elem -- ^ value to search for
-> Elem -- ^ value 2 to search for
-> Elem -- ^ value 3 to search for
-> IO Int -- ^ dest index where it can be found, or
-- \"-1\" if not found
cacheLineSearch3 !vec !start !value !value2 !value3 = do
#ifdef NO_C_SEARCH
let !vlen = M.length vec
let !st1 = vlen - start
let !nvlen = numElemsInCacheLine - st1
let adv = (start + cacheLineIntMask) .&. complement cacheLineIntMask
let st2 = adv - start
if nvlen > 0 || not (isCacheLineAligned start)
then naiveSearch3 vec start (min st1 st2) value value2 value3
else lineSearch3 vec start value value2 value3
#else
lineSearch3 vec start value value2 value3
#endif
{-# INLINE cacheLineSearch3 #-}
| bjpop/blip | blipinterpreter/src/Blip/Interpreter/HashTable/CacheLine.hs | bsd-3-clause | 35,326 | 0 | 18 | 11,689 | 12,289 | 5,771 | 6,518 | 528 | 5 |
module Filesystem.Find where
import Filesystem.Utils
import Utils
import Control.Monad (foldM)
import System.Directory (getDirectoryContents,doesDirectoryExist)
import System.FilePath ((</>))
findFiles :: FilePath -> (FilePath -> Bool) -> IO [FilePath]
findFiles base pred = loop base
where
loop path = do
(matches,dirs) <- partition =<< getDirectoryContents path
rest <- mapM (loop . (path </>)) dirs
return (concat (map (path </>) matches : rest))
partition = foldM step ([],[])
where
step acc@(ms,ds) path = do
isDir <- doesDirectoryExist path
case path of
"." -> return acc
".." -> return acc
_ | isDir -> return (ms,path:ds)
| pred path -> return (path:ms,ds)
| otherwise -> return acc
| elliottt/din | src/Filesystem/Find.hs | bsd-3-clause | 812 | 0 | 17 | 223 | 307 | 159 | 148 | 21 | 3 |
{-# LANGUAGE
ScopedTypeVariables,
TypeFamilies,
FlexibleContexts,
FlexibleInstances,
LiberalTypeSynonyms
#-}
-- | Facilities for defining new object types which can be marshalled between
-- Haskell and QML.
module Graphics.QML.Objects (
-- * Object References
ObjRef,
newObject,
newObjectDC,
fromObjRef,
-- * Dynamic Object References
AnyObjRef,
anyObjRef,
fromAnyObjRef,
-- * Class Definition
Class,
newClass,
DefaultClass (
classMembers),
Member,
-- * Methods
defMethod,
defMethod',
MethodSuffix,
-- * Signals
defSignal,
defSignalNamedParams,
fireSignal,
SignalKey,
newSignalKey,
SignalKeyValue (type SignalValueParams),
SignalKeyClass (
type SignalParams),
SignalSuffix (type SignalParamNames),
-- * Properties
defPropertyConst,
defPropertyRO,
defPropertySigRO,
defPropertyRW,
defPropertySigRW,
defPropertyConst',
defPropertyRO',
defPropertySigRO',
defPropertyRW',
defPropertySigRW'
) where
import Graphics.QML.Internal.BindCore
import Graphics.QML.Internal.BindObj
import Graphics.QML.Internal.JobQueue
import Graphics.QML.Internal.Marshal
import Graphics.QML.Internal.MetaObj
import Graphics.QML.Internal.Objects
import Graphics.QML.Internal.Types
import Graphics.QML.Objects.ParamNames
import Control.Concurrent.MVar
import Data.Map (Map)
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Maybe
import Data.Proxy
import Data.Tagged
import Data.Typeable
import Data.IORef
import Data.Unique
import Foreign.Ptr
import Foreign.Storable
import Foreign.Marshal.Array
import System.IO.Unsafe
import Numeric
--
-- ObjRef
--
-- | Creates a QML object given a 'Class' and a Haskell value of type @tt@.
newObject :: forall tt. Class tt -> tt -> IO (ObjRef tt)
newObject (Class cHndl) obj =
fmap ObjRef $ hsqmlCreateObject obj cHndl
-- | Creates a QML object given a Haskell value of type @tt@ which has a
-- 'DefaultClass' instance.
newObjectDC :: forall tt. (DefaultClass tt) => tt -> IO (ObjRef tt)
newObjectDC obj = do
clazz <- getDefaultClass :: IO (Class tt)
newObject clazz obj
-- | Returns the associated value of the underlying Haskell type @tt@ from an
-- instance of the QML class which wraps it.
fromObjRef :: ObjRef tt -> tt
fromObjRef = unsafeDupablePerformIO . fromObjRefIO
-- | Upcasts an 'ObjRef' into an 'AnyObjRef'.
anyObjRef :: ObjRef tt -> AnyObjRef
anyObjRef (ObjRef hndl) = AnyObjRef hndl
-- | Attempts to downcast an 'AnyObjRef' into an 'ObjRef' with the specific
-- underlying Haskell type @tt@.
fromAnyObjRef :: (Typeable tt) => AnyObjRef -> Maybe (ObjRef tt)
fromAnyObjRef = unsafeDupablePerformIO . fromAnyObjRefIO
--
-- Class
--
-- | Represents a QML class which wraps the type @tt@.
newtype Class tt = Class HsQMLClassHandle
-- | Creates a new QML class for the type @tt@.
newClass :: forall tt. (Typeable tt) => [Member tt] -> IO (Class tt)
newClass = fmap Class . createClass (typeOf (undefined :: tt))
createClass :: forall tt. TypeRep -> [Member tt] -> IO HsQMLClassHandle
createClass typRep ms = do
hsqmlInit
classId <- hsqmlGetNextClassId
let constrs t = typeRepTyCon t : (concatMap constrs $ typeRepArgs t)
name = foldr (\c s -> showString (tyConName c) .
showChar '_' . s) id (constrs typRep) $ showInt classId ""
ms' = ms ++ implicitSignals ms
moc = compileClass name ms'
sigs = filterMembers SignalMember ms'
sigMap = Map.fromList $ flip zip [0..] $ map (fromJust . memberKey) sigs
info = ClassInfo typRep sigMap
maybeMarshalFunc = maybe (return nullFunPtr) marshalFunc
metaDataPtr <- crlToNewArray return (mData moc)
metaStrInfoPtr <- crlToNewArray return (mStrInfo moc)
metaStrCharPtr <- crlToNewArray return (mStrChar moc)
methodsPtr <- crlToNewArray maybeMarshalFunc (mFuncMethods moc)
propsPtr <- crlToNewArray maybeMarshalFunc (mFuncProperties moc)
maybeHndl <- hsqmlCreateClass
metaDataPtr metaStrInfoPtr metaStrCharPtr info methodsPtr propsPtr
case maybeHndl of
Just hndl -> return hndl
Nothing -> error ("Failed to create QML class '"++name++"'.")
implicitSignals :: [Member tt] -> [Member tt]
implicitSignals ms =
let sigKeys = Set.fromList $ mapMaybe memberKey $
filterMembers SignalMember ms
impKeys = filter (flip Set.notMember sigKeys) $ mapMaybe memberKey $
filterMembers PropertyMember ms
impMember i k = Member SignalMember
("__implicitSignal" ++ show i)
tyVoid
[]
(\_ _ -> return ())
Nothing
(Just k)
in map (uncurry impMember) $ zip [(0::Int)..] impKeys
--
-- Default Class
--
data MemoStore k v = MemoStore (MVar (Map k v)) (IORef (Map k v))
newMemoStore :: IO (MemoStore k v)
newMemoStore = do
let m = Map.empty
mr <- newMVar m
ir <- newIORef m
return $ MemoStore mr ir
getFromMemoStore :: (Ord k) => MemoStore k v -> k -> IO v -> IO (Bool, v)
getFromMemoStore (MemoStore mr ir) key fn = do
fstMap <- readIORef ir
case Map.lookup key fstMap of
Just val -> return (False, val)
Nothing -> modifyMVar mr $ \sndMap -> do
case Map.lookup key sndMap of
Just val -> return (sndMap, (False, val))
Nothing -> do
val <- fn
let newMap = Map.insert key val sndMap
writeIORef ir newMap
return (newMap, (True, val))
-- | The class 'DefaultClass' specifies a standard class definition for the
-- type @tt@.
class (Typeable tt) => DefaultClass tt where
-- | List of default class members.
classMembers :: [Member tt]
{-# NOINLINE defaultClassDb #-}
defaultClassDb :: MemoStore TypeRep HsQMLClassHandle
defaultClassDb = unsafePerformIO $ newMemoStore
getDefaultClass :: forall tt. (DefaultClass tt) => IO (Class tt)
getDefaultClass = do
let typ = typeOf (undefined :: tt)
(_, val) <- getFromMemoStore defaultClassDb typ $
createClass typ (classMembers :: [Member tt])
return (Class val)
--
-- Method
--
data MethodTypeInfo = MethodTypeInfo {
methodParamTypes :: [TypeId],
methodReturnType :: TypeId
}
-- | Supports marshalling Haskell functions with an arbitrary number of
-- arguments.
class MethodSuffix a where
mkMethodFunc :: Int -> a -> Ptr (Ptr ()) -> ErrIO ()
mkMethodTypes :: Tagged a MethodTypeInfo
instance (Marshal a, CanGetFrom a ~ Yes, MethodSuffix b) =>
MethodSuffix (a -> b) where
mkMethodFunc n f pv = do
ptr <- errIO $ peekElemOff pv n
val <- mFromCVal ptr
mkMethodFunc (n+1) (f val) pv
return ()
mkMethodTypes =
let (MethodTypeInfo p r) =
untag (mkMethodTypes :: Tagged b MethodTypeInfo)
typ = untag (mTypeCVal :: Tagged a TypeId)
in Tagged $ MethodTypeInfo (typ:p) r
instance (Marshal a, CanReturnTo a ~ Yes) =>
MethodSuffix (IO a) where
mkMethodFunc _ f pv = errIO $ do
ptr <- peekElemOff pv 0
val <- f
if nullPtr == ptr
then return ()
else mToCVal val ptr
mkMethodTypes =
let typ = untag (mTypeCVal :: Tagged a TypeId)
in Tagged $ MethodTypeInfo [] typ
mkUniformFunc :: forall tt ms.
(Marshal tt, CanGetFrom tt ~ Yes, IsObjType tt ~ Yes,
MethodSuffix ms) =>
(tt -> ms) -> UniformFunc
mkUniformFunc f = \pt pv -> do
hndl <- hsqmlGetObjectFromPointer pt
this <- mFromHndl hndl
runErrIO $ mkMethodFunc 1 (f this) pv
newtype VoidIO = VoidIO {runVoidIO :: (IO ())}
instance MethodSuffix VoidIO where
mkMethodFunc _ f _ = errIO $ runVoidIO f
mkMethodTypes = Tagged $ MethodTypeInfo [] tyVoid
class IsVoidIO a
instance (IsVoidIO b) => IsVoidIO (a -> b)
instance IsVoidIO VoidIO
mkSpecialFunc :: forall tt ms.
(Marshal tt, CanGetFrom tt ~ Yes, IsObjType tt ~ Yes,
MethodSuffix ms, IsVoidIO ms) => (tt -> ms) -> UniformFunc
mkSpecialFunc f = \pt pv -> do
hndl <- hsqmlGetObjectFromPointer pt
this <- mFromHndl hndl
runErrIO $ mkMethodFunc 0 (f this) pv
-- | Defines a named method using a function @f@ in the IO monad.
--
-- The first argument to @f@ receives the \"this\" object and hence must match
-- the type of the class on which the method is being defined. Subsequently,
-- there may be zero or more parameter arguments followed by an optional return
-- argument in the IO monad.
defMethod :: forall tt ms.
(Marshal tt, CanGetFrom tt ~ Yes, IsObjType tt ~ Yes, MethodSuffix ms) =>
String -> (tt -> ms) -> Member (GetObjType tt)
defMethod name f =
let crude = untag (mkMethodTypes :: Tagged ms MethodTypeInfo)
in Member MethodMember
name
(methodReturnType crude)
(map (\t->("",t)) $ methodParamTypes crude)
(mkUniformFunc f)
Nothing
Nothing
-- | Alias of 'defMethod' which is less polymorphic to reduce the need for type
-- signatures.
defMethod' :: forall obj ms. (Typeable obj, MethodSuffix ms) =>
String -> (ObjRef obj -> ms) -> Member obj
defMethod' = defMethod
--
-- Signal
--
data SignalTypeInfo = SignalTypeInfo {
signalParamTypes :: [TypeId]
}
-- | Defines a named signal. The signal is identified in subsequent calls to
-- 'fireSignal' using a 'SignalKeyValue'. This can be either i) type-based
-- using 'Proxy' @sk@ where @sk@ is an instance of the 'SignalKeyClass' class
-- or ii) value-based using a 'SignalKey' value creating using 'newSignalKey'.
defSignal ::
forall obj skv. (SignalKeyValue skv) => String -> skv -> Member obj
defSignal name key = defSignalNamedParams name key anonParams
-- | Defines a named signal with named parameters. This is otherwise identical
-- to 'defSignal', but allows QML code to reference signal parameters by-name
-- in addition to by-position.
defSignalNamedParams :: forall obj skv. (SignalKeyValue skv) =>
String -> skv ->
ParamNames (SignalParamNames (SignalValueParams skv)) -> Member obj
defSignalNamedParams name key pnames =
let crude = untag (mkSignalTypes ::
Tagged (SignalValueParams skv) SignalTypeInfo)
in Member SignalMember
name
tyVoid
(paramNames pnames `zip` signalParamTypes crude)
(\_ _ -> return ())
Nothing
(Just $ signalKey key)
-- | Fires a signal defined on an object instance. The signal is identified
-- using either a type- or value-based signal key, as described in the
-- documentation for 'defSignal'. The first argument is the signal key, the
-- second is the object, and the remaining arguments, if any, are the arguments
-- to the signal as specified by the signal key.
--
-- If this function is called using a signal key which doesn't match a signal
-- defined on the supplied object, it will silently do nothing.
--
-- This function is safe to call from any thread. Any attached signal handlers
-- will be executed asynchronously on the event loop thread.
fireSignal ::
forall tt skv. (Marshal tt, CanPassTo tt ~ Yes, IsObjType tt ~ Yes,
SignalKeyValue skv) => skv -> tt -> SignalValueParams skv
fireSignal key this =
let start cnt = postJob $ do
hndl <- mToHndl this
info <- hsqmlObjectGetHsTyperep hndl
let slotMay = Map.lookup (signalKey key) $ cinfoSignals info
case slotMay of
Just slotIdx ->
withActiveObject hndl $ cnt $ SignalData hndl slotIdx
Nothing ->
return () -- Should warn?
cont ps (SignalData hndl slotIdx) =
withArray (nullPtr:ps) (\pptr ->
hsqmlFireSignal hndl slotIdx pptr)
in mkSignalArgs start cont
data SignalData = SignalData HsQMLObjectHandle Int
-- | Values of the type 'SignalKey' identify distinct signals by value. The
-- type parameter @p@ specifies the signal's signature.
newtype SignalKey p = SignalKey Unique
-- | Creates a new 'SignalKey'.
newSignalKey :: (SignalSuffix p) => IO (SignalKey p)
newSignalKey = fmap SignalKey $ newUnique
-- | Instances of the 'SignalKeyClass' class identify distinct signals by type.
-- The associated 'SignalParams' type specifies the signal's signature.
class (SignalSuffix (SignalParams sk)) => SignalKeyClass sk where
type SignalParams sk
class (SignalSuffix (SignalValueParams skv)) => SignalKeyValue skv where
type SignalValueParams skv
signalKey :: skv -> MemberKey
instance (SignalKeyClass sk, Typeable sk) => SignalKeyValue (Proxy sk) where
type SignalValueParams (Proxy sk) = SignalParams sk
signalKey _ = TypeKey $ typeOf (undefined :: sk)
instance (SignalSuffix p) => SignalKeyValue (SignalKey p) where
type SignalValueParams (SignalKey p) = p
signalKey (SignalKey u) = DataKey u
-- | Supports marshalling an arbitrary number of arguments into a QML signal.
class (AnonParams (SignalParamNames ss)) => SignalSuffix ss where
type SignalParamNames ss
mkSignalArgs :: forall usr.
((usr -> IO ()) -> IO ()) -> ([Ptr ()] -> usr -> IO ()) -> ss
mkSignalTypes :: Tagged ss SignalTypeInfo
instance (Marshal a, CanPassTo a ~ Yes, SignalSuffix b) =>
SignalSuffix (a -> b) where
type SignalParamNames (a -> b) = String -> SignalParamNames b
mkSignalArgs start cont param =
mkSignalArgs start (\ps usr ->
mWithCVal param (\ptr ->
cont (ptr:ps) usr))
mkSignalTypes =
let (SignalTypeInfo p) =
untag (mkSignalTypes :: Tagged b SignalTypeInfo)
typ = untag (mTypeCVal :: Tagged a TypeId)
in Tagged $ SignalTypeInfo (typ:p)
instance SignalSuffix (IO ()) where
type SignalParamNames (IO ()) = ()
mkSignalArgs start cont =
start $ cont []
mkSignalTypes =
Tagged $ SignalTypeInfo []
--
-- Property
--
-- | Defines a named constant property using an accessor function in the IO
-- monad.
defPropertyConst :: forall tt tr.
(Marshal tt, CanGetFrom tt ~ Yes, IsObjType tt ~ Yes, Marshal tr,
CanReturnTo tr ~ Yes) => String ->
(tt -> IO tr) -> Member (GetObjType tt)
defPropertyConst name g = Member ConstPropertyMember
name
(untag (mTypeCVal :: Tagged tr TypeId))
[]
(mkUniformFunc g)
Nothing
Nothing
-- | Defines a named read-only property using an accessor function in the IO
-- monad.
defPropertyRO :: forall tt tr.
(Marshal tt, CanGetFrom tt ~ Yes, IsObjType tt ~ Yes, Marshal tr,
CanReturnTo tr ~ Yes) => String ->
(tt -> IO tr) -> Member (GetObjType tt)
defPropertyRO name g = Member PropertyMember
name
(untag (mTypeCVal :: Tagged tr TypeId))
[]
(mkUniformFunc g)
Nothing
Nothing
-- | Defines a named read-only property with an associated signal.
defPropertySigRO :: forall tt tr skv.
(Marshal tt, CanGetFrom tt ~ Yes, IsObjType tt ~ Yes, Marshal tr,
CanReturnTo tr ~ Yes, SignalKeyValue skv) => String -> skv ->
(tt -> IO tr) -> Member (GetObjType tt)
defPropertySigRO name key g = Member PropertyMember
name
(untag (mTypeCVal :: Tagged tr TypeId))
[]
(mkUniformFunc g)
Nothing
(Just $ signalKey key)
-- | Defines a named read-write property using a pair of accessor and mutator
-- functions in the IO monad.
defPropertyRW :: forall tt tr.
(Marshal tt, CanGetFrom tt ~ Yes, IsObjType tt ~ Yes, Marshal tr,
CanReturnTo tr ~ Yes, CanGetFrom tr ~ Yes) => String ->
(tt -> IO tr) -> (tt -> tr -> IO ()) -> Member (GetObjType tt)
defPropertyRW name g s = Member PropertyMember
name
(untag (mTypeCVal :: Tagged tr TypeId))
[]
(mkUniformFunc g)
(Just $ mkSpecialFunc (\a b -> VoidIO $ s a b))
Nothing
-- | Defines a named read-write property with an associated signal.
defPropertySigRW :: forall tt tr skv.
(Marshal tt, CanGetFrom tt ~ Yes, IsObjType tt ~ Yes, Marshal tr,
CanReturnTo tr ~ Yes, CanGetFrom tr ~ Yes, SignalKeyValue skv) =>
String -> skv -> (tt -> IO tr) -> (tt -> tr -> IO ()) ->
Member (GetObjType tt)
defPropertySigRW name key g s = Member PropertyMember
name
(untag (mTypeCVal :: Tagged tr TypeId))
[]
(mkUniformFunc g)
(Just $ mkSpecialFunc (\a b -> VoidIO $ s a b))
(Just $ signalKey key)
-- | Alias of 'defPropertyConst' which is less polymorphic to reduce the need
-- for type signatures.
defPropertyConst' :: forall obj tr.
(Typeable obj, Marshal tr, CanReturnTo tr ~ Yes) =>
String -> (ObjRef obj -> IO tr) -> Member obj
defPropertyConst' = defPropertyConst
-- | Alias of 'defPropertyRO' which is less polymorphic to reduce the need for
-- type signatures.
defPropertyRO' :: forall obj tr.
(Typeable obj, Marshal tr, CanReturnTo tr ~ Yes) =>
String -> (ObjRef obj -> IO tr) -> Member obj
defPropertyRO' = defPropertyRO
-- | Alias of 'defPropertySigRO' which is less polymorphic to reduce the need
-- for type signatures.
defPropertySigRO' :: forall obj tr skv.
(Typeable obj, Marshal tr, CanReturnTo tr ~ Yes, SignalKeyValue skv) =>
String -> skv -> (ObjRef obj -> IO tr) -> Member obj
defPropertySigRO' = defPropertySigRO
-- | Alias of 'defPropertyRW' which is less polymorphic to reduce the need for
-- type signatures.
defPropertyRW' :: forall obj tr.
(Typeable obj, Marshal tr, CanReturnTo tr ~ Yes, CanGetFrom tr ~ Yes) =>
String -> (ObjRef obj -> IO tr) -> (ObjRef obj -> tr -> IO ()) -> Member obj
defPropertyRW' = defPropertyRW
-- | Alias of 'defPropertySigRW' which is less polymorphic to reduce the need
-- for type signatures.
defPropertySigRW' :: forall obj tr skv.
(Typeable obj, Marshal tr, CanReturnTo tr ~ Yes, CanGetFrom tr ~ Yes,
SignalKeyValue skv) => String -> skv ->
(ObjRef obj -> IO tr) -> (ObjRef obj -> tr -> IO ()) -> Member obj
defPropertySigRW' = defPropertySigRW
| marcinmrotek/hsqml-fork | src/Graphics/QML/Objects.hs | bsd-3-clause | 17,688 | 3 | 23 | 4,016 | 4,929 | 2,560 | 2,369 | -1 | -1 |
{-# LANGUAGE OverloadedStrings, FlexibleContexts, PackageImports #-}
module ManyChanPipe (
fromChan, fromChans, toChan,
) where
import Control.Applicative
-- import Control.Monad
import "monads-tf" Control.Monad.Trans
import Control.Monad.Base
import Control.Monad.Trans.Control
import Data.Pipe
-- import Data.Pipe.ByteString
-- import Control.Concurrent hiding (yield)
import Control.Concurrent.STM
-- import System.IO
-- import qualified Data.ByteString as BS
{-
main :: IO ()
main = do
c1 <- atomically newTChan
c2 <- atomically newTChan
forkIO . forever $ do
sln <- BS.getLine
case BS.splitAt 2 sln of
("1 ", ln) -> atomically $ writeTChan c1 ln
("2 ", ln) -> atomically $ writeTChan c2 ln
_ -> return ()
_ <- runPipe (fromChans [c1, c2] =$= toHandleLn stdout :: Pipe () () IO ())
return ()
-}
fromChan :: MonadBaseControl IO m => TChan a -> Pipe () a m ()
fromChan c = lift (liftBase . atomically $ readTChan c) >>= yield >> fromChan c
toChan :: MonadBaseControl IO m => TChan a -> Pipe a () m ()
toChan c = await >>=
maybe (return ()) ((>> toChan c) . lift . liftBase . atomically . writeTChan c)
fromChans :: MonadBaseControl IO m => [TChan a] -> Pipe () a m ()
fromChans cs = (>> fromChans cs) . (yield =<<) . lift . liftBase . atomically $ do
mx <- readTChans cs
case mx of
Just x -> return x
_ -> retry
readTChans :: [TChan a] -> STM (Maybe a)
readTChans [] = return Nothing
readTChans (c : cs) = do
e <- isEmptyTChan c
if e then readTChans cs else Just <$> readTChan c
| YoshikuniJujo/xmpipe | test/ManyChanPipe.hs | bsd-3-clause | 1,520 | 6 | 13 | 297 | 417 | 215 | 202 | 25 | 2 |
{-# language CPP #-}
-- | = Name
--
-- VK_KHR_dynamic_rendering - device extension
--
-- == VK_KHR_dynamic_rendering
--
-- [__Name String__]
-- @VK_KHR_dynamic_rendering@
--
-- [__Extension Type__]
-- Device extension
--
-- [__Registered Extension Number__]
-- 45
--
-- [__Revision__]
-- 1
--
-- [__Extension and Version Dependencies__]
--
-- - Requires Vulkan 1.0
--
-- - Requires @VK_KHR_get_physical_device_properties2@
--
-- [__Deprecation state__]
--
-- - /Promoted/ to
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#versions-1.3-promotions Vulkan 1.3>
--
-- [__Contact__]
--
-- - Tobias Hector
-- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_dynamic_rendering] @tobski%0A<<Here describe the issue or question you have about the VK_KHR_dynamic_rendering extension>> >
--
-- [__Extension Proposal__]
-- <https://github.com/KhronosGroup/Vulkan-Docs/tree/main/proposals/VK_KHR_dynamic_rendering.asciidoc VK_KHR_dynamic_rendering>
--
-- == Other Extension Metadata
--
-- [__Last Modified Date__]
-- 2021-10-06
--
-- [__Interactions and External Dependencies__]
--
-- - Promoted to Vulkan 1.3 Core
--
-- [__Contributors__]
--
-- - Tobias Hector, AMD
--
-- - Arseny Kapoulkine, Roblox
--
-- - François Duranleau, Gameloft
--
-- - Stuart Smith, AMD
--
-- - Hai Nguyen, Google
--
-- - Jean-François Roy, Google
--
-- - Jeff Leger, Qualcomm
--
-- - Jan-Harald Fredriksen, Arm
--
-- - Piers Daniell, Nvidia
--
-- - James Fitzpatrick, Imagination
--
-- - Piotr Byszewski, Mobica
--
-- - Jesse Hall, Google
--
-- - Mike Blumenkrantz, Valve
--
-- == Description
--
-- This extension allows applications to create single-pass render pass
-- instances without needing to create render pass objects or framebuffers.
-- Dynamic render passes can also span across multiple primary command
-- buffers, rather than relying on secondary command buffers.
--
-- This extension also incorporates 'ATTACHMENT_STORE_OP_NONE_KHR' from
-- <VK_QCOM_render_pass_store_ops.html VK_QCOM_render_pass_store_ops>,
-- enabling applications to avoid unnecessary synchronization when an
-- attachment is not written during a render pass.
--
-- == New Commands
--
-- - 'cmdBeginRenderingKHR'
--
-- - 'cmdEndRenderingKHR'
--
-- == New Structures
--
-- - 'RenderingAttachmentInfoKHR'
--
-- - 'RenderingInfoKHR'
--
-- - Extending
-- 'Vulkan.Core10.CommandBuffer.CommandBufferInheritanceInfo':
--
-- - 'CommandBufferInheritanceRenderingInfoKHR'
--
-- - Extending 'Vulkan.Core10.Pipeline.GraphicsPipelineCreateInfo':
--
-- - 'PipelineRenderingCreateInfoKHR'
--
-- - Extending
-- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2',
-- 'Vulkan.Core10.Device.DeviceCreateInfo':
--
-- - 'PhysicalDeviceDynamicRenderingFeaturesKHR'
--
-- If
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_AMD_mixed_attachment_samples VK_AMD_mixed_attachment_samples>
-- is supported:
--
-- - Extending
-- 'Vulkan.Core10.CommandBuffer.CommandBufferInheritanceInfo',
-- 'Vulkan.Core10.Pipeline.GraphicsPipelineCreateInfo':
--
-- - 'AttachmentSampleCountInfoAMD'
--
-- If
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_fragment_density_map VK_EXT_fragment_density_map>
-- is supported:
--
-- - Extending
-- 'Vulkan.Core13.Promoted_From_VK_KHR_dynamic_rendering.RenderingInfo':
--
-- - 'RenderingFragmentDensityMapAttachmentInfoEXT'
--
-- If
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_fragment_shading_rate VK_KHR_fragment_shading_rate>
-- is supported:
--
-- - Extending
-- 'Vulkan.Core13.Promoted_From_VK_KHR_dynamic_rendering.RenderingInfo':
--
-- - 'RenderingFragmentShadingRateAttachmentInfoKHR'
--
-- If
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_NV_framebuffer_mixed_samples VK_NV_framebuffer_mixed_samples>
-- is supported:
--
-- - Extending
-- 'Vulkan.Core10.CommandBuffer.CommandBufferInheritanceInfo',
-- 'Vulkan.Core10.Pipeline.GraphicsPipelineCreateInfo':
--
-- - 'AttachmentSampleCountInfoNV'
--
-- If
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_NVX_multiview_per_view_attributes VK_NVX_multiview_per_view_attributes>
-- is supported:
--
-- - Extending
-- 'Vulkan.Core10.CommandBuffer.CommandBufferInheritanceInfo',
-- 'Vulkan.Core10.Pipeline.GraphicsPipelineCreateInfo',
-- 'Vulkan.Core13.Promoted_From_VK_KHR_dynamic_rendering.RenderingInfo':
--
-- - 'MultiviewPerViewAttributesInfoNVX'
--
-- == New Enums
--
-- - 'RenderingFlagBitsKHR'
--
-- == New Bitmasks
--
-- - 'RenderingFlagsKHR'
--
-- == New Enum Constants
--
-- - 'KHR_DYNAMIC_RENDERING_EXTENSION_NAME'
--
-- - 'KHR_DYNAMIC_RENDERING_SPEC_VERSION'
--
-- - Extending 'Vulkan.Core10.Enums.AttachmentStoreOp.AttachmentStoreOp':
--
-- - 'ATTACHMENT_STORE_OP_NONE_KHR'
--
-- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType':
--
-- - 'STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_RENDERING_INFO_KHR'
--
-- - 'STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR'
--
-- - 'STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR'
--
-- - 'STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR'
--
-- - 'STRUCTURE_TYPE_RENDERING_INFO_KHR'
--
-- If
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_AMD_mixed_attachment_samples VK_AMD_mixed_attachment_samples>
-- is supported:
--
-- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType':
--
-- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_ATTACHMENT_SAMPLE_COUNT_INFO_AMD'
--
-- If
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_fragment_density_map VK_EXT_fragment_density_map>
-- is supported:
--
-- - Extending
-- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PipelineCreateFlagBits':
--
-- - 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RENDERING_FRAGMENT_DENSITY_MAP_ATTACHMENT_BIT_EXT'
--
-- - 'PIPELINE_RASTERIZATION_STATE_CREATE_FRAGMENT_DENSITY_MAP_ATTACHMENT_BIT_EXT'
--
-- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType':
--
-- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_RENDERING_FRAGMENT_DENSITY_MAP_ATTACHMENT_INFO_EXT'
--
-- If
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_fragment_shading_rate VK_KHR_fragment_shading_rate>
-- is supported:
--
-- - Extending
-- 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PipelineCreateFlagBits':
--
-- - 'Vulkan.Core10.Enums.PipelineCreateFlagBits.PIPELINE_CREATE_RENDERING_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR'
--
-- - 'PIPELINE_RASTERIZATION_STATE_CREATE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR'
--
-- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType':
--
-- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_RENDERING_FRAGMENT_SHADING_RATE_ATTACHMENT_INFO_KHR'
--
-- If
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_NV_framebuffer_mixed_samples VK_NV_framebuffer_mixed_samples>
-- is supported:
--
-- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType':
--
-- - 'STRUCTURE_TYPE_ATTACHMENT_SAMPLE_COUNT_INFO_NV'
--
-- If
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_NVX_multiview_per_view_attributes VK_NVX_multiview_per_view_attributes>
-- is supported:
--
-- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType':
--
-- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_MULTIVIEW_PER_VIEW_ATTRIBUTES_INFO_NVX'
--
-- == Promotion to Vulkan 1.3
--
-- Functionality in this extension is included in core Vulkan 1.3, with the
-- KHR suffix omitted. The original type, enum and command names are still
-- available as aliases of the core functionality.
--
-- == Version History
--
-- - Revision 1, 2021-10-06 (Tobias Hector)
--
-- - Initial revision
--
-- == See Also
--
-- 'CommandBufferInheritanceRenderingInfoKHR',
-- 'PhysicalDeviceDynamicRenderingFeaturesKHR',
-- 'PipelineRenderingCreateInfoKHR', 'RenderingAttachmentInfoKHR',
-- 'RenderingFlagBitsKHR', 'RenderingFlagsKHR', 'RenderingInfoKHR',
-- 'cmdBeginRenderingKHR', 'cmdEndRenderingKHR'
--
-- == Document Notes
--
-- For more information, see the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_KHR_dynamic_rendering Vulkan Specification>
--
-- This page is a generated document. Fixes and changes should be made to
-- the generator scripts, not directly.
module Vulkan.Extensions.VK_KHR_dynamic_rendering ( pattern STRUCTURE_TYPE_RENDERING_INFO_KHR
, pattern STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR
, pattern STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR
, pattern STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR
, pattern STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_RENDERING_INFO_KHR
, pattern ATTACHMENT_STORE_OP_NONE_KHR
, pattern PIPELINE_RASTERIZATION_STATE_CREATE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR
, pattern PIPELINE_RASTERIZATION_STATE_CREATE_FRAGMENT_DENSITY_MAP_ATTACHMENT_BIT_EXT
, pattern STRUCTURE_TYPE_ATTACHMENT_SAMPLE_COUNT_INFO_NV
, cmdBeginRenderingKHR
, cmdEndRenderingKHR
, RenderingFragmentShadingRateAttachmentInfoKHR(..)
, RenderingFragmentDensityMapAttachmentInfoEXT(..)
, AttachmentSampleCountInfoAMD(..)
, MultiviewPerViewAttributesInfoNVX(..)
, RenderingFlagsKHR
, RenderingFlagBitsKHR
, PipelineRenderingCreateInfoKHR
, RenderingInfoKHR
, RenderingAttachmentInfoKHR
, PhysicalDeviceDynamicRenderingFeaturesKHR
, CommandBufferInheritanceRenderingInfoKHR
, AttachmentSampleCountInfoNV
, KHR_DYNAMIC_RENDERING_SPEC_VERSION
, pattern KHR_DYNAMIC_RENDERING_SPEC_VERSION
, KHR_DYNAMIC_RENDERING_EXTENSION_NAME
, pattern KHR_DYNAMIC_RENDERING_EXTENSION_NAME
) where
import Foreign.Marshal.Alloc (allocaBytes)
import Foreign.Ptr (nullPtr)
import Foreign.Ptr (plusPtr)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Cont (evalContT)
import Data.Vector (generateM)
import qualified Data.Vector (imapM_)
import qualified Data.Vector (length)
import Vulkan.CStruct (FromCStruct)
import Vulkan.CStruct (FromCStruct(..))
import Vulkan.CStruct (ToCStruct)
import Vulkan.CStruct (ToCStruct(..))
import Vulkan.Zero (Zero(..))
import Data.String (IsString)
import Data.Typeable (Typeable)
import Foreign.Storable (Storable)
import Foreign.Storable (Storable(peek))
import Foreign.Storable (Storable(poke))
import qualified Foreign.Storable (Storable(..))
import GHC.Generics (Generic)
import Foreign.Ptr (Ptr)
import Data.Word (Word32)
import Data.Kind (Type)
import Control.Monad.Trans.Cont (ContT(..))
import Data.Vector (Vector)
import Vulkan.CStruct.Utils (advancePtrBytes)
import Vulkan.Core10.FundamentalTypes (bool32ToBool)
import Vulkan.Core10.FundamentalTypes (boolToBool32)
import Vulkan.Core13.Promoted_From_VK_KHR_dynamic_rendering (cmdBeginRendering)
import Vulkan.Core13.Promoted_From_VK_KHR_dynamic_rendering (cmdEndRendering)
import Vulkan.Core10.FundamentalTypes (Bool32)
import Vulkan.Core13.Promoted_From_VK_KHR_dynamic_rendering (CommandBufferInheritanceRenderingInfo)
import Vulkan.Core10.FundamentalTypes (Extent2D)
import Vulkan.Core10.Enums.ImageLayout (ImageLayout)
import Vulkan.Core10.Handles (ImageView)
import Vulkan.Core13.Promoted_From_VK_KHR_dynamic_rendering (PhysicalDeviceDynamicRenderingFeatures)
import Vulkan.Core13.Promoted_From_VK_KHR_dynamic_rendering (PipelineRenderingCreateInfo)
import Vulkan.Core13.Promoted_From_VK_KHR_dynamic_rendering (RenderingAttachmentInfo)
import Vulkan.Core13.Enums.RenderingFlagBits (RenderingFlagBits)
import Vulkan.Core13.Enums.RenderingFlagBits (RenderingFlags)
import Vulkan.Core13.Promoted_From_VK_KHR_dynamic_rendering (RenderingInfo)
import Vulkan.Core10.Enums.SampleCountFlagBits (SampleCountFlagBits)
import Vulkan.Core10.Enums.StructureType (StructureType)
import Vulkan.Core10.Enums.AttachmentStoreOp (AttachmentStoreOp(ATTACHMENT_STORE_OP_NONE))
import Vulkan.Core10.Enums.PipelineCreateFlagBits (PipelineCreateFlags)
import Vulkan.Core10.Enums.PipelineCreateFlagBits (PipelineCreateFlagBits(PIPELINE_CREATE_RENDERING_FRAGMENT_DENSITY_MAP_ATTACHMENT_BIT_EXT))
import Vulkan.Core10.Enums.PipelineCreateFlagBits (PipelineCreateFlags)
import Vulkan.Core10.Enums.PipelineCreateFlagBits (PipelineCreateFlagBits(PIPELINE_CREATE_RENDERING_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_ATTACHMENT_SAMPLE_COUNT_INFO_AMD))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_RENDERING_INFO))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_MULTIVIEW_PER_VIEW_ATTRIBUTES_INFO_NVX))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_RENDERING_FRAGMENT_DENSITY_MAP_ATTACHMENT_INFO_EXT))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_RENDERING_FRAGMENT_SHADING_RATE_ATTACHMENT_INFO_KHR))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_RENDERING_INFO))
-- No documentation found for TopLevel "VK_STRUCTURE_TYPE_RENDERING_INFO_KHR"
pattern STRUCTURE_TYPE_RENDERING_INFO_KHR = STRUCTURE_TYPE_RENDERING_INFO
-- No documentation found for TopLevel "VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR"
pattern STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR = STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO
-- No documentation found for TopLevel "VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR"
pattern STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR = STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO
-- No documentation found for TopLevel "VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR"
pattern STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR = STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES
-- No documentation found for TopLevel "VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_RENDERING_INFO_KHR"
pattern STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_RENDERING_INFO_KHR = STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_RENDERING_INFO
-- No documentation found for TopLevel "VK_ATTACHMENT_STORE_OP_NONE_KHR"
pattern ATTACHMENT_STORE_OP_NONE_KHR = ATTACHMENT_STORE_OP_NONE
-- No documentation found for TopLevel "VK_PIPELINE_RASTERIZATION_STATE_CREATE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR"
pattern PIPELINE_RASTERIZATION_STATE_CREATE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR = PIPELINE_CREATE_RENDERING_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR
-- No documentation found for TopLevel "VK_PIPELINE_RASTERIZATION_STATE_CREATE_FRAGMENT_DENSITY_MAP_ATTACHMENT_BIT_EXT"
pattern PIPELINE_RASTERIZATION_STATE_CREATE_FRAGMENT_DENSITY_MAP_ATTACHMENT_BIT_EXT = PIPELINE_CREATE_RENDERING_FRAGMENT_DENSITY_MAP_ATTACHMENT_BIT_EXT
-- No documentation found for TopLevel "VK_STRUCTURE_TYPE_ATTACHMENT_SAMPLE_COUNT_INFO_NV"
pattern STRUCTURE_TYPE_ATTACHMENT_SAMPLE_COUNT_INFO_NV = STRUCTURE_TYPE_ATTACHMENT_SAMPLE_COUNT_INFO_AMD
-- No documentation found for TopLevel "vkCmdBeginRenderingKHR"
cmdBeginRenderingKHR = cmdBeginRendering
-- No documentation found for TopLevel "vkCmdEndRenderingKHR"
cmdEndRenderingKHR = cmdEndRendering
-- | VkRenderingFragmentShadingRateAttachmentInfoKHR - Structure specifying
-- fragment shading rate attachment information
--
-- = Description
--
-- This structure can be included in the @pNext@ chain of
-- 'Vulkan.Core13.Promoted_From_VK_KHR_dynamic_rendering.RenderingInfo' to
-- define a
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#primsrast-fragment-shading-rate-attachment fragment shading rate attachment>.
-- If @imageView@ is 'Vulkan.Core10.APIConstants.NULL_HANDLE', or if this
-- structure is not specified, the implementation behaves as if a valid
-- shading rate attachment was specified with all texels specifying a
-- single pixel per fragment.
--
-- == Valid Usage
--
-- - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageView-06147#
-- If @imageView@ is not 'Vulkan.Core10.APIConstants.NULL_HANDLE',
-- @layout@ /must/ be
-- 'Vulkan.Core10.Enums.ImageLayout.IMAGE_LAYOUT_GENERAL' or
-- 'Vulkan.Core10.Enums.ImageLayout.IMAGE_LAYOUT_FRAGMENT_SHADING_RATE_ATTACHMENT_OPTIMAL_KHR'
--
-- - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageView-06148#
-- If @imageView@ is not 'Vulkan.Core10.APIConstants.NULL_HANDLE', it
-- /must/ have been created with
-- 'Vulkan.Core10.Enums.ImageUsageFlagBits.IMAGE_USAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR'
--
-- - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageView-06149#
-- If @imageView@ is not 'Vulkan.Core10.APIConstants.NULL_HANDLE',
-- @shadingRateAttachmentTexelSize.width@ /must/ be a power of two
-- value
--
-- - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageView-06150#
-- If @imageView@ is not 'Vulkan.Core10.APIConstants.NULL_HANDLE',
-- @shadingRateAttachmentTexelSize.width@ /must/ be less than or equal
-- to
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#limits-maxFragmentShadingRateAttachmentTexelSize maxFragmentShadingRateAttachmentTexelSize.width>
--
-- - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageView-06151#
-- If @imageView@ is not 'Vulkan.Core10.APIConstants.NULL_HANDLE',
-- @shadingRateAttachmentTexelSize.width@ /must/ be greater than or
-- equal to
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#limits-minFragmentShadingRateAttachmentTexelSize minFragmentShadingRateAttachmentTexelSize.width>
--
-- - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageView-06152#
-- If @imageView@ is not 'Vulkan.Core10.APIConstants.NULL_HANDLE',
-- @shadingRateAttachmentTexelSize.height@ /must/ be a power of two
-- value
--
-- - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageView-06153#
-- If @imageView@ is not 'Vulkan.Core10.APIConstants.NULL_HANDLE',
-- @shadingRateAttachmentTexelSize.height@ /must/ be less than or equal
-- to
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#limits-maxFragmentShadingRateAttachmentTexelSize maxFragmentShadingRateAttachmentTexelSize.height>
--
-- - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageView-06154#
-- If @imageView@ is not 'Vulkan.Core10.APIConstants.NULL_HANDLE',
-- @shadingRateAttachmentTexelSize.height@ /must/ be greater than or
-- equal to
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#limits-minFragmentShadingRateAttachmentTexelSize minFragmentShadingRateAttachmentTexelSize.height>
--
-- - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageView-06155#
-- If @imageView@ is not 'Vulkan.Core10.APIConstants.NULL_HANDLE', the
-- quotient of @shadingRateAttachmentTexelSize.width@ and
-- @shadingRateAttachmentTexelSize.height@ /must/ be less than or equal
-- to
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#limits-maxFragmentShadingRateAttachmentTexelSizeAspectRatio maxFragmentShadingRateAttachmentTexelSizeAspectRatio>
--
-- - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageView-06156#
-- If @imageView@ is not 'Vulkan.Core10.APIConstants.NULL_HANDLE', the
-- quotient of @shadingRateAttachmentTexelSize.height@ and
-- @shadingRateAttachmentTexelSize.width@ /must/ be less than or equal
-- to
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#limits-maxFragmentShadingRateAttachmentTexelSizeAspectRatio maxFragmentShadingRateAttachmentTexelSizeAspectRatio>
--
-- == Valid Usage (Implicit)
--
-- - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-sType-sType#
-- @sType@ /must/ be
-- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_RENDERING_FRAGMENT_SHADING_RATE_ATTACHMENT_INFO_KHR'
--
-- - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageView-parameter#
-- If @imageView@ is not 'Vulkan.Core10.APIConstants.NULL_HANDLE',
-- @imageView@ /must/ be a valid 'Vulkan.Core10.Handles.ImageView'
-- handle
--
-- - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageLayout-parameter#
-- @imageLayout@ /must/ be a valid
-- 'Vulkan.Core10.Enums.ImageLayout.ImageLayout' value
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_dynamic_rendering VK_KHR_dynamic_rendering>,
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_fragment_shading_rate VK_KHR_fragment_shading_rate>,
-- 'Vulkan.Core10.FundamentalTypes.Extent2D',
-- 'Vulkan.Core10.Enums.ImageLayout.ImageLayout',
-- 'Vulkan.Core10.Handles.ImageView',
-- 'Vulkan.Core10.Enums.StructureType.StructureType'
data RenderingFragmentShadingRateAttachmentInfoKHR = RenderingFragmentShadingRateAttachmentInfoKHR
{ -- | @imageView@ is the image view that will be used as a fragment shading
-- rate attachment.
imageView :: ImageView
, -- | @imageLayout@ is the layout that @imageView@ will be in during
-- rendering.
imageLayout :: ImageLayout
, -- | @shadingRateAttachmentTexelSize@ specifies the number of pixels
-- corresponding to each texel in @imageView@.
shadingRateAttachmentTexelSize :: Extent2D
}
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (RenderingFragmentShadingRateAttachmentInfoKHR)
#endif
deriving instance Show RenderingFragmentShadingRateAttachmentInfoKHR
instance ToCStruct RenderingFragmentShadingRateAttachmentInfoKHR where
withCStruct x f = allocaBytes 40 $ \p -> pokeCStruct p x (f p)
pokeCStruct p RenderingFragmentShadingRateAttachmentInfoKHR{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_RENDERING_FRAGMENT_SHADING_RATE_ATTACHMENT_INFO_KHR)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr ImageView)) (imageView)
poke ((p `plusPtr` 24 :: Ptr ImageLayout)) (imageLayout)
poke ((p `plusPtr` 28 :: Ptr Extent2D)) (shadingRateAttachmentTexelSize)
f
cStructSize = 40
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_RENDERING_FRAGMENT_SHADING_RATE_ATTACHMENT_INFO_KHR)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 24 :: Ptr ImageLayout)) (zero)
poke ((p `plusPtr` 28 :: Ptr Extent2D)) (zero)
f
instance FromCStruct RenderingFragmentShadingRateAttachmentInfoKHR where
peekCStruct p = do
imageView <- peek @ImageView ((p `plusPtr` 16 :: Ptr ImageView))
imageLayout <- peek @ImageLayout ((p `plusPtr` 24 :: Ptr ImageLayout))
shadingRateAttachmentTexelSize <- peekCStruct @Extent2D ((p `plusPtr` 28 :: Ptr Extent2D))
pure $ RenderingFragmentShadingRateAttachmentInfoKHR
imageView imageLayout shadingRateAttachmentTexelSize
instance Storable RenderingFragmentShadingRateAttachmentInfoKHR where
sizeOf ~_ = 40
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero RenderingFragmentShadingRateAttachmentInfoKHR where
zero = RenderingFragmentShadingRateAttachmentInfoKHR
zero
zero
zero
-- | VkRenderingFragmentDensityMapAttachmentInfoEXT - Structure specifying
-- fragment shading rate attachment information
--
-- = Description
--
-- This structure can be included in the @pNext@ chain of
-- 'Vulkan.Core13.Promoted_From_VK_KHR_dynamic_rendering.RenderingInfo' to
-- define a fragment density map. If this structure is not included in the
-- @pNext@ chain, @imageView@ is treated as
-- 'Vulkan.Core10.APIConstants.NULL_HANDLE'.
--
-- == Valid Usage
--
-- - #VUID-VkRenderingFragmentDensityMapAttachmentInfoEXT-imageView-06157#
-- If @imageView@ is not 'Vulkan.Core10.APIConstants.NULL_HANDLE',
-- @layout@ /must/ be
-- 'Vulkan.Core10.Enums.ImageLayout.IMAGE_LAYOUT_GENERAL' or
-- 'Vulkan.Core10.Enums.ImageLayout.IMAGE_LAYOUT_FRAGMENT_DENSITY_MAP_OPTIMAL_EXT'
--
-- - #VUID-VkRenderingFragmentDensityMapAttachmentInfoEXT-imageView-06158#
-- If @imageView@ is not 'Vulkan.Core10.APIConstants.NULL_HANDLE', it
-- /must/ have been created with
-- 'Vulkan.Core10.Enums.ImageUsageFlagBits.IMAGE_USAGE_FRAGMENT_DENSITY_MAP_BIT_EXT'
--
-- - #VUID-VkRenderingFragmentDensityMapAttachmentInfoEXT-imageView-06159#
-- If @imageView@ is not 'Vulkan.Core10.APIConstants.NULL_HANDLE', it
-- /must/ not have been created with
-- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_SUBSAMPLED_BIT_EXT'
--
-- == Valid Usage (Implicit)
--
-- - #VUID-VkRenderingFragmentDensityMapAttachmentInfoEXT-sType-sType#
-- @sType@ /must/ be
-- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_RENDERING_FRAGMENT_DENSITY_MAP_ATTACHMENT_INFO_EXT'
--
-- - #VUID-VkRenderingFragmentDensityMapAttachmentInfoEXT-imageView-parameter#
-- @imageView@ /must/ be a valid 'Vulkan.Core10.Handles.ImageView'
-- handle
--
-- - #VUID-VkRenderingFragmentDensityMapAttachmentInfoEXT-imageLayout-parameter#
-- @imageLayout@ /must/ be a valid
-- 'Vulkan.Core10.Enums.ImageLayout.ImageLayout' value
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_fragment_density_map VK_EXT_fragment_density_map>,
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_dynamic_rendering VK_KHR_dynamic_rendering>,
-- 'Vulkan.Core10.Enums.ImageLayout.ImageLayout',
-- 'Vulkan.Core10.Handles.ImageView',
-- 'Vulkan.Core10.Enums.StructureType.StructureType'
data RenderingFragmentDensityMapAttachmentInfoEXT = RenderingFragmentDensityMapAttachmentInfoEXT
{ -- | @imageView@ is the image view that will be used as a fragment shading
-- rate attachment.
imageView :: ImageView
, -- | @imageLayout@ is the layout that @imageView@ will be in during
-- rendering.
imageLayout :: ImageLayout
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (RenderingFragmentDensityMapAttachmentInfoEXT)
#endif
deriving instance Show RenderingFragmentDensityMapAttachmentInfoEXT
instance ToCStruct RenderingFragmentDensityMapAttachmentInfoEXT where
withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p)
pokeCStruct p RenderingFragmentDensityMapAttachmentInfoEXT{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_RENDERING_FRAGMENT_DENSITY_MAP_ATTACHMENT_INFO_EXT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr ImageView)) (imageView)
poke ((p `plusPtr` 24 :: Ptr ImageLayout)) (imageLayout)
f
cStructSize = 32
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_RENDERING_FRAGMENT_DENSITY_MAP_ATTACHMENT_INFO_EXT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr ImageView)) (zero)
poke ((p `plusPtr` 24 :: Ptr ImageLayout)) (zero)
f
instance FromCStruct RenderingFragmentDensityMapAttachmentInfoEXT where
peekCStruct p = do
imageView <- peek @ImageView ((p `plusPtr` 16 :: Ptr ImageView))
imageLayout <- peek @ImageLayout ((p `plusPtr` 24 :: Ptr ImageLayout))
pure $ RenderingFragmentDensityMapAttachmentInfoEXT
imageView imageLayout
instance Storable RenderingFragmentDensityMapAttachmentInfoEXT where
sizeOf ~_ = 32
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero RenderingFragmentDensityMapAttachmentInfoEXT where
zero = RenderingFragmentDensityMapAttachmentInfoEXT
zero
zero
-- | VkAttachmentSampleCountInfoAMD - Structure specifying command buffer
-- inheritance info for dynamic render pass instances
--
-- = Description
--
-- If
-- 'Vulkan.Core10.CommandBuffer.CommandBufferInheritanceInfo'::@renderPass@
-- is 'Vulkan.Core10.APIConstants.NULL_HANDLE',
-- 'Vulkan.Core10.Enums.CommandBufferUsageFlagBits.COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT'
-- is specified in
-- 'Vulkan.Core10.CommandBuffer.CommandBufferBeginInfo'::@flags@, and the
-- @pNext@ chain of
-- 'Vulkan.Core10.CommandBuffer.CommandBufferInheritanceInfo' includes
-- 'AttachmentSampleCountInfoAMD', then this structure defines the sample
-- counts of each attachment within the render pass instance. If
-- 'AttachmentSampleCountInfoAMD' is not included, the value of
-- 'Vulkan.Core13.Promoted_From_VK_KHR_dynamic_rendering.CommandBufferInheritanceRenderingInfo'::@rasterizationSamples@
-- is used as the sample count for each attachment. If
-- 'Vulkan.Core10.CommandBuffer.CommandBufferInheritanceInfo'::@renderPass@
-- is not 'Vulkan.Core10.APIConstants.NULL_HANDLE', or
-- 'Vulkan.Core10.Enums.CommandBufferUsageFlagBits.COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT'
-- is not specified in
-- 'Vulkan.Core10.CommandBuffer.CommandBufferBeginInfo'::@flags@,
-- parameters of this structure are ignored.
--
-- 'AttachmentSampleCountInfoAMD' /can/ also be included in the @pNext@
-- chain of 'Vulkan.Core10.Pipeline.GraphicsPipelineCreateInfo'. When a
-- graphics pipeline is created without a
-- 'Vulkan.Core10.Handles.RenderPass', if this structure is present in the
-- @pNext@ chain of 'Vulkan.Core10.Pipeline.GraphicsPipelineCreateInfo', it
-- specifies the sample count of attachments used for rendering. If this
-- structure is not specified, and the pipeline does not include a
-- 'Vulkan.Core10.Handles.RenderPass', the value of
-- 'Vulkan.Core10.Pipeline.PipelineMultisampleStateCreateInfo'::@rasterizationSamples@
-- is used as the sample count for each attachment. If a graphics pipeline
-- is created with a valid 'Vulkan.Core10.Handles.RenderPass', parameters
-- of this structure are ignored.
--
-- == Valid Usage (Implicit)
--
-- - #VUID-VkAttachmentSampleCountInfoAMD-sType-sType# @sType@ /must/ be
-- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_ATTACHMENT_SAMPLE_COUNT_INFO_AMD'
--
-- - #VUID-VkAttachmentSampleCountInfoAMD-pColorAttachmentSamples-parameter#
-- If @colorAttachmentCount@ is not @0@, @pColorAttachmentSamples@
-- /must/ be a valid pointer to an array of @colorAttachmentCount@
-- valid 'Vulkan.Core10.Enums.SampleCountFlagBits.SampleCountFlagBits'
-- values
--
-- - #VUID-VkAttachmentSampleCountInfoAMD-depthStencilAttachmentSamples-parameter#
-- If @depthStencilAttachmentSamples@ is not @0@,
-- @depthStencilAttachmentSamples@ /must/ be a valid
-- 'Vulkan.Core10.Enums.SampleCountFlagBits.SampleCountFlagBits' value
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_AMD_mixed_attachment_samples VK_AMD_mixed_attachment_samples>,
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_dynamic_rendering VK_KHR_dynamic_rendering>,
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_NV_framebuffer_mixed_samples VK_NV_framebuffer_mixed_samples>,
-- 'Vulkan.Core10.Enums.SampleCountFlagBits.SampleCountFlagBits',
-- 'Vulkan.Core10.Enums.StructureType.StructureType'
data AttachmentSampleCountInfoAMD = AttachmentSampleCountInfoAMD
{ -- | @pColorAttachmentSamples@ is a pointer to an array of
-- 'Vulkan.Core10.Enums.SampleCountFlagBits.SampleCountFlagBits' values
-- defining the sample count of color attachments.
colorAttachmentSamples :: Vector SampleCountFlagBits
, -- | @depthStencilAttachmentSamples@ is a
-- 'Vulkan.Core10.Enums.SampleCountFlagBits.SampleCountFlagBits' value
-- defining the sample count of a depth\/stencil attachment.
depthStencilAttachmentSamples :: SampleCountFlagBits
}
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (AttachmentSampleCountInfoAMD)
#endif
deriving instance Show AttachmentSampleCountInfoAMD
instance ToCStruct AttachmentSampleCountInfoAMD where
withCStruct x f = allocaBytes 40 $ \p -> pokeCStruct p x (f p)
pokeCStruct p AttachmentSampleCountInfoAMD{..} f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_ATTACHMENT_SAMPLE_COUNT_INFO_AMD)
lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
lift $ poke ((p `plusPtr` 16 :: Ptr Word32)) ((fromIntegral (Data.Vector.length $ (colorAttachmentSamples)) :: Word32))
pPColorAttachmentSamples' <- ContT $ allocaBytes @SampleCountFlagBits ((Data.Vector.length (colorAttachmentSamples)) * 4)
lift $ Data.Vector.imapM_ (\i e -> poke (pPColorAttachmentSamples' `plusPtr` (4 * (i)) :: Ptr SampleCountFlagBits) (e)) (colorAttachmentSamples)
lift $ poke ((p `plusPtr` 24 :: Ptr (Ptr SampleCountFlagBits))) (pPColorAttachmentSamples')
lift $ poke ((p `plusPtr` 32 :: Ptr SampleCountFlagBits)) (depthStencilAttachmentSamples)
lift $ f
cStructSize = 40
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_ATTACHMENT_SAMPLE_COUNT_INFO_AMD)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
f
instance FromCStruct AttachmentSampleCountInfoAMD where
peekCStruct p = do
colorAttachmentCount <- peek @Word32 ((p `plusPtr` 16 :: Ptr Word32))
pColorAttachmentSamples <- peek @(Ptr SampleCountFlagBits) ((p `plusPtr` 24 :: Ptr (Ptr SampleCountFlagBits)))
pColorAttachmentSamples' <- generateM (fromIntegral colorAttachmentCount) (\i -> peek @SampleCountFlagBits ((pColorAttachmentSamples `advancePtrBytes` (4 * (i)) :: Ptr SampleCountFlagBits)))
depthStencilAttachmentSamples <- peek @SampleCountFlagBits ((p `plusPtr` 32 :: Ptr SampleCountFlagBits))
pure $ AttachmentSampleCountInfoAMD
pColorAttachmentSamples' depthStencilAttachmentSamples
instance Zero AttachmentSampleCountInfoAMD where
zero = AttachmentSampleCountInfoAMD
mempty
zero
-- | VkMultiviewPerViewAttributesInfoNVX - Structure specifying the multiview
-- per-attribute properties
--
-- = Description
--
-- When dynamic render pass instances are being used, instead of specifying
-- 'Vulkan.Core10.Enums.SubpassDescriptionFlagBits.SUBPASS_DESCRIPTION_PER_VIEW_ATTRIBUTES_BIT_NVX'
-- or
-- 'Vulkan.Core10.Enums.SubpassDescriptionFlagBits.SUBPASS_DESCRIPTION_PER_VIEW_POSITION_X_ONLY_BIT_NVX'
-- in the subpass description flags, the per-attibute properties of the
-- render pass instance /must/ be specified by the
-- 'MultiviewPerViewAttributesInfoNVX' structure Include the
-- 'MultiviewPerViewAttributesInfoNVX' structure in the @pNext@ chain of
-- 'Vulkan.Core10.Pipeline.GraphicsPipelineCreateInfo' when creating a
-- graphics pipeline for dynamic rendering,
-- 'Vulkan.Core13.Promoted_From_VK_KHR_dynamic_rendering.RenderingInfo'
-- when starting a dynamic render pass instance, and
-- 'Vulkan.Core10.CommandBuffer.CommandBufferInheritanceInfo' when
-- specifying the dynamic render pass instance parameters for secondary
-- command buffers.
--
-- == Valid Usage
--
-- - #VUID-VkMultiviewPerViewAttributesInfoNVX-perViewAttributesPositionXOnly-06163#
-- If @perViewAttributesPositionXOnly@ is
-- 'Vulkan.Core10.FundamentalTypes.TRUE' then @perViewAttributes@
-- /must/ also be 'Vulkan.Core10.FundamentalTypes.TRUE'
--
-- == Valid Usage (Implicit)
--
-- - #VUID-VkMultiviewPerViewAttributesInfoNVX-sType-sType# @sType@
-- /must/ be
-- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_MULTIVIEW_PER_VIEW_ATTRIBUTES_INFO_NVX'
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_dynamic_rendering VK_KHR_dynamic_rendering>,
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_NVX_multiview_per_view_attributes VK_NVX_multiview_per_view_attributes>,
-- 'Vulkan.Core10.FundamentalTypes.Bool32',
-- 'Vulkan.Core10.Enums.StructureType.StructureType'
data MultiviewPerViewAttributesInfoNVX = MultiviewPerViewAttributesInfoNVX
{ -- | @perViewAttributes@ specifies that shaders compiled for this pipeline
-- write the attributes for all views in a single invocation of each vertex
-- processing stage. All pipelines executed within a render pass instance
-- that includes this bit /must/ write per-view attributes to the
-- @*PerViewNV[]@ shader outputs, in addition to the non-per-view (e.g.
-- @Position@) outputs.
perViewAttributes :: Bool
, -- | @perViewAttributesPositionXOnly@ specifies that shaders compiled for
-- this pipeline use per-view positions which only differ in value in the x
-- component. Per-view viewport mask /can/ also be used.
perViewAttributesPositionXOnly :: Bool
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (MultiviewPerViewAttributesInfoNVX)
#endif
deriving instance Show MultiviewPerViewAttributesInfoNVX
instance ToCStruct MultiviewPerViewAttributesInfoNVX where
withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p)
pokeCStruct p MultiviewPerViewAttributesInfoNVX{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_MULTIVIEW_PER_VIEW_ATTRIBUTES_INFO_NVX)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (perViewAttributes))
poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (perViewAttributesPositionXOnly))
f
cStructSize = 24
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_MULTIVIEW_PER_VIEW_ATTRIBUTES_INFO_NVX)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero))
poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (zero))
f
instance FromCStruct MultiviewPerViewAttributesInfoNVX where
peekCStruct p = do
perViewAttributes <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32))
perViewAttributesPositionXOnly <- peek @Bool32 ((p `plusPtr` 20 :: Ptr Bool32))
pure $ MultiviewPerViewAttributesInfoNVX
(bool32ToBool perViewAttributes) (bool32ToBool perViewAttributesPositionXOnly)
instance Storable MultiviewPerViewAttributesInfoNVX where
sizeOf ~_ = 24
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero MultiviewPerViewAttributesInfoNVX where
zero = MultiviewPerViewAttributesInfoNVX
zero
zero
-- No documentation found for TopLevel "VkRenderingFlagsKHR"
type RenderingFlagsKHR = RenderingFlags
-- No documentation found for TopLevel "VkRenderingFlagBitsKHR"
type RenderingFlagBitsKHR = RenderingFlagBits
-- No documentation found for TopLevel "VkPipelineRenderingCreateInfoKHR"
type PipelineRenderingCreateInfoKHR = PipelineRenderingCreateInfo
-- No documentation found for TopLevel "VkRenderingInfoKHR"
type RenderingInfoKHR = RenderingInfo
-- No documentation found for TopLevel "VkRenderingAttachmentInfoKHR"
type RenderingAttachmentInfoKHR = RenderingAttachmentInfo
-- No documentation found for TopLevel "VkPhysicalDeviceDynamicRenderingFeaturesKHR"
type PhysicalDeviceDynamicRenderingFeaturesKHR = PhysicalDeviceDynamicRenderingFeatures
-- No documentation found for TopLevel "VkCommandBufferInheritanceRenderingInfoKHR"
type CommandBufferInheritanceRenderingInfoKHR = CommandBufferInheritanceRenderingInfo
-- No documentation found for TopLevel "VkAttachmentSampleCountInfoNV"
type AttachmentSampleCountInfoNV = AttachmentSampleCountInfoAMD
type KHR_DYNAMIC_RENDERING_SPEC_VERSION = 1
-- No documentation found for TopLevel "VK_KHR_DYNAMIC_RENDERING_SPEC_VERSION"
pattern KHR_DYNAMIC_RENDERING_SPEC_VERSION :: forall a . Integral a => a
pattern KHR_DYNAMIC_RENDERING_SPEC_VERSION = 1
type KHR_DYNAMIC_RENDERING_EXTENSION_NAME = "VK_KHR_dynamic_rendering"
-- No documentation found for TopLevel "VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME"
pattern KHR_DYNAMIC_RENDERING_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern KHR_DYNAMIC_RENDERING_EXTENSION_NAME = "VK_KHR_dynamic_rendering"
| expipiplus1/vulkan | src/Vulkan/Extensions/VK_KHR_dynamic_rendering.hs | bsd-3-clause | 42,110 | 0 | 18 | 6,097 | 4,100 | 2,549 | 1,551 | -1 | -1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE IncoherentInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE UndecidableInstances #-}
module Language.Rsc.Pretty.Module where
import qualified Language.Fixpoint.Types as F
import Language.Rsc.Module
import Language.Rsc.Pretty.Common
import Language.Rsc.Pretty.Symbols ()
import Text.PrettyPrint.HughesPJ
instance (PP r, F.Reftable r) => PP (ModuleDef r) where
pp (ModuleDef vars tys enums path) =
pp (take 80 (repeat '-'))
$+$ text "module" <+> pp path
$+$ pp (take 80 (repeat '-'))
$+$ text "Variables" $+$ nest 4 (pp vars)
$+$ text "Types" $+$ nest 4 (pp tys)
$+$ text "Enums" $+$ nest 4 (pp enums)
| UCSD-PL/RefScript | src/Language/Rsc/Pretty/Module.hs | bsd-3-clause | 1,224 | 0 | 19 | 347 | 229 | 127 | 102 | 28 | 0 |
module Ivory.OS.FreeRTOS
( kernel
, wrapper
, objects
, Config(..)
, defaultConfig
) where
import System.FilePath
import qualified Paths_ivory_freertos_bindings as P
import Ivory.Artifact
import Ivory.OS.FreeRTOS.Config
kernel :: Config -> [Located Artifact]
kernel conf = configHeader conf : kas
where
kas = map loc kernelfiles
wrapper :: [Located Artifact]
wrapper = map loc wrapperfiles
loc :: FilePath -> Located Artifact
loc f = l $ artifactCabalFile P.getDataDir f
where
l = case takeExtension f of
".h" -> Incl
".c" -> Src
_ -> Root
wrapperfiles :: [FilePath]
wrapperfiles =
[ "wrapper/freertos_atomic_wrapper.h"
, "wrapper/freertos_atomic_wrapper.c"
, "wrapper/freertos_semaphore_wrapper.h"
, "wrapper/freertos_semaphore_wrapper.c"
, "wrapper/freertos_mutex_wrapper.h"
, "wrapper/freertos_mutex_wrapper.c"
, "wrapper/freertos_task_wrapper.h"
, "wrapper/freertos_task_wrapper.c"
, "wrapper/freertos_time_wrapper.h"
, "wrapper/freertos_time_wrapper.c"
]
kernelfiles :: [FilePath]
kernelfiles =
[ "freertos-sources/list.c"
, "freertos-sources/queue.c"
, "freertos-sources/tasks.c"
, "freertos-sources/timers.c"
, "freertos-sources/include/FreeRTOS.h"
, "freertos-sources/include/StackMacros.h"
, "freertos-sources/include/list.h"
, "freertos-sources/include/mpu_wrappers.h"
, "freertos-sources/include/portable.h"
, "freertos-sources/include/projdefs.h"
, "freertos-sources/include/queue.h"
, "freertos-sources/include/semphr.h"
, "freertos-sources/include/task.h"
, "freertos-sources/include/timers.h"
, "freertos-sources/include/deprecated_definitions.h"
, "freertos-sources/portable/GCC/ARM_CM4F/port.c"
, "freertos-sources/portable/GCC/ARM_CM4F/portmacro.h"
, "freertos-sources/portable/MemMang/heap_1.c"
, "syscalls/assert.h"
, "syscalls/syscalls.c"
]
objects :: [FilePath]
objects = map (\f -> replaceExtension f "o") sources
sources :: [FilePath]
sources = filter (\f -> takeExtension f == ".c")
$ map takeFileName ( wrapperfiles ++ kernelfiles )
defaultConfig :: Config
defaultConfig = Config
{ cpu_clock_hz = 168 * 1000 * 1000
, tick_rate_hz = 1000
, max_priorities = 5
, minimal_stack_size = 256
, total_heap_size = 64 * 1024
}
| GaloisInc/ivory-tower-stm32 | ivory-freertos-bindings/src/Ivory/OS/FreeRTOS.hs | bsd-3-clause | 2,289 | 0 | 10 | 366 | 425 | 249 | 176 | 67 | 3 |
{-# LANGUAGE ImplicitParams, FlexibleContexts #-}
module Frontend.TVarOps(varMapExpr, varType) where
import Control.Monad.Error
import TSLUtil
import Pos
import Name
import Frontend.Spec
import Frontend.NS
import Frontend.TVar
import Frontend.Type
import Frontend.TypeOps
import Frontend.Expr
import {-# SOURCE #-} Frontend.ExprOps
varMapExpr :: (?spec::Spec) => (Scope -> Expr -> Expr) -> Scope -> Var -> Var
varMapExpr f s v = Var (pos v) (varMem v) (tspecMapExpr f s $ tspec v) (name v) (fmap (mapExpr f s) $ varInit v)
varType :: (?spec::Spec, ?scope::Scope) => Var -> Type
varType = Type ?scope . tspec
| termite2/tsl | Frontend/TVarOps.hs | bsd-3-clause | 613 | 0 | 10 | 93 | 216 | 121 | 95 | 17 | 1 |
{-# LANGUAGE TypeSynonymInstances #-}
-- | This module contains a number of utility functions useful for converting
-- Lava circuits to the Netlist AST.
module Language.KansasLava.Netlist.Utils
(
ToTypedExpr(..),
ToStdLogicExpr(..), toStdLogicTy,
AddNext(..),
toIntegerExpr,
sizedRange, sigName,
isHigh,
lookupInput, lookupInputType,
-- Needed for Inst
isMatrixStdLogicTy, isStdLogicTy, isStdLogicVectorTy,
sanitizeName,
active_high, stdLogicToMem, memToStdLogic,
addNum, prodSlices, toMemIndex,
mkExprConcat,
assignStmt, assignDecl
) where
import Language.KansasLava.Types
import Language.Netlist.AST hiding (U)
import Language.Netlist.Util
import Language.KansasLava.Rep
import Data.Reify.Graph (Unique)
import Data.List(find,mapAccumL)
-- There are three type "classes" in our generated VHDL.
-- 1. std_logic_vector
-- 2. signed/unsigned
-- 3. integer, as used to index into arrays, etc.
-- Turn a signal of std_logic[_vector], and
-- turn it into a Typed logic Expr. (signed, unsigned, or as is)
-- based on the given type.
-- | Convert a Lava value of a given type into a Netlist expression.
class ToTypedExpr v where
-- | Given a type and a value, convert it to a netlist Expr.
toTypedExpr :: Type -> v -> Expr
instance (Integral a) => ToTypedExpr (Driver a) where
-- From a std_logic* into a typed Expr
toTypedExpr ty (Lit n) = toTypedExpr ty n
toTypedExpr ty (Generic n) = toTypedExpr ty n
toTypedExpr ty (Port v n) = toTypedExpr ty (sigName v (fromIntegral n))
toTypedExpr ty (Pad nm) = toTypedExpr ty nm
toTypedExpr _ other = error $ "toTypedExpr(Driver a): " ++ show other
instance ToTypedExpr String where
-- From a std_logic* into a typed Expr
toTypedExpr B nm = ExprVar nm
toTypedExpr ClkTy nm = ExprVar nm
toTypedExpr (V _) nm = ExprVar nm
toTypedExpr (S _) nm = signed $ ExprVar nm
toTypedExpr (U _) nm = unsigned $ ExprVar nm
toTypedExpr (TupleTy _) nm = ExprVar nm
toTypedExpr (MatrixTy _ _) nm = ExprVar nm
toTypedExpr (SampledTy {}) nm = ExprVar nm
toTypedExpr _other nm = error $ show ("toTypedExpr",_other,nm)
instance ToTypedExpr Integer where
-- From a literal into a typed Expr
toTypedExpr = fromIntegerToExpr
-- | Convert an integer represented by a given Lava type into a netlist Expr.
fromIntegerToExpr :: Type -> Integer -> Expr
fromIntegerToExpr t i =
case toStdLogicTy t of
B -> ExprLit Nothing (ExprBit (b (fromInteger i)))
V n -> ExprLit (Just n) (ExprNum i)
GenericTy -> ExprLit Nothing (ExprNum i)
_ -> error "fromIntegerToExpr: was expecting B or V from normalized number"
where b :: Int -> Bit
b 0 = F
b 1 = T
b _ = error "fromIntegerExpr: bit not of a value 0 or 1"
instance ToTypedExpr RepValue where
-- From a literal into a typed Expr
-- NOTE: We use Integer here as a natural, and assume overflow
toTypedExpr t r = toTypedExpr t (fromRepToInteger r)
-- | Type-directed converstion between Lava values and Netlist expressions.
class ToStdLogicExpr v where
-- | Turn a value into a std_logic[_vector] Expr, given the appropriate type.
toStdLogicExpr :: Type -> v -> Expr
toStdLogicExpr' :: Type -> v -> Expr
toStdLogicExpr' = toStdLogicExpr
-- | Turn a value into an access of a specific element of an array.
-- The Type is type of the element.
toStdLogicEleExpr :: Int -> Type -> v -> Expr
toStdLogicEleExpr = error "toStdLogicEleExpr"
instance (Integral a) => ToStdLogicExpr (Driver a) where
-- From a std_logic* (because you are a driver) into a std_logic.
toStdLogicExpr ty _
| typeWidth ty == 0 = ExprVar "\"\""
toStdLogicExpr ty (Lit n) = toStdLogicExpr ty n
toStdLogicExpr ty (Generic n) = toStdLogicExpr ty n
toStdLogicExpr (MatrixTy w ty') (Port v n)
= mkExprConcat
[ (ty', memToStdLogic ty' $
ExprIndex (sigName v (fromIntegral n))
(ExprLit Nothing $ ExprNum $ fromIntegral (i)))
| i <- reverse [0..(w-1)]
]
toStdLogicExpr _ (Port v n) = ExprVar (sigName v (fromIntegral n))
toStdLogicExpr _ (Pad v) = ExprVar v
toStdLogicExpr _ other = error $ show other
toStdLogicExpr' (MatrixTy 1 _) (Port v n) =
memToStdLogic B $
ExprIndex (sigName v (fromIntegral n))
(ExprLit Nothing $ ExprNum $ 0)
toStdLogicExpr' _ _ = error "missing pattern in toStdLogicExpr'"
toStdLogicEleExpr i ty (Port v n) =
memToStdLogic ty $
ExprIndex (sigName v (fromIntegral n))
(ExprLit Nothing $ ExprNum $ fromIntegral i)
toStdLogicEleExpr _ _ _ = error "missing pattern in toStdLogicEleExpr"
instance ToStdLogicExpr Integer where
-- From a literal into a StdLogic Expr
toStdLogicExpr = fromIntegerToExpr
instance ToStdLogicExpr RepValue where
toStdLogicExpr t r = toTypedExpr t (fromRepToInteger r)
instance ToStdLogicExpr Expr where
-- Convert from a typed expression (as noted by the type) back into a std_logic*
toStdLogicExpr B e = e
toStdLogicExpr ClkTy e = e
toStdLogicExpr (V _) e = e
toStdLogicExpr (TupleTy _) e = e
toStdLogicExpr (MatrixTy _n _) (ExprVar _nm) = error "BBB"
{-
ExprConcat
[ ExprIndex nm
(ExprLit Nothing $ ExprNum $ fromIntegral i)
| i <- [0..(n-1)]
]
-}
toStdLogicExpr (S _) e = std_logic_vector e
toStdLogicExpr (U _) e = std_logic_vector e
toStdLogicExpr(SampledTy {}) e = e
toStdLogicExpr _other e = error $ show ("toStdLogicExpr", _other,e)
-- | Convert an integer to a netlist expression, not represented as a Netlist
-- std_logic_vector, though.
class ToIntegerExpr v where
-- | Given a type and a signal, generate the appropriate Netlist Expr.
toIntegerExpr :: Type -> v -> Expr
instance (Integral i) => ToIntegerExpr (Driver i) where
toIntegerExpr ty (Lit v) = toStdLogicExpr ty v
toIntegerExpr GenericTy other = toTypedExpr GenericTy other -- HACK
toIntegerExpr ty other = to_integer (toTypedExpr ty other)
-- TOOD: remove, and replace with toStdLogicType.
-- | Turn a Kansas Lava type into its std_logic[_vector] type (in KL format)
-- There are three possible results (V n, B, MatrixTy n (V m))
-- This function does not have an inverse.
toStdLogicTy :: Type -> Type
toStdLogicTy B = B
toStdLogicTy ClkTy = B
toStdLogicTy (V n) = V n
toStdLogicTy GenericTy = GenericTy
toStdLogicTy (MatrixTy i ty) = MatrixTy i (V $ fromIntegral size)
where size = typeWidth ty
toStdLogicTy ty = V $ fromIntegral size
where size = typeWidth ty
-- | Does this type have a *matrix* representation?
isMatrixStdLogicTy :: Type -> Bool
isMatrixStdLogicTy ty = case toStdLogicType ty of
SLVA {} -> True
_ -> False
isStdLogicTy :: Type -> Bool
isStdLogicTy ty = case toStdLogicType ty of
SL {} -> True
_ -> False
isStdLogicVectorTy :: Type -> Bool
isStdLogicVectorTy ty = case toStdLogicType ty of
SLV {} -> True
_ -> False
-- | Create a name for a signal.
sigName :: String -> Unique -> String
sigName v d = "sig_" ++ show d ++ "_" ++ v
-- | Given a Lava type, calculate the Netlist Range corresponding to the size.
sizedRange :: Type -> Maybe Range
sizedRange ty = case toStdLogicTy ty of
B -> Nothing
V n -> Just $ Range high low
where high = ExprLit Nothing (ExprNum (fromIntegral n - 1))
low = ExprLit Nothing (ExprNum 0)
MatrixTy _ _ -> error "sizedRange: does not support matrix types"
sty -> error $ "sizedRange: does not support type " ++ show sty
-- * VHDL macros
-- | The netlist representation of the active_high function.
active_high :: Expr -> Expr
active_high d = ExprCond d (ExprLit Nothing (ExprBit T)) (ExprLit Nothing (ExprBit F))
-- | The netlist representation of the VHDL std_logic_vector coercion.
std_logic_vector :: Expr -> Expr
std_logic_vector d = ExprFunCall "std_logic_vector" [d]
-- | The netlist representation of the VHDL unsigned coercion.
unsigned :: Expr -> Expr
unsigned x = ExprFunCall "unsigned" [x]
-- | The netlist representation of the VHDL signed coercion.
signed :: Expr -> Expr
signed x = ExprFunCall "signed" [x]
-- | The netlist representation of the VHDL to_integer coercion.
to_integer :: Expr -> Expr
to_integer e = ExprFunCall "to_integer" [e]
-- | The netlist representation of the isHigh predicate.
isHigh :: Expr -> Expr
isHigh (ExprLit Nothing (ExprBit T)) = ExprVar "true"
isHigh d = ExprBinary Equals d (ExprLit Nothing (ExprBit T))
-- | Convert a driver to an Expr to be used as a memory address.
toMemIndex :: Integral t => Type -> Driver t -> Expr
toMemIndex ty _ | typeWidth ty == 0 = ExprLit Nothing (ExprNum 0)
toMemIndex _ (Lit n) = ExprLit Nothing $ ExprNum $ fromRepToInteger n
toMemIndex ty dr = to_integer $ unsigned $ toStdLogicExpr ty dr
-- Both of these are hacks for memories, that do not use arrays of Bools.
-- | Convert a 'memory' to a std_logic_vector.
memToStdLogic :: Type -> Expr -> Expr
memToStdLogic B e = ExprFunCall "lava_to_std_logic" [e]
memToStdLogic _ e = e
-- | Convert a std_logic_vector to a memory.
stdLogicToMem :: Type -> Expr -> Expr
stdLogicToMem B e = ExprConcat [ExprLit Nothing $ ExprBitVector [],e]
stdLogicToMem _ e = e
-- mkExprConcat always returns a std_logic_vector
-- If there is only one thing, and it is B, then we
-- coerce into a std_logic_vector
mkExprConcat :: [(Type,Expr)] -> Expr
mkExprConcat [(B,e)] = ExprConcat [ExprVar "\"\"",e]
mkExprConcat xs = ExprConcat $ map snd xs
---------------------------------------------------------------------------------------------------
-- Other utils
-- The Type here goes from left to right, but we use it right to left.
-- So [B,U4] => <XXXX:4 to 1><X:0>, because of the convension ordering in our generated VHDL.
-- Notice the result list is in the same order as the argument list.
-- The result is written out as a std_logic[_vector].
-- We assume that the input is *not* a constant (would cause lava-compile-time crash)
-- | Given a value and a list of types, corresponding to tuple element types,
-- generate a list of expressions corresponding to the indexing operations for
-- each tuple element.
prodSlices :: Driver Unique -> [Type] -> [Expr]
prodSlices d tys = reverse $ snd $ mapAccumL f size $ reverse tys
where size = fromIntegral $ sum (map typeWidth tys) - 1
nm = case d of
Port v n -> sigName v n
Pad v -> v
Lit {} -> error "projecting into a literal (not implemented yet!)"
driver -> error "projecting into " ++ show driver ++ " not implemented"
f :: Integer -> Type -> (Integer,Expr)
f i B = (i-1,ExprIndex nm (ExprLit Nothing (ExprNum i)))
f i ty = let w = fromIntegral $ typeWidth ty
nextIdx = i - w
in (nextIdx, ExprSlice nm (ExprLit Nothing (ExprNum i))
(ExprLit Nothing (ExprNum (nextIdx + 1))))
-- | Find some specific (named) input inside the entity.
lookupInput :: (Show b) => String -> Entity b -> Driver b
lookupInput i (Entity _ _ inps) = case find (\(v,_,_) -> v == i) inps of
Just (_,_,d) -> d
Nothing -> error $ "lookupInput: Can't find input" ++ show (i,inps)
-- | Find some specific (named) input's type inside the entity.
lookupInputType :: String -> Entity t -> Type
lookupInputType i (Entity _ _ inps) = case find (\(v,_,_) -> v == i) inps of
Just (_,ty,_) -> ty
Nothing -> error "lookupInputType: Can't find input"
-- | Add an integer generic (always named "i0" to an input list.
addNum :: Integer -> [(String,Type,Driver Unique)] -> [(String,Type,Driver Unique)]
addNum i [("i0",ty,d)] = [("i0",GenericTy,Generic i),("i1",ty,d)]
addNum _ _ = error "addNum"
-- TODO: should ty be GenericTy only here?
------------------------------------------------------------------------
-- | The 'AddNext' class is used to uniformly generate the names of 'next' signals.
class AddNext s where
-- | Given a signal, return the name of the "next" signal.
next :: s -> s
instance AddNext String where
next nm = nm ++ "_next"
instance AddNext (Driver i) where
next (Port v i) = Port (next v) i
next other = other
------------------------------------------------------------------------------
-- | Convert a string representing a Lava operation to a VHDL-friendly name.
sanitizeName :: String -> String
sanitizeName "+" = "add"
sanitizeName "-" = "sub"
sanitizeName "*" = "mul"
sanitizeName ".>." = "gt"
sanitizeName ".<." = "lt"
sanitizeName ".<=." = "ge"
sanitizeName ".>=." = "le"
-- TODO: Add check for symbols
sanitizeName other = other
{-
-- Use the log of the resolution + 1 bit for sign
log2 1 = 0
log2 num
| num > 1 = 1 + log2 (num `div` 2)
| otherwise = error $ "Can't take the log of negative number " ++ show num
-}
----------------------------------------------
-- Build an assignment statement.
assignStmt :: String -> Unique -> Type -> Driver Unique -> Stmt
assignStmt nm i ty d =
case toStdLogicType ty of
SL -> Assign (ExprVar $ sigName nm i) (toStdLogicExpr ty d)
SLV {} -> Assign (ExprVar $ sigName nm i) (toStdLogicExpr ty d)
SLVA n m -> statements $
[ Assign (ExprIndex (sigName nm i)
(ExprLit Nothing $ ExprNum $ fromIntegral j))
$ toStdLogicEleExpr j (V m) d
| j <- [0..(n-1)]
]
G {} -> error "assignStmt {G} ?"
-- | 'assignDecl' takes a name and unique, a target type, and
-- a function that takes a driver-to-expr function, and returns an expr.
assignDecl :: String -> Unique -> Type -> ((Driver Unique -> Expr) -> Expr) -> [Decl]
assignDecl nm i ty f =
case toStdLogicType ty of
SL -> [ NetAssign (sigName nm i)
(f $ toStdLogicExpr ty)
]
SLV {} -> [ NetAssign (sigName nm i)
(f $ toStdLogicExpr ty)
]
SLVA n m -> [ MemAssign (sigName "o0" i)
(ExprLit Nothing $ ExprNum $ fromIntegral j)
(f $ toStdLogicEleExpr j (V m))
| j <- [0..(n-1)]
]
G {} -> error "assignDecl {G} ?"
--error "assignStmt of Matrix"
| andygill/kansas-lava | Language/KansasLava/Netlist/Utils.hs | bsd-3-clause | 14,626 | 96 | 17 | 3,700 | 3,707 | 1,923 | 1,784 | 226 | 6 |
module RecompileRelaunchTest where
import qualified Config.Dyre as Dyre
import Config.Dyre.Relaunch
import System.IO
realMain message = do
state <- restoreTextState False
putStr message >> hFlush stdout
if state then putStrLn ""
else relaunchWithTextState True Nothing
recompileRelaunchTest = Dyre.wrapMain $ Dyre.defaultParams
{ Dyre.projectName = "recompileRelaunchTest"
, Dyre.realMain = realMain
, Dyre.showError = const
, Dyre.statusOut = const . return $ ()
}
| bitemyapp/dyre | Tests/recompile-relaunch/RecompileRelaunchTest.hs | bsd-3-clause | 521 | 0 | 9 | 115 | 130 | 71 | 59 | 14 | 2 |
{-# LANGUAGE RecordWildCards #-}
module Lang.Lexer
( BracketSide(..)
, _BracketSideOpening
, _BracketSideClosing
, UnknownChar(..)
, FilePath'(..)
, Token(..)
, _TokenSquareBracket
, _TokenParenthesis
, _TokenString
, _TokenAddress
, _TokenPublicKey
, _TokenStakeholderId
, _TokenHash
, _TokenBlockVersion
, _TokenSoftwareVersion
, _TokenFilePath
, _TokenNumber
, _TokenName
, _TokenKey
, _TokenEquals
, _TokenSemicolon
, _TokenUnknown
, tokenize
, tokenize'
, detokenize
, tokenRender
) where
import Universum hiding (try)
import qualified Control.Applicative.Combinators.NonEmpty as NonEmpty
import Control.Lens (makePrisms)
import Data.Char (isAlpha, isAlphaNum)
import qualified Data.List as List
import qualified Data.List.NonEmpty as NonEmpty
import Data.Loc (Loc, Span, loc, spanFromTo)
import Data.Scientific (Scientific)
import qualified Data.Text as Text
import Formatting (sformat)
import qualified Formatting.Buildable as Buildable
import Test.QuickCheck.Arbitrary.Generic (Arbitrary (..),
genericArbitrary, genericShrink)
import qualified Test.QuickCheck.Gen as QC
import Test.QuickCheck.Instances ()
import Text.Megaparsec (Parsec, SourcePos (..), anySingle, between,
choice, eof, getSourcePos, manyTill, notFollowedBy,
parseMaybe, satisfy, skipMany, takeP, takeWhile1P, try,
unPos, (<?>))
import Text.Megaparsec.Char (char, spaceChar,
string)
import Text.Megaparsec.Char.Lexer (decimal, scientific, signed)
import Lang.Name (Letter, Name (..), unsafeMkLetter)
import Pos.Chain.Update (ApplicationName (..), BlockVersion (..),
SoftwareVersion (..))
import Pos.Core (Address, StakeholderId, decodeTextAddress)
import Pos.Crypto (AHash (..), PublicKey, decodeAbstractHash,
fullPublicKeyF, hashHexF, parseFullPublicKey,
unsafeCheatingHashCoerce)
import Pos.Util.Util (toParsecError)
import Test.Pos.Chain.Update.Arbitrary ()
import Test.Pos.Core.Arbitrary ()
data BracketSide = BracketSideOpening | BracketSideClosing
deriving (Eq, Ord, Show, Generic)
makePrisms ''BracketSide
withBracketSide :: a -> a -> BracketSide -> a
withBracketSide onOpening onClosing = \case
BracketSideOpening -> onOpening
BracketSideClosing -> onClosing
instance Arbitrary BracketSide where
arbitrary = genericArbitrary
shrink = genericShrink
newtype UnknownChar = UnknownChar Char
deriving (Eq, Ord, Show)
instance Arbitrary UnknownChar where
arbitrary = pure (UnknownChar '\0')
newtype FilePath' = FilePath'
{ getFilePath' :: FilePath
} deriving (Eq, Ord, Show, Generic, IsString)
instance Arbitrary FilePath' where
arbitrary = QC.elements
[ "/a/b/c"
, "./a/b/c"
, "/p a t h/h e r e.k"
] -- TODO: proper generator
instance Buildable FilePath' where
build = fromString . concatMap escape . getFilePath'
where
escape c | isFilePathChar c = [c]
| otherwise = '\\':[c]
isFilePathChar :: Char -> Bool
isFilePathChar c = isAlphaNum c || c `elem` ['.', '/', '-', '_']
data Token
= TokenSquareBracket BracketSide
| TokenParenthesis BracketSide
| TokenString Text
| TokenNumber Scientific
| TokenAddress Address
| TokenPublicKey PublicKey
| TokenStakeholderId StakeholderId
| TokenHash AHash
| TokenBlockVersion BlockVersion
| TokenSoftwareVersion SoftwareVersion
| TokenFilePath FilePath'
| TokenName Name
| TokenKey Name
| TokenEquals
| TokenSemicolon
| TokenUnknown UnknownChar
deriving (Eq, Ord, Show, Generic)
makePrisms ''Token
instance Arbitrary Token where
arbitrary = genericArbitrary
shrink = genericShrink
tokenRender :: Token -> Text
tokenRender = \case
TokenSquareBracket bs -> withBracketSide "[" "]" bs
TokenParenthesis bs -> withBracketSide "(" ")" bs
-- Double up every double quote, and surround the whole thing with double
-- quotes.
TokenString t -> quote (escapeQuotes t)
where
quote :: Text -> Text
quote t' = Text.concat [Text.singleton '\"', t', Text.singleton '\"']
escapeQuotes :: Text -> Text
escapeQuotes = Text.intercalate "\"\"" . Text.splitOn "\""
TokenNumber n -> show n
TokenAddress a -> pretty a
TokenPublicKey pk -> sformat fullPublicKeyF pk
TokenStakeholderId sId -> sformat hashHexF sId
TokenHash h -> sformat hashHexF (getAHash h)
TokenBlockVersion v -> pretty v
TokenSoftwareVersion v -> "~software~" <> pretty v
TokenFilePath s -> pretty s
TokenName ss -> pretty ss
TokenKey ss -> pretty ss <> ":"
TokenEquals -> "="
TokenSemicolon -> ";"
TokenUnknown (UnknownChar c) -> Text.singleton c
detokenize :: [Token] -> Text
detokenize = unwords . List.map tokenRender
type Lexer a = Parsec Void Text a
tokenize :: Text -> [(Span, Token)]
tokenize = fromMaybe noTokenErr . tokenize'
where
noTokenErr =
error "tokenize: no token could be consumed. This is a bug"
tokenize' :: Text -> Maybe [(Span, Token)]
tokenize' = parseMaybe (between pSkip eof (many pToken))
pToken :: Lexer (Span, Token)
pToken = withPosition (try pToken' <|> pUnknown) <* pSkip
where
posToLoc :: SourcePos -> Loc
posToLoc (SourcePos _ sourceLine sourceColumn) = uncurry loc
( fromIntegral . unPos $ sourceLine
, fromIntegral . unPos $ sourceColumn)
withPosition p = do
pos1 <- posToLoc <$> getSourcePos
t <- p
pos2 <- posToLoc <$> getSourcePos
return (spanFromTo pos1 pos2, t)
pUnknown :: Lexer Token
pUnknown = TokenUnknown . UnknownChar <$> anySingle
pSkip :: Lexer ()
pSkip = skipMany (void spaceChar)
marking :: Text -> Lexer a -> Lexer a
marking t p = optional (string $ "~" <> t <> "~") *> p
pToken' :: Lexer Token
pToken' = choice
[ pPunct
, marking "addr" $ TokenAddress <$> try pAddress
, marking "pk" $ TokenPublicKey <$> try pPublicKey
, marking "stakeholder" $ TokenStakeholderId <$> try pStakeholderId
, marking "hash" $ TokenHash <$> try pHash
, marking "block-v" $ TokenBlockVersion <$> try pBlockVersion
, string "~software~" *> (TokenSoftwareVersion <$> try pSoftwareVersion)
, marking "filepath" $ TokenFilePath <$> pFilePath
, marking "num" $ TokenNumber <$> pScientific
, marking "str" $ TokenString <$> pText
, marking "ident" $ pIdent
] <?> "token"
pPunct :: Lexer Token
pPunct = choice
[ char '[' $> TokenSquareBracket BracketSideOpening
, char ']' $> TokenSquareBracket BracketSideClosing
, char '(' $> TokenParenthesis BracketSideOpening
, char ')' $> TokenParenthesis BracketSideClosing
, char '=' $> TokenEquals
, char ';' $> TokenSemicolon
] <?> "punct"
pText :: Lexer Text
pText = do
_ <- char '\"'
Text.pack <$> loop []
where
loop :: [Char] -> Lexer [Char]
loop !acc = do
next <- anySingle
case next of
-- Check for double double quotes. If it's a single double quote,
-- it's the end of the string.
'\"' -> try (doubleQuote acc) <|> pure (reverse acc)
c -> loop (c : acc)
doubleQuote :: [Char] -> Lexer [Char]
doubleQuote !acc = char '\"' >> loop ('\"' : acc)
pSomeAlphaNum :: Lexer Text
pSomeAlphaNum = takeWhile1P (Just "alphanumeric") isAlphaNum
pAddress :: Lexer Address
pAddress = do
str <- pSomeAlphaNum
toParsecError $ decodeTextAddress str
pPublicKey :: Lexer PublicKey
pPublicKey = do
str <- (<>) <$> takeP (Just "base64") 86 <*> string "=="
toParsecError $ parseFullPublicKey str
pStakeholderId :: Lexer StakeholderId
pStakeholderId = do
str <- pSomeAlphaNum
toParsecError $ decodeAbstractHash str
pHash :: Lexer AHash
pHash = do
str <- pSomeAlphaNum
toParsecError . fmap unsafeCheatingHashCoerce $ decodeAbstractHash str
pBlockVersion :: Lexer BlockVersion
pBlockVersion = do
bvMajor <- decimal
void $ char '.'
bvMinor <- decimal
void $ char '.'
bvAlt <- decimal
notFollowedBy $ char '.'
return BlockVersion{..}
pSoftwareVersion :: Lexer SoftwareVersion
pSoftwareVersion = do
appName <- manyTill (satisfy isAlphaNum <|> char '-') (char ':')
let svAppName = ApplicationName (toText appName)
svNumber <- decimal
notFollowedBy $ char '.'
return SoftwareVersion {..}
pFilePath :: Lexer FilePath'
pFilePath = FilePath' <$> do
dots <- many (char '.')
cs <-
(:) <$> char '/'
<*> many pFilePathChar
<|> pure ""
notFollowedBy pFilePathChar
let path = dots <> cs
guard $ not (null path)
return path
where
pFilePathChar :: Lexer Char
pFilePathChar =
char '\\' *> anySingle <|>
satisfy isFilePathChar
pIdent :: Lexer Token
pIdent = do
name <- NonEmpty.sepBy1 pNameSection (char '-')
notFollowedBy (satisfy isAlphaNum)
isKey <- isJust <$> optional (char ':')
return $ (if isKey then TokenKey else TokenName) (Name name)
pNameSection :: Lexer (NonEmpty Letter)
pNameSection = NonEmpty.some1 pLetter
pLetter :: Lexer Letter
pLetter = unsafeMkLetter <$> satisfy isAlpha
pScientific :: Lexer Scientific
pScientific = do
n <- signed (return ()) scientific
p <- isJust <$> optional (char '%')
return $ if p then n / 100 else n
{-# ANN module ("HLint: ignore Use toText" :: Text) #-}
| input-output-hk/pos-haskell-prototype | auxx/src/Lang/Lexer.hs | mit | 9,796 | 0 | 15 | 2,504 | 2,719 | 1,430 | 1,289 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module RarecoalLib.ModelTemplate.Test (tests) where
import RarecoalLib.ModelTemplate (ModelTemplate(..), MTEvent(..), MTConstraint(..), ParamSpec(..),
ConstraintOperator(..), getModelTemplate, ModelOptions(..))
import Test.Tasty
import Test.Tasty.HUnit (testCase, Assertion, assertEqual)
template :: ModelTemplate
template = ModelTemplate {
mtBranchNames = ["EUR", "SEA", "SIB", "FAM"],
mtEvents = [
MTPopSizeChange (ParamFixed 0.0) "EUR" (ParamVariable "p_EUR"),
MTPopSizeChange (ParamFixed 0.0) "SEA" (ParamVariable "p_SEA"),
MTPopSizeChange (ParamFixed 0.0) "SIB" (ParamVariable "p_SIB"),
MTPopSizeChange (ParamFixed 0.0) "FAM" (ParamVariable "p_FAM"),
MTJoinPopSizeChange (ParamVariable "t_EUR_SIB") "EUR" "SIB" (ParamVariable "p_EUR_SIB"),
MTJoinPopSizeChange (ParamVariable "t_SEA_FAM") "SEA" "FAM" (ParamVariable "p_SEA_FAM"),
MTJoinPopSizeChange (ParamVariable "t_EUR_SEA") "EUR" "SEA" (ParamVariable "p_EUR_SEA"),
MTSplit (ParamVariable "tAdm_FAM_SIB") "FAM" "SIB" (ParamVariable "adm_FAM_SIB"),
MTPopSizeChange (ParamVariable "tAdm_FAM_SIB") "FAM" (ParamVariable "pAdm_FAM_SIB"),
MTSplit (ParamVariable "tAdm_SEA_SIB") "SEA" "SIB" (ParamVariable "adm_SEA_SIB"),
MTPopSizeChange (ParamVariable "tAdm_SEA_SIB") "SEA" (ParamVariable "pAdm_SEA_SIB"),
MTSplit (ParamFixed 0.00022) "EUR" "FAM" (ParamVariable "adm_EUR_FAM")
],
mtConstraints = [
MTConstraint (ParamVariable "tAdm_FAM_SIB") (ParamFixed 0.00022) ConstraintOpGreater
]
}
testLoadTemplate :: Assertion
testLoadTemplate = do
t <- getModelTemplate (ModelByFile "exampleData/fourPop.template.txt")
assertEqual "testLoadTemplate" t template
-- testGetNewParams :: Assertion
-- testGetNewParams = do
-- let p = V.fromList [1,1,1,1,1,0.02,0.04,0.041,0.05,1,2,3,4]
-- newP = getNewParams template p 6 0.002
-- assertEqual "switch time with overlapping join" (V.fromList [1, 1, 1, 1, 1, 0.02, 0.042, 0.041, 0.05, 1, 3, 3, 4]) newP
-- let newP' = getNewParams template p 7 0.002
-- diffVec = V.zipWith (\a b -> abs (a - b)) (V.fromList [1, 1, 1, 1, 1, 0.02, 0.04, 0.043, 0.05, 1, 2, 3, 4]) newP'
-- assertBool "no overlapping join" $ V.all (<1.0e-8) diffVec
tests :: TestTree
tests = testGroup "ModelTemplate Tests" [ testCase "testing template loading" testLoadTemplate]
-- , testCase "testing getNewParams" testGetNewParams]
| stschiff/rarecoal | src/RarecoalLib/ModelTemplate/Test.hs | gpl-3.0 | 2,533 | 0 | 10 | 467 | 495 | 273 | 222 | 30 | 1 |
-- Copyright (C) 2017 Red Hat, Inc.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, see <http://www.gnu.org/licenses/>.
module BDCS.Label.InfoPage(matches,
mkLabel)
where
import Data.List(isPrefixOf, isSuffixOf)
import qualified Data.Text as T
import Text.Regex.PCRE((=~))
import BDCS.DB(Files(..))
import BDCS.Label.Types(Label(..))
matches :: Files -> Bool
matches Files{..} = let
compressedInfoPageExt = "\\.info-[0-9]+\\.gz" :: String
filesPath' = T.unpack filesPath
in
"/usr/share/info/" `isPrefixOf` filesPath' &&
(".info.gz" `isSuffixOf` filesPath' || filesPath' =~ compressedInfoPageExt)
mkLabel :: Files -> Maybe Label
mkLabel _ = Just InfoPageLabel
| atodorov/bdcs | src/BDCS/Label/InfoPage.hs | lgpl-2.1 | 1,327 | 0 | 11 | 263 | 189 | 117 | 72 | -1 | -1 |
{-# LANGUAGE ScopedTypeVariables #-}
--
-- Reg.hs --- I/O register access from Ivory.
--
-- Copyright (C) 2013, Galois, Inc.
-- All Rights Reserved.
--
module Ivory.HW.Reg where
import Ivory.Language
import Ivory.HW.Prim
-- | An I/O register containing a value of type "t". Define registers
-- using the "mkReg" functions.
data Reg t = Reg Integer
-- | Previously, this was a smart constructor to raise an error if the address
-- is invalid, but we didn't find a way to parameterize the valid address
-- space by the platform, so now mkReg accepts all addresses.
mkReg :: forall t. IvoryIOReg t => Integer -> Reg t
mkReg addr = Reg addr
-- | Read an I/O register, returning an Ivory value.
readReg :: IvoryIOReg a => Reg a -> Ivory eff a
readReg (Reg addr) = call ioRegRead (fromIntegral addr)
-- | Write an I/O register from an Ivory value.
writeReg :: IvoryIOReg a => Reg a -> a -> Ivory eff ()
writeReg (Reg addr) val = call_ ioRegWrite (fromIntegral addr) val
| GaloisInc/ivory | ivory-hw/src/Ivory/HW/Reg.hs | bsd-3-clause | 975 | 0 | 9 | 185 | 185 | 100 | 85 | 11 | 1 |
{-# OPTIONS_GHC -fno-implicit-prelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : Foreign.Concurrent
-- Copyright : (c) The University of Glasgow 2003
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : non-portable (requires concurrency)
--
-- FFI datatypes and operations that use or require concurrency (GHC only).
--
-----------------------------------------------------------------------------
module Foreign.Concurrent
(
-- * Concurrency-based 'ForeignPtr' operations
-- | These functions generalize their namesakes in the portable
-- "Foreign.ForeignPtr" module by allowing arbitrary 'IO' actions
-- as finalizers. These finalizers necessarily run in a separate
-- thread, cf. /Destructors, Finalizers and Synchronization/,
-- by Hans Boehm, /POPL/, 2003.
newForeignPtr,
addForeignPtrFinalizer,
) where
#ifdef __GLASGOW_HASKELL__
import GHC.IOBase ( IO )
import GHC.Ptr ( Ptr )
import GHC.ForeignPtr ( ForeignPtr )
import qualified GHC.ForeignPtr
#endif
#ifdef __GLASGOW_HASKELL__
newForeignPtr :: Ptr a -> IO () -> IO (ForeignPtr a)
-- ^Turns a plain memory reference into a foreign object by associating
-- a finalizer - given by the monadic operation - with the reference.
-- The finalizer will be executed after the last reference to the
-- foreign object is dropped. Note that there is no guarantee on how
-- soon the finalizer is executed after the last reference was dropped;
-- this depends on the details of the Haskell storage manager. The only
-- guarantee is that the finalizer runs before the program terminates.
newForeignPtr = GHC.ForeignPtr.newConcForeignPtr
addForeignPtrFinalizer :: ForeignPtr a -> IO () -> IO ()
-- ^This function adds a finalizer to the given 'ForeignPtr'.
-- The finalizer will run after the last reference to the foreign object
-- is dropped, but /before/ all previously registered finalizers for the
-- same object.
addForeignPtrFinalizer = GHC.ForeignPtr.addForeignPtrConcFinalizer
#endif
| alekar/hugs | packages/base/Foreign/Concurrent.hs | bsd-3-clause | 2,123 | 10 | 9 | 328 | 168 | 108 | 60 | 5 | 0 |
-----------------------------------------------------------------------------
--
-- Machine-dependent assembly language
--
-- (c) The University of Glasgow 1993-2004
--
-----------------------------------------------------------------------------
{-# OPTIONS -fno-warn-tabs #-}
-- The above warning supression flag is a temporary kludge.
-- While working on this module you are encouraged to remove it and
-- detab the module (please do the detabbing in a separate patch). See
-- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
-- for details
#include "HsVersions.h"
#include "nativeGen/NCG.h"
module PPC.Instr (
archWordSize,
RI(..),
Instr(..),
maxSpillSlots
)
where
import PPC.Regs
import PPC.Cond
import Instruction
import Size
import TargetReg
import RegClass
import Reg
import Constants (rESERVED_C_STACK_BYTES)
import BlockId
import OldCmm
import FastString
import CLabel
import Outputable
import Platform
import FastBool
--------------------------------------------------------------------------------
-- Size of a PPC memory address, in bytes.
--
archWordSize :: Size
archWordSize = II32
-- | Instruction instance for powerpc
instance Instruction Instr where
regUsageOfInstr = ppc_regUsageOfInstr
patchRegsOfInstr = ppc_patchRegsOfInstr
isJumpishInstr = ppc_isJumpishInstr
jumpDestsOfInstr = ppc_jumpDestsOfInstr
patchJumpInstr = ppc_patchJumpInstr
mkSpillInstr = ppc_mkSpillInstr
mkLoadInstr = ppc_mkLoadInstr
takeDeltaInstr = ppc_takeDeltaInstr
isMetaInstr = ppc_isMetaInstr
mkRegRegMoveInstr _ = ppc_mkRegRegMoveInstr
takeRegRegMoveInstr = ppc_takeRegRegMoveInstr
mkJumpInstr = ppc_mkJumpInstr
-- -----------------------------------------------------------------------------
-- Machine's assembly language
-- We have a few common "instructions" (nearly all the pseudo-ops) but
-- mostly all of 'Instr' is machine-specific.
-- Register or immediate
data RI
= RIReg Reg
| RIImm Imm
data Instr
-- comment pseudo-op
= COMMENT FastString
-- some static data spat out during code
-- generation. Will be extracted before
-- pretty-printing.
| LDATA Section CmmStatics
-- start a new basic block. Useful during
-- codegen, removed later. Preceding
-- instruction should be a jump, as per the
-- invariants for a BasicBlock (see Cmm).
| NEWBLOCK BlockId
-- specify current stack offset for
-- benefit of subsequent passes
| DELTA Int
-- Loads and stores.
| LD Size Reg AddrMode -- Load size, dst, src
| LA Size Reg AddrMode -- Load arithmetic size, dst, src
| ST Size Reg AddrMode -- Store size, src, dst
| STU Size Reg AddrMode -- Store with Update size, src, dst
| LIS Reg Imm -- Load Immediate Shifted dst, src
| LI Reg Imm -- Load Immediate dst, src
| MR Reg Reg -- Move Register dst, src -- also for fmr
| CMP Size Reg RI --- size, src1, src2
| CMPL Size Reg RI --- size, src1, src2
| BCC Cond BlockId
| BCCFAR Cond BlockId
| JMP CLabel -- same as branch,
-- but with CLabel instead of block ID
| MTCTR Reg
| BCTR [Maybe BlockId] (Maybe CLabel) -- with list of local destinations, and jump table location if necessary
| BL CLabel [Reg] -- with list of argument regs
| BCTRL [Reg]
| ADD Reg Reg RI -- dst, src1, src2
| ADDC Reg Reg Reg -- (carrying) dst, src1, src2
| ADDE Reg Reg Reg -- (extend) dst, src1, src2
| ADDIS Reg Reg Imm -- Add Immediate Shifted dst, src1, src2
| SUBF Reg Reg Reg -- dst, src1, src2 ; dst = src2 - src1
| MULLW Reg Reg RI
| DIVW Reg Reg Reg
| DIVWU Reg Reg Reg
| MULLW_MayOflo Reg Reg Reg
-- dst = 1 if src1 * src2 overflows
-- pseudo-instruction; pretty-printed as:
-- mullwo. dst, src1, src2
-- mfxer dst
-- rlwinm dst, dst, 2, 31,31
| AND Reg Reg RI -- dst, src1, src2
| OR Reg Reg RI -- dst, src1, src2
| XOR Reg Reg RI -- dst, src1, src2
| XORIS Reg Reg Imm -- XOR Immediate Shifted dst, src1, src2
| EXTS Size Reg Reg
| NEG Reg Reg
| NOT Reg Reg
| SLW Reg Reg RI -- shift left word
| SRW Reg Reg RI -- shift right word
| SRAW Reg Reg RI -- shift right arithmetic word
-- Rotate Left Word Immediate then AND with Mask
| RLWINM Reg Reg Int Int Int
| FADD Size Reg Reg Reg
| FSUB Size Reg Reg Reg
| FMUL Size Reg Reg Reg
| FDIV Size Reg Reg Reg
| FNEG Reg Reg -- negate is the same for single and double prec.
| FCMP Reg Reg
| FCTIWZ Reg Reg -- convert to integer word
| FRSP Reg Reg -- reduce to single precision
-- (but destination is a FP register)
| CRNOR Int Int Int -- condition register nor
| MFCR Reg -- move from condition register
| MFLR Reg -- move from link register
| FETCHPC Reg -- pseudo-instruction:
-- bcl to next insn, mflr reg
| LWSYNC -- memory barrier
-- | Get the registers that are being used by this instruction.
-- regUsage doesn't need to do any trickery for jumps and such.
-- Just state precisely the regs read and written by that insn.
-- The consequences of control flow transfers, as far as register
-- allocation goes, are taken care of by the register allocator.
--
ppc_regUsageOfInstr :: Instr -> RegUsage
ppc_regUsageOfInstr instr
= case instr of
LD _ reg addr -> usage (regAddr addr, [reg])
LA _ reg addr -> usage (regAddr addr, [reg])
ST _ reg addr -> usage (reg : regAddr addr, [])
STU _ reg addr -> usage (reg : regAddr addr, [])
LIS reg _ -> usage ([], [reg])
LI reg _ -> usage ([], [reg])
MR reg1 reg2 -> usage ([reg2], [reg1])
CMP _ reg ri -> usage (reg : regRI ri,[])
CMPL _ reg ri -> usage (reg : regRI ri,[])
BCC _ _ -> noUsage
BCCFAR _ _ -> noUsage
MTCTR reg -> usage ([reg],[])
BCTR _ _ -> noUsage
BL _ params -> usage (params, callClobberedRegs)
BCTRL params -> usage (params, callClobberedRegs)
ADD reg1 reg2 ri -> usage (reg2 : regRI ri, [reg1])
ADDC reg1 reg2 reg3-> usage ([reg2,reg3], [reg1])
ADDE reg1 reg2 reg3-> usage ([reg2,reg3], [reg1])
ADDIS reg1 reg2 _ -> usage ([reg2], [reg1])
SUBF reg1 reg2 reg3-> usage ([reg2,reg3], [reg1])
MULLW reg1 reg2 ri -> usage (reg2 : regRI ri, [reg1])
DIVW reg1 reg2 reg3-> usage ([reg2,reg3], [reg1])
DIVWU reg1 reg2 reg3-> usage ([reg2,reg3], [reg1])
MULLW_MayOflo reg1 reg2 reg3
-> usage ([reg2,reg3], [reg1])
AND reg1 reg2 ri -> usage (reg2 : regRI ri, [reg1])
OR reg1 reg2 ri -> usage (reg2 : regRI ri, [reg1])
XOR reg1 reg2 ri -> usage (reg2 : regRI ri, [reg1])
XORIS reg1 reg2 _ -> usage ([reg2], [reg1])
EXTS _ reg1 reg2 -> usage ([reg2], [reg1])
NEG reg1 reg2 -> usage ([reg2], [reg1])
NOT reg1 reg2 -> usage ([reg2], [reg1])
SLW reg1 reg2 ri -> usage (reg2 : regRI ri, [reg1])
SRW reg1 reg2 ri -> usage (reg2 : regRI ri, [reg1])
SRAW reg1 reg2 ri -> usage (reg2 : regRI ri, [reg1])
RLWINM reg1 reg2 _ _ _
-> usage ([reg2], [reg1])
FADD _ r1 r2 r3 -> usage ([r2,r3], [r1])
FSUB _ r1 r2 r3 -> usage ([r2,r3], [r1])
FMUL _ r1 r2 r3 -> usage ([r2,r3], [r1])
FDIV _ r1 r2 r3 -> usage ([r2,r3], [r1])
FNEG r1 r2 -> usage ([r2], [r1])
FCMP r1 r2 -> usage ([r1,r2], [])
FCTIWZ r1 r2 -> usage ([r2], [r1])
FRSP r1 r2 -> usage ([r2], [r1])
MFCR reg -> usage ([], [reg])
MFLR reg -> usage ([], [reg])
FETCHPC reg -> usage ([], [reg])
_ -> noUsage
where
usage (src, dst) = RU (filter interesting src)
(filter interesting dst)
regAddr (AddrRegReg r1 r2) = [r1, r2]
regAddr (AddrRegImm r1 _) = [r1]
regRI (RIReg r) = [r]
regRI _ = []
interesting :: Reg -> Bool
interesting (RegVirtual _) = True
interesting (RegReal (RealRegSingle i))
= isFastTrue (freeReg i)
interesting (RegReal (RealRegPair{}))
= panic "PPC.Instr.interesting: no reg pairs on this arch"
-- | Apply a given mapping to all the register references in this
-- instruction.
ppc_patchRegsOfInstr :: Instr -> (Reg -> Reg) -> Instr
ppc_patchRegsOfInstr instr env
= case instr of
LD sz reg addr -> LD sz (env reg) (fixAddr addr)
LA sz reg addr -> LA sz (env reg) (fixAddr addr)
ST sz reg addr -> ST sz (env reg) (fixAddr addr)
STU sz reg addr -> STU sz (env reg) (fixAddr addr)
LIS reg imm -> LIS (env reg) imm
LI reg imm -> LI (env reg) imm
MR reg1 reg2 -> MR (env reg1) (env reg2)
CMP sz reg ri -> CMP sz (env reg) (fixRI ri)
CMPL sz reg ri -> CMPL sz (env reg) (fixRI ri)
BCC cond lbl -> BCC cond lbl
BCCFAR cond lbl -> BCCFAR cond lbl
MTCTR reg -> MTCTR (env reg)
BCTR targets lbl -> BCTR targets lbl
BL imm argRegs -> BL imm argRegs -- argument regs
BCTRL argRegs -> BCTRL argRegs -- cannot be remapped
ADD reg1 reg2 ri -> ADD (env reg1) (env reg2) (fixRI ri)
ADDC reg1 reg2 reg3-> ADDC (env reg1) (env reg2) (env reg3)
ADDE reg1 reg2 reg3-> ADDE (env reg1) (env reg2) (env reg3)
ADDIS reg1 reg2 imm -> ADDIS (env reg1) (env reg2) imm
SUBF reg1 reg2 reg3-> SUBF (env reg1) (env reg2) (env reg3)
MULLW reg1 reg2 ri -> MULLW (env reg1) (env reg2) (fixRI ri)
DIVW reg1 reg2 reg3-> DIVW (env reg1) (env reg2) (env reg3)
DIVWU reg1 reg2 reg3-> DIVWU (env reg1) (env reg2) (env reg3)
MULLW_MayOflo reg1 reg2 reg3
-> MULLW_MayOflo (env reg1) (env reg2) (env reg3)
AND reg1 reg2 ri -> AND (env reg1) (env reg2) (fixRI ri)
OR reg1 reg2 ri -> OR (env reg1) (env reg2) (fixRI ri)
XOR reg1 reg2 ri -> XOR (env reg1) (env reg2) (fixRI ri)
XORIS reg1 reg2 imm -> XORIS (env reg1) (env reg2) imm
EXTS sz reg1 reg2 -> EXTS sz (env reg1) (env reg2)
NEG reg1 reg2 -> NEG (env reg1) (env reg2)
NOT reg1 reg2 -> NOT (env reg1) (env reg2)
SLW reg1 reg2 ri -> SLW (env reg1) (env reg2) (fixRI ri)
SRW reg1 reg2 ri -> SRW (env reg1) (env reg2) (fixRI ri)
SRAW reg1 reg2 ri -> SRAW (env reg1) (env reg2) (fixRI ri)
RLWINM reg1 reg2 sh mb me
-> RLWINM (env reg1) (env reg2) sh mb me
FADD sz r1 r2 r3 -> FADD sz (env r1) (env r2) (env r3)
FSUB sz r1 r2 r3 -> FSUB sz (env r1) (env r2) (env r3)
FMUL sz r1 r2 r3 -> FMUL sz (env r1) (env r2) (env r3)
FDIV sz r1 r2 r3 -> FDIV sz (env r1) (env r2) (env r3)
FNEG r1 r2 -> FNEG (env r1) (env r2)
FCMP r1 r2 -> FCMP (env r1) (env r2)
FCTIWZ r1 r2 -> FCTIWZ (env r1) (env r2)
FRSP r1 r2 -> FRSP (env r1) (env r2)
MFCR reg -> MFCR (env reg)
MFLR reg -> MFLR (env reg)
FETCHPC reg -> FETCHPC (env reg)
_ -> instr
where
fixAddr (AddrRegReg r1 r2) = AddrRegReg (env r1) (env r2)
fixAddr (AddrRegImm r1 i) = AddrRegImm (env r1) i
fixRI (RIReg r) = RIReg (env r)
fixRI other = other
--------------------------------------------------------------------------------
-- | Checks whether this instruction is a jump/branch instruction.
-- One that can change the flow of control in a way that the
-- register allocator needs to worry about.
ppc_isJumpishInstr :: Instr -> Bool
ppc_isJumpishInstr instr
= case instr of
BCC{} -> True
BCCFAR{} -> True
BCTR{} -> True
BCTRL{} -> True
BL{} -> True
JMP{} -> True
_ -> False
-- | Checks whether this instruction is a jump/branch instruction.
-- One that can change the flow of control in a way that the
-- register allocator needs to worry about.
ppc_jumpDestsOfInstr :: Instr -> [BlockId]
ppc_jumpDestsOfInstr insn
= case insn of
BCC _ id -> [id]
BCCFAR _ id -> [id]
BCTR targets _ -> [id | Just id <- targets]
_ -> []
-- | Change the destination of this jump instruction.
-- Used in the linear allocator when adding fixup blocks for join
-- points.
ppc_patchJumpInstr :: Instr -> (BlockId -> BlockId) -> Instr
ppc_patchJumpInstr insn patchF
= case insn of
BCC cc id -> BCC cc (patchF id)
BCCFAR cc id -> BCCFAR cc (patchF id)
BCTR ids lbl -> BCTR (map (fmap patchF) ids) lbl
_ -> insn
-- -----------------------------------------------------------------------------
-- | An instruction to spill a register into a spill slot.
ppc_mkSpillInstr
:: Platform
-> Reg -- register to spill
-> Int -- current stack delta
-> Int -- spill slot to use
-> Instr
ppc_mkSpillInstr platform reg delta slot
= let off = spillSlotToOffset slot
in
let sz = case targetClassOfReg platform reg of
RcInteger -> II32
RcDouble -> FF64
_ -> panic "PPC.Instr.mkSpillInstr: no match"
in ST sz reg (AddrRegImm sp (ImmInt (off-delta)))
ppc_mkLoadInstr
:: Platform
-> Reg -- register to load
-> Int -- current stack delta
-> Int -- spill slot to use
-> Instr
ppc_mkLoadInstr platform reg delta slot
= let off = spillSlotToOffset slot
in
let sz = case targetClassOfReg platform reg of
RcInteger -> II32
RcDouble -> FF64
_ -> panic "PPC.Instr.mkLoadInstr: no match"
in LD sz reg (AddrRegImm sp (ImmInt (off-delta)))
spillSlotSize :: Int
spillSlotSize = 8
maxSpillSlots :: Int
maxSpillSlots = ((rESERVED_C_STACK_BYTES - 64) `div` spillSlotSize) - 1
-- convert a spill slot number to a *byte* offset, with no sign:
-- decide on a per arch basis whether you are spilling above or below
-- the C stack pointer.
spillSlotToOffset :: Int -> Int
spillSlotToOffset slot
| slot >= 0 && slot < maxSpillSlots
= 64 + spillSlotSize * slot
| otherwise
= pprPanic "spillSlotToOffset:"
( text "invalid spill location: " <> int slot
$$ text "maxSpillSlots: " <> int maxSpillSlots)
--------------------------------------------------------------------------------
-- | See if this instruction is telling us the current C stack delta
ppc_takeDeltaInstr
:: Instr
-> Maybe Int
ppc_takeDeltaInstr instr
= case instr of
DELTA i -> Just i
_ -> Nothing
ppc_isMetaInstr
:: Instr
-> Bool
ppc_isMetaInstr instr
= case instr of
COMMENT{} -> True
LDATA{} -> True
NEWBLOCK{} -> True
DELTA{} -> True
_ -> False
-- | Copy the value in a register to another one.
-- Must work for all register classes.
ppc_mkRegRegMoveInstr
:: Reg
-> Reg
-> Instr
ppc_mkRegRegMoveInstr src dst
= MR dst src
-- | Make an unconditional jump instruction.
-- For architectures with branch delay slots, its ok to put
-- a NOP after the jump. Don't fill the delay slot with an
-- instruction that references regs or you'll confuse the
-- linear allocator.
ppc_mkJumpInstr
:: BlockId
-> [Instr]
ppc_mkJumpInstr id
= [BCC ALWAYS id]
-- | Take the source and destination from this reg -> reg move instruction
-- or Nothing if it's not one
ppc_takeRegRegMoveInstr :: Instr -> Maybe (Reg,Reg)
ppc_takeRegRegMoveInstr (MR dst src) = Just (src,dst)
ppc_takeRegRegMoveInstr _ = Nothing
| mcmaniac/ghc | compiler/nativeGen/PPC/Instr.hs | bsd-3-clause | 15,650 | 340 | 13 | 4,402 | 4,905 | 2,566 | 2,339 | 306 | 49 |
module Handler.Comments where
import Import
import Model.Comment
import Model.Subscription
import Model.UserComment
import Notification
import Helper.Request
import Helper.Validation
import Text.Markdown
import qualified Data.Text.Lazy as TL
data CommentRequest = CommentRequest
{ reqArticle :: Text
, reqArticleTitle :: Text
, reqArticleAuthor :: Text
, reqThread :: Text
, reqBody :: Markdown
}
instance FromJSON CommentRequest where
parseJSON (Object v) = CommentRequest
<$> v .: "article_url"
<*> v .: "article_title"
<*> v .: "article_author"
<*> v .: "thread"
<*> fmap asMarkdown (v .: "body")
where
asMarkdown :: TL.Text -> Markdown
asMarkdown = Markdown . TL.filter (/= '\r')
parseJSON _ = mzero
postCommentsR :: SiteId -> Handler Value
postCommentsR siteId = do
allowCrossOrigin
u <- requireAuth
t <- liftIO getCurrentTime
c <- fmap (buildComment t u siteId) requireJsonBody
runValidation validateComment c $ \v -> do
userComment <- runDB $ do
commentId <- insert v
buildUserComment (Entity commentId v) u
let notification = NewComment userComment
runDB $ subscribe (notificationName notification) $ entityKey u
sendNotification notification
sendResponseStatus status201 $ object ["comment" .= userComment]
getCommentsR :: SiteId -> Handler Value
getCommentsR siteId = do
allowCrossOrigin
marticle <- lookupGetParam "article"
comments <- runDB $ findUserComments siteId marticle
return $ object ["comments" .= comments]
optionsCommentsR :: SiteId -> Handler ()
optionsCommentsR _ = do
allowCrossOrigin
sendResponseStatus status200 ()
buildComment :: UTCTime -> Entity User -> SiteId -> CommentRequest -> Comment
buildComment t u siteId req = Comment
{ commentUser = entityKey u
, commentSite = siteId
, commentArticleURL = reqArticle req
, commentArticleTitle = reqArticleTitle req
, commentArticleAuthor = reqArticleAuthor req
, commentThread = reqThread req
, commentBody = reqBody req
, commentCreated = t
}
| thoughtbot/carnival | Handler/Comments.hs | mit | 2,189 | 1 | 18 | 535 | 584 | 296 | 288 | 60 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.IAM.AddClientIDToOpenIDConnectProvider
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Adds a new client ID (also known as audience) to the list of client IDs
-- already registered for the specified IAM OpenID Connect provider.
--
-- This action is idempotent; it does not fail or return an error if you add an
-- existing client ID to the provider.
--
-- <http://docs.aws.amazon.com/IAM/latest/APIReference/API_AddClientIDToOpenIDConnectProvider.html>
module Network.AWS.IAM.AddClientIDToOpenIDConnectProvider
(
-- * Request
AddClientIDToOpenIDConnectProvider
-- ** Request constructor
, addClientIDToOpenIDConnectProvider
-- ** Request lenses
, acidtoidcpClientID
, acidtoidcpOpenIDConnectProviderArn
-- * Response
, AddClientIDToOpenIDConnectProviderResponse
-- ** Response constructor
, addClientIDToOpenIDConnectProviderResponse
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.IAM.Types
import qualified GHC.Exts
data AddClientIDToOpenIDConnectProvider = AddClientIDToOpenIDConnectProvider
{ _acidtoidcpClientID :: Text
, _acidtoidcpOpenIDConnectProviderArn :: Text
} deriving (Eq, Ord, Read, Show)
-- | 'AddClientIDToOpenIDConnectProvider' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'acidtoidcpClientID' @::@ 'Text'
--
-- * 'acidtoidcpOpenIDConnectProviderArn' @::@ 'Text'
--
addClientIDToOpenIDConnectProvider :: Text -- ^ 'acidtoidcpOpenIDConnectProviderArn'
-> Text -- ^ 'acidtoidcpClientID'
-> AddClientIDToOpenIDConnectProvider
addClientIDToOpenIDConnectProvider p1 p2 = AddClientIDToOpenIDConnectProvider
{ _acidtoidcpOpenIDConnectProviderArn = p1
, _acidtoidcpClientID = p2
}
-- | The client ID (also known as audience) to add to the IAM OpenID Connect
-- provider.
acidtoidcpClientID :: Lens' AddClientIDToOpenIDConnectProvider Text
acidtoidcpClientID =
lens _acidtoidcpClientID (\s a -> s { _acidtoidcpClientID = a })
-- | The Amazon Resource Name (ARN) of the IAM OpenID Connect (OIDC) provider to
-- add the client ID to. You can get a list of OIDC provider ARNs by using the 'ListOpenIDConnectProviders' action.
acidtoidcpOpenIDConnectProviderArn :: Lens' AddClientIDToOpenIDConnectProvider Text
acidtoidcpOpenIDConnectProviderArn =
lens _acidtoidcpOpenIDConnectProviderArn
(\s a -> s { _acidtoidcpOpenIDConnectProviderArn = a })
data AddClientIDToOpenIDConnectProviderResponse = AddClientIDToOpenIDConnectProviderResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'AddClientIDToOpenIDConnectProviderResponse' constructor.
addClientIDToOpenIDConnectProviderResponse :: AddClientIDToOpenIDConnectProviderResponse
addClientIDToOpenIDConnectProviderResponse = AddClientIDToOpenIDConnectProviderResponse
instance ToPath AddClientIDToOpenIDConnectProvider where
toPath = const "/"
instance ToQuery AddClientIDToOpenIDConnectProvider where
toQuery AddClientIDToOpenIDConnectProvider{..} = mconcat
[ "ClientID" =? _acidtoidcpClientID
, "OpenIDConnectProviderArn" =? _acidtoidcpOpenIDConnectProviderArn
]
instance ToHeaders AddClientIDToOpenIDConnectProvider
instance AWSRequest AddClientIDToOpenIDConnectProvider where
type Sv AddClientIDToOpenIDConnectProvider = IAM
type Rs AddClientIDToOpenIDConnectProvider = AddClientIDToOpenIDConnectProviderResponse
request = post "AddClientIDToOpenIDConnectProvider"
response = nullResponse AddClientIDToOpenIDConnectProviderResponse
| romanb/amazonka | amazonka-iam/gen/Network/AWS/IAM/AddClientIDToOpenIDConnectProvider.hs | mpl-2.0 | 4,615 | 0 | 9 | 892 | 399 | 246 | 153 | 55 | 1 |
{-
(c) The University of Glasgow, 2006
\section[HscTypes]{Types for the per-module compiler}
-}
{-# LANGUAGE CPP, DeriveDataTypeable, ScopedTypeVariables #-}
-- | Types for the per-module compiler
module HscTypes (
-- * compilation state
HscEnv(..), hscEPS,
FinderCache, FindResult(..), FoundHs(..), FindExactResult(..),
Target(..), TargetId(..), pprTarget, pprTargetId,
ModuleGraph, emptyMG,
HscStatus(..),
-- * Hsc monad
Hsc(..), runHsc, runInteractiveHsc,
-- * Information about modules
ModDetails(..), emptyModDetails,
ModGuts(..), CgGuts(..), ForeignStubs(..), appendStubC,
ImportedMods, ImportedModsVal,
ModSummary(..), ms_imps, ms_mod_name, showModMsg, isBootSummary,
msHsFilePath, msHiFilePath, msObjFilePath,
SourceModified(..),
-- * Information about the module being compiled
-- (re-exported from DriverPhases)
HscSource(..), isHsBootOrSig, hscSourceString,
-- * State relating to modules in this package
HomePackageTable, HomeModInfo(..), emptyHomePackageTable,
hptInstances, hptRules, hptVectInfo, pprHPT,
hptObjs,
-- * State relating to known packages
ExternalPackageState(..), EpsStats(..), addEpsInStats,
PackageTypeEnv, PackageIfaceTable, emptyPackageIfaceTable,
lookupIfaceByModule, emptyModIface, lookupHptByModule,
PackageInstEnv, PackageFamInstEnv, PackageRuleBase,
mkSOName, mkHsSOName, soExt,
-- * Metaprogramming
MetaRequest(..),
MetaResult, -- data constructors not exported to ensure correct response type
metaRequestE, metaRequestP, metaRequestT, metaRequestD, metaRequestAW,
MetaHook,
-- * Annotations
prepareAnnotations,
-- * Interactive context
InteractiveContext(..), emptyInteractiveContext,
icPrintUnqual, icInScopeTTs, icExtendGblRdrEnv,
extendInteractiveContext, extendInteractiveContextWithIds,
substInteractiveContext,
setInteractivePrintName, icInteractiveModule,
InteractiveImport(..), setInteractivePackage,
mkPrintUnqualified, pprModulePrefix,
mkQualPackage, mkQualModule, pkgQual,
-- * Interfaces
ModIface(..), mkIfaceWarnCache, mkIfaceHashCache, mkIfaceFixCache,
emptyIfaceWarnCache,
-- * Fixity
FixityEnv, FixItem(..), lookupFixity, emptyFixityEnv,
-- * TyThings and type environments
TyThing(..), tyThingAvailInfo,
tyThingTyCon, tyThingDataCon,
tyThingId, tyThingCoAxiom, tyThingParent_maybe, tyThingsTyVars,
implicitTyThings, implicitTyConThings, implicitClassThings,
isImplicitTyThing,
TypeEnv, lookupType, lookupTypeHscEnv, mkTypeEnv, emptyTypeEnv,
typeEnvFromEntities, mkTypeEnvWithImplicits,
extendTypeEnv, extendTypeEnvList,
extendTypeEnvWithIds,
lookupTypeEnv,
typeEnvElts, typeEnvTyCons, typeEnvIds, typeEnvPatSyns,
typeEnvDataCons, typeEnvCoAxioms, typeEnvClasses,
-- * MonadThings
MonadThings(..),
-- * Information on imports and exports
WhetherHasOrphans, IsBootInterface, Usage(..),
Dependencies(..), noDependencies,
NameCache(..), OrigNameCache,
IfaceExport,
-- * Warnings
Warnings(..), WarningTxt(..), plusWarns,
-- * Linker stuff
Linkable(..), isObjectLinkable, linkableObjs,
Unlinked(..), CompiledByteCode,
isObject, nameOfObject, isInterpretable, byteCodeOfObject,
-- * Program coverage
HpcInfo(..), emptyHpcInfo, isHpcUsed, AnyHpcUsage,
-- * Breakpoints
ModBreaks (..), BreakIndex, emptyModBreaks,
-- * Vectorisation information
VectInfo(..), IfaceVectInfo(..), noVectInfo, plusVectInfo,
noIfaceVectInfo, isNoIfaceVectInfo,
-- * Safe Haskell information
IfaceTrustInfo, getSafeMode, setSafeMode, noIfaceTrustInfo,
trustInfoToNum, numToTrustInfo, IsSafeImport,
-- * result of the parser
HsParsedModule(..),
-- * Compilation errors and warnings
SourceError, GhcApiError, mkSrcErr, srcErrorMessages, mkApiErr,
throwOneError, handleSourceError,
handleFlagWarnings, printOrThrowWarnings,
) where
#include "HsVersions.h"
#ifdef GHCI
import ByteCodeAsm ( CompiledByteCode )
import InteractiveEvalTypes ( Resume )
#endif
import HsSyn
import RdrName
import Avail
import Module
import InstEnv ( InstEnv, ClsInst, identicalClsInstHead )
import FamInstEnv
import CoreSyn ( CoreProgram, RuleBase )
import Name
import NameEnv
import NameSet
import VarEnv
import VarSet
import Var
import Id
import IdInfo ( IdDetails(..) )
import Type
import ApiAnnotation ( ApiAnns )
import Annotations ( Annotation, AnnEnv, mkAnnEnv, plusAnnEnv )
import Class
import TyCon
import CoAxiom
import ConLike
import DataCon
import PatSyn
import PrelNames ( gHC_PRIM, ioTyConName, printName, mkInteractiveModule )
import Packages hiding ( Version(..) )
import DynFlags
import DriverPhases ( Phase, HscSource(..), isHsBootOrSig, hscSourceString )
import BasicTypes
import IfaceSyn
import CoreSyn ( CoreRule, CoreVect )
import Maybes
import Outputable
import BreakArray
import SrcLoc
-- import Unique
import UniqFM
import UniqSupply
import FastString
import StringBuffer ( StringBuffer )
import Fingerprint
import MonadUtils
import Bag
import Binary
import ErrUtils
import Platform
import Util
import Serialized ( Serialized )
import Control.Monad ( guard, liftM, when, ap )
import Data.Array ( Array, array )
import Data.IORef
import Data.Time
import Data.Word
import Data.Typeable ( Typeable )
import Exception
import System.FilePath
-- -----------------------------------------------------------------------------
-- Compilation state
-- -----------------------------------------------------------------------------
-- | Status of a compilation to hard-code
data HscStatus
= HscNotGeneratingCode
| HscUpToDate
| HscUpdateBoot
| HscUpdateSig
| HscRecomp CgGuts ModSummary
-- -----------------------------------------------------------------------------
-- The Hsc monad: Passing an environment and warning state
newtype Hsc a = Hsc (HscEnv -> WarningMessages -> IO (a, WarningMessages))
instance Functor Hsc where
fmap = liftM
instance Applicative Hsc where
pure = return
(<*>) = ap
instance Monad Hsc where
return a = Hsc $ \_ w -> return (a, w)
Hsc m >>= k = Hsc $ \e w -> do (a, w1) <- m e w
case k a of
Hsc k' -> k' e w1
instance MonadIO Hsc where
liftIO io = Hsc $ \_ w -> do a <- io; return (a, w)
instance HasDynFlags Hsc where
getDynFlags = Hsc $ \e w -> return (hsc_dflags e, w)
runHsc :: HscEnv -> Hsc a -> IO a
runHsc hsc_env (Hsc hsc) = do
(a, w) <- hsc hsc_env emptyBag
printOrThrowWarnings (hsc_dflags hsc_env) w
return a
runInteractiveHsc :: HscEnv -> Hsc a -> IO a
-- A variant of runHsc that switches in the DynFlags from the
-- InteractiveContext before running the Hsc computation.
runInteractiveHsc hsc_env
= runHsc (hsc_env { hsc_dflags = interactive_dflags })
where
interactive_dflags = ic_dflags (hsc_IC hsc_env)
-- -----------------------------------------------------------------------------
-- Source Errors
-- When the compiler (HscMain) discovers errors, it throws an
-- exception in the IO monad.
mkSrcErr :: ErrorMessages -> SourceError
mkSrcErr = SourceError
srcErrorMessages :: SourceError -> ErrorMessages
srcErrorMessages (SourceError msgs) = msgs
mkApiErr :: DynFlags -> SDoc -> GhcApiError
mkApiErr dflags msg = GhcApiError (showSDoc dflags msg)
throwOneError :: MonadIO m => ErrMsg -> m ab
throwOneError err = liftIO $ throwIO $ mkSrcErr $ unitBag err
-- | A source error is an error that is caused by one or more errors in the
-- source code. A 'SourceError' is thrown by many functions in the
-- compilation pipeline. Inside GHC these errors are merely printed via
-- 'log_action', but API clients may treat them differently, for example,
-- insert them into a list box. If you want the default behaviour, use the
-- idiom:
--
-- > handleSourceError printExceptionAndWarnings $ do
-- > ... api calls that may fail ...
--
-- The 'SourceError's error messages can be accessed via 'srcErrorMessages'.
-- This list may be empty if the compiler failed due to @-Werror@
-- ('Opt_WarnIsError').
--
-- See 'printExceptionAndWarnings' for more information on what to take care
-- of when writing a custom error handler.
newtype SourceError = SourceError ErrorMessages
deriving Typeable
instance Show SourceError where
show (SourceError msgs) = unlines . map show . bagToList $ msgs
instance Exception SourceError
-- | Perform the given action and call the exception handler if the action
-- throws a 'SourceError'. See 'SourceError' for more information.
handleSourceError :: (ExceptionMonad m) =>
(SourceError -> m a) -- ^ exception handler
-> m a -- ^ action to perform
-> m a
handleSourceError handler act =
gcatch act (\(e :: SourceError) -> handler e)
-- | An error thrown if the GHC API is used in an incorrect fashion.
newtype GhcApiError = GhcApiError String
deriving Typeable
instance Show GhcApiError where
show (GhcApiError msg) = msg
instance Exception GhcApiError
-- | Given a bag of warnings, turn them into an exception if
-- -Werror is enabled, or print them out otherwise.
printOrThrowWarnings :: DynFlags -> Bag WarnMsg -> IO ()
printOrThrowWarnings dflags warns
| gopt Opt_WarnIsError dflags
= when (not (isEmptyBag warns)) $ do
throwIO $ mkSrcErr $ warns `snocBag` warnIsErrorMsg dflags
| otherwise
= printBagOfErrors dflags warns
handleFlagWarnings :: DynFlags -> [Located String] -> IO ()
handleFlagWarnings dflags warns
= when (wopt Opt_WarnDeprecatedFlags dflags) $ do
-- It would be nicer if warns :: [Located MsgDoc], but that
-- has circular import problems.
let bag = listToBag [ mkPlainWarnMsg dflags loc (text warn)
| L loc warn <- warns ]
printOrThrowWarnings dflags bag
{-
************************************************************************
* *
\subsection{HscEnv}
* *
************************************************************************
-}
-- | Hscenv is like 'Session', except that some of the fields are immutable.
-- An HscEnv is used to compile a single module from plain Haskell source
-- code (after preprocessing) to either C, assembly or C--. Things like
-- the module graph don't change during a single compilation.
--
-- Historical note: \"hsc\" used to be the name of the compiler binary,
-- when there was a separate driver and compiler. To compile a single
-- module, the driver would invoke hsc on the source code... so nowadays
-- we think of hsc as the layer of the compiler that deals with compiling
-- a single module.
data HscEnv
= HscEnv {
hsc_dflags :: DynFlags,
-- ^ The dynamic flag settings
hsc_targets :: [Target],
-- ^ The targets (or roots) of the current session
hsc_mod_graph :: ModuleGraph,
-- ^ The module graph of the current session
hsc_IC :: InteractiveContext,
-- ^ The context for evaluating interactive statements
hsc_HPT :: HomePackageTable,
-- ^ The home package table describes already-compiled
-- home-package modules, /excluding/ the module we
-- are compiling right now.
-- (In one-shot mode the current module is the only
-- home-package module, so hsc_HPT is empty. All other
-- modules count as \"external-package\" modules.
-- However, even in GHCi mode, hi-boot interfaces are
-- demand-loaded into the external-package table.)
--
-- 'hsc_HPT' is not mutable because we only demand-load
-- external packages; the home package is eagerly
-- loaded, module by module, by the compilation manager.
--
-- The HPT may contain modules compiled earlier by @--make@
-- but not actually below the current module in the dependency
-- graph.
--
-- (This changes a previous invariant: changed Jan 05.)
hsc_EPS :: {-# UNPACK #-} !(IORef ExternalPackageState),
-- ^ Information about the currently loaded external packages.
-- This is mutable because packages will be demand-loaded during
-- a compilation run as required.
hsc_NC :: {-# UNPACK #-} !(IORef NameCache),
-- ^ As with 'hsc_EPS', this is side-effected by compiling to
-- reflect sucking in interface files. They cache the state of
-- external interface files, in effect.
hsc_FC :: {-# UNPACK #-} !(IORef FinderCache),
-- ^ The cached result of performing finding in the file system
hsc_type_env_var :: Maybe (Module, IORef TypeEnv)
-- ^ Used for one-shot compilation only, to initialise
-- the 'IfGblEnv'. See 'TcRnTypes.tcg_type_env_var' for
-- 'TcRunTypes.TcGblEnv'
}
instance ContainsDynFlags HscEnv where
extractDynFlags env = hsc_dflags env
replaceDynFlags env dflags = env {hsc_dflags = dflags}
-- | Retrieve the ExternalPackageState cache.
hscEPS :: HscEnv -> IO ExternalPackageState
hscEPS hsc_env = readIORef (hsc_EPS hsc_env)
-- | A compilation target.
--
-- A target may be supplied with the actual text of the
-- module. If so, use this instead of the file contents (this
-- is for use in an IDE where the file hasn't been saved by
-- the user yet).
data Target
= Target {
targetId :: TargetId, -- ^ module or filename
targetAllowObjCode :: Bool, -- ^ object code allowed?
targetContents :: Maybe (StringBuffer,UTCTime)
-- ^ in-memory text buffer?
}
data TargetId
= TargetModule ModuleName
-- ^ A module name: search for the file
| TargetFile FilePath (Maybe Phase)
-- ^ A filename: preprocess & parse it to find the module name.
-- If specified, the Phase indicates how to compile this file
-- (which phase to start from). Nothing indicates the starting phase
-- should be determined from the suffix of the filename.
deriving Eq
pprTarget :: Target -> SDoc
pprTarget (Target id obj _) =
(if obj then char '*' else empty) <> pprTargetId id
instance Outputable Target where
ppr = pprTarget
pprTargetId :: TargetId -> SDoc
pprTargetId (TargetModule m) = ppr m
pprTargetId (TargetFile f _) = text f
instance Outputable TargetId where
ppr = pprTargetId
{-
************************************************************************
* *
\subsection{Package and Module Tables}
* *
************************************************************************
-}
-- | Helps us find information about modules in the home package
type HomePackageTable = ModuleNameEnv HomeModInfo
-- Domain = modules in the home package that have been fully compiled
-- "home" package key cached here for convenience
-- | Helps us find information about modules in the imported packages
type PackageIfaceTable = ModuleEnv ModIface
-- Domain = modules in the imported packages
-- | Constructs an empty HomePackageTable
emptyHomePackageTable :: HomePackageTable
emptyHomePackageTable = emptyUFM
-- | Constructs an empty PackageIfaceTable
emptyPackageIfaceTable :: PackageIfaceTable
emptyPackageIfaceTable = emptyModuleEnv
pprHPT :: HomePackageTable -> SDoc
-- A bit aribitrary for now
pprHPT hpt
= vcat [ hang (ppr (mi_module (hm_iface hm)))
2 (ppr (md_types (hm_details hm)))
| hm <- eltsUFM hpt ]
lookupHptByModule :: HomePackageTable -> Module -> Maybe HomeModInfo
-- The HPT is indexed by ModuleName, not Module,
-- we must check for a hit on the right Module
lookupHptByModule hpt mod
= case lookupUFM hpt (moduleName mod) of
Just hm | mi_module (hm_iface hm) == mod -> Just hm
_otherwise -> Nothing
-- | Information about modules in the package being compiled
data HomeModInfo
= HomeModInfo {
hm_iface :: !ModIface,
-- ^ The basic loaded interface file: every loaded module has one of
-- these, even if it is imported from another package
hm_details :: !ModDetails,
-- ^ Extra information that has been created from the 'ModIface' for
-- the module, typically during typechecking
hm_linkable :: !(Maybe Linkable)
-- ^ The actual artifact we would like to link to access things in
-- this module.
--
-- 'hm_linkable' might be Nothing:
--
-- 1. If this is an .hs-boot module
--
-- 2. Temporarily during compilation if we pruned away
-- the old linkable because it was out of date.
--
-- After a complete compilation ('GHC.load'), all 'hm_linkable' fields
-- in the 'HomePackageTable' will be @Just@.
--
-- When re-linking a module ('HscMain.HscNoRecomp'), we construct the
-- 'HomeModInfo' by building a new 'ModDetails' from the old
-- 'ModIface' (only).
}
-- | Find the 'ModIface' for a 'Module', searching in both the loaded home
-- and external package module information
lookupIfaceByModule
:: DynFlags
-> HomePackageTable
-> PackageIfaceTable
-> Module
-> Maybe ModIface
lookupIfaceByModule _dflags hpt pit mod
= case lookupHptByModule hpt mod of
Just hm -> Just (hm_iface hm)
Nothing -> lookupModuleEnv pit mod
-- If the module does come from the home package, why do we look in the PIT as well?
-- (a) In OneShot mode, even home-package modules accumulate in the PIT
-- (b) Even in Batch (--make) mode, there is *one* case where a home-package
-- module is in the PIT, namely GHC.Prim when compiling the base package.
-- We could eliminate (b) if we wanted, by making GHC.Prim belong to a package
-- of its own, but it doesn't seem worth the bother.
-- | Find all the instance declarations (of classes and families) from
-- the Home Package Table filtered by the provided predicate function.
-- Used in @tcRnImports@, to select the instances that are in the
-- transitive closure of imports from the currently compiled module.
hptInstances :: HscEnv -> (ModuleName -> Bool) -> ([ClsInst], [FamInst])
hptInstances hsc_env want_this_module
= let (insts, famInsts) = unzip $ flip hptAllThings hsc_env $ \mod_info -> do
guard (want_this_module (moduleName (mi_module (hm_iface mod_info))))
let details = hm_details mod_info
return (md_insts details, md_fam_insts details)
in (concat insts, concat famInsts)
-- | Get the combined VectInfo of all modules in the home package table. In
-- contrast to instances and rules, we don't care whether the modules are
-- "below" us in the dependency sense. The VectInfo of those modules not "below"
-- us does not affect the compilation of the current module.
hptVectInfo :: HscEnv -> VectInfo
hptVectInfo = concatVectInfo . hptAllThings ((: []) . md_vect_info . hm_details)
-- | Get rules from modules "below" this one (in the dependency sense)
hptRules :: HscEnv -> [(ModuleName, IsBootInterface)] -> [CoreRule]
hptRules = hptSomeThingsBelowUs (md_rules . hm_details) False
-- | Get annotations from modules "below" this one (in the dependency sense)
hptAnns :: HscEnv -> Maybe [(ModuleName, IsBootInterface)] -> [Annotation]
hptAnns hsc_env (Just deps) = hptSomeThingsBelowUs (md_anns . hm_details) False hsc_env deps
hptAnns hsc_env Nothing = hptAllThings (md_anns . hm_details) hsc_env
hptAllThings :: (HomeModInfo -> [a]) -> HscEnv -> [a]
hptAllThings extract hsc_env = concatMap extract (eltsUFM (hsc_HPT hsc_env))
-- | Get things from modules "below" this one (in the dependency sense)
-- C.f Inst.hptInstances
hptSomeThingsBelowUs :: (HomeModInfo -> [a]) -> Bool -> HscEnv -> [(ModuleName, IsBootInterface)] -> [a]
hptSomeThingsBelowUs extract include_hi_boot hsc_env deps
| isOneShot (ghcMode (hsc_dflags hsc_env)) = []
| otherwise
= let hpt = hsc_HPT hsc_env
in
[ thing
| -- Find each non-hi-boot module below me
(mod, is_boot_mod) <- deps
, include_hi_boot || not is_boot_mod
-- unsavoury: when compiling the base package with --make, we
-- sometimes try to look up RULES etc for GHC.Prim. GHC.Prim won't
-- be in the HPT, because we never compile it; it's in the EPT
-- instead. ToDo: clean up, and remove this slightly bogus filter:
, mod /= moduleName gHC_PRIM
-- Look it up in the HPT
, let things = case lookupUFM hpt mod of
Just info -> extract info
Nothing -> pprTrace "WARNING in hptSomeThingsBelowUs" msg []
msg = vcat [ptext (sLit "missing module") <+> ppr mod,
ptext (sLit "Probable cause: out-of-date interface files")]
-- This really shouldn't happen, but see Trac #962
-- And get its dfuns
, thing <- things ]
hptObjs :: HomePackageTable -> [FilePath]
hptObjs hpt = concat (map (maybe [] linkableObjs . hm_linkable) (eltsUFM hpt))
{-
************************************************************************
* *
\subsection{Metaprogramming}
* *
************************************************************************
-}
-- | The supported metaprogramming result types
data MetaRequest
= MetaE (LHsExpr RdrName -> MetaResult)
| MetaP (LPat RdrName -> MetaResult)
| MetaT (LHsType RdrName -> MetaResult)
| MetaD ([LHsDecl RdrName] -> MetaResult)
| MetaAW (Serialized -> MetaResult)
-- | data constructors not exported to ensure correct result type
data MetaResult
= MetaResE { unMetaResE :: LHsExpr RdrName }
| MetaResP { unMetaResP :: LPat RdrName }
| MetaResT { unMetaResT :: LHsType RdrName }
| MetaResD { unMetaResD :: [LHsDecl RdrName] }
| MetaResAW { unMetaResAW :: Serialized }
type MetaHook f = MetaRequest -> LHsExpr Id -> f MetaResult
metaRequestE :: Functor f => MetaHook f -> LHsExpr Id -> f (LHsExpr RdrName)
metaRequestE h = fmap unMetaResE . h (MetaE MetaResE)
metaRequestP :: Functor f => MetaHook f -> LHsExpr Id -> f (LPat RdrName)
metaRequestP h = fmap unMetaResP . h (MetaP MetaResP)
metaRequestT :: Functor f => MetaHook f -> LHsExpr Id -> f (LHsType RdrName)
metaRequestT h = fmap unMetaResT . h (MetaT MetaResT)
metaRequestD :: Functor f => MetaHook f -> LHsExpr Id -> f [LHsDecl RdrName]
metaRequestD h = fmap unMetaResD . h (MetaD MetaResD)
metaRequestAW :: Functor f => MetaHook f -> LHsExpr Id -> f Serialized
metaRequestAW h = fmap unMetaResAW . h (MetaAW MetaResAW)
{-
************************************************************************
* *
\subsection{Dealing with Annotations}
* *
************************************************************************
-}
-- | Deal with gathering annotations in from all possible places
-- and combining them into a single 'AnnEnv'
prepareAnnotations :: HscEnv -> Maybe ModGuts -> IO AnnEnv
prepareAnnotations hsc_env mb_guts = do
eps <- hscEPS hsc_env
let -- Extract annotations from the module being compiled if supplied one
mb_this_module_anns = fmap (mkAnnEnv . mg_anns) mb_guts
-- Extract dependencies of the module if we are supplied one,
-- otherwise load annotations from all home package table
-- entries regardless of dependency ordering.
home_pkg_anns = (mkAnnEnv . hptAnns hsc_env) $ fmap (dep_mods . mg_deps) mb_guts
other_pkg_anns = eps_ann_env eps
ann_env = foldl1' plusAnnEnv $ catMaybes [mb_this_module_anns,
Just home_pkg_anns,
Just other_pkg_anns]
return ann_env
{-
************************************************************************
* *
\subsection{The Finder cache}
* *
************************************************************************
-}
-- | The 'FinderCache' maps modules to the result of
-- searching for that module. It records the results of searching for
-- modules along the search path. On @:load@, we flush the entire
-- contents of this cache.
--
type FinderCache = ModuleEnv FindExactResult
-- | The result of search for an exact 'Module'.
data FindExactResult
= FoundExact ModLocation Module
-- ^ The module/signature was found
| NoPackageExact PackageKey
| NotFoundExact
{ fer_paths :: [FilePath]
, fer_pkg :: Maybe PackageKey
}
-- | A found module or signature; e.g. anything with an interface file
data FoundHs = FoundHs { fr_loc :: ModLocation
, fr_mod :: Module
-- , fr_origin :: ModuleOrigin
}
-- | The result of searching for an imported module.
data FindResult
= FoundModule FoundHs
-- ^ The module was found
| FoundSigs [FoundHs] Module
-- ^ Signatures were found, with some backing implementation
| NoPackage PackageKey
-- ^ The requested package was not found
| FoundMultiple [(Module, ModuleOrigin)]
-- ^ _Error_: both in multiple packages
-- | Not found
| NotFound
{ fr_paths :: [FilePath] -- Places where I looked
, fr_pkg :: Maybe PackageKey -- Just p => module is in this package's
-- manifest, but couldn't find
-- the .hi file
, fr_mods_hidden :: [PackageKey] -- Module is in these packages,
-- but the *module* is hidden
, fr_pkgs_hidden :: [PackageKey] -- Module is in these packages,
-- but the *package* is hidden
, fr_suggestions :: [ModuleSuggestion] -- Possible mis-spelled modules
}
{-
************************************************************************
* *
\subsection{Symbol tables and Module details}
* *
************************************************************************
-}
-- | A 'ModIface' plus a 'ModDetails' summarises everything we know
-- about a compiled module. The 'ModIface' is the stuff *before* linking,
-- and can be written out to an interface file. The 'ModDetails is after
-- linking and can be completely recovered from just the 'ModIface'.
--
-- When we read an interface file, we also construct a 'ModIface' from it,
-- except that we explicitly make the 'mi_decls' and a few other fields empty;
-- as when reading we consolidate the declarations etc. into a number of indexed
-- maps and environments in the 'ExternalPackageState'.
data ModIface
= ModIface {
mi_module :: !Module, -- ^ Name of the module we are for
mi_sig_of :: !(Maybe Module), -- ^ Are we a sig of another mod?
mi_iface_hash :: !Fingerprint, -- ^ Hash of the whole interface
mi_mod_hash :: !Fingerprint, -- ^ Hash of the ABI only
mi_flag_hash :: !Fingerprint, -- ^ Hash of the important flags
-- used when compiling this module
mi_orphan :: !WhetherHasOrphans, -- ^ Whether this module has orphans
mi_finsts :: !WhetherHasFamInst, -- ^ Whether this module has family instances
mi_boot :: !IsBootInterface, -- ^ Read from an hi-boot file?
mi_deps :: Dependencies,
-- ^ The dependencies of the module. This is
-- consulted for directly-imported modules, but not
-- for anything else (hence lazy)
mi_usages :: [Usage],
-- ^ Usages; kept sorted so that it's easy to decide
-- whether to write a new iface file (changing usages
-- doesn't affect the hash of this module)
-- NOT STRICT! we read this field lazily from the interface file
-- It is *only* consulted by the recompilation checker
mi_exports :: ![IfaceExport],
-- ^ Exports
-- Kept sorted by (mod,occ), to make version comparisons easier
-- Records the modules that are the declaration points for things
-- exported by this module, and the 'OccName's of those things
mi_exp_hash :: !Fingerprint,
-- ^ Hash of export list
mi_used_th :: !Bool,
-- ^ Module required TH splices when it was compiled.
-- This disables recompilation avoidance (see #481).
mi_fixities :: [(OccName,Fixity)],
-- ^ Fixities
-- NOT STRICT! we read this field lazily from the interface file
mi_warns :: Warnings,
-- ^ Warnings
-- NOT STRICT! we read this field lazily from the interface file
mi_anns :: [IfaceAnnotation],
-- ^ Annotations
-- NOT STRICT! we read this field lazily from the interface file
mi_decls :: [(Fingerprint,IfaceDecl)],
-- ^ Type, class and variable declarations
-- The hash of an Id changes if its fixity or deprecations change
-- (as well as its type of course)
-- Ditto data constructors, class operations, except that
-- the hash of the parent class/tycon changes
mi_globals :: !(Maybe GlobalRdrEnv),
-- ^ Binds all the things defined at the top level in
-- the /original source/ code for this module. which
-- is NOT the same as mi_exports, nor mi_decls (which
-- may contains declarations for things not actually
-- defined by the user). Used for GHCi and for inspecting
-- the contents of modules via the GHC API only.
--
-- (We need the source file to figure out the
-- top-level environment, if we didn't compile this module
-- from source then this field contains @Nothing@).
--
-- Strictly speaking this field should live in the
-- 'HomeModInfo', but that leads to more plumbing.
-- Instance declarations and rules
mi_insts :: [IfaceClsInst], -- ^ Sorted class instance
mi_fam_insts :: [IfaceFamInst], -- ^ Sorted family instances
mi_rules :: [IfaceRule], -- ^ Sorted rules
mi_orphan_hash :: !Fingerprint, -- ^ Hash for orphan rules, class and family
-- instances, and vectorise pragmas combined
mi_vect_info :: !IfaceVectInfo, -- ^ Vectorisation information
-- Cached environments for easy lookup
-- These are computed (lazily) from other fields
-- and are not put into the interface file
mi_warn_fn :: Name -> Maybe WarningTxt, -- ^ Cached lookup for 'mi_warns'
mi_fix_fn :: OccName -> Fixity, -- ^ Cached lookup for 'mi_fixities'
mi_hash_fn :: OccName -> Maybe (OccName, Fingerprint),
-- ^ Cached lookup for 'mi_decls'.
-- The @Nothing@ in 'mi_hash_fn' means that the thing
-- isn't in decls. It's useful to know that when
-- seeing if we are up to date wrt. the old interface.
-- The 'OccName' is the parent of the name, if it has one.
mi_hpc :: !AnyHpcUsage,
-- ^ True if this program uses Hpc at any point in the program.
mi_trust :: !IfaceTrustInfo,
-- ^ Safe Haskell Trust information for this module.
mi_trust_pkg :: !Bool
-- ^ Do we require the package this module resides in be trusted
-- to trust this module? This is used for the situation where a
-- module is Safe (so doesn't require the package be trusted
-- itself) but imports some trustworthy modules from its own
-- package (which does require its own package be trusted).
-- See Note [RnNames . Trust Own Package]
}
instance Binary ModIface where
put_ bh (ModIface {
mi_module = mod,
mi_sig_of = sig_of,
mi_boot = is_boot,
mi_iface_hash= iface_hash,
mi_mod_hash = mod_hash,
mi_flag_hash = flag_hash,
mi_orphan = orphan,
mi_finsts = hasFamInsts,
mi_deps = deps,
mi_usages = usages,
mi_exports = exports,
mi_exp_hash = exp_hash,
mi_used_th = used_th,
mi_fixities = fixities,
mi_warns = warns,
mi_anns = anns,
mi_decls = decls,
mi_insts = insts,
mi_fam_insts = fam_insts,
mi_rules = rules,
mi_orphan_hash = orphan_hash,
mi_vect_info = vect_info,
mi_hpc = hpc_info,
mi_trust = trust,
mi_trust_pkg = trust_pkg }) = do
put_ bh mod
put_ bh is_boot
put_ bh iface_hash
put_ bh mod_hash
put_ bh flag_hash
put_ bh orphan
put_ bh hasFamInsts
lazyPut bh deps
lazyPut bh usages
put_ bh exports
put_ bh exp_hash
put_ bh used_th
put_ bh fixities
lazyPut bh warns
lazyPut bh anns
put_ bh decls
put_ bh insts
put_ bh fam_insts
lazyPut bh rules
put_ bh orphan_hash
put_ bh vect_info
put_ bh hpc_info
put_ bh trust
put_ bh trust_pkg
put_ bh sig_of
get bh = do
mod_name <- get bh
is_boot <- get bh
iface_hash <- get bh
mod_hash <- get bh
flag_hash <- get bh
orphan <- get bh
hasFamInsts <- get bh
deps <- lazyGet bh
usages <- {-# SCC "bin_usages" #-} lazyGet bh
exports <- {-# SCC "bin_exports" #-} get bh
exp_hash <- get bh
used_th <- get bh
fixities <- {-# SCC "bin_fixities" #-} get bh
warns <- {-# SCC "bin_warns" #-} lazyGet bh
anns <- {-# SCC "bin_anns" #-} lazyGet bh
decls <- {-# SCC "bin_tycldecls" #-} get bh
insts <- {-# SCC "bin_insts" #-} get bh
fam_insts <- {-# SCC "bin_fam_insts" #-} get bh
rules <- {-# SCC "bin_rules" #-} lazyGet bh
orphan_hash <- get bh
vect_info <- get bh
hpc_info <- get bh
trust <- get bh
trust_pkg <- get bh
sig_of <- get bh
return (ModIface {
mi_module = mod_name,
mi_sig_of = sig_of,
mi_boot = is_boot,
mi_iface_hash = iface_hash,
mi_mod_hash = mod_hash,
mi_flag_hash = flag_hash,
mi_orphan = orphan,
mi_finsts = hasFamInsts,
mi_deps = deps,
mi_usages = usages,
mi_exports = exports,
mi_exp_hash = exp_hash,
mi_used_th = used_th,
mi_anns = anns,
mi_fixities = fixities,
mi_warns = warns,
mi_decls = decls,
mi_globals = Nothing,
mi_insts = insts,
mi_fam_insts = fam_insts,
mi_rules = rules,
mi_orphan_hash = orphan_hash,
mi_vect_info = vect_info,
mi_hpc = hpc_info,
mi_trust = trust,
mi_trust_pkg = trust_pkg,
-- And build the cached values
mi_warn_fn = mkIfaceWarnCache warns,
mi_fix_fn = mkIfaceFixCache fixities,
mi_hash_fn = mkIfaceHashCache decls })
-- | The original names declared of a certain module that are exported
type IfaceExport = AvailInfo
-- | Constructs an empty ModIface
emptyModIface :: Module -> ModIface
emptyModIface mod
= ModIface { mi_module = mod,
mi_sig_of = Nothing,
mi_iface_hash = fingerprint0,
mi_mod_hash = fingerprint0,
mi_flag_hash = fingerprint0,
mi_orphan = False,
mi_finsts = False,
mi_boot = False,
mi_deps = noDependencies,
mi_usages = [],
mi_exports = [],
mi_exp_hash = fingerprint0,
mi_used_th = False,
mi_fixities = [],
mi_warns = NoWarnings,
mi_anns = [],
mi_insts = [],
mi_fam_insts = [],
mi_rules = [],
mi_decls = [],
mi_globals = Nothing,
mi_orphan_hash = fingerprint0,
mi_vect_info = noIfaceVectInfo,
mi_warn_fn = emptyIfaceWarnCache,
mi_fix_fn = emptyIfaceFixCache,
mi_hash_fn = emptyIfaceHashCache,
mi_hpc = False,
mi_trust = noIfaceTrustInfo,
mi_trust_pkg = False }
-- | Constructs cache for the 'mi_hash_fn' field of a 'ModIface'
mkIfaceHashCache :: [(Fingerprint,IfaceDecl)]
-> (OccName -> Maybe (OccName, Fingerprint))
mkIfaceHashCache pairs
= \occ -> lookupOccEnv env occ
where
env = foldr add_decl emptyOccEnv pairs
add_decl (v,d) env0 = foldr add env0 (ifaceDeclFingerprints v d)
where
add (occ,hash) env0 = extendOccEnv env0 occ (occ,hash)
emptyIfaceHashCache :: OccName -> Maybe (OccName, Fingerprint)
emptyIfaceHashCache _occ = Nothing
-- | The 'ModDetails' is essentially a cache for information in the 'ModIface'
-- for home modules only. Information relating to packages will be loaded into
-- global environments in 'ExternalPackageState'.
data ModDetails
= ModDetails {
-- The next two fields are created by the typechecker
md_exports :: [AvailInfo],
md_types :: !TypeEnv, -- ^ Local type environment for this particular module
-- Includes Ids, TyCons, PatSyns
md_insts :: ![ClsInst], -- ^ 'DFunId's for the instances in this module
md_fam_insts :: ![FamInst],
md_rules :: ![CoreRule], -- ^ Domain may include 'Id's from other modules
md_anns :: ![Annotation], -- ^ Annotations present in this module: currently
-- they only annotate things also declared in this module
md_vect_info :: !VectInfo -- ^ Module vectorisation information
}
-- | Constructs an empty ModDetails
emptyModDetails :: ModDetails
emptyModDetails
= ModDetails { md_types = emptyTypeEnv,
md_exports = [],
md_insts = [],
md_rules = [],
md_fam_insts = [],
md_anns = [],
md_vect_info = noVectInfo }
-- | Records the modules directly imported by a module for extracting e.g. usage information
type ImportedMods = ModuleEnv [ImportedModsVal]
type ImportedModsVal = (ModuleName, Bool, SrcSpan, IsSafeImport)
-- | A ModGuts is carried through the compiler, accumulating stuff as it goes
-- There is only one ModGuts at any time, the one for the module
-- being compiled right now. Once it is compiled, a 'ModIface' and
-- 'ModDetails' are extracted and the ModGuts is discarded.
data ModGuts
= ModGuts {
mg_module :: !Module, -- ^ Module being compiled
mg_boot :: IsBootInterface, -- ^ Whether it's an hs-boot module
mg_exports :: ![AvailInfo], -- ^ What it exports
mg_deps :: !Dependencies, -- ^ What it depends on, directly or
-- otherwise
mg_dir_imps :: !ImportedMods, -- ^ Directly-imported modules; used to
-- generate initialisation code
mg_used_names:: !NameSet, -- ^ What the module needed (used in 'MkIface.mkIface')
mg_used_th :: !Bool, -- ^ Did we run a TH splice?
mg_rdr_env :: !GlobalRdrEnv, -- ^ Top-level lexical environment
-- These fields all describe the things **declared in this module**
mg_fix_env :: !FixityEnv, -- ^ Fixities declared in this module.
-- Used for creating interface files.
mg_tcs :: ![TyCon], -- ^ TyCons declared in this module
-- (includes TyCons for classes)
mg_insts :: ![ClsInst], -- ^ Class instances declared in this module
mg_fam_insts :: ![FamInst],
-- ^ Family instances declared in this module
mg_patsyns :: ![PatSyn], -- ^ Pattern synonyms declared in this module
mg_rules :: ![CoreRule], -- ^ Before the core pipeline starts, contains
-- See Note [Overall plumbing for rules] in Rules.hs
mg_binds :: !CoreProgram, -- ^ Bindings for this module
mg_foreign :: !ForeignStubs, -- ^ Foreign exports declared in this module
mg_warns :: !Warnings, -- ^ Warnings declared in the module
mg_anns :: [Annotation], -- ^ Annotations declared in this module
mg_hpc_info :: !HpcInfo, -- ^ Coverage tick boxes in the module
mg_modBreaks :: !ModBreaks, -- ^ Breakpoints for the module
mg_vect_decls:: ![CoreVect], -- ^ Vectorisation declarations in this module
-- (produced by desugarer & consumed by vectoriser)
mg_vect_info :: !VectInfo, -- ^ Pool of vectorised declarations in the module
-- The next two fields are unusual, because they give instance
-- environments for *all* modules in the home package, including
-- this module, rather than for *just* this module.
-- Reason: when looking up an instance we don't want to have to
-- look at each module in the home package in turn
mg_inst_env :: InstEnv,
-- ^ Class instance environment from /home-package/ modules (including
-- this one); c.f. 'tcg_inst_env'
mg_fam_inst_env :: FamInstEnv,
-- ^ Type-family instance environment for /home-package/ modules
-- (including this one); c.f. 'tcg_fam_inst_env'
mg_safe_haskell :: SafeHaskellMode,
-- ^ Safe Haskell mode
mg_trust_pkg :: Bool,
-- ^ Do we need to trust our own package for Safe Haskell?
-- See Note [RnNames . Trust Own Package]
mg_dependent_files :: [FilePath] -- ^ dependencies from addDependentFile
}
-- The ModGuts takes on several slightly different forms:
--
-- After simplification, the following fields change slightly:
-- mg_rules Orphan rules only (local ones now attached to binds)
-- mg_binds With rules attached
---------------------------------------------------------
-- The Tidy pass forks the information about this module:
-- * one lot goes to interface file generation (ModIface)
-- and later compilations (ModDetails)
-- * the other lot goes to code generation (CgGuts)
-- | A restricted form of 'ModGuts' for code generation purposes
data CgGuts
= CgGuts {
cg_module :: !Module,
-- ^ Module being compiled
cg_tycons :: [TyCon],
-- ^ Algebraic data types (including ones that started
-- life as classes); generate constructors and info
-- tables. Includes newtypes, just for the benefit of
-- External Core
cg_binds :: CoreProgram,
-- ^ The tidied main bindings, including
-- previously-implicit bindings for record and class
-- selectors, and data constructor wrappers. But *not*
-- data constructor workers; reason: we we regard them
-- as part of the code-gen of tycons
cg_foreign :: !ForeignStubs, -- ^ Foreign export stubs
cg_dep_pkgs :: ![PackageKey], -- ^ Dependent packages, used to
-- generate #includes for C code gen
cg_hpc_info :: !HpcInfo, -- ^ Program coverage tick box information
cg_modBreaks :: !ModBreaks -- ^ Module breakpoints
}
-----------------------------------
-- | Foreign export stubs
data ForeignStubs
= NoStubs
-- ^ We don't have any stubs
| ForeignStubs SDoc SDoc
-- ^ There are some stubs. Parameters:
--
-- 1) Header file prototypes for
-- "foreign exported" functions
--
-- 2) C stubs to use when calling
-- "foreign exported" functions
appendStubC :: ForeignStubs -> SDoc -> ForeignStubs
appendStubC NoStubs c_code = ForeignStubs empty c_code
appendStubC (ForeignStubs h c) c_code = ForeignStubs h (c $$ c_code)
{-
************************************************************************
* *
\subsection{The interactive context}
* *
************************************************************************
Note [The interactive package]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Type, class, and value declarations at the command prompt are treated
as if they were defined in modules
interactive:Ghci1
interactive:Ghci2
...etc...
with each bunch of declarations using a new module, all sharing a
common package 'interactive' (see Module.interactivePackageKey, and
PrelNames.mkInteractiveModule).
This scheme deals well with shadowing. For example:
ghci> data T = A
ghci> data T = B
ghci> :i A
data Ghci1.T = A -- Defined at <interactive>:2:10
Here we must display info about constructor A, but its type T has been
shadowed by the second declaration. But it has a respectable
qualified name (Ghci1.T), and its source location says where it was
defined.
So the main invariant continues to hold, that in any session an
original name M.T only refers to one unique thing. (In a previous
iteration both the T's above were called :Interactive.T, albeit with
different uniques, which gave rise to all sorts of trouble.)
The details are a bit tricky though:
* The field ic_mod_index counts which Ghci module we've got up to.
It is incremented when extending ic_tythings
* ic_tythings contains only things from the 'interactive' package.
* Module from the 'interactive' package (Ghci1, Ghci2 etc) never go
in the Home Package Table (HPT). When you say :load, that's when we
extend the HPT.
* The 'thisPackage' field of DynFlags is *not* set to 'interactive'.
It stays as 'main' (or whatever -this-package-key says), and is the
package to which :load'ed modules are added to.
* So how do we arrange that declarations at the command prompt get to
be in the 'interactive' package? Simply by setting the tcg_mod
field of the TcGblEnv to "interactive:Ghci1". This is done by the
call to initTc in initTcInteractive, which in turn get the module
from it 'icInteractiveModule' field of the interactive context.
The 'thisPackage' field stays as 'main' (or whatever -this-package-key says.
* The main trickiness is that the type environment (tcg_type_env) and
fixity envt (tcg_fix_env), now contain entities from all the
interactive-package modules (Ghci1, Ghci2, ...) together, rather
than just a single module as is usually the case. So you can't use
"nameIsLocalOrFrom" to decide whether to look in the TcGblEnv vs
the HPT/PTE. This is a change, but not a problem provided you
know.
* However, the tcg_binds, tcg_sigs, tcg_insts, tcg_fam_insts, etc fields
of the TcGblEnv, which collect "things defined in this module", all
refer to stuff define in a single GHCi command, *not* all the commands
so far.
In contrast, tcg_inst_env, tcg_fam_inst_env, have instances from
all GhciN modules, which makes sense -- they are all "home package"
modules.
Note [Interactively-bound Ids in GHCi]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The Ids bound by previous Stmts in GHCi are currently
a) GlobalIds
b) with an Internal Name (not External)
c) and a tidied type
(a) They must be GlobalIds (not LocalIds) otherwise when we come to
compile an expression using these ids later, the byte code
generator will consider the occurrences to be free rather than
global.
(b) They start with an Internal Name because a Stmt is a local
construct, so the renamer naturally builds an Internal name for
each of its binders. It would be possible subsequently to give
them an External Name (in a GhciN module) but then we'd have
to substitute it out. So for now they stay Internal.
(c) Their types are tidied. This is important, because :info may ask
to look at them, and :info expects the things it looks up to have
tidy types
However note that TyCons, Classes, and even Ids bound by other top-level
declarations in GHCi (eg foreign import, record selectors) currently get
External Names, with Ghci9 (or 8, or 7, etc) as the module name.
Note [ic_tythings]
~~~~~~~~~~~~~~~~~~
The ic_tythings field contains
* The TyThings declared by the user at the command prompt
(eg Ids, TyCons, Classes)
* The user-visible Ids that arise from such things, which
*don't* come from 'implicitTyThings', notably:
- record selectors
- class ops
The implicitTyThings are readily obtained from the TyThings
but record selectors etc are not
It does *not* contain
* DFunIds (they can be gotten from ic_instances)
* CoAxioms (ditto)
See also Note [Interactively-bound Ids in GHCi]
Note [Override identical instances in GHCi]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If you declare a new instance in GHCi that is identical to a previous one,
we simply override the previous one; we don't regard it as overlapping.
e.g. Prelude> data T = A | B
Prelude> instance Eq T where ...
Prelude> instance Eq T where ... -- This one overrides
It's exactly the same for type-family instances. See Trac #7102
-}
-- | Interactive context, recording information about the state of the
-- context in which statements are executed in a GHC session.
data InteractiveContext
= InteractiveContext {
ic_dflags :: DynFlags,
-- ^ The 'DynFlags' used to evaluate interative expressions
-- and statements.
ic_mod_index :: Int,
-- ^ Each GHCi stmt or declaration brings some new things into
-- scope. We give them names like interactive:Ghci9.T,
-- where the ic_index is the '9'. The ic_mod_index is
-- incremented whenever we add something to ic_tythings
-- See Note [The interactive package]
ic_imports :: [InteractiveImport],
-- ^ The GHCi top-level scope (ic_rn_gbl_env) is extended with
-- these imports
--
-- This field is only stored here so that the client
-- can retrieve it with GHC.getContext. GHC itself doesn't
-- use it, but does reset it to empty sometimes (such
-- as before a GHC.load). The context is set with GHC.setContext.
ic_tythings :: [TyThing],
-- ^ TyThings defined by the user, in reverse order of
-- definition (ie most recent at the front)
-- See Note [ic_tythings]
ic_rn_gbl_env :: GlobalRdrEnv,
-- ^ The cached 'GlobalRdrEnv', built by
-- 'InteractiveEval.setContext' and updated regularly
-- It contains everything in scope at the command line,
-- including everything in ic_tythings
ic_instances :: ([ClsInst], [FamInst]),
-- ^ All instances and family instances created during
-- this session. These are grabbed en masse after each
-- update to be sure that proper overlapping is retained.
-- That is, rather than re-check the overlapping each
-- time we update the context, we just take the results
-- from the instance code that already does that.
ic_fix_env :: FixityEnv,
-- ^ Fixities declared in let statements
ic_default :: Maybe [Type],
-- ^ The current default types, set by a 'default' declaration
#ifdef GHCI
ic_resume :: [Resume],
-- ^ The stack of breakpoint contexts
#endif
ic_monad :: Name,
-- ^ The monad that GHCi is executing in
ic_int_print :: Name,
-- ^ The function that is used for printing results
-- of expressions in ghci and -e mode.
ic_cwd :: Maybe FilePath
-- virtual CWD of the program
}
data InteractiveImport
= IIDecl (ImportDecl RdrName)
-- ^ Bring the exports of a particular module
-- (filtered by an import decl) into scope
| IIModule ModuleName
-- ^ Bring into scope the entire top-level envt of
-- of this module, including the things imported
-- into it.
-- | Constructs an empty InteractiveContext.
emptyInteractiveContext :: DynFlags -> InteractiveContext
emptyInteractiveContext dflags
= InteractiveContext {
ic_dflags = dflags,
ic_imports = [],
ic_rn_gbl_env = emptyGlobalRdrEnv,
ic_mod_index = 1,
ic_tythings = [],
ic_instances = ([],[]),
ic_fix_env = emptyNameEnv,
ic_monad = ioTyConName, -- IO monad by default
ic_int_print = printName, -- System.IO.print by default
ic_default = Nothing,
#ifdef GHCI
ic_resume = [],
#endif
ic_cwd = Nothing }
icInteractiveModule :: InteractiveContext -> Module
icInteractiveModule (InteractiveContext { ic_mod_index = index })
= mkInteractiveModule index
-- | This function returns the list of visible TyThings (useful for
-- e.g. showBindings)
icInScopeTTs :: InteractiveContext -> [TyThing]
icInScopeTTs = ic_tythings
-- | Get the PrintUnqualified function based on the flags and this InteractiveContext
icPrintUnqual :: DynFlags -> InteractiveContext -> PrintUnqualified
icPrintUnqual dflags InteractiveContext{ ic_rn_gbl_env = grenv } =
mkPrintUnqualified dflags grenv
-- | extendInteractiveContext is called with new TyThings recently defined to update the
-- InteractiveContext to include them. Ids are easily removed when shadowed,
-- but Classes and TyCons are not. Some work could be done to determine
-- whether they are entirely shadowed, but as you could still have references
-- to them (e.g. instances for classes or values of the type for TyCons), it's
-- not clear whether removing them is even the appropriate behavior.
extendInteractiveContext :: InteractiveContext
-> [Id] -> [TyCon]
-> [ClsInst] -> [FamInst]
-> Maybe [Type]
-> [PatSyn]
-> InteractiveContext
extendInteractiveContext ictxt ids tcs new_cls_insts new_fam_insts defaults new_patsyns
= ictxt { ic_mod_index = ic_mod_index ictxt + 1
-- Always bump this; even instances should create
-- a new mod_index (Trac #9426)
, ic_tythings = new_tythings ++ old_tythings
, ic_rn_gbl_env = ic_rn_gbl_env ictxt `icExtendGblRdrEnv` new_tythings
, ic_instances = ( new_cls_insts ++ old_cls_insts
, new_fam_insts ++ old_fam_insts )
, ic_default = defaults }
where
new_tythings = map AnId ids ++ map ATyCon tcs ++ map (AConLike . PatSynCon) new_patsyns
old_tythings = filterOut (shadowed_by ids) (ic_tythings ictxt)
-- Discard old instances that have been fully overrridden
-- See Note [Override identical instances in GHCi]
(cls_insts, fam_insts) = ic_instances ictxt
old_cls_insts = filterOut (\i -> any (identicalClsInstHead i) new_cls_insts) cls_insts
old_fam_insts = filterOut (\i -> any (identicalFamInstHead i) new_fam_insts) fam_insts
extendInteractiveContextWithIds :: InteractiveContext -> [Id] -> InteractiveContext
extendInteractiveContextWithIds ictxt ids
| null ids = ictxt
| otherwise = ictxt { ic_mod_index = ic_mod_index ictxt + 1
, ic_tythings = new_tythings ++ old_tythings
, ic_rn_gbl_env = ic_rn_gbl_env ictxt `icExtendGblRdrEnv` new_tythings }
where
new_tythings = map AnId ids
old_tythings = filterOut (shadowed_by ids) (ic_tythings ictxt)
shadowed_by :: [Id] -> TyThing -> Bool
shadowed_by ids = shadowed
where
shadowed id = getOccName id `elemOccSet` new_occs
new_occs = mkOccSet (map getOccName ids)
setInteractivePackage :: HscEnv -> HscEnv
-- Set the 'thisPackage' DynFlag to 'interactive'
setInteractivePackage hsc_env
= hsc_env { hsc_dflags = (hsc_dflags hsc_env) { thisPackage = interactivePackageKey } }
setInteractivePrintName :: InteractiveContext -> Name -> InteractiveContext
setInteractivePrintName ic n = ic{ic_int_print = n}
-- ToDo: should not add Ids to the gbl env here
-- | Add TyThings to the GlobalRdrEnv, earlier ones in the list shadowing
-- later ones, and shadowing existing entries in the GlobalRdrEnv.
icExtendGblRdrEnv :: GlobalRdrEnv -> [TyThing] -> GlobalRdrEnv
icExtendGblRdrEnv env tythings
= foldr add env tythings -- Foldr makes things in the front of
-- the list shadow things at the back
where
add thing env = extendGlobalRdrEnv True {- Shadowing please -} env
[tyThingAvailInfo thing]
-- One at a time, to ensure each shadows the previous ones
substInteractiveContext :: InteractiveContext -> TvSubst -> InteractiveContext
substInteractiveContext ictxt@InteractiveContext{ ic_tythings = tts } subst
| isEmptyTvSubst subst = ictxt
| otherwise = ictxt { ic_tythings = map subst_ty tts }
where
subst_ty (AnId id) = AnId $ id `setIdType` substTy subst (idType id)
subst_ty tt = tt
instance Outputable InteractiveImport where
ppr (IIModule m) = char '*' <> ppr m
ppr (IIDecl d) = ppr d
{-
************************************************************************
* *
Building a PrintUnqualified
* *
************************************************************************
Note [Printing original names]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Deciding how to print names is pretty tricky. We are given a name
P:M.T, where P is the package name, M is the defining module, and T is
the occurrence name, and we have to decide in which form to display
the name given a GlobalRdrEnv describing the current scope.
Ideally we want to display the name in the form in which it is in
scope. However, the name might not be in scope at all, and that's
where it gets tricky. Here are the cases:
1. T uniquely maps to P:M.T ---> "T" NameUnqual
2. There is an X for which X.T
uniquely maps to P:M.T ---> "X.T" NameQual X
3. There is no binding for "M.T" ---> "M.T" NameNotInScope1
4. Otherwise ---> "P:M.T" NameNotInScope2
(3) and (4) apply when the entity P:M.T is not in the GlobalRdrEnv at
all. In these cases we still want to refer to the name as "M.T", *but*
"M.T" might mean something else in the current scope (e.g. if there's
an "import X as M"), so to avoid confusion we avoid using "M.T" if
there's already a binding for it. Instead we write P:M.T.
There's one further subtlety: in case (3), what if there are two
things around, P1:M.T and P2:M.T? Then we don't want to print both of
them as M.T! However only one of the modules P1:M and P2:M can be
exposed (say P2), so we use M.T for that, and P1:M.T for the other one.
This is handled by the qual_mod component of PrintUnqualified, inside
the (ppr mod) of case (3), in Name.pprModulePrefix
Note [Printing package keys]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In the old days, original names were tied to PackageIds, which directly
corresponded to the entities that users wrote in Cabal files, and were perfectly
suitable for printing when we need to disambiguate packages. However, with
PackageKey, the situation is different. First, the key is not a human readable
at all, so we need to consult the package database to find the appropriate
PackageId to display. Second, there may be multiple copies of a library visible
with the same PackageId, in which case we need to disambiguate. For now,
we just emit the actual package key (which the user can go look up); however,
another scheme is to (recursively) say which dependencies are different.
NB: When we extend package keys to also have holes, we will have to disambiguate
those as well.
-}
-- | Creates some functions that work out the best ways to format
-- names for the user according to a set of heuristics.
mkPrintUnqualified :: DynFlags -> GlobalRdrEnv -> PrintUnqualified
mkPrintUnqualified dflags env = QueryQualify qual_name
(mkQualModule dflags)
(mkQualPackage dflags)
where
qual_name mod occ
| [] <- unqual_gres
, modulePackageKey mod `elem` [primPackageKey, basePackageKey, thPackageKey]
, not (isDerivedOccName occ)
= NameUnqual -- For names from ubiquitous packages that come with GHC, if
-- there are no entities called unqualified 'occ', then
-- print unqualified. Doing so does not cause ambiguity,
-- and it reduces the amount of qualification in error
-- messages. We can't do this for all packages, because we
-- might get errors like "Can't unify T with T". But the
-- ubiquitous packages don't contain any such gratuitous
-- name clashes.
--
-- A motivating example is 'Constraint'. It's often not in
-- scope, but printing GHC.Prim.Constraint seems overkill.
| [gre] <- unqual_gres
, right_name gre
= NameUnqual -- If there's a unique entity that's in scope
-- unqualified with 'occ' AND that entity is
-- the right one, then we can use the unqualified name
| [gre] <- qual_gres
= NameQual (get_qual_mod (gre_prov gre))
| null qual_gres
= if null (lookupGRE_RdrName (mkRdrQual (moduleName mod) occ) env)
then NameNotInScope1
else NameNotInScope2
| otherwise
= NameNotInScope1 -- Can happen if 'f' is bound twice in the module
-- Eg f = True; g = 0; f = False
where
right_name gre = nameModule_maybe (gre_name gre) == Just mod
unqual_gres = lookupGRE_RdrName (mkRdrUnqual occ) env
qual_gres = filter right_name (lookupGlobalRdrEnv env occ)
get_qual_mod LocalDef = moduleName mod
get_qual_mod (Imported is) = ASSERT( not (null is) ) is_as (is_decl (head is))
-- we can mention a module P:M without the P: qualifier iff
-- "import M" would resolve unambiguously to P:M. (if P is the
-- current package we can just assume it is unqualified).
-- | Creates a function for formatting modules based on two heuristics:
-- (1) if the module is the current module, don't qualify, and (2) if there
-- is only one exposed package which exports this module, don't qualify.
mkQualModule :: DynFlags -> QueryQualifyModule
mkQualModule dflags mod
| modulePackageKey mod == thisPackage dflags = False
| [(_, pkgconfig)] <- lookup,
packageConfigId pkgconfig == modulePackageKey mod
-- this says: we are given a module P:M, is there just one exposed package
-- that exposes a module M, and is it package P?
= False
| otherwise = True
where lookup = lookupModuleInAllPackages dflags (moduleName mod)
-- | Creates a function for formatting packages based on two heuristics:
-- (1) don't qualify if the package in question is "main", and (2) only qualify
-- with a package key if the package ID would be ambiguous.
mkQualPackage :: DynFlags -> QueryQualifyPackage
mkQualPackage dflags pkg_key
| pkg_key == mainPackageKey || pkg_key == interactivePackageKey
-- Skip the lookup if it's main, since it won't be in the package
-- database!
= False
| searchPackageId dflags pkgid `lengthIs` 1
-- this says: we are given a package pkg-0.1@MMM, are there only one
-- exposed packages whose package ID is pkg-0.1?
= False
| otherwise
= True
where pkg = fromMaybe (pprPanic "qual_pkg" (ftext (packageKeyFS pkg_key)))
(lookupPackage dflags pkg_key)
pkgid = sourcePackageId pkg
-- | A function which only qualifies package names if necessary; but
-- qualifies all other identifiers.
pkgQual :: DynFlags -> PrintUnqualified
pkgQual dflags = alwaysQualify {
queryQualifyPackage = mkQualPackage dflags
}
{-
************************************************************************
* *
Implicit TyThings
* *
************************************************************************
Note [Implicit TyThings]
~~~~~~~~~~~~~~~~~~~~~~~~
DEFINITION: An "implicit" TyThing is one that does not have its own
IfaceDecl in an interface file. Instead, its binding in the type
environment is created as part of typechecking the IfaceDecl for
some other thing.
Examples:
* All DataCons are implicit, because they are generated from the
IfaceDecl for the data/newtype. Ditto class methods.
* Record selectors are *not* implicit, because they get their own
free-standing IfaceDecl.
* Associated data/type families are implicit because they are
included in the IfaceDecl of the parent class. (NB: the
IfaceClass decl happens to use IfaceDecl recursively for the
associated types, but that's irrelevant here.)
* Dictionary function Ids are not implicit.
* Axioms for newtypes are implicit (same as above), but axioms
for data/type family instances are *not* implicit (like DFunIds).
-}
-- | Determine the 'TyThing's brought into scope by another 'TyThing'
-- /other/ than itself. For example, Id's don't have any implicit TyThings
-- as they just bring themselves into scope, but classes bring their
-- dictionary datatype, type constructor and some selector functions into
-- scope, just for a start!
-- N.B. the set of TyThings returned here *must* match the set of
-- names returned by LoadIface.ifaceDeclImplicitBndrs, in the sense that
-- TyThing.getOccName should define a bijection between the two lists.
-- This invariant is used in LoadIface.loadDecl (see note [Tricky iface loop])
-- The order of the list does not matter.
implicitTyThings :: TyThing -> [TyThing]
implicitTyThings (AnId _) = []
implicitTyThings (ACoAxiom _cc) = []
implicitTyThings (ATyCon tc) = implicitTyConThings tc
implicitTyThings (AConLike cl) = implicitConLikeThings cl
implicitConLikeThings :: ConLike -> [TyThing]
implicitConLikeThings (RealDataCon dc)
= map AnId (dataConImplicitIds dc)
-- For data cons add the worker and (possibly) wrapper
implicitConLikeThings (PatSynCon {})
= [] -- Pattern synonyms have no implicit Ids; the wrapper and matcher
-- are not "implicit"; they are simply new top-level bindings,
-- and they have their own declaration in an interface file
implicitClassThings :: Class -> [TyThing]
implicitClassThings cl
= -- Does not include default methods, because those Ids may have
-- their own pragmas, unfoldings etc, not derived from the Class object
-- associated types
-- No extras_plus (recursive call) for the classATs, because they
-- are only the family decls; they have no implicit things
map ATyCon (classATs cl) ++
-- superclass and operation selectors
map AnId (classAllSelIds cl)
implicitTyConThings :: TyCon -> [TyThing]
implicitTyConThings tc
= class_stuff ++
-- fields (names of selectors)
-- (possibly) implicit newtype coercion
implicitCoTyCon tc ++
-- for each data constructor in order,
-- the contructor, worker, and (possibly) wrapper
concatMap (extras_plus . AConLike . RealDataCon) (tyConDataCons tc)
-- NB. record selectors are *not* implicit, they have fully-fledged
-- bindings that pass through the compilation pipeline as normal.
where
class_stuff = case tyConClass_maybe tc of
Nothing -> []
Just cl -> implicitClassThings cl
-- add a thing and recursive call
extras_plus :: TyThing -> [TyThing]
extras_plus thing = thing : implicitTyThings thing
-- For newtypes and closed type families (only) add the implicit coercion tycon
implicitCoTyCon :: TyCon -> [TyThing]
implicitCoTyCon tc
| Just co <- newTyConCo_maybe tc = [ACoAxiom $ toBranchedAxiom co]
| Just co <- isClosedSynFamilyTyConWithAxiom_maybe tc
= [ACoAxiom co]
| otherwise = []
-- | Returns @True@ if there should be no interface-file declaration
-- for this thing on its own: either it is built-in, or it is part
-- of some other declaration, or it is generated implicitly by some
-- other declaration.
isImplicitTyThing :: TyThing -> Bool
isImplicitTyThing (AConLike cl) = case cl of
RealDataCon {} -> True
PatSynCon {} -> False
isImplicitTyThing (AnId id) = isImplicitId id
isImplicitTyThing (ATyCon tc) = isImplicitTyCon tc
isImplicitTyThing (ACoAxiom ax) = isImplicitCoAxiom ax
-- | tyThingParent_maybe x returns (Just p)
-- when pprTyThingInContext sould print a declaration for p
-- (albeit with some "..." in it) when asked to show x
-- It returns the *immediate* parent. So a datacon returns its tycon
-- but the tycon could be the associated type of a class, so it in turn
-- might have a parent.
tyThingParent_maybe :: TyThing -> Maybe TyThing
tyThingParent_maybe (AConLike cl) = case cl of
RealDataCon dc -> Just (ATyCon (dataConTyCon dc))
PatSynCon{} -> Nothing
tyThingParent_maybe (ATyCon tc) = case tyConAssoc_maybe tc of
Just cls -> Just (ATyCon (classTyCon cls))
Nothing -> Nothing
tyThingParent_maybe (AnId id) = case idDetails id of
RecSelId { sel_tycon = tc } -> Just (ATyCon tc)
ClassOpId cls -> Just (ATyCon (classTyCon cls))
_other -> Nothing
tyThingParent_maybe _other = Nothing
tyThingsTyVars :: [TyThing] -> TyVarSet
tyThingsTyVars tts =
unionVarSets $ map ttToVarSet tts
where
ttToVarSet (AnId id) = tyVarsOfType $ idType id
ttToVarSet (AConLike cl) = case cl of
RealDataCon dc -> tyVarsOfType $ dataConRepType dc
PatSynCon{} -> emptyVarSet
ttToVarSet (ATyCon tc)
= case tyConClass_maybe tc of
Just cls -> (mkVarSet . fst . classTvsFds) cls
Nothing -> tyVarsOfType $ tyConKind tc
ttToVarSet _ = emptyVarSet
-- | The Names that a TyThing should bring into scope. Used to build
-- the GlobalRdrEnv for the InteractiveContext.
tyThingAvailInfo :: TyThing -> AvailInfo
tyThingAvailInfo (ATyCon t)
= case tyConClass_maybe t of
Just c -> AvailTC n (n : map getName (classMethods c)
++ map getName (classATs c))
where n = getName c
Nothing -> AvailTC n (n : map getName dcs ++
concatMap dataConFieldLabels dcs)
where n = getName t
dcs = tyConDataCons t
tyThingAvailInfo t
= Avail (getName t)
{-
************************************************************************
* *
TypeEnv
* *
************************************************************************
-}
-- | A map from 'Name's to 'TyThing's, constructed by typechecking
-- local declarations or interface files
type TypeEnv = NameEnv TyThing
emptyTypeEnv :: TypeEnv
typeEnvElts :: TypeEnv -> [TyThing]
typeEnvTyCons :: TypeEnv -> [TyCon]
typeEnvCoAxioms :: TypeEnv -> [CoAxiom Branched]
typeEnvIds :: TypeEnv -> [Id]
typeEnvPatSyns :: TypeEnv -> [PatSyn]
typeEnvDataCons :: TypeEnv -> [DataCon]
typeEnvClasses :: TypeEnv -> [Class]
lookupTypeEnv :: TypeEnv -> Name -> Maybe TyThing
emptyTypeEnv = emptyNameEnv
typeEnvElts env = nameEnvElts env
typeEnvTyCons env = [tc | ATyCon tc <- typeEnvElts env]
typeEnvCoAxioms env = [ax | ACoAxiom ax <- typeEnvElts env]
typeEnvIds env = [id | AnId id <- typeEnvElts env]
typeEnvPatSyns env = [ps | AConLike (PatSynCon ps) <- typeEnvElts env]
typeEnvDataCons env = [dc | AConLike (RealDataCon dc) <- typeEnvElts env]
typeEnvClasses env = [cl | tc <- typeEnvTyCons env,
Just cl <- [tyConClass_maybe tc]]
mkTypeEnv :: [TyThing] -> TypeEnv
mkTypeEnv things = extendTypeEnvList emptyTypeEnv things
mkTypeEnvWithImplicits :: [TyThing] -> TypeEnv
mkTypeEnvWithImplicits things =
mkTypeEnv things
`plusNameEnv`
mkTypeEnv (concatMap implicitTyThings things)
typeEnvFromEntities :: [Id] -> [TyCon] -> [FamInst] -> TypeEnv
typeEnvFromEntities ids tcs famInsts =
mkTypeEnv ( map AnId ids
++ map ATyCon all_tcs
++ concatMap implicitTyConThings all_tcs
++ map (ACoAxiom . toBranchedAxiom . famInstAxiom) famInsts
)
where
all_tcs = tcs ++ famInstsRepTyCons famInsts
lookupTypeEnv = lookupNameEnv
-- Extend the type environment
extendTypeEnv :: TypeEnv -> TyThing -> TypeEnv
extendTypeEnv env thing = extendNameEnv env (getName thing) thing
extendTypeEnvList :: TypeEnv -> [TyThing] -> TypeEnv
extendTypeEnvList env things = foldl extendTypeEnv env things
extendTypeEnvWithIds :: TypeEnv -> [Id] -> TypeEnv
extendTypeEnvWithIds env ids
= extendNameEnvList env [(getName id, AnId id) | id <- ids]
-- | Find the 'TyThing' for the given 'Name' by using all the resources
-- at our disposal: the compiled modules in the 'HomePackageTable' and the
-- compiled modules in other packages that live in 'PackageTypeEnv'. Note
-- that this does NOT look up the 'TyThing' in the module being compiled: you
-- have to do that yourself, if desired
lookupType :: DynFlags
-> HomePackageTable
-> PackageTypeEnv
-> Name
-> Maybe TyThing
lookupType dflags hpt pte name
| isOneShot (ghcMode dflags) -- in one-shot, we don't use the HPT
= lookupNameEnv pte name
| otherwise
= case lookupHptByModule hpt mod of
Just hm -> lookupNameEnv (md_types (hm_details hm)) name
Nothing -> lookupNameEnv pte name
where
mod = ASSERT2( isExternalName name, ppr name ) nameModule name
-- | As 'lookupType', but with a marginally easier-to-use interface
-- if you have a 'HscEnv'
lookupTypeHscEnv :: HscEnv -> Name -> IO (Maybe TyThing)
lookupTypeHscEnv hsc_env name = do
eps <- readIORef (hsc_EPS hsc_env)
return $! lookupType dflags hpt (eps_PTE eps) name
where
dflags = hsc_dflags hsc_env
hpt = hsc_HPT hsc_env
-- | Get the 'TyCon' from a 'TyThing' if it is a type constructor thing. Panics otherwise
tyThingTyCon :: TyThing -> TyCon
tyThingTyCon (ATyCon tc) = tc
tyThingTyCon other = pprPanic "tyThingTyCon" (pprTyThing other)
-- | Get the 'CoAxiom' from a 'TyThing' if it is a coercion axiom thing. Panics otherwise
tyThingCoAxiom :: TyThing -> CoAxiom Branched
tyThingCoAxiom (ACoAxiom ax) = ax
tyThingCoAxiom other = pprPanic "tyThingCoAxiom" (pprTyThing other)
-- | Get the 'DataCon' from a 'TyThing' if it is a data constructor thing. Panics otherwise
tyThingDataCon :: TyThing -> DataCon
tyThingDataCon (AConLike (RealDataCon dc)) = dc
tyThingDataCon other = pprPanic "tyThingDataCon" (pprTyThing other)
-- | Get the 'Id' from a 'TyThing' if it is a id *or* data constructor thing. Panics otherwise
tyThingId :: TyThing -> Id
tyThingId (AnId id) = id
tyThingId (AConLike (RealDataCon dc)) = dataConWrapId dc
tyThingId other = pprPanic "tyThingId" (pprTyThing other)
{-
************************************************************************
* *
\subsection{MonadThings and friends}
* *
************************************************************************
-}
-- | Class that abstracts out the common ability of the monads in GHC
-- to lookup a 'TyThing' in the monadic environment by 'Name'. Provides
-- a number of related convenience functions for accessing particular
-- kinds of 'TyThing'
class Monad m => MonadThings m where
lookupThing :: Name -> m TyThing
lookupId :: Name -> m Id
lookupId = liftM tyThingId . lookupThing
lookupDataCon :: Name -> m DataCon
lookupDataCon = liftM tyThingDataCon . lookupThing
lookupTyCon :: Name -> m TyCon
lookupTyCon = liftM tyThingTyCon . lookupThing
{-
************************************************************************
* *
\subsection{Auxiliary types}
* *
************************************************************************
These types are defined here because they are mentioned in ModDetails,
but they are mostly elaborated elsewhere
-}
------------------ Warnings -------------------------
-- | Warning information for a module
data Warnings
= NoWarnings -- ^ Nothing deprecated
| WarnAll WarningTxt -- ^ Whole module deprecated
| WarnSome [(OccName,WarningTxt)] -- ^ Some specific things deprecated
-- Only an OccName is needed because
-- (1) a deprecation always applies to a binding
-- defined in the module in which the deprecation appears.
-- (2) deprecations are only reported outside the defining module.
-- this is important because, otherwise, if we saw something like
--
-- {-# DEPRECATED f "" #-}
-- f = ...
-- h = f
-- g = let f = undefined in f
--
-- we'd need more information than an OccName to know to say something
-- about the use of f in h but not the use of the locally bound f in g
--
-- however, because we only report about deprecations from the outside,
-- and a module can only export one value called f,
-- an OccName suffices.
--
-- this is in contrast with fixity declarations, where we need to map
-- a Name to its fixity declaration.
deriving( Eq )
instance Binary Warnings where
put_ bh NoWarnings = putByte bh 0
put_ bh (WarnAll t) = do
putByte bh 1
put_ bh t
put_ bh (WarnSome ts) = do
putByte bh 2
put_ bh ts
get bh = do
h <- getByte bh
case h of
0 -> return NoWarnings
1 -> do aa <- get bh
return (WarnAll aa)
_ -> do aa <- get bh
return (WarnSome aa)
-- | Constructs the cache for the 'mi_warn_fn' field of a 'ModIface'
mkIfaceWarnCache :: Warnings -> Name -> Maybe WarningTxt
mkIfaceWarnCache NoWarnings = \_ -> Nothing
mkIfaceWarnCache (WarnAll t) = \_ -> Just t
mkIfaceWarnCache (WarnSome pairs) = lookupOccEnv (mkOccEnv pairs) . nameOccName
emptyIfaceWarnCache :: Name -> Maybe WarningTxt
emptyIfaceWarnCache _ = Nothing
plusWarns :: Warnings -> Warnings -> Warnings
plusWarns d NoWarnings = d
plusWarns NoWarnings d = d
plusWarns _ (WarnAll t) = WarnAll t
plusWarns (WarnAll t) _ = WarnAll t
plusWarns (WarnSome v1) (WarnSome v2) = WarnSome (v1 ++ v2)
-- | Creates cached lookup for the 'mi_fix_fn' field of 'ModIface'
mkIfaceFixCache :: [(OccName, Fixity)] -> OccName -> Fixity
mkIfaceFixCache pairs
= \n -> lookupOccEnv env n `orElse` defaultFixity
where
env = mkOccEnv pairs
emptyIfaceFixCache :: OccName -> Fixity
emptyIfaceFixCache _ = defaultFixity
-- | Fixity environment mapping names to their fixities
type FixityEnv = NameEnv FixItem
-- | Fixity information for an 'Name'. We keep the OccName in the range
-- so that we can generate an interface from it
data FixItem = FixItem OccName Fixity
instance Outputable FixItem where
ppr (FixItem occ fix) = ppr fix <+> ppr occ
emptyFixityEnv :: FixityEnv
emptyFixityEnv = emptyNameEnv
lookupFixity :: FixityEnv -> Name -> Fixity
lookupFixity env n = case lookupNameEnv env n of
Just (FixItem _ fix) -> fix
Nothing -> defaultFixity
{-
************************************************************************
* *
\subsection{WhatsImported}
* *
************************************************************************
-}
-- | Records whether a module has orphans. An \"orphan\" is one of:
--
-- * An instance declaration in a module other than the definition
-- module for one of the type constructors or classes in the instance head
--
-- * A transformation rule in a module other than the one defining
-- the function in the head of the rule
--
-- * A vectorisation pragma
type WhetherHasOrphans = Bool
-- | Does this module define family instances?
type WhetherHasFamInst = Bool
-- | Did this module originate from a *-boot file?
type IsBootInterface = Bool
-- | Dependency information about ALL modules and packages below this one
-- in the import hierarchy.
--
-- Invariant: the dependencies of a module @M@ never includes @M@.
--
-- Invariant: none of the lists contain duplicates.
--
-- NB: While this contains information about all modules and packages below
-- this one in the the import *hierarchy*, this may not accurately reflect
-- the full runtime dependencies of the module. This is because this module may
-- have imported a boot module, in which case we'll only have recorded the
-- dependencies from the hs-boot file, not the actual hs file. (This is
-- unavoidable: usually, the actual hs file will have been compiled *after*
-- we wrote this interface file.) See #936, and also @getLinkDeps@ in
-- @compiler/ghci/Linker.hs@ for code which cares about this distinction.
data Dependencies
= Deps { dep_mods :: [(ModuleName, IsBootInterface)]
-- ^ All home-package modules transitively below this one
-- I.e. modules that this one imports, or that are in the
-- dep_mods of those directly-imported modules
, dep_pkgs :: [(PackageKey, Bool)]
-- ^ All packages transitively below this module
-- I.e. packages to which this module's direct imports belong,
-- or that are in the dep_pkgs of those modules
-- The bool indicates if the package is required to be
-- trusted when the module is imported as a safe import
-- (Safe Haskell). See Note [RnNames . Tracking Trust Transitively]
, dep_orphs :: [Module]
-- ^ Transitive closure of orphan modules (whether
-- home or external pkg).
--
-- (Possible optimization: don't include family
-- instance orphans as they are anyway included in
-- 'dep_finsts'. But then be careful about code
-- which relies on dep_orphs having the complete list!)
, dep_finsts :: [Module]
-- ^ Modules that contain family instances (whether the
-- instances are from the home or an external package)
}
deriving( Eq )
-- Equality used only for old/new comparison in MkIface.addFingerprints
-- See 'TcRnTypes.ImportAvails' for details on dependencies.
instance Binary Dependencies where
put_ bh deps = do put_ bh (dep_mods deps)
put_ bh (dep_pkgs deps)
put_ bh (dep_orphs deps)
put_ bh (dep_finsts deps)
get bh = do ms <- get bh
ps <- get bh
os <- get bh
fis <- get bh
return (Deps { dep_mods = ms, dep_pkgs = ps, dep_orphs = os,
dep_finsts = fis })
noDependencies :: Dependencies
noDependencies = Deps [] [] [] []
-- | Records modules for which changes may force recompilation of this module
-- See wiki: http://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/RecompilationAvoidance
--
-- This differs from Dependencies. A module X may be in the dep_mods of this
-- module (via an import chain) but if we don't use anything from X it won't
-- appear in our Usage
data Usage
-- | Module from another package
= UsagePackageModule {
usg_mod :: Module,
-- ^ External package module depended on
usg_mod_hash :: Fingerprint,
-- ^ Cached module fingerprint
usg_safe :: IsSafeImport
-- ^ Was this module imported as a safe import
}
-- | Module from the current package
| UsageHomeModule {
usg_mod_name :: ModuleName,
-- ^ Name of the module
usg_mod_hash :: Fingerprint,
-- ^ Cached module fingerprint
usg_entities :: [(OccName,Fingerprint)],
-- ^ Entities we depend on, sorted by occurrence name and fingerprinted.
-- NB: usages are for parent names only, e.g. type constructors
-- but not the associated data constructors.
usg_exports :: Maybe Fingerprint,
-- ^ Fingerprint for the export list of this module,
-- if we directly imported it (and hence we depend on its export list)
usg_safe :: IsSafeImport
-- ^ Was this module imported as a safe import
} -- ^ Module from the current package
-- | A file upon which the module depends, e.g. a CPP #include, or using TH's
-- 'addDependentFile'
| UsageFile {
usg_file_path :: FilePath,
-- ^ External file dependency. From a CPP #include or TH
-- addDependentFile. Should be absolute.
usg_file_hash :: Fingerprint
-- ^ 'Fingerprint' of the file contents.
-- Note: We don't consider things like modification timestamps
-- here, because there's no reason to recompile if the actual
-- contents don't change. This previously lead to odd
-- recompilation behaviors; see #8114
}
deriving( Eq )
-- The export list field is (Just v) if we depend on the export list:
-- i.e. we imported the module directly, whether or not we
-- enumerated the things we imported, or just imported
-- everything
-- We need to recompile if M's exports change, because
-- if the import was import M, we might now have a name clash
-- in the importing module.
-- if the import was import M(x) M might no longer export x
-- The only way we don't depend on the export list is if we have
-- import M()
-- And of course, for modules that aren't imported directly we don't
-- depend on their export lists
instance Binary Usage where
put_ bh usg@UsagePackageModule{} = do
putByte bh 0
put_ bh (usg_mod usg)
put_ bh (usg_mod_hash usg)
put_ bh (usg_safe usg)
put_ bh usg@UsageHomeModule{} = do
putByte bh 1
put_ bh (usg_mod_name usg)
put_ bh (usg_mod_hash usg)
put_ bh (usg_exports usg)
put_ bh (usg_entities usg)
put_ bh (usg_safe usg)
put_ bh usg@UsageFile{} = do
putByte bh 2
put_ bh (usg_file_path usg)
put_ bh (usg_file_hash usg)
get bh = do
h <- getByte bh
case h of
0 -> do
nm <- get bh
mod <- get bh
safe <- get bh
return UsagePackageModule { usg_mod = nm, usg_mod_hash = mod, usg_safe = safe }
1 -> do
nm <- get bh
mod <- get bh
exps <- get bh
ents <- get bh
safe <- get bh
return UsageHomeModule { usg_mod_name = nm, usg_mod_hash = mod,
usg_exports = exps, usg_entities = ents, usg_safe = safe }
2 -> do
fp <- get bh
hash <- get bh
return UsageFile { usg_file_path = fp, usg_file_hash = hash }
i -> error ("Binary.get(Usage): " ++ show i)
{-
************************************************************************
* *
The External Package State
* *
************************************************************************
-}
type PackageTypeEnv = TypeEnv
type PackageRuleBase = RuleBase
type PackageInstEnv = InstEnv
type PackageFamInstEnv = FamInstEnv
type PackageVectInfo = VectInfo
type PackageAnnEnv = AnnEnv
-- | Information about other packages that we have slurped in by reading
-- their interface files
data ExternalPackageState
= EPS {
eps_is_boot :: !(ModuleNameEnv (ModuleName, IsBootInterface)),
-- ^ In OneShot mode (only), home-package modules
-- accumulate in the external package state, and are
-- sucked in lazily. For these home-pkg modules
-- (only) we need to record which are boot modules.
-- We set this field after loading all the
-- explicitly-imported interfaces, but before doing
-- anything else
--
-- The 'ModuleName' part is not necessary, but it's useful for
-- debug prints, and it's convenient because this field comes
-- direct from 'TcRnTypes.imp_dep_mods'
eps_PIT :: !PackageIfaceTable,
-- ^ The 'ModIface's for modules in external packages
-- whose interfaces we have opened.
-- The declarations in these interface files are held in the
-- 'eps_decls', 'eps_inst_env', 'eps_fam_inst_env' and 'eps_rules'
-- fields of this record, not in the 'mi_decls' fields of the
-- interface we have sucked in.
--
-- What /is/ in the PIT is:
--
-- * The Module
--
-- * Fingerprint info
--
-- * Its exports
--
-- * Fixities
--
-- * Deprecations and warnings
eps_PTE :: !PackageTypeEnv,
-- ^ Result of typechecking all the external package
-- interface files we have sucked in. The domain of
-- the mapping is external-package modules
eps_inst_env :: !PackageInstEnv, -- ^ The total 'InstEnv' accumulated
-- from all the external-package modules
eps_fam_inst_env :: !PackageFamInstEnv,-- ^ The total 'FamInstEnv' accumulated
-- from all the external-package modules
eps_rule_base :: !PackageRuleBase, -- ^ The total 'RuleEnv' accumulated
-- from all the external-package modules
eps_vect_info :: !PackageVectInfo, -- ^ The total 'VectInfo' accumulated
-- from all the external-package modules
eps_ann_env :: !PackageAnnEnv, -- ^ The total 'AnnEnv' accumulated
-- from all the external-package modules
eps_mod_fam_inst_env :: !(ModuleEnv FamInstEnv), -- ^ The family instances accumulated from external
-- packages, keyed off the module that declared them
eps_stats :: !EpsStats -- ^ Stastics about what was loaded from external packages
}
-- | Accumulated statistics about what we are putting into the 'ExternalPackageState'.
-- \"In\" means stuff that is just /read/ from interface files,
-- \"Out\" means actually sucked in and type-checked
data EpsStats = EpsStats { n_ifaces_in
, n_decls_in, n_decls_out
, n_rules_in, n_rules_out
, n_insts_in, n_insts_out :: !Int }
addEpsInStats :: EpsStats -> Int -> Int -> Int -> EpsStats
-- ^ Add stats for one newly-read interface
addEpsInStats stats n_decls n_insts n_rules
= stats { n_ifaces_in = n_ifaces_in stats + 1
, n_decls_in = n_decls_in stats + n_decls
, n_insts_in = n_insts_in stats + n_insts
, n_rules_in = n_rules_in stats + n_rules }
{-
Names in a NameCache are always stored as a Global, and have the SrcLoc
of their binding locations.
Actually that's not quite right. When we first encounter the original
name, we might not be at its binding site (e.g. we are reading an
interface file); so we give it 'noSrcLoc' then. Later, when we find
its binding site, we fix it up.
-}
-- | The NameCache makes sure that there is just one Unique assigned for
-- each original name; i.e. (module-name, occ-name) pair and provides
-- something of a lookup mechanism for those names.
data NameCache
= NameCache { nsUniqs :: !UniqSupply,
-- ^ Supply of uniques
nsNames :: !OrigNameCache
-- ^ Ensures that one original name gets one unique
}
-- | Per-module cache of original 'OccName's given 'Name's
type OrigNameCache = ModuleEnv (OccEnv Name)
mkSOName :: Platform -> FilePath -> FilePath
mkSOName platform root
= case platformOS platform of
OSDarwin -> ("lib" ++ root) <.> "dylib"
OSMinGW32 -> root <.> "dll"
_ -> ("lib" ++ root) <.> "so"
mkHsSOName :: Platform -> FilePath -> FilePath
mkHsSOName platform root = ("lib" ++ root) <.> soExt platform
soExt :: Platform -> FilePath
soExt platform
= case platformOS platform of
OSDarwin -> "dylib"
OSMinGW32 -> "dll"
_ -> "so"
{-
************************************************************************
* *
The module graph and ModSummary type
A ModSummary is a node in the compilation manager's
dependency graph, and it's also passed to hscMain
* *
************************************************************************
-}
-- | A ModuleGraph contains all the nodes from the home package (only).
-- There will be a node for each source module, plus a node for each hi-boot
-- module.
--
-- The graph is not necessarily stored in topologically-sorted order. Use
-- 'GHC.topSortModuleGraph' and 'Digraph.flattenSCC' to achieve this.
type ModuleGraph = [ModSummary]
emptyMG :: ModuleGraph
emptyMG = []
-- | A single node in a 'ModuleGraph'. The nodes of the module graph
-- are one of:
--
-- * A regular Haskell source module
-- * A hi-boot source module
--
data ModSummary
= ModSummary {
ms_mod :: Module,
-- ^ Identity of the module
ms_hsc_src :: HscSource,
-- ^ The module source either plain Haskell or hs-boot
ms_location :: ModLocation,
-- ^ Location of the various files belonging to the module
ms_hs_date :: UTCTime,
-- ^ Timestamp of source file
ms_obj_date :: Maybe UTCTime,
-- ^ Timestamp of object, if we have one
ms_iface_date :: Maybe UTCTime,
-- ^ Timestamp of hi file, if we *only* are typechecking (it is
-- 'Nothing' otherwise.
-- See Note [Recompilation checking when typechecking only] and #9243
ms_srcimps :: [Located (ImportDecl RdrName)],
-- ^ Source imports of the module
ms_textual_imps :: [Located (ImportDecl RdrName)],
-- ^ Non-source imports of the module from the module *text*
ms_hspp_file :: FilePath,
-- ^ Filename of preprocessed source file
ms_hspp_opts :: DynFlags,
-- ^ Cached flags from @OPTIONS@, @INCLUDE@ and @LANGUAGE@
-- pragmas in the modules source code
ms_hspp_buf :: Maybe StringBuffer
-- ^ The actual preprocessed source, if we have it
}
ms_mod_name :: ModSummary -> ModuleName
ms_mod_name = moduleName . ms_mod
ms_imps :: ModSummary -> [Located (ImportDecl RdrName)]
ms_imps ms =
ms_textual_imps ms ++
map mk_additional_import (dynFlagDependencies (ms_hspp_opts ms))
where
-- This is a not-entirely-satisfactory means of creating an import
-- that corresponds to an import that did not occur in the program
-- text, such as those induced by the use of plugins (the -plgFoo
-- flag)
mk_additional_import mod_nm = noLoc $ ImportDecl {
ideclSourceSrc = Nothing,
ideclName = noLoc mod_nm,
ideclPkgQual = Nothing,
ideclSource = False,
ideclImplicit = True, -- Maybe implicit because not "in the program text"
ideclQualified = False,
ideclAs = Nothing,
ideclHiding = Nothing,
ideclSafe = False
}
-- The ModLocation contains both the original source filename and the
-- filename of the cleaned-up source file after all preprocessing has been
-- done. The point is that the summariser will have to cpp/unlit/whatever
-- all files anyway, and there's no point in doing this twice -- just
-- park the result in a temp file, put the name of it in the location,
-- and let @compile@ read from that file on the way back up.
-- The ModLocation is stable over successive up-sweeps in GHCi, wheres
-- the ms_hs_date and imports can, of course, change
msHsFilePath, msHiFilePath, msObjFilePath :: ModSummary -> FilePath
msHsFilePath ms = expectJust "msHsFilePath" (ml_hs_file (ms_location ms))
msHiFilePath ms = ml_hi_file (ms_location ms)
msObjFilePath ms = ml_obj_file (ms_location ms)
-- | Did this 'ModSummary' originate from a hs-boot file?
isBootSummary :: ModSummary -> Bool
isBootSummary ms = ms_hsc_src ms == HsBootFile
instance Outputable ModSummary where
ppr ms
= sep [text "ModSummary {",
nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)),
text "ms_mod =" <+> ppr (ms_mod ms)
<> text (hscSourceString (ms_hsc_src ms)) <> comma,
text "ms_textual_imps =" <+> ppr (ms_textual_imps ms),
text "ms_srcimps =" <+> ppr (ms_srcimps ms)]),
char '}'
]
showModMsg :: DynFlags -> HscTarget -> Bool -> ModSummary -> String
showModMsg dflags target recomp mod_summary
= showSDoc dflags $
hsep [text (mod_str ++ replicate (max 0 (16 - length mod_str)) ' '),
char '(', text (normalise $ msHsFilePath mod_summary) <> comma,
case target of
HscInterpreted | recomp
-> text "interpreted"
HscNothing -> text "nothing"
_ | HsigFile == ms_hsc_src mod_summary -> text "nothing"
| otherwise -> text (normalise $ msObjFilePath mod_summary),
char ')']
where
mod = moduleName (ms_mod mod_summary)
mod_str = showPpr dflags mod
++ hscSourceString' dflags mod (ms_hsc_src mod_summary)
-- | Variant of hscSourceString which prints more information for signatures.
-- This can't live in DriverPhases because this would cause a module loop.
hscSourceString' :: DynFlags -> ModuleName -> HscSource -> String
hscSourceString' _ _ HsSrcFile = ""
hscSourceString' _ _ HsBootFile = "[boot]"
hscSourceString' dflags mod HsigFile =
"[" ++ (maybe "abstract sig"
(("sig of "++).showPpr dflags)
(getSigOf dflags mod)) ++ "]"
-- NB: -sig-of could be missing if we're just typechecking
{-
************************************************************************
* *
\subsection{Recmpilation}
* *
************************************************************************
-}
-- | Indicates whether a given module's source has been modified since it
-- was last compiled.
data SourceModified
= SourceModified
-- ^ the source has been modified
| SourceUnmodified
-- ^ the source has not been modified. Compilation may or may
-- not be necessary, depending on whether any dependencies have
-- changed since we last compiled.
| SourceUnmodifiedAndStable
-- ^ the source has not been modified, and furthermore all of
-- its (transitive) dependencies are up to date; it definitely
-- does not need to be recompiled. This is important for two
-- reasons: (a) we can omit the version check in checkOldIface,
-- and (b) if the module used TH splices we don't need to force
-- recompilation.
{-
************************************************************************
* *
\subsection{Hpc Support}
* *
************************************************************************
-}
-- | Information about a modules use of Haskell Program Coverage
data HpcInfo
= HpcInfo
{ hpcInfoTickCount :: Int
, hpcInfoHash :: Int
}
| NoHpcInfo
{ hpcUsed :: AnyHpcUsage -- ^ Is hpc used anywhere on the module \*tree\*?
}
-- | This is used to signal if one of my imports used HPC instrumentation
-- even if there is no module-local HPC usage
type AnyHpcUsage = Bool
emptyHpcInfo :: AnyHpcUsage -> HpcInfo
emptyHpcInfo = NoHpcInfo
-- | Find out if HPC is used by this module or any of the modules
-- it depends upon
isHpcUsed :: HpcInfo -> AnyHpcUsage
isHpcUsed (HpcInfo {}) = True
isHpcUsed (NoHpcInfo { hpcUsed = used }) = used
{-
************************************************************************
* *
\subsection{Vectorisation Support}
* *
************************************************************************
The following information is generated and consumed by the vectorisation
subsystem. It communicates the vectorisation status of declarations from one
module to another.
Why do we need both f and f_v in the ModGuts/ModDetails/EPS version VectInfo
below? We need to know `f' when converting to IfaceVectInfo. However, during
vectorisation, we need to know `f_v', whose `Var' we cannot lookup based
on just the OccName easily in a Core pass.
-}
-- |Vectorisation information for 'ModGuts', 'ModDetails' and 'ExternalPackageState'; see also
-- documentation at 'Vectorise.Env.GlobalEnv'.
--
-- NB: The following tables may also include 'Var's, 'TyCon's and 'DataCon's from imported modules,
-- which have been subsequently vectorised in the current module.
--
data VectInfo
= VectInfo
{ vectInfoVar :: VarEnv (Var , Var ) -- ^ @(f, f_v)@ keyed on @f@
, vectInfoTyCon :: NameEnv (TyCon , TyCon) -- ^ @(T, T_v)@ keyed on @T@
, vectInfoDataCon :: NameEnv (DataCon, DataCon) -- ^ @(C, C_v)@ keyed on @C@
, vectInfoParallelVars :: VarSet -- ^ set of parallel variables
, vectInfoParallelTyCons :: NameSet -- ^ set of parallel type constructors
}
-- |Vectorisation information for 'ModIface'; i.e, the vectorisation information propagated
-- across module boundaries.
--
-- NB: The field 'ifaceVectInfoVar' explicitly contains the workers of data constructors as well as
-- class selectors — i.e., their mappings are /not/ implicitly generated from the data types.
-- Moreover, whether the worker of a data constructor is in 'ifaceVectInfoVar' determines
-- whether that data constructor was vectorised (or is part of an abstractly vectorised type
-- constructor).
--
data IfaceVectInfo
= IfaceVectInfo
{ ifaceVectInfoVar :: [Name] -- ^ All variables in here have a vectorised variant
, ifaceVectInfoTyCon :: [Name] -- ^ All 'TyCon's in here have a vectorised variant;
-- the name of the vectorised variant and those of its
-- data constructors are determined by
-- 'OccName.mkVectTyConOcc' and
-- 'OccName.mkVectDataConOcc'; the names of the
-- isomorphisms are determined by 'OccName.mkVectIsoOcc'
, ifaceVectInfoTyConReuse :: [Name] -- ^ The vectorised form of all the 'TyCon's in here
-- coincides with the unconverted form; the name of the
-- isomorphisms is determined by 'OccName.mkVectIsoOcc'
, ifaceVectInfoParallelVars :: [Name] -- iface version of 'vectInfoParallelVar'
, ifaceVectInfoParallelTyCons :: [Name] -- iface version of 'vectInfoParallelTyCon'
}
noVectInfo :: VectInfo
noVectInfo
= VectInfo emptyVarEnv emptyNameEnv emptyNameEnv emptyVarSet emptyNameSet
plusVectInfo :: VectInfo -> VectInfo -> VectInfo
plusVectInfo vi1 vi2 =
VectInfo (vectInfoVar vi1 `plusVarEnv` vectInfoVar vi2)
(vectInfoTyCon vi1 `plusNameEnv` vectInfoTyCon vi2)
(vectInfoDataCon vi1 `plusNameEnv` vectInfoDataCon vi2)
(vectInfoParallelVars vi1 `unionVarSet` vectInfoParallelVars vi2)
(vectInfoParallelTyCons vi1 `unionNameSet` vectInfoParallelTyCons vi2)
concatVectInfo :: [VectInfo] -> VectInfo
concatVectInfo = foldr plusVectInfo noVectInfo
noIfaceVectInfo :: IfaceVectInfo
noIfaceVectInfo = IfaceVectInfo [] [] [] [] []
isNoIfaceVectInfo :: IfaceVectInfo -> Bool
isNoIfaceVectInfo (IfaceVectInfo l1 l2 l3 l4 l5)
= null l1 && null l2 && null l3 && null l4 && null l5
instance Outputable VectInfo where
ppr info = vcat
[ ptext (sLit "variables :") <+> ppr (vectInfoVar info)
, ptext (sLit "tycons :") <+> ppr (vectInfoTyCon info)
, ptext (sLit "datacons :") <+> ppr (vectInfoDataCon info)
, ptext (sLit "parallel vars :") <+> ppr (vectInfoParallelVars info)
, ptext (sLit "parallel tycons :") <+> ppr (vectInfoParallelTyCons info)
]
instance Outputable IfaceVectInfo where
ppr info = vcat
[ ptext (sLit "variables :") <+> ppr (ifaceVectInfoVar info)
, ptext (sLit "tycons :") <+> ppr (ifaceVectInfoTyCon info)
, ptext (sLit "tycons reuse :") <+> ppr (ifaceVectInfoTyConReuse info)
, ptext (sLit "parallel vars :") <+> ppr (ifaceVectInfoParallelVars info)
, ptext (sLit "parallel tycons :") <+> ppr (ifaceVectInfoParallelTyCons info)
]
instance Binary IfaceVectInfo where
put_ bh (IfaceVectInfo a1 a2 a3 a4 a5) = do
put_ bh a1
put_ bh a2
put_ bh a3
put_ bh a4
put_ bh a5
get bh = do
a1 <- get bh
a2 <- get bh
a3 <- get bh
a4 <- get bh
a5 <- get bh
return (IfaceVectInfo a1 a2 a3 a4 a5)
{-
************************************************************************
* *
\subsection{Safe Haskell Support}
* *
************************************************************************
This stuff here is related to supporting the Safe Haskell extension,
primarily about storing under what trust type a module has been compiled.
-}
-- | Is an import a safe import?
type IsSafeImport = Bool
-- | Safe Haskell information for 'ModIface'
-- Simply a wrapper around SafeHaskellMode to sepperate iface and flags
newtype IfaceTrustInfo = TrustInfo SafeHaskellMode
getSafeMode :: IfaceTrustInfo -> SafeHaskellMode
getSafeMode (TrustInfo x) = x
setSafeMode :: SafeHaskellMode -> IfaceTrustInfo
setSafeMode = TrustInfo
noIfaceTrustInfo :: IfaceTrustInfo
noIfaceTrustInfo = setSafeMode Sf_None
trustInfoToNum :: IfaceTrustInfo -> Word8
trustInfoToNum it
= case getSafeMode it of
Sf_None -> 0
Sf_Unsafe -> 1
Sf_Trustworthy -> 2
Sf_Safe -> 3
numToTrustInfo :: Word8 -> IfaceTrustInfo
numToTrustInfo 0 = setSafeMode Sf_None
numToTrustInfo 1 = setSafeMode Sf_Unsafe
numToTrustInfo 2 = setSafeMode Sf_Trustworthy
numToTrustInfo 3 = setSafeMode Sf_Safe
numToTrustInfo 4 = setSafeMode Sf_Safe -- retained for backwards compat, used
-- to be Sf_SafeInfered but we no longer
-- differentiate.
numToTrustInfo n = error $ "numToTrustInfo: bad input number! (" ++ show n ++ ")"
instance Outputable IfaceTrustInfo where
ppr (TrustInfo Sf_None) = ptext $ sLit "none"
ppr (TrustInfo Sf_Unsafe) = ptext $ sLit "unsafe"
ppr (TrustInfo Sf_Trustworthy) = ptext $ sLit "trustworthy"
ppr (TrustInfo Sf_Safe) = ptext $ sLit "safe"
instance Binary IfaceTrustInfo where
put_ bh iftrust = putByte bh $ trustInfoToNum iftrust
get bh = getByte bh >>= (return . numToTrustInfo)
{-
************************************************************************
* *
\subsection{Parser result}
* *
************************************************************************
-}
data HsParsedModule = HsParsedModule {
hpm_module :: Located (HsModule RdrName),
hpm_src_files :: [FilePath],
-- ^ extra source files (e.g. from #includes). The lexer collects
-- these from '# <file> <line>' pragmas, which the C preprocessor
-- leaves behind. These files and their timestamps are stored in
-- the .hi file, so that we can force recompilation if any of
-- them change (#3589)
hpm_annotations :: ApiAnns
-- See note [Api annotations] in ApiAnnotation.hs
}
{-
************************************************************************
* *
\subsection{Linkable stuff}
* *
************************************************************************
This stuff is in here, rather than (say) in Linker.hs, because the Linker.hs
stuff is the *dynamic* linker, and isn't present in a stage-1 compiler
-}
-- | Information we can use to dynamically link modules into the compiler
data Linkable = LM {
linkableTime :: UTCTime, -- ^ Time at which this linkable was built
-- (i.e. when the bytecodes were produced,
-- or the mod date on the files)
linkableModule :: Module, -- ^ The linkable module itself
linkableUnlinked :: [Unlinked]
-- ^ Those files and chunks of code we have yet to link.
--
-- INVARIANT: A valid linkable always has at least one 'Unlinked' item.
-- If this list is empty, the Linkable represents a fake linkable, which
-- is generated in HscNothing mode to avoid recompiling modules.
--
-- ToDo: Do items get removed from this list when they get linked?
}
isObjectLinkable :: Linkable -> Bool
isObjectLinkable l = not (null unlinked) && all isObject unlinked
where unlinked = linkableUnlinked l
-- A linkable with no Unlinked's is treated as a BCO. We can
-- generate a linkable with no Unlinked's as a result of
-- compiling a module in HscNothing mode, and this choice
-- happens to work well with checkStability in module GHC.
linkableObjs :: Linkable -> [FilePath]
linkableObjs l = [ f | DotO f <- linkableUnlinked l ]
instance Outputable Linkable where
ppr (LM when_made mod unlinkeds)
= (text "LinkableM" <+> parens (text (show when_made)) <+> ppr mod)
$$ nest 3 (ppr unlinkeds)
-------------------------------------------
-- | Objects which have yet to be linked by the compiler
data Unlinked
= DotO FilePath -- ^ An object file (.o)
| DotA FilePath -- ^ Static archive file (.a)
| DotDLL FilePath -- ^ Dynamically linked library file (.so, .dll, .dylib)
| BCOs CompiledByteCode ModBreaks -- ^ A byte-code object, lives only in memory
#ifndef GHCI
data CompiledByteCode = CompiledByteCodeUndefined
_unused :: CompiledByteCode
_unused = CompiledByteCodeUndefined
#endif
instance Outputable Unlinked where
ppr (DotO path) = text "DotO" <+> text path
ppr (DotA path) = text "DotA" <+> text path
ppr (DotDLL path) = text "DotDLL" <+> text path
#ifdef GHCI
ppr (BCOs bcos _) = text "BCOs" <+> ppr bcos
#else
ppr (BCOs _ _) = text "No byte code"
#endif
-- | Is this an actual file on disk we can link in somehow?
isObject :: Unlinked -> Bool
isObject (DotO _) = True
isObject (DotA _) = True
isObject (DotDLL _) = True
isObject _ = False
-- | Is this a bytecode linkable with no file on disk?
isInterpretable :: Unlinked -> Bool
isInterpretable = not . isObject
-- | Retrieve the filename of the linkable if possible. Panic if it is a byte-code object
nameOfObject :: Unlinked -> FilePath
nameOfObject (DotO fn) = fn
nameOfObject (DotA fn) = fn
nameOfObject (DotDLL fn) = fn
nameOfObject other = pprPanic "nameOfObject" (ppr other)
-- | Retrieve the compiled byte-code if possible. Panic if it is a file-based linkable
byteCodeOfObject :: Unlinked -> CompiledByteCode
byteCodeOfObject (BCOs bc _) = bc
byteCodeOfObject other = pprPanic "byteCodeOfObject" (ppr other)
{-
************************************************************************
* *
\subsection{Breakpoint Support}
* *
************************************************************************
-}
-- | Breakpoint index
type BreakIndex = Int
-- | All the information about the breakpoints for a given module
data ModBreaks
= ModBreaks
{ modBreaks_flags :: BreakArray
-- ^ The array of flags, one per breakpoint,
-- indicating which breakpoints are enabled.
, modBreaks_locs :: !(Array BreakIndex SrcSpan)
-- ^ An array giving the source span of each breakpoint.
, modBreaks_vars :: !(Array BreakIndex [OccName])
-- ^ An array giving the names of the free variables at each breakpoint.
, modBreaks_decls :: !(Array BreakIndex [String])
-- ^ An array giving the names of the declarations enclosing each breakpoint.
}
-- | Construct an empty ModBreaks
emptyModBreaks :: ModBreaks
emptyModBreaks = ModBreaks
{ modBreaks_flags = error "ModBreaks.modBreaks_array not initialised"
-- ToDo: can we avoid this?
, modBreaks_locs = array (0,-1) []
, modBreaks_vars = array (0,-1) []
, modBreaks_decls = array (0,-1) []
}
| fmthoma/ghc | compiler/main/HscTypes.hs | bsd-3-clause | 119,691 | 1 | 21 | 36,084 | 15,268 | 8,516 | 6,752 | 1,414 | 6 |
{-# LANGUAGE ScopedTypeVariables, OverloadedStrings #-}
-----------------------------------------------------------------------------
--
-- Module : IDE.Debug
-- Copyright : (c) Hamish Mackenzie, Juergen Nicklisch-Franken
-- License : GNU-GPL
--
-- Maintainer : <maintainer at leksah.org>
-- Stability : provisional
-- Portability : portable
--
--
-- | The debug methods of ide.
--
---------------------------------------------------------------------------------
module IDE.Debug (
debugCommand
, debugCommand'
, debugToggled
, debugQuit
, debugExecuteSelection
, debugExecuteAndShowSelection
, debugSetBreakpoint
, debugDeleteAllBreakpoints
, debugDeleteBreakpoint
, debugContinue
, debugAbandon
, debugStop
, debugStep
, debugStepExpression
, debugStepExpr
, debugStepLocal
, debugStepModule
, debugTrace
, debugTraceExpression
, debugTraceExpr
, debugHistory
, debugBack
, debugForward
, debugForce
, debugPrint
, debugSimplePrint
, debugShowBindings
, debugShowBreakpoints
, debugShowContext
, debugShowModules
, debugShowPackages
, debugShowLanguages
, debugInformation
, debugKind
, debugType
, debugSetPrintEvldWithShow
, debugSetBreakOnException
, debugSetBreakOnError
, debugSetPrintBindResult
) where
import IDE.Core.State
import IDE.LogRef
import Control.Exception (SomeException(..))
import IDE.Pane.SourceBuffer
(selectedLocation, selectedText, selectedModuleName,
insertTextAfterSelection, selectedTextOrCurrentLine)
import IDE.Metainfo.Provider (getActivePackageDescr)
import Distribution.Text (display)
import IDE.Pane.Log
import Data.List (stripPrefix, isSuffixOf)
import IDE.Utils.GUIUtils (getDebugToggled)
import IDE.Package (debugStart, executeDebugCommand, tryDebug, printBindResultFlag,
breakOnErrorFlag, breakOnExceptionFlag, printEvldWithShowFlag)
import IDE.Utils.Tool (ToolOutput(..), toolProcess, interruptProcessGroupOf)
import IDE.Workspaces (packageTry)
import qualified Data.Conduit as C
import qualified Data.Conduit.List as CL
import Control.Monad.Trans.Class (MonadTrans(..))
import Control.Monad.Trans.Reader (ask)
import Control.Monad.IO.Class (MonadIO(..))
import Control.Applicative (Alternative(..), (<$>), (<*>))
import Data.IORef (newIORef)
import Data.Monoid ((<>), Monoid(..))
import Data.Text (Text)
import qualified Data.Text as T
(pack, lines, stripPrefix, unlines, isSuffixOf, unpack)
import System.Exit (ExitCode(..))
import IDE.Pane.WebKit.Output (loadOutputUri)
-- | Get the last item
sinkLast = CL.fold (\_ a -> Just a) Nothing
debugCommand :: Text -> C.Sink ToolOutput IDEM () -> DebugAction
debugCommand command handler = do
debugCommand' command handler
lift $ triggerEventIDE VariablesChanged
return ()
debugCommand' :: Text -> C.Sink ToolOutput IDEM () -> DebugAction
debugCommand' command handler = do
ghci <- ask
lift $ catchIDE (runDebug (executeDebugCommand command handler) ghci)
(\(e :: SomeException) -> (print e))
debugToggled :: IDEAction
debugToggled = do
toggled <- getDebugToggled
maybeDebug <- readIDE debugState
case (toggled, maybeDebug) of
(True, Nothing) -> packageTry debugStart
(False, Just _) -> debugQuit
_ -> return ()
debugQuit :: IDEAction
debugQuit = do
maybeDebug <- readIDE debugState
case maybeDebug of
Just debug -> runDebug (debugCommand ":quit" logOutputDefault) debug
_ -> return ()
-- | Remove haddock code prefix from selected text so it can be run
-- in ghci
--
-- Press Ctrl + Enter on these to try it out...
--
-- > stripComments "-- > Wow this is meta"
--
-- > stripComments "-- This is still a comment"
stripComments :: Text -> Text
stripComments t = maybe t T.unlines $
mapM (T.stripPrefix "-- >>>") lines'
<|> mapM (T.stripPrefix "-- >") lines'
where
lines' = T.lines t
debugExecuteSelection :: IDEAction
debugExecuteSelection = do
maybeText <- selectedTextOrCurrentLine
case maybeText of
Just text -> do
let command = packageTry $ tryDebug $ do
debugSetLiberalScope
buffer <- liftIO $ newIORef mempty
debugCommand (stripComments text) $ do
_ <- C.getZipSink $ const
<$> C.ZipSink sinkLast
<*> C.ZipSink (logOutputPane text buffer)
mbURI <- lift $ readIDE autoURI
case mbURI of
Just uri -> lift . postSyncIDE . loadOutputUri $ T.unpack uri
Nothing -> return ()
modifyIDE_ $ \ide -> ide {autoCommand = command, autoURI = Nothing}
command
Nothing -> ideMessage Normal "Please select some text in the editor to execute"
debugExecuteAndShowSelection :: IDEAction
debugExecuteAndShowSelection = do
maybeText <- selectedTextOrCurrentLine
case maybeText of
Just text -> packageTry $ tryDebug $ do
debugSetLiberalScope
debugCommand (stripComments text) $ do
out <- C.getZipSink $ const
<$> C.ZipSink (CL.fold buildOutputString "")
<*> C.ZipSink logOutputDefault
lift . insertTextAfterSelection $ " " <> out
Nothing -> ideMessage Normal "Please select some text in the editor to execute"
where
buildOutputString :: Text -> ToolOutput -> Text
buildOutputString "" (ToolOutput str) = str
buildOutputString s (ToolOutput str) = s <> "\n" <> str
buildOutputString s _ = s
debugSetLiberalScope :: DebugAction
debugSetLiberalScope = do
maybeModuleName <- lift selectedModuleName
case maybeModuleName of
Just moduleName ->
debugCommand (":module *" <> moduleName) CL.sinkNull
Nothing -> do
mbPackage <- lift getActivePackageDescr
case mbPackage of
Nothing -> return ()
Just p -> let packageNames = map (T.pack . display . modu . mdModuleId) (pdModules p)
in debugCommand' (foldl (\a b -> a <> " *" <> b) ":module + " packageNames)
CL.sinkNull
debugAbandon :: IDEAction
debugAbandon =
packageTry $ tryDebug $ debugCommand ":abandon" logOutputDefault
debugBack :: IDEAction
debugBack = packageTry $ do
currentHist' <- lift $ readIDE currentHist
liftIDE $ modifyIDE_ (\ide -> ide{currentHist = min (currentHist' - 1) 0})
tryDebug $ do
(debugPackage, _) <- ask
debugCommand ":back" (logOutputForHistoricContextDefault debugPackage)
debugForward :: IDEAction
debugForward = packageTry $ do
currentHist' <- lift $ readIDE currentHist
liftIDE $ modifyIDE_ (\ide -> ide{currentHist = currentHist' + 1})
tryDebug $ do
(debugPackage, _) <- ask
debugCommand ":forward" (logOutputForHistoricContextDefault debugPackage)
debugStop :: IDEAction
debugStop = do
maybeDebug <- readIDE debugState
liftIO $ case maybeDebug of
Just (_, ghci) -> toolProcess ghci >>= interruptProcessGroupOf
Nothing -> return ()
debugContinue :: IDEAction
debugContinue = packageTry $ tryDebug $ do
(debugPackage, _) <- ask
debugCommand ":continue" (logOutputForHistoricContextDefault debugPackage)
debugDeleteAllBreakpoints :: IDEAction
debugDeleteAllBreakpoints = do
packageTry $ tryDebug $ debugCommand ":delete *" logOutputDefault
setBreakpointList []
debugDeleteBreakpoint :: Text -> LogRef -> IDEAction
debugDeleteBreakpoint indexString lr = do
packageTry $ tryDebug $ debugCommand (":delete " <> indexString) logOutputDefault
bl <- readIDE breakpointRefs
setBreakpointList $ filter (/= lr) bl
ideR <- ask
return ()
debugForce :: IDEAction
debugForce = do
maybeText <- selectedTextOrCurrentLine
case maybeText of
Just text -> packageTry $ tryDebug $ debugCommand (":force " <> stripComments text) logOutputDefault
Nothing -> ideMessage Normal "Please select an expression in the editor"
debugHistory :: IDEAction
debugHistory = packageTry $ tryDebug $ debugCommand ":history" logOutputDefault
debugPrint :: IDEAction
debugPrint = do
maybeText <- selectedTextOrCurrentLine
case maybeText of
Just text -> packageTry $ tryDebug $ debugCommand (":print " <> stripComments text) logOutputDefault
Nothing -> ideMessage Normal "Please select an name in the editor"
debugSimplePrint :: IDEAction
debugSimplePrint = do
maybeText <- selectedTextOrCurrentLine
case maybeText of
Just text -> packageTry $ tryDebug $ debugCommand (":force " <> stripComments text) logOutputDefault
Nothing -> ideMessage Normal "Please select an name in the editor"
debugStep :: IDEAction
debugStep = packageTry $ tryDebug $ do
(debugPackage, _) <- ask
debugSetLiberalScope
debugCommand ":step" (logOutputForHistoricContextDefault debugPackage)
debugStepExpression :: IDEAction
debugStepExpression = do
maybeText <- selectedTextOrCurrentLine
packageTry $ tryDebug $ do
debugSetLiberalScope
debugStepExpr maybeText
debugStepExpr :: Maybe Text -> DebugAction
debugStepExpr maybeText = do
(debugPackage, _) <- ask
case maybeText of
Just text -> debugCommand (":step " <> stripComments text) (logOutputForHistoricContextDefault debugPackage)
Nothing -> lift $ ideMessage Normal "Please select an expression in the editor"
debugStepLocal :: IDEAction
debugStepLocal = packageTry $ tryDebug $ do
(debugPackage, _) <- ask
debugCommand ":steplocal" (logOutputForHistoricContextDefault debugPackage)
debugStepModule :: IDEAction
debugStepModule = packageTry $ tryDebug $ do
(debugPackage, _) <- ask
debugCommand ":stepmodule" (logOutputForHistoricContextDefault debugPackage)
logTraceOutput debugPackage = do
logOutputForLiveContextDefault debugPackage
lift $ triggerEventIDE TraceChanged
return ()
debugTrace :: IDEAction
debugTrace = packageTry $ tryDebug $ do
(debugPackage, _) <- ask
debugCommand ":trace" $ logTraceOutput debugPackage
debugTraceExpression :: IDEAction
debugTraceExpression = do
maybeText <- selectedTextOrCurrentLine
packageTry $ tryDebug $ do
debugSetLiberalScope
debugTraceExpr maybeText
debugTraceExpr :: Maybe Text -> DebugAction
debugTraceExpr maybeText = do
(debugPackage, _) <- ask
case maybeText of
Just text -> debugCommand (":trace " <> stripComments text) $ logTraceOutput debugPackage
Nothing -> lift $ ideMessage Normal "Please select an expression in the editor"
debugShowBindings :: IDEAction
debugShowBindings = packageTry $ tryDebug $ debugCommand ":show bindings" logOutputDefault
debugShowBreakpoints :: IDEAction
debugShowBreakpoints = packageTry $ tryDebug $ do
(debugPackage, _) <- ask
debugCommand ":show breaks" (logOutputForSetBreakpointDefault debugPackage)
debugShowContext :: IDEAction
debugShowContext = packageTry $ tryDebug $ do
(debugPackage, _) <- ask
debugCommand ":show context" (logOutputForHistoricContextDefault debugPackage)
debugShowModules :: IDEAction
debugShowModules = packageTry $ tryDebug $ debugCommand ":show modules" $
logOutputLines_Default $ \log logLaunch output -> liftIO $ do
case output of
ToolInput line -> appendLog log logLaunch (line <> "\n") InputTag
ToolOutput line | ", interpreted )" `T.isSuffixOf` line
-> appendLog log logLaunch (line <> "\n") LogTag
ToolOutput line -> appendLog log logLaunch (line <> "\n") InfoTag
ToolError line -> appendLog log logLaunch (line <> "\n") ErrorTag
ToolPrompt _ -> defaultLineLogger' log logLaunch output
ToolExit _ -> appendLog log logLaunch "X--X--X ghci process exited unexpectedly X--X--X" FrameTag
return ()
debugShowPackages :: IDEAction
debugShowPackages = packageTry $ tryDebug $ debugCommand ":show packages" logOutputDefault
debugShowLanguages :: IDEAction
debugShowLanguages = packageTry $ tryDebug $ debugCommand ":show languages" logOutputDefault
debugInformation :: IDEAction
debugInformation = do
maybeText <- selectedTextOrCurrentLine
case maybeText of
Just text -> packageTry $ tryDebug $ do
debugSetLiberalScope
debugCommand (":info "<>stripComments text) logOutputDefault
Nothing -> ideMessage Normal "Please select a name in the editor"
debugKind :: IDEAction
debugKind = do
maybeText <- selectedTextOrCurrentLine
case maybeText of
Just text -> packageTry $ tryDebug $ do
debugSetLiberalScope
debugCommand (":kind "<>stripComments text) logOutputDefault
Nothing -> ideMessage Normal "Please select a type in the editor"
debugType :: IDEAction
debugType = do
maybeText <- selectedTextOrCurrentLine
case maybeText of
Just text -> packageTry $ tryDebug $ do
debugSetLiberalScope
debugCommand (":type "<>stripComments text) logOutputDefault
Nothing -> ideMessage Normal "Please select an expression in the editor"
debugSetBreakpoint :: IDEAction
debugSetBreakpoint = do
maybeModuleName <- selectedModuleName
case maybeModuleName of
Just moduleName -> do
-- ### debugCommand (":add *"++moduleName) $ logOutputForBuild True
maybeText <- selectedText
case maybeText of
Just text -> packageTry $ tryDebug $ do
(debugPackage, _) <- ask
debugCommand (":module *" <> moduleName) logOutputDefault
debugCommand (":break " <> text) (logOutputForSetBreakpointDefault debugPackage)
Nothing -> do
maybeLocation <- selectedLocation
case maybeLocation of
Just (line, lineOffset) -> packageTry $ tryDebug $ do
(debugPackage, _) <- ask
debugCommand (":break " <> moduleName <> " " <> T.pack (show $ line + 1) <> " " <> T.pack (show lineOffset))
(logOutputForSetBreakpointDefault debugPackage)
Nothing -> ideMessage Normal "Unknown error setting breakpoint"
ref <- ask
return ()
Nothing -> ideMessage Normal "Please select module file in the editor"
debugSet :: (Bool -> Text) -> Bool -> IDEAction
debugSet flag value =
packageTry $ tryDebug $ debugCommand (":set " <> flag value) logOutputDefault
debugSetPrintEvldWithShow :: Bool -> IDEAction
debugSetPrintEvldWithShow = debugSet printEvldWithShowFlag
debugSetBreakOnException :: Bool -> IDEAction
debugSetBreakOnException = debugSet breakOnExceptionFlag
debugSetBreakOnError :: Bool -> IDEAction
debugSetBreakOnError = debugSet breakOnErrorFlag
debugSetPrintBindResult :: Bool -> IDEAction
debugSetPrintBindResult = debugSet printBindResultFlag
| 573/leksah | src/IDE/Debug.hs | gpl-2.0 | 15,140 | 35 | 34 | 3,574 | 3,681 | 1,814 | 1,867 | -1 | -1 |
{-
Copyright (C) 2001, 2004 Ian Lynagh <[email protected]>
Modified by Einar Karttunen to remove dependency on packed strings
and autoconf.
Modified by John Meacham for code cleanups.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-}
{-# OPTIONS -funbox-strict-fields -fglasgow-exts -fno-warn-name-shadowing -O2 #-}
module Util.SHA1 (sha1String,sha1file,sha1Bytes,hashToBytes,sha1Handle,ABCDE(..),Hash,emptyHash) where
import Control.Monad (unless)
import Data.Char (intToDigit,ord)
import Foreign
import Foreign.C
import System.IO
import System.IO.Unsafe (unsafePerformIO) as US
type Hash = ABCDE
data ABCDE = ABCDE !Word32 !Word32 !Word32 !Word32 !Word32
deriving(Eq,Ord)
emptyHash = ABCDE 0 0 0 0 0
data XYZ = XYZ !Word32 !Word32 !Word32
sha1String :: String -> Hash
sha1String ss = sha1Bytes (toUTF ss) where
-- | Convert Unicode characters to UTF-8.
toUTF :: String -> [Word8]
toUTF [] = []
toUTF (x:xs) | ord x<=0x007F = (fromIntegral $ ord x):toUTF xs
| ord x<=0x07FF = fromIntegral (0xC0 .|. ((ord x `shift` (-6)) .&. 0x1F)):
fromIntegral (0x80 .|. (ord x .&. 0x3F)):
toUTF xs
| otherwise = fromIntegral (0xE0 .|. ((ord x `shift` (-12)) .&. 0x0F)):
fromIntegral (0x80 .|. ((ord x `shift` (-6)) .&. 0x3F)):
fromIntegral (0x80 .|. (ord x .&. 0x3F)):
toUTF xs
sha1Bytes :: [Word8] -> Hash
sha1Bytes ss = US.unsafePerformIO $ do
let len = length ss
plen = sha1_step_1_2_plength len
allocaBytes plen $ \ptr -> do
pokeArray ptr ss
let num_nuls = (55 - len) `mod` 64
pokeArray (advancePtr ptr len) ((128:replicate num_nuls 0)++(reverse $ size_split 8 (fromIntegral len*8)))
let abcde = sha1_step_3_init
let ptr' = castPtr ptr
unless big_endian $ fiddle_endianness ptr' plen
res <- sha1_step_4_main abcde ptr' plen
return res
{-# NOINLINE sha1Handle #-}
sha1Handle :: Handle -> IO Hash
sha1Handle h = do
hSeek h AbsoluteSeek 0
len <- hFileSize h
len <- return $ fromIntegral len
let plen = sha1_step_1_2_plength len
allocaBytes plen $ \ptr -> do
cnt <- hGetBuf h ptr len
unless (cnt == len) $ fail "sha1File - read returned too few bytes"
hSeek h AbsoluteSeek 0
let num_nuls = (55 - len) `mod` 64
pokeArray (advancePtr ptr len) ((128:replicate num_nuls 0)++(reverse $ size_split 8 (fromIntegral len*8)))
let abcde = sha1_step_3_init
let ptr' = castPtr ptr
unless big_endian $ fiddle_endianness ptr' plen
res <- sha1_step_4_main abcde ptr' plen
return res
{-# NOINLINE sha1file #-}
sha1file :: FilePath -> IO Hash
sha1file fp = do
h <- openBinaryFile fp ReadMode
hash <- sha1Handle h
hClose h
return hash
big_endian = US.unsafePerformIO $ do
let x :: Word32
x = 0x12345678
s <- with x $ \ptr -> peekCStringLen (castPtr ptr,4)
case s of
"\x12\x34\x56\x78" -> return True
"\x78\x56\x34\x12" -> return False
_ -> error "Testing endianess failed"
fiddle_endianness :: Ptr Word32 -> Int -> IO ()
fiddle_endianness p 0 = p `seq` return ()
fiddle_endianness p n
= do x <- peek p
poke p $ shiftL x 24
.|. shiftL (x .&. 0xff00) 8
.|. (shiftR x 8 .&. 0xff00)
.|. shiftR x 24
fiddle_endianness (p `advancePtr` 1) (n - 4)
-- sha1_step_1_2_pad_length assumes the length is at most 2^61.
-- This seems reasonable as the Int used to represent it is normally 32bit,
-- but obviously could go wrong with large inputs on 64bit machines.
-- The PackedString library should probably move to Word64s if this is an
-- issue, though.
--
-- sha1_step_1_2_pad_length :: PackedString -> PackedString
-- sha1_step_1_2_pad_length s
-- = let len = lengthPS s
-- num_nuls = (55 - len) `mod` 64
-- padding = 128:replicate num_nuls 0
-- len_w8s = reverse $ size_split 8 (fromIntegral len*8)
-- in concatLenPS (len + 1 + num_nuls + 8)
-- [s, packWords padding, packWords len_w8s]
sha1_step_1_2_plength :: Int -> Int
sha1_step_1_2_plength len = (len + 1 + num_nuls + 8) where num_nuls = (55 - len) `mod` 64
size_split :: Int -> Integer -> [Word8]
size_split 0 _ = []
size_split p n = fromIntegral d:size_split (p-1) n'
where (n', d) = divMod n 256
sha1_step_3_init :: ABCDE
sha1_step_3_init = ABCDE 0x67452301 0xefcdab89 0x98badcfe 0x10325476 0xc3d2e1f0
sha1_step_4_main :: ABCDE -> Ptr Word32 -> Int -> IO ABCDE
sha1_step_4_main abcde _ 0 = return $! abcde
sha1_step_4_main (ABCDE a0@a b0@b c0@c d0@d e0@e) s len
= do
(e, b) <- doit f1 0x5a827999 (x 0) a b c d e
(d, a) <- doit f1 0x5a827999 (x 1) e a b c d
(c, e) <- doit f1 0x5a827999 (x 2) d e a b c
(b, d) <- doit f1 0x5a827999 (x 3) c d e a b
(a, c) <- doit f1 0x5a827999 (x 4) b c d e a
(e, b) <- doit f1 0x5a827999 (x 5) a b c d e
(d, a) <- doit f1 0x5a827999 (x 6) e a b c d
(c, e) <- doit f1 0x5a827999 (x 7) d e a b c
(b, d) <- doit f1 0x5a827999 (x 8) c d e a b
(a, c) <- doit f1 0x5a827999 (x 9) b c d e a
(e, b) <- doit f1 0x5a827999 (x 10) a b c d e
(d, a) <- doit f1 0x5a827999 (x 11) e a b c d
(c, e) <- doit f1 0x5a827999 (x 12) d e a b c
(b, d) <- doit f1 0x5a827999 (x 13) c d e a b
(a, c) <- doit f1 0x5a827999 (x 14) b c d e a
(e, b) <- doit f1 0x5a827999 (x 15) a b c d e
(d, a) <- doit f1 0x5a827999 (m 16) e a b c d
(c, e) <- doit f1 0x5a827999 (m 17) d e a b c
(b, d) <- doit f1 0x5a827999 (m 18) c d e a b
(a, c) <- doit f1 0x5a827999 (m 19) b c d e a
(e, b) <- doit f2 0x6ed9eba1 (m 20) a b c d e
(d, a) <- doit f2 0x6ed9eba1 (m 21) e a b c d
(c, e) <- doit f2 0x6ed9eba1 (m 22) d e a b c
(b, d) <- doit f2 0x6ed9eba1 (m 23) c d e a b
(a, c) <- doit f2 0x6ed9eba1 (m 24) b c d e a
(e, b) <- doit f2 0x6ed9eba1 (m 25) a b c d e
(d, a) <- doit f2 0x6ed9eba1 (m 26) e a b c d
(c, e) <- doit f2 0x6ed9eba1 (m 27) d e a b c
(b, d) <- doit f2 0x6ed9eba1 (m 28) c d e a b
(a, c) <- doit f2 0x6ed9eba1 (m 29) b c d e a
(e, b) <- doit f2 0x6ed9eba1 (m 30) a b c d e
(d, a) <- doit f2 0x6ed9eba1 (m 31) e a b c d
(c, e) <- doit f2 0x6ed9eba1 (m 32) d e a b c
(b, d) <- doit f2 0x6ed9eba1 (m 33) c d e a b
(a, c) <- doit f2 0x6ed9eba1 (m 34) b c d e a
(e, b) <- doit f2 0x6ed9eba1 (m 35) a b c d e
(d, a) <- doit f2 0x6ed9eba1 (m 36) e a b c d
(c, e) <- doit f2 0x6ed9eba1 (m 37) d e a b c
(b, d) <- doit f2 0x6ed9eba1 (m 38) c d e a b
(a, c) <- doit f2 0x6ed9eba1 (m 39) b c d e a
(e, b) <- doit f3 0x8f1bbcdc (m 40) a b c d e
(d, a) <- doit f3 0x8f1bbcdc (m 41) e a b c d
(c, e) <- doit f3 0x8f1bbcdc (m 42) d e a b c
(b, d) <- doit f3 0x8f1bbcdc (m 43) c d e a b
(a, c) <- doit f3 0x8f1bbcdc (m 44) b c d e a
(e, b) <- doit f3 0x8f1bbcdc (m 45) a b c d e
(d, a) <- doit f3 0x8f1bbcdc (m 46) e a b c d
(c, e) <- doit f3 0x8f1bbcdc (m 47) d e a b c
(b, d) <- doit f3 0x8f1bbcdc (m 48) c d e a b
(a, c) <- doit f3 0x8f1bbcdc (m 49) b c d e a
(e, b) <- doit f3 0x8f1bbcdc (m 50) a b c d e
(d, a) <- doit f3 0x8f1bbcdc (m 51) e a b c d
(c, e) <- doit f3 0x8f1bbcdc (m 52) d e a b c
(b, d) <- doit f3 0x8f1bbcdc (m 53) c d e a b
(a, c) <- doit f3 0x8f1bbcdc (m 54) b c d e a
(e, b) <- doit f3 0x8f1bbcdc (m 55) a b c d e
(d, a) <- doit f3 0x8f1bbcdc (m 56) e a b c d
(c, e) <- doit f3 0x8f1bbcdc (m 57) d e a b c
(b, d) <- doit f3 0x8f1bbcdc (m 58) c d e a b
(a, c) <- doit f3 0x8f1bbcdc (m 59) b c d e a
(e, b) <- doit f2 0xca62c1d6 (m 60) a b c d e
(d, a) <- doit f2 0xca62c1d6 (m 61) e a b c d
(c, e) <- doit f2 0xca62c1d6 (m 62) d e a b c
(b, d) <- doit f2 0xca62c1d6 (m 63) c d e a b
(a, c) <- doit f2 0xca62c1d6 (m 64) b c d e a
(e, b) <- doit f2 0xca62c1d6 (m 65) a b c d e
(d, a) <- doit f2 0xca62c1d6 (m 66) e a b c d
(c, e) <- doit f2 0xca62c1d6 (m 67) d e a b c
(b, d) <- doit f2 0xca62c1d6 (m 68) c d e a b
(a, c) <- doit f2 0xca62c1d6 (m 69) b c d e a
(e, b) <- doit f2 0xca62c1d6 (m 70) a b c d e
(d, a) <- doit f2 0xca62c1d6 (m 71) e a b c d
(c, e) <- doit f2 0xca62c1d6 (m 72) d e a b c
(b, d) <- doit f2 0xca62c1d6 (m 73) c d e a b
(a, c) <- doit f2 0xca62c1d6 (m 74) b c d e a
(e, b) <- doit f2 0xca62c1d6 (m 75) a b c d e
(d, a) <- doit f2 0xca62c1d6 (m 76) e a b c d
(c, e) <- doit f2 0xca62c1d6 (m 77) d e a b c
(b, d) <- doit f2 0xca62c1d6 (m 78) c d e a b
(a, c) <- doit f2 0xca62c1d6 (m 79) b c d e a
let abcde' = ABCDE (a0 + a) (b0 + b) (c0 + c) (d0 + d) (e0 + e)
sha1_step_4_main abcde' (s `advancePtr` 16) (len - 64)
where {-# INLINE f1 #-}
f1 (XYZ x y z) = (x .&. y) .|. ((complement x) .&. z)
{-# INLINE f2 #-}
f2 (XYZ x y z) = x `xor` y `xor` z
{-# INLINE f3 #-}
f3 (XYZ x y z) = (x .&. y) .|. (x .&. z) .|. (y .&. z)
{-# INLINE x #-}
x n = peek (s `advancePtr` n)
{-# INLINE m #-}
m n = do let base = s `advancePtr` (n .&. 15)
x0 <- peek base
x1 <- peek (s `advancePtr` ((n - 14) .&. 15))
x2 <- peek (s `advancePtr` ((n - 8) .&. 15))
x3 <- peek (s `advancePtr` ((n - 3) .&. 15))
let res = rotateL (x0 `xor` x1 `xor` x2 `xor` x3) 1
poke base res
return res
{-# INLINE doit #-}
doit f k i a b c d e = a `seq` c `seq`
do i' <- i
return (rotateL a 5 + f (XYZ b c d) + e + i' + k,
rotateL b 30)
hashToBytes :: Hash -> [Word8]
hashToBytes (ABCDE a b c d e) = tb a . tb b . tb c . tb d . tb e $ [] where
tb :: Word32 -> [Word8] -> [Word8]
tb n = showIt 4 n
showIt :: Int -> Word32 -> [Word8] -> [Word8]
showIt 0 _ r = r
showIt i x r = case quotRem x 256 of
(y, z) -> let c = fromIntegral z
in c `seq` showIt (i-1) y (c:r)
instance Show ABCDE where
showsPrec _ (ABCDE a b c d e) = showAsHex a . showAsHex b . showAsHex c . showAsHex d . showAsHex e
showAsHex :: Word32 -> ShowS
showAsHex n = showIt 8 n
where
showIt :: Int -> Word32 -> String -> String
showIt 0 _ r = r
showIt i x r = case quotRem x 16 of
(y, z) -> let c = intToDigit (fromIntegral z)
in c `seq` showIt (i-1) y (c:r)
| hvr/jhc | src/Util/SHA1.hs | mit | 11,613 | 11 | 30 | 3,855 | 5,255 | 2,642 | 2,613 | -1 | -1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="hi-IN">
<title>OpenAPI Support Add-on</title>
<maps>
<homeID>openapi</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | thc202/zap-extensions | addOns/openapi/src/main/javahelp/org/zaproxy/zap/extension/openapi/resources/help_hi_IN/helpset_hi_IN.hs | apache-2.0 | 971 | 77 | 67 | 157 | 413 | 209 | 204 | -1 | -1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="tr-TR">
<title>Custom Payloads Add-on</title>
<maps>
<homeID>custompayloads</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | kingthorin/zap-extensions | addOns/custompayloads/src/main/javahelp/org/zaproxy/zap/extension/custompayloads/resources/help_tr_TR/helpset_tr_TR.hs | apache-2.0 | 978 | 77 | 67 | 157 | 413 | 209 | 204 | -1 | -1 |
{-|
Module : Idris.REPL.Parser
Description : Parser for the REPL commands.
License : BSD3
Maintainer : The Idris Community.
-}
{-# LANGUAGE FlexibleContexts #-}
module Idris.REPL.Parser (
parseCmd
, help
, allHelp
, setOptions
) where
import Idris.AbsSyntax
import Idris.Colours
import Idris.Core.TT
import Idris.Help
import Idris.Imports
import Idris.Options
import qualified Idris.Parser as IP
import qualified Idris.Parser.Expr as IP
import qualified Idris.Parser.Helpers as IP
import qualified Idris.Parser.Ops as IP
import Idris.REPL.Commands
import Control.Applicative
import Control.Monad.State.Strict
import Data.Char (isSpace, toLower)
import Data.List
import Data.List.Split (splitOn)
import System.Console.ANSI (Color(..))
import System.FilePath ((</>))
import qualified Text.Megaparsec as P
parseCmd :: IState -> String -> String -> Either IP.ParseError (Either String Command)
parseCmd i inputname = IP.runparser pCmd i inputname . trim
where trim = f . f
where f = reverse . dropWhile isSpace
type CommandTable = [ ( [String], CmdArg, String
, String -> IP.IdrisParser (Either String Command) ) ]
setOptions :: [(String, Opt)]
setOptions = [("errorcontext", ErrContext),
("showimplicits", ShowImpl),
("originalerrors", ShowOrigErr),
("autosolve", AutoSolve),
("nobanner", NoBanner),
("warnreach", WarnReach),
("evaltypes", EvalTypes),
("desugarnats", DesugarNats)]
help :: [([String], CmdArg, String)]
help = (["<expr>"], NoArg, "Evaluate an expression") :
[ (map (':' :) names, args, text) | (names, args, text, _) <- parserCommandsForHelp ]
allHelp :: [([String], CmdArg, String)]
allHelp = [ (map (':' :) names, args, text)
| (names, args, text, _) <- parserCommandsForHelp ++ parserCommands ]
parserCommandsForHelp :: CommandTable
parserCommandsForHelp =
[ exprArgCmd ["t", "type"] Check "Check the type of an expression"
, exprArgCmd ["core"] Core "View the core language representation of a term"
, nameArgCmd ["miss", "missing"] Missing "Show missing clauses"
, (["doc"], NameArg, "Show internal documentation", cmd_doc)
, (["mkdoc"], NamespaceArg, "Generate IdrisDoc for namespace(s) and dependencies"
, genArg "namespace" (P.many P.anySingle) MakeDoc)
, (["apropos"], SeqArgs (OptionalArg PkgArgs) NameArg, " Search names, types, and documentation"
, cmd_apropos)
, (["s", "search"], SeqArgs (OptionalArg PkgArgs) ExprArg
, " Search for values by type", cmd_search)
, nameArgCmd ["wc", "whocalls"] WhoCalls "List the callers of some name"
, nameArgCmd ["cw", "callswho"] CallsWho "List the callees of some name"
, namespaceArgCmd ["browse"] Browse "List the contents of some namespace"
, nameArgCmd ["total"] TotCheck "Check the totality of a name"
, noArgCmd ["r", "reload"] Reload "Reload current file"
, noArgCmd ["w", "watch"] Watch "Watch the current file for changes"
, (["l", "load"], FileArg, "Load a new file"
, strArg (\f -> Load f Nothing))
, (["!"], ShellCommandArg, "Run a shell command", strArg RunShellCommand)
, (["cd"], FileArg, "Change working directory"
, strArg ChangeDirectory)
, (["module"], ModuleArg, "Import an extra module", moduleArg ModImport) -- NOTE: dragons
, noArgCmd ["e", "edit"] Edit "Edit current file using $EDITOR or $VISUAL"
, noArgCmd ["m", "metavars"] Metavars "Show remaining proof obligations (metavariables or holes)"
, (["p", "prove"], MetaVarArg, "Prove a metavariable"
, nameArg (Prove False))
, (["elab"], MetaVarArg, "Build a metavariable using the elaboration shell"
, nameArg (Prove True))
, (["a", "addproof"], NameArg, "Add proof to source file", cmd_addproof)
, (["rmproof"], NameArg, "Remove proof from proof stack"
, nameArg RmProof)
, (["showproof"], NameArg, "Show proof"
, nameArg ShowProof)
, noArgCmd ["proofs"] Proofs "Show available proofs"
, exprArgCmd ["x"] ExecVal "Execute IO actions resulting from an expression using the interpreter"
, (["c", "compile"], FileArg, "Compile to an executable [codegen] <filename>", cmd_compile)
, (["exec", "execute"], OptionalArg ExprArg, "Compile to an executable and run", cmd_execute)
, (["dynamic"], FileArg, "Dynamically load a C library (similar to %dynamic)", cmd_dynamic)
, (["dynamic"], NoArg, "List dynamically loaded C libraries", cmd_dynamic)
, noArgCmd ["?", "h", "help"] Help "Display this help text"
, optArgCmd ["set"] SetOpt $ "Set an option (" ++ optionsList ++ ")"
, optArgCmd ["unset"] UnsetOpt "Unset an option"
, (["color", "colour"], ColourArg
, "Turn REPL colours on or off; set a specific colour"
, cmd_colour)
, (["consolewidth"], ConsoleWidthArg, "Set the width of the console", cmd_consolewidth)
, (["printerdepth"], OptionalArg NumberArg, "Set the maximum pretty-printer depth (no arg for infinite)", cmd_printdepth)
, noArgCmd ["q", "quit"] Quit "Exit the Idris system"
, noArgCmd ["version"] ShowVersion "Display the Idris version"
, noArgCmd ["warranty"] Warranty "Displays warranty information"
, (["let"], ManyArgs DeclArg
, "Evaluate a declaration, such as a function definition, instance implementation, or fixity declaration"
, cmd_let)
, (["unlet", "undefine"], ManyArgs NameArg
, "Remove the listed repl definitions, or all repl definitions if no names given"
, cmd_unlet)
, nameArgCmd ["printdef"] PrintDef "Show the definition of a function"
, (["pp", "pprint"], (SeqArgs OptionArg (SeqArgs NumberArg NameArg))
, "Pretty prints an Idris function in either LaTeX or HTML and for a specified width."
, cmd_pprint)
, (["verbosity"], NumberArg, "Set verbosity level", cmd_verb)
]
where optionsList = intercalate ", " $ map fst setOptions
parserCommands :: CommandTable
parserCommands =
[ noArgCmd ["u", "universes"] Universes "Display universe constraints"
, noArgCmd ["errorhandlers"] ListErrorHandlers "List registered error handlers"
, nameArgCmd ["d", "def"] Defn "Display a name's internal definitions"
, nameArgCmd ["transinfo"] TransformInfo "Show relevant transformation rules for a name"
, nameArgCmd ["di", "dbginfo"] DebugInfo "Show debugging information for a name"
, exprArgCmd ["patt"] Pattelab "(Debugging) Elaborate pattern expression"
, exprArgCmd ["spec"] Spec "?"
, exprArgCmd ["whnf"] WHNF "(Debugging) Show weak head normal form of an expression"
, exprArgCmd ["inline"] TestInline "?"
, proofArgCmd ["cs", "casesplit"] CaseSplitAt
":cs <line> <name> splits the pattern variable on the line"
, proofArgCmd ["apc", "addproofclause"] AddProofClauseFrom
":apc <line> <name> adds a pattern-matching proof clause to name on line"
, proofArgCmd ["ac", "addclause"] AddClauseFrom
":ac <line> <name> adds a clause for the definition of the name on the line"
, proofArgCmd ["am", "addmissing"] AddMissing
":am <line> <name> adds all missing pattern matches for the name on the line"
, proofArgCmd ["mw", "makewith"] MakeWith
":mw <line> <name> adds a with clause for the definition of the name on the line"
, proofArgCmd ["mc", "makecase"] MakeCase
":mc <line> <name> adds a case block for the definition of the metavariable on the line"
, proofArgCmd ["ml", "makelemma"] MakeLemma "?"
, (["log"], NumberArg, "Set logging level", cmd_log)
, ( ["logcats"]
, ManyArgs NameArg
, "Set logging categories"
, cmd_cats)
, (["lto", "loadto"], SeqArgs NumberArg FileArg
, "Load file up to line number", cmd_loadto)
, (["ps", "proofsearch"], NoArg
, ":ps <line> <name> <names> does proof search for name on line, with names as hints"
, cmd_proofsearch)
, (["ref", "refine"], NoArg
, ":ref <line> <name> <name'> attempts to partially solve name on line, with name' as hint, introducing metavariables for arguments that aren't inferrable"
, cmd_refine)
, (["debugunify"], SeqArgs ExprArg ExprArg
, "(Debugging) Try to unify two expressions", const $ do
l <- IP.simpleExpr defaultSyntax
r <- IP.simpleExpr defaultSyntax
P.eof
return (Right (DebugUnify l r))
)
]
noArgCmd names command doc =
(names, NoArg, doc, noArgs command)
nameArgCmd names command doc =
(names, NameArg, doc, fnNameArg command)
namespaceArgCmd names command doc =
(names, NamespaceArg, doc, namespaceArg command)
exprArgCmd names command doc =
(names, ExprArg, doc, exprArg command)
optArgCmd names command doc =
(names, OptionArg, doc, optArg command)
proofArgCmd names command doc =
(names, NoArg, doc, proofArg command)
pCmd :: IP.IdrisParser (Either String Command)
pCmd = P.choice [ do c <- cmd names; parser c
| (names, _, _, parser) <- parserCommandsForHelp ++ parserCommands ]
<|> unrecognized
<|> nop
<|> eval
where nop = do P.eof; return (Right NOP)
unrecognized = do
IP.lchar ':'
cmd <- P.many P.anySingle
let cmd' = takeWhile (/=' ') cmd
return (Left $ "Unrecognized command: " ++ cmd')
cmd :: [String] -> IP.IdrisParser String
cmd xs = P.try $ do
IP.lchar ':'
docmd sorted_xs
where docmd [] = fail "Could not parse command"
docmd (x:xs) = P.try (IP.reserved x >> return x) <|> docmd xs
sorted_xs = sortBy (\x y -> compare (length y) (length x)) xs
noArgs :: Command -> String -> IP.IdrisParser (Either String Command)
noArgs cmd name = do
let emptyArgs = do
P.eof
return (Right cmd)
let failure = return (Left $ ":" ++ name ++ " takes no arguments")
emptyArgs <|> failure
eval :: IP.IdrisParser (Either String Command)
eval = do
t <- IP.fullExpr defaultSyntax
return $ Right (Eval t)
exprArg :: (PTerm -> Command) -> String -> IP.IdrisParser (Either String Command)
exprArg cmd name = do
let noArg = do
P.eof
return $ Left ("Usage is :" ++ name ++ " <expression>")
let justOperator = do
(op, fc) <- IP.withExtent IP.symbolicOperator
P.eof
return $ Right $ cmd (PRef fc [] (sUN op))
let properArg = do
t <- IP.fullExpr defaultSyntax
return $ Right (cmd t)
P.try noArg <|> P.try justOperator <|> properArg
genArg :: String -> IP.IdrisParser a -> (a -> Command)
-> String -> IP.IdrisParser (Either String Command)
genArg argName argParser cmd name = do
let emptyArgs = do P.eof; failure
oneArg = do arg <- argParser
P.eof
return (Right (cmd arg))
P.try emptyArgs <|> oneArg <|> failure
where
failure = return $ Left ("Usage is :" ++ name ++ " <" ++ argName ++ ">")
nameArg, fnNameArg :: (Name -> Command) -> String -> IP.IdrisParser (Either String Command)
nameArg = genArg "name" IP.name
fnNameArg = genArg "functionname" IP.fnName
strArg :: (String -> Command) -> String -> IP.IdrisParser (Either String Command)
strArg = genArg "string" (P.many P.anySingle)
moduleArg :: (FilePath -> Command) -> String -> IP.IdrisParser (Either String Command)
moduleArg = genArg "module" (fmap toPath IP.identifier)
where
toPath n = foldl1' (</>) $ splitOn "." n
namespaceArg :: ([String] -> Command) -> String -> IP.IdrisParser (Either String Command)
namespaceArg = genArg "namespace" (fmap toNS IP.identifier)
where
toNS = splitOn "."
optArg :: (Opt -> Command) -> String -> IP.IdrisParser (Either String Command)
optArg cmd name = do
let emptyArgs = do
P.eof
return $ Left ("Usage is :" ++ name ++ " <option>")
let oneArg = do
o <- pOption
IP.whiteSpace
P.eof
return (Right (cmd o))
let failure = return $ Left "Unrecognized setting"
P.try emptyArgs <|> oneArg <|> failure
where
pOption :: IP.IdrisParser Opt
pOption = foldl (<|>) empty $ map (\(a, b) -> do discard (IP.symbol a); return b) setOptions
proofArg :: (Bool -> Int -> Name -> Command) -> String -> IP.IdrisParser (Either String Command)
proofArg cmd name = do
upd <- P.option False $ do
IP.lchar '!'
return True
l <- IP.natural
n <- IP.name
return (Right (cmd upd (fromInteger l) n))
cmd_doc :: String -> IP.IdrisParser (Either String Command)
cmd_doc name = do
let constant = do
c <- IP.constant
P.eof
return $ Right (DocStr (Right c) FullDocs)
let pType = do
IP.reserved "Type"
P.eof
return $ Right (DocStr (Left $ sUN "Type") FullDocs)
let fnName = fnNameArg (\n -> DocStr (Left n) FullDocs) name
P.try constant <|> pType <|> fnName
cmd_consolewidth :: String -> IP.IdrisParser (Either String Command)
cmd_consolewidth name = do
w <- pConsoleWidth
return (Right (SetConsoleWidth w))
where
pConsoleWidth :: IP.IdrisParser ConsoleWidth
pConsoleWidth = do discard (IP.symbol "auto"); return AutomaticWidth
<|> do discard (IP.symbol "infinite"); return InfinitelyWide
<|> do n <- fromInteger <$> IP.natural
return (ColsWide n)
cmd_printdepth :: String -> IP.IdrisParser (Either String Command)
cmd_printdepth _ = do d <- optional (fromInteger <$> IP.natural)
return (Right $ SetPrinterDepth d)
cmd_execute :: String -> IP.IdrisParser (Either String Command)
cmd_execute name = do
tm <- P.option maintm (IP.fullExpr defaultSyntax)
return (Right (Execute tm))
where
maintm = PRef (fileFC "(repl)") [] (sNS (sUN "main") ["Main"])
cmd_dynamic :: String -> IP.IdrisParser (Either String Command)
cmd_dynamic name = do
let optArg = do l <- P.many P.anySingle
if (l /= "")
then return $ Right (DynamicLink l)
else return $ Right ListDynamic
let failure = return $ Left $ "Usage is :" ++ name ++ " [<library>]"
P.try optArg <|> failure
cmd_pprint :: String -> IP.IdrisParser (Either String Command)
cmd_pprint name = do
fmt <- ppFormat
IP.whiteSpace
n <- fromInteger <$> IP.natural
IP.whiteSpace
t <- IP.fullExpr defaultSyntax
return (Right (PPrint fmt n t))
where
ppFormat :: IP.IdrisParser OutputFmt
ppFormat = (discard (IP.symbol "html") >> return HTMLOutput)
<|> (discard (IP.symbol "latex") >> return LaTeXOutput)
cmd_compile :: String -> IP.IdrisParser (Either String Command)
cmd_compile name = do
let defaultCodegen = Via IBCFormat "c"
let codegenOption :: IP.IdrisParser Codegen
codegenOption = do
let bytecodeCodegen = discard (IP.symbol "bytecode") *> return Bytecode
viaCodegen = do x <- IP.identifier
return (Via IBCFormat (map toLower x))
bytecodeCodegen <|> viaCodegen
let hasOneArg = do
i <- get
f <- IP.identifier
P.eof
return $ Right (Compile defaultCodegen f)
let hasTwoArgs = do
i <- get
codegen <- codegenOption
f <- IP.identifier
P.eof
return $ Right (Compile codegen f)
let failure = return $ Left $ "Usage is :" ++ name ++ " [<codegen>] <filename>"
P.try hasTwoArgs <|> P.try hasOneArg <|> failure
cmd_addproof :: String -> IP.IdrisParser (Either String Command)
cmd_addproof name = do
n <- P.option Nothing $ do
x <- IP.name
return (Just x)
P.eof
return (Right (AddProof n))
cmd_log :: String -> IP.IdrisParser (Either String Command)
cmd_log name = do
i <- fromIntegral <$> IP.natural
P.eof
return (Right (LogLvl i))
cmd_verb :: String -> IP.IdrisParser (Either String Command)
cmd_verb name = do
i <- fromIntegral <$> IP.natural
P.eof
return (Right (Verbosity i))
cmd_cats :: String -> IP.IdrisParser (Either String Command)
cmd_cats name = do
cs <- P.sepBy pLogCats (IP.whiteSpace)
P.eof
return $ Right $ LogCategory (concat cs)
where
badCat = do
c <- IP.identifier
fail $ "Category: " ++ c ++ " is not recognised."
pLogCats :: IP.IdrisParser [LogCat]
pLogCats = P.try (parserCats <$ IP.symbol (strLogCat IParse))
<|> P.try (elabCats <$ IP.symbol (strLogCat IElab))
<|> P.try (codegenCats <$ IP.symbol (strLogCat ICodeGen))
<|> P.try ([ICoverage] <$ IP.symbol (strLogCat ICoverage))
<|> P.try ([IIBC] <$ IP.symbol (strLogCat IIBC))
<|> P.try ([IErasure] <$ IP.symbol (strLogCat IErasure))
<|> badCat
cmd_let :: String -> IP.IdrisParser (Either String Command)
cmd_let name = do
defn <- concat <$> P.many (IP.decl defaultSyntax)
return (Right (NewDefn defn))
cmd_unlet :: String -> IP.IdrisParser (Either String Command)
cmd_unlet name = Right . Undefine <$> P.many IP.name
cmd_loadto :: String -> IP.IdrisParser (Either String Command)
cmd_loadto name = do
toline <- fromInteger <$> IP.natural
f <- P.many P.anySingle
return (Right (Load f (Just toline)))
cmd_colour :: String -> IP.IdrisParser (Either String Command)
cmd_colour name = fmap Right pSetColourCmd
where
colours :: [(String, Maybe Color)]
colours = [ ("black", Just Black)
, ("red", Just Red)
, ("green", Just Green)
, ("yellow", Just Yellow)
, ("blue", Just Blue)
, ("magenta", Just Magenta)
, ("cyan", Just Cyan)
, ("white", Just White)
, ("default", Nothing)
]
pSetColourCmd :: IP.IdrisParser Command
pSetColourCmd = (do c <- pColourType
let defaultColour = IdrisColour Nothing True False False False
opts <- P.sepBy pColourMod (IP.whiteSpace)
let colour = foldr ($) defaultColour $ reverse opts
return $ SetColour c colour)
<|> P.try (IP.symbol "on" >> return ColourOn)
<|> P.try (IP.symbol "off" >> return ColourOff)
pColour :: IP.IdrisParser (Maybe Color)
pColour = doColour colours
where doColour [] = fail "Unknown colour"
doColour ((s, c):cs) = (P.try (IP.symbol s) >> return c) <|> doColour cs
pColourMod :: IP.IdrisParser (IdrisColour -> IdrisColour)
pColourMod = P.try (doVivid <$ IP.symbol "vivid")
<|> P.try (doDull <$ IP.symbol "dull")
<|> P.try (doUnderline <$ IP.symbol "underline")
<|> P.try (doNoUnderline <$ IP.symbol "nounderline")
<|> P.try (doBold <$ IP.symbol "bold")
<|> P.try (doNoBold <$ IP.symbol "nobold")
<|> P.try (doItalic <$ IP.symbol "italic")
<|> P.try (doNoItalic <$ IP.symbol "noitalic")
<|> P.try (pColour >>= return . doSetColour)
where doVivid i = i { vivid = True }
doDull i = i { vivid = False }
doUnderline i = i { underline = True }
doNoUnderline i = i { underline = False }
doBold i = i { bold = True }
doNoBold i = i { bold = False }
doItalic i = i { italic = True }
doNoItalic i = i { italic = False }
doSetColour c i = i { colour = c }
-- | Generate the colour type names using the default Show instance.
colourTypes :: [(String, ColourType)]
colourTypes = map (\x -> ((map toLower . reverse . drop 6 . reverse . show) x, x)) $
enumFromTo minBound maxBound
pColourType :: IP.IdrisParser ColourType
pColourType = doColourType colourTypes
where doColourType [] = fail $ "Unknown colour category. Options: " ++
(concat . intersperse ", " . map fst) colourTypes
doColourType ((s,ct):cts) = (P.try (IP.symbol s) >> return ct) <|> doColourType cts
idChar = P.oneOf (['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] ++ ['_'])
cmd_apropos :: String -> IP.IdrisParser (Either String Command)
cmd_apropos = packageBasedCmd (some idChar) Apropos
packageBasedCmd :: IP.IdrisParser a -> ([PkgName] -> a -> Command)
-> String -> IP.IdrisParser (Either String Command)
packageBasedCmd valParser cmd name =
P.try (do IP.lchar '('
pkgs <- P.sepBy (pkg <* IP.whiteSpace) (IP.lchar ',')
IP.lchar ')'
val <- valParser
return (Right (cmd pkgs val)))
<|> do val <- valParser
return (Right (cmd [] val))
where
pkg = either fail pure . pkgName =<< IP.packageName
cmd_search :: String -> IP.IdrisParser (Either String Command)
cmd_search = packageBasedCmd
(IP.fullExpr (defaultSyntax { implicitAllowed = True })) Search
cmd_proofsearch :: String -> IP.IdrisParser (Either String Command)
cmd_proofsearch name = do
upd <- P.option False (True <$ IP.lchar '!')
l <- fromInteger <$> IP.natural; n <- IP.name
hints <- P.many IP.fnName
return (Right (DoProofSearch upd True l n hints))
cmd_refine :: String -> IP.IdrisParser (Either String Command)
cmd_refine name = do
upd <- P.option False (do IP.lchar '!'; return True)
l <- fromInteger <$> IP.natural; n <- IP.name
hint <- IP.fnName
return (Right (DoProofSearch upd False l n [hint]))
| kojiromike/Idris-dev | src/Idris/REPL/Parser.hs | bsd-3-clause | 21,587 | 0 | 21 | 5,580 | 6,751 | 3,496 | 3,255 | 444 | 3 |
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable, MultiParamTypeClasses,
FlexibleInstances, DeriveGeneric #-}
module WorkerSample where
import Control.Distributed.Process
import Control.Distributed.Process.Serializable
import Control.Distributed.Process.Closure
import Control.Monad.IO.Class
import Control.Monad
import Text.Printf
import Control.Concurrent
import GHC.Generics (Generic)
import Data.Binary
import Data.Typeable
import qualified Data.Map as Map
import Data.Map (Map)
class Send c a where
(!) :: Serializable a => c -> a -> Process ()
instance Send ProcessId a where
(!) = send
instance Send (SendPort a) a where
(!) = sendChan
type Key = String -- should really use ByteString
type Value = String
data Request
= Set Key Value
| Get Key (SendPort (Maybe Value))
deriving (Typeable, Generic)
instance Binary Request
worker :: Process ()
worker = go Map.empty
where
go store = do
r <- expect
case r of
Set k v ->
go (Map.insert k v store)
Get k port -> do
port ! (Map.lookup k store)
go store
remotable ['worker]
| prt2121/haskell-practice | parconc/distrib-db/WorkerSample.hs | apache-2.0 | 1,108 | 0 | 17 | 228 | 338 | 185 | 153 | 39 | 2 |
{-# LANGUAGE Safe #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Ratio
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : stable
-- Portability : portable
--
-- Standard functions on rational numbers
--
-----------------------------------------------------------------------------
module Data.Ratio
( Ratio
, Rational
, (%)
, numerator
, denominator
, approxRational
) where
import Prelude
import GHC.Real -- The basic defns for Ratio
-- -----------------------------------------------------------------------------
-- approxRational
-- | 'approxRational', applied to two real fractional numbers @x@ and @epsilon@,
-- returns the simplest rational number within @epsilon@ of @x@.
-- A rational number @y@ is said to be /simpler/ than another @y'@ if
--
-- * @'abs' ('numerator' y) <= 'abs' ('numerator' y')@, and
--
-- * @'denominator' y <= 'denominator' y'@.
--
-- Any real interval contains a unique simplest rational;
-- in particular, note that @0\/1@ is the simplest rational of all.
-- Implementation details: Here, for simplicity, we assume a closed rational
-- interval. If such an interval includes at least one whole number, then
-- the simplest rational is the absolutely least whole number. Otherwise,
-- the bounds are of the form q%1 + r%d and q%1 + r'%d', where abs r < d
-- and abs r' < d', and the simplest rational is q%1 + the reciprocal of
-- the simplest rational between d'%r' and d%r.
approxRational :: (RealFrac a) => a -> a -> Rational
approxRational rat eps = simplest (rat-eps) (rat+eps)
where simplest x y | y < x = simplest y x
| x == y = xr
| x > 0 = simplest' n d n' d'
| y < 0 = - simplest' (-n') d' (-n) d
| otherwise = 0 :% 1
where xr = toRational x
n = numerator xr
d = denominator xr
nd' = toRational y
n' = numerator nd'
d' = denominator nd'
simplest' n d n' d' -- assumes 0 < n%d < n'%d'
| r == 0 = q :% 1
| q /= q' = (q+1) :% 1
| otherwise = (q*n''+d'') :% n''
where (q,r) = quotRem n d
(q',r') = quotRem n' d'
nd'' = simplest' d' r' d r
n'' = numerator nd''
d'' = denominator nd''
| lukexi/ghc | libraries/base/Data/Ratio.hs | bsd-3-clause | 3,036 | 0 | 11 | 1,224 | 424 | 233 | 191 | 32 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
module Main where
import JSImages
import LI11718
import qualified Tarefa3_${group} as T3
import System.Environment
import Data.Maybe
import Data.List as List
import qualified Data.Text as Text
import Text.Read
import Control.Monad
import Control.Exception
import GHC.Float
import qualified CodeWorld as CW
import Graphics.Gloss hiding ((.*.),(.+.),(.-.))
--import Graphics.Gloss.Data.Picture
--import Graphics.Gloss.Interface.Pure.Game
--import Graphics.Gloss.Juicy
--import Graphics.Gloss.Geometry.Line
import Safe
mexe :: (Int,Int) -> Orientacao -> (Int,Int)
mexe (x,y) Este = (x+1,y)
mexe (x,y) Sul = (x,y+1)
mexe (x,y) Oeste = (x-1,y)
mexe (x,y) Norte = (x,y-1)
roda :: Orientacao -> Bool -> Orientacao
roda Este True = Sul
roda Sul True = Oeste
roda Oeste True = Norte
roda Norte True = Este
roda d False = roda (roda (roda d True) True) True
ponto2Pos :: Ponto -> Posicao
ponto2Pos (x,y) = (i,j)
where x' = floor x
y' = floor y
i = x'
j = y'
data EstadoJogo = J { mapaE :: Mapa
, terreno :: Terreno
, jogador :: EstadoCarro
, tamBloco :: Float
, imagens :: [(String,Picture)]
}
data EstadoCarro = C { posicaoC :: (Double,Double)
, direcaoC :: Double
, velocidadeC :: (Double,Double)
, checkPosicao :: Int
, acelera :: Bool
, trava :: Bool
, viraD :: Bool
, viraE :: Bool
}
data Terreno = T { delta_roda :: Double
, delta_acel :: Double
, delta_drag :: Double
, delta_drift :: Double
, delta_gravity :: Double
}
estadoInicial :: Mapa -> Float -> [(String,Picture)] -> EstadoJogo
estadoInicial m@(Mapa p t) tam imgs = J { mapaE = m
, terreno = standard
, jogador = carroInicial t (fst p) 0
, tamBloco = tam
, imagens = imgs
}
posInicial :: Tabuleiro -> Posicao -> Ponto
posInicial t (a,b) = centroPeca tp (a,b)
where (Peca tp _) = (atNote2 "posInicial" t b a)
carroInicial :: Tabuleiro -> Posicao -> Int -> EstadoCarro
carroInicial t (a,b) i = C { posicaoC = posInicial t (a,b)
, direcaoC = 0
, velocidadeC = (0,0)
, checkPosicao = 0
, acelera = False
, trava = False
, viraD = False
, viraE = False
}
standard :: Terreno
standard = T { delta_roda = 180 -- rotaçao, angulo / segundo
, delta_acel = 4 -- aceleraçao, velocidade / segundo
, delta_drag = 1 -- abrandamento, velocidade / segundo
, delta_drift = 8 -- resistencia pneus, velocidade / segundo
, delta_gravity = 3.5 -- gravidade, velocidade / segundo
}
move :: Double -> EstadoJogo -> EstadoJogo
move n e = e { jogador = c' }
where p = (jogador e)
Mapa _ m = (mapaE e)
c' = moveCarro e n (terreno e) p
moveCarro :: EstadoJogo -> Double -> Terreno -> EstadoCarro -> EstadoCarro
moveCarro b n t c = andaCarro b n t $$ rodaCarro n t c
rodaCarro :: Double -> Terreno -> EstadoCarro -> EstadoCarro
rodaCarro t r c | viraD c = c { direcaoC = direcaoC c - (t*delta_roda r)}
| viraE c = c { direcaoC = direcaoC c + (t*delta_roda r)}
| otherwise = c
andaCarro :: EstadoJogo -> Tempo -> Terreno -> EstadoCarro -> EstadoCarro
andaCarro e t r c = maybe (c { posicaoC = posInicial m (fst p0), velocidadeC = (0,0) }) id col
where v' = (velocidadeC c) .+. (t .*. ((accelVec r c) .+. (dragVec r c) .+. (driftVec r c) .+. (gravityVec r b c)))
Mapa p0 m = mapaE e
(i,j) = (ponto2Pos (posicaoC c))
b = atNote2 "andaCarro" m j i
c' = c { velocidadeC = v' }
col = colideEstado (mapaE e) t c'
(vv,va) = componentsToArrow (velocidadeC c)
colideEstado :: Mapa -> Tempo -> EstadoCarro -> Maybe EstadoCarro
colideEstado (Mapa _ tab) tempo e = do
let carro = Carro (posicaoC e) (direcaoC e) (velocidadeC e)
carro' <- T3.movimenta tab tempo carro
return $$ e { posicaoC = posicao carro', direcaoC = direcao carro', velocidadeC = velocidade carro' }
accelVec :: Terreno -> EstadoCarro -> (Double,Double)
accelVec t c | acelera c && not (trava c) = arrowToComponents (delta_acel t,direcaoC c)
| trava c && not (acelera c) = arrowToComponents (delta_acel t,direcaoC c + 180)
| otherwise = (0,0)
dragVec :: Terreno -> EstadoCarro -> (Double,Double)
dragVec t c = arrowToComponents (delta_drag t*v,a + 180)
where (v,a) = componentsToArrow (velocidadeC c)
driftVec :: Terreno -> EstadoCarro -> (Double,Double)
driftVec t c = arrowToComponents (driftCoef,driftAngle)
where (vv,av) = componentsToArrow $$ velocidadeC c
ad = direcaoC c
driftAngle = if (sin (radians (av-ad))) > 0
then ad-90 -- going right
else ad+90 -- going left
driftCoef = vv * delta_drift t * abs (sin (radians (av-ad)))
gravityVec :: Terreno -> Peca -> EstadoCarro -> (Double,Double)
gravityVec t (Peca (Rampa Sul) _) c = arrowToComponents (delta_gravity t, 90)
gravityVec t (Peca (Rampa Norte) _) c = arrowToComponents (delta_gravity t, 270)
gravityVec t (Peca (Rampa Oeste) _) c = arrowToComponents (delta_gravity t, 0)
gravityVec t (Peca (Rampa Este) _) c = arrowToComponents (delta_gravity t, 180)
gravityVec t _ c = (0,0)
centroPeca :: Tipo -> Posicao -> Ponto
centroPeca (Curva Norte) (a,b) = (toEnum a+0.7,toEnum b+0.7)
centroPeca (Curva Este) (a,b) = (toEnum a+0.3,toEnum b+0.7)
centroPeca (Curva Sul) (a,b) = (toEnum a+0.3,toEnum b+0.3)
centroPeca (Curva Oeste) (a,b) = (toEnum a+0.7,toEnum b+0.3)
centroPeca _ (a,b) = (toEnum a+0.5,toEnum b+0.5)
-- geometry
-- copiado do Gloss para Double
intersecta :: (Ponto,Ponto) -> (Ponto,Ponto) -> Maybe Ponto
intersecta (p1,p2) (p3,p4) | Just p0 <- intersectaL p1 p2 p3 p4
, t12 <- closestPosicaoOnL p1 p2 p0
, t23 <- closestPosicaoOnL p3 p4 p0
, t12 >= 0 && t12 <= 1
, t23 >= 0 && t23 <= 1
= Just p0
| otherwise
= Nothing
-- copiado do Gloss para Double
intersectaL :: Ponto -> Ponto -> Ponto -> Ponto -> Maybe Ponto
intersectaL (x1, y1) (x2, y2) (x3, y3) (x4, y4)
= let dx12 = x1 - x2
dx34 = x3 - x4
dy12 = y1 - y2
dy34 = y3 - y4
den = dx12 * dy34 - dy12 * dx34
in if den == 0
then Nothing
else let det12 = x1*y2 - y1*x2
det34 = x3*y4 - y3*x4
numx = det12 * dx34 - dx12 * det34
numy = det12 * dy34 - dy12 * det34
in Just (numx / den, numy / den)
-- copiado do Gloss para Double
closestPosicaoOnL :: Ponto -> Ponto -> Ponto -> Double
closestPosicaoOnL p1 p2 p3 = (p3 .-. p1) .$$. (p2 .-. p1) / (p2 .-. p1) .$$. (p2 .-. p1)
(.*.) :: Double -> (Double,Double) -> (Double,Double)
(.*.) x (a,b) = ((x*a),(x*b))
(.+.) :: (Double,Double) -> (Double,Double) -> (Double,Double)
(.+.) (x,y) (a,b) = ((x+a),(y+b))
(.-.) :: (Double,Double) -> (Double,Double) -> (Double,Double)
(.-.) (x,y) (a,b) = ((x-a),(y-b))
-- the dot product between two (Double,Double)s
(.$$.) :: (Double,Double) -> (Double,Double) -> Double
(.$$.) (d1,a1) (d2,a2) = (x1*x2) + (y1*y2)
where (x1,y1) = (d1,a1)
(x2,y2) = (d2,a2)
radians th = th * (pi/180)
degrees th = th * (180/pi)
arrowToComponents :: (Double,Double) -> Ponto
arrowToComponents (v,th) = (getX v th,getY v th)
where getX v th = v * cos (radians (th))
getY v th = v * sin (radians (-th))
componentsToArrow :: Ponto -> (Double,Double)
componentsToArrow (x,0) | x >= 0 = (x,0)
componentsToArrow (x,0) | x < 0 = (x,180)
componentsToArrow (0,y) | y >= 0 = (y,-90)
componentsToArrow (0,y) | y < 0 = (y,90)
componentsToArrow (x,y) = (hyp,dir angle)
where
dir o = case (x >= 0, y >= 0) of
(True,True) -> -o
(True,False) -> o
(False,False) -> 180 - o
(False,True) -> 180 + o
hyp = sqrt ((abs x)^2 + (abs y)^2)
angle = degrees $$ atan (abs y / abs x)
dist :: Ponto -> Ponto -> Double
dist (x1,y1) (x2,y2) = sqrt ((x2-x1)^2+(y2-y1)^2)
glossBloco :: EstadoJogo -> Peca -> Picture
glossBloco e (Peca Recta p) = Color (corAltura p) $$ Polygon [(0,-tamBloco e),(0,0),(tamBloco e,0),(tamBloco e,-tamBloco e)]
--glossBloco e (Peca Recta p) = getImage "recta" e --Color (corAltura p) $$ Polygon [(0,-tamBloco e),(0,0),(tamBloco e,0),(tamBloco e,-tamBloco e)]
glossBloco e (Peca (Rampa Norte) p) = transitaBloco e (corAltura (p+1),corAltura p) False
glossBloco e (Peca (Rampa Oeste) p) = transitaBloco e (corAltura (p+1),corAltura p) True
glossBloco e (Peca (Rampa Sul) p) = transitaBloco e (corAltura p,corAltura (p+1)) False
glossBloco e (Peca (Rampa Este) p) = transitaBloco e (corAltura p,corAltura (p+1)) True
glossBloco e (Peca (Curva Oeste) p) = Pictures [getImage "lava" e,Color (corAltura p) $$ Polygon [(0,0),(tamBloco e,0),(tamBloco e,-tamBloco e)]]
glossBloco e (Peca (Curva Sul) p) = Pictures [getImage "lava" e,Color (corAltura p) $$ Polygon [(0,-tamBloco e),(tamBloco e,0),(0,0)]]
glossBloco e (Peca (Curva Norte) p) = Pictures [getImage "lava" e,Color (corAltura p) $$ Polygon [(0,-tamBloco e),(tamBloco e,-tamBloco e),(tamBloco e,0)]]
glossBloco e (Peca (Curva Este) p) = Pictures [getImage "lava" e,Color (corAltura p) $$ Polygon [(0,0),(0,-tamBloco e),(tamBloco e,-tamBloco e)]]
--glossBloco e (Peca (Curva Oeste) p) = Rotate 270 $$ getImage "curva" e --Color (corAltura p) $$ Polygon [(0,0),(tamBloco e,0),(tamBloco e,-tamBloco e)]
--glossBloco e (Peca (Curva Sul) p) = Rotate 180 $$ getImage "curva" e --Color (corAltura p) $$ Polygon [(0,-tamBloco e),(tamBloco e,0),(0,0)]
--glossBloco e (Peca (Curva Norte) p) = Rotate 0 $$ getImage "curva" e --Color (corAltura p) $$ Polygon [(0,-tamBloco e),(tamBloco e,-tamBloco e),(tamBloco e,0)]
--glossBloco e (Peca (Curva Este) p) = Rotate 90 $$ getImage "curva" e --Color (corAltura p) $$ Polygon [(0,0),(0,-tamBloco e),(tamBloco e,-tamBloco e)]
glossBloco e (Peca Lava _) = getImage "lava" e--Blank
numalturas = 5
corAltura :: Altura -> Color
corAltura a | a >= 0 = makeColor c c c 1
where c = (toEnum a) * 1 / numalturas
corAltura a | a < 0 = makeColor r 0 0 1
where r = abs (toEnum a) * 1 / numalturas
--makeColor (0.2*(toEnum a+2)) (0.2*(toEnum a+2)) (0.15*(toEnum a+2)) 1
transitaBloco :: EstadoJogo -> (Color,Color) -> Bool -> Picture
transitaBloco e (c1,c2) i = Translate 0 gy $$ Rotate g $$ Pictures [a,b,c]
where a = Color c1 $$ Polygon [(0,0),(tamBloco e/2,-tamBloco e),(tamBloco e,0)]
b = Color c2 $$ Polygon [(0,0),(tamBloco e/2,-tamBloco e),(0,-tamBloco e)]
c = Color c2 $$ Polygon [(tamBloco e,0),(tamBloco e/2,-tamBloco e),(tamBloco e,-tamBloco e)]
g = if i then -90 else 0
gy = if i then -tamBloco e else 0
glossMapa :: EstadoJogo -> (Float,Float) -> Tabuleiro -> [Picture]
glossMapa e (x,y) [] = []
glossMapa e (x,y) ([]:ls) = glossMapa e (0,y-tamBloco e) ls
--glossMapa e (x,y) ((c:cs):ls) = (Translate (x+(tamBloco e / 2)) (y-(tamBloco e / 2)) $$ glossBloco e c) : glossMapa e (x+tamBloco e,y) (cs:ls)
glossMapa e (x,y) ((c:cs):ls) = (Translate x y $$ glossBloco e c) : glossMapa e (x+tamBloco e,y) (cs:ls)
glossCarro :: EstadoJogo -> Picture
glossCarro s = Translate (double2Float x*tamBloco s) (-double2Float y*tamBloco s) $$ Scale 0.5 0.5 $$ Rotate (-double2Float a) pic
where (x,y) = posicaoC (jogador s)
a = direcaoC (jogador s)
pic = getImage "c1" s --Polygon [(-6,5),(6,0),(-6,-5)]
Mapa _ m = mapaE s
t = atNote2 "glossCarro" m (floor y) (floor x)
glossEvento :: Event -> EstadoJogo -> EstadoJogo
glossEvento e s = s { jogador = c' }
where c' = glossEventoCarro e (jogador s)
glossEventoCarro :: Event -> EstadoCarro -> EstadoCarro
glossEventoCarro (EventKey (SpecialKey KeyDown ) kst _ _) e = e { trava = kst == Down }
glossEventoCarro (EventKey (SpecialKey KeyUp ) kst _ _) e = e { acelera = kst == Down }
glossEventoCarro (EventKey (SpecialKey KeyLeft ) kst _ _) e = e { viraE = kst == Down }
glossEventoCarro (EventKey (SpecialKey KeyRight) kst _ _) e = e { viraD = kst == Down }
glossEventoCarro _ st = st
glossTempo :: Float -> EstadoJogo -> EstadoJogo
glossTempo t m = move (float2Double t) m
glossDesenha :: EstadoJogo -> Picture
glossDesenha e = Translate (-toEnum x*(tamBloco e)/2) (toEnum y*(tamBloco e)/2) $$ Pictures (m'++meta:[p])
where (Mapa ((i,j),_) m) = mapaE e
m' = glossMapa e (0,0) m
p = glossCarro e
meta = Color green $$ Line [((toEnum i*tamBloco e),-(toEnum j*tamBloco e))
,((toEnum i*tamBloco e),-(toEnum j*tamBloco e)-tamBloco e)]
x = (length (head m))
y = (length m)
getImage x e = fromJust $$ List.lookup x (imagens e)
joga :: Int -> IO ()
joga i = do
screen@(Display screenx screeny) <- getDisplay
let back = greyN 0.5
x = toEnum (length (head m))
y = toEnum (length m)
tamanhoX::Float = (realToFrac screenx) / (realToFrac x)
tamanhoY::Float = (realToFrac screeny) / (realToFrac y)
tamanho = min tamanhoX tamanhoY
mapas = (map constroi caminhos_validos) ++ mapas_validos
ini@(Mapa p m) = atNote "joga" mapas i
imgs <- loadImages tamanho screen
let e = (estadoInicial ini tamanho imgs)
play screen back 20 e glossDesenha glossEvento glossTempo
main = catch (joga 0) $$ \(e::SomeException) -> CW.trace (Text.pack $$ displayException e) $$ throw e
-- exemplos
caminhos_validos, caminhos_invalidos :: [Caminho]
caminhos_validos = [c_ex1,c_ex1',c_ex2,c_ex3,c_ex4,c_ex5,c_ex6]
caminhos_invalidos = [c_exOL,c_exOP,c_exDM,c_exHM,c_exR,c_exE]
mapas_validos, mapas_invalidos :: [Mapa]
mapas_validos = [m_ex1,m_ex2,m_ex3]
mapas_invalidos = [m_exPI,m_exLV,m_exEX,m_exLH,m_why]
-- bom
c_ex1 :: Caminho
c_ex1 = [Avanca,CurvaEsq,Avanca,CurvaDir,Avanca,CurvaDir,Desce,Avanca,CurvaEsq,CurvaDir
,CurvaEsq,CurvaDir,CurvaDir,CurvaEsq,CurvaDir,CurvaEsq,CurvaEsq,Avanca,Avanca
,Desce,CurvaDir,CurvaDir,Avanca,Avanca,Desce,CurvaEsq,CurvaDir,Sobe,CurvaDir
,CurvaEsq,CurvaDir,CurvaEsq,Avanca,CurvaDir,Sobe,Sobe,Avanca,Avanca,CurvaDir,Avanca]
c_ex1' :: Caminho
c_ex1' = [Avanca,CurvaEsq,Avanca,CurvaDir,Avanca,CurvaDir,Sobe,Avanca,CurvaEsq,CurvaDir
,CurvaEsq,CurvaDir,CurvaDir,CurvaEsq,CurvaDir,CurvaEsq,CurvaEsq,Avanca,Avanca
,Sobe,CurvaDir,CurvaDir,Avanca,Avanca,Sobe,CurvaEsq,CurvaDir,Desce,CurvaDir
,CurvaEsq,CurvaDir,CurvaEsq,Avanca,CurvaDir,Desce,Desce,Avanca,Avanca,CurvaDir,Avanca]
c_ex2 :: Caminho
c_ex2 = [Avanca,CurvaEsq,CurvaEsq,Avanca,CurvaEsq,CurvaEsq]
-- mapa sobreposto, altura /= da inicial
c_ex3 :: Caminho
c_ex3 = [Desce,CurvaEsq,CurvaEsq,Desce,CurvaEsq,CurvaEsq
,Avanca,CurvaEsq,CurvaEsq,Avanca,CurvaEsq,CurvaEsq]
-- caminho em 8, cruza
c_ex4 :: Caminho
c_ex4 = [Avanca,CurvaDir,Avanca,Avanca,Avanca,CurvaEsq,Avanca,CurvaEsq,Avanca
,CurvaEsq,Avanca,Avanca,Avanca,CurvaDir,Avanca,CurvaDir]
-- caminho minimo válido
c_ex5 :: Caminho
c_ex5 = [CurvaDir,CurvaDir,CurvaDir,CurvaDir]
-- caminho minimo sem vizinhos
c_ex6 :: Caminho
c_ex6 = [Avanca,CurvaDir,Avanca,CurvaDir,Avanca,CurvaDir,Avanca,CurvaDir]
-- mapa nao geravel por caminhos, lava extra a volta
m_ex1 = Mapa ((2,2),Este) [[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava]
,[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava]
,[Peca Lava altLava, Peca (Curva Norte) 2,Peca (Curva Este) 2, Peca Lava altLava]
,[Peca Lava altLava, Peca (Curva Oeste) 2,Peca (Curva Sul) 2, Peca Lava altLava]
,[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava]
,[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava]
]
-- mapa nao geravel por caminhos, altura /= inicial sem possibilidade de rampas
m_ex2 = Mapa ((2,1),Este) [[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava]
,[Peca Lava altLava, Peca (Curva Norte) 5,Peca (Curva Este) 5, Peca Lava altLava]
,[Peca Lava altLava, Peca (Curva Oeste) 5,Peca (Curva Sul) 5, Peca Lava altLava]
,[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava]
]
-- mapa minimo sem vizinhos
m_ex3 = Mapa ((2,1),Este) [[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava]
,[Peca Lava altLava, Peca (Curva Norte) 2,Peca Recta 2,Peca (Curva Este) 2, Peca Lava altLava]
,[Peca Lava altLava, Peca Recta 2,Peca Lava altLava,Peca Recta 2, Peca Lava altLava]
,[Peca Lava altLava, Peca (Curva Oeste) 2,Peca Recta 2,Peca (Curva Sul) 2, Peca Lava altLava]
,[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava]
]
-- testes invalidos
-- aberto
c_exOP :: Caminho
c_exOP = [Avanca,Avanca,CurvaDir,Avanca,Avanca,CurvaEsq,Avanca,CurvaDir,CurvaDir
,Avanca,Avanca,Avanca,CurvaDir,CurvaEsq,Avanca,Avanca,CurvaDir,Avanca,Avanca,CurvaDir,Avanca]
-- fecha mas direcao errada
c_exDM :: Caminho
c_exDM = [Sobe,CurvaEsq,CurvaEsq,Sobe,CurvaEsq,CurvaEsq
,Avanca,CurvaEsq,CurvaEsq,Avanca,CurvaEsq,Avanca]
-- overlaps, aberto
c_exOL :: Caminho
c_exOL = [Avanca,Avanca,CurvaDir,Avanca,Avanca,CurvaEsq,Avanca,CurvaDir,CurvaDir
,Avanca,CurvaDir,Avanca,CurvaDir,CurvaEsq,Avanca,CurvaDir,Avanca,Avanca,CurvaDir,Avanca]
-- height mismatch
c_exHM :: Caminho
c_exHM = [Avanca,Avanca,CurvaDir,Avanca,Avanca,CurvaEsq,Avanca,CurvaDir,CurvaDir
,Avanca,Sobe,Avanca,CurvaDir,CurvaEsq,Avanca,CurvaDir,Avanca,Avanca,CurvaDir,Avanca]
-- cruza com alturas invalidas
c_exR :: Caminho
c_exR = [Avanca,CurvaDir,Avanca,Avanca,Avanca,CurvaEsq,Sobe,CurvaEsq,Avanca
,CurvaEsq,Avanca,Avanca,Avanca,CurvaDir,Desce,CurvaDir]
-- caminho vazio
c_exE :: Caminho
c_exE = []
-- posicao inicial invalida
m_exPI = Mapa ((0,0),Este) [[Peca (Curva Norte) 2,Peca (Curva Este) 2],[Peca (Curva Oeste) 2,Peca (Curva Sul) 2]]
-- mapa so lava
m_exLV = Mapa ((0,0),Este) $$ theFloorIsLava (5,10)
-- mapa com caminho extra
m_exEX = Mapa ((1,0),Este) [[Peca (Curva Norte) 2,Peca Recta 2,Peca (Curva Este) 2],[Peca Recta 2,Peca Recta 2,Peca Recta 2],[Peca (Curva Oeste) 2,Peca Recta 2,Peca (Curva Sul) 2]]
-- altura da lava invalida
m_exLH = Mapa ((1,0),Este) [[Peca (Curva Norte) 2,Peca Recta 2,Peca (Curva Este) 2],[Peca Recta 2,Peca Lava 2,Peca Recta 2],[Peca (Curva Oeste) 2,Peca Recta 2,Peca (Curva Sul) 2]]
m_why = Mapa ((1,1),Este) [[Peca (Curva Norte) 2,Peca Recta 2,Peca (Curva Este) 2],[Peca Recta 2,Peca Recta 2,Peca Recta 2],[Peca (Curva Oeste) 2,Peca Recta 2,Peca (Curva Sul) 2]]
-- T1
constroi :: Caminho -> Mapa
constroi c = Mapa (partida c,dirInit) $$ processa c dirInit altInit (partida c) (theFloorIsLava (dimensao c))
--------------
-- == T1: Solução
--------------
--mexe :: (Int,Int) -> Orientacao -> (Int,Int)
--mexe (x,y) Este = (x+1,y)
--mexe (x,y) Sul = (x,y+1)
--mexe (x,y) Oeste = (x-1,y)
--mexe (x,y) Norte = (x,y-1)
--
--roda :: Orientacao -> Bool -> Orientacao
--roda Este True = Sul
--roda Sul True = Oeste
--roda Oeste True = Norte
--roda Norte True = Este
--roda d False = roda (roda (roda d True) True) True
theFloorIsLava :: Dimensao -> [[Peca]]
theFloorIsLava (n,m) = replicate m (replicate n (Peca Lava altLava))
processa :: Caminho -> Orientacao -> Altura -> (Int,Int) -> [[Peca]] -> [[Peca]]
processa [] _ _ _ m = m
processa (CurvaDir:c) d a (x,y) m = processa c d' a (mexe (x,y) d') m'
where m' = replace m (x,y) (blocoCurvo d d' a)
d' = roda d True
processa (CurvaEsq:c) d a (x,y) m = processa c d' a (mexe (x,y) d') m'
where m' = replace m (x,y) (blocoCurvo d d' a)
d' = roda d False
processa (Avanca:c) d a (x,y) m = processa c d a (mexe (x,y) d) m'
where m' = replace m (x,y) (Peca Recta a)
processa (s:c) d a (x,y) m = processa c d a' (mexe (x,y) d) m'
where m' = replace m (x,y) p'
a' = adapta s a
p' = (blocoRampa s d) (min a a')
replace :: [[a]] -> (Int,Int) -> a -> [[a]]
replace m (x,y) e = (take y m) ++ [l] ++ (drop (y+1) m)
where l = (take x (atNote "replace" m y)) ++ [e] ++ (drop (x+1) (atNote "replace" m y))
blocoCurvo :: Orientacao -> Orientacao -> Altura -> Peca
blocoCurvo Norte Este = Peca (Curva Norte)
blocoCurvo Este Sul = Peca (Curva Este)
blocoCurvo Sul Oeste = Peca (Curva Sul)
blocoCurvo Oeste Norte = Peca (Curva Oeste)
blocoCurvo m n = blocoCurvo (roda (roda n True) True) (roda (roda m True) True)
-- Este Norte == Sul Oeste
-- Sul Este == Oeste Norte
adapta :: Passo -> Altura -> Altura
adapta Sobe a = a+1
adapta Desce a = a-1
adapta _ a = a
blocoRampa :: Passo -> Orientacao -> (Altura -> Peca)
blocoRampa Sobe Norte = Peca (Rampa Norte)
blocoRampa Sobe Oeste = Peca (Rampa Oeste)
blocoRampa Sobe Sul = Peca (Rampa Sul)
blocoRampa Sobe Este = Peca (Rampa Este)
blocoRampa Desce d = blocoRampa Sobe (roda (roda d True) True)
atNote2 str xys x y = atNote str (atNote str xys x) y
| hpacheco/HAAP | examples/plab/oracle/CollisionSimulator.hs | mit | 22,262 | 18 | 15 | 5,734 | 8,929 | 4,898 | 4,031 | -1 | -1 |
-- xmonad config used by Vic Fryzel
-- Author: Vic Fryzel
-- http://github.com/vicfryzel/xmonad-config
import System.IO
import System.Exit
import Data.List(isPrefixOf)
import XMonad
import XMonad.Actions.PhysicalScreens
import XMonad.Hooks.DynamicLog
import XMonad.Hooks.EwmhDesktops
import XMonad.Hooks.InsertPosition
import XMonad.Hooks.ManageDocks
import XMonad.Hooks.ManageHelpers
import XMonad.Hooks.SetWMName
import XMonad.Hooks.UrgencyHook
import XMonad.Layout.Renamed
import qualified XMonad.Layout.Fullscreen as FS
import XMonad.Layout.NoBorders
import XMonad.Layout.Spiral
import XMonad.Layout.Tabbed
import XMonad.Layout.Reflect
import XMonad.Layout.PerWorkspace
import XMonad.Layout.Grid
import XMonad.Layout.IM
import XMonad.Util.Run(spawnPipe)
import XMonad.Util.EZConfig(additionalKeys)
import Data.Ratio ((%))
import qualified XMonad.StackSet as W
import qualified Data.Map as M
import qualified XMonadConfig as C
------------------------------------------------------------------------
-- Terminal
-- The preferred terminal program, which is used in a binding below and by
-- certain contrib modules.
--
myTerminal = "/usr/bin/terminator"
------------------------------------------------------------------------
-- Workspaces
-- The default number of workspaces (virtual screens) and their names.
--
myWorkspaces = ["1:term","2:code","3:web","4:debug","5:vm","6:chat"] ++ map ( (++":") . show ) [7..9]
------------------------------------------------------------------------
-- Window rules
-- Execute arbitrary actions and WindowSet manipulations when managing
-- a new window. You can use this to, for example, always float a
-- particular program, or have a client always appear on a particular
-- workspace.
--
-- To find the property name associated with a program, use
-- > xprop | grep WM_CLASS
-- and click on the client you're interested in.
--
-- To match on the WM_NAME, you can use 'title' in the same way that
-- 'className' and 'resource' are used below.
--
myManageHook = composeAll
[
-- this puts new windows after the current one in the stack
-- problem is that if that window is then closed, focus goes to the next
-- window not the previous one
--insertPosition Below Newer
FS.fullscreenManageHook
, className =? "Gnome-terminal" --> doShift "1:term"
, className =? "Sublime" --> doShift "2:code"
, className =? "Sublime_text" --> doShift "2:code"
, className =? "sun-awt-X11-XFramePeer" --> doShift "4:debug" --SQL Developer and jDeveloper
, resource =? "desktop_window" --> doIgnore
, className =? "Galculator" --> doFloat
, className =? "Steam" --> doFloat
, className =? "Gimp" --> doFloat
, resource =? "gpicview" --> doFloat
, className =? "MPlayer" --> doFloat
, className =? "Pidgin" --> doShift "6:chat"
, className =? "VirtualBox" --> doShift "5:vm"
--not sure why this doesn't work
--, ( className =? "Chromium-browser" ) <&&> fmap ( isPrefixOf "Developer Tools - " ) title --> doShift "4:debug"
, className =? "Chromium-browser" --> doShift "3:web"
, className =? "Google-chrome" --> doShift "3:web"
]
------------------------------------------------------------------------
-- Layouts
-- You can specify and transform your layouts by modifying these values.
-- If you change layout bindings be sure to use 'mod-shift-space' after
-- restarting (with 'mod-q') to reset your layout state to the new
-- defaults, as xmonad preserves your old layout settings by default.
--
-- The available layouts. Note that each layout is separated by |||,
-- which denotes layout choice.
--
myLayout =
avoidStruts (
onWorkspace "6:chat" ( renamed [ Replace "chat" ] $ withIM (1%7) ( Role "buddy_list") Grid ) $
renamed [ Replace "tall-left" ] ( Tall 1 (3/100) (1/2) )
||| renamed [ Replace "tall-right" ] ( reflectHoriz( Tall 1 (3/100) (1/2) ) )
||| renamed [ Replace "wide" ] ( Mirror (Tall 1 (3/100) (1/2)) )
||| renamed [ Replace "tabs" ] ( tabbed shrinkText tabConfig )
||| renamed [ Replace "full" ] Full
-- ||| renamed [ Replace "spiral" ] ( spiral (6/7) )
)
||| renamed [ Replace "fullscreen" ] ( noBorders (FS.fullscreenFull Full) )
------------------------------------------------------------------------
-- Colors for text and backgrounds of each tab when in "Tabbed" layout.
tabConfig = defaultTheme {
activeBorderColor = C.normal C.colors,
activeTextColor = C.active C.colors,
activeColor = C.background C.colors,
inactiveBorderColor = C.normal C.colors,
inactiveTextColor = C.inactive C.colors,
inactiveColor = C.background C.colors
}
------------------------------------------------------------------------
-- Key bindings
--
-- modMask lets you specify which modkey you want to use. The default
-- is mod1Mask ("left alt"). You may also consider using mod3Mask
-- ("right alt"), which does not conflict with emacs keybindings. The
-- "windows key" is usually mod4Mask.
--
myModMask = mod4Mask
myKeys conf@(XConfig {XMonad.modMask = modMask}) = M.fromList $
----------------------------------------------------------------------
-- Custom key bindings
--
-- Start a terminal. Terminal to start is specified by myTerminal variable.
[ ((modMask .|. shiftMask, xK_Return),
spawn $ XMonad.terminal conf)
-- Lock the screen using xscreensaver.
, ((modMask .|. controlMask, xK_l),
spawn "slock")
-- Launch dmenu via yeganesh.
-- Use this to launch programs without a key binding.
, ((modMask, xK_p),
spawn ( "dmenu_run -m 1 -nb \""
++ C.background C.colors
++ "\" -nf \""
++ C.normal C.colors
++ "\" -sb \""
++ C.active C.colors
++ "\" -sf \""
++ C.background C.colors
++ "\"" )
)
-- Take a screenshot in select mode.
-- After pressing this key binding, click a window, or draw a rectangle with
-- the mouse.
, ((modMask .|. shiftMask, xK_p),
spawn "select-screenshot")
-- Take full screenshot in multi-head mode.
-- That is, take a screenshot of everything you see.
, ((modMask .|. controlMask .|. shiftMask, xK_p),
spawn "screenshot")
-- Mute volume.
, ((0, 0x1008FF12),
spawn "amixer -q set Master toggle")
-- Decrease volume.
, ((0, 0x1008FF11),
spawn "amixer -q set Master 2%- unmute")
-- Increase volume.
, ((0, 0x1008FF13),
spawn "amixer -q set Master 2%+ unmute")
-- Audio previous.
, ((0, 0x1008FF16),
spawn "")
-- Play/pause.
, ((0, 0x1008FF14),
spawn "")
-- Audio next.
, ((0, 0x1008FF17),
spawn "")
-- Eject CD tray.
, ((0, 0x1008FF2C),
spawn "eject -T")
--------------------------------------------------------------------
-- "Standard" xmonad key bindings
--
-- Close focused window.
, ((modMask .|. shiftMask, xK_c),
kill )
-- Cycle through the available layout algorithms.
, ((modMask, xK_space),
sendMessage NextLayout)
-- Reset the layouts on the current workspace to default.
, ((modMask .|. shiftMask, xK_space),
setLayout $ XMonad.layoutHook conf)
-- Resize viewed windows to the correct size.
, ((modMask, xK_n),
refresh)
-- Move focus to the next window.
, ((modMask, xK_Tab),
windows W.focusDown)
-- Move focus to the next window.
, ((modMask, xK_j),
windows W.focusUp)
-- Move focus to the previous window.
, ((modMask, xK_k),
windows W.focusDown )
-- Move focus to the master window.
, ((modMask, xK_m),
windows W.focusMaster )
-- Swap the focused window and the master window.
, ((modMask, xK_Return),
windows W.swapMaster)
-- Swap the focused window with the next window.
, ((modMask .|. shiftMask, xK_j),
windows W.swapDown )
-- Swap the focused window with the previous window.
, ((modMask .|. shiftMask, xK_k),
windows W.swapUp )
-- Shrink the master area.
, ((modMask, xK_h),
sendMessage Shrink)
-- Expand the master area.
, ((modMask, xK_l),
sendMessage Expand)
-- Push window back into tiling.
, ((modMask, xK_t),
withFocused $ windows . W.sink)
-- Increment the number of windows in the master area.
, ((modMask, xK_comma),
sendMessage (IncMasterN 1))
-- Decrement the number of windows in the master area.
, ((modMask, xK_period),
sendMessage (IncMasterN (-1)))
-- Toggle the status bar gap.
-- TODO: update this binding with avoidStruts, ((modMask, xK_b),
-- Quit xmonad.
, ((modMask .|. shiftMask, xK_q),
io (exitWith ExitSuccess))
-- Restart xmonad.
, ((modMask, xK_q),
restart "xmonad" True)
]
++
-- mod-[1..9], Switch to workspace N
-- mod-shift-[1..9], Move client to workspace N
[((m .|. modMask, k), windows $ f i)
| (i, k) <- zip (XMonad.workspaces conf) [xK_1 .. xK_9]
, (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)]]
++
--
-- mod-{w,e,r}, Switch to physical/Xinerama screens 1, 2, or 3
-- mod-shift-{w,e,r}, Move client to screen 1, 2, or 3
--
[((modMask .|. mask, key), f sc)
| (key, sc) <- zip [xK_w, xK_e, xK_r] [0..]
, (f, mask) <- [(viewScreen, 0), (sendToScreen, shiftMask)]]
------------------------------------------------------------------------
-- Mouse bindings
--
-- Focus rules
-- True if your focus should follow your mouse cursor.
myFocusFollowsMouse :: Bool
myFocusFollowsMouse = True
myMouseBindings (XConfig {XMonad.modMask = modMask}) = M.fromList $
[
-- mod-button1, Set the window to floating mode and move by dragging
((modMask, button1),
(\w -> focus w >> mouseMoveWindow w))
-- mod-button2, Raise the window to the top of the stack
, ((modMask, button2),
(\w -> focus w >> windows W.swapMaster))
-- mod-button3, Set the window to floating mode and resize by dragging
, ((modMask, button3),
(\w -> focus w >> mouseResizeWindow w))
-- you may also bind events to the mouse scroll wheel (button4 and button5)
]
------------------------------------------------------------------------
-- Status bars and logging
-- Perform an arbitrary action on each internal state change or X event.
-- See the 'DynamicLog' extension for examples.
--
-- To emulate dwm's status bar
--
-- > logHook = dynamicLogDzen
--
------------------------------------------------------------------------
myEventHook = FS.fullscreenEventHook
------------------------------------------------------------------------
-- Startup hook
-- Perform an arbitrary action each time xmonad starts or is restarted
-- with mod-q. Used by, e.g., XMonad.Layout.PerWorkspace to initialize
-- per-workspace layout choices.
--
-- By default, do nothing.
myStartupHook = return ()
------------------------------------------------------------------------
-- Run xmonad with all the defaults we set up.
--
main = do
xmproc <- spawnPipe "/usr/bin/xmobar ~/.xmonad/xmobar.hs"
xmonad
$ ewmh
$ withUrgencyHook NoUrgencyHook
$ defaults {
logHook = dynamicLogWithPP $ xmobarPP {
ppOutput = hPutStrLn xmproc
, ppTitle = xmobarColor ( C.highlight C.colors ) "" . shorten 100
, ppCurrent = xmobarColor ( C.active C.colors ) ""
, ppVisible = xmobarColor ( C.inactive C.colors ) ""
, ppUrgent = xmobarColor ( C.urgent C.colors ) "" .wrap "*" "*"
, ppSep = " "}
, manageHook = manageDocks <+> myManageHook
, startupHook = setWMName "LG3D"
}
------------------------------------------------------------------------
-- Combine it all together
-- A structure containing your configuration settings, overriding
-- fields in the default config. Any you don't override, will
-- use the defaults defined in xmonad/XMonad/Config.hs
--
-- No need to modify this.
--
defaults = defaultConfig {
-- simple stuff
terminal = myTerminal,
focusFollowsMouse = myFocusFollowsMouse,
modMask = myModMask,
workspaces = myWorkspaces,
normalBorderColor = C.normal C.colors,
focusedBorderColor = C.active C.colors,
-- key bindings
keys = myKeys,
mouseBindings = myMouseBindings,
-- hooks, layouts
layoutHook = smartBorders $ myLayout,
manageHook = myManageHook,
startupHook = myStartupHook,
handleEventHook = myEventHook
}
| justinhoward/dotfiles | modules/xmonad/installed-config/xmonad.hs | mit | 12,090 | 139 | 21 | 2,251 | 2,394 | 1,416 | 978 | 180 | 1 |
module Text.Docvim.Compile (compile) where
import Text.Docvim.AST
import Text.Docvim.Optimize
import Text.Docvim.Visitor
import Text.Docvim.Visitor.Command
import Text.Docvim.Visitor.Commands
import Text.Docvim.Visitor.Footer
import Text.Docvim.Visitor.Function
import Text.Docvim.Visitor.Functions
import Text.Docvim.Visitor.Header
import Text.Docvim.Visitor.Heading
import Text.Docvim.Visitor.Mapping
import Text.Docvim.Visitor.Mappings
import Text.Docvim.Visitor.Option
import Text.Docvim.Visitor.Options
import Text.Docvim.Visitor.Plugin
import Text.Docvim.Visitor.Section
-- | "Compile" a set of translation units into a project.
compile :: [Node] -> Node
compile ns = do
let ast = foldr ($) (Project ns) [ injectCommands
, injectFunctions
, injectMappings
, injectOptions
]
let steps = [ extract extractHeader
, extract extractPlugin
, extract extractCommands
, extract extractCommand
, extract extractMappings
, extract extractMapping
, extract extractOptions
, extract extractOption
, extract extractFunctions
, extract extractFunction
, extract extractFooter
]
let (remainder, sections) = foldl reduce (ast, []) steps
let (beginning, rest) = splitAt 1 sections
optimize $ injectTOC $ Project $ (concat . concat) [beginning, [[remainder]], rest]
where
reduce (remainder', sections') step = do
let (r', s') = step remainder'
(r', sections' ++ [s'])
| wincent/docvim | lib/Text/Docvim/Compile.hs | mit | 1,720 | 0 | 12 | 518 | 398 | 230 | 168 | 40 | 1 |
module Job.Tracking
( sendGoogleAnalyticsTracking
) where
import Import
import qualified Data.ByteString.Lazy.Char8 as C
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.UUID as UU
import qualified Data.UUID.V1 as UU
import qualified Network.HTTP.Simple as HTTP
googleAnalyticsApiEndpoint :: String
googleAnalyticsApiEndpoint = "http://www.google-analytics.com/collect"
mkTrackingPayload :: Text -> Text -> Text -> Maybe Text -> IO Text
mkTrackingPayload uaCode jobName uid content = do
let utmContent = case content of
Nothing -> ""
Just c -> "&cc=" <> c
maybeUUID <- UU.nextUUID
case maybeUUID of
Nothing -> return ""
Just uuid -> return $ "v=1&t=event&ds=backend&tid=" <> uaCode <> "&cid=" <> (UU.toText uuid) <> "&uid=" <> uid <> "&cn=" <> jobName <> "&cm=backend&ni=1" <> utmContent
trackingPostRequest :: MonadIO m => Text -> m (Either Text Text)
trackingPostRequest payload = do
let postUrl = parseRequest_ $ "POST " <> googleAnalyticsApiEndpoint
let requestPayload = C.fromStrict $ T.encodeUtf8 payload
let postRequest = HTTP.setRequestIgnoreStatus
$ HTTP.setRequestBodyLBS requestPayload postUrl
postResponse <- liftIO $ HTTP.httpLBS postRequest
let postResp = T.decodeUtf8 . C.toStrict $ HTTP.getResponseBody postResponse
case HTTP.getResponseStatusCode postResponse of
200 -> return $ Right postResp
_ -> return $ Left postResp
sendTrackingEvent :: Text -> Maybe (Entity Signup) -> Text -> Maybe Text -> HandlerT App IO ()
sendTrackingEvent uaCode maybeSignup jobName content = do
case maybeSignup of
Just (Entity signupId _) -> do
let uid = T.pack $ show signupId
payload <- liftIO $ mkTrackingPayload uaCode jobName uid content
_ <- trackingPostRequest payload
return ()
Nothing -> return ()
-- | Track the events with Google Analytics.
sendGoogleAnalyticsTracking :: Text -> JobAction -> JobValue -> HandlerT App IO ()
sendGoogleAnalyticsTracking uaCode SendActiviatonMail (JobValueUserMail mail) = do
maybeSignup <- runDB . getBy $ UniqueEmail mail
sendTrackingEvent uaCode maybeSignup "activation+mail" Nothing
sendGoogleAnalyticsTracking uaCode SendWelcomeMail (JobValueUserMail mail) = do
maybeSignup <- runDB . getBy $ UniqueEmail mail
sendTrackingEvent uaCode maybeSignup "welcome+mail" Nothing
sendGoogleAnalyticsTracking uaCode SendStepAchievedMail (JobValueStepNumber mail stepNumber) = do
maybeSignup <- runDB . getBy $ UniqueEmail mail
let step = T.pack $ show stepNumber
sendTrackingEvent uaCode maybeSignup "step+achieved" (Just step)
sendGoogleAnalyticsTracking _ _ _ = return ()
| Tehnix/campaigns | Job/Tracking.hs | mit | 2,759 | 0 | 19 | 544 | 767 | 377 | 390 | 52 | 3 |
import Data.List
import Data.Char
incletter c i = chr (ord c + i)
letter = incletter 'a'
doubles = [ [c, c] | i <- [0..25], let c = letter i ]
runs = [ [letter i, letter (i+1), letter (i+2)] | i <- [0..23] ]
noneof = ["i", "o", "l"]
increv ('z' : xs) = 'a' : increv xs
increv (c : xs) = incletter c 1 : xs
inc = reverse . increv . reverse
matches s = hasDoubles && hasRun && notBad
where hasDoubles = length (filter (`isInfixOf` s) doubles) >= 2
hasRun = any (`isInfixOf` s) runs
notBad = not $ any (`isInfixOf` s) noneof
-- Again, I actually just ran this in ghci. Outputs both of the answers.
input = "hepxcrrq"
main = putStrLn $ show $ take 2 $ filter matches $ iterate inc input
| msullivan/advent-of-code | 2015/A11a.hs | mit | 707 | 0 | 11 | 165 | 326 | 176 | 150 | 16 | 1 |
module FP15.Parsing where
import FP15.Parsing.Types()
import FP15.Parsing.Lexer()
| Ming-Tang/FP15 | src/FP15/Parsing.hs | mit | 83 | 0 | 4 | 8 | 24 | 16 | 8 | 3 | 0 |
{- shooter.hs
- This game has simple character movement with the arrow keys,
- as well as shooting simple missiles with the SpaceBar.
-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RecursiveDo #-}
{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE FlexibleContexts #-}
import Control.Concurrent (threadDelay)
import Control.Monad (forever, unless, (<=<))
import Control.Monad.Reader (MonadReader, asks)
import Control.Monad.IO.Class (MonadIO)
import Data.IORef (IORef, newIORef)
import Data.Foldable (for_)
import Hickory.Camera
import Hickory.Color
import Hickory.FRP (unionFirst, mkCoreEvents, CoreEvents(..), CoreEventGenerators)
import qualified Hickory.Graphics as H
import Hickory.Input
import Hickory.Math (Mat44, vnull, Scalar, mkTranslation, mkScale)
import Hickory.Resources (pull, readerFromIORef)
import Linear (zero, V2(..), V3(..), (^*), (!*!))
import Hickory.Types
import Linear.Metric
import Platforms.GLFW.FRP (glfwCoreEventGenerators)
import Platforms.GLFW.Utils
import Reactive.Banana ((<@))
import qualified Graphics.UI.GLFW as GLFW
import qualified Reactive.Banana as B
import qualified Reactive.Banana.Frameworks as B
import qualified Data.HashMap.Strict as Map
-- ** GAMEPLAY **
type Vec = V2 Double
-- Our game data
data Model = Model
{ playerPos :: Vec
, playerMoveDir :: Vec
, firingDirection :: Vec
, missiles :: [(Vec, Vec)]
}
-- All the possible inputs
data Msg = Fire | AddMove Vec | SubMove Vec | Tick Double | Noop
-- By default, our firingDirection is to the right
newGame :: Model
newGame = Model zero zero (V2 1 0) []
-- Change the game model by processing some input
gameStep :: Msg -> Model -> Model
gameStep msg model@Model { playerPos, firingDirection, missiles } = case msg of
Tick time -> physics time model
Fire -> model { missiles = (playerPos, firingDirection) : missiles }
AddMove dir -> adjustMoveDir dir model
SubMove dir -> adjustMoveDir (- dir) model
Noop -> model
-- Step the world forward by some small delta
physics :: Double -> Model -> Model
physics delta model@Model { playerPos, playerMoveDir, missiles } = model
{ playerPos = playerPos + (playerMoveDir ^* (delta * playerMovementSpeed))
, missiles = filter missileInBounds $
map (\(pos, dir) -> (pos + (dir ^* (delta * missileMovementSpeed)), dir)) missiles
}
-- Some gameplay constants
playerMovementSpeed :: Double
playerMovementSpeed = 100
missileMovementSpeed :: Double
missileMovementSpeed = 200
-- Pure utilities
missileInBounds :: (Vec, Vec) -> Bool
missileInBounds (pos, _) = norm pos < 500
adjustMoveDir :: Vec -> Model -> Model
adjustMoveDir dir model@Model { playerMoveDir, firingDirection } =
model { playerMoveDir = newMoveDir
, firingDirection = if vnull newMoveDir then firingDirection else newMoveDir
}
where newMoveDir = playerMoveDir + dir
-- ** RENDERING **
-- The resources used by our rendering function
data Resources = Resources
{ missileTex :: H.TexID
, vaoCache :: H.VAOCache
}
-- Set up our scene, load assets, etc.
loadResources :: String -> IO Resources
loadResources path = do
-- To draw the missiles, we also need a shader that can draw
-- textures, and the actual missile texture
solid <- H.loadSolidShader
textured <- H.loadTexturedShader
missiletex <- H.loadTexture' path ("circle.png", H.texLoadDefaults)
-- We'll use some square geometry and draw our texture on top
vaoCache <- Map.fromList <$> traverse sequence
[("square", H.mkSquareVAOObj 0.5 solid)
,("squaretex", H.mkSquareVAOObj 0.5 textured)]
pure $ Resources missiletex vaoCache
-- This function calculates a view matrix, used during rendering
calcCameraMatrix :: Size Int -> Mat44
calcCameraMatrix size@(Size w _h) =
let proj = Ortho (realToFrac w) 1 100 True
camera = Camera proj (V3 0 0 10) zero (V3 0 1 0)
in viewProjectionMatrix camera (aspectRatio size)
-- Our render function
renderGame :: (MonadIO m, MonadReader Resources m) => Size Int -> Model -> Scalar -> m ()
renderGame scrSize Model { playerPos, missiles } _gameTime = do
H.runMatrixT . H.xform (calcCameraMatrix scrSize) $ do
missileTex <- asks missileTex
tex <- pull vaoCache "squaretex"
for_ missiles \(pos, _) -> H.xform (mkTranslation pos !*! mkScale (V2 5 5)) do
H.drawVAO tex do
H.bindTextures [missileTex]
H.bindUniform "color" red
H.bindMatrix "modelMat"
pull vaoCache "square" >>= flip H.drawVAO do
H.xform (mkTranslation playerPos !*! mkScale (V2 10 10)) $ H.bindMatrix "modelMat"
H.bindUniform "color" white
-- ** INPUT **
-- Translating raw input to game input
isMoveKey :: Key -> Bool
isMoveKey key = key `elem` [Key'Up, Key'Down, Key'Left, Key'Right]
moveKeyVec :: Key -> Vec
moveKeyVec key = case key of
Key'Up -> V2 0 1
Key'Down -> V2 0 (-1)
Key'Left -> V2 (-1) 0
Key'Right -> V2 1 0
_ -> zero
procKeyDown :: Key -> Msg
procKeyDown k =
if isMoveKey k
then AddMove (moveKeyVec k)
else case k of
Key'Space -> Fire
_ -> Noop
procKeyUp :: Key -> Msg
procKeyUp k =
if isMoveKey k
then SubMove (moveKeyVec k)
else Noop
-- Build the FRP network
buildNetwork :: IORef Resources -> CoreEventGenerators -> IO ()
buildNetwork resRef evGens = do
B.actuate <=< B.compile $ mdo
coreEvents <- mkCoreEvents evGens
-- currentTime isn't currently used, but it's useful for things like animation
currentTime <- B.accumB 0 ((+) <$> eTime coreEvents)
let evs = unionFirst [ Tick <$> eTime coreEvents -- step the physics
, procKeyDown <$> keyDown coreEvents
, procKeyUp <$> keyUp coreEvents
]
-- Step the game model forward every time we get a new event
mdl <- B.accumB newGame (gameStep <$> evs)
-- every time we get a 'render' event tick, draw the screen
B.reactimate $ readerFromIORef resRef <$>
(renderGame <$> scrSizeB coreEvents <*> mdl <*> currentTime)
<@ eRender coreEvents
main :: IO ()
main = withWindow 750 750 "Demo" $ \win -> do
H.configGLState 0.125 0.125 0.125
resources <- newIORef
=<< loadResources "assets"
-- setup event generators for core input (keys, mouse clicks, and elapsed time, etc.)
(coreEvProc, evGens) <- glfwCoreEventGenerators win
-- build and run the FRP network
buildNetwork resources evGens
forever $ do
coreEvProc -- check the input buffers and generate FRP events
GLFW.swapBuffers win -- present latest drawn frame
H.clearDepth
H.clearScreen
focused <- GLFW.getWindowFocused win
-- don't consume CPU when the window isn't focused
unless focused (threadDelay 100000)
| asivitz/Hickory | Example/Shooter/shooter.hs | mit | 6,765 | 0 | 20 | 1,397 | 1,809 | 974 | 835 | -1 | -1 |
{-
Copyright (c) 2015 Nils 'bash0r' Jonsson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-}
{- |
Module : $Header$
Description : A semantic result monad.
Author : Nils 'bash0r' Jonsson
Copyright : (c) 2015 Nils 'bash0r' Jonsson
License : MIT
Maintainer : [email protected]
Stability : unstable
Portability : non-portable (Portability is untested.)
A semantic result monad.
-}
module Language.Transformation.Semantics.SemanticResult
( SemanticResult (..)
) where
import Control.Applicative
import Control.Monad
import Language.Transformation.Semantics.Class
data SemanticResult a
= Result a
| Error String
deriving (Show, Eq)
instance Functor SemanticResult where
fmap f (Result a) = (Result . f) a
fmap _ (Error m) = Error m
instance Applicative SemanticResult where
pure = Result
(Result f) <*> r = fmap f r
(Error m) <*> _ = Error m
instance Alternative SemanticResult where
empty = Error ""
l@(Result {}) <|> _ = l
(Error _ ) <|> r@(Result {}) = r
(Error l ) <|> (Error r ) = Error (l ++ "\nor " ++ r)
instance Monad SemanticResult where
return = pure
fail = Error
(Result a) >>= f = f a
(Error m) >>= _ = Error m
instance Semantics SemanticResult where
report = fail
| project-horizon/framework | src/lib/Language/Transformation/Semantics/SemanticResult.hs | mit | 2,284 | 0 | 9 | 482 | 342 | 178 | 164 | 28 | 0 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.HTMLMenuElement
(js_setCompact, setCompact, js_getCompact, getCompact,
HTMLMenuElement, castToHTMLMenuElement, gTypeHTMLMenuElement)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe "$1[\"compact\"] = $2;"
js_setCompact :: HTMLMenuElement -> Bool -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLMenuElement.compact Mozilla HTMLMenuElement.compact documentation>
setCompact :: (MonadIO m) => HTMLMenuElement -> Bool -> m ()
setCompact self val = liftIO (js_setCompact (self) val)
foreign import javascript unsafe "($1[\"compact\"] ? 1 : 0)"
js_getCompact :: HTMLMenuElement -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLMenuElement.compact Mozilla HTMLMenuElement.compact documentation>
getCompact :: (MonadIO m) => HTMLMenuElement -> m Bool
getCompact self = liftIO (js_getCompact (self)) | manyoo/ghcjs-dom | ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/HTMLMenuElement.hs | mit | 1,723 | 14 | 8 | 205 | 438 | 271 | 167 | 26 | 1 |
import Data.Char
{-------------------------------------------------------------------------------------------------
1. Nos exercícios a seguir, escreva primeiramente uma função recursiva. Em
seguida, reescreva essa função utilizando função de ordem superior. Você
pode usar as funções nativas map, filter e foldr.
-}
{- (a) pares :: [Int] -> [Int] que remove todos os elementos ímpares de uma lista. -}
pares_recursao :: [Int] -> [Int] -- Usando Recursão
pares_recursao [] = []
pares_recursao (x:xs)
| even x = x : pares_recursao xs
| otherwise = pares_recursao xs
pares_sup :: [Int] -> [Int] -- Usando ordem superior.
pares_sup x = filter even x
-- Função filter, usando genérico.
meufilter :: (a -> Bool) -> [a] -> [a]
meufilter f [] = []
meufilter f (x:xs)
| f x = x : meufilter f xs
| otherwise = meufilter f xs
-- > meufilter even [1,2,3,4,5]
-- [2,4]
{- (b) Função rm_char :: Char -> String -> String que remove todas as ocorrências de um caractere em uma string. -}
rm_char :: Char -> [Char] -> [Char] -- Recursão
rm_char letra [] = []
rm_char letra (x:xs)
| letra /= x = x : rm_char letra xs
| otherwise = rm_char letra xs
rm_char_ordem :: Char -> [Char] -> [Char] -- Ordem Superior
rm_char_ordem letra palavra = filter (letra /= ) palavra
{- (c) Função acima :: Int -> [Int] -> [Int] que remove todos os números menores ou iguais a um determinado valor. -}
acima :: Int -> [Int] -> [Int]
acima val [] = []
acima val (x:xs)
| x > val = x : acima val xs
| otherwise = acima val xs
acima_sup :: Int -> [Int] -> [Int]
acima_sup val lista_num = filter (val <) lista_num
{- (d) Função produto :: Num a=> [a] -> a que computa o produto dos números de uma lista. -}
produto :: Num a => [a] -> a
produto [] = 1
produto (x:xs) = x * produto xs
produto_f :: Num a => [a] -> a
produto_f x = foldr (*) 1 x
{- (e) Função concatena :: [String] -> String que junta uma lista de strings em uma única string. -}
concatena :: [String] -> String
concatena [] = []
concatena (x:xs) = x ++ concatena xs
concatena_f :: [String] -> String
concatena_f x = foldr (++) [] x
{-------------------------------------------------------------------------------------------------
2. Faça a função ssp que considera uma lista de inteiros e devolve a soma dos
quadrados dos elementos positivos da lista.
-}
ssd :: [Int] -> Int
ssd x = foldr (+) 0 (map (^2) (filter (>0) x))
{-------------------------------------------------------------------------------------------------
3. Defina a função sumsq que considera um inteiro n como argumento e devolve
a soma dos quadrados dos n primeiros inteiros. Ou seja:
*Main > sumsq 4
30
pois 1² + 2² + 3² + 4² = 30.
-}
sumsq :: Int -> Int
sumsq x = foldr (+) 0 (map (^2) [1..x])
{-------------------------------------------------------------------------------------------------
4. Uma função que devolva o valor da soma dos comprimentos de cada string
(elemento) da lista. Isto é, a soma total dos comprimentos da lista de entrada.
-}
somaComprimentos :: [String] -> Int
somaComprimentos l = foldr (+) 0 (map length l)
{-------------------------------------------------------------------------------------------------
5. Faça uma função que separe caracteres de números em uma string de
entrada. O retorno é uma tupla, em que no primeiro argumento esteja a
sequência de caracteres (string), e no segundo argumento uma sequência de
inteiros. Dica: Utilize isAlpha e isDigit, presentes em Data.Char.
Por exemplo:
> separa "aA29bB71"
("aAbB ", "2971")
-}
separa :: String -> (String,String)
separa str = (filter isAlpha str, filter isDigit str)
| hugonasciutti/Exercises | Haskell/Exercises/pratica8.hs | mit | 3,679 | 0 | 10 | 669 | 788 | 418 | 370 | 45 | 1 |
{- |
module: $Header$
description: Higher order logic type variables
license: MIT
maintainer: Joe Leslie-Hurd <[email protected]>
stability: provisional
portability: portable
-}
module HOL.TypeVar
where
import qualified Data.Foldable as Foldable
import Data.Set (Set)
import qualified Data.Set as Set
import HOL.Name
import HOL.Data
-------------------------------------------------------------------------------
-- Constructors and destructors
-------------------------------------------------------------------------------
mk :: Name -> TypeVar
mk = TypeVar
dest :: TypeVar -> Name
dest (TypeVar n) = n
eqName :: Name -> TypeVar -> Bool
eqName n (TypeVar m) = m == n
-------------------------------------------------------------------------------
-- Named type variables (used in standard axioms)
-------------------------------------------------------------------------------
alpha :: TypeVar
alpha = mk (mkGlobal "A")
beta :: TypeVar
beta = mk (mkGlobal "B")
-------------------------------------------------------------------------------
-- Collecting type variables
-------------------------------------------------------------------------------
class HasVars a where
vars :: a -> Set TypeVar
instance HasVars TypeVar where
vars = Set.singleton
instance HasVars a => HasVars [a] where
vars = Foldable.foldMap vars
instance HasVars a => HasVars (Set a) where
vars = Foldable.foldMap vars
instance HasVars TypeData where
vars (VarType v) = vars v
vars (OpType _ tys) = vars tys
instance HasVars Type where
vars (Type _ _ _ vs) = vs
instance HasVars Var where
vars (Var _ ty) = vars ty
instance HasVars TermData where
vars (ConstTerm _ ty) = vars ty
vars (VarTerm v) = vars v
vars (AppTerm f x) = Set.union (vars f) (vars x)
vars (AbsTerm v b) = Set.union (vars v) (vars b)
instance HasVars Term where
vars (Term _ _ _ _ vs _) = vs
| gilith/hol | src/HOL/TypeVar.hs | mit | 1,878 | 0 | 8 | 289 | 500 | 261 | 239 | 38 | 1 |
{-# LANGUAGE BangPatterns
, FlexibleContexts
, TypeFamilies
, MultiParamTypeClasses
, FunctionalDependencies
, TypeSynonymInstances
, FlexibleInstances #-}
module RobotVision.ImageRep.Class
( Expandable (..)
, Shrinkable (..)
, GreyImage
, RGBImage
, Grey, GreyD, GreyU, GreyF, GreyI, GreyDW, GreyUI
, RGB, RGBD, RGBU, RGBF, RGBI, RGBDW
, Image
, ToGrey (..)
, toRGB
) where
import Data.Array.Repa
import qualified Data.Array.Repa.Repr.Unboxed as U
import Data.Array.Repa.Repr.ForeignPtr as F
import Data.Word
import Prelude hiding (map)
import Data.Convertible
import qualified Vision.Image as V
import qualified Vision.Primitive as P
test = id
-- Image Representation for this project is limited to, strictly, RGB, Grey, and HSV Word8, Int, and Float
-- The only representations that are permissible in memory are the Word8 ones. Because Haskell can inline
-- the conversion functions and this library makes use of Repa's delayed computation capabilities, the conversions
-- happen as needed, in place, but are never stored to avoid type change induced copying.
-- To avoid confusing types, all functions will be explicit. Generalizing types does not (I think) make sense
-- in this context. All computation itself will be generalized, but types will be explicit.
--- Origin is at bottom
-- (y,0) (y,x)
-- (0,0) (0,x)
type Grey r e = Array r DIM2 e
type GreyD e = Grey D e
type GreyU = Grey U Word8
type GreyF = Grey F Word8
type RGB r e = Array r DIM3 e
type RGBD e = RGB D e
type RGBU = RGB U Word8
type RGBF = RGB F Word8
type GreyI = Grey D Int
type RGBI = RGB D Int
type GreyDW = Grey D Word8
type RGBDW = RGB D Word8
type GreyUI = Grey U Int
data GreyImage = GreyI | GreyU | GreyF | GreyDW | GreyUI
data RGBImage = RGBI | RGBU | RGBF | RGBDW
data Image = GreyImage | RGBImage
class Expandable a b | a -> b where
expand :: a -> b
instance Expandable GreyU GreyI where
expand = map fromIntegral
{-# INLINE expand #-}
instance Expandable GreyUI GreyI where
expand = map id
{-# INLINE expand #-}
instance Expandable GreyF GreyI where
expand = map fromIntegral
{-# INLINE expand #-}
instance Expandable GreyDW GreyI where
expand = map fromIntegral
{-# INLINE expand #-}
instance Expandable GreyI GreyI where
expand = id
{-# INLINE expand #-}
instance Expandable RGBU RGBI where
expand = map fromIntegral
{-# INLINE expand #-}
instance Expandable RGBF RGBI where
expand = map fromIntegral
{-# INLINE expand #-}
instance Expandable RGBDW RGBI where
expand = map fromIntegral
{-# INLINE expand #-}
instance Expandable RGBI RGBI where
expand = id
{-# INLINE expand #-}
class Shrinkable a b | a -> b where
shrink :: a -> b
instance Shrinkable GreyI GreyDW where
shrink = map (fromIntegral . max 0 . min 255)
{-# INLINE shrink #-}
instance Shrinkable GreyUI GreyDW where
shrink = map (fromIntegral . max 0 . min 255)
{-# INLINE shrink #-}
instance Shrinkable GreyDW GreyDW where
shrink = id
{-# INLINE shrink #-}
instance Shrinkable RGBI RGBDW where
shrink = map (fromIntegral . max 0 . min 255)
{-# INLINE shrink #-}
instance Shrinkable RGBDW RGBDW where
shrink = id
{-# INLINE shrink #-}
class ToGrey a b where
toGrey :: a -> b
instance ToGrey RGBDW GreyDW where
toGrey = combineImage rgbToGrey
{-# INLINE toGrey #-}
instance ToGrey GreyDW GreyDW where
toGrey = id
{-# INLINE toGrey #-}
-- Takes a function to convert one rgb pixel into one grey pixel
combineImage :: (Word8 -> Word8 -> Word8 -> Word8) -> RGBDW -> GreyDW
combineImage f arr = let sh@(Z :. y :. x :. _) = extent arr in fromFunction (Z :. y :. x) g
where
g (Z :. i :. j) = f r g b
where
r = arr ! (Z :. i :. j :. 0)
g = arr ! (Z :. i :. j :. 1)
b = arr ! (Z :. i :. j :. 2)
{-# INLINE combineImage #-}
rgbToGrey :: Word8 -> Word8 -> Word8 -> Word8
rgbToGrey !r !g !b =
let
rd = fromIntegral r :: Double
gd = fromIntegral g :: Double
bd = fromIntegral b :: Double
in ceiling $ 0.21 * rd + 0.71 * gd + 0.07 * bd
{-# INLINE rgbToGrey #-}
-- Convert from RGBA or RGB (does nothing in that case)
toRGB :: (Source r e, Num e) => Array r DIM3 e -> Array D DIM3 e
toRGB img =
let (Z :. width :. length :. depth) = extent img
in case depth of
3 -> map id img
4 -> fromFunction (Z :. width :. length :. 3) f
where
f (Z :. j :. i :. k) = img ! (Z :. j :. i :. k) | eklinkhammer/haskell-vision | RobotVision/ImageRep/Class.hs | mit | 4,637 | 0 | 14 | 1,220 | 1,219 | 674 | 545 | 118 | 2 |
-----------------------------------------------------------------------------
-- |
-- Module : Postgis.Simple
-- Copyright : (c) igor720
-- License : MIT
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Reexports "Postgis.Simple.Internal" and "Postgis.Simple.Field.Default" modules.
--
-- Except for the import of this module and "Database.PostgreSQL.Simple"
-- you may also import "Postgis.Simple.Types.Default" and plainly use its types.
--
-- If you have some beloved old legacy data types and want to escape type convertions.
-- Then you should manualy create
-- instances of GeoData and Geometry type classes similar to those defined in "Postgis.Simple.Types.Default".
-- Here we will give an example of declarations that can cause your data to work with Postgis.
-- Let's assume you have polygons in nested lists and your points are latitude-longitude pairs.
--
-- @
-- type MySRID = Int
-- data LatLon = LatLon Double Double deriving Show
-- newtype Poly = Poly [[LatLon]] deriving Show -- just use newtype
-- @
--
-- Then we will make additional declarations.
--
-- @
-- import Control.Monad
-- import Database.PostgreSQL.Simple.ToField
-- import Database.PostgreSQL.Simple.FromField
--
-- data MyGPoly = MyGPoly (Maybe MySRID) Poly deriving Show
--
-- instance GeoData Poly where
-- hasM (Poly _) = False
-- hasZ (Poly _) = False
-- geoType _ = pgisPolygon
--
-- instance Geometry MyGPoly where
-- putGeometry (MyGPoly s pg@(Poly rs)) = do
-- putHeader s pg
-- putChainLen $ length rs
-- mapM_ putChain rs
-- getGeometry = do
-- h <- getHeaderPre
-- let geo gt
-- | gt==pgisPolygon = mkGeom h MyGPoly getPolygon
-- | otherwise = error $ "geometry type is not yet implemented: "++show gt
-- geo $ lookGeoType h
--
-- putChain :: Putter [LatLon]
-- putChain r = do
-- putChainLen $ length r
-- mapM_ (\\(LatLon y x) -> putPoint (x, y, Nothing, Nothing)) r
--
-- getChain :: Getter [LatLon]
-- getChain = getChainLen >>= (\`replicateM\` getPoint) >>= mapM (\\(x, y, _, _) -> return $ LatLon y x)
--
-- getPolygon :: Getter Poly
-- getPolygon = skipHeader >> Poly \<$> (getChainLen >>= (\`replicateM\` getChain))
--
-- instance ToField MyGPoly where
-- toField = toFieldDefault
--
-- instance FromField MyGPoly where
-- fromField = fromFieldDefault
-- @
--
-- Your app module may look like following.
--
-- @
-- import Database.PostgreSQL.Simple
-- import Postgis.Simple
--
-- {..above declarations here or in a separate module..}
--
-- main :: IO ()
-- main = do
-- conn <- connectPostgreSQL "..."
-- let srid = Just 4326
-- ring = [LatLon 1 2, LatLon 1.5 2.5, LatLon 2.5 3, LatLon 1 2]
-- pl = MyGPoly srid (Poly [ring, ring])
-- _ <- execute conn "INSERT INTO t1 (name, geom) VALUES (?, ?)" ("polygon"::String, pl)
-- a <- query_ conn "select * from t1 LIMIT 1" :: IO [(String, MyGPoly)]
-- print a
-- @
-----------------------------------------------------------------------------
module Postgis.Simple (
module Postgis.Simple.Internal
, module Postgis.Simple.Field.Default
) where
import Postgis.Simple.Internal
import Postgis.Simple.Field.Default
| igor720/postgis-simple | src/Postgis/Simple.hs | mit | 3,308 | 0 | 5 | 694 | 126 | 115 | 11 | 5 | 0 |
module C.Parser (parseExpr) where
import C.Expr
import Text.Parsec
import Text.Parsec.Expr
import Text.Parsec.String (Parser)
import Text.Parsec.Language (javaStyle)
import qualified Text.Parsec.Token as Token
import Control.Monad
import Control.Applicative ((<$>), (<*>))
import System.Environment
import Numeric
-- Lexer
lexer :: Token.TokenParser ()
lexer = Token.makeTokenParser style
where style = javaStyle {
Token.opStart = oneOf "+-*/=",
Token.reservedNames = ["int"]
}
integer :: Parser Integer
integer = Token.integer lexer
symbol :: String -> Parser String
symbol = Token.symbol lexer
parens :: Parser a -> Parser a
parens = Token.parens lexer
braces :: Parser a -> Parser a
braces = Token.braces lexer
semi :: Parser String
semi = Token.semi lexer
comma :: Parser String
comma = Token.comma lexer
reserved :: String -> Parser ()
reserved = Token.reserved lexer
reservedOp :: String -> Parser ()
reservedOp = Token.reservedOp lexer
operator :: Parser String
operator = Token.operator lexer
identifier :: Parser String
identifier = Token.identifier lexer
commaSep :: Parser a -> Parser [a]
commaSep = Token.commaSep lexer
semiSep :: Parser a -> Parser [a]
semiSep = Token.semiSep lexer
whiteSpace :: Parser ()
whiteSpace = Token.whiteSpace lexer
stringLiteral :: Parser String
stringLiteral = Token.stringLiteral lexer
varTypeQualifier :: Parser DataType
varTypeQualifier = do
tq <- choice [
try $ symbol "uint8",
try $ symbol "uint16"
]
-- tq <- symbol "uint" >>= (symbol "8" <|> symbol "16")
return $ typeOf tq
where typeOf "uint8" = Uint8
typeOf "uint16" = Uint16
typeQualifier :: Parser DataType
typeQualifier = varTypeQualifier <|> do
tq <- symbol "void"
return Void
-- Parser
num :: Parser Expr
num = do
x <- integer
return $ Num (fromInteger x)
cstring :: Parser Expr
cstring = String `fmap` stringLiteral
funcDef :: Parser Expr
funcDef = do
dataType <- typeQualifier
name <- identifier
args <- parens $ varDef `sepBy` comma
body <- braces $ many statement
return $ FuncDef name dataType args body
varDef :: Parser Expr
varDef = do
dataType <- varTypeQualifier
name <- identifier
return $ VarDef name dataType
var :: Parser Expr
var = do
name <- identifier
return $ Var name
asm :: Parser Expr
asm = do
symbol "asm"
body <- braces $ many $ noneOf "{}"
return $ Asm body
varAssign :: Parser Expr
varAssign = do
v <- var
symbol "="
val <- expr
return $ assignExpr v val
mathOp :: Parser (Expr -> Expr -> Expr)
mathOp = do
op <- operator
return $ case op of
"+" -> addExpr
"-" -> subExpr
"*" -> mulExpr
"/" -> divExpr
binOp :: Parser Expr
binOp = chainl1 (try funcCall <|> try var <|> num <|> parens expr) mathOp
funcCall :: Parser Expr
funcCall = do
name <- identifier
args <- parens $ expr `sepBy` comma
return $ FuncCall name args
statement :: Parser Expr
statement = try asm <|> do
xpr <- expr
semi
return xpr
expr :: Parser Expr
expr = try varDef
<|> try varAssign
<|> try funcCall
<|> try binOp
<|> try var
<|> num
<|> cstring
<|> parens expr
topLevelStatement :: Parser Expr
topLevelStatement = try funcDef
<|> do var <- varDef
semi
return var
parseExpr :: String -> [Expr]
parseExpr t =
case parse (many1 $ whiteSpace >> topLevelStatement) "stdin" t of
Left err -> error (show err)
Right ast -> ast
| unknownloner/calccomp | C/Parser.hs | mit | 3,627 | 0 | 12 | 939 | 1,199 | 596 | 603 | 128 | 4 |
module Sudoku.Types (Cell, House, Value, Options,
cells, fromInt, diff, isExpandable,
isAssigned, isEmpty, expand) where
import Data.List ((\\))
type Cell = Int
type House = [Cell]
-- I use this to map/iterate over a Board without the need to use a for/while loop
cells :: [Cell]
cells = [0..80]
-------
-- Use a data type instead of integers, to avoid ending up with wrong values in a cell
data Value = One | Two | Three | Four | Five | Six | Seven | Eight | Nine deriving (Eq, Ord)
-- All possible possibleCellValues
possibleCellValues :: [Value]
possibleCellValues = [One, Two, Three, Four, Five, Six, Seven, Eight, Nine]
instance Enum Value where
toEnum n = possibleCellValues !! (n-1)
fromEnum e = el possibleCellValues e 1
where
el (v:vs) w n
| v == w = n
| otherwise = el vs w (n+1)
instance Show Value where
show e = show $ fromEnum e
-- Use a datatype to represent the possible values a cell can take
-- A sudoku board will be solve if all cells have only one possible value (that follows the rules)
-- and will be impossible to solve if one of the cells have empty options
data Options = Options [Value] deriving Eq
instance Show Options where
show (Options []) = "⊥"
show (Options [n]) = show n
show (Options xs) = nums !! ((length xs) - 1)
where
nums = ["", "B", "C", "D", "E", "F", "G", "H", "I"]
fromInt :: Int -> Options
fromInt 0 = Options possibleCellValues
fromInt n = Options [toEnum n]
diff :: Options -> Options -> Options
(Options vs) `diff` (Options ws) = Options $ vs \\ ws
isEmpty :: Options -> Bool
isEmpty (Options []) = True
isEmpty _ = False
isAssigned :: Options -> Bool
isAssigned (Options [_]) = True
isAssigned _ = False
isExpandable :: Options -> Bool
isExpandable (Options []) = False
isExpandable (Options [_]) = False
isExpandable _ = True
expand :: Options -> [Options]
expand (Options vs) = map builder vs
where
builder v = Options [v]
| oforero/sudoku | haskell/src/Sudoku/Types.hs | mit | 2,054 | 0 | 11 | 521 | 665 | 369 | 296 | 43 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
import Control.Monad.Trans.Resource (runResourceT)
import Control.Monad.Logger (runStderrLoggingT)
import Database.Persist.Sqlite
import Network.HTTP.Client.Conduit (newManager)
import Test.Hspec (hspec)
import Yesod
import Yesod.Auth.HashDB (setPassword)
#ifndef STANDALONE
import IntegrationTest
#endif
import TestSite
main :: IO ()
main = runStderrLoggingT $ withSqliteConn ":memory:" $ \conn -> liftIO $ do
runResourceT $ flip runSqlConn conn $ do
runMigration migrateAll
validUser <- setPassword "MyPassword" $ User "paul" Nothing
insert_ validUser
mgr <- newManager
#ifdef STANDALONE
-- Run as a stand-alone server - see the cabal file in this directory
warp 3000 $ App mgr conn
#else
-- Otherwise run the tests
hspec $ withApp (App mgr conn) integrationSpec
#endif
| paul-rouse/yesod-auth-hashdb | test/integration.hs | mit | 949 | 0 | 15 | 229 | 184 | 100 | 84 | 19 | 1 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
import Prelude (Num(..), Show(..), Int, Char, String, undefined)
-- Some basic types to illustrate constructors
data Void
data Unit = MkUnit
data Bool = False | True deriving Show
data Weight = MkWeight Int
-- Canonical ADTs
data Pair a b = Pair a b
data Either a b = Left a | Right b
-- data Maybe a = Nothing | Just a
type Maybe a = Either Unit a
data Identity a = Identity a
data Const a b = Const a
-- Recursive data types
data Nat = Z | S Nat
data List a = Empty | Cons a (List a)
deriving Show
append :: List a -> List a -> List a
append Empty l2 = l2
append (Cons x l1) l2 = Cons x (append l1 l2)
-- This is an incorrect definition of append which compiles and can incorrectly
-- pass as "good" behaviour. Thus we need to consider append to be an axiom.
--append Empty l2 = case l2 of
-- Empty -> l2
-- Cons x _ -> Cons x l2
class Eq a where
(==) :: a -> a -> Bool
instance Eq Bool where
True == True = True
False == False = True
_ == _ = False
instance Eq Nat where
Z == Z = True
S n1 == S n2 = n1 == n2
_ == _ = False
data Z
data S n
class Card n where
instance Card Z where
instance Card n => Card (S n) where
type family AddNat x y
type instance AddNat Z y = y
type instance AddNat (S x) y = AddNat x (S y)
newtype Vector n a = Vector { fromVect :: List a }
deriving Show
vnil :: Vector Z a
vnil = Vector Empty
vcons :: Card n => a -> Vector n a -> Vector (S n) a
vcons x (Vector xs) = Vector (x `Cons` xs)
vhead :: Card n => Vector (S n) a -> a
vhead (Vector (Cons x _)) = x
vtail :: Card n => Vector (S n) a -> Vector n a
vtail (Vector (Cons _ xs)) = Vector xs
vappend :: Card n => Vector n a -> Vector m a -> Vector (AddNat n m) a
vappend (Vector l1) (Vector l2) = Vector (l1 `append` l2)
| spyked/slides | ht-revisited/examples/ref-examples.hs | cc0-1.0 | 1,833 | 0 | 10 | 461 | 731 | 389 | 342 | -1 | -1 |
module Settings where
import Prelude
import Text.Shakespeare.Text (st)
import Language.Haskell.TH.Syntax
import Database.Persist.MySQL (MySQLConf)
import Yesod.Default.Config
import Yesod.Default.Util
import Data.Text (Text)
import Data.Yaml
import Control.Applicative
import Settings.Development
import Data.Default (def)
import Text.Hamlet
type PersistConf = MySQLConf
-- | The location of static files on the system.
staticDir :: FilePath
staticDir = "static"
-- | The base URL for static files.
-- A powerful optimization can be serving static files from a separate
-- domain name. This allows you to use a web server optimized for static
-- files, more easily set expires and cache values, and avoid possibly
-- costly transference of cookies on static files. For more information,
-- please see:
-- http://code.google.com/speed/page-speed/docs/request.html#ServeFromCookielessDomain
--
-- If you change the resource pattern for StaticR in Foundation.hs, you will
-- have to make a corresponding change here.
--
-- To see how this value is used, see urlRenderOverride in Foundation.hs
staticRoot :: AppConfig DefaultEnv x -> Text
staticRoot conf = [st|#{appRoot conf}/static|]
-- | Settings for 'widgetFile', such as which template languages to support and
-- default Hamlet settings.
--
-- For more information on modifying behavior, see:
--
-- https://github.com/yesodweb/yesod/wiki/Overriding-widgetFile
widgetFileSettings :: WidgetFileSettings
widgetFileSettings = def
{ wfsHamletSettings = defaultHamletSettings
{ hamletNewlines = NoNewlines
}
}
widgetFile :: String -> Q Exp
widgetFile = (if development then widgetFileReload
else widgetFileNoReload)
widgetFileSettings
data Extra = Extra
{ extraCopyright :: Text
, extraAnalytics :: Maybe Text -- ^ Google Analytics
, extraLanguages :: [Text]
} deriving Show
parseExtra :: DefaultEnv -> Object -> Parser Extra
parseExtra _ o = Extra
<$> o .: "copyright"
<*> o .:? "analytics"
<*> o .: "languages"
| marcellussiegburg/autotool | yesod/Settings.hs | gpl-2.0 | 2,067 | 0 | 10 | 377 | 293 | 181 | 112 | -1 | -1 |
{-# LANGUAGE CPP, ScopedTypeVariables #-}
{-
Copyright (C) 2014 Matthew Pickering <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
module Text.TeXMath.Shared
( getMMLType
, getTextType
, getLaTeXTextCommand
, getScalerCommand
, getScalerValue
, scalers
, getSpaceWidth
, getSpaceChars
, getDiacriticalCommand
, getDiacriticalCons
, diacriticals
, getOperator
, readLength
, fixTree
, isEmpty
, empty
) where
import Text.TeXMath.Types
import Text.TeXMath.TeX
import qualified Data.Map as M
import Data.Maybe (fromMaybe)
import Data.Ratio ((%))
import Data.List (sort)
import Control.Applicative ((<$>), (<*>))
import Control.Monad (guard)
import Text.Parsec (Parsec, parse, getInput, digit, char, many1, option)
import Data.Generics (everywhere, mkT)
-- As we constuct from the bottom up, this situation can occur.
removeNesting :: Exp -> Exp
removeNesting (EDelimited o c [Right (EDelimited "" "" xs)]) = EDelimited o c xs
removeNesting (EDelimited "" "" [x]) = either (ESymbol Ord) id x
removeNesting (EGrouped [x]) = x
removeNesting x = x
removeEmpty :: [Exp] -> [Exp]
removeEmpty xs = filter (not . isEmpty) xs
-- | An empty group of expressions
empty :: Exp
empty = EGrouped []
-- | Test to see whether an expression is @empty@.
isEmpty :: Exp -> Bool
isEmpty (EGrouped []) = True
isEmpty _ = False
-- | Walks over a tree of expressions, removing empty expressions, and
-- fixing delimited expressions with no delimiters and unnecessarily
-- grouped expressions.
fixTree :: Exp -> Exp
fixTree = everywhere (mkT removeNesting) . everywhere (mkT removeEmpty)
-- | Maps TextType to the corresponding MathML mathvariant
getMMLType :: TextType -> String
getMMLType t = fromMaybe "normal" (fst <$> M.lookup t textTypesMap)
-- | Maps TextType to corresponding LaTeX command
getLaTeXTextCommand :: Env -> TextType -> String
getLaTeXTextCommand e t =
let textCmd = fromMaybe "\\mathrm"
(snd <$> M.lookup t textTypesMap) in
if textPackage textCmd e
then textCmd
else fromMaybe "\\mathrm" (lookup textCmd alts)
-- | Maps MathML mathvariant to the corresponing TextType
getTextType :: String -> TextType
getTextType s = fromMaybe TextNormal (M.lookup s revTextTypesMap)
-- | Maps a LaTeX scaling command to the percentage scaling
getScalerCommand :: Rational -> Maybe String
getScalerCommand width =
case sort [ (w, cmd) | (cmd, w) <- scalers, w >= width ] of
((_,cmd):_) -> Just cmd
_ -> Nothing
-- note, we don't use a Map here because we need the first
-- match: \Big, not \Bigr
-- | Gets percentage scaling from LaTeX scaling command
getScalerValue :: String -> Maybe Rational
getScalerValue command = lookup command scalers
-- | Returns the correct constructor given a LaTeX command
getDiacriticalCons :: String -> Maybe (Exp -> Exp)
getDiacriticalCons command =
f <$> M.lookup command diaMap
where
diaMap = M.fromList (reverseKeys diacriticals)
f s e = (if command `elem` under
then EUnder False
else EOver False) e (ESymbol Accent s)
-- | Given a diacritical mark, returns the corresponding LaTeX command
getDiacriticalCommand :: Position -> String -> Maybe String
getDiacriticalCommand pos symbol = do
command <- M.lookup symbol diaMap
guard (not $ command `elem` unavailable)
let below = command `elem` under
case pos of
Under -> if below then Just command else Nothing
Over -> if not below then Just command else Nothing
where
diaMap = M.fromList diacriticals
-- Operator Table
getOperator :: Exp -> Maybe TeX
getOperator op = fmap ControlSeq $ lookup op operators
operators :: [(Exp, String)]
operators =
[ (EMathOperator "arccos", "\\arccos")
, (EMathOperator "arcsin", "\\arcsin")
, (EMathOperator "arctan", "\\arctan")
, (EMathOperator "arg", "\\arg")
, (EMathOperator "cos", "\\cos")
, (EMathOperator "cosh", "\\cosh")
, (EMathOperator "cot", "\\cot")
, (EMathOperator "coth", "\\coth")
, (EMathOperator "csc", "\\csc")
, (EMathOperator "deg", "\\deg")
, (EMathOperator "det", "\\det")
, (EMathOperator "dim", "\\dim")
, (EMathOperator "exp", "\\exp")
, (EMathOperator "gcd", "\\gcd")
, (EMathOperator "hom", "\\hom")
, (EMathOperator "inf", "\\inf")
, (EMathOperator "ker", "\\ker")
, (EMathOperator "lg", "\\lg")
, (EMathOperator "lim", "\\lim")
, (EMathOperator "liminf", "\\liminf")
, (EMathOperator "limsup", "\\limsup")
, (EMathOperator "ln", "\\ln")
, (EMathOperator "log", "\\log")
, (EMathOperator "max", "\\max")
, (EMathOperator "min", "\\min")
, (EMathOperator "Pr", "\\Pr")
, (EMathOperator "sec", "\\sec")
, (EMathOperator "sin", "\\sin")
, (EMathOperator "sinh", "\\sinh")
, (EMathOperator "sup", "\\sup")
, (EMathOperator "tan", "\\tan")
, (EMathOperator "tanh", "\\tanh") ]
-- | Attempts to convert a string into
readLength :: String -> Maybe Rational
readLength s = do
(n, unit) <- case (parse parseLength "" s) of
Left _ -> Nothing
Right v -> Just v
(n *) <$> unitToMultiplier unit
parseLength :: Parsec String () (Rational, String)
parseLength = do
neg <- option "" ((:[]) <$> char '-')
dec <- many1 digit
frac <- option "" ((:) <$> char '.' <*> many1 digit)
unit <- getInput
-- This is safe as dec and frac must be a double of some kind
let [(n :: Double, [])] = reads (neg ++ dec ++ frac) :: [(Double, String)]
return (round (n * 18) % 18, unit)
reverseKeys :: [(a, b)] -> [(b, a)]
reverseKeys = map (\(k,v) -> (v, k))
textTypesMap :: M.Map TextType (String, String)
textTypesMap = M.fromList textTypes
revTextTypesMap :: M.Map String TextType
revTextTypesMap = M.fromList $ map (\(k, (v,_)) -> (v,k)) textTypes
--TextType to (MathML, LaTeX)
textTypes :: [(TextType, (String, String))]
textTypes =
[ ( TextNormal , ("normal", "\\mathrm"))
, ( TextBold , ("bold", "\\mathbf"))
, ( TextItalic , ("italic","\\mathit"))
, ( TextMonospace , ("monospace","\\mathtt"))
, ( TextSansSerif , ("sans-serif","\\mathsf"))
, ( TextDoubleStruck , ("double-struck","\\mathbb"))
, ( TextScript , ("script","\\mathcal"))
, ( TextFraktur , ("fraktur","\\mathfrak"))
, ( TextBoldItalic , ("bold-italic","\\mathbfit"))
, ( TextSansSerifBold , ("bold-sans-serif","\\mathbfsfup"))
, ( TextSansSerifBoldItalic , ("sans-serif-bold-italic","\\mathbfsfit"))
, ( TextBoldScript , ("bold-script","\\mathbfscr"))
, ( TextBoldFraktur , ("bold-fraktur","\\mathbffrak"))
, ( TextSansSerifItalic , ("sans-serif-italic","\\mathsfit")) ]
unicodeMath, base :: [String]
unicodeMath = ["\\mathbfit", "\\mathbfsfup", "\\mathbfsfit", "\\mathbfscr", "\\mathbffrak", "\\mathsfit"]
base = ["\\mathbb", "\\mathrm", "\\mathbf", "\\mathit", "\\mathsf", "\\mathtt", "\\mathfrak", "\\mathcal"]
alts :: [(String, String)]
alts = [ ("\\mathbfit", "\\mathbf"), ("\\mathbfsfup", "\\mathbf"), ("\\mathbfsfit", "\\mathbf")
, ("\\mathbfscr", "\\mathcal"), ("\\mathbffrak", "\\mathfrak"), ("\\mathsfit", "\\mathsf")]
textPackage :: String -> [String] -> Bool
textPackage s e
| s `elem` unicodeMath = "unicode-math" `elem` e
| s `elem` base = True
| otherwise = True
-- | Mapping between LaTeX scaling commands and the scaling factor
scalers :: [(String, Rational)]
scalers =
[ ("\\bigg", widthbigg)
, ("\\Bigg", widthBigg)
, ("\\big", widthbig)
, ("\\Big", widthBig)
, ("\\biggr", widthbigg)
, ("\\Biggr", widthBigg)
, ("\\bigr", widthbig)
, ("\\Bigr", widthBig)
, ("\\biggl", widthbigg)
, ("\\Biggl", widthBigg)
, ("\\bigl", widthbig)]
where widthbig = 6 / 5
widthBig = 9 / 5
widthbigg = 12 / 5
widthBigg = 3
-- | Returns the space width for a unicode space character, or Nothing.
getSpaceWidth :: Char -> Maybe Rational
getSpaceWidth ' ' = Just (4/18)
getSpaceWidth '\xA0' = Just (4/18)
getSpaceWidth '\x2000' = Just (1/2)
getSpaceWidth '\x2001' = Just 1
getSpaceWidth '\x2002' = Just (1/2)
getSpaceWidth '\x2003' = Just 1
getSpaceWidth '\x2004' = Just (1/3)
getSpaceWidth '\x2005' = Just (4/18)
getSpaceWidth '\x2006' = Just (1/6)
getSpaceWidth '\x2007' = Just (1/3) -- ? width of a digit
getSpaceWidth '\x2008' = Just (1/6) -- ? width of a period
getSpaceWidth '\x2009' = Just (1/6)
getSpaceWidth '\x200A' = Just (1/9)
getSpaceWidth '\x200B' = Just 0
getSpaceWidth '\x202F' = Just (3/18)
getSpaceWidth '\x205F' = Just (4/18)
getSpaceWidth _ = Nothing
-- | Returns the sequence of unicode space characters closest to the
-- specified width.
getSpaceChars :: Rational -> [Char]
getSpaceChars n =
case n of
_ | n < 0 -> "\x200B" -- no negative space chars in unicode
| n <= 2/18 -> "\x200A"
| n <= 3/18 -> "\x2006"
| n <= 4/18 -> "\xA0" -- could also be "\x2005"
| n <= 5/18 -> "\x2005"
| n <= 7/18 -> "\x2004"
| n <= 9/18 -> "\x2000"
| n < 1 -> '\x2000' : getSpaceChars (n - (1/2))
| n == 1 -> "\x2001"
| otherwise -> '\x2001' : getSpaceChars (n - 1)
-- Accents which go under the character
under :: [String]
under = ["\\underbrace", "\\underline", "\\underbar", "\\underbracket"]
-- We want to parse these but we can't represent them in LaTeX
unavailable :: [String]
unavailable = ["\\overbracket", "\\underbracket"]
-- | Mapping between unicode combining character and LaTeX accent command
diacriticals :: [(String, String)]
diacriticals =
[ ("\x00B4", "\\acute")
, (("\x0060", "\\grave"))
, (("\x02D8", "\\breve"))
, (("\x02C7", "\\check"))
, (("\x307", "\\dot"))
, (("\x308", "\\ddot"))
, (("\x20DB", "\\dddot"))
, (("\x20DC", "\\ddddot"))
, (("\x00B0", "\\mathring"))
, (("\x20D7", "\\vec"))
, (("\x20D7", "\\overrightarrow"))
, (("\x20D6", "\\overleftarrow"))
, (("\x005E", "\\hat"))
, (("\x0302", "\\widehat"))
, (("\x02C6", "\\widehat"))
, (("\x0303", "\\tilde"))
, (("\x02DC", "\\widetilde"))
, (("\x203E", "\\bar"))
, (("\x23DE", "\\overbrace"))
, (("\xFE37", "\\overbrace"))
, (("\x23B4", "\\overbracket")) -- Only availible in mathtools
, (("\x00AF", "\\overline"))
, (("\x23DF", "\\underbrace"))
, (("\xFE38", "\\underbrace"))
, (("\x23B5", "\\underbracket")) -- mathtools
, (("\x0332", "\\underline"))
, (("\x0333", "\\underbar"))
]
-- Converts unit to multiplier to reach em
unitToMultiplier :: String -> Maybe Rational
unitToMultiplier s = lookup s units
where
units =
[ ( "pt" , 10)
, ( "mm" , (351/10))
, ( "cm" , (35/100))
, ( "in" , (14/100))
, ( "ex" , (232/100))
, ( "em" , 1)
, ( "mu" , 18)
, ( "dd" , (93/100))
, ( "bp" , (996/1000))
, ( "pc" , (83/100)) ]
| beni55/texmath | src/Text/TeXMath/Shared.hs | gpl-2.0 | 12,387 | 0 | 14 | 3,273 | 3,406 | 1,958 | 1,448 | 253 | 4 |
{-# LANGUAGE TemplateHaskell #-}
module HEphem.NGCParser where
import Data.FileEmbed
import Data.Maybe
import Data.String
import HEphem.Data
import HEphem.ParserUtil
import Text.ParserCombinators.ReadP
import Text.Read (readMaybe)
readMaybeFloatWithComma :: String -> Maybe Float
readMaybeFloatWithComma = readMaybe . sanitize
where
sanitize = map (\c -> if c == ',' then '.' else c)
ngcobjecttext :: IsString a => a
ngcobjecttext = $(embedStringFile "ngc-ic2000/ngc-ic2000.csv")
ngcObjectList :: [NGCObject]
ngcObjectList = mapMaybe readNGCObject (lines ngcobjecttext)
readRecord :: String -> [String]
readRecord = fst . last . readP_to_S p
where
p = sepBy (many (satisfy (/='|')))(char '|')
readNGCObject :: String -> Maybe NGCObject
readNGCObject st = do
h <- readMaybe (l !! 5)
m <- readMaybe (l !! 7)
s <- readMaybeFloatWithComma (l !! 9)
let ra = fromHMS h m s
mag <- readMaybeFloatWithComma (l !! 18)
d <- readMaybe (l !! 11)
m' <- readMaybe (l !! 13)
s' <- readMaybeFloatWithComma (l !! 15)
let dec = fromDMS d m' s'
return NGCObject
{ nID = head l
, nPGC= l !! 1
, nMessier= l !! 2
, nType= l !! 3
, nClass= l !! 4
, nRA= ra
, nDec= dec
,nMag= mag
}
where
l = readRecord st
| slspeek/hephem | src/HEphem/NGCParser.hs | gpl-3.0 | 1,358 | 0 | 12 | 369 | 465 | 245 | 220 | 40 | 2 |
module MaxN (MaxN(), empty, toList, insert) where
data MaxN a =
MaxN
{ mMaxSize :: Int
, mSize :: Int
, mFull :: Bool
, mElems :: [a]
} deriving (Show)
empty :: Int -> MaxN a
empty maxSize
| maxSize < 0 = error "MaxN.empty: maxSize < 0"
| otherwise = MaxN maxSize 0 (maxSize == 0) []
toList :: MaxN a -> [a]
toList = reverse . mElems
insert :: (Ord a) => a -> MaxN a -> MaxN a
insert x m@MaxN{ .. } = f $ m { mElems = insertSorted mFull x mElems }
where
f = case mFull of
True -> id
False -> \m@MaxN{ .. } -> m { mSize = mSize + 1, mFull = mSize + 1 == mMaxSize }
insertSorted :: (Ord a) => Bool -> a -> [a] -> [a]
insertSorted _ x [] = [x]
insertSorted True x xs@(min : maxs)
| min >= x = xs
| otherwise = insertSorted False x maxs
insertSorted False x xs@(min : maxs)
| min >= x = x : xs
| otherwise = min : insertSorted False x maxs
| ktvoelker/Picker | src/MaxN.hs | gpl-3.0 | 914 | 0 | 14 | 267 | 431 | 229 | 202 | -1 | -1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE FlexibleInstances #-}
module Hive.Server.Types where
import Control.Concurrent.STM
import Control.Monad.Reader (ask, asks, ReaderT, runReaderT, lift)
import Control.Monad.Trans
import Control.Monad.Trans.Except
import Data.Aeson
import Data.Aeson.TH
import Data.Hashable (Hashable)
import qualified Data.HashMap.Strict as H
import Data.Int
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe (fromJust)
import Data.Text (Text(..))
import Data.Text.Encoding (decodeUtf8)
import qualified Data.Text as T
import Servant
-- TODO: make some kind of roll-up package Hive.Game that re-exports the public stuff
import Hive.Game.Board (Board(..))
import Hive.Game.Move (AbsoluteMove(..))
import Hive.Game.HexGrid (AxialPoint(..))
import Hive.Game.Piece (Piece(..), Team(..), piece)
import Hive.Game.Engine (Game(..),GameState(..))
-- should i have IDs in the models or not?
-- Persistent keeps them out...
type PlayerId = Int64
data Player = Player { playerName :: Text
, playerId :: Int64
} deriving (Eq, Show)
type GameId = Int64
data GameInfo = GameInfo { giWhite :: Maybe Player
, giBlack :: Maybe Player
, giGame :: Game
, giAnnounceChan :: TChan Game
}
type AppM = ReaderT Config (ExceptT ServantErr IO)
type AppSTM = ReaderT Config (ExceptT ServantErr STM)
runApp :: Config -> AppM a -> IO (Either ServantErr a)
runApp cfg app = runExceptT (runReaderT app cfg)
liftSTM :: STM a -> AppSTM a
liftSTM = lift . lift
-- | like `atomically` but for our custom monad stacks
apptomically :: AppSTM a -> AppM a
apptomically stmAct = do
context <- ask
lift $ ExceptT $ liftIO $ atomically $
runExceptT $ runReaderT stmAct context
type GameDB = TVar (Map GameId GameInfo)
data Config = Config { userDB :: TVar [User]
, gameDB :: GameDB
}
data User = User
{ userId :: Int
, userFirstName :: String
, userLastName :: String
} deriving (Eq, Show)
$(deriveJSON defaultOptions ''User)
$(deriveJSON defaultOptions ''AxialPoint)
$(deriveJSON defaultOptions ''Team)
$(deriveJSON defaultOptions ''Board)
$(deriveJSON defaultOptions ''AbsoluteMove)
$(deriveJSON defaultOptions ''GameState)
$(deriveJSON defaultOptions ''Game)
instance ToJSON Piece where
toJSON = toJSON . pieceName
instance FromJSON Piece where
parseJSON = (piece <$>) . parseJSON
instance ToJSON a => ToJSON (Map Piece a) where
toJSON = Object . mapHashKeyVal (T.pack . show) toJSON
instance FromJSON a => FromJSON (Map Piece a) where
-- TODO: validate that this is a legit piece
parseJSON = fmap (hashMapKey piece) . parseJSON
instance ToJSON a => ToJSON (Map AxialPoint a) where
toJSON = Object . mapHashKeyVal (T.pack . show) toJSON
instance FromJSON a => FromJSON (Map AxialPoint a) where
parseJSON = fmap (hashMapKey shittyParse) . parseJSON
where
shittyParse s = let [p,q] = read s
in Axial p q
-- | Transform a 'Map' into a 'HashMap' while transforming the keys.
-- (ganked directly from Data.Aeson.Functions in service of yak-shavery)
mapHashKeyVal :: (Eq k2, Hashable k2) => (k1 -> k2) -> (v1 -> v2)
-> Map k1 v1 -> H.HashMap k2 v2
mapHashKeyVal fk kv = Map.foldrWithKey (\k v -> H.insert (fk k) (kv v)) H.empty
-- | Transform a 'M.Map' into a 'H.HashMap' while transforming the keys.
-- (also ganked directly from Data.Aeson.Functions)
hashMapKey :: (Ord k2) => (k1 -> k2)
-> H.HashMap k1 v -> Map k2 v
hashMapKey kv = H.foldrWithKey (Map.insert . kv) Map.empty
{-# INLINE hashMapKey #-}
-- eventually might stick some more useful stuff in here
data NewGameResult = NewGameResult { gameId :: GameId
} deriving (Show)
$(deriveJSON defaultOptions ''NewGameResult)
newtype FakeAuth = FakeAuth Text -- ^ username
deriving (Eq, Ord, Show)
instance FromHttpApiData FakeAuth where
parseUrlPiece t =
case T.words $ T.strip t of
"Fake":r:_ -> Right (FakeAuth r)
_ -> Left "We only cotton to the Fake realm round these parts"
hoistEither :: Monad m => Either e a -> ExceptT e m a
hoistEither = ExceptT . return
| nathanic/hive-hs | src/Hive/Server/Types.hs | gpl-3.0 | 4,502 | 0 | 12 | 1,178 | 1,268 | 689 | 579 | 92 | 1 |
module QFeldspar.Expression.Conversions.Evaluation.ADTUntypedNamed () where
import QFeldspar.MyPrelude
import QFeldspar.Expression.ADTUntypedNamed
import qualified QFeldspar.Expression.ADTValue as FAV
import QFeldspar.Environment.Map
import QFeldspar.Conversion
instance (Show x , Eq x) => Cnv (Exp x , (Env x FAV.Exp , Env x FAV.Exp)) FAV.Exp where
cnv (ee , r@(s , g)) = join (case ee of
Var x -> FAV.var <$> get x g
Prm x es -> FAV.prm <$> get x s <*> mapM (\ e -> cnv (e,r)) es
_ -> $(biGenOverloadedML 'ee ''Exp "FAV" ['Prm,'Var]
(\ tt -> if
| matchQ tt [t| Exp x |] ->
[| \ e -> cnv (e , r) |]
| matchQ tt [t| (x , Exp x) |] ->
[| \ (x , e) ->
pure (\ v -> frmRgtZro (cnv (e , (s , (x,v) : g)))) |]
| otherwise ->
[| pure |])))
| shayan-najd/QFeldspar | QFeldspar/Expression/Conversions/Evaluation/ADTUntypedNamed.hs | gpl-3.0 | 862 | 0 | 20 | 265 | 294 | 167 | 127 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
-- |
-- Module : Network.Google.Vision
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Integrates Google Vision features, including image labeling, face, logo,
-- and landmark detection, optical character recognition (OCR), and
-- detection of explicit content, into applications.
--
-- /See:/ <https://cloud.google.com/vision/ Google Cloud Vision API Reference>
module Network.Google.Vision
(
-- * Service Configuration
visionService
-- * OAuth Scopes
, cloudPlatformScope
-- * API Declaration
, VisionAPI
-- * Resources
-- ** vision.images.annotate
, module Network.Google.Resource.Vision.Images.Annotate
-- * Types
-- ** LatLng
, LatLng
, latLng
, llLatitude
, llLongitude
-- ** FaceAnnotationUnderExposedLikelihood
, FaceAnnotationUnderExposedLikelihood (..)
-- ** Feature
, Feature
, feature
, fType
, fMaxResults
-- ** Status
, Status
, status
, sDetails
, sCode
, sMessage
-- ** Property
, Property
, property
, pValue
, pName
-- ** Image
, Image
, image
, iContent
, iSource
-- ** Landmark
, Landmark
, landmark
, lType
, lPosition
-- ** Color
, Color
, color
, cRed
, cAlpha
, cGreen
, cBlue
-- ** FaceAnnotationHeadwearLikelihood
, FaceAnnotationHeadwearLikelihood (..)
-- ** BoundingPoly
, BoundingPoly
, boundingPoly
, bpVertices
-- ** SafeSearchAnnotationAdult
, SafeSearchAnnotationAdult (..)
-- ** Vertex
, Vertex
, vertex
, vX
, vY
-- ** FaceAnnotationAngerLikelihood
, FaceAnnotationAngerLikelihood (..)
-- ** LocationInfo
, LocationInfo
, locationInfo
, liLatLng
-- ** SafeSearchAnnotationMedical
, SafeSearchAnnotationMedical (..)
-- ** StatusDetailsItem
, StatusDetailsItem
, statusDetailsItem
, sdiAddtional
-- ** BatchAnnotateImagesRequest
, BatchAnnotateImagesRequest
, batchAnnotateImagesRequest
, bairRequests
-- ** ColorInfo
, ColorInfo
, colorInfo
, ciColor
, ciScore
, ciPixelFraction
-- ** FaceAnnotationBlurredLikelihood
, FaceAnnotationBlurredLikelihood (..)
-- ** AnnotateImageResponse
, AnnotateImageResponse
, annotateImageResponse
, airLogoAnnotations
, airLabelAnnotations
, airFaceAnnotations
, airError
, airSafeSearchAnnotation
, airLandmarkAnnotations
, airTextAnnotations
, airImagePropertiesAnnotation
-- ** ImageProperties
, ImageProperties
, imageProperties
, ipDominantColors
-- ** FaceAnnotation
, FaceAnnotation
, faceAnnotation
, faTiltAngle
, faBlurredLikelihood
, faBoundingPoly
, faSurpriseLikelihood
, faLandmarkingConfidence
, faPanAngle
, faRollAngle
, faUnderExposedLikelihood
, faFdBoundingPoly
, faAngerLikelihood
, faDetectionConfidence
, faHeadwearLikelihood
, faSorrowLikelihood
, faJoyLikelihood
, faLandmarks
-- ** SafeSearchAnnotationViolence
, SafeSearchAnnotationViolence (..)
-- ** EntityAnnotation
, EntityAnnotation
, entityAnnotation
, eaScore
, eaTopicality
, eaLocale
, eaBoundingPoly
, eaConfidence
, eaMid
, eaLocations
, eaDescription
, eaProperties
-- ** FeatureType
, FeatureType (..)
-- ** AnnotateImageRequest
, AnnotateImageRequest
, annotateImageRequest
, airImage
, airFeatures
, airImageContext
-- ** LandmarkType
, LandmarkType (..)
-- ** Xgafv
, Xgafv (..)
-- ** ImageSource
, ImageSource
, imageSource
, isGcsImageURI
-- ** SafeSearchAnnotationSpoof
, SafeSearchAnnotationSpoof (..)
-- ** FaceAnnotationSurpriseLikelihood
, FaceAnnotationSurpriseLikelihood (..)
-- ** SafeSearchAnnotation
, SafeSearchAnnotation
, safeSearchAnnotation
, ssaSpoof
, ssaAdult
, ssaMedical
, ssaViolence
-- ** FaceAnnotationSorrowLikelihood
, FaceAnnotationSorrowLikelihood (..)
-- ** FaceAnnotationJoyLikelihood
, FaceAnnotationJoyLikelihood (..)
-- ** ImageContext
, ImageContext
, imageContext
, icLanguageHints
, icLatLongRect
-- ** DominantColorsAnnotation
, DominantColorsAnnotation
, dominantColorsAnnotation
, dcaColors
-- ** LatLongRect
, LatLongRect
, latLongRect
, llrMaxLatLng
, llrMinLatLng
-- ** BatchAnnotateImagesResponse
, BatchAnnotateImagesResponse
, batchAnnotateImagesResponse
, bairResponses
-- ** Position
, Position
, position
, pZ
, pX
, pY
) where
import Network.Google.Prelude
import Network.Google.Resource.Vision.Images.Annotate
import Network.Google.Vision.Types
{- $resources
TODO
-}
-- | Represents the entirety of the methods and resources available for the Google Cloud Vision API service.
type VisionAPI = ImagesAnnotateResource
| rueshyna/gogol | gogol-vision/gen/Network/Google/Vision.hs | mpl-2.0 | 5,464 | 0 | 5 | 1,444 | 597 | 427 | 170 | 155 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.CloudResourceManager.Liens.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Delete a Lien by \`name\`. Callers of this method will require
-- permission on the \`parent\` resource. For example, a Lien with a
-- \`parent\` of \`projects\/1234\` requires permission
-- \`resourcemanager.projects.updateLiens\`.
--
-- /See:/ <https://cloud.google.com/resource-manager Cloud Resource Manager API Reference> for @cloudresourcemanager.liens.delete@.
module Network.Google.Resource.CloudResourceManager.Liens.Delete
(
-- * REST Resource
LiensDeleteResource
-- * Creating a Request
, liensDelete
, LiensDelete
-- * Request Lenses
, ldXgafv
, ldUploadProtocol
, ldAccessToken
, ldUploadType
, ldName
, ldCallback
) where
import Network.Google.Prelude
import Network.Google.ResourceManager.Types
-- | A resource alias for @cloudresourcemanager.liens.delete@ method which the
-- 'LiensDelete' request conforms to.
type LiensDeleteResource =
"v3" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] Empty
-- | Delete a Lien by \`name\`. Callers of this method will require
-- permission on the \`parent\` resource. For example, a Lien with a
-- \`parent\` of \`projects\/1234\` requires permission
-- \`resourcemanager.projects.updateLiens\`.
--
-- /See:/ 'liensDelete' smart constructor.
data LiensDelete =
LiensDelete'
{ _ldXgafv :: !(Maybe Xgafv)
, _ldUploadProtocol :: !(Maybe Text)
, _ldAccessToken :: !(Maybe Text)
, _ldUploadType :: !(Maybe Text)
, _ldName :: !Text
, _ldCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LiensDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ldXgafv'
--
-- * 'ldUploadProtocol'
--
-- * 'ldAccessToken'
--
-- * 'ldUploadType'
--
-- * 'ldName'
--
-- * 'ldCallback'
liensDelete
:: Text -- ^ 'ldName'
-> LiensDelete
liensDelete pLdName_ =
LiensDelete'
{ _ldXgafv = Nothing
, _ldUploadProtocol = Nothing
, _ldAccessToken = Nothing
, _ldUploadType = Nothing
, _ldName = pLdName_
, _ldCallback = Nothing
}
-- | V1 error format.
ldXgafv :: Lens' LiensDelete (Maybe Xgafv)
ldXgafv = lens _ldXgafv (\ s a -> s{_ldXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
ldUploadProtocol :: Lens' LiensDelete (Maybe Text)
ldUploadProtocol
= lens _ldUploadProtocol
(\ s a -> s{_ldUploadProtocol = a})
-- | OAuth access token.
ldAccessToken :: Lens' LiensDelete (Maybe Text)
ldAccessToken
= lens _ldAccessToken
(\ s a -> s{_ldAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
ldUploadType :: Lens' LiensDelete (Maybe Text)
ldUploadType
= lens _ldUploadType (\ s a -> s{_ldUploadType = a})
-- | Required. The name\/identifier of the Lien to delete.
ldName :: Lens' LiensDelete Text
ldName = lens _ldName (\ s a -> s{_ldName = a})
-- | JSONP
ldCallback :: Lens' LiensDelete (Maybe Text)
ldCallback
= lens _ldCallback (\ s a -> s{_ldCallback = a})
instance GoogleRequest LiensDelete where
type Rs LiensDelete = Empty
type Scopes LiensDelete =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only"]
requestClient LiensDelete'{..}
= go _ldName _ldXgafv _ldUploadProtocol
_ldAccessToken
_ldUploadType
_ldCallback
(Just AltJSON)
resourceManagerService
where go
= buildClient (Proxy :: Proxy LiensDeleteResource)
mempty
| brendanhay/gogol | gogol-resourcemanager/gen/Network/Google/Resource/CloudResourceManager/Liens/Delete.hs | mpl-2.0 | 4,708 | 0 | 15 | 1,065 | 703 | 413 | 290 | 99 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.DialogFlow.Projects.Locations.Agents.Flows.Versions.Load
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Loads resources in the specified version to the draft flow.
--
-- /See:/ <https://cloud.google.com/dialogflow/ Dialogflow API Reference> for @dialogflow.projects.locations.agents.flows.versions.load@.
module Network.Google.Resource.DialogFlow.Projects.Locations.Agents.Flows.Versions.Load
(
-- * REST Resource
ProjectsLocationsAgentsFlowsVersionsLoadResource
-- * Creating a Request
, projectsLocationsAgentsFlowsVersionsLoad
, ProjectsLocationsAgentsFlowsVersionsLoad
-- * Request Lenses
, plafvlXgafv
, plafvlUploadProtocol
, plafvlAccessToken
, plafvlUploadType
, plafvlPayload
, plafvlName
, plafvlCallback
) where
import Network.Google.DialogFlow.Types
import Network.Google.Prelude
-- | A resource alias for @dialogflow.projects.locations.agents.flows.versions.load@ method which the
-- 'ProjectsLocationsAgentsFlowsVersionsLoad' request conforms to.
type ProjectsLocationsAgentsFlowsVersionsLoadResource
=
"v3" :>
CaptureMode "name" "load" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON]
GoogleCloudDialogflowCxV3LoadVersionRequest
:> Post '[JSON] GoogleLongrunningOperation
-- | Loads resources in the specified version to the draft flow.
--
-- /See:/ 'projectsLocationsAgentsFlowsVersionsLoad' smart constructor.
data ProjectsLocationsAgentsFlowsVersionsLoad =
ProjectsLocationsAgentsFlowsVersionsLoad'
{ _plafvlXgafv :: !(Maybe Xgafv)
, _plafvlUploadProtocol :: !(Maybe Text)
, _plafvlAccessToken :: !(Maybe Text)
, _plafvlUploadType :: !(Maybe Text)
, _plafvlPayload :: !GoogleCloudDialogflowCxV3LoadVersionRequest
, _plafvlName :: !Text
, _plafvlCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsAgentsFlowsVersionsLoad' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plafvlXgafv'
--
-- * 'plafvlUploadProtocol'
--
-- * 'plafvlAccessToken'
--
-- * 'plafvlUploadType'
--
-- * 'plafvlPayload'
--
-- * 'plafvlName'
--
-- * 'plafvlCallback'
projectsLocationsAgentsFlowsVersionsLoad
:: GoogleCloudDialogflowCxV3LoadVersionRequest -- ^ 'plafvlPayload'
-> Text -- ^ 'plafvlName'
-> ProjectsLocationsAgentsFlowsVersionsLoad
projectsLocationsAgentsFlowsVersionsLoad pPlafvlPayload_ pPlafvlName_ =
ProjectsLocationsAgentsFlowsVersionsLoad'
{ _plafvlXgafv = Nothing
, _plafvlUploadProtocol = Nothing
, _plafvlAccessToken = Nothing
, _plafvlUploadType = Nothing
, _plafvlPayload = pPlafvlPayload_
, _plafvlName = pPlafvlName_
, _plafvlCallback = Nothing
}
-- | V1 error format.
plafvlXgafv :: Lens' ProjectsLocationsAgentsFlowsVersionsLoad (Maybe Xgafv)
plafvlXgafv
= lens _plafvlXgafv (\ s a -> s{_plafvlXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
plafvlUploadProtocol :: Lens' ProjectsLocationsAgentsFlowsVersionsLoad (Maybe Text)
plafvlUploadProtocol
= lens _plafvlUploadProtocol
(\ s a -> s{_plafvlUploadProtocol = a})
-- | OAuth access token.
plafvlAccessToken :: Lens' ProjectsLocationsAgentsFlowsVersionsLoad (Maybe Text)
plafvlAccessToken
= lens _plafvlAccessToken
(\ s a -> s{_plafvlAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
plafvlUploadType :: Lens' ProjectsLocationsAgentsFlowsVersionsLoad (Maybe Text)
plafvlUploadType
= lens _plafvlUploadType
(\ s a -> s{_plafvlUploadType = a})
-- | Multipart request metadata.
plafvlPayload :: Lens' ProjectsLocationsAgentsFlowsVersionsLoad GoogleCloudDialogflowCxV3LoadVersionRequest
plafvlPayload
= lens _plafvlPayload
(\ s a -> s{_plafvlPayload = a})
-- | Required. The Version to be loaded to draft flow. Format:
-- \`projects\/\/locations\/\/agents\/\/flows\/\/versions\/\`.
plafvlName :: Lens' ProjectsLocationsAgentsFlowsVersionsLoad Text
plafvlName
= lens _plafvlName (\ s a -> s{_plafvlName = a})
-- | JSONP
plafvlCallback :: Lens' ProjectsLocationsAgentsFlowsVersionsLoad (Maybe Text)
plafvlCallback
= lens _plafvlCallback
(\ s a -> s{_plafvlCallback = a})
instance GoogleRequest
ProjectsLocationsAgentsFlowsVersionsLoad
where
type Rs ProjectsLocationsAgentsFlowsVersionsLoad =
GoogleLongrunningOperation
type Scopes ProjectsLocationsAgentsFlowsVersionsLoad
=
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/dialogflow"]
requestClient
ProjectsLocationsAgentsFlowsVersionsLoad'{..}
= go _plafvlName _plafvlXgafv _plafvlUploadProtocol
_plafvlAccessToken
_plafvlUploadType
_plafvlCallback
(Just AltJSON)
_plafvlPayload
dialogFlowService
where go
= buildClient
(Proxy ::
Proxy
ProjectsLocationsAgentsFlowsVersionsLoadResource)
mempty
| brendanhay/gogol | gogol-dialogflow/gen/Network/Google/Resource/DialogFlow/Projects/Locations/Agents/Flows/Versions/Load.hs | mpl-2.0 | 6,224 | 0 | 16 | 1,329 | 784 | 459 | 325 | 123 | 1 |
{-# language TypeFamilies #-}
class C a where
type family F a
instance C Int where
type F Int = IO Int -- x
| lspitzner/brittany | data/Test216.hs | agpl-3.0 | 112 | 0 | 6 | 28 | 37 | 20 | 17 | 5 | 0 |
module LSystem.Utils (
(/.),
maybeHead,
parseInt,
toMaybeCond,
readToBlankLine,
splitNonEmpty,
parse,
degToRad,
round2,
filterNonEmpty
) where
import Data.List
import Data.Function
----------------------------------------------------------------------------------------------------
-- | Helper operator for division.
(/.) = (/) `on` fromIntegral
maybeHead :: [a] -> Maybe a
maybeHead xs =
let x = take 1 xs in
if length x == 1 then Just $ head x else Nothing
-- | Reads string by given func and returns first result which has empty remainder (whole given
-- string was readed by reads func)
parse :: ReadS a -> String -> Maybe a
parse readsFunc str =
let fullyParsed = filter (\ (_, rest) -> null rest) $ readsFunc str in
if null fullyParsed then
Nothing
else
Just $ fst $ head fullyParsed
parseInt :: String -> Maybe Int
parseInt = parse reads
toMaybeCond :: (a -> Bool) -> a -> Maybe a
toMaybeCond condFunc x = if condFunc x then Just x else Nothing
readToBlankLine :: [String] -> ([String], [String])
readToBlankLine strLines =
case break null strLines of
([], rest) -> ([], rest)
(lines, rest) -> (lines, drop 1 rest) -- drop empty line
-- | Returns all possible splits of list, left nor right part of split is epty.
splitNonEmpty :: [a] -> [([a], [a])]
splitNonEmpty xs = [splitAt n xs | n <- [1..(length xs - 1)]]
-- | Converts angle in dergees to radians.
degToRad :: Double -> Double
degToRad x = x * (pi / 180.0)
-- | Rounds double to precision of 2 digits after deciaml point.
round2 :: Double -> Double
round2 n = round (n * 100) /. 100
filterNonEmpty :: [[a]] -> [[a]]
filterNonEmpty = filter (\x -> not $ null x)
| NightElfik/L-systems-in-Haskell | src/LSystem/Utils.hs | unlicense | 1,749 | 0 | 13 | 403 | 545 | 302 | 243 | 41 | 2 |
module Git.Command.CountObjects (run) where
run :: [String] -> IO ()
run args = return () | wereHamster/yag | Git/Command/CountObjects.hs | unlicense | 90 | 0 | 7 | 15 | 42 | 23 | 19 | 3 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Types
-- author : cdannapp & tmielcza
--
-- Types returned by parsing and used for Resolution
--
-----------------------------------------------------------------------------
module Types
(
Expr(Xor, Or, And, Fact, Not),
Relation(Eq, Imply),
Init,
Query,
Types.State(..),
Knowledge,
Resolved,
Resolution,
exprToStringState
) where
import Control.Monad.Trans.State.Lazy as S (State)
import Control.Monad.Trans.Reader (ReaderT)
import Control.Monad.Except (ExceptT)
import Data.Map
import Prelude hiding (Bool(..), not)
import qualified Prelude (Bool(..), not)
type Query = [Expr]
type Init = [(String, Types.State)]
-- | the type of expressions all constructors are recursives except Fact
data Expr = Xor Expr Expr |
Or Expr Expr |
And Expr Expr |
Fact String |
Not Expr
data State = Unsolved Expr | True | False | Unprovable Expr
deriving (Show, Eq)
-- | Association of an Expr (Mostly a Fact) to a State
--type FactState = (Expr, Types.State)
type Knowledge = Map String Types.State
-- | The type of the relations between the Exprs. They form rules.
data Relation = Eq Expr Expr | Imply Expr Expr
-- | this type is used for resolution, it contains the knowledges first and then the state of the goal
type Resolved = (Knowledge, Types.State)
type Resolution a = ExceptT String (ReaderT [Relation] (S.State Knowledge)) a
instance Eq Expr where
(And a1 b1) == (And a2 b2) = cmpBinaryExprSides a1 a2 b1 b2
(Or a1 b1) == (Or a2 b2) = cmpBinaryExprSides a1 a2 b1 b2
(Xor a1 b1) == (Xor a2 b2) = cmpBinaryExprSides a1 a2 b1 b2
a == Not (Not b) = a == b
Not (Not a) == b = b == a
(Not a) == (Not b) = a == b
(Fact a) == (Fact b) = a == b
_ == _ = Prelude.False
instance Show Expr where
show (Xor e1 e2) = "(" ++ show e1 ++ "^" ++ show e2 ++ ")"
show (Or e1 e2) = "(" ++ show e1 ++ "|" ++ show e2 ++ ")"
show (And e1 e2) = "(" ++ show e1 ++ "+" ++ show e2 ++ ")"
show (Fact c) = c
show (Not e) = "!" ++ show e
instance Show Relation where
show (Imply e1 e2) = "{" ++ show e1 ++ "=>" ++ show e2 ++ "}"
show (Eq e1 e2) = "{" ++ show e1 ++ "<=>" ++ show e2 ++ "}"
-- Functions of types
cmpBinaryExprSides lhs1 rhs1 lhs2 rhs2
| lhs1 == lhs2 && rhs1 == rhs2 = Prelude.True
| lhs1 == rhs2 && lhs2 == rhs1 = Prelude.True
| otherwise = Prelude.False
exprToStringState :: Expr -> (String, Types.State)
exprToStringState (Not (Not (e))) = exprToStringState e
exprToStringState (Not (Fact f)) = (f, False)
exprToStringState (Fact f) = (f, True)
| tmielcza/demiurge | src/Types.hs | apache-2.0 | 2,692 | 0 | 10 | 620 | 945 | 510 | 435 | 60 | 1 |
{-# LANGUAGE TemplateHaskell, QuasiQuotes, OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE ViewPatterns #-}
module Handler.Posts where
import Import
import Yesod.Auth (requireAuthId)
import Helpers.Post
import Helpers.Shorten
getPostsR :: Handler Html
getPostsR = do
(map entityVal -> posts) <- runDB $ selectList [] [Desc PostCreated]
standardLayout $ do
setDtekTitle "Gamla inlägg"
$(widgetFile "posts")
getPostR :: Text -> Handler Html
getPostR slug = standardLayout $ do
setDtekTitle "Specifikt inlägg"
slugToPostWidget True slug
postPostR :: Text -> Handler Html
postPostR = getPostR
getManagePostsR :: Handler Html
getManagePostsR = do
uid <- requireAuthId
(map entityVal -> posts) <- runDB $ selectList [] [Desc PostCreated]
defaultLayout $ do
setDtekTitle "Administrera inlägg"
let (postslist :: Widget) = $(widgetFile "postslist")
$(widgetFile "manage")
postManagePostsR :: Handler Html
postManagePostsR = getManagePostsR
getEditPostR :: Text -> Handler Html
getEditPostR slug = do
uid <- requireAuthId
mkpost <- runDB $ selectFirst [PostSlug ==. slug] []
defaultLayout $ do
setDtekTitle "Redigera inlägg"
$(widgetFile "editpost")
postEditPostR :: Text -> Handler Html
postEditPostR = getEditPostR
getDelPostR :: Text -> Handler Html
getDelPostR slug = do
p <- runDB $ getBy $ UniquePost slug
case p of
Just (entityKey -> key) -> do
runDB $ delete key
setSuccessMessage "Inlägg raderat!"
Nothing -> setErrorMessage "Inlägg ej funnet."
redirect ManagePostsR
| dtekcth/DtekPortalen | src/Handler/Posts.hs | bsd-2-clause | 1,661 | 0 | 15 | 368 | 455 | 216 | 239 | 48 | 2 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QNetworkProxy.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:36
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Enums.Network.QNetworkProxy (
ProxyType, eDefaultProxy, eSocks5Proxy, eNoProxy, eHttpProxy
)
where
import Foreign.C.Types
import Qtc.Classes.Base
import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr)
import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int)
import Qtc.Enums.Base
import Qtc.Enums.Classes.Core
data CProxyType a = CProxyType a
type ProxyType = QEnum(CProxyType Int)
ieProxyType :: Int -> ProxyType
ieProxyType x = QEnum (CProxyType x)
instance QEnumC (CProxyType Int) where
qEnum_toInt (QEnum (CProxyType x)) = x
qEnum_fromInt x = QEnum (CProxyType x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> ProxyType -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
eDefaultProxy :: ProxyType
eDefaultProxy
= ieProxyType $ 0
eSocks5Proxy :: ProxyType
eSocks5Proxy
= ieProxyType $ 1
eNoProxy :: ProxyType
eNoProxy
= ieProxyType $ 2
eHttpProxy :: ProxyType
eHttpProxy
= ieProxyType $ 3
| keera-studios/hsQt | Qtc/Enums/Network/QNetworkProxy.hs | bsd-2-clause | 2,503 | 0 | 18 | 543 | 629 | 323 | 306 | 58 | 1 |
-- | Global configuration for output
-- (This should be deprecated in the future as Recipes evolve)
module Language.Drasil.Config(numberedSections,hyperSettings,fontSize,bibFname,
verboseDDDescription,StyleGuide(..),bibStyleH,bibStyleT,colAwidth,colBwidth,
numberedDDEquations,numberedTMEquations) where
-- | TeX font size
fontSize :: Int
fontSize = 12
-- | Print verbose data definition descriptions?
verboseDDDescription :: Bool
verboseDDDescription = True
-- | TeX Only - Number Data Definition equations?
numberedDDEquations :: Bool
numberedDDEquations = False -- Does not affect HTML
-- | TeX Only - Number Theoretical Model equations?
numberedTMEquations :: Bool
numberedTMEquations = False
-- | TeX Only - Numbered sections?
numberedSections :: Bool
numberedSections = True
--TeX Document Parameter Defaults (can be modified to affect all documents OR
-- you can create your own parameter function and replace the one above.
--defaultSRSparams :: SRSParams
--defaultSRSparams = SRSParams
-- (DocClass Nothing "article")
-- (UsePackages ["fullpage","booktabs","longtable","listings","graphics","hyperref","caption",
-- "amsmath"])
-- | TeX Only - column width for data definitions
-- (fraction of LaTeX textwidth)
colAwidth, colBwidth :: Double
colAwidth = 0.13
colBwidth = 0.82
-- | TeX Only - Settings for hyperref
hyperSettings :: String
hyperSettings =
"bookmarks=true," -- show bookmarks bar?
++ "colorlinks=true," -- false: boxed links; true: colored links
++ "linkcolor=red," -- color of internal links
++ "citecolor=blue," -- color of links to bibliography
++ "filecolor=magenta," -- color of file links
++ "urlcolor=cyan" -- color of external links
-- | The bibliography format
data StyleGuide = MLA | APA | Chicago
useStyleTeX :: StyleGuide -> String
useStyleTeX MLA = "ieeetr"
useStyleTeX APA = "apalike"
useStyleTeX Chicago = "plain"
bibStyleT :: String
bibStyleT = useStyleTeX bibStyle --This will be an input for the user eventually
bibStyleH :: StyleGuide
bibStyleH = bibStyle
bibStyle :: StyleGuide
bibStyle = MLA
-- | Used to name the BibTeX file
bibFname :: String
bibFname = "bibfile" --needed in TeX/Print and TeX/Preamble
| JacquesCarette/literate-scientific-software | code/drasil-printers/Language/Drasil/Config.hs | bsd-2-clause | 2,212 | 0 | 9 | 355 | 263 | 168 | 95 | 37 | 1 |
curr f a b = f (a,b)
uncurr f (a,b) = f a b
| abhinav-mehta/CipherSolver | src/other/Curr.hs | bsd-3-clause | 44 | 0 | 6 | 14 | 43 | 22 | 21 | 2 | 1 |
module Abstract.Queue.Enq (
module Abstract.Interfaces.Queue.Enq,
mkQueue'Enq
) where
import Abstract.Queue
import Abstract.Interfaces.Queue
import Abstract.Interfaces.Queue.Enq
mkQueue'Enq url pack unpack = do
c <- mkQueue url pack unpack
return $ queueToEnq c
| adarqui/Abstract | src/Abstract/Queue/Enq.hs | bsd-3-clause | 269 | 0 | 8 | 37 | 74 | 42 | 32 | 9 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
module Snap.Snaplet.Auth.Backends.Persistent.Types where
------------------------------------------------------------------------------
import Data.Text (Text)
import Data.Time
import Database.Persist.Quasi
import Database.Persist.TH hiding (derivePersistField)
------------------------------------------------------------------------------
share [mkPersist sqlSettings, mkMigrate "migrateAuth"]
$(persistFileWith lowerCaseSettings "schema.txt")
| Soostone/snaplet-persistent | src/Snap/Snaplet/Auth/Backends/Persistent/Types.hs | bsd-3-clause | 1,174 | 0 | 8 | 301 | 89 | 59 | 30 | 22 | 0 |
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-|
Module : Game.GoreAndAsh.Network
Description : Module that contains network low-level API for Gore&Ash
Copyright : (c) Anton Gushcha, 2015-2016
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : POSIX
The core module contains API for basic networking for Gore&Ash. The network module is built
over Enet library, UDP transport with custom implementation of reliability. The API provides
connection handling and basic message handling (bytestring sending and receiving).
-}
module Game.GoreAndAsh.Network(
-- * Types
ChannelId(..)
, RemoteAddress
, MessageType(..)
, HasNetworkBackend(..)
, SendError(..)
, NetworkT
, withNetwork
, runNetworkT
-- ** Options
, NetworkOptions
, defaultNetworkOptions
, networkOptsDetailedLogging
, networkOptsBackendOptions
-- ** Errors
, NetworkError(..)
, renderNetworkError
-- * Network API
, NetworkMonad(..)
, peerSend
, peerChanSend
, peerSendMany
, peerChanSendMany
, terminateNetwork
, peerMessage
, chanMessage
, peerChanMessage
-- ** Client API
, NetworkClient(..)
, whenConnected
, whenConnectedWithDisconnect
-- ** Server API
, NetworkServer(..)
-- ** Collections
, PeerAction(..)
, peersCollection
, peersCollectionWithDisconnect
, processPeers
, processPeersWithDisconnect
) where
import Game.GoreAndAsh.Network.API as X
import Game.GoreAndAsh.Network.Backend as X
import Game.GoreAndAsh.Network.Error as X
import Game.GoreAndAsh.Network.Module as X
import Game.GoreAndAsh.Network.Options as X
import Game.GoreAndAsh.Network.State as X
| Teaspot-Studio/gore-and-ash-network | src/Game/GoreAndAsh/Network.hs | bsd-3-clause | 1,663 | 0 | 5 | 289 | 204 | 148 | 56 | 40 | 0 |
{-# OPTIONS -XScopedTypeVariables -XRecordWildCards -XMagicHash -XUnboxedTuples -XBangPatterns #-}
module PackToMem
where
import GHC.IO ( IO(..) )
import GHC.Prim
( ByteArray#, sizeofByteArray#, serialize#, deserialize# )
import GHC.Exts ( Int(..), Word )
import Data.Array.Base ( UArray(..), elems, listArray )
import Foreign.Storable ( sizeOf )
-- Read and Show instances
import Text.Printf ( printf )
import Text.ParserCombinators.ReadP (sepBy1, many1, ReadP, munch,
munch1, pfail, readP_to_S, satisfy, skipSpaces, string )
import Data.Char ( isDigit )
import Data.Typeable ( Typeable(..), TypeRep, typeOf )
-- for dynamic type checks when parsing
import Data.Binary ( Get, Binary(..), encode, decode, encodeFile, decodeFile )
----------------------------------------------------------
-- IO wrappers for primitive operation:
--
---------
heapToArray :: a -> IO (UArray Int Word)
heapToArray x
= IO (\s ->
case serialize# x s of
(# s', bArr# #) ->
case sizeofByteArray# bArr# of
sz# -> let -- we return a word array, need to
-- adjust size. OTOH, the ByteArray
-- size is always multiple of
-- sizeOf(StgWord) by construction.
size = (I# sz# ) `div`
sizeOf(undefined::Word)
upper = size - 1
in (# s', UArray 0 upper size bArr# #) )
heapFromArray :: UArray Int Word -> IO a
heapFromArray (UArray 0 hi size bArr# )
= IO (\s -> case deserialize# bArr# s of
(# s', newData #) -> (# s', newData #))
heapFromArray other
= error "internal error: unexpected array bounds"
-- Type-safe variant
-- phantom type a ensures that we do not unpack rubbish
-- size is needed for parsing packets
data Serialized a = Serialized { packetData :: ByteArray# }
serialize :: a -> IO (Serialized a)
serialize x
= IO (\s ->
case serialize# x s of
(# s', bArr# #) -> (# s', Serialized { packetData=bArr# } #) )
deseri_ :: ByteArray# -> IO a
deseri_ bArr# = IO (\s -> case deserialize# bArr# s of
(# s', newData #) -> (# s', newData #))
deserialize :: Serialized a -> IO a
deserialize ( Serialized{..} ) = do deseri_ packetData
-----------------------------------------------
-- Show Instance:
-- print packet as Word array in 4 columns
-----------------------------------------------
instance Typeable a => Show (Serialized a) where
show (Serialized {..} )
= "Serialization Packet, size " ++ show size
++ ", type " ++ show t ++ "\n"
++ showWArray (UArray 0 (size-1) size packetData )
where size = case sizeofByteArray# packetData of
sz# -> (I# sz# ) `div` sizeOf(undefined::Word)
t = typeOf ( undefined :: a )
-- show a serialized structure as a packet (Word Array)
showWArray :: UArray Int Word -> String
showWArray arr = unlines [ show i ++ ":" ++ unwords (map showH row)
| (i,row) <- zip [0,4..] elRows ]
where showH w = -- "\t0x" ++ showHex w " "
printf "\t0x%08x " w
elRows = takeEach 4 (elems arr)
takeEach :: Int -> [a] -> [[a]]
takeEach n [] = []
takeEach n xs = first:takeEach n rest
where (first,rest) = splitAt n xs
-----------------------------------------------
-- Read Instance, using ReadP parser (base-4.2)
-- eats the format we output above (Show), but
-- can also consume other formats of the array
-- (not implemented yet).
-----------------------------------------------
instance Typeable a => Read (Serialized a)
where readsPrec _ input
= case parseP input of
[] -> error "No parse for packet"
[((sz,tp,dat),r)]
-> let !(UArray _ _ _ arr# ) = listArray (0,sz-1) dat
t = typeOf (undefined::a)
in if show t == tp
then [(Serialized arr# , r)]
else error ("type error during packet parse: "
++ show t ++ " vs. " ++ tp)
other -> error ("Ambiguous parse for packet: " ++ show other)
-- Parser: read header with size and type, then iterate over array
-- values, reading several hex words in one row, separated by tab and
-- space. Size is needed here to avoid returning prefixes.
parseP :: ReadS (Int, String,[Word])
parseP = readP_to_S $
do string "Serialization Packet, size "
sz_str <- munch1 isDigit
let sz = read sz_str::Int
string ", type "
tp <- munch1 (not . (== '\n'))
newline
let startRow = do { many1 digit; colon; tabSpace }
row = do { startRow; sepBy1 hexNum tabSpace }
valss <- sepBy1 row newline
skipSpaces -- eat remaining spaces
let vals = concat valss
l = length vals
-- filter out wrong lengths:
if (sz /= length vals) then pfail
else return (sz, tp, vals)
digit = satisfy isDigit
colon = satisfy (==':')
tabSpace = munch1 ( \x -> x `elem` " \t" )
newline = munch1 (\x -> x `elem` " \n")
hexNum :: ReadP Word -- we are fixing the type to what we need
hexNum = do string "0x"
ds <- munch hexDigit
return (read ("0x" ++ ds))
where hexDigit = (\x -> x `elem` "0123456789abcdefABCDEF")
------------------------------------------------------------------
-- Binary instance, and some convenience wrappers
-- we make our life simple and construct/deconstruct Word (U)Arrays,
-- quite as we did in the Show/Read instances above already. The
-- TypeRep, however, has to be shown to a string to serialize.
instance Typeable a => Binary (Serialized a) where
-- put :: (Serialized a) -> Put
put (Serialized bArr#)
= do let typeStr = show (typeOf (undefined :: a))
arr = UArray 0 (sz-1) sz bArr# :: UArray Int Word
sz = case sizeofByteArray# bArr# of
sz# -> (I# sz# ) `div` sizeOf(undefined::Word)
put typeStr
put arr
get = do typeStr <- get :: Get String
uarr <- get :: Get (UArray Int Word)
let !(UArray _ _ sz bArr#) = uarr
tp = typeOf (undefined :: a) -- for type check
if (show tp == typeStr)
then return ( Serialized bArr# )
else error ("Type error during packet parse:\n\tExpected "
++ show tp ++ ", found " ++ typeStr ++ ".")
encodeToFile :: Typeable a => FilePath -> a -> IO ()
encodeToFile path x = serialize x >>= encodeFile path
decodeFromFile :: Typeable a => FilePath -> IO a
decodeFromFile path = decodeFile path >>= deserialize
| jberthold/rts-serialisation | PackToMemIFL10.hs | bsd-3-clause | 7,088 | 0 | 20 | 2,328 | 1,821 | 968 | 853 | -1 | -1 |
{-# OPTIONS_GHC -Wall #-}
{-| The Abstract Syntax Tree (AST) for expressions comes in a couple formats.
The first is the fully general version and is labeled with a prime (Expr').
The others are specialized versions of the AST that represent specific phases
of the compilation process. I expect there to be more phases as we begin to
enrich the AST with more information.
-}
module AST.Expression.General where
import AST.PrettyPrint
import Text.PrettyPrint as P
import AST.Type (Type)
import qualified AST.Annotation as Annotation
import qualified AST.Helpers as Help
import qualified AST.Literal as Literal
import qualified AST.Pattern as Pattern
import qualified AST.Variable as Var
---- GENERAL AST ----
{-| This is a fully general Abstract Syntax Tree (AST) for expressions. It has
"type holes" that allow us to enrich the AST with additional information as we
move through the compilation process. The type holes are used to represent:
ann: Annotations for arbitrary expressions. Allows you to add information
to the AST like position in source code or inferred types.
def: Definition style. The source syntax separates type annotations and
definitions, but after parsing we check that they are well formed and
collapse them.
var: Representation of variables. Starts as strings, but is later enriched
with information about what module a variable came from.
-}
type Expr annotation definition variable =
Annotation.Annotated annotation (Expr' annotation definition variable)
data Expr' ann def var
= Literal Literal.Literal
| Var var
| Range (Expr ann def var) (Expr ann def var)
| ExplicitList [Expr ann def var]
| Binop var (Expr ann def var) (Expr ann def var)
| Lambda (Pattern.Pattern var) (Expr ann def var)
| App (Expr ann def var) (Expr ann def var)
| MultiIf [(Expr ann def var,Expr ann def var)]
| Let [def] (Expr ann def var)
| Case (Expr ann def var) [(Pattern.Pattern var, Expr ann def var)]
| Data String [Expr ann def var]
| Access (Expr ann def var) String
| Remove (Expr ann def var) String
| Insert (Expr ann def var) String (Expr ann def var)
| Modify (Expr ann def var) [(String, Expr ann def var)]
| Record [(String, Expr ann def var)]
-- for type checking and code gen only
| PortIn String (Type var)
| PortOut String (Type var) (Expr ann def var)
| GLShader String String Literal.GLShaderTipe
deriving (Show)
---- UTILITIES ----
rawVar :: String -> Expr' ann def Var.Raw
rawVar x = Var (Var.Raw x)
localVar :: String -> Expr' ann def Var.Canonical
localVar x = Var (Var.Canonical Var.Local x)
tuple :: [Expr ann def var] -> Expr' ann def var
tuple es = Data ("_Tuple" ++ show (length es)) es
delist :: Expr ann def var -> [Expr ann def var]
delist (Annotation.A _ (Data "::" [h,t])) = h : delist t
delist _ = []
saveEnvName :: String
saveEnvName = "_save_the_environment!!!"
dummyLet :: (Pretty def) => [def] -> Expr Annotation.Region def Var.Canonical
dummyLet defs =
Annotation.none $ Let defs (Annotation.none $ Var (Var.builtin saveEnvName))
instance (Pretty def, Pretty var, Var.ToString var) => Pretty (Expr' ann def var) where
pretty expr =
case expr of
Literal lit ->
pretty lit
Var x ->
pretty x
Range e1 e2 ->
P.brackets (pretty e1 <> P.text ".." <> pretty e2)
ExplicitList es ->
P.brackets (commaCat (map pretty es))
Binop op (Annotation.A _ (Literal (Literal.IntNum 0))) e
| Var.toString op == "-" ->
P.text "-" <> prettyParens e
Binop op e1 e2 ->
P.hang (prettyParens e1) 2 (P.text op'' <+> prettyParens e2)
where
op' = Var.toString op
op'' = if Help.isOp op' then op' else "`" ++ op' ++ "`"
Lambda p e ->
P.text "\\" <> args <+> P.text "->" <+> pretty body
where
(ps,body) = collectLambdas (Annotation.A undefined $ Lambda p e)
args = P.sep (map Pattern.prettyParens ps)
App _ _ ->
P.hang func 2 (P.sep args)
where
func:args =
map prettyParens (collectApps (Annotation.A undefined expr))
MultiIf branches ->
P.text "if" $$ nest 3 (vcat $ map iff branches)
where
iff (b,e) = P.text "|" <+> P.hang (pretty b <+> P.text "->") 2 (pretty e)
Let defs e ->
P.sep
[ P.hang (P.text "let") 4 (P.vcat (map pretty defs))
, P.text "in" <+> pretty e
]
Case e pats ->
P.hang pexpr 2 (P.vcat (map pretty' pats))
where
pexpr = P.sep [ P.text "case" <+> pretty e, P.text "of" ]
pretty' (p,b) = pretty p <+> P.text "->" <+> pretty b
Data "::" [hd,tl] -> pretty hd <+> P.text "::" <+> pretty tl
Data "[]" [] -> P.text "[]"
Data name es
| Help.isTuple name -> P.parens (commaCat (map pretty es))
| otherwise -> P.hang (P.text name) 2 (P.sep (map prettyParens es))
Access e x ->
prettyParens e <> P.text "." <> variable x
Remove e x ->
P.braces (pretty e <+> P.text "-" <+> variable x)
Insert (Annotation.A _ (Remove e y)) x v ->
P.braces $
P.hsep
[ pretty e, P.text "-", variable y, P.text "|"
, variable x, P.equals, pretty v
]
Insert e x v ->
P.braces (pretty e <+> P.text "|" <+> variable x <+> P.equals <+> pretty v)
Modify e fs ->
P.braces $
P.hang
(pretty e <+> P.text "|")
4
(commaSep $ map field fs)
where
field (k,v) = variable k <+> P.text "<-" <+> pretty v
Record fs ->
P.sep
[ P.cat (zipWith (<+>) (P.lbrace : repeat P.comma) (map field fs))
, P.rbrace
]
where
field (field, value) =
variable field <+> P.equals <+> pretty value
GLShader _ _ _ -> P.text "[glsl| ... |]"
PortIn name _ -> P.text $ "<port:" ++ name ++ ">"
PortOut _ _ signal -> pretty signal
collectApps :: Expr ann def var -> [Expr ann def var]
collectApps annExpr@(Annotation.A _ expr) =
case expr of
App a b -> collectApps a ++ [b]
_ -> [annExpr]
collectLambdas :: Expr ann def var -> ([Pattern.Pattern var], Expr ann def var)
collectLambdas lexpr@(Annotation.A _ expr) =
case expr of
Lambda pattern body ->
let (ps, body') = collectLambdas body
in (pattern : ps, body')
_ -> ([], lexpr)
prettyParens :: (Pretty def, Pretty var, Var.ToString var) => Expr ann def var -> Doc
prettyParens (Annotation.A _ expr) =
parensIf needed (pretty expr)
where
needed =
case expr of
Binop name _ _ -> not ((Var.toString name) == "::")
Lambda _ _ -> True
App _ _ -> True
MultiIf _ -> True
Let _ _ -> True
Case _ _ -> True
Data name (_:_) -> not (name == "::" || Help.isTuple name)
_ -> False
| JoeyEremondi/utrecht-apa-p1 | src/AST/Expression/General.hs | bsd-3-clause | 7,116 | 0 | 17 | 2,116 | 2,498 | 1,250 | 1,248 | 141 | 8 |
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE RankNTypes #-}
-- |
-- Module:
-- Reflex.Profiled
-- Description:
-- This module contains an instance of the 'Reflex' class that provides
-- profiling/cost-center information.
module Reflex.Profiled where
import Control.Monad
import Control.Monad.Exception
import Control.Monad.Fix
import Control.Monad.Primitive
import Control.Monad.Reader
import Control.Monad.Ref
import Control.Monad.State.Strict (StateT, execStateT, modify)
import Data.Bifunctor
import Data.Coerce
import Data.Dependent.Map (DMap)
import Data.GADT.Compare (GCompare)
import Data.FastMutableIntMap
import Data.IORef
import Data.List
import Data.Map (Map)
import qualified Data.Map.Strict as Map
import Data.Monoid ((<>))
import Data.Ord
import Data.Profunctor.Unsafe ((#.))
import qualified Data.Semigroup as S
import Data.Type.Coercion
import Foreign.Ptr
import GHC.Foreign
import GHC.IO.Encoding
import GHC.Stack
import Reflex.Adjustable.Class
import Reflex.BehaviorWriter.Class
import Reflex.Class
import Reflex.DynamicWriter.Class
import Reflex.EventWriter.Class
import Reflex.Host.Class
import Reflex.NotReady.Class
import Reflex.PerformEvent.Class
import Reflex.PostBuild.Class
import Reflex.Query.Class
import Reflex.Requester.Class
import Reflex.TriggerEvent.Class
import System.IO.Unsafe
data ProfiledTimeline t
{-# NOINLINE profilingData #-}
profilingData :: IORef (Map (Ptr CostCentreStack) Int)
profilingData = unsafePerformIO $ newIORef Map.empty
data CostCentreTree = CostCentreTree
{ _costCentreTree_ownEntries :: !Int
, _costCentreTree_cumulativeEntries :: !Int
, _costCentreTree_children :: !(Map (Ptr CostCentre) CostCentreTree)
}
deriving (Show, Eq, Ord)
instance S.Semigroup CostCentreTree where
(CostCentreTree oa ea ca) <> (CostCentreTree ob eb cb) =
CostCentreTree (oa + ob) (ea + eb) $ Map.unionWith (S.<>) ca cb
instance Monoid CostCentreTree where
mempty = CostCentreTree 0 0 mempty
mappend = (S.<>)
getCostCentreStack :: Ptr CostCentreStack -> IO [Ptr CostCentre]
getCostCentreStack = go []
where go l ccs = if ccs == nullPtr
then return l
else do
cc <- ccsCC ccs
parent <- ccsParent ccs
go (cc : l) parent
toCostCentreTree :: Ptr CostCentreStack -> Int -> IO CostCentreTree
toCostCentreTree ccs n =
foldr (\cc child -> CostCentreTree 0 n $ Map.singleton cc child) (CostCentreTree n n mempty)
<$> getCostCentreStack ccs
getCostCentreTree :: IO CostCentreTree
getCostCentreTree = do
vals <- readIORef profilingData
mconcat <$> mapM (uncurry toCostCentreTree) (Map.toList vals)
formatCostCentreTree :: CostCentreTree -> IO String
formatCostCentreTree cct0 = unlines . reverse <$> execStateT (go 0 cct0) []
where go :: Int -> CostCentreTree -> StateT [String] IO ()
go depth cct = do
let children = sortOn (Down . _costCentreTree_cumulativeEntries . snd) $ Map.toList $ _costCentreTree_children cct
indent = mconcat $ replicate depth " "
forM_ children $ \(cc, childCct) -> do
lbl <- liftIO $ peekCString utf8 =<< ccLabel cc
mdl <- liftIO $ peekCString utf8 =<< ccModule cc
loc <- liftIO $ peekCString utf8 =<< ccSrcSpan cc
let description = mdl <> "." <> lbl <> " (" <> loc <> ")"
modify $ (:) $ indent <> description <> "\t" <> show (_costCentreTree_cumulativeEntries childCct) <> "\t" <> show (_costCentreTree_ownEntries childCct)
go (succ depth) childCct
showProfilingData :: IO ()
showProfilingData = do
putStr =<< formatCostCentreTree =<< getCostCentreTree
writeProfilingData :: FilePath -> IO ()
writeProfilingData p = do
writeFile p =<< formatCostCentreTree =<< getCostCentreTree
newtype ProfiledM m a = ProfiledM { runProfiledM :: m a }
deriving (Functor, Applicative, Monad, MonadFix, MonadException, MonadAsyncException)
profileEvent :: Reflex t => Event t a -> Event t a
profileEvent e = unsafePerformIO $ do
stack <- getCurrentCCS e
let f x = unsafePerformIO $ do
modifyIORef' profilingData $ Map.insertWith (+) stack 1
return $ return $ Just x
return $ pushCheap f e
--TODO: Instead of profiling just the input or output of each one, profile all the inputs and all the outputs
instance Reflex t => Reflex (ProfiledTimeline t) where
newtype Behavior (ProfiledTimeline t) a = Behavior_Profiled { unBehavior_Profiled :: Behavior t a }
newtype Event (ProfiledTimeline t) a = Event_Profiled { unEvent_Profiled :: Event t a }
newtype Dynamic (ProfiledTimeline t) a = Dynamic_Profiled { unDynamic_Profiled :: Dynamic t a }
newtype Incremental (ProfiledTimeline t) p = Incremental_Profiled { unIncremental_Profiled :: Incremental t p }
type PushM (ProfiledTimeline t) = ProfiledM (PushM t)
type PullM (ProfiledTimeline t) = ProfiledM (PullM t)
never = Event_Profiled never
constant = Behavior_Profiled . constant
push f (Event_Profiled e) = coerce $ push (coerce f) $ profileEvent e -- Profile before rather than after; this way fanout won't count against us
pushCheap f (Event_Profiled e) = coerce $ pushCheap (coerce f) $ profileEvent e
pull = Behavior_Profiled . pull . coerce
fanG (Event_Profiled e) = EventSelectorG $ coerce $ selectG (fanG $ profileEvent e)
mergeG :: forall (k :: z -> *) q v. GCompare k
=> (forall a. q a -> Event (ProfiledTimeline t) (v a))
-> DMap k q -> Event (ProfiledTimeline t) (DMap k v)
mergeG nt = Event_Profiled #. mergeG (coerce nt)
switch (Behavior_Profiled b) = coerce $ profileEvent $ switch (coerceBehavior b)
coincidence (Event_Profiled e) = coerce $ profileEvent $ coincidence (coerceEvent e)
current (Dynamic_Profiled d) = coerce $ current d
updated (Dynamic_Profiled d) = coerce $ profileEvent $ updated d
unsafeBuildDynamic (ProfiledM a0) (Event_Profiled a') = coerce $ unsafeBuildDynamic a0 a'
unsafeBuildIncremental (ProfiledM a0) (Event_Profiled a') = coerce $ unsafeBuildIncremental a0 a'
mergeIncrementalG nt res = Event_Profiled $ mergeIncrementalG (coerce nt) (coerce res)
mergeIncrementalWithMoveG nt res = Event_Profiled $ mergeIncrementalWithMoveG (coerce nt) (coerce res)
currentIncremental (Incremental_Profiled i) = coerce $ currentIncremental i
updatedIncremental (Incremental_Profiled i) = coerce $ profileEvent $ updatedIncremental i
incrementalToDynamic (Incremental_Profiled i) = coerce $ incrementalToDynamic i
behaviorCoercion c =
Coercion `trans` behaviorCoercion @t c `trans` Coercion
eventCoercion c =
Coercion `trans` eventCoercion @t c `trans` Coercion
dynamicCoercion c =
Coercion `trans` dynamicCoercion @t c `trans` Coercion
incrementalCoercion c d =
Coercion `trans` incrementalCoercion @t c d `trans` Coercion
mergeIntIncremental = Event_Profiled . mergeIntIncremental .
coerceWith (Coercion `trans` incrementalCoercion Coercion Coercion `trans` Coercion)
fanInt (Event_Profiled e) = coerce $ fanInt $ profileEvent e
deriving instance Functor (Dynamic t) => Functor (Dynamic (ProfiledTimeline t))
deriving instance Applicative (Dynamic t) => Applicative (Dynamic (ProfiledTimeline t))
deriving instance Monad (Dynamic t) => Monad (Dynamic (ProfiledTimeline t))
instance MonadHold t m => MonadHold (ProfiledTimeline t) (ProfiledM m) where
hold v0 (Event_Profiled v') = ProfiledM $ Behavior_Profiled <$> hold v0 v'
holdDyn v0 (Event_Profiled v') = ProfiledM $ Dynamic_Profiled <$> holdDyn v0 v'
holdIncremental v0 (Event_Profiled v') = ProfiledM $ Incremental_Profiled <$> holdIncremental v0 v'
buildDynamic (ProfiledM v0) (Event_Profiled v') = ProfiledM $ Dynamic_Profiled <$> buildDynamic v0 v'
headE (Event_Profiled e) = ProfiledM $ Event_Profiled <$> headE e
now = ProfiledM $ Event_Profiled <$> now
instance MonadSample t m => MonadSample (ProfiledTimeline t) (ProfiledM m) where
sample (Behavior_Profiled b) = ProfiledM $ sample b
instance Adjustable t m => Adjustable (ProfiledTimeline t) (ProfiledM m) where
runWithReplace a0 a' = (fmap . fmap) coerce . lift $
runWithReplace (coerce a0) (coerce $ coerce <$> a')
traverseIntMapWithKeyWithAdjust f dm0 dm' = (fmap . fmap) coerce . lift $
traverseIntMapWithKeyWithAdjust (\k v -> coerce $ f k v) dm0 (coerce dm')
traverseDMapWithKeyWithAdjust f dm0 dm' = (fmap . fmap) coerce . lift $
traverseDMapWithKeyWithAdjust (\k v -> coerce $ f k v) dm0 (coerce dm')
traverseDMapWithKeyWithAdjustWithMove f dm0 dm' = (fmap . fmap) coerce . lift $
traverseDMapWithKeyWithAdjustWithMove (\k v -> coerce $ f k v) dm0 (coerce dm')
instance MonadTrans ProfiledM where
lift = ProfiledM
instance MonadIO m => MonadIO (ProfiledM m) where
liftIO = lift . liftIO
instance PerformEvent t m => PerformEvent (ProfiledTimeline t) (ProfiledM m) where
type Performable (ProfiledM m) = Performable m
performEvent_ = lift . performEvent_ . coerce
performEvent = lift . fmap coerce . performEvent . coerce
instance TriggerEvent t m => TriggerEvent (ProfiledTimeline t) (ProfiledM m) where
newTriggerEvent = first coerce <$> lift newTriggerEvent
newTriggerEventWithOnComplete = first coerce <$> lift newTriggerEventWithOnComplete
newEventWithLazyTriggerWithOnComplete f = coerce <$> lift (newEventWithLazyTriggerWithOnComplete f)
instance PostBuild t m => PostBuild (ProfiledTimeline t) (ProfiledM m) where
getPostBuild = coerce <$> lift getPostBuild
instance NotReady t m => NotReady (ProfiledTimeline t) (ProfiledM m) where
notReady = lift notReady
notReadyUntil = lift . notReadyUntil . coerce
instance BehaviorWriter t w m => BehaviorWriter (ProfiledTimeline t) w (ProfiledM m) where
tellBehavior = lift . tellBehavior . coerce
instance DynamicWriter t w m => DynamicWriter (ProfiledTimeline t) w (ProfiledM m) where
tellDyn = lift . tellDyn . coerce
instance EventWriter t w m => EventWriter (ProfiledTimeline t) w (ProfiledM m) where
tellEvent = lift . tellEvent . coerce
instance MonadQuery t q m => MonadQuery (ProfiledTimeline t) q (ProfiledM m) where
tellQueryIncremental = lift . tellQueryIncremental . coerce
askQueryResult = coerce <$> lift askQueryResult
queryIncremental = fmap coerce . lift . queryIncremental . coerce
instance Requester t m => Requester (ProfiledTimeline t) (ProfiledM m) where
type Request (ProfiledM m) = Request m
type Response (ProfiledM m) = Response m
requesting = fmap coerce . lift . requesting . coerce
requesting_ = lift . requesting_ . coerce
instance MonadRef m => MonadRef (ProfiledM m) where
type Ref (ProfiledM m) = Ref m
newRef = lift . newRef
readRef = lift . readRef
writeRef r = lift . writeRef r
instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger (ProfiledTimeline t) (ProfiledM m) where
newEventWithTrigger = lift . fmap coerce . newEventWithTrigger
newFanEventWithTrigger f = do
es <- lift $ newFanEventWithTrigger f
return $ EventSelector $ \k -> coerce $ select es k
instance MonadReader r m => MonadReader r (ProfiledM m) where
ask = lift ask
local f (ProfiledM a) = ProfiledM $ local f a
reader = lift . reader
instance ReflexHost t => ReflexHost (ProfiledTimeline t) where
type EventTrigger (ProfiledTimeline t) = EventTrigger t
type EventHandle (ProfiledTimeline t) = EventHandle t
type HostFrame (ProfiledTimeline t) = ProfiledM (HostFrame t)
instance MonadSubscribeEvent t m => MonadSubscribeEvent (ProfiledTimeline t) (ProfiledM m) where
subscribeEvent = lift . subscribeEvent . coerce
instance PrimMonad m => PrimMonad (ProfiledM m) where
type PrimState (ProfiledM m) = PrimState m
primitive = lift . primitive
instance MonadReflexHost t m => MonadReflexHost (ProfiledTimeline t) (ProfiledM m) where
type ReadPhase (ProfiledM m) = ProfiledM (ReadPhase m)
fireEventsAndRead ts r = lift $ fireEventsAndRead ts $ coerce r
runHostFrame = lift . runHostFrame . coerce
instance MonadReadEvent t m => MonadReadEvent (ProfiledTimeline t) (ProfiledM m) where
readEvent = lift . fmap coerce . readEvent
| ryantrinkle/reflex | src/Reflex/Profiled.hs | bsd-3-clause | 12,394 | 0 | 20 | 2,157 | 3,931 | 2,001 | 1,930 | -1 | -1 |
import System.Environment (getArgs)
parent :: Int -> Int
parent 3 = 8
parent 8 = 30
parent 10 = 20
parent 20 = 8
parent 29 = 20
parent 52 = 30
parent _ = 0
lca :: Int -> [Int] -> Int
lca w xs | x == y = x
| w == 0 = lca y [x, y]
| y == 0 = lca w [parent x, w]
| otherwise = lca w [x, parent y]
where x = head xs
y = last xs
main :: IO ()
main = do
[inpFile] <- getArgs
input <- readFile inpFile
putStr . unlines . map (show . lca 0 . map read . words) $ lines input
| nikai3d/ce-challenges | moderate/lca.hs | bsd-3-clause | 550 | 0 | 14 | 203 | 282 | 138 | 144 | 21 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Y2018.Day06 (answer1, answer2) where
import qualified Data.Text as Tx
import qualified Data.Text.IO as Tx.IO
import Text.Megaparsec
import Text.Megaparsec.Char
import Text.Megaparsec.Char.Lexer
import qualified Utils.Parser as Utils
import qualified Data.Array as Arr
import Control.Monad
import Data.Foldable
import Data.Void
import Data.Ord
import Data.List
import Data.Maybe
type Parser = Parsec Void Tx.Text
type Coord = (Int, Int)
type Grid = Arr.Array Coord (Maybe Int)
type Grid2 = Arr.Array Coord Bool
answer1, answer2 :: IO ()
answer1 = do
coords <- getData
let grid = makeGrid coords
print $ maximum $ areas grid
answer2 = do
coords <- getData
print $ areas' $ makeGrid' coords 10000
makeGrid :: [Coord] -> Grid
makeGrid coords =
let minX = minimum $ map fst coords
minY = minimum $ map snd coords
maxX = maximum $ map fst coords
maxY = maximum $ map snd coords
b = ((minX, minY), (maxX, maxY))
withIdx = zip [1..] coords
points = do
x <- [minX..maxX]
y <- [minY..maxY]
let dists = sortOn snd $ map (\(i, c) -> (i, manhattan (x, y) c)) withIdx
let v = case dists of
(a:b:_) -> if snd a == snd b then Nothing else Just (fst a)
_ -> Nothing
pure ((x, y), v)
in Arr.array b points
-- ignore infinite area, with any luck the biggest one is already inside
areas :: Grid -> [Int]
areas grid = map length $ group $ sort $ catMaybes $ Arr.elems grid
areas' :: Grid2 -> Int
areas' grid = length $ filter id $ Arr.elems grid
makeGrid' :: [Coord] -> Int -> Grid2
makeGrid' coords maxDist =
let minX = minimum $ map fst coords
minY = minimum $ map snd coords
maxX = maximum $ map fst coords
maxY = maximum $ map snd coords
b = ((minX, minY), (maxX, maxY))
withIdx = zip [1..] coords
points = do
x <- [minX..maxX]
y <- [minY..maxY]
let dist = sum $ map (manhattan (x,y)) coords
pure ((x,y), dist < maxDist)
in Arr.array b points
manhattan :: Coord -> Coord -> Int
manhattan (a, b) (c, d) = abs (c-a) + abs (d-b)
getData :: IO [Coord]
getData = do
raw <- Tx.IO.readFile "data/2018/day06.txt"
case parse gridParser "day06" raw of
Left err -> error $ show err
Right x -> pure x
gridParser :: Parser [Coord]
gridParser = Utils.parseLines $ (,) <$> decimal <* string ", " <*> decimal
test :: [Coord]
test =
[ (1, 1)
, (1, 6)
, (8, 3)
, (3, 4)
, (5, 5)
, (8, 9)
]
| geekingfrog/advent-of-code | src/Y2018/Day06.hs | bsd-3-clause | 2,534 | 0 | 20 | 660 | 1,047 | 565 | 482 | 80 | 3 |
import Data.List
import Text.Parsec
import Text.Parsec.Char
import Text.Parsec.Combinator
presentFile = do
result <- many line
eof
return result
line = do
length <- many1 digit
char 'x'
width <- many1 digit
char 'x'
height <- many1 digit
char '\n' -- This should probably eol, but I can't find what to import for it
return (read length ::Int, read width ::Int, read height ::Int)
parsePresents :: String -> Either ParseError [(Int, Int, Int)]
parsePresents input = parse presentFile "(unknown)" input
unwrapPresents :: Either ParseError [(Int, Int, Int)] -> [(Int,Int,Int)]
unwrapPresents (Left error) = [(0,0,0)]
unwrapPresents (Right xs) = xs
wrapSize presents = sum $ map wrapSizePresent presents
wrapSizePresent :: (Int, Int, Int) -> Int
wrapSizePresent (length, width, height) = 2 * length * width + 2 * width * height + 2 * height * length +
foldl1 min [length *width , width * height, height * length]
ribbonSize presents = sum $ map ribbonSizePresent presents
ribbonSizePresent (length, width, height) = length * width * height + 2 * sum smallesSides
where smallesSides = take 2 $ sort [length, width, height]
main = do
input <- getContents
let presents = unwrapPresents $ parse presentFile "(unknown)" input
putStrLn $ show $ wrapSize presents
putStrLn $ show $ ribbonSize presents
return ()
| sorindumitru/adventofcode | day2/Main.hs | bsd-3-clause | 1,405 | 2 | 13 | 313 | 517 | 263 | 254 | 34 | 1 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE GADTs #-}
{-# LANGUAGE NoRebindableSyntax #-}
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Time.ZH.CN.Rules
( rules
) where
import Prelude
import Duckling.Regex.Types
import Duckling.Time.Helpers
import Duckling.Types
ruleNationalDay :: Rule
ruleNationalDay = Rule
{ name = "national day"
, pattern =
[ regex "(国庆|國慶)(节|節)?"
]
, prod = \_ -> tt $ monthDay 10 1
}
rules :: [Rule]
rules =
[ ruleNationalDay
]
| facebookincubator/duckling | Duckling/Time/ZH/CN/Rules.hs | bsd-3-clause | 674 | 0 | 9 | 129 | 108 | 70 | 38 | 18 | 1 |
-- | Debug.Tasks data-type, to avoid Config dependency on debug code
{-# LANGUAGE TemplateHaskell, DerivingVia #-}
module Lamdu.Debug.Tasks
( Tasks(..), inference, sugaring, layout, database, naming
) where
import qualified Control.Lens as Lens
import qualified Data.Aeson.TH.Extended as JsonTH
import Lamdu.Prelude
data Tasks a = Tasks
{ _inference :: a
, _sugaring :: a
, _layout :: a
, _database :: a
, _naming :: a
} deriving stock (Generic, Generic1, Eq, Show, Functor, Foldable, Traversable)
deriving Applicative via Generically1 Tasks
Lens.makeLenses ''Tasks
JsonTH.derivePrefixed "_" ''Tasks
| lamdu/lamdu | src/Lamdu/Debug/Tasks.hs | gpl-3.0 | 649 | 0 | 8 | 133 | 161 | 97 | 64 | -1 | -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.