code stringlengths 5 1.03M | repo_name stringlengths 5 90 | path stringlengths 4 158 | license stringclasses 15 values | size int64 5 1.03M | n_ast_errors int64 0 53.9k | ast_max_depth int64 2 4.17k | n_whitespaces int64 0 365k | n_ast_nodes int64 3 317k | n_ast_terminals int64 1 171k | n_ast_nonterminals int64 1 146k | loc int64 -1 37.3k | cycloplexity int64 -1 1.31k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
module Ripple.Federation (
resolve,
resolveAgainst,
getRippleTxt,
Alias(..),
ResolvedAlias(..),
-- * Errors
Error(..),
ErrorType(..),
-- * Utils
rippleTxtParser
)where
import Control.Applicative ((<$>), (<*>), (*>), (<*), (<|>), many, some)
import Control.Monad (guard)
import Data.Either (rights)
import Data.Monoid (Monoid(..))
import Data.Word (Word32)
import Control.Error (readZ, fmapLT, throwT, runEitherT, EitherT(..), hoistEither, note)
import UnexceptionalIO (fromIO, runUnexceptionalIO, UnexceptionalIO)
import Control.Exception (fromException)
import Data.Base58Address (RippleAddress)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as BS8 -- eww
import Blaze.ByteString.Builder (Builder)
import Network.URI (URI(..), URIAuth(..), parseAbsoluteURI)
import System.IO.Streams (OutputStream, InputStream)
import System.IO.Streams.Attoparsec (parseFromStream, ParseException(..))
import Network.Http.Client (withConnection, establishConnection, sendRequest, buildRequest, http, setAccept, Response, receiveResponse, RequestBuilder, setContentLength)
import qualified Network.Http.Client as HttpStreams
import Network.HTTP.Types.QueryLike (QueryLike(..))
import Network.HTTP.Types.URI (renderQuery)
import Data.Aeson (FromJSON(..), ToJSON(..), object, (.=), (.:), (.:?))
import qualified Data.Aeson as Aeson
import qualified Data.Attoparsec.ByteString as Attoparsec
import qualified Data.Attoparsec.ByteString.Char8 as Attoparsec hiding (takeTill)
-- * Errors and stuff
data ErrorType = NoSuchUser | NoSupported | NoSuchDomain | InvalidParams | Unavailable deriving (Show, Eq)
data Error = Error {
errorType :: ErrorType,
errorMessage :: Text
} deriving (Show, Eq)
instance Monoid Error where
mempty = Error Unavailable (T.pack "mempty")
mappend _ y = y
instance ToJSON Error where
toJSON (Error typ message) = object [
T.pack "result" .= "error",
T.pack "error" .= typ,
T.pack "error_message" .= message
]
instance FromJSON Error where
parseJSON (Aeson.Object o) =
Error <$>
(o .: T.pack "error") <*>
(o .: T.pack "error_message")
parseJSON _ = fail "Ripple federation errors are always objects."
instance ToJSON ErrorType where
toJSON NoSuchUser = toJSON "noSuchUser"
toJSON NoSupported = toJSON "noSupported"
toJSON NoSuchDomain = toJSON "noSuchDomain"
toJSON InvalidParams = toJSON "invalidParams"
toJSON Unavailable = toJSON "unavailable"
instance FromJSON ErrorType where
parseJSON (Aeson.String s) =
maybe (fail "Unknown Ripple federation error type.") return $
lookup s [
(T.pack "noSuchUser", NoSuchUser),
(T.pack "noSupported", NoSupported),
(T.pack "noSuchDomain", NoSuchDomain),
(T.pack "invalidParams", InvalidParams),
(T.pack "unavailable", Unavailable)
]
parseJSON _ = fail "Ripple federation error type is always a string."
newtype FederationResult a = FederationResult (Either Error a)
instance (FromJSON a) => FromJSON (FederationResult a) where
parseJSON v@(Aeson.Object o) = FederationResult <$> do
r <- o .:? T.pack "result"
case r of
Just x | x == T.pack "error" -> Left <$> Aeson.parseJSON v
_ -> Right <$> Aeson.parseJSON v
parseJSON _ = fail "Ripple federation results are always objects."
-- * Aliases: user@domain.tld
-- | destination\@domain
data Alias = Alias {
destination :: Text,
domain :: Text
} deriving (Eq)
instance Show Alias where
show (Alias dest domain) = T.unpack dest ++ "@" ++ T.unpack domain
instance Read Alias where
readsPrec _ = readParen False go
where
domainchars = ['a'..'z']++['A'..'Z']++['0'..'9']++['-','.']
whitespace = [' ', '\t', '\n', '\r']
go s = case span (/='@') (dropWhile (`elem` whitespace) s) of
(dest, '@':rest) ->
let (domain, end) = span (`elem` domainchars) rest in
[(Alias (T.pack dest) (T.pack domain), end)]
_ -> []
instance QueryLike Alias where
toQuery (Alias dest domain) = toQuery [
("type", T.pack "federation"),
("destination", dest),
("user", dest),
("domain", domain)
]
data ResolvedAlias = ResolvedAlias {
alias :: Alias,
ripple :: RippleAddress,
dt :: Maybe Word32
} deriving (Show, Eq)
instance ToJSON ResolvedAlias where
toJSON (ResolvedAlias (Alias dest domain) ripple dt) = object [
T.pack "federation_json" .= object ([
T.pack "type" .= "federation_record",
T.pack "destination" .= dest,
T.pack "domain" .= domain,
T.pack "destination_address" .= show ripple
] ++ maybe [] (\x -> [T.pack "dt" .= x]) dt)
]
instance FromJSON ResolvedAlias where
parseJSON (Aeson.Object o) = do
o' <- o .: T.pack "federation_json"
dest <- o' .:? T.pack "destination"
ultimateDest <- case dest of
Just (Aeson.String s) -> return s
_ -> o' .: T.pack "user"
ResolvedAlias <$> (
Alias ultimateDest <$>
(o' .: T.pack "domain")
) <*>
(o' .: T.pack "destination_address" >>= readZ) <*>
(o' .:? T.pack "dt")
parseJSON _ = fail "Ripple federation records are always objects."
-- * Resolve aliases
-- | Resolve an alias
resolve :: Alias -> IO (Either Error ResolvedAlias)
resolve a@(Alias u domain) | domain == T.pack "ripple.com" = runEitherT $ do
FederationResult r <- EitherT $ runUnexceptionalIO $ runEitherT $
get (URI "https:" (Just $ URIAuth "" "id.ripple.com" "") ("/v1/user/" ++ T.unpack u) "" "") a
RippleNameResponse x <- hoistEither r
return x
resolve a@(Alias _ domain) = runEitherT $ do
txt <- EitherT (getRippleTxt domain)
uri <- case lookup (T.pack "federation_url") txt of
Just [url] -> hoistEither $ note
(Error NoSupported (T.pack "federation_url in ripple.txt is invalid"))
(parseAbsoluteURI $ T.unpack url)
_ ->
throwT $ Error NoSupported (T.pack "No federation_url in ripple.txt")
EitherT (a `resolveAgainst` uri)
-- | Resolve an alias against a known federation_url
resolveAgainst :: Alias -> URI -> IO (Either Error ResolvedAlias)
resolveAgainst a uri = runEitherT $ do
FederationResult r <- EitherT $ runUnexceptionalIO $ runEitherT $ get uri a
hoistEither r
-- | Lookup the ripple.txt for a domain
getRippleTxt ::
Text -- ^ Domain to lookup
-> IO (Either Error [(Text, [Text])])
getRippleTxt domain = runUnexceptionalIO $ runEitherT $
tryOne (uri domain') <|>
tryOne (uri ("www." ++ domain')) <|>
tryOne (uri ("ripple." ++ domain'))
where
domain' = T.unpack domain
uri d = URI "https:" (Just $ URIAuth "" d "") "/ripple.txt" "" ""
tryOne uri =
(hoistEither =<<) $
fmapLT (const $ Error Unavailable (T.pack "Network error")) $ fromIO $
oneShotHTTP HttpStreams.GET uri
(setContentLength 0 >> setAccept (BS8.pack "text/plain"))
HttpStreams.emptyBody (parseResponse rippleTxtParser)
-- | Attoparsec parser for ripple.txt
rippleTxtParser :: Attoparsec.Parser [(Text, [Text])]
rippleTxtParser = some section
where
section = do
h <- header >>= utf8
ls <- many (Attoparsec.eitherP comment line)
ls' <- mapM utf8 (rights ls)
return (h, ls')
utf8 bs = case T.decodeUtf8' bs of
Right r -> return r
Left e -> fail $ show e
header = Attoparsec.skipSpace *>
Attoparsec.char '[' *> Attoparsec.takeTill(==0x5D) <* Attoparsec.char ']'
line = Attoparsec.skipSpace *> do
c <- Attoparsec.peekChar
guard (c /= Just '[')
Attoparsec.takeTill Attoparsec.isEndOfLine <* Attoparsec.endOfLine
comment = Attoparsec.skipSpace *> Attoparsec.char '#' *>
Attoparsec.takeTill Attoparsec.isEndOfLine <* Attoparsec.endOfLine
-- * Internal Helpers
get :: (QueryLike a, FromJSON b) => URI -> a -> EitherT Error UnexceptionalIO b
get uri payload =
(hoistEither =<<) $
fmapLT (const $ Error Unavailable (T.pack "Network error")) $ fromIO $
oneShotHTTP HttpStreams.GET uri'
(setContentLength 0 >> setAccept (BS8.pack "application/json"))
HttpStreams.emptyBody safeJSONresponse
where
uri' = uri { uriQuery = BS8.unpack $ renderQuery True (toQuery payload)}
safeJSONresponse :: (Aeson.FromJSON a) => Response -> InputStream ByteString -> IO (Either Error a)
safeJSONresponse resp i = runEitherT $ do
v <- EitherT $ parseResponse Aeson.json' resp i
case Aeson.fromJSON v of
Aeson.Success a -> return a
Aeson.Error e -> throwT $ Error Unavailable $
T.pack $ "JSON parser error: " ++ e
parseResponse :: Attoparsec.Parser a -> Response -> InputStream ByteString -> IO (Either Error a)
parseResponse parser _ i = runUnexceptionalIO $ runEitherT $
fmapLT (\e -> handle e (fromException e)) $ fromIO $
parseFromStream parser i
where
parseError e = Error Unavailable (T.pack $ "Parse error: " ++ show e)
handle _ (Just (ParseException e)) = parseError e
handle e _ = Error Unavailable (T.pack $ "Exception: " ++ show e)
oneShotHTTP :: HttpStreams.Method -> URI -> RequestBuilder () -> (OutputStream Builder -> IO ()) -> (Response -> InputStream ByteString -> IO b) -> IO b
oneShotHTTP method uri req body handler = do
req' <- buildRequest $ do
http method (BS8.pack $ uriPath uri ++ uriQuery uri)
req
withConnection (establishConnection url) $ \conn -> do
sendRequest conn req' body
receiveResponse conn handler
where
url = BS8.pack $ show uri -- URI can only have ASCII, so should be safe
-- * Temporary stuff to handle centralised Ripple Names hack
newtype RippleNameResponse = RippleNameResponse ResolvedAlias
instance FromJSON RippleNameResponse where
parseJSON (Aeson.Object o) = RippleNameResponse <$> (
ResolvedAlias <$> (
Alias <$>
(o .: T.pack "username") <*>
return (T.pack "ripple.com")
) <*>
(o .: T.pack "address" >>= readZ) <*>
return Nothing
)
parseJSON _ = fail "Ripple federation records are always objects."
| singpolyma/ripple-federation-haskell | Ripple/Federation.hs | isc | 9,768 | 433 | 18 | 1,784 | 3,466 | 1,895 | 1,571 | 220 | 2 |
module Main where
import Control.Monad (forever)
import Network.Socket hiding (recv)
import Network.Socket.ByteString (recv, sendAll)
logAndEcho :: Socket -> IO ()
logAndEcho sock = forever $ do
(soc, _) <- accept sock
printAndKickback soc
close soc
where printAndKickback conn = do
msg <- recv conn 1024
print msg
sendAll conn msg
main :: IO ()
main = withSocketsDo $ do
addrinfos <- getAddrInfo (Just (defaultHints {addrFlags = [AI_PASSIVE]})) Nothing (Just "79")
let serveraddr = head addrinfos
sock <- socket (addrFamily serveraddr) Stream defaultProtocol
bind sock (addrAddress serveraddr)
listen sock 1
logAndEcho sock
close sock
| NickAger/LearningHaskell | HaskellProgrammingFromFirstPrinciples/Chapter31/fingerd/src/Debug.hs | mit | 720 | 0 | 15 | 177 | 254 | 123 | 131 | 22 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module CliOpts (
parseCliOpts
) where
import Data.Monoid ((<>))
import Options.Applicative
-- nanopage imports
import Config
import FileDB (Mode (..))
helpHeader :: String
helpHeader = "This is nanoPage, a minimalistic flat-file CMS written in Haskell. For more information see http://nanopage.li/."
helpDescription :: String
helpDescription = "Run the nanoPage webserver."
-- | Server config info
defaultPortNumber = 3000 :: Int
defaultServerName = "localhost" :: String
parseOpts :: Parser NanopageConfig
parseOpts = NanopageConfig
<$> option auto (
long "port" <>
short 'p' <>
help "port number" <>
showDefault <>
value defaultPortNumber <>
metavar "INT"
) <*> strOption (
long "server" <>
short 'n' <>
help "Server name" <>
showDefault <>
value defaultServerName <>
metavar "STRING"
) <*> option auto (
long "mode" <>
short 'm' <>
help "Server mode can be PROD or ADMIN. The admin pages are only shown in ADMIN mode." <>
showDefault <>
value PROD <>
metavar "MODE"
) <*> strOption (
long "working-dir" <>
short 'C' <>
help "Working directory" <>
showDefault <>
value "." <>
metavar "STRING"
)
parseCliOpts :: IO NanopageConfig
parseCliOpts = execParser $ info (parseOpts <**> helper) (fullDesc <> progDesc helpDescription <> header helpHeader)
| mayeranalytics/nanoPage | src/CliOpts.hs | mit | 1,601 | 0 | 16 | 483 | 324 | 165 | 159 | 46 | 1 |
module Game.TypeClasses where
class Describable a where
describe :: a -> String
class Drawable a where
filename :: a -> String
| maqqr/psycho-bongo-fight | Game/TypeClasses.hs | mit | 137 | 0 | 7 | 31 | 42 | 22 | 20 | 5 | 0 |
{-# LANGUAGE BangPatterns #-}
module Document.Test where
import Control.Exception (evaluate)
import Document.Document
-- import qualified Document.Tests.CompCalc as CC
import qualified Document.Tests.Cubes as Cubes
import qualified Document.Tests.Definitions as Defs
-- import qualified Document.Tests.IndirectEq as Ind
import qualified Document.Tests.Lambdas as Lambdas
import qualified Document.Tests.LockFreeDeque as LFD
import qualified Document.Tests.Phase as Phase
import qualified Document.Tests.Puzzle as Puz
import qualified Document.Tests.SmallMachine as SMch
import qualified Document.Tests.TrainStation as Train
import qualified Document.Tests.TrainStationRefinement as Ref
import qualified Document.Tests.TrainStationSets as Set
import qualified Document.Tests.UnlessExcept as UE
-- import qualified Document.Tests.Suite as Suite
import qualified Document.Scope (Scope)
import qualified Document.ExprScope as ESc
import qualified Document.VarScope as VSc
import qualified Document.MachineSpec as MSpec
import qualified Document.Tests.GarbageCollector as Gar
import qualified Document.Tests.Parser as Parser
import qualified Document.Tests.TerminationDetection as Term
import qualified Document.Phase.Test as PhTest
import Document.Tests.Suite (find_errors)
import Document.Phase.Declarations as PDecl
import Document.Phase.Expressions as PExp
import Latex.Parser
import Latex.Monad
import Test.UnitTest
import UnitB.UnitB
-- Libraries
import Test.QuickCheck.AxiomaticClass
import Utilities.Syntactic
test_case :: TestCase
test_case = test
test :: TestCase
test = test_cases
"Unit-B Document"
[ stringCase "basic syntax and scopes" case1 result1
, LFD.test_case
-- , CC.test_case
-- , Ind.test_case
, SMch.test_case
, stringCase "Contextual predicate visibility rules" case2 result2
, Puz.test_case
, UE.test_case
, PhTest.test_case
, Cubes.test_case
, Defs.test_case
, Train.test_case
, Lambdas.test_case
, Phase.test_case
, Ref.test_case
, Set.test_case
, Gar.test_case
, Term.test_case
, Parser.test_case
, QuickCheckProps "QuickCheck spec of machine parser"
MSpec.run_spec
, all_properties
, check_axioms
, QuickCheckProps "expression phase, properties"
PExp.check_props
, QuickCheckProps "expression scope, properties"
ESc.run_tests
, QuickCheckProps "variable scope, properties"
VSc.run_tests
]
result1 :: String
result1 = unlines
[ " o m/enter/FIS/in@prime/goal"
, " o m/enter/FIS/in@prime/hypotheses"
, " o m/enter/FIS/in@prime/relation"
, " o m/enter/FIS/in@prime/step 1"
, "passed 4 / 4"
]
path1 :: FilePath
path1 = [path|Tests/new_syntax.tex|]
case1 :: IO String
case1 = do
r <- parse_machine path1
case r of
Right [m] -> do
(s,_,_) <- str_verify_machine m
return s
Left x -> return $ show_err x
x -> return $ show x
result2 :: String
result2 = unlines
[ "error 23:12:"
, " predicate is undefined: 'a1'"
]
path2 :: FilePath
path2 = [path|Tests/new_syntax-err0.tex|]
case2 :: IO String
case2 = find_errors path2
check_axioms :: TestCase
check_axioms = QuickCheckProps "conformance of instances to type class axioms"
$(quickCheckClassesWith [''Document.Scope.Scope])
all_properties :: TestCase
all_properties = aCase "the parser is exception free"
(evaluate (all_machines tree) >> return ()) ()
tree0' :: LatexGen ()
tree0' = begin "machine" [] $ do
brackets' Square $ return ()
brackets' Curly $ do
text "\FS1"
text "\n"
text "7\130\220.1\169"
text "\n"
text "N\183T\241N"
text "\n"
brackets' Curly $ return ()
begin "=F\129\216\RS\DC3\USG!0\150`\b\DC2I=}'\DC10\\\196-e9\STX\168\166Nt" [] $ do
begin "\239\n\132\&0\DC4X\nNr>#a\EOT;\183\188\162\231!l\DC1\STXf\FS" [] $ return ()
text "9\""
open Square
text "\178\179\&6\190s\155\ETB`"
text "\n"
text "\252\NUL0Sz,\215\255S\235\248\RSAu\251\217"
text "\n"
text "\198\&6fH\231e"
command "\\\203" []
text "#"
open Square
text "\167\SOH\242\&7\137iS"
text "\n"
tree0 :: LatexDoc
tree0 = makeLatex "" tree0'
tree :: LatexDoc
tree = makeLatex "" $ do
begin "fschedule" [] $ do
text "ZK\DC3^\EOT<+\202\&0\144Ny\141;\129\242"
text "\n"
text "\v"
text "@\252l\EOT\183\128\SOH\199"
text "\f"
text "\DC20\ETB\btT\199p9\248Q&\144\207\221u"
text "\n"
text "\SOH\169\138H\168\&5Z;\EMs\243ddQV\193.\201\184zv\191T\DELm;"
text "\n"
text "\198\&7\230m'\SIq7"
close Square
text "\177"
close Curly
text "1\173\180Bu\aHBJ\SI\ETX"
text "\n"
brackets' Square $ do
text "\FSI"
text " "
text "\175HD\US!0\174\242\DC2Nhx\199Z\143\238+\253?\181k\204?X"
text "\n"
text "\t"
text "pL/5\212\SOH\164\152),\SUBD\213\US~\199"
close Curly
text "s\209\184\228\239m\DC4"
text "\n"
begin "fschedule" [] $ do
text "x"
text "\n"
text "/\SYNu\203%/6\221Q\249\193"
text " "
text "gt\DC2\141"
text "\n"
text "\214\162h\DC4!B5p\227\NUL9"
text "\n"
text "c8\136\230\&3H%\SOHi\154wyu\143pc"
close Square
text "9\147"
text "\r"
text "\224iZO\169\223"
text "\n"
tree0'
text "\186z;\139\254\SIk1wr\a~\131"
close Square
text "l_\192!\170"
text "\n"
li :: Int -> Int -> LineInfo
li i j = LI "" i j
| literate-unitb/literate-unitb | src/Document/Test.hs | mit | 6,676 | 0 | 17 | 2,343 | 1,245 | 632 | 613 | -1 | -1 |
-- Representation.hs
module Graphter.Representation where
--
-- Vertex representation
--
data Vertex = Vertex {
vertexName :: String,
vertexWeight :: Int
} deriving(Show, Eq)
--
-- Edge representation
--
data Edge = Edge {
startVertex :: Vertex,
endVertex :: Vertex,
edgeWeight :: Int
} deriving(Show, Eq)
--
-- Graph representation
--
data Type = Directed | Undirected
deriving(Show, Eq)
data Graph = Graph {
graphType :: Type,
graphVertices :: [Vertex],
graphEdges :: [Edge]
} deriving(Show, Eq)
| martinstarman/graphter | src/Graphter/Representation.hs | mit | 543 | 0 | 9 | 121 | 151 | 95 | 56 | 17 | 0 |
module DeepRegion where
type Point = (Double,Double)
type Radius = Double
magnitude :: Point -> Double
magnitude (x,y) = sqrt (x^2 + y^2)
data Region = Circle Radius
| Intersect Region Region
| Outside Region
| Union Region Region
circle r = Circle r
outside r = Outside r
r1 /\ r2 = Intersect r1 r2
r1 \/ r2 = Union r1 r2
p `inRegion` (Circle r) = magnitude p <= r
p `inRegion` (Outside r) = not (p `inRegion` r)
p `inRegion` (Intersect r1 r2) = p `inRegion` r1 && p `inRegion` r2
p `inRegion` (Union r1 r2) = p `inRegion` r1 || p `inRegion` r2
annulus :: Radius -> Radius -> Region
annulus r1 r2 = outside (circle r1) /\ (circle r2)
| josefs/deep-shallow-paper | DeepRegion.hs | mit | 713 | 0 | 9 | 202 | 318 | 170 | 148 | 19 | 1 |
{-# OPTIONS_GHC -w #-}
module LineSintaticScanner (parseLine) where
import LineLexicalScanner
import BasicTypes
-- parser produced by Happy Version 1.18.9
data HappyAbsSyn t4 t5 t6
= HappyTerminal (Token)
| HappyErrorToken Int
| HappyAbsSyn4 t4
| HappyAbsSyn5 t5
| HappyAbsSyn6 t6
action_0 (7) = happyShift action_6
action_0 (8) = happyShift action_7
action_0 (9) = happyShift action_8
action_0 (10) = happyShift action_9
action_0 (4) = happyGoto action_3
action_0 (5) = happyGoto action_4
action_0 (6) = happyGoto action_5
action_0 _ = happyFail
action_1 (7) = happyShift action_2
action_1 _ = happyFail
action_2 (9) = happyShift action_14
action_2 _ = happyFail
action_3 (11) = happyAccept
action_3 _ = happyFail
action_4 (7) = happyShift action_12
action_4 (8) = happyShift action_7
action_4 (9) = happyShift action_8
action_4 (10) = happyShift action_13
action_4 (5) = happyGoto action_4
action_4 (6) = happyGoto action_11
action_4 _ = happyReduce_9
action_5 _ = happyReduce_4
action_6 (9) = happyShift action_10
action_6 _ = happyReduce_5
action_7 _ = happyReduce_6
action_8 _ = happyReduce_7
action_9 (11) = happyReduce_8
action_9 _ = happyReduce_8
action_10 (8) = happyShift action_16
action_10 (10) = happyShift action_15
action_10 _ = happyFail
action_11 _ = happyReduce_10
action_12 _ = happyReduce_5
action_13 _ = happyReduce_8
action_14 (10) = happyShift action_15
action_14 _ = happyFail
action_15 (8) = happyShift action_17
action_15 _ = happyFail
action_16 _ = happyReduce_2
action_17 _ = happyReduce_1
happyReduce_1 = happyReduce 4 4 happyReduction_1
happyReduction_1 (_ `HappyStk`
(HappyTerminal (TokenText happy_var_3)) `HappyStk`
_ `HappyStk`
_ `HappyStk`
happyRest)
= HappyAbsSyn4
(Condition happy_var_3
) `HappyStk` happyRest
happyReduce_2 = happySpecReduce_3 4 happyReduction_2
happyReduction_2 _
_
_
= HappyAbsSyn4
(EndCondition
)
happyReduce_3 = happySpecReduce_1 4 happyReduction_3
happyReduction_3 (HappyTerminal (TokenText happy_var_1))
= HappyAbsSyn4
(CodeLine happy_var_1
)
happyReduction_3 _ = notHappyAtAll
happyReduce_4 = happySpecReduce_1 4 happyReduction_4
happyReduction_4 (HappyAbsSyn6 happy_var_1)
= HappyAbsSyn4
(CodeLine (foldl (++) [] happy_var_1)
)
happyReduction_4 _ = notHappyAtAll
happyReduce_5 = happySpecReduce_1 5 happyReduction_5
happyReduction_5 _
= HappyAbsSyn5
("/*"
)
happyReduce_6 = happySpecReduce_1 5 happyReduction_6
happyReduction_6 _
= HappyAbsSyn5
("*/"
)
happyReduce_7 = happySpecReduce_1 5 happyReduction_7
happyReduction_7 _
= HappyAbsSyn5
("#"
)
happyReduce_8 = happySpecReduce_1 5 happyReduction_8
happyReduction_8 (HappyTerminal (TokenText happy_var_1))
= HappyAbsSyn5
(happy_var_1
)
happyReduction_8 _ = notHappyAtAll
happyReduce_9 = happySpecReduce_1 6 happyReduction_9
happyReduction_9 (HappyAbsSyn5 happy_var_1)
= HappyAbsSyn6
([happy_var_1]
)
happyReduction_9 _ = notHappyAtAll
happyReduce_10 = happySpecReduce_2 6 happyReduction_10
happyReduction_10 (HappyAbsSyn6 happy_var_2)
(HappyAbsSyn5 happy_var_1)
= HappyAbsSyn6
(happy_var_1 : happy_var_2
)
happyReduction_10 _ _ = notHappyAtAll
happyNewToken action sts stk [] =
action 11 11 notHappyAtAll (HappyState action) sts stk []
happyNewToken action sts stk (tk:tks) =
let cont i = action i i tk (HappyState action) sts stk tks in
case tk of {
TokenCommentBegin -> cont 7;
TokenCommentEnd -> cont 8;
TokenPlasmaCutter -> cont 9;
TokenText happy_dollar_dollar -> cont 10;
_ -> happyError' (tk:tks)
}
happyError_ 11 tk tks = happyError' tks
happyError_ _ tk tks = happyError' (tk:tks)
newtype HappyIdentity a = HappyIdentity a
happyIdentity = HappyIdentity
happyRunIdentity (HappyIdentity a) = a
instance Monad HappyIdentity where
return = HappyIdentity
(HappyIdentity p) >>= q = q p
happyThen :: () => HappyIdentity a -> (a -> HappyIdentity b) -> HappyIdentity b
happyThen = (>>=)
happyReturn :: () => a -> HappyIdentity a
happyReturn = (return)
happyThen1 m k tks = (>>=) m (\a -> k a tks)
happyReturn1 :: () => a -> b -> HappyIdentity a
happyReturn1 = \a tks -> (return) a
happyError' :: () => [(Token)] -> HappyIdentity a
happyError' = HappyIdentity . parseError
expr tks = happyRunIdentity happySomeParser where
happySomeParser = happyThen (happyParse action_0 tks) (\x -> case x of {HappyAbsSyn4 z -> happyReturn z; _other -> notHappyAtAll })
happySeq = happyDontSeq
parseError :: [Token] -> a
parseError _ = error "Line parse error"
parseLine :: String -> Line
parseLine = expr . scanTokens
{-# LINE 1 "templates/GenericTemplate.hs" #-}
{-# LINE 1 "templates/GenericTemplate.hs" #-}
{-# LINE 1 "<built-in>" #-}
{-# LINE 1 "<command-line>" #-}
{-# LINE 1 "templates/GenericTemplate.hs" #-}
-- Id: GenericTemplate.hs,v 1.26 2005/01/14 14:47:22 simonmar Exp
{-# LINE 30 "templates/GenericTemplate.hs" #-}
{-# LINE 51 "templates/GenericTemplate.hs" #-}
{-# LINE 61 "templates/GenericTemplate.hs" #-}
{-# LINE 70 "templates/GenericTemplate.hs" #-}
infixr 9 `HappyStk`
data HappyStk a = HappyStk a (HappyStk a)
-----------------------------------------------------------------------------
-- starting the parse
happyParse start_state = happyNewToken start_state notHappyAtAll notHappyAtAll
-----------------------------------------------------------------------------
-- Accepting the parse
-- If the current token is (1), it means we've just accepted a partial
-- parse (a %partial parser). We must ignore the saved token on the top of
-- the stack in this case.
happyAccept (1) tk st sts (_ `HappyStk` ans `HappyStk` _) =
happyReturn1 ans
happyAccept j tk st sts (HappyStk ans _) =
(happyReturn1 ans)
-----------------------------------------------------------------------------
-- Arrays only: do the next action
{-# LINE 148 "templates/GenericTemplate.hs" #-}
-----------------------------------------------------------------------------
-- HappyState data type (not arrays)
newtype HappyState b c = HappyState
(Int -> -- token number
Int -> -- token number (yes, again)
b -> -- token semantic value
HappyState b c -> -- current state
[HappyState b c] -> -- state stack
c)
-----------------------------------------------------------------------------
-- Shifting a token
happyShift new_state (1) tk st sts stk@(x `HappyStk` _) =
let (i) = (case x of { HappyErrorToken (i) -> i }) in
-- trace "shifting the error token" $
new_state i i tk (HappyState (new_state)) ((st):(sts)) (stk)
happyShift new_state i tk st sts stk =
happyNewToken new_state ((st):(sts)) ((HappyTerminal (tk))`HappyStk`stk)
-- happyReduce is specialised for the common cases.
happySpecReduce_0 i fn (1) tk st sts stk
= happyFail (1) tk st sts stk
happySpecReduce_0 nt fn j tk st@((HappyState (action))) sts stk
= action nt j tk st ((st):(sts)) (fn `HappyStk` stk)
happySpecReduce_1 i fn (1) tk st sts stk
= happyFail (1) tk st sts stk
happySpecReduce_1 nt fn j tk _ sts@(((st@(HappyState (action))):(_))) (v1`HappyStk`stk')
= let r = fn v1 in
happySeq r (action nt j tk st sts (r `HappyStk` stk'))
happySpecReduce_2 i fn (1) tk st sts stk
= happyFail (1) tk st sts stk
happySpecReduce_2 nt fn j tk _ ((_):(sts@(((st@(HappyState (action))):(_))))) (v1`HappyStk`v2`HappyStk`stk')
= let r = fn v1 v2 in
happySeq r (action nt j tk st sts (r `HappyStk` stk'))
happySpecReduce_3 i fn (1) tk st sts stk
= happyFail (1) tk st sts stk
happySpecReduce_3 nt fn j tk _ ((_):(((_):(sts@(((st@(HappyState (action))):(_))))))) (v1`HappyStk`v2`HappyStk`v3`HappyStk`stk')
= let r = fn v1 v2 v3 in
happySeq r (action nt j tk st sts (r `HappyStk` stk'))
happyReduce k i fn (1) tk st sts stk
= happyFail (1) tk st sts stk
happyReduce k nt fn j tk st sts stk
= case happyDrop (k - ((1) :: Int)) sts of
sts1@(((st1@(HappyState (action))):(_))) ->
let r = fn stk in -- it doesn't hurt to always seq here...
happyDoSeq r (action nt j tk st1 sts1 r)
happyMonadReduce k nt fn (1) tk st sts stk
= happyFail (1) tk st sts stk
happyMonadReduce k nt fn j tk st sts stk =
happyThen1 (fn stk tk) (\r -> action nt j tk st1 sts1 (r `HappyStk` drop_stk))
where (sts1@(((st1@(HappyState (action))):(_)))) = happyDrop k ((st):(sts))
drop_stk = happyDropStk k stk
happyMonad2Reduce k nt fn (1) tk st sts stk
= happyFail (1) tk st sts stk
happyMonad2Reduce k nt fn j tk st sts stk =
happyThen1 (fn stk tk) (\r -> happyNewToken new_state sts1 (r `HappyStk` drop_stk))
where (sts1@(((st1@(HappyState (action))):(_)))) = happyDrop k ((st):(sts))
drop_stk = happyDropStk k stk
new_state = action
happyDrop (0) l = l
happyDrop n ((_):(t)) = happyDrop (n - ((1) :: Int)) t
happyDropStk (0) l = l
happyDropStk n (x `HappyStk` xs) = happyDropStk (n - ((1)::Int)) xs
-----------------------------------------------------------------------------
-- Moving to a new state after a reduction
{-# LINE 246 "templates/GenericTemplate.hs" #-}
happyGoto action j tk st = action j j tk (HappyState action)
-----------------------------------------------------------------------------
-- Error recovery ((1) is the error token)
-- parse error if we are in recovery and we fail again
happyFail (1) tk old_st _ stk@(x `HappyStk` _) =
let (i) = (case x of { HappyErrorToken (i) -> i }) in
-- trace "failing" $
happyError_ i tk
{- We don't need state discarding for our restricted implementation of
"error". In fact, it can cause some bogus parses, so I've disabled it
for now --SDM
-- discard a state
happyFail (1) tk old_st (((HappyState (action))):(sts))
(saved_tok `HappyStk` _ `HappyStk` stk) =
-- trace ("discarding state, depth " ++ show (length stk)) $
action (1) (1) tk (HappyState (action)) sts ((saved_tok`HappyStk`stk))
-}
-- Enter error recovery: generate an error token,
-- save the old token and carry on.
happyFail i tk (HappyState (action)) sts stk =
-- trace "entering error recovery" $
action (1) (1) tk (HappyState (action)) sts ( (HappyErrorToken (i)) `HappyStk` stk)
-- Internal happy errors:
notHappyAtAll :: a
notHappyAtAll = error "Internal Happy error\n"
-----------------------------------------------------------------------------
-- Hack to get the typechecker to accept our action functions
-----------------------------------------------------------------------------
-- Seq-ing. If the --strict flag is given, then Happy emits
-- happySeq = happyDoSeq
-- otherwise it emits
-- happySeq = happyDontSeq
happyDoSeq, happyDontSeq :: a -> b -> b
happyDoSeq a b = a `seq` b
happyDontSeq a b = b
-----------------------------------------------------------------------------
-- Don't inline any functions from the template. GHC has a nasty habit
-- of deciding to inline happyGoto everywhere, which increases the size of
-- the generated parser quite a bit.
{-# LINE 312 "templates/GenericTemplate.hs" #-}
{-# NOINLINE happyShift #-}
{-# NOINLINE happySpecReduce_0 #-}
{-# NOINLINE happySpecReduce_1 #-}
{-# NOINLINE happySpecReduce_2 #-}
{-# NOINLINE happySpecReduce_3 #-}
{-# NOINLINE happyReduce #-}
{-# NOINLINE happyMonadReduce #-}
{-# NOINLINE happyGoto #-}
{-# NOINLINE happyFail #-}
-- end of Happy Template.
| hephaestus-pl/hephaestus | willian/hephaestus-parser-only/LineSintaticScanner.hs | mit | 11,507 | 104 | 20 | 2,196 | 3,363 | 1,820 | 1,543 | 219 | 5 |
-- Copyright © 2013 Julian Blake Kongslie <jblake@jblake.org>
-- Licensed under the MIT license.
{-# OPTIONS_GHC -Wall -Werror #-}
module Language.GBAsm.File
where
import Control.Exception
import Data.Generics.Uniplate.Operations
import qualified Text.Parsec as P
import Language.GBAsm.Lexer
import Language.GBAsm.Parser
import Language.GBAsm.Types
-- This is a top-down IO transformation which finds File nodes, reads the
-- referenced file, lexes, parses, and substitutes in the resulting AST.
filePass :: SourceAST -> IO SourceAST
filePass (File d file) = flip catch (\e -> return $ Err d $ "Could not load file " ++ show file ++ ": " ++ show (e :: SomeException)) $ do
fileData <- readFile file
let fileLex = lexer file fileData
case P.parse fileParser file fileLex of
-- Ideally, the parser never fails, it just produces internal Err nodes.
-- But we catch failure anyway, just in case.
Left e -> return $ Err d $ "Could not parse file " ++ show file ++ ":\n\n" ++ show e
-- We have to recurse to catch nested references.
Right parsedAST -> filePass parsedAST
filePass n = descendM filePass n
| jblake/gbasm | src/Language/GBAsm/File.hs | mit | 1,136 | 0 | 16 | 214 | 236 | 124 | 112 | 16 | 2 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.MediaList
(js_item, item, js_deleteMedium, deleteMedium, js_appendMedium,
appendMedium, js_setMediaText, setMediaText, js_getMediaText,
getMediaText, js_getLength, getLength, MediaList, castToMediaList,
gTypeMediaList)
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[\"item\"]($2)" js_item ::
MediaList -> Word -> IO (Nullable JSString)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaList.item Mozilla MediaList.item documentation>
item ::
(MonadIO m, FromJSString result) =>
MediaList -> Word -> m (Maybe result)
item self index
= liftIO (fromMaybeJSString <$> (js_item (self) index))
foreign import javascript unsafe "$1[\"deleteMedium\"]($2)"
js_deleteMedium :: MediaList -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaList.deleteMedium Mozilla MediaList.deleteMedium documentation>
deleteMedium ::
(MonadIO m, ToJSString oldMedium) => MediaList -> oldMedium -> m ()
deleteMedium self oldMedium
= liftIO (js_deleteMedium (self) (toJSString oldMedium))
foreign import javascript unsafe "$1[\"appendMedium\"]($2)"
js_appendMedium :: MediaList -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaList.appendMedium Mozilla MediaList.appendMedium documentation>
appendMedium ::
(MonadIO m, ToJSString newMedium) => MediaList -> newMedium -> m ()
appendMedium self newMedium
= liftIO (js_appendMedium (self) (toJSString newMedium))
foreign import javascript unsafe "$1[\"mediaText\"] = $2;"
js_setMediaText :: MediaList -> Nullable JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaList.mediaText Mozilla MediaList.mediaText documentation>
setMediaText ::
(MonadIO m, ToJSString val) => MediaList -> Maybe val -> m ()
setMediaText self val
= liftIO (js_setMediaText (self) (toMaybeJSString val))
foreign import javascript unsafe "$1[\"mediaText\"]"
js_getMediaText :: MediaList -> IO (Nullable JSString)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaList.mediaText Mozilla MediaList.mediaText documentation>
getMediaText ::
(MonadIO m, FromJSString result) => MediaList -> m (Maybe result)
getMediaText self
= liftIO (fromMaybeJSString <$> (js_getMediaText (self)))
foreign import javascript unsafe "$1[\"length\"]" js_getLength ::
MediaList -> IO Word
-- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaList.length Mozilla MediaList.length documentation>
getLength :: (MonadIO m) => MediaList -> m Word
getLength self = liftIO (js_getLength (self)) | manyoo/ghcjs-dom | ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/MediaList.hs | mit | 3,507 | 44 | 10 | 516 | 852 | 487 | 365 | 55 | 1 |
module Main where
import HOpenCV.OpenCV
import HOpenCV.HighImage
import HOpenCV.HCxCore
import HOpenCV.HUtil
import HOpenCV.HVideo
import HOpenCV.ImageProcessors
import qualified Control.Processor as Processor
import Control.Processor((--<))
import Prelude hiding ((.),id)
import Control.Arrow
import Control.Category
resizer :: ImageProcessor
resizer = resizeIP 320 240 CV_INTER_LINEAR
edges :: ImageProcessor
edges = cannyIP 30 190 3
faceDetect :: Processor.IOProcessor Image [CvRect]
faceDetect = haarDetect "haarcascade_frontalface_alt.xml" 1.1 3 haarFlagNone (CvSize 20 20)
captureDev :: ImageSource
--captureDev = videoFile "/tmp/video.flv" -- Many formats are supported, not just flv (FFMPEG-based, normally).
-- If you have a webcam, uncomment this, and comment the other definition.
captureDev = camera 0
-- Shows the camera output in two windows (same images in both).
main :: IO ()
main = runTillKeyPressed ((camera 0) --< (window 0 *** window 1))
| juanmab37/HOpenCV-0.5.0.1 | src/examples/Test.hs | gpl-2.0 | 970 | 0 | 10 | 135 | 211 | 121 | 90 | 22 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Numeric.Random.Spectrum.Brown
-- Copyright : (c) Matthew Donadio 2003
-- License : GPL
--
-- Maintainer : m.p.donadio@ieee.org
-- Stability : experimental
-- Portability : portable
--
-- Function for brown noise, which is integrated white noise
--
-----------------------------------------------------------------------------
module Numeric.Random.Spectrum.Brown (brown) where
brown :: [Double] -- ^ noise
-> [Double] -- ^ brown noise
brown = scanl1 (+)
| tolysz/dsp | Numeric/Random/Spectrum/Brown.hs | gpl-2.0 | 579 | 0 | 6 | 94 | 53 | 39 | 14 | 4 | 1 |
import Data.List
import Language
import German
sentences = [statement (the $ girl P) sleeps [],
statement (the $ girl S) eats [the $ cat S],
statement (the $ cat P) sleeps []]
main :: IO ()
main = mapM_ write sentences | Fedjmike/ngen | ngen.hs | gpl-3.0 | 253 | 3 | 9 | 72 | 116 | 58 | 58 | 8 | 1 |
module Database.Design.Ampersand.FSpec.GenerateUML (generateUML) where
import Database.Design.Ampersand.Basics
import Database.Design.Ampersand.Core.AbstractSyntaxTree (explMarkup,aMarkup2String,Rule,Declaration,Purpose(..))
import Database.Design.Ampersand.FSpec.Graphic.ClassDiagram
import Database.Design.Ampersand.FSpec
import Data.Map (Map)
import Data.List
import qualified Data.Map as Map
import Control.Monad.State.Lazy (State, gets, evalState, modify)
fatal :: Int -> String -> a
fatal = fatalMsg "FSpec.GenerateUML"
-- TODO: escape
-- TODO: names of model, package, assoc (empty?), etc.
generateUML :: FSpec -> String
generateUML fSpec = showUML (fSpec2UML fSpec)
showUML :: UML -> String
showUML uml = unlines $ evalState uml $ UMLState 0 Map.empty [] []
fSpec2UML :: FSpec -> UML
fSpec2UML fSpec =
do { packageId0 <- mkUnlabeledId "TopPackage"
; packageId1 <- mkUnlabeledId "PackageClasses"
; packageId2 <- mkUnlabeledId "PackageReqs"
; diagramId <- mkUnlabeledId "Diagram"
; _ <- mapM (mkLabeledId "Datatype") datatypeNames
; _ <- mapM (mkLabeledId "Class") classNames
; datatypesUML <- mapM genUMLDatatype datatypeNames
; classesUML <- mapM genUMLClass (classes classDiag)
; assocsUML <- mapM genUMLAssociation (assocs classDiag)
; requirementsUML <- mapM genUMLRequirement (requirements fSpec)
; diagramElements <- genDiagramElements
; customProfileElements <- genCustomProfileElements
; customReqElements <- genCustomReqElements fSpec packageId2
; return $ [ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
, "<!-- Generated by "++ampersandVersionStr++" -->"
, "<xmi:XMI xmi:version=\"2.1\" xmlns:uml=\"http://schema.omg.org/spec/UML/2.1\" xmlns:xmi=\"http://schema.omg.org/spec/XMI/2.1\" xmlns:thecustomprofile=\"http://www.sparxsystems.com/profiles/thecustomprofile/1.0\">"
-- WHY is the exporter not something like `Ampersand` (in the string below)?
-- BECAUSE then for some reason the importer doesn't show the properties of the requirements.
, " <xmi:Documentation exporter=\"Enterprise Architect\" exporterVersion=\"6.5\"/>"
, " <uml:Model xmi:type=\"uml:Model\" name=\""++contextName++"\" visibility=\"public\">"
, " <packagedElement xmi:type=\"uml:Package\" xmi:id="++show packageId0++" name="++show contextName++" visibility=\"public\">" ] ++
[ " <packagedElement xmi:type=\"uml:Package\" xmi:id="++show packageId1++" name="++show ("classesOf_"++contextName)++" visibility=\"public\">" ] ++
concat datatypesUML ++
concat classesUML ++
concat assocsUML ++
[ " </packagedElement>" ] ++
[ " <packagedElement xmi:type=\"uml:Package\" xmi:id="++show packageId2++" name="++show ("RequirementsOf_"++contextName)++" visibility=\"public\">" ] ++
concat requirementsUML ++
[ " </packagedElement>" ] ++
[ " </packagedElement>" ] ++
customProfileElements ++
[ " </uml:Model>"
, " <xmi:Extension extender=\"Enterprise Architect\" extenderID=\"6.5\">"
, " <elements>"] ++
[ " <element xmi:idref="++show packageId0++" xmi:type=\"uml:Package\" name="++show contextName++" scope=\"public\">"]++
[ " </element>"]++
[ " <element xmi:idref="++show packageId1++" xmi:type=\"uml:Package\" name="++show ("classesOf_"++contextName)++" scope=\"public\">"]++
[ " <model package2="++show packageId1++" package="++show packageId0++" tpos=\"0\" ea_eleType=\"package\"/>"]++
[ " </element>"]++
[ " <element xmi:idref="++show packageId2++" xmi:type=\"uml:Package\" name="++show ("RequirementsOf_"++contextName)++" scope=\"public\">"]++
[ " <model package2="++show packageId2++" package="++show packageId0++" tpos=\"0\" ea_eleType=\"package\"/>"]++
[ " </element>"]++
customReqElements ++
[ " </elements>"
, " <diagrams>"
, " <diagram xmi:id=\""++diagramId++"\">"
, " <model package=\""++packageId1++"\" owner=\""++packageId1++"\"/>"
, " <properties name=\"Data Model\" type=\"Logical\"/>"
, " <elements>" ] ++
diagramElements ++
[ " </elements>"
, " </diagram>"
, " </diagrams>"
, " </xmi:Extension>"
, "</xmi:XMI>" ]
}
where classDiag = cdAnalysis fSpec
contextName = cdName classDiag
allConcs = ooCpts classDiag
classNames = map name (classes classDiag)
datatypeNames = map name allConcs >- classNames
genUMLRequirement :: Req -> UML
genUMLRequirement req =
do { reqLId <- mkUnlabeledId "Req"
; addReqToState (reqLId, req)
; return $ [ " <packagedElement xmi:type=\"uml:Class\" xmi:id=\""++reqLId++"\" name=\""++reqId req++"\" visibility=\"public\"/> " ]
}
genUMLDatatype :: String -> UML
genUMLDatatype nm =
do { datatypeId <- refLabeledId nm
; addToDiagram datatypeId
; return [ " <packagedElement xmi:type=\"uml:DataType\" xmi:id=\""++datatypeId++"\" name=\""++nm++"\" visibility=\"public\"/> " ]
}
genUMLClass :: Class -> UML
genUMLClass cl =
do { classId <- refLabeledId (clName cl)
; addToDiagram classId
; attributesUML <- mapM genUMAttribute (clAtts cl)
; return $ [ " <packagedElement xmi:type=\"uml:Class\" xmi:id=\""++classId++"\" name=\""++clName cl++"\" visibility=\"public\">"] ++
concat attributesUML ++
[ " </packagedElement>"]
}
genUMAttribute :: CdAttribute -> UML
genUMAttribute (OOAttr nm attrType optional) =
do { attrId <- mkUnlabeledId "Attr"
; lIntId <- mkUnlabeledId "Int"
; uIntId <- mkUnlabeledId "Int"
; classId <- refLabeledId attrType
; return [ " <ownedAttribute xmi:type=\"uml:Property\" xmi:id=\""++attrId++"\" name=\""++nm++"\" visibility=\"public\" isStatic=\"false\""++
" isReadOnly=\"false\" isDerived=\"false\" isOrdered=\"false\" isUnique=\"true\" isDerivedUnion=\"false\">"
, " <type xmi:idref=\""++classId++"\"/>"
, " <lowerValue xmi:type=\"uml:LiteralInteger\" xmi:id=\""++lIntId++"\" value=\""++(if optional then "0" else "1")++"\"/>"
, " <upperValue xmi:type=\"uml:LiteralInteger\" xmi:id=\""++uIntId++"\" value=\"1\"/>"
, " </ownedAttribute>"]
}
genUMLAssociation :: Association -> UML
genUMLAssociation ass =
do { assocId <- mkUnlabeledId "Assoc"
; lMemberAndOwnedEnd <- genMemberAndOwnedEnd (asslhm ass) assocId (assSrc ass)
; rMemberAndOwnedEnd <- genMemberAndOwnedEnd (assrhm ass) assocId (assTgt ass)
; return $
[ " <packagedElement xmi:type=\"uml:Association\" xmi:id=\""++assocId++"\" name=\""++assrhr ass++"\" visibility=\"public\">"
] ++
lMemberAndOwnedEnd ++
rMemberAndOwnedEnd ++
[ " </packagedElement>"
]
}
where genMemberAndOwnedEnd (Mult minVal maxVal) assocId type' =
do { endId <- mkUnlabeledId "MemberEnd"
; typeId <- refLabeledId type'
; lIntId <- mkUnlabeledId "Int"
; uIntId <- mkUnlabeledId "Int"
; return
[ " <memberEnd xmi:idref=\""++endId++"\"/>"
, " <ownedEnd xmi:type=\"uml:Property\" xmi:id=\""++endId++"\" visibility=\"public\" association=\""++assocId++"\" isStatic=\"false\""++
" isReadOnly=\"false\" isDerived=\"false\" isOrdered=\"false\" isUnique=\"true\" isDerivedUnion=\"false\" aggregation=\"none\">"
, " <type xmi:idref=\""++typeId++"\"/>"
, " <lowerValue xmi:type=\"uml:LiteralInteger\" xmi:id=\""++lIntId++"\" value=\""++(if minVal == MinZero then "0" else "1")++"\"/>"
, case maxVal of
MaxOne -> " <upperValue xmi:type=\"uml:LiteralInteger\" xmi:id=\""++uIntId++"\" value=\"1\"/>"
MaxMany -> " <upperValue xmi:type=\"uml:LiteralUnlimitedNatural\" xmi:id=\""++uIntId++"\" value=\"-1\"/>"
, " </ownedEnd>"
]
}
genDiagramElements :: UML
genDiagramElements =
do { elementIds <- gets diagramEltIds
; return [ " <element subject=\""++elementId++"\"/>" | elementId <- elementIds ]
}
genCustomProfileElements :: UML
genCustomProfileElements =
do { reqVals <- gets reqValues
; return [reqUML req | req <- reverse reqVals]
}
where
reqUML :: ReqValue2 -> String
reqUML (xmiId, req) = intercalate "\n"
( [" <thecustomprofile:Functional base_Requirement="++show xmiId++"/>"]++
[tagUML xmiId count puprtxt reftxt | (count, (puprtxt, reftxt)) <- zip [0::Int ..] [(aMarkup2String (explMarkup p), intercalate ";" (explRefIds p)) | p <- reqPurposes req]]
)
tagUML xmiId nr value reftxt = intercalate "\n"
[ " <thecustomprofile:"++keyMeaning++" base_Requirement="++show xmiId++" "++keyMeaning++"="++show value++"/>"
, " <thecustomprofile:"++keyRef ++" base_Requirement="++show xmiId++" "++keyRef++"="++show reftxt++"/>"
]
where keyMeaning = "Meaning"++show nr
keyRef = "Reference"++show nr
genCustomReqElements :: FSpec -> String -> UML
genCustomReqElements fSpec parentPackageId =
do { reqVals <- gets reqValues
; return [reqUML req | req <- reverse reqVals]
}
where
reqUML :: ReqValue2 -> String
reqUML (xmiId, req) = intercalate "\n"
([ " <element xmi:idref="++show xmiId++" xmi:type=\"uml:Requirement\" name="++show (reqId req)++" scope=\"public\""++">"
, " <model package="++show parentPackageId++" ea_eleType=\"element\"/>"
, " <properties documentation="++show (maybe "" aMarkup2String (meaning (fsLang fSpec) req))++" isSpecification=\"false\" sType=\"Requirement\" nType=\"0\" scope=\"public\" stereotype=\"Functional\"/>"
, " <tags>"]++
[ " <tag name=\"Purpose"++nr++"\" value="++show p++" modelElement="++show xmiId++"/>" | (nr ,p) <- zip ("" : map show [1::Int ..]) ([aMarkup2String (explMarkup p) | p <- reqPurposes req]) ]++
[ " </tags>"
, " </element>"
])
-- Requirements
data Req = Req { reqId :: String
-- , reqRef :: String
, reqOrig :: Either Rule Declaration
, reqPurposes :: [Purpose]
}
instance Meaning Req where
meaning l r = case reqOrig r of
Right rul -> meaning l rul
Left dcl -> meaning l dcl
requirements :: FSpec -> [Req]
requirements fSpec
= [decl2req d | d <- vrels fSpec]
++[rule2req r | r <- vrules fSpec]
where
decl2req d = Req { reqId = name d
, reqOrig = Right d
, reqPurposes = purposesDefinedIn fSpec (fsLang fSpec) d
}
rule2req r = Req { reqId = name r
, reqOrig = Left r
, reqPurposes = purposesDefinedIn fSpec (fsLang fSpec) r
}
-- State and Monad
data UMLState = UMLState { idCounter :: Int
, labelIdMap :: Map String String
, diagramEltIds :: [String]
, reqValues :: [ReqValue2]
}
type StateUML a = State UMLState a
type UML = StateUML [String]
type ReqValue2 = ( String -- the xmi-id
, Req
)
addToDiagram :: String -> StateUML ()
addToDiagram elementId =
modify $ \state' -> state' { diagramEltIds = elementId : diagramEltIds state'}
addReqToState :: ReqValue2 -> StateUML ()
addReqToState reqVal =
modify $ \state' -> state' { reqValues = reqVal : reqValues state'}
mkUnlabeledId :: String -> StateUML String
mkUnlabeledId tag =
do { idC <- gets idCounter
; modify $ \state' -> state' { idCounter = idCounter state' + 1}
; let unlabeledId = tag++"ID_"++show idC
; return unlabeledId
}
refLabeledId :: String -> StateUML String
refLabeledId label =
do { lidMap <- gets labelIdMap
; case Map.lookup label lidMap of
Just lid -> return lid
Nothing -> fatal 147 $ "Requesting non-existent label "++label
}
mkLabeledId :: String -> String -> StateUML ()
mkLabeledId tag label =
do { let classId = tag++"ID_"++label
; modify $ \state' -> state' { labelIdMap = Map.insert label classId (labelIdMap state') }
} | DanielSchiavini/ampersand | src/Database/Design/Ampersand/FSpec/GenerateUML.hs | gpl-3.0 | 12,713 | 0 | 36 | 3,302 | 2,943 | 1,528 | 1,415 | 208 | 3 |
import Data.List
matrixInfList :: [[a]] -> [a]
matrixList matrix = foldl1 (++) (transpose matrix)
matrixInfList matrix = cycle (matrixList matrix)
main :: IO()
main = do
print (matrixInfList [[1,2],[3,4],[5,6]]) | deni-sl/Functional-programming | Homework 3/hw3.81275.task2.hs | gpl-3.0 | 217 | 1 | 12 | 34 | 120 | 64 | 56 | 7 | 1 |
module Carl.Write (
module Carl.Write.LaTeX,
module Carl.Write.Unicode
) where
import Carl.Write.LaTeX
import Carl.Write.Unicode
| nbloomf/carl | src/Carl/Write.hs | gpl-3.0 | 134 | 0 | 5 | 18 | 34 | 23 | 11 | 5 | 0 |
module Philosophers where
import Control.Concurrent
import Control.Concurrent.MVar (MVar, newMVar, putMVar, takeMVar)
import Control.Concurrent.STM
import Control.Monad
import System.Random (randomRIO)
import Philosophers.Log
import Philosophers.Snapshot
import Philosophers.STM
import Philosophers.Types
mkFork :: Int -> IO TFork
mkFork n = newTVarIO $ Fork (show n) Free
mkPhilosoper :: (Int, TForkPair) -> IO Philosopher
mkPhilosoper (n, tFs) = do
tAct <- newTVarIO Thinking
tCycles <- newTVarIO 0
pure $ Philosopher (show n) tCycles tAct tFs
mkCycledPairs :: [TFork] -> [TForkPair]
mkCycledPairs [] = error "No elems"
mkCycledPairs [_] = error "Only 1 elem"
mkCycledPairs fs = map mkPair pairIndexes
where
pairIndexes :: [(Int, Int)]
pairIndexes = [(x, x + 1) | x <- [0..length fs - 2]] ++ [(length fs - 1, 0)]
mkPair :: (Int, Int) -> TForkPair
mkPair (i1, i2) = (fs !! i1, fs !! i2)
monitoringWorker :: LogLock -> Snapshot -> [Philosopher] -> IO ()
monitoringWorker logLock s@(ss, n) ps = do
threadDelay $ 1000 * 1000
snapshot <- takeSnapshot (n + 1) ps
if s /= snapshot
then do
printSnapshot logLock s
monitoringWorker logLock snapshot ps
else monitoringWorker logLock s ps
philosopherWorker :: LogLock -> Philosopher -> IO ()
philosopherWorker logLock p@(Philosopher n _ tAct _) = do
t1 <- randomRIO (1, 5)
t2 <- randomRIO (1, 5)
let activity1Time = 1000 * 1000 * t1
let activity2Time = 1000 * 1000 * t2
c <- atomically $ incrementCycles p
logMsg logLock $ "-- Philosopher " ++ show n ++ " next cycle: " ++ show c
act1 <- atomically $ changeActivity p
logMsg logLock $ "-- Philosopher " ++ show n ++ " changed activity to: " ++ show act1 ++ " for " ++ show t1 ++ " secs."
threadDelay activity1Time
act2 <- atomically $ changeActivity p
logMsg logLock $ "-- Philosopher " ++ show n ++ " changed activity to: " ++ show act2 ++ " for " ++ show t2 ++ " secs."
threadDelay activity2Time
philosopherWorker logLock p
runPhilosopherTread :: LogLock -> Philosopher -> IO ()
runPhilosopherTread logLock ps = void $ forkIO (philosopherWorker logLock ps)
runPhilosophers :: Int -> IO ()
runPhilosophers count = do
forks <- sequence $ take count (map mkFork [1..])
let forkPairs = mkCycledPairs forks
ps <- mapM mkPhilosoper (zip [1..] forkPairs)
logLock <- newMVar ()
s@(ss, _) <- takeSnapshot 0 ps
printSnapshot logLock s
_ <- forkIO (monitoringWorker logLock (ss, 1) ps)
mapM_ (runPhilosopherTread logLock) ps
| graninas/Haskell-Algorithms | Tests/STM/philosopers/src/Philosophers.hs | gpl-3.0 | 2,621 | 49 | 15 | 609 | 937 | 477 | 460 | 61 | 2 |
module Scene
( Scene(..)
, sceneObjects
) where
import Data.Monoid
-- A scene tree, managing the order of transformation compositions
-- when listing the transformed objects.
data Scene t a =
SceneObject a
| SceneFork [Scene t a]
| Transformed t (Scene t a)
sceneObjects :: (Monoid t) => Scene t a -> [(t, a)]
sceneObjects = go mempty
go :: (Monoid t) => t -> Scene t a -> [(t, a)]
go t (SceneObject a) = return (t, a)
go t (SceneFork l) = concatMap (go t) l
go t (Transformed t' s) = go (t <> t') s
| MatthiasHu/4d-labyrinth | src/Scene.hs | gpl-3.0 | 527 | 0 | 9 | 127 | 220 | 121 | 99 | 14 | 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.FirebaseRules.Projects.Releases.Patch
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Update a \`Release\` via PATCH. Only updates to \`ruleset_name\` will be
-- honored. \`Release\` rename is not supported. To create a \`Release\`
-- use the CreateRelease method.
--
-- /See:/ <https://firebase.google.com/docs/storage/security Firebase Rules API Reference> for @firebaserules.projects.releases.patch@.
module Network.Google.Resource.FirebaseRules.Projects.Releases.Patch
(
-- * REST Resource
ProjectsReleasesPatchResource
-- * Creating a Request
, projectsReleasesPatch
, ProjectsReleasesPatch
-- * Request Lenses
, prpXgafv
, prpUploadProtocol
, prpAccessToken
, prpUploadType
, prpPayload
, prpName
, prpCallback
) where
import Network.Google.FirebaseRules.Types
import Network.Google.Prelude
-- | A resource alias for @firebaserules.projects.releases.patch@ method which the
-- 'ProjectsReleasesPatch' request conforms to.
type ProjectsReleasesPatchResource =
"v1" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] UpdateReleaseRequest :>
Patch '[JSON] Release
-- | Update a \`Release\` via PATCH. Only updates to \`ruleset_name\` will be
-- honored. \`Release\` rename is not supported. To create a \`Release\`
-- use the CreateRelease method.
--
-- /See:/ 'projectsReleasesPatch' smart constructor.
data ProjectsReleasesPatch =
ProjectsReleasesPatch'
{ _prpXgafv :: !(Maybe Xgafv)
, _prpUploadProtocol :: !(Maybe Text)
, _prpAccessToken :: !(Maybe Text)
, _prpUploadType :: !(Maybe Text)
, _prpPayload :: !UpdateReleaseRequest
, _prpName :: !Text
, _prpCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsReleasesPatch' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'prpXgafv'
--
-- * 'prpUploadProtocol'
--
-- * 'prpAccessToken'
--
-- * 'prpUploadType'
--
-- * 'prpPayload'
--
-- * 'prpName'
--
-- * 'prpCallback'
projectsReleasesPatch
:: UpdateReleaseRequest -- ^ 'prpPayload'
-> Text -- ^ 'prpName'
-> ProjectsReleasesPatch
projectsReleasesPatch pPrpPayload_ pPrpName_ =
ProjectsReleasesPatch'
{ _prpXgafv = Nothing
, _prpUploadProtocol = Nothing
, _prpAccessToken = Nothing
, _prpUploadType = Nothing
, _prpPayload = pPrpPayload_
, _prpName = pPrpName_
, _prpCallback = Nothing
}
-- | V1 error format.
prpXgafv :: Lens' ProjectsReleasesPatch (Maybe Xgafv)
prpXgafv = lens _prpXgafv (\ s a -> s{_prpXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
prpUploadProtocol :: Lens' ProjectsReleasesPatch (Maybe Text)
prpUploadProtocol
= lens _prpUploadProtocol
(\ s a -> s{_prpUploadProtocol = a})
-- | OAuth access token.
prpAccessToken :: Lens' ProjectsReleasesPatch (Maybe Text)
prpAccessToken
= lens _prpAccessToken
(\ s a -> s{_prpAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
prpUploadType :: Lens' ProjectsReleasesPatch (Maybe Text)
prpUploadType
= lens _prpUploadType
(\ s a -> s{_prpUploadType = a})
-- | Multipart request metadata.
prpPayload :: Lens' ProjectsReleasesPatch UpdateReleaseRequest
prpPayload
= lens _prpPayload (\ s a -> s{_prpPayload = a})
-- | Required. Resource name for the project which owns this \`Release\`.
-- Format: \`projects\/{project_id}\`
prpName :: Lens' ProjectsReleasesPatch Text
prpName = lens _prpName (\ s a -> s{_prpName = a})
-- | JSONP
prpCallback :: Lens' ProjectsReleasesPatch (Maybe Text)
prpCallback
= lens _prpCallback (\ s a -> s{_prpCallback = a})
instance GoogleRequest ProjectsReleasesPatch where
type Rs ProjectsReleasesPatch = Release
type Scopes ProjectsReleasesPatch =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/firebase"]
requestClient ProjectsReleasesPatch'{..}
= go _prpName _prpXgafv _prpUploadProtocol
_prpAccessToken
_prpUploadType
_prpCallback
(Just AltJSON)
_prpPayload
firebaseRulesService
where go
= buildClient
(Proxy :: Proxy ProjectsReleasesPatchResource)
mempty
| brendanhay/gogol | gogol-firebase-rules/gen/Network/Google/Resource/FirebaseRules/Projects/Releases/Patch.hs | mpl-2.0 | 5,419 | 0 | 16 | 1,212 | 783 | 459 | 324 | 113 | 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.TagManager.Accounts.Containers.Workspaces.Folders.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists all GTM Folders of a Container.
--
-- /See:/ <https://developers.google.com/tag-manager Tag Manager API Reference> for @tagmanager.accounts.containers.workspaces.folders.list@.
module Network.Google.Resource.TagManager.Accounts.Containers.Workspaces.Folders.List
(
-- * REST Resource
AccountsContainersWorkspacesFoldersListResource
-- * Creating a Request
, accountsContainersWorkspacesFoldersList
, AccountsContainersWorkspacesFoldersList
-- * Request Lenses
, acwflParent
, acwflXgafv
, acwflUploadProtocol
, acwflAccessToken
, acwflUploadType
, acwflPageToken
, acwflCallback
) where
import Network.Google.Prelude
import Network.Google.TagManager.Types
-- | A resource alias for @tagmanager.accounts.containers.workspaces.folders.list@ method which the
-- 'AccountsContainersWorkspacesFoldersList' request conforms to.
type AccountsContainersWorkspacesFoldersListResource
=
"tagmanager" :>
"v2" :>
Capture "parent" Text :>
"folders" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "pageToken" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListFoldersResponse
-- | Lists all GTM Folders of a Container.
--
-- /See:/ 'accountsContainersWorkspacesFoldersList' smart constructor.
data AccountsContainersWorkspacesFoldersList =
AccountsContainersWorkspacesFoldersList'
{ _acwflParent :: !Text
, _acwflXgafv :: !(Maybe Xgafv)
, _acwflUploadProtocol :: !(Maybe Text)
, _acwflAccessToken :: !(Maybe Text)
, _acwflUploadType :: !(Maybe Text)
, _acwflPageToken :: !(Maybe Text)
, _acwflCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AccountsContainersWorkspacesFoldersList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'acwflParent'
--
-- * 'acwflXgafv'
--
-- * 'acwflUploadProtocol'
--
-- * 'acwflAccessToken'
--
-- * 'acwflUploadType'
--
-- * 'acwflPageToken'
--
-- * 'acwflCallback'
accountsContainersWorkspacesFoldersList
:: Text -- ^ 'acwflParent'
-> AccountsContainersWorkspacesFoldersList
accountsContainersWorkspacesFoldersList pAcwflParent_ =
AccountsContainersWorkspacesFoldersList'
{ _acwflParent = pAcwflParent_
, _acwflXgafv = Nothing
, _acwflUploadProtocol = Nothing
, _acwflAccessToken = Nothing
, _acwflUploadType = Nothing
, _acwflPageToken = Nothing
, _acwflCallback = Nothing
}
-- | GTM Workspace\'s API relative path. Example:
-- accounts\/{account_id}\/containers\/{container_id}\/workspaces\/{workspace_id}
acwflParent :: Lens' AccountsContainersWorkspacesFoldersList Text
acwflParent
= lens _acwflParent (\ s a -> s{_acwflParent = a})
-- | V1 error format.
acwflXgafv :: Lens' AccountsContainersWorkspacesFoldersList (Maybe Xgafv)
acwflXgafv
= lens _acwflXgafv (\ s a -> s{_acwflXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
acwflUploadProtocol :: Lens' AccountsContainersWorkspacesFoldersList (Maybe Text)
acwflUploadProtocol
= lens _acwflUploadProtocol
(\ s a -> s{_acwflUploadProtocol = a})
-- | OAuth access token.
acwflAccessToken :: Lens' AccountsContainersWorkspacesFoldersList (Maybe Text)
acwflAccessToken
= lens _acwflAccessToken
(\ s a -> s{_acwflAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
acwflUploadType :: Lens' AccountsContainersWorkspacesFoldersList (Maybe Text)
acwflUploadType
= lens _acwflUploadType
(\ s a -> s{_acwflUploadType = a})
-- | Continuation token for fetching the next page of results.
acwflPageToken :: Lens' AccountsContainersWorkspacesFoldersList (Maybe Text)
acwflPageToken
= lens _acwflPageToken
(\ s a -> s{_acwflPageToken = a})
-- | JSONP
acwflCallback :: Lens' AccountsContainersWorkspacesFoldersList (Maybe Text)
acwflCallback
= lens _acwflCallback
(\ s a -> s{_acwflCallback = a})
instance GoogleRequest
AccountsContainersWorkspacesFoldersList
where
type Rs AccountsContainersWorkspacesFoldersList =
ListFoldersResponse
type Scopes AccountsContainersWorkspacesFoldersList =
'["https://www.googleapis.com/auth/tagmanager.edit.containers",
"https://www.googleapis.com/auth/tagmanager.readonly"]
requestClient
AccountsContainersWorkspacesFoldersList'{..}
= go _acwflParent _acwflXgafv _acwflUploadProtocol
_acwflAccessToken
_acwflUploadType
_acwflPageToken
_acwflCallback
(Just AltJSON)
tagManagerService
where go
= buildClient
(Proxy ::
Proxy
AccountsContainersWorkspacesFoldersListResource)
mempty
| brendanhay/gogol | gogol-tagmanager/gen/Network/Google/Resource/TagManager/Accounts/Containers/Workspaces/Folders/List.hs | mpl-2.0 | 6,017 | 0 | 18 | 1,337 | 789 | 460 | 329 | 123 | 1 |
{-# LANGUAGE Rank2Types #-}
module Model.Issue where
import Import
import Data.Filter
import Data.Order
import Widgets.Tag (pickForegroundColor)
import qualified Data.Set as S
import qualified Data.Text as T
import qualified Github.Issues as GH
import Numeric (readHex)
import Text.Printf
-- An Issue abstracts a Snowdrift ticket, Github issue, etc.
class Issue a where
issueWidget :: a -> Widget
issueFilterable :: a -> Filterable
issueOrderable :: a -> Orderable
-- Existentially quantified Issue.
newtype SomeIssue = SomeIssue { unSomeIssue :: forall b. (forall a. Issue a => a -> b) -> b }
mkSomeIssue :: Issue a => a -> SomeIssue
mkSomeIssue issue = SomeIssue (\k -> k issue)
instance Issue SomeIssue where
issueWidget (SomeIssue k) = k issueWidget
issueFilterable (SomeIssue k) = k issueFilterable
issueOrderable (SomeIssue k) = k issueOrderable
instance Issue GH.Issue where
issueWidget github_issue =
[whamlet|
<tr>
<td>
$maybe url <- GH.issueHtmlUrl github_issue
<a href="#{url}">
GH-#{GH.issueNumber github_issue}
$nothing
GH-#{GH.issueNumber github_issue}
<td>
#{GH.issueTitle github_issue}
<td>
$forall tag <- GH.issueLabels github_issue
^{githubIssueTagWidget tag}
|]
where
githubIssueTagWidget :: GH.IssueLabel -> Widget
githubIssueTagWidget tag = do
[whamlet|
<form .tag>
#{GH.labelName tag}
|]
toWidget [cassius|
.tag
background-color: ##{GH.labelColor tag}
color: ##{fg $ GH.labelColor tag}
font-size: xx-small
|]
fg :: String -> String
fg = printf "%06x" . pickForegroundColor . maybe 0 fst . listToMaybe . readHex
issueFilterable = mkFromGithubIssue Filterable
issueOrderable = mkFromGithubIssue Orderable
mkFromGithubIssue :: ((Text -> Bool) -> (Text -> Set UTCTime) -> (Text -> Bool) -> t) -> GH.Issue -> t
mkFromGithubIssue c i = c has_tag get_named_ts search_literal
where
has_tag t = elem (T.unpack t) $ map GH.labelName $ GH.issueLabels i
get_named_ts "CREATED" = S.singleton $ GH.fromGithubDate $ GH.issueCreatedAt i
get_named_ts "LAST UPDATED" = S.singleton $ GH.fromGithubDate $ GH.issueUpdatedAt i
get_named_ts name = error $ "Unrecognized time name " ++ T.unpack name
search_literal str =
not (null $ T.breakOnAll str $ T.pack $ GH.issueTitle i)
|| fromMaybe False (null . T.breakOnAll str . T.pack <$> GH.issueBody i)
| Happy0/snowdrift | Model/Issue.hs | agpl-3.0 | 2,813 | 0 | 14 | 879 | 612 | 323 | 289 | -1 | -1 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE DataKinds #-}
module Data.Bounds
(
Bounds (..),
collapseBounds
)
where
import GHC.TypeLits
import Data.Constraint
import Data.Constraint.Nat
-- | An existential wrapper around 'Nat' indexed structures of kind @Nat -> * ->
-- *@, such as 'Set', which also provides lower and upper bounds for the
-- existentially quantified index.
--
-- @Bounds l h x a@ therefore provides proof that @l@ is a lower bound on the
-- index of @x@, and @h@ is an upper bound on it.
--
-- Pattern matching on the @Bounds@ constructor brings a 'KnownNat' @n@
-- constraint into scope, as well as @l <= n@ and @n <= h@.
data Bounds (x :: Nat -> * -> *) (l :: Nat) (h :: Nat) a where
Bounds :: (l <= n, n <= h, KnownNat n) => x n a -> Bounds x l h a
-- | Given a 'Bounds' with two equal bounds, collapse it to the contained
-- structure. In other words, given that @l <= k <= h@, we get a proof that @l =
-- k = h@ and therefore, the existentially quantified index can be extracted.
collapseBounds :: forall n f a. KnownNat n => Bounds f n n a -> f n a
collapseBounds (Bounds (x :: f k a)) = x \\ leEq @n @k
{-# INLINABLE collapseBounds #-}
| tsahyt/indexed-set | src/Data/Bounds.hs | lgpl-3.0 | 1,301 | 0 | 10 | 260 | 211 | 126 | 85 | 17 | 1 |
module SetTools where
import Data.HashSet (HashSet) --unordered-containers
import Data.Hashable (Hashable)
import qualified Data.HashSet as Set
setBind :: (Hashable s1, Hashable s2, Eq s1, Eq s2) => HashSet s1 -> (s1 -> HashSet s2) -> HashSet s2
setBind s f = foldl (Set.union) Set.empty $ Set.map f s
--I can't make a monad instance because of the type constraints on what goes into the set.
powerSet :: (Hashable a, Eq a) => HashSet a -> HashSet (HashSet a)
powerSet mySet = Set.fromList $ map Set.fromList (powerSetList (Set.toList mySet))
powerSetList :: [a] -> [[a]]
powerSetList [] = [[]]
powerSetList (x:xs) = tailSet ++ map (x:) tailSet
where tailSet = powerSetList xs
cartesianProduct :: (Hashable s1, Hashable s2, Eq s1, Eq s2) => HashSet s1 -> HashSet s2 -> HashSet (s1, s2)
cartesianProduct s1 s2 = s1 `setBind` (\e1 -> Set.map (\e2 -> (e1, e2)) s2)
| Crazycolorz5/Automata | SetTools.hs | unlicense | 872 | 0 | 11 | 153 | 365 | 195 | 170 | 14 | 1 |
module Faceted (
module Faceted.Pure,
module Faceted.FIORef,
module Faceted.FHandle,
module Faceted.FIO
) where
import Faceted.Pure
import Faceted.FIORef
import Faceted.FHandle
import Faceted.FIO
| tommy-schmitz/haskell-faceted | Faceted.hs | apache-2.0 | 207 | 0 | 5 | 32 | 50 | 32 | 18 | 9 | 0 |
module Operator00002 ((Prelude.:->)) where
import qualified Lib
f x = case x of
y :-> _ -> y
f x = case x of
y Lib.:-> _ -> y
| carymrobbins/intellij-haskforce | tests/gold/parser/Operator00002.hs | apache-2.0 | 133 | 0 | 8 | 36 | 63 | 35 | 28 | 6 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-----------------------------------------------------------------------------
-- |
-- Module : FFICXX.Generate.Type.PackageInterface
-- Copyright : (c) 2011-2013 Ian-Woo Kim
--
-- License : BSD3
-- Maintainer : Ian-Woo Kim <ianwookim@gmail.com>
-- Stability : experimental
-- Portability : GHC
--
-----------------------------------------------------------------------------
module FFICXX.Generate.Type.PackageInterface where
import Data.Hashable
import qualified Data.HashMap.Strict as HM
newtype PackageName = PkgName String deriving (Hashable, Show, Eq, Ord)
newtype ClassName = ClsName String deriving (Hashable, Show, Eq, Ord)
newtype HeaderName = HdrName String deriving (Hashable, Show, Eq, Ord)
type PackageInterface = HM.HashMap (PackageName, ClassName) HeaderName
newtype TypeMacro = TypMcro { unTypMcro :: String }
deriving (Show,Eq,Ord)
| Gabriel439/fficxx | lib/FFICXX/Generate/Type/PackageInterface.hs | bsd-2-clause | 945 | 0 | 6 | 149 | 162 | 101 | 61 | 10 | 0 |
{-# LANGUAGE FlexibleContexts, FlexibleInstances, MultiParamTypeClasses, RecordWildCards,
TypeFamilies, TemplateHaskell #-}
module Conditionals where
import Control.Applicative
import Data.Monoid ((<>))
import qualified Rank2.TH
import Text.Grampa
import Text.Grampa.ContextFree.LeftRecursive (Parser)
class ConditionalDomain c e where
ifThenElse :: c -> e -> e -> e
instance ConditionalDomain Bool e where
ifThenElse True t _ = t
ifThenElse False _ f = f
instance ConditionalDomain [Char] [Char] where
ifThenElse cond t f = "if " <> cond <> " then " <> t <> " else " <> f
data Conditionals t e f = Conditionals{expr :: f e,
test :: f t,
term :: f e}
instance (Show (f t), Show (f e)) => Show (Conditionals t e f) where
showsPrec prec a rest = "Conditionals{expr=" ++ showsPrec prec (expr a)
(", test= " ++ showsPrec prec (test a)
(", term= " ++ showsPrec prec (term a) ("}" ++ rest)))
instance TokenParsing (Parser (Conditionals t e) String)
instance LexicalParsing (Parser (Conditionals t e) String)
$(Rank2.TH.deriveAll ''Conditionals)
conditionals :: (ConditionalDomain t e, LexicalParsing (Parser g String))
=> GrammarBuilder (Conditionals t e) g Parser String
conditionals Conditionals{..} =
Conditionals{expr= ifThenElse <$> (keyword "if" *> test) <*> (keyword "then" *> term) <*> (keyword "else" *> term),
test= empty,
term= empty}
| blamario/grampa | grammatical-parsers/examples/Conditionals.hs | bsd-2-clause | 1,560 | 0 | 15 | 421 | 499 | 264 | 235 | 31 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UnicodeSyntax #-}
{-| This adapter implements parallelism by spawning multiple processes. The
number of processes can be changed during the run and even be set to zero.
-}
module LogicGrowsOnTrees.Parallel.Adapter.Processes
(
-- * Driver
driver
-- * Controller
, ProcessesControllerMonad
, abort
, changeNumberOfWorkersAsync
, changeNumberOfWorkers
, fork
, getCurrentProgressAsync
, getCurrentProgress
, getCurrentStatisticsAsync
, getCurrentStatistics
, getNumberOfWorkersAsync
, getNumberOfWorkers
, requestProgressUpdateAsync
, requestProgressUpdate
, setNumberOfWorkersAsync
, setNumberOfWorkers
, setWorkloadBufferSize
-- * Outcome types
, RunOutcome
, RunStatistics(..)
, TerminationReason(..)
-- * Generic runner functions
-- $runners
, runSupervisor
, runWorker
, runWorkerUsingHandles
, runExplorer
-- * Utility functions
, getProgFilepath
) where
import Prelude hiding (catch)
import Control.Applicative ((<$>),(<*>),Applicative,liftA2)
import Control.Arrow (second)
import Control.Concurrent (forkIO)
import Control.Exception (AsyncException(ThreadKilled,UserInterrupt),SomeException,catch,catchJust,fromException)
import Control.Monad (forever,liftM2)
import Control.Monad.CatchIO (MonadCatchIO)
import Control.Monad.IO.Class (MonadIO,liftIO)
import Control.Monad.Trans.State.Strict (get,modify)
import qualified Data.Foldable as Fold
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.Maybe (fromMaybe)
import Data.Monoid (Monoid(mempty))
import Data.Serialize (Serialize)
import System.Console.CmdTheLine
import System.Environment (getArgs,getProgName)
import System.Environment.FindBin (getProgPath)
import System.FilePath ((</>))
import System.IO (Handle,hGetLine,stdin,stdout)
import System.IO.Error (isEOFError)
import qualified System.Log.Logger as Logger
import System.Log.Logger (Priority(DEBUG,ERROR))
import System.Log.Logger.TH
import System.Process (CreateProcess(..),CmdSpec(RawCommand),StdStream(..),ProcessHandle,createProcess,interruptProcessGroupOf)
import LogicGrowsOnTrees (TreeT)
import LogicGrowsOnTrees.Parallel.Common.Message
import LogicGrowsOnTrees.Parallel.Common.Process (runWorker,runWorkerUsingHandles)
import LogicGrowsOnTrees.Parallel.Common.RequestQueue
import LogicGrowsOnTrees.Parallel.Common.Workgroup hiding (C,unwrapC)
import LogicGrowsOnTrees.Parallel.ExplorationMode
import LogicGrowsOnTrees.Parallel.Main
(Driver(..)
,DriverParameters(..)
,RunOutcome
,RunOutcomeFor
,RunStatistics(..)
,TerminationReason(..)
,mainParser
)
import LogicGrowsOnTrees.Parallel.Purity
import LogicGrowsOnTrees.Utils.Handle
import LogicGrowsOnTrees.Utils.Word_
--------------------------------------------------------------------------------
----------------------------------- Loggers ------------------------------------
--------------------------------------------------------------------------------
deriveLoggers "Logger" [DEBUG,ERROR]
--------------------------------------------------------------------------------
------------------------------------ Driver ------------------------------------
--------------------------------------------------------------------------------
{-| This is the driver for the threads adapter; the number of workers is
specified via. the (required) command-line option "-n".
Note that there are not seperate drivers for the supervisor process and the
worker process; instead, the same executable is used for both the supervisor
and the worker, with a sentinel argument (or arguments) determining which
role it should run as.
-}
driver ::
( Serialize shared_configuration
, Serialize (ProgressFor exploration_mode)
, Serialize (WorkerFinishedProgressFor exploration_mode)
) ⇒
Driver IO shared_configuration supervisor_configuration m n exploration_mode
driver = Driver $ \DriverParameters{..} → do
runExplorer
constructExplorationMode
purity
(mainParser (liftA2 (,) shared_configuration_term (liftA2 (,) number_of_processes_term supervisor_configuration_term)) program_info)
initializeGlobalState
constructTree
(curry $ uncurry getStartingProgress . second snd)
(\shared_configuration (Word_ number_of_processes,supervisor_configuration) → do
setNumberOfWorkers number_of_processes
constructController shared_configuration supervisor_configuration
)
>>=
maybe (return ()) (notifyTerminated <$> fst . fst <*> snd . snd . fst <*> snd)
where
number_of_processes_term = required (flip opt (
(optInfo ["n","number-of-processes"])
{ optName = "#"
, optDoc = "This *required* option specifies the number of worker processes to spawn."
}
) Nothing )
{-# INLINE driver #-}
--------------------------------------------------------------------------------
---------------------------------- Controller ----------------------------------
--------------------------------------------------------------------------------
{-| The monad in which the processes controller will run. -}
newtype ProcessesControllerMonad exploration_mode α =
C { unwrapC :: WorkgroupControllerMonad (IntMap Worker) exploration_mode α
} deriving (Applicative,Functor,Monad,MonadCatchIO,MonadIO,RequestQueueMonad,WorkgroupRequestQueueMonad)
instance HasExplorationMode (ProcessesControllerMonad exploration_mode) where
type ExplorationModeFor (ProcessesControllerMonad exploration_mode) = exploration_mode
--------------------------------------------------------------------------------
------------------------------- Generic runners --------------------------------
--------------------------------------------------------------------------------
{- $runners
In this section the full functionality of this module is exposed in case one
does not want the restrictions of the driver interface. If you decide to go in
this direction, then you need to decide whether you want there to be a single
executable for both the supervisor and worker with the process of determining in
which mode it should run taken care of for you, or whether you want to do this
yourself in order to give yourself more control (such as by having separate
supervisor and worker executables) at the price of more work.
If you want to use a single executable with automated handling of the
supervisor and worker roles, then use 'runExplorer'. Otherwise, use
'runSupervisor' to run the supervisor loop and on each worker use
'runWorkerUsingHandles', passing 'stdin' and 'stdout' as the process handles.
-}
{-| This runs the supervisor, which will spawn and kill worker processes as
needed so that the total number is equal to the number set by the
controller.
-}
runSupervisor ::
( Serialize (ProgressFor exploration_mode)
, Serialize (WorkerFinishedProgressFor exploration_mode)
) ⇒
ExplorationMode exploration_mode {-^ the exploration mode -} →
String {-^ the path to the worker executable -} →
[String] {-^ the arguments to pass to the worker executable -} →
(Handle → IO ()) {-^ an action that writes any information needed by the worker to the given handle -} →
ProgressFor exploration_mode {-^ the initial progress of the run -} →
ProcessesControllerMonad exploration_mode () {-^ the controller of the supervisor, which must at least set the number of workers to be positive for anything to take place -} →
IO (RunOutcomeFor exploration_mode) {-^ the result of the run -}
runSupervisor
exploration_mode
worker_filepath
worker_arguments
sendConfigurationTo
starting_progress
(C controller)
= do
runWorkgroup
exploration_mode
mempty
(\message_receivers@MessageForSupervisorReceivers{..} →
let createWorker worker_id = do
debugM $ "Launching worker process: " ++ worker_filepath ++ " " ++ unwords worker_arguments
(Just write_handle,Just read_handle,Just error_handle,process_handle) ← liftIO . createProcess $
CreateProcess
{ cmdspec = RawCommand worker_filepath worker_arguments
, cwd = Nothing
, env = Nothing
, std_in = CreatePipe
, std_out = CreatePipe
, std_err = CreatePipe
, close_fds = True
, create_group = True
}
liftIO $ do
_ ← forkIO $
catchJust
(\e → if isEOFError e then Just () else Nothing)
(forever $ hGetLine error_handle >>= \line → debugM $ "[" ++ show worker_id ++ "] " ++ line)
(const $ return ())
`catch`
(\(e::SomeException) → errorM $ "Error reading stderr for worker " ++ show worker_id ++ ": " ++ show e)
_ ← forkIO $
receiveAndProcessMessagesFromWorkerUsingHandle message_receivers read_handle worker_id
`catch`
(\(e::SomeException) →
case fromException e of
Just ThreadKilled → return ()
Just UserInterrupt → return ()
_ → do
debugM $ "Worker " ++ show worker_id ++ " failed with exception: " ++ show e
interruptProcessGroupOf process_handle
receiveFailureFromWorker worker_id (show e)
)
sendConfigurationTo write_handle
modify . IntMap.insert worker_id $ Worker{..}
destroyWorker worker_id _ = do
debugM $ "Sending QuitWorker to " ++ show worker_id ++ "..."
get >>=
liftIO
.
flip send QuitWorker
.
write_handle
.
fromJustOrBust ("destroyWorker failed to get record for " ++ show worker_id)
.
IntMap.lookup worker_id
debugM $ "Finished sending QuitWorker to " ++ show worker_id ++ "."
modify $ IntMap.delete worker_id
killAllWorkers _ =
debugM "Killing all workers..." >>
get >>= liftIO . Fold.mapM_ (flip send QuitWorker . write_handle) >>
debugM "Done killing all workers."
sendMessageToWorker message worker_id =
get >>=
liftIO
.
maybe (return ()) (
flip send message
.
write_handle
)
.
IntMap.lookup worker_id
sendProgressUpdateRequestTo = sendMessageToWorker RequestProgressUpdate
sendWorkloadStealRequestTo = sendMessageToWorker RequestWorkloadSteal
sendWorkloadTo worker_id workload = sendMessageToWorker (StartWorkload workload) worker_id
in WorkgroupCallbacks{..}
)
starting_progress
controller
{-# INLINE runSupervisor #-}
{-| Explores the given tree using multiple processes to achieve parallelism.
This function grants access to all of the functionality of this adapter,
rather than having to go through the more restricted driver interface. The
signature of this function is very complicated because it is meant to be
used in both the supervisor and worker; it figures out which role it is
supposed to play based on whether the list of command line arguments matches
a sentinel.
The configuration information is divided into two parts: information shared
between the supervisor and the workers, and information that is specific to
the supervisor and not sent to the workers. (Note that only the former needs
to be serializable.) An action must be supplied that obtains this
configuration information, and most of the arguments are functions that are
given all or part of this information.
-}
runExplorer ::
( Serialize shared_configuration
, Serialize (ProgressFor exploration_mode)
, Serialize (WorkerFinishedProgressFor exploration_mode)
) ⇒
(shared_configuration → ExplorationMode exploration_mode)
{-^ a function that constructs the exploration mode given the shared
configuration
-} →
Purity m n {-^ the purity of the tree -} →
IO (shared_configuration,supervisor_configuration)
{-^ an action that gets the shared and supervisor-specific configuration
information (run only on the supervisor)
-} →
(shared_configuration → IO ())
{-^ an action that initializes the global state of the process given the
shared configuration (run on both supervisor and worker processes)
-} →
(shared_configuration → TreeT m (ResultFor exploration_mode))
{-^ a function that constructs the tree from the shared configuration
(called only on the worker)
-} →
(shared_configuration → supervisor_configuration → IO (ProgressFor exploration_mode))
{-^ an action that gets the starting progress given the full
configuration information (run only on the supervisor)
-} →
(shared_configuration → supervisor_configuration → ProcessesControllerMonad exploration_mode ())
{-^ a function that constructs the controller for the supervisor, which
must at least set the number of workers to be non-zero (called only
on the supervisor)
-} →
IO (Maybe ((shared_configuration,supervisor_configuration),RunOutcomeFor exploration_mode))
{-^ if this process is the supervisor, then the outcome of the run as
well as the configuration information wrapped in 'Just'; otherwise
'Nothing'
-}
runExplorer
constructExplorationMode
purity
getConfiguration
initializeGlobalState
constructTree
getStartingProgress
constructController
= getArgs >>= \args →
if args == sentinel
then do
shared_configuration ← receive stdin
initializeGlobalState shared_configuration
runWorkerUsingHandles
(constructExplorationMode shared_configuration)
purity
(constructTree shared_configuration)
stdin
stdout
return Nothing
else do
configuration@(shared_configuration,supervisor_configuration) ← getConfiguration
initializeGlobalState shared_configuration
program_filepath ← getProgFilepath
starting_progress ← getStartingProgress shared_configuration supervisor_configuration
termination_result ←
runSupervisor
(constructExplorationMode shared_configuration)
program_filepath
sentinel
(flip send shared_configuration)
starting_progress
(constructController shared_configuration supervisor_configuration)
return $ Just (configuration,termination_result)
where
sentinel = ["explorer","worker","bee"]
{-# INLINE runExplorer #-}
--------------------------------------------------------------------------------
------------------------------- Utility funtions -------------------------------
--------------------------------------------------------------------------------
{-| Gets the full path to this executable. -}
getProgFilepath :: IO String
getProgFilepath = liftM2 (</>) getProgPath getProgName
--------------------------------------------------------------------------------
----------------------------------- Internal -----------------------------------
--------------------------------------------------------------------------------
data Worker = Worker
{ read_handle :: Handle
, write_handle :: Handle
, process_handle :: ProcessHandle
}
fromJustOrBust message = fromMaybe (error message)
| gcross/LogicGrowsOnTrees-processes | sources/LogicGrowsOnTrees/Parallel/Adapter/Processes.hs | bsd-2-clause | 17,129 | 8 | 34 | 4,508 | 2,257 | 1,248 | 1,009 | 253 | 4 |
module Player where
import Cards
data PlayerType = Ai | Human deriving (Eq, Show)
data Player = Player {
getType :: PlayerType
, getName :: String
, getCards :: Hand
} deriving (Show)
addCards :: [Card] -> Player -> Player
addCards a (Player t n c) = Player t n (a ++ c)
applyHand :: (Hand -> Hand) -> Player -> Player
applyHand f (Player t n c) = Player t n (f c)
| Kingdread/Huno | src/Player.hs | bsd-2-clause | 398 | 0 | 8 | 107 | 165 | 91 | 74 | 12 | 1 |
module Text.Md.MdParserSpec (
main,
spec,
) where
import Test.Hspec
import Text.Md.MdParser
-- Not necessary for automatic test discovery
main :: IO ()
main = hspec spec
-- Must export `spec` as type of `Spec`
spec :: Spec
spec = do
describe "parseMd" $ do
it "parses to paragraph" $
parseMd "foobar\n\n"
`shouldBe`
"<div><p>foobar</p></div>"
it "parses to header" $ do
parseMd "# header1\n\npara1\n\n## header2\n\n### header3\n\n"
`shouldBe`
"<div><h1>header1</h1><p>para1</p><h2>header2</h2><h3>header3</h3></div>"
it "parses html block elements to blocks without framing by 'p' tag" $ do
parseMd "line1\n\n<div id=\"header\">**line2**</div>\n\nline3\n\n" `shouldBe` "<div><p>line1</p><div id=\"header\">**line2**</div><p>line3</p></div>"
parseMd "line1\n\n<div><ul><li>list1</li><li>list2</li>\n\n</ul></div>\n\nline3\n\n" `shouldBe` "<div><p>line1</p><div><ul><li>list1</li><li>list2</li>\n\n</ul></div><p>line3</p></div>"
-- attributes and text framed by tags are escaped.
parseMd "<div class=\"a&b\">\n one & two\n</div>\n\n" `shouldBe` "<div><div class=\"a&b\">\n one & two\n</div></div>"
it "parses to horizontal rule" $ do
parseMd "foobar\n\n---\n\nfoobar\n\n" `shouldBe` "<div><p>foobar</p><hr /><p>foobar</p></div>"
parseMd "foobar\n\n- - - \n\nfoobar\n\n" `shouldBe` "<div><p>foobar</p><hr /><p>foobar</p></div>"
parseMd "foobar\n\n___\n\n***\n\n" `shouldBe` "<div><p>foobar</p><hr /><hr /></div>"
it "parses to simple list" $ do
parseMd "- one\n- two\n- three\n\n" `shouldBe` "<div><ul><li>one</li><li>two</li><li>three</li></ul></div>"
parseMd "+ one\n+ **two**\n+ three\n\n" `shouldBe` "<div><ul><li>one</li><li><strong>two</strong></li><li>three</li></ul></div>"
parseMd "* one\n* **two**\n* three\n\n" `shouldBe` "<div><ul><li>one</li><li><strong>two</strong></li><li>three</li></ul></div>"
it "parses to list with multiple lines" $ do
parseMd "- one\ntwo, three\n- four\n and\n- five\n\n" `shouldBe` "<div><ul><li>one two, three</li><li>four and</li><li>five</li></ul></div>"
it "parses to list with paragraphs" $ do
parseMd "prev para\n\n- one\n\n- two\n\nfollowing para\n\n" `shouldBe` "<div><p>prev para</p><ul><li><p>one</p></li><li><p>two</p></li></ul><p>following para</p></div>"
parseMd "- one\ntwo\n\n- three\n four\n\n" `shouldBe` "<div><ul><li><p>one two</p></li><li><p>three four</p></li></ul></div>"
parseMd "- one\n\n two\n\n three\n\n- four\n\n five\n\n" `shouldBe` "<div><ul><li><p>one</p><p>two</p><p>three</p></li><li><p>four</p><p>five</p></li></ul></div>"
parseMd "- one\n two\n\n three\n four\n\n- five\n six\n\n" `shouldBe` "<div><ul><li><p>one two</p><p>three four</p></li><li><p>five six</p></li></ul></div>"
it "parses to list with different levels" $ do
parseMd "- one\n- two\n - three\n - four\n - five\n- six\n - seven\n\n" `shouldBe` "<div><ul><li>one</li><li>two<ul><li>three<ul><li>four</li></ul></li><li>five</li></ul></li><li>six<ul><li>seven</li></ul></li></ul></div>"
parseMd "- one\n\n- two\n\n three\n\n - four\n\n" `shouldBe` "<div><ul><li><p>one</p></li><li><p>two</p><p>three</p><ul><li><p>four</p></li></ul></li></ul></div>"
it "parses to code blocks" $ do
parseMd "```\none\ntwo & three\n\nfour"\n```\n\n" `shouldBe` "<div><pre><code>one\ntwo & three\n\nfour&quot;</code></pre></div>"
parseMd "```\n**one** and `two`\n```\n\n" `shouldBe` "<div><pre><code>**one** and `two`</code></pre></div>"
it "parses to block quotes" $ do
parseMd "prev para\n\n> aaa\n> bbb\n\nfollowing para\n\n" `shouldBe` "<div><p>prev para</p><blockquote><p>aaa bbb</p></blockquote><p>following para</p></div>"
parseMd "> aaa\nbbb\n\n" `shouldBe` "<div><blockquote><p>aaa bbb</p></blockquote></div>"
it "parses to block quote with multiple paragraphs" $ do
parseMd ">one\n>two\n>\n>three\n>\n>four\n>five\n\nfollowing para\n\n" `shouldBe` "<div><blockquote><p>one two</p><p>three</p><p>four five</p></blockquote><p>following para</p></div>"
-- To parse blocks, space is necessary after '>'
it "parses to block quote contains other kinds of blocks" $ do
-- head and list
parseMd "> # head1\n>\n> - one\n> - two\n> - three\n\n" `shouldBe` "<div><blockquote><h1>head1</h1><ul><li>one</li><li>two<ul><li>three</li></ul></li></ul></blockquote></div>"
-- code blocks
parseMd "> ```\n> code1\n> code2\n> ```\n>\n> ---\n>\n> <div>html content</div>\n\n" `shouldBe` "<div><blockquote><pre><code>code1\ncode2</code></pre><hr /><div>html content</div></blockquote></div>"
-- html blocks
parseMd "> <div class=\"a&b\">\n> one & two\n> </div>\n\n" `shouldBe` "<div><blockquote><div class=\"a&b\">\n one & two\n</div></blockquote></div>"
-- inner blockquotes
parseMd "> one\n>\n> > two\n>\n> three\n\n" `shouldBe` "<div><blockquote><p>one</p><blockquote><p>two</p></blockquote><p>three</p></blockquote></div>"
parseMd "> one\n>\n> oneone\n>\n> > # two\n> >\n> > twotwo\n\n" `shouldBe` "<div><blockquote><p>one</p><p>oneone</p><blockquote><h1>two</h1><p>twotwo</p></blockquote></blockquote></div>"
it "parses to strong" $ do
parseMd "this is **strong**\n\n" `shouldBe` "<div><p>this is <strong>strong</strong></p></div>"
parseMd "this is **also\nstrong**\n\n" `shouldBe` "<div><p>this is <strong>also strong</strong></p></div>"
parseMd "this is **str\\*\\*ong**\n\n" `shouldBe` "<div><p>this is <strong>str**ong</strong></p></div>"
it "parses to emphasis" $ do
parseMd "this is *emphasis*\n\n" `shouldBe` "<div><p>this is <em>emphasis</em></p></div>"
parseMd "this is *e\\*m*\n\n" `shouldBe` "<div><p>this is <em>e*m</em></p></div>"
it "parses to inline link" $ do
parseMd "this is [inline link](http://foo.com \"inline-link\").\n\n" `shouldBe` "<div><p>this is <a href=\"http://foo.com\" title=\"inline-link\">inline link</a>.</p></div>"
it "parses to reference link" $ do
parseMd "this is [reference link][1].\n\n[1]: http://foo.com\n\n" `shouldBe` "<div><p>this is <a href=\"http://foo.com\">reference link</a>.</p></div>"
parseMd "this is [reference link][1].\n\n[1]: http://foo.com \"link title\"\n\n" `shouldBe` "<div><p>this is <a href=\"http://foo.com\" title=\"link title\">reference link</a>.</p></div>"
it "parses to multiple reference links" $ do
parseMd "[one][1], [two][2], [three][3]\n\n[1]: http://one.com\n[2]: http://two.com\n[3]: http://three.com\n\n"
`shouldBe`
"<div><p><a href=\"http://one.com\">one</a>, <a href=\"http://two.com\">two</a>, <a href=\"http://three.com\">three</a></p></div>"
it "parses to linebreak and softbreak in paragraph" $ do
parseMd "Before break \nafter break\nand just space\n\n"
`shouldBe`
"<div><p>Before break<br />after break and just space</p></div>"
it "parses incomplete strong symbol to just chars" $ do
parseMd "**abc\n\n" `shouldBe` "<div><p>**abc</p></div>"
parseMd "abc**\n\n" `shouldBe` "<div><p>abc**</p></div>"
parseMd "**abc\n\n**\n\n" `shouldBe` "<div><p>**abc</p><p>**</p></div>"
it "parses inline codes" $ do
parseMd "one ` two three ` four\n\n" `shouldBe` "<div><p>one <code>two three</code> four</p></div>"
parseMd "` one & two & three `\n\n" `shouldBe` "<div><p><code>one & two &amp; three</code></p></div>"
parseMd "``` `two` three `four` ```\n\n" `shouldBe` "<div><p><code>`two` three `four`</code></p></div>"
it "parses html inline elements and just show original text" $ do
parseMd "this is framed by <span class=\"cl1\">span</span> tag.\n\n"
`shouldBe`
"<div><p>this is framed by <span class=\"cl1\">span</span> tag.</p></div>"
it "accepts markdown literals inside html inline elements" $ do
parseMd "this is framed by <span class=\"cl1\">not span but **span**</span> tag.\n\n"
`shouldBe`
"<div><p>this is framed by <span class=\"cl1\">not span but <strong>span</strong></span> tag.</p></div>"
it "escapes markdown literals" $ do
parseMd "Is this \\*\\*escaped?\\*\\*.\n\n" `shouldBe` "<div><p>Is this **escaped?**.</p></div>"
parseMd "Is this <span>\\*\\*escaped?\\*\\*.</span>\n\n" `shouldBe` "<div><p>Is this <span>**escaped?**.</span></p></div>"
it "escapes html" $ do
parseMd "Is this escaped? \"5 > 2 && 5 < 2\"\n\n" `shouldBe` "<div><p>Is this escaped? "5 > 2 && 5 < 2"</p></div>"
parseMd "This is already escaped, &, <, >, & "\n\n" `shouldBe` "<div><p>This is already escaped, &, <, >, & "</p></div>"
describe "parseMdFile" $ do
it "parses complex markdown" $ do
actual <- parseMdFileFormat "samples/sample.md"
expect <- readFile "samples/sample-expect.html"
actual `shouldBe` expect
| tiqwab/md-parser | test/Text/Md/MdParserSpec.hs | bsd-3-clause | 9,021 | 0 | 14 | 1,433 | 959 | 461 | 498 | 101 | 1 |
{-# LANGUAGE BangPatterns #-}
module Data.Graph.Algorithms.Dominators ( dom, iDom ) where
import Data.Graph.Interface
import Data.Graph.Algorithms.DFS ( dff )
import Data.Tree ( Tree(..) )
import qualified Data.Tree as T
import Data.Array
import Data.List ( foldl' )
import Data.Map ( Map )
import qualified Data.Map as M
iDom :: (DecomposableGraph gr, VertexListGraph gr, BidirectionalAdjacencyGraph gr)
=> gr -> Vertex -> Maybe [(Vertex, Vertex)]
iDom g root = do
(result, toNode, _) <- idomWork g root
let toResult (a, b) = (toNode ! a, toNode ! b)
return $ map toResult (assocs result)
dom :: (DecomposableGraph gr, VertexListGraph gr, BidirectionalAdjacencyGraph gr)
=> gr -> Vertex -> Maybe [(Vertex, [Vertex])]
dom g root = do
(idoms, toNode, fromNode) <- idomWork g root
let e1 = (0, [toNode ! 0])
relems = [(i, toNode ! i : dom' ! (idoms ! i)) | i <- range (bounds idoms)]
dom' = array (0, snd (bounds idoms)) (e1 : relems)
nodes' = vertices g
rest = M.keys (M.filter (-1 ==) fromNode)
return $ [(toNode ! i, dom' ! i) | i <- range (bounds dom')] ++
[(n, nodes') | n <- rest]
type Node' = Int
type IDom = Array Node' Node'
type Preds = Array Node' [Node']
type ToNode = Array Node' Vertex
type FromNode = Map Vertex Node'
idomWork :: (DecomposableGraph gr, VertexListGraph gr, BidirectionalAdjacencyGraph gr)
=> gr -> Vertex -> Maybe (IDom, ToNode, FromNode)
idomWork g root
| null trees = Nothing
| otherwise = Just (doms, toNode, fromNode)
where
trees@(~[tree]) = dff [root] g
(s, ntree) = numberTree 0 tree
idom0 = array (1, s-1) (treeEdges ntree)
fromNode = M.unionWith const (M.fromList (zip (T.flatten tree) (T.flatten ntree))) (M.fromList (zip (vertices g) (repeat (-1))))
toNode = array (0, s-1) (zip (T.flatten ntree) (T.flatten tree))
preds = array (1, s-1) [(i, filter (/= -1) (map (fromNode M.!) (pre g (toNode ! i)))) | i <- [1..s-1]]
doms = fixEq (refineIDom preds) idom0
refineIDom :: Preds -> IDom -> IDom
refineIDom preds idom = fmap (foldl1 (intersect idom)) preds
intersect :: IDom -> Node' -> Node' -> Node'
intersect idom a b =
case a `compare` b of
LT -> intersect idom a (idom ! b)
EQ -> a
GT -> intersect idom (idom ! a) b
numberTree :: Node' -> Tree a -> (Node', Tree Node')
numberTree !n !(Node _ ts) = (n', Node n ts')
where
(n', ts') = numberForest (n + 1) ts
numberForest :: Node' -> [Tree a] -> (Node', [Tree Node'])
numberForest !n [] = (n, [])
numberForest !n (t:ts) = (n'', t' : ts')
where
(n', t') = numberTree n t
(n'', ts') = numberForest n' ts
treeEdges :: Tree a -> [(a, a)]
treeEdges = go []
where
go acc (Node a ts) =
let es = map (\t -> (rootLabel t, a)) ts
in foldl' go (es ++ acc) ts
fixEq :: (Eq a) => (a -> a) -> a -> a
fixEq f v | v' == v = v
| otherwise = fixEq f v'
where
v' = f v
| travitch/hbgl-experimental | src/Data/Graph/Algorithms/Dominators.hs | bsd-3-clause | 2,918 | 0 | 16 | 684 | 1,424 | 761 | 663 | 69 | 3 |
import Control.Concurrent
import Control.Monad
import Data.IORef
threadA :: (IORef Int, IORef Int) -> IO ()
threadA (aref,bref) = do
a <- readIORef aref
b <- readIORef bref
putStrLn $ "threadA:" ++ show a ++ ", " ++ show b
-- threadDelay 100000
writeIORef aref (a+1)
writeIORef bref (b-1)
threadB :: (IORef Int, IORef Int) -> IO ()
threadB (aref,bref) = do
a <- readIORef aref
threadDelay 100
b <- readIORef bref
putStrLn $ "threadB:" ++ show a ++ ", " ++ show b
writeIORef aref (a-1)
writeIORef bref (b+1)
main :: IO ()
main = do
aref <- newIORef (100 :: Int)
bref <- newIORef (100 :: Int)
forkIO $ replicateM_ 1000 (threadA (aref,bref))
replicateM_ 1000 (threadB (aref,bref))
return ()
| wavewave/chatter | test/ioref.hs | bsd-3-clause | 764 | 0 | 11 | 196 | 352 | 169 | 183 | 25 | 1 |
-- Copyright 2013 Kevin Backhouse.
module TestAssembler ( tests ) where
import qualified Test.Framework as TF ( Test )
import Test.Framework.Providers.HUnit
import Control.Monad ( when )
import Control.Monad.ST2
import Control.Monad.MultiPass
import Control.Monad.MultiPass.Example.Assembler
import Data.Array
import Data.Word
tests :: [TF.Test]
tests =
concat $
[ [ testCase "example1" $ prop_assemble n (genExample 1) output1
, testCase "example2" $ prop_assemble n (genExample 2) output2
, testCase "example3" $ prop_assemble n (genExample 3) output3
, testCase "example10" $ prop_assemble n (genExample 10) output10
, testCase "example30" $ prop_assemble n (genExample 30) output30
]
| n <- [1..4]
]
prop_assemble :: Int -> [Instruction] -> [Word8] -> IO ()
prop_assemble nThreads input output =
st2ToIO $
do output' <- runAssembler nThreads input
when (output /= output') $ fail (show output')
-- | Simple wrapper around 'assembler' which reads the instructions
-- from a list and returns the result as a list.
runAssembler :: Int -> [Instruction] -> ST2 r w [Word8]
runAssembler nThreads example =
do instructions <- newST2Array_ (0, length example - 1)
sequence_
[ writeST2Array instructions i instr
| (i,instr) <- zip [0..] example
]
xs <- assemble (NumThreads nThreads) instructions
bnds <- boundsST2Array xs
sequence
[ readST2Array xs i
| i <- range bnds
]
output1 :: [Word8]
output1 =
[ 72, 131, 192, 0, 235, 250, 72, 131, 192, 0 ]
output2 :: [Word8]
output2 =
[ 72, 131, 192, 0, 72, 131, 192, 1, 235, 250, 72, 131, 192, 0, 235,
240, 72, 131, 192, 1 ]
output3 :: [Word8]
output3 =
[ 72, 131, 192, 0, 72, 131, 192, 1, 72, 131, 192, 2, 235, 250, 72,
131, 192, 0, 235, 240, 72, 131, 192, 1, 235, 230, 72, 131, 192, 2 ]
output10 :: [Word8]
output10 =
[ 72, 131, 192, 0, 72, 131, 192, 1, 72, 131, 192, 2, 72, 131, 192,
3, 72, 131, 192, 4, 72, 131, 192, 5, 72, 131, 192, 6, 72, 131,
192, 7, 72, 131, 192, 8, 72, 131, 192, 9, 235, 250, 72, 131, 192,
0, 235, 240, 72, 131, 192, 1, 235, 230, 72, 131, 192, 2, 235, 220,
72, 131, 192, 3, 235, 210, 72, 131, 192, 4, 235, 200, 72, 131,
192, 5, 235, 190, 72, 131, 192, 6, 235, 180, 72, 131, 192, 7, 235,
170, 72, 131, 192, 8, 235, 160, 72, 131, 192, 9 ]
output30 :: [Word8]
output30 =
[ 72, 131, 192, 0, 72, 131, 192, 1, 72, 131, 192, 2, 72, 131, 192,
3, 72, 131, 192, 4, 72, 131, 192, 5, 72, 131, 192, 6, 72, 131,
192, 7, 72, 131, 192, 8, 72, 131, 192, 9, 72, 131, 192, 10, 72,
131, 192, 11, 72, 131, 192, 12, 72, 131, 192, 13, 72, 131, 192,
14, 72, 131, 192, 15, 72, 131, 192, 16, 72, 131, 192, 17, 72, 131,
192, 18, 72, 131, 192, 19, 72, 131, 192, 20, 72, 131, 192, 21, 72,
131, 192, 22, 72, 131, 192, 23, 72, 131, 192, 24, 72, 131, 192,
25, 72, 131, 192, 26, 72, 131, 192, 27, 72, 131, 192, 28, 72, 131,
192, 29, 235, 250, 72, 131, 192, 0, 235, 240, 72, 131, 192, 1,
235, 230, 72, 131, 192, 2, 235, 220, 72, 131, 192, 3, 235, 210,
72, 131, 192, 4, 235, 200, 72, 131, 192, 5, 235, 190, 72, 131,
192, 6, 235, 180, 72, 131, 192, 7, 235, 170, 72, 131, 192, 8, 235,
160, 72, 131, 192, 9, 235, 150, 72, 131, 192, 10, 235, 140, 72,
131, 192, 11, 235, 130, 72, 131, 192, 12, 233, 117, 255, 255, 255,
72, 131, 192, 13, 233, 104, 255, 255, 255, 72, 131, 192, 14, 233,
91, 255, 255, 255, 72, 131, 192, 15, 233, 78, 255, 255, 255, 72,
131, 192, 16, 233, 65, 255, 255, 255, 72, 131, 192, 17, 233, 52,
255, 255, 255, 72, 131, 192, 18, 233, 39, 255, 255, 255, 72, 131,
192, 19, 233, 26, 255, 255, 255, 72, 131, 192, 20, 233, 13, 255,
255, 255, 72, 131, 192, 21, 233, 0, 255, 255, 255, 72, 131, 192,
22, 233, 243, 254, 255, 255, 72, 131, 192, 23, 233, 230, 254, 255,
255, 72, 131, 192, 24, 233, 217, 254, 255, 255, 72, 131, 192, 25,
233, 204, 254, 255, 255, 72, 131, 192, 26, 233, 191, 254, 255,
255, 72, 131, 192, 27, 233, 178, 254, 255, 255, 72, 131, 192, 28,
233, 165, 254, 255, 255, 72, 131, 192, 29 ]
-- Generate an example input containing some add instructions, labels,
-- and gotos. The argument n determines the size of the example
-- generated.
genExample :: Int -> [Instruction]
genExample n =
concat
[ [ Label $ LabelName $ show i
, AddImm8 (Register 0) (fromIntegral i)
]
| i <- [0 .. n-1]
] ++
concat
[ [ Goto $ LabelName $ show (n - i - 1)
, AddImm8 (Register 0) (fromIntegral i)
]
| i <- [0 .. n-1]
]
| kevinbackhouse/Control-Monad-MultiPass | tests/TestAssembler.hs | bsd-3-clause | 4,555 | 0 | 13 | 1,136 | 2,206 | 1,380 | 826 | 92 | 1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ExplicitNamespaces #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Type.Equality
-- License : BSD-style (see the LICENSE file in the distribution)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : not portable
--
-- Definition of propositional equality @(:~:)@. Pattern-matching on a variable
-- of type @(a :~: b)@ produces a proof that @a ~ b@.
--
-- @since 4.7.0.0
-----------------------------------------------------------------------------
module Data.Type.Equality (
-- * The equality types
(:~:)(..), type (~~),
-- * Working with equality
sym, trans, castWith, gcastWith, apply, inner, outer,
-- * Inferring equality from other types
TestEquality(..),
-- * Boolean type-level equality
type (==)
) where
import Data.Maybe
import GHC.Enum
import GHC.Show
import GHC.Read
import GHC.Base
import Data.Type.Bool
-- | Lifted, homogeneous equality. By lifted, we mean that it can be
-- bogus (deferred type error). By homogeneous, the two types @a@
-- and @b@ must have the same kind.
class a ~~ b => (a :: k) ~ (b :: k) | a -> b, b -> a
-- See Note [The equality types story] in TysPrim
-- NB: All this class does is to wrap its superclass, which is
-- the "real", inhomogeneous equality; this is needed when
-- we have a Given (a~b), and we want to prove things from it
-- NB: Not exported, as (~) is magical syntax. That's also why there's
-- no fixity.
instance {-# INCOHERENT #-} a ~~ b => a ~ b
-- See Note [The equality types story] in TysPrim
-- If we have a Wanted (t1 ~ t2), we want to immediately
-- simplify it to (t1 ~~ t2) and solve that instead
--
-- INCOHERENT because we want to use this instance eagerly, even when
-- the tyvars are partially unknown.
infix 4 :~:
-- | Propositional equality. If @a :~: b@ is inhabited by some terminating
-- value, then the type @a@ is the same as the type @b@. To use this equality
-- in practice, pattern-match on the @a :~: b@ to get out the @Refl@ constructor;
-- in the body of the pattern-match, the compiler knows that @a ~ b@.
--
-- @since 4.7.0.0
data a :~: b where -- See Note [The equality types story] in TysPrim
Refl :: a :~: a
-- with credit to Conal Elliott for 'ty', Erik Hesselink & Martijn van
-- Steenbergen for 'type-equality', Edward Kmett for 'eq', and Gabor Greif
-- for 'type-eq'
-- | Symmetry of equality
sym :: (a :~: b) -> (b :~: a)
sym Refl = Refl
-- | Transitivity of equality
trans :: (a :~: b) -> (b :~: c) -> (a :~: c)
trans Refl Refl = Refl
-- | Type-safe cast, using propositional equality
castWith :: (a :~: b) -> a -> b
castWith Refl x = x
-- | Generalized form of type-safe cast using propositional equality
gcastWith :: (a :~: b) -> ((a ~ b) => r) -> r
gcastWith Refl x = x
-- | Apply one equality to another, respectively
apply :: (f :~: g) -> (a :~: b) -> (f a :~: g b)
apply Refl Refl = Refl
-- | Extract equality of the arguments from an equality of a applied types
inner :: (f a :~: g b) -> (a :~: b)
inner Refl = Refl
-- | Extract equality of type constructors from an equality of applied types
outer :: (f a :~: g b) -> (f :~: g)
outer Refl = Refl
deriving instance Eq (a :~: b)
deriving instance Show (a :~: b)
deriving instance Ord (a :~: b)
instance a ~ b => Read (a :~: b) where
readsPrec d = readParen (d > 10) (\r -> [(Refl, s) | ("Refl",s) <- lex r ])
instance a ~ b => Enum (a :~: b) where
toEnum 0 = Refl
toEnum _ = errorWithoutStackTrace "Data.Type.Equality.toEnum: bad argument"
fromEnum Refl = 0
instance a ~ b => Bounded (a :~: b) where
minBound = Refl
maxBound = Refl
-- | This class contains types where you can learn the equality of two types
-- from information contained in /terms/. Typically, only singleton types should
-- inhabit this class.
class TestEquality f where
-- | Conditionally prove the equality of @a@ and @b@.
testEquality :: f a -> f b -> Maybe (a :~: b)
instance TestEquality ((:~:) a) where
testEquality Refl Refl = Just Refl
-- | A type family to compute Boolean equality. Instances are provided
-- only for /open/ kinds, such as @*@ and function kinds. Instances are
-- also provided for datatypes exported from base. A poly-kinded instance
-- is /not/ provided, as a recursive definition for algebraic kinds is
-- generally more useful.
type family (a :: k) == (b :: k) :: Bool
infix 4 ==
{-
This comment explains more about why a poly-kinded instance for (==) is
not provided. To be concrete, here would be the poly-kinded instance:
type family EqPoly (a :: k) (b :: k) where
EqPoly a a = True
EqPoly a b = False
type instance (a :: k) == (b :: k) = EqPoly a b
Note that this overlaps with every other instance -- if this were defined,
it would be the only instance for (==).
Now, consider
data Nat = Zero | Succ Nat
Suppose I want
foo :: (Succ n == Succ m) ~ True => ((n == m) :~: True)
foo = Refl
This would not type-check with the poly-kinded instance. `Succ n == Succ m`
quickly becomes `EqPoly (Succ n) (Succ m)` but then is stuck. We don't know
enough about `n` and `m` to reduce further.
On the other hand, consider this:
type family EqNat (a :: Nat) (b :: Nat) where
EqNat Zero Zero = True
EqNat (Succ n) (Succ m) = EqNat n m
EqNat n m = False
type instance (a :: Nat) == (b :: Nat) = EqNat a b
With this instance, `foo` type-checks fine. `Succ n == Succ m` becomes `EqNat
(Succ n) (Succ m)` which becomes `EqNat n m`. Thus, we can conclude `(n == m)
~ True` as desired.
So, the Nat-specific instance allows strictly more reductions, and is thus
preferable to the poly-kinded instance. But, if we introduce the poly-kinded
instance, we are barred from writing the Nat-specific instance, due to
overlap.
Even better than the current instance for * would be one that does this sort
of recursion for all datatypes, something like this:
type family EqStar (a :: *) (b :: *) where
EqStar Bool Bool = True
EqStar (a,b) (c,d) = a == c && b == d
EqStar (Maybe a) (Maybe b) = a == b
...
EqStar a b = False
The problem is the (...) is extensible -- we would want to add new cases for
all datatypes in scope. This is not currently possible for closed type
families.
-}
-- all of the following closed type families are local to this module
type family EqStar (a :: *) (b :: *) where
EqStar _a _a = 'True
EqStar _a _b = 'False
-- This looks dangerous, but it isn't. This allows == to be defined
-- over arbitrary type constructors.
type family EqArrow (a :: k1 -> k2) (b :: k1 -> k2) where
EqArrow _a _a = 'True
EqArrow _a _b = 'False
type family EqBool a b where
EqBool 'True 'True = 'True
EqBool 'False 'False = 'True
EqBool _a _b = 'False
type family EqOrdering a b where
EqOrdering 'LT 'LT = 'True
EqOrdering 'EQ 'EQ = 'True
EqOrdering 'GT 'GT = 'True
EqOrdering _a _b = 'False
type EqUnit (a :: ()) (b :: ()) = 'True
type family EqList a b where
EqList '[] '[] = 'True
EqList (h1 ': t1) (h2 ': t2) = (h1 == h2) && (t1 == t2)
EqList _a _b = 'False
type family EqMaybe a b where
EqMaybe 'Nothing 'Nothing = 'True
EqMaybe ('Just x) ('Just y) = x == y
EqMaybe _a _b = 'False
type family Eq2 a b where
Eq2 '(a1, b1) '(a2, b2) = a1 == a2 && b1 == b2
type family Eq3 a b where
Eq3 '(a1, b1, c1) '(a2, b2, c2) = a1 == a2 && b1 == b2 && c1 == c2
type family Eq4 a b where
Eq4 '(a1, b1, c1, d1) '(a2, b2, c2, d2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2
type family Eq5 a b where
Eq5 '(a1, b1, c1, d1, e1) '(a2, b2, c2, d2, e2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2
type family Eq6 a b where
Eq6 '(a1, b1, c1, d1, e1, f1) '(a2, b2, c2, d2, e2, f2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 && f1 == f2
type family Eq7 a b where
Eq7 '(a1, b1, c1, d1, e1, f1, g1) '(a2, b2, c2, d2, e2, f2, g2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 && f1 == f2 && g1 == g2
type family Eq8 a b where
Eq8 '(a1, b1, c1, d1, e1, f1, g1, h1) '(a2, b2, c2, d2, e2, f2, g2, h2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 && f1 == f2 && g1 == g2 && h1 == h2
type family Eq9 a b where
Eq9 '(a1, b1, c1, d1, e1, f1, g1, h1, i1) '(a2, b2, c2, d2, e2, f2, g2, h2, i2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 && f1 == f2 && g1 == g2 && h1 == h2 && i1 == i2
type family Eq10 a b where
Eq10 '(a1, b1, c1, d1, e1, f1, g1, h1, i1, j1) '(a2, b2, c2, d2, e2, f2, g2, h2, i2, j2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 && f1 == f2 && g1 == g2 && h1 == h2 && i1 == i2 && j1 == j2
type family Eq11 a b where
Eq11 '(a1, b1, c1, d1, e1, f1, g1, h1, i1, j1, k1) '(a2, b2, c2, d2, e2, f2, g2, h2, i2, j2, k2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 && f1 == f2 && g1 == g2 && h1 == h2 && i1 == i2 && j1 == j2 && k1 == k2
type family Eq12 a b where
Eq12 '(a1, b1, c1, d1, e1, f1, g1, h1, i1, j1, k1, l1) '(a2, b2, c2, d2, e2, f2, g2, h2, i2, j2, k2, l2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 && f1 == f2 && g1 == g2 && h1 == h2 && i1 == i2 && j1 == j2 && k1 == k2 && l1 == l2
type family Eq13 a b where
Eq13 '(a1, b1, c1, d1, e1, f1, g1, h1, i1, j1, k1, l1, m1) '(a2, b2, c2, d2, e2, f2, g2, h2, i2, j2, k2, l2, m2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 && f1 == f2 && g1 == g2 && h1 == h2 && i1 == i2 && j1 == j2 && k1 == k2 && l1 == l2 && m1 == m2
type family Eq14 a b where
Eq14 '(a1, b1, c1, d1, e1, f1, g1, h1, i1, j1, k1, l1, m1, n1) '(a2, b2, c2, d2, e2, f2, g2, h2, i2, j2, k2, l2, m2, n2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 && f1 == f2 && g1 == g2 && h1 == h2 && i1 == i2 && j1 == j2 && k1 == k2 && l1 == l2 && m1 == m2 && n1 == n2
type family Eq15 a b where
Eq15 '(a1, b1, c1, d1, e1, f1, g1, h1, i1, j1, k1, l1, m1, n1, o1) '(a2, b2, c2, d2, e2, f2, g2, h2, i2, j2, k2, l2, m2, n2, o2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 && f1 == f2 && g1 == g2 && h1 == h2 && i1 == i2 && j1 == j2 && k1 == k2 && l1 == l2 && m1 == m2 && n1 == n2 && o1 == o2
-- these all look to be overlapping, but they are differentiated by their kinds
type instance a == b = EqStar a b
type instance a == b = EqArrow a b
type instance a == b = EqBool a b
type instance a == b = EqOrdering a b
type instance a == b = EqUnit a b
type instance a == b = EqList a b
type instance a == b = EqMaybe a b
type instance a == b = Eq2 a b
type instance a == b = Eq3 a b
type instance a == b = Eq4 a b
type instance a == b = Eq5 a b
type instance a == b = Eq6 a b
type instance a == b = Eq7 a b
type instance a == b = Eq8 a b
type instance a == b = Eq9 a b
type instance a == b = Eq10 a b
type instance a == b = Eq11 a b
type instance a == b = Eq12 a b
type instance a == b = Eq13 a b
type instance a == b = Eq14 a b
type instance a == b = Eq15 a b
| gridaphobe/ghc | libraries/base/Data/Type/Equality.hs | bsd-3-clause | 11,466 | 21 | 34 | 2,818 | 3,515 | 2,025 | 1,490 | -1 | -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.
module Duckling.Quantity.PT.Tests
( tests ) where
import Prelude
import Data.String
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.Quantity.PT.Corpus
import Duckling.Testing.Asserts
tests :: TestTree
tests = testGroup "PT Tests"
[ makeCorpusTest [Seal Quantity] corpus
]
| facebookincubator/duckling | tests/Duckling/Quantity/PT/Tests.hs | bsd-3-clause | 507 | 0 | 9 | 78 | 79 | 50 | 29 | 11 | 1 |
{-# LANGUAGE LambdaCase #-}
module Main where
import UI.Dialogui
import UI.Dialogui.TUI
main :: IO ()
main =
let
setup = writeLn "Echo service is ready!"
in
runTUI setup echo
echo :: (Monad m) => Controller m Int
echo =
Controller
{ initialize = return 1
, finalize = const $ return ()
, communicate = (return .) . communicate'
}
where
communicate' cnt = \case
"" ->
showHelp
":?" ->
showHelp
":q" ->
quit
":r" ->
clear <> clearInput
msg ->
setState (cnt + 1)
<> clearInput
<> write (show cnt)
<> write ": "
<> writeLn msg
showHelp =
write
$ unlines
[ "Use:"
, " \":?\" to show this help"
, " \":q\" to quit (Ctrl+D works same way)"
, " \":r\" to reset state"
, " <msg> to see an echo"
]
clearInput = setInput ""
| astynax/dialogui | examples/Echo.hs | bsd-3-clause | 936 | 0 | 16 | 362 | 236 | 125 | 111 | 39 | 5 |
module Math.IRT.Model.TwoPLM
( TwoPLM (..)
) where
import Statistics.Distribution
import Math.IRT.Internal.Distribution
import Math.IRT.Internal.LogLikelihood
import Math.IRT.Model.FourPLM ( FourPLM(..) )
import Math.IRT.Model.Generic
data TwoPLM = TwoPLM { discrimination :: !Double
, difficulty :: !Double
} deriving (Show)
instance Distribution TwoPLM where
cumulative = cumulative . toFourPLM
instance ContDistr TwoPLM where
density = density . toFourPLM
quantile _ = error "This shouldn't be needed"
instance DensityDeriv TwoPLM where
densityDeriv = densityDeriv . toFourPLM
instance GenericModel TwoPLM where
fromRasch b = TwoPLM 1.0 b
fromOnePLM b = TwoPLM 1.7 b
fromTwoPLM = TwoPLM
fromThreePLM a b _ = TwoPLM a b
fromFourPLM a b _ _ = TwoPLM a b
instance LogLikelihood TwoPLM where
logLikelihood b = logLikelihood b . toFourPLM
toFourPLM :: TwoPLM -> FourPLM
toFourPLM (TwoPLM sa sb) = FourPLM sa sb 0.0 1.0
| argiopetech/irt | Math/IRT/Model/TwoPLM.hs | bsd-3-clause | 1,049 | 0 | 9 | 264 | 283 | 154 | 129 | 31 | 1 |
module Solr.Query.Internal.Internal where
import Solr.Prelude
import Builder
class (Coercible query Builder, Default (LocalParams query))
=> Query query where
data LocalParams query :: *
compileLocalParams :: LocalParams query -> [(Builder, Builder)]
coerceQuery :: Query query => query -> Builder
coerceQuery = coerce
(&&:) :: Query query => query -> query -> query
(&&:) q1 q2 = coerce (parens (coerce q1 <> " AND " <> coerce q2))
infixr 3 &&:
(||:) :: Query query => query -> query -> query
(||:) q1 q2 = coerce (parens (coerce q1 <> " OR " <> coerce q2))
infixr 2 ||:
(-:) :: Query query => query -> query -> query
(-:) q1 q2 = coerce (parens (coerce q1 <> " NOT " <> coerce q2))
infixl 6 -:
-- | The @\'^\'@ operator, which boosts a 'Query'.
boost :: Query query => Float -> query -> query
boost n q = coerce (parens (coerce q <> char '^' <> bshow n))
-- | The @\'^=\'@ operator, which assigns a constant score to a 'Query'.
score :: Query query => Float -> query -> query
score n q = coerce (parens (coerce q <> "^=" <> bshow n))
-- | 'SomeQuery' is a simple wrapper around a 'Query' that enables composition
-- through its 'Monoid' instance.
--
-- It has no 'LocalParams' of its own - you can only create them with 'def'.
newtype SomeQuery
= SomeQ Builder
instance Query SomeQuery where
data LocalParams SomeQuery = SomeQueryParams -- unused
compileLocalParams :: LocalParams SomeQuery -> [(Builder, Builder)]
compileLocalParams _ = []
instance Default (LocalParams SomeQuery) where
def = SomeQueryParams
-- | Create a 'SomeQuery' from a 'Query' and its 'LocalParams'.
someQuery :: Query query => LocalParams query -> query -> SomeQuery
someQuery locals query = SomeQ (compileQuery locals query)
-- | Compile a 'Query' and its 'LocalParams' to a 'Builder'.
compileQuery :: Query query => LocalParams query -> query -> Builder
compileQuery locals query =
case compileLocalParams locals of
[] -> coerce query
xs -> mconcat
[ "{!"
, intersperse ' ' (map (\(x, y) -> x <> char '=' <> y) xs)
, char '}'
, coerce query
]
| Sentenai/solr-query | src/Solr/Query/Internal/Internal.hs | bsd-3-clause | 2,096 | 0 | 17 | 429 | 653 | 341 | 312 | -1 | -1 |
-----------------------------------------------------------------------------
--
-- GHC Interactive support for inspecting arbitrary closures at runtime
--
-- Pepe Iborra (supported by Google SoC) 2006
--
-----------------------------------------------------------------------------
{-# 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
module RtClosureInspect(
cvObtainTerm, -- :: HscEnv -> Int -> Bool -> Maybe Type -> HValue -> IO Term
cvReconstructType,
improveRTTIType,
Term(..),
isTerm, isSuspension, isPrim, isFun, isFunLike, isNewtypeWrap,
isFullyEvaluated, isFullyEvaluatedTerm,
termType, mapTermType, termTyVars,
foldTerm, TermFold(..), foldTermM, TermFoldM(..), idTermFold,
pprTerm, cPprTerm, cPprTermBase, CustomTermPrinter,
-- unsafeDeepSeq,
Closure(..), getClosureData, ClosureType(..), isConstr, isIndirection
) where
#include "HsVersions.h"
import DebuggerUtils
import ByteCodeItbls ( StgInfoTable )
import qualified ByteCodeItbls as BCI( StgInfoTable(..) )
import HscTypes
import Linker
import DataCon
import Type
import qualified Unify as U
import Var
import TcRnMonad
import TcType
import TcMType
import TcHsSyn ( mkZonkTcTyVar )
import TcUnify
import TcEnv
import TyCon
import Name
import VarEnv
import Util
import VarSet
import TysPrim
import PrelNames
import TysWiredIn
import DynFlags
import Outputable as Ppr
import FastString
import Constants ( wORD_SIZE )
import GHC.Arr ( Array(..) )
import GHC.Exts
import GHC.IO ( IO(..) )
import StaticFlags( opt_PprStyle_Debug )
import Control.Monad
import Data.Maybe
import Data.Array.Base
import Data.Ix
import Data.List
import qualified Data.Sequence as Seq
import Data.Monoid (mappend)
import Data.Sequence (viewl, ViewL(..))
import Foreign.Safe
import System.IO.Unsafe
---------------------------------------------
-- * A representation of semi evaluated Terms
---------------------------------------------
data Term = Term { ty :: RttiType
, dc :: Either String DataCon
-- Carries a text representation if the datacon is
-- not exported by the .hi file, which is the case
-- for private constructors in -O0 compiled libraries
, val :: HValue
, subTerms :: [Term] }
| Prim { ty :: RttiType
, value :: [Word] }
| Suspension { ctype :: ClosureType
, ty :: RttiType
, val :: HValue
, bound_to :: Maybe Name -- Useful for printing
}
| NewtypeWrap{ -- At runtime there are no newtypes, and hence no
-- newtype constructors. A NewtypeWrap is just a
-- made-up tag saying "heads up, there used to be
-- a newtype constructor here".
ty :: RttiType
, dc :: Either String DataCon
, wrapped_term :: Term }
| RefWrap { -- The contents of a reference
ty :: RttiType
, wrapped_term :: Term }
isTerm, isSuspension, isPrim, isFun, isFunLike, isNewtypeWrap :: Term -> Bool
isTerm Term{} = True
isTerm _ = False
isSuspension Suspension{} = True
isSuspension _ = False
isPrim Prim{} = True
isPrim _ = False
isNewtypeWrap NewtypeWrap{} = True
isNewtypeWrap _ = False
isFun Suspension{ctype=Fun} = True
isFun _ = False
isFunLike s@Suspension{ty=ty} = isFun s || isFunTy ty
isFunLike _ = False
termType :: Term -> RttiType
termType t = ty t
isFullyEvaluatedTerm :: Term -> Bool
isFullyEvaluatedTerm Term {subTerms=tt} = all isFullyEvaluatedTerm tt
isFullyEvaluatedTerm Prim {} = True
isFullyEvaluatedTerm NewtypeWrap{wrapped_term=t} = isFullyEvaluatedTerm t
isFullyEvaluatedTerm RefWrap{wrapped_term=t} = isFullyEvaluatedTerm t
isFullyEvaluatedTerm _ = False
instance Outputable (Term) where
ppr t | Just doc <- cPprTerm cPprTermBase t = doc
| otherwise = panic "Outputable Term instance"
-------------------------------------------------------------------------
-- Runtime Closure Datatype and functions for retrieving closure related stuff
-------------------------------------------------------------------------
data ClosureType = Constr
| Fun
| Thunk Int
| ThunkSelector
| Blackhole
| AP
| PAP
| Indirection Int
| MutVar Int
| MVar Int
| Other Int
deriving (Show, Eq)
data Closure = Closure { tipe :: ClosureType
, infoPtr :: Ptr ()
, infoTable :: StgInfoTable
, ptrs :: Array Int HValue
, nonPtrs :: [Word]
}
instance Outputable ClosureType where
ppr = text . show
#include "../includes/rts/storage/ClosureTypes.h"
aP_CODE, pAP_CODE :: Int
aP_CODE = AP
pAP_CODE = PAP
#undef AP
#undef PAP
getClosureData :: a -> IO Closure
getClosureData a =
case unpackClosure# a of
(# iptr, ptrs, nptrs #) -> do
let iptr'
| ghciTablesNextToCode =
Ptr iptr
| otherwise =
-- the info pointer we get back from unpackClosure#
-- is to the beginning of the standard info table,
-- but the Storable instance for info tables takes
-- into account the extra entry pointer when
-- !ghciTablesNextToCode, so we must adjust here:
Ptr iptr `plusPtr` negate wORD_SIZE
itbl <- peek iptr'
let tipe = readCType (BCI.tipe itbl)
elems = fromIntegral (BCI.ptrs itbl)
ptrsList = Array 0 (elems - 1) elems ptrs
nptrs_data = [W# (indexWordArray# nptrs i)
| I# i <- [0.. fromIntegral (BCI.nptrs itbl)-1] ]
ASSERT(elems >= 0) return ()
ptrsList `seq`
return (Closure tipe (Ptr iptr) itbl ptrsList nptrs_data)
readCType :: Integral a => a -> ClosureType
readCType i
| i >= CONSTR && i <= CONSTR_NOCAF_STATIC = Constr
| i >= FUN && i <= FUN_STATIC = Fun
| i >= THUNK && i < THUNK_SELECTOR = Thunk i'
| i == THUNK_SELECTOR = ThunkSelector
| i == BLACKHOLE = Blackhole
| i >= IND && i <= IND_STATIC = Indirection i'
| i' == aP_CODE = AP
| i == AP_STACK = AP
| i' == pAP_CODE = PAP
| i == MUT_VAR_CLEAN || i == MUT_VAR_DIRTY= MutVar i'
| i == MVAR_CLEAN || i == MVAR_DIRTY = MVar i'
| otherwise = Other i'
where i' = fromIntegral i
isConstr, isIndirection, isThunk :: ClosureType -> Bool
isConstr Constr = True
isConstr _ = False
isIndirection (Indirection _) = True
isIndirection _ = False
isThunk (Thunk _) = True
isThunk ThunkSelector = True
isThunk AP = True
isThunk _ = False
isFullyEvaluated :: a -> IO Bool
isFullyEvaluated a = do
closure <- getClosureData a
case tipe closure of
Constr -> do are_subs_evaluated <- amapM isFullyEvaluated (ptrs closure)
return$ and are_subs_evaluated
_ -> return False
where amapM f = sequence . amap' f
-- TODO: Fix it. Probably the otherwise case is failing, trace/debug it
{-
unsafeDeepSeq :: a -> b -> b
unsafeDeepSeq = unsafeDeepSeq1 2
where unsafeDeepSeq1 0 a b = seq a $! b
unsafeDeepSeq1 i a b -- 1st case avoids infinite loops for non reducible thunks
| not (isConstr tipe) = seq a $! unsafeDeepSeq1 (i-1) a b
-- | unsafePerformIO (isFullyEvaluated a) = b
| otherwise = case unsafePerformIO (getClosureData a) of
closure -> foldl' (flip unsafeDeepSeq) b (ptrs closure)
where tipe = unsafePerformIO (getClosureType a)
-}
-----------------------------------
-- * Traversals for Terms
-----------------------------------
type TermProcessor a b = RttiType -> Either String DataCon -> HValue -> [a] -> b
data TermFold a = TermFold { fTerm :: TermProcessor a a
, fPrim :: RttiType -> [Word] -> a
, fSuspension :: ClosureType -> RttiType -> HValue
-> Maybe Name -> a
, fNewtypeWrap :: RttiType -> Either String DataCon
-> a -> a
, fRefWrap :: RttiType -> a -> a
}
data TermFoldM m a =
TermFoldM {fTermM :: TermProcessor a (m a)
, fPrimM :: RttiType -> [Word] -> m a
, fSuspensionM :: ClosureType -> RttiType -> HValue
-> Maybe Name -> m a
, fNewtypeWrapM :: RttiType -> Either String DataCon
-> a -> m a
, fRefWrapM :: RttiType -> a -> m a
}
foldTerm :: TermFold a -> Term -> a
foldTerm tf (Term ty dc v tt) = fTerm tf ty dc v (map (foldTerm tf) tt)
foldTerm tf (Prim ty v ) = fPrim tf ty v
foldTerm tf (Suspension ct ty v b) = fSuspension tf ct ty v b
foldTerm tf (NewtypeWrap ty dc t) = fNewtypeWrap tf ty dc (foldTerm tf t)
foldTerm tf (RefWrap ty t) = fRefWrap tf ty (foldTerm tf t)
foldTermM :: Monad m => TermFoldM m a -> Term -> m a
foldTermM tf (Term ty dc v tt) = mapM (foldTermM tf) tt >>= fTermM tf ty dc v
foldTermM tf (Prim ty v ) = fPrimM tf ty v
foldTermM tf (Suspension ct ty v b) = fSuspensionM tf ct ty v b
foldTermM tf (NewtypeWrap ty dc t) = foldTermM tf t >>= fNewtypeWrapM tf ty dc
foldTermM tf (RefWrap ty t) = foldTermM tf t >>= fRefWrapM tf ty
idTermFold :: TermFold Term
idTermFold = TermFold {
fTerm = Term,
fPrim = Prim,
fSuspension = Suspension,
fNewtypeWrap = NewtypeWrap,
fRefWrap = RefWrap
}
mapTermType :: (RttiType -> Type) -> Term -> Term
mapTermType f = foldTerm idTermFold {
fTerm = \ty dc hval tt -> Term (f ty) dc hval tt,
fSuspension = \ct ty hval n ->
Suspension ct (f ty) hval n,
fNewtypeWrap= \ty dc t -> NewtypeWrap (f ty) dc t,
fRefWrap = \ty t -> RefWrap (f ty) t}
mapTermTypeM :: Monad m => (RttiType -> m Type) -> Term -> m Term
mapTermTypeM f = foldTermM TermFoldM {
fTermM = \ty dc hval tt -> f ty >>= \ty' -> return $ Term ty' dc hval tt,
fPrimM = (return.) . Prim,
fSuspensionM = \ct ty hval n ->
f ty >>= \ty' -> return $ Suspension ct ty' hval n,
fNewtypeWrapM= \ty dc t -> f ty >>= \ty' -> return $ NewtypeWrap ty' dc t,
fRefWrapM = \ty t -> f ty >>= \ty' -> return $ RefWrap ty' t}
termTyVars :: Term -> TyVarSet
termTyVars = foldTerm TermFold {
fTerm = \ty _ _ tt ->
tyVarsOfType ty `plusVarEnv` concatVarEnv tt,
fSuspension = \_ ty _ _ -> tyVarsOfType ty,
fPrim = \ _ _ -> emptyVarEnv,
fNewtypeWrap= \ty _ t -> tyVarsOfType ty `plusVarEnv` t,
fRefWrap = \ty t -> tyVarsOfType ty `plusVarEnv` t}
where concatVarEnv = foldr plusVarEnv emptyVarEnv
----------------------------------
-- Pretty printing of terms
----------------------------------
type Precedence = Int
type TermPrinter = Precedence -> Term -> SDoc
type TermPrinterM m = Precedence -> Term -> m SDoc
app_prec,cons_prec, max_prec ::Int
max_prec = 10
app_prec = max_prec
cons_prec = 5 -- TODO Extract this info from GHC itself
pprTerm :: TermPrinter -> TermPrinter
pprTerm y p t | Just doc <- pprTermM (\p -> Just . y p) p t = doc
pprTerm _ _ _ = panic "pprTerm"
pprTermM, ppr_termM, pprNewtypeWrap :: Monad m => TermPrinterM m -> TermPrinterM m
pprTermM y p t = pprDeeper `liftM` ppr_termM y p t
ppr_termM y p Term{dc=Left dc_tag, subTerms=tt} = do
tt_docs <- mapM (y app_prec) tt
return $ cparen (not (null tt) && p >= app_prec)
(text dc_tag <+> pprDeeperList fsep tt_docs)
ppr_termM y p Term{dc=Right dc, subTerms=tt}
{- | dataConIsInfix dc, (t1:t2:tt') <- tt --TODO fixity
= parens (ppr_term1 True t1 <+> ppr dc <+> ppr_term1 True ppr t2)
<+> hsep (map (ppr_term1 True) tt)
-} -- TODO Printing infix constructors properly
| null sub_terms_to_show
= return (ppr dc)
| otherwise
= do { tt_docs <- mapM (y app_prec) sub_terms_to_show
; return $ cparen (p >= app_prec) $
sep [ppr dc, nest 2 (pprDeeperList fsep tt_docs)] }
where
sub_terms_to_show -- Don't show the dictionary arguments to
-- constructors unless -dppr-debug is on
| opt_PprStyle_Debug = tt
| otherwise = dropList (dataConTheta dc) tt
ppr_termM y p t@NewtypeWrap{} = pprNewtypeWrap y p t
ppr_termM y p RefWrap{wrapped_term=t} = do
contents <- y app_prec t
return$ cparen (p >= app_prec) (text "GHC.Prim.MutVar#" <+> contents)
-- The constructor name is wired in here ^^^ for the sake of simplicity.
-- I don't think mutvars are going to change in a near future.
-- In any case this is solely a presentation matter: MutVar# is
-- a datatype with no constructors, implemented by the RTS
-- (hence there is no way to obtain a datacon and print it).
ppr_termM _ _ t = ppr_termM1 t
ppr_termM1 :: Monad m => Term -> m SDoc
ppr_termM1 Prim{value=words, ty=ty} =
return$ text$ repPrim (tyConAppTyCon ty) words
ppr_termM1 Suspension{ty=ty, bound_to=Nothing} =
return (char '_' <+> ifPprDebug (text "::" <> ppr ty))
ppr_termM1 Suspension{ty=ty, bound_to=Just n}
-- | Just _ <- splitFunTy_maybe ty = return$ ptext (sLit("<function>")
| otherwise = return$ parens$ ppr n <> text "::" <> ppr ty
ppr_termM1 Term{} = panic "ppr_termM1 - Term"
ppr_termM1 RefWrap{} = panic "ppr_termM1 - RefWrap"
ppr_termM1 NewtypeWrap{} = panic "ppr_termM1 - NewtypeWrap"
pprNewtypeWrap y p NewtypeWrap{ty=ty, wrapped_term=t}
| Just (tc,_) <- tcSplitTyConApp_maybe ty
, ASSERT(isNewTyCon tc) True
, Just new_dc <- tyConSingleDataCon_maybe tc = do
real_term <- y max_prec t
return $ cparen (p >= app_prec) (ppr new_dc <+> real_term)
pprNewtypeWrap _ _ _ = panic "pprNewtypeWrap"
-------------------------------------------------------
-- Custom Term Pretty Printers
-------------------------------------------------------
-- We can want to customize the representation of a
-- term depending on its type.
-- However, note that custom printers have to work with
-- type representations, instead of directly with types.
-- We cannot use type classes here, unless we employ some
-- typerep trickery (e.g. Weirich's RepLib tricks),
-- which I didn't. Therefore, this code replicates a lot
-- of what type classes provide for free.
type CustomTermPrinter m = TermPrinterM m
-> [Precedence -> Term -> (m (Maybe SDoc))]
-- | Takes a list of custom printers with a explicit recursion knot and a term,
-- and returns the output of the first succesful printer, or the default printer
cPprTerm :: Monad m => CustomTermPrinter m -> Term -> m SDoc
cPprTerm printers_ = go 0 where
printers = printers_ go
go prec t = do
let default_ = Just `liftM` pprTermM go prec t
mb_customDocs = [pp prec t | pp <- printers] ++ [default_]
Just doc <- firstJustM mb_customDocs
return$ cparen (prec>app_prec+1) doc
firstJustM (mb:mbs) = mb >>= maybe (firstJustM mbs) (return . Just)
firstJustM [] = return Nothing
-- Default set of custom printers. Note that the recursion knot is explicit
cPprTermBase :: forall m. Monad m => CustomTermPrinter m
cPprTermBase y =
[ ifTerm (isTupleTy.ty) (\_p -> liftM (parens . hcat . punctuate comma)
. mapM (y (-1))
. subTerms)
, ifTerm (\t -> isTyCon listTyCon (ty t) && subTerms t `lengthIs` 2)
ppr_list
, ifTerm (isTyCon intTyCon . ty) ppr_int
, ifTerm (isTyCon charTyCon . ty) ppr_char
, ifTerm (isTyCon floatTyCon . ty) ppr_float
, ifTerm (isTyCon doubleTyCon . ty) ppr_double
, ifTerm (isIntegerTy . ty) ppr_integer
]
where
ifTerm :: (Term -> Bool)
-> (Precedence -> Term -> m SDoc)
-> Precedence -> Term -> m (Maybe SDoc)
ifTerm pred f prec t@Term{}
| pred t = Just `liftM` f prec t
ifTerm _ _ _ _ = return Nothing
isTupleTy ty = fromMaybe False $ do
(tc,_) <- tcSplitTyConApp_maybe ty
return (isBoxedTupleTyCon tc)
isTyCon a_tc ty = fromMaybe False $ do
(tc,_) <- tcSplitTyConApp_maybe ty
return (a_tc == tc)
isIntegerTy ty = fromMaybe False $ do
(tc,_) <- tcSplitTyConApp_maybe ty
return (tyConName tc == integerTyConName)
ppr_int, ppr_char, ppr_float, ppr_double, ppr_integer
:: Precedence -> Term -> m SDoc
ppr_int _ v = return (Ppr.int (unsafeCoerce# (val v)))
ppr_char _ v = return (Ppr.char '\'' <> Ppr.char (unsafeCoerce# (val v)) <> Ppr.char '\'')
ppr_float _ v = return (Ppr.float (unsafeCoerce# (val v)))
ppr_double _ v = return (Ppr.double (unsafeCoerce# (val v)))
ppr_integer _ v = return (Ppr.integer (unsafeCoerce# (val v)))
--Note pprinting of list terms is not lazy
ppr_list :: Precedence -> Term -> m SDoc
ppr_list p (Term{subTerms=[h,t]}) = do
let elems = h : getListTerms t
isConsLast = not(termType(last elems) `eqType` termType h)
is_string = all (isCharTy . ty) elems
print_elems <- mapM (y cons_prec) elems
if is_string
then return (Ppr.doubleQuotes (Ppr.text (unsafeCoerce# (map val elems))))
else if isConsLast
then return $ cparen (p >= cons_prec)
$ pprDeeperList fsep
$ punctuate (space<>colon) print_elems
else return $ brackets
$ pprDeeperList fcat
$ punctuate comma print_elems
where getListTerms Term{subTerms=[h,t]} = h : getListTerms t
getListTerms Term{subTerms=[]} = []
getListTerms t@Suspension{} = [t]
getListTerms t = pprPanic "getListTerms" (ppr t)
ppr_list _ _ = panic "doList"
repPrim :: TyCon -> [Word] -> String
repPrim t = rep where
rep x
| t == charPrimTyCon = show (build x :: Char)
| t == intPrimTyCon = show (build x :: Int)
| t == wordPrimTyCon = show (build x :: Word)
| t == floatPrimTyCon = show (build x :: Float)
| t == doublePrimTyCon = show (build x :: Double)
| t == int32PrimTyCon = show (build x :: Int32)
| t == word32PrimTyCon = show (build x :: Word32)
| t == int64PrimTyCon = show (build x :: Int64)
| t == word64PrimTyCon = show (build x :: Word64)
| t == addrPrimTyCon = show (nullPtr `plusPtr` build x)
| t == stablePtrPrimTyCon = "<stablePtr>"
| t == stableNamePrimTyCon = "<stableName>"
| t == statePrimTyCon = "<statethread>"
| t == realWorldTyCon = "<realworld>"
| t == threadIdPrimTyCon = "<ThreadId>"
| t == weakPrimTyCon = "<Weak>"
| t == arrayPrimTyCon = "<array>"
| t == byteArrayPrimTyCon = "<bytearray>"
| t == mutableArrayPrimTyCon = "<mutableArray>"
| t == mutableByteArrayPrimTyCon = "<mutableByteArray>"
| t == mutVarPrimTyCon= "<mutVar>"
| t == mVarPrimTyCon = "<mVar>"
| t == tVarPrimTyCon = "<tVar>"
| otherwise = showSDoc (char '<' <> ppr t <> char '>')
where build ww = unsafePerformIO $ withArray ww (peek . castPtr)
-- This ^^^ relies on the representation of Haskell heap values being
-- the same as in a C array.
-----------------------------------
-- Type Reconstruction
-----------------------------------
{-
Type Reconstruction is type inference done on heap closures.
The algorithm walks the heap generating a set of equations, which
are solved with syntactic unification.
A type reconstruction equation looks like:
<datacon reptype> = <actual heap contents>
The full equation set is generated by traversing all the subterms, starting
from a given term.
The only difficult part is that newtypes are only found in the lhs of equations.
Right hand sides are missing them. We can either (a) drop them from the lhs, or
(b) reconstruct them in the rhs when possible.
The function congruenceNewtypes takes a shot at (b)
-}
-- A (non-mutable) tau type containing
-- existentially quantified tyvars.
-- (since GHC type language currently does not support
-- existentials, we leave these variables unquantified)
type RttiType = Type
-- An incomplete type as stored in GHCi:
-- no polymorphism: no quantifiers & all tyvars are skolem.
type GhciType = Type
-- The Type Reconstruction monad
--------------------------------
type TR a = TcM a
runTR :: HscEnv -> TR a -> IO a
runTR hsc_env thing = do
mb_val <- runTR_maybe hsc_env thing
case mb_val of
Nothing -> error "unable to :print the term"
Just x -> return x
runTR_maybe :: HscEnv -> TR a -> IO (Maybe a)
runTR_maybe hsc_env = fmap snd . initTc hsc_env HsSrcFile False iNTERACTIVE
traceTR :: SDoc -> TR ()
traceTR = liftTcM . traceOptTcRn Opt_D_dump_rtti
-- Semantically different to recoverM in TcRnMonad
-- recoverM retains the errors in the first action,
-- whereas recoverTc here does not
recoverTR :: TR a -> TR a -> TR a
recoverTR recover thing = do
(_,mb_res) <- tryTcErrs thing
case mb_res of
Nothing -> recover
Just res -> return res
trIO :: IO a -> TR a
trIO = liftTcM . liftIO
liftTcM :: TcM a -> TR a
liftTcM = id
newVar :: Kind -> TR TcType
newVar = liftTcM . newFlexiTyVarTy
instTyVars :: [TyVar] -> TR ([TcTyVar], [TcType], TvSubst)
-- Instantiate fresh mutable type variables from some TyVars
-- This function preserves the print-name, which helps error messages
instTyVars = liftTcM . tcInstTyVars
type RttiInstantiation = [(TcTyVar, TyVar)]
-- Associates the typechecker-world meta type variables
-- (which are mutable and may be refined), to their
-- debugger-world RuntimeUnk counterparts.
-- If the TcTyVar has not been refined by the runtime type
-- elaboration, then we want to turn it back into the
-- original RuntimeUnk
-- | Returns the instantiated type scheme ty', and the
-- mapping from new (instantiated) -to- old (skolem) type variables
instScheme :: QuantifiedType -> TR (TcType, RttiInstantiation)
instScheme (tvs, ty)
= liftTcM $ do { (tvs', _, subst) <- tcInstTyVars tvs
; let rtti_inst = [(tv',tv) | (tv',tv) <- tvs' `zip` tvs]
; return (substTy subst ty, rtti_inst) }
applyRevSubst :: RttiInstantiation -> TR ()
-- Apply the *reverse* substitution in-place to any un-filled-in
-- meta tyvars. This recovers the original debugger-world variable
-- unless it has been refined by new information from the heap
applyRevSubst pairs = liftTcM (mapM_ do_pair pairs)
where
do_pair (tc_tv, rtti_tv)
= do { tc_ty <- zonkTcTyVar tc_tv
; case tcGetTyVar_maybe tc_ty of
Just tv | isMetaTyVar tv -> writeMetaTyVar tv (mkTyVarTy rtti_tv)
_ -> return () }
-- Adds a constraint of the form t1 == t2
-- t1 is expected to come from walking the heap
-- t2 is expected to come from a datacon signature
-- Before unification, congruenceNewtypes needs to
-- do its magic.
addConstraint :: TcType -> TcType -> TR ()
addConstraint actual expected = do
traceTR (text "add constraint:" <+> fsep [ppr actual, equals, ppr expected])
recoverTR (traceTR $ fsep [text "Failed to unify", ppr actual,
text "with", ppr expected]) $
do { (ty1, ty2) <- congruenceNewtypes actual expected
; _ <- captureConstraints $ unifyType ty1 ty2
; return () }
-- TOMDO: what about the coercion?
-- we should consider family instances
-- Type & Term reconstruction
------------------------------
cvObtainTerm :: HscEnv -> Int -> Bool -> RttiType -> HValue -> IO Term
cvObtainTerm hsc_env max_depth force old_ty hval = runTR hsc_env $ do
-- we quantify existential tyvars as universal,
-- as this is needed to be able to manipulate
-- them properly
let quant_old_ty@(old_tvs, old_tau) = quantifyType old_ty
sigma_old_ty = mkForAllTys old_tvs old_tau
traceTR (text "Term reconstruction started with initial type " <> ppr old_ty)
term <-
if null old_tvs
then do
term <- go max_depth sigma_old_ty sigma_old_ty hval
term' <- zonkTerm term
return $ fixFunDictionaries $ expandNewtypes term'
else do
(old_ty', rev_subst) <- instScheme quant_old_ty
my_ty <- newVar argTypeKind
when (check1 quant_old_ty) (traceTR (text "check1 passed") >>
addConstraint my_ty old_ty')
term <- go max_depth my_ty sigma_old_ty hval
new_ty <- zonkTcType (termType term)
if isMonomorphic new_ty || check2 (quantifyType new_ty) quant_old_ty
then do
traceTR (text "check2 passed")
addConstraint new_ty old_ty'
applyRevSubst rev_subst
zterm' <- zonkTerm term
return ((fixFunDictionaries . expandNewtypes) zterm')
else do
traceTR (text "check2 failed" <+> parens
(ppr term <+> text "::" <+> ppr new_ty))
-- we have unsound types. Replace constructor types in
-- subterms with tyvars
zterm' <- mapTermTypeM
(\ty -> case tcSplitTyConApp_maybe ty of
Just (tc, _:_) | tc /= funTyCon
-> newVar argTypeKind
_ -> return ty)
term
zonkTerm zterm'
traceTR (text "Term reconstruction completed." $$
text "Term obtained: " <> ppr term $$
text "Type obtained: " <> ppr (termType term))
return term
where
go :: Int -> Type -> Type -> HValue -> TcM Term
-- [SPJ May 11] I don't understand the difference between my_ty and old_ty
go max_depth _ _ _ | seq max_depth False = undefined
go 0 my_ty _old_ty a = do
traceTR (text "Gave up reconstructing a term after" <>
int max_depth <> text " steps")
clos <- trIO $ getClosureData a
return (Suspension (tipe clos) my_ty a Nothing)
go max_depth my_ty old_ty a = do
let monomorphic = not(isTyVarTy my_ty)
-- This ^^^ is a convention. The ancestor tests for
-- monomorphism and passes a type instead of a tv
clos <- trIO $ getClosureData a
case tipe clos of
-- Thunks we may want to force
t | isThunk t && force -> traceTR (text "Forcing a " <> text (show t)) >>
seq a (go (pred max_depth) my_ty old_ty a)
-- Blackholes are indirections iff the payload is not TSO or BLOCKING_QUEUE. So we
-- treat them like indirections; if the payload is TSO or BLOCKING_QUEUE, we'll end up
-- showing '_' which is what we want.
Blackhole -> do traceTR (text "Following a BLACKHOLE")
appArr (go max_depth my_ty old_ty) (ptrs clos) 0
-- We always follow indirections
Indirection i -> do traceTR (text "Following an indirection" <> parens (int i) )
go max_depth my_ty old_ty $! (ptrs clos ! 0)
-- We also follow references
MutVar _ | Just (tycon,[world,contents_ty]) <- tcSplitTyConApp_maybe old_ty
-> do
-- Deal with the MutVar# primitive
-- It does not have a constructor at all,
-- so we simulate the following one
-- MutVar# :: contents_ty -> MutVar# s contents_ty
traceTR (text "Following a MutVar")
contents_tv <- newVar liftedTypeKind
contents <- trIO$ IO$ \w -> readMutVar# (unsafeCoerce# a) w
ASSERT(isUnliftedTypeKind $ typeKind my_ty) return ()
(mutvar_ty,_) <- instScheme $ quantifyType $ mkFunTy
contents_ty (mkTyConApp tycon [world,contents_ty])
addConstraint (mkFunTy contents_tv my_ty) mutvar_ty
x <- go (pred max_depth) contents_tv contents_ty contents
return (RefWrap my_ty x)
-- The interesting case
Constr -> do
traceTR (text "entering a constructor " <>
if monomorphic
then parens (text "already monomorphic: " <> ppr my_ty)
else Ppr.empty)
Right dcname <- dataConInfoPtrToName (infoPtr clos)
(_,mb_dc) <- tryTcErrs (tcLookupDataCon dcname)
case mb_dc of
Nothing -> do -- This can happen for private constructors compiled -O0
-- where the .hi descriptor does not export them
-- In such case, we return a best approximation:
-- ignore the unpointed args, and recover the pointeds
-- This preserves laziness, and should be safe.
traceTR (text "Nothing" <+> ppr dcname)
let tag = showSDoc (ppr dcname)
vars <- replicateM (length$ elems$ ptrs clos)
(newVar liftedTypeKind)
subTerms <- sequence [appArr (go (pred max_depth) tv tv) (ptrs clos) i
| (i, tv) <- zip [0..] vars]
return (Term my_ty (Left ('<' : tag ++ ">")) a subTerms)
Just dc -> do
traceTR (text "Just" <+> ppr dc)
subTtypes <- getDataConArgTys dc my_ty
let (subTtypesP, subTtypesNP) = partition isPtrType subTtypes
subTermsP <- sequence
[ appArr (go (pred max_depth) ty ty) (ptrs clos) i
| (i,ty) <- zip [0..] subTtypesP]
let unboxeds = extractUnboxed subTtypesNP clos
subTermsNP = zipWith Prim subTtypesNP unboxeds
subTerms = reOrderTerms subTermsP subTermsNP subTtypes
return (Term my_ty (Right dc) a subTerms)
-- The otherwise case: can be a Thunk,AP,PAP,etc.
tipe_clos ->
return (Suspension tipe_clos my_ty a Nothing)
-- put together pointed and nonpointed subterms in the
-- correct order.
reOrderTerms _ _ [] = []
reOrderTerms pointed unpointed (ty:tys)
| isPtrType ty = ASSERT2(not(null pointed)
, ptext (sLit "reOrderTerms") $$
(ppr pointed $$ ppr unpointed))
let (t:tt) = pointed in t : reOrderTerms tt unpointed tys
| otherwise = ASSERT2(not(null unpointed)
, ptext (sLit "reOrderTerms") $$
(ppr pointed $$ ppr unpointed))
let (t:tt) = unpointed in t : reOrderTerms pointed tt tys
-- insert NewtypeWraps around newtypes
expandNewtypes = foldTerm idTermFold { fTerm = worker } where
worker ty dc hval tt
| Just (tc, args) <- tcSplitTyConApp_maybe ty
, isNewTyCon tc
, wrapped_type <- newTyConInstRhs tc args
, Just dc' <- tyConSingleDataCon_maybe tc
, t' <- worker wrapped_type dc hval tt
= NewtypeWrap ty (Right dc') t'
| otherwise = Term ty dc hval tt
-- Avoid returning types where predicates have been expanded to dictionaries.
fixFunDictionaries = foldTerm idTermFold {fSuspension = worker} where
worker ct ty hval n | isFunTy ty = Suspension ct (dictsView ty) hval n
| otherwise = Suspension ct ty hval n
-- Fast, breadth-first Type reconstruction
------------------------------------------
cvReconstructType :: HscEnv -> Int -> GhciType -> HValue -> IO (Maybe Type)
cvReconstructType hsc_env max_depth old_ty hval = runTR_maybe hsc_env $ do
traceTR (text "RTTI started with initial type " <> ppr old_ty)
let sigma_old_ty@(old_tvs, _) = quantifyType old_ty
new_ty <-
if null old_tvs
then return old_ty
else do
(old_ty', rev_subst) <- instScheme sigma_old_ty
my_ty <- newVar argTypeKind
when (check1 sigma_old_ty) (traceTR (text "check1 passed") >>
addConstraint my_ty old_ty')
search (isMonomorphic `fmap` zonkTcType my_ty)
(\(ty,a) -> go ty a)
(Seq.singleton (my_ty, hval))
max_depth
new_ty <- zonkTcType my_ty
if isMonomorphic new_ty || check2 (quantifyType new_ty) sigma_old_ty
then do
traceTR (text "check2 passed" <+> ppr old_ty $$ ppr new_ty)
addConstraint my_ty old_ty'
applyRevSubst rev_subst
zonkRttiType new_ty
else traceTR (text "check2 failed" <+> parens (ppr new_ty)) >>
return old_ty
traceTR (text "RTTI completed. Type obtained:" <+> ppr new_ty)
return new_ty
where
-- search :: m Bool -> ([a] -> [a] -> [a]) -> [a] -> m ()
search _ _ _ 0 = traceTR (text "Failed to reconstruct a type after " <>
int max_depth <> text " steps")
search stop expand l d =
case viewl l of
EmptyL -> return ()
x :< xx -> unlessM stop $ do
new <- expand x
search stop expand (xx `mappend` Seq.fromList new) $! (pred d)
-- returns unification tasks,since we are going to want a breadth-first search
go :: Type -> HValue -> TR [(Type, HValue)]
go my_ty a = do
traceTR (text "go" <+> ppr my_ty)
clos <- trIO $ getClosureData a
case tipe clos of
Blackhole -> appArr (go my_ty) (ptrs clos) 0 -- carefully, don't eval the TSO
Indirection _ -> go my_ty $! (ptrs clos ! 0)
MutVar _ -> do
contents <- trIO$ IO$ \w -> readMutVar# (unsafeCoerce# a) w
tv' <- newVar liftedTypeKind
world <- newVar liftedTypeKind
addConstraint my_ty (mkTyConApp mutVarPrimTyCon [world,tv'])
return [(tv', contents)]
Constr -> do
Right dcname <- dataConInfoPtrToName (infoPtr clos)
traceTR (text "Constr1" <+> ppr dcname)
(_,mb_dc) <- tryTcErrs (tcLookupDataCon dcname)
case mb_dc of
Nothing-> do
-- TODO: Check this case
forM [0..length (elems $ ptrs clos)] $ \i -> do
tv <- newVar liftedTypeKind
return$ appArr (\e->(tv,e)) (ptrs clos) i
Just dc -> do
arg_tys <- getDataConArgTys dc my_ty
traceTR (text "Constr2" <+> ppr dcname <+> ppr arg_tys)
return $ [ appArr (\e-> (ty,e)) (ptrs clos) i
| (i,ty) <- zip [0..] (filter isPtrType arg_tys)]
_ -> return []
-- Compute the difference between a base type and the type found by RTTI
-- improveType <base_type> <rtti_type>
-- The types can contain skolem type variables, which need to be treated as normal vars.
-- In particular, we want them to unify with things.
improveRTTIType :: HscEnv -> RttiType -> RttiType -> Maybe TvSubst
improveRTTIType _ base_ty new_ty
= U.tcUnifyTys (const U.BindMe) [base_ty] [new_ty]
getDataConArgTys :: DataCon -> Type -> TR [Type]
-- Given the result type ty of a constructor application (D a b c :: ty)
-- return the types of the arguments. This is RTTI-land, so 'ty' might
-- not be fully known. Moreover, the arg types might involve existentials;
-- if so, make up fresh RTTI type variables for them
getDataConArgTys dc con_app_ty
= do { (_, ex_tys, _) <- instTyVars ex_tvs
; let rep_con_app_ty = repType con_app_ty
; ty_args <- case tcSplitTyConApp_maybe rep_con_app_ty of
Just (tc, ty_args) | dataConTyCon dc == tc
-> ASSERT( univ_tvs `equalLength` ty_args)
return ty_args
_ -> do { (_, ty_args, subst) <- instTyVars univ_tvs
; let res_ty = substTy subst (dataConOrigResTy dc)
; addConstraint rep_con_app_ty res_ty
; return ty_args }
-- It is necessary to check dataConTyCon dc == tc
-- because it may be the case that tc is a recursive
-- newtype and tcSplitTyConApp has not removed it. In
-- that case, we happily give up and don't match
; let subst = zipTopTvSubst (univ_tvs ++ ex_tvs) (ty_args ++ ex_tys)
; return (substTys subst (dataConRepArgTys dc)) }
where
univ_tvs = dataConUnivTyVars dc
ex_tvs = dataConExTyVars dc
isPtrType :: Type -> Bool
isPtrType ty = case typePrimRep ty of
PtrRep -> True
_ -> False
-- Soundness checks
--------------------
{-
This is not formalized anywhere, so hold to your seats!
RTTI in the presence of newtypes can be a tricky and unsound business.
Example:
~~~~~~~~~
Suppose we are doing RTTI for a partially evaluated
closure t, the real type of which is t :: MkT Int, for
newtype MkT a = MkT [Maybe a]
The table below shows the results of RTTI and the improvement
calculated for different combinations of evaluatedness and :type t.
Regard the two first columns as input and the next two as output.
# | t | :type t | rtti(t) | improv. | result
------------------------------------------------------------
1 | _ | t b | a | none | OK
2 | _ | MkT b | a | none | OK
3 | _ | t Int | a | none | OK
If t is not evaluated at *all*, we are safe.
4 | (_ : _) | t b | [a] | t = [] | UNSOUND
5 | (_ : _) | MkT b | MkT a | none | OK (compensating for the missing newtype)
6 | (_ : _) | t Int | [Int] | t = [] | UNSOUND
If a is a minimal whnf, we run into trouble. Note that
row 5 above does newtype enrichment on the ty_rtty parameter.
7 | (Just _:_)| t b |[Maybe a] | t = [], | UNSOUND
| | | b = Maybe a|
8 | (Just _:_)| MkT b | MkT a | none | OK
9 | (Just _:_)| t Int | FAIL | none | OK
And if t is any more evaluated than whnf, we are still in trouble.
Because constraints are solved in top-down order, when we reach the
Maybe subterm what we got is already unsound. This explains why the
row 9 fails to complete.
10 | (Just _:_)| t Int | [Maybe a] | FAIL | OK
11 | (Just 1:_)| t Int | [Maybe Int] | FAIL | OK
We can undo the failure in row 9 by leaving out the constraint
coming from the type signature of t (i.e., the 2nd column).
Note that this type information is still used
to calculate the improvement. But we fail
when trying to calculate the improvement, as there is no unifier for
t Int = [Maybe a] or t Int = [Maybe Int].
Another set of examples with t :: [MkT (Maybe Int)] \equiv [[Maybe (Maybe Int)]]
# | t | :type t | rtti(t) | improvement | result
---------------------------------------------------------------------
1 |(Just _:_) | [t (Maybe a)] | [[Maybe b]] | t = [] |
| | | | b = Maybe a |
The checks:
~~~~~~~~~~~
Consider a function obtainType that takes a value and a type and produces
the Term representation and a substitution (the improvement).
Assume an auxiliar rtti' function which does the actual job if recovering
the type, but which may produce a false type.
In pseudocode:
rtti' :: a -> IO Type -- Does not use the static type information
obtainType :: a -> Type -> IO (Maybe (Term, Improvement))
obtainType v old_ty = do
rtti_ty <- rtti' v
if monomorphic rtti_ty || (check rtti_ty old_ty)
then ...
else return Nothing
where check rtti_ty old_ty = check1 rtti_ty &&
check2 rtti_ty old_ty
check1 :: Type -> Bool
check2 :: Type -> Type -> Bool
Now, if rtti' returns a monomorphic type, we are safe.
If that is not the case, then we consider two conditions.
1. To prevent the class of unsoundness displayed by
rows 4 and 7 in the example: no higher kind tyvars
accepted.
check1 (t a) = NO
check1 (t Int) = NO
check1 ([] a) = YES
2. To prevent the class of unsoundness shown by row 6,
the rtti type should be structurally more
defined than the old type we are comparing it to.
check2 :: NewType -> OldType -> Bool
check2 a _ = True
check2 [a] a = True
check2 [a] (t Int) = False
check2 [a] (t a) = False -- By check1 we never reach this equation
check2 [Int] a = True
check2 [Int] (t Int) = True
check2 [Maybe a] (t Int) = False
check2 [Maybe Int] (t Int) = True
check2 (Maybe [a]) (m [Int]) = False
check2 (Maybe [Int]) (m [Int]) = True
-}
check1 :: QuantifiedType -> Bool
check1 (tvs, _) = not $ any isHigherKind (map tyVarKind tvs)
where
isHigherKind = not . null . fst . splitKindFunTys
check2 :: QuantifiedType -> QuantifiedType -> Bool
check2 (_, rtti_ty) (_, old_ty)
| Just (_, rttis) <- tcSplitTyConApp_maybe rtti_ty
= case () of
_ | Just (_,olds) <- tcSplitTyConApp_maybe old_ty
-> and$ zipWith check2 (map quantifyType rttis) (map quantifyType olds)
_ | Just _ <- splitAppTy_maybe old_ty
-> isMonomorphicOnNonPhantomArgs rtti_ty
_ -> True
| otherwise = True
-- Dealing with newtypes
--------------------------
{-
congruenceNewtypes does a parallel fold over two Type values,
compensating for missing newtypes on both sides.
This is necessary because newtypes are not present
in runtime, but sometimes there is evidence available.
Evidence can come from DataCon signatures or
from compile-time type inference.
What we are doing here is an approximation
of unification modulo a set of equations derived
from newtype definitions. These equations should be the
same as the equality coercions generated for newtypes
in System Fc. The idea is to perform a sort of rewriting,
taking those equations as rules, before launching unification.
The caller must ensure the following.
The 1st type (lhs) comes from the heap structure of ptrs,nptrs.
The 2nd type (rhs) comes from a DataCon type signature.
Rewriting (i.e. adding/removing a newtype wrapper) can happen
in both types, but in the rhs it is restricted to the result type.
Note that it is very tricky to make this 'rewriting'
work with the unification implemented by TcM, where
substitutions are operationally inlined. The order in which
constraints are unified is vital as we cannot modify
anything that has been touched by a previous unification step.
Therefore, congruenceNewtypes is sound only if the types
recovered by the RTTI mechanism are unified Top-Down.
-}
congruenceNewtypes :: TcType -> TcType -> TR (TcType,TcType)
congruenceNewtypes lhs rhs = go lhs rhs >>= \rhs' -> return (lhs,rhs')
where
go l r
-- TyVar lhs inductive case
| Just tv <- getTyVar_maybe l
, isTcTyVar tv
, isMetaTyVar tv
= recoverTR (return r) $ do
Indirect ty_v <- readMetaTyVar tv
traceTR $ fsep [text "(congruence) Following indirect tyvar:",
ppr tv, equals, ppr ty_v]
go ty_v r
-- FunTy inductive case
| Just (l1,l2) <- splitFunTy_maybe l
, Just (r1,r2) <- splitFunTy_maybe r
= do r2' <- go l2 r2
r1' <- go l1 r1
return (mkFunTy r1' r2')
-- TyconApp Inductive case; this is the interesting bit.
| Just (tycon_l, _) <- tcSplitTyConApp_maybe lhs
, Just (tycon_r, _) <- tcSplitTyConApp_maybe rhs
, tycon_l /= tycon_r
= upgrade tycon_l r
| otherwise = return r
where upgrade :: TyCon -> Type -> TR Type
upgrade new_tycon ty
| not (isNewTyCon new_tycon) = do
traceTR (text "(Upgrade) Not matching newtype evidence: " <>
ppr new_tycon <> text " for " <> ppr ty)
return ty
| otherwise = do
traceTR (text "(Upgrade) upgraded " <> ppr ty <>
text " in presence of newtype evidence " <> ppr new_tycon)
(_, vars, _) <- instTyVars (tyConTyVars new_tycon)
let ty' = mkTyConApp new_tycon vars
_ <- liftTcM (unifyType ty (repType ty'))
-- assumes that reptype doesn't ^^^^ touch tyconApp args
return ty'
zonkTerm :: Term -> TcM Term
zonkTerm = foldTermM (TermFoldM
{ fTermM = \ty dc v tt -> zonkRttiType ty >>= \ty' ->
return (Term ty' dc v tt)
, fSuspensionM = \ct ty v b -> zonkRttiType ty >>= \ty ->
return (Suspension ct ty v b)
, fNewtypeWrapM = \ty dc t -> zonkRttiType ty >>= \ty' ->
return$ NewtypeWrap ty' dc t
, fRefWrapM = \ty t -> return RefWrap `ap`
zonkRttiType ty `ap` return t
, fPrimM = (return.) . Prim })
zonkRttiType :: TcType -> TcM Type
-- Zonk the type, replacing any unbound Meta tyvars
-- by skolems, safely out of Meta-tyvar-land
zonkRttiType = zonkType (mkZonkTcTyVar zonk_unbound_meta mkTyVarTy)
where
zonk_unbound_meta tv
= ASSERT( isTcTyVar tv )
do { tv' <- skolemiseUnboundMetaTyVar tv RuntimeUnk
-- This is where RuntimeUnks are born:
-- otherwise-unconstrained unification variables are
-- turned into RuntimeUnks as they leave the
-- typechecker's monad
; return (mkTyVarTy tv') }
--------------------------------------------------------------------------------
-- Restore Class predicates out of a representation type
dictsView :: Type -> Type
dictsView ty = ty
-- Use only for RTTI types
isMonomorphic :: RttiType -> Bool
isMonomorphic ty = noExistentials && noUniversals
where (tvs, _, ty') = tcSplitSigmaTy ty
noExistentials = isEmptyVarSet (tyVarsOfType ty')
noUniversals = null tvs
-- Use only for RTTI types
isMonomorphicOnNonPhantomArgs :: RttiType -> Bool
isMonomorphicOnNonPhantomArgs ty
| Just (tc, all_args) <- tcSplitTyConApp_maybe (repType ty)
, phantom_vars <- tyConPhantomTyVars tc
, concrete_args <- [ arg | (tyv,arg) <- tyConTyVars tc `zip` all_args
, tyv `notElem` phantom_vars]
= all isMonomorphicOnNonPhantomArgs concrete_args
| Just (ty1, ty2) <- splitFunTy_maybe ty
= all isMonomorphicOnNonPhantomArgs [ty1,ty2]
| otherwise = isMonomorphic ty
tyConPhantomTyVars :: TyCon -> [TyVar]
tyConPhantomTyVars tc
| isAlgTyCon tc
, Just dcs <- tyConDataCons_maybe tc
, dc_vars <- concatMap dataConUnivTyVars dcs
= tyConTyVars tc \\ dc_vars
tyConPhantomTyVars _ = []
type QuantifiedType = ([TyVar], Type) -- Make the free type variables explicit
quantifyType :: Type -> QuantifiedType
-- Generalize the type: find all free tyvars and wrap in the appropiate ForAll.
quantifyType ty = (varSetElems (tyVarsOfType ty), ty)
unlessM :: Monad m => m Bool -> m () -> m ()
unlessM condM acc = condM >>= \c -> unless c acc
-- Strict application of f at index i
appArr :: Ix i => (e -> a) -> Array i e -> Int -> a
appArr f a@(Array _ _ _ ptrs#) i@(I# i#)
= ASSERT2 (i < length(elems a), ppr(length$ elems a, i))
case indexArray# ptrs# i# of
(# e #) -> f e
amap' :: (t -> b) -> Array Int t -> [b]
amap' f (Array i0 i _ arr#) = map g [0 .. i - i0]
where g (I# i#) = case indexArray# arr# i# of
(# e #) -> f e
extractUnboxed :: [Type] -> Closure -> [[Word]]
extractUnboxed tt clos = go tt (nonPtrs clos)
where sizeofType t = primRepSizeW (typePrimRep t)
go [] _ = []
go (t:tt) xx
| (x, rest) <- splitAt (sizeofType t) xx
= x : go tt rest
| ilyasergey/GHC-XAppFix | compiler/ghci/RtClosureInspect.hs | bsd-3-clause | 49,191 | 187 | 27 | 15,081 | 11,057 | 5,758 | 5,299 | -1 | -1 |
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.NV.AlphaToCoverageDitherControl
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.NV.AlphaToCoverageDitherControl (
-- * Extension Support
glGetNVAlphaToCoverageDitherControl,
gl_NV_alpha_to_coverage_dither_control,
-- * Enums
pattern GL_ALPHA_TO_COVERAGE_DITHER_DEFAULT_NV,
pattern GL_ALPHA_TO_COVERAGE_DITHER_DISABLE_NV,
pattern GL_ALPHA_TO_COVERAGE_DITHER_ENABLE_NV,
pattern GL_ALPHA_TO_COVERAGE_DITHER_MODE_NV,
-- * Functions
glAlphaToCoverageDitherControlNV
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
| haskell-opengl/OpenGLRaw | src/Graphics/GL/NV/AlphaToCoverageDitherControl.hs | bsd-3-clause | 956 | 0 | 5 | 113 | 72 | 52 | 20 | 12 | 0 |
{-# LANGUAGE TemplateHaskell, Rank2Types #-}
-- | Experimental features using Template Haskell.
-- You need to have a @{-\# LANGUAGE TemplateHaskell \#-}@ pragma in
-- your module for any of these to work.
module Test.QuickCheck.All(
-- ** Testing all properties in a module.
quickCheckAll,
verboseCheckAll,
forAllProperties,
-- ** Testing polymorphic properties.
polyQuickCheck,
polyVerboseCheck,
mono) where
import Language.Haskell.TH
import Test.QuickCheck.Property hiding (Result)
import Test.QuickCheck.Test
import Data.Char
import Data.List
import Control.Monad
-- | Test a polymorphic property, defaulting all type variables to 'Integer'.
--
-- Invoke as @$('polyQuickCheck' 'prop)@, where @prop@ is a property.
-- Note that just evaluating @'quickCheck' prop@ in GHCi will seem to
-- work, but will silently default all type variables to @()@!
polyQuickCheck :: Name -> ExpQ
polyQuickCheck x = [| quickCheck $(mono x) |]
-- | Test a polymorphic property, defaulting all type variables to 'Integer'.
-- This is just a convenience function that combines 'polyQuickCheck' and 'verbose'.
polyVerboseCheck :: Name -> ExpQ
polyVerboseCheck x = [| verboseCheck $(mono x) |]
type Error = forall a. String -> a
-- | Monomorphise an arbitrary name by defaulting all type variables to 'Integer'.
--
-- For example, if @f@ has type @'Ord' a => [a] -> [a]@
-- then @$('mono' 'f)@ has type @['Integer'] -> ['Integer']@.
mono :: Name -> ExpQ
mono t = do
ty0 <- fmap infoType (reify t)
let err msg = error $ msg ++ ": " ++ pprint ty0
(polys, ctx, ty) <- deconstructType err ty0
case polys of
[] -> return (VarE t)
_ -> do
integer <- [t| Integer |]
ty' <- monomorphise err integer ty
return (SigE (VarE t) ty')
infoType :: Info -> Type
infoType (ClassOpI _ ty _ _) = ty
infoType (DataConI _ ty _ _) = ty
infoType (VarI _ ty _ _) = ty
deconstructType :: Error -> Type -> Q ([Name], Cxt, Type)
deconstructType err ty0@(ForallT xs ctx ty) = do
let plain (PlainTV _) = True
plain _ = False
unless (all plain xs) $ err "Higher-kinded type variables in type"
return (map (\(PlainTV x) -> x) xs, ctx, ty)
deconstructType _ ty = return ([], [], ty)
monomorphise :: Error -> Type -> Type -> TypeQ
monomorphise err mono ty@(VarT n) = return mono
monomorphise err mono (AppT t1 t2) = liftM2 AppT (monomorphise err mono t1) (monomorphise err mono t2)
monomorphise err mono ty@(ForallT _ _ _) = err $ "Higher-ranked type"
monomorphise err mono ty = return ty
-- | Test all properties in the current module, using a custom
-- 'quickCheck' function. The same caveats as with 'quickCheckAll'
-- apply.
--
-- @$'forAllProperties'@ has type @('Property' -> 'IO' 'Result') -> 'IO' 'Bool'@.
-- An example invocation is @$'forAllProperties' 'quickCheckResult'@,
-- which does the same thing as @$'quickCheckAll'@.
forAllProperties :: Q Exp -- :: (Property -> IO Result) -> IO Bool
forAllProperties = do
Loc { loc_filename = filename } <- location
when (filename == "<interactive>") $ error "don't run this interactively"
ls <- runIO (fmap lines (readFile filename))
let prefixes = map (takeWhile (\c -> isAlphaNum c || c == '_') . dropWhile (\c -> isSpace c || c == '>')) ls
idents = nubBy (\x y -> snd x == snd y) (filter (("prop_" `isPrefixOf`) . snd) (zip [1..] prefixes))
quickCheckOne :: (Int, String) -> Q [Exp]
quickCheckOne (l, x) = do
exists <- return False `recover` (reify (mkName x) >> return True)
if exists then sequence [ [| ($(stringE $ x ++ " on " ++ filename ++ ":" ++ show l),
property $(mono (mkName x))) |] ]
else return []
[| runQuickCheckAll $(fmap (ListE . concat) (mapM quickCheckOne idents)) |]
-- | Test all properties in the current module.
-- The name of the property must begin with @prop_@.
-- Polymorphic properties will be defaulted to 'Integer'.
-- Returns 'True' if all tests succeeded, 'False' otherwise.
--
-- Using 'quickCheckAll' interactively doesn't work.
-- Instead, add a definition to your module along the lines of
--
-- > runTests = $quickCheckAll
--
-- and then execute @runTests@.
quickCheckAll :: Q Exp
quickCheckAll = [| $(forAllProperties) quickCheckResult |]
-- | Test all properties in the current module.
-- This is just a convenience function that combines 'quickCheckAll' and 'verbose'.
verboseCheckAll :: Q Exp
verboseCheckAll = [| $(forAllProperties) verboseCheckResult |]
runQuickCheckAll :: [(String, Property)] -> (Property -> IO Result) -> IO Bool
runQuickCheckAll ps qc =
fmap and . forM ps $ \(xs, p) -> do
putStrLn $ "=== " ++ xs ++ " ==="
r <- qc p
return $ case r of
Success { } -> True
Failure { } -> False
NoExpectedFailure { } -> False
| AlexBaranosky/QuickCheck | Test/QuickCheck/All.hs | bsd-3-clause | 4,775 | 0 | 18 | 971 | 1,145 | 616 | 529 | 73 | 3 |
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ExistentialQuantification #-}
module Ivory.Language.Effects
( Effects(..)
, AllocEffects
, ProcEffects
, NoEffects
, ReturnEff(..)
, GetReturn()
, ClearReturn()
, BreakEff(..)
, GetBreaks()
, AllowBreak()
, ClearBreak()
, AllocEff(..)
, GetAlloc()
, ClearAlloc()
) where
--------------------------------------------------------------------------------
-- Effect Context
-- | The effect context for 'Ivory' operations.
data Effects = Effects ReturnEff BreakEff AllocEff
-- | Function return effect.
data ReturnEff = forall t. Returns t | NoReturn
-- | Loop break effect.
data BreakEff = Break | NoBreak
-- | Stack allocation effect.
data AllocEff = forall s. Scope s | NoAlloc
--------------------------------------------------------------------------------
-- Returns
-- | Retrieve any 'Return' effect present.
type family GetReturn (effs :: Effects) :: ReturnEff
type instance GetReturn ('Effects r b a) = r
-- | Remove any 'Return' effects present.
type family ClearReturn (effs :: Effects) :: Effects
type instance ClearReturn ('Effects r b a) = 'Effects 'NoReturn b a
--------------------------------------------------------------------------------
-- Breaks
-- | Retrieve any 'Breaks' effect present.
type family GetBreaks (effs :: Effects) :: BreakEff
type instance GetBreaks ('Effects r b a) = b
-- | Add the 'Break' effect into an effect context.
type family AllowBreak (effs :: Effects) :: Effects
type instance AllowBreak ('Effects r b a) = 'Effects r 'Break a
-- | Remove any 'Break' effect present.
type family ClearBreak (effs :: Effects) :: Effects
type instance ClearBreak ('Effects r b a) = 'Effects r 'NoBreak a
--------------------------------------------------------------------------------
-- Allocs
-- | Retrieve the current allocation effect.
type family GetAlloc (effs :: Effects) :: AllocEff
type instance GetAlloc ('Effects r b a) = a
-- | Remove any allocation effect currently present.
type family ClearAlloc (effs :: Effects) :: Effects
type instance ClearAlloc ('Effects r b a) = 'Effects r b 'NoAlloc
--------------------------------------------------------------------------------
-- Helpers
type AllocEffects s = 'Effects 'NoReturn 'NoBreak (Scope s)
type ProcEffects s t = 'Effects (Returns t) 'NoBreak (Scope s)
type NoEffects = 'Effects 'NoReturn 'NoBreak 'NoAlloc
--------------------------------------------------------------------------------
| Hodapp87/ivory | ivory/src/Ivory/Language/Effects.hs | bsd-3-clause | 2,597 | 0 | 7 | 413 | 553 | 336 | 217 | 56 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
module Kis.SqliteBackend
( withSqliteKis
, withSqliteKisWithNotifs
, sqliteBackend
, SqliteBackendType(..)
, runClient
, runSingleClientSqlite
, buildKisWithBackend
, RunNotifications(..)
)
where
import Kis.Kis
import Kis.Notifications
import Kis.SqlBackend
import Control.Concurrent
import Control.Concurrent.Async
import Control.Monad.Catch
import Control.Monad.Except
import Control.Monad.Trans.Control
import Database.Persist.Sql as S
import Database.Persist.Sqlite
import Database.Sqlite as Sqlite hiding (config)
import Data.Pool
import Data.Monoid
import qualified Data.Text as T
data SqliteBackendType = InMemory | PoolBackendType T.Text Int
withSqliteKisWithNotifs ::
SqliteBackendType
-> KisConfig IO
-> [NotificationHandler]
-> (Kis IO -> IO a)
-> IO a
withSqliteKisWithNotifs backendType config notifHandlers f =
do backend <- sqliteBackend backendType
stopNotifThread <- newEmptyMVar
(kis, notifThread) <-
buildKisWithBackend backend config (RunNotifs stopNotifThread notifHandlers)
res <- f kis
putMVar stopNotifThread ()
wait notifThread
return res
withSqliteKis ::
SqliteBackendType
-> KisConfig IO
-> (Kis IO -> IO a)
-> IO a
withSqliteKis backendType config f =
do backend <- sqliteBackend backendType
(kis, _) <- buildKisWithBackend backend config NoNotifs
f kis
runSingleClientSqlite ::
SqliteBackendType
-> KisConfig IO
-> KisClient IO a
-> IO a
runSingleClientSqlite backendType config client =
withSqliteKis backendType config $ \kis -> runClient kis client
sqliteBackend :: (MonadCatch m, MonadBaseControl IO m, MonadIO m) => SqliteBackendType -> m (KisBackend SqliteException)
sqliteBackend backendType = do
backend <- case backendType of
InMemory ->
do backend <- singleBackend ":memory:"
return (SingleBackend backend sqliteExceptions)
(PoolBackendType filename size) -> poolBackend filename size
sqlMigrate backend
return backend
sqliteExceptions :: SqliteException -> KisException
sqliteExceptions (SqliteException ErrorConstraint _ _) = ConstraintViolation
sqliteExceptions (SqliteException errorType x y) = OtherError (T.pack (show errorType) <> ": " <> x <> " " <> y)
poolBackend :: MonadIO m => T.Text -> Int -> m (KisBackend SqliteException)
poolBackend filename size =
do pool <- liftIO $ createPool (singleBackend filename) (const $ return ()) 1 20 size
return (PoolBackend pool sqliteExceptions)
singleBackend :: MonadIO m => T.Text -> m SqlBackend
singleBackend filename =
liftIO $ do
connection <- Sqlite.open filename
stmt <- Sqlite.prepare connection "PRAGMA foreign_keys = ON;"
void $ Sqlite.step stmt
Sqlite.finalize stmt
wrapConnection connection (\_ _ _ _ -> return ())
| lslah/kis-proto | src/Kis/SqliteBackend.hs | bsd-3-clause | 2,990 | 0 | 15 | 646 | 825 | 414 | 411 | 81 | 2 |
{-# LANGUAGE
DeriveDataTypeable
, DeriveGeneric
, TemplateHaskell
, TypeFamilies
#-}
module Type.CustomerInvoice where
import Data.Aeson
import Data.JSON.Schema
import Data.Typeable
import GHC.Generics
import Generics.Regular
import Generics.Regular.XmlPickler
import Text.XML.HXT.Arrow.Pickle
import Type.CreateInvoice (CreateInvoice)
import Type.Customer (Customer)
data CustomerInvoice = CustomerInvoice { customer :: Customer, invoice :: CreateInvoice }
deriving (Eq, Generic, Ord, Show, Typeable)
deriveAll ''CustomerInvoice "PFCustomerInvoice"
type instance PF CustomerInvoice = PFCustomerInvoice
instance XmlPickler CustomerInvoice where xpickle = gxpickle
instance JSONSchema CustomerInvoice where schema = gSchema
instance FromJSON CustomerInvoice
instance ToJSON CustomerInvoice
| tinkerthaler/basic-invoice-rest | example-api/Type/CustomerInvoice.hs | bsd-3-clause | 814 | 0 | 8 | 105 | 171 | 98 | 73 | 23 | 0 |
error = (\x -> e) ==> (let f x = e in f) | jonathankochems/raskell-git-download | HLint.hs | bsd-3-clause | 40 | 0 | 11 | 12 | 35 | 18 | 17 | 1 | 1 |
import SFML.Graphics.Internal.RenderWindow
import SFML.Graphics.Internal.Image
import SFML.Graphics.Internal.Sprite
import SFML.Graphics.Internal.Color
import SFML.Graphics.Internal.Text
import SFML.Graphics.Internal.Font
import SFML.Window.Internal.Types
import SFML.Window.Internal.VideoMode
import SFML.Window.Internal.Event
import SFML.System.Internal.Clock
import SFML.Audio.Internal.Music
import Control.Monad
import Foreign.ForeignPtr
import SFML.Graphics.Internal.Types
withMaybe :: Monad m => Maybe a -> (a -> m b) -> m ()
withMaybe Nothing _ = return ()
withMaybe (Just x) m = m x >> return ()
main = do
window <- renderWindowCreate (VideoMode 800 600 32) "SFML window" [] Nothing
renderWindowEnableVerticalSync window True
renderWindowSetFramerateLimit window 5
Just image <- imageCreateFromFile "test.png"
Just sprite <- spriteCreate
spriteSetImage sprite image True
Just text <- textCreate
textSetFont text fontDefault
textSetString text "Hello"
textSetCharacterSize text 50
Just music <- musicCreateFromFile "Music.ogg"
musicPlay music
run window sprite text music
putStrLn "Main exiting"
run window sprite text music = do
isOpen <- renderWindowIsOpened window
when isOpen $ do
handleEvents window sprite music
renderWindowClear window colorBlack
renderWindowDrawSprite window sprite
renderWindowDrawText window text
renderWindowDisplay window
run window sprite text music
where
handleEvents window sprite music = do
event <- renderWindowPollEvent window
withMaybe event $ \evt ->do
case evt of
Closed -> renderWindowClose window
(KeyPressed KeyEscape _ _ _) -> renderWindowClose window
(KeyPressed KeyLeft _ _ _) -> spriteMove sprite (-5) 0
(KeyPressed KeyRight _ _ _) -> spriteMove sprite 5 0
(KeyPressed KeyUp _ _ _) -> spriteMove sprite 0 (-5)
(KeyPressed KeyDown _ _ _) -> spriteMove sprite 0 5
(KeyPressed KeyP _ _ _) -> musicPlay music
(KeyPressed KeyS _ _ _) -> musicStop music
(KeyPressed key _ _ _) -> putStrLn ("Pressed " ++ show key)
_ -> return ()
handleEvents window sprite music
| Berengal/SFML---Haskell-bindings | Hacking.hs | bsd-3-clause | 2,198 | 0 | 19 | 452 | 695 | 334 | 361 | 56 | 10 |
{- |
Module : $Header$
Description : shell related functions
Copyright : uni-bremen and DFKI
License : GPLv2 or higher, see LICENSE.txt
Maintainer : r.pascanu@jacobs-university.de
Stability : provisional
Portability : portable
CMDL.Shell contains almost all functions related
the CMDL shell or haskeline
-}
module CMDL.Shell
( cComment
, cOpenComment
, cCloseComment
, nodeNames
, cmdlCompletionFn
, checkCom
) where
import CMDL.DataTypes
import CMDL.Utils
import CMDL.DataTypesUtils
import Common.Utils (trimLeft, trimRight, nubOrd, splitOn)
import Common.Result (Result (Result))
import Comorphisms.LogicGraph (comorphismList, logicGraph,
lookupComorphism_in_LG)
import Interfaces.Command (Command (CommentCmd))
import Interfaces.DataTypes
import Interfaces.Utils
import Interfaces.GenericATPState
import Logic.Comorphism
import Logic.Grothendieck (logics, findComorphismPaths,
G_sublogics (..))
import Logic.Prover
import Logic.Logic
import Logic.Coerce (coerceSublogic)
import Proofs.AbstractState
import Static.DevGraph
import Static.GTheory
import Data.Char (isSpace)
import Data.List
import qualified Data.Map
import Data.Maybe (mapMaybe, isNothing)
import System.Directory (doesDirectoryExist, getDirectoryContents)
register2history :: CmdlCmdDescription -> CmdlState -> IO CmdlState
register2history dscr state = do
let oldHistory = i_hist $ intState state
case undoList oldHistory of
[] -> return state
h : r -> case command h of
CommentCmd _ -> do
let nwh = h {
command = cmdDescription dscr }
return $ state {
intState = (intState state) {
i_hist = oldHistory {
undoList = nwh : r,
redoList = []
} } }
_ -> return state
-- process a comment line
processComment :: CmdlState -> String -> CmdlState
processComment st inp =
if isInfixOf "}%" inp then st { openComment = False } else st
-- adds a line to the script
addToScript :: CmdlState -> IntIState -> String -> CmdlState
addToScript st ist str
= let olds = script ist
oldextOpts = tsExtraOpts olds
in st {
intState = (intState st) {
i_state = Just ist {
script = olds { tsExtraOpts = str : oldextOpts } }
} }
checkCom :: CmdlCmdDescription -> CmdlState -> IO CmdlState
checkCom descr state =
-- check the priority of the current command
case cmdPriority descr of
CmdNoPriority ->
-- check if there is open comment
if openComment state
then return $ processComment state $ cmdInput descr
else
case i_state $ intState state of
Nothing -> register2history descr state
Just ist ->
-- check if there is inside a script
if loadScript ist
then return $ addToScript state ist
$ cmdName descr ++ " " ++ cmdInput descr
else register2history descr state
CmdGreaterThanComments ->
case i_state $ intState state of
Nothing -> register2history descr state
Just ist ->
if loadScript ist
then return $ addToScript state ist
$ cmdName descr ++ " " ++ cmdInput descr
else register2history descr state
CmdGreaterThanScriptAndComments -> return state
-- | Function handle a comment line
cComment :: String -> CmdlState -> IO CmdlState
cComment _ = return
-- For normal keyboard input
cOpenComment :: String -> CmdlState -> IO CmdlState
cOpenComment _ state = return state { openComment = True }
cCloseComment :: CmdlState -> IO CmdlState
cCloseComment state = return state { openComment = False }
{- | given an input it assumes that it starts with a
command name and tries to remove this command name -}
subtractCommandName :: [CmdlCmdDescription] -> String -> String
subtractCommandName allcmds input =
let inp = trimLeft input
in case mapMaybe ((`stripPrefix` inp) . cmdName) allcmds of
[] -> inp
hd : _ -> hd
{- This function tries to extract the name of command. In most cases this
would be the first word of the string but we have a few exceptions :
dg * commands
dg-all * commands
del * commands
del-all * commands
add * commands
set * commands
set-all * commands -}
getCmdName :: String -> String
getCmdName inp = case words inp of
[] -> []
hw : tws -> case tws of
[] -> hw
hwd : _ -> let
cs = ["dg", "del", "set"]
csa = "add" : cs ++ map (++ "-all") cs
in if elem hw csa then hw ++ ' ' : hwd else hw
{- | The function determines the requirements of the command
name found at the begining of the string -}
getTypeOf :: [CmdlCmdDescription] -> String -> CmdlCmdRequirements
getTypeOf allcmds input
= let nwInput = getCmdName input
tmp = concatMap (\ x -> case find (== nwInput) [cmdName x] of
Nothing -> []
Just _ -> [cmdReq x]) allcmds
in case tmp of
result : [] -> result
_ -> ReqUnknown
nodeNames :: [(a, DGNodeLab)] -> [String]
nodeNames = map (getDGNodeName . snd)
{- | The function provides a list of possible completion
to a given input if any -}
cmdlCompletionFn :: [CmdlCmdDescription] -> CmdlState -> String -> IO [String]
cmdlCompletionFn allcmds allState input =
let s0_9 = map show [0 .. (9 :: Int)]
app h = (h ++) . (' ' :)
in case getTypeOf allcmds input of
ReqNodesOrEdges mn mf ->
case i_state $ intState allState of
Nothing -> return []
Just state -> do
{- a pair, where the first element is what needs
to be completed while the second is what is
before the word that needs to be completed
-}
let -- get all nodes
ns = getAllNodes state
fns = nodeNames $ maybe id (\ f -> filter (\ (_, nd) ->
case f of
OpenCons -> hasOpenNodeConsStatus False nd
OpenGoals -> hasOpenGoals nd))
mf ns
es = map fst
$ maybe id (\ f -> filter $ case f of
OpenCons -> isOpenConsEdge
OpenGoals -> edgeContainsGoals
. snd) mf
$ createEdgeNames ns (getAllEdges state)
allNames = case mn of
Nothing -> es ++ fns
Just b -> if b then fns else es
(fins, tC) = finishedNames allNames
$ subtractCommandName allcmds input
-- what is before tC
bC = reverse $ trimLeft $ drop (length tC) $ reverse input
{- filter out words that do not start with the word
that needs to be completed and add the word that
was before the word that needs to be completed -}
return $ map (app bC) $ filter (isPrefixOf tC) $ allNames \\ fins
ReqConsCheck -> do
let tC = if isSpace $ lastChar input
then []
else lastString $ words input
bC = if isSpace $ lastChar input
then trimRight input
else unwords $ init $ words input
getCCName (G_cons_checker _ p) = ccName p
createConsCheckersList = map (getCCName . fst) . getAllConsCheckers
case i_state $ intState allState of
Nothing ->
{- not in proving mode !? you can not choose a consistency
checker here -}
return []
Just proofState ->
case cComorphism proofState of
-- some comorphism was used
Just c -> return $ map (app bC) $ filter (isPrefixOf tC)
$ createConsCheckersList [c]
Nothing ->
case elements proofState of
-- no elements selected
[] -> return []
c : _ -> case c of
Element z _ -> return $ map (app bC)
$ filter (isPrefixOf tC)
$ createConsCheckersList
$ findComorphismPaths logicGraph
(sublogicOfTheory z)
ReqProvers -> do
let bC : tl = words input
tC = unwords tl
{- find the last comorphism used if none use the
the comorphism of the first selected node -}
case i_state $ intState allState of
Nothing ->
{- not in proving mode !? you can not choose
provers here -}
return []
Just proofState ->
case elements proofState of
-- no elements selected
[] -> return []
-- use the first element to get a comorphism
c : _ -> case c of
Element z _ -> do
ps <- getUsableProvers ProveCMDLautomatic
(sublogicOfTheory z) logicGraph
let lst = nub $ map (getProverName . fst) ps
return $ map (app bC) $ filter (isPrefixOf tC) lst
ReqComorphism ->
let input'' = case words input of
cmd : s' -> unwords (cmd : concatMap (splitOn ':')
(concatMap (splitOn ';') s'))
_ -> input
input' = if elem (lastChar input) ";: " then
input'' ++ " " else input''
in case i_state $ intState allState of
Nothing -> return []
Just pS ->
case elements pS of
[] -> return []
Element st _ : _ ->
let tC = if isSpace $ lastChar input'
then []
else lastString $ words input'
appendC' =
map (\ coname -> case lookupComorphism_in_LG coname of
Result _ cmor -> cmor) $
tail $ words input'
appendC = sequence $ (if not (null appendC') &&
isNothing (last appendC')
then init else id) appendC'
comor = case appendC of
Nothing -> cComorphism pS
Just cs ->
foldl (\ c1 c2 -> maybe Nothing
(`compComorphism` c2) c1)
(cComorphism pS) cs
bC = if isSpace $ lastChar input'
then trimRight input'
else unwords $ init $ words input'
sl = case comor of
Just (Comorphism cid) ->
case sublogicOfTheory st of
G_sublogics lid sl2 ->
case coerceSublogic lid (sourceLogic cid) "" sl2 of
Just sl2' -> case mapSublogic cid sl2' of
Just sl1 -> G_sublogics (targetLogic cid) sl1
Nothing -> G_sublogics (targetLogic cid)
(top_sublogic $ targetLogic cid)
Nothing -> G_sublogics (targetLogic cid)
(top_sublogic $ targetLogic cid)
Nothing -> sublogicOfTheory st
cL = concatMap (\ (Comorphism cid) ->
[ language_name cid
| isSubElemG sl (G_sublogics
(sourceLogic cid)
(sourceSublogic cid)) ]
) comorphismList
in return $ map (app bC)
$ filter (isPrefixOf tC) cL
ReqLogic ->
let l' = lastString $ words input
i = unwords (init $ words input) ++ " "
in if elem '.' l'
then let (l, _ : sl) = Data.List.break (== '.') l'
in case Data.Map.lookup l $ logics logicGraph of
Just (Logic lid) -> return $ map ((i ++ l ++ ".") ++) $
filter (Data.List.isPrefixOf sl)
(map sublogicName $ all_sublogics lid)
Nothing -> return []
else return $ concatMap
(\ (n, Logic lid) ->
case map sublogicName $ all_sublogics lid of
[_] -> [i ++ n]
sls -> (i ++ n) : map
(\ sl -> i ++ n ++ "." ++ sl) sls) $
filter (Data.List.isPrefixOf l' . fst) $
Data.Map.toList $ logics logicGraph
ReqFile -> do
-- the incomplete path introduced until now
let initwd = if isSpace $ lastChar input
then []
else lastString $ words input
{- the folder in which to look for (it might be
empty) -}
tmpPath = reverse $ dropWhile (/= '/') $ reverse initwd
{- in case no folder was introduced yet look into
current folder -}
lastPath = case tmpPath of
[] -> "./"
_ -> tmpPath
{- the name of file/directory that needs to be
completed from the already introduced path -}
tC = reverse $ takeWhile (/= '/') $ reverse initwd
bC = if isSpace $ lastChar input
then input
else unwords (init $ words input) ++ " " ++ tmpPath
-- leave just folders and files with extenstion .casl
b' <- doesDirectoryExist lastPath
ls <- if b' then getDirectoryContents lastPath else return []
names <- fileFilter lastPath ls []
{- case list contains only one name
then if it is a folder extend it -}
let names' = filter (isPrefixOf tC) names
names'' <- case safeTail names' of
{- check CMDL.Utils to see how it
works, function should be done with
something like map but that can handle
functions with IO
(mapIO !? couldn't make it work though) -}
[] -> fileExtend lastPath names' []
_ -> return names'
return $ map (bC ++) names''
ReqAxm b ->
case i_state $ intState allState of
Nothing -> return []
Just pS ->
do
let tC = if isSpace $ lastChar input
then []
else lastString $ words input
bC = if isSpace $ lastChar input
then trimRight input
else unwords $ init $ words input
return $ map (app bC) $ filter (isPrefixOf tC) $ nubOrd
$ concatMap (\ (Element st nb) ->
if b then map fst $ getAxioms st else
case getTh Do_translate nb allState of
Nothing -> []
Just th -> map fst $ filter
(maybe False (not . isProvedBasically) . snd)
$ getThGoals th)
$ elements pS
ReqNumber -> case words input of
[hd] -> return $ map (app hd) s0_9
_ : _ : [] -> return $ if isSpace $ lastChar input
then []
else map (input ++) s0_9
_ -> return []
ReqNothing -> return []
ReqUnknown -> return []
| mariefarrell/Hets | CMDL/Shell.hs | gpl-2.0 | 15,710 | 89 | 35 | 6,397 | 2,775 | 1,603 | 1,172 | 299 | 49 |
-- |
-- Module : Distro
-- Copyright : (C) 2016 Jens Petersen
--
-- Maintainer : Jens Petersen <petersen@fedoraproject.org>
--
-- Types and utility functions to represent different RPM-based distributions.
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
module Distro (
detectDistro, parseDistroName, readDistroName, Distro(..)
) where
import SysCmd (cmd)
import Data.Maybe (fromMaybe)
import Data.Char (toLower)
data Distro = Fedora | RHEL5 | SUSE deriving (Show, Eq)
detectDistro :: IO Distro
detectDistro = do
suseVersion <- cmd "rpm" ["--eval", "%{?suse_version}"]
if null suseVersion then do
dist <- cmd "rpm" ["--eval", "%{?dist}"]
-- RHEL5 does not have macros.dist
return $ if null dist || dist == ".el5" then RHEL5 else Fedora
else return SUSE
parseDistroName :: String -> Maybe Distro
parseDistroName x = lookup (map toLower x) known
where
known = [ ("suse", SUSE)
, ("fedora", Fedora)
, ("rhel5", RHEL5)
]
readDistroName :: String -> Distro
readDistroName s = fromMaybe (error $ "unrecognized distribution name " ++ show s) (parseDistroName s)
| opensuse-haskell/cabal-rpm | src/Distro.hs | gpl-3.0 | 1,346 | 0 | 14 | 285 | 287 | 163 | 124 | 20 | 3 |
-- @Author: Zeyuan Shang
-- @Date: 2015-12-04 01:40:40
-- @Last Modified by: Zeyuan Shang
-- @Last Modified time: 2015-12-04 03:27:24
import Control.Monad
import Data.Graph
import qualified Data.Array as A
import qualified Data.IntMap as M
----- naive AVL -----
data AVLTree a = Null | AVLNode a (AVLTree a) (AVLTree a) Int Int -- height size
deriving Show
value Null = error "null"
value (AVLNode v _ _ _ _) = v
left Null = Null
left (AVLNode _ l _ _ _) = l
right Null = Null
right (AVLNode _ _ r _ _) = r
height Null = 0
height (AVLNode _ _ _ h _) = h
size Null = 0
size (AVLNode _ _ _ _ s) = s
weight Null = 0
weight (AVLNode _ l r _ s) = (height l) - (height r)
update Null = Null
update (AVLNode root l r _ _) = AVLNode root l r (1 + max (height l) (height r)) (1 + (size l) + (size r))
leftRotate Null = Null
leftRotate (AVLNode root l r h s) = update $ AVLNode (value r) newLeft (right r) 0 0
where newLeft = update $ AVLNode root l (left r) 0 0
rightRotate Null = Null
rightRotate (AVLNode root l r h s) = update $ AVLNode (value l) (left l) newRight 0 0
where newRight = update $ AVLNode root (right l) r 0 0
balance Null = Null
balance (AVLNode root l r h s)
| abs w <= 1 = AVLNode root l r h s
| w > 0 = if weight l < 0 then rightRotate $ AVLNode root newLeft r h s
else rightRotate $ AVLNode root l r h s
| otherwise = if weight r > 0 then leftRotate $ AVLNode root l newRight h s
else leftRotate $ AVLNode root l r h s
where w = weight (AVLNode root l r h s)
newLeft = leftRotate l
newRight = rightRotate r
insert :: (Ord a) => AVLTree a -> a -> AVLTree a
insert Null value = AVLNode value Null Null 1 1
insert (AVLNode root l r h s) value = balance . update $ AVLNode root newLeft newRight h s
where newLeft = if value < root then insert l value else l
newRight = if value < root then r else insert r value
select :: AVLTree a -> Int -> a -- find kth element in the AVL tree
select Null k = error "null"
select (AVLNode root l r _ _) k
| rank == k = root
| rank > k = select l k
| otherwise = select r (k - rank)
where rank = 1 + size l
----- naive AVL -----
----- main -----
toTwo [] = []
toTwo (x:y:rs) = (y, x):toTwo rs
walk Null = []
walk (AVLNode root l r _ _) = root : walk l ++ walk r
merge ta tb
| size ta >= size tb = foldl insert ta (walk tb)
| otherwise = merge tb ta
build :: A.Array Int Int -> Graph -> M.IntMap (AVLTree (Int, Int)) -> Int -> M.IntMap (AVLTree (Int, Int))
build salaries graph m u = let vs = graph A.! u
ut = foldl1 merge $ (foldl insert Null [(salaries A.! v, v) | v <- vs]) : [m M.! v | v <- vs]
in M.insert u ut m
main :: IO ()
main = do
inputs <- getContents >>= return . map (read :: String -> Int) . words
let (n:m:rest) = inputs
(edges', rest') = splitAt (2 * (n - 1)) rest
edges = toTwo edges'
(salaries', rest'') = splitAt n rest'
queries = toTwo rest''
graph = buildG (1, n) edges
salaries = A.listArray (1, n) salaries'
build' = build salaries graph
topOrder = reverse $ topSort graph
trees = M.toAscList $ foldl build' M.empty topOrder
vecs = A.array (1, n) trees
results = tail $ scanl (\n (k, u) -> snd $ select (vecs A.! (n + u)) k) 0 queries
mapM_ print results
----- main ----- | EdisonAlgorithms/HackerRank | practice/fp/persistent-ds/boleyn-salary/boleyn-salary.hs | mit | 3,476 | 0 | 19 | 1,024 | 1,592 | 805 | 787 | 75 | 3 |
{-
Copyright (C) 2010 Ivan Lazar Miljenovic <Ivan.Miljenovic@gmail.com>
This file is part of SourceGraph.
SourceGraph 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- |
Module : Analyse.Visualise
Description : Visualisation functions.
Copyright : (c) Ivan Lazar Miljenovic 2010
License : GPL-3 or later.
Maintainer : Ivan.Miljenovic@gmail.com
Utility functions and types for analysis.
-}
module Analyse.Colors where
import Data.GraphViz.Attributes
inaccessibleColor :: X11Color
inaccessibleColor = Crimson
exportedRootColor :: X11Color
exportedRootColor = Gold
exportedInnerColor :: X11Color
exportedInnerColor = Goldenrod
implicitExportColor :: X11Color
implicitExportColor = Khaki
leafColor :: X11Color
leafColor = Cyan
defaultNodeColor :: X11Color
defaultNodeColor = Bisque
defaultEdgeColor :: X11Color
defaultEdgeColor = Black
cliqueColor :: X11Color
cliqueColor = Orange
cycleColor :: X11Color
cycleColor = DarkOrchid
chainColor :: X11Color
chainColor = Chartreuse
clusterBackground :: X11Color
clusterBackground = Lavender
noBackground :: X11Color
noBackground = Snow
| Baranowski/SourceGraph | Analyse/Colors.hs | gpl-3.0 | 1,742 | 0 | 4 | 288 | 134 | 82 | 52 | 26 | 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.RemoveRoleFromInstanceProfile
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Removes the specified role from the specified instance profile.
--
-- Make sure you do not have any Amazon EC2 instances running with the role
-- you are about to remove from the instance profile. Removing a role from an
-- instance profile that is associated with a running instance will break any
-- applications running on the instance. For more information about roles, go
-- to <http://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html Working with Roles>. For more information about instance profiles, go to <http://docs.aws.amazon.com/IAM/latest/UserGuide/AboutInstanceProfiles.html About Instance Profiles>.
--
-- <http://docs.aws.amazon.com/IAM/latest/APIReference/API_RemoveRoleFromInstanceProfile.html>
module Network.AWS.IAM.RemoveRoleFromInstanceProfile
(
-- * Request
RemoveRoleFromInstanceProfile
-- ** Request constructor
, removeRoleFromInstanceProfile
-- ** Request lenses
, rrfipInstanceProfileName
, rrfipRoleName
-- * Response
, RemoveRoleFromInstanceProfileResponse
-- ** Response constructor
, removeRoleFromInstanceProfileResponse
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.IAM.Types
import qualified GHC.Exts
data RemoveRoleFromInstanceProfile = RemoveRoleFromInstanceProfile
{ _rrfipInstanceProfileName :: Text
, _rrfipRoleName :: Text
} deriving (Eq, Ord, Read, Show)
-- | 'RemoveRoleFromInstanceProfile' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'rrfipInstanceProfileName' @::@ 'Text'
--
-- * 'rrfipRoleName' @::@ 'Text'
--
removeRoleFromInstanceProfile :: Text -- ^ 'rrfipInstanceProfileName'
-> Text -- ^ 'rrfipRoleName'
-> RemoveRoleFromInstanceProfile
removeRoleFromInstanceProfile p1 p2 = RemoveRoleFromInstanceProfile
{ _rrfipInstanceProfileName = p1
, _rrfipRoleName = p2
}
-- | The name of the instance profile to update.
rrfipInstanceProfileName :: Lens' RemoveRoleFromInstanceProfile Text
rrfipInstanceProfileName =
lens _rrfipInstanceProfileName
(\s a -> s { _rrfipInstanceProfileName = a })
-- | The name of the role to remove.
rrfipRoleName :: Lens' RemoveRoleFromInstanceProfile Text
rrfipRoleName = lens _rrfipRoleName (\s a -> s { _rrfipRoleName = a })
data RemoveRoleFromInstanceProfileResponse = RemoveRoleFromInstanceProfileResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'RemoveRoleFromInstanceProfileResponse' constructor.
removeRoleFromInstanceProfileResponse :: RemoveRoleFromInstanceProfileResponse
removeRoleFromInstanceProfileResponse = RemoveRoleFromInstanceProfileResponse
instance ToPath RemoveRoleFromInstanceProfile where
toPath = const "/"
instance ToQuery RemoveRoleFromInstanceProfile where
toQuery RemoveRoleFromInstanceProfile{..} = mconcat
[ "InstanceProfileName" =? _rrfipInstanceProfileName
, "RoleName" =? _rrfipRoleName
]
instance ToHeaders RemoveRoleFromInstanceProfile
instance AWSRequest RemoveRoleFromInstanceProfile where
type Sv RemoveRoleFromInstanceProfile = IAM
type Rs RemoveRoleFromInstanceProfile = RemoveRoleFromInstanceProfileResponse
request = post "RemoveRoleFromInstanceProfile"
response = nullResponse RemoveRoleFromInstanceProfileResponse
| kim/amazonka | amazonka-iam/gen/Network/AWS/IAM/RemoveRoleFromInstanceProfile.hs | mpl-2.0 | 4,433 | 0 | 9 | 864 | 399 | 246 | 153 | 54 | 1 |
-- (c) The University of Glasgow 2006
{-# LANGUAGE CPP #-}
module ETA.Types.OptCoercion ( optCoercion, checkAxInstCo ) where
#include "HsVersions.h"
import ETA.Types.Coercion
import qualified ETA.Types.Type as Type
import ETA.Types.Type hiding( substTyVarBndr, substTy, extendTvSubst )
import ETA.TypeCheck.TcType ( exactTyVarsOfType )
import ETA.Types.TyCon
import ETA.Types.CoAxiom
import ETA.BasicTypes.Var
import ETA.BasicTypes.VarSet
import ETA.Types.FamInstEnv ( flattenTys )
import ETA.BasicTypes.VarEnv
import ETA.Main.StaticFlags ( opt_NoOptCoercion )
import ETA.Utils.Outputable
import ETA.Utils.Pair
import ETA.Utils.FastString
import ETA.Utils.Util
import ETA.Types.Unify
import ETA.Utils.ListSetOps
import ETA.Types.InstEnv
import Control.Monad ( zipWithM )
{-
************************************************************************
* *
Optimising coercions
* *
************************************************************************
Note [Subtle shadowing in coercions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Supose we optimising a coercion
optCoercion (forall (co_X5:t1~t2). ...co_B1...)
The co_X5 is a wild-card; the bound variable of a coercion for-all
should never appear in the body of the forall. Indeed we often
write it like this
optCoercion ( (t1~t2) => ...co_B1... )
Just because it's a wild-card doesn't mean we are free to choose
whatever variable we like. For example it'd be wrong for optCoercion
to return
forall (co_B1:t1~t2). ...co_B1...
because now the co_B1 (which is really free) has been captured, and
subsequent substitutions will go wrong. That's why we can't use
mkCoPredTy in the ForAll case, where this note appears.
Note [Optimising coercion optimisation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Looking up a coercion's role or kind is linear in the size of the
coercion. Thus, doing this repeatedly during the recursive descent
of coercion optimisation is disastrous. We must be careful to avoid
doing this if at all possible.
Because it is generally easy to know a coercion's components' roles
from the role of the outer coercion, we pass down the known role of
the input in the algorithm below. We also keep functions opt_co2
and opt_co3 separate from opt_co4, so that the former two do Phantom
checks that opt_co4 can avoid. This is a big win because Phantom coercions
rarely appear within non-phantom coercions -- only in some TyConAppCos
and some AxiomInstCos. We handle these cases specially by calling
opt_co2.
-}
optCoercion :: CvSubst -> Coercion -> NormalCo
-- ^ optCoercion applies a substitution to a coercion,
-- *and* optimises it to reduce its size
optCoercion env co
| opt_NoOptCoercion = substCo env co
| otherwise = opt_co1 env False co
type NormalCo = Coercion
-- Invariants:
-- * The substitution has been fully applied
-- * For trans coercions (co1 `trans` co2)
-- co1 is not a trans, and neither co1 nor co2 is identity
-- * If the coercion is the identity, it has no CoVars of CoTyCons in it (just types)
type NormalNonIdCo = NormalCo -- Extra invariant: not the identity
-- | Do we apply a @sym@ to the result?
type SymFlag = Bool
-- | Do we force the result to be representational?
type ReprFlag = Bool
-- | Optimize a coercion, making no assumptions.
opt_co1 :: CvSubst
-> SymFlag
-> Coercion -> NormalCo
opt_co1 env sym co = opt_co2 env sym (coercionRole co) co
{-
opt_co env sym co
= pprTrace "opt_co {" (ppr sym <+> ppr co $$ ppr env) $
co1 `seq`
pprTrace "opt_co done }" (ppr co1) $
(WARN( not same_co_kind, ppr co <+> dcolon <+> ppr (coercionType co)
$$ ppr co1 <+> dcolon <+> ppr (coercionType co1) )
WARN( not (coreEqCoercion co1 simple_result),
(text "env=" <+> ppr env) $$
(text "input=" <+> ppr co) $$
(text "simple=" <+> ppr simple_result) $$
(text "opt=" <+> ppr co1) )
co1)
where
co1 = opt_co' env sym co
same_co_kind = s1 `eqType` s2 && t1 `eqType` t2
Pair s t = coercionKind (substCo env co)
(s1,t1) | sym = (t,s)
| otherwise = (s,t)
Pair s2 t2 = coercionKind co1
simple_result | sym = mkSymCo (substCo env co)
| otherwise = substCo env co
-}
-- See Note [Optimising coercion optimisation]
-- | Optimize a coercion, knowing the coercion's role. No other assumptions.
opt_co2 :: CvSubst
-> SymFlag
-> Role -- ^ The role of the input coercion
-> Coercion -> NormalCo
opt_co2 env sym Phantom co = opt_phantom env sym co
opt_co2 env sym r co = opt_co3 env sym Nothing r co
-- See Note [Optimising coercion optimisation]
-- | Optimize a coercion, knowing the coercion's non-Phantom role.
opt_co3 :: CvSubst -> SymFlag -> Maybe Role -> Role -> Coercion -> NormalCo
opt_co3 env sym (Just Phantom) _ co = opt_phantom env sym co
opt_co3 env sym (Just Representational) r co = opt_co4 env sym True r co
-- if mrole is Just Nominal, that can't be a downgrade, so we can ignore
opt_co3 env sym _ r co = opt_co4 env sym False r co
-- See Note [Optimising coercion optimisation]
-- | Optimize a non-phantom coercion.
opt_co4 :: CvSubst -> SymFlag -> ReprFlag -> Role -> Coercion -> NormalCo
opt_co4 env _ rep r (Refl _r ty)
= ASSERT( r == _r )
Refl (chooseRole rep r) (substTy env ty)
opt_co4 env sym rep r (SymCo co) = opt_co4 env (not sym) rep r co
opt_co4 env sym rep r g@(TyConAppCo _r tc cos)
= ASSERT( r == _r )
case (rep, r) of
(True, Nominal) ->
mkTyConAppCo Representational tc
(zipWith3 (opt_co3 env sym)
(map Just (tyConRolesX Representational tc))
(repeat Nominal)
cos)
(False, Nominal) ->
mkTyConAppCo Nominal tc (map (opt_co4 env sym False Nominal) cos)
(_, Representational) ->
-- must use opt_co2 here, because some roles may be P
-- See Note [Optimising coercion optimisation]
mkTyConAppCo r tc (zipWith (opt_co2 env sym)
(tyConRolesX r tc) -- the current roles
cos)
(_, Phantom) -> pprPanic "opt_co4 sees a phantom!" (ppr g)
opt_co4 env sym rep r (AppCo co1 co2) = mkAppCo (opt_co4 env sym rep r co1)
(opt_co4 env sym False Nominal co2)
opt_co4 env sym rep r (ForAllCo tv co)
= case substTyVarBndr env tv of
(env', tv') -> mkForAllCo tv' (opt_co4 env' sym rep r co)
-- Use the "mk" functions to check for nested Refls
opt_co4 env sym rep r (CoVarCo cv)
| Just co <- lookupCoVar env cv
= opt_co4 (zapCvSubstEnv env) sym rep r co
| Just cv1 <- lookupInScope (getCvInScope env) cv
= ASSERT( isCoVar cv1 ) wrapRole rep r $ wrapSym sym (CoVarCo cv1)
-- cv1 might have a substituted kind!
| otherwise = WARN( True, ptext (sLit "opt_co: not in scope:") <+> ppr cv $$ ppr env)
ASSERT( isCoVar cv )
wrapRole rep r $ wrapSym sym (CoVarCo cv)
opt_co4 env sym rep r (AxiomInstCo con ind cos)
-- Do *not* push sym inside top-level axioms
-- e.g. if g is a top-level axiom
-- g a : f a ~ a
-- then (sym (g ty)) /= g (sym ty) !!
= ASSERT( r == coAxiomRole con )
wrapRole rep (coAxiomRole con) $
wrapSym sym $
-- some sub-cos might be P: use opt_co2
-- See Note [Optimising coercion optimisation]
AxiomInstCo con ind (zipWith (opt_co2 env False)
(coAxBranchRoles (coAxiomNthBranch con ind))
cos)
-- Note that the_co does *not* have sym pushed into it
opt_co4 env sym rep r (UnivCo s _r oty1 oty2)
= ASSERT( r == _r )
opt_univ env s (chooseRole rep r) a b
where
(a,b) = if sym then (oty2,oty1) else (oty1,oty2)
opt_co4 env sym rep r (TransCo co1 co2)
-- sym (g `o` h) = sym h `o` sym g
| sym = opt_trans in_scope co2' co1'
| otherwise = opt_trans in_scope co1' co2'
where
co1' = opt_co4 env sym rep r co1
co2' = opt_co4 env sym rep r co2
in_scope = getCvInScope env
opt_co4 env sym rep r co@(NthCo {}) = opt_nth_co env sym rep r co
opt_co4 env sym rep r (LRCo lr co)
| Just pr_co <- splitAppCo_maybe co
= ASSERT( r == Nominal )
opt_co4 env sym rep Nominal (pickLR lr pr_co)
| Just pr_co <- splitAppCo_maybe co'
= ASSERT( r == Nominal )
if rep
then opt_co4 (zapCvSubstEnv env) False True Nominal (pickLR lr pr_co)
else pickLR lr pr_co
| otherwise
= wrapRole rep Nominal $ LRCo lr co'
where
co' = opt_co4 env sym False Nominal co
opt_co4 env sym rep r (InstCo co ty)
-- See if the first arg is already a forall
-- ...then we can just extend the current substitution
| Just (tv, co_body) <- splitForAllCo_maybe co
= opt_co4 (extendTvSubst env tv ty') sym rep r co_body
-- See if it is a forall after optimization
-- If so, do an inefficient one-variable substitution
| Just (tv, co'_body) <- splitForAllCo_maybe co'
= substCoWithTy (getCvInScope env) tv ty' co'_body
| otherwise = InstCo co' ty'
where
co' = opt_co4 env sym rep r co
ty' = substTy env ty
opt_co4 env sym _ r (SubCo co)
= ASSERT( r == Representational )
opt_co4 env sym True Nominal co
-- XXX: We could add another field to CoAxiomRule that
-- would allow us to do custom simplifications.
opt_co4 env sym rep r (AxiomRuleCo co ts cs)
= ASSERT( r == coaxrRole co )
wrapRole rep r $
wrapSym sym $
AxiomRuleCo co (map (substTy env) ts)
(zipWith (opt_co2 env False) (coaxrAsmpRoles co) cs)
-------------
-- | Optimize a phantom coercion. The input coercion may not necessarily
-- be a phantom, but the output sure will be.
opt_phantom :: CvSubst -> SymFlag -> Coercion -> NormalCo
opt_phantom env sym co
= if sym
then opt_univ env (fsLit "opt_phantom") Phantom ty2 ty1
else opt_univ env (fsLit "opt_phantom") Phantom ty1 ty2
where
Pair ty1 ty2 = coercionKind co
opt_univ :: CvSubst -> FastString -> Role -> Type -> Type -> Coercion
opt_univ env prov role oty1 oty2
| Just (tc1, tys1) <- splitTyConApp_maybe oty1
, Just (tc2, tys2) <- splitTyConApp_maybe oty2
, tc1 == tc2
= mkTyConAppCo role tc1 (zipWith3 (opt_univ env prov) (tyConRolesX role tc1) tys1 tys2)
| Just (l1, r1) <- splitAppTy_maybe oty1
, Just (l2, r2) <- splitAppTy_maybe oty2
, typeKind l1 `eqType` typeKind l2 -- kind(r1) == kind(r2) by consequence
= let role' = if role == Phantom then Phantom else Nominal in
-- role' is to comform to mkAppCo's precondition
mkAppCo (opt_univ env prov role l1 l2) (opt_univ env prov role' r1 r2)
| Just (tv1, ty1) <- splitForAllTy_maybe oty1
, Just (tv2, ty2) <- splitForAllTy_maybe oty2
, tyVarKind tv1 `eqType` tyVarKind tv2 -- rule out a weird unsafeCo
= case substTyVarBndr2 env tv1 tv2 of { (env1, env2, tv') ->
let ty1' = substTy env1 ty1
ty2' = substTy env2 ty2 in
mkForAllCo tv' (opt_univ (zapCvSubstEnv2 env1 env2) prov role ty1' ty2') }
| otherwise
= mkUnivCo prov role (substTy env oty1) (substTy env oty2)
-------------
-- NthCo must be handled separately, because it's the one case where we can't
-- tell quickly what the component coercion's role is from the containing
-- coercion. To avoid repeated coercionRole calls as opt_co1 calls opt_co2,
-- we just look for nested NthCo's, which can happen in practice.
opt_nth_co :: CvSubst -> SymFlag -> ReprFlag -> Role -> Coercion -> NormalCo
opt_nth_co env sym rep r = go []
where
go ns (NthCo n co) = go (n:ns) co
-- previous versions checked if the tycon is decomposable. This
-- is redundant, because a non-decomposable tycon under an NthCo
-- is entirely bogus. See docs/core-spec/core-spec.pdf.
go ns co
= opt_nths ns co
-- input coercion is *not* yet sym'd or opt'd
opt_nths [] co = opt_co4 env sym rep r co
opt_nths (n:ns) (TyConAppCo _ _ cos) = opt_nths ns (cos `getNth` n)
-- here, the co isn't a TyConAppCo, so we opt it, hoping to get
-- a TyConAppCo as output. We don't know the role, so we use
-- opt_co1. This is slightly annoying, because opt_co1 will call
-- coercionRole, but as long as we don't have a long chain of
-- NthCo's interspersed with some other coercion former, we should
-- be OK.
opt_nths ns co = opt_nths' ns (opt_co1 env sym co)
-- input coercion *is* sym'd and opt'd
opt_nths' [] co
= if rep && (r == Nominal)
-- propagate the SubCo:
then opt_co4 (zapCvSubstEnv env) False True r co
else co
opt_nths' (n:ns) (TyConAppCo _ _ cos) = opt_nths' ns (cos `getNth` n)
opt_nths' ns co = wrapRole rep r (mk_nths ns co)
mk_nths [] co = co
mk_nths (n:ns) co = mk_nths ns (mkNthCo n co)
-------------
opt_transList :: InScopeSet -> [NormalCo] -> [NormalCo] -> [NormalCo]
opt_transList is = zipWith (opt_trans is)
opt_trans :: InScopeSet -> NormalCo -> NormalCo -> NormalCo
opt_trans is co1 co2
| isReflCo co1 = co2
| otherwise = opt_trans1 is co1 co2
opt_trans1 :: InScopeSet -> NormalNonIdCo -> NormalCo -> NormalCo
-- First arg is not the identity
opt_trans1 is co1 co2
| isReflCo co2 = co1
| otherwise = opt_trans2 is co1 co2
opt_trans2 :: InScopeSet -> NormalNonIdCo -> NormalNonIdCo -> NormalCo
-- Neither arg is the identity
opt_trans2 is (TransCo co1a co1b) co2
-- Don't know whether the sub-coercions are the identity
= opt_trans is co1a (opt_trans is co1b co2)
opt_trans2 is co1 co2
| Just co <- opt_trans_rule is co1 co2
= co
opt_trans2 is co1 (TransCo co2a co2b)
| Just co1_2a <- opt_trans_rule is co1 co2a
= if isReflCo co1_2a
then co2b
else opt_trans1 is co1_2a co2b
opt_trans2 _ co1 co2
= mkTransCo co1 co2
------
-- Optimize coercions with a top-level use of transitivity.
opt_trans_rule :: InScopeSet -> NormalNonIdCo -> NormalNonIdCo -> Maybe NormalCo
-- Push transitivity through matching destructors
opt_trans_rule is in_co1@(NthCo d1 co1) in_co2@(NthCo d2 co2)
| d1 == d2
, co1 `compatible_co` co2
= fireTransRule "PushNth" in_co1 in_co2 $
mkNthCo d1 (opt_trans is co1 co2)
opt_trans_rule is in_co1@(LRCo d1 co1) in_co2@(LRCo d2 co2)
| d1 == d2
, co1 `compatible_co` co2
= fireTransRule "PushLR" in_co1 in_co2 $
mkLRCo d1 (opt_trans is co1 co2)
-- Push transitivity inside instantiation
opt_trans_rule is in_co1@(InstCo co1 ty1) in_co2@(InstCo co2 ty2)
| ty1 `eqType` ty2
, co1 `compatible_co` co2
= fireTransRule "TrPushInst" in_co1 in_co2 $
mkInstCo (opt_trans is co1 co2) ty1
-- Push transitivity down through matching top-level constructors.
opt_trans_rule is in_co1@(TyConAppCo r1 tc1 cos1) in_co2@(TyConAppCo r2 tc2 cos2)
| tc1 == tc2
= ASSERT( r1 == r2 )
fireTransRule "PushTyConApp" in_co1 in_co2 $
TyConAppCo r1 tc1 (opt_transList is cos1 cos2)
opt_trans_rule is in_co1@(AppCo co1a co1b) in_co2@(AppCo co2a co2b)
= fireTransRule "TrPushApp" in_co1 in_co2 $
mkAppCo (opt_trans is co1a co2a) (opt_trans is co1b co2b)
-- Eta rules
opt_trans_rule is co1@(TyConAppCo r tc cos1) co2
| Just cos2 <- etaTyConAppCo_maybe tc co2
= ASSERT( length cos1 == length cos2 )
fireTransRule "EtaCompL" co1 co2 $
TyConAppCo r tc (opt_transList is cos1 cos2)
opt_trans_rule is co1 co2@(TyConAppCo r tc cos2)
| Just cos1 <- etaTyConAppCo_maybe tc co1
= ASSERT( length cos1 == length cos2 )
fireTransRule "EtaCompR" co1 co2 $
TyConAppCo r tc (opt_transList is cos1 cos2)
opt_trans_rule is co1@(AppCo co1a co1b) co2
| Just (co2a,co2b) <- etaAppCo_maybe co2
= fireTransRule "EtaAppL" co1 co2 $
mkAppCo (opt_trans is co1a co2a) (opt_trans is co1b co2b)
opt_trans_rule is co1 co2@(AppCo co2a co2b)
| Just (co1a,co1b) <- etaAppCo_maybe co1
= fireTransRule "EtaAppR" co1 co2 $
mkAppCo (opt_trans is co1a co2a) (opt_trans is co1b co2b)
-- Push transitivity inside forall
opt_trans_rule is co1 co2
| Just (tv1,r1) <- splitForAllCo_maybe co1
, Just (tv2,r2) <- etaForAllCo_maybe co2
, let r2' = substCoWithTy is' tv2 (mkTyVarTy tv1) r2
is' = is `extendInScopeSet` tv1
= fireTransRule "EtaAllL" co1 co2 $
mkForAllCo tv1 (opt_trans2 is' r1 r2')
| Just (tv2,r2) <- splitForAllCo_maybe co2
, Just (tv1,r1) <- etaForAllCo_maybe co1
, let r1' = substCoWithTy is' tv1 (mkTyVarTy tv2) r1
is' = is `extendInScopeSet` tv2
= fireTransRule "EtaAllR" co1 co2 $
mkForAllCo tv1 (opt_trans2 is' r1' r2)
-- Push transitivity inside axioms
opt_trans_rule is co1 co2
-- See Note [Why call checkAxInstCo during optimisation]
-- TrPushSymAxR
| Just (sym, con, ind, cos1) <- co1_is_axiom_maybe
, Just cos2 <- matchAxiom sym con ind co2
, True <- sym
, let newAxInst = AxiomInstCo con ind (opt_transList is (map mkSymCo cos2) cos1)
, Nothing <- checkAxInstCo newAxInst
= fireTransRule "TrPushSymAxR" co1 co2 $ SymCo newAxInst
-- TrPushAxR
| Just (sym, con, ind, cos1) <- co1_is_axiom_maybe
, Just cos2 <- matchAxiom sym con ind co2
, False <- sym
, let newAxInst = AxiomInstCo con ind (opt_transList is cos1 cos2)
, Nothing <- checkAxInstCo newAxInst
= fireTransRule "TrPushAxR" co1 co2 newAxInst
-- TrPushSymAxL
| Just (sym, con, ind, cos2) <- co2_is_axiom_maybe
, Just cos1 <- matchAxiom (not sym) con ind co1
, True <- sym
, let newAxInst = AxiomInstCo con ind (opt_transList is cos2 (map mkSymCo cos1))
, Nothing <- checkAxInstCo newAxInst
= fireTransRule "TrPushSymAxL" co1 co2 $ SymCo newAxInst
-- TrPushAxL
| Just (sym, con, ind, cos2) <- co2_is_axiom_maybe
, Just cos1 <- matchAxiom (not sym) con ind co1
, False <- sym
, let newAxInst = AxiomInstCo con ind (opt_transList is cos1 cos2)
, Nothing <- checkAxInstCo newAxInst
= fireTransRule "TrPushAxL" co1 co2 newAxInst
-- TrPushAxSym/TrPushSymAx
| Just (sym1, con1, ind1, cos1) <- co1_is_axiom_maybe
, Just (sym2, con2, ind2, cos2) <- co2_is_axiom_maybe
, con1 == con2
, ind1 == ind2
, sym1 == not sym2
, let branch = coAxiomNthBranch con1 ind1
qtvs = coAxBranchTyVars branch
lhs = coAxNthLHS con1 ind1
rhs = coAxBranchRHS branch
pivot_tvs = exactTyVarsOfType (if sym2 then rhs else lhs)
, all (`elemVarSet` pivot_tvs) qtvs
= fireTransRule "TrPushAxSym" co1 co2 $
if sym2
then liftCoSubstWith role qtvs (opt_transList is cos1 (map mkSymCo cos2)) lhs -- TrPushAxSym
else liftCoSubstWith role qtvs (opt_transList is (map mkSymCo cos1) cos2) rhs -- TrPushSymAx
where
co1_is_axiom_maybe = isAxiom_maybe co1
co2_is_axiom_maybe = isAxiom_maybe co2
role = coercionRole co1 -- should be the same as coercionRole co2!
opt_trans_rule _ co1 co2 -- Identity rule
| (Pair ty1 _, r) <- coercionKindRole co1
, Pair _ ty2 <- coercionKind co2
, ty1 `eqType` ty2
= fireTransRule "RedTypeDirRefl" co1 co2 $
Refl r ty2
opt_trans_rule _ _ _ = Nothing
fireTransRule :: String -> Coercion -> Coercion -> Coercion -> Maybe Coercion
fireTransRule _rule _co1 _co2 res
= -- pprTrace ("Trans rule fired: " ++ _rule) (vcat [ppr _co1, ppr _co2, ppr res]) $
Just res
{-
Note [Conflict checking with AxiomInstCo]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider the following type family and axiom:
type family Equal (a :: k) (b :: k) :: Bool
type instance where
Equal a a = True
Equal a b = False
--
Equal :: forall k::BOX. k -> k -> Bool
axEqual :: { forall k::BOX. forall a::k. Equal k a a ~ True
; forall k::BOX. forall a::k. forall b::k. Equal k a b ~ False }
We wish to disallow (axEqual[1] <*> <Int> <Int). (Recall that the index is
0-based, so this is the second branch of the axiom.) The problem is that, on
the surface, it seems that (axEqual[1] <*> <Int> <Int>) :: (Equal * Int Int ~
False) and that all is OK. But, all is not OK: we want to use the first branch
of the axiom in this case, not the second. The problem is that the parameters
of the first branch can unify with the supplied coercions, thus meaning that
the first branch should be taken. See also Note [Branched instance checking]
in types/FamInstEnv.lhs.
Note [Why call checkAxInstCo during optimisation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It is possible that otherwise-good-looking optimisations meet with disaster
in the presence of axioms with multiple equations. Consider
type family Equal (a :: *) (b :: *) :: Bool where
Equal a a = True
Equal a b = False
type family Id (a :: *) :: * where
Id a = a
axEq :: { [a::*]. Equal a a ~ True
; [a::*, b::*]. Equal a b ~ False }
axId :: [a::*]. Id a ~ a
co1 = Equal (axId[0] Int) (axId[0] Bool)
:: Equal (Id Int) (Id Bool) ~ Equal Int Bool
co2 = axEq[1] <Int> <Bool>
:: Equal Int Bool ~ False
We wish to optimise (co1 ; co2). We end up in rule TrPushAxL, noting that
co2 is an axiom and that matchAxiom succeeds when looking at co1. But, what
happens when we push the coercions inside? We get
co3 = axEq[1] (axId[0] Int) (axId[0] Bool)
:: Equal (Id Int) (Id Bool) ~ False
which is bogus! This is because the type system isn't smart enough to know
that (Id Int) and (Id Bool) are Surely Apart, as they're headed by type
families. At the time of writing, I (Richard Eisenberg) couldn't think of
a way of detecting this any more efficient than just building the optimised
coercion and checking.
-}
-- | Check to make sure that an AxInstCo is internally consistent.
-- Returns the conflicting branch, if it exists
-- See Note [Conflict checking with AxiomInstCo]
checkAxInstCo :: Coercion -> Maybe CoAxBranch
-- defined here to avoid dependencies in Coercion
-- If you edit this function, you may need to update the GHC formalism
-- See Note [GHC Formalism] in CoreLint
checkAxInstCo (AxiomInstCo ax ind cos)
= let branch = coAxiomNthBranch ax ind
tvs = coAxBranchTyVars branch
incomps = coAxBranchIncomps branch
tys = map (pFst . coercionKind) cos
subst = zipOpenTvSubst tvs tys
target = Type.substTys subst (coAxBranchLHS branch)
in_scope = mkInScopeSet $
unionVarSets (map (tyVarsOfTypes . coAxBranchLHS) incomps)
flattened_target = flattenTys in_scope target in
check_no_conflict flattened_target incomps
where
check_no_conflict :: [Type] -> [CoAxBranch] -> Maybe CoAxBranch
check_no_conflict _ [] = Nothing
check_no_conflict flat (b@CoAxBranch { cab_lhs = lhs_incomp } : rest)
-- See Note [Apartness] in FamInstEnv
| SurelyApart <- tcUnifyTysFG instanceBindFun flat lhs_incomp
= check_no_conflict flat rest
| otherwise
= Just b
checkAxInstCo _ = Nothing
-----------
wrapSym :: SymFlag -> Coercion -> Coercion
wrapSym sym co | sym = SymCo co
| otherwise = co
-- | Conditionally set a role to be representational
wrapRole :: ReprFlag
-> Role -- ^ current role
-> Coercion -> Coercion
wrapRole False _ = id
wrapRole True current = downgradeRole Representational current
-- | If we require a representational role, return that. Otherwise,
-- return the "default" role provided.
chooseRole :: ReprFlag
-> Role -- ^ "default" role
-> Role
chooseRole True _ = Representational
chooseRole _ r = r
-----------
-- takes two tyvars and builds env'ts to map them to the same tyvar
substTyVarBndr2 :: CvSubst -> TyVar -> TyVar
-> (CvSubst, CvSubst, TyVar)
substTyVarBndr2 env tv1 tv2
= case substTyVarBndr env tv1 of
(env1, tv1') -> (env1, extendTvSubstAndInScope env tv2 (mkTyVarTy tv1'), tv1')
zapCvSubstEnv2 :: CvSubst -> CvSubst -> CvSubst
zapCvSubstEnv2 env1 env2 = mkCvSubst (is1 `unionInScope` is2) []
where is1 = getCvInScope env1
is2 = getCvInScope env2
-----------
isAxiom_maybe :: Coercion -> Maybe (Bool, CoAxiom Branched, Int, [Coercion])
isAxiom_maybe (SymCo co)
| Just (sym, con, ind, cos) <- isAxiom_maybe co
= Just (not sym, con, ind, cos)
isAxiom_maybe (AxiomInstCo con ind cos)
= Just (False, con, ind, cos)
isAxiom_maybe _ = Nothing
matchAxiom :: Bool -- True = match LHS, False = match RHS
-> CoAxiom br -> Int -> Coercion -> Maybe [Coercion]
-- If we succeed in matching, then *all the quantified type variables are bound*
-- E.g. if tvs = [a,b], lhs/rhs = [b], we'll fail
matchAxiom sym ax@(CoAxiom { co_ax_tc = tc }) ind co
= let (CoAxBranch { cab_tvs = qtvs
, cab_roles = roles
, cab_lhs = lhs
, cab_rhs = rhs }) = coAxiomNthBranch ax ind in
case liftCoMatch (mkVarSet qtvs) (if sym then (mkTyConApp tc lhs) else rhs) co of
Nothing -> Nothing
Just subst -> zipWithM (liftCoSubstTyVar subst) roles qtvs
-------------
compatible_co :: Coercion -> Coercion -> Bool
-- Check whether (co1 . co2) will be well-kinded
compatible_co co1 co2
= x1 `eqType` x2
where
Pair _ x1 = coercionKind co1
Pair x2 _ = coercionKind co2
-------------
etaForAllCo_maybe :: Coercion -> Maybe (TyVar, Coercion)
-- Try to make the coercion be of form (forall tv. co)
etaForAllCo_maybe co
| Just (tv, r) <- splitForAllCo_maybe co
= Just (tv, r)
| Pair ty1 ty2 <- coercionKind co
, Just (tv1, _) <- splitForAllTy_maybe ty1
, Just (tv2, _) <- splitForAllTy_maybe ty2
, tyVarKind tv1 `eqKind` tyVarKind tv2
= Just (tv1, mkInstCo co (mkTyVarTy tv1))
| otherwise
= Nothing
etaAppCo_maybe :: Coercion -> Maybe (Coercion,Coercion)
-- If possible, split a coercion
-- g :: t1a t1b ~ t2a t2b
-- into a pair of coercions (left g, right g)
etaAppCo_maybe co
| Just (co1,co2) <- splitAppCo_maybe co
= Just (co1,co2)
| (Pair ty1 ty2, Nominal) <- coercionKindRole co
, Just (_,t1) <- splitAppTy_maybe ty1
, Just (_,t2) <- splitAppTy_maybe ty2
, typeKind t1 `eqType` typeKind t2 -- Note [Eta for AppCo]
= Just (LRCo CLeft co, LRCo CRight co)
| otherwise
= Nothing
etaTyConAppCo_maybe :: TyCon -> Coercion -> Maybe [Coercion]
-- If possible, split a coercion
-- g :: T s1 .. sn ~ T t1 .. tn
-- into [ Nth 0 g :: s1~t1, ..., Nth (n-1) g :: sn~tn ]
etaTyConAppCo_maybe tc (TyConAppCo _ tc2 cos2)
= ASSERT( tc == tc2 ) Just cos2
etaTyConAppCo_maybe tc co
| isDecomposableTyCon tc
, Pair ty1 ty2 <- coercionKind co
, Just (tc1, tys1) <- splitTyConApp_maybe ty1
, Just (tc2, tys2) <- splitTyConApp_maybe ty2
, tc1 == tc2
, let n = length tys1
= ASSERT( tc == tc1 )
ASSERT( n == length tys2 )
Just (decomposeCo n co)
-- NB: n might be <> tyConArity tc
-- e.g. data family T a :: * -> *
-- g :: T a b ~ T c d
| otherwise
= Nothing
{-
Note [Eta for AppCo]
~~~~~~~~~~~~~~~~~~~~
Suppose we have
g :: s1 t1 ~ s2 t2
Then we can't necessarily make
left g :: s1 ~ s2
right g :: t1 ~ t2
because it's possible that
s1 :: * -> * t1 :: *
s2 :: (*->*) -> * t2 :: * -> *
and in that case (left g) does not have the same
kind on either side.
It's enough to check that
kind t1 = kind t2
because if g is well-kinded then
kind (s1 t2) = kind (s2 t2)
and these two imply
kind s1 = kind s2
-}
| pparkkin/eta | compiler/ETA/Types/OptCoercion.hs | bsd-3-clause | 27,459 | 0 | 15 | 6,659 | 6,405 | 3,259 | 3,146 | -1 | -1 |
{-
Copyright (C) 2007-2015 John MacFarlane <jgm@berkeley.edu>
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.Pandoc.Writers.Man
Copyright : Copyright (C) 2007-2015 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <jgm@berkeley.edu>
Stability : alpha
Portability : portable
Conversion of 'Pandoc' documents to groff man page format.
-}
module Text.Pandoc.Writers.Man ( writeMan) where
import Text.Pandoc.Definition
import Text.Pandoc.Templates
import Text.Pandoc.Shared
import Text.Pandoc.Writers.Shared
import Text.Pandoc.Options
import Text.Pandoc.Readers.TeXMath
import Text.Printf ( printf )
import Data.List ( stripPrefix, intersperse, intercalate )
import Data.Maybe (fromMaybe)
import Text.Pandoc.Pretty
import Text.Pandoc.Builder (deleteMeta)
import Control.Monad.State
import Data.Char ( isDigit )
type Notes = [[Block]]
data WriterState = WriterState { stNotes :: Notes
, stHasTables :: Bool }
-- | Convert Pandoc to Man.
writeMan :: WriterOptions -> Pandoc -> String
writeMan opts document = evalState (pandocToMan opts document) (WriterState [] False)
-- | Return groff man representation of document.
pandocToMan :: WriterOptions -> Pandoc -> State WriterState String
pandocToMan opts (Pandoc meta blocks) = do
let colwidth = if writerWrapText opts == WrapAuto
then Just $ writerColumns opts
else Nothing
let render' = render colwidth
titleText <- inlineListToMan opts $ docTitle meta
let title' = render' titleText
let setFieldsFromTitle =
case break (== ' ') title' of
(cmdName, rest) -> case reverse cmdName of
(')':d:'(':xs) | isDigit d ->
defField "title" (reverse xs) .
defField "section" [d] .
case splitBy (=='|') rest of
(ft:hds) ->
defField "footer" (trim ft) .
defField "header"
(trim $ concat hds)
[] -> id
_ -> defField "title" title'
metadata <- metaToJSON opts
(fmap (render colwidth) . blockListToMan opts)
(fmap (render colwidth) . inlineListToMan opts)
$ deleteMeta "title" meta
body <- blockListToMan opts blocks
notes <- liftM stNotes get
notes' <- notesToMan opts (reverse notes)
let main = render' $ body $$ notes' $$ text ""
hasTables <- liftM stHasTables get
let context = defField "body" main
$ setFieldsFromTitle
$ defField "has-tables" hasTables
$ defField "hyphenate" True
$ defField "pandoc-version" pandocVersion
$ metadata
if writerStandalone opts
then return $ renderTemplate' (writerTemplate opts) context
else return main
-- | Return man representation of notes.
notesToMan :: WriterOptions -> [[Block]] -> State WriterState Doc
notesToMan opts notes =
if null notes
then return empty
else mapM (\(num, note) -> noteToMan opts num note) (zip [1..] notes) >>=
return . (text ".SH NOTES" $$) . vcat
-- | Return man representation of a note.
noteToMan :: WriterOptions -> Int -> [Block] -> State WriterState Doc
noteToMan opts num note = do
contents <- blockListToMan opts note
let marker = cr <> text ".SS " <> brackets (text (show num))
return $ marker $$ contents
-- | Association list of characters to escape.
manEscapes :: [(Char, String)]
manEscapes = [ ('\160', "\\ ")
, ('\'', "\\[aq]")
, ('’', "'")
, ('\x2014', "\\[em]")
, ('\x2013', "\\[en]")
, ('\x2026', "\\&...")
] ++ backslashEscapes "-@\\"
-- | Escape special characters for Man.
escapeString :: String -> String
escapeString = escapeStringUsing manEscapes
-- | Escape a literal (code) section for Man.
escapeCode :: String -> String
escapeCode = concat . intersperse "\n" . map escapeLine . lines where
escapeLine codeline =
case escapeStringUsing (manEscapes ++ backslashEscapes "\t ") codeline of
a@('.':_) -> "\\&" ++ a
b -> b
-- We split inline lists into sentences, and print one sentence per
-- line. groff/troff treats the line-ending period differently.
-- See http://code.google.com/p/pandoc/issues/detail?id=148.
-- | Returns the first sentence in a list of inlines, and the rest.
breakSentence :: [Inline] -> ([Inline], [Inline])
breakSentence [] = ([],[])
breakSentence xs =
let isSentenceEndInline (Str ys@(_:_)) | last ys == '.' = True
isSentenceEndInline (Str ys@(_:_)) | last ys == '?' = True
isSentenceEndInline (LineBreak) = True
isSentenceEndInline _ = False
(as, bs) = break isSentenceEndInline xs
in case bs of
[] -> (as, [])
[c] -> (as ++ [c], [])
(c:Space:cs) -> (as ++ [c], cs)
(c:SoftBreak:cs) -> (as ++ [c], cs)
(Str ".":Str (')':ys):cs) -> (as ++ [Str ".", Str (')':ys)], cs)
(x@(Str ('.':')':_)):cs) -> (as ++ [x], cs)
(LineBreak:x@(Str ('.':_)):cs) -> (as ++[LineBreak], x:cs)
(c:cs) -> (as ++ [c] ++ ds, es)
where (ds, es) = breakSentence cs
-- | Split a list of inlines into sentences.
splitSentences :: [Inline] -> [[Inline]]
splitSentences xs =
let (sent, rest) = breakSentence xs
in if null rest then [sent] else sent : splitSentences rest
-- | Convert Pandoc block element to man.
blockToMan :: WriterOptions -- ^ Options
-> Block -- ^ Block element
-> State WriterState Doc
blockToMan _ Null = return empty
blockToMan opts (Div _ bs) = blockListToMan opts bs
blockToMan opts (Plain inlines) =
liftM vcat $ mapM (inlineListToMan opts) $ splitSentences inlines
blockToMan opts (Para inlines) = do
contents <- liftM vcat $ mapM (inlineListToMan opts) $
splitSentences inlines
return $ text ".PP" $$ contents
blockToMan _ (RawBlock f str)
| f == Format "man" = return $ text str
| otherwise = return empty
blockToMan _ HorizontalRule = return $ text ".PP" $$ text " * * * * *"
blockToMan opts (Header level _ inlines) = do
contents <- inlineListToMan opts inlines
let heading = case level of
1 -> ".SH "
_ -> ".SS "
return $ text heading <> contents
blockToMan _ (CodeBlock _ str) = return $
text ".IP" $$
text ".nf" $$
text "\\f[C]" $$
text (escapeCode str) $$
text "\\f[]" $$
text ".fi"
blockToMan opts (BlockQuote blocks) = do
contents <- blockListToMan opts blocks
return $ text ".RS" $$ contents $$ text ".RE"
blockToMan opts (Table caption alignments widths headers rows) =
let aligncode AlignLeft = "l"
aligncode AlignRight = "r"
aligncode AlignCenter = "c"
aligncode AlignDefault = "l"
in do
caption' <- inlineListToMan opts caption
modify $ \st -> st{ stHasTables = True }
let iwidths = if all (== 0) widths
then repeat ""
else map (printf "w(%0.1fn)" . (70 *)) widths
-- 78n default width - 8n indent = 70n
let coldescriptions = text $ intercalate " "
(zipWith (\align width -> aligncode align ++ width)
alignments iwidths) ++ "."
colheadings <- mapM (blockListToMan opts) headers
let makeRow cols = text "T{" $$
(vcat $ intersperse (text "T}@T{") cols) $$
text "T}"
let colheadings' = if all null headers
then empty
else makeRow colheadings $$ char '_'
body <- mapM (\row -> do
cols <- mapM (blockListToMan opts) row
return $ makeRow cols) rows
return $ text ".PP" $$ caption' $$
text ".TS" $$ text "tab(@);" $$ coldescriptions $$
colheadings' $$ vcat body $$ text ".TE"
blockToMan opts (BulletList items) = do
contents <- mapM (bulletListItemToMan opts) items
return (vcat contents)
blockToMan opts (OrderedList attribs items) = do
let markers = take (length items) $ orderedListMarkers attribs
let indent = 1 + (maximum $ map length markers)
contents <- mapM (\(num, item) -> orderedListItemToMan opts num indent item) $
zip markers items
return (vcat contents)
blockToMan opts (DefinitionList items) = do
contents <- mapM (definitionListItemToMan opts) items
return (vcat contents)
-- | Convert bullet list item (list of blocks) to man.
bulletListItemToMan :: WriterOptions -> [Block] -> State WriterState Doc
bulletListItemToMan _ [] = return empty
bulletListItemToMan opts ((Para first):rest) =
bulletListItemToMan opts ((Plain first):rest)
bulletListItemToMan opts ((Plain first):rest) = do
first' <- blockToMan opts (Plain first)
rest' <- blockListToMan opts rest
let first'' = text ".IP \\[bu] 2" $$ first'
let rest'' = if null rest
then empty
else text ".RS 2" $$ rest' $$ text ".RE"
return (first'' $$ rest'')
bulletListItemToMan opts (first:rest) = do
first' <- blockToMan opts first
rest' <- blockListToMan opts rest
return $ text "\\[bu] .RS 2" $$ first' $$ rest' $$ text ".RE"
-- | Convert ordered list item (a list of blocks) to man.
orderedListItemToMan :: WriterOptions -- ^ options
-> String -- ^ order marker for list item
-> Int -- ^ number of spaces to indent
-> [Block] -- ^ list item (list of blocks)
-> State WriterState Doc
orderedListItemToMan _ _ _ [] = return empty
orderedListItemToMan opts num indent ((Para first):rest) =
orderedListItemToMan opts num indent ((Plain first):rest)
orderedListItemToMan opts num indent (first:rest) = do
first' <- blockToMan opts first
rest' <- blockListToMan opts rest
let num' = printf ("%" ++ show (indent - 1) ++ "s") num
let first'' = text (".IP \"" ++ num' ++ "\" " ++ show indent) $$ first'
let rest'' = if null rest
then empty
else text ".RS 4" $$ rest' $$ text ".RE"
return $ first'' $$ rest''
-- | Convert definition list item (label, list of blocks) to man.
definitionListItemToMan :: WriterOptions
-> ([Inline],[[Block]])
-> State WriterState Doc
definitionListItemToMan opts (label, defs) = do
labelText <- inlineListToMan opts label
contents <- if null defs
then return empty
else liftM vcat $ forM defs $ \blocks -> do
let (first, rest) = case blocks of
((Para x):y) -> (Plain x,y)
(x:y) -> (x,y)
[] -> error "blocks is null"
rest' <- liftM vcat $
mapM (\item -> blockToMan opts item) rest
first' <- blockToMan opts first
return $ first' $$ text ".RS" $$ rest' $$ text ".RE"
return $ text ".TP" $$ nowrap (text ".B " <> labelText) $$ contents
-- | Convert list of Pandoc block elements to man.
blockListToMan :: WriterOptions -- ^ Options
-> [Block] -- ^ List of block elements
-> State WriterState Doc
blockListToMan opts blocks =
mapM (blockToMan opts) blocks >>= (return . vcat)
-- | Convert list of Pandoc inline elements to man.
inlineListToMan :: WriterOptions -> [Inline] -> State WriterState Doc
-- if list starts with ., insert a zero-width character \& so it
-- won't be interpreted as markup if it falls at the beginning of a line.
inlineListToMan opts lst@(Str ('.':_) : _) = mapM (inlineToMan opts) lst >>=
(return . (text "\\&" <>) . hcat)
inlineListToMan opts lst = mapM (inlineToMan opts) lst >>= (return . hcat)
-- | Convert Pandoc inline element to man.
inlineToMan :: WriterOptions -> Inline -> State WriterState Doc
inlineToMan opts (Span _ ils) = inlineListToMan opts ils
inlineToMan opts (Emph lst) = do
contents <- inlineListToMan opts lst
return $ text "\\f[I]" <> contents <> text "\\f[]"
inlineToMan opts (Strong lst) = do
contents <- inlineListToMan opts lst
return $ text "\\f[B]" <> contents <> text "\\f[]"
inlineToMan opts (Strikeout lst) = do
contents <- inlineListToMan opts lst
return $ text "[STRIKEOUT:" <> contents <> char ']'
inlineToMan opts (Superscript lst) = do
contents <- inlineListToMan opts lst
return $ char '^' <> contents <> char '^'
inlineToMan opts (Subscript lst) = do
contents <- inlineListToMan opts lst
return $ char '~' <> contents <> char '~'
inlineToMan opts (SmallCaps lst) = inlineListToMan opts lst -- not supported
inlineToMan opts (Quoted SingleQuote lst) = do
contents <- inlineListToMan opts lst
return $ char '`' <> contents <> char '\''
inlineToMan opts (Quoted DoubleQuote lst) = do
contents <- inlineListToMan opts lst
return $ text "\\[lq]" <> contents <> text "\\[rq]"
inlineToMan opts (Cite _ lst) =
inlineListToMan opts lst
inlineToMan _ (Code _ str) =
return $ text $ "\\f[C]" ++ escapeCode str ++ "\\f[]"
inlineToMan _ (Str str) = return $ text $ escapeString str
inlineToMan opts (Math InlineMath str) =
inlineListToMan opts $ texMathToInlines InlineMath str
inlineToMan opts (Math DisplayMath str) = do
contents <- inlineListToMan opts $ texMathToInlines DisplayMath str
return $ cr <> text ".RS" $$ contents $$ text ".RE"
inlineToMan _ (RawInline f str)
| f == Format "man" = return $ text str
| otherwise = return empty
inlineToMan _ (LineBreak) = return $
cr <> text ".PD 0" $$ text ".P" $$ text ".PD" <> cr
inlineToMan _ SoftBreak = return space
inlineToMan _ Space = return space
inlineToMan opts (Link _ txt (src, _)) = do
linktext <- inlineListToMan opts txt
let srcSuffix = fromMaybe src (stripPrefix "mailto:" src)
return $ case txt of
[Str s]
| escapeURI s == srcSuffix ->
char '<' <> text srcSuffix <> char '>'
_ -> linktext <> text " (" <> text src <> char ')'
inlineToMan opts (Image attr alternate (source, tit)) = do
let txt = if (null alternate) || (alternate == [Str ""]) ||
(alternate == [Str source]) -- to prevent autolinks
then [Str "image"]
else alternate
linkPart <- inlineToMan opts (Link attr txt (source, tit))
return $ char '[' <> text "IMAGE: " <> linkPart <> char ']'
inlineToMan _ (Note contents) = do
-- add to notes in state
modify $ \st -> st{ stNotes = contents : stNotes st }
notes <- liftM stNotes get
let ref = show $ (length notes)
return $ char '[' <> text ref <> char ']'
| janschulz/pandoc | src/Text/Pandoc/Writers/Man.hs | gpl-2.0 | 15,679 | 278 | 20 | 4,473 | 4,504 | 2,338 | 2,166 | 297 | 11 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
import System.Environment (getArgs)
import qualified Data.Aeson as J
import qualified Data.Yaml as Y
import Control.Monad (when)
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import Control.Applicative ((<$>))
main :: IO ()
main = do
args <- getArgs
when (length args > 2) $ error "Usage: json2yaml [in] [out]"
let (input:output:_) = args ++ repeat "-"
mval <- J.decode <$>
case input of
"-" -> L.getContents
_ -> L.readFile input
case mval of
Nothing -> error "Invalid input JSON"
Just val -> do
case output of
"-" -> S.putStr $ Y.encode (val :: Y.Value)
_ -> Y.encodeFile output val
| snoyberg/json2yaml | json2yaml.hs | bsd-2-clause | 807 | 0 | 18 | 221 | 247 | 131 | 116 | 24 | 4 |
<?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="az-AZ">
<title>Server-Sent Events Add-on</title>
<maps>
<homeID>sse.introduction</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>İndeks</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Axtar</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/sse/src/main/javahelp/org/zaproxy/zap/extension/sse/resources/help_az_AZ/helpset_az_AZ.hs | apache-2.0 | 984 | 82 | 54 | 157 | 402 | 212 | 190 | -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="ar-SA">
<title>Revisit | 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> | thc202/zap-extensions | addOns/revisit/src/main/javahelp/org/zaproxy/zap/extension/revisit/resources/help_ar_SA/helpset_ar_SA.hs | apache-2.0 | 968 | 83 | 52 | 158 | 394 | 208 | 186 | -1 | -1 |
module Renaming.B1 (myFringe) where
import Renaming.D1 hiding (sumSquares)
import qualified Renaming.D1
instance SameOrNot Float where
isSame a b = a ==b
isNotSame a b = a /=b
myFringe:: Tree a -> [a]
myFringe (Leaf x ) = [x]
myFringe (Branch left right) = myFringe right
sumSquares (x:xs)= x^2 + sumSquares xs
sumSquares [] =0
| SAdams601/HaRe | test/testdata/Renaming/B1.hs | bsd-3-clause | 344 | 0 | 7 | 70 | 151 | 80 | 71 | 11 | 1 |
module ImpurePlugin where
import GhcPlugins
import Common
plugin :: Plugin
plugin = defaultPlugin {
installCoreToDos = install,
pluginRecompile = impurePlugin
}
| sdiehl/ghc | testsuite/tests/plugins/plugin-recomp/ImpurePlugin.hs | bsd-3-clause | 173 | 0 | 6 | 33 | 34 | 22 | 12 | 7 | 1 |
module CError (module Foreign.C.Error) where
import Foreign.C.Error
| alekar/hugs | packages/haskell98/CError.hs | bsd-3-clause | 68 | 0 | 5 | 7 | 19 | 13 | 6 | 2 | 0 |
{-# LANGUAGE TypeApplications #-}
module T13902 where
f :: a -> a
f x = x
g :: Int
g = f @Int 42 5
| ezyang/ghc | testsuite/tests/typecheck/should_fail/T13902.hs | bsd-3-clause | 101 | 0 | 6 | 27 | 41 | 23 | 18 | 6 | 1 |
{-# LANGUAGE Arrows #-}
module ShouldCompile where
import Control.Arrow
f :: Arrow a => a (Int,Int) Int
f = proc (x,y) -> let z = x*y in returnA -< y+z
| wxwxwwxxx/ghc | testsuite/tests/arrows/should_compile/arrowlet1.hs | bsd-3-clause | 155 | 1 | 10 | 33 | 74 | 40 | 34 | 5 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TupleSections #-}
{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}
{-# OPTIONS_HADDOCK hide, not-home #-}
module Web.Rep.Page
( -- $page
Page (..),
PageConfig (..),
defaultPageConfig,
Concerns (..),
suffixes,
concernNames,
PageConcerns (..),
PageStructure (..),
PageRender (..),
-- $css
Css,
RepCss (..),
renderCss,
renderRepCss,
-- $js
JS (..),
RepJs (..),
onLoad,
renderRepJs,
parseJs,
renderJs,
)
where
import qualified Clay
import Clay (Css)
import Control.Lens
import Data.Generics.Labels ()
import GHC.Show (show)
import Language.JavaScript.Parser
import Language.JavaScript.Parser.AST
import Language.JavaScript.Process.Minify
import Lucid
import NumHask.Prelude hiding (show)
import Text.InterpolatedString.Perl6
-- | Components of a web page.
--
-- A web page can take many forms but still have the same underlying representation. For example, CSS can be linked to in a separate file, or can be inline within html, but still be the same css and have the same expected external effect. A Page represents the practical components of what makes up a static snapshot of a web page.
data Page
= Page
{ -- | css library links
libsCss :: [Html ()],
-- | javascript library links
libsJs :: [Html ()],
-- | css
cssBody :: RepCss,
-- | javascript with global scope
jsGlobal :: RepJs,
-- | javascript included within the onLoad function
jsOnLoad :: RepJs,
-- | html within the header
htmlHeader :: Html (),
-- | body html
htmlBody :: Html ()
}
deriving (Show, Generic)
instance Semigroup Page where
(<>) p0 p1 =
Page
(p0 ^. #libsCss <> p1 ^. #libsCss)
(p0 ^. #libsJs <> p1 ^. #libsJs)
(p0 ^. #cssBody <> p1 ^. #cssBody)
(p0 ^. #jsGlobal <> p1 ^. #jsGlobal)
(p0 ^. #jsOnLoad <> p1 ^. #jsOnLoad)
(p0 ^. #htmlHeader <> p1 ^. #htmlHeader)
(p0 ^. #htmlBody <> p1 ^. #htmlBody)
instance Monoid Page where
mempty = Page [] [] mempty mempty mempty mempty mempty
mappend = (<>)
-- | A web page typically is composed of some css, javascript and html.
--
-- 'Concerns' abstracts this structural feature of a web page.
data Concerns a
= Concerns
{ cssConcern :: a,
jsConcern :: a,
htmlConcern :: a
}
deriving (Eq, Show, Foldable, Traversable, Generic)
instance Functor Concerns where
fmap f (Concerns c j h) = Concerns (f c) (f j) (f h)
instance Applicative Concerns where
pure a = Concerns a a a
Concerns f g h <*> Concerns a b c = Concerns (f a) (g b) (h c)
-- | The common file suffixes of the three concerns.
suffixes :: Concerns FilePath
suffixes = Concerns ".css" ".js" ".html"
-- | Create filenames for each Concern element.
concernNames :: FilePath -> FilePath -> Concerns FilePath
concernNames dir stem =
(\x -> dir <> stem <> x) <$> suffixes
-- | Is the rendering to include all 'Concerns' (typically in a html file) or be separated (tyypically into separate files and linked in the html file)?
data PageConcerns
= Inline
| Separated
deriving (Show, Eq, Generic)
-- | Various ways that a Html file can be structured.
data PageStructure
= HeaderBody
| Headless
| Snippet
| Svg
deriving (Show, Eq, Generic)
-- | Post-processing of page concerns
data PageRender
= Pretty
| Minified
| NoPost
deriving (Show, Eq, Generic)
-- | Configuration options when rendering a 'Page'.
data PageConfig
= PageConfig
{ concerns :: PageConcerns,
structure :: PageStructure,
pageRender :: PageRender,
filenames :: Concerns FilePath,
localdirs :: [FilePath]
}
deriving (Show, Eq, Generic)
-- | Default configuration is inline ecma and css, separate html header and body, minified code, with the suggested filename prefix.
defaultPageConfig :: FilePath -> PageConfig
defaultPageConfig stem =
PageConfig
Inline
HeaderBody
Minified
((stem <>) <$> suffixes)
[]
-- | Unifies css as either a 'Clay.Css' or as Text.
data RepCss = RepCss Clay.Css | RepCssText Text deriving (Generic)
instance Show RepCss where
show (RepCss css) = unpack . renderCss $ css
show (RepCssText txt) = unpack txt
instance Semigroup RepCss where
(<>) (RepCss css) (RepCss css') = RepCss (css <> css')
(<>) (RepCssText css) (RepCssText css') = RepCssText (css <> css')
(<>) (RepCss css) (RepCssText css') =
RepCssText (renderCss css <> css')
(<>) (RepCssText css) (RepCss css') =
RepCssText (css <> renderCss css')
instance Monoid RepCss where
mempty = RepCssText mempty
mappend = (<>)
-- | Render 'RepCss' as text.
renderRepCss :: PageRender -> RepCss -> Text
renderRepCss Minified (RepCss css) = toStrict $ Clay.renderWith Clay.compact [] css
renderRepCss _ (RepCss css) = toStrict $ Clay.render css
renderRepCss _ (RepCssText css) = css
-- | Render 'Css' as text.
renderCss :: Css -> Text
renderCss = toStrict . Clay.render
-- | wrapper for `JSAST`
newtype JS = JS {unJS :: JSAST} deriving (Show, Eq, Generic)
instance Semigroup JS where
(<>) (JS (JSAstProgram ss ann)) (JS (JSAstProgram ss' _)) =
JS $ JSAstProgram (ss <> ss') ann
(<>) (JS (JSAstProgram ss ann)) (JS (JSAstStatement s _)) =
JS $ JSAstProgram (ss <> [s]) ann
(<>) (JS (JSAstProgram ss ann)) (JS (JSAstExpression e ann')) =
JS $ JSAstProgram (ss <> [JSExpressionStatement e (JSSemi ann')]) ann
(<>) (JS (JSAstProgram ss ann)) (JS (JSAstLiteral e ann')) =
JS $ JSAstProgram (ss <> [JSExpressionStatement e (JSSemi ann')]) ann
(<>) (JS (JSAstStatement s ann)) (JS (JSAstProgram ss _)) =
JS $ JSAstProgram (s : ss) ann
(<>) (JS (JSAstStatement s ann)) (JS (JSAstStatement s' _)) =
JS $ JSAstProgram [s, s'] ann
(<>) (JS (JSAstStatement s ann)) (JS (JSAstExpression e ann')) =
JS $ JSAstProgram [s, JSExpressionStatement e (JSSemi ann')] ann
(<>) (JS (JSAstStatement s ann)) (JS (JSAstLiteral e ann')) =
JS $ JSAstProgram [s, JSExpressionStatement e (JSSemi ann')] ann
(<>) (JS (JSAstExpression e ann)) (JS (JSAstProgram ss _)) =
JS $ JSAstProgram (JSExpressionStatement e (JSSemi ann) : ss) ann
(<>) (JS (JSAstExpression e ann)) (JS (JSAstStatement s' _)) =
JS $ JSAstProgram [JSExpressionStatement e (JSSemi ann), s'] ann
(<>) (JS (JSAstExpression e ann)) (JS (JSAstExpression e' ann')) =
JS $ JSAstProgram [JSExpressionStatement e (JSSemi ann), JSExpressionStatement e' (JSSemi ann')] ann
(<>) (JS (JSAstExpression e ann)) (JS (JSAstLiteral e' ann')) =
JS $ JSAstProgram [JSExpressionStatement e (JSSemi ann), JSExpressionStatement e' (JSSemi ann')] ann
(<>) (JS (JSAstLiteral e ann)) (JS (JSAstProgram ss _)) =
JS $ JSAstProgram (JSExpressionStatement e (JSSemi ann) : ss) ann
(<>) (JS (JSAstLiteral e ann)) (JS (JSAstStatement s' _)) =
JS $ JSAstProgram [JSExpressionStatement e (JSSemi ann), s'] ann
(<>) (JS (JSAstLiteral e ann)) (JS (JSAstExpression e' ann')) =
JS $ JSAstProgram [JSExpressionStatement e (JSSemi ann), JSExpressionStatement e' (JSSemi ann')] ann
(<>) (JS (JSAstLiteral e ann)) (JS (JSAstLiteral e' ann')) =
JS $ JSAstProgram [JSExpressionStatement e (JSSemi ann), JSExpressionStatement e' (JSSemi ann')] ann
instance Monoid JS where
mempty = JS $ JSAstProgram [] (JSAnnot (TokenPn 0 0 0) [])
mappend = (<>)
-- | Unifies javascript as 'JSStatement' and script as 'Text'.
data RepJs = RepJs JS | RepJsText Text deriving (Eq, Show, Generic)
instance Semigroup RepJs where
(<>) (RepJs js) (RepJs js') = RepJs (js <> js')
(<>) (RepJsText js) (RepJsText js') = RepJsText (js <> js')
(<>) (RepJs js) (RepJsText js') =
RepJsText (toStrict (renderToText $ unJS js) <> js')
(<>) (RepJsText js) (RepJs js') =
RepJsText (js <> toStrict (renderToText $ unJS js'))
instance Monoid RepJs where
mempty = RepJs mempty
mappend = (<>)
-- | Wrap js in standard DOM window loader.
onLoad :: RepJs -> RepJs
onLoad (RepJs js) = RepJs $ onLoadStatements [toStatement js]
onLoad (RepJsText js) = RepJsText $ onLoadText js
toStatement :: JS -> JSStatement
toStatement (JS (JSAstProgram ss ann)) = JSStatementBlock JSNoAnnot ss JSNoAnnot (JSSemi ann)
toStatement (JS (JSAstStatement s _)) = s
toStatement (JS (JSAstExpression e ann')) = JSExpressionStatement e (JSSemi ann')
toStatement (JS (JSAstLiteral e ann')) = JSExpressionStatement e (JSSemi ann')
onLoadStatements :: [JSStatement] -> JS
onLoadStatements js = JS $ JSAstProgram [JSAssignStatement (JSMemberDot (JSIdentifier JSNoAnnot "window") JSNoAnnot (JSIdentifier JSNoAnnot "onload")) (JSAssign JSNoAnnot) (JSFunctionExpression JSNoAnnot JSIdentNone JSNoAnnot JSLNil JSNoAnnot (JSBlock JSNoAnnot js JSNoAnnot)) JSSemiAuto] JSNoAnnot
onLoadText :: Text -> Text
onLoadText t = [qc| window.onload=function()\{{t}};|]
-- | Convert 'Text' to 'JS', throwing an error on incorrectness.
parseJs :: Text -> JS
parseJs = JS . readJs . unpack
-- | Render 'JS' as 'Text'.
renderJs :: JS -> Text
renderJs = toStrict . renderToText . unJS
-- | Render 'RepJs' as 'Text'.
renderRepJs :: PageRender -> RepJs -> Text
renderRepJs _ (RepJsText js) = js
renderRepJs Minified (RepJs js) = toStrict . renderToText . minifyJS . unJS $ js
renderRepJs Pretty (RepJs js) = toStrict . renderToText . unJS $ js
| tonyday567/lucid-page | src/Web/Rep/Page.hs | mit | 9,573 | 0 | 13 | 1,992 | 3,091 | 1,662 | 1,429 | 200 | 1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.HTMLAppletElement
(js_setAlign, setAlign, js_getAlign, getAlign, js_setAlt, setAlt,
js_getAlt, getAlt, js_setArchive, setArchive, js_getArchive,
getArchive, js_setCode, setCode, js_getCode, getCode,
js_setCodeBase, setCodeBase, js_getCodeBase, getCodeBase,
js_setHeight, setHeight, js_getHeight, getHeight, js_setHspace,
setHspace, js_getHspace, getHspace, js_setName, setName,
js_getName, getName, js_setObject, setObject, js_getObject,
getObject, js_setVspace, setVspace, js_getVspace, getVspace,
js_setWidth, setWidth, js_getWidth, getWidth, HTMLAppletElement,
castToHTMLAppletElement, gTypeHTMLAppletElement)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSRef(..), JSString, castRef)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSRef(..), FromJSRef(..))
import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.Enums
foreign import javascript unsafe "$1[\"align\"] = $2;" js_setAlign
:: JSRef HTMLAppletElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAppletElement.align Mozilla HTMLAppletElement.align documentation>
setAlign ::
(MonadIO m, ToJSString val) => HTMLAppletElement -> val -> m ()
setAlign self val
= liftIO (js_setAlign (unHTMLAppletElement self) (toJSString val))
foreign import javascript unsafe "$1[\"align\"]" js_getAlign ::
JSRef HTMLAppletElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAppletElement.align Mozilla HTMLAppletElement.align documentation>
getAlign ::
(MonadIO m, FromJSString result) => HTMLAppletElement -> m result
getAlign self
= liftIO
(fromJSString <$> (js_getAlign (unHTMLAppletElement self)))
foreign import javascript unsafe "$1[\"alt\"] = $2;" js_setAlt ::
JSRef HTMLAppletElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAppletElement.alt Mozilla HTMLAppletElement.alt documentation>
setAlt ::
(MonadIO m, ToJSString val) => HTMLAppletElement -> val -> m ()
setAlt self val
= liftIO (js_setAlt (unHTMLAppletElement self) (toJSString val))
foreign import javascript unsafe "$1[\"alt\"]" js_getAlt ::
JSRef HTMLAppletElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAppletElement.alt Mozilla HTMLAppletElement.alt documentation>
getAlt ::
(MonadIO m, FromJSString result) => HTMLAppletElement -> m result
getAlt self
= liftIO (fromJSString <$> (js_getAlt (unHTMLAppletElement self)))
foreign import javascript unsafe "$1[\"archive\"] = $2;"
js_setArchive :: JSRef HTMLAppletElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAppletElement.archive Mozilla HTMLAppletElement.archive documentation>
setArchive ::
(MonadIO m, ToJSString val) => HTMLAppletElement -> val -> m ()
setArchive self val
= liftIO
(js_setArchive (unHTMLAppletElement self) (toJSString val))
foreign import javascript unsafe "$1[\"archive\"]" js_getArchive ::
JSRef HTMLAppletElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAppletElement.archive Mozilla HTMLAppletElement.archive documentation>
getArchive ::
(MonadIO m, FromJSString result) => HTMLAppletElement -> m result
getArchive self
= liftIO
(fromJSString <$> (js_getArchive (unHTMLAppletElement self)))
foreign import javascript unsafe "$1[\"code\"] = $2;" js_setCode ::
JSRef HTMLAppletElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAppletElement.code Mozilla HTMLAppletElement.code documentation>
setCode ::
(MonadIO m, ToJSString val) => HTMLAppletElement -> val -> m ()
setCode self val
= liftIO (js_setCode (unHTMLAppletElement self) (toJSString val))
foreign import javascript unsafe "$1[\"code\"]" js_getCode ::
JSRef HTMLAppletElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAppletElement.code Mozilla HTMLAppletElement.code documentation>
getCode ::
(MonadIO m, FromJSString result) => HTMLAppletElement -> m result
getCode self
= liftIO (fromJSString <$> (js_getCode (unHTMLAppletElement self)))
foreign import javascript unsafe "$1[\"codeBase\"] = $2;"
js_setCodeBase :: JSRef HTMLAppletElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAppletElement.codeBase Mozilla HTMLAppletElement.codeBase documentation>
setCodeBase ::
(MonadIO m, ToJSString val) => HTMLAppletElement -> val -> m ()
setCodeBase self val
= liftIO
(js_setCodeBase (unHTMLAppletElement self) (toJSString val))
foreign import javascript unsafe "$1[\"codeBase\"]" js_getCodeBase
:: JSRef HTMLAppletElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAppletElement.codeBase Mozilla HTMLAppletElement.codeBase documentation>
getCodeBase ::
(MonadIO m, FromJSString result) => HTMLAppletElement -> m result
getCodeBase self
= liftIO
(fromJSString <$> (js_getCodeBase (unHTMLAppletElement self)))
foreign import javascript unsafe "$1[\"height\"] = $2;"
js_setHeight :: JSRef HTMLAppletElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAppletElement.height Mozilla HTMLAppletElement.height documentation>
setHeight ::
(MonadIO m, ToJSString val) => HTMLAppletElement -> val -> m ()
setHeight self val
= liftIO (js_setHeight (unHTMLAppletElement self) (toJSString val))
foreign import javascript unsafe "$1[\"height\"]" js_getHeight ::
JSRef HTMLAppletElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAppletElement.height Mozilla HTMLAppletElement.height documentation>
getHeight ::
(MonadIO m, FromJSString result) => HTMLAppletElement -> m result
getHeight self
= liftIO
(fromJSString <$> (js_getHeight (unHTMLAppletElement self)))
foreign import javascript unsafe "$1[\"hspace\"] = $2;"
js_setHspace :: JSRef HTMLAppletElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAppletElement.hspace Mozilla HTMLAppletElement.hspace documentation>
setHspace ::
(MonadIO m, ToJSString val) => HTMLAppletElement -> val -> m ()
setHspace self val
= liftIO (js_setHspace (unHTMLAppletElement self) (toJSString val))
foreign import javascript unsafe "$1[\"hspace\"]" js_getHspace ::
JSRef HTMLAppletElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAppletElement.hspace Mozilla HTMLAppletElement.hspace documentation>
getHspace ::
(MonadIO m, FromJSString result) => HTMLAppletElement -> m result
getHspace self
= liftIO
(fromJSString <$> (js_getHspace (unHTMLAppletElement self)))
foreign import javascript unsafe "$1[\"name\"] = $2;" js_setName ::
JSRef HTMLAppletElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAppletElement.name Mozilla HTMLAppletElement.name documentation>
setName ::
(MonadIO m, ToJSString val) => HTMLAppletElement -> val -> m ()
setName self val
= liftIO (js_setName (unHTMLAppletElement self) (toJSString val))
foreign import javascript unsafe "$1[\"name\"]" js_getName ::
JSRef HTMLAppletElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAppletElement.name Mozilla HTMLAppletElement.name documentation>
getName ::
(MonadIO m, FromJSString result) => HTMLAppletElement -> m result
getName self
= liftIO (fromJSString <$> (js_getName (unHTMLAppletElement self)))
foreign import javascript unsafe "$1[\"object\"] = $2;"
js_setObject :: JSRef HTMLAppletElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAppletElement.object Mozilla HTMLAppletElement.object documentation>
setObject ::
(MonadIO m, ToJSString val) => HTMLAppletElement -> val -> m ()
setObject self val
= liftIO (js_setObject (unHTMLAppletElement self) (toJSString val))
foreign import javascript unsafe "$1[\"object\"]" js_getObject ::
JSRef HTMLAppletElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAppletElement.object Mozilla HTMLAppletElement.object documentation>
getObject ::
(MonadIO m, FromJSString result) => HTMLAppletElement -> m result
getObject self
= liftIO
(fromJSString <$> (js_getObject (unHTMLAppletElement self)))
foreign import javascript unsafe "$1[\"vspace\"] = $2;"
js_setVspace :: JSRef HTMLAppletElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAppletElement.vspace Mozilla HTMLAppletElement.vspace documentation>
setVspace ::
(MonadIO m, ToJSString val) => HTMLAppletElement -> val -> m ()
setVspace self val
= liftIO (js_setVspace (unHTMLAppletElement self) (toJSString val))
foreign import javascript unsafe "$1[\"vspace\"]" js_getVspace ::
JSRef HTMLAppletElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAppletElement.vspace Mozilla HTMLAppletElement.vspace documentation>
getVspace ::
(MonadIO m, FromJSString result) => HTMLAppletElement -> m result
getVspace self
= liftIO
(fromJSString <$> (js_getVspace (unHTMLAppletElement self)))
foreign import javascript unsafe "$1[\"width\"] = $2;" js_setWidth
:: JSRef HTMLAppletElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAppletElement.width Mozilla HTMLAppletElement.width documentation>
setWidth ::
(MonadIO m, ToJSString val) => HTMLAppletElement -> val -> m ()
setWidth self val
= liftIO (js_setWidth (unHTMLAppletElement self) (toJSString val))
foreign import javascript unsafe "$1[\"width\"]" js_getWidth ::
JSRef HTMLAppletElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAppletElement.width Mozilla HTMLAppletElement.width documentation>
getWidth ::
(MonadIO m, FromJSString result) => HTMLAppletElement -> m result
getWidth self
= liftIO
(fromJSString <$> (js_getWidth (unHTMLAppletElement self))) | plow-technologies/ghcjs-dom | src/GHCJS/DOM/JSFFI/Generated/HTMLAppletElement.hs | mit | 10,910 | 154 | 11 | 1,699 | 2,384 | 1,278 | 1,106 | 168 | 1 |
-- |
-- Module: Math.NumberTheory.ZetaTests
-- Copyright: (c) 2016 Andrew Lelechenko
-- Licence: MIT
-- Maintainer: Andrew Lelechenko <andrew.lelechenko@gmail.com>
-- Stability: Provisional
--
-- Tests for Math.NumberTheory.Zeta
--
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
module Math.NumberTheory.ZetaTests
( testSuite
) where
import Test.Tasty
import Test.Tasty.HUnit
import Math.NumberTheory.Zeta
import Math.NumberTheory.TestUtils
assertEqualUpToEps :: String -> Double -> Double -> Double -> Assertion
assertEqualUpToEps msg eps expected actual
= assertBool msg (abs (expected - actual) < eps)
epsilon :: Double
epsilon = 1e-14
zetasEvenSpecialCase1 :: Assertion
zetasEvenSpecialCase1
= assertEqual "zeta(0) = -1/2"
(approximateValue $ zetasEven !! 0)
(-1 / 2)
zetasEvenSpecialCase2 :: Assertion
zetasEvenSpecialCase2
= assertEqualUpToEps "zeta(2) = pi^2/6" epsilon
(approximateValue $ zetasEven !! 1)
(pi * pi / 6)
zetasEvenSpecialCase3 :: Assertion
zetasEvenSpecialCase3
= assertEqualUpToEps "zeta(4) = pi^4/90" epsilon
(approximateValue $ zetasEven !! 2)
(pi ^ 4 / 90)
zetasEvenProperty1 :: Positive Int -> Bool
zetasEvenProperty1 (Positive m)
= zetaM < 1
|| zetaM > zetaM1
where
zetaM = approximateValue (zetasEven !! m)
zetaM1 = approximateValue (zetasEven !! (m + 1))
zetasEvenProperty2 :: Positive Int -> Bool
zetasEvenProperty2 (Positive m)
= abs (zetaM - zetaM') < epsilon
where
zetaM = approximateValue (zetasEven !! m)
zetaM' = zetas' !! (2 * m)
zetas' :: [Double]
zetas' = zetas epsilon
zetasSpecialCase1 :: Assertion
zetasSpecialCase1
= assertEqual "zeta(1) = Infinity"
(zetas' !! 1)
(1 / 0)
zetasSpecialCase2 :: Assertion
zetasSpecialCase2
= assertEqualUpToEps "zeta(3) = 1.2020569" epsilon
(zetas' !! 3)
1.2020569031595942853997381615114499908
zetasSpecialCase3 :: Assertion
zetasSpecialCase3
= assertEqualUpToEps "zeta(5) = 1.0369277" epsilon
(zetas' !! 5)
1.0369277551433699263313654864570341681
zetasProperty1 :: Positive Int -> Bool
zetasProperty1 (Positive m)
= zetaM >= zetaM1
&& zetaM1 >= 1
where
zetaM = zetas' !! m
zetaM1 = zetas' !! (m + 1)
zetasProperty2 :: NonNegative Int -> NonNegative Int -> Bool
zetasProperty2 (NonNegative e1) (NonNegative e2)
= maximum (take 25 $ drop 2 $ zipWith ((abs .) . (-)) (zetas eps1) (zetas eps2)) < eps1 + eps2
where
eps1, eps2 :: Double
eps1 = 1.0 / 2 ^ e1
eps2 = 1.0 / 2 ^ e2
testSuite :: TestTree
testSuite = testGroup "Zeta"
[ testGroup "zetasEven"
[ testCase "zeta(0)" zetasEvenSpecialCase1
, testCase "zeta(2)" zetasEvenSpecialCase2
, testCase "zeta(4)" zetasEvenSpecialCase3
, testSmallAndQuick "zeta(2n) > zeta(2n+2)" zetasEvenProperty1
, testSmallAndQuick "zetasEven matches zetas" zetasEvenProperty2
]
, testGroup "zetas"
[ testCase "zeta(1)" zetasSpecialCase1
, testCase "zeta(3)" zetasSpecialCase2
, testCase "zeta(5)" zetasSpecialCase3
, testSmallAndQuick "zeta(n) > zeta(n+1)" zetasProperty1
, testSmallAndQuick "precision" zetasProperty2
]
]
| cfredric/arithmoi | test-suite/Math/NumberTheory/ZetaTests.hs | mit | 3,308 | 0 | 13 | 775 | 792 | 425 | 367 | 81 | 1 |
{- |
The HList library
(C) 2004, Oleg Kiselyov, Ralf Laemmel, Keean Schupke
This is a next-to-main module that loads all modules that at least
*compile* fine for all the models of interest. See the Makefile
for ways to run different models.
-}
module Data.HList.CommonMain (
module Data.HList.FakePrelude
, module Data.HList.HListPrelude
, module Data.HList.HArray
, module Data.HList.HOccurs
, module Data.HList.HTypeIndexed
, module Data.HList.TIP
, module Data.HList.TIC
, module Data.HList.HZip
, module Data.HList.Record
, module Data.HList.Variant
) where
import Data.HList.FakePrelude
import Data.HList.HListPrelude
import Data.HList.HArray
import Data.HList.HOccurs
import Data.HList.HTypeIndexed
import Data.HList.TIP
import Data.HList.TIC
import Data.HList.HZip
import Data.HList.Record
import Data.HList.Variant
| bjornbm/HList-classic | Data/HList/CommonMain.hs | mit | 857 | 0 | 5 | 131 | 140 | 97 | 43 | 21 | 0 |
{-# LANGUAGE FlexibleInstances, UndecidableInstances, ScopedTypeVariables, OverlappingInstances #-}
module Probability where
import Control.Monad
import System.Random
--
-- probabilities
--
rollDie :: Integer -> IO Integer
rollDie faces = getStdRandom (randomR (1,faces))
rollDice :: Int -> Integer -> IO [Integer]
rollDice n faces = replicateM n (rollDie faces)
-- some sweet 'tax..
d :: Int -> Integer -> IO [Integer]
d = rollDice
--select random elems from bounded enums like r <- randomIO :: Klass
instance (Bounded a, Enum a) => Random a where
random = randomR (minBound :: a, maxBound :: a)
randomR (f, t) gen =
(toEnum r :: a, nextGen)
where
(rnd, nextGen) = next gen
r = fromEnum f + (rnd `mod` length [f..t])
randomIndex :: [a] -> IO Int
randomIndex l = getStdRandom (randomR (0, length l - 1))
pickFrom :: [a] -> IO a
pickFrom l = do
index <- randomIndex l
return (l !! index) | jweissman/heroes | src/Probability.hs | mit | 1,031 | 0 | 12 | 294 | 327 | 176 | 151 | 22 | 1 |
{-# LANGUAGE CPP #-}
module Network.Wai.Handler.Warp.Conduit where
import Control.Exception
import qualified Data.ByteString as S
import qualified Data.IORef as I
import Network.Wai.Handler.Warp.Imports
import Network.Wai.Handler.Warp.Types
----------------------------------------------------------------
-- | Contains a @Source@ and a byte count that is still to be read in.
data ISource = ISource !Source !(I.IORef Int)
mkISource :: Source -> Int -> IO ISource
mkISource src cnt = do
ref <- I.newIORef cnt
return $! ISource src ref
-- | Given an @IsolatedBSSource@ provide a @Source@ that only allows up to the
-- specified number of bytes to be passed downstream. All leftovers should be
-- retained within the @Source@. If there are not enough bytes available,
-- throws a @ConnectionClosedByPeer@ exception.
readISource :: ISource -> IO ByteString
readISource (ISource src ref) = do
count <- I.readIORef ref
if count == 0
then return S.empty
else do
bs <- readSource src
-- If no chunk available, then there aren't enough bytes in the
-- stream. Throw a ConnectionClosedByPeer
when (S.null bs) $ throwIO ConnectionClosedByPeer
let -- How many of the bytes in this chunk to send downstream
toSend = min count (S.length bs)
-- How many bytes will still remain to be sent downstream
count' = count - toSend
case () of
()
-- The expected count is greater than the size of the
-- chunk we just read. Send the entire chunk
-- downstream, and then loop on this function for the
-- next chunk.
| count' > 0 -> do
I.writeIORef ref count'
return bs
-- Some of the bytes in this chunk should not be sent
-- downstream. Split up the chunk into the sent and
-- not-sent parts, add the not-sent parts onto the new
-- source, and send the rest of the chunk downstream.
| otherwise -> do
let (x, y) = S.splitAt toSend bs
leftoverSource src y
assert (count' == 0) $ I.writeIORef ref count'
return x
----------------------------------------------------------------
data CSource = CSource !Source !(I.IORef ChunkState)
data ChunkState = NeedLen
| NeedLenNewline
| HaveLen Word
| DoneChunking
deriving Show
mkCSource :: Source -> IO CSource
mkCSource src = do
ref <- I.newIORef NeedLen
return $! CSource src ref
readCSource :: CSource -> IO ByteString
readCSource (CSource src ref) = do
mlen <- I.readIORef ref
go mlen
where
withLen 0 bs = do
leftoverSource src bs
dropCRLF
yield' S.empty DoneChunking
withLen len bs
| S.null bs = do
-- FIXME should this throw an exception if len > 0?
I.writeIORef ref DoneChunking
return S.empty
| otherwise =
case S.length bs `compare` fromIntegral len of
EQ -> yield' bs NeedLenNewline
LT -> yield' bs $ HaveLen $ len - fromIntegral (S.length bs)
GT -> do
let (x, y) = S.splitAt (fromIntegral len) bs
leftoverSource src y
yield' x NeedLenNewline
yield' bs mlen = do
I.writeIORef ref mlen
return bs
dropCRLF = do
bs <- readSource src
case S.uncons bs of
Nothing -> return ()
Just (13, bs') -> dropLF bs'
Just (10, bs') -> leftoverSource src bs'
Just _ -> leftoverSource src bs
dropLF bs =
case S.uncons bs of
Nothing -> do
bs2 <- readSource' src
unless (S.null bs2) $ dropLF bs2
Just (10, bs') -> leftoverSource src bs'
Just _ -> leftoverSource src bs
go NeedLen = getLen
go NeedLenNewline = dropCRLF >> getLen
go (HaveLen 0) = do
-- Drop the final CRLF
dropCRLF
I.writeIORef ref DoneChunking
return S.empty
go (HaveLen len) = do
bs <- readSource src
withLen len bs
go DoneChunking = return S.empty
-- Get the length from the source, and then pass off control to withLen
getLen = do
bs <- readSource src
if S.null bs
then do
I.writeIORef ref $ assert False $ HaveLen 0
return S.empty
else do
(x, y) <-
case S.break (== 10) bs of
(x, y)
| S.null y -> do
bs2 <- readSource' src
return $ if S.null bs2
then (x, y)
else S.break (== 10) $ bs `S.append` bs2
| otherwise -> return (x, y)
let w =
S.foldl' (\i c -> i * 16 + fromIntegral (hexToWord c)) 0
$ S.takeWhile isHexDigit x
let y' = S.drop 1 y
y'' <-
if S.null y'
then readSource src
else return y'
withLen w y''
hexToWord w
| w < 58 = w - 48
| w < 71 = w - 55
| otherwise = w - 87
isHexDigit :: Word8 -> Bool
isHexDigit w = w >= 48 && w <= 57
|| w >= 65 && w <= 70
|| w >= 97 && w <= 102
| creichert/wai | warp/Network/Wai/Handler/Warp/Conduit.hs | mit | 5,666 | 12 | 24 | 2,253 | 1,339 | 662 | 677 | 131 | 16 |
module Main where
main :: IO ()
main = putStrLn "Nothing implemented"
| willprice/haskell-cabal-example-tests | src/Main.hs | mit | 72 | 0 | 6 | 14 | 22 | 12 | 10 | 3 | 1 |
{-# LANGUAGE TupleSections #-}
module Parser
(
parse
)
where
import Stack (CalcError(ParsecError), Symbol(String, Bool, Variable, Real, Int, List))
import Text.ParserCombinators.Parsec hiding (parse)
import qualified Text.ParserCombinators.Parsec as Parsec (parse)
import Data.Functor ((<$>))
import Control.Monad (when)
import Numeric (readHex, readOct, readDec, readInt)
parse :: [Char] -> Either CalcError [Symbol]
parse input = case Parsec.parse rpnInput "(RPN input)" input of
Left err -> Left $ ParsecError err
Right res -> Right res
rpnInput :: GenParser Char st [Symbol]
rpnInput = do
spaces
result <- fmap concat (sepEndBy command (many1 space))
eof
return result
-- functions and operators identified by proper text are handled as strings
command :: GenParser Char st [Symbol]
command = combined
<|> fmap (:[]) operator
combined :: GenParser Char st [Symbol]
combined = do
lit <- literal
op <- optionMaybe operator
case op of
Nothing -> return [lit]
Just o -> return [lit, o]
operator :: GenParser Char st Symbol
operator = fmap String $ many1 (oneOf symbolChar)
symbolChar :: [Char]
symbolChar = "+-/*%^<>=|&!~@#$:,"
literal :: GenParser Char st Symbol
literal = number
<|> fmap (Bool . read) bool
<|> fmap Variable variable
<|> list
<|> fmap String quotedString
<|> fmap String unquotedString
<?> "value"
separator :: GenParser Char st Char
separator = lookAhead . try . oneOf $ ' ' : '[' : ']' : symbolChar
complete :: GenParser Char st Char
complete = eof >> return '\0'
manyM :: GenParser Char st a -> GenParser Char st [a]
manyM p = manyTill p (separator <|> complete)
variable :: GenParser Char st String
variable = try $ do
x <- upper
xs <- manyM alphaNum
return $ x:xs
bool :: GenParser Char st String
bool = try (string "True" <|> string "False")
number :: GenParser Char st Symbol
number = fmap (Real . read) real <|> wrap <$> int
where wrap = Int . fst . head
real :: GenParser Char st String
real = try $ do
intPart <- many digit
char '.'
let (intPart', combinator) = if null intPart then ("0", many1) else (intPart, many)
decPart <- combinator digit
return $ intPart' ++ '.' : decPart
int :: GenParser Char st [(Integer, String)]
int = try hexInt <|> try octalInt <|> try binInt <|> try decInt
intBase :: GenParser Char st Char -> ReadS Integer -> String -> GenParser Char st [(Integer, String)]
intBase p reader err = do
i <- manyM p
when (null i) $ fail err
return $ reader i
hexInt :: GenParser Char st [(Integer,String)]
octalInt :: GenParser Char st [(Integer,String)]
binInt :: GenParser Char st [(Integer,String)]
decInt :: GenParser Char st [(Integer,String)]
hexInt = string "0x" >> intBase hexDigit readHex "hexadecimal number"
octalInt = char '0' >> intBase octDigit readOct "octal number"
binInt = string "0b" >> intBase (oneOf "01") readBin "binary number"
where readBin :: Num a => ReadS a
readBin = readInt 2 (`elem` "01") (\c -> if c == '0' then 0 else 1)
decInt = intBase digit readDec "number"
quotedString :: GenParser Char st String
quotedString = do
char '"'
c <- many1 quotedChar
char '"'
return c
where quotedChar = try escaped <|> noneOf "\""
escaped = string "\\\"" >> return '\"' :: GenParser Char st Char
unquotedString :: GenParser Char st String
unquotedString = many1 unquotedChar
where unquotedChar = try escaped <|> alphaNum <|> oneOf "_."
escaped = char '\\' >> oneOf "\' " :: GenParser Char st Char
list :: GenParser Char st Symbol
list = List <$> between (char '[') (char ']') (sepBy listItem (char ','))
listItem :: GenParser Char st Symbol
listItem = do
spaces
i <- literal
spaces
return i
| qsn/rhcalc | src/Parser.hs | mit | 3,731 | 0 | 13 | 779 | 1,402 | 716 | 686 | 102 | 2 |
module Network.Telegram.Bot.Yesod
( module Network.Telegram.Bot.Types
, module Network.Telegram.Bot.Requests.Yesod
) where
import Network.Telegram.Bot.Types
import Network.Telegram.Bot.Requests.Yesod | Vlix/telegram-bot-http | Network/Telegram/Bot/Yesod.hs | mit | 227 | 0 | 5 | 41 | 42 | 31 | 11 | 5 | 0 |
{-# LANGUAGE RecordWildCards #-}
module Settings
( AppSettings(..)
, loadAppSettings
) where
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import qualified Data.Text as T
import LoadEnv
import System.Environment
import WordList
data AppSettings = AppSettings
{ appDefaultSize :: Int
, appRandomApiKey :: Text
, appRandomRequestSize :: Int
, appWordList :: WordList
}
loadAppSettings :: IO AppSettings
loadAppSettings = do
loadEnv
-- Required
appRandomApiKey <- T.pack <$> getEnv "RANDOM_API_KEY"
-- Optional
appDefaultSize <- read <$> getEnvDefault "4" "PASSPHRASE_SIZE"
appRandomRequestSize <- read <$> getEnvDefault "1000" "RANDOM_REQUEST_SIZE"
fp <- getEnvDefault "wordlist" "WORDLIST_FILE"
appWordList <- either (error . show) id <$> readWordList fp
pure AppSettings {..}
getEnvDefault :: String -> String -> IO String
getEnvDefault x k = fromMaybe x <$> lookupEnv k
| pbrisbin/passphrase.me | src/Settings.hs | mit | 955 | 0 | 11 | 193 | 240 | 128 | 112 | 26 | 1 |
merge :: Ord a => [a] -> [a] -> [a]
merge xs [] = xs
merge [] ys = ys
merge (x:xs) (y:ys) = x : y : merge xs ys | rootguy1/code-base | haskel/merge.hs | gpl-2.0 | 130 | 0 | 8 | 49 | 91 | 47 | 44 | 4 | 1 |
module Expression (Expression(Constant, Variable, Abstraction, Application, Block, Assignment, Definition, Branch), Expression.parser) where
import Text.ParserCombinators.Parsec
import Data.List
import JSON
import Text.JSON
import Data
data Expression
= Constant Data
| Variable String
| Abstraction [String] Expression
| Application Expression [Expression]
| Block Expression Expression [Expression]
| Assignment String Expression
| Definition String Expression
| Branch Expression Expression Expression
deriving Eq
----------
-- JSON --
----------
instance JSON Expression where
showJSON expr = JSString $ toJSString $ show expr
readJSON (JSString jss) = parsec expression jss
readJSON _ = Error "expects a string"
-------------------
-- Show & Parsec --
-------------------
instance Show Expression where
show (Constant dta) = show dta
show (Variable str) = str
show (Abstraction ids expr) = "(lambda ("++(intercalate " " ids)++") "++(show expr)++")"
show (Application expr exprs) = "("++(show expr)++(concatMap ((' ':).show) exprs)++")"
show (Block expr1 expr2 exprs) = "(begin "++(show expr1)++" "++(show expr2)++(concatMap ((' ':).show) exprs)++")"
show (Assignment str expr) = "(set! "++str++" "++(show expr)++")"
show (Definition str expr) = "(define "++str++" "++(show expr)++")"
show (Branch expr1 expr2 expr3) = "(if "++(show expr1)++" "++(show expr2)++" "++(show expr3)++")"
eat = many (space <|> tab <|> newline)
identifier = eat >> (many1 $ noneOf " \t\n()")
parser = expression
expression = choice [try abstraction, try block, try assignment, try definition, try branch, try application, try constant, try variable]
constant = eat >> Data.parser >>= (return . Constant)
variable = identifier >>= (return . Variable)
abstraction = do eat
char '('
eat
string "lambda"
eat
char '('
params <- many identifier
eat
char ')'
body <- expression
eat
char ')'
return $ Abstraction params body
block = do eat
char '('
eat
string "begin"
expr1 <- expression
expr2 <- expression
exprs <- many expression
eat
char ')'
return $ Block expr1 expr2 exprs
assignment = do eat
char '('
eat
string "set!"
param <- identifier
body <- expression
eat
char ')'
return $ Assignment param body
definition = do eat
char '('
eat
string "define"
param <- identifier
body <- expression
eat
char ')'
return $ Definition param body
branch = do eat
char '('
eat
string "if"
pred <- expression
cons <- expression
alt <- expression
eat
char ')'
return $ Branch pred cons alt
application = do eat
char '('
proc <- expression
args <- many expression
eat
char ')'
return $ Application proc args
| lachrist/kusasa-hs | expression.hs | gpl-2.0 | 3,400 | 0 | 13 | 1,215 | 1,049 | 511 | 538 | 95 | 1 |
{-# LANGUAGE DeriveGeneric, DefaultSignatures #-} -- For automatic generation of cereal put and get
module Dust.Services.File.File
(
File(..),
FileHeader(..),
FileData(..),
readEncodedFile,
openFile,
writeFileData
)
where
import GHC.Generics
import Data.Serialize
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.List.Split
import System.Directory
data File = File FileHeader [FileData] deriving (Generic, Show, Eq) -- name contents
instance Serialize File
data FileHeader = FileHeader String Int deriving (Generic, Show, Eq) -- filename count
instance Serialize FileHeader
data FileData = FileData ByteString deriving (Generic, Show, Eq)
instance Serialize FileData
readEncodedFile :: String -> IO File
readEncodedFile path = do
let name = sanitize path
contents <- B.readFile path
let chunks = splitData 1000 contents
let filedata = map FileData chunks
let header = FileHeader name $ length chunks
return $ File header filedata
splitData :: Int -> ByteString -> [ByteString]
splitData size bs =
if B.length bs < size
then [bs]
else (B.take size bs) : splitData size (B.drop size bs)
openFile :: FileHeader -> IO ()
openFile (FileHeader path _) = do
let name = sanitize path
removeFile $ "incoming/"++name
writeFileData :: FileHeader -> FileData -> IO()
writeFileData (FileHeader path _) (FileData contents) = do
let name = sanitize path
B.appendFile ("incoming/"++name) contents
sanitize :: String -> String
sanitize path = do
if elem '/' path
then last $ splitOn "/" path
else path
| blanu/Dust-tools | Dust/Services/File/File.hs | gpl-2.0 | 1,636 | 0 | 11 | 335 | 527 | 273 | 254 | 47 | 2 |
import Graphics.Rendering.Cairo
data Point = Point Double Double
deriving Show
data Vector = Vector Double Double
deriving Show
data RGBA = RGB Double Double Double
| RGBA Double Double Double Double
tau = 6.28318530717958647692
uncurry3 f (a,b,c) = f a b c
mkVector (Point x0 y0) (Point x1 y1) =
Vector (x1 - x0) (y1 - y0)
toPoint (Point x0 y0) (Vector dx dy) =
Point (x0 + dx) (y0 + dy)
toPoint1 (Vector dx dy) =
Point dx dy
normal (Vector dx dy) =
Vector (-dy) dx
dist (Point x0 y0) (Point x1 y1) =
sqrt ((sqr dx) + (sqr dy))
where
sqr x = x * x
dx = x1 - x0
dy = y1 - y0
magnitude (Vector dx dy) =
dist (Point 0 0) (Point dx dy)
darkPoly = [Point 200 50, Point 55 180, Point 75 340, Point 345 210]
unit r (Vector dx dy) =
Vector (r * dx / mag) (r * dy / mag)
where
mag = magnitude (Vector dx dy)
white = RGBA 1.00 1.00 1.00 1.00
red = RGB 0.88 0.29 0.22
orange = RGB 0.98 0.63 0.15
yellow = RGB 0.97 0.85 0.39
green = RGB 0.38 0.74 0.43
darkGreen = RGB 0.00 0.66 0.52
fileName = "dark-green-points.png"
vectorAngle (Vector x y)
| y >= 0 = acos x
| otherwise = -(acos x)
setColor (RGBA r g b a) = setSourceRGBA r g b a
setColor (RGB r g b) = setColor (RGBA r g b 0.8)
drawMarkerAt color (Point x y) = do
let bw = 10.0
save
translate x y
setColor color
rectangle (-0.5*bw) (-0.5*bw) bw bw
fill
restore
drawArc color r (Point x y) angle1 angle2 = do
setColor color
arc x y r angle1 angle2
stroke
drawLine color (Point x0 y0) (Point x1 y1) = do
setColor color
moveTo x0 y0
lineTo x1 y1
stroke
drawVector color (Point x y) (Vector dx dy) = do
setColor color
moveTo x y
relLineTo dx dy
stroke
paintCanvas = do
setSourceRGB 1 1 1
paint
mapM_ (drawMarkerAt darkGreen) darkPoly
createPng fileName = do
let w = 400
h = 400
img <- createImageSurface FormatARGB32 w h
renderWith img paintCanvas
surfaceWriteToPNG img fileName
main = do
createPng fileName
| jsavatgy/xroads-game | code/dark-green-points.hs | gpl-2.0 | 1,997 | 49 | 9 | 520 | 909 | 466 | 443 | 74 | 1 |
{-# Language OverloadedStrings, FlexibleInstances, TypeFamilies, NoMonomorphismRestriction, ScopedTypeVariables, FlexibleContexts #-}
module Test.Sort where
import Data.List
import Test.Tasty
import Test.Helper
import Person
tests :: TestTree
tests = testGroup "sorting" [
[Female, Male] .==. sort [Male, Female],
[Female, Female] .==. sort [Female, Female],
[jane, winston] .==. sortBy genderOrder [winston, jane],
[jane, winston] .==. sortBy lastNameOrder [winston, jane],
[winston, jane] .==. sortBy (flip lastNameOrder) [winston, jane],
[winston, wendy] .==. sortBy birthDateOrder [wendy, winston],
[jane, wendy, antonin] .==. sortBy genderThenLastNameOrder [antonin, jane, wendy],
[jane, wendy, antonin] .==. sortBy genderThenLastNameOrder [wendy, antonin, jane]]
where jane = Person "Jane" "Jay" Female (Date 1979 4 2) "Green"
winston = Person "Winston" "Watertown" Male (Date 1925 12 18) "Orange"
wendy = Person "Wendy" "Watertown" Female (Date 1925 12 19) "Dark Orange"
antonin = Person "Antonin" "Applebaum" Male (Date 1925 12 19) "Dark Gray"
| mattraibert/codetest | src/Test/Sort.hs | gpl-3.0 | 1,097 | 0 | 10 | 179 | 352 | 198 | 154 | 20 | 1 |
{-
Textual Positions
This file is part of AEx.
Copyright (C) 2016 Jeffrey Sharp
AEx 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.
AEx 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 AEx. If not, see <http://www.gnu.org/licenses/>.
-}
-- | Textual positions within files.
module Aex.Pos where
import Aex.Util (Display, display)
import Data.ByteString (ByteString)
import Data.ByteString.Builder
import Data.Monoid
--------------------------------------------------------------------------------
-- | A file name.
type FileName = ByteString
-- | A byte offset, where 0 indicates the first byte.
type Offset = Word
-- | A line number, where 1 indicates the first line.
type LineNum = Word
-- | A column number, where 1 indicates the first column.
type ColumnNum = Word
-- | A position within a named file.
data Pos = Pos
{ fileName :: !FileName
, byteOff :: !Offset
, lineNum :: !LineNum
, columnNum :: !ColumnNum
} deriving (Eq, Show)
-- | Create a new 'Pos' positioned at the beginning of the named file.
bof :: ByteString -> Pos
bof f = Pos f 0 1 1
-- | Advance a position by the given character. Given a newline (\'\\n\'), the
-- line number is incrememted, and the column number is set to 1. Given any
-- other character, the column number is incremented.
move :: Pos -> Char -> Pos
move (Pos f b l c) '\n' = Pos f (b + 1) (l + 1) ( 1)
move (Pos f b l c) _ = Pos f (b + 1) (l ) (c + 1)
instance Display Pos where
display (Pos f _ l c)
= byteString f
<> char8 ':' <> wordDec l
<> char8 ':' <> wordDec c
--------------------------------------------------------------------------------
-- | Class for items having a textual position within a named file.
class HasPos a where
-- | Get the textual position.
pos :: a -> Pos
| sharpjs/haskell-learning | src/Aex/Pos.hs | gpl-3.0 | 2,324 | 0 | 10 | 552 | 339 | 189 | 150 | 35 | 1 |
-- 2014 - Ahmet Cetinkaya
increaseBase :: Integer -> Integer -> Integer
increaseBase number base = increaseBase' number base 0 0
where increaseBase' number base i acc
| number == 0 = acc
| otherwise = increaseBase' (div number base) base (i + 1) acc + ((base + 1) ^ (increaseBase i base)) * (rem number base)
goodsteinIterate :: Integer -> Integer -> Integer
goodsteinIterate number base = (increaseBase number base) - 1
goodsteinSequence :: Integer -> Integer -> [Integer]
goodsteinSequence initialNumber initialBase
| initialNumber == 0 = [0]
| otherwise = initialNumber : (goodsteinSequence (goodsteinIterate initialNumber initialBase) (initialBase + 1))
| cetinkaya/goodstein | goodstein.hs | gpl-3.0 | 727 | 1 | 13 | 170 | 239 | 121 | 118 | 11 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module SerieController ( SerieviewerStatus(..)
, getSerieviewerStatus
, getSerieList
, serieKill
, serieNext
, serieKillAndNext
, seriePlay
, vlcPause
, vlcPlay
, vlcChapterPrev
, vlcChapterNext
) where
import DBus
import DBus.Client (call_, Client, ClientError)
import Control.Concurrent (threadDelay)
import Control.Exception (try)
import Data.Maybe (fromMaybe)
data SerieviewerStatus = Running | NotRunning deriving (Show)
extractException :: Either ClientError MethodReturn -> Maybe MethodReturn
extractException (Left _) = Nothing
extractException (Right a) = Just a
callDBus :: Client -> ObjectPath -> InterfaceName -> BusName -> MemberName-> IO (Maybe MethodReturn)
callDBus client objectpath interfacename methoddestination membername = do
r <- try (call_ client (methodCall objectpath interfacename membername)
{ methodCallDestination = Just methoddestination
})
return $ extractException r
-- serie calls
callSerie :: Client -> String -> IO (Maybe MethodReturn)
callSerie client method = do
let m = memberName_ method
callDBus client "/Serieviewer" "org.serieviewer" "org.serieviewer" m
callVLCWithInterface :: Client -> String -> String -> IO (Maybe MethodReturn)
callVLCWithInterface client interfacename membername = do
let m = memberName_ membername
let i = interfaceName_ interfacename
callDBus client "/org/mpris/MediaPlayer2" i "org.mpris.MediaPlayer2.vlc" m
callVLC :: Client -> String -> IO (Maybe MethodReturn)
callVLC client membername =
callVLCWithInterface client "org.mpris.MediaPlayer2" membername
callVLCPlayer :: Client -> String -> IO (Maybe MethodReturn)
callVLCPlayer client membername =
callVLCWithInterface client "org.mpris.MediaPlayer2.Player" membername
callDBusNames :: Client -> IO (Maybe MethodReturn)
callDBusNames client =
let o = objectPath_ "/"
m = memberName_ "ListNames" in
callDBus client o "org.freedesktop.DBus" "org.freedesktop.DBus" m
serieStatus :: Maybe MethodReturn -> SerieviewerStatus
serieStatus Nothing = NotRunning
serieStatus (Just method) =
let v = head $ methodReturnBody method
list = (fromVariant v ::Maybe [String])
test = \l -> "org.serieviewer" `elem` l
exists = maybe False test list in
if exists then Running else NotRunning
getSerieviewerStatus :: Client -> IO SerieviewerStatus
getSerieviewerStatus client = do
let m_methodreturn = callDBusNames client
status <- fmap serieStatus m_methodreturn;
return status
extractSerieNames :: Maybe MethodReturn -> [String]
extractSerieNames method =
case method of -- for some reason matching didn't work, check why
Nothing -> []
Just m ->
let v = head $ methodReturnBody m in
fromMaybe [] $ fromVariant v
getSerieList :: Client -> IO [String]
getSerieList client = do
let m_methodreturn = callSerie client "getSerieNameList"
list <- fmap extractSerieNames m_methodreturn;
return list
serieKill :: Client -> IO ()
serieKill client = do _ <- callVLC client "Quit"; return ();
serieNext :: Client -> IO ()
serieNext client = do _ <- callSerie client "playNextInSerie"; return ();
serieKillAndNext :: Client -> IO ()
serieKillAndNext client = do
serieKill client;
threadDelay 5;
serieNext client;
seriePlay :: Client -> Int -> IO ()
seriePlay client sid = do
let o = objectPath_ "/Serieviewer"
m = memberName_ "playIndex"
i = show sid in
call_ client (methodCall o "org.serieviewer" m)
{
methodCallDestination = Just "org.serieviewer",
methodCallBody = [toVariant i]
};
return ()
-- VLC Calls
vlcPause :: Client -> IO ()
vlcPause client = do _ <- callVLCPlayer client "Pause"; return ();
vlcPlay :: Client -> IO ()
vlcPlay client = do _ <- callVLCPlayer client "Play"; return ();
vlcChapterPrev :: Client -> IO ()
vlcChapterPrev client = do return ()
vlcChapterNext :: Client -> IO ()
vlcChapterNext client = do return ()
| Narfinger/player-control | haskell/SerieController.hs | gpl-3.0 | 4,247 | 0 | 13 | 1,008 | 1,207 | 598 | 609 | 97 | 2 |
{-# 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.DLP.Projects.Locations.InspectTemplates.Create
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Creates an InspectTemplate for re-using frequently used configuration
-- for inspecting content, images, and storage. See
-- https:\/\/cloud.google.com\/dlp\/docs\/creating-templates to learn more.
--
-- /See:/ <https://cloud.google.com/dlp/docs/ Cloud Data Loss Prevention (DLP) API Reference> for @dlp.projects.locations.inspectTemplates.create@.
module Network.Google.Resource.DLP.Projects.Locations.InspectTemplates.Create
(
-- * REST Resource
ProjectsLocationsInspectTemplatesCreateResource
-- * Creating a Request
, projectsLocationsInspectTemplatesCreate
, ProjectsLocationsInspectTemplatesCreate
-- * Request Lenses
, plitcParent
, plitcXgafv
, plitcUploadProtocol
, plitcAccessToken
, plitcUploadType
, plitcPayload
, plitcCallback
) where
import Network.Google.DLP.Types
import Network.Google.Prelude
-- | A resource alias for @dlp.projects.locations.inspectTemplates.create@ method which the
-- 'ProjectsLocationsInspectTemplatesCreate' request conforms to.
type ProjectsLocationsInspectTemplatesCreateResource
=
"v2" :>
Capture "parent" Text :>
"inspectTemplates" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON]
GooglePrivacyDlpV2CreateInspectTemplateRequest
:> Post '[JSON] GooglePrivacyDlpV2InspectTemplate
-- | Creates an InspectTemplate for re-using frequently used configuration
-- for inspecting content, images, and storage. See
-- https:\/\/cloud.google.com\/dlp\/docs\/creating-templates to learn more.
--
-- /See:/ 'projectsLocationsInspectTemplatesCreate' smart constructor.
data ProjectsLocationsInspectTemplatesCreate =
ProjectsLocationsInspectTemplatesCreate'
{ _plitcParent :: !Text
, _plitcXgafv :: !(Maybe Xgafv)
, _plitcUploadProtocol :: !(Maybe Text)
, _plitcAccessToken :: !(Maybe Text)
, _plitcUploadType :: !(Maybe Text)
, _plitcPayload :: !GooglePrivacyDlpV2CreateInspectTemplateRequest
, _plitcCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsInspectTemplatesCreate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plitcParent'
--
-- * 'plitcXgafv'
--
-- * 'plitcUploadProtocol'
--
-- * 'plitcAccessToken'
--
-- * 'plitcUploadType'
--
-- * 'plitcPayload'
--
-- * 'plitcCallback'
projectsLocationsInspectTemplatesCreate
:: Text -- ^ 'plitcParent'
-> GooglePrivacyDlpV2CreateInspectTemplateRequest -- ^ 'plitcPayload'
-> ProjectsLocationsInspectTemplatesCreate
projectsLocationsInspectTemplatesCreate pPlitcParent_ pPlitcPayload_ =
ProjectsLocationsInspectTemplatesCreate'
{ _plitcParent = pPlitcParent_
, _plitcXgafv = Nothing
, _plitcUploadProtocol = Nothing
, _plitcAccessToken = Nothing
, _plitcUploadType = Nothing
, _plitcPayload = pPlitcPayload_
, _plitcCallback = Nothing
}
-- | Required. Parent resource name. The format of this value varies
-- depending on the scope of the request (project or organization) and
-- whether you have [specified a processing
-- location](https:\/\/cloud.google.com\/dlp\/docs\/specifying-location): +
-- Projects scope, location specified:
-- \`projects\/\`PROJECT_ID\`\/locations\/\`LOCATION_ID + Projects scope,
-- no location specified (defaults to global): \`projects\/\`PROJECT_ID +
-- Organizations scope, location specified:
-- \`organizations\/\`ORG_ID\`\/locations\/\`LOCATION_ID + Organizations
-- scope, no location specified (defaults to global):
-- \`organizations\/\`ORG_ID The following example \`parent\` string
-- specifies a parent project with the identifier \`example-project\`, and
-- specifies the \`europe-west3\` location for processing data:
-- parent=projects\/example-project\/locations\/europe-west3
plitcParent :: Lens' ProjectsLocationsInspectTemplatesCreate Text
plitcParent
= lens _plitcParent (\ s a -> s{_plitcParent = a})
-- | V1 error format.
plitcXgafv :: Lens' ProjectsLocationsInspectTemplatesCreate (Maybe Xgafv)
plitcXgafv
= lens _plitcXgafv (\ s a -> s{_plitcXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
plitcUploadProtocol :: Lens' ProjectsLocationsInspectTemplatesCreate (Maybe Text)
plitcUploadProtocol
= lens _plitcUploadProtocol
(\ s a -> s{_plitcUploadProtocol = a})
-- | OAuth access token.
plitcAccessToken :: Lens' ProjectsLocationsInspectTemplatesCreate (Maybe Text)
plitcAccessToken
= lens _plitcAccessToken
(\ s a -> s{_plitcAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
plitcUploadType :: Lens' ProjectsLocationsInspectTemplatesCreate (Maybe Text)
plitcUploadType
= lens _plitcUploadType
(\ s a -> s{_plitcUploadType = a})
-- | Multipart request metadata.
plitcPayload :: Lens' ProjectsLocationsInspectTemplatesCreate GooglePrivacyDlpV2CreateInspectTemplateRequest
plitcPayload
= lens _plitcPayload (\ s a -> s{_plitcPayload = a})
-- | JSONP
plitcCallback :: Lens' ProjectsLocationsInspectTemplatesCreate (Maybe Text)
plitcCallback
= lens _plitcCallback
(\ s a -> s{_plitcCallback = a})
instance GoogleRequest
ProjectsLocationsInspectTemplatesCreate
where
type Rs ProjectsLocationsInspectTemplatesCreate =
GooglePrivacyDlpV2InspectTemplate
type Scopes ProjectsLocationsInspectTemplatesCreate =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient
ProjectsLocationsInspectTemplatesCreate'{..}
= go _plitcParent _plitcXgafv _plitcUploadProtocol
_plitcAccessToken
_plitcUploadType
_plitcCallback
(Just AltJSON)
_plitcPayload
dLPService
where go
= buildClient
(Proxy ::
Proxy
ProjectsLocationsInspectTemplatesCreateResource)
mempty
| brendanhay/gogol | gogol-dlp/gen/Network/Google/Resource/DLP/Projects/Locations/InspectTemplates/Create.hs | mpl-2.0 | 7,143 | 0 | 17 | 1,431 | 797 | 472 | 325 | 122 | 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.GroupsSettings.Groups.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Gets one resource by id.
--
-- /See:/ <https://developers.google.com/google-apps/groups-settings/get_started Groups Settings API Reference> for @groupsSettings.groups.get@.
module Network.Google.Resource.GroupsSettings.Groups.Get
(
-- * REST Resource
GroupsGetResource
-- * Creating a Request
, groupsGet
, GroupsGet
-- * Request Lenses
, ggGroupUniqueId
) where
import Network.Google.GroupsSettings.Types
import Network.Google.Prelude
-- | A resource alias for @groupsSettings.groups.get@ method which the
-- 'GroupsGet' request conforms to.
type GroupsGetResource =
"groups" :>
"v1" :>
"groups" :>
Capture "groupUniqueId" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] Groups
-- | Gets one resource by id.
--
-- /See:/ 'groupsGet' smart constructor.
newtype GroupsGet =
GroupsGet'
{ _ggGroupUniqueId :: Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GroupsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ggGroupUniqueId'
groupsGet
:: Text -- ^ 'ggGroupUniqueId'
-> GroupsGet
groupsGet pGgGroupUniqueId_ = GroupsGet' {_ggGroupUniqueId = pGgGroupUniqueId_}
-- | The group\'s email address.
ggGroupUniqueId :: Lens' GroupsGet Text
ggGroupUniqueId
= lens _ggGroupUniqueId
(\ s a -> s{_ggGroupUniqueId = a})
instance GoogleRequest GroupsGet where
type Rs GroupsGet = Groups
type Scopes GroupsGet =
'["https://www.googleapis.com/auth/apps.groups.settings"]
requestClient GroupsGet'{..}
= go _ggGroupUniqueId (Just AltJSON)
groupsSettingsService
where go
= buildClient (Proxy :: Proxy GroupsGetResource)
mempty
| brendanhay/gogol | gogol-groups-settings/gen/Network/Google/Resource/GroupsSettings/Groups/Get.hs | mpl-2.0 | 2,634 | 0 | 12 | 583 | 299 | 184 | 115 | 48 | 1 |
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE ViewPatterns #-}
-- |
-- XML Schema Datatypes
--
-- <http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/> (selected portions)
module SAML2.XML.Schema.Datatypes where
import Prelude hiding (String)
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Base64 as B64
import Data.Char (isDigit)
import Data.Char.Properties.XMLCharProps (isXmlSpaceChar, isXmlNameChar)
import Data.Fixed (Pico, showFixed)
import Data.List (elemIndex)
import Data.Semigroup ((<>))
import qualified Data.Time.Clock as Time
import Data.Time.Format (formatTime, parseTimeM, defaultTimeLocale)
import Data.Word (Word16)
import qualified Network.URI as URI
import qualified Text.XML.HXT.Arrow.Pickle.Schema as XPS
import Text.XML.HXT.DOM.QualifiedName (isNCName)
import qualified Text.XML.HXT.DOM.XmlNode as XN
import qualified Text.XML.HXT.XMLSchema.DataTypeLibW3CNames as XSD
import qualified Text.XML.HXT.Arrow.Pickle.Xml.Invertible as XP
-- |§3.2.1
type String = [Char]
xpString :: XP.PU String
xpString = XP.xpTextDT (XPS.scDTxsd XSD.xsd_string [])
-- |§3.2.1
type Boolean = Bool
xpBoolean :: XP.PU Boolean
xpBoolean = XP.xpWrapEither
( \s -> case s of
"true" -> Right True
"false" -> Right False
"1" -> Right True
"0" -> Right False
_ -> Left "invalid boolean"
, \b -> if b then "true" else "false"
) $ XP.xpTextDT $ XPS.scDTxsd XSD.xsd_boolean []
-- |§3.2.6 specifies a complete ISO8601 6-component duration; for SAML2 purposes we don't overly care
type Duration = Time.NominalDiffTime
xpDuration :: XP.PU Duration
xpDuration = XP.xpWrapEither
( maybe (Left "invalid duration") (Right . realToFrac) . prd
, \t -> (if signum t < 0 then ('-':) else id)
$ 'P':'T': showFixed True (abs $ realToFrac t :: Pico) ++ "S"
) $ XP.xpTextDT $ XPS.scDTxsd XSD.xsd_duration [] where
prd ('-':s) = negate <$> prp s
prd ('+':s) = prp s
prd s = prp s
prp ('P':s) = pru (0 :: Pico) prt [('Y',31556952),('M',2629746),('D',86400)] s
prp _ = Nothing
prt x "" = Just x
prt x ('T':s) = pru x prs [('H',3600),('M',60)] s
prt _ _ = Nothing
prs x "" = Just x
prs x s = case span isDigit s of
(d@(_:_),'.':(span isDigit -> (p,"S"))) -> Just $ x + read (d ++ '.' : p)
(d@(_:_),"S") -> Just $ x + read d
_ -> Nothing
pru x c ul s = case span isDigit s of
(d@(_:_),uc:sr) | (_,uv):ur <- dropWhile ((uc /=) . fst) ul -> pru (x + uv * read d) c ur sr
_ -> c x s
-- |§3.2.7 theoretically allows timezones, but SAML2 does not use them
type DateTime = Time.UTCTime
xpDateTime :: XP.PU DateTime
xpDateTime = XP.PU
{ XP.theSchema = XPS.scDTxsd XSD.xsd_dateTime []
, XP.appPickle = XP.putCont . XN.mkText . tweakTimeString . formatTime defaultTimeLocale fmtz
, XP.appUnPickle = XP.getCont >>= XP.liftMaybe "dateTime expects text" . XN.getText >>= parseTime
}
where
-- timezone must be 'Z', and MicrosoftS(tm) Azure(tm) will choke when it is ommitted. (error
-- messages are utterly unhelpful.)
fmtz = "%Y-%m-%dT%H:%M:%S%QZ"
parseTime dateString = maybe (XP.throwMsg $ "can't parse date " <> dateString) pure
$ parseTimeM True defaultTimeLocale fmtz dateString
-- adding '%Q' may be longer than 7 digits, which makes MicrosoftS(tm) Azure(tm) choke.
tweakTimeString :: String -> String
tweakTimeString s = case elemIndex '.' s of
Nothing -> s
Just i -> case splitAt i s of
(t, u) -> case splitAt 8 u of
(_, "") -> t ++ u
(v, _) -> t ++ v ++ "Z"
-- |§3.2.16
type Base64Binary = BS.ByteString
xpBase64Binary :: XP.PU Base64Binary
xpBase64Binary = XP.xpWrapEither
( B64.decode . BS.pack . filter (not . isXmlSpaceChar)
, BS.unpack . B64.encode
) $ XP.xpText0DT $ XPS.scDTxsd XSD.xsd_base64Binary []
-- |§3.2.17
type AnyURI = URI.URI
xpAnyURI :: XP.PU AnyURI
xpAnyURI = XP.xpWrapEither
( maybe (Left "invalid anyURI") Right . URI.parseURIReference
, \u -> URI.uriToString id u "")
$ XP.xpText0DT $ XPS.scDTxsd XSD.xsd_anyURI []
-- |§3.3.1
type NormalizedString = String
-- |§3.3.2
type Token = NormalizedString
-- |§3.3.3
type Language = Token
xpLanguage :: XP.PU Language
xpLanguage = XP.xpTextDT $ XPS.scDTxsd XSD.xsd_language []
-- |§3.3.4
type NMTOKEN = Token
isNMTOKEN :: Token -> Bool
isNMTOKEN [] = False
isNMTOKEN s = all isXmlNameChar s
xpNMTOKEN :: XP.PU NMTOKEN
xpNMTOKEN = XP.xpWrapEither
( \x -> if isNMTOKEN x then Right x else Left "NMTOKEN expected"
, id
) $ XP.xpTextDT $ XPS.scDTxsd XSD.xsd_NMTOKEN []
-- |§3.3.5
type NMTOKENS = [NMTOKEN]
xpNMTOKENS :: XP.PU NMTOKENS
xpNMTOKENS = XP.xpWrapEither
( \x -> case words x of
[] -> Left "NMTOKENS expected"
l | all isNMTOKEN l -> Right l
_ -> Left "NMTOKENS expected"
, unwords
) $ XP.xpTextDT $ XPS.scDTxsd XSD.xsd_NMTOKENS []
-- |§3.3.8
type ID = String
type NCName = String
xpNCName :: XP.PU NCName
xpNCName = XP.xpWrapEither
( \x -> if isNCName x then Right x else Left "NCName expected"
, id
) $ XP.xpTextDT $ XPS.scDTxsd XSD.xsd_NCName []
xpID :: XP.PU ID
xpID = xpNCName{ XP.theSchema = XPS.scDTxsd XSD.xsd_ID [] }
-- |§3.3.13
xpInteger :: XP.PU Integer
xpInteger = XP.xpPrim{ XP.theSchema = XPS.scDTxsd XSD.xsd_integer [] }
-- |§3.3.20
type NonNegativeInteger = Word
xpNonNegativeInteger :: XP.PU NonNegativeInteger
xpNonNegativeInteger = XP.xpPrim{ XP.theSchema = XPS.scDTxsd XSD.xsd_nonNegativeInteger [] }
-- |§3.3.23
type UnsignedShort = Word16
xpUnsignedShort :: XP.PU UnsignedShort
xpUnsignedShort = XP.xpPrim{ XP.theSchema = XPS.scDTxsd XSD.xsd_unsignedShort [] }
-- |§3.3.20
type PositiveInteger = NonNegativeInteger
xpPositiveInteger :: XP.PU PositiveInteger
xpPositiveInteger = XP.xpWrapEither
( \x -> if x > 0 then Right x else Left "0 is not positive"
, id
) $ XP.xpPrim{ XP.theSchema = XPS.scDTxsd XSD.xsd_positiveInteger [] }
| dylex/hsaml2 | SAML2/XML/Schema/Datatypes.hs | apache-2.0 | 5,874 | 0 | 17 | 1,094 | 1,982 | 1,087 | 895 | 131 | 11 |
{-
Copyright 2015 Tristan Aubrey-Jones
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
{-|
Copyright : (c) Tristan Aubrey-Jones, 2015
License : Apache-2
Maintainer : developer@flocc.net
Stability : experimental
For more information please see <http://www.flocc.net/>
-}
module Compiler.Front.Front where
import Compiler.Front.Common
import Compiler.Front.Indices
import Compiler.Front.ExprTree
import Compiler.Front.SrcLexer
import Compiler.Front.SrcParser
import Control.Monad.State (lift)
-- |parseSrc path. Returns the AST for the source code.
parseSrc :: Monad m => [(String, Idx)] -> String -> IdxMonad m Expr
parseSrc libVarIds src = do
-- lex and parse it
ast <- parseAndLabel libVarIds $ scan src
return ast
-- |parseSrcFile path. Reads the contents of the file
-- |at path, and returns it's AST.
parseSrcFile :: [(String, Idx)] -> FilePath -> IdxMonad IO Expr
parseSrcFile libVarIds path = do
-- read in file
src <- lift $ readFileForce path
-- lex and parse it
ast <- parseAndLabel libVarIds $ scan src
return ast
testParseSrcFile :: FilePath -> IO Expr
testParseSrcFile path = do
-- read in file
src <- readFileForce path
return $ parse $ scan src
| flocc-net/flocc | v0.1/Compiler/Front/Front.hs | apache-2.0 | 1,678 | 0 | 9 | 290 | 242 | 128 | 114 | 20 | 1 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE ViewPatterns #-}
-- | Machinery for making decisions about C++ level materialization for K3.
module Language.K3.Codegen.CPP.Materialization where
import Prelude hiding (concat, mapM, mapM_, or, and)
import Control.Applicative
import Control.Arrow
import Control.Monad.Identity (Identity(..), runIdentity)
import Control.Monad.State (StateT(..), MonadState(..), modify, runState)
import Language.K3.Analysis.Provenance.Core
import Language.K3.Analysis.Provenance.Inference (PIEnv(..))
import qualified Language.K3.Analysis.Provenance.Constructors as P
import Language.K3.Analysis.SEffects.Core
import Language.K3.Analysis.SEffects.Inference (FIEnv(..))
import Language.K3.Codegen.CPP.Materialization.Hints
import Data.Functor
import Data.Traversable
import Data.Foldable
import Data.Maybe (fromMaybe, maybeToList)
import Data.Tree
import qualified Data.Map as M
import qualified Data.IntMap as I
import Language.K3.Core.Annotation
import Language.K3.Core.Declaration
import Language.K3.Core.Expression
import Language.K3.Core.Common hiding (getUID)
type Table = I.IntMap (M.Map Identifier Decision)
type MaterializationS = (Table, PIEnv, FIEnv, [K3 Expression])
type MaterializationM = StateT MaterializationS Identity
-- State Accessors
dLookup :: Int -> Identifier -> MaterializationM Decision
dLookup u i = get >>= \(t, _, _, _) -> return $ fromMaybe defaultDecision (I.lookup u t >>= M.lookup i)
dLookupAll :: Int -> MaterializationM (M.Map Identifier Decision)
dLookupAll u = get >>= \(t, _, _, _) -> return (I.findWithDefault M.empty u t)
pLookup :: PPtr -> MaterializationM (K3 Provenance)
pLookup p = get >>= \(_, e, _, _) -> return (fromMaybe (error "Dangling provenance pointer") (I.lookup p (ppenv e)))
pLookupDeep :: PPtr -> MaterializationM (K3 Provenance)
pLookupDeep p = pLookup p >>= \case
(tag -> PBVar (PMatVar { pmvptr })) -> pLookupDeep pmvptr
p' -> return p'
-- A /very/ rough approximation of ReaderT's ~local~ for StateT.
withLocalDS :: [K3 Expression] -> MaterializationM a -> MaterializationM a
withLocalDS nds m = do
(t, e, f, ds) <- get
put (t, e, f, (nds ++ ds))
r <- m
(t', e', f', _) <- get
put (t', e', f', ds)
return r
getUID :: K3 Expression -> Int
getUID e = let EUID (UID u) = fromMaybe (error "No UID on expression.")
(e @~ \case { EUID _ -> True; _ -> False }) in u
getProvenance :: K3 Expression -> K3 Provenance
getProvenance e = let EProvenance p = fromMaybe (error "No provenance on expression.")
(e @~ \case { EProvenance _ -> True; _ -> False}) in p
getEffects :: K3 Expression -> K3 Effect
getEffects e = let ESEffect f = fromMaybe (error "No effects on expression.")
(e @~ \case { ESEffect _ -> True; _ -> False }) in f
getFStructure :: K3 Expression -> K3 Effect
getFStructure e = let EFStructure f = fromMaybe (error "No effects on expression.")
(e @~ \case { EFStructure _ -> True; _ -> False }) in f
setDecision :: Int -> Identifier -> Decision -> MaterializationM ()
setDecision u i d = modify $ \(t, e, f, ds) -> (I.insertWith M.union u (M.singleton i d) t, e, f, ds)
getClosureSymbols :: Int -> MaterializationM [Identifier]
getClosureSymbols i = get >>= \(_, plcenv -> e, _, _) -> return $ concat $ maybeToList (I.lookup i e)
pmvloc' :: PMatVar -> Int
pmvloc' pmv = let UID u = pmvloc pmv in u
-- Table Construction/Attachment
runMaterializationM :: MaterializationM a -> MaterializationS -> (a, MaterializationS)
runMaterializationM m s = runIdentity $ runStateT m s
optimizeMaterialization :: (PIEnv, FIEnv) -> K3 Declaration -> K3 Declaration
optimizeMaterialization (p, f) d = fst $ runMaterializationM (materializationD d) (I.empty, p, f, [])
materializationD :: K3 Declaration -> MaterializationM (K3 Declaration)
materializationD (Node (d :@: as) cs)
= case d of
DGlobal i t me -> traverse materializationE me >>= \me' -> Node (DGlobal i t me' :@: as) <$> cs'
DTrigger i t e -> materializationE e >>= \e' -> Node (DTrigger i t e' :@: as) <$> cs'
DRole i -> Node (DRole i :@: as) <$> cs'
_ -> Node (d :@: as) <$> cs'
where
cs' = mapM materializationD cs
materializationE :: K3 Expression -> MaterializationM (K3 Expression)
materializationE e@(Node (t :@: as) cs)
= case t of
EOperate OApp -> do
[f, x] <- mapM materializationE cs
let applicationEffects = getFStructure e
let (executionEffects, returnEffects, formalParameter) =
case applicationEffects of
(tag &&& children -> (FApply (Just fmv), [_, executionEffects, returnEffects])) ->
(executionEffects, returnEffects, fmv)
_ -> error "Invalid effect structure"
conservativeDoMoveLocal <- hasWriteInIF (fmvn formalParameter) executionEffects
conservativeDoMoveReturn <-
case f of
(tag &&& children -> (ELambda i, [f'])) ->
case f' of
(tag -> ELambda _) -> do
let f'id = getUID f'
f'd <- dLookup f'id i
return $ inD f'd == Moved
_ -> return False
_ -> return False
moveable <- isMoveableNow x
let applicationDecision d =
if (conservativeDoMoveLocal || conservativeDoMoveReturn) && moveable
then d { inD = Moved }
else d
setDecision (getUID e) "" $ applicationDecision defaultDecision
decisions <- dLookupAll (getUID e)
return (Node (t :@: (EMaterialization decisions:as)) [f, x])
ELambda x -> do
[b] <- mapM materializationE cs
let lambdaEffects = getEffects e
let (deferredEffects, returnedEffects)
= case lambdaEffects of
(tag &&& children -> (FLambda _, [_, deferredEffects, returnedEffects]))
-> (deferredEffects, returnedEffects)
_ -> error "Invalid effect structure"
let lambdaProvenance = getProvenance e
let returnedProvenance =
case getProvenance e of
(tag &&& children -> (PLambda _, [returnedProvenance])) -> returnedProvenance
_ -> error "Invalid provenance structure"
readOnly <- not <$> hasWriteInP (P.pfvar x) b
let nrvoProvenance q =
case q of
(tag -> PFVar _) -> return True
(tag -> PBVar _) -> not <$> isGlobalP q
(tag -> PSet) -> anyM nrvoProvenance (children q)
_ -> return False
nrvo <- nrvoProvenance returnedProvenance
let readOnlyDecision d = if readOnly then d { inD = ConstReferenced } else d
let nrvoDecision d = if nrvo then d { outD = Moved } else d
setDecision (getUID e) x $ readOnlyDecision $ nrvoDecision $ defaultDecision
closureSymbols <- getClosureSymbols (getUID e)
forM_ closureSymbols $ \s -> do
closureHasWrite <- hasWriteInI s b
moveable <- return True
let closureDecision d =
if closureHasWrite
then if moveable
then d { inD = Moved }
else d { inD = Copied }
else d { inD = Referenced }
setDecision (getUID e) s $ closureDecision defaultDecision
decisions <- dLookupAll (getUID e)
return $ (Node (t :@: (EMaterialization decisions:as)) [b])
EBindAs b -> do
let [x, y] = cs
x' <- withLocalDS [y] (materializationE x)
y' <- materializationE y
let xp = getProvenance x
mention <- (||) <$> hasReadInP xp y' <*> hasWriteInP xp y'
let referenceBind d = if not mention then d { inD = Referenced, outD = Referenced } else d
case b of
BIndirection i -> setDecision (getUID e) i $ referenceBind defaultDecision
BTuple is -> mapM_ (\i -> setDecision (getUID e) i $ referenceBind defaultDecision) is
BRecord iis -> mapM_ (\(_, i) -> setDecision (getUID e) i $ referenceBind defaultDecision) iis
decisions <- dLookupAll (getUID e)
return (Node (t :@: (EMaterialization decisions:as)) [x', y'])
ECaseOf i -> do
let [x, s, n] = cs
x' <- withLocalDS [s, n] (materializationE x)
s' <- materializationE s
n' <- materializationE n
let xp = getProvenance x
-- TODO: Slightly conservative, although it takes reasonably unusual code to trigger
-- those cases.
noMention <- do
sMention <- (||) <$> hasReadInP xp s' <*> hasWriteInP xp s'
nMention <- (||) <$> hasReadInP xp n' <*> hasWriteInP xp n'
return $ not (sMention || nMention)
let referenceBind d = if noMention then d { inD = Referenced, outD = Referenced } else d
setDecision (getUID e) i $ referenceBind defaultDecision
decisions <- dLookupAll (getUID e)
return (Node (t :@: (EMaterialization decisions:as)) [x', s', n'])
ELetIn i -> do
let [x, b] = cs
x' <- withLocalDS [b] (materializationE x)
b' <- materializationE b
setDecision (getUID e) i defaultDecision
decisions <- dLookupAll (getUID e)
return (Node (t :@: (EMaterialization decisions:as)) [x', b'])
_ -> (Node (t :@: as)) <$> mapM materializationE cs
-- Queries
anyM :: (Functor m, Applicative m, Monad m) => (a -> m Bool) -> [a] -> m Bool
anyM f xs = or <$> mapM f xs
allM :: (Functor m, Applicative m, Monad m) => (a -> m Bool) -> [a] -> m Bool
allM f xs = and <$> mapM f xs
-- Determine if a piece of provenance 'occurs in' another. The answer can be influenced by 'width
-- flag', determining whether or not the provenance of superstructure occurs in the provenance of
-- its substructure.
occursIn :: Bool -> K3 Provenance -> K3 Provenance -> MaterializationM Bool
occursIn wide a b
= case tag b of
-- Everything occurs in itself.
_ | a == b -> return True
-- Something occurs in a bound variable if it occurs in anything that was used to initialize
-- that bound variable, and that bound variable was initialized using a non-isolating method.
PBVar mv -> do
decision <- dLookup (pmvloc' mv) (pmvn mv)
if inD decision == Referenced || inD decision == ConstReferenced
then pLookup (pmvptr mv) >>= occursIn wide a
else return False
-- Something occurs in substructure if it occurs in any superstructure, and wide effects are
-- set.
POption | wide -> anyM (occursIn wide a) (children b)
PIndirection | wide -> anyM (occursIn wide a) (children b)
PTuple _ | wide -> anyM (occursIn wide a) (children b)
PProject _ | wide -> anyM (occursIn wide a) (children b)
PRecord _ | wide -> anyM (occursIn wide a) (children b)
-- TODO: Add more intelligent handling of substructure + PData combinations.
_ -> return False
isReadIn :: K3 Expression -> K3 Expression -> MaterializationM Bool
isReadIn x f =
case f of
_ -> isReadInF (getProvenance x) (getEffects f)
isReadInF :: K3 Provenance -> K3 Effect -> MaterializationM Bool
isReadInF xp ff =
case ff of
(tag -> FRead yp) -> occursIn False xp yp
(tag -> FScope _) -> anyM (isReadInF xp) (children ff)
(tag -> FSeq) -> anyM (isReadInF xp) (children ff)
(tag -> FSet) -> anyM (isReadInF xp) (children ff)
_ -> return False
isWrittenIn :: K3 Expression -> K3 Expression -> MaterializationM Bool
isWrittenIn x f =
case f of
_ -> isWrittenInF (getProvenance x) (getEffects f)
isWrittenInF :: K3 Provenance -> K3 Effect -> MaterializationM Bool
isWrittenInF xp ff =
case ff of
(tag -> FWrite yp) -> occursIn True xp yp
(tag -> FScope _) -> anyM (isWrittenInF xp) (children ff)
(tag -> FSeq) -> anyM (isWrittenInF xp) (children ff)
(tag -> FSet) -> anyM (isWrittenInF xp) (children ff)
_ -> return False
hasWriteInIF :: Identifier -> K3 Effect -> MaterializationM Bool
hasWriteInIF ident effect =
case effect of
(tag -> FWrite (tag -> PFVar i)) | i == ident -> return True
(tag -> FWrite (tag -> PBVar m)) | pmvn m == ident -> return True
(tag -> FScope _) -> anyM (hasWriteInIF ident) (children effect)
(tag -> FSeq) -> anyM (hasWriteInIF ident) (children effect)
(tag -> FSet) -> anyM (hasWriteInIF ident) (children effect)
_ -> return False
hasWriteInI :: Identifier -> K3 Expression -> MaterializationM Bool
hasWriteInI ident expr =
case expr of
(tag -> ELambda i) | i == ident -> return False
(tag &&& children -> (ELambda _, [body])) -> do
lambdaDecisions <- dLookupAll (getUID expr)
case M.lookup ident lambdaDecisions of
Nothing -> return False
Just cd ->
case inD cd of
ConstReferenced -> return False
Referenced -> hasWriteInI ident body
Moved -> return True
Copied -> return False
(tag &&& children -> (ELetIn i, [e, _])) | i == ident -> hasWriteInI ident e
(tag &&& children -> (ELetIn j, [e, b])) -> do
eHasWriteInI <- hasWriteInI ident e
bHasWriteInI <- hasWriteInI ident b
(||) <$> hasWriteInI ident e <*> hasWriteInI ident b
-- TODO: Other shadow cases.
_ -> do
localHasWrite <- hasWriteInIF ident (getEffects expr)
childHasWrite <- anyM (hasWriteInI ident) (children expr)
return (localHasWrite || childHasWrite)
pVarName :: K3 Provenance -> Maybe Identifier
pVarName p =
case p of
(tag -> PFVar j) -> Just j
(tag -> PBVar pmv) -> Just $ pmvn pmv
_ -> Nothing
hasWriteInP :: K3 Provenance -> K3 Expression -> MaterializationM Bool
hasWriteInP prov expr =
case expr of
(tag &&& children -> (ELambda i, [b])) -> do
closureDecisions <- dLookupAll (getUID expr)
let writeInClosure = maybe False (\j -> maybe False (\d -> inD d == Moved) $ M.lookup j closureDecisions)
(pVarName prov)
childHasWrite <- hasWriteInP prov b
return (writeInClosure || childHasWrite)
(tag &&& children -> (EOperate OApp, [f, x])) -> do
let argProv = getProvenance x
argOccurs <- occursIn True prov argProv
appDecision <- dLookup (getUID expr) ""
functionHasWrite <- hasWriteInP prov f
argHasWrite <- hasWriteInP prov x
let appHasWrite = inD appDecision == Moved && argOccurs
appHasIntrinsicWrite <- isWrittenInF prov (getEffects expr)
return (functionHasWrite || argHasWrite || appHasWrite || appHasIntrinsicWrite)
_ -> (||) <$> isWrittenInF prov (getEffects expr) <*> anyM (hasWriteInP prov) (children expr)
hasReadInP :: K3 Provenance -> K3 Expression -> MaterializationM Bool
hasReadInP prov expr =
case expr of
(tag &&& children -> (ELambda i, [b])) -> do
closureDecisions <- dLookupAll (getUID expr)
let readInClosure = maybe False (\j -> maybe False (\d -> inD d == Copied) $ M.lookup j closureDecisions)
(pVarName prov)
childHasRead <- hasReadInP prov b
return (readInClosure || childHasRead)
(tag &&& children -> (EOperate OApp, [f, x])) -> do
let argProv = getProvenance x
argOccurs <- occursIn True prov argProv
appDecision <- dLookup (getUID expr) ""
functionHasRead <- hasReadInP prov f
argHasRead <- hasReadInP prov x
let appHasRead = inD appDecision == Moved && argOccurs
return (functionHasRead || argHasRead || appHasRead)
_ -> (||) <$> isReadInF prov (getEffects expr) <*> anyM (hasReadInP prov) (children expr)
isGlobalP :: K3 Provenance -> MaterializationM Bool
isGlobalP ep =
case ep of
(tag -> PGlobal _) -> return True
(tag -> PBVar pmv) -> pLookup (pmvptr pmv) >>= isGlobalP
(tag &&& children -> (PProject _, [pp])) -> isGlobalP pp
_ -> return False
isMoveable :: K3 Expression -> MaterializationM Bool
isMoveable e =
case e of
(tag -> ELambda _) -> return False
_ -> not <$> isGlobalP (getProvenance e)
isMoveableIn :: K3 Expression -> K3 Expression -> MaterializationM Bool
isMoveableIn x c = do
isRead <- isReadIn x c
isWritten <- isWrittenIn x c
return $ not (isRead || isWritten)
isMoveableNow :: K3 Expression -> MaterializationM Bool
isMoveableNow x = do
(_, _, _, downstreams) <- get
isMoveable1 <- isMoveable x
allMoveable <- allM (isMoveableIn x) downstreams
return $ isMoveable1 && allMoveable
| yliu120/K3 | src/Language/K3/Codegen/CPP/Materialization.hs | apache-2.0 | 17,091 | 0 | 22 | 4,868 | 5,882 | 2,930 | 2,952 | 320 | 23 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UndecidableInstances #-}
----------------------------------------------------------------------------
-- |
-- Module : Type.Class.Nullary
-- Copyright : 2015 Derek Elkins
-- License : BSD2
--
-- Maintainer : Derek Elkins <derek.a.elkins@gmail.com>
-- Stability : experimental
-- Portability : non-portable
--
-- Provides a framework for defining and using nullary type classes
-- without needing orphan instances. To do this requires some evil
-- to locally generate a type class instances. This library
-- encapsulates that evil and provides a mechanism for safely
-- defining new nullary type classes.
--
-- To define a nullary type class, you use the following pattern:
--
-- > -- The following four extensions are necessary.
-- > -- Users do not need these extensions.
-- > {-# LANGUAGE FlexibleContexts #-}
-- > {-# LANGUAGE MultiParamTypeClasses #-}
-- > {-# LANGUAGE Rank2Types #-}
-- > {-# LANGUAGE UndecidableInstances #-}
-- >
-- > -- Not exported unless you want to allow users to opt out of
-- > -- the checking by making an instance for Tag PartialTag.
-- > data PartialTag
-- >
-- > -- The nullary type class. It can have members, but it's not
-- > -- clear this accomplishes anything.
-- > class Partial
-- >
-- > -- Enable this library. Instances like this unfortunately
-- > -- require UndecidableInstances.
-- > instance Tag PartialTag => Partial
-- >
-- > -- Wrap unsafeTag for user convenience.
-- > partial :: (Partial => a) -> a
-- > partial = unsafeTag (Proxy :: Proxy PartialTag)
-- > {-# INLINE partial #-}
-- >
-- > -- Define your functions using the Partial class.
-- > head :: Partial => [a] -> a
-- > head (x:xs) = x
-------------------------------------------------------------------------------
module Type.Class.Nullary (
Tag,
unsafeTag,
Proxy(..) -- re-exported for convenience
) where
import Data.Proxy ( Proxy(..) )
import Unsafe.Coerce ( unsafeCoerce )
-- | Class for declaring tagged nullary instances. See module description.
class Tag t
-- The evil.
newtype MagicTag t r = MagicTag (Tag t => r)
-- | Unsafely cast off the Tag constraint. This should only
-- be used at the "top-level" of an application. In practice,
-- specializations of this should be provided, e.g. unsafeUnsafe.
-- This uses the same evil as Data.Reflection.
unsafeTag :: forall r t. Proxy t -> (Tag t => r) -> r
unsafeTag Proxy f = unsafeCoerce (MagicTag f :: MagicTag t r) ()
{-# INLINE unsafeTag #-}
| derekelkins/nullary | Type/Class/Nullary.hs | bsd-2-clause | 2,606 | 0 | 10 | 463 | 195 | 136 | 59 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeOperators #-}
module Serv.Api.Auth
( Principal(..)
, basicAuthServerContext
) where
import Data.Text (Text)
import Servant.API
import Servant.API.BasicAuth (BasicAuthData (BasicAuthData))
import Servant.Server (BasicAuthCheck (BasicAuthCheck), BasicAuthResult (Authorized, Unauthorized),
Context ((:.), EmptyContext), Handler,
Server, err401, err403, errBody,
serveWithContext)
data Principal = Principal
{ principalName :: Text
} deriving (Eq, Show)
-- | 'BasicAuthCheck' holds the handler we'll use to verify a username and password.
authCheck :: BasicAuthCheck Principal
authCheck =
let check (BasicAuthData username password) =
if username == "servant" && password == "server"
then return (Authorized (Principal "servant"))
else return Unauthorized
in BasicAuthCheck check
basicAuthServerContext :: Context (BasicAuthCheck Principal ': '[])
basicAuthServerContext = authCheck :. EmptyContext
| orangefiredragon/bear | src/Serv/Api/Auth.hs | bsd-3-clause | 1,215 | 0 | 14 | 354 | 240 | 142 | 98 | 25 | 2 |
module Generics.SOP.Lens.Computed (
-- * Abstract lenses
AbstractLens(..)
, abstractId
, afterGLens
-- * Getters and setters
, get
, set
, modify
, getM
, setM
, modifyM
-- * Computing lenses
, Path
, CLens
, lens
-- * Manually constructing lenses
, emptyPathOnly
-- * Configuration
, LensOptions(..)
, defaultLensOptions
) where
import Prelude hiding (id, (.))
import Control.Arrow
import Control.Category
import Control.Monad
import Data.Functor.Identity
import Data.Maybe (catMaybes)
import Generics.SOP
import Generics.SOP.Lens (GLens)
import qualified Generics.SOP.Lens as GLens
{-------------------------------------------------------------------------------
Abstract lenses
-------------------------------------------------------------------------------}
-- | An abstract lens qualifies existentially over the target type of the lens
--
-- Sadly, abstract lenses do not form a category, so we provide special
-- identity and composition functions.
data AbstractLens r w c a =
forall x. c x => AbstractLens (GLens r w a x)
-- | Identity abstract lens
abstractId :: (ArrowApply r, ArrowApply w, c a) => AbstractLens r w c a
abstractId = AbstractLens id
-- | Compose with a pointwise lens on the right
afterGLens :: (ArrowApply r, ArrowApply w)
=> AbstractLens r w c a -- ^ @a -> x@
-> GLens r w b a -- ^ @b -> a@
-> AbstractLens r w c b -- ^ @b -> x@
afterGLens (AbstractLens l) l' = AbstractLens (l . l')
{-------------------------------------------------------------------------------
Getters and setters (mostly just for convenience)
-------------------------------------------------------------------------------}
-- | Getter for computed lenses
--
-- > get l == runIdentity . getM l . Identity
get :: Category r => AbstractLens r w c a -> (forall x. c x => r a x -> b) -> b
get l f = runIdentity $ getM l (Identity . f)
-- | Setter for computed lenses
--
-- > set l == runIdentity . setM l . Identity
set :: Arrow w => AbstractLens r w c a -> (forall x. c x => x) -> w a a
set l x = runIdentity $ setM l (Identity x)
-- | Modifier for computed lenses
modify :: Arrow w => AbstractLens r w c a -> (forall x. c x => w x x) -> w a a
modify l f = runIdentity $ modifyM l (Identity f)
-- | Getter with possibility for "compile time" failure
getM :: (Monad m, Category r)
=> AbstractLens r w c a
-> (forall x. c x => r a x -> m b)
-> m b
getM (AbstractLens l) k = k (GLens.get l)
-- | Setter with possibility for "compile time" failure
setM :: (Monad m, Arrow w)
=> AbstractLens r w c a -> (forall x. c x => m x) -> m (w a a)
setM (AbstractLens l) mx =
mx >>= \x -> return $ GLens.set l . arr (\a -> (x, a))
-- | Modifier with possibility for "compile time" failure
modifyM :: (Monad m, Arrow w)
=> AbstractLens r w c a -> (forall x. c x => m (w x x)) -> m (w a a)
modifyM (AbstractLens l) mf =
mf >>= \f -> return $ GLens.modify l . arr (\a -> (f, a))
{-------------------------------------------------------------------------------
Paths
-------------------------------------------------------------------------------}
-- | A path is a series of field names. For instance, given
--
-- > data T1 = T1 { a :: Int, b :: Int } deriving Generic
-- > data T2 = T2 { c :: T1, d :: Int } deriving Generic
--
-- valid paths on T2 are
--
-- > []
-- > ["c"]
-- > ["d"]
-- > ["c", "a"]
-- > ["c", "b"]
type Path = [String]
{-------------------------------------------------------------------------------
Top-level generic function
-------------------------------------------------------------------------------}
-- | Compute a lens for a given type and path
--
-- The @Either@ is used to indicate "compile time" failure of the computation
-- of the lens (for instance, when this path is invalid for this data type).
--
-- Some lenses may of course be themselves effectful, depending on the category.
-- However, the lenses returned by the generic computation are pure and total
-- (as is evident from the type of glens).
class CLens r w c a where
default lens :: ( Generic a
, HasDatatypeInfo a
, ArrowApply r
, ArrowApply w
, c a
, Code a ~ '[xs]
, All (CLens r w c) xs
)
=> LensOptions -> Path -> Either String (AbstractLens r w c a)
lens :: LensOptions -> Path -> Either String (AbstractLens r w c a)
lens = glens
{-------------------------------------------------------------------------------
Instances
We don't provide any instances here, because applications might want to
implement special kinds of semantics for certain paths for types that we
normally cannot "look into".
-------------------------------------------------------------------------------}
-- | A lens for abstract types (supports empty paths only)
--
-- Useful for defining CLens instances for types such as Int, Bool,
-- Text, etc.
--
-- > instance CLens c Int where lens = emptyPathOnly
emptyPathOnly :: (ArrowApply r, ArrowApply w, c a)
=> LensOptions -> Path -> Either String (AbstractLens r w c a)
emptyPathOnly _ [] = Right $ abstractId
emptyPathOnly _ _ = Left "Trying to look inside abstract type"
{-------------------------------------------------------------------------------
Lens options
-------------------------------------------------------------------------------}
data LensOptions = LensOptions {
-- | Match a selector against a path component
lensOptionsMatch :: DatatypeName -> FieldName -> String -> Bool
}
-- | Default match just compares field names
defaultLensOptions :: LensOptions
defaultLensOptions = LensOptions {
lensOptionsMatch = const (==)
}
{-------------------------------------------------------------------------------
The actual generic function
-------------------------------------------------------------------------------}
glens :: forall r w a c xs.
( ArrowApply r
, ArrowApply w
, Generic a
, HasDatatypeInfo a
, c a
, Code a ~ '[xs]
, All (CLens r w c) xs
)
=> LensOptions -> Path -> Either String (AbstractLens r w c a)
glens _ [] = Right $ abstractId
glens opts (p:ps) = liftM (`afterGLens` (GLens.sop . GLens.rep))
. glens' opts p ps
$ datatypeInfo (Proxy :: Proxy a)
glens' :: ( ArrowApply r
, ArrowApply w
, All (CLens r w c) xs
)
=> LensOptions -> String -> Path
-> DatatypeInfo '[xs]
-> Either String (AbstractLens r w c (NP I xs))
glens' opts p ps d =
glens'' opts ps (datatypeName d) p (hd (constructorInfo d))
glens'' :: forall r w c xs.
( ArrowApply r
, ArrowApply w
, All (CLens r w c) xs
)
=> LensOptions -> Path
-> DatatypeName -> String
-> ConstructorInfo xs
-> Either String (AbstractLens r w c (NP I xs))
glens'' _ _ _ _ (Constructor _) =
Left $ "Cannot compute lenses for non-record types"
glens'' _ _ _ _ (Infix _ _ _) =
Left $ "Cannot compute lenses for non-record types"
glens'' opts ps d p (Record _ fs) =
case matchingLenses of
[] -> Left $ "Unknown field " ++ show p ++ " of datatype " ++ show d
[l] -> l
_ -> Left $ "Invalid metadata for datatype " ++ show d
where
matchingLenses :: [Either String (AbstractLens r w c (NP I xs))]
matchingLenses = catMaybes . hcollapse $ hcliftA2 pl aux fs GLens.np
aux :: forall a. CLens r w c a
=> FieldInfo a
-> GLens r w (NP I xs) a
-> K (Maybe (Either String (AbstractLens r w c (NP I xs)))) a
aux (FieldInfo f) l = K $
if lensOptionsMatch opts d f p
then Just $ ((`afterGLens` l) `liftM` lens opts ps)
else Nothing
pl :: Proxy (CLens r w c)
pl = Proxy
| well-typed/lens-sop | src/Generics/SOP/Lens/Computed.hs | bsd-3-clause | 7,959 | 0 | 19 | 1,971 | 2,000 | 1,069 | 931 | -1 | -1 |
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.SGIX.Shadow
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.SGIX.Shadow (
-- * Extension Support
glGetSGIXShadow,
gl_SGIX_shadow,
-- * Enums
pattern GL_TEXTURE_COMPARE_OPERATOR_SGIX,
pattern GL_TEXTURE_COMPARE_SGIX,
pattern GL_TEXTURE_GEQUAL_R_SGIX,
pattern GL_TEXTURE_LEQUAL_R_SGIX
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
| haskell-opengl/OpenGLRaw | src/Graphics/GL/SGIX/Shadow.hs | bsd-3-clause | 745 | 0 | 5 | 103 | 62 | 45 | 17 | 10 | 0 |
--------------------------------------------------------------------------------
-- | Super-simple trie datastructure
{-# LANGUAGE BangPatterns #-}
module LoremMarkdownum.Trie
( Trie
, empty
, insert
, insertWith
, lookup
, fromList
, toList
) where
--------------------------------------------------------------------------------
import Data.List (foldl')
import Data.Map (Map)
import qualified Data.Map as M
import Prelude hiding (lookup, map)
--------------------------------------------------------------------------------
data Trie k v
= Trie !(Maybe v) !(Map k (Trie k v))
deriving (Eq, Ord, Show)
--------------------------------------------------------------------------------
instance Ord k => Functor (Trie k) where
fmap f (Trie mv children) = Trie (fmap f mv) (M.map (fmap f) children)
--------------------------------------------------------------------------------
empty :: Ord k => Trie k v
empty = Trie Nothing M.empty
--------------------------------------------------------------------------------
insert :: Ord k => [k] -> v -> Trie k v -> Trie k v
insert = insertWith const
--------------------------------------------------------------------------------
insertWith :: Ord k => (v -> v -> v) -> [k] -> v -> Trie k v -> Trie k v
insertWith f keys !v = go keys
where
go [] (Trie Nothing children) = Trie (Just v) children
go [] (Trie (Just v') children) =
let !nv = f v v' in Trie (Just nv) children
go (k : ks) (Trie mv children) = case M.lookup k children of
Nothing -> Trie mv (M.insert k (go ks empty) children)
Just t -> Trie mv (M.insert k (go ks t) children)
--------------------------------------------------------------------------------
lookup :: Ord k => [k] -> Trie k v -> Maybe v
lookup [] (Trie mv _) = mv
lookup (k : ks) (Trie _ children) = case M.lookup k children of
Nothing -> Nothing
Just c -> lookup ks c
--------------------------------------------------------------------------------
fromList :: Ord k => [([k], v)] -> Trie k v
fromList = foldl' (\t (k, v) -> insert k v t) empty
--------------------------------------------------------------------------------
toList :: Ord k => Trie k v -> [([k], v)]
toList = go id
where
go path (Trie mv children) = maybe id (\v -> ((path [], v) :)) mv $
[ l
| (k, child) <- M.toList children
, l <- go ((++ [k]) . path) child
]
| jaspervdj/lorem-markdownum | lib/LoremMarkdownum/Trie.hs | bsd-3-clause | 2,535 | 0 | 15 | 562 | 849 | 442 | 407 | 47 | 4 |
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-warnings-deprecations #-}
module Scheme.Data (
ThrowsError
, LispVal (..)
, LispError (..)
, Env
, IOThrowsError
, showVal
) where
import Control.Monad.Error
-- TODO convert to Except
--import Control.Monad.Except
import Data.IORef
import Data.Text (Text)
import qualified Data.Text as T
import Text.ParserCombinators.Parsec (ParseError)
import System.IO
type IOThrowsError = ErrorT LispError IO
instance Error LispError where
noMsg = Default "An error has occurred"
strMsg = Default
type ThrowsError = Either LispError
type Env = IORef [(Text, IORef LispVal)]
data LispError = NumArgs Integer [LispVal]
| TypeMismatch String LispVal
| Parser ParseError
| BadSpecialForm String LispVal
| NotFunction String String
| UnboundVar String String
| Default String
showError :: LispError -> String
showError (UnboundVar message varname) = message ++ ": " ++ varname
showError (BadSpecialForm message form) = message ++ ": " ++ show form
showError (NotFunction message func) = message ++ ": " ++ show func
showError (NumArgs expected found) = "Expected " ++ show expected
++ " args; found values " ++ (T.unpack . unwordsList $ found)
showError (TypeMismatch expected found) = "Invalid type: expected " ++ expected
++ ", found " ++ show found
showError (Parser parseErr) = "Parse error at " ++ show parseErr
showError (Default e) = "Default error at " ++ show e
instance Show LispError where show = showError
data LispVal =
Atom Text
| List [LispVal]
| DottedList [LispVal] LispVal
| Number Integer
| String Text
| Bool Bool
| PrimitiveFunc ([LispVal] -> ThrowsError LispVal)
| Func { params :: [Text], vargs :: (Maybe Text),
body :: [LispVal], closure :: Env }
| IOFunc ([LispVal] -> IOThrowsError LispVal)
| Port Handle
instance Show LispVal where show = T.unpack . showVal
showVal :: LispVal -> T.Text
showVal (String contents) = T.unwords ["\"", contents, "\""]
showVal (Atom name) = name
showVal (Number contents) = T.pack $ show contents
showVal (Bool True) = "#true"
showVal (Bool False) = "#false"
showVal (List contents) = T.unwords ["(", unwordsList contents, ")"]
showVal (DottedList h t) = T.unwords ["(", unwordsList h, " . ", showVal t, ")"]
showVal (PrimitiveFunc _) = "<primitive>"
showVal (Port _) = "<IO port>"
showVal (IOFunc _) = "<IO primitive>"
showVal (Func {params = args, vargs = varargs, body = _body, closure = _env}) =
T.pack $ "(lambda (" ++ unwords (map show args) ++
(case varargs of
Nothing -> ""
Just arg -> " . " ++ (T.unpack arg)) ++ ") ...)"
unwordsList :: [LispVal] -> T.Text
unwordsList = T.unwords . Prelude.map showVal
| tmcgilchrist/scheme | src/Scheme/Data.hs | bsd-3-clause | 2,968 | 0 | 14 | 769 | 907 | 493 | 414 | 70 | 2 |
{-# LANGUAGE PolyKinds, DataKinds, TypeOperators, FlexibleInstances,
ScopedTypeVariables, FlexibleContexts, ConstraintKinds #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Metrology.Show
-- Copyright : (C) 2013 Richard Eisenberg
-- License : BSD-style (see LICENSE)
-- Maintainer : Richard Eisenberg (eir@cis.upenn.edu)
-- Stability : experimental
-- Portability : non-portable
--
-- This module defines 'Show' instance for quantities. The show instance
-- prints out the number stored internally with its correct units. To print
-- out quantities with specific units use the function `showIn`.
-----------------------------------------------------------------------------
module Data.Metrology.Show () where
import Data.Proxy (Proxy(..))
import Data.List
import Data.Singletons (sing, SingI)
import Data.Metrology.Factor
import Data.Metrology.Qu
import Data.Metrology.Z
import Data.Metrology.LCSU
class ShowUnitFactor (dims :: [Factor *]) where
showDims :: Bool -- take absolute value of exponents?
-> Proxy dims -> ([String], [String])
instance ShowUnitFactor '[] where
showDims _ _ = ([], [])
instance (ShowUnitFactor rest, Show unit, SingI z)
=> ShowUnitFactor (F unit z ': rest) where
showDims take_abs _ =
let (nums, denoms) = showDims take_abs (Proxy :: Proxy rest)
baseStr = show (undefined :: unit)
power = szToInt (sing :: Sing z)
abs_power = if take_abs then abs power else power
str = if abs_power == 1
then baseStr
else baseStr ++ "^" ++ (show abs_power) in
case compare power 0 of
LT -> (nums, str : denoms)
EQ -> (nums, denoms)
GT -> (str : nums, denoms)
showFactor :: ShowUnitFactor dimspec => Proxy dimspec -> String
showFactor p
= let (nums, denoms) = mapPair (build_string . sort) $ showDims True p in
case (length nums, length denoms) of
(0, 0) -> ""
(_, 0) -> " " ++ nums
(0, _) -> " " ++ build_string (snd (showDims False p))
(_, _) -> " " ++ nums ++ "/" ++ denoms
where
mapPair :: (a -> b) -> (a, a) -> (b, b)
mapPair f (x, y) = (f x, f y)
build_string :: [String] -> String
build_string [] = ""
build_string [s] = s
build_string s = "(" ++ build_string_helper s ++ ")"
build_string_helper :: [String] -> String
build_string_helper [] = ""
build_string_helper [s] = s
build_string_helper (h:t) = h ++ " * " ++ build_string_helper t
instance (ShowUnitFactor (LookupList dims lcsu), Show n)
=> Show (Qu dims lcsu n) where
show (Qu d) = show d ++
(showFactor (Proxy :: Proxy (LookupList dims lcsu)))
| hesiod/units | Data/Metrology/Show.hs | bsd-3-clause | 2,828 | 0 | 15 | 698 | 802 | 439 | 363 | 52 | 8 |
{-# LANGUAGE RecordWildCards #-}
module Network.HTTP.Download.VerifiedSpec where
import Crypto.Hash
import Control.Monad.Trans.Reader
import Data.Maybe
import Network.HTTP.Client.Conduit
import Network.HTTP.Download.Verified
import Path
import System.Directory
import System.IO.Temp
import Test.Hspec
-- TODO: share across test files
withTempDir :: (Path Abs Dir -> IO a) -> IO a
withTempDir f = withSystemTempDirectory "NHD_VerifiedSpec" $ \dirFp -> do
dir <- parseAbsDir dirFp
f dir
-- | An example path to download the exampleReq.
getExamplePath :: Path Abs Dir -> IO (Path Abs File)
getExamplePath dir = do
file <- parseRelFile "cabal-install-1.22.4.0.tar.gz"
return (dir </> file)
-- | An example DownloadRequest that uses a SHA1
exampleReq :: DownloadRequest
exampleReq = fromMaybe (error "exampleReq") $ do
req <- parseUrl "http://download.fpcomplete.com/stackage-cli/linux64/cabal-install-1.22.4.0.tar.gz"
return DownloadRequest
{ drRequest = req
, drHashChecks = [exampleHashCheck]
, drLengthCheck = Just exampleLengthCheck
}
exampleHashCheck :: HashCheck
exampleHashCheck = HashCheck
{ hashCheckAlgorithm = SHA1
, hashCheckHexDigest = "b98eea96d321cdeed83a201c192dac116e786ec2"
}
exampleLengthCheck :: LengthCheck
exampleLengthCheck = 302513
-- | The wrong ContentLength for exampleReq
exampleWrongContentLength :: Int
exampleWrongContentLength = 302512
-- | The wrong SHA1 digest for exampleReq
exampleWrongDigest :: String
exampleWrongDigest = "b98eea96d321cdeed83a201c192dac116e786ec3"
exampleWrongContent :: String
exampleWrongContent = "example wrong content"
isWrongContentLength :: VerifiedDownloadException -> Bool
isWrongContentLength WrongContentLength{} = True
isWrongContentLength _ = False
isWrongDigest :: VerifiedDownloadException -> Bool
isWrongDigest WrongDigest{} = True
isWrongDigest _ = False
data T = T
{ manager :: Manager
}
runWith :: Manager -> ReaderT Manager m r -> m r
runWith = flip runReaderT
setup :: IO T
setup = do
manager <- newManager
return T{..}
teardown :: T -> IO ()
teardown _ = return ()
spec :: Spec
spec = beforeAll setup $ afterAll teardown $ do
let exampleProgressHook = return ()
describe "verifiedDownload" $ do
-- Preconditions:
-- * the exampleReq server is running
-- * the test runner has working internet access to it
it "downloads the file correctly" $ \T{..} -> withTempDir $ \dir -> do
examplePath <- getExamplePath dir
let exampleFilePath = toFilePath examplePath
doesFileExist exampleFilePath `shouldReturn` False
let go = runWith manager $ verifiedDownload exampleReq examplePath exampleProgressHook
go `shouldReturn` True
doesFileExist exampleFilePath `shouldReturn` True
it "is idempotent, and doesn't redownload unnecessarily" $ \T{..} -> withTempDir $ \dir -> do
examplePath <- getExamplePath dir
let exampleFilePath = toFilePath examplePath
doesFileExist exampleFilePath `shouldReturn` False
let go = runWith manager $ verifiedDownload exampleReq examplePath exampleProgressHook
go `shouldReturn` True
doesFileExist exampleFilePath `shouldReturn` True
go `shouldReturn` False
doesFileExist exampleFilePath `shouldReturn` True
it "does redownload when the destination file is wrong" $ \T{..} -> withTempDir $ \dir -> do
examplePath <- getExamplePath dir
let exampleFilePath = toFilePath examplePath
writeFile exampleFilePath exampleWrongContent
doesFileExist exampleFilePath `shouldReturn` True
let go = runWith manager $ verifiedDownload exampleReq examplePath exampleProgressHook
go `shouldReturn` True
doesFileExist exampleFilePath `shouldReturn` True
it "rejects incorrect content length" $ \T{..} -> withTempDir $ \dir -> do
examplePath <- getExamplePath dir
let exampleFilePath = toFilePath examplePath
let wrongContentLengthReq = exampleReq
{ drLengthCheck = Just exampleWrongContentLength
}
let go = runWith manager $ verifiedDownload wrongContentLengthReq examplePath exampleProgressHook
go `shouldThrow` isWrongContentLength
doesFileExist exampleFilePath `shouldReturn` False
it "rejects incorrect digest" $ \T{..} -> withTempDir $ \dir -> do
examplePath <- getExamplePath dir
let exampleFilePath = toFilePath examplePath
let wrongHashCheck = exampleHashCheck { hashCheckHexDigest = exampleWrongDigest }
let wrongDigestReq = exampleReq { drHashChecks = [wrongHashCheck] }
let go = runWith manager $ verifiedDownload wrongDigestReq examplePath exampleProgressHook
go `shouldThrow` isWrongDigest
doesFileExist exampleFilePath `shouldReturn` False
| mietek/stack | src/test/Network/HTTP/Download/VerifiedSpec.hs | bsd-3-clause | 4,785 | 0 | 22 | 906 | 1,127 | 567 | 560 | 98 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DoRec #-}
-- Page.hs: example pages
-- as part of rawe - ReActive Web Framework
--
-- Copyright 2011 Roman Smrž <roman.smrz@seznam.cz>, see file LICENSE
-- This module contains several example pages assigned to variables page<n>,
-- which can be used to choose among them in the main module.
module Page where
import qualified Prelude as P
import FRP.Rawe
import FRP.Rawe.Prelude
import FRP.Rawe.Html
{- Example 1 – using behaviours and textfields -}
page1 = html $ do
head_ $ do
title "Rawe - example 1"
body $ do
-- texfields give behaviour of their value
a <- textfield
-- which can be displayed ...
bhv $ toHtml a
br
b <- textfield
-- ... or counted
bhv $ toHtml $ length b
{- Value loaded from server -}
page2 = html $ do
head_ $ do
title "Rawe - example 2"
body $ do
-- value from server may simply displayed
let count = sget "count" :: Bhv (Maybe Int)
bhv $ toHtml count
{- Example 3 – event folds -}
page3 = html $ do
head_ $ do
title "Rawe - example 3"
body $ do
-- button generates events for clicking
a <- button ! value "+1"
-- we map give each of them a value 1 and then sum them
bhv $ toHtml $ evfold (const (+)) (0::Bhv Int) $ fmap (const 1) a
br
-- changing behaviour can be also used as values for the event from
-- a button:
text <- textfield
addtext <- button ! value "->"
bhv $ toHtml $ timedFold (const (++)) "" $ fmap (const text) addtext
{- Example 4 - sending form data -}
page4 = html $ do
head_ $ do
title "Rawe - example 4"
body $ do
-- generate a form ...
req <- form $ do textfield ! name "a"; br
str "+"; br
textfield ! name "b"; br
submit ! value "="
-- and send data to a server (and display result)
sum <- post "sum" req :: HtmlM (Bhv (Maybe Int))
bhv $ toHtml sum
{- Example 5 - multiple pages with links -}
-- several sample pages, parts from previous examples
pages :: Bhv [(String, Html)]
pages = cb $
[ ("text", div_ $ do
b <- textfield
bhv $ toHtml $ length b
)
, ("server", div_ $ do
let count = sget "count" :: Bhv (Maybe Int)
bhv $ toHtml count
)
, ("event", div_ $ do
a <- button ! value "+1"
bhv $ toHtml $ timedFold (const (+)) (0::Bhv Int) $ fmap (const 1) a
br
)
]
page5 = html $ do
head_ $ do
title "Rawe - example 5"
body $ do
-- the links generates events for clicking ...
p1 <- ae "text" $ "Textfields"
br
p2 <- ae "server" $ "Server get"
br
p3 <- ae "event" $ "Event fold"
br
--- which can be aggregated
let pm = P.foldl1 (evmerge const) [p1, p2, p3]
-- and then used to choose a page
bhv $ timed "" (\_ k -> maybe "" id (lookup k pages)) pm
{- Example 6 - self-replacing form -}
page6 = html $ do
head_ $ do
title "Rawe - example 5"
body $ do
-- send the form only, if it passed the check
rec result <- post "register" formData' :: HtmlM (Bhv (Maybe Int))
(formData, formData') <- P.fmap (id &&& evguard checkForm) $ bhv $ (
-- the form itself
cb $ form $ do
textfield ! name "name"
br
textfield ! name "pass" ! type_ "password"
br
textfield ! name "pass-check" ! type_ "password"
br
bhv $ ("Password mismatch"::Bhv Html) `displayUnless`
timed true (const checkForm) formData
br
submit
) `until` (
-- once sent replace with saying so
fmap (const "Sending ...") $ timed nothing (\_ -> just) formData'
) `until` (
-- after the anwer was received, display OK
fmap (const "OK") result
)
P.return ()
-- just check if pass and pass-check agree
checkForm :: Bhv [(String, String)] -> Bhv Bool
checkForm x = lookup "pass" x == lookup "pass-check" x
-- display the html only if the condition does not hold
displayUnless :: (ToHtmlBhv a) => Bhv a -> Bhv Bool -> Bhv Html
displayUnless what = toHtml . bool nothing (just what)
| roman-smrz/rawe | examples/Page.hs | bsd-3-clause | 4,611 | 0 | 24 | 1,704 | 1,181 | 579 | 602 | 92 | 1 |
module SMACCMPilot.GCS.Gateway.Commsec
( mkCommsec
, Commsec
, encrypt
, decrypt
) where
import qualified Data.ByteString as B
import Data.ByteString (ByteString)
import Text.Printf
import qualified SMACCMPilot.Communications as Comm
import qualified SMACCMPilot.GCS.Commsec as CS
import qualified SMACCMPilot.GCS.Commsec.Opts as CS
import SMACCMPilot.GCS.Gateway.Monad
data Commsec =
Commsec
{ encrypt :: ByteString -> GW (Maybe ByteString)
, decrypt :: ByteString -> GW (Maybe ByteString)
}
mkCommsec :: CS.Options -> IO Commsec
mkCommsec opts = do
cryptoCtx <- CS.secPkgInit_HS baseId rsalt rkey ssalt skey
return $ Commsec
{ encrypt = \pt ->
case ptlen == B.length pt of
False -> invalid "encrypt pt length" ptlen (B.length pt)
True -> do
mct <- lift $ CS.secPkgEncInPlace_HS cryptoCtx pt
case mct of
Nothing -> err "encryption failure"
Just ct -> case (B.length ct) == ctlen of
False -> invalid "encrypt ct length" ctlen (B.length ct)
True -> return (Just ct)
, decrypt = \ct ->
case (B.length ct) == ctlen of
False -> invalid "decrypt ct length" ctlen (B.length ct)
True -> do
decrypted <- lift $ CS.secPkgDec_HS cryptoCtx ct
case decrypted of
Left e -> err ("decryption error: " ++ (show e))
Right pt -> case (B.length pt) == ptlen of
False -> invalid "decrypt pt length" ptlen (B.length pt)
True -> return (Just pt)
}
where
ptlen = fromIntegral Comm.mavlinkSize
ctlen = fromIntegral Comm.commsecPkgSize
baseId = fromIntegral (CS.sendID opts)
rsalt = CS.recvSalt opts
rkey = B.pack (CS.recvKey opts)
ssalt = CS.sendSalt opts
skey = B.pack (CS.sendKey opts)
invalid name expected got = err $ printf "Invalid %s: expected %s got %s"
name (show expected) (show got)
err msg = writeErr msg >> return Nothing
| GaloisInc/smaccmpilot-gcs-gateway | SMACCMPilot/GCS/Gateway/Commsec.hs | bsd-3-clause | 2,128 | 0 | 25 | 685 | 637 | 328 | 309 | 50 | 7 |
-----------------------------------------------------------------------------
-- |
-- Module : TestSuite.Queries.Int_ABC
-- Copyright : (c) Levent Erkok
-- License : BSD3
-- Maintainer : erkokl@gmail.com
-- Stability : experimental
--
-- Testing ABC specific interactive features.
-----------------------------------------------------------------------------
{-# LANGUAGE ScopedTypeVariables #-}
module TestSuite.Queries.Int_ABC (tests) where
import Data.SBV.Control
import Control.Monad (unless)
import Utils.SBVTestFramework
-- Test suite
tests :: TestTree
tests =
testGroup "Basics.QueryIndividual"
[ goldenCapturedIO "query_abc" $ \rf -> runSMTWith abc{verbose=True, redirectVerbose=Just rf} q
]
q :: Symbolic ()
q = do a <- sInt32 "a"
b <- sInt32 "b"
constrain $ a .> 0
constrain $ b .> 0
-- this is severely limited since ABC doesn't like multi check-sat calls, oh well.
query $ do constrain $ a+2 .<= 15
constrain $ a .< 2
constrain $ b .< 2
constrain $ a+b .< 12
constrain $ a .< 2
cs <- checkSat
case cs of
Unk -> getInfo ReasonUnknown >>= error . show
Unsat -> error "Got UNSAT!"
Sat -> do -- Query a/b
res <- (,) <$> getValue a <*> getValue b
unless (res == (1, 1)) $ error $ "Didn't get (1,1): " ++ show res
| josefs/sbv | SBVTestSuite/TestSuite/Queries/Int_ABC.hs | bsd-3-clause | 1,537 | 0 | 21 | 503 | 330 | 170 | 160 | 26 | 3 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-|
Module : Diagrams.Backend.Cairo.Raster.Repa
Description : Draw 'repa' arrays into Cairo diagrams.
Copyright : (c) Taru Karttunen, 2014
License : BSD3
Maintainer : taruti@taruti.net
Stability : experimental
Draw 'repa' arrays into Cairo diagrams.
-}
module Diagrams.Backend.Cairo.Raster.Repa(
cairoRepa, computeIntoP, computeIntoS
) where
import Data.Array.Base (MArray (unsafeWrite))
import Data.Array.Repa as R
import Data.Array.Repa.Eval
import Diagrams.Backend.Cairo.Internal
import Diagrams.Backend.Cairo.Raster.Internal
import Diagrams.Prelude
import qualified Graphics.Rendering.Cairo as C
{-# INLINE cairoRepa #-}
-- | Compute a DImage from a 'repa' array with the supplied width and height.
-- The function calculating the array receives a 'DIM2' containing the dimensions
-- of the array which may be /different/ from the image width and height specified
-- due to Cairo requirements of image data alignment. The 'DIM2' is in the form
-- @(Z :. height :. width)@.
cairoRepa :: Load r1 sh CairoColor => (DIM2 -> Array r1 sh CairoColor) -> Int -> Int -> IO (Diagram Cairo R2)
cairoRepa !afun !w0 !h0 = do
(s,sd,w',_) <- cairoBitmapArray w0 h0
computeIntoP sd $ afun (Z :. h0 :. w')
fmap image $ cairoSurfaceImage s w0 h0
{-# INLINE computeIntoP #-}
-- | Low-level primitive: Compute a 'repa' array into a 'SurfaceData' in parallel.
computeIntoP :: Load r1 sh CairoColor => C.SurfaceData Int CairoColor -> Array r1 sh CairoColor -> IO ()
computeIntoP !sd !arr = loadP arr (CF sd)
{-# INLINE computeIntoS #-}
-- | Low-level primitive: Compute a 'repa' array into a 'SurfaceData' sequentally.
computeIntoS :: Load r1 sh CairoColor => C.SurfaceData Int CairoColor -> Array r1 sh CairoColor -> IO ()
computeIntoS !sd !arr = loadS arr (CF sd)
data CF
instance Target CF CairoColor where
data MVec CF CairoColor = CF (C.SurfaceData Int CairoColor)
newMVec _n = error "CF newMVec NIMP"
{-# INLINE newMVec #-}
unsafeWriteMVec !(CF cf) !ix !x = unsafeWrite cf ix x
{-# INLINE unsafeWriteMVec #-}
unsafeFreezeMVec !_sh _ = error "CF unsafeFreezeMVec NIMP"
{-# INLINE unsafeFreezeMVec #-}
deepSeqMVec !(CF fp) x = fp `seq` x
{-# INLINE deepSeqMVec #-}
touchMVec !(CF fp) = fp `seq` return ()
{-# INLINE touchMVec #-}
| taruti/diagrams-cairo-raster | src/Diagrams/Backend/Cairo/Raster/Repa.hs | bsd-3-clause | 2,553 | 0 | 11 | 529 | 505 | 267 | 238 | -1 | -1 |
module Main where
import Hear.Trainer
main :: IO ()
main = trainer
| no-scope/hear | app/Main.hs | bsd-3-clause | 69 | 0 | 6 | 14 | 24 | 14 | 10 | 4 | 1 |
module Core.AST where
import Data.Maybe (fromMaybe)
type Program a = [Defn a]
type CoreProgram = Program Name
type Defn a = (Name, [a], Expr a)
type CoreDefn = Defn Name
type CoreExpr = Expr Name
data Expr a = Var Name
| Num Int
| Constr Int Int -- Constructor tag arity
| App (Expr a) (Expr a)
| Let IsRec [(a, Expr a)] (Expr a)
| Case (Expr a) [Alter a]
| Lam [a] (Expr a)
deriving Show
type Name = String
type IsRec = Bool
type Alter a = (Int, [a], Expr a)
type CoreAlt = Alter Name
-- Get variables and definitions out of a let expr
bindersOf :: [(a,b)] -> [a]
bindersOf defs = [ name | (name, _) <- defs ]
rhssOf :: [(a,b)] -> [b]
rhssOf defs = [ rhs | (_, rhs) <- defs ]
isAtomic :: Expr a -> Bool
isAtomic (Var _) = True
isAtomic (Num _) = True
isAtomic _ = False
-- Simple helper tool for list dictionaries
findWithDefault x k = fromMaybe x . lookup k
| WraithM/CoreCompiler | src/Core/AST.hs | bsd-3-clause | 899 | 0 | 9 | 217 | 390 | 223 | 167 | 28 | 1 |
module Data.Geo.GPX.Lens.TypeL where
import Data.Lens.Common
class TypeL a where
typeL :: Lens a (Maybe String)
| tonymorris/geo-gpx | src/Data/Geo/GPX/Lens/TypeL.hs | bsd-3-clause | 117 | 0 | 9 | 20 | 40 | 23 | 17 | 4 | 0 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# OPTIONS_GHC -Wno-orphans #-}
module CommandLine.TestWorld (TestWorldState, TestWorld, lastExitCode, init,uploadFile, downloadFile, eval,queueStdin,fullStdout,golden,fullStderr,expectExit,expectFileContents,goldenExitStdout) where
import Prelude hiding (putStr, putStrLn, readFile, writeFile, init)
import CommandLine.World
import qualified Control.Monad.State.Lazy as State
import Data.FileTree (FileTree)
import qualified Data.FileTree as FileTree
import Data.Text (Text)
import qualified Data.Text as Text
import qualified TestWorld.Stdio as Stdio
import Control.Monad.Identity (Identity)
import Test.Hspec.Golden ( Golden(..) )
import qualified Data.Text.IO
import Test.Hspec.Core.Spec (Example(..), Result(..), ResultStatus(..))
import Test.Tasty.Hspec (shouldBe, Expectation)
data TestWorldState =
TestWorldState
{ filesystem :: FileTree Text
, stdio :: Stdio.State
, _lastExitCode :: LastExitCode
}
newtype LastExitCode = LastExitCode (Maybe Int)
type TestWorld = State.StateT TestWorldState Identity
--
-- Generic types
--
class Lens s t where
get :: s -> t
set :: t -> s -> s
over :: (t -> t) -> s -> s
over f s = set (f $ get s) s
from :: (t -> z) -> s -> z
from f = f . get
instance Lens t t where
get = id
set = const
class Has t m where
state :: (t -> (a, t)) -> m a
modify :: (t -> t) -> m ()
modify f = state (\t -> ((), f t))
modify' :: t -> (t -> t) -> m ()
modify' _ = modify
gets :: (t -> a) -> m a
gets f = state (\t -> (f t, t))
gets' :: t -> (t -> a) -> m a
gets' _ = gets
instance (Monad m, Lens s t) => Has t (State.StateT s m) where
state f = State.state $ \outer -> fmap (flip set outer) (f $ get outer)
gets f = State.gets (f . get)
--
-- Lens definitions
--
instance Lens TestWorldState (FileTree Text) where
get = filesystem
set x s = s { filesystem = x }
instance Lens TestWorldState Stdio.State where
get = stdio
set x s = s { stdio = x }
instance Lens TestWorldState LastExitCode where
get = _lastExitCode
set x s = s { _lastExitCode = x }
--
-- World instance
--
instance Monad m => World (State.StateT TestWorldState m) where
doesFileExist = gets . (FileTree.doesFileExist :: FilePath -> FileTree Text -> Bool)
doesDirectoryExist = gets . (FileTree.doesDirectoryExist :: FilePath -> FileTree Text -> Bool)
listDirectory = gets . (FileTree.listDirectory :: FilePath -> FileTree Text -> [FilePath])
readUtf8File path =
gets $ orError . FileTree.read path
where
orError (Just a) = a
orError Nothing = error $ path ++ ": does not exist"
writeUtf8File = modify <<< FileTree.write
getStdin = state Stdio.getStdin
putStr = modify . Stdio.putStr
putStrLn = modify . Stdio.putStrLn
writeStdout text =
putStr text
putStrStderr = modify . Stdio.putStrStderr
putStrLnStderr = modify . Stdio.putStrLnStderr
getProgName =
return "elm-format"
exitSuccess = modify $ const (LastExitCode $ Just 0)
exitFailure = modify $ const (LastExitCode $ Just 1)
infixr 8 <<<
(<<<) :: (c -> z) -> (a -> b -> c) -> a -> b -> z
(<<<) f g a b = f $ g a b
testWorld :: [(String, String)] -> TestWorldState
testWorld files =
TestWorldState
{ filesystem = foldl (\t (p, c) -> FileTree.write p c t) mempty $ fmap (fmap Text.pack) files
, stdio = Stdio.empty
, _lastExitCode = LastExitCode Nothing
}
eval :: State.State s a -> s -> a
eval = State.evalState
queueStdin :: Text -> TestWorld ()
queueStdin =
modify' (undefined :: Stdio.State) . over . Stdio.queueStdin
init :: TestWorldState
init = testWorld []
uploadFile :: FilePath -> Text -> TestWorld ()
uploadFile =
modify' (undefined :: FileTree Text) <<< over <<< FileTree.write
downloadFile :: FilePath -> TestWorld (Maybe Text)
downloadFile =
gets' (undefined :: FileTree Text) . from . FileTree.read
fullStdout :: TestWorld Text
fullStdout =
gets' (undefined :: Stdio.State) $ from Stdio.fullStdout
fullStderr :: TestWorld Text
fullStderr =
gets' (undefined :: Stdio.State) $ from Stdio.fullStderr
lastExitCode :: TestWorld (Maybe Int)
lastExitCode =
gets' (undefined :: LastExitCode) $ from (\(LastExitCode i) -> i)
--
-- hspec helpers
--
expectExit :: Int -> TestWorld Expectation
expectExit expected =
fmap (\actual -> actual `shouldBe` Just expected) lastExitCode
expectFileContents :: FilePath -> Text -> TestWorld Expectation
expectFileContents filename expectedContent = do
actual <- downloadFile filename
return $ actual `shouldBe` Just expectedContent
goldenExitStdout :: Int -> FilePath -> TestWorld (Expectation, Golden Text)
goldenExitStdout expectedExitCode goldenFile = do
actualExitCode <- lastExitCode
actualStdout <- fullStdout
return
( actualExitCode `shouldBe` Just expectedExitCode
, golden goldenFile actualStdout
)
--
-- hspec instances
--
instance Example a => Example (TestWorld a) where
type Arg (TestWorld a) = Arg a
evaluateExample e =
evaluateExample (State.evalState e init)
golden :: FilePath -> Text -> Golden Text
golden name actualOutput =
Golden
{ output = actualOutput
, encodePretty = Text.unpack
, writeToFile = Data.Text.IO.writeFile
, readFromFile = Data.Text.IO.readFile
, testName = name
, directory = "."
, failFirstTime = True
}
--
-- A mess of instances to allow `goldenExitStdout`
-- to return both a Spec and a Golden
--
instance (Example a, Arg a ~ ()) => Example (Maybe a) where
type Arg (Maybe a) = Arg a
evaluateExample Nothing =
evaluateExample (Result "" Success)
evaluateExample (Just a) =
evaluateExample a
instance (Example a, Example b, Arg a ~ Arg b) => Example (a, b) where
type Arg (a, b) = Arg a
evaluateExample (a, b) params actionWith callback = do
ra <- evaluateExample a params actionWith callback
rb <- evaluateExample b params actionWith callback
return (ra <> rb)
instance Semigroup Result where
(Result a ra) <> (Result b rb) = Result (a ++ "/" ++ b) (ra <> rb)
instance Semigroup ResultStatus where
Success <> b = b
Pending a1 a2 <> Success = Pending a1 a2
Pending _ _ <> b = b
a <> _ = a
| avh4/elm-format | elm-format-test-lib/src/CommandLine/TestWorld.hs | bsd-3-clause | 6,565 | 0 | 12 | 1,576 | 2,223 | 1,199 | 1,024 | 156 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.